diff --git a/.gitignore b/.gitignore index b09429865e..d4bc5dd91f 100644 --- a/.gitignore +++ b/.gitignore @@ -23,12 +23,7 @@ Properties *~ # test folder -!_infrastructure/*.js -!_infrastructure/tests/* -!_infrastructure/tests/*.js -!_infrastructure/tests/*/*.js -!_infrastructure/tests/*/*/*.js -!_infrastructure/tests/*/*/*/*.js +_infrastructure/tests/build .idea *.iml diff --git a/.travis.yml b/.travis.yml index d138403cc2..acfc5176f9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: node_js node_js: - - 0.10 + - "0.10" notifications: email: false diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 13053ce7ff..3b48e78746 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1 +1 @@ -Please see the [contribution guide](https://github.com/borisyankov/DefinitelyTyped/wiki/How-to-contribute) for information on how to contribute to this project. +Please see the [contribution guide](http://definitelytyped.org/guides/contributing.html) at [definitelytyped.org](http://definitelytyped.org/guides/contributing.html) for information on how to contribute to DefinitelyTyped. diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md new file mode 100644 index 0000000000..af326634b1 --- /dev/null +++ b/CONTRIBUTORS.md @@ -0,0 +1,367 @@ +# Contributors + +This is a non-exhaustive list of definitions and their creators. If you created a definition but are not listed then feel free to send a pull request on this file with your name and url. + +All definitions files include a header with the author and editors, so at some point this list will be auto-generated. + +* [accounting.js](http://josscrowcroft.github.io/accounting.js/) (by [Sergey Gerasimov](https://github.com/gerich-home)) +* [Ace Cloud9 Editor](http://ace.ajax.org/) (by [Diullei Gomes](https://github.com/Diullei)) +* [Add To Home Screen](http://cubiq.org/add-to-home-screen) (by [James Wilkins](http://www.codeplex.com/site/users/view/jamesnw)) +* [AmCharts](http://www.amcharts.com/) (by [Covobonomo](https://github.com/covobonomo/)) +* [AngularAgility](https://github.com/AngularAgility/AngularAgility) (by [Roland Zwaga](https://github.com/rolandzwaga)) +* [AngularBootstrapLightbox](https://github.com/compact/angular-bootstrap-lightbox) (by [Roland Zwaga](https://github.com/rolandzwaga)) +* [AngularFire](https://www.firebase.com/docs/angular/reference.html) (by [Dénes Harmath](https://github.com/thSoft)) +* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes)) +* [angularLocalStorage](https://github.com/agrublev/angularLocalStorage) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) +* [AngularUI](http://angular-ui.github.io/) (by [Michel Salib](https://github.com/michelsalib)) +* [Angular Hotkeys](https://github.com/chieffancypants/angular-hotkeys/) (by [Jason Zhao](https://github.com/jlz27)) +* [Angular Protractor](https://github.com/angular/protractor) (by [Bill Armstrong](https://github.com/BillArmstrong)) +* [Angular Translate](http://pascalprecht.github.io/angular-translate/) (by [Michel Salib](https://github.com/michelsalib)) +* [Angular UI Bootstrap](http://angular-ui.github.io/bootstrap) (by [Brian Surowiec](https://github.com/xt0rted)) +* [AppFramework](http://app-framework-software.intel.com/) (by [Kyo Ago](https://github.com/kyo-ago)) +* [Arbiter](http://arbiterjs.com/) (by [Arash Shakery](https://github.com/arash16)) +* [asciify](https://github.com/olizilla/asciify) (by [Alan](http://alan.norbauer.com)) +* [assert](https://github.com/Jxck/assert) (by [vvakame](https://github.com/vvakame)) +* [async](https://github.com/caolan/async) (by [Boris Yankov](https://github.com/borisyankov)) +* [atmosphere](https://github.com/Atmosphere/atmosphere-javascript) (by [Kai Toedter](https://github.com/toedter)) +* [Atom](https://atom.io/) (by [vvakame](https://github.com/vvakame)) +* [Auth0](https://auth0.com/) (by [Robert McLaws](https://github.com/advancedrei)) +* [Auth0.Widget](https://auth0.com/) (by [Robert McLaws](https://github.com/advancedrei)) +* [aws-sdk-js](https://github.com/aws/aws-sdk-js) (by [midknight41](https://github.com/midknight41)) +* [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Backbone Relational](http://backbonerelational.org/) (by [Eirik Hoem](https://github.com/eirikhm)) +* [big.js](https://github.com/MikeMcl/big.js) (by [Steve Ognibene](https://github.com/nycdotnet)) +* [BigInteger](https://github.com/peterolson/BigInteger.js) (by [Ingo Bürk](https://github.com/Airblader)) +* [BigScreen](http://brad.is/coding/BigScreen/) (by [Douglas Eichelberger](https://github.com/dduugg)) +* [Bluebird](https://github.com/petkaantonov/bluebird) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [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)) +* [Browser Harness](https://github.com/scriby/browser-harness) (by [Chris Scribner](https://github.com/scriby)) +* [bucks](https://github.com/CyberAgent/bucks.js) (by [Shunsuke Ohtani](https://github.com/zaneli)) +* [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) and [otiai10](https://github.com/otiai10)) +* [Chrome App](http://developer.chrome.com/apps/) (by [Adam Lay](https://github.com/AdamLay)) +* [CKEditor](https://github.com/ckeditor/ckeditor-dev) (by [Ondrej Sevcik](https://github.com/ondrejsevcik)) +* [Clone](https://github.com/pvorb/node-clone) (by [Kieran Simpson](https://github.com/kierans)) +* [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)) +* [configstore](http://github.com/yeoman/configstore) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [Cordova](http://cordova.apache.org) (by [Microsoft Open Technologies, Inc.](http://msopentech.com/)) +* [Cordovarduino](https://github.com/stereolux/cordovarduino) (by [Hendrik Maus](https://github.com/hendrikmaus)) +* [Couchbase / Couchnode](https://github.com/couchbase/couchnode) (by [Basarat Ali Syed](https://github.com/basarat)) +* [Crossfilter](https://github.com/square/crossfilter) (by [Schmulik Raskin](https://github.com/schmuli)) +* [crypto-js](https://code.google.com/p/crypto-js/) (by [Gia Bảo @ Sân Đình](https://github.com/giabao)). @see [cryptojs.d.ts repo](https://github.com/giabao/cryptojs.d.ts) +* [d3.js](http://d3js.org/) (from TypeScript samples) +* [dhtmlxGantt](http://dhtmlx.com/docs/products/dhtmlxGantt) (by [Maksim Kozhukh](http://github.com/mkozhukh)) +* [dhtmlxScheduler](http://dhtmlx.com/docs/products/dhtmlxScheduler) (by [Maksim Kozhukh](http://github.com/mkozhukh)) +* [diff](https://github.com/kpdecker/jsdiff) (by [vvakame](http://github.com/vvakame)) +* [Dock Spawn](http://dockspawn.com) (by [Drew Noakes](https://drewnoakes.com)) +* [docCookies](https://developer.mozilla.org/en-US/docs/Web/API/document.cookie) (by [Jon Egerton](https://github.com/jonegerton)) +* [domo](http://domo-js.com/) (by [Steve Fenton](https://github.com/Steve-Fenton)) +* [doT](https://github.com/olado/doT) (by [ZombieHunter](https://github.com/ZombieHunter)) +* [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)) +* [EasyStar](http://easystarjs.com/) (by [Magnus Gustafsson](https://github.com/Borundin)) +* [Elm](http://elm-lang.org) (by [Dénes Harmath](https://github.com/thSoft)) +* [ember.js](http://emberjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [emissary](https://github.com/atom/emissary) (by [vvakame](https://github.com/vvakame)) +* [EpicEditor](http://epiceditor.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [ES6-Promises](https://github.com/jakearchibald/ES6-Promises) (by [François de Campredon](https://github.com/fdecampredon/)) +* [Esprima](http://esprima.org/) (by [Teppei Sato](https://github.com/teppeis)) +* [expect.js](https://github.com/LearnBoost/expect.js) (by [Teppei Sato](https://github.com/teppeis)) +* [expectations](https://github.com/spmason/expectations) (by [vvakame](https://github.com/vvakame)) +* [Express](http://expressjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Ext JS](http://www.sencha.com/products/extjs/) (by [Brian Kotek](https://github.com/brian428)) +* [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/)) +* [Finch](https://github.com/stoodder/finchjs) (by [David Sichau](https://github.com/DavidSichau/)) +* [fingerprintjs](https://github.com/Valve/fingerprintjs) (by [Shunsuke Ohtani](https://github.com/zaneli)) +* [Finite State Machine](https://github.com/jakesgordon/javascript-state-machine) (by [Boris Yankov](https://github.com/borisyankov)) +* [Firebase](https://www.firebase.com/docs/javascript/firebase) (by [Vincent Bortone](https://github.com/vbortone)) +* [Firefox](https://developer.mozilla.org/en-US/docs/Web/API) (by [vvakame](https://github.com/vvakame)) +* [FlexSlider](http://www.woothemes.com/flexslider/) (by [Diullei Gomes](https://github.com/Diullei)) +* [Flight by Twitter](http://flightjs.github.com/flight/) (by [Jonathan Hedrén](https://github.com/jonathanhedren)) +* [flipsnap.js](http://pxgrid.github.io/js-flipsnap/) (by [kubosho_](https://github.com/kubosho), [gsino](https://github.com/gsino), [Mayuki Sawatari](https://github.com/mayuki)) +* [Foundation](http://foundation.zurb.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [FPSMeter](http://darsa.in/fpsmeter/) (by [Aaron Lampros](https://github.com/alampros)) +* [fs-extra](https://github.com/jprichardson/node-fs-extra) (by [midknight41](https://github.com/midknight41)) +* [FullCalendar](http://arshaw.com/fullcalendar/) (by [Neil Stalker](https://github.com/nestalk)) +* [Fuse.js](https://github.com/krisk/Fuse) (by [Greg Smith](https://github.com/smrq)) +* [Gamepad](http://www.w3.org/TR/gamepad/) (by [Kon](http://phyzkit.net/)) +* [GeoJSON](http://geojson.org/) (by [Jake Bruun](https://github.com/cobster)) +* [Giraffe](https://github.com/barc/backbone.giraffe) (by [Matt McCray](https://github.com/darthapo)) +* [glDatePicker](http://glad.github.com/glDatePicker/) (by [Dániel Tar](https://github.com/qcz)) +* [Glob](https://github.com/isaacs/node-glob) (by [vvakame](https://github.com/vvakame)) +* [GoJS](http://gojs.net/) (by [Barbara Duckworth](https://github.com/barbara42)) +* [Greasemonkey](http://www.greasespot.net/) (by [Kota Saito](https://github.com/kotas)) +* [GreenSock Animation Platform (GSAP)](http://www.greensock.com/get-started-js/) (by [Robert S.](https://github.com/codeBelt)) +* [gridfs-stream](https://github.com/aheckmann/gridfs-stream) (by [Lior Mualem](https://github.com/liorm)) +* [Grunt JS](http://gruntjs.com/) (by [Jeff May](https://github.com/jeffmay), [Basarat Ali Syed](https://github.com/basarat) and [San Chen](https://github.com/bigsan)) +* [Google API Client](https://code.google.com/p/google-api-javascript-client/) (by [Frank M](https://github.com/sgtfrankieboy)) +* [Google App Engine Channel API](https://developers.google.com/appengine/docs/java/channel/javascript) (by [vvakame](https://github.com/vvakame)) +* [GoogleMaps](https://developers.google.com/maps/) (by [Esben Nepper](https://github.com/eNepper)) +* [GoogleMaps InfoBubble](http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/) (by [Johan Nilsson](https://github.com/dashue)) +* [Google Geolocation](https://code.google.com/p/geo-location-javascript/) (by [Vincent Bortone](https://github.com/vbortone)) +* [Google Page Speed Online API](https://developers.google.com/speed/pagespeed/) (by [Frank M](https://github.com/sgtfrankieboy)) +* [Google Translate API](https://developers.google.com/translate/) (by [Frank M](https://github.com/sgtfrankieboy)) +* [Google Url Shortener](https://developers.google.com/url-shortener/) (by [Frank M](https://github.com/sgtfrankieboy)) +* [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)) +* [HashMap](https://github.com/flesler/hashmap) (by [Rafał Wrzeszcz](https://wrzasq.pl)) +* [HashSet](http://www.timdown.co.uk/jshashtable/jshashset.html) (by [Sergey Gerasimov](https://github.com/gerich-home)) +* [Hashtable](http://www.timdown.co.uk/jshashtable/) (by [Sergey Gerasimov](https://github.com/gerich-home)) +* [HelloJS](http://adodson.com/hello.js) (by [Pavel Zika](https://github.com/PavelPZ)) +* [Highcharts](http://www.highcharts.com/) (by [damianog](https://github.com/damianog)) +* [Highland](http://highlandjs.org/) (by [Bart van der Schoor](https://github.com/Bartvds/)) +* [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee)) +* [History.js](https://github.com/browserstate/history.js) (by [Boris Yankov](https://github.com/borisyankov)) +* [Html2Canvas.js](https://github.com/niklasvh/html2canvas/) (by [Richard Hepburn](https://github.com/rwhepburn)) +* [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)) +* [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz)) +* [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov)) +* [Imagemagick](http://github.com/rsms/node-imagemagick) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) +* [interact.js](http://github.com/taye/interact.js) (by [Douglas Eichelberger](https://github.com/dduugg)) +* [Ion.RangeSlider](https://github.com/IonDen/ion.rangeSlider) (by [Douglas Eichelberger](https://github.com/dduugg)) +* [Ionic-Cordova](https://github.com/driftyco/) (by [Hendrik Maus](https://github.com/hendrikmaus)) +* [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov) and [Christiaan Rakowski](https://github.com/csrakowski)) +* [IxJS (Interactive extensions)](https://github.com/Reactive-Extensions/IxJS) (by [Igor Oleinikov](https://github.com/Igorbek)) +* [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/)) +* [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Jasmine-jQuery](https://github.com/velesin/jasmine-jquery) (by [Gregor Stamac](https://github.com/gstamac)) +* [jDataView](https://github.com/jDataView/jDataView) (by [Ingvar Stepanyan](https://github.com/RReverser)) +* [JointJS](http://www.jointjs.com/) (by [Aidan Reel](http://github.com/areel)) +* [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.Address](https://github.com/asual/jquery-address) (by [Martin Duparc](https://github.com/martinduparc/) and [Tim Klingeleers](https://github.com/mardaneus86/)) +* [jQuery.areYouSure](https://github.com/codedance/jquery.AreYouSure) (by [Jon Egerton](https://github.com/jonegerton)) +* [jQuery.autosize](http://www.jacklmoore.com/autosize/) (by [Jack Moore](http://www.jacklmoore.com/)) +* [jQuery.BBQ](http://benalman.com/projects/jquery-bbq-plugin/) (by [Adam R. Smith](https://github.com/sunetos)) +* [jQuery.CLEditor](http://premiumsoftware.net/CLEditor) (by [Jeffery Grajkowski](https://github.com/pushplay)) +* [jQuery.clientSideLogging](https://github.com/remybach/jQuery.clientSideLogging/) (by [Diullei Gomes](https://github.com/diullei/)) +* [jQuery.Colorbox](http://www.jacklmoore.com/colorbox/) (by [Gidon Junge](https://github.com/gjunge)) +* [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.Cycle](http://jquery.malsup.com/cycle/) (by [François Guillot](http://fguillot.developpez.com/)) +* [jQuery.Cycle2](http://jquery.malsup.com/cycle2/) (by [Donny Nadolny](https://github.com/dnadolny)) +* [jQuery.dataTables](http://www.datatables.net) (by [Armin Sander](https://github.com/pragmatrix)) +* [jQuery.datetimepicker](http://trentrichardson.com/examples/timepicker/) (by [Doug McDonald](https://github.com/dougajmcdonald)) +* [jQuery.dynatree](http://code.google.com/p/dynatree/) (by [François de Campredon](https://github.com/fdecampredon)) +* [jQuery.Fileupload](https://github.com/blueimp/jQuery-File-Upload/) (by [Rob Alarcon](https://github.com/rob-alarcon)) +* [jQuery.Finger](http://ngryman.sh/jquery.finger/) (by [Max Ackley](https://github.com/maxackley)) +* [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.gridster](http://gridster.net) (by [Josh Baldwin](https://github.com/jbaldwin/gridster.d.ts)) +* [jQuery.jNotify](http://jnotify.codeplex.com) (by [James Curran](https://github.com/jamescurran/)) +* [jQuery.joyride](http://zurb.com/playground/jquery-joyride-feature-tour-plugin) (by [Vincent Bortone](https://github.com/vbortone)) +* [jQuery.jSignature](https://github.com/willowsystems/jSignature) (by [Patrick Magee](https://github.com/pjmagee)) +* [jQuery.notifyBar](http://www.whoop.ee/posts/2013-04-05-the-resurrection-of-jquery-notify-bar/) (by [Shunsuke Ohtani](https://github.com/zaneli)) +* [jQuery.noty](http://needim.github.io/noty/) (by [Aaron King](https://github.com/kingdango/)) +* [jQuery.payment](http://needim.github.io/noty/) (by [Eric J. Smith](https://github.com/ejsmith/)) +* [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb)) +* [jQuery.pjax](https://github.com/defunkt/jquery-pjax) (by [Junle Li](https://github.com/lijunle)) +* [jQuery.pjax.falsandtru](https://github.com/falsandtru/jquery.pjax.js/) (by [NewNotMoon](http://new.not-moon.net/)) +* [jQuery.pnotify](http://sciactive.github.io/pnotify/) (by [David Sichau](https://github.com/DavidSichau/)) +* [jQuery.postMessage](http://benalman.com/projects/jquery-postmessage-plugin/) (by [Junle Li](https://github.com/lijunle)) +* [jQuery.prettyphoto](https://github.com/scaron/prettyphoto) (by [Paul Gaske](https://github.com/pgaske)) +* [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.superLink](http://james.padolsey.com/demos/plugins/jQuery/superLink/superlink.jquery.js) (by [Blake Niemyjski](https://github.com/niemyjski)) +* [jQuery.tile](https://github.com/urin/jquery.tile.js) (by [Shunsuke Ohtani](https://github.com/zaneli)) +* [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.Timer](http://jchavannes.com/jquery-timer/demo) (by [Joshua Strobl](https://github.com/JoshStrobl)) +* [jQuery.TinyCarousel](http://baijs.nl/tinycarousel/) (by [Christiaan Rakowski](https://github.com/csrakowski)) +* [jQuery.TinyScrollbar](http://baijs.nl/tinyscrollbar/) (by [Christiaan Rakowski](https://github.com/csrakowski)) +* [jQuery.tooltipster](https://github.com/iamceege/tooltipster) (by [Patrick Magee](https://github.com/pjmagee)) +* [jQuery.total-storage](https://github.com/Upstatement/jquery-total-storage) (by [Jeremy Brooks](https://github.com/JeremyCBrooks/)) +* [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)) +* [jQuery.base64](https://github.com/yatt/jquery.base64) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki)) +* [js-git](https://github.com/creationix/js-git) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [js-url](https://github.com/websanova/js-url) (by [MIZUNE Pine](https://github.com/pine613)) +* [js-yaml](https://github.com/nodeca/js-yaml) (by [Bart van der Schoor](https://github.com/Bartvds/)) +* [jScrollPane](http://jscrollpane.kelvinluck.com) (by [Dániel Tar](https://github.com/qcz)) +* [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/)) +* [JSON-Pointer](https://www.npmjs.org/package/json-pointer) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [JsRender](http://www.jsviews.com/#jsrender) (by [Kensuke MATSUZAKI](https://github.com/zakki)) +* [jStorage](http://www.jstorage.info/) (by [Danil Flores](https://github.com/dflor003/)) +* [jsTree](http://www.jstree.com/) (by [Adam Pluciński](https://github.com/adaskothebeast)) +* [JWPlayer](http://developer.longtailvideo.com/trac/) (by [Martin Duparc](https://github.com/martinduparc/)) +* [KeyboardJS](https://github.com/RobertWHurst/KeyboardJS) (by [Vincent Bortone](https://github.com/vbortone/)) +* [keymaster.js](https://github.com/madrobby/keymaster) (by [Marting W. Kirst](https://github.com/nitram509/)) +* [KineticJS](http://kineticjs.com/) (by [Basarat Ali Syed](https://github.com/basarat)) +* [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.Amd.Helpers](https://github.com/rniemeyer/knockout-amd-helpers) (by [David Sichau](https://github.com/DavidSichau/)) +* [Knockout.DeferredUpdates](https://github.com/mbest/knockout-deferred-updates) (by [Sebastián Galiano](https://github.com/sgaliano)) +* [Knockout.ES5](https://github.com/SteveSanderson/knockout-es5) (by [Sebastián Galiano](https://github.com/sgaliano)) +* [Knockout.Mapper](https://github.com/LucasLorentz/knockout.mapper) (by [Brandon Meyer](https://github.com/BMeyerKC)) +* [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 Himango](https://github.com/JudahGabriel)) +* [Knockout.Rx](https://github.com/Igorbek/knockout.rx) (by [Igor Oleinikov](https://github.com/Igorbek)) +* [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)) +* [Lazy.js](http://danieltao.com/lazy.js/) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [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)) +* [ladda](https://github.com/hakimel/Ladda) (by [Danil Flores](https://github.com/dflor003)) +* [Levelup](https://github.com/rvagg/node-levelup) (by [Bret Little](https://github.com/blittle)) +* [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)) +* [localForage](https://github.com/mozilla/localForage) (by [david pichsenmeister](https://github.com/3x14159265)) +* [Lodash](http://lodash.com/) (by [Brian Zengel](https://github.com/bczengel)) +* [Logg](https://github.com/dpup/node-logg) (by [Bret Little](https://github.com/blittle)) +* [Long.js](https://github.com/dcodeIO/Long.js) (by [Toshihide Hara](https://github.com/kerug)) +* [lz-string](https://github.com/pieroxy/lz-string) (by [Roman Nikitin](https://github.com/M0ns1gn0r)) +* [Mapbox](https://github.com/mapbox/mapbox.js/) (by [Maxime Fabre](https://github.com/anahkiasen)) +* [Marked](https://github.com/chjj/marked) (by [William Orr](https://github.com/worr)) +* [MathJax](https://github.com/mathjax/MathJax) (by [Roland Zwaga](https://github.com/rolandzwaga)) +* [mCustomScrollbar](https://github.com/malihu/malihu-custom-scrollbar-plugin) (by [Sarah Williams](https://github.com/flurg)) +* [Meteor](https://www.meteor.com) (by [Dave Allen](https://github.com/fullflavedave)) +* [Microsoft Ajax](http://msdn.microsoft.com/en-us/library/ee341002(v=vs.100).aspx) (by [Patrick Magee](https://github.com/pjmagee)) +* [Microsoft Live Connect](http://msdn.microsoft.com/en-us/library/live/hh243643.aspx) (by [John Vilk](https://github.com/jvilk)) +* [Minimatch](https://github.com/isaacs/minimatch) (by [vvakame](https://github.com/vvakame)) +* [minimist](https://github.com/substack/minimist) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [Mixpanel](https://github.com/mixpanel/mixpanel-js) (by [Knut Eirik Leira Hjelle](https://github.com/hjellek)) +* [mixto](https://github.com/atom/mixto) (by [vvakame](https://github.com/vvakame)) +* [Modernizr](http://modernizr.com/) (by [Boris Yankov](https://github.com/borisyankov) and [Theodore Brown](https://github.com/theodorejb/)) +* [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield)) +* [MongoDB](http://mongodb.github.io/node-mongodb-native/) (from TypeScript samples, updated by [Niklas Mollenhauer](https://github.com/nikeee)) +* [mongoose](http://mongoosejs.com/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) +* [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz)) +* [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki)) +* [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov)) +* [nconf](https://github.com/flatiron/nconf) (by [Jeff Goddard](https://github.com/jedigo)) +* [noble](https://github.com/sandeepmistry/noble) (by [Seon-Wook Park](https://github.com/swook)) +* [nock](https://github.com/pgte/nock) (by [bonnici](https://github.com/bonnici)) +* [Node.js](http://nodejs.org/) (from TypeScript samples) +* [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov)) +* [node-ffi](https://github.com/rbranson/node-ffi) (by [Paul Loyd](https://github.com/loyd)) +* [node-form](https://github.com/rsamec/form) (by [Roman Samec](https://github.com/rsamec)) +* [node-git](https://github.com/christkv/node-git) (by [vvakame](https://github.com/vvakame)) +* [nodeunit](https://github.com/caolan/nodeunit) (by [Jeff Goddard](https://github.com/jedigo)) +* [node_zeromq](https://github.com/JustinTulloss/zeromq.node) (by [Dave McKeown](https://github.com/davemckeown)) +* [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov)) +* [node-uuid](https://github.com/broofa/node-uuid) (by [Jeff May](https://github.com/jeffmay)) +* [notify.js](https://github.com/alexgibson/notify.js) (by [soundTricker](https://github.com/soundTricker)) +* [NProgress](https://github.com/rstacruz/nprogress) (by [Judah Gabriel Himango](https://github.com/judahgabriel)) +* [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/)) +* [object-path](https://github.com/mariocasciaro/object-path) (by [Paulo Cesar](https://github.com/pocesar/)) +* [ocLazyLoad](https://github.com/ocombe/ocLazyLoad) (by [Roland Zwaga](https://github.com/rolandzwaga/)) +* [OpenLayers](https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/)) +* [Optimist](https://github.com/substack/node-optimist) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) +* [Passport](http://passportjs.org/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) +* [passport-strategy](https://github.com/jaredhanson/passport-strategy) (by [Lior Mualem](https://github.com/liorm)) +* [pathwatcher](http://atom.github.io/node-pathwatcher/) (by [vvakame](https://github.com/vvakame)) +* [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin)) +* [Parsimmon](https://github.com/jayferd/parsimmon) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [PDF.js](https://github.com/mozilla/pdf.js) (by [Josh Baldwin](https://github.com/jbaldwin)) +* [PEG.js](http://pegjs.majda.cz/) (by [vvakame](https://github.com/vvakame)) +* [Persona](http://www.mozilla.org/en-US/persona) (by [James Frasca](https://github.com/Nycto)) +* [PhantomJS](http://phantomjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker)) +* [PhoneGap](http://phonegap.com) (by [Boris Yankov](https://github.com/borisyankov)) +* [PixiJS](https://github.com/GoodBoyDigital/pixi.js) (by [Pedro Casaubon](https://github.com/xperiments)) +* [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)) +* [ProgressJs](http://usablica.github.io/progress.js/) (by [Shunsuke Ohtani](https://github.com/zaneli)) +* [Q](https://github.com/kriskowal/q) (by Barrie Nemetchek, Andrew Gaspar) +* [Q-io](https://github.com/kriskowal/q-io) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei)) +* [Raven.js](https://github.com/getsentry/raven-js) (by [Santi Albo](https://github.com/santialbo)) +* [Recaptcha.js](https://www.google.com/recaptcha) (by [Brent Jenkins](https://github.com/brentj73)) +* [Rickshaw](http://code.shutterstock.com/rickshaw/) (by [Blake Niemyjski](https://github.com/niemyjski)) +* [Riot.js](https://github.com/moot/riotjs) (by [vvakame](https://github.com/vvakame)) +* [Restify](https://github.com/mcavage/node-restify) (by [Bret Little](https://github.com/blittle)) +* [Redis](https://github.com/mranney/node_redis) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) +* [Request](https://github.com/mikeal/request) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) +* [Royalslider](http://dimsemenov.com/plugins/royal-slider/) (by [Christiaan Rakowski](https://github.com/csrakowski)) +* [Rx.js](http://rx.codeplex.com/) (by [gsino](http://www.codeplex.com/site/users/view/gsino), [Igor Oleinikov](https://github.com/Igorbek), [Carl de Billy](http://carl.debilly.net/), [zoetrope](https://github.com/zoetrope)) +* [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall)) +* [Restangular](https://github.com/mgonto/restangular/) (by [Boris Yankov](https://github.com/borisyankov)) +* [require.js](http://requirejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/)) +* [rtree.js](https://github.com/leaflet-extras/RTree) (by [Omede Firouz](https://github.com/oefirouz)) +* [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)) +* [Selenium WebDriverJS](https://code.google.com/p/selenium/) (by [Bill Armstrong](https://github.com/BillArmstrong)) +* [Semver](https://github.com/isaacs/node-semver) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [Sencha Touch](http://www.sencha.com/products/touch/) (by [Brian Kotek](https://github.com/brian428)) +* [SharePoint](http://sptypescript.codeplex.com) (by [Stanislav Vyshchepan](http://gandjustas.blogspot.ru) and [Andrey Markeev](http://markeev.com)) +* [SignalR](http://www.asp.net/signalr) (by [Boris Yankov](https://github.com/borisyankov)) +* [simple-cw-node](https://github.com/astronaughts/simple-cw-node) (by [vvakame](https://github.com/vvakame)) +* [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u)) +* [SlickGrid](https://github.com/mleibman/SlickGrid) (by [Josh Baldwin](https://github.com/jbaldwin)) +* [smoothie](https://github.com/joewalnes/smoothie) (by [Mike H. Hawley](https://github.com/mikehhawley) and [Drew Noakes](https://drewnoakes.com)) +* [socket.io](http://socket.io) (by [William Orr](https://github.com/worr)) +* [socket.io-client](http://socket.io) (by [Maido Kaara](https://github.com/v3rm0n)) +* [SockJS](https://github.com/sockjs/sockjs-client) (by [Emil Ivanov](https://github.com/vladev)) +* [sockjs-node](https://github.com/sockjs/sockjs-node) (by [Phil McCloghry-Laing](https://github.com/pmccloghrylaing)) +* [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)) +* [sqlite3](https://github.com/mapbox/node-sqlite3) (by [Nick Malaguti](https://github.com/nmalaguti)) +* [status-bar](https://github.com/atom/status-bar) (by [vvakame](https://github.com/vvakame)) +* [stripe](https://stripe.com/) (by [Eric J. Smith](https://github.com/ejsmith/)) +* [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/)) +* [Swiper](http://www.idangero.us/sliders/swiper) (by [Sebastián Galiano](https://github.com/sgaliano)) +* [SwipeView](http://cubiq.org/swipeview) (by [Boris Yankov](https://github.com/borisyankov)) +* [Swiz](https://github.com/racker/node-swiz) (by [Jeff Goddard](https://github.com/jedigo)) +* [TV4](https://github.com/geraintluff/tv4) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [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)) +* [text-buffer](https://github.com/atom/text-buffer) (by [vvakame](https://github.com/vvakame)) +* [text-encoding](https://github.com/inexorabletash/text-encoding) (by [MIZUNE Pine](https://github.com/pine613)) +* [three.js](http://mrdoob.github.com/three.js/) (by [Kon](http://phyzkit.net/)) +* [TimelineJS](https://github.com/NUKnightLab/TimelineJS) (by [Roland Zwaga](https://github.com/rolandzwaga)) +* [timezonecomplete](https://github.com/SpiritIT/timezonecomplete) (by [Rogier Schouten](https://github.com/rogierschouten)) +* [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)) +* [Twitter Typeahead](http://twitter.github.io/typeahead.js) (by [Ivaylo Gochkov](https://github.com/igochkov)) +* [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)) +* [universal-analytics](https://github.com/peaksandpies/universal-analytics) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [update-notifier](https://github.com/yeoman/update-notifier) (by [vvakame](https://github.com/vvakame)) +* [uri-templates](https://github.com/geraintluff/uri-templates) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [urlrouter](https://github.com/fengmk2/urlrouter) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) +* [UUID.js](https://github.com/LiosK/UUID.js) (by [Jason Jarrett](https://github.com/staxmanade)) +* [Valerie](https://github.com/davewatts/valerie) (by [Howard Richards](https://github.com/conficient)) +* [Velocity](http://velocityjs.org/) (by [Greg Smith](https://github.com/smrq)) +* [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/)) +* [vinyl](https://github.com/wearefractal/vinyl) (by [vvakame](https://github.com/vvakame/)) +* [vinyl-fs](https://github.com/wearefractal/vinyl-fs) (by [vvakame](https://github.com/vvakame/)) +* [WebRTC](http://dev.w3.org/2011/webrtc/editor/webrtc.html) (by [Ken Smith](https://github.com/smithkl42)) +* [websocket](https://github.com/Worlize/WebSocket-Node) (by [Paul Loyd](https://github.com/loyd)) +* [WinJS](http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx) (from TypeScript samples) +* [WinRT](http://msdn.microsoft.com/en-us/library/windows/apps/br211377.aspx) (from TypeScript samples) +* [ws](http://einaros.github.io/ws/) (by [Paul Loyd](https://github.com/loyd)) +* [x2js](https://code.google.com/p/x2js/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) +* [xml2js](https://github.com/Leonidas-from-XIV/node-xml2js) (by [Michel Salib](https://github.com/michelsalib)) +* [XRegExp](http://xregexp.com/) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [YouTube](https://developers.google.com/youtube/) (by [Daz Wilkin](https://github.com/DazWilkin/)) +* [YouTube Analytics API](https://developers.google.com/youtube/analytics/) (by [Frank M](https://github.com/sgtfrankieboy)) +* [YouTube Data API](https://developers.google.com/youtube/v3/) (by [Frank M](https://github.com/sgtfrankieboy/)) +* [Zepto.js](http://zeptojs.com/) (by [Josh Baldwin](https://github.com/jbaldwin)) +* [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)) diff --git a/Finch/Finch-tests.ts b/Finch/Finch-tests.ts new file mode 100644 index 0000000000..28aeb6b668 --- /dev/null +++ b/Finch/Finch-tests.ts @@ -0,0 +1,368 @@ +/// + +function test_Finch() { + + + Finch.route("Hello/Route", function() { + return console.log("Well hello there! How you doin'?!"); + }); + + Finch.route("Hello/Route/:someId", function(bindings) { + return console.log("Hey! Here's Some Id: " + bindings.someId); + }); + + Finch.route("Hello/Route/:someId", function(bindings, childCallback) { + console.log("Hey! Here's Some Id: " + bindings.someId); + return childCallback(); + }); + + Finch.route("some/route", { + setup: function(bindings) { + return console.log("Some Route has been setup! :)"); + }, + load: function(bindings) { + return console.log("Some Route has been loaed! :D"); + }, + unload: function(bindings) { + return console.log("Some Route has been loaed! :("); + }, + teardown: function(bindings) { + return console.log("Some Route has been torndown! :'("); + } + }); + + Finch.route("some/route", { + setup: function(bindings, childCallback) { + console.log("Some Route has been setup! :)"); + return childCallback(); + }, + load: function(bindings, childCallback) { + console.log("Some Route has been loaed! :D"); + return childCallback(); + }, + unload: function(bindings, childCallback) { + console.log("Some Route has been loaed! :("); + return childCallback(); + }, + teardown: function(bindings, childCallback) { + console.log("Some Route has been torndown! :'("); + return childCallback(); + } + }); + + Finch.call("Some/Route"); + + Finch.route("Some/Route", function() { + return Finch.observe("hello", "foo", function(hello: any, foo: string) { + return console.log("" + hello + " and " + foo); + }); + }); + + Finch.route("Some/Route", function() { + return Finch.observe(["hello", "foo"], function(hello: any, foo: any) { + return console.log("" + hello + " and " + foo); + }); + }); + + Finch.route("Some/Route", function(bindings) { + return Finch.observe(function(params) { + }); + }); + + Finch.navigate("Some/Route"); + + Finch.navigate("Some/Route", { + hello: 'world', + foo: 'bar' + }); + + Finch.navigate("Some/Route", { + foo: 'bar' + }, true); + + Finch.navigate("Some/Route", true); + + Finch.navigate({ + hello: 'world2', + wow: 'wee' + }); + + Finch.navigate({ + foo: 'bar', + wow: 'wee!!!' + }); + + Finch.navigate({ + hello: 'world2' + }, true); + + Finch.listen(); + Finch.ignore(); + Finch.abort(); + + + //test from Finch + Finch.call("/foo/bar"); + Finch.call("/foo/bar/123"); + Finch.call("/foo/bar/123"); + Finch.call("/foo/bar/123?x=Hello&y=World"); + Finch.call("/foo/baz/456"); + Finch.call("/quux/789?band=Sunn O)))&genre=Post-Progressive Fridgecore"); + Finch.call("/foo/bar/baz"); + Finch.call("/foo/bar/quux"); + Finch.call("/foo"); + Finch.call("/foo/bar"); + Finch.call("/foo"); + Finch.call("/foo"); + Finch.call("/"); + Finch.call("/"); + Finch.call("/foo"); + Finch.call("/foo/bar"); + Finch.call("/foo/bar?baz=quux"); + Finch.call("/foo/bar?baz=xyzzy"); + + var cb: any; + Finch.route("foo", { + setup: cb.setup_foo = this.stub(), + load: cb.load_foo = this.stub(), + unload: cb.unload_foo = this.stub(), + teardown: cb.teardown_foo = this.stub() + }); + Finch.route("[foo]/bar", { + setup: cb.setup_foo_bar = this.stub(), + load: cb.load_foo_bar = this.stub(), + unload: cb.unload_foo_bar = this.stub(), + teardown: cb.teardown_foo_bar = this.stub() + }); + Finch.route("[foo/bar]/:id", { + setup: cb.setup_foo_bar_id = this.stub(), + load: cb.load_foo_bar_id = this.stub(), + unload: cb.unload_foo_bar_id = this.stub(), + teardown: cb.teardown_foo_bar_id = this.stub() + }); + Finch.route("[foo]/baz", { + setup: cb.setup_foo_baz = this.stub(), + load: cb.load_foo_baz = this.stub(), + unload: cb.unload_foo_baz = this.stub(), + teardown: cb.teardown_foo_baz = this.stub() + }); + Finch.route("[foo/baz]/:id", { + setup: cb.setup_foo_baz_id = this.stub(), + load: cb.load_foo_baz_id = this.stub(), + unload: cb.unload_foo_baz_id = this.stub(), + teardown: cb.teardown_foo_baz_id = this.stub() + }); + Finch.call("/foo"); + Finch.call("/foo/bar"); + Finch.call("/foo"); + Finch.call("/foo/bar/123?x=abc"); + Finch.call("/foo/bar/456?x=aaa&y=zzz"); + Finch.call("/foo/bar/456?x=bbb&y=zzz"); + Finch.call("/foo/bar/456?y=zzz&x=bbb"); + Finch.call("/foo/baz/789"); + Finch.call("/foo/baz/abc?term=Hello"); + Finch.call("/foo/baz/abc?term=World"); + Finch.route("bar", this.stub()); + Finch.call("/foo"); + Finch.call("/bar"); + Finch.route("/", function() { + }); + Finch.route("[/]home", function() { + }); + Finch.route("[/home]/news", { + setup: function() { + }, + load: function() { + }, + unload: function() { + return true; + }, + teardown: function() { + return false; + } + }); + Finch.route("/foo", { + setup: function() { + return true; + }, + load: function() { + return true; + }, + unload: function() { + }, + teardown: function() { + } + }); + Finch.route("[/]bar", { + setup: function() { + }, + load: function() { + }, + unload: function() { + }, + teardown: function() { + } + }); + Finch.call("/bar"); + Finch.call("/home/news"); + Finch.call("/foo"); + Finch.call("/home/news"); + Finch.call("/bar"); + Finch.route("baz", this.stub()); + Finch.call("/foo"); + Finch.call("/foo/bar"); + Finch.call("/baz"); + Finch.route("/home", { + setup: function(bindings, next) { + return next(); + }, + load: function(bindings, next) { + return next(); + }, + unload: function(bindings, next) { + return next(); + }, + teardown: function(bindings, next) { + return next(); + } + }); + Finch.route("[/home]/news", { + setup: function(bindings, next) { + return next(); + }, + load: function(bindings, next) { + return next(); + }, + unload: function(bindings, next) { + return next(); + }, + teardown: function(bindings, next) { + return next(); + } + }); + Finch.call("/home"); + Finch.call("/home/news"); + Finch.call("/foo"); + + Finch.route("/", function(bindings) { + return Finch.observe(["x"], function(x) { + }); + }); + Finch.call("/?x=123"); + Finch.call("/?x=123.456"); + Finch.call("/?x=true"); + Finch.call("/?x=false"); + Finch.call("/?x=stuff"); + Finch.options({ + CoerceParameterTypes: true + }); + Finch.call("/?x=123"); + Finch.call("/?x=123.456"); + Finch.call("/?x=true"); + Finch.call("/?x=false"); + Finch.call("/?x=stuff"); + Finch.route("/:x", function(_arg) { + }); + Finch.call("/123"); + Finch.call("/123.456"); + Finch.call("/true"); + Finch.call("/false"); + Finch.call("/stuff"); + Finch.options({ + CoerceParameterTypes: true + }); + Finch.call("/123"); + Finch.call("/123.456"); + Finch.call("/true"); + Finch.call("/false"); + Finch.call("/stuff"); + + Finch.navigate("/home"); + Finch.navigate("/home/news"); + Finch.navigate("/home"); + Finch.navigate("/home", { + foo: "bar" + }); + Finch.navigate("/home", { + hello: "world" + }); + Finch.navigate({ + foos: "bars" + }); + Finch.navigate({ + foos: "baz" + }); + Finch.navigate({ + hello: "world" + }, true); + Finch.navigate({ + foos: null + }, true); + Finch.navigate("/home/news", true); + Finch.navigate("/hello world", {}); + Finch.navigate("/hello world", { + foo: "bar bar" + }); + Finch.navigate({ + foo: "baz baz" + }); + Finch.navigate({ + hello: 'world world' + }, true); + Finch.navigate("/home?foo=bar", { + hello: "world" + }); + Finch.navigate("/home?foo=bar", { + hello: "world", + foo: "baz" + }); + Finch.navigate("/home?foo=bar", { + hello: "world", + free: "bird" + }); + Finch.navigate("#/home", true); + Finch.navigate("#/home"); + Finch.navigate("#/home/news", { + free: "birds", + hello: "worlds" + }); + Finch.navigate("#/home/news", { + foo: "bar" + }, true); + Finch.navigate("/home/news"); + Finch.navigate("../"); + Finch.navigate("./"); + Finch.navigate("./news"); + Finch.navigate("/home/news/article"); + Finch.navigate("../../account"); + + Finch.listen(); + Finch.ignore(); + Finch.route("/home", function(bindings, continuation) { + }); + Finch.route("/foo", function(bindings, continuation) { + }); + Finch.call("home"); + Finch.call("foo"); + Finch.abort(); + Finch.call("foo"); + Finch.route("/", { + 'setup': cb.slash_setup = this.stub(), + 'load': cb.slash_load = this.stub(), + 'unload': cb.slash_unload = this.stub(), + 'teardown': cb.slash_teardown = this.stub() + }); + Finch.route("[/]users/profile", { + 'setup': cb.profile_setup = this.stub(), + 'load': cb.profile_load = this.stub(), + 'unload': cb.profile_unload = this.stub(), + 'teardown': cb.profile_teardown = this.stub() + }); + Finch.route("[/]:page", { + 'setup': cb.page_setup = this.stub(), + 'load': cb.page_load = this.stub(), + 'unload': cb.page_unload = this.stub(), + 'teardown': cb.page_teardown = this.stub() + }); + Finch.call("/users"); +} diff --git a/Finch/Finch.d.ts b/Finch/Finch.d.ts new file mode 100644 index 0000000000..e3dd86c701 --- /dev/null +++ b/Finch/Finch.d.ts @@ -0,0 +1,47 @@ +// Type definitions for Finch 0.5.13 +// Project: https://github.com/stoodder/finchjs +// Definitions by: David Sichau +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +interface FinchCallback { + (bindings?: any, childCallback? : () => void): any; +} + +interface ExpandedCallback { + setup?: FinchCallback; + load?: FinchCallback; + unload?: FinchCallback; + teardown?: FinchCallback; +} + +interface ObserveCallback { + (...args: any[]): string; +} +interface FinchOptions { + CoerceParameterTypes?: boolean; +} + + +interface FinchStatic { + route(route: string, callback: FinchCallback): void; + route(route: string, callbacks: ExpandedCallback): void; + call( uri: string ): void; + + observe(argN: string[], callback: (params: ObserveCallback ) => void): void; + observe(callback: (params: ObserveCallback) => void): void; + observe(...args: any[]): void; + navigate(uri:string, queryParams?:any, doUpdate?:boolean ): void; + navigate(uri:string, doUpdate:boolean ): void; + navigate(queryParams:any, doUpdate?:boolean ): void; + listen(): boolean; + ignore(): boolean; + abort(): void; + options(options: FinchOptions): void; +} + + +declare var Finch: FinchStatic; +declare module "finch" { + export = Finch; +} diff --git a/JSONStream/JSONStream-tests.ts b/JSONStream/JSONStream-tests.ts new file mode 100644 index 0000000000..ea7eb64ff9 --- /dev/null +++ b/JSONStream/JSONStream-tests.ts @@ -0,0 +1,15 @@ +/// + +import json = require('JSONStream'); + +var read: NodeJS.ReadableStream; +var write: NodeJS.WritableStream; + +read = read.pipe(json.parse('*')); +read = read.pipe(json.parse(['foo/*', 'bar/*'])); + +read = json.stringify(); +read = json.stringify('{', ',', '}'); + +read = json.stringifyObject(); +read = json.stringifyObject('{', ',', '}'); diff --git a/JSONStream/JSONStream.d.ts b/JSONStream/JSONStream.d.ts new file mode 100644 index 0000000000..869f965f45 --- /dev/null +++ b/JSONStream/JSONStream.d.ts @@ -0,0 +1,22 @@ +// Type definitions for JSONStream v0.8.0 +// Project: http://github.com/dominictarr/JSONStream +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'JSONStream' { + + export interface Options { + recurse: boolean; + } + + export function parse(pattern: any): NodeJS.ReadWriteStream; + export function parse(patterns: any[]): NodeJS.ReadWriteStream; + + export function stringify(): NodeJS.ReadWriteStream; + export function stringify(open: string, sep: string, close: string): NodeJS.ReadWriteStream; + + export function stringifyObject(): NodeJS.ReadWriteStream; + export function stringifyObject(open: string, sep: string, close: string): NodeJS.ReadWriteStream; +} diff --git a/README.md b/README.md old mode 100755 new mode 100644 index 4120a354ef..479e04cc89 --- a/README.md +++ b/README.md @@ -1,317 +1,41 @@ -DefinitelyTyped [![Build Status](https://travis-ci.org/borisyankov/DefinitelyTyped.png?branch=master)](https://travis-ci.org/borisyankov/DefinitelyTyped) -=============== +# 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. +> The repository for *high quality* TypeScript type definitions. + +For more information see the [definitelytyped.org](http://definitelytyped.org) website. + +## Usage -Usage ------ Include a line like this: -``` +```typescript /// ``` -[TypeScript Directory: tools, libraries, projects and learning resources](https://github.com/DefinitelyTyped/typescript-directory) +## Contributions -Contributor Guidelines ----------------------- +DefinitelyTyped only works because of contributions by users like you! -See the section: [How to contribute](https://github.com/borisyankov/DefinitelyTyped/wiki/How-to-contribute) +Please see the [contribution guide](http://definitelytyped.org/guides/contributing.html) on how to contribute to DefinitelyTyped. -Other means to get the definitions ----------------------------------- +## How to get the definitions + +* Directly from the Github repos * [NuGet packages](http://nuget.org/packages?q=DefinitelyTyped) -* [TypeScript Definition package manager](https://github.com/DefinitelyTyped/tsd) +* [TypeScript Definition manager](https://github.com/DefinitelyTyped/tsd) -List of Definitions -------------------- -* [accounting.js](http://josscrowcroft.github.io/accounting.js/) (by [Sergey Gerasimov](https://github.com/gerich-home)) -* [Ace Cloud9 Editor](http://ace.ajax.org/) (by [Diullei Gomes](https://github.com/Diullei)) -* [Add To Home Screen] (http://cubiq.org/add-to-home-screen) (by [James Wilkins] (http://www.codeplex.com/site/users/view/jamesnw)) -* [AmCharts](http://www.amcharts.com/) (by [Covobonomo](https://github.com/covobonomo/)) -* [AngularFire](https://www.firebase.com/docs/angular/reference.html) (by [Dénes Harmath](https://github.com/thSoft)) -* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes)) -* [AngularUI](http://angular-ui.github.io/) (by [Michel Salib](https://github.com/michelsalib)) -* [Angular Protractor](https://github.com/angular/protractor) (by [Bill Armstrong](https://github.com/BillArmstrong)) -* [Angular Translate](http://pascalprecht.github.io/angular-translate/) (by [Michel Salib](https://github.com/michelsalib)) -* [Angular UI Bootstrap](http://angular-ui.github.io/bootstrap) (by [Brian Surowiec](https://github.com/xt0rted)) -* [AppFramework](http://app-framework-software.intel.com/) (by [Kyo Ago](https://github.com/kyo-ago)) -* [Arbiter](http://arbiterjs.com/) (by [Arash Shakery](https://github.com/arash16)) -* [asciify](https://github.com/olizilla/asciify) (by [Alan](http://alan.norbauer.com)) -* [assert](https://github.com/Jxck/assert) (by [vvakame](https://github.com/vvakame)) -* [async](https://github.com/caolan/async) (by [Boris Yankov](https://github.com/borisyankov)) -* [Atom](https://atom.io/) (by [vvakame](https://github.com/vvakame)) -* [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Backbone Relational](http://backbonerelational.org/) (by [Eirik Hoem](https://github.com/eirikhm)) -* [BigScreen](http://brad.is/coding/BigScreen/) (by [Douglas Eichelberger](https://github.com/dduugg)) -* [Bluebird](https://github.com/petkaantonov/bluebird) (by [Bart van der Schoor](https://github.com/Bartvds)) -* [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)) -* [Browser Harness](https://github.com/scriby/browser-harness) (by [Chris Scribner](https://github.com/scriby)) -* [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) and [otiai10](https://github.com/otiai10)) -* [Chrome App](http://developer.chrome.com/apps/) (by [Adam Lay](https://github.com/AdamLay)) -* [CKEditor](https://github.com/ckeditor/ckeditor-dev) (by [Ondrej Sevcik](https://github.com/ondrejsevcik)) -* [Clone](https://github.com/pvorb/node-clone) (by [Kieran Simpson](https://github.com/kierans)) -* [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)) -* [configstore](http://github.com/yeoman/configstore) (by [Bart van der Schoor](https://github.com/Bartvds)) -* [Cordova](http://cordova.apache.org) (by [Microsoft Open Technologies, Inc.](http://msopentech.com/)) -* [Couchbase / Couchnode](https://github.com/couchbase/couchnode) (by [Basarat Ali Syed](https://github.com/basarat)) -* [Crossfilter](https://github.com/square/crossfilter) (by [Schmulik Raskin](https://github.com/schmuli)) -* [crypto-js](https://code.google.com/p/crypto-js/) (by [Gia Bảo @ Sân Đình](https://github.com/giabao)). @see [cryptojs.d.ts repo](https://github.com/giabao/cryptojs.d.ts) -* [d3.js](http://d3js.org/) (from TypeScript samples) -* [dhtmlxGantt](http://dhtmlx.com/docs/products/dhtmlxGantt) (by [Maksim Kozhukh](http://github.com/mkozhukh)) -* [dhtmlxScheduler](http://dhtmlx.com/docs/products/dhtmlxScheduler) (by [Maksim Kozhukh](http://github.com/mkozhukh)) -* [diff](https://github.com/kpdecker/jsdiff) (by [vvakame](http://github.com/vvakame)) -* [Dock Spawn](http://dockspawn.com) (by [Drew Noakes](https://drewnoakes.com)) -* [docCookies](https://developer.mozilla.org/en-US/docs/Web/API/document.cookie) (by [Jon Egerton](https://github.com/jonegerton)) -* [domo](http://domo-js.com/) (by [Steve Fenton](https://github.com/Steve-Fenton)) -* [doT](https://github.com/olado/doT) (by [ZombieHunter](https://github.com/ZombieHunter)) -* [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)) -* [EasyStar](http://easystarjs.com/) (by [Magnus Gustafsson](https://github.com/Borundin)) -* [ember.js](http://emberjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) -* [emissary](https://github.com/atom/emissary) (by [vvakame](https://github.com/vvakame)) -* [EpicEditor](http://epiceditor.com/) (by [Boris Yankov](https://github.com/borisyankov)) -* [ES6-Promises](https://github.com/jakearchibald/ES6-Promises) (by [François de Campredon](https://github.com/fdecampredon/)) -* [expect.js](https://github.com/LearnBoost/expect.js) (by [Teppei Sato](https://github.com/teppeis)) -* [expectations](https://github.com/spmason/expectations) (by [vvakame](https://github.com/vvakame)) -* [Express](http://expressjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Ext JS](http://www.sencha.com/products/extjs/) (by [Brian Kotek](https://github.com/brian428)) -* [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)) -* [Firebase](https://www.firebase.com/docs/javascript/firebase) (by [Vincent Bortone](https://github.com/vbortone)) -* [Firefox](https://developer.mozilla.org/en-US/docs/Web/API) (by [vvakame](https://github.com/vvakame)) -* [FlexSlider](http://www.woothemes.com/flexslider/) (by [Diullei Gomes](https://github.com/Diullei)) -* [Flight by Twitter](http://flightjs.github.com/flight/) (by [Jonathan Hedrén](https://github.com/jonathanhedren)) -* [Foundation](http://foundation.zurb.com/) (by [Boris Yankov](https://github.com/borisyankov)) -* [FPSMeter](http://darsa.in/fpsmeter/) (by [Aaron Lampros](https://github.com/alampros)) -* [FullCalendar](http://arshaw.com/fullcalendar/) (by [Neil Stalker](https://github.com/nestalk)) -* [Gamepad](http://www.w3.org/TR/gamepad/) (by [Kon](http://phyzkit.net/)) -* [Giraffe](https://github.com/barc/backbone.giraffe) (by [Matt McCray](https://github.com/darthapo)) -* [glDatePicker](http://glad.github.com/glDatePicker/) (by [Dániel Tar](https://github.com/qcz)) -* [Glob](https://github.com/isaacs/node-glob) (by [vvakame](https://github.com/vvakame)) -* [GoJS](http://gojs.net/) (by [Barbara Duckworth](https://github.com/barbara42)) -* [Greasemonkey](http://www.greasespot.net/) (by [Kota Saito](https://github.com/kotas)) -* [GreenSock Animation Platform (GSAP)](http://www.greensock.com/get-started-js/) (by [Robert S.](https://github.com/codeBelt)) -* [Grunt JS](http://gruntjs.com/) (by [Jeff May](https://github.com/jeffmay), [Basarat Ali Syed](https://github.com/basarat) and [San Chen](https://github.com/bigsan)) -* [Google API Client](https://code.google.com/p/google-api-javascript-client/) (by [Frank M](https://github.com/sgtfrankieboy)) -* [Google App Engine Channel API](https://developers.google.com/appengine/docs/java/channel/javascript) (by [vvakame](https://github.com/vvakame)) -* [GoogleMaps](https://developers.google.com/maps/) (by [Esben Nepper](https://github.com/eNepper)) -* [GoogleMaps InfoBubble](http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/) (by [Johan Nilsson](https://github.com/dashue)) -* [Google Geolocation](https://code.google.com/p/geo-location-javascript/) (by [Vincent Bortone](https://github.com/vbortone)) -* [Google Page Speed Online API](https://developers.google.com/speed/pagespeed/) (by [Frank M](https://github.com/sgtfrankieboy)) -* [Google Translate API](https://developers.google.com/translate/) (by [Frank M](https://github.com/sgtfrankieboy)) -* [Google Url Shortener](https://developers.google.com/url-shortener/) (by [Frank M](https://github.com/sgtfrankieboy)) -* [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)) -* [HashSet](http://www.timdown.co.uk/jshashtable/jshashset.html) (by [Sergey Gerasimov](https://github.com/gerich-home)) -* [Hashtable](http://www.timdown.co.uk/jshashtable/) (by [Sergey Gerasimov](https://github.com/gerich-home)) -* [HelloJS](http://adodson.com/hello.js) (by [Pavel Zika](https://github.com/PavelPZ)) -* [Highcharts](http://www.highcharts.com/) (by [damianog](https://github.com/damianog)) -* [Highland](http://highlandjs.org/) (by [Bart van der Schoor](https://github.com/Bartvds/)) -* [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee)) -* [History.js](https://github.com/browserstate/history.js) (by [Boris Yankov](https://github.com/borisyankov)) -* [Html2Canvas.js](https://github.com/niklasvh/html2canvas/) (by [Richard Hepburn](https://github.com/rwhepburn)) -* [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)) -* [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz)) -* [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) and [Christiaan Rakowski](https://github.com/csrakowski)) -* [IxJS (Interactive extensions)](https://github.com/Reactive-Extensions/IxJS) (by [Igor Oleinikov](https://github.com/Igorbek)) -* [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/)) -* [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Jasmine-jQuery](https://github.com/velesin/jasmine-jquery) (by [Gregor Stamac](https://github.com/gstamac)) -* [JointJS](http://www.jointjs.com/) (by [Aidan Reel](http://github.com/areel)) -* [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.Address](https://github.com/asual/jquery-address) (by [Martin Duparc](https://github.com/martinduparc/)) -* [jQuery.areYouSure](https://github.com/codedance/jquery.AreYouSure) (by [Jon Egerton](https://github.com/jonegerton)) -* [jQuery.autosize](http://www.jacklmoore.com/autosize/) (by [Jack Moore](http://www.jacklmoore.com/)) -* [jQuery.BBQ](http://benalman.com/projects/jquery-bbq-plugin/) (by [Adam R. Smith](https://github.com/sunetos)) -* [jQuery.CLEditor](http://premiumsoftware.net/CLEditor) (by [Jeffery Grajkowski](https://github.com/pushplay)) -* [jQuery.clientSideLogging](https://github.com/remybach/jQuery.clientSideLogging/) (by [Diullei Gomes](https://github.com/diullei/)) -* [jQuery.Colorbox](http://www.jacklmoore.com/colorbox/) (by [Gidon Junge](https://github.com/gjunge)) -* [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.Cycle](http://jquery.malsup.com/cycle/) (by [François Guillot](http://fguillot.developpez.com/)) -* [jQuery.Cycle2](http://jquery.malsup.com/cycle2/) (by [Donny Nadolny](https://github.com/dnadolny)) -* [jQuery.dataTables](http://www.datatables.net) (by [Armin Sander](https://github.com/pragmatrix)) -* [jQuery.datetimepicker](http://trentrichardson.com/examples/timepicker/) (by [Doug McDonald](https://github.com/dougajmcdonald)) -* [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.gridster](http://gridster.net) (by [Josh Baldwin](https://github.com/jbaldwin/gridster.d.ts)) -* [jQuery.jNotify](http://jnotify.codeplex.com) (by [James Curran](https://github.com/jamescurran/)) -* [jQuery.joyride](http://zurb.com/playground/jquery-joyride-feature-tour-plugin) (by [Vincent Bortone](https://github.com/vbortone)) -* [jQuery.jSignature] (https://github.com/willowsystems/jSignature) (by [Patrick Magee](https://github.com/pjmagee)) -* [jQuery.noty](http://needim.github.io/noty/) (by [Aaron King](https://github.com/kingdango/)) -* [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb)) -* [jQuery.payment](http://needim.github.io/noty/) (by [Eric J. Smith](https://github.com/ejsmith/)) -* [jQuery.pnotify](http://sciactive.github.io/pnotify/ (by [David Sichau](https://github.com/DavidSichau/)) -* [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.superLink](http://james.padolsey.com/demos/plugins/jQuery/superLink/superlink.jquery.js) (by [Blake Niemyjski](https://github.com/niemyjski)) -* [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.Timer](http://jchavannes.com/jquery-timer/demo) (by [Joshua Strobl](https://github.com/JoshStrobl)) -* [jQuery.TinyCarousel](http://baijs.nl/tinycarousel/) (by [Christiaan Rakowski](https://github.com/csrakowski)) -* [jQuery.TinyScrollbar](http://baijs.nl/tinyscrollbar/) (by [Christiaan Rakowski](https://github.com/csrakowski)) -* [jQuery.tooltipster] (https://github.com/iamceege/tooltipster) (by [Patrick Magee](https://github.com/pjmagee)) -* [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)) -* [jQuery.base64](https://github.com/yatt/jquery.base64) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki)) -* [js-git](https://github.com/creationix/js-git) (by [Bart van der Schoor](https://github.com/Bartvds)) -* [js-yaml](https://github.com/nodeca/js-yaml) (by [Bart van der Schoor](https://github.com/Bartvds/)) -* [jScrollPane](http://jscrollpane.kelvinluck.com) (by [Dániel Tar](https://github.com/qcz)) -* [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/)) -* [JSON-Pointer](https://www.npmjs.org/package/json-pointer) (by [Bart van der Schoor](https://github.com/Bartvds)) -* [JsRender](http://www.jsviews.com/#jsrender) (by [Kensuke MATSUZAKI](https://github.com/zakki)) -* [jStorage](http://www.jstorage.info/) (by [Danil Flores](https://github.com/dflor003/)) -* [JWPlayer](http://developer.longtailvideo.com/trac/) (by [Martin Duparc](https://github.com/martinduparc/)) -* [KeyboardJS](https://github.com/RobertWHurst/KeyboardJS) (by [Vincent Bortone](https://github.com/vbortone/)) -* [KineticJS](http://kineticjs.com/) (by [Basarat Ali Syed](https://github.com/basarat)) -* [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.DeferredUpdates](https://github.com/mbest/knockout-deferred-updates) (by [Sebastián Galiano](https://github.com/sgaliano)) -* [Knockout.ES5](https://github.com/SteveSanderson/knockout-es5) (by [Sebastián Galiano](https://github.com/sgaliano)) -* [Knockout.Mapper](https://github.com/LucasLorentz/knockout.mapper) (by [Brandon Meyer](https://github.com/BMeyerKC)) -* [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 Himango](https://github.com/JudahGabriel)) -* [Knockout.Rx](https://github.com/Igorbek/knockout.rx) (by [Igor Oleinikov](https://github.com/Igorbek)) -* [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)) -* [Lazy.js](http://danieltao.com/lazy.js/) (by [Bart van der Schoor](https://github.com/Bartvds)) -* [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)) -* [ladda](https://github.com/hakimel/Ladda) (by [Danil Flores](https://github.com/dflor003)) -* [Levelup](https://github.com/rvagg/node-levelup) (by [Bret Little](https://github.com/blittle)) -* [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)) -* [localForage](https://github.com/mozilla/localForage) (by [david pichsenmeister](https://github.com/3x14159265)) -* [Lodash](http://lodash.com/) (by [Brian Zengel](https://github.com/bczengel)) -* [Logg](https://github.com/dpup/node-logg) (by [Bret Little](https://github.com/blittle)) -* [Marked](https://github.com/chjj/marked) (by [William Orr](https://github.com/worr)) -* [mCustomScrollbar](https://github.com/malihu/malihu-custom-scrollbar-plugin) (by [Sarah Williams](https://github.com/flurg)) -* [Meteor](https://www.meteor.com) (by [Dave Allen](https://github.com/fullflavedave)) -* [Microsoft Live Connect](http://msdn.microsoft.com/en-us/library/live/hh243643.aspx) (by [John Vilk](https://github.com/jvilk)) -* [Minimatch](https://github.com/isaacs/minimatch) (by [vvakame](https://github.com/vvakame)) -* [minimist](https://github.com/substack/minimist) (by [Bart van der Schoor](https://github.com/Bartvds)) -* [mixto](https://github.com/atom/mixto) (by [vvakame](https://github.com/vvakame)) -* [Modernizr](http://modernizr.com/) (by [Boris Yankov](https://github.com/borisyankov) and [Theodore Brown](https://github.com/theodorejb/)) -* [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield)) -* [MongoDB](http://mongodb.github.io/node-mongodb-native/) (from TypeScript samples, updated by [Niklas Mollenhauer](https://github.com/nikeee)) -* [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz)) -* [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki)) -* [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-ffi](https://github.com/rbranson/node-ffi) (by [Paul Loyd](https://github.com/loyd)) -* [node-git](https://github.com/christkv/node-git) (by [vvakame](https://github.com/vvakame)) -* [node_zeromq](https://github.com/JustinTulloss/zeromq.node) (by [Dave McKeown](https://github.com/davemckeown)) -* [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov)) -* [notify.js](https://github.com/alexgibson/notify.js) (by [soundTricker](https://github.com/soundTricker)) -* [NProgress](https://github.com/rstacruz/nprogress) (by [Judah Gabriel Himango](https://github.com/judahgabriel)) -* [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/)) -* [OpenLayers](https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/)) -* [Passport](http://passportjs.org/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) -* [pathwatcher](http://atom.github.io/node-pathwatcher/) (by [vvakame](https://github.com/vvakame)) -* [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin)) -* [Parsimmon](https://github.com/jayferd/parsimmon) (by [Bart van der Schoor](https://github.com/Bartvds)) -* [PDF.js](https://github.com/mozilla/pdf.js) (by [Josh Baldwin](https://github.com/jbaldwin)) -* [PEG.js](http://pegjs.majda.cz/) (by [vvakame](https://github.com/vvakame)) -* [Persona](http://www.mozilla.org/en-US/persona) (by [James Frasca](https://github.com/Nycto)) -* [PhantomJS](http://phantomjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker)) -* [PhoneGap](http://phonegap.com) (by [Boris Yankov](https://github.com/borisyankov)) -* [PixiJS](https://github.com/GoodBoyDigital/pixi.js) (by [Pedro Casaubon](https://github.com/xperiments)) -* [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)) -* [Q](https://github.com/kriskowal/q) (by Barrie Nemetchek, Andrew Gaspar) -* [Q-io](https://github.com/kriskowal/q-io) (by [Bart van der Schoor](https://github.com/Bartvds)) -* [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei)) -* [Raven.js](https://github.com/getsentry/raven-js) (by [Santi Albo](https://github.com/santialbo)) -* [Rickshaw](http://code.shutterstock.com/rickshaw/) (by [Blake Niemyjski](https://github.com/niemyjski)) -* [Riot.js](https://github.com/moot/riotjs) (by [vvakame](https://github.com/vvakame)) -* [Restify](https://github.com/mcavage/node-restify) (by [Bret Little](https://github.com/blittle)) -* [Royalslider](http://dimsemenov.com/plugins/royal-slider/) (by [Christiaan Rakowski](https://github.com/csrakowski)) -* [Rx.js](http://rx.codeplex.com/) (by [gsino](http://www.codeplex.com/site/users/view/gsino), [Igor Oleinikov](https://github.com/Igorbek), [Carl de Billy](http://carl.debilly.net/), [zoetrope](https://github.com/zoetrope)) -* [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall)) -* [Restangular](https://github.com/mgonto/restangular/) (by [Boris Yankov](https://github.com/borisyankov)) -* [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)) -* [Selenium WebDriverJS](https://code.google.com/p/selenium/) (by [Bill Armstrong](https://github.com/BillArmstrong)) -* [Semver](https://github.com/isaacs/node-semver) (by [Bart van der Schoor](https://github.com/Bartvds)) -* [Sencha Touch](http://www.sencha.com/products/touch/) (by [Brian Kotek](https://github.com/brian428)) -* [SharePoint](http://sptypescript.codeplex.com) (by [Stanislav Vyshchepan](http://gandjustas.blogspot.ru) and [Andrey Markeev](http://markeev.com)) -* [SignalR](http://www.asp.net/signalr) (by [Boris Yankov](https://github.com/borisyankov)) -* [simple-cw-node](https://github.com/astronaughts/simple-cw-node) (by [vvakame](https://github.com/vvakame)) -* [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u)) -* [SlickGrid](https://github.com/mleibman/SlickGrid) (by [Josh Baldwin](https://github.com/jbaldwin)) -* [smoothie](https://github.com/joewalnes/smoothie) (by [Mike H. Hawley](https://github.com/mikehhawley) and [Drew Noakes](https://drewnoakes.com)) -* [socket.io](http://socket.io) (by [William Orr](https://github.com/worr)) -* [socket.io-client](http://socket.io) (by [Maido Kaara](https://github.com/v3rm0n)) -* [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)) -* [stripe](https://stripe.com/) (by [Eric J. Smith](https://github.com/ejsmith/)) -* [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/)) -* [Swiper](http://www.idangero.us/sliders/swiper) (by [Sebastián Galiano](https://github.com/sgaliano)) -* [SwipeView](http://cubiq.org/swipeview) (by [Boris Yankov](https://github.com/borisyankov)) -* [TV4](https://github.com/geraintluff/tv4) (by [Bart van der Schoor](https://github.com/Bartvds)) -* [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)) -* [Twitter Typeahead](http://twitter.github.io/typeahead.js) (by [Ivaylo Gochkov](https://github.com/igochkov)) -* [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)) -* [universal-analytics](https://github.com/peaksandpies/universal-analytics) (by [Bart van der Schoor](https://github.com/Bartvds)) -* [update-notifier](https://github.com/yeoman/update-notifier) (by [vvakame](https://github.com/vvakame)) -* [uri-templates](https://github.com/geraintluff/uri-templates) (by [Bart van der Schoor](https://github.com/Bartvds)) -* [urlrouter](https://github.com/fengmk2/urlrouter) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) -* [UUID.js](https://github.com/LiosK/UUID.js) (by [Jason Jarrett](https://github.com/staxmanade)) -* [Valerie](https://github.com/davewatts/valerie) (by [Howard Richards](https://github.com/conficient)) -* [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)) -* [websocket](https://github.com/Worlize/WebSocket-Node) (by [Paul Loyd](https://github.com/loyd)) -* [WinJS](http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx) (from TypeScript samples) -* [WinRT](http://msdn.microsoft.com/en-us/library/windows/apps/br211377.aspx) (from TypeScript samples) -* [ws](http://einaros.github.io/ws/) (by [Paul Loyd](https://github.com/loyd)) -* [XRegExp](http://xregexp.com/) (by [Bart van der Schoor](https://github.com/Bartvds)) -* [YouTube](https://developers.google.com/youtube/) (by [Daz Wilkin](https://github.com/DazWilkin/)) -* [YouTube Analytics API](https://developers.google.com/youtube/analytics/) (by [Frank M](https://github.com/sgtfrankieboy)) -* [YouTube Data API](https://developers.google.com/youtube/v3/) (by [Frank M](https://github.com/sgtfrankieboy/)) -* [Zepto.js](http://zeptojs.com/) (by [Josh Baldwin](https://github.com/jbaldwin)) -* [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)) +## List of definitions -Requested Definitions ---------------------- -Here is an updated list of [definitions people have requested](https://github.com/borisyankov/DefinitelyTyped/issues?labels=Definition%3ARequest) +* See [CONTRIBUTORS.md](CONTRIBUTORS.md) + +## Requested definitions + +Here is an updated list of [definitions people have requested](https://github.com/borisyankov/DefinitelyTyped/issues?labels=Definition%3ARequest). + +## Licence + +This project is licensed under the MIT license. + +Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file. + +[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) \ No newline at end of file diff --git a/_infrastructure/runner.js b/_infrastructure/runner.js new file mode 100644 index 0000000000..b9b9446ecf --- /dev/null +++ b/_infrastructure/runner.js @@ -0,0 +1 @@ +require('definition-tester'); diff --git a/_infrastructure/tests/_ref.d.ts b/_infrastructure/tests/_ref.d.ts deleted file mode 100644 index 5a0809f3b8..0000000000 --- a/_infrastructure/tests/_ref.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/_infrastructure/tests/compile-runner.bat b/_infrastructure/tests/compile-runner.bat deleted file mode 100644 index 49f737c5d2..0000000000 --- a/_infrastructure/tests/compile-runner.bat +++ /dev/null @@ -1 +0,0 @@ -tsc runner.ts --target ES5 --out runner.js --module commonjs --sourcemap diff --git a/_infrastructure/tests/runner.js b/_infrastructure/tests/runner.js deleted file mode 100644 index 171efe87dd..0000000000 --- a/_infrastructure/tests/runner.js +++ /dev/null @@ -1,1321 +0,0 @@ -var DT; -(function (DT) { - 'use strict'; - - var Promise = require('bluebird'); - var nodeExec = require('child_process').exec; - - var ExecResult = (function () { - function ExecResult() { - this.stdout = ''; - this.stderr = ''; - } - return ExecResult; - })(); - DT.ExecResult = ExecResult; - - function exec(filename, cmdLineArgs) { - return new Promise(function (resolve) { - var result = new ExecResult(); - result.exitCode = null; - - var cmdLine = filename + ' ' + cmdLineArgs.join(' '); - - nodeExec(cmdLine, { maxBuffer: 1 * 1024 * 1024 }, function (error, stdout, stderr) { - result.error = error; - result.stdout = stdout; - result.stderr = stderr; - result.exitCode = error ? error.code : 0; - resolve(result); - }); - }); - } - DT.exec = exec; -})(DT || (DT = {})); -/// -var DT; -(function (DT) { - 'use strict'; - - var path = require('path'); - - ///////////////////////////////// - // Given a document root + ts file pattern this class returns: - // all the TS files OR just tests OR just definition files - ///////////////////////////////// - var File = (function () { - function File(baseDir, filePathWithName) { - this.references = []; - // why choose? - this.baseDir = baseDir; - this.filePathWithName = filePathWithName; - this.ext = path.extname(this.filePathWithName); - this.file = path.basename(this.filePathWithName, this.ext); - this.dir = path.dirname(this.filePathWithName); - this.fullPath = path.join(this.baseDir, this.dir, this.file + this.ext); - // lock it (shallow) (needs `use strict` in each file to work) - // Object.freeze(this); - } - File.prototype.toString = function () { - return '[File ' + this.filePathWithName + ']'; - }; - return File; - })(); - DT.File = File; -})(DT || (DT = {})); -/// -/// -/// -var DT; -(function (DT) { - 'use strict'; - - var fs = require('fs'); - - var Promise = require('bluebird'); - - var Tsc = (function () { - function Tsc() { - } - Tsc.run = function (tsfile, options) { - var tscPath; - return new Promise.attempt(function () { - options = options || {}; - options.tscVersion = options.tscVersion || DT.DEFAULT_TSC_VERSION; - if (typeof options.checkNoImplicitAny === 'undefined') { - options.checkNoImplicitAny = true; - } - if (typeof options.useTscParams === 'undefined') { - options.useTscParams = true; - } - return DT.fileExists(tsfile); - }).then(function (exists) { - if (!exists) { - throw new Error(tsfile + ' not exists'); - } - tscPath = './_infrastructure/tests/typescript/' + options.tscVersion + '/tsc.js'; - return DT.fileExists(tscPath); - }).then(function (exists) { - if (!exists) { - throw new Error(tscPath + ' is not exists'); - } - return DT.fileExists(tsfile + '.tscparams'); - }).then(function (exists) { - var command = 'node ' + tscPath + ' --module commonjs '; - if (options.useTscParams && exists) { - command += '@' + tsfile + '.tscparams'; - } else if (options.checkNoImplicitAny) { - command += '--noImplicitAny'; - } - return DT.exec(command, [tsfile]); - }); - }; - return Tsc; - })(); - DT.Tsc = Tsc; -})(DT || (DT = {})); -/// -/// -var DT; -(function (DT) { - 'use strict'; - - ///////////////////////////////// - // Timer.start starts a timer - // Timer.end stops the timer and sets asString to the pretty print value - ///////////////////////////////// - var Timer = (function () { - function Timer() { - this.time = 0; - this.asString = ''; - } - Timer.prototype.start = function () { - this.time = 0; - this.startTime = this.now(); - this.asString = ''; - }; - - Timer.prototype.now = function () { - return Date.now(); - }; - - Timer.prototype.end = function () { - this.time = (this.now() - this.startTime) / 1000; - this.asString = Timer.prettyDate(this.startTime, this.now()); - }; - - Timer.prettyDate = function (date1, date2) { - var diff = ((date2 - date1) / 1000); - var day_diff = Math.floor(diff / 86400); - - if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) { - return null; - } - - return (day_diff == 0 && (diff < 60 && (diff + ' seconds') || diff < 120 && '1 minute' || diff < 3600 && Math.floor(diff / 60) + ' minutes' || diff < 7200 && '1 hour' || diff < 86400 && Math.floor(diff / 3600) + ' hours') || day_diff == 1 && 'Yesterday' || day_diff < 7 && day_diff + ' days' || day_diff < 31 && Math.ceil(day_diff / 7) + ' weeks'); - }; - return Timer; - })(); - DT.Timer = Timer; -})(DT || (DT = {})); -/// -var DT; -(function (DT) { - 'use strict'; - - var fs = require('fs'); - var Lazy = require('lazy.js'); - var Promise = require('bluebird'); - - var referenceTagExp = //g; - - function endsWith(str, suffix) { - return str.indexOf(suffix, str.length - suffix.length) !== -1; - } - DT.endsWith = endsWith; - - function extractReferenceTags(source) { - var ret = []; - var match; - - if (!referenceTagExp.global) { - throw new Error('referenceTagExp RegExp must have global flag'); - } - referenceTagExp.lastIndex = 0; - - while ((match = referenceTagExp.exec(source))) { - if (match.length > 0 && match[1].length > 0) { - ret.push(match[1]); - } - } - return ret; - } - DT.extractReferenceTags = extractReferenceTags; - - function fileExists(target) { - return new Promise(function (resolve, reject) { - fs.exists(target, function (bool) { - resolve(bool); - }); - }); - } - DT.fileExists = fileExists; -})(DT || (DT = {})); -/// -/// -/// -var DT; -(function (DT) { - 'use strict'; - - var fs = require('fs'); - var path = require('path'); - var glob = require('glob'); - var Lazy = require('lazy.js'); - var Promise = require('bluebird'); - - var readFile = Promise.promisify(fs.readFile); - - ///////////////////////////////// - // Track all files in the repo: map full path to File objects - ///////////////////////////////// - var FileIndex = (function () { - function FileIndex(runner, options) { - this.runner = runner; - this.options = options; - } - FileIndex.prototype.hasFile = function (target) { - return target in this.fileMap; - }; - - FileIndex.prototype.getFile = function (target) { - if (target in this.fileMap) { - return this.fileMap[target]; - } - return null; - }; - - FileIndex.prototype.setFile = function (file) { - if (file.fullPath in this.fileMap) { - throw new Error('cannot overwrite file'); - } - this.fileMap[file.fullPath] = file; - }; - - FileIndex.prototype.readIndex = function () { - var _this = this; - this.fileMap = Object.create(null); - - return Promise.promisify(glob).call(glob, '**/*.ts', { - cwd: this.runner.dtPath - }).then(function (filesNames) { - _this.files = Lazy(filesNames).filter(function (fileName) { - return _this.runner.checkAcceptFile(fileName); - }).map(function (fileName) { - var file = new DT.File(_this.runner.dtPath, fileName); - _this.fileMap[file.fullPath] = file; - return file; - }).toArray(); - }); - }; - - FileIndex.prototype.collectDiff = function (changes) { - var _this = this; - return new Promise(function (resolve) { - // filter changes and bake map for easy lookup - _this.changed = Object.create(null); - _this.removed = Object.create(null); - - Lazy(changes).filter(function (full) { - return _this.runner.checkAcceptFile(full); - }).uniq().each(function (local) { - var full = path.resolve(_this.runner.dtPath, local); - var file = _this.getFile(full); - if (!file) { - // TODO figure out what to do here - // what does it mean? deleted?ss - file = new DT.File(_this.runner.dtPath, local); - _this.setFile(file); - _this.removed[full] = file; - // console.log('not in index? %', file.fullPath); - } else { - _this.changed[full] = file; - } - }); - - // console.log('changed:\n' + Object.keys(this.changed).join('\n')); - // console.log('removed:\n' + Object.keys(this.removed).join('\n')); - resolve(); - }); - }; - - FileIndex.prototype.parseFiles = function () { - var _this = this; - return this.loadReferences(this.files).then(function () { - return _this.getMissingReferences(); - }); - }; - - FileIndex.prototype.getMissingReferences = function () { - var _this = this; - return Promise.attempt(function () { - _this.missing = Object.create(null); - Lazy(_this.removed).keys().each(function (removed) { - if (removed in _this.refMap) { - _this.missing[removed] = _this.refMap[removed]; - } - }); - }); - }; - - FileIndex.prototype.loadReferences = function (files) { - var _this = this; - return new Promise(function (resolve, reject) { - var queue = files.slice(0); - var active = []; - var max = 50; - var next = function () { - if (queue.length === 0 && active.length === 0) { - resolve(); - return; - } - - while (queue.length > 0 && active.length < max) { - var file = queue.pop(); - active.push(file); - _this.parseFile(file).then(function (file) { - active.splice(active.indexOf(file), 1); - next(); - }).catch(function (err) { - queue = []; - active = []; - reject(err); - }); - } - }; - next(); - }).then(function () { - // bake reverse reference map (referenced to referrers) - _this.refMap = Object.create(null); - - Lazy(files).each(function (file) { - Lazy(file.references).each(function (ref) { - if (ref.fullPath in _this.refMap) { - _this.refMap[ref.fullPath].push(file); - } else { - _this.refMap[ref.fullPath] = [file]; - } - }); - }); - }); - }; - - // TODO replace with a stream? - FileIndex.prototype.parseFile = function (file) { - var _this = this; - return readFile(file.filePathWithName, { - encoding: 'utf8', - flag: 'r' - }).then(function (content) { - file.references = Lazy(DT.extractReferenceTags(content)).map(function (ref) { - return path.resolve(path.dirname(file.fullPath), ref); - }).reduce(function (memo, ref) { - if (ref in _this.fileMap) { - memo.push(_this.fileMap[ref]); - } else { - console.log('not mapped? -> ' + ref); - } - return memo; - }, []); - - // return the object - return file; - }); - }; - - FileIndex.prototype.collectTargets = function () { - var _this = this; - return new Promise(function (resolve) { - // map out files linked to changes - // - queue holds files touched by a change - // - pre-fill with actually changed files - // - loop queue, if current not seen: - // - add to result - // - from refMap queue all files referring to current - var result = Object.create(null); - var queue = Lazy(_this.changed).values().toArray(); - - while (queue.length > 0) { - var next = queue.shift(); - var fp = next.fullPath; - if (result[fp]) { - continue; - } - result[fp] = next; - if (fp in _this.refMap) { - var arr = _this.refMap[fp]; - for (var i = 0, ii = arr.length; i < ii; i++) { - // just add it and skip expensive checks - queue.push(arr[i]); - } - } - } - resolve(Lazy(result).values().toArray()); - }); - }; - return FileIndex; - })(); - DT.FileIndex = FileIndex; -})(DT || (DT = {})); -/// -/// -var DT; -(function (DT) { - 'use strict'; - - var fs = require('fs'); - var path = require('path'); - var Git = require('git-wrapper'); - var Promise = require('bluebird'); - - var GitChanges = (function () { - function GitChanges(runner) { - this.runner = runner; - this.options = {}; - var dir = path.join(this.runner.dtPath, '.git'); - if (!fs.existsSync(dir)) { - throw new Error('cannot locate git-dir: ' + dir); - } - this.options['git-dir'] = dir; - - this.git = new Git(this.options); - this.git.exec = Promise.promisify(this.git.exec); - } - GitChanges.prototype.readChanges = function () { - var opts = {}; - var args = ['--name-only HEAD~1']; - return this.git.exec('diff', opts, args).then(function (msg) { - return msg.replace(/^\s+/, '').replace(/\s+$/, '').split(/\r?\n/g); - }); - }; - return GitChanges; - })(); - DT.GitChanges = GitChanges; -})(DT || (DT = {})); -/// -/// -var DT; -(function (DT) { - var os = require('os'); - - ///////////////////////////////// - // All the common things that we print are functions of this class - ///////////////////////////////// - var Print = (function () { - function Print(version) { - this.version = version; - this.WIDTH = 77; - } - Print.prototype.init = function (typings, tests, tsFiles) { - this.typings = typings; - this.tests = tests; - this.tsFiles = tsFiles; - }; - - Print.prototype.out = function (s) { - process.stdout.write(s); - return this; - }; - - Print.prototype.repeat = function (s, times) { - return new Array(times + 1).join(s); - }; - - Print.prototype.printChangeHeader = function () { - this.out('=============================================================================\n'); - this.out(' \33[36m\33[1mDefinitelyTyped Diff Detector 0.1.0\33[0m \n'); - this.out('=============================================================================\n'); - }; - - Print.prototype.printHeader = function (options) { - var totalMem = Math.round(os.totalmem() / 1024 / 1024) + ' mb'; - var freemem = Math.round(os.freemem() / 1024 / 1024) + ' mb'; - - this.out('=============================================================================\n'); - this.out(' \33[36m\33[1mDefinitelyTyped Test Runner 0.5.0\33[0m\n'); - this.out('=============================================================================\n'); - this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n'); - this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n'); - this.out(' \33[36m\33[1mTests :\33[0m ' + this.tests + '\n'); - this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n'); - this.out(' \33[36m\33[1mTotal Memory :\33[0m ' + totalMem + '\n'); - this.out(' \33[36m\33[1mFree Memory :\33[0m ' + freemem + '\n'); - this.out(' \33[36m\33[1mCores :\33[0m ' + os.cpus().length + '\n'); - this.out(' \33[36m\33[1mConcurrent :\33[0m ' + options.concurrent + '\n'); - }; - - Print.prototype.printSuiteHeader = function (title) { - var left = Math.floor((this.WIDTH - title.length) / 2) - 1; - var right = Math.ceil((this.WIDTH - title.length) / 2) - 1; - this.out(this.repeat('=', left)).out(' \33[34m\33[1m'); - this.out(title); - this.out('\33[0m ').out(this.repeat('=', right)).printBreak(); - }; - - Print.prototype.printDiv = function () { - this.out('-----------------------------------------------------------------------------\n'); - }; - - Print.prototype.printBoldDiv = function () { - this.out('=============================================================================\n'); - }; - - Print.prototype.printErrorsHeader = function () { - this.out('=============================================================================\n'); - this.out(' \33[34m\33[1mErrors in files\33[0m \n'); - this.out('=============================================================================\n'); - }; - - Print.prototype.printErrorsForFile = function (testResult) { - this.out('----------------- For file:' + testResult.targetFile.filePathWithName); - this.printBreak().out(testResult.stderr).printBreak(); - }; - - Print.prototype.printBreak = function () { - this.out('\n'); - return this; - }; - - Print.prototype.clearCurrentLine = function () { - this.out('\r\33[K'); - return this; - }; - - Print.prototype.printSuccessCount = function (current, total) { - var arb = (total === 0) ? 0 : (current / total); - this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - }; - - Print.prototype.printFailedCount = function (current, total) { - var arb = (total === 0) ? 0 : (current / total); - this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - }; - - Print.prototype.printTypingsWithoutTestsMessage = function () { - this.out(' \33[36m\33[1mTyping without tests\33[0m\n'); - }; - - Print.prototype.printTotalMessage = function () { - this.out(' \33[36m\33[1mTotal\33[0m\n'); - }; - - Print.prototype.printElapsedTime = function (time, s) { - this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n'); - }; - - Print.prototype.printSuiteErrorCount = function (errorHeadline, current, total, warn) { - if (typeof warn === "undefined") { warn = false; } - var arb = (total === 0) ? 0 : (current / total); - this.out(' \33[36m\33[1m').out(errorHeadline).out(this.repeat(' ', 16 - errorHeadline.length)); - if (warn) { - this.out(': \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - } else { - this.out(': \33[33m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - } - }; - - Print.prototype.printSubHeader = function (file) { - this.out(' \33[36m\33[1m' + file + '\33[0m\n'); - }; - - Print.prototype.printWarnCode = function (str) { - this.out(' \33[31m\33[1m<' + str.toLowerCase().replace(/ +/g, '-') + '>\33[0m\n'); - }; - - Print.prototype.printLine = function (file) { - this.out(file + '\n'); - }; - - Print.prototype.printElement = function (file) { - this.out(' - ' + file + '\n'); - }; - - Print.prototype.printElement2 = function (file) { - this.out(' - ' + file + '\n'); - }; - - Print.prototype.printTypingsWithoutTestName = function (file) { - this.out(' - \33[33m\33[1m' + file + '\33[0m\n'); - }; - - Print.prototype.printTypingsWithoutTest = function (withoutTestTypings) { - var _this = this; - if (withoutTestTypings.length > 0) { - this.printTypingsWithoutTestsMessage(); - - this.printDiv(); - withoutTestTypings.forEach(function (t) { - _this.printTypingsWithoutTestName(t); - }); - } - }; - - Print.prototype.printTestComplete = function (testResult) { - var reporter = testResult.hostedBy.testReporter; - if (testResult.success) { - reporter.printPositiveCharacter(testResult); - } else { - reporter.printNegativeCharacter(testResult); - } - }; - - Print.prototype.printSuiteComplete = function (suite) { - this.printBreak(); - - this.printDiv(); - this.printElapsedTime(suite.timer.asString, suite.timer.time); - this.printSuccessCount(suite.okTests.length, suite.testResults.length); - this.printFailedCount(suite.ngTests.length, suite.testResults.length); - }; - - Print.prototype.printTests = function (adding) { - var _this = this; - this.printDiv(); - this.printSubHeader('Testing'); - this.printDiv(); - - Object.keys(adding).sort().map(function (src) { - _this.printLine(adding[src].filePathWithName); - return adding[src]; - }); - }; - - Print.prototype.printQueue = function (files) { - var _this = this; - this.printDiv(); - this.printSubHeader('Queued for testing'); - this.printDiv(); - - files.forEach(function (file) { - _this.printLine(file.filePathWithName); - }); - }; - - Print.prototype.printTestAll = function () { - this.printDiv(); - this.printSubHeader('Ignoring changes, testing all files'); - }; - - Print.prototype.printFiles = function (files) { - var _this = this; - this.printDiv(); - this.printSubHeader('Files'); - this.printDiv(); - - files.forEach(function (file) { - _this.printLine(file.filePathWithName); - file.references.forEach(function (file) { - _this.printElement(file.filePathWithName); - }); - }); - }; - - Print.prototype.printMissing = function (index, refMap) { - var _this = this; - this.printDiv(); - this.printSubHeader('Missing references'); - this.printDiv(); - - Object.keys(refMap).sort().forEach(function (src) { - var ref = index.getFile(src); - _this.printLine('\33[31m\33[1m' + ref.filePathWithName + '\33[0m'); - refMap[src].forEach(function (file) { - _this.printElement(file.filePathWithName); - }); - }); - }; - - Print.prototype.printAllChanges = function (paths) { - var _this = this; - this.printSubHeader('All changes'); - this.printDiv(); - - paths.sort().forEach(function (line) { - _this.printLine(line); - }); - }; - - Print.prototype.printRelChanges = function (changeMap) { - var _this = this; - this.printDiv(); - this.printSubHeader('Interesting files'); - this.printDiv(); - - Object.keys(changeMap).sort().forEach(function (src) { - _this.printLine(changeMap[src].filePathWithName); - }); - }; - - Print.prototype.printRemovals = function (changeMap) { - var _this = this; - this.printDiv(); - this.printSubHeader('Removed files'); - this.printDiv(); - - Object.keys(changeMap).sort().forEach(function (src) { - _this.printLine(changeMap[src].filePathWithName); - }); - }; - - Print.prototype.printRefMap = function (index, refMap) { - var _this = this; - this.printDiv(); - this.printSubHeader('Referring'); - this.printDiv(); - - Object.keys(refMap).sort().forEach(function (src) { - var ref = index.getFile(src); - _this.printLine(ref.filePathWithName); - refMap[src].forEach(function (file) { - _this.printLine(' - ' + file.filePathWithName); - }); - }); - }; - return Print; - })(); - DT.Print = Print; -})(DT || (DT = {})); -/// -/// -var DT; -(function (DT) { - - - ///////////////////////////////// - // Default test reporter - ///////////////////////////////// - var DefaultTestReporter = (function () { - function DefaultTestReporter(print) { - this.print = print; - this.index = 0; - } - DefaultTestReporter.prototype.printPositiveCharacter = function (testResult) { - this.print.out('\33[36m\33[1m' + '.' + '\33[0m'); - this.index++; - this.printBreakIfNeeded(this.index); - }; - - DefaultTestReporter.prototype.printNegativeCharacter = function (testResult) { - this.print.out('x'); - this.index++; - this.printBreakIfNeeded(this.index); - }; - - DefaultTestReporter.prototype.printBreakIfNeeded = function (index) { - if (index % this.print.WIDTH === 0) { - this.print.printBreak(); - } - }; - return DefaultTestReporter; - })(); - DT.DefaultTestReporter = DefaultTestReporter; -})(DT || (DT = {})); -/// -var DT; -(function (DT) { - 'use strict'; - - var Promise = require('bluebird'); - - - - ///////////////////////////////// - // Base class for test suite - ///////////////////////////////// - var TestSuiteBase = (function () { - function TestSuiteBase(options, testSuiteName, errorHeadline) { - this.options = options; - this.testSuiteName = testSuiteName; - this.errorHeadline = errorHeadline; - this.timer = new DT.Timer(); - this.testResults = []; - this.printErrorCount = true; - this.queue = new DT.TestQueue(options.concurrent); - } - TestSuiteBase.prototype.filterTargetFiles = function (files) { - throw new Error('please implement this method'); - }; - - TestSuiteBase.prototype.start = function (targetFiles, testCallback) { - var _this = this; - this.timer.start(); - - return this.filterTargetFiles(targetFiles).then(function (targetFiles) { - // tests get queued for multi-threading - return Promise.all(targetFiles.map(function (targetFile) { - return _this.runTest(targetFile).then(function (result) { - testCallback(result); - }); - })); - }).then(function () { - _this.timer.end(); - return _this; - }); - }; - - TestSuiteBase.prototype.runTest = function (targetFile) { - var _this = this; - return this.queue.run(new DT.Test(this, targetFile, { - tscVersion: this.options.tscVersion - })).then(function (result) { - _this.testResults.push(result); - return result; - }); - }; - - Object.defineProperty(TestSuiteBase.prototype, "okTests", { - get: function () { - return this.testResults.filter(function (r) { - return r.success; - }); - }, - enumerable: true, - configurable: true - }); - - Object.defineProperty(TestSuiteBase.prototype, "ngTests", { - get: function () { - return this.testResults.filter(function (r) { - return !r.success; - }); - }, - enumerable: true, - configurable: true - }); - return TestSuiteBase; - })(); - DT.TestSuiteBase = TestSuiteBase; -})(DT || (DT = {})); -/// -/// -var __extends = this.__extends || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); -}; -var DT; -(function (DT) { - 'use strict'; - - var Promise = require('bluebird'); - - var endDts = /\w\.d\.ts$/i; - - ///////////////////////////////// - // .d.ts syntax inspection - ///////////////////////////////// - var SyntaxChecking = (function (_super) { - __extends(SyntaxChecking, _super); - function SyntaxChecking(options) { - _super.call(this, options, 'Syntax checking', 'Syntax error'); - } - SyntaxChecking.prototype.filterTargetFiles = function (files) { - return Promise.cast(files.filter(function (file) { - return endDts.test(file.filePathWithName); - })); - }; - return SyntaxChecking; - })(DT.TestSuiteBase); - DT.SyntaxChecking = SyntaxChecking; -})(DT || (DT = {})); -/// -/// -var DT; -(function (DT) { - 'use strict'; - - var Promise = require('bluebird'); - - var endTestDts = /\w-tests?\.ts$/i; - - ///////////////////////////////// - // Compile with *-tests.ts - ///////////////////////////////// - var TestEval = (function (_super) { - __extends(TestEval, _super); - function TestEval(options) { - _super.call(this, options, 'Typing tests', 'Failed tests'); - } - TestEval.prototype.filterTargetFiles = function (files) { - return Promise.cast(files.filter(function (file) { - return endTestDts.test(file.filePathWithName); - })); - }; - return TestEval; - })(DT.TestSuiteBase); - DT.TestEval = TestEval; -})(DT || (DT = {})); -/// -/// -var DT; -(function (DT) { - 'use strict'; - - var fs = require('fs'); - var Promise = require('bluebird'); - - ///////////////////////////////// - // Try compile without .tscparams - // It may indicate that it is compatible with --noImplicitAny maybe... - ///////////////////////////////// - var FindNotRequiredTscparams = (function (_super) { - __extends(FindNotRequiredTscparams, _super); - function FindNotRequiredTscparams(options, print) { - var _this = this; - _super.call(this, options, 'Find not required .tscparams files', 'New arrival!'); - this.print = print; - this.printErrorCount = false; - - this.testReporter = { - printPositiveCharacter: function (testResult) { - _this.print.clearCurrentLine().printTypingsWithoutTestName(testResult.targetFile.filePathWithName); - }, - printNegativeCharacter: function (testResult) { - } - }; - } - FindNotRequiredTscparams.prototype.filterTargetFiles = function (files) { - return Promise.filter(files, function (file) { - return new Promise(function (resolve) { - fs.exists(file.filePathWithName + '.tscparams', resolve); - }); - }); - }; - - FindNotRequiredTscparams.prototype.runTest = function (targetFile) { - var _this = this; - this.print.clearCurrentLine().out(targetFile.filePathWithName); - - return this.queue.run(new DT.Test(this, targetFile, { - tscVersion: this.options.tscVersion, - useTscParams: false, - checkNoImplicitAny: true - })).then(function (result) { - _this.testResults.push(result); - _this.print.clearCurrentLine(); - return result; - }); - }; - - Object.defineProperty(FindNotRequiredTscparams.prototype, "ngTests", { - get: function () { - // Do not show ng test results - return []; - }, - enumerable: true, - configurable: true - }); - return FindNotRequiredTscparams; - })(DT.TestSuiteBase); - DT.FindNotRequiredTscparams = FindNotRequiredTscparams; -})(DT || (DT = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -var DT; -(function (DT) { - require('source-map-support').install(); - - // hacky typing - var Lazy = require('lazy.js'); - var Promise = require('bluebird'); - - var os = require('os'); - var fs = require('fs'); - var path = require('path'); - var assert = require('assert'); - - var tsExp = /\.ts$/; - - DT.DEFAULT_TSC_VERSION = '0.9.7'; - - ///////////////////////////////// - // Single test - ///////////////////////////////// - var Test = (function () { - function Test(suite, tsfile, options) { - this.suite = suite; - this.tsfile = tsfile; - this.options = options; - } - Test.prototype.run = function () { - var _this = this; - return DT.Tsc.run(this.tsfile.filePathWithName, this.options).then(function (execResult) { - var testResult = new TestResult(); - testResult.hostedBy = _this.suite; - testResult.targetFile = _this.tsfile; - testResult.options = _this.options; - - testResult.stdout = execResult.stdout; - testResult.stderr = execResult.stderr; - testResult.exitCode = execResult.exitCode; - - return testResult; - }); - }; - return Test; - })(); - DT.Test = Test; - - ///////////////////////////////// - // Parallel execute Tests - ///////////////////////////////// - var TestQueue = (function () { - function TestQueue(concurrent) { - this.queue = []; - this.active = []; - this.concurrent = Math.max(1, concurrent); - } - // add to queue and return a promise - TestQueue.prototype.run = function (test) { - var _this = this; - var defer = Promise.defer(); - - // add a closure to queue - this.queue.push(function () { - // run it - var p = test.run(); - p.then(defer.resolve.bind(defer), defer.reject.bind(defer)); - p.finally(function () { - var i = _this.active.indexOf(test); - if (i > -1) { - _this.active.splice(i, 1); - } - _this.step(); - }); - - // return it - return test; - }); - this.step(); - - // defer it - return defer.promise; - }; - - TestQueue.prototype.step = function () { - while (this.queue.length > 0 && this.active.length < this.concurrent) { - this.active.push(this.queue.pop().call(null)); - } - }; - return TestQueue; - })(); - DT.TestQueue = TestQueue; - - ///////////////////////////////// - // Test results - ///////////////////////////////// - var TestResult = (function () { - function TestResult() { - } - Object.defineProperty(TestResult.prototype, "success", { - get: function () { - return this.exitCode === 0; - }, - enumerable: true, - configurable: true - }); - return TestResult; - })(); - DT.TestResult = TestResult; - - ///////////////////////////////// - // The main class to kick things off - ///////////////////////////////// - var TestRunner = (function () { - function TestRunner(dtPath, options) { - if (typeof options === "undefined") { options = { tscVersion: DT.DEFAULT_TSC_VERSION }; } - this.dtPath = dtPath; - this.options = options; - this.suites = []; - this.options.findNotRequiredTscparams = !!this.options.findNotRequiredTscparams; - - this.index = new DT.FileIndex(this, this.options); - this.changes = new DT.GitChanges(this); - - this.print = new DT.Print(this.options.tscVersion); - } - TestRunner.prototype.addSuite = function (suite) { - this.suites.push(suite); - }; - - TestRunner.prototype.checkAcceptFile = function (fileName) { - var ok = tsExp.test(fileName); - ok = ok && fileName.indexOf('_infrastructure') < 0; - ok = ok && fileName.indexOf('node_modules/') < 0; - ok = ok && /^[a-z]/i.test(fileName); - return ok; - }; - - TestRunner.prototype.run = function () { - var _this = this; - this.timer = new DT.Timer(); - this.timer.start(); - - this.print.printChangeHeader(); - - // only includes .d.ts or -tests.ts or -test.ts or .ts - return this.index.readIndex().then(function () { - return _this.changes.readChanges(); - }).then(function (changes) { - _this.print.printAllChanges(changes); - return _this.index.collectDiff(changes); - }).then(function () { - _this.print.printRemovals(_this.index.removed); - _this.print.printRelChanges(_this.index.changed); - return _this.index.parseFiles(); - }).then(function () { - if (_this.options.printRefMap) { - _this.print.printRefMap(_this.index, _this.index.refMap); - } - if (Lazy(_this.index.missing).some(function (arr) { - return arr.length > 0; - })) { - _this.print.printMissing(_this.index, _this.index.missing); - _this.print.printBoldDiv(); - - // bail - return Promise.cast(false); - } - if (_this.options.printFiles) { - _this.print.printFiles(_this.index.files); - } - return _this.index.collectTargets().then(function (files) { - if (_this.options.testChanges) { - _this.print.printQueue(files); - return _this.runTests(files); - } else { - _this.print.printTestAll(); - return _this.runTests(_this.index.files); - } - }).then(function () { - return !_this.suites.some(function (suite) { - return suite.ngTests.length !== 0; - }); - }); - }); - }; - - TestRunner.prototype.runTests = function (files) { - var _this = this; - return Promise.attempt(function () { - assert(Array.isArray(files), 'files must be array'); - - var syntaxChecking = new DT.SyntaxChecking(_this.options); - var testEval = new DT.TestEval(_this.options); - - if (!_this.options.findNotRequiredTscparams) { - _this.addSuite(syntaxChecking); - _this.addSuite(testEval); - } - - return Promise.all([ - syntaxChecking.filterTargetFiles(files), - testEval.filterTargetFiles(files) - ]); - }).spread(function (syntaxFiles, testFiles) { - _this.print.init(syntaxFiles.length, testFiles.length, files.length); - _this.print.printHeader(_this.options); - - if (_this.options.findNotRequiredTscparams) { - _this.addSuite(new DT.FindNotRequiredTscparams(_this.options, _this.print)); - } - - return Promise.reduce(_this.suites, function (count, suite) { - suite.testReporter = suite.testReporter || new DT.DefaultTestReporter(_this.print); - - _this.print.printSuiteHeader(suite.testSuiteName); - - if (_this.options.skipTests) { - _this.print.printWarnCode('skipped test'); - return Promise.cast(count++); - } - - return suite.start(files, function (testResult) { - _this.print.printTestComplete(testResult); - }).then(function (suite) { - _this.print.printSuiteComplete(suite); - return count++; - }); - }, 0); - }).then(function (count) { - _this.timer.end(); - _this.finaliseTests(files); - }); - }; - - TestRunner.prototype.finaliseTests = function (files) { - var _this = this; - var testEval = Lazy(this.suites).filter(function (suite) { - return suite instanceof DT.TestEval; - }).first(); - - if (testEval) { - var existsTestTypings = Lazy(testEval.testResults).map(function (testResult) { - return testResult.targetFile.dir; - }).reduce(function (a, b) { - return a.indexOf(b) < 0 ? a.concat([b]) : a; - }, []); - - var typings = Lazy(files).map(function (file) { - return file.dir; - }).reduce(function (a, b) { - return a.indexOf(b) < 0 ? a.concat([b]) : a; - }, []); - - var withoutTestTypings = typings.filter(function (typing) { - return existsTestTypings.indexOf(typing) < 0; - }); - - this.print.printDiv(); - this.print.printTypingsWithoutTest(withoutTestTypings); - } - - this.print.printDiv(); - this.print.printTotalMessage(); - - this.print.printDiv(); - this.print.printElapsedTime(this.timer.asString, this.timer.time); - - this.suites.filter(function (suite) { - return suite.printErrorCount; - }).forEach(function (suite) { - _this.print.printSuiteErrorCount(suite.errorHeadline, suite.ngTests.length, suite.testResults.length); - }); - if (testEval) { - this.print.printSuiteErrorCount('Without tests', withoutTestTypings.length, typings.length, true); - } - - this.print.printDiv(); - - if (this.suites.some(function (suite) { - return suite.ngTests.length !== 0; - })) { - this.print.printErrorsHeader(); - - this.suites.filter(function (suite) { - return suite.ngTests.length !== 0; - }).forEach(function (suite) { - suite.ngTests.forEach(function (testResult) { - _this.print.printErrorsForFile(testResult); - }); - _this.print.printBoldDiv(); - }); - } - }; - return TestRunner; - })(); - DT.TestRunner = TestRunner; - - var optimist = require('optimist')(process.argv); - optimist.default('try-without-tscparams', false); - optimist.default('single-thread', false); - optimist.default('tsc-version', DT.DEFAULT_TSC_VERSION); - - optimist.default('test-changes', false); - optimist.default('skip-tests', false); - optimist.default('print-files', false); - optimist.default('print-refmap', false); - - optimist.boolean('help'); - optimist.describe('help', 'print help'); - optimist.alias('h', 'help'); - - var argv = optimist.argv; - - var dtPath = path.resolve(path.dirname((module).filename), '..', '..'); - var cpuCores = os.cpus().length; - - if (argv.help) { - optimist.showHelp(); - var pkg = require('../../package.json'); - console.log('Scripts:'); - console.log(''); - Lazy(pkg.scripts).keys().each(function (key) { - console.log(' $ npm run ' + key); - }); - process.exit(0); - } - - var testFull = process.env['TRAVIS_BRANCH'] ? /\w\/full$/.test(process.env['TRAVIS_BRANCH']) : false; - - new TestRunner(dtPath, { - concurrent: argv['single-thread'] ? 1 : Math.max(Math.min(24, cpuCores), 2), - tscVersion: argv['tsc-version'], - testChanges: testFull ? false : argv['test-changes'], - skipTests: argv['skip-tests'], - printFiles: argv['print-files'], - printRefMap: argv['print-refmap'], - findNotRequiredTscparams: argv['try-without-tscparam'] - }).run().then(function (success) { - if (!success) { - process.exit(1); - } - }).catch(function (err) { - throw err; - process.exit(2); - }); -})(DT || (DT = {})); -//# sourceMappingURL=runner.js.map diff --git a/_infrastructure/tests/runner.ts b/_infrastructure/tests/runner.ts deleted file mode 100644 index 1f75aca7a8..0000000000 --- a/_infrastructure/tests/runner.ts +++ /dev/null @@ -1,367 +0,0 @@ -/// - -/// - -/// -/// -/// -/// - -/// -/// - -/// -/// - -/// -/// -/// -/// - -module DT { - require('source-map-support').install(); - - // hacky typing - var Lazy: LazyJS.LazyStatic = require('lazy.js'); - var Promise: typeof Promise = require('bluebird'); - - var os = require('os'); - var fs = require('fs'); - var path = require('path'); - var assert = require('assert'); - - var tsExp = /\.ts$/; - - export var DEFAULT_TSC_VERSION = '0.9.7'; - - interface PackageJSON { - scripts: {[key:string]: string}; - } - - ///////////////////////////////// - // Single test - ///////////////////////////////// - export class Test { - constructor(public suite: ITestSuite, public tsfile: File, public options?: TscExecOptions) { - } - - public run(): Promise { - return Tsc.run(this.tsfile.filePathWithName, this.options).then((execResult: ExecResult) => { - var testResult = new TestResult(); - testResult.hostedBy = this.suite; - testResult.targetFile = this.tsfile; - testResult.options = this.options; - - testResult.stdout = execResult.stdout; - testResult.stderr = execResult.stderr; - testResult.exitCode = execResult.exitCode; - - return testResult; - }); - } - } - - ///////////////////////////////// - // Parallel execute Tests - ///////////////////////////////// - export class TestQueue { - - private queue: Function[] = []; - private active: Test[] = []; - private concurrent: number; - - constructor(concurrent: number) { - this.concurrent = Math.max(1, concurrent); - } - - // add to queue and return a promise - run(test: Test): Promise { - var defer = Promise.defer(); - // add a closure to queue - this.queue.push(() => { - // run it - var p = test.run(); - p.then(defer.resolve.bind(defer), defer.reject.bind(defer)); - p.finally(() => { - var i = this.active.indexOf(test); - if (i > -1) { - this.active.splice(i, 1); - } - this.step(); - }); - // return it - return test; - }); - this.step(); - // defer it - return defer.promise; - } - - private step(): void { - while (this.queue.length > 0 && this.active.length < this.concurrent) { - this.active.push(this.queue.pop().call(null)); - } - } - } - - ///////////////////////////////// - // Test results - ///////////////////////////////// - export class TestResult { - hostedBy: ITestSuite; - targetFile: File; - options: TscExecOptions; - - stdout: string; - stderr: string; - exitCode: number; - - public get success(): boolean { - return this.exitCode === 0; - } - } - - export interface ITestRunnerOptions { - tscVersion:string; - concurrent?:number; - testChanges?:boolean; - skipTests?:boolean; - printFiles?:boolean; - printRefMap?:boolean; - findNotRequiredTscparams?:boolean; - } - - ///////////////////////////////// - // The main class to kick things off - ///////////////////////////////// - export class TestRunner { - private timer: Timer; - private suites: ITestSuite[] = []; - - public changes: GitChanges; - public index: FileIndex; - public print: Print; - - constructor(public dtPath: string, public options: ITestRunnerOptions = {tscVersion: DT.DEFAULT_TSC_VERSION}) { - this.options.findNotRequiredTscparams = !!this.options.findNotRequiredTscparams; - - this.index = new FileIndex(this, this.options); - this.changes = new GitChanges(this); - - this.print = new Print(this.options.tscVersion); - } - - public addSuite(suite: ITestSuite): void { - this.suites.push(suite); - } - - public checkAcceptFile(fileName: string): boolean { - var ok = tsExp.test(fileName); - ok = ok && fileName.indexOf('_infrastructure') < 0; - ok = ok && fileName.indexOf('node_modules/') < 0; - ok = ok && /^[a-z]/i.test(fileName); - return ok; - } - - public run(): Promise { - this.timer = new Timer(); - this.timer.start(); - - this.print.printChangeHeader(); - - // only includes .d.ts or -tests.ts or -test.ts or .ts - return this.index.readIndex().then(() => { - return this.changes.readChanges(); - }).then((changes: string[]) => { - this.print.printAllChanges(changes); - return this.index.collectDiff(changes); - }).then(() => { - this.print.printRemovals(this.index.removed); - this.print.printRelChanges(this.index.changed); - return this.index.parseFiles(); - }).then(() => { - if (this.options.printRefMap) { - this.print.printRefMap(this.index, this.index.refMap); - } - if (Lazy(this.index.missing).some((arr: any[]) => arr.length > 0)) { - this.print.printMissing(this.index, this.index.missing); - this.print.printBoldDiv(); - // bail - return Promise.cast(false); - } - if (this.options.printFiles) { - this.print.printFiles(this.index.files); - } - return this.index.collectTargets().then((files) => { - if (this.options.testChanges) { - this.print.printQueue(files); - return this.runTests(files); - } - else { - this.print.printTestAll(); - return this.runTests(this.index.files) - } - }).then(() => { - return !this.suites.some((suite) => { - return suite.ngTests.length !== 0 - }); - }); - }); - } - - private runTests(files: File[]): Promise { - return Promise.attempt(() => { - assert(Array.isArray(files), 'files must be array'); - - var syntaxChecking = new SyntaxChecking(this.options); - var testEval = new TestEval(this.options); - - if (!this.options.findNotRequiredTscparams) { - this.addSuite(syntaxChecking); - this.addSuite(testEval); - } - - return Promise.all([ - syntaxChecking.filterTargetFiles(files), - testEval.filterTargetFiles(files) - ]); - }).spread((syntaxFiles, testFiles) => { - this.print.init(syntaxFiles.length, testFiles.length, files.length); - this.print.printHeader(this.options); - - if (this.options.findNotRequiredTscparams) { - this.addSuite(new FindNotRequiredTscparams(this.options, this.print)); - } - - return Promise.reduce(this.suites, (count, suite: ITestSuite) => { - suite.testReporter = suite.testReporter || new DefaultTestReporter(this.print); - - this.print.printSuiteHeader(suite.testSuiteName); - - if (this.options.skipTests) { - this.print.printWarnCode('skipped test'); - return Promise.cast(count++); - } - - return suite.start(files, (testResult) => { - this.print.printTestComplete(testResult); - }).then((suite) => { - this.print.printSuiteComplete(suite); - return count++; - }); - }, 0); - }).then((count) => { - this.timer.end(); - this.finaliseTests(files); - }); - } - - private finaliseTests(files: File[]): void { - var testEval: TestEval = Lazy(this.suites).filter((suite) => { - return suite instanceof TestEval; - }).first(); - - if (testEval) { - var existsTestTypings: string[] = Lazy(testEval.testResults).map((testResult) => { - return testResult.targetFile.dir; - }).reduce((a: string[], b: string) => { - return a.indexOf(b) < 0 ? a.concat([b]) : a; - }, []); - - var typings: string[] = Lazy(files).map((file) => { - return file.dir; - }).reduce((a: string[], b: string) => { - return a.indexOf(b) < 0 ? a.concat([b]) : a; - }, []); - - var withoutTestTypings: string[] = typings.filter((typing) => { - return existsTestTypings.indexOf(typing) < 0; - }); - - this.print.printDiv(); - this.print.printTypingsWithoutTest(withoutTestTypings); - } - - this.print.printDiv(); - this.print.printTotalMessage(); - - this.print.printDiv(); - this.print.printElapsedTime(this.timer.asString, this.timer.time); - - this.suites.filter((suite: ITestSuite) => { - return suite.printErrorCount; - }).forEach((suite: ITestSuite) => { - this.print.printSuiteErrorCount(suite.errorHeadline, suite.ngTests.length, suite.testResults.length); - }); - if (testEval) { - this.print.printSuiteErrorCount('Without tests', withoutTestTypings.length, typings.length, true); - } - - this.print.printDiv(); - - if (this.suites.some((suite) => { - return suite.ngTests.length !== 0 - })) { - this.print.printErrorsHeader(); - - this.suites.filter((suite) => { - return suite.ngTests.length !== 0; - }).forEach((suite) => { - suite.ngTests.forEach((testResult) => { - this.print.printErrorsForFile(testResult); - }); - this.print.printBoldDiv(); - }); - } - } - } - - var optimist: Optimist = require('optimist')(process.argv); - optimist.default('try-without-tscparams', false); - optimist.default('single-thread', false); - optimist.default('tsc-version', DEFAULT_TSC_VERSION); - - optimist.default('test-changes', false); - optimist.default('skip-tests', false); - optimist.default('print-files', false); - optimist.default('print-refmap', false); - - optimist.boolean('help'); - optimist.describe('help', 'print help'); - optimist.alias('h', 'help'); - - var argv: any = optimist.argv; - - var dtPath = path.resolve(path.dirname((module).filename), '..', '..'); - var cpuCores = os.cpus().length; - - if (argv.help) { - optimist.showHelp(); - var pkg: PackageJSON = require('../../package.json'); - console.log('Scripts:'); - console.log(''); - Lazy(pkg.scripts).keys().each((key) => { - console.log(' $ npm run ' + key); - }); - process.exit(0); - } - - var testFull = process.env['TRAVIS_BRANCH'] ? /\w\/full$/.test(process.env['TRAVIS_BRANCH']) : false; - - new TestRunner(dtPath, { - concurrent: argv['single-thread'] ? 1 : Math.max(Math.min(24, cpuCores), 2), - tscVersion: argv['tsc-version'], - testChanges: testFull ? false : argv['test-changes'], // allow magic branch - skipTests: argv['skip-tests'], - printFiles: argv['print-files'], - printRefMap: argv['print-refmap'], - findNotRequiredTscparams: argv['try-without-tscparam'] - }).run().then((success) => { - if (!success) { - process.exit(1); - } - }).catch((err) => { - throw err; - process.exit(2); - }); -} diff --git a/_infrastructure/tests/src/changes.ts b/_infrastructure/tests/src/changes.ts deleted file mode 100644 index a56c4029eb..0000000000 --- a/_infrastructure/tests/src/changes.ts +++ /dev/null @@ -1,36 +0,0 @@ -/// -/// - -module DT { - 'use strict'; - - var fs = require('fs'); - var path = require('path'); - var Git = require('git-wrapper'); - var Promise: typeof Promise = require('bluebird'); - - export class GitChanges { - - git; - options = {}; - - constructor(private runner: TestRunner) { - var dir = path.join(this.runner.dtPath, '.git'); - if (!fs.existsSync(dir)) { - throw new Error('cannot locate git-dir: ' + dir); - } - this.options['git-dir'] = dir; - - this.git = new Git(this.options); - this.git.exec = Promise.promisify(this.git.exec); - } - - public readChanges(): Promise { - var opts = {}; - var args = ['--name-only HEAD~1']; - return this.git.exec('diff', opts, args).then((msg: string) => { - return msg.replace(/^\s+/, '').replace(/\s+$/, '').split(/\r?\n/g); - }); - } - } -} diff --git a/_infrastructure/tests/src/exec.ts b/_infrastructure/tests/src/exec.ts deleted file mode 100644 index 3c3f3c0e02..0000000000 --- a/_infrastructure/tests/src/exec.ts +++ /dev/null @@ -1,30 +0,0 @@ -module DT { - 'use strict'; - - var Promise: typeof Promise = require('bluebird'); - var nodeExec = require('child_process').exec; - - export class ExecResult { - error; - stdout = ''; - stderr = ''; - exitCode: number; - } - - export function exec(filename: string, cmdLineArgs: string[]): Promise { - return new Promise((resolve) => { - var result = new ExecResult(); - result.exitCode = null; - - var cmdLine = filename + ' ' + cmdLineArgs.join(' '); - - nodeExec(cmdLine, {maxBuffer: 1 * 1024 * 1024}, (error, stdout, stderr) => { - result.error = error; - result.stdout = stdout; - result.stderr = stderr; - result.exitCode = error ? error.code : 0; - resolve(result); - }); - }); - } -} diff --git a/_infrastructure/tests/src/file.ts b/_infrastructure/tests/src/file.ts deleted file mode 100644 index 2c69f8f885..0000000000 --- a/_infrastructure/tests/src/file.ts +++ /dev/null @@ -1,46 +0,0 @@ -/// - -module DT { - 'use strict'; - - var path = require('path'); - - export interface FileDict { - [fullPath:string]: File; - } - - export interface FileArrDict { - [fullPath:string]: File[]; - } - - ///////////////////////////////// - // Given a document root + ts file pattern this class returns: - // all the TS files OR just tests OR just definition files - ///////////////////////////////// - export class File { - baseDir: string; - filePathWithName: string; - dir: string; - file: string; - ext: string; - fullPath: string; - references: File[] = []; - - constructor(baseDir: string, filePathWithName: string) { - // why choose? - this.baseDir = baseDir; - this.filePathWithName = filePathWithName; - this.ext = path.extname(this.filePathWithName); - this.file = path.basename(this.filePathWithName, this.ext); - this.dir = path.dirname(this.filePathWithName); - this.fullPath = path.join(this.baseDir, this.dir, this.file + this.ext); - - // lock it (shallow) (needs `use strict` in each file to work) - // Object.freeze(this); - } - - toString(): string { - return '[File ' + this.filePathWithName + ']'; - } - } -} diff --git a/_infrastructure/tests/src/index.ts b/_infrastructure/tests/src/index.ts deleted file mode 100644 index 7f5878dcb3..0000000000 --- a/_infrastructure/tests/src/index.ts +++ /dev/null @@ -1,208 +0,0 @@ -/// -/// -/// - -module DT { - 'use strict'; - - var fs = require('fs'); - var path = require('path'); - var glob = require('glob'); - var Lazy: LazyJS.LazyStatic = require('lazy.js'); - var Promise: typeof Promise = require('bluebird'); - - var readFile = Promise.promisify(fs.readFile); - - ///////////////////////////////// - // Track all files in the repo: map full path to File objects - ///////////////////////////////// - export class FileIndex { - - files: File[]; - fileMap: FileDict; - refMap: FileArrDict; - options: ITestRunnerOptions; - changed: FileDict; - removed: FileDict; - missing: FileArrDict; - - constructor(private runner: TestRunner, options: ITestRunnerOptions) { - this.options = options; - } - - public hasFile(target: string): boolean { - return target in this.fileMap; - } - - public getFile(target: string): File { - if (target in this.fileMap) { - return this.fileMap[target]; - } - return null; - } - - public setFile(file: File): void { - if (file.fullPath in this.fileMap) { - throw new Error('cannot overwrite file'); - } - this.fileMap[file.fullPath] = file; - } - - public readIndex(): Promise { - this.fileMap = Object.create(null); - - return Promise.promisify(glob).call(glob, '**/*.ts', { - cwd: this.runner.dtPath - }).then((filesNames: string[]) => { - this.files = Lazy(filesNames).filter((fileName) => { - return this.runner.checkAcceptFile(fileName); - }).map((fileName: string) => { - var file = new File(this.runner.dtPath, fileName); - this.fileMap[file.fullPath] = file; - return file; - }).toArray(); - }); - } - - public collectDiff(changes: string[]): Promise { - return new Promise((resolve) => { - // filter changes and bake map for easy lookup - this.changed = Object.create(null); - this.removed = Object.create(null); - - Lazy(changes).filter((full) => { - return this.runner.checkAcceptFile(full); - }).uniq().each((local) => { - var full = path.resolve(this.runner.dtPath, local); - var file = this.getFile(full); - if (!file) { - // TODO figure out what to do here - // what does it mean? deleted?ss - file = new File(this.runner.dtPath, local); - this.setFile(file); - this.removed[full] = file; - // console.log('not in index? %', file.fullPath); - } - else { - this.changed[full] = file; - } - }); - // console.log('changed:\n' + Object.keys(this.changed).join('\n')); - // console.log('removed:\n' + Object.keys(this.removed).join('\n')); - resolve(); - }); - } - - public parseFiles(): Promise { - return this.loadReferences(this.files).then(() => { - return this.getMissingReferences(); - }); - } - - private getMissingReferences(): Promise { - return Promise.attempt(() => { - this.missing = Object.create(null); - Lazy(this.removed).keys().each((removed) => { - if (removed in this.refMap) { - this.missing[removed] = this.refMap[removed]; - } - }); - }); - } - - private loadReferences(files: File[]): Promise { - return new Promise((resolve, reject) => { - var queue = files.slice(0); - var active = []; - var max = 50; - var next = () => { - if (queue.length === 0 && active.length === 0) { - resolve(); - return; - } - // queue paralel - while (queue.length > 0 && active.length < max) { - var file = queue.pop(); - active.push(file); - this.parseFile(file).then((file) => { - active.splice(active.indexOf(file), 1); - next(); - }).catch((err) => { - queue = []; - active = []; - reject(err); - }); - } - }; - next(); - }).then(() => { - // bake reverse reference map (referenced to referrers) - this.refMap = Object.create(null); - - Lazy(files).each((file) => { - Lazy(file.references).each((ref) => { - if (ref.fullPath in this.refMap) { - this.refMap[ref.fullPath].push(file); - } - else { - this.refMap[ref.fullPath] = [file]; - } - }); - }); - }); - } - - // TODO replace with a stream? - private parseFile(file: File): Promise { - return readFile(file.filePathWithName, { - encoding: 'utf8', - flag: 'r' - }).then((content) => { - file.references = Lazy(extractReferenceTags(content)).map((ref) => { - return path.resolve(path.dirname(file.fullPath), ref); - }).reduce((memo: File[], ref) => { - if (ref in this.fileMap) { - memo.push(this.fileMap[ref]); - } - else { - console.log('not mapped? -> ' + ref); - } - return memo; - }, []); - // return the object - return file; - }); - } - - public collectTargets(): Promise { - return new Promise((resolve) => { - // map out files linked to changes - // - queue holds files touched by a change - // - pre-fill with actually changed files - // - loop queue, if current not seen: - // - add to result - // - from refMap queue all files referring to current - - var result: FileDict = Object.create(null); - var queue = Lazy(this.changed).values().toArray(); - - while (queue.length > 0) { - var next = queue.shift(); - var fp = next.fullPath; - if (result[fp]) { - continue; - } - result[fp] = next; - if (fp in this.refMap) { - var arr = this.refMap[fp]; - for (var i = 0, ii = arr.length; i < ii; i++) { - // just add it and skip expensive checks - queue.push(arr[i]); - } - } - } - resolve(Lazy(result).values().toArray()); - }); - } - } -} diff --git a/_infrastructure/tests/src/printer.ts b/_infrastructure/tests/src/printer.ts deleted file mode 100644 index 9ee01f3c6d..0000000000 --- a/_infrastructure/tests/src/printer.ts +++ /dev/null @@ -1,281 +0,0 @@ -/// -/// - -module DT { - - var os = require('os'); - - ///////////////////////////////// - // All the common things that we print are functions of this class - ///////////////////////////////// - export class Print { - - WIDTH = 77; - - typings: number; - tests: number; - tsFiles: number - - constructor(public version: string){ - - } - - public init(typings: number, tests: number, tsFiles: number) { - this.typings = typings; - this.tests = tests; - this.tsFiles = tsFiles; - } - - public out(s: any): Print { - process.stdout.write(s); - return this; - } - - public repeat(s: string, times: number): string { - return new Array(times + 1).join(s); - } - - public printChangeHeader() { - this.out('=============================================================================\n'); - this.out(' \33[36m\33[1mDefinitelyTyped Diff Detector 0.1.0\33[0m \n'); - this.out('=============================================================================\n'); - } - - public printHeader(options: ITestRunnerOptions) { - var totalMem = Math.round(os.totalmem() / 1024 / 1024) + ' mb'; - var freemem = Math.round(os.freemem() / 1024 / 1024) + ' mb'; - - this.out('=============================================================================\n'); - this.out(' \33[36m\33[1mDefinitelyTyped Test Runner 0.5.0\33[0m\n'); - this.out('=============================================================================\n'); - this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n'); - this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n'); - this.out(' \33[36m\33[1mTests :\33[0m ' + this.tests + '\n'); - this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n'); - this.out(' \33[36m\33[1mTotal Memory :\33[0m ' + totalMem + '\n'); - this.out(' \33[36m\33[1mFree Memory :\33[0m ' + freemem + '\n'); - this.out(' \33[36m\33[1mCores :\33[0m ' + os.cpus().length + '\n'); - this.out(' \33[36m\33[1mConcurrent :\33[0m ' + options.concurrent + '\n'); - } - - public printSuiteHeader(title: string) { - var left = Math.floor((this.WIDTH - title.length ) / 2) - 1; - var right = Math.ceil((this.WIDTH - title.length ) / 2) - 1; - this.out(this.repeat('=', left)).out(' \33[34m\33[1m'); - this.out(title); - this.out('\33[0m ').out(this.repeat('=', right)).printBreak(); - } - - public printDiv() { - this.out('-----------------------------------------------------------------------------\n'); - } - - public printBoldDiv() { - this.out('=============================================================================\n'); - } - - public printErrorsHeader() { - this.out('=============================================================================\n'); - this.out(' \33[34m\33[1mErrors in files\33[0m \n'); - this.out('=============================================================================\n'); - } - - public printErrorsForFile(testResult: TestResult) { - this.out('----------------- For file:' + testResult.targetFile.filePathWithName); - this.printBreak().out(testResult.stderr).printBreak(); - } - - public printBreak(): Print { - this.out('\n'); - return this; - } - - public clearCurrentLine(): Print { - this.out('\r\33[K'); - return this; - } - - public printSuccessCount(current: number, total: number) { - var arb = (total === 0) ? 0 : (current / total); - this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - } - - public printFailedCount(current: number, total: number) { - var arb = (total === 0) ? 0 : (current / total); - this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - } - - public printTypingsWithoutTestsMessage() { - this.out(' \33[36m\33[1mTyping without tests\33[0m\n'); - } - - public printTotalMessage() { - this.out(' \33[36m\33[1mTotal\33[0m\n'); - } - - public printElapsedTime(time: string, s: number) { - this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n'); - } - - public printSuiteErrorCount(errorHeadline: string, current: number, total: number, warn: boolean = false) { - var arb = (total === 0) ? 0 : (current / total); - this.out(' \33[36m\33[1m').out(errorHeadline).out(this.repeat(' ', 16 - errorHeadline.length)); - if (warn) { - this.out(': \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - } - else { - this.out(': \33[33m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - } - } - - public printSubHeader(file: string) { - this.out(' \33[36m\33[1m' + file + '\33[0m\n'); - } - - public printWarnCode(str: string) { - this.out(' \33[31m\33[1m<' + str.toLowerCase().replace(/ +/g, '-') + '>\33[0m\n'); - } - - public printLine(file: string) { - this.out(file + '\n'); - } - - public printElement(file: string) { - this.out(' - ' + file + '\n'); - } - - public printElement2(file: string) { - this.out(' - ' + file + '\n'); - } - - public printTypingsWithoutTestName(file: string) { - this.out(' - \33[33m\33[1m' + file + '\33[0m\n'); - } - - public printTypingsWithoutTest(withoutTestTypings: string[]) { - if (withoutTestTypings.length > 0) { - this.printTypingsWithoutTestsMessage(); - - this.printDiv(); - withoutTestTypings.forEach((t) => { - this.printTypingsWithoutTestName(t); - }); - } - } - - public printTestComplete(testResult: TestResult): void { - var reporter = testResult.hostedBy.testReporter; - if (testResult.success) { - reporter.printPositiveCharacter(testResult); - } - else { - reporter.printNegativeCharacter(testResult); - } - } - - public printSuiteComplete(suite: ITestSuite): void { - this.printBreak(); - - this.printDiv(); - this.printElapsedTime(suite.timer.asString, suite.timer.time); - this.printSuccessCount(suite.okTests.length, suite.testResults.length); - this.printFailedCount(suite.ngTests.length, suite.testResults.length); - } - - public printTests(adding: FileDict): void { - this.printDiv(); - this.printSubHeader('Testing'); - this.printDiv(); - - Object.keys(adding).sort().map((src) => { - this.printLine(adding[src].filePathWithName); - return adding[src]; - }); - } - - public printQueue(files: File[]): void { - this.printDiv(); - this.printSubHeader('Queued for testing'); - this.printDiv(); - - files.forEach((file) => { - this.printLine(file.filePathWithName); - }); - } - - public printTestAll(): void { - this.printDiv(); - this.printSubHeader('Ignoring changes, testing all files'); - } - - public printFiles(files: File[]): void { - this.printDiv(); - this.printSubHeader('Files'); - this.printDiv(); - - files.forEach((file) => { - this.printLine(file.filePathWithName); - file.references.forEach((file) => { - this.printElement(file.filePathWithName); - }); - }); - } - - public printMissing(index: FileIndex, refMap: FileArrDict): void { - this.printDiv(); - this.printSubHeader('Missing references'); - this.printDiv(); - - Object.keys(refMap).sort().forEach((src) => { - var ref = index.getFile(src); - this.printLine('\33[31m\33[1m' + ref.filePathWithName + '\33[0m'); - refMap[src].forEach((file) => { - this.printElement(file.filePathWithName); - }); - }); - } - - public printAllChanges(paths: string[]): void { - this.printSubHeader('All changes'); - this.printDiv(); - - paths.sort().forEach((line) => { - this.printLine(line); - }); - } - - public printRelChanges(changeMap: FileDict): void { - this.printDiv(); - this.printSubHeader('Interesting files'); - this.printDiv(); - - Object.keys(changeMap).sort().forEach((src) => { - this.printLine(changeMap[src].filePathWithName); - }); - } - - public printRemovals(changeMap: FileDict): void { - this.printDiv(); - this.printSubHeader('Removed files'); - this.printDiv(); - - Object.keys(changeMap).sort().forEach((src) => { - this.printLine(changeMap[src].filePathWithName); - }); - } - - public printRefMap(index: FileIndex, refMap: FileArrDict): void { - this.printDiv(); - this.printSubHeader('Referring'); - this.printDiv(); - - Object.keys(refMap).sort().forEach((src) => { - var ref = index.getFile(src); - this.printLine(ref.filePathWithName); - refMap[src].forEach((file) => { - this.printLine(' - ' + file.filePathWithName); - }); - }); - } - } -} diff --git a/_infrastructure/tests/src/reporter/reporter.ts b/_infrastructure/tests/src/reporter/reporter.ts deleted file mode 100644 index 736ac413cc..0000000000 --- a/_infrastructure/tests/src/reporter/reporter.ts +++ /dev/null @@ -1,42 +0,0 @@ -/// -/// - -module DT { - ///////////////////////////////// - // Test reporter interface - // for example, . and x - ///////////////////////////////// - export interface ITestReporter { - printPositiveCharacter(testResult: TestResult):void; - printNegativeCharacter(testResult: TestResult):void; - } - - ///////////////////////////////// - // Default test reporter - ///////////////////////////////// - export class DefaultTestReporter implements ITestReporter { - - index = 0; - - constructor(public print: Print) { - } - - public printPositiveCharacter(testResult: TestResult) { - this.print.out('\33[36m\33[1m' + '.' + '\33[0m'); - this.index++; - this.printBreakIfNeeded(this.index); - } - - public printNegativeCharacter( testResult: TestResult) { - this.print.out('x'); - this.index++; - this.printBreakIfNeeded(this.index); - } - - private printBreakIfNeeded(index: number) { - if (index % this.print.WIDTH === 0) { - this.print.printBreak(); - } - } - } -} diff --git a/_infrastructure/tests/src/suite/suite.ts b/_infrastructure/tests/src/suite/suite.ts deleted file mode 100644 index 8624da0d37..0000000000 --- a/_infrastructure/tests/src/suite/suite.ts +++ /dev/null @@ -1,82 +0,0 @@ -/// - -module DT { - 'use strict'; - - var Promise: typeof Promise = require('bluebird'); - - ///////////////////////////////// - // The interface for test suite - ///////////////////////////////// - export interface ITestSuite { - testSuiteName:string; - errorHeadline:string; - filterTargetFiles(files: File[]): Promise; - - start(targetFiles: File[], testCallback: (result: TestResult, index: number) => void): Promise; - - testResults:TestResult[]; - okTests:TestResult[]; - ngTests:TestResult[]; - timer:Timer; - - testReporter:ITestReporter; - printErrorCount:boolean; - } - - ///////////////////////////////// - // Base class for test suite - ///////////////////////////////// - export class TestSuiteBase implements ITestSuite { - timer: Timer = new Timer(); - testResults: TestResult[] = []; - testReporter: ITestReporter; - printErrorCount = true; - queue: TestQueue; - - constructor(public options: ITestRunnerOptions, public testSuiteName: string, public errorHeadline: string) { - this.queue = new TestQueue(options.concurrent); - } - - public filterTargetFiles(files: File[]): Promise { - throw new Error('please implement this method'); - } - - public start(targetFiles: File[], testCallback: (result: TestResult) => void): Promise { - this.timer.start(); - - return this.filterTargetFiles(targetFiles).then((targetFiles) => { - // tests get queued for multi-threading - return Promise.all(targetFiles.map((targetFile) => { - return this.runTest(targetFile).then((result) => { - testCallback(result); - }); - })); - }).then(() => { - this.timer.end(); - return this; - }); - } - - public runTest(targetFile: File): Promise { - return this.queue.run(new Test(this, targetFile, { - tscVersion: this.options.tscVersion - })).then((result) => { - this.testResults.push(result); - return result; - }); - } - - public get okTests(): TestResult[] { - return this.testResults.filter((r) => { - return r.success; - }); - } - - public get ngTests(): TestResult[] { - return this.testResults.filter((r) => { - return !r.success - }); - } - } -} diff --git a/_infrastructure/tests/src/suite/syntax.ts b/_infrastructure/tests/src/suite/syntax.ts deleted file mode 100644 index 915fd18d07..0000000000 --- a/_infrastructure/tests/src/suite/syntax.ts +++ /dev/null @@ -1,26 +0,0 @@ -/// -/// - -module DT { - 'use strict'; - - var Promise: typeof Promise = require('bluebird'); - - var endDts = /\w\.d\.ts$/i; - - ///////////////////////////////// - // .d.ts syntax inspection - ///////////////////////////////// - export class SyntaxChecking extends TestSuiteBase { - - constructor(options: ITestRunnerOptions) { - super(options, 'Syntax checking', 'Syntax error'); - } - - public filterTargetFiles(files: File[]): Promise { - return Promise.cast(files.filter((file) => { - return endDts.test(file.filePathWithName); - })); - } - } -} diff --git a/_infrastructure/tests/src/suite/testEval.ts b/_infrastructure/tests/src/suite/testEval.ts deleted file mode 100644 index abc4d50935..0000000000 --- a/_infrastructure/tests/src/suite/testEval.ts +++ /dev/null @@ -1,26 +0,0 @@ -/// -/// - -module DT { - 'use strict'; - - var Promise: typeof Promise = require('bluebird'); - - var endTestDts = /\w-tests?\.ts$/i; - - ///////////////////////////////// - // Compile with *-tests.ts - ///////////////////////////////// - export class TestEval extends TestSuiteBase { - - constructor(options) { - super(options, 'Typing tests', 'Failed tests'); - } - - public filterTargetFiles(files: File[]): Promise { - return Promise.cast(files.filter((file) => { - return endTestDts.test(file.filePathWithName); - })); - } - } -} diff --git a/_infrastructure/tests/src/suite/tscParams.ts b/_infrastructure/tests/src/suite/tscParams.ts deleted file mode 100644 index 12e3f46017..0000000000 --- a/_infrastructure/tests/src/suite/tscParams.ts +++ /dev/null @@ -1,59 +0,0 @@ -/// -/// - -module DT { - 'use strict'; - - var fs = require('fs'); - var Promise: typeof Promise = require('bluebird'); - - ///////////////////////////////// - // Try compile without .tscparams - // It may indicate that it is compatible with --noImplicitAny maybe... - ///////////////////////////////// - export class FindNotRequiredTscparams extends TestSuiteBase { - testReporter: ITestReporter; - printErrorCount = false; - - constructor(options: ITestRunnerOptions, private print: Print) { - super(options, 'Find not required .tscparams files', 'New arrival!'); - - this.testReporter = { - printPositiveCharacter: (testResult: TestResult) => { - this.print - .clearCurrentLine() - .printTypingsWithoutTestName(testResult.targetFile.filePathWithName); - }, - printNegativeCharacter: (testResult: TestResult) => { - } - } - } - - public filterTargetFiles(files: File[]): Promise { - return Promise.filter(files, (file) => { - return new Promise((resolve) => { - fs.exists(file.filePathWithName + '.tscparams', resolve); - }); - }); - } - - public runTest(targetFile: File): Promise { - this.print.clearCurrentLine().out(targetFile.filePathWithName); - - return this.queue.run(new Test(this, targetFile, { - tscVersion: this.options.tscVersion, - useTscParams: false, - checkNoImplicitAny: true - })).then((result) => { - this.testResults.push(result); - this.print.clearCurrentLine(); - return result - }); - } - - public get ngTests(): TestResult[] { - // Do not show ng test results - return []; - } - } -} diff --git a/_infrastructure/tests/src/timer.ts b/_infrastructure/tests/src/timer.ts deleted file mode 100644 index 0f74743471..0000000000 --- a/_infrastructure/tests/src/timer.ts +++ /dev/null @@ -1,50 +0,0 @@ -/// -/// - -module DT { - 'use strict'; - - ///////////////////////////////// - // Timer.start starts a timer - // Timer.end stops the timer and sets asString to the pretty print value - ///////////////////////////////// - export class Timer { - startTime: number; - time = 0; - asString: string = '' - - public start() { - this.time = 0; - this.startTime = this.now(); - this.asString = ''; - } - - public now(): number { - return Date.now(); - } - - public end() { - this.time = (this.now() - this.startTime) / 1000; - this.asString = Timer.prettyDate(this.startTime, this.now()); - } - - public static prettyDate(date1: number, date2: number): string { - var diff = ((date2 - date1) / 1000); - var day_diff = Math.floor(diff / 86400); - - if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) { - return null; - } - - return ( (day_diff == 0 && ( - diff < 60 && (diff + ' seconds') || - diff < 120 && '1 minute' || - diff < 3600 && Math.floor(diff / 60) + ' minutes' || - diff < 7200 && '1 hour' || - diff < 86400 && Math.floor(diff / 3600) + ' hours') || - day_diff == 1 && 'Yesterday' || - day_diff < 7 && day_diff + ' days' || - day_diff < 31 && Math.ceil(day_diff / 7) + ' weeks')); - } - } -} diff --git a/_infrastructure/tests/src/tsc.ts b/_infrastructure/tests/src/tsc.ts deleted file mode 100644 index 9730a1394c..0000000000 --- a/_infrastructure/tests/src/tsc.ts +++ /dev/null @@ -1,54 +0,0 @@ -/// -/// -/// - -module DT { - 'use strict'; - - var fs = require('fs'); - - var Promise: typeof Promise = require('bluebird'); - - export interface TscExecOptions { - tscVersion?:string; - useTscParams?:boolean; - checkNoImplicitAny?:boolean; - } - - export class Tsc { - public static run(tsfile: string, options: TscExecOptions): Promise { - var tscPath; - return new Promise.attempt(() => { - options = options || {}; - options.tscVersion = options.tscVersion || DEFAULT_TSC_VERSION; - if (typeof options.checkNoImplicitAny === 'undefined') { - options.checkNoImplicitAny = true; - } - if (typeof options.useTscParams === 'undefined') { - options.useTscParams = true; - } - return fileExists(tsfile); - }).then((exists) => { - if (!exists) { - throw new Error(tsfile + ' not exists'); - } - tscPath = './_infrastructure/tests/typescript/' + options.tscVersion + '/tsc.js'; - return fileExists(tscPath); - }).then((exists) => { - if (!exists) { - throw new Error(tscPath + ' is not exists'); - } - return fileExists(tsfile + '.tscparams'); - }).then((exists) => { - var command = 'node ' + tscPath + ' --module commonjs '; - if (options.useTscParams && exists) { - command += '@' + tsfile + '.tscparams'; - } - else if (options.checkNoImplicitAny) { - command += '--noImplicitAny'; - } - return exec(command, [tsfile]); - }); - } - } -} diff --git a/_infrastructure/tests/src/util.ts b/_infrastructure/tests/src/util.ts deleted file mode 100644 index a712bb90cd..0000000000 --- a/_infrastructure/tests/src/util.ts +++ /dev/null @@ -1,40 +0,0 @@ -/// - -module DT { - 'use strict'; - - var fs = require('fs'); - var Lazy: LazyJS.LazyStatic = require('lazy.js'); - var Promise: typeof Promise = require('bluebird'); - - var referenceTagExp = //g; - - export function endsWith(str: string, suffix: string) { - return str.indexOf(suffix, str.length - suffix.length) !== -1; - } - - export function extractReferenceTags(source: string): string[] { - var ret: string[] = []; - var match: RegExpExecArray; - - if (!referenceTagExp.global) { - throw new Error('referenceTagExp RegExp must have global flag'); - } - referenceTagExp.lastIndex = 0; - - while ((match = referenceTagExp.exec(source))) { - if (match.length > 0 && match[1].length > 0) { - ret.push(match[1]); - } - } - return ret; - } - - export function fileExists(target: string): Promise { - return new Promise((resolve, reject) => { - fs.exists(target, (bool: boolean) => { - resolve(bool); - }); - }); - } -} diff --git a/_infrastructure/tests/typescript/1.0.1/lib.d.ts b/_infrastructure/tests/typescript/1.0.1/lib.d.ts new file mode 100644 index 0000000000..d3e57e7e63 --- /dev/null +++ b/_infrastructure/tests/typescript/1.0.1/lib.d.ts @@ -0,0 +1,14958 @@ +/* ***************************************************************************** +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): boolean; + +/** + * Determines whether a supplied number is finite. + * @param number Any numeric value. + */ +declare function isFinite(number: number): boolean; + +/** + * 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?: boolean; + enumerable?: boolean; + value?: any; + writable?: boolean; + get? (): any; + set? (v: any): void; +} + +interface PropertyDescriptorMap { + [s: string]: PropertyDescriptor; +} + +interface Object { + /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ + constructor: Function; + + /** 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): boolean; + + /** + * 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): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: string): boolean; +} + +/** + * 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): boolean; + + /** + * 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): boolean; + + /** + * Returns a value that indicates whether new properties can be added to an object. + * @param o Object to test. + */ + isExtensible(o: any): boolean; + + /** + * 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 number indicating the beginning of the substring. + * @param end Zero-based index number 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; + + [index: 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): boolean; + prototype: Boolean; +} + +interface Number { + /** + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. + */ + toString(radix?: number): string; + + /** + * Returns a string representing a number in fixed-point notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toFixed(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented in exponential notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toExponential(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. + * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. + */ + 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 number 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 number 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 number. + * @param x The value to be rounded to the nearest number. + */ + 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; + /** Returns a value as a string value appropriate to the host environment's current locale. */ + 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): number; + /** + * Sets the milliseconds value in the Date object using local time. + * @param ms A numeric value equal to the millisecond value. + */ + setMilliseconds(ms: number): number; + /** + * 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): number; + + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** 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; +} + +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 number between 0 and 11 (January to December). + * @param date The date as an number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. + * @param ms An number 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(separator?: 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[]) => boolean, thisArg?: any): boolean; + some(callbackfn: (value: string, index: number, array: string[]) => boolean, thisArg?: any): boolean; + 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[]) => boolean, 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): boolean; + + /** 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: boolean; + + /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ + ignoreCase: boolean; + + /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ + multiline: boolean; + + 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 { + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: U[]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Removes the last element from an array and returns it. + */ + pop(): T; + /** + * Appends new elements to an array, and returns the new length of the array. + * @param items New elements of the Array. + */ + push(...items: T[]): number; + /** + * Reverses the elements in an Array. + */ + reverse(): T[]; + /** + * Removes the first element from an array and returns it. + */ + shift(): T; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: T, b: T) => number): T[]; + + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + */ + splice(start: number): T[]; + + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param items Elements to insert into the array in place of the deleted elements. + */ + splice(start: number, deleteCount: number, ...items: T[]): T[]; + + /** + * Inserts new elements at the start of an array. + * @param items Elements to insert at the start of the Array. + */ + unshift(...items: T[]): number; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; + + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + /** + * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. + */ + length: number; + + [n: number]: T; +} +declare var Array: { + new (arrayLength?: number): any[]; + new (arrayLength: number): T[]; + new (...items: T[]): T[]; + (arrayLength?: number): any[]; + (arrayLength: number): T[]; + (...items: T[]): T[]; + isArray(arg: any): boolean; + prototype: Array; +} + + +///////////////////////////// +/// IE10 ECMAScript Extensions +///////////////////////////// + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + /** + * Read-only. The length of the ArrayBuffer (in bytes). + */ + byteLength: number; +} + +declare var ArrayBuffer: { + prototype: ArrayBuffer; + new (byteLength: number): ArrayBuffer; +} + +interface ArrayBufferView { + buffer: ArrayBuffer; + byteOffset: number; + byteLength: number; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Int8Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Int8Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Uint8Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Uint8Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * A typed array of 16-bit integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Int16Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Int16Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Uint16Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Uint16Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * A typed array of 32-bit integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Int32Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Int32Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Uint32Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Int8Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Float32Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Float32Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Float32Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Float64Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Float64Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Float64Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * You can use a DataView object to read and write the different kinds of binary data to any location in the ArrayBuffer. + */ +interface DataView extends ArrayBufferView { + /** + * Gets the Int8 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt8(byteOffset: number): number; + + /** + * Gets the Uint8 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint8(byteOffset: number): number; + + /** + * Gets the Int16 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt16(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint16 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint16(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Int32 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint32 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Float32 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Float64 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat64(byteOffset: number, littleEndian?: boolean): number; + + /** + * Stores an Int8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setInt8(byteOffset: number, value: number): void; + + /** + * Stores an Uint8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setUint8(byteOffset: number, value: number): void; + + /** + * Stores an Int16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. + */ + setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. + */ + setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. + */ + setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. + */ + setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Float32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. + */ + setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Float64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. + */ + setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; +} +declare var DataView: { + prototype: DataView; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): DataView; +} + +///////////////////////////// +/// IE11 ECMAScript Extensions +///////////////////////////// + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; + get(key: K): V; + has(key: K): boolean; + set(key: K, value: V): Map; + size: number; +} +declare var Map: { + new (): Map; +} + +interface WeakMap { + clear(): void; + delete(key: K): boolean; + get(key: K): V; + has(key: K): boolean; + set(key: K, value: V): WeakMap; +} +declare var WeakMap: { + new (): WeakMap; +} + +interface Set { + add(value: T): Set; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + size: number; +} +declare var Set: { + new (): Set; +} + +declare module Intl { + + interface CollatorOptions { + usage?: string; + localeMatcher?: string; + numeric?: boolean; + caseFirst?: string; + sensitivity?: string; + ignorePunctuation?: boolean; + } + + interface ResolvedCollatorOptions { + locale: string; + usage: string; + sensitivity: string; + ignorePunctuation: boolean; + collation: string; + caseFirst: string; + numeric: boolean; + } + + interface Collator { + compare(x: string, y: string): number; + resolvedOptions(): ResolvedCollatorOptions; + } + var Collator: { + new (locales?: string[], options?: CollatorOptions): Collator; + new (locale?: string, options?: CollatorOptions): Collator; + (locales?: string[], options?: CollatorOptions): Collator; + (locale?: string, options?: CollatorOptions): Collator; + supportedLocalesOf(locales: string[], options?: CollatorOptions): string[]; + supportedLocalesOf(locale: string, options?: CollatorOptions): string[]; + } + + interface NumberFormatOptions { + localeMatcher?: string; + style?: string; + currency?: string; + currencyDisplay?: string; + useGrouping?: boolean; + } + + interface ResolvedNumberFormatOptions { + locale: string; + numberingSystem: string; + style: string; + currency?: string; + currencyDisplay?: string; + minimumintegerDigits: number; + minimumFractionDigits: number; + maximumFractionDigits: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + useGrouping: boolean; + } + + interface NumberFormat { + format(value: number): string; + resolvedOptions(): ResolvedNumberFormatOptions; + } + var NumberFormat: { + new (locales?: string[], options?: NumberFormatOptions): Collator; + new (locale?: string, options?: NumberFormatOptions): Collator; + (locales?: string[], options?: NumberFormatOptions): Collator; + (locale?: string, options?: NumberFormatOptions): Collator; + supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[]; + supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[]; + } + + interface DateTimeFormatOptions { + localeMatcher?: string; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + formatMatcher?: string; + hour12: boolean; + } + + interface ResolvedDateTimeFormatOptions { + locale: string; + calendar: string; + numberingSystem: string; + timeZone: string; + hour12?: boolean; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + } + + interface DateTimeFormat { + format(date: number): string; + resolvedOptions(): ResolvedDateTimeFormatOptions; + } + var DateTimeFormat: { + new (locales?: string[], options?: DateTimeFormatOptions): Collator; + new (locale?: string, options?: DateTimeFormatOptions): Collator; + (locales?: string[], options?: DateTimeFormatOptions): Collator; + (locale?: string, options?: DateTimeFormatOptions): Collator; + supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[]; + supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[]; + } +} + +interface String { + localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number; + localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number; +} + +interface Number { + toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string; + toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string; +} + +interface Date { + toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string; + toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string; +} + + +///////////////////////////// +/// IE9 DOM APIs +///////////////////////////// + +interface PositionOptions { + enableHighAccuracy?: boolean; + timeout?: number; + maximumAge?: number; +} + +interface NavigatorID { + appVersion: string; + appName: string; + userAgent: string; + platform: string; +} + +interface HTMLTableElement extends HTMLElement, MSDataBindingTableExtensions, MSDataBindingExtensions, DOML2DeprecatedBackgroundStyle, DOML2DeprecatedBackgroundColorStyle { + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Sets or retrieves the color for one of the two colors used to draw the 3-D border of the object. + */ + borderColorLight: any; + /** + * Sets or retrieves the amount of space between cells in a table. + */ + cellSpacing: string; + /** + * Retrieves the tFoot object of the table. + */ + tFoot: HTMLTableSectionElement; + /** + * Sets or retrieves the way the border frame around the table is displayed. + */ + frame: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: HTMLCollection; + /** + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ + rules: string; + /** + * Sets or retrieves the number of columns in the table. + */ + cols: number; + /** + * Sets or retrieves a description and/or structure of the object. + */ + summary: string; + /** + * Retrieves the caption object of a table. + */ + caption: HTMLTableCaptionElement; + /** + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ + tBodies: HTMLCollection; + /** + * Retrieves the tHead object of the table. + */ + tHead: HTMLTableSectionElement; + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + /** + * Retrieves a collection of all cells in the table row or in the entire table. + */ + cells: HTMLCollection; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ + cellPadding: string; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + border: string; + /** + * Sets or retrieves the color for one of the two colors used to draw the 3-D border of the object. + */ + borderColorDark: any; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index?: number): void; + /** + * Creates an empty tBody element in the table. + */ + createTBody(): HTMLElement; + /** + * Deletes the caption element and its contents from the table. + */ + deleteCaption(): void; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLElement; + /** + * Deletes the tFoot element and its contents from the table. + */ + deleteTFoot(): void; + /** + * Returns the tHead element object if successful, or null otherwise. + */ + createTHead(): HTMLElement; + /** + * Deletes the tHead element and its contents from the table. + */ + deleteTHead(): void; + /** + * Creates an empty caption element in the table. + */ + createCaption(): HTMLElement; + /** + * Moves a table row to a new position. + * @param indexFrom Number that specifies the index in the rows collection of the table row that is moved. + * @param indexTo Number that specifies where the row is moved within the rows collection. + */ + moveRow(indexFrom?: number, indexTo?: number): Object; + /** + * Creates an empty tFoot element in the table. + */ + createTFoot(): HTMLElement; +} +declare var HTMLTableElement: { + prototype: HTMLTableElement; + new (): HTMLTableElement; +} + +interface TreeWalker { + whatToShow: number; + filter: NodeFilter; + root: Node; + currentNode: Node; + expandEntityReferences: boolean; + previousSibling(): Node; + lastChild(): Node; + nextSibling(): Node; + nextNode(): Node; + parentNode(): Node; + firstChild(): Node; + previousNode(): Node; +} +declare var TreeWalker: { + prototype: TreeWalker; + new (): TreeWalker; +} + +interface GetSVGDocument { + getSVGDocument(): Document; +} + +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; + getEntriesByType(entryType: string): any; + toJSON(): any; + getMeasures(measureName?: string): any; + clearMarks(markName?: string): void; + getMarks(markName?: string): any; + clearResourceTimings(): void; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + getEntriesByName(name: string, entryType?: string): any; + getEntries(): any; + clearMeasures(measureName?: string): void; + setResourceTimingBufferSize(maxSize: number): void; +} +declare var Performance: { + prototype: Performance; + new (): Performance; +} + +interface MSDataBindingTableExtensions { + dataPageSize: number; + nextPage(): void; + firstPage(): void; + refresh(): void; + previousPage(): void; + lastPage(): void; +} + +interface CompositionEvent extends UIEvent { + data: string; + locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} +declare var CompositionEvent: { + prototype: CompositionEvent; + new (): CompositionEvent; +} + +interface WindowTimers { + clearTimeout(handle: number): void; + setTimeout(handler: any, timeout?: any, ...args: any[]): number; + clearInterval(handle: number): void; + setInterval(handler: any, timeout?: any, ...args: any[]): number; +} + +interface SVGMarkerElement extends SVGElement, SVGStylable, SVGLangSpace, SVGFitToViewBox, SVGExternalResourcesRequired { + 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 CSSStyleDeclaration { + backgroundAttachment: string; + visibility: string; + textAlignLast: string; + borderRightStyle: string; + counterIncrement: string; + orphans: string; + cssText: string; + borderStyle: string; + pointerEvents: string; + borderTopColor: string; + markerEnd: string; + textIndent: string; + listStyleImage: string; + cursor: string; + listStylePosition: string; + wordWrap: string; + borderTopStyle: string; + alignmentBaseline: string; + opacity: string; + direction: string; + strokeMiterlimit: string; + maxWidth: string; + color: string; + clip: string; + borderRightWidth: string; + verticalAlign: string; + overflow: string; + mask: string; + borderLeftStyle: string; + emptyCells: string; + stopOpacity: string; + paddingRight: string; + parentRule: CSSRule; + background: string; + boxSizing: string; + textJustify: string; + height: string; + paddingTop: string; + length: number; + right: string; + baselineShift: string; + borderLeft: string; + widows: string; + lineHeight: string; + left: string; + textUnderlinePosition: string; + glyphOrientationHorizontal: string; + display: string; + textAnchor: string; + cssFloat: string; + strokeDasharray: string; + rubyAlign: string; + fontSizeAdjust: string; + borderLeftColor: string; + backgroundImage: string; + listStyleType: string; + strokeWidth: string; + textOverflow: string; + fillRule: string; + borderBottomColor: string; + zIndex: string; + position: string; + listStyle: string; + msTransformOrigin: string; + dominantBaseline: string; + overflowY: string; + fill: string; + captionSide: string; + borderCollapse: string; + boxShadow: string; + quotes: string; + tableLayout: string; + unicodeBidi: string; + borderBottomWidth: string; + backgroundSize: string; + textDecoration: string; + strokeDashoffset: string; + fontSize: string; + border: string; + pageBreakBefore: string; + borderTopRightRadius: string; + msTransform: string; + borderBottomLeftRadius: string; + textTransform: string; + rubyPosition: string; + strokeLinejoin: string; + clipPath: string; + borderRightColor: string; + fontFamily: string; + clear: string; + content: string; + backgroundClip: string; + marginBottom: string; + counterReset: string; + outlineWidth: string; + marginRight: string; + paddingLeft: string; + borderBottom: string; + wordBreak: string; + marginTop: string; + top: string; + fontWeight: string; + borderRight: string; + width: string; + kerning: string; + pageBreakAfter: string; + borderBottomStyle: string; + fontStretch: string; + padding: string; + strokeOpacity: string; + markerStart: string; + bottom: string; + borderLeftWidth: string; + clipRule: string; + backgroundPosition: string; + backgroundColor: string; + pageBreakInside: string; + backgroundOrigin: string; + strokeLinecap: string; + borderTopWidth: string; + outlineStyle: string; + borderTop: string; + outlineColor: string; + paddingBottom: string; + marginLeft: string; + font: string; + outline: string; + wordSpacing: string; + maxHeight: string; + fillOpacity: string; + letterSpacing: string; + borderSpacing: string; + backgroundRepeat: string; + borderRadius: string; + borderWidth: string; + borderBottomRightRadius: string; + whiteSpace: string; + fontStyle: string; + minWidth: string; + stopColor: string; + borderTopLeftRadius: string; + borderColor: string; + marker: string; + glyphOrientationVertical: string; + markerMid: string; + fontVariant: string; + minHeight: string; + stroke: string; + rubyOverhang: string; + overflowX: string; + textAlign: string; + margin: string; + 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, SVGExternalResourcesRequired { +} +declare var SVGGElement: { + prototype: SVGGElement; + new (): SVGGElement; +} + +interface MSStyleCSSProperties extends MSCSSProperties { + pixelWidth: number; + posHeight: number; + posLeft: number; + pixelTop: number; + pixelBottom: number; + textDecorationNone: boolean; + pixelLeft: number; + posTop: number; + posBottom: number; + textDecorationOverline: boolean; + posWidth: number; + textDecorationLineThrough: boolean; + pixelHeight: number; + textDecorationBlink: boolean; + posRight: number; + pixelRight: number; + textDecorationUnderline: boolean; +} +declare var MSStyleCSSProperties: { + prototype: MSStyleCSSProperties; + new (): MSStyleCSSProperties; +} + +interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, MSNavigatorExtensions, NavigatorGeolocation, MSNavigatorDoNotTrack, NavigatorStorageUtils { +} +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 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 { +} +declare var HTMLTableDataCellElement: { + prototype: HTMLTableDataCellElement; + new (): HTMLTableDataCellElement; +} + +interface HTMLBaseElement extends HTMLElement { + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Gets or sets the baseline URL on which relative links are based. + */ + 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 { + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createDocument(namespaceURI: string, qualifiedName: string, doctype: DocumentType): Document; + hasFeature(feature: string, version?: string): boolean; + createHTMLDocument(title: string): Document; +} +declare var DOMImplementation: { + prototype: DOMImplementation; + new (): DOMImplementation; +} + +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 Element extends Node, NodeSelector, ElementTraversal { + 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): boolean; + getBoundingClientRect(): ClientRect; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + msMatchesSelector(selectors: string): boolean; + hasAttribute(name: string): boolean; + removeAttribute(name?: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + getAttributeNode(name: string): Attr; + fireEvent(eventName: string, eventObj?: any): boolean; + getElementsByTagName(name: "a"): NodeListOf; + getElementsByTagName(name: "abbr"): NodeListOf; + getElementsByTagName(name: "address"): NodeListOf; + getElementsByTagName(name: "area"): NodeListOf; + getElementsByTagName(name: "article"): NodeListOf; + getElementsByTagName(name: "aside"): NodeListOf; + getElementsByTagName(name: "audio"): NodeListOf; + getElementsByTagName(name: "b"): NodeListOf; + getElementsByTagName(name: "base"): NodeListOf; + getElementsByTagName(name: "bdi"): NodeListOf; + getElementsByTagName(name: "bdo"): NodeListOf; + getElementsByTagName(name: "blockquote"): NodeListOf; + getElementsByTagName(name: "body"): NodeListOf; + getElementsByTagName(name: "br"): NodeListOf; + getElementsByTagName(name: "button"): NodeListOf; + getElementsByTagName(name: "canvas"): NodeListOf; + getElementsByTagName(name: "caption"): NodeListOf; + getElementsByTagName(name: "cite"): NodeListOf; + getElementsByTagName(name: "code"): NodeListOf; + getElementsByTagName(name: "col"): NodeListOf; + getElementsByTagName(name: "colgroup"): NodeListOf; + getElementsByTagName(name: "datalist"): NodeListOf; + getElementsByTagName(name: "dd"): NodeListOf; + getElementsByTagName(name: "del"): NodeListOf; + getElementsByTagName(name: "dfn"): NodeListOf; + getElementsByTagName(name: "div"): NodeListOf; + getElementsByTagName(name: "dl"): NodeListOf; + getElementsByTagName(name: "dt"): NodeListOf; + getElementsByTagName(name: "em"): NodeListOf; + getElementsByTagName(name: "embed"): NodeListOf; + getElementsByTagName(name: "fieldset"): NodeListOf; + getElementsByTagName(name: "figcaption"): NodeListOf; + getElementsByTagName(name: "figure"): NodeListOf; + getElementsByTagName(name: "footer"): NodeListOf; + getElementsByTagName(name: "form"): NodeListOf; + getElementsByTagName(name: "h1"): NodeListOf; + getElementsByTagName(name: "h2"): NodeListOf; + getElementsByTagName(name: "h3"): NodeListOf; + getElementsByTagName(name: "h4"): NodeListOf; + getElementsByTagName(name: "h5"): NodeListOf; + getElementsByTagName(name: "h6"): NodeListOf; + getElementsByTagName(name: "head"): NodeListOf; + getElementsByTagName(name: "header"): NodeListOf; + getElementsByTagName(name: "hgroup"): NodeListOf; + getElementsByTagName(name: "hr"): NodeListOf; + getElementsByTagName(name: "html"): NodeListOf; + getElementsByTagName(name: "i"): NodeListOf; + getElementsByTagName(name: "iframe"): NodeListOf; + getElementsByTagName(name: "img"): NodeListOf; + getElementsByTagName(name: "input"): NodeListOf; + getElementsByTagName(name: "ins"): NodeListOf; + getElementsByTagName(name: "kbd"): NodeListOf; + getElementsByTagName(name: "label"): NodeListOf; + getElementsByTagName(name: "legend"): NodeListOf; + getElementsByTagName(name: "li"): NodeListOf; + getElementsByTagName(name: "link"): NodeListOf; + getElementsByTagName(name: "main"): NodeListOf; + getElementsByTagName(name: "map"): NodeListOf; + getElementsByTagName(name: "mark"): NodeListOf; + getElementsByTagName(name: "menu"): NodeListOf; + getElementsByTagName(name: "meta"): NodeListOf; + getElementsByTagName(name: "nav"): NodeListOf; + getElementsByTagName(name: "noscript"): NodeListOf; + getElementsByTagName(name: "object"): NodeListOf; + getElementsByTagName(name: "ol"): NodeListOf; + getElementsByTagName(name: "optgroup"): NodeListOf; + getElementsByTagName(name: "option"): NodeListOf; + getElementsByTagName(name: "p"): NodeListOf; + getElementsByTagName(name: "param"): NodeListOf; + getElementsByTagName(name: "pre"): NodeListOf; + getElementsByTagName(name: "progress"): NodeListOf; + getElementsByTagName(name: "q"): NodeListOf; + getElementsByTagName(name: "rp"): NodeListOf; + getElementsByTagName(name: "rt"): NodeListOf; + getElementsByTagName(name: "ruby"): NodeListOf; + getElementsByTagName(name: "s"): NodeListOf; + getElementsByTagName(name: "samp"): NodeListOf; + getElementsByTagName(name: "script"): NodeListOf; + getElementsByTagName(name: "section"): NodeListOf; + getElementsByTagName(name: "select"): NodeListOf; + getElementsByTagName(name: "small"): NodeListOf; + getElementsByTagName(name: "source"): NodeListOf; + getElementsByTagName(name: "span"): NodeListOf; + getElementsByTagName(name: "strong"): NodeListOf; + getElementsByTagName(name: "style"): NodeListOf; + getElementsByTagName(name: "sub"): NodeListOf; + getElementsByTagName(name: "summary"): NodeListOf; + getElementsByTagName(name: "sup"): NodeListOf; + getElementsByTagName(name: "table"): NodeListOf; + getElementsByTagName(name: "tbody"): NodeListOf; + getElementsByTagName(name: "td"): NodeListOf; + getElementsByTagName(name: "textarea"): NodeListOf; + getElementsByTagName(name: "tfoot"): NodeListOf; + getElementsByTagName(name: "th"): NodeListOf; + getElementsByTagName(name: "thead"): NodeListOf; + getElementsByTagName(name: "title"): NodeListOf; + getElementsByTagName(name: "tr"): NodeListOf; + getElementsByTagName(name: "track"): NodeListOf; + getElementsByTagName(name: "u"): NodeListOf; + getElementsByTagName(name: "ul"): NodeListOf; + getElementsByTagName(name: "var"): NodeListOf; + getElementsByTagName(name: "video"): NodeListOf; + getElementsByTagName(name: "wbr"): NodeListOf; + getElementsByTagName(name: string): NodeList; + getClientRects(): ClientRectList; + setAttributeNode(newAttr: Attr): Attr; + removeAttributeNode(oldAttr: Attr): Attr; + setAttribute(name?: string, value?: string): void; + removeAttributeNS(namespaceURI: string, localName: string): void; +} +declare var Element: { + prototype: Element; + new (): Element; +} + +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, SVGExternalResourcesRequired { + y1: SVGAnimatedLength; + x2: SVGAnimatedLength; + x1: SVGAnimatedLength; + y2: SVGAnimatedLength; +} +declare var SVGLineElement: { + prototype: SVGLineElement; + new (): SVGLineElement; +} + +interface HTMLParagraphElement extends HTMLElement, DOML2DeprecatedTextFlowControl { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; +} +declare var HTMLParagraphElement: { + prototype: HTMLParagraphElement; + new (): HTMLParagraphElement; +} + +interface HTMLAreasCollection extends HTMLCollection { + /** + * Removes an element from the collection. + */ + remove(index?: number): void; + /** + * Adds an element to the areas, controlRange, or options collection. + */ + 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: NamedNodeMap; + firstChild: Node; + prefix: string; + removeChild(oldChild: Node): Node; + appendChild(newChild: Node): Node; + isSupported(feature: string, version: string): boolean; + isEqualNode(arg: Node): boolean; + lookupPrefix(namespaceURI: string): string; + isDefaultNamespace(namespaceURI: string): boolean; + compareDocumentPosition(other: Node): number; + normalize(): void; + isSameNode(other: Node): boolean; + hasAttributes(): boolean; + lookupNamespaceURI(prefix: string): string; + cloneNode(deep?: boolean): Node; + hasChildNodes(): boolean; + 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 SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { + y: number; + x: number; +} +declare var SVGPathSegCurvetoQuadraticSmoothRel: { + prototype: SVGPathSegCurvetoQuadraticSmoothRel; + new (): SVGPathSegCurvetoQuadraticSmoothRel; +} + +interface DOML2DeprecatedListSpaceReduction { + compact: boolean; +} + +interface MSScriptHost { +} +declare var MSScriptHost: { + prototype: MSScriptHost; + new (): MSScriptHost; +} + +interface SVGClipPathElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { + clipPathUnits: SVGAnimatedEnumeration; +} +declare var SVGClipPathElement: { + prototype: SVGClipPathElement; + new (): SVGClipPathElement; +} + +interface MouseEvent extends UIEvent { + toElement: Element; + layerY: number; + fromElement: Element; + which: number; + pageX: number; + offsetY: number; + x: number; + y: number; + metaKey: boolean; + altKey: boolean; + ctrlKey: boolean; + offsetX: number; + screenX: number; + clientY: number; + shiftKey: boolean; + layerX: number; + screenY: number; + relatedTarget: EventTarget; + button: number; + pageY: number; + buttons: number; + clientX: number; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget): void; + getModifierState(keyArg: string): boolean; +} +declare var MouseEvent: { + prototype: MouseEvent; + new (): MouseEvent; +} + +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 SVGTextPositioningElement extends SVGTextContentElement { + y: SVGAnimatedLengthList; + rotate: SVGAnimatedNumberList; + dy: SVGAnimatedLengthList; + x: SVGAnimatedLengthList; + dx: SVGAnimatedLengthList; +} +declare var SVGTextPositioningElement: { + prototype: SVGTextPositioningElement; + new (): SVGTextPositioningElement; +} + +interface HTMLAppletElement extends HTMLElement, DOML2DeprecatedMarginStyle, DOML2DeprecatedBorderStyle, DOML2DeprecatedAlignmentStyle, MSDataBindingExtensions, MSDataBindingRecordSetExtensions { + width: number; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + object: string; + form: HTMLFormElement; + code: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the class identifier for the object. + */ + classid: string; + /** + * Sets or retrieves the shape of the object. + */ + name: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ + contentDocument: Document; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ + declare: boolean; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + BaseHref: string; +} +declare var HTMLAppletElement: { + prototype: HTMLAppletElement; + new (): HTMLAppletElement; +} + +interface TextMetrics { + width: number; +} +declare var TextMetrics: { + prototype: TextMetrics; + new (): TextMetrics; +} + +interface DocumentEvent { + createEvent(eventInterface: string): Event; +} + +interface HTMLOListElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, DOML2DeprecatedListNumberingAndBulletStyle { + /** + * The starting number. + */ + start: number; +} +declare var HTMLOListElement: { + prototype: HTMLOListElement; + new (): HTMLOListElement; +} + +interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { + y: number; +} +declare var SVGPathSegLinetoVerticalRel: { + prototype: SVGPathSegLinetoVerticalRel; + new (): SVGPathSegLinetoVerticalRel; +} + +interface SVGAnimatedString { + animVal: string; + baseVal: string; +} +declare var SVGAnimatedString: { + prototype: SVGAnimatedString; + new (): SVGAnimatedString; +} + +interface CDATASection extends Text { +} +declare var CDATASection: { + prototype: CDATASection; + new (): CDATASection; +} + +interface StyleMedia { + type: string; + matchMedium(mediaquery: string): boolean; +} +declare var StyleMedia: { + prototype: StyleMedia; + new (): StyleMedia; +} + +interface HTMLSelectElement extends HTMLElement, MSHTMLCollectionExtensions, MSDataBindingExtensions { + options: HTMLSelectElement; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Sets or retrieves the number of rows in the list box. + */ + size: number; + /** + * Sets or retrieves the number of objects in a collection. + */ + length: number; + /** + * Sets or retrieves the index of the selected option in a select object. + */ + selectedIndex: number; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ + type: string; + /** + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ + remove(index?: number): void; + /** + * Adds an element to the areas, controlRange, or options collection. + * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + */ + add(element: HTMLElement, before?: any): void; + /** + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(name?: any, index?: any): any; + /** + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ + namedItem(name: string): any; + [name: string]: any; +} +declare var HTMLSelectElement: { + prototype: HTMLSelectElement; + new (): HTMLSelectElement; +} + +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): boolean; + scrollIntoView(fStart?: boolean): void; + findText(string: string, count?: number, flags?: number): boolean; + execCommand(cmdID: string, showUI?: boolean, value?: any): boolean; + getBoundingClientRect(): ClientRect; + moveToBookmark(bookmark: string): boolean; + isEqual(range: TextRange): boolean; + duplicate(): TextRange; + collapse(start?: boolean): void; + queryCommandText(cmdID: string): string; + select(): void; + pasteHTML(html: string): void; + inRange(range: TextRange): boolean; + moveEnd(unit: string, count?: number): number; + getClientRects(): ClientRectList; + moveStart(unit: string, count?: number): number; + parentElement(): Element; + queryCommandState(cmdID: string): boolean; + compareEndPoints(how: string, sourceRange: TextRange): number; + execCommandShowHelp(cmdID: string): boolean; + moveToElementText(element: Element): void; + expand(Unit: string): boolean; + queryCommandSupported(cmdID: string): boolean; + setEndPoint(how: string, SourceRange: TextRange): void; + queryCommandEnabled(cmdID: string): boolean; +} +declare var TextRange: { + prototype: TextRange; + new (): TextRange; +} + +interface SVGTests { + requiredFeatures: SVGStringList; + requiredExtensions: SVGStringList; + systemLanguage: SVGStringList; + hasExtension(extension: string): boolean; +} + +interface HTMLBlockElement extends HTMLElement, DOML2DeprecatedTextFlowControl { + /** + * Sets or retrieves the width of the object. + */ + width: number; + /** + * Sets or retrieves reference information about the object. + */ + cite: string; +} +declare var HTMLBlockElement: { + prototype: HTMLBlockElement; + new (): HTMLBlockElement; +} + +interface CSSStyleSheet extends StyleSheet { + owningElement: Element; + imports: StyleSheetList; + isAlternate: boolean; + rules: MSCSSRuleList; + isPrefAlternate: boolean; + readOnly: boolean; + cssText: string; + ownerRule: CSSRule; + href: string; + cssRules: CSSRuleList; + id: string; + pages: StyleSheetPageList; + addImport(bstrURL: string, lIndex?: number): number; + addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; + insertRule(rule: string, index?: number): number; + removeRule(lIndex: number): void; + deleteRule(index?: number): void; + addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; + removeImport(lIndex: number): void; +} +declare var CSSStyleSheet: { + prototype: CSSStyleSheet; + new (): CSSStyleSheet; +} + +interface MSSelection { + type: string; + typeDetail: string; + createRange(): TextRange; + clear(): void; + createRangeCollection(): TextRangeCollection; + empty(): void; +} +declare var MSSelection: { + prototype: MSSelection; + new (): MSSelection; +} + +interface HTMLMetaElement extends HTMLElement { + /** + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ + httpEquiv: string; + /** + * Sets or retrieves the value specified in the content attribute of the meta object. + */ + name: string; + /** + * Gets or sets meta-information to associate with httpEquiv or name. + */ + content: string; + /** + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ + url: string; + /** + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ + scheme: string; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; +} +declare var HTMLMetaElement: { + prototype: HTMLMetaElement; + new (): HTMLMetaElement; +} + +interface SVGPatternElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGTests, SVGFitToViewBox, SVGExternalResourcesRequired, SVGURIReference { + patternUnits: SVGAnimatedEnumeration; + y: SVGAnimatedLength; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + patternContentUnits: SVGAnimatedEnumeration; + patternTransform: SVGAnimatedTransformList; + height: SVGAnimatedLength; +} +declare var SVGPatternElement: { + prototype: SVGPatternElement; + new (): SVGPatternElement; +} + +interface SVGAnimatedAngle { + animVal: SVGAngle; + baseVal: SVGAngle; +} +declare var SVGAnimatedAngle: { + prototype: SVGAnimatedAngle; + new (): SVGAnimatedAngle; +} + +interface Selection { + isCollapsed: boolean; + 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 SVGScriptElement extends SVGElement, SVGExternalResourcesRequired, SVGURIReference { + type: string; +} +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new (): SVGScriptElement; +} + +interface HTMLDDElement extends HTMLElement { + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; +} +declare var HTMLDDElement: { + prototype: HTMLDDElement; + new (): HTMLDDElement; +} + +interface MSDataBindingRecordSetReadonlyExtensions { + recordset: Object; + namedRecordset(dataMember: string, hierarchy?: any): Object; +} + +interface CSSStyleRule extends CSSRule { + selectorText: string; + style: MSStyleCSSProperties; + readOnly: boolean; +} +declare var CSSStyleRule: { + prototype: CSSStyleRule; + new (): CSSStyleRule; +} + +interface NodeIterator { + whatToShow: number; + filter: NodeFilter; + root: Node; + expandEntityReferences: boolean; + nextNode(): Node; + detach(): void; + previousNode(): Node; +} +declare var NodeIterator: { + prototype: NodeIterator; + new (): NodeIterator; +} + +interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox, SVGExternalResourcesRequired { + viewTarget: SVGStringList; +} +declare var SVGViewElement: { + prototype: SVGViewElement; + new (): SVGViewElement; +} + +interface HTMLLinkElement extends HTMLElement, LinkStyle { + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rev: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; +} +declare var HTMLLinkElement: { + prototype: HTMLLinkElement; + new (): HTMLLinkElement; +} + +interface SVGLocatable { + farthestViewportElement: SVGElement; + nearestViewportElement: SVGElement; + getBBox(): SVGRect; + getTransformToElement(element: SVGElement): SVGMatrix; + getCTM(): SVGMatrix; + getScreenCTM(): SVGMatrix; +} + +interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves the current typeface family. + */ + face: string; +} +declare var HTMLFontElement: { + prototype: HTMLFontElement; + new (): HTMLFontElement; +} + +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): boolean; + scrollIntoView(varargStart?: any): void; + item(index: number): Element; + [index: number]: Element; + execCommand(cmdID: string, showUI?: boolean, value?: any): boolean; + addElement(item: Element): void; + queryCommandState(cmdID: string): boolean; + queryCommandSupported(cmdID: string): boolean; + queryCommandEnabled(cmdID: string): boolean; + queryCommandText(cmdID: string): string; + select(): void; +} +declare var ControlRangeCollection: { + prototype: ControlRangeCollection; + new (): ControlRangeCollection; +} + +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 { + /** + * Sets or retrieves the alignment of the caption or legend. + */ + align: string; + /** + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ + vAlign: string; +} +declare var HTMLTableCaptionElement: { + prototype: HTMLTableCaptionElement; + new (): HTMLTableCaptionElement; +} + +interface HTMLOptionElement extends HTMLElement, MSDataBindingExtensions { + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + index: number; + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + /** + * Sets or retrieves the text string specified by the option tag. + */ + text: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; + create(): HTMLOptionElement; +} +declare var HTMLOptionElement: { + prototype: HTMLOptionElement; + new (): HTMLOptionElement; +} + +interface HTMLMapElement extends HTMLElement { + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Retrieves a collection of the area objects defined for the given map object. + */ + areas: HTMLAreasCollection; +} +declare var HTMLMapElement: { + prototype: HTMLMapElement; + new (): HTMLMapElement; +} + +interface HTMLMenuElement extends HTMLElement, DOML2DeprecatedListSpaceReduction { + type: string; +} +declare var HTMLMenuElement: { + prototype: HTMLMenuElement; + new (): HTMLMenuElement; +} + +interface MouseWheelEvent extends MouseEvent { + wheelDelta: number; + initMouseWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, 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 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 SVGAnimatedLengthList { + animVal: SVGLengthList; + baseVal: SVGLengthList; +} +declare var SVGAnimatedLengthList: { + prototype: SVGAnimatedLengthList; + new (): SVGAnimatedLengthList; +} + +interface Window extends EventTarget, MSEventAttachmentTarget, WindowLocalStorage, MSWindowExtensions, 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; + screenX: number; + onmouseover: (ev: MouseEvent) => any; + ondragleave: (ev: DragEvent) => any; + history: History; + pageXOffset: number; + 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; + innerHeight: number; + 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; + outerWidth: number; + onstalled: (ev: Event) => any; + onmousemove: (ev: MouseEvent) => any; + innerWidth: number; + onoffline: (ev: Event) => any; + length: number; + screen: Screen; + 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; + document: Document; + onprogress: (ev: any) => any; + ondblclick: (ev: MouseEvent) => any; + pageYOffset: number; + oncontextmenu: (ev: MouseEvent) => any; + onchange: (ev: Event) => any; + onloadedmetadata: (ev: Event) => any; + onplay: (ev: Event) => any; + onerror: ErrorEventHandler; + onplaying: (ev: Event) => any; + parent: Window; + location: Location; + oncanplaythrough: (ev: Event) => any; + onabort: (ev: UIEvent) => any; + onreadystatechange: (ev: Event) => any; + outerHeight: number; + 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; + onselect: (ev: UIEvent) => any; + navigator: Navigator; + styleMedia: StyleMedia; + ondrop: (ev: DragEvent) => any; + onmouseout: (ev: MouseEvent) => any; + onended: (ev: Event) => any; + onhashchange: (ev: Event) => any; + onunload: (ev: Event) => any; + onscroll: (ev: UIEvent) => any; + screenY: number; + onmousewheel: (ev: MouseWheelEvent) => any; + onload: (ev: Event) => any; + onvolumechange: (ev: Event) => any; + oninput: (ev: Event) => any; + performance: Performance; + alert(message?: any): void; + scroll(x?: number, y?: number): void; + focus(): void; + scrollTo(x?: number, y?: number): void; + print(): void; + prompt(message?: string, defaul?: string): string; + toString(): string; + open(url?: string, target?: string, features?: string, replace?: boolean): Window; + scrollBy(x?: number, y?: number): void; + confirm(message?: string): boolean; + close(): void; + postMessage(message: any, targetOrigin: string, ports?: any): void; + showModalDialog(url?: string, argument?: any, options?: any): any; + blur(): void; + getSelection(): Selection; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; +} +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 DOML2DeprecatedTextFlowControl { + clear: string; +} + +interface StyleSheetPageList { + length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new (): StyleSheetPageList; +} + +interface MSCSSProperties extends CSSStyleDeclaration { + 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; + getAttribute(attributeName: string, flags?: number): any; + setAttribute(attributeName: string, AttributeValue: any, flags?: number): void; + removeAttribute(attributeName: string, flags?: number): boolean; +} +declare var MSCSSProperties: { + prototype: MSCSSProperties; + new (): MSCSSProperties; +} + +interface HTMLCollection extends MSHTMLCollectionExtensions { + /** + * Sets or retrieves the number of objects in a collection. + */ + length: number; + /** + * Retrieves an object from various collections. + */ + item(nameOrIndex?: any, optionalIndex?: any): Element; + /** + * Retrieves a select object or an object from an options collection. + */ + namedItem(name: string): Element; + [name: number]: Element; +} +declare var HTMLCollection: { + prototype: HTMLCollection; + new (): HTMLCollection; +} + +interface SVGExternalResourcesRequired { + externalResourcesRequired: SVGAnimatedBoolean; +} + +interface HTMLImageElement extends HTMLElement, MSImageResourceExtensions, MSDataBindingExtensions, MSResourceMetadata { + /** + * Sets or retrieves the width of the object. + */ + width: number; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * The original height of the image resource before sizing. + */ + naturalHeight: number; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * The original width of the image resource before sizing. + */ + naturalWidth: number; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Sets or retrieves the height of the object. + */ + height: number; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + hspace: number; + /** + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ + longDesc: string; + /** + * Contains the hypertext reference (HREF) of the URL. + */ + href: string; + /** + * Sets or retrieves whether the image is a server-side image map. + */ + isMap: boolean; + /** + * Retrieves whether the object is fully loaded. + */ + complete: boolean; + create(): HTMLImageElement; +} +declare var HTMLImageElement: { + prototype: HTMLImageElement; + new (): HTMLImageElement; +} + +interface HTMLAreaElement extends HTMLElement { + /** + * Sets or retrieves the protocol portion of a URL. + */ + protocol: string; + /** + * Sets or retrieves the substring of the href property that follows the question mark. + */ + search: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + /** + * Sets or retrieves the host name part of the location or URL. + */ + hostname: string; + /** + * Sets or retrieves the port number associated with a URL. + */ + port: string; + /** + * Sets or retrieves the file name or path specified by the object. + */ + pathname: string; + /** + * Sets or retrieves the hostname and port number of the location or URL. + */ + host: string; + /** + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ + hash: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or gets whether clicks in this region cause action. + */ + noHref: boolean; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + /** + * Returns a string representation of an object. + */ + toString(): string; +} +declare var HTMLAreaElement: { + prototype: HTMLAreaElement; + new (): HTMLAreaElement; +} + +interface EventTarget { + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; + removeEventListener(type: string, listener: EventListener, useCapture?: boolean): void; + dispatchEvent(evt: Event): boolean; +} + +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, MSDataBindingExtensions { + /** + * Sets or retrieves the default or selected value of the control. + */ + value: string; + status: any; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets the classification and default behavior of the button. + */ + type: string; + /** + * Creates a TextRange object for the element. + */ + createTextRange(): TextRange; +} +declare var HTMLButtonElement: { + prototype: HTMLButtonElement; + new (): HTMLButtonElement; +} + +interface HTMLSourceElement extends HTMLElement { + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + /** + * Gets or sets the intended media type of the media source. + */ + media: string; + /** + * Gets or sets the MIME type of a media resource. + */ + 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 { + location: number; + keyCode: number; + shiftKey: boolean; + which: number; + locale: string; + key: string; + altKey: boolean; + metaKey: boolean; + char: string; + ctrlKey: boolean; + repeat: boolean; + charCode: number; + getModifierState(keyArg: string): boolean; + initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, 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, NodeSelector, MSEventAttachmentTarget, DocumentEvent, MSResourceMetadata, MSNodeExtensions { + /** + * Retrieves the collection of user agents and versions declared in the X-UA-Compatible + */ + compatible: MSCompatibleInfoCollection; + /** + * Fires when the user presses a key. + * @param ev The keyboard event + */ + onkeydown: (ev: KeyboardEvent) => any; + /** + * Fires when the user releases a key. + * @param ev The keyboard event + */ + onkeyup: (ev: KeyboardEvent) => any; + + /** + * Gets the implementation object of the current document. + */ + implementation: DOMImplementation; + /** + * Fires when the user resets a form. + * @param ev The event. + */ + onreset: (ev: Event) => any; + + /** + * Retrieves a collection of all script objects in the document. + */ + scripts: HTMLCollection; + + /** + * Fires when the user presses the F1 key while the browser is the active window. + * @param ev The event. + */ + onhelp: (ev: Event) => any; + + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ + ondragleave: (ev: DragEvent) => any; + + /** + * Gets or sets the character set used to encode the object. + */ + charset: string; + + /** + * Fires for an element just prior to setting focus on that element. + * @param ev The focus event + */ + onfocusin: (ev: FocusEvent) => any; + + + /** + * Sets or gets the color of the links that the user has visited. + */ + vlinkColor: string; + + /** + * Occurs when the seek operation ends. + * @param ev The event. + */ + onseeked: (ev: Event) => any; + + security: string; + + /** + * Contains the title of the document. + */ + title: string; + + /** + * Retrieves a collection of namespace objects. + */ + namespaces: MSNamespaceInfoCollection; + + /** + * Gets the default character set from the current regional language settings. + */ + defaultCharset: string; + + /** + * Retrieves a collection of all embed objects in the document. + */ + embeds: HTMLCollection; + + /** + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ + styleSheets: StyleSheetList; + + /** + * Retrieves a collection of all window objects defined by the given document or defined by the document associated with the given window. + */ + frames: Window; + + /** + * Occurs when the duration attribute is updated. + * @param ev The event. + */ + ondurationchange: (ev: Event) => any; + + + /** + * Returns a reference to the collection of elements contained by the object. + */ + all: HTMLCollection; + + /** + * Retrieves a collection, in source order, of all form objects in the document. + */ + forms: HTMLCollection; + + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ + onblur: (ev: FocusEvent) => any; + + + /** + * Sets or retrieves a value that indicates the reading order of the object. + */ + dir: string; + + /** + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ + onemptied: (ev: Event) => any; + + + /** + * Sets or gets a value that indicates whether the document can be edited. + */ + designMode: string; + + /** + * Occurs when the current playback position is moved. + * @param ev The event. + */ + onseeking: (ev: Event) => any; + + + /** + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ + ondeactivate: (ev: UIEvent) => any; + + + /** + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ + oncanplay: (ev: Event) => any; + + + /** + * Fires when the data set exposed by a data source object changes. + * @param ev The event. + */ + ondatasetchanged: (ev: MSEventObj) => any; + + + /** + * Fires when rows are about to be deleted from the recordset. + * @param ev The event + */ + onrowsdelete: (ev: MSEventObj) => any; + + Script: MSScriptHost; + + /** + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ + onloadstart: (ev: Event) => any; + + + /** + * Gets the URL for the document, stripped of any character encoding. + */ + URLUnencoded: string; + + defaultView: Window; + + /** + * Fires when the user is about to make a control selection of the object. + * @param ev The event. + */ + oncontrolselect: (ev: MSEventObj) => any; + + + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ + ondragenter: (ev: DragEvent) => any; + + onsubmit: (ev: Event) => any; + + /** + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ + inputEncoding: string; + + /** + * Gets the object that has the focus when the parent document has focus. + */ + activeElement: Element; + + /** + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ + onchange: (ev: Event) => any; + + + /** + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ + links: HTMLCollection; + + /** + * Retrieves an autogenerated, unique identifier for the object. + */ + uniqueID: string; + + /** + * Sets or gets the URL for the current document. + */ + URL: string; + + /** + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ + onbeforeactivate: (ev: UIEvent) => any; + + head: HTMLHeadElement; + cookie: string; + xmlEncoding: string; + oncanplaythrough: (ev: Event) => any; + + /** + * Retrieves the document compatibility mode of the document. + */ + documentMode: number; + + characterSet: string; + + /** + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ + anchors: HTMLCollection; + + onbeforeupdate: (ev: MSEventObj) => any; + + /** + * Fires to indicate that all data is available from the data source object. + * @param ev The event. + */ + ondatasetcomplete: (ev: MSEventObj) => any; + + plugins: HTMLCollection; + + /** + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ + onsuspend: (ev: Event) => any; + + + /** + * Gets the root svg element in the document hierarchy. + */ + rootElement: SVGSVGElement; + + /** + * Retrieves a value that indicates the current state of the object. + */ + readyState: string; + + /** + * Gets the URL of the location that referred the user to the current page. + */ + referrer: string; + + /** + * Sets or gets the color of all active links in the document. + */ + alinkColor: string; + + /** + * Fires on a databound object when an error occurs while updating the associated data in the data source object. + * @param ev The event. + */ + onerrorupdate: (ev: MSEventObj) => any; + + + /** + * Gets a reference to the container object of the window. + */ + parentWindow: Window; + + /** + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ + onmouseout: (ev: MouseEvent) => any; + + + /** + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ + onmsthumbnailclick: (ev: MSSiteModeEvent) => any; + + + /** + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ + onmousewheel: (ev: MouseWheelEvent) => any; + + + /** + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ + onvolumechange: (ev: Event) => any; + + + /** + * Fires when data changes in the data provider. + * @param ev The event. + */ + oncellchange: (ev: MSEventObj) => any; + + + /** + * Fires just before the data source control changes the current row in the object. + * @param ev The event. + */ + onrowexit: (ev: MSEventObj) => any; + + + /** + * Fires just after new rows are inserted in the current recordset. + * @param ev The event. + */ + onrowsinserted: (ev: MSEventObj) => any; + + + /** + * Gets or sets the version attribute specified in the declaration of an XML document. + */ + xmlVersion: string; + + msCapsLockWarningOff: boolean; + + /** + * Fires when a property changes on the object. + * @param ev The event. + */ + onpropertychange: (ev: MSEventObj) => any; + + + /** + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ + ondragend: (ev: DragEvent) => any; + + + /** + * Gets an object representing the document type declaration associated with the current document. + */ + doctype: DocumentType; + + /** + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ + ondragover: (ev: DragEvent) => any; + + + /** + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ + bgColor: string; + + /** + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ + ondragstart: (ev: DragEvent) => any; + + + /** + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ + onmouseup: (ev: MouseEvent) => any; + + + /** + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ + ondrag: (ev: DragEvent) => any; + + + /** + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ + onmouseover: (ev: MouseEvent) => any; + + + /** + * Sets or gets the color of the document links. + */ + linkColor: string; + + /** + * Occurs when playback is paused. + * @param ev The event. + */ + onpause: (ev: Event) => any; + + + /** + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ + onmousedown: (ev: MouseEvent) => any; + + + /** + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ + onclick: (ev: MouseEvent) => any; + + + /** + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ + onwaiting: (ev: Event) => any; + + + /** + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ + onstop: (ev: Event) => any; + + /** + * false (false)[rolls + */ + + /** + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ + onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; + + + /** + * Retrieves a collection of all applet objects in the document. + */ + applets: HTMLCollection; + + /** + * Specifies the beginning and end of the document body. + */ + body: HTMLElement; + + /** + * Sets or gets the security domain of the document. + */ + domain: string; + + xmlStandalone: boolean; + + /** + * Represents the active selection, which is a highlighted block of text or other elements in the document that a user or a script can carry out some action on. + */ + selection: MSSelection; + + /** + * Occurs when the download has stopped. + * @param ev The event. + */ + onstalled: (ev: Event) => any; + + + /** + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ + onmousemove: (ev: MouseEvent) => any; + + + /** + * Gets a reference to the root node of the document. + */ + documentElement: HTMLElement; + + /** + * Fires before an object contained in an editable element enters a UI-activated state or when an editable container object is control selected. + * @param ev The event. + */ + onbeforeeditfocus: (ev: MSEventObj) => any; + + + /** + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ + onratechange: (ev: Event) => any; + + + /** + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ + onprogress: (ev: any) => any; + + + /** + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ + ondblclick: (ev: MouseEvent) => any; + + + /** + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ + oncontextmenu: (ev: MouseEvent) => any; + + + /** + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ + onloadedmetadata: (ev: Event) => any; + + media: string; + + /** + * Fires when an error occurs during object loading. + * @param ev The event. + */ + onerror: (ev: Event) => any; + + + /** + * Occurs when the play method is requested. + * @param ev The event. + */ + onplay: (ev: Event) => any; + + onafterupdate: (ev: MSEventObj) => any; + + /** + * Occurs when the audio or video has started playing. + * @param ev The event. + */ + onplaying: (ev: Event) => any; + + + /** + * Retrieves a collection, in source order, of img objects in the document. + */ + images: HTMLCollection; + + /** + * Contains information about the current URL. + */ + location: Location; + + /** + * Fires when the user aborts the download. + * @param ev The event. + */ + onabort: (ev: UIEvent) => any; + + + /** + * Fires for the current element with focus immediately after moving focus to another element. + * @param ev The event. + */ + onfocusout: (ev: FocusEvent) => any; + + + /** + * Fires when the selection state of a document changes. + * @param ev The event. + */ + onselectionchange: (ev: Event) => any; + + + /** + * Fires when a local DOM Storage area is written to disk. + * @param ev The event. + */ + onstoragecommit: (ev: StorageEvent) => any; + + + /** + * Fires periodically as data arrives from data source objects that asynchronously transmit their data. + * @param ev The event. + */ + ondataavailable: (ev: MSEventObj) => any; + + + /** + * Fires when the state of the object has changed. + * @param ev The event + */ + onreadystatechange: (ev: Event) => any; + + + /** + * Gets the date that the page was last modified, if the page supplies one. + */ + lastModified: string; + + /** + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ + onkeypress: (ev: KeyboardEvent) => any; + + + /** + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ + onloadeddata: (ev: Event) => any; + + + /** + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ + onbeforedeactivate: (ev: UIEvent) => any; + + + /** + * Fires when the object is set as the active element. + * @param ev The event. + */ + onactivate: (ev: UIEvent) => any; + + + onselectstart: (ev: Event) => any; + + /** + * Fires when the object receives focus. + * @param ev The event. + */ + onfocus: (ev: FocusEvent) => any; + + + /** + * Sets or gets the foreground (text) color of the document. + */ + fgColor: string; + + /** + * Occurs to indicate the current playback position. + * @param ev The event. + */ + ontimeupdate: (ev: Event) => any; + + + /** + * Fires when the current selection changes. + * @param ev The event. + */ + onselect: (ev: UIEvent) => any; + + ondrop: (ev: DragEvent) => any; + + /** + * Occurs when the end of playback is reached. + * @param ev The event + */ + onended: (ev: Event) => any; + + + /** + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ + compatMode: string; + + /** + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ + onscroll: (ev: UIEvent) => any; + + + /** + * Fires to indicate that the current row has changed in the data source and new data values are available on the object. + * @param ev The event. + */ + onrowenter: (ev: MSEventObj) => any; + + + /** + * Fires immediately after the browser loads the object. + * @param ev The event. + */ + onload: (ev: Event) => any; + + oninput: (ev: Event) => any; + + /** + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ + queryCommandValue(commandId: string): string; + + adoptNode(source: Node): Node; + + /** + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ + queryCommandIndeterm(commandId: string): boolean; + + getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList; + createProcessingInstruction(target: string, data: string): ProcessingInstruction; + + /** + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ + execCommand(commandId: string, showUI?: boolean, value?: any): boolean; + + /** + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ + elementFromPoint(x: number, y: number): Element; + createCDATASection(data: string): CDATASection; + + /** + * Retrieves the string associated with a command. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + */ + queryCommandText(commandId: string): string; + + /** + * Writes one or more HTML expressions to a document in the specified window. + * @param content Specifies the text and HTML tags to write. + */ + write(...content: string[]): void; + + /** + * Allows updating the print settings for the page. + */ + updateSettings(): void; + + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "a"): HTMLAnchorElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "abbr"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "address"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "area"): HTMLAreaElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "article"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "aside"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "audio"): HTMLAudioElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "b"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "base"): HTMLBaseElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "bdi"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "bdo"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "blockquote"): HTMLQuoteElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "body"): HTMLBodyElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "br"): HTMLBRElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "button"): HTMLButtonElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "canvas"): HTMLCanvasElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "caption"): HTMLTableCaptionElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "cite"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "code"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "col"): HTMLTableColElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "colgroup"): HTMLTableColElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "datalist"): HTMLDataListElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "dd"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "del"): HTMLModElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "dfn"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "div"): HTMLDivElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "dl"): HTMLDListElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "dt"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "em"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "embed"): HTMLEmbedElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "fieldset"): HTMLFieldSetElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "figcaption"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "figure"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "footer"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "form"): HTMLFormElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "h1"): HTMLHeadingElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "h2"): HTMLHeadingElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "h3"): HTMLHeadingElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "h4"): HTMLHeadingElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "h5"): HTMLHeadingElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "h6"): HTMLHeadingElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "head"): HTMLHeadElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "header"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "hgroup"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "hr"): HTMLHRElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "html"): HTMLHtmlElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "i"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "iframe"): HTMLIFrameElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "img"): HTMLImageElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "input"): HTMLInputElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "ins"): HTMLModElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "kbd"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "label"): HTMLLabelElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "legend"): HTMLLegendElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "li"): HTMLLIElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "link"): HTMLLinkElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "main"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "map"): HTMLMapElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "mark"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "menu"): HTMLMenuElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "meta"): HTMLMetaElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "nav"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "noscript"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "object"): HTMLObjectElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "ol"): HTMLOListElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "optgroup"): HTMLOptGroupElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "option"): HTMLOptionElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "p"): HTMLParagraphElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "param"): HTMLParamElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "pre"): HTMLPreElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "progress"): HTMLProgressElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "q"): HTMLQuoteElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "rp"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "rt"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "ruby"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "s"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "samp"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "script"): HTMLScriptElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "section"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "select"): HTMLSelectElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "small"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "source"): HTMLSourceElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "span"): HTMLSpanElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "strong"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "style"): HTMLStyleElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "sub"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "summary"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "sup"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "table"): HTMLTableElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "tbody"): HTMLTableSectionElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "td"): HTMLTableDataCellElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "textarea"): HTMLTextAreaElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "tfoot"): HTMLTableSectionElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "th"): HTMLTableHeaderCellElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "thead"): HTMLTableSectionElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "title"): HTMLTitleElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "tr"): HTMLTableRowElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "track"): HTMLTrackElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "u"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "ul"): HTMLUListElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "var"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "video"): HTMLVideoElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "wbr"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: string): HTMLElement; + + /** + * Removes mouse capture from the object in the current document. + */ + releaseCapture(): void; + + /** + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * @param content The text and HTML tags to write. + */ + writeln(...content: string[]): void; + createElementNS(namespaceURI: string, qualifiedName: string): Element; + + /** + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @param replace Specifies whether the existing entry for the document is replaced in the history list. + */ + open(url?: string, name?: string, features?: string, replace?: boolean): any; + + /** + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ + queryCommandSupported(commandId: string): boolean; + + /** + * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + createTreeWalker(root: Node, whatToShow: number, filter: NodeFilter, entityReferenceExpansion: boolean): TreeWalker; + createAttributeNS(namespaceURI: string, qualifiedName: string): Attr; + + /** + * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. + * @param commandId Specifies a command identifier. + */ + queryCommandEnabled(commandId: string): boolean; + + /** + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ + focus(): void; + + /** + * Closes an output stream and forces the sent data to display. + */ + close(): void; + + getElementsByClassName(classNames: string): NodeList; + importNode(importedNode: Node, deep: boolean): Node; + + /** + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + */ + createRange(): Range; + + /** + * Fires a specified event on the object. + * @param eventName Specifies the name of the event to fire. + * @param eventObj Object that specifies the event object from which to obtain event object properties. + */ + fireEvent(eventName: string, eventObj?: any): boolean; + + /** + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ + createComment(data: string): Comment; + + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "a"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "abbr"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "address"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "area"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "article"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "aside"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "audio"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "b"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "base"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "bdi"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "bdo"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "blockquote"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "body"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "br"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "button"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "canvas"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "caption"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "cite"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "code"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "col"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "colgroup"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "datalist"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "dd"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "del"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "dfn"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "div"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "dl"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "dt"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "em"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "embed"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "fieldset"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "figcaption"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "figure"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "footer"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "form"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "h1"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "h2"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "h3"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "h4"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "h5"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "h6"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "head"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "header"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "hgroup"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "hr"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "html"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "i"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "iframe"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "img"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "input"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "ins"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "kbd"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "label"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "legend"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "li"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "link"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "main"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "map"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "mark"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "menu"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "meta"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "nav"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "noscript"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "object"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "ol"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "optgroup"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "option"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "p"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "param"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "pre"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "progress"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "q"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "rp"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "rt"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "ruby"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "s"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "samp"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "script"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "section"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "select"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "small"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "source"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "span"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "strong"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "style"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "sub"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "summary"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "sup"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "table"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "tbody"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "td"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "textarea"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "tfoot"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "th"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "thead"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "title"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "tr"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "track"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "u"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "ul"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "var"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "video"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "wbr"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: string): NodeList; + + /** + * Creates a new document. + */ + createDocumentFragment(): DocumentFragment; + + /** + * Creates a style sheet for the document. + * @param href Specifies how to add the style sheet to the document. If a file name is specified for the URL, the style information is added as a link object. If the URL contains style information, it is added to the style object. + * @param index Specifies the index that indicates where the new style sheet is inserted in the styleSheets collection. The default is to insert the new style sheet at the end of the collection. + */ + createStyleSheet(href?: string, index?: number): CSSStyleSheet; + + /** + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ + getElementsByName(elementName: string): NodeList; + + /** + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ + queryCommandState(commandId: string): boolean; + + /** + * Gets a value indicating whether the object currently has focus. + */ + hasFocus(): boolean; + + /** + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ + execCommandShowHelp(commandId: string): boolean; + + /** + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ + createAttribute(name: string): Attr; + + /** + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ + createTextNode(data: string): Text; + + /** + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + createNodeIterator(root: Node, whatToShow: number, filter: NodeFilter, entityReferenceExpansion: boolean): NodeIterator; + + /** + * Generates an event object to pass event context information when you use the fireEvent method. + * @param eventObj An object that specifies an existing event object on which to base the new object. + */ + createEventObject(eventObj?: any): MSEventObj; + + /** + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ + getSelection(): Selection; + + /** + * Returns a reference to the first object with the specified value of the ID or NAME attribute. + * @param elementId String that specifies the ID value. Case-insensitive. + */ + 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: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} +declare var MessageEvent: { + prototype: MessageEvent; + new (): MessageEvent; +} + +interface SVGElement extends Element { + onmouseover: (ev: MouseEvent) => any; + viewportElement: SVGElement; + onmousemove: (ev: MouseEvent) => any; + onmouseout: (ev: MouseEvent) => any; + ondblclick: (ev: MouseEvent) => any; + onfocusout: (ev: FocusEvent) => any; + onfocusin: (ev: FocusEvent) => any; + xmlbase: string; + onmousedown: (ev: MouseEvent) => any; + onload: (ev: Event) => any; + onmouseup: (ev: MouseEvent) => any; + onclick: (ev: MouseEvent) => any; + ownerSVGElement: SVGSVGElement; + id: string; +} +declare var SVGElement: { + prototype: SVGElement; + new (): SVGElement; +} + +interface HTMLScriptElement extends HTMLElement { + /** + * Sets or retrieves the status of the script. + */ + defer: boolean; + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + /** + * Retrieves the URL to an external file that contains the source code or data. + */ + src: string; + /** + * Sets or retrieves the object that is bound to the event script. + */ + htmlFor: string; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the MIME type for the associated scripting engine. + */ + type: string; + /** + * Sets or retrieves the event for which the script is written. + */ + event: string; +} +declare var HTMLScriptElement: { + prototype: HTMLScriptElement; + new (): HTMLScriptElement; +} + +interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment, DOML2DeprecatedBackgroundColorStyle { + /** + * Retrieves the position of the object in the rows collection for the table. + */ + rowIndex: number; + /** + * Retrieves a collection of all cells in the table row. + */ + cells: HTMLCollection; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves the color for one of the two colors used to draw the 3-D border of the object. + */ + borderColorLight: any; + /** + * Retrieves the position of the object in the collection. + */ + sectionRowIndex: number; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves the color for one of the two colors used to draw the 3-D border of the object. + */ + borderColorDark: any; + /** + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ + deleteCell(index?: number): void; + /** + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ + insertCell(index?: number): HTMLElement; +} +declare var HTMLTableRowElement: { + prototype: HTMLTableRowElement; + new (): HTMLTableRowElement; +} + +interface CanvasRenderingContext2D { + miterLimit: number; + font: string; + globalCompositeOperation: string; + msFillRule: string; + lineCap: string; + msImageSmoothingEnabled: boolean; + lineDashOffset: number; + shadowColor: string; + lineJoin: string; + shadowOffsetX: number; + lineWidth: number; + canvas: HTMLCanvasElement; + strokeStyle: any; + globalAlpha: number; + shadowOffsetY: number; + fillStyle: any; + shadowBlur: number; + textAlign: string; + textBaseline: 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?: boolean): void; + measureText(text: string): TextMetrics; + isPointInPath(x: number, y: number, fillRule?: string): boolean; + 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; + getLineDash(): Array; + fill(fillRule?: string): void; + createImageData(imageDataOrSw: any, sh?: number): ImageData; + createPattern(image: HTMLElement, repetition: string): CanvasPattern; + closePath(): void; + rect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: string): void; + 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; + setLineDash(segments: Array): 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 MSCSSRuleList { + length: number; + item(index?: number): CSSStyleRule; + [index: number]: CSSStyleRule; +} +declare var MSCSSRuleList: { + prototype: MSCSSRuleList; + new (): MSCSSRuleList; +} + +interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { + x: number; +} +declare var SVGPathSegLinetoHorizontalAbs: { + prototype: SVGPathSegLinetoHorizontalAbs; + new (): SVGPathSegLinetoHorizontalAbs; +} + +interface SVGPathSegArcAbs extends SVGPathSeg { + y: number; + sweepFlag: boolean; + r2: number; + x: number; + angle: number; + r1: number; + largeArcFlag: boolean; +} +declare var SVGPathSegArcAbs: { + prototype: SVGPathSegArcAbs; + new (): SVGPathSegArcAbs; +} + +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 HTMLHtmlElement extends HTMLElement { + /** + * Sets or retrieves the DTD version that governs the current document. + */ + version: string; +} +declare var HTMLHtmlElement: { + prototype: HTMLHtmlElement; + new (): HTMLHtmlElement; +} + +interface SVGPathSegClosePath extends SVGPathSeg { +} +declare var SVGPathSegClosePath: { + prototype: SVGPathSegClosePath; + new (): SVGPathSegClosePath; +} + +interface HTMLFrameElement extends HTMLElement, GetSVGDocument, MSDataBindingExtensions { + /** + * Sets or retrieves the width of the object. + */ + width: any; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + scrolling: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + marginWidth: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + noResize: boolean; + /** + * Retrieves the object of the specified. + */ + contentWindow: Window; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Retrieves the document object of the page or frame. + */ + contentDocument: Document; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Sets or retrieves a URI to a long description of the object. + */ + longDesc: string; + /** + * Raised when the object has been completely received from the server. + */ + onload: (ev: Event) => any; + /** + * Sets the value indicating whether the source file of a frame or iframe has specific security restrictions applied. + */ + security: any; +} +declare var HTMLFrameElement: { + prototype: HTMLFrameElement; + new (): HTMLFrameElement; +} + +interface SVGAnimatedLength { + animVal: SVGLength; + baseVal: SVGLength; +} +declare var SVGAnimatedLength: { + prototype: SVGAnimatedLength; + new (): SVGAnimatedLength; +} + +interface SVGAnimatedPoints { + points: SVGPointList; + animatedPoints: SVGPointList; +} + +interface SVGDefsElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { +} +declare var SVGDefsElement: { + prototype: SVGDefsElement; + new (): SVGDefsElement; +} + +interface HTMLQuoteElement extends HTMLElement { + /** + * Sets or retrieves the date and time of a modification to the object. + */ + dateTime: string; + /** + * Sets or retrieves reference information about the object. + */ + cite: string; +} +declare var HTMLQuoteElement: { + prototype: HTMLQuoteElement; + new (): HTMLQuoteElement; +} + +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 WindowModal { + dialogArguments: any; + returnValue: any; +} + +interface XMLHttpRequest extends EventTarget { + responseBody: any; + status: number; + readyState: number; + responseText: string; + responseXML: Document; + ontimeout: (ev: Event) => any; + statusText: string; + onreadystatechange: (ev: Event) => any; + timeout: number; + onload: (ev: Event) => any; + open(method: string, url: string, async?: boolean, user?: string, password?: string): void; + create(): XMLHttpRequest; + 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 { + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; +} +declare var HTMLTableHeaderCellElement: { + prototype: HTMLTableHeaderCellElement; + new (): HTMLTableHeaderCellElement; +} + +interface HTMLDListElement extends HTMLElement, DOML2DeprecatedListSpaceReduction { +} +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new (): HTMLDListElement; +} + +interface MSDataBindingExtensions { + dataSrc: string; + dataFormatAs: string; + dataFld: string; +} + +interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { + x: number; +} +declare var SVGPathSegLinetoHorizontalRel: { + prototype: SVGPathSegLinetoHorizontalRel; + new (): SVGPathSegLinetoHorizontalRel; +} + +interface SVGEllipseElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { + ry: SVGAnimatedLength; + cx: SVGAnimatedLength; + rx: SVGAnimatedLength; + cy: SVGAnimatedLength; +} +declare var SVGEllipseElement: { + prototype: SVGEllipseElement; + new (): SVGEllipseElement; +} + +interface SVGAElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired, SVGURIReference { + target: SVGAnimatedString; +} +declare var SVGAElement: { + prototype: SVGAElement; + new (): SVGAElement; +} + +interface SVGStylable { + className: SVGAnimatedString; + style: CSSStyleDeclaration; +} + +interface SVGTransformable extends SVGLocatable { + transform: SVGAnimatedTransformList; +} + +interface HTMLFrameSetElement extends HTMLElement { + ononline: (ev: Event) => any; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves the frame heights of the object. + */ + rows: string; + /** + * Sets or retrieves the frame widths of the object. + */ + cols: string; + /** + * Fires when the object loses the input focus. + */ + onblur: (ev: FocusEvent) => any; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Fires when the object receives focus. + */ + onfocus: (ev: FocusEvent) => any; + onmessage: (ev: MessageEvent) => any; + onerror: (ev: Event) => any; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + onresize: (ev: UIEvent) => any; + name: string; + onafterprint: (ev: Event) => any; + onbeforeprint: (ev: Event) => any; + onoffline: (ev: Event) => any; + border: string; + onunload: (ev: Event) => any; + onhashchange: (ev: Event) => any; + onload: (ev: Event) => any; + onbeforeunload: (ev: BeforeUnloadEvent) => any; + onstorage: (ev: StorageEvent) => any; +} +declare var HTMLFrameSetElement: { + prototype: HTMLFrameSetElement; + new (): HTMLFrameSetElement; +} + +interface Screen { + width: number; + deviceXDPI: number; + fontSmoothingEnabled: boolean; + bufferDepth: number; + logicalXDPI: number; + systemXDPI: number; + availHeight: number; + height: number; + logicalYDPI: number; + systemYDPI: number; + updateInterval: number; + colorDepth: number; + availWidth: number; + deviceYDPI: number; + pixelDepth: number; +} +declare var Screen: { + prototype: Screen; + new (): Screen; +} + +interface Coordinates { + altitudeAccuracy: number; + longitude: number; + latitude: number; + speed: number; + heading: number; + altitude: number; + accuracy: number; +} +declare var Coordinates: { + prototype: Coordinates; + new (): Coordinates; +} + +interface NavigatorGeolocation { + geolocation: Geolocation; +} + +interface NavigatorContentUtils { +} + +interface EventListener { + (evt: Event): void; +} + +interface SVGLangSpace { + xmllang: string; + xmlspace: string; +} + +interface DataTransfer { + effectAllowed: string; + dropEffect: string; + clearData(format?: string): boolean; + setData(format: string, data: string): boolean; + getData(format: string): string; +} +declare var DataTransfer: { + prototype: DataTransfer; + new (): DataTransfer; +} + +interface FocusEvent extends UIEvent { + relatedTarget: EventTarget; + initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void; +} +declare var FocusEvent: { + prototype: FocusEvent; + new (): FocusEvent; +} + +interface Range { + startOffset: number; + collapsed: boolean; + 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: boolean): 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 SVGPoint { + y: number; + x: number; + matrixTransform(matrix: SVGMatrix): SVGPoint; +} +declare var SVGPoint: { + prototype: SVGPoint; + new (): SVGPoint; +} + +interface MSPluginsCollection { + length: number; + refresh(reload?: boolean): void; +} +declare var MSPluginsCollection: { + prototype: MSPluginsCollection; + new (): MSPluginsCollection; +} + +interface SVGAnimatedNumberList { + animVal: SVGNumberList; + baseVal: SVGNumberList; +} +declare var SVGAnimatedNumberList: { + prototype: SVGAnimatedNumberList; + new (): SVGAnimatedNumberList; +} + +interface SVGSVGElement extends SVGElement, SVGStylable, SVGZoomAndPan, DocumentEvent, SVGLangSpace, SVGLocatable, SVGTests, SVGFitToViewBox, SVGExternalResourcesRequired { + width: SVGAnimatedLength; + x: SVGAnimatedLength; + contentStyleType: string; + onzoom: (ev: any) => any; + y: SVGAnimatedLength; + viewport: SVGRect; + onerror: (ev: Event) => any; + pixelUnitToMillimeterY: number; + onresize: (ev: UIEvent) => any; + screenPixelToMillimeterY: number; + height: SVGAnimatedLength; + onabort: (ev: UIEvent) => any; + contentScriptType: string; + pixelUnitToMillimeterX: number; + currentTranslate: SVGPoint; + onunload: (ev: Event) => any; + currentScale: number; + onscroll: (ev: UIEvent) => any; + screenPixelToMillimeterX: number; + setCurrentTime(seconds: number): void; + createSVGLength(): SVGLength; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeList; + unpauseAnimations(): void; + createSVGRect(): SVGRect; + checkIntersection(element: SVGElement, rect: SVGRect): boolean; + 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): boolean; + createSVGMatrix(): SVGMatrix; + createSVGPoint(): SVGPoint; + createSVGNumber(): SVGNumber; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; + getElementById(elementId: string): Element; +} +declare var SVGSVGElement: { + prototype: SVGSVGElement; + new (): SVGSVGElement; +} + +interface HTMLLabelElement extends HTMLElement, MSDataBindingExtensions { + /** + * Sets or retrieves the object to which the given label object is assigned. + */ + htmlFor: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + 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 HTMLLegendElement extends HTMLElement, MSDataBindingExtensions { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + align: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; +} +declare var HTMLLegendElement: { + prototype: HTMLLegendElement; + new (): HTMLLegendElement; +} + +interface HTMLDirectoryElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, DOML2DeprecatedListNumberingAndBulletStyle { +} +declare var HTMLDirectoryElement: { + prototype: HTMLDirectoryElement; + new (): HTMLDirectoryElement; +} + +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 { + /** + * Sets or retrieves the value of a list item. + */ + value: number; +} +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new (): HTMLLIElement; +} + +interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { + y: number; +} +declare var SVGPathSegLinetoVerticalAbs: { + prototype: SVGPathSegLinetoVerticalAbs; + new (): SVGPathSegLinetoVerticalAbs; +} + +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 MSHTMLCollectionExtensions { + urns(urn: any): Object; + tags(tagName: any): Object; +} + +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 HTMLIFrameElement extends HTMLElement, GetSVGDocument, MSDataBindingExtensions { + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + scrolling: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + marginWidth: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + noResize: boolean; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Retrieves the object of the specified. + */ + contentWindow: Window; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Retrieves the document object of the page or frame. + */ + contentDocument: Document; + /** + * Sets or retrieves the horizontal margin for the object. + */ + hspace: number; + /** + * Sets or retrieves a URI to a long description of the object. + */ + longDesc: string; + /** + * Sets the value indicating whether the source file of a frame or iframe has specific security restrictions applied. + */ + security: any; + /** + * Raised when the object has been completely received from the server. + */ + onload: (ev: Event) => any; +} +declare var HTMLIFrameElement: { + prototype: HTMLIFrameElement; + new (): HTMLIFrameElement; +} + +interface TextRangeCollection { + length: number; + item(index: number): TextRange; + [index: number]: TextRange; +} +declare var TextRangeCollection: { + prototype: TextRangeCollection; + new (): TextRangeCollection; +} + +interface HTMLBodyElement extends HTMLElement, DOML2DeprecatedBackgroundStyle, DOML2DeprecatedBackgroundColorStyle { + scroll: string; + ononline: (ev: Event) => any; + onblur: (ev: FocusEvent) => any; + noWrap: boolean; + onfocus: (ev: FocusEvent) => any; + onmessage: (ev: MessageEvent) => any; + text: any; + onerror: (ev: Event) => any; + bgProperties: string; + onresize: (ev: UIEvent) => any; + link: any; + aLink: any; + bottomMargin: any; + topMargin: any; + onafterprint: (ev: Event) => any; + vLink: any; + onbeforeprint: (ev: Event) => any; + onoffline: (ev: Event) => any; + onunload: (ev: Event) => any; + onhashchange: (ev: Event) => any; + onload: (ev: Event) => any; + rightMargin: any; + onbeforeunload: (ev: BeforeUnloadEvent) => any; + leftMargin: any; + onstorage: (ev: StorageEvent) => any; + createTextRange(): TextRange; +} +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 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: boolean, cancelableArg: boolean, 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: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; +} +declare var DragEvent: { + prototype: DragEvent; + new (): DragEvent; +} + +interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment, DOML2DeprecatedBackgroundColorStyle { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: HTMLCollection; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index?: number): void; + /** + * Moves a table row to a new position. + * @param indexFrom Number that specifies the index in the rows collection of the table row that is moved. + * @param indexTo Number that specifies where the row is moved within the rows collection. + */ + moveRow(indexFrom?: number, indexTo?: number): Object; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLElement; +} +declare var HTMLTableSectionElement: { + prototype: HTMLTableSectionElement; + new (): HTMLTableSectionElement; +} + +interface DOML2DeprecatedListNumberingAndBulletStyle { + type: string; +} + +interface HTMLInputElement extends HTMLElement, MSDataBindingExtensions { + /** + * Sets or retrieves the width of the object. + */ + width: string; + status: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + indeterminate: boolean; + readOnly: boolean; + size: number; + loop: number; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Sets or retrieves the URL of the virtual reality modeling language (VRML) world to be displayed in the window. + */ + vrml: string; + /** + * Sets or retrieves a lower resolution image to display. + */ + lowsrc: string; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Sets or retrieves a comma-separated list of content types. + */ + accept: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves the state of the check box or radio button. + */ + defaultChecked: boolean; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Returns the value of the data at the cursor's current position. + */ + value: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + border: string; + dynsrc: string; + /** + * Sets or retrieves the state of the check box or radio button. + */ + checked: boolean; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + hspace: number; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + /** + * Retrieves whether the object is fully loaded. + */ + complete: boolean; + start: string; + /** + * Creates a TextRange object for the element. + */ + createTextRange(): TextRange; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ + setSelectionRange(start: number, end: number): void; + /** + * Makes the selection equal to the current object. + */ + select(): void; +} +declare var HTMLInputElement: { + prototype: HTMLInputElement; + new (): HTMLInputElement; +} + +interface HTMLAnchorElement extends HTMLElement, MSDataBindingExtensions { + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + /** + * Contains the protocol of the URL. + */ + protocol: string; + /** + * Sets or retrieves the substring of the href property that follows the question mark. + */ + search: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + /** + * Contains the hostname of a URL. + */ + hostname: string; + /** + * Contains the pathname of the URL. + */ + pathname: string; + Methods: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + protocolLong: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the shape of the object. + */ + name: string; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; + /** + * Sets or retrieves the port number associated with a URL. + */ + port: string; + /** + * Contains the hostname and port values of the URL. + */ + host: string; + /** + * Contains the anchor portion of the URL including the hash sign (#). + */ + hash: string; + nameProp: string; + urn: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rev: string; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + type: string; + mimeType: string; + /** + * Returns a string representation of an object. + */ + toString(): string; +} +declare var HTMLAnchorElement: { + prototype: HTMLAnchorElement; + new (): HTMLAnchorElement; +} + +interface HTMLParamElement extends HTMLElement { + /** + * Sets or retrieves the value of an input parameter for an element. + */ + value: string; + /** + * Sets or retrieves the name of an input parameter for an element. + */ + name: string; + /** + * Sets or retrieves the content type of the resource designated by the value attribute. + */ + type: string; + /** + * Sets or retrieves the data type of the value attribute. + */ + valueType: string; +} +declare var HTMLParamElement: { + prototype: HTMLParamElement; + new (): HTMLParamElement; +} + +interface SVGImageElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired, SVGURIReference { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGImageElement: { + prototype: SVGImageElement; + new (): SVGImageElement; +} + +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 HTMLPreElement extends HTMLElement, DOML2DeprecatedTextFlowControl { + /** + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ + width: number; + /** + * Indicates a citation by rendering text in italic type. + */ + cite: string; +} +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 MSNavigatorDoNotTrack { + msDoNotTrack: string; +} + +interface NavigatorOnLine { + onLine: boolean; +} + +interface WindowLocalStorage { + localStorage: Storage; +} + +interface SVGMetadataElement extends SVGElement { +} +declare var SVGMetadataElement: { + prototype: SVGMetadataElement; + new (): SVGMetadataElement; +} + +interface SVGPathSegArcRel extends SVGPathSeg { + y: number; + sweepFlag: boolean; + r2: number; + x: number; + angle: number; + r1: number; + largeArcFlag: boolean; +} +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; + create(): XDomainRequest; + 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, SVGExternalResourcesRequired { +} +declare var SVGPolygonElement: { + prototype: SVGPolygonElement; + new (): SVGPolygonElement; +} + +interface HTMLPhraseElement extends HTMLElement { + /** + * Sets or retrieves the date and time of a modification to the object. + */ + dateTime: string; + /** + * Sets or retrieves reference information about the object. + */ + cite: string; +} +declare var HTMLPhraseElement: { + prototype: HTMLPhraseElement; + new (): HTMLPhraseElement; +} + +interface NavigatorStorageUtils { +} + +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 extends Event { + 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: boolean; + altLeft: boolean; + behaviorCookie: number; + bookmarks: BookmarkCollection; + type: string; + repeat: boolean; + srcElement: Element; + source: Window; + fromElement: Element; + offsetY: number; + x: number; + behaviorPart: number; + qualifier: string; + altKey: boolean; + ctrlKey: boolean; + clientY: number; + shiftKey: boolean; + shiftLeft: boolean; + contentOverflow: boolean; + screenY: number; + ctrlLeft: boolean; + 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): boolean; +} +declare var MSEventObj: { + prototype: MSEventObj; + new (): MSEventObj; +} + +interface SVGTextContentElement extends SVGElement, SVGStylable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { + 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 HTMLCanvasElement extends HTMLElement { + /** + * Gets or sets the width of a canvas element on a document. + */ + width: number; + /** + * Gets or sets the height of a canvas element on a document. + */ + height: number; + /** + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. + */ + toDataURL(type?: string, ...args: any[]): string; + /** + * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. + * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); + */ + getContext(contextId: "2d"): CanvasRenderingContext2D; + getContext(contextId: "experimental-webgl"): WebGLRenderingContext; + getContext(contextId: string, ...args: any[]): any; +} +declare var HTMLCanvasElement: { + prototype: HTMLCanvasElement; + new (): HTMLCanvasElement; +} + +interface Location { + hash: string; + protocol: string; + search: string; + href: string; + hostname: string; + port: string; + pathname: string; + host: string; + reload(flag?: boolean): void; + replace(url: string): void; + assign(url: string): void; + toString(): string; +} +declare var Location: { + prototype: Location; + new (): Location; +} + +interface HTMLTitleElement extends HTMLElement { + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; +} +declare var HTMLTitleElement: { + prototype: HTMLTitleElement; + new (): HTMLTitleElement; +} + +interface HTMLStyleElement extends HTMLElement, LinkStyle { + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Retrieves the CSS language in which the style sheet is written. + */ + type: string; +} +declare var HTMLStyleElement: { + prototype: HTMLStyleElement; + new (): HTMLStyleElement; +} + +interface PerformanceEntry { + name: string; + startTime: number; + duration: number; + entryType: string; +} +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new (): PerformanceEntry; +} + +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 UIEvent extends Event { + detail: number; + view: Window; + initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void; +} +declare var UIEvent: { + prototype: UIEvent; + new (): UIEvent; +} + +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: { + prototype: SVGPathSeg; + new (): 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: boolean, cancelableArg: boolean, viewArg: Window, 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 MSEventAttachmentTarget { + attachEvent(event: string, listener: EventListener): boolean; + 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, SVGExternalResourcesRequired { + 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: boolean, sweepFlag: boolean): 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: boolean, sweepFlag: boolean): SVGPathSegArcAbs; +} +declare var SVGPathElement: { + prototype: SVGPathElement; + new (): SVGPathElement; +} + +interface MSCompatibleInfo { + version: string; + userAgent: string; +} +declare var MSCompatibleInfo: { + prototype: MSCompatibleInfo; + new (): MSCompatibleInfo; +} + +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 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 HTMLUnknownElement extends HTMLElement, MSDataBindingRecordSetReadonlyExtensions { +} +declare var HTMLUnknownElement: { + prototype: HTMLUnknownElement; + new (): HTMLUnknownElement; +} + +interface HTMLAudioElement extends HTMLMediaElement { +} +declare var HTMLAudioElement: { + prototype: HTMLAudioElement; + new (): HTMLAudioElement; +} + +interface MSImageResourceExtensions { + dynsrc: string; + vrml: string; + lowsrc: string; + start: string; + loop: number; +} + +interface PositionError { + code: number; + message: string; + toString(): string; + POSITION_UNAVAILABLE: number; + PERMISSION_DENIED: number; + TIMEOUT: number; +} +declare var PositionError: { + prototype: PositionError; + new (): PositionError; + POSITION_UNAVAILABLE: number; + PERMISSION_DENIED: number; + TIMEOUT: number; +} + +interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment, DOML2DeprecatedBackgroundStyle, DOML2DeprecatedBackgroundColorStyle { + /** + * Sets or retrieves the width of the object. + */ + width: number; + /** + * Sets or retrieves a list of header cells that provide information for the object. + */ + headers: string; + /** + * Retrieves the position of the object in the cells collection of a row. + */ + cellIndex: number; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves the color for one of the two colors used to draw the 3-D border of the object. + */ + borderColorLight: any; + /** + * Sets or retrieves the number columns in the table that the object should span. + */ + colSpan: number; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ + axis: string; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; + /** + * Sets or retrieves abbreviated text for the object. + */ + abbr: string; + /** + * Sets or retrieves how many rows in a table the cell should span. + */ + rowSpan: number; + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; + /** + * Sets or retrieves the color for one of the two colors used to draw the 3-D border of the object. + */ + borderColorDark: any; +} +declare var HTMLTableCellElement: { + prototype: HTMLTableCellElement; + new (): HTMLTableCellElement; +} + +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 MSNamespaceInfoCollection { + length: number; + add(namespace?: string, urn?: string, implementationUrl?: any): Object; + item(index: any): Object; + [index: string]: Object; +} +declare var MSNamespaceInfoCollection: { + prototype: MSNamespaceInfoCollection; + new (): MSNamespaceInfoCollection; +} + +interface SVGCircleElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { + cx: SVGAnimatedLength; + r: SVGAnimatedLength; + cy: SVGAnimatedLength; +} +declare var SVGCircleElement: { + prototype: SVGCircleElement; + new (): SVGCircleElement; +} + +interface StyleSheetList { + length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; +} +declare var StyleSheetList: { + prototype: StyleSheetList; + new (): StyleSheetList; +} + +interface CSSImportRule extends CSSRule { + styleSheet: CSSStyleSheet; + href: string; + media: MediaList; +} +declare var CSSImportRule: { + prototype: CSSImportRule; + new (): CSSImportRule; +} + +interface CustomEvent extends Event { + detail: any; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; +} +declare var CustomEvent: { + prototype: CustomEvent; + new (): CustomEvent; +} + +interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { + /** + * Sets or retrieves the current typeface family. + */ + face: string; + /** + * Sets or retrieves the font size of the object. + */ + size: number; +} +declare var HTMLBaseFontElement: { + prototype: HTMLBaseFontElement; + new (): HTMLBaseFontElement; +} + +interface HTMLTextAreaElement extends HTMLElement, MSDataBindingExtensions { + /** + * Retrieves or sets the text in the entry field of the textArea element. + */ + value: string; + /** + * Sets or retrieves the value indicating whether the control is selected. + */ + status: any; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: number; + /** + * Sets or retrieves the width of the object. + */ + cols: number; + /** + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ + readOnly: boolean; + /** + * Sets or retrieves how to handle wordwrapping in the object. + */ + wrap: string; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Retrieves the type of control. + */ + type: string; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + /** + * Creates a TextRange object for the element. + */ + createTextRange(): TextRange; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ + setSelectionRange(start: number, end: number): void; + /** + * Highlights the input area of a form element. + */ + select(): void; +} +declare var HTMLTextAreaElement: { + prototype: HTMLTextAreaElement; + new (): HTMLTextAreaElement; +} + +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 DOML2DeprecatedMarginStyle { + vspace: number; + hspace: number; +} + +interface MSWindowModeless { + dialogTop: any; + dialogLeft: any; + dialogWidth: any; + dialogHeight: any; + menuArguments: any; +} + +interface DOML2DeprecatedAlignmentStyle { + align: string; +} + +interface HTMLMarqueeElement extends HTMLElement, MSDataBindingExtensions, DOML2DeprecatedBackgroundColorStyle { + width: string; + onbounce: (ev: Event) => any; + vspace: number; + trueSpeed: boolean; + scrollAmount: number; + scrollDelay: number; + behavior: string; + height: string; + loop: number; + direction: string; + hspace: number; + 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?: boolean): Node; + replaceNode(replacement: Node): Node; +} + +interface History { + length: number; + back(distance?: any): void; + forward(distance?: any): void; + go(delta?: any): void; +} +declare var History: { + prototype: History; + new (): History; +} + +interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { + y: number; + y1: number; + x2: number; + x: number; + x1: number; + y2: number; +} +declare var SVGPathSegCurvetoCubicAbs: { + prototype: SVGPathSegCurvetoCubicAbs; + new (): SVGPathSegCurvetoCubicAbs; +} + +interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { + y: number; + y1: number; + x: number; + x1: number; +} +declare var SVGPathSegCurvetoQuadraticAbs: { + prototype: SVGPathSegCurvetoQuadraticAbs; + new (): SVGPathSegCurvetoQuadraticAbs; +} + +interface TimeRanges { + length: number; + start(index: number): number; + end(index: number): number; +} +declare var TimeRanges: { + prototype: TimeRanges; + new (): TimeRanges; +} + +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 HTMLModElement extends HTMLElement { + /** + * Sets or retrieves the date and time of a modification to the object. + */ + dateTime: string; + /** + * Sets or retrieves reference information about the object. + */ + cite: string; +} +declare var HTMLModElement: { + prototype: HTMLModElement; + new (): HTMLModElement; +} + +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 MSPopupWindow { + document: Document; + isOpen: boolean; + show(x: number, y: number, w: number, h: number, element?: any): void; + hide(): void; +} +declare var MSPopupWindow: { + prototype: MSPopupWindow; + new (): MSPopupWindow; +} + +interface BeforeUnloadEvent extends Event { + returnValue: string; +} +declare var BeforeUnloadEvent: { + prototype: BeforeUnloadEvent; + new (): BeforeUnloadEvent; +} + +interface SVGUseElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired, SVGURIReference { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + animatedInstanceRoot: SVGElementInstance; + instanceRoot: SVGElementInstance; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGUseElement: { + prototype: SVGUseElement; + new (): SVGUseElement; +} + +interface Event { + timeStamp: number; + defaultPrevented: boolean; + isTrusted: boolean; + currentTarget: EventTarget; + cancelBubble: boolean; + target: EventTarget; + eventPhase: number; + cancelable: boolean; + type: string; + srcElement: Element; + bubbles: boolean; + initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): 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: Uint8Array; + height: number; +} +declare var ImageData: { + prototype: ImageData; + new (): ImageData; +} + +interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves the width of the object. + */ + width: any; + /** + * Sets or retrieves the alignment of the object relative to the display or table. + */ + align: string; + /** + * Sets or retrieves the number of columns in the group. + */ + span: number; +} +declare var HTMLTableColElement: { + prototype: HTMLTableColElement; + new (): HTMLTableColElement; +} + +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 SVGLinearGradientElement extends SVGGradientElement { + y1: SVGAnimatedLength; + x2: SVGAnimatedLength; + x1: SVGAnimatedLength; + y2: SVGAnimatedLength; +} +declare var SVGLinearGradientElement: { + prototype: SVGLinearGradientElement; + new (): SVGLinearGradientElement; +} + +interface HTMLTableAlignment { + /** + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ + ch: string; + /** + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ + vAlign: string; + /** + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ + chOff: string; +} + +interface SVGAnimatedEnumeration { + animVal: number; + baseVal: number; +} +declare var SVGAnimatedEnumeration: { + prototype: SVGAnimatedEnumeration; + new (): SVGAnimatedEnumeration; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface HTMLUListElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, DOML2DeprecatedListNumberingAndBulletStyle { +} +declare var HTMLUListElement: { + prototype: HTMLUListElement; + new (): HTMLUListElement; +} + +interface SVGRectElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + ry: SVGAnimatedLength; + rx: SVGAnimatedLength; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGRectElement: { + prototype: SVGRectElement; + new (): SVGRectElement; +} + +interface ErrorEventHandler { + (event: Event, source: string, fileno: number, columnNumber: number): void; + (message: any, uri: string, lineNumber: number, columnNumber?: number): void; +} + +interface HTMLDivElement extends HTMLElement, MSDataBindingExtensions { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; +} +declare var HTMLDivElement: { + prototype: HTMLDivElement; + new (): HTMLDivElement; +} + +interface DOML2DeprecatedBorderStyle { + border: string; +} + +interface NamedNodeMap { + length: number; + removeNamedItemNS(namespaceURI: string, localName: string): Attr; + item(index: number): Attr; + [index: number]: Attr; + removeNamedItem(name: string): Attr; + getNamedItem(name: string): Attr; + setNamedItem(arg: Attr): Attr; + getNamedItemNS(namespaceURI: string, localName: string): Attr; + setNamedItemNS(arg: Attr): Attr; +} +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 SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { + y: number; + x2: number; + x: number; + y2: number; +} +declare var SVGPathSegCurvetoCubicSmoothRel: { + prototype: SVGPathSegCurvetoCubicSmoothRel; + new (): SVGPathSegCurvetoCubicSmoothRel; +} + +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 ProcessingInstruction extends Node { + target: string; + data: string; +} +declare var ProcessingInstruction: { + prototype: ProcessingInstruction; + new (): ProcessingInstruction; +} + +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: boolean; + onhelp: (ev: Event) => any; + external: External; + 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 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: boolean, cancelableArg: boolean, viewArg: Window, 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 DocumentFragment extends Node, NodeSelector, MSEventAttachmentTarget, MSNodeExtensions { +} +declare var DocumentFragment: { + prototype: DocumentFragment; + new (): DocumentFragment; +} + +interface SVGPolylineElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGAnimatedPoints, SVGTests, SVGExternalResourcesRequired { +} +declare var SVGPolylineElement: { + prototype: SVGPolylineElement; + new (): SVGPolylineElement; +} + +interface SVGAnimatedPathData { + pathSegList: SVGPathSegList; +} + +interface Position { + timestamp: number; + 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 PerformanceMark extends PerformanceEntry { +} +declare var PerformanceMark: { + prototype: PerformanceMark; + new (): PerformanceMark; +} + +interface CSSPageRule extends CSSRule { + pseudoClass: string; + selectorText: string; + selector: string; + style: CSSStyleDeclaration; +} +declare var CSSPageRule: { + prototype: CSSPageRule; + new (): CSSPageRule; +} + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; +} +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new (): HTMLBRElement; +} + +interface MSNavigatorExtensions { + userLanguage: string; + plugins: MSPluginsCollection; + cookieEnabled: boolean; + appCodeName: string; + cpuClass: string; + appMinorVersion: string; + connectionSpeed: number; + browserLanguage: string; + mimeTypes: MSMimeTypesCollection; + systemLanguage: string; + javaEnabled(): boolean; + taintEnabled(): boolean; +} + +interface HTMLSpanElement extends HTMLElement, MSDataBindingExtensions { +} +declare var HTMLSpanElement: { + prototype: HTMLSpanElement; + new (): HTMLSpanElement; +} + +interface HTMLHeadElement extends HTMLElement { + profile: string; +} +declare var HTMLHeadElement: { + prototype: HTMLHeadElement; + new (): HTMLHeadElement; +} + +interface HTMLHeadingElement extends HTMLElement, DOML2DeprecatedTextFlowControl { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; +} +declare var HTMLHeadingElement: { + prototype: HTMLHeadingElement; + new (): HTMLHeadingElement; +} + +interface HTMLFormElement extends HTMLElement, MSHTMLCollectionExtensions { + /** + * Sets or retrieves the number of objects in a collection. + */ + length: number; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ + acceptCharset: string; + /** + * Sets or retrieves the encoding type for the form. + */ + enctype: string; + /** + * Retrieves a collection, in source order, of all controls in a given form. + */ + elements: HTMLCollection; + /** + * Sets or retrieves the URL to which the form content is sent for processing. + */ + action: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Sets or retrieves how to send the form data to the server. + */ + method: string; + /** + * Sets or retrieves the MIME encoding for the form. + */ + encoding: string; + /** + * Fires when the user resets a form. + */ + reset(): void; + /** + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(name?: any, index?: any): any; + /** + * Fires when a FORM is about to be submitted. + */ + submit(): void; + /** + * Retrieves a form object or an object from an elements collection. + */ + namedItem(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 HTMLMediaElement extends HTMLElement { + /** + * Gets the earliest possible position, in seconds, that the playback can begin. + */ + initialTime: number; + /** + * Gets TimeRanges for the current media resource that has been played. + */ + played: TimeRanges; + /** + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ + currentSrc: string; + readyState: any; + /** + * The autobuffer element is not supported by Internet Explorer 9. Use the preload element instead. + */ + autobuffer: boolean; + /** + * Gets or sets a flag to specify whether playback should restart after it completes. + */ + loop: boolean; + /** + * Gets information about whether the playback has ended or not. + */ + ended: boolean; + /** + * Gets a collection of buffered time ranges. + */ + buffered: TimeRanges; + /** + * Returns an object representing the current error state of the audio or video element. + */ + error: MediaError; + /** + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ + seekable: TimeRanges; + /** + * Gets or sets a value that indicates whether to start playing the media automatically. + */ + autoplay: boolean; + /** + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ + controls: boolean; + /** + * Gets or sets the volume level for audio portions of the media element. + */ + volume: number; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + /** + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ + playbackRate: number; + /** + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ + duration: number; + /** + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ + muted: boolean; + /** + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ + defaultPlaybackRate: number; + /** + * Gets a flag that specifies whether playback is paused. + */ + paused: boolean; + /** + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ + seeking: boolean; + /** + * Gets or sets the current playback position, in seconds. + */ + currentTime: number; + /** + * Gets or sets the current playback position, in seconds. + */ + preload: string; + /** + * Gets the current network activity for the element. + */ + networkState: number; + /** + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ + pause(): void; + /** + * Loads and starts playback of a media resource. + */ + play(): void; + /** + * Fires immediately after the client loads the object. + */ + load(): void; + /** + * Returns a string that specifies whether the client can play a given media resource type. + */ + 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 { + runtimeStyle: MSStyleCSSProperties; + currentStyle: MSCurrentStyleCSSProperties; + doScroll(component?: any): void; + componentFromPoint(x: number, y: number): string; +} + +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: boolean; + ownerNode: Node; + parentStyleSheet: StyleSheet; + href: string; + media: MediaList; + type: string; + title: string; +} +declare var StyleSheet: { + prototype: StyleSheet; + new (): StyleSheet; +} + +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 HTMLDTElement extends HTMLElement { + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; +} +declare var HTMLDTElement: { + prototype: HTMLDTElement; + new (): HTMLDTElement; +} + +interface NodeList { + length: number; + item(index: number): Node; + [index: number]: Node; +} +declare var NodeList: { + prototype: NodeList; + new (): NodeList; +} + +interface NodeListOf extends NodeList { + length: number; + item(index: number): TNode; + [index: number]: TNode; +} + +interface XMLSerializer { + serializeToString(target: Node): string; +} +declare var XMLSerializer: { + prototype: XMLSerializer; + new (): XMLSerializer; +} + +interface PerformanceMeasure extends PerformanceEntry { +} +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new (): PerformanceMeasure; +} + +interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGExternalResourcesRequired, 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 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 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 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 HTMLFieldSetElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; +} +declare var HTMLFieldSetElement: { + prototype: HTMLFieldSetElement; + new (): HTMLFieldSetElement; +} + +interface HTMLBGSoundElement extends HTMLElement { + /** + * Sets or gets the value indicating how the volume of the background sound is divided between the left speaker and the right speaker. + */ + balance: any; + /** + * Sets or gets the volume setting for the sound. + */ + volume: any; + /** + * Sets or gets the URL of a sound to play. + */ + src: string; + /** + * Sets or retrieves the number of times a sound or video clip will loop when activated. + */ + loop: number; +} +declare var HTMLBGSoundElement: { + prototype: HTMLBGSoundElement; + new (): HTMLBGSoundElement; +} + +interface HTMLElement extends Element, ElementCSSInlineStyle, MSEventAttachmentTarget, MSNodeExtensions { + onmouseleave: (ev: MouseEvent) => any; + onbeforecut: (ev: DragEvent) => any; + onkeydown: (ev: KeyboardEvent) => any; + onmove: (ev: MSEventObj) => any; + onkeyup: (ev: KeyboardEvent) => any; + onreset: (ev: Event) => any; + onhelp: (ev: Event) => any; + ondragleave: (ev: DragEvent) => any; + className: string; + onfocusin: (ev: FocusEvent) => any; + onseeked: (ev: Event) => any; + recordNumber: any; + title: string; + parentTextEdit: Element; + outerHTML: string; + ondurationchange: (ev: Event) => any; + offsetHeight: number; + all: HTMLCollection; + onblur: (ev: FocusEvent) => any; + dir: string; + onemptied: (ev: Event) => any; + onseeking: (ev: Event) => any; + oncanplay: (ev: Event) => any; + ondeactivate: (ev: UIEvent) => any; + ondatasetchanged: (ev: MSEventObj) => any; + onrowsdelete: (ev: MSEventObj) => any; + sourceIndex: number; + onloadstart: (ev: Event) => any; + onlosecapture: (ev: MSEventObj) => any; + ondragenter: (ev: DragEvent) => any; + oncontrolselect: (ev: MSEventObj) => any; + onsubmit: (ev: Event) => any; + behaviorUrns: MSBehaviorUrnsCollection; + scopeName: string; + onchange: (ev: Event) => any; + id: string; + onlayoutcomplete: (ev: MSEventObj) => any; + uniqueID: string; + onbeforeactivate: (ev: UIEvent) => any; + oncanplaythrough: (ev: Event) => any; + onbeforeupdate: (ev: MSEventObj) => any; + onfilterchange: (ev: MSEventObj) => any; + offsetParent: Element; + ondatasetcomplete: (ev: MSEventObj) => any; + onsuspend: (ev: Event) => any; + readyState: any; + onmouseenter: (ev: MouseEvent) => any; + innerText: string; + onerrorupdate: (ev: MSEventObj) => any; + onmouseout: (ev: MouseEvent) => any; + parentElement: HTMLElement; + onmousewheel: (ev: MouseWheelEvent) => any; + onvolumechange: (ev: Event) => any; + oncellchange: (ev: MSEventObj) => any; + onrowexit: (ev: MSEventObj) => any; + onrowsinserted: (ev: MSEventObj) => any; + onpropertychange: (ev: MSEventObj) => any; + filters: Object; + children: HTMLCollection; + ondragend: (ev: DragEvent) => any; + onbeforepaste: (ev: DragEvent) => any; + ondragover: (ev: DragEvent) => any; + offsetTop: number; + onmouseup: (ev: MouseEvent) => any; + ondragstart: (ev: DragEvent) => any; + onbeforecopy: (ev: DragEvent) => any; + ondrag: (ev: DragEvent) => any; + innerHTML: string; + onmouseover: (ev: MouseEvent) => any; + lang: string; + uniqueNumber: number; + onpause: (ev: Event) => any; + tagUrn: string; + onmousedown: (ev: MouseEvent) => any; + onclick: (ev: MouseEvent) => any; + onwaiting: (ev: Event) => any; + onresizestart: (ev: MSEventObj) => any; + offsetLeft: number; + isTextEdit: boolean; + isDisabled: boolean; + onpaste: (ev: DragEvent) => any; + canHaveHTML: boolean; + onmoveend: (ev: MSEventObj) => any; + language: string; + onstalled: (ev: Event) => any; + onmousemove: (ev: MouseEvent) => any; + style: MSStyleCSSProperties; + isContentEditable: boolean; + onbeforeeditfocus: (ev: MSEventObj) => any; + onratechange: (ev: Event) => any; + contentEditable: string; + tabIndex: number; + document: Document; + onprogress: (ev: any) => any; + ondblclick: (ev: MouseEvent) => any; + oncontextmenu: (ev: MouseEvent) => any; + onloadedmetadata: (ev: Event) => any; + onafterupdate: (ev: MSEventObj) => any; + onerror: (ev: Event) => any; + onplay: (ev: Event) => any; + onresizeend: (ev: MSEventObj) => any; + onplaying: (ev: Event) => any; + isMultiLine: boolean; + onfocusout: (ev: FocusEvent) => any; + onabort: (ev: UIEvent) => any; + ondataavailable: (ev: MSEventObj) => any; + hideFocus: boolean; + onreadystatechange: (ev: Event) => any; + onkeypress: (ev: KeyboardEvent) => any; + onloadeddata: (ev: Event) => any; + onbeforedeactivate: (ev: UIEvent) => any; + outerText: string; + disabled: boolean; + onactivate: (ev: UIEvent) => any; + accessKey: string; + onmovestart: (ev: MSEventObj) => any; + onselectstart: (ev: Event) => any; + onfocus: (ev: FocusEvent) => any; + ontimeupdate: (ev: Event) => any; + onresize: (ev: UIEvent) => any; + oncut: (ev: DragEvent) => any; + onselect: (ev: UIEvent) => any; + ondrop: (ev: DragEvent) => any; + offsetWidth: number; + oncopy: (ev: DragEvent) => any; + onended: (ev: Event) => any; + onscroll: (ev: UIEvent) => any; + onrowenter: (ev: MSEventObj) => any; + onload: (ev: Event) => any; + canHaveChildren: boolean; + oninput: (ev: Event) => any; + dragDrop(): boolean; + scrollIntoView(top?: boolean): void; + addFilter(filter: Object): void; + setCapture(containerCapture?: boolean): void; + focus(): void; + getAdjacentText(where: string): string; + insertAdjacentText(where: string, text: string): void; + getElementsByClassName(classNames: string): NodeList; + setActive(): void; + removeFilter(filter: Object): void; + blur(): void; + clearAttributes(): void; + releaseCapture(): void; + createControlRange(): ControlRangeCollection; + removeBehavior(cookie: number): boolean; + contains(child: HTMLElement): boolean; + click(): void; + insertAdjacentElement(position: string, insertedElement: Element): Element; + mergeAttributes(source: HTMLElement, preserveIdentity?: boolean): void; + replaceAdjacentText(where: string, newText: string): string; + applyElement(apply: Element, where?: string): Element; + addBehavior(bstrUrl: string, factory?: any): number; + insertAdjacentHTML(where: string, html: string): void; +} +declare var HTMLElement: { + prototype: HTMLElement; + new (): HTMLElement; +} + +interface Comment extends CharacterData { + text: string; +} +declare var Comment: { + prototype: Comment; + new (): Comment; +} + +interface PerformanceResourceTiming extends PerformanceEntry { + redirectStart: number; + redirectEnd: number; + domainLookupEnd: number; + responseStart: number; + domainLookupStart: number; + fetchStart: number; + requestStart: number; + connectEnd: number; + connectStart: number; + initiatorType: string; + responseEnd: number; +} +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new (): PerformanceResourceTiming; +} + +interface CanvasPattern { +} +declare var CanvasPattern: { + prototype: CanvasPattern; + new (): CanvasPattern; +} + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves the width of the object. + */ + width: number; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; +} +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new (): HTMLHRElement; +} + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument, DOML2DeprecatedMarginStyle, DOML2DeprecatedBorderStyle, DOML2DeprecatedAlignmentStyle, MSDataBindingExtensions, MSDataBindingRecordSetExtensions { + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the contained object. + */ + object: Object; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves the class identifier for the object. + */ + classid: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Retrieves the document object of the page or frame. + */ + contentDocument: Document; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + declare: boolean; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + BaseHref: string; +} +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new (): HTMLObjectElement; +} + +interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Retrieves the palette used for the embedded document. + */ + palette: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Retrieves the URL of the plug-in used to view an embedded document. + */ + pluginspage: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves the height and width units of the embed object. + */ + units: string; +} +declare var HTMLEmbedElement: { + prototype: HTMLEmbedElement; + new (): HTMLEmbedElement; +} + +interface StorageEvent extends Event { + oldValue: any; + newValue: any; + url: string; + storageArea: Storage; + key: string; + initStorageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, keyArg: string, oldValueArg: any, newValueArg: any, urlArg: string, storageAreaArg: Storage): void; +} +declare var StorageEvent: { + prototype: StorageEvent; + new (): StorageEvent; +} + +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 HTMLOptGroupElement extends HTMLElement, MSDataBindingExtensions { + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + index: number; + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + /** + * Sets or retrieves the text string specified by the option tag. + */ + text: string; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; +} +declare var HTMLOptGroupElement: { + prototype: HTMLOptGroupElement; + new (): HTMLOptGroupElement; +} + +interface HTMLIsIndexElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the URL to which the form content is sent for processing. + */ + action: string; + 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 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 SVGAnimatedBoolean { + animVal: boolean; + baseVal: boolean; +} +declare var SVGAnimatedBoolean: { + prototype: SVGAnimatedBoolean; + new (): SVGAnimatedBoolean; +} + +interface MSCompatibleInfoCollection { + length: number; + item(index: number): MSCompatibleInfo; +} +declare var MSCompatibleInfoCollection: { + prototype: MSCompatibleInfoCollection; + new (): MSCompatibleInfoCollection; +} + +interface SVGSwitchElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { +} +declare var SVGSwitchElement: { + prototype: SVGSwitchElement; + new (): SVGSwitchElement; +} + +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 { + expando: boolean; + specified: boolean; + ownerElement: Element; + value: string; + name: string; +} +declare var Attr: { + prototype: Attr; + new (): Attr; +} + +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 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, SVGExternalResourcesRequired { +} +declare var SVGSymbolElement: { + prototype: SVGSymbolElement; + new (): SVGSymbolElement; +} + +interface SVGElementInstanceList { + length: number; + item(index: number): SVGElementInstance; +} +declare var SVGElementInstanceList: { + prototype: SVGElementInstanceList; + new (): SVGElementInstanceList; +} + +interface CSSRuleList { + length: number; + item(index: number): CSSRule; + [index: number]: CSSRule; +} +declare var CSSRuleList: { + prototype: CSSRuleList; + new (): CSSRuleList; +} + +interface MSDataBindingRecordSetExtensions { + recordset: Object; + namedRecordset(dataMember: string, hierarchy?: any): Object; +} + +interface LinkStyle { + styleSheet: StyleSheet; + sheet: StyleSheet; +} + +interface HTMLVideoElement extends HTMLMediaElement { + /** + * Gets or sets the width of the video element. + */ + width: number; + /** + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ + videoWidth: number; + /** + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ + videoHeight: number; + /** + * Gets or sets the height of the video element. + */ + height: number; + /** + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ + poster: string; +} +declare var HTMLVideoElement: { + prototype: HTMLVideoElement; + new (): HTMLVideoElement; +} + +interface ClientRectList { + length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} +declare var ClientRectList: { + prototype: ClientRectList; + new (): ClientRectList; +} + +interface SVGMaskElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + maskUnits: SVGAnimatedEnumeration; + maskContentUnits: SVGAnimatedEnumeration; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGMaskElement: { + prototype: SVGMaskElement; + new (): SVGMaskElement; +} + +interface External { +} +declare var External: { + prototype: External; + new (): External; +} + +declare var Audio: { new (src?: string): HTMLAudioElement; }; +declare var Option: { new (text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): 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 screenX: number; +declare var onmouseover: (ev: MouseEvent) => any; +declare var ondragleave: (ev: DragEvent) => any; +declare var history: History; +declare var pageXOffset: number; +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 innerHeight: number; +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 outerWidth: number; +declare var onstalled: (ev: Event) => any; +declare var onmousemove: (ev: MouseEvent) => any; +declare var innerWidth: number; +declare var onoffline: (ev: Event) => any; +declare var length: number; +declare var screen: Screen; +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 document: Document; +declare var onprogress: (ev: any) => any; +declare var ondblclick: (ev: MouseEvent) => any; +declare var pageYOffset: number; +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: ErrorEventHandler; +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 outerHeight: number; +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 onselect: (ev: UIEvent) => any; +declare var navigator: Navigator; +declare var styleMedia: StyleMedia; +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 screenY: number; +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 var performance: Performance; +declare function alert(message?: any): void; +declare function scroll(x?: number, y?: number): void; +declare function focus(): void; +declare function scrollTo(x?: number, y?: number): 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?: boolean): Window; +declare function scrollBy(x?: number, y?: number): void; +declare function confirm(message?: string): boolean; +declare function close(): void; +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 removeEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +declare function dispatchEvent(evt: Event): boolean; +declare function attachEvent(event: string, listener: EventListener): boolean; +declare function detachEvent(event: string, listener: EventListener): void; +declare var localStorage: Storage; +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: boolean; +declare var onhelp: (ev: Event) => any; +declare var external: External; +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 sessionStorage: Storage; +declare function clearTimeout(handle: number): void; +declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; +declare function clearInterval(handle: number): void; +declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; + + +///////////////////////////// +/// IE10 DOM APIs +///////////////////////////// + + +interface ObjectURLOptions { + oneTimeOnly?: boolean; +} + +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: boolean, cancelableArg: boolean, viewArg: Window, 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: { + MSGESTURE_FLAG_BEGIN: number; + MSGESTURE_FLAG_END: number; + MSGESTURE_FLAG_CANCEL: number; + MSGESTURE_FLAG_INERTIA: number; + MSGESTURE_FLAG_NONE: number; +} + +interface HTMLAnchorElement { + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; +} + +interface HTMLInputElement { + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Returns a FileList object on a file type input object. + */ + files: FileList; + /** + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ + max: string; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ + step: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Returns the input field value as a number. + */ + valueAsNumber: number; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Specifies the ID of a pre-defined datalist of options for an input element. + */ + list: HTMLElement; + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ + min: string; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Gets or sets a string containing a regular expression that the user's input must match. + */ + pattern: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: string; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ + stepDown(n?: number): void; + /** + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ + stepUp(n?: number): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; +} + +interface ErrorEvent extends Event { + colno: number; + filename: string; + error: any; + lineno: number; + message: string; + initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; +} + +interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + filterResX: SVGAnimatedInteger; + filterUnits: SVGAnimatedEnumeration; + primitiveUnits: SVGAnimatedEnumeration; + x: SVGAnimatedLength; + height: SVGAnimatedLength; + filterResY: SVGAnimatedInteger; + setFilterRes(filterResX: number, filterResY: number): void; +} + +interface TrackEvent extends Event { + track: any; +} + +interface SVGFEMergeNodeElement extends SVGElement { + in1: SVGAnimatedString; +} + +interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { +} + +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: boolean; + id: string; + startTime: number; + onexit: (ev: Event) => any; + getCueAsHTML(): DocumentFragment; +} +declare var TextTrackCue: { + prototype: TextTrackCue; + new (): TextTrackCue; +} + +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 DOMTokenList { + length: number; + contains(token: string): boolean; + remove(token: string): void; + toggle(token: string): boolean; + add(token: string): void; + item(index: number): string; + [index: number]: string; + toString(): string; +} + +interface EventException { + name: string; +} + +interface Performance { + now(): number; +} + +interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { +} + +interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; +} + +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: { + 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 { +} + +interface CSSStyleDeclaration { + animationFillMode: string; + floodColor: string; + animationIterationCount: string; + textShadow: string; + backfaceVisibility: string; + msAnimationIterationCount: string; + animationDelay: string; + animationTimingFunction: string; + columnWidth: any; + msScrollSnapX: string; + columnRuleColor: any; + columnRuleWidth: any; + transitionDelay: string; + transition: string; + msFlowFrom: string; + msScrollSnapType: string; + msContentZoomSnapType: string; + msGridColumns: string; + msAnimationName: string; + msGridRowAlign: string; + msContentZoomChaining: string; + msGridColumn: any; + msHyphenateLimitZone: any; + msScrollRails: string; + msAnimationDelay: string; + enableBackground: string; + msWrapThrough: string; + columnRuleStyle: string; + msAnimation: string; + msFlexFlow: string; + msScrollSnapY: string; + msHyphenateLimitLines: any; + msTouchAction: string; + msScrollLimit: string; + animation: string; + transform: string; + filter: string; + colorInterpolationFilters: string; + transitionTimingFunction: string; + msBackfaceVisibility: string; + animationPlayState: string; + transformOrigin: string; + msScrollLimitYMin: any; + msFontFeatureSettings: string; + msContentZoomLimitMin: any; + columnGap: any; + transitionProperty: string; + msAnimationDuration: string; + msAnimationFillMode: string; + msFlexDirection: string; + msTransitionDuration: string; + fontFeatureSettings: string; + breakBefore: string; + msFlexWrap: string; + perspective: string; + msFlowInto: string; + msTransformStyle: string; + msScrollTranslation: string; + msTransitionProperty: string; + msUserSelect: string; + msOverflowStyle: string; + msScrollSnapPointsY: string; + animationDirection: string; + animationDuration: string; + msFlex: string; + msTransitionTimingFunction: string; + animationName: string; + columnRule: string; + msGridColumnSpan: any; + msFlexNegative: string; + columnFill: string; + msGridRow: any; + msFlexOrder: string; + msFlexItemAlign: string; + msFlexPositive: string; + msContentZoomLimitMax: any; + msScrollLimitYMax: any; + msGridColumnAlign: string; + perspectiveOrigin: string; + lightingColor: string; + columns: string; + msScrollChaining: string; + msHyphenateLimitChars: string; + msTouchSelect: string; + floodOpacity: string; + msAnimationDirection: string; + msAnimationPlayState: string; + columnSpan: string; + msContentZooming: string; + msPerspective: string; + msFlexPack: string; + msScrollSnapPointsX: string; + msContentZoomSnapPoints: string; + msGridRowSpan: any; + msContentZoomSnap: string; + msScrollLimitXMin: any; + breakInside: string; + msHighContrastAdjust: string; + msFlexLinePack: string; + msGridRows: string; + transitionDuration: string; + msHyphens: string; + breakAfter: string; + msTransition: string; + msPerspectiveOrigin: string; + msContentZoomLimit: string; + msScrollLimitXMax: any; + msFlexAlign: string; + msWrapMargin: any; + columnCount: any; + msAnimationTimingFunction: string; + msTransitionDelay: string; + transformStyle: string; + msWrapFlow: string; + msFlexPreferredSize: string; +} + +interface MessageChannel { + port2: MessagePort; + port1: MessagePort; +} +declare var MessageChannel: { + prototype: MessageChannel; + new (): MessageChannel; +} + +interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { +} + +interface Navigator extends MSFileSaver { + msMaxTouchPoints: number; + msPointerEnabled: boolean; + msManipulationViewsEnabled: boolean; + msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; +} + +interface TransitionEvent extends Event { + propertyName: string; + elapsedTime: number; + initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void; +} + +interface MediaQueryList { + matches: boolean; + media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +interface DOMError { + name: string; + toString(): string; +} + +interface CloseEvent extends Event { + wasClean: boolean; + reason: string; + code: number; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +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 SVGFEPointLightElement extends SVGElement { + y: SVGAnimatedNumber; + x: SVGAnimatedNumber; + z: SVGAnimatedNumber; +} + +interface ProgressEvent extends Event { + loaded: number; + lengthComputable: boolean; + total: number; + initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; +} + +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; + delete(key: any): IDBRequest; +} + +interface HTMLCanvasElement { + /** + * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. + */ + msToBlob(): Blob; +} + +interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + stdDeviationX: SVGAnimatedNumber; + in1: SVGAnimatedString; + stdDeviationY: SVGAnimatedNumber; + setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; +} + +interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + height: SVGAnimatedLength; + result: SVGAnimatedString; +} + +interface Element { + 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; +} + +interface IDBVersionChangeEvent extends Event { + newVersion: number; + oldVersion: number; +} + +interface IDBIndex { + unique: boolean; + 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; +} + +interface WheelEvent { + getCurrentPoint(element: Element): void; +} + +interface FileList { + length: number; + item(index: number): File; + [index: number]: File; +} + +interface IDBCursor { + source: any; + direction: string; + key: any; + primaryKey: any; + advance(count: number): void; + delete(): IDBRequest; + continue(key?: any): void; + update(value: any): IDBRequest; +} + +interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + kernelUnitLengthY: SVGAnimatedNumber; + surfaceScale: SVGAnimatedNumber; + specularExponent: SVGAnimatedNumber; + in1: SVGAnimatedString; + kernelUnitLengthX: SVGAnimatedNumber; + specularConstant: SVGAnimatedNumber; +} + +interface File extends Blob { + lastModifiedDate: any; + name: string; +} + +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; +} + +interface HTMLTextAreaElement { + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + 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; +} + +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; +} + +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 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: { + SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; + SVG_MORPHOLOGY_OPERATOR_ERODE: number; + SVG_MORPHOLOGY_OPERATOR_DILATE: number; +} + +interface HTMLSelectElement { + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; +} + +interface CSSRule { + KEYFRAMES_RULE: number; + KEYFRAME_RULE: number; + VIEWPORT_RULE: number; +} +//declare var CSSRule: { +// KEYFRAMES_RULE: number; +// KEYFRAME_RULE: number; +// VIEWPORT_RULE: number; +//} + +interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { +} + +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: { + SVG_CHANNEL_B: number; + SVG_CHANNEL_R: number; + SVG_CHANNEL_G: number; + SVG_CHANNEL_UNKNOWN: number; + SVG_CHANNEL_A: number; +} + +interface AnimationEvent extends Event { + animationName: string; + elapsedTime: number; + initAnimationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, animationNameArg: string, elapsedTimeArg: number): void; +} + +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: { + 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; +} + +interface SVGFEDistantLightElement extends SVGElement { + azimuth: SVGAnimatedNumber; + elevation: SVGAnimatedNumber; +} + +interface SVGException { + name: string; +} + +interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { +} + +interface IDBKeyRange { + upper: any; + upperOpen: boolean; + lower: any; + lowerOpen: boolean; + bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; + only(value: any): IDBKeyRange; + lowerBound(bound: any, open?: boolean): IDBKeyRange; + upperBound(bound: any, open?: boolean): IDBKeyRange; +} + +interface WindowConsole { + console: Console; +} + +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; +} + +interface AudioTrack { + kind: string; + language: string; + id: string; + label: string; + enabled: boolean; +} + +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: { + 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; +} + +interface CSSKeyframesRule extends CSSRule { + name: string; + cssRules: CSSRuleList; + findRule(rule: string): CSSKeyframeRule; + deleteRule(rule: string): void; + appendRule(rule: string): void; +} + +interface Window extends WindowBase64, IDBEnvironment, WindowConsole { + onmspointerdown: (ev: any) => any; + animationStartTime: number; + 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; + msAnimationStartTime: number; + applicationCache: ApplicationCache; + onmsinertiastart: (ev: any) => any; + onmspointerover: (ev: any) => any; + onpopstate: (ev: PopStateEvent) => any; + onmspointerup: (ev: any) => any; + msCancelRequestAnimationFrame(handle: number): void; + matchMedia(mediaQuery: string): MediaQueryList; + cancelAnimationFrame(handle: number): void; + msIsStaticHTML(html: string): boolean; + msMatchMedia(mediaQuery: string): MediaQueryList; + requestAnimationFrame(callback: FrameRequestCallback): number; + msRequestAnimationFrame(callback: FrameRequestCallback): number; +} + +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: { + 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; +} + +interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { +} + +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: { + 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(message?: any, ...optionalParams: any[]): void; + profile(reportName?: string): void; + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + clear(): void; + dir(value?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; + error(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + profileEnd(): void; +} + +interface SVGFESpotLightElement extends SVGElement { + pointsAtY: SVGAnimatedNumber; + y: SVGAnimatedNumber; + limitingConeAngle: SVGAnimatedNumber; + specularExponent: SVGAnimatedNumber; + x: SVGAnimatedNumber; + pointsAtZ: SVGAnimatedNumber; + z: SVGAnimatedNumber; + pointsAtX: SVGAnimatedNumber; +} + +interface HTMLImageElement { + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + msPlayToSource: any; +} + +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; +} + +interface DOMStringList { + length: number; + contains(str: string): boolean; + item(index: number): string; + [index: number]: string; +} + +interface HTMLButtonElement { + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: string; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; +} + +interface IDBOpenDBRequest extends IDBRequest { + onupgradeneeded: (ev: IDBVersionChangeEvent) => any; + onblocked: (ev: Event) => any; +} + +interface HTMLProgressElement extends HTMLElement { + /** + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ + value: number; + /** + * Defines the maximum, or "done" value for a progress element. + */ + max: number; + /** + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ + position: number; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; +} + +interface MSLaunchUriCallback { + (): void; +} + +interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + dy: SVGAnimatedNumber; + in1: SVGAnimatedString; + dx: SVGAnimatedNumber; +} + +interface HTMLFormElement { + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Designates a form that is not validated when submitted. + */ + noValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; +} + +interface MSUnsafeFunctionCallback { + (): any; +} + +interface Document { + onmspointerdown: (ev: any) => any; + msHidden: boolean; + msVisibilityState: string; + onmsgesturedoubletap: (ev: any) => any; + visibilityState: string; + onmsmanipulationstatechanged: (ev: any) => any; + onmspointerhover: (ev: any) => any; + onmscontentzoom: (ev: any) => any; + onmspointermove: (ev: any) => any; + onmsgesturehold: (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; + msCSSOMElementFloatMetrics: boolean; + onmspointerover: (ev: any) => any; + hidden: boolean; + onmspointerup: (ev: any) => any; + msElementsFromPoint(x: number, y: number): NodeList; + msElementsFromRect(left: number, top: number, width: number, height: number): NodeList; + clear(): void; +} + +interface MessageEvent extends Event { + ports: any; +} + +interface HTMLScriptElement { + async: boolean; +} + +interface HTMLMediaElement { + /** + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ + msAudioCategory: string; + /** + * Specifies whether or not to enable low-latency playback on the media element. + */ + msRealTime: boolean; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + textTracks: TextTrackList; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ + audioTracks: AudioTrackList; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + msPlayToSource: any; + /** + * Specifies the output device id that the audio will be sent to. + */ + msAudioDeviceType: string; + /** + * Clears all effects from the media pipeline. + */ + msClearEffects(): void; + /** + * Specifies the media protection manager for a given media pipeline. + */ + msSetMediaProtectionManager(mediaProtectionManager?: any): void; + /** + * Inserts the specified audio effect into media pipeline. + */ + msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; +} + +interface TextTrack extends EventTarget { + language: string; + mode: any; + readyState: number; + 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: { + 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; +} + +interface MessagePort extends EventTarget { + onmessage: (ev: any) => any; + close(): void; + postMessage(message?: any, ports?: any): void; + start(): void; +} + +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 BlobPropertyBag { + type?: string; + endings?: string; +} + +interface Blob { + type: string; + size: number; + msDetachStream(): any; + slice(start?: number, end?: number, contentType?: string): Blob; + msClose(): void; +} +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: { + CHECKING: number; + UNCACHED: number; + UPDATEREADY: number; + DOWNLOADING: number; + IDLE: number; + OBSOLETE: number; +} + +interface FrameRequestCallback { + (time: number): void; +} + +interface XMLHttpRequest { + response: any; + withCredentials: boolean; + onprogress: (ev: ProgressEvent) => any; + onabort: (ev: any) => any; + responseType: string; + onloadend: (ev: ProgressEvent) => any; + upload: XMLHttpRequestEventTarget; + onerror: (ev: ErrorEvent) => any; + onloadstart: (ev: any) => any; +} + +interface PopStateEvent extends Event { + state: any; + initPopStateEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, stateArg: any): void; +} + +interface CSSKeyframeRule extends CSSRule { + keyText: string; + style: CSSStyleDeclaration; +} + +interface MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +interface MSStream { + type: string; + msDetachStream(): any; + msClose(): void; +} + +interface MediaError { + msExtendedCode: number; +} + +interface HTMLFieldSetElement { + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; +} + +interface MSBlobBuilder { + append(data: any, endings?: string): void; + getBlob(contentType?: string): Blob; +} +declare var MSBlobBuilder: { + prototype: MSBlobBuilder; + new (): MSBlobBuilder; +} + +interface HTMLElement { + onmscontentzoom: (ev: any) => any; + oncuechange: (ev: Event) => any; + spellcheck: boolean; + classList: DOMTokenList; + onmsmanipulationstatechanged: (ev: any) => any; + draggable: boolean; +} + +interface DataTransfer { + types: DOMStringList; + files: FileList; +} + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +interface IDBFactory { + open(name: string, version?: number): IDBOpenDBRequest; + cmp(first: any, second: any): number; + deleteDatabase(name: string): IDBOpenDBRequest; +} + +interface Range { + createContextualFragment(fragment: string): DocumentFragment; +} + +interface HTMLObjectElement { + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; +} + +interface MSPointerEvent extends MouseEvent { + width: number; + rotation: number; + pressure: number; + pointerType: any; + isPrimary: boolean; + tiltY: number; + height: number; + intermediatePoints: any; + currentPoint: any; + tiltX: number; + hwTimestamp: number; + pointerId: number; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + MSPOINTER_TYPE_PEN: number; + MSPOINTER_TYPE_MOUSE: number; + MSPOINTER_TYPE_TOUCH: number; +} +declare var MSPointerEvent: { + MSPOINTER_TYPE_PEN: number; + MSPOINTER_TYPE_MOUSE: number; + MSPOINTER_TYPE_TOUCH: number; +} + +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 MSManipulationEvent extends UIEvent { + lastState: number; + currentState: number; + initMSManipulationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, 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: { + 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 (form?: HTMLFormElement): FormData; +} + +interface HTMLDataListElement extends HTMLElement { + options: HTMLCollection; +} + +interface SVGFEImageElement extends SVGElement, SVGLangSpace, SVGFilterPrimitiveStandardAttributes, SVGURIReference, SVGExternalResourcesRequired { + preserveAspectRatio: SVGAnimatedPreserveAspectRatio; +} + +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: { + 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: boolean; + valueMissing: boolean; + stepMismatch: boolean; + rangeUnderflow: boolean; + rangeOverflow: boolean; + typeMismatch: boolean; + patternMismatch: boolean; + tooLong: boolean; + valid: boolean; +} + +interface HTMLTrackElement extends HTMLElement { + kind: string; + src: string; + srclang: string; + track: TextTrack; + label: string; + default: boolean; +} + +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): any; + addPublicLocalApplicationUri(uri: string): void; + createDataPackageFromSelection(): any; +} +declare var MSApp: MSApp; + +interface HTMLVideoElement { + msIsStereo3D: boolean; + msStereo3DPackingMode: string; + onMSVideoOptimalLayoutChanged: (ev: any) => any; + onMSVideoFrameStepCompleted: (ev: any) => any; + msStereo3DRenderMode: string; + msIsLayoutOptimalForPlayback: boolean; + msHorizontalMirror: boolean; + onMSVideoFormatChanged: (ev: any) => any; + msZoom: boolean; + msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; + msFrameStep(forward: boolean): void; +} + +interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; +} + +interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + kernelUnitLengthY: SVGAnimatedNumber; + surfaceScale: SVGAnimatedNumber; + in1: SVGAnimatedString; + kernelUnitLengthX: SVGAnimatedNumber; + diffuseConstant: SVGAnimatedNumber; +} + +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; +} + +declare var onmspointerdown: (ev: any) => any; +declare var animationStartTime: number; +declare var onmsgesturedoubletap: (ev: any) => any; +declare var onmspointerhover: (ev: any) => any; +declare var onmsgesturehold: (ev: any) => any; +declare var onmspointermove: (ev: any) => any; +declare var onmsgesturechange: (ev: any) => any; +declare var onmsgesturestart: (ev: any) => any; +declare var onmspointercancel: (ev: any) => any; +declare var onmsgestureend: (ev: any) => any; +declare var onmsgesturetap: (ev: any) => any; +declare var onmspointerout: (ev: any) => any; +declare var msAnimationStartTime: number; +declare var applicationCache: ApplicationCache; +declare var onmsinertiastart: (ev: any) => any; +declare var onmspointerover: (ev: any) => any; +declare var onpopstate: (ev: PopStateEvent) => any; +declare var onmspointerup: (ev: any) => any; +declare function msCancelRequestAnimationFrame(handle: number): void; +declare function matchMedia(mediaQuery: string): MediaQueryList; +declare function cancelAnimationFrame(handle: number): void; +declare function msIsStaticHTML(html: string): boolean; +declare function msMatchMedia(mediaQuery: string): MediaQueryList; +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; + + +///////////////////////////// +/// IE11 DOM APIs +///////////////////////////// + + +interface StoreExceptionsInformation extends ExceptionInformation { + siteName?: string; + explanationString?: string; + detailURI?: string; +} + +interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { + arrayOfDomainStrings?: Array; +} + +interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { + arrayOfDomainStrings?: Array; +} + +interface AlgorithmParameters { +} + +interface MutationObserverInit { + childList?: boolean; + attributes?: boolean; + characterData?: boolean; + subtree?: boolean; + attributeOldValue?: boolean; + characterDataOldValue?: boolean; + attributeFilter?: Array; +} + +interface ExceptionInformation { + domain?: string; +} + +interface MsZoomToOptions { + contentX?: number; + contentY?: number; + viewportX?: string; + viewportY?: string; + scaleFactor?: number; + animate?: string; +} + +interface DeviceAccelerationDict { + x?: number; + y?: number; + z?: number; +} + +interface DeviceRotationRateDict { + alpha?: number; + beta?: number; + gamma?: number; +} + +interface Algorithm { + name?: string; + params?: AlgorithmParameters; +} + +interface NavigatorID { + product: string; + vendor: string; +} + +interface HTMLBodyElement { + onpageshow: (ev: PageTransitionEvent) => any; + onpagehide: (ev: PageTransitionEvent) => any; +} + +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} + +interface MSWindowExtensions { + captureEvents(): void; + releaseEvents(): void; +} + +interface MSGraphicsTrust { + status: string; + constrictionActive: boolean; +} + +interface AudioTrack { + sourceBuffer: SourceBuffer; +} + +interface DragEvent { + msConvertURL(file: File, targetType: string, targetURL?: string): void; +} + +interface SubtleCrypto { + unwrapKey(wrappedKey: ArrayBufferView, keyAlgorithm: any, keyEncryptionKey: Key, extractable?: boolean, keyUsages?: string[]): KeyOperation; + encrypt(algorithm: any, key: Key, buffer?: ArrayBufferView): CryptoOperation; + importKey(format: string, keyData: ArrayBufferView, algorithm: any, extractable?: boolean, keyUsages?: string[]): KeyOperation; + wrapKey(key: Key, keyEncryptionKey: Key, keyWrappingAlgorithm: any): KeyOperation; + verify(algorithm: any, key: Key, signature: ArrayBufferView, buffer?: ArrayBufferView): CryptoOperation; + deriveKey(algorithm: any, baseKey: Key, derivedKeyType: any, extractable?: boolean, keyUsages?: string[]): KeyOperation; + digest(algorithm: any, buffer?: ArrayBufferView): CryptoOperation; + exportKey(format: string, key: Key): KeyOperation; + generateKey(algorithm: any, extractable?: boolean, keyUsages?: string[]): KeyOperation; + sign(algorithm: any, key: Key, buffer?: ArrayBufferView): CryptoOperation; + decrypt(algorithm: any, key: Key, buffer?: ArrayBufferView): CryptoOperation; +} + +interface Crypto extends RandomSource { + subtle: SubtleCrypto; +} + +interface VideoPlaybackQuality { + totalFrameDelay: number; + creationTime: number; + totalVideoFrames: number; + droppedVideoFrames: number; +} + +interface GlobalEventHandlers { + onpointerenter: (ev: PointerEvent) => any; + onpointerout: (ev: PointerEvent) => any; + onpointerdown: (ev: PointerEvent) => any; + onpointerup: (ev: PointerEvent) => any; + onpointercancel: (ev: PointerEvent) => any; + onpointerover: (ev: PointerEvent) => any; + onpointermove: (ev: PointerEvent) => any; + onpointerleave: (ev: PointerEvent) => any; +} + +interface Window extends GlobalEventHandlers { + onpageshow: (ev: PageTransitionEvent) => any; + ondevicemotion: (ev: DeviceMotionEvent) => any; + devicePixelRatio: number; + msCrypto: Crypto; + ondeviceorientation: (ev: DeviceOrientationEvent) => any; + doNotTrack: string; + onmspointerenter: (ev: any) => any; + onpagehide: (ev: PageTransitionEvent) => any; + onmspointerleave: (ev: any) => any; +} + +interface Key { + algorithm: Algorithm; + type: string; + extractable: boolean; + keyUsage: string[]; +} + +interface TextTrackList extends EventTarget { + onaddtrack: (ev: any) => any; +} + +interface DeviceAcceleration { + y: number; + x: number; + z: number; +} + +interface Console { + count(countTitle?: string): void; + groupEnd(): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(): void; + group(groupTitle?: string): void; + dirxml(value: any): void; + debug(message?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string): void; + select(element: Element): void; +} + +interface MSNavigatorDoNotTrack { + removeSiteSpecificTrackingException(args: ExceptionInformation): void; + removeWebWideTrackingException(args: ExceptionInformation): void; + storeWebWideTrackingException(args: StoreExceptionsInformation): void; + storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void; + confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean; + confirmWebWideTrackingException(args: ExceptionInformation): boolean; +} + +interface HTMLImageElement { + crossOrigin: string; + msPlayToPreferredSourceUri: string; +} + +interface HTMLAllCollection extends HTMLCollection { + namedItem(name: string): Element; + //[name: string]: Element; +} + +interface MSNavigatorExtensions { + language: string; +} + +interface AesGcmEncryptResult { + ciphertext: ArrayBuffer; + tag: ArrayBuffer; +} + +interface HTMLSourceElement { + msKeySystem: string; +} + +interface CSSStyleDeclaration { + alignItems: string; + borderImageSource: string; + flexBasis: string; + borderImageWidth: string; + borderImageRepeat: string; + order: string; + flex: string; + alignContent: string; + msImeAlign: string; + flexShrink: string; + flexGrow: string; + borderImageSlice: string; + flexWrap: string; + borderImageOutset: string; + flexDirection: string; + touchAction: string; + flexFlow: string; + borderImage: string; + justifyContent: string; + alignSelf: string; + msTextCombineHorizontal: string; +} + +interface NavigationCompletedEvent extends NavigationEvent { + webErrorStatus: number; + isSuccess: boolean; +} + +interface MutationRecord { + oldValue: string; + previousSibling: Node; + addedNodes: NodeList; + attributeName: string; + removedNodes: NodeList; + target: Node; + nextSibling: Node; + attributeNamespace: string; + type: string; +} + +interface Navigator { + pointerEnabled: boolean; + maxTouchPoints: number; +} + +interface Document extends MSDocumentExtensions, GlobalEventHandlers { + msFullscreenEnabled: boolean; + onmsfullscreenerror: (ev: any) => any; + onmspointerenter: (ev: any) => any; + msFullscreenElement: Element; + onmsfullscreenchange: (ev: any) => any; + onmspointerleave: (ev: any) => any; + msExitFullscreen(): void; +} + +interface MimeTypeArray { + length: number; + item(index: number): Plugin; + [index: number]: Plugin; + namedItem(type: string): Plugin; + //[type: string]: Plugin; +} + +interface HTMLMediaElement { + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + onmsneedkey: (ev: MSMediaKeyNeededEvent) => any; + /** + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ + msKeys: MSMediaKeys; + msGraphicsTrustStatus: MSGraphicsTrust; + msSetMediaKeys(mediaKeys: MSMediaKeys): void; + addTextTrack(kind: string, label?: string, language?: string): TextTrack; +} + +interface TextTrack { + addCue(cue: TextTrackCue): void; + removeCue(cue: TextTrackCue): void; +} + +interface KeyOperation extends EventTarget { + oncomplete: (ev: any) => any; + onerror: (ev: any) => any; + result: any; +} + +interface DOMStringMap { +} + +interface DeviceOrientationEvent extends Event { + gamma: number; + alpha: number; + absolute: boolean; + beta: number; + initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number, beta: number, gamma: number, absolute: boolean): void; +} + +interface MSMediaKeys { + keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; + isTypeSupported(keySystem: string, type?: string): boolean; +} +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new (): MSMediaKeys; +} + +interface MSMediaKeyMessageEvent extends Event { + destinationURL: string; + message: Uint8Array; +} + +interface MSHTMLWebViewElement extends HTMLElement { + documentTitle: string; + width: number; + src: string; + canGoForward: boolean; + height: number; + canGoBack: boolean; + navigateWithHttpRequestMessage(requestMessage: any): void; + goBack(): void; + navigate(uri: string): void; + stop(): void; + navigateToString(contents: string): void; + captureSelectedContentToDataPackageAsync(): MSWebViewAsyncOperation; + capturePreviewToBlobAsync(): MSWebViewAsyncOperation; + refresh(): void; + goForward(): void; + navigateToLocalStreamUri(source: string, streamResolver: any): void; + invokeScriptAsync(scriptName: string, ...args: any[]): MSWebViewAsyncOperation; + buildLocalStreamUri(contentIdentifier: string, relativePath: string): string; +} + +interface NavigationEvent extends Event { + uri: string; +} + +interface Element extends GlobalEventHandlers { + onlostpointercapture: (ev: PointerEvent) => any; + onmspointerenter: (ev: any) => any; + ongotpointercapture: (ev: PointerEvent) => any; + onmspointerleave: (ev: any) => any; + msZoomTo(args: MsZoomToOptions): void; + setPointerCapture(pointerId: number): void; + msGetUntransformedBounds(): ClientRect; + releasePointerCapture(pointerId: number): void; + msRequestFullscreen(): void; +} + +interface RandomSource { + getRandomValues(array: ArrayBufferView): ArrayBufferView; +} + +interface XMLHttpRequest { + msCaching: string; + msCachingEnabled(): boolean; + overrideMimeType(mime: string): void; +} + +interface SourceBuffer extends EventTarget { + updating: boolean; + appendWindowStart: number; + appendWindowEnd: number; + buffered: TimeRanges; + timestampOffset: number; + audioTracks: AudioTrackList; + appendBuffer(data: ArrayBuffer): void; + remove(start: number, end: number): void; + abort(): void; + appendStream(stream: MSStream, maxSize?: number): void; +} + +interface MSInputMethodContext extends EventTarget { + oncandidatewindowshow: (ev: any) => any; + target: HTMLElement; + compositionStartOffset: number; + oncandidatewindowhide: (ev: any) => any; + oncandidatewindowupdate: (ev: any) => any; + compositionEndOffset: number; + getCompositionAlternatives(): string[]; + getCandidateWindowClientRect(): ClientRect; + hasComposition(): boolean; + isCandidateWindowVisible(): boolean; +} + +interface DeviceRotationRate { + gamma: number; + alpha: number; + beta: number; +} + +interface PluginArray { + length: number; + refresh(reload?: boolean): void; + item(index: number): Plugin; + [index: number]: Plugin; + namedItem(name: string): Plugin; + //[name: string]: Plugin; +} + +interface MSMediaKeyError { + systemCode: number; + code: number; + MS_MEDIA_KEYERR_SERVICE: number; + MS_MEDIA_KEYERR_HARDWARECHANGE: number; + MS_MEDIA_KEYERR_OUTPUT: number; + MS_MEDIA_KEYERR_DOMAIN: number; + MS_MEDIA_KEYERR_UNKNOWN: number; + MS_MEDIA_KEYERR_CLIENT: number; +} +declare var MSMediaKeyError: { + MS_MEDIA_KEYERR_SERVICE: number; + MS_MEDIA_KEYERR_HARDWARECHANGE: number; + MS_MEDIA_KEYERR_OUTPUT: number; + MS_MEDIA_KEYERR_DOMAIN: number; + MS_MEDIA_KEYERR_UNKNOWN: number; + MS_MEDIA_KEYERR_CLIENT: number; +} + +interface Plugin { + length: number; + filename: string; + version: string; + name: string; + description: string; + item(index: number): MimeType; + [index: number]: MimeType; + namedItem(type: string): MimeType; + //[type: string]: MimeType; +} + +interface HTMLFrameSetElement { + onpageshow: (ev: PageTransitionEvent) => any; + onpagehide: (ev: PageTransitionEvent) => any; +} + +interface Screen extends EventTarget { + msOrientation: string; + onmsorientationchange: (ev: any) => any; + msLockOrientation(orientation: string): boolean; + msLockOrientation(orientations: string[]): boolean; + msUnlockOrientation(): void; +} + +interface MediaSource extends EventTarget { + sourceBuffers: SourceBufferList; + duration: number; + readyState: string; + activeSourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: string): void; + isTypeSupported(type: string): boolean; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} +declare var MediaSource: { + prototype: MediaSource; + new (): MediaSource; +} + +interface MediaError { + MS_MEDIA_ERR_ENCRYPTED: number; +} +//declare var MediaError: { +// MS_MEDIA_ERR_ENCRYPTED: number; +//} + +interface SourceBufferList extends EventTarget { + length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +interface XMLDocument extends Document { +} + +interface DeviceMotionEvent extends Event { + rotationRate: DeviceRotationRate; + acceleration: DeviceAcceleration; + interval: number; + accelerationIncludingGravity: DeviceAcceleration; + initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict, accelerationIncludingGravity: DeviceAccelerationDict, rotationRate: DeviceRotationRateDict, interval: number): void; +} + +interface MimeType { + enabledPlugin: Plugin; + suffixes: string; + type: string; + description: string; +} + +interface PointerEvent extends MouseEvent { + width: number; + rotation: number; + pressure: number; + pointerType: any; + isPrimary: boolean; + tiltY: number; + height: number; + intermediatePoints: any; + currentPoint: any; + tiltX: number; + hwTimestamp: number; + pointerId: number; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; +} + +interface MSDocumentExtensions { + captureEvents(): void; + releaseEvents(): void; +} + +interface HTMLElement { + dataset: DOMStringMap; + hidden: boolean; + msGetInputContext(): MSInputMethodContext; +} + +interface MutationObserver { + observe(target: Node, options: MutationObserverInit): void; + takeRecords(): MutationRecord[]; + disconnect(): void; +} +declare var MutationObserver: { + prototype: MutationObserver; + new (callback: (arr: MutationRecord[], observer: MutationObserver)=>any): MutationObserver; +} + +interface AudioTrackList { + onremovetrack: (ev: PluginArray) => any; +} + +interface HTMLObjectElement { + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + readyState: number; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + msPlayToSource: any; +} + +interface HTMLEmbedElement { + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + readyState: string; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + msPlayToSource: any; +} + +interface MSWebViewAsyncOperation extends EventTarget { + target: MSHTMLWebViewElement; + oncomplete: (ev: any) => any; + error: DOMError; + onerror: (ev: any) => any; + readyState: number; + type: number; + result: any; + start(): void; + ERROR: number; + TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; + TYPE_INVOKE_SCRIPT: number; + COMPLETED: number; + TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; + STARTED: number; +} +declare var MSWebViewAsyncOperation: { + ERROR: number; + TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; + TYPE_INVOKE_SCRIPT: number; + COMPLETED: number; + TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; + STARTED: number; +} + +interface ScriptNotifyEvent extends Event { + value: string; + callingUri: string; +} + +interface PerformanceNavigationTiming extends PerformanceEntry { + redirectStart: number; + domainLookupEnd: number; + responseStart: number; + domComplete: number; + domainLookupStart: number; + loadEventStart: number; + unloadEventEnd: number; + fetchStart: number; + requestStart: number; + domInteractive: number; + navigationStart: number; + connectEnd: number; + loadEventEnd: number; + connectStart: number; + responseEnd: number; + domLoading: number; + redirectEnd: number; + redirectCount: number; + unloadEventStart: number; + domContentLoadedEventStart: number; + domContentLoadedEventEnd: number; + type: string; +} + +interface MSMediaKeyNeededEvent extends Event { + initData: Uint8Array; +} + +interface MSManipulationEvent { + MS_MANIPULATION_STATE_SELECTING: number; + MS_MANIPULATION_STATE_COMMITTED: number; + MS_MANIPULATION_STATE_PRESELECT: number; + MS_MANIPULATION_STATE_DRAGGING: number; + MS_MANIPULATION_STATE_CANCELLED: number; +} +//declare var MSManipulationEvent: { +// MS_MANIPULATION_STATE_SELECTING: number; +// MS_MANIPULATION_STATE_COMMITTED: number; +// MS_MANIPULATION_STATE_PRESELECT: number; +// MS_MANIPULATION_STATE_DRAGGING: number; +// MS_MANIPULATION_STATE_CANCELLED: number; +//} + +interface LongRunningScriptDetectedEvent extends Event { + stopPageScriptExecution: boolean; + executionTime: number; +} + +interface MSAppView { + viewId: number; + close(): void; + postMessage(message: any, targetOrigin: string, ports?: any): void; +} + +interface PerfWidgetExternal { + maxCpuSpeed: number; + independentRenderingEnabled: boolean; + irDisablingContentString: string; + irStatusAvailable: boolean; + performanceCounter: number; + averagePaintTime: number; + activeNetworkRequestCount: number; + paintRequestsPerSecond: number; + extraInformationEnabled: boolean; + performanceCounterFrequency: number; + averageFrameTime: number; + repositionWindow(x: number, y: number): void; + getRecentMemoryUsage(last: number): any; + getMemoryUsage(): number; + resizeWindow(width: number, height: number): void; + getProcessCpuUsage(): number; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; + removeEventListener(eventType: string, callback: (ev: any) => any): void; + getRecentCpuUsage(last: number): any; + addEventListener(eventType: string, callback: (ev: any) => any): void; + getRecentFrames(last: number): any; + getRecentPaintRequests(last: number): any; +} + +interface PageTransitionEvent extends Event { + persisted: boolean; +} + +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} + +interface HTMLDocument extends Document { +} + +interface KeyPair { + privateKey: Key; + publicKey: Key; +} + +interface MSApp { + getViewOpener(): MSAppView; + suppressSubdownloadCredentialPrompts(suppress: boolean): void; + execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void; + isTaskScheduledAtPriorityOrHigher(priority: string): boolean; + execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any; + createNewView(uri: string): MSAppView; + getCurrentPriority(): string; + NORMAL: string; + HIGH: string; + IDLE: string; + CURRENT: string; +} +//declare var MSApp: { +// NORMAL: string; +// HIGH: string; +// IDLE: string; +// CURRENT: string; +//} + +interface MSMediaKeySession extends EventTarget { + sessionId: string; + error: MSMediaKeyError; + keySystem: string; + close(): void; + update(key: Uint8Array): void; +} + +interface HTMLTrackElement { + readyState: number; + ERROR: number; + LOADING: number; + LOADED: number; + NONE: number; +} +//declare var HTMLTrackElement: { +// ERROR: number; +// LOADING: number; +// LOADED: number; +// NONE: number; +//} + +interface HTMLVideoElement { + getVideoPlaybackQuality(): VideoPlaybackQuality; +} + +interface UnviewableContentIdentifiedEvent extends NavigationEvent { + referrer: string; +} + +interface CryptoOperation extends EventTarget { + algorithm: Algorithm; + oncomplete: (ev: any) => any; + onerror: (ev: any) => any; + onprogress: (ev: any) => any; + onabort: (ev: any) => any; + key: Key; + result: any; + abort(): void; + finish(): void; + process(buffer: ArrayBufferView): void; +} + +declare var onpageshow: (ev: PageTransitionEvent) => any; +declare var ondevicemotion: (ev: DeviceMotionEvent) => any; +declare var devicePixelRatio: number; +declare var msCrypto: Crypto; +declare var ondeviceorientation: (ev: DeviceOrientationEvent) => any; +declare var doNotTrack: string; +declare var onmspointerenter: (ev: any) => any; +declare var onpagehide: (ev: PageTransitionEvent) => any; +declare var onmspointerleave: (ev: any) => any; +declare var onpointerenter: (ev: PointerEvent) => any; +declare var onpointerout: (ev: PointerEvent) => any; +declare var onpointerdown: (ev: PointerEvent) => any; +declare var onpointerup: (ev: PointerEvent) => any; +declare var onpointercancel: (ev: PointerEvent) => any; +declare var onpointerover: (ev: PointerEvent) => any; +declare var onpointermove: (ev: PointerEvent) => any; +declare var onpointerleave: (ev: PointerEvent) => any; + + +///////////////////////////// +/// WebGL APIs +///////////////////////////// + + +interface WebGLTexture extends WebGLObject { +} + +interface OES_texture_float { +} + +interface WebGLContextEvent extends Event { + statusMessage: string; +} +declare var WebGLContextEvent: { + prototype: WebGLContextEvent; + new (): WebGLContextEvent; +} + +interface WebGLRenderbuffer extends WebGLObject { +} + +interface WebGLUniformLocation { +} + +interface WebGLActiveInfo { + name: string; + type: number; + size: number; +} + +interface WEBGL_compressed_texture_s3tc { + COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} +declare var WEBGL_compressed_texture_s3tc: { + COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +interface WebGLContextAttributes { + alpha: boolean; + depth: boolean; + stencil: boolean; + antialias: boolean; + premultipliedAlpha: boolean; + preserveDrawingBuffer: boolean; +} + +interface WebGLRenderingContext { + drawingBufferWidth: number; + drawingBufferHeight: number; + canvas: HTMLCanvasElement; + getUniformLocation(program: WebGLProgram, name: string): WebGLUniformLocation; + bindTexture(target: number, texture: WebGLTexture): void; + bufferData(target: number, data: ArrayBufferView, usage: number): void; + bufferData(target: number, data: ArrayBuffer, usage: number): void; + bufferData(target: number, size: number, usage: number): void; + depthMask(flag: boolean): void; + getUniform(program: WebGLProgram, location: WebGLUniformLocation): any; + vertexAttrib3fv(indx: number, values: number[]): void; + vertexAttrib3fv(indx: number, values: Float32Array): void; + linkProgram(program: WebGLProgram): void; + getSupportedExtensions(): string[]; + bufferSubData(target: number, offset: number, data: ArrayBuffer): void; + bufferSubData(target: number, offset: number, data: ArrayBufferView): void; + vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void; + polygonOffset(factor: number, units: number): void; + blendColor(red: number, green: number, blue: number, alpha: number): void; + createTexture(): WebGLTexture; + hint(target: number, mode: number): void; + getVertexAttrib(index: number, pname: number): any; + enableVertexAttribArray(index: number): void; + depthRange(zNear: number, zFar: number): void; + cullFace(mode: number): void; + createFramebuffer(): WebGLFramebuffer; + uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: number[]): void; + uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; + framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture, level: number): void; + deleteFramebuffer(framebuffer: WebGLFramebuffer): void; + colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: ArrayBufferView): void; + uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: number[]): void; + uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; + getExtension(name: string): Object; + createProgram(): WebGLProgram; + deleteShader(shader: WebGLShader): void; + getAttachedShaders(program: WebGLProgram): WebGLShader[]; + enable(cap: number): void; + blendEquation(mode: number): void; + texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, image: HTMLImageElement): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, canvas: HTMLCanvasElement): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, video: HTMLVideoElement): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageData): void; + createBuffer(): WebGLBuffer; + deleteTexture(texture: WebGLTexture): void; + useProgram(program: WebGLProgram): void; + vertexAttrib2fv(indx: number, values: number[]): void; + vertexAttrib2fv(indx: number, values: Float32Array): void; + checkFramebufferStatus(target: number): number; + frontFace(mode: number): void; + getBufferParameter(target: number, pname: number): any; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, image: HTMLImageElement): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, canvas: HTMLCanvasElement): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, video: HTMLVideoElement): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void; + copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void; + getVertexAttribOffset(index: number, pname: number): number; + disableVertexAttribArray(index: number): void; + blendFunc(sfactor: number, dfactor: number): void; + drawElements(mode: number, count: number, type: number, offset: number): void; + isFramebuffer(framebuffer: WebGLFramebuffer): boolean; + uniform3iv(location: WebGLUniformLocation, v: number[]): void; + uniform3iv(location: WebGLUniformLocation, v: Int32Array): void; + lineWidth(width: number): void; + getShaderInfoLog(shader: WebGLShader): string; + getTexParameter(target: number, pname: number): any; + getParameter(pname: number): any; + getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat; + getContextAttributes(): WebGLContextAttributes; + vertexAttrib1f(indx: number, x: number): void; + bindFramebuffer(target: number, framebuffer: WebGLFramebuffer): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: ArrayBufferView): void; + isContextLost(): boolean; + uniform1iv(location: WebGLUniformLocation, v: number[]): void; + uniform1iv(location: WebGLUniformLocation, v: Int32Array): void; + getRenderbufferParameter(target: number, pname: number): any; + uniform2fv(location: WebGLUniformLocation, v: number[]): void; + uniform2fv(location: WebGLUniformLocation, v: Float32Array): void; + isTexture(texture: WebGLTexture): boolean; + getError(): number; + shaderSource(shader: WebGLShader, source: string): void; + deleteRenderbuffer(renderbuffer: WebGLRenderbuffer): void; + stencilMask(mask: number): void; + bindBuffer(target: number, buffer: WebGLBuffer): void; + getAttribLocation(program: WebGLProgram, name: string): number; + uniform3i(location: WebGLUniformLocation, x: number, y: number, z: number): void; + blendEquationSeparate(modeRGB: number, modeAlpha: number): void; + clear(mask: number): void; + blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void; + stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; + scissor(x: number, y: number, width: number, height: number): void; + uniform2i(location: WebGLUniformLocation, x: number, y: number): void; + getActiveAttrib(program: WebGLProgram, index: number): WebGLActiveInfo; + getShaderSource(shader: WebGLShader): string; + generateMipmap(target: number): void; + bindAttribLocation(program: WebGLProgram, index: number, name: string): void; + uniform1fv(location: WebGLUniformLocation, v: number[]): void; + uniform1fv(location: WebGLUniformLocation, v: Float32Array): void; + uniform2iv(location: WebGLUniformLocation, v: number[]): void; + uniform2iv(location: WebGLUniformLocation, v: Int32Array): void; + stencilOp(fail: number, zfail: number, zpass: number): void; + uniform4fv(location: WebGLUniformLocation, v: number[]): void; + uniform4fv(location: WebGLUniformLocation, v: Float32Array): void; + vertexAttrib1fv(indx: number, values: number[]): void; + vertexAttrib1fv(indx: number, values: Float32Array): void; + flush(): void; + uniform4f(location: WebGLUniformLocation, x: number, y: number, z: number, w: number): void; + deleteProgram(program: WebGLProgram): void; + isRenderbuffer(renderbuffer: WebGLRenderbuffer): boolean; + uniform1i(location: WebGLUniformLocation, x: number): void; + getProgramParameter(program: WebGLProgram, pname: number): any; + getActiveUniform(program: WebGLProgram, index: number): WebGLActiveInfo; + stencilFunc(func: number, ref: number, mask: number): void; + pixelStorei(pname: number, param: number): void; + disable(cap: number): void; + vertexAttrib4fv(indx: number, values: number[]): void; + vertexAttrib4fv(indx: number, values: Float32Array): void; + createRenderbuffer(): WebGLRenderbuffer; + isBuffer(buffer: WebGLBuffer): boolean; + stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; + getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; + uniform4i(location: WebGLUniformLocation, x: number, y: number, z: number, w: number): void; + sampleCoverage(value: number, invert: boolean): void; + depthFunc(func: number): void; + texParameterf(target: number, pname: number, param: number): void; + vertexAttrib3f(indx: number, x: number, y: number, z: number): void; + drawArrays(mode: number, first: number, count: number): void; + texParameteri(target: number, pname: number, param: number): void; + vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void; + getShaderParameter(shader: WebGLShader, pname: number): any; + clearDepth(depth: number): void; + activeTexture(texture: number): void; + viewport(x: number, y: number, width: number, height: number): void; + detachShader(program: WebGLProgram, shader: WebGLShader): void; + uniform1f(location: WebGLUniformLocation, x: number): void; + uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: number[]): void; + uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; + deleteBuffer(buffer: WebGLBuffer): void; + copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void; + uniform3fv(location: WebGLUniformLocation, v: number[]): void; + uniform3fv(location: WebGLUniformLocation, v: Float32Array): void; + stencilMaskSeparate(face: number, mask: number): void; + attachShader(program: WebGLProgram, shader: WebGLShader): void; + compileShader(shader: WebGLShader): void; + clearColor(red: number, green: number, blue: number, alpha: number): void; + isShader(shader: WebGLShader): boolean; + clearStencil(s: number): void; + framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer): void; + finish(): void; + uniform2f(location: WebGLUniformLocation, x: number, y: number): void; + renderbufferStorage(target: number, internalformat: number, width: number, height: number): void; + uniform3f(location: WebGLUniformLocation, x: number, y: number, z: number): void; + getProgramInfoLog(program: WebGLProgram): string; + validateProgram(program: WebGLProgram): void; + isEnabled(cap: number): boolean; + vertexAttrib2f(indx: number, x: number, y: number): void; + isProgram(program: WebGLProgram): boolean; + createShader(type: number): WebGLShader; + bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer): void; + uniform4iv(location: WebGLUniformLocation, v: number[]): void; + uniform4iv(location: WebGLUniformLocation, v: Int32Array): void; + DEPTH_FUNC: number; + DEPTH_COMPONENT16: number; + REPLACE: number; + REPEAT: number; + VERTEX_ATTRIB_ARRAY_ENABLED: number; + FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + STENCIL_BUFFER_BIT: number; + RENDERER: number; + STENCIL_BACK_REF: number; + TEXTURE26: number; + RGB565: number; + DITHER: number; + CONSTANT_COLOR: number; + GENERATE_MIPMAP_HINT: number; + POINTS: number; + DECR: number; + INT_VEC3: number; + TEXTURE28: number; + ONE_MINUS_CONSTANT_ALPHA: number; + BACK: number; + RENDERBUFFER_STENCIL_SIZE: number; + UNPACK_FLIP_Y_WEBGL: number; + BLEND: number; + TEXTURE9: number; + ARRAY_BUFFER_BINDING: number; + MAX_VIEWPORT_DIMS: number; + INVALID_FRAMEBUFFER_OPERATION: number; + TEXTURE: number; + TEXTURE0: number; + TEXTURE31: number; + TEXTURE24: number; + HIGH_INT: number; + RENDERBUFFER_BINDING: number; + BLEND_COLOR: number; + FASTEST: number; + STENCIL_WRITEMASK: number; + ALIASED_POINT_SIZE_RANGE: number; + TEXTURE12: number; + DST_ALPHA: number; + BLEND_EQUATION_RGB: number; + FRAMEBUFFER_COMPLETE: number; + NEAREST_MIPMAP_NEAREST: number; + VERTEX_ATTRIB_ARRAY_SIZE: number; + TEXTURE3: number; + DEPTH_WRITEMASK: number; + CONTEXT_LOST_WEBGL: number; + INVALID_VALUE: number; + TEXTURE_MAG_FILTER: number; + ONE_MINUS_CONSTANT_COLOR: number; + ONE_MINUS_SRC_ALPHA: number; + TEXTURE_CUBE_MAP_POSITIVE_Z: number; + NOTEQUAL: number; + ALPHA: number; + DEPTH_STENCIL: number; + MAX_VERTEX_UNIFORM_VECTORS: number; + DEPTH_COMPONENT: number; + RENDERBUFFER_RED_SIZE: number; + TEXTURE20: number; + RED_BITS: number; + RENDERBUFFER_BLUE_SIZE: number; + SCISSOR_BOX: number; + VENDOR: number; + FRONT_AND_BACK: number; + CONSTANT_ALPHA: number; + VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + NEAREST: number; + CULL_FACE: number; + ALIASED_LINE_WIDTH_RANGE: number; + TEXTURE19: number; + FRONT: number; + DEPTH_CLEAR_VALUE: number; + GREEN_BITS: number; + TEXTURE29: number; + TEXTURE23: number; + MAX_RENDERBUFFER_SIZE: number; + STENCIL_ATTACHMENT: number; + TEXTURE27: number; + BOOL_VEC2: number; + OUT_OF_MEMORY: number; + MIRRORED_REPEAT: number; + POLYGON_OFFSET_UNITS: number; + TEXTURE_MIN_FILTER: number; + STENCIL_BACK_PASS_DEPTH_PASS: number; + LINE_LOOP: number; + FLOAT_MAT3: number; + TEXTURE14: number; + LINEAR: number; + RGB5_A1: number; + ONE_MINUS_SRC_COLOR: number; + SAMPLE_COVERAGE_INVERT: number; + DONT_CARE: number; + FRAMEBUFFER_BINDING: number; + RENDERBUFFER_ALPHA_SIZE: number; + STENCIL_REF: number; + ZERO: number; + DECR_WRAP: number; + SAMPLE_COVERAGE: number; + STENCIL_BACK_FUNC: number; + TEXTURE30: number; + VIEWPORT: number; + STENCIL_BITS: number; + FLOAT: number; + COLOR_WRITEMASK: number; + SAMPLE_COVERAGE_VALUE: number; + TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + STENCIL_BACK_FAIL: number; + FLOAT_MAT4: number; + UNSIGNED_SHORT_4_4_4_4: number; + TEXTURE6: number; + RENDERBUFFER_WIDTH: number; + RGBA4: number; + ALWAYS: number; + BLEND_EQUATION_ALPHA: number; + COLOR_BUFFER_BIT: number; + TEXTURE_CUBE_MAP: number; + DEPTH_BUFFER_BIT: number; + STENCIL_CLEAR_VALUE: number; + BLEND_EQUATION: number; + RENDERBUFFER_GREEN_SIZE: number; + NEAREST_MIPMAP_LINEAR: number; + VERTEX_ATTRIB_ARRAY_TYPE: number; + INCR_WRAP: number; + ONE_MINUS_DST_COLOR: number; + HIGH_FLOAT: number; + BYTE: number; + FRONT_FACE: number; + SAMPLE_ALPHA_TO_COVERAGE: number; + CCW: number; + TEXTURE13: number; + MAX_VERTEX_ATTRIBS: number; + MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + TEXTURE_WRAP_T: number; + UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + FLOAT_VEC2: number; + LUMINANCE: number; + GREATER: number; + INT_VEC2: number; + VALIDATE_STATUS: number; + FRAMEBUFFER: number; + FRAMEBUFFER_UNSUPPORTED: number; + TEXTURE5: number; + FUNC_SUBTRACT: number; + BLEND_DST_ALPHA: number; + SAMPLER_CUBE: number; + ONE_MINUS_DST_ALPHA: number; + LESS: number; + TEXTURE_CUBE_MAP_POSITIVE_X: number; + BLUE_BITS: number; + DEPTH_TEST: number; + VERTEX_ATTRIB_ARRAY_STRIDE: number; + DELETE_STATUS: number; + TEXTURE18: number; + POLYGON_OFFSET_FACTOR: number; + UNSIGNED_INT: number; + TEXTURE_2D: number; + DST_COLOR: number; + FLOAT_MAT2: number; + COMPRESSED_TEXTURE_FORMATS: number; + MAX_FRAGMENT_UNIFORM_VECTORS: number; + DEPTH_STENCIL_ATTACHMENT: number; + LUMINANCE_ALPHA: number; + CW: number; + VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + LINEAR_MIPMAP_LINEAR: number; + BUFFER_SIZE: number; + SAMPLE_BUFFERS: number; + TEXTURE15: number; + ACTIVE_TEXTURE: number; + VERTEX_SHADER: number; + TEXTURE22: number; + VERTEX_ATTRIB_ARRAY_POINTER: number; + INCR: number; + COMPILE_STATUS: number; + MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + TEXTURE7: number; + UNSIGNED_SHORT_5_5_5_1: number; + DEPTH_BITS: number; + RGBA: number; + TRIANGLE_STRIP: number; + COLOR_CLEAR_VALUE: number; + BROWSER_DEFAULT_WEBGL: number; + INVALID_ENUM: number; + SCISSOR_TEST: number; + LINE_STRIP: number; + FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + STENCIL_FUNC: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + RENDERBUFFER_HEIGHT: number; + TEXTURE8: number; + TRIANGLES: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + STENCIL_BACK_VALUE_MASK: number; + TEXTURE25: number; + RENDERBUFFER: number; + LEQUAL: number; + TEXTURE1: number; + STENCIL_INDEX8: number; + FUNC_ADD: number; + STENCIL_FAIL: number; + BLEND_SRC_ALPHA: number; + BOOL: number; + ALPHA_BITS: number; + LOW_INT: number; + TEXTURE10: number; + SRC_COLOR: number; + MAX_VARYING_VECTORS: number; + BLEND_DST_RGB: number; + TEXTURE_BINDING_CUBE_MAP: number; + STENCIL_INDEX: number; + TEXTURE_BINDING_2D: number; + MEDIUM_INT: number; + SHADER_TYPE: number; + POLYGON_OFFSET_FILL: number; + DYNAMIC_DRAW: number; + TEXTURE4: number; + STENCIL_BACK_PASS_DEPTH_FAIL: number; + STREAM_DRAW: number; + MAX_CUBE_MAP_TEXTURE_SIZE: number; + TEXTURE17: number; + TRIANGLE_FAN: number; + UNPACK_ALIGNMENT: number; + CURRENT_PROGRAM: number; + LINES: number; + INVALID_OPERATION: number; + FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + LINEAR_MIPMAP_NEAREST: number; + CLAMP_TO_EDGE: number; + RENDERBUFFER_DEPTH_SIZE: number; + TEXTURE_WRAP_S: number; + ELEMENT_ARRAY_BUFFER: number; + UNSIGNED_SHORT_5_6_5: number; + ACTIVE_UNIFORMS: number; + FLOAT_VEC3: number; + NO_ERROR: number; + ATTACHED_SHADERS: number; + DEPTH_ATTACHMENT: number; + TEXTURE11: number; + STENCIL_TEST: number; + ONE: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + STATIC_DRAW: number; + GEQUAL: number; + BOOL_VEC4: number; + COLOR_ATTACHMENT0: number; + PACK_ALIGNMENT: number; + MAX_TEXTURE_SIZE: number; + STENCIL_PASS_DEPTH_FAIL: number; + CULL_FACE_MODE: number; + TEXTURE16: number; + STENCIL_BACK_WRITEMASK: number; + SRC_ALPHA: number; + UNSIGNED_SHORT: number; + TEXTURE21: number; + FUNC_REVERSE_SUBTRACT: number; + SHADING_LANGUAGE_VERSION: number; + EQUAL: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + BOOL_VEC3: number; + SAMPLER_2D: number; + TEXTURE_CUBE_MAP_NEGATIVE_X: number; + MAX_TEXTURE_IMAGE_UNITS: number; + TEXTURE_CUBE_MAP_POSITIVE_Y: number; + RENDERBUFFER_INTERNAL_FORMAT: number; + STENCIL_VALUE_MASK: number; + ELEMENT_ARRAY_BUFFER_BINDING: number; + ARRAY_BUFFER: number; + DEPTH_RANGE: number; + NICEST: number; + ACTIVE_ATTRIBUTES: number; + NEVER: number; + FLOAT_VEC4: number; + CURRENT_VERTEX_ATTRIB: number; + STENCIL_PASS_DEPTH_PASS: number; + INVERT: number; + LINK_STATUS: number; + RGB: number; + INT_VEC4: number; + TEXTURE2: number; + UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + MEDIUM_FLOAT: number; + SRC_ALPHA_SATURATE: number; + BUFFER_USAGE: number; + SHORT: number; + NONE: number; + UNSIGNED_BYTE: number; + INT: number; + SUBPIXEL_BITS: number; + KEEP: number; + SAMPLES: number; + FRAGMENT_SHADER: number; + LINE_WIDTH: number; + BLEND_SRC_RGB: number; + LOW_FLOAT: number; + VERSION: number; +} +declare var WebGLRenderingContext: { + DEPTH_FUNC: number; + DEPTH_COMPONENT16: number; + REPLACE: number; + REPEAT: number; + VERTEX_ATTRIB_ARRAY_ENABLED: number; + FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + STENCIL_BUFFER_BIT: number; + RENDERER: number; + STENCIL_BACK_REF: number; + TEXTURE26: number; + RGB565: number; + DITHER: number; + CONSTANT_COLOR: number; + GENERATE_MIPMAP_HINT: number; + POINTS: number; + DECR: number; + INT_VEC3: number; + TEXTURE28: number; + ONE_MINUS_CONSTANT_ALPHA: number; + BACK: number; + RENDERBUFFER_STENCIL_SIZE: number; + UNPACK_FLIP_Y_WEBGL: number; + BLEND: number; + TEXTURE9: number; + ARRAY_BUFFER_BINDING: number; + MAX_VIEWPORT_DIMS: number; + INVALID_FRAMEBUFFER_OPERATION: number; + TEXTURE: number; + TEXTURE0: number; + TEXTURE31: number; + TEXTURE24: number; + HIGH_INT: number; + RENDERBUFFER_BINDING: number; + BLEND_COLOR: number; + FASTEST: number; + STENCIL_WRITEMASK: number; + ALIASED_POINT_SIZE_RANGE: number; + TEXTURE12: number; + DST_ALPHA: number; + BLEND_EQUATION_RGB: number; + FRAMEBUFFER_COMPLETE: number; + NEAREST_MIPMAP_NEAREST: number; + VERTEX_ATTRIB_ARRAY_SIZE: number; + TEXTURE3: number; + DEPTH_WRITEMASK: number; + CONTEXT_LOST_WEBGL: number; + INVALID_VALUE: number; + TEXTURE_MAG_FILTER: number; + ONE_MINUS_CONSTANT_COLOR: number; + ONE_MINUS_SRC_ALPHA: number; + TEXTURE_CUBE_MAP_POSITIVE_Z: number; + NOTEQUAL: number; + ALPHA: number; + DEPTH_STENCIL: number; + MAX_VERTEX_UNIFORM_VECTORS: number; + DEPTH_COMPONENT: number; + RENDERBUFFER_RED_SIZE: number; + TEXTURE20: number; + RED_BITS: number; + RENDERBUFFER_BLUE_SIZE: number; + SCISSOR_BOX: number; + VENDOR: number; + FRONT_AND_BACK: number; + CONSTANT_ALPHA: number; + VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + NEAREST: number; + CULL_FACE: number; + ALIASED_LINE_WIDTH_RANGE: number; + TEXTURE19: number; + FRONT: number; + DEPTH_CLEAR_VALUE: number; + GREEN_BITS: number; + TEXTURE29: number; + TEXTURE23: number; + MAX_RENDERBUFFER_SIZE: number; + STENCIL_ATTACHMENT: number; + TEXTURE27: number; + BOOL_VEC2: number; + OUT_OF_MEMORY: number; + MIRRORED_REPEAT: number; + POLYGON_OFFSET_UNITS: number; + TEXTURE_MIN_FILTER: number; + STENCIL_BACK_PASS_DEPTH_PASS: number; + LINE_LOOP: number; + FLOAT_MAT3: number; + TEXTURE14: number; + LINEAR: number; + RGB5_A1: number; + ONE_MINUS_SRC_COLOR: number; + SAMPLE_COVERAGE_INVERT: number; + DONT_CARE: number; + FRAMEBUFFER_BINDING: number; + RENDERBUFFER_ALPHA_SIZE: number; + STENCIL_REF: number; + ZERO: number; + DECR_WRAP: number; + SAMPLE_COVERAGE: number; + STENCIL_BACK_FUNC: number; + TEXTURE30: number; + VIEWPORT: number; + STENCIL_BITS: number; + FLOAT: number; + COLOR_WRITEMASK: number; + SAMPLE_COVERAGE_VALUE: number; + TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + STENCIL_BACK_FAIL: number; + FLOAT_MAT4: number; + UNSIGNED_SHORT_4_4_4_4: number; + TEXTURE6: number; + RENDERBUFFER_WIDTH: number; + RGBA4: number; + ALWAYS: number; + BLEND_EQUATION_ALPHA: number; + COLOR_BUFFER_BIT: number; + TEXTURE_CUBE_MAP: number; + DEPTH_BUFFER_BIT: number; + STENCIL_CLEAR_VALUE: number; + BLEND_EQUATION: number; + RENDERBUFFER_GREEN_SIZE: number; + NEAREST_MIPMAP_LINEAR: number; + VERTEX_ATTRIB_ARRAY_TYPE: number; + INCR_WRAP: number; + ONE_MINUS_DST_COLOR: number; + HIGH_FLOAT: number; + BYTE: number; + FRONT_FACE: number; + SAMPLE_ALPHA_TO_COVERAGE: number; + CCW: number; + TEXTURE13: number; + MAX_VERTEX_ATTRIBS: number; + MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + TEXTURE_WRAP_T: number; + UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + FLOAT_VEC2: number; + LUMINANCE: number; + GREATER: number; + INT_VEC2: number; + VALIDATE_STATUS: number; + FRAMEBUFFER: number; + FRAMEBUFFER_UNSUPPORTED: number; + TEXTURE5: number; + FUNC_SUBTRACT: number; + BLEND_DST_ALPHA: number; + SAMPLER_CUBE: number; + ONE_MINUS_DST_ALPHA: number; + LESS: number; + TEXTURE_CUBE_MAP_POSITIVE_X: number; + BLUE_BITS: number; + DEPTH_TEST: number; + VERTEX_ATTRIB_ARRAY_STRIDE: number; + DELETE_STATUS: number; + TEXTURE18: number; + POLYGON_OFFSET_FACTOR: number; + UNSIGNED_INT: number; + TEXTURE_2D: number; + DST_COLOR: number; + FLOAT_MAT2: number; + COMPRESSED_TEXTURE_FORMATS: number; + MAX_FRAGMENT_UNIFORM_VECTORS: number; + DEPTH_STENCIL_ATTACHMENT: number; + LUMINANCE_ALPHA: number; + CW: number; + VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + LINEAR_MIPMAP_LINEAR: number; + BUFFER_SIZE: number; + SAMPLE_BUFFERS: number; + TEXTURE15: number; + ACTIVE_TEXTURE: number; + VERTEX_SHADER: number; + TEXTURE22: number; + VERTEX_ATTRIB_ARRAY_POINTER: number; + INCR: number; + COMPILE_STATUS: number; + MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + TEXTURE7: number; + UNSIGNED_SHORT_5_5_5_1: number; + DEPTH_BITS: number; + RGBA: number; + TRIANGLE_STRIP: number; + COLOR_CLEAR_VALUE: number; + BROWSER_DEFAULT_WEBGL: number; + INVALID_ENUM: number; + SCISSOR_TEST: number; + LINE_STRIP: number; + FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + STENCIL_FUNC: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + RENDERBUFFER_HEIGHT: number; + TEXTURE8: number; + TRIANGLES: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + STENCIL_BACK_VALUE_MASK: number; + TEXTURE25: number; + RENDERBUFFER: number; + LEQUAL: number; + TEXTURE1: number; + STENCIL_INDEX8: number; + FUNC_ADD: number; + STENCIL_FAIL: number; + BLEND_SRC_ALPHA: number; + BOOL: number; + ALPHA_BITS: number; + LOW_INT: number; + TEXTURE10: number; + SRC_COLOR: number; + MAX_VARYING_VECTORS: number; + BLEND_DST_RGB: number; + TEXTURE_BINDING_CUBE_MAP: number; + STENCIL_INDEX: number; + TEXTURE_BINDING_2D: number; + MEDIUM_INT: number; + SHADER_TYPE: number; + POLYGON_OFFSET_FILL: number; + DYNAMIC_DRAW: number; + TEXTURE4: number; + STENCIL_BACK_PASS_DEPTH_FAIL: number; + STREAM_DRAW: number; + MAX_CUBE_MAP_TEXTURE_SIZE: number; + TEXTURE17: number; + TRIANGLE_FAN: number; + UNPACK_ALIGNMENT: number; + CURRENT_PROGRAM: number; + LINES: number; + INVALID_OPERATION: number; + FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + LINEAR_MIPMAP_NEAREST: number; + CLAMP_TO_EDGE: number; + RENDERBUFFER_DEPTH_SIZE: number; + TEXTURE_WRAP_S: number; + ELEMENT_ARRAY_BUFFER: number; + UNSIGNED_SHORT_5_6_5: number; + ACTIVE_UNIFORMS: number; + FLOAT_VEC3: number; + NO_ERROR: number; + ATTACHED_SHADERS: number; + DEPTH_ATTACHMENT: number; + TEXTURE11: number; + STENCIL_TEST: number; + ONE: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + STATIC_DRAW: number; + GEQUAL: number; + BOOL_VEC4: number; + COLOR_ATTACHMENT0: number; + PACK_ALIGNMENT: number; + MAX_TEXTURE_SIZE: number; + STENCIL_PASS_DEPTH_FAIL: number; + CULL_FACE_MODE: number; + TEXTURE16: number; + STENCIL_BACK_WRITEMASK: number; + SRC_ALPHA: number; + UNSIGNED_SHORT: number; + TEXTURE21: number; + FUNC_REVERSE_SUBTRACT: number; + SHADING_LANGUAGE_VERSION: number; + EQUAL: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + BOOL_VEC3: number; + SAMPLER_2D: number; + TEXTURE_CUBE_MAP_NEGATIVE_X: number; + MAX_TEXTURE_IMAGE_UNITS: number; + TEXTURE_CUBE_MAP_POSITIVE_Y: number; + RENDERBUFFER_INTERNAL_FORMAT: number; + STENCIL_VALUE_MASK: number; + ELEMENT_ARRAY_BUFFER_BINDING: number; + ARRAY_BUFFER: number; + DEPTH_RANGE: number; + NICEST: number; + ACTIVE_ATTRIBUTES: number; + NEVER: number; + FLOAT_VEC4: number; + CURRENT_VERTEX_ATTRIB: number; + STENCIL_PASS_DEPTH_PASS: number; + INVERT: number; + LINK_STATUS: number; + RGB: number; + INT_VEC4: number; + TEXTURE2: number; + UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + MEDIUM_FLOAT: number; + SRC_ALPHA_SATURATE: number; + BUFFER_USAGE: number; + SHORT: number; + NONE: number; + UNSIGNED_BYTE: number; + INT: number; + SUBPIXEL_BITS: number; + KEEP: number; + SAMPLES: number; + FRAGMENT_SHADER: number; + LINE_WIDTH: number; + BLEND_SRC_RGB: number; + LOW_FLOAT: number; + VERSION: number; +} + +interface WebGLProgram extends WebGLObject { +} + +interface OES_standard_derivatives { + FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} +declare var OES_standard_derivatives: { + FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} + +interface WebGLFramebuffer extends WebGLObject { +} + +interface WebGLShader extends WebGLObject { +} + +interface OES_texture_float_linear { +} + +interface WebGLObject { +} + +interface WebGLBuffer extends WebGLObject { +} + +interface WebGLShaderPrecisionFormat { + rangeMin: number; + rangeMax: number; + precision: number; +} + +interface EXT_texture_filter_anisotropic { + TEXTURE_MAX_ANISOTROPY_EXT: number; + MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; +} +declare var EXT_texture_filter_anisotropic: { + TEXTURE_MAX_ANISOTROPY_EXT: number; + MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; +} + + +///////////////////////////// +/// addEventListener overloads +///////////////////////////// + +interface HTMLElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface Document { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "msthumbnailclick", listener: (ev: MSSiteModeEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stop", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mssitemodejumplistitemremoved", listener: (ev: MSSiteModeEvent) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectionchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "storagecommit", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msfullscreenerror", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msfullscreenchange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface Element { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSNamespaceInfo { + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface Window { + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "devicemotion", listener: (ev: DeviceMotionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "deviceorientation", listener: (ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface SVGElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLFrameElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface XMLHttpRequest { + addEventListener(type: "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLFrameSetElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface Screen { + addEventListener(type: "msorientationchange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface SVGSVGElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "zoom", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLIFrameElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLBodyElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface XDomainRequest { + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLMarqueeElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "bounce", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "start", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "finish", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSWindowExtensions { + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLMediaElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msneedkey", listener: (ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLVideoElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msneedkey", listener: (ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSVideoOptimalLayoutChanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "MSVideoFrameStepCompleted", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "MSVideoFormatChanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface TextTrackCue { + addEventListener(type: "enter", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "exit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface WebSocket { + addEventListener(type: "open", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "close", listener: (ev: CloseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface XMLHttpRequestEventTarget { + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface AudioTrackList { + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "addtrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: "removetrack", listener: (ev: any /*PluginArray*/) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSBaseReader { + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} +interface IDBTransaction { + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface TextTrackList { + addEventListener(type: "addtrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface IDBDatabase { + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface IDBOpenDBRequest { + addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "upgradeneeded", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blocked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface TextTrack { + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface IDBRequest { + addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MessagePort { + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface ApplicationCache { + addEventListener(type: "downloading", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "updateready", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cached", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "obsolete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "checking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "noupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface AbstractWorker { + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} +interface Worker { + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface GlobalEventHandlers { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} +interface KeyOperation { + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSInputMethodContext { + addEventListener(type: "candidatewindowshow", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "candidatewindowhide", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "candidatewindowupdate", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSWebViewAsyncOperation { + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface CryptoOperation { + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + + +declare function addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "devicemotion", listener: (ev: DeviceMotionEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "deviceorientation", listener: (ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; + + +///////////////////////////// +/// WorkerGlobalScope APIs +///////////////////////////// +// TODO: These are only available in a Web Worker - should be in a separate 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: any): void; + StdErr: ITextWriter; + StdOut: ITextWriter; + Arguments: { length: number; Item(n: number): string; }; + ScriptFullName: string; + Quit(exitCode?: number): number; +} diff --git a/_infrastructure/tests/typescript/1.0.1/tsc b/_infrastructure/tests/typescript/1.0.1/tsc new file mode 100644 index 0000000000..3c0dab574f --- /dev/null +++ b/_infrastructure/tests/typescript/1.0.1/tsc @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('./tsc.js') diff --git a/_infrastructure/tests/typescript/1.0.1/tsc.js b/_infrastructure/tests/typescript/1.0.1/tsc.js new file mode 100644 index 0000000000..5813312f1e --- /dev/null +++ b/_infrastructure/tests/typescript/1.0.1/tsc.js @@ -0,0 +1,62929 @@ +/*! ***************************************************************************** +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) { + TypeScript.DiagnosticCode = { + error_TS_0_1: "error TS{0}: {1}", + warning_TS_0_1: "warning TS{0}: {1}", + Unrecognized_escape_sequence: "Unrecognized escape sequence.", + Unexpected_character_0: "Unexpected character {0}.", + Missing_close_quote_character: "Missing close quote character.", + Identifier_expected: "Identifier expected.", + _0_keyword_expected: "'{0}' keyword expected.", + _0_expected: "'{0}' expected.", + Identifier_expected_0_is_a_keyword: "Identifier expected; '{0}' is a keyword.", + Automatic_semicolon_insertion_not_allowed: "Automatic semicolon insertion not allowed.", + Unexpected_token_0_expected: "Unexpected token; '{0}' expected.", + Trailing_separator_not_allowed: "Trailing separator not allowed.", + AsteriskSlash_expected: "'*/' expected.", + public_or_private_modifier_must_precede_static: "'public' or 'private' modifier must precede 'static'.", + Unexpected_token: "Unexpected token.", + Catch_clause_parameter_cannot_have_a_type_annotation: "Catch clause parameter cannot have a type annotation.", + Rest_parameter_must_be_last_in_list: "Rest parameter must be last in list.", + Parameter_cannot_have_question_mark_and_initializer: "Parameter cannot have question mark and initializer.", + Required_parameter_cannot_follow_optional_parameter: "Required parameter cannot follow optional parameter.", + Index_signatures_cannot_have_rest_parameters: "Index signatures cannot have rest parameters.", + Index_signature_parameter_cannot_have_accessibility_modifiers: "Index signature parameter cannot have accessibility modifiers.", + Index_signature_parameter_cannot_have_a_question_mark: "Index signature parameter cannot have a question mark.", + Index_signature_parameter_cannot_have_an_initializer: "Index signature parameter cannot have an initializer.", + Index_signature_must_have_a_type_annotation: "Index signature must have a type annotation.", + Index_signature_parameter_must_have_a_type_annotation: "Index signature parameter must have a type annotation.", + Index_signature_parameter_type_must_be_string_or_number: "Index signature parameter type must be 'string' or 'number'.", + extends_clause_already_seen: "'extends' clause already seen.", + extends_clause_must_precede_implements_clause: "'extends' clause must precede 'implements' clause.", + Classes_can_only_extend_a_single_class: "Classes can only extend a single class.", + implements_clause_already_seen: "'implements' clause already seen.", + Accessibility_modifier_already_seen: "Accessibility modifier already seen.", + _0_modifier_must_precede_1_modifier: "'{0}' modifier must precede '{1}' modifier.", + _0_modifier_already_seen: "'{0}' modifier already seen.", + _0_modifier_cannot_appear_on_a_class_element: "'{0}' modifier cannot appear on a class element.", + Interface_declaration_cannot_have_implements_clause: "Interface declaration cannot have 'implements' clause.", + super_invocation_cannot_have_type_arguments: "'super' invocation cannot have type arguments.", + Only_ambient_modules_can_use_quoted_names: "Only ambient modules can use quoted names.", + Statements_are_not_allowed_in_ambient_contexts: "Statements are not allowed in ambient contexts.", + Implementations_are_not_allowed_in_ambient_contexts: "Implementations are not allowed in ambient contexts.", + declare_modifier_not_allowed_for_code_already_in_an_ambient_context: "'declare' modifier not allowed for code already in an ambient context.", + Initializers_are_not_allowed_in_ambient_contexts: "Initializers are not allowed in ambient contexts.", + Parameter_property_declarations_can_only_be_used_in_a_non_ambient_constructor_declaration: "Parameter property declarations can only be used in a non-ambient constructor declaration.", + Function_implementation_expected: "Function implementation expected.", + Constructor_implementation_expected: "Constructor implementation expected.", + Function_overload_name_must_be_0: "Function overload name must be '{0}'.", + _0_modifier_cannot_appear_on_a_module_element: "'{0}' modifier cannot appear on a module element.", + declare_modifier_cannot_appear_on_an_interface_declaration: "'declare' modifier cannot appear on an interface declaration.", + declare_modifier_required_for_top_level_element: "'declare' modifier required for top level element.", + Rest_parameter_cannot_be_optional: "Rest parameter cannot be optional.", + Rest_parameter_cannot_have_an_initializer: "Rest parameter cannot have an initializer.", + set_accessor_must_have_one_and_only_one_parameter: "'set' accessor must have one and only one parameter.", + set_accessor_parameter_cannot_be_optional: "'set' accessor parameter cannot be optional.", + set_accessor_parameter_cannot_have_an_initializer: "'set' accessor parameter cannot have an initializer.", + set_accessor_cannot_have_rest_parameter: "'set' accessor cannot have rest parameter.", + get_accessor_cannot_have_parameters: "'get' accessor cannot have parameters.", + Modifiers_cannot_appear_here: "Modifiers cannot appear here.", + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: "Accessors are only available when targeting ECMAScript 5 and higher.", + Class_name_cannot_be_0: "Class name cannot be '{0}'.", + Interface_name_cannot_be_0: "Interface name cannot be '{0}'.", + Enum_name_cannot_be_0: "Enum name cannot be '{0}'.", + Module_name_cannot_be_0: "Module name cannot be '{0}'.", + Enum_member_must_have_initializer: "Enum member must have initializer.", + Export_assignment_cannot_be_used_in_internal_modules: "Export assignment cannot be used in internal modules.", + Export_assignment_not_allowed_in_module_with_exported_element: "Export assignment not allowed in module with exported element.", + Module_cannot_have_multiple_export_assignments: "Module cannot have multiple export assignments.", + Ambient_enum_elements_can_only_have_integer_literal_initializers: "Ambient enum elements can only have integer literal initializers.", + module_class_interface_enum_import_or_statement: "module, class, interface, enum, import or statement", + constructor_function_accessor_or_variable: "constructor, function, accessor or variable", + statement: "statement", + case_or_default_clause: "case or default clause", + identifier: "identifier", + call_construct_index_property_or_function_signature: "call, construct, index, property or function signature", + expression: "expression", + type_name: "type name", + property_or_accessor: "property or accessor", + parameter: "parameter", + type: "type", + type_parameter: "type parameter", + declare_modifier_not_allowed_on_import_declaration: "'declare' modifier not allowed on import declaration.", + Function_overload_must_be_static: "Function overload must be static.", + Function_overload_must_not_be_static: "Function overload must not be static.", + Parameter_property_declarations_cannot_be_used_in_a_constructor_overload: "Parameter property declarations cannot be used in a constructor overload.", + Invalid_reference_directive_syntax: "Invalid 'reference' directive syntax.", + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: "Octal literals are not available when targeting ECMAScript 5 and higher.", + Accessors_are_not_allowed_in_ambient_contexts: "Accessors are not allowed in ambient contexts.", + _0_modifier_cannot_appear_on_a_constructor_declaration: "'{0}' modifier cannot appear on a constructor declaration.", + _0_modifier_cannot_appear_on_a_parameter: "'{0}' modifier cannot appear on a parameter.", + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: "Only a single variable declaration is allowed in a 'for...in' statement.", + Type_parameters_cannot_appear_on_a_constructor_declaration: "Type parameters cannot appear on a constructor declaration.", + Type_annotation_cannot_appear_on_a_constructor_declaration: "Type annotation cannot appear on a constructor declaration.", + Duplicate_identifier_0: "Duplicate identifier '{0}'.", + The_name_0_does_not_exist_in_the_current_scope: "The name '{0}' does not exist in the current scope.", + The_name_0_does_not_refer_to_a_value: "The name '{0}' does not refer to a value.", + super_can_only_be_used_inside_a_class_instance_method: "'super' can only be used inside a class instance method.", + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_property_or_indexer: "The left-hand side of an assignment expression must be a variable, property or indexer.", + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: "Value of type '{0}' is not callable. Did you mean to include 'new'?", + Value_of_type_0_is_not_callable: "Value of type '{0}' is not callable.", + Value_of_type_0_is_not_newable: "Value of type '{0}' is not newable.", + Value_of_type_0_is_not_indexable_by_type_1: "Value of type '{0}' is not indexable by type '{1}'.", + Operator_0_cannot_be_applied_to_types_1_and_2: "Operator '{0}' cannot be applied to types '{1}' and '{2}'.", + Operator_0_cannot_be_applied_to_types_1_and_2_3: "Operator '{0}' cannot be applied to types '{1}' and '{2}': {3}", + Cannot_convert_0_to_1: "Cannot convert '{0}' to '{1}'.", + Cannot_convert_0_to_1_NL_2: "Cannot convert '{0}' to '{1}':{NL}{2}", + Expected_var_class_interface_or_module: "Expected var, class, interface, or module.", + Operator_0_cannot_be_applied_to_type_1: "Operator '{0}' cannot be applied to type '{1}'.", + Getter_0_already_declared: "Getter '{0}' already declared.", + Setter_0_already_declared: "Setter '{0}' already declared.", + Exported_class_0_extends_private_class_1: "Exported class '{0}' extends private class '{1}'.", + Exported_class_0_implements_private_interface_1: "Exported class '{0}' implements private interface '{1}'.", + Exported_interface_0_extends_private_interface_1: "Exported interface '{0}' extends private interface '{1}'.", + Exported_class_0_extends_class_from_inaccessible_module_1: "Exported class '{0}' extends class from inaccessible module {1}.", + Exported_class_0_implements_interface_from_inaccessible_module_1: "Exported class '{0}' implements interface from inaccessible module {1}.", + Exported_interface_0_extends_interface_from_inaccessible_module_1: "Exported interface '{0}' extends interface from inaccessible module {1}.", + Public_static_property_0_of_exported_class_has_or_is_using_private_type_1: "Public static property '{0}' of exported class has or is using private type '{1}'.", + Public_property_0_of_exported_class_has_or_is_using_private_type_1: "Public property '{0}' of exported class has or is using private type '{1}'.", + Property_0_of_exported_interface_has_or_is_using_private_type_1: "Property '{0}' of exported interface has or is using private type '{1}'.", + Exported_variable_0_has_or_is_using_private_type_1: "Exported variable '{0}' has or is using private type '{1}'.", + Public_static_property_0_of_exported_class_is_using_inaccessible_module_1: "Public static property '{0}' of exported class is using inaccessible module {1}.", + Public_property_0_of_exported_class_is_using_inaccessible_module_1: "Public property '{0}' of exported class is using inaccessible module {1}.", + Property_0_of_exported_interface_is_using_inaccessible_module_1: "Property '{0}' of exported interface is using inaccessible module {1}.", + Exported_variable_0_is_using_inaccessible_module_1: "Exported variable '{0}' is using inaccessible module {1}.", + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of constructor from exported class has or is using private type '{1}'.", + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public static property setter from exported class has or is using private type '{1}'.", + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public property setter from exported class has or is using private type '{1}'.", + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.", + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of call signature from exported interface has or is using private type '{1}'.", + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public static method from exported class has or is using private type '{1}'.", + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public method from exported class has or is using private type '{1}'.", + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of method from exported interface has or is using private type '{1}'.", + Parameter_0_of_exported_function_has_or_is_using_private_type_1: "Parameter '{0}' of exported function has or is using private type '{1}'.", + Parameter_0_of_constructor_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of constructor from exported class is using inaccessible module {1}.", + Parameter_0_of_public_static_property_setter_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public static property setter from exported class is using inaccessible module {1}.", + Parameter_0_of_public_property_setter_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public property setter from exported class is using inaccessible module {1}.", + Parameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.", + Parameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of call signature from exported interface is using inaccessible module {1}", + Parameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public static method from exported class is using inaccessible module {1}.", + Parameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public method from exported class is using inaccessible module {1}.", + Parameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of method from exported interface is using inaccessible module {1}.", + Parameter_0_of_exported_function_is_using_inaccessible_module_1: "Parameter '{0}' of exported function is using inaccessible module {1}.", + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type_0: "Return type of public static property getter from exported class has or is using private type '{0}'.", + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type_0: "Return type of public property getter from exported class has or is using private type '{0}'.", + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of constructor signature from exported interface has or is using private type '{0}'.", + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of call signature from exported interface has or is using private type '{0}'.", + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of index signature from exported interface has or is using private type '{0}'.", + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type_0: "Return type of public static method from exported class has or is using private type '{0}'.", + Return_type_of_public_method_from_exported_class_has_or_is_using_private_type_0: "Return type of public method from exported class has or is using private type '{0}'.", + Return_type_of_method_from_exported_interface_has_or_is_using_private_type_0: "Return type of method from exported interface has or is using private type '{0}'.", + Return_type_of_exported_function_has_or_is_using_private_type_0: "Return type of exported function has or is using private type '{0}'.", + Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module_0: "Return type of public static property getter from exported class is using inaccessible module {0}.", + Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module_0: "Return type of public property getter from exported class is using inaccessible module {0}.", + Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of constructor signature from exported interface is using inaccessible module {0}.", + Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of call signature from exported interface is using inaccessible module {0}.", + Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of index signature from exported interface is using inaccessible module {0}.", + Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module_0: "Return type of public static method from exported class is using inaccessible module {0}.", + Return_type_of_public_method_from_exported_class_is_using_inaccessible_module_0: "Return type of public method from exported class is using inaccessible module {0}.", + Return_type_of_method_from_exported_interface_is_using_inaccessible_module_0: "Return type of method from exported interface is using inaccessible module {0}.", + Return_type_of_exported_function_is_using_inaccessible_module_0: "Return type of exported function is using inaccessible module {0}.", + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: "'new T[]' cannot be used to create an array. Use 'new Array()' instead.", + A_parameter_list_must_follow_a_generic_type_argument_list_expected: "A parameter list must follow a generic type argument list. '(' expected.", + Multiple_constructor_implementations_are_not_allowed: "Multiple constructor implementations are not allowed.", + Unable_to_resolve_external_module_0: "Unable to resolve external module '{0}'.", + Module_cannot_be_aliased_to_a_non_module_type: "Module cannot be aliased to a non-module type.", + A_class_may_only_extend_another_class: "A class may only extend another class.", + A_class_may_only_implement_another_class_or_interface: "A class may only implement another class or interface.", + An_interface_may_only_extend_another_class_or_interface: "An interface may only extend another class or interface.", + Unable_to_resolve_type: "Unable to resolve type.", + Unable_to_resolve_type_of_0: "Unable to resolve type of '{0}'.", + Unable_to_resolve_type_parameter_constraint: "Unable to resolve type parameter constraint.", + Type_parameter_constraint_cannot_be_a_primitive_type: "Type parameter constraint cannot be a primitive type.", + Supplied_parameters_do_not_match_any_signature_of_call_target: "Supplied parameters do not match any signature of call target.", + Supplied_parameters_do_not_match_any_signature_of_call_target_NL_0: "Supplied parameters do not match any signature of call target:{NL}{0}", + Invalid_new_expression: "Invalid 'new' expression.", + Call_signatures_used_in_a_new_expression_must_have_a_void_return_type: "Call signatures used in a 'new' expression must have a 'void' return type.", + Could_not_select_overload_for_new_expression: "Could not select overload for 'new' expression.", + Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2: "Type '{0}' does not satisfy the constraint '{1}' for type parameter '{2}'.", + Could_not_select_overload_for_call_expression: "Could not select overload for 'call' expression.", + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: "Cannot invoke an expression whose type lacks a call signature.", + Calls_to_super_are_only_valid_inside_a_class: "Calls to 'super' are only valid inside a class.", + Generic_type_0_requires_1_type_argument_s: "Generic type '{0}' requires {1} type argument(s).", + Type_of_array_literal_cannot_be_determined_Best_common_type_could_not_be_found_for_array_elements: "Type of array literal cannot be determined. Best common type could not be found for array elements.", + Could_not_find_enclosing_symbol_for_dotted_name_0: "Could not find enclosing symbol for dotted name '{0}'.", + The_property_0_does_not_exist_on_value_of_type_1: "The property '{0}' does not exist on value of type '{1}'.", + Could_not_find_symbol_0: "Could not find symbol '{0}'.", + get_and_set_accessor_must_have_the_same_type: "'get' and 'set' accessor must have the same type.", + this_cannot_be_referenced_in_current_location: "'this' cannot be referenced in current location.", + Static_members_cannot_reference_class_type_parameters: "Static members cannot reference class type parameters.", + Class_0_is_recursively_referenced_as_a_base_type_of_itself: "Class '{0}' is recursively referenced as a base type of itself.", + Interface_0_is_recursively_referenced_as_a_base_type_of_itself: "Interface '{0}' is recursively referenced as a base type of itself.", + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class.", + super_cannot_be_referenced_in_non_derived_classes: "'super' cannot be referenced in non-derived classes.", + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.", + Constructors_for_derived_classes_must_contain_a_super_call: "Constructors for derived classes must contain a 'super' call.", + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: "Super calls are not permitted outside constructors or in nested functions inside constructors.", + _0_1_is_inaccessible: "'{0}.{1}' is inaccessible.", + this_cannot_be_referenced_within_module_bodies: "'this' cannot be referenced within module bodies.", + Invalid_expression_types_not_known_to_support_the_addition_operator: "Invalid '+' expression - types not known to support the addition operator.", + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type_any_number_or_an_enum_type: "The type of a unary arithmetic operation operand must be of type 'any', 'number' or an enum type.", + Variable_declarations_of_a_for_statement_cannot_use_a_type_annotation: "Variable declarations of a 'for' statement cannot use a type annotation.", + Variable_declarations_of_a_for_statement_must_be_of_types_string_or_any: "Variable declarations of a 'for' statement must be of types 'string' or 'any'.", + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter.", + The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number: "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'.", + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.", + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.", + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.", + Setters_cannot_return_a_value: "Setters cannot return a value.", + Tried_to_query_type_of_uninitialized_module_0: "Tried to query type of uninitialized module '{0}'.", + Tried_to_set_variable_type_to_uninitialized_module_type_0: "Tried to set variable type to uninitialized module type '{0}'.", + Type_0_does_not_have_type_parameters: "Type '{0}' does not have type parameters.", + Getters_must_return_a_value: "Getters must return a value.", + Getter_and_setter_accessors_do_not_agree_in_visibility: "Getter and setter accessors do not agree in visibility.", + Invalid_left_hand_side_of_assignment_expression: "Invalid left-hand side of assignment expression.", + Function_declared_a_non_void_return_type_but_has_no_return_expression: "Function declared a non-void return type, but has no return expression.", + Cannot_resolve_return_type_reference: "Cannot resolve return type reference.", + Constructors_cannot_have_a_return_type_of_void: "Constructors cannot have a return type of 'void'.", + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'.", + All_symbols_within_a_with_block_will_be_resolved_to_any: "All symbols within a with block will be resolved to 'any'.", + Import_declarations_in_an_internal_module_cannot_reference_an_external_module: "Import declarations in an internal module cannot reference an external module.", + Class_0_declares_interface_1_but_does_not_implement_it_NL_2: "Class {0} declares interface {1} but does not implement it:{NL}{2}", + Class_0_declares_class_1_as_an_interface_but_does_not_implement_it_NL_2: "Class {0} declares class {1} as an interface but does not implement it:{NL}{2}", + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: "The operand of an increment or decrement operator must be a variable, property or indexer.", + this_cannot_be_referenced_in_static_initializers_in_a_class_body: "'this' cannot be referenced in static initializers in a class body.", + Class_0_cannot_extend_class_1_NL_2: "Class '{0}' cannot extend class '{1}':{NL}{2}", + Interface_0_cannot_extend_class_1_NL_2: "Interface '{0}' cannot extend class '{1}':{NL}{2}", + Interface_0_cannot_extend_interface_1_NL_2: "Interface '{0}' cannot extend interface '{1}':{NL}{2}", + Duplicate_overload_signature_for_0: "Duplicate overload signature for '{0}'.", + Duplicate_constructor_overload_signature: "Duplicate constructor overload signature.", + Duplicate_overload_call_signature: "Duplicate overload call signature.", + Duplicate_overload_construct_signature: "Duplicate overload construct signature.", + Overload_signature_is_not_compatible_with_function_definition: "Overload signature is not compatible with function definition.", + Overload_signature_is_not_compatible_with_function_definition_NL_0: "Overload signature is not compatible with function definition:{NL}{0}", + Overload_signatures_must_all_be_public_or_private: "Overload signatures must all be public or private.", + Overload_signatures_must_all_be_exported_or_not_exported: "Overload signatures must all be exported or not exported.", + Overload_signatures_must_all_be_ambient_or_non_ambient: "Overload signatures must all be ambient or non-ambient.", + Overload_signatures_must_all_be_optional_or_required: "Overload signatures must all be optional or required.", + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: "Specialized overload signature is not assignable to any non-specialized signature.", + this_cannot_be_referenced_in_constructor_arguments: "'this' cannot be referenced in constructor arguments.", + Instance_member_cannot_be_accessed_off_a_class: "Instance member cannot be accessed off a class.", + Untyped_function_calls_may_not_accept_type_arguments: "Untyped function calls may not accept type arguments.", + Non_generic_functions_may_not_accept_type_arguments: "Non-generic functions may not accept type arguments.", + A_generic_type_may_not_reference_itself_with_a_wrapped_form_of_its_own_type_parameters: "A generic type may not reference itself with a wrapped form of its own type parameters.", + Rest_parameters_must_be_array_types: "Rest parameters must be array types.", + Overload_signature_implementation_cannot_use_specialized_type: "Overload signature implementation cannot use specialized type.", + Export_assignments_may_only_be_used_at_the_top_level_of_external_modules: "Export assignments may only be used at the top-level of external modules.", + Export_assignments_may_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: "Export assignments may only be made with variables, functions, classes, interfaces, enums and internal modules.", + Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword: "Only public methods of the base class are accessible via the 'super' keyword.", + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1: "Numeric indexer type '{0}' must be assignable to string indexer type '{1}'.", + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1_NL_2: "Numeric indexer type '{0}' must be assignable to string indexer type '{1}':{NL}{2}", + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0: "All numerically named properties must be assignable to numeric indexer type '{0}'.", + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0_NL_1: "All numerically named properties must be assignable to numeric indexer type '{0}':{NL}{1}", + All_named_properties_must_be_assignable_to_string_indexer_type_0: "All named properties must be assignable to string indexer type '{0}'.", + All_named_properties_must_be_assignable_to_string_indexer_type_0_NL_1: "All named properties must be assignable to string indexer type '{0}':{NL}{1}", + Generic_type_references_must_include_all_type_arguments: "Generic type references must include all type arguments.", + Default_arguments_are_only_allowed_in_implementation: "Default arguments are only allowed in implementation.", + Overloads_cannot_differ_only_by_return_type: "Overloads cannot differ only by return type.", + Function_expression_declared_a_non_void_return_type_but_has_no_return_expression: "Function expression declared a non-void return type, but has no return expression.", + Import_declaration_referencing_identifier_from_internal_module_can_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: "Import declaration referencing identifier from internal module can only be made with variables, functions, classes, interfaces, enums and internal modules.", + Could_not_find_symbol_0_in_module_1: "Could not find symbol '{0}' in module '{1}'.", + Unable_to_resolve_module_reference_0: "Unable to resolve module reference '{0}'.", + Could_not_find_module_0_in_module_1: "Could not find module '{0}' in module '{1}'.", + Exported_import_declaration_0_is_assigned_value_with_type_that_has_or_is_using_private_type_1: "Exported import declaration '{0}' is assigned value with type that has or is using private type '{1}'.", + Exported_import_declaration_0_is_assigned_value_with_type_that_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned value with type that is using inaccessible module '{1}'.", + Exported_import_declaration_0_is_assigned_type_that_has_or_is_using_private_type_1: "Exported import declaration '{0}' is assigned type that has or is using private type '{1}'.", + Exported_import_declaration_0_is_assigned_type_that_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned type that is using inaccessible module '{1}'.", + Exported_import_declaration_0_is_assigned_container_that_is_or_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned container that is or is using inaccessible module '{1}'.", + Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_1: "Type name '{0}' in extends clause does not reference constructor function for '{1}'.", + Internal_module_reference_0_in_import_declaration_does_not_reference_module_instance_for_1: "Internal module reference '{0}' in import declaration does not reference module instance for '{1}'.", + Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2: "Module '{0}' cannot merge with previous declaration of '{1}' in a different file '{2}'.", + Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':{NL}{3}", + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it.", + Ambient_external_module_declaration_cannot_be_reopened: "Ambient external module declaration cannot be reopened.", + All_declarations_of_merged_declaration_0_must_be_exported_or_not_exported: "All declarations of merged declaration '{0}' must be exported or not exported.", + super_cannot_be_referenced_in_constructor_arguments: "'super' cannot be referenced in constructor arguments.", + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: "Return type of constructor signature must be assignable to the instance type of the class.", + Ambient_external_module_declaration_must_be_defined_in_global_context: "Ambient external module declaration must be defined in global context.", + Ambient_external_module_declaration_cannot_specify_relative_module_name: "Ambient external module declaration cannot specify relative module name.", + Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name: "Import declaration in an ambient external module declaration cannot reference external module through relative external module name.", + Could_not_find_the_best_common_type_of_types_of_all_return_statement_expressions: "Could not find the best common type of types of all return statement expressions.", + Import_declaration_cannot_refer_to_external_module_reference_when_noResolve_option_is_set: "Import declaration cannot refer to external module reference when --noResolve option is set.", + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference.", + continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: "'continue' statement can only be used within an enclosing iteration statement.", + break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: "'break' statement can only be used within an enclosing iteration or switch statement.", + Jump_target_not_found: "Jump target not found.", + Jump_target_cannot_cross_function_boundary: "Jump target cannot cross function boundary.", + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference.", + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference.", + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: "Expression resolves to '_super' that compiler uses to capture base class reference.", + TypeParameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of call signature from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of public static method from exported class has or is using private type '{1}'.", + TypeParameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of public method from exported class has or is using private type '{1}'.", + TypeParameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of method from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_exported_function_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported function has or is using private type '{1}'.", + TypeParameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.", + TypeParameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of call signature from exported interface is using inaccessible module {1}", + TypeParameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of public static method from exported class is using inaccessible module {1}.", + TypeParameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of public method from exported class is using inaccessible module {1}.", + TypeParameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of method from exported interface is using inaccessible module {1}.", + TypeParameter_0_of_exported_function_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported function is using inaccessible module {1}.", + TypeParameter_0_of_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported class has or is using private type '{1}'.", + TypeParameter_0_of_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported interface has or is using private type '{1}'.", + TypeParameter_0_of_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported class is using inaccessible module {1}.", + TypeParameter_0_of_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported interface is using inaccessible module {1}.", + Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter: "Duplicate identifier '_i'. Compiler uses '_i' to initialize rest parameter.", + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters.", + Type_of_conditional_0_must_be_identical_to_1_or_2: "Type of conditional '{0}' must be identical to '{1}' or '{2}'.", + Type_of_conditional_0_must_be_identical_to_1_2_or_3: "Type of conditional '{0}' must be identical to '{1}', '{2}' or '{3}'.", + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of an external module.", + Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.", + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.", + Parameter_0_cannot_be_referenced_in_its_initializer: "Parameter '{0}' cannot be referenced in its initializer.", + Duplicate_string_index_signature: "Duplicate string index signature.", + Duplicate_number_index_signature: "Duplicate number index signature.", + All_declarations_of_an_interface_must_have_identical_type_parameters: "All declarations of an interface must have identical type parameters.", + Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter: "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter.", + Type_0_is_missing_property_1_from_type_2: "Type '{0}' is missing property '{1}' from type '{2}'.", + Types_of_property_0_of_types_1_and_2_are_incompatible: "Types of property '{0}' of types '{1}' and '{2}' are incompatible.", + Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3: "Types of property '{0}' of types '{1}' and '{2}' are incompatible:{NL}{3}", + Property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2: "Property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.", + Property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2: "Property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.", + Types_0_and_1_define_property_2_as_private: "Types '{0}' and '{1}' define property '{2}' as private.", + Call_signatures_of_types_0_and_1_are_incompatible: "Call signatures of types '{0}' and '{1}' are incompatible.", + Call_signatures_of_types_0_and_1_are_incompatible_NL_2: "Call signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Type_0_requires_a_call_signature_but_type_1_lacks_one: "Type '{0}' requires a call signature, but type '{1}' lacks one.", + Construct_signatures_of_types_0_and_1_are_incompatible: "Construct signatures of types '{0}' and '{1}' are incompatible.", + Construct_signatures_of_types_0_and_1_are_incompatible_NL_2: "Construct signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Type_0_requires_a_construct_signature_but_type_1_lacks_one: "Type '{0}' requires a construct signature, but type '{1}' lacks one.", + Index_signatures_of_types_0_and_1_are_incompatible: "Index signatures of types '{0}' and '{1}' are incompatible.", + Index_signatures_of_types_0_and_1_are_incompatible_NL_2: "Index signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Call_signature_expects_0_or_fewer_parameters: "Call signature expects {0} or fewer parameters.", + Could_not_apply_type_0_to_argument_1_which_is_of_type_2: "Could not apply type '{0}' to argument {1} which is of type '{2}'.", + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function.", + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.", + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor.", + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.", + Types_of_static_property_0_of_class_1_and_class_2_are_incompatible: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible.", + Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible:{NL}{3}", + Type_reference_cannot_refer_to_container_0: "Type reference cannot refer to container '{0}'.", + Type_reference_must_refer_to_type: "Type reference must refer to type.", + In_enums_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_the_first_enum_element: "In enums with multiple declarations only one declaration can omit an initializer for the first enum element.", + _0_overload_s: " (+ {0} overload(s))", + Variable_declaration_cannot_have_the_same_name_as_an_import_declaration: "Variable declaration cannot have the same name as an import declaration.", + Signature_expected_0_type_arguments_got_1_instead: "Signature expected {0} type arguments, got {1} instead.", + Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2: "Property '{0}' defined as optional in type '{1}', but is required in type '{2}'.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_do_not_refer_to_same_named_type: "Types '{0}' and '{1}' originating in infinitely expanding type reference do not refer to same named type.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments: "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2: "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments:{NL}{2}", + Named_properties_0_of_types_1_and_2_are_not_identical: "Named properties '{0}' of types '{1}' and '{2}' are not identical.", + Types_of_string_indexer_of_types_0_and_1_are_not_identical: "Types of string indexer of types '{0}' and '{1}' are not identical.", + Types_of_number_indexer_of_types_0_and_1_are_not_identical: "Types of number indexer of types '{0}' and '{1}' are not identical.", + Type_of_number_indexer_in_type_0_is_not_assignable_to_string_indexer_type_in_type_1_NL_2: "Type of number indexer in type '{0}' is not assignable to string indexer type in type '{1}'.{NL}{2}", + Type_of_property_0_in_type_1_is_not_assignable_to_string_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not assignable to string indexer type in type '{2}'.{NL}{3}", + Type_of_property_0_in_type_1_is_not_assignable_to_number_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not assignable to number indexer type in type '{2}'.{NL}{3}", + Static_property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2: "Static property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.", + Static_property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2: "Static property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.", + Types_0_and_1_define_static_property_2_as_private: "Types '{0}' and '{1}' define static property '{2}' as private.", + Current_host_does_not_support_0_option: "Current host does not support '{0}' option.", + ECMAScript_target_version_0_not_supported_Specify_a_valid_target_version_1_default_or_2: "ECMAScript target version '{0}' not supported. Specify a valid target version: '{1}' (default), or '{2}'", + Module_code_generation_0_not_supported: "Module code generation '{0}' not supported.", + Could_not_find_file_0: "Could not find file: '{0}'.", + A_file_cannot_have_a_reference_to_itself: "A file cannot have a reference to itself.", + Cannot_resolve_referenced_file_0: "Cannot resolve referenced file: '{0}'.", + Cannot_find_the_common_subdirectory_path_for_the_input_files: "Cannot find the common subdirectory path for the input files.", + Emit_Error_0: "Emit Error: {0}.", + Cannot_read_file_0_1: "Cannot read file '{0}': {1}", + Unsupported_file_encoding: "Unsupported file encoding.", + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: "Locale must be of the form or -. For example '{0}' or '{1}'.", + Unsupported_locale_0: "Unsupported locale: '{0}'.", + Execution_Failed_NL: "Execution Failed.{NL}", + Invalid_call_to_up: "Invalid call to 'up'", + Invalid_call_to_down: "Invalid call to 'down'", + Base64_value_0_finished_with_a_continuation_bit: "Base64 value '{0}' finished with a continuation bit.", + Unknown_option_0: "Unknown option '{0}'", + Expected_0_arguments_to_message_got_1_instead: "Expected {0} arguments to message, got {1} instead.", + Expected_the_message_0_to_have_1_arguments_but_it_had_2: "Expected the message '{0}' to have {1} arguments, but it had {2}", + Could_not_delete_file_0: "Could not delete file '{0}'", + Could_not_create_directory_0: "Could not create directory '{0}'", + Error_while_executing_file_0: "Error while executing file '{0}': ", + Cannot_compile_external_modules_unless_the_module_flag_is_provided: "Cannot compile external modules unless the '--module' flag is provided.", + Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: "Option mapRoot cannot be specified without specifying sourcemap option.", + Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: "Option sourceRoot cannot be specified without specifying sourcemap option.", + Options_mapRoot_and_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: "Options mapRoot and sourceRoot cannot be specified without specifying sourcemap option.", + Option_0_specified_without_1: "Option '{0}' specified without '{1}'", + codepage_option_not_supported_on_current_platform: "'codepage' option not supported on current platform.", + Concatenate_and_emit_output_to_single_file: "Concatenate and emit output to single file.", + Generates_corresponding_0_file: "Generates corresponding {0} file.", + Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: "Specifies the location where debugger should locate map files instead of generated locations.", + Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: "Specifies the location where debugger should locate TypeScript files instead of source locations.", + Watch_input_files: "Watch input files.", + Redirect_output_structure_to_the_directory: "Redirect output structure to the directory.", + Do_not_emit_comments_to_output: "Do not emit comments to output.", + Skip_resolution_and_preprocessing: "Skip resolution and preprocessing.", + Specify_ECMAScript_target_version_0_default_or_1: "Specify ECMAScript target version: '{0}' (default), or '{1}'", + Specify_module_code_generation_0_or_1: "Specify module code generation: '{0}' or '{1}'", + Print_this_message: "Print this message.", + Print_the_compiler_s_version_0: "Print the compiler's version: {0}", + Allow_use_of_deprecated_0_keyword_when_referencing_an_external_module: "Allow use of deprecated '{0}' keyword when referencing an external module.", + Specify_locale_for_errors_and_messages_For_example_0_or_1: "Specify locale for errors and messages. For example '{0}' or '{1}'", + Syntax_0: "Syntax: {0}", + options: "options", + file1: "file", + Examples: "Examples:", + Options: "Options:", + Insert_command_line_options_and_files_from_a_file: "Insert command line options and files from a file.", + Version_0: "Version {0}", + Use_the_0_flag_to_see_options: "Use the '{0}' flag to see options.", + NL_Recompiling_0: "{NL}Recompiling ({0}):", + STRING: "STRING", + KIND: "KIND", + file2: "FILE", + VERSION: "VERSION", + LOCATION: "LOCATION", + DIRECTORY: "DIRECTORY", + NUMBER: "NUMBER", + Specify_the_codepage_to_use_when_opening_source_files: "Specify the codepage to use when opening source files.", + Additional_locations: "Additional locations:", + This_version_of_the_Javascript_runtime_does_not_support_the_0_function: "This version of the Javascript runtime does not support the '{0}' function.", + Unknown_rule: "Unknown rule.", + Invalid_line_number_0: "Invalid line number ({0})", + Warn_on_expressions_and_declarations_with_an_implied_any_type: "Warn on expressions and declarations with an implied 'any' type.", + Variable_0_implicitly_has_an_any_type: "Variable '{0}' implicitly has an 'any' type.", + Parameter_0_of_1_implicitly_has_an_any_type: "Parameter '{0}' of '{1}' implicitly has an 'any' type.", + Parameter_0_of_function_type_implicitly_has_an_any_type: "Parameter '{0}' of function type implicitly has an 'any' type.", + Member_0_of_object_type_implicitly_has_an_any_type: "Member '{0}' of object type implicitly has an 'any' type.", + new_expression_which_lacks_a_constructor_signature_implicitly_has_an_any_type: "'new' expression, which lacks a constructor signature, implicitly has an 'any' type.", + _0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "'{0}', which lacks return-type annotation, implicitly has an 'any' return type.", + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Function expression, which lacks return-type annotation, implicitly has an 'any' return type.", + Parameter_0_of_lambda_function_implicitly_has_an_any_type: "Parameter '{0}' of lambda function implicitly has an 'any' type.", + Constructor_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Constructor signature, which lacks return-type annotation, implicitly has an 'any' return type.", + Lambda_Function_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Lambda Function, which lacks return-type annotation, implicitly has an 'any' return type.", + Array_Literal_implicitly_has_an_any_type_from_widening: "Array Literal implicitly has an 'any' type from widening.", + _0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type: "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type.", + Index_signature_of_object_type_implicitly_has_an_any_type: "Index signature of object type implicitly has an 'any' type.", + Object_literal_s_property_0_implicitly_has_an_any_type_from_widening: "Object literal's property '{0}' implicitly has an 'any' type from widening." + }; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ArrayUtilities = (function () { + function ArrayUtilities() { + } + ArrayUtilities.isArray = function (value) { + return Object.prototype.toString.apply(value, []) === '[object Array]'; + }; + + ArrayUtilities.sequenceEquals = function (array1, array2, equals) { + if (array1 === array2) { + return true; + } + + if (array1 === null || array2 === null) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0, n = array1.length; i < n; i++) { + if (!equals(array1[i], array2[i])) { + return false; + } + } + + return true; + }; + + ArrayUtilities.contains = function (array, value) { + for (var i = 0; i < array.length; i++) { + if (array[i] === value) { + return true; + } + } + + return false; + }; + + ArrayUtilities.groupBy = function (array, func) { + var result = {}; + + for (var i = 0, n = array.length; i < n; i++) { + var v = array[i]; + var k = func(v); + + var list = result[k] || []; + list.push(v); + result[k] = list; + } + + return result; + }; + + ArrayUtilities.distinct = function (array, equalsFn) { + var result = []; + + for (var i = 0, n = array.length; i < n; i++) { + var current = array[i]; + for (var j = 0; j < result.length; j++) { + if (equalsFn(result[j], current)) { + break; + } + } + + if (j === result.length) { + result.push(current); + } + } + + return result; + }; + + ArrayUtilities.min = function (array, func) { + var min = func(array[0]); + + for (var i = 1; i < array.length; i++) { + var next = func(array[i]); + if (next < min) { + min = next; + } + } + + return min; + }; + + ArrayUtilities.max = function (array, func) { + var max = func(array[0]); + + for (var i = 1; i < array.length; i++) { + var next = func(array[i]); + if (next > max) { + max = next; + } + } + + return max; + }; + + ArrayUtilities.last = function (array) { + if (array.length === 0) { + throw TypeScript.Errors.argumentOutOfRange('array'); + } + + return array[array.length - 1]; + }; + + ArrayUtilities.lastOrDefault = function (array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var v = array[i]; + if (predicate(v, i)) { + return v; + } + } + + return null; + }; + + ArrayUtilities.firstOrDefault = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + var value = array[i]; + if (func(value, i)) { + return value; + } + } + + return null; + }; + + ArrayUtilities.first = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + var value = array[i]; + if (!func || func(value, i)) { + return value; + } + } + + throw TypeScript.Errors.invalidOperation(); + }; + + ArrayUtilities.sum = function (array, func) { + var result = 0; + + for (var i = 0, n = array.length; i < n; i++) { + result += func(array[i]); + } + + return result; + }; + + ArrayUtilities.select = function (values, func) { + var result = new Array(values.length); + + for (var i = 0; i < values.length; i++) { + result[i] = func(values[i]); + } + + return result; + }; + + ArrayUtilities.where = function (values, func) { + var result = new Array(); + + for (var i = 0; i < values.length; i++) { + if (func(values[i])) { + result.push(values[i]); + } + } + + return result; + }; + + ArrayUtilities.any = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + if (func(array[i])) { + return true; + } + } + + return false; + }; + + ArrayUtilities.all = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + if (!func(array[i])) { + return false; + } + } + + return true; + }; + + ArrayUtilities.binarySearch = function (array, value) { + var low = 0; + var high = array.length - 1; + + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midValue = array[middle]; + + if (midValue === value) { + return middle; + } else if (midValue > value) { + high = middle - 1; + } else { + low = middle + 1; + } + } + + return ~low; + }; + + ArrayUtilities.createArray = function (length, defaultValue) { + var result = new Array(length); + for (var i = 0; i < length; i++) { + result[i] = defaultValue; + } + + return result; + }; + + ArrayUtilities.grow = function (array, length, defaultValue) { + var count = length - array.length; + for (var i = 0; i < count; i++) { + array.push(defaultValue); + } + }; + + ArrayUtilities.copy = function (sourceArray, sourceIndex, destinationArray, destinationIndex, length) { + for (var i = 0; i < length; i++) { + destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i]; + } + }; + + ArrayUtilities.indexOf = function (array, predicate) { + for (var i = 0, n = array.length; i < n; i++) { + if (predicate(array[i])) { + return i; + } + } + + return -1; + }; + return ArrayUtilities; + })(); + TypeScript.ArrayUtilities = ArrayUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (BitVector) { + var pool = []; + var Constants; + (function (Constants) { + Constants[Constants["MaxBitsPerEncodedNumber"] = 30] = "MaxBitsPerEncodedNumber"; + Constants[Constants["BitsPerEncodedBiStateValue"] = 1] = "BitsPerEncodedBiStateValue"; + + Constants[Constants["BitsPerEncodedTriStateValue"] = 2] = "BitsPerEncodedTriStateValue"; + + Constants[Constants["BiStateEncodedTrue"] = 1] = "BiStateEncodedTrue"; + Constants[Constants["BiStateClearBitsMask"] = 1] = "BiStateClearBitsMask"; + + Constants[Constants["TriStateEncodedFalse"] = 1] = "TriStateEncodedFalse"; + Constants[Constants["TriStateEncodedTrue"] = 2] = "TriStateEncodedTrue"; + Constants[Constants["TriStateClearBitsMask"] = 3] = "TriStateClearBitsMask"; + })(Constants || (Constants = {})); + + var BitVectorImpl = (function () { + function BitVectorImpl(allowUndefinedValues) { + this.allowUndefinedValues = allowUndefinedValues; + this.isReleased = false; + this.bits = []; + } + BitVectorImpl.prototype.computeTriStateArrayIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 2 /* BitsPerEncodedTriStateValue */; + + return (index / encodedValuesPerNumber) >>> 0; + }; + + BitVectorImpl.prototype.computeBiStateArrayIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 1 /* BitsPerEncodedBiStateValue */; + + return (index / encodedValuesPerNumber) >>> 0; + }; + + BitVectorImpl.prototype.computeTriStateEncodedValueIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 2 /* BitsPerEncodedTriStateValue */; + + return (index % encodedValuesPerNumber) * 2 /* BitsPerEncodedTriStateValue */; + }; + + BitVectorImpl.prototype.computeBiStateEncodedValueIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 1 /* BitsPerEncodedBiStateValue */; + + return (index % encodedValuesPerNumber) * 1 /* BitsPerEncodedBiStateValue */; + }; + + BitVectorImpl.prototype.valueAt = function (index) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + if (this.allowUndefinedValues) { + var arrayIndex = this.computeTriStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + return undefined; + } + + var bitIndex = this.computeTriStateEncodedValueIndex(index); + if (encoded & (2 /* TriStateEncodedTrue */ << bitIndex)) { + return true; + } else if (encoded & (1 /* TriStateEncodedFalse */ << bitIndex)) { + return false; + } else { + return undefined; + } + } else { + var arrayIndex = this.computeBiStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + return false; + } + + var bitIndex = this.computeBiStateEncodedValueIndex(index); + if (encoded & (1 /* BiStateEncodedTrue */ << bitIndex)) { + return true; + } else { + return false; + } + } + }; + + BitVectorImpl.prototype.setValueAt = function (index, value) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + if (this.allowUndefinedValues) { + TypeScript.Debug.assert(value === true || value === false || value === undefined, "value must only be true, false or undefined."); + + var arrayIndex = this.computeTriStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + if (value === undefined) { + return; + } + + encoded = 0; + } + + var bitIndex = this.computeTriStateEncodedValueIndex(index); + + var clearMask = ~(3 /* TriStateClearBitsMask */ << bitIndex); + encoded = encoded & clearMask; + + if (value === true) { + encoded = encoded | (2 /* TriStateEncodedTrue */ << bitIndex); + } else if (value === false) { + encoded = encoded | (1 /* TriStateEncodedFalse */ << bitIndex); + } + + this.bits[arrayIndex] = encoded; + } else { + TypeScript.Debug.assert(value === true || value === false, "value must only be true or false."); + + var arrayIndex = this.computeBiStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + if (value === false) { + return; + } + + encoded = 0; + } + + var bitIndex = this.computeBiStateEncodedValueIndex(index); + + encoded = encoded & ~(1 /* BiStateClearBitsMask */ << bitIndex); + + if (value) { + encoded = encoded | (1 /* BiStateEncodedTrue */ << bitIndex); + } + + this.bits[arrayIndex] = encoded; + } + }; + + BitVectorImpl.prototype.release = function () { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + this.isReleased = true; + this.bits.length = 0; + pool.push(this); + }; + return BitVectorImpl; + })(); + + function getBitVector(allowUndefinedValues) { + if (pool.length === 0) { + return new BitVectorImpl(allowUndefinedValues); + } + + var vector = pool.pop(); + vector.isReleased = false; + vector.allowUndefinedValues = allowUndefinedValues; + + return vector; + } + BitVector.getBitVector = getBitVector; + })(TypeScript.BitVector || (TypeScript.BitVector = {})); + var BitVector = TypeScript.BitVector; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (BitMatrix) { + var pool = []; + + var BitMatrixImpl = (function () { + function BitMatrixImpl(allowUndefinedValues) { + this.allowUndefinedValues = allowUndefinedValues; + this.isReleased = false; + this.vectors = []; + } + BitMatrixImpl.prototype.valueAt = function (x, y) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + var vector = this.vectors[x]; + if (!vector) { + return this.allowUndefinedValues ? undefined : false; + } + + return vector.valueAt(y); + }; + + BitMatrixImpl.prototype.setValueAt = function (x, y, value) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + var vector = this.vectors[x]; + if (!vector) { + if (value === undefined) { + return; + } + + vector = TypeScript.BitVector.getBitVector(this.allowUndefinedValues); + this.vectors[x] = vector; + } + + vector.setValueAt(y, value); + }; + + BitMatrixImpl.prototype.release = function () { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + this.isReleased = true; + + for (var name in this.vectors) { + if (this.vectors.hasOwnProperty(name)) { + var vector = this.vectors[name]; + vector.release(); + } + } + + this.vectors.length = 0; + pool.push(this); + }; + return BitMatrixImpl; + })(); + + function getBitMatrix(allowUndefinedValues) { + if (pool.length === 0) { + return new BitMatrixImpl(allowUndefinedValues); + } + + var matrix = pool.pop(); + matrix.isReleased = false; + matrix.allowUndefinedValues = allowUndefinedValues; + + return matrix; + } + BitMatrix.getBitMatrix = getBitMatrix; + })(TypeScript.BitMatrix || (TypeScript.BitMatrix = {})); + var BitMatrix = TypeScript.BitMatrix; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Constants) { + Constants[Constants["Max31BitInteger"] = 1073741823] = "Max31BitInteger"; + Constants[Constants["Min31BitInteger"] = -1073741824] = "Min31BitInteger"; + })(TypeScript.Constants || (TypeScript.Constants = {})); + var Constants = TypeScript.Constants; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(TypeScript.AssertionLevel || (TypeScript.AssertionLevel = {})); + var AssertionLevel = TypeScript.AssertionLevel; + + var Debug = (function () { + function Debug() { + } + Debug.shouldAssert = function (level) { + return this.currentAssertionLevel >= level; + }; + + Debug.assert = function (expression, message, verboseDebugInfo) { + if (typeof message === "undefined") { message = ""; } + if (typeof verboseDebugInfo === "undefined") { verboseDebugInfo = null; } + if (!expression) { + var verboseDebugString = ""; + if (verboseDebugInfo) { + verboseDebugString = "\r\nVerbose Debug Information:" + verboseDebugInfo(); + } + + throw new Error("Debug Failure. False expression: " + message + verboseDebugString); + } + }; + + Debug.fail = function (message) { + Debug.assert(false, message); + }; + Debug.currentAssertionLevel = 0 /* None */; + return Debug; + })(); + TypeScript.Debug = Debug; +})(TypeScript || (TypeScript = {})); +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var TypeScript; +(function (TypeScript) { + TypeScript.LocalizedDiagnosticMessages = null; + + var Location = (function () { + function Location(fileName, lineMap, start, length) { + this._fileName = fileName; + this._lineMap = lineMap; + this._start = start; + this._length = length; + } + Location.prototype.fileName = function () { + return this._fileName; + }; + + Location.prototype.lineMap = function () { + return this._lineMap; + }; + + Location.prototype.line = function () { + return this._lineMap ? this._lineMap.getLineNumberFromPosition(this.start()) : 0; + }; + + Location.prototype.character = function () { + return this._lineMap ? this._lineMap.getLineAndCharacterFromPosition(this.start()).character() : 0; + }; + + Location.prototype.start = function () { + return this._start; + }; + + Location.prototype.length = function () { + return this._length; + }; + + Location.equals = function (location1, location2) { + return location1._fileName === location2._fileName && location1._start === location2._start && location1._length === location2._length; + }; + return Location; + })(); + TypeScript.Location = Location; + + var Diagnostic = (function (_super) { + __extends(Diagnostic, _super); + function Diagnostic(fileName, lineMap, start, length, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + _super.call(this, fileName, lineMap, start, length); + this._diagnosticKey = diagnosticKey; + this._arguments = (_arguments && _arguments.length > 0) ? _arguments : null; + this._additionalLocations = (additionalLocations && additionalLocations.length > 0) ? additionalLocations : null; + } + Diagnostic.prototype.toJSON = function (key) { + var result = {}; + result.start = this.start(); + result.length = this.length(); + + result.diagnosticCode = this._diagnosticKey; + + var _arguments = this.arguments(); + if (_arguments && _arguments.length > 0) { + result.arguments = _arguments; + } + + return result; + }; + + Diagnostic.prototype.diagnosticKey = function () { + return this._diagnosticKey; + }; + + Diagnostic.prototype.arguments = function () { + return this._arguments; + }; + + Diagnostic.prototype.text = function () { + return TypeScript.getLocalizedText(this._diagnosticKey, this._arguments); + }; + + Diagnostic.prototype.message = function () { + return TypeScript.getDiagnosticMessage(this._diagnosticKey, this._arguments); + }; + + Diagnostic.prototype.additionalLocations = function () { + return this._additionalLocations || []; + }; + + Diagnostic.equals = function (diagnostic1, diagnostic2) { + return Location.equals(diagnostic1, diagnostic2) && diagnostic1._diagnosticKey === diagnostic2._diagnosticKey && TypeScript.ArrayUtilities.sequenceEquals(diagnostic1._arguments, diagnostic2._arguments, function (v1, v2) { + return v1 === v2; + }); + }; + + Diagnostic.prototype.info = function () { + return getDiagnosticInfoFromKey(this.diagnosticKey()); + }; + return Diagnostic; + })(Location); + TypeScript.Diagnostic = Diagnostic; + + function newLine() { + return TypeScript.Environment ? TypeScript.Environment.newLine : "\r\n"; + } + TypeScript.newLine = newLine; + + function getLargestIndex(diagnostic) { + var largest = -1; + var regex = /\{(\d+)\}/g; + + var match; + while (match = regex.exec(diagnostic)) { + var val = parseInt(match[1]); + if (!isNaN(val) && val > largest) { + largest = val; + } + } + + return largest; + } + + function getDiagnosticInfoFromKey(diagnosticKey) { + var result = TypeScript.diagnosticInformationMap[diagnosticKey]; + TypeScript.Debug.assert(result); + return result; + } + + function getLocalizedText(diagnosticKey, args) { + if (TypeScript.LocalizedDiagnosticMessages) { + } + + var diagnosticMessageText = TypeScript.LocalizedDiagnosticMessages ? TypeScript.LocalizedDiagnosticMessages[diagnosticKey] : diagnosticKey; + TypeScript.Debug.assert(diagnosticMessageText !== undefined && diagnosticMessageText !== null); + + var actualCount = args ? args.length : 0; + + var expectedCount = 1 + getLargestIndex(diagnosticKey); + + if (expectedCount !== actualCount) { + throw new Error(getLocalizedText(TypeScript.DiagnosticCode.Expected_0_arguments_to_message_got_1_instead, [expectedCount, actualCount])); + } + + var valueCount = 1 + getLargestIndex(diagnosticMessageText); + if (valueCount !== expectedCount) { + throw new Error(getLocalizedText(TypeScript.DiagnosticCode.Expected_the_message_0_to_have_1_arguments_but_it_had_2, [diagnosticMessageText, expectedCount, valueCount])); + } + + diagnosticMessageText = diagnosticMessageText.replace(/{(\d+)}/g, function (match, num) { + return typeof args[num] !== 'undefined' ? args[num] : match; + }); + + diagnosticMessageText = diagnosticMessageText.replace(/{(NL)}/g, function (match) { + return TypeScript.newLine(); + }); + + return diagnosticMessageText; + } + TypeScript.getLocalizedText = getLocalizedText; + + function getDiagnosticMessage(diagnosticKey, args) { + var diagnostic = getDiagnosticInfoFromKey(diagnosticKey); + var diagnosticMessageText = getLocalizedText(diagnosticKey, args); + + var message; + if (diagnostic.category === 1 /* Error */) { + message = getLocalizedText(TypeScript.DiagnosticCode.error_TS_0_1, [diagnostic.code, diagnosticMessageText]); + } else if (diagnostic.category === 0 /* Warning */) { + message = getLocalizedText(TypeScript.DiagnosticCode.warning_TS_0_1, [diagnostic.code, diagnosticMessageText]); + } else { + message = diagnosticMessageText; + } + + return message; + } + TypeScript.getDiagnosticMessage = getDiagnosticMessage; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Errors = (function () { + function Errors() { + } + Errors.argument = function (argument, message) { + return new Error("Invalid argument: " + argument + ". " + message); + }; + + Errors.argumentOutOfRange = function (argument) { + return new Error("Argument out of range: " + argument); + }; + + Errors.argumentNull = function (argument) { + return new Error("Argument null: " + argument); + }; + + Errors.abstract = function () { + return new Error("Operation not implemented properly by subclass."); + }; + + Errors.notYetImplemented = function () { + return new Error("Not yet implemented."); + }; + + Errors.invalidOperation = function (message) { + return new Error("Invalid operation: " + message); + }; + return Errors; + })(); + TypeScript.Errors = Errors; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Hash = (function () { + function Hash() { + } + Hash.computeFnv1aCharArrayHashCode = function (text, start, len) { + var hashCode = Hash.FNV_BASE; + var end = start + len; + + for (var i = start; i < end; i++) { + hashCode = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(hashCode ^ text[i], Hash.FNV_PRIME); + } + + return hashCode; + }; + + Hash.computeSimple31BitCharArrayHashCode = function (key, start, len) { + var hash = 0; + + for (var i = 0; i < len; i++) { + var ch = key[start + i]; + + hash = ((((hash << 5) - hash) | 0) + ch) | 0; + } + + return hash & 0x7FFFFFFF; + }; + + Hash.computeSimple31BitStringHashCode = function (key) { + var hash = 0; + + var start = 0; + var len = key.length; + + for (var i = 0; i < len; i++) { + var ch = key.charCodeAt(start + i); + + hash = ((((hash << 5) - hash) | 0) + ch) | 0; + } + + return hash & 0x7FFFFFFF; + }; + + Hash.computeMurmur2StringHashCode = function (key, seed) { + var m = 0x5bd1e995; + var r = 24; + + var numberOfCharsLeft = key.length; + var h = Math.abs(seed ^ numberOfCharsLeft); + + var index = 0; + while (numberOfCharsLeft >= 2) { + var c1 = key.charCodeAt(index); + var c2 = key.charCodeAt(index + 1); + + var k = Math.abs(c1 | (c2 << 16)); + + k = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(k, m); + k ^= k >> r; + k = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(k, m); + + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + h ^= k; + + index += 2; + numberOfCharsLeft -= 2; + } + + if (numberOfCharsLeft === 1) { + h ^= key.charCodeAt(index); + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + } + + h ^= h >> 13; + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + h ^= h >> 15; + + return h; + }; + + Hash.getPrime = function (min) { + for (var i = 0; i < Hash.primes.length; i++) { + var num = Hash.primes[i]; + if (num >= min) { + return num; + } + } + + throw TypeScript.Errors.notYetImplemented(); + }; + + Hash.expandPrime = function (oldSize) { + var num = oldSize << 1; + if (num > 2146435069 && 2146435069 > oldSize) { + return 2146435069; + } + return Hash.getPrime(num); + }; + + Hash.combine = function (value, currentHash) { + return (((currentHash << 5) + currentHash) + value) & 0x7FFFFFFF; + }; + Hash.FNV_BASE = 2166136261; + Hash.FNV_PRIME = 16777619; + + Hash.primes = [ + 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, + 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, + 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, + 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, + 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, + 4166287, 4999559, 5999471, 7199369]; + return Hash; + })(); + TypeScript.Hash = Hash; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Collections) { + Collections.DefaultHashTableCapacity = 1024; + + var HashTableEntry = (function () { + function HashTableEntry(Key, Value, HashCode, Next) { + this.Key = Key; + this.Value = Value; + this.HashCode = HashCode; + this.Next = Next; + } + return HashTableEntry; + })(); + + var HashTable = (function () { + function HashTable(capacity, hash) { + this.hash = hash; + this.count = 0; + var size = TypeScript.Hash.getPrime(capacity); + this.entries = TypeScript.ArrayUtilities.createArray(size, null); + } + HashTable.prototype.set = function (key, value) { + this.addOrSet(key, value, false); + }; + + HashTable.prototype.add = function (key, value) { + this.addOrSet(key, value, true); + }; + + HashTable.prototype.containsKey = function (key) { + var hashCode = this.computeHashCode(key); + var entry = this.findEntry(key, hashCode); + return entry !== null; + }; + + HashTable.prototype.get = function (key) { + var hashCode = this.computeHashCode(key); + var entry = this.findEntry(key, hashCode); + + return entry === null ? null : entry.Value; + }; + + HashTable.prototype.computeHashCode = function (key) { + var hashCode = this.hash === null ? key.hashCode : this.hash(key); + + hashCode = hashCode & 0x7FFFFFFF; + TypeScript.Debug.assert(hashCode >= 0); + + return hashCode; + }; + + HashTable.prototype.addOrSet = function (key, value, throwOnExistingEntry) { + var hashCode = this.computeHashCode(key); + + var entry = this.findEntry(key, hashCode); + if (entry !== null) { + if (throwOnExistingEntry) { + throw TypeScript.Errors.argument('key', "Key was already in table."); + } + + entry.Key = key; + entry.Value = value; + return; + } + + return this.addEntry(key, value, hashCode); + }; + + HashTable.prototype.findEntry = function (key, hashCode) { + for (var e = this.entries[hashCode % this.entries.length]; e !== null; e = e.Next) { + if (e.HashCode === hashCode && key === e.Key) { + return e; + } + } + + return null; + }; + + HashTable.prototype.addEntry = function (key, value, hashCode) { + var index = hashCode % this.entries.length; + + var e = new HashTableEntry(key, value, hashCode, this.entries[index]); + + this.entries[index] = e; + + if (this.count >= (this.entries.length / 2)) { + this.grow(); + } + + this.count++; + return e.Key; + }; + + HashTable.prototype.grow = function () { + var newSize = TypeScript.Hash.expandPrime(this.entries.length); + + var oldEntries = this.entries; + var newEntries = TypeScript.ArrayUtilities.createArray(newSize, null); + + this.entries = newEntries; + + for (var i = 0; i < oldEntries.length; i++) { + var e = oldEntries[i]; + + while (e !== null) { + var newIndex = e.HashCode % newSize; + var tmp = e.Next; + e.Next = newEntries[newIndex]; + newEntries[newIndex] = e; + e = tmp; + } + } + }; + return HashTable; + })(); + Collections.HashTable = HashTable; + + function createHashTable(capacity, hash) { + if (typeof capacity === "undefined") { capacity = Collections.DefaultHashTableCapacity; } + if (typeof hash === "undefined") { hash = null; } + return new HashTable(capacity, hash); + } + Collections.createHashTable = createHashTable; + + var currentHashCode = 1; + function identityHashCode(value) { + if (value.__hash === undefined) { + value.__hash = currentHashCode; + currentHashCode++; + } + + return value.__hash; + } + Collections.identityHashCode = identityHashCode; + })(TypeScript.Collections || (TypeScript.Collections = {})); + var Collections = TypeScript.Collections; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + TypeScript.nodeMakeDirectoryTime = 0; + TypeScript.nodeCreateBufferTime = 0; + TypeScript.nodeWriteFileSyncTime = 0; + + (function (ByteOrderMark) { + ByteOrderMark[ByteOrderMark["None"] = 0] = "None"; + ByteOrderMark[ByteOrderMark["Utf8"] = 1] = "Utf8"; + ByteOrderMark[ByteOrderMark["Utf16BigEndian"] = 2] = "Utf16BigEndian"; + ByteOrderMark[ByteOrderMark["Utf16LittleEndian"] = 3] = "Utf16LittleEndian"; + })(TypeScript.ByteOrderMark || (TypeScript.ByteOrderMark = {})); + var ByteOrderMark = TypeScript.ByteOrderMark; + + var FileInformation = (function () { + function FileInformation(contents, byteOrderMark) { + this.contents = contents; + this.byteOrderMark = byteOrderMark; + } + return FileInformation; + })(); + TypeScript.FileInformation = FileInformation; + + TypeScript.Environment = (function () { + function getWindowsScriptHostEnvironment() { + try { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + } catch (e) { + return null; + } + + 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 { + newLine: "\r\n", + currentDirectory: function () { + return WScript.CreateObject("WScript.Shell").CurrentDirectory; + }, + supportsCodePage: function () { + return WScript.ReadFile; + }, + readFile: function (path, codepage) { + try { + if (codepage !== null && this.supportsCodePage()) { + try { + var contents = WScript.ReadFile(path, codepage); + return new FileInformation(contents, 0 /* None */); + } catch (e) { + } + } + + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; + + streamObj.Charset = 'x-ansi'; + + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); + + streamObj.Position = 0; + + var byteOrderMark = 0 /* None */; + + if (bomChar.charCodeAt(0) === 0xFE && bomChar.charCodeAt(1) === 0xFF) { + streamObj.Charset = 'unicode'; + byteOrderMark = 2 /* Utf16BigEndian */; + } else if (bomChar.charCodeAt(0) === 0xFF && bomChar.charCodeAt(1) === 0xFE) { + streamObj.Charset = 'unicode'; + byteOrderMark = 3 /* Utf16LittleEndian */; + } else if (bomChar.charCodeAt(0) === 0xEF && bomChar.charCodeAt(1) === 0xBB) { + streamObj.Charset = 'utf-8'; + byteOrderMark = 1 /* Utf8 */; + } else { + streamObj.Charset = 'utf-8'; + } + + var contents = streamObj.ReadText(-1); + streamObj.Close(); + releaseStreamObject(streamObj); + return new FileInformation(contents, byteOrderMark); + } catch (err) { + var message; + if (err.number === -2147024809) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Unsupported_file_encoding, null); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Cannot_read_file_0_1, [path, err.message]); + } + + throw new Error(message); + } + }, + writeFile: function (path, contents, writeByteOrderMark) { + var textStream = getStreamObject(); + textStream.Charset = 'utf-8'; + textStream.Open(); + textStream.WriteText(contents, 0); + + if (!writeByteOrderMark) { + textStream.Position = 3; + } else { + textStream.Position = 0; + } + + var fileStream = getStreamObject(); + fileStream.Type = 1; + fileStream.Open(); + + textStream.CopyTo(fileStream); + + fileStream.Flush(); + fileStream.SaveToFile(path, 2); + fileStream.Close(); + + textStream.Flush(); + textStream.Close(); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + deleteFile: function (path) { + if (fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + listFiles: 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); + }, + arguments: args, + standardOut: WScript.StdOut + }; + } + ; + + function getNodeEnvironment() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + var _os = require('os'); + + return { + newLine: _os.EOL, + currentDirectory: function () { + return process.cwd(); + }, + supportsCodePage: function () { + return false; + }, + readFile: function (file, codepage) { + if (codepage !== null) { + throw new Error(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.codepage_option_not_supported_on_current_platform, null)); + } + + 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 new FileInformation(buffer.toString("ucs2", 2), 2 /* Utf16BigEndian */); + } + break; + case 0xFF: + if (buffer[1] === 0xFE) { + return new FileInformation(buffer.toString("ucs2", 2), 3 /* Utf16LittleEndian */); + } + break; + case 0xEF: + if (buffer[1] === 0xBB) { + return new FileInformation(buffer.toString("utf8", 3), 1 /* Utf8 */); + } + } + + return new FileInformation(buffer.toString("utf8", 0), 0 /* None */); + }, + writeFile: function (path, contents, writeByteOrderMark) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if (stats.isFile()) { + throw "\"" + path + "\" exists but isn't a directory."; + } else if (stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 509); + } + } + var start = new Date().getTime(); + mkdirRecursiveSync(_path.dirname(path)); + TypeScript.nodeMakeDirectoryTime += new Date().getTime() - start; + + if (writeByteOrderMark) { + contents = '\uFEFF' + contents; + } + + var start = new Date().getTime(); + + var chunkLength = 4 * 1024; + var fileDescriptor = _fs.openSync(path, "w"); + try { + for (var index = 0; index < contents.length; index += chunkLength) { + var bufferStart = new Date().getTime(); + var buffer = new Buffer(contents.substr(index, chunkLength), "utf8"); + TypeScript.nodeCreateBufferTime += new Date().getTime() - bufferStart; + + _fs.writeSync(fileDescriptor, buffer, 0, buffer.length, null); + } + } finally { + _fs.closeSync(fileDescriptor); + } + + TypeScript.nodeWriteFileSyncTime += new Date().getTime() - start; + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); + }, + listFiles: 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); + }, + arguments: process.argv.slice(2), + standardOut: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + } + }; + } + ; + + if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { + return getWindowsScriptHostEnvironment(); + } else if (typeof module !== 'undefined' && module.exports) { + return getNodeEnvironment(); + } else { + return null; + } + })(); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (IntegerUtilities) { + function integerDivide(numerator, denominator) { + return (numerator / denominator) >> 0; + } + IntegerUtilities.integerDivide = integerDivide; + + function integerMultiplyLow32Bits(n1, n2) { + var n1Low16 = n1 & 0x0000ffff; + var n1High16 = n1 >>> 16; + + var n2Low16 = n2 & 0x0000ffff; + var n2High16 = n2 >>> 16; + + var resultLow32 = (((n1 & 0xffff0000) * n2) >>> 0) + (((n1 & 0x0000ffff) * n2) >>> 0) >>> 0; + return resultLow32; + } + IntegerUtilities.integerMultiplyLow32Bits = integerMultiplyLow32Bits; + + function integerMultiplyHigh32Bits(n1, n2) { + var n1Low16 = n1 & 0x0000ffff; + var n1High16 = n1 >>> 16; + + var n2Low16 = n2 & 0x0000ffff; + var n2High16 = n2 >>> 16; + + var resultHigh32 = n1High16 * n2High16 + ((((n1Low16 * n2Low16) >>> 17) + n1Low16 * n2High16) >>> 15); + return resultHigh32; + } + IntegerUtilities.integerMultiplyHigh32Bits = integerMultiplyHigh32Bits; + + function isInteger(text) { + return /^[0-9]+$/.test(text); + } + IntegerUtilities.isInteger = isInteger; + + function isHexInteger(text) { + return /^0(x|X)[0-9a-fA-F]+$/.test(text); + } + IntegerUtilities.isHexInteger = isHexInteger; + })(TypeScript.IntegerUtilities || (TypeScript.IntegerUtilities = {})); + var IntegerUtilities = TypeScript.IntegerUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var LineMap = (function () { + function LineMap(_computeLineStarts, length) { + this._computeLineStarts = _computeLineStarts; + this.length = length; + this._lineStarts = null; + } + LineMap.prototype.toJSON = function (key) { + return { lineStarts: this.lineStarts(), length: this.length }; + }; + + LineMap.prototype.equals = function (other) { + return this.length === other.length && TypeScript.ArrayUtilities.sequenceEquals(this.lineStarts(), other.lineStarts(), function (v1, v2) { + return v1 === v2; + }); + }; + + LineMap.prototype.lineStarts = function () { + if (this._lineStarts === null) { + this._lineStarts = this._computeLineStarts(); + } + + return this._lineStarts; + }; + + LineMap.prototype.lineCount = function () { + return this.lineStarts().length; + }; + + LineMap.prototype.getPosition = function (line, character) { + return this.lineStarts()[line] + character; + }; + + LineMap.prototype.getLineNumberFromPosition = function (position) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + if (position === this.length) { + return this.lineCount() - 1; + } + + var lineNumber = TypeScript.ArrayUtilities.binarySearch(this.lineStarts(), position); + if (lineNumber < 0) { + lineNumber = (~lineNumber) - 1; + } + + return lineNumber; + }; + + LineMap.prototype.getLineStartPosition = function (lineNumber) { + return this.lineStarts()[lineNumber]; + }; + + LineMap.prototype.fillLineAndCharacterFromPosition = function (position, lineAndCharacter) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + lineAndCharacter.line = lineNumber; + lineAndCharacter.character = position - this.lineStarts()[lineNumber]; + }; + + LineMap.prototype.getLineAndCharacterFromPosition = function (position) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + + return new TypeScript.LineAndCharacter(lineNumber, position - this.lineStarts()[lineNumber]); + }; + LineMap.empty = new LineMap(function () { + return [0]; + }, 0); + return LineMap; + })(); + TypeScript.LineMap = LineMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var LineAndCharacter = (function () { + function LineAndCharacter(line, character) { + this._line = 0; + this._character = 0; + if (line < 0) { + throw TypeScript.Errors.argumentOutOfRange("line"); + } + + if (character < 0) { + throw TypeScript.Errors.argumentOutOfRange("character"); + } + + this._line = line; + this._character = character; + } + LineAndCharacter.prototype.line = function () { + return this._line; + }; + + LineAndCharacter.prototype.character = function () { + return this._character; + }; + return LineAndCharacter; + })(); + TypeScript.LineAndCharacter = LineAndCharacter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var MathPrototype = (function () { + function MathPrototype() { + } + MathPrototype.max = function (a, b) { + return a >= b ? a : b; + }; + + MathPrototype.min = function (a, b) { + return a <= b ? a : b; + }; + return MathPrototype; + })(); + TypeScript.MathPrototype = MathPrototype; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Collections) { + Collections.DefaultStringTableCapacity = 256; + + var StringTableEntry = (function () { + function StringTableEntry(Text, HashCode, Next) { + this.Text = Text; + this.HashCode = HashCode; + this.Next = Next; + } + return StringTableEntry; + })(); + + var StringTable = (function () { + function StringTable(capacity) { + this.count = 0; + var size = TypeScript.Hash.getPrime(capacity); + this.entries = TypeScript.ArrayUtilities.createArray(size, null); + } + StringTable.prototype.addCharArray = function (key, start, len) { + var hashCode = TypeScript.Hash.computeSimple31BitCharArrayHashCode(key, start, len) & 0x7FFFFFFF; + + var entry = this.findCharArrayEntry(key, start, len, hashCode); + if (entry !== null) { + return entry.Text; + } + + var slice = key.slice(start, start + len); + return this.addEntry(TypeScript.StringUtilities.fromCharCodeArray(slice), hashCode); + }; + + StringTable.prototype.findCharArrayEntry = function (key, start, len, hashCode) { + for (var e = this.entries[hashCode % this.entries.length]; e !== null; e = e.Next) { + if (e.HashCode === hashCode && StringTable.textCharArrayEquals(e.Text, key, start, len)) { + return e; + } + } + + return null; + }; + + StringTable.prototype.addEntry = function (text, hashCode) { + var index = hashCode % this.entries.length; + + var e = new StringTableEntry(text, hashCode, this.entries[index]); + + this.entries[index] = e; + + if (this.count === this.entries.length) { + this.grow(); + } + + this.count++; + return e.Text; + }; + + StringTable.prototype.grow = function () { + var newSize = TypeScript.Hash.expandPrime(this.entries.length); + + var oldEntries = this.entries; + var newEntries = TypeScript.ArrayUtilities.createArray(newSize, null); + + this.entries = newEntries; + + for (var i = 0; i < oldEntries.length; i++) { + var e = oldEntries[i]; + while (e !== null) { + var newIndex = e.HashCode % newSize; + var tmp = e.Next; + e.Next = newEntries[newIndex]; + newEntries[newIndex] = e; + e = tmp; + } + } + }; + + StringTable.textCharArrayEquals = function (text, array, start, length) { + if (text.length !== length) { + return false; + } + + var s = start; + for (var i = 0; i < length; i++) { + if (text.charCodeAt(i) !== array[s]) { + return false; + } + + s++; + } + + return true; + }; + return StringTable; + })(); + Collections.StringTable = StringTable; + + Collections.DefaultStringTable = new StringTable(Collections.DefaultStringTableCapacity); + })(TypeScript.Collections || (TypeScript.Collections = {})); + var Collections = TypeScript.Collections; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var StringUtilities = (function () { + function StringUtilities() { + } + StringUtilities.isString = function (value) { + return Object.prototype.toString.apply(value, []) === '[object String]'; + }; + + StringUtilities.fromCharCodeArray = function (array) { + return String.fromCharCode.apply(null, array); + }; + + StringUtilities.endsWith = function (string, value) { + return string.substring(string.length - value.length, string.length) === value; + }; + + StringUtilities.startsWith = function (string, value) { + return string.substr(0, value.length) === value; + }; + + StringUtilities.copyTo = function (source, sourceIndex, destination, destinationIndex, count) { + for (var i = 0; i < count; i++) { + destination[destinationIndex + i] = source.charCodeAt(sourceIndex + i); + } + }; + + StringUtilities.repeat = function (value, count) { + return Array(count + 1).join(value); + }; + + StringUtilities.stringEquals = function (val1, val2) { + return val1 === val2; + }; + return StringUtilities; + })(); + TypeScript.StringUtilities = StringUtilities; +})(TypeScript || (TypeScript = {})); +var global = Function("return this").call(null); + +var TypeScript; +(function (TypeScript) { + var Clock; + (function (Clock) { + Clock.now; + Clock.resolution; + + if (typeof WScript !== "undefined" && typeof global['WScript'].InitializeProjection !== "undefined") { + global['WScript'].InitializeProjection(); + + Clock.now = function () { + return TestUtilities.QueryPerformanceCounter(); + }; + + Clock.resolution = TestUtilities.QueryPerformanceFrequency(); + } else { + Clock.now = function () { + return Date.now(); + }; + + Clock.resolution = 1000; + } + })(Clock || (Clock = {})); + + var Timer = (function () { + function Timer() { + this.time = 0; + } + Timer.prototype.start = function () { + this.time = 0; + this.startTime = Clock.now(); + }; + + Timer.prototype.end = function () { + this.time = (Clock.now() - this.startTime); + }; + return Timer; + })(); + TypeScript.Timer = Timer; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + DiagnosticCategory[DiagnosticCategory["NoPrefix"] = 3] = "NoPrefix"; + })(TypeScript.DiagnosticCategory || (TypeScript.DiagnosticCategory = {})); + var DiagnosticCategory = TypeScript.DiagnosticCategory; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.diagnosticInformationMap = { + "error TS{0}: {1}": { + "code": 0, + "category": 3 /* NoPrefix */ + }, + "warning TS{0}: {1}": { + "code": 1, + "category": 3 /* NoPrefix */ + }, + "Unrecognized escape sequence.": { + "code": 1000, + "category": 1 /* Error */ + }, + "Unexpected character {0}.": { + "code": 1001, + "category": 1 /* Error */ + }, + "Missing close quote character.": { + "code": 1002, + "category": 1 /* Error */ + }, + "Identifier expected.": { + "code": 1003, + "category": 1 /* Error */ + }, + "'{0}' keyword expected.": { + "code": 1004, + "category": 1 /* Error */ + }, + "'{0}' expected.": { + "code": 1005, + "category": 1 /* Error */ + }, + "Identifier expected; '{0}' is a keyword.": { + "code": 1006, + "category": 1 /* Error */ + }, + "Automatic semicolon insertion not allowed.": { + "code": 1007, + "category": 1 /* Error */ + }, + "Unexpected token; '{0}' expected.": { + "code": 1008, + "category": 1 /* Error */ + }, + "Trailing separator not allowed.": { + "code": 1009, + "category": 1 /* Error */ + }, + "'*/' expected.": { + "code": 1010, + "category": 1 /* Error */ + }, + "'public' or 'private' modifier must precede 'static'.": { + "code": 1011, + "category": 1 /* Error */ + }, + "Unexpected token.": { + "code": 1012, + "category": 1 /* Error */ + }, + "Catch clause parameter cannot have a type annotation.": { + "code": 1013, + "category": 1 /* Error */ + }, + "Rest parameter must be last in list.": { + "code": 1014, + "category": 1 /* Error */ + }, + "Parameter cannot have question mark and initializer.": { + "code": 1015, + "category": 1 /* Error */ + }, + "Required parameter cannot follow optional parameter.": { + "code": 1016, + "category": 1 /* Error */ + }, + "Index signatures cannot have rest parameters.": { + "code": 1017, + "category": 1 /* Error */ + }, + "Index signature parameter cannot have accessibility modifiers.": { + "code": 1018, + "category": 1 /* Error */ + }, + "Index signature parameter cannot have a question mark.": { + "code": 1019, + "category": 1 /* Error */ + }, + "Index signature parameter cannot have an initializer.": { + "code": 1020, + "category": 1 /* Error */ + }, + "Index signature must have a type annotation.": { + "code": 1021, + "category": 1 /* Error */ + }, + "Index signature parameter must have a type annotation.": { + "code": 1022, + "category": 1 /* Error */ + }, + "Index signature parameter type must be 'string' or 'number'.": { + "code": 1023, + "category": 1 /* Error */ + }, + "'extends' clause already seen.": { + "code": 1024, + "category": 1 /* Error */ + }, + "'extends' clause must precede 'implements' clause.": { + "code": 1025, + "category": 1 /* Error */ + }, + "Classes can only extend a single class.": { + "code": 1026, + "category": 1 /* Error */ + }, + "'implements' clause already seen.": { + "code": 1027, + "category": 1 /* Error */ + }, + "Accessibility modifier already seen.": { + "code": 1028, + "category": 1 /* Error */ + }, + "'{0}' modifier must precede '{1}' modifier.": { + "code": 1029, + "category": 1 /* Error */ + }, + "'{0}' modifier already seen.": { + "code": 1030, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a class element.": { + "code": 1031, + "category": 1 /* Error */ + }, + "Interface declaration cannot have 'implements' clause.": { + "code": 1032, + "category": 1 /* Error */ + }, + "'super' invocation cannot have type arguments.": { + "code": 1034, + "category": 1 /* Error */ + }, + "Only ambient modules can use quoted names.": { + "code": 1035, + "category": 1 /* Error */ + }, + "Statements are not allowed in ambient contexts.": { + "code": 1036, + "category": 1 /* Error */ + }, + "Implementations are not allowed in ambient contexts.": { + "code": 1037, + "category": 1 /* Error */ + }, + "'declare' modifier not allowed for code already in an ambient context.": { + "code": 1038, + "category": 1 /* Error */ + }, + "Initializers are not allowed in ambient contexts.": { + "code": 1039, + "category": 1 /* Error */ + }, + "Parameter property declarations can only be used in a non-ambient constructor declaration.": { + "code": 1040, + "category": 1 /* Error */ + }, + "Function implementation expected.": { + "code": 1041, + "category": 1 /* Error */ + }, + "Constructor implementation expected.": { + "code": 1042, + "category": 1 /* Error */ + }, + "Function overload name must be '{0}'.": { + "code": 1043, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a module element.": { + "code": 1044, + "category": 1 /* Error */ + }, + "'declare' modifier cannot appear on an interface declaration.": { + "code": 1045, + "category": 1 /* Error */ + }, + "'declare' modifier required for top level element.": { + "code": 1046, + "category": 1 /* Error */ + }, + "Rest parameter cannot be optional.": { + "code": 1047, + "category": 1 /* Error */ + }, + "Rest parameter cannot have an initializer.": { + "code": 1048, + "category": 1 /* Error */ + }, + "'set' accessor must have one and only one parameter.": { + "code": 1049, + "category": 1 /* Error */ + }, + "'set' accessor parameter cannot be optional.": { + "code": 1051, + "category": 1 /* Error */ + }, + "'set' accessor parameter cannot have an initializer.": { + "code": 1052, + "category": 1 /* Error */ + }, + "'set' accessor cannot have rest parameter.": { + "code": 1053, + "category": 1 /* Error */ + }, + "'get' accessor cannot have parameters.": { + "code": 1054, + "category": 1 /* Error */ + }, + "Modifiers cannot appear here.": { + "code": 1055, + "category": 1 /* Error */ + }, + "Accessors are only available when targeting ECMAScript 5 and higher.": { + "code": 1056, + "category": 1 /* Error */ + }, + "Class name cannot be '{0}'.": { + "code": 1057, + "category": 1 /* Error */ + }, + "Interface name cannot be '{0}'.": { + "code": 1058, + "category": 1 /* Error */ + }, + "Enum name cannot be '{0}'.": { + "code": 1059, + "category": 1 /* Error */ + }, + "Module name cannot be '{0}'.": { + "code": 1060, + "category": 1 /* Error */ + }, + "Enum member must have initializer.": { + "code": 1061, + "category": 1 /* Error */ + }, + "Export assignment cannot be used in internal modules.": { + "code": 1063, + "category": 1 /* Error */ + }, + "Export assignment not allowed in module with exported element.": { + "code": 1064, + "category": 1 /* Error */ + }, + "Module cannot have multiple export assignments.": { + "code": 1065, + "category": 1 /* Error */ + }, + "Ambient enum elements can only have integer literal initializers.": { + "code": 1066, + "category": 1 /* Error */ + }, + "module, class, interface, enum, import or statement": { + "code": 1067, + "category": 3 /* NoPrefix */ + }, + "constructor, function, accessor or variable": { + "code": 1068, + "category": 3 /* NoPrefix */ + }, + "statement": { + "code": 1069, + "category": 3 /* NoPrefix */ + }, + "case or default clause": { + "code": 1070, + "category": 3 /* NoPrefix */ + }, + "identifier": { + "code": 1071, + "category": 3 /* NoPrefix */ + }, + "call, construct, index, property or function signature": { + "code": 1072, + "category": 3 /* NoPrefix */ + }, + "expression": { + "code": 1073, + "category": 3 /* NoPrefix */ + }, + "type name": { + "code": 1074, + "category": 3 /* NoPrefix */ + }, + "property or accessor": { + "code": 1075, + "category": 3 /* NoPrefix */ + }, + "parameter": { + "code": 1076, + "category": 3 /* NoPrefix */ + }, + "type": { + "code": 1077, + "category": 3 /* NoPrefix */ + }, + "type parameter": { + "code": 1078, + "category": 3 /* NoPrefix */ + }, + "'declare' modifier not allowed on import declaration.": { + "code": 1079, + "category": 1 /* Error */ + }, + "Function overload must be static.": { + "code": 1080, + "category": 1 /* Error */ + }, + "Function overload must not be static.": { + "code": 1081, + "category": 1 /* Error */ + }, + "Parameter property declarations cannot be used in a constructor overload.": { + "code": 1083, + "category": 1 /* Error */ + }, + "Invalid 'reference' directive syntax.": { + "code": 1084, + "category": 1 /* Error */ + }, + "Octal literals are not available when targeting ECMAScript 5 and higher.": { + "code": 1085, + "category": 1 /* Error */ + }, + "Accessors are not allowed in ambient contexts.": { + "code": 1086, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a constructor declaration.": { + "code": 1089, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a parameter.": { + "code": 1090, + "category": 1 /* Error */ + }, + "Only a single variable declaration is allowed in a 'for...in' statement.": { + "code": 1091, + "category": 1 /* Error */ + }, + "Type parameters cannot appear on a constructor declaration.": { + "code": 1091, + "category": 1 /* Error */ + }, + "Type annotation cannot appear on a constructor declaration.": { + "code": 1092, + "category": 1 /* Error */ + }, + "Duplicate identifier '{0}'.": { + "code": 2000, + "category": 1 /* Error */ + }, + "The name '{0}' does not exist in the current scope.": { + "code": 2001, + "category": 1 /* Error */ + }, + "The name '{0}' does not refer to a value.": { + "code": 2002, + "category": 1 /* Error */ + }, + "'super' can only be used inside a class instance method.": { + "code": 2003, + "category": 1 /* Error */ + }, + "The left-hand side of an assignment expression must be a variable, property or indexer.": { + "code": 2004, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not callable. Did you mean to include 'new'?": { + "code": 2161, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not callable.": { + "code": 2006, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not newable.": { + "code": 2007, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not indexable by type '{1}'.": { + "code": 2008, + "category": 1 /* Error */ + }, + "Operator '{0}' cannot be applied to types '{1}' and '{2}'.": { + "code": 2009, + "category": 1 /* Error */ + }, + "Operator '{0}' cannot be applied to types '{1}' and '{2}': {3}": { + "code": 2010, + "category": 1 /* Error */ + }, + "Cannot convert '{0}' to '{1}'.": { + "code": 2011, + "category": 1 /* Error */ + }, + "Cannot convert '{0}' to '{1}':{NL}{2}": { + "code": 2012, + "category": 1 /* Error */ + }, + "Expected var, class, interface, or module.": { + "code": 2013, + "category": 1 /* Error */ + }, + "Operator '{0}' cannot be applied to type '{1}'.": { + "code": 2014, + "category": 1 /* Error */ + }, + "Getter '{0}' already declared.": { + "code": 2015, + "category": 1 /* Error */ + }, + "Setter '{0}' already declared.": { + "code": 2016, + "category": 1 /* Error */ + }, + "Exported class '{0}' extends private class '{1}'.": { + "code": 2018, + "category": 1 /* Error */ + }, + "Exported class '{0}' implements private interface '{1}'.": { + "code": 2019, + "category": 1 /* Error */ + }, + "Exported interface '{0}' extends private interface '{1}'.": { + "code": 2020, + "category": 1 /* Error */ + }, + "Exported class '{0}' extends class from inaccessible module {1}.": { + "code": 2021, + "category": 1 /* Error */ + }, + "Exported class '{0}' implements interface from inaccessible module {1}.": { + "code": 2022, + "category": 1 /* Error */ + }, + "Exported interface '{0}' extends interface from inaccessible module {1}.": { + "code": 2023, + "category": 1 /* Error */ + }, + "Public static property '{0}' of exported class has or is using private type '{1}'.": { + "code": 2024, + "category": 1 /* Error */ + }, + "Public property '{0}' of exported class has or is using private type '{1}'.": { + "code": 2025, + "category": 1 /* Error */ + }, + "Property '{0}' of exported interface has or is using private type '{1}'.": { + "code": 2026, + "category": 1 /* Error */ + }, + "Exported variable '{0}' has or is using private type '{1}'.": { + "code": 2027, + "category": 1 /* Error */ + }, + "Public static property '{0}' of exported class is using inaccessible module {1}.": { + "code": 2028, + "category": 1 /* Error */ + }, + "Public property '{0}' of exported class is using inaccessible module {1}.": { + "code": 2029, + "category": 1 /* Error */ + }, + "Property '{0}' of exported interface is using inaccessible module {1}.": { + "code": 2030, + "category": 1 /* Error */ + }, + "Exported variable '{0}' is using inaccessible module {1}.": { + "code": 2031, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor from exported class has or is using private type '{1}'.": { + "code": 2032, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static property setter from exported class has or is using private type '{1}'.": { + "code": 2033, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public property setter from exported class has or is using private type '{1}'.": { + "code": 2034, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.": { + "code": 2035, + "category": 1 /* Error */ + }, + "Parameter '{0}' of call signature from exported interface has or is using private type '{1}'.": { + "code": 2036, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static method from exported class has or is using private type '{1}'.": { + "code": 2037, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public method from exported class has or is using private type '{1}'.": { + "code": 2038, + "category": 1 /* Error */ + }, + "Parameter '{0}' of method from exported interface has or is using private type '{1}'.": { + "code": 2039, + "category": 1 /* Error */ + }, + "Parameter '{0}' of exported function has or is using private type '{1}'.": { + "code": 2040, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor from exported class is using inaccessible module {1}.": { + "code": 2041, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static property setter from exported class is using inaccessible module {1}.": { + "code": 2042, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public property setter from exported class is using inaccessible module {1}.": { + "code": 2043, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.": { + "code": 2044, + "category": 1 /* Error */ + }, + "Parameter '{0}' of call signature from exported interface is using inaccessible module {1}": { + "code": 2045, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static method from exported class is using inaccessible module {1}.": { + "code": 2046, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public method from exported class is using inaccessible module {1}.": { + "code": 2047, + "category": 1 /* Error */ + }, + "Parameter '{0}' of method from exported interface is using inaccessible module {1}.": { + "code": 2048, + "category": 1 /* Error */ + }, + "Parameter '{0}' of exported function is using inaccessible module {1}.": { + "code": 2049, + "category": 1 /* Error */ + }, + "Return type of public static property getter from exported class has or is using private type '{0}'.": { + "code": 2050, + "category": 1 /* Error */ + }, + "Return type of public property getter from exported class has or is using private type '{0}'.": { + "code": 2051, + "category": 1 /* Error */ + }, + "Return type of constructor signature from exported interface has or is using private type '{0}'.": { + "code": 2052, + "category": 1 /* Error */ + }, + "Return type of call signature from exported interface has or is using private type '{0}'.": { + "code": 2053, + "category": 1 /* Error */ + }, + "Return type of index signature from exported interface has or is using private type '{0}'.": { + "code": 2054, + "category": 1 /* Error */ + }, + "Return type of public static method from exported class has or is using private type '{0}'.": { + "code": 2055, + "category": 1 /* Error */ + }, + "Return type of public method from exported class has or is using private type '{0}'.": { + "code": 2056, + "category": 1 /* Error */ + }, + "Return type of method from exported interface has or is using private type '{0}'.": { + "code": 2057, + "category": 1 /* Error */ + }, + "Return type of exported function has or is using private type '{0}'.": { + "code": 2058, + "category": 1 /* Error */ + }, + "Return type of public static property getter from exported class is using inaccessible module {0}.": { + "code": 2059, + "category": 1 /* Error */ + }, + "Return type of public property getter from exported class is using inaccessible module {0}.": { + "code": 2060, + "category": 1 /* Error */ + }, + "Return type of constructor signature from exported interface is using inaccessible module {0}.": { + "code": 2061, + "category": 1 /* Error */ + }, + "Return type of call signature from exported interface is using inaccessible module {0}.": { + "code": 2062, + "category": 1 /* Error */ + }, + "Return type of index signature from exported interface is using inaccessible module {0}.": { + "code": 2063, + "category": 1 /* Error */ + }, + "Return type of public static method from exported class is using inaccessible module {0}.": { + "code": 2064, + "category": 1 /* Error */ + }, + "Return type of public method from exported class is using inaccessible module {0}.": { + "code": 2065, + "category": 1 /* Error */ + }, + "Return type of method from exported interface is using inaccessible module {0}.": { + "code": 2066, + "category": 1 /* Error */ + }, + "Return type of exported function is using inaccessible module {0}.": { + "code": 2067, + "category": 1 /* Error */ + }, + "'new T[]' cannot be used to create an array. Use 'new Array()' instead.": { + "code": 2068, + "category": 1 /* Error */ + }, + "A parameter list must follow a generic type argument list. '(' expected.": { + "code": 2069, + "category": 1 /* Error */ + }, + "Multiple constructor implementations are not allowed.": { + "code": 2070, + "category": 1 /* Error */ + }, + "Unable to resolve external module '{0}'.": { + "code": 2071, + "category": 1 /* Error */ + }, + "Module cannot be aliased to a non-module type.": { + "code": 2072, + "category": 1 /* Error */ + }, + "A class may only extend another class.": { + "code": 2073, + "category": 1 /* Error */ + }, + "A class may only implement another class or interface.": { + "code": 2074, + "category": 1 /* Error */ + }, + "An interface may only extend another class or interface.": { + "code": 2075, + "category": 1 /* Error */ + }, + "Unable to resolve type.": { + "code": 2077, + "category": 1 /* Error */ + }, + "Unable to resolve type of '{0}'.": { + "code": 2078, + "category": 1 /* Error */ + }, + "Unable to resolve type parameter constraint.": { + "code": 2079, + "category": 1 /* Error */ + }, + "Type parameter constraint cannot be a primitive type.": { + "code": 2080, + "category": 1 /* Error */ + }, + "Supplied parameters do not match any signature of call target.": { + "code": 2081, + "category": 1 /* Error */ + }, + "Supplied parameters do not match any signature of call target:{NL}{0}": { + "code": 2082, + "category": 1 /* Error */ + }, + "Invalid 'new' expression.": { + "code": 2083, + "category": 1 /* Error */ + }, + "Call signatures used in a 'new' expression must have a 'void' return type.": { + "code": 2084, + "category": 1 /* Error */ + }, + "Could not select overload for 'new' expression.": { + "code": 2085, + "category": 1 /* Error */ + }, + "Type '{0}' does not satisfy the constraint '{1}' for type parameter '{2}'.": { + "code": 2086, + "category": 1 /* Error */ + }, + "Could not select overload for 'call' expression.": { + "code": 2087, + "category": 1 /* Error */ + }, + "Cannot invoke an expression whose type lacks a call signature.": { + "code": 2088, + "category": 1 /* Error */ + }, + "Calls to 'super' are only valid inside a class.": { + "code": 2089, + "category": 1 /* Error */ + }, + "Generic type '{0}' requires {1} type argument(s).": { + "code": 2090, + "category": 1 /* Error */ + }, + "Type of array literal cannot be determined. Best common type could not be found for array elements.": { + "code": 2092, + "category": 1 /* Error */ + }, + "Could not find enclosing symbol for dotted name '{0}'.": { + "code": 2093, + "category": 1 /* Error */ + }, + "The property '{0}' does not exist on value of type '{1}'.": { + "code": 2094, + "category": 1 /* Error */ + }, + "Could not find symbol '{0}'.": { + "code": 2095, + "category": 1 /* Error */ + }, + "'get' and 'set' accessor must have the same type.": { + "code": 2096, + "category": 1 /* Error */ + }, + "'this' cannot be referenced in current location.": { + "code": 2097, + "category": 1 /* Error */ + }, + "Static members cannot reference class type parameters.": { + "code": 2099, + "category": 1 /* Error */ + }, + "Class '{0}' is recursively referenced as a base type of itself.": { + "code": 2100, + "category": 1 /* Error */ + }, + "Interface '{0}' is recursively referenced as a base type of itself.": { + "code": 2101, + "category": 1 /* Error */ + }, + "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class.": { + "code": 2102, + "category": 1 /* Error */ + }, + "'super' cannot be referenced in non-derived classes.": { + "code": 2103, + "category": 1 /* Error */ + }, + "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.": { + "code": 2104, + "category": 1 /* Error */ + }, + "Constructors for derived classes must contain a 'super' call.": { + "code": 2105, + "category": 1 /* Error */ + }, + "Super calls are not permitted outside constructors or in nested functions inside constructors.": { + "code": 2106, + "category": 1 /* Error */ + }, + "'{0}.{1}' is inaccessible.": { + "code": 2107, + "category": 1 /* Error */ + }, + "'this' cannot be referenced within module bodies.": { + "code": 2108, + "category": 1 /* Error */ + }, + "Invalid '+' expression - types not known to support the addition operator.": { + "code": 2111, + "category": 1 /* Error */ + }, + "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.": { + "code": 2112, + "category": 1 /* Error */ + }, + "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.": { + "code": 2113, + "category": 1 /* Error */ + }, + "The type of a unary arithmetic operation operand must be of type 'any', 'number' or an enum type.": { + "code": 2114, + "category": 1 /* Error */ + }, + "Variable declarations of a 'for' statement cannot use a type annotation.": { + "code": 2115, + "category": 1 /* Error */ + }, + "Variable declarations of a 'for' statement must be of types 'string' or 'any'.": { + "code": 2116, + "category": 1 /* Error */ + }, + "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter.": { + "code": 2117, + "category": 1 /* Error */ + }, + "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'.": { + "code": 2118, + "category": 1 /* Error */ + }, + "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.": { + "code": 2119, + "category": 1 /* Error */ + }, + "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.": { + "code": 2120, + "category": 1 /* Error */ + }, + "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.": { + "code": 2121, + "category": 1 /* Error */ + }, + "Setters cannot return a value.": { + "code": 2122, + "category": 1 /* Error */ + }, + "Tried to query type of uninitialized module '{0}'.": { + "code": 2123, + "category": 1 /* Error */ + }, + "Tried to set variable type to uninitialized module type '{0}'.": { + "code": 2124, + "category": 1 /* Error */ + }, + "Type '{0}' does not have type parameters.": { + "code": 2125, + "category": 1 /* Error */ + }, + "Getters must return a value.": { + "code": 2126, + "category": 1 /* Error */ + }, + "Getter and setter accessors do not agree in visibility.": { + "code": 2127, + "category": 1 /* Error */ + }, + "Invalid left-hand side of assignment expression.": { + "code": 2130, + "category": 1 /* Error */ + }, + "Function declared a non-void return type, but has no return expression.": { + "code": 2131, + "category": 1 /* Error */ + }, + "Cannot resolve return type reference.": { + "code": 2132, + "category": 1 /* Error */ + }, + "Constructors cannot have a return type of 'void'.": { + "code": 2133, + "category": 1 /* Error */ + }, + "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'.": { + "code": 2134, + "category": 1 /* Error */ + }, + "All symbols within a with block will be resolved to 'any'.": { + "code": 2135, + "category": 1 /* Error */ + }, + "Import declarations in an internal module cannot reference an external module.": { + "code": 2136, + "category": 1 /* Error */ + }, + "Class {0} declares interface {1} but does not implement it:{NL}{2}": { + "code": 2137, + "category": 1 /* Error */ + }, + "Class {0} declares class {1} as an interface but does not implement it:{NL}{2}": { + "code": 2138, + "category": 1 /* Error */ + }, + "The operand of an increment or decrement operator must be a variable, property or indexer.": { + "code": 2139, + "category": 1 /* Error */ + }, + "'this' cannot be referenced in static initializers in a class body.": { + "code": 2140, + "category": 1 /* Error */ + }, + "Class '{0}' cannot extend class '{1}':{NL}{2}": { + "code": 2141, + "category": 1 /* Error */ + }, + "Interface '{0}' cannot extend class '{1}':{NL}{2}": { + "code": 2142, + "category": 1 /* Error */ + }, + "Interface '{0}' cannot extend interface '{1}':{NL}{2}": { + "code": 2143, + "category": 1 /* Error */ + }, + "Duplicate overload signature for '{0}'.": { + "code": 2144, + "category": 1 /* Error */ + }, + "Duplicate constructor overload signature.": { + "code": 2145, + "category": 1 /* Error */ + }, + "Duplicate overload call signature.": { + "code": 2146, + "category": 1 /* Error */ + }, + "Duplicate overload construct signature.": { + "code": 2147, + "category": 1 /* Error */ + }, + "Overload signature is not compatible with function definition.": { + "code": 2148, + "category": 1 /* Error */ + }, + "Overload signature is not compatible with function definition:{NL}{0}": { + "code": 2149, + "category": 1 /* Error */ + }, + "Overload signatures must all be public or private.": { + "code": 2150, + "category": 1 /* Error */ + }, + "Overload signatures must all be exported or not exported.": { + "code": 2151, + "category": 1 /* Error */ + }, + "Overload signatures must all be ambient or non-ambient.": { + "code": 2152, + "category": 1 /* Error */ + }, + "Overload signatures must all be optional or required.": { + "code": 2153, + "category": 1 /* Error */ + }, + "Specialized overload signature is not assignable to any non-specialized signature.": { + "code": 2154, + "category": 1 /* Error */ + }, + "'this' cannot be referenced in constructor arguments.": { + "code": 2155, + "category": 1 /* Error */ + }, + "Instance member cannot be accessed off a class.": { + "code": 2157, + "category": 1 /* Error */ + }, + "Untyped function calls may not accept type arguments.": { + "code": 2158, + "category": 1 /* Error */ + }, + "Non-generic functions may not accept type arguments.": { + "code": 2159, + "category": 1 /* Error */ + }, + "A generic type may not reference itself with a wrapped form of its own type parameters.": { + "code": 2160, + "category": 1 /* Error */ + }, + "Rest parameters must be array types.": { + "code": 2162, + "category": 1 /* Error */ + }, + "Overload signature implementation cannot use specialized type.": { + "code": 2163, + "category": 1 /* Error */ + }, + "Export assignments may only be used at the top-level of external modules.": { + "code": 2164, + "category": 1 /* Error */ + }, + "Export assignments may only be made with variables, functions, classes, interfaces, enums and internal modules.": { + "code": 2165, + "category": 1 /* Error */ + }, + "Only public methods of the base class are accessible via the 'super' keyword.": { + "code": 2166, + "category": 1 /* Error */ + }, + "Numeric indexer type '{0}' must be assignable to string indexer type '{1}'.": { + "code": 2167, + "category": 1 /* Error */ + }, + "Numeric indexer type '{0}' must be assignable to string indexer type '{1}':{NL}{2}": { + "code": 2168, + "category": 1 /* Error */ + }, + "All numerically named properties must be assignable to numeric indexer type '{0}'.": { + "code": 2169, + "category": 1 /* Error */ + }, + "All numerically named properties must be assignable to numeric indexer type '{0}':{NL}{1}": { + "code": 2170, + "category": 1 /* Error */ + }, + "All named properties must be assignable to string indexer type '{0}'.": { + "code": 2171, + "category": 1 /* Error */ + }, + "All named properties must be assignable to string indexer type '{0}':{NL}{1}": { + "code": 2172, + "category": 1 /* Error */ + }, + "Generic type references must include all type arguments.": { + "code": 2173, + "category": 1 /* Error */ + }, + "Default arguments are only allowed in implementation.": { + "code": 2174, + "category": 1 /* Error */ + }, + "Overloads cannot differ only by return type.": { + "code": 2175, + "category": 1 /* Error */ + }, + "Function expression declared a non-void return type, but has no return expression.": { + "code": 2176, + "category": 1 /* Error */ + }, + "Import declaration referencing identifier from internal module can only be made with variables, functions, classes, interfaces, enums and internal modules.": { + "code": 2177, + "category": 1 /* Error */ + }, + "Could not find symbol '{0}' in module '{1}'.": { + "code": 2178, + "category": 1 /* Error */ + }, + "Unable to resolve module reference '{0}'.": { + "code": 2179, + "category": 1 /* Error */ + }, + "Could not find module '{0}' in module '{1}'.": { + "code": 2180, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned value with type that has or is using private type '{1}'.": { + "code": 2181, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned value with type that is using inaccessible module '{1}'.": { + "code": 2182, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned type that has or is using private type '{1}'.": { + "code": 2183, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned type that is using inaccessible module '{1}'.": { + "code": 2184, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned container that is or is using inaccessible module '{1}'.": { + "code": 2185, + "category": 1 /* Error */ + }, + "Type name '{0}' in extends clause does not reference constructor function for '{1}'.": { + "code": 2186, + "category": 1 /* Error */ + }, + "Internal module reference '{0}' in import declaration does not reference module instance for '{1}'.": { + "code": 2187, + "category": 1 /* Error */ + }, + "Module '{0}' cannot merge with previous declaration of '{1}' in a different file '{2}'.": { + "code": 2188, + "category": 1 /* Error */ + }, + "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':{NL}{3}": { + "code": 2189, + "category": 1 /* Error */ + }, + "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it.": { + "code": 2190, + "category": 1 /* Error */ + }, + "Ambient external module declaration cannot be reopened.": { + "code": 2191, + "category": 1 /* Error */ + }, + "All declarations of merged declaration '{0}' must be exported or not exported.": { + "code": 2192, + "category": 1 /* Error */ + }, + "'super' cannot be referenced in constructor arguments.": { + "code": 2193, + "category": 1 /* Error */ + }, + "Return type of constructor signature must be assignable to the instance type of the class.": { + "code": 2194, + "category": 1 /* Error */ + }, + "Ambient external module declaration must be defined in global context.": { + "code": 2195, + "category": 1 /* Error */ + }, + "Ambient external module declaration cannot specify relative module name.": { + "code": 2196, + "category": 1 /* Error */ + }, + "Import declaration in an ambient external module declaration cannot reference external module through relative external module name.": { + "code": 2197, + "category": 1 /* Error */ + }, + "Could not find the best common type of types of all return statement expressions.": { + "code": 2198, + "category": 1 /* Error */ + }, + "Import declaration cannot refer to external module reference when --noResolve option is set.": { + "code": 2199, + "category": 1 /* Error */ + }, + "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference.": { + "code": 2200, + "category": 1 /* Error */ + }, + "'continue' statement can only be used within an enclosing iteration statement.": { + "code": 2201, + "category": 1 /* Error */ + }, + "'break' statement can only be used within an enclosing iteration or switch statement.": { + "code": 2202, + "category": 1 /* Error */ + }, + "Jump target not found.": { + "code": 2203, + "category": 1 /* Error */ + }, + "Jump target cannot cross function boundary.": { + "code": 2204, + "category": 1 /* Error */ + }, + "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference.": { + "code": 2205, + "category": 1 /* Error */ + }, + "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference.": { + "code": 2206, + "category": 1 /* Error */ + }, + "Expression resolves to '_super' that compiler uses to capture base class reference.": { + "code": 2207, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.": { + "code": 2208, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of call signature from exported interface has or is using private type '{1}'.": { + "code": 2209, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public static method from exported class has or is using private type '{1}'.": { + "code": 2210, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public method from exported class has or is using private type '{1}'.": { + "code": 2211, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of method from exported interface has or is using private type '{1}'.": { + "code": 2212, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported function has or is using private type '{1}'.": { + "code": 2213, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.": { + "code": 2214, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of call signature from exported interface is using inaccessible module {1}": { + "code": 2215, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public static method from exported class is using inaccessible module {1}.": { + "code": 2216, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public method from exported class is using inaccessible module {1}.": { + "code": 2217, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of method from exported interface is using inaccessible module {1}.": { + "code": 2218, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported function is using inaccessible module {1}.": { + "code": 2219, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported class has or is using private type '{1}'.": { + "code": 2220, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported interface has or is using private type '{1}'.": { + "code": 2221, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported class is using inaccessible module {1}.": { + "code": 2222, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported interface is using inaccessible module {1}.": { + "code": 2223, + "category": 1 /* Error */ + }, + "Duplicate identifier '_i'. Compiler uses '_i' to initialize rest parameter.": { + "code": 2224, + "category": 1 /* Error */ + }, + "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters.": { + "code": 2225, + "category": 1 /* Error */ + }, + "Type of conditional '{0}' must be identical to '{1}' or '{2}'.": { + "code": 2226, + "category": 1 /* Error */ + }, + "Type of conditional '{0}' must be identical to '{1}', '{2}' or '{3}'.": { + "code": 2227, + "category": 1 /* Error */ + }, + "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of an external module.": { + "code": 2228, + "category": 1 /* Error */ + }, + "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.": { + "code": 2229, + "category": 1 /* Error */ + }, + "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.": { + "code": 2230, + "category": 1 /* Error */ + }, + "Parameter '{0}' cannot be referenced in its initializer.": { + "code": 2231, + "category": 1 /* Error */ + }, + "Duplicate string index signature.": { + "code": 2232, + "category": 1 /* Error */ + }, + "Duplicate number index signature.": { + "code": 2233, + "category": 1 /* Error */ + }, + "All declarations of an interface must have identical type parameters.": { + "code": 2234, + "category": 1 /* Error */ + }, + "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter.": { + "code": 2235, + "category": 1 /* Error */ + }, + "Type '{0}' is missing property '{1}' from type '{2}'.": { + "code": 4000, + "category": 3 /* NoPrefix */ + }, + "Types of property '{0}' of types '{1}' and '{2}' are incompatible.": { + "code": 4001, + "category": 3 /* NoPrefix */ + }, + "Types of property '{0}' of types '{1}' and '{2}' are incompatible:{NL}{3}": { + "code": 4002, + "category": 3 /* NoPrefix */ + }, + "Property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.": { + "code": 4003, + "category": 3 /* NoPrefix */ + }, + "Property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.": { + "code": 4004, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' define property '{2}' as private.": { + "code": 4005, + "category": 3 /* NoPrefix */ + }, + "Call signatures of types '{0}' and '{1}' are incompatible.": { + "code": 4006, + "category": 3 /* NoPrefix */ + }, + "Call signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { + "code": 4007, + "category": 3 /* NoPrefix */ + }, + "Type '{0}' requires a call signature, but type '{1}' lacks one.": { + "code": 4008, + "category": 3 /* NoPrefix */ + }, + "Construct signatures of types '{0}' and '{1}' are incompatible.": { + "code": 4009, + "category": 3 /* NoPrefix */ + }, + "Construct signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { + "code": 4010, + "category": 3 /* NoPrefix */ + }, + "Type '{0}' requires a construct signature, but type '{1}' lacks one.": { + "code": 4011, + "category": 3 /* NoPrefix */ + }, + "Index signatures of types '{0}' and '{1}' are incompatible.": { + "code": 4012, + "category": 3 /* NoPrefix */ + }, + "Index signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { + "code": 4013, + "category": 3 /* NoPrefix */ + }, + "Call signature expects {0} or fewer parameters.": { + "code": 4014, + "category": 3 /* NoPrefix */ + }, + "Could not apply type '{0}' to argument {1} which is of type '{2}'.": { + "code": 4015, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function.": { + "code": 4016, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.": { + "code": 4017, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor.": { + "code": 4018, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.": { + "code": 4019, + "category": 3 /* NoPrefix */ + }, + "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible.": { + "code": 4020, + "category": 3 /* NoPrefix */ + }, + "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible:{NL}{3}": { + "code": 4021, + "category": 3 /* NoPrefix */ + }, + "Type reference cannot refer to container '{0}'.": { + "code": 4022, + "category": 1 /* Error */ + }, + "Type reference must refer to type.": { + "code": 4023, + "category": 1 /* Error */ + }, + "In enums with multiple declarations only one declaration can omit an initializer for the first enum element.": { + "code": 4024, + "category": 1 /* Error */ + }, + " (+ {0} overload(s))": { + "code": 4025, + "category": 2 /* Message */ + }, + "Variable declaration cannot have the same name as an import declaration.": { + "code": 4026, + "category": 1 /* Error */ + }, + "Signature expected {0} type arguments, got {1} instead.": { + "code": 4027, + "category": 1 /* Error */ + }, + "Property '{0}' defined as optional in type '{1}', but is required in type '{2}'.": { + "code": 4028, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference do not refer to same named type.": { + "code": 4029, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments.": { + "code": 4030, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments:{NL}{2}": { + "code": 4031, + "category": 3 /* NoPrefix */ + }, + "Named properties '{0}' of types '{1}' and '{2}' are not identical.": { + "code": 4032, + "category": 3 /* NoPrefix */ + }, + "Types of string indexer of types '{0}' and '{1}' are not identical.": { + "code": 4033, + "category": 3 /* NoPrefix */ + }, + "Types of number indexer of types '{0}' and '{1}' are not identical.": { + "code": 4034, + "category": 3 /* NoPrefix */ + }, + "Type of number indexer in type '{0}' is not assignable to string indexer type in type '{1}'.{NL}{2}": { + "code": 4035, + "category": 3 /* NoPrefix */ + }, + "Type of property '{0}' in type '{1}' is not assignable to string indexer type in type '{2}'.{NL}{3}": { + "code": 4036, + "category": 3 /* NoPrefix */ + }, + "Type of property '{0}' in type '{1}' is not assignable to number indexer type in type '{2}'.{NL}{3}": { + "code": 4037, + "category": 3 /* NoPrefix */ + }, + "Static property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.": { + "code": 4038, + "category": 3 /* NoPrefix */ + }, + "Static property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.": { + "code": 4039, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' define static property '{2}' as private.": { + "code": 4040, + "category": 3 /* NoPrefix */ + }, + "Current host does not support '{0}' option.": { + "code": 5001, + "category": 1 /* Error */ + }, + "ECMAScript target version '{0}' not supported. Specify a valid target version: '{1}' (default), or '{2}'": { + "code": 5002, + "category": 1 /* Error */ + }, + "Module code generation '{0}' not supported.": { + "code": 5003, + "category": 1 /* Error */ + }, + "Could not find file: '{0}'.": { + "code": 5004, + "category": 1 /* Error */ + }, + "A file cannot have a reference to itself.": { + "code": 5006, + "category": 1 /* Error */ + }, + "Cannot resolve referenced file: '{0}'.": { + "code": 5007, + "category": 1 /* Error */ + }, + "Cannot find the common subdirectory path for the input files.": { + "code": 5009, + "category": 1 /* Error */ + }, + "Emit Error: {0}.": { + "code": 5011, + "category": 1 /* Error */ + }, + "Cannot read file '{0}': {1}": { + "code": 5012, + "category": 1 /* Error */ + }, + "Unsupported file encoding.": { + "code": 5013, + "category": 3 /* NoPrefix */ + }, + "Locale must be of the form or -. For example '{0}' or '{1}'.": { + "code": 5014, + "category": 1 /* Error */ + }, + "Unsupported locale: '{0}'.": { + "code": 5015, + "category": 1 /* Error */ + }, + "Execution Failed.{NL}": { + "code": 5016, + "category": 1 /* Error */ + }, + "Invalid call to 'up'": { + "code": 5019, + "category": 1 /* Error */ + }, + "Invalid call to 'down'": { + "code": 5020, + "category": 1 /* Error */ + }, + "Base64 value '{0}' finished with a continuation bit.": { + "code": 5021, + "category": 1 /* Error */ + }, + "Unknown option '{0}'": { + "code": 5023, + "category": 1 /* Error */ + }, + "Expected {0} arguments to message, got {1} instead.": { + "code": 5024, + "category": 1 /* Error */ + }, + "Expected the message '{0}' to have {1} arguments, but it had {2}": { + "code": 5025, + "category": 1 /* Error */ + }, + "Could not delete file '{0}'": { + "code": 5034, + "category": 1 /* Error */ + }, + "Could not create directory '{0}'": { + "code": 5035, + "category": 1 /* Error */ + }, + "Error while executing file '{0}': ": { + "code": 5036, + "category": 1 /* Error */ + }, + "Cannot compile external modules unless the '--module' flag is provided.": { + "code": 5037, + "category": 1 /* Error */ + }, + "Option mapRoot cannot be specified without specifying sourcemap option.": { + "code": 5038, + "category": 1 /* Error */ + }, + "Option sourceRoot cannot be specified without specifying sourcemap option.": { + "code": 5039, + "category": 1 /* Error */ + }, + "Options mapRoot and sourceRoot cannot be specified without specifying sourcemap option.": { + "code": 5040, + "category": 1 /* Error */ + }, + "Option '{0}' specified without '{1}'": { + "code": 5041, + "category": 1 /* Error */ + }, + "'codepage' option not supported on current platform.": { + "code": 5042, + "category": 1 /* Error */ + }, + "Concatenate and emit output to single file.": { + "code": 6001, + "category": 2 /* Message */ + }, + "Generates corresponding {0} file.": { + "code": 6002, + "category": 2 /* Message */ + }, + "Specifies the location where debugger should locate map files instead of generated locations.": { + "code": 6003, + "category": 2 /* Message */ + }, + "Specifies the location where debugger should locate TypeScript files instead of source locations.": { + "code": 6004, + "category": 2 /* Message */ + }, + "Watch input files.": { + "code": 6005, + "category": 2 /* Message */ + }, + "Redirect output structure to the directory.": { + "code": 6006, + "category": 2 /* Message */ + }, + "Do not emit comments to output.": { + "code": 6009, + "category": 2 /* Message */ + }, + "Skip resolution and preprocessing.": { + "code": 6010, + "category": 2 /* Message */ + }, + "Specify ECMAScript target version: '{0}' (default), or '{1}'": { + "code": 6015, + "category": 2 /* Message */ + }, + "Specify module code generation: '{0}' or '{1}'": { + "code": 6016, + "category": 2 /* Message */ + }, + "Print this message.": { + "code": 6017, + "category": 2 /* Message */ + }, + "Print the compiler's version: {0}": { + "code": 6019, + "category": 2 /* Message */ + }, + "Allow use of deprecated '{0}' keyword when referencing an external module.": { + "code": 6021, + "category": 2 /* Message */ + }, + "Specify locale for errors and messages. For example '{0}' or '{1}'": { + "code": 6022, + "category": 2 /* Message */ + }, + "Syntax: {0}": { + "code": 6023, + "category": 2 /* Message */ + }, + "options": { + "code": 6024, + "category": 2 /* Message */ + }, + "file1": { + "code": 6025, + "category": 2 /* Message */ + }, + "Examples:": { + "code": 6026, + "category": 2 /* Message */ + }, + "Options:": { + "code": 6027, + "category": 2 /* Message */ + }, + "Insert command line options and files from a file.": { + "code": 6030, + "category": 2 /* Message */ + }, + "Version {0}": { + "code": 6029, + "category": 2 /* Message */ + }, + "Use the '{0}' flag to see options.": { + "code": 6031, + "category": 2 /* Message */ + }, + "{NL}Recompiling ({0}):": { + "code": 6032, + "category": 2 /* Message */ + }, + "STRING": { + "code": 6033, + "category": 2 /* Message */ + }, + "KIND": { + "code": 6034, + "category": 2 /* Message */ + }, + "file2": { + "code": 6035, + "category": 2 /* Message */ + }, + "VERSION": { + "code": 6036, + "category": 2 /* Message */ + }, + "LOCATION": { + "code": 6037, + "category": 2 /* Message */ + }, + "DIRECTORY": { + "code": 6038, + "category": 2 /* Message */ + }, + "NUMBER": { + "code": 6039, + "category": 2 /* Message */ + }, + "Specify the codepage to use when opening source files.": { + "code": 6040, + "category": 2 /* Message */ + }, + "Additional locations:": { + "code": 6041, + "category": 2 /* Message */ + }, + "This version of the Javascript runtime does not support the '{0}' function.": { + "code": 7000, + "category": 1 /* Error */ + }, + "Unknown rule.": { + "code": 7002, + "category": 1 /* Error */ + }, + "Invalid line number ({0})": { + "code": 7003, + "category": 1 /* Error */ + }, + "Warn on expressions and declarations with an implied 'any' type.": { + "code": 7004, + "category": 2 /* Message */ + }, + "Variable '{0}' implicitly has an 'any' type.": { + "code": 7005, + "category": 1 /* Error */ + }, + "Parameter '{0}' of '{1}' implicitly has an 'any' type.": { + "code": 7006, + "category": 1 /* Error */ + }, + "Parameter '{0}' of function type implicitly has an 'any' type.": { + "code": 7007, + "category": 1 /* Error */ + }, + "Member '{0}' of object type implicitly has an 'any' type.": { + "code": 7008, + "category": 1 /* Error */ + }, + "'new' expression, which lacks a constructor signature, implicitly has an 'any' type.": { + "code": 7009, + "category": 1 /* Error */ + }, + "'{0}', which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7010, + "category": 1 /* Error */ + }, + "Function expression, which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7011, + "category": 1 /* Error */ + }, + "Parameter '{0}' of lambda function implicitly has an 'any' type.": { + "code": 7012, + "category": 1 /* Error */ + }, + "Constructor signature, which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7013, + "category": 1 /* Error */ + }, + "Lambda Function, which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7014, + "category": 1 /* Error */ + }, + "Array Literal implicitly has an 'any' type from widening.": { + "code": 7015, + "category": 1 /* Error */ + }, + "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type.": { + "code": 7016, + "category": 1 /* Error */ + }, + "Index signature of object type implicitly has an 'any' type.": { + "code": 7017, + "category": 1 /* Error */ + }, + "Object literal's property '{0}' implicitly has an 'any' type from widening.": { + "code": 7018, + "category": 1 /* Error */ + } + }; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 0x2028] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 0x2029] = "paragraphSeparator"; + + CharacterCodes[CharacterCodes["nextLine"] = 0x0085] = "nextLine"; + + CharacterCodes[CharacterCodes["space"] = 0x0020] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 0x00A0] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 0x2000] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 0x2001] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 0x2002] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 0x2003] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 0x2004] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 0x2005] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 0x2006] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 0x2007] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 0x2008] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 0x2009] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 0x200A] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 0x200B] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 0x202F] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 0x3000] = "ideographicSpace"; + + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 0xFEFF] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(TypeScript.CharacterCodes || (TypeScript.CharacterCodes = {})); + var CharacterCodes = TypeScript.CharacterCodes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + + + (function (ScriptSnapshot) { + var StringScriptSnapshot = (function () { + function StringScriptSnapshot(text) { + this.text = text; + this._lineStartPositions = null; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + + StringScriptSnapshot.prototype.getLineStartPositions = function () { + if (!this._lineStartPositions) { + this._lineStartPositions = TypeScript.TextUtilities.parseLineStarts(this.text); + } + + return this._lineStartPositions; + }; + + StringScriptSnapshot.prototype.getTextChangeRangeSinceVersion = function (scriptVersion) { + throw TypeScript.Errors.notYetImplemented(); + }; + return StringScriptSnapshot; + })(); + + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(TypeScript.ScriptSnapshot || (TypeScript.ScriptSnapshot = {})); + var ScriptSnapshot = TypeScript.ScriptSnapshot; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (LineMap1) { + function fromSimpleText(text) { + return new TypeScript.LineMap(function () { + return TypeScript.TextUtilities.parseLineStarts({ charCodeAt: function (index) { + return text.charCodeAt(index); + }, length: text.length() }); + }, text.length()); + } + LineMap1.fromSimpleText = fromSimpleText; + + function fromScriptSnapshot(scriptSnapshot) { + return new TypeScript.LineMap(function () { + return scriptSnapshot.getLineStartPositions(); + }, scriptSnapshot.getLength()); + } + LineMap1.fromScriptSnapshot = fromScriptSnapshot; + + function fromString(text) { + return new TypeScript.LineMap(function () { + return TypeScript.TextUtilities.parseLineStarts(text); + }, text.length); + } + LineMap1.fromString = fromString; + })(TypeScript.LineMap1 || (TypeScript.LineMap1 = {})); + var LineMap1 = TypeScript.LineMap1; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TextFactory) { + function getStartAndLengthOfLineBreakEndingAt(text, index, info) { + var c = text.charCodeAt(index); + if (c === 10 /* lineFeed */) { + if (index > 0 && text.charCodeAt(index - 1) === 13 /* carriageReturn */) { + info.startPosition = index - 1; + info.length = 2; + } else { + info.startPosition = index; + info.length = 1; + } + } else if (TypeScript.TextUtilities.isAnyLineBreakCharacter(c)) { + info.startPosition = index; + info.length = 1; + } else { + info.startPosition = index + 1; + info.length = 0; + } + } + + var LinebreakInfo = (function () { + function LinebreakInfo(startPosition, length) { + this.startPosition = startPosition; + this.length = length; + } + return LinebreakInfo; + })(); + + var TextLine = (function () { + function TextLine(text, body, lineBreakLength, lineNumber) { + this._text = null; + this._textSpan = null; + if (text === null) { + throw TypeScript.Errors.argumentNull('text'); + } + TypeScript.Debug.assert(lineBreakLength >= 0); + TypeScript.Debug.assert(lineNumber >= 0); + this._text = text; + this._textSpan = body; + this._lineBreakLength = lineBreakLength; + this._lineNumber = lineNumber; + } + TextLine.prototype.start = function () { + return this._textSpan.start(); + }; + + TextLine.prototype.end = function () { + return this._textSpan.end(); + }; + + TextLine.prototype.endIncludingLineBreak = function () { + return this.end() + this._lineBreakLength; + }; + + TextLine.prototype.extent = function () { + return this._textSpan; + }; + + TextLine.prototype.extentIncludingLineBreak = function () { + return TypeScript.TextSpan.fromBounds(this.start(), this.endIncludingLineBreak()); + }; + + TextLine.prototype.toString = function () { + return this._text.toString(this._textSpan); + }; + + TextLine.prototype.lineNumber = function () { + return this._lineNumber; + }; + return TextLine; + })(); + + var TextBase = (function () { + function TextBase() { + this.linebreakInfo = new LinebreakInfo(0, 0); + this.lastLineFoundForPosition = null; + } + TextBase.prototype.length = function () { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.charCodeAt = function (position) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.checkSubSpan = function (span) { + if (span.start() < 0 || span.start() > this.length() || span.end() > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("span"); + } + }; + + TextBase.prototype.toString = function (span) { + if (typeof span === "undefined") { span = null; } + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SubText(this, span); + }; + + TextBase.prototype.substr = function (start, length, intern) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.lineCount = function () { + return this._lineStarts().length; + }; + + TextBase.prototype.lines = function () { + var lines = []; + + var length = this.lineCount(); + for (var i = 0; i < length; ++i) { + lines[i] = this.getLineFromLineNumber(i); + } + + return lines; + }; + + TextBase.prototype.lineMap = function () { + var _this = this; + return new TypeScript.LineMap(function () { + return _this._lineStarts(); + }, this.length()); + }; + + TextBase.prototype._lineStarts = function () { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.getLineFromLineNumber = function (lineNumber) { + var lineStarts = this._lineStarts(); + + if (lineNumber < 0 || lineNumber >= lineStarts.length) { + throw TypeScript.Errors.argumentOutOfRange("lineNumber"); + } + + var first = lineStarts[lineNumber]; + if (lineNumber === lineStarts.length - 1) { + return new TextLine(this, new TypeScript.TextSpan(first, this.length() - first), 0, lineNumber); + } else { + getStartAndLengthOfLineBreakEndingAt(this, lineStarts[lineNumber + 1] - 1, this.linebreakInfo); + return new TextLine(this, new TypeScript.TextSpan(first, this.linebreakInfo.startPosition - first), this.linebreakInfo.length, lineNumber); + } + }; + + TextBase.prototype.getLineFromPosition = function (position) { + var lastFound = this.lastLineFoundForPosition; + if (lastFound !== null && lastFound.start() <= position && lastFound.endIncludingLineBreak() > position) { + return lastFound; + } + + var lineNumber = this.getLineNumberFromPosition(position); + + var result = this.getLineFromLineNumber(lineNumber); + this.lastLineFoundForPosition = result; + return result; + }; + + TextBase.prototype.getLineNumberFromPosition = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + if (position === this.length()) { + return this.lineCount() - 1; + } + + var lineNumber = TypeScript.ArrayUtilities.binarySearch(this._lineStarts(), position); + if (lineNumber < 0) { + lineNumber = (~lineNumber) - 1; + } + + return lineNumber; + }; + + TextBase.prototype.getLinePosition = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + + return new TypeScript.LineAndCharacter(lineNumber, position - this._lineStarts()[lineNumber]); + }; + return TextBase; + })(); + + var SubText = (function (_super) { + __extends(SubText, _super); + function SubText(text, span) { + _super.call(this); + this._lazyLineStarts = null; + + if (text === null) { + throw TypeScript.Errors.argumentNull("text"); + } + + if (span.start() < 0 || span.start() >= text.length() || span.end() < 0 || span.end() > text.length()) { + throw TypeScript.Errors.argument("span"); + } + + this.text = text; + this.span = span; + } + SubText.prototype.length = function () { + return this.span.length(); + }; + + SubText.prototype.charCodeAt = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + return this.text.charCodeAt(this.span.start() + position); + }; + + SubText.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SubText(this.text, this.getCompositeSpan(span.start(), span.length())); + }; + + SubText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var span = this.getCompositeSpan(sourceIndex, count); + this.text.copyTo(span.start(), destination, destinationIndex, span.length()); + }; + + SubText.prototype.substr = function (start, length, intern) { + var startInOriginalText = this.span.start() + start; + return this.text.substr(startInOriginalText, length, intern); + }; + + SubText.prototype.getCompositeSpan = function (start, length) { + var compositeStart = TypeScript.MathPrototype.min(this.text.length(), this.span.start() + start); + var compositeEnd = TypeScript.MathPrototype.min(this.text.length(), compositeStart + length); + return new TypeScript.TextSpan(compositeStart, compositeEnd - compositeStart); + }; + + SubText.prototype._lineStarts = function () { + var _this = this; + if (!this._lazyLineStarts) { + this._lazyLineStarts = TypeScript.TextUtilities.parseLineStarts({ charCodeAt: function (index) { + return _this.charCodeAt(index); + }, length: this.length() }); + } + + return this._lazyLineStarts; + }; + return SubText; + })(TextBase); + + var StringText = (function (_super) { + __extends(StringText, _super); + function StringText(data) { + _super.call(this); + this.source = null; + this._lazyLineStarts = null; + + if (data === null) { + throw TypeScript.Errors.argumentNull("data"); + } + + this.source = data; + } + StringText.prototype.length = function () { + return this.source.length; + }; + + StringText.prototype.charCodeAt = function (position) { + if (position < 0 || position >= this.source.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + return this.source.charCodeAt(position); + }; + + StringText.prototype.substr = function (start, length, intern) { + return this.source.substr(start, length); + }; + + StringText.prototype.toString = function (span) { + if (typeof span === "undefined") { span = null; } + if (span === null) { + span = new TypeScript.TextSpan(0, this.length()); + } + + this.checkSubSpan(span); + + if (span.start() === 0 && span.length() === this.length()) { + return this.source; + } + + return this.source.substr(span.start(), span.length()); + }; + + StringText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + TypeScript.StringUtilities.copyTo(this.source, sourceIndex, destination, destinationIndex, count); + }; + + StringText.prototype._lineStarts = function () { + if (this._lazyLineStarts === null) { + this._lazyLineStarts = TypeScript.TextUtilities.parseLineStarts(this.source); + } + + return this._lazyLineStarts; + }; + return StringText; + })(TextBase); + + function createText(value) { + return new StringText(value); + } + TextFactory.createText = createText; + })(TypeScript.TextFactory || (TypeScript.TextFactory = {})); + var TextFactory = TypeScript.TextFactory; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (SimpleText) { + var SimpleSubText = (function () { + function SimpleSubText(text, span) { + this.text = null; + this.span = null; + if (text === null) { + throw TypeScript.Errors.argumentNull("text"); + } + + if (span.start() < 0 || span.start() >= text.length() || span.end() < 0 || span.end() > text.length()) { + throw TypeScript.Errors.argument("span"); + } + + this.text = text; + this.span = span; + } + SimpleSubText.prototype.checkSubSpan = function (span) { + if (span.start() < 0 || span.start() > this.length() || span.end() > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("span"); + } + }; + + SimpleSubText.prototype.checkSubPosition = function (position) { + if (position < 0 || position >= this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + }; + + SimpleSubText.prototype.length = function () { + return this.span.length(); + }; + + SimpleSubText.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SimpleSubText(this.text, this.getCompositeSpan(span.start(), span.length())); + }; + + SimpleSubText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var span = this.getCompositeSpan(sourceIndex, count); + this.text.copyTo(span.start(), destination, destinationIndex, span.length()); + }; + + SimpleSubText.prototype.substr = function (start, length, intern) { + var span = this.getCompositeSpan(start, length); + return this.text.substr(span.start(), span.length(), intern); + }; + + SimpleSubText.prototype.getCompositeSpan = function (start, length) { + var compositeStart = TypeScript.MathPrototype.min(this.text.length(), this.span.start() + start); + var compositeEnd = TypeScript.MathPrototype.min(this.text.length(), compositeStart + length); + return new TypeScript.TextSpan(compositeStart, compositeEnd - compositeStart); + }; + + SimpleSubText.prototype.charCodeAt = function (index) { + this.checkSubPosition(index); + return this.text.charCodeAt(this.span.start() + index); + }; + + SimpleSubText.prototype.lineMap = function () { + return TypeScript.LineMap1.fromSimpleText(this); + }; + return SimpleSubText; + })(); + + var SimpleStringText = (function () { + function SimpleStringText(value) { + this.value = value; + this._lineMap = null; + } + SimpleStringText.prototype.length = function () { + return this.value.length; + }; + + SimpleStringText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + TypeScript.StringUtilities.copyTo(this.value, sourceIndex, destination, destinationIndex, count); + }; + + SimpleStringText.prototype.substr = function (start, length, intern) { + if (intern) { + var array = length <= SimpleStringText.charArray.length ? SimpleStringText.charArray : TypeScript.ArrayUtilities.createArray(length, 0); + this.copyTo(start, array, 0, length); + return TypeScript.Collections.DefaultStringTable.addCharArray(array, 0, length); + } + + return this.value.substr(start, length); + }; + + SimpleStringText.prototype.subText = function (span) { + return new SimpleSubText(this, span); + }; + + SimpleStringText.prototype.charCodeAt = function (index) { + return this.value.charCodeAt(index); + }; + + SimpleStringText.prototype.lineMap = function () { + if (!this._lineMap) { + this._lineMap = TypeScript.LineMap1.fromString(this.value); + } + + return this._lineMap; + }; + SimpleStringText.charArray = TypeScript.ArrayUtilities.createArray(1024, 0); + return SimpleStringText; + })(); + + var SimpleScriptSnapshotText = (function () { + function SimpleScriptSnapshotText(scriptSnapshot) { + this.scriptSnapshot = scriptSnapshot; + } + SimpleScriptSnapshotText.prototype.charCodeAt = function (index) { + return this.scriptSnapshot.getText(index, index + 1).charCodeAt(0); + }; + + SimpleScriptSnapshotText.prototype.length = function () { + return this.scriptSnapshot.getLength(); + }; + + SimpleScriptSnapshotText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var text = this.scriptSnapshot.getText(sourceIndex, sourceIndex + count); + TypeScript.StringUtilities.copyTo(text, 0, destination, destinationIndex, count); + }; + + SimpleScriptSnapshotText.prototype.substr = function (start, length, intern) { + return this.scriptSnapshot.getText(start, start + length); + }; + + SimpleScriptSnapshotText.prototype.subText = function (span) { + return new SimpleSubText(this, span); + }; + + SimpleScriptSnapshotText.prototype.lineMap = function () { + var _this = this; + return new TypeScript.LineMap(function () { + return _this.scriptSnapshot.getLineStartPositions(); + }, this.length()); + }; + return SimpleScriptSnapshotText; + })(); + + function fromString(value) { + return new SimpleStringText(value); + } + SimpleText.fromString = fromString; + + function fromScriptSnapshot(scriptSnapshot) { + return new SimpleScriptSnapshotText(scriptSnapshot); + } + SimpleText.fromScriptSnapshot = fromScriptSnapshot; + })(TypeScript.SimpleText || (TypeScript.SimpleText = {})); + var SimpleText = TypeScript.SimpleText; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TextUtilities) { + function parseLineStarts(text) { + var length = text.length; + + if (0 === length) { + var result = new Array(); + result.push(0); + return result; + } + + var position = 0; + var index = 0; + var arrayBuilder = new Array(); + var lineNumber = 0; + + while (index < length) { + var c = text.charCodeAt(index); + var lineBreakLength; + + if (c > 13 /* carriageReturn */ && c <= 127) { + index++; + continue; + } else if (c === 13 /* carriageReturn */ && index + 1 < length && text.charCodeAt(index + 1) === 10 /* lineFeed */) { + lineBreakLength = 2; + } else if (c === 10 /* lineFeed */) { + lineBreakLength = 1; + } else { + lineBreakLength = TextUtilities.getLengthOfLineBreak(text, index); + } + + if (0 === lineBreakLength) { + index++; + } else { + arrayBuilder.push(position); + index += lineBreakLength; + position = index; + lineNumber++; + } + } + + arrayBuilder.push(position); + + return arrayBuilder; + } + TextUtilities.parseLineStarts = parseLineStarts; + + function getLengthOfLineBreakSlow(text, index, c) { + if (c === 13 /* carriageReturn */) { + var next = index + 1; + return (next < text.length) && 10 /* lineFeed */ === text.charCodeAt(next) ? 2 : 1; + } else if (isAnyLineBreakCharacter(c)) { + return 1; + } else { + return 0; + } + } + TextUtilities.getLengthOfLineBreakSlow = getLengthOfLineBreakSlow; + + function getLengthOfLineBreak(text, index) { + var c = text.charCodeAt(index); + + if (c > 13 /* carriageReturn */ && c <= 127) { + return 0; + } + + return getLengthOfLineBreakSlow(text, index, c); + } + TextUtilities.getLengthOfLineBreak = getLengthOfLineBreak; + + function isAnyLineBreakCharacter(c) { + return c === 10 /* lineFeed */ || c === 13 /* carriageReturn */ || c === 133 /* nextLine */ || c === 8232 /* lineSeparator */ || c === 8233 /* paragraphSeparator */; + } + TextUtilities.isAnyLineBreakCharacter = isAnyLineBreakCharacter; + })(TypeScript.TextUtilities || (TypeScript.TextUtilities = {})); + var TextUtilities = TypeScript.TextUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextSpan = (function () { + function TextSpan(start, length) { + if (start < 0) { + TypeScript.Errors.argument("start"); + } + + if (length < 0) { + TypeScript.Errors.argument("length"); + } + + this._start = start; + this._length = length; + } + TextSpan.prototype.start = function () { + return this._start; + }; + + TextSpan.prototype.length = function () { + return this._length; + }; + + TextSpan.prototype.end = function () { + return this._start + this._length; + }; + + TextSpan.prototype.isEmpty = function () { + return this._length === 0; + }; + + TextSpan.prototype.containsPosition = function (position) { + return position >= this._start && position < this.end(); + }; + + TextSpan.prototype.containsTextSpan = function (span) { + return span._start >= this._start && span.end() <= this.end(); + }; + + TextSpan.prototype.overlapsWith = function (span) { + var overlapStart = TypeScript.MathPrototype.max(this._start, span._start); + var overlapEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + return overlapStart < overlapEnd; + }; + + TextSpan.prototype.overlap = function (span) { + var overlapStart = TypeScript.MathPrototype.max(this._start, span._start); + var overlapEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + if (overlapStart < overlapEnd) { + return TextSpan.fromBounds(overlapStart, overlapEnd); + } + + return null; + }; + + TextSpan.prototype.intersectsWithTextSpan = function (span) { + return span._start <= this.end() && span.end() >= this._start; + }; + + TextSpan.prototype.intersectsWith = function (start, length) { + var end = start + length; + return start <= this.end() && end >= this._start; + }; + + TextSpan.prototype.intersectsWithPosition = function (position) { + return position <= this.end() && position >= this._start; + }; + + TextSpan.prototype.intersection = function (span) { + var intersectStart = TypeScript.MathPrototype.max(this._start, span._start); + var intersectEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + if (intersectStart <= intersectEnd) { + return TextSpan.fromBounds(intersectStart, intersectEnd); + } + + return null; + }; + + TextSpan.fromBounds = function (start, end) { + TypeScript.Debug.assert(start >= 0); + TypeScript.Debug.assert(end - start >= 0); + return new TextSpan(start, end - start); + }; + return TextSpan; + })(); + TypeScript.TextSpan = TextSpan; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextChangeRange = (function () { + function TextChangeRange(span, newLength) { + if (newLength < 0) { + throw TypeScript.Errors.argumentOutOfRange("newLength"); + } + + this._span = span; + this._newLength = newLength; + } + TextChangeRange.prototype.span = function () { + return this._span; + }; + + TextChangeRange.prototype.newLength = function () { + return this._newLength; + }; + + TextChangeRange.prototype.newSpan = function () { + return new TypeScript.TextSpan(this.span().start(), this.newLength()); + }; + + TextChangeRange.prototype.isUnchanged = function () { + return this.span().isEmpty() && this.newLength() === 0; + }; + + TextChangeRange.collapseChangesFromSingleVersion = function (changes) { + var diff = 0; + var start = 1073741823 /* Max31BitInteger */; + var end = 0; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + diff += change.newLength() - change.span().length(); + + if (change.span().start() < start) { + start = change.span().start(); + } + + if (change.span().end() > end) { + end = change.span().end(); + } + } + + if (start > end) { + return null; + } + + var combined = TypeScript.TextSpan.fromBounds(start, end); + var newLen = combined.length() + diff; + + return new TextChangeRange(combined, newLen); + }; + + TextChangeRange.collapseChangesAcrossMultipleVersions = function (changes) { + if (changes.length === 0) { + return TextChangeRange.unchanged; + } + + if (changes.length === 1) { + return changes[0]; + } + + var change0 = changes[0]; + + var oldStartN = change0.span().start(); + var oldEndN = change0.span().end(); + var newEndN = oldStartN + change0.newLength(); + + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + + var oldStart2 = nextChange.span().start(); + var oldEnd2 = nextChange.span().end(); + var newEnd2 = oldStart2 + nextChange.newLength(); + + oldStartN = TypeScript.MathPrototype.min(oldStart1, oldStart2); + oldEndN = TypeScript.MathPrototype.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = TypeScript.MathPrototype.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + + return new TextChangeRange(TypeScript.TextSpan.fromBounds(oldStartN, oldEndN), newEndN - oldStartN); + }; + TextChangeRange.unchanged = new TextChangeRange(new TypeScript.TextSpan(0, 0), 0); + return TextChangeRange; + })(); + TypeScript.TextChangeRange = TextChangeRange; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CharacterInfo = (function () { + function CharacterInfo() { + } + CharacterInfo.isDecimalDigit = function (c) { + return c >= 48 /* _0 */ && c <= 57 /* _9 */; + }; + CharacterInfo.isOctalDigit = function (c) { + return c >= 48 /* _0 */ && c <= 55 /* _7 */; + }; + + CharacterInfo.isHexDigit = function (c) { + return CharacterInfo.isDecimalDigit(c) || (c >= 65 /* A */ && c <= 70 /* F */) || (c >= 97 /* a */ && c <= 102 /* f */); + }; + + CharacterInfo.hexValue = function (c) { + return CharacterInfo.isDecimalDigit(c) ? (c - 48 /* _0 */) : (c >= 65 /* A */ && c <= 70 /* F */) ? c - 65 /* A */ + 10 : c - 97 /* a */ + 10; + }; + + CharacterInfo.isWhitespace = function (ch) { + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + return true; + } + + return false; + }; + + CharacterInfo.isLineTerminator = function (ch) { + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + return true; + } + + return false; + }; + return CharacterInfo; + })(); + TypeScript.CharacterInfo = CharacterInfo; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxConstants) { + SyntaxConstants[SyntaxConstants["TriviaNewLineMask"] = 0x00000001] = "TriviaNewLineMask"; + SyntaxConstants[SyntaxConstants["TriviaCommentMask"] = 0x00000002] = "TriviaCommentMask"; + SyntaxConstants[SyntaxConstants["TriviaFullWidthShift"] = 2] = "TriviaFullWidthShift"; + + SyntaxConstants[SyntaxConstants["NodeDataComputed"] = 0x00000001] = "NodeDataComputed"; + SyntaxConstants[SyntaxConstants["NodeIncrementallyUnusableMask"] = 0x00000002] = "NodeIncrementallyUnusableMask"; + SyntaxConstants[SyntaxConstants["NodeParsedInStrictModeMask"] = 0x00000004] = "NodeParsedInStrictModeMask"; + SyntaxConstants[SyntaxConstants["NodeFullWidthShift"] = 3] = "NodeFullWidthShift"; + + SyntaxConstants[SyntaxConstants["IsVariableWidthKeyword"] = 1 << 31] = "IsVariableWidthKeyword"; + })(TypeScript.SyntaxConstants || (TypeScript.SyntaxConstants = {})); + var SyntaxConstants = TypeScript.SyntaxConstants; +})(TypeScript || (TypeScript = {})); +var FormattingOptions = (function () { + function FormattingOptions(useTabs, spacesPerTab, indentSpaces, newLineCharacter) { + this.useTabs = useTabs; + this.spacesPerTab = spacesPerTab; + this.indentSpaces = indentSpaces; + this.newLineCharacter = newLineCharacter; + } + FormattingOptions.defaultOptions = new FormattingOptions(false, 4, 4, "\r\n"); + return FormattingOptions; +})(); +var TypeScript; +(function (TypeScript) { + (function (Indentation) { + function columnForEndOfToken(token, syntaxInformationMap, options) { + return columnForStartOfToken(token, syntaxInformationMap, options) + token.width(); + } + Indentation.columnForEndOfToken = columnForEndOfToken; + + function columnForStartOfToken(token, syntaxInformationMap, options) { + var firstTokenInLine = syntaxInformationMap.firstTokenInLineContainingToken(token); + var leadingTextInReverse = []; + + var current = token; + while (current !== firstTokenInLine) { + current = syntaxInformationMap.previousToken(current); + + if (current === firstTokenInLine) { + leadingTextInReverse.push(current.trailingTrivia().fullText()); + leadingTextInReverse.push(current.text()); + } else { + leadingTextInReverse.push(current.fullText()); + } + } + + collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse); + + return columnForLeadingTextInReverse(leadingTextInReverse, options); + } + Indentation.columnForStartOfToken = columnForStartOfToken; + + function columnForStartOfFirstTokenInLineContainingToken(token, syntaxInformationMap, options) { + var firstTokenInLine = syntaxInformationMap.firstTokenInLineContainingToken(token); + var leadingTextInReverse = []; + + collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse); + + return columnForLeadingTextInReverse(leadingTextInReverse, options); + } + Indentation.columnForStartOfFirstTokenInLineContainingToken = columnForStartOfFirstTokenInLineContainingToken; + + function collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse) { + var leadingTrivia = firstTokenInLine.leadingTrivia(); + + for (var i = leadingTrivia.count() - 1; i >= 0; i--) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.kind() === 5 /* NewLineTrivia */) { + break; + } + + if (trivia.kind() === 6 /* MultiLineCommentTrivia */) { + var lineSegments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + leadingTextInReverse.push(TypeScript.ArrayUtilities.last(lineSegments)); + + if (lineSegments.length > 0) { + break; + } + } + + leadingTextInReverse.push(trivia.fullText()); + } + } + + function columnForLeadingTextInReverse(leadingTextInReverse, options) { + var column = 0; + + for (var i = leadingTextInReverse.length - 1; i >= 0; i--) { + var text = leadingTextInReverse[i]; + column = columnForPositionInStringWorker(text, text.length, column, options); + } + + return column; + } + + function columnForPositionInString(input, position, options) { + return columnForPositionInStringWorker(input, position, 0, options); + } + Indentation.columnForPositionInString = columnForPositionInString; + + function columnForPositionInStringWorker(input, position, startColumn, options) { + var column = startColumn; + var spacesPerTab = options.spacesPerTab; + + for (var j = 0; j < position; j++) { + var ch = input.charCodeAt(j); + + if (ch === 9 /* tab */) { + column += spacesPerTab - column % spacesPerTab; + } else { + column++; + } + } + + return column; + } + + function indentationString(column, options) { + var numberOfTabs = 0; + var numberOfSpaces = TypeScript.MathPrototype.max(0, column); + + if (options.useTabs) { + numberOfTabs = Math.floor(column / options.spacesPerTab); + numberOfSpaces -= numberOfTabs * options.spacesPerTab; + } + + return TypeScript.StringUtilities.repeat('\t', numberOfTabs) + TypeScript.StringUtilities.repeat(' ', numberOfSpaces); + } + Indentation.indentationString = indentationString; + + function indentationTrivia(column, options) { + return TypeScript.Syntax.whitespace(this.indentationString(column, options)); + } + Indentation.indentationTrivia = indentationTrivia; + + function firstNonWhitespacePosition(value) { + for (var i = 0; i < value.length; i++) { + var ch = value.charCodeAt(i); + if (!TypeScript.CharacterInfo.isWhitespace(ch)) { + return i; + } + } + + return value.length; + } + Indentation.firstNonWhitespacePosition = firstNonWhitespacePosition; + })(TypeScript.Indentation || (TypeScript.Indentation = {})); + var Indentation = TypeScript.Indentation; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (LanguageVersion) { + LanguageVersion[LanguageVersion["EcmaScript3"] = 0] = "EcmaScript3"; + LanguageVersion[LanguageVersion["EcmaScript5"] = 1] = "EcmaScript5"; + })(TypeScript.LanguageVersion || (TypeScript.LanguageVersion = {})); + var LanguageVersion = TypeScript.LanguageVersion; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ParseOptions = (function () { + function ParseOptions(languageVersion, allowAutomaticSemicolonInsertion) { + this._languageVersion = languageVersion; + this._allowAutomaticSemicolonInsertion = allowAutomaticSemicolonInsertion; + } + ParseOptions.prototype.toJSON = function (key) { + return { allowAutomaticSemicolonInsertion: this._allowAutomaticSemicolonInsertion }; + }; + + ParseOptions.prototype.languageVersion = function () { + return this._languageVersion; + }; + + ParseOptions.prototype.allowAutomaticSemicolonInsertion = function () { + return this._allowAutomaticSemicolonInsertion; + }; + return ParseOptions; + })(); + TypeScript.ParseOptions = ParseOptions; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PositionedElement = (function () { + function PositionedElement(parent, element, fullStart) { + this._parent = parent; + this._element = element; + this._fullStart = fullStart; + } + PositionedElement.create = function (parent, element, fullStart) { + if (element === null) { + return null; + } + + if (element.isNode()) { + return new PositionedNode(parent, element, fullStart); + } else if (element.isToken()) { + return new PositionedToken(parent, element, fullStart); + } else if (element.isList()) { + return new PositionedList(parent, element, fullStart); + } else if (element.isSeparatedList()) { + return new PositionedSeparatedList(parent, element, fullStart); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + PositionedElement.prototype.parent = function () { + return this._parent; + }; + + PositionedElement.prototype.parentElement = function () { + return this._parent && this._parent._element; + }; + + PositionedElement.prototype.element = function () { + return this._element; + }; + + PositionedElement.prototype.kind = function () { + return this.element().kind(); + }; + + PositionedElement.prototype.childIndex = function (child) { + return TypeScript.Syntax.childIndex(this.element(), child); + }; + + PositionedElement.prototype.childCount = function () { + return this.element().childCount(); + }; + + PositionedElement.prototype.childAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + return PositionedElement.create(this, this.element().childAt(index), this.fullStart() + offset); + }; + + PositionedElement.prototype.childStart = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return this.fullStart() + offset + child.leadingTriviaWidth(); + }; + + PositionedElement.prototype.childEnd = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return this.fullStart() + offset + child.leadingTriviaWidth() + child.width(); + }; + + PositionedElement.prototype.childStartAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + var child = this.element().childAt(index); + return this.fullStart() + offset + child.leadingTriviaWidth(); + }; + + PositionedElement.prototype.childEndAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + var child = this.element().childAt(index); + return this.fullStart() + offset + child.leadingTriviaWidth() + child.width(); + }; + + PositionedElement.prototype.getPositionedChild = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return PositionedElement.create(this, child, this.fullStart() + offset); + }; + + PositionedElement.prototype.fullStart = function () { + return this._fullStart; + }; + + PositionedElement.prototype.fullEnd = function () { + return this.fullStart() + this.element().fullWidth(); + }; + + PositionedElement.prototype.fullWidth = function () { + return this.element().fullWidth(); + }; + + PositionedElement.prototype.start = function () { + return this.fullStart() + this.element().leadingTriviaWidth(); + }; + + PositionedElement.prototype.end = function () { + return this.fullStart() + this.element().leadingTriviaWidth() + this.element().width(); + }; + + PositionedElement.prototype.root = function () { + var current = this; + while (current.parent() !== null) { + current = current.parent(); + } + + return current; + }; + + PositionedElement.prototype.containingNode = function () { + var current = this.parent(); + + while (current !== null && !current.element().isNode()) { + current = current.parent(); + } + + return current; + }; + return PositionedElement; + })(); + TypeScript.PositionedElement = PositionedElement; + + var PositionedNodeOrToken = (function (_super) { + __extends(PositionedNodeOrToken, _super); + function PositionedNodeOrToken(parent, nodeOrToken, fullStart) { + _super.call(this, parent, nodeOrToken, fullStart); + } + PositionedNodeOrToken.prototype.nodeOrToken = function () { + return this.element(); + }; + return PositionedNodeOrToken; + })(PositionedElement); + TypeScript.PositionedNodeOrToken = PositionedNodeOrToken; + + var PositionedNode = (function (_super) { + __extends(PositionedNode, _super); + function PositionedNode(parent, node, fullStart) { + _super.call(this, parent, node, fullStart); + } + PositionedNode.prototype.node = function () { + return this.element(); + }; + return PositionedNode; + })(PositionedNodeOrToken); + TypeScript.PositionedNode = PositionedNode; + + var PositionedToken = (function (_super) { + __extends(PositionedToken, _super); + function PositionedToken(parent, token, fullStart) { + _super.call(this, parent, token, fullStart); + } + PositionedToken.prototype.token = function () { + return this.element(); + }; + + PositionedToken.prototype.previousToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var triviaList = this.token().leadingTrivia(); + if (includeSkippedTokens && triviaList && triviaList.hasSkippedToken()) { + var currentTriviaEndPosition = this.start(); + for (var i = triviaList.count() - 1; i >= 0; i--) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isSkippedToken()) { + return new PositionedSkippedToken(this, trivia.skippedToken(), currentTriviaEndPosition - trivia.fullWidth()); + } + + currentTriviaEndPosition -= trivia.fullWidth(); + } + } + + var start = this.fullStart(); + if (start === 0) { + return null; + } + + return this.root().node().findToken(start - 1, includeSkippedTokens); + }; + + PositionedToken.prototype.nextToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + if (this.token().tokenKind === 10 /* EndOfFileToken */) { + return null; + } + + var triviaList = this.token().trailingTrivia(); + if (includeSkippedTokens && triviaList && triviaList.hasSkippedToken()) { + var fullStart = this.end(); + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isSkippedToken()) { + return new PositionedSkippedToken(this, trivia.skippedToken(), fullStart); + } + + fullStart += trivia.fullWidth(); + } + } + + return this.root().node().findToken(this.fullEnd(), includeSkippedTokens); + }; + return PositionedToken; + })(PositionedNodeOrToken); + TypeScript.PositionedToken = PositionedToken; + + var PositionedList = (function (_super) { + __extends(PositionedList, _super); + function PositionedList(parent, list, fullStart) { + _super.call(this, parent, list, fullStart); + } + PositionedList.prototype.list = function () { + return this.element(); + }; + return PositionedList; + })(PositionedElement); + TypeScript.PositionedList = PositionedList; + + var PositionedSeparatedList = (function (_super) { + __extends(PositionedSeparatedList, _super); + function PositionedSeparatedList(parent, list, fullStart) { + _super.call(this, parent, list, fullStart); + } + PositionedSeparatedList.prototype.list = function () { + return this.element(); + }; + return PositionedSeparatedList; + })(PositionedElement); + TypeScript.PositionedSeparatedList = PositionedSeparatedList; + + var PositionedSkippedToken = (function (_super) { + __extends(PositionedSkippedToken, _super); + function PositionedSkippedToken(parentToken, token, fullStart) { + _super.call(this, parentToken.parent(), token, fullStart); + this._parentToken = parentToken; + } + PositionedSkippedToken.prototype.parentToken = function () { + return this._parentToken; + }; + + PositionedSkippedToken.prototype.previousToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var start = this.fullStart(); + + if (includeSkippedTokens) { + var previousToken; + + if (start >= this.parentToken().end()) { + previousToken = TypeScript.Syntax.findSkippedTokenInTrailingTriviaList(this.parentToken(), start - 1); + + if (previousToken) { + return previousToken; + } + + return this.parentToken(); + } else { + previousToken = TypeScript.Syntax.findSkippedTokenInLeadingTriviaList(this.parentToken(), start - 1); + + if (previousToken) { + return previousToken; + } + } + } + + var start = this.parentToken().fullStart(); + if (start === 0) { + return null; + } + + return this.root().node().findToken(start - 1, includeSkippedTokens); + }; + + PositionedSkippedToken.prototype.nextToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + if (this.token().tokenKind === 10 /* EndOfFileToken */) { + return null; + } + + if (includeSkippedTokens) { + var end = this.end(); + var nextToken; + + if (end <= this.parentToken().start()) { + nextToken = TypeScript.Syntax.findSkippedTokenInLeadingTriviaList(this.parentToken(), end); + + if (nextToken) { + return nextToken; + } + + return this.parentToken(); + } else { + nextToken = TypeScript.Syntax.findSkippedTokenInTrailingTriviaList(this.parentToken(), end); + + if (nextToken) { + return nextToken; + } + } + } + + return this.root().node().findToken(this.parentToken().fullEnd(), includeSkippedTokens); + }; + return PositionedSkippedToken; + })(PositionedToken); + TypeScript.PositionedSkippedToken = PositionedSkippedToken; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["None"] = 0] = "None"; + SyntaxKind[SyntaxKind["List"] = 1] = "List"; + SyntaxKind[SyntaxKind["SeparatedList"] = 2] = "SeparatedList"; + SyntaxKind[SyntaxKind["TriviaList"] = 3] = "TriviaList"; + + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 4] = "WhitespaceTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 5] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 6] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 7] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["SkippedTokenTrivia"] = 8] = "SkippedTokenTrivia"; + + SyntaxKind[SyntaxKind["ErrorToken"] = 9] = "ErrorToken"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 10] = "EndOfFileToken"; + + SyntaxKind[SyntaxKind["IdentifierName"] = 11] = "IdentifierName"; + + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 13] = "NumericLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 14] = "StringLiteral"; + + SyntaxKind[SyntaxKind["BreakKeyword"] = 15] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 16] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 17] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 18] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 19] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 20] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 21] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 22] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 23] = "ElseKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 24] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 25] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 26] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 27] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 28] = "IfKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 29] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 30] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 31] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 32] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 33] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 34] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 35] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 36] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 37] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 38] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 39] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 40] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 41] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 42] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 43] = "WithKeyword"; + + SyntaxKind[SyntaxKind["ClassKeyword"] = 44] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 45] = "ConstKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 46] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 47] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 48] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 49] = "ImportKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 50] = "SuperKeyword"; + + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 51] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 52] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 53] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 54] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 55] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 56] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 57] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 58] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 59] = "YieldKeyword"; + + SyntaxKind[SyntaxKind["AnyKeyword"] = 60] = "AnyKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 61] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 62] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 63] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 64] = "GetKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 65] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 66] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 67] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 68] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 69] = "StringKeyword"; + + SyntaxKind[SyntaxKind["OpenBraceToken"] = 70] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 71] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 72] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 73] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 74] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 75] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 76] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 77] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 78] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 79] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 80] = "LessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 81] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 82] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 83] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 84] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 85] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 86] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 87] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 88] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 89] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 90] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 91] = "AsteriskToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 92] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 93] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 94] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 95] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 96] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 97] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 98] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 99] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 100] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 101] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 102] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 103] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 104] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 105] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 106] = "ColonToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 107] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 108] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 109] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 110] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 111] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 112] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 113] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 114] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 115] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 116] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 117] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 118] = "SlashToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 119] = "SlashEqualsToken"; + + SyntaxKind[SyntaxKind["SourceUnit"] = 120] = "SourceUnit"; + + SyntaxKind[SyntaxKind["QualifiedName"] = 121] = "QualifiedName"; + + SyntaxKind[SyntaxKind["ObjectType"] = 122] = "ObjectType"; + SyntaxKind[SyntaxKind["FunctionType"] = 123] = "FunctionType"; + SyntaxKind[SyntaxKind["ArrayType"] = 124] = "ArrayType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 125] = "ConstructorType"; + SyntaxKind[SyntaxKind["GenericType"] = 126] = "GenericType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 127] = "TypeQuery"; + + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 128] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 129] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 130] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 131] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 132] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 133] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 134] = "ExportAssignment"; + + SyntaxKind[SyntaxKind["MemberFunctionDeclaration"] = 135] = "MemberFunctionDeclaration"; + SyntaxKind[SyntaxKind["MemberVariableDeclaration"] = 136] = "MemberVariableDeclaration"; + SyntaxKind[SyntaxKind["ConstructorDeclaration"] = 137] = "ConstructorDeclaration"; + SyntaxKind[SyntaxKind["IndexMemberDeclaration"] = 138] = "IndexMemberDeclaration"; + + SyntaxKind[SyntaxKind["GetAccessor"] = 139] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 140] = "SetAccessor"; + + SyntaxKind[SyntaxKind["PropertySignature"] = 141] = "PropertySignature"; + SyntaxKind[SyntaxKind["CallSignature"] = 142] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 143] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 144] = "IndexSignature"; + SyntaxKind[SyntaxKind["MethodSignature"] = 145] = "MethodSignature"; + + SyntaxKind[SyntaxKind["Block"] = 146] = "Block"; + SyntaxKind[SyntaxKind["IfStatement"] = 147] = "IfStatement"; + SyntaxKind[SyntaxKind["VariableStatement"] = 148] = "VariableStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 149] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 150] = "ReturnStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 151] = "SwitchStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 152] = "BreakStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 153] = "ContinueStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 154] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 155] = "ForInStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 156] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 157] = "ThrowStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 158] = "WhileStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 159] = "TryStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 160] = "LabeledStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 161] = "DoStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 162] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 163] = "WithStatement"; + + SyntaxKind[SyntaxKind["PlusExpression"] = 164] = "PlusExpression"; + SyntaxKind[SyntaxKind["NegateExpression"] = 165] = "NegateExpression"; + SyntaxKind[SyntaxKind["BitwiseNotExpression"] = 166] = "BitwiseNotExpression"; + SyntaxKind[SyntaxKind["LogicalNotExpression"] = 167] = "LogicalNotExpression"; + SyntaxKind[SyntaxKind["PreIncrementExpression"] = 168] = "PreIncrementExpression"; + SyntaxKind[SyntaxKind["PreDecrementExpression"] = 169] = "PreDecrementExpression"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 170] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 171] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 172] = "VoidExpression"; + SyntaxKind[SyntaxKind["CommaExpression"] = 173] = "CommaExpression"; + SyntaxKind[SyntaxKind["AssignmentExpression"] = 174] = "AssignmentExpression"; + SyntaxKind[SyntaxKind["AddAssignmentExpression"] = 175] = "AddAssignmentExpression"; + SyntaxKind[SyntaxKind["SubtractAssignmentExpression"] = 176] = "SubtractAssignmentExpression"; + SyntaxKind[SyntaxKind["MultiplyAssignmentExpression"] = 177] = "MultiplyAssignmentExpression"; + SyntaxKind[SyntaxKind["DivideAssignmentExpression"] = 178] = "DivideAssignmentExpression"; + SyntaxKind[SyntaxKind["ModuloAssignmentExpression"] = 179] = "ModuloAssignmentExpression"; + SyntaxKind[SyntaxKind["AndAssignmentExpression"] = 180] = "AndAssignmentExpression"; + SyntaxKind[SyntaxKind["ExclusiveOrAssignmentExpression"] = 181] = "ExclusiveOrAssignmentExpression"; + SyntaxKind[SyntaxKind["OrAssignmentExpression"] = 182] = "OrAssignmentExpression"; + SyntaxKind[SyntaxKind["LeftShiftAssignmentExpression"] = 183] = "LeftShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["SignedRightShiftAssignmentExpression"] = 184] = "SignedRightShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["UnsignedRightShiftAssignmentExpression"] = 185] = "UnsignedRightShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 186] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["LogicalOrExpression"] = 187] = "LogicalOrExpression"; + SyntaxKind[SyntaxKind["LogicalAndExpression"] = 188] = "LogicalAndExpression"; + SyntaxKind[SyntaxKind["BitwiseOrExpression"] = 189] = "BitwiseOrExpression"; + SyntaxKind[SyntaxKind["BitwiseExclusiveOrExpression"] = 190] = "BitwiseExclusiveOrExpression"; + SyntaxKind[SyntaxKind["BitwiseAndExpression"] = 191] = "BitwiseAndExpression"; + SyntaxKind[SyntaxKind["EqualsWithTypeConversionExpression"] = 192] = "EqualsWithTypeConversionExpression"; + SyntaxKind[SyntaxKind["NotEqualsWithTypeConversionExpression"] = 193] = "NotEqualsWithTypeConversionExpression"; + SyntaxKind[SyntaxKind["EqualsExpression"] = 194] = "EqualsExpression"; + SyntaxKind[SyntaxKind["NotEqualsExpression"] = 195] = "NotEqualsExpression"; + SyntaxKind[SyntaxKind["LessThanExpression"] = 196] = "LessThanExpression"; + SyntaxKind[SyntaxKind["GreaterThanExpression"] = 197] = "GreaterThanExpression"; + SyntaxKind[SyntaxKind["LessThanOrEqualExpression"] = 198] = "LessThanOrEqualExpression"; + SyntaxKind[SyntaxKind["GreaterThanOrEqualExpression"] = 199] = "GreaterThanOrEqualExpression"; + SyntaxKind[SyntaxKind["InstanceOfExpression"] = 200] = "InstanceOfExpression"; + SyntaxKind[SyntaxKind["InExpression"] = 201] = "InExpression"; + SyntaxKind[SyntaxKind["LeftShiftExpression"] = 202] = "LeftShiftExpression"; + SyntaxKind[SyntaxKind["SignedRightShiftExpression"] = 203] = "SignedRightShiftExpression"; + SyntaxKind[SyntaxKind["UnsignedRightShiftExpression"] = 204] = "UnsignedRightShiftExpression"; + SyntaxKind[SyntaxKind["MultiplyExpression"] = 205] = "MultiplyExpression"; + SyntaxKind[SyntaxKind["DivideExpression"] = 206] = "DivideExpression"; + SyntaxKind[SyntaxKind["ModuloExpression"] = 207] = "ModuloExpression"; + SyntaxKind[SyntaxKind["AddExpression"] = 208] = "AddExpression"; + SyntaxKind[SyntaxKind["SubtractExpression"] = 209] = "SubtractExpression"; + SyntaxKind[SyntaxKind["PostIncrementExpression"] = 210] = "PostIncrementExpression"; + SyntaxKind[SyntaxKind["PostDecrementExpression"] = 211] = "PostDecrementExpression"; + SyntaxKind[SyntaxKind["MemberAccessExpression"] = 212] = "MemberAccessExpression"; + SyntaxKind[SyntaxKind["InvocationExpression"] = 213] = "InvocationExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 214] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 215] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectCreationExpression"] = 216] = "ObjectCreationExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 217] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["ParenthesizedArrowFunctionExpression"] = 218] = "ParenthesizedArrowFunctionExpression"; + SyntaxKind[SyntaxKind["SimpleArrowFunctionExpression"] = 219] = "SimpleArrowFunctionExpression"; + SyntaxKind[SyntaxKind["CastExpression"] = 220] = "CastExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 221] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 222] = "FunctionExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 223] = "OmittedExpression"; + + SyntaxKind[SyntaxKind["VariableDeclaration"] = 224] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarator"] = 225] = "VariableDeclarator"; + + SyntaxKind[SyntaxKind["ArgumentList"] = 226] = "ArgumentList"; + SyntaxKind[SyntaxKind["ParameterList"] = 227] = "ParameterList"; + SyntaxKind[SyntaxKind["TypeArgumentList"] = 228] = "TypeArgumentList"; + SyntaxKind[SyntaxKind["TypeParameterList"] = 229] = "TypeParameterList"; + + SyntaxKind[SyntaxKind["ExtendsHeritageClause"] = 230] = "ExtendsHeritageClause"; + SyntaxKind[SyntaxKind["ImplementsHeritageClause"] = 231] = "ImplementsHeritageClause"; + SyntaxKind[SyntaxKind["EqualsValueClause"] = 232] = "EqualsValueClause"; + SyntaxKind[SyntaxKind["CaseSwitchClause"] = 233] = "CaseSwitchClause"; + SyntaxKind[SyntaxKind["DefaultSwitchClause"] = 234] = "DefaultSwitchClause"; + SyntaxKind[SyntaxKind["ElseClause"] = 235] = "ElseClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 236] = "CatchClause"; + SyntaxKind[SyntaxKind["FinallyClause"] = 237] = "FinallyClause"; + + SyntaxKind[SyntaxKind["TypeParameter"] = 238] = "TypeParameter"; + SyntaxKind[SyntaxKind["Constraint"] = 239] = "Constraint"; + + SyntaxKind[SyntaxKind["SimplePropertyAssignment"] = 240] = "SimplePropertyAssignment"; + + SyntaxKind[SyntaxKind["FunctionPropertyAssignment"] = 241] = "FunctionPropertyAssignment"; + + SyntaxKind[SyntaxKind["Parameter"] = 242] = "Parameter"; + SyntaxKind[SyntaxKind["EnumElement"] = 243] = "EnumElement"; + SyntaxKind[SyntaxKind["TypeAnnotation"] = 244] = "TypeAnnotation"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 245] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ModuleNameModuleReference"] = 246] = "ModuleNameModuleReference"; + SyntaxKind[SyntaxKind["Last"] = SyntaxKind.ModuleNameModuleReference] = "Last"; + + SyntaxKind[SyntaxKind["FirstStandardKeyword"] = SyntaxKind.BreakKeyword] = "FirstStandardKeyword"; + SyntaxKind[SyntaxKind["LastStandardKeyword"] = SyntaxKind.WithKeyword] = "LastStandardKeyword"; + + SyntaxKind[SyntaxKind["FirstFutureReservedKeyword"] = SyntaxKind.ClassKeyword] = "FirstFutureReservedKeyword"; + SyntaxKind[SyntaxKind["LastFutureReservedKeyword"] = SyntaxKind.SuperKeyword] = "LastFutureReservedKeyword"; + + SyntaxKind[SyntaxKind["FirstFutureReservedStrictKeyword"] = SyntaxKind.ImplementsKeyword] = "FirstFutureReservedStrictKeyword"; + SyntaxKind[SyntaxKind["LastFutureReservedStrictKeyword"] = SyntaxKind.YieldKeyword] = "LastFutureReservedStrictKeyword"; + + SyntaxKind[SyntaxKind["FirstTypeScriptKeyword"] = SyntaxKind.AnyKeyword] = "FirstTypeScriptKeyword"; + SyntaxKind[SyntaxKind["LastTypeScriptKeyword"] = SyntaxKind.StringKeyword] = "LastTypeScriptKeyword"; + + SyntaxKind[SyntaxKind["FirstKeyword"] = SyntaxKind.FirstStandardKeyword] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = SyntaxKind.LastTypeScriptKeyword] = "LastKeyword"; + + SyntaxKind[SyntaxKind["FirstToken"] = SyntaxKind.ErrorToken] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = SyntaxKind.SlashEqualsToken] = "LastToken"; + + SyntaxKind[SyntaxKind["FirstPunctuation"] = SyntaxKind.OpenBraceToken] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = SyntaxKind.SlashEqualsToken] = "LastPunctuation"; + + SyntaxKind[SyntaxKind["FirstFixedWidth"] = SyntaxKind.FirstKeyword] = "FirstFixedWidth"; + SyntaxKind[SyntaxKind["LastFixedWidth"] = SyntaxKind.LastPunctuation] = "LastFixedWidth"; + + SyntaxKind[SyntaxKind["FirstTrivia"] = SyntaxKind.WhitespaceTrivia] = "FirstTrivia"; + SyntaxKind[SyntaxKind["LastTrivia"] = SyntaxKind.SkippedTokenTrivia] = "LastTrivia"; + })(TypeScript.SyntaxKind || (TypeScript.SyntaxKind = {})); + var SyntaxKind = TypeScript.SyntaxKind; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxFacts) { + var textToKeywordKind = { + "any": 60 /* AnyKeyword */, + "boolean": 61 /* BooleanKeyword */, + "break": 15 /* BreakKeyword */, + "case": 16 /* CaseKeyword */, + "catch": 17 /* CatchKeyword */, + "class": 44 /* ClassKeyword */, + "continue": 18 /* ContinueKeyword */, + "const": 45 /* ConstKeyword */, + "constructor": 62 /* ConstructorKeyword */, + "debugger": 19 /* DebuggerKeyword */, + "declare": 63 /* DeclareKeyword */, + "default": 20 /* DefaultKeyword */, + "delete": 21 /* DeleteKeyword */, + "do": 22 /* DoKeyword */, + "else": 23 /* ElseKeyword */, + "enum": 46 /* EnumKeyword */, + "export": 47 /* ExportKeyword */, + "extends": 48 /* ExtendsKeyword */, + "false": 24 /* FalseKeyword */, + "finally": 25 /* FinallyKeyword */, + "for": 26 /* ForKeyword */, + "function": 27 /* FunctionKeyword */, + "get": 64 /* GetKeyword */, + "if": 28 /* IfKeyword */, + "implements": 51 /* ImplementsKeyword */, + "import": 49 /* ImportKeyword */, + "in": 29 /* InKeyword */, + "instanceof": 30 /* InstanceOfKeyword */, + "interface": 52 /* InterfaceKeyword */, + "let": 53 /* LetKeyword */, + "module": 65 /* ModuleKeyword */, + "new": 31 /* NewKeyword */, + "null": 32 /* NullKeyword */, + "number": 67 /* NumberKeyword */, + "package": 54 /* PackageKeyword */, + "private": 55 /* PrivateKeyword */, + "protected": 56 /* ProtectedKeyword */, + "public": 57 /* PublicKeyword */, + "require": 66 /* RequireKeyword */, + "return": 33 /* ReturnKeyword */, + "set": 68 /* SetKeyword */, + "static": 58 /* StaticKeyword */, + "string": 69 /* StringKeyword */, + "super": 50 /* SuperKeyword */, + "switch": 34 /* SwitchKeyword */, + "this": 35 /* ThisKeyword */, + "throw": 36 /* ThrowKeyword */, + "true": 37 /* TrueKeyword */, + "try": 38 /* TryKeyword */, + "typeof": 39 /* TypeOfKeyword */, + "var": 40 /* VarKeyword */, + "void": 41 /* VoidKeyword */, + "while": 42 /* WhileKeyword */, + "with": 43 /* WithKeyword */, + "yield": 59 /* YieldKeyword */, + "{": 70 /* OpenBraceToken */, + "}": 71 /* CloseBraceToken */, + "(": 72 /* OpenParenToken */, + ")": 73 /* CloseParenToken */, + "[": 74 /* OpenBracketToken */, + "]": 75 /* CloseBracketToken */, + ".": 76 /* DotToken */, + "...": 77 /* DotDotDotToken */, + ";": 78 /* SemicolonToken */, + ",": 79 /* CommaToken */, + "<": 80 /* LessThanToken */, + ">": 81 /* GreaterThanToken */, + "<=": 82 /* LessThanEqualsToken */, + ">=": 83 /* GreaterThanEqualsToken */, + "==": 84 /* EqualsEqualsToken */, + "=>": 85 /* EqualsGreaterThanToken */, + "!=": 86 /* ExclamationEqualsToken */, + "===": 87 /* EqualsEqualsEqualsToken */, + "!==": 88 /* ExclamationEqualsEqualsToken */, + "+": 89 /* PlusToken */, + "-": 90 /* MinusToken */, + "*": 91 /* AsteriskToken */, + "%": 92 /* PercentToken */, + "++": 93 /* PlusPlusToken */, + "--": 94 /* MinusMinusToken */, + "<<": 95 /* LessThanLessThanToken */, + ">>": 96 /* GreaterThanGreaterThanToken */, + ">>>": 97 /* GreaterThanGreaterThanGreaterThanToken */, + "&": 98 /* AmpersandToken */, + "|": 99 /* BarToken */, + "^": 100 /* CaretToken */, + "!": 101 /* ExclamationToken */, + "~": 102 /* TildeToken */, + "&&": 103 /* AmpersandAmpersandToken */, + "||": 104 /* BarBarToken */, + "?": 105 /* QuestionToken */, + ":": 106 /* ColonToken */, + "=": 107 /* EqualsToken */, + "+=": 108 /* PlusEqualsToken */, + "-=": 109 /* MinusEqualsToken */, + "*=": 110 /* AsteriskEqualsToken */, + "%=": 111 /* PercentEqualsToken */, + "<<=": 112 /* LessThanLessThanEqualsToken */, + ">>=": 113 /* GreaterThanGreaterThanEqualsToken */, + ">>>=": 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */, + "&=": 115 /* AmpersandEqualsToken */, + "|=": 116 /* BarEqualsToken */, + "^=": 117 /* CaretEqualsToken */, + "/": 118 /* SlashToken */, + "/=": 119 /* SlashEqualsToken */ + }; + + var kindToText = new Array(); + + for (var name in textToKeywordKind) { + if (textToKeywordKind.hasOwnProperty(name)) { + kindToText[textToKeywordKind[name]] = name; + } + } + + kindToText[62 /* ConstructorKeyword */] = "constructor"; + + function getTokenKind(text) { + if (textToKeywordKind.hasOwnProperty(text)) { + return textToKeywordKind[text]; + } + + return 0 /* None */; + } + SyntaxFacts.getTokenKind = getTokenKind; + + function getText(kind) { + var result = kindToText[kind]; + return result !== undefined ? result : null; + } + SyntaxFacts.getText = getText; + + function isTokenKind(kind) { + return kind >= 9 /* FirstToken */ && kind <= 119 /* LastToken */; + } + SyntaxFacts.isTokenKind = isTokenKind; + + function isAnyKeyword(kind) { + return kind >= 15 /* FirstKeyword */ && kind <= 69 /* LastKeyword */; + } + SyntaxFacts.isAnyKeyword = isAnyKeyword; + + function isStandardKeyword(kind) { + return kind >= 15 /* FirstStandardKeyword */ && kind <= 43 /* LastStandardKeyword */; + } + SyntaxFacts.isStandardKeyword = isStandardKeyword; + + function isFutureReservedKeyword(kind) { + return kind >= 44 /* FirstFutureReservedKeyword */ && kind <= 50 /* LastFutureReservedKeyword */; + } + SyntaxFacts.isFutureReservedKeyword = isFutureReservedKeyword; + + function isFutureReservedStrictKeyword(kind) { + return kind >= 51 /* FirstFutureReservedStrictKeyword */ && kind <= 59 /* LastFutureReservedStrictKeyword */; + } + SyntaxFacts.isFutureReservedStrictKeyword = isFutureReservedStrictKeyword; + + function isAnyPunctuation(kind) { + return kind >= 70 /* FirstPunctuation */ && kind <= 119 /* LastPunctuation */; + } + SyntaxFacts.isAnyPunctuation = isAnyPunctuation; + + function isPrefixUnaryExpressionOperatorToken(tokenKind) { + return getPrefixUnaryExpressionFromOperatorToken(tokenKind) !== 0 /* None */; + } + SyntaxFacts.isPrefixUnaryExpressionOperatorToken = isPrefixUnaryExpressionOperatorToken; + + function isBinaryExpressionOperatorToken(tokenKind) { + return getBinaryExpressionFromOperatorToken(tokenKind) !== 0 /* None */; + } + SyntaxFacts.isBinaryExpressionOperatorToken = isBinaryExpressionOperatorToken; + + function getPrefixUnaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 89 /* PlusToken */: + return 164 /* PlusExpression */; + case 90 /* MinusToken */: + return 165 /* NegateExpression */; + case 102 /* TildeToken */: + return 166 /* BitwiseNotExpression */; + case 101 /* ExclamationToken */: + return 167 /* LogicalNotExpression */; + case 93 /* PlusPlusToken */: + return 168 /* PreIncrementExpression */; + case 94 /* MinusMinusToken */: + return 169 /* PreDecrementExpression */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getPrefixUnaryExpressionFromOperatorToken = getPrefixUnaryExpressionFromOperatorToken; + + function getPostfixUnaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 93 /* PlusPlusToken */: + return 210 /* PostIncrementExpression */; + case 94 /* MinusMinusToken */: + return 211 /* PostDecrementExpression */; + default: + return 0 /* None */; + } + } + SyntaxFacts.getPostfixUnaryExpressionFromOperatorToken = getPostfixUnaryExpressionFromOperatorToken; + + function getBinaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 91 /* AsteriskToken */: + return 205 /* MultiplyExpression */; + + case 118 /* SlashToken */: + return 206 /* DivideExpression */; + + case 92 /* PercentToken */: + return 207 /* ModuloExpression */; + + case 89 /* PlusToken */: + return 208 /* AddExpression */; + + case 90 /* MinusToken */: + return 209 /* SubtractExpression */; + + case 95 /* LessThanLessThanToken */: + return 202 /* LeftShiftExpression */; + + case 96 /* GreaterThanGreaterThanToken */: + return 203 /* SignedRightShiftExpression */; + + case 97 /* GreaterThanGreaterThanGreaterThanToken */: + return 204 /* UnsignedRightShiftExpression */; + + case 80 /* LessThanToken */: + return 196 /* LessThanExpression */; + + case 81 /* GreaterThanToken */: + return 197 /* GreaterThanExpression */; + + case 82 /* LessThanEqualsToken */: + return 198 /* LessThanOrEqualExpression */; + + case 83 /* GreaterThanEqualsToken */: + return 199 /* GreaterThanOrEqualExpression */; + + case 30 /* InstanceOfKeyword */: + return 200 /* InstanceOfExpression */; + + case 29 /* InKeyword */: + return 201 /* InExpression */; + + case 84 /* EqualsEqualsToken */: + return 192 /* EqualsWithTypeConversionExpression */; + + case 86 /* ExclamationEqualsToken */: + return 193 /* NotEqualsWithTypeConversionExpression */; + + case 87 /* EqualsEqualsEqualsToken */: + return 194 /* EqualsExpression */; + + case 88 /* ExclamationEqualsEqualsToken */: + return 195 /* NotEqualsExpression */; + + case 98 /* AmpersandToken */: + return 191 /* BitwiseAndExpression */; + + case 100 /* CaretToken */: + return 190 /* BitwiseExclusiveOrExpression */; + + case 99 /* BarToken */: + return 189 /* BitwiseOrExpression */; + + case 103 /* AmpersandAmpersandToken */: + return 188 /* LogicalAndExpression */; + + case 104 /* BarBarToken */: + return 187 /* LogicalOrExpression */; + + case 116 /* BarEqualsToken */: + return 182 /* OrAssignmentExpression */; + + case 115 /* AmpersandEqualsToken */: + return 180 /* AndAssignmentExpression */; + + case 117 /* CaretEqualsToken */: + return 181 /* ExclusiveOrAssignmentExpression */; + + case 112 /* LessThanLessThanEqualsToken */: + return 183 /* LeftShiftAssignmentExpression */; + + case 113 /* GreaterThanGreaterThanEqualsToken */: + return 184 /* SignedRightShiftAssignmentExpression */; + + case 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + return 185 /* UnsignedRightShiftAssignmentExpression */; + + case 108 /* PlusEqualsToken */: + return 175 /* AddAssignmentExpression */; + + case 109 /* MinusEqualsToken */: + return 176 /* SubtractAssignmentExpression */; + + case 110 /* AsteriskEqualsToken */: + return 177 /* MultiplyAssignmentExpression */; + + case 119 /* SlashEqualsToken */: + return 178 /* DivideAssignmentExpression */; + + case 111 /* PercentEqualsToken */: + return 179 /* ModuloAssignmentExpression */; + + case 107 /* EqualsToken */: + return 174 /* AssignmentExpression */; + + case 79 /* CommaToken */: + return 173 /* CommaExpression */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getBinaryExpressionFromOperatorToken = getBinaryExpressionFromOperatorToken; + + function getOperatorTokenFromBinaryExpression(tokenKind) { + switch (tokenKind) { + case 205 /* MultiplyExpression */: + return 91 /* AsteriskToken */; + + case 206 /* DivideExpression */: + return 118 /* SlashToken */; + + case 207 /* ModuloExpression */: + return 92 /* PercentToken */; + + case 208 /* AddExpression */: + return 89 /* PlusToken */; + + case 209 /* SubtractExpression */: + return 90 /* MinusToken */; + + case 202 /* LeftShiftExpression */: + return 95 /* LessThanLessThanToken */; + + case 203 /* SignedRightShiftExpression */: + return 96 /* GreaterThanGreaterThanToken */; + + case 204 /* UnsignedRightShiftExpression */: + return 97 /* GreaterThanGreaterThanGreaterThanToken */; + + case 196 /* LessThanExpression */: + return 80 /* LessThanToken */; + + case 197 /* GreaterThanExpression */: + return 81 /* GreaterThanToken */; + + case 198 /* LessThanOrEqualExpression */: + return 82 /* LessThanEqualsToken */; + + case 199 /* GreaterThanOrEqualExpression */: + return 83 /* GreaterThanEqualsToken */; + + case 200 /* InstanceOfExpression */: + return 30 /* InstanceOfKeyword */; + + case 201 /* InExpression */: + return 29 /* InKeyword */; + + case 192 /* EqualsWithTypeConversionExpression */: + return 84 /* EqualsEqualsToken */; + + case 193 /* NotEqualsWithTypeConversionExpression */: + return 86 /* ExclamationEqualsToken */; + + case 194 /* EqualsExpression */: + return 87 /* EqualsEqualsEqualsToken */; + + case 195 /* NotEqualsExpression */: + return 88 /* ExclamationEqualsEqualsToken */; + + case 191 /* BitwiseAndExpression */: + return 98 /* AmpersandToken */; + + case 190 /* BitwiseExclusiveOrExpression */: + return 100 /* CaretToken */; + + case 189 /* BitwiseOrExpression */: + return 99 /* BarToken */; + + case 188 /* LogicalAndExpression */: + return 103 /* AmpersandAmpersandToken */; + + case 187 /* LogicalOrExpression */: + return 104 /* BarBarToken */; + + case 182 /* OrAssignmentExpression */: + return 116 /* BarEqualsToken */; + + case 180 /* AndAssignmentExpression */: + return 115 /* AmpersandEqualsToken */; + + case 181 /* ExclusiveOrAssignmentExpression */: + return 117 /* CaretEqualsToken */; + + case 183 /* LeftShiftAssignmentExpression */: + return 112 /* LessThanLessThanEqualsToken */; + + case 184 /* SignedRightShiftAssignmentExpression */: + return 113 /* GreaterThanGreaterThanEqualsToken */; + + case 185 /* UnsignedRightShiftAssignmentExpression */: + return 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + + case 175 /* AddAssignmentExpression */: + return 108 /* PlusEqualsToken */; + + case 176 /* SubtractAssignmentExpression */: + return 109 /* MinusEqualsToken */; + + case 177 /* MultiplyAssignmentExpression */: + return 110 /* AsteriskEqualsToken */; + + case 178 /* DivideAssignmentExpression */: + return 119 /* SlashEqualsToken */; + + case 179 /* ModuloAssignmentExpression */: + return 111 /* PercentEqualsToken */; + + case 174 /* AssignmentExpression */: + return 107 /* EqualsToken */; + + case 173 /* CommaExpression */: + return 79 /* CommaToken */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getOperatorTokenFromBinaryExpression = getOperatorTokenFromBinaryExpression; + + function isAnyDivideToken(kind) { + switch (kind) { + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + return true; + default: + return false; + } + } + SyntaxFacts.isAnyDivideToken = isAnyDivideToken; + + function isAnyDivideOrRegularExpressionToken(kind) { + switch (kind) { + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + case 12 /* RegularExpressionLiteral */: + return true; + default: + return false; + } + } + SyntaxFacts.isAnyDivideOrRegularExpressionToken = isAnyDivideOrRegularExpressionToken; + })(TypeScript.SyntaxFacts || (TypeScript.SyntaxFacts = {})); + var SyntaxFacts = TypeScript.SyntaxFacts; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var isKeywordStartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + var isIdentifierStartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + var isIdentifierPartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + var isNumericLiteralStart = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + + for (var character = 0; character < 127 /* maxAsciiCharacter */; character++) { + if (character >= 97 /* a */ && character <= 122 /* z */) { + isIdentifierStartCharacter[character] = true; + isIdentifierPartCharacter[character] = true; + } else if ((character >= 65 /* A */ && character <= 90 /* Z */) || character === 95 /* _ */ || character === 36 /* $ */) { + isIdentifierStartCharacter[character] = true; + isIdentifierPartCharacter[character] = true; + } else if (character >= 48 /* _0 */ && character <= 57 /* _9 */) { + isIdentifierPartCharacter[character] = true; + isNumericLiteralStart[character] = true; + } + } + + isNumericLiteralStart[46 /* dot */] = true; + + for (var keywordKind = 15 /* FirstKeyword */; keywordKind <= 69 /* LastKeyword */; keywordKind++) { + var keyword = TypeScript.SyntaxFacts.getText(keywordKind); + isKeywordStartCharacter[keyword.charCodeAt(0)] = true; + } + + var Scanner = (function () { + function Scanner(fileName, text, languageVersion, window) { + if (typeof window === "undefined") { window = TypeScript.ArrayUtilities.createArray(2048, 0); } + this.slidingWindow = new TypeScript.SlidingWindow(this, window, 0, text.length()); + this.fileName = fileName; + this.text = text; + this._languageVersion = languageVersion; + } + Scanner.prototype.languageVersion = function () { + return this._languageVersion; + }; + + Scanner.prototype.fetchMoreItems = function (argument, sourceIndex, window, destinationIndex, spaceAvailable) { + var charactersRemaining = this.text.length() - sourceIndex; + var amountToRead = TypeScript.MathPrototype.min(charactersRemaining, spaceAvailable); + this.text.copyTo(sourceIndex, window, destinationIndex, amountToRead); + return amountToRead; + }; + + Scanner.prototype.currentCharCode = function () { + return this.slidingWindow.currentItem(null); + }; + + Scanner.prototype.absoluteIndex = function () { + return this.slidingWindow.absoluteIndex(); + }; + + Scanner.prototype.setAbsoluteIndex = function (index) { + this.slidingWindow.setAbsoluteIndex(index); + }; + + Scanner.prototype.scan = function (diagnostics, allowRegularExpression) { + var diagnosticsLength = diagnostics.length; + var fullStart = this.slidingWindow.absoluteIndex(); + var leadingTriviaInfo = this.scanTriviaInfo(diagnostics, false); + + var start = this.slidingWindow.absoluteIndex(); + var kindAndFlags = this.scanSyntaxToken(diagnostics, allowRegularExpression); + var end = this.slidingWindow.absoluteIndex(); + + var trailingTriviaInfo = this.scanTriviaInfo(diagnostics, true); + var fullEnd = this.slidingWindow.absoluteIndex(); + + var isVariableWidthKeyword = (kindAndFlags & -2147483648 /* IsVariableWidthKeyword */) !== 0; + var kind = kindAndFlags & ~-2147483648 /* IsVariableWidthKeyword */; + + var token = this.createToken(fullStart, leadingTriviaInfo, start, kind, end, fullEnd, trailingTriviaInfo, isVariableWidthKeyword); + + return diagnosticsLength !== diagnostics.length ? TypeScript.Syntax.realizeToken(token) : token; + }; + + Scanner.prototype.createToken = function (fullStart, leadingTriviaInfo, start, kind, end, fullEnd, trailingTriviaInfo, isVariableWidthKeyword) { + if (!isVariableWidthKeyword && kind >= 15 /* FirstFixedWidth */) { + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.FixedWidthTokenWithNoTrivia(kind); + } else { + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo); + } else { + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo); + } + } else { + var width = end - start; + + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.VariableWidthTokenWithNoTrivia(fullText, kind); + } else { + return new TypeScript.Syntax.VariableWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.VariableWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo); + } else { + return new TypeScript.Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo); + } + } + }; + + Scanner.scanTrivia = function (text, start, length, isTrailing) { + var scanner = new Scanner(null, text.subText(new TypeScript.TextSpan(start, length)), 1 /* EcmaScript5 */, Scanner.triviaWindow); + return scanner.scanTrivia(text, start, isTrailing); + }; + + Scanner.prototype.scanTrivia = function (underlyingText, underlyingTextStart, isTrailing) { + var trivia = new Array(); + + while (true) { + if (!this.slidingWindow.isAtEndOfSource()) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + trivia.push(this.scanWhitespaceTrivia(underlyingText, underlyingTextStart)); + continue; + + case 47 /* slash */: + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 47 /* slash */) { + trivia.push(this.scanSingleLineCommentTrivia(underlyingText, underlyingTextStart)); + continue; + } + + if (ch2 === 42 /* asterisk */) { + trivia.push(this.scanMultiLineCommentTrivia(underlyingText, underlyingTextStart)); + continue; + } + + throw TypeScript.Errors.invalidOperation(); + + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + trivia.push(this.scanLineTerminatorSequenceTrivia(ch)); + + if (!isTrailing) { + continue; + } + + break; + + default: + throw TypeScript.Errors.invalidOperation(); + } + } + + return TypeScript.Syntax.triviaList(trivia); + } + }; + + Scanner.prototype.scanTriviaInfo = function (diagnostics, isTrailing) { + var width = 0; + var hasCommentOrNewLine = 0; + + while (true) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + this.slidingWindow.moveToNextItem(); + width++; + continue; + + case 47 /* slash */: + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 47 /* slash */) { + hasCommentOrNewLine |= 2 /* TriviaCommentMask */; + width += this.scanSingleLineCommentTriviaLength(); + continue; + } + + if (ch2 === 42 /* asterisk */) { + hasCommentOrNewLine |= 2 /* TriviaCommentMask */; + width += this.scanMultiLineCommentTriviaLength(diagnostics); + continue; + } + + break; + + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + hasCommentOrNewLine |= 1 /* TriviaNewLineMask */; + width += this.scanLineTerminatorSequenceLength(ch); + + if (!isTrailing) { + continue; + } + + break; + } + + return (width << 2 /* TriviaFullWidthShift */) | hasCommentOrNewLine; + } + }; + + Scanner.prototype.isNewLineCharacter = function (ch) { + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + return true; + default: + return false; + } + }; + + Scanner.prototype.scanWhitespaceTrivia = function (underlyingText, underlyingTextStart) { + var absoluteStartIndex = this.absoluteIndex(); + + var width = 0; + while (true) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + this.slidingWindow.moveToNextItem(); + width++; + continue; + } + + break; + } + + return TypeScript.Syntax.deferredTrivia(4 /* WhitespaceTrivia */, underlyingText, underlyingTextStart + absoluteStartIndex, width); + }; + + Scanner.prototype.scanSingleLineCommentTrivia = function (underlyingText, underlyingTextStart) { + var absoluteStartIndex = this.slidingWindow.absoluteIndex(); + var width = this.scanSingleLineCommentTriviaLength(); + + return TypeScript.Syntax.deferredTrivia(7 /* SingleLineCommentTrivia */, underlyingText, underlyingTextStart + absoluteStartIndex, width); + }; + + Scanner.prototype.scanSingleLineCommentTriviaLength = function () { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + var width = 2; + while (true) { + if (this.slidingWindow.isAtEndOfSource() || this.isNewLineCharacter(this.currentCharCode())) { + return width; + } + + this.slidingWindow.moveToNextItem(); + width++; + } + }; + + Scanner.prototype.scanMultiLineCommentTrivia = function (underlyingText, underlyingTextStart) { + var absoluteStartIndex = this.absoluteIndex(); + var width = this.scanMultiLineCommentTriviaLength(null); + + return TypeScript.Syntax.deferredTrivia(6 /* MultiLineCommentTrivia */, underlyingText, underlyingTextStart + absoluteStartIndex, width); + }; + + Scanner.prototype.scanMultiLineCommentTriviaLength = function (diagnostics) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + var width = 2; + while (true) { + if (this.slidingWindow.isAtEndOfSource()) { + if (diagnostics !== null) { + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), this.slidingWindow.absoluteIndex(), 0, TypeScript.DiagnosticCode.AsteriskSlash_expected, null)); + } + + return width; + } + + var ch = this.currentCharCode(); + if (ch === 42 /* asterisk */ && this.slidingWindow.peekItemN(1) === 47 /* slash */) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + width += 2; + return width; + } + + this.slidingWindow.moveToNextItem(); + width++; + } + }; + + Scanner.prototype.scanLineTerminatorSequenceTrivia = function (ch) { + var absoluteStartIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + var width = this.scanLineTerminatorSequenceLength(ch); + + var text = this.substring(absoluteStartIndex, absoluteStartIndex + width, false); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(absoluteStartIndex); + + return TypeScript.Syntax.trivia(5 /* NewLineTrivia */, text); + }; + + Scanner.prototype.scanLineTerminatorSequenceLength = function (ch) { + this.slidingWindow.moveToNextItem(); + + if (ch === 13 /* carriageReturn */ && this.currentCharCode() === 10 /* lineFeed */) { + this.slidingWindow.moveToNextItem(); + return 2; + } else { + return 1; + } + }; + + Scanner.prototype.scanSyntaxToken = function (diagnostics, allowRegularExpression) { + if (this.slidingWindow.isAtEndOfSource()) { + return 10 /* EndOfFileToken */; + } + + var character = this.currentCharCode(); + + switch (character) { + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + return this.scanStringLiteral(diagnostics); + + case 47 /* slash */: + return this.scanSlashToken(allowRegularExpression); + + case 46 /* dot */: + return this.scanDotToken(diagnostics); + + case 45 /* minus */: + return this.scanMinusToken(); + + case 33 /* exclamation */: + return this.scanExclamationToken(); + + case 61 /* equals */: + return this.scanEqualsToken(); + + case 124 /* bar */: + return this.scanBarToken(); + + case 42 /* asterisk */: + return this.scanAsteriskToken(); + + case 43 /* plus */: + return this.scanPlusToken(); + + case 37 /* percent */: + return this.scanPercentToken(); + + case 38 /* ampersand */: + return this.scanAmpersandToken(); + + case 94 /* caret */: + return this.scanCaretToken(); + + case 60 /* lessThan */: + return this.scanLessThanToken(); + + case 62 /* greaterThan */: + return this.advanceAndSetTokenKind(81 /* GreaterThanToken */); + + case 44 /* comma */: + return this.advanceAndSetTokenKind(79 /* CommaToken */); + + case 58 /* colon */: + return this.advanceAndSetTokenKind(106 /* ColonToken */); + + case 59 /* semicolon */: + return this.advanceAndSetTokenKind(78 /* SemicolonToken */); + + case 126 /* tilde */: + return this.advanceAndSetTokenKind(102 /* TildeToken */); + + case 40 /* openParen */: + return this.advanceAndSetTokenKind(72 /* OpenParenToken */); + + case 41 /* closeParen */: + return this.advanceAndSetTokenKind(73 /* CloseParenToken */); + + case 123 /* openBrace */: + return this.advanceAndSetTokenKind(70 /* OpenBraceToken */); + + case 125 /* closeBrace */: + return this.advanceAndSetTokenKind(71 /* CloseBraceToken */); + + case 91 /* openBracket */: + return this.advanceAndSetTokenKind(74 /* OpenBracketToken */); + + case 93 /* closeBracket */: + return this.advanceAndSetTokenKind(75 /* CloseBracketToken */); + + case 63 /* question */: + return this.advanceAndSetTokenKind(105 /* QuestionToken */); + } + + if (isNumericLiteralStart[character]) { + return this.scanNumericLiteral(diagnostics); + } + + if (isIdentifierStartCharacter[character]) { + var result = this.tryFastScanIdentifierOrKeyword(character); + if (result !== 0 /* None */) { + return result; + } + } + + if (this.isIdentifierStart(this.peekCharOrUnicodeEscape())) { + return this.slowScanIdentifierOrKeyword(diagnostics); + } + + return this.scanDefaultCharacter(character, diagnostics); + }; + + Scanner.prototype.isIdentifierStart = function (interpretedChar) { + if (isIdentifierStartCharacter[interpretedChar]) { + return true; + } + + return interpretedChar > 127 /* maxAsciiCharacter */ && TypeScript.Unicode.isIdentifierStart(interpretedChar, this._languageVersion); + }; + + Scanner.prototype.isIdentifierPart = function (interpretedChar) { + if (isIdentifierPartCharacter[interpretedChar]) { + return true; + } + + return interpretedChar > 127 /* maxAsciiCharacter */ && TypeScript.Unicode.isIdentifierPart(interpretedChar, this._languageVersion); + }; + + Scanner.prototype.tryFastScanIdentifierOrKeyword = function (firstCharacter) { + var slidingWindow = this.slidingWindow; + var window = slidingWindow.window; + + var startIndex = slidingWindow.currentRelativeItemIndex; + var endIndex = slidingWindow.windowCount; + var currentIndex = startIndex; + var character = 0; + + while (currentIndex < endIndex) { + character = window[currentIndex]; + if (!isIdentifierPartCharacter[character]) { + break; + } + + currentIndex++; + } + + if (currentIndex === endIndex) { + return 0 /* None */; + } else if (character === 92 /* backslash */ || character > 127 /* maxAsciiCharacter */) { + return 0 /* None */; + } else { + var kind; + var identifierLength = currentIndex - startIndex; + if (isKeywordStartCharacter[firstCharacter]) { + kind = TypeScript.ScannerUtilities.identifierKind(window, startIndex, identifierLength); + } else { + kind = 11 /* IdentifierName */; + } + + slidingWindow.setAbsoluteIndex(slidingWindow.absoluteIndex() + identifierLength); + + return kind; + } + }; + + Scanner.prototype.slowScanIdentifierOrKeyword = function (diagnostics) { + var startIndex = this.slidingWindow.absoluteIndex(); + var sawUnicodeEscape = false; + + do { + var unicodeEscape = this.scanCharOrUnicodeEscape(diagnostics); + sawUnicodeEscape = sawUnicodeEscape || unicodeEscape; + } while(this.isIdentifierPart(this.peekCharOrUnicodeEscape())); + + var length = this.slidingWindow.absoluteIndex() - startIndex; + var text = this.text.substr(startIndex, length, false); + var valueText = TypeScript.Syntax.massageEscapes(text); + + var keywordKind = TypeScript.SyntaxFacts.getTokenKind(valueText); + if (keywordKind >= 15 /* FirstKeyword */ && keywordKind <= 69 /* LastKeyword */) { + if (sawUnicodeEscape) { + return keywordKind | -2147483648 /* IsVariableWidthKeyword */; + } else { + return keywordKind; + } + } + + return 11 /* IdentifierName */; + }; + + Scanner.prototype.scanNumericLiteral = function (diagnostics) { + if (this.isHexNumericLiteral()) { + this.scanHexNumericLiteral(); + } else if (this.isOctalNumericLiteral()) { + this.scanOctalNumericLiteral(diagnostics); + } else { + this.scanDecimalNumericLiteral(); + } + + return 13 /* NumericLiteral */; + }; + + Scanner.prototype.isOctalNumericLiteral = function () { + return this.currentCharCode() === 48 /* _0 */ && TypeScript.CharacterInfo.isOctalDigit(this.slidingWindow.peekItemN(1)); + }; + + Scanner.prototype.scanOctalNumericLiteral = function (diagnostics) { + var position = this.absoluteIndex(); + + while (TypeScript.CharacterInfo.isOctalDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + + if (this.languageVersion() >= 1 /* EcmaScript5 */) { + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), position, this.absoluteIndex() - position, TypeScript.DiagnosticCode.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher, null)); + } + }; + + Scanner.prototype.scanDecimalDigits = function () { + while (TypeScript.CharacterInfo.isDecimalDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + }; + + Scanner.prototype.scanDecimalNumericLiteral = function () { + this.scanDecimalDigits(); + + if (this.currentCharCode() === 46 /* dot */) { + this.slidingWindow.moveToNextItem(); + } + + this.scanDecimalDigits(); + + var ch = this.currentCharCode(); + if (ch === 101 /* e */ || ch === 69 /* E */) { + var nextChar1 = this.slidingWindow.peekItemN(1); + + if (TypeScript.CharacterInfo.isDecimalDigit(nextChar1)) { + this.slidingWindow.moveToNextItem(); + this.scanDecimalDigits(); + } else if (nextChar1 === 45 /* minus */ || nextChar1 === 43 /* plus */) { + var nextChar2 = this.slidingWindow.peekItemN(2); + if (TypeScript.CharacterInfo.isDecimalDigit(nextChar2)) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + this.scanDecimalDigits(); + } + } + } + }; + + Scanner.prototype.scanHexNumericLiteral = function () { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + while (TypeScript.CharacterInfo.isHexDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + }; + + Scanner.prototype.isHexNumericLiteral = function () { + if (this.currentCharCode() === 48 /* _0 */) { + var ch = this.slidingWindow.peekItemN(1); + + if (ch === 120 /* x */ || ch === 88 /* X */) { + ch = this.slidingWindow.peekItemN(2); + + return TypeScript.CharacterInfo.isHexDigit(ch); + } + } + + return false; + }; + + Scanner.prototype.advanceAndSetTokenKind = function (kind) { + this.slidingWindow.moveToNextItem(); + return kind; + }; + + Scanner.prototype.scanLessThanToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 82 /* LessThanEqualsToken */; + } else if (this.currentCharCode() === 60 /* lessThan */) { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 112 /* LessThanLessThanEqualsToken */; + } else { + return 95 /* LessThanLessThanToken */; + } + } else { + return 80 /* LessThanToken */; + } + }; + + Scanner.prototype.scanBarToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 116 /* BarEqualsToken */; + } else if (this.currentCharCode() === 124 /* bar */) { + this.slidingWindow.moveToNextItem(); + return 104 /* BarBarToken */; + } else { + return 99 /* BarToken */; + } + }; + + Scanner.prototype.scanCaretToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 117 /* CaretEqualsToken */; + } else { + return 100 /* CaretToken */; + } + }; + + Scanner.prototype.scanAmpersandToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 115 /* AmpersandEqualsToken */; + } else if (this.currentCharCode() === 38 /* ampersand */) { + this.slidingWindow.moveToNextItem(); + return 103 /* AmpersandAmpersandToken */; + } else { + return 98 /* AmpersandToken */; + } + }; + + Scanner.prototype.scanPercentToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 111 /* PercentEqualsToken */; + } else { + return 92 /* PercentToken */; + } + }; + + Scanner.prototype.scanMinusToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 109 /* MinusEqualsToken */; + } else if (character === 45 /* minus */) { + this.slidingWindow.moveToNextItem(); + return 94 /* MinusMinusToken */; + } else { + return 90 /* MinusToken */; + } + }; + + Scanner.prototype.scanPlusToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 108 /* PlusEqualsToken */; + } else if (character === 43 /* plus */) { + this.slidingWindow.moveToNextItem(); + return 93 /* PlusPlusToken */; + } else { + return 89 /* PlusToken */; + } + }; + + Scanner.prototype.scanAsteriskToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 110 /* AsteriskEqualsToken */; + } else { + return 91 /* AsteriskToken */; + } + }; + + Scanner.prototype.scanEqualsToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + return 87 /* EqualsEqualsEqualsToken */; + } else { + return 84 /* EqualsEqualsToken */; + } + } else if (character === 62 /* greaterThan */) { + this.slidingWindow.moveToNextItem(); + return 85 /* EqualsGreaterThanToken */; + } else { + return 107 /* EqualsToken */; + } + }; + + Scanner.prototype.isDotPrefixedNumericLiteral = function () { + if (this.currentCharCode() === 46 /* dot */) { + var ch = this.slidingWindow.peekItemN(1); + return TypeScript.CharacterInfo.isDecimalDigit(ch); + } + + return false; + }; + + Scanner.prototype.scanDotToken = function (diagnostics) { + if (this.isDotPrefixedNumericLiteral()) { + return this.scanNumericLiteral(diagnostics); + } + + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 46 /* dot */ && this.slidingWindow.peekItemN(1) === 46 /* dot */) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + return 77 /* DotDotDotToken */; + } else { + return 76 /* DotToken */; + } + }; + + Scanner.prototype.scanSlashToken = function (allowRegularExpression) { + if (allowRegularExpression) { + var result = this.tryScanRegularExpressionToken(); + if (result !== 0 /* None */) { + return result; + } + } + + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 119 /* SlashEqualsToken */; + } else { + return 118 /* SlashToken */; + } + }; + + Scanner.prototype.tryScanRegularExpressionToken = function () { + var startIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + this.slidingWindow.moveToNextItem(); + + var inEscape = false; + var inCharacterClass = false; + while (true) { + var ch = this.currentCharCode(); + + if (this.isNewLineCharacter(ch) || this.slidingWindow.isAtEndOfSource()) { + this.slidingWindow.rewindToPinnedIndex(startIndex); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + return 0 /* None */; + } + + this.slidingWindow.moveToNextItem(); + if (inEscape) { + inEscape = false; + continue; + } + + switch (ch) { + case 92 /* backslash */: + inEscape = true; + continue; + + case 91 /* openBracket */: + inCharacterClass = true; + continue; + + case 93 /* closeBracket */: + inCharacterClass = false; + continue; + + case 47 /* slash */: + if (inCharacterClass) { + continue; + } + + break; + + default: + continue; + } + + break; + } + + while (isIdentifierPartCharacter[this.currentCharCode()]) { + this.slidingWindow.moveToNextItem(); + } + + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + return 12 /* RegularExpressionLiteral */; + }; + + Scanner.prototype.scanExclamationToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + return 88 /* ExclamationEqualsEqualsToken */; + } else { + return 86 /* ExclamationEqualsToken */; + } + } else { + return 101 /* ExclamationToken */; + } + }; + + Scanner.prototype.scanDefaultCharacter = function (character, diagnostics) { + var position = this.slidingWindow.absoluteIndex(); + this.slidingWindow.moveToNextItem(); + + var text = String.fromCharCode(character); + var messageText = this.getErrorMessageText(text); + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), position, 1, TypeScript.DiagnosticCode.Unexpected_character_0, [messageText])); + + return 9 /* ErrorToken */; + }; + + Scanner.prototype.getErrorMessageText = function (text) { + if (text === "\\") { + return '"\\"'; + } + + return JSON.stringify(text); + }; + + Scanner.prototype.skipEscapeSequence = function (diagnostics) { + var rewindPoint = this.slidingWindow.getAndPinAbsoluteIndex(); + + this.slidingWindow.moveToNextItem(); + + var ch = this.currentCharCode(); + this.slidingWindow.moveToNextItem(); + switch (ch) { + case 120 /* x */: + case 117 /* u */: + this.slidingWindow.rewindToPinnedIndex(rewindPoint); + var value = this.scanUnicodeOrHexEscape(diagnostics); + break; + + case 13 /* carriageReturn */: + if (this.currentCharCode() === 10 /* lineFeed */) { + this.slidingWindow.moveToNextItem(); + } + break; + + default: + break; + } + + this.slidingWindow.releaseAndUnpinAbsoluteIndex(rewindPoint); + }; + + Scanner.prototype.scanStringLiteral = function (diagnostics) { + var quoteCharacter = this.currentCharCode(); + + this.slidingWindow.moveToNextItem(); + + while (true) { + var ch = this.currentCharCode(); + if (ch === 92 /* backslash */) { + this.skipEscapeSequence(diagnostics); + } else if (ch === quoteCharacter) { + this.slidingWindow.moveToNextItem(); + break; + } else if (this.isNewLineCharacter(ch) || this.slidingWindow.isAtEndOfSource()) { + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), TypeScript.MathPrototype.min(this.slidingWindow.absoluteIndex(), this.text.length()), 1, TypeScript.DiagnosticCode.Missing_close_quote_character, null)); + break; + } else { + this.slidingWindow.moveToNextItem(); + } + } + + return 14 /* StringLiteral */; + }; + + Scanner.prototype.isUnicodeEscape = function (character) { + if (character === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 117 /* u */) { + return true; + } + } + + return false; + }; + + Scanner.prototype.peekCharOrUnicodeEscape = function () { + var character = this.currentCharCode(); + if (this.isUnicodeEscape(character)) { + return this.peekUnicodeOrHexEscape(); + } else { + return character; + } + }; + + Scanner.prototype.peekUnicodeOrHexEscape = function () { + var startIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + var ch = this.scanUnicodeOrHexEscape(null); + + this.slidingWindow.rewindToPinnedIndex(startIndex); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + + return ch; + }; + + Scanner.prototype.scanCharOrUnicodeEscape = function (errors) { + var ch = this.currentCharCode(); + if (ch === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 117 /* u */) { + this.scanUnicodeOrHexEscape(errors); + return true; + } + } + + this.slidingWindow.moveToNextItem(); + return false; + }; + + Scanner.prototype.scanUnicodeOrHexEscape = function (errors) { + var start = this.slidingWindow.absoluteIndex(); + var character = this.currentCharCode(); + + this.slidingWindow.moveToNextItem(); + + character = this.currentCharCode(); + + var intChar = 0; + this.slidingWindow.moveToNextItem(); + + var count = character === 117 /* u */ ? 4 : 2; + + for (var i = 0; i < count; i++) { + var ch2 = this.currentCharCode(); + if (!TypeScript.CharacterInfo.isHexDigit(ch2)) { + if (errors !== null) { + var end = this.slidingWindow.absoluteIndex(); + var info = this.createIllegalEscapeDiagnostic(start, end); + errors.push(info); + } + + break; + } + + intChar = (intChar << 4) + TypeScript.CharacterInfo.hexValue(ch2); + this.slidingWindow.moveToNextItem(); + } + + return intChar; + }; + + Scanner.prototype.substring = function (start, end, intern) { + var length = end - start; + var offset = start - this.slidingWindow.windowAbsoluteStartIndex; + + if (intern) { + return TypeScript.Collections.DefaultStringTable.addCharArray(this.slidingWindow.window, offset, length); + } else { + return TypeScript.StringUtilities.fromCharCodeArray(this.slidingWindow.window.slice(offset, offset + length)); + } + }; + + Scanner.prototype.createIllegalEscapeDiagnostic = function (start, end) { + return new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), start, end - start, TypeScript.DiagnosticCode.Unrecognized_escape_sequence, null); + }; + + Scanner.isValidIdentifier = function (text, languageVersion) { + var scanner = new Scanner(null, text, languageVersion, Scanner.triviaWindow); + var errors = new Array(); + var token = scanner.scan(errors, false); + + return errors.length === 0 && TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token) && token.width() === text.length(); + }; + Scanner.triviaWindow = TypeScript.ArrayUtilities.createArray(2048, 0); + return Scanner; + })(); + TypeScript.Scanner = Scanner; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScannerUtilities = (function () { + function ScannerUtilities() { + } + ScannerUtilities.identifierKind = function (array, startIndex, length) { + switch (length) { + case 2: + switch (array[startIndex]) { + case 100 /* d */: + return (array[startIndex + 1] === 111 /* o */) ? 22 /* DoKeyword */ : 11 /* IdentifierName */; + case 105 /* i */: + switch (array[startIndex + 1]) { + case 102 /* f */: + return 28 /* IfKeyword */; + case 110 /* n */: + return 29 /* InKeyword */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 3: + switch (array[startIndex]) { + case 102 /* f */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 114 /* r */) ? 26 /* ForKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 119 /* w */) ? 31 /* NewKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 121 /* y */) ? 38 /* TryKeyword */ : 11 /* IdentifierName */; + case 118 /* v */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 114 /* r */) ? 40 /* VarKeyword */ : 11 /* IdentifierName */; + case 108 /* l */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 53 /* LetKeyword */ : 11 /* IdentifierName */; + case 97 /* a */: + return (array[startIndex + 1] === 110 /* n */ && array[startIndex + 2] === 121 /* y */) ? 60 /* AnyKeyword */ : 11 /* IdentifierName */; + case 103 /* g */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 64 /* GetKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 68 /* SetKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 4: + switch (array[startIndex]) { + case 99 /* c */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 101 /* e */) ? 16 /* CaseKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + switch (array[startIndex + 1]) { + case 108 /* l */: + return (array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 101 /* e */) ? 23 /* ElseKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 2] === 117 /* u */ && array[startIndex + 3] === 109 /* m */) ? 46 /* EnumKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 110 /* n */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 108 /* l */) ? 32 /* NullKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + switch (array[startIndex + 1]) { + case 104 /* h */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 115 /* s */) ? 35 /* ThisKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 2] === 117 /* u */ && array[startIndex + 3] === 101 /* e */) ? 37 /* TrueKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 118 /* v */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 100 /* d */) ? 41 /* VoidKeyword */ : 11 /* IdentifierName */; + case 119 /* w */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 104 /* h */) ? 43 /* WithKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 5: + switch (array[startIndex]) { + case 98 /* b */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 101 /* e */ && array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 107 /* k */) ? 15 /* BreakKeyword */ : 11 /* IdentifierName */; + case 99 /* c */: + switch (array[startIndex + 1]) { + case 97 /* a */: + return (array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 99 /* c */ && array[startIndex + 4] === 104 /* h */) ? 17 /* CatchKeyword */ : 11 /* IdentifierName */; + case 108 /* l */: + return (array[startIndex + 2] === 97 /* a */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 115 /* s */) ? 44 /* ClassKeyword */ : 11 /* IdentifierName */; + case 111 /* o */: + return (array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 116 /* t */) ? 45 /* ConstKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 102 /* f */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 101 /* e */) ? 24 /* FalseKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + return (array[startIndex + 1] === 104 /* h */ && array[startIndex + 2] === 114 /* r */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 119 /* w */) ? 36 /* ThrowKeyword */ : 11 /* IdentifierName */; + case 119 /* w */: + return (array[startIndex + 1] === 104 /* h */ && array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */) ? 42 /* WhileKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 114 /* r */) ? 50 /* SuperKeyword */ : 11 /* IdentifierName */; + case 121 /* y */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 101 /* e */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 100 /* d */) ? 59 /* YieldKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 6: + switch (array[startIndex]) { + case 100 /* d */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 101 /* e */) ? 21 /* DeleteKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 110 /* n */) ? 33 /* ReturnKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + switch (array[startIndex + 1]) { + case 119 /* w */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 99 /* c */ && array[startIndex + 5] === 104 /* h */) ? 34 /* SwitchKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + switch (array[startIndex + 2]) { + case 97 /* a */: + return (array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 99 /* c */) ? 58 /* StaticKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 3] === 105 /* i */ && array[startIndex + 4] === 110 /* n */ && array[startIndex + 5] === 103 /* g */) ? 69 /* StringKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 116 /* t */: + return (array[startIndex + 1] === 121 /* y */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 111 /* o */ && array[startIndex + 5] === 102 /* f */) ? 39 /* TypeOfKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + return (array[startIndex + 1] === 120 /* x */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 116 /* t */) ? 47 /* ExportKeyword */ : 11 /* IdentifierName */; + case 105 /* i */: + return (array[startIndex + 1] === 109 /* m */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 116 /* t */) ? 49 /* ImportKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 98 /* b */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 99 /* c */) ? 57 /* PublicKeyword */ : 11 /* IdentifierName */; + case 109 /* m */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 100 /* d */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 108 /* l */ && array[startIndex + 5] === 101 /* e */) ? 65 /* ModuleKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 109 /* m */ && array[startIndex + 3] === 98 /* b */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 114 /* r */) ? 67 /* NumberKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 7: + switch (array[startIndex]) { + case 100 /* d */: + switch (array[startIndex + 1]) { + case 101 /* e */: + switch (array[startIndex + 2]) { + case 102 /* f */: + return (array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 117 /* u */ && array[startIndex + 5] === 108 /* l */ && array[startIndex + 6] === 116 /* t */) ? 20 /* DefaultKeyword */ : 11 /* IdentifierName */; + case 99 /* c */: + return (array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 101 /* e */) ? 63 /* DeclareKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 102 /* f */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 108 /* l */ && array[startIndex + 5] === 108 /* l */ && array[startIndex + 6] === 121 /* y */) ? 25 /* FinallyKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + return (array[startIndex + 1] === 120 /* x */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 110 /* n */ && array[startIndex + 5] === 100 /* d */ && array[startIndex + 6] === 115 /* s */) ? 48 /* ExtendsKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + switch (array[startIndex + 1]) { + case 97 /* a */: + return (array[startIndex + 2] === 99 /* c */ && array[startIndex + 3] === 107 /* k */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 103 /* g */ && array[startIndex + 6] === 101 /* e */) ? 54 /* PackageKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 118 /* v */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 116 /* t */ && array[startIndex + 6] === 101 /* e */) ? 55 /* PrivateKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 98 /* b */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 111 /* o */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 97 /* a */ && array[startIndex + 6] === 110 /* n */) ? 61 /* BooleanKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 113 /* q */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 101 /* e */) ? 66 /* RequireKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 8: + switch (array[startIndex]) { + case 99 /* c */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 110 /* n */ && array[startIndex + 6] === 117 /* u */ && array[startIndex + 7] === 101 /* e */) ? 18 /* ContinueKeyword */ : 11 /* IdentifierName */; + case 100 /* d */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 98 /* b */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 103 /* g */ && array[startIndex + 5] === 103 /* g */ && array[startIndex + 6] === 101 /* e */ && array[startIndex + 7] === 114 /* r */) ? 19 /* DebuggerKeyword */ : 11 /* IdentifierName */; + case 102 /* f */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 99 /* c */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 105 /* i */ && array[startIndex + 6] === 111 /* o */ && array[startIndex + 7] === 110 /* n */) ? 27 /* FunctionKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 9: + switch (array[startIndex]) { + case 105 /* i */: + return (array[startIndex + 1] === 110 /* n */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 102 /* f */ && array[startIndex + 6] === 97 /* a */ && array[startIndex + 7] === 99 /* c */ && array[startIndex + 8] === 101 /* e */) ? 52 /* InterfaceKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 111 /* o */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 99 /* c */ && array[startIndex + 6] === 116 /* t */ && array[startIndex + 7] === 101 /* e */ && array[startIndex + 8] === 100 /* d */) ? 56 /* ProtectedKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 10: + switch (array[startIndex]) { + case 105 /* i */: + switch (array[startIndex + 1]) { + case 110 /* n */: + return (array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 110 /* n */ && array[startIndex + 6] === 99 /* c */ && array[startIndex + 7] === 101 /* e */ && array[startIndex + 8] === 111 /* o */ && array[startIndex + 9] === 102 /* f */) ? 30 /* InstanceOfKeyword */ : 11 /* IdentifierName */; + case 109 /* m */: + return (array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 109 /* m */ && array[startIndex + 6] === 101 /* e */ && array[startIndex + 7] === 110 /* n */ && array[startIndex + 8] === 116 /* t */ && array[startIndex + 9] === 115 /* s */) ? 51 /* ImplementsKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 11: + return (array[startIndex] === 99 /* c */ && array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 117 /* u */ && array[startIndex + 7] === 99 /* c */ && array[startIndex + 8] === 116 /* t */ && array[startIndex + 9] === 111 /* o */ && array[startIndex + 10] === 114 /* r */) ? 62 /* ConstructorKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + }; + return ScannerUtilities; + })(); + TypeScript.ScannerUtilities = ScannerUtilities; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var EmptySeparatedSyntaxList = (function () { + function EmptySeparatedSyntaxList() { + } + EmptySeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + EmptySeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isList = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + + EmptySeparatedSyntaxList.prototype.toJSON = function (key) { + return []; + }; + + EmptySeparatedSyntaxList.prototype.childCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.separatorCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.toArray = function () { + return []; + }; + + EmptySeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + return []; + }; + + EmptySeparatedSyntaxList.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.separatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.collectTextElements = function (elements) { + }; + + EmptySeparatedSyntaxList.prototype.firstToken = function () { + return null; + }; + + EmptySeparatedSyntaxList.prototype.lastToken = function () { + return null; + }; + + EmptySeparatedSyntaxList.prototype.fullWidth = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.fullText = function () { + return ""; + }; + + EmptySeparatedSyntaxList.prototype.width = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + throw TypeScript.Errors.invalidOperation(); + }; + + EmptySeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + }; + + EmptySeparatedSyntaxList.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySeparatedSyntaxList.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return 0; + }; + return EmptySeparatedSyntaxList; + })(); + + Syntax.emptySeparatedList = new EmptySeparatedSyntaxList(); + + var SingletonSeparatedSyntaxList = (function () { + function SingletonSeparatedSyntaxList(item) { + this.item = item; + } + SingletonSeparatedSyntaxList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + SingletonSeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isList = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + + SingletonSeparatedSyntaxList.prototype.childCount = function () { + return 1; + }; + SingletonSeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return 1; + }; + SingletonSeparatedSyntaxList.prototype.separatorCount = function () { + return 0; + }; + + SingletonSeparatedSyntaxList.prototype.toArray = function () { + return [this.item]; + }; + SingletonSeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + return [this.item]; + }; + + SingletonSeparatedSyntaxList.prototype.childAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSeparatedSyntaxList.prototype.separatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + SingletonSeparatedSyntaxList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSeparatedSyntaxList.prototype.firstToken = function () { + return this.item.firstToken(); + }; + + SingletonSeparatedSyntaxList.prototype.lastToken = function () { + return this.item.lastToken(); + }; + + SingletonSeparatedSyntaxList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.width = function () { + return this.item.width(); + }; + + SingletonSeparatedSyntaxList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSeparatedSyntaxList.prototype.leadingTrivia = function () { + return this.item.leadingTrivia(); + }; + + SingletonSeparatedSyntaxList.prototype.trailingTrivia = function () { + return this.item.trailingTrivia(); + }; + + SingletonSeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return this.item.leadingTriviaWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return this.item.trailingTriviaWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + return this.item.isTypeScriptSpecific(); + }; + + SingletonSeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return this.item.isIncrementallyUnusable(); + }; + + SingletonSeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + return this.item.findTokenInternal(new TypeScript.PositionedSeparatedList(parent, this, fullStart), position, fullStart); + }; + + SingletonSeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + array.splice(index, 0, this.item); + }; + return SingletonSeparatedSyntaxList; + })(); + + var NormalSeparatedSyntaxList = (function () { + function NormalSeparatedSyntaxList(elements) { + this._data = 0; + this.elements = elements; + } + NormalSeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + NormalSeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isList = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + NormalSeparatedSyntaxList.prototype.toJSON = function (key) { + return this.elements; + }; + + NormalSeparatedSyntaxList.prototype.childCount = function () { + return this.elements.length; + }; + NormalSeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return TypeScript.IntegerUtilities.integerDivide(this.elements.length + 1, 2); + }; + NormalSeparatedSyntaxList.prototype.separatorCount = function () { + return TypeScript.IntegerUtilities.integerDivide(this.elements.length, 2); + }; + + NormalSeparatedSyntaxList.prototype.toArray = function () { + return this.elements.slice(0); + }; + + NormalSeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + var result = []; + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + result.push(this.nonSeparatorAt(i)); + } + + return result; + }; + + NormalSeparatedSyntaxList.prototype.childAt = function (index) { + if (index < 0 || index >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[index]; + }; + + NormalSeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + var value = index * 2; + if (value < 0 || value >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[value]; + }; + + NormalSeparatedSyntaxList.prototype.separatorAt = function (index) { + var value = index * 2 + 1; + if (value < 0 || value >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[value]; + }; + + NormalSeparatedSyntaxList.prototype.firstToken = function () { + var token; + for (var i = 0, n = this.elements.length; i < n; i++) { + if (i % 2 === 0) { + var nodeOrToken = this.elements[i]; + token = nodeOrToken.firstToken(); + if (token !== null) { + return token; + } + } else { + token = this.elements[i]; + if (token.width() > 0) { + return token; + } + } + } + + return null; + }; + + NormalSeparatedSyntaxList.prototype.lastToken = function () { + var token; + for (var i = this.elements.length - 1; i >= 0; i--) { + if (i % 2 === 0) { + var nodeOrToken = this.elements[i]; + token = nodeOrToken.lastToken(); + if (token !== null) { + return token; + } + } else { + token = this.elements[i]; + if (token.width() > 0) { + return token; + } + } + } + + return null; + }; + + NormalSeparatedSyntaxList.prototype.fullText = function () { + var elements = []; + this.collectTextElements(elements); + return elements.join(""); + }; + + NormalSeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + if (this.nonSeparatorAt(i).isTypeScriptSpecific()) { + return true; + } + } + + return false; + }; + + NormalSeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + NormalSeparatedSyntaxList.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + NormalSeparatedSyntaxList.prototype.width = function () { + var fullWidth = this.fullWidth(); + return fullWidth - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.leadingTrivia = function () { + return this.firstToken().leadingTrivia(); + }; + + NormalSeparatedSyntaxList.prototype.trailingTrivia = function () { + return this.lastToken().trailingTrivia(); + }; + + NormalSeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return this.firstToken().leadingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return this.lastToken().trailingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.computeData = function () { + var fullWidth = 0; + var isIncrementallyUnusable = false; + + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + + var childWidth = element.fullWidth(); + fullWidth += childWidth; + + isIncrementallyUnusable = isIncrementallyUnusable || element.isIncrementallyUnusable(); + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + NormalSeparatedSyntaxList.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data = this.computeData(); + } + + return this._data; + }; + + NormalSeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedSeparatedList(parent, this, fullStart); + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + + var childWidth = element.fullWidth(); + if (position < childWidth) { + return element.findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + NormalSeparatedSyntaxList.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + element.collectTextElements(elements); + } + }; + + NormalSeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + if (index === 0) { + array.unshift.apply(array, this.elements); + } else { + array.splice.apply(array, [index, 0].concat(this.elements)); + } + }; + return NormalSeparatedSyntaxList; + })(); + + function separatedList(nodes) { + return separatedListAndValidate(nodes, false); + } + Syntax.separatedList = separatedList; + + function separatedListAndValidate(nodes, validate) { + if (nodes === undefined || nodes === null || nodes.length === 0) { + return Syntax.emptySeparatedList; + } + + if (validate) { + for (var i = 0; i < nodes.length; i++) { + var item = nodes[i]; + + if (i % 2 === 1) { + } + } + } + + if (nodes.length === 1) { + return new SingletonSeparatedSyntaxList(nodes[0]); + } + + return new NormalSeparatedSyntaxList(nodes); + } + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SlidingWindow = (function () { + function SlidingWindow(source, window, defaultValue, sourceLength) { + if (typeof sourceLength === "undefined") { sourceLength = -1; } + this.source = source; + this.window = window; + this.defaultValue = defaultValue; + this.sourceLength = sourceLength; + this.windowCount = 0; + this.windowAbsoluteStartIndex = 0; + this.currentRelativeItemIndex = 0; + this._pinCount = 0; + this.firstPinnedAbsoluteIndex = -1; + } + SlidingWindow.prototype.windowAbsoluteEndIndex = function () { + return this.windowAbsoluteStartIndex + this.windowCount; + }; + + SlidingWindow.prototype.addMoreItemsToWindow = function (argument) { + if (this.sourceLength >= 0 && this.absoluteIndex() >= this.sourceLength) { + return false; + } + + if (this.windowCount >= this.window.length) { + this.tryShiftOrGrowWindow(); + } + + var spaceAvailable = this.window.length - this.windowCount; + var amountFetched = this.source.fetchMoreItems(argument, this.windowAbsoluteEndIndex(), this.window, this.windowCount, spaceAvailable); + + this.windowCount += amountFetched; + return amountFetched > 0; + }; + + SlidingWindow.prototype.tryShiftOrGrowWindow = function () { + var currentIndexIsPastWindowHalfwayPoint = this.currentRelativeItemIndex > (this.window.length >>> 1); + + var isAllowedToShift = this.firstPinnedAbsoluteIndex === -1 || this.firstPinnedAbsoluteIndex > this.windowAbsoluteStartIndex; + + if (currentIndexIsPastWindowHalfwayPoint && isAllowedToShift) { + var shiftStartIndex = this.firstPinnedAbsoluteIndex === -1 ? this.currentRelativeItemIndex : this.firstPinnedAbsoluteIndex - this.windowAbsoluteStartIndex; + + var shiftCount = this.windowCount - shiftStartIndex; + + if (shiftCount > 0) { + TypeScript.ArrayUtilities.copy(this.window, shiftStartIndex, this.window, 0, shiftCount); + } + + this.windowAbsoluteStartIndex += shiftStartIndex; + + this.windowCount -= shiftStartIndex; + + this.currentRelativeItemIndex -= shiftStartIndex; + } else { + TypeScript.ArrayUtilities.grow(this.window, this.window.length * 2, this.defaultValue); + } + }; + + SlidingWindow.prototype.absoluteIndex = function () { + return this.windowAbsoluteStartIndex + this.currentRelativeItemIndex; + }; + + SlidingWindow.prototype.isAtEndOfSource = function () { + return this.absoluteIndex() >= this.sourceLength; + }; + + SlidingWindow.prototype.getAndPinAbsoluteIndex = function () { + var absoluteIndex = this.absoluteIndex(); + var pinCount = this._pinCount++; + if (pinCount === 0) { + this.firstPinnedAbsoluteIndex = absoluteIndex; + } + + return absoluteIndex; + }; + + SlidingWindow.prototype.releaseAndUnpinAbsoluteIndex = function (absoluteIndex) { + this._pinCount--; + if (this._pinCount === 0) { + this.firstPinnedAbsoluteIndex = -1; + } + }; + + SlidingWindow.prototype.rewindToPinnedIndex = function (absoluteIndex) { + var relativeIndex = absoluteIndex - this.windowAbsoluteStartIndex; + + this.currentRelativeItemIndex = relativeIndex; + }; + + SlidingWindow.prototype.currentItem = function (argument) { + if (this.currentRelativeItemIndex >= this.windowCount) { + if (!this.addMoreItemsToWindow(argument)) { + return this.defaultValue; + } + } + + return this.window[this.currentRelativeItemIndex]; + }; + + SlidingWindow.prototype.peekItemN = function (n) { + while (this.currentRelativeItemIndex + n >= this.windowCount) { + if (!this.addMoreItemsToWindow(null)) { + return this.defaultValue; + } + } + + return this.window[this.currentRelativeItemIndex + n]; + }; + + SlidingWindow.prototype.moveToNextItem = function () { + this.currentRelativeItemIndex++; + }; + + SlidingWindow.prototype.disgardAllItemsFromCurrentIndexOnwards = function () { + this.windowCount = this.currentRelativeItemIndex; + }; + + SlidingWindow.prototype.setAbsoluteIndex = function (absoluteIndex) { + if (this.absoluteIndex() === absoluteIndex) { + return; + } + + if (this._pinCount > 0) { + } + + if (absoluteIndex >= this.windowAbsoluteStartIndex && absoluteIndex < this.windowAbsoluteEndIndex()) { + this.currentRelativeItemIndex = (absoluteIndex - this.windowAbsoluteStartIndex); + } else { + this.windowAbsoluteStartIndex = absoluteIndex; + + this.windowCount = 0; + + this.currentRelativeItemIndex = 0; + } + }; + + SlidingWindow.prototype.pinCount = function () { + return this._pinCount; + }; + return SlidingWindow; + })(); + TypeScript.SlidingWindow = SlidingWindow; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + function emptySourceUnit() { + return Syntax.normalModeFactory.sourceUnit(Syntax.emptyList, Syntax.token(10 /* EndOfFileToken */, { text: "" })); + } + Syntax.emptySourceUnit = emptySourceUnit; + + function getStandaloneExpression(positionedToken) { + var token = positionedToken.token(); + if (positionedToken !== null && positionedToken.kind() === 11 /* IdentifierName */) { + var parentPositionedNode = positionedToken.containingNode(); + var parentNode = parentPositionedNode.node(); + + if (parentNode.kind() === 121 /* QualifiedName */ && parentNode.right === token) { + return parentPositionedNode; + } else if (parentNode.kind() === 212 /* MemberAccessExpression */ && parentNode.name === token) { + return parentPositionedNode; + } + } + + return positionedToken; + } + Syntax.getStandaloneExpression = getStandaloneExpression; + + function isInModuleOrTypeContext(positionedToken) { + if (positionedToken !== null) { + var positionedNodeOrToken = Syntax.getStandaloneExpression(positionedToken); + var parent = positionedNodeOrToken.containingNode(); + + if (parent !== null) { + switch (parent.kind()) { + case 246 /* ModuleNameModuleReference */: + return true; + case 121 /* QualifiedName */: + return true; + default: + return isInTypeOnlyContext(positionedToken); + } + } + } + + return false; + } + Syntax.isInModuleOrTypeContext = isInModuleOrTypeContext; + + function isInTypeOnlyContext(positionedToken) { + var positionedNodeOrToken = Syntax.getStandaloneExpression(positionedToken); + var positionedParent = positionedNodeOrToken.containingNode(); + + var parent = positionedParent.node(); + var nodeOrToken = positionedNodeOrToken.nodeOrToken(); + + if (parent !== null) { + switch (parent.kind()) { + case 124 /* ArrayType */: + return parent.type === nodeOrToken; + case 220 /* CastExpression */: + return parent.type === nodeOrToken; + case 244 /* TypeAnnotation */: + case 230 /* ExtendsHeritageClause */: + case 231 /* ImplementsHeritageClause */: + case 228 /* TypeArgumentList */: + return true; + } + } + + return false; + } + Syntax.isInTypeOnlyContext = isInTypeOnlyContext; + + function childOffset(parent, child) { + var offset = 0; + for (var i = 0, n = parent.childCount(); i < n; i++) { + var current = parent.childAt(i); + if (current === child) { + return offset; + } + + if (current !== null) { + offset += current.fullWidth(); + } + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.childOffset = childOffset; + + function childOffsetAt(parent, index) { + var offset = 0; + for (var i = 0; i < index; i++) { + var current = parent.childAt(i); + if (current !== null) { + offset += current.fullWidth(); + } + } + + return offset; + } + Syntax.childOffsetAt = childOffsetAt; + + function childIndex(parent, child) { + for (var i = 0, n = parent.childCount(); i < n; i++) { + var current = parent.childAt(i); + if (current === child) { + return i; + } + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.childIndex = childIndex; + + function nodeStructuralEquals(node1, node2) { + if (node1 === null) { + return node2 === null; + } + + return node1.structuralEquals(node2); + } + Syntax.nodeStructuralEquals = nodeStructuralEquals; + + function nodeOrTokenStructuralEquals(node1, node2) { + if (node1 === node2) { + return true; + } + + if (node1 === null || node2 === null) { + return false; + } + + if (node1.isToken()) { + return node2.isToken() ? tokenStructuralEquals(node1, node2) : false; + } + + return node2.isNode() ? nodeStructuralEquals(node1, node2) : false; + } + Syntax.nodeOrTokenStructuralEquals = nodeOrTokenStructuralEquals; + + function tokenStructuralEquals(token1, token2) { + if (token1 === token2) { + return true; + } + + if (token1 === null || token2 === null) { + return false; + } + + return token1.kind() === token2.kind() && token1.width() === token2.width() && token1.fullWidth() === token2.fullWidth() && token1.text() === token2.text() && Syntax.triviaListStructuralEquals(token1.leadingTrivia(), token2.leadingTrivia()) && Syntax.triviaListStructuralEquals(token1.trailingTrivia(), token2.trailingTrivia()); + } + Syntax.tokenStructuralEquals = tokenStructuralEquals; + + function triviaListStructuralEquals(triviaList1, triviaList2) { + if (triviaList1.count() !== triviaList2.count()) { + return false; + } + + for (var i = 0, n = triviaList1.count(); i < n; i++) { + if (!Syntax.triviaStructuralEquals(triviaList1.syntaxTriviaAt(i), triviaList2.syntaxTriviaAt(i))) { + return false; + } + } + + return true; + } + Syntax.triviaListStructuralEquals = triviaListStructuralEquals; + + function triviaStructuralEquals(trivia1, trivia2) { + return trivia1.kind() === trivia2.kind() && trivia1.fullWidth() === trivia2.fullWidth() && trivia1.fullText() === trivia2.fullText(); + } + Syntax.triviaStructuralEquals = triviaStructuralEquals; + + function listStructuralEquals(list1, list2) { + if (list1.childCount() !== list2.childCount()) { + return false; + } + + for (var i = 0, n = list1.childCount(); i < n; i++) { + var child1 = list1.childAt(i); + var child2 = list2.childAt(i); + + if (!Syntax.nodeOrTokenStructuralEquals(child1, child2)) { + return false; + } + } + + return true; + } + Syntax.listStructuralEquals = listStructuralEquals; + + function separatedListStructuralEquals(list1, list2) { + if (list1.childCount() !== list2.childCount()) { + return false; + } + + for (var i = 0, n = list1.childCount(); i < n; i++) { + var element1 = list1.childAt(i); + var element2 = list2.childAt(i); + if (!Syntax.nodeOrTokenStructuralEquals(element1, element2)) { + return false; + } + } + + return true; + } + Syntax.separatedListStructuralEquals = separatedListStructuralEquals; + + function elementStructuralEquals(element1, element2) { + if (element1 === element2) { + return true; + } + + if (element1 === null || element2 === null) { + return false; + } + + if (element2.kind() !== element2.kind()) { + return false; + } + + if (element1.isToken()) { + return tokenStructuralEquals(element1, element2); + } else if (element1.isNode()) { + return nodeStructuralEquals(element1, element2); + } else if (element1.isList()) { + return listStructuralEquals(element1, element2); + } else if (element1.isSeparatedList()) { + return separatedListStructuralEquals(element1, element2); + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.elementStructuralEquals = elementStructuralEquals; + + function identifierName(text, info) { + if (typeof info === "undefined") { info = null; } + return Syntax.identifier(text); + } + Syntax.identifierName = identifierName; + + function trueExpression() { + return Syntax.token(37 /* TrueKeyword */); + } + Syntax.trueExpression = trueExpression; + + function falseExpression() { + return Syntax.token(24 /* FalseKeyword */); + } + Syntax.falseExpression = falseExpression; + + function numericLiteralExpression(text) { + return Syntax.token(13 /* NumericLiteral */, { text: text }); + } + Syntax.numericLiteralExpression = numericLiteralExpression; + + function stringLiteralExpression(text) { + return Syntax.token(14 /* StringLiteral */, { text: text }); + } + Syntax.stringLiteralExpression = stringLiteralExpression; + + function isSuperInvocationExpression(node) { + return node.kind() === 213 /* InvocationExpression */ && node.expression.kind() === 50 /* SuperKeyword */; + } + Syntax.isSuperInvocationExpression = isSuperInvocationExpression; + + function isSuperInvocationExpressionStatement(node) { + return node.kind() === 149 /* ExpressionStatement */ && isSuperInvocationExpression(node.expression); + } + Syntax.isSuperInvocationExpressionStatement = isSuperInvocationExpressionStatement; + + function isSuperMemberAccessExpression(node) { + return node.kind() === 212 /* MemberAccessExpression */ && node.expression.kind() === 50 /* SuperKeyword */; + } + Syntax.isSuperMemberAccessExpression = isSuperMemberAccessExpression; + + function isSuperMemberAccessInvocationExpression(node) { + return node.kind() === 213 /* InvocationExpression */ && isSuperMemberAccessExpression(node.expression); + } + Syntax.isSuperMemberAccessInvocationExpression = isSuperMemberAccessInvocationExpression; + + function assignmentExpression(left, token, right) { + return Syntax.normalModeFactory.binaryExpression(174 /* AssignmentExpression */, left, token, right); + } + Syntax.assignmentExpression = assignmentExpression; + + function nodeHasSkippedOrMissingTokens(node) { + for (var i = 0; i < node.childCount(); i++) { + var child = node.childAt(i); + if (child !== null && child.isToken()) { + var token = child; + + if (token.hasSkippedToken() || (token.width() === 0 && token.kind() !== 10 /* EndOfFileToken */)) { + return true; + } + } + } + return false; + } + Syntax.nodeHasSkippedOrMissingTokens = nodeHasSkippedOrMissingTokens; + + function isUnterminatedStringLiteral(token) { + if (token && token.kind() === 14 /* StringLiteral */) { + var text = token.text(); + return text.length < 2 || text.charCodeAt(text.length - 1) !== text.charCodeAt(0); + } + + return false; + } + Syntax.isUnterminatedStringLiteral = isUnterminatedStringLiteral; + + function isUnterminatedMultilineCommentTrivia(trivia) { + if (trivia && trivia.kind() === 6 /* MultiLineCommentTrivia */) { + var text = trivia.fullText(); + return text.length < 4 || text.substring(text.length - 2) !== "*/"; + } + return false; + } + Syntax.isUnterminatedMultilineCommentTrivia = isUnterminatedMultilineCommentTrivia; + + function isEntirelyInsideCommentTrivia(trivia, fullStart, position) { + if (trivia && trivia.isComment() && position > fullStart) { + var end = fullStart + trivia.fullWidth(); + if (position < end) { + return true; + } else if (position === end) { + return trivia.kind() === 7 /* SingleLineCommentTrivia */ || isUnterminatedMultilineCommentTrivia(trivia); + } + } + + return false; + } + Syntax.isEntirelyInsideCommentTrivia = isEntirelyInsideCommentTrivia; + + function isEntirelyInsideComment(sourceUnit, position) { + var positionedToken = sourceUnit.findToken(position); + var fullStart = positionedToken.fullStart(); + var triviaList = null; + var lastTriviaBeforeToken = null; + + if (positionedToken.kind() === 10 /* EndOfFileToken */) { + if (positionedToken.token().hasLeadingTrivia()) { + triviaList = positionedToken.token().leadingTrivia(); + } else { + positionedToken = positionedToken.previousToken(); + if (positionedToken) { + if (positionedToken && positionedToken.token().hasTrailingTrivia()) { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + } + } + } else { + if (position <= (fullStart + positionedToken.token().leadingTriviaWidth())) { + triviaList = positionedToken.token().leadingTrivia(); + } else if (position >= (fullStart + positionedToken.token().width())) { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + } + + if (triviaList) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (position <= fullStart) { + break; + } else if (position <= fullStart + trivia.fullWidth() && trivia.isComment()) { + lastTriviaBeforeToken = trivia; + break; + } + + fullStart += trivia.fullWidth(); + } + } + + return lastTriviaBeforeToken && isEntirelyInsideCommentTrivia(lastTriviaBeforeToken, fullStart, position); + } + Syntax.isEntirelyInsideComment = isEntirelyInsideComment; + + function isEntirelyInStringOrRegularExpressionLiteral(sourceUnit, position) { + var positionedToken = sourceUnit.findToken(position); + + if (positionedToken) { + if (positionedToken.kind() === 10 /* EndOfFileToken */) { + positionedToken = positionedToken.previousToken(); + return positionedToken && positionedToken.token().trailingTriviaWidth() === 0 && isUnterminatedStringLiteral(positionedToken.token()); + } else if (position > positionedToken.start()) { + return (position < positionedToken.end() && (positionedToken.kind() === 14 /* StringLiteral */ || positionedToken.kind() === 12 /* RegularExpressionLiteral */)) || (position <= positionedToken.end() && isUnterminatedStringLiteral(positionedToken.token())); + } + } + + return false; + } + Syntax.isEntirelyInStringOrRegularExpressionLiteral = isEntirelyInStringOrRegularExpressionLiteral; + + function findSkippedTokenInTriviaList(positionedToken, position, lookInLeadingTriviaList) { + var triviaList = null; + var fullStart; + + if (lookInLeadingTriviaList) { + triviaList = positionedToken.token().leadingTrivia(); + fullStart = positionedToken.fullStart(); + } else { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + + if (triviaList && triviaList.hasSkippedToken()) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + var triviaWidth = trivia.fullWidth(); + + if (trivia.isSkippedToken() && position >= fullStart && position <= fullStart + triviaWidth) { + return new TypeScript.PositionedSkippedToken(positionedToken, trivia.skippedToken(), fullStart); + } + + fullStart += triviaWidth; + } + } + + return null; + } + + function findSkippedTokenOnLeftInTriviaList(positionedToken, position, lookInLeadingTriviaList) { + var triviaList = null; + var fullEnd; + + if (lookInLeadingTriviaList) { + triviaList = positionedToken.token().leadingTrivia(); + fullEnd = positionedToken.fullStart() + triviaList.fullWidth(); + } else { + triviaList = positionedToken.token().trailingTrivia(); + fullEnd = positionedToken.fullEnd(); + } + + if (triviaList && triviaList.hasSkippedToken()) { + for (var i = triviaList.count() - 1; i >= 0; i--) { + var trivia = triviaList.syntaxTriviaAt(i); + var triviaWidth = trivia.fullWidth(); + + if (trivia.isSkippedToken() && position >= fullEnd) { + return new TypeScript.PositionedSkippedToken(positionedToken, trivia.skippedToken(), fullEnd - triviaWidth); + } + + fullEnd -= triviaWidth; + } + } + + return null; + } + + function findSkippedTokenInLeadingTriviaList(positionedToken, position) { + return findSkippedTokenInTriviaList(positionedToken, position, true); + } + Syntax.findSkippedTokenInLeadingTriviaList = findSkippedTokenInLeadingTriviaList; + + function findSkippedTokenInTrailingTriviaList(positionedToken, position) { + return findSkippedTokenInTriviaList(positionedToken, position, false); + } + Syntax.findSkippedTokenInTrailingTriviaList = findSkippedTokenInTrailingTriviaList; + + function findSkippedTokenInPositionedToken(positionedToken, position) { + var positionInLeadingTriviaList = (position < positionedToken.start()); + return findSkippedTokenInTriviaList(positionedToken, position, positionInLeadingTriviaList); + } + Syntax.findSkippedTokenInPositionedToken = findSkippedTokenInPositionedToken; + + function findSkippedTokenOnLeft(positionedToken, position) { + var positionInLeadingTriviaList = (position < positionedToken.start()); + return findSkippedTokenOnLeftInTriviaList(positionedToken, position, positionInLeadingTriviaList); + } + Syntax.findSkippedTokenOnLeft = findSkippedTokenOnLeft; + + function getAncestorOfKind(positionedToken, kind) { + while (positionedToken && positionedToken.parent()) { + if (positionedToken.parent().kind() === kind) { + return positionedToken.parent(); + } + + positionedToken = positionedToken.parent(); + } + + return null; + } + Syntax.getAncestorOfKind = getAncestorOfKind; + + function hasAncestorOfKind(positionedToken, kind) { + return Syntax.getAncestorOfKind(positionedToken, kind) !== null; + } + Syntax.hasAncestorOfKind = hasAncestorOfKind; + + function isIntegerLiteral(expression) { + if (expression) { + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + expression = expression.operand; + return expression.isToken() && TypeScript.IntegerUtilities.isInteger(expression.text()); + + case 13 /* NumericLiteral */: + var text = expression.text(); + return TypeScript.IntegerUtilities.isInteger(text) || TypeScript.IntegerUtilities.isHexInteger(text); + } + } + + return false; + } + Syntax.isIntegerLiteral = isIntegerLiteral; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var NormalModeFactory = (function () { + function NormalModeFactory() { + } + NormalModeFactory.prototype.sourceUnit = function (moduleElements, endOfFileToken) { + return new TypeScript.SourceUnitSyntax(moduleElements, endOfFileToken, false); + }; + NormalModeFactory.prototype.externalModuleReference = function (requireKeyword, openParenToken, stringLiteral, closeParenToken) { + return new TypeScript.ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, false); + }; + NormalModeFactory.prototype.moduleNameModuleReference = function (moduleName) { + return new TypeScript.ModuleNameModuleReferenceSyntax(moduleName, false); + }; + NormalModeFactory.prototype.importDeclaration = function (modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new TypeScript.ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, false); + }; + NormalModeFactory.prototype.exportAssignment = function (exportKeyword, equalsToken, identifier, semicolonToken) { + return new TypeScript.ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.classDeclaration = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + return new TypeScript.ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.interfaceDeclaration = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + return new TypeScript.InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, false); + }; + NormalModeFactory.prototype.heritageClause = function (kind, extendsOrImplementsKeyword, typeNames) { + return new TypeScript.HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, false); + }; + NormalModeFactory.prototype.moduleDeclaration = function (modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + return new TypeScript.ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.functionDeclaration = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + return new TypeScript.FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.variableStatement = function (modifiers, variableDeclaration, semicolonToken) { + return new TypeScript.VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, false); + }; + NormalModeFactory.prototype.variableDeclaration = function (varKeyword, variableDeclarators) { + return new TypeScript.VariableDeclarationSyntax(varKeyword, variableDeclarators, false); + }; + NormalModeFactory.prototype.variableDeclarator = function (propertyName, typeAnnotation, equalsValueClause) { + return new TypeScript.VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, false); + }; + NormalModeFactory.prototype.equalsValueClause = function (equalsToken, value) { + return new TypeScript.EqualsValueClauseSyntax(equalsToken, value, false); + }; + NormalModeFactory.prototype.prefixUnaryExpression = function (kind, operatorToken, operand) { + return new TypeScript.PrefixUnaryExpressionSyntax(kind, operatorToken, operand, false); + }; + NormalModeFactory.prototype.arrayLiteralExpression = function (openBracketToken, expressions, closeBracketToken) { + return new TypeScript.ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, false); + }; + NormalModeFactory.prototype.omittedExpression = function () { + return new TypeScript.OmittedExpressionSyntax(false); + }; + NormalModeFactory.prototype.parenthesizedExpression = function (openParenToken, expression, closeParenToken) { + return new TypeScript.ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, false); + }; + NormalModeFactory.prototype.simpleArrowFunctionExpression = function (identifier, equalsGreaterThanToken, block, expression) { + return new TypeScript.SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, false); + }; + NormalModeFactory.prototype.parenthesizedArrowFunctionExpression = function (callSignature, equalsGreaterThanToken, block, expression) { + return new TypeScript.ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, false); + }; + NormalModeFactory.prototype.qualifiedName = function (left, dotToken, right) { + return new TypeScript.QualifiedNameSyntax(left, dotToken, right, false); + }; + NormalModeFactory.prototype.typeArgumentList = function (lessThanToken, typeArguments, greaterThanToken) { + return new TypeScript.TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, false); + }; + NormalModeFactory.prototype.constructorType = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, false); + }; + NormalModeFactory.prototype.functionType = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, false); + }; + NormalModeFactory.prototype.objectType = function (openBraceToken, typeMembers, closeBraceToken) { + return new TypeScript.ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, false); + }; + NormalModeFactory.prototype.arrayType = function (type, openBracketToken, closeBracketToken) { + return new TypeScript.ArrayTypeSyntax(type, openBracketToken, closeBracketToken, false); + }; + NormalModeFactory.prototype.genericType = function (name, typeArgumentList) { + return new TypeScript.GenericTypeSyntax(name, typeArgumentList, false); + }; + NormalModeFactory.prototype.typeQuery = function (typeOfKeyword, name) { + return new TypeScript.TypeQuerySyntax(typeOfKeyword, name, false); + }; + NormalModeFactory.prototype.typeAnnotation = function (colonToken, type) { + return new TypeScript.TypeAnnotationSyntax(colonToken, type, false); + }; + NormalModeFactory.prototype.block = function (openBraceToken, statements, closeBraceToken) { + return new TypeScript.BlockSyntax(openBraceToken, statements, closeBraceToken, false); + }; + NormalModeFactory.prototype.parameter = function (dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + return new TypeScript.ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, false); + }; + NormalModeFactory.prototype.memberAccessExpression = function (expression, dotToken, name) { + return new TypeScript.MemberAccessExpressionSyntax(expression, dotToken, name, false); + }; + NormalModeFactory.prototype.postfixUnaryExpression = function (kind, operand, operatorToken) { + return new TypeScript.PostfixUnaryExpressionSyntax(kind, operand, operatorToken, false); + }; + NormalModeFactory.prototype.elementAccessExpression = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + return new TypeScript.ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, false); + }; + NormalModeFactory.prototype.invocationExpression = function (expression, argumentList) { + return new TypeScript.InvocationExpressionSyntax(expression, argumentList, false); + }; + NormalModeFactory.prototype.argumentList = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + return new TypeScript.ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, false); + }; + NormalModeFactory.prototype.binaryExpression = function (kind, left, operatorToken, right) { + return new TypeScript.BinaryExpressionSyntax(kind, left, operatorToken, right, false); + }; + NormalModeFactory.prototype.conditionalExpression = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + return new TypeScript.ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, false); + }; + NormalModeFactory.prototype.constructSignature = function (newKeyword, callSignature) { + return new TypeScript.ConstructSignatureSyntax(newKeyword, callSignature, false); + }; + NormalModeFactory.prototype.methodSignature = function (propertyName, questionToken, callSignature) { + return new TypeScript.MethodSignatureSyntax(propertyName, questionToken, callSignature, false); + }; + NormalModeFactory.prototype.indexSignature = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + return new TypeScript.IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, false); + }; + NormalModeFactory.prototype.propertySignature = function (propertyName, questionToken, typeAnnotation) { + return new TypeScript.PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, false); + }; + NormalModeFactory.prototype.callSignature = function (typeParameterList, parameterList, typeAnnotation) { + return new TypeScript.CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, false); + }; + NormalModeFactory.prototype.parameterList = function (openParenToken, parameters, closeParenToken) { + return new TypeScript.ParameterListSyntax(openParenToken, parameters, closeParenToken, false); + }; + NormalModeFactory.prototype.typeParameterList = function (lessThanToken, typeParameters, greaterThanToken) { + return new TypeScript.TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, false); + }; + NormalModeFactory.prototype.typeParameter = function (identifier, constraint) { + return new TypeScript.TypeParameterSyntax(identifier, constraint, false); + }; + NormalModeFactory.prototype.constraint = function (extendsKeyword, type) { + return new TypeScript.ConstraintSyntax(extendsKeyword, type, false); + }; + NormalModeFactory.prototype.elseClause = function (elseKeyword, statement) { + return new TypeScript.ElseClauseSyntax(elseKeyword, statement, false); + }; + NormalModeFactory.prototype.ifStatement = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + return new TypeScript.IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, false); + }; + NormalModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { + return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, false); + }; + NormalModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { + return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.getAccessor = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + return new TypeScript.GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, false); + }; + NormalModeFactory.prototype.setAccessor = function (modifiers, setKeyword, propertyName, parameterList, block) { + return new TypeScript.SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, false); + }; + NormalModeFactory.prototype.memberVariableDeclaration = function (modifiers, variableDeclarator, semicolonToken) { + return new TypeScript.MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, false); + }; + NormalModeFactory.prototype.indexMemberDeclaration = function (modifiers, indexSignature, semicolonToken) { + return new TypeScript.IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, false); + }; + NormalModeFactory.prototype.throwStatement = function (throwKeyword, expression, semicolonToken) { + return new TypeScript.ThrowStatementSyntax(throwKeyword, expression, semicolonToken, false); + }; + NormalModeFactory.prototype.returnStatement = function (returnKeyword, expression, semicolonToken) { + return new TypeScript.ReturnStatementSyntax(returnKeyword, expression, semicolonToken, false); + }; + NormalModeFactory.prototype.objectCreationExpression = function (newKeyword, expression, argumentList) { + return new TypeScript.ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, false); + }; + NormalModeFactory.prototype.switchStatement = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + return new TypeScript.SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, false); + }; + NormalModeFactory.prototype.caseSwitchClause = function (caseKeyword, expression, colonToken, statements) { + return new TypeScript.CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, false); + }; + NormalModeFactory.prototype.defaultSwitchClause = function (defaultKeyword, colonToken, statements) { + return new TypeScript.DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, false); + }; + NormalModeFactory.prototype.breakStatement = function (breakKeyword, identifier, semicolonToken) { + return new TypeScript.BreakStatementSyntax(breakKeyword, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.continueStatement = function (continueKeyword, identifier, semicolonToken) { + return new TypeScript.ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.forStatement = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + return new TypeScript.ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.forInStatement = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + return new TypeScript.ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.whileStatement = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.withStatement = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.enumDeclaration = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + return new TypeScript.EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.enumElement = function (propertyName, equalsValueClause) { + return new TypeScript.EnumElementSyntax(propertyName, equalsValueClause, false); + }; + NormalModeFactory.prototype.castExpression = function (lessThanToken, type, greaterThanToken, expression) { + return new TypeScript.CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, false); + }; + NormalModeFactory.prototype.objectLiteralExpression = function (openBraceToken, propertyAssignments, closeBraceToken) { + return new TypeScript.ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, false); + }; + NormalModeFactory.prototype.simplePropertyAssignment = function (propertyName, colonToken, expression) { + return new TypeScript.SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, false); + }; + NormalModeFactory.prototype.functionPropertyAssignment = function (propertyName, callSignature, block) { + return new TypeScript.FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, false); + }; + NormalModeFactory.prototype.functionExpression = function (functionKeyword, identifier, callSignature, block) { + return new TypeScript.FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, false); + }; + NormalModeFactory.prototype.emptyStatement = function (semicolonToken) { + return new TypeScript.EmptyStatementSyntax(semicolonToken, false); + }; + NormalModeFactory.prototype.tryStatement = function (tryKeyword, block, catchClause, finallyClause) { + return new TypeScript.TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, false); + }; + NormalModeFactory.prototype.catchClause = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + return new TypeScript.CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, false); + }; + NormalModeFactory.prototype.finallyClause = function (finallyKeyword, block) { + return new TypeScript.FinallyClauseSyntax(finallyKeyword, block, false); + }; + NormalModeFactory.prototype.labeledStatement = function (identifier, colonToken, statement) { + return new TypeScript.LabeledStatementSyntax(identifier, colonToken, statement, false); + }; + NormalModeFactory.prototype.doStatement = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + return new TypeScript.DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, false); + }; + NormalModeFactory.prototype.typeOfExpression = function (typeOfKeyword, expression) { + return new TypeScript.TypeOfExpressionSyntax(typeOfKeyword, expression, false); + }; + NormalModeFactory.prototype.deleteExpression = function (deleteKeyword, expression) { + return new TypeScript.DeleteExpressionSyntax(deleteKeyword, expression, false); + }; + NormalModeFactory.prototype.voidExpression = function (voidKeyword, expression) { + return new TypeScript.VoidExpressionSyntax(voidKeyword, expression, false); + }; + NormalModeFactory.prototype.debuggerStatement = function (debuggerKeyword, semicolonToken) { + return new TypeScript.DebuggerStatementSyntax(debuggerKeyword, semicolonToken, false); + }; + return NormalModeFactory; + })(); + Syntax.NormalModeFactory = NormalModeFactory; + + var StrictModeFactory = (function () { + function StrictModeFactory() { + } + StrictModeFactory.prototype.sourceUnit = function (moduleElements, endOfFileToken) { + return new TypeScript.SourceUnitSyntax(moduleElements, endOfFileToken, true); + }; + StrictModeFactory.prototype.externalModuleReference = function (requireKeyword, openParenToken, stringLiteral, closeParenToken) { + return new TypeScript.ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, true); + }; + StrictModeFactory.prototype.moduleNameModuleReference = function (moduleName) { + return new TypeScript.ModuleNameModuleReferenceSyntax(moduleName, true); + }; + StrictModeFactory.prototype.importDeclaration = function (modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new TypeScript.ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, true); + }; + StrictModeFactory.prototype.exportAssignment = function (exportKeyword, equalsToken, identifier, semicolonToken) { + return new TypeScript.ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.classDeclaration = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + return new TypeScript.ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.interfaceDeclaration = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + return new TypeScript.InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, true); + }; + StrictModeFactory.prototype.heritageClause = function (kind, extendsOrImplementsKeyword, typeNames) { + return new TypeScript.HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, true); + }; + StrictModeFactory.prototype.moduleDeclaration = function (modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + return new TypeScript.ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.functionDeclaration = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + return new TypeScript.FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.variableStatement = function (modifiers, variableDeclaration, semicolonToken) { + return new TypeScript.VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, true); + }; + StrictModeFactory.prototype.variableDeclaration = function (varKeyword, variableDeclarators) { + return new TypeScript.VariableDeclarationSyntax(varKeyword, variableDeclarators, true); + }; + StrictModeFactory.prototype.variableDeclarator = function (propertyName, typeAnnotation, equalsValueClause) { + return new TypeScript.VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, true); + }; + StrictModeFactory.prototype.equalsValueClause = function (equalsToken, value) { + return new TypeScript.EqualsValueClauseSyntax(equalsToken, value, true); + }; + StrictModeFactory.prototype.prefixUnaryExpression = function (kind, operatorToken, operand) { + return new TypeScript.PrefixUnaryExpressionSyntax(kind, operatorToken, operand, true); + }; + StrictModeFactory.prototype.arrayLiteralExpression = function (openBracketToken, expressions, closeBracketToken) { + return new TypeScript.ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, true); + }; + StrictModeFactory.prototype.omittedExpression = function () { + return new TypeScript.OmittedExpressionSyntax(true); + }; + StrictModeFactory.prototype.parenthesizedExpression = function (openParenToken, expression, closeParenToken) { + return new TypeScript.ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, true); + }; + StrictModeFactory.prototype.simpleArrowFunctionExpression = function (identifier, equalsGreaterThanToken, block, expression) { + return new TypeScript.SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, true); + }; + StrictModeFactory.prototype.parenthesizedArrowFunctionExpression = function (callSignature, equalsGreaterThanToken, block, expression) { + return new TypeScript.ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, true); + }; + StrictModeFactory.prototype.qualifiedName = function (left, dotToken, right) { + return new TypeScript.QualifiedNameSyntax(left, dotToken, right, true); + }; + StrictModeFactory.prototype.typeArgumentList = function (lessThanToken, typeArguments, greaterThanToken) { + return new TypeScript.TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, true); + }; + StrictModeFactory.prototype.constructorType = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, true); + }; + StrictModeFactory.prototype.functionType = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, true); + }; + StrictModeFactory.prototype.objectType = function (openBraceToken, typeMembers, closeBraceToken) { + return new TypeScript.ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, true); + }; + StrictModeFactory.prototype.arrayType = function (type, openBracketToken, closeBracketToken) { + return new TypeScript.ArrayTypeSyntax(type, openBracketToken, closeBracketToken, true); + }; + StrictModeFactory.prototype.genericType = function (name, typeArgumentList) { + return new TypeScript.GenericTypeSyntax(name, typeArgumentList, true); + }; + StrictModeFactory.prototype.typeQuery = function (typeOfKeyword, name) { + return new TypeScript.TypeQuerySyntax(typeOfKeyword, name, true); + }; + StrictModeFactory.prototype.typeAnnotation = function (colonToken, type) { + return new TypeScript.TypeAnnotationSyntax(colonToken, type, true); + }; + StrictModeFactory.prototype.block = function (openBraceToken, statements, closeBraceToken) { + return new TypeScript.BlockSyntax(openBraceToken, statements, closeBraceToken, true); + }; + StrictModeFactory.prototype.parameter = function (dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + return new TypeScript.ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, true); + }; + StrictModeFactory.prototype.memberAccessExpression = function (expression, dotToken, name) { + return new TypeScript.MemberAccessExpressionSyntax(expression, dotToken, name, true); + }; + StrictModeFactory.prototype.postfixUnaryExpression = function (kind, operand, operatorToken) { + return new TypeScript.PostfixUnaryExpressionSyntax(kind, operand, operatorToken, true); + }; + StrictModeFactory.prototype.elementAccessExpression = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + return new TypeScript.ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, true); + }; + StrictModeFactory.prototype.invocationExpression = function (expression, argumentList) { + return new TypeScript.InvocationExpressionSyntax(expression, argumentList, true); + }; + StrictModeFactory.prototype.argumentList = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + return new TypeScript.ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, true); + }; + StrictModeFactory.prototype.binaryExpression = function (kind, left, operatorToken, right) { + return new TypeScript.BinaryExpressionSyntax(kind, left, operatorToken, right, true); + }; + StrictModeFactory.prototype.conditionalExpression = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + return new TypeScript.ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, true); + }; + StrictModeFactory.prototype.constructSignature = function (newKeyword, callSignature) { + return new TypeScript.ConstructSignatureSyntax(newKeyword, callSignature, true); + }; + StrictModeFactory.prototype.methodSignature = function (propertyName, questionToken, callSignature) { + return new TypeScript.MethodSignatureSyntax(propertyName, questionToken, callSignature, true); + }; + StrictModeFactory.prototype.indexSignature = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + return new TypeScript.IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, true); + }; + StrictModeFactory.prototype.propertySignature = function (propertyName, questionToken, typeAnnotation) { + return new TypeScript.PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, true); + }; + StrictModeFactory.prototype.callSignature = function (typeParameterList, parameterList, typeAnnotation) { + return new TypeScript.CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, true); + }; + StrictModeFactory.prototype.parameterList = function (openParenToken, parameters, closeParenToken) { + return new TypeScript.ParameterListSyntax(openParenToken, parameters, closeParenToken, true); + }; + StrictModeFactory.prototype.typeParameterList = function (lessThanToken, typeParameters, greaterThanToken) { + return new TypeScript.TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, true); + }; + StrictModeFactory.prototype.typeParameter = function (identifier, constraint) { + return new TypeScript.TypeParameterSyntax(identifier, constraint, true); + }; + StrictModeFactory.prototype.constraint = function (extendsKeyword, type) { + return new TypeScript.ConstraintSyntax(extendsKeyword, type, true); + }; + StrictModeFactory.prototype.elseClause = function (elseKeyword, statement) { + return new TypeScript.ElseClauseSyntax(elseKeyword, statement, true); + }; + StrictModeFactory.prototype.ifStatement = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + return new TypeScript.IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, true); + }; + StrictModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { + return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, true); + }; + StrictModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { + return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.getAccessor = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + return new TypeScript.GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, true); + }; + StrictModeFactory.prototype.setAccessor = function (modifiers, setKeyword, propertyName, parameterList, block) { + return new TypeScript.SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, true); + }; + StrictModeFactory.prototype.memberVariableDeclaration = function (modifiers, variableDeclarator, semicolonToken) { + return new TypeScript.MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, true); + }; + StrictModeFactory.prototype.indexMemberDeclaration = function (modifiers, indexSignature, semicolonToken) { + return new TypeScript.IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, true); + }; + StrictModeFactory.prototype.throwStatement = function (throwKeyword, expression, semicolonToken) { + return new TypeScript.ThrowStatementSyntax(throwKeyword, expression, semicolonToken, true); + }; + StrictModeFactory.prototype.returnStatement = function (returnKeyword, expression, semicolonToken) { + return new TypeScript.ReturnStatementSyntax(returnKeyword, expression, semicolonToken, true); + }; + StrictModeFactory.prototype.objectCreationExpression = function (newKeyword, expression, argumentList) { + return new TypeScript.ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, true); + }; + StrictModeFactory.prototype.switchStatement = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + return new TypeScript.SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, true); + }; + StrictModeFactory.prototype.caseSwitchClause = function (caseKeyword, expression, colonToken, statements) { + return new TypeScript.CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, true); + }; + StrictModeFactory.prototype.defaultSwitchClause = function (defaultKeyword, colonToken, statements) { + return new TypeScript.DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, true); + }; + StrictModeFactory.prototype.breakStatement = function (breakKeyword, identifier, semicolonToken) { + return new TypeScript.BreakStatementSyntax(breakKeyword, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.continueStatement = function (continueKeyword, identifier, semicolonToken) { + return new TypeScript.ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.forStatement = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + return new TypeScript.ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.forInStatement = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + return new TypeScript.ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.whileStatement = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.withStatement = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.enumDeclaration = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + return new TypeScript.EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.enumElement = function (propertyName, equalsValueClause) { + return new TypeScript.EnumElementSyntax(propertyName, equalsValueClause, true); + }; + StrictModeFactory.prototype.castExpression = function (lessThanToken, type, greaterThanToken, expression) { + return new TypeScript.CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, true); + }; + StrictModeFactory.prototype.objectLiteralExpression = function (openBraceToken, propertyAssignments, closeBraceToken) { + return new TypeScript.ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, true); + }; + StrictModeFactory.prototype.simplePropertyAssignment = function (propertyName, colonToken, expression) { + return new TypeScript.SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, true); + }; + StrictModeFactory.prototype.functionPropertyAssignment = function (propertyName, callSignature, block) { + return new TypeScript.FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, true); + }; + StrictModeFactory.prototype.functionExpression = function (functionKeyword, identifier, callSignature, block) { + return new TypeScript.FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, true); + }; + StrictModeFactory.prototype.emptyStatement = function (semicolonToken) { + return new TypeScript.EmptyStatementSyntax(semicolonToken, true); + }; + StrictModeFactory.prototype.tryStatement = function (tryKeyword, block, catchClause, finallyClause) { + return new TypeScript.TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, true); + }; + StrictModeFactory.prototype.catchClause = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + return new TypeScript.CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, true); + }; + StrictModeFactory.prototype.finallyClause = function (finallyKeyword, block) { + return new TypeScript.FinallyClauseSyntax(finallyKeyword, block, true); + }; + StrictModeFactory.prototype.labeledStatement = function (identifier, colonToken, statement) { + return new TypeScript.LabeledStatementSyntax(identifier, colonToken, statement, true); + }; + StrictModeFactory.prototype.doStatement = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + return new TypeScript.DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, true); + }; + StrictModeFactory.prototype.typeOfExpression = function (typeOfKeyword, expression) { + return new TypeScript.TypeOfExpressionSyntax(typeOfKeyword, expression, true); + }; + StrictModeFactory.prototype.deleteExpression = function (deleteKeyword, expression) { + return new TypeScript.DeleteExpressionSyntax(deleteKeyword, expression, true); + }; + StrictModeFactory.prototype.voidExpression = function (voidKeyword, expression) { + return new TypeScript.VoidExpressionSyntax(voidKeyword, expression, true); + }; + StrictModeFactory.prototype.debuggerStatement = function (debuggerKeyword, semicolonToken) { + return new TypeScript.DebuggerStatementSyntax(debuggerKeyword, semicolonToken, true); + }; + return StrictModeFactory; + })(); + Syntax.StrictModeFactory = StrictModeFactory; + + Syntax.normalModeFactory = new NormalModeFactory(); + Syntax.strictModeFactory = new StrictModeFactory(); + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxFacts) { + function isDirectivePrologueElement(node) { + if (node.kind() === 149 /* ExpressionStatement */) { + var expressionStatement = node; + var expression = expressionStatement.expression; + + if (expression.kind() === 14 /* StringLiteral */) { + return true; + } + } + + return false; + } + SyntaxFacts.isDirectivePrologueElement = isDirectivePrologueElement; + + function isUseStrictDirective(node) { + var expressionStatement = node; + var stringLiteral = expressionStatement.expression; + + var text = stringLiteral.text(); + return text === '"use strict"' || text === "'use strict'"; + } + SyntaxFacts.isUseStrictDirective = isUseStrictDirective; + + function isIdentifierNameOrAnyKeyword(token) { + var tokenKind = token.tokenKind; + return tokenKind === 11 /* IdentifierName */ || SyntaxFacts.isAnyKeyword(tokenKind); + } + SyntaxFacts.isIdentifierNameOrAnyKeyword = isIdentifierNameOrAnyKeyword; + })(TypeScript.SyntaxFacts || (TypeScript.SyntaxFacts = {})); + var SyntaxFacts = TypeScript.SyntaxFacts; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var EmptySyntaxList = (function () { + function EmptySyntaxList() { + } + EmptySyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + EmptySyntaxList.prototype.isNode = function () { + return false; + }; + EmptySyntaxList.prototype.isToken = function () { + return false; + }; + EmptySyntaxList.prototype.isList = function () { + return true; + }; + EmptySyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + EmptySyntaxList.prototype.toJSON = function (key) { + return []; + }; + + EmptySyntaxList.prototype.childCount = function () { + return 0; + }; + + EmptySyntaxList.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySyntaxList.prototype.toArray = function () { + return []; + }; + + EmptySyntaxList.prototype.collectTextElements = function (elements) { + }; + + EmptySyntaxList.prototype.firstToken = function () { + return null; + }; + + EmptySyntaxList.prototype.lastToken = function () { + return null; + }; + + EmptySyntaxList.prototype.fullWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.width = function () { + return 0; + }; + + EmptySyntaxList.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySyntaxList.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySyntaxList.prototype.leadingTriviaWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.trailingTriviaWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.fullText = function () { + return ""; + }; + + EmptySyntaxList.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptySyntaxList.prototype.isIncrementallyUnusable = function () { + return false; + }; + + EmptySyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + throw TypeScript.Errors.invalidOperation(); + }; + + EmptySyntaxList.prototype.insertChildrenInto = function (array, index) { + }; + return EmptySyntaxList; + })(); + Syntax.EmptySyntaxList = EmptySyntaxList; + + Syntax.emptyList = new EmptySyntaxList(); + + var SingletonSyntaxList = (function () { + function SingletonSyntaxList(item) { + this.item = item; + } + SingletonSyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + SingletonSyntaxList.prototype.isToken = function () { + return false; + }; + SingletonSyntaxList.prototype.isNode = function () { + return false; + }; + SingletonSyntaxList.prototype.isList = function () { + return true; + }; + SingletonSyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + SingletonSyntaxList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSyntaxList.prototype.childCount = function () { + return 1; + }; + + SingletonSyntaxList.prototype.childAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSyntaxList.prototype.toArray = function () { + return [this.item]; + }; + + SingletonSyntaxList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSyntaxList.prototype.firstToken = function () { + return this.item.firstToken(); + }; + + SingletonSyntaxList.prototype.lastToken = function () { + return this.item.lastToken(); + }; + + SingletonSyntaxList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSyntaxList.prototype.width = function () { + return this.item.width(); + }; + + SingletonSyntaxList.prototype.leadingTrivia = function () { + return this.item.leadingTrivia(); + }; + + SingletonSyntaxList.prototype.trailingTrivia = function () { + return this.item.trailingTrivia(); + }; + + SingletonSyntaxList.prototype.leadingTriviaWidth = function () { + return this.item.leadingTriviaWidth(); + }; + + SingletonSyntaxList.prototype.trailingTriviaWidth = function () { + return this.item.trailingTriviaWidth(); + }; + + SingletonSyntaxList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSyntaxList.prototype.isTypeScriptSpecific = function () { + return this.item.isTypeScriptSpecific(); + }; + + SingletonSyntaxList.prototype.isIncrementallyUnusable = function () { + return this.item.isIncrementallyUnusable(); + }; + + SingletonSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + return this.item.findTokenInternal(new TypeScript.PositionedList(parent, this, fullStart), position, fullStart); + }; + + SingletonSyntaxList.prototype.insertChildrenInto = function (array, index) { + array.splice(index, 0, this.item); + }; + return SingletonSyntaxList; + })(); + + var NormalSyntaxList = (function () { + function NormalSyntaxList(nodeOrTokens) { + this._data = 0; + this.nodeOrTokens = nodeOrTokens; + } + NormalSyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + NormalSyntaxList.prototype.isNode = function () { + return false; + }; + NormalSyntaxList.prototype.isToken = function () { + return false; + }; + NormalSyntaxList.prototype.isList = function () { + return true; + }; + NormalSyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + NormalSyntaxList.prototype.toJSON = function (key) { + return this.nodeOrTokens; + }; + + NormalSyntaxList.prototype.childCount = function () { + return this.nodeOrTokens.length; + }; + + NormalSyntaxList.prototype.childAt = function (index) { + if (index < 0 || index >= this.nodeOrTokens.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.nodeOrTokens[index]; + }; + + NormalSyntaxList.prototype.toArray = function () { + return this.nodeOrTokens.slice(0); + }; + + NormalSyntaxList.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var element = this.nodeOrTokens[i]; + element.collectTextElements(elements); + } + }; + + NormalSyntaxList.prototype.firstToken = function () { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var token = this.nodeOrTokens[i].firstToken(); + if (token !== null) { + return token; + } + } + + return null; + }; + + NormalSyntaxList.prototype.lastToken = function () { + for (var i = this.nodeOrTokens.length - 1; i >= 0; i--) { + var token = this.nodeOrTokens[i].lastToken(); + if (token !== null) { + return token; + } + } + + return null; + }; + + NormalSyntaxList.prototype.fullText = function () { + var elements = new Array(); + this.collectTextElements(elements); + return elements.join(""); + }; + + NormalSyntaxList.prototype.isTypeScriptSpecific = function () { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + if (this.nodeOrTokens[i].isTypeScriptSpecific()) { + return true; + } + } + + return false; + }; + + NormalSyntaxList.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + NormalSyntaxList.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + NormalSyntaxList.prototype.width = function () { + var fullWidth = this.fullWidth(); + return fullWidth - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + NormalSyntaxList.prototype.leadingTrivia = function () { + return this.firstToken().leadingTrivia(); + }; + + NormalSyntaxList.prototype.trailingTrivia = function () { + return this.lastToken().trailingTrivia(); + }; + + NormalSyntaxList.prototype.leadingTriviaWidth = function () { + return this.firstToken().leadingTriviaWidth(); + }; + + NormalSyntaxList.prototype.trailingTriviaWidth = function () { + return this.lastToken().trailingTriviaWidth(); + }; + + NormalSyntaxList.prototype.computeData = function () { + var fullWidth = 0; + var isIncrementallyUnusable = false; + + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var node = this.nodeOrTokens[i]; + fullWidth += node.fullWidth(); + isIncrementallyUnusable = isIncrementallyUnusable || node.isIncrementallyUnusable(); + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + NormalSyntaxList.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data = this.computeData(); + } + + return this._data; + }; + + NormalSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedList(parent, this, fullStart); + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var nodeOrToken = this.nodeOrTokens[i]; + + var childWidth = nodeOrToken.fullWidth(); + if (position < childWidth) { + return nodeOrToken.findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + NormalSyntaxList.prototype.insertChildrenInto = function (array, index) { + if (index === 0) { + array.unshift.apply(array, this.nodeOrTokens); + } else { + array.splice.apply(array, [index, 0].concat(this.nodeOrTokens)); + } + }; + return NormalSyntaxList; + })(); + + function list(nodes) { + if (nodes === undefined || nodes === null || nodes.length === 0) { + return Syntax.emptyList; + } + + if (nodes.length === 1) { + var item = nodes[0]; + return new SingletonSyntaxList(item); + } + + return new NormalSyntaxList(nodes); + } + Syntax.list = list; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxNode = (function () { + function SyntaxNode(parsedInStrictMode) { + this._data = parsedInStrictMode ? 4 /* NodeParsedInStrictModeMask */ : 0; + } + SyntaxNode.prototype.isNode = function () { + return true; + }; + SyntaxNode.prototype.isToken = function () { + return false; + }; + SyntaxNode.prototype.isList = function () { + return false; + }; + SyntaxNode.prototype.isSeparatedList = function () { + return false; + }; + + SyntaxNode.prototype.kind = function () { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.childCount = function () { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.childAt = function (slot) { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.firstToken = function () { + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + if (element.fullWidth() > 0 || element.kind() === 10 /* EndOfFileToken */) { + return element.firstToken(); + } + } + } + + return null; + }; + + SyntaxNode.prototype.lastToken = function () { + for (var i = this.childCount() - 1; i >= 0; i--) { + var element = this.childAt(i); + + if (element !== null) { + if (element.fullWidth() > 0 || element.kind() === 10 /* EndOfFileToken */) { + return element.lastToken(); + } + } + } + + return null; + }; + + SyntaxNode.prototype.insertChildrenInto = function (array, index) { + for (var i = this.childCount() - 1; i >= 0; i--) { + var element = this.childAt(i); + + if (element !== null) { + if (element.isNode() || element.isToken()) { + array.splice(index, 0, element); + } else if (element.isList()) { + element.insertChildrenInto(array, index); + } else if (element.isSeparatedList()) { + element.insertChildrenInto(array, index); + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + } + }; + + SyntaxNode.prototype.leadingTrivia = function () { + var firstToken = this.firstToken(); + return firstToken ? firstToken.leadingTrivia() : TypeScript.Syntax.emptyTriviaList; + }; + + SyntaxNode.prototype.trailingTrivia = function () { + var lastToken = this.lastToken(); + return lastToken ? lastToken.trailingTrivia() : TypeScript.Syntax.emptyTriviaList; + }; + + SyntaxNode.prototype.toJSON = function (key) { + var result = { + kind: TypeScript.SyntaxKind[this.kind()], + fullWidth: this.fullWidth() + }; + + if (this.isIncrementallyUnusable()) { + result.isIncrementallyUnusable = true; + } + + if (this.parsedInStrictMode()) { + result.parsedInStrictMode = true; + } + + var thisAsIndexable = this; + for (var i = 0, n = this.childCount(); i < n; i++) { + var value = this.childAt(i); + + if (value) { + for (var name in this) { + if (value === thisAsIndexable[name]) { + result[name] = value; + break; + } + } + } + } + + return result; + }; + + SyntaxNode.prototype.accept = function (visitor) { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.fullText = function () { + var elements = []; + this.collectTextElements(elements); + return elements.join(""); + }; + + SyntaxNode.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + element.collectTextElements(elements); + } + } + }; + + SyntaxNode.prototype.replaceToken = function (token1, token2) { + if (token1 === token2) { + return this; + } + + return this.accept(new TypeScript.SyntaxTokenReplacer(token1, token2)); + }; + + SyntaxNode.prototype.withLeadingTrivia = function (trivia) { + return this.replaceToken(this.firstToken(), this.firstToken().withLeadingTrivia(trivia)); + }; + + SyntaxNode.prototype.withTrailingTrivia = function (trivia) { + return this.replaceToken(this.lastToken(), this.lastToken().withTrailingTrivia(trivia)); + }; + + SyntaxNode.prototype.hasLeadingTrivia = function () { + return this.lastToken().hasLeadingTrivia(); + }; + + SyntaxNode.prototype.hasTrailingTrivia = function () { + return this.lastToken().hasTrailingTrivia(); + }; + + SyntaxNode.prototype.isTypeScriptSpecific = function () { + return false; + }; + + SyntaxNode.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + SyntaxNode.prototype.parsedInStrictMode = function () { + return (this.data() & 4 /* NodeParsedInStrictModeMask */) !== 0; + }; + + SyntaxNode.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + SyntaxNode.prototype.computeData = function () { + var slotCount = this.childCount(); + + var fullWidth = 0; + var childWidth = 0; + + var isIncrementallyUnusable = ((this._data & 2 /* NodeIncrementallyUnusableMask */) !== 0) || slotCount === 0; + + for (var i = 0, n = slotCount; i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + childWidth = element.fullWidth(); + fullWidth += childWidth; + + if (!isIncrementallyUnusable) { + isIncrementallyUnusable = element.isIncrementallyUnusable(); + } + } + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + SyntaxNode.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data |= this.computeData(); + } + + return this._data; + }; + + SyntaxNode.prototype.findToken = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var endOfFileToken = this.tryGetEndOfFileAt(position); + if (endOfFileToken !== null) { + return endOfFileToken; + } + + if (position < 0 || position >= this.fullWidth()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var positionedToken = this.findTokenInternal(null, position, 0); + + if (includeSkippedTokens) { + return TypeScript.Syntax.findSkippedTokenInPositionedToken(positionedToken, position) || positionedToken; + } + + return positionedToken; + }; + + SyntaxNode.prototype.tryGetEndOfFileAt = function (position) { + if (this.kind() === 120 /* SourceUnit */ && position === this.fullWidth()) { + var sourceUnit = this; + return new TypeScript.PositionedToken(new TypeScript.PositionedNode(null, sourceUnit, 0), sourceUnit.endOfFileToken, sourceUnit.moduleElements.fullWidth()); + } + + return null; + }; + + SyntaxNode.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedNode(parent, this, fullStart); + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + var childWidth = element.fullWidth(); + + if (position < childWidth) { + return element.findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + } + + throw TypeScript.Errors.invalidOperation(); + }; + + SyntaxNode.prototype.findTokenOnLeft = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var positionedToken = this.findToken(position, false); + var start = positionedToken.start(); + + if (includeSkippedTokens) { + positionedToken = TypeScript.Syntax.findSkippedTokenOnLeft(positionedToken, position) || positionedToken; + } + + if (position > start) { + return positionedToken; + } + + if (positionedToken.fullStart() === 0) { + return null; + } + + return positionedToken.previousToken(includeSkippedTokens); + }; + + SyntaxNode.prototype.findCompleteTokenOnLeft = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var positionedToken = this.findToken(position, false); + + if (includeSkippedTokens) { + positionedToken = TypeScript.Syntax.findSkippedTokenOnLeft(positionedToken, position) || positionedToken; + } + + if (positionedToken.token().width() > 0 && position >= positionedToken.end()) { + return positionedToken; + } + + return positionedToken.previousToken(includeSkippedTokens); + }; + + SyntaxNode.prototype.isModuleElement = function () { + return false; + }; + + SyntaxNode.prototype.isClassElement = function () { + return false; + }; + + SyntaxNode.prototype.isTypeMember = function () { + return false; + }; + + SyntaxNode.prototype.isStatement = function () { + return false; + }; + + SyntaxNode.prototype.isExpression = function () { + return false; + }; + + SyntaxNode.prototype.isSwitchClause = function () { + return false; + }; + + SyntaxNode.prototype.structuralEquals = function (node) { + if (this === node) { + return true; + } + if (node === null) { + return false; + } + if (this.kind() !== node.kind()) { + return false; + } + + for (var i = 0, n = this.childCount(); i < n; i++) { + var element1 = this.childAt(i); + var element2 = node.childAt(i); + + if (!TypeScript.Syntax.elementStructuralEquals(element1, element2)) { + return false; + } + } + + return true; + }; + + SyntaxNode.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + SyntaxNode.prototype.leadingTriviaWidth = function () { + var firstToken = this.firstToken(); + return firstToken === null ? 0 : firstToken.leadingTriviaWidth(); + }; + + SyntaxNode.prototype.trailingTriviaWidth = function () { + var lastToken = this.lastToken(); + return lastToken === null ? 0 : lastToken.trailingTriviaWidth(); + }; + return SyntaxNode; + })(); + TypeScript.SyntaxNode = SyntaxNode; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceUnitSyntax = (function (_super) { + __extends(SourceUnitSyntax, _super); + function SourceUnitSyntax(moduleElements, endOfFileToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.moduleElements = moduleElements; + this.endOfFileToken = endOfFileToken; + } + SourceUnitSyntax.prototype.accept = function (visitor) { + return visitor.visitSourceUnit(this); + }; + + SourceUnitSyntax.prototype.kind = function () { + return 120 /* SourceUnit */; + }; + + SourceUnitSyntax.prototype.childCount = function () { + return 2; + }; + + SourceUnitSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.moduleElements; + case 1: + return this.endOfFileToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SourceUnitSyntax.prototype.update = function (moduleElements, endOfFileToken) { + if (this.moduleElements === moduleElements && this.endOfFileToken === endOfFileToken) { + return this; + } + + return new SourceUnitSyntax(moduleElements, endOfFileToken, this.parsedInStrictMode()); + }; + + SourceUnitSyntax.create = function (endOfFileToken) { + return new SourceUnitSyntax(TypeScript.Syntax.emptyList, endOfFileToken, false); + }; + + SourceUnitSyntax.create1 = function (endOfFileToken) { + return new SourceUnitSyntax(TypeScript.Syntax.emptyList, endOfFileToken, false); + }; + + SourceUnitSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SourceUnitSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SourceUnitSyntax.prototype.withModuleElements = function (moduleElements) { + return this.update(moduleElements, this.endOfFileToken); + }; + + SourceUnitSyntax.prototype.withModuleElement = function (moduleElement) { + return this.withModuleElements(TypeScript.Syntax.list([moduleElement])); + }; + + SourceUnitSyntax.prototype.withEndOfFileToken = function (endOfFileToken) { + return this.update(this.moduleElements, endOfFileToken); + }; + + SourceUnitSyntax.prototype.isTypeScriptSpecific = function () { + if (this.moduleElements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SourceUnitSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SourceUnitSyntax = SourceUnitSyntax; + + var ExternalModuleReferenceSyntax = (function (_super) { + __extends(ExternalModuleReferenceSyntax, _super); + function ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.requireKeyword = requireKeyword; + this.openParenToken = openParenToken; + this.stringLiteral = stringLiteral; + this.closeParenToken = closeParenToken; + } + ExternalModuleReferenceSyntax.prototype.accept = function (visitor) { + return visitor.visitExternalModuleReference(this); + }; + + ExternalModuleReferenceSyntax.prototype.kind = function () { + return 245 /* ExternalModuleReference */; + }; + + ExternalModuleReferenceSyntax.prototype.childCount = function () { + return 4; + }; + + ExternalModuleReferenceSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.requireKeyword; + case 1: + return this.openParenToken; + case 2: + return this.stringLiteral; + case 3: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExternalModuleReferenceSyntax.prototype.isModuleReference = function () { + return true; + }; + + ExternalModuleReferenceSyntax.prototype.update = function (requireKeyword, openParenToken, stringLiteral, closeParenToken) { + if (this.requireKeyword === requireKeyword && this.openParenToken === openParenToken && this.stringLiteral === stringLiteral && this.closeParenToken === closeParenToken) { + return this; + } + + return new ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, this.parsedInStrictMode()); + }; + + ExternalModuleReferenceSyntax.create1 = function (stringLiteral) { + return new ExternalModuleReferenceSyntax(TypeScript.Syntax.token(66 /* RequireKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), stringLiteral, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ExternalModuleReferenceSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExternalModuleReferenceSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExternalModuleReferenceSyntax.prototype.withRequireKeyword = function (requireKeyword) { + return this.update(requireKeyword, this.openParenToken, this.stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.requireKeyword, openParenToken, this.stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withStringLiteral = function (stringLiteral) { + return this.update(this.requireKeyword, this.openParenToken, stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.requireKeyword, this.openParenToken, this.stringLiteral, closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ExternalModuleReferenceSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExternalModuleReferenceSyntax = ExternalModuleReferenceSyntax; + + var ModuleNameModuleReferenceSyntax = (function (_super) { + __extends(ModuleNameModuleReferenceSyntax, _super); + function ModuleNameModuleReferenceSyntax(moduleName, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.moduleName = moduleName; + } + ModuleNameModuleReferenceSyntax.prototype.accept = function (visitor) { + return visitor.visitModuleNameModuleReference(this); + }; + + ModuleNameModuleReferenceSyntax.prototype.kind = function () { + return 246 /* ModuleNameModuleReference */; + }; + + ModuleNameModuleReferenceSyntax.prototype.childCount = function () { + return 1; + }; + + ModuleNameModuleReferenceSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.moduleName; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ModuleNameModuleReferenceSyntax.prototype.isModuleReference = function () { + return true; + }; + + ModuleNameModuleReferenceSyntax.prototype.update = function (moduleName) { + if (this.moduleName === moduleName) { + return this; + } + + return new ModuleNameModuleReferenceSyntax(moduleName, this.parsedInStrictMode()); + }; + + ModuleNameModuleReferenceSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ModuleNameModuleReferenceSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ModuleNameModuleReferenceSyntax.prototype.withModuleName = function (moduleName) { + return this.update(moduleName); + }; + + ModuleNameModuleReferenceSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ModuleNameModuleReferenceSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ModuleNameModuleReferenceSyntax = ModuleNameModuleReferenceSyntax; + + var ImportDeclarationSyntax = (function (_super) { + __extends(ImportDeclarationSyntax, _super); + function ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.importKeyword = importKeyword; + this.identifier = identifier; + this.equalsToken = equalsToken; + this.moduleReference = moduleReference; + this.semicolonToken = semicolonToken; + } + ImportDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitImportDeclaration(this); + }; + + ImportDeclarationSyntax.prototype.kind = function () { + return 133 /* ImportDeclaration */; + }; + + ImportDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + ImportDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.importKeyword; + case 2: + return this.identifier; + case 3: + return this.equalsToken; + case 4: + return this.moduleReference; + case 5: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ImportDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ImportDeclarationSyntax.prototype.update = function (modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + if (this.modifiers === modifiers && this.importKeyword === importKeyword && this.identifier === identifier && this.equalsToken === equalsToken && this.moduleReference === moduleReference && this.semicolonToken === semicolonToken) { + return this; + } + + return new ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, this.parsedInStrictMode()); + }; + + ImportDeclarationSyntax.create = function (importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new ImportDeclarationSyntax(TypeScript.Syntax.emptyList, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, false); + }; + + ImportDeclarationSyntax.create1 = function (identifier, moduleReference) { + return new ImportDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(49 /* ImportKeyword */), identifier, TypeScript.Syntax.token(107 /* EqualsToken */), moduleReference, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ImportDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ImportDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ImportDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.importKeyword, this.identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ImportDeclarationSyntax.prototype.withImportKeyword = function (importKeyword) { + return this.update(this.modifiers, importKeyword, this.identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.importKeyword, identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(this.modifiers, this.importKeyword, this.identifier, equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withModuleReference = function (moduleReference) { + return this.update(this.modifiers, this.importKeyword, this.identifier, this.equalsToken, moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.importKeyword, this.identifier, this.equalsToken, this.moduleReference, semicolonToken); + }; + + ImportDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ImportDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ImportDeclarationSyntax = ImportDeclarationSyntax; + + var ExportAssignmentSyntax = (function (_super) { + __extends(ExportAssignmentSyntax, _super); + function ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.exportKeyword = exportKeyword; + this.equalsToken = equalsToken; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + ExportAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitExportAssignment(this); + }; + + ExportAssignmentSyntax.prototype.kind = function () { + return 134 /* ExportAssignment */; + }; + + ExportAssignmentSyntax.prototype.childCount = function () { + return 4; + }; + + ExportAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.exportKeyword; + case 1: + return this.equalsToken; + case 2: + return this.identifier; + case 3: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExportAssignmentSyntax.prototype.isModuleElement = function () { + return true; + }; + + ExportAssignmentSyntax.prototype.update = function (exportKeyword, equalsToken, identifier, semicolonToken) { + if (this.exportKeyword === exportKeyword && this.equalsToken === equalsToken && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + ExportAssignmentSyntax.create1 = function (identifier) { + return new ExportAssignmentSyntax(TypeScript.Syntax.token(47 /* ExportKeyword */), TypeScript.Syntax.token(107 /* EqualsToken */), identifier, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ExportAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExportAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExportAssignmentSyntax.prototype.withExportKeyword = function (exportKeyword) { + return this.update(exportKeyword, this.equalsToken, this.identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(this.exportKeyword, equalsToken, this.identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.exportKeyword, this.equalsToken, identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.exportKeyword, this.equalsToken, this.identifier, semicolonToken); + }; + + ExportAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ExportAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExportAssignmentSyntax = ExportAssignmentSyntax; + + var ClassDeclarationSyntax = (function (_super) { + __extends(ClassDeclarationSyntax, _super); + function ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.classKeyword = classKeyword; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.openBraceToken = openBraceToken; + this.classElements = classElements; + this.closeBraceToken = closeBraceToken; + } + ClassDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitClassDeclaration(this); + }; + + ClassDeclarationSyntax.prototype.kind = function () { + return 131 /* ClassDeclaration */; + }; + + ClassDeclarationSyntax.prototype.childCount = function () { + return 8; + }; + + ClassDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.classKeyword; + case 2: + return this.identifier; + case 3: + return this.typeParameterList; + case 4: + return this.heritageClauses; + case 5: + return this.openBraceToken; + case 6: + return this.classElements; + case 7: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ClassDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ClassDeclarationSyntax.prototype.update = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + if (this.modifiers === modifiers && this.classKeyword === classKeyword && this.identifier === identifier && this.typeParameterList === typeParameterList && this.heritageClauses === heritageClauses && this.openBraceToken === openBraceToken && this.classElements === classElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, this.parsedInStrictMode()); + }; + + ClassDeclarationSyntax.create = function (classKeyword, identifier, openBraceToken, closeBraceToken) { + return new ClassDeclarationSyntax(TypeScript.Syntax.emptyList, classKeyword, identifier, null, TypeScript.Syntax.emptyList, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + ClassDeclarationSyntax.create1 = function (identifier) { + return new ClassDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(44 /* ClassKeyword */), identifier, null, TypeScript.Syntax.emptyList, TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ClassDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ClassDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ClassDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ClassDeclarationSyntax.prototype.withClassKeyword = function (classKeyword) { + return this.update(this.modifiers, classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.classKeyword, identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.modifiers, this.classKeyword, this.identifier, typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withHeritageClauses = function (heritageClauses) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withHeritageClause = function (heritageClause) { + return this.withHeritageClauses(TypeScript.Syntax.list([heritageClause])); + }; + + ClassDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withClassElements = function (classElements) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withClassElement = function (classElement) { + return this.withClassElements(TypeScript.Syntax.list([classElement])); + }; + + ClassDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ClassDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ClassDeclarationSyntax = ClassDeclarationSyntax; + + var InterfaceDeclarationSyntax = (function (_super) { + __extends(InterfaceDeclarationSyntax, _super); + function InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.interfaceKeyword = interfaceKeyword; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.body = body; + } + InterfaceDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitInterfaceDeclaration(this); + }; + + InterfaceDeclarationSyntax.prototype.kind = function () { + return 128 /* InterfaceDeclaration */; + }; + + InterfaceDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + InterfaceDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.interfaceKeyword; + case 2: + return this.identifier; + case 3: + return this.typeParameterList; + case 4: + return this.heritageClauses; + case 5: + return this.body; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + InterfaceDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + InterfaceDeclarationSyntax.prototype.update = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + if (this.modifiers === modifiers && this.interfaceKeyword === interfaceKeyword && this.identifier === identifier && this.typeParameterList === typeParameterList && this.heritageClauses === heritageClauses && this.body === body) { + return this; + } + + return new InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, this.parsedInStrictMode()); + }; + + InterfaceDeclarationSyntax.create = function (interfaceKeyword, identifier, body) { + return new InterfaceDeclarationSyntax(TypeScript.Syntax.emptyList, interfaceKeyword, identifier, null, TypeScript.Syntax.emptyList, body, false); + }; + + InterfaceDeclarationSyntax.create1 = function (identifier) { + return new InterfaceDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(52 /* InterfaceKeyword */), identifier, null, TypeScript.Syntax.emptyList, ObjectTypeSyntax.create1(), false); + }; + + InterfaceDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + InterfaceDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + InterfaceDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + InterfaceDeclarationSyntax.prototype.withInterfaceKeyword = function (interfaceKeyword) { + return this.update(this.modifiers, interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.interfaceKeyword, identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withHeritageClauses = function (heritageClauses) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withHeritageClause = function (heritageClause) { + return this.withHeritageClauses(TypeScript.Syntax.list([heritageClause])); + }; + + InterfaceDeclarationSyntax.prototype.withBody = function (body) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, body); + }; + + InterfaceDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return InterfaceDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.InterfaceDeclarationSyntax = InterfaceDeclarationSyntax; + + var HeritageClauseSyntax = (function (_super) { + __extends(HeritageClauseSyntax, _super); + function HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.extendsOrImplementsKeyword = extendsOrImplementsKeyword; + this.typeNames = typeNames; + + this._kind = kind; + } + HeritageClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitHeritageClause(this); + }; + + HeritageClauseSyntax.prototype.childCount = function () { + return 2; + }; + + HeritageClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.extendsOrImplementsKeyword; + case 1: + return this.typeNames; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + HeritageClauseSyntax.prototype.kind = function () { + return this._kind; + }; + + HeritageClauseSyntax.prototype.update = function (kind, extendsOrImplementsKeyword, typeNames) { + if (this._kind === kind && this.extendsOrImplementsKeyword === extendsOrImplementsKeyword && this.typeNames === typeNames) { + return this; + } + + return new HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, this.parsedInStrictMode()); + }; + + HeritageClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + HeritageClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + HeritageClauseSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.extendsOrImplementsKeyword, this.typeNames); + }; + + HeritageClauseSyntax.prototype.withExtendsOrImplementsKeyword = function (extendsOrImplementsKeyword) { + return this.update(this._kind, extendsOrImplementsKeyword, this.typeNames); + }; + + HeritageClauseSyntax.prototype.withTypeNames = function (typeNames) { + return this.update(this._kind, this.extendsOrImplementsKeyword, typeNames); + }; + + HeritageClauseSyntax.prototype.withTypeName = function (typeName) { + return this.withTypeNames(TypeScript.Syntax.separatedList([typeName])); + }; + + HeritageClauseSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return HeritageClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.HeritageClauseSyntax = HeritageClauseSyntax; + + var ModuleDeclarationSyntax = (function (_super) { + __extends(ModuleDeclarationSyntax, _super); + function ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.moduleKeyword = moduleKeyword; + this.name = name; + this.stringLiteral = stringLiteral; + this.openBraceToken = openBraceToken; + this.moduleElements = moduleElements; + this.closeBraceToken = closeBraceToken; + } + ModuleDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitModuleDeclaration(this); + }; + + ModuleDeclarationSyntax.prototype.kind = function () { + return 130 /* ModuleDeclaration */; + }; + + ModuleDeclarationSyntax.prototype.childCount = function () { + return 7; + }; + + ModuleDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.moduleKeyword; + case 2: + return this.name; + case 3: + return this.stringLiteral; + case 4: + return this.openBraceToken; + case 5: + return this.moduleElements; + case 6: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ModuleDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ModuleDeclarationSyntax.prototype.update = function (modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + if (this.modifiers === modifiers && this.moduleKeyword === moduleKeyword && this.name === name && this.stringLiteral === stringLiteral && this.openBraceToken === openBraceToken && this.moduleElements === moduleElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, this.parsedInStrictMode()); + }; + + ModuleDeclarationSyntax.create = function (moduleKeyword, openBraceToken, closeBraceToken) { + return new ModuleDeclarationSyntax(TypeScript.Syntax.emptyList, moduleKeyword, null, null, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + ModuleDeclarationSyntax.create1 = function () { + return new ModuleDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(65 /* ModuleKeyword */), null, null, TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ModuleDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ModuleDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ModuleDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ModuleDeclarationSyntax.prototype.withModuleKeyword = function (moduleKeyword) { + return this.update(this.modifiers, moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withName = function (name) { + return this.update(this.modifiers, this.moduleKeyword, name, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withStringLiteral = function (stringLiteral) { + return this.update(this.modifiers, this.moduleKeyword, this.name, stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.moduleKeyword, this.name, this.stringLiteral, openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModuleElements = function (moduleElements) { + return this.update(this.modifiers, this.moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModuleElement = function (moduleElement) { + return this.withModuleElements(TypeScript.Syntax.list([moduleElement])); + }; + + ModuleDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, this.moduleElements, closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ModuleDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ModuleDeclarationSyntax = ModuleDeclarationSyntax; + + var FunctionDeclarationSyntax = (function (_super) { + __extends(FunctionDeclarationSyntax, _super); + function FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.functionKeyword = functionKeyword; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + FunctionDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionDeclaration(this); + }; + + FunctionDeclarationSyntax.prototype.kind = function () { + return 129 /* FunctionDeclaration */; + }; + + FunctionDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + FunctionDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.functionKeyword; + case 2: + return this.identifier; + case 3: + return this.callSignature; + case 4: + return this.block; + case 5: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionDeclarationSyntax.prototype.isStatement = function () { + return true; + }; + + FunctionDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + FunctionDeclarationSyntax.prototype.update = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.functionKeyword === functionKeyword && this.identifier === identifier && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + FunctionDeclarationSyntax.create = function (functionKeyword, identifier, callSignature) { + return new FunctionDeclarationSyntax(TypeScript.Syntax.emptyList, functionKeyword, identifier, callSignature, null, null, false); + }; + + FunctionDeclarationSyntax.create1 = function (identifier) { + return new FunctionDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(27 /* FunctionKeyword */), identifier, CallSignatureSyntax.create1(), null, null, false); + }; + + FunctionDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.functionKeyword, this.identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + FunctionDeclarationSyntax.prototype.withFunctionKeyword = function (functionKeyword) { + return this.update(this.modifiers, functionKeyword, this.identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.functionKeyword, identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, this.callSignature, block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, this.callSignature, this.block, semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.childCount() > 0) { + return true; + } + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block !== null && this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionDeclarationSyntax = FunctionDeclarationSyntax; + + var VariableStatementSyntax = (function (_super) { + __extends(VariableStatementSyntax, _super); + function VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.variableDeclaration = variableDeclaration; + this.semicolonToken = semicolonToken; + } + VariableStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableStatement(this); + }; + + VariableStatementSyntax.prototype.kind = function () { + return 148 /* VariableStatement */; + }; + + VariableStatementSyntax.prototype.childCount = function () { + return 3; + }; + + VariableStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.variableDeclaration; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableStatementSyntax.prototype.isStatement = function () { + return true; + }; + + VariableStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + VariableStatementSyntax.prototype.update = function (modifiers, variableDeclaration, semicolonToken) { + if (this.modifiers === modifiers && this.variableDeclaration === variableDeclaration && this.semicolonToken === semicolonToken) { + return this; + } + + return new VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, this.parsedInStrictMode()); + }; + + VariableStatementSyntax.create = function (variableDeclaration, semicolonToken) { + return new VariableStatementSyntax(TypeScript.Syntax.emptyList, variableDeclaration, semicolonToken, false); + }; + + VariableStatementSyntax.create1 = function (variableDeclaration) { + return new VariableStatementSyntax(TypeScript.Syntax.emptyList, variableDeclaration, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + VariableStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableStatementSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.variableDeclaration, this.semicolonToken); + }; + + VariableStatementSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + VariableStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.modifiers, variableDeclaration, this.semicolonToken); + }; + + VariableStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.variableDeclaration, semicolonToken); + }; + + VariableStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.childCount() > 0) { + return true; + } + if (this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableStatementSyntax = VariableStatementSyntax; + + var VariableDeclarationSyntax = (function (_super) { + __extends(VariableDeclarationSyntax, _super); + function VariableDeclarationSyntax(varKeyword, variableDeclarators, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.varKeyword = varKeyword; + this.variableDeclarators = variableDeclarators; + } + VariableDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableDeclaration(this); + }; + + VariableDeclarationSyntax.prototype.kind = function () { + return 224 /* VariableDeclaration */; + }; + + VariableDeclarationSyntax.prototype.childCount = function () { + return 2; + }; + + VariableDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.varKeyword; + case 1: + return this.variableDeclarators; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableDeclarationSyntax.prototype.update = function (varKeyword, variableDeclarators) { + if (this.varKeyword === varKeyword && this.variableDeclarators === variableDeclarators) { + return this; + } + + return new VariableDeclarationSyntax(varKeyword, variableDeclarators, this.parsedInStrictMode()); + }; + + VariableDeclarationSyntax.create1 = function (variableDeclarators) { + return new VariableDeclarationSyntax(TypeScript.Syntax.token(40 /* VarKeyword */), variableDeclarators, false); + }; + + VariableDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableDeclarationSyntax.prototype.withVarKeyword = function (varKeyword) { + return this.update(varKeyword, this.variableDeclarators); + }; + + VariableDeclarationSyntax.prototype.withVariableDeclarators = function (variableDeclarators) { + return this.update(this.varKeyword, variableDeclarators); + }; + + VariableDeclarationSyntax.prototype.withVariableDeclarator = function (variableDeclarator) { + return this.withVariableDeclarators(TypeScript.Syntax.separatedList([variableDeclarator])); + }; + + VariableDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclarators.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableDeclarationSyntax = VariableDeclarationSyntax; + + var VariableDeclaratorSyntax = (function (_super) { + __extends(VariableDeclaratorSyntax, _super); + function VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + } + VariableDeclaratorSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableDeclarator(this); + }; + + VariableDeclaratorSyntax.prototype.kind = function () { + return 225 /* VariableDeclarator */; + }; + + VariableDeclaratorSyntax.prototype.childCount = function () { + return 3; + }; + + VariableDeclaratorSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.typeAnnotation; + case 2: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableDeclaratorSyntax.prototype.update = function (propertyName, typeAnnotation, equalsValueClause) { + if (this.propertyName === propertyName && this.typeAnnotation === typeAnnotation && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, this.parsedInStrictMode()); + }; + + VariableDeclaratorSyntax.create = function (propertyName) { + return new VariableDeclaratorSyntax(propertyName, null, null, false); + }; + + VariableDeclaratorSyntax.create1 = function (propertyName) { + return new VariableDeclaratorSyntax(propertyName, null, null, false); + }; + + VariableDeclaratorSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableDeclaratorSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableDeclaratorSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.typeAnnotation, this.equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.propertyName, typeAnnotation, this.equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.propertyName, this.typeAnnotation, equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeAnnotation !== null) { + return true; + } + if (this.equalsValueClause !== null && this.equalsValueClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableDeclaratorSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableDeclaratorSyntax = VariableDeclaratorSyntax; + + var EqualsValueClauseSyntax = (function (_super) { + __extends(EqualsValueClauseSyntax, _super); + function EqualsValueClauseSyntax(equalsToken, value, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.equalsToken = equalsToken; + this.value = value; + } + EqualsValueClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitEqualsValueClause(this); + }; + + EqualsValueClauseSyntax.prototype.kind = function () { + return 232 /* EqualsValueClause */; + }; + + EqualsValueClauseSyntax.prototype.childCount = function () { + return 2; + }; + + EqualsValueClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.equalsToken; + case 1: + return this.value; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EqualsValueClauseSyntax.prototype.update = function (equalsToken, value) { + if (this.equalsToken === equalsToken && this.value === value) { + return this; + } + + return new EqualsValueClauseSyntax(equalsToken, value, this.parsedInStrictMode()); + }; + + EqualsValueClauseSyntax.create1 = function (value) { + return new EqualsValueClauseSyntax(TypeScript.Syntax.token(107 /* EqualsToken */), value, false); + }; + + EqualsValueClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EqualsValueClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EqualsValueClauseSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(equalsToken, this.value); + }; + + EqualsValueClauseSyntax.prototype.withValue = function (value) { + return this.update(this.equalsToken, value); + }; + + EqualsValueClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.value.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return EqualsValueClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EqualsValueClauseSyntax = EqualsValueClauseSyntax; + + var PrefixUnaryExpressionSyntax = (function (_super) { + __extends(PrefixUnaryExpressionSyntax, _super); + function PrefixUnaryExpressionSyntax(kind, operatorToken, operand, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.operatorToken = operatorToken; + this.operand = operand; + + this._kind = kind; + } + PrefixUnaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitPrefixUnaryExpression(this); + }; + + PrefixUnaryExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + PrefixUnaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.operatorToken; + case 1: + return this.operand; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PrefixUnaryExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + PrefixUnaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + PrefixUnaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + PrefixUnaryExpressionSyntax.prototype.update = function (kind, operatorToken, operand) { + if (this._kind === kind && this.operatorToken === operatorToken && this.operand === operand) { + return this; + } + + return new PrefixUnaryExpressionSyntax(kind, operatorToken, operand, this.parsedInStrictMode()); + }; + + PrefixUnaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PrefixUnaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PrefixUnaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.operatorToken, this.operand); + }; + + PrefixUnaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, operatorToken, this.operand); + }; + + PrefixUnaryExpressionSyntax.prototype.withOperand = function (operand) { + return this.update(this._kind, this.operatorToken, operand); + }; + + PrefixUnaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.operand.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return PrefixUnaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PrefixUnaryExpressionSyntax = PrefixUnaryExpressionSyntax; + + var ArrayLiteralExpressionSyntax = (function (_super) { + __extends(ArrayLiteralExpressionSyntax, _super); + function ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBracketToken = openBracketToken; + this.expressions = expressions; + this.closeBracketToken = closeBracketToken; + } + ArrayLiteralExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitArrayLiteralExpression(this); + }; + + ArrayLiteralExpressionSyntax.prototype.kind = function () { + return 214 /* ArrayLiteralExpression */; + }; + + ArrayLiteralExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ArrayLiteralExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBracketToken; + case 1: + return this.expressions; + case 2: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArrayLiteralExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.update = function (openBracketToken, expressions, closeBracketToken) { + if (this.openBracketToken === openBracketToken && this.expressions === expressions && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, this.parsedInStrictMode()); + }; + + ArrayLiteralExpressionSyntax.create = function (openBracketToken, closeBracketToken) { + return new ArrayLiteralExpressionSyntax(openBracketToken, TypeScript.Syntax.emptySeparatedList, closeBracketToken, false); + }; + + ArrayLiteralExpressionSyntax.create1 = function () { + return new ArrayLiteralExpressionSyntax(TypeScript.Syntax.token(74 /* OpenBracketToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(75 /* CloseBracketToken */), false); + }; + + ArrayLiteralExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArrayLiteralExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArrayLiteralExpressionSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(openBracketToken, this.expressions, this.closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.withExpressions = function (expressions) { + return this.update(this.openBracketToken, expressions, this.closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.withExpression = function (expression) { + return this.withExpressions(TypeScript.Syntax.separatedList([expression])); + }; + + ArrayLiteralExpressionSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.openBracketToken, this.expressions, closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expressions.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ArrayLiteralExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArrayLiteralExpressionSyntax = ArrayLiteralExpressionSyntax; + + var OmittedExpressionSyntax = (function (_super) { + __extends(OmittedExpressionSyntax, _super); + function OmittedExpressionSyntax(parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + } + OmittedExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitOmittedExpression(this); + }; + + OmittedExpressionSyntax.prototype.kind = function () { + return 223 /* OmittedExpression */; + }; + + OmittedExpressionSyntax.prototype.childCount = function () { + return 0; + }; + + OmittedExpressionSyntax.prototype.childAt = function (slot) { + throw TypeScript.Errors.invalidOperation(); + }; + + OmittedExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + OmittedExpressionSyntax.prototype.update = function () { + return this; + }; + + OmittedExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + OmittedExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + OmittedExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return OmittedExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.OmittedExpressionSyntax = OmittedExpressionSyntax; + + var ParenthesizedExpressionSyntax = (function (_super) { + __extends(ParenthesizedExpressionSyntax, _super); + function ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openParenToken = openParenToken; + this.expression = expression; + this.closeParenToken = closeParenToken; + } + ParenthesizedExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitParenthesizedExpression(this); + }; + + ParenthesizedExpressionSyntax.prototype.kind = function () { + return 217 /* ParenthesizedExpression */; + }; + + ParenthesizedExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ParenthesizedExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openParenToken; + case 1: + return this.expression; + case 2: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParenthesizedExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.update = function (openParenToken, expression, closeParenToken) { + if (this.openParenToken === openParenToken && this.expression === expression && this.closeParenToken === closeParenToken) { + return this; + } + + return new ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, this.parsedInStrictMode()); + }; + + ParenthesizedExpressionSyntax.create1 = function (expression) { + return new ParenthesizedExpressionSyntax(TypeScript.Syntax.token(72 /* OpenParenToken */), expression, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ParenthesizedExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParenthesizedExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParenthesizedExpressionSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(openParenToken, this.expression, this.closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.openParenToken, expression, this.closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.openParenToken, this.expression, closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ParenthesizedExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParenthesizedExpressionSyntax = ParenthesizedExpressionSyntax; + + var SimpleArrowFunctionExpressionSyntax = (function (_super) { + __extends(SimpleArrowFunctionExpressionSyntax, _super); + function SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.block = block; + this.expression = expression; + } + SimpleArrowFunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitSimpleArrowFunctionExpression(this); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.kind = function () { + return 219 /* SimpleArrowFunctionExpression */; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.equalsGreaterThanToken; + case 2: + return this.block; + case 3: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isArrowFunctionExpression = function () { + return true; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.update = function (identifier, equalsGreaterThanToken, block, expression) { + if (this.identifier === identifier && this.equalsGreaterThanToken === equalsGreaterThanToken && this.block === block && this.expression === expression) { + return this; + } + + return new SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, this.parsedInStrictMode()); + }; + + SimpleArrowFunctionExpressionSyntax.create = function (identifier, equalsGreaterThanToken) { + return new SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, null, null, false); + }; + + SimpleArrowFunctionExpressionSyntax.create1 = function (identifier) { + return new SimpleArrowFunctionExpressionSyntax(identifier, TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), null, null, false); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.equalsGreaterThanToken, this.block, this.expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.identifier, equalsGreaterThanToken, this.block, this.expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withBlock = function (block) { + return this.update(this.identifier, this.equalsGreaterThanToken, block, this.expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.identifier, this.equalsGreaterThanToken, this.block, expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return SimpleArrowFunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SimpleArrowFunctionExpressionSyntax = SimpleArrowFunctionExpressionSyntax; + + var ParenthesizedArrowFunctionExpressionSyntax = (function (_super) { + __extends(ParenthesizedArrowFunctionExpressionSyntax, _super); + function ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.callSignature = callSignature; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.block = block; + this.expression = expression; + } + ParenthesizedArrowFunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitParenthesizedArrowFunctionExpression(this); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.kind = function () { + return 218 /* ParenthesizedArrowFunctionExpression */; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.callSignature; + case 1: + return this.equalsGreaterThanToken; + case 2: + return this.block; + case 3: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isArrowFunctionExpression = function () { + return true; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.update = function (callSignature, equalsGreaterThanToken, block, expression) { + if (this.callSignature === callSignature && this.equalsGreaterThanToken === equalsGreaterThanToken && this.block === block && this.expression === expression) { + return this; + } + + return new ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, this.parsedInStrictMode()); + }; + + ParenthesizedArrowFunctionExpressionSyntax.create = function (callSignature, equalsGreaterThanToken) { + return new ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, null, null, false); + }; + + ParenthesizedArrowFunctionExpressionSyntax.create1 = function () { + return new ParenthesizedArrowFunctionExpressionSyntax(CallSignatureSyntax.create1(), TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), null, null, false); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(callSignature, this.equalsGreaterThanToken, this.block, this.expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.callSignature, equalsGreaterThanToken, this.block, this.expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withBlock = function (block) { + return this.update(this.callSignature, this.equalsGreaterThanToken, block, this.expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.callSignature, this.equalsGreaterThanToken, this.block, expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ParenthesizedArrowFunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParenthesizedArrowFunctionExpressionSyntax = ParenthesizedArrowFunctionExpressionSyntax; + + var QualifiedNameSyntax = (function (_super) { + __extends(QualifiedNameSyntax, _super); + function QualifiedNameSyntax(left, dotToken, right, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.left = left; + this.dotToken = dotToken; + this.right = right; + } + QualifiedNameSyntax.prototype.accept = function (visitor) { + return visitor.visitQualifiedName(this); + }; + + QualifiedNameSyntax.prototype.kind = function () { + return 121 /* QualifiedName */; + }; + + QualifiedNameSyntax.prototype.childCount = function () { + return 3; + }; + + QualifiedNameSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.left; + case 1: + return this.dotToken; + case 2: + return this.right; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + QualifiedNameSyntax.prototype.isName = function () { + return true; + }; + + QualifiedNameSyntax.prototype.isType = function () { + return true; + }; + + QualifiedNameSyntax.prototype.update = function (left, dotToken, right) { + if (this.left === left && this.dotToken === dotToken && this.right === right) { + return this; + } + + return new QualifiedNameSyntax(left, dotToken, right, this.parsedInStrictMode()); + }; + + QualifiedNameSyntax.create1 = function (left, right) { + return new QualifiedNameSyntax(left, TypeScript.Syntax.token(76 /* DotToken */), right, false); + }; + + QualifiedNameSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + QualifiedNameSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + QualifiedNameSyntax.prototype.withLeft = function (left) { + return this.update(left, this.dotToken, this.right); + }; + + QualifiedNameSyntax.prototype.withDotToken = function (dotToken) { + return this.update(this.left, dotToken, this.right); + }; + + QualifiedNameSyntax.prototype.withRight = function (right) { + return this.update(this.left, this.dotToken, right); + }; + + QualifiedNameSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return QualifiedNameSyntax; + })(TypeScript.SyntaxNode); + TypeScript.QualifiedNameSyntax = QualifiedNameSyntax; + + var TypeArgumentListSyntax = (function (_super) { + __extends(TypeArgumentListSyntax, _super); + function TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.typeArguments = typeArguments; + this.greaterThanToken = greaterThanToken; + } + TypeArgumentListSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeArgumentList(this); + }; + + TypeArgumentListSyntax.prototype.kind = function () { + return 228 /* TypeArgumentList */; + }; + + TypeArgumentListSyntax.prototype.childCount = function () { + return 3; + }; + + TypeArgumentListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.typeArguments; + case 2: + return this.greaterThanToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeArgumentListSyntax.prototype.update = function (lessThanToken, typeArguments, greaterThanToken) { + if (this.lessThanToken === lessThanToken && this.typeArguments === typeArguments && this.greaterThanToken === greaterThanToken) { + return this; + } + + return new TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, this.parsedInStrictMode()); + }; + + TypeArgumentListSyntax.create = function (lessThanToken, greaterThanToken) { + return new TypeArgumentListSyntax(lessThanToken, TypeScript.Syntax.emptySeparatedList, greaterThanToken, false); + }; + + TypeArgumentListSyntax.create1 = function () { + return new TypeArgumentListSyntax(TypeScript.Syntax.token(80 /* LessThanToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(81 /* GreaterThanToken */), false); + }; + + TypeArgumentListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeArgumentListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeArgumentListSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.typeArguments, this.greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.withTypeArguments = function (typeArguments) { + return this.update(this.lessThanToken, typeArguments, this.greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.withTypeArgument = function (typeArgument) { + return this.withTypeArguments(TypeScript.Syntax.separatedList([typeArgument])); + }; + + TypeArgumentListSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.typeArguments, greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeArgumentListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeArgumentListSyntax = TypeArgumentListSyntax; + + var ConstructorTypeSyntax = (function (_super) { + __extends(ConstructorTypeSyntax, _super); + function ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.type = type; + } + ConstructorTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructorType(this); + }; + + ConstructorTypeSyntax.prototype.kind = function () { + return 125 /* ConstructorType */; + }; + + ConstructorTypeSyntax.prototype.childCount = function () { + return 5; + }; + + ConstructorTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.typeParameterList; + case 2: + return this.parameterList; + case 3: + return this.equalsGreaterThanToken; + case 4: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructorTypeSyntax.prototype.isType = function () { + return true; + }; + + ConstructorTypeSyntax.prototype.update = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + if (this.newKeyword === newKeyword && this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.equalsGreaterThanToken === equalsGreaterThanToken && this.type === type) { + return this; + } + + return new ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, this.parsedInStrictMode()); + }; + + ConstructorTypeSyntax.create = function (newKeyword, parameterList, equalsGreaterThanToken, type) { + return new ConstructorTypeSyntax(newKeyword, null, parameterList, equalsGreaterThanToken, type, false); + }; + + ConstructorTypeSyntax.create1 = function (type) { + return new ConstructorTypeSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), null, ParameterListSyntax.create1(), TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), type, false); + }; + + ConstructorTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructorTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructorTypeSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.newKeyword, typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.newKeyword, this.typeParameterList, parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.newKeyword, this.typeParameterList, this.parameterList, equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withType = function (type) { + return this.update(this.newKeyword, this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, type); + }; + + ConstructorTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructorTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructorTypeSyntax = ConstructorTypeSyntax; + + var FunctionTypeSyntax = (function (_super) { + __extends(FunctionTypeSyntax, _super); + function FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.type = type; + } + FunctionTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionType(this); + }; + + FunctionTypeSyntax.prototype.kind = function () { + return 123 /* FunctionType */; + }; + + FunctionTypeSyntax.prototype.childCount = function () { + return 4; + }; + + FunctionTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeParameterList; + case 1: + return this.parameterList; + case 2: + return this.equalsGreaterThanToken; + case 3: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionTypeSyntax.prototype.isType = function () { + return true; + }; + + FunctionTypeSyntax.prototype.update = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + if (this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.equalsGreaterThanToken === equalsGreaterThanToken && this.type === type) { + return this; + } + + return new FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, this.parsedInStrictMode()); + }; + + FunctionTypeSyntax.create = function (parameterList, equalsGreaterThanToken, type) { + return new FunctionTypeSyntax(null, parameterList, equalsGreaterThanToken, type, false); + }; + + FunctionTypeSyntax.create1 = function (type) { + return new FunctionTypeSyntax(null, ParameterListSyntax.create1(), TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), type, false); + }; + + FunctionTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionTypeSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.typeParameterList, parameterList, this.equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.typeParameterList, this.parameterList, equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withType = function (type) { + return this.update(this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, type); + }; + + FunctionTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return FunctionTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionTypeSyntax = FunctionTypeSyntax; + + var ObjectTypeSyntax = (function (_super) { + __extends(ObjectTypeSyntax, _super); + function ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.typeMembers = typeMembers; + this.closeBraceToken = closeBraceToken; + } + ObjectTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectType(this); + }; + + ObjectTypeSyntax.prototype.kind = function () { + return 122 /* ObjectType */; + }; + + ObjectTypeSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.typeMembers; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectTypeSyntax.prototype.isType = function () { + return true; + }; + + ObjectTypeSyntax.prototype.update = function (openBraceToken, typeMembers, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.typeMembers === typeMembers && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, this.parsedInStrictMode()); + }; + + ObjectTypeSyntax.create = function (openBraceToken, closeBraceToken) { + return new ObjectTypeSyntax(openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + ObjectTypeSyntax.create1 = function () { + return new ObjectTypeSyntax(TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ObjectTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectTypeSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.typeMembers, this.closeBraceToken); + }; + + ObjectTypeSyntax.prototype.withTypeMembers = function (typeMembers) { + return this.update(this.openBraceToken, typeMembers, this.closeBraceToken); + }; + + ObjectTypeSyntax.prototype.withTypeMember = function (typeMember) { + return this.withTypeMembers(TypeScript.Syntax.separatedList([typeMember])); + }; + + ObjectTypeSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.typeMembers, closeBraceToken); + }; + + ObjectTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ObjectTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectTypeSyntax = ObjectTypeSyntax; + + var ArrayTypeSyntax = (function (_super) { + __extends(ArrayTypeSyntax, _super); + function ArrayTypeSyntax(type, openBracketToken, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.type = type; + this.openBracketToken = openBracketToken; + this.closeBracketToken = closeBracketToken; + } + ArrayTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitArrayType(this); + }; + + ArrayTypeSyntax.prototype.kind = function () { + return 124 /* ArrayType */; + }; + + ArrayTypeSyntax.prototype.childCount = function () { + return 3; + }; + + ArrayTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.type; + case 1: + return this.openBracketToken; + case 2: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArrayTypeSyntax.prototype.isType = function () { + return true; + }; + + ArrayTypeSyntax.prototype.update = function (type, openBracketToken, closeBracketToken) { + if (this.type === type && this.openBracketToken === openBracketToken && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ArrayTypeSyntax(type, openBracketToken, closeBracketToken, this.parsedInStrictMode()); + }; + + ArrayTypeSyntax.create1 = function (type) { + return new ArrayTypeSyntax(type, TypeScript.Syntax.token(74 /* OpenBracketToken */), TypeScript.Syntax.token(75 /* CloseBracketToken */), false); + }; + + ArrayTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArrayTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArrayTypeSyntax.prototype.withType = function (type) { + return this.update(type, this.openBracketToken, this.closeBracketToken); + }; + + ArrayTypeSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(this.type, openBracketToken, this.closeBracketToken); + }; + + ArrayTypeSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.type, this.openBracketToken, closeBracketToken); + }; + + ArrayTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ArrayTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArrayTypeSyntax = ArrayTypeSyntax; + + var GenericTypeSyntax = (function (_super) { + __extends(GenericTypeSyntax, _super); + function GenericTypeSyntax(name, typeArgumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.name = name; + this.typeArgumentList = typeArgumentList; + } + GenericTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitGenericType(this); + }; + + GenericTypeSyntax.prototype.kind = function () { + return 126 /* GenericType */; + }; + + GenericTypeSyntax.prototype.childCount = function () { + return 2; + }; + + GenericTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.name; + case 1: + return this.typeArgumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + GenericTypeSyntax.prototype.isType = function () { + return true; + }; + + GenericTypeSyntax.prototype.update = function (name, typeArgumentList) { + if (this.name === name && this.typeArgumentList === typeArgumentList) { + return this; + } + + return new GenericTypeSyntax(name, typeArgumentList, this.parsedInStrictMode()); + }; + + GenericTypeSyntax.create1 = function (name) { + return new GenericTypeSyntax(name, TypeArgumentListSyntax.create1(), false); + }; + + GenericTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + GenericTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + GenericTypeSyntax.prototype.withName = function (name) { + return this.update(name, this.typeArgumentList); + }; + + GenericTypeSyntax.prototype.withTypeArgumentList = function (typeArgumentList) { + return this.update(this.name, typeArgumentList); + }; + + GenericTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return GenericTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.GenericTypeSyntax = GenericTypeSyntax; + + var TypeQuerySyntax = (function (_super) { + __extends(TypeQuerySyntax, _super); + function TypeQuerySyntax(typeOfKeyword, name, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeOfKeyword = typeOfKeyword; + this.name = name; + } + TypeQuerySyntax.prototype.accept = function (visitor) { + return visitor.visitTypeQuery(this); + }; + + TypeQuerySyntax.prototype.kind = function () { + return 127 /* TypeQuery */; + }; + + TypeQuerySyntax.prototype.childCount = function () { + return 2; + }; + + TypeQuerySyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeOfKeyword; + case 1: + return this.name; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeQuerySyntax.prototype.isType = function () { + return true; + }; + + TypeQuerySyntax.prototype.update = function (typeOfKeyword, name) { + if (this.typeOfKeyword === typeOfKeyword && this.name === name) { + return this; + } + + return new TypeQuerySyntax(typeOfKeyword, name, this.parsedInStrictMode()); + }; + + TypeQuerySyntax.create1 = function (name) { + return new TypeQuerySyntax(TypeScript.Syntax.token(39 /* TypeOfKeyword */), name, false); + }; + + TypeQuerySyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeQuerySyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeQuerySyntax.prototype.withTypeOfKeyword = function (typeOfKeyword) { + return this.update(typeOfKeyword, this.name); + }; + + TypeQuerySyntax.prototype.withName = function (name) { + return this.update(this.typeOfKeyword, name); + }; + + TypeQuerySyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeQuerySyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeQuerySyntax = TypeQuerySyntax; + + var TypeAnnotationSyntax = (function (_super) { + __extends(TypeAnnotationSyntax, _super); + function TypeAnnotationSyntax(colonToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.colonToken = colonToken; + this.type = type; + } + TypeAnnotationSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeAnnotation(this); + }; + + TypeAnnotationSyntax.prototype.kind = function () { + return 244 /* TypeAnnotation */; + }; + + TypeAnnotationSyntax.prototype.childCount = function () { + return 2; + }; + + TypeAnnotationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.colonToken; + case 1: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeAnnotationSyntax.prototype.update = function (colonToken, type) { + if (this.colonToken === colonToken && this.type === type) { + return this; + } + + return new TypeAnnotationSyntax(colonToken, type, this.parsedInStrictMode()); + }; + + TypeAnnotationSyntax.create1 = function (type) { + return new TypeAnnotationSyntax(TypeScript.Syntax.token(106 /* ColonToken */), type, false); + }; + + TypeAnnotationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeAnnotationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeAnnotationSyntax.prototype.withColonToken = function (colonToken) { + return this.update(colonToken, this.type); + }; + + TypeAnnotationSyntax.prototype.withType = function (type) { + return this.update(this.colonToken, type); + }; + + TypeAnnotationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeAnnotationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeAnnotationSyntax = TypeAnnotationSyntax; + + var BlockSyntax = (function (_super) { + __extends(BlockSyntax, _super); + function BlockSyntax(openBraceToken, statements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.statements = statements; + this.closeBraceToken = closeBraceToken; + } + BlockSyntax.prototype.accept = function (visitor) { + return visitor.visitBlock(this); + }; + + BlockSyntax.prototype.kind = function () { + return 146 /* Block */; + }; + + BlockSyntax.prototype.childCount = function () { + return 3; + }; + + BlockSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.statements; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BlockSyntax.prototype.isStatement = function () { + return true; + }; + + BlockSyntax.prototype.isModuleElement = function () { + return true; + }; + + BlockSyntax.prototype.update = function (openBraceToken, statements, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.statements === statements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new BlockSyntax(openBraceToken, statements, closeBraceToken, this.parsedInStrictMode()); + }; + + BlockSyntax.create = function (openBraceToken, closeBraceToken) { + return new BlockSyntax(openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + BlockSyntax.create1 = function () { + return new BlockSyntax(TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + BlockSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BlockSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BlockSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.statements, this.closeBraceToken); + }; + + BlockSyntax.prototype.withStatements = function (statements) { + return this.update(this.openBraceToken, statements, this.closeBraceToken); + }; + + BlockSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + BlockSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.statements, closeBraceToken); + }; + + BlockSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return BlockSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BlockSyntax = BlockSyntax; + + var ParameterSyntax = (function (_super) { + __extends(ParameterSyntax, _super); + function ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.dotDotDotToken = dotDotDotToken; + this.modifiers = modifiers; + this.identifier = identifier; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + } + ParameterSyntax.prototype.accept = function (visitor) { + return visitor.visitParameter(this); + }; + + ParameterSyntax.prototype.kind = function () { + return 242 /* Parameter */; + }; + + ParameterSyntax.prototype.childCount = function () { + return 6; + }; + + ParameterSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.dotDotDotToken; + case 1: + return this.modifiers; + case 2: + return this.identifier; + case 3: + return this.questionToken; + case 4: + return this.typeAnnotation; + case 5: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParameterSyntax.prototype.update = function (dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + if (this.dotDotDotToken === dotDotDotToken && this.modifiers === modifiers && this.identifier === identifier && this.questionToken === questionToken && this.typeAnnotation === typeAnnotation && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, this.parsedInStrictMode()); + }; + + ParameterSyntax.create = function (identifier) { + return new ParameterSyntax(null, TypeScript.Syntax.emptyList, identifier, null, null, null, false); + }; + + ParameterSyntax.create1 = function (identifier) { + return new ParameterSyntax(null, TypeScript.Syntax.emptyList, identifier, null, null, null, false); + }; + + ParameterSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParameterSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParameterSyntax.prototype.withDotDotDotToken = function (dotDotDotToken) { + return this.update(dotDotDotToken, this.modifiers, this.identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withModifiers = function (modifiers) { + return this.update(this.dotDotDotToken, modifiers, this.identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ParameterSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.dotDotDotToken, this.modifiers, identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.dotDotDotToken, this.modifiers, this.identifier, questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.dotDotDotToken, this.modifiers, this.identifier, this.questionToken, typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.dotDotDotToken, this.modifiers, this.identifier, this.questionToken, this.typeAnnotation, equalsValueClause); + }; + + ParameterSyntax.prototype.isTypeScriptSpecific = function () { + if (this.dotDotDotToken !== null) { + return true; + } + if (this.modifiers.isTypeScriptSpecific()) { + return true; + } + if (this.questionToken !== null) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + if (this.equalsValueClause !== null) { + return true; + } + return false; + }; + return ParameterSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParameterSyntax = ParameterSyntax; + + var MemberAccessExpressionSyntax = (function (_super) { + __extends(MemberAccessExpressionSyntax, _super); + function MemberAccessExpressionSyntax(expression, dotToken, name, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.dotToken = dotToken; + this.name = name; + } + MemberAccessExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberAccessExpression(this); + }; + + MemberAccessExpressionSyntax.prototype.kind = function () { + return 212 /* MemberAccessExpression */; + }; + + MemberAccessExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + MemberAccessExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.dotToken; + case 2: + return this.name; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberAccessExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.update = function (expression, dotToken, name) { + if (this.expression === expression && this.dotToken === dotToken && this.name === name) { + return this; + } + + return new MemberAccessExpressionSyntax(expression, dotToken, name, this.parsedInStrictMode()); + }; + + MemberAccessExpressionSyntax.create1 = function (expression, name) { + return new MemberAccessExpressionSyntax(expression, TypeScript.Syntax.token(76 /* DotToken */), name, false); + }; + + MemberAccessExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberAccessExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberAccessExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.dotToken, this.name); + }; + + MemberAccessExpressionSyntax.prototype.withDotToken = function (dotToken) { + return this.update(this.expression, dotToken, this.name); + }; + + MemberAccessExpressionSyntax.prototype.withName = function (name) { + return this.update(this.expression, this.dotToken, name); + }; + + MemberAccessExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return MemberAccessExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberAccessExpressionSyntax = MemberAccessExpressionSyntax; + + var PostfixUnaryExpressionSyntax = (function (_super) { + __extends(PostfixUnaryExpressionSyntax, _super); + function PostfixUnaryExpressionSyntax(kind, operand, operatorToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.operand = operand; + this.operatorToken = operatorToken; + + this._kind = kind; + } + PostfixUnaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitPostfixUnaryExpression(this); + }; + + PostfixUnaryExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + PostfixUnaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.operand; + case 1: + return this.operatorToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PostfixUnaryExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + PostfixUnaryExpressionSyntax.prototype.update = function (kind, operand, operatorToken) { + if (this._kind === kind && this.operand === operand && this.operatorToken === operatorToken) { + return this; + } + + return new PostfixUnaryExpressionSyntax(kind, operand, operatorToken, this.parsedInStrictMode()); + }; + + PostfixUnaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PostfixUnaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PostfixUnaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.operand, this.operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.withOperand = function (operand) { + return this.update(this._kind, operand, this.operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, this.operand, operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.operand.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return PostfixUnaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PostfixUnaryExpressionSyntax = PostfixUnaryExpressionSyntax; + + var ElementAccessExpressionSyntax = (function (_super) { + __extends(ElementAccessExpressionSyntax, _super); + function ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.openBracketToken = openBracketToken; + this.argumentExpression = argumentExpression; + this.closeBracketToken = closeBracketToken; + } + ElementAccessExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitElementAccessExpression(this); + }; + + ElementAccessExpressionSyntax.prototype.kind = function () { + return 221 /* ElementAccessExpression */; + }; + + ElementAccessExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + ElementAccessExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.openBracketToken; + case 2: + return this.argumentExpression; + case 3: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ElementAccessExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.update = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + if (this.expression === expression && this.openBracketToken === openBracketToken && this.argumentExpression === argumentExpression && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, this.parsedInStrictMode()); + }; + + ElementAccessExpressionSyntax.create1 = function (expression, argumentExpression) { + return new ElementAccessExpressionSyntax(expression, TypeScript.Syntax.token(74 /* OpenBracketToken */), argumentExpression, TypeScript.Syntax.token(75 /* CloseBracketToken */), false); + }; + + ElementAccessExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ElementAccessExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ElementAccessExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.openBracketToken, this.argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(this.expression, openBracketToken, this.argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withArgumentExpression = function (argumentExpression) { + return this.update(this.expression, this.openBracketToken, argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.expression, this.openBracketToken, this.argumentExpression, closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentExpression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ElementAccessExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ElementAccessExpressionSyntax = ElementAccessExpressionSyntax; + + var InvocationExpressionSyntax = (function (_super) { + __extends(InvocationExpressionSyntax, _super); + function InvocationExpressionSyntax(expression, argumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.argumentList = argumentList; + } + InvocationExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitInvocationExpression(this); + }; + + InvocationExpressionSyntax.prototype.kind = function () { + return 213 /* InvocationExpression */; + }; + + InvocationExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + InvocationExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.argumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + InvocationExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.update = function (expression, argumentList) { + if (this.expression === expression && this.argumentList === argumentList) { + return this; + } + + return new InvocationExpressionSyntax(expression, argumentList, this.parsedInStrictMode()); + }; + + InvocationExpressionSyntax.create1 = function (expression) { + return new InvocationExpressionSyntax(expression, ArgumentListSyntax.create1(), false); + }; + + InvocationExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + InvocationExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + InvocationExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.argumentList); + }; + + InvocationExpressionSyntax.prototype.withArgumentList = function (argumentList) { + return this.update(this.expression, argumentList); + }; + + InvocationExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentList.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return InvocationExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.InvocationExpressionSyntax = InvocationExpressionSyntax; + + var ArgumentListSyntax = (function (_super) { + __extends(ArgumentListSyntax, _super); + function ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeArgumentList = typeArgumentList; + this.openParenToken = openParenToken; + this.closeParenToken = closeParenToken; + + this.arguments = _arguments; + } + ArgumentListSyntax.prototype.accept = function (visitor) { + return visitor.visitArgumentList(this); + }; + + ArgumentListSyntax.prototype.kind = function () { + return 226 /* ArgumentList */; + }; + + ArgumentListSyntax.prototype.childCount = function () { + return 4; + }; + + ArgumentListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeArgumentList; + case 1: + return this.openParenToken; + case 2: + return this.arguments; + case 3: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArgumentListSyntax.prototype.update = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + if (this.typeArgumentList === typeArgumentList && this.openParenToken === openParenToken && this.arguments === _arguments && this.closeParenToken === closeParenToken) { + return this; + } + + return new ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, this.parsedInStrictMode()); + }; + + ArgumentListSyntax.create = function (openParenToken, closeParenToken) { + return new ArgumentListSyntax(null, openParenToken, TypeScript.Syntax.emptySeparatedList, closeParenToken, false); + }; + + ArgumentListSyntax.create1 = function () { + return new ArgumentListSyntax(null, TypeScript.Syntax.token(72 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ArgumentListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArgumentListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArgumentListSyntax.prototype.withTypeArgumentList = function (typeArgumentList) { + return this.update(typeArgumentList, this.openParenToken, this.arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.typeArgumentList, openParenToken, this.arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withArguments = function (_arguments) { + return this.update(this.typeArgumentList, this.openParenToken, _arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withArgument = function (_argument) { + return this.withArguments(TypeScript.Syntax.separatedList([_argument])); + }; + + ArgumentListSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.typeArgumentList, this.openParenToken, this.arguments, closeParenToken); + }; + + ArgumentListSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeArgumentList !== null && this.typeArgumentList.isTypeScriptSpecific()) { + return true; + } + if (this.arguments.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ArgumentListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArgumentListSyntax = ArgumentListSyntax; + + var BinaryExpressionSyntax = (function (_super) { + __extends(BinaryExpressionSyntax, _super); + function BinaryExpressionSyntax(kind, left, operatorToken, right, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.left = left; + this.operatorToken = operatorToken; + this.right = right; + + this._kind = kind; + } + BinaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitBinaryExpression(this); + }; + + BinaryExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + BinaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.left; + case 1: + return this.operatorToken; + case 2: + return this.right; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BinaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + BinaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + BinaryExpressionSyntax.prototype.update = function (kind, left, operatorToken, right) { + if (this._kind === kind && this.left === left && this.operatorToken === operatorToken && this.right === right) { + return this; + } + + return new BinaryExpressionSyntax(kind, left, operatorToken, right, this.parsedInStrictMode()); + }; + + BinaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BinaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BinaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.left, this.operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withLeft = function (left) { + return this.update(this._kind, left, this.operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, this.left, operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withRight = function (right) { + return this.update(this._kind, this.left, this.operatorToken, right); + }; + + BinaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.left.isTypeScriptSpecific()) { + return true; + } + if (this.right.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return BinaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BinaryExpressionSyntax = BinaryExpressionSyntax; + + var ConditionalExpressionSyntax = (function (_super) { + __extends(ConditionalExpressionSyntax, _super); + function ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.condition = condition; + this.questionToken = questionToken; + this.whenTrue = whenTrue; + this.colonToken = colonToken; + this.whenFalse = whenFalse; + } + ConditionalExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitConditionalExpression(this); + }; + + ConditionalExpressionSyntax.prototype.kind = function () { + return 186 /* ConditionalExpression */; + }; + + ConditionalExpressionSyntax.prototype.childCount = function () { + return 5; + }; + + ConditionalExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.condition; + case 1: + return this.questionToken; + case 2: + return this.whenTrue; + case 3: + return this.colonToken; + case 4: + return this.whenFalse; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConditionalExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ConditionalExpressionSyntax.prototype.update = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + if (this.condition === condition && this.questionToken === questionToken && this.whenTrue === whenTrue && this.colonToken === colonToken && this.whenFalse === whenFalse) { + return this; + } + + return new ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, this.parsedInStrictMode()); + }; + + ConditionalExpressionSyntax.create1 = function (condition, whenTrue, whenFalse) { + return new ConditionalExpressionSyntax(condition, TypeScript.Syntax.token(105 /* QuestionToken */), whenTrue, TypeScript.Syntax.token(106 /* ColonToken */), whenFalse, false); + }; + + ConditionalExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConditionalExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConditionalExpressionSyntax.prototype.withCondition = function (condition) { + return this.update(condition, this.questionToken, this.whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.condition, questionToken, this.whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withWhenTrue = function (whenTrue) { + return this.update(this.condition, this.questionToken, whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.condition, this.questionToken, this.whenTrue, colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withWhenFalse = function (whenFalse) { + return this.update(this.condition, this.questionToken, this.whenTrue, this.colonToken, whenFalse); + }; + + ConditionalExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.whenTrue.isTypeScriptSpecific()) { + return true; + } + if (this.whenFalse.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ConditionalExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConditionalExpressionSyntax = ConditionalExpressionSyntax; + + var ConstructSignatureSyntax = (function (_super) { + __extends(ConstructSignatureSyntax, _super); + function ConstructSignatureSyntax(newKeyword, callSignature, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.callSignature = callSignature; + } + ConstructSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructSignature(this); + }; + + ConstructSignatureSyntax.prototype.kind = function () { + return 143 /* ConstructSignature */; + }; + + ConstructSignatureSyntax.prototype.childCount = function () { + return 2; + }; + + ConstructSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.callSignature; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + ConstructSignatureSyntax.prototype.update = function (newKeyword, callSignature) { + if (this.newKeyword === newKeyword && this.callSignature === callSignature) { + return this; + } + + return new ConstructSignatureSyntax(newKeyword, callSignature, this.parsedInStrictMode()); + }; + + ConstructSignatureSyntax.create1 = function () { + return new ConstructSignatureSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), CallSignatureSyntax.create1(), false); + }; + + ConstructSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructSignatureSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.callSignature); + }; + + ConstructSignatureSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.newKeyword, callSignature); + }; + + ConstructSignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructSignatureSyntax = ConstructSignatureSyntax; + + var MethodSignatureSyntax = (function (_super) { + __extends(MethodSignatureSyntax, _super); + function MethodSignatureSyntax(propertyName, questionToken, callSignature, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.callSignature = callSignature; + } + MethodSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitMethodSignature(this); + }; + + MethodSignatureSyntax.prototype.kind = function () { + return 145 /* MethodSignature */; + }; + + MethodSignatureSyntax.prototype.childCount = function () { + return 3; + }; + + MethodSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.questionToken; + case 2: + return this.callSignature; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MethodSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + MethodSignatureSyntax.prototype.update = function (propertyName, questionToken, callSignature) { + if (this.propertyName === propertyName && this.questionToken === questionToken && this.callSignature === callSignature) { + return this; + } + + return new MethodSignatureSyntax(propertyName, questionToken, callSignature, this.parsedInStrictMode()); + }; + + MethodSignatureSyntax.create = function (propertyName, callSignature) { + return new MethodSignatureSyntax(propertyName, null, callSignature, false); + }; + + MethodSignatureSyntax.create1 = function (propertyName) { + return new MethodSignatureSyntax(propertyName, null, CallSignatureSyntax.create1(), false); + }; + + MethodSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MethodSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MethodSignatureSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.questionToken, this.callSignature); + }; + + MethodSignatureSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.propertyName, questionToken, this.callSignature); + }; + + MethodSignatureSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.propertyName, this.questionToken, callSignature); + }; + + MethodSignatureSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return MethodSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MethodSignatureSyntax = MethodSignatureSyntax; + + var IndexSignatureSyntax = (function (_super) { + __extends(IndexSignatureSyntax, _super); + function IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBracketToken = openBracketToken; + this.parameter = parameter; + this.closeBracketToken = closeBracketToken; + this.typeAnnotation = typeAnnotation; + } + IndexSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitIndexSignature(this); + }; + + IndexSignatureSyntax.prototype.kind = function () { + return 144 /* IndexSignature */; + }; + + IndexSignatureSyntax.prototype.childCount = function () { + return 4; + }; + + IndexSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBracketToken; + case 1: + return this.parameter; + case 2: + return this.closeBracketToken; + case 3: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IndexSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + IndexSignatureSyntax.prototype.update = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + if (this.openBracketToken === openBracketToken && this.parameter === parameter && this.closeBracketToken === closeBracketToken && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, this.parsedInStrictMode()); + }; + + IndexSignatureSyntax.create = function (openBracketToken, parameter, closeBracketToken) { + return new IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, null, false); + }; + + IndexSignatureSyntax.create1 = function (parameter) { + return new IndexSignatureSyntax(TypeScript.Syntax.token(74 /* OpenBracketToken */), parameter, TypeScript.Syntax.token(75 /* CloseBracketToken */), null, false); + }; + + IndexSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IndexSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IndexSignatureSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(openBracketToken, this.parameter, this.closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withParameter = function (parameter) { + return this.update(this.openBracketToken, parameter, this.closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.openBracketToken, this.parameter, closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.openBracketToken, this.parameter, this.closeBracketToken, typeAnnotation); + }; + + IndexSignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return IndexSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IndexSignatureSyntax = IndexSignatureSyntax; + + var PropertySignatureSyntax = (function (_super) { + __extends(PropertySignatureSyntax, _super); + function PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + } + PropertySignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitPropertySignature(this); + }; + + PropertySignatureSyntax.prototype.kind = function () { + return 141 /* PropertySignature */; + }; + + PropertySignatureSyntax.prototype.childCount = function () { + return 3; + }; + + PropertySignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.questionToken; + case 2: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PropertySignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + PropertySignatureSyntax.prototype.update = function (propertyName, questionToken, typeAnnotation) { + if (this.propertyName === propertyName && this.questionToken === questionToken && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, this.parsedInStrictMode()); + }; + + PropertySignatureSyntax.create = function (propertyName) { + return new PropertySignatureSyntax(propertyName, null, null, false); + }; + + PropertySignatureSyntax.create1 = function (propertyName) { + return new PropertySignatureSyntax(propertyName, null, null, false); + }; + + PropertySignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PropertySignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PropertySignatureSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.questionToken, this.typeAnnotation); + }; + + PropertySignatureSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.propertyName, questionToken, this.typeAnnotation); + }; + + PropertySignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.propertyName, this.questionToken, typeAnnotation); + }; + + PropertySignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return PropertySignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PropertySignatureSyntax = PropertySignatureSyntax; + + var CallSignatureSyntax = (function (_super) { + __extends(CallSignatureSyntax, _super); + function CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + } + CallSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitCallSignature(this); + }; + + CallSignatureSyntax.prototype.kind = function () { + return 142 /* CallSignature */; + }; + + CallSignatureSyntax.prototype.childCount = function () { + return 3; + }; + + CallSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeParameterList; + case 1: + return this.parameterList; + case 2: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CallSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + CallSignatureSyntax.prototype.update = function (typeParameterList, parameterList, typeAnnotation) { + if (this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, this.parsedInStrictMode()); + }; + + CallSignatureSyntax.create = function (parameterList) { + return new CallSignatureSyntax(null, parameterList, null, false); + }; + + CallSignatureSyntax.create1 = function () { + return new CallSignatureSyntax(null, ParameterListSyntax.create1(), null, false); + }; + + CallSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CallSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CallSignatureSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(typeParameterList, this.parameterList, this.typeAnnotation); + }; + + CallSignatureSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.typeParameterList, parameterList, this.typeAnnotation); + }; + + CallSignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.typeParameterList, this.parameterList, typeAnnotation); + }; + + CallSignatureSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeParameterList !== null) { + return true; + } + if (this.parameterList.isTypeScriptSpecific()) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + return false; + }; + return CallSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CallSignatureSyntax = CallSignatureSyntax; + + var ParameterListSyntax = (function (_super) { + __extends(ParameterListSyntax, _super); + function ParameterListSyntax(openParenToken, parameters, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openParenToken = openParenToken; + this.parameters = parameters; + this.closeParenToken = closeParenToken; + } + ParameterListSyntax.prototype.accept = function (visitor) { + return visitor.visitParameterList(this); + }; + + ParameterListSyntax.prototype.kind = function () { + return 227 /* ParameterList */; + }; + + ParameterListSyntax.prototype.childCount = function () { + return 3; + }; + + ParameterListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openParenToken; + case 1: + return this.parameters; + case 2: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParameterListSyntax.prototype.update = function (openParenToken, parameters, closeParenToken) { + if (this.openParenToken === openParenToken && this.parameters === parameters && this.closeParenToken === closeParenToken) { + return this; + } + + return new ParameterListSyntax(openParenToken, parameters, closeParenToken, this.parsedInStrictMode()); + }; + + ParameterListSyntax.create = function (openParenToken, closeParenToken) { + return new ParameterListSyntax(openParenToken, TypeScript.Syntax.emptySeparatedList, closeParenToken, false); + }; + + ParameterListSyntax.create1 = function () { + return new ParameterListSyntax(TypeScript.Syntax.token(72 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ParameterListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParameterListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParameterListSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(openParenToken, this.parameters, this.closeParenToken); + }; + + ParameterListSyntax.prototype.withParameters = function (parameters) { + return this.update(this.openParenToken, parameters, this.closeParenToken); + }; + + ParameterListSyntax.prototype.withParameter = function (parameter) { + return this.withParameters(TypeScript.Syntax.separatedList([parameter])); + }; + + ParameterListSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.openParenToken, this.parameters, closeParenToken); + }; + + ParameterListSyntax.prototype.isTypeScriptSpecific = function () { + if (this.parameters.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ParameterListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParameterListSyntax = ParameterListSyntax; + + var TypeParameterListSyntax = (function (_super) { + __extends(TypeParameterListSyntax, _super); + function TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.typeParameters = typeParameters; + this.greaterThanToken = greaterThanToken; + } + TypeParameterListSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeParameterList(this); + }; + + TypeParameterListSyntax.prototype.kind = function () { + return 229 /* TypeParameterList */; + }; + + TypeParameterListSyntax.prototype.childCount = function () { + return 3; + }; + + TypeParameterListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.typeParameters; + case 2: + return this.greaterThanToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeParameterListSyntax.prototype.update = function (lessThanToken, typeParameters, greaterThanToken) { + if (this.lessThanToken === lessThanToken && this.typeParameters === typeParameters && this.greaterThanToken === greaterThanToken) { + return this; + } + + return new TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, this.parsedInStrictMode()); + }; + + TypeParameterListSyntax.create = function (lessThanToken, greaterThanToken) { + return new TypeParameterListSyntax(lessThanToken, TypeScript.Syntax.emptySeparatedList, greaterThanToken, false); + }; + + TypeParameterListSyntax.create1 = function () { + return new TypeParameterListSyntax(TypeScript.Syntax.token(80 /* LessThanToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(81 /* GreaterThanToken */), false); + }; + + TypeParameterListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeParameterListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeParameterListSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.typeParameters, this.greaterThanToken); + }; + + TypeParameterListSyntax.prototype.withTypeParameters = function (typeParameters) { + return this.update(this.lessThanToken, typeParameters, this.greaterThanToken); + }; + + TypeParameterListSyntax.prototype.withTypeParameter = function (typeParameter) { + return this.withTypeParameters(TypeScript.Syntax.separatedList([typeParameter])); + }; + + TypeParameterListSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.typeParameters, greaterThanToken); + }; + + TypeParameterListSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeParameterListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeParameterListSyntax = TypeParameterListSyntax; + + var TypeParameterSyntax = (function (_super) { + __extends(TypeParameterSyntax, _super); + function TypeParameterSyntax(identifier, constraint, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.constraint = constraint; + } + TypeParameterSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeParameter(this); + }; + + TypeParameterSyntax.prototype.kind = function () { + return 238 /* TypeParameter */; + }; + + TypeParameterSyntax.prototype.childCount = function () { + return 2; + }; + + TypeParameterSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.constraint; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeParameterSyntax.prototype.update = function (identifier, constraint) { + if (this.identifier === identifier && this.constraint === constraint) { + return this; + } + + return new TypeParameterSyntax(identifier, constraint, this.parsedInStrictMode()); + }; + + TypeParameterSyntax.create = function (identifier) { + return new TypeParameterSyntax(identifier, null, false); + }; + + TypeParameterSyntax.create1 = function (identifier) { + return new TypeParameterSyntax(identifier, null, false); + }; + + TypeParameterSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeParameterSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeParameterSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.constraint); + }; + + TypeParameterSyntax.prototype.withConstraint = function (constraint) { + return this.update(this.identifier, constraint); + }; + + TypeParameterSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeParameterSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeParameterSyntax = TypeParameterSyntax; + + var ConstraintSyntax = (function (_super) { + __extends(ConstraintSyntax, _super); + function ConstraintSyntax(extendsKeyword, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.extendsKeyword = extendsKeyword; + this.type = type; + } + ConstraintSyntax.prototype.accept = function (visitor) { + return visitor.visitConstraint(this); + }; + + ConstraintSyntax.prototype.kind = function () { + return 239 /* Constraint */; + }; + + ConstraintSyntax.prototype.childCount = function () { + return 2; + }; + + ConstraintSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.extendsKeyword; + case 1: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstraintSyntax.prototype.update = function (extendsKeyword, type) { + if (this.extendsKeyword === extendsKeyword && this.type === type) { + return this; + } + + return new ConstraintSyntax(extendsKeyword, type, this.parsedInStrictMode()); + }; + + ConstraintSyntax.create1 = function (type) { + return new ConstraintSyntax(TypeScript.Syntax.token(48 /* ExtendsKeyword */), type, false); + }; + + ConstraintSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstraintSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstraintSyntax.prototype.withExtendsKeyword = function (extendsKeyword) { + return this.update(extendsKeyword, this.type); + }; + + ConstraintSyntax.prototype.withType = function (type) { + return this.update(this.extendsKeyword, type); + }; + + ConstraintSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstraintSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstraintSyntax = ConstraintSyntax; + + var ElseClauseSyntax = (function (_super) { + __extends(ElseClauseSyntax, _super); + function ElseClauseSyntax(elseKeyword, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.elseKeyword = elseKeyword; + this.statement = statement; + } + ElseClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitElseClause(this); + }; + + ElseClauseSyntax.prototype.kind = function () { + return 235 /* ElseClause */; + }; + + ElseClauseSyntax.prototype.childCount = function () { + return 2; + }; + + ElseClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.elseKeyword; + case 1: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ElseClauseSyntax.prototype.update = function (elseKeyword, statement) { + if (this.elseKeyword === elseKeyword && this.statement === statement) { + return this; + } + + return new ElseClauseSyntax(elseKeyword, statement, this.parsedInStrictMode()); + }; + + ElseClauseSyntax.create1 = function (statement) { + return new ElseClauseSyntax(TypeScript.Syntax.token(23 /* ElseKeyword */), statement, false); + }; + + ElseClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ElseClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ElseClauseSyntax.prototype.withElseKeyword = function (elseKeyword) { + return this.update(elseKeyword, this.statement); + }; + + ElseClauseSyntax.prototype.withStatement = function (statement) { + return this.update(this.elseKeyword, statement); + }; + + ElseClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ElseClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ElseClauseSyntax = ElseClauseSyntax; + + var IfStatementSyntax = (function (_super) { + __extends(IfStatementSyntax, _super); + function IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.ifKeyword = ifKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + this.elseClause = elseClause; + } + IfStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitIfStatement(this); + }; + + IfStatementSyntax.prototype.kind = function () { + return 147 /* IfStatement */; + }; + + IfStatementSyntax.prototype.childCount = function () { + return 6; + }; + + IfStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.ifKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + case 5: + return this.elseClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IfStatementSyntax.prototype.isStatement = function () { + return true; + }; + + IfStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + IfStatementSyntax.prototype.update = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + if (this.ifKeyword === ifKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement && this.elseClause === elseClause) { + return this; + } + + return new IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, this.parsedInStrictMode()); + }; + + IfStatementSyntax.create = function (ifKeyword, openParenToken, condition, closeParenToken, statement) { + return new IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, null, false); + }; + + IfStatementSyntax.create1 = function (condition, statement) { + return new IfStatementSyntax(TypeScript.Syntax.token(28 /* IfKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, null, false); + }; + + IfStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IfStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IfStatementSyntax.prototype.withIfKeyword = function (ifKeyword) { + return this.update(ifKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.ifKeyword, openParenToken, this.condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.ifKeyword, this.openParenToken, condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, this.closeParenToken, statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withElseClause = function (elseClause) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement, elseClause); + }; + + IfStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + if (this.elseClause !== null && this.elseClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return IfStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IfStatementSyntax = IfStatementSyntax; + + var ExpressionStatementSyntax = (function (_super) { + __extends(ExpressionStatementSyntax, _super); + function ExpressionStatementSyntax(expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ExpressionStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitExpressionStatement(this); + }; + + ExpressionStatementSyntax.prototype.kind = function () { + return 149 /* ExpressionStatement */; + }; + + ExpressionStatementSyntax.prototype.childCount = function () { + return 2; + }; + + ExpressionStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExpressionStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ExpressionStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ExpressionStatementSyntax.prototype.update = function (expression, semicolonToken) { + if (this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ExpressionStatementSyntax(expression, semicolonToken, this.parsedInStrictMode()); + }; + + ExpressionStatementSyntax.create1 = function (expression) { + return new ExpressionStatementSyntax(expression, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ExpressionStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExpressionStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExpressionStatementSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.semicolonToken); + }; + + ExpressionStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.expression, semicolonToken); + }; + + ExpressionStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ExpressionStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExpressionStatementSyntax = ExpressionStatementSyntax; + + var ConstructorDeclarationSyntax = (function (_super) { + __extends(ConstructorDeclarationSyntax, _super); + function ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.constructorKeyword = constructorKeyword; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + ConstructorDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructorDeclaration(this); + }; + + ConstructorDeclarationSyntax.prototype.kind = function () { + return 137 /* ConstructorDeclaration */; + }; + + ConstructorDeclarationSyntax.prototype.childCount = function () { + return 5; + }; + + ConstructorDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.constructorKeyword; + case 2: + return this.callSignature; + case 3: + return this.block; + case 4: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructorDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + ConstructorDeclarationSyntax.prototype.update = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.constructorKeyword === constructorKeyword && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + ConstructorDeclarationSyntax.create = function (constructorKeyword, callSignature) { + return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, constructorKeyword, callSignature, null, null, false); + }; + + ConstructorDeclarationSyntax.create1 = function () { + return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(62 /* ConstructorKeyword */), CallSignatureSyntax.create1(), null, null, false); + }; + + ConstructorDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructorDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructorDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.constructorKeyword, this.callSignature, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ConstructorDeclarationSyntax.prototype.withConstructorKeyword = function (constructorKeyword) { + return this.update(this.modifiers, constructorKeyword, this.callSignature, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.constructorKeyword, callSignature, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.constructorKeyword, this.callSignature, block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.constructorKeyword, this.callSignature, this.block, semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructorDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructorDeclarationSyntax = ConstructorDeclarationSyntax; + + var MemberFunctionDeclarationSyntax = (function (_super) { + __extends(MemberFunctionDeclarationSyntax, _super); + function MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + MemberFunctionDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberFunctionDeclaration(this); + }; + + MemberFunctionDeclarationSyntax.prototype.kind = function () { + return 135 /* MemberFunctionDeclaration */; + }; + + MemberFunctionDeclarationSyntax.prototype.childCount = function () { + return 5; + }; + + MemberFunctionDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.propertyName; + case 2: + return this.callSignature; + case 3: + return this.block; + case 4: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberFunctionDeclarationSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + MemberFunctionDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + MemberFunctionDeclarationSyntax.prototype.update = function (modifiers, propertyName, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.propertyName === propertyName && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + MemberFunctionDeclarationSyntax.create = function (propertyName, callSignature) { + return new MemberFunctionDeclarationSyntax(TypeScript.Syntax.emptyList, propertyName, callSignature, null, null, false); + }; + + MemberFunctionDeclarationSyntax.create1 = function (propertyName) { + return new MemberFunctionDeclarationSyntax(TypeScript.Syntax.emptyList, propertyName, CallSignatureSyntax.create1(), null, null, false); + }; + + MemberFunctionDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberFunctionDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberFunctionDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.propertyName, this.callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + MemberFunctionDeclarationSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, propertyName, this.callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.propertyName, callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.propertyName, this.callSignature, block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.propertyName, this.callSignature, this.block, semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return MemberFunctionDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberFunctionDeclarationSyntax = MemberFunctionDeclarationSyntax; + + var GetAccessorSyntax = (function (_super) { + __extends(GetAccessorSyntax, _super); + function GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.getKeyword = getKeyword; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + this.block = block; + } + GetAccessorSyntax.prototype.accept = function (visitor) { + return visitor.visitGetAccessor(this); + }; + + GetAccessorSyntax.prototype.kind = function () { + return 139 /* GetAccessor */; + }; + + GetAccessorSyntax.prototype.childCount = function () { + return 6; + }; + + GetAccessorSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.getKeyword; + case 2: + return this.propertyName; + case 3: + return this.parameterList; + case 4: + return this.typeAnnotation; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + GetAccessorSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + GetAccessorSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + GetAccessorSyntax.prototype.isClassElement = function () { + return true; + }; + + GetAccessorSyntax.prototype.update = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + if (this.modifiers === modifiers && this.getKeyword === getKeyword && this.propertyName === propertyName && this.parameterList === parameterList && this.typeAnnotation === typeAnnotation && this.block === block) { + return this; + } + + return new GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, this.parsedInStrictMode()); + }; + + GetAccessorSyntax.create = function (getKeyword, propertyName, parameterList, block) { + return new GetAccessorSyntax(TypeScript.Syntax.emptyList, getKeyword, propertyName, parameterList, null, block, false); + }; + + GetAccessorSyntax.create1 = function (propertyName) { + return new GetAccessorSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(64 /* GetKeyword */), propertyName, ParameterListSyntax.create1(), null, BlockSyntax.create1(), false); + }; + + GetAccessorSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + GetAccessorSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + GetAccessorSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + GetAccessorSyntax.prototype.withGetKeyword = function (getKeyword) { + return this.update(this.modifiers, getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, this.getKeyword, propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, this.parameterList, typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, block); + }; + + GetAccessorSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.childCount() > 0) { + return true; + } + if (this.parameterList.isTypeScriptSpecific()) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return GetAccessorSyntax; + })(TypeScript.SyntaxNode); + TypeScript.GetAccessorSyntax = GetAccessorSyntax; + + var SetAccessorSyntax = (function (_super) { + __extends(SetAccessorSyntax, _super); + function SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.setKeyword = setKeyword; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.block = block; + } + SetAccessorSyntax.prototype.accept = function (visitor) { + return visitor.visitSetAccessor(this); + }; + + SetAccessorSyntax.prototype.kind = function () { + return 140 /* SetAccessor */; + }; + + SetAccessorSyntax.prototype.childCount = function () { + return 5; + }; + + SetAccessorSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.setKeyword; + case 2: + return this.propertyName; + case 3: + return this.parameterList; + case 4: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SetAccessorSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + SetAccessorSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + SetAccessorSyntax.prototype.isClassElement = function () { + return true; + }; + + SetAccessorSyntax.prototype.update = function (modifiers, setKeyword, propertyName, parameterList, block) { + if (this.modifiers === modifiers && this.setKeyword === setKeyword && this.propertyName === propertyName && this.parameterList === parameterList && this.block === block) { + return this; + } + + return new SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, this.parsedInStrictMode()); + }; + + SetAccessorSyntax.create = function (setKeyword, propertyName, parameterList, block) { + return new SetAccessorSyntax(TypeScript.Syntax.emptyList, setKeyword, propertyName, parameterList, block, false); + }; + + SetAccessorSyntax.create1 = function (propertyName) { + return new SetAccessorSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(68 /* SetKeyword */), propertyName, ParameterListSyntax.create1(), BlockSyntax.create1(), false); + }; + + SetAccessorSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SetAccessorSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SetAccessorSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.setKeyword, this.propertyName, this.parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + SetAccessorSyntax.prototype.withSetKeyword = function (setKeyword) { + return this.update(this.modifiers, setKeyword, this.propertyName, this.parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, this.setKeyword, propertyName, this.parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.modifiers, this.setKeyword, this.propertyName, parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.setKeyword, this.propertyName, this.parameterList, block); + }; + + SetAccessorSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return SetAccessorSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SetAccessorSyntax = SetAccessorSyntax; + + var MemberVariableDeclarationSyntax = (function (_super) { + __extends(MemberVariableDeclarationSyntax, _super); + function MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.variableDeclarator = variableDeclarator; + this.semicolonToken = semicolonToken; + } + MemberVariableDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberVariableDeclaration(this); + }; + + MemberVariableDeclarationSyntax.prototype.kind = function () { + return 136 /* MemberVariableDeclaration */; + }; + + MemberVariableDeclarationSyntax.prototype.childCount = function () { + return 3; + }; + + MemberVariableDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.variableDeclarator; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberVariableDeclarationSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + MemberVariableDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + MemberVariableDeclarationSyntax.prototype.update = function (modifiers, variableDeclarator, semicolonToken) { + if (this.modifiers === modifiers && this.variableDeclarator === variableDeclarator && this.semicolonToken === semicolonToken) { + return this; + } + + return new MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, this.parsedInStrictMode()); + }; + + MemberVariableDeclarationSyntax.create = function (variableDeclarator, semicolonToken) { + return new MemberVariableDeclarationSyntax(TypeScript.Syntax.emptyList, variableDeclarator, semicolonToken, false); + }; + + MemberVariableDeclarationSyntax.create1 = function (variableDeclarator) { + return new MemberVariableDeclarationSyntax(TypeScript.Syntax.emptyList, variableDeclarator, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + MemberVariableDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberVariableDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberVariableDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.variableDeclarator, this.semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + MemberVariableDeclarationSyntax.prototype.withVariableDeclarator = function (variableDeclarator) { + return this.update(this.modifiers, variableDeclarator, this.semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.variableDeclarator, semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return MemberVariableDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberVariableDeclarationSyntax = MemberVariableDeclarationSyntax; + + var IndexMemberDeclarationSyntax = (function (_super) { + __extends(IndexMemberDeclarationSyntax, _super); + function IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.indexSignature = indexSignature; + this.semicolonToken = semicolonToken; + } + IndexMemberDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitIndexMemberDeclaration(this); + }; + + IndexMemberDeclarationSyntax.prototype.kind = function () { + return 138 /* IndexMemberDeclaration */; + }; + + IndexMemberDeclarationSyntax.prototype.childCount = function () { + return 3; + }; + + IndexMemberDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.indexSignature; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IndexMemberDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + IndexMemberDeclarationSyntax.prototype.update = function (modifiers, indexSignature, semicolonToken) { + if (this.modifiers === modifiers && this.indexSignature === indexSignature && this.semicolonToken === semicolonToken) { + return this; + } + + return new IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, this.parsedInStrictMode()); + }; + + IndexMemberDeclarationSyntax.create = function (indexSignature, semicolonToken) { + return new IndexMemberDeclarationSyntax(TypeScript.Syntax.emptyList, indexSignature, semicolonToken, false); + }; + + IndexMemberDeclarationSyntax.create1 = function (indexSignature) { + return new IndexMemberDeclarationSyntax(TypeScript.Syntax.emptyList, indexSignature, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + IndexMemberDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IndexMemberDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IndexMemberDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.indexSignature, this.semicolonToken); + }; + + IndexMemberDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + IndexMemberDeclarationSyntax.prototype.withIndexSignature = function (indexSignature) { + return this.update(this.modifiers, indexSignature, this.semicolonToken); + }; + + IndexMemberDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.indexSignature, semicolonToken); + }; + + IndexMemberDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return IndexMemberDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IndexMemberDeclarationSyntax = IndexMemberDeclarationSyntax; + + var ThrowStatementSyntax = (function (_super) { + __extends(ThrowStatementSyntax, _super); + function ThrowStatementSyntax(throwKeyword, expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.throwKeyword = throwKeyword; + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ThrowStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitThrowStatement(this); + }; + + ThrowStatementSyntax.prototype.kind = function () { + return 157 /* ThrowStatement */; + }; + + ThrowStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ThrowStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.throwKeyword; + case 1: + return this.expression; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ThrowStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ThrowStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ThrowStatementSyntax.prototype.update = function (throwKeyword, expression, semicolonToken) { + if (this.throwKeyword === throwKeyword && this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ThrowStatementSyntax(throwKeyword, expression, semicolonToken, this.parsedInStrictMode()); + }; + + ThrowStatementSyntax.create1 = function (expression) { + return new ThrowStatementSyntax(TypeScript.Syntax.token(36 /* ThrowKeyword */), expression, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ThrowStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ThrowStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ThrowStatementSyntax.prototype.withThrowKeyword = function (throwKeyword) { + return this.update(throwKeyword, this.expression, this.semicolonToken); + }; + + ThrowStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.throwKeyword, expression, this.semicolonToken); + }; + + ThrowStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.throwKeyword, this.expression, semicolonToken); + }; + + ThrowStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ThrowStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ThrowStatementSyntax = ThrowStatementSyntax; + + var ReturnStatementSyntax = (function (_super) { + __extends(ReturnStatementSyntax, _super); + function ReturnStatementSyntax(returnKeyword, expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.returnKeyword = returnKeyword; + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ReturnStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitReturnStatement(this); + }; + + ReturnStatementSyntax.prototype.kind = function () { + return 150 /* ReturnStatement */; + }; + + ReturnStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ReturnStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.returnKeyword; + case 1: + return this.expression; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ReturnStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ReturnStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ReturnStatementSyntax.prototype.update = function (returnKeyword, expression, semicolonToken) { + if (this.returnKeyword === returnKeyword && this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ReturnStatementSyntax(returnKeyword, expression, semicolonToken, this.parsedInStrictMode()); + }; + + ReturnStatementSyntax.create = function (returnKeyword, semicolonToken) { + return new ReturnStatementSyntax(returnKeyword, null, semicolonToken, false); + }; + + ReturnStatementSyntax.create1 = function () { + return new ReturnStatementSyntax(TypeScript.Syntax.token(33 /* ReturnKeyword */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ReturnStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ReturnStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ReturnStatementSyntax.prototype.withReturnKeyword = function (returnKeyword) { + return this.update(returnKeyword, this.expression, this.semicolonToken); + }; + + ReturnStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.returnKeyword, expression, this.semicolonToken); + }; + + ReturnStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.returnKeyword, this.expression, semicolonToken); + }; + + ReturnStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression !== null && this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ReturnStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ReturnStatementSyntax = ReturnStatementSyntax; + + var ObjectCreationExpressionSyntax = (function (_super) { + __extends(ObjectCreationExpressionSyntax, _super); + function ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.expression = expression; + this.argumentList = argumentList; + } + ObjectCreationExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectCreationExpression(this); + }; + + ObjectCreationExpressionSyntax.prototype.kind = function () { + return 216 /* ObjectCreationExpression */; + }; + + ObjectCreationExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectCreationExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.expression; + case 2: + return this.argumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectCreationExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.update = function (newKeyword, expression, argumentList) { + if (this.newKeyword === newKeyword && this.expression === expression && this.argumentList === argumentList) { + return this; + } + + return new ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, this.parsedInStrictMode()); + }; + + ObjectCreationExpressionSyntax.create = function (newKeyword, expression) { + return new ObjectCreationExpressionSyntax(newKeyword, expression, null, false); + }; + + ObjectCreationExpressionSyntax.create1 = function (expression) { + return new ObjectCreationExpressionSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), expression, null, false); + }; + + ObjectCreationExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectCreationExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectCreationExpressionSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.expression, this.argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.newKeyword, expression, this.argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.withArgumentList = function (argumentList) { + return this.update(this.newKeyword, this.expression, argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentList !== null && this.argumentList.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ObjectCreationExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectCreationExpressionSyntax = ObjectCreationExpressionSyntax; + + var SwitchStatementSyntax = (function (_super) { + __extends(SwitchStatementSyntax, _super); + function SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.switchKeyword = switchKeyword; + this.openParenToken = openParenToken; + this.expression = expression; + this.closeParenToken = closeParenToken; + this.openBraceToken = openBraceToken; + this.switchClauses = switchClauses; + this.closeBraceToken = closeBraceToken; + } + SwitchStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitSwitchStatement(this); + }; + + SwitchStatementSyntax.prototype.kind = function () { + return 151 /* SwitchStatement */; + }; + + SwitchStatementSyntax.prototype.childCount = function () { + return 7; + }; + + SwitchStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.switchKeyword; + case 1: + return this.openParenToken; + case 2: + return this.expression; + case 3: + return this.closeParenToken; + case 4: + return this.openBraceToken; + case 5: + return this.switchClauses; + case 6: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SwitchStatementSyntax.prototype.isStatement = function () { + return true; + }; + + SwitchStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + SwitchStatementSyntax.prototype.update = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + if (this.switchKeyword === switchKeyword && this.openParenToken === openParenToken && this.expression === expression && this.closeParenToken === closeParenToken && this.openBraceToken === openBraceToken && this.switchClauses === switchClauses && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, this.parsedInStrictMode()); + }; + + SwitchStatementSyntax.create = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, closeBraceToken) { + return new SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + SwitchStatementSyntax.create1 = function (expression) { + return new SwitchStatementSyntax(TypeScript.Syntax.token(34 /* SwitchKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), expression, TypeScript.Syntax.token(73 /* CloseParenToken */), TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + SwitchStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SwitchStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SwitchStatementSyntax.prototype.withSwitchKeyword = function (switchKeyword) { + return this.update(switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.switchKeyword, openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.switchKeyword, this.openParenToken, expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withSwitchClauses = function (switchClauses) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withSwitchClause = function (switchClause) { + return this.withSwitchClauses(TypeScript.Syntax.list([switchClause])); + }; + + SwitchStatementSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, closeBraceToken); + }; + + SwitchStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.switchClauses.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SwitchStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SwitchStatementSyntax = SwitchStatementSyntax; + + var CaseSwitchClauseSyntax = (function (_super) { + __extends(CaseSwitchClauseSyntax, _super); + function CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.caseKeyword = caseKeyword; + this.expression = expression; + this.colonToken = colonToken; + this.statements = statements; + } + CaseSwitchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitCaseSwitchClause(this); + }; + + CaseSwitchClauseSyntax.prototype.kind = function () { + return 233 /* CaseSwitchClause */; + }; + + CaseSwitchClauseSyntax.prototype.childCount = function () { + return 4; + }; + + CaseSwitchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.caseKeyword; + case 1: + return this.expression; + case 2: + return this.colonToken; + case 3: + return this.statements; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CaseSwitchClauseSyntax.prototype.isSwitchClause = function () { + return true; + }; + + CaseSwitchClauseSyntax.prototype.update = function (caseKeyword, expression, colonToken, statements) { + if (this.caseKeyword === caseKeyword && this.expression === expression && this.colonToken === colonToken && this.statements === statements) { + return this; + } + + return new CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, this.parsedInStrictMode()); + }; + + CaseSwitchClauseSyntax.create = function (caseKeyword, expression, colonToken) { + return new CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, TypeScript.Syntax.emptyList, false); + }; + + CaseSwitchClauseSyntax.create1 = function (expression) { + return new CaseSwitchClauseSyntax(TypeScript.Syntax.token(16 /* CaseKeyword */), expression, TypeScript.Syntax.token(106 /* ColonToken */), TypeScript.Syntax.emptyList, false); + }; + + CaseSwitchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CaseSwitchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CaseSwitchClauseSyntax.prototype.withCaseKeyword = function (caseKeyword) { + return this.update(caseKeyword, this.expression, this.colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withExpression = function (expression) { + return this.update(this.caseKeyword, expression, this.colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.caseKeyword, this.expression, colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withStatements = function (statements) { + return this.update(this.caseKeyword, this.expression, this.colonToken, statements); + }; + + CaseSwitchClauseSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + CaseSwitchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return CaseSwitchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CaseSwitchClauseSyntax = CaseSwitchClauseSyntax; + + var DefaultSwitchClauseSyntax = (function (_super) { + __extends(DefaultSwitchClauseSyntax, _super); + function DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.defaultKeyword = defaultKeyword; + this.colonToken = colonToken; + this.statements = statements; + } + DefaultSwitchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitDefaultSwitchClause(this); + }; + + DefaultSwitchClauseSyntax.prototype.kind = function () { + return 234 /* DefaultSwitchClause */; + }; + + DefaultSwitchClauseSyntax.prototype.childCount = function () { + return 3; + }; + + DefaultSwitchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.defaultKeyword; + case 1: + return this.colonToken; + case 2: + return this.statements; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DefaultSwitchClauseSyntax.prototype.isSwitchClause = function () { + return true; + }; + + DefaultSwitchClauseSyntax.prototype.update = function (defaultKeyword, colonToken, statements) { + if (this.defaultKeyword === defaultKeyword && this.colonToken === colonToken && this.statements === statements) { + return this; + } + + return new DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, this.parsedInStrictMode()); + }; + + DefaultSwitchClauseSyntax.create = function (defaultKeyword, colonToken) { + return new DefaultSwitchClauseSyntax(defaultKeyword, colonToken, TypeScript.Syntax.emptyList, false); + }; + + DefaultSwitchClauseSyntax.create1 = function () { + return new DefaultSwitchClauseSyntax(TypeScript.Syntax.token(20 /* DefaultKeyword */), TypeScript.Syntax.token(106 /* ColonToken */), TypeScript.Syntax.emptyList, false); + }; + + DefaultSwitchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DefaultSwitchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DefaultSwitchClauseSyntax.prototype.withDefaultKeyword = function (defaultKeyword) { + return this.update(defaultKeyword, this.colonToken, this.statements); + }; + + DefaultSwitchClauseSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.defaultKeyword, colonToken, this.statements); + }; + + DefaultSwitchClauseSyntax.prototype.withStatements = function (statements) { + return this.update(this.defaultKeyword, this.colonToken, statements); + }; + + DefaultSwitchClauseSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + DefaultSwitchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DefaultSwitchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DefaultSwitchClauseSyntax = DefaultSwitchClauseSyntax; + + var BreakStatementSyntax = (function (_super) { + __extends(BreakStatementSyntax, _super); + function BreakStatementSyntax(breakKeyword, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.breakKeyword = breakKeyword; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + BreakStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitBreakStatement(this); + }; + + BreakStatementSyntax.prototype.kind = function () { + return 152 /* BreakStatement */; + }; + + BreakStatementSyntax.prototype.childCount = function () { + return 3; + }; + + BreakStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.breakKeyword; + case 1: + return this.identifier; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BreakStatementSyntax.prototype.isStatement = function () { + return true; + }; + + BreakStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + BreakStatementSyntax.prototype.update = function (breakKeyword, identifier, semicolonToken) { + if (this.breakKeyword === breakKeyword && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new BreakStatementSyntax(breakKeyword, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + BreakStatementSyntax.create = function (breakKeyword, semicolonToken) { + return new BreakStatementSyntax(breakKeyword, null, semicolonToken, false); + }; + + BreakStatementSyntax.create1 = function () { + return new BreakStatementSyntax(TypeScript.Syntax.token(15 /* BreakKeyword */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + BreakStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BreakStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BreakStatementSyntax.prototype.withBreakKeyword = function (breakKeyword) { + return this.update(breakKeyword, this.identifier, this.semicolonToken); + }; + + BreakStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.breakKeyword, identifier, this.semicolonToken); + }; + + BreakStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.breakKeyword, this.identifier, semicolonToken); + }; + + BreakStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return BreakStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BreakStatementSyntax = BreakStatementSyntax; + + var ContinueStatementSyntax = (function (_super) { + __extends(ContinueStatementSyntax, _super); + function ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.continueKeyword = continueKeyword; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + ContinueStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitContinueStatement(this); + }; + + ContinueStatementSyntax.prototype.kind = function () { + return 153 /* ContinueStatement */; + }; + + ContinueStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ContinueStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.continueKeyword; + case 1: + return this.identifier; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ContinueStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ContinueStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ContinueStatementSyntax.prototype.update = function (continueKeyword, identifier, semicolonToken) { + if (this.continueKeyword === continueKeyword && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + ContinueStatementSyntax.create = function (continueKeyword, semicolonToken) { + return new ContinueStatementSyntax(continueKeyword, null, semicolonToken, false); + }; + + ContinueStatementSyntax.create1 = function () { + return new ContinueStatementSyntax(TypeScript.Syntax.token(18 /* ContinueKeyword */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ContinueStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ContinueStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ContinueStatementSyntax.prototype.withContinueKeyword = function (continueKeyword) { + return this.update(continueKeyword, this.identifier, this.semicolonToken); + }; + + ContinueStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.continueKeyword, identifier, this.semicolonToken); + }; + + ContinueStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.continueKeyword, this.identifier, semicolonToken); + }; + + ContinueStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return ContinueStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ContinueStatementSyntax = ContinueStatementSyntax; + + var ForStatementSyntax = (function (_super) { + __extends(ForStatementSyntax, _super); + function ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.forKeyword = forKeyword; + this.openParenToken = openParenToken; + this.variableDeclaration = variableDeclaration; + this.initializer = initializer; + this.firstSemicolonToken = firstSemicolonToken; + this.condition = condition; + this.secondSemicolonToken = secondSemicolonToken; + this.incrementor = incrementor; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + ForStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitForStatement(this); + }; + + ForStatementSyntax.prototype.kind = function () { + return 154 /* ForStatement */; + }; + + ForStatementSyntax.prototype.childCount = function () { + return 10; + }; + + ForStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.forKeyword; + case 1: + return this.openParenToken; + case 2: + return this.variableDeclaration; + case 3: + return this.initializer; + case 4: + return this.firstSemicolonToken; + case 5: + return this.condition; + case 6: + return this.secondSemicolonToken; + case 7: + return this.incrementor; + case 8: + return this.closeParenToken; + case 9: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ForStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + ForStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ForStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ForStatementSyntax.prototype.update = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + if (this.forKeyword === forKeyword && this.openParenToken === openParenToken && this.variableDeclaration === variableDeclaration && this.initializer === initializer && this.firstSemicolonToken === firstSemicolonToken && this.condition === condition && this.secondSemicolonToken === secondSemicolonToken && this.incrementor === incrementor && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, this.parsedInStrictMode()); + }; + + ForStatementSyntax.create = function (forKeyword, openParenToken, firstSemicolonToken, secondSemicolonToken, closeParenToken, statement) { + return new ForStatementSyntax(forKeyword, openParenToken, null, null, firstSemicolonToken, null, secondSemicolonToken, null, closeParenToken, statement, false); + }; + + ForStatementSyntax.create1 = function (statement) { + return new ForStatementSyntax(TypeScript.Syntax.token(26 /* ForKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), null, null, TypeScript.Syntax.token(78 /* SemicolonToken */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), null, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + ForStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ForStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ForStatementSyntax.prototype.withForKeyword = function (forKeyword) { + return this.update(forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.forKeyword, openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.forKeyword, this.openParenToken, variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withInitializer = function (initializer) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withFirstSemicolonToken = function (firstSemicolonToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withSecondSemicolonToken = function (secondSemicolonToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withIncrementor = function (incrementor) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, statement); + }; + + ForStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclaration !== null && this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + if (this.initializer !== null && this.initializer.isTypeScriptSpecific()) { + return true; + } + if (this.condition !== null && this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.incrementor !== null && this.incrementor.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ForStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ForStatementSyntax = ForStatementSyntax; + + var ForInStatementSyntax = (function (_super) { + __extends(ForInStatementSyntax, _super); + function ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.forKeyword = forKeyword; + this.openParenToken = openParenToken; + this.variableDeclaration = variableDeclaration; + this.left = left; + this.inKeyword = inKeyword; + this.expression = expression; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + ForInStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitForInStatement(this); + }; + + ForInStatementSyntax.prototype.kind = function () { + return 155 /* ForInStatement */; + }; + + ForInStatementSyntax.prototype.childCount = function () { + return 8; + }; + + ForInStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.forKeyword; + case 1: + return this.openParenToken; + case 2: + return this.variableDeclaration; + case 3: + return this.left; + case 4: + return this.inKeyword; + case 5: + return this.expression; + case 6: + return this.closeParenToken; + case 7: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ForInStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + ForInStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ForInStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ForInStatementSyntax.prototype.update = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + if (this.forKeyword === forKeyword && this.openParenToken === openParenToken && this.variableDeclaration === variableDeclaration && this.left === left && this.inKeyword === inKeyword && this.expression === expression && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, this.parsedInStrictMode()); + }; + + ForInStatementSyntax.create = function (forKeyword, openParenToken, inKeyword, expression, closeParenToken, statement) { + return new ForInStatementSyntax(forKeyword, openParenToken, null, null, inKeyword, expression, closeParenToken, statement, false); + }; + + ForInStatementSyntax.create1 = function (expression, statement) { + return new ForInStatementSyntax(TypeScript.Syntax.token(26 /* ForKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), null, null, TypeScript.Syntax.token(29 /* InKeyword */), expression, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + ForInStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ForInStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ForInStatementSyntax.prototype.withForKeyword = function (forKeyword) { + return this.update(forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.forKeyword, openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.forKeyword, this.openParenToken, variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withLeft = function (left) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withInKeyword = function (inKeyword) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, statement); + }; + + ForInStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclaration !== null && this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + if (this.left !== null && this.left.isTypeScriptSpecific()) { + return true; + } + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ForInStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ForInStatementSyntax = ForInStatementSyntax; + + var WhileStatementSyntax = (function (_super) { + __extends(WhileStatementSyntax, _super); + function WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.whileKeyword = whileKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + WhileStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitWhileStatement(this); + }; + + WhileStatementSyntax.prototype.kind = function () { + return 158 /* WhileStatement */; + }; + + WhileStatementSyntax.prototype.childCount = function () { + return 5; + }; + + WhileStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.whileKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + WhileStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + WhileStatementSyntax.prototype.isStatement = function () { + return true; + }; + + WhileStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + WhileStatementSyntax.prototype.update = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + if (this.whileKeyword === whileKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, this.parsedInStrictMode()); + }; + + WhileStatementSyntax.create1 = function (condition, statement) { + return new WhileStatementSyntax(TypeScript.Syntax.token(42 /* WhileKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + WhileStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + WhileStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + WhileStatementSyntax.prototype.withWhileKeyword = function (whileKeyword) { + return this.update(whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.whileKeyword, openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.whileKeyword, this.openParenToken, condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.whileKeyword, this.openParenToken, this.condition, closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, statement); + }; + + WhileStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return WhileStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.WhileStatementSyntax = WhileStatementSyntax; + + var WithStatementSyntax = (function (_super) { + __extends(WithStatementSyntax, _super); + function WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.withKeyword = withKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + WithStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitWithStatement(this); + }; + + WithStatementSyntax.prototype.kind = function () { + return 163 /* WithStatement */; + }; + + WithStatementSyntax.prototype.childCount = function () { + return 5; + }; + + WithStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.withKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + WithStatementSyntax.prototype.isStatement = function () { + return true; + }; + + WithStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + WithStatementSyntax.prototype.update = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + if (this.withKeyword === withKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, this.parsedInStrictMode()); + }; + + WithStatementSyntax.create1 = function (condition, statement) { + return new WithStatementSyntax(TypeScript.Syntax.token(43 /* WithKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + WithStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + WithStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + WithStatementSyntax.prototype.withWithKeyword = function (withKeyword) { + return this.update(withKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.withKeyword, openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.withKeyword, this.openParenToken, condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.withKeyword, this.openParenToken, this.condition, closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.withKeyword, this.openParenToken, this.condition, this.closeParenToken, statement); + }; + + WithStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return WithStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.WithStatementSyntax = WithStatementSyntax; + + var EnumDeclarationSyntax = (function (_super) { + __extends(EnumDeclarationSyntax, _super); + function EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.enumKeyword = enumKeyword; + this.identifier = identifier; + this.openBraceToken = openBraceToken; + this.enumElements = enumElements; + this.closeBraceToken = closeBraceToken; + } + EnumDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitEnumDeclaration(this); + }; + + EnumDeclarationSyntax.prototype.kind = function () { + return 132 /* EnumDeclaration */; + }; + + EnumDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + EnumDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.enumKeyword; + case 2: + return this.identifier; + case 3: + return this.openBraceToken; + case 4: + return this.enumElements; + case 5: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EnumDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + EnumDeclarationSyntax.prototype.update = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + if (this.modifiers === modifiers && this.enumKeyword === enumKeyword && this.identifier === identifier && this.openBraceToken === openBraceToken && this.enumElements === enumElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, this.parsedInStrictMode()); + }; + + EnumDeclarationSyntax.create = function (enumKeyword, identifier, openBraceToken, closeBraceToken) { + return new EnumDeclarationSyntax(TypeScript.Syntax.emptyList, enumKeyword, identifier, openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + EnumDeclarationSyntax.create1 = function (identifier) { + return new EnumDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(46 /* EnumKeyword */), identifier, TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + EnumDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EnumDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EnumDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.enumKeyword, this.identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + EnumDeclarationSyntax.prototype.withEnumKeyword = function (enumKeyword) { + return this.update(this.modifiers, enumKeyword, this.identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.enumKeyword, identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withEnumElements = function (enumElements) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, this.openBraceToken, enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withEnumElement = function (enumElement) { + return this.withEnumElements(TypeScript.Syntax.separatedList([enumElement])); + }; + + EnumDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, this.openBraceToken, this.enumElements, closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return EnumDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EnumDeclarationSyntax = EnumDeclarationSyntax; + + var EnumElementSyntax = (function (_super) { + __extends(EnumElementSyntax, _super); + function EnumElementSyntax(propertyName, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.equalsValueClause = equalsValueClause; + } + EnumElementSyntax.prototype.accept = function (visitor) { + return visitor.visitEnumElement(this); + }; + + EnumElementSyntax.prototype.kind = function () { + return 243 /* EnumElement */; + }; + + EnumElementSyntax.prototype.childCount = function () { + return 2; + }; + + EnumElementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EnumElementSyntax.prototype.update = function (propertyName, equalsValueClause) { + if (this.propertyName === propertyName && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new EnumElementSyntax(propertyName, equalsValueClause, this.parsedInStrictMode()); + }; + + EnumElementSyntax.create = function (propertyName) { + return new EnumElementSyntax(propertyName, null, false); + }; + + EnumElementSyntax.create1 = function (propertyName) { + return new EnumElementSyntax(propertyName, null, false); + }; + + EnumElementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EnumElementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EnumElementSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.equalsValueClause); + }; + + EnumElementSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.propertyName, equalsValueClause); + }; + + EnumElementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.equalsValueClause !== null && this.equalsValueClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return EnumElementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EnumElementSyntax = EnumElementSyntax; + + var CastExpressionSyntax = (function (_super) { + __extends(CastExpressionSyntax, _super); + function CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.type = type; + this.greaterThanToken = greaterThanToken; + this.expression = expression; + } + CastExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitCastExpression(this); + }; + + CastExpressionSyntax.prototype.kind = function () { + return 220 /* CastExpression */; + }; + + CastExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + CastExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.type; + case 2: + return this.greaterThanToken; + case 3: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CastExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + CastExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + CastExpressionSyntax.prototype.update = function (lessThanToken, type, greaterThanToken, expression) { + if (this.lessThanToken === lessThanToken && this.type === type && this.greaterThanToken === greaterThanToken && this.expression === expression) { + return this; + } + + return new CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, this.parsedInStrictMode()); + }; + + CastExpressionSyntax.create1 = function (type, expression) { + return new CastExpressionSyntax(TypeScript.Syntax.token(80 /* LessThanToken */), type, TypeScript.Syntax.token(81 /* GreaterThanToken */), expression, false); + }; + + CastExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CastExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CastExpressionSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.type, this.greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withType = function (type) { + return this.update(this.lessThanToken, type, this.greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.type, greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.lessThanToken, this.type, this.greaterThanToken, expression); + }; + + CastExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return CastExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CastExpressionSyntax = CastExpressionSyntax; + + var ObjectLiteralExpressionSyntax = (function (_super) { + __extends(ObjectLiteralExpressionSyntax, _super); + function ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.propertyAssignments = propertyAssignments; + this.closeBraceToken = closeBraceToken; + } + ObjectLiteralExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectLiteralExpression(this); + }; + + ObjectLiteralExpressionSyntax.prototype.kind = function () { + return 215 /* ObjectLiteralExpression */; + }; + + ObjectLiteralExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectLiteralExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.propertyAssignments; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectLiteralExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.update = function (openBraceToken, propertyAssignments, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.propertyAssignments === propertyAssignments && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, this.parsedInStrictMode()); + }; + + ObjectLiteralExpressionSyntax.create = function (openBraceToken, closeBraceToken) { + return new ObjectLiteralExpressionSyntax(openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + ObjectLiteralExpressionSyntax.create1 = function () { + return new ObjectLiteralExpressionSyntax(TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ObjectLiteralExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectLiteralExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectLiteralExpressionSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.propertyAssignments, this.closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.withPropertyAssignments = function (propertyAssignments) { + return this.update(this.openBraceToken, propertyAssignments, this.closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.withPropertyAssignment = function (propertyAssignment) { + return this.withPropertyAssignments(TypeScript.Syntax.separatedList([propertyAssignment])); + }; + + ObjectLiteralExpressionSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.propertyAssignments, closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.propertyAssignments.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ObjectLiteralExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectLiteralExpressionSyntax = ObjectLiteralExpressionSyntax; + + var SimplePropertyAssignmentSyntax = (function (_super) { + __extends(SimplePropertyAssignmentSyntax, _super); + function SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.colonToken = colonToken; + this.expression = expression; + } + SimplePropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitSimplePropertyAssignment(this); + }; + + SimplePropertyAssignmentSyntax.prototype.kind = function () { + return 240 /* SimplePropertyAssignment */; + }; + + SimplePropertyAssignmentSyntax.prototype.childCount = function () { + return 3; + }; + + SimplePropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.colonToken; + case 2: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SimplePropertyAssignmentSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + SimplePropertyAssignmentSyntax.prototype.update = function (propertyName, colonToken, expression) { + if (this.propertyName === propertyName && this.colonToken === colonToken && this.expression === expression) { + return this; + } + + return new SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, this.parsedInStrictMode()); + }; + + SimplePropertyAssignmentSyntax.create1 = function (propertyName, expression) { + return new SimplePropertyAssignmentSyntax(propertyName, TypeScript.Syntax.token(106 /* ColonToken */), expression, false); + }; + + SimplePropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SimplePropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SimplePropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.colonToken, this.expression); + }; + + SimplePropertyAssignmentSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.propertyName, colonToken, this.expression); + }; + + SimplePropertyAssignmentSyntax.prototype.withExpression = function (expression) { + return this.update(this.propertyName, this.colonToken, expression); + }; + + SimplePropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SimplePropertyAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SimplePropertyAssignmentSyntax = SimplePropertyAssignmentSyntax; + + var FunctionPropertyAssignmentSyntax = (function (_super) { + __extends(FunctionPropertyAssignmentSyntax, _super); + function FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + } + FunctionPropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionPropertyAssignment(this); + }; + + FunctionPropertyAssignmentSyntax.prototype.kind = function () { + return 241 /* FunctionPropertyAssignment */; + }; + + FunctionPropertyAssignmentSyntax.prototype.childCount = function () { + return 3; + }; + + FunctionPropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.callSignature; + case 2: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionPropertyAssignmentSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + FunctionPropertyAssignmentSyntax.prototype.update = function (propertyName, callSignature, block) { + if (this.propertyName === propertyName && this.callSignature === callSignature && this.block === block) { + return this; + } + + return new FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, this.parsedInStrictMode()); + }; + + FunctionPropertyAssignmentSyntax.create1 = function (propertyName) { + return new FunctionPropertyAssignmentSyntax(propertyName, CallSignatureSyntax.create1(), BlockSyntax.create1(), false); + }; + + FunctionPropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionPropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionPropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.callSignature, this.block); + }; + + FunctionPropertyAssignmentSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.propertyName, callSignature, this.block); + }; + + FunctionPropertyAssignmentSyntax.prototype.withBlock = function (block) { + return this.update(this.propertyName, this.callSignature, block); + }; + + FunctionPropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionPropertyAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionPropertyAssignmentSyntax = FunctionPropertyAssignmentSyntax; + + var FunctionExpressionSyntax = (function (_super) { + __extends(FunctionExpressionSyntax, _super); + function FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.functionKeyword = functionKeyword; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + } + FunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionExpression(this); + }; + + FunctionExpressionSyntax.prototype.kind = function () { + return 222 /* FunctionExpression */; + }; + + FunctionExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + FunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.functionKeyword; + case 1: + return this.identifier; + case 2: + return this.callSignature; + case 3: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.update = function (functionKeyword, identifier, callSignature, block) { + if (this.functionKeyword === functionKeyword && this.identifier === identifier && this.callSignature === callSignature && this.block === block) { + return this; + } + + return new FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, this.parsedInStrictMode()); + }; + + FunctionExpressionSyntax.create = function (functionKeyword, callSignature, block) { + return new FunctionExpressionSyntax(functionKeyword, null, callSignature, block, false); + }; + + FunctionExpressionSyntax.create1 = function () { + return new FunctionExpressionSyntax(TypeScript.Syntax.token(27 /* FunctionKeyword */), null, CallSignatureSyntax.create1(), BlockSyntax.create1(), false); + }; + + FunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionExpressionSyntax.prototype.withFunctionKeyword = function (functionKeyword) { + return this.update(functionKeyword, this.identifier, this.callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.functionKeyword, identifier, this.callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.functionKeyword, this.identifier, callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withBlock = function (block) { + return this.update(this.functionKeyword, this.identifier, this.callSignature, block); + }; + + FunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionExpressionSyntax = FunctionExpressionSyntax; + + var EmptyStatementSyntax = (function (_super) { + __extends(EmptyStatementSyntax, _super); + function EmptyStatementSyntax(semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.semicolonToken = semicolonToken; + } + EmptyStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitEmptyStatement(this); + }; + + EmptyStatementSyntax.prototype.kind = function () { + return 156 /* EmptyStatement */; + }; + + EmptyStatementSyntax.prototype.childCount = function () { + return 1; + }; + + EmptyStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EmptyStatementSyntax.prototype.isStatement = function () { + return true; + }; + + EmptyStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + EmptyStatementSyntax.prototype.update = function (semicolonToken) { + if (this.semicolonToken === semicolonToken) { + return this; + } + + return new EmptyStatementSyntax(semicolonToken, this.parsedInStrictMode()); + }; + + EmptyStatementSyntax.create1 = function () { + return new EmptyStatementSyntax(TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + EmptyStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EmptyStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EmptyStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(semicolonToken); + }; + + EmptyStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return EmptyStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EmptyStatementSyntax = EmptyStatementSyntax; + + var TryStatementSyntax = (function (_super) { + __extends(TryStatementSyntax, _super); + function TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.tryKeyword = tryKeyword; + this.block = block; + this.catchClause = catchClause; + this.finallyClause = finallyClause; + } + TryStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitTryStatement(this); + }; + + TryStatementSyntax.prototype.kind = function () { + return 159 /* TryStatement */; + }; + + TryStatementSyntax.prototype.childCount = function () { + return 4; + }; + + TryStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.tryKeyword; + case 1: + return this.block; + case 2: + return this.catchClause; + case 3: + return this.finallyClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TryStatementSyntax.prototype.isStatement = function () { + return true; + }; + + TryStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + TryStatementSyntax.prototype.update = function (tryKeyword, block, catchClause, finallyClause) { + if (this.tryKeyword === tryKeyword && this.block === block && this.catchClause === catchClause && this.finallyClause === finallyClause) { + return this; + } + + return new TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, this.parsedInStrictMode()); + }; + + TryStatementSyntax.create = function (tryKeyword, block) { + return new TryStatementSyntax(tryKeyword, block, null, null, false); + }; + + TryStatementSyntax.create1 = function () { + return new TryStatementSyntax(TypeScript.Syntax.token(38 /* TryKeyword */), BlockSyntax.create1(), null, null, false); + }; + + TryStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TryStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TryStatementSyntax.prototype.withTryKeyword = function (tryKeyword) { + return this.update(tryKeyword, this.block, this.catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withBlock = function (block) { + return this.update(this.tryKeyword, block, this.catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withCatchClause = function (catchClause) { + return this.update(this.tryKeyword, this.block, catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withFinallyClause = function (finallyClause) { + return this.update(this.tryKeyword, this.block, this.catchClause, finallyClause); + }; + + TryStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.block.isTypeScriptSpecific()) { + return true; + } + if (this.catchClause !== null && this.catchClause.isTypeScriptSpecific()) { + return true; + } + if (this.finallyClause !== null && this.finallyClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return TryStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TryStatementSyntax = TryStatementSyntax; + + var CatchClauseSyntax = (function (_super) { + __extends(CatchClauseSyntax, _super); + function CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.catchKeyword = catchKeyword; + this.openParenToken = openParenToken; + this.identifier = identifier; + this.typeAnnotation = typeAnnotation; + this.closeParenToken = closeParenToken; + this.block = block; + } + CatchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitCatchClause(this); + }; + + CatchClauseSyntax.prototype.kind = function () { + return 236 /* CatchClause */; + }; + + CatchClauseSyntax.prototype.childCount = function () { + return 6; + }; + + CatchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.catchKeyword; + case 1: + return this.openParenToken; + case 2: + return this.identifier; + case 3: + return this.typeAnnotation; + case 4: + return this.closeParenToken; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CatchClauseSyntax.prototype.update = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + if (this.catchKeyword === catchKeyword && this.openParenToken === openParenToken && this.identifier === identifier && this.typeAnnotation === typeAnnotation && this.closeParenToken === closeParenToken && this.block === block) { + return this; + } + + return new CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, this.parsedInStrictMode()); + }; + + CatchClauseSyntax.create = function (catchKeyword, openParenToken, identifier, closeParenToken, block) { + return new CatchClauseSyntax(catchKeyword, openParenToken, identifier, null, closeParenToken, block, false); + }; + + CatchClauseSyntax.create1 = function (identifier) { + return new CatchClauseSyntax(TypeScript.Syntax.token(17 /* CatchKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), identifier, null, TypeScript.Syntax.token(73 /* CloseParenToken */), BlockSyntax.create1(), false); + }; + + CatchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CatchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CatchClauseSyntax.prototype.withCatchKeyword = function (catchKeyword) { + return this.update(catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.catchKeyword, openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.catchKeyword, this.openParenToken, identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withBlock = function (block) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, block); + }; + + CatchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeAnnotation !== null && this.typeAnnotation.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return CatchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CatchClauseSyntax = CatchClauseSyntax; + + var FinallyClauseSyntax = (function (_super) { + __extends(FinallyClauseSyntax, _super); + function FinallyClauseSyntax(finallyKeyword, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.finallyKeyword = finallyKeyword; + this.block = block; + } + FinallyClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitFinallyClause(this); + }; + + FinallyClauseSyntax.prototype.kind = function () { + return 237 /* FinallyClause */; + }; + + FinallyClauseSyntax.prototype.childCount = function () { + return 2; + }; + + FinallyClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.finallyKeyword; + case 1: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FinallyClauseSyntax.prototype.update = function (finallyKeyword, block) { + if (this.finallyKeyword === finallyKeyword && this.block === block) { + return this; + } + + return new FinallyClauseSyntax(finallyKeyword, block, this.parsedInStrictMode()); + }; + + FinallyClauseSyntax.create1 = function () { + return new FinallyClauseSyntax(TypeScript.Syntax.token(25 /* FinallyKeyword */), BlockSyntax.create1(), false); + }; + + FinallyClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FinallyClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FinallyClauseSyntax.prototype.withFinallyKeyword = function (finallyKeyword) { + return this.update(finallyKeyword, this.block); + }; + + FinallyClauseSyntax.prototype.withBlock = function (block) { + return this.update(this.finallyKeyword, block); + }; + + FinallyClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FinallyClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FinallyClauseSyntax = FinallyClauseSyntax; + + var LabeledStatementSyntax = (function (_super) { + __extends(LabeledStatementSyntax, _super); + function LabeledStatementSyntax(identifier, colonToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.colonToken = colonToken; + this.statement = statement; + } + LabeledStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitLabeledStatement(this); + }; + + LabeledStatementSyntax.prototype.kind = function () { + return 160 /* LabeledStatement */; + }; + + LabeledStatementSyntax.prototype.childCount = function () { + return 3; + }; + + LabeledStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.colonToken; + case 2: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + LabeledStatementSyntax.prototype.isStatement = function () { + return true; + }; + + LabeledStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + LabeledStatementSyntax.prototype.update = function (identifier, colonToken, statement) { + if (this.identifier === identifier && this.colonToken === colonToken && this.statement === statement) { + return this; + } + + return new LabeledStatementSyntax(identifier, colonToken, statement, this.parsedInStrictMode()); + }; + + LabeledStatementSyntax.create1 = function (identifier, statement) { + return new LabeledStatementSyntax(identifier, TypeScript.Syntax.token(106 /* ColonToken */), statement, false); + }; + + LabeledStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + LabeledStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + LabeledStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.colonToken, this.statement); + }; + + LabeledStatementSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.identifier, colonToken, this.statement); + }; + + LabeledStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.identifier, this.colonToken, statement); + }; + + LabeledStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return LabeledStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.LabeledStatementSyntax = LabeledStatementSyntax; + + var DoStatementSyntax = (function (_super) { + __extends(DoStatementSyntax, _super); + function DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.doKeyword = doKeyword; + this.statement = statement; + this.whileKeyword = whileKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.semicolonToken = semicolonToken; + } + DoStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitDoStatement(this); + }; + + DoStatementSyntax.prototype.kind = function () { + return 161 /* DoStatement */; + }; + + DoStatementSyntax.prototype.childCount = function () { + return 7; + }; + + DoStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.doKeyword; + case 1: + return this.statement; + case 2: + return this.whileKeyword; + case 3: + return this.openParenToken; + case 4: + return this.condition; + case 5: + return this.closeParenToken; + case 6: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DoStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + DoStatementSyntax.prototype.isStatement = function () { + return true; + }; + + DoStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + DoStatementSyntax.prototype.update = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + if (this.doKeyword === doKeyword && this.statement === statement && this.whileKeyword === whileKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.semicolonToken === semicolonToken) { + return this; + } + + return new DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, this.parsedInStrictMode()); + }; + + DoStatementSyntax.create1 = function (statement, condition) { + return new DoStatementSyntax(TypeScript.Syntax.token(22 /* DoKeyword */), statement, TypeScript.Syntax.token(42 /* WhileKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + DoStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DoStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DoStatementSyntax.prototype.withDoKeyword = function (doKeyword) { + return this.update(doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.doKeyword, statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withWhileKeyword = function (whileKeyword) { + return this.update(this.doKeyword, this.statement, whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, semicolonToken); + }; + + DoStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + if (this.condition.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DoStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DoStatementSyntax = DoStatementSyntax; + + var TypeOfExpressionSyntax = (function (_super) { + __extends(TypeOfExpressionSyntax, _super); + function TypeOfExpressionSyntax(typeOfKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeOfKeyword = typeOfKeyword; + this.expression = expression; + } + TypeOfExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeOfExpression(this); + }; + + TypeOfExpressionSyntax.prototype.kind = function () { + return 171 /* TypeOfExpression */; + }; + + TypeOfExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + TypeOfExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeOfKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeOfExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + TypeOfExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + TypeOfExpressionSyntax.prototype.update = function (typeOfKeyword, expression) { + if (this.typeOfKeyword === typeOfKeyword && this.expression === expression) { + return this; + } + + return new TypeOfExpressionSyntax(typeOfKeyword, expression, this.parsedInStrictMode()); + }; + + TypeOfExpressionSyntax.create1 = function (expression) { + return new TypeOfExpressionSyntax(TypeScript.Syntax.token(39 /* TypeOfKeyword */), expression, false); + }; + + TypeOfExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeOfExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeOfExpressionSyntax.prototype.withTypeOfKeyword = function (typeOfKeyword) { + return this.update(typeOfKeyword, this.expression); + }; + + TypeOfExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.typeOfKeyword, expression); + }; + + TypeOfExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return TypeOfExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeOfExpressionSyntax = TypeOfExpressionSyntax; + + var DeleteExpressionSyntax = (function (_super) { + __extends(DeleteExpressionSyntax, _super); + function DeleteExpressionSyntax(deleteKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.deleteKeyword = deleteKeyword; + this.expression = expression; + } + DeleteExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitDeleteExpression(this); + }; + + DeleteExpressionSyntax.prototype.kind = function () { + return 170 /* DeleteExpression */; + }; + + DeleteExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + DeleteExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.deleteKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DeleteExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + DeleteExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + DeleteExpressionSyntax.prototype.update = function (deleteKeyword, expression) { + if (this.deleteKeyword === deleteKeyword && this.expression === expression) { + return this; + } + + return new DeleteExpressionSyntax(deleteKeyword, expression, this.parsedInStrictMode()); + }; + + DeleteExpressionSyntax.create1 = function (expression) { + return new DeleteExpressionSyntax(TypeScript.Syntax.token(21 /* DeleteKeyword */), expression, false); + }; + + DeleteExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DeleteExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DeleteExpressionSyntax.prototype.withDeleteKeyword = function (deleteKeyword) { + return this.update(deleteKeyword, this.expression); + }; + + DeleteExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.deleteKeyword, expression); + }; + + DeleteExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DeleteExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DeleteExpressionSyntax = DeleteExpressionSyntax; + + var VoidExpressionSyntax = (function (_super) { + __extends(VoidExpressionSyntax, _super); + function VoidExpressionSyntax(voidKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.voidKeyword = voidKeyword; + this.expression = expression; + } + VoidExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitVoidExpression(this); + }; + + VoidExpressionSyntax.prototype.kind = function () { + return 172 /* VoidExpression */; + }; + + VoidExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + VoidExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.voidKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VoidExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + VoidExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + VoidExpressionSyntax.prototype.update = function (voidKeyword, expression) { + if (this.voidKeyword === voidKeyword && this.expression === expression) { + return this; + } + + return new VoidExpressionSyntax(voidKeyword, expression, this.parsedInStrictMode()); + }; + + VoidExpressionSyntax.create1 = function (expression) { + return new VoidExpressionSyntax(TypeScript.Syntax.token(41 /* VoidKeyword */), expression, false); + }; + + VoidExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VoidExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VoidExpressionSyntax.prototype.withVoidKeyword = function (voidKeyword) { + return this.update(voidKeyword, this.expression); + }; + + VoidExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.voidKeyword, expression); + }; + + VoidExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VoidExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VoidExpressionSyntax = VoidExpressionSyntax; + + var DebuggerStatementSyntax = (function (_super) { + __extends(DebuggerStatementSyntax, _super); + function DebuggerStatementSyntax(debuggerKeyword, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.debuggerKeyword = debuggerKeyword; + this.semicolonToken = semicolonToken; + } + DebuggerStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitDebuggerStatement(this); + }; + + DebuggerStatementSyntax.prototype.kind = function () { + return 162 /* DebuggerStatement */; + }; + + DebuggerStatementSyntax.prototype.childCount = function () { + return 2; + }; + + DebuggerStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.debuggerKeyword; + case 1: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DebuggerStatementSyntax.prototype.isStatement = function () { + return true; + }; + + DebuggerStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + DebuggerStatementSyntax.prototype.update = function (debuggerKeyword, semicolonToken) { + if (this.debuggerKeyword === debuggerKeyword && this.semicolonToken === semicolonToken) { + return this; + } + + return new DebuggerStatementSyntax(debuggerKeyword, semicolonToken, this.parsedInStrictMode()); + }; + + DebuggerStatementSyntax.create1 = function () { + return new DebuggerStatementSyntax(TypeScript.Syntax.token(19 /* DebuggerKeyword */), TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + DebuggerStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DebuggerStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DebuggerStatementSyntax.prototype.withDebuggerKeyword = function (debuggerKeyword) { + return this.update(debuggerKeyword, this.semicolonToken); + }; + + DebuggerStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.debuggerKeyword, semicolonToken); + }; + + DebuggerStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return DebuggerStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DebuggerStatementSyntax = DebuggerStatementSyntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxRewriter = (function () { + function SyntaxRewriter() { + } + SyntaxRewriter.prototype.visitToken = function (token) { + return token; + }; + + SyntaxRewriter.prototype.visitNode = function (node) { + return node.accept(this); + }; + + SyntaxRewriter.prototype.visitNodeOrToken = function (node) { + return node.isToken() ? this.visitToken(node) : this.visitNode(node); + }; + + SyntaxRewriter.prototype.visitList = function (list) { + var newItems = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + var newItem = this.visitNodeOrToken(item); + + if (item !== newItem && newItems === null) { + newItems = []; + for (var j = 0; j < i; j++) { + newItems.push(list.childAt(j)); + } + } + + if (newItems) { + newItems.push(newItem); + } + } + + return newItems === null ? list : TypeScript.Syntax.list(newItems); + }; + + SyntaxRewriter.prototype.visitSeparatedList = function (list) { + var newItems = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + var newItem = item.isToken() ? this.visitToken(item) : this.visitNode(item); + + if (item !== newItem && newItems === null) { + newItems = []; + for (var j = 0; j < i; j++) { + newItems.push(list.childAt(j)); + } + } + + if (newItems) { + newItems.push(newItem); + } + } + + return newItems === null ? list : TypeScript.Syntax.separatedList(newItems); + }; + + SyntaxRewriter.prototype.visitSourceUnit = function (node) { + return node.update(this.visitList(node.moduleElements), this.visitToken(node.endOfFileToken)); + }; + + SyntaxRewriter.prototype.visitExternalModuleReference = function (node) { + return node.update(this.visitToken(node.requireKeyword), this.visitToken(node.openParenToken), this.visitToken(node.stringLiteral), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitModuleNameModuleReference = function (node) { + return node.update(this.visitNodeOrToken(node.moduleName)); + }; + + SyntaxRewriter.prototype.visitImportDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.importKeyword), this.visitToken(node.identifier), this.visitToken(node.equalsToken), this.visitNodeOrToken(node.moduleReference), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitExportAssignment = function (node) { + return node.update(this.visitToken(node.exportKeyword), this.visitToken(node.equalsToken), this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitClassDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.classKeyword), this.visitToken(node.identifier), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitList(node.heritageClauses), this.visitToken(node.openBraceToken), this.visitList(node.classElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitInterfaceDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.interfaceKeyword), this.visitToken(node.identifier), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitList(node.heritageClauses), this.visitNode(node.body)); + }; + + SyntaxRewriter.prototype.visitHeritageClause = function (node) { + return node.update(node.kind(), this.visitToken(node.extendsOrImplementsKeyword), this.visitSeparatedList(node.typeNames)); + }; + + SyntaxRewriter.prototype.visitModuleDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.moduleKeyword), node.name === null ? null : this.visitNodeOrToken(node.name), node.stringLiteral === null ? null : this.visitToken(node.stringLiteral), this.visitToken(node.openBraceToken), this.visitList(node.moduleElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitFunctionDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.functionKeyword), this.visitToken(node.identifier), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitVariableStatement = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.variableDeclaration), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitVariableDeclaration = function (node) { + return node.update(this.visitToken(node.varKeyword), this.visitSeparatedList(node.variableDeclarators)); + }; + + SyntaxRewriter.prototype.visitVariableDeclarator = function (node) { + return node.update(this.visitToken(node.propertyName), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitEqualsValueClause = function (node) { + return node.update(this.visitToken(node.equalsToken), this.visitNodeOrToken(node.value)); + }; + + SyntaxRewriter.prototype.visitPrefixUnaryExpression = function (node) { + return node.update(node.kind(), this.visitToken(node.operatorToken), this.visitNodeOrToken(node.operand)); + }; + + SyntaxRewriter.prototype.visitArrayLiteralExpression = function (node) { + return node.update(this.visitToken(node.openBracketToken), this.visitSeparatedList(node.expressions), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitOmittedExpression = function (node) { + return node; + }; + + SyntaxRewriter.prototype.visitParenthesizedExpression = function (node) { + return node.update(this.visitToken(node.openParenToken), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitSimpleArrowFunctionExpression = function (node) { + return node.update(this.visitToken(node.identifier), this.visitToken(node.equalsGreaterThanToken), node.block === null ? null : this.visitNode(node.block), node.expression === null ? null : this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + return node.update(this.visitNode(node.callSignature), this.visitToken(node.equalsGreaterThanToken), node.block === null ? null : this.visitNode(node.block), node.expression === null ? null : this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitQualifiedName = function (node) { + return node.update(this.visitNodeOrToken(node.left), this.visitToken(node.dotToken), this.visitToken(node.right)); + }; + + SyntaxRewriter.prototype.visitTypeArgumentList = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitSeparatedList(node.typeArguments), this.visitToken(node.greaterThanToken)); + }; + + SyntaxRewriter.prototype.visitConstructorType = function (node) { + return node.update(this.visitToken(node.newKeyword), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitFunctionType = function (node) { + return node.update(node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitObjectType = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitSeparatedList(node.typeMembers), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitArrayType = function (node) { + return node.update(this.visitNodeOrToken(node.type), this.visitToken(node.openBracketToken), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitGenericType = function (node) { + return node.update(this.visitNodeOrToken(node.name), this.visitNode(node.typeArgumentList)); + }; + + SyntaxRewriter.prototype.visitTypeQuery = function (node) { + return node.update(this.visitToken(node.typeOfKeyword), this.visitNodeOrToken(node.name)); + }; + + SyntaxRewriter.prototype.visitTypeAnnotation = function (node) { + return node.update(this.visitToken(node.colonToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitBlock = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitList(node.statements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitParameter = function (node) { + return node.update(node.dotDotDotToken === null ? null : this.visitToken(node.dotDotDotToken), this.visitList(node.modifiers), this.visitToken(node.identifier), node.questionToken === null ? null : this.visitToken(node.questionToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitMemberAccessExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.dotToken), this.visitToken(node.name)); + }; + + SyntaxRewriter.prototype.visitPostfixUnaryExpression = function (node) { + return node.update(node.kind(), this.visitNodeOrToken(node.operand), this.visitToken(node.operatorToken)); + }; + + SyntaxRewriter.prototype.visitElementAccessExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.openBracketToken), this.visitNodeOrToken(node.argumentExpression), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitInvocationExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitNode(node.argumentList)); + }; + + SyntaxRewriter.prototype.visitArgumentList = function (node) { + return node.update(node.typeArgumentList === null ? null : this.visitNode(node.typeArgumentList), this.visitToken(node.openParenToken), this.visitSeparatedList(node.arguments), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitBinaryExpression = function (node) { + return node.update(node.kind(), this.visitNodeOrToken(node.left), this.visitToken(node.operatorToken), this.visitNodeOrToken(node.right)); + }; + + SyntaxRewriter.prototype.visitConditionalExpression = function (node) { + return node.update(this.visitNodeOrToken(node.condition), this.visitToken(node.questionToken), this.visitNodeOrToken(node.whenTrue), this.visitToken(node.colonToken), this.visitNodeOrToken(node.whenFalse)); + }; + + SyntaxRewriter.prototype.visitConstructSignature = function (node) { + return node.update(this.visitToken(node.newKeyword), this.visitNode(node.callSignature)); + }; + + SyntaxRewriter.prototype.visitMethodSignature = function (node) { + return node.update(this.visitToken(node.propertyName), node.questionToken === null ? null : this.visitToken(node.questionToken), this.visitNode(node.callSignature)); + }; + + SyntaxRewriter.prototype.visitIndexSignature = function (node) { + return node.update(this.visitToken(node.openBracketToken), this.visitNode(node.parameter), this.visitToken(node.closeBracketToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitPropertySignature = function (node) { + return node.update(this.visitToken(node.propertyName), node.questionToken === null ? null : this.visitToken(node.questionToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitCallSignature = function (node) { + return node.update(node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitParameterList = function (node) { + return node.update(this.visitToken(node.openParenToken), this.visitSeparatedList(node.parameters), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitTypeParameterList = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitSeparatedList(node.typeParameters), this.visitToken(node.greaterThanToken)); + }; + + SyntaxRewriter.prototype.visitTypeParameter = function (node) { + return node.update(this.visitToken(node.identifier), node.constraint === null ? null : this.visitNode(node.constraint)); + }; + + SyntaxRewriter.prototype.visitConstraint = function (node) { + return node.update(this.visitToken(node.extendsKeyword), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitElseClause = function (node) { + return node.update(this.visitToken(node.elseKeyword), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitIfStatement = function (node) { + return node.update(this.visitToken(node.ifKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement), node.elseClause === null ? null : this.visitNode(node.elseClause)); + }; + + SyntaxRewriter.prototype.visitExpressionStatement = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitConstructorDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.constructorKeyword), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitMemberFunctionDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.propertyName), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitGetAccessor = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.getKeyword), this.visitToken(node.propertyName), this.visitNode(node.parameterList), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitSetAccessor = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.setKeyword), this.visitToken(node.propertyName), this.visitNode(node.parameterList), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitMemberVariableDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.variableDeclarator), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitIndexMemberDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.indexSignature), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitThrowStatement = function (node) { + return node.update(this.visitToken(node.throwKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitReturnStatement = function (node) { + return node.update(this.visitToken(node.returnKeyword), node.expression === null ? null : this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitObjectCreationExpression = function (node) { + return node.update(this.visitToken(node.newKeyword), this.visitNodeOrToken(node.expression), node.argumentList === null ? null : this.visitNode(node.argumentList)); + }; + + SyntaxRewriter.prototype.visitSwitchStatement = function (node) { + return node.update(this.visitToken(node.switchKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken), this.visitToken(node.openBraceToken), this.visitList(node.switchClauses), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitCaseSwitchClause = function (node) { + return node.update(this.visitToken(node.caseKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.colonToken), this.visitList(node.statements)); + }; + + SyntaxRewriter.prototype.visitDefaultSwitchClause = function (node) { + return node.update(this.visitToken(node.defaultKeyword), this.visitToken(node.colonToken), this.visitList(node.statements)); + }; + + SyntaxRewriter.prototype.visitBreakStatement = function (node) { + return node.update(this.visitToken(node.breakKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitContinueStatement = function (node) { + return node.update(this.visitToken(node.continueKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitForStatement = function (node) { + return node.update(this.visitToken(node.forKeyword), this.visitToken(node.openParenToken), node.variableDeclaration === null ? null : this.visitNode(node.variableDeclaration), node.initializer === null ? null : this.visitNodeOrToken(node.initializer), this.visitToken(node.firstSemicolonToken), node.condition === null ? null : this.visitNodeOrToken(node.condition), this.visitToken(node.secondSemicolonToken), node.incrementor === null ? null : this.visitNodeOrToken(node.incrementor), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitForInStatement = function (node) { + return node.update(this.visitToken(node.forKeyword), this.visitToken(node.openParenToken), node.variableDeclaration === null ? null : this.visitNode(node.variableDeclaration), node.left === null ? null : this.visitNodeOrToken(node.left), this.visitToken(node.inKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitWhileStatement = function (node) { + return node.update(this.visitToken(node.whileKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitWithStatement = function (node) { + return node.update(this.visitToken(node.withKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitEnumDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.enumKeyword), this.visitToken(node.identifier), this.visitToken(node.openBraceToken), this.visitSeparatedList(node.enumElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitEnumElement = function (node) { + return node.update(this.visitToken(node.propertyName), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitCastExpression = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitNodeOrToken(node.type), this.visitToken(node.greaterThanToken), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitObjectLiteralExpression = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitSeparatedList(node.propertyAssignments), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitSimplePropertyAssignment = function (node) { + return node.update(this.visitToken(node.propertyName), this.visitToken(node.colonToken), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitFunctionPropertyAssignment = function (node) { + return node.update(this.visitToken(node.propertyName), this.visitNode(node.callSignature), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitFunctionExpression = function (node) { + return node.update(this.visitToken(node.functionKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitNode(node.callSignature), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitEmptyStatement = function (node) { + return node.update(this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitTryStatement = function (node) { + return node.update(this.visitToken(node.tryKeyword), this.visitNode(node.block), node.catchClause === null ? null : this.visitNode(node.catchClause), node.finallyClause === null ? null : this.visitNode(node.finallyClause)); + }; + + SyntaxRewriter.prototype.visitCatchClause = function (node) { + return node.update(this.visitToken(node.catchKeyword), this.visitToken(node.openParenToken), this.visitToken(node.identifier), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), this.visitToken(node.closeParenToken), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitFinallyClause = function (node) { + return node.update(this.visitToken(node.finallyKeyword), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitLabeledStatement = function (node) { + return node.update(this.visitToken(node.identifier), this.visitToken(node.colonToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitDoStatement = function (node) { + return node.update(this.visitToken(node.doKeyword), this.visitNodeOrToken(node.statement), this.visitToken(node.whileKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitTypeOfExpression = function (node) { + return node.update(this.visitToken(node.typeOfKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitDeleteExpression = function (node) { + return node.update(this.visitToken(node.deleteKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitVoidExpression = function (node) { + return node.update(this.visitToken(node.voidKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitDebuggerStatement = function (node) { + return node.update(this.visitToken(node.debuggerKeyword), this.visitToken(node.semicolonToken)); + }; + return SyntaxRewriter; + })(); + TypeScript.SyntaxRewriter = SyntaxRewriter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxDedenter = (function (_super) { + __extends(SyntaxDedenter, _super); + function SyntaxDedenter(dedentFirstToken, dedentationAmount, minimumIndent, options) { + _super.call(this); + this.dedentationAmount = dedentationAmount; + this.minimumIndent = minimumIndent; + this.options = options; + this.lastTriviaWasNewLine = dedentFirstToken; + } + SyntaxDedenter.prototype.abort = function () { + this.lastTriviaWasNewLine = false; + this.dedentationAmount = 0; + }; + + SyntaxDedenter.prototype.isAborted = function () { + return this.dedentationAmount === 0; + }; + + SyntaxDedenter.prototype.visitToken = function (token) { + if (token.width() === 0) { + return token; + } + + var result = token; + if (this.lastTriviaWasNewLine) { + result = token.withLeadingTrivia(this.dedentTriviaList(token.leadingTrivia())); + } + + if (this.isAborted()) { + return token; + } + + this.lastTriviaWasNewLine = token.hasTrailingNewLine(); + return result; + }; + + SyntaxDedenter.prototype.dedentTriviaList = function (triviaList) { + var result = []; + var dedentNextWhitespace = true; + + for (var i = 0, n = triviaList.count(); i < n && !this.isAborted(); i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + var dedentThisTrivia = dedentNextWhitespace; + dedentNextWhitespace = false; + + if (dedentThisTrivia) { + if (trivia.kind() === 4 /* WhitespaceTrivia */) { + var hasFollowingNewLine = (i < triviaList.count() - 1) && triviaList.syntaxTriviaAt(i + 1).kind() === 5 /* NewLineTrivia */; + result.push(this.dedentWhitespace(trivia, hasFollowingNewLine)); + continue; + } else if (trivia.kind() !== 5 /* NewLineTrivia */) { + this.abort(); + break; + } + } + + if (trivia.kind() === 6 /* MultiLineCommentTrivia */) { + result.push(this.dedentMultiLineComment(trivia)); + continue; + } + + result.push(trivia); + if (trivia.kind() === 5 /* NewLineTrivia */) { + dedentNextWhitespace = true; + } + } + + if (dedentNextWhitespace) { + this.abort(); + } + + if (this.isAborted()) { + return triviaList; + } + + return TypeScript.Syntax.triviaList(result); + }; + + SyntaxDedenter.prototype.dedentSegment = function (segment, hasFollowingNewLineTrivia) { + var firstNonWhitespacePosition = TypeScript.Indentation.firstNonWhitespacePosition(segment); + + if (firstNonWhitespacePosition === segment.length) { + if (hasFollowingNewLineTrivia) { + return ""; + } + } else if (TypeScript.CharacterInfo.isLineTerminator(segment.charCodeAt(firstNonWhitespacePosition))) { + return segment.substring(firstNonWhitespacePosition); + } + + var firstNonWhitespaceColumn = TypeScript.Indentation.columnForPositionInString(segment, firstNonWhitespacePosition, this.options); + + var newFirstNonWhitespaceColumn = TypeScript.MathPrototype.min(firstNonWhitespaceColumn, TypeScript.MathPrototype.max(firstNonWhitespaceColumn - this.dedentationAmount, this.minimumIndent)); + + if (newFirstNonWhitespaceColumn === firstNonWhitespaceColumn) { + this.abort(); + return segment; + } + + this.dedentationAmount = firstNonWhitespaceColumn - newFirstNonWhitespaceColumn; + TypeScript.Debug.assert(this.dedentationAmount >= 0); + + var indentationString = TypeScript.Indentation.indentationString(newFirstNonWhitespaceColumn, this.options); + + return indentationString + segment.substring(firstNonWhitespacePosition); + }; + + SyntaxDedenter.prototype.dedentWhitespace = function (trivia, hasFollowingNewLineTrivia) { + var newIndentation = this.dedentSegment(trivia.fullText(), hasFollowingNewLineTrivia); + return TypeScript.Syntax.whitespace(newIndentation); + }; + + SyntaxDedenter.prototype.dedentMultiLineComment = function (trivia) { + var segments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + if (segments.length === 1) { + return trivia; + } + + for (var i = 1; i < segments.length; i++) { + var segment = segments[i]; + segments[i] = this.dedentSegment(segment, false); + } + + var result = segments.join(""); + + return TypeScript.Syntax.multiLineComment(result); + }; + + SyntaxDedenter.dedentNode = function (node, dedentFirstToken, dedentAmount, minimumIndent, options) { + var dedenter = new SyntaxDedenter(dedentFirstToken, dedentAmount, minimumIndent, options); + var result = node.accept(dedenter); + + if (dedenter.isAborted()) { + return node; + } + + return result; + }; + return SyntaxDedenter; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxDedenter = SyntaxDedenter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxIndenter = (function (_super) { + __extends(SyntaxIndenter, _super); + function SyntaxIndenter(indentFirstToken, indentationAmount, options) { + _super.call(this); + this.indentationAmount = indentationAmount; + this.options = options; + this.lastTriviaWasNewLine = indentFirstToken; + this.indentationTrivia = TypeScript.Indentation.indentationTrivia(this.indentationAmount, this.options); + } + SyntaxIndenter.prototype.visitToken = function (token) { + if (token.width() === 0) { + return token; + } + + var result = token; + if (this.lastTriviaWasNewLine) { + result = token.withLeadingTrivia(this.indentTriviaList(token.leadingTrivia())); + } + + this.lastTriviaWasNewLine = token.hasTrailingNewLine(); + return result; + }; + + SyntaxIndenter.prototype.indentTriviaList = function (triviaList) { + var result = []; + + var indentNextTrivia = true; + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + var indentThisTrivia = indentNextTrivia; + indentNextTrivia = false; + + switch (trivia.kind()) { + case 6 /* MultiLineCommentTrivia */: + this.indentMultiLineComment(trivia, indentThisTrivia, result); + continue; + + case 7 /* SingleLineCommentTrivia */: + case 8 /* SkippedTokenTrivia */: + this.indentSingleLineOrSkippedText(trivia, indentThisTrivia, result); + continue; + + case 4 /* WhitespaceTrivia */: + this.indentWhitespace(trivia, indentThisTrivia, result); + continue; + + case 5 /* NewLineTrivia */: + result.push(trivia); + indentNextTrivia = true; + continue; + + default: + throw TypeScript.Errors.invalidOperation(); + } + } + + if (indentNextTrivia) { + result.push(this.indentationTrivia); + } + + return TypeScript.Syntax.triviaList(result); + }; + + SyntaxIndenter.prototype.indentSegment = function (segment) { + var firstNonWhitespacePosition = TypeScript.Indentation.firstNonWhitespacePosition(segment); + + if (firstNonWhitespacePosition < segment.length && TypeScript.CharacterInfo.isLineTerminator(segment.charCodeAt(firstNonWhitespacePosition))) { + return segment; + } + + var firstNonWhitespaceColumn = TypeScript.Indentation.columnForPositionInString(segment, firstNonWhitespacePosition, this.options); + + var newFirstNonWhitespaceColumn = firstNonWhitespaceColumn + this.indentationAmount; + + var indentationString = TypeScript.Indentation.indentationString(newFirstNonWhitespaceColumn, this.options); + + return indentationString + segment.substring(firstNonWhitespacePosition); + }; + + SyntaxIndenter.prototype.indentWhitespace = function (trivia, indentThisTrivia, result) { + if (!indentThisTrivia) { + result.push(trivia); + return; + } + + var newIndentation = this.indentSegment(trivia.fullText()); + result.push(TypeScript.Syntax.whitespace(newIndentation)); + }; + + SyntaxIndenter.prototype.indentSingleLineOrSkippedText = function (trivia, indentThisTrivia, result) { + if (indentThisTrivia) { + result.push(this.indentationTrivia); + } + + result.push(trivia); + }; + + SyntaxIndenter.prototype.indentMultiLineComment = function (trivia, indentThisTrivia, result) { + if (indentThisTrivia) { + result.push(this.indentationTrivia); + } + + var segments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + + for (var i = 1; i < segments.length; i++) { + segments[i] = this.indentSegment(segments[i]); + } + + var newText = segments.join(""); + result.push(TypeScript.Syntax.multiLineComment(newText)); + }; + + SyntaxIndenter.indentNode = function (node, indentFirstToken, indentAmount, options) { + var indenter = new SyntaxIndenter(indentFirstToken, indentAmount, options); + return node.accept(indenter); + }; + + SyntaxIndenter.indentNodes = function (nodes, indentFirstToken, indentAmount, options) { + var indenter = new SyntaxIndenter(indentFirstToken, indentAmount, options); + var result = TypeScript.ArrayUtilities.select(nodes, function (n) { + return n.accept(indenter); + }); + + return result; + }; + return SyntaxIndenter; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxIndenter = SyntaxIndenter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var VariableWidthTokenWithNoTrivia = (function () { + function VariableWidthTokenWithNoTrivia(fullText, kind) { + this._fullText = fullText; + this.tokenKind = kind; + } + VariableWidthTokenWithNoTrivia.prototype.clone = function () { + return new VariableWidthTokenWithNoTrivia(this._fullText, this.tokenKind); + }; + + VariableWidthTokenWithNoTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithNoTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithNoTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithNoTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithNoTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithNoTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithNoTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithNoTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithNoTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithNoTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingComment = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingComment = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithNoTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithNoTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithNoTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithNoTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithNoTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithNoTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithNoTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithNoTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithNoTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithNoTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithNoTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithNoTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithNoTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithNoTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithNoTrivia; + })(); + Syntax.VariableWidthTokenWithNoTrivia = VariableWidthTokenWithNoTrivia; + + var VariableWidthTokenWithLeadingTrivia = (function () { + function VariableWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + } + VariableWidthTokenWithLeadingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithLeadingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithLeadingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithLeadingTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithLeadingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingComment = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithLeadingTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithLeadingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithLeadingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithLeadingTrivia; + })(); + Syntax.VariableWidthTokenWithLeadingTrivia = VariableWidthTokenWithLeadingTrivia; + + var VariableWidthTokenWithTrailingTrivia = (function () { + function VariableWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._trailingTriviaInfo = trailingTriviaInfo; + } + VariableWidthTokenWithTrailingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithTrailingTrivia(this._fullText, this.tokenKind, this._trailingTriviaInfo); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithTrailingTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingComment = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithTrailingTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithTrailingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithTrailingTrivia; + })(); + Syntax.VariableWidthTokenWithTrailingTrivia = VariableWidthTokenWithTrailingTrivia; + + var VariableWidthTokenWithLeadingAndTrailingTrivia = (function () { + function VariableWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + this._trailingTriviaInfo = trailingTriviaInfo; + } + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithLeadingAndTrailingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithLeadingAndTrailingTrivia; + })(); + Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia = VariableWidthTokenWithLeadingAndTrailingTrivia; + + var FixedWidthTokenWithNoTrivia = (function () { + function FixedWidthTokenWithNoTrivia(kind) { + this.tokenKind = kind; + } + FixedWidthTokenWithNoTrivia.prototype.clone = function () { + return new FixedWidthTokenWithNoTrivia(this.tokenKind); + }; + + FixedWidthTokenWithNoTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithNoTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithNoTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithNoTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithNoTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithNoTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithNoTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithNoTrivia.prototype.fullText = function () { + return this.text(); + }; + + FixedWidthTokenWithNoTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithNoTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingComment = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithNoTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingComment = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithNoTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithNoTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithNoTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithNoTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithNoTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithNoTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithNoTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithNoTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithNoTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithNoTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithNoTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithNoTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithNoTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithNoTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithNoTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithNoTrivia; + })(); + Syntax.FixedWidthTokenWithNoTrivia = FixedWidthTokenWithNoTrivia; + + var FixedWidthTokenWithLeadingTrivia = (function () { + function FixedWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + } + FixedWidthTokenWithLeadingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithLeadingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithLeadingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithLeadingTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithLeadingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingComment = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithLeadingTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithLeadingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithLeadingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithLeadingTrivia; + })(); + Syntax.FixedWidthTokenWithLeadingTrivia = FixedWidthTokenWithLeadingTrivia; + + var FixedWidthTokenWithTrailingTrivia = (function () { + function FixedWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._trailingTriviaInfo = trailingTriviaInfo; + } + FixedWidthTokenWithTrailingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithTrailingTrivia(this._fullText, this.tokenKind, this._trailingTriviaInfo); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithTrailingTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingComment = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithTrailingTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithTrailingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithTrailingTrivia; + })(); + Syntax.FixedWidthTokenWithTrailingTrivia = FixedWidthTokenWithTrailingTrivia; + + var FixedWidthTokenWithLeadingAndTrailingTrivia = (function () { + function FixedWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + this._trailingTriviaInfo = trailingTriviaInfo; + } + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithLeadingAndTrailingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithLeadingAndTrailingTrivia; + })(); + Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia = FixedWidthTokenWithLeadingAndTrailingTrivia; + + function collectTokenTextElements(token, elements) { + token.leadingTrivia().collectTextElements(elements); + elements.push(token.text()); + token.trailingTrivia().collectTextElements(elements); + } + + function getTriviaWidth(value) { + return value >>> 2 /* TriviaFullWidthShift */; + } + + function hasTriviaComment(value) { + return (value & 2 /* TriviaCommentMask */) !== 0; + } + + function hasTriviaNewLine(value) { + return (value & 1 /* TriviaNewLineMask */) !== 0; + } + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + function isExpression(token) { + switch (token.tokenKind) { + case 11 /* IdentifierName */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NumericLiteral */: + case 14 /* StringLiteral */: + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 50 /* SuperKeyword */: + return true; + } + + return false; + } + Syntax.isExpression = isExpression; + + function realizeToken(token) { + return new RealizedToken(token.tokenKind, token.leadingTrivia(), token.text(), token.value(), token.valueText(), token.trailingTrivia()); + } + Syntax.realizeToken = realizeToken; + + function convertToIdentifierName(token) { + TypeScript.Debug.assert(TypeScript.SyntaxFacts.isAnyKeyword(token.tokenKind)); + return new RealizedToken(11 /* IdentifierName */, token.leadingTrivia(), token.text(), token.text(), token.text(), token.trailingTrivia()); + } + Syntax.convertToIdentifierName = convertToIdentifierName; + + function tokenToJSON(token) { + var result = {}; + + for (var name in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind[name] === token.kind()) { + result.kind = name; + break; + } + } + + result.width = token.width(); + if (token.fullWidth() !== token.width()) { + result.fullWidth = token.fullWidth(); + } + + result.text = token.text(); + + var value = token.value(); + if (value !== null) { + result.value = value; + result.valueText = token.valueText(); + } + + if (token.hasLeadingTrivia()) { + result.hasLeadingTrivia = true; + } + + if (token.hasLeadingComment()) { + result.hasLeadingComment = true; + } + + if (token.hasLeadingNewLine()) { + result.hasLeadingNewLine = true; + } + + if (token.hasLeadingSkippedText()) { + result.hasLeadingSkippedText = true; + } + + if (token.hasTrailingTrivia()) { + result.hasTrailingTrivia = true; + } + + if (token.hasTrailingComment()) { + result.hasTrailingComment = true; + } + + if (token.hasTrailingNewLine()) { + result.hasTrailingNewLine = true; + } + + if (token.hasTrailingSkippedText()) { + result.hasTrailingSkippedText = true; + } + + var trivia = token.leadingTrivia(); + if (trivia.count() > 0) { + result.leadingTrivia = trivia; + } + + trivia = token.trailingTrivia(); + if (trivia.count() > 0) { + result.trailingTrivia = trivia; + } + + return result; + } + Syntax.tokenToJSON = tokenToJSON; + + function value(token) { + return value1(token.tokenKind, token.text()); + } + Syntax.value = value; + + function hexValue(text, start, length) { + var intChar = 0; + for (var i = 0; i < length; i++) { + var ch2 = text.charCodeAt(start + i); + if (!TypeScript.CharacterInfo.isHexDigit(ch2)) { + break; + } + + intChar = (intChar << 4) + TypeScript.CharacterInfo.hexValue(ch2); + } + + return intChar; + } + + var characterArray = []; + + function convertEscapes(text) { + characterArray.length = 0; + var result = ""; + + for (var i = 0, n = text.length; i < n; i++) { + var ch = text.charCodeAt(i); + + if (ch === 92 /* backslash */) { + i++; + if (i < n) { + ch = text.charCodeAt(i); + switch (ch) { + case 48 /* _0 */: + characterArray.push(0 /* nullCharacter */); + continue; + + case 98 /* b */: + characterArray.push(8 /* backspace */); + continue; + + case 102 /* f */: + characterArray.push(12 /* formFeed */); + continue; + + case 110 /* n */: + characterArray.push(10 /* lineFeed */); + continue; + + case 114 /* r */: + characterArray.push(13 /* carriageReturn */); + continue; + + case 116 /* t */: + characterArray.push(9 /* tab */); + continue; + + case 118 /* v */: + characterArray.push(11 /* verticalTab */); + continue; + + case 120 /* x */: + characterArray.push(hexValue(text, i + 1, 2)); + i += 2; + continue; + + case 117 /* u */: + characterArray.push(hexValue(text, i + 1, 4)); + i += 4; + continue; + + case 13 /* carriageReturn */: + var nextIndex = i + 1; + if (nextIndex < text.length && text.charCodeAt(nextIndex) === 10 /* lineFeed */) { + i++; + } + continue; + + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + continue; + + default: + } + } + } + + characterArray.push(ch); + + if (i && !(i % 1024)) { + result = result.concat(String.fromCharCode.apply(null, characterArray)); + characterArray.length = 0; + } + } + + if (characterArray.length) { + result = result.concat(String.fromCharCode.apply(null, characterArray)); + } + + return result; + } + + function massageEscapes(text) { + return text.indexOf("\\") >= 0 ? convertEscapes(text) : text; + } + Syntax.massageEscapes = massageEscapes; + + function value1(kind, text) { + if (kind === 11 /* IdentifierName */) { + return massageEscapes(text); + } + + switch (kind) { + case 37 /* TrueKeyword */: + return true; + case 24 /* FalseKeyword */: + return false; + case 32 /* NullKeyword */: + return null; + } + + if (TypeScript.SyntaxFacts.isAnyKeyword(kind) || TypeScript.SyntaxFacts.isAnyPunctuation(kind)) { + return TypeScript.SyntaxFacts.getText(kind); + } + + if (kind === 13 /* NumericLiteral */) { + return TypeScript.IntegerUtilities.isHexInteger(text) ? parseInt(text, 16) : parseFloat(text); + } else if (kind === 14 /* StringLiteral */) { + if (text.length > 1 && text.charCodeAt(text.length - 1) === text.charCodeAt(0)) { + return massageEscapes(text.substr(1, text.length - 2)); + } else { + return massageEscapes(text.substr(1)); + } + } else if (kind === 12 /* RegularExpressionLiteral */) { + return regularExpressionValue(text); + } else if (kind === 10 /* EndOfFileToken */ || kind === 9 /* ErrorToken */) { + return null; + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + + function regularExpressionValue(text) { + try { + var lastSlash = text.lastIndexOf("/"); + var body = text.substring(1, lastSlash); + var flags = text.substring(lastSlash + 1); + return new RegExp(body, flags); + } catch (e) { + return null; + } + } + + function valueText1(kind, text) { + var value = value1(kind, text); + return value === null ? "" : value.toString(); + } + + function valueText(token) { + var value = token.value(); + return value === null ? "" : value.toString(); + } + Syntax.valueText = valueText; + + var EmptyToken = (function () { + function EmptyToken(kind) { + this.tokenKind = kind; + } + EmptyToken.prototype.clone = function () { + return new EmptyToken(this.tokenKind); + }; + + EmptyToken.prototype.kind = function () { + return this.tokenKind; + }; + + EmptyToken.prototype.isToken = function () { + return true; + }; + EmptyToken.prototype.isNode = function () { + return false; + }; + EmptyToken.prototype.isList = function () { + return false; + }; + EmptyToken.prototype.isSeparatedList = function () { + return false; + }; + + EmptyToken.prototype.childCount = function () { + return 0; + }; + + EmptyToken.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptyToken.prototype.toJSON = function (key) { + return tokenToJSON(this); + }; + EmptyToken.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + + EmptyToken.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + EmptyToken.prototype.firstToken = function () { + return this; + }; + EmptyToken.prototype.lastToken = function () { + return this; + }; + EmptyToken.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptyToken.prototype.isIncrementallyUnusable = function () { + return true; + }; + + EmptyToken.prototype.fullWidth = function () { + return 0; + }; + EmptyToken.prototype.width = function () { + return 0; + }; + EmptyToken.prototype.text = function () { + return ""; + }; + EmptyToken.prototype.fullText = function () { + return ""; + }; + EmptyToken.prototype.value = function () { + return null; + }; + EmptyToken.prototype.valueText = function () { + return ""; + }; + + EmptyToken.prototype.hasLeadingTrivia = function () { + return false; + }; + EmptyToken.prototype.hasLeadingComment = function () { + return false; + }; + EmptyToken.prototype.hasLeadingNewLine = function () { + return false; + }; + EmptyToken.prototype.hasLeadingSkippedText = function () { + return false; + }; + EmptyToken.prototype.leadingTriviaWidth = function () { + return 0; + }; + EmptyToken.prototype.hasTrailingTrivia = function () { + return false; + }; + EmptyToken.prototype.hasTrailingComment = function () { + return false; + }; + EmptyToken.prototype.hasTrailingNewLine = function () { + return false; + }; + EmptyToken.prototype.hasTrailingSkippedText = function () { + return false; + }; + EmptyToken.prototype.hasSkippedToken = function () { + return false; + }; + + EmptyToken.prototype.trailingTriviaWidth = function () { + return 0; + }; + EmptyToken.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + EmptyToken.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + EmptyToken.prototype.realize = function () { + return realizeToken(this); + }; + EmptyToken.prototype.collectTextElements = function (elements) { + }; + + EmptyToken.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + EmptyToken.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + EmptyToken.prototype.isExpression = function () { + return isExpression(this); + }; + + EmptyToken.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + EmptyToken.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + EmptyToken.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + EmptyToken.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return EmptyToken; + })(); + + function emptyToken(kind) { + return new EmptyToken(kind); + } + Syntax.emptyToken = emptyToken; + + var RealizedToken = (function () { + function RealizedToken(tokenKind, leadingTrivia, text, value, valueText, trailingTrivia) { + this.tokenKind = tokenKind; + this._leadingTrivia = leadingTrivia; + this._text = text; + this._value = value; + this._valueText = valueText; + this._trailingTrivia = trailingTrivia; + } + RealizedToken.prototype.clone = function () { + return new RealizedToken(this.tokenKind, this._leadingTrivia, this._text, this._value, this._valueText, this._trailingTrivia); + }; + + RealizedToken.prototype.kind = function () { + return this.tokenKind; + }; + RealizedToken.prototype.toJSON = function (key) { + return tokenToJSON(this); + }; + RealizedToken.prototype.firstToken = function () { + return this; + }; + RealizedToken.prototype.lastToken = function () { + return this; + }; + RealizedToken.prototype.isTypeScriptSpecific = function () { + return false; + }; + + RealizedToken.prototype.isIncrementallyUnusable = function () { + return true; + }; + + RealizedToken.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + + RealizedToken.prototype.childCount = function () { + return 0; + }; + + RealizedToken.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + RealizedToken.prototype.isToken = function () { + return true; + }; + RealizedToken.prototype.isNode = function () { + return false; + }; + RealizedToken.prototype.isList = function () { + return false; + }; + RealizedToken.prototype.isSeparatedList = function () { + return false; + }; + RealizedToken.prototype.isTrivia = function () { + return false; + }; + RealizedToken.prototype.isTriviaList = function () { + return false; + }; + + RealizedToken.prototype.fullWidth = function () { + return this._leadingTrivia.fullWidth() + this.width() + this._trailingTrivia.fullWidth(); + }; + RealizedToken.prototype.width = function () { + return this.text().length; + }; + + RealizedToken.prototype.text = function () { + return this._text; + }; + RealizedToken.prototype.fullText = function () { + return this._leadingTrivia.fullText() + this.text() + this._trailingTrivia.fullText(); + }; + + RealizedToken.prototype.value = function () { + return this._value; + }; + RealizedToken.prototype.valueText = function () { + return this._valueText; + }; + + RealizedToken.prototype.hasLeadingTrivia = function () { + return this._leadingTrivia.count() > 0; + }; + RealizedToken.prototype.hasLeadingComment = function () { + return this._leadingTrivia.hasComment(); + }; + RealizedToken.prototype.hasLeadingNewLine = function () { + return this._leadingTrivia.hasNewLine(); + }; + RealizedToken.prototype.hasLeadingSkippedText = function () { + return this._leadingTrivia.hasSkippedToken(); + }; + RealizedToken.prototype.leadingTriviaWidth = function () { + return this._leadingTrivia.fullWidth(); + }; + + RealizedToken.prototype.hasTrailingTrivia = function () { + return this._trailingTrivia.count() > 0; + }; + RealizedToken.prototype.hasTrailingComment = function () { + return this._trailingTrivia.hasComment(); + }; + RealizedToken.prototype.hasTrailingNewLine = function () { + return this._trailingTrivia.hasNewLine(); + }; + RealizedToken.prototype.hasTrailingSkippedText = function () { + return this._trailingTrivia.hasSkippedToken(); + }; + RealizedToken.prototype.trailingTriviaWidth = function () { + return this._trailingTrivia.fullWidth(); + }; + + RealizedToken.prototype.hasSkippedToken = function () { + return this.hasLeadingSkippedText() || this.hasTrailingSkippedText(); + }; + + RealizedToken.prototype.leadingTrivia = function () { + return this._leadingTrivia; + }; + RealizedToken.prototype.trailingTrivia = function () { + return this._trailingTrivia; + }; + + RealizedToken.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + RealizedToken.prototype.collectTextElements = function (elements) { + this.leadingTrivia().collectTextElements(elements); + elements.push(this.text()); + this.trailingTrivia().collectTextElements(elements); + }; + + RealizedToken.prototype.withLeadingTrivia = function (leadingTrivia) { + return new RealizedToken(this.tokenKind, leadingTrivia, this._text, this._value, this._valueText, this._trailingTrivia); + }; + + RealizedToken.prototype.withTrailingTrivia = function (trailingTrivia) { + return new RealizedToken(this.tokenKind, this._leadingTrivia, this._text, this._value, this._valueText, trailingTrivia); + }; + + RealizedToken.prototype.isExpression = function () { + return isExpression(this); + }; + + RealizedToken.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + RealizedToken.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + RealizedToken.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + RealizedToken.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return RealizedToken; + })(); + + function token(kind, info) { + if (typeof info === "undefined") { info = null; } + var text = (info !== null && info.text !== undefined) ? info.text : TypeScript.SyntaxFacts.getText(kind); + + return new RealizedToken(kind, Syntax.triviaList(info === null ? null : info.leadingTrivia), text, value1(kind, text), valueText1(kind, text), Syntax.triviaList(info === null ? null : info.trailingTrivia)); + } + Syntax.token = token; + + function identifier(text, info) { + if (typeof info === "undefined") { info = null; } + info = info || {}; + info.text = text; + return token(11 /* IdentifierName */, info); + } + Syntax.identifier = identifier; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTokenReplacer = (function (_super) { + __extends(SyntaxTokenReplacer, _super); + function SyntaxTokenReplacer(token1, token2) { + _super.call(this); + this.token1 = token1; + this.token2 = token2; + } + SyntaxTokenReplacer.prototype.visitToken = function (token) { + if (token === this.token1) { + var result = this.token2; + this.token1 = null; + this.token2 = null; + + return result; + } + + return token; + }; + + SyntaxTokenReplacer.prototype.visitNode = function (node) { + if (this.token1 === null) { + return node; + } + + return _super.prototype.visitNode.call(this, node); + }; + + SyntaxTokenReplacer.prototype.visitList = function (list) { + if (this.token1 === null) { + return list; + } + + return _super.prototype.visitList.call(this, list); + }; + + SyntaxTokenReplacer.prototype.visitSeparatedList = function (list) { + if (this.token1 === null) { + return list; + } + + return _super.prototype.visitSeparatedList.call(this, list); + }; + return SyntaxTokenReplacer; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxTokenReplacer = SyntaxTokenReplacer; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var AbstractTrivia = (function () { + function AbstractTrivia(_kind) { + this._kind = _kind; + } + AbstractTrivia.prototype.fullWidth = function () { + throw TypeScript.Errors.abstract(); + }; + + AbstractTrivia.prototype.fullText = function () { + throw TypeScript.Errors.abstract(); + }; + + AbstractTrivia.prototype.skippedToken = function () { + throw TypeScript.Errors.abstract(); + }; + + AbstractTrivia.prototype.toJSON = function (key) { + var result = {}; + + for (var name in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind[name] === this._kind) { + result.kind = name; + break; + } + } + + if (this.isSkippedToken()) { + result.skippedToken = this.skippedToken(); + } else { + result.text = this.fullText(); + } + return result; + }; + + AbstractTrivia.prototype.kind = function () { + return this._kind; + }; + + AbstractTrivia.prototype.isWhitespace = function () { + return this.kind() === 4 /* WhitespaceTrivia */; + }; + + AbstractTrivia.prototype.isComment = function () { + return this.kind() === 7 /* SingleLineCommentTrivia */ || this.kind() === 6 /* MultiLineCommentTrivia */; + }; + + AbstractTrivia.prototype.isNewLine = function () { + return this.kind() === 5 /* NewLineTrivia */; + }; + + AbstractTrivia.prototype.isSkippedToken = function () { + return this.kind() === 8 /* SkippedTokenTrivia */; + }; + + AbstractTrivia.prototype.collectTextElements = function (elements) { + elements.push(this.fullText()); + }; + return AbstractTrivia; + })(); + + var NormalTrivia = (function (_super) { + __extends(NormalTrivia, _super); + function NormalTrivia(kind, _text) { + _super.call(this, kind); + this._text = _text; + } + NormalTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + + NormalTrivia.prototype.fullText = function () { + return this._text; + }; + + NormalTrivia.prototype.skippedToken = function () { + throw TypeScript.Errors.invalidOperation(); + }; + return NormalTrivia; + })(AbstractTrivia); + + var SkippedTokenTrivia = (function (_super) { + __extends(SkippedTokenTrivia, _super); + function SkippedTokenTrivia(_skippedToken) { + _super.call(this, 8 /* SkippedTokenTrivia */); + this._skippedToken = _skippedToken; + } + SkippedTokenTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + + SkippedTokenTrivia.prototype.fullText = function () { + return this.skippedToken().fullText(); + }; + + SkippedTokenTrivia.prototype.skippedToken = function () { + return this._skippedToken; + }; + return SkippedTokenTrivia; + })(AbstractTrivia); + + var DeferredTrivia = (function (_super) { + __extends(DeferredTrivia, _super); + function DeferredTrivia(kind, _text, _fullStart, _fullWidth) { + _super.call(this, kind); + this._text = _text; + this._fullStart = _fullStart; + this._fullWidth = _fullWidth; + this._fullText = null; + } + DeferredTrivia.prototype.fullWidth = function () { + return this._fullWidth; + }; + + DeferredTrivia.prototype.fullText = function () { + if (!this._fullText) { + this._fullText = this._text.substr(this._fullStart, this._fullWidth, false); + this._text = null; + } + + return this._fullText; + }; + + DeferredTrivia.prototype.skippedToken = function () { + throw TypeScript.Errors.invalidOperation(); + }; + return DeferredTrivia; + })(AbstractTrivia); + + function deferredTrivia(kind, text, fullStart, fullWidth) { + return new DeferredTrivia(kind, text, fullStart, fullWidth); + } + Syntax.deferredTrivia = deferredTrivia; + + function trivia(kind, text) { + return new NormalTrivia(kind, text); + } + Syntax.trivia = trivia; + + function skippedTokenTrivia(token) { + TypeScript.Debug.assert(!token.hasLeadingTrivia()); + TypeScript.Debug.assert(!token.hasTrailingTrivia()); + TypeScript.Debug.assert(token.fullWidth() > 0); + return new SkippedTokenTrivia(token); + } + Syntax.skippedTokenTrivia = skippedTokenTrivia; + + function spaces(count) { + return trivia(4 /* WhitespaceTrivia */, TypeScript.StringUtilities.repeat(" ", count)); + } + Syntax.spaces = spaces; + + function whitespace(text) { + return trivia(4 /* WhitespaceTrivia */, text); + } + Syntax.whitespace = whitespace; + + function multiLineComment(text) { + return trivia(6 /* MultiLineCommentTrivia */, text); + } + Syntax.multiLineComment = multiLineComment; + + function singleLineComment(text) { + return trivia(7 /* SingleLineCommentTrivia */, text); + } + Syntax.singleLineComment = singleLineComment; + + Syntax.spaceTrivia = spaces(1); + Syntax.lineFeedTrivia = trivia(5 /* NewLineTrivia */, "\n"); + Syntax.carriageReturnTrivia = trivia(5 /* NewLineTrivia */, "\r"); + Syntax.carriageReturnLineFeedTrivia = trivia(5 /* NewLineTrivia */, "\r\n"); + + function splitMultiLineCommentTriviaIntoMultipleLines(trivia) { + var result = []; + + var triviaText = trivia.fullText(); + var currentIndex = 0; + + for (var i = 0; i < triviaText.length; i++) { + var ch = triviaText.charCodeAt(i); + + var isCarriageReturnLineFeed = false; + switch (ch) { + case 13 /* carriageReturn */: + if (i < triviaText.length - 1 && triviaText.charCodeAt(i + 1) === 10 /* lineFeed */) { + i++; + } + + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + result.push(triviaText.substring(currentIndex, i + 1)); + + currentIndex = i + 1; + continue; + } + } + + result.push(triviaText.substring(currentIndex)); + return result; + } + Syntax.splitMultiLineCommentTriviaIntoMultipleLines = splitMultiLineCommentTriviaIntoMultipleLines; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + Syntax.emptyTriviaList = { + kind: function () { + return 3 /* TriviaList */; + }, + count: function () { + return 0; + }, + syntaxTriviaAt: function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }, + last: function () { + throw TypeScript.Errors.argumentOutOfRange("index"); + }, + fullWidth: function () { + return 0; + }, + fullText: function () { + return ""; + }, + hasComment: function () { + return false; + }, + hasNewLine: function () { + return false; + }, + hasSkippedToken: function () { + return false; + }, + toJSON: function (key) { + return []; + }, + collectTextElements: function (elements) { + }, + toArray: function () { + return []; + }, + concat: function (trivia) { + return trivia; + } + }; + + function concatTrivia(list1, list2) { + if (list1.count() === 0) { + return list2; + } + + if (list2.count() === 0) { + return list1; + } + + var trivia = list1.toArray(); + trivia.push.apply(trivia, list2.toArray()); + + return triviaList(trivia); + } + + function isComment(trivia) { + return trivia.kind() === 6 /* MultiLineCommentTrivia */ || trivia.kind() === 7 /* SingleLineCommentTrivia */; + } + + var SingletonSyntaxTriviaList = (function () { + function SingletonSyntaxTriviaList(item) { + this.item = item; + } + SingletonSyntaxTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + + SingletonSyntaxTriviaList.prototype.count = function () { + return 1; + }; + + SingletonSyntaxTriviaList.prototype.syntaxTriviaAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSyntaxTriviaList.prototype.last = function () { + return this.item; + }; + + SingletonSyntaxTriviaList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSyntaxTriviaList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSyntaxTriviaList.prototype.hasComment = function () { + return isComment(this.item); + }; + + SingletonSyntaxTriviaList.prototype.hasNewLine = function () { + return this.item.kind() === 5 /* NewLineTrivia */; + }; + + SingletonSyntaxTriviaList.prototype.hasSkippedToken = function () { + return this.item.kind() === 8 /* SkippedTokenTrivia */; + }; + + SingletonSyntaxTriviaList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSyntaxTriviaList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSyntaxTriviaList.prototype.toArray = function () { + return [this.item]; + }; + + SingletonSyntaxTriviaList.prototype.concat = function (trivia) { + return concatTrivia(this, trivia); + }; + return SingletonSyntaxTriviaList; + })(); + + var NormalSyntaxTriviaList = (function () { + function NormalSyntaxTriviaList(trivia) { + this.trivia = trivia; + } + NormalSyntaxTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + + NormalSyntaxTriviaList.prototype.count = function () { + return this.trivia.length; + }; + + NormalSyntaxTriviaList.prototype.syntaxTriviaAt = function (index) { + if (index < 0 || index >= this.trivia.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.trivia[index]; + }; + + NormalSyntaxTriviaList.prototype.last = function () { + return this.trivia[this.trivia.length - 1]; + }; + + NormalSyntaxTriviaList.prototype.fullWidth = function () { + return TypeScript.ArrayUtilities.sum(this.trivia, function (t) { + return t.fullWidth(); + }); + }; + + NormalSyntaxTriviaList.prototype.fullText = function () { + var result = ""; + + for (var i = 0, n = this.trivia.length; i < n; i++) { + result += this.trivia[i].fullText(); + } + + return result; + }; + + NormalSyntaxTriviaList.prototype.hasComment = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (isComment(this.trivia[i])) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.hasNewLine = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (this.trivia[i].kind() === 5 /* NewLineTrivia */) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.hasSkippedToken = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (this.trivia[i].kind() === 8 /* SkippedTokenTrivia */) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.toJSON = function (key) { + return this.trivia; + }; + + NormalSyntaxTriviaList.prototype.collectTextElements = function (elements) { + for (var i = 0; i < this.trivia.length; i++) { + this.trivia[i].collectTextElements(elements); + } + }; + + NormalSyntaxTriviaList.prototype.toArray = function () { + return this.trivia.slice(0); + }; + + NormalSyntaxTriviaList.prototype.concat = function (trivia) { + return concatTrivia(this, trivia); + }; + return NormalSyntaxTriviaList; + })(); + + function triviaList(trivia) { + if (trivia === undefined || trivia === null || trivia.length === 0) { + return Syntax.emptyTriviaList; + } + + if (trivia.length === 1) { + return new SingletonSyntaxTriviaList(trivia[0]); + } + + return new NormalSyntaxTriviaList(trivia); + } + Syntax.triviaList = triviaList; + + Syntax.spaceTriviaList = triviaList([Syntax.spaceTrivia]); + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxUtilities = (function () { + function SyntaxUtilities() { + } + SyntaxUtilities.isAngleBracket = function (positionedElement) { + var element = positionedElement.element(); + var parent = positionedElement.parentElement(); + if (parent !== null && (element.kind() === 80 /* LessThanToken */ || element.kind() === 81 /* GreaterThanToken */)) { + switch (parent.kind()) { + case 228 /* TypeArgumentList */: + case 229 /* TypeParameterList */: + case 220 /* CastExpression */: + return true; + } + } + + return false; + }; + + SyntaxUtilities.getToken = function (list, kind) { + for (var i = 0, n = list.childCount(); i < n; i++) { + var token = list.childAt(i); + if (token.tokenKind === kind) { + return token; + } + } + + return null; + }; + + SyntaxUtilities.containsToken = function (list, kind) { + return SyntaxUtilities.getToken(list, kind) !== null; + }; + + SyntaxUtilities.hasExportKeyword = function (moduleElement) { + return SyntaxUtilities.getExportKeyword(moduleElement) !== null; + }; + + SyntaxUtilities.getExportKeyword = function (moduleElement) { + switch (moduleElement.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 148 /* VariableStatement */: + case 132 /* EnumDeclaration */: + case 128 /* InterfaceDeclaration */: + case 133 /* ImportDeclaration */: + return SyntaxUtilities.getToken(moduleElement.modifiers, 47 /* ExportKeyword */); + default: + return null; + } + }; + + SyntaxUtilities.isAmbientDeclarationSyntax = function (positionNode) { + if (!positionNode) { + return false; + } + + var node = positionNode.node(); + switch (node.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 148 /* VariableStatement */: + case 132 /* EnumDeclaration */: + if (SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */)) { + return true; + } + + case 133 /* ImportDeclaration */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 136 /* MemberVariableDeclaration */: + if (node.isClassElement() || node.isModuleElement()) { + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode()); + } + + case 243 /* EnumElement */: + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode().containingNode()); + + default: + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode()); + } + }; + return SyntaxUtilities; + })(); + TypeScript.SyntaxUtilities = SyntaxUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxVisitor = (function () { + function SyntaxVisitor() { + } + SyntaxVisitor.prototype.defaultVisit = function (node) { + return null; + }; + + SyntaxVisitor.prototype.visitToken = function (token) { + return this.defaultVisit(token); + }; + + SyntaxVisitor.prototype.visitSourceUnit = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExternalModuleReference = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitModuleNameModuleReference = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitImportDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExportAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitClassDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitInterfaceDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitHeritageClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitModuleDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableDeclarator = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEqualsValueClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPrefixUnaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArrayLiteralExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitOmittedExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParenthesizedExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitQualifiedName = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeArgumentList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructorType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArrayType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitGenericType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeQuery = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeAnnotation = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBlock = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParameter = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberAccessExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPostfixUnaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitElementAccessExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitInvocationExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArgumentList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBinaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConditionalExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMethodSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIndexSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPropertySignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCallSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParameterList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeParameterList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeParameter = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstraint = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitElseClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIfStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExpressionStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructorDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitGetAccessor = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSetAccessor = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberVariableDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIndexMemberDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitThrowStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitReturnStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectCreationExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSwitchStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCaseSwitchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDefaultSwitchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBreakStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitContinueStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitForStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitForInStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitWhileStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitWithStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEnumDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEnumElement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCastExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectLiteralExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSimplePropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEmptyStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTryStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCatchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFinallyClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitLabeledStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDoStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeOfExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDeleteExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVoidExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDebuggerStatement = function (node) { + return this.defaultVisit(node); + }; + return SyntaxVisitor; + })(); + TypeScript.SyntaxVisitor = SyntaxVisitor; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxWalker = (function () { + function SyntaxWalker() { + } + SyntaxWalker.prototype.visitToken = function (token) { + }; + + SyntaxWalker.prototype.visitNode = function (node) { + node.accept(this); + }; + + SyntaxWalker.prototype.visitNodeOrToken = function (nodeOrToken) { + if (nodeOrToken.isToken()) { + this.visitToken(nodeOrToken); + } else { + this.visitNode(nodeOrToken); + } + }; + + SyntaxWalker.prototype.visitOptionalToken = function (token) { + if (token === null) { + return; + } + + this.visitToken(token); + }; + + SyntaxWalker.prototype.visitOptionalNode = function (node) { + if (node === null) { + return; + } + + this.visitNode(node); + }; + + SyntaxWalker.prototype.visitOptionalNodeOrToken = function (nodeOrToken) { + if (nodeOrToken === null) { + return; + } + + this.visitNodeOrToken(nodeOrToken); + }; + + SyntaxWalker.prototype.visitList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + this.visitNodeOrToken(list.childAt(i)); + } + }; + + SyntaxWalker.prototype.visitSeparatedList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + this.visitNodeOrToken(item); + } + }; + + SyntaxWalker.prototype.visitSourceUnit = function (node) { + this.visitList(node.moduleElements); + this.visitToken(node.endOfFileToken); + }; + + SyntaxWalker.prototype.visitExternalModuleReference = function (node) { + this.visitToken(node.requireKeyword); + this.visitToken(node.openParenToken); + this.visitToken(node.stringLiteral); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitModuleNameModuleReference = function (node) { + this.visitNodeOrToken(node.moduleName); + }; + + SyntaxWalker.prototype.visitImportDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.importKeyword); + this.visitToken(node.identifier); + this.visitToken(node.equalsToken); + this.visitNodeOrToken(node.moduleReference); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitExportAssignment = function (node) { + this.visitToken(node.exportKeyword); + this.visitToken(node.equalsToken); + this.visitToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitClassDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.classKeyword); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeParameterList); + this.visitList(node.heritageClauses); + this.visitToken(node.openBraceToken); + this.visitList(node.classElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitInterfaceDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.interfaceKeyword); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeParameterList); + this.visitList(node.heritageClauses); + this.visitNode(node.body); + }; + + SyntaxWalker.prototype.visitHeritageClause = function (node) { + this.visitToken(node.extendsOrImplementsKeyword); + this.visitSeparatedList(node.typeNames); + }; + + SyntaxWalker.prototype.visitModuleDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.moduleKeyword); + this.visitOptionalNodeOrToken(node.name); + this.visitOptionalToken(node.stringLiteral); + this.visitToken(node.openBraceToken); + this.visitList(node.moduleElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitFunctionDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.functionKeyword); + this.visitToken(node.identifier); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitVariableStatement = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.variableDeclaration); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitVariableDeclaration = function (node) { + this.visitToken(node.varKeyword); + this.visitSeparatedList(node.variableDeclarators); + }; + + SyntaxWalker.prototype.visitVariableDeclarator = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalNode(node.typeAnnotation); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitEqualsValueClause = function (node) { + this.visitToken(node.equalsToken); + this.visitNodeOrToken(node.value); + }; + + SyntaxWalker.prototype.visitPrefixUnaryExpression = function (node) { + this.visitToken(node.operatorToken); + this.visitNodeOrToken(node.operand); + }; + + SyntaxWalker.prototype.visitArrayLiteralExpression = function (node) { + this.visitToken(node.openBracketToken); + this.visitSeparatedList(node.expressions); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitOmittedExpression = function (node) { + }; + + SyntaxWalker.prototype.visitParenthesizedExpression = function (node) { + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitSimpleArrowFunctionExpression = function (node) { + this.visitToken(node.identifier); + this.visitToken(node.equalsGreaterThanToken); + this.visitOptionalNode(node.block); + this.visitOptionalNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + this.visitNode(node.callSignature); + this.visitToken(node.equalsGreaterThanToken); + this.visitOptionalNode(node.block); + this.visitOptionalNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitQualifiedName = function (node) { + this.visitNodeOrToken(node.left); + this.visitToken(node.dotToken); + this.visitToken(node.right); + }; + + SyntaxWalker.prototype.visitTypeArgumentList = function (node) { + this.visitToken(node.lessThanToken); + this.visitSeparatedList(node.typeArguments); + this.visitToken(node.greaterThanToken); + }; + + SyntaxWalker.prototype.visitConstructorType = function (node) { + this.visitToken(node.newKeyword); + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitFunctionType = function (node) { + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitObjectType = function (node) { + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.typeMembers); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitArrayType = function (node) { + this.visitNodeOrToken(node.type); + this.visitToken(node.openBracketToken); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitGenericType = function (node) { + this.visitNodeOrToken(node.name); + this.visitNode(node.typeArgumentList); + }; + + SyntaxWalker.prototype.visitTypeQuery = function (node) { + this.visitToken(node.typeOfKeyword); + this.visitNodeOrToken(node.name); + }; + + SyntaxWalker.prototype.visitTypeAnnotation = function (node) { + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitBlock = function (node) { + this.visitToken(node.openBraceToken); + this.visitList(node.statements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitParameter = function (node) { + this.visitOptionalToken(node.dotDotDotToken); + this.visitList(node.modifiers); + this.visitToken(node.identifier); + this.visitOptionalToken(node.questionToken); + this.visitOptionalNode(node.typeAnnotation); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitMemberAccessExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.dotToken); + this.visitToken(node.name); + }; + + SyntaxWalker.prototype.visitPostfixUnaryExpression = function (node) { + this.visitNodeOrToken(node.operand); + this.visitToken(node.operatorToken); + }; + + SyntaxWalker.prototype.visitElementAccessExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.openBracketToken); + this.visitNodeOrToken(node.argumentExpression); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitInvocationExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitNode(node.argumentList); + }; + + SyntaxWalker.prototype.visitArgumentList = function (node) { + this.visitOptionalNode(node.typeArgumentList); + this.visitToken(node.openParenToken); + this.visitSeparatedList(node.arguments); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitBinaryExpression = function (node) { + this.visitNodeOrToken(node.left); + this.visitToken(node.operatorToken); + this.visitNodeOrToken(node.right); + }; + + SyntaxWalker.prototype.visitConditionalExpression = function (node) { + this.visitNodeOrToken(node.condition); + this.visitToken(node.questionToken); + this.visitNodeOrToken(node.whenTrue); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.whenFalse); + }; + + SyntaxWalker.prototype.visitConstructSignature = function (node) { + this.visitToken(node.newKeyword); + this.visitNode(node.callSignature); + }; + + SyntaxWalker.prototype.visitMethodSignature = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalToken(node.questionToken); + this.visitNode(node.callSignature); + }; + + SyntaxWalker.prototype.visitIndexSignature = function (node) { + this.visitToken(node.openBracketToken); + this.visitNode(node.parameter); + this.visitToken(node.closeBracketToken); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitPropertySignature = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalToken(node.questionToken); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitCallSignature = function (node) { + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitParameterList = function (node) { + this.visitToken(node.openParenToken); + this.visitSeparatedList(node.parameters); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitTypeParameterList = function (node) { + this.visitToken(node.lessThanToken); + this.visitSeparatedList(node.typeParameters); + this.visitToken(node.greaterThanToken); + }; + + SyntaxWalker.prototype.visitTypeParameter = function (node) { + this.visitToken(node.identifier); + this.visitOptionalNode(node.constraint); + }; + + SyntaxWalker.prototype.visitConstraint = function (node) { + this.visitToken(node.extendsKeyword); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitElseClause = function (node) { + this.visitToken(node.elseKeyword); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitIfStatement = function (node) { + this.visitToken(node.ifKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + this.visitOptionalNode(node.elseClause); + }; + + SyntaxWalker.prototype.visitExpressionStatement = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitConstructorDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.constructorKeyword); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitMemberFunctionDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitGetAccessor = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.getKeyword); + this.visitToken(node.propertyName); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.typeAnnotation); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitSetAccessor = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.setKeyword); + this.visitToken(node.propertyName); + this.visitNode(node.parameterList); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitMemberVariableDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.variableDeclarator); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitIndexMemberDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.indexSignature); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitThrowStatement = function (node) { + this.visitToken(node.throwKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitReturnStatement = function (node) { + this.visitToken(node.returnKeyword); + this.visitOptionalNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitObjectCreationExpression = function (node) { + this.visitToken(node.newKeyword); + this.visitNodeOrToken(node.expression); + this.visitOptionalNode(node.argumentList); + }; + + SyntaxWalker.prototype.visitSwitchStatement = function (node) { + this.visitToken(node.switchKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + this.visitToken(node.openBraceToken); + this.visitList(node.switchClauses); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitCaseSwitchClause = function (node) { + this.visitToken(node.caseKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.colonToken); + this.visitList(node.statements); + }; + + SyntaxWalker.prototype.visitDefaultSwitchClause = function (node) { + this.visitToken(node.defaultKeyword); + this.visitToken(node.colonToken); + this.visitList(node.statements); + }; + + SyntaxWalker.prototype.visitBreakStatement = function (node) { + this.visitToken(node.breakKeyword); + this.visitOptionalToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitContinueStatement = function (node) { + this.visitToken(node.continueKeyword); + this.visitOptionalToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitForStatement = function (node) { + this.visitToken(node.forKeyword); + this.visitToken(node.openParenToken); + this.visitOptionalNode(node.variableDeclaration); + this.visitOptionalNodeOrToken(node.initializer); + this.visitToken(node.firstSemicolonToken); + this.visitOptionalNodeOrToken(node.condition); + this.visitToken(node.secondSemicolonToken); + this.visitOptionalNodeOrToken(node.incrementor); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitForInStatement = function (node) { + this.visitToken(node.forKeyword); + this.visitToken(node.openParenToken); + this.visitOptionalNode(node.variableDeclaration); + this.visitOptionalNodeOrToken(node.left); + this.visitToken(node.inKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitWhileStatement = function (node) { + this.visitToken(node.whileKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitWithStatement = function (node) { + this.visitToken(node.withKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitEnumDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.enumKeyword); + this.visitToken(node.identifier); + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.enumElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitEnumElement = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitCastExpression = function (node) { + this.visitToken(node.lessThanToken); + this.visitNodeOrToken(node.type); + this.visitToken(node.greaterThanToken); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitObjectLiteralExpression = function (node) { + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.propertyAssignments); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitSimplePropertyAssignment = function (node) { + this.visitToken(node.propertyName); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitFunctionPropertyAssignment = function (node) { + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitFunctionExpression = function (node) { + this.visitToken(node.functionKeyword); + this.visitOptionalToken(node.identifier); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitEmptyStatement = function (node) { + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitTryStatement = function (node) { + this.visitToken(node.tryKeyword); + this.visitNode(node.block); + this.visitOptionalNode(node.catchClause); + this.visitOptionalNode(node.finallyClause); + }; + + SyntaxWalker.prototype.visitCatchClause = function (node) { + this.visitToken(node.catchKeyword); + this.visitToken(node.openParenToken); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeAnnotation); + this.visitToken(node.closeParenToken); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitFinallyClause = function (node) { + this.visitToken(node.finallyKeyword); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitLabeledStatement = function (node) { + this.visitToken(node.identifier); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitDoStatement = function (node) { + this.visitToken(node.doKeyword); + this.visitNodeOrToken(node.statement); + this.visitToken(node.whileKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitTypeOfExpression = function (node) { + this.visitToken(node.typeOfKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitDeleteExpression = function (node) { + this.visitToken(node.deleteKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitVoidExpression = function (node) { + this.visitToken(node.voidKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitDebuggerStatement = function (node) { + this.visitToken(node.debuggerKeyword); + this.visitToken(node.semicolonToken); + }; + return SyntaxWalker; + })(); + TypeScript.SyntaxWalker = SyntaxWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PositionTrackingWalker = (function (_super) { + __extends(PositionTrackingWalker, _super); + function PositionTrackingWalker() { + _super.apply(this, arguments); + this._position = 0; + } + PositionTrackingWalker.prototype.visitToken = function (token) { + this._position += token.fullWidth(); + }; + + PositionTrackingWalker.prototype.position = function () { + return this._position; + }; + + PositionTrackingWalker.prototype.skip = function (element) { + this._position += element.fullWidth(); + }; + return PositionTrackingWalker; + })(TypeScript.SyntaxWalker); + TypeScript.PositionTrackingWalker = PositionTrackingWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxInformationMap = (function (_super) { + __extends(SyntaxInformationMap, _super); + function SyntaxInformationMap(trackParents, trackPreviousToken) { + _super.call(this); + this.trackParents = trackParents; + this.trackPreviousToken = trackPreviousToken; + this.tokenToInformation = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this.elementToPosition = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this._previousToken = null; + this._previousTokenInformation = null; + this._currentPosition = 0; + this._elementToParent = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this._parentStack = []; + this._parentStack.push(null); + } + SyntaxInformationMap.create = function (node, trackParents, trackPreviousToken) { + var map = new SyntaxInformationMap(trackParents, trackPreviousToken); + map.visitNode(node); + return map; + }; + + SyntaxInformationMap.prototype.visitNode = function (node) { + this.trackParents && this._elementToParent.add(node, TypeScript.ArrayUtilities.last(this._parentStack)); + this.elementToPosition.add(node, this._currentPosition); + + this.trackParents && this._parentStack.push(node); + _super.prototype.visitNode.call(this, node); + this.trackParents && this._parentStack.pop(); + }; + + SyntaxInformationMap.prototype.visitToken = function (token) { + this.trackParents && this._elementToParent.add(token, TypeScript.ArrayUtilities.last(this._parentStack)); + + if (this.trackPreviousToken) { + var tokenInformation = { + previousToken: this._previousToken, + nextToken: null + }; + + if (this._previousTokenInformation !== null) { + this._previousTokenInformation.nextToken = token; + } + + this._previousToken = token; + this._previousTokenInformation = tokenInformation; + + this.tokenToInformation.add(token, tokenInformation); + } + + this.elementToPosition.add(token, this._currentPosition); + this._currentPosition += token.fullWidth(); + }; + + SyntaxInformationMap.prototype.parent = function (element) { + return this._elementToParent.get(element); + }; + + SyntaxInformationMap.prototype.fullStart = function (element) { + return this.elementToPosition.get(element); + }; + + SyntaxInformationMap.prototype.start = function (element) { + return this.fullStart(element) + element.leadingTriviaWidth(); + }; + + SyntaxInformationMap.prototype.end = function (element) { + return this.start(element) + element.width(); + }; + + SyntaxInformationMap.prototype.previousToken = function (token) { + return this.tokenInformation(token).previousToken; + }; + + SyntaxInformationMap.prototype.tokenInformation = function (token) { + return this.tokenToInformation.get(token); + }; + + SyntaxInformationMap.prototype.firstTokenInLineContainingToken = function (token) { + var current = token; + while (true) { + var information = this.tokenInformation(current); + if (this.isFirstTokenInLineWorker(information)) { + break; + } + + current = information.previousToken; + } + + return current; + }; + + SyntaxInformationMap.prototype.isFirstTokenInLine = function (token) { + var information = this.tokenInformation(token); + return this.isFirstTokenInLineWorker(information); + }; + + SyntaxInformationMap.prototype.isFirstTokenInLineWorker = function (information) { + return information.previousToken === null || information.previousToken.hasTrailingNewLine(); + }; + return SyntaxInformationMap; + })(TypeScript.SyntaxWalker); + TypeScript.SyntaxInformationMap = SyntaxInformationMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxNodeInvariantsChecker = (function (_super) { + __extends(SyntaxNodeInvariantsChecker, _super); + function SyntaxNodeInvariantsChecker() { + _super.apply(this, arguments); + this.tokenTable = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + } + SyntaxNodeInvariantsChecker.checkInvariants = function (node) { + node.accept(new SyntaxNodeInvariantsChecker()); + }; + + SyntaxNodeInvariantsChecker.prototype.visitToken = function (token) { + this.tokenTable.add(token, token); + }; + return SyntaxNodeInvariantsChecker; + })(TypeScript.SyntaxWalker); + TypeScript.SyntaxNodeInvariantsChecker = SyntaxNodeInvariantsChecker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DepthLimitedWalker = (function (_super) { + __extends(DepthLimitedWalker, _super); + function DepthLimitedWalker(maximumDepth) { + _super.call(this); + this._depth = 0; + this._maximumDepth = 0; + this._maximumDepth = maximumDepth; + } + DepthLimitedWalker.prototype.visitNode = function (node) { + if (this._depth < this._maximumDepth) { + this._depth++; + _super.prototype.visitNode.call(this, node); + this._depth--; + } else { + this.skip(node); + } + }; + return DepthLimitedWalker; + })(TypeScript.PositionTrackingWalker); + TypeScript.DepthLimitedWalker = DepthLimitedWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Parser) { + + + var ExpressionPrecedence; + (function (ExpressionPrecedence) { + ExpressionPrecedence[ExpressionPrecedence["CommaExpressionPrecedence"] = 1] = "CommaExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["AssignmentExpressionPrecedence"] = 2] = "AssignmentExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["ConditionalExpressionPrecedence"] = 3] = "ConditionalExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["ArrowFunctionPrecedence"] = 4] = "ArrowFunctionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["LogicalOrExpressionPrecedence"] = 5] = "LogicalOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["LogicalAndExpressionPrecedence"] = 6] = "LogicalAndExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseOrExpressionPrecedence"] = 7] = "BitwiseOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseExclusiveOrExpressionPrecedence"] = 8] = "BitwiseExclusiveOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseAndExpressionPrecedence"] = 9] = "BitwiseAndExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["EqualityExpressionPrecedence"] = 10] = "EqualityExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["RelationalExpressionPrecedence"] = 11] = "RelationalExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["ShiftExpressionPrecdence"] = 12] = "ShiftExpressionPrecdence"; + ExpressionPrecedence[ExpressionPrecedence["AdditiveExpressionPrecedence"] = 13] = "AdditiveExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["MultiplicativeExpressionPrecedence"] = 14] = "MultiplicativeExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["UnaryExpressionPrecedence"] = 15] = "UnaryExpressionPrecedence"; + })(ExpressionPrecedence || (ExpressionPrecedence = {})); + + var ListParsingState; + (function (ListParsingState) { + ListParsingState[ListParsingState["SourceUnit_ModuleElements"] = 1 << 0] = "SourceUnit_ModuleElements"; + ListParsingState[ListParsingState["ClassDeclaration_ClassElements"] = 1 << 1] = "ClassDeclaration_ClassElements"; + ListParsingState[ListParsingState["ModuleDeclaration_ModuleElements"] = 1 << 2] = "ModuleDeclaration_ModuleElements"; + ListParsingState[ListParsingState["SwitchStatement_SwitchClauses"] = 1 << 3] = "SwitchStatement_SwitchClauses"; + ListParsingState[ListParsingState["SwitchClause_Statements"] = 1 << 4] = "SwitchClause_Statements"; + ListParsingState[ListParsingState["Block_Statements"] = 1 << 5] = "Block_Statements"; + ListParsingState[ListParsingState["TryBlock_Statements"] = 1 << 6] = "TryBlock_Statements"; + ListParsingState[ListParsingState["CatchBlock_Statements"] = 1 << 7] = "CatchBlock_Statements"; + ListParsingState[ListParsingState["EnumDeclaration_EnumElements"] = 1 << 8] = "EnumDeclaration_EnumElements"; + ListParsingState[ListParsingState["ObjectType_TypeMembers"] = 1 << 9] = "ObjectType_TypeMembers"; + ListParsingState[ListParsingState["ClassOrInterfaceDeclaration_HeritageClauses"] = 1 << 10] = "ClassOrInterfaceDeclaration_HeritageClauses"; + ListParsingState[ListParsingState["HeritageClause_TypeNameList"] = 1 << 11] = "HeritageClause_TypeNameList"; + ListParsingState[ListParsingState["VariableDeclaration_VariableDeclarators_AllowIn"] = 1 << 12] = "VariableDeclaration_VariableDeclarators_AllowIn"; + ListParsingState[ListParsingState["VariableDeclaration_VariableDeclarators_DisallowIn"] = 1 << 13] = "VariableDeclaration_VariableDeclarators_DisallowIn"; + ListParsingState[ListParsingState["ArgumentList_AssignmentExpressions"] = 1 << 14] = "ArgumentList_AssignmentExpressions"; + ListParsingState[ListParsingState["ObjectLiteralExpression_PropertyAssignments"] = 1 << 15] = "ObjectLiteralExpression_PropertyAssignments"; + ListParsingState[ListParsingState["ArrayLiteralExpression_AssignmentExpressions"] = 1 << 16] = "ArrayLiteralExpression_AssignmentExpressions"; + ListParsingState[ListParsingState["ParameterList_Parameters"] = 1 << 17] = "ParameterList_Parameters"; + ListParsingState[ListParsingState["TypeArgumentList_Types"] = 1 << 18] = "TypeArgumentList_Types"; + ListParsingState[ListParsingState["TypeParameterList_TypeParameters"] = 1 << 19] = "TypeParameterList_TypeParameters"; + + ListParsingState[ListParsingState["FirstListParsingState"] = ListParsingState.SourceUnit_ModuleElements] = "FirstListParsingState"; + ListParsingState[ListParsingState["LastListParsingState"] = ListParsingState.TypeParameterList_TypeParameters] = "LastListParsingState"; + })(ListParsingState || (ListParsingState = {})); + + var SyntaxCursor = (function () { + function SyntaxCursor(sourceUnit) { + this._elements = []; + this._index = 0; + this._pinCount = 0; + sourceUnit.insertChildrenInto(this._elements, 0); + } + SyntaxCursor.prototype.isFinished = function () { + return this._index === this._elements.length; + }; + + SyntaxCursor.prototype.currentElement = function () { + if (this.isFinished()) { + return null; + } + + return this._elements[this._index]; + }; + + SyntaxCursor.prototype.currentNode = function () { + var element = this.currentElement(); + return element !== null && element.isNode() ? element : null; + }; + + SyntaxCursor.prototype.moveToFirstChild = function () { + if (this.isFinished()) { + return; + } + + var element = this._elements[this._index]; + if (element.isToken()) { + return; + } + + var node = element; + + this._elements.splice(this._index, 1); + + node.insertChildrenInto(this._elements, this._index); + }; + + SyntaxCursor.prototype.moveToNextSibling = function () { + if (this.isFinished()) { + return; + } + + if (this._pinCount > 0) { + this._index++; + return; + } + + this._elements.shift(); + }; + + SyntaxCursor.prototype.getAndPinCursorIndex = function () { + this._pinCount++; + return this._index; + }; + + SyntaxCursor.prototype.releaseAndUnpinCursorIndex = function (index) { + this._pinCount--; + if (this._pinCount === 0) { + } + }; + + SyntaxCursor.prototype.rewindToPinnedCursorIndex = function (index) { + this._index = index; + }; + + SyntaxCursor.prototype.pinCount = function () { + return this._pinCount; + }; + + SyntaxCursor.prototype.moveToFirstToken = function () { + var element; + + while (!this.isFinished()) { + element = this.currentElement(); + if (element.isNode()) { + this.moveToFirstChild(); + continue; + } + + return; + } + }; + + SyntaxCursor.prototype.currentToken = function () { + this.moveToFirstToken(); + if (this.isFinished()) { + return null; + } + + var element = this.currentElement(); + + return element; + }; + + SyntaxCursor.prototype.peekToken = function (n) { + this.moveToFirstToken(); + var pin = this.getAndPinCursorIndex(); + + for (var i = 0; i < n; i++) { + this.moveToNextSibling(); + this.moveToFirstToken(); + } + + var result = this.currentToken(); + this.rewindToPinnedCursorIndex(pin); + this.releaseAndUnpinCursorIndex(pin); + + return result; + }; + return SyntaxCursor; + })(); + + + + var NormalParserSource = (function () { + function NormalParserSource(fileName, text, languageVersion) { + this._previousToken = null; + this._absolutePosition = 0; + this._tokenDiagnostics = []; + this.rewindPointPool = []; + this.rewindPointPoolCount = 0; + this.slidingWindow = new TypeScript.SlidingWindow(this, TypeScript.ArrayUtilities.createArray(32, null), null); + this.scanner = new TypeScript.Scanner(fileName, text, languageVersion); + } + NormalParserSource.prototype.currentNode = function () { + return null; + }; + + NormalParserSource.prototype.moveToNextNode = function () { + throw TypeScript.Errors.invalidOperation(); + }; + + NormalParserSource.prototype.absolutePosition = function () { + return this._absolutePosition; + }; + + NormalParserSource.prototype.previousToken = function () { + return this._previousToken; + }; + + NormalParserSource.prototype.tokenDiagnostics = function () { + return this._tokenDiagnostics; + }; + + NormalParserSource.prototype.getOrCreateRewindPoint = function () { + if (this.rewindPointPoolCount === 0) { + return {}; + } + + this.rewindPointPoolCount--; + var result = this.rewindPointPool[this.rewindPointPoolCount]; + this.rewindPointPool[this.rewindPointPoolCount] = null; + return result; + }; + + NormalParserSource.prototype.getRewindPoint = function () { + var slidingWindowIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + var rewindPoint = this.getOrCreateRewindPoint(); + + rewindPoint.slidingWindowIndex = slidingWindowIndex; + rewindPoint.previousToken = this._previousToken; + rewindPoint.absolutePosition = this._absolutePosition; + + rewindPoint.pinCount = this.slidingWindow.pinCount(); + + return rewindPoint; + }; + + NormalParserSource.prototype.isPinned = function () { + return this.slidingWindow.pinCount() > 0; + }; + + NormalParserSource.prototype.rewind = function (rewindPoint) { + this.slidingWindow.rewindToPinnedIndex(rewindPoint.slidingWindowIndex); + + this._previousToken = rewindPoint.previousToken; + this._absolutePosition = rewindPoint.absolutePosition; + }; + + NormalParserSource.prototype.releaseRewindPoint = function (rewindPoint) { + this.slidingWindow.releaseAndUnpinAbsoluteIndex(rewindPoint.absoluteIndex); + + this.rewindPointPool[this.rewindPointPoolCount] = rewindPoint; + this.rewindPointPoolCount++; + }; + + NormalParserSource.prototype.fetchMoreItems = function (allowRegularExpression, sourceIndex, window, destinationIndex, spaceAvailable) { + window[destinationIndex] = this.scanner.scan(this._tokenDiagnostics, allowRegularExpression); + return 1; + }; + + NormalParserSource.prototype.peekToken = function (n) { + return this.slidingWindow.peekItemN(n); + }; + + NormalParserSource.prototype.moveToNextToken = function () { + var currentToken = this.currentToken(); + this._absolutePosition += currentToken.fullWidth(); + this._previousToken = currentToken; + + this.slidingWindow.moveToNextItem(); + }; + + NormalParserSource.prototype.currentToken = function () { + return this.slidingWindow.currentItem(false); + }; + + NormalParserSource.prototype.removeDiagnosticsOnOrAfterPosition = function (position) { + var tokenDiagnosticsLength = this._tokenDiagnostics.length; + while (tokenDiagnosticsLength > 0) { + var diagnostic = this._tokenDiagnostics[tokenDiagnosticsLength - 1]; + if (diagnostic.start() >= position) { + tokenDiagnosticsLength--; + } else { + break; + } + } + + this._tokenDiagnostics.length = tokenDiagnosticsLength; + }; + + NormalParserSource.prototype.resetToPosition = function (absolutePosition, previousToken) { + this._absolutePosition = absolutePosition; + this._previousToken = previousToken; + + this.removeDiagnosticsOnOrAfterPosition(absolutePosition); + + this.slidingWindow.disgardAllItemsFromCurrentIndexOnwards(); + + this.scanner.setAbsoluteIndex(absolutePosition); + }; + + NormalParserSource.prototype.currentTokenAllowingRegularExpression = function () { + this.resetToPosition(this._absolutePosition, this._previousToken); + + var token = this.slidingWindow.currentItem(true); + + return token; + }; + return NormalParserSource; + })(); + + var IncrementalParserSource = (function () { + function IncrementalParserSource(oldSyntaxTree, textChangeRange, newText) { + this._changeDelta = 0; + var oldSourceUnit = oldSyntaxTree.sourceUnit(); + this._oldSourceUnitCursor = new SyntaxCursor(oldSourceUnit); + + this._changeRange = IncrementalParserSource.extendToAffectedRange(textChangeRange, oldSourceUnit); + + if (TypeScript.Debug.shouldAssert(2 /* Aggressive */)) { + TypeScript.Debug.assert((oldSourceUnit.fullWidth() - this._changeRange.span().length() + this._changeRange.newLength()) === newText.length()); + } + + this._normalParserSource = new NormalParserSource(oldSyntaxTree.fileName(), newText, oldSyntaxTree.parseOptions().languageVersion()); + } + IncrementalParserSource.extendToAffectedRange = function (changeRange, sourceUnit) { + var maxLookahead = 1; + + var start = changeRange.span().start(); + + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var token = sourceUnit.findToken(start); + + var position = token.fullStart(); + + start = TypeScript.MathPrototype.max(0, position - 1); + } + + var finalSpan = TypeScript.TextSpan.fromBounds(start, changeRange.span().end()); + var finalLength = changeRange.newLength() + (changeRange.span().start() - start); + + return new TypeScript.TextChangeRange(finalSpan, finalLength); + }; + + IncrementalParserSource.prototype.absolutePosition = function () { + return this._normalParserSource.absolutePosition(); + }; + + IncrementalParserSource.prototype.previousToken = function () { + return this._normalParserSource.previousToken(); + }; + + IncrementalParserSource.prototype.tokenDiagnostics = function () { + return this._normalParserSource.tokenDiagnostics(); + }; + + IncrementalParserSource.prototype.getRewindPoint = function () { + var rewindPoint = this._normalParserSource.getRewindPoint(); + var oldSourceUnitCursorIndex = this._oldSourceUnitCursor.getAndPinCursorIndex(); + + rewindPoint.changeDelta = this._changeDelta; + rewindPoint.changeRange = this._changeRange; + rewindPoint.oldSourceUnitCursorIndex = oldSourceUnitCursorIndex; + + return rewindPoint; + }; + + IncrementalParserSource.prototype.rewind = function (rewindPoint) { + this._changeRange = rewindPoint.changeRange; + this._changeDelta = rewindPoint.changeDelta; + this._oldSourceUnitCursor.rewindToPinnedCursorIndex(rewindPoint.oldSourceUnitCursorIndex); + + this._normalParserSource.rewind(rewindPoint); + }; + + IncrementalParserSource.prototype.releaseRewindPoint = function (rewindPoint) { + this._oldSourceUnitCursor.releaseAndUnpinCursorIndex(rewindPoint.oldSourceUnitCursorIndex); + this._normalParserSource.releaseRewindPoint(rewindPoint); + }; + + IncrementalParserSource.prototype.canReadFromOldSourceUnit = function () { + if (this._normalParserSource.isPinned()) { + return false; + } + + if (this._changeRange !== null && this._changeRange.newSpan().intersectsWithPosition(this.absolutePosition())) { + return false; + } + + this.syncCursorToNewTextIfBehind(); + + return this._changeDelta === 0 && !this._oldSourceUnitCursor.isFinished(); + }; + + IncrementalParserSource.prototype.currentNode = function () { + if (this.canReadFromOldSourceUnit()) { + return this.tryGetNodeFromOldSourceUnit(); + } + + return null; + }; + + IncrementalParserSource.prototype.currentToken = function () { + if (this.canReadFromOldSourceUnit()) { + var token = this.tryGetTokenFromOldSourceUnit(); + if (token !== null) { + return token; + } + } + + return this._normalParserSource.currentToken(); + }; + + IncrementalParserSource.prototype.currentTokenAllowingRegularExpression = function () { + return this._normalParserSource.currentTokenAllowingRegularExpression(); + }; + + IncrementalParserSource.prototype.syncCursorToNewTextIfBehind = function () { + while (true) { + if (this._oldSourceUnitCursor.isFinished()) { + break; + } + + if (this._changeDelta >= 0) { + break; + } + + var currentElement = this._oldSourceUnitCursor.currentElement(); + + if (currentElement.isNode() && (currentElement.fullWidth() > Math.abs(this._changeDelta))) { + this._oldSourceUnitCursor.moveToFirstChild(); + } else { + this._oldSourceUnitCursor.moveToNextSibling(); + + this._changeDelta += currentElement.fullWidth(); + } + } + }; + + IncrementalParserSource.prototype.intersectsWithChangeRangeSpanInOriginalText = function (start, length) { + return this._changeRange !== null && this._changeRange.span().intersectsWith(start, length); + }; + + IncrementalParserSource.prototype.tryGetNodeFromOldSourceUnit = function () { + while (true) { + var node = this._oldSourceUnitCursor.currentNode(); + if (node === null) { + return null; + } + + if (!this.intersectsWithChangeRangeSpanInOriginalText(this.absolutePosition(), node.fullWidth())) { + if (!node.isIncrementallyUnusable()) { + return node; + } + } + + this._oldSourceUnitCursor.moveToFirstChild(); + } + }; + + IncrementalParserSource.prototype.canReuseTokenFromOldSourceUnit = function (position, token) { + if (token !== null) { + if (!this.intersectsWithChangeRangeSpanInOriginalText(position, token.fullWidth())) { + if (!token.isIncrementallyUnusable()) { + return true; + } + } + } + + return false; + }; + + IncrementalParserSource.prototype.tryGetTokenFromOldSourceUnit = function () { + var token = this._oldSourceUnitCursor.currentToken(); + + return this.canReuseTokenFromOldSourceUnit(this.absolutePosition(), token) ? token : null; + }; + + IncrementalParserSource.prototype.peekToken = function (n) { + if (this.canReadFromOldSourceUnit()) { + var token = this.tryPeekTokenFromOldSourceUnit(n); + if (token !== null) { + return token; + } + } + + return this._normalParserSource.peekToken(n); + }; + + IncrementalParserSource.prototype.tryPeekTokenFromOldSourceUnit = function (n) { + var currentPosition = this.absolutePosition(); + for (var i = 0; i < n; i++) { + var interimToken = this._oldSourceUnitCursor.peekToken(i); + if (!this.canReuseTokenFromOldSourceUnit(currentPosition, interimToken)) { + return null; + } + + currentPosition += interimToken.fullWidth(); + } + + var token = this._oldSourceUnitCursor.peekToken(n); + return this.canReuseTokenFromOldSourceUnit(currentPosition, token) ? token : null; + }; + + IncrementalParserSource.prototype.moveToNextNode = function () { + var currentElement = this._oldSourceUnitCursor.currentElement(); + var currentNode = this._oldSourceUnitCursor.currentNode(); + + this._oldSourceUnitCursor.moveToNextSibling(); + + var absolutePosition = this.absolutePosition() + currentNode.fullWidth(); + var previousToken = currentNode.lastToken(); + this._normalParserSource.resetToPosition(absolutePosition, previousToken); + + if (this._changeRange !== null) { + } + }; + + IncrementalParserSource.prototype.moveToNextToken = function () { + var currentToken = this.currentToken(); + + if (this._oldSourceUnitCursor.currentToken() === currentToken) { + this._oldSourceUnitCursor.moveToNextSibling(); + + var absolutePosition = this.absolutePosition() + currentToken.fullWidth(); + var previousToken = currentToken; + this._normalParserSource.resetToPosition(absolutePosition, previousToken); + + if (this._changeRange !== null) { + } + } else { + this._changeDelta -= currentToken.fullWidth(); + + this._normalParserSource.moveToNextToken(); + + if (this._changeRange !== null) { + var changeRangeSpanInNewText = this._changeRange.newSpan(); + if (this.absolutePosition() >= changeRangeSpanInNewText.end()) { + this._changeDelta += this._changeRange.newLength() - this._changeRange.span().length(); + this._changeRange = null; + } + } + } + }; + return IncrementalParserSource; + })(); + + var ParserImpl = (function () { + function ParserImpl(fileName, lineMap, source, parseOptions, newText_forDebuggingPurposesOnly) { + this.newText_forDebuggingPurposesOnly = newText_forDebuggingPurposesOnly; + this.listParsingState = 0; + this.isInStrictMode = false; + this.diagnostics = []; + this.factory = TypeScript.Syntax.normalModeFactory; + this.mergeTokensStorage = []; + this.arrayPool = []; + this.fileName = fileName; + this.lineMap = lineMap; + this.source = source; + this.parseOptions = parseOptions; + } + ParserImpl.prototype.getRewindPoint = function () { + var rewindPoint = this.source.getRewindPoint(); + + rewindPoint.diagnosticsCount = this.diagnostics.length; + + rewindPoint.isInStrictMode = this.isInStrictMode; + rewindPoint.listParsingState = this.listParsingState; + + return rewindPoint; + }; + + ParserImpl.prototype.rewind = function (rewindPoint) { + this.source.rewind(rewindPoint); + + this.diagnostics.length = rewindPoint.diagnosticsCount; + }; + + ParserImpl.prototype.releaseRewindPoint = function (rewindPoint) { + this.source.releaseRewindPoint(rewindPoint); + }; + + ParserImpl.prototype.currentTokenStart = function () { + return this.source.absolutePosition() + this.currentToken().leadingTriviaWidth(); + }; + + ParserImpl.prototype.previousTokenStart = function () { + if (this.previousToken() === null) { + return 0; + } + + return this.source.absolutePosition() - this.previousToken().fullWidth() + this.previousToken().leadingTriviaWidth(); + }; + + ParserImpl.prototype.previousTokenEnd = function () { + if (this.previousToken() === null) { + return 0; + } + + return this.previousTokenStart() + this.previousToken().width(); + }; + + ParserImpl.prototype.currentNode = function () { + var node = this.source.currentNode(); + + if (node === null || node.parsedInStrictMode() !== this.isInStrictMode) { + return null; + } + + return node; + }; + + ParserImpl.prototype.currentToken = function () { + return this.source.currentToken(); + }; + + ParserImpl.prototype.currentTokenAllowingRegularExpression = function () { + return this.source.currentTokenAllowingRegularExpression(); + }; + + ParserImpl.prototype.peekToken = function (n) { + return this.source.peekToken(n); + }; + + ParserImpl.prototype.eatAnyToken = function () { + var token = this.currentToken(); + this.moveToNextToken(); + return token; + }; + + ParserImpl.prototype.moveToNextToken = function () { + this.source.moveToNextToken(); + }; + + ParserImpl.prototype.previousToken = function () { + return this.source.previousToken(); + }; + + ParserImpl.prototype.eatNode = function () { + var node = this.source.currentNode(); + this.source.moveToNextNode(); + return node; + }; + + ParserImpl.prototype.eatToken = function (kind) { + var token = this.currentToken(); + if (token.tokenKind === kind) { + this.moveToNextToken(); + return token; + } + + return this.createMissingToken(kind, token); + }; + + ParserImpl.prototype.tryEatToken = function (kind) { + if (this.currentToken().tokenKind === kind) { + return this.eatToken(kind); + } + + return null; + }; + + ParserImpl.prototype.eatKeyword = function (kind) { + var token = this.currentToken(); + if (token.tokenKind === kind) { + this.moveToNextToken(); + return token; + } + + return this.createMissingToken(kind, token); + }; + + ParserImpl.prototype.isIdentifier = function (token) { + var tokenKind = token.tokenKind; + + if (tokenKind === 11 /* IdentifierName */) { + return true; + } + + if (tokenKind >= 51 /* FirstFutureReservedStrictKeyword */) { + if (tokenKind <= 59 /* LastFutureReservedStrictKeyword */) { + return !this.isInStrictMode; + } + + return tokenKind <= 69 /* LastTypeScriptKeyword */; + } + + return false; + }; + + ParserImpl.prototype.eatIdentifierNameToken = function () { + var token = this.currentToken(); + + if (token.tokenKind === 11 /* IdentifierName */) { + this.moveToNextToken(); + return token; + } + + if (TypeScript.SyntaxFacts.isAnyKeyword(token.tokenKind)) { + this.moveToNextToken(); + return TypeScript.Syntax.convertToIdentifierName(token); + } + + return this.createMissingToken(11 /* IdentifierName */, token); + }; + + ParserImpl.prototype.eatIdentifierToken = function () { + var token = this.currentToken(); + if (this.isIdentifier(token)) { + this.moveToNextToken(); + + if (token.tokenKind === 11 /* IdentifierName */) { + return token; + } + + return TypeScript.Syntax.convertToIdentifierName(token); + } + + return this.createMissingToken(11 /* IdentifierName */, token); + }; + + ParserImpl.prototype.canEatAutomaticSemicolon = function (allowWithoutNewLine) { + var token = this.currentToken(); + + if (token.tokenKind === 10 /* EndOfFileToken */) { + return true; + } + + if (token.tokenKind === 71 /* CloseBraceToken */) { + return true; + } + + if (allowWithoutNewLine) { + return true; + } + + if (this.previousToken() !== null && this.previousToken().hasTrailingNewLine()) { + return true; + } + + return false; + }; + + ParserImpl.prototype.canEatExplicitOrAutomaticSemicolon = function (allowWithoutNewline) { + var token = this.currentToken(); + + if (token.tokenKind === 78 /* SemicolonToken */) { + return true; + } + + return this.canEatAutomaticSemicolon(allowWithoutNewline); + }; + + ParserImpl.prototype.eatExplicitOrAutomaticSemicolon = function (allowWithoutNewline) { + var token = this.currentToken(); + + if (token.tokenKind === 78 /* SemicolonToken */) { + return this.eatToken(78 /* SemicolonToken */); + } + + if (this.canEatAutomaticSemicolon(allowWithoutNewline)) { + var semicolonToken = TypeScript.Syntax.emptyToken(78 /* SemicolonToken */); + + if (!this.parseOptions.allowAutomaticSemicolonInsertion()) { + this.addDiagnostic(new TypeScript.Diagnostic(this.fileName, this.lineMap, this.previousTokenEnd(), 0, TypeScript.DiagnosticCode.Automatic_semicolon_insertion_not_allowed, null)); + } + + return semicolonToken; + } + + return this.eatToken(78 /* SemicolonToken */); + }; + + ParserImpl.prototype.isKeyword = function (kind) { + if (kind >= 15 /* FirstKeyword */) { + if (kind <= 50 /* LastFutureReservedKeyword */) { + return true; + } + + if (this.isInStrictMode) { + return kind <= 59 /* LastFutureReservedStrictKeyword */; + } + } + + return false; + }; + + ParserImpl.prototype.createMissingToken = function (expectedKind, actual) { + var diagnostic = this.getExpectedTokenDiagnostic(expectedKind, actual); + this.addDiagnostic(diagnostic); + + return TypeScript.Syntax.emptyToken(expectedKind); + }; + + ParserImpl.prototype.getExpectedTokenDiagnostic = function (expectedKind, actual) { + var token = this.currentToken(); + + if (TypeScript.SyntaxFacts.isAnyKeyword(expectedKind) || TypeScript.SyntaxFacts.isAnyPunctuation(expectedKind)) { + return new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode._0_expected, [TypeScript.SyntaxFacts.getText(expectedKind)]); + } else { + if (actual !== null && TypeScript.SyntaxFacts.isAnyKeyword(actual.tokenKind)) { + return new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode.Identifier_expected_0_is_a_keyword, [TypeScript.SyntaxFacts.getText(actual.tokenKind)]); + } else { + return new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode.Identifier_expected, null); + } + } + }; + + ParserImpl.getPrecedence = function (expressionKind) { + switch (expressionKind) { + case 173 /* CommaExpression */: + return 1 /* CommaExpressionPrecedence */; + + case 174 /* AssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + return 2 /* AssignmentExpressionPrecedence */; + + case 186 /* ConditionalExpression */: + return 3 /* ConditionalExpressionPrecedence */; + + case 187 /* LogicalOrExpression */: + return 5 /* LogicalOrExpressionPrecedence */; + + case 188 /* LogicalAndExpression */: + return 6 /* LogicalAndExpressionPrecedence */; + + case 189 /* BitwiseOrExpression */: + return 7 /* BitwiseOrExpressionPrecedence */; + + case 190 /* BitwiseExclusiveOrExpression */: + return 8 /* BitwiseExclusiveOrExpressionPrecedence */; + + case 191 /* BitwiseAndExpression */: + return 9 /* BitwiseAndExpressionPrecedence */; + + case 192 /* EqualsWithTypeConversionExpression */: + case 193 /* NotEqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + return 10 /* EqualityExpressionPrecedence */; + + case 196 /* LessThanExpression */: + case 197 /* GreaterThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 200 /* InstanceOfExpression */: + case 201 /* InExpression */: + return 11 /* RelationalExpressionPrecedence */; + + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + return 12 /* ShiftExpressionPrecdence */; + + case 208 /* AddExpression */: + case 209 /* SubtractExpression */: + return 13 /* AdditiveExpressionPrecedence */; + + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + return 14 /* MultiplicativeExpressionPrecedence */; + + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + case 166 /* BitwiseNotExpression */: + case 167 /* LogicalNotExpression */: + case 170 /* DeleteExpression */: + case 171 /* TypeOfExpression */: + case 172 /* VoidExpression */: + case 168 /* PreIncrementExpression */: + case 169 /* PreDecrementExpression */: + return 15 /* UnaryExpressionPrecedence */; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + ParserImpl.prototype.addSkippedTokenAfterNodeOrToken = function (nodeOrToken, skippedToken) { + if (nodeOrToken.isToken()) { + return this.addSkippedTokenAfterToken(nodeOrToken, skippedToken); + } else if (nodeOrToken.isNode()) { + return this.addSkippedTokenAfterNode(nodeOrToken, skippedToken); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.addSkippedTokenAfterNode = function (node, skippedToken) { + var oldToken = node.lastToken(); + var newToken = this.addSkippedTokenAfterToken(oldToken, skippedToken); + + return node.replaceToken(oldToken, newToken); + }; + + ParserImpl.prototype.addSkippedTokensBeforeNode = function (node, skippedTokens) { + if (skippedTokens.length > 0) { + var oldToken = node.firstToken(); + var newToken = this.addSkippedTokensBeforeToken(oldToken, skippedTokens); + + return node.replaceToken(oldToken, newToken); + } + + return node; + }; + + ParserImpl.prototype.addSkippedTokensBeforeToken = function (token, skippedTokens) { + var leadingTrivia = []; + for (var i = 0, n = skippedTokens.length; i < n; i++) { + this.addSkippedTokenToTriviaArray(leadingTrivia, skippedTokens[i]); + } + + this.addTriviaTo(token.leadingTrivia(), leadingTrivia); + + this.returnArray(skippedTokens); + return token.withLeadingTrivia(TypeScript.Syntax.triviaList(leadingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokensAfterToken = function (token, skippedTokens) { + if (skippedTokens.length === 0) { + this.returnArray(skippedTokens); + return token; + } + + var trailingTrivia = token.trailingTrivia().toArray(); + + for (var i = 0, n = skippedTokens.length; i < n; i++) { + this.addSkippedTokenToTriviaArray(trailingTrivia, skippedTokens[i]); + } + + this.returnArray(skippedTokens); + return token.withTrailingTrivia(TypeScript.Syntax.triviaList(trailingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokenAfterToken = function (token, skippedToken) { + var trailingTrivia = token.trailingTrivia().toArray(); + this.addSkippedTokenToTriviaArray(trailingTrivia, skippedToken); + + return token.withTrailingTrivia(TypeScript.Syntax.triviaList(trailingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokenToTriviaArray = function (array, skippedToken) { + this.addTriviaTo(skippedToken.leadingTrivia(), array); + + var trimmedToken = skippedToken.withLeadingTrivia(TypeScript.Syntax.emptyTriviaList).withTrailingTrivia(TypeScript.Syntax.emptyTriviaList); + array.push(TypeScript.Syntax.skippedTokenTrivia(trimmedToken)); + + this.addTriviaTo(skippedToken.trailingTrivia(), array); + }; + + ParserImpl.prototype.addTriviaTo = function (list, array) { + for (var i = 0, n = list.count(); i < n; i++) { + array.push(list.syntaxTriviaAt(i)); + } + }; + + ParserImpl.prototype.parseSyntaxTree = function (isDeclaration) { + var sourceUnit = this.parseSourceUnit(); + + var allDiagnostics = this.source.tokenDiagnostics().concat(this.diagnostics); + allDiagnostics.sort(function (a, b) { + return a.start() - b.start(); + }); + + return new TypeScript.SyntaxTree(sourceUnit, isDeclaration, allDiagnostics, this.fileName, this.lineMap, this.parseOptions); + }; + + ParserImpl.prototype.setStrictMode = function (isInStrictMode) { + this.isInStrictMode = isInStrictMode; + this.factory = isInStrictMode ? TypeScript.Syntax.strictModeFactory : TypeScript.Syntax.normalModeFactory; + }; + + ParserImpl.prototype.parseSourceUnit = function () { + var savedIsInStrictMode = this.isInStrictMode; + + var result = this.parseSyntaxList(1 /* SourceUnit_ModuleElements */, ParserImpl.updateStrictModeState); + var moduleElements = result.list; + + this.setStrictMode(savedIsInStrictMode); + + var sourceUnit = this.factory.sourceUnit(moduleElements, this.currentToken()); + sourceUnit = this.addSkippedTokensBeforeNode(sourceUnit, result.skippedTokens); + + if (TypeScript.Debug.shouldAssert(2 /* Aggressive */)) { + TypeScript.Debug.assert(sourceUnit.fullWidth() === this.newText_forDebuggingPurposesOnly.length()); + + if (TypeScript.Debug.shouldAssert(3 /* VeryAggressive */)) { + TypeScript.Debug.assert(sourceUnit.fullText() === this.newText_forDebuggingPurposesOnly.substr(0, this.newText_forDebuggingPurposesOnly.length(), false)); + } + } + + return sourceUnit; + }; + + ParserImpl.updateStrictModeState = function (parser, items) { + if (!parser.isInStrictMode) { + for (var i = 0; i < items.length; i++) { + var item = items[i]; + if (!TypeScript.SyntaxFacts.isDirectivePrologueElement(item)) { + return; + } + } + + parser.setStrictMode(TypeScript.SyntaxFacts.isUseStrictDirective(items[items.length - 1])); + } + }; + + ParserImpl.prototype.isModuleElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isModuleElement()) { + return true; + } + + var modifierCount = this.modifierCount(); + return this.isImportDeclaration(modifierCount) || this.isExportAssignment() || this.isModuleDeclaration(modifierCount) || this.isInterfaceDeclaration(modifierCount) || this.isClassDeclaration(modifierCount) || this.isEnumDeclaration(modifierCount) || this.isStatement(inErrorRecovery); + }; + + ParserImpl.prototype.parseModuleElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isModuleElement()) { + return this.eatNode(); + } + + var modifierCount = this.modifierCount(); + if (this.isImportDeclaration(modifierCount)) { + return this.parseImportDeclaration(); + } else if (this.isExportAssignment()) { + return this.parseExportAssignment(); + } else if (this.isModuleDeclaration(modifierCount)) { + return this.parseModuleDeclaration(); + } else if (this.isInterfaceDeclaration(modifierCount)) { + return this.parseInterfaceDeclaration(); + } else if (this.isClassDeclaration(modifierCount)) { + return this.parseClassDeclaration(); + } else if (this.isEnumDeclaration(modifierCount)) { + return this.parseEnumDeclaration(); + } else if (this.isStatement(inErrorRecovery)) { + return this.parseStatement(inErrorRecovery); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isImportDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 49 /* ImportKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 49 /* ImportKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseImportDeclaration = function () { + var modifiers = this.parseModifiers(); + var importKeyword = this.eatKeyword(49 /* ImportKeyword */); + var identifier = this.eatIdentifierToken(); + var equalsToken = this.eatToken(107 /* EqualsToken */); + var moduleReference = this.parseModuleReference(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.importDeclaration(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken); + }; + + ParserImpl.prototype.isExportAssignment = function () { + return this.currentToken().tokenKind === 47 /* ExportKeyword */ && this.peekToken(1).tokenKind === 107 /* EqualsToken */; + }; + + ParserImpl.prototype.parseExportAssignment = function () { + var exportKeyword = this.eatKeyword(47 /* ExportKeyword */); + var equalsToken = this.eatToken(107 /* EqualsToken */); + var identifier = this.eatIdentifierToken(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.exportAssignment(exportKeyword, equalsToken, identifier, semicolonToken); + }; + + ParserImpl.prototype.parseModuleReference = function () { + if (this.isExternalModuleReference()) { + return this.parseExternalModuleReference(); + } else { + return this.parseModuleNameModuleReference(); + } + }; + + ParserImpl.prototype.isExternalModuleReference = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 66 /* RequireKeyword */) { + return this.peekToken(1).tokenKind === 72 /* OpenParenToken */; + } + + return false; + }; + + ParserImpl.prototype.parseExternalModuleReference = function () { + var requireKeyword = this.eatKeyword(66 /* RequireKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var stringLiteral = this.eatToken(14 /* StringLiteral */); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + return this.factory.externalModuleReference(requireKeyword, openParenToken, stringLiteral, closeParenToken); + }; + + ParserImpl.prototype.parseModuleNameModuleReference = function () { + var name = this.parseName(); + return this.factory.moduleNameModuleReference(name); + }; + + ParserImpl.prototype.parseIdentifierName = function () { + var identifierName = this.eatIdentifierNameToken(); + return identifierName; + }; + + ParserImpl.prototype.tryParseTypeArgumentList = function (inExpression) { + if (this.currentToken().kind() !== 80 /* LessThanToken */) { + return null; + } + + var lessThanToken; + var greaterThanToken; + var result; + var typeArguments; + + if (!inExpression) { + lessThanToken = this.eatToken(80 /* LessThanToken */); + + result = this.parseSeparatedSyntaxList(262144 /* TypeArgumentList_Types */); + typeArguments = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + + return this.factory.typeArgumentList(lessThanToken, typeArguments, greaterThanToken); + } + + var rewindPoint = this.getRewindPoint(); + + lessThanToken = this.eatToken(80 /* LessThanToken */); + + result = this.parseSeparatedSyntaxList(262144 /* TypeArgumentList_Types */); + typeArguments = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + + if (greaterThanToken.fullWidth() === 0 || !this.canFollowTypeArgumentListInExpression(this.currentToken().kind())) { + this.rewind(rewindPoint); + + this.releaseRewindPoint(rewindPoint); + return null; + } else { + this.releaseRewindPoint(rewindPoint); + var typeArgumentList = this.factory.typeArgumentList(lessThanToken, typeArguments, greaterThanToken); + + return typeArgumentList; + } + }; + + ParserImpl.prototype.canFollowTypeArgumentListInExpression = function (kind) { + switch (kind) { + case 72 /* OpenParenToken */: + case 76 /* DotToken */: + + case 73 /* CloseParenToken */: + case 75 /* CloseBracketToken */: + case 106 /* ColonToken */: + case 78 /* SemicolonToken */: + case 79 /* CommaToken */: + case 105 /* QuestionToken */: + case 84 /* EqualsEqualsToken */: + case 87 /* EqualsEqualsEqualsToken */: + case 86 /* ExclamationEqualsToken */: + case 88 /* ExclamationEqualsEqualsToken */: + case 103 /* AmpersandAmpersandToken */: + case 104 /* BarBarToken */: + case 100 /* CaretToken */: + case 98 /* AmpersandToken */: + case 99 /* BarToken */: + case 71 /* CloseBraceToken */: + case 10 /* EndOfFileToken */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.parseName = function () { + var shouldContinue = this.isIdentifier(this.currentToken()); + var current = this.eatIdentifierToken(); + + while (shouldContinue && this.currentToken().tokenKind === 76 /* DotToken */) { + var dotToken = this.eatToken(76 /* DotToken */); + + var currentToken = this.currentToken(); + var identifierName; + + if (TypeScript.SyntaxFacts.isAnyKeyword(currentToken.tokenKind) && this.previousToken().hasTrailingNewLine() && !currentToken.hasTrailingNewLine() && TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(this.peekToken(1))) { + identifierName = this.createMissingToken(11 /* IdentifierName */, currentToken); + } else { + identifierName = this.eatIdentifierNameToken(); + } + + current = this.factory.qualifiedName(current, dotToken, identifierName); + + shouldContinue = identifierName.fullWidth() > 0; + } + + return current; + }; + + ParserImpl.prototype.isEnumDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 46 /* EnumKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 46 /* EnumKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseEnumDeclaration = function () { + var modifiers = this.parseModifiers(); + var enumKeyword = this.eatKeyword(46 /* EnumKeyword */); + var identifier = this.eatIdentifierToken(); + + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + var enumElements = TypeScript.Syntax.emptySeparatedList; + + if (openBraceToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(256 /* EnumDeclaration_EnumElements */); + enumElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.enumDeclaration(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken); + }; + + ParserImpl.prototype.isEnumElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().kind() === 243 /* EnumElement */) { + return true; + } + + return this.isPropertyName(this.currentToken(), inErrorRecovery); + }; + + ParserImpl.prototype.parseEnumElement = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 243 /* EnumElement */) { + return this.eatNode(); + } + + var propertyName = this.eatPropertyName(); + var equalsValueClause = null; + if (this.isEqualsValueClause(false)) { + equalsValueClause = this.parseEqualsValueClause(true); + } + + return this.factory.enumElement(propertyName, equalsValueClause); + }; + + ParserImpl.isModifier = function (token) { + switch (token.tokenKind) { + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + case 47 /* ExportKeyword */: + case 63 /* DeclareKeyword */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.modifierCount = function () { + var modifierCount = 0; + while (true) { + if (ParserImpl.isModifier(this.peekToken(modifierCount))) { + modifierCount++; + continue; + } + + break; + } + + return modifierCount; + }; + + ParserImpl.prototype.parseModifiers = function () { + var tokens = this.getArray(); + + while (true) { + if (ParserImpl.isModifier(this.currentToken())) { + tokens.push(this.eatAnyToken()); + continue; + } + + break; + } + + var result = TypeScript.Syntax.list(tokens); + + this.returnZeroOrOneLengthArray(tokens); + + return result; + }; + + ParserImpl.prototype.isClassDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 44 /* ClassKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 44 /* ClassKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseHeritageClauses = function () { + var heritageClauses = TypeScript.Syntax.emptyList; + + if (this.isHeritageClause()) { + var result = this.parseSyntaxList(1024 /* ClassOrInterfaceDeclaration_HeritageClauses */); + heritageClauses = result.list; + TypeScript.Debug.assert(result.skippedTokens.length === 0); + } + + return heritageClauses; + }; + + ParserImpl.prototype.parseClassDeclaration = function () { + var modifiers = this.parseModifiers(); + + var classKeyword = this.eatKeyword(44 /* ClassKeyword */); + var identifier = this.eatIdentifierToken(); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var heritageClauses = this.parseHeritageClauses(); + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + var classElements = TypeScript.Syntax.emptyList; + + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(2 /* ClassDeclaration_ClassElements */); + + classElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + return this.factory.classDeclaration(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken); + }; + + ParserImpl.isPublicOrPrivateKeyword = function (token) { + return token.tokenKind === 57 /* PublicKeyword */ || token.tokenKind === 55 /* PrivateKeyword */; + }; + + ParserImpl.prototype.isAccessor = function (inErrorRecovery) { + var index = this.modifierCount(); + + if (this.peekToken(index).tokenKind !== 64 /* GetKeyword */ && this.peekToken(index).tokenKind !== 68 /* SetKeyword */) { + return false; + } + + index++; + return this.isPropertyName(this.peekToken(index), inErrorRecovery); + }; + + ParserImpl.prototype.parseAccessor = function (checkForStrictMode) { + var modifiers = this.parseModifiers(); + + if (this.currentToken().tokenKind === 64 /* GetKeyword */) { + return this.parseGetMemberAccessorDeclaration(modifiers, checkForStrictMode); + } else if (this.currentToken().tokenKind === 68 /* SetKeyword */) { + return this.parseSetMemberAccessorDeclaration(modifiers, checkForStrictMode); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseGetMemberAccessorDeclaration = function (modifiers, checkForStrictMode) { + var getKeyword = this.eatKeyword(64 /* GetKeyword */); + var propertyName = this.eatPropertyName(); + var parameterList = this.parseParameterList(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + var block = this.parseBlock(false, checkForStrictMode); + + return this.factory.getAccessor(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block); + }; + + ParserImpl.prototype.parseSetMemberAccessorDeclaration = function (modifiers, checkForStrictMode) { + var setKeyword = this.eatKeyword(68 /* SetKeyword */); + var propertyName = this.eatPropertyName(); + var parameterList = this.parseParameterList(); + var block = this.parseBlock(false, checkForStrictMode); + + return this.factory.setAccessor(modifiers, setKeyword, propertyName, parameterList, block); + }; + + ParserImpl.prototype.isClassElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isClassElement()) { + return true; + } + + return this.isConstructorDeclaration() || this.isMemberFunctionDeclaration(inErrorRecovery) || this.isAccessor(inErrorRecovery) || this.isMemberVariableDeclaration(inErrorRecovery) || this.isIndexMemberDeclaration(); + }; + + ParserImpl.prototype.parseClassElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isClassElement()) { + return this.eatNode(); + } + + if (this.isConstructorDeclaration()) { + return this.parseConstructorDeclaration(); + } else if (this.isMemberFunctionDeclaration(inErrorRecovery)) { + return this.parseMemberFunctionDeclaration(); + } else if (this.isAccessor(inErrorRecovery)) { + return this.parseAccessor(false); + } else if (this.isMemberVariableDeclaration(inErrorRecovery)) { + return this.parseMemberVariableDeclaration(); + } else if (this.isIndexMemberDeclaration()) { + return this.parseIndexMemberDeclaration(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isConstructorDeclaration = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 62 /* ConstructorKeyword */; + }; + + ParserImpl.prototype.parseConstructorDeclaration = function () { + var modifiers = this.parseModifiers(); + var constructorKeyword = this.eatKeyword(62 /* ConstructorKeyword */); + var callSignature = this.parseCallSignature(false); + + var semicolonToken = null; + var block = null; + + if (this.isBlock()) { + block = this.parseBlock(false, true); + } else { + semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.constructorDeclaration(modifiers, constructorKeyword, callSignature, block, semicolonToken); + }; + + ParserImpl.prototype.isMemberFunctionDeclaration = function (inErrorRecovery) { + var index = 0; + + while (true) { + var token = this.peekToken(index); + if (this.isPropertyName(token, inErrorRecovery) && this.isCallSignature(index + 1)) { + return true; + } + + if (ParserImpl.isModifier(token)) { + index++; + continue; + } + + return false; + } + }; + + ParserImpl.prototype.parseMemberFunctionDeclaration = function () { + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (this.isPropertyName(currentToken, false) && this.isCallSignature(1)) { + break; + } + + TypeScript.Debug.assert(ParserImpl.isModifier(currentToken)); + modifierArray.push(this.eatAnyToken()); + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var propertyName = this.eatPropertyName(); + var callSignature = this.parseCallSignature(false); + + var parseBlockEvenWithNoOpenBrace = false; + var newCallSignature = this.tryAddUnexpectedEqualsGreaterThanToken(callSignature); + if (newCallSignature !== callSignature) { + parseBlockEvenWithNoOpenBrace = true; + callSignature = newCallSignature; + } + + var block = null; + var semicolon = null; + + if (parseBlockEvenWithNoOpenBrace || this.isBlock()) { + block = this.parseBlock(parseBlockEvenWithNoOpenBrace, true); + } else { + semicolon = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.memberFunctionDeclaration(modifiers, propertyName, callSignature, block, semicolon); + }; + + ParserImpl.prototype.isDefinitelyMemberVariablePropertyName = function (index) { + if (TypeScript.SyntaxFacts.isAnyKeyword(this.peekToken(index).tokenKind)) { + switch (this.peekToken(index + 1).tokenKind) { + case 78 /* SemicolonToken */: + case 107 /* EqualsToken */: + case 106 /* ColonToken */: + case 71 /* CloseBraceToken */: + case 10 /* EndOfFileToken */: + return true; + default: + return false; + } + } else { + return true; + } + }; + + ParserImpl.prototype.isMemberVariableDeclaration = function (inErrorRecovery) { + var index = 0; + + while (true) { + var token = this.peekToken(index); + if (this.isPropertyName(token, inErrorRecovery) && this.isDefinitelyMemberVariablePropertyName(index)) { + return true; + } + + if (ParserImpl.isModifier(this.peekToken(index))) { + index++; + continue; + } + + return false; + } + }; + + ParserImpl.prototype.parseMemberVariableDeclaration = function () { + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (this.isPropertyName(currentToken, false) && this.isDefinitelyMemberVariablePropertyName(0)) { + break; + } + + TypeScript.Debug.assert(ParserImpl.isModifier(currentToken)); + modifierArray.push(this.eatAnyToken()); + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var variableDeclarator = this.parseVariableDeclarator(true, true); + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.memberVariableDeclaration(modifiers, variableDeclarator, semicolon); + }; + + ParserImpl.prototype.isIndexMemberDeclaration = function () { + var index = this.modifierCount(); + return this.isIndexSignature(index); + }; + + ParserImpl.prototype.parseIndexMemberDeclaration = function () { + var modifiers = this.parseModifiers(); + var indexSignature = this.parseIndexSignature(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.indexMemberDeclaration(modifiers, indexSignature, semicolonToken); + }; + + ParserImpl.prototype.tryAddUnexpectedEqualsGreaterThanToken = function (callSignature) { + var token0 = this.currentToken(); + + var hasEqualsGreaterThanToken = token0.tokenKind === 85 /* EqualsGreaterThanToken */; + if (hasEqualsGreaterThanToken) { + if (callSignature.lastToken()) { + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token0.width(), TypeScript.DiagnosticCode.Unexpected_token_0_expected, [TypeScript.SyntaxFacts.getText(70 /* OpenBraceToken */)]); + this.addDiagnostic(diagnostic); + + var token = this.eatAnyToken(); + return this.addSkippedTokenAfterNode(callSignature, token0); + } + } + + return callSignature; + }; + + ParserImpl.prototype.isFunctionDeclaration = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 27 /* FunctionKeyword */; + }; + + ParserImpl.prototype.parseFunctionDeclaration = function () { + var modifiers = this.parseModifiers(); + var functionKeyword = this.eatKeyword(27 /* FunctionKeyword */); + var identifier = this.eatIdentifierToken(); + var callSignature = this.parseCallSignature(false); + + var parseBlockEvenWithNoOpenBrace = false; + var newCallSignature = this.tryAddUnexpectedEqualsGreaterThanToken(callSignature); + if (newCallSignature !== callSignature) { + parseBlockEvenWithNoOpenBrace = true; + callSignature = newCallSignature; + } + + var semicolonToken = null; + var block = null; + + if (parseBlockEvenWithNoOpenBrace || this.isBlock()) { + block = this.parseBlock(parseBlockEvenWithNoOpenBrace, true); + } else { + semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.functionDeclaration(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken); + }; + + ParserImpl.prototype.isModuleDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 65 /* ModuleKeyword */) { + return true; + } + + if (this.currentToken().tokenKind === 65 /* ModuleKeyword */) { + var token1 = this.peekToken(1); + return this.isIdentifier(token1) || token1.tokenKind === 14 /* StringLiteral */; + } + + return false; + }; + + ParserImpl.prototype.parseModuleDeclaration = function () { + var modifiers = this.parseModifiers(); + var moduleKeyword = this.eatKeyword(65 /* ModuleKeyword */); + + var moduleName = null; + var stringLiteral = null; + + if (this.currentToken().tokenKind === 14 /* StringLiteral */) { + stringLiteral = this.eatToken(14 /* StringLiteral */); + } else { + moduleName = this.parseName(); + } + + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var moduleElements = TypeScript.Syntax.emptyList; + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(4 /* ModuleDeclaration_ModuleElements */); + moduleElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.moduleDeclaration(modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken); + }; + + ParserImpl.prototype.isInterfaceDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 52 /* InterfaceKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 52 /* InterfaceKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseInterfaceDeclaration = function () { + var modifiers = this.parseModifiers(); + var interfaceKeyword = this.eatKeyword(52 /* InterfaceKeyword */); + var identifier = this.eatIdentifierToken(); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var heritageClauses = this.parseHeritageClauses(); + + var objectType = this.parseObjectType(); + return this.factory.interfaceDeclaration(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, objectType); + }; + + ParserImpl.prototype.parseObjectType = function () { + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var typeMembers = TypeScript.Syntax.emptySeparatedList; + if (openBraceToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(512 /* ObjectType_TypeMembers */); + typeMembers = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + return this.factory.objectType(openBraceToken, typeMembers, closeBraceToken); + }; + + ParserImpl.prototype.isTypeMember = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isTypeMember()) { + return true; + } + + return this.isCallSignature(0) || this.isConstructSignature() || this.isIndexSignature(0) || this.isMethodSignature(inErrorRecovery) || this.isPropertySignature(inErrorRecovery); + }; + + ParserImpl.prototype.parseTypeMember = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isTypeMember()) { + return this.eatNode(); + } + + if (this.isCallSignature(0)) { + return this.parseCallSignature(false); + } else if (this.isConstructSignature()) { + return this.parseConstructSignature(); + } else if (this.isIndexSignature(0)) { + return this.parseIndexSignature(); + } else if (this.isMethodSignature(inErrorRecovery)) { + return this.parseMethodSignature(); + } else if (this.isPropertySignature(inErrorRecovery)) { + return this.parsePropertySignature(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseConstructSignature = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + var callSignature = this.parseCallSignature(false); + + return this.factory.constructSignature(newKeyword, callSignature); + }; + + ParserImpl.prototype.parseIndexSignature = function () { + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + var parameter = this.parseParameter(); + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.indexSignature(openBracketToken, parameter, closeBracketToken, typeAnnotation); + }; + + ParserImpl.prototype.parseMethodSignature = function () { + var propertyName = this.eatPropertyName(); + var questionToken = this.tryEatToken(105 /* QuestionToken */); + var callSignature = this.parseCallSignature(false); + + return this.factory.methodSignature(propertyName, questionToken, callSignature); + }; + + ParserImpl.prototype.parsePropertySignature = function () { + var propertyName = this.eatPropertyName(); + var questionToken = this.tryEatToken(105 /* QuestionToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.propertySignature(propertyName, questionToken, typeAnnotation); + }; + + ParserImpl.prototype.isCallSignature = function (tokenIndex) { + var tokenKind = this.peekToken(tokenIndex).tokenKind; + return tokenKind === 72 /* OpenParenToken */ || tokenKind === 80 /* LessThanToken */; + }; + + ParserImpl.prototype.isConstructSignature = function () { + if (this.currentToken().tokenKind !== 31 /* NewKeyword */) { + return false; + } + + var token1 = this.peekToken(1); + return token1.tokenKind === 80 /* LessThanToken */ || token1.tokenKind === 72 /* OpenParenToken */; + }; + + ParserImpl.prototype.isIndexSignature = function (tokenIndex) { + return this.peekToken(tokenIndex).tokenKind === 74 /* OpenBracketToken */; + }; + + ParserImpl.prototype.isMethodSignature = function (inErrorRecovery) { + if (this.isPropertyName(this.currentToken(), inErrorRecovery)) { + if (this.isCallSignature(1)) { + return true; + } + + if (this.peekToken(1).tokenKind === 105 /* QuestionToken */ && this.isCallSignature(2)) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.isPropertySignature = function (inErrorRecovery) { + var currentToken = this.currentToken(); + + if (ParserImpl.isModifier(currentToken) && !currentToken.hasTrailingNewLine() && this.isPropertyName(this.peekToken(1), inErrorRecovery)) { + return false; + } + + return this.isPropertyName(currentToken, inErrorRecovery); + }; + + ParserImpl.prototype.isHeritageClause = function () { + var token0 = this.currentToken(); + return token0.tokenKind === 48 /* ExtendsKeyword */ || token0.tokenKind === 51 /* ImplementsKeyword */; + }; + + ParserImpl.prototype.isNotHeritageClauseTypeName = function () { + if (this.currentToken().tokenKind === 51 /* ImplementsKeyword */ || this.currentToken().tokenKind === 48 /* ExtendsKeyword */) { + return this.isIdentifier(this.peekToken(1)); + } + + return false; + }; + + ParserImpl.prototype.isHeritageClauseTypeName = function () { + if (this.isIdentifier(this.currentToken())) { + return !this.isNotHeritageClauseTypeName(); + } + + return false; + }; + + ParserImpl.prototype.parseHeritageClause = function () { + var extendsOrImplementsKeyword = this.eatAnyToken(); + TypeScript.Debug.assert(extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */ || extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + + var result = this.parseSeparatedSyntaxList(2048 /* HeritageClause_TypeNameList */); + var typeNames = result.list; + extendsOrImplementsKeyword = this.addSkippedTokensAfterToken(extendsOrImplementsKeyword, result.skippedTokens); + + return this.factory.heritageClause(extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */ ? 230 /* ExtendsHeritageClause */ : 231 /* ImplementsHeritageClause */, extendsOrImplementsKeyword, typeNames); + }; + + ParserImpl.prototype.isStatement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isStatement()) { + return true; + } + + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + switch (currentTokenKind) { + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + var token1 = this.peekToken(1); + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token1)) { + return false; + } + + break; + + case 28 /* IfKeyword */: + case 70 /* OpenBraceToken */: + case 33 /* ReturnKeyword */: + case 34 /* SwitchKeyword */: + case 36 /* ThrowKeyword */: + case 15 /* BreakKeyword */: + case 18 /* ContinueKeyword */: + case 26 /* ForKeyword */: + case 42 /* WhileKeyword */: + case 43 /* WithKeyword */: + case 22 /* DoKeyword */: + case 38 /* TryKeyword */: + case 19 /* DebuggerKeyword */: + return true; + } + + if (this.isInterfaceDeclaration(0) || this.isClassDeclaration(0) || this.isEnumDeclaration(0) || this.isModuleDeclaration(0)) { + return false; + } + + return this.isLabeledStatement(currentToken) || this.isVariableStatement() || this.isFunctionDeclaration() || this.isEmptyStatement(currentToken, inErrorRecovery) || this.isExpressionStatement(currentToken); + }; + + ParserImpl.prototype.parseStatement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isStatement()) { + return this.eatNode(); + } + + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + + switch (currentTokenKind) { + case 28 /* IfKeyword */: + return this.parseIfStatement(); + case 70 /* OpenBraceToken */: + return this.parseBlock(false, false); + case 33 /* ReturnKeyword */: + return this.parseReturnStatement(); + case 34 /* SwitchKeyword */: + return this.parseSwitchStatement(); + case 36 /* ThrowKeyword */: + return this.parseThrowStatement(); + case 15 /* BreakKeyword */: + return this.parseBreakStatement(); + case 18 /* ContinueKeyword */: + return this.parseContinueStatement(); + case 26 /* ForKeyword */: + return this.parseForOrForInStatement(); + case 42 /* WhileKeyword */: + return this.parseWhileStatement(); + case 43 /* WithKeyword */: + return this.parseWithStatement(); + case 22 /* DoKeyword */: + return this.parseDoStatement(); + case 38 /* TryKeyword */: + return this.parseTryStatement(); + case 19 /* DebuggerKeyword */: + return this.parseDebuggerStatement(); + } + + if (this.isVariableStatement()) { + return this.parseVariableStatement(); + } else if (this.isLabeledStatement(currentToken)) { + return this.parseLabeledStatement(); + } else if (this.isFunctionDeclaration()) { + return this.parseFunctionDeclaration(); + } else if (this.isEmptyStatement(currentToken, inErrorRecovery)) { + return this.parseEmptyStatement(); + } else { + return this.parseExpressionStatement(); + } + }; + + ParserImpl.prototype.parseDebuggerStatement = function () { + var debuggerKeyword = this.eatKeyword(19 /* DebuggerKeyword */); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.debuggerStatement(debuggerKeyword, semicolonToken); + }; + + ParserImpl.prototype.parseDoStatement = function () { + var doKeyword = this.eatKeyword(22 /* DoKeyword */); + var statement = this.parseStatement(false); + var whileKeyword = this.eatKeyword(42 /* WhileKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(true); + + return this.factory.doStatement(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); + }; + + ParserImpl.prototype.isLabeledStatement = function (currentToken) { + return this.isIdentifier(currentToken) && this.peekToken(1).tokenKind === 106 /* ColonToken */; + }; + + ParserImpl.prototype.parseLabeledStatement = function () { + var identifier = this.eatIdentifierToken(); + var colonToken = this.eatToken(106 /* ColonToken */); + var statement = this.parseStatement(false); + + return this.factory.labeledStatement(identifier, colonToken, statement); + }; + + ParserImpl.prototype.parseTryStatement = function () { + var tryKeyword = this.eatKeyword(38 /* TryKeyword */); + + var savedListParsingState = this.listParsingState; + this.listParsingState |= 64 /* TryBlock_Statements */; + var block = this.parseBlock(false, false); + this.listParsingState = savedListParsingState; + + var catchClause = null; + if (this.isCatchClause()) { + catchClause = this.parseCatchClause(); + } + + var finallyClause = null; + if (catchClause === null || this.isFinallyClause()) { + finallyClause = this.parseFinallyClause(); + } + + return this.factory.tryStatement(tryKeyword, block, catchClause, finallyClause); + }; + + ParserImpl.prototype.isCatchClause = function () { + return this.currentToken().tokenKind === 17 /* CatchKeyword */; + }; + + ParserImpl.prototype.parseCatchClause = function () { + var catchKeyword = this.eatKeyword(17 /* CatchKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var identifier = this.eatIdentifierToken(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + var savedListParsingState = this.listParsingState; + this.listParsingState |= 128 /* CatchBlock_Statements */; + var block = this.parseBlock(false, false); + this.listParsingState = savedListParsingState; + + return this.factory.catchClause(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block); + }; + + ParserImpl.prototype.isFinallyClause = function () { + return this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.parseFinallyClause = function () { + var finallyKeyword = this.eatKeyword(25 /* FinallyKeyword */); + var block = this.parseBlock(false, false); + + return this.factory.finallyClause(finallyKeyword, block); + }; + + ParserImpl.prototype.parseWithStatement = function () { + var withKeyword = this.eatKeyword(43 /* WithKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.withStatement(withKeyword, openParenToken, condition, closeParenToken, statement); + }; + + ParserImpl.prototype.parseWhileStatement = function () { + var whileKeyword = this.eatKeyword(42 /* WhileKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.whileStatement(whileKeyword, openParenToken, condition, closeParenToken, statement); + }; + + ParserImpl.prototype.isEmptyStatement = function (currentToken, inErrorRecovery) { + if (inErrorRecovery) { + return false; + } + + return currentToken.tokenKind === 78 /* SemicolonToken */; + }; + + ParserImpl.prototype.parseEmptyStatement = function () { + var semicolonToken = this.eatToken(78 /* SemicolonToken */); + return this.factory.emptyStatement(semicolonToken); + }; + + ParserImpl.prototype.parseForOrForInStatement = function () { + var forKeyword = this.eatKeyword(26 /* ForKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + + var currentToken = this.currentToken(); + if (currentToken.tokenKind === 40 /* VarKeyword */) { + return this.parseForOrForInStatementWithVariableDeclaration(forKeyword, openParenToken); + } else if (currentToken.tokenKind === 78 /* SemicolonToken */) { + return this.parseForStatementWithNoVariableDeclarationOrInitializer(forKeyword, openParenToken); + } else { + return this.parseForOrForInStatementWithInitializer(forKeyword, openParenToken); + } + }; + + ParserImpl.prototype.parseForOrForInStatementWithVariableDeclaration = function (forKeyword, openParenToken) { + var variableDeclaration = this.parseVariableDeclaration(false); + + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return this.parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null); + } + + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null); + }; + + ParserImpl.prototype.parseForInStatementWithVariableDeclarationOrInitializer = function (forKeyword, openParenToken, variableDeclaration, initializer) { + var inKeyword = this.eatKeyword(29 /* InKeyword */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.forInStatement(forKeyword, openParenToken, variableDeclaration, initializer, inKeyword, expression, closeParenToken, statement); + }; + + ParserImpl.prototype.parseForOrForInStatementWithInitializer = function (forKeyword, openParenToken) { + var initializer = this.parseExpression(false); + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return this.parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + } else { + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + } + }; + + ParserImpl.prototype.parseForStatementWithNoVariableDeclarationOrInitializer = function (forKeyword, openParenToken) { + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, null); + }; + + ParserImpl.prototype.parseForStatementWithVariableDeclarationOrInitializer = function (forKeyword, openParenToken, variableDeclaration, initializer) { + var firstSemicolonToken = this.eatToken(78 /* SemicolonToken */); + + var condition = null; + if (this.currentToken().tokenKind !== 78 /* SemicolonToken */ && this.currentToken().tokenKind !== 73 /* CloseParenToken */ && this.currentToken().tokenKind !== 10 /* EndOfFileToken */) { + condition = this.parseExpression(true); + } + + var secondSemicolonToken = this.eatToken(78 /* SemicolonToken */); + + var incrementor = null; + if (this.currentToken().tokenKind !== 73 /* CloseParenToken */ && this.currentToken().tokenKind !== 10 /* EndOfFileToken */) { + incrementor = this.parseExpression(true); + } + + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.forStatement(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement); + }; + + ParserImpl.prototype.parseBreakStatement = function () { + var breakKeyword = this.eatKeyword(15 /* BreakKeyword */); + + var identifier = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + } + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + return this.factory.breakStatement(breakKeyword, identifier, semicolon); + }; + + ParserImpl.prototype.parseContinueStatement = function () { + var continueKeyword = this.eatKeyword(18 /* ContinueKeyword */); + + var identifier = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + } + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + return this.factory.continueStatement(continueKeyword, identifier, semicolon); + }; + + ParserImpl.prototype.parseSwitchStatement = function () { + var switchKeyword = this.eatKeyword(34 /* SwitchKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var switchClauses = TypeScript.Syntax.emptyList; + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(8 /* SwitchStatement_SwitchClauses */); + switchClauses = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + return this.factory.switchStatement(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken); + }; + + ParserImpl.prototype.isCaseSwitchClause = function () { + return this.currentToken().tokenKind === 16 /* CaseKeyword */; + }; + + ParserImpl.prototype.isDefaultSwitchClause = function () { + return this.currentToken().tokenKind === 20 /* DefaultKeyword */; + }; + + ParserImpl.prototype.isSwitchClause = function () { + if (this.currentNode() !== null && this.currentNode().isSwitchClause()) { + return true; + } + + return this.isCaseSwitchClause() || this.isDefaultSwitchClause(); + }; + + ParserImpl.prototype.parseSwitchClause = function () { + if (this.currentNode() !== null && this.currentNode().isSwitchClause()) { + return this.eatNode(); + } + + if (this.isCaseSwitchClause()) { + return this.parseCaseSwitchClause(); + } else if (this.isDefaultSwitchClause()) { + return this.parseDefaultSwitchClause(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseCaseSwitchClause = function () { + var caseKeyword = this.eatKeyword(16 /* CaseKeyword */); + var expression = this.parseExpression(true); + var colonToken = this.eatToken(106 /* ColonToken */); + var statements = TypeScript.Syntax.emptyList; + + if (colonToken.fullWidth() > 0) { + var result = this.parseSyntaxList(16 /* SwitchClause_Statements */); + statements = result.list; + colonToken = this.addSkippedTokensAfterToken(colonToken, result.skippedTokens); + } + + return this.factory.caseSwitchClause(caseKeyword, expression, colonToken, statements); + }; + + ParserImpl.prototype.parseDefaultSwitchClause = function () { + var defaultKeyword = this.eatKeyword(20 /* DefaultKeyword */); + var colonToken = this.eatToken(106 /* ColonToken */); + var statements = TypeScript.Syntax.emptyList; + + if (colonToken.fullWidth() > 0) { + var result = this.parseSyntaxList(16 /* SwitchClause_Statements */); + statements = result.list; + colonToken = this.addSkippedTokensAfterToken(colonToken, result.skippedTokens); + } + + return this.factory.defaultSwitchClause(defaultKeyword, colonToken, statements); + }; + + ParserImpl.prototype.parseThrowStatement = function () { + var throwKeyword = this.eatKeyword(36 /* ThrowKeyword */); + + var expression = null; + if (this.canEatExplicitOrAutomaticSemicolon(false)) { + var token = this.createMissingToken(11 /* IdentifierName */, null); + expression = token; + } else { + expression = this.parseExpression(true); + } + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.throwStatement(throwKeyword, expression, semicolonToken); + }; + + ParserImpl.prototype.parseReturnStatement = function () { + var returnKeyword = this.eatKeyword(33 /* ReturnKeyword */); + + var expression = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + expression = this.parseExpression(true); + } + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.returnStatement(returnKeyword, expression, semicolonToken); + }; + + ParserImpl.prototype.isExpressionStatement = function (currentToken) { + var kind = currentToken.tokenKind; + if (kind === 70 /* OpenBraceToken */ || kind === 27 /* FunctionKeyword */) { + return false; + } + + return this.isExpression(currentToken); + }; + + ParserImpl.prototype.isAssignmentOrOmittedExpression = function () { + var currentToken = this.currentToken(); + if (currentToken.tokenKind === 79 /* CommaToken */) { + return true; + } + + return this.isExpression(currentToken); + }; + + ParserImpl.prototype.parseAssignmentOrOmittedExpression = function () { + if (this.currentToken().tokenKind === 79 /* CommaToken */) { + return this.factory.omittedExpression(); + } + + return this.parseAssignmentExpression(true); + }; + + ParserImpl.prototype.isExpression = function (currentToken) { + switch (currentToken.tokenKind) { + case 13 /* NumericLiteral */: + case 14 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + + case 74 /* OpenBracketToken */: + + case 72 /* OpenParenToken */: + + case 80 /* LessThanToken */: + + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + case 89 /* PlusToken */: + case 90 /* MinusToken */: + case 102 /* TildeToken */: + case 101 /* ExclamationToken */: + + case 70 /* OpenBraceToken */: + + case 85 /* EqualsGreaterThanToken */: + + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + + case 50 /* SuperKeyword */: + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + + case 31 /* NewKeyword */: + + case 21 /* DeleteKeyword */: + case 41 /* VoidKeyword */: + case 39 /* TypeOfKeyword */: + + case 27 /* FunctionKeyword */: + return true; + } + + return this.isIdentifier(currentToken); + }; + + ParserImpl.prototype.parseExpressionStatement = function () { + var expression = this.parseExpression(true); + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.expressionStatement(expression, semicolon); + }; + + ParserImpl.prototype.parseIfStatement = function () { + var ifKeyword = this.eatKeyword(28 /* IfKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + var elseClause = null; + if (this.isElseClause()) { + elseClause = this.parseElseClause(); + } + + return this.factory.ifStatement(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause); + }; + + ParserImpl.prototype.isElseClause = function () { + return this.currentToken().tokenKind === 23 /* ElseKeyword */; + }; + + ParserImpl.prototype.parseElseClause = function () { + var elseKeyword = this.eatKeyword(23 /* ElseKeyword */); + var statement = this.parseStatement(false); + + return this.factory.elseClause(elseKeyword, statement); + }; + + ParserImpl.prototype.isVariableStatement = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 40 /* VarKeyword */; + }; + + ParserImpl.prototype.parseVariableStatement = function () { + var modifiers = this.parseModifiers(); + var variableDeclaration = this.parseVariableDeclaration(true); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.variableStatement(modifiers, variableDeclaration, semicolonToken); + }; + + ParserImpl.prototype.parseVariableDeclaration = function (allowIn) { + var varKeyword = this.eatKeyword(40 /* VarKeyword */); + + var listParsingState = allowIn ? 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */ : 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */; + + var result = this.parseSeparatedSyntaxList(listParsingState); + var variableDeclarators = result.list; + varKeyword = this.addSkippedTokensAfterToken(varKeyword, result.skippedTokens); + + return this.factory.variableDeclaration(varKeyword, variableDeclarators); + }; + + ParserImpl.prototype.isVariableDeclarator = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 225 /* VariableDeclarator */) { + return true; + } + + return this.isIdentifier(this.currentToken()); + }; + + ParserImpl.prototype.canReuseVariableDeclaratorNode = function (node) { + if (node === null || node.kind() !== 225 /* VariableDeclarator */) { + return false; + } + + var variableDeclarator = node; + return variableDeclarator.equalsValueClause === null; + }; + + ParserImpl.prototype.parseVariableDeclarator = function (allowIn, allowPropertyName) { + if (this.canReuseVariableDeclaratorNode(this.currentNode())) { + return this.eatNode(); + } + + var propertyName = allowPropertyName ? this.eatPropertyName() : this.eatIdentifierToken(); + var equalsValueClause = null; + var typeAnnotation = null; + + if (propertyName.width() > 0) { + typeAnnotation = this.parseOptionalTypeAnnotation(false); + + if (this.isEqualsValueClause(false)) { + equalsValueClause = this.parseEqualsValueClause(allowIn); + } + } + + return this.factory.variableDeclarator(propertyName, typeAnnotation, equalsValueClause); + }; + + ParserImpl.prototype.isColonValueClause = function () { + return this.currentToken().tokenKind === 106 /* ColonToken */; + }; + + ParserImpl.prototype.isEqualsValueClause = function (inParameter) { + var token0 = this.currentToken(); + if (token0.tokenKind === 107 /* EqualsToken */) { + return true; + } + + if (!this.previousToken().hasTrailingNewLine()) { + if (token0.tokenKind === 85 /* EqualsGreaterThanToken */) { + return false; + } + + if (token0.tokenKind === 70 /* OpenBraceToken */ && inParameter) { + return false; + } + + return this.isExpression(token0); + } + + return false; + }; + + ParserImpl.prototype.parseEqualsValueClause = function (allowIn) { + var equalsToken = this.eatToken(107 /* EqualsToken */); + var value = this.parseAssignmentExpression(allowIn); + + return this.factory.equalsValueClause(equalsToken, value); + }; + + ParserImpl.prototype.parseExpression = function (allowIn) { + return this.parseSubExpression(0, allowIn); + }; + + ParserImpl.prototype.parseAssignmentExpression = function (allowIn) { + return this.parseSubExpression(2 /* AssignmentExpressionPrecedence */, allowIn); + }; + + ParserImpl.prototype.parseUnaryExpressionOrLower = function () { + var currentTokenKind = this.currentToken().tokenKind; + if (TypeScript.SyntaxFacts.isPrefixUnaryExpressionOperatorToken(currentTokenKind)) { + var operatorKind = TypeScript.SyntaxFacts.getPrefixUnaryExpressionFromOperatorToken(currentTokenKind); + + var operatorToken = this.eatAnyToken(); + + var operand = this.parseUnaryExpressionOrLower(); + return this.factory.prefixUnaryExpression(operatorKind, operatorToken, operand); + } else if (currentTokenKind === 39 /* TypeOfKeyword */) { + return this.parseTypeOfExpression(); + } else if (currentTokenKind === 41 /* VoidKeyword */) { + return this.parseVoidExpression(); + } else if (currentTokenKind === 21 /* DeleteKeyword */) { + return this.parseDeleteExpression(); + } else if (currentTokenKind === 80 /* LessThanToken */) { + return this.parseCastExpression(); + } else { + return this.parsePostfixExpressionOrLower(); + } + }; + + ParserImpl.prototype.parseSubExpression = function (precedence, allowIn) { + if (precedence <= 2 /* AssignmentExpressionPrecedence */) { + if (this.isSimpleArrowFunctionExpression()) { + return this.parseSimpleArrowFunctionExpression(); + } + + var parethesizedArrowFunction = this.tryParseParenthesizedArrowFunctionExpression(); + if (parethesizedArrowFunction !== null) { + return parethesizedArrowFunction; + } + } + + var leftOperand = this.parseUnaryExpressionOrLower(); + return this.parseBinaryOrConditionalExpressions(precedence, allowIn, leftOperand); + }; + + ParserImpl.prototype.parseBinaryOrConditionalExpressions = function (precedence, allowIn, leftOperand) { + while (true) { + var token0 = this.currentToken(); + var token0Kind = token0.tokenKind; + + if (TypeScript.SyntaxFacts.isBinaryExpressionOperatorToken(token0Kind)) { + if (token0Kind === 29 /* InKeyword */ && !allowIn) { + break; + } + + var mergedToken = this.tryMergeBinaryExpressionTokens(); + var tokenKind = mergedToken === null ? token0Kind : mergedToken.syntaxKind; + + var binaryExpressionKind = TypeScript.SyntaxFacts.getBinaryExpressionFromOperatorToken(tokenKind); + var newPrecedence = ParserImpl.getPrecedence(binaryExpressionKind); + + if (newPrecedence < precedence) { + break; + } + + if (newPrecedence === precedence && !this.isRightAssociative(binaryExpressionKind)) { + break; + } + + var operatorToken = mergedToken === null ? token0 : TypeScript.Syntax.token(mergedToken.syntaxKind).withLeadingTrivia(token0.leadingTrivia()).withTrailingTrivia(this.peekToken(mergedToken.tokenCount - 1).trailingTrivia()); + + var skipCount = mergedToken === null ? 1 : mergedToken.tokenCount; + for (var i = 0; i < skipCount; i++) { + this.eatAnyToken(); + } + + leftOperand = this.factory.binaryExpression(binaryExpressionKind, leftOperand, operatorToken, this.parseSubExpression(newPrecedence, allowIn)); + continue; + } + + if (token0Kind === 105 /* QuestionToken */ && precedence <= 3 /* ConditionalExpressionPrecedence */) { + var questionToken = this.eatToken(105 /* QuestionToken */); + + var whenTrueExpression = this.parseAssignmentExpression(allowIn); + var colon = this.eatToken(106 /* ColonToken */); + + var whenFalseExpression = this.parseAssignmentExpression(allowIn); + leftOperand = this.factory.conditionalExpression(leftOperand, questionToken, whenTrueExpression, colon, whenFalseExpression); + continue; + } + + break; + } + + return leftOperand; + }; + + ParserImpl.prototype.tryMergeBinaryExpressionTokens = function () { + var token0 = this.currentToken(); + + if (token0.tokenKind === 81 /* GreaterThanToken */ && !token0.hasTrailingTrivia()) { + var storage = this.mergeTokensStorage; + storage[0] = 0 /* None */; + storage[1] = 0 /* None */; + storage[2] = 0 /* None */; + + for (var i = 0; i < storage.length; i++) { + var nextToken = this.peekToken(i + 1); + + if (!nextToken.hasLeadingTrivia()) { + storage[i] = nextToken.tokenKind; + } + + if (nextToken.hasTrailingTrivia()) { + break; + } + } + + if (storage[0] === 81 /* GreaterThanToken */) { + if (storage[1] === 81 /* GreaterThanToken */) { + if (storage[2] === 107 /* EqualsToken */) { + return { tokenCount: 4, syntaxKind: 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */ }; + } else { + return { tokenCount: 3, syntaxKind: 97 /* GreaterThanGreaterThanGreaterThanToken */ }; + } + } else if (storage[1] === 107 /* EqualsToken */) { + return { tokenCount: 3, syntaxKind: 113 /* GreaterThanGreaterThanEqualsToken */ }; + } else { + return { tokenCount: 2, syntaxKind: 96 /* GreaterThanGreaterThanToken */ }; + } + } else if (storage[0] === 107 /* EqualsToken */) { + return { tokenCount: 2, syntaxKind: 83 /* GreaterThanEqualsToken */ }; + } + } + + return null; + }; + + ParserImpl.prototype.isRightAssociative = function (expressionKind) { + switch (expressionKind) { + case 174 /* AssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + return true; + default: + return false; + } + }; + + ParserImpl.prototype.parseMemberExpressionOrLower = function (inObjectCreation) { + if (this.currentToken().tokenKind === 31 /* NewKeyword */) { + return this.parseObjectCreationExpression(); + } + + var expression = this.parsePrimaryExpression(); + if (expression === null) { + return this.eatIdentifierToken(); + } + + return this.parseMemberExpressionRest(expression, false, inObjectCreation); + }; + + ParserImpl.prototype.parseCallExpressionOrLower = function () { + var expression; + if (this.currentToken().tokenKind === 50 /* SuperKeyword */) { + expression = this.eatKeyword(50 /* SuperKeyword */); + + var currentTokenKind = this.currentToken().tokenKind; + if (currentTokenKind !== 72 /* OpenParenToken */ && currentTokenKind !== 76 /* DotToken */) { + expression = this.factory.memberAccessExpression(expression, this.eatToken(76 /* DotToken */), this.eatIdentifierNameToken()); + } + } else { + expression = this.parseMemberExpressionOrLower(false); + } + + return this.parseMemberExpressionRest(expression, true, false); + }; + + ParserImpl.prototype.parseMemberExpressionRest = function (expression, allowArguments, inObjectCreation) { + while (true) { + var currentTokenKind = this.currentToken().tokenKind; + + switch (currentTokenKind) { + case 72 /* OpenParenToken */: + if (!allowArguments) { + return expression; + } + + expression = this.factory.invocationExpression(expression, this.parseArgumentList(null)); + continue; + + case 80 /* LessThanToken */: + if (!allowArguments) { + return expression; + } + + var argumentList = this.tryParseArgumentList(); + if (argumentList !== null) { + expression = this.factory.invocationExpression(expression, argumentList); + continue; + } + + break; + + case 74 /* OpenBracketToken */: + expression = this.parseElementAccessExpression(expression, inObjectCreation); + continue; + + case 76 /* DotToken */: + expression = this.factory.memberAccessExpression(expression, this.eatToken(76 /* DotToken */), this.eatIdentifierNameToken()); + continue; + } + + return expression; + } + }; + + ParserImpl.prototype.parseLeftHandSideExpressionOrLower = function () { + if (this.currentToken().tokenKind === 31 /* NewKeyword */) { + return this.parseObjectCreationExpression(); + } else { + return this.parseCallExpressionOrLower(); + } + }; + + ParserImpl.prototype.parsePostfixExpressionOrLower = function () { + var expression = this.parseLeftHandSideExpressionOrLower(); + if (expression === null) { + return this.eatIdentifierToken(); + } + + var currentTokenKind = this.currentToken().tokenKind; + + switch (currentTokenKind) { + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + if (this.previousToken() !== null && this.previousToken().hasTrailingNewLine()) { + break; + } + + return this.factory.postfixUnaryExpression(TypeScript.SyntaxFacts.getPostfixUnaryExpressionFromOperatorToken(currentTokenKind), expression, this.eatAnyToken()); + } + + return expression; + }; + + ParserImpl.prototype.tryParseGenericArgumentList = function () { + var rewindPoint = this.getRewindPoint(); + + var typeArgumentList = this.tryParseTypeArgumentList(true); + var token0 = this.currentToken(); + + var isOpenParen = token0.tokenKind === 72 /* OpenParenToken */; + var isDot = token0.tokenKind === 76 /* DotToken */; + var isOpenParenOrDot = isOpenParen || isDot; + + var argumentList = null; + if (typeArgumentList === null || !isOpenParenOrDot) { + this.rewind(rewindPoint); + this.releaseRewindPoint(rewindPoint); + return null; + } else { + this.releaseRewindPoint(rewindPoint); + + if (isDot) { + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token0.width(), TypeScript.DiagnosticCode.A_parameter_list_must_follow_a_generic_type_argument_list_expected, null); + this.addDiagnostic(diagnostic); + + return this.factory.argumentList(typeArgumentList, TypeScript.Syntax.emptyToken(72 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.emptyToken(73 /* CloseParenToken */)); + } else { + return this.parseArgumentList(typeArgumentList); + } + } + }; + + ParserImpl.prototype.tryParseArgumentList = function () { + if (this.currentToken().tokenKind === 80 /* LessThanToken */) { + return this.tryParseGenericArgumentList(); + } + + if (this.currentToken().tokenKind === 72 /* OpenParenToken */) { + return this.parseArgumentList(null); + } + + return null; + }; + + ParserImpl.prototype.parseArgumentList = function (typeArgumentList) { + var openParenToken = this.eatToken(72 /* OpenParenToken */); + + var _arguments = TypeScript.Syntax.emptySeparatedList; + + if (openParenToken.fullWidth() > 0) { + var result = this.parseSeparatedSyntaxList(16384 /* ArgumentList_AssignmentExpressions */); + _arguments = result.list; + openParenToken = this.addSkippedTokensAfterToken(openParenToken, result.skippedTokens); + } + + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + return this.factory.argumentList(typeArgumentList, openParenToken, _arguments, closeParenToken); + }; + + ParserImpl.prototype.parseElementAccessExpression = function (expression, inObjectCreation) { + var start = this.currentTokenStart(); + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + var argumentExpression; + + if (this.currentToken().tokenKind === 75 /* CloseBracketToken */ && inObjectCreation) { + var end = this.currentTokenStart() + this.currentToken().width(); + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, start, end - start, TypeScript.DiagnosticCode.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead, null); + this.addDiagnostic(diagnostic); + + argumentExpression = TypeScript.Syntax.emptyToken(11 /* IdentifierName */); + } else { + argumentExpression = this.parseExpression(true); + } + + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + + return this.factory.elementAccessExpression(expression, openBracketToken, argumentExpression, closeBracketToken); + }; + + ParserImpl.prototype.parsePrimaryExpression = function () { + var currentToken = this.currentToken(); + + if (this.isIdentifier(currentToken)) { + return this.eatIdentifierToken(); + } + + var currentTokenKind = currentToken.tokenKind; + switch (currentTokenKind) { + case 35 /* ThisKeyword */: + return this.parseThisExpression(); + + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return this.parseLiteralExpression(); + + case 32 /* NullKeyword */: + return this.parseLiteralExpression(); + + case 27 /* FunctionKeyword */: + return this.parseFunctionExpression(); + + case 13 /* NumericLiteral */: + return this.parseLiteralExpression(); + + case 12 /* RegularExpressionLiteral */: + return this.parseLiteralExpression(); + + case 14 /* StringLiteral */: + return this.parseLiteralExpression(); + + case 74 /* OpenBracketToken */: + return this.parseArrayLiteralExpression(); + + case 70 /* OpenBraceToken */: + return this.parseObjectLiteralExpression(); + + case 72 /* OpenParenToken */: + return this.parseParenthesizedExpression(); + + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + var result = this.tryReparseDivideAsRegularExpression(); + if (result !== null) { + return result; + } + break; + } + + return null; + }; + + ParserImpl.prototype.tryReparseDivideAsRegularExpression = function () { + var currentToken = this.currentToken(); + + if (this.previousToken() !== null) { + var previousTokenKind = this.previousToken().tokenKind; + switch (previousTokenKind) { + case 11 /* IdentifierName */: + return null; + + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return null; + + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + case 12 /* RegularExpressionLiteral */: + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + case 75 /* CloseBracketToken */: + return null; + } + } + + currentToken = this.currentTokenAllowingRegularExpression(); + + if (currentToken.tokenKind === 118 /* SlashToken */ || currentToken.tokenKind === 119 /* SlashEqualsToken */) { + return null; + } else if (currentToken.tokenKind === 12 /* RegularExpressionLiteral */) { + return this.parseLiteralExpression(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseTypeOfExpression = function () { + var typeOfKeyword = this.eatKeyword(39 /* TypeOfKeyword */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.typeOfExpression(typeOfKeyword, expression); + }; + + ParserImpl.prototype.parseDeleteExpression = function () { + var deleteKeyword = this.eatKeyword(21 /* DeleteKeyword */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.deleteExpression(deleteKeyword, expression); + }; + + ParserImpl.prototype.parseVoidExpression = function () { + var voidKeyword = this.eatKeyword(41 /* VoidKeyword */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.voidExpression(voidKeyword, expression); + }; + + ParserImpl.prototype.parseFunctionExpression = function () { + var functionKeyword = this.eatKeyword(27 /* FunctionKeyword */); + var identifier = null; + + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + + var callSignature = this.parseCallSignature(false); + var block = this.parseBlock(false, true); + + return this.factory.functionExpression(functionKeyword, identifier, callSignature, block); + }; + + ParserImpl.prototype.parseObjectCreationExpression = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + + var expression = this.parseObjectCreationExpressionOrLower(true); + var argumentList = this.tryParseArgumentList(); + + var result = this.factory.objectCreationExpression(newKeyword, expression, argumentList); + return this.parseMemberExpressionRest(result, true, false); + }; + + ParserImpl.prototype.parseObjectCreationExpressionOrLower = function (inObjectCreation) { + if (this.currentToken().tokenKind === 31 /* NewKeyword */) { + return this.parseObjectCreationExpression(); + } else { + return this.parseMemberExpressionOrLower(inObjectCreation); + } + }; + + ParserImpl.prototype.parseCastExpression = function () { + var lessThanToken = this.eatToken(80 /* LessThanToken */); + var type = this.parseType(); + var greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.castExpression(lessThanToken, type, greaterThanToken, expression); + }; + + ParserImpl.prototype.parseParenthesizedExpression = function () { + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + return this.factory.parenthesizedExpression(openParenToken, expression, closeParenToken); + }; + + ParserImpl.prototype.tryParseParenthesizedArrowFunctionExpression = function () { + var tokenKind = this.currentToken().tokenKind; + if (tokenKind !== 72 /* OpenParenToken */ && tokenKind !== 80 /* LessThanToken */) { + return null; + } + + if (this.isDefinitelyArrowFunctionExpression()) { + return this.parseParenthesizedArrowFunctionExpression(false); + } + + if (!this.isPossiblyArrowFunctionExpression()) { + return null; + } + + var rewindPoint = this.getRewindPoint(); + + var arrowFunction = this.parseParenthesizedArrowFunctionExpression(true); + if (arrowFunction === null) { + this.rewind(rewindPoint); + } + + this.releaseRewindPoint(rewindPoint); + return arrowFunction; + }; + + ParserImpl.prototype.parseParenthesizedArrowFunctionExpression = function (requireArrow) { + var currentToken = this.currentToken(); + + var callSignature = this.parseCallSignature(true); + + if (requireArrow && this.currentToken().tokenKind !== 85 /* EqualsGreaterThanToken */) { + return null; + } + + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + + var block = this.tryParseArrowFunctionBlock(); + var expression = null; + if (block === null) { + expression = this.parseAssignmentExpression(true); + } + + return this.factory.parenthesizedArrowFunctionExpression(callSignature, equalsGreaterThanToken, block, expression); + }; + + ParserImpl.prototype.tryParseArrowFunctionBlock = function () { + if (this.isBlock()) { + return this.parseBlock(false, false); + } else { + if (this.isStatement(false) && !this.isExpressionStatement(this.currentToken()) && !this.isFunctionDeclaration()) { + return this.parseBlock(true, false); + } else { + return null; + } + } + }; + + ParserImpl.prototype.isSimpleArrowFunctionExpression = function () { + if (this.currentToken().tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + + return this.isIdentifier(this.currentToken()) && this.peekToken(1).tokenKind === 85 /* EqualsGreaterThanToken */; + }; + + ParserImpl.prototype.parseSimpleArrowFunctionExpression = function () { + var identifier = this.eatIdentifierToken(); + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + + var block = this.tryParseArrowFunctionBlock(); + var expression = null; + if (block === null) { + expression = this.parseAssignmentExpression(true); + } + + return this.factory.simpleArrowFunctionExpression(identifier, equalsGreaterThanToken, block, expression); + }; + + ParserImpl.prototype.isBlock = function () { + return this.currentToken().tokenKind === 70 /* OpenBraceToken */; + }; + + ParserImpl.prototype.isDefinitelyArrowFunctionExpression = function () { + var token0 = this.currentToken(); + if (token0.tokenKind !== 72 /* OpenParenToken */) { + return false; + } + + var token1 = this.peekToken(1); + var token2; + + if (token1.tokenKind === 73 /* CloseParenToken */) { + token2 = this.peekToken(2); + return token2.tokenKind === 106 /* ColonToken */ || token2.tokenKind === 85 /* EqualsGreaterThanToken */ || token2.tokenKind === 70 /* OpenBraceToken */; + } + + if (token1.tokenKind === 77 /* DotDotDotToken */) { + return true; + } + + token2 = this.peekToken(2); + if (token1.tokenKind === 57 /* PublicKeyword */ || token1.tokenKind === 55 /* PrivateKeyword */) { + if (this.isIdentifier(token2)) { + return true; + } + } + + if (!this.isIdentifier(token1)) { + return false; + } + + if (token2.tokenKind === 106 /* ColonToken */) { + return true; + } + + var token3 = this.peekToken(3); + if (token2.tokenKind === 105 /* QuestionToken */) { + if (token3.tokenKind === 106 /* ColonToken */ || token3.tokenKind === 73 /* CloseParenToken */ || token3.tokenKind === 79 /* CommaToken */) { + return true; + } + } + + if (token2.tokenKind === 73 /* CloseParenToken */) { + if (token3.tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.isPossiblyArrowFunctionExpression = function () { + var token0 = this.currentToken(); + if (token0.tokenKind !== 72 /* OpenParenToken */) { + return true; + } + + var token1 = this.peekToken(1); + + if (!this.isIdentifier(token1)) { + return false; + } + + var token2 = this.peekToken(2); + if (token2.tokenKind === 107 /* EqualsToken */) { + return true; + } + + if (token2.tokenKind === 79 /* CommaToken */) { + return true; + } + + if (token2.tokenKind === 73 /* CloseParenToken */) { + var token3 = this.peekToken(3); + if (token3.tokenKind === 106 /* ColonToken */) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.parseObjectLiteralExpression = function () { + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var result = this.parseSeparatedSyntaxList(32768 /* ObjectLiteralExpression_PropertyAssignments */); + var propertyAssignments = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.objectLiteralExpression(openBraceToken, propertyAssignments, closeBraceToken); + }; + + ParserImpl.prototype.parsePropertyAssignment = function (inErrorRecovery) { + if (this.isAccessor(inErrorRecovery)) { + return this.parseAccessor(true); + } else if (this.isFunctionPropertyAssignment(inErrorRecovery)) { + return this.parseFunctionPropertyAssignment(); + } else if (this.isSimplePropertyAssignment(inErrorRecovery)) { + return this.parseSimplePropertyAssignment(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isPropertyAssignment = function (inErrorRecovery) { + return this.isAccessor(inErrorRecovery) || this.isFunctionPropertyAssignment(inErrorRecovery) || this.isSimplePropertyAssignment(inErrorRecovery); + }; + + ParserImpl.prototype.eatPropertyName = function () { + return TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(this.currentToken()) ? this.eatIdentifierNameToken() : this.eatAnyToken(); + }; + + ParserImpl.prototype.isFunctionPropertyAssignment = function (inErrorRecovery) { + return this.isPropertyName(this.currentToken(), inErrorRecovery) && this.isCallSignature(1); + }; + + ParserImpl.prototype.parseFunctionPropertyAssignment = function () { + var propertyName = this.eatPropertyName(); + var callSignature = this.parseCallSignature(false); + var block = this.parseBlock(false, true); + + return this.factory.functionPropertyAssignment(propertyName, callSignature, block); + }; + + ParserImpl.prototype.isSimplePropertyAssignment = function (inErrorRecovery) { + return this.isPropertyName(this.currentToken(), inErrorRecovery); + }; + + ParserImpl.prototype.parseSimplePropertyAssignment = function () { + var propertyName = this.eatPropertyName(); + var colonToken = this.eatToken(106 /* ColonToken */); + var expression = this.parseAssignmentExpression(true); + + return this.factory.simplePropertyAssignment(propertyName, colonToken, expression); + }; + + ParserImpl.prototype.isPropertyName = function (token, inErrorRecovery) { + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) { + if (inErrorRecovery) { + return this.isIdentifier(token); + } else { + return true; + } + } + + switch (token.tokenKind) { + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.parseArrayLiteralExpression = function () { + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + + var result = this.parseSeparatedSyntaxList(65536 /* ArrayLiteralExpression_AssignmentExpressions */); + var expressions = result.list; + openBracketToken = this.addSkippedTokensAfterToken(openBracketToken, result.skippedTokens); + + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + + return this.factory.arrayLiteralExpression(openBracketToken, expressions, closeBracketToken); + }; + + ParserImpl.prototype.parseLiteralExpression = function () { + return this.eatAnyToken(); + }; + + ParserImpl.prototype.parseThisExpression = function () { + return this.eatKeyword(35 /* ThisKeyword */); + }; + + ParserImpl.prototype.parseBlock = function (parseBlockEvenWithNoOpenBrace, checkForStrictMode) { + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var statements = TypeScript.Syntax.emptyList; + + if (parseBlockEvenWithNoOpenBrace || openBraceToken.width() > 0) { + var savedIsInStrictMode = this.isInStrictMode; + + var processItems = checkForStrictMode ? ParserImpl.updateStrictModeState : null; + var result = this.parseSyntaxList(32 /* Block_Statements */, processItems); + statements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + + this.setStrictMode(savedIsInStrictMode); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.block(openBraceToken, statements, closeBraceToken); + }; + + ParserImpl.prototype.parseCallSignature = function (requireCompleteTypeParameterList) { + var typeParameterList = this.parseOptionalTypeParameterList(requireCompleteTypeParameterList); + var parameterList = this.parseParameterList(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.callSignature(typeParameterList, parameterList, typeAnnotation); + }; + + ParserImpl.prototype.parseOptionalTypeParameterList = function (requireCompleteTypeParameterList) { + if (this.currentToken().tokenKind !== 80 /* LessThanToken */) { + return null; + } + + var rewindPoint = this.getRewindPoint(); + + var lessThanToken = this.eatToken(80 /* LessThanToken */); + + var result = this.parseSeparatedSyntaxList(524288 /* TypeParameterList_TypeParameters */); + var typeParameters = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + var greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + + if (requireCompleteTypeParameterList && greaterThanToken.fullWidth() === 0) { + this.rewind(rewindPoint); + this.releaseRewindPoint(rewindPoint); + return null; + } else { + this.releaseRewindPoint(rewindPoint); + var typeParameterList = this.factory.typeParameterList(lessThanToken, typeParameters, greaterThanToken); + + return typeParameterList; + } + }; + + ParserImpl.prototype.isTypeParameter = function () { + return this.isIdentifier(this.currentToken()); + }; + + ParserImpl.prototype.parseTypeParameter = function () { + var identifier = this.eatIdentifierToken(); + var constraint = this.parseOptionalConstraint(); + + return this.factory.typeParameter(identifier, constraint); + }; + + ParserImpl.prototype.parseOptionalConstraint = function () { + if (this.currentToken().kind() !== 48 /* ExtendsKeyword */) { + return null; + } + + var extendsKeyword = this.eatKeyword(48 /* ExtendsKeyword */); + var type = this.parseType(); + + return this.factory.constraint(extendsKeyword, type); + }; + + ParserImpl.prototype.parseParameterList = function () { + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var parameters = TypeScript.Syntax.emptySeparatedList; + + if (openParenToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(131072 /* ParameterList_Parameters */); + parameters = result.list; + openParenToken = this.addSkippedTokensAfterToken(openParenToken, result.skippedTokens); + } + + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + return this.factory.parameterList(openParenToken, parameters, closeParenToken); + }; + + ParserImpl.prototype.isTypeAnnotation = function () { + return this.currentToken().tokenKind === 106 /* ColonToken */; + }; + + ParserImpl.prototype.parseOptionalTypeAnnotation = function (allowStringLiteral) { + return this.isTypeAnnotation() ? this.parseTypeAnnotation(allowStringLiteral) : null; + }; + + ParserImpl.prototype.parseTypeAnnotation = function (allowStringLiteral) { + var colonToken = this.eatToken(106 /* ColonToken */); + var type = allowStringLiteral && this.currentToken().tokenKind === 14 /* StringLiteral */ ? this.eatToken(14 /* StringLiteral */) : this.parseType(); + + return this.factory.typeAnnotation(colonToken, type); + }; + + ParserImpl.prototype.isType = function () { + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + + switch (currentTokenKind) { + case 39 /* TypeOfKeyword */: + + case 60 /* AnyKeyword */: + case 67 /* NumberKeyword */: + case 61 /* BooleanKeyword */: + case 69 /* StringKeyword */: + case 41 /* VoidKeyword */: + + case 70 /* OpenBraceToken */: + + case 72 /* OpenParenToken */: + case 80 /* LessThanToken */: + + case 31 /* NewKeyword */: + return true; + } + + return this.isIdentifier(currentToken); + }; + + ParserImpl.prototype.parseType = function () { + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + + var type = this.parseNonArrayType(currentToken); + + while (this.currentToken().tokenKind === 74 /* OpenBracketToken */) { + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + + type = this.factory.arrayType(type, openBracketToken, closeBracketToken); + } + + return type; + }; + + ParserImpl.prototype.isTypeQuery = function () { + return this.currentToken().tokenKind === 39 /* TypeOfKeyword */; + }; + + ParserImpl.prototype.parseTypeQuery = function () { + var typeOfKeyword = this.eatToken(39 /* TypeOfKeyword */); + var name = this.parseName(); + + return this.factory.typeQuery(typeOfKeyword, name); + }; + + ParserImpl.prototype.parseNonArrayType = function (currentToken) { + var currentTokenKind = currentToken.tokenKind; + switch (currentTokenKind) { + case 60 /* AnyKeyword */: + case 67 /* NumberKeyword */: + case 61 /* BooleanKeyword */: + case 69 /* StringKeyword */: + case 41 /* VoidKeyword */: + return this.eatAnyToken(); + + case 70 /* OpenBraceToken */: + return this.parseObjectType(); + + case 72 /* OpenParenToken */: + case 80 /* LessThanToken */: + return this.parseFunctionType(); + + case 31 /* NewKeyword */: + return this.parseConstructorType(); + + case 39 /* TypeOfKeyword */: + return this.parseTypeQuery(); + } + + return this.parseNameOrGenericType(); + }; + + ParserImpl.prototype.parseNameOrGenericType = function () { + var name = this.parseName(); + var typeArgumentList = this.tryParseTypeArgumentList(false); + + return typeArgumentList === null ? name : this.factory.genericType(name, typeArgumentList); + }; + + ParserImpl.prototype.parseFunctionType = function () { + var typeParameterList = this.parseOptionalTypeParameterList(false); + var parameterList = this.parseParameterList(); + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + var returnType = this.parseType(); + + return this.factory.functionType(typeParameterList, parameterList, equalsGreaterThanToken, returnType); + }; + + ParserImpl.prototype.parseConstructorType = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var parameterList = this.parseParameterList(); + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + var type = this.parseType(); + + return this.factory.constructorType(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type); + }; + + ParserImpl.prototype.isParameter = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 242 /* Parameter */) { + return true; + } + + var token = this.currentToken(); + var tokenKind = token.tokenKind; + if (tokenKind === 77 /* DotDotDotToken */) { + return true; + } + + if (ParserImpl.isModifier(token) && !this.isModifierUsedAsParameterIdentifier(token)) { + return true; + } + + return this.isIdentifier(token); + }; + + ParserImpl.prototype.isModifierUsedAsParameterIdentifier = function (token) { + if (this.isIdentifier(token)) { + var nextTokenKind = this.peekToken(1).tokenKind; + switch (nextTokenKind) { + case 73 /* CloseParenToken */: + case 106 /* ColonToken */: + case 107 /* EqualsToken */: + case 79 /* CommaToken */: + case 105 /* QuestionToken */: + return true; + } + } + + return false; + }; + + ParserImpl.prototype.parseParameter = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 242 /* Parameter */) { + return this.eatNode(); + } + + var dotDotDotToken = this.tryEatToken(77 /* DotDotDotToken */); + + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (ParserImpl.isModifier(currentToken) && !this.isModifierUsedAsParameterIdentifier(currentToken)) { + modifierArray.push(this.eatAnyToken()); + continue; + } + + break; + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var identifier = this.eatIdentifierToken(); + var questionToken = this.tryEatToken(105 /* QuestionToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(true); + + var equalsValueClause = null; + if (this.isEqualsValueClause(true)) { + equalsValueClause = this.parseEqualsValueClause(true); + } + + return this.factory.parameter(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause); + }; + + ParserImpl.prototype.parseSyntaxList = function (currentListType, processItems) { + if (typeof processItems === "undefined") { processItems = null; } + var savedListParsingState = this.listParsingState; + this.listParsingState |= currentListType; + + var result = this.parseSyntaxListWorker(currentListType, processItems); + + this.listParsingState = savedListParsingState; + + return result; + }; + + ParserImpl.prototype.parseSeparatedSyntaxList = function (currentListType) { + var savedListParsingState = this.listParsingState; + this.listParsingState |= currentListType; + + var result = this.parseSeparatedSyntaxListWorker(currentListType); + + this.listParsingState = savedListParsingState; + + return result; + }; + + ParserImpl.prototype.abortParsingListOrMoveToNextToken = function (currentListType, items, skippedTokens) { + this.reportUnexpectedTokenDiagnostic(currentListType); + + for (var state = 524288 /* LastListParsingState */; state >= 1 /* FirstListParsingState */; state >>= 1) { + if ((this.listParsingState & state) !== 0) { + if (this.isExpectedListTerminator(state) || this.isExpectedListItem(state, true)) { + return true; + } + } + } + + var skippedToken = this.currentToken(); + + this.moveToNextToken(); + + this.addSkippedTokenToList(items, skippedTokens, skippedToken); + + return false; + }; + + ParserImpl.prototype.addSkippedTokenToList = function (items, skippedTokens, skippedToken) { + for (var i = items.length - 1; i >= 0; i--) { + var item = items[i]; + var lastToken = item.lastToken(); + if (lastToken.fullWidth() > 0) { + items[i] = this.addSkippedTokenAfterNodeOrToken(item, skippedToken); + return; + } + } + + skippedTokens.push(skippedToken); + }; + + ParserImpl.prototype.tryParseExpectedListItem = function (currentListType, inErrorRecovery, items, processItems) { + if (this.isExpectedListItem(currentListType, inErrorRecovery)) { + var item = this.parseExpectedListItem(currentListType, inErrorRecovery); + + items.push(item); + + if (processItems !== null) { + processItems(this, items); + } + } + }; + + ParserImpl.prototype.listIsTerminated = function (currentListType) { + return this.isExpectedListTerminator(currentListType) || this.currentToken().tokenKind === 10 /* EndOfFileToken */; + }; + + ParserImpl.prototype.getArray = function () { + if (this.arrayPool.length > 0) { + return this.arrayPool.pop(); + } + + return []; + }; + + ParserImpl.prototype.returnZeroOrOneLengthArray = function (array) { + if (array.length <= 1) { + this.returnArray(array); + } + }; + + ParserImpl.prototype.returnArray = function (array) { + array.length = 0; + this.arrayPool.push(array); + }; + + ParserImpl.prototype.parseSyntaxListWorker = function (currentListType, processItems) { + var items = this.getArray(); + var skippedTokens = this.getArray(); + + while (true) { + var oldItemsCount = items.length; + this.tryParseExpectedListItem(currentListType, false, items, processItems); + + var newItemsCount = items.length; + if (newItemsCount === oldItemsCount) { + if (this.listIsTerminated(currentListType)) { + break; + } + + var abort = this.abortParsingListOrMoveToNextToken(currentListType, items, skippedTokens); + if (abort) { + break; + } + } + } + + var result = TypeScript.Syntax.list(items); + + this.returnZeroOrOneLengthArray(items); + + return { skippedTokens: skippedTokens, list: result }; + }; + + ParserImpl.prototype.parseSeparatedSyntaxListWorker = function (currentListType) { + var items = this.getArray(); + var skippedTokens = this.getArray(); + TypeScript.Debug.assert(items.length === 0); + TypeScript.Debug.assert(skippedTokens.length === 0); + TypeScript.Debug.assert(skippedTokens !== items); + + var separatorKind = this.separatorKind(currentListType); + var allowAutomaticSemicolonInsertion = separatorKind === 78 /* SemicolonToken */; + + var inErrorRecovery = false; + var listWasTerminated = false; + while (true) { + var oldItemsCount = items.length; + + this.tryParseExpectedListItem(currentListType, inErrorRecovery, items, null); + + var newItemsCount = items.length; + if (newItemsCount === oldItemsCount) { + if (this.listIsTerminated(currentListType)) { + listWasTerminated = true; + break; + } + + var abort = this.abortParsingListOrMoveToNextToken(currentListType, items, skippedTokens); + if (abort) { + break; + } else { + inErrorRecovery = true; + continue; + } + } + + inErrorRecovery = false; + + var currentToken = this.currentToken(); + if (currentToken.tokenKind === separatorKind || currentToken.tokenKind === 79 /* CommaToken */) { + items.push(this.eatAnyToken()); + continue; + } + + if (this.listIsTerminated(currentListType)) { + listWasTerminated = true; + break; + } + + if (allowAutomaticSemicolonInsertion && this.canEatAutomaticSemicolon(false)) { + items.push(this.eatExplicitOrAutomaticSemicolon(false)); + + continue; + } + + items.push(this.eatToken(separatorKind)); + + inErrorRecovery = true; + } + + var result = TypeScript.Syntax.separatedList(items); + + this.returnZeroOrOneLengthArray(items); + + return { skippedTokens: skippedTokens, list: result }; + }; + + ParserImpl.prototype.separatorKind = function (currentListType) { + switch (currentListType) { + case 2048 /* HeritageClause_TypeNameList */: + case 16384 /* ArgumentList_AssignmentExpressions */: + case 256 /* EnumDeclaration_EnumElements */: + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + case 131072 /* ParameterList_Parameters */: + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + case 262144 /* TypeArgumentList_Types */: + case 524288 /* TypeParameterList_TypeParameters */: + return 79 /* CommaToken */; + + case 512 /* ObjectType_TypeMembers */: + return 78 /* SemicolonToken */; + + case 1 /* SourceUnit_ModuleElements */: + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + case 2 /* ClassDeclaration_ClassElements */: + case 4 /* ModuleDeclaration_ModuleElements */: + case 8 /* SwitchStatement_SwitchClauses */: + case 16 /* SwitchClause_Statements */: + case 32 /* Block_Statements */: + default: + throw TypeScript.Errors.notYetImplemented(); + } + }; + + ParserImpl.prototype.reportUnexpectedTokenDiagnostic = function (listType) { + var token = this.currentToken(); + + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode.Unexpected_token_0_expected, [this.getExpectedListElementType(listType)]); + this.addDiagnostic(diagnostic); + }; + + ParserImpl.prototype.addDiagnostic = function (diagnostic) { + if (this.diagnostics.length > 0 && this.diagnostics[this.diagnostics.length - 1].start() === diagnostic.start()) { + return; + } + + this.diagnostics.push(diagnostic); + }; + + ParserImpl.prototype.isExpectedListTerminator = function (currentListType) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.isExpectedSourceUnit_ModuleElementsTerminator(); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.isExpectedClassDeclaration_ClassElementsTerminator(); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.isExpectedModuleDeclaration_ModuleElementsTerminator(); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.isExpectedSwitchStatement_SwitchClausesTerminator(); + + case 16 /* SwitchClause_Statements */: + return this.isExpectedSwitchClause_StatementsTerminator(); + + case 32 /* Block_Statements */: + return this.isExpectedBlock_StatementsTerminator(); + + case 64 /* TryBlock_Statements */: + return this.isExpectedTryBlock_StatementsTerminator(); + + case 128 /* CatchBlock_Statements */: + return this.isExpectedCatchBlock_StatementsTerminator(); + + case 256 /* EnumDeclaration_EnumElements */: + return this.isExpectedEnumDeclaration_EnumElementsTerminator(); + + case 512 /* ObjectType_TypeMembers */: + return this.isExpectedObjectType_TypeMembersTerminator(); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.isExpectedArgumentList_AssignmentExpressionsTerminator(); + + case 2048 /* HeritageClause_TypeNameList */: + return this.isExpectedHeritageClause_TypeNameListTerminator(); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return this.isExpectedVariableDeclaration_VariableDeclarators_AllowInTerminator(); + + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.isExpectedVariableDeclaration_VariableDeclarators_DisallowInTerminator(); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.isExpectedObjectLiteralExpression_PropertyAssignmentsTerminator(); + + case 131072 /* ParameterList_Parameters */: + return this.isExpectedParameterList_ParametersTerminator(); + + case 262144 /* TypeArgumentList_Types */: + return this.isExpectedTypeArgumentList_TypesTerminator(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.isExpectedTypeParameterList_TypeParametersTerminator(); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.isExpectedLiteralExpression_AssignmentExpressionsTerminator(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isExpectedSourceUnit_ModuleElementsTerminator = function () { + return this.currentToken().tokenKind === 10 /* EndOfFileToken */; + }; + + ParserImpl.prototype.isExpectedEnumDeclaration_EnumElementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedModuleDeclaration_ModuleElementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedObjectType_TypeMembersTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedObjectLiteralExpression_PropertyAssignmentsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedLiteralExpression_AssignmentExpressionsTerminator = function () { + return this.currentToken().tokenKind === 75 /* CloseBracketToken */; + }; + + ParserImpl.prototype.isExpectedTypeArgumentList_TypesTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 81 /* GreaterThanToken */) { + return true; + } + + if (this.canFollowTypeArgumentListInExpression(token.tokenKind)) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedTypeParameterList_TypeParametersTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 81 /* GreaterThanToken */) { + return true; + } + + if (token.tokenKind === 72 /* OpenParenToken */ || token.tokenKind === 70 /* OpenBraceToken */ || token.tokenKind === 48 /* ExtendsKeyword */ || token.tokenKind === 51 /* ImplementsKeyword */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedParameterList_ParametersTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 73 /* CloseParenToken */) { + return true; + } + + if (token.tokenKind === 70 /* OpenBraceToken */) { + return true; + } + + if (token.tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedVariableDeclaration_VariableDeclarators_DisallowInTerminator = function () { + if (this.currentToken().tokenKind === 78 /* SemicolonToken */ || this.currentToken().tokenKind === 73 /* CloseParenToken */) { + return true; + } + + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedVariableDeclaration_VariableDeclarators_AllowInTerminator = function () { + if (this.previousToken().tokenKind === 79 /* CommaToken */) { + return false; + } + + if (this.currentToken().tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + + return this.canEatExplicitOrAutomaticSemicolon(false); + }; + + ParserImpl.prototype.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 70 /* OpenBraceToken */ || token0.tokenKind === 71 /* CloseBraceToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedHeritageClause_TypeNameListTerminator = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 48 /* ExtendsKeyword */ || token0.tokenKind === 51 /* ImplementsKeyword */) { + return true; + } + + if (this.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator()) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedArgumentList_AssignmentExpressionsTerminator = function () { + var token0 = this.currentToken(); + return token0.tokenKind === 73 /* CloseParenToken */ || token0.tokenKind === 78 /* SemicolonToken */; + }; + + ParserImpl.prototype.isExpectedClassDeclaration_ClassElementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedSwitchStatement_SwitchClausesTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedSwitchClause_StatementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */ || this.isSwitchClause(); + }; + + ParserImpl.prototype.isExpectedBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedTryBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 17 /* CatchKeyword */ || this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.isExpectedCatchBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.isExpectedListItem = function (currentListType, inErrorRecovery) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.isModuleElement(inErrorRecovery); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.isHeritageClause(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.isClassElement(inErrorRecovery); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.isModuleElement(inErrorRecovery); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.isSwitchClause(); + + case 16 /* SwitchClause_Statements */: + return this.isStatement(inErrorRecovery); + + case 32 /* Block_Statements */: + return this.isStatement(inErrorRecovery); + + case 64 /* TryBlock_Statements */: + case 128 /* CatchBlock_Statements */: + return false; + + case 256 /* EnumDeclaration_EnumElements */: + return this.isEnumElement(inErrorRecovery); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.isVariableDeclarator(); + + case 512 /* ObjectType_TypeMembers */: + return this.isTypeMember(inErrorRecovery); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.isExpectedArgumentList_AssignmentExpression(); + + case 2048 /* HeritageClause_TypeNameList */: + return this.isHeritageClauseTypeName(); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.isPropertyAssignment(inErrorRecovery); + + case 131072 /* ParameterList_Parameters */: + return this.isParameter(); + + case 262144 /* TypeArgumentList_Types */: + return this.isType(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.isTypeParameter(); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.isAssignmentOrOmittedExpression(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isExpectedArgumentList_AssignmentExpression = function () { + var currentToken = this.currentToken(); + if (this.isExpression(currentToken)) { + return true; + } + + if (currentToken.tokenKind === 79 /* CommaToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.parseExpectedListItem = function (currentListType, inErrorRecovery) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.parseModuleElement(inErrorRecovery); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.parseHeritageClause(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.parseClassElement(inErrorRecovery); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.parseModuleElement(inErrorRecovery); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.parseSwitchClause(); + + case 16 /* SwitchClause_Statements */: + return this.parseStatement(inErrorRecovery); + + case 32 /* Block_Statements */: + return this.parseStatement(inErrorRecovery); + + case 256 /* EnumDeclaration_EnumElements */: + return this.parseEnumElement(); + + case 512 /* ObjectType_TypeMembers */: + return this.parseTypeMember(inErrorRecovery); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.parseAssignmentExpression(true); + + case 2048 /* HeritageClause_TypeNameList */: + return this.parseNameOrGenericType(); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return this.parseVariableDeclarator(true, false); + + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.parseVariableDeclarator(false, false); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.parsePropertyAssignment(inErrorRecovery); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.parseAssignmentOrOmittedExpression(); + + case 131072 /* ParameterList_Parameters */: + return this.parseParameter(); + + case 262144 /* TypeArgumentList_Types */: + return this.parseType(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.parseTypeParameter(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.getExpectedListElementType = function (currentListType) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.module_class_interface_enum_import_or_statement, null); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return '{'; + + case 2 /* ClassDeclaration_ClassElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.constructor_function_accessor_or_variable, null); + + case 4 /* ModuleDeclaration_ModuleElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.module_class_interface_enum_import_or_statement, null); + + case 8 /* SwitchStatement_SwitchClauses */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.case_or_default_clause, null); + + case 16 /* SwitchClause_Statements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.statement, null); + + case 32 /* Block_Statements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.statement, null); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null); + + case 256 /* EnumDeclaration_EnumElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null); + + case 512 /* ObjectType_TypeMembers */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.call_construct_index_property_or_function_signature, null); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + + case 2048 /* HeritageClause_TypeNameList */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_name, null); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.property_or_accessor, null); + + case 131072 /* ParameterList_Parameters */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.parameter, null); + + case 262144 /* TypeArgumentList_Types */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type, null); + + case 524288 /* TypeParameterList_TypeParameters */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_parameter, null); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + return ParserImpl; + })(); + + function parse(fileName, text, isDeclaration, options) { + var source = new NormalParserSource(fileName, text, options.languageVersion()); + + return new ParserImpl(fileName, text.lineMap(), source, options, text).parseSyntaxTree(isDeclaration); + } + Parser.parse = parse; + + function incrementalParse(oldSyntaxTree, textChangeRange, newText) { + if (textChangeRange.isUnchanged()) { + return oldSyntaxTree; + } + + var source = new IncrementalParserSource(oldSyntaxTree, textChangeRange, newText); + + return new ParserImpl(oldSyntaxTree.fileName(), newText.lineMap(), source, oldSyntaxTree.parseOptions(), newText).parseSyntaxTree(oldSyntaxTree.isDeclaration()); + } + Parser.incrementalParse = incrementalParse; + })(TypeScript.Parser || (TypeScript.Parser = {})); + var Parser = TypeScript.Parser; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTree = (function () { + function SyntaxTree(sourceUnit, isDeclaration, diagnostics, fileName, lineMap, parseOtions) { + this._allDiagnostics = null; + this._sourceUnit = sourceUnit; + this._isDeclaration = isDeclaration; + this._parserDiagnostics = diagnostics; + this._fileName = fileName; + this._lineMap = lineMap; + this._parseOptions = parseOtions; + } + SyntaxTree.prototype.toJSON = function (key) { + var result = {}; + + result.isDeclaration = this._isDeclaration; + result.languageVersion = TypeScript.LanguageVersion[this._parseOptions.languageVersion()]; + result.parseOptions = this._parseOptions; + + if (this.diagnostics().length > 0) { + result.diagnostics = this.diagnostics(); + } + + result.sourceUnit = this._sourceUnit; + result.lineMap = this._lineMap; + + return result; + }; + + SyntaxTree.prototype.sourceUnit = function () { + return this._sourceUnit; + }; + + SyntaxTree.prototype.isDeclaration = function () { + return this._isDeclaration; + }; + + SyntaxTree.prototype.computeDiagnostics = function () { + if (this._parserDiagnostics.length > 0) { + return this._parserDiagnostics; + } + + var diagnostics = []; + this.sourceUnit().accept(new GrammarCheckerWalker(this, diagnostics)); + + return diagnostics; + }; + + SyntaxTree.prototype.diagnostics = function () { + if (this._allDiagnostics === null) { + this._allDiagnostics = this.computeDiagnostics(); + } + + return this._allDiagnostics; + }; + + SyntaxTree.prototype.fileName = function () { + return this._fileName; + }; + + SyntaxTree.prototype.lineMap = function () { + return this._lineMap; + }; + + SyntaxTree.prototype.parseOptions = function () { + return this._parseOptions; + }; + + SyntaxTree.prototype.structuralEquals = function (tree) { + return TypeScript.ArrayUtilities.sequenceEquals(this.diagnostics(), tree.diagnostics(), TypeScript.Diagnostic.equals) && this.sourceUnit().structuralEquals(tree.sourceUnit()); + }; + return SyntaxTree; + })(); + TypeScript.SyntaxTree = SyntaxTree; + + var GrammarCheckerWalker = (function (_super) { + __extends(GrammarCheckerWalker, _super); + function GrammarCheckerWalker(syntaxTree, diagnostics) { + _super.call(this); + this.syntaxTree = syntaxTree; + this.diagnostics = diagnostics; + this.inAmbientDeclaration = false; + this.inBlock = false; + this.inObjectLiteralExpression = false; + this.currentConstructor = null; + } + GrammarCheckerWalker.prototype.childFullStart = function (parent, child) { + return this.position() + TypeScript.Syntax.childOffset(parent, child); + }; + + GrammarCheckerWalker.prototype.childStart = function (parent, child) { + return this.childFullStart(parent, child) + child.leadingTriviaWidth(); + }; + + GrammarCheckerWalker.prototype.pushDiagnostic = function (start, length, diagnosticKey, args) { + if (typeof args === "undefined") { args = null; } + this.diagnostics.push(new TypeScript.Diagnostic(this.syntaxTree.fileName(), this.syntaxTree.lineMap(), start, length, diagnosticKey, args)); + }; + + GrammarCheckerWalker.prototype.pushDiagnostic1 = function (elementFullStart, element, diagnosticKey, args) { + if (typeof args === "undefined") { args = null; } + this.diagnostics.push(new TypeScript.Diagnostic(this.syntaxTree.fileName(), this.syntaxTree.lineMap(), elementFullStart + element.leadingTriviaWidth(), element.width(), diagnosticKey, args)); + }; + + GrammarCheckerWalker.prototype.visitCatchClause = function (node) { + if (node.typeAnnotation) { + this.pushDiagnostic(this.childStart(node, node.typeAnnotation), node.typeAnnotation.width(), TypeScript.DiagnosticCode.Catch_clause_parameter_cannot_have_a_type_annotation); + } + + _super.prototype.visitCatchClause.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkParameterListOrder = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameters); + + var seenOptionalParameter = false; + var parameterCount = node.parameters.nonSeparatorCount(); + + for (var i = 0, n = node.parameters.childCount(); i < n; i++) { + var nodeOrToken = node.parameters.childAt(i); + if (i % 2 === 0) { + var parameterIndex = i / 2; + var parameter = node.parameters.childAt(i); + + if (parameter.dotDotDotToken) { + if (parameterIndex !== (parameterCount - 1)) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Rest_parameter_must_be_last_in_list); + return true; + } + + if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Rest_parameter_cannot_be_optional); + return true; + } + + if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Rest_parameter_cannot_have_an_initializer); + return true; + } + } else if (parameter.questionToken || parameter.equalsValueClause) { + seenOptionalParameter = true; + + if (parameter.questionToken && parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Parameter_cannot_have_question_mark_and_initializer); + return true; + } + } else { + if (seenOptionalParameter) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Required_parameter_cannot_follow_optional_parameter); + return true; + } + } + } + + parameterFullStart += nodeOrToken.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkParameterListAcessibilityModifiers = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameters); + + for (var i = 0, n = node.parameters.childCount(); i < n; i++) { + var nodeOrToken = node.parameters.childAt(i); + if (i % 2 === 0) { + var parameter = node.parameters.childAt(i); + + if (this.checkParameterAccessibilityModifiers(node, parameter, parameterFullStart)) { + return true; + } + } + + parameterFullStart += nodeOrToken.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkParameterAccessibilityModifiers = function (parameterList, parameter, parameterFullStart) { + if (parameter.modifiers.childCount() > 0) { + var modifiers = parameter.modifiers; + var modifierFullStart = parameterFullStart + TypeScript.Syntax.childOffset(parameter, modifiers); + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + + if (this.checkParameterAccessibilityModifier(parameterList, modifier, modifierFullStart, i)) { + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkParameterAccessibilityModifier = function (parameterList, modifier, modifierFullStart, modifierIndex) { + if (modifier.tokenKind !== 57 /* PublicKeyword */ && modifier.tokenKind !== 55 /* PrivateKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_parameter, [modifier.text()]); + return true; + } else { + if (modifierIndex > 0) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return true; + } + + if (!this.inAmbientDeclaration && this.currentConstructor && !this.currentConstructor.block && this.currentConstructor.callSignature.parameterList === parameterList) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_cannot_be_used_in_a_constructor_overload); + return true; + } else if (this.inAmbientDeclaration || this.currentConstructor === null || this.currentConstructor.callSignature.parameterList !== parameterList) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_can_only_be_used_in_a_non_ambient_constructor_declaration); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForTrailingSeparator = function (parent, list) { + if (list.childCount() === 0 || list.childCount() % 2 === 1) { + return false; + } + + var currentElementFullStart = this.childFullStart(parent, list); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var child = list.childAt(i); + if (i === n - 1) { + this.pushDiagnostic1(currentElementFullStart, child, TypeScript.DiagnosticCode.Trailing_separator_not_allowed); + } + + currentElementFullStart += child.fullWidth(); + } + + return true; + }; + + GrammarCheckerWalker.prototype.checkForAtLeastOneElement = function (parent, list, expected) { + if (list.childCount() > 0) { + return false; + } + + var listFullStart = this.childFullStart(parent, list); + var tokenAtStart = this.syntaxTree.sourceUnit().findToken(listFullStart); + + this.pushDiagnostic1(listFullStart, tokenAtStart.token(), TypeScript.DiagnosticCode.Unexpected_token_0_expected, [expected]); + + return true; + }; + + GrammarCheckerWalker.prototype.visitParameterList = function (node) { + if (this.checkParameterListAcessibilityModifiers(node) || this.checkParameterListOrder(node) || this.checkForTrailingSeparator(node, node.parameters)) { + this.skip(node); + return; + } + + _super.prototype.visitParameterList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitHeritageClause = function (node) { + if (this.checkForTrailingSeparator(node, node.typeNames) || this.checkForAtLeastOneElement(node, node.typeNames, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_name, null))) { + this.skip(node); + return; + } + + _super.prototype.visitHeritageClause.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitArgumentList = function (node) { + if (this.checkForTrailingSeparator(node, node.arguments)) { + this.skip(node); + return; + } + + _super.prototype.visitArgumentList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitVariableDeclaration = function (node) { + if (this.checkForTrailingSeparator(node, node.variableDeclarators) || this.checkForAtLeastOneElement(node, node.variableDeclarators, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null))) { + this.skip(node); + return; + } + + _super.prototype.visitVariableDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTypeArgumentList = function (node) { + if (this.checkForTrailingSeparator(node, node.typeArguments) || this.checkForAtLeastOneElement(node, node.typeArguments, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null))) { + this.skip(node); + return; + } + + _super.prototype.visitTypeArgumentList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTypeParameterList = function (node) { + if (this.checkForTrailingSeparator(node, node.typeParameters) || this.checkForAtLeastOneElement(node, node.typeParameters, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null))) { + this.skip(node); + return; + } + + _super.prototype.visitTypeParameterList.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkIndexSignatureParameter = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameter); + var parameter = node.parameter; + + if (parameter.dotDotDotToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signatures_cannot_have_rest_parameters); + return true; + } else if (parameter.modifiers.childCount() > 0) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_accessibility_modifiers); + return true; + } else if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_a_question_mark); + return true; + } else if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_an_initializer); + return true; + } else if (!parameter.typeAnnotation) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_must_have_a_type_annotation); + return true; + } else if (parameter.typeAnnotation.type.kind() !== 69 /* StringKeyword */ && parameter.typeAnnotation.type.kind() !== 67 /* NumberKeyword */) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_type_must_be_string_or_number); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitIndexSignature = function (node) { + if (this.checkIndexSignatureParameter(node)) { + this.skip(node); + return; + } + + if (!node.typeAnnotation) { + this.pushDiagnostic1(this.position(), node, TypeScript.DiagnosticCode.Index_signature_must_have_a_type_annotation); + this.skip(node); + return; + } + + _super.prototype.visitIndexSignature.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkClassDeclarationHeritageClauses = function (node) { + var heritageClauseFullStart = this.childFullStart(node, node.heritageClauses); + + var seenExtendsClause = false; + var seenImplementsClause = false; + + for (var i = 0, n = node.heritageClauses.childCount(); i < n; i++) { + TypeScript.Debug.assert(i <= 2); + var heritageClause = node.heritageClauses.childAt(i); + + if (heritageClause.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */) { + if (seenExtendsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.extends_clause_already_seen); + return true; + } + + if (seenImplementsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.extends_clause_must_precede_implements_clause); + return true; + } + + if (heritageClause.typeNames.nonSeparatorCount() > 1) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.Classes_can_only_extend_a_single_class); + return true; + } + + seenExtendsClause = true; + } else { + TypeScript.Debug.assert(heritageClause.extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + if (seenImplementsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.implements_clause_already_seen); + return true; + } + + seenImplementsClause = true; + } + + heritageClauseFullStart += heritageClause.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedDeclareModifier = function (modifiers) { + if (this.inAmbientDeclaration) { + var declareToken = TypeScript.SyntaxUtilities.getToken(modifiers, 63 /* DeclareKeyword */); + + if (declareToken) { + this.pushDiagnostic1(this.childFullStart(modifiers, declareToken), declareToken, TypeScript.DiagnosticCode.declare_modifier_not_allowed_for_code_already_in_an_ambient_context); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForRequiredDeclareModifier = function (moduleElement, typeKeyword, modifiers) { + if (!this.inAmbientDeclaration && this.syntaxTree.isDeclaration()) { + if (!TypeScript.SyntaxUtilities.containsToken(modifiers, 63 /* DeclareKeyword */)) { + this.pushDiagnostic1(this.childFullStart(moduleElement, typeKeyword), typeKeyword.firstToken(), TypeScript.DiagnosticCode.declare_modifier_required_for_top_level_element); + return true; + } + } + }; + + GrammarCheckerWalker.prototype.checkFunctionOverloads = function (node, moduleElements) { + if (!this.inAmbientDeclaration && !this.syntaxTree.isDeclaration()) { + var moduleElementFullStart = this.childFullStart(node, moduleElements); + + var inFunctionOverloadChain = false; + var functionOverloadChainName = null; + + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var moduleElement = moduleElements.childAt(i); + var lastElement = i === (n - 1); + + if (inFunctionOverloadChain) { + if (moduleElement.kind() !== 129 /* FunctionDeclaration */) { + this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + + var functionDeclaration = moduleElement; + if (functionDeclaration.identifier.valueText() !== functionOverloadChainName) { + var identifierFullStart = moduleElementFullStart + TypeScript.Syntax.childOffset(moduleElement, functionDeclaration.identifier); + this.pushDiagnostic1(identifierFullStart, functionDeclaration.identifier, TypeScript.DiagnosticCode.Function_overload_name_must_be_0, [functionOverloadChainName]); + return true; + } + } + + if (moduleElement.kind() === 129 /* FunctionDeclaration */) { + functionDeclaration = moduleElement; + if (!TypeScript.SyntaxUtilities.containsToken(functionDeclaration.modifiers, 63 /* DeclareKeyword */)) { + inFunctionOverloadChain = functionDeclaration.block === null; + functionOverloadChainName = functionDeclaration.identifier.valueText(); + + if (inFunctionOverloadChain) { + if (lastElement) { + this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } else { + var nextElement = moduleElements.childAt(i + 1); + if (nextElement.kind() === 129 /* FunctionDeclaration */) { + var nextFunction = nextElement; + + if (nextFunction.identifier.valueText() !== functionOverloadChainName && nextFunction.block === null) { + var identifierFullStart = moduleElementFullStart + TypeScript.Syntax.childOffset(moduleElement, functionDeclaration.identifier); + this.pushDiagnostic1(identifierFullStart, functionDeclaration.identifier, TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + } + } + } + } else { + inFunctionOverloadChain = false; + functionOverloadChainName = ""; + } + } + + moduleElementFullStart += moduleElement.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkClassOverloads = function (node) { + if (!this.inAmbientDeclaration && !TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */)) { + var classElementFullStart = this.childFullStart(node, node.classElements); + + var inFunctionOverloadChain = false; + var inConstructorOverloadChain = false; + + var functionOverloadChainName = null; + var isInStaticOverloadChain = null; + var memberFunctionDeclaration = null; + + for (var i = 0, n = node.classElements.childCount(); i < n; i++) { + var classElement = node.classElements.childAt(i); + var lastElement = i === (n - 1); + var isStaticOverload = null; + + if (inFunctionOverloadChain) { + if (classElement.kind() !== 135 /* MemberFunctionDeclaration */) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + + memberFunctionDeclaration = classElement; + if (memberFunctionDeclaration.propertyName.valueText() !== functionOverloadChainName) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, TypeScript.DiagnosticCode.Function_overload_name_must_be_0, [functionOverloadChainName]); + return true; + } + + isStaticOverload = TypeScript.SyntaxUtilities.containsToken(memberFunctionDeclaration.modifiers, 58 /* StaticKeyword */); + if (isStaticOverload !== isInStaticOverloadChain) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + var diagnostic = isInStaticOverloadChain ? TypeScript.DiagnosticCode.Function_overload_must_be_static : TypeScript.DiagnosticCode.Function_overload_must_not_be_static; + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, diagnostic, null); + return true; + } + } else if (inConstructorOverloadChain) { + if (classElement.kind() !== 137 /* ConstructorDeclaration */) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Constructor_implementation_expected); + return true; + } + } + + if (classElement.kind() === 135 /* MemberFunctionDeclaration */) { + memberFunctionDeclaration = classElement; + + inFunctionOverloadChain = memberFunctionDeclaration.block === null; + functionOverloadChainName = memberFunctionDeclaration.propertyName.valueText(); + isInStaticOverloadChain = TypeScript.SyntaxUtilities.containsToken(memberFunctionDeclaration.modifiers, 58 /* StaticKeyword */); + + if (inFunctionOverloadChain) { + if (lastElement) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } else { + var nextElement = node.classElements.childAt(i + 1); + if (nextElement.kind() === 135 /* MemberFunctionDeclaration */) { + var nextMemberFunction = nextElement; + + if (nextMemberFunction.propertyName.valueText() !== functionOverloadChainName && nextMemberFunction.block === null) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + } + } + } + } else if (classElement.kind() === 137 /* ConstructorDeclaration */) { + var constructorDeclaration = classElement; + + inConstructorOverloadChain = constructorDeclaration.block === null; + if (lastElement && inConstructorOverloadChain) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Constructor_implementation_expected); + return true; + } + } + + classElementFullStart += classElement.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForReservedName = function (parent, name, diagnosticKey) { + var nameFullStart = this.childFullStart(parent, name); + var token; + var tokenFullStart; + + var current = name; + while (current !== null) { + if (current.kind() === 121 /* QualifiedName */) { + var qualifiedName = current; + token = qualifiedName.right; + tokenFullStart = nameFullStart + this.childFullStart(qualifiedName, token); + current = qualifiedName.left; + } else { + TypeScript.Debug.assert(current.kind() === 11 /* IdentifierName */); + token = current; + tokenFullStart = nameFullStart; + current = null; + } + + switch (token.valueText()) { + case "any": + case "number": + case "boolean": + case "string": + case "void": + this.pushDiagnostic(tokenFullStart + token.leadingTriviaWidth(), token.width(), diagnosticKey, [token.valueText()]); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitClassDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, TypeScript.DiagnosticCode.Class_name_cannot_be_0) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.classKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkClassDeclarationHeritageClauses(node) || this.checkClassOverloads(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitClassDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkInterfaceDeclarationHeritageClauses = function (node) { + var heritageClauseFullStart = this.childFullStart(node, node.heritageClauses); + + var seenExtendsClause = false; + + for (var i = 0, n = node.heritageClauses.childCount(); i < n; i++) { + TypeScript.Debug.assert(i <= 1); + var heritageClause = node.heritageClauses.childAt(i); + + if (heritageClause.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */) { + if (seenExtendsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.extends_clause_already_seen); + return true; + } + + seenExtendsClause = true; + } else { + TypeScript.Debug.assert(heritageClause.extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.Interface_declaration_cannot_have_implements_clause); + return true; + } + + heritageClauseFullStart += heritageClause.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkInterfaceModifiers = function (modifiers) { + var modifierFullStart = this.position(); + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + if (modifier.tokenKind === 63 /* DeclareKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.declare_modifier_cannot_appear_on_an_interface_declaration); + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitInterfaceDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, TypeScript.DiagnosticCode.Interface_name_cannot_be_0) || this.checkInterfaceModifiers(node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkInterfaceDeclarationHeritageClauses(node)) { + this.skip(node); + return; + } + + _super.prototype.visitInterfaceDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkClassElementModifiers = function (list) { + var modifierFullStart = this.position(); + + var seenAccessibilityModifier = false; + var seenStaticModifier = false; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var modifier = list.childAt(i); + if (modifier.tokenKind === 57 /* PublicKeyword */ || modifier.tokenKind === 55 /* PrivateKeyword */) { + if (seenAccessibilityModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return true; + } + + if (seenStaticModifier) { + var previousToken = list.childAt(i - 1); + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_must_precede_1_modifier, [modifier.text(), previousToken.text()]); + return true; + } + + seenAccessibilityModifier = true; + } else if (modifier.tokenKind === 58 /* StaticKeyword */) { + if (seenStaticModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_already_seen, [modifier.text()]); + return true; + } + + seenStaticModifier = true; + } else { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_class_element, [modifier.text()]); + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitMemberVariableDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitMemberVariableDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitMemberFunctionDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitMemberFunctionDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkGetAccessorParameter = function (node, getKeyword, parameterList) { + var getKeywordFullStart = this.childFullStart(node, getKeyword); + if (parameterList.parameters.childCount() !== 0) { + this.pushDiagnostic1(getKeywordFullStart, getKeyword, TypeScript.DiagnosticCode.get_accessor_cannot_have_parameters); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitIndexMemberDeclaration = function (node) { + if (this.checkIndexMemberModifiers(node)) { + this.skip(node); + return; + } + + _super.prototype.visitIndexMemberDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkIndexMemberModifiers = function (node) { + if (node.modifiers.childCount() > 0) { + var modifierFullStart = this.childFullStart(node, node.modifiers); + this.pushDiagnostic1(modifierFullStart, node.modifiers.childAt(0), TypeScript.DiagnosticCode.Modifiers_cannot_appear_here); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkEcmaScriptVersionIsAtLeast = function (parent, node, languageVersion, diagnosticKey) { + if (this.syntaxTree.parseOptions().languageVersion() < languageVersion) { + var nodeFullStart = this.childFullStart(parent, node); + this.pushDiagnostic1(nodeFullStart, node, diagnosticKey); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitObjectLiteralExpression = function (node) { + var savedInObjectLiteralExpression = this.inObjectLiteralExpression; + this.inObjectLiteralExpression = true; + _super.prototype.visitObjectLiteralExpression.call(this, node); + this.inObjectLiteralExpression = savedInObjectLiteralExpression; + }; + + GrammarCheckerWalker.prototype.visitGetAccessor = function (node) { + if (this.checkForAccessorDeclarationInAmbientContext(node) || this.checkEcmaScriptVersionIsAtLeast(node, node.getKeyword, 1 /* EcmaScript5 */, TypeScript.DiagnosticCode.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkClassElementModifiers(node.modifiers) || this.checkGetAccessorParameter(node, node.getKeyword, node.parameterList)) { + this.skip(node); + return; + } + + _super.prototype.visitGetAccessor.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkForAccessorDeclarationInAmbientContext = function (accessor) { + if (this.inAmbientDeclaration) { + this.pushDiagnostic1(this.position(), accessor, TypeScript.DiagnosticCode.Accessors_are_not_allowed_in_ambient_contexts, null); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkSetAccessorParameter = function (node, setKeyword, parameterList) { + var setKeywordFullStart = this.childFullStart(node, setKeyword); + if (parameterList.parameters.childCount() !== 1) { + this.pushDiagnostic1(setKeywordFullStart, setKeyword, TypeScript.DiagnosticCode.set_accessor_must_have_one_and_only_one_parameter); + return true; + } + + var parameterListFullStart = this.childFullStart(node, parameterList); + var parameterFullStart = parameterListFullStart + TypeScript.Syntax.childOffset(parameterList, parameterList.openParenToken); + var parameter = parameterList.parameters.childAt(0); + + if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.set_accessor_parameter_cannot_be_optional); + return true; + } + + if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.set_accessor_parameter_cannot_have_an_initializer); + return true; + } + + if (parameter.dotDotDotToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.set_accessor_cannot_have_rest_parameter); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitSetAccessor = function (node) { + if (this.checkForAccessorDeclarationInAmbientContext(node) || this.checkEcmaScriptVersionIsAtLeast(node, node.setKeyword, 1 /* EcmaScript5 */, TypeScript.DiagnosticCode.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkClassElementModifiers(node.modifiers) || this.checkSetAccessorParameter(node, node.setKeyword, node.parameterList)) { + this.skip(node); + return; + } + + _super.prototype.visitSetAccessor.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitEnumDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, TypeScript.DiagnosticCode.Enum_name_cannot_be_0) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.enumKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers), this.checkEnumElements(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitEnumDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkEnumElements = function (node) { + var enumElementFullStart = this.childFullStart(node, node.enumElements); + + var previousValueWasComputed = false; + for (var i = 0, n = node.enumElements.childCount(); i < n; i++) { + var child = node.enumElements.childAt(i); + + if (i % 2 === 0) { + var enumElement = child; + + if (!enumElement.equalsValueClause && previousValueWasComputed) { + this.pushDiagnostic1(enumElementFullStart, enumElement, TypeScript.DiagnosticCode.Enum_member_must_have_initializer, null); + return true; + } + + if (enumElement.equalsValueClause) { + var value = enumElement.equalsValueClause.value; + previousValueWasComputed = !TypeScript.Syntax.isIntegerLiteral(value); + } + } + + enumElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitEnumElement = function (node) { + if (this.inAmbientDeclaration && node.equalsValueClause) { + var expression = node.equalsValueClause.value; + if (!TypeScript.Syntax.isIntegerLiteral(expression)) { + this.pushDiagnostic1(this.childFullStart(node, node.equalsValueClause), node.equalsValueClause.firstToken(), TypeScript.DiagnosticCode.Ambient_enum_elements_can_only_have_integer_literal_initializers); + this.skip(node); + return; + } + } + + _super.prototype.visitEnumElement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitInvocationExpression = function (node) { + if (node.expression.kind() === 50 /* SuperKeyword */ && node.argumentList.typeArgumentList !== null) { + this.pushDiagnostic1(this.position(), node, TypeScript.DiagnosticCode.super_invocation_cannot_have_type_arguments); + } + + _super.prototype.visitInvocationExpression.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkModuleElementModifiers = function (modifiers) { + var modifierFullStart = this.position(); + var seenExportModifier = false; + var seenDeclareModifier = false; + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + if (modifier.tokenKind === 57 /* PublicKeyword */ || modifier.tokenKind === 55 /* PrivateKeyword */ || modifier.tokenKind === 58 /* StaticKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_module_element, [modifier.text()]); + return true; + } + + if (modifier.tokenKind === 63 /* DeclareKeyword */) { + if (seenDeclareModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return; + } + + seenDeclareModifier = true; + } else if (modifier.tokenKind === 47 /* ExportKeyword */) { + if (seenExportModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_already_seen, [modifier.text()]); + return; + } + + if (seenDeclareModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_must_precede_1_modifier, [TypeScript.SyntaxFacts.getText(47 /* ExportKeyword */), TypeScript.SyntaxFacts.getText(63 /* DeclareKeyword */)]); + return; + } + + seenExportModifier = true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedImportDeclaration = function (node) { + var currentElementFullStart = this.childFullStart(node, node.moduleElements); + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var child = node.moduleElements.childAt(i); + if (child.kind() === 133 /* ImportDeclaration */) { + var importDeclaration = child; + if (importDeclaration.moduleReference.kind() === 245 /* ExternalModuleReference */) { + if (node.stringLiteral === null) { + this.pushDiagnostic1(currentElementFullStart, importDeclaration, TypeScript.DiagnosticCode.Import_declarations_in_an_internal_module_cannot_reference_an_external_module, null); + } + } + } + + currentElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedDeclareModifierOnImportDeclaration = function (modifiers) { + var declareToken = TypeScript.SyntaxUtilities.getToken(modifiers, 63 /* DeclareKeyword */); + + if (declareToken) { + this.pushDiagnostic1(this.childFullStart(modifiers, declareToken), declareToken, TypeScript.DiagnosticCode.declare_modifier_not_allowed_on_import_declaration); + return true; + } + }; + + GrammarCheckerWalker.prototype.visitImportDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifierOnImportDeclaration(node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitImportDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitModuleDeclaration = function (node) { + if (this.checkForReservedName(node, node.name, TypeScript.DiagnosticCode.Module_name_cannot_be_0) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.moduleKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkForDisallowedImportDeclaration(node) || this.checkForDisallowedExports(node, node.moduleElements) || this.checkForMultipleExportAssignments(node, node.moduleElements)) { + this.skip(node); + return; + } + + if (!TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */) && this.checkFunctionOverloads(node, node.moduleElements)) { + this.skip(node); + return; + } + + if (node.stringLiteral) { + if (!this.inAmbientDeclaration && !TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */)) { + var stringLiteralFullStart = this.childFullStart(node, node.stringLiteral); + this.pushDiagnostic1(stringLiteralFullStart, node.stringLiteral, TypeScript.DiagnosticCode.Only_ambient_modules_can_use_quoted_names); + this.skip(node); + return; + } + } + + if (!node.stringLiteral && this.checkForDisallowedExportAssignment(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitModuleDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedExports = function (node, moduleElements) { + var seenExportedElement = false; + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + + if (TypeScript.SyntaxUtilities.hasExportKeyword(child)) { + seenExportedElement = true; + break; + } + } + + var moduleElementFullStart = this.childFullStart(node, moduleElements); + if (seenExportedElement) { + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + + if (child.kind() === 134 /* ExportAssignment */) { + this.pushDiagnostic1(moduleElementFullStart, child, TypeScript.DiagnosticCode.Export_assignment_not_allowed_in_module_with_exported_element); + return true; + } + + moduleElementFullStart += child.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForMultipleExportAssignments = function (node, moduleElements) { + var moduleElementFullStart = this.childFullStart(node, moduleElements); + var seenExportAssignment = false; + var errorFound = false; + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + if (child.kind() === 134 /* ExportAssignment */) { + if (seenExportAssignment) { + this.pushDiagnostic1(moduleElementFullStart, child, TypeScript.DiagnosticCode.Module_cannot_have_multiple_export_assignments); + errorFound = true; + } + seenExportAssignment = true; + } + + moduleElementFullStart += child.fullWidth(); + } + + return errorFound; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedExportAssignment = function (node) { + var moduleElementFullStart = this.childFullStart(node, node.moduleElements); + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var child = node.moduleElements.childAt(i); + + if (child.kind() === 134 /* ExportAssignment */) { + this.pushDiagnostic1(moduleElementFullStart, child, TypeScript.DiagnosticCode.Export_assignment_cannot_be_used_in_internal_modules); + + return true; + } + + moduleElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitBlock = function (node) { + if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) { + this.pushDiagnostic1(this.position(), node.firstToken(), TypeScript.DiagnosticCode.Implementations_are_not_allowed_in_ambient_contexts); + this.skip(node); + return; + } + + if (this.checkFunctionOverloads(node, node.statements)) { + this.skip(node); + return; + } + + var savedInBlock = this.inBlock; + this.inBlock = true; + _super.prototype.visitBlock.call(this, node); + this.inBlock = savedInBlock; + }; + + GrammarCheckerWalker.prototype.checkForStatementInAmbientContxt = function (node) { + if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) { + this.pushDiagnostic1(this.position(), node.firstToken(), TypeScript.DiagnosticCode.Statements_are_not_allowed_in_ambient_contexts); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitBreakStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitBreakStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitContinueStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitContinueStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitDebuggerStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitDebuggerStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitDoStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitDoStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitEmptyStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitEmptyStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitExpressionStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitExpressionStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitForInStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node) || this.checkForInStatementVariableDeclaration(node)) { + this.skip(node); + return; + } + + _super.prototype.visitForInStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkForInStatementVariableDeclaration = function (node) { + if (node.variableDeclaration && node.variableDeclaration.variableDeclarators.nonSeparatorCount() > 1) { + var variableDeclarationFullStart = this.childFullStart(node, node.variableDeclaration); + + this.pushDiagnostic1(variableDeclarationFullStart, node.variableDeclaration, TypeScript.DiagnosticCode.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitForStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitForStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitIfStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitIfStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitLabeledStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitLabeledStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitReturnStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitReturnStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitSwitchStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitSwitchStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitThrowStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitThrowStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTryStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitTryStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitWhileStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitWhileStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitWithStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitWithStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkForDisallowedModifiers = function (parent, modifiers) { + if (this.inBlock || this.inObjectLiteralExpression) { + if (modifiers.childCount() > 0) { + var modifierFullStart = this.childFullStart(parent, modifiers); + this.pushDiagnostic1(modifierFullStart, modifiers.childAt(0), TypeScript.DiagnosticCode.Modifiers_cannot_appear_here); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitFunctionDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkForRequiredDeclareModifier(node, node.functionKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitFunctionDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitVariableStatement = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkForRequiredDeclareModifier(node, node.variableDeclaration, node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitVariableStatement.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkListSeparators = function (parent, list, kind) { + var currentElementFullStart = this.childFullStart(parent, list); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var child = list.childAt(i); + if (i % 2 === 1 && child.kind() !== kind) { + this.pushDiagnostic1(currentElementFullStart, child, TypeScript.DiagnosticCode._0_expected, [TypeScript.SyntaxFacts.getText(kind)]); + } + + currentElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitObjectType = function (node) { + if (this.checkListSeparators(node, node.typeMembers, 78 /* SemicolonToken */)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitObjectType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitArrayType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitArrayType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitFunctionType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitFunctionType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitConstructorType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitConstructorType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitVariableDeclarator = function (node) { + if (this.inAmbientDeclaration && node.equalsValueClause) { + this.pushDiagnostic1(this.childFullStart(node, node.equalsValueClause), node.equalsValueClause.firstToken(), TypeScript.DiagnosticCode.Initializers_are_not_allowed_in_ambient_contexts); + this.skip(node); + return; + } + + _super.prototype.visitVariableDeclarator.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitConstructorDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers) || this.checkConstructorModifiers(node.modifiers) || this.checkConstructorTypeParameterList(node) || this.checkConstructorTypeAnnotation(node)) { + this.skip(node); + return; + } + + var savedCurrentConstructor = this.currentConstructor; + this.currentConstructor = node; + _super.prototype.visitConstructorDeclaration.call(this, node); + this.currentConstructor = savedCurrentConstructor; + }; + + GrammarCheckerWalker.prototype.checkConstructorModifiers = function (modifiers) { + var currentElementFullStart = this.position(); + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var child = modifiers.childAt(i); + if (child.kind() !== 57 /* PublicKeyword */) { + this.pushDiagnostic1(currentElementFullStart, child, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_constructor_declaration, [TypeScript.SyntaxFacts.getText(child.kind())]); + return true; + } + + currentElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkConstructorTypeParameterList = function (node) { + var currentElementFullStart = this.position(); + + if (node.callSignature.typeParameterList) { + var callSignatureFullStart = this.childFullStart(node, node.callSignature); + var typeParameterListFullStart = callSignatureFullStart + TypeScript.Syntax.childOffset(node.callSignature, node.callSignature.typeAnnotation); + this.pushDiagnostic1(callSignatureFullStart, node.callSignature.typeParameterList, TypeScript.DiagnosticCode.Type_parameters_cannot_appear_on_a_constructor_declaration); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkConstructorTypeAnnotation = function (node) { + var currentElementFullStart = this.position(); + + if (node.callSignature.typeAnnotation) { + var callSignatureFullStart = this.childFullStart(node, node.callSignature); + var typeAnnotationFullStart = callSignatureFullStart + TypeScript.Syntax.childOffset(node.callSignature, node.callSignature.typeAnnotation); + this.pushDiagnostic1(typeAnnotationFullStart, node.callSignature.typeAnnotation, TypeScript.DiagnosticCode.Type_annotation_cannot_appear_on_a_constructor_declaration); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitSourceUnit = function (node) { + if (this.checkFunctionOverloads(node, node.moduleElements) || this.checkForDisallowedExports(node, node.moduleElements) || this.checkForMultipleExportAssignments(node, node.moduleElements)) { + this.skip(node); + return; + } + + _super.prototype.visitSourceUnit.call(this, node); + }; + return GrammarCheckerWalker; + })(TypeScript.PositionTrackingWalker); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Unicode = (function () { + function Unicode() { + } + Unicode.lookupInUnicodeMap = function (code, map) { + if (code < map[0]) { + return false; + } + + 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; + }; + + Unicode.isIdentifierStart = function (code, languageVersion) { + if (languageVersion === 0 /* EcmaScript3 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES3IdentifierStart); + } else if (languageVersion === 1 /* EcmaScript5 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES5IdentifierStart); + } else { + throw TypeScript.Errors.argumentOutOfRange("languageVersion"); + } + }; + + Unicode.isIdentifierPart = function (code, languageVersion) { + if (languageVersion === 0 /* EcmaScript3 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES3IdentifierPart); + } else if (languageVersion === 1 /* EcmaScript5 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES5IdentifierPart); + } else { + throw TypeScript.Errors.argumentOutOfRange("languageVersion"); + } + }; + Unicode.unicodeES3IdentifierStart = [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]; + Unicode.unicodeES3IdentifierPart = [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, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 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, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 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, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 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, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + + Unicode.unicodeES5IdentifierStart = [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]; + Unicode.unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 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, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 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, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 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, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 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, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + return Unicode; + })(); + TypeScript.Unicode = Unicode; +})(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; + + function timeFunction(logger, funcDescription, func) { + var start = (new Date()).getTime(); + var result = func(); + var end = (new Date()).getTime(); + if (logger.information()) { + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + } + return result; + } + TypeScript.timeFunction = timeFunction; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Document = (function () { + function Document(_compiler, _semanticInfoChain, fileName, referencedFiles, _scriptSnapshot, byteOrderMark, version, isOpen, _syntaxTree, _topLevelDecl) { + this._compiler = _compiler; + this._semanticInfoChain = _semanticInfoChain; + this.fileName = fileName; + this.referencedFiles = referencedFiles; + this._scriptSnapshot = _scriptSnapshot; + this.byteOrderMark = byteOrderMark; + this.version = version; + this.isOpen = isOpen; + this._syntaxTree = _syntaxTree; + this._topLevelDecl = _topLevelDecl; + this._diagnostics = null; + this._bloomFilter = null; + this._sourceUnit = null; + this._lineMap = null; + this._declASTMap = []; + this._astDeclMap = []; + this._amdDependencies = undefined; + this._externalModuleIndicatorSpan = undefined; + } + Document.prototype.invalidate = function () { + this._declASTMap.length = 0; + this._astDeclMap.length = 0; + this._topLevelDecl = null; + + this._syntaxTree = null; + this._sourceUnit = null; + this._diagnostics = null; + this._bloomFilter = null; + }; + + Document.prototype.isDeclareFile = function () { + return TypeScript.isDTSFile(this.fileName); + }; + + Document.prototype.cacheSyntaxTreeInfo = function (syntaxTree) { + var start = new Date().getTime(); + this._diagnostics = syntaxTree.diagnostics(); + TypeScript.syntaxDiagnosticsTime += new Date().getTime() - start; + + this._lineMap = syntaxTree.lineMap(); + + var sourceUnit = syntaxTree.sourceUnit(); + var leadingTrivia = sourceUnit.leadingTrivia(); + + this._externalModuleIndicatorSpan = this.getImplicitImportSpan(leadingTrivia) || this.getTopLevelImportOrExportSpan(sourceUnit); + + var amdDependencies = []; + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.isComment()) { + var amdDependency = this.getAmdDependency(trivia.fullText()); + if (amdDependency) { + amdDependencies.push(amdDependency); + } + } + } + + this._amdDependencies = amdDependencies; + }; + + Document.prototype.getAmdDependency = function (comment) { + var amdDependencyRegEx = /^\/\/\/\s*/gim; + var match = implicitImportRegEx.exec(trivia.fullText()); + + if (match) { + return new TypeScript.TextSpan(position, trivia.fullWidth()); + } + + return null; + }; + + Document.prototype.getTopLevelImportOrExportSpan = function (node) { + var firstToken; + var position = 0; + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var moduleElement = node.moduleElements.childAt(i); + + firstToken = moduleElement.firstToken(); + if (firstToken !== null && firstToken.tokenKind === 47 /* ExportKeyword */) { + return new TypeScript.TextSpan(position + firstToken.leadingTriviaWidth(), firstToken.width()); + } + + if (moduleElement.kind() === 133 /* ImportDeclaration */) { + var importDecl = moduleElement; + if (importDecl.moduleReference.kind() === 245 /* ExternalModuleReference */) { + return new TypeScript.TextSpan(position + importDecl.leadingTriviaWidth(), importDecl.width()); + } + } + + position += moduleElement.fullWidth(); + } + + return null; + ; + }; + + Document.prototype.sourceUnit = function () { + if (!this._sourceUnit) { + var start = new Date().getTime(); + var syntaxTree = this.syntaxTree(); + this._sourceUnit = TypeScript.SyntaxTreeToAstVisitor.visit(syntaxTree, this.fileName, this._compiler.compilationSettings(), this.isOpen); + TypeScript.astTranslationTime += new Date().getTime() - start; + + if (!this.isOpen) { + this._syntaxTree = null; + } + } + + return this._sourceUnit; + }; + + Document.prototype.diagnostics = function () { + if (this._diagnostics === null) { + this.syntaxTree(); + TypeScript.Debug.assert(this._diagnostics); + } + + return this._diagnostics; + }; + + Document.prototype.lineMap = function () { + if (this._lineMap === null) { + this.syntaxTree(); + TypeScript.Debug.assert(this._lineMap); + } + + return this._lineMap; + }; + + Document.prototype.isExternalModule = function () { + return this.externalModuleIndicatorSpan() !== null; + }; + + Document.prototype.externalModuleIndicatorSpan = function () { + if (this._externalModuleIndicatorSpan === undefined) { + this.syntaxTree(); + TypeScript.Debug.assert(this._externalModuleIndicatorSpan !== undefined); + } + + return this._externalModuleIndicatorSpan; + }; + + Document.prototype.amdDependencies = function () { + if (this._amdDependencies === undefined) { + this.syntaxTree(); + TypeScript.Debug.assert(this._amdDependencies !== undefined); + } + + return this._amdDependencies; + }; + + Document.prototype.syntaxTree = function () { + var result = this._syntaxTree; + if (!result) { + var start = new Date().getTime(); + + result = TypeScript.Parser.parse(this.fileName, TypeScript.SimpleText.fromScriptSnapshot(this._scriptSnapshot), TypeScript.isDTSFile(this.fileName), TypeScript.getParseOptions(this._compiler.compilationSettings())); + + TypeScript.syntaxTreeParseTime += new Date().getTime() - start; + + if (this.isOpen || !this._sourceUnit) { + this._syntaxTree = result; + } + } + + this.cacheSyntaxTreeInfo(result); + return result; + }; + + Document.prototype.bloomFilter = function () { + if (!this._bloomFilter) { + var identifiers = TypeScript.createIntrinsicsObject(); + var pre = function (cur) { + if (TypeScript.ASTHelpers.isValidAstNode(cur)) { + if (cur.kind() === 11 /* IdentifierName */) { + var nodeText = cur.valueText(); + + identifiers[nodeText] = true; + } + } + }; + + TypeScript.getAstWalkerFactory().simpleWalk(this.sourceUnit(), pre, null, identifiers); + + var identifierCount = 0; + for (var name in identifiers) { + if (identifiers[name]) { + identifierCount++; + } + } + + this._bloomFilter = new TypeScript.BloomFilter(identifierCount); + this._bloomFilter.addKeys(identifiers); + } + return this._bloomFilter; + }; + + Document.prototype.emitToOwnOutputFile = function () { + return !this._compiler.compilationSettings().outFileOption() || this.isExternalModule(); + }; + + Document.prototype.update = function (scriptSnapshot, version, isOpen, textChangeRange) { + var oldSyntaxTree = this._syntaxTree; + + if (textChangeRange !== null && TypeScript.Debug.shouldAssert(1 /* Normal */)) { + var oldText = this._scriptSnapshot; + var newText = scriptSnapshot; + + TypeScript.Debug.assert((oldText.getLength() - textChangeRange.span().length() + textChangeRange.newLength()) === newText.getLength()); + + if (TypeScript.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldTextPrefix = oldText.getText(0, textChangeRange.span().start()); + var newTextPrefix = newText.getText(0, textChangeRange.span().start()); + TypeScript.Debug.assert(oldTextPrefix === newTextPrefix); + + var oldTextSuffix = oldText.getText(textChangeRange.span().end(), oldText.getLength()); + var newTextSuffix = newText.getText(textChangeRange.newSpan().end(), newText.getLength()); + TypeScript.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + + var text = TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot); + + var newSyntaxTree = textChangeRange === null || oldSyntaxTree === null ? TypeScript.Parser.parse(this.fileName, text, TypeScript.isDTSFile(this.fileName), TypeScript.getParseOptions(this._compiler.compilationSettings())) : TypeScript.Parser.incrementalParse(oldSyntaxTree, textChangeRange, text); + + return new Document(this._compiler, this._semanticInfoChain, this.fileName, this.referencedFiles, scriptSnapshot, this.byteOrderMark, version, isOpen, newSyntaxTree, null); + }; + + Document.create = function (compiler, semanticInfoChain, fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles) { + return new Document(compiler, semanticInfoChain, fileName, referencedFiles, scriptSnapshot, byteOrderMark, version, isOpen, null, null); + }; + + Document.prototype.topLevelDecl = function () { + if (this._topLevelDecl === null) { + this._topLevelDecl = TypeScript.DeclarationCreator.create(this, this._semanticInfoChain, this._compiler.compilationSettings()); + } + + return this._topLevelDecl; + }; + + Document.prototype._getDeclForAST = function (ast) { + this.topLevelDecl(); + return this._astDeclMap[ast.syntaxID()]; + }; + + Document.prototype.getEnclosingDecl = function (ast) { + if (ast.kind() === 120 /* SourceUnit */) { + return this._getDeclForAST(ast); + } + + ast = ast.parent; + var decl = null; + while (ast) { + decl = this._getDeclForAST(ast); + + if (decl) { + break; + } + + ast = ast.parent; + } + + return decl._getEnclosingDeclFromParentDecl(); + }; + + Document.prototype._setDeclForAST = function (ast, decl) { + TypeScript.Debug.assert(decl.fileName() === this.fileName); + this._astDeclMap[ast.syntaxID()] = decl; + }; + + Document.prototype._getASTForDecl = function (decl) { + return this._declASTMap[decl.declID]; + }; + + Document.prototype._setASTForDecl = function (decl, ast) { + TypeScript.Debug.assert(decl.fileName() === this.fileName); + this._declASTMap[decl.declID] = ast; + }; + return Document; + })(); + TypeScript.Document = Document; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function hasFlag(val, flag) { + return (val & flag) !== 0; + } + TypeScript.hasFlag = hasFlag; + + (function (TypeRelationshipFlags) { + TypeRelationshipFlags[TypeRelationshipFlags["SuccessfulComparison"] = 0] = "SuccessfulComparison"; + TypeRelationshipFlags[TypeRelationshipFlags["RequiredPropertyIsMissing"] = 1 << 1] = "RequiredPropertyIsMissing"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleSignatures"] = 1 << 2] = "IncompatibleSignatures"; + TypeRelationshipFlags[TypeRelationshipFlags["SourceSignatureHasTooManyParameters"] = 3] = "SourceSignatureHasTooManyParameters"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleReturnTypes"] = 1 << 4] = "IncompatibleReturnTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatiblePropertyTypes"] = 1 << 5] = "IncompatiblePropertyTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleParameterTypes"] = 1 << 6] = "IncompatibleParameterTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["InconsistantPropertyAccesibility"] = 1 << 7] = "InconsistantPropertyAccesibility"; + })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); + var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; + + (function (ModuleGenTarget) { + ModuleGenTarget[ModuleGenTarget["Unspecified"] = 0] = "Unspecified"; + ModuleGenTarget[ModuleGenTarget["Synchronous"] = 1] = "Synchronous"; + ModuleGenTarget[ModuleGenTarget["Asynchronous"] = 2] = "Asynchronous"; + })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); + var ModuleGenTarget = TypeScript.ModuleGenTarget; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var proto = "__proto__"; + + 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; + + this[proto] = null; + this[proto] = undefined; + } + return BlockIntrinsics; + })(); + + function createIntrinsicsObject() { + return new BlockIntrinsics(); + } + TypeScript.createIntrinsicsObject = createIntrinsicsObject; + + var StringHashTable = (function () { + function StringHashTable() { + this.itemCount = 0; + this.table = createIntrinsicsObject(); + } + StringHashTable.prototype.getAllKeys = function () { + var result = []; + + for (var k in this.table) { + if (this.table[k] !== undefined) { + result.push(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]; + return data === undefined ? null : data; + }; + + StringHashTable.prototype.remove = function (key) { + if (this.table[key] !== undefined) { + this.table[key] = undefined; + this.itemCount--; + } + }; + return StringHashTable; + })(); + TypeScript.StringHashTable = StringHashTable; + + var IdentiferNameHashTable = (function (_super) { + __extends(IdentiferNameHashTable, _super); + function IdentiferNameHashTable() { + _super.apply(this, arguments); + } + IdentiferNameHashTable.prototype.getAllKeys = function () { + var result = []; + + _super.prototype.map.call(this, function (k, v, c) { + if (v !== undefined) { + result.push(k.substring(1)); + } + }, null); + + return result; + }; + + IdentiferNameHashTable.prototype.add = function (key, data) { + return _super.prototype.add.call(this, "#" + key, data); + }; + + IdentiferNameHashTable.prototype.addOrUpdate = function (key, data) { + return _super.prototype.addOrUpdate.call(this, "#" + key, data); + }; + + IdentiferNameHashTable.prototype.map = function (fn, context) { + return _super.prototype.map.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.every = function (fn, context) { + return _super.prototype.every.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.some = function (fn, context) { + return _super.prototype.some.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.lookup = function (key) { + return _super.prototype.lookup.call(this, "#" + key); + }; + return IdentiferNameHashTable; + })(StringHashTable); + TypeScript.IdentiferNameHashTable = IdentiferNameHashTable; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (ASTHelpers) { + function scriptIsElided(sourceUnit) { + return TypeScript.isDTSFile(sourceUnit.fileName()) || moduleMembersAreElided(sourceUnit.moduleElements); + } + ASTHelpers.scriptIsElided = scriptIsElided; + + function moduleIsElided(declaration) { + return TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) || moduleMembersAreElided(declaration.moduleElements); + } + ASTHelpers.moduleIsElided = moduleIsElided; + + function moduleMembersAreElided(members) { + for (var i = 0, n = members.childCount(); i < n; i++) { + var member = members.childAt(i); + + if (member.kind() === 130 /* ModuleDeclaration */) { + if (!moduleIsElided(member)) { + return false; + } + } else if (member.kind() !== 128 /* InterfaceDeclaration */) { + return false; + } + } + + return true; + } + + function enumIsElided(declaration) { + if (TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */)) { + return true; + } + + return false; + } + ASTHelpers.enumIsElided = enumIsElided; + + function isValidAstNode(ast) { + if (!ast) + return false; + + if (ast.start() === -1 || ast.end() === -1) + return false; + + return true; + } + ASTHelpers.isValidAstNode = isValidAstNode; + + function getAstAtPosition(script, pos, useTrailingTriviaAsLimChar, forceInclusive) { + if (typeof useTrailingTriviaAsLimChar === "undefined") { useTrailingTriviaAsLimChar = true; } + if (typeof forceInclusive === "undefined") { forceInclusive = false; } + var top = null; + + var pre = function (cur, walker) { + if (isValidAstNode(cur)) { + var isInvalid1 = cur.kind() === 149 /* ExpressionStatement */ && cur.width() === 0; + + if (isInvalid1) { + walker.options.goChildren = false; + } else { + var inclusive = forceInclusive || cur.kind() === 11 /* IdentifierName */ || cur.kind() === 212 /* MemberAccessExpression */ || cur.kind() === 121 /* QualifiedName */ || cur.kind() === 224 /* VariableDeclaration */ || cur.kind() === 225 /* VariableDeclarator */ || cur.kind() === 213 /* InvocationExpression */ || pos === script.end() + script.trailingTriviaWidth(); + + var minChar = cur.start(); + var limChar = cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0) + (inclusive ? 1 : 0); + if (pos >= minChar && pos < limChar) { + if ((cur.kind() !== 1 /* List */ && cur.kind() !== 2 /* SeparatedList */) || cur.end() > cur.start()) { + if (top === null) { + top = cur; + } else if (cur.start() >= top.start() && (cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0)) <= (top.end() + (useTrailingTriviaAsLimChar ? top.trailingTriviaWidth() : 0))) { + if (top.width() !== 0 || cur.width() !== 0) { + top = cur; + } + } + } + } + + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + }; + + TypeScript.getAstWalkerFactory().walk(script, pre); + return top; + } + ASTHelpers.getAstAtPosition = getAstAtPosition; + + function getExtendsHeritageClause(clauses) { + if (!clauses) { + return null; + } + + return clauses.firstOrDefault(function (c) { + return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 230 /* ExtendsHeritageClause */; + }); + } + ASTHelpers.getExtendsHeritageClause = getExtendsHeritageClause; + + function getImplementsHeritageClause(clauses) { + if (!clauses) { + return null; + } + + return clauses.firstOrDefault(function (c) { + return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 231 /* ImplementsHeritageClause */; + }); + } + ASTHelpers.getImplementsHeritageClause = getImplementsHeritageClause; + + function isCallExpression(ast) { + return (ast && ast.kind() === 213 /* InvocationExpression */) || (ast && ast.kind() === 216 /* ObjectCreationExpression */); + } + ASTHelpers.isCallExpression = isCallExpression; + + function isCallExpressionTarget(ast) { + if (!ast) { + return false; + } + + var current = ast; + + while (current && current.parent) { + if (current.parent.kind() === 212 /* MemberAccessExpression */ && current.parent.name === current) { + current = current.parent; + continue; + } + + break; + } + + if (current && current.parent) { + if (current.parent.kind() === 213 /* InvocationExpression */ || current.parent.kind() === 216 /* ObjectCreationExpression */) { + return current === current.parent.expression; + } + } + + return false; + } + ASTHelpers.isCallExpressionTarget = isCallExpressionTarget; + + function isNameOfSomeDeclaration(ast) { + if (ast === null || ast.parent === null) { + return false; + } + if (ast.kind() !== 11 /* IdentifierName */) { + return false; + } + + switch (ast.parent.kind()) { + case 131 /* ClassDeclaration */: + return ast.parent.identifier === ast; + case 128 /* InterfaceDeclaration */: + return ast.parent.identifier === ast; + case 132 /* EnumDeclaration */: + return ast.parent.identifier === ast; + case 130 /* ModuleDeclaration */: + return ast.parent.name === ast || ast.parent.stringLiteral === ast; + case 225 /* VariableDeclarator */: + return ast.parent.propertyName === ast; + case 129 /* FunctionDeclaration */: + return ast.parent.identifier === ast; + case 135 /* MemberFunctionDeclaration */: + return ast.parent.propertyName === ast; + case 242 /* Parameter */: + return ast.parent.identifier === ast; + case 238 /* TypeParameter */: + return ast.parent.identifier === ast; + case 240 /* SimplePropertyAssignment */: + return ast.parent.propertyName === ast; + case 241 /* FunctionPropertyAssignment */: + return ast.parent.propertyName === ast; + case 243 /* EnumElement */: + return ast.parent.propertyName === ast; + case 133 /* ImportDeclaration */: + return ast.parent.identifier === ast; + } + + return false; + } + + function isDeclarationASTOrDeclarationNameAST(ast) { + return isNameOfSomeDeclaration(ast) || isDeclarationAST(ast); + } + ASTHelpers.isDeclarationASTOrDeclarationNameAST = isDeclarationASTOrDeclarationNameAST; + + function getEnclosingParameterForInitializer(ast) { + var current = ast; + while (current) { + switch (current.kind()) { + case 232 /* EqualsValueClause */: + if (current.parent && current.parent.kind() === 242 /* Parameter */) { + return current.parent; + } + break; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + return null; + } + + current = current.parent; + } + return null; + } + ASTHelpers.getEnclosingParameterForInitializer = getEnclosingParameterForInitializer; + + function getEnclosingMemberVariableDeclaration(ast) { + var current = ast; + + while (current) { + switch (current.kind()) { + case 136 /* MemberVariableDeclaration */: + return current; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + return null; + } + current = current.parent; + } + + return null; + } + ASTHelpers.getEnclosingMemberVariableDeclaration = getEnclosingMemberVariableDeclaration; + + function isNameOfFunction(ast) { + return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 129 /* FunctionDeclaration */ && ast.parent.identifier === ast; + } + ASTHelpers.isNameOfFunction = isNameOfFunction; + + function isNameOfMemberFunction(ast) { + return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 135 /* MemberFunctionDeclaration */ && ast.parent.propertyName === ast; + } + ASTHelpers.isNameOfMemberFunction = isNameOfMemberFunction; + + function isNameOfMemberAccessExpression(ast) { + if (ast && ast.parent && ast.parent.kind() === 212 /* MemberAccessExpression */ && ast.parent.name === ast) { + return true; + } + + return false; + } + ASTHelpers.isNameOfMemberAccessExpression = isNameOfMemberAccessExpression; + + function isRightSideOfQualifiedName(ast) { + if (ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast) { + return true; + } + + return false; + } + ASTHelpers.isRightSideOfQualifiedName = isRightSideOfQualifiedName; + + function parentIsModuleDeclaration(ast) { + return ast.parent && ast.parent.kind() === 130 /* ModuleDeclaration */; + } + ASTHelpers.parentIsModuleDeclaration = parentIsModuleDeclaration; + + function parametersFromIdentifier(id) { + return { + length: 1, + lastParameterIsRest: function () { + return false; + }, + ast: id, + astAt: function (index) { + return id; + }, + identifierAt: function (index) { + return id; + }, + typeAt: function (index) { + return null; + }, + initializerAt: function (index) { + return null; + }, + isOptionalAt: function (index) { + return false; + } + }; + } + ASTHelpers.parametersFromIdentifier = parametersFromIdentifier; + + function parametersFromParameter(parameter) { + return { + length: 1, + lastParameterIsRest: function () { + return parameter.dotDotDotToken !== null; + }, + ast: parameter, + astAt: function (index) { + return parameter; + }, + identifierAt: function (index) { + return parameter.identifier; + }, + typeAt: function (index) { + return getType(parameter); + }, + initializerAt: function (index) { + return parameter.equalsValueClause; + }, + isOptionalAt: function (index) { + return parameterIsOptional(parameter); + } + }; + } + ASTHelpers.parametersFromParameter = parametersFromParameter; + + function parameterIsOptional(parameter) { + return parameter.questionToken !== null || parameter.equalsValueClause !== null; + } + + function parametersFromParameterList(list) { + return { + length: list.parameters.nonSeparatorCount(), + lastParameterIsRest: function () { + return TypeScript.lastParameterIsRest(list); + }, + ast: list.parameters, + astAt: function (index) { + return list.parameters.nonSeparatorAt(index); + }, + identifierAt: function (index) { + return list.parameters.nonSeparatorAt(index).identifier; + }, + typeAt: function (index) { + return getType(list.parameters.nonSeparatorAt(index)); + }, + initializerAt: function (index) { + return list.parameters.nonSeparatorAt(index).equalsValueClause; + }, + isOptionalAt: function (index) { + return parameterIsOptional(list.parameters.nonSeparatorAt(index)); + } + }; + } + ASTHelpers.parametersFromParameterList = parametersFromParameterList; + + function isDeclarationAST(ast) { + switch (ast.kind()) { + case 225 /* VariableDeclarator */: + return getVariableStatement(ast) !== null; + + case 133 /* ImportDeclaration */: + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 242 /* Parameter */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 144 /* IndexSignature */: + case 129 /* FunctionDeclaration */: + case 130 /* ModuleDeclaration */: + case 124 /* ArrayType */: + case 122 /* ObjectType */: + case 238 /* TypeParameter */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 136 /* MemberVariableDeclaration */: + case 138 /* IndexMemberDeclaration */: + case 132 /* EnumDeclaration */: + case 243 /* EnumElement */: + case 240 /* SimplePropertyAssignment */: + case 241 /* FunctionPropertyAssignment */: + case 222 /* FunctionExpression */: + case 142 /* CallSignature */: + case 143 /* ConstructSignature */: + case 145 /* MethodSignature */: + case 141 /* PropertySignature */: + return true; + default: + return false; + } + } + ASTHelpers.isDeclarationAST = isDeclarationAST; + + function docComments(ast) { + if (isDeclarationAST(ast)) { + var preComments = ast.kind() === 225 /* VariableDeclarator */ ? getVariableStatement(ast).preComments() : ast.preComments(); + + if (preComments && preComments.length > 0) { + var preCommentsLength = preComments.length; + var docComments = new Array(); + for (var i = preCommentsLength - 1; i >= 0; i--) { + if (isDocComment(preComments[i])) { + docComments.push(preComments[i]); + continue; + } + + break; + } + + return docComments.reverse(); + } + } + + return TypeScript.sentinelEmptyArray; + } + ASTHelpers.docComments = docComments; + + function isDocComment(comment) { + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + var fullText = comment.fullText(); + return fullText.charAt(2) === "*" && fullText.charAt(3) !== "/"; + } + + return false; + } + + function getParameterList(ast) { + if (ast) { + switch (ast.kind()) { + case 137 /* ConstructorDeclaration */: + return getParameterList(ast.callSignature); + case 129 /* FunctionDeclaration */: + return getParameterList(ast.callSignature); + case 218 /* ParenthesizedArrowFunctionExpression */: + return getParameterList(ast.callSignature); + case 143 /* ConstructSignature */: + return getParameterList(ast.callSignature); + case 135 /* MemberFunctionDeclaration */: + return getParameterList(ast.callSignature); + case 241 /* FunctionPropertyAssignment */: + return getParameterList(ast.callSignature); + case 222 /* FunctionExpression */: + return getParameterList(ast.callSignature); + case 145 /* MethodSignature */: + return getParameterList(ast.callSignature); + case 125 /* ConstructorType */: + return ast.parameterList; + case 123 /* FunctionType */: + return ast.parameterList; + case 142 /* CallSignature */: + return ast.parameterList; + case 139 /* GetAccessor */: + return ast.parameterList; + case 140 /* SetAccessor */: + return ast.parameterList; + } + } + + return null; + } + ASTHelpers.getParameterList = getParameterList; + + function getType(ast) { + if (ast) { + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + return getType(ast.callSignature); + case 218 /* ParenthesizedArrowFunctionExpression */: + return getType(ast.callSignature); + case 143 /* ConstructSignature */: + return getType(ast.callSignature); + case 135 /* MemberFunctionDeclaration */: + return getType(ast.callSignature); + case 241 /* FunctionPropertyAssignment */: + return getType(ast.callSignature); + case 222 /* FunctionExpression */: + return getType(ast.callSignature); + case 145 /* MethodSignature */: + return getType(ast.callSignature); + case 142 /* CallSignature */: + return getType(ast.typeAnnotation); + case 144 /* IndexSignature */: + return getType(ast.typeAnnotation); + case 141 /* PropertySignature */: + return getType(ast.typeAnnotation); + case 139 /* GetAccessor */: + return getType(ast.typeAnnotation); + case 242 /* Parameter */: + return getType(ast.typeAnnotation); + case 136 /* MemberVariableDeclaration */: + return getType(ast.variableDeclarator); + case 225 /* VariableDeclarator */: + return getType(ast.typeAnnotation); + case 236 /* CatchClause */: + return getType(ast.typeAnnotation); + case 125 /* ConstructorType */: + return ast.type; + case 123 /* FunctionType */: + return ast.type; + case 244 /* TypeAnnotation */: + return ast.type; + } + } + + return null; + } + ASTHelpers.getType = getType; + + function getVariableStatement(variableDeclarator) { + if (variableDeclarator && variableDeclarator.parent && variableDeclarator.parent.parent && variableDeclarator.parent.parent.parent && variableDeclarator.parent.kind() === 2 /* SeparatedList */ && variableDeclarator.parent.parent.kind() === 224 /* VariableDeclaration */ && variableDeclarator.parent.parent.parent.kind() === 148 /* VariableStatement */) { + return variableDeclarator.parent.parent.parent; + } + + return null; + } + + function getVariableDeclaratorModifiers(variableDeclarator) { + var variableStatement = getVariableStatement(variableDeclarator); + return variableStatement ? variableStatement.modifiers : TypeScript.sentinelEmptyArray; + } + ASTHelpers.getVariableDeclaratorModifiers = getVariableDeclaratorModifiers; + + function isIntegerLiteralAST(expression) { + if (expression) { + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + expression = expression.operand; + return expression.kind() === 13 /* NumericLiteral */ && TypeScript.IntegerUtilities.isInteger(expression.text()); + + case 13 /* NumericLiteral */: + var text = expression.text(); + return TypeScript.IntegerUtilities.isInteger(text) || TypeScript.IntegerUtilities.isHexInteger(text); + } + } + + return false; + } + ASTHelpers.isIntegerLiteralAST = isIntegerLiteralAST; + + function getEnclosingModuleDeclaration(ast) { + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + return ast; + } + + ast = ast.parent; + } + + return null; + } + ASTHelpers.getEnclosingModuleDeclaration = getEnclosingModuleDeclaration; + + function isEntireNameOfModuleDeclaration(nameAST) { + return parentIsModuleDeclaration(nameAST) && nameAST.parent.name === nameAST; + } + + function getModuleDeclarationFromNameAST(ast) { + if (ast) { + switch (ast.kind()) { + case 14 /* StringLiteral */: + if (parentIsModuleDeclaration(ast) && ast.parent.stringLiteral === ast) { + return ast.parent; + } + return null; + + case 11 /* IdentifierName */: + case 121 /* QualifiedName */: + if (isEntireNameOfModuleDeclaration(ast)) { + return ast.parent; + } + break; + + default: + return null; + } + + for (ast = ast.parent; ast && ast.kind() === 121 /* QualifiedName */; ast = ast.parent) { + if (isEntireNameOfModuleDeclaration(ast)) { + return ast.parent; + } + } + } + + return null; + } + ASTHelpers.getModuleDeclarationFromNameAST = getModuleDeclarationFromNameAST; + + function isLastNameOfModule(ast, astName) { + if (ast) { + if (ast.stringLiteral) { + return astName === ast.stringLiteral; + } else if (ast.name.kind() === 121 /* QualifiedName */) { + return astName === ast.name.right; + } else { + return astName === ast.name; + } + } + + return false; + } + ASTHelpers.isLastNameOfModule = isLastNameOfModule; + + function getNameOfIdenfierOrQualifiedName(name) { + if (name.kind() === 11 /* IdentifierName */) { + return name.text(); + } else { + TypeScript.Debug.assert(name.kind() == 121 /* QualifiedName */); + var dotExpr = name; + return getNameOfIdenfierOrQualifiedName(dotExpr.left) + "." + getNameOfIdenfierOrQualifiedName(dotExpr.right); + } + } + ASTHelpers.getNameOfIdenfierOrQualifiedName = getNameOfIdenfierOrQualifiedName; + + function getModuleNames(name, result) { + result = result || []; + + if (name.kind() === 121 /* QualifiedName */) { + getModuleNames(name.left, result); + result.push(name.right); + } else { + result.push(name); + } + + return result; + } + ASTHelpers.getModuleNames = getModuleNames; + })(TypeScript.ASTHelpers || (TypeScript.ASTHelpers = {})); + var ASTHelpers = TypeScript.ASTHelpers; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function walkListChildren(preAst, walker) { + for (var i = 0, n = preAst.childCount(); i < n; i++) { + walker.walk(preAst.childAt(i)); + } + } + + function walkThrowStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkPrefixUnaryExpressionChildren(preAst, walker) { + walker.walk(preAst.operand); + } + + function walkPostfixUnaryExpressionChildren(preAst, walker) { + walker.walk(preAst.operand); + } + + function walkDeleteExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkTypeArgumentListChildren(preAst, walker) { + walker.walk(preAst.typeArguments); + } + + function walkTypeOfExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkVoidExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkArgumentListChildren(preAst, walker) { + walker.walk(preAst.typeArgumentList); + walker.walk(preAst.arguments); + } + + function walkArrayLiteralExpressionChildren(preAst, walker) { + walker.walk(preAst.expressions); + } + + function walkSimplePropertyAssignmentChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.expression); + } + + function walkFunctionPropertyAssignmentChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkGetAccessorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.parameterList); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.block); + } + + function walkSeparatedListChildren(preAst, walker) { + for (var i = 0, n = preAst.nonSeparatorCount(); i < n; i++) { + walker.walk(preAst.nonSeparatorAt(i)); + } + } + + function walkSetAccessorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.parameterList); + walker.walk(preAst.block); + } + + function walkObjectLiteralExpressionChildren(preAst, walker) { + walker.walk(preAst.propertyAssignments); + } + + function walkCastExpressionChildren(preAst, walker) { + walker.walk(preAst.type); + walker.walk(preAst.expression); + } + + function walkParenthesizedExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkElementAccessExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentExpression); + } + + function walkMemberAccessExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.name); + } + + function walkQualifiedNameChildren(preAst, walker) { + walker.walk(preAst.left); + walker.walk(preAst.right); + } + + function walkBinaryExpressionChildren(preAst, walker) { + walker.walk(preAst.left); + walker.walk(preAst.right); + } + + function walkEqualsValueClauseChildren(preAst, walker) { + walker.walk(preAst.value); + } + + function walkTypeParameterChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.constraint); + } + + function walkTypeParameterListChildren(preAst, walker) { + walker.walk(preAst.typeParameters); + } + + function walkGenericTypeChildren(preAst, walker) { + walker.walk(preAst.name); + walker.walk(preAst.typeArgumentList); + } + + function walkTypeAnnotationChildren(preAst, walker) { + walker.walk(preAst.type); + } + + function walkTypeQueryChildren(preAst, walker) { + walker.walk(preAst.name); + } + + function walkInvocationExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentList); + } + + function walkObjectCreationExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentList); + } + + function walkTrinaryExpressionChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.whenTrue); + walker.walk(preAst.whenFalse); + } + + function walkFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkFunctionTypeChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.type); + } + + function walkParenthesizedArrowFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + walker.walk(preAst.expression); + } + + function walkSimpleArrowFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.block); + walker.walk(preAst.expression); + } + + function walkMemberFunctionDeclarationChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkFuncDeclChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkIndexMemberDeclarationChildren(preAst, walker) { + walker.walk(preAst.indexSignature); + } + + function walkIndexSignatureChildren(preAst, walker) { + walker.walk(preAst.parameter); + walker.walk(preAst.typeAnnotation); + } + + function walkCallSignatureChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.typeAnnotation); + } + + function walkConstraintChildren(preAst, walker) { + walker.walk(preAst.type); + } + + function walkConstructorDeclarationChildren(preAst, walker) { + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkConstructorTypeChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.type); + } + + function walkConstructSignatureChildren(preAst, walker) { + walker.walk(preAst.callSignature); + } + + function walkParameterChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.equalsValueClause); + } + + function walkParameterListChildren(preAst, walker) { + walker.walk(preAst.parameters); + } + + function walkPropertySignatureChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.typeAnnotation); + } + + function walkVariableDeclaratorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.equalsValueClause); + } + + function walkMemberVariableDeclarationChildren(preAst, walker) { + walker.walk(preAst.variableDeclarator); + } + + function walkMethodSignatureChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + } + + function walkReturnStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkForStatementChildren(preAst, walker) { + walker.walk(preAst.variableDeclaration); + walker.walk(preAst.initializer); + walker.walk(preAst.condition); + walker.walk(preAst.incrementor); + walker.walk(preAst.statement); + } + + function walkForInStatementChildren(preAst, walker) { + walker.walk(preAst.variableDeclaration); + walker.walk(preAst.left); + walker.walk(preAst.expression); + walker.walk(preAst.statement); + } + + function walkIfStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + walker.walk(preAst.elseClause); + } + + function walkElseClauseChildren(preAst, walker) { + walker.walk(preAst.statement); + } + + function walkWhileStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + + function walkDoStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + + function walkBlockChildren(preAst, walker) { + walker.walk(preAst.statements); + } + + function walkVariableDeclarationChildren(preAst, walker) { + walker.walk(preAst.declarators); + } + + function walkCaseSwitchClauseChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.statements); + } + + function walkDefaultSwitchClauseChildren(preAst, walker) { + walker.walk(preAst.statements); + } + + function walkSwitchStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.switchClauses); + } + + function walkTryStatementChildren(preAst, walker) { + walker.walk(preAst.block); + walker.walk(preAst.catchClause); + walker.walk(preAst.finallyClause); + } + + function walkCatchClauseChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.block); + } + + function walkExternalModuleReferenceChildren(preAst, walker) { + walker.walk(preAst.stringLiteral); + } + + function walkFinallyClauseChildren(preAst, walker) { + walker.walk(preAst.block); + } + + function walkClassDeclChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeParameterList); + walker.walk(preAst.heritageClauses); + walker.walk(preAst.classElements); + } + + function walkScriptChildren(preAst, walker) { + walker.walk(preAst.moduleElements); + } + + function walkHeritageClauseChildren(preAst, walker) { + walker.walk(preAst.typeNames); + } + + function walkInterfaceDeclerationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeParameterList); + walker.walk(preAst.heritageClauses); + walker.walk(preAst.body); + } + + function walkObjectTypeChildren(preAst, walker) { + walker.walk(preAst.typeMembers); + } + + function walkArrayTypeChildren(preAst, walker) { + walker.walk(preAst.type); + } + + function walkModuleDeclarationChildren(preAst, walker) { + walker.walk(preAst.name); + walker.walk(preAst.stringLiteral); + walker.walk(preAst.moduleElements); + } + + function walkModuleNameModuleReferenceChildren(preAst, walker) { + walker.walk(preAst.moduleName); + } + + function walkEnumDeclarationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.enumElements); + } + + function walkEnumElementChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.equalsValueClause); + } + + function walkImportDeclarationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.moduleReference); + } + + function walkExportAssignmentChildren(preAst, walker) { + walker.walk(preAst.identifier); + } + + function walkWithStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + + function walkExpressionStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkLabeledStatementChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.statement); + } + + function walkVariableStatementChildren(preAst, walker) { + walker.walk(preAst.declaration); + } + + var childrenWalkers = new Array(246 /* Last */ + 1); + + for (var i = 9 /* FirstToken */, n = 119 /* LastToken */; i <= n; i++) { + childrenWalkers[i] = null; + } + for (var i = 4 /* FirstTrivia */, n = 8 /* LastTrivia */; i <= n; i++) { + childrenWalkers[i] = null; + } + + childrenWalkers[175 /* AddAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[208 /* AddExpression */] = walkBinaryExpressionChildren; + childrenWalkers[180 /* AndAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[60 /* AnyKeyword */] = null; + childrenWalkers[226 /* ArgumentList */] = walkArgumentListChildren; + childrenWalkers[214 /* ArrayLiteralExpression */] = walkArrayLiteralExpressionChildren; + childrenWalkers[124 /* ArrayType */] = walkArrayTypeChildren; + childrenWalkers[219 /* SimpleArrowFunctionExpression */] = walkSimpleArrowFunctionExpressionChildren; + childrenWalkers[218 /* ParenthesizedArrowFunctionExpression */] = walkParenthesizedArrowFunctionExpressionChildren; + childrenWalkers[174 /* AssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[191 /* BitwiseAndExpression */] = walkBinaryExpressionChildren; + childrenWalkers[190 /* BitwiseExclusiveOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[166 /* BitwiseNotExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[189 /* BitwiseOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[146 /* Block */] = walkBlockChildren; + childrenWalkers[61 /* BooleanKeyword */] = null; + childrenWalkers[152 /* BreakStatement */] = null; + childrenWalkers[142 /* CallSignature */] = walkCallSignatureChildren; + childrenWalkers[233 /* CaseSwitchClause */] = walkCaseSwitchClauseChildren; + childrenWalkers[220 /* CastExpression */] = walkCastExpressionChildren; + childrenWalkers[236 /* CatchClause */] = walkCatchClauseChildren; + childrenWalkers[131 /* ClassDeclaration */] = walkClassDeclChildren; + childrenWalkers[173 /* CommaExpression */] = walkBinaryExpressionChildren; + childrenWalkers[186 /* ConditionalExpression */] = walkTrinaryExpressionChildren; + childrenWalkers[239 /* Constraint */] = walkConstraintChildren; + childrenWalkers[137 /* ConstructorDeclaration */] = walkConstructorDeclarationChildren; + childrenWalkers[143 /* ConstructSignature */] = walkConstructSignatureChildren; + childrenWalkers[153 /* ContinueStatement */] = null; + childrenWalkers[125 /* ConstructorType */] = walkConstructorTypeChildren; + childrenWalkers[162 /* DebuggerStatement */] = null; + childrenWalkers[234 /* DefaultSwitchClause */] = walkDefaultSwitchClauseChildren; + childrenWalkers[170 /* DeleteExpression */] = walkDeleteExpressionChildren; + childrenWalkers[178 /* DivideAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[206 /* DivideExpression */] = walkBinaryExpressionChildren; + childrenWalkers[161 /* DoStatement */] = walkDoStatementChildren; + childrenWalkers[221 /* ElementAccessExpression */] = walkElementAccessExpressionChildren; + childrenWalkers[235 /* ElseClause */] = walkElseClauseChildren; + childrenWalkers[156 /* EmptyStatement */] = null; + childrenWalkers[132 /* EnumDeclaration */] = walkEnumDeclarationChildren; + childrenWalkers[243 /* EnumElement */] = walkEnumElementChildren; + childrenWalkers[194 /* EqualsExpression */] = walkBinaryExpressionChildren; + childrenWalkers[232 /* EqualsValueClause */] = walkEqualsValueClauseChildren; + childrenWalkers[192 /* EqualsWithTypeConversionExpression */] = walkBinaryExpressionChildren; + childrenWalkers[181 /* ExclusiveOrAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[134 /* ExportAssignment */] = walkExportAssignmentChildren; + childrenWalkers[149 /* ExpressionStatement */] = walkExpressionStatementChildren; + childrenWalkers[230 /* ExtendsHeritageClause */] = walkHeritageClauseChildren; + childrenWalkers[245 /* ExternalModuleReference */] = walkExternalModuleReferenceChildren; + childrenWalkers[24 /* FalseKeyword */] = null; + childrenWalkers[237 /* FinallyClause */] = walkFinallyClauseChildren; + childrenWalkers[155 /* ForInStatement */] = walkForInStatementChildren; + childrenWalkers[154 /* ForStatement */] = walkForStatementChildren; + childrenWalkers[129 /* FunctionDeclaration */] = walkFuncDeclChildren; + childrenWalkers[222 /* FunctionExpression */] = walkFunctionExpressionChildren; + childrenWalkers[241 /* FunctionPropertyAssignment */] = walkFunctionPropertyAssignmentChildren; + childrenWalkers[123 /* FunctionType */] = walkFunctionTypeChildren; + childrenWalkers[126 /* GenericType */] = walkGenericTypeChildren; + childrenWalkers[139 /* GetAccessor */] = walkGetAccessorChildren; + childrenWalkers[197 /* GreaterThanExpression */] = walkBinaryExpressionChildren; + childrenWalkers[199 /* GreaterThanOrEqualExpression */] = walkBinaryExpressionChildren; + childrenWalkers[147 /* IfStatement */] = walkIfStatementChildren; + childrenWalkers[231 /* ImplementsHeritageClause */] = walkHeritageClauseChildren; + childrenWalkers[133 /* ImportDeclaration */] = walkImportDeclarationChildren; + childrenWalkers[138 /* IndexMemberDeclaration */] = walkIndexMemberDeclarationChildren; + childrenWalkers[144 /* IndexSignature */] = walkIndexSignatureChildren; + childrenWalkers[201 /* InExpression */] = walkBinaryExpressionChildren; + childrenWalkers[200 /* InstanceOfExpression */] = walkBinaryExpressionChildren; + childrenWalkers[128 /* InterfaceDeclaration */] = walkInterfaceDeclerationChildren; + childrenWalkers[213 /* InvocationExpression */] = walkInvocationExpressionChildren; + childrenWalkers[160 /* LabeledStatement */] = walkLabeledStatementChildren; + childrenWalkers[183 /* LeftShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[202 /* LeftShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[196 /* LessThanExpression */] = walkBinaryExpressionChildren; + childrenWalkers[198 /* LessThanOrEqualExpression */] = walkBinaryExpressionChildren; + childrenWalkers[1 /* List */] = walkListChildren; + childrenWalkers[188 /* LogicalAndExpression */] = walkBinaryExpressionChildren; + childrenWalkers[167 /* LogicalNotExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[187 /* LogicalOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[212 /* MemberAccessExpression */] = walkMemberAccessExpressionChildren; + childrenWalkers[135 /* MemberFunctionDeclaration */] = walkMemberFunctionDeclarationChildren; + childrenWalkers[136 /* MemberVariableDeclaration */] = walkMemberVariableDeclarationChildren; + childrenWalkers[145 /* MethodSignature */] = walkMethodSignatureChildren; + childrenWalkers[130 /* ModuleDeclaration */] = walkModuleDeclarationChildren; + childrenWalkers[246 /* ModuleNameModuleReference */] = walkModuleNameModuleReferenceChildren; + childrenWalkers[179 /* ModuloAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[207 /* ModuloExpression */] = walkBinaryExpressionChildren; + childrenWalkers[177 /* MultiplyAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[205 /* MultiplyExpression */] = walkBinaryExpressionChildren; + childrenWalkers[11 /* IdentifierName */] = null; + childrenWalkers[165 /* NegateExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[0 /* None */] = null; + childrenWalkers[195 /* NotEqualsExpression */] = walkBinaryExpressionChildren; + childrenWalkers[193 /* NotEqualsWithTypeConversionExpression */] = walkBinaryExpressionChildren; + childrenWalkers[32 /* NullKeyword */] = null; + childrenWalkers[67 /* NumberKeyword */] = null; + childrenWalkers[13 /* NumericLiteral */] = null; + childrenWalkers[216 /* ObjectCreationExpression */] = walkObjectCreationExpressionChildren; + childrenWalkers[215 /* ObjectLiteralExpression */] = walkObjectLiteralExpressionChildren; + childrenWalkers[122 /* ObjectType */] = walkObjectTypeChildren; + childrenWalkers[223 /* OmittedExpression */] = null; + childrenWalkers[182 /* OrAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[242 /* Parameter */] = walkParameterChildren; + childrenWalkers[227 /* ParameterList */] = walkParameterListChildren; + childrenWalkers[217 /* ParenthesizedExpression */] = walkParenthesizedExpressionChildren; + childrenWalkers[164 /* PlusExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[211 /* PostDecrementExpression */] = walkPostfixUnaryExpressionChildren; + childrenWalkers[210 /* PostIncrementExpression */] = walkPostfixUnaryExpressionChildren; + childrenWalkers[169 /* PreDecrementExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[168 /* PreIncrementExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[141 /* PropertySignature */] = walkPropertySignatureChildren; + childrenWalkers[121 /* QualifiedName */] = walkQualifiedNameChildren; + childrenWalkers[12 /* RegularExpressionLiteral */] = null; + childrenWalkers[150 /* ReturnStatement */] = walkReturnStatementChildren; + childrenWalkers[120 /* SourceUnit */] = walkScriptChildren; + childrenWalkers[2 /* SeparatedList */] = walkSeparatedListChildren; + childrenWalkers[140 /* SetAccessor */] = walkSetAccessorChildren; + childrenWalkers[184 /* SignedRightShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[203 /* SignedRightShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[240 /* SimplePropertyAssignment */] = walkSimplePropertyAssignmentChildren; + childrenWalkers[14 /* StringLiteral */] = null; + childrenWalkers[69 /* StringKeyword */] = null; + childrenWalkers[176 /* SubtractAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[209 /* SubtractExpression */] = walkBinaryExpressionChildren; + childrenWalkers[50 /* SuperKeyword */] = null; + childrenWalkers[151 /* SwitchStatement */] = walkSwitchStatementChildren; + childrenWalkers[35 /* ThisKeyword */] = null; + childrenWalkers[157 /* ThrowStatement */] = walkThrowStatementChildren; + childrenWalkers[3 /* TriviaList */] = null; + childrenWalkers[37 /* TrueKeyword */] = null; + childrenWalkers[159 /* TryStatement */] = walkTryStatementChildren; + childrenWalkers[244 /* TypeAnnotation */] = walkTypeAnnotationChildren; + childrenWalkers[228 /* TypeArgumentList */] = walkTypeArgumentListChildren; + childrenWalkers[171 /* TypeOfExpression */] = walkTypeOfExpressionChildren; + childrenWalkers[238 /* TypeParameter */] = walkTypeParameterChildren; + childrenWalkers[229 /* TypeParameterList */] = walkTypeParameterListChildren; + childrenWalkers[127 /* TypeQuery */] = walkTypeQueryChildren; + childrenWalkers[185 /* UnsignedRightShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[204 /* UnsignedRightShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[224 /* VariableDeclaration */] = walkVariableDeclarationChildren; + childrenWalkers[225 /* VariableDeclarator */] = walkVariableDeclaratorChildren; + childrenWalkers[148 /* VariableStatement */] = walkVariableStatementChildren; + childrenWalkers[172 /* VoidExpression */] = walkVoidExpressionChildren; + childrenWalkers[41 /* VoidKeyword */] = null; + childrenWalkers[158 /* WhileStatement */] = walkWhileStatementChildren; + childrenWalkers[163 /* WithStatement */] = walkWithStatementChildren; + + for (var e in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind.hasOwnProperty(e) && TypeScript.StringUtilities.isString(TypeScript.SyntaxKind[e])) { + TypeScript.Debug.assert(childrenWalkers[e] !== undefined, "Fix initWalkers: " + TypeScript.SyntaxKind[e]); + } + } + + var AstWalkOptions = (function () { + function AstWalkOptions() { + this.goChildren = true; + this.stopWalking = false; + } + return AstWalkOptions; + })(); + TypeScript.AstWalkOptions = AstWalkOptions; + + var SimplePreAstWalker = (function () { + function SimplePreAstWalker(pre, state) { + this.pre = pre; + this.state = state; + this.options = new AstWalkOptions(); + } + SimplePreAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + + this.pre(ast, this.state); + + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + }; + return SimplePreAstWalker; + })(); + + var SimplePrePostAstWalker = (function () { + function SimplePrePostAstWalker(pre, post, state) { + this.pre = pre; + this.post = post; + this.state = state; + this.options = new AstWalkOptions(); + } + SimplePrePostAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + + this.pre(ast, this.state); + + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + + this.post(ast, this.state); + }; + return SimplePrePostAstWalker; + })(); + + var NormalAstWalker = (function () { + function NormalAstWalker(pre, post, state) { + this.pre = pre; + this.post = post; + this.state = state; + this.options = new AstWalkOptions(); + } + NormalAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + + if (this.options.stopWalking) { + return; + } + + this.pre(ast, this); + + if (this.options.stopWalking) { + return; + } + + if (this.options.goChildren) { + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + } else { + this.options.goChildren = true; + } + + if (this.post) { + this.post(ast, this); + } + }; + return NormalAstWalker; + })(); + + var AstWalkerFactory = (function () { + function AstWalkerFactory() { + } + AstWalkerFactory.prototype.walk = function (ast, pre, post, state) { + new NormalAstWalker(pre, post, state).walk(ast); + }; + + AstWalkerFactory.prototype.simpleWalk = function (ast, pre, post, state) { + if (post) { + new SimplePrePostAstWalker(pre, post, state).walk(ast); + } else { + new SimplePreAstWalker(pre, state).walk(ast); + } + }; + return AstWalkerFactory; + })(); + TypeScript.AstWalkerFactory = AstWalkerFactory; + + var globalAstWalkerFactory = new AstWalkerFactory(); + + function getAstWalkerFactory() { + return globalAstWalkerFactory; + } + TypeScript.getAstWalkerFactory = getAstWalkerFactory; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Base64Format = (function () { + function Base64Format() { + } + Base64Format.encode = function (inValue) { + if (inValue < 64) { + return Base64Format.encodedValues.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + }; + + Base64Format.decodeChar = function (inChar) { + if (inChar.length === 1) { + return Base64Format.encodedValues.indexOf(inChar); + } else { + throw TypeError('"' + inChar + '" must have length 1'); + } + }; + Base64Format.encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + return Base64Format; + })(); + + var Base64VLQFormat = (function () { + function Base64VLQFormat() { + } + Base64VLQFormat.encode = function (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 (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(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Base64_value_0_finished_with_a_continuation_bit, [inString])); + }; + return Base64VLQFormat; + })(); + TypeScript.Base64VLQFormat = Base64VLQFormat; +})(TypeScript || (TypeScript = {})); +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 SourceMapEntry = (function () { + function SourceMapEntry(emittedFile, emittedLine, emittedColumn, sourceFile, sourceLine, sourceColumn, sourceName) { + this.emittedFile = emittedFile; + this.emittedLine = emittedLine; + this.emittedColumn = emittedColumn; + this.sourceFile = sourceFile; + this.sourceLine = sourceLine; + this.sourceColumn = sourceColumn; + this.sourceName = sourceName; + TypeScript.Debug.assert(isFinite(emittedLine)); + TypeScript.Debug.assert(isFinite(emittedColumn)); + TypeScript.Debug.assert(isFinite(sourceColumn)); + TypeScript.Debug.assert(isFinite(sourceLine)); + } + return SourceMapEntry; + })(); + TypeScript.SourceMapEntry = SourceMapEntry; + + var SourceMapper = (function () { + function SourceMapper(jsFile, sourceMapOut, document, jsFilePath, emitOptions, resolvePath) { + this.jsFile = jsFile; + this.sourceMapOut = sourceMapOut; + this.names = []; + this.mappingLevel = []; + this.tsFilePaths = []; + this.allSourceMappings = []; + this.sourceMapEntries = []; + this.setSourceMapOptions(document, jsFilePath, emitOptions, resolvePath); + this.setNewSourceFile(document, emitOptions); + } + SourceMapper.prototype.getOutputFile = function () { + var result = this.sourceMapOut.getOutputFile(); + result.sourceMapEntries = this.sourceMapEntries; + + return result; + }; + + SourceMapper.prototype.increaseMappingLevel = function (ast) { + this.mappingLevel.push(ast); + }; + + SourceMapper.prototype.decreaseMappingLevel = function (ast) { + TypeScript.Debug.assert(this.mappingLevel.length > 0, "Mapping level should never be less than 0. This suggests a missing start call."); + var expectedAst = this.mappingLevel.pop(); + var expectedAstInfo = expectedAst.kind ? TypeScript.SyntaxKind[expectedAst.kind()] : [expectedAst.start(), expectedAst.end()]; + var astInfo = ast.kind ? TypeScript.SyntaxKind[ast.kind()] : [ast.start(), ast.end()]; + TypeScript.Debug.assert(ast === expectedAst, "Provided ast is not the expected AST, Expected: " + expectedAstInfo + " Given: " + astInfo); + }; + + SourceMapper.prototype.setNewSourceFile = function (document, emitOptions) { + var sourceMappings = []; + this.allSourceMappings.push(sourceMappings); + this.currentMappings = [sourceMappings]; + this.currentNameIndex = []; + + this.setNewSourceFilePath(document, emitOptions); + }; + + SourceMapper.prototype.setSourceMapOptions = function (document, jsFilePath, emitOptions, resolvePath) { + var prettyJsFileName = TypeScript.getPrettyName(jsFilePath, false, true); + var prettyMapFileName = prettyJsFileName + SourceMapper.MapFileExtension; + this.jsFileName = prettyJsFileName; + + if (emitOptions.sourceMapRootDirectory()) { + this.sourceMapDirectory = emitOptions.sourceMapRootDirectory(); + if (document.emitToOwnOutputFile()) { + this.sourceMapDirectory = this.sourceMapDirectory + TypeScript.switchToForwardSlashes(TypeScript.getRootFilePath((document.fileName)).replace(emitOptions.commonDirectoryPath(), "")); + } + + if (TypeScript.isRelative(this.sourceMapDirectory)) { + this.sourceMapDirectory = emitOptions.commonDirectoryPath() + this.sourceMapDirectory; + this.sourceMapDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(resolvePath(this.sourceMapDirectory))); + this.sourceMapPath = TypeScript.getRelativePathToFixedPath(TypeScript.getRootFilePath(jsFilePath), this.sourceMapDirectory + prettyMapFileName); + } else { + this.sourceMapPath = this.sourceMapDirectory + prettyMapFileName; + } + } else { + this.sourceMapPath = prettyMapFileName; + this.sourceMapDirectory = TypeScript.getRootFilePath(jsFilePath); + } + this.sourceRoot = emitOptions.sourceRootDirectory(); + }; + + SourceMapper.prototype.setNewSourceFilePath = function (document, emitOptions) { + var tsFilePath = TypeScript.switchToForwardSlashes(document.fileName); + if (emitOptions.sourceRootDirectory()) { + tsFilePath = TypeScript.getRelativePathToFixedPath(emitOptions.commonDirectoryPath(), tsFilePath); + } else { + tsFilePath = TypeScript.getRelativePathToFixedPath(this.sourceMapDirectory, tsFilePath); + } + this.tsFilePaths.push(tsFilePath); + }; + + SourceMapper.prototype.emitSourceMapping = function () { + var _this = this; + TypeScript.Debug.assert(this.mappingLevel.length === 0, "Mapping level is not 0. This suggest a missing end call. Value: " + this.mappingLevel.map(function (item) { + return ['Node of type', TypeScript.SyntaxKind[item.kind()], 'at', item.start(), 'to', item.end()].join(' '); + }).join(', ')); + + this.jsFile.WriteLine("//# sourceMappingURL=" + this.sourceMapPath); + + var mappingsString = ""; + + var prevEmittedColumn = 0; + var prevEmittedLine = 0; + var prevSourceColumn = 0; + var prevSourceLine = 0; + var prevSourceIndex = 0; + var prevNameIndex = 0; + var emitComma = false; + + var recordedPosition = null; + for (var sourceIndex = 0; sourceIndex < this.tsFilePaths.length; sourceIndex++) { + 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 + ","; + } + + _this.sourceMapEntries.push(new SourceMapEntry(_this.jsFileName, mappedPosition.emittedLine + 1, mappedPosition.emittedColumn + 1, _this.tsFilePaths[sourceIndex], mappedPosition.sourceLine, mappedPosition.sourceColumn + 1, nameIndex >= 0 ? _this.names[nameIndex] : undefined)); + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.emittedColumn - prevEmittedColumn); + prevEmittedColumn = mappedPosition.emittedColumn; + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(sourceIndex - prevSourceIndex); + prevSourceIndex = sourceIndex; + + 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(nameIndex - prevNameIndex); + prevNameIndex = 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(this.allSourceMappings[sourceIndex]); + } + + this.sourceMapOut.Write(JSON.stringify({ + version: 3, + file: this.jsFileName, + sourceRoot: this.sourceRoot, + sources: this.tsFilePaths, + names: this.names, + mappings: mappingsString + })); + + this.sourceMapOut.Close(); + }; + SourceMapper.MapFileExtension = ".map"; + return SourceMapper; + })(); + TypeScript.SourceMapper = SourceMapper; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (EmitContainer) { + EmitContainer[EmitContainer["Prog"] = 0] = "Prog"; + EmitContainer[EmitContainer["Module"] = 1] = "Module"; + EmitContainer[EmitContainer["DynamicModule"] = 2] = "DynamicModule"; + EmitContainer[EmitContainer["Class"] = 3] = "Class"; + EmitContainer[EmitContainer["Constructor"] = 4] = "Constructor"; + EmitContainer[EmitContainer["Function"] = 5] = "Function"; + EmitContainer[EmitContainer["Args"] = 6] = "Args"; + EmitContainer[EmitContainer["Interface"] = 7] = "Interface"; + })(TypeScript.EmitContainer || (TypeScript.EmitContainer = {})); + var EmitContainer = TypeScript.EmitContainer; + + var EmitState = (function () { + function EmitState() { + this.column = 0; + this.line = 0; + this.container = 0 /* Prog */; + } + return EmitState; + })(); + TypeScript.EmitState = EmitState; + + var EmitOptions = (function () { + function EmitOptions(compiler, resolvePath) { + this.resolvePath = resolvePath; + this._diagnostic = null; + this._settings = null; + this._commonDirectoryPath = ""; + this._sharedOutputFile = ""; + this._sourceRootDirectory = ""; + this._sourceMapRootDirectory = ""; + this._outputDirectory = ""; + var settings = compiler.compilationSettings(); + this._settings = settings; + + if (settings.moduleGenTarget() === 0 /* Unspecified */) { + var fileNames = compiler.fileNames(); + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = compiler.getDocument(fileNames[i]); + if (!document.isDeclareFile() && document.isExternalModule()) { + var errorSpan = document.externalModuleIndicatorSpan(); + this._diagnostic = new TypeScript.Diagnostic(document.fileName, document.lineMap(), errorSpan.start(), errorSpan.length(), TypeScript.DiagnosticCode.Cannot_compile_external_modules_unless_the_module_flag_is_provided); + + return; + } + } + } + + if (!settings.mapSourceFiles()) { + if (settings.mapRoot()) { + if (settings.sourceRoot()) { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Options_mapRoot_and_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option, null); + return; + } else { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option, null); + return; + } + } else if (settings.sourceRoot()) { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option, null); + return; + } + } + + this._sourceMapRootDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(settings.mapRoot())); + this._sourceRootDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(settings.sourceRoot())); + + if (settings.outFileOption() || settings.outDirOption() || settings.mapRoot() || settings.sourceRoot()) { + if (settings.outFileOption()) { + this._sharedOutputFile = TypeScript.switchToForwardSlashes(resolvePath(settings.outFileOption())); + } + + if (settings.outDirOption()) { + this._outputDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(resolvePath(settings.outDirOption()))); + } + + if (this._outputDirectory || this._sourceMapRootDirectory || this.sourceRootDirectory) { + this.determineCommonDirectoryPath(compiler); + } + } + } + EmitOptions.prototype.diagnostic = function () { + return this._diagnostic; + }; + + EmitOptions.prototype.commonDirectoryPath = function () { + return this._commonDirectoryPath; + }; + EmitOptions.prototype.sharedOutputFile = function () { + return this._sharedOutputFile; + }; + EmitOptions.prototype.sourceRootDirectory = function () { + return this._sourceRootDirectory; + }; + EmitOptions.prototype.sourceMapRootDirectory = function () { + return this._sourceMapRootDirectory; + }; + EmitOptions.prototype.outputDirectory = function () { + return this._outputDirectory; + }; + + EmitOptions.prototype.compilationSettings = function () { + return this._settings; + }; + + EmitOptions.prototype.determineCommonDirectoryPath = function (compiler) { + var commonComponents = []; + var commonComponentsLength = -1; + + var fileNames = compiler.fileNames(); + for (var i = 0, len = fileNames.length; i < len; i++) { + var fileName = fileNames[i]; + var document = compiler.getDocument(fileNames[i]); + var sourceUnit = document.sourceUnit(); + + if (!document.isDeclareFile()) { + 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) { + var isDynamicModuleCompilation = TypeScript.ArrayUtilities.any(fileNames, function (fileName) { + document = compiler.getDocument(fileName); + return !document.isDeclareFile() && document.isExternalModule(); + }); + + if (this._outputDirectory || this._sourceRootDirectory || (this._sourceMapRootDirectory && (!this._sharedOutputFile || isDynamicModuleCompilation))) { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Cannot_find_the_common_subdirectory_path_for_the_input_files, null); + return; + } + + return; + } + + break; + } + } + + if (!updatedPath && fileComponents.length < commonComponentsLength) { + commonComponentsLength = fileComponents.length; + } + } + } + } + + this._commonDirectoryPath = commonComponents.slice(0, commonComponentsLength).join("/") + "/"; + }; + return EmitOptions; + })(); + TypeScript.EmitOptions = EmitOptions; + + var Indenter = (function () { + function Indenter() { + this.indentAmt = 0; + } + 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; + }; + Indenter.indentStep = 4; + Indenter.indentStepString = " "; + Indenter.indentStrings = []; + return Indenter; + })(); + TypeScript.Indenter = Indenter; + + function lastParameterIsRest(parameterList) { + var parameters = parameterList.parameters; + return parameters.nonSeparatorCount() > 0 && parameters.nonSeparatorAt(parameters.nonSeparatorCount() - 1).dotDotDotToken !== null; + } + TypeScript.lastParameterIsRest = lastParameterIsRest; + + var Emitter = (function () { + function Emitter(emittingFileName, outfile, emitOptions, semanticInfoChain) { + this.emittingFileName = emittingFileName; + this.outfile = outfile; + this.emitOptions = emitOptions; + this.semanticInfoChain = semanticInfoChain; + this.globalThisCapturePrologueEmitted = false; + this.extendsPrologueEmitted = false; + this.thisClassNode = null; + this.inArrowFunction = false; + this.moduleName = ""; + this.emitState = new EmitState(); + this.indenter = new Indenter(); + this.sourceMapper = null; + this.captureThisStmtString = "var _this = this;"; + this.declStack = []; + this.exportAssignment = null; + this.inWithBlock = false; + this.document = null; + this.detachedCommentsElement = null; + } + Emitter.prototype.pushDecl = function (decl) { + if (decl) { + this.declStack[this.declStack.length] = decl; + } + }; + + Emitter.prototype.popDecl = function (decl) { + if (decl) { + this.declStack.length--; + } + }; + + Emitter.prototype.getEnclosingDecl = function () { + var declStackLen = this.declStack.length; + var enclosingDecl = declStackLen > 0 ? this.declStack[declStackLen - 1] : null; + return enclosingDecl; + }; + + Emitter.prototype.setExportAssignment = function (exportAssignment) { + this.exportAssignment = exportAssignment; + }; + + Emitter.prototype.getExportAssignment = function () { + return this.exportAssignment; + }; + + Emitter.prototype.setDocument = function (document) { + this.document = document; + }; + + Emitter.prototype.shouldEmitImportDeclaration = function (importDeclAST) { + var isExternalModuleReference = importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */; + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); + var isExported = TypeScript.hasFlag(importDecl.flags, 1 /* Exported */); + var isAmdCodeGen = this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */; + + if (isExternalModuleReference && !isExported && isAmdCodeGen) { + return false; + } + + var importSymbol = importDecl.getSymbol(); + if (importSymbol.isUsedAsValue()) { + return true; + } + + if (importDeclAST.moduleReference.kind() !== 245 /* ExternalModuleReference */) { + var canBeUsedExternally = isExported || importSymbol.typeUsedExternally() || importSymbol.isUsedInExportedAlias(); + if (!canBeUsedExternally && !this.document.isExternalModule()) { + canBeUsedExternally = TypeScript.hasFlag(importDecl.getParentDecl().kind, 1 /* Script */ | 32 /* DynamicModule */); + } + + if (canBeUsedExternally) { + if (importSymbol.getExportAssignedValueSymbol()) { + return true; + } + + var containerSymbol = importSymbol.getExportAssignedContainerSymbol(); + if (containerSymbol && containerSymbol.getInstanceSymbol()) { + return true; + } + } + } + + return false; + }; + + Emitter.prototype.emitImportDeclaration = function (importDeclAST) { + var isExternalModuleReference = importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */; + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); + var isExported = TypeScript.hasFlag(importDecl.flags, 1 /* Exported */); + var isAmdCodeGen = this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */; + + this.emitComments(importDeclAST, true); + + var importSymbol = importDecl.getSymbol(); + + var parentSymbol = importSymbol.getContainer(); + var parentKind = parentSymbol ? parentSymbol.kind : 0 /* None */; + var associatedParentSymbol = parentSymbol ? parentSymbol.getAssociatedContainerType() : null; + var associatedParentSymbolKind = associatedParentSymbol ? associatedParentSymbol.kind : 0 /* None */; + + var needsPropertyAssignment = false; + var usePropertyAssignmentInsteadOfVarDecl = false; + var moduleNamePrefix; + + if (isExported && (parentKind === 4 /* Container */ || parentKind === 32 /* DynamicModule */ || associatedParentSymbolKind === 4 /* Container */ || associatedParentSymbolKind === 32 /* DynamicModule */)) { + if (importSymbol.getExportAssignedTypeSymbol() || importSymbol.getExportAssignedContainerSymbol()) { + needsPropertyAssignment = true; + } else { + var valueSymbol = importSymbol.getExportAssignedValueSymbol(); + if (valueSymbol && (valueSymbol.kind === 65536 /* Method */ || valueSymbol.kind === 16384 /* Function */)) { + needsPropertyAssignment = true; + } else { + usePropertyAssignmentInsteadOfVarDecl = true; + } + } + + if (this.emitState.container === 2 /* DynamicModule */) { + moduleNamePrefix = "exports."; + } else { + moduleNamePrefix = this.moduleName + "."; + } + } + + if (isAmdCodeGen && isExternalModuleReference) { + needsPropertyAssignment = true; + } else { + this.recordSourceMappingStart(importDeclAST); + if (usePropertyAssignmentInsteadOfVarDecl) { + this.writeToOutput(moduleNamePrefix); + } else { + this.writeToOutput("var "); + } + this.writeToOutput(importDeclAST.identifier.text() + " = "); + var aliasAST = importDeclAST.moduleReference; + + if (isExternalModuleReference) { + this.writeToOutput("require(" + aliasAST.stringLiteral.text() + ")"); + } else { + this.emitJavascript(aliasAST.moduleName, false); + } + + this.recordSourceMappingEnd(importDeclAST); + this.writeToOutput(";"); + + if (needsPropertyAssignment) { + this.writeLineToOutput(""); + this.emitIndent(); + } + } + + if (needsPropertyAssignment) { + this.writeToOutputWithSourceMapRecord(moduleNamePrefix + importDeclAST.identifier.text() + " = " + importDeclAST.identifier.text(), importDeclAST); + this.writeToOutput(";"); + } + this.emitComments(importDeclAST, false); + }; + + Emitter.prototype.createSourceMapper = function (document, jsFileName, jsFile, sourceMapOut, resolvePath) { + this.sourceMapper = new TypeScript.SourceMapper(jsFile, sourceMapOut, document, jsFileName, this.emitOptions, resolvePath); + }; + + Emitter.prototype.setSourceMapperNewSourceFile = function (document) { + this.sourceMapper.setNewSourceFile(document, this.emitOptions); + }; + + Emitter.prototype.updateLineAndColumn = function (s) { + var lineNumbers = TypeScript.TextUtilities.parseLineStarts(s); + if (lineNumbers.length > 1) { + this.emitState.line += lineNumbers.length - 1; + this.emitState.column = s.length - lineNumbers[lineNumbers.length - 1]; + } else { + this.emitState.column += s.length; + } + }; + + Emitter.prototype.writeToOutputWithSourceMapRecord = function (s, astSpan) { + this.recordSourceMappingStart(astSpan); + this.writeToOutput(s); + this.recordSourceMappingEnd(astSpan); + }; + + Emitter.prototype.writeToOutput = function (s) { + this.outfile.Write(s); + this.updateLineAndColumn(s); + }; + + Emitter.prototype.writeLineToOutput = function (s, force) { + if (typeof force === "undefined") { force = false; } + if (!force && s === "" && this.emitState.column === 0) { + return; + } + + this.outfile.WriteLine(s); + this.updateLineAndColumn(s); + this.emitState.column = 0; + this.emitState.line++; + }; + + Emitter.prototype.writeCaptureThisStatement = function (ast) { + this.emitIndent(); + this.writeToOutputWithSourceMapRecord(this.captureThisStmtString, ast); + this.writeLineToOutput(""); + }; + + Emitter.prototype.setContainer = function (c) { + var temp = this.emitState.container; + this.emitState.container = c; + return temp; + }; + + Emitter.prototype.getIndentString = function () { + return this.indenter.getIndent(); + }; + + Emitter.prototype.emitIndent = function () { + this.writeToOutput(this.getIndentString()); + }; + + Emitter.prototype.emitComment = function (comment, trailing, first) { + if (this.emitOptions.compilationSettings().removeComments()) { + return; + } + + var text = getTrimmedTextLines(comment); + var emitColumn = this.emitState.column; + + if (emitColumn === 0) { + this.emitIndent(); + } else if (trailing && first) { + this.writeToOutput(" "); + } + + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + 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(""); + } else { + this.recordSourceMappingEnd(comment); + this.writeToOutput(" "); + return; + } + } else { + this.recordSourceMappingStart(comment); + this.writeToOutput(text[0]); + this.recordSourceMappingEnd(comment); + this.writeLineToOutput(""); + } + + if (!trailing && emitColumn !== 0) { + this.emitIndent(); + } + }; + + Emitter.prototype.emitComments = function (ast, pre, onlyPinnedOrTripleSlashComments) { + var _this = this; + if (typeof onlyPinnedOrTripleSlashComments === "undefined") { onlyPinnedOrTripleSlashComments = false; } + if (ast && ast.kind() !== 146 /* Block */) { + if (ast.parent.kind() === 219 /* SimpleArrowFunctionExpression */ || ast.parent.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { + return; + } + } + + if (pre) { + var preComments = ast.preComments(); + + if (preComments && ast === this.detachedCommentsElement) { + var detachedComments = this.getDetachedComments(ast); + preComments = preComments.slice(detachedComments.length); + this.detachedCommentsElement = null; + } + + if (preComments && onlyPinnedOrTripleSlashComments) { + preComments = TypeScript.ArrayUtilities.where(preComments, function (c) { + return _this.isPinnedOrTripleSlash(c); + }); + } + + this.emitCommentsArray(preComments, false); + } else { + this.emitCommentsArray(ast.postComments(), true); + } + }; + + Emitter.prototype.isPinnedOrTripleSlash = function (comment) { + var fullText = comment.fullText(); + if (fullText.match(TypeScript.tripleSlashReferenceRegExp)) { + return true; + } else { + return fullText.indexOf("/*!") === 0; + } + }; + + Emitter.prototype.emitCommentsArray = function (comments, trailing) { + if (!this.emitOptions.compilationSettings().removeComments() && comments) { + for (var i = 0, n = comments.length; i < n; i++) { + this.emitComment(comments[i], trailing, i === 0); + } + } + }; + + Emitter.prototype.emitObjectLiteralExpression = function (objectLiteral) { + this.recordSourceMappingStart(objectLiteral); + + this.writeToOutput("{"); + this.emitCommaSeparatedList(objectLiteral, objectLiteral.propertyAssignments, " ", true); + this.writeToOutput("}"); + + this.recordSourceMappingEnd(objectLiteral); + }; + + Emitter.prototype.emitArrayLiteralExpression = function (arrayLiteral) { + this.recordSourceMappingStart(arrayLiteral); + + this.writeToOutput("["); + this.emitCommaSeparatedList(arrayLiteral, arrayLiteral.expressions, "", true); + this.writeToOutput("]"); + + this.recordSourceMappingEnd(arrayLiteral); + }; + + Emitter.prototype.emitObjectCreationExpression = function (objectCreationExpression) { + this.recordSourceMappingStart(objectCreationExpression); + this.writeToOutput("new "); + var target = objectCreationExpression.expression; + + this.emit(target); + if (objectCreationExpression.argumentList) { + this.recordSourceMappingStart(objectCreationExpression.argumentList); + this.writeToOutput("("); + this.emitCommaSeparatedList(objectCreationExpression.argumentList, objectCreationExpression.argumentList.arguments, "", false); + this.writeToOutputWithSourceMapRecord(")", objectCreationExpression.argumentList.closeParenToken); + this.recordSourceMappingEnd(objectCreationExpression.argumentList); + } + + this.recordSourceMappingEnd(objectCreationExpression); + }; + + Emitter.prototype.getConstantDecl = function (dotExpr) { + var pullSymbol = this.semanticInfoChain.getSymbolForAST(dotExpr); + if (pullSymbol && pullSymbol.kind === 67108864 /* EnumMember */) { + var pullDecls = pullSymbol.getDeclarations(); + if (pullDecls.length === 1) { + var pullDecl = pullDecls[0]; + if (pullDecl.kind === 67108864 /* EnumMember */) { + return pullDecl; + } + } + } + + return null; + }; + + Emitter.prototype.tryEmitConstant = function (dotExpr) { + var propertyName = dotExpr.name; + var boundDecl = this.getConstantDecl(dotExpr); + if (boundDecl) { + var value = boundDecl.constantValue; + if (value !== null) { + this.recordSourceMappingStart(dotExpr); + this.writeToOutput(value.toString()); + var comment = " /* "; + comment += propertyName.text(); + comment += " */"; + this.writeToOutput(comment); + this.recordSourceMappingEnd(dotExpr); + return true; + } + } + + return false; + }; + + Emitter.prototype.emitInvocationExpression = function (callNode) { + this.recordSourceMappingStart(callNode); + var target = callNode.expression; + var args = callNode.argumentList.arguments; + + if (target.kind() === 212 /* MemberAccessExpression */ && target.expression.kind() === 50 /* SuperKeyword */) { + this.emit(target); + this.writeToOutput(".call"); + this.recordSourceMappingStart(args); + this.writeToOutput("("); + this.emitThis(); + if (args && args.nonSeparatorCount() > 0) { + this.writeToOutput(", "); + this.emitCommaSeparatedList(callNode.argumentList, args, "", false); + } + } else { + if (callNode.expression.kind() === 50 /* SuperKeyword */ && this.emitState.container === 4 /* Constructor */) { + this.writeToOutput("_super.call"); + } else { + this.emitJavascript(target, false); + } + this.recordSourceMappingStart(args); + this.writeToOutput("("); + if (callNode.expression.kind() === 50 /* SuperKeyword */ && this.emitState.container === 4 /* Constructor */) { + this.writeToOutput("this"); + if (args && args.nonSeparatorCount() > 0) { + this.writeToOutput(", "); + } + } + this.emitCommaSeparatedList(callNode.argumentList, args, "", false); + } + + this.writeToOutputWithSourceMapRecord(")", callNode.argumentList.closeParenToken); + this.recordSourceMappingEnd(args); + this.recordSourceMappingEnd(callNode); + }; + + Emitter.prototype.emitParameterList = function (list) { + this.writeToOutput("("); + this.emitCommentsArray(list.openParenTrailingComments, true); + this.emitFunctionParameters(TypeScript.ASTHelpers.parametersFromParameterList(list)); + this.writeToOutput(")"); + }; + + Emitter.prototype.emitFunctionParameters = function (parameters) { + var argsLen = 0; + + if (parameters) { + this.emitComments(parameters.ast, true); + + var tempContainer = this.setContainer(6 /* Args */); + argsLen = parameters.length; + var printLen = argsLen; + if (parameters.lastParameterIsRest()) { + printLen--; + } + for (var i = 0; i < printLen; i++) { + var arg = parameters.astAt(i); + this.emit(arg); + + if (i < (printLen - 1)) { + this.writeToOutput(", "); + } + } + this.setContainer(tempContainer); + + this.emitComments(parameters.ast, false); + } + }; + + Emitter.prototype.emitFunctionBodyStatements = function (name, funcDecl, parameterList, block, bodyExpression) { + this.writeLineToOutput(" {"); + if (name) { + this.recordSourceMappingNameStart(name); + } + + this.indenter.increaseIndent(); + + if (block) { + this.emitDetachedComments(block.statements); + } + + if (this.shouldCaptureThis(funcDecl)) { + this.writeCaptureThisStatement(funcDecl); + } + + if (parameterList) { + this.emitDefaultValueAssignments(parameterList); + this.emitRestParameterInitializer(parameterList); + } + + if (block) { + this.emitList(block.statements); + this.emitCommentsArray(block.closeBraceLeadingComments, false); + } else { + this.emitIndent(); + this.emitCommentsArray(bodyExpression.preComments(), false); + this.writeToOutput("return "); + this.emit(bodyExpression); + this.writeLineToOutput(";"); + this.emitCommentsArray(bodyExpression.postComments(), true); + } + + this.indenter.decreaseIndent(); + this.emitIndent(); + + if (block) { + this.writeToOutputWithSourceMapRecord("}", block.closeBraceToken); + } else { + this.writeToOutputWithSourceMapRecord("}", bodyExpression); + } + + if (name) { + this.recordSourceMappingNameEnd(); + } + }; + + Emitter.prototype.emitDefaultValueAssignments = function (parameters) { + var n = parameters.length; + if (parameters.lastParameterIsRest()) { + n--; + } + + for (var i = 0; i < n; i++) { + var arg = parameters.astAt(i); + var id = parameters.identifierAt(i); + var equalsValueClause = parameters.initializerAt(i); + if (equalsValueClause) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.writeToOutput("if (typeof " + id.text() + " === \"undefined\") { "); + this.writeToOutputWithSourceMapRecord(id.text(), id); + this.emitJavascript(equalsValueClause, false); + this.writeLineToOutput("; }"); + this.recordSourceMappingEnd(arg); + } + } + }; + + Emitter.prototype.emitRestParameterInitializer = function (parameters) { + if (parameters.lastParameterIsRest()) { + var n = parameters.length; + var lastArg = parameters.astAt(n - 1); + var id = parameters.identifierAt(n - 1); + this.emitIndent(); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var "); + this.writeToOutputWithSourceMapRecord(id.text(), id); + this.writeLineToOutput(" = [];"); + this.recordSourceMappingEnd(lastArg); + this.emitIndent(); + this.writeToOutput("for ("); + this.writeToOutputWithSourceMapRecord("var _i = 0;", lastArg); + this.writeToOutput(" "); + this.writeToOutputWithSourceMapRecord("_i < (arguments.length - " + (n - 1) + ")", lastArg); + this.writeToOutput("; "); + this.writeToOutputWithSourceMapRecord("_i++", lastArg); + this.writeLineToOutput(") {"); + this.indenter.increaseIndent(); + this.emitIndent(); + + this.writeToOutputWithSourceMapRecord(id.text() + "[_i] = arguments[_i + " + (n - 1) + "];", lastArg); + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + } + }; + + Emitter.prototype.getImportDecls = function (fileName) { + var topLevelDecl = this.semanticInfoChain.topLevelDecl(this.document.fileName); + var result = []; + + var dynamicModuleDecl = topLevelDecl.getChildDecls()[0]; + var queue = dynamicModuleDecl.getChildDecls(); + + for (var i = 0, n = queue.length; i < n; i++) { + var decl = queue[i]; + + if (decl.kind & 128 /* TypeAlias */) { + var importStatementAST = this.semanticInfoChain.getASTForDecl(decl); + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + var symbol = decl.getSymbol(); + var typeSymbol = symbol && symbol.type; + if (typeSymbol && typeSymbol !== this.semanticInfoChain.anyTypeSymbol && !typeSymbol.isError()) { + result.push(decl); + } + } + } + } + + return result; + }; + + Emitter.prototype.getModuleImportAndDependencyList = function (sourceUnit) { + var importList = ""; + var dependencyList = ""; + + var importDecls = this.getImportDecls(this.document.fileName); + + if (importDecls.length) { + for (var i = 0; i < importDecls.length; i++) { + var importStatementDecl = importDecls[i]; + var importStatementSymbol = importStatementDecl.getSymbol(); + var importStatementAST = this.semanticInfoChain.getASTForDecl(importStatementDecl); + + if (importStatementSymbol.isUsedAsValue()) { + if (i <= importDecls.length - 1) { + dependencyList += ", "; + importList += ", "; + } + + importList += importStatementDecl.name; + dependencyList += importStatementAST.moduleReference.stringLiteral.text(); + } + } + } + + var amdDependencies = this.document.amdDependencies(); + for (var i = 0; i < amdDependencies.length; i++) { + dependencyList += ", \"" + amdDependencies[i] + "\""; + } + + return { + importList: importList, + dependencyList: dependencyList + }; + }; + + Emitter.prototype.shouldCaptureThis = function (ast) { + if (ast.kind() === 120 /* SourceUnit */) { + var scriptDecl = this.semanticInfoChain.topLevelDecl(this.document.fileName); + return TypeScript.hasFlag(scriptDecl.flags, 262144 /* MustCaptureThis */); + } + + var decl = this.semanticInfoChain.getDeclForAST(ast); + if (decl) { + return TypeScript.hasFlag(decl.flags, 262144 /* MustCaptureThis */); + } + + return false; + }; + + Emitter.prototype.emitEnum = function (moduleDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(moduleDecl); + this.pushDecl(pullDecl); + + var svModuleName = this.moduleName; + this.moduleName = moduleDecl.identifier.text(); + + var temp = this.setContainer(1 /* Module */); + var isExported = TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */); + + if (!isExported) { + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("var "); + this.recordSourceMappingStart(moduleDecl.identifier); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.identifier); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(moduleDecl); + this.emitIndent(); + } + + this.writeToOutput("("); + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("function ("); + this.writeToOutputWithSourceMapRecord(this.moduleName, moduleDecl.identifier); + this.writeLineToOutput(") {"); + + this.recordSourceMappingNameStart(this.moduleName); + + this.indenter.increaseIndent(); + + if (this.shouldCaptureThis(moduleDecl)) { + this.writeCaptureThisStatement(moduleDecl); + } + + this.emitSeparatedList(moduleDecl.enumElements); + this.indenter.decreaseIndent(); + this.emitIndent(); + + var parentIsDynamic = temp === 2 /* DynamicModule */; + if (temp === 0 /* Prog */ && isExported) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); + } else if (isExported || temp === 0 /* Prog */) { + var dotMod = svModuleName !== "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); + } else if (!isExported && temp !== 0 /* Prog */) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); + } else { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")();"); + } + + this.recordSourceMappingEnd(moduleDecl); + if (temp !== 0 /* Prog */ && isExported) { + this.recordSourceMappingStart(moduleDecl); + if (parentIsDynamic) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); + } else { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); + } + this.recordSourceMappingEnd(moduleDecl); + } + + this.setContainer(temp); + this.moduleName = svModuleName; + + this.popDecl(pullDecl); + }; + + Emitter.prototype.getModuleDeclToVerifyChildNameCollision = function (moduleDecl, changeNameIfAnyDeclarationInContext) { + if (TypeScript.ArrayUtilities.contains(this.declStack, moduleDecl)) { + return moduleDecl; + } else if (changeNameIfAnyDeclarationInContext) { + var symbol = moduleDecl.getSymbol(); + if (symbol) { + var otherDecls = symbol.getDeclarations(); + for (var i = 0; i < otherDecls.length; i++) { + if (TypeScript.ArrayUtilities.contains(this.declStack, otherDecls[i])) { + return otherDecls[i]; + } + } + } + } + + return null; + }; + + Emitter.prototype.hasChildNameCollision = function (moduleName, parentDecl) { + var _this = this; + var childDecls = parentDecl.getChildDecls(); + return TypeScript.ArrayUtilities.any(childDecls, function (childDecl) { + var childAST = _this.semanticInfoChain.getASTForDecl(childDecl); + + if (childDecl.kind != 67108864 /* EnumMember */ && _this.shouldEmit(childAST)) { + if (childDecl.name === moduleName) { + if (parentDecl.kind != 8 /* Class */) { + return true; + } + + if (!(childDecl.kind == 65536 /* Method */ || childDecl.kind == 4096 /* Property */ || childDecl.kind == 524288 /* SetAccessor */ || childDecl.kind == 262144 /* GetAccessor */)) { + return true; + } + } + + if (_this.hasChildNameCollision(moduleName, childDecl)) { + return true; + } + } + return false; + }); + }; + + Emitter.prototype.getModuleName = function (moduleDecl, changeNameIfAnyDeclarationInContext) { + var moduleName = moduleDecl.name; + var moduleDisplayName = moduleDecl.getDisplayName(); + + moduleDecl = this.getModuleDeclToVerifyChildNameCollision(moduleDecl, changeNameIfAnyDeclarationInContext); + if (moduleDecl && moduleDecl.kind != 64 /* Enum */) { + while (this.hasChildNameCollision(moduleName, moduleDecl)) { + moduleName = "_" + moduleName; + moduleDisplayName = "_" + moduleDisplayName; + } + } + + return moduleDisplayName; + }; + + Emitter.prototype.emitModuleDeclarationWorker = function (moduleDecl) { + if (moduleDecl.stringLiteral) { + this.emitSingleModuleDeclaration(moduleDecl, moduleDecl.stringLiteral); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDecl.name); + this.emitSingleModuleDeclaration(moduleDecl, moduleNames[0]); + } + }; + + Emitter.prototype.emitSingleModuleDeclaration = function (moduleDecl, moduleName) { + var isLastName = TypeScript.ASTHelpers.isLastNameOfModule(moduleDecl, moduleName); + + if (isLastName) { + this.emitComments(moduleDecl, true); + } + + var pullDecl = this.semanticInfoChain.getDeclForAST(moduleName); + this.pushDecl(pullDecl); + + var svModuleName = this.moduleName; + + if (moduleDecl.stringLiteral) { + this.moduleName = moduleDecl.stringLiteral.valueText(); + if (TypeScript.isTSFile(this.moduleName)) { + this.moduleName = this.moduleName.substring(0, this.moduleName.length - ".ts".length); + } + } else { + this.moduleName = moduleName.text(); + } + + var temp = this.setContainer(1 /* Module */); + var isExported = TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */); + + if (!isExported) { + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("var "); + this.recordSourceMappingStart(moduleName); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleName); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(moduleDecl); + this.emitIndent(); + } + + this.writeToOutput("("); + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("function ("); + + this.moduleName = this.getModuleName(pullDecl); + this.writeToOutputWithSourceMapRecord(this.moduleName, moduleName); + this.writeLineToOutput(") {"); + + this.recordSourceMappingNameStart(moduleName.text()); + + this.indenter.increaseIndent(); + + if (this.shouldCaptureThis(moduleDecl)) { + this.writeCaptureThisStatement(moduleDecl); + } + + if (moduleName === moduleDecl.stringLiteral) { + this.emitList(moduleDecl.moduleElements); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDecl.name); + var nameIndex = moduleNames.indexOf(moduleName); + TypeScript.Debug.assert(nameIndex >= 0); + + if (isLastName) { + this.emitList(moduleDecl.moduleElements); + } else { + this.emitIndent(); + this.emitSingleModuleDeclaration(moduleDecl, moduleNames[nameIndex + 1]); + this.writeLineToOutput(""); + } + } + + this.moduleName = moduleName.text(); + this.indenter.decreaseIndent(); + this.emitIndent(); + + var parentIsDynamic = temp === 2 /* DynamicModule */; + this.recordSourceMappingStart(moduleDecl.endingToken); + if (temp === 0 /* Prog */ && isExported) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); + } else if (isExported || temp === 0 /* Prog */) { + var dotMod = svModuleName !== "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); + } else if (!isExported && temp !== 0 /* Prog */) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); + } else { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")();"); + } + + this.recordSourceMappingEnd(moduleDecl); + if (temp !== 0 /* Prog */ && isExported) { + this.recordSourceMappingStart(moduleDecl); + if (parentIsDynamic) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); + } else { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); + } + this.recordSourceMappingEnd(moduleDecl); + } + + this.setContainer(temp); + this.moduleName = svModuleName; + + this.popDecl(pullDecl); + + if (isLastName) { + this.emitComments(moduleDecl, false); + } + }; + + Emitter.prototype.emitEnumElement = function (varDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(varDecl); + TypeScript.Debug.assert(pullDecl && pullDecl.kind === 67108864 /* EnumMember */); + + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + var name = varDecl.propertyName.text(); + var quoted = TypeScript.isQuoted(name); + this.writeToOutput(this.moduleName); + this.writeToOutput('['); + this.writeToOutput(this.moduleName); + this.writeToOutput('['); + this.writeToOutput(quoted ? name : '"' + name + '"'); + this.writeToOutput(']'); + + if (varDecl.equalsValueClause) { + this.emit(varDecl.equalsValueClause); + } else if (pullDecl.constantValue !== null) { + this.writeToOutput(' = '); + this.writeToOutput(pullDecl.constantValue.toString()); + } else { + this.writeToOutput(' = null'); + } + + this.writeToOutput('] = '); + this.writeToOutput(quoted ? name : '"' + name + '"'); + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + this.writeToOutput(';'); + }; + + Emitter.prototype.emitElementAccessExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.emit(expression.expression); + this.writeToOutput("["); + this.emit(expression.argumentExpression); + this.writeToOutput("]"); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitSimpleArrowFunctionExpression = function (arrowFunction) { + this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromIdentifier(arrowFunction.identifier), arrowFunction.block, arrowFunction.expression); + }; + + Emitter.prototype.emitParenthesizedArrowFunctionExpression = function (arrowFunction) { + this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), arrowFunction.block, arrowFunction.expression); + }; + + Emitter.prototype.emitAnyArrowFunctionExpression = function (arrowFunction, funcName, parameters, block, expression) { + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = true; + + var temp = this.setContainer(5 /* Function */); + + this.recordSourceMappingStart(arrowFunction); + + var pullDecl = this.semanticInfoChain.getDeclForAST(arrowFunction); + this.pushDecl(pullDecl); + + this.emitComments(arrowFunction, true); + + this.recordSourceMappingStart(arrowFunction); + this.writeToOutput("function "); + this.writeToOutput("("); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(funcName, arrowFunction, parameters, block, expression); + + this.recordSourceMappingEnd(arrowFunction); + + this.recordSourceMappingEnd(arrowFunction); + + this.emitComments(arrowFunction, false); + + this.popDecl(pullDecl); + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + }; + + Emitter.prototype.emitConstructor = function (funcDecl) { + if (!funcDecl.block) { + return; + } + var temp = this.setContainer(4 /* Constructor */); + + this.recordSourceMappingStart(funcDecl); + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.emitComments(funcDecl, true); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + this.writeToOutput(this.thisClassNode.identifier.text()); + this.writeToOutput("("); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionParameters(parameters); + this.writeLineToOutput(") {"); + + this.recordSourceMappingNameStart("constructor"); + this.indenter.increaseIndent(); + + this.emitDefaultValueAssignments(parameters); + this.emitRestParameterInitializer(parameters); + + if (this.shouldCaptureThis(funcDecl)) { + this.writeCaptureThisStatement(funcDecl); + } + + this.emitConstructorStatements(funcDecl); + this.emitCommentsArray(funcDecl.block.closeBraceLeadingComments, false); + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("}", funcDecl.block.closeBraceToken); + + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.popDecl(pullDecl); + this.setContainer(temp); + }; + + Emitter.prototype.emitGetAccessor = function (accessor) { + this.recordSourceMappingStart(accessor); + this.writeToOutput("get "); + + var temp = this.setContainer(5 /* Function */); + + this.recordSourceMappingStart(accessor); + + var pullDecl = this.semanticInfoChain.getDeclForAST(accessor); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(accessor); + + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(accessor, this.semanticInfoChain); + var container = accessorSymbol.getContainer(); + var containerKind = container.kind; + + this.recordSourceMappingNameStart(accessor.propertyName.text()); + this.writeToOutput(accessor.propertyName.text()); + this.writeToOutput("("); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(null, accessor, TypeScript.ASTHelpers.parametersFromParameterList(accessor.parameterList), accessor.block, null); + + this.recordSourceMappingEnd(accessor); + + this.recordSourceMappingEnd(accessor); + + this.popDecl(pullDecl); + this.setContainer(temp); + this.recordSourceMappingEnd(accessor); + }; + + Emitter.prototype.emitSetAccessor = function (accessor) { + this.recordSourceMappingStart(accessor); + this.writeToOutput("set "); + + var temp = this.setContainer(5 /* Function */); + + this.recordSourceMappingStart(accessor); + + var pullDecl = this.semanticInfoChain.getDeclForAST(accessor); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(accessor); + + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(accessor, this.semanticInfoChain); + var container = accessorSymbol.getContainer(); + var containerKind = container.kind; + + this.recordSourceMappingNameStart(accessor.propertyName.text()); + this.writeToOutput(accessor.propertyName.text()); + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(accessor.parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(null, accessor, parameters, accessor.block, null); + + this.recordSourceMappingEnd(accessor); + + this.recordSourceMappingEnd(accessor); + + this.popDecl(pullDecl); + this.setContainer(temp); + this.recordSourceMappingEnd(accessor); + }; + + Emitter.prototype.emitFunctionExpression = function (funcDecl) { + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = false; + + var temp = this.setContainer(5 /* Function */); + + var funcName = funcDecl.identifier ? funcDecl.identifier.text() : null; + + this.recordSourceMappingStart(funcDecl); + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + if (funcDecl.identifier) { + this.recordSourceMappingStart(funcDecl.identifier); + this.writeToOutput(funcDecl.identifier.text()); + this.recordSourceMappingEnd(funcDecl.identifier); + } + + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(funcName, funcDecl, parameters, funcDecl.block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.popDecl(pullDecl); + + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + }; + + Emitter.prototype.emitFunction = function (funcDecl) { + if (funcDecl.block === null) { + return; + } + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = false; + + var temp = this.setContainer(5 /* Function */); + + var funcName = funcDecl.identifier.text(); + + this.recordSourceMappingStart(funcDecl); + + var printName = funcDecl.identifier !== null; + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.emitComments(funcDecl, true); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + if (printName) { + var id = funcDecl.identifier.text(); + if (id) { + if (funcDecl.identifier) { + this.recordSourceMappingStart(funcDecl.identifier); + } + this.writeToOutput(id); + if (funcDecl.identifier) { + this.recordSourceMappingEnd(funcDecl.identifier); + } + } + } + + this.emitParameterList(funcDecl.callSignature.parameterList); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionBodyStatements(funcDecl.identifier.text(), funcDecl, parameters, funcDecl.block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.popDecl(pullDecl); + + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + + if (funcDecl.block) { + var pullFunctionDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + if ((this.emitState.container === 1 /* Module */ || this.emitState.container === 2 /* DynamicModule */) && pullFunctionDecl && TypeScript.hasFlag(pullFunctionDecl.flags, 1 /* Exported */)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = this.emitState.container === 1 /* Module */ ? this.moduleName : "exports"; + this.recordSourceMappingStart(funcDecl); + this.writeToOutput(modName + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + }; + + Emitter.prototype.emitAmbientVarDecl = function (varDecl) { + this.recordSourceMappingStart(this.currentVariableDeclaration); + if (varDecl.equalsValueClause) { + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + this.writeToOutputWithSourceMapRecord(varDecl.propertyName.text(), varDecl.propertyName); + this.emitJavascript(varDecl.equalsValueClause, false); + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + } + }; + + Emitter.prototype.emitVarDeclVar = function () { + if (this.currentVariableDeclaration) { + this.writeToOutput("var "); + } + }; + + Emitter.prototype.emitVariableDeclaration = function (declaration) { + var varDecl = declaration.declarators.nonSeparatorAt(0); + + var symbol = this.semanticInfoChain.getSymbolForAST(varDecl); + + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentKind = parentSymbol ? parentSymbol.kind : 0 /* None */; + + this.emitComments(declaration, true); + + var pullVarDecl = this.semanticInfoChain.getDeclForAST(varDecl); + var isAmbientWithoutInit = pullVarDecl && TypeScript.hasFlag(pullVarDecl.flags, 8 /* Ambient */) && varDecl.equalsValueClause === null; + if (!isAmbientWithoutInit) { + var prevVariableDeclaration = this.currentVariableDeclaration; + this.currentVariableDeclaration = declaration; + + for (var i = 0, n = declaration.declarators.nonSeparatorCount(); i < n; i++) { + var declarator = declaration.declarators.nonSeparatorAt(i); + + if (i > 0) { + this.writeToOutput(", "); + } + + this.emit(declarator); + } + this.currentVariableDeclaration = prevVariableDeclaration; + + this.recordSourceMappingEnd(declaration); + } + + this.emitComments(declaration, false); + }; + + Emitter.prototype.emitMemberVariableDeclaration = function (varDecl) { + TypeScript.Debug.assert(!TypeScript.hasModifier(varDecl.modifiers, 16 /* Static */) && varDecl.variableDeclarator.equalsValueClause); + + var pullDecl = this.semanticInfoChain.getDeclForAST(varDecl); + this.pushDecl(pullDecl); + + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + + var varDeclName = varDecl.variableDeclarator.propertyName.text(); + var quotedOrNumber = TypeScript.isQuoted(varDeclName) || varDecl.variableDeclarator.propertyName.kind() !== 11 /* IdentifierName */; + + var symbol = this.semanticInfoChain.getSymbolForAST(varDecl); + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentDecl = pullDecl && pullDecl.getParentDecl(); + + if (quotedOrNumber) { + this.writeToOutput("this["); + } else { + this.writeToOutput("this."); + } + + this.writeToOutputWithSourceMapRecord(varDecl.variableDeclarator.propertyName.text(), varDecl.variableDeclarator.propertyName); + + if (quotedOrNumber) { + this.writeToOutput("]"); + } + + if (varDecl.variableDeclarator.equalsValueClause) { + var prevVariableDeclaration = this.currentVariableDeclaration; + this.emit(varDecl.variableDeclarator.equalsValueClause); + this.currentVariableDeclaration = prevVariableDeclaration; + } + + if (this.emitState.container !== 6 /* Args */) { + this.writeToOutput(";"); + } + + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitVariableDeclarator = function (varDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(varDecl); + this.pushDecl(pullDecl); + if (pullDecl && (pullDecl.flags & 8 /* Ambient */) === 8 /* Ambient */) { + this.emitAmbientVarDecl(varDecl); + } else { + this.emitComments(varDecl, true); + this.recordSourceMappingStart(this.currentVariableDeclaration); + this.recordSourceMappingStart(varDecl); + + var varDeclName = varDecl.propertyName.text(); + + var symbol = this.semanticInfoChain.getSymbolForAST(varDecl); + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentDecl = pullDecl && pullDecl.getParentDecl(); + var parentIsModule = parentDecl && (parentDecl.flags & 102400 /* SomeInitializedModule */); + + if (parentIsModule) { + if (!TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */)) { + this.emitVarDeclVar(); + } else { + if (this.emitState.container === 2 /* DynamicModule */) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(this.moduleName + "."); + } + } + } else { + this.emitVarDeclVar(); + } + + this.writeToOutputWithSourceMapRecord(varDecl.propertyName.text(), varDecl.propertyName); + + if (varDecl.equalsValueClause) { + var prevVariableDeclaration = this.currentVariableDeclaration; + this.emit(varDecl.equalsValueClause); + this.currentVariableDeclaration = prevVariableDeclaration; + } + + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + } + this.currentVariableDeclaration = undefined; + this.popDecl(pullDecl); + }; + + Emitter.prototype.symbolIsUsedInItsEnclosingContainer = function (symbol, dynamic) { + if (typeof dynamic === "undefined") { dynamic = false; } + var symDecls = symbol.getDeclarations(); + + if (symDecls.length) { + var enclosingDecl = this.getEnclosingDecl(); + if (enclosingDecl) { + var parentDecl = symDecls[0].getParentDecl(); + if (parentDecl) { + var symbolDeclarationEnclosingContainer = parentDecl; + var enclosingContainer = enclosingDecl; + + while (symbolDeclarationEnclosingContainer) { + if (symbolDeclarationEnclosingContainer.kind === (dynamic ? 32 /* DynamicModule */ : 4 /* Container */)) { + break; + } + symbolDeclarationEnclosingContainer = symbolDeclarationEnclosingContainer.getParentDecl(); + } + + if (symbolDeclarationEnclosingContainer) { + while (enclosingContainer) { + if (enclosingContainer.kind === (dynamic ? 32 /* DynamicModule */ : 4 /* Container */)) { + break; + } + + enclosingContainer = enclosingContainer.getParentDecl(); + } + } + + if (symbolDeclarationEnclosingContainer && enclosingContainer) { + var same = symbolDeclarationEnclosingContainer === enclosingContainer; + + if (!same && symbol.anyDeclHasFlag(32768 /* InitializedModule */)) { + same = symbolDeclarationEnclosingContainer === enclosingContainer.getParentDecl(); + } + + return same; + } + } + } + } + + return false; + }; + + Emitter.prototype.shouldQualifySymbolNameWithParentName = function (symbol) { + var enclosingContextDeclPath = this.declStack; + var symbolDeclarations = symbol.getDeclarations(); + for (var i = 0; i < symbolDeclarations.length; i++) { + var currentDecl = symbolDeclarations[i]; + var declParent = currentDecl.getParentDecl(); + + if (currentDecl.kind === 67108864 /* EnumMember */) { + return true; + } + + if (!TypeScript.hasFlag(currentDecl.flags, 1 /* Exported */)) { + return false; + } + + if (currentDecl.kind === 512 /* Variable */ && !TypeScript.hasFlag(currentDecl.flags, 118784 /* ImplicitVariable */)) { + return true; + } + + if (TypeScript.ArrayUtilities.contains(this.declStack, declParent)) { + return false; + } + } + + return true; + }; + + Emitter.prototype.getSymbolForEmit = function (ast) { + var pullSymbol = this.semanticInfoChain.getSymbolForAST(ast); + var pullSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(ast); + if (pullSymbol && pullSymbolAlias) { + var symbolToCompare = TypeScript.isTypesOnlyLocation(ast) ? pullSymbolAlias.getExportAssignedTypeSymbol() : pullSymbolAlias.getExportAssignedValueSymbol(); + + if (pullSymbol === symbolToCompare) { + pullSymbol = pullSymbolAlias; + pullSymbolAlias = null; + } + } + return { symbol: pullSymbol, aliasSymbol: pullSymbolAlias }; + }; + + Emitter.prototype.emitName = function (name, addThis) { + this.emitComments(name, true); + this.recordSourceMappingStart(name); + if (name.text().length > 0) { + var symbolForEmit = this.getSymbolForEmit(name); + var pullSymbol = symbolForEmit.symbol; + if (!pullSymbol) { + pullSymbol = this.semanticInfoChain.anyTypeSymbol; + } + var pullSymbolAlias = symbolForEmit.aliasSymbol; + var pullSymbolKind = pullSymbol.kind; + var isLocalAlias = pullSymbolAlias && (pullSymbolAlias.getDeclarations()[0].getParentDecl() === this.getEnclosingDecl()); + if (addThis && (this.emitState.container !== 6 /* Args */) && pullSymbol) { + var pullSymbolContainer = pullSymbol.getContainer(); + + if (pullSymbolContainer) { + var pullSymbolContainerKind = pullSymbolContainer.kind; + + if (TypeScript.PullHelpers.symbolIsModule(pullSymbolContainer) || pullSymbolContainerKind === 64 /* Enum */ || pullSymbolContainer.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */)) { + var needToEmitParentName = this.shouldQualifySymbolNameWithParentName(pullSymbol); + if (needToEmitParentName) { + var parentDecl = pullSymbol.getDeclarations()[0].getParentDecl(); + TypeScript.Debug.assert(parentDecl && !parentDecl.isRootDecl()); + this.writeToOutput(this.getModuleName(parentDecl, true) + "."); + } + } else if (pullSymbolContainerKind === 32 /* DynamicModule */ || pullSymbolContainer.anyDeclHasFlag(65536 /* InitializedDynamicModule */)) { + if (pullSymbolKind === 4096 /* Property */) { + this.writeToOutput("exports."); + } else if (pullSymbol.anyDeclHasFlag(1 /* Exported */) && !isLocalAlias && !pullSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */) && pullSymbol.kind !== 32768 /* ConstructorMethod */ && pullSymbol.kind !== 8 /* Class */ && pullSymbol.kind !== 64 /* Enum */) { + this.writeToOutput("exports."); + } + } + } + } + + this.writeToOutput(name.text()); + } + + this.recordSourceMappingEnd(name); + this.emitComments(name, false); + }; + + Emitter.prototype.recordSourceMappingNameStart = function (name) { + if (this.sourceMapper) { + var nameIndex = -1; + if (name) { + if (this.sourceMapper.currentNameIndex.length > 0) { + var parentNameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; + if (parentNameIndex !== -1) { + name = this.sourceMapper.names[parentNameIndex] + "." + name; + } + } + + var nameIndex = this.sourceMapper.names.length - 1; + for (nameIndex; nameIndex >= 0; nameIndex--) { + if (this.sourceMapper.names[nameIndex] === name) { + break; + } + } + + if (nameIndex === -1) { + nameIndex = this.sourceMapper.names.length; + this.sourceMapper.names.push(name); + } + } + this.sourceMapper.currentNameIndex.push(nameIndex); + } + }; + + Emitter.prototype.recordSourceMappingNameEnd = function () { + if (this.sourceMapper) { + this.sourceMapper.currentNameIndex.pop(); + } + }; + + Emitter.prototype.recordSourceMappingStart = function (ast) { + if (this.sourceMapper && TypeScript.ASTHelpers.isValidAstNode(ast)) { + var lineCol = { line: -1, character: -1 }; + var sourceMapping = new TypeScript.SourceMapping(); + sourceMapping.start.emittedColumn = this.emitState.column; + sourceMapping.start.emittedLine = this.emitState.line; + + var lineMap = this.document.lineMap(); + lineMap.fillLineAndCharacterFromPosition(ast.start(), lineCol); + sourceMapping.start.sourceColumn = lineCol.character; + sourceMapping.start.sourceLine = lineCol.line + 1; + lineMap.fillLineAndCharacterFromPosition(ast.end(), lineCol); + sourceMapping.end.sourceColumn = lineCol.character; + sourceMapping.end.sourceLine = lineCol.line + 1; + + TypeScript.Debug.assert(!isNaN(sourceMapping.start.emittedColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.start.emittedLine)); + TypeScript.Debug.assert(!isNaN(sourceMapping.start.sourceColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.start.sourceLine)); + TypeScript.Debug.assert(!isNaN(sourceMapping.end.sourceColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.end.sourceLine)); + + 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); + this.sourceMapper.increaseMappingLevel(ast); + } + }; + + Emitter.prototype.recordSourceMappingEnd = function (ast) { + if (this.sourceMapper && TypeScript.ASTHelpers.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; + + TypeScript.Debug.assert(!isNaN(sourceMapping.end.emittedColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.end.emittedLine)); + + this.sourceMapper.decreaseMappingLevel(ast); + } + }; + + Emitter.prototype.getOutputFiles = function () { + var result = []; + if (this.sourceMapper !== null) { + this.sourceMapper.emitSourceMapping(); + result.push(this.sourceMapper.getOutputFile()); + } + + result.push(this.outfile.getOutputFile()); + return result; + }; + + Emitter.prototype.emitParameterPropertyAndMemberVariableAssignments = function () { + var constructorDecl = getLastConstructor(this.thisClassNode); + + if (constructorDecl) { + for (var i = 0, n = constructorDecl.callSignature.parameterList.parameters.nonSeparatorCount(); i < n; i++) { + var parameter = constructorDecl.callSignature.parameterList.parameters.nonSeparatorAt(i); + var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter); + if (TypeScript.hasFlag(parameterDecl.flags, 8388608 /* PropertyParameter */)) { + this.emitIndent(); + this.recordSourceMappingStart(parameter); + this.writeToOutputWithSourceMapRecord("this." + parameter.identifier.text(), parameter.identifier); + this.writeToOutput(" = "); + this.writeToOutputWithSourceMapRecord(parameter.identifier.text(), parameter.identifier); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(parameter); + } + } + } + + for (var i = 0, n = this.thisClassNode.classElements.childCount(); i < n; i++) { + if (this.thisClassNode.classElements.childAt(i).kind() === 136 /* MemberVariableDeclaration */) { + var varDecl = this.thisClassNode.classElements.childAt(i); + if (!TypeScript.hasModifier(varDecl.modifiers, 16 /* Static */) && varDecl.variableDeclarator.equalsValueClause) { + this.emitIndent(); + this.emitMemberVariableDeclaration(varDecl); + this.writeLineToOutput(""); + } + } + } + }; + + Emitter.prototype.isOnSameLine = function (pos1, pos2) { + var lineMap = this.document.lineMap(); + return lineMap.getLineNumberFromPosition(pos1) === lineMap.getLineNumberFromPosition(pos2); + }; + + Emitter.prototype.emitCommaSeparatedList = function (parent, list, buffer, preserveNewLines) { + if (list === null || list.nonSeparatorCount() === 0) { + return; + } + + var startLine = preserveNewLines && !this.isOnSameLine(parent.end(), list.nonSeparatorAt(0).end()); + + if (preserveNewLines) { + this.indenter.increaseIndent(); + } + + if (startLine) { + this.writeLineToOutput(""); + } else { + this.writeToOutput(buffer); + } + + for (var i = 0, n = list.nonSeparatorCount(); i < n; i++) { + var emitNode = list.nonSeparatorAt(i); + + this.emitJavascript(emitNode, startLine); + + if (i < (n - 1)) { + startLine = preserveNewLines && !this.isOnSameLine(emitNode.end(), list.nonSeparatorAt(i + 1).start()); + if (startLine) { + this.writeLineToOutput(","); + } else { + this.writeToOutput(", "); + } + } + } + + if (preserveNewLines) { + this.indenter.decreaseIndent(); + } + + if (preserveNewLines && !this.isOnSameLine(parent.end(), list.nonSeparatorAt(list.nonSeparatorCount() - 1).end())) { + this.writeLineToOutput(""); + this.emitIndent(); + } else { + this.writeToOutput(buffer); + } + }; + + Emitter.prototype.emitList = function (list, useNewLineSeparator, startInclusive, endExclusive) { + if (typeof useNewLineSeparator === "undefined") { useNewLineSeparator = true; } + if (typeof startInclusive === "undefined") { startInclusive = 0; } + if (typeof endExclusive === "undefined") { endExclusive = list.childCount(); } + if (list === null) { + return; + } + + this.emitComments(list, true); + var lastEmittedNode = null; + + for (var i = startInclusive; i < endExclusive; i++) { + var node = list.childAt(i); + + if (this.shouldEmit(node)) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + if (useNewLineSeparator) { + this.writeLineToOutput(""); + } + + lastEmittedNode = node; + } + } + + this.emitComments(list, false); + }; + + Emitter.prototype.emitSeparatedList = function (list, useNewLineSeparator, startInclusive, endExclusive) { + if (typeof useNewLineSeparator === "undefined") { useNewLineSeparator = true; } + if (typeof startInclusive === "undefined") { startInclusive = 0; } + if (typeof endExclusive === "undefined") { endExclusive = list.nonSeparatorCount(); } + if (list === null) { + return; + } + + this.emitComments(list, true); + var lastEmittedNode = null; + + for (var i = startInclusive; i < endExclusive; i++) { + var node = list.nonSeparatorAt(i); + + if (this.shouldEmit(node)) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + if (useNewLineSeparator) { + this.writeLineToOutput(""); + } + + lastEmittedNode = node; + } + } + + this.emitComments(list, false); + }; + + Emitter.prototype.isDirectivePrologueElement = function (node) { + if (node.kind() === 149 /* ExpressionStatement */) { + var exprStatement = node; + return exprStatement.expression.kind() === 14 /* StringLiteral */; + } + + return false; + }; + + Emitter.prototype.emitSpaceBetweenConstructs = function (node1, node2) { + if (node1 === null || node2 === null) { + return; + } + + if (node1.start() === -1 || node1.end() === -1 || node2.start() === -1 || node2.end() === -1) { + return; + } + + var lineMap = this.document.lineMap(); + var node1EndLine = lineMap.getLineNumberFromPosition(node1.end()); + var node2StartLine = lineMap.getLineNumberFromPosition(node2.start()); + + if ((node2StartLine - node1EndLine) > 1) { + this.writeLineToOutput("", true); + } + }; + + Emitter.prototype.getDetachedComments = function (element) { + var preComments = element.preComments(); + if (preComments) { + var lineMap = this.document.lineMap(); + + var detachedComments = []; + var lastComment = null; + + for (var i = 0, n = preComments.length; i < n; i++) { + var comment = preComments[i]; + + if (lastComment) { + var lastCommentLine = lineMap.getLineNumberFromPosition(lastComment.end()); + var commentLine = lineMap.getLineNumberFromPosition(comment.start()); + + if (commentLine >= lastCommentLine + 2) { + return detachedComments; + } + } + + detachedComments.push(comment); + lastComment = comment; + } + + var lastCommentLine = lineMap.getLineNumberFromPosition(TypeScript.ArrayUtilities.last(detachedComments).end()); + var astLine = lineMap.getLineNumberFromPosition(element.start()); + if (astLine >= lastCommentLine + 2) { + return detachedComments; + } + } + + return []; + }; + + Emitter.prototype.emitPossibleCopyrightHeaders = function (script) { + this.emitDetachedComments(script.moduleElements); + }; + + Emitter.prototype.emitDetachedComments = function (list) { + if (list.childCount() > 0) { + var firstElement = list.childAt(0); + + this.detachedCommentsElement = firstElement; + this.emitCommentsArray(this.getDetachedComments(this.detachedCommentsElement), false); + } + }; + + Emitter.prototype.emitScriptElements = function (sourceUnit) { + var list = sourceUnit.moduleElements; + + this.emitPossibleCopyrightHeaders(sourceUnit); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var node = list.childAt(i); + + if (!this.isDirectivePrologueElement(node)) { + break; + } + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + } + + this.emitPrologue(sourceUnit); + + var isExternalModule = this.document.isExternalModule(); + var isNonElidedExternalModule = isExternalModule && !TypeScript.ASTHelpers.scriptIsElided(sourceUnit); + if (isNonElidedExternalModule) { + this.recordSourceMappingStart(sourceUnit); + + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + var dependencyList = "[\"require\", \"exports\""; + var importList = "require, exports"; + + var importAndDependencyList = this.getModuleImportAndDependencyList(sourceUnit); + importList += importAndDependencyList.importList; + dependencyList += importAndDependencyList.dependencyList + "]"; + + this.writeLineToOutput("define(" + dependencyList + "," + " function(" + importList + ") {"); + } + } + + if (isExternalModule) { + var temp = this.setContainer(2 /* DynamicModule */); + + var svModuleName = this.moduleName; + this.moduleName = sourceUnit.fileName(); + if (TypeScript.isTSFile(this.moduleName)) { + this.moduleName = this.moduleName.substring(0, this.moduleName.length - ".ts".length); + } + + this.setExportAssignment(null); + + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + this.indenter.increaseIndent(); + } + + var externalModule = this.semanticInfoChain.getDeclForAST(this.document.sourceUnit()); + + if (TypeScript.hasFlag(externalModule.flags, 262144 /* MustCaptureThis */)) { + this.writeCaptureThisStatement(sourceUnit); + } + + this.pushDecl(externalModule); + } + + this.emitList(list, true, i, n); + + if (isExternalModule) { + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + this.indenter.decreaseIndent(); + } + + if (isNonElidedExternalModule) { + var exportAssignment = this.getExportAssignment(); + var exportAssignmentIdentifierText = exportAssignment ? exportAssignment.identifier.text() : null; + var exportAssignmentValueSymbol = externalModule.getSymbol().getExportAssignedValueSymbol(); + + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + if (exportAssignmentIdentifierText && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { + this.indenter.increaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("return " + exportAssignmentIdentifierText, exportAssignment); + this.writeLineToOutput(";"); + this.indenter.decreaseIndent(); + } + this.writeToOutput("});"); + } else if (exportAssignmentIdentifierText && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("module.exports = " + exportAssignmentIdentifierText, exportAssignment); + this.writeToOutput(";"); + } + + this.recordSourceMappingEnd(sourceUnit); + this.writeLineToOutput(""); + } + + this.setContainer(temp); + this.moduleName = svModuleName; + this.popDecl(externalModule); + } + }; + + Emitter.prototype.emitConstructorStatements = function (funcDecl) { + var list = funcDecl.block.statements; + + if (list === null) { + return; + } + + this.emitComments(list, true); + + var emitPropertyAssignmentsAfterSuperCall = TypeScript.ASTHelpers.getExtendsHeritageClause(this.thisClassNode.heritageClauses) !== null; + var propertyAssignmentIndex = emitPropertyAssignmentsAfterSuperCall ? 1 : 0; + var lastEmittedNode = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + if (i === propertyAssignmentIndex) { + this.emitParameterPropertyAndMemberVariableAssignments(); + } + + var node = list.childAt(i); + + if (this.shouldEmit(node)) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + + lastEmittedNode = node; + } + } + + if (i === propertyAssignmentIndex) { + this.emitParameterPropertyAndMemberVariableAssignments(); + } + + this.emitComments(list, false); + }; + + Emitter.prototype.emitJavascript = function (ast, startLine) { + if (ast === null) { + return; + } + + if (startLine && this.indenter.indentAmt > 0) { + this.emitIndent(); + } + + this.emit(ast); + }; + + Emitter.prototype.emitAccessorMemberDeclaration = function (funcDecl, name, className, isProto) { + if (funcDecl.kind() !== 139 /* GetAccessor */) { + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain); + if (accessorSymbol.getGetter()) { + return; + } + } + + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + + this.writeToOutput("Object.defineProperty(" + className); + if (isProto) { + this.writeToOutput(".prototype, "); + } else { + this.writeToOutput(", "); + } + + var functionName = name.text(); + if (TypeScript.isQuoted(functionName)) { + this.writeToOutput(functionName); + } else { + this.writeToOutput('"' + functionName + '"'); + } + + this.writeLineToOutput(", {"); + + this.indenter.increaseIndent(); + + var accessors = TypeScript.PullHelpers.getGetterAndSetterFunction(funcDecl, this.semanticInfoChain); + if (accessors.getter) { + this.emitIndent(); + this.recordSourceMappingStart(accessors.getter); + this.emitComments(accessors.getter, true); + this.writeToOutput("get: "); + this.emitAccessorBody(accessors.getter, accessors.getter.parameterList, accessors.getter.block); + this.writeLineToOutput(","); + } + + if (accessors.setter) { + this.emitIndent(); + this.recordSourceMappingStart(accessors.setter); + this.emitComments(accessors.setter, true); + this.writeToOutput("set: "); + this.emitAccessorBody(accessors.setter, accessors.setter.parameterList, accessors.setter.block); + this.writeLineToOutput(","); + } + + this.emitIndent(); + this.writeLineToOutput("enumerable: true,"); + this.emitIndent(); + this.writeLineToOutput("configurable: true"); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("});"); + this.recordSourceMappingEnd(funcDecl); + }; + + Emitter.prototype.emitAccessorBody = function (funcDecl, parameterList, block) { + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(null, funcDecl, parameters, block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitClass = function (classDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(classDecl); + this.pushDecl(pullDecl); + + var svClassNode = this.thisClassNode; + this.thisClassNode = classDecl; + var className = classDecl.identifier.text(); + this.emitComments(classDecl, true); + var temp = this.setContainer(3 /* Class */); + + this.recordSourceMappingStart(classDecl); + this.writeToOutput("var " + className); + + var hasBaseClass = TypeScript.ASTHelpers.getExtendsHeritageClause(classDecl.heritageClauses) !== null; + var baseTypeReference = null; + var varDecl = null; + + if (hasBaseClass) { + this.writeLineToOutput(" = (function (_super) {"); + } else { + this.writeLineToOutput(" = (function () {"); + } + + this.recordSourceMappingNameStart(className); + this.indenter.increaseIndent(); + + if (hasBaseClass) { + baseTypeReference = TypeScript.ASTHelpers.getExtendsHeritageClause(classDecl.heritageClauses).typeNames.nonSeparatorAt(0); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("__extends(" + className + ", _super)", baseTypeReference); + this.writeLineToOutput(";"); + } + + this.emitIndent(); + + var constrDecl = getLastConstructor(classDecl); + + if (constrDecl) { + this.emit(constrDecl); + this.writeLineToOutput(""); + } else { + this.recordSourceMappingStart(classDecl); + + this.indenter.increaseIndent(); + this.writeLineToOutput("function " + classDecl.identifier.text() + "() {"); + this.recordSourceMappingNameStart("constructor"); + if (hasBaseClass) { + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("_super.apply(this, arguments)", baseTypeReference); + this.writeLineToOutput(";"); + } + + if (this.shouldCaptureThis(classDecl)) { + this.writeCaptureThisStatement(classDecl); + } + + this.emitParameterPropertyAndMemberVariableAssignments(); + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("}", classDecl.closeBraceToken); + this.writeLineToOutput(""); + + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl); + } + + this.emitClassMembers(classDecl); + + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("return " + className + ";", classDecl.closeBraceToken); + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("}", classDecl.closeBraceToken); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingStart(classDecl); + this.writeToOutput(")("); + if (hasBaseClass) { + this.emitJavascript(baseTypeReference, false); + } + this.writeToOutput(");"); + this.recordSourceMappingEnd(classDecl); + + if ((temp === 1 /* Module */ || temp === 2 /* DynamicModule */) && TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = temp === 1 /* Module */ ? this.moduleName : "exports"; + this.writeToOutputWithSourceMapRecord(modName + "." + className + " = " + className + ";", classDecl); + } + + this.recordSourceMappingEnd(classDecl); + this.emitComments(classDecl, false); + this.setContainer(temp); + this.thisClassNode = svClassNode; + + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitClassMembers = function (classDecl) { + var lastEmittedMember = null; + + for (var i = 0, n = classDecl.classElements.childCount(); i < n; i++) { + var memberDecl = classDecl.classElements.childAt(i); + + if (memberDecl.kind() === 139 /* GetAccessor */) { + this.emitSpaceBetweenConstructs(lastEmittedMember, memberDecl); + var getter = memberDecl; + this.emitAccessorMemberDeclaration(getter, getter.propertyName, classDecl.identifier.text(), !TypeScript.hasModifier(getter.modifiers, 16 /* Static */)); + lastEmittedMember = memberDecl; + } else if (memberDecl.kind() === 140 /* SetAccessor */) { + this.emitSpaceBetweenConstructs(lastEmittedMember, memberDecl); + var setter = memberDecl; + this.emitAccessorMemberDeclaration(setter, setter.propertyName, classDecl.identifier.text(), !TypeScript.hasModifier(setter.modifiers, 16 /* Static */)); + lastEmittedMember = memberDecl; + } else if (memberDecl.kind() === 135 /* MemberFunctionDeclaration */) { + var memberFunction = memberDecl; + + if (memberFunction.block) { + this.emitSpaceBetweenConstructs(lastEmittedMember, memberDecl); + + this.emitClassMemberFunctionDeclaration(classDecl, memberFunction); + lastEmittedMember = memberDecl; + } + } + } + + for (var i = 0, n = classDecl.classElements.childCount(); i < n; i++) { + var memberDecl = classDecl.classElements.childAt(i); + + if (memberDecl.kind() === 136 /* MemberVariableDeclaration */) { + var varDecl = memberDecl; + + if (TypeScript.hasModifier(varDecl.modifiers, 16 /* Static */) && varDecl.variableDeclarator.equalsValueClause) { + this.emitSpaceBetweenConstructs(lastEmittedMember, varDecl); + + this.emitIndent(); + this.recordSourceMappingStart(varDecl); + + var varDeclName = varDecl.variableDeclarator.propertyName.text(); + if (TypeScript.isQuoted(varDeclName) || varDecl.variableDeclarator.propertyName.kind() !== 11 /* IdentifierName */) { + this.writeToOutput(classDecl.identifier.text() + "[" + varDeclName + "]"); + } else { + this.writeToOutput(classDecl.identifier.text() + "." + varDeclName); + } + + this.emit(varDecl.variableDeclarator.equalsValueClause); + + this.recordSourceMappingEnd(varDecl); + this.writeLineToOutput(";"); + + lastEmittedMember = varDecl; + } + } + } + }; + + Emitter.prototype.emitClassMemberFunctionDeclaration = function (classDecl, funcDecl) { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.emitComments(funcDecl, true); + var functionName = funcDecl.propertyName.text(); + + this.writeToOutput(classDecl.identifier.text()); + + if (!TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */)) { + this.writeToOutput(".prototype"); + } + + if (TypeScript.isQuoted(functionName) || funcDecl.propertyName.kind() !== 11 /* IdentifierName */) { + this.writeToOutput("[" + functionName + "] = "); + } else { + this.writeToOutput("." + functionName + " = "); + } + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + this.emitParameterList(funcDecl.callSignature.parameterList); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionBodyStatements(funcDecl.propertyName.text(), funcDecl, parameters, funcDecl.block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.recordSourceMappingEnd(funcDecl); + this.popDecl(pullDecl); + + this.writeLineToOutput(";"); + }; + + Emitter.prototype.requiresExtendsBlock = function (moduleElements) { + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var moduleElement = moduleElements.childAt(i); + + if (moduleElement.kind() === 130 /* ModuleDeclaration */) { + var moduleAST = moduleElement; + + if (!TypeScript.hasModifier(moduleAST.modifiers, 8 /* Ambient */) && this.requiresExtendsBlock(moduleAST.moduleElements)) { + return true; + } + } else if (moduleElement.kind() === 131 /* ClassDeclaration */) { + var classDeclaration = moduleElement; + + if (!TypeScript.hasModifier(classDeclaration.modifiers, 8 /* Ambient */) && TypeScript.ASTHelpers.getExtendsHeritageClause(classDeclaration.heritageClauses) !== null) { + return true; + } + } + } + + return false; + }; + + Emitter.prototype.emitPrologue = function (sourceUnit) { + if (!this.extendsPrologueEmitted) { + if (this.requiresExtendsBlock(sourceUnit.moduleElements)) { + this.extendsPrologueEmitted = true; + this.writeLineToOutput("var __extends = this.__extends || function (d, b) {"); + this.writeLineToOutput(" for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];"); + this.writeLineToOutput(" function __() { this.constructor = d; }"); + this.writeLineToOutput(" __.prototype = b.prototype;"); + this.writeLineToOutput(" d.prototype = new __();"); + this.writeLineToOutput("};"); + } + } + + if (!this.globalThisCapturePrologueEmitted) { + if (this.shouldCaptureThis(sourceUnit)) { + this.globalThisCapturePrologueEmitted = true; + this.writeLineToOutput(this.captureThisStmtString); + } + } + }; + + Emitter.prototype.emitThis = function () { + if (!this.inWithBlock && this.inArrowFunction) { + this.writeToOutput("_this"); + } else { + this.writeToOutput("this"); + } + }; + + Emitter.prototype.emitBlockOrStatement = function (node) { + if (node.kind() === 146 /* Block */) { + this.emit(node); + } else { + this.writeLineToOutput(""); + this.indenter.increaseIndent(); + this.emitJavascript(node, true); + this.indenter.decreaseIndent(); + } + }; + + Emitter.prototype.emitLiteralExpression = function (expression) { + switch (expression.kind()) { + case 32 /* NullKeyword */: + this.writeToOutputWithSourceMapRecord("null", expression); + break; + case 24 /* FalseKeyword */: + this.writeToOutputWithSourceMapRecord("false", expression); + break; + case 37 /* TrueKeyword */: + this.writeToOutputWithSourceMapRecord("true", expression); + break; + default: + throw TypeScript.Errors.abstract(); + } + }; + + Emitter.prototype.emitThisExpression = function (expression) { + if (!this.inWithBlock && this.inArrowFunction) { + this.writeToOutputWithSourceMapRecord("_this", expression); + } else { + this.writeToOutputWithSourceMapRecord("this", expression); + } + }; + + Emitter.prototype.emitSuperExpression = function (expression) { + this.writeToOutputWithSourceMapRecord("_super.prototype", expression); + }; + + Emitter.prototype.emitParenthesizedExpression = function (parenthesizedExpression) { + var omitParentheses = false; + + if (parenthesizedExpression.expression.kind() === 220 /* CastExpression */ && parenthesizedExpression.openParenTrailingComments === null) { + var castedExpression = parenthesizedExpression.expression.expression; + + while (castedExpression.kind() == 220 /* CastExpression */) { + castedExpression = castedExpression.expression; + } + + switch (castedExpression.kind()) { + case 217 /* ParenthesizedExpression */: + case 11 /* IdentifierName */: + case 32 /* NullKeyword */: + case 35 /* ThisKeyword */: + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + case 12 /* RegularExpressionLiteral */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + case 214 /* ArrayLiteralExpression */: + case 215 /* ObjectLiteralExpression */: + case 212 /* MemberAccessExpression */: + case 221 /* ElementAccessExpression */: + omitParentheses = true; + break; + + case 213 /* InvocationExpression */: + if (parenthesizedExpression.parent.kind() !== 216 /* ObjectCreationExpression */) { + omitParentheses = true; + } + + break; + } + } + + if (omitParentheses) { + this.emit(parenthesizedExpression.expression); + } else { + this.recordSourceMappingStart(parenthesizedExpression); + this.writeToOutput("("); + this.emitCommentsArray(parenthesizedExpression.openParenTrailingComments, false); + this.emit(parenthesizedExpression.expression); + this.writeToOutput(")"); + this.recordSourceMappingEnd(parenthesizedExpression); + } + }; + + Emitter.prototype.emitCastExpression = function (expression) { + this.emit(expression.expression); + }; + + Emitter.prototype.emitPrefixUnaryExpression = function (expression) { + var nodeType = expression.kind(); + + this.recordSourceMappingStart(expression); + switch (nodeType) { + case 167 /* LogicalNotExpression */: + this.writeToOutput("!"); + this.emit(expression.operand); + break; + case 166 /* BitwiseNotExpression */: + this.writeToOutput("~"); + this.emit(expression.operand); + break; + case 165 /* NegateExpression */: + this.writeToOutput("-"); + if (expression.operand.kind() === 165 /* NegateExpression */ || expression.operand.kind() === 169 /* PreDecrementExpression */) { + this.writeToOutput(" "); + } + this.emit(expression.operand); + break; + case 164 /* PlusExpression */: + this.writeToOutput("+"); + if (expression.operand.kind() === 164 /* PlusExpression */ || expression.operand.kind() === 168 /* PreIncrementExpression */) { + this.writeToOutput(" "); + } + this.emit(expression.operand); + break; + case 168 /* PreIncrementExpression */: + this.writeToOutput("++"); + this.emit(expression.operand); + break; + case 169 /* PreDecrementExpression */: + this.writeToOutput("--"); + this.emit(expression.operand); + break; + default: + throw TypeScript.Errors.abstract(); + } + + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitPostfixUnaryExpression = function (expression) { + var nodeType = expression.kind(); + + this.recordSourceMappingStart(expression); + switch (nodeType) { + case 210 /* PostIncrementExpression */: + this.emit(expression.operand); + this.writeToOutput("++"); + break; + case 211 /* PostDecrementExpression */: + this.emit(expression.operand); + this.writeToOutput("--"); + break; + default: + throw TypeScript.Errors.abstract(); + } + + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitTypeOfExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.writeToOutput("typeof "); + this.emit(expression.expression); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitDeleteExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.writeToOutput("delete "); + this.emit(expression.expression); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitVoidExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.writeToOutput("void "); + this.emit(expression.expression); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.canEmitDottedNameMemberAccessExpression = function (expression) { + var memberExpressionNodeType = expression.expression.kind(); + + if (memberExpressionNodeType === 11 /* IdentifierName */ || memberExpressionNodeType == 212 /* MemberAccessExpression */) { + var memberAccessSymbol = this.getSymbolForEmit(expression).symbol; + var memberAccessExpressionSymbol = this.getSymbolForEmit(expression.expression).symbol; + if (memberAccessSymbol && memberAccessExpressionSymbol && !this.semanticInfoChain.getAliasSymbolForAST(expression.expression) && (TypeScript.PullHelpers.symbolIsModule(memberAccessExpressionSymbol) || memberAccessExpressionSymbol.kind === 64 /* Enum */ || memberAccessExpressionSymbol.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */))) { + var memberAccessSymbolKind = memberAccessSymbol.kind; + if (memberAccessSymbolKind === 4096 /* Property */ || memberAccessSymbolKind === 67108864 /* EnumMember */ || (memberAccessSymbol.anyDeclHasFlag(1 /* Exported */) && memberAccessSymbolKind === 512 /* Variable */ && !memberAccessSymbol.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */)) || ((memberAccessSymbol.anyDeclHasFlag(1 /* Exported */) && !this.symbolIsUsedInItsEnclosingContainer(memberAccessSymbol)))) { + if (memberExpressionNodeType === 212 /* MemberAccessExpression */) { + return this.canEmitDottedNameMemberAccessExpression(expression.expression); + } + + return true; + } + } + } + + return false; + }; + + Emitter.prototype.emitDottedNameMemberAccessExpression = function (expression) { + this.recordSourceMappingStart(expression); + if (expression.expression.kind() === 212 /* MemberAccessExpression */) { + this.emitDottedNameMemberAccessExpressionRecurse(expression.expression); + } else { + this.emitName(expression.expression, true); + } + + this.writeToOutput("."); + this.emitName(expression.name, false); + + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitDottedNameMemberAccessExpressionRecurse = function (expression) { + this.emitComments(expression, true); + this.emitDottedNameMemberAccessExpression(expression); + this.emitComments(expression, false); + }; + + Emitter.prototype.emitMemberAccessExpression = function (expression) { + if (!this.tryEmitConstant(expression)) { + if (this.canEmitDottedNameMemberAccessExpression(expression)) { + this.emitDottedNameMemberAccessExpression(expression); + } else { + this.recordSourceMappingStart(expression); + this.emit(expression.expression); + this.writeToOutput("."); + this.emitName(expression.name, false); + this.recordSourceMappingEnd(expression); + } + } + }; + + Emitter.prototype.emitQualifiedName = function (name) { + this.recordSourceMappingStart(name); + + this.emit(name.left); + this.writeToOutput("."); + this.emitName(name.right, false); + + this.recordSourceMappingEnd(name); + }; + + Emitter.prototype.emitBinaryExpression = function (expression) { + this.recordSourceMappingStart(expression); + switch (expression.kind()) { + case 173 /* CommaExpression */: + this.emit(expression.left); + this.writeToOutput(", "); + this.emit(expression.right); + break; + default: { + this.emit(expression.left); + var binOp = TypeScript.SyntaxFacts.getText(TypeScript.SyntaxFacts.getOperatorTokenFromBinaryExpression(expression.kind())); + if (binOp === "instanceof") { + this.writeToOutput(" instanceof "); + } else if (binOp === "in") { + this.writeToOutput(" in "); + } else { + this.writeToOutput(" " + binOp + " "); + } + this.emit(expression.right); + } + } + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitSimplePropertyAssignment = function (property) { + this.recordSourceMappingStart(property); + this.emit(property.propertyName); + this.writeToOutput(": "); + this.emit(property.expression); + this.recordSourceMappingEnd(property); + }; + + Emitter.prototype.emitFunctionPropertyAssignment = function (funcProp) { + this.recordSourceMappingStart(funcProp); + + this.emit(funcProp.propertyName); + this.writeToOutput(": "); + + var pullFunctionDecl = this.semanticInfoChain.getDeclForAST(funcProp); + + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = false; + + var temp = this.setContainer(5 /* Function */); + var funcName = funcProp.propertyName; + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcProp); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcProp); + this.writeToOutput("function "); + + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(funcProp.propertyName.text(), funcProp, parameters, funcProp.block, null); + + this.recordSourceMappingEnd(funcProp); + + this.recordSourceMappingEnd(funcProp); + + this.emitComments(funcProp, false); + + this.popDecl(pullDecl); + + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + }; + + Emitter.prototype.emitConditionalExpression = function (expression) { + this.emit(expression.condition); + this.writeToOutput(" ? "); + this.emit(expression.whenTrue); + this.writeToOutput(" : "); + this.emit(expression.whenFalse); + }; + + Emitter.prototype.emitThrowStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("throw "); + this.emit(statement.expression); + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitExpressionStatement = function (statement) { + var isArrowExpression = statement.expression.kind() === 219 /* SimpleArrowFunctionExpression */ || statement.expression.kind() === 218 /* ParenthesizedArrowFunctionExpression */; + + this.recordSourceMappingStart(statement); + if (isArrowExpression) { + this.writeToOutput("("); + } + + this.emit(statement.expression); + + if (isArrowExpression) { + this.writeToOutput(")"); + } + + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitLabeledStatement = function (statement) { + this.writeToOutputWithSourceMapRecord(statement.identifier.text(), statement.identifier); + this.writeLineToOutput(":"); + this.emitJavascript(statement.statement, true); + }; + + Emitter.prototype.emitBlock = function (block) { + this.recordSourceMappingStart(block); + this.writeLineToOutput(" {"); + this.indenter.increaseIndent(); + if (block.statements) { + this.emitList(block.statements); + } + this.emitCommentsArray(block.closeBraceLeadingComments, false); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + this.recordSourceMappingEnd(block); + }; + + Emitter.prototype.emitBreakStatement = function (jump) { + this.recordSourceMappingStart(jump); + this.writeToOutput("break"); + + if (jump.identifier) { + this.writeToOutput(" " + jump.identifier.text()); + } + + this.recordSourceMappingEnd(jump); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitContinueStatement = function (jump) { + this.recordSourceMappingStart(jump); + this.writeToOutput("continue"); + + if (jump.identifier) { + this.writeToOutput(" " + jump.identifier.text()); + } + + this.recordSourceMappingEnd(jump); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitWhileStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("while ("); + this.emit(statement.condition); + this.writeToOutput(")"); + this.emitBlockOrStatement(statement.statement); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitDoStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("do"); + this.emitBlockOrStatement(statement.statement); + this.writeToOutputWithSourceMapRecord(" while", statement.whileKeyword); + this.writeToOutput('('); + this.emit(statement.condition); + this.writeToOutput(")"); + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitIfStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("if ("); + this.emit(statement.condition); + this.writeToOutput(")"); + + this.emitBlockOrStatement(statement.statement); + + if (statement.elseClause) { + if (statement.statement.kind() !== 146 /* Block */) { + this.writeLineToOutput(""); + this.emitIndent(); + } else { + this.writeToOutput(" "); + } + + this.emit(statement.elseClause); + } + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitElseClause = function (elseClause) { + if (elseClause.statement.kind() === 147 /* IfStatement */) { + this.writeToOutput("else "); + this.emit(elseClause.statement); + } else { + this.writeToOutput("else"); + this.emitBlockOrStatement(elseClause.statement); + } + }; + + Emitter.prototype.emitReturnStatement = function (statement) { + this.recordSourceMappingStart(statement); + if (statement.expression) { + this.writeToOutput("return "); + this.emit(statement.expression); + } else { + this.writeToOutput("return"); + } + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitForInStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("for ("); + if (statement.left) { + this.emit(statement.left); + } else { + this.emit(statement.variableDeclaration); + } + this.writeToOutput(" in "); + this.emit(statement.expression); + this.writeToOutput(")"); + this.emitBlockOrStatement(statement.statement); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitForStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("for ("); + if (statement.variableDeclaration) { + this.emit(statement.variableDeclaration); + } else if (statement.initializer) { + this.emit(statement.initializer); + } + + this.writeToOutput("; "); + this.emitJavascript(statement.condition, false); + this.writeToOutput(";"); + if (statement.incrementor) { + this.writeToOutput(" "); + this.emitJavascript(statement.incrementor, false); + } + this.writeToOutput(")"); + this.emitBlockOrStatement(statement.statement); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitWithStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("with ("); + if (statement.condition) { + this.emit(statement.condition); + } + + this.writeToOutput(")"); + var prevInWithBlock = this.inWithBlock; + this.inWithBlock = true; + this.emitBlockOrStatement(statement.statement); + this.inWithBlock = prevInWithBlock; + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitSwitchStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("switch ("); + this.emit(statement.expression); + this.recordSourceMappingStart(statement.closeParenToken); + this.writeToOutput(")"); + this.recordSourceMappingEnd(statement.closeParenToken); + this.writeLineToOutput(" {"); + this.indenter.increaseIndent(); + this.emitList(statement.switchClauses, false); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitCaseSwitchClause = function (clause) { + this.recordSourceMappingStart(clause); + this.writeToOutput("case "); + this.emit(clause.expression); + this.writeToOutput(":"); + + this.emitSwitchClauseBody(clause.statements); + this.recordSourceMappingEnd(clause); + }; + + Emitter.prototype.emitSwitchClauseBody = function (body) { + if (body.childCount() === 1 && body.childAt(0).kind() === 146 /* Block */) { + this.emit(body.childAt(0)); + this.writeLineToOutput(""); + } else { + this.writeLineToOutput(""); + this.indenter.increaseIndent(); + this.emit(body); + this.indenter.decreaseIndent(); + } + }; + + Emitter.prototype.emitDefaultSwitchClause = function (clause) { + this.recordSourceMappingStart(clause); + this.writeToOutput("default:"); + + this.emitSwitchClauseBody(clause.statements); + this.recordSourceMappingEnd(clause); + }; + + Emitter.prototype.emitTryStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("try "); + this.emit(statement.block); + this.emitJavascript(statement.catchClause, false); + + if (statement.finallyClause) { + this.emit(statement.finallyClause); + } + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitCatchClause = function (clause) { + this.writeToOutput(" "); + this.recordSourceMappingStart(clause); + this.writeToOutput("catch ("); + this.emit(clause.identifier); + this.writeToOutput(")"); + this.emit(clause.block); + this.recordSourceMappingEnd(clause); + }; + + Emitter.prototype.emitFinallyClause = function (clause) { + this.writeToOutput(" finally"); + this.emit(clause.block); + }; + + Emitter.prototype.emitDebuggerStatement = function (statement) { + this.writeToOutputWithSourceMapRecord("debugger", statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitNumericLiteral = function (literal) { + this.writeToOutputWithSourceMapRecord(literal.text(), literal); + }; + + Emitter.prototype.emitRegularExpressionLiteral = function (literal) { + this.writeToOutputWithSourceMapRecord(literal.text(), literal); + }; + + Emitter.prototype.emitStringLiteral = function (literal) { + this.writeToOutputWithSourceMapRecord(literal.text(), literal); + }; + + Emitter.prototype.emitEqualsValueClause = function (clause) { + this.writeToOutput(" = "); + this.emit(clause.value); + }; + + Emitter.prototype.emitParameter = function (parameter) { + this.writeToOutputWithSourceMapRecord(parameter.identifier.text(), parameter); + }; + + Emitter.prototype.emitConstructorDeclaration = function (declaration) { + if (declaration.block) { + this.emitConstructor(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitFunctionDeclaration = function (declaration) { + return declaration.preComments() !== null || (!TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) && declaration.block !== null); + }; + + Emitter.prototype.emitFunctionDeclaration = function (declaration) { + if (!TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) && declaration.block !== null) { + this.emitFunction(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.emitSourceUnit = function (sourceUnit) { + if (!this.document.isDeclareFile()) { + var pullDecl = this.semanticInfoChain.getDeclForAST(sourceUnit); + this.pushDecl(pullDecl); + this.emitScriptElements(sourceUnit); + this.popDecl(pullDecl); + + this.emitCommentsArray(sourceUnit.endOfFileTokenLeadingComments, false); + } + }; + + Emitter.prototype.shouldEmitEnumDeclaration = function (declaration) { + return declaration.preComments() !== null || !TypeScript.ASTHelpers.enumIsElided(declaration); + }; + + Emitter.prototype.emitEnumDeclaration = function (declaration) { + if (!TypeScript.ASTHelpers.enumIsElided(declaration)) { + this.emitComments(declaration, true); + this.emitEnum(declaration); + this.emitComments(declaration, false); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitModuleDeclaration = function (declaration) { + return declaration.preComments() !== null || !TypeScript.ASTHelpers.moduleIsElided(declaration); + }; + + Emitter.prototype.emitModuleDeclaration = function (declaration) { + if (!TypeScript.ASTHelpers.moduleIsElided(declaration)) { + this.emitModuleDeclarationWorker(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitClassDeclaration = function (declaration) { + return declaration.preComments() !== null || !TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */); + }; + + Emitter.prototype.emitClassDeclaration = function (declaration) { + if (!TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */)) { + this.emitClass(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitInterfaceDeclaration = function (declaration) { + return declaration.preComments() !== null; + }; + + Emitter.prototype.emitInterfaceDeclaration = function (declaration) { + this.emitComments(declaration, true, true); + }; + + Emitter.prototype.firstVariableDeclarator = function (statement) { + return statement.declaration.declarators.nonSeparatorAt(0); + }; + + Emitter.prototype.isNotAmbientOrHasInitializer = function (variableStatement) { + return !TypeScript.hasModifier(variableStatement.modifiers, 8 /* Ambient */) || this.firstVariableDeclarator(variableStatement).equalsValueClause !== null; + }; + + Emitter.prototype.shouldEmitVariableStatement = function (statement) { + return statement.preComments() !== null || this.isNotAmbientOrHasInitializer(statement); + }; + + Emitter.prototype.emitVariableStatement = function (statement) { + if (this.isNotAmbientOrHasInitializer(statement)) { + this.emitComments(statement, true); + this.emit(statement.declaration); + this.writeToOutput(";"); + this.emitComments(statement, false); + } else { + this.emitComments(statement, true, true); + } + }; + + Emitter.prototype.emitGenericType = function (type) { + this.emit(type.name); + }; + + Emitter.prototype.shouldEmit = function (ast) { + if (!ast) { + return false; + } + + switch (ast.kind()) { + case 133 /* ImportDeclaration */: + return this.shouldEmitImportDeclaration(ast); + case 131 /* ClassDeclaration */: + return this.shouldEmitClassDeclaration(ast); + case 128 /* InterfaceDeclaration */: + return this.shouldEmitInterfaceDeclaration(ast); + case 129 /* FunctionDeclaration */: + return this.shouldEmitFunctionDeclaration(ast); + case 130 /* ModuleDeclaration */: + return this.shouldEmitModuleDeclaration(ast); + case 148 /* VariableStatement */: + return this.shouldEmitVariableStatement(ast); + case 223 /* OmittedExpression */: + return false; + case 132 /* EnumDeclaration */: + return this.shouldEmitEnumDeclaration(ast); + } + + return true; + }; + + Emitter.prototype.emit = function (ast) { + if (!ast) { + return; + } + + switch (ast.kind()) { + case 2 /* SeparatedList */: + return this.emitSeparatedList(ast); + case 1 /* List */: + return this.emitList(ast); + case 120 /* SourceUnit */: + return this.emitSourceUnit(ast); + case 133 /* ImportDeclaration */: + return this.emitImportDeclaration(ast); + case 134 /* ExportAssignment */: + return this.setExportAssignment(ast); + case 131 /* ClassDeclaration */: + return this.emitClassDeclaration(ast); + case 128 /* InterfaceDeclaration */: + return this.emitInterfaceDeclaration(ast); + case 11 /* IdentifierName */: + return this.emitName(ast, true); + case 225 /* VariableDeclarator */: + return this.emitVariableDeclarator(ast); + case 219 /* SimpleArrowFunctionExpression */: + return this.emitSimpleArrowFunctionExpression(ast); + case 218 /* ParenthesizedArrowFunctionExpression */: + return this.emitParenthesizedArrowFunctionExpression(ast); + case 129 /* FunctionDeclaration */: + return this.emitFunctionDeclaration(ast); + case 130 /* ModuleDeclaration */: + return this.emitModuleDeclaration(ast); + case 224 /* VariableDeclaration */: + return this.emitVariableDeclaration(ast); + case 126 /* GenericType */: + return this.emitGenericType(ast); + case 137 /* ConstructorDeclaration */: + return this.emitConstructorDeclaration(ast); + case 132 /* EnumDeclaration */: + return this.emitEnumDeclaration(ast); + case 243 /* EnumElement */: + return this.emitEnumElement(ast); + case 222 /* FunctionExpression */: + return this.emitFunctionExpression(ast); + case 148 /* VariableStatement */: + return this.emitVariableStatement(ast); + } + + this.emitComments(ast, true); + this.emitWorker(ast); + this.emitComments(ast, false); + }; + + Emitter.prototype.emitWorker = function (ast) { + if (!ast) { + return; + } + + switch (ast.kind()) { + case 13 /* NumericLiteral */: + return this.emitNumericLiteral(ast); + case 12 /* RegularExpressionLiteral */: + return this.emitRegularExpressionLiteral(ast); + case 14 /* StringLiteral */: + return this.emitStringLiteral(ast); + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + case 37 /* TrueKeyword */: + return this.emitLiteralExpression(ast); + case 35 /* ThisKeyword */: + return this.emitThisExpression(ast); + case 50 /* SuperKeyword */: + return this.emitSuperExpression(ast); + case 217 /* ParenthesizedExpression */: + return this.emitParenthesizedExpression(ast); + case 214 /* ArrayLiteralExpression */: + return this.emitArrayLiteralExpression(ast); + case 211 /* PostDecrementExpression */: + case 210 /* PostIncrementExpression */: + return this.emitPostfixUnaryExpression(ast); + case 167 /* LogicalNotExpression */: + case 166 /* BitwiseNotExpression */: + case 165 /* NegateExpression */: + case 164 /* PlusExpression */: + case 168 /* PreIncrementExpression */: + case 169 /* PreDecrementExpression */: + return this.emitPrefixUnaryExpression(ast); + case 213 /* InvocationExpression */: + return this.emitInvocationExpression(ast); + case 221 /* ElementAccessExpression */: + return this.emitElementAccessExpression(ast); + case 212 /* MemberAccessExpression */: + return this.emitMemberAccessExpression(ast); + case 121 /* QualifiedName */: + return this.emitQualifiedName(ast); + case 173 /* CommaExpression */: + case 174 /* AssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 187 /* LogicalOrExpression */: + case 188 /* LogicalAndExpression */: + case 189 /* BitwiseOrExpression */: + case 190 /* BitwiseExclusiveOrExpression */: + case 191 /* BitwiseAndExpression */: + case 192 /* EqualsWithTypeConversionExpression */: + case 193 /* NotEqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + case 196 /* LessThanExpression */: + case 197 /* GreaterThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 200 /* InstanceOfExpression */: + case 201 /* InExpression */: + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + case 208 /* AddExpression */: + case 209 /* SubtractExpression */: + return this.emitBinaryExpression(ast); + case 186 /* ConditionalExpression */: + return this.emitConditionalExpression(ast); + case 232 /* EqualsValueClause */: + return this.emitEqualsValueClause(ast); + case 242 /* Parameter */: + return this.emitParameter(ast); + case 146 /* Block */: + return this.emitBlock(ast); + case 235 /* ElseClause */: + return this.emitElseClause(ast); + case 147 /* IfStatement */: + return this.emitIfStatement(ast); + case 149 /* ExpressionStatement */: + return this.emitExpressionStatement(ast); + case 139 /* GetAccessor */: + return this.emitGetAccessor(ast); + case 140 /* SetAccessor */: + return this.emitSetAccessor(ast); + case 157 /* ThrowStatement */: + return this.emitThrowStatement(ast); + case 150 /* ReturnStatement */: + return this.emitReturnStatement(ast); + case 216 /* ObjectCreationExpression */: + return this.emitObjectCreationExpression(ast); + case 151 /* SwitchStatement */: + return this.emitSwitchStatement(ast); + case 233 /* CaseSwitchClause */: + return this.emitCaseSwitchClause(ast); + case 234 /* DefaultSwitchClause */: + return this.emitDefaultSwitchClause(ast); + case 152 /* BreakStatement */: + return this.emitBreakStatement(ast); + case 153 /* ContinueStatement */: + return this.emitContinueStatement(ast); + case 154 /* ForStatement */: + return this.emitForStatement(ast); + case 155 /* ForInStatement */: + return this.emitForInStatement(ast); + case 158 /* WhileStatement */: + return this.emitWhileStatement(ast); + case 163 /* WithStatement */: + return this.emitWithStatement(ast); + case 220 /* CastExpression */: + return this.emitCastExpression(ast); + case 215 /* ObjectLiteralExpression */: + return this.emitObjectLiteralExpression(ast); + case 240 /* SimplePropertyAssignment */: + return this.emitSimplePropertyAssignment(ast); + case 241 /* FunctionPropertyAssignment */: + return this.emitFunctionPropertyAssignment(ast); + case 156 /* EmptyStatement */: + return this.writeToOutputWithSourceMapRecord(";", ast); + case 159 /* TryStatement */: + return this.emitTryStatement(ast); + case 236 /* CatchClause */: + return this.emitCatchClause(ast); + case 237 /* FinallyClause */: + return this.emitFinallyClause(ast); + case 160 /* LabeledStatement */: + return this.emitLabeledStatement(ast); + case 161 /* DoStatement */: + return this.emitDoStatement(ast); + case 171 /* TypeOfExpression */: + return this.emitTypeOfExpression(ast); + case 170 /* DeleteExpression */: + return this.emitDeleteExpression(ast); + case 172 /* VoidExpression */: + return this.emitVoidExpression(ast); + case 162 /* DebuggerStatement */: + return this.emitDebuggerStatement(ast); + } + }; + return Emitter; + })(); + TypeScript.Emitter = Emitter; + + function getLastConstructor(classDecl) { + return classDecl.classElements.lastOrDefault(function (e) { + return e.kind() === 137 /* ConstructorDeclaration */; + }); + } + TypeScript.getLastConstructor = getLastConstructor; + + function getTrimmedTextLines(comment) { + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + return comment.fullText().split("\n").map(function (s) { + return s.trim(); + }); + } else { + return [comment.fullText().trim()]; + } + } + TypeScript.getTrimmedTextLines = getTrimmedTextLines; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var MemberName = (function () { + function MemberName() { + this.prefix = ""; + this.suffix = ""; + } + MemberName.prototype.isString = function () { + return false; + }; + MemberName.prototype.isArray = function () { + return false; + }; + MemberName.prototype.isMarker = function () { + return !this.isString() && !this.isArray(); + }; + + MemberName.prototype.toString = function () { + return MemberName.memberNameToString(this); + }; + + MemberName.memberNameToString = function (memberName, markerInfo, markerBaseLength) { + if (typeof markerBaseLength === "undefined") { markerBaseLength = 0; } + var result = memberName.prefix; + + if (memberName.isString()) { + result += memberName.text; + } else if (memberName.isArray()) { + var ar = memberName; + for (var index = 0; index < ar.entries.length; index++) { + if (ar.entries[index].isMarker()) { + if (markerInfo) { + markerInfo.push(markerBaseLength + result.length); + } + continue; + } + + result += MemberName.memberNameToString(ar.entries[index], markerInfo, markerBaseLength + result.length); + result += ar.delim; + } + } + + result += memberName.suffix; + return result; + }; + + MemberName.create = function (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.call(this); + 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; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function stripStartAndEndQuotes(str) { + var firstCharCode = str && str.charCodeAt(0); + if (str && str.length >= 2 && firstCharCode === str.charCodeAt(str.length - 1) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { + return str.substring(1, str.length - 1); + } + + return str; + } + TypeScript.stripStartAndEndQuotes = stripStartAndEndQuotes; + + function isSingleQuoted(str) { + return str && str.length >= 2 && str.charCodeAt(0) === str.charCodeAt(str.length - 1) && str.charCodeAt(0) === 39 /* singleQuote */; + } + TypeScript.isSingleQuoted = isSingleQuoted; + + function isDoubleQuoted(str) { + return str && str.length >= 2 && str.charCodeAt(0) === str.charCodeAt(str.length - 1) && str.charCodeAt(0) === 34 /* doubleQuote */; + } + TypeScript.isDoubleQuoted = isDoubleQuoted; + + function isQuoted(str) { + return isDoubleQuoted(str) || isSingleQuoted(str); + } + TypeScript.isQuoted = isQuoted; + + function quoteStr(str) { + return "\"" + str + "\""; + } + TypeScript.quoteStr = quoteStr; + + var switchToForwardSlashesRegEx = /\\/g; + function switchToForwardSlashes(path) { + return path.replace(switchToForwardSlashesRegEx, "/"); + } + TypeScript.switchToForwardSlashes = switchToForwardSlashes; + + function trimModName(modName) { + 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 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 isTSFile(fname) { + return isFileOfExtension(fname, ".ts"); + } + TypeScript.isTSFile = isTSFile; + + 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(stripStartAndEndQuotes(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, isAbsoultePathURL) { + if (typeof isAbsoultePathURL === "undefined") { isAbsoultePathURL = true; } + 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("/"); + } + + if (isAbsoultePathURL && absoluteModPath.indexOf("://") === -1) { + absoluteModPath = "file:///" + absoluteModPath; + } + + return absoluteModPath; + } + TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; + + function changePathToDTS(modPath) { + return trimModName(stripStartAndEndQuotes(modPath)) + ".d.ts"; + } + TypeScript.changePathToDTS = changePathToDTS; + + function isRelative(path) { + return path.length > 0 && path.charAt(0) === "."; + } + TypeScript.isRelative = isRelative; + function isRooted(path) { + return path.length > 0 && (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 convertToDirectoryPath(dirPath) { + if (dirPath && dirPath.charAt(dirPath.length - 1) !== "/") { + dirPath += "/"; + } + + return dirPath; + } + TypeScript.convertToDirectoryPath = convertToDirectoryPath; + + var normalizePathRegEx = /^\\\\[^\\]/; + function normalizePath(path) { + if (normalizePathRegEx.test(path)) { + path = "file:" + path; + } + var parts = this.getPathComponents(switchToForwardSlashes(path)); + var normalizedParts = []; + + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + if (part === ".") { + continue; + } + + if (normalizedParts.length > 0 && TypeScript.ArrayUtilities.last(normalizedParts) !== ".." && part === "..") { + normalizedParts.pop(); + continue; + } + + normalizedParts.push(part); + } + + return normalizedParts.join("/"); + } + TypeScript.normalizePath = normalizePath; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + + + function isNoDefaultLibMatch(comment) { + var isNoDefaultLibRegex = /^(\/\/\/\s*/gim; + return isNoDefaultLibRegex.exec(comment); + } + + TypeScript.tripleSlashReferenceRegExp = /^(\/\/\/\s*/; + + function getFileReferenceFromReferencePath(fileName, lineMap, position, comment, diagnostics) { + var simpleReferenceRegEx = /^\/\/\/\s*= 7 && fullReference[6] === "true"; + if (isResident) { + TypeScript.CompilerDiagnostics.debugPrint(path + " is resident"); + } + return { + line: 0, + character: 0, + position: 0, + length: 0, + path: TypeScript.switchToForwardSlashes(adjustedPath), + isResident: isResident + }; + } + } + } + + return null; + } + + var scannerWindow = TypeScript.ArrayUtilities.createArray(2048, 0); + var scannerDiagnostics = []; + + function processImports(lineMap, scanner, token, importedFiles) { + var position = 0; + var lineChar = { line: -1, character: -1 }; + + var start = new Date().getTime(); + + while (token.tokenKind !== 10 /* EndOfFileToken */) { + if (token.tokenKind === 49 /* ImportKeyword */) { + var importStart = position + token.leadingTriviaWidth(); + token = scanner.scan(scannerDiagnostics, false); + + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 107 /* EqualsToken */) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 65 /* ModuleKeyword */ || token.tokenKind === 66 /* RequireKeyword */) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 72 /* OpenParenToken */) { + var afterOpenParenPosition = scanner.absoluteIndex(); + token = scanner.scan(scannerDiagnostics, false); + + lineMap.fillLineAndCharacterFromPosition(importStart, lineChar); + + if (token.tokenKind === 14 /* StringLiteral */) { + var ref = { + line: lineChar.line, + character: lineChar.character, + position: afterOpenParenPosition + token.leadingTriviaWidth(), + length: token.width(), + path: TypeScript.stripStartAndEndQuotes(TypeScript.switchToForwardSlashes(token.text())), + isResident: false + }; + importedFiles.push(ref); + } + } + } + } + } + } + + position = scanner.absoluteIndex(); + token = scanner.scan(scannerDiagnostics, false); + } + + var totalTime = new Date().getTime() - start; + TypeScript.fileResolutionScanImportsTime += totalTime; + } + + function processTripleSlashDirectives(fileName, lineMap, firstToken) { + var leadingTrivia = firstToken.leadingTrivia(); + + var position = 0; + var lineChar = { line: -1, character: -1 }; + var noDefaultLib = false; + var diagnostics = []; + var referencedFiles = []; + + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + + if (trivia.kind() === 7 /* SingleLineCommentTrivia */) { + var triviaText = trivia.fullText(); + var referencedCode = getFileReferenceFromReferencePath(fileName, lineMap, position, triviaText, diagnostics); + + if (referencedCode) { + lineMap.fillLineAndCharacterFromPosition(position, lineChar); + referencedCode.position = position; + referencedCode.length = trivia.fullWidth(); + referencedCode.line = lineChar.line; + referencedCode.character = lineChar.character; + + referencedFiles.push(referencedCode); + } + + var isNoDefaultLib = isNoDefaultLibMatch(triviaText); + if (isNoDefaultLib) { + noDefaultLib = isNoDefaultLib[3] === "true"; + } + } + + position += trivia.fullWidth(); + } + + return { noDefaultLib: noDefaultLib, diagnostics: diagnostics, referencedFiles: referencedFiles }; + } + + function preProcessFile(fileName, sourceText, readImportFiles) { + if (typeof readImportFiles === "undefined") { readImportFiles = true; } + var text = TypeScript.SimpleText.fromScriptSnapshot(sourceText); + var scanner = new TypeScript.Scanner(fileName, text, 1 /* EcmaScript5 */, scannerWindow); + + var firstToken = scanner.scan(scannerDiagnostics, false); + + var importedFiles = []; + if (readImportFiles) { + processImports(text.lineMap(), scanner, firstToken, importedFiles); + } + + var properties = processTripleSlashDirectives(fileName, text.lineMap(), firstToken); + + scannerDiagnostics.length = 0; + return { referencedFiles: properties.referencedFiles, importedFiles: importedFiles, isLibFile: properties.noDefaultLib, diagnostics: properties.diagnostics }; + } + TypeScript.preProcessFile = preProcessFile; + + function getParseOptions(settings) { + return new TypeScript.ParseOptions(settings.codeGenTarget(), settings.allowAutomaticSemicolonInsertion()); + } + TypeScript.getParseOptions = getParseOptions; + + function getReferencedFiles(fileName, sourceText) { + return preProcessFile(fileName, sourceText, false).referencedFiles; + } + TypeScript.getReferencedFiles = getReferencedFiles; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ReferenceResolutionResult = (function () { + function ReferenceResolutionResult() { + this.resolvedFiles = []; + this.diagnostics = []; + this.seenNoDefaultLibTag = false; + } + return ReferenceResolutionResult; + })(); + TypeScript.ReferenceResolutionResult = ReferenceResolutionResult; + + var ReferenceLocation = (function () { + function ReferenceLocation(filePath, lineMap, position, length, isImported) { + this.filePath = filePath; + this.lineMap = lineMap; + this.position = position; + this.length = length; + this.isImported = isImported; + } + return ReferenceLocation; + })(); + + var ReferenceResolver = (function () { + function ReferenceResolver(inputFileNames, host, useCaseSensitiveFileResolution) { + this.useCaseSensitiveFileResolution = useCaseSensitiveFileResolution; + this.inputFileNames = inputFileNames; + this.host = host; + this.visited = {}; + } + ReferenceResolver.resolve = function (inputFileNames, host, useCaseSensitiveFileResolution) { + var resolver = new ReferenceResolver(inputFileNames, host, useCaseSensitiveFileResolution); + return resolver.resolveInputFiles(); + }; + + ReferenceResolver.prototype.resolveInputFiles = function () { + var _this = this; + var result = new ReferenceResolutionResult(); + + if (!this.inputFileNames || this.inputFileNames.length <= 0) { + return result; + } + + var referenceLocation = new ReferenceLocation(null, null, 0, 0, false); + this.inputFileNames.forEach(function (fileName) { + return _this.resolveIncludedFile(fileName, referenceLocation, result); + }); + + return result; + }; + + ReferenceResolver.prototype.resolveIncludedFile = function (path, referenceLocation, resolutionResult) { + var normalizedPath = this.getNormalizedFilePath(path, referenceLocation.filePath); + + if (this.isSameFile(normalizedPath, referenceLocation.filePath)) { + if (!referenceLocation.isImported) { + resolutionResult.diagnostics.push(new TypeScript.Diagnostic(referenceLocation.filePath, referenceLocation.lineMap, referenceLocation.position, referenceLocation.length, TypeScript.DiagnosticCode.A_file_cannot_have_a_reference_to_itself, null)); + } + + return normalizedPath; + } + + if (!TypeScript.isTSFile(normalizedPath) && !TypeScript.isDTSFile(normalizedPath)) { + var dtsFile = normalizedPath + ".d.ts"; + var tsFile = normalizedPath + ".ts"; + + if (this.host.fileExists(tsFile)) { + normalizedPath = tsFile; + } else { + normalizedPath = dtsFile; + } + } + + if (!this.host.fileExists(normalizedPath)) { + if (!referenceLocation.isImported) { + resolutionResult.diagnostics.push(new TypeScript.Diagnostic(referenceLocation.filePath, referenceLocation.lineMap, referenceLocation.position, referenceLocation.length, TypeScript.DiagnosticCode.Cannot_resolve_referenced_file_0, [path])); + } + + return normalizedPath; + } + + return this.resolveFile(normalizedPath, resolutionResult); + }; + + ReferenceResolver.prototype.resolveImportedFile = function (path, referenceLocation, resolutionResult) { + var isRelativePath = TypeScript.isRelative(path); + var isRootedPath = isRelativePath ? false : TypeScript.isRooted(path); + + if (isRelativePath || isRootedPath) { + return this.resolveIncludedFile(path, referenceLocation, resolutionResult); + } else { + var parentDirectory = this.host.getParentDirectory(referenceLocation.filePath); + var searchFilePath = null; + var dtsFileName = path + ".d.ts"; + var tsFilePath = path + ".ts"; + + var start = new Date().getTime(); + + do { + currentFilePath = this.host.resolveRelativePath(tsFilePath, parentDirectory); + if (this.host.fileExists(currentFilePath)) { + searchFilePath = currentFilePath; + break; + } + + var currentFilePath = this.host.resolveRelativePath(dtsFileName, parentDirectory); + if (this.host.fileExists(currentFilePath)) { + searchFilePath = currentFilePath; + break; + } + + parentDirectory = this.host.getParentDirectory(parentDirectory); + } while(parentDirectory); + + TypeScript.fileResolutionImportFileSearchTime += new Date().getTime() - start; + + if (!searchFilePath) { + return path; + } + + return this.resolveFile(searchFilePath, resolutionResult); + } + }; + + ReferenceResolver.prototype.resolveFile = function (normalizedPath, resolutionResult) { + var _this = this; + var visitedPath = this.isVisited(normalizedPath); + if (!visitedPath) { + this.recordVisitedFile(normalizedPath); + + var start = new Date().getTime(); + var scriptSnapshot = this.host.getScriptSnapshot(normalizedPath); + var totalTime = new Date().getTime() - start; + TypeScript.fileResolutionIOTime += totalTime; + + var lineMap = TypeScript.LineMap1.fromScriptSnapshot(scriptSnapshot); + var preprocessedFileInformation = TypeScript.preProcessFile(normalizedPath, scriptSnapshot); + resolutionResult.diagnostics.push.apply(resolutionResult.diagnostics, preprocessedFileInformation.diagnostics); + + if (preprocessedFileInformation.isLibFile) { + resolutionResult.seenNoDefaultLibTag = true; + } + + var normalizedReferencePaths = []; + preprocessedFileInformation.referencedFiles.forEach(function (fileReference) { + var currentReferenceLocation = new ReferenceLocation(normalizedPath, lineMap, fileReference.position, fileReference.length, false); + var normalizedReferencePath = _this.resolveIncludedFile(fileReference.path, currentReferenceLocation, resolutionResult); + normalizedReferencePaths.push(normalizedReferencePath); + }); + + var normalizedImportPaths = []; + for (var i = 0; i < preprocessedFileInformation.importedFiles.length; i++) { + var fileImport = preprocessedFileInformation.importedFiles[i]; + var currentReferenceLocation = new ReferenceLocation(normalizedPath, lineMap, fileImport.position, fileImport.length, true); + var normalizedImportPath = this.resolveImportedFile(fileImport.path, currentReferenceLocation, resolutionResult); + normalizedImportPaths.push(normalizedImportPath); + } + + resolutionResult.resolvedFiles.push({ + path: normalizedPath, + referencedFiles: normalizedReferencePaths, + importedFiles: normalizedImportPaths + }); + } else { + normalizedPath = visitedPath; + } + + return normalizedPath; + }; + + ReferenceResolver.prototype.getNormalizedFilePath = function (path, parentFilePath) { + var parentFileDirectory = parentFilePath ? this.host.getParentDirectory(parentFilePath) : ""; + var normalizedPath = this.host.resolveRelativePath(path, parentFileDirectory); + return normalizedPath; + }; + + ReferenceResolver.prototype.getUniqueFileId = function (filePath) { + return this.useCaseSensitiveFileResolution ? filePath : filePath.toLocaleUpperCase(); + }; + + ReferenceResolver.prototype.recordVisitedFile = function (filePath) { + this.visited[this.getUniqueFileId(filePath)] = filePath; + }; + + ReferenceResolver.prototype.isVisited = function (filePath) { + return this.visited[this.getUniqueFileId(filePath)]; + }; + + ReferenceResolver.prototype.isSameFile = function (filePath1, filePath2) { + if (!filePath1 || !filePath2) { + return false; + } + + if (this.useCaseSensitiveFileResolution) { + return filePath1 === filePath2; + } else { + return filePath1.toLocaleUpperCase() === filePath2.toLocaleUpperCase(); + } + }; + return ReferenceResolver; + })(); + TypeScript.ReferenceResolver = ReferenceResolver; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextWriter = (function () { + function TextWriter(name, writeByteOrderMark, outputFileType) { + this.name = name; + this.writeByteOrderMark = writeByteOrderMark; + this.outputFileType = outputFileType; + this.contents = ""; + this.onNewLine = true; + } + TextWriter.prototype.Write = function (s) { + this.contents += s; + this.onNewLine = false; + }; + + TextWriter.prototype.WriteLine = function (s) { + this.contents += s; + this.contents += TypeScript.newLine(); + this.onNewLine = true; + }; + + TextWriter.prototype.Close = function () { + }; + + TextWriter.prototype.getOutputFile = function () { + return new TypeScript.OutputFile(this.name, this.writeByteOrderMark, this.contents, this.outputFileType); + }; + return TextWriter; + })(); + TypeScript.TextWriter = TextWriter; + + var DeclarationEmitter = (function () { + function DeclarationEmitter(emittingFileName, document, compiler, emitOptions, semanticInfoChain) { + this.emittingFileName = emittingFileName; + this.document = document; + this.compiler = compiler; + this.emitOptions = emitOptions; + this.semanticInfoChain = semanticInfoChain; + this.declFile = null; + this.indenter = new TypeScript.Indenter(); + this.emittedReferencePaths = false; + this.declFile = new TextWriter(emittingFileName, this.document.byteOrderMark !== 0 /* None */, 2 /* Declaration */); + } + DeclarationEmitter.prototype.getOutputFile = function () { + return this.declFile.getOutputFile(); + }; + + DeclarationEmitter.prototype.emitDeclarations = function (sourceUnit) { + this.emitDeclarationsForSourceUnit(sourceUnit); + }; + + DeclarationEmitter.prototype.emitDeclarationsForList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + this.emitDeclarationsForAST(list.childAt(i)); + } + }; + + DeclarationEmitter.prototype.emitSeparatedList = function (list) { + for (var i = 0, n = list.nonSeparatorCount(); i < n; i++) { + this.emitDeclarationsForAST(list.nonSeparatorAt(i)); + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForAST = function (ast) { + switch (ast.kind()) { + case 148 /* VariableStatement */: + return this.emitDeclarationsForVariableStatement(ast); + case 141 /* PropertySignature */: + return this.emitPropertySignature(ast); + case 225 /* VariableDeclarator */: + return this.emitVariableDeclarator(ast, true, true); + case 136 /* MemberVariableDeclaration */: + return this.emitDeclarationsForMemberVariableDeclaration(ast); + case 137 /* ConstructorDeclaration */: + return this.emitDeclarationsForConstructorDeclaration(ast); + case 139 /* GetAccessor */: + return this.emitDeclarationsForGetAccessor(ast); + case 140 /* SetAccessor */: + return this.emitDeclarationsForSetAccessor(ast); + case 138 /* IndexMemberDeclaration */: + return this.emitIndexMemberDeclaration(ast); + case 144 /* IndexSignature */: + return this.emitIndexSignature(ast); + case 142 /* CallSignature */: + return this.emitCallSignature(ast); + case 143 /* ConstructSignature */: + return this.emitConstructSignature(ast); + case 145 /* MethodSignature */: + return this.emitMethodSignature(ast); + case 129 /* FunctionDeclaration */: + return this.emitDeclarationsForFunctionDeclaration(ast); + case 135 /* MemberFunctionDeclaration */: + return this.emitMemberFunctionDeclaration(ast); + case 131 /* ClassDeclaration */: + return this.emitDeclarationsForClassDeclaration(ast); + case 128 /* InterfaceDeclaration */: + return this.emitDeclarationsForInterfaceDeclaration(ast); + case 133 /* ImportDeclaration */: + return this.emitDeclarationsForImportDeclaration(ast); + case 130 /* ModuleDeclaration */: + return this.emitDeclarationsForModuleDeclaration(ast); + case 132 /* EnumDeclaration */: + return this.emitDeclarationsForEnumDeclaration(ast); + case 134 /* ExportAssignment */: + return this.emitDeclarationsForExportAssignment(ast); + } + }; + + DeclarationEmitter.prototype.getIndentString = function (declIndent) { + if (typeof declIndent === "undefined") { declIndent = false; } + return this.indenter.getIndent(); + }; + + DeclarationEmitter.prototype.emitIndent = function () { + this.declFile.Write(this.getIndentString()); + }; + + DeclarationEmitter.prototype.canEmitDeclarations = function (declAST) { + var container = DeclarationEmitter.getEnclosingContainer(declAST); + if (container.kind() === 130 /* ModuleDeclaration */ || container.kind() === 120 /* SourceUnit */) { + var pullDecl = this.semanticInfoChain.getDeclForAST(declAST); + if (!TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */)) { + var start = new Date().getTime(); + var declSymbol = this.semanticInfoChain.getSymbolForAST(declAST); + var result = declSymbol && declSymbol.isExternallyVisible(); + TypeScript.declarationEmitIsExternallyVisibleTime += new Date().getTime() - start; + + return result; + } + } + + return true; + }; + + DeclarationEmitter.prototype.getDeclFlagsString = function (pullDecl, typeString) { + var result = this.getIndentString(); + var pullFlags = pullDecl.flags; + + if (TypeScript.hasFlag(pullFlags, 16 /* Static */)) { + if (TypeScript.hasFlag(pullFlags, 2 /* Private */)) { + result += "private "; + } + result += "static "; + } else { + if (TypeScript.hasFlag(pullFlags, 2 /* Private */)) { + result += "private "; + } else if (TypeScript.hasFlag(pullFlags, 4 /* Public */)) { + result += "public "; + } else { + var emitDeclare = !TypeScript.hasFlag(pullFlags, 1 /* Exported */); + + var declAST = this.semanticInfoChain.getASTForDecl(pullDecl); + var container = DeclarationEmitter.getEnclosingContainer(declAST); + + var isExternalModule = container.kind() === 120 /* SourceUnit */ && this.document.isExternalModule(); + + if (isExternalModule && TypeScript.hasFlag(pullFlags, 1 /* Exported */)) { + result += "export "; + emitDeclare = true; + } + + if (isExternalModule || container.kind() === 120 /* SourceUnit */) { + if (emitDeclare && typeString !== "interface" && typeString !== "import") { + result += "declare "; + } + } + + result += typeString + " "; + } + } + + return result; + }; + + DeclarationEmitter.prototype.emitDeclFlags = function (declarationAST, typeString) { + this.declFile.Write(this.getDeclFlagsString(this.semanticInfoChain.getDeclForAST(declarationAST), typeString)); + }; + + 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 if (memberName.isArray()) { + 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 (ast, type) { + var declarationContainerAst = DeclarationEmitter.getEnclosingContainer(ast); + + var start = new Date().getTime(); + var declarationContainerDecl = this.semanticInfoChain.getDeclForAST(declarationContainerAst); + + var declarationPullSymbol = declarationContainerDecl.getSymbol(); + TypeScript.declarationEmitTypeSignatureTime += new Date().getTime() - start; + + var isNotAGenericType = ast.kind() !== 126 /* GenericType */; + + var typeNameMembers = type.getScopedNameEx(declarationPullSymbol, false, false, false, false, false, isNotAGenericType); + this.emitTypeNamesMember(typeNameMembers); + }; + + DeclarationEmitter.prototype.emitComment = function (comment) { + var text = TypeScript.getTrimmedTextLines(comment); + if (this.declFile.onNewLine) { + this.emitIndent(); + } else if (comment.kind() !== 6 /* MultiLineCommentTrivia */) { + 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.kind() !== 6 /* MultiLineCommentTrivia */) { + this.declFile.WriteLine(""); + } else { + this.declFile.Write(" "); + } + }; + + DeclarationEmitter.prototype.emitDeclarationComments = function (astOrSymbol, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + if (this.emitOptions.compilationSettings().removeComments()) { + return; + } + + var declComments = astOrSymbol.docComments ? astOrSymbol.docComments() : TypeScript.ASTHelpers.docComments(astOrSymbol); + this.writeDeclarationComments(declComments, endLine); + }; + + DeclarationEmitter.prototype.writeDeclarationComments = function (declComments, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + 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.emitTypeOfVariableDeclaratorOrParameter = function (boundDecl) { + var start = new Date().getTime(); + var decl = this.semanticInfoChain.getDeclForAST(boundDecl); + var pullSymbol = decl.getSymbol(); + TypeScript.declarationEmitGetBoundDeclTypeTime += new Date().getTime() - start; + + var type = pullSymbol.type; + TypeScript.Debug.assert(type); + + this.declFile.Write(": "); + this.emitTypeSignature(boundDecl, type); + }; + + DeclarationEmitter.prototype.emitPropertySignature = function (varDecl) { + this.emitDeclarationComments(varDecl); + this.emitIndent(); + this.declFile.Write(varDecl.propertyName.text()); + if (varDecl.questionToken) { + this.declFile.Write("?"); + } + + this.emitTypeOfVariableDeclaratorOrParameter(varDecl); + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitVariableDeclarator = function (varDecl, isFirstVarInList, isLastVarInList) { + if (this.canEmitDeclarations(varDecl)) { + this.emitDeclarationComments(varDecl); + + if (isFirstVarInList) { + this.emitDeclFlags(varDecl, "var"); + } + + this.declFile.Write(varDecl.propertyName.text()); + + if (!TypeScript.hasModifier(TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), 2 /* Private */)) { + this.emitTypeOfVariableDeclaratorOrParameter(varDecl); + } + + if (isLastVarInList) { + this.declFile.WriteLine(";"); + } else { + this.declFile.Write(", "); + } + } + }; + + DeclarationEmitter.prototype.emitClassElementModifiers = function (modifiers) { + if (TypeScript.hasModifier(modifiers, 16 /* Static */)) { + if (TypeScript.hasModifier(modifiers, 2 /* Private */)) { + this.declFile.Write("private "); + } + this.declFile.Write("static "); + } else { + if (TypeScript.hasModifier(modifiers, 2 /* Private */)) { + this.declFile.Write("private "); + } else { + this.declFile.Write("public "); + } + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForMemberVariableDeclaration = function (varDecl) { + if (this.canEmitDeclarations(varDecl)) { + this.emitDeclarationComments(varDecl); + + this.declFile.Write(this.getIndentString()); + this.emitClassElementModifiers(varDecl.modifiers); + ; + + this.declFile.Write(varDecl.variableDeclarator.propertyName.text()); + + if (!TypeScript.hasModifier(varDecl.modifiers, 2 /* Private */)) { + this.emitTypeOfVariableDeclaratorOrParameter(varDecl); + } + + this.declFile.WriteLine(";"); + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForVariableStatement = function (variableStatement) { + this.emitDeclarationsForVariableDeclaration(variableStatement.declaration); + }; + + DeclarationEmitter.prototype.emitDeclarationsForVariableDeclaration = function (variableDeclaration) { + var varListCount = variableDeclaration.declarators.nonSeparatorCount(); + for (var i = 0; i < varListCount; i++) { + this.emitVariableDeclarator(variableDeclaration.declarators.nonSeparatorAt(i), i === 0, i === varListCount - 1); + } + }; + + DeclarationEmitter.prototype.emitArgDecl = function (argDecl, id, isOptional, isPrivate) { + this.indenter.increaseIndent(); + + this.emitDeclarationComments(argDecl, false); + this.declFile.Write(id.text()); + if (isOptional) { + this.declFile.Write("?"); + } + + this.indenter.decreaseIndent(); + + if (!isPrivate) { + this.emitTypeOfVariableDeclaratorOrParameter(argDecl); + } + }; + + DeclarationEmitter.prototype.isOverloadedCallSignature = function (funcDecl) { + var start = new Date().getTime(); + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSymbol = functionDecl.getSymbol(); + TypeScript.declarationEmitIsOverloadedCallSignatureTime += new Date().getTime() - start; + + var funcTypeSymbol = funcSymbol.type; + var signatures = funcTypeSymbol.getCallSignatures(); + var result = signatures && signatures.length > 1; + + return result; + }; + + DeclarationEmitter.prototype.emitDeclarationsForConstructorDeclaration = function (funcDecl) { + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + var funcTypeSymbol = funcSymbol.type; + if (funcDecl.block) { + var constructSignatures = funcTypeSymbol.getConstructSignatures(); + if (constructSignatures && constructSignatures.length > 1) { + return; + } + } + + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write("constructor"); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitParameterList = function (isPrivate, parameterList) { + this.declFile.Write("("); + this.emitParameters(isPrivate, TypeScript.ASTHelpers.parametersFromParameterList(parameterList)); + this.declFile.Write(")"); + }; + + DeclarationEmitter.prototype.emitParameters = function (isPrivate, parameterList) { + var hasLastParameterRestParameter = parameterList.lastParameterIsRest(); + var argsLen = parameterList.length; + if (hasLastParameterRestParameter) { + argsLen--; + } + + for (var i = 0; i < argsLen; i++) { + this.emitArgDecl(parameterList.astAt(i), parameterList.identifierAt(i), parameterList.isOptionalAt(i), isPrivate); + if (i < (argsLen - 1)) { + this.declFile.Write(", "); + } + } + + if (hasLastParameterRestParameter) { + if (parameterList.length > 1) { + this.declFile.Write(", ..."); + } else { + this.declFile.Write("..."); + } + + var index = parameterList.length - 1; + this.emitArgDecl(parameterList.astAt(index), parameterList.identifierAt(index), parameterList.isOptionalAt(index), isPrivate); + } + }; + + DeclarationEmitter.prototype.emitMemberFunctionDeclaration = function (funcDecl) { + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + var funcTypeSymbol = funcSymbol.type; + if (funcDecl.block) { + var constructSignatures = funcTypeSymbol.getConstructSignatures(); + if (constructSignatures && constructSignatures.length > 1) { + return; + } else if (this.isOverloadedCallSignature(funcDecl)) { + return; + } + } else if (TypeScript.hasModifier(funcDecl.modifiers, 2 /* Private */) && this.isOverloadedCallSignature(funcDecl)) { + var callSignatures = funcTypeSymbol.getCallSignatures(); + TypeScript.Debug.assert(callSignatures && callSignatures.length > 1); + var firstSignature = callSignatures[0].isDefinition() ? callSignatures[1] : callSignatures[0]; + var firstSignatureDecl = firstSignature.getDeclarations()[0]; + var firstFuncDecl = this.semanticInfoChain.getASTForDecl(firstSignatureDecl); + if (firstFuncDecl !== funcDecl) { + return; + } + } + + if (!this.canEmitDeclarations(funcDecl)) { + return; + } + + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitDeclarationComments(funcDecl); + + this.emitDeclFlags(funcDecl, "function"); + var id = funcDecl.propertyName.text(); + this.declFile.Write(id); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + var isPrivate = TypeScript.hasModifier(funcDecl.modifiers, 2 /* Private */); + + this.emitParameterList(isPrivate, funcDecl.callSignature.parameterList); + + if (!isPrivate) { + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + this.emitTypeSignature(funcDecl, returnType); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitCallSignature = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + this.emitDeclarationComments(funcDecl); + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.typeParameterList, funcSignature); + + this.emitIndent(); + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitConstructSignature = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write("new"); + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitMethodSignature = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write(funcDecl.propertyName.text()); + if (funcDecl.questionToken) { + this.declFile.Write("? "); + } + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForFunctionDeclaration = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + if (funcDecl.block) { + var funcTypeSymbol = funcSymbol.type; + var constructSignatures = funcTypeSymbol.getConstructSignatures(); + if (constructSignatures && constructSignatures.length > 1) { + return; + } else if (this.isOverloadedCallSignature(funcDecl)) { + return; + } + } + + if (!this.canEmitDeclarations(funcDecl)) { + return; + } + + this.emitDeclarationComments(funcDecl); + + var id = funcDecl.identifier.text(); + this.emitDeclFlags(funcDecl, "function"); + if (id !== "" || !funcDecl.identifier || funcDecl.identifier.text().length > 0) { + this.declFile.Write(id); + } else if (funcPullDecl.kind === 2097152 /* ConstructSignature */) { + this.declFile.Write("new"); + } + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitIndexMemberDeclaration = function (funcDecl) { + this.emitDeclarationsForAST(funcDecl.indexSignature); + }; + + DeclarationEmitter.prototype.emitIndexSignature = function (funcDecl) { + if (!this.canEmitDeclarations(funcDecl)) { + return; + } + + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write("["); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameter(funcDecl.parameter)); + this.declFile.Write("]"); + + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSignature = funcPullDecl.getSignatureSymbol(); + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + this.emitTypeSignature(funcDecl, returnType); + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitBaseList = function (bases, useExtendsList) { + if (bases && (bases.nonSeparatorCount() > 0)) { + var qual = useExtendsList ? "extends" : "implements"; + this.declFile.Write(" " + qual + " "); + var basesLen = bases.nonSeparatorCount(); + for (var i = 0; i < basesLen; i++) { + if (i > 0) { + this.declFile.Write(", "); + } + var base = bases.nonSeparatorAt(i); + var baseType = this.semanticInfoChain.getSymbolForAST(base); + this.emitTypeSignature(base, baseType); + } + } + }; + + DeclarationEmitter.prototype.emitAccessorDeclarationComments = function (funcDecl) { + if (this.emitOptions.compilationSettings().removeComments()) { + return; + } + + var start = new Date().getTime(); + var accessors = TypeScript.PullHelpers.getGetterAndSetterFunction(funcDecl, this.semanticInfoChain); + TypeScript.declarationEmitGetAccessorFunctionTime += new Date().getTime(); + + var comments = []; + if (accessors.getter) { + comments = comments.concat(TypeScript.ASTHelpers.docComments(accessors.getter)); + } + if (accessors.setter) { + comments = comments.concat(TypeScript.ASTHelpers.docComments(accessors.setter)); + } + + this.writeDeclarationComments(comments); + }; + + DeclarationEmitter.prototype.emitDeclarationsForGetAccessor = function (funcDecl) { + this.emitMemberAccessorDeclaration(funcDecl, funcDecl.modifiers, funcDecl.propertyName); + }; + + DeclarationEmitter.prototype.emitDeclarationsForSetAccessor = function (funcDecl) { + this.emitMemberAccessorDeclaration(funcDecl, funcDecl.modifiers, funcDecl.propertyName); + }; + + DeclarationEmitter.prototype.emitMemberAccessorDeclaration = function (funcDecl, modifiers, name) { + var start = new Date().getTime(); + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain); + TypeScript.declarationEmitGetAccessorFunctionTime += new Date().getTime(); + + if (funcDecl.kind() === 140 /* SetAccessor */ && accessorSymbol.getGetter()) { + return; + } + + var isPrivate = TypeScript.hasModifier(modifiers, 2 /* Private */); + this.emitAccessorDeclarationComments(funcDecl); + this.declFile.Write(this.getIndentString()); + this.emitClassElementModifiers(modifiers); + this.declFile.Write(name.text()); + if (!isPrivate) { + this.declFile.Write(" : "); + var type = accessorSymbol.type; + this.emitTypeSignature(funcDecl, type); + } + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { + var argsLen = funcDecl.callSignature.parameterList.parameters.nonSeparatorCount(); + if (TypeScript.lastParameterIsRest(funcDecl.callSignature.parameterList)) { + argsLen--; + } + + for (var i = 0; i < argsLen; i++) { + var parameter = funcDecl.callSignature.parameterList.parameters.nonSeparatorAt(i); + var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter); + if (TypeScript.hasFlag(parameterDecl.flags, 8388608 /* PropertyParameter */)) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.emitDeclarationComments(parameter); + this.declFile.Write(this.getIndentString()); + this.emitClassElementModifiers(parameter.modifiers); + this.declFile.Write(parameter.identifier.text()); + + if (!TypeScript.hasModifier(parameter.modifiers, 2 /* Private */)) { + this.emitTypeOfVariableDeclaratorOrParameter(parameter); + } + this.declFile.WriteLine(";"); + } + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForClassDeclaration = function (classDecl) { + if (!this.canEmitDeclarations(classDecl)) { + return; + } + + var className = classDecl.identifier.text(); + this.emitDeclarationComments(classDecl); + var classPullDecl = this.semanticInfoChain.getDeclForAST(classDecl); + this.emitDeclFlags(classDecl, "class"); + this.declFile.Write(className); + + this.emitTypeParameters(classDecl.typeParameterList); + this.emitHeritageClauses(classDecl.heritageClauses); + this.declFile.WriteLine(" {"); + + this.indenter.increaseIndent(); + var constructorDecl = TypeScript.getLastConstructor(classDecl); + if (constructorDecl) { + this.emitClassMembersFromConstructorDefinition(constructorDecl); + } + + this.emitDeclarationsForList(classDecl.classElements); + + this.indenter.decreaseIndent(); + + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitHeritageClauses = function (clauses) { + if (clauses) { + for (var i = 0, n = clauses.childCount(); i < n; i++) { + this.emitHeritageClause(clauses.childAt(i)); + } + } + }; + + DeclarationEmitter.prototype.emitHeritageClause = function (clause) { + this.emitBaseList(clause.typeNames, clause.kind() === 230 /* ExtendsHeritageClause */); + }; + + DeclarationEmitter.getEnclosingContainer = function (ast) { + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(ast); + ast = enclosingModule || ast; + + ast = ast.parent; + while (ast) { + if (ast.kind() === 131 /* ClassDeclaration */ || ast.kind() === 128 /* InterfaceDeclaration */ || ast.kind() === 130 /* ModuleDeclaration */ || ast.kind() === 120 /* SourceUnit */) { + return ast; + } + + ast = ast.parent; + } + + return null; + }; + + DeclarationEmitter.prototype.emitTypeParameters = function (typeParams, funcSignature) { + if (!typeParams || !typeParams.typeParameters.nonSeparatorCount()) { + return; + } + + this.declFile.Write("<"); + var containerAst = DeclarationEmitter.getEnclosingContainer(typeParams); + + var start = new Date().getTime(); + var containerDecl = this.semanticInfoChain.getDeclForAST(containerAst); + var containerSymbol = containerDecl.getSymbol(); + TypeScript.declarationEmitGetTypeParameterSymbolTime += new Date().getTime() - start; + + var typars; + if (funcSignature) { + typars = funcSignature.getTypeParameters(); + } else { + typars = containerSymbol.getTypeArgumentsOrTypeParameters(); + } + + for (var i = 0; i < typars.length; i++) { + if (i) { + this.declFile.Write(", "); + } + + var memberName = typars[i].getScopedNameEx(containerSymbol, false, true); + this.emitTypeNamesMember(memberName); + } + + this.declFile.Write(">"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForInterfaceDeclaration = function (interfaceDecl) { + if (!this.canEmitDeclarations(interfaceDecl)) { + return; + } + + var interfaceName = interfaceDecl.identifier.text(); + this.emitDeclarationComments(interfaceDecl); + var interfacePullDecl = this.semanticInfoChain.getDeclForAST(interfaceDecl); + this.emitDeclFlags(interfaceDecl, "interface"); + this.declFile.Write(interfaceName); + + this.emitTypeParameters(interfaceDecl.typeParameterList); + this.emitHeritageClauses(interfaceDecl.heritageClauses); + this.declFile.WriteLine(" {"); + + this.indenter.increaseIndent(); + + this.emitSeparatedList(interfaceDecl.body.typeMembers); + + this.indenter.decreaseIndent(); + + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForImportDeclaration = function (importDeclAST) { + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); + var importSymbol = importDecl.getSymbol(); + var isExportedImportDecl = TypeScript.hasModifier(importDeclAST.modifiers, 1 /* Exported */); + + if (isExportedImportDecl || importSymbol.typeUsedExternally() || TypeScript.PullContainerSymbol.usedAsSymbol(importSymbol.getContainer(), importSymbol)) { + this.emitDeclarationComments(importDeclAST); + this.emitIndent(); + if (isExportedImportDecl) { + this.declFile.Write("export "); + } + this.declFile.Write("import "); + this.declFile.Write(importDeclAST.identifier.text() + " = "); + if (importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + this.declFile.WriteLine("require(" + importDeclAST.moduleReference.stringLiteral.text() + ");"); + } else { + this.declFile.WriteLine(TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(importDeclAST.moduleReference.moduleName) + ";"); + } + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForEnumDeclaration = function (moduleDecl) { + if (!this.canEmitDeclarations(moduleDecl)) { + return; + } + + this.emitDeclarationComments(moduleDecl); + var modulePullDecl = this.semanticInfoChain.getDeclForAST(moduleDecl); + this.emitDeclFlags(moduleDecl, "enum"); + this.declFile.WriteLine(moduleDecl.identifier.text() + " {"); + + this.indenter.increaseIndent(); + var membersLen = moduleDecl.enumElements.nonSeparatorCount(); + for (var j = 0; j < membersLen; j++) { + var memberDecl = moduleDecl.enumElements.nonSeparatorAt(j); + var enumElement = memberDecl; + var enumElementDecl = this.semanticInfoChain.getDeclForAST(enumElement); + this.emitDeclarationComments(enumElement); + this.emitIndent(); + this.declFile.Write(enumElement.propertyName.text()); + if (enumElementDecl.constantValue !== null) { + this.declFile.Write(" = " + enumElementDecl.constantValue); + } + this.declFile.WriteLine(","); + } + this.indenter.decreaseIndent(); + + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForModuleDeclaration = function (moduleDecl) { + var name = moduleDecl.stringLiteral || TypeScript.ArrayUtilities.first(TypeScript.ASTHelpers.getModuleNames(moduleDecl.name)); + if (!this.canEmitDeclarations(name)) { + return; + } + + this.emitDeclarationComments(moduleDecl); + this.emitDeclFlags(name, "module"); + + if (moduleDecl.stringLiteral) { + this.declFile.Write(moduleDecl.stringLiteral.text()); + } else { + this.declFile.Write(TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(moduleDecl.name)); + } + + this.declFile.WriteLine(" {"); + this.indenter.increaseIndent(); + + this.emitDeclarationsForList(moduleDecl.moduleElements); + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForExportAssignment = function (ast) { + this.emitIndent(); + this.declFile.Write("export = "); + this.declFile.Write(ast.identifier.text()); + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.resolveScriptReference = function (document, reference) { + if (!this.emitOptions.compilationSettings().noResolve() || TypeScript.isRooted(reference)) { + return reference; + } + + var documentDir = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(TypeScript.getRootFilePath(document.fileName))); + var resolvedReferencePath = this.emitOptions.resolvePath(documentDir + reference); + return resolvedReferencePath; + }; + + DeclarationEmitter.prototype.emitReferencePaths = function (sourceUnit) { + if (this.emittedReferencePaths) { + return; + } + + var documents = []; + if (this.document.emitToOwnOutputFile()) { + var scriptReferences = this.document.referencedFiles; + var addedGlobalDocument = false; + for (var j = 0; j < scriptReferences.length; j++) { + var currentReference = this.resolveScriptReference(this.document, scriptReferences[j]); + var document = this.compiler.getDocument(currentReference); + + if (document && (document.emitToOwnOutputFile() || document.isDeclareFile() || !addedGlobalDocument)) { + documents = documents.concat(document); + + if (!document.isDeclareFile() && document.isExternalModule()) { + addedGlobalDocument = true; + } + } + } + } else { + var fileNames = this.compiler.fileNames(); + for (var i = 0; i < fileNames.length; i++) { + var doc = this.compiler.getDocument(fileNames[i]); + if (!doc.isDeclareFile() && !doc.isExternalModule()) { + var scriptReferences = doc.referencedFiles; + for (var j = 0; j < scriptReferences.length; j++) { + var currentReference = this.resolveScriptReference(doc, scriptReferences[j]); + var document = this.compiler.getDocument(currentReference); + + if (document && (document.isDeclareFile() || document.isExternalModule())) { + for (var k = 0; k < documents.length; k++) { + if (documents[k] === document) { + break; + } + } + + if (k === documents.length) { + documents = documents.concat(document); + } + } + } + } + } + } + + var emittingFilePath = documents.length ? TypeScript.getRootFilePath(this.emittingFileName) : null; + for (var i = 0; i < documents.length; i++) { + var document = documents[i]; + var declFileName; + if (document.isDeclareFile()) { + declFileName = document.fileName; + } else { + declFileName = this.compiler.mapOutputFileName(document, this.emitOptions, TypeScript.TypeScriptCompiler.mapToDTSFileName); + } + + declFileName = TypeScript.getRelativePathToFixedPath(emittingFilePath, declFileName, false); + this.declFile.WriteLine('/// '); + } + + this.emittedReferencePaths = true; + }; + + DeclarationEmitter.prototype.emitDeclarationsForSourceUnit = function (sourceUnit) { + this.emitReferencePaths(sourceUnit); + this.emitDeclarationsForList(sourceUnit.moduleElements); + }; + return DeclarationEmitter; + })(); + TypeScript.DeclarationEmitter = DeclarationEmitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var BloomFilter = (function () { + function BloomFilter(expectedCount) { + var m = Math.max(1, BloomFilter.computeM(expectedCount)); + var k = Math.max(1, BloomFilter.computeK(expectedCount)); + ; + + var sizeInEvenBytes = (m + 7) & ~7; + + this.bitArray = []; + for (var i = 0, len = sizeInEvenBytes; i < len; i++) { + this.bitArray[i] = false; + } + this.hashFunctionCount = k; + } + BloomFilter.computeM = function (expectedCount) { + var p = BloomFilter.falsePositiveProbability; + var n = expectedCount; + + var numerator = n * Math.log(p); + var denominator = Math.log(1.0 / Math.pow(2.0, Math.log(2.0))); + return Math.ceil(numerator / denominator); + }; + + BloomFilter.computeK = function (expectedCount) { + var n = expectedCount; + var m = BloomFilter.computeM(expectedCount); + + var temp = Math.log(2.0) * m / n; + return Math.round(temp); + }; + + BloomFilter.prototype.computeHash = function (key, seed) { + return TypeScript.Hash.computeMurmur2StringHashCode(key, seed); + }; + + BloomFilter.prototype.addKeys = function (keys) { + for (var name in keys) { + if (keys[name]) { + this.add(name); + } + } + }; + + BloomFilter.prototype.add = function (value) { + for (var i = 0; i < this.hashFunctionCount; i++) { + var hash = this.computeHash(value, i); + hash = hash % this.bitArray.length; + this.bitArray[Math.abs(hash)] = true; + } + }; + + BloomFilter.prototype.probablyContains = function (value) { + for (var i = 0; i < this.hashFunctionCount; i++) { + var hash = this.computeHash(value, i); + hash = hash % this.bitArray.length; + if (!this.bitArray[Math.abs(hash)]) { + return false; + } + } + + return true; + }; + + BloomFilter.prototype.isEquivalent = function (filter) { + return BloomFilter.isEquivalent(this.bitArray, filter.bitArray) && this.hashFunctionCount === filter.hashFunctionCount; + }; + + BloomFilter.isEquivalent = function (array1, array2) { + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; i++) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; + }; + BloomFilter.falsePositiveProbability = 0.0001; + return BloomFilter; + })(); + TypeScript.BloomFilter = BloomFilter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var IdentifierWalker = (function (_super) { + __extends(IdentifierWalker, _super); + function IdentifierWalker(list) { + _super.call(this); + this.list = list; + } + IdentifierWalker.prototype.visitToken = function (token) { + this.list[token.text()] = true; + }; + return IdentifierWalker; + })(TypeScript.SyntaxWalker); + TypeScript.IdentifierWalker = IdentifierWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CompilationSettings = (function () { + function CompilationSettings() { + this.propagateEnumConstants = false; + this.removeComments = false; + this.watch = false; + this.noResolve = false; + this.allowAutomaticSemicolonInsertion = true; + this.noImplicitAny = false; + this.noLib = false; + this.codeGenTarget = 0 /* EcmaScript3 */; + this.moduleGenTarget = 0 /* Unspecified */; + this.outFileOption = ""; + this.outDirOption = ""; + this.mapSourceFiles = false; + this.mapRoot = ""; + this.sourceRoot = ""; + this.generateDeclarationFiles = false; + this.useCaseSensitiveFileResolution = false; + this.gatherDiagnostics = false; + this.codepage = null; + this.createFileLog = false; + } + return CompilationSettings; + })(); + TypeScript.CompilationSettings = CompilationSettings; + + var ImmutableCompilationSettings = (function () { + function ImmutableCompilationSettings(propagateEnumConstants, removeComments, watch, noResolve, allowAutomaticSemicolonInsertion, noImplicitAny, noLib, codeGenTarget, moduleGenTarget, outFileOption, outDirOption, mapSourceFiles, mapRoot, sourceRoot, generateDeclarationFiles, useCaseSensitiveFileResolution, gatherDiagnostics, codepage, createFileLog) { + this._propagateEnumConstants = propagateEnumConstants; + this._removeComments = removeComments; + this._watch = watch; + this._noResolve = noResolve; + this._allowAutomaticSemicolonInsertion = allowAutomaticSemicolonInsertion; + this._noImplicitAny = noImplicitAny; + this._noLib = noLib; + this._codeGenTarget = codeGenTarget; + this._moduleGenTarget = moduleGenTarget; + this._outFileOption = outFileOption; + this._outDirOption = outDirOption; + this._mapSourceFiles = mapSourceFiles; + this._mapRoot = mapRoot; + this._sourceRoot = sourceRoot; + this._generateDeclarationFiles = generateDeclarationFiles; + this._useCaseSensitiveFileResolution = useCaseSensitiveFileResolution; + this._gatherDiagnostics = gatherDiagnostics; + this._codepage = codepage; + this._createFileLog = createFileLog; + } + ImmutableCompilationSettings.prototype.propagateEnumConstants = function () { + return this._propagateEnumConstants; + }; + ImmutableCompilationSettings.prototype.removeComments = function () { + return this._removeComments; + }; + ImmutableCompilationSettings.prototype.watch = function () { + return this._watch; + }; + ImmutableCompilationSettings.prototype.noResolve = function () { + return this._noResolve; + }; + ImmutableCompilationSettings.prototype.allowAutomaticSemicolonInsertion = function () { + return this._allowAutomaticSemicolonInsertion; + }; + ImmutableCompilationSettings.prototype.noImplicitAny = function () { + return this._noImplicitAny; + }; + ImmutableCompilationSettings.prototype.noLib = function () { + return this._noLib; + }; + ImmutableCompilationSettings.prototype.codeGenTarget = function () { + return this._codeGenTarget; + }; + ImmutableCompilationSettings.prototype.moduleGenTarget = function () { + return this._moduleGenTarget; + }; + ImmutableCompilationSettings.prototype.outFileOption = function () { + return this._outFileOption; + }; + ImmutableCompilationSettings.prototype.outDirOption = function () { + return this._outDirOption; + }; + ImmutableCompilationSettings.prototype.mapSourceFiles = function () { + return this._mapSourceFiles; + }; + ImmutableCompilationSettings.prototype.mapRoot = function () { + return this._mapRoot; + }; + ImmutableCompilationSettings.prototype.sourceRoot = function () { + return this._sourceRoot; + }; + ImmutableCompilationSettings.prototype.generateDeclarationFiles = function () { + return this._generateDeclarationFiles; + }; + ImmutableCompilationSettings.prototype.useCaseSensitiveFileResolution = function () { + return this._useCaseSensitiveFileResolution; + }; + ImmutableCompilationSettings.prototype.gatherDiagnostics = function () { + return this._gatherDiagnostics; + }; + ImmutableCompilationSettings.prototype.codepage = function () { + return this._codepage; + }; + ImmutableCompilationSettings.prototype.createFileLog = function () { + return this._createFileLog; + }; + + ImmutableCompilationSettings.defaultSettings = function () { + if (!ImmutableCompilationSettings._defaultSettings) { + ImmutableCompilationSettings._defaultSettings = ImmutableCompilationSettings.fromCompilationSettings(new CompilationSettings()); + } + + return ImmutableCompilationSettings._defaultSettings; + }; + + ImmutableCompilationSettings.fromCompilationSettings = function (settings) { + return new ImmutableCompilationSettings(settings.propagateEnumConstants, settings.removeComments, settings.watch, settings.noResolve, settings.allowAutomaticSemicolonInsertion, settings.noImplicitAny, settings.noLib, settings.codeGenTarget, settings.moduleGenTarget, settings.outFileOption, settings.outDirOption, settings.mapSourceFiles, settings.mapRoot, settings.sourceRoot, settings.generateDeclarationFiles, settings.useCaseSensitiveFileResolution, settings.gatherDiagnostics, settings.codepage, settings.createFileLog); + }; + + ImmutableCompilationSettings.prototype.toCompilationSettings = function () { + var result = new CompilationSettings(); + + var thisAsIndexable = this; + var resultAsIndexable = result; + for (var name in this) { + if (this.hasOwnProperty(name) && TypeScript.StringUtilities.startsWith(name, "_")) { + resultAsIndexable[name.substr(1)] = thisAsIndexable[name]; + } + } + + return result; + }; + return ImmutableCompilationSettings; + })(); + TypeScript.ImmutableCompilationSettings = ImmutableCompilationSettings; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (PullElementFlags) { + PullElementFlags[PullElementFlags["None"] = 0] = "None"; + PullElementFlags[PullElementFlags["Exported"] = 1] = "Exported"; + PullElementFlags[PullElementFlags["Private"] = 1 << 1] = "Private"; + PullElementFlags[PullElementFlags["Public"] = 1 << 2] = "Public"; + PullElementFlags[PullElementFlags["Ambient"] = 1 << 3] = "Ambient"; + PullElementFlags[PullElementFlags["Static"] = 1 << 4] = "Static"; + PullElementFlags[PullElementFlags["Optional"] = 1 << 7] = "Optional"; + PullElementFlags[PullElementFlags["Signature"] = 1 << 11] = "Signature"; + PullElementFlags[PullElementFlags["Enum"] = 1 << 12] = "Enum"; + PullElementFlags[PullElementFlags["ArrowFunction"] = 1 << 13] = "ArrowFunction"; + + PullElementFlags[PullElementFlags["ClassConstructorVariable"] = 1 << 14] = "ClassConstructorVariable"; + PullElementFlags[PullElementFlags["InitializedModule"] = 1 << 15] = "InitializedModule"; + PullElementFlags[PullElementFlags["InitializedDynamicModule"] = 1 << 16] = "InitializedDynamicModule"; + + PullElementFlags[PullElementFlags["MustCaptureThis"] = 1 << 18] = "MustCaptureThis"; + + PullElementFlags[PullElementFlags["DeclaredInAWithBlock"] = 1 << 21] = "DeclaredInAWithBlock"; + + PullElementFlags[PullElementFlags["HasReturnStatement"] = 1 << 22] = "HasReturnStatement"; + + PullElementFlags[PullElementFlags["PropertyParameter"] = 1 << 23] = "PropertyParameter"; + + PullElementFlags[PullElementFlags["IsAnnotatedWithAny"] = 1 << 24] = "IsAnnotatedWithAny"; + + PullElementFlags[PullElementFlags["HasDefaultArgs"] = 1 << 25] = "HasDefaultArgs"; + + PullElementFlags[PullElementFlags["ConstructorParameter"] = 1 << 26] = "ConstructorParameter"; + + PullElementFlags[PullElementFlags["ImplicitVariable"] = PullElementFlags.ClassConstructorVariable | PullElementFlags.InitializedModule | PullElementFlags.InitializedDynamicModule | PullElementFlags.Enum] = "ImplicitVariable"; + PullElementFlags[PullElementFlags["SomeInitializedModule"] = PullElementFlags.InitializedModule | PullElementFlags.InitializedDynamicModule | PullElementFlags.Enum] = "SomeInitializedModule"; + })(TypeScript.PullElementFlags || (TypeScript.PullElementFlags = {})); + var PullElementFlags = TypeScript.PullElementFlags; + + function hasModifier(modifiers, flag) { + for (var i = 0, n = modifiers.length; i < n; i++) { + if (TypeScript.hasFlag(modifiers[i], flag)) { + return true; + } + } + + return false; + } + TypeScript.hasModifier = hasModifier; + + (function (PullElementKind) { + PullElementKind[PullElementKind["None"] = 0] = "None"; + PullElementKind[PullElementKind["Global"] = 0] = "Global"; + + PullElementKind[PullElementKind["Script"] = 1 << 0] = "Script"; + PullElementKind[PullElementKind["Primitive"] = 1 << 1] = "Primitive"; + + PullElementKind[PullElementKind["Container"] = 1 << 2] = "Container"; + PullElementKind[PullElementKind["Class"] = 1 << 3] = "Class"; + PullElementKind[PullElementKind["Interface"] = 1 << 4] = "Interface"; + PullElementKind[PullElementKind["DynamicModule"] = 1 << 5] = "DynamicModule"; + PullElementKind[PullElementKind["Enum"] = 1 << 6] = "Enum"; + PullElementKind[PullElementKind["TypeAlias"] = 1 << 7] = "TypeAlias"; + PullElementKind[PullElementKind["ObjectLiteral"] = 1 << 8] = "ObjectLiteral"; + + PullElementKind[PullElementKind["Variable"] = 1 << 9] = "Variable"; + PullElementKind[PullElementKind["CatchVariable"] = 1 << 10] = "CatchVariable"; + PullElementKind[PullElementKind["Parameter"] = 1 << 11] = "Parameter"; + PullElementKind[PullElementKind["Property"] = 1 << 12] = "Property"; + PullElementKind[PullElementKind["TypeParameter"] = 1 << 13] = "TypeParameter"; + + PullElementKind[PullElementKind["Function"] = 1 << 14] = "Function"; + PullElementKind[PullElementKind["ConstructorMethod"] = 1 << 15] = "ConstructorMethod"; + PullElementKind[PullElementKind["Method"] = 1 << 16] = "Method"; + PullElementKind[PullElementKind["FunctionExpression"] = 1 << 17] = "FunctionExpression"; + + PullElementKind[PullElementKind["GetAccessor"] = 1 << 18] = "GetAccessor"; + PullElementKind[PullElementKind["SetAccessor"] = 1 << 19] = "SetAccessor"; + + PullElementKind[PullElementKind["CallSignature"] = 1 << 20] = "CallSignature"; + PullElementKind[PullElementKind["ConstructSignature"] = 1 << 21] = "ConstructSignature"; + PullElementKind[PullElementKind["IndexSignature"] = 1 << 22] = "IndexSignature"; + + PullElementKind[PullElementKind["ObjectType"] = 1 << 23] = "ObjectType"; + PullElementKind[PullElementKind["FunctionType"] = 1 << 24] = "FunctionType"; + PullElementKind[PullElementKind["ConstructorType"] = 1 << 25] = "ConstructorType"; + + PullElementKind[PullElementKind["EnumMember"] = 1 << 26] = "EnumMember"; + + PullElementKind[PullElementKind["WithBlock"] = 1 << 27] = "WithBlock"; + PullElementKind[PullElementKind["CatchBlock"] = 1 << 28] = "CatchBlock"; + + PullElementKind[PullElementKind["All"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Container | PullElementKind.Class | PullElementKind.Interface | PullElementKind.DynamicModule | PullElementKind.Enum | PullElementKind.TypeAlias | PullElementKind.ObjectLiteral | PullElementKind.Variable | PullElementKind.Parameter | PullElementKind.Property | PullElementKind.TypeParameter | PullElementKind.Function | PullElementKind.ConstructorMethod | PullElementKind.Method | PullElementKind.FunctionExpression | PullElementKind.GetAccessor | PullElementKind.SetAccessor | PullElementKind.CallSignature | PullElementKind.ConstructSignature | PullElementKind.IndexSignature | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.EnumMember | PullElementKind.WithBlock | PullElementKind.CatchBlock] = "All"; + + PullElementKind[PullElementKind["SomeFunction"] = PullElementKind.Function | PullElementKind.ConstructorMethod | PullElementKind.Method | PullElementKind.FunctionExpression | PullElementKind.GetAccessor | PullElementKind.SetAccessor] = "SomeFunction"; + + PullElementKind[PullElementKind["SomeValue"] = PullElementKind.Variable | PullElementKind.Parameter | PullElementKind.Property | PullElementKind.EnumMember | PullElementKind.SomeFunction] = "SomeValue"; + + PullElementKind[PullElementKind["SomeType"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.ObjectLiteral | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.TypeParameter] = "SomeType"; + + PullElementKind[PullElementKind["AcceptableAlias"] = PullElementKind.Variable | PullElementKind.SomeFunction | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.Container | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType] = "AcceptableAlias"; + + PullElementKind[PullElementKind["SomeContainer"] = PullElementKind.Container | PullElementKind.DynamicModule | PullElementKind.TypeAlias] = "SomeContainer"; + + PullElementKind[PullElementKind["SomeSignature"] = PullElementKind.CallSignature | PullElementKind.ConstructSignature | PullElementKind.IndexSignature] = "SomeSignature"; + + PullElementKind[PullElementKind["SomeTypeReference"] = PullElementKind.Interface | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType] = "SomeTypeReference"; + + PullElementKind[PullElementKind["SomeInstantiatableType"] = PullElementKind.Class | PullElementKind.Interface | PullElementKind.TypeParameter] = "SomeInstantiatableType"; + })(TypeScript.PullElementKind || (TypeScript.PullElementKind = {})); + var PullElementKind = TypeScript.PullElementKind; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var pullDeclID = 0; + var sentinelEmptyPullDeclArray = []; + + var PullDecl = (function () { + function PullDecl(declName, displayName, kind, declFlags, semanticInfoChain) { + this.declID = pullDeclID++; + this.flags = 0 /* None */; + this.declGroups = null; + this.childDecls = null; + this.typeParameters = null; + this.synthesizedValDecl = null; + this.containerDecl = null; + this.childDeclTypeCache = null; + this.childDeclValueCache = null; + this.childDeclNamespaceCache = null; + this.childDeclTypeParameterCache = null; + this.name = declName; + this.kind = kind; + this.flags = declFlags; + this.semanticInfoChain = semanticInfoChain; + + if (displayName !== this.name) { + this.declDisplayName = displayName; + } + } + PullDecl.prototype.fileName = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.getParentPath = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.getParentDecl = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.isExternalModule = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.getEnclosingDecl = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype._getEnclosingDeclFromParentDecl = function () { + var decl = this; + while (decl) { + switch (decl.kind) { + default: + return decl; + case 512 /* Variable */: + case 8192 /* TypeParameter */: + case 2048 /* Parameter */: + case 128 /* TypeAlias */: + case 67108864 /* EnumMember */: + } + + decl = decl.getParentDecl(); + } + + TypeScript.Debug.fail(); + }; + + PullDecl.prototype.getDisplayName = function () { + return this.declDisplayName === undefined ? this.name : this.declDisplayName; + }; + + PullDecl.prototype.setSymbol = function (symbol) { + this.semanticInfoChain.setSymbolForDecl(this, symbol); + }; + + PullDecl.prototype.ensureSymbolIsBound = function () { + if (!this.hasBeenBound() && this.kind !== 1 /* Script */) { + var binder = this.semanticInfoChain.getBinder(); + binder.bindDeclToPullSymbol(this); + } + }; + + PullDecl.prototype.getSymbol = function () { + if (this.kind === 1 /* Script */) { + return null; + } + + this.ensureSymbolIsBound(); + + return this.semanticInfoChain.getSymbolForDecl(this); + }; + + PullDecl.prototype.hasSymbol = function () { + var symbol = this.semanticInfoChain.getSymbolForDecl(this); + return !!symbol; + }; + + PullDecl.prototype.setSignatureSymbol = function (signatureSymbol) { + this.semanticInfoChain.setSignatureSymbolForDecl(this, signatureSymbol); + }; + + PullDecl.prototype.getSignatureSymbol = function () { + this.ensureSymbolIsBound(); + return this.semanticInfoChain.getSignatureSymbolForDecl(this); + }; + + PullDecl.prototype.hasSignatureSymbol = function () { + var signatureSymbol = this.semanticInfoChain.getSignatureSymbolForDecl(this); + return !!signatureSymbol; + }; + + PullDecl.prototype.setFlags = function (flags) { + this.flags = flags; + }; + + PullDecl.prototype.setFlag = function (flags) { + this.flags |= flags; + }; + + PullDecl.prototype.setValueDecl = function (valDecl) { + this.synthesizedValDecl = valDecl; + valDecl.containerDecl = this; + }; + + PullDecl.prototype.getValueDecl = function () { + return this.synthesizedValDecl; + }; + + PullDecl.prototype.getContainerDecl = function () { + return this.containerDecl; + }; + + PullDecl.prototype.getChildDeclCache = function (declKind) { + if (declKind === 8192 /* TypeParameter */) { + if (!this.childDeclTypeParameterCache) { + this.childDeclTypeParameterCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclTypeParameterCache; + } else if (TypeScript.hasFlag(declKind, 164 /* SomeContainer */)) { + if (!this.childDeclNamespaceCache) { + this.childDeclNamespaceCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclNamespaceCache; + } else if (TypeScript.hasFlag(declKind, 58728795 /* SomeType */)) { + if (!this.childDeclTypeCache) { + this.childDeclTypeCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclTypeCache; + } else { + if (!this.childDeclValueCache) { + this.childDeclValueCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclValueCache; + } + }; + + PullDecl.prototype.addChildDecl = function (childDecl) { + if (childDecl.kind === 8192 /* TypeParameter */) { + if (!this.typeParameters) { + this.typeParameters = []; + } + this.typeParameters[this.typeParameters.length] = childDecl; + } else { + if (!this.childDecls) { + this.childDecls = []; + } + this.childDecls[this.childDecls.length] = childDecl; + } + + var declName = childDecl.name; + + if (!(childDecl.kind & 7340032 /* SomeSignature */)) { + var cache = this.getChildDeclCache(childDecl.kind); + var childrenOfName = cache[declName]; + if (!childrenOfName) { + childrenOfName = []; + } + + childrenOfName.push(childDecl); + cache[declName] = childrenOfName; + } + }; + + PullDecl.prototype.searchChildDecls = function (declName, searchKind) { + var cacheVal = null; + + if (searchKind & 58728795 /* SomeType */) { + cacheVal = this.childDeclTypeCache ? this.childDeclTypeCache[declName] : null; + } else if (searchKind & 164 /* SomeContainer */) { + cacheVal = this.childDeclNamespaceCache ? this.childDeclNamespaceCache[declName] : null; + } else { + cacheVal = this.childDeclValueCache ? this.childDeclValueCache[declName] : null; + } + + if (cacheVal) { + return cacheVal; + } else { + if (searchKind & 58728795 /* SomeType */) { + cacheVal = this.childDeclTypeParameterCache ? this.childDeclTypeParameterCache[declName] : null; + + if (cacheVal) { + return cacheVal; + } + } + + return sentinelEmptyPullDeclArray; + } + }; + + PullDecl.prototype.getChildDecls = function () { + return this.childDecls || sentinelEmptyPullDeclArray; + }; + + PullDecl.prototype.getTypeParameters = function () { + return this.typeParameters || sentinelEmptyPullDeclArray; + }; + + PullDecl.prototype.addVariableDeclToGroup = function (decl) { + if (!this.declGroups) { + this.declGroups = TypeScript.createIntrinsicsObject(); + } + + var declGroup = this.declGroups[decl.name]; + if (declGroup) { + declGroup.addDecl(decl); + } else { + declGroup = new PullDeclGroup(decl.name); + declGroup.addDecl(decl); + this.declGroups[decl.name] = declGroup; + } + }; + + PullDecl.prototype.getVariableDeclGroups = function () { + var declGroups = null; + + if (this.declGroups) { + for (var declName in this.declGroups) { + if (this.declGroups[declName]) { + if (declGroups === null) { + declGroups = []; + } + + declGroups.push(this.declGroups[declName].getDecls()); + } + } + } + + return declGroups || sentinelEmptyPullDeclArray; + }; + + PullDecl.prototype.hasBeenBound = function () { + return this.hasSymbol() || this.hasSignatureSymbol(); + }; + + PullDecl.prototype.isSynthesized = function () { + return false; + }; + + PullDecl.prototype.ast = function () { + return this.semanticInfoChain.getASTForDecl(this); + }; + + PullDecl.prototype.isRootDecl = function () { + throw TypeScript.Errors.abstract(); + }; + return PullDecl; + })(); + TypeScript.PullDecl = PullDecl; + + var RootPullDecl = (function (_super) { + __extends(RootPullDecl, _super); + function RootPullDecl(name, fileName, kind, declFlags, semanticInfoChain, isExternalModule) { + _super.call(this, name, name, kind, declFlags, semanticInfoChain); + this.semanticInfoChain = semanticInfoChain; + this._isExternalModule = isExternalModule; + this._fileName = fileName; + } + RootPullDecl.prototype.fileName = function () { + return this._fileName; + }; + + RootPullDecl.prototype.getParentPath = function () { + return [this]; + }; + + RootPullDecl.prototype.getParentDecl = function () { + return null; + }; + + RootPullDecl.prototype.isExternalModule = function () { + return this._isExternalModule; + }; + + RootPullDecl.prototype.getEnclosingDecl = function () { + return this; + }; + + RootPullDecl.prototype.isRootDecl = function () { + return true; + }; + return RootPullDecl; + })(PullDecl); + TypeScript.RootPullDecl = RootPullDecl; + + var NormalPullDecl = (function (_super) { + __extends(NormalPullDecl, _super); + function NormalPullDecl(declName, displayName, kind, declFlags, parentDecl, addToParent) { + if (typeof addToParent === "undefined") { addToParent = true; } + _super.call(this, declName, displayName, kind, declFlags, parentDecl ? parentDecl.semanticInfoChain : null); + this.parentDecl = null; + this.parentPath = null; + + this.parentDecl = parentDecl; + if (addToParent) { + parentDecl.addChildDecl(this); + } + + if (this.parentDecl) { + if (this.parentDecl.isRootDecl()) { + this._rootDecl = this.parentDecl; + } else { + this._rootDecl = this.parentDecl._rootDecl; + } + } else { + TypeScript.Debug.assert(this.isSynthesized()); + this._rootDecl = null; + } + } + NormalPullDecl.prototype.fileName = function () { + return this._rootDecl.fileName(); + }; + + NormalPullDecl.prototype.getParentDecl = function () { + return this.parentDecl; + }; + + NormalPullDecl.prototype.getParentPath = function () { + if (!this.parentPath) { + var path = [this]; + var parentDecl = this.parentDecl; + + while (parentDecl) { + if (parentDecl && path[path.length - 1] !== parentDecl && !(parentDecl.kind & (256 /* ObjectLiteral */ | 8388608 /* ObjectType */))) { + path.unshift(parentDecl); + } + + parentDecl = parentDecl.getParentDecl(); + } + + this.parentPath = path; + } + + return this.parentPath; + }; + + NormalPullDecl.prototype.isExternalModule = function () { + return false; + }; + + NormalPullDecl.prototype.getEnclosingDecl = function () { + return this.parentDecl && this.parentDecl._getEnclosingDeclFromParentDecl(); + }; + + NormalPullDecl.prototype.isRootDecl = function () { + return false; + }; + return NormalPullDecl; + })(PullDecl); + TypeScript.NormalPullDecl = NormalPullDecl; + + var PullEnumElementDecl = (function (_super) { + __extends(PullEnumElementDecl, _super); + function PullEnumElementDecl(declName, displayName, parentDecl) { + _super.call(this, declName, displayName, 67108864 /* EnumMember */, 4 /* Public */, parentDecl); + this.constantValue = null; + } + return PullEnumElementDecl; + })(NormalPullDecl); + TypeScript.PullEnumElementDecl = PullEnumElementDecl; + + var PullFunctionExpressionDecl = (function (_super) { + __extends(PullFunctionExpressionDecl, _super); + function PullFunctionExpressionDecl(expressionName, declFlags, parentDecl, displayName) { + if (typeof displayName === "undefined") { displayName = ""; } + _super.call(this, "", displayName, 131072 /* FunctionExpression */, declFlags, parentDecl); + this.functionExpressionName = expressionName; + } + PullFunctionExpressionDecl.prototype.getFunctionExpressionName = function () { + return this.functionExpressionName; + }; + return PullFunctionExpressionDecl; + })(NormalPullDecl); + TypeScript.PullFunctionExpressionDecl = PullFunctionExpressionDecl; + + var PullSynthesizedDecl = (function (_super) { + __extends(PullSynthesizedDecl, _super); + function PullSynthesizedDecl(declName, displayName, kind, declFlags, parentDecl, semanticInfoChain) { + _super.call(this, declName, displayName, kind, declFlags, parentDecl, false); + this.semanticInfoChain = semanticInfoChain; + } + PullSynthesizedDecl.prototype.isSynthesized = function () { + return true; + }; + + PullSynthesizedDecl.prototype.fileName = function () { + return this._rootDecl ? this._rootDecl.fileName() : ""; + }; + return PullSynthesizedDecl; + })(NormalPullDecl); + TypeScript.PullSynthesizedDecl = PullSynthesizedDecl; + + var PullDeclGroup = (function () { + function PullDeclGroup(name) { + this.name = name; + this._decls = []; + } + PullDeclGroup.prototype.addDecl = function (decl) { + if (decl.name === this.name) { + this._decls[this._decls.length] = decl; + } + }; + + PullDeclGroup.prototype.getDecls = function () { + return this._decls; + }; + return PullDeclGroup; + })(); + TypeScript.PullDeclGroup = PullDeclGroup; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.pullSymbolID = 0; + TypeScript.sentinelEmptyArray = []; + + var PullSymbol = (function () { + function PullSymbol(name, declKind) { + this.pullSymbolID = ++TypeScript.pullSymbolID; + this._container = null; + this.type = null; + this._declarations = null; + this.isResolved = false; + this.isOptional = false; + this.inResolution = false; + this.isSynthesized = false; + this.isVarArg = false; + this.rootSymbol = null; + this._enclosingSignature = null; + this._docComments = null; + this.isPrinting = false; + this.name = name; + this.kind = declKind; + } + PullSymbol.prototype.isAny = function () { + return false; + }; + + PullSymbol.prototype.isType = function () { + return (this.kind & 58728795 /* SomeType */) !== 0; + }; + + PullSymbol.prototype.isTypeReference = function () { + return false; + }; + + PullSymbol.prototype.isSignature = function () { + return (this.kind & 7340032 /* SomeSignature */) !== 0; + }; + + PullSymbol.prototype.isArrayNamedTypeReference = function () { + return false; + }; + + PullSymbol.prototype.isPrimitive = function () { + return this.kind === 2 /* Primitive */; + }; + + PullSymbol.prototype.isAccessor = function () { + return false; + }; + + PullSymbol.prototype.isError = function () { + return false; + }; + + PullSymbol.prototype.isInterface = function () { + return this.kind === 16 /* Interface */; + }; + + PullSymbol.prototype.isMethod = function () { + return this.kind === 65536 /* Method */; + }; + + PullSymbol.prototype.isProperty = function () { + return this.kind === 4096 /* Property */; + }; + + PullSymbol.prototype.isAlias = function () { + return false; + }; + + PullSymbol.prototype.isContainer = function () { + return false; + }; + + PullSymbol.prototype.findAliasedTypeSymbols = function (scopeSymbol, skipScopeSymbolAliasesLookIn, lookIntoOnlyExportedAlias, aliasSymbols, visitedScopeDeclarations) { + if (typeof aliasSymbols === "undefined") { aliasSymbols = []; } + if (typeof visitedScopeDeclarations === "undefined") { visitedScopeDeclarations = []; } + var scopeDeclarations = scopeSymbol.getDeclarations(); + var scopeSymbolAliasesToLookIn = []; + + for (var i = 0; i < scopeDeclarations.length; i++) { + var scopeDecl = scopeDeclarations[i]; + if (!TypeScript.ArrayUtilities.contains(visitedScopeDeclarations, scopeDecl)) { + visitedScopeDeclarations.push(scopeDecl); + + var childDecls = scopeDecl.getChildDecls(); + for (var j = 0; j < childDecls.length; j++) { + var childDecl = childDecls[j]; + if (childDecl.kind === 128 /* TypeAlias */ && (!lookIntoOnlyExportedAlias || (childDecl.flags & 1 /* Exported */))) { + var symbol = childDecl.getSymbol(); + + if (PullContainerSymbol.usedAsSymbol(symbol, this) || (this.rootSymbol && PullContainerSymbol.usedAsSymbol(symbol, this.rootSymbol))) { + aliasSymbols.push(symbol); + return aliasSymbols; + } + + if (!skipScopeSymbolAliasesLookIn && PullSymbol._isExternalModuleReferenceAlias(symbol) && (!symbol.assignedContainer().hasExportAssignment() || (symbol.assignedContainer().getExportAssignedContainerSymbol() && symbol.assignedContainer().getExportAssignedContainerSymbol().kind === 32 /* DynamicModule */))) { + scopeSymbolAliasesToLookIn.push(symbol); + } + } + } + } + } + + for (var i = 0; i < scopeSymbolAliasesToLookIn.length; i++) { + var scopeSymbolAlias = scopeSymbolAliasesToLookIn[i]; + + aliasSymbols.push(scopeSymbolAlias); + var result = this.findAliasedTypeSymbols(scopeSymbolAlias.assignedContainer().hasExportAssignment() ? scopeSymbolAlias.assignedContainer().getExportAssignedContainerSymbol() : scopeSymbolAlias.assignedContainer(), false, true, aliasSymbols, visitedScopeDeclarations); + if (result) { + return result; + } + + aliasSymbols.pop(); + } + + return null; + }; + + PullSymbol.prototype.getExternalAliasedSymbols = function (scopeSymbol) { + if (!scopeSymbol) { + return null; + } + + var scopePath = scopeSymbol.pathToRoot(); + if (scopePath.length && scopePath[scopePath.length - 1].kind === 32 /* DynamicModule */) { + var symbols = this.findAliasedTypeSymbols(scopePath[scopePath.length - 1]); + return symbols; + } + + return null; + }; + + PullSymbol._isExternalModuleReferenceAlias = function (aliasSymbol) { + if (aliasSymbol) { + if (aliasSymbol.assignedValue()) { + return false; + } + + if (aliasSymbol.assignedType() && aliasSymbol.assignedType() !== aliasSymbol.assignedContainer()) { + return false; + } + + if (aliasSymbol.assignedContainer() && aliasSymbol.assignedContainer().kind !== 32 /* DynamicModule */) { + return false; + } + + return true; + } + + return false; + }; + + PullSymbol.prototype.getExportedInternalAliasSymbol = function (scopeSymbol) { + if (scopeSymbol) { + if (this.kind !== 128 /* TypeAlias */) { + var scopePath = scopeSymbol.pathToRoot(); + for (var i = 0; i < scopePath.length; i++) { + var internalAliases = this.findAliasedTypeSymbols(scopeSymbol, true, true); + if (internalAliases) { + TypeScript.Debug.assert(internalAliases.length === 1); + return internalAliases[0]; + } + } + } + } + + return null; + }; + + PullSymbol.prototype.getAliasSymbolName = function (scopeSymbol, aliasNameGetter, aliasPartsNameGetter, skipInternalAlias) { + if (!skipInternalAlias) { + var internalAlias = this.getExportedInternalAliasSymbol(scopeSymbol); + if (internalAlias) { + return aliasNameGetter(internalAlias); + } + } + + var externalAliases = this.getExternalAliasedSymbols(scopeSymbol); + + if (externalAliases && externalAliases[0] != this && PullSymbol._isExternalModuleReferenceAlias(externalAliases[externalAliases.length - 1])) { + var aliasFullName = aliasNameGetter(externalAliases[0]); + if (!aliasFullName) { + return null; + } + for (var i = 1, symbolsLen = externalAliases.length; i < symbolsLen; i++) { + aliasFullName = aliasFullName + "." + aliasPartsNameGetter(externalAliases[i]); + } + return aliasFullName; + } + + return null; + }; + + PullSymbol.prototype._getResolver = function () { + TypeScript.Debug.assert(this._declarations && this._declarations.length > 0); + return this._declarations[0].semanticInfoChain.getResolver(); + }; + + PullSymbol.prototype._resolveDeclaredSymbol = function () { + return this._getResolver().resolveDeclaredSymbol(this); + }; + + PullSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + var aliasName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getName(scopeSymbol, useConstraintInName); + }, function (symbol) { + return symbol.getName(); + }); + return aliasName || this.name; + }; + + PullSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { + var aliasDisplayName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getDisplayName(scopeSymbol, useConstraintInName); + }, function (symbol) { + return symbol.getDisplayName(); + }, skipInternalAliasName); + if (aliasDisplayName) { + return aliasDisplayName; + } + + var decls = this.getDeclarations(); + var name = decls.length && decls[0].getDisplayName(); + + return (name && name.length) ? name : this.name; + }; + + PullSymbol.prototype.getIsSpecialized = function () { + return false; + }; + + PullSymbol.prototype.getRootSymbol = function () { + if (!this.rootSymbol) { + return this; + } + return this.rootSymbol; + }; + PullSymbol.prototype.setRootSymbol = function (symbol) { + this.rootSymbol = symbol; + }; + + PullSymbol.prototype.setIsSynthesized = function (value) { + if (typeof value === "undefined") { value = true; } + TypeScript.Debug.assert(this.rootSymbol == null); + this.isSynthesized = value; + }; + + PullSymbol.prototype.getIsSynthesized = function () { + if (this.rootSymbol) { + return this.rootSymbol.getIsSynthesized(); + } + return this.isSynthesized; + }; + + PullSymbol.prototype.setEnclosingSignature = function (signature) { + this._enclosingSignature = signature; + }; + + PullSymbol.prototype.getEnclosingSignature = function () { + return this._enclosingSignature; + }; + + PullSymbol.prototype.addDeclaration = function (decl) { + TypeScript.Debug.assert(!!decl); + + if (this.rootSymbol) { + return; + } + + if (!this._declarations) { + this._declarations = [decl]; + } else { + this._declarations[this._declarations.length] = decl; + } + }; + + PullSymbol.prototype.getDeclarations = function () { + if (this.rootSymbol) { + return this.rootSymbol.getDeclarations(); + } + + if (!this._declarations) { + this._declarations = []; + } + + return this._declarations; + }; + + PullSymbol.prototype.hasDeclaration = function (decl) { + if (!this._declarations) { + return false; + } + + return TypeScript.ArrayUtilities.any(this._declarations, function (eachDecl) { + return eachDecl === decl; + }); + }; + + PullSymbol.prototype.setContainer = function (containerSymbol) { + if (this.rootSymbol) { + return; + } + + this._container = containerSymbol; + }; + + PullSymbol.prototype.getContainer = function () { + if (this.rootSymbol) { + return this.rootSymbol.getContainer(); + } + + return this._container; + }; + + PullSymbol.prototype.setResolved = function () { + this.isResolved = true; + this.inResolution = false; + }; + + PullSymbol.prototype.startResolving = function () { + this.inResolution = true; + }; + + PullSymbol.prototype.setUnresolved = function () { + this.isResolved = false; + this.inResolution = false; + }; + + PullSymbol.prototype.anyDeclHasFlag = function (flag) { + var declarations = this.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + if (TypeScript.hasFlag(declarations[i].flags, flag)) { + return true; + } + } + return false; + }; + + PullSymbol.prototype.allDeclsHaveFlag = function (flag) { + var declarations = this.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + if (!TypeScript.hasFlag(declarations[i].flags, flag)) { + return false; + } + } + return true; + }; + + PullSymbol.prototype.pathToRoot = function () { + var path = []; + var node = this; + while (node) { + if (node.isType()) { + var associatedContainerSymbol = node.getAssociatedContainerType(); + if (associatedContainerSymbol) { + node = associatedContainerSymbol; + } + } + path[path.length] = node; + var nodeKind = node.kind; + if (nodeKind === 2048 /* Parameter */) { + break; + } else { + node = node.getContainer(); + } + } + return path; + }; + + PullSymbol.unqualifiedNameReferencesDifferentSymbolInScope = function (symbol, scopePath, endScopePathIndex) { + var declPath = scopePath[0].getDeclarations()[0].getParentPath(); + for (var i = 0, declIndex = declPath.length - 1; i <= endScopePathIndex; i++, declIndex--) { + if (scopePath[i].isContainer()) { + var scopeContainer = scopePath[i]; + if (symbol.isContainer()) { + var memberSymbol = scopeContainer.findContainedNonMemberContainer(symbol.name, 164 /* SomeContainer */); + if (memberSymbol && memberSymbol != symbol && memberSymbol.getDeclarations()[0].getParentDecl() == declPath[declIndex]) { + return true; + } + + var memberSymbol = scopeContainer.findNestedContainer(symbol.name, 164 /* SomeContainer */); + if (memberSymbol && memberSymbol != symbol) { + return true; + } + } else if (symbol.isType()) { + var memberSymbol = scopeContainer.findContainedNonMemberType(symbol.name, 58728795 /* SomeType */); + var symbolRootType = TypeScript.PullHelpers.getRootType(symbol); + if (memberSymbol && TypeScript.PullHelpers.getRootType(memberSymbol) != symbolRootType && memberSymbol.getDeclarations()[0].getParentDecl() == declPath[declIndex]) { + return true; + } + + var memberSymbol = scopeContainer.findNestedType(symbol.name, 58728795 /* SomeType */); + if (memberSymbol && TypeScript.PullHelpers.getRootType(memberSymbol) != symbolRootType) { + return true; + } + } + } + } + + return false; + }; + + PullSymbol.prototype.findQualifyingSymbolPathInScopeSymbol = function (scopeSymbol) { + var thisPath = this.pathToRoot(); + if (thisPath.length === 1) { + return thisPath; + } + + var scopeSymbolPath; + if (scopeSymbol) { + scopeSymbolPath = scopeSymbol.pathToRoot(); + } else { + return thisPath; + } + + var thisCommonAncestorIndex = TypeScript.ArrayUtilities.indexOf(thisPath, function (thisNode) { + return TypeScript.ArrayUtilities.contains(scopeSymbolPath, thisNode); + }); + if (thisCommonAncestorIndex > 0) { + var thisCommonAncestor = thisPath[thisCommonAncestorIndex]; + var scopeCommonAncestorIndex = TypeScript.ArrayUtilities.indexOf(scopeSymbolPath, function (scopeNode) { + return scopeNode === thisCommonAncestor; + }); + TypeScript.Debug.assert(thisPath.length - thisCommonAncestorIndex === scopeSymbolPath.length - scopeCommonAncestorIndex); + + for (; thisCommonAncestorIndex < thisPath.length; thisCommonAncestorIndex++, scopeCommonAncestorIndex++) { + if (!PullSymbol.unqualifiedNameReferencesDifferentSymbolInScope(thisPath[thisCommonAncestorIndex - 1], scopeSymbolPath, scopeCommonAncestorIndex)) { + break; + } + } + } + + if (thisCommonAncestorIndex >= 0 && thisCommonAncestorIndex < thisPath.length) { + return thisPath.slice(0, thisCommonAncestorIndex); + } else { + return thisPath; + } + }; + + PullSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + var str = this.getNameAndTypeName(scopeSymbol); + return str; + }; + + PullSymbol.prototype.getNamePartForFullName = function () { + return this.getDisplayName(null, true); + }; + + PullSymbol.prototype.fullName = function (scopeSymbol) { + var _this = this; + var path = this.pathToRoot(); + var fullName = ""; + + var aliasFullName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.fullName(scopeSymbol); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }); + if (aliasFullName) { + return aliasFullName; + } + + for (var i = 1; i < path.length; i++) { + var aliasFullName = path[i].getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol === _this ? null : symbol.fullName(scopeSymbol); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }); + if (aliasFullName) { + fullName = aliasFullName + "." + fullName; + break; + } + + var scopedName = path[i].getNamePartForFullName(); + if (path[i].kind === 32 /* DynamicModule */ && !TypeScript.isQuoted(scopedName)) { + break; + } + + if (scopedName === "") { + break; + } + + fullName = scopedName + "." + fullName; + } + + fullName = fullName + this.getNamePartForFullName(); + return fullName; + }; + + PullSymbol.prototype.getScopedName = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName) { + var path = this.findQualifyingSymbolPathInScopeSymbol(scopeSymbol); + var fullName = ""; + + var aliasFullName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getScopedName(scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }, skipInternalAliasName); + if (aliasFullName) { + return aliasFullName; + } + + for (var i = 1; i < path.length; i++) { + var kind = path[i].kind; + if (kind === 4 /* Container */ || kind === 32 /* DynamicModule */) { + var aliasFullName = path[i].getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getScopedName(scopeSymbol, skipTypeParametersInName, false, skipInternalAliasName); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }, skipInternalAliasName); + if (aliasFullName) { + fullName = aliasFullName + "." + fullName; + break; + } + + if (kind === 4 /* Container */) { + fullName = path[i].getDisplayName() + "." + fullName; + } else { + var displayName = path[i].getDisplayName(); + if (TypeScript.isQuoted(displayName)) { + fullName = displayName + "." + fullName; + } + break; + } + } else { + break; + } + } + fullName = fullName + this.getDisplayName(scopeSymbol, useConstraintInName, skipInternalAliasName); + return fullName; + }; + + PullSymbol.prototype.getScopedNameEx = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName) { + var name = this.getScopedName(scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName); + return TypeScript.MemberName.create(name); + }; + + PullSymbol.prototype.getTypeName = function (scopeSymbol, getPrettyTypeName) { + var memberName = this.getTypeNameEx(scopeSymbol, getPrettyTypeName); + return memberName.toString(); + }; + + PullSymbol.prototype.getTypeNameEx = function (scopeSymbol, getPrettyTypeName) { + var type = this.type; + if (type) { + var memberName = getPrettyTypeName ? this.getTypeNameForFunctionSignature("", scopeSymbol, getPrettyTypeName) : null; + if (!memberName) { + memberName = type.getScopedNameEx(scopeSymbol, false, true, getPrettyTypeName); + } + + return memberName; + } + return TypeScript.MemberName.create(""); + }; + + PullSymbol.prototype.getTypeNameForFunctionSignature = function (prefix, scopeSymbol, getPrettyTypeName) { + var type = this.type; + if (type && !type.isNamedTypeSymbol() && this.kind !== 4096 /* Property */ && this.kind !== 512 /* Variable */ && this.kind !== 2048 /* Parameter */) { + var signatures = type.getCallSignatures(); + if (signatures.length === 1 || (getPrettyTypeName && signatures.length)) { + var typeName = new TypeScript.MemberNameArray(); + var signatureName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, prefix, false, false, scopeSymbol, getPrettyTypeName); + typeName.addAll(signatureName); + return typeName; + } + } + + return null; + }; + + PullSymbol.prototype.getNameAndTypeName = function (scopeSymbol) { + var nameAndTypeName = this.getNameAndTypeNameEx(scopeSymbol); + return nameAndTypeName.toString(); + }; + + PullSymbol.prototype.getNameAndTypeNameEx = function (scopeSymbol) { + var type = this.type; + var nameStr = this.getDisplayName(scopeSymbol); + if (type) { + nameStr = nameStr + (this.isOptional ? "?" : ""); + var memberName = this.getTypeNameForFunctionSignature(nameStr, scopeSymbol); + if (!memberName) { + var typeNameEx = type.getScopedNameEx(scopeSymbol); + memberName = TypeScript.MemberName.create(typeNameEx, nameStr + ": ", ""); + } + return memberName; + } + return TypeScript.MemberName.create(nameStr); + }; + + PullSymbol.getTypeParameterString = function (typars, scopeSymbol, useContraintInName) { + return PullSymbol.getTypeParameterStringEx(typars, scopeSymbol, undefined, useContraintInName).toString(); + }; + + PullSymbol.getTypeParameterStringEx = function (typeParameters, scopeSymbol, getTypeParamMarkerInfo, useContraintInName) { + var builder = new TypeScript.MemberNameArray(); + builder.prefix = ""; + + if (typeParameters && typeParameters.length) { + builder.add(TypeScript.MemberName.create("<")); + + for (var i = 0; i < typeParameters.length; i++) { + if (i) { + builder.add(TypeScript.MemberName.create(", ")); + } + + if (getTypeParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + + builder.add(typeParameters[i].getScopedNameEx(scopeSymbol, false, useContraintInName)); + + if (getTypeParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + } + + builder.add(TypeScript.MemberName.create(">")); + } + + return builder; + }; + + PullSymbol.getIsExternallyVisible = function (symbol, fromIsExternallyVisibleSymbol, inIsExternallyVisibleSymbols) { + if (inIsExternallyVisibleSymbols) { + for (var i = 0; i < inIsExternallyVisibleSymbols.length; i++) { + if (inIsExternallyVisibleSymbols[i] === symbol) { + return true; + } + } + } else { + inIsExternallyVisibleSymbols = []; + } + + if (fromIsExternallyVisibleSymbol === symbol) { + return true; + } + + inIsExternallyVisibleSymbols.push(fromIsExternallyVisibleSymbol); + + var result = symbol.isExternallyVisible(inIsExternallyVisibleSymbols); + + TypeScript.Debug.assert(TypeScript.ArrayUtilities.last(inIsExternallyVisibleSymbols) === fromIsExternallyVisibleSymbol); + inIsExternallyVisibleSymbols.pop(); + + return result; + }; + + PullSymbol.prototype.isExternallyVisible = function (inIsExternallyVisibleSymbols) { + var kind = this.kind; + if (kind === 2 /* Primitive */) { + return true; + } + + if (this.rootSymbol) { + return PullSymbol.getIsExternallyVisible(this.rootSymbol, this, inIsExternallyVisibleSymbols); + } + + if (this.isType()) { + var associatedContainerSymbol = this.getAssociatedContainerType(); + if (associatedContainerSymbol) { + return PullSymbol.getIsExternallyVisible(associatedContainerSymbol, this, inIsExternallyVisibleSymbols); + } + } + + if (this.anyDeclHasFlag(2 /* Private */)) { + return false; + } + + var container = this.getContainer(); + if (container === null) { + var decls = this.getDeclarations(); + if (decls.length) { + var parentDecl = decls[0].getParentDecl(); + if (parentDecl) { + var parentSymbol = parentDecl.getSymbol(); + if (!parentSymbol || parentDecl.kind === 1 /* Script */) { + return true; + } + + return PullSymbol.getIsExternallyVisible(parentSymbol, this, inIsExternallyVisibleSymbols); + } + } + + return true; + } + + if (container.kind === 32 /* DynamicModule */ || (container.getAssociatedContainerType() && container.getAssociatedContainerType().kind === 32 /* DynamicModule */)) { + var containerSymbol = container.kind === 32 /* DynamicModule */ ? container : container.getAssociatedContainerType(); + if (PullContainerSymbol.usedAsSymbol(containerSymbol, this)) { + return true; + } + } + + if (!this.anyDeclHasFlag(1 /* Exported */) && kind !== 4096 /* Property */ && kind !== 65536 /* Method */) { + return false; + } + + return PullSymbol.getIsExternallyVisible(container, this, inIsExternallyVisibleSymbols); + }; + + PullSymbol.prototype.getDocCommentsOfDecl = function (decl) { + var ast = decl.ast(); + + if (ast) { + var enclosingModuleDeclaration = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(ast); + if (TypeScript.ASTHelpers.isLastNameOfModule(enclosingModuleDeclaration, ast)) { + return TypeScript.ASTHelpers.docComments(enclosingModuleDeclaration); + } + + if (ast.kind() !== 130 /* ModuleDeclaration */ || decl.kind !== 512 /* Variable */) { + return TypeScript.ASTHelpers.docComments(ast); + } + } + + return []; + }; + + PullSymbol.prototype.getDocCommentArray = function (symbol) { + var docComments = []; + if (!symbol) { + return docComments; + } + + var isParameter = symbol.kind === 2048 /* Parameter */; + var decls = symbol.getDeclarations(); + for (var i = 0; i < decls.length; i++) { + if (isParameter && decls[i].kind === 4096 /* Property */) { + continue; + } + docComments = docComments.concat(this.getDocCommentsOfDecl(decls[i])); + } + return docComments; + }; + + PullSymbol.getDefaultConstructorSymbolForDocComments = function (classSymbol) { + if (classSymbol.getHasDefaultConstructor()) { + var extendedTypes = classSymbol.getExtendedTypes(); + if (extendedTypes.length) { + return PullSymbol.getDefaultConstructorSymbolForDocComments(extendedTypes[0]); + } + } + + return classSymbol.type.getConstructSignatures()[0]; + }; + + PullSymbol.prototype.getDocCommentText = function (comments) { + var docCommentText = new Array(); + for (var c = 0; c < comments.length; c++) { + var commentText = this.getDocCommentTextValue(comments[c]); + if (commentText !== "") { + docCommentText.push(commentText); + } + } + return docCommentText.join("\n"); + }; + + PullSymbol.prototype.getDocCommentTextValue = function (comment) { + return this.cleanJSDocComment(comment.fullText()); + }; + + PullSymbol.prototype.docComments = function (useConstructorAsClass) { + var decls = this.getDeclarations(); + if (useConstructorAsClass && decls.length && decls[0].kind === 32768 /* ConstructorMethod */) { + var classDecl = decls[0].getParentDecl(); + return this.getDocCommentText(this.getDocCommentsOfDecl(classDecl)); + } + + if (this._docComments === null) { + var docComments = ""; + if (!useConstructorAsClass && this.kind === 2097152 /* ConstructSignature */ && decls.length && decls[0].kind === 8 /* Class */) { + var classSymbol = this.returnType; + var extendedTypes = classSymbol.getExtendedTypes(); + if (extendedTypes.length) { + docComments = extendedTypes[0].getConstructorMethod().docComments(); + } else { + docComments = ""; + } + } else if (this.kind === 2048 /* Parameter */) { + var parameterComments = []; + + var funcContainer = this.getEnclosingSignature(); + var funcDocComments = this.getDocCommentArray(funcContainer); + var paramComment = this.getParameterDocCommentText(this.getDisplayName(), funcDocComments); + if (paramComment != "") { + parameterComments.push(paramComment); + } + + var paramSelfComment = this.getDocCommentText(this.getDocCommentArray(this)); + if (paramSelfComment != "") { + parameterComments.push(paramSelfComment); + } + docComments = parameterComments.join("\n"); + } else { + var getSymbolComments = true; + if (this.kind === 16777216 /* FunctionType */) { + var functionSymbol = this.getFunctionSymbol(); + + if (functionSymbol) { + docComments = functionSymbol._docComments || ""; + getSymbolComments = false; + } else { + var declarationList = this.getDeclarations(); + if (declarationList.length > 0) { + docComments = declarationList[0].getSymbol()._docComments || ""; + getSymbolComments = false; + } + } + } + if (getSymbolComments) { + docComments = this.getDocCommentText(this.getDocCommentArray(this)); + if (docComments === "") { + if (this.kind === 1048576 /* CallSignature */) { + var callTypeSymbol = this.functionType; + if (callTypeSymbol && callTypeSymbol.getCallSignatures().length === 1) { + docComments = callTypeSymbol.docComments(); + } + } + } + } + } + + this._docComments = docComments; + } + + return this._docComments; + }; + + PullSymbol.prototype.getParameterDocCommentText = function (param, fncDocComments) { + if (fncDocComments.length === 0 || fncDocComments[0].kind() !== 6 /* MultiLineCommentTrivia */) { + return ""; + } + + for (var i = 0; i < fncDocComments.length; i++) { + var commentContents = fncDocComments[i].fullText(); + for (var j = commentContents.indexOf("@param", 0); 0 <= j; j = commentContents.indexOf("@param", j)) { + j += 6; + if (!this.isSpaceChar(commentContents, j)) { + continue; + } + + j = this.consumeLeadingSpace(commentContents, j); + if (j === -1) { + break; + } + + if (commentContents.charCodeAt(j) === 123 /* openBrace */) { + j++; + + var charCode = 0; + for (var curlies = 1; j < commentContents.length; j++) { + charCode = commentContents.charCodeAt(j); + + if (charCode === 123 /* openBrace */) { + curlies++; + continue; + } + + if (charCode === 125 /* closeBrace */) { + curlies--; + if (curlies === 0) { + break; + } else { + continue; + } + } + + if (charCode === 64 /* at */) { + break; + } + } + + if (j === commentContents.length) { + break; + } + + if (charCode === 64 /* at */) { + continue; + } + + j = this.consumeLeadingSpace(commentContents, j + 1); + if (j === -1) { + break; + } + } + + if (param !== commentContents.substr(j, param.length) || !this.isSpaceChar(commentContents, j + param.length)) { + continue; + } + + j = this.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 = this.consumeLeadingSpace(commentContents, paramLineIndex); + if (startSpaceRemovalIndex !== j && commentContents.charAt(startSpaceRemovalIndex) === "*") { + paramSpacesToRemove = j - startSpaceRemovalIndex - 1; + } + + return this.cleanJSDocComment(paramHelpString, paramSpacesToRemove); + } + } + + return ""; + }; + + PullSymbol.prototype.cleanJSDocComment = function (content, spacesToRemove) { + var docCommentLines = new Array(); + 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 = this.cleanDocCommentLine(line, true, spacesToRemove); + if (!cleanLinePos) { + continue; + } + + var docCommentText = ""; + var prevPos = cleanLinePos.start; + for (var i = line.indexOf("@", cleanLinePos.start); 0 <= i && i < cleanLinePos.end; i = line.indexOf("@", i + 1)) { + var wasInParamtag = inParamTag; + + if (line.indexOf("param", i + 1) === i + 1 && this.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.end); + } + + var newCleanPos = this.cleanDocCommentLine(docCommentText, false); + if (newCleanPos) { + if (spacesToRemove === undefined) { + spacesToRemove = cleanLinePos.jsDocSpacesRemoved; + } + docCommentLines.push(docCommentText); + } + } + + return docCommentLines.join("\n"); + }; + + PullSymbol.prototype.consumeLeadingSpace = function (line, startIndex, maxSpacesToRemove) { + var endIndex = line.length; + if (maxSpacesToRemove !== undefined) { + endIndex = TypeScript.MathPrototype.min(startIndex + maxSpacesToRemove, endIndex); + } + + for (; startIndex < endIndex; startIndex++) { + var charCode = line.charCodeAt(startIndex); + if (charCode !== 32 /* space */ && charCode !== 9 /* tab */) { + return startIndex; + } + } + + if (endIndex !== line.length) { + return endIndex; + } + + return -1; + }; + + PullSymbol.prototype.isSpaceChar = function (line, index) { + var length = line.length; + if (index < length) { + var charCode = line.charCodeAt(index); + + return charCode === 32 /* space */ || charCode === 9 /* tab */; + } + + return index === length; + }; + + PullSymbol.prototype.cleanDocCommentLine = function (line, jsDocStyleComment, jsDocLineSpaceToRemove) { + var nonSpaceIndex = this.consumeLeadingSpace(line, 0); + if (nonSpaceIndex !== -1) { + var jsDocSpacesRemoved = nonSpaceIndex; + if (jsDocStyleComment && line.charAt(nonSpaceIndex) === '*') { + var startIndex = nonSpaceIndex + 1; + nonSpaceIndex = this.consumeLeadingSpace(line, startIndex, jsDocLineSpaceToRemove); + + if (nonSpaceIndex !== -1) { + jsDocSpacesRemoved = nonSpaceIndex - startIndex; + } else { + return null; + } + } + + return { + start: nonSpaceIndex, + end: line.charAt(line.length - 1) === "\r" ? line.length - 1 : line.length, + jsDocSpacesRemoved: jsDocSpacesRemoved + }; + } + + return null; + }; + return PullSymbol; + })(); + TypeScript.PullSymbol = PullSymbol; + + + + var PullSignatureSymbol = (function (_super) { + __extends(PullSignatureSymbol, _super); + function PullSignatureSymbol(kind, _isDefinition) { + if (typeof _isDefinition === "undefined") { _isDefinition = false; } + _super.call(this, "", kind); + this._isDefinition = _isDefinition; + this._memberTypeParameterNameCache = null; + this._stringConstantOverload = undefined; + this.parameters = TypeScript.sentinelEmptyArray; + this._typeParameters = null; + this.returnType = null; + this.functionType = null; + this.hasOptionalParam = false; + this.nonOptionalParamCount = 0; + this.hasVarArgs = false; + this._allowedToReferenceTypeParameters = null; + this._instantiationCache = null; + this.hasBeenChecked = false; + this.inWrapCheck = false; + this.inWrapInfiniteExpandingReferenceCheck = false; + } + PullSignatureSymbol.prototype.isDefinition = function () { + return this._isDefinition; + }; + + PullSignatureSymbol.prototype.isGeneric = function () { + var typeParameters = this.getTypeParameters(); + return !!typeParameters && typeParameters.length !== 0; + }; + + PullSignatureSymbol.prototype.addParameter = function (parameter, isOptional) { + if (typeof isOptional === "undefined") { isOptional = false; } + if (this.parameters === TypeScript.sentinelEmptyArray) { + this.parameters = []; + } + + this.parameters[this.parameters.length] = parameter; + this.hasOptionalParam = isOptional; + + if (!parameter.getEnclosingSignature()) { + parameter.setEnclosingSignature(this); + } + + if (!isOptional) { + this.nonOptionalParamCount++; + } + }; + + PullSignatureSymbol.prototype.addTypeParameter = function (typeParameter) { + if (!this._typeParameters) { + this._typeParameters = []; + } + + if (!this._memberTypeParameterNameCache) { + this._memberTypeParameterNameCache = TypeScript.createIntrinsicsObject(); + } + + this._typeParameters[this._typeParameters.length] = typeParameter; + + this._memberTypeParameterNameCache[typeParameter.getName()] = typeParameter; + }; + + PullSignatureSymbol.prototype.addTypeParametersFromReturnType = function () { + var typeParameters = this.returnType.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + this.addTypeParameter(typeParameters[i]); + } + }; + + PullSignatureSymbol.prototype.getTypeParameters = function () { + if (!this._typeParameters) { + this._typeParameters = []; + } + + return this._typeParameters; + }; + + PullSignatureSymbol.prototype.findTypeParameter = function (name) { + var memberSymbol; + + if (!this._memberTypeParameterNameCache) { + this._memberTypeParameterNameCache = TypeScript.createIntrinsicsObject(); + + for (var i = 0; i < this.getTypeParameters().length; i++) { + this._memberTypeParameterNameCache[this._typeParameters[i].getName()] = this._typeParameters[i]; + } + } + + memberSymbol = this._memberTypeParameterNameCache[name]; + + return memberSymbol; + }; + + PullSignatureSymbol.prototype.getTypeParameterArgumentMap = function () { + return null; + }; + + PullSignatureSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._allowedToReferenceTypeParameters) { + this._allowedToReferenceTypeParameters = TypeScript.PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl(this.getDeclarations()[0]); + } + + return this._allowedToReferenceTypeParameters; + }; + + PullSignatureSymbol.prototype.addSpecialization = function (specializedVersionOfThisSignature, typeArgumentMap) { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._instantiationCache) { + this._instantiationCache = TypeScript.createIntrinsicsObject(); + } + + this._instantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)] = specializedVersionOfThisSignature; + }; + + PullSignatureSymbol.prototype.getSpecialization = function (typeArgumentMap) { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._instantiationCache) { + return null; + } + + var result = this._instantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)]; + return result || null; + }; + + PullSignatureSymbol.prototype.isStringConstantOverloadSignature = function () { + if (this._stringConstantOverload === undefined) { + var params = this.parameters; + this._stringConstantOverload = false; + for (var i = 0; i < params.length; i++) { + var paramType = params[i].type; + if (paramType && paramType.isPrimitive() && paramType.isStringConstant()) { + this._stringConstantOverload = true; + } + } + } + + return this._stringConstantOverload; + }; + + PullSignatureSymbol.prototype.getParameterTypeAtIndex = function (iParam) { + if (iParam < this.parameters.length - 1 || (iParam < this.parameters.length && !this.hasVarArgs)) { + return this.parameters[iParam].type; + } else if (this.hasVarArgs) { + var paramType = this.parameters[this.parameters.length - 1].type; + if (paramType.isArrayNamedTypeReference()) { + paramType = paramType.getElementType(); + } + return paramType; + } + + return null; + }; + + PullSignatureSymbol.getSignatureTypeMemberName = function (candidateSignature, signatures, scopeSymbol) { + var allMemberNames = new TypeScript.MemberNameArray(); + var signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, "", false, false, scopeSymbol, true, candidateSignature); + allMemberNames.addAll(signatureMemberName); + return allMemberNames; + }; + + PullSignatureSymbol.getSignaturesTypeNameEx = function (signatures, prefix, shortform, brackets, scopeSymbol, getPrettyTypeName, candidateSignature) { + var result = []; + if (!signatures) { + return result; + } + + var len = signatures.length; + if (!getPrettyTypeName && len > 1) { + shortform = false; + } + + var foundDefinition = false; + if (candidateSignature && candidateSignature.isDefinition() && len > 1) { + candidateSignature = null; + } + + for (var i = 0; i < len; i++) { + if (len > 1 && signatures[i].isDefinition()) { + foundDefinition = true; + continue; + } + + var signature = signatures[i]; + if (getPrettyTypeName && candidateSignature) { + signature = candidateSignature; + } + + result.push(signature.getSignatureTypeNameEx(prefix, shortform, brackets, scopeSymbol)); + if (getPrettyTypeName) { + break; + } + } + + if (getPrettyTypeName && result.length && len > 1) { + var lastMemberName = result[result.length - 1]; + for (var i = i + 1; i < len; i++) { + if (signatures[i].isDefinition()) { + foundDefinition = true; + break; + } + } + var overloadString = TypeScript.getLocalizedText(TypeScript.DiagnosticCode._0_overload_s, [foundDefinition ? len - 2 : len - 1]); + lastMemberName.add(TypeScript.MemberName.create(overloadString)); + } + + return result; + }; + + PullSignatureSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + var s = this.getSignatureTypeNameEx(this.getScopedNameEx().toString(), false, false, scopeSymbol, undefined, useConstraintInName).toString(); + return s; + }; + + PullSignatureSymbol.prototype.getSignatureTypeNameEx = function (prefix, shortform, brackets, scopeSymbol, getParamMarkerInfo, getTypeParamMarkerInfo) { + var typeParamterBuilder = new TypeScript.MemberNameArray(); + + typeParamterBuilder.add(PullSymbol.getTypeParameterStringEx(this.getTypeParameters(), scopeSymbol, getTypeParamMarkerInfo, true)); + + if (brackets) { + typeParamterBuilder.add(TypeScript.MemberName.create("[")); + } else { + typeParamterBuilder.add(TypeScript.MemberName.create("(")); + } + + var builder = new TypeScript.MemberNameArray(); + builder.prefix = prefix; + + if (getTypeParamMarkerInfo) { + builder.prefix = prefix; + builder.addAll(typeParamterBuilder.entries); + } else { + builder.prefix = prefix + typeParamterBuilder.toString(); + } + + var params = this.parameters; + var paramLen = params.length; + for (var i = 0; i < paramLen; i++) { + var paramType = params[i].type; + var typeString = paramType ? ": " : ""; + var paramIsVarArg = params[i].isVarArg; + var varArgPrefix = paramIsVarArg ? "..." : ""; + var optionalString = (!paramIsVarArg && params[i].isOptional) ? "?" : ""; + if (getParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + builder.add(TypeScript.MemberName.create(varArgPrefix + params[i].getScopedNameEx(scopeSymbol).toString() + optionalString + typeString)); + if (paramType) { + builder.add(paramType.getScopedNameEx(scopeSymbol)); + } + if (getParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + if (i < paramLen - 1) { + builder.add(TypeScript.MemberName.create(", ")); + } + } + + 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) { + builder.add(this.returnType.getScopedNameEx(scopeSymbol)); + } else { + builder.add(TypeScript.MemberName.create("any")); + } + + return builder; + }; + + PullSignatureSymbol.prototype.forAllParameterTypes = function (length, predicate) { + if (this.parameters.length < length && !this.hasVarArgs) { + length = this.parameters.length; + } + + for (var i = 0; i < length; i++) { + var paramType = this.getParameterTypeAtIndex(i); + if (!predicate(paramType, i)) { + return false; + } + } + + return true; + }; + + PullSignatureSymbol.prototype.forAllCorrespondingParameterTypesInThisAndOtherSignature = function (otherSignature, predicate) { + var length; + if (this.hasVarArgs) { + length = otherSignature.hasVarArgs ? Math.max(this.parameters.length, otherSignature.parameters.length) : otherSignature.parameters.length; + } else { + length = otherSignature.hasVarArgs ? this.parameters.length : Math.min(this.parameters.length, otherSignature.parameters.length); + } + + for (var i = 0; i < length; i++) { + var thisParamType = this.getParameterTypeAtIndex(i); + var otherParamType = otherSignature.getParameterTypeAtIndex(i); + if (!predicate(thisParamType, otherParamType, i)) { + return false; + } + } + + return true; + }; + + PullSignatureSymbol.prototype.wrapsSomeTypeParameter = function (typeParameterArgumentMap) { + return this.getWrappingTypeParameterID(typeParameterArgumentMap) !== 0; + }; + + PullSignatureSymbol.prototype.getWrappingTypeParameterID = function (typeParameterArgumentMap) { + var signature = this; + if (signature.inWrapCheck) { + return 0; + } + + this._wrapsTypeParameterCache = this._wrapsTypeParameterCache || new TypeScript.WrapsTypeParameterCache(); + + var wrappingTypeParameterID = this._wrapsTypeParameterCache.getWrapsTypeParameter(typeParameterArgumentMap); + if (wrappingTypeParameterID === undefined) { + wrappingTypeParameterID = this.getWrappingTypeParameterIDWorker(typeParameterArgumentMap); + this._wrapsTypeParameterCache.setWrapsTypeParameter(typeParameterArgumentMap, wrappingTypeParameterID); + } + + return wrappingTypeParameterID; + }; + + PullSignatureSymbol.prototype.getWrappingTypeParameterIDWorker = function (typeParameterArgumentMap) { + var signature = this; + signature.inWrapCheck = true; + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(signature); + var wrappingTypeParameterID = signature.returnType ? signature.returnType.getWrappingTypeParameterID(typeParameterArgumentMap) : 0; + + var parameters = signature.parameters; + for (var i = 0; !wrappingTypeParameterID && i < parameters.length; i++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(parameters[i]); + wrappingTypeParameterID = parameters[i].type.getWrappingTypeParameterID(typeParameterArgumentMap); + } + + signature.inWrapCheck = false; + + return wrappingTypeParameterID; + }; + + PullSignatureSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference = function (enclosingType, knownWrapMap) { + var wrapsIntoInfinitelyExpandingTypeReference = knownWrapMap.valueAt(this.pullSymbolID, enclosingType.pullSymbolID); + if (wrapsIntoInfinitelyExpandingTypeReference != undefined) { + return wrapsIntoInfinitelyExpandingTypeReference; + } + + if (this.inWrapInfiniteExpandingReferenceCheck) { + return false; + } + + this.inWrapInfiniteExpandingReferenceCheck = true; + wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker(enclosingType, knownWrapMap); + knownWrapMap.setValueAt(this.pullSymbolID, enclosingType.pullSymbolID, wrapsIntoInfinitelyExpandingTypeReference); + this.inWrapInfiniteExpandingReferenceCheck = false; + + return wrapsIntoInfinitelyExpandingTypeReference; + }; + + PullSignatureSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker = function (enclosingType, knownWrapMap) { + if (this.returnType && this.returnType._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; + } + + var parameters = this.parameters; + + for (var i = 0; i < parameters.length; i++) { + if (parameters[i].type && parameters[i].type._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; + } + } + + return false; + }; + return PullSignatureSymbol; + })(PullSymbol); + TypeScript.PullSignatureSymbol = PullSignatureSymbol; + + var PullTypeSymbol = (function (_super) { + __extends(PullTypeSymbol, _super); + function PullTypeSymbol(name, kind) { + _super.call(this, name, kind); + this._members = TypeScript.sentinelEmptyArray; + this._enclosedMemberTypes = null; + this._enclosedMemberContainers = null; + this._typeParameters = null; + this._allowedToReferenceTypeParameters = null; + this._specializedVersionsOfThisType = null; + this._arrayVersionOfThisType = null; + this._implementedTypes = null; + this._extendedTypes = null; + this._typesThatExplicitlyImplementThisType = null; + this._typesThatExtendThisType = null; + this._callSignatures = null; + this._allCallSignatures = null; + this._constructSignatures = null; + this._allConstructSignatures = null; + this._indexSignatures = null; + this._allIndexSignatures = null; + this._allIndexSignaturesOfAugmentedType = null; + this._memberNameCache = null; + this._enclosedTypeNameCache = null; + this._enclosedContainerCache = null; + this._typeParameterNameCache = null; + this._containedNonMemberNameCache = null; + this._containedNonMemberTypeNameCache = null; + this._containedNonMemberContainerCache = null; + this._simpleInstantiationCache = null; + this._complexInstantiationCache = null; + this._hasGenericSignature = false; + this._hasGenericMember = false; + this._hasBaseTypeConflict = false; + this._knownBaseTypeCount = 0; + this._associatedContainerTypeSymbol = null; + this._constructorMethod = null; + this._hasDefaultConstructor = false; + this._functionSymbol = null; + this._inMemberTypeNameEx = false; + this.inSymbolPrivacyCheck = false; + this.inWrapCheck = false; + this.inWrapInfiniteExpandingReferenceCheck = false; + this.typeReference = null; + this._widenedType = null; + this._isArrayNamedTypeReference = undefined; + this.type = this; + } + PullTypeSymbol.prototype.isArrayNamedTypeReference = function () { + if (this._isArrayNamedTypeReference === undefined) { + this._isArrayNamedTypeReference = this.computeIsArrayNamedTypeReference(); + } + + return this._isArrayNamedTypeReference; + }; + + PullTypeSymbol.prototype.computeIsArrayNamedTypeReference = function () { + var typeArgs = this.getTypeArguments(); + if (typeArgs && this.getTypeArguments().length === 1 && this.name === "Array") { + var declaration = this.getDeclarations()[0]; + + if (declaration && declaration.getParentDecl() && declaration.getParentDecl().getParentDecl() === null) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.isType = function () { + return true; + }; + PullTypeSymbol.prototype.isClass = function () { + return this.kind === 8 /* Class */ || (this._constructorMethod !== null); + }; + PullTypeSymbol.prototype.isFunction = function () { + return (this.kind & (33554432 /* ConstructorType */ | 16777216 /* FunctionType */)) !== 0; + }; + PullTypeSymbol.prototype.isConstructor = function () { + return this.kind === 33554432 /* ConstructorType */ || (this._associatedContainerTypeSymbol && this._associatedContainerTypeSymbol.isClass()); + }; + PullTypeSymbol.prototype.isTypeParameter = function () { + return false; + }; + PullTypeSymbol.prototype.isTypeVariable = function () { + return false; + }; + PullTypeSymbol.prototype.isError = function () { + return false; + }; + PullTypeSymbol.prototype.isEnum = function () { + return this.kind === 64 /* Enum */; + }; + + PullTypeSymbol.prototype.getTypeParameterArgumentMap = function () { + return null; + }; + + PullTypeSymbol.prototype.isObject = function () { + return TypeScript.hasFlag(this.kind, 8 /* Class */ | 33554432 /* ConstructorType */ | 64 /* Enum */ | 16777216 /* FunctionType */ | 16 /* Interface */ | 8388608 /* ObjectType */ | 256 /* ObjectLiteral */); + }; + + PullTypeSymbol.prototype.isFunctionType = function () { + return this.getCallSignatures().length > 0 || this.getConstructSignatures().length > 0; + }; + + PullTypeSymbol.prototype.getKnownBaseTypeCount = function () { + return this._knownBaseTypeCount; + }; + PullTypeSymbol.prototype.resetKnownBaseTypeCount = function () { + this._knownBaseTypeCount = 0; + }; + PullTypeSymbol.prototype.incrementKnownBaseCount = function () { + this._knownBaseTypeCount++; + }; + + PullTypeSymbol.prototype.setHasBaseTypeConflict = function () { + this._hasBaseTypeConflict = true; + }; + PullTypeSymbol.prototype.hasBaseTypeConflict = function () { + return this._hasBaseTypeConflict; + }; + + PullTypeSymbol.prototype.hasMembers = function () { + if (this._members !== TypeScript.sentinelEmptyArray) { + return true; + } + + var parents = this.getExtendedTypes(); + + for (var i = 0; i < parents.length; i++) { + if (parents[i].hasMembers()) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.setHasGenericSignature = function () { + this._hasGenericSignature = true; + }; + PullTypeSymbol.prototype.getHasGenericSignature = function () { + return this._hasGenericSignature; + }; + + PullTypeSymbol.prototype.setHasGenericMember = function () { + this._hasGenericMember = true; + }; + PullTypeSymbol.prototype.getHasGenericMember = function () { + return this._hasGenericMember; + }; + + PullTypeSymbol.prototype.setAssociatedContainerType = function (type) { + this._associatedContainerTypeSymbol = type; + }; + + PullTypeSymbol.prototype.getAssociatedContainerType = function () { + return this._associatedContainerTypeSymbol; + }; + + PullTypeSymbol.prototype.getArrayType = function () { + return this._arrayVersionOfThisType; + }; + + PullTypeSymbol.prototype.getElementType = function () { + return null; + }; + + PullTypeSymbol.prototype.setArrayType = function (arrayType) { + this._arrayVersionOfThisType = arrayType; + }; + + PullTypeSymbol.prototype.getFunctionSymbol = function () { + return this._functionSymbol; + }; + + PullTypeSymbol.prototype.setFunctionSymbol = function (symbol) { + if (symbol) { + this._functionSymbol = symbol; + } + }; + + PullTypeSymbol.prototype.findContainedNonMember = function (name) { + if (!this._containedNonMemberNameCache) { + return null; + } + + return this._containedNonMemberNameCache[name]; + }; + + PullTypeSymbol.prototype.findContainedNonMemberType = function (typeName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + if (!this._containedNonMemberTypeNameCache) { + return null; + } + + var nonMemberSymbol = this._containedNonMemberTypeNameCache[typeName]; + + if (nonMemberSymbol && kind !== 0 /* None */) { + nonMemberSymbol = TypeScript.hasFlag(nonMemberSymbol.kind, kind) ? nonMemberSymbol : null; + } + + return nonMemberSymbol; + }; + + PullTypeSymbol.prototype.findContainedNonMemberContainer = function (containerName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + if (!this._containedNonMemberContainerCache) { + return null; + } + + var nonMemberSymbol = this._containedNonMemberContainerCache[containerName]; + + if (nonMemberSymbol && kind !== 0 /* None */) { + nonMemberSymbol = TypeScript.hasFlag(nonMemberSymbol.kind, kind) ? nonMemberSymbol : null; + } + + return nonMemberSymbol; + }; + + PullTypeSymbol.prototype.addMember = function (memberSymbol) { + if (!memberSymbol) { + return; + } + + memberSymbol.setContainer(this); + + if (!this._memberNameCache) { + this._memberNameCache = TypeScript.createIntrinsicsObject(); + } + + if (this._members === TypeScript.sentinelEmptyArray) { + this._members = []; + } + + this._members.push(memberSymbol); + this._memberNameCache[memberSymbol.name] = memberSymbol; + }; + + PullTypeSymbol.prototype.addEnclosedMemberType = function (enclosedType) { + if (!enclosedType) { + return; + } + + enclosedType.setContainer(this); + + if (!this._enclosedTypeNameCache) { + this._enclosedTypeNameCache = TypeScript.createIntrinsicsObject(); + } + + if (!this._enclosedMemberTypes) { + this._enclosedMemberTypes = []; + } + + this._enclosedMemberTypes[this._enclosedMemberTypes.length] = enclosedType; + this._enclosedTypeNameCache[enclosedType.name] = enclosedType; + }; + + PullTypeSymbol.prototype.addEnclosedMemberContainer = function (enclosedContainer) { + if (!enclosedContainer) { + return; + } + + enclosedContainer.setContainer(this); + + if (!this._enclosedContainerCache) { + this._enclosedContainerCache = TypeScript.createIntrinsicsObject(); + } + + if (!this._enclosedMemberContainers) { + this._enclosedMemberContainers = []; + } + + this._enclosedMemberContainers[this._enclosedMemberContainers.length] = enclosedContainer; + this._enclosedContainerCache[enclosedContainer.name] = enclosedContainer; + }; + + PullTypeSymbol.prototype.addEnclosedNonMember = function (enclosedNonMember) { + if (!enclosedNonMember) { + return; + } + + enclosedNonMember.setContainer(this); + + if (!this._containedNonMemberNameCache) { + this._containedNonMemberNameCache = TypeScript.createIntrinsicsObject(); + } + + this._containedNonMemberNameCache[enclosedNonMember.name] = enclosedNonMember; + }; + + PullTypeSymbol.prototype.addEnclosedNonMemberType = function (enclosedNonMemberType) { + if (!enclosedNonMemberType) { + return; + } + + enclosedNonMemberType.setContainer(this); + + if (!this._containedNonMemberTypeNameCache) { + this._containedNonMemberTypeNameCache = TypeScript.createIntrinsicsObject(); + } + + this._containedNonMemberTypeNameCache[enclosedNonMemberType.name] = enclosedNonMemberType; + }; + + PullTypeSymbol.prototype.addEnclosedNonMemberContainer = function (enclosedNonMemberContainer) { + if (!enclosedNonMemberContainer) { + return; + } + + enclosedNonMemberContainer.setContainer(this); + + if (!this._containedNonMemberContainerCache) { + this._containedNonMemberContainerCache = TypeScript.createIntrinsicsObject(); + } + + this._containedNonMemberContainerCache[enclosedNonMemberContainer.name] = enclosedNonMemberContainer; + }; + + PullTypeSymbol.prototype.addTypeParameter = function (typeParameter) { + if (!typeParameter) { + return; + } + + if (!typeParameter.getContainer()) { + typeParameter.setContainer(this); + } + + if (!this._typeParameterNameCache) { + this._typeParameterNameCache = TypeScript.createIntrinsicsObject(); + } + + if (!this._typeParameters) { + this._typeParameters = []; + } + + this._typeParameters[this._typeParameters.length] = typeParameter; + this._typeParameterNameCache[typeParameter.getName()] = typeParameter; + }; + + PullTypeSymbol.prototype.getMembers = function () { + return this._members; + }; + + PullTypeSymbol.prototype.setHasDefaultConstructor = function (hasOne) { + if (typeof hasOne === "undefined") { hasOne = true; } + this._hasDefaultConstructor = hasOne; + }; + + PullTypeSymbol.prototype.getHasDefaultConstructor = function () { + return this._hasDefaultConstructor; + }; + + PullTypeSymbol.prototype.getConstructorMethod = function () { + return this._constructorMethod; + }; + + PullTypeSymbol.prototype.setConstructorMethod = function (constructorMethod) { + this._constructorMethod = constructorMethod; + }; + + PullTypeSymbol.prototype.getTypeParameters = function () { + if (!this._typeParameters) { + return TypeScript.sentinelEmptyArray; + } + + return this._typeParameters; + }; + + PullTypeSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + if (!!(this.kind && 8216 /* SomeInstantiatableType */) && this.isNamedTypeSymbol() && !this.isTypeParameter()) { + return this.getTypeParameters(); + } + + if (!this._allowedToReferenceTypeParameters) { + this._allowedToReferenceTypeParameters = TypeScript.PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl(this.getDeclarations()[0]); + } + + return this._allowedToReferenceTypeParameters; + }; + + PullTypeSymbol.prototype.isGeneric = function () { + return (this._typeParameters && this._typeParameters.length > 0) || this._hasGenericSignature || this._hasGenericMember || this.isArrayNamedTypeReference(); + }; + + PullTypeSymbol.prototype.canUseSimpleInstantiationCache = function (typeArgumentMap) { + if (this.isTypeParameter()) { + return true; + } + + var typeParameters = this.getTypeParameters(); + return typeArgumentMap && this.isNamedTypeSymbol() && typeParameters.length === 1 && typeArgumentMap[typeParameters[0].pullSymbolID].kind !== 8388608 /* ObjectType */; + }; + + PullTypeSymbol.prototype.getSimpleInstantiationCacheId = function (typeArgumentMap) { + if (this.isTypeParameter()) { + return typeArgumentMap[0].pullSymbolID; + } + + return typeArgumentMap[this.getTypeParameters()[0].pullSymbolID].pullSymbolID; + }; + + PullTypeSymbol.prototype.addSpecialization = function (specializedVersionOfThisType, typeArgumentMap) { + if (this.canUseSimpleInstantiationCache(typeArgumentMap)) { + if (!this._simpleInstantiationCache) { + this._simpleInstantiationCache = []; + } + + this._simpleInstantiationCache[this.getSimpleInstantiationCacheId(typeArgumentMap)] = specializedVersionOfThisType; + } else { + if (!this._complexInstantiationCache) { + this._complexInstantiationCache = TypeScript.createIntrinsicsObject(); + } + + this._complexInstantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)] = specializedVersionOfThisType; + } + + if (!this._specializedVersionsOfThisType) { + this._specializedVersionsOfThisType = []; + } + + this._specializedVersionsOfThisType.push(specializedVersionOfThisType); + }; + + PullTypeSymbol.prototype.getSpecialization = function (typeArgumentMap) { + if (this.canUseSimpleInstantiationCache(typeArgumentMap)) { + if (!this._simpleInstantiationCache) { + return null; + } + + var result = this._simpleInstantiationCache[this.getSimpleInstantiationCacheId(typeArgumentMap)]; + return result || null; + } else { + if (!this._complexInstantiationCache) { + return null; + } + + if (this.getAllowedToReferenceTypeParameters().length == 0) { + return this; + } + + var result = this._complexInstantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)]; + return result || null; + } + }; + + PullTypeSymbol.prototype.getKnownSpecializations = function () { + if (!this._specializedVersionsOfThisType) { + return TypeScript.sentinelEmptyArray; + } + + return this._specializedVersionsOfThisType; + }; + + PullTypeSymbol.prototype.getTypeArguments = function () { + return null; + }; + + PullTypeSymbol.prototype.getTypeArgumentsOrTypeParameters = function () { + return this.getTypeParameters(); + }; + + PullTypeSymbol.prototype.addCallOrConstructSignaturePrerequisiteBase = function (signature) { + if (signature.isGeneric()) { + this._hasGenericSignature = true; + } + + signature.functionType = this; + }; + + PullTypeSymbol.prototype.addCallSignaturePrerequisite = function (callSignature) { + if (!this._callSignatures) { + this._callSignatures = []; + } + + this.addCallOrConstructSignaturePrerequisiteBase(callSignature); + }; + + PullTypeSymbol.prototype.appendCallSignature = function (callSignature) { + this.addCallSignaturePrerequisite(callSignature); + this._callSignatures.push(callSignature); + }; + + PullTypeSymbol.prototype.insertCallSignatureAtIndex = function (callSignature, index) { + this.addCallSignaturePrerequisite(callSignature); + TypeScript.Debug.assert(index <= this._callSignatures.length); + if (index === this._callSignatures.length) { + this._callSignatures.push(callSignature); + } else { + this._callSignatures.splice(index, 0, callSignature); + } + }; + + PullTypeSymbol.prototype.addConstructSignaturePrerequisite = function (constructSignature) { + if (!this._constructSignatures) { + this._constructSignatures = []; + } + + this.addCallOrConstructSignaturePrerequisiteBase(constructSignature); + }; + + PullTypeSymbol.prototype.appendConstructSignature = function (constructSignature) { + this.addConstructSignaturePrerequisite(constructSignature); + this._constructSignatures.push(constructSignature); + }; + + PullTypeSymbol.prototype.insertConstructSignatureAtIndex = function (constructSignature, index) { + this.addConstructSignaturePrerequisite(constructSignature); + TypeScript.Debug.assert(index <= this._constructSignatures.length); + if (index === this._constructSignatures.length) { + this._constructSignatures.push(constructSignature); + } else { + this._constructSignatures.splice(index, 0, constructSignature); + } + }; + + PullTypeSymbol.prototype.addIndexSignature = function (indexSignature) { + if (!this._indexSignatures) { + this._indexSignatures = []; + } + + this._indexSignatures[this._indexSignatures.length] = indexSignature; + + if (indexSignature.isGeneric()) { + this._hasGenericSignature = true; + } + + indexSignature.functionType = this; + }; + + PullTypeSymbol.prototype.hasOwnCallSignatures = function () { + return this._callSignatures !== null; + }; + + PullTypeSymbol.prototype.getOwnCallSignatures = function () { + return this._callSignatures || TypeScript.sentinelEmptyArray; + }; + + PullTypeSymbol.prototype.getCallSignatures = function () { + if (this._allCallSignatures) { + return this._allCallSignatures; + } + + var signatures = []; + + if (this._callSignatures) { + signatures = signatures.concat(this._callSignatures); + } + + if (this._extendedTypes && this.kind === 16 /* Interface */) { + for (var i = 0; i < this._extendedTypes.length; i++) { + if (this._extendedTypes[i].hasBase(this)) { + continue; + } + + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._callSignatures, this._extendedTypes[i].getCallSignatures(), signatures); + } + } + + this._allCallSignatures = signatures; + + return signatures; + }; + + PullTypeSymbol.prototype.hasOwnConstructSignatures = function () { + return this._constructSignatures !== null; + }; + + PullTypeSymbol.prototype.getOwnDeclaredConstructSignatures = function () { + return this._constructSignatures || TypeScript.sentinelEmptyArray; + }; + + PullTypeSymbol.prototype.getConstructSignatures = function () { + if (this._allConstructSignatures) { + return this._allConstructSignatures; + } + + var signatures = []; + + if (this._constructSignatures) { + signatures = signatures.concat(this._constructSignatures); + } else if (this.isConstructor()) { + if (this._extendedTypes && this._extendedTypes.length > 0) { + signatures = this.getBaseClassConstructSignatures(this._extendedTypes[0]); + } else { + signatures = [this.getDefaultClassConstructSignature()]; + } + } + + if (this._extendedTypes && this.kind === 16 /* Interface */) { + for (var i = 0; i < this._extendedTypes.length; i++) { + if (this._extendedTypes[i].hasBase(this)) { + continue; + } + + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._constructSignatures, this._extendedTypes[i].getConstructSignatures(), signatures); + } + } + + this._allConstructSignatures = signatures; + + return signatures; + }; + + PullTypeSymbol.prototype.hasOwnIndexSignatures = function () { + return this._indexSignatures !== null; + }; + + PullTypeSymbol.prototype.getOwnIndexSignatures = function () { + return this._indexSignatures || TypeScript.sentinelEmptyArray; + }; + + PullTypeSymbol.prototype.getIndexSignatures = function () { + if (this._allIndexSignatures) { + return this._allIndexSignatures; + } + + var signatures = []; + + if (this._indexSignatures) { + signatures = signatures.concat(this._indexSignatures); + } + + if (this._extendedTypes) { + for (var i = 0; i < this._extendedTypes.length; i++) { + if (this._extendedTypes[i].hasBase(this)) { + continue; + } + + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._indexSignatures, this._extendedTypes[i].getIndexSignatures(), signatures); + } + } + + this._allIndexSignatures = signatures; + + return signatures; + }; + + PullTypeSymbol.prototype.getIndexSignaturesOfAugmentedType = function (resolver, globalFunctionInterface, globalObjectInterface) { + if (!this._allIndexSignaturesOfAugmentedType) { + var initialIndexSignatures = this.getIndexSignatures(); + var shouldAddFunctionSignatures = false; + var shouldAddObjectSignatures = false; + + if (globalFunctionInterface && this.isFunctionType() && this !== globalFunctionInterface) { + var functionIndexSignatures = globalFunctionInterface.getIndexSignatures(); + if (functionIndexSignatures.length) { + shouldAddFunctionSignatures = true; + } + } + + if (globalObjectInterface && this !== globalObjectInterface) { + var objectIndexSignatures = globalObjectInterface.getIndexSignatures(); + if (objectIndexSignatures.length) { + shouldAddObjectSignatures = true; + } + } + + if (shouldAddFunctionSignatures || shouldAddObjectSignatures) { + this._allIndexSignaturesOfAugmentedType = initialIndexSignatures.slice(0); + if (shouldAddFunctionSignatures) { + resolver._addUnhiddenSignaturesFromBaseType(initialIndexSignatures, functionIndexSignatures, this._allIndexSignaturesOfAugmentedType); + } + if (shouldAddObjectSignatures) { + if (shouldAddFunctionSignatures) { + initialIndexSignatures = initialIndexSignatures.concat(functionIndexSignatures); + } + resolver._addUnhiddenSignaturesFromBaseType(initialIndexSignatures, objectIndexSignatures, this._allIndexSignaturesOfAugmentedType); + } + } else { + this._allIndexSignaturesOfAugmentedType = initialIndexSignatures; + } + } + + return this._allIndexSignaturesOfAugmentedType; + }; + + PullTypeSymbol.prototype.getBaseClassConstructSignatures = function (baseType) { + TypeScript.Debug.assert(this.isConstructor() && baseType.isConstructor()); + var instanceTypeSymbol = this.getAssociatedContainerType(); + TypeScript.Debug.assert(instanceTypeSymbol.getDeclarations().length === 1); + if (baseType.hasBase(this)) { + return null; + } + + var baseConstructSignatures = baseType.getConstructSignatures(); + var signatures = []; + for (var i = 0; i < baseConstructSignatures.length; i++) { + var baseSignature = baseConstructSignatures[i]; + + baseSignature._resolveDeclaredSymbol(); + var currentSignature = new PullSignatureSymbol(2097152 /* ConstructSignature */, baseSignature.isDefinition()); + currentSignature.returnType = instanceTypeSymbol; + currentSignature.addTypeParametersFromReturnType(); + for (var j = 0; j < baseSignature.parameters.length; j++) { + currentSignature.addParameter(baseSignature.parameters[j], baseSignature.parameters[j].isOptional); + } + if (baseSignature.parameters.length > 0) { + currentSignature.hasVarArgs = baseSignature.parameters[baseSignature.parameters.length - 1].isVarArg; + } + + currentSignature.addDeclaration(instanceTypeSymbol.getDeclarations()[0]); + this.addCallOrConstructSignaturePrerequisiteBase(currentSignature); + signatures.push(currentSignature); + } + + return signatures; + }; + + PullTypeSymbol.prototype.getDefaultClassConstructSignature = function () { + TypeScript.Debug.assert(this.isConstructor()); + var instanceTypeSymbol = this.getAssociatedContainerType(); + TypeScript.Debug.assert(instanceTypeSymbol.getDeclarations().length == 1); + var signature = new PullSignatureSymbol(2097152 /* ConstructSignature */, true); + signature.returnType = instanceTypeSymbol; + signature.addTypeParametersFromReturnType(); + signature.addDeclaration(instanceTypeSymbol.getDeclarations()[0]); + this.addCallOrConstructSignaturePrerequisiteBase(signature); + + return signature; + }; + + PullTypeSymbol.prototype.addImplementedType = function (implementedType) { + if (!implementedType) { + return; + } + + if (!this._implementedTypes) { + this._implementedTypes = []; + } + + this._implementedTypes[this._implementedTypes.length] = implementedType; + + implementedType.addTypeThatExplicitlyImplementsThisType(this); + }; + + PullTypeSymbol.prototype.getImplementedTypes = function () { + if (!this._implementedTypes) { + return TypeScript.sentinelEmptyArray; + } + + return this._implementedTypes; + }; + + PullTypeSymbol.prototype.addExtendedType = function (extendedType) { + if (!extendedType) { + return; + } + + if (!this._extendedTypes) { + this._extendedTypes = []; + } + + this._extendedTypes[this._extendedTypes.length] = extendedType; + + extendedType.addTypeThatExtendsThisType(this); + }; + + PullTypeSymbol.prototype.getExtendedTypes = function () { + if (!this._extendedTypes) { + return TypeScript.sentinelEmptyArray; + } + + return this._extendedTypes; + }; + + PullTypeSymbol.prototype.addTypeThatExtendsThisType = function (type) { + if (!type) { + return; + } + + if (!this._typesThatExtendThisType) { + this._typesThatExtendThisType = []; + } + + this._typesThatExtendThisType[this._typesThatExtendThisType.length] = type; + }; + + PullTypeSymbol.prototype.getTypesThatExtendThisType = function () { + if (!this._typesThatExtendThisType) { + this._typesThatExtendThisType = []; + } + + return this._typesThatExtendThisType; + }; + + PullTypeSymbol.prototype.addTypeThatExplicitlyImplementsThisType = function (type) { + if (!type) { + return; + } + + if (!this._typesThatExplicitlyImplementThisType) { + this._typesThatExplicitlyImplementThisType = []; + } + + this._typesThatExplicitlyImplementThisType[this._typesThatExplicitlyImplementThisType.length] = type; + }; + + PullTypeSymbol.prototype.getTypesThatExplicitlyImplementThisType = function () { + if (!this._typesThatExplicitlyImplementThisType) { + this._typesThatExplicitlyImplementThisType = []; + } + + return this._typesThatExplicitlyImplementThisType; + }; + + PullTypeSymbol.prototype.hasBase = function (potentialBase, visited) { + if (typeof visited === "undefined") { visited = []; } + if (this === potentialBase || this.getRootSymbol() === potentialBase || this === potentialBase.getRootSymbol()) { + return true; + } + + if (TypeScript.ArrayUtilities.contains(visited, this)) { + return true; + } + + visited.push(this); + + var extendedTypes = this.getExtendedTypes(); + + for (var i = 0; i < extendedTypes.length; i++) { + if (extendedTypes[i].hasBase(potentialBase, visited)) { + return true; + } + } + + var implementedTypes = this.getImplementedTypes(); + + for (var i = 0; i < implementedTypes.length; i++) { + if (implementedTypes[i].hasBase(potentialBase, visited)) { + return true; + } + } + + visited.pop(); + + return false; + }; + + PullTypeSymbol.prototype.isValidBaseKind = function (baseType, isExtendedType) { + if (baseType.isError()) { + return false; + } + + var thisIsClass = this.isClass(); + if (isExtendedType) { + if (thisIsClass) { + return baseType.kind === 8 /* Class */; + } + } else { + if (!thisIsClass) { + return false; + } + } + + return !!(baseType.kind & (16 /* Interface */ | 8 /* Class */)); + }; + + PullTypeSymbol.prototype.findMember = function (name, lookInParent) { + var memberSymbol = null; + + if (this._memberNameCache) { + memberSymbol = this._memberNameCache[name]; + } + + if (memberSymbol || !lookInParent) { + return memberSymbol; + } + + if (this._extendedTypes) { + for (var i = 0; i < this._extendedTypes.length; i++) { + memberSymbol = this._extendedTypes[i].findMember(name, lookInParent); + + if (memberSymbol) { + return memberSymbol; + } + } + } + + return null; + }; + + PullTypeSymbol.prototype.findNestedType = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + var memberSymbol; + + if (!this._enclosedTypeNameCache) { + return null; + } + + memberSymbol = this._enclosedTypeNameCache[name]; + + if (memberSymbol && kind !== 0 /* None */) { + memberSymbol = TypeScript.hasFlag(memberSymbol.kind, kind) ? memberSymbol : null; + } + + return memberSymbol; + }; + + PullTypeSymbol.prototype.findNestedContainer = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + var memberSymbol; + + if (!this._enclosedContainerCache) { + return null; + } + + memberSymbol = this._enclosedContainerCache[name]; + + if (memberSymbol && kind !== 0 /* None */) { + memberSymbol = TypeScript.hasFlag(memberSymbol.kind, kind) ? memberSymbol : null; + } + + return memberSymbol; + }; + + PullTypeSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisiblity) { + var allMembers = []; + + if (this._members !== TypeScript.sentinelEmptyArray) { + for (var i = 0, n = this._members.length; i < n; i++) { + var member = this._members[i]; + if ((member.kind & searchDeclKind) && (memberVisiblity !== 2 /* externallyVisible */ || !member.anyDeclHasFlag(2 /* Private */))) { + allMembers[allMembers.length] = member; + } + } + } + + if (this._extendedTypes) { + var extenedMembersVisibility = memberVisiblity !== 0 /* all */ ? 2 /* externallyVisible */ : 0 /* all */; + + for (var i = 0, n = this._extendedTypes.length; i < n; i++) { + var extendedMembers = this._extendedTypes[i].getAllMembers(searchDeclKind, extenedMembersVisibility); + + for (var j = 0, m = extendedMembers.length; j < m; j++) { + var extendedMember = extendedMembers[j]; + if (!(this._memberNameCache && this._memberNameCache[extendedMember.name])) { + allMembers[allMembers.length] = extendedMember; + } + } + } + } + + if (this.isContainer()) { + if (this._enclosedMemberTypes) { + for (var i = 0; i < this._enclosedMemberTypes.length; i++) { + allMembers[allMembers.length] = this._enclosedMemberTypes[i]; + } + } + if (this._enclosedMemberContainers) { + for (var i = 0; i < this._enclosedMemberContainers.length; i++) { + allMembers[allMembers.length] = this._enclosedMemberContainers[i]; + } + } + } + + return allMembers; + }; + + PullTypeSymbol.prototype.findTypeParameter = function (name) { + if (!this._typeParameterNameCache) { + return null; + } + + return this._typeParameterNameCache[name]; + }; + + PullTypeSymbol.prototype.setResolved = function () { + _super.prototype.setResolved.call(this); + }; + + PullTypeSymbol.prototype.getNamePartForFullName = function () { + var name = _super.prototype.getNamePartForFullName.call(this); + + var typars = this.getTypeArgumentsOrTypeParameters(); + var typarString = PullSymbol.getTypeParameterString(typars, this, true); + return name + typarString; + }; + + PullTypeSymbol.prototype.getScopedName = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName) { + return this.getScopedNameEx(scopeSymbol, skipTypeParametersInName, useConstraintInName, false, false, skipInternalAliasName).toString(); + }; + + PullTypeSymbol.prototype.isNamedTypeSymbol = function () { + var kind = this.kind; + if (kind === 2 /* Primitive */ || kind === 8 /* Class */ || kind === 4 /* Container */ || kind === 32 /* DynamicModule */ || kind === 128 /* TypeAlias */ || kind === 64 /* Enum */ || kind === 8192 /* TypeParameter */ || ((kind === 16 /* Interface */ || kind === 8388608 /* ObjectType */) && this.name !== "")) { + return true; + } + + return false; + }; + + PullTypeSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + var s = this.getScopedNameEx(scopeSymbol, false, useConstraintInName).toString(); + return s; + }; + + PullTypeSymbol.prototype.getScopedNameEx = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName, shouldAllowArrayType) { + if (typeof shouldAllowArrayType === "undefined") { shouldAllowArrayType = true; } + if (this.isArrayNamedTypeReference() && shouldAllowArrayType) { + var elementType = this.getElementType(); + var elementMemberName = elementType ? (elementType.isArrayNamedTypeReference() || elementType.isNamedTypeSymbol() ? elementType.getScopedNameEx(scopeSymbol, false, false, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName) : elementType.getMemberTypeNameEx(false, scopeSymbol, getPrettyTypeName)) : TypeScript.MemberName.create("any"); + return TypeScript.MemberName.create(elementMemberName, "", "[]"); + } + + if (!this.isNamedTypeSymbol()) { + return this.getMemberTypeNameEx(true, scopeSymbol, getPrettyTypeName); + } + + if (skipTypeParametersInName) { + return TypeScript.MemberName.create(_super.prototype.getScopedName.call(this, scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName)); + } else { + var builder = new TypeScript.MemberNameArray(); + builder.prefix = _super.prototype.getScopedName.call(this, scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName); + + var typars = this.getTypeArgumentsOrTypeParameters(); + builder.add(PullSymbol.getTypeParameterStringEx(typars, scopeSymbol, getTypeParamMarkerInfo, useConstraintInName)); + + return builder; + } + }; + + PullTypeSymbol.prototype.hasOnlyOverloadCallSignatures = function () { + var members = this.getMembers(); + var callSignatures = this.getCallSignatures(); + var constructSignatures = this.getConstructSignatures(); + return members.length === 0 && constructSignatures.length === 0 && callSignatures.length > 1; + }; + + PullTypeSymbol.prototype.getTypeOfSymbol = function () { + var associatedContainerType = this.getAssociatedContainerType(); + if (associatedContainerType && associatedContainerType.isNamedTypeSymbol()) { + return associatedContainerType; + } + + var functionSymbol = this.getFunctionSymbol(); + if (functionSymbol && functionSymbol.kind === 16384 /* Function */ && !TypeScript.PullHelpers.isSymbolLocal(functionSymbol)) { + return TypeScript.PullHelpers.isExportedSymbolInClodule(functionSymbol) ? null : functionSymbol; + } + + return null; + }; + + PullTypeSymbol.prototype.getMemberTypeNameEx = function (topLevel, scopeSymbol, getPrettyTypeName) { + var members = this.getMembers(); + var callSignatures = this.getCallSignatures(); + var constructSignatures = this.getConstructSignatures(); + var indexSignatures = this.getIndexSignatures(); + + var typeOfSymbol = this.getTypeOfSymbol(); + if (typeOfSymbol) { + var nameForTypeOf = typeOfSymbol.getScopedNameEx(scopeSymbol, true); + return TypeScript.MemberName.create(nameForTypeOf, "typeof ", ""); + } + + if (members.length > 0 || callSignatures.length > 0 || constructSignatures.length > 0 || indexSignatures.length > 0) { + if (this._inMemberTypeNameEx) { + return TypeScript.MemberName.create("any"); + } + + this._inMemberTypeNameEx = true; + + var allMemberNames = new TypeScript.MemberNameArray(); + var curlies = !topLevel || indexSignatures.length !== 0; + var delim = "; "; + for (var i = 0; i < members.length; i++) { + if (members[i].kind === 65536 /* Method */ && members[i].type.hasOnlyOverloadCallSignatures()) { + var methodCallSignatures = members[i].type.getCallSignatures(); + var nameStr = members[i].getDisplayName(scopeSymbol) + (members[i].isOptional ? "?" : ""); + ; + var methodMemberNames = PullSignatureSymbol.getSignaturesTypeNameEx(methodCallSignatures, nameStr, false, false, scopeSymbol); + allMemberNames.addAll(methodMemberNames); + } else { + var memberTypeName = members[i].getNameAndTypeNameEx(scopeSymbol); + if (memberTypeName.isArray() && memberTypeName.delim === delim) { + allMemberNames.addAll(memberTypeName.entries); + } else { + allMemberNames.add(memberTypeName); + } + } + curlies = true; + } + + var getPrettyFunctionOverload = getPrettyTypeName && !curlies && this.hasOnlyOverloadCallSignatures(); + + var signatureCount = callSignatures.length + constructSignatures.length + indexSignatures.length; + var useShortFormSignature = !curlies && (signatureCount === 1); + var signatureMemberName; + + if (callSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(callSignatures, "", useShortFormSignature, false, scopeSymbol, getPrettyFunctionOverload); + allMemberNames.addAll(signatureMemberName); + } + + if (constructSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(constructSignatures, "new", useShortFormSignature, false, scopeSymbol); + allMemberNames.addAll(signatureMemberName); + } + + if (indexSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(indexSignatures, "", useShortFormSignature, true, scopeSymbol); + allMemberNames.addAll(signatureMemberName); + } + + if ((curlies) || (!getPrettyFunctionOverload && (signatureCount > 1) && topLevel)) { + allMemberNames.prefix = "{ "; + allMemberNames.suffix = "}"; + allMemberNames.delim = delim; + } else if (allMemberNames.entries.length > 1) { + allMemberNames.delim = delim; + } + + this._inMemberTypeNameEx = false; + + return allMemberNames; + } + + return TypeScript.MemberName.create("{}"); + }; + + PullTypeSymbol.prototype.getGenerativeTypeClassification = function (enclosingType) { + return 2 /* Closed */; + }; + + PullTypeSymbol.prototype.wrapsSomeTypeParameter = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + return this.getWrappingTypeParameterID(typeParameterArgumentMap, skipTypeArgumentCheck) != 0; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterID = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + var type = this; + + if (type.isTypeParameter()) { + if (typeParameterArgumentMap[type.pullSymbolID] || typeParameterArgumentMap[type.getRootSymbol().pullSymbolID]) { + return type.pullSymbolID; + } + + var constraint = type.getConstraint(); + var wrappingTypeParameterID = constraint ? constraint.getWrappingTypeParameterID(typeParameterArgumentMap) : 0; + return wrappingTypeParameterID; + } + + if (type.inWrapCheck) { + return 0; + } + + this._wrapsTypeParameterCache = this._wrapsTypeParameterCache || new TypeScript.WrapsTypeParameterCache(); + var wrappingTypeParameterID = this._wrapsTypeParameterCache.getWrapsTypeParameter(typeParameterArgumentMap); + if (wrappingTypeParameterID === undefined) { + wrappingTypeParameterID = this.getWrappingTypeParameterIDWorker(typeParameterArgumentMap, skipTypeArgumentCheck); + + this._wrapsTypeParameterCache.setWrapsTypeParameter(typeParameterArgumentMap, wrappingTypeParameterID); + } + return wrappingTypeParameterID; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterIDFromSignatures = function (signatures, typeParameterArgumentMap) { + for (var i = 0; i < signatures.length; i++) { + var wrappingTypeParameterID = signatures[i].getWrappingTypeParameterID(typeParameterArgumentMap); + if (wrappingTypeParameterID !== 0) { + return wrappingTypeParameterID; + } + } + + return 0; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterIDWorker = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + var type = this; + var wrappingTypeParameterID = 0; + + if (!skipTypeArgumentCheck) { + type.inWrapCheck = true; + + var typeArguments = type.getTypeArguments(); + + if (type.isGeneric() && !typeArguments) { + typeArguments = type.getTypeParameters(); + } + + if (typeArguments) { + for (var i = 0; !wrappingTypeParameterID && i < typeArguments.length; i++) { + wrappingTypeParameterID = typeArguments[i].getWrappingTypeParameterID(typeParameterArgumentMap); + } + } + } + + if (skipTypeArgumentCheck || !(type.kind & 8216 /* SomeInstantiatableType */) || !type.name) { + var members = type.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + for (var i = 0; !wrappingTypeParameterID && i < members.length; i++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(members[i]); + wrappingTypeParameterID = members[i].type.getWrappingTypeParameterID(typeParameterArgumentMap); + } + + wrappingTypeParameterID = wrappingTypeParameterID || this.getWrappingTypeParameterIDFromSignatures(type.getCallSignatures(), typeParameterArgumentMap) || this.getWrappingTypeParameterIDFromSignatures(type.getConstructSignatures(), typeParameterArgumentMap) || this.getWrappingTypeParameterIDFromSignatures(type.getIndexSignatures(), typeParameterArgumentMap); + } + + if (!skipTypeArgumentCheck) { + type.inWrapCheck = false; + } + + return wrappingTypeParameterID; + }; + + PullTypeSymbol.prototype.wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference = function (enclosingType) { + TypeScript.Debug.assert(this.isNamedTypeSymbol()); + TypeScript.Debug.assert(TypeScript.PullHelpers.getRootType(enclosingType) == enclosingType); + var knownWrapMap = TypeScript.BitMatrix.getBitMatrix(true); + var wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap); + knownWrapMap.release(); + return wrapsIntoInfinitelyExpandingTypeReference; + }; + + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse = function (enclosingType, knownWrapMap) { + var wrapsIntoInfinitelyExpandingTypeReference = knownWrapMap.valueAt(this.pullSymbolID, enclosingType.pullSymbolID); + if (wrapsIntoInfinitelyExpandingTypeReference != undefined) { + return wrapsIntoInfinitelyExpandingTypeReference; + } + + if (this.inWrapInfiniteExpandingReferenceCheck) { + return false; + } + + this.inWrapInfiniteExpandingReferenceCheck = true; + wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker(enclosingType, knownWrapMap); + knownWrapMap.setValueAt(this.pullSymbolID, enclosingType.pullSymbolID, wrapsIntoInfinitelyExpandingTypeReference); + this.inWrapInfiniteExpandingReferenceCheck = false; + + return wrapsIntoInfinitelyExpandingTypeReference; + }; + + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker = function (enclosingType, knownWrapMap) { + var thisRootType = TypeScript.PullHelpers.getRootType(this); + + if (thisRootType != enclosingType) { + var thisIsNamedType = this.isNamedTypeSymbol(); + + if (thisIsNamedType) { + if (thisRootType.inWrapInfiniteExpandingReferenceCheck) { + return false; + } + + thisRootType.inWrapInfiniteExpandingReferenceCheck = true; + } + + var wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceStructure(enclosingType, knownWrapMap); + + if (thisIsNamedType) { + thisRootType.inWrapInfiniteExpandingReferenceCheck = false; + } + + return wrapsIntoInfinitelyExpandingTypeReference; + } + + var enclosingTypeParameters = enclosingType.getTypeParameters(); + var typeArguments = this.getTypeArguments(); + for (var i = 0; i < typeArguments.length; i++) { + if (TypeScript.ArrayUtilities.contains(enclosingTypeParameters, typeArguments[i])) { + continue; + } + + if (typeArguments[i].wrapsSomeTypeParameter(this.getTypeParameterArgumentMap())) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceStructure = function (enclosingType, knownWrapMap) { + var members = this.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + for (var i = 0; i < members.length; i++) { + if (members[i].type && members[i].type._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; + } + } + + var sigs = this.getCallSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + sigs = this.getConstructSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + sigs = this.getIndexSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.widenedType = function (resolver, ast, context) { + if (!this._widenedType) { + this._widenedType = resolver.widenType(this, ast, context); + } + return this._widenedType; + }; + return PullTypeSymbol; + })(PullSymbol); + TypeScript.PullTypeSymbol = PullTypeSymbol; + + var PullPrimitiveTypeSymbol = (function (_super) { + __extends(PullPrimitiveTypeSymbol, _super); + function PullPrimitiveTypeSymbol(name) { + _super.call(this, name, 2 /* Primitive */); + + this.isResolved = true; + } + PullPrimitiveTypeSymbol.prototype.isAny = function () { + return !this.isStringConstant() && this.name === "any"; + }; + + PullPrimitiveTypeSymbol.prototype.isNull = function () { + return !this.isStringConstant() && this.name === "null"; + }; + + PullPrimitiveTypeSymbol.prototype.isUndefined = function () { + return !this.isStringConstant() && this.name === "undefined"; + }; + + PullPrimitiveTypeSymbol.prototype.isStringConstant = function () { + return false; + }; + + PullPrimitiveTypeSymbol.prototype.setUnresolved = function () { + }; + + PullPrimitiveTypeSymbol.prototype.getDisplayName = function () { + if (this.isNull() || this.isUndefined()) { + return "any"; + } else { + return _super.prototype.getDisplayName.call(this); + } + }; + return PullPrimitiveTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullPrimitiveTypeSymbol = PullPrimitiveTypeSymbol; + + var PullStringConstantTypeSymbol = (function (_super) { + __extends(PullStringConstantTypeSymbol, _super); + function PullStringConstantTypeSymbol(name) { + _super.call(this, name); + } + PullStringConstantTypeSymbol.prototype.isStringConstant = function () { + return true; + }; + return PullStringConstantTypeSymbol; + })(PullPrimitiveTypeSymbol); + TypeScript.PullStringConstantTypeSymbol = PullStringConstantTypeSymbol; + + var PullErrorTypeSymbol = (function (_super) { + __extends(PullErrorTypeSymbol, _super); + function PullErrorTypeSymbol(_anyType, name) { + _super.call(this, name); + this._anyType = _anyType; + + TypeScript.Debug.assert(this._anyType); + this.isResolved = true; + } + PullErrorTypeSymbol.prototype.isError = function () { + return true; + }; + + PullErrorTypeSymbol.prototype._getResolver = function () { + return this._anyType._getResolver(); + }; + + PullErrorTypeSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + return this._anyType.getName(scopeSymbol, useConstraintInName); + }; + + PullErrorTypeSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { + return this._anyType.getName(scopeSymbol, useConstraintInName); + }; + + PullErrorTypeSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + return this._anyType.getName(scopeSymbol, useConstraintInName); + }; + return PullErrorTypeSymbol; + })(PullPrimitiveTypeSymbol); + TypeScript.PullErrorTypeSymbol = PullErrorTypeSymbol; + + var PullContainerSymbol = (function (_super) { + __extends(PullContainerSymbol, _super); + function PullContainerSymbol(name, kind) { + _super.call(this, name, kind); + this.instanceSymbol = null; + this.assignedValue = null; + this.assignedType = null; + this.assignedContainer = null; + } + PullContainerSymbol.prototype.isContainer = function () { + return true; + }; + + PullContainerSymbol.prototype.setInstanceSymbol = function (symbol) { + this.instanceSymbol = symbol; + }; + + PullContainerSymbol.prototype.getInstanceSymbol = function () { + return this.instanceSymbol; + }; + + PullContainerSymbol.prototype.setExportAssignedValueSymbol = function (symbol) { + this.assignedValue = symbol; + }; + + PullContainerSymbol.prototype.getExportAssignedValueSymbol = function () { + return this.assignedValue; + }; + + PullContainerSymbol.prototype.setExportAssignedTypeSymbol = function (type) { + this.assignedType = type; + }; + + PullContainerSymbol.prototype.getExportAssignedTypeSymbol = function () { + return this.assignedType; + }; + + PullContainerSymbol.prototype.setExportAssignedContainerSymbol = function (container) { + this.assignedContainer = container; + }; + + PullContainerSymbol.prototype.getExportAssignedContainerSymbol = function () { + return this.assignedContainer; + }; + + PullContainerSymbol.prototype.hasExportAssignment = function () { + return !!this.assignedValue || !!this.assignedType || !!this.assignedContainer; + }; + + PullContainerSymbol.usedAsSymbol = function (containerSymbol, symbol) { + if (!containerSymbol || !containerSymbol.isContainer()) { + return false; + } + + if (!containerSymbol.isAlias() && containerSymbol.type === symbol) { + return true; + } + + var moduleSymbol = containerSymbol; + var valueExportSymbol = moduleSymbol.getExportAssignedValueSymbol(); + var typeExportSymbol = moduleSymbol.getExportAssignedTypeSymbol(); + var containerExportSymbol = moduleSymbol.getExportAssignedContainerSymbol(); + if (valueExportSymbol || typeExportSymbol || containerExportSymbol) { + if (valueExportSymbol === symbol || typeExportSymbol == symbol || containerExportSymbol == symbol) { + return true; + } + + if (containerExportSymbol != containerSymbol) { + return PullContainerSymbol.usedAsSymbol(containerExportSymbol, symbol); + } + } + + return false; + }; + + PullContainerSymbol.prototype.getInstanceType = function () { + return this.instanceSymbol ? this.instanceSymbol.type : null; + }; + return PullContainerSymbol; + })(PullTypeSymbol); + TypeScript.PullContainerSymbol = PullContainerSymbol; + + var PullTypeAliasSymbol = (function (_super) { + __extends(PullTypeAliasSymbol, _super); + function PullTypeAliasSymbol(name) { + _super.call(this, name, 128 /* TypeAlias */); + this._assignedValue = null; + this._assignedType = null; + this._assignedContainer = null; + this._isUsedAsValue = false; + this._typeUsedExternally = false; + this._isUsedInExportAlias = false; + this.retrievingExportAssignment = false; + this.linkedAliasSymbols = null; + } + PullTypeAliasSymbol.prototype.isUsedInExportedAlias = function () { + this._resolveDeclaredSymbol(); + return this._isUsedInExportAlias; + }; + + PullTypeAliasSymbol.prototype.typeUsedExternally = function () { + this._resolveDeclaredSymbol(); + return this._typeUsedExternally; + }; + + PullTypeAliasSymbol.prototype.isUsedAsValue = function () { + this._resolveDeclaredSymbol(); + return this._isUsedAsValue; + }; + + PullTypeAliasSymbol.prototype.setTypeUsedExternally = function () { + this._typeUsedExternally = true; + }; + + PullTypeAliasSymbol.prototype.setIsUsedInExportedAlias = function () { + this._isUsedInExportAlias = true; + if (this.linkedAliasSymbols) { + this.linkedAliasSymbols.forEach(function (s) { + return s.setIsUsedInExportedAlias(); + }); + } + }; + + PullTypeAliasSymbol.prototype.addLinkedAliasSymbol = function (contingentValueSymbol) { + if (!this.linkedAliasSymbols) { + this.linkedAliasSymbols = [contingentValueSymbol]; + } else { + this.linkedAliasSymbols.push(contingentValueSymbol); + } + }; + + PullTypeAliasSymbol.prototype.setIsUsedAsValue = function () { + this._isUsedAsValue = true; + if (this.linkedAliasSymbols) { + this.linkedAliasSymbols.forEach(function (s) { + return s.setIsUsedAsValue(); + }); + } + }; + + PullTypeAliasSymbol.prototype.assignedValue = function () { + this._resolveDeclaredSymbol(); + return this._assignedValue; + }; + + PullTypeAliasSymbol.prototype.assignedType = function () { + this._resolveDeclaredSymbol(); + return this._assignedType; + }; + + PullTypeAliasSymbol.prototype.assignedContainer = function () { + this._resolveDeclaredSymbol(); + return this._assignedContainer; + }; + + PullTypeAliasSymbol.prototype.isAlias = function () { + return true; + }; + PullTypeAliasSymbol.prototype.isContainer = function () { + return true; + }; + + PullTypeAliasSymbol.prototype.setAssignedValueSymbol = function (symbol) { + this._assignedValue = symbol; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedValueSymbol = function () { + if (this._assignedValue) { + return this._assignedValue; + } + + if (this.retrievingExportAssignment) { + return null; + } + + if (this._assignedContainer) { + if (this._assignedContainer.hasExportAssignment()) { + this.retrievingExportAssignment = true; + var sym = this._assignedContainer.getExportAssignedValueSymbol(); + this.retrievingExportAssignment = false; + return sym; + } + + return this._assignedContainer.getInstanceSymbol(); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.setAssignedTypeSymbol = function (type) { + this._assignedType = type; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedTypeSymbol = function () { + if (this.retrievingExportAssignment) { + return null; + } + + if (this._assignedType) { + if (this._assignedType.isAlias()) { + this.retrievingExportAssignment = true; + var sym = this._assignedType.getExportAssignedTypeSymbol(); + this.retrievingExportAssignment = false; + } else if (this._assignedType !== this._assignedContainer) { + return this._assignedType; + } + } + + if (this._assignedContainer) { + this.retrievingExportAssignment = true; + var sym = this._assignedContainer.getExportAssignedTypeSymbol(); + this.retrievingExportAssignment = false; + if (sym) { + return sym; + } + } + + return this._assignedContainer; + }; + + PullTypeAliasSymbol.prototype.setAssignedContainerSymbol = function (container) { + this._assignedContainer = container; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedContainerSymbol = function () { + if (this.retrievingExportAssignment) { + return null; + } + + if (this._assignedContainer) { + this.retrievingExportAssignment = true; + var sym = this._assignedContainer.getExportAssignedContainerSymbol(); + this.retrievingExportAssignment = false; + if (sym) { + return sym; + } + } + + return this._assignedContainer; + }; + + PullTypeAliasSymbol.prototype.getMembers = function () { + if (this._assignedType) { + return this._assignedType.getMembers(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.getCallSignatures = function () { + if (this._assignedType) { + return this._assignedType.getCallSignatures(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.getConstructSignatures = function () { + if (this._assignedType) { + return this._assignedType.getConstructSignatures(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.getIndexSignatures = function () { + if (this._assignedType) { + return this._assignedType.getIndexSignatures(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.findMember = function (name) { + if (this._assignedType) { + return this._assignedType.findMember(name, true); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.findNestedType = function (name) { + if (this._assignedType) { + return this._assignedType.findNestedType(name); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.findNestedContainer = function (name) { + if (this._assignedType) { + return this._assignedType.findNestedContainer(name); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisibility) { + if (this._assignedType) { + return this._assignedType.getAllMembers(searchDeclKind, memberVisibility); + } + + return TypeScript.sentinelEmptyArray; + }; + return PullTypeAliasSymbol; + })(PullTypeSymbol); + TypeScript.PullTypeAliasSymbol = PullTypeAliasSymbol; + + var PullTypeParameterSymbol = (function (_super) { + __extends(PullTypeParameterSymbol, _super); + function PullTypeParameterSymbol(name) { + _super.call(this, name, 8192 /* TypeParameter */); + this._constraint = null; + } + PullTypeParameterSymbol.prototype.isTypeParameter = function () { + return true; + }; + + PullTypeParameterSymbol.prototype.setConstraint = function (constraintType) { + this._constraint = constraintType; + }; + + PullTypeParameterSymbol.prototype.getConstraint = function () { + return this._constraint; + }; + + PullTypeParameterSymbol.prototype.getBaseConstraint = function (semanticInfoChain) { + var preBaseConstraint = this.getConstraintRecursively({}); + TypeScript.Debug.assert(preBaseConstraint === null || !preBaseConstraint.isTypeParameter()); + return preBaseConstraint || semanticInfoChain.emptyTypeSymbol; + }; + + PullTypeParameterSymbol.prototype.getConstraintRecursively = function (visitedTypeParameters) { + var constraint = this.getConstraint(); + + if (constraint) { + if (constraint.isTypeParameter()) { + var constraintAsTypeParameter = constraint; + if (!visitedTypeParameters[constraintAsTypeParameter.pullSymbolID]) { + visitedTypeParameters[constraintAsTypeParameter.pullSymbolID] = constraintAsTypeParameter; + return constraintAsTypeParameter.getConstraintRecursively(visitedTypeParameters); + } + } else { + return constraint; + } + } + + return null; + }; + + PullTypeParameterSymbol.prototype.getDefaultConstraint = function (semanticInfoChain) { + return this._constraint || semanticInfoChain.emptyTypeSymbol; + }; + + PullTypeParameterSymbol.prototype.getCallSignatures = function () { + if (this._constraint) { + return this._constraint.getCallSignatures(); + } + + return _super.prototype.getCallSignatures.call(this); + }; + + PullTypeParameterSymbol.prototype.getConstructSignatures = function () { + if (this._constraint) { + return this._constraint.getConstructSignatures(); + } + + return _super.prototype.getConstructSignatures.call(this); + }; + + PullTypeParameterSymbol.prototype.getIndexSignatures = function () { + if (this._constraint) { + return this._constraint.getIndexSignatures(); + } + + return _super.prototype.getIndexSignatures.call(this); + }; + + PullTypeParameterSymbol.prototype.isGeneric = function () { + return true; + }; + + PullTypeParameterSymbol.prototype.fullName = function (scopeSymbol) { + var name = this.getDisplayName(scopeSymbol); + var container = this.getContainer(); + if (container) { + var containerName = container.fullName(scopeSymbol); + name = name + " in " + containerName; + } + + return name; + }; + + PullTypeParameterSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + var name = _super.prototype.getName.call(this, scopeSymbol); + + if (this.isPrinting) { + return name; + } + + this.isPrinting = true; + + if (useConstraintInName && this._constraint) { + name += " extends " + this._constraint.toString(scopeSymbol); + } + + this.isPrinting = false; + + return name; + }; + + PullTypeParameterSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { + var name = _super.prototype.getDisplayName.call(this, scopeSymbol, useConstraintInName, skipInternalAliasName); + + if (this.isPrinting) { + return name; + } + + this.isPrinting = true; + + if (useConstraintInName && this._constraint) { + name += " extends " + this._constraint.toString(scopeSymbol); + } + + this.isPrinting = false; + + return name; + }; + + PullTypeParameterSymbol.prototype.isExternallyVisible = function (inIsExternallyVisibleSymbols) { + return true; + }; + return PullTypeParameterSymbol; + })(PullTypeSymbol); + TypeScript.PullTypeParameterSymbol = PullTypeParameterSymbol; + + var PullAccessorSymbol = (function (_super) { + __extends(PullAccessorSymbol, _super); + function PullAccessorSymbol(name) { + _super.call(this, name, 4096 /* Property */); + this._getterSymbol = null; + this._setterSymbol = null; + } + PullAccessorSymbol.prototype.isAccessor = function () { + return true; + }; + + PullAccessorSymbol.prototype.setSetter = function (setter) { + if (!setter) { + return; + } + + this._setterSymbol = setter; + }; + + PullAccessorSymbol.prototype.getSetter = function () { + return this._setterSymbol; + }; + + PullAccessorSymbol.prototype.setGetter = function (getter) { + if (!getter) { + return; + } + + this._getterSymbol = getter; + }; + + PullAccessorSymbol.prototype.getGetter = function () { + return this._getterSymbol; + }; + return PullAccessorSymbol; + })(PullSymbol); + TypeScript.PullAccessorSymbol = PullAccessorSymbol; + + function getIDForTypeSubstitutions(instantiatingTypeOrSignature, typeArgumentMap) { + var substitution = ""; + var members = null; + + var allowedToReferenceTypeParameters = instantiatingTypeOrSignature.getAllowedToReferenceTypeParameters(); + for (var i = 0; i < allowedToReferenceTypeParameters.length; i++) { + var typeParameter = allowedToReferenceTypeParameters[i]; + var typeParameterID = typeParameter.pullSymbolID; + var typeArg = typeArgumentMap[typeParameterID]; + if (!typeArg) { + typeArg = typeParameter; + } + substitution += typeParameterID + ":" + getIDForTypeSubstitutionsOfType(typeArg); + } + + return substitution; + } + TypeScript.getIDForTypeSubstitutions = getIDForTypeSubstitutions; + + function getIDForTypeSubstitutionsOfType(type) { + var structure; + if (type.isError()) { + structure = "E" + getIDForTypeSubstitutionsOfType(type._anyType); + } else if (!type.isNamedTypeSymbol()) { + structure = getIDForTypeSubstitutionsFromObjectType(type); + } + + if (!structure) { + structure = type.pullSymbolID + "#"; + } + + return structure; + } + + function getIDForTypeSubstitutionsFromObjectType(type) { + if (type.isResolved) { + var getIDForTypeSubStitutionWalker = new GetIDForTypeSubStitutionWalker(); + TypeScript.PullHelpers.walkPullTypeSymbolStructure(type, getIDForTypeSubStitutionWalker); + } + + return null; + } + + var GetIDForTypeSubStitutionWalker = (function () { + function GetIDForTypeSubStitutionWalker() { + this.structure = ""; + } + GetIDForTypeSubStitutionWalker.prototype.memberSymbolWalk = function (memberSymbol) { + this.structure += memberSymbol.name + "@" + getIDForTypeSubstitutionsOfType(memberSymbol.type); + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.callSignatureWalk = function (signatureSymbol) { + this.structure += "("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.constructSignatureWalk = function (signatureSymbol) { + this.structure += "new("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.indexSignatureWalk = function (signatureSymbol) { + this.structure += "[]("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.signatureParameterWalk = function (parameterSymbol) { + this.structure += parameterSymbol.name + "@" + getIDForTypeSubstitutionsOfType(parameterSymbol.type); + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.signatureReturnTypeWalk = function (returnType) { + this.structure += ")" + getIDForTypeSubstitutionsOfType(returnType); + return true; + }; + return GetIDForTypeSubStitutionWalker; + })(); + + (function (GetAllMembersVisiblity) { + GetAllMembersVisiblity[GetAllMembersVisiblity["all"] = 0] = "all"; + + GetAllMembersVisiblity[GetAllMembersVisiblity["internallyVisible"] = 1] = "internallyVisible"; + + GetAllMembersVisiblity[GetAllMembersVisiblity["externallyVisible"] = 2] = "externallyVisible"; + })(TypeScript.GetAllMembersVisiblity || (TypeScript.GetAllMembersVisiblity = {})); + var GetAllMembersVisiblity = TypeScript.GetAllMembersVisiblity; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var EnclosingTypeWalkerState = (function () { + function EnclosingTypeWalkerState() { + } + EnclosingTypeWalkerState.getDefaultEnclosingTypeWalkerState = function () { + var defaultEnclosingTypeWalkerState = new EnclosingTypeWalkerState(); + defaultEnclosingTypeWalkerState._hasSetEnclosingType = false; + return defaultEnclosingTypeWalkerState; + }; + + EnclosingTypeWalkerState.getNonGenericEnclosingTypeWalkerState = function () { + var defaultEnclosingTypeWalkerState = new EnclosingTypeWalkerState(); + defaultEnclosingTypeWalkerState._hasSetEnclosingType = true; + return defaultEnclosingTypeWalkerState; + }; + + EnclosingTypeWalkerState.getGenericEnclosingTypeWalkerState = function (genericEnclosingType) { + var defaultEnclosingTypeWalkerState = new EnclosingTypeWalkerState(); + defaultEnclosingTypeWalkerState._hasSetEnclosingType = true; + defaultEnclosingTypeWalkerState._currentSymbols = [TypeScript.PullHelpers.getRootType(genericEnclosingType)]; + return defaultEnclosingTypeWalkerState; + }; + return EnclosingTypeWalkerState; + })(); + TypeScript.EnclosingTypeWalkerState = EnclosingTypeWalkerState; + + var PullTypeEnclosingTypeWalker = (function () { + function PullTypeEnclosingTypeWalker() { + this.setDefaultTypeWalkerState(); + } + PullTypeEnclosingTypeWalker.prototype.setDefaultTypeWalkerState = function () { + this.enclosingTypeWalkerState = PullTypeEnclosingTypeWalker._defaultEnclosingTypeWalkerState; + }; + + PullTypeEnclosingTypeWalker.prototype.setNonGenericEnclosingTypeWalkerState = function () { + this.enclosingTypeWalkerState = PullTypeEnclosingTypeWalker._nonGenericEnclosingTypeWalkerState; + }; + + PullTypeEnclosingTypeWalker.prototype.canSymbolOrDeclBeUsedAsEnclosingTypeHelper = function (name, kind) { + return name && (kind === 8 /* Class */ || kind === 16 /* Interface */); + }; + + PullTypeEnclosingTypeWalker.prototype.canDeclBeUsedAsEnclosingType = function (decl) { + return this.canSymbolOrDeclBeUsedAsEnclosingTypeHelper(decl.name, decl.kind); + }; + + PullTypeEnclosingTypeWalker.prototype.canSymbolBeUsedAsEnclosingType = function (symbol) { + return this.canSymbolOrDeclBeUsedAsEnclosingTypeHelper(symbol.name, symbol.kind); + }; + + PullTypeEnclosingTypeWalker.prototype.getEnclosingType = function () { + var currentSymbols = this.enclosingTypeWalkerState._currentSymbols; + if (currentSymbols) { + TypeScript.Debug.assert(currentSymbols.length > 0); + return currentSymbols[0]; + } + + return null; + }; + + PullTypeEnclosingTypeWalker.prototype._canWalkStructure = function () { + var enclosingType = this.getEnclosingType(); + TypeScript.Debug.assert(!enclosingType || enclosingType.isGeneric()); + return !!enclosingType; + }; + + PullTypeEnclosingTypeWalker.prototype._getCurrentSymbol = function () { + var currentSymbols = this.enclosingTypeWalkerState._currentSymbols; + if (currentSymbols && currentSymbols.length) { + return currentSymbols[currentSymbols.length - 1]; + } + + return null; + }; + + PullTypeEnclosingTypeWalker.prototype.getGenerativeClassification = function () { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + if (!currentType) { + return 0 /* Unknown */; + } + + var variableNeededToFixNodeJitterBug = this.getEnclosingType(); + + return currentType.getGenerativeTypeClassification(variableNeededToFixNodeJitterBug); + } + + return 2 /* Closed */; + }; + + PullTypeEnclosingTypeWalker.prototype._pushSymbol = function (symbol) { + return this.enclosingTypeWalkerState._currentSymbols.push(symbol); + }; + + PullTypeEnclosingTypeWalker.prototype._popSymbol = function () { + return this.enclosingTypeWalkerState._currentSymbols.pop(); + }; + + PullTypeEnclosingTypeWalker.prototype.setSymbolAsEnclosingType = function (type) { + if (type.isGeneric()) { + this.enclosingTypeWalkerState = EnclosingTypeWalkerState.getGenericEnclosingTypeWalkerState(type); + } else { + this.setNonGenericEnclosingTypeWalkerState(); + } + }; + + PullTypeEnclosingTypeWalker.prototype._setEnclosingTypeOfParentDecl = function (decl, setSignature) { + var parentDecl = decl.getParentDecl(); + + if (parentDecl && !(parentDecl.kind & (164 /* SomeContainer */ | 1 /* Script */))) { + if (this.canDeclBeUsedAsEnclosingType(parentDecl)) { + this.setSymbolAsEnclosingType(parentDecl.getSymbol()); + } else { + this._setEnclosingTypeOfParentDecl(parentDecl, true); + } + + if (this._canWalkStructure()) { + var symbol = decl.getSymbol(); + if (symbol) { + if (!symbol.isType() && !symbol.isSignature()) { + symbol = symbol.type; + } + + this._pushSymbol(symbol); + } + + if (setSignature) { + var signature = decl.getSignatureSymbol(); + if (signature) { + this._pushSymbol(signature); + } + } + } + } + }; + + PullTypeEnclosingTypeWalker.prototype.setEnclosingTypeForSymbol = function (symbol) { + var currentEnclosingTypeWalkerState = this.enclosingTypeWalkerState; + if (this.canSymbolBeUsedAsEnclosingType(symbol)) { + this.setSymbolAsEnclosingType(symbol); + } else { + this.setDefaultTypeWalkerState(); + + var decls = symbol.getDeclarations(); + for (var i = 0; i < decls.length; i++) { + var decl = decls[i]; + this._setEnclosingTypeOfParentDecl(decl, symbol.isSignature()); + + if (this.enclosingTypeWalkerState._hasSetEnclosingType) { + break; + } + } + + if (!this.enclosingTypeWalkerState._hasSetEnclosingType) { + this.setNonGenericEnclosingTypeWalkerState(); + } + } + return currentEnclosingTypeWalkerState; + }; + + PullTypeEnclosingTypeWalker.prototype.startWalkingType = function (symbol) { + var currentState = this.enclosingTypeWalkerState; + + var setEnclosingTypeForSymbol = !this.enclosingTypeWalkerState._hasSetEnclosingType || this.canSymbolBeUsedAsEnclosingType(symbol); + if (setEnclosingTypeForSymbol) { + this.setEnclosingTypeForSymbol(symbol); + } + return currentState; + }; + + PullTypeEnclosingTypeWalker.prototype.endWalkingType = function (stateWhenStartedWalkingTypes) { + this.enclosingTypeWalkerState = stateWhenStartedWalkingTypes; + }; + + PullTypeEnclosingTypeWalker.prototype.walkMemberType = function (memberName, resolver) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + var memberSymbol = currentType ? resolver._getNamedPropertySymbolOfAugmentedType(memberName, currentType) : null; + this._pushSymbol(memberSymbol ? memberSymbol.type : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkMemberType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkSignature = function (kind, index) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + var signatures; + if (currentType) { + if (kind == 1048576 /* CallSignature */) { + signatures = currentType.getCallSignatures(); + } else if (kind == 2097152 /* ConstructSignature */) { + signatures = currentType.getConstructSignatures(); + } else { + signatures = currentType.getIndexSignatures(); + } + } + + this._pushSymbol(signatures ? signatures[index] : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkSignature = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkTypeArgument = function (index) { + if (this._canWalkStructure()) { + var typeArgument = null; + var currentType = this._getCurrentSymbol(); + if (currentType) { + var typeArguments = currentType.getTypeArguments(); + typeArgument = typeArguments ? typeArguments[index] : null; + } + this._pushSymbol(typeArgument); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkTypeArgument = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkTypeParameterConstraint = function (index) { + if (this._canWalkStructure()) { + var typeParameters; + var currentSymbol = this._getCurrentSymbol(); + if (currentSymbol) { + if (currentSymbol.isSignature()) { + typeParameters = currentSymbol.getTypeParameters(); + } else { + TypeScript.Debug.assert(currentSymbol.isType()); + typeParameters = currentSymbol.getTypeParameters(); + } + } + this._pushSymbol(typeParameters ? typeParameters[index].getConstraint() : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkTypeParameterConstraint = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkReturnType = function () { + if (this._canWalkStructure()) { + var currentSignature = this._getCurrentSymbol(); + this._pushSymbol(currentSignature ? currentSignature.returnType : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkReturnType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkParameterType = function (iParam) { + if (this._canWalkStructure()) { + var currentSignature = this._getCurrentSymbol(); + this._pushSymbol(currentSignature ? currentSignature.getParameterTypeAtIndex(iParam) : null); + } + }; + PullTypeEnclosingTypeWalker.prototype.postWalkParameterType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.getBothKindOfIndexSignatures = function (resolver, context, includeAugmentedType) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + if (currentType) { + return resolver._getBothKindsOfIndexSignatures(currentType, context, includeAugmentedType); + } + } + return null; + }; + + PullTypeEnclosingTypeWalker.prototype.walkIndexSignatureReturnType = function (indexSigInfo, useStringIndexSignature, onlySignature) { + if (this._canWalkStructure()) { + var indexSig = indexSigInfo ? (useStringIndexSignature ? indexSigInfo.stringSignature : indexSigInfo.numericSignature) : null; + this._pushSymbol(indexSig); + if (!onlySignature) { + this._pushSymbol(indexSig ? indexSig.returnType : null); + } + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkIndexSignatureReturnType = function (onlySignature) { + if (this._canWalkStructure()) { + if (!onlySignature) { + this._popSymbol(); + } + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.resetEnclosingTypeWalkerState = function () { + var currentState = this.enclosingTypeWalkerState; + this.setDefaultTypeWalkerState(); + return currentState; + }; + + PullTypeEnclosingTypeWalker.prototype.setEnclosingTypeWalkerState = function (enclosingTypeWalkerState) { + if (enclosingTypeWalkerState) { + this.enclosingTypeWalkerState = enclosingTypeWalkerState; + } else { + this.setDefaultTypeWalkerState(); + } + }; + PullTypeEnclosingTypeWalker._defaultEnclosingTypeWalkerState = EnclosingTypeWalkerState.getDefaultEnclosingTypeWalkerState(); + + PullTypeEnclosingTypeWalker._nonGenericEnclosingTypeWalkerState = EnclosingTypeWalkerState.getNonGenericEnclosingTypeWalkerState(); + return PullTypeEnclosingTypeWalker; + })(); + TypeScript.PullTypeEnclosingTypeWalker = PullTypeEnclosingTypeWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CandidateInferenceInfo = (function () { + function CandidateInferenceInfo() { + this.typeParameter = null; + this._inferredTypeAfterFixing = null; + this.inferenceCandidates = []; + } + CandidateInferenceInfo.prototype.addCandidate = function (candidate) { + if (!this._inferredTypeAfterFixing) { + this.inferenceCandidates[this.inferenceCandidates.length] = candidate; + } + }; + + CandidateInferenceInfo.prototype.isFixed = function () { + return !!this._inferredTypeAfterFixing; + }; + + CandidateInferenceInfo.prototype.fixTypeParameter = function (resolver, context) { + var _this = this; + if (!this._inferredTypeAfterFixing) { + var collection = { + getLength: function () { + return _this.inferenceCandidates.length; + }, + getTypeAtIndex: function (index) { + return _this.inferenceCandidates[index].type; + } + }; + + var bestCommonType = resolver.findBestCommonType(collection, context, new TypeScript.TypeComparisonInfo()); + this._inferredTypeAfterFixing = bestCommonType.widenedType(resolver, null, context); + } + }; + return CandidateInferenceInfo; + })(); + TypeScript.CandidateInferenceInfo = CandidateInferenceInfo; + + var TypeArgumentInferenceContext = (function () { + function TypeArgumentInferenceContext(resolver, context, signatureBeingInferred) { + this.resolver = resolver; + this.context = context; + this.signatureBeingInferred = signatureBeingInferred; + this.inferenceCache = TypeScript.BitMatrix.getBitMatrix(false); + this.candidateCache = []; + var typeParameters = signatureBeingInferred.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + this.addInferenceRoot(typeParameters[i]); + } + } + TypeArgumentInferenceContext.prototype.alreadyRelatingTypes = function (objectType, parameterType) { + if (this.inferenceCache.valueAt(objectType.pullSymbolID, parameterType.pullSymbolID)) { + return true; + } else { + this.inferenceCache.setValueAt(objectType.pullSymbolID, parameterType.pullSymbolID, true); + return false; + } + }; + + TypeArgumentInferenceContext.prototype.resetRelationshipCache = function () { + this.inferenceCache.release(); + this.inferenceCache = TypeScript.BitMatrix.getBitMatrix(false); + }; + + TypeArgumentInferenceContext.prototype.addInferenceRoot = function (param) { + var info = this.candidateCache[param.pullSymbolID]; + + if (!info) { + info = new CandidateInferenceInfo(); + info.typeParameter = param; + this.candidateCache[param.pullSymbolID] = info; + } + }; + + TypeArgumentInferenceContext.prototype.getInferenceInfo = function (param) { + return this.candidateCache[param.pullSymbolID]; + }; + + TypeArgumentInferenceContext.prototype.addCandidateForInference = function (param, candidate) { + var info = this.getInferenceInfo(param); + + if (info && candidate && info.inferenceCandidates.indexOf(candidate) < 0) { + info.addCandidate(candidate); + } + }; + + TypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + throw TypeScript.Errors.abstract(); + }; + + TypeArgumentInferenceContext.prototype.fixTypeParameter = function (typeParameter) { + var candidateInfo = this.candidateCache[typeParameter.pullSymbolID]; + if (candidateInfo) { + candidateInfo.fixTypeParameter(this.resolver, this.context); + } + }; + + TypeArgumentInferenceContext.prototype._finalizeInferredTypeArguments = function () { + var results = []; + var typeParameters = this.signatureBeingInferred.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + var info = this.candidateCache[typeParameters[i].pullSymbolID]; + + info.fixTypeParameter(this.resolver, this.context); + + for (var i = 0; i < results.length; i++) { + if (results[i].type === info.typeParameter) { + results[i].type = info._inferredTypeAfterFixing; + } + } + + results.push(info._inferredTypeAfterFixing); + } + + return results; + }; + + TypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + throw TypeScript.Errors.abstract(); + }; + return TypeArgumentInferenceContext; + })(); + TypeScript.TypeArgumentInferenceContext = TypeArgumentInferenceContext; + + var InvocationTypeArgumentInferenceContext = (function (_super) { + __extends(InvocationTypeArgumentInferenceContext, _super); + function InvocationTypeArgumentInferenceContext(resolver, context, signatureBeingInferred, argumentASTs) { + _super.call(this, resolver, context, signatureBeingInferred); + this.argumentASTs = argumentASTs; + } + InvocationTypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + return true; + }; + + InvocationTypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + var _this = this; + this.signatureBeingInferred.forAllParameterTypes(this.argumentASTs.nonSeparatorCount(), function (parameterType, argumentIndex) { + var argumentAST = _this.argumentASTs.nonSeparatorAt(argumentIndex); + + _this.context.pushInferentialType(parameterType, _this); + var argumentType = _this.resolver.resolveAST(argumentAST, true, _this.context).type; + _this.resolver.relateTypeToTypeParametersWithNewEnclosingTypes(argumentType, parameterType, _this, _this.context); + _this.context.popAnyContextualType(); + + return true; + }); + + return this._finalizeInferredTypeArguments(); + }; + return InvocationTypeArgumentInferenceContext; + })(TypeArgumentInferenceContext); + TypeScript.InvocationTypeArgumentInferenceContext = InvocationTypeArgumentInferenceContext; + + var ContextualSignatureInstantiationTypeArgumentInferenceContext = (function (_super) { + __extends(ContextualSignatureInstantiationTypeArgumentInferenceContext, _super); + function ContextualSignatureInstantiationTypeArgumentInferenceContext(resolver, context, signatureBeingInferred, contextualSignature, shouldFixContextualSignatureParameterTypes) { + _super.call(this, resolver, context, signatureBeingInferred); + this.contextualSignature = contextualSignature; + this.shouldFixContextualSignatureParameterTypes = shouldFixContextualSignatureParameterTypes; + } + ContextualSignatureInstantiationTypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + return false; + }; + + ContextualSignatureInstantiationTypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + var _this = this; + var relateTypesCallback = function (parameterTypeBeingInferred, contextualParameterType) { + if (_this.shouldFixContextualSignatureParameterTypes) { + contextualParameterType = _this.context.fixAllTypeParametersReferencedByType(contextualParameterType, _this.resolver, _this); + } + _this.resolver.relateTypeToTypeParametersWithNewEnclosingTypes(contextualParameterType, parameterTypeBeingInferred, _this, _this.context); + + return true; + }; + + this.signatureBeingInferred.forAllCorrespondingParameterTypesInThisAndOtherSignature(this.contextualSignature, relateTypesCallback); + + return this._finalizeInferredTypeArguments(); + }; + return ContextualSignatureInstantiationTypeArgumentInferenceContext; + })(TypeArgumentInferenceContext); + TypeScript.ContextualSignatureInstantiationTypeArgumentInferenceContext = ContextualSignatureInstantiationTypeArgumentInferenceContext; + + var PullContextualTypeContext = (function () { + function PullContextualTypeContext(contextualType, provisional, isInferentiallyTyping, typeArgumentInferenceContext) { + this.contextualType = contextualType; + this.provisional = provisional; + this.isInferentiallyTyping = isInferentiallyTyping; + this.typeArgumentInferenceContext = typeArgumentInferenceContext; + this.provisionallyTypedSymbols = []; + this.hasProvisionalErrors = false; + this.astSymbolMap = []; + } + PullContextualTypeContext.prototype.recordProvisionallyTypedSymbol = function (symbol) { + this.provisionallyTypedSymbols[this.provisionallyTypedSymbols.length] = symbol; + }; + + PullContextualTypeContext.prototype.invalidateProvisionallyTypedSymbols = function () { + for (var i = 0; i < this.provisionallyTypedSymbols.length; i++) { + this.provisionallyTypedSymbols[i].setUnresolved(); + } + }; + + PullContextualTypeContext.prototype.setSymbolForAST = function (ast, symbol) { + this.astSymbolMap[ast.syntaxID()] = symbol; + }; + + PullContextualTypeContext.prototype.getSymbolForAST = function (ast) { + return this.astSymbolMap[ast.syntaxID()]; + }; + return PullContextualTypeContext; + })(); + TypeScript.PullContextualTypeContext = PullContextualTypeContext; + + var PullTypeResolutionContext = (function () { + function PullTypeResolutionContext(resolver, inTypeCheck, fileName) { + if (typeof inTypeCheck === "undefined") { inTypeCheck = false; } + if (typeof fileName === "undefined") { fileName = null; } + this.resolver = resolver; + this.inTypeCheck = inTypeCheck; + this.fileName = fileName; + this.contextStack = []; + this.typeCheckedNodes = null; + this.enclosingTypeWalker1 = null; + this.enclosingTypeWalker2 = null; + this.inBaseTypeResolution = false; + if (inTypeCheck) { + TypeScript.Debug.assert(fileName, "A file name must be provided if you are typechecking"); + this.typeCheckedNodes = TypeScript.BitVector.getBitVector(false); + } + } + PullTypeResolutionContext.prototype.setTypeChecked = function (ast) { + if (!this.inProvisionalResolution()) { + this.typeCheckedNodes.setValueAt(ast.syntaxID(), true); + } + }; + + PullTypeResolutionContext.prototype.canTypeCheckAST = function (ast) { + return this.typeCheck() && !this.typeCheckedNodes.valueAt(ast.syntaxID()) && this.fileName === ast.fileName(); + }; + + PullTypeResolutionContext.prototype._pushAnyContextualType = function (type, provisional, isInferentiallyTyping, argContext) { + this.contextStack.push(new PullContextualTypeContext(type, provisional, isInferentiallyTyping, argContext)); + }; + + PullTypeResolutionContext.prototype.pushNewContextualType = function (type) { + this._pushAnyContextualType(type, this.inProvisionalResolution(), false, null); + }; + + PullTypeResolutionContext.prototype.propagateContextualType = function (type) { + this._pushAnyContextualType(type, this.inProvisionalResolution(), this.isInferentiallyTyping(), this.getCurrentTypeArgumentInferenceContext()); + }; + + PullTypeResolutionContext.prototype.pushInferentialType = function (type, typeArgumentInferenceContext) { + this._pushAnyContextualType(type, true, true, typeArgumentInferenceContext); + }; + + PullTypeResolutionContext.prototype.pushProvisionalType = function (type) { + this._pushAnyContextualType(type, true, false, null); + }; + + PullTypeResolutionContext.prototype.popAnyContextualType = function () { + var tc = this.contextStack.pop(); + + tc.invalidateProvisionallyTypedSymbols(); + + if (tc.hasProvisionalErrors && this.inProvisionalResolution()) { + this.contextStack[this.contextStack.length - 1].hasProvisionalErrors = true; + } + + return tc; + }; + + PullTypeResolutionContext.prototype.hasProvisionalErrors = function () { + return this.contextStack.length ? this.contextStack[this.contextStack.length - 1].hasProvisionalErrors : false; + }; + + PullTypeResolutionContext.prototype.getContextualType = function () { + var context = !this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]; + + if (context) { + var type = context.contextualType; + + if (!type) { + return null; + } + + return type; + } + + return null; + }; + + PullTypeResolutionContext.prototype.fixAllTypeParametersReferencedByType = function (type, resolver, argContext) { + var argContext = this.getCurrentTypeArgumentInferenceContext(); + if (type.wrapsSomeTypeParameter(argContext.candidateCache)) { + var typeParameterArgumentMap = []; + + for (var n in argContext.candidateCache) { + var typeParameter = argContext.candidateCache[n] && argContext.candidateCache[n].typeParameter; + if (typeParameter) { + var dummyMap = []; + dummyMap[typeParameter.pullSymbolID] = typeParameter; + if (type.wrapsSomeTypeParameter(dummyMap)) { + argContext.fixTypeParameter(typeParameter); + TypeScript.Debug.assert(argContext.candidateCache[n]._inferredTypeAfterFixing); + typeParameterArgumentMap[typeParameter.pullSymbolID] = argContext.candidateCache[n]._inferredTypeAfterFixing; + } + } + } + + return resolver.instantiateType(type, typeParameterArgumentMap); + } + + return type; + }; + + PullTypeResolutionContext.prototype.getCurrentTypeArgumentInferenceContext = function () { + return this.contextStack.length ? this.contextStack[this.contextStack.length - 1].typeArgumentInferenceContext : null; + }; + + PullTypeResolutionContext.prototype.isInferentiallyTyping = function () { + return this.contextStack.length > 0 && this.contextStack[this.contextStack.length - 1].isInferentiallyTyping; + }; + + PullTypeResolutionContext.prototype.inProvisionalResolution = function () { + return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); + }; + + PullTypeResolutionContext.prototype.isInBaseTypeResolution = function () { + return this.inBaseTypeResolution; + }; + + PullTypeResolutionContext.prototype.startBaseTypeResolution = function () { + var wasInBaseTypeResoltion = this.inBaseTypeResolution; + this.inBaseTypeResolution = true; + return wasInBaseTypeResoltion; + }; + + PullTypeResolutionContext.prototype.doneBaseTypeResolution = function (wasInBaseTypeResolution) { + this.inBaseTypeResolution = wasInBaseTypeResolution; + }; + + PullTypeResolutionContext.prototype.setTypeInContext = function (symbol, type) { + if (symbol.type && symbol.type.isError() && !type.isError()) { + return; + } + symbol.type = type; + + if (this.contextStack.length && this.inProvisionalResolution()) { + this.contextStack[this.contextStack.length - 1].recordProvisionallyTypedSymbol(symbol); + } + }; + + PullTypeResolutionContext.prototype.postDiagnostic = function (diagnostic) { + if (diagnostic) { + if (this.inProvisionalResolution()) { + (this.contextStack[this.contextStack.length - 1]).hasProvisionalErrors = true; + } else if (this.inTypeCheck && this.resolver) { + this.resolver.semanticInfoChain.addDiagnostic(diagnostic); + } + } + }; + + PullTypeResolutionContext.prototype.typeCheck = function () { + return this.inTypeCheck && !this.inProvisionalResolution(); + }; + + PullTypeResolutionContext.prototype.setSymbolForAST = function (ast, symbol) { + this.contextStack[this.contextStack.length - 1].setSymbolForAST(ast, symbol); + }; + + PullTypeResolutionContext.prototype.getSymbolForAST = function (ast) { + for (var i = this.contextStack.length - 1; i >= 0; i--) { + var typeContext = this.contextStack[i]; + if (!typeContext.provisional) { + break; + } + + var symbol = typeContext.getSymbolForAST(ast); + if (symbol) { + return symbol; + } + } + + return null; + }; + + PullTypeResolutionContext.prototype.startWalkingTypes = function (symbol1, symbol2) { + if (!this.enclosingTypeWalker1) { + this.enclosingTypeWalker1 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var stateWhenStartedWalkingTypes1 = this.enclosingTypeWalker1.startWalkingType(symbol1); + if (!this.enclosingTypeWalker2) { + this.enclosingTypeWalker2 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var stateWhenStartedWalkingTypes2 = this.enclosingTypeWalker2.startWalkingType(symbol2); + return { + stateWhenStartedWalkingTypes1: stateWhenStartedWalkingTypes1, + stateWhenStartedWalkingTypes2: stateWhenStartedWalkingTypes2 + }; + }; + + PullTypeResolutionContext.prototype.endWalkingTypes = function (statesWhenStartedWalkingTypes) { + this.enclosingTypeWalker1.endWalkingType(statesWhenStartedWalkingTypes.stateWhenStartedWalkingTypes1); + this.enclosingTypeWalker2.endWalkingType(statesWhenStartedWalkingTypes.stateWhenStartedWalkingTypes2); + }; + + PullTypeResolutionContext.prototype.setEnclosingTypeForSymbols = function (symbol1, symbol2) { + if (!this.enclosingTypeWalker1) { + this.enclosingTypeWalker1 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var enclosingTypeWalkerState1 = this.enclosingTypeWalker1.setEnclosingTypeForSymbol(symbol1); + if (!this.enclosingTypeWalker2) { + this.enclosingTypeWalker2 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var enclosingTypeWalkerState2 = this.enclosingTypeWalker2.setEnclosingTypeForSymbol(symbol2); + return { + enclosingTypeWalkerState1: enclosingTypeWalkerState1, + enclosingTypeWalkerState2: enclosingTypeWalkerState2 + }; + }; + + PullTypeResolutionContext.prototype.walkMemberTypes = function (memberName) { + this.enclosingTypeWalker1.walkMemberType(memberName, this.resolver); + this.enclosingTypeWalker2.walkMemberType(memberName, this.resolver); + }; + + PullTypeResolutionContext.prototype.postWalkMemberTypes = function () { + this.enclosingTypeWalker1.postWalkMemberType(); + this.enclosingTypeWalker2.postWalkMemberType(); + }; + + PullTypeResolutionContext.prototype.walkSignatures = function (kind, index, index2) { + this.enclosingTypeWalker1.walkSignature(kind, index); + this.enclosingTypeWalker2.walkSignature(kind, index2 == undefined ? index : index2); + }; + + PullTypeResolutionContext.prototype.postWalkSignatures = function () { + this.enclosingTypeWalker1.postWalkSignature(); + this.enclosingTypeWalker2.postWalkSignature(); + }; + + PullTypeResolutionContext.prototype.walkTypeParameterConstraints = function (index) { + this.enclosingTypeWalker1.walkTypeParameterConstraint(index); + this.enclosingTypeWalker2.walkTypeParameterConstraint(index); + }; + + PullTypeResolutionContext.prototype.postWalkTypeParameterConstraints = function () { + this.enclosingTypeWalker1.postWalkTypeParameterConstraint(); + this.enclosingTypeWalker2.postWalkTypeParameterConstraint(); + }; + + PullTypeResolutionContext.prototype.walkTypeArgument = function (index) { + this.enclosingTypeWalker1.walkTypeArgument(index); + this.enclosingTypeWalker2.walkTypeArgument(index); + }; + + PullTypeResolutionContext.prototype.postWalkTypeArgument = function () { + this.enclosingTypeWalker1.postWalkTypeArgument(); + this.enclosingTypeWalker2.postWalkTypeArgument(); + }; + + PullTypeResolutionContext.prototype.walkReturnTypes = function () { + this.enclosingTypeWalker1.walkReturnType(); + this.enclosingTypeWalker2.walkReturnType(); + }; + + PullTypeResolutionContext.prototype.postWalkReturnTypes = function () { + this.enclosingTypeWalker1.postWalkReturnType(); + this.enclosingTypeWalker2.postWalkReturnType(); + }; + + PullTypeResolutionContext.prototype.walkParameterTypes = function (iParam) { + this.enclosingTypeWalker1.walkParameterType(iParam); + this.enclosingTypeWalker2.walkParameterType(iParam); + }; + + PullTypeResolutionContext.prototype.postWalkParameterTypes = function () { + this.enclosingTypeWalker1.postWalkParameterType(); + this.enclosingTypeWalker2.postWalkParameterType(); + }; + + PullTypeResolutionContext.prototype.getBothKindOfIndexSignatures = function (includeAugmentedType1, includeAugmentedType2) { + var indexSigs1 = this.enclosingTypeWalker1.getBothKindOfIndexSignatures(this.resolver, this, includeAugmentedType1); + var indexSigs2 = this.enclosingTypeWalker2.getBothKindOfIndexSignatures(this.resolver, this, includeAugmentedType2); + return { indexSigs1: indexSigs1, indexSigs2: indexSigs2 }; + }; + + PullTypeResolutionContext.prototype.walkIndexSignatureReturnTypes = function (indexSigs, useStringIndexSignature1, useStringIndexSignature2, onlySignature) { + this.enclosingTypeWalker1.walkIndexSignatureReturnType(indexSigs.indexSigs1, useStringIndexSignature1, onlySignature); + this.enclosingTypeWalker2.walkIndexSignatureReturnType(indexSigs.indexSigs2, useStringIndexSignature2, onlySignature); + }; + + PullTypeResolutionContext.prototype.postWalkIndexSignatureReturnTypes = function (onlySignature) { + this.enclosingTypeWalker1.postWalkIndexSignatureReturnType(onlySignature); + this.enclosingTypeWalker2.postWalkIndexSignatureReturnType(onlySignature); + }; + + PullTypeResolutionContext.prototype.swapEnclosingTypeWalkers = function () { + var tempEnclosingWalker1 = this.enclosingTypeWalker1; + this.enclosingTypeWalker1 = this.enclosingTypeWalker2; + this.enclosingTypeWalker2 = tempEnclosingWalker1; + }; + + PullTypeResolutionContext.prototype.oneOfClassificationsIsInfinitelyExpanding = function () { + var generativeClassification1 = this.enclosingTypeWalker1.getGenerativeClassification(); + if (generativeClassification1 === 3 /* InfinitelyExpanding */) { + return true; + } + var generativeClassification2 = this.enclosingTypeWalker2.getGenerativeClassification(); + if (generativeClassification2 === 3 /* InfinitelyExpanding */) { + return true; + } + + return false; + }; + + PullTypeResolutionContext.prototype.resetEnclosingTypeWalkerStates = function () { + var enclosingTypeWalkerState1 = this.enclosingTypeWalker1 ? this.enclosingTypeWalker1.resetEnclosingTypeWalkerState() : null; + var enclosingTypeWalkerState2 = this.enclosingTypeWalker2 ? this.enclosingTypeWalker2.resetEnclosingTypeWalkerState() : null; + return { + enclosingTypeWalkerState1: enclosingTypeWalkerState1, + enclosingTypeWalkerState2: enclosingTypeWalkerState2 + }; + }; + + PullTypeResolutionContext.prototype.setEnclosingTypeWalkerStates = function (enclosingTypeWalkerStates) { + TypeScript.Debug.assert(this.enclosingTypeWalker1 || !enclosingTypeWalkerStates.enclosingTypeWalkerState1); + if (this.enclosingTypeWalker1) { + this.enclosingTypeWalker1.setEnclosingTypeWalkerState(enclosingTypeWalkerStates.enclosingTypeWalkerState1); + } + TypeScript.Debug.assert(this.enclosingTypeWalker2 || !enclosingTypeWalkerStates.enclosingTypeWalkerState2); + if (this.enclosingTypeWalker2) { + this.enclosingTypeWalker2.setEnclosingTypeWalkerState(enclosingTypeWalkerStates.enclosingTypeWalkerState2); + } + }; + return PullTypeResolutionContext; + })(); + TypeScript.PullTypeResolutionContext = PullTypeResolutionContext; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var OverloadApplicabilityStatus; + (function (OverloadApplicabilityStatus) { + OverloadApplicabilityStatus[OverloadApplicabilityStatus["NotAssignable"] = 0] = "NotAssignable"; + OverloadApplicabilityStatus[OverloadApplicabilityStatus["AssignableButWithProvisionalErrors"] = 1] = "AssignableButWithProvisionalErrors"; + OverloadApplicabilityStatus[OverloadApplicabilityStatus["AssignableWithNoProvisionalErrors"] = 2] = "AssignableWithNoProvisionalErrors"; + OverloadApplicabilityStatus[OverloadApplicabilityStatus["Subtype"] = 3] = "Subtype"; + })(OverloadApplicabilityStatus || (OverloadApplicabilityStatus = {})); + + var PullAdditionalCallResolutionData = (function () { + function PullAdditionalCallResolutionData() { + this.targetSymbol = null; + this.resolvedSignatures = null; + this.candidateSignature = null; + this.actualParametersContextTypeSymbols = null; + this.diagnosticsFromOverloadResolution = []; + } + return PullAdditionalCallResolutionData; + })(); + TypeScript.PullAdditionalCallResolutionData = PullAdditionalCallResolutionData; + + var PullAdditionalObjectLiteralResolutionData = (function () { + function PullAdditionalObjectLiteralResolutionData() { + this.membersContextTypeSymbols = null; + } + return PullAdditionalObjectLiteralResolutionData; + })(); + TypeScript.PullAdditionalObjectLiteralResolutionData = PullAdditionalObjectLiteralResolutionData; + + var MemberWithBaseOrigin = (function () { + function MemberWithBaseOrigin(memberSymbol, baseOrigin) { + this.memberSymbol = memberSymbol; + this.baseOrigin = baseOrigin; + } + return MemberWithBaseOrigin; + })(); + + var SignatureWithBaseOrigin = (function () { + function SignatureWithBaseOrigin(signature, baseOrigin) { + this.signature = signature; + this.baseOrigin = baseOrigin; + } + return SignatureWithBaseOrigin; + })(); + + var InheritedIndexSignatureInfo = (function () { + function InheritedIndexSignatureInfo() { + } + return InheritedIndexSignatureInfo; + })(); + + var CompilerReservedName; + (function (CompilerReservedName) { + CompilerReservedName[CompilerReservedName["_this"] = 1] = "_this"; + CompilerReservedName[CompilerReservedName["_super"] = 2] = "_super"; + CompilerReservedName[CompilerReservedName["arguments"] = 3] = "arguments"; + CompilerReservedName[CompilerReservedName["_i"] = 4] = "_i"; + CompilerReservedName[CompilerReservedName["require"] = 5] = "require"; + CompilerReservedName[CompilerReservedName["exports"] = 6] = "exports"; + })(CompilerReservedName || (CompilerReservedName = {})); + + function getCompilerReservedName(name) { + var nameText = name.valueText(); + return CompilerReservedName[nameText]; + } + + var PullTypeResolver = (function () { + function PullTypeResolver(compilationSettings, semanticInfoChain) { + this.compilationSettings = compilationSettings; + this.semanticInfoChain = semanticInfoChain; + this._cachedArrayInterfaceType = null; + this._cachedNumberInterfaceType = null; + this._cachedStringInterfaceType = null; + this._cachedBooleanInterfaceType = null; + this._cachedObjectInterfaceType = null; + this._cachedFunctionInterfaceType = null; + this._cachedIArgumentsInterfaceType = null; + this._cachedRegExpInterfaceType = null; + this._cachedAnyTypeArgs = null; + this.typeCheckCallBacks = []; + this.postTypeCheckWorkitems = []; + this._cachedFunctionArgumentsSymbol = null; + this.assignableCache = TypeScript.BitMatrix.getBitMatrix(true); + this.subtypeCache = TypeScript.BitMatrix.getBitMatrix(true); + this.identicalCache = TypeScript.BitMatrix.getBitMatrix(true); + this.inResolvingOtherDeclsWalker = new TypeScript.PullHelpers.OtherPullDeclsWalker(); + } + PullTypeResolver.prototype.cachedArrayInterfaceType = function () { + if (!this._cachedArrayInterfaceType) { + this._cachedArrayInterfaceType = this.getSymbolFromDeclPath("Array", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (!this._cachedArrayInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedArrayInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedArrayInterfaceType; + }; + + PullTypeResolver.prototype.getArrayNamedType = function () { + return this.cachedArrayInterfaceType(); + }; + + PullTypeResolver.prototype.cachedNumberInterfaceType = function () { + if (!this._cachedNumberInterfaceType) { + this._cachedNumberInterfaceType = this.getSymbolFromDeclPath("Number", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedNumberInterfaceType && !this._cachedNumberInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedNumberInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedNumberInterfaceType; + }; + + PullTypeResolver.prototype.cachedStringInterfaceType = function () { + if (!this._cachedStringInterfaceType) { + this._cachedStringInterfaceType = this.getSymbolFromDeclPath("String", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedStringInterfaceType && !this._cachedStringInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedStringInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedStringInterfaceType; + }; + + PullTypeResolver.prototype.cachedBooleanInterfaceType = function () { + if (!this._cachedBooleanInterfaceType) { + this._cachedBooleanInterfaceType = this.getSymbolFromDeclPath("Boolean", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedBooleanInterfaceType && !this._cachedBooleanInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedBooleanInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedBooleanInterfaceType; + }; + + PullTypeResolver.prototype.cachedObjectInterfaceType = function () { + if (!this._cachedObjectInterfaceType) { + this._cachedObjectInterfaceType = this.getSymbolFromDeclPath("Object", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (!this._cachedObjectInterfaceType) { + this._cachedObjectInterfaceType = this.semanticInfoChain.anyTypeSymbol; + } + + if (!this._cachedObjectInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedObjectInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedObjectInterfaceType; + }; + + PullTypeResolver.prototype.cachedFunctionInterfaceType = function () { + if (!this._cachedFunctionInterfaceType) { + this._cachedFunctionInterfaceType = this.getSymbolFromDeclPath("Function", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedFunctionInterfaceType && !this._cachedFunctionInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedFunctionInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedFunctionInterfaceType; + }; + + PullTypeResolver.prototype.cachedIArgumentsInterfaceType = function () { + if (!this._cachedIArgumentsInterfaceType) { + this._cachedIArgumentsInterfaceType = this.getSymbolFromDeclPath("IArguments", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedIArgumentsInterfaceType && !this._cachedIArgumentsInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedIArgumentsInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedIArgumentsInterfaceType; + }; + + PullTypeResolver.prototype.cachedRegExpInterfaceType = function () { + if (!this._cachedRegExpInterfaceType) { + this._cachedRegExpInterfaceType = this.getSymbolFromDeclPath("RegExp", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedRegExpInterfaceType && !this._cachedRegExpInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedRegExpInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedRegExpInterfaceType; + }; + + PullTypeResolver.prototype.cachedFunctionArgumentsSymbol = function () { + if (!this._cachedFunctionArgumentsSymbol) { + this._cachedFunctionArgumentsSymbol = new TypeScript.PullSymbol("arguments", 512 /* Variable */); + this._cachedFunctionArgumentsSymbol.type = this.cachedIArgumentsInterfaceType() || this.semanticInfoChain.anyTypeSymbol; + this._cachedFunctionArgumentsSymbol.setResolved(); + + var functionArgumentsDecl = new TypeScript.PullSynthesizedDecl("arguments", "arguments", 2048 /* Parameter */, 0 /* None */, null, this.semanticInfoChain); + functionArgumentsDecl.setSymbol(this._cachedFunctionArgumentsSymbol); + this._cachedFunctionArgumentsSymbol.addDeclaration(functionArgumentsDecl); + } + + return this._cachedFunctionArgumentsSymbol; + }; + + PullTypeResolver.prototype.getApparentType = function (type) { + if (type.isTypeParameter()) { + var baseConstraint = type.getBaseConstraint(this.semanticInfoChain); + if (baseConstraint === this.semanticInfoChain.anyTypeSymbol) { + return this.semanticInfoChain.emptyTypeSymbol; + } else { + type = baseConstraint; + } + } + if (type.isPrimitive()) { + if (type === this.semanticInfoChain.numberTypeSymbol) { + return this.cachedNumberInterfaceType(); + } + if (type === this.semanticInfoChain.booleanTypeSymbol) { + return this.cachedBooleanInterfaceType(); + } + if (type === this.semanticInfoChain.stringTypeSymbol) { + return this.cachedStringInterfaceType(); + } + return type; + } + if (type.isEnum()) { + return this.cachedNumberInterfaceType(); + } + return type; + }; + + PullTypeResolver.prototype.setTypeChecked = function (ast, context) { + context.setTypeChecked(ast); + }; + + PullTypeResolver.prototype.canTypeCheckAST = function (ast, context) { + return context.canTypeCheckAST(ast); + }; + + PullTypeResolver.prototype.setSymbolForAST = function (ast, symbol, context) { + if (context && context.inProvisionalResolution()) { + context.setSymbolForAST(ast, symbol); + } else { + this.semanticInfoChain.setSymbolForAST(ast, symbol); + } + }; + + PullTypeResolver.prototype.getSymbolForAST = function (ast, context) { + var symbol = this.semanticInfoChain.getSymbolForAST(ast); + + if (!symbol) { + if (context && context.inProvisionalResolution()) { + symbol = context.getSymbolForAST(ast); + } + } + + return symbol; + }; + + PullTypeResolver.prototype.getASTForDecl = function (decl) { + return this.semanticInfoChain.getASTForDecl(decl); + }; + + PullTypeResolver.prototype.getNewErrorTypeSymbol = function (name) { + if (typeof name === "undefined") { name = null; } + return new TypeScript.PullErrorTypeSymbol(this.semanticInfoChain.anyTypeSymbol, name); + }; + + PullTypeResolver.prototype.getEnclosingDecl = function (decl) { + var declPath = decl.getParentPath(); + + if (declPath.length > 1 && declPath[declPath.length - 1] === decl) { + return declPath[declPath.length - 2]; + } else { + return declPath[declPath.length - 1]; + } + }; + + PullTypeResolver.prototype.getExportedMemberSymbol = function (symbol, parent) { + if (!(symbol.kind & (65536 /* Method */ | 4096 /* Property */))) { + var isContainer = (parent.kind & (4 /* Container */ | 32 /* DynamicModule */)) !== 0; + var containerType = !isContainer ? parent.getAssociatedContainerType() : parent; + + if (isContainer && containerType) { + if (symbol.anyDeclHasFlag(1 /* Exported */)) { + return symbol; + } + + return null; + } + } + + return symbol; + }; + + PullTypeResolver.prototype._getNamedPropertySymbolOfAugmentedType = function (symbolName, parent) { + var memberSymbol = this.getNamedPropertySymbol(symbolName, 68147712 /* SomeValue */, parent); + if (memberSymbol) { + return memberSymbol; + } + + if (this.cachedFunctionInterfaceType() && parent.isFunctionType()) { + memberSymbol = this.cachedFunctionInterfaceType().findMember(symbolName, true); + if (memberSymbol) { + return memberSymbol; + } + } + + if (this.cachedObjectInterfaceType()) { + return this.cachedObjectInterfaceType().findMember(symbolName, true); + } + + return null; + }; + + PullTypeResolver.prototype.getNamedPropertySymbol = function (symbolName, declSearchKind, parent) { + var member = null; + + if (declSearchKind & 68147712 /* SomeValue */) { + member = parent.findMember(symbolName, true); + } else if (declSearchKind & 58728795 /* SomeType */) { + member = parent.findNestedType(symbolName); + } else if (declSearchKind & 164 /* SomeContainer */) { + member = parent.findNestedContainer(symbolName); + } + + if (member) { + return this.getExportedMemberSymbol(member, parent); + } + + var containerType = parent.getAssociatedContainerType(); + + if (containerType) { + if (containerType.isClass()) { + return null; + } + + parent = containerType; + + if (declSearchKind & 68147712 /* SomeValue */) { + member = parent.findMember(symbolName, true); + } else if (declSearchKind & 58728795 /* SomeType */) { + member = parent.findNestedType(symbolName); + } else if (declSearchKind & 164 /* SomeContainer */) { + member = parent.findNestedContainer(symbolName); + } + + if (member) { + return this.getExportedMemberSymbol(member, parent); + } + } + + if (parent.kind & 164 /* SomeContainer */) { + var typeDeclarations = parent.getDeclarations(); + var childDecls = null; + + for (var j = 0; j < typeDeclarations.length; j++) { + childDecls = typeDeclarations[j].searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + member = childDecls[0].getSymbol(); + + if (!member) { + member = childDecls[0].getSignatureSymbol(); + } + return this.getExportedMemberSymbol(member, parent); + } + + if ((declSearchKind & 58728795 /* SomeType */) !== 0 || (declSearchKind & 68147712 /* SomeValue */) !== 0) { + childDecls = typeDeclarations[j].searchChildDecls(symbolName, 128 /* TypeAlias */); + if (childDecls.length && childDecls[0].kind === 128 /* TypeAlias */) { + var aliasSymbol = this.getExportedMemberSymbol(childDecls[0].getSymbol(), parent); + if (aliasSymbol) { + if ((declSearchKind & 58728795 /* SomeType */) !== 0) { + var typeSymbol = aliasSymbol.getExportAssignedTypeSymbol(); + if (typeSymbol) { + return typeSymbol; + } + } else { + var valueSymbol = aliasSymbol.getExportAssignedValueSymbol(); + if (valueSymbol) { + aliasSymbol.setIsUsedAsValue(); + return valueSymbol; + } + } + + return aliasSymbol; + } + } + } + } + } + }; + + PullTypeResolver.prototype.getSymbolFromDeclPath = function (symbolName, declPath, declSearchKind) { + var _this = this; + var symbol = null; + + var decl = null; + var childDecls; + var declSymbol = null; + var declMembers; + var pathDeclKind; + var valDecl = null; + var kind; + var instanceSymbol = null; + var instanceType = null; + var childSymbol = null; + + var allowedContainerDeclKind = 4 /* Container */ | 32 /* DynamicModule */; + if (TypeScript.hasFlag(declSearchKind, 67108864 /* EnumMember */)) { + allowedContainerDeclKind |= 64 /* Enum */; + } + + var isAcceptableAlias = function (symbol) { + if (symbol.isAlias()) { + _this.resolveDeclaredSymbol(symbol); + if (TypeScript.hasFlag(declSearchKind, 164 /* SomeContainer */)) { + if (symbol.assignedContainer() || symbol.getExportAssignedContainerSymbol()) { + return true; + } + } else if (TypeScript.hasFlag(declSearchKind, 58728795 /* SomeType */)) { + var type = symbol.getExportAssignedTypeSymbol(); + if (type && type.kind !== 32 /* DynamicModule */) { + return true; + } + + var type = symbol.assignedType(); + if (type && type.kind !== 32 /* DynamicModule */) { + return true; + } + } else if (TypeScript.hasFlag(declSearchKind, 68147712 /* SomeValue */ & ~67108864 /* EnumMember */)) { + if (symbol.assignedType() && symbol.assignedType().isError()) { + return true; + } else if (symbol.assignedValue() || symbol.getExportAssignedValueSymbol()) { + return true; + } else { + var assignedType = symbol.assignedType(); + if (assignedType && assignedType.isContainer() && assignedType.getInstanceType()) { + return true; + } + + var decls = symbol.getDeclarations(); + var ast = decls[0].ast(); + return ast.moduleReference.kind() === 245 /* ExternalModuleReference */; + } + } + } + + return false; + }; + + var tryFindAlias = function (decl) { + var childDecls = decl.searchChildDecls(symbolName, 128 /* TypeAlias */); + + if (childDecls.length) { + var sym = childDecls[0].getSymbol(); + if (isAcceptableAlias(sym)) { + return sym; + } + } + return null; + }; + + for (var i = declPath.length - 1; i >= 0; i--) { + decl = declPath[i]; + pathDeclKind = decl.kind; + + if (decl.flags & 2097152 /* DeclaredInAWithBlock */) { + return this.semanticInfoChain.anyTypeSymbol; + } + + if (pathDeclKind & allowedContainerDeclKind) { + childDecls = decl.searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + return childDecls[0].getSymbol(); + } + + var alias = tryFindAlias(decl); + if (alias) { + return alias; + } + + if (declSearchKind & 68147712 /* SomeValue */) { + instanceSymbol = decl.getSymbol().getInstanceSymbol(); + + if (instanceSymbol) { + instanceType = instanceSymbol.type; + + childSymbol = this.getNamedPropertySymbol(symbolName, declSearchKind, instanceType); + + if (childSymbol && (childSymbol.kind & declSearchKind) && !childSymbol.anyDeclHasFlag(16 /* Static */)) { + return childSymbol; + } + } + + valDecl = decl.getValueDecl(); + + if (valDecl) { + decl = valDecl; + } + } + + declSymbol = decl.getSymbol().type; + + var childSymbol = this.getNamedPropertySymbol(symbolName, declSearchKind, declSymbol); + + if (childSymbol && (childSymbol.kind & declSearchKind) && !childSymbol.anyDeclHasFlag(16 /* Static */)) { + return childSymbol; + } + } else if ((declSearchKind & (58728795 /* SomeType */ | 164 /* SomeContainer */)) || !(pathDeclKind & 8 /* Class */)) { + var candidateSymbol = null; + + if (pathDeclKind === 131072 /* FunctionExpression */ && symbolName === decl.getFunctionExpressionName()) { + candidateSymbol = decl.getSymbol(); + } + + childDecls = decl.searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + if (decl.kind & 1032192 /* SomeFunction */) { + decl.ensureSymbolIsBound(); + } + return childDecls[0].getSymbol(); + } + + if (candidateSymbol) { + return candidateSymbol; + } + + var alias = tryFindAlias(decl); + if (alias) { + return alias; + } + } + } + + symbol = this.semanticInfoChain.findSymbol([symbolName], declSearchKind); + if (symbol) { + return symbol; + } + + if (!TypeScript.hasFlag(declSearchKind, 128 /* TypeAlias */)) { + symbol = this.semanticInfoChain.findSymbol([symbolName], 128 /* TypeAlias */); + if (symbol && isAcceptableAlias(symbol)) { + return symbol; + } + } + + return null; + }; + + PullTypeResolver.prototype.getVisibleDeclsFromDeclPath = function (declPath, declSearchKind) { + var result = []; + var decl = null; + var childDecls; + var pathDeclKind; + + for (var i = declPath.length - 1; i >= 0; i--) { + decl = declPath[i]; + pathDeclKind = decl.kind; + + var declKind = decl.kind; + + if (declKind !== 8 /* Class */ && declKind !== 16 /* Interface */) { + this.addFilteredDecls(decl.getChildDecls(), declSearchKind, result); + } + + switch (declKind) { + case 4 /* Container */: + case 32 /* DynamicModule */: + var otherDecls = this.semanticInfoChain.findDeclsFromPath(declPath.slice(0, i + 1), 164 /* SomeContainer */); + for (var j = 0, m = otherDecls.length; j < m; j++) { + var otherDecl = otherDecls[j]; + if (otherDecl === decl) { + continue; + } + + var otherDeclChildren = otherDecl.getChildDecls(); + for (var k = 0, s = otherDeclChildren.length; k < s; k++) { + var otherDeclChild = otherDeclChildren[k]; + if ((otherDeclChild.flags & 1 /* Exported */) && (otherDeclChild.kind & declSearchKind)) { + result.push(otherDeclChild); + } + } + } + + break; + + case 8 /* Class */: + case 16 /* Interface */: + var parameters = decl.getTypeParameters(); + if (parameters && parameters.length) { + this.addFilteredDecls(parameters, declSearchKind, result); + } + + break; + + case 131072 /* FunctionExpression */: + var functionExpressionName = decl.getFunctionExpressionName(); + if (functionExpressionName) { + result.push(decl); + } + + case 16384 /* Function */: + case 32768 /* ConstructorMethod */: + case 65536 /* Method */: + var parameters = decl.getTypeParameters(); + if (parameters && parameters.length) { + this.addFilteredDecls(parameters, declSearchKind, result); + } + + break; + } + } + + var topLevelDecls = this.semanticInfoChain.topLevelDecls(); + for (var i = 0, n = topLevelDecls.length; i < n; i++) { + var topLevelDecl = topLevelDecls[i]; + if (declPath.length > 0 && topLevelDecl.fileName() === declPath[0].fileName()) { + continue; + } + + if (!topLevelDecl.isExternalModule()) { + this.addFilteredDecls(topLevelDecl.getChildDecls(), declSearchKind, result); + } + } + + return result; + }; + + PullTypeResolver.prototype.addFilteredDecls = function (decls, declSearchKind, result) { + if (decls.length) { + for (var i = 0, n = decls.length; i < n; i++) { + var decl = decls[i]; + if (decl.kind & declSearchKind) { + result.push(decl); + } + } + } + }; + + PullTypeResolver.prototype.getVisibleDecls = function (enclosingDecl) { + var declPath = enclosingDecl.getParentPath(); + + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + + return this.getVisibleDeclsFromDeclPath(declPath, declSearchKind); + }; + + PullTypeResolver.prototype.getVisibleContextSymbols = function (enclosingDecl, context) { + var contextualTypeSymbol = context.getContextualType(); + if (!contextualTypeSymbol || this.isAnyOrEquivalent(contextualTypeSymbol)) { + return null; + } + + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + var members = contextualTypeSymbol.getAllMembers(declSearchKind, 2 /* externallyVisible */); + + for (var i = 0; i < members.length; i++) { + members[i].setUnresolved(); + } + + return members; + }; + + PullTypeResolver.prototype.getVisibleMembersFromExpression = function (expression, enclosingDecl, context) { + var lhs = this.resolveAST(expression, false, context); + + if (isTypesOnlyLocation(expression) && (lhs.kind === 8 /* Class */ || lhs.kind === 16 /* Interface */ || lhs.kind === 64 /* Enum */)) { + return null; + } + + var lhsType = lhs.type; + if (!lhsType) { + return null; + } + + this.resolveDeclaredSymbol(lhsType, context); + + if (lhsType.isContainer() && lhsType.isAlias()) { + lhsType = lhsType.getExportAssignedTypeSymbol(); + } + + if (this.isAnyOrEquivalent(lhsType)) { + return null; + } + + var memberVisibilty = 2 /* externallyVisible */; + var containerSymbol = lhsType; + if (containerSymbol.kind === 33554432 /* ConstructorType */) { + containerSymbol = containerSymbol.getConstructSignatures()[0].returnType; + } + + if (containerSymbol && containerSymbol.isClass()) { + var declPath = enclosingDecl.getParentPath(); + if (declPath && declPath.length) { + var declarations = containerSymbol.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + var declaration = declarations[i]; + if (TypeScript.ArrayUtilities.contains(declPath, declaration)) { + memberVisibilty = 1 /* internallyVisible */; + break; + } + } + } + } + + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + + var members = []; + + if (lhsType.isContainer()) { + var exportedAssignedContainerSymbol = lhsType.getExportAssignedContainerSymbol(); + if (exportedAssignedContainerSymbol) { + lhsType = exportedAssignedContainerSymbol; + } + } + + lhsType = this.getApparentType(lhsType); + + if (!lhsType.isResolved) { + var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, context); + + if (potentiallySpecializedType !== lhsType) { + if (!lhs.isType()) { + context.setTypeInContext(lhs, potentiallySpecializedType); + } + + lhsType = potentiallySpecializedType; + } + } + + members = lhsType.getAllMembers(declSearchKind, memberVisibilty); + + if (lhsType.isContainer()) { + var associatedInstance = lhsType.getInstanceSymbol(); + if (associatedInstance) { + var instanceType = associatedInstance.type; + this.resolveDeclaredSymbol(instanceType, context); + var instanceMembers = instanceType.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(instanceMembers); + } + + var exportedContainer = lhsType.getExportAssignedContainerSymbol(); + if (exportedContainer) { + var exportedContainerMembers = exportedContainer.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(exportedContainerMembers); + } + } else if (!lhsType.isConstructor() && !lhsType.isEnum()) { + var associatedContainerSymbol = lhsType.getAssociatedContainerType(); + if (associatedContainerSymbol) { + var containerType = associatedContainerSymbol.type; + this.resolveDeclaredSymbol(containerType, context); + var containerMembers = containerType.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(containerMembers); + } + } + + if (lhsType.isFunctionType() && this.cachedFunctionInterfaceType()) { + members = members.concat(this.cachedFunctionInterfaceType().getAllMembers(declSearchKind, 2 /* externallyVisible */)); + } + + return members; + }; + + PullTypeResolver.prototype.isAnyOrEquivalent = function (type) { + return (type === this.semanticInfoChain.anyTypeSymbol) || type.isError(); + }; + + PullTypeResolver.prototype.resolveExternalModuleReference = function (idText, currentFileName) { + var originalIdText = idText; + var symbol = null; + + if (TypeScript.isRelative(originalIdText)) { + var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); + symbol = this.semanticInfoChain.findExternalModule(path + idText); + } else { + idText = originalIdText; + + symbol = this.semanticInfoChain.findAmbientExternalModuleInGlobalContext(TypeScript.quoteStr(originalIdText)); + + if (!symbol) { + var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); + + while (symbol === null && path != "") { + symbol = this.semanticInfoChain.findExternalModule(path + idText); + if (symbol === null) { + if (path === '/') { + path = ''; + } else { + path = TypeScript.normalizePath(path + ".."); + path = path && path != '/' ? path + '/' : path; + } + } + } + } + } + + return symbol; + }; + + PullTypeResolver.prototype.resolveDeclaredSymbol = function (symbol, context) { + if (!symbol || symbol.isResolved || symbol.isTypeReference()) { + return symbol; + } + + if (!context) { + context = new TypeScript.PullTypeResolutionContext(this); + } + + return this.resolveDeclaredSymbolWorker(symbol, context); + }; + + PullTypeResolver.prototype.resolveDeclaredSymbolWorker = function (symbol, context) { + if (!symbol || symbol.isResolved) { + return symbol; + } + + if (symbol.inResolution) { + if (!symbol.type && !symbol.isType()) { + symbol.type = this.semanticInfoChain.anyTypeSymbol; + } + + return symbol; + } + + var decls = symbol.getDeclarations(); + + for (var i = 0; i < decls.length; i++) { + var decl = decls[i]; + + var ast = this.semanticInfoChain.getASTForDecl(decl); + + if (!ast || (ast.kind() === 139 /* GetAccessor */ && ast.parent.parent.kind() === 215 /* ObjectLiteralExpression */) || (ast.kind() === 140 /* SetAccessor */ && ast.parent.parent.kind() === 215 /* ObjectLiteralExpression */)) { + return symbol; + } + + if (ast.parent && ast.parent.kind() === 236 /* CatchClause */ && ast.parent.identifier === ast) { + return symbol; + } + + if (ast.parent && ast.parent.kind() === 219 /* SimpleArrowFunctionExpression */ && ast.parent.identifier === ast) { + return symbol; + } + + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(ast); + var resolvedSymbol; + if (enclosingModule) { + resolvedSymbol = this.resolveSingleModuleDeclaration(enclosingModule, ast, context); + } else if (ast.kind() === 120 /* SourceUnit */ && decl.kind === 32 /* DynamicModule */) { + resolvedSymbol = this.resolveModuleSymbol(decl.getSymbol(), context, null, null, ast); + } else { + TypeScript.Debug.assert(ast.kind() !== 11 /* IdentifierName */ && ast.kind() !== 212 /* MemberAccessExpression */); + resolvedSymbol = this.resolveAST(ast, false, context); + } + + if (decl.kind === 2048 /* Parameter */ && !symbol.isResolved && !symbol.type && resolvedSymbol && symbol.anyDeclHasFlag(8388608 /* PropertyParameter */ | 67108864 /* ConstructorParameter */)) { + symbol.type = resolvedSymbol.type; + symbol.setResolved(); + } + } + + if (!symbol.isResolved) { + TypeScript.Debug.assert(!symbol.inResolution); + + symbol.setResolved(); + } + + return symbol; + }; + + PullTypeResolver.prototype.resolveOtherDecl = function (otherDecl, context) { + var astForOtherDecl = this.getASTForDecl(otherDecl); + var moduleDecl = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(astForOtherDecl); + if (moduleDecl) { + this.resolveSingleModuleDeclaration(moduleDecl, astForOtherDecl, context); + } else { + this.resolveAST(astForOtherDecl, false, context); + } + }; + + PullTypeResolver.prototype.resolveOtherDeclarations = function (astName, context) { + var _this = this; + var resolvedDecl = this.semanticInfoChain.getDeclForAST(astName); + var symbol = resolvedDecl.getSymbol(); + + var allDecls = symbol.getDeclarations(); + this.inResolvingOtherDeclsWalker.walkOtherPullDecls(resolvedDecl, symbol.getDeclarations(), function (otherDecl) { + return _this.resolveOtherDecl(otherDecl, context); + }); + }; + + PullTypeResolver.prototype.resolveSourceUnit = function (sourceUnit, context) { + var enclosingDecl = this.getEnclosingDeclForAST(sourceUnit); + var moduleSymbol = enclosingDecl.getSymbol(); + this.ensureAllSymbolsAreBound(moduleSymbol); + + this.resolveFirstExportAssignmentStatement(sourceUnit.moduleElements, context); + this.resolveAST(sourceUnit.moduleElements, false, context); + + if (this.canTypeCheckAST(sourceUnit, context)) { + this.typeCheckSourceUnit(sourceUnit, context); + } + + return moduleSymbol; + }; + + PullTypeResolver.prototype.typeCheckSourceUnit = function (sourceUnit, context) { + var _this = this; + this.setTypeChecked(sourceUnit, context); + + this.resolveAST(sourceUnit.moduleElements, false, context); + + this.typeCheckCallBacks.push(function (context) { + return _this.verifyUniquenessOfImportNamesInSourceUnit(sourceUnit); + }); + }; + + PullTypeResolver.prototype.verifyUniquenessOfImportNamesInSourceUnit = function (sourceUnit) { + var _this = this; + var enclosingDecl = this.semanticInfoChain.getDeclForAST(sourceUnit); + + var doesImportNameExistInOtherFiles = function (name) { + var importSymbol = _this.semanticInfoChain.findTopLevelSymbol(name, 128 /* TypeAlias */, null); + return importSymbol && importSymbol.isAlias(); + }; + + this.checkUniquenessOfImportNames([enclosingDecl], doesImportNameExistInOtherFiles); + }; + + PullTypeResolver.prototype.resolveEnumDeclaration = function (ast, context) { + var containerDecl = this.semanticInfoChain.getDeclForAST(ast); + var containerSymbol = containerDecl.getSymbol(); + + if (containerSymbol.isResolved || containerSymbol.inResolution) { + return containerSymbol; + } + + containerSymbol.inResolution = true; + + var containerDecls = containerSymbol.getDeclarations(); + + for (var i = 0; i < containerDecls.length; i++) { + var childDecls = containerDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + + containerSymbol.setResolved(); + + this.resolveOtherDeclarations(ast, context); + + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckEnumDeclaration(ast, context); + } + + return containerSymbol; + }; + + PullTypeResolver.prototype.typeCheckEnumDeclaration = function (ast, context) { + var _this = this; + this.setTypeChecked(ast, context); + + this.resolveAST(ast.enumElements, false, context); + var containerDecl = this.semanticInfoChain.getDeclForAST(ast); + this.validateVariableDeclarationGroups(containerDecl, context); + + this.typeCheckCallBacks.push(function (context) { + return _this.checkInitializersInEnumDeclarations(containerDecl, context); + }); + + if (!TypeScript.ASTHelpers.enumIsElided(ast)) { + this.checkNameForCompilerGeneratedDeclarationCollision(ast, true, ast.identifier, context); + } + }; + + PullTypeResolver.prototype.postTypeCheckEnumDeclaration = function (ast, context) { + this.checkThisCaptureVariableCollides(ast, true, context); + }; + + PullTypeResolver.prototype.checkInitializersInEnumDeclarations = function (decl, context) { + var symbol = decl.getSymbol(); + + var declarations = symbol.getDeclarations(); + if (decl !== declarations[0]) { + return; + } + + var seenEnumDeclWithNoFirstMember = false; + for (var i = 0; i < declarations.length; ++i) { + var currentDecl = declarations[i]; + + var ast = currentDecl.ast(); + if (ast.enumElements.nonSeparatorCount() === 0) { + continue; + } + + var firstVariable = ast.enumElements.nonSeparatorAt(0); + if (!firstVariable.equalsValueClause) { + if (!seenEnumDeclWithNoFirstMember) { + seenEnumDeclWithNoFirstMember = true; + } else { + this.semanticInfoChain.addDiagnosticFromAST(firstVariable, TypeScript.DiagnosticCode.In_enums_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_the_first_enum_element); + } + } + } + }; + + PullTypeResolver.prototype.resolveModuleDeclaration = function (ast, context) { + var result; + + if (ast.stringLiteral) { + result = this.resolveSingleModuleDeclaration(ast, ast.stringLiteral, context); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(ast.name); + for (var i = 0, n = moduleNames.length; i < n; i++) { + result = this.resolveSingleModuleDeclaration(ast, moduleNames[i], context); + } + } + + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckModuleDeclaration(ast, context); + } + + return result; + }; + + PullTypeResolver.prototype.ensureAllSymbolsAreBound = function (containerSymbol) { + if (containerSymbol) { + var containerDecls = containerSymbol.getDeclarations(); + + for (var i = 0; i < containerDecls.length; i++) { + var childDecls = containerDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + } + }; + + PullTypeResolver.prototype.resolveModuleSymbol = function (containerSymbol, context, moduleDeclAST, moduleDeclNameAST, sourceUnitAST) { + if (containerSymbol.isResolved || containerSymbol.inResolution) { + return containerSymbol; + } + + containerSymbol.inResolution = true; + this.ensureAllSymbolsAreBound(containerSymbol); + + var instanceSymbol = containerSymbol.getInstanceSymbol(); + + if (instanceSymbol) { + this.resolveDeclaredSymbol(instanceSymbol, context); + } + + var isLastName = TypeScript.ASTHelpers.isLastNameOfModule(moduleDeclAST, moduleDeclNameAST); + if (isLastName) { + this.resolveFirstExportAssignmentStatement(moduleDeclAST.moduleElements, context); + } else if (sourceUnitAST) { + this.resolveFirstExportAssignmentStatement(sourceUnitAST.moduleElements, context); + } + + containerSymbol.setResolved(); + + if (moduleDeclNameAST) { + this.resolveOtherDeclarations(moduleDeclNameAST, context); + } + + return containerSymbol; + }; + + PullTypeResolver.prototype.resolveFirstExportAssignmentStatement = function (moduleElements, context) { + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var moduleElement = moduleElements.childAt(i); + if (moduleElement.kind() === 134 /* ExportAssignment */) { + this.resolveExportAssignmentStatement(moduleElement, context); + return; + } + } + }; + + PullTypeResolver.prototype.resolveSingleModuleDeclaration = function (ast, astName, context) { + var containerDecl = this.semanticInfoChain.getDeclForAST(astName); + var containerSymbol = containerDecl.getSymbol(); + + return this.resolveModuleSymbol(containerSymbol, context, ast, astName, null); + }; + + PullTypeResolver.prototype.typeCheckModuleDeclaration = function (ast, context) { + if (ast.stringLiteral) { + this.typeCheckSingleModuleDeclaration(ast, ast.stringLiteral, context); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(ast.name); + for (var i = 0, n = moduleNames.length; i < n; i++) { + this.typeCheckSingleModuleDeclaration(ast, moduleNames[i], context); + } + } + }; + + PullTypeResolver.prototype.typeCheckSingleModuleDeclaration = function (ast, astName, context) { + var _this = this; + this.setTypeChecked(ast, context); + + if (TypeScript.ASTHelpers.isLastNameOfModule(ast, astName)) { + this.resolveAST(ast.moduleElements, false, context); + } + + var containerDecl = this.semanticInfoChain.getDeclForAST(astName); + this.validateVariableDeclarationGroups(containerDecl, context); + + if (ast.stringLiteral) { + if (TypeScript.isRelative(ast.stringLiteral.valueText())) { + this.semanticInfoChain.addDiagnosticFromAST(ast.stringLiteral, TypeScript.DiagnosticCode.Ambient_external_module_declaration_cannot_specify_relative_module_name); + } + } + + if (!TypeScript.ASTHelpers.moduleIsElided(ast) && !ast.stringLiteral) { + this.checkNameForCompilerGeneratedDeclarationCollision(astName, true, astName, context); + } + + this.typeCheckCallBacks.push(function (context) { + return _this.verifyUniquenessOfImportNamesInModule(containerDecl); + }); + }; + + PullTypeResolver.prototype.verifyUniquenessOfImportNamesInModule = function (decl) { + var symbol = decl.getSymbol(); + if (!symbol) { + return; + } + + var decls = symbol.getDeclarations(); + + if (decls[0] !== decl) { + return; + } + + this.checkUniquenessOfImportNames(decls); + }; + + PullTypeResolver.prototype.checkUniquenessOfImportNames = function (decls, doesNameExistOutside) { + var _this = this; + var importDeclarationNames; + + for (var i = 0; i < decls.length; ++i) { + var childDecls = decls[i].getChildDecls(); + for (var j = 0; j < childDecls.length; ++j) { + var childDecl = childDecls[j]; + if (childDecl.kind === 128 /* TypeAlias */) { + importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); + importDeclarationNames[childDecl.name] = true; + } + } + } + + if (!importDeclarationNames && !doesNameExistOutside) { + return; + } + + for (var i = 0; i < decls.length; ++i) { + this.scanVariableDeclarationGroups(decls[i], function (firstDeclInGroup) { + var nameConflict = importDeclarationNames && importDeclarationNames[firstDeclInGroup.name]; + if (!nameConflict) { + nameConflict = doesNameExistOutside && doesNameExistOutside(firstDeclInGroup.name); + if (nameConflict) { + importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); + importDeclarationNames[firstDeclInGroup.name] = true; + } + } + + if (nameConflict) { + _this.semanticInfoChain.addDiagnosticFromAST(firstDeclInGroup.ast(), TypeScript.DiagnosticCode.Variable_declaration_cannot_have_the_same_name_as_an_import_declaration); + } + }); + } + }; + + PullTypeResolver.prototype.scanVariableDeclarationGroups = function (enclosingDecl, firstDeclHandler, subsequentDeclHandler) { + var declGroups = enclosingDecl.getVariableDeclGroups(); + + for (var i = 0; i < declGroups.length; i++) { + var firstSymbol = null; + var enclosingDeclForFirstSymbol = null; + + if (enclosingDecl.kind === 1 /* Script */ && declGroups[i].length) { + var name = declGroups[i][0].name; + var candidateSymbol = this.semanticInfoChain.findTopLevelSymbol(name, 512 /* Variable */, enclosingDecl); + if (candidateSymbol) { + if (!candidateSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */)) { + if (!candidateSymbol.isResolved) { + this.resolveDeclaredSymbol(candidateSymbol); + } + firstSymbol = candidateSymbol; + } + } + } + + for (var j = 0; j < declGroups[i].length; j++) { + var decl = declGroups[i][j]; + + var name = decl.name; + + var symbol = decl.getSymbol(); + + if (j === 0) { + firstDeclHandler(decl); + if (!subsequentDeclHandler) { + break; + } + + if (!firstSymbol || !firstSymbol.type) { + firstSymbol = symbol; + continue; + } + } + + subsequentDeclHandler(decl, firstSymbol); + } + } + }; + + PullTypeResolver.prototype.postTypeCheckModuleDeclaration = function (ast, context) { + this.checkThisCaptureVariableCollides(ast, true, context); + }; + + PullTypeResolver.prototype.isTypeRefWithoutTypeArgs = function (term) { + if (term.kind() === 11 /* IdentifierName */) { + return true; + } else if (term.kind() === 121 /* QualifiedName */) { + var binex = term; + + if (binex.right.kind() === 11 /* IdentifierName */) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.createInstantiatedType = function (type, typeArguments) { + if (!type.isGeneric()) { + return type; + } + + var typeParameters = type.getTypeArgumentsOrTypeParameters(); + + var typeParameterArgumentMap = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameterArgumentMap[typeParameters[i].pullSymbolID] = typeArguments[i] || new TypeScript.PullErrorTypeSymbol(this.semanticInfoChain.anyTypeSymbol, typeParameters[i].name); + } + + return TypeScript.PullInstantiatedTypeReferenceSymbol.create(this, type, typeParameterArgumentMap); + }; + + PullTypeResolver.prototype.resolveReferenceTypeDeclaration = function (classOrInterface, name, heritageClauses, context) { + var _this = this; + var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var enclosingDecl = this.getEnclosingDecl(typeDecl); + var typeDeclSymbol = typeDecl.getSymbol(); + var typeDeclIsClass = classOrInterface.kind() === 131 /* ClassDeclaration */; + var hasVisited = this.getSymbolForAST(classOrInterface, context) !== null; + + if ((typeDeclSymbol.isResolved && hasVisited) || (typeDeclSymbol.inResolution && !context.isInBaseTypeResolution())) { + return typeDeclSymbol; + } + + var wasResolving = typeDeclSymbol.inResolution; + typeDeclSymbol.startResolving(); + + var typeRefDecls = typeDeclSymbol.getDeclarations(); + + for (var i = 0; i < typeRefDecls.length; i++) { + var childDecls = typeRefDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + + if (!typeDeclSymbol.isResolved) { + var typeDeclTypeParameters = typeDeclSymbol.getTypeParameters(); + for (var i = 0; i < typeDeclTypeParameters.length; i++) { + this.resolveDeclaredSymbol(typeDeclTypeParameters[i], context); + } + } + + var wasInBaseTypeResolution = context.startBaseTypeResolution(); + + if (!typeDeclIsClass && !hasVisited) { + typeDeclSymbol.resetKnownBaseTypeCount(); + } + + var extendsClause = TypeScript.ASTHelpers.getExtendsHeritageClause(heritageClauses); + if (extendsClause) { + for (var i = typeDeclSymbol.getKnownBaseTypeCount(); i < extendsClause.typeNames.nonSeparatorCount(); i = typeDeclSymbol.getKnownBaseTypeCount()) { + typeDeclSymbol.incrementKnownBaseCount(); + var parentType = this.resolveTypeReference(extendsClause.typeNames.nonSeparatorAt(i), context); + + if (typeDeclSymbol.isValidBaseKind(parentType, true)) { + this.setSymbolForAST(extendsClause.typeNames.nonSeparatorAt(i), parentType, null); + + if (!typeDeclSymbol.hasBase(parentType) && !parentType.hasBase(typeDeclSymbol)) { + typeDeclSymbol.addExtendedType(parentType); + + var specializations = typeDeclSymbol.getKnownSpecializations(); + + for (var j = 0; j < specializations.length; j++) { + specializations[j].addExtendedType(parentType); + } + } + } else if (parentType && !this.getSymbolForAST(extendsClause.typeNames.nonSeparatorAt(i), context)) { + this.setSymbolForAST(extendsClause.typeNames.nonSeparatorAt(i), parentType, null); + } + } + } + + var implementsClause = TypeScript.ASTHelpers.getImplementsHeritageClause(heritageClauses); + if (implementsClause && typeDeclIsClass) { + var extendsCount = extendsClause ? extendsClause.typeNames.nonSeparatorCount() : 0; + for (var i = typeDeclSymbol.getKnownBaseTypeCount(); ((i - extendsCount) >= 0) && ((i - extendsCount) < implementsClause.typeNames.nonSeparatorCount()); i = typeDeclSymbol.getKnownBaseTypeCount()) { + typeDeclSymbol.incrementKnownBaseCount(); + var implementedTypeAST = implementsClause.typeNames.nonSeparatorAt(i - extendsCount); + var implementedType = this.resolveTypeReference(implementedTypeAST, context); + + if (typeDeclSymbol.isValidBaseKind(implementedType, false)) { + this.setSymbolForAST(implementsClause.typeNames.nonSeparatorAt(i - extendsCount), implementedType, null); + + if (!typeDeclSymbol.hasBase(implementedType) && !implementedType.hasBase(typeDeclSymbol)) { + typeDeclSymbol.addImplementedType(implementedType); + } + } else if (implementedType && !this.getSymbolForAST(implementsClause.typeNames.nonSeparatorAt(i - extendsCount), context)) { + this.setSymbolForAST(implementsClause.typeNames.nonSeparatorAt(i - extendsCount), implementedType, null); + } + } + } + + context.doneBaseTypeResolution(wasInBaseTypeResolution); + + if (wasInBaseTypeResolution) { + typeDeclSymbol.inResolution = false; + + this.typeCheckCallBacks.push(function (context) { + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + _this.resolveClassDeclaration(classOrInterface, context); + } else { + _this.resolveInterfaceDeclaration(classOrInterface, context); + } + }); + + return typeDeclSymbol; + } + + this.setSymbolForAST(name, typeDeclSymbol, context); + this.setSymbolForAST(classOrInterface, typeDeclSymbol, context); + + typeDeclSymbol.setResolved(); + + return typeDeclSymbol; + }; + + PullTypeResolver.prototype.resolveClassDeclaration = function (classDeclAST, context) { + var classDecl = this.semanticInfoChain.getDeclForAST(classDeclAST); + var classDeclSymbol = classDecl.getSymbol(); + + if (!classDeclSymbol.isResolved) { + this.resolveReferenceTypeDeclaration(classDeclAST, classDeclAST.identifier, classDeclAST.heritageClauses, context); + + var constructorMethod = classDeclSymbol.getConstructorMethod(); + var extendedTypes = classDeclSymbol.getExtendedTypes(); + var parentType = extendedTypes.length ? extendedTypes[0] : null; + + if (constructorMethod) { + if (parentType) { + var parentConstructorSymbol = parentType.getConstructorMethod(); + + if (parentConstructorSymbol) { + var parentConstructorTypeSymbol = parentConstructorSymbol.type; + var constructorTypeSymbol = constructorMethod.type; + if (!constructorTypeSymbol.hasBase(parentConstructorTypeSymbol)) { + constructorTypeSymbol.addExtendedType(parentConstructorTypeSymbol); + } + } + } + + if (!classDeclSymbol.isResolved) { + return classDeclSymbol; + } + } + + this.resolveOtherDeclarations(classDeclAST, context); + } + + if (this.canTypeCheckAST(classDeclAST, context)) { + this.typeCheckClassDeclaration(classDeclAST, context); + } + + return classDeclSymbol; + }; + + PullTypeResolver.prototype.typeCheckTypeParametersOfTypeDeclaration = function (classOrInterface, context) { + var _this = this; + var typeParametersList = classOrInterface.kind() == 131 /* ClassDeclaration */ ? classOrInterface.typeParameterList : classOrInterface.typeParameterList; + + if (typeParametersList) { + var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var typeDeclSymbol = typeDecl.getSymbol(); + + for (var i = 0; i < typeParametersList.typeParameters.nonSeparatorCount(); i++) { + var typeParameterAST = typeParametersList.typeParameters.nonSeparatorAt(i); + this.resolveTypeParameterDeclaration(typeParameterAST, context); + + var typeParameterDecl = this.semanticInfoChain.getDeclForAST(typeParameterAST); + var typeParameterSymbol = typeParameterDecl.getSymbol(); + + this.checkSymbolPrivacy(typeDeclSymbol, typeParameterSymbol, function (symbol) { + return _this.typeParameterOfTypeDeclarationPrivacyErrorReporter(classOrInterface, typeParameterAST, typeParameterSymbol, symbol, context); + }); + } + } + }; + + PullTypeResolver.prototype.typeCheckClassDeclaration = function (classDeclAST, context) { + this.setTypeChecked(classDeclAST, context); + + var classDecl = this.semanticInfoChain.getDeclForAST(classDeclAST); + var classDeclSymbol = classDecl.getSymbol(); + + this.checkNameForCompilerGeneratedDeclarationCollision(classDeclAST, true, classDeclAST.identifier, context); + this.resolveAST(classDeclAST.classElements, false, context); + + this.typeCheckTypeParametersOfTypeDeclaration(classDeclAST, context); + this.typeCheckBases(classDeclAST, classDeclAST.identifier, classDeclAST.heritageClauses, classDeclSymbol, this.getEnclosingDecl(classDecl), context); + + if (!classDeclSymbol.hasBaseTypeConflict()) { + this.typeCheckMembersAgainstIndexer(classDeclSymbol, classDecl, context); + } + + this.checkTypeForDuplicateIndexSignatures(classDeclSymbol); + }; + + PullTypeResolver.prototype.postTypeCheckClassDeclaration = function (classDeclAST, context) { + this.checkThisCaptureVariableCollides(classDeclAST, true, context); + }; + + PullTypeResolver.prototype.resolveTypeSymbolSignatures = function (typeSymbol, context) { + var callSignatures = typeSymbol.getCallSignatures(); + for (var i = 0; i < callSignatures.length; i++) { + this.resolveDeclaredSymbol(callSignatures[i], context); + } + + var constructSignatures = typeSymbol.getConstructSignatures(); + for (var i = 0; i < constructSignatures.length; i++) { + this.resolveDeclaredSymbol(constructSignatures[i], context); + } + + var indexSignatures = typeSymbol.getIndexSignatures(); + for (var i = 0; i < indexSignatures.length; i++) { + this.resolveDeclaredSymbol(indexSignatures[i], context); + } + }; + + PullTypeResolver.prototype.resolveInterfaceDeclaration = function (interfaceDeclAST, context) { + this.resolveReferenceTypeDeclaration(interfaceDeclAST, interfaceDeclAST.identifier, interfaceDeclAST.heritageClauses, context); + + var interfaceDecl = this.semanticInfoChain.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + this.resolveTypeSymbolSignatures(interfaceDeclSymbol, context); + + if (interfaceDeclSymbol.isResolved) { + this.resolveOtherDeclarations(interfaceDeclAST, context); + + if (this.canTypeCheckAST(interfaceDeclAST, context)) { + this.typeCheckInterfaceDeclaration(interfaceDeclAST, context); + } + } + + return interfaceDeclSymbol; + }; + + PullTypeResolver.prototype.typeCheckInterfaceDeclaration = function (interfaceDeclAST, context) { + this.setTypeChecked(interfaceDeclAST, context); + + var interfaceDecl = this.semanticInfoChain.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + this.resolveAST(interfaceDeclAST.body.typeMembers, false, context); + + this.typeCheckTypeParametersOfTypeDeclaration(interfaceDeclAST, context); + this.typeCheckBases(interfaceDeclAST, interfaceDeclAST.identifier, interfaceDeclAST.heritageClauses, interfaceDeclSymbol, this.getEnclosingDecl(interfaceDecl), context); + + if (!interfaceDeclSymbol.hasBaseTypeConflict()) { + this.typeCheckMembersAgainstIndexer(interfaceDeclSymbol, interfaceDecl, context); + } + + var allInterfaceDecls = interfaceDeclSymbol.getDeclarations(); + if (interfaceDecl === allInterfaceDecls[allInterfaceDecls.length - 1]) { + this.checkTypeForDuplicateIndexSignatures(interfaceDeclSymbol); + } + + if (!this.checkInterfaceDeclForIdenticalTypeParameters(interfaceDeclAST, context)) { + this.semanticInfoChain.addDiagnosticFromAST(interfaceDeclAST.identifier, TypeScript.DiagnosticCode.All_declarations_of_an_interface_must_have_identical_type_parameters); + } + }; + + PullTypeResolver.prototype.checkInterfaceDeclForIdenticalTypeParameters = function (interfaceDeclAST, context) { + var interfaceDecl = this.semanticInfoChain.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + if (!interfaceDeclSymbol.isGeneric()) { + return true; + } + + var firstInterfaceDecl = interfaceDeclSymbol.getDeclarations()[0]; + if (firstInterfaceDecl == interfaceDecl) { + return true; + } + + var typeParameters = interfaceDecl.getTypeParameters(); + var firstInterfaceDeclTypeParameters = firstInterfaceDecl.getTypeParameters(); + + if (typeParameters.length != firstInterfaceDeclTypeParameters.length) { + return false; + } + + for (var i = 0; i < typeParameters.length; i++) { + var typeParameter = typeParameters[i]; + var firstInterfaceDeclTypeParameter = firstInterfaceDeclTypeParameters[i]; + + if (typeParameter.name != firstInterfaceDeclTypeParameter.name) { + return false; + } + + var typeParameterSymbol = typeParameter.getSymbol(); + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter); + var firstInterfaceDeclTypeParameterAST = this.semanticInfoChain.getASTForDecl(firstInterfaceDeclTypeParameter); + + if (!!typeParameterAST.constraint != !!firstInterfaceDeclTypeParameterAST.constraint) { + return false; + } + + if (typeParameterAST.constraint) { + var typeParameterConstraint = this.resolveAST(typeParameterAST.constraint, false, context); + if (!this.typesAreIdenticalWithNewEnclosingTypes(typeParameterConstraint, typeParameterSymbol.getConstraint(), context)) { + return false; + } + } + } + + return true; + }; + + PullTypeResolver.prototype.checkTypeForDuplicateIndexSignatures = function (enclosingTypeSymbol) { + var indexSignatures = enclosingTypeSymbol.getOwnIndexSignatures(); + var firstStringIndexer = null; + var firstNumberIndexer = null; + for (var i = 0; i < indexSignatures.length; i++) { + var currentIndexer = indexSignatures[i]; + var currentParameterType = currentIndexer.parameters[0].type; + TypeScript.Debug.assert(currentParameterType); + if (currentParameterType === this.semanticInfoChain.stringTypeSymbol) { + if (firstStringIndexer) { + this.semanticInfoChain.addDiagnosticFromAST(currentIndexer.getDeclarations()[0].ast(), TypeScript.DiagnosticCode.Duplicate_string_index_signature, null, [this.semanticInfoChain.locationFromAST(firstStringIndexer.getDeclarations()[0].ast())]); + return; + } else { + firstStringIndexer = currentIndexer; + } + } else if (currentParameterType === this.semanticInfoChain.numberTypeSymbol) { + if (firstNumberIndexer) { + this.semanticInfoChain.addDiagnosticFromAST(currentIndexer.getDeclarations()[0].ast(), TypeScript.DiagnosticCode.Duplicate_number_index_signature, null, [this.semanticInfoChain.locationFromAST(firstNumberIndexer.getDeclarations()[0].ast())]); + return; + } else { + firstNumberIndexer = currentIndexer; + } + } + } + }; + + PullTypeResolver.prototype.filterSymbol = function (symbol, kind, enclosingDecl, context) { + if (symbol) { + if (symbol.kind & kind) { + return symbol; + } + + if (symbol.isAlias()) { + this.resolveDeclaredSymbol(symbol, context); + + var alias = symbol; + if (kind & 164 /* SomeContainer */) { + return alias.getExportAssignedContainerSymbol(); + } else if (kind & 58728795 /* SomeType */) { + return alias.getExportAssignedTypeSymbol(); + } else if (kind & 68147712 /* SomeValue */) { + return alias.getExportAssignedValueSymbol(); + } + } + } + return null; + }; + + PullTypeResolver.prototype.getMemberSymbolOfKind = function (symbolName, kind, pullTypeSymbol, enclosingDecl, context) { + var memberSymbol = this.getNamedPropertySymbol(symbolName, kind, pullTypeSymbol); + + return { + symbol: this.filterSymbol(memberSymbol, kind, enclosingDecl, context), + aliasSymbol: memberSymbol && memberSymbol.isAlias() ? memberSymbol : null + }; + }; + + PullTypeResolver.prototype.resolveIdentifierOfInternalModuleReference = function (importDecl, identifier, moduleSymbol, enclosingDecl, context) { + var rhsName = identifier.valueText(); + if (rhsName.length === 0) { + return null; + } + + var moduleTypeSymbol = moduleSymbol.type; + var memberSymbol = this.getMemberSymbolOfKind(rhsName, 164 /* SomeContainer */, moduleTypeSymbol, enclosingDecl, context); + var containerSymbol = memberSymbol.symbol; + var valueSymbol = null; + var typeSymbol = null; + var aliasSymbol = null; + + var acceptableAlias = true; + + if (containerSymbol) { + acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) !== 0; + aliasSymbol = memberSymbol.aliasSymbol; + } + + if (!acceptableAlias && containerSymbol && containerSymbol.kind === 128 /* TypeAlias */) { + this.resolveDeclaredSymbol(containerSymbol, context); + var aliasedAssignedValue = containerSymbol.getExportAssignedValueSymbol(); + var aliasedAssignedType = containerSymbol.getExportAssignedTypeSymbol(); + var aliasedAssignedContainer = containerSymbol.getExportAssignedContainerSymbol(); + + if (aliasedAssignedValue || aliasedAssignedType || aliasedAssignedContainer) { + aliasSymbol = containerSymbol; + valueSymbol = aliasedAssignedValue; + typeSymbol = aliasedAssignedType; + containerSymbol = aliasedAssignedContainer; + acceptableAlias = true; + } + } + + if (!acceptableAlias) { + this.semanticInfoChain.addDiagnosticFromAST(identifier, TypeScript.DiagnosticCode.Import_declaration_referencing_identifier_from_internal_module_can_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules); + return null; + } + + if (!valueSymbol) { + if (moduleTypeSymbol.getInstanceSymbol()) { + memberSymbol = this.getMemberSymbolOfKind(rhsName, 68147712 /* SomeValue */, moduleTypeSymbol.getInstanceSymbol().type, enclosingDecl, context); + valueSymbol = memberSymbol.symbol; + if (valueSymbol && memberSymbol.aliasSymbol) { + aliasSymbol = memberSymbol.aliasSymbol; + } + } + } + + if (!typeSymbol) { + memberSymbol = this.getMemberSymbolOfKind(rhsName, 58728795 /* SomeType */, moduleTypeSymbol, enclosingDecl, context); + typeSymbol = memberSymbol.symbol; + if (typeSymbol && memberSymbol.aliasSymbol) { + aliasSymbol = memberSymbol.aliasSymbol; + } + } + + if (!valueSymbol && !typeSymbol && !containerSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(identifier, TypeScript.DiagnosticCode.Could_not_find_symbol_0_in_module_1, [rhsName, moduleSymbol.toString()]); + return null; + } + + if (!typeSymbol && containerSymbol) { + typeSymbol = containerSymbol; + } + + return { + valueSymbol: valueSymbol, + typeSymbol: typeSymbol, + containerSymbol: containerSymbol, + aliasSymbol: aliasSymbol + }; + }; + + PullTypeResolver.prototype.resolveModuleReference = function (importDecl, moduleNameExpr, enclosingDecl, context, declPath) { + TypeScript.Debug.assert(moduleNameExpr.kind() === 121 /* QualifiedName */ || moduleNameExpr.kind() === 11 /* IdentifierName */ || moduleNameExpr.kind() === 14 /* StringLiteral */, "resolving module reference should always be either name or member reference"); + + var moduleSymbol = null; + var moduleName; + + if (moduleNameExpr.kind() === 121 /* QualifiedName */) { + var dottedNameAST = moduleNameExpr; + var moduleContainer = this.resolveModuleReference(importDecl, dottedNameAST.left, enclosingDecl, context, declPath); + if (moduleContainer) { + moduleName = dottedNameAST.right.valueText(); + + moduleSymbol = this.getMemberSymbolOfKind(moduleName, 4 /* Container */, moduleContainer.type, enclosingDecl, context).symbol; + if (!moduleSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(dottedNameAST.right, TypeScript.DiagnosticCode.Could_not_find_module_0_in_module_1, [moduleName, moduleContainer.toString()]); + } + } + } else { + var valueText = moduleNameExpr.kind() === 11 /* IdentifierName */ ? moduleNameExpr.valueText() : moduleNameExpr.valueText(); + var text = moduleNameExpr.kind() === 11 /* IdentifierName */ ? moduleNameExpr.text() : moduleNameExpr.text(); + + if (text.length > 0) { + var resolvedModuleNameSymbol = this.getSymbolFromDeclPath(valueText, declPath, 4 /* Container */); + moduleSymbol = this.filterSymbol(resolvedModuleNameSymbol, 4 /* Container */, enclosingDecl, context); + if (moduleSymbol) { + this.semanticInfoChain.setSymbolForAST(moduleNameExpr, moduleSymbol); + if (resolvedModuleNameSymbol.isAlias()) { + this.semanticInfoChain.setAliasSymbolForAST(moduleNameExpr, resolvedModuleNameSymbol); + var importDeclSymbol = importDecl.getSymbol(); + importDeclSymbol.addLinkedAliasSymbol(resolvedModuleNameSymbol); + } + } else { + this.semanticInfoChain.addDiagnosticFromAST(moduleNameExpr, TypeScript.DiagnosticCode.Unable_to_resolve_module_reference_0, [valueText]); + } + } + } + + return moduleSymbol; + }; + + PullTypeResolver.prototype.resolveInternalModuleReference = function (importStatementAST, context) { + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var enclosingDecl = this.getEnclosingDecl(importDecl); + + var moduleReference = importStatementAST.moduleReference; + + var aliasExpr = moduleReference.kind() === 245 /* ExternalModuleReference */ ? moduleReference.stringLiteral : moduleReference.moduleName; + + var declPath = enclosingDecl.getParentPath(); + var aliasedType = null; + var importDeclSymbol = importDecl.getSymbol(); + + if (aliasExpr.kind() === 11 /* IdentifierName */ || aliasExpr.kind() === 14 /* StringLiteral */) { + var moduleSymbol = this.resolveModuleReference(importDecl, aliasExpr, enclosingDecl, context, declPath); + if (moduleSymbol) { + aliasedType = moduleSymbol.type; + this.semanticInfoChain.setAliasSymbolForAST(moduleReference, this.semanticInfoChain.getAliasSymbolForAST(aliasExpr)); + if (aliasedType.anyDeclHasFlag(32768 /* InitializedModule */)) { + var moduleName = aliasExpr.kind() === 11 /* IdentifierName */ ? aliasExpr.valueText() : aliasExpr.valueText(); + var valueSymbol = this.getSymbolFromDeclPath(moduleName, declPath, 68147712 /* SomeValue */); + var instanceSymbol = aliasedType.getInstanceSymbol(); + + if (valueSymbol && (instanceSymbol != valueSymbol || valueSymbol.type === aliasedType)) { + var text = aliasExpr.kind() === 11 /* IdentifierName */ ? aliasExpr.text() : aliasExpr.text(); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(aliasExpr, TypeScript.DiagnosticCode.Internal_module_reference_0_in_import_declaration_does_not_reference_module_instance_for_1, [text, moduleSymbol.type.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + } else { + importDeclSymbol.setAssignedValueSymbol(valueSymbol); + } + } + } else { + aliasedType = this.getNewErrorTypeSymbol(); + } + } else if (aliasExpr.kind() === 121 /* QualifiedName */) { + var dottedNameAST = aliasExpr; + var moduleSymbol = this.resolveModuleReference(importDecl, dottedNameAST.left, enclosingDecl, context, declPath); + if (moduleSymbol) { + var identifierResolution = this.resolveIdentifierOfInternalModuleReference(importDecl, dottedNameAST.right, moduleSymbol, enclosingDecl, context); + if (identifierResolution) { + importDeclSymbol.setAssignedValueSymbol(identifierResolution.valueSymbol); + importDeclSymbol.setAssignedTypeSymbol(identifierResolution.typeSymbol); + importDeclSymbol.setAssignedContainerSymbol(identifierResolution.containerSymbol); + this.semanticInfoChain.setAliasSymbolForAST(moduleReference, identifierResolution.aliasSymbol); + return null; + } + } + } + + if (!aliasedType) { + importDeclSymbol.setAssignedTypeSymbol(this.getNewErrorTypeSymbol()); + } + + return aliasedType; + }; + + PullTypeResolver.prototype.resolveImportDeclaration = function (importStatementAST, context) { + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var enclosingDecl = this.getEnclosingDecl(importDecl); + var importDeclSymbol = importDecl.getSymbol(); + + var aliasedType = null; + + if (importDeclSymbol.isResolved) { + return importDeclSymbol; + } + + importDeclSymbol.startResolving(); + + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + var modPath = importStatementAST.moduleReference.stringLiteral.valueText(); + var declPath = enclosingDecl.getParentPath(); + + aliasedType = this.resolveExternalModuleReference(modPath, importDecl.fileName()); + + if (!aliasedType) { + var path = importStatementAST.moduleReference.stringLiteral.text(); + this.semanticInfoChain.addDiagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Unable_to_resolve_external_module_0, [path]); + aliasedType = this.getNewErrorTypeSymbol(); + } + } else { + aliasedType = this.resolveInternalModuleReference(importStatementAST, context); + } + + if (aliasedType) { + if (!aliasedType.isContainer()) { + this.semanticInfoChain.addDiagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Module_cannot_be_aliased_to_a_non_module_type); + if (!aliasedType.isError()) { + aliasedType = this.getNewErrorTypeSymbol(); + } + } + + if (aliasedType.isContainer()) { + importDeclSymbol.setAssignedContainerSymbol(aliasedType); + } + importDeclSymbol.setAssignedTypeSymbol(aliasedType); + + this.setSymbolForAST(importStatementAST.moduleReference, aliasedType, null); + } + + importDeclSymbol.setResolved(); + + this.resolveDeclaredSymbol(importDeclSymbol.assignedValue(), context); + this.resolveDeclaredSymbol(importDeclSymbol.assignedType(), context); + this.resolveDeclaredSymbol(importDeclSymbol.assignedContainer(), context); + + if (aliasedType && importDeclSymbol.anyDeclHasFlag(1 /* Exported */)) { + importDeclSymbol.setIsUsedInExportedAlias(); + + if (aliasedType.isContainer() && aliasedType.getExportAssignedValueSymbol()) { + importDeclSymbol.setIsUsedAsValue(); + } + } + + if (this.canTypeCheckAST(importStatementAST, context)) { + this.typeCheckImportDeclaration(importStatementAST, context); + } + + return importDeclSymbol; + }; + + PullTypeResolver.prototype.typeCheckImportDeclaration = function (importStatementAST, context) { + var _this = this; + this.setTypeChecked(importStatementAST, context); + + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var enclosingDecl = this.getEnclosingDecl(importDecl); + var importDeclSymbol = importDecl.getSymbol(); + + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + if (this.compilationSettings.noResolve()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Import_declaration_cannot_refer_to_external_module_reference_when_noResolve_option_is_set, null)); + } + + var modPath = importStatementAST.moduleReference.stringLiteral.valueText(); + if (enclosingDecl.kind === 32 /* DynamicModule */) { + var ast = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(this.getASTForDecl(enclosingDecl)); + if (ast && ast.kind() === 130 /* ModuleDeclaration */) { + if (TypeScript.isRelative(modPath)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name)); + } + } + } + } + + var checkPrivacy; + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + var containerSymbol = importDeclSymbol.getExportAssignedContainerSymbol(); + var container = containerSymbol ? containerSymbol.getContainer() : null; + if (container && container.kind === 32 /* DynamicModule */) { + checkPrivacy = true; + } + } else { + checkPrivacy = true; + } + + if (checkPrivacy) { + var typeSymbol = importDeclSymbol.getExportAssignedTypeSymbol(); + var containerSymbol = importDeclSymbol.getExportAssignedContainerSymbol(); + var valueSymbol = importDeclSymbol.getExportAssignedValueSymbol(); + + this.checkSymbolPrivacy(importDeclSymbol, containerSymbol, function (symbol) { + var messageCode = TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_container_that_is_or_is_using_inaccessible_module_1; + var messageArguments = [importDeclSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null), symbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null, false, false, true)]; + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(importStatementAST, messageCode, messageArguments)); + }); + + if (typeSymbol !== containerSymbol) { + this.checkSymbolPrivacy(importDeclSymbol, typeSymbol, function (symbol) { + var messageCode = symbol.isContainer() && !symbol.isEnum() ? TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_type_that_is_using_inaccessible_module_1 : TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_type_that_has_or_is_using_private_type_1; + + var messageArguments = [importDeclSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null), symbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null, false, false, true)]; + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(importStatementAST, messageCode, messageArguments)); + }); + } + + if (valueSymbol) { + this.checkSymbolPrivacy(importDeclSymbol, valueSymbol.type, function (symbol) { + var messageCode = symbol.isContainer() && !symbol.isEnum() ? TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_value_with_type_that_is_using_inaccessible_module_1 : TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_value_with_type_that_has_or_is_using_private_type_1; + var messageArguments = [importDeclSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null), symbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null, false, false, true)]; + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(importStatementAST, messageCode, messageArguments)); + }); + } + } + + this.checkNameForCompilerGeneratedDeclarationCollision(importStatementAST, true, importStatementAST.identifier, context); + }; + + PullTypeResolver.prototype.postTypeCheckImportDeclaration = function (importStatementAST, context) { + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var importSymbol = importDecl.getSymbol(); + + var isUsedAsValue = importSymbol.isUsedAsValue(); + var hasAssignedValue = importStatementAST.moduleReference.kind() !== 245 /* ExternalModuleReference */ && importSymbol.getExportAssignedValueSymbol() !== null; + + if (isUsedAsValue || hasAssignedValue) { + this.checkThisCaptureVariableCollides(importStatementAST, true, context); + } + }; + + PullTypeResolver.prototype.resolveExportAssignmentStatement = function (exportAssignmentAST, context) { + var id = exportAssignmentAST.identifier.valueText(); + if (id.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var valueSymbol = null; + var typeSymbol = null; + var containerSymbol = null; + + var enclosingDecl = this.getEnclosingDeclForAST(exportAssignmentAST); + var parentSymbol = enclosingDecl.getSymbol(); + + if (!parentSymbol.isType() && parentSymbol.isContainer()) { + this.semanticInfoChain.addDiagnosticFromAST(exportAssignmentAST, TypeScript.DiagnosticCode.Export_assignments_may_only_be_used_at_the_top_level_of_external_modules); + return this.semanticInfoChain.anyTypeSymbol; + } + + var declPath = enclosingDecl !== null ? [enclosingDecl] : []; + + containerSymbol = this.getSymbolFromDeclPath(id, declPath, 164 /* SomeContainer */); + + var acceptableAlias = true; + + if (containerSymbol) { + acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) !== 0; + } + + if (!acceptableAlias && containerSymbol && containerSymbol.kind === 128 /* TypeAlias */) { + this.resolveDeclaredSymbol(containerSymbol, context); + + var aliasSymbol = containerSymbol; + var aliasedAssignedValue = aliasSymbol.getExportAssignedValueSymbol(); + var aliasedAssignedType = aliasSymbol.getExportAssignedTypeSymbol(); + var aliasedAssignedContainer = aliasSymbol.getExportAssignedContainerSymbol(); + + if (aliasedAssignedValue || aliasedAssignedType || aliasedAssignedContainer) { + valueSymbol = aliasedAssignedValue; + typeSymbol = aliasedAssignedType; + containerSymbol = aliasedAssignedContainer; + aliasSymbol.setTypeUsedExternally(); + if (valueSymbol) { + aliasSymbol.setIsUsedAsValue(); + } + acceptableAlias = true; + } + } + + if (!acceptableAlias) { + this.semanticInfoChain.addDiagnosticFromAST(exportAssignmentAST, TypeScript.DiagnosticCode.Export_assignments_may_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules); + return this.semanticInfoChain.voidTypeSymbol; + } + + if (!valueSymbol) { + valueSymbol = this.getSymbolFromDeclPath(id, declPath, 68147712 /* SomeValue */); + } + if (!typeSymbol) { + typeSymbol = this.getSymbolFromDeclPath(id, declPath, 58728795 /* SomeType */); + } + + if (!valueSymbol && !typeSymbol && !containerSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(exportAssignmentAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [id])); + return this.semanticInfoChain.voidTypeSymbol; + } + + if (valueSymbol) { + parentSymbol.setExportAssignedValueSymbol(valueSymbol); + } + if (typeSymbol) { + parentSymbol.setExportAssignedTypeSymbol(typeSymbol); + } + if (containerSymbol) { + parentSymbol.setExportAssignedContainerSymbol(containerSymbol); + } + + this.resolveDeclaredSymbol(valueSymbol, context); + this.resolveDeclaredSymbol(typeSymbol, context); + this.resolveDeclaredSymbol(containerSymbol, context); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveAnyFunctionTypeSignature = function (funcDeclAST, typeParameters, parameterList, returnTypeAnnotation, context) { + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + TypeScript.Debug.assert(functionDecl); + + var funcDeclSymbol = functionDecl.getSymbol(); + + var signature = funcDeclSymbol.kind === 33554432 /* ConstructorType */ ? funcDeclSymbol.getConstructSignatures()[0] : funcDeclSymbol.getCallSignatures()[0]; + + if (returnTypeAnnotation) { + signature.returnType = this.resolveTypeReference(returnTypeAnnotation, context); + } + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + if (parameterList) { + for (var i = 0; i < parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveFunctionTypeSignatureParameter(parameterList.parameters.nonSeparatorAt(i), signature, functionDecl, context); + } + } + + funcDeclSymbol.setResolved(); + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.setTypeChecked(funcDeclAST, context); + this.typeCheckFunctionOverloads(funcDeclAST, context); + } + + return funcDeclSymbol; + }; + + PullTypeResolver.prototype.resolveFunctionTypeSignatureParameter = function (argDeclAST, signature, enclosingDecl, context) { + var paramDecl = this.semanticInfoChain.getDeclForAST(argDeclAST); + var paramSymbol = paramDecl.getSymbol(); + + if (argDeclAST.typeAnnotation) { + var typeRef = this.resolveTypeReference(TypeScript.ASTHelpers.getType(argDeclAST), context); + + if (paramSymbol.isVarArg && !typeRef.isArrayNamedTypeReference()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); + typeRef = this.getNewErrorTypeSymbol(); + } + + context.setTypeInContext(paramSymbol, typeRef); + } else { + if (paramSymbol.isVarArg) { + if (this.cachedArrayInterfaceType()) { + context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [this.semanticInfoChain.anyTypeSymbol])); + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_function_type_implicitly_has_an_any_type, [argDeclAST.identifier.text()])); + } + } + + if (TypeScript.hasFlag(paramDecl.flags, 128 /* Optional */) && argDeclAST.equalsValueClause && isTypesOnlyLocation(argDeclAST)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Default_arguments_are_only_allowed_in_implementation)); + } + + paramSymbol.setResolved(); + }; + + PullTypeResolver.prototype.resolveFunctionExpressionParameter = function (argDeclAST, id, typeExpr, equalsValueClause, contextParam, enclosingDecl, context) { + var paramDecl = this.semanticInfoChain.getDeclForAST(argDeclAST); + var paramSymbol = paramDecl.getSymbol(); + var contextualType = contextParam && contextParam.type; + var isImplicitAny = false; + + if (typeExpr) { + var typeRef = this.resolveTypeReference(typeExpr, context); + + if (paramSymbol.isVarArg && !typeRef.isArrayNamedTypeReference()) { + var diagnostic = context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); + typeRef = this.getNewErrorTypeSymbol(); + } + + contextualType = typeRef || contextualType; + } + if (contextualType) { + if (context.isInferentiallyTyping()) { + contextualType = context.fixAllTypeParametersReferencedByType(contextualType, this); + } + context.setTypeInContext(paramSymbol, contextualType); + } else if (paramSymbol.isVarArg) { + if (this.cachedArrayInterfaceType()) { + context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [this.semanticInfoChain.anyTypeSymbol])); + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + isImplicitAny = true; + } + + var canTypeCheckAST = this.canTypeCheckAST(argDeclAST, context); + if (equalsValueClause && (canTypeCheckAST || !contextualType)) { + if (contextualType) { + context.propagateContextualType(contextualType); + } + + var initExprSymbol = this.resolveAST(equalsValueClause, contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + } + + if (!initExprSymbol || !initExprSymbol.type) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Unable_to_resolve_type_of_0, [id.text()])); + + if (!contextualType) { + context.setTypeInContext(paramSymbol, this.getNewErrorTypeSymbol(paramSymbol.name)); + } + } else { + var initTypeSymbol = this.getInstanceTypeForAssignment(argDeclAST, initExprSymbol.type, context); + if (!contextualType) { + context.setTypeInContext(paramSymbol, initTypeSymbol.widenedType(this, equalsValueClause, context)); + isImplicitAny = initTypeSymbol !== paramSymbol.type; + } else { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(initTypeSymbol, contextualType, argDeclAST, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(argDeclAST); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [initTypeSymbol.toString(enclosingSymbol), contextualType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [initTypeSymbol.toString(enclosingSymbol), contextualType.toString(enclosingSymbol)])); + } + } + } + } + } + + if (!contextualType && !paramSymbol.isVarArg && !initTypeSymbol) { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + isImplicitAny = true; + } + + if (isImplicitAny && this.compilationSettings.noImplicitAny()) { + var functionExpressionName = paramDecl.getParentDecl().getFunctionExpressionName(); + if (functionExpressionName) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [id.text(), functionExpressionName])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_lambda_function_implicitly_has_an_any_type, [id.text()])); + } + } + + if (canTypeCheckAST) { + this.checkNameForCompilerGeneratedDeclarationCollision(argDeclAST, true, id, context); + } + + paramSymbol.setResolved(); + }; + + PullTypeResolver.prototype.checkNameForCompilerGeneratedDeclarationCollision = function (astWithName, isDeclaration, name, context) { + var compilerReservedName = getCompilerReservedName(name); + switch (compilerReservedName) { + case 1 /* _this */: + this.postTypeCheckWorkitems.push(astWithName); + return; + + case 2 /* _super */: + this.checkSuperCaptureVariableCollides(astWithName, isDeclaration, context); + return; + + case 3 /* arguments */: + this.checkArgumentsCollides(astWithName, context); + return; + + case 4 /* _i */: + this.checkIndexOfRestArgumentInitializationCollides(astWithName, isDeclaration, context); + return; + + case 5 /* require */: + case 6 /* exports */: + if (isDeclaration) { + this.checkExternalModuleRequireExportsCollides(astWithName, name, context); + } + return; + } + }; + + PullTypeResolver.prototype.hasRestParameterCodeGen = function (someFunctionDecl) { + var enclosingAST = this.getASTForDecl(someFunctionDecl); + var nodeType = enclosingAST.kind(); + + if (nodeType === 129 /* FunctionDeclaration */) { + var functionDeclaration = enclosingAST; + return !TypeScript.hasFlag(someFunctionDecl.kind === 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && functionDeclaration.block && TypeScript.lastParameterIsRest(functionDeclaration.callSignature.parameterList); + } else if (nodeType === 135 /* MemberFunctionDeclaration */) { + var memberFunction = enclosingAST; + return !TypeScript.hasFlag(someFunctionDecl.kind === 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && memberFunction.block && TypeScript.lastParameterIsRest(memberFunction.callSignature.parameterList); + } else if (nodeType === 137 /* ConstructorDeclaration */) { + var constructorDeclaration = enclosingAST; + return !TypeScript.hasFlag(someFunctionDecl.getParentDecl().flags, 8 /* Ambient */) && constructorDeclaration.block && TypeScript.lastParameterIsRest(constructorDeclaration.callSignature.parameterList); + } else if (nodeType === 218 /* ParenthesizedArrowFunctionExpression */) { + var arrowFunctionExpression = enclosingAST; + return TypeScript.lastParameterIsRest(arrowFunctionExpression.callSignature.parameterList); + } else if (nodeType === 222 /* FunctionExpression */) { + var functionExpression = enclosingAST; + return TypeScript.lastParameterIsRest(functionExpression.callSignature.parameterList); + } + + return false; + }; + + PullTypeResolver.prototype.checkArgumentsCollides = function (ast, context) { + if (ast.kind() === 242 /* Parameter */) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + if (TypeScript.hasFlag(enclosingDecl.kind, 1032192 /* SomeFunction */)) { + if (this.hasRestParameterCodeGen(enclosingDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters)); + } + } + } + }; + + PullTypeResolver.prototype.checkIndexOfRestArgumentInitializationCollides = function (ast, isDeclaration, context) { + if (!isDeclaration || ast.kind() === 242 /* Parameter */) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + var declPath = isDeclaration ? [enclosingDecl] : (enclosingDecl ? enclosingDecl.getParentPath() : []); + var resolvedSymbol = null; + var resolvedSymbolContainer; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + if (!isDeclaration) { + if (!resolvedSymbol) { + resolvedSymbol = this.resolveNameExpression(ast, context); + if (resolvedSymbol.isError()) { + return; + } + + resolvedSymbolContainer = resolvedSymbol.getContainer(); + } + + if (resolvedSymbolContainer && TypeScript.ArrayUtilities.contains(resolvedSymbolContainer.getDeclarations(), decl)) { + break; + } + } + + if (TypeScript.hasFlag(decl.kind, 1032192 /* SomeFunction */)) { + if (this.hasRestParameterCodeGen(decl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, isDeclaration ? TypeScript.DiagnosticCode.Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter : TypeScript.DiagnosticCode.Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter)); + } + } + } + } + }; + + PullTypeResolver.prototype.checkExternalModuleRequireExportsCollides = function (ast, name, context) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(name); + if (enclosingModule) { + enclosingDecl = this.getEnclosingDeclForAST(enclosingModule); + } + + if (enclosingDecl && enclosingDecl.kind === 32 /* DynamicModule */) { + var decl = this.semanticInfoChain.getDeclForAST(ast); + + if (!TypeScript.hasFlag(decl.flags, 8 /* Ambient */)) { + var nameText = name.valueText(); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module, [nameText, nameText])); + } + } + }; + + PullTypeResolver.prototype.resolveObjectTypeTypeReference = function (objectType, context) { + var interfaceDecl = this.semanticInfoChain.getDeclForAST(objectType); + TypeScript.Debug.assert(interfaceDecl); + + var interfaceSymbol = interfaceDecl.getSymbol(); + TypeScript.Debug.assert(interfaceSymbol); + + if (objectType.typeMembers) { + var memberDecl = null; + var memberSymbol = null; + var memberType = null; + var typeMembers = objectType.typeMembers; + + for (var i = 0; i < typeMembers.nonSeparatorCount(); i++) { + memberDecl = this.semanticInfoChain.getDeclForAST(typeMembers.nonSeparatorAt(i)); + memberSymbol = (memberDecl.kind & 7340032 /* SomeSignature */) ? memberDecl.getSignatureSymbol() : memberDecl.getSymbol(); + + this.resolveAST(typeMembers.nonSeparatorAt(i), false, context); + + memberType = memberSymbol.type; + + if ((memberType && memberType.isGeneric()) || (memberSymbol.isSignature() && memberSymbol.isGeneric())) { + interfaceSymbol.setHasGenericMember(); + } + } + } + + interfaceSymbol.setResolved(); + + if (this.canTypeCheckAST(objectType, context)) { + this.typeCheckObjectTypeTypeReference(objectType, context); + } + + return interfaceSymbol; + }; + + PullTypeResolver.prototype.typeCheckObjectTypeTypeReference = function (objectType, context) { + this.setTypeChecked(objectType, context); + var objectTypeDecl = this.semanticInfoChain.getDeclForAST(objectType); + var objectTypeSymbol = objectTypeDecl.getSymbol(); + + this.typeCheckMembersAgainstIndexer(objectTypeSymbol, objectTypeDecl, context); + this.checkTypeForDuplicateIndexSignatures(objectTypeSymbol); + }; + + PullTypeResolver.prototype.resolveTypeAnnotation = function (typeAnnotation, context) { + return this.resolveTypeReference(typeAnnotation.type, context); + }; + + PullTypeResolver.prototype.resolveTypeReference = function (typeRef, context) { + if (typeRef === null) { + return null; + } + + TypeScript.Debug.assert(typeRef.kind() !== 244 /* TypeAnnotation */); + + var aliasType = null; + var type = this.computeTypeReferenceSymbol(typeRef, context); + + if (type.kind === 4 /* Container */) { + var container = type; + var instanceSymbol = container.getInstanceSymbol(); + + if (instanceSymbol && (instanceSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */) || instanceSymbol.kind === 32768 /* ConstructorMethod */)) { + type = instanceSymbol.type.getAssociatedContainerType(); + } + } + + if (type && type.isAlias()) { + aliasType = type; + type = aliasType.getExportAssignedTypeSymbol(); + } + + if (type && !type.isGeneric()) { + if (aliasType) { + this.semanticInfoChain.setAliasSymbolForAST(typeRef, aliasType); + } + } + + if (type && !type.isError()) { + if ((type.kind & 58728795 /* SomeType */) === 0) { + if (type.kind & 164 /* SomeContainer */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeRef, TypeScript.DiagnosticCode.Type_reference_cannot_refer_to_container_0, [aliasType ? aliasType.toString() : type.toString()])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeRef, TypeScript.DiagnosticCode.Type_reference_must_refer_to_type)); + } + } + } + + if (this.canTypeCheckAST(typeRef, context)) { + this.setTypeChecked(typeRef, context); + } + + return type; + }; + + PullTypeResolver.prototype.getArrayType = function (elementType) { + var arraySymbol = elementType.getArrayType(); + + if (!arraySymbol) { + arraySymbol = this.createInstantiatedType(this.cachedArrayInterfaceType(), [elementType]); + + if (!arraySymbol) { + arraySymbol = this.semanticInfoChain.anyTypeSymbol; + } + + elementType.setArrayType(arraySymbol); + } + + return arraySymbol; + }; + + PullTypeResolver.prototype.computeTypeReferenceSymbol = function (term, context) { + switch (term.kind()) { + case 60 /* AnyKeyword */: + return this.semanticInfoChain.anyTypeSymbol; + case 61 /* BooleanKeyword */: + return this.semanticInfoChain.booleanTypeSymbol; + case 67 /* NumberKeyword */: + return this.semanticInfoChain.numberTypeSymbol; + case 69 /* StringKeyword */: + return this.semanticInfoChain.stringTypeSymbol; + case 41 /* VoidKeyword */: + return this.semanticInfoChain.voidTypeSymbol; + } + + var typeDeclSymbol = null; + + if (term.kind() === 11 /* IdentifierName */) { + typeDeclSymbol = this.resolveTypeNameExpression(term, context); + } else if (term.kind() === 123 /* FunctionType */) { + var functionType = term; + typeDeclSymbol = this.resolveAnyFunctionTypeSignature(functionType, functionType.typeParameterList, functionType.parameterList, functionType.type, context); + } else if (term.kind() === 125 /* ConstructorType */) { + var constructorType = term; + typeDeclSymbol = this.resolveAnyFunctionTypeSignature(constructorType, constructorType.typeParameterList, constructorType.parameterList, constructorType.type, context); + } else if (term.kind() === 122 /* ObjectType */) { + typeDeclSymbol = this.resolveObjectTypeTypeReference(term, context); + } else if (term.kind() === 126 /* GenericType */) { + typeDeclSymbol = this.resolveGenericTypeReference(term, context); + } else if (term.kind() === 121 /* QualifiedName */) { + typeDeclSymbol = this.resolveQualifiedName(term, context); + } else if (term.kind() === 14 /* StringLiteral */) { + var stringConstantAST = term; + var enclosingDecl = this.getEnclosingDeclForAST(term); + typeDeclSymbol = new TypeScript.PullStringConstantTypeSymbol(stringConstantAST.text()); + var decl = new TypeScript.PullSynthesizedDecl(stringConstantAST.text(), stringConstantAST.text(), typeDeclSymbol.kind, null, enclosingDecl, enclosingDecl.semanticInfoChain); + typeDeclSymbol.addDeclaration(decl); + } else if (term.kind() === 127 /* TypeQuery */) { + var typeQuery = term; + + var typeQueryTerm = typeQuery.name; + + var valueSymbol = this.resolveAST(typeQueryTerm, false, context); + + if (valueSymbol && valueSymbol.isAlias()) { + if (valueSymbol.assignedValue()) { + valueSymbol = valueSymbol.assignedValue(); + } else { + var containerSymbol = valueSymbol.getExportAssignedContainerSymbol(); + valueSymbol = (containerSymbol && containerSymbol.isContainer() && !containerSymbol.isEnum()) ? containerSymbol.getInstanceSymbol() : null; + } + } + + if (valueSymbol) { + typeDeclSymbol = valueSymbol.type.widenedType(this, typeQueryTerm, context); + } else { + typeDeclSymbol = this.getNewErrorTypeSymbol(); + } + } else if (term.kind() === 124 /* ArrayType */) { + var arrayType = term; + var underlying = this.resolveTypeReference(arrayType.type, context); + typeDeclSymbol = this.getArrayType(underlying); + } else { + throw TypeScript.Errors.invalidOperation("unknown type"); + } + + if (!typeDeclSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(term, TypeScript.DiagnosticCode.Unable_to_resolve_type)); + return this.getNewErrorTypeSymbol(); + } + + if (typeDeclSymbol.isError()) { + return typeDeclSymbol; + } + + if (this.genericTypeIsUsedWithoutRequiredTypeArguments(typeDeclSymbol, term, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(term, TypeScript.DiagnosticCode.Generic_type_references_must_include_all_type_arguments)); + typeDeclSymbol = this.instantiateTypeToAny(typeDeclSymbol, context); + } + + return typeDeclSymbol; + }; + + PullTypeResolver.prototype.genericTypeIsUsedWithoutRequiredTypeArguments = function (typeSymbol, term, context) { + if (!typeSymbol) { + return false; + } + + if (typeSymbol.isAlias()) { + return this.genericTypeIsUsedWithoutRequiredTypeArguments(typeSymbol.getExportAssignedTypeSymbol(), term, context); + } + + return typeSymbol.isNamedTypeSymbol() && typeSymbol.isGeneric() && !typeSymbol.isTypeParameter() && (typeSymbol.isResolved || typeSymbol.inResolution) && !typeSymbol.getIsSpecialized() && typeSymbol.getTypeParameters().length && typeSymbol.getTypeArguments() === null && this.isTypeRefWithoutTypeArgs(term); + }; + + PullTypeResolver.prototype.resolveMemberVariableDeclaration = function (varDecl, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.ASTHelpers.getType(varDecl.variableDeclarator), varDecl.variableDeclarator.equalsValueClause, context); + }; + + PullTypeResolver.prototype.resolvePropertySignature = function (varDecl, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), null, context); + }; + + PullTypeResolver.prototype.resolveVariableDeclarator = function (varDecl, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.equalsValueClause, context); + }; + + PullTypeResolver.prototype.resolveParameterList = function (list, context) { + return this.resolveSeparatedList(list.parameters, context); + }; + + PullTypeResolver.prototype.resolveParameter = function (parameter, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.ASTHelpers.getType(parameter), parameter.equalsValueClause, context); + }; + + PullTypeResolver.prototype.getEnumTypeSymbol = function (enumElement, context) { + var enumDeclaration = enumElement.parent.parent; + var decl = this.semanticInfoChain.getDeclForAST(enumDeclaration); + var symbol = decl.getSymbol(); + this.resolveDeclaredSymbol(symbol, context); + + return symbol; + }; + + PullTypeResolver.prototype.resolveEnumElement = function (enumElement, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(enumElement, TypeScript.sentinelEmptyArray, enumElement.propertyName, null, enumElement.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckEnumElement = function (enumElement, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(enumElement, TypeScript.sentinelEmptyArray, enumElement.propertyName, null, enumElement.equalsValueClause, context); + }; + + PullTypeResolver.prototype.resolveEqualsValueClause = function (clause, isContextuallyTyped, context) { + if (this.canTypeCheckAST(clause, context)) { + this.setTypeChecked(clause, context); + } + + return this.resolveAST(clause.value, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveVariableDeclaratorOrParameterOrEnumElement = function (varDeclOrParameter, modifiers, name, typeExpr, init, context) { + var hasTypeExpr = typeExpr !== null || varDeclOrParameter.kind() === 243 /* EnumElement */; + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + + if (enclosingDecl && decl.kind === 2048 /* Parameter */) { + enclosingDecl.ensureSymbolIsBound(); + } + + var declSymbol = decl.getSymbol(); + var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; + + if (declSymbol.isResolved) { + var declType = declSymbol.type; + var valDecl = decl.getValueDecl(); + + if (valDecl) { + var valSymbol = valDecl.getSymbol(); + + if (valSymbol && !valSymbol.isResolved) { + valSymbol.type = declType; + valSymbol.setResolved(); + } + } + } else { + if (declSymbol.inResolution) { + declSymbol.type = this.semanticInfoChain.anyTypeSymbol; + declSymbol.setResolved(); + return declSymbol; + } + + if (!declSymbol.type || !declSymbol.type.isError()) { + declSymbol.startResolving(); + + var typeExprSymbol = this.resolveAndTypeCheckVariableDeclarationTypeExpr(varDeclOrParameter, name, typeExpr, context); + + if (!hasTypeExpr) { + this.resolveAndTypeCheckVariableDeclaratorOrParameterInitExpr(varDeclOrParameter, name, typeExpr, init, context, typeExprSymbol); + } + + if (!(hasTypeExpr || init)) { + var defaultType = this.semanticInfoChain.anyTypeSymbol; + + if (declSymbol.isVarArg && this.cachedArrayInterfaceType()) { + defaultType = this.createInstantiatedType(this.cachedArrayInterfaceType(), [defaultType]); + } + + context.setTypeInContext(declSymbol, defaultType); + + if (declParameterSymbol) { + declParameterSymbol.type = defaultType; + } + } + declSymbol.setResolved(); + + if (declParameterSymbol) { + declParameterSymbol.setResolved(); + } + } + } + + if (this.canTypeCheckAST(varDeclOrParameter, context)) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDeclOrParameter, modifiers, name, typeExpr, init, context); + } + + return declSymbol; + }; + + PullTypeResolver.prototype.resolveAndTypeCheckVariableDeclarationTypeExpr = function (varDeclOrParameter, name, typeExpr, context) { + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + var declSymbol = decl.getSymbol(); + var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; + + if (varDeclOrParameter.kind() === 243 /* EnumElement */) { + var result = this.getEnumTypeSymbol(varDeclOrParameter, context); + declSymbol.type = result; + return result; + } + + if (!typeExpr) { + return null; + } + + var wrapperDecl = this.getEnclosingDecl(decl); + wrapperDecl = wrapperDecl || enclosingDecl; + + var typeExprSymbol = this.resolveTypeReference(typeExpr, context); + + if (!typeExprSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Unable_to_resolve_type_of_0, [name.text()])); + declSymbol.type = this.getNewErrorTypeSymbol(); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } else if (typeExprSymbol.isError()) { + context.setTypeInContext(declSymbol, typeExprSymbol); + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, typeExprSymbol); + } + } else { + if (typeExprSymbol === this.semanticInfoChain.anyTypeSymbol) { + decl.setFlag(16777216 /* IsAnnotatedWithAny */); + } + + if (typeExprSymbol.isContainer()) { + var exportedTypeSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + + if (exportedTypeSymbol) { + typeExprSymbol = exportedTypeSymbol; + } else { + typeExprSymbol = typeExprSymbol.type; + + if (typeExprSymbol.isAlias()) { + typeExprSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + } + + if (typeExprSymbol && typeExprSymbol.isContainer() && !typeExprSymbol.isEnum()) { + var instanceSymbol = typeExprSymbol.getInstanceSymbol(); + + if (!instanceSymbol || !TypeScript.PullHelpers.symbolIsEnum(instanceSymbol)) { + typeExprSymbol = this.getNewErrorTypeSymbol(); + } else { + typeExprSymbol = instanceSymbol.type; + } + } + } + } else if (declSymbol.isVarArg && !(typeExprSymbol.isArrayNamedTypeReference() || typeExprSymbol === this.cachedArrayInterfaceType())) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); + typeExprSymbol = this.getNewErrorTypeSymbol(); + } + + context.setTypeInContext(declSymbol, typeExprSymbol); + + if (declParameterSymbol) { + declParameterSymbol.type = typeExprSymbol; + } + + if (typeExprSymbol.kind === 16777216 /* FunctionType */ && !typeExprSymbol.getFunctionSymbol()) { + typeExprSymbol.setFunctionSymbol(declSymbol); + } + } + + return typeExprSymbol; + }; + + PullTypeResolver.prototype.resolveAndTypeCheckVariableDeclaratorOrParameterInitExpr = function (varDeclOrParameter, name, typeExpr, init, context, typeExprSymbol) { + if (!init) { + return null; + } + + var hasTypeExpr = typeExpr !== null || varDeclOrParameter.kind() === 243 /* EnumElement */; + if (typeExprSymbol) { + context.pushNewContextualType(typeExprSymbol); + } + + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + var declSymbol = decl.getSymbol(); + var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; + + var wrapperDecl = this.getEnclosingDecl(decl); + wrapperDecl = wrapperDecl || enclosingDecl; + + var initExprSymbol = this.resolveAST(init, typeExprSymbol !== null, context); + + if (typeExprSymbol) { + context.popAnyContextualType(); + } + + if (!initExprSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Unable_to_resolve_type_of_0, [name.text()])); + + if (!hasTypeExpr) { + context.setTypeInContext(declSymbol, this.getNewErrorTypeSymbol()); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } + } else { + var initTypeSymbol = initExprSymbol.type; + + if (!hasTypeExpr) { + var widenedInitTypeSymbol = initTypeSymbol.widenedType(this, init.value, context); + context.setTypeInContext(declSymbol, widenedInitTypeSymbol); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, widenedInitTypeSymbol); + } + + if (this.compilationSettings.noImplicitAny()) { + if ((widenedInitTypeSymbol !== initTypeSymbol) && (widenedInitTypeSymbol === this.semanticInfoChain.anyTypeSymbol)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Variable_0_implicitly_has_an_any_type, [name.text()])); + } + } + + return widenedInitTypeSymbol; + } + } + + return initTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckPropertySignature = function (varDecl, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckMemberVariableDeclaration = function (varDecl, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.variableDeclarator.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckVariableDeclarator = function (varDecl, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckParameter = function (parameter, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.ASTHelpers.getType(parameter), parameter.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckVariableDeclaratorOrParameterOrEnumElement = function (varDeclOrParameter, modifiers, name, typeExpr, init, context) { + var _this = this; + this.setTypeChecked(varDeclOrParameter, context); + + var hasTypeExpr = typeExpr !== null || varDeclOrParameter.kind() === 243 /* EnumElement */; + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + var declSymbol = decl.getSymbol(); + + var typeExprSymbol = this.resolveAndTypeCheckVariableDeclarationTypeExpr(varDeclOrParameter, name, typeExpr, context); + + var initTypeSymbol = this.resolveAndTypeCheckVariableDeclaratorOrParameterInitExpr(varDeclOrParameter, name, typeExpr, init, context, typeExprSymbol); + + if (hasTypeExpr || init) { + if (typeExprSymbol && typeExprSymbol.isAlias()) { + typeExprSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + } + + if (typeExprSymbol && typeExprSymbol.kind === 32 /* DynamicModule */) { + var exportedTypeSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + + if (exportedTypeSymbol) { + typeExprSymbol = exportedTypeSymbol; + } else { + var instanceTypeSymbol = typeExprSymbol.getInstanceType(); + + if (!instanceTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Tried_to_set_variable_type_to_uninitialized_module_type_0, [typeExprSymbol.toString()])); + typeExprSymbol = null; + } else { + typeExprSymbol = instanceTypeSymbol; + } + } + } + + initTypeSymbol = this.getInstanceTypeForAssignment(varDeclOrParameter, initTypeSymbol, context); + + if (initTypeSymbol && typeExprSymbol) { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(initTypeSymbol, typeExprSymbol, varDeclOrParameter, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(varDeclOrParameter); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [initTypeSymbol.toString(enclosingSymbol), typeExprSymbol.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [initTypeSymbol.toString(enclosingSymbol), typeExprSymbol.toString(enclosingSymbol)])); + } + } + } + } else if (varDeclOrParameter.kind() !== 243 /* EnumElement */ && this.compilationSettings.noImplicitAny() && !this.isForInVariableDeclarator(varDeclOrParameter)) { + var wrapperDecl = this.getEnclosingDecl(decl); + wrapperDecl = wrapperDecl || enclosingDecl; + + var needReportError = function (containerDecl, selfDecl) { + if (!TypeScript.hasFlag(containerDecl.flags, 8 /* Ambient */)) { + return true; + } + + return selfDecl && !TypeScript.hasFlag(selfDecl.flags, 2 /* Private */); + }; + + if ((wrapperDecl.kind === 16384 /* Function */ || wrapperDecl.kind === 32768 /* ConstructorMethod */ || wrapperDecl.kind === 2097152 /* ConstructSignature */)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [name.text(), enclosingDecl.name])); + } else if (wrapperDecl.kind === 65536 /* Method */) { + var parentDecl = wrapperDecl.getParentDecl(); + + if (needReportError(parentDecl, wrapperDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [name.text(), enclosingDecl.name])); + } + } else if (decl.kind === 4096 /* Property */ && !declSymbol.getContainer().isNamedTypeSymbol()) { + if (needReportError(wrapperDecl, decl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Member_0_of_object_type_implicitly_has_an_any_type, [name.text()])); + } + } else if (wrapperDecl.kind !== 268435456 /* CatchBlock */) { + if (needReportError(wrapperDecl) || !TypeScript.hasModifier(modifiers, 2 /* Private */)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Variable_0_implicitly_has_an_any_type, [name.text()])); + } + } + } + + if (init && varDeclOrParameter.kind() === 242 /* Parameter */) { + var containerSignature = enclosingDecl.getSignatureSymbol(); + if (containerSignature && !containerSignature.isDefinition()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Default_arguments_are_only_allowed_in_implementation)); + } + } + if (declSymbol.kind !== 2048 /* Parameter */ && (declSymbol.kind !== 4096 /* Property */ || declSymbol.getContainer().isNamedTypeSymbol())) { + this.checkSymbolPrivacy(declSymbol, declSymbol.type, function (symbol) { + return _this.variablePrivacyErrorReporter(varDeclOrParameter, declSymbol, symbol, context); + }); + } + + if ((declSymbol.kind !== 4096 /* Property */ && declSymbol.kind !== 67108864 /* EnumMember */) || declSymbol.anyDeclHasFlag(8388608 /* PropertyParameter */)) { + this.checkNameForCompilerGeneratedDeclarationCollision(varDeclOrParameter, true, name, context); + } + }; + + PullTypeResolver.prototype.isForInVariableDeclarator = function (ast) { + return ast.kind() === 225 /* VariableDeclarator */ && ast.parent && ast.parent.parent && ast.parent.parent.parent && ast.parent.kind() === 2 /* SeparatedList */ && ast.parent.parent.kind() === 224 /* VariableDeclaration */ && ast.parent.parent.parent.kind() === 155 /* ForInStatement */ && ast.parent.parent.parent.variableDeclaration === ast.parent.parent; + }; + + PullTypeResolver.prototype.checkSuperCaptureVariableCollides = function (superAST, isDeclaration, context) { + var enclosingDecl = this.getEnclosingDeclForAST(superAST); + + var classSymbol = this.getContextualClassSymbolForEnclosingDecl(superAST, enclosingDecl); + + if (classSymbol && !classSymbol.anyDeclHasFlag(8 /* Ambient */)) { + if (superAST.kind() === 242 /* Parameter */) { + var enclosingAST = this.getASTForDecl(enclosingDecl); + if (enclosingAST.kind() !== 218 /* ParenthesizedArrowFunctionExpression */ && enclosingAST.kind() !== 219 /* SimpleArrowFunctionExpression */) { + var block = enclosingDecl.kind === 65536 /* Method */ ? enclosingAST.block : enclosingAST.block; + if (!block) { + return; + } + } + } + + this.resolveDeclaredSymbol(classSymbol, context); + + var parents = classSymbol.getExtendedTypes(); + if (parents.length) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(superAST, isDeclaration ? TypeScript.DiagnosticCode.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference : TypeScript.DiagnosticCode.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference)); + } + } + }; + + PullTypeResolver.prototype.checkThisCaptureVariableCollides = function (_thisAST, isDeclaration, context) { + if (isDeclaration) { + var decl = this.semanticInfoChain.getDeclForAST(_thisAST); + if (TypeScript.hasFlag(decl.flags, 8 /* Ambient */)) { + return; + } + } + + var enclosingDecl = this.getEnclosingDeclForAST(_thisAST); + + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(_thisAST); + if (enclosingModule) { + enclosingDecl = this.getEnclosingDeclForAST(enclosingModule); + } + + var declPath = enclosingDecl.getParentPath(); + + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.kind; + if (declKind === 131072 /* FunctionExpression */ && TypeScript.hasFlag(decl.flags, 8192 /* ArrowFunction */)) { + continue; + } + + if (declKind === 16384 /* Function */ || declKind === 65536 /* Method */ || declKind === 32768 /* ConstructorMethod */ || declKind === 262144 /* GetAccessor */ || declKind === 524288 /* SetAccessor */ || declKind === 131072 /* FunctionExpression */ || declKind === 8 /* Class */ || declKind === 4 /* Container */ || declKind === 32 /* DynamicModule */ || declKind === 1 /* Script */) { + if (TypeScript.hasFlag(decl.flags, 262144 /* MustCaptureThis */)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(_thisAST, isDeclaration ? TypeScript.DiagnosticCode.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference : TypeScript.DiagnosticCode.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference)); + } + break; + } + } + }; + + PullTypeResolver.prototype.postTypeCheckVariableDeclaratorOrParameter = function (varDeclOrParameter, context) { + this.checkThisCaptureVariableCollides(varDeclOrParameter, true, context); + }; + + PullTypeResolver.prototype.resolveTypeParameterDeclaration = function (typeParameterAST, context) { + var typeParameterDecl = this.semanticInfoChain.getDeclForAST(typeParameterAST); + var typeParameterSymbol = typeParameterDecl.getSymbol(); + + this.resolveFirstTypeParameterDeclaration(typeParameterSymbol, context); + + if (typeParameterSymbol.isResolved && this.canTypeCheckAST(typeParameterAST, context)) { + this.typeCheckTypeParameterDeclaration(typeParameterAST, context); + } + + return typeParameterSymbol; + }; + + PullTypeResolver.prototype.resolveFirstTypeParameterDeclaration = function (typeParameterSymbol, context) { + var typeParameterDecl = typeParameterSymbol.getDeclarations()[0]; + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecl); + + if (typeParameterSymbol.isResolved || typeParameterSymbol.inResolution) { + return; + } + + typeParameterSymbol.startResolving(); + + if (typeParameterAST.constraint) { + var constraintTypeSymbol = this.resolveTypeReference(typeParameterAST.constraint.type, context); + + if (constraintTypeSymbol) { + typeParameterSymbol.setConstraint(constraintTypeSymbol); + } + } + + typeParameterSymbol.setResolved(); + }; + + PullTypeResolver.prototype.typeCheckTypeParameterDeclaration = function (typeParameterAST, context) { + this.setTypeChecked(typeParameterAST, context); + + var constraint = this.resolveAST(typeParameterAST.constraint, false, context); + + if (constraint) { + var typeParametersAST = typeParameterAST.parent; + var typeParameters = []; + for (var i = 0; i < typeParametersAST.nonSeparatorCount(); i++) { + var currentTypeParameterAST = typeParametersAST.nonSeparatorAt(i); + var currentTypeParameterDecl = this.semanticInfoChain.getDeclForAST(currentTypeParameterAST); + var currentTypeParameter = this.semanticInfoChain.getSymbolForDecl(currentTypeParameterDecl); + typeParameters[currentTypeParameter.pullSymbolID] = currentTypeParameter; + } + + if (constraint.wrapsSomeTypeParameter(typeParameters)) { + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); + } + } + }; + + PullTypeResolver.prototype.resolveConstraint = function (constraint, context) { + if (this.canTypeCheckAST(constraint, context)) { + this.setTypeChecked(constraint, context); + } + + return this.resolveTypeReference(constraint.type, context); + }; + + PullTypeResolver.prototype.resolveFunctionBodyReturnTypes = function (funcDeclAST, block, bodyExpression, signature, useContextualType, enclosingDecl, context) { + var _this = this; + var returnStatementsExpressions = []; + + var enclosingDeclStack = [enclosingDecl]; + + var preFindReturnExpressionTypes = function (ast, walker) { + var go = true; + + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 215 /* ObjectLiteralExpression */: + go = false; + break; + + case 150 /* ReturnStatement */: + var returnStatement = ast; + enclosingDecl.setFlag(4194304 /* HasReturnStatement */); + returnStatementsExpressions.push({ expression: returnStatement.expression, enclosingDecl: enclosingDeclStack[enclosingDeclStack.length - 1] }); + go = false; + break; + + case 236 /* CatchClause */: + case 163 /* WithStatement */: + enclosingDeclStack[enclosingDeclStack.length] = _this.semanticInfoChain.getDeclForAST(ast); + break; + + default: + break; + } + + walker.options.goChildren = go; + + return ast; + }; + + var postFindReturnExpressionEnclosingDecls = function (ast, walker) { + switch (ast.kind()) { + case 236 /* CatchClause */: + case 163 /* WithStatement */: + enclosingDeclStack.length--; + break; + default: + break; + } + + walker.options.goChildren = true; + + return ast; + }; + + if (block) { + TypeScript.getAstWalkerFactory().walk(block, preFindReturnExpressionTypes, postFindReturnExpressionEnclosingDecls); + } else { + returnStatementsExpressions.push({ expression: bodyExpression, enclosingDecl: enclosingDecl }); + enclosingDecl.setFlag(4194304 /* HasReturnStatement */); + } + + if (!returnStatementsExpressions.length) { + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + } else { + var returnExpressionSymbols = []; + var returnExpressions = []; + + for (var i = 0; i < returnStatementsExpressions.length; i++) { + var returnExpression = returnStatementsExpressions[i].expression; + if (returnExpression) { + var returnType = this.resolveAST(returnExpression, useContextualType, context).type; + + if (returnType.isError()) { + signature.returnType = returnType; + return; + } else { + if (returnExpression.parent.kind() === 150 /* ReturnStatement */) { + this.setSymbolForAST(returnExpression.parent, returnType, context); + } + } + + returnExpressionSymbols.push(returnType); + returnExpressions.push(returnExpression); + } + } + + if (!returnExpressionSymbols.length) { + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + } else { + var collection = { + getLength: function () { + return returnExpressionSymbols.length; + }, + getTypeAtIndex: function (index) { + return returnExpressionSymbols[index].type; + } + }; + + var bestCommonReturnType = this.findBestCommonType(collection, context, new TypeComparisonInfo()); + var returnType = bestCommonReturnType; + var returnExpression = returnExpressions[returnExpressionSymbols.indexOf(returnType)]; + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var functionSymbol = functionDecl.getSymbol(); + + if (returnType) { + var previousReturnType = returnType; + var newReturnType = returnType.widenedType(this, returnExpression, context); + signature.returnType = newReturnType; + + if (!TypeScript.ArrayUtilities.contains(returnExpressionSymbols, bestCommonReturnType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Could_not_find_the_best_common_type_of_types_of_all_return_statement_expressions)); + } + + if (this.compilationSettings.noImplicitAny()) { + if (previousReturnType !== newReturnType && newReturnType === this.semanticInfoChain.anyTypeSymbol) { + var functionName = enclosingDecl.name; + if (functionName === "") { + functionName = enclosingDecl.getFunctionExpressionName(); + } + + if (functionName != "") { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type, [functionName])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + } + } + + if (!functionSymbol.type && functionSymbol.isAccessor()) { + functionSymbol.type = signature.returnType; + } + } + } + }; + + PullTypeResolver.prototype.typeCheckConstructorDeclaration = function (funcDeclAST, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + for (var i = 0; i < funcDeclAST.callSignature.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveAST(funcDeclAST.callSignature.parameterList.parameters.nonSeparatorAt(i), false, context); + } + + this.resolveAST(funcDeclAST.block, false, context); + + if (funcDecl.getSignatureSymbol() && funcDecl.getSignatureSymbol().isDefinition() && this.enclosingClassIsDerived(funcDecl.getParentDecl())) { + if (!this.constructorHasSuperCall(funcDeclAST)) { + context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), "constructor".length, TypeScript.DiagnosticCode.Constructors_for_derived_classes_must_contain_a_super_call)); + } else if (this.superCallMustBeFirstStatementInConstructor(funcDecl)) { + var firstStatement = this.getFirstStatementOfBlockOrNull(funcDeclAST.block); + if (!firstStatement || !this.isSuperInvocationExpressionStatement(firstStatement)) { + context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), "constructor".length, TypeScript.DiagnosticCode.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties)); + } + } + } + + this.validateVariableDeclarationGroups(funcDecl, context); + + this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.callSignature.parameterList), null, funcDeclAST.block, context); + + this.typeCheckCallBacks.push(function (context) { + _this.typeCheckFunctionOverloads(funcDeclAST, context); + }); + }; + + PullTypeResolver.prototype.constructorHasSuperCall = function (constructorDecl) { + var _this = this; + if (constructorDecl.block) { + var foundSuperCall = false; + var pre = function (ast, walker) { + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 215 /* ObjectLiteralExpression */: + walker.options.goChildren = false; + default: + if (_this.isSuperInvocationExpression(ast)) { + foundSuperCall = true; + walker.options.stopWalking = true; + } + } + }; + + TypeScript.getAstWalkerFactory().walk(constructorDecl.block, pre); + return foundSuperCall; + } + + return false; + }; + + PullTypeResolver.prototype.typeCheckFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + this.typeCheckAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), funcDecl.callSignature.typeAnnotation, funcDecl.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckCallSignature = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckConstructSignature = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckMethodSignature = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, false, funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckMemberFunctionDeclaration = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + }; + + PullTypeResolver.prototype.containsSingleThrowStatement = function (block) { + return block !== null && block.statements.childCount() === 1 && block.statements.childAt(0).kind() === 157 /* ThrowStatement */; + }; + + PullTypeResolver.prototype.typeCheckAnyFunctionDeclaration = function (funcDeclAST, isStatic, name, typeParameters, parameters, returnTypeAnnotation, block, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + this.resolveAST(parameters, false, context); + + this.resolveAST(block, false, context); + var enclosingDecl = this.getEnclosingDecl(funcDecl); + + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); + this.validateVariableDeclarationGroups(funcDecl, context); + + this.checkFunctionTypePrivacy(funcDeclAST, isStatic, typeParameters, TypeScript.ASTHelpers.parametersFromParameterList(parameters), returnTypeAnnotation, block, context); + + this.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement(funcDecl, returnTypeAnnotation, funcDecl.getSignatureSymbol().returnType, block, context); + + if (funcDecl.kind === 16384 /* Function */) { + this.checkNameForCompilerGeneratedDeclarationCollision(funcDeclAST, true, name, context); + } + + this.typeCheckCallBacks.push(function (context) { + _this.typeCheckFunctionOverloads(funcDeclAST, context); + }); + }; + + PullTypeResolver.prototype.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement = function (functionDecl, returnTypeAnnotation, returnTypeSymbol, block, context) { + var hasReturn = TypeScript.hasFlag(functionDecl.flags, 4194304 /* HasReturnStatement */); + + if (block !== null && returnTypeAnnotation !== null && !hasReturn) { + var isVoidOrAny = this.isAnyOrEquivalent(returnTypeSymbol) || returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol; + + if (!isVoidOrAny && !this.containsSingleThrowStatement(block)) { + var funcName = functionDecl.getDisplayName() || TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Function_declared_a_non_void_return_type_but_has_no_return_expression)); + } + } + }; + + PullTypeResolver.prototype.typeCheckIndexSignature = function (funcDeclAST, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + this.resolveAST(funcDeclAST.parameter, false, context); + + var enclosingDecl = this.getEnclosingDecl(funcDecl); + + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); + this.validateVariableDeclarationGroups(funcDecl, context); + + this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.ASTHelpers.parametersFromParameter(funcDeclAST.parameter), TypeScript.ASTHelpers.getType(funcDeclAST), null, context); + + var signature = funcDecl.getSignatureSymbol(); + + this.typeCheckCallBacks.push(function (context) { + var parentSymbol = funcDecl.getSignatureSymbol().getContainer(); + var allIndexSignatures = _this.getBothKindsOfIndexSignaturesExcludingAugmentedType(parentSymbol, context); + var stringIndexSignature = allIndexSignatures.stringSignature; + var numberIndexSignature = allIndexSignatures.numericSignature; + var isNumericIndexer = numberIndexSignature === signature; + + if (numberIndexSignature && stringIndexSignature && (isNumericIndexer || stringIndexSignature.getDeclarations()[0].getParentDecl() !== numberIndexSignature.getDeclarations()[0].getParentDecl())) { + var comparisonInfo = new TypeComparisonInfo(); + + if (!_this.sourceIsAssignableToTarget(numberIndexSignature.returnType, stringIndexSignature.returnType, funcDeclAST, context, comparisonInfo)) { + var enclosingSymbol = _this.getEnclosingSymbolForAST(funcDeclAST); + if (comparisonInfo.message) { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1_NL_2, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol)])); + } + } + } + + var allMembers = parentSymbol.type.getAllMembers(536869887 /* All */, 0 /* all */); + for (var i = 0; i < allMembers.length; i++) { + var member = allMembers[i]; + var name = member.name; + if (name || (member.kind === 4096 /* Property */ && name === "")) { + if (!allMembers[i].isResolved) { + _this.resolveDeclaredSymbol(allMembers[i], context); + } + + if (parentSymbol !== allMembers[i].getContainer()) { + var isMemberNumeric = TypeScript.PullHelpers.isNameNumeric(name); + var indexerKindMatchesMemberNameKind = isNumericIndexer === isMemberNumeric; + var onlyStringIndexerIsPresent = !numberIndexSignature; + + if (indexerKindMatchesMemberNameKind || onlyStringIndexerIsPresent) { + var comparisonInfo = new TypeComparisonInfo(); + if (!_this.sourceIsAssignableToTarget(allMembers[i].type, signature.returnType, funcDeclAST, context, comparisonInfo, false)) { + _this.reportErrorThatMemberIsNotSubtypeOfIndexer(allMembers[i], signature, funcDeclAST, context, comparisonInfo); + } + } + } + } + } + }); + }; + + PullTypeResolver.prototype.postTypeCheckFunctionDeclaration = function (funcDeclAST, context) { + this.checkThisCaptureVariableCollides(funcDeclAST, true, context); + }; + + PullTypeResolver.prototype.resolveReturnTypeAnnotationOfFunctionDeclaration = function (funcDeclAST, returnTypeAnnotation, context) { + var returnTypeSymbol = null; + + if (returnTypeAnnotation) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + returnTypeSymbol = this.resolveTypeReference(returnTypeAnnotation, context); + + if (!returnTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); + } else { + var isConstructor = funcDeclAST.kind() === 137 /* ConstructorDeclaration */ || funcDeclAST.kind() === 143 /* ConstructSignature */; + if (isConstructor && returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Constructors_cannot_have_a_return_type_of_void)); + } + } + } + + return returnTypeSymbol; + }; + + PullTypeResolver.prototype.resolveMemberFunctionDeclaration = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + }; + + PullTypeResolver.prototype.resolveCallSignature = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.resolveConstructSignature = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.resolveMethodSignature = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, false, funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.resolveAnyFunctionDeclaration = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + }; + + PullTypeResolver.prototype.resolveFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveSimpleArrowFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcDecl, null, TypeScript.ASTHelpers.parametersFromIdentifier(funcDecl.identifier), null, funcDecl.block, funcDecl.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveParenthesizedArrowFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, funcDecl.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.getEnclosingClassDeclaration = function (ast) { + while (ast) { + if (ast.kind() === 131 /* ClassDeclaration */) { + return ast; + } + + ast = ast.parent; + } + + return null; + }; + + PullTypeResolver.prototype.resolveConstructorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcSymbol = funcDecl.getSymbol(); + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckConstructorDeclaration(funcDeclAST, context); + } + return funcSymbol; + } + + if (!signature.inResolution) { + var classAST = this.getEnclosingClassDeclaration(funcDeclAST); + + if (classAST) { + var classDecl = this.semanticInfoChain.getDeclForAST(classAST); + var classSymbol = classDecl.getSymbol(); + + if (!classSymbol.isResolved && !classSymbol.inResolution) { + this.resolveDeclaredSymbol(classSymbol, context); + } + } + } + + var functionTypeSymbol = funcSymbol && funcSymbol.type; + + if (signature.inResolution) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + return funcSymbol; + } + + if (funcSymbol) { + funcSymbol.startResolving(); + } + signature.startResolving(); + + var prevInTypeCheck = context.inTypeCheck; + + context.inTypeCheck = false; + + for (var i = 0; i < funcDeclAST.callSignature.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(funcDeclAST.callSignature.parameterList.parameters.nonSeparatorAt(i), context); + } + + context.inTypeCheck = prevInTypeCheck; + + if (signature.isGeneric()) { + if (funcSymbol) { + funcSymbol.type.setHasGenericSignature(); + } + } + + if (!hadError) { + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + } + } + + if (funcSymbol) { + this.resolveOtherDeclarations(funcDeclAST, context); + } + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckConstructorDeclaration(funcDeclAST, context); + } + + return funcSymbol; + }; + + PullTypeResolver.prototype.resolveIndexMemberDeclaration = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + } + + return this.resolveIndexSignature(ast.indexSignature, context); + }; + + PullTypeResolver.prototype.resolveIndexSignature = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcSymbol = funcDecl.getSymbol(); + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckIndexSignature(funcDeclAST, context); + } + return funcSymbol; + } + + var functionTypeSymbol = funcSymbol && funcSymbol.type; + + if (signature.inResolution) { + if (funcDeclAST.typeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(TypeScript.ASTHelpers.getType(funcDeclAST), context); + if (!returnTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(TypeScript.ASTHelpers.getType(funcDeclAST), TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + } + + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + return funcSymbol; + } + + if (funcSymbol) { + funcSymbol.startResolving(); + } + signature.startResolving(); + + if (funcDeclAST.parameter) { + var prevInTypeCheck = context.inTypeCheck; + + context.inTypeCheck = false; + this.resolveParameter(funcDeclAST.parameter, context); + context.inTypeCheck = prevInTypeCheck; + } + + if (funcDeclAST.typeAnnotation) { + returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); + + if (!returnTypeSymbol) { + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + } + + if (!hadError) { + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + } + } + + if (funcSymbol) { + this.resolveOtherDeclarations(funcDeclAST, context); + } + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckIndexSignature(funcDeclAST, context); + } + + return funcSymbol; + }; + + PullTypeResolver.prototype.resolveFunctionDeclaration = function (funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcSymbol = funcDecl.getSymbol(); + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + var isConstructor = funcDeclAST.kind() === 143 /* ConstructSignature */; + + if (signature) { + if (signature.isResolved) { + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckAnyFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); + } + return funcSymbol; + } + + if (isConstructor && !signature.inResolution) { + var classAST = this.getEnclosingClassDeclaration(funcDeclAST); + + if (classAST) { + var classDecl = this.semanticInfoChain.getDeclForAST(classAST); + var classSymbol = classDecl.getSymbol(); + + if (!classSymbol.isResolved && !classSymbol.inResolution) { + this.resolveDeclaredSymbol(classSymbol, context); + } + } + } + + var functionTypeSymbol = funcSymbol && funcSymbol.type; + + if (signature.inResolution) { + if (returnTypeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(returnTypeAnnotation, context); + if (!returnTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + + if (isConstructor && returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Constructors_cannot_have_a_return_type_of_void)); + } + } + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + } + + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + return funcSymbol; + } + + if (funcSymbol) { + funcSymbol.startResolving(); + } + signature.startResolving(); + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + if (parameterList) { + var prevInTypeCheck = context.inTypeCheck; + + context.inTypeCheck = false; + + for (var i = 0; i < parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(parameterList.parameters.nonSeparatorAt(i), context); + } + + context.inTypeCheck = prevInTypeCheck; + } + + if (returnTypeAnnotation) { + returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); + + if (!returnTypeSymbol) { + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else if (funcDecl.kind !== 2097152 /* ConstructSignature */) { + if (TypeScript.hasFlag(funcDecl.flags, 2048 /* Signature */)) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + var parentDeclFlags = 0 /* None */; + if (TypeScript.hasFlag(funcDecl.kind, 65536 /* Method */) || TypeScript.hasFlag(funcDecl.kind, 32768 /* ConstructorMethod */)) { + var parentDecl = funcDecl.getParentDecl(); + parentDeclFlags = parentDecl.flags; + } + + if (this.compilationSettings.noImplicitAny() && (!TypeScript.hasFlag(parentDeclFlags, 8 /* Ambient */) || (TypeScript.hasFlag(parentDeclFlags, 8 /* Ambient */) && !TypeScript.hasFlag(funcDecl.flags, 2 /* Private */)))) { + var funcDeclASTName = name; + if (funcDeclASTName) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type, [funcDeclASTName.text()])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Lambda_Function_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + } else { + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, null, signature, false, funcDecl, context); + } + } else if (funcDecl.kind === 2097152 /* ConstructSignature */) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Constructor_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + + if (!hadError) { + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + } + } + + if (funcSymbol) { + this.resolveOtherDeclarations(funcDeclAST, context); + } + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckAnyFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); + } + + return funcSymbol; + }; + + PullTypeResolver.prototype.resolveGetterReturnTypeAnnotation = function (getterFunctionDeclarationAst, enclosingDecl, context) { + if (getterFunctionDeclarationAst && getterFunctionDeclarationAst.typeAnnotation) { + return this.resolveTypeReference(TypeScript.ASTHelpers.getType(getterFunctionDeclarationAst), context); + } + + return null; + }; + + PullTypeResolver.prototype.resolveSetterArgumentTypeAnnotation = function (setterFunctionDeclarationAst, enclosingDecl, context) { + if (setterFunctionDeclarationAst && setterFunctionDeclarationAst.parameterList && setterFunctionDeclarationAst.parameterList.parameters.nonSeparatorCount() > 0) { + var parameter = setterFunctionDeclarationAst.parameterList.parameters.nonSeparatorAt(0); + return this.resolveTypeReference(TypeScript.ASTHelpers.getType(parameter), context); + } + + return null; + }; + + PullTypeResolver.prototype.resolveAccessorDeclaration = function (funcDeclAst, context) { + var functionDeclaration = this.semanticInfoChain.getDeclForAST(funcDeclAst); + var accessorSymbol = functionDeclaration.getSymbol(); + + if (accessorSymbol.inResolution) { + accessorSymbol.type = this.semanticInfoChain.anyTypeSymbol; + accessorSymbol.setResolved(); + + return accessorSymbol; + } + + if (accessorSymbol.isResolved) { + if (!accessorSymbol.type) { + accessorSymbol.type = this.semanticInfoChain.anyTypeSymbol; + } + } else { + var getterSymbol = accessorSymbol.getGetter(); + var getterFunctionDeclarationAst = getterSymbol ? getterSymbol.getDeclarations()[0].ast() : null; + var hasGetter = getterSymbol !== null; + + var setterSymbol = accessorSymbol.getSetter(); + var setterFunctionDeclarationAst = setterSymbol ? setterSymbol.getDeclarations()[0].ast() : null; + var hasSetter = setterSymbol !== null; + + var getterAnnotatedType = this.resolveGetterReturnTypeAnnotation(getterFunctionDeclarationAst, functionDeclaration, context); + var getterHasTypeAnnotation = getterAnnotatedType !== null; + + var setterAnnotatedType = this.resolveSetterArgumentTypeAnnotation(setterFunctionDeclarationAst, functionDeclaration, context); + var setterHasTypeAnnotation = setterAnnotatedType !== null; + + accessorSymbol.startResolving(); + + if (hasGetter) { + getterSymbol = this.resolveGetAccessorDeclaration(getterFunctionDeclarationAst, getterFunctionDeclarationAst.parameterList, TypeScript.ASTHelpers.getType(getterFunctionDeclarationAst), getterFunctionDeclarationAst.block, setterAnnotatedType, context); + } + + if (hasSetter) { + setterSymbol = this.resolveSetAccessorDeclaration(setterFunctionDeclarationAst, setterFunctionDeclarationAst.parameterList, context); + } + + if (hasGetter && hasSetter) { + var setterSig = setterSymbol.type.getCallSignatures()[0]; + var setterParameters = setterSig.parameters; + var setterHasParameters = setterParameters.length > 0; + var getterSig = getterSymbol.type.getCallSignatures()[0]; + + var setterSuppliedTypeSymbol = setterHasParameters ? setterParameters[0].type : null; + var getterSuppliedTypeSymbol = getterSig.returnType; + + if (setterHasTypeAnnotation && !getterHasTypeAnnotation) { + getterSuppliedTypeSymbol = setterSuppliedTypeSymbol; + getterSig.returnType = setterSuppliedTypeSymbol; + } else if ((getterHasTypeAnnotation && !setterHasTypeAnnotation) || (!getterHasTypeAnnotation && !setterHasTypeAnnotation)) { + setterSuppliedTypeSymbol = getterSuppliedTypeSymbol; + + if (setterHasParameters) { + setterParameters[0].type = getterSuppliedTypeSymbol; + } + } + + if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol, context)) { + accessorSymbol.type = this.getNewErrorTypeSymbol(); + } else { + accessorSymbol.type = getterSuppliedTypeSymbol; + } + } else if (hasSetter) { + var setterSig = setterSymbol.type.getCallSignatures()[0]; + var setterParameters = setterSig.parameters; + var setterHasParameters = setterParameters.length > 0; + + accessorSymbol.type = setterHasParameters ? setterParameters[0].type : this.semanticInfoChain.anyTypeSymbol; + } else { + var getterSig = getterSymbol.type.getCallSignatures()[0]; + accessorSymbol.type = getterSig.returnType; + } + + accessorSymbol.setResolved(); + } + + if (this.canTypeCheckAST(funcDeclAst, context)) { + this.typeCheckAccessorDeclaration(funcDeclAst, context); + } + + return accessorSymbol; + }; + + PullTypeResolver.prototype.typeCheckAccessorDeclaration = function (funcDeclAst, context) { + this.setTypeChecked(funcDeclAst, context); + var functionDeclaration = this.semanticInfoChain.getDeclForAST(funcDeclAst); + var accessorSymbol = functionDeclaration.getSymbol(); + var getterSymbol = accessorSymbol.getGetter(); + var setterSymbol = accessorSymbol.getSetter(); + + var isGetter = funcDeclAst.kind() === 139 /* GetAccessor */; + if (isGetter) { + var getterFunctionDeclarationAst = funcDeclAst; + context.pushNewContextualType(getterSymbol.type); + this.typeCheckGetAccessorDeclaration(getterFunctionDeclarationAst, context); + context.popAnyContextualType(); + } else { + var setterFunctionDeclarationAst = funcDeclAst; + this.typeCheckSetAccessorDeclaration(setterFunctionDeclarationAst, context); + } + }; + + PullTypeResolver.prototype.resolveGetAccessorDeclaration = function (funcDeclAST, parameters, returnTypeAnnotation, block, setterAnnotatedType, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + var getterSymbol = accessorSymbol.getGetter(); + var getterTypeSymbol = getterSymbol.type; + + var signature = getterTypeSymbol.getCallSignatures()[0]; + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + return getterSymbol; + } + + if (signature.inResolution) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + signature.setResolved(); + + return getterSymbol; + } + + signature.startResolving(); + + if (returnTypeAnnotation) { + var returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); + + if (!returnTypeSymbol) { + signature.returnType = this.getNewErrorTypeSymbol(); + + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else { + if (!setterAnnotatedType) { + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, null, signature, false, funcDecl, context); + } else { + signature.returnType = setterAnnotatedType; + } + } + + if (!hadError) { + signature.setResolved(); + } + } + + return getterSymbol; + }; + + PullTypeResolver.prototype.checkIfGetterAndSetterTypeMatch = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + var getter = accessorSymbol.getGetter(); + var setter = accessorSymbol.getSetter(); + + if (getter && setter) { + var getterAST = getter.getDeclarations()[0].ast(); + var setterAST = setter.getDeclarations()[0].ast(); + + if (getterAST.typeAnnotation && PullTypeResolver.hasSetAccessorParameterTypeAnnotation(setterAST)) { + var setterSig = setter.type.getCallSignatures()[0]; + var setterParameters = setterSig.parameters; + + var getter = accessorSymbol.getGetter(); + var getterSig = getter.type.getCallSignatures()[0]; + + var setterSuppliedTypeSymbol = setterParameters[0].type; + var getterSuppliedTypeSymbol = getterSig.returnType; + + if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.get_and_set_accessor_must_have_the_same_type)); + } + } + } + }; + + PullTypeResolver.prototype.typeCheckGetAccessorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); + + this.resolveAST(funcDeclAST.block, false, context); + + this.validateVariableDeclarationGroups(funcDecl, context); + + var enclosingDecl = this.getEnclosingDecl(funcDecl); + + var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) !== 0; + var funcNameAST = funcDeclAST.propertyName; + + if (!hasReturn && !this.containsSingleThrowStatement(funcDeclAST.block)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getters_must_return_a_value)); + } + + var setter = accessorSymbol.getSetter(); + if (setter) { + var setterDecl = setter.getDeclarations()[0]; + var setterIsPrivate = TypeScript.hasFlag(setterDecl.flags, 2 /* Private */); + var getterIsPrivate = TypeScript.hasModifier(funcDeclAST.modifiers, 2 /* Private */); + + if (getterIsPrivate !== setterIsPrivate) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getter_and_setter_accessors_do_not_agree_in_visibility)); + } + + this.checkIfGetterAndSetterTypeMatch(funcDeclAST, context); + } + + this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), TypeScript.ASTHelpers.getType(funcDeclAST), funcDeclAST.block, context); + }; + + PullTypeResolver.hasSetAccessorParameterTypeAnnotation = function (setAccessor) { + return setAccessor.parameterList && setAccessor.parameterList.parameters.nonSeparatorCount() > 0 && setAccessor.parameterList.parameters.nonSeparatorAt(0).typeAnnotation !== null; + }; + + PullTypeResolver.prototype.resolveSetAccessorDeclaration = function (funcDeclAST, parameterList, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + var setterSymbol = accessorSymbol.getSetter(); + var setterTypeSymbol = setterSymbol.type; + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + return setterSymbol; + } + + if (signature.inResolution) { + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + signature.setResolved(); + return setterSymbol; + } + + signature.startResolving(); + + if (parameterList) { + for (var i = 0; i < parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(parameterList.parameters.nonSeparatorAt(i), context); + } + } + + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + + if (!hadError) { + signature.setResolved(); + } + } + + return setterSymbol; + }; + + PullTypeResolver.prototype.typeCheckSetAccessorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + if (funcDeclAST.parameterList) { + for (var i = 0; i < funcDeclAST.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(funcDeclAST.parameterList.parameters.nonSeparatorAt(i), context); + } + } + + this.resolveAST(funcDeclAST.block, false, context); + + this.validateVariableDeclarationGroups(funcDecl, context); + + var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) !== 0; + + var getter = accessorSymbol.getGetter(); + + var funcNameAST = funcDeclAST.propertyName; + + if (getter) { + var getterDecl = getter.getDeclarations()[0]; + var getterIsPrivate = TypeScript.hasFlag(getterDecl.flags, 2 /* Private */); + var setterIsPrivate = TypeScript.hasModifier(funcDeclAST.modifiers, 2 /* Private */); + + if (getterIsPrivate !== setterIsPrivate) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getter_and_setter_accessors_do_not_agree_in_visibility)); + } + + this.checkIfGetterAndSetterTypeMatch(funcDeclAST, context); + } else { + if (this.compilationSettings.noImplicitAny()) { + var setterFunctionDeclarationAst = funcDeclAST; + if (!PullTypeResolver.hasSetAccessorParameterTypeAnnotation(setterFunctionDeclarationAst) && accessorSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type, [setterFunctionDeclarationAst.propertyName.text()])); + } + } + } + + this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), null, funcDeclAST.block, context); + }; + + PullTypeResolver.prototype.resolveList = function (list, context) { + if (this.canTypeCheckAST(list, context)) { + this.setTypeChecked(list, context); + + for (var i = 0, n = list.childCount(); i < n; i++) { + this.resolveAST(list.childAt(i), false, context); + } + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveSeparatedList = function (list, context) { + if (this.canTypeCheckAST(list, context)) { + this.setTypeChecked(list, context); + + for (var i = 0, n = list.nonSeparatorCount(); i < n; i++) { + this.resolveAST(list.nonSeparatorAt(i), false, context); + } + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveVoidExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.undefinedTypeSymbol; + }; + + PullTypeResolver.prototype.resolveLogicalOperation = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckLogicalOperation(ast, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckLogicalOperation = function (binex, context) { + this.setTypeChecked(binex, context); + + var leftType = this.resolveAST(binex.left, false, context).type; + var rightType = this.resolveAST(binex.right, false, context).type; + + var comparisonInfo = new TypeComparisonInfo(); + if (!this.sourceIsAssignableToTarget(leftType, rightType, binex, context, comparisonInfo) && !this.sourceIsAssignableToTarget(rightType, leftType, binex, context, comparisonInfo)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(binex); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binex, TypeScript.DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2, [ + TypeScript.SyntaxFacts.getText(TypeScript.SyntaxFacts.getOperatorTokenFromBinaryExpression(binex.kind())), + leftType.toString(enclosingSymbol), rightType.toString(enclosingSymbol)])); + } + }; + + PullTypeResolver.prototype.resolveLogicalNotExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.operand, false, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.resolveUnaryArithmeticOperation = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckUnaryArithmeticOperation(ast, context); + } + + return this.semanticInfoChain.numberTypeSymbol; + }; + + PullTypeResolver.prototype.resolvePostfixUnaryExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckPostfixUnaryExpression(ast, context); + } + + return this.semanticInfoChain.numberTypeSymbol; + }; + + PullTypeResolver.prototype.isAnyOrNumberOrEnum = function (type) { + return this.isAnyOrEquivalent(type) || type === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(type); + }; + + PullTypeResolver.prototype.typeCheckUnaryArithmeticOperation = function (unaryExpression, context) { + this.setTypeChecked(unaryExpression, context); + + var nodeType = unaryExpression.kind(); + var expression = this.resolveAST(unaryExpression.operand, false, context); + + if (nodeType === 164 /* PlusExpression */ || nodeType == 165 /* NegateExpression */ || nodeType == 166 /* BitwiseNotExpression */) { + return; + } + + TypeScript.Debug.assert(nodeType === 168 /* PreIncrementExpression */ || nodeType === 169 /* PreDecrementExpression */); + + var operandType = expression.type; + if (!this.isAnyOrNumberOrEnum(operandType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type_any_number_or_an_enum_type)); + } + + if (!this.isReference(unaryExpression.operand, expression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer)); + } + }; + + PullTypeResolver.prototype.typeCheckPostfixUnaryExpression = function (unaryExpression, context) { + this.setTypeChecked(unaryExpression, context); + + var nodeType = unaryExpression.kind(); + var expression = this.resolveAST(unaryExpression.operand, false, context); + + TypeScript.Debug.assert(nodeType === 210 /* PostIncrementExpression */ || nodeType === 211 /* PostDecrementExpression */); + + var operandType = expression.type; + if (!this.isAnyOrNumberOrEnum(operandType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type_any_number_or_an_enum_type)); + } + + if (!this.isReference(unaryExpression.operand, expression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer)); + } + }; + + PullTypeResolver.prototype.resolveBinaryArithmeticExpression = function (binaryExpression, context) { + if (this.canTypeCheckAST(binaryExpression, context)) { + this.typeCheckBinaryArithmeticExpression(binaryExpression, context); + } + + return this.semanticInfoChain.numberTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckBinaryArithmeticExpression = function (binaryExpression, context) { + this.setTypeChecked(binaryExpression, context); + + var lhsSymbol = this.resolveAST(binaryExpression.left, false, context); + + var lhsType = lhsSymbol.type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + if (lhsType === this.semanticInfoChain.nullTypeSymbol || lhsType === this.semanticInfoChain.undefinedTypeSymbol) { + lhsType = rhsType; + } + + if (rhsType === this.semanticInfoChain.nullTypeSymbol || rhsType === this.semanticInfoChain.undefinedTypeSymbol) { + rhsType = lhsType; + } + + var lhsIsFit = this.isAnyOrNumberOrEnum(lhsType); + var rhsIsFit = this.isAnyOrNumberOrEnum(rhsType); + + if (!rhsIsFit) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type)); + } + + if (!lhsIsFit) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type)); + } + + if (lhsIsFit && rhsIsFit) { + switch (binaryExpression.kind()) { + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + if (!this.isReference(binaryExpression.left, lhsSymbol)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_left_hand_side_of_assignment_expression)); + } + + this.checkAssignability(binaryExpression.left, rhsType, lhsType, context); + } + } + }; + + PullTypeResolver.prototype.resolveTypeOfExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.stringTypeSymbol; + }; + + PullTypeResolver.prototype.resolveThrowStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveDeleteExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.resolveInstanceOfExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckInstanceOfExpression(ast, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckInstanceOfExpression = function (binaryExpression, context) { + this.setTypeChecked(binaryExpression, context); + + var lhsType = this.resolveAST(binaryExpression.left, false, context).type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + var enclosingSymbol = this.getEnclosingSymbolForAST(binaryExpression); + var isValidLHS = this.isAnyOrEquivalent(lhsType) || lhsType.isObject() || lhsType.isTypeParameter(); + var isValidRHS = this.isAnyOrEquivalent(rhsType) || this.typeIsAssignableToFunction(rhsType, binaryExpression, context); + + if (!isValidLHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter)); + } + + if (!isValidRHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type)); + } + }; + + PullTypeResolver.prototype.resolveCommaExpression = function (commaExpression, context) { + if (this.canTypeCheckAST(commaExpression, context)) { + this.setTypeChecked(commaExpression, context); + + this.resolveAST(commaExpression.left, false, context); + } + + return this.resolveAST(commaExpression.right, false, context).type; + }; + + PullTypeResolver.prototype.resolveInExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckInExpression(ast, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckInExpression = function (binaryExpression, context) { + this.setTypeChecked(binaryExpression, context); + + var lhsType = this.resolveAST(binaryExpression.left, false, context).type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + var isValidLHS = this.isAnyOrEquivalent(lhsType.type) || lhsType.type === this.semanticInfoChain.stringTypeSymbol || lhsType.type === this.semanticInfoChain.numberTypeSymbol; + + var isValidRHS = this.isAnyOrEquivalent(rhsType) || rhsType.isObject() || rhsType.isTypeParameter(); + + if (!isValidLHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number)); + } + + if (!isValidRHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter)); + } + }; + + PullTypeResolver.prototype.resolveForStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.variableDeclaration, false, context); + this.resolveAST(ast.initializer, false, context); + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.incrementor, false, context); + this.resolveAST(ast.statement, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveForInStatement = function (forInStatement, context) { + if (this.canTypeCheckAST(forInStatement, context)) { + this.typeCheckForInStatement(forInStatement, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckForInStatement = function (forInStatement, context) { + this.setTypeChecked(forInStatement, context); + + if (forInStatement.variableDeclaration) { + var declaration = forInStatement.variableDeclaration; + + if (declaration.declarators.nonSeparatorCount() === 1) { + var varDecl = declaration.declarators.nonSeparatorAt(0); + + if (varDecl.typeAnnotation) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(declaration, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_cannot_use_a_type_annotation)); + } + } + } else { + var varSym = this.resolveAST(forInStatement.left, false, context); + var isStringOrNumber = varSym.type === this.semanticInfoChain.stringTypeSymbol || this.isAnyOrEquivalent(varSym.type); + + if (!isStringOrNumber) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(forInStatement.left, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_must_be_of_types_string_or_any)); + } + } + + var rhsType = this.resolveAST(forInStatement.expression, false, context).type; + var isValidRHS = rhsType && (this.isAnyOrEquivalent(rhsType) || rhsType.isObject() || rhsType.isTypeParameter()); + + if (!isValidRHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(forInStatement.expression, TypeScript.DiagnosticCode.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter)); + } + + this.resolveAST(forInStatement.statement, false, context); + }; + + PullTypeResolver.prototype.resolveWhileStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckWhileStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckWhileStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.resolveDoStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckDoStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckDoStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.resolveIfStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckIfStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckIfStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.statement, false, context); + this.resolveAST(ast.elseClause, false, context); + }; + + PullTypeResolver.prototype.resolveElseClause = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckElseClause(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckElseClause = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.resolveBlock = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.statements, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveVariableStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.declaration, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveVariableDeclarationList = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.declarators, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveWithStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckWithStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckWithStatement = function (ast, context) { + this.setTypeChecked(ast, context); + var withStatement = ast; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(withStatement.condition, TypeScript.DiagnosticCode.All_symbols_within_a_with_block_will_be_resolved_to_any)); + }; + + PullTypeResolver.prototype.resolveTryStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckTryStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckTryStatement = function (ast, context) { + this.setTypeChecked(ast, context); + var tryStatement = ast; + + this.resolveAST(tryStatement.block, false, context); + this.resolveAST(tryStatement.catchClause, false, context); + this.resolveAST(tryStatement.finallyClause, false, context); + }; + + PullTypeResolver.prototype.resolveCatchClause = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckCatchClause(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckCatchClause = function (ast, context) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.block, false, context); + + var catchDecl = this.semanticInfoChain.getDeclForAST(ast); + this.validateVariableDeclarationGroups(catchDecl, context); + }; + + PullTypeResolver.prototype.resolveFinallyClause = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckFinallyClause(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckFinallyClause = function (ast, context) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.block, false, context); + }; + + PullTypeResolver.prototype.getEnclosingFunctionDeclaration = function (ast) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + + while (enclosingDecl) { + if (enclosingDecl.kind & 1032192 /* SomeFunction */) { + return enclosingDecl; + } + + enclosingDecl = enclosingDecl.getParentDecl(); + } + + return null; + }; + + PullTypeResolver.prototype.resolveReturnExpression = function (expression, enclosingFunction, context) { + if (enclosingFunction) { + enclosingFunction.setFlag(4194304 /* HasReturnStatement */); + } + + var isContextuallyTyped = false; + + if (enclosingFunction) { + var enclosingDeclAST = this.getASTForDecl(enclosingFunction); + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); + if (typeAnnotation) { + var returnTypeAnnotationSymbol = this.resolveTypeReference(typeAnnotation, context); + if (returnTypeAnnotationSymbol) { + isContextuallyTyped = true; + context.pushNewContextualType(returnTypeAnnotationSymbol); + } + } else { + var currentContextualType = context.getContextualType(); + if (currentContextualType && currentContextualType.isFunction()) { + var contextualSignatures = currentContextualType.kind == 33554432 /* ConstructorType */ ? currentContextualType.getConstructSignatures() : currentContextualType.getCallSignatures(); + var currentContextualTypeSignatureSymbol = contextualSignatures[0]; + + var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.returnType; + if (currentContextualTypeReturnTypeSymbol) { + isContextuallyTyped = true; + context.propagateContextualType(currentContextualTypeReturnTypeSymbol); + } + } + } + } + + var result = this.resolveAST(expression, isContextuallyTyped, context).type; + if (isContextuallyTyped) { + context.popAnyContextualType(); + } + + return result; + }; + + PullTypeResolver.prototype.typeCheckReturnExpression = function (expression, expressionType, enclosingFunction, context) { + if (enclosingFunction && enclosingFunction.kind === 32768 /* ConstructorMethod */) { + var classDecl = enclosingFunction.getParentDecl(); + if (classDecl) { + var classSymbol = classDecl.getSymbol(); + this.resolveDeclaredSymbol(classSymbol, context); + + var comparisonInfo = new TypeComparisonInfo(); + var isAssignable = this.sourceIsAssignableToTarget(expressionType, classSymbol.type, expression, context, comparisonInfo); + if (!isAssignable) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class)); + } + } + } + + if (enclosingFunction && enclosingFunction.kind === 524288 /* SetAccessor */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Setters_cannot_return_a_value)); + } + + if (enclosingFunction) { + var enclosingDeclAST = this.getASTForDecl(enclosingFunction); + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); + if (typeAnnotation || enclosingFunction.kind === 262144 /* GetAccessor */) { + var signatureSymbol = enclosingFunction.getSignatureSymbol(); + var sigReturnType = signatureSymbol.returnType; + + if (expressionType && sigReturnType) { + var comparisonInfo = new TypeComparisonInfo(); + var upperBound = null; + + this.resolveDeclaredSymbol(expressionType, context); + this.resolveDeclaredSymbol(sigReturnType, context); + + var isAssignable = this.sourceIsAssignableToTarget(expressionType, sigReturnType, expression, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(expression); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [expressionType.toString(enclosingSymbol), sigReturnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [expressionType.toString(enclosingSymbol), sigReturnType.toString(enclosingSymbol)])); + } + } + } + } + } + }; + + PullTypeResolver.prototype.resolveReturnStatement = function (returnAST, context) { + var enclosingFunction = this.getEnclosingFunctionDeclaration(returnAST); + if (enclosingFunction) { + enclosingFunction.setFlag(4194304 /* HasReturnStatement */); + } + + var returnType = this.getSymbolForAST(returnAST, context); + var canTypeCheckAST = this.canTypeCheckAST(returnAST, context); + if (!returnType || canTypeCheckAST) { + var returnExpr = returnAST.expression; + + var resolvedReturnType = returnExpr === null ? this.semanticInfoChain.voidTypeSymbol : this.resolveReturnExpression(returnExpr, enclosingFunction, context); + + if (!returnType) { + returnType = resolvedReturnType; + this.setSymbolForAST(returnAST, resolvedReturnType, context); + } + + if (returnExpr && canTypeCheckAST) { + this.setTypeChecked(returnExpr, context); + this.typeCheckReturnExpression(returnExpr, resolvedReturnType, enclosingFunction, context); + } + } + + return returnType; + }; + + PullTypeResolver.prototype.resolveSwitchStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckSwitchStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckSwitchStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + var expressionType = this.resolveAST(ast.expression, false, context).type; + + for (var i = 0, n = ast.switchClauses.childCount(); i < n; i++) { + var switchClause = ast.switchClauses.childAt(i); + if (switchClause.kind() === 233 /* CaseSwitchClause */) { + var caseSwitchClause = switchClause; + + var caseClauseExpressionType = this.resolveAST(caseSwitchClause.expression, false, context).type; + this.resolveAST(caseSwitchClause.statements, false, context); + + var comparisonInfo = new TypeComparisonInfo(); + if (!this.sourceIsAssignableToTarget(expressionType, caseClauseExpressionType, caseSwitchClause.expression, context, comparisonInfo) && !this.sourceIsAssignableToTarget(caseClauseExpressionType, expressionType, caseSwitchClause.expression, context, comparisonInfo)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(caseSwitchClause.expression); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(caseSwitchClause.expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [caseClauseExpressionType.toString(enclosingSymbol), expressionType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(caseSwitchClause.expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [caseClauseExpressionType.toString(enclosingSymbol), expressionType.toString(enclosingSymbol)])); + } + } + } else { + var defaultSwitchClause = switchClause; + this.resolveAST(defaultSwitchClause.statements, false, context); + } + } + }; + + PullTypeResolver.prototype.resolveLabeledStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckLabeledStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckLabeledStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + var labelIdentifier = ast.identifier.valueText(); + + var breakableLabels = this.getEnclosingLabels(ast, true, false); + + var matchingLabel = TypeScript.ArrayUtilities.firstOrDefault(breakableLabels, function (s) { + return s.identifier.valueText() === labelIdentifier; + }); + if (matchingLabel) { + context.postDiagnostic(this.semanticInfoChain.duplicateIdentifierDiagnosticFromAST(ast.identifier, labelIdentifier, matchingLabel)); + } + + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.labelIsOnContinuableConstruct = function (statement) { + switch (statement.kind()) { + case 160 /* LabeledStatement */: + return this.labelIsOnContinuableConstruct(statement.statement); + + case 158 /* WhileStatement */: + case 154 /* ForStatement */: + case 155 /* ForInStatement */: + case 161 /* DoStatement */: + return true; + + default: + return false; + } + }; + + PullTypeResolver.prototype.resolveContinueStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckContinueStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.isIterationStatement = function (ast) { + switch (ast.kind()) { + case 154 /* ForStatement */: + case 155 /* ForInStatement */: + case 158 /* WhileStatement */: + case 161 /* DoStatement */: + return true; + } + + return false; + }; + + PullTypeResolver.prototype.isAnyFunctionExpressionOrDeclaration = function (ast) { + switch (ast.kind()) { + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 129 /* FunctionDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 241 /* FunctionPropertyAssignment */: + case 137 /* ConstructorDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + return true; + } + + return false; + }; + + PullTypeResolver.prototype.inSwitchStatement = function (ast) { + while (ast) { + if (ast.kind() === 151 /* SwitchStatement */) { + return true; + } + + if (this.isAnyFunctionExpressionOrDeclaration(ast)) { + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inIterationStatement = function (ast, crossFunctions) { + while (ast) { + if (this.isIterationStatement(ast)) { + return true; + } + + if (!crossFunctions && this.isAnyFunctionExpressionOrDeclaration(ast)) { + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.getEnclosingLabels = function (ast, breakable, crossFunctions) { + var result = []; + + ast = ast.parent; + while (ast) { + if (ast.kind() === 160 /* LabeledStatement */) { + var labeledStatement = ast; + if (breakable) { + result.push(labeledStatement); + } else { + if (this.labelIsOnContinuableConstruct(labeledStatement.statement)) { + result.push(labeledStatement); + } + } + } + + if (!crossFunctions && this.isAnyFunctionExpressionOrDeclaration(ast)) { + break; + } + + ast = ast.parent; + } + + return result; + }; + + PullTypeResolver.prototype.typeCheckContinueStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + if (!this.inIterationStatement(ast, false)) { + if (this.inIterationStatement(ast, true)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.continue_statement_can_only_be_used_within_an_enclosing_iteration_statement)); + } + } else if (ast.identifier) { + var continuableLabels = this.getEnclosingLabels(ast, false, false); + + if (!TypeScript.ArrayUtilities.any(continuableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + var continuableLabels = this.getEnclosingLabels(ast, false, true); + + if (TypeScript.ArrayUtilities.any(continuableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_not_found)); + } + } + } + }; + + PullTypeResolver.prototype.resolveBreakStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckBreakStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckBreakStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + if (ast.identifier) { + var breakableLabels = this.getEnclosingLabels(ast, true, false); + + if (!TypeScript.ArrayUtilities.any(breakableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + var breakableLabels = this.getEnclosingLabels(ast, true, true); + if (TypeScript.ArrayUtilities.any(breakableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_not_found)); + } + } + } else if (!this.inIterationStatement(ast, false) && !this.inSwitchStatement(ast)) { + if (this.inIterationStatement(ast, true)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement)); + } + } + }; + + PullTypeResolver.prototype.resolveAST = function (ast, isContextuallyTyped, context) { + if (!ast) { + return; + } + + var symbol = this.getSymbolForAST(ast, context); + if (symbol && symbol.isResolved) { + this.typeCheckAST(ast, isContextuallyTyped, context); + return symbol; + } + + if (ast.isExpression() && !isTypesOnlyLocation(ast)) { + return this.resolveExpressionAST(ast, isContextuallyTyped, context); + } + + var nodeType = ast.kind(); + + switch (nodeType) { + case 124 /* ArrayType */: + case 126 /* GenericType */: + case 122 /* ObjectType */: + case 127 /* TypeQuery */: + case 125 /* ConstructorType */: + case 123 /* FunctionType */: + return this.resolveTypeReference(ast, context); + + case 1 /* List */: + return this.resolveList(ast, context); + + case 2 /* SeparatedList */: + return this.resolveSeparatedList(ast, context); + + case 120 /* SourceUnit */: + return this.resolveSourceUnit(ast, context); + + case 132 /* EnumDeclaration */: + return this.resolveEnumDeclaration(ast, context); + + case 130 /* ModuleDeclaration */: + return this.resolveModuleDeclaration(ast, context); + + case 128 /* InterfaceDeclaration */: + return this.resolveInterfaceDeclaration(ast, context); + + case 131 /* ClassDeclaration */: + return this.resolveClassDeclaration(ast, context); + + case 224 /* VariableDeclaration */: + return this.resolveVariableDeclarationList(ast, context); + + case 136 /* MemberVariableDeclaration */: + return this.resolveMemberVariableDeclaration(ast, context); + + case 225 /* VariableDeclarator */: + return this.resolveVariableDeclarator(ast, context); + + case 141 /* PropertySignature */: + return this.resolvePropertySignature(ast, context); + + case 227 /* ParameterList */: + return this.resolveParameterList(ast, context); + + case 242 /* Parameter */: + return this.resolveParameter(ast, context); + + case 243 /* EnumElement */: + return this.resolveEnumElement(ast, context); + + case 232 /* EqualsValueClause */: + return this.resolveEqualsValueClause(ast, isContextuallyTyped, context); + + case 238 /* TypeParameter */: + return this.resolveTypeParameterDeclaration(ast, context); + + case 239 /* Constraint */: + return this.resolveConstraint(ast, context); + + case 133 /* ImportDeclaration */: + return this.resolveImportDeclaration(ast, context); + + case 240 /* SimplePropertyAssignment */: + return this.resolveSimplePropertyAssignment(ast, isContextuallyTyped, context); + + case 241 /* FunctionPropertyAssignment */: + return this.resolveFunctionPropertyAssignment(ast, isContextuallyTyped, context); + + case 11 /* IdentifierName */: + TypeScript.Debug.assert(isTypesOnlyLocation(ast)); + return this.resolveTypeNameExpression(ast, context); + + case 121 /* QualifiedName */: + return this.resolveQualifiedName(ast, context); + + case 137 /* ConstructorDeclaration */: + return this.resolveConstructorDeclaration(ast, context); + + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + return this.resolveAccessorDeclaration(ast, context); + + case 138 /* IndexMemberDeclaration */: + return this.resolveIndexMemberDeclaration(ast, context); + + case 144 /* IndexSignature */: + return this.resolveIndexSignature(ast, context); + + case 135 /* MemberFunctionDeclaration */: + return this.resolveMemberFunctionDeclaration(ast, context); + + case 142 /* CallSignature */: + return this.resolveCallSignature(ast, context); + + case 143 /* ConstructSignature */: + return this.resolveConstructSignature(ast, context); + + case 145 /* MethodSignature */: + return this.resolveMethodSignature(ast, context); + + case 129 /* FunctionDeclaration */: + return this.resolveAnyFunctionDeclaration(ast, context); + + case 244 /* TypeAnnotation */: + return this.resolveTypeAnnotation(ast, context); + + case 134 /* ExportAssignment */: + return this.resolveExportAssignmentStatement(ast, context); + + case 157 /* ThrowStatement */: + return this.resolveThrowStatement(ast, context); + + case 149 /* ExpressionStatement */: + return this.resolveExpressionStatement(ast, context); + + case 154 /* ForStatement */: + return this.resolveForStatement(ast, context); + + case 155 /* ForInStatement */: + return this.resolveForInStatement(ast, context); + + case 158 /* WhileStatement */: + return this.resolveWhileStatement(ast, context); + + case 161 /* DoStatement */: + return this.resolveDoStatement(ast, context); + + case 147 /* IfStatement */: + return this.resolveIfStatement(ast, context); + + case 235 /* ElseClause */: + return this.resolveElseClause(ast, context); + + case 146 /* Block */: + return this.resolveBlock(ast, context); + + case 148 /* VariableStatement */: + return this.resolveVariableStatement(ast, context); + + case 163 /* WithStatement */: + return this.resolveWithStatement(ast, context); + + case 159 /* TryStatement */: + return this.resolveTryStatement(ast, context); + + case 236 /* CatchClause */: + return this.resolveCatchClause(ast, context); + + case 237 /* FinallyClause */: + return this.resolveFinallyClause(ast, context); + + case 150 /* ReturnStatement */: + return this.resolveReturnStatement(ast, context); + + case 151 /* SwitchStatement */: + return this.resolveSwitchStatement(ast, context); + + case 153 /* ContinueStatement */: + return this.resolveContinueStatement(ast, context); + + case 152 /* BreakStatement */: + return this.resolveBreakStatement(ast, context); + + case 160 /* LabeledStatement */: + return this.resolveLabeledStatement(ast, context); + } + + return this.semanticInfoChain.anyTypeSymbol; + }; + + PullTypeResolver.prototype.resolveExpressionAST = function (ast, isContextuallyOrInferentiallyTyped, context) { + var expressionSymbol = this.resolveExpressionWorker(ast, isContextuallyOrInferentiallyTyped, context); + + if (isContextuallyOrInferentiallyTyped && context.isInferentiallyTyping()) { + return this.alterPotentialGenericFunctionTypeToInstantiatedFunctionTypeForTypeArgumentInference(expressionSymbol, context); + } else { + return expressionSymbol; + } + }; + + PullTypeResolver.prototype.resolveExpressionWorker = function (ast, isContextuallyTyped, context) { + switch (ast.kind()) { + case 215 /* ObjectLiteralExpression */: + return this.resolveObjectLiteralExpression(ast, isContextuallyTyped, context); + + case 11 /* IdentifierName */: + return this.resolveNameExpression(ast, context); + + case 212 /* MemberAccessExpression */: + return this.resolveMemberAccessExpression(ast, context); + + case 222 /* FunctionExpression */: + return this.resolveFunctionExpression(ast, isContextuallyTyped, context); + + case 219 /* SimpleArrowFunctionExpression */: + return this.resolveSimpleArrowFunctionExpression(ast, isContextuallyTyped, context); + + case 218 /* ParenthesizedArrowFunctionExpression */: + return this.resolveParenthesizedArrowFunctionExpression(ast, isContextuallyTyped, context); + + case 214 /* ArrayLiteralExpression */: + return this.resolveArrayLiteralExpression(ast, isContextuallyTyped, context); + + case 35 /* ThisKeyword */: + return this.resolveThisExpression(ast, context); + + case 50 /* SuperKeyword */: + return this.resolveSuperExpression(ast, context); + + case 213 /* InvocationExpression */: + return this.resolveInvocationExpression(ast, context); + + case 216 /* ObjectCreationExpression */: + return this.resolveObjectCreationExpression(ast, context); + + case 220 /* CastExpression */: + return this.resolveCastExpression(ast, context); + + case 13 /* NumericLiteral */: + return this.semanticInfoChain.numberTypeSymbol; + + case 14 /* StringLiteral */: + return this.semanticInfoChain.stringTypeSymbol; + + case 32 /* NullKeyword */: + return this.semanticInfoChain.nullTypeSymbol; + + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return this.semanticInfoChain.booleanTypeSymbol; + + case 172 /* VoidExpression */: + return this.resolveVoidExpression(ast, context); + + case 174 /* AssignmentExpression */: + return this.resolveAssignmentExpression(ast, context); + + case 167 /* LogicalNotExpression */: + return this.resolveLogicalNotExpression(ast, context); + + case 193 /* NotEqualsWithTypeConversionExpression */: + case 192 /* EqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + case 196 /* LessThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 197 /* GreaterThanExpression */: + return this.resolveLogicalOperation(ast, context); + + case 208 /* AddExpression */: + case 175 /* AddAssignmentExpression */: + return this.resolveBinaryAdditionOperation(ast, context); + + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + case 166 /* BitwiseNotExpression */: + case 168 /* PreIncrementExpression */: + case 169 /* PreDecrementExpression */: + return this.resolveUnaryArithmeticOperation(ast, context); + + case 210 /* PostIncrementExpression */: + case 211 /* PostDecrementExpression */: + return this.resolvePostfixUnaryExpression(ast, context); + + case 209 /* SubtractExpression */: + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + case 189 /* BitwiseOrExpression */: + case 191 /* BitwiseAndExpression */: + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + case 190 /* BitwiseExclusiveOrExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + return this.resolveBinaryArithmeticExpression(ast, context); + + case 221 /* ElementAccessExpression */: + return this.resolveElementAccessExpression(ast, context); + + case 187 /* LogicalOrExpression */: + return this.resolveLogicalOrExpression(ast, isContextuallyTyped, context); + + case 188 /* LogicalAndExpression */: + return this.resolveLogicalAndExpression(ast, context); + + case 171 /* TypeOfExpression */: + return this.resolveTypeOfExpression(ast, context); + + case 170 /* DeleteExpression */: + return this.resolveDeleteExpression(ast, context); + + case 186 /* ConditionalExpression */: + return this.resolveConditionalExpression(ast, isContextuallyTyped, context); + + case 12 /* RegularExpressionLiteral */: + return this.resolveRegularExpressionLiteral(); + + case 217 /* ParenthesizedExpression */: + return this.resolveParenthesizedExpression(ast, context); + + case 200 /* InstanceOfExpression */: + return this.resolveInstanceOfExpression(ast, context); + + case 173 /* CommaExpression */: + return this.resolveCommaExpression(ast, context); + + case 201 /* InExpression */: + return this.resolveInExpression(ast, context); + + case 223 /* OmittedExpression */: + return this.semanticInfoChain.undefinedTypeSymbol; + } + + TypeScript.Debug.fail("resolveExpressionASTWorker: Missing expression kind: " + TypeScript.SyntaxKind[ast.kind()]); + }; + + PullTypeResolver.prototype.typeCheckAST = function (ast, isContextuallyTyped, context) { + if (!this.canTypeCheckAST(ast, context)) { + return; + } + + var nodeType = ast.kind(); + switch (nodeType) { + case 120 /* SourceUnit */: + this.typeCheckSourceUnit(ast, context); + return; + + case 132 /* EnumDeclaration */: + this.typeCheckEnumDeclaration(ast, context); + return; + + case 130 /* ModuleDeclaration */: + this.typeCheckModuleDeclaration(ast, context); + return; + + case 128 /* InterfaceDeclaration */: + this.typeCheckInterfaceDeclaration(ast, context); + return; + + case 131 /* ClassDeclaration */: + this.typeCheckClassDeclaration(ast, context); + return; + + case 243 /* EnumElement */: + this.typeCheckEnumElement(ast, context); + return; + + case 136 /* MemberVariableDeclaration */: + this.typeCheckMemberVariableDeclaration(ast, context); + return; + + case 225 /* VariableDeclarator */: + this.typeCheckVariableDeclarator(ast, context); + return; + + case 141 /* PropertySignature */: + this.typeCheckPropertySignature(ast, context); + return; + + case 242 /* Parameter */: + this.typeCheckParameter(ast, context); + return; + + case 133 /* ImportDeclaration */: + this.typeCheckImportDeclaration(ast, context); + return; + + case 215 /* ObjectLiteralExpression */: + this.resolveObjectLiteralExpression(ast, isContextuallyTyped, context); + return; + + case 241 /* FunctionPropertyAssignment */: + this.typeCheckFunctionPropertyAssignment(ast, isContextuallyTyped, context); + return; + + case 11 /* IdentifierName */: + if (isTypesOnlyLocation(ast)) { + this.resolveTypeNameExpression(ast, context); + } else { + this.resolveNameExpression(ast, context); + } + return; + + case 212 /* MemberAccessExpression */: + this.resolveMemberAccessExpression(ast, context); + return; + + case 121 /* QualifiedName */: + this.resolveQualifiedName(ast, context); + return; + + case 222 /* FunctionExpression */: + this.typeCheckFunctionExpression(ast, isContextuallyTyped, context); + return; + + case 137 /* ConstructorDeclaration */: + this.typeCheckConstructorDeclaration(ast, context); + return; + + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + this.typeCheckAccessorDeclaration(ast, context); + return; + + case 135 /* MemberFunctionDeclaration */: + this.typeCheckMemberFunctionDeclaration(ast, context); + return; + + case 145 /* MethodSignature */: + this.typeCheckMethodSignature(ast, context); + return; + + case 144 /* IndexSignature */: + this.typeCheckIndexSignature(ast, context); + break; + + case 142 /* CallSignature */: + this.typeCheckCallSignature(ast, context); + return; + + case 143 /* ConstructSignature */: + this.typeCheckConstructSignature(ast, context); + return; + + case 129 /* FunctionDeclaration */: { + var funcDecl = ast; + this.typeCheckAnyFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + return; + } + + case 219 /* SimpleArrowFunctionExpression */: + this.typeCheckSimpleArrowFunctionExpression(ast, isContextuallyTyped, context); + return; + + case 218 /* ParenthesizedArrowFunctionExpression */: + this.typeCheckParenthesizedArrowFunctionExpression(ast, isContextuallyTyped, context); + return; + + case 214 /* ArrayLiteralExpression */: + this.resolveArrayLiteralExpression(ast, isContextuallyTyped, context); + return; + + case 213 /* InvocationExpression */: + this.typeCheckInvocationExpression(ast, context); + return; + + case 216 /* ObjectCreationExpression */: + this.typeCheckObjectCreationExpression(ast, context); + return; + + case 150 /* ReturnStatement */: + this.resolveReturnStatement(ast, context); + return; + + default: + TypeScript.Debug.assert(false, "Failure nodeType: " + TypeScript.SyntaxKind[ast.kind()] + ". Implement typeCheck when symbol is set for the ast as part of resolution."); + } + }; + + PullTypeResolver.prototype.processPostTypeCheckWorkItems = function (context) { + while (this.postTypeCheckWorkitems.length) { + var ast = this.postTypeCheckWorkitems.pop(); + this.postTypeCheck(ast, context); + } + }; + + PullTypeResolver.prototype.postTypeCheck = function (ast, context) { + var nodeType = ast.kind(); + + switch (nodeType) { + case 242 /* Parameter */: + case 225 /* VariableDeclarator */: + this.postTypeCheckVariableDeclaratorOrParameter(ast, context); + return; + + case 131 /* ClassDeclaration */: + this.postTypeCheckClassDeclaration(ast, context); + return; + + case 129 /* FunctionDeclaration */: + this.postTypeCheckFunctionDeclaration(ast, context); + return; + + case 130 /* ModuleDeclaration */: + this.postTypeCheckModuleDeclaration(ast, context); + return; + + case 132 /* EnumDeclaration */: + this.postTypeCheckEnumDeclaration(ast, context); + return; + + case 133 /* ImportDeclaration */: + this.postTypeCheckImportDeclaration(ast, context); + return; + + case 11 /* IdentifierName */: + this.postTypeCheckNameExpression(ast, context); + return; + + default: + TypeScript.Debug.assert(false, "Implement postTypeCheck clause to handle the postTypeCheck work, nodeType: " + TypeScript.SyntaxKind[ast.kind()]); + } + }; + + PullTypeResolver.prototype.resolveRegularExpressionLiteral = function () { + if (this.cachedRegExpInterfaceType()) { + return this.cachedRegExpInterfaceType(); + } else { + return this.semanticInfoChain.anyTypeSymbol; + } + }; + + PullTypeResolver.prototype.postTypeCheckNameExpression = function (nameAST, context) { + this.checkThisCaptureVariableCollides(nameAST, false, context); + }; + + PullTypeResolver.prototype.typeCheckNameExpression = function (nameAST, context) { + this.setTypeChecked(nameAST, context); + this.checkNameForCompilerGeneratedDeclarationCollision(nameAST, false, nameAST, context); + }; + + PullTypeResolver.prototype.resolveNameExpression = function (nameAST, context) { + var nameSymbol = this.getSymbolForAST(nameAST, context); + var foundCached = nameSymbol !== null; + + if (!foundCached || this.canTypeCheckAST(nameAST, context)) { + if (this.canTypeCheckAST(nameAST, context)) { + this.typeCheckNameExpression(nameAST, context); + } + nameSymbol = this.computeNameExpression(nameAST, context); + } + + this.resolveDeclaredSymbol(nameSymbol, context); + + if (nameSymbol && (nameSymbol.type !== this.semanticInfoChain.anyTypeSymbol || nameSymbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { + this.setSymbolForAST(nameAST, nameSymbol, context); + } + + return nameSymbol; + }; + + PullTypeResolver.prototype.isInEnumDecl = function (decl) { + if (decl.kind & 64 /* Enum */) { + return true; + } + + var declPath = decl.getParentPath(); + + var disallowedKinds = 164 /* SomeContainer */ | 58728795 /* SomeType */; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + + if (decl.kind & 64 /* Enum */) { + return true; + } + + if (decl.kind & disallowedKinds) { + return false; + } + } + return false; + }; + + PullTypeResolver.prototype.getSomeInnermostFunctionScopeDecl = function (declPath) { + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + if (decl.kind & 1032192 /* SomeFunction */) { + return decl; + } + } + + return null; + }; + + PullTypeResolver.prototype.isFromFunctionScope = function (nameSymbol, functionScopeDecl) { + var _this = this; + return TypeScript.ArrayUtilities.any(nameSymbol.getDeclarations(), function (nameSymbolDecl) { + return _this.getSomeInnermostFunctionScopeDecl(nameSymbolDecl.getParentPath()) === functionScopeDecl; + }); + }; + + PullTypeResolver.prototype.findConstructorDeclOfEnclosingType = function (decl) { + var current = decl; + while (current) { + if (TypeScript.hasFlag(current.kind, 4096 /* Property */)) { + var parentDecl = current.getParentDecl(); + if (TypeScript.hasFlag(parentDecl.kind, 8 /* Class */)) { + return TypeScript.ArrayUtilities.lastOrDefault(parentDecl.getChildDecls(), function (decl) { + return TypeScript.hasFlag(decl.kind, 32768 /* ConstructorMethod */); + }); + } + } + + if (TypeScript.hasFlag(current.kind, 164 /* SomeContainer */)) { + return null; + } + + current = current.getParentDecl(); + } + return null; + }; + + PullTypeResolver.prototype.checkNameAsPartOfInitializerExpressionForInstanceMemberVariable = function (nameAST, nameSymbol, context) { + var id = nameAST.valueText(); + if (id.length === 0) { + return false; + } + + var memberVariableDeclarationAST = TypeScript.ASTHelpers.getEnclosingMemberVariableDeclaration(nameAST); + if (memberVariableDeclarationAST) { + var memberVariableDecl = this.semanticInfoChain.getDeclForAST(memberVariableDeclarationAST); + if (!TypeScript.hasFlag(memberVariableDecl.flags, 16 /* Static */)) { + var constructorDecl = this.findConstructorDeclOfEnclosingType(memberVariableDecl); + + if (constructorDecl) { + var childDecls = constructorDecl.searchChildDecls(id, 68147712 /* SomeValue */); + if (childDecls.length) { + if (TypeScript.PullHelpers.isSymbolDeclaredInScopeChain(nameSymbol, constructorDecl.getSymbol().getContainer())) { + var memberVariableSymbol = memberVariableDecl.getSymbol(); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, [memberVariableSymbol.getScopedName(constructorDecl.getSymbol()), nameAST.text()])); + return true; + } + } + } + } + } + return false; + }; + + PullTypeResolver.prototype.computeNameExpression = function (nameAST, context) { + var id = nameAST.valueText(); + if (id.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var nameSymbol = null; + var enclosingDecl = this.getEnclosingDeclForAST(nameAST); + + if (TypeScript.hasFlag(enclosingDecl.flags, 8388608 /* PropertyParameter */)) { + var valueDecl = enclosingDecl.getValueDecl(); + if (valueDecl && TypeScript.hasFlag(valueDecl.kind, 2048 /* Parameter */)) { + enclosingDecl = valueDecl; + } + } + + var isDeclarationASTOrDeclarationNameAST = TypeScript.ASTHelpers.isDeclarationASTOrDeclarationNameAST(nameAST); + if (isDeclarationASTOrDeclarationNameAST) { + nameSymbol = this.semanticInfoChain.getDeclForAST(nameAST.parent).getSymbol(); + } + + var declPath = enclosingDecl.getParentPath(); + + if (!nameSymbol) { + var searchKind = 68147712 /* SomeValue */; + + if (!this.isInEnumDecl(enclosingDecl)) { + searchKind = searchKind & ~(67108864 /* EnumMember */); + } + + var nameSymbol = this.getSymbolFromDeclPath(id, declPath, searchKind); + } + + if (id === "arguments") { + var functionScopeDecl = this.getSomeInnermostFunctionScopeDecl(declPath); + if (functionScopeDecl) { + if (!nameSymbol || !this.isFromFunctionScope(nameSymbol, functionScopeDecl)) { + nameSymbol = this.cachedFunctionArgumentsSymbol(); + this.resolveDeclaredSymbol(this.cachedIArgumentsInterfaceType(), context); + } + } + } + + var aliasSymbol = null; + if (nameSymbol && nameSymbol.isAlias() && !isDeclarationASTOrDeclarationNameAST) { + aliasSymbol = nameSymbol; + if (!this.inTypeQuery(nameAST)) { + aliasSymbol.setIsUsedAsValue(); + } + + this.resolveDeclaredSymbol(nameSymbol, context); + + this.resolveDeclaredSymbol(aliasSymbol.assignedValue(), context); + this.resolveDeclaredSymbol(aliasSymbol.assignedContainer(), context); + + nameSymbol = aliasSymbol.getExportAssignedValueSymbol(); + if (!nameSymbol) { + aliasSymbol = null; + } + } + + if (!nameSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [nameAST.text()])); + return this.getNewErrorTypeSymbol(id); + } else if (this.checkNameAsPartOfInitializerExpressionForInstanceMemberVariable(nameAST, nameSymbol, context)) { + return this.getNewErrorTypeSymbol(id); + } + + var nameDeclaration = nameSymbol.getDeclarations()[0]; + var nameParentDecl = nameDeclaration.getParentDecl(); + if (nameParentDecl && (nameParentDecl.kind & 1032192 /* SomeFunction */) && (nameParentDecl.flags & 33554432 /* HasDefaultArgs */)) { + var enclosingFunctionAST = this.semanticInfoChain.getASTForDecl(nameParentDecl); + var currentParameterIndex = this.getCurrentParameterIndexForFunction(nameAST, enclosingFunctionAST); + + var parameterList = TypeScript.ASTHelpers.getParameterList(enclosingFunctionAST); + + if (currentParameterIndex >= 0) { + var matchingParameter; + if (parameterList) { + for (var i = 0; i <= currentParameterIndex; i++) { + var candidateParameter = parameterList.parameters.nonSeparatorAt(i); + if (candidateParameter && candidateParameter.identifier.valueText() === id) { + matchingParameter = candidateParameter; + break; + } + } + } + + if (!matchingParameter) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, [parameterList.parameters.nonSeparatorAt(currentParameterIndex).identifier.text(), nameAST.text()])); + return this.getNewErrorTypeSymbol(id); + } else if (matchingParameter === TypeScript.ASTHelpers.getEnclosingParameterForInitializer(nameAST)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Parameter_0_cannot_be_referenced_in_its_initializer, [parameterList.parameters.nonSeparatorAt(currentParameterIndex).identifier.text()])); + return this.getNewErrorTypeSymbol(id); + } + } + } + + if (aliasSymbol) { + this.semanticInfoChain.setAliasSymbolForAST(nameAST, aliasSymbol); + } + + return nameSymbol; + }; + + PullTypeResolver.prototype.getCurrentParameterIndexForFunction = function (parameter, funcDecl) { + var parameterList = TypeScript.ASTHelpers.getParameterList(funcDecl); + if (parameterList) { + while (parameter && parameter.parent) { + if (parameter.parent.parent === parameterList) { + return parameterList.parameters.nonSeparatorIndexOf(parameter); + } + + parameter = parameter.parent; + } + } + + return -1; + }; + + PullTypeResolver.prototype.resolveMemberAccessExpression = function (dottedNameAST, context) { + return this.resolveDottedNameExpression(dottedNameAST, dottedNameAST.expression, dottedNameAST.name, context); + }; + + PullTypeResolver.prototype.resolveDottedNameExpression = function (dottedNameAST, expression, name, context) { + var symbol = this.getSymbolForAST(dottedNameAST, context); + var foundCached = symbol !== null; + + if (!foundCached || this.canTypeCheckAST(dottedNameAST, context)) { + var canTypeCheckDottedNameAST = this.canTypeCheckAST(dottedNameAST, context); + if (canTypeCheckDottedNameAST) { + this.setTypeChecked(dottedNameAST, context); + } + + symbol = this.computeDottedNameExpression(expression, name, context, canTypeCheckDottedNameAST); + } + + this.resolveDeclaredSymbol(symbol, context); + + if (symbol && (symbol.type !== this.semanticInfoChain.anyTypeSymbol || symbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { + this.setSymbolForAST(dottedNameAST, symbol, context); + this.setSymbolForAST(name, symbol, context); + } + + return symbol; + }; + + PullTypeResolver.prototype.computeDottedNameExpression = function (expression, name, context, checkSuperPrivateAndStaticAccess) { + var rhsName = name.valueText(); + if (rhsName.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var lhs = this.resolveAST(expression, false, context); + return this.computeDottedNameExpressionFromLHS(lhs, expression, name, context, checkSuperPrivateAndStaticAccess); + }; + + PullTypeResolver.prototype.computeDottedNameExpressionFromLHS = function (lhs, expression, name, context, checkSuperPrivateAndStaticAccess) { + var rhsName = name.valueText(); + if (rhsName.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var lhsType = lhs.type; + + if (lhs.isAlias()) { + var lhsAlias = lhs; + if (!this.inTypeQuery(expression)) { + lhsAlias.setIsUsedAsValue(); + } + lhsType = lhsAlias.getExportAssignedTypeSymbol(); + } + + if (lhsType.isAlias()) { + lhsType = lhsType.getExportAssignedTypeSymbol(); + } + + if (!lhsType) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.Could_not_find_enclosing_symbol_for_dotted_name_0, [name.text()])); + return this.getNewErrorTypeSymbol(); + } + + if (!lhsType.isResolved) { + var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, context); + + if (potentiallySpecializedType !== lhsType) { + if (!lhs.isType()) { + context.setTypeInContext(lhs, potentiallySpecializedType); + } + + lhsType = potentiallySpecializedType; + } + } + + if (lhsType.isContainer() && !lhsType.isAlias() && !lhsType.isEnum()) { + var instanceSymbol = lhsType.getInstanceSymbol(); + + if (instanceSymbol) { + lhsType = instanceSymbol.type; + } + } + + var originalLhsTypeForErrorReporting = lhsType; + + lhsType = this.getApparentType(lhsType).widenedType(this, expression, context); + + if (this.isAnyOrEquivalent(lhsType)) { + return lhsType; + } + + var nameSymbol = this._getNamedPropertySymbolOfAugmentedType(rhsName, lhsType); + + if (!nameSymbol) { + if (lhsType.kind === 32 /* DynamicModule */) { + var container = lhsType; + var associatedInstance = container.getInstanceSymbol(); + + if (associatedInstance) { + var instanceType = associatedInstance.type; + + nameSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, instanceType); + } + } else { + var associatedType = lhsType.getAssociatedContainerType(); + + if (associatedType && !associatedType.isClass()) { + nameSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, associatedType); + } + } + + if (!nameSymbol) { + var enclosingDecl = this.getEnclosingDeclForAST(expression); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.The_property_0_does_not_exist_on_value_of_type_1, [name.text(), originalLhsTypeForErrorReporting.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + return this.getNewErrorTypeSymbol(rhsName); + } + } + + if (checkSuperPrivateAndStaticAccess) { + this.checkForSuperMemberAccess(expression, name, nameSymbol, context) || this.checkForPrivateMemberAccess(name, lhsType, nameSymbol, context); + } + + return nameSymbol; + }; + + PullTypeResolver.prototype.resolveTypeNameExpression = function (nameAST, context) { + var typeNameSymbol = this.getSymbolForAST(nameAST, context); + + if (!typeNameSymbol || !typeNameSymbol.isType() || this.canTypeCheckAST(nameAST, context)) { + if (this.canTypeCheckAST(nameAST, context)) { + this.setTypeChecked(nameAST, context); + } + typeNameSymbol = this.computeTypeNameExpression(nameAST, context); + this.setSymbolForAST(nameAST, typeNameSymbol, context); + } + + this.resolveDeclaredSymbol(typeNameSymbol, context); + + return typeNameSymbol; + }; + + PullTypeResolver.prototype.computeTypeNameExpression = function (nameAST, context) { + var id = nameAST.valueText(); + if (id.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var enclosingDecl = this.getEnclosingDeclForAST(nameAST); + + var declPath = enclosingDecl.getParentPath(); + + var onLeftOfDot = this.isLeftSideOfQualifiedName(nameAST); + + var kindToCheckFirst = onLeftOfDot ? 164 /* SomeContainer */ : 58728795 /* SomeType */; + var kindToCheckSecond = onLeftOfDot ? 58728795 /* SomeType */ : 164 /* SomeContainer */; + + var typeNameSymbol = this.getSymbolFromDeclPath(id, declPath, kindToCheckFirst); + + if (!typeNameSymbol) { + typeNameSymbol = this.getSymbolFromDeclPath(id, declPath, kindToCheckSecond); + } + + if (!typeNameSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [nameAST.text()])); + return this.getNewErrorTypeSymbol(id); + } + + var typeNameSymbolAlias = null; + if (typeNameSymbol.isAlias()) { + typeNameSymbolAlias = typeNameSymbol; + this.resolveDeclaredSymbol(typeNameSymbol, context); + + var aliasedType = typeNameSymbolAlias.getExportAssignedTypeSymbol(); + + this.resolveDeclaredSymbol(aliasedType, context); + } + + if (typeNameSymbol.isTypeParameter()) { + if (this.isInStaticMemberContext(enclosingDecl)) { + var parentDecl = typeNameSymbol.getDeclarations()[0].getParentDecl(); + + if (parentDecl.kind === 8 /* Class */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Static_members_cannot_reference_class_type_parameters)); + return this.getNewErrorTypeSymbol(); + } + } + } + + if (!typeNameSymbol.isGeneric() && (typeNameSymbol.isClass() || typeNameSymbol.isInterface())) { + typeNameSymbol = TypeScript.PullTypeReferenceSymbol.createTypeReference(typeNameSymbol); + } + + return typeNameSymbol; + }; + + PullTypeResolver.prototype.isInStaticMemberContext = function (decl) { + while (decl) { + if (TypeScript.hasFlag(decl.kind, 1032192 /* SomeFunction */ | 4096 /* Property */) && TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + return true; + } + + if (TypeScript.hasFlag(decl.kind, 164 /* SomeContainer */)) { + return false; + } + + decl = decl.getParentDecl(); + } + + return false; + }; + + PullTypeResolver.prototype.isLeftSideOfQualifiedName = function (ast) { + return ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.left === ast; + }; + + PullTypeResolver.prototype.resolveGenericTypeReference = function (genericTypeAST, context) { + var _this = this; + var genericTypeSymbol = this.resolveAST(genericTypeAST.name, false, context).type; + + if (genericTypeSymbol.isError()) { + return genericTypeSymbol; + } + + if (!genericTypeSymbol.inResolution && !genericTypeSymbol.isResolved) { + this.resolveDeclaredSymbol(genericTypeSymbol, context); + } + + if (genericTypeSymbol.isAlias()) { + if (this.inClassExtendsHeritageClause(genericTypeAST) && !this.inTypeArgumentList(genericTypeAST)) { + genericTypeSymbol.setIsUsedAsValue(); + } + genericTypeSymbol = genericTypeSymbol.getExportAssignedTypeSymbol(); + } + + var typeParameters = genericTypeSymbol.getTypeParameters(); + if (typeParameters.length === 0) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Type_0_does_not_have_type_parameters, [genericTypeSymbol.toString()])); + return this.getNewErrorTypeSymbol(); + } + + var typeArgs = []; + + if (genericTypeAST.typeArgumentList && genericTypeAST.typeArgumentList.typeArguments.nonSeparatorCount()) { + for (var i = 0; i < genericTypeAST.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { + typeArgs[i] = this.resolveTypeReference(genericTypeAST.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + + if (typeArgs[i].isError()) { + typeArgs[i] = this.semanticInfoChain.anyTypeSymbol; + } + } + } + + if (typeArgs.length && typeArgs.length !== typeParameters.length) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Generic_type_0_requires_1_type_argument_s, [genericTypeSymbol.toString(), genericTypeSymbol.getTypeParameters().length])); + return this.getNewErrorTypeSymbol(); + } + + if (!genericTypeSymbol.isResolved) { + var typeDecls = genericTypeSymbol.getDeclarations(); + var childDecls = null; + + for (var i = 0; i < typeDecls.length; i++) { + childDecls = typeDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + } + + var specializedSymbol = this.createInstantiatedType(genericTypeSymbol, typeArgs); + + var upperBound = null; + + typeParameters = specializedSymbol.getTypeParameters(); + + var typeConstraintSubstitutionMap = []; + + var instantiatedSubstitutionMap = specializedSymbol.getTypeParameterArgumentMap(); + + for (var i = 0; i < typeParameters.length; i++) { + typeConstraintSubstitutionMap[typeParameters[i].pullSymbolID] = typeParameters[i]; + } + + for (var id in instantiatedSubstitutionMap) { + typeConstraintSubstitutionMap[id] = instantiatedSubstitutionMap[id]; + } + + for (var iArg = 0; (iArg < typeArgs.length) && (iArg < typeParameters.length); iArg++) { + var typeArg = typeArgs[iArg]; + var typeParameter = typeParameters[iArg]; + var typeConstraint = typeParameter.getConstraint(); + + typeConstraintSubstitutionMap[typeParameter.pullSymbolID] = typeArg; + + if (typeConstraint) { + if (typeConstraint.isTypeParameter()) { + for (var j = 0; j < typeParameters.length && j < typeArgs.length; j++) { + if (typeParameters[j] === typeConstraint) { + typeConstraint = typeArgs[j]; + } + } + } else if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeConstraintSubstitutionMap); + } + + if (typeArg.isTypeParameter()) { + upperBound = typeArg.getConstraint(); + + if (upperBound) { + typeArg = upperBound; + } + } + + if (typeArg.inResolution || (typeArg.isTypeReference() && typeArg.referencedTypeSymbol.inResolution)) { + return specializedSymbol; + } + + if (context.canTypeCheckAST(genericTypeAST)) { + this.typeCheckCallBacks.push(function (context) { + if (!_this.sourceIsAssignableToTarget(typeArg, typeConstraint, genericTypeAST, context)) { + var enclosingSymbol = _this.getEnclosingSymbolForAST(genericTypeAST); + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [typeArg.toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameter.toString(enclosingSymbol, true)])); + } + }); + } + } + } + + return specializedSymbol; + }; + + PullTypeResolver.prototype.resolveQualifiedName = function (dottedNameAST, context) { + if (this.inTypeQuery(dottedNameAST)) { + return this.resolveDottedNameExpression(dottedNameAST, dottedNameAST.left, dottedNameAST.right, context).type; + } + + var symbol = this.getSymbolForAST(dottedNameAST, context); + if (!symbol || this.canTypeCheckAST(dottedNameAST, context)) { + var canTypeCheck = this.canTypeCheckAST(dottedNameAST, context); + if (canTypeCheck) { + this.setTypeChecked(dottedNameAST, context); + } + + symbol = this.computeQualifiedName(dottedNameAST, context); + this.setSymbolForAST(dottedNameAST, symbol, context); + } + + this.resolveDeclaredSymbol(symbol, context); + + return symbol; + }; + + PullTypeResolver.prototype.isLastNameOfModuleNameModuleReference = function (ast) { + return ast.kind() === 11 /* IdentifierName */ && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast && ast.parent.parent && ast.parent.parent.kind() === 246 /* ModuleNameModuleReference */; + }; + + PullTypeResolver.prototype.computeQualifiedName = function (dottedNameAST, context) { + var rhsName = dottedNameAST.right.valueText(); + if (rhsName.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var enclosingDecl = this.getEnclosingDeclForAST(dottedNameAST); + var lhs = this.resolveAST(dottedNameAST.left, false, context); + + var lhsType = lhs.isAlias() ? lhs.getExportAssignedContainerSymbol() : lhs.type; + + if (this.inClassExtendsHeritageClause(dottedNameAST) && !this.inTypeArgumentList(dottedNameAST)) { + if (lhs.isAlias()) { + lhs.setIsUsedAsValue(); + } + } + + if (!lhsType) { + return this.getNewErrorTypeSymbol(); + } + + if (this.isAnyOrEquivalent(lhsType)) { + return lhsType; + } + + var onLeftOfDot = this.isLeftSideOfQualifiedName(dottedNameAST); + var isNameOfModule = dottedNameAST.parent.kind() === 130 /* ModuleDeclaration */ && dottedNameAST.parent.name === dottedNameAST; + + var memberKind = (onLeftOfDot || isNameOfModule) ? 164 /* SomeContainer */ : 58728795 /* SomeType */; + + var childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, lhsType); + + if (!childTypeSymbol && !isNameOfModule && this.isLastNameOfModuleNameModuleReference(dottedNameAST.right)) { + childTypeSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, lhsType); + } + + if (!childTypeSymbol && lhsType.isContainer()) { + var exportedContainer = lhsType.getExportAssignedContainerSymbol(); + + if (exportedContainer) { + childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, exportedContainer); + } + } + + if (!childTypeSymbol && enclosingDecl) { + var parentDecl = enclosingDecl; + + while (parentDecl) { + if (parentDecl.kind & 164 /* SomeContainer */) { + break; + } + + parentDecl = parentDecl.getParentDecl(); + } + + if (parentDecl) { + var enclosingSymbolType = parentDecl.getSymbol().type; + + if (enclosingSymbolType === lhsType) { + childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, lhsType); + } + } + } + + if (!childTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(dottedNameAST.right, TypeScript.DiagnosticCode.The_property_0_does_not_exist_on_value_of_type_1, [dottedNameAST.right.text(), lhsType.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + return this.getNewErrorTypeSymbol(rhsName); + } + + return childTypeSymbol; + }; + + PullTypeResolver.prototype.shouldContextuallyTypeAnyFunctionExpression = function (functionExpressionAST, typeParameters, parameters, returnTypeAnnotation, context) { + if (typeParameters && typeParameters.typeParameters.nonSeparatorCount() > 0) { + return false; + } + + if (returnTypeAnnotation) { + return false; + } + + if (parameters) { + for (var i = 0, n = parameters.length; i < n; i++) { + if (parameters.typeAt(i)) { + return false; + } + } + } + + var contextualFunctionTypeSymbol = context.getContextualType(); + + if (contextualFunctionTypeSymbol) { + this.resolveDeclaredSymbol(contextualFunctionTypeSymbol, context); + var callSignatures = contextualFunctionTypeSymbol.getCallSignatures(); + var exactlyOneCallSignature = callSignatures && callSignatures.length === 1; + if (!exactlyOneCallSignature) { + return false; + } + + var callSignatureIsGeneric = callSignatures[0].getTypeParameters().length > 0; + return !callSignatureIsGeneric; + } + + return false; + }; + + PullTypeResolver.prototype.resolveAnyFunctionExpression = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context) { + var funcDeclSymbol = null; + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + TypeScript.Debug.assert(functionDecl); + + if (functionDecl && functionDecl.hasSymbol()) { + funcDeclSymbol = functionDecl.getSymbol(); + if (funcDeclSymbol.isResolved || funcDeclSymbol.inResolution) { + return funcDeclSymbol; + } + } + + funcDeclSymbol = functionDecl.getSymbol(); + TypeScript.Debug.assert(funcDeclSymbol); + + var funcDeclType = funcDeclSymbol.type; + var signature = funcDeclType.getCallSignatures()[0]; + funcDeclSymbol.startResolving(); + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + var assigningFunctionSignature = null; + if (isContextuallyTyped && this.shouldContextuallyTypeAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, context)) { + assigningFunctionSignature = context.getContextualType().getCallSignatures()[0]; + } + + this.resolveAnyFunctionExpressionParameters(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context); + + if (returnTypeAnnotation) { + signature.returnType = this.resolveTypeReference(returnTypeAnnotation, context); + } else { + if (assigningFunctionSignature) { + var returnType = assigningFunctionSignature.returnType; + + if (returnType) { + context.propagateContextualType(returnType); + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, bodyExpression, signature, true, functionDecl, context); + context.popAnyContextualType(); + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + + if (this.compilationSettings.noImplicitAny()) { + var functionExpressionName = functionDecl.getFunctionExpressionName(); + + if (functionExpressionName != "") { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type, [functionExpressionName])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + } + } else { + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, bodyExpression, signature, false, functionDecl, context); + } + } + + context.setTypeInContext(funcDeclSymbol, funcDeclType); + funcDeclSymbol.setResolved(); + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context); + } + + return funcDeclSymbol; + }; + + PullTypeResolver.prototype.resolveAnyFunctionExpressionParameters = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context) { + if (!parameters) { + return; + } + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var contextParams = []; + + var assigningFunctionSignature = null; + if (isContextuallyTyped && this.shouldContextuallyTypeAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, context)) { + assigningFunctionSignature = context.getContextualType().getCallSignatures()[0]; + } + + if (assigningFunctionSignature) { + contextParams = assigningFunctionSignature.parameters; + } + + var contextualParametersCount = contextParams.length; + for (var i = 0, n = parameters.length; i < n; i++) { + var actualParameterIsVarArgParameter = (i === (n - 1)) && parameters.lastParameterIsRest(); + var correspondingContextualParameter = null; + var contextualParameterType = null; + + if (i < contextualParametersCount) { + correspondingContextualParameter = contextParams[i]; + } else if (contextualParametersCount && contextParams[contextualParametersCount - 1].isVarArg) { + correspondingContextualParameter = contextParams[contextualParametersCount - 1]; + } + + if (correspondingContextualParameter) { + if (correspondingContextualParameter.isVarArg === actualParameterIsVarArgParameter) { + contextualParameterType = correspondingContextualParameter.type; + } else if (correspondingContextualParameter.isVarArg) { + contextualParameterType = correspondingContextualParameter.type.getElementType(); + } + } + + this.resolveFunctionExpressionParameter(parameters.astAt(i), parameters.identifierAt(i), parameters.typeAt(i), parameters.initializerAt(i), contextualParameterType, functionDecl, context); + } + }; + + PullTypeResolver.prototype.typeCheckSimpleArrowFunctionExpression = function (arrowFunction, isContextuallyTyped, context) { + return this.typeCheckAnyFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromIdentifier(arrowFunction.identifier), null, arrowFunction.block, arrowFunction.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckParenthesizedArrowFunctionExpression = function (arrowFunction, isContextuallyTyped, context) { + return this.typeCheckAnyFunctionExpression(arrowFunction, arrowFunction.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), TypeScript.ASTHelpers.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckAnyFunctionExpression = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcDeclSymbol = functionDecl.getSymbol(); + var funcDeclType = funcDeclSymbol.type; + var signature = funcDeclType.getCallSignatures()[0]; + var returnTypeSymbol = signature.returnType; + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + this.resolveAnyFunctionExpressionParameters(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context); + + context.pushNewContextualType(null); + if (block) { + this.resolveAST(block, false, context); + } else { + var bodyExpressionType = this.resolveReturnExpression(bodyExpression, functionDecl, context); + this.typeCheckReturnExpression(bodyExpression, bodyExpressionType, functionDecl, context); + } + + context.popAnyContextualType(); + + this.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement(functionDecl, returnTypeAnnotation, returnTypeSymbol, block, context); + + this.validateVariableDeclarationGroups(functionDecl, context); + + this.typeCheckCallBacks.push(function (context) { + _this.typeCheckFunctionOverloads(funcDeclAST, context); + }); + }; + + PullTypeResolver.prototype.resolveThisExpression = function (thisExpression, context) { + var enclosingDecl = this.getEnclosingDeclForAST(thisExpression); + var thisTypeSymbol = this.getContextualClassSymbolForEnclosingDecl(thisExpression, enclosingDecl) || this.semanticInfoChain.anyTypeSymbol; + + if (this.canTypeCheckAST(thisExpression, context)) { + this.typeCheckThisExpression(thisExpression, context, enclosingDecl); + } + + return thisTypeSymbol; + }; + + PullTypeResolver.prototype.inTypeArgumentList = function (ast) { + var previous = null; + var current = ast; + + while (current) { + switch (current.kind()) { + case 126 /* GenericType */: + var genericType = current; + if (genericType.typeArgumentList === previous) { + return true; + } + break; + + case 226 /* ArgumentList */: + var argumentList = current; + return argumentList.typeArgumentList === previous; + } + + previous = current; + current = current.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inClassExtendsHeritageClause = function (ast) { + while (ast) { + switch (ast.kind()) { + case 230 /* ExtendsHeritageClause */: + var heritageClause = ast; + + return heritageClause.parent.parent.kind() === 131 /* ClassDeclaration */; + + case 137 /* ConstructorDeclaration */: + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inTypeQuery = function (ast) { + while (ast) { + switch (ast.kind()) { + case 127 /* TypeQuery */: + return true; + case 129 /* FunctionDeclaration */: + case 213 /* InvocationExpression */: + case 137 /* ConstructorDeclaration */: + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inArgumentListOfSuperInvocation = function (ast) { + var previous = null; + var current = ast; + while (current) { + switch (current.kind()) { + case 213 /* InvocationExpression */: + var invocationExpression = current; + if (previous === invocationExpression.argumentList && invocationExpression.expression.kind() === 50 /* SuperKeyword */) { + return true; + } + break; + + case 137 /* ConstructorDeclaration */: + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + previous = current; + current = current.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inConstructorParameterList = function (ast) { + var previous = null; + var current = ast; + while (current) { + switch (current.kind()) { + case 142 /* CallSignature */: + var callSignature = current; + if (previous === callSignature.parameterList && callSignature.parent.kind() === 137 /* ConstructorDeclaration */) { + return true; + } + + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + previous = current; + current = current.parent; + } + + return false; + }; + PullTypeResolver.prototype.isFunctionAccessorOrNonArrowFunctionExpression = function (decl) { + if (decl.kind === 262144 /* GetAccessor */ || decl.kind === 524288 /* SetAccessor */) { + return true; + } + + return this.isFunctionOrNonArrowFunctionExpression(decl); + }; + + PullTypeResolver.prototype.isFunctionOrNonArrowFunctionExpression = function (decl) { + if (decl.kind === 16384 /* Function */) { + return true; + } else if (decl.kind === 131072 /* FunctionExpression */ && !TypeScript.hasFlag(decl.flags, 8192 /* ArrowFunction */)) { + return true; + } + + return false; + }; + + PullTypeResolver.prototype.typeCheckThisExpression = function (thisExpression, context, enclosingDecl) { + this.checkForThisCaptureInArrowFunction(thisExpression); + + if (this.inConstructorParameterList(thisExpression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_constructor_arguments)); + return; + } + + for (var currentDecl = enclosingDecl; currentDecl !== null; currentDecl = currentDecl.getParentDecl()) { + if (this.isFunctionAccessorOrNonArrowFunctionExpression(currentDecl)) { + return; + } else if (currentDecl.kind === 4 /* Container */ || currentDecl.kind === 32 /* DynamicModule */) { + if (currentDecl.getParentDecl() === null) { + return; + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_within_module_bodies)); + return; + } + } else if (currentDecl.kind === 64 /* Enum */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_current_location)); + return; + } else if (currentDecl.kind === 32768 /* ConstructorMethod */) { + if (this.inArgumentListOfSuperInvocation(thisExpression) && this.superCallMustBeFirstStatementInConstructor(currentDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_current_location)); + } + + return; + } else if (currentDecl.kind === 8 /* Class */) { + if (this.inStaticMemberVariableDeclaration(thisExpression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_static_initializers_in_a_class_body)); + } + + return; + } + } + }; + + PullTypeResolver.prototype.getContextualClassSymbolForEnclosingDecl = function (ast, enclosingDecl) { + var declPath = enclosingDecl.getParentPath(); + + if (declPath.length) { + var isStaticContext = false; + + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.kind; + var declFlags = decl.flags; + + if (declFlags & 16 /* Static */) { + isStaticContext = true; + } else if (declKind === 131072 /* FunctionExpression */ && !TypeScript.hasFlag(declFlags, 8192 /* ArrowFunction */)) { + return null; + } else if (declKind === 16384 /* Function */) { + return null; + } else if (declKind === 8 /* Class */) { + if (this.inStaticMemberVariableDeclaration(ast)) { + return this.getNewErrorTypeSymbol(); + } else { + var classSymbol = decl.getSymbol(); + if (isStaticContext) { + var constructorSymbol = classSymbol.getConstructorMethod(); + return constructorSymbol.type; + } else { + return classSymbol; + } + } + } + } + } + + return null; + }; + + PullTypeResolver.prototype.inStaticMemberVariableDeclaration = function (ast) { + while (ast) { + if (ast.kind() === 136 /* MemberVariableDeclaration */ && TypeScript.hasModifier(ast.modifiers, 16 /* Static */)) { + return true; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.resolveSuperExpression = function (ast, context) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + var superType = this.semanticInfoChain.anyTypeSymbol; + + var classSymbol = this.getContextualClassSymbolForEnclosingDecl(ast, enclosingDecl); + + if (classSymbol) { + this.resolveDeclaredSymbol(classSymbol, context); + + var parents = classSymbol.getExtendedTypes(); + + if (parents.length) { + superType = parents[0]; + } + } + + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckSuperExpression(ast, context, enclosingDecl); + } + + return superType; + }; + + PullTypeResolver.prototype.typeCheckSuperExpression = function (ast, context, enclosingDecl) { + this.setTypeChecked(ast, context); + + this.checkForThisCaptureInArrowFunction(ast); + + var isSuperCall = ast.parent.kind() === 213 /* InvocationExpression */; + var isSuperPropertyAccess = ast.parent.kind() === 212 /* MemberAccessExpression */; + TypeScript.Debug.assert(isSuperCall || isSuperPropertyAccess); + + if (isSuperPropertyAccess) { + for (var currentDecl = enclosingDecl; currentDecl !== null; currentDecl = currentDecl.getParentDecl()) { + if (this.isFunctionOrNonArrowFunctionExpression(currentDecl)) { + break; + } else if (currentDecl.kind === 8 /* Class */) { + if (!this.enclosingClassIsDerived(currentDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_non_derived_classes)); + return; + } else if (this.inConstructorParameterList(ast)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_constructor_arguments)); + return; + } else if (this.inStaticMemberVariableDeclaration(ast)) { + break; + } + + return; + } + } + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class)); + return; + } else { + if (enclosingDecl.kind === 32768 /* ConstructorMethod */) { + var classDecl = enclosingDecl.getParentDecl(); + + if (!this.enclosingClassIsDerived(classDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_non_derived_classes)); + return; + } else if (this.inConstructorParameterList(ast)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_constructor_arguments)); + return; + } + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors)); + } + } + }; + + PullTypeResolver.prototype.resolveSimplePropertyAssignment = function (propertyAssignment, isContextuallyTyped, context) { + return this.resolveAST(propertyAssignment.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveFunctionPropertyAssignment = function (funcProp, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcProp), funcProp.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckFunctionPropertyAssignment = function (funcProp, isContextuallyTyped, context) { + this.typeCheckAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcProp), funcProp.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveObjectLiteralExpression = function (expressionAST, isContextuallyTyped, context, additionalResults) { + var symbol = this.getSymbolForAST(expressionAST, context); + var hasResolvedSymbol = symbol && symbol.isResolved; + + if (!hasResolvedSymbol || additionalResults || this.canTypeCheckAST(expressionAST, context)) { + if (this.canTypeCheckAST(expressionAST, context)) { + this.setTypeChecked(expressionAST, context); + } + symbol = this.computeObjectLiteralExpression(expressionAST, isContextuallyTyped, context, additionalResults); + this.setSymbolForAST(expressionAST, symbol, context); + } + + return symbol; + }; + + PullTypeResolver.prototype.bindObjectLiteralMembers = function (objectLiteralDeclaration, objectLiteralTypeSymbol, objectLiteralMembers, isUsingExistingSymbol, pullTypeContext) { + var boundMemberSymbols = []; + var memberSymbol; + for (var i = 0, len = objectLiteralMembers.nonSeparatorCount(); i < len; i++) { + var propertyAssignment = objectLiteralMembers.nonSeparatorAt(i); + + var id = this.getPropertyAssignmentName(propertyAssignment); + var assignmentText = getPropertyAssignmentNameTextFromIdentifier(id); + + var isAccessor = propertyAssignment.kind() === 139 /* GetAccessor */ || propertyAssignment.kind() === 140 /* SetAccessor */; + var decl = this.semanticInfoChain.getDeclForAST(propertyAssignment); + TypeScript.Debug.assert(decl); + + if (propertyAssignment.kind() === 240 /* SimplePropertyAssignment */) { + if (!isUsingExistingSymbol) { + memberSymbol = new TypeScript.PullSymbol(assignmentText.memberName, 4096 /* Property */); + memberSymbol.addDeclaration(decl); + decl.setSymbol(memberSymbol); + } else { + memberSymbol = decl.getSymbol(); + } + } else if (propertyAssignment.kind() === 241 /* FunctionPropertyAssignment */) { + memberSymbol = decl.getSymbol(); + } else { + TypeScript.Debug.assert(isAccessor); + memberSymbol = decl.getSymbol(); + } + + if (!isUsingExistingSymbol && !isAccessor) { + var existingMember = objectLiteralTypeSymbol.findMember(memberSymbol.name, true); + if (existingMember) { + pullTypeContext.postDiagnostic(this.semanticInfoChain.duplicateIdentifierDiagnosticFromAST(propertyAssignment, assignmentText.actualText, existingMember.getDeclarations()[0].ast())); + } + + objectLiteralTypeSymbol.addMember(memberSymbol); + } + + boundMemberSymbols.push(memberSymbol); + } + + return boundMemberSymbols; + }; + + PullTypeResolver.prototype.resolveObjectLiteralMembers = function (objectLiteralDeclaration, objectLiteralTypeSymbol, objectLiteralContextualType, objectLiteralMembers, stringIndexerSignature, numericIndexerSignature, allMemberTypes, allNumericMemberTypes, boundMemberSymbols, isUsingExistingSymbol, pullTypeContext, additionalResults) { + for (var i = 0, len = objectLiteralMembers.nonSeparatorCount(); i < len; i++) { + var propertyAssignment = objectLiteralMembers.nonSeparatorAt(i); + + var acceptedContextualType = false; + var assigningSymbol = null; + + var id = this.getPropertyAssignmentName(propertyAssignment); + var memberSymbol = boundMemberSymbols[i]; + var contextualMemberType = null; + + if (objectLiteralContextualType) { + assigningSymbol = this.getNamedPropertySymbol(memberSymbol.name, 68147712 /* SomeValue */, objectLiteralContextualType); + + if (!assigningSymbol) { + if (numericIndexerSignature && TypeScript.PullHelpers.isNameNumeric(memberSymbol.name)) { + assigningSymbol = numericIndexerSignature; + } else if (stringIndexerSignature) { + assigningSymbol = stringIndexerSignature; + } + } + + if (assigningSymbol) { + this.resolveDeclaredSymbol(assigningSymbol, pullTypeContext); + + contextualMemberType = assigningSymbol.kind === 4194304 /* IndexSignature */ ? assigningSymbol.returnType : assigningSymbol.type; + pullTypeContext.propagateContextualType(contextualMemberType); + + acceptedContextualType = true; + + if (additionalResults) { + additionalResults.membersContextTypeSymbols[i] = contextualMemberType; + } + } + } + + var memberSymbolType = this.resolveAST(propertyAssignment, contextualMemberType !== null, pullTypeContext).type; + + if (memberSymbolType) { + if (memberSymbolType.isGeneric()) { + objectLiteralTypeSymbol.setHasGenericMember(); + } + + if (stringIndexerSignature) { + allMemberTypes.push(memberSymbolType); + } + if (numericIndexerSignature && TypeScript.PullHelpers.isNameNumeric(memberSymbol.name)) { + allNumericMemberTypes.push(memberSymbolType); + } + } + + if (acceptedContextualType) { + pullTypeContext.popAnyContextualType(); + } + + var isAccessor = propertyAssignment.kind() === 140 /* SetAccessor */ || propertyAssignment.kind() === 139 /* GetAccessor */; + if (!memberSymbol.isResolved) { + if (isAccessor) { + this.setSymbolForAST(id, memberSymbolType, pullTypeContext); + } else { + pullTypeContext.setTypeInContext(memberSymbol, memberSymbolType); + memberSymbol.setResolved(); + + this.setSymbolForAST(id, memberSymbol, pullTypeContext); + } + } + } + }; + + PullTypeResolver.prototype.computeObjectLiteralExpression = function (objectLitAST, isContextuallyTyped, context, additionalResults) { + var objectLitDecl = this.semanticInfoChain.getDeclForAST(objectLitAST); + TypeScript.Debug.assert(objectLitDecl); + + var typeSymbol = this.getSymbolForAST(objectLitAST, context); + var isUsingExistingSymbol = !!typeSymbol; + + if (!typeSymbol) { + typeSymbol = new TypeScript.PullTypeSymbol("", 256 /* ObjectLiteral */); + typeSymbol.addDeclaration(objectLitDecl); + this.setSymbolForAST(objectLitAST, typeSymbol, context); + objectLitDecl.setSymbol(typeSymbol); + } + + var propertyAssignments = objectLitAST.propertyAssignments; + var contextualType = null; + + if (isContextuallyTyped) { + contextualType = context.getContextualType(); + this.resolveDeclaredSymbol(contextualType, context); + } + + var stringIndexerSignature = null; + var numericIndexerSignature = null; + var allMemberTypes = null; + var allNumericMemberTypes = null; + + if (contextualType) { + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(contextualType, context); + + stringIndexerSignature = indexSignatures.stringSignature; + numericIndexerSignature = indexSignatures.numericSignature; + + var inInferentialTyping = context.isInferentiallyTyping(); + if (stringIndexerSignature) { + allMemberTypes = inInferentialTyping ? [] : [stringIndexerSignature.returnType]; + } + + if (numericIndexerSignature) { + allNumericMemberTypes = inInferentialTyping ? [] : [numericIndexerSignature.returnType]; + } + } + + if (propertyAssignments) { + if (additionalResults) { + additionalResults.membersContextTypeSymbols = []; + } + + var boundMemberSymbols = this.bindObjectLiteralMembers(objectLitDecl, typeSymbol, propertyAssignments, isUsingExistingSymbol, context); + + this.resolveObjectLiteralMembers(objectLitDecl, typeSymbol, contextualType, propertyAssignments, stringIndexerSignature, numericIndexerSignature, allMemberTypes, allNumericMemberTypes, boundMemberSymbols, isUsingExistingSymbol, context, additionalResults); + + if (!isUsingExistingSymbol) { + this.stampObjectLiteralWithIndexSignature(typeSymbol, allMemberTypes, stringIndexerSignature, context); + this.stampObjectLiteralWithIndexSignature(typeSymbol, allNumericMemberTypes, numericIndexerSignature, context); + } + } + + typeSymbol.setResolved(); + return typeSymbol; + }; + + PullTypeResolver.prototype.getPropertyAssignmentName = function (propertyAssignment) { + if (propertyAssignment.kind() === 240 /* SimplePropertyAssignment */) { + return propertyAssignment.propertyName; + } else if (propertyAssignment.kind() === 241 /* FunctionPropertyAssignment */) { + return propertyAssignment.propertyName; + } else if (propertyAssignment.kind() === 139 /* GetAccessor */) { + return propertyAssignment.propertyName; + } else if (propertyAssignment.kind() === 140 /* SetAccessor */) { + return propertyAssignment.propertyName; + } else { + TypeScript.Debug.assert(false); + } + }; + + PullTypeResolver.prototype.stampObjectLiteralWithIndexSignature = function (objectLiteralSymbol, indexerTypeCandidates, contextualIndexSignature, context) { + if (contextualIndexSignature) { + var typeCollection = { + getLength: function () { + return indexerTypeCandidates.length; + }, + getTypeAtIndex: function (index) { + return indexerTypeCandidates[index]; + } + }; + var decl = objectLiteralSymbol.getDeclarations()[0]; + var indexerReturnType = this.findBestCommonType(typeCollection, context).widenedType(this, null, context); + if (indexerReturnType === contextualIndexSignature.returnType) { + objectLiteralSymbol.addIndexSignature(contextualIndexSignature); + } else { + this.semanticInfoChain.addSyntheticIndexSignature(decl, objectLiteralSymbol, this.getASTForDecl(decl), contextualIndexSignature.parameters[0].name, contextualIndexSignature.parameters[0].type, indexerReturnType); + } + } + }; + + PullTypeResolver.prototype.resolveArrayLiteralExpression = function (arrayLit, isContextuallyTyped, context) { + var symbol = this.getSymbolForAST(arrayLit, context); + if (!symbol || this.canTypeCheckAST(arrayLit, context)) { + if (this.canTypeCheckAST(arrayLit, context)) { + this.setTypeChecked(arrayLit, context); + } + symbol = this.computeArrayLiteralExpressionSymbol(arrayLit, isContextuallyTyped, context); + this.setSymbolForAST(arrayLit, symbol, context); + } + + return symbol; + }; + + PullTypeResolver.prototype.computeArrayLiteralExpressionSymbol = function (arrayLit, isContextuallyTyped, context) { + var elements = arrayLit.expressions; + var elementType = null; + var elementTypes = []; + var comparisonInfo = new TypeComparisonInfo(); + var contextualElementType = null; + comparisonInfo.onlyCaptureFirstError = true; + + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + + this.resolveDeclaredSymbol(contextualType, context); + + if (contextualType) { + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(contextualType, context); + if (indexSignatures.numericSignature) { + contextualElementType = indexSignatures.numericSignature.returnType; + } + } + } + + if (elements) { + if (contextualElementType) { + context.propagateContextualType(contextualElementType); + } + + for (var i = 0, n = elements.nonSeparatorCount(); i < n; i++) { + elementTypes.push(this.resolveAST(elements.nonSeparatorAt(i), contextualElementType !== null, context).type); + } + + if (contextualElementType) { + context.popAnyContextualType(); + } + } + + if (elementTypes.length) { + elementType = elementTypes[0]; + } + var collection; + + if (contextualElementType && !context.isInferentiallyTyping()) { + if (!elementType) { + elementType = contextualElementType; + } + + collection = { + getLength: function () { + return elements.nonSeparatorCount() + 1; + }, + getTypeAtIndex: function (index) { + return index === 0 ? contextualElementType : elementTypes[index - 1]; + } + }; + } else { + collection = { + getLength: function () { + return elements.nonSeparatorCount(); + }, + getTypeAtIndex: function (index) { + return elementTypes[index]; + } + }; + } + + elementType = elementType ? this.findBestCommonType(collection, context, comparisonInfo) : elementType; + + if (!elementType) { + elementType = this.semanticInfoChain.undefinedTypeSymbol; + } + + return this.getArrayType(elementType); + }; + + PullTypeResolver.prototype.resolveElementAccessExpression = function (callEx, context) { + var symbolAndDiagnostic = this.computeElementAccessExpressionSymbolAndDiagnostic(callEx, context); + + if (this.canTypeCheckAST(callEx, context)) { + this.typeCheckElementAccessExpression(callEx, context, symbolAndDiagnostic); + } + + return symbolAndDiagnostic.symbol; + }; + + PullTypeResolver.prototype.typeCheckElementAccessExpression = function (callEx, context, symbolAndDiagnostic) { + this.setTypeChecked(callEx, context); + context.postDiagnostic(symbolAndDiagnostic.diagnostic); + }; + + PullTypeResolver.prototype.computeElementAccessExpressionSymbolAndDiagnostic = function (callEx, context) { + var targetSymbol = this.resolveAST(callEx.expression, false, context); + var indexType = this.resolveAST(callEx.argumentExpression, false, context).type; + + var targetTypeSymbol = targetSymbol.type; + + targetTypeSymbol = this.getApparentType(targetTypeSymbol); + + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + return { symbol: targetTypeSymbol }; + } + + var elementType = targetTypeSymbol.getElementType(); + + var isNumberIndex = indexType === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(indexType); + + if (elementType && isNumberIndex) { + return { symbol: elementType }; + } + + if (callEx.argumentExpression.kind() === 14 /* StringLiteral */ || callEx.argumentExpression.kind() === 13 /* NumericLiteral */) { + var memberName = callEx.argumentExpression.kind() === 14 /* StringLiteral */ ? TypeScript.stripStartAndEndQuotes(callEx.argumentExpression.text()) : callEx.argumentExpression.valueText(); + + var member = this._getNamedPropertySymbolOfAugmentedType(memberName, targetTypeSymbol); + + if (member) { + this.resolveDeclaredSymbol(member, context); + + return { symbol: member.type }; + } + } + + var signatures = this.getBothKindsOfIndexSignaturesIncludingAugmentedType(targetTypeSymbol, context); + + var stringSignature = signatures.stringSignature; + var numberSignature = signatures.numericSignature; + + if (numberSignature && (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol)) { + return { symbol: numberSignature.returnType || this.semanticInfoChain.anyTypeSymbol }; + } else if (stringSignature && (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol)) { + return { symbol: stringSignature.returnType || this.semanticInfoChain.anyTypeSymbol }; + } else if (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol) { + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(callEx.argumentExpression, TypeScript.DiagnosticCode.Index_signature_of_object_type_implicitly_has_an_any_type)); + } + return { symbol: this.semanticInfoChain.anyTypeSymbol }; + } else { + return { + symbol: this.getNewErrorTypeSymbol(), + diagnostic: this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.Value_of_type_0_is_not_indexable_by_type_1, [targetTypeSymbol.toString(), indexType.toString()]) + }; + } + }; + + PullTypeResolver.prototype.getBothKindsOfIndexSignaturesIncludingAugmentedType = function (enclosingType, context) { + return this._getBothKindsOfIndexSignatures(enclosingType, context, true); + }; + + PullTypeResolver.prototype.getBothKindsOfIndexSignaturesExcludingAugmentedType = function (enclosingType, context) { + return this._getBothKindsOfIndexSignatures(enclosingType, context, false); + }; + + PullTypeResolver.prototype._getBothKindsOfIndexSignatures = function (enclosingType, context, includeAugmentedType) { + var signatures = includeAugmentedType ? enclosingType.getIndexSignaturesOfAugmentedType(this, this.cachedFunctionInterfaceType(), this.cachedObjectInterfaceType()) : enclosingType.getIndexSignatures(); + + var stringSignature = null; + var numberSignature = null; + var signature = null; + var paramSymbols; + var paramType; + + for (var i = 0; i < signatures.length; i++) { + if (stringSignature && numberSignature) { + break; + } + + signature = signatures[i]; + if (!signature.isResolved) { + this.resolveDeclaredSymbol(signature, context); + } + + paramSymbols = signature.parameters; + + if (paramSymbols.length) { + paramType = paramSymbols[0].type; + + if (!stringSignature && paramType === this.semanticInfoChain.stringTypeSymbol) { + stringSignature = signature; + continue; + } else if (!numberSignature && paramType === this.semanticInfoChain.numberTypeSymbol) { + numberSignature = signature; + continue; + } + } + } + + return { + numericSignature: numberSignature, + stringSignature: stringSignature + }; + }; + + PullTypeResolver.prototype._addUnhiddenSignaturesFromBaseType = function (derivedTypeSignatures, baseTypeSignatures, signaturesBeingAggregated) { + var _this = this; + if (!derivedTypeSignatures) { + signaturesBeingAggregated.push.apply(signaturesBeingAggregated, baseTypeSignatures); + return; + } + + var context = new TypeScript.PullTypeResolutionContext(this); + for (var i = 0; i < baseTypeSignatures.length; i++) { + var baseSignature = baseTypeSignatures[i]; + + var signatureIsHidden = TypeScript.ArrayUtilities.any(derivedTypeSignatures, function (sig) { + return _this.signaturesAreIdenticalWithNewEnclosingTypes(baseSignature, sig, context, false); + }); + + if (!signatureIsHidden) { + signaturesBeingAggregated.push(baseSignature); + } + } + }; + + PullTypeResolver.prototype.resolveBinaryAdditionOperation = function (binaryExpression, context) { + var lhsExpression = this.resolveAST(binaryExpression.left, false, context); + var lhsType = lhsExpression.type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + if (TypeScript.PullHelpers.symbolIsEnum(lhsType)) { + lhsType = this.semanticInfoChain.numberTypeSymbol; + } + + if (TypeScript.PullHelpers.symbolIsEnum(rhsType)) { + rhsType = this.semanticInfoChain.numberTypeSymbol; + } + + var isLhsTypeNullOrUndefined = lhsType === this.semanticInfoChain.nullTypeSymbol || lhsType === this.semanticInfoChain.undefinedTypeSymbol; + var isRhsTypeNullOrUndefined = rhsType === this.semanticInfoChain.nullTypeSymbol || rhsType === this.semanticInfoChain.undefinedTypeSymbol; + + if (isLhsTypeNullOrUndefined) { + if (isRhsTypeNullOrUndefined) { + lhsType = rhsType = this.semanticInfoChain.anyTypeSymbol; + } else { + lhsType = rhsType; + } + } else if (isRhsTypeNullOrUndefined) { + rhsType = lhsType; + } + + var exprType = null; + + if (lhsType === this.semanticInfoChain.stringTypeSymbol || rhsType === this.semanticInfoChain.stringTypeSymbol) { + exprType = this.semanticInfoChain.stringTypeSymbol; + } else if (this.isAnyOrEquivalent(lhsType) || this.isAnyOrEquivalent(rhsType)) { + exprType = this.semanticInfoChain.anyTypeSymbol; + } else if (rhsType === this.semanticInfoChain.numberTypeSymbol && lhsType === this.semanticInfoChain.numberTypeSymbol) { + exprType = this.semanticInfoChain.numberTypeSymbol; + } + + if (this.canTypeCheckAST(binaryExpression, context)) { + this.setTypeChecked(binaryExpression, context); + + if (exprType) { + if (binaryExpression.kind() === 175 /* AddAssignmentExpression */) { + if (!this.isReference(binaryExpression.left, lhsExpression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_left_hand_side_of_assignment_expression)); + } + + this.checkAssignability(binaryExpression.left, exprType, lhsType, context); + } + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_expression_types_not_known_to_support_the_addition_operator)); + } + } + + if (!exprType) { + exprType = this.semanticInfoChain.anyTypeSymbol; + } + + return exprType; + }; + + PullTypeResolver.prototype.bestCommonTypeOfTwoTypes = function (type1, type2, context) { + return this.findBestCommonType({ + getLength: function () { + return 2; + }, + getTypeAtIndex: function (index) { + switch (index) { + case 0: + return type1; + case 1: + return type2; + } + } + }, context); + }; + + PullTypeResolver.prototype.bestCommonTypeOfThreeTypes = function (type1, type2, type3, context) { + return this.findBestCommonType({ + getLength: function () { + return 3; + }, + getTypeAtIndex: function (index) { + switch (index) { + case 0: + return type1; + case 1: + return type2; + case 2: + return type3; + } + } + }, context); + }; + + PullTypeResolver.prototype.resolveLogicalOrExpression = function (binex, isContextuallyTyped, context) { + if (this.canTypeCheckAST(binex, context)) { + this.setTypeChecked(binex, context); + } + + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + var leftType = this.resolveAST(binex.left, isContextuallyTyped, context).type; + var rightType = this.resolveAST(binex.right, isContextuallyTyped, context).type; + + return context.isInferentiallyTyping() ? this.bestCommonTypeOfTwoTypes(leftType, rightType, context) : this.bestCommonTypeOfThreeTypes(contextualType, leftType, rightType, context); + } else { + var leftType = this.resolveAST(binex.left, false, context).type; + + context.pushNewContextualType(leftType); + var rightType = this.resolveAST(binex.right, true, context).type; + context.popAnyContextualType(); + + return this.bestCommonTypeOfTwoTypes(leftType, rightType, context); + } + }; + + PullTypeResolver.prototype.resolveLogicalAndExpression = function (binex, context) { + if (this.canTypeCheckAST(binex, context)) { + this.setTypeChecked(binex, context); + + this.resolveAST(binex.left, false, context); + } + + return this.resolveAST(binex.right, false, context).type; + }; + + PullTypeResolver.prototype.computeTypeOfConditionalExpression = function (leftType, rightType, isContextuallyTyped, context) { + if (isContextuallyTyped && !context.isInferentiallyTyping()) { + var contextualType = context.getContextualType(); + return this.bestCommonTypeOfThreeTypes(contextualType, leftType, rightType, context); + } else { + return this.bestCommonTypeOfTwoTypes(leftType, rightType, context); + } + }; + + PullTypeResolver.prototype.resolveConditionalExpression = function (trinex, isContextuallyTyped, context) { + var leftType = this.resolveAST(trinex.whenTrue, isContextuallyTyped, context).type; + var rightType = this.resolveAST(trinex.whenFalse, isContextuallyTyped, context).type; + + var expressionType = this.computeTypeOfConditionalExpression(leftType, rightType, isContextuallyTyped, context); + + var conditionalTypesAreValid = this.conditionExpressionTypesAreValid(leftType, rightType, expressionType, isContextuallyTyped, context); + + if (this.canTypeCheckAST(trinex, context)) { + this.setTypeChecked(trinex, context); + this.resolveAST(trinex.condition, false, context); + + if (!this.conditionExpressionTypesAreValid(leftType, rightType, expressionType, isContextuallyTyped, context)) { + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(trinex, TypeScript.DiagnosticCode.Type_of_conditional_0_must_be_identical_to_1_2_or_3, [expressionType.toString(), leftType.toString(), rightType.toString(), contextualType.toString()])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(trinex, TypeScript.DiagnosticCode.Type_of_conditional_0_must_be_identical_to_1_or_2, [expressionType.toString(), leftType.toString(), rightType.toString()])); + } + } + } + + if (!conditionalTypesAreValid) { + return this.getNewErrorTypeSymbol(); + } + + return expressionType; + }; + + PullTypeResolver.prototype.conditionExpressionTypesAreValid = function (leftType, rightType, expressionType, isContextuallyTyped, context) { + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + if (this.typesAreIdentical(expressionType, leftType, context) || this.typesAreIdentical(expressionType, rightType, context) || this.typesAreIdentical(expressionType, contextualType, context)) { + return true; + } + } else { + if (this.typesAreIdentical(expressionType, leftType, context) || this.typesAreIdentical(expressionType, rightType, context)) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.resolveParenthesizedExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + } + + return this.resolveAST(ast.expression, false, context); + }; + + PullTypeResolver.prototype.resolveExpressionStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveInvocationExpression = function (callEx, context, additionalResults) { + var symbol = this.getSymbolForAST(callEx, context); + + if (!symbol || !symbol.isResolved) { + if (!additionalResults) { + additionalResults = new PullAdditionalCallResolutionData(); + } + symbol = this.computeInvocationExpressionSymbol(callEx, context, additionalResults); + if (this.canTypeCheckAST(callEx, context)) { + this.setTypeChecked(callEx, context); + } + if (symbol !== this.semanticInfoChain.anyTypeSymbol) { + this.setSymbolForAST(callEx, symbol, context); + } + this.semanticInfoChain.setCallResolutionDataForAST(callEx, additionalResults); + } else { + if (this.canTypeCheckAST(callEx, context)) { + this.typeCheckInvocationExpression(callEx, context); + } + + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + if (additionalResults && (callResolutionData !== additionalResults)) { + additionalResults.actualParametersContextTypeSymbols = callResolutionData.actualParametersContextTypeSymbols; + additionalResults.candidateSignature = callResolutionData.candidateSignature; + additionalResults.resolvedSignatures = callResolutionData.resolvedSignatures; + additionalResults.targetSymbol = callResolutionData.targetSymbol; + } + } + + return symbol; + }; + + PullTypeResolver.prototype.typeCheckInvocationExpression = function (callEx, context) { + this.setTypeChecked(callEx, context); + var targetSymbol = this.resolveAST(callEx.expression, false, context); + + if (callEx.argumentList.arguments) { + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + + var len = callEx.argumentList.arguments.nonSeparatorCount(); + for (var i = 0; i < len; i++) { + var contextualType = callResolutionData.actualParametersContextTypeSymbols ? callResolutionData.actualParametersContextTypeSymbols[i] : null; + if (contextualType) { + context.pushNewContextualType(contextualType); + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + for (var i = 0; i < callResolutionData.diagnosticsFromOverloadResolution.length; i++) { + context.postDiagnostic(callResolutionData.diagnosticsFromOverloadResolution[i]); + } + }; + + PullTypeResolver.prototype.computeInvocationExpressionSymbol = function (callEx, context, additionalResults) { + var targetSymbol = this.resolveAST(callEx.expression, false, context); + var targetAST = this.getCallTargetErrorSpanAST(callEx); + + var targetTypeSymbol = targetSymbol.type; + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + this.resolveAST(callEx.argumentList.arguments, false, context); + + if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { + if (targetTypeSymbol === this.semanticInfoChain.anyTypeSymbol) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Untyped_function_calls_may_not_accept_type_arguments), additionalResults, context); + return this.getNewErrorTypeSymbol(); + } + } + + return this.semanticInfoChain.anyTypeSymbol; + } + + var isSuperCall = false; + + if (callEx.expression.kind() === 50 /* SuperKeyword */) { + isSuperCall = true; + + if (targetTypeSymbol.isClass()) { + targetSymbol = targetTypeSymbol.getConstructorMethod(); + this.resolveDeclaredSymbol(targetSymbol, context); + targetTypeSymbol = targetSymbol.type; + } else { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Calls_to_super_are_only_valid_inside_a_class), additionalResults, context); + this.resolveAST(callEx.argumentList.arguments, false, context); + + return this.getNewErrorTypeSymbol(); + } + } + + var signatures = isSuperCall ? targetTypeSymbol.getConstructSignatures() : targetTypeSymbol.getCallSignatures(); + + if (!signatures.length && (targetTypeSymbol.kind === 33554432 /* ConstructorType */)) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, [targetTypeSymbol.toString()]), additionalResults, context); + } + + var explicitTypeArgs = null; + var couldNotFindGenericOverload = false; + var couldNotAssignToConstraint; + var constraintDiagnostic = null; + var typeArgumentCountDiagnostic = null; + var diagnostics = []; + + if (callEx.argumentList.typeArgumentList) { + explicitTypeArgs = []; + + if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { + for (var i = 0; i < callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { + explicitTypeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + } + } + } + + var triedToInferTypeArgs = false; + + var resolvedSignatures = []; + var inferredOrExplicitTypeArgs; + var specializedSignature; + var typeParameters; + var typeConstraint = null; + var beforeResolutionSignatures = signatures; + var targetTypeReplacementMap = targetTypeSymbol.getTypeParameterArgumentMap(); + + for (var i = 0; i < signatures.length; i++) { + typeParameters = signatures[i].getTypeParameters(); + couldNotAssignToConstraint = false; + + if (signatures[i].isGeneric() && typeParameters.length) { + if (isSuperCall && targetTypeSymbol.isGeneric() && !callEx.argumentList.typeArgumentList) { + explicitTypeArgs = signatures[i].returnType.getTypeArguments(); + } + + if (explicitTypeArgs) { + if (explicitTypeArgs.length === typeParameters.length) { + inferredOrExplicitTypeArgs = explicitTypeArgs; + } else { + typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, explicitTypeArgs.length]); + continue; + } + } else { + TypeScript.Debug.assert(callEx.argumentList); + var typeArgumentInferenceContext = new TypeScript.InvocationTypeArgumentInferenceContext(this, context, signatures[i], callEx.argumentList.arguments); + inferredOrExplicitTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); + triedToInferTypeArgs = true; + } + + TypeScript.Debug.assert(inferredOrExplicitTypeArgs && inferredOrExplicitTypeArgs.length == typeParameters.length); + + var mutableTypeReplacementMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(targetTypeReplacementMap ? targetTypeReplacementMap : []); + TypeScript.PullInstantiationHelpers.updateMutableTypeParameterArgumentMap(typeParameters, inferredOrExplicitTypeArgs, mutableTypeReplacementMap); + var typeReplacementMap = mutableTypeReplacementMap.typeParameterArgumentMap; + + if (explicitTypeArgs) { + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); + } + + if (!this.sourceIsAssignableToTarget(inferredOrExplicitTypeArgs[j], typeConstraint, targetAST, context, null, true)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); + constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredOrExplicitTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); + couldNotAssignToConstraint = true; + } + + if (couldNotAssignToConstraint) { + break; + } + } + } + } + + if (couldNotAssignToConstraint) { + continue; + } + + specializedSignature = this.instantiateSignature(signatures[i], typeReplacementMap); + + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; + } + } else { + if (!(callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount())) { + resolvedSignatures[resolvedSignatures.length] = signatures[i]; + } + } + } + + if (signatures.length && !resolvedSignatures.length) { + couldNotFindGenericOverload = true; + } + + signatures = resolvedSignatures; + + var errorCondition = null; + if (!signatures.length) { + additionalResults.targetSymbol = targetSymbol; + additionalResults.resolvedSignatures = beforeResolutionSignatures; + additionalResults.candidateSignature = beforeResolutionSignatures && beforeResolutionSignatures.length ? beforeResolutionSignatures[0] : null; + + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + + this.resolveAST(callEx.argumentList.arguments, false, context); + + if (!couldNotFindGenericOverload) { + if (this.cachedFunctionInterfaceType() && this.sourceIsAssignableToTarget(targetTypeSymbol, this.cachedFunctionInterfaceType(), targetAST, context)) { + if (callEx.argumentList.typeArgumentList) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Non_generic_functions_may_not_accept_type_arguments), additionalResults, context); + } + return this.semanticInfoChain.anyTypeSymbol; + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature), additionalResults, context); + } else if (constraintDiagnostic) { + this.postOverloadResolutionDiagnostics(constraintDiagnostic, additionalResults, context); + } else if (typeArgumentCountDiagnostic) { + this.postOverloadResolutionDiagnostics(typeArgumentCountDiagnostic, additionalResults, context); + } else { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.Could_not_select_overload_for_call_expression), additionalResults, context); + } + + return this.getNewErrorTypeSymbol(); + } + + var signature = this.resolveOverloads(callEx, signatures, callEx.argumentList.typeArgumentList !== null, context, diagnostics); + var useBeforeResolutionSignatures = signature == null; + + if (!signature) { + for (var i = 0; i < diagnostics.length; i++) { + this.postOverloadResolutionDiagnostics(diagnostics[i], additionalResults, context); + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Could_not_select_overload_for_call_expression), additionalResults, context); + + errorCondition = this.getNewErrorTypeSymbol(); + + if (!signatures.length) { + return errorCondition; + } + + signature = signatures[0]; + } + + var rootSignature = signature.getRootSymbol(); + if (!rootSignature.isGeneric() && callEx.argumentList.typeArgumentList) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Non_generic_functions_may_not_accept_type_arguments), additionalResults, context); + } else if (rootSignature.isGeneric() && callEx.argumentList.typeArgumentList && rootSignature.getTypeParameters() && (callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount() !== rootSignature.getTypeParameters().length)) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [rootSignature.getTypeParameters().length, callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()]), additionalResults, context); + } + + var returnType = isSuperCall ? this.semanticInfoChain.voidTypeSymbol : signature.returnType; + + var actualParametersContextTypeSymbols = []; + if (callEx.argumentList.arguments) { + var len = callEx.argumentList.arguments.nonSeparatorCount(); + var params = signature.parameters; + var contextualType = null; + var signatureDecl = signature.getDeclarations()[0]; + + for (var i = 0; i < len; i++) { + if (params.length) { + if (i < params.length - 1 || (i < params.length && !signature.hasVarArgs)) { + this.resolveDeclaredSymbol(params[i], context); + contextualType = params[i].type; + } else if (signature.hasVarArgs) { + contextualType = params[params.length - 1].type; + if (contextualType.isArrayNamedTypeReference()) { + contextualType = contextualType.getElementType(); + } + } + } + + if (contextualType) { + context.pushNewContextualType(contextualType); + actualParametersContextTypeSymbols[i] = contextualType; + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + additionalResults.targetSymbol = targetSymbol; + if (useBeforeResolutionSignatures && beforeResolutionSignatures) { + additionalResults.resolvedSignatures = beforeResolutionSignatures; + additionalResults.candidateSignature = beforeResolutionSignatures[0]; + } else { + additionalResults.resolvedSignatures = signatures; + additionalResults.candidateSignature = signature; + } + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + + if (errorCondition) { + return errorCondition; + } + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return returnType; + }; + + PullTypeResolver.prototype.resolveObjectCreationExpression = function (callEx, context, additionalResults) { + var symbol = this.getSymbolForAST(callEx, context); + + if (!symbol || !symbol.isResolved) { + if (!additionalResults) { + additionalResults = new PullAdditionalCallResolutionData(); + } + symbol = this.computeObjectCreationExpressionSymbol(callEx, context, additionalResults); + if (this.canTypeCheckAST(callEx, context)) { + this.setTypeChecked(callEx, context); + } + this.setSymbolForAST(callEx, symbol, context); + this.semanticInfoChain.setCallResolutionDataForAST(callEx, additionalResults); + } else { + if (this.canTypeCheckAST(callEx, context)) { + this.typeCheckObjectCreationExpression(callEx, context); + } + + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + if (additionalResults && (callResolutionData !== additionalResults)) { + additionalResults.actualParametersContextTypeSymbols = callResolutionData.actualParametersContextTypeSymbols; + additionalResults.candidateSignature = callResolutionData.candidateSignature; + additionalResults.resolvedSignatures = callResolutionData.resolvedSignatures; + additionalResults.targetSymbol = callResolutionData.targetSymbol; + } + } + + return symbol; + }; + + PullTypeResolver.prototype.typeCheckObjectCreationExpression = function (callEx, context) { + this.setTypeChecked(callEx, context); + this.resolveAST(callEx.expression, false, context); + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + if (callEx.argumentList) { + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + var len = callEx.argumentList.arguments.nonSeparatorCount(); + + for (var i = 0; i < len; i++) { + var contextualType = callResolutionData.actualParametersContextTypeSymbols ? callResolutionData.actualParametersContextTypeSymbols[i] : null; + if (contextualType) { + context.pushNewContextualType(contextualType); + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + for (var i = 0; i < callResolutionData.diagnosticsFromOverloadResolution.length; i++) { + context.postDiagnostic(callResolutionData.diagnosticsFromOverloadResolution[i]); + } + }; + + PullTypeResolver.prototype.postOverloadResolutionDiagnostics = function (diagnostic, additionalResults, context) { + if (!context.inProvisionalResolution()) { + additionalResults.diagnosticsFromOverloadResolution.push(diagnostic); + } + context.postDiagnostic(diagnostic); + }; + + PullTypeResolver.prototype.computeObjectCreationExpressionSymbol = function (callEx, context, additionalResults) { + var _this = this; + var returnType = null; + + var targetSymbol = this.resolveAST(callEx.expression, false, context); + var targetTypeSymbol = targetSymbol.isType() ? targetSymbol : targetSymbol.type; + + var targetAST = this.getCallTargetErrorSpanAST(callEx); + + var constructSignatures = targetTypeSymbol.getConstructSignatures(); + + var explicitTypeArgs = null; + var usedCallSignaturesInstead = false; + var couldNotAssignToConstraint; + var constraintDiagnostic = null; + var typeArgumentCountDiagnostic = null; + var diagnostics = []; + + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + if (callEx.argumentList) { + this.resolveAST(callEx.argumentList.arguments, false, context); + } + + return targetTypeSymbol; + } + + if (!constructSignatures.length) { + constructSignatures = targetTypeSymbol.getCallSignatures(); + usedCallSignaturesInstead = true; + + if (this.compilationSettings.noImplicitAny()) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.new_expression_which_lacks_a_constructor_signature_implicitly_has_an_any_type), additionalResults, context); + } + } + + if (constructSignatures.length) { + if (callEx.argumentList && callEx.argumentList.typeArgumentList) { + explicitTypeArgs = []; + + if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { + for (var i = 0; i < callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { + explicitTypeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + } + } + } + + if (targetTypeSymbol.isGeneric()) { + var resolvedSignatures = []; + var inferredOrExplicitTypeArgs; + var specializedSignature; + var typeParameters; + var typeConstraint = null; + var triedToInferTypeArgs; + var targetTypeReplacementMap = targetTypeSymbol.getTypeParameterArgumentMap(); + + for (var i = 0; i < constructSignatures.length; i++) { + couldNotAssignToConstraint = false; + + if (constructSignatures[i].isGeneric()) { + typeParameters = constructSignatures[i].getTypeParameters(); + + if (explicitTypeArgs) { + if (explicitTypeArgs.length === typeParameters.length) { + inferredOrExplicitTypeArgs = explicitTypeArgs; + } else { + typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, explicitTypeArgs.length]); + continue; + } + } else if (callEx.argumentList) { + var typeArgumentInferenceContext = new TypeScript.InvocationTypeArgumentInferenceContext(this, context, constructSignatures[i], callEx.argumentList.arguments); + inferredOrExplicitTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); + triedToInferTypeArgs = true; + } else { + inferredOrExplicitTypeArgs = TypeScript.ArrayUtilities.select(typeParameters, function (typeParameter) { + return typeParameter.getDefaultConstraint(_this.semanticInfoChain); + }); + } + + TypeScript.Debug.assert(inferredOrExplicitTypeArgs && inferredOrExplicitTypeArgs.length == typeParameters.length); + + var mutableTypeReplacementMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(targetTypeReplacementMap ? targetTypeReplacementMap : []); + TypeScript.PullInstantiationHelpers.updateMutableTypeParameterArgumentMap(typeParameters, inferredOrExplicitTypeArgs, mutableTypeReplacementMap); + var typeReplacementMap = mutableTypeReplacementMap.typeParameterArgumentMap; + + if (explicitTypeArgs) { + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); + } + + if (!this.sourceIsAssignableToTarget(inferredOrExplicitTypeArgs[j], typeConstraint, targetAST, context, null, true)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); + constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredOrExplicitTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); + couldNotAssignToConstraint = true; + } + + if (couldNotAssignToConstraint) { + break; + } + } + } + } + + if (couldNotAssignToConstraint) { + continue; + } + + specializedSignature = this.instantiateSignature(constructSignatures[i], typeReplacementMap); + + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; + } + } else { + if (!(callEx.argumentList && callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount())) { + resolvedSignatures[resolvedSignatures.length] = constructSignatures[i]; + } + } + } + + constructSignatures = resolvedSignatures; + } + + var signature = this.resolveOverloads(callEx, constructSignatures, callEx.argumentList && callEx.argumentList.typeArgumentList !== null, context, diagnostics); + + additionalResults.targetSymbol = targetSymbol; + additionalResults.resolvedSignatures = constructSignatures; + additionalResults.candidateSignature = signature; + additionalResults.actualParametersContextTypeSymbols = []; + + if (!constructSignatures.length) { + if (constraintDiagnostic) { + this.postOverloadResolutionDiagnostics(constraintDiagnostic, additionalResults, context); + } else if (typeArgumentCountDiagnostic) { + this.postOverloadResolutionDiagnostics(typeArgumentCountDiagnostic, additionalResults, context); + } + + return this.getNewErrorTypeSymbol(); + } + + var errorCondition = null; + + if (!signature) { + for (var i = 0; i < diagnostics.length; i++) { + this.postOverloadResolutionDiagnostics(diagnostics[i], additionalResults, context); + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Could_not_select_overload_for_new_expression), additionalResults, context); + + errorCondition = this.getNewErrorTypeSymbol(); + + if (!constructSignatures.length) { + return errorCondition; + } + + signature = constructSignatures[0]; + } + + returnType = signature.returnType; + + if (returnType && !signature.isGeneric() && returnType.isGeneric() && !returnType.getIsSpecialized()) { + if (explicitTypeArgs && explicitTypeArgs.length) { + returnType = this.createInstantiatedType(returnType, explicitTypeArgs); + } else { + returnType = this.instantiateTypeToAny(returnType, context); + } + } + + if (usedCallSignaturesInstead) { + if (returnType !== this.semanticInfoChain.voidTypeSymbol) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Call_signatures_used_in_a_new_expression_must_have_a_void_return_type), additionalResults, context); + + return this.getNewErrorTypeSymbol(); + } else { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + } + + if (!returnType) { + returnType = signature.returnType; + + if (!returnType) { + returnType = targetTypeSymbol; + } + } + + var actualParametersContextTypeSymbols = []; + if (callEx.argumentList && callEx.argumentList.arguments) { + var len = callEx.argumentList.arguments.nonSeparatorCount(); + var params = signature.parameters; + var contextualType = null; + var signatureDecl = signature.getDeclarations()[0]; + + for (var i = 0; i < len; i++) { + if (params.length) { + if (i < params.length - 1 || (i < params.length && !signature.hasVarArgs)) { + this.resolveDeclaredSymbol(params[i], context); + contextualType = params[i].type; + } else if (signature.hasVarArgs) { + contextualType = params[params.length - 1].type; + if (contextualType.isArrayNamedTypeReference()) { + contextualType = contextualType.getElementType(); + } + } + } + + if (contextualType) { + context.pushNewContextualType(contextualType); + actualParametersContextTypeSymbols[i] = contextualType; + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + additionalResults.targetSymbol = targetSymbol; + additionalResults.resolvedSignatures = constructSignatures; + additionalResults.candidateSignature = signature; + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + + if (errorCondition) { + return errorCondition; + } + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return returnType; + } else if (callEx.argumentList) { + this.resolveAST(callEx.argumentList.arguments, false, context); + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Invalid_new_expression), additionalResults, context); + + return this.getNewErrorTypeSymbol(); + }; + + PullTypeResolver.prototype.instantiateSignatureInContext = function (signatureAToInstantiate, contextualSignatureB, context, shouldFixContextualSignatureParameterTypes) { + var typeReplacementMap = []; + var inferredTypeArgs; + var specializedSignature; + var typeParameters = signatureAToInstantiate.getTypeParameters(); + var typeConstraint = null; + + var typeArgumentInferenceContext = new TypeScript.ContextualSignatureInstantiationTypeArgumentInferenceContext(this, context, signatureAToInstantiate, contextualSignatureB, shouldFixContextualSignatureParameterTypes); + inferredTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); + + var functionTypeA = signatureAToInstantiate.functionType; + var functionTypeB = contextualSignatureB.functionType; + var enclosingTypeParameterMap; + + if (functionTypeA) { + enclosingTypeParameterMap = functionTypeA.getTypeParameterArgumentMap(); + + for (var id in enclosingTypeParameterMap) { + typeReplacementMap[id] = enclosingTypeParameterMap[id]; + } + } + + if (functionTypeB) { + enclosingTypeParameterMap = functionTypeB.getTypeParameterArgumentMap(); + + for (var id in enclosingTypeParameterMap) { + typeReplacementMap[id] = enclosingTypeParameterMap[id]; + } + } + + TypeScript.PullInstantiationHelpers.updateTypeParameterArgumentMap(typeParameters, inferredTypeArgs, typeReplacementMap); + + return this.instantiateSignature(signatureAToInstantiate, typeReplacementMap); + }; + + PullTypeResolver.prototype.resolveCastExpression = function (assertionExpression, context) { + var typeAssertionType = this.resolveTypeReference(assertionExpression.type, context).type; + + if (this.canTypeCheckAST(assertionExpression, context)) { + this.typeCheckCastExpression(assertionExpression, context, typeAssertionType); + } + + return typeAssertionType; + }; + + PullTypeResolver.prototype.typeCheckCastExpression = function (assertionExpression, context, typeAssertionType) { + this.setTypeChecked(assertionExpression, context); + + context.pushNewContextualType(typeAssertionType); + var exprType = this.resolveAST(assertionExpression.expression, true, context).type; + context.popAnyContextualType(); + + this.resolveDeclaredSymbol(typeAssertionType, context); + this.resolveDeclaredSymbol(exprType, context); + + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(exprType, typeAssertionType, assertionExpression, context, comparisonInfo); + + if (!isAssignable) { + var widenedExprType = exprType.widenedType(this, assertionExpression.expression, context); + isAssignable = this.sourceIsAssignableToTarget(typeAssertionType, widenedExprType, assertionExpression, context, comparisonInfo); + } + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(assertionExpression); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(assertionExpression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [exprType.toString(enclosingSymbol), typeAssertionType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(assertionExpression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [exprType.toString(enclosingSymbol), typeAssertionType.toString(enclosingSymbol)])); + } + } + }; + + PullTypeResolver.prototype.resolveAssignmentExpression = function (binaryExpression, context) { + var leftExpr = this.resolveAST(binaryExpression.left, false, context); + var leftType = leftExpr.type; + + context.pushNewContextualType(leftType); + var rightType = this.resolveAST(binaryExpression.right, true, context).type; + context.popAnyContextualType(); + + rightType = this.getInstanceTypeForAssignment(binaryExpression.left, rightType, context); + + if (this.canTypeCheckAST(binaryExpression, context)) { + this.setTypeChecked(binaryExpression, context); + + if (!this.isReference(binaryExpression.left, leftExpr)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_left_hand_side_of_assignment_expression)); + } else { + this.checkAssignability(binaryExpression.left, rightType, leftExpr.type, context); + } + } + + return rightType; + }; + + PullTypeResolver.prototype.getInstanceTypeForAssignment = function (lhs, type, context) { + var typeToReturn = type; + if (typeToReturn && typeToReturn.isAlias()) { + typeToReturn = typeToReturn.getExportAssignedTypeSymbol(); + } + + if (typeToReturn && typeToReturn.isContainer() && !typeToReturn.isEnum()) { + var instanceTypeSymbol = typeToReturn.getInstanceType(); + + if (!instanceTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(lhs, TypeScript.DiagnosticCode.Tried_to_set_variable_type_to_uninitialized_module_type_0, [type.toString()])); + typeToReturn = null; + } else { + typeToReturn = instanceTypeSymbol; + } + } + + return typeToReturn; + }; + + PullTypeResolver.prototype.widenType = function (type, ast, context) { + if (type === this.semanticInfoChain.undefinedTypeSymbol || type === this.semanticInfoChain.nullTypeSymbol || type.isError()) { + return this.semanticInfoChain.anyTypeSymbol; + } + + if (type.isArrayNamedTypeReference()) { + return this.widenArrayType(type, ast, context); + } else if (type.kind === 256 /* ObjectLiteral */) { + return this.widenObjectLiteralType(type, ast, context); + } + + return type; + }; + + PullTypeResolver.prototype.widenArrayType = function (type, ast, context) { + var elementType = type.getElementType().widenedType(this, ast, context); + + if (this.compilationSettings.noImplicitAny() && ast) { + if (elementType === this.semanticInfoChain.anyTypeSymbol && type.getElementType() !== this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Array_Literal_implicitly_has_an_any_type_from_widening)); + } + } + + return this.getArrayType(elementType); + }; + + PullTypeResolver.prototype.widenObjectLiteralType = function (type, ast, context) { + if (!this.needsToWidenObjectLiteralType(type, ast, context)) { + return type; + } + + TypeScript.Debug.assert(type.name === ""); + var newObjectTypeSymbol = new TypeScript.PullTypeSymbol(type.name, type.kind); + var declsOfObjectType = type.getDeclarations(); + TypeScript.Debug.assert(declsOfObjectType.length === 1); + newObjectTypeSymbol.addDeclaration(declsOfObjectType[0]); + var members = type.getMembers(); + + for (var i = 0; i < members.length; i++) { + var memberType = members[i].type; + + var widenedMemberType = members[i].type.widenedType(this, ast, context); + var newMember = new TypeScript.PullSymbol(members[i].name, members[i].kind); + + var declsOfMember = members[i].getDeclarations(); + + newMember.addDeclaration(declsOfMember[0]); + newMember.type = widenedMemberType; + newObjectTypeSymbol.addMember(newMember); + newMember.setResolved(); + + if (this.compilationSettings.noImplicitAny() && ast && widenedMemberType === this.semanticInfoChain.anyTypeSymbol && memberType !== this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Object_literal_s_property_0_implicitly_has_an_any_type_from_widening, [members[i].name])); + } + } + + var indexers = type.getIndexSignatures(); + for (var i = 0; i < indexers.length; i++) { + var newIndexer = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + var parameter = indexers[i].parameters[0]; + var newParameter = new TypeScript.PullSymbol(parameter.name, parameter.kind); + newParameter.type = parameter.type; + newIndexer.addParameter(newParameter); + newIndexer.returnType = indexers[i].returnType; + newObjectTypeSymbol.addIndexSignature(newIndexer); + } + + return newObjectTypeSymbol; + }; + + PullTypeResolver.prototype.needsToWidenObjectLiteralType = function (type, ast, context) { + var members = type.getMembers(); + for (var i = 0; i < members.length; i++) { + var memberType = members[i].type; + if (memberType !== memberType.widenedType(this, ast, context)) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.findBestCommonType = function (collection, context, comparisonInfo) { + var len = collection.getLength(); + + for (var i = 0; i < len; i++) { + var candidateType = collection.getTypeAtIndex(i); + if (this.typeIsBestCommonTypeCandidate(candidateType, collection, context)) { + return candidateType; + } + } + + return this.semanticInfoChain.emptyTypeSymbol; + }; + + PullTypeResolver.prototype.typeIsBestCommonTypeCandidate = function (candidateType, collection, context) { + for (var i = 0; i < collection.getLength(); i++) { + var otherType = collection.getTypeAtIndex(i); + if (candidateType === otherType) { + continue; + } + + if (!this.sourceIsSubtypeOfTarget(otherType, candidateType, null, context)) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.typesAreIdenticalInEnclosingTypes = function (t1, t2, context) { + t1 = this.getSymbolForRelationshipCheck(t1); + t2 = this.getSymbolForRelationshipCheck(t2); + + if (t1 === t2) { + return true; + } + + if (t1 && t2) { + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + return this.infinitelyExpandingTypesAreIdentical(t1, t2, context); + } + } + + return this.typesAreIdentical(t1, t2, context); + }; + + PullTypeResolver.prototype.typesAreIdenticalWithNewEnclosingTypes = function (t1, t2, context) { + var enclosingTypeWalkerStates = context.resetEnclosingTypeWalkerStates(); + var areTypesIdentical = this.typesAreIdentical(t1, t2, context); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areTypesIdentical; + }; + + PullTypeResolver.prototype.typesAreIdentical = function (t1, t2, context) { + t1 = this.getSymbolForRelationshipCheck(t1); + t2 = this.getSymbolForRelationshipCheck(t2); + + if (t1 === t2) { + return true; + } + + if (!t1 || !t2) { + return false; + } + + if (TypeScript.hasFlag(t1.kind, 64 /* Enum */) || TypeScript.hasFlag(t2.kind, 64 /* Enum */)) { + return false; + } + + if (t1.isPrimitive() && t1.isStringConstant() && t2.isPrimitive() && t2.isStringConstant()) { + return TypeScript.stripStartAndEndQuotes(t1.name) === TypeScript.stripStartAndEndQuotes(t2.name); + } + + if (t1.isPrimitive() || t2.isPrimitive()) { + return false; + } + + if (t1.isError() && t2.isError()) { + return true; + } + + var isIdentical = this.identicalCache.valueAt(t1.pullSymbolID, t2.pullSymbolID); + if (isIdentical != undefined) { + return isIdentical; + } + + if (t1.isTypeParameter() !== t2.isTypeParameter()) { + return false; + } else if (t1.isTypeParameter()) { + var t1ParentDeclaration = t1.getDeclarations()[0].getParentDecl(); + var t2ParentDeclaration = t2.getDeclarations()[0].getParentDecl(); + + if (t1ParentDeclaration === t2ParentDeclaration) { + return this.symbolsShareDeclaration(t1, t2); + } else { + return false; + } + } + + if (t1.isPrimitive() !== t2.isPrimitive()) { + return false; + } + + this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, true); + var statesWhenStartedWalkingTypes = context.startWalkingTypes(t1, t2); + isIdentical = this.typesAreIdenticalWorker(t1, t2, context); + context.endWalkingTypes(statesWhenStartedWalkingTypes); + this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, isIdentical); + + return isIdentical; + }; + + PullTypeResolver.prototype.typesAreIdenticalWorker = function (t1, t2, context) { + if (t1.getIsSpecialized() && t2.getIsSpecialized()) { + if (TypeScript.PullHelpers.getRootType(t1) === TypeScript.PullHelpers.getRootType(t2) && TypeScript.PullHelpers.getRootType(t1).isNamedTypeSymbol()) { + var t1TypeArguments = t1.getTypeArguments(); + var t2TypeArguments = t2.getTypeArguments(); + + if (t1TypeArguments && t2TypeArguments) { + for (var i = 0; i < t1TypeArguments.length; i++) { + if (!this.typesAreIdenticalWithNewEnclosingTypes(t1TypeArguments[i], t2TypeArguments[i], context)) { + return false; + } + } + } + + return true; + } + } + + if (t1.hasMembers() && t2.hasMembers()) { + var t1Members = t1.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + var t2Members = t2.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + + if (t1Members.length !== t2Members.length) { + return false; + } + + var t1MemberSymbol = null; + var t2MemberSymbol = null; + + var t1MemberType = null; + var t2MemberType = null; + + for (var iMember = 0; iMember < t1Members.length; iMember++) { + t1MemberSymbol = t1Members[iMember]; + t2MemberSymbol = this.getNamedPropertySymbol(t1MemberSymbol.name, 68147712 /* SomeValue */, t2); + + if (!this.propertiesAreIdentical(t1MemberSymbol, t2MemberSymbol, context)) { + return false; + } + } + } else if (t1.hasMembers() || t2.hasMembers()) { + return false; + } + + var t1CallSigs = t1.getCallSignatures(); + var t2CallSigs = t2.getCallSignatures(); + + var t1ConstructSigs = t1.getConstructSignatures(); + var t2ConstructSigs = t2.getConstructSignatures(); + + var t1IndexSigs = t1.getIndexSignatures(); + var t2IndexSigs = t2.getIndexSignatures(); + + if (!this.signatureGroupsAreIdentical(t1CallSigs, t2CallSigs, context)) { + return false; + } + + if (!this.signatureGroupsAreIdentical(t1ConstructSigs, t2ConstructSigs, context)) { + return false; + } + + if (!this.signatureGroupsAreIdentical(t1IndexSigs, t2IndexSigs, context)) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.propertiesAreIdentical = function (propertySymbol1, propertySymbol2, context) { + if (!propertySymbol2 || (propertySymbol1.isOptional !== propertySymbol2.isOptional)) { + return false; + } + + var t1MemberSymbolIsPrivate = propertySymbol1.anyDeclHasFlag(2 /* Private */); + var t2MemberSymbolIsPrivate = propertySymbol2.anyDeclHasFlag(2 /* Private */); + + if (t1MemberSymbolIsPrivate !== t2MemberSymbolIsPrivate) { + return false; + } else if (t2MemberSymbolIsPrivate && t1MemberSymbolIsPrivate) { + var t1MemberSymbolDecl = propertySymbol1.getDeclarations()[0]; + var sourceDecl = propertySymbol2.getDeclarations()[0]; + if (t1MemberSymbolDecl !== sourceDecl) { + return false; + } + } + + var t1MemberType = propertySymbol1.type; + var t2MemberType = propertySymbol2.type; + + context.walkMemberTypes(propertySymbol1.name); + var areMemberTypesIdentical = this.typesAreIdenticalInEnclosingTypes(t1MemberType, t2MemberType, context); + context.postWalkMemberTypes(); + return areMemberTypesIdentical; + }; + + PullTypeResolver.prototype.propertiesAreIdenticalWithNewEnclosingTypes = function (type1, type2, property1, property2, context) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(type1, type2); + var arePropertiesIdentical = this.propertiesAreIdentical(property1, property2, context); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return arePropertiesIdentical; + }; + + PullTypeResolver.prototype.signatureGroupsAreIdentical = function (sg1, sg2, context) { + if (sg1 === sg2) { + return true; + } + + if (!sg1 || !sg2) { + return false; + } + + if (sg1.length !== sg2.length) { + return false; + } + + for (var i = 0; i < sg1.length; i++) { + context.walkSignatures(sg1[i].kind, i); + var areSignaturesIdentical = this.signaturesAreIdentical(sg1[i], sg2[i], context, true); + context.postWalkSignatures(); + if (!areSignaturesIdentical) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.typeParametersAreIdentical = function (tp1, tp2, context) { + var typeParamsAreIdentical = this.typeParametersAreIdenticalWorker(tp1, tp2, context); + + this.setTypeParameterIdentity(tp1, tp2, undefined); + + return typeParamsAreIdentical; + }; + + PullTypeResolver.prototype.typeParametersAreIdenticalWorker = function (tp1, tp2, context) { + if (!!(tp1 && tp1.length) !== !!(tp2 && tp2.length)) { + return false; + } + + if (tp1 && tp2 && (tp1.length !== tp2.length)) { + return false; + } + + if (tp1 && tp2) { + for (var i = 0; i < tp1.length; i++) { + context.walkTypeParameterConstraints(i); + var areConstraintsIdentical = this.typesAreIdentical(tp1[i].getConstraint(), tp2[i].getConstraint(), context); + context.postWalkTypeParameterConstraints(); + if (!areConstraintsIdentical) { + return false; + } + } + } + + return true; + }; + + PullTypeResolver.prototype.setTypeParameterIdentity = function (tp1, tp2, val) { + if (tp1 && tp2 && tp1.length === tp2.length) { + for (var i = 0; i < tp1.length; i++) { + this.identicalCache.setValueAt(tp1[i].pullSymbolID, tp2[i].pullSymbolID, val); + } + } + }; + + PullTypeResolver.prototype.signaturesAreIdenticalWithNewEnclosingTypes = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(s1, s2); + var areSignaturesIdentical = this.signaturesAreIdentical(s1, s2, context, includingReturnType); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSignaturesIdentical; + }; + + PullTypeResolver.prototype.signaturesAreIdentical = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + if (s1 === s2) { + return true; + } + + var signaturesIdentical = this.identicalCache.valueAt(s1.pullSymbolID, s2.pullSymbolID); + if (signaturesIdentical || (signaturesIdentical != undefined && includingReturnType)) { + return signaturesIdentical; + } + + var oldValue = signaturesIdentical; + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, true); + + signaturesIdentical = this.signaturesAreIdenticalWorker(s1, s2, context, includingReturnType); + + if (includingReturnType) { + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, signaturesIdentical); + } else { + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, oldValue); + } + + return signaturesIdentical; + }; + + PullTypeResolver.prototype.signaturesAreIdenticalWorker = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + if (s1.hasVarArgs !== s2.hasVarArgs) { + return false; + } + + if (s1.nonOptionalParamCount !== s2.nonOptionalParamCount) { + return false; + } + + if (s1.parameters.length !== s2.parameters.length) { + return false; + } + + var s1TypeParameters = s1.getTypeParameters(); + var s2TypeParameters = s2.getTypeParameters(); + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, true); + + var typeParametersParametersAndReturnTypesAreIdentical = this.signatureTypeParametersParametersAndReturnTypesAreIdentical(s1, s2, context, includingReturnType); + + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, undefined); + return typeParametersParametersAndReturnTypesAreIdentical; + }; + + PullTypeResolver.prototype.signatureTypeParametersParametersAndReturnTypesAreIdentical = function (s1, s2, context, includingReturnType) { + if (!this.typeParametersAreIdenticalWorker(s1.getTypeParameters(), s2.getTypeParameters(), context)) { + return false; + } + + if (includingReturnType) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s1); + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s2); + context.walkReturnTypes(); + var areReturnTypesIdentical = this.typesAreIdenticalInEnclosingTypes(s1.returnType, s2.returnType, context); + context.postWalkReturnTypes(); + if (!areReturnTypesIdentical) { + return false; + } + } + + var s1Params = s1.parameters; + var s2Params = s2.parameters; + + for (var iParam = 0; iParam < s1Params.length; iParam++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s1Params[iParam]); + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s2Params[iParam]); + context.walkParameterTypes(iParam); + var areParameterTypesIdentical = this.typesAreIdenticalInEnclosingTypes(s1Params[iParam].type, s2Params[iParam].type, context); + context.postWalkParameterTypes(); + + if (!areParameterTypesIdentical) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.signatureReturnTypesAreIdentical = function (s1, s2, context) { + var s1TypeParameters = s1.getTypeParameters(); + var s2TypeParameters = s2.getTypeParameters(); + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, true); + + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(s1, s2); + context.walkReturnTypes(); + var returnTypeIsIdentical = this.typesAreIdenticalInEnclosingTypes(s1.returnType, s2.returnType, context); + + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, undefined); + + return returnTypeIsIdentical; + }; + + PullTypeResolver.prototype.symbolsShareDeclaration = function (symbol1, symbol2) { + var decls1 = symbol1.getDeclarations(); + var decls2 = symbol2.getDeclarations(); + + if (decls1.length && decls2.length) { + return decls1[0] === decls2[0]; + } + + return false; + }; + + PullTypeResolver.prototype.sourceIsSubtypeOfTarget = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.sourceMembersAreAssignableToTargetMembers = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceMembersAreAssignableToTargetMembers = this.sourceMembersAreRelatableToTargetMembers(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceMembersAreAssignableToTargetMembers; + }; + + PullTypeResolver.prototype.sourcePropertyIsAssignableToTargetProperty = function (source, target, sourceProp, targetProp, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var isSourcePropertyIsAssignableToTargetProperty = this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return isSourcePropertyIsAssignableToTargetProperty; + }; + + PullTypeResolver.prototype.sourceCallSignaturesAreAssignableToTargetCallSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceCallSignaturesAssignableToTargetCallSignatures = this.sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceCallSignaturesAssignableToTargetCallSignatures; + }; + + PullTypeResolver.prototype.sourceConstructSignaturesAreAssignableToTargetConstructSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceConstructSignaturesAssignableToTargetConstructSignatures = this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceConstructSignaturesAssignableToTargetConstructSignatures; + }; + + PullTypeResolver.prototype.sourceIndexSignaturesAreAssignableToTargetIndexSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceIndexSignaturesAssignableToTargetIndexSignatures = this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceIndexSignaturesAssignableToTargetIndexSignatures; + }; + + PullTypeResolver.prototype.typeIsAssignableToFunction = function (source, ast, context) { + if (source.isFunctionType()) { + return true; + } + + return this.cachedFunctionInterfaceType() && this.sourceIsAssignableToTarget(source, this.cachedFunctionInterfaceType(), ast, context); + }; + + PullTypeResolver.prototype.signatureIsAssignableToTarget = function (s1, s2, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(s1, s2); + var isSignatureIsAssignableToTarget = this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return isSignatureIsAssignableToTarget; + }; + + PullTypeResolver.prototype.sourceIsAssignableToTarget = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + return this.sourceIsRelatableToTarget(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.sourceIsAssignableToTargetWithNewEnclosingTypes = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + return this.sourceIsRelatableToTargetWithNewEnclosingTypes(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.getSymbolForRelationshipCheck = function (symbol) { + if (symbol && symbol.isTypeReference()) { + return symbol.getReferencedTypeSymbol(); + } + + return symbol; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetInEnclosingTypes = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + source = this.getSymbolForRelationshipCheck(source); + target = this.getSymbolForRelationshipCheck(target); + + if (source === target) { + return true; + } + + if (source && target) { + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + return this.infinitelyExpandingSourceTypeIsRelatableToTargetType(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + } + } + + return this.sourceIsRelatableToTarget(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetWithNewEnclosingTypes = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.resetEnclosingTypeWalkerStates(); + var isSourceRelatable = this.sourceIsRelatableToTarget(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return isSourceRelatable; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetInCache = function (source, target, comparisonCache, comparisonInfo) { + var isRelatable = comparisonCache.valueAt(source.pullSymbolID, target.pullSymbolID); + + if (isRelatable) { + return { isRelatable: isRelatable }; + } + + if (isRelatable != undefined && !comparisonInfo) { + return { isRelatable: isRelatable }; + } + + return null; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + source = this.getSymbolForRelationshipCheck(source); + target = this.getSymbolForRelationshipCheck(target); + + if (source === target) { + return true; + } + + if (!(source && target)) { + return true; + } + + var sourceApparentType = this.getApparentType(source); + + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(source, target, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; + } + + if (source === this.semanticInfoChain.stringTypeSymbol && target.isPrimitive() && target.isStringConstant()) { + return comparisonInfo && comparisonInfo.stringConstantVal && (comparisonInfo.stringConstantVal.kind() === 14 /* StringLiteral */) && (TypeScript.stripStartAndEndQuotes(comparisonInfo.stringConstantVal.text()) === TypeScript.stripStartAndEndQuotes(target.name)); + } + + if (assignableTo) { + if (this.isAnyOrEquivalent(source) || this.isAnyOrEquivalent(target)) { + return true; + } + } else { + if (this.isAnyOrEquivalent(target)) { + return true; + } + } + + if (target === this.semanticInfoChain.stringTypeSymbol && source.isPrimitive() && source.isStringConstant()) { + return true; + } + + if (source.isPrimitive() && source.isStringConstant() && target.isPrimitive() && target.isStringConstant()) { + return TypeScript.stripStartAndEndQuotes(source.name) === TypeScript.stripStartAndEndQuotes(target.name); + } + + if (source === this.semanticInfoChain.undefinedTypeSymbol) { + return true; + } + + if ((source === this.semanticInfoChain.nullTypeSymbol) && (target !== this.semanticInfoChain.undefinedTypeSymbol && target != this.semanticInfoChain.voidTypeSymbol)) { + return true; + } + + if (target === this.semanticInfoChain.voidTypeSymbol) { + if (source === this.semanticInfoChain.undefinedTypeSymbol || source == this.semanticInfoChain.nullTypeSymbol) { + return true; + } + + return false; + } else if (source === this.semanticInfoChain.voidTypeSymbol) { + if (target === this.semanticInfoChain.anyTypeSymbol) { + return true; + } + + return false; + } + + if (target === this.semanticInfoChain.numberTypeSymbol && TypeScript.PullHelpers.symbolIsEnum(source)) { + return true; + } + + if (source === this.semanticInfoChain.numberTypeSymbol && TypeScript.PullHelpers.symbolIsEnum(target)) { + return assignableTo; + } + + if (TypeScript.PullHelpers.symbolIsEnum(target) && TypeScript.PullHelpers.symbolIsEnum(source)) { + return this.symbolsShareDeclaration(target, source); + } + + if ((source.kind & 64 /* Enum */) || (target.kind & 64 /* Enum */)) { + return false; + } + + if (source.getIsSpecialized() && target.getIsSpecialized()) { + if (TypeScript.PullHelpers.getRootType(source) === TypeScript.PullHelpers.getRootType(target) && TypeScript.PullHelpers.getRootType(source).isNamedTypeSymbol()) { + var sourceTypeArguments = source.getTypeArguments(); + var targetTypeArguments = target.getTypeArguments(); + + if (sourceTypeArguments && targetTypeArguments) { + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, true); + + for (var i = 0; i < sourceTypeArguments.length; i++) { + if (!this.sourceIsRelatableToTargetWithNewEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, null, isComparingInstantiatedSignatures)) { + break; + } + } + + if (i === sourceTypeArguments.length) { + return true; + } else { + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, undefined); + } + } + } + } + + if (target.isTypeParameter()) { + if (source.isTypeParameter()) { + if (!source.getConstraint()) { + return this.typesAreIdentical(target, source, context); + } else { + return this.isSourceTypeParameterConstrainedToTargetTypeParameter(source, target); + } + } else { + if (isComparingInstantiatedSignatures) { + target = target.getBaseConstraint(this.semanticInfoChain); + } else { + return this.typesAreIdentical(target, sourceApparentType, context); + } + } + } + + if (sourceApparentType.isPrimitive() || target.isPrimitive()) { + return false; + } + + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, true); + + var symbolsWhenStartedWalkingTypes = context.startWalkingTypes(sourceApparentType, target); + var isRelatable = this.sourceIsRelatableToTargetWorker(sourceApparentType, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.endWalkingTypes(symbolsWhenStartedWalkingTypes); + + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.isSourceTypeParameterConstrainedToTargetTypeParameter = function (source, target) { + var current = source; + while (current && current.isTypeParameter()) { + if (current === target) { + return true; + } + + current = current.getConstraint(); + } + return false; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetWorker = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + if (target.hasMembers() && !this.sourceMembersAreRelatableToTargetMembers(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.sourceMembersAreRelatableToTargetMembers = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetProps = target.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + + for (var itargetProp = 0; itargetProp < targetProps.length; itargetProp++) { + var targetProp = targetProps[itargetProp]; + + var sourceProp = this._getNamedPropertySymbolOfAugmentedType(targetProp.name, source); + + this.resolveDeclaredSymbol(targetProp, context); + + var targetPropType = targetProp.type; + + if (!sourceProp) { + if (!(targetProp.isOptional)) { + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_is_missing_property_1_from_type_2, [source.toString(enclosingSymbol), targetProp.getScopedNameEx().toString(), target.toString(enclosingSymbol)])); + } + return false; + } + continue; + } + + if (!this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.infinitelyExpandingSourceTypeIsRelatableToTargetType = function (sourceType, targetType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var widenedTargetType = targetType.widenedType(this, null, context); + var widenedSourceType = sourceType.widenedType(this, null, context); + + if ((widenedSourceType !== this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType !== this.semanticInfoChain.anyTypeSymbol)) { + var sourceTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(sourceType); + var targetTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(targetType); + + if (sourceTypeNamedTypeReference !== targetTypeNamedTypeReference) { + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_do_not_refer_to_same_named_type, [sourceType.getScopedNameEx(enclosingSymbol).toString(), targetType.toString(enclosingSymbol)])); + } + return false; + } + + var sourceTypeArguments = sourceType.getTypeArguments(); + var targetTypeArguments = targetType.getTypeArguments(); + + if (!sourceTypeArguments && !targetTypeArguments) { + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, true); + return true; + } + + if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length !== targetTypeArguments.length) { + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)])); + } + return false; + } + + var comparisonInfoTypeArgumentsCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoTypeArgumentsCheck = new TypeComparisonInfo(comparisonInfo); + } + var isRelatable = true; + for (var i = 0; i < sourceTypeArguments.length && isRelatable; i++) { + context.walkTypeArgument(i); + + if (!this.sourceIsRelatableToTargetInEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, comparisonInfoTypeArgumentsCheck, isComparingInstantiatedSignatures)) { + isRelatable = false; + if (comparisonInfo) { + var message; + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + + if (comparisonInfoTypeArgumentsCheck && comparisonInfoTypeArgumentsCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol), comparisonInfoTypeArgumentsCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)]); + } + comparisonInfo.addMessage(message); + } + } + + context.postWalkTypeArgument(); + } + } + + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.infinitelyExpandingTypesAreIdentical = function (sourceType, targetType, context) { + var widenedTargetType = targetType.widenedType(this, null, null); + var widenedSourceType = sourceType.widenedType(this, null, null); + + if ((widenedSourceType !== this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType !== this.semanticInfoChain.anyTypeSymbol)) { + var sourceTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(sourceType); + var targetTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(targetType); + if (sourceTypeNamedTypeReference !== targetTypeNamedTypeReference) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + return false; + } + + var sourceTypeArguments = sourceType.getTypeArguments(); + var targetTypeArguments = targetType.getTypeArguments(); + + if (!sourceTypeArguments && !targetTypeArguments) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, true); + return true; + } + + if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length !== targetTypeArguments.length) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + return false; + } + + for (var i = 0; i < sourceTypeArguments.length; i++) { + context.walkTypeArgument(i); + var areIdentical = this.typesAreIdenticalInEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], context); + context.postWalkTypeArgument(); + + if (!areIdentical) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + return false; + } + } + } + + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, true); + return true; + }; + + PullTypeResolver.prototype.sourcePropertyIsRelatableToTargetProperty = function (source, target, sourceProp, targetProp, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var _this = this; + var sourceAndTargetAreConstructors = source.isConstructor() && target.isConstructor(); + + var getNames = function (takeTypesFromPropertyContainers) { + var enclosingSymbol = _this.getEnclosingSymbolForAST(ast); + var sourceType = takeTypesFromPropertyContainers ? sourceProp.getContainer() : source; + var targetType = takeTypesFromPropertyContainers ? targetProp.getContainer() : target; + if (sourceAndTargetAreConstructors) { + sourceType = sourceType.getAssociatedContainerType(); + targetType = targetType.getAssociatedContainerType(); + } + return { + propertyName: targetProp.getScopedNameEx().toString(), + sourceTypeName: sourceType.toString(enclosingSymbol), + targetTypeName: targetType.toString(enclosingSymbol) + }; + }; + + var targetPropIsPrivate = targetProp.anyDeclHasFlag(2 /* Private */); + var sourcePropIsPrivate = sourceProp.anyDeclHasFlag(2 /* Private */); + + if (targetPropIsPrivate !== sourcePropIsPrivate) { + if (comparisonInfo) { + var names = getNames(true); + var code; + if (targetPropIsPrivate) { + code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Static_property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2 : TypeScript.DiagnosticCode.Property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2; + } else { + code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Static_property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2 : TypeScript.DiagnosticCode.Property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2; + } + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName])); + comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; + } + return false; + } else if (sourcePropIsPrivate && targetPropIsPrivate) { + var targetDecl = targetProp.getDeclarations()[0]; + var sourceDecl = sourceProp.getDeclarations()[0]; + + if (targetDecl !== sourceDecl) { + if (comparisonInfo) { + var names = getNames(true); + + comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_0_and_1_define_static_property_2_as_private : TypeScript.DiagnosticCode.Types_0_and_1_define_property_2_as_private; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(code, [names.sourceTypeName, names.targetTypeName, names.propertyName])); + } + + return false; + } + } + + if (sourceProp.isOptional && !targetProp.isOptional) { + if (comparisonInfo) { + var names = getNames(true); + comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2, [names.propertyName, names.sourceTypeName, names.targetTypeName])); + } + return false; + } + + this.resolveDeclaredSymbol(sourceProp, context); + + var sourcePropType = sourceProp.type; + var targetPropType = targetProp.type; + + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(sourcePropType, targetPropType, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; + } + + var comparisonInfoPropertyTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoPropertyTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + context.walkMemberTypes(targetProp.name); + var isSourcePropertyRelatableToTargetProperty = this.sourceIsRelatableToTargetInEnclosingTypes(sourcePropType, targetPropType, assignableTo, comparisonCache, ast, context, comparisonInfoPropertyTypeCheck, isComparingInstantiatedSignatures); + context.postWalkMemberTypes(); + + if (!isSourcePropertyRelatableToTargetProperty && comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.flags |= 32 /* IncompatiblePropertyTypes */; + var message; + var names = getNames(false); + if (comparisonInfoPropertyTypeCheck && comparisonInfoPropertyTypeCheck.message) { + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3 : TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3; + message = TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName, comparisonInfoPropertyTypeCheck.message]); + } else { + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible : TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible; + message = TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName]); + } + comparisonInfo.addMessage(message); + } + + return isSourcePropertyRelatableToTargetProperty; + }; + + PullTypeResolver.prototype.sourceCallSignaturesAreRelatableToTargetCallSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetCallSigs = target.getCallSignatures(); + + if (targetCallSigs.length) { + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + var sourceCallSigs = source.getCallSignatures(); + if (!this.signatureGroupIsRelatableToTarget(source, target, sourceCallSigs, targetCallSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { + if (comparisonInfo) { + var message; + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + if (sourceCallSigs.length && targetCallSigs.length) { + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signatures_of_types_0_and_1_are_incompatible_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signatures_of_types_0_and_1_are_incompatible, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)]); + } + } else { + var hasSig = targetCallSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + var lacksSig = !targetCallSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_requires_a_call_signature_but_type_1_lacks_one, [hasSig, lacksSig]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.sourceConstructSignaturesAreRelatableToTargetConstructSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetConstructSigs = target.getConstructSignatures(); + if (targetConstructSigs.length) { + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + var sourceConstructSigs = source.getConstructSignatures(); + if (!this.signatureGroupIsRelatableToTarget(source, target, sourceConstructSigs, targetConstructSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + var message; + if (sourceConstructSigs.length && targetConstructSigs.length) { + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Construct_signatures_of_types_0_and_1_are_incompatible_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Construct_signatures_of_types_0_and_1_are_incompatible, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)]); + } + } else { + var hasSig = targetConstructSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + var lacksSig = !targetConstructSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_requires_a_construct_signature_but_type_1_lacks_one, [hasSig, lacksSig]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.sourceIndexSignaturesAreRelatableToTargetIndexSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetIndexSigs = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(target, context); + var targetStringSig = targetIndexSigs.stringSignature; + var targetNumberSig = targetIndexSigs.numericSignature; + + if (targetStringSig || targetNumberSig) { + var sourceIndexSigs = this.getBothKindsOfIndexSignaturesIncludingAugmentedType(source, context); + var enclosingTypeIndexSigs = context.getBothKindOfIndexSignatures(true, false); + var sourceStringSig = sourceIndexSigs.stringSignature; + var sourceNumberSig = sourceIndexSigs.numericSignature; + + var comparable = true; + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + if (targetStringSig) { + if (sourceStringSig) { + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, true, true); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceStringSig.returnType, targetStringSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); + } else { + comparable = false; + } + } + + if (comparable && targetNumberSig) { + if (sourceNumberSig) { + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, false, false); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceNumberSig.returnType, targetNumberSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); + } else if (sourceStringSig) { + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, true, false); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceStringSig.returnType, targetNumberSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); + } else { + comparable = false; + } + } + + if (!comparable) { + if (comparisonInfo) { + var message; + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Index_signatures_of_types_0_and_1_are_incompatible_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Index_signatures_of_types_0_and_1_are_incompatible, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.signatureGroupIsRelatableToTarget = function (source, target, sourceSG, targetSG, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + if (sourceSG === targetSG) { + return true; + } + + if (!(sourceSG.length && targetSG.length)) { + return false; + } + + var foundMatch = false; + + var targetExcludeDefinition = targetSG.length > 1; + var sourceExcludeDefinition = sourceSG.length > 1; + var sigsCompared = 0; + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo, true); + comparisonInfoSignatuesTypeCheck.message = comparisonInfo.message; + } + for (var iMSig = 0; iMSig < targetSG.length; iMSig++) { + var mSig = targetSG[iMSig]; + + if (mSig.isStringConstantOverloadSignature() || (targetExcludeDefinition && mSig.isDefinition())) { + continue; + } + + for (var iNSig = 0; iNSig < sourceSG.length; iNSig++) { + var nSig = sourceSG[iNSig]; + + if (nSig.isStringConstantOverloadSignature() || (sourceExcludeDefinition && nSig.isDefinition())) { + continue; + } + + context.walkSignatures(nSig.kind, iNSig, iMSig); + var isSignatureRelatableToTarget = this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, ast, context, sigsCompared == 0 ? comparisonInfoSignatuesTypeCheck : null, isComparingInstantiatedSignatures); + context.postWalkSignatures(); + + sigsCompared++; + + if (isSignatureRelatableToTarget) { + foundMatch = true; + break; + } + } + + if (foundMatch) { + foundMatch = false; + continue; + } + + if (comparisonInfo && sigsCompared == 1) { + comparisonInfo.message = comparisonInfoSignatuesTypeCheck.message; + } + + return false; + } + + return true; + }; + + PullTypeResolver.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(sourceSig, targetSig, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; + } + + comparisonCache.setValueAt(sourceSig.pullSymbolID, targetSig.pullSymbolID, true); + var isRelatable = this.signatureIsRelatableToTargetWorker(sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + comparisonCache.setValueAt(sourceSig.pullSymbolID, targetSig.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.signatureIsRelatableToTargetWorker = function (sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var _this = this; + var sourceParameters = sourceSig.parameters; + var targetParameters = targetSig.parameters; + + if (!sourceParameters || !targetParameters) { + return false; + } + + var targetNonOptionalParamCount = targetSig.nonOptionalParamCount; + var sourceNonOptionalParamCount = sourceSig.nonOptionalParamCount; + + if (!targetSig.hasVarArgs && sourceNonOptionalParamCount > targetParameters.length) { + if (comparisonInfo) { + comparisonInfo.flags |= 3 /* SourceSignatureHasTooManyParameters */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signature_expects_0_or_fewer_parameters, [targetParameters.length])); + } + return false; + } + + if (this.signaturesAreIdentical(sourceSig, targetSig, context)) { + return true; + } + + if (targetSig.isGeneric()) { + targetSig = this.instantiateSignatureToAny(targetSig); + } + + if (sourceSig.isGeneric()) { + sourceSig = this.instantiateSignatureToAny(sourceSig); + } + + var sourceReturnType = sourceSig.returnType; + var targetReturnType = targetSig.returnType; + + if (targetReturnType !== this.semanticInfoChain.voidTypeSymbol) { + context.walkReturnTypes(); + var returnTypesAreRelatable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceReturnType, targetReturnType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.postWalkReturnTypes(); + if (!returnTypesAreRelatable) { + if (comparisonInfo) { + comparisonInfo.flags |= 16 /* IncompatibleReturnTypes */; + } + + return false; + } + } + + return targetSig.forAllCorrespondingParameterTypesInThisAndOtherSignature(sourceSig, function (targetParamType, sourceParamType, iParam) { + context.walkParameterTypes(iParam); + var areParametersRelatable = _this.sourceIsRelatableToTargetInEnclosingTypes(sourceParamType, targetParamType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + if (!areParametersRelatable) { + context.swapEnclosingTypeWalkers(); + areParametersRelatable = _this.sourceIsRelatableToTargetInEnclosingTypes(targetParamType, sourceParamType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.swapEnclosingTypeWalkers(); + } + context.postWalkParameterTypes(); + + if (!areParametersRelatable) { + if (comparisonInfo) { + comparisonInfo.flags |= 64 /* IncompatibleParameterTypes */; + } + } + + return areParametersRelatable; + }); + }; + + PullTypeResolver.prototype.resolveOverloads = function (application, group, haveTypeArgumentsAtCallSite, context, diagnostics) { + var _this = this; + var hasOverloads = group.length > 1; + var comparisonInfo = new TypeComparisonInfo(); + var args = application.argumentList ? application.argumentList.arguments : null; + + var initialCandidates = TypeScript.ArrayUtilities.where(group, function (signature) { + if (hasOverloads && signature.isDefinition()) { + return false; + } + + var rootSignature = signature.getRootSymbol(); + if (haveTypeArgumentsAtCallSite && !rootSignature.isGeneric()) { + return false; + } + + return _this.overloadHasCorrectArity(signature, args); + }); + + var firstAssignableButNotSupertypeSignature = null; + var firstAssignableWithProvisionalErrorsSignature = null; + + for (var i = 0; i < initialCandidates.length; i++) { + var applicability = this.overloadIsApplicable(initialCandidates[i], args, context, comparisonInfo); + if (applicability === 3 /* Subtype */) { + return initialCandidates[i]; + } else if (applicability === 2 /* AssignableWithNoProvisionalErrors */ && !firstAssignableButNotSupertypeSignature) { + firstAssignableButNotSupertypeSignature = initialCandidates[i]; + } else if (applicability === 1 /* AssignableButWithProvisionalErrors */ && !firstAssignableWithProvisionalErrorsSignature) { + firstAssignableWithProvisionalErrorsSignature = initialCandidates[i]; + } + } + + if (firstAssignableButNotSupertypeSignature || firstAssignableWithProvisionalErrorsSignature) { + return firstAssignableButNotSupertypeSignature || firstAssignableWithProvisionalErrorsSignature; + } else { + var target = this.getCallTargetErrorSpanAST(application); + if (comparisonInfo.message) { + diagnostics.push(this.semanticInfoChain.diagnosticFromAST(target, TypeScript.DiagnosticCode.Supplied_parameters_do_not_match_any_signature_of_call_target_NL_0, [comparisonInfo.message])); + } else { + diagnostics.push(this.semanticInfoChain.diagnosticFromAST(target, TypeScript.DiagnosticCode.Supplied_parameters_do_not_match_any_signature_of_call_target, null)); + } + } + + return null; + }; + + PullTypeResolver.prototype.getCallTargetErrorSpanAST = function (callEx) { + return (callEx.expression.kind() === 212 /* MemberAccessExpression */) ? callEx.expression.name : callEx.expression; + }; + + PullTypeResolver.prototype.overloadHasCorrectArity = function (signature, args) { + if (args == null) { + return signature.nonOptionalParamCount === 0; + } + + var numberOfArgs = (args.nonSeparatorCount() && args.nonSeparatorCount() === args.separatorCount()) ? args.separatorCount() + 1 : args.nonSeparatorCount(); + if (numberOfArgs < signature.nonOptionalParamCount) { + return false; + } + if (!signature.hasVarArgs && numberOfArgs > signature.parameters.length) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.overloadIsApplicable = function (signature, args, context, comparisonInfo) { + if (args === null) { + return 3 /* Subtype */; + } + + var isInVarArg = false; + var parameters = signature.parameters; + var paramType = null; + + var overloadApplicability = 3 /* Subtype */; + + for (var i = 0; i < args.nonSeparatorCount(); i++) { + if (!isInVarArg) { + this.resolveDeclaredSymbol(parameters[i], context); + + if (parameters[i].isVarArg) { + paramType = parameters[i].type.getElementType() || this.getNewErrorTypeSymbol(parameters[i].type.getName()); + isInVarArg = true; + } else { + paramType = parameters[i].type; + } + } + + var statusOfCurrentArgument = this.overloadIsApplicableForArgument(paramType, args.nonSeparatorAt(i), i, context, comparisonInfo); + + if (statusOfCurrentArgument === 0 /* NotAssignable */) { + return 0 /* NotAssignable */; + } else if (statusOfCurrentArgument === 1 /* AssignableButWithProvisionalErrors */) { + overloadApplicability = 1 /* AssignableButWithProvisionalErrors */; + } else if (overloadApplicability !== 1 /* AssignableButWithProvisionalErrors */ && statusOfCurrentArgument === 2 /* AssignableWithNoProvisionalErrors */) { + overloadApplicability = 2 /* AssignableWithNoProvisionalErrors */; + } + } + + return overloadApplicability; + }; + + PullTypeResolver.prototype.overloadIsApplicableForArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + if (paramType.isAny()) { + return 3 /* Subtype */; + } else if (paramType.isError()) { + return 1 /* AssignableButWithProvisionalErrors */; + } else if (arg.kind() === 219 /* SimpleArrowFunctionExpression */) { + var simpleArrowFunction = arg; + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, null, TypeScript.ASTHelpers.parametersFromIdentifier(simpleArrowFunction.identifier), null, simpleArrowFunction.block, simpleArrowFunction.expression, argIndex, context, comparisonInfo); + } else if (arg.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { + var arrowFunction = arg; + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, arrowFunction.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), TypeScript.ASTHelpers.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, argIndex, context, comparisonInfo); + } else if (arg.kind() === 222 /* FunctionExpression */) { + var functionExpression = arg; + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, functionExpression.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(functionExpression.callSignature.parameterList), TypeScript.ASTHelpers.getType(functionExpression), functionExpression.block, null, argIndex, context, comparisonInfo); + } else if (arg.kind() === 215 /* ObjectLiteralExpression */) { + return this.overloadIsApplicableForObjectLiteralArgument(paramType, arg, argIndex, context, comparisonInfo); + } else if (arg.kind() === 214 /* ArrayLiteralExpression */) { + return this.overloadIsApplicableForArrayLiteralArgument(paramType, arg, argIndex, context, comparisonInfo); + } else { + return this.overloadIsApplicableForOtherArgument(paramType, arg, argIndex, context, comparisonInfo); + } + }; + + PullTypeResolver.prototype.overloadIsApplicableForAnyFunctionExpressionArgument = function (paramType, arg, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, argIndex, context, comparisonInfo) { + if (this.cachedFunctionInterfaceType() && paramType === this.cachedFunctionInterfaceType()) { + return 2 /* AssignableWithNoProvisionalErrors */; + } + + context.pushProvisionalType(paramType); + + var argSym = this.resolveAnyFunctionExpression(arg, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, true, context); + + var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + + context.popAnyContextualType(); + + return applicabilityStatus; + }; + + PullTypeResolver.prototype.overloadIsApplicableForObjectLiteralArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + if (this.cachedObjectInterfaceType() && paramType === this.cachedObjectInterfaceType()) { + return 2 /* AssignableWithNoProvisionalErrors */; + } + + context.pushProvisionalType(paramType); + var argSym = this.resolveObjectLiteralExpression(arg, true, context); + + var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + + context.popAnyContextualType(); + + return applicabilityStatus; + }; + + PullTypeResolver.prototype.overloadIsApplicableForArrayLiteralArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + if (paramType === this.cachedArrayInterfaceType()) { + return 2 /* AssignableWithNoProvisionalErrors */; + } + + context.pushProvisionalType(paramType); + var argSym = this.resolveArrayLiteralExpression(arg, true, context); + + var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + + context.popAnyContextualType(); + + return applicabilityStatus; + }; + + PullTypeResolver.prototype.overloadIsApplicableForOtherArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + var argSym = this.resolveAST(arg, false, context); + + if (argSym.type.isAlias()) { + var aliasSym = argSym.type; + argSym = aliasSym.getExportAssignedTypeSymbol(); + } + + comparisonInfo.stringConstantVal = arg; + return this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + }; + + PullTypeResolver.prototype.overloadIsApplicableForArgumentHelper = function (paramType, argSym, argumentIndex, comparisonInfo, arg, context) { + var tempComparisonInfo = new TypeComparisonInfo(); + tempComparisonInfo.stringConstantVal = comparisonInfo.stringConstantVal; + if (!context.hasProvisionalErrors() && this.sourceIsSubtypeOfTarget(argSym.type, paramType, arg, context, tempComparisonInfo)) { + return 3 /* Subtype */; + } + + if (this.sourceIsAssignableToTarget(argSym.type, paramType, arg, context, comparisonInfo.message ? tempComparisonInfo : comparisonInfo)) { + return context.hasProvisionalErrors() ? 1 /* AssignableButWithProvisionalErrors */ : 2 /* AssignableWithNoProvisionalErrors */; + } + + if (!comparisonInfo.message) { + var enclosingSymbol = this.getEnclosingSymbolForAST(arg); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Could_not_apply_type_0_to_argument_1_which_is_of_type_2, [paramType.toString(enclosingSymbol), (argumentIndex + 1), argSym.getTypeName(enclosingSymbol)])); + } + + return 0 /* NotAssignable */; + }; + + PullTypeResolver.prototype.inferArgumentTypesForSignature = function (argContext, comparisonInfo, context) { + var inferenceResultTypes = argContext.inferTypeArguments(); + var typeParameters = argContext.signatureBeingInferred.getTypeParameters(); + TypeScript.Debug.assert(typeParameters.length == inferenceResultTypes.length); + + var typeReplacementMapForConstraints = null; + for (var i = 0; i < inferenceResultTypes.length; i++) { + if (typeParameters[i].getConstraint()) { + typeReplacementMapForConstraints = typeReplacementMapForConstraints || TypeScript.PullInstantiationHelpers.createTypeParameterArgumentMap(typeParameters, inferenceResultTypes); + var associatedConstraint = this.instantiateType(typeParameters[i].getConstraint(), typeReplacementMapForConstraints); + if (!this.sourceIsAssignableToTargetWithNewEnclosingTypes(inferenceResultTypes[i], associatedConstraint, null, context, null, false)) { + inferenceResultTypes[i] = associatedConstraint; + } + } + } + + if (argContext.isInvocationInferenceContext()) { + var invocationContext = argContext; + if (!this.typeParametersAreInScopeAtArgumentList(typeParameters, invocationContext.argumentASTs)) { + for (var i = 0; i < inferenceResultTypes.length; i++) { + if (inferenceResultTypes[i].wrapsSomeTypeParameter(argContext.candidateCache)) { + inferenceResultTypes[i] = this.semanticInfoChain.anyTypeSymbol; + } + } + } + } + + return inferenceResultTypes; + }; + + PullTypeResolver.prototype.typeParametersAreInScopeAtArgumentList = function (typeParameters, args) { + var enclosingDecl = this.getEnclosingDeclForAST(args); + var typeParameterParentDecl = typeParameters[0].getDeclarations()[0].getParentDecl(); + return enclosingDecl.getParentPath().indexOf(typeParameterParentDecl) > -1; + }; + + PullTypeResolver.prototype.relateTypeToTypeParametersInEnclosingType = function (expressionType, parameterType, argContext, context) { + if (expressionType && parameterType) { + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + this.relateInifinitelyExpandingTypeToTypeParameters(expressionType, parameterType, argContext, context); + return; + } + } + this.relateTypeToTypeParameters(expressionType, parameterType, argContext, context); + }; + + PullTypeResolver.prototype.relateTypeToTypeParametersWithNewEnclosingTypes = function (expressionType, parameterType, argContext, context) { + var enclosingTypeWalkerStates = context.resetEnclosingTypeWalkerStates(); + this.relateTypeToTypeParameters(expressionType, parameterType, argContext, context); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + }; + + PullTypeResolver.prototype.relateTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { + if (!expressionType || !parameterType) { + return; + } + + if (expressionType.isError()) { + expressionType = this.semanticInfoChain.anyTypeSymbol; + } + + if (parameterType.isTypeParameter()) { + var typeParameter = parameterType; + argContext.addCandidateForInference(typeParameter, expressionType); + return; + } + + if (parameterType.isNamedTypeSymbol() && !parameterType.isGeneric() && !parameterType.getTypeArguments()) { + return; + } + + if (TypeScript.PullInstantiationHelpers.twoTypesAreInstantiationsOfSameNamedGenericType(expressionType, parameterType)) { + this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, argContext, context); + } else { + var symbolsWhenStartedWalkingTypes = context.startWalkingTypes(expressionType, parameterType); + this.relateObjectTypeToTypeParameters(expressionType, parameterType, argContext, context); + context.endWalkingTypes(symbolsWhenStartedWalkingTypes); + } + }; + + PullTypeResolver.prototype.relateTypeArgumentsOfTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { + var parameterSideTypeArguments = parameterType.getTypeArguments(); + var argumentSideTypeArguments = expressionType.getTypeArguments(); + + TypeScript.Debug.assert(parameterSideTypeArguments && argumentSideTypeArguments && parameterSideTypeArguments.length === argumentSideTypeArguments.length); + for (var i = 0; i < parameterSideTypeArguments.length; i++) { + this.relateTypeToTypeParametersWithNewEnclosingTypes(argumentSideTypeArguments[i], parameterSideTypeArguments[i], argContext, context); + } + }; + + PullTypeResolver.prototype.relateInifinitelyExpandingTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { + if (!expressionType || !parameterType) { + return; + } + + var expressionTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(expressionType); + var parameterTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(parameterType); + if (expressionTypeNamedTypeReference !== parameterTypeNamedTypeReference) { + return; + } + + var expressionTypeTypeArguments = expressionType.getTypeArguments(); + var parameterTypeArguments = parameterType.getTypeArguments(); + + if (expressionTypeTypeArguments && parameterTypeArguments && expressionTypeTypeArguments.length === parameterTypeArguments.length) { + for (var i = 0; i < expressionTypeTypeArguments.length; i++) { + this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, argContext, context); + } + } + }; + + PullTypeResolver.prototype.relateFunctionSignatureToTypeParameters = function (expressionSignature, parameterSignature, argContext, context) { + var _this = this; + var expressionReturnType = expressionSignature.returnType; + var parameterReturnType = parameterSignature.returnType; + + parameterSignature.forAllCorrespondingParameterTypesInThisAndOtherSignature(expressionSignature, function (parameterSignatureParameterType, expressionSignatureParameterType, i) { + context.walkParameterTypes(i); + _this.relateTypeToTypeParametersInEnclosingType(expressionSignatureParameterType, parameterSignatureParameterType, argContext, context); + context.postWalkParameterTypes(); + return true; + }); + + context.walkReturnTypes(); + this.relateTypeToTypeParametersInEnclosingType(expressionReturnType, parameterReturnType, argContext, context); + context.postWalkReturnTypes(); + }; + + PullTypeResolver.prototype.relateObjectTypeToTypeParameters = function (objectType, parameterType, argContext, context) { + var parameterTypeMembers = parameterType.getMembers(); + var parameterSignatures; + + var objectMember; + var objectSignatures; + + if (argContext.alreadyRelatingTypes(objectType, parameterType)) { + return; + } + + for (var i = 0; i < parameterTypeMembers.length; i++) { + objectMember = this.getNamedPropertySymbol(parameterTypeMembers[i].name, 68147712 /* SomeValue */, objectType); + if (objectMember) { + this.resolveDeclaredSymbol(objectMember); + this.resolveDeclaredSymbol(parameterTypeMembers[i]); + context.walkMemberTypes(parameterTypeMembers[i].name); + this.relateTypeToTypeParametersInEnclosingType(objectMember.type, parameterTypeMembers[i].type, argContext, context); + context.postWalkMemberTypes(); + } + } + + this.relateSignatureGroupToTypeParameters(objectType.getCallSignatures(), parameterType.getCallSignatures(), 1048576 /* CallSignature */, argContext, context); + + this.relateSignatureGroupToTypeParameters(objectType.getConstructSignatures(), parameterType.getConstructSignatures(), 2097152 /* ConstructSignature */, argContext, context); + + var parameterIndexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(parameterType, context); + var objectIndexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(objectType, context); + var indexSigInfo = context.getBothKindOfIndexSignatures(false, false); + + if (parameterIndexSignatures.stringSignature && objectIndexSignatures.stringSignature) { + context.walkIndexSignatureReturnTypes(indexSigInfo, true, true, true); + this.relateFunctionSignatureToTypeParameters(objectIndexSignatures.stringSignature, parameterIndexSignatures.stringSignature, argContext, context); + context.postWalkIndexSignatureReturnTypes(true); + } + if (parameterIndexSignatures.numericSignature && objectIndexSignatures.numericSignature) { + context.walkIndexSignatureReturnTypes(indexSigInfo, false, false, true); + this.relateFunctionSignatureToTypeParameters(objectIndexSignatures.numericSignature, parameterIndexSignatures.numericSignature, argContext, context); + context.postWalkIndexSignatureReturnTypes(true); + } + }; + + PullTypeResolver.prototype.relateSignatureGroupToTypeParameters = function (argumentSignatures, parameterSignatures, signatureKind, argContext, context) { + for (var i = 0; i < parameterSignatures.length; i++) { + var paramSignature = parameterSignatures[i]; + if (argumentSignatures.length > 0 && paramSignature.isGeneric()) { + paramSignature = this.instantiateSignatureToAny(paramSignature); + } + for (var j = 0; j < argumentSignatures.length; j++) { + var argumentSignature = argumentSignatures[j]; + if (argumentSignature.nonOptionalParamCount > paramSignature.nonOptionalParamCount) { + continue; + } + + if (argumentSignature.isGeneric()) { + argumentSignature = this.instantiateSignatureToAny(argumentSignature); + } + + context.walkSignatures(signatureKind, j, i); + this.relateFunctionSignatureToTypeParameters(argumentSignature, paramSignature, argContext, context); + context.postWalkSignatures(); + } + } + }; + + PullTypeResolver.prototype.alterPotentialGenericFunctionTypeToInstantiatedFunctionTypeForTypeArgumentInference = function (expressionSymbol, context) { + var inferentialType = context.getContextualType(); + TypeScript.Debug.assert(inferentialType); + var expressionType = expressionSymbol.type; + if (this.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers(expressionType, true) && this.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers(inferentialType, false)) { + var genericExpressionSignature = expressionType.getCallSignatures()[0]; + var contextualSignature = inferentialType.getCallSignatures()[0]; + + var instantiatedSignature = this.instantiateSignatureInContext(genericExpressionSignature, contextualSignature, context, true); + if (instantiatedSignature === null) { + return expressionSymbol; + } + + var newType = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + newType.appendCallSignature(instantiatedSignature); + return newType; + } + + return expressionSymbol; + }; + + PullTypeResolver.prototype.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers = function (type, callSignatureShouldBeGeneric) { + TypeScript.Debug.assert(type); + if (type.getCallSignatures().length !== 1) { + return false; + } + + var callSignatureIsGeneric = type.getCallSignatures()[0].isGeneric(); + if (callSignatureIsGeneric !== callSignatureShouldBeGeneric) { + return false; + } + + var typeHasOtherMembers = type.getConstructSignatures().length || type.getIndexSignatures().length || type.getAllMembers(68147712 /* SomeValue */, 0 /* all */).length; + if (typeHasOtherMembers) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.instantiateTypeToAny = function (typeToSpecialize, context) { + var typeParameters = typeToSpecialize.getTypeParameters(); + + if (!typeParameters.length) { + return typeToSpecialize; + } + + var typeArguments = null; + + if (!this._cachedAnyTypeArgs) { + this._cachedAnyTypeArgs = [ + [this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol] + ]; + } + + if (typeParameters.length < this._cachedAnyTypeArgs.length) { + typeArguments = this._cachedAnyTypeArgs[typeParameters.length - 1]; + } else { + typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArguments[typeArguments.length] = this.semanticInfoChain.anyTypeSymbol; + } + } + + var type = this.createInstantiatedType(typeToSpecialize, typeArguments); + + return type; + }; + + PullTypeResolver.prototype.instantiateSignatureToAny = function (signature) { + var typeParameters = signature.getTypeParameters(); + if (!this._cachedAnyTypeArgs) { + this._cachedAnyTypeArgs = [ + [this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol] + ]; + } + + if (typeParameters.length < this._cachedAnyTypeArgs.length) { + var typeArguments = this._cachedAnyTypeArgs[typeParameters.length - 1]; + } else { + var typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArguments[typeArguments.length] = this.semanticInfoChain.anyTypeSymbol; + } + } + + var typeParameterArgumentMap = TypeScript.PullInstantiationHelpers.createTypeParameterArgumentMap(typeParameters, typeArguments); + return this.instantiateSignature(signature, typeParameterArgumentMap); + }; + + PullTypeResolver.typeCheck = function (compilationSettings, semanticInfoChain, document) { + var sourceUnit = document.sourceUnit(); + + var resolver = semanticInfoChain.getResolver(); + var context = new TypeScript.PullTypeResolutionContext(resolver, true, sourceUnit.fileName()); + + if (resolver.canTypeCheckAST(sourceUnit, context)) { + resolver.resolveAST(sourceUnit, false, context); + resolver.validateVariableDeclarationGroups(semanticInfoChain.getDeclForAST(sourceUnit), context); + + while (resolver.typeCheckCallBacks.length) { + var callBack = resolver.typeCheckCallBacks.pop(); + callBack(context); + } + + resolver.processPostTypeCheckWorkItems(context); + } + }; + + PullTypeResolver.prototype.validateVariableDeclarationGroups = function (enclosingDecl, context) { + var _this = this; + this.scanVariableDeclarationGroups(enclosingDecl, function (_) { + }, function (subsequentDecl, firstSymbol) { + if (TypeScript.hasFlag(subsequentDecl.kind, 2048 /* Parameter */) || TypeScript.hasFlag(subsequentDecl.flags, 8388608 /* PropertyParameter */)) { + return; + } + + var boundDeclAST = _this.semanticInfoChain.getASTForDecl(subsequentDecl); + + var symbol = subsequentDecl.getSymbol(); + var symbolType = symbol.type; + var firstSymbolType = firstSymbol.type; + + if (symbolType && firstSymbolType && symbolType !== firstSymbolType && !_this.typesAreIdentical(symbolType, firstSymbolType, context)) { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(boundDeclAST, TypeScript.DiagnosticCode.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, [symbol.getScopedName(), firstSymbolType.toString(firstSymbol), symbolType.toString(symbol)])); + } + }); + }; + + PullTypeResolver.prototype.typeCheckFunctionOverloads = function (funcDecl, context, signature, allSignatures) { + if (!signature) { + var functionSignatureInfo = TypeScript.PullHelpers.getSignatureForFuncDecl(this.semanticInfoChain.getDeclForAST(funcDecl)); + signature = functionSignatureInfo.signature; + allSignatures = functionSignatureInfo.allSignatures; + } + var functionDeclaration = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSymbol = functionDeclaration.getSymbol(); + + var definitionSignature = null; + for (var i = allSignatures.length - 1; i >= 0; i--) { + if (allSignatures[i].isDefinition()) { + definitionSignature = allSignatures[i]; + break; + } + } + + if (!signature.isDefinition()) { + var signatureParentDecl = signature.getDeclarations()[0].getParentDecl(); + for (var i = 0; i < allSignatures.length; i++) { + if (allSignatures[i] === signature) { + break; + } + + var allSignaturesParentDecl = allSignatures[i].getDeclarations()[0].getParentDecl(); + if (allSignaturesParentDecl !== signatureParentDecl) { + continue; + } + + if (this.signaturesAreIdenticalWithNewEnclosingTypes(allSignatures[i], signature, context, false)) { + if (!this.signatureReturnTypesAreIdentical(allSignatures[i], signature, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overloads_cannot_differ_only_by_return_type)); + } else if (funcDecl.kind() === 137 /* ConstructorDeclaration */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_constructor_overload_signature)); + } else if (functionDeclaration.kind === 2097152 /* ConstructSignature */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_overload_construct_signature)); + } else if (functionDeclaration.kind === 1048576 /* CallSignature */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_overload_call_signature)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_overload_signature_for_0, [funcSymbol.getScopedNameEx().toString()])); + } + + break; + } + } + } + + var isConstantOverloadSignature = signature.isStringConstantOverloadSignature(); + if (isConstantOverloadSignature) { + if (signature.isDefinition()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overload_signature_implementation_cannot_use_specialized_type)); + } else { + var foundSubtypeSignature = false; + for (var i = 0; i < allSignatures.length; i++) { + if (allSignatures[i].isDefinition() || allSignatures[i] === signature) { + continue; + } + + if (!allSignatures[i].isResolved) { + this.resolveDeclaredSymbol(allSignatures[i], context); + } + + if (allSignatures[i].isStringConstantOverloadSignature()) { + continue; + } + + if (this.signatureIsAssignableToTarget(signature, allSignatures[i], null, context)) { + foundSubtypeSignature = true; + break; + } + } + + if (!foundSubtypeSignature) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature)); + } + } + } else if (definitionSignature && definitionSignature !== signature) { + var comparisonInfo = new TypeComparisonInfo(); + + if (!definitionSignature.isResolved) { + this.resolveDeclaredSymbol(definitionSignature, context); + } + + if (!this.signatureIsAssignableToTarget(definitionSignature, signature, funcDecl, context, comparisonInfo)) { + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overload_signature_is_not_compatible_with_function_definition_NL_0, [comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overload_signature_is_not_compatible_with_function_definition)); + } + } + } + + var signatureForVisibilityCheck = definitionSignature; + if (!definitionSignature) { + if (allSignatures[0] === signature) { + return; + } + signatureForVisibilityCheck = allSignatures[0]; + } + + if (funcDecl.kind() !== 137 /* ConstructorDeclaration */ && functionDeclaration.kind !== 2097152 /* ConstructSignature */ && signatureForVisibilityCheck && signature !== signatureForVisibilityCheck) { + var errorCode; + + if (signatureForVisibilityCheck.anyDeclHasFlag(2 /* Private */) !== signature.anyDeclHasFlag(2 /* Private */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_public_or_private; + } else if (signatureForVisibilityCheck.anyDeclHasFlag(1 /* Exported */) !== signature.anyDeclHasFlag(1 /* Exported */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_exported_or_not_exported; + } else if (signatureForVisibilityCheck.anyDeclHasFlag(8 /* Ambient */) !== signature.anyDeclHasFlag(8 /* Ambient */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_ambient_or_non_ambient; + } else if (signatureForVisibilityCheck.anyDeclHasFlag(128 /* Optional */) !== signature.anyDeclHasFlag(128 /* Optional */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_optional_or_required; + } + + if (errorCode) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, errorCode)); + } + } + }; + + PullTypeResolver.prototype.checkSymbolPrivacy = function (declSymbol, symbol, privacyErrorReporter) { + if (!symbol || symbol.kind === 2 /* Primitive */) { + return; + } + + if (symbol.isType()) { + var typeSymbol = symbol; + var isNamedType = typeSymbol.isNamedTypeSymbol(); + + if (typeSymbol.isArrayNamedTypeReference()) { + this.checkSymbolPrivacy(declSymbol, typeSymbol.getElementType(), privacyErrorReporter); + return; + } + + if (!isNamedType) { + var typeOfSymbol = typeSymbol.getTypeOfSymbol(); + if (typeOfSymbol) { + this.checkSymbolPrivacy(declSymbol, typeOfSymbol, privacyErrorReporter); + return; + } + } + + if (typeSymbol.inSymbolPrivacyCheck) { + return; + } + + typeSymbol.inSymbolPrivacyCheck = true; + + var typars = typeSymbol.getTypeArgumentsOrTypeParameters(); + if (typars) { + for (var i = 0; i < typars.length; i++) { + this.checkSymbolPrivacy(declSymbol, typars[i], privacyErrorReporter); + } + } + + if (!isNamedType) { + var members = typeSymbol.getMembers(); + for (var i = 0; i < members.length; i++) { + this.checkSymbolPrivacy(declSymbol, members[i].type, privacyErrorReporter); + } + + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getCallSignatures(), privacyErrorReporter); + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getConstructSignatures(), privacyErrorReporter); + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getIndexSignatures(), privacyErrorReporter); + } else if (typeSymbol.kind === 8192 /* TypeParameter */) { + this.checkSymbolPrivacy(declSymbol, typeSymbol.getConstraint(), privacyErrorReporter); + } + + typeSymbol.inSymbolPrivacyCheck = false; + + if (!isNamedType) { + return; + } + } + + if (declSymbol.isExternallyVisible()) { + var symbolIsVisible = symbol.isExternallyVisible(); + + if (symbolIsVisible && symbol.kind !== 8192 /* TypeParameter */) { + var symbolPath = symbol.pathToRoot(); + var declSymbolPath = declSymbol.pathToRoot(); + + if (symbolPath[symbolPath.length - 1].kind === 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1].kind === 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1] !== symbolPath[symbolPath.length - 1]) { + symbolIsVisible = false; + var declSymbolScope = declSymbolPath[declSymbolPath.length - 1]; + for (var i = symbolPath.length - 1; i >= 0; i--) { + var aliasSymbols = symbolPath[i].getExternalAliasedSymbols(declSymbolScope); + if (aliasSymbols) { + symbolIsVisible = true; + aliasSymbols[0].setTypeUsedExternally(); + break; + } + } + symbol = symbolPath[symbolPath.length - 1]; + } + } else if (symbol.kind === 128 /* TypeAlias */) { + var aliasSymbol = symbol; + symbolIsVisible = true; + aliasSymbol.setTypeUsedExternally(); + } + + if (!symbolIsVisible) { + privacyErrorReporter(symbol); + } + } + }; + + PullTypeResolver.prototype.checkTypePrivacyOfSignatures = function (declSymbol, signatures, privacyErrorReporter) { + for (var i = 0; i < signatures.length; i++) { + var signature = signatures[i]; + if (signatures.length > 1 && signature.isDefinition()) { + continue; + } + + var typeParams = signature.getTypeParameters(); + for (var j = 0; j < typeParams.length; j++) { + this.checkSymbolPrivacy(declSymbol, typeParams[j], privacyErrorReporter); + } + + var params = signature.parameters; + for (var j = 0; j < params.length; j++) { + var paramType = params[j].type; + this.checkSymbolPrivacy(declSymbol, paramType, privacyErrorReporter); + } + + var returnType = signature.returnType; + this.checkSymbolPrivacy(declSymbol, returnType, privacyErrorReporter); + } + }; + + PullTypeResolver.prototype.typeParameterOfTypeDeclarationPrivacyErrorReporter = function (classOrInterface, typeParameterAST, typeParameter, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + var messageCode; + + var typeParameters = classOrInterface.kind() === 131 /* ClassDeclaration */ ? classOrInterface.typeParameterList : classOrInterface.typeParameterList; + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_interface_is_using_inaccessible_module_1; + } + } else { + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_interface_has_or_is_using_private_type_1; + } + } + + var messageArguments = [typeParameter.getScopedName(enclosingSymbol, false, true), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeParameterAST, messageCode, messageArguments)); + }; + + PullTypeResolver.prototype.baseListPrivacyErrorReporter = function (classOrInterface, declSymbol, baseAst, isExtendedType, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + var messageCode; + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + if (isExtendedType) { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_extends_class_from_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_implements_interface_from_inaccessible_module_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_interface_0_extends_interface_from_inaccessible_module_1; + } + } else { + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + if (isExtendedType) { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_extends_private_class_1; + } else { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_implements_private_interface_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_interface_0_extends_private_interface_1; + } + } + + var messageArguments = [declSymbol.getScopedName(enclosingSymbol), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseAst, messageCode, messageArguments)); + }; + + PullTypeResolver.prototype.variablePrivacyErrorReporter = function (declAST, declSymbol, symbol, context) { + var typeSymbol = symbol; + var enclosingDecl = this.getEnclosingDecl(declSymbol.getDeclarations()[0]); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + + var isProperty = declSymbol.kind === 4096 /* Property */; + var isPropertyOfClass = false; + var declParent = declSymbol.getContainer(); + if (declParent && (declParent.kind === 8 /* Class */ || declParent.kind === 32768 /* ConstructorMethod */)) { + isPropertyOfClass = true; + } + + var messageCode; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (declSymbol.anyDeclHasFlag(16 /* Static */)) { + messageCode = TypeScript.DiagnosticCode.Public_static_property_0_of_exported_class_is_using_inaccessible_module_1; + } else if (isProperty) { + if (isPropertyOfClass) { + messageCode = TypeScript.DiagnosticCode.Public_property_0_of_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Property_0_of_exported_interface_is_using_inaccessible_module_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_variable_0_is_using_inaccessible_module_1; + } + } else { + if (declSymbol.anyDeclHasFlag(16 /* Static */)) { + messageCode = TypeScript.DiagnosticCode.Public_static_property_0_of_exported_class_has_or_is_using_private_type_1; + } else if (isProperty) { + if (isPropertyOfClass) { + messageCode = TypeScript.DiagnosticCode.Public_property_0_of_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.Property_0_of_exported_interface_has_or_is_using_private_type_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_variable_0_has_or_is_using_private_type_1; + } + } + + var messageArguments = [declSymbol.getScopedName(enclosingSymbol), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(declAST, messageCode, messageArguments)); + }; + + PullTypeResolver.prototype.checkFunctionTypePrivacy = function (funcDeclAST, isStatic, typeParameters, parameters, returnTypeAnnotation, block, context) { + var _this = this; + if (funcDeclAST.kind() === 222 /* FunctionExpression */ || funcDeclAST.kind() === 241 /* FunctionPropertyAssignment */ || (funcDeclAST.kind() === 139 /* GetAccessor */ && funcDeclAST.parent.parent.kind() === 215 /* ObjectLiteralExpression */) || (funcDeclAST.kind() === 140 /* SetAccessor */ && funcDeclAST.parent.parent.kind() === 215 /* ObjectLiteralExpression */)) { + return; + } + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var functionSymbol = functionDecl.getSymbol(); + ; + var functionSignature; + + var isGetter = funcDeclAST.kind() === 139 /* GetAccessor */; + var isSetter = funcDeclAST.kind() === 140 /* SetAccessor */; + var isIndexSignature = functionDecl.kind === 4194304 /* IndexSignature */; + + if (isGetter || isSetter) { + var accessorSymbol = functionSymbol; + functionSignature = (isGetter ? accessorSymbol.getGetter() : accessorSymbol.getSetter()).type.getCallSignatures()[0]; + } else { + if (!functionSymbol) { + var parentDecl = functionDecl.getParentDecl(); + functionSymbol = parentDecl.getSymbol(); + if (functionSymbol && functionSymbol.isType() && !functionSymbol.isNamedTypeSymbol()) { + return; + } + } else if (functionSymbol.kind === 65536 /* Method */ && !isStatic && !functionSymbol.getContainer().isNamedTypeSymbol()) { + return; + } + functionSignature = functionDecl.getSignatureSymbol(); + } + + if (typeParameters && !isGetter && !isSetter && !isIndexSignature && funcDeclAST.kind() !== 137 /* ConstructorDeclaration */) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + var typeParameterAST = typeParameters.typeParameters.nonSeparatorAt(i); + var typeParameter = this.resolveTypeParameterDeclaration(typeParameterAST, context); + this.checkSymbolPrivacy(functionSymbol, typeParameter, function (symbol) { + return _this.functionTypeArgumentArgumentTypePrivacyErrorReporter(funcDeclAST, isStatic, typeParameterAST, typeParameter, symbol, context); + }); + } + } + + if (!isGetter && !isIndexSignature) { + var funcParams = functionSignature.parameters; + for (var i = 0; i < funcParams.length; i++) { + this.checkSymbolPrivacy(functionSymbol, funcParams[i].type, function (symbol) { + return _this.functionArgumentTypePrivacyErrorReporter(funcDeclAST, isStatic, parameters, i, funcParams[i], symbol, context); + }); + } + } + + if (!isSetter) { + this.checkSymbolPrivacy(functionSymbol, functionSignature.returnType, function (symbol) { + return _this.functionReturnTypePrivacyErrorReporter(funcDeclAST, isStatic, returnTypeAnnotation, block, functionSignature.returnType, symbol, context); + }); + } + }; + + PullTypeResolver.prototype.functionTypeArgumentArgumentTypePrivacyErrorReporter = function (declAST, isStatic, typeParameterAST, typeParameter, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(declAST); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + + var isMethod = decl.kind === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.kind === 8 /* Class */ || isStatic)) { + isMethodOfClass = true; + } + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + var messageCode; + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_function_is_using_inaccessible_module_1; + } + } else { + if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_function_has_or_is_using_private_type_1; + } + } + + if (messageCode) { + var messageArgs = [typeParameter.getScopedName(enclosingSymbol, false, true), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeParameterAST, messageCode, messageArgs)); + } + }; + + PullTypeResolver.prototype.functionArgumentTypePrivacyErrorReporter = function (declAST, isStatic, parameters, argIndex, paramSymbol, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(declAST); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + + var isGetter = declAST.kind() === 139 /* GetAccessor */; + var isSetter = declAST.kind() === 140 /* SetAccessor */; + var isMethod = decl.kind === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.kind === 8 /* Class */ || isStatic)) { + isMethodOfClass = true; + } + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + var messageCode; + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (declAST.kind() === 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_from_exported_class_is_using_inaccessible_module_1; + } else if (isSetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_property_setter_from_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_property_setter_from_exported_class_is_using_inaccessible_module_1; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1; + } + } else if (!isGetter) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_exported_function_is_using_inaccessible_module_1; + } + } else { + if (declAST.kind() === 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_type_1; + } else if (isSetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_type_1; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1; + } + } else if (!isGetter && decl.kind !== 4194304 /* IndexSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_exported_function_has_or_is_using_private_type_1; + } + } + + if (messageCode) { + var parameter = parameters.astAt(argIndex); + + var messageArgs = [paramSymbol.getScopedName(enclosingSymbol), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(parameter, messageCode, messageArgs)); + } + }; + + PullTypeResolver.prototype.functionReturnTypePrivacyErrorReporter = function (declAST, isStatic, returnTypeAnnotation, block, funcReturnType, symbol, context) { + var _this = this; + var decl = this.semanticInfoChain.getDeclForAST(declAST); + var enclosingDecl = this.getEnclosingDecl(decl); + + var isGetter = declAST.kind() === 139 /* GetAccessor */; + var isSetter = declAST.kind() === 140 /* SetAccessor */; + var isMethod = decl.kind === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.kind === 8 /* Class */ || isStatic)) { + isMethodOfClass = true; + } + + var messageCode = null; + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (isGetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module_0; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_0; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module_0; + } else if (decl.kind === 4194304 /* IndexSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module_0; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module_0; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_method_from_exported_class_is_using_inaccessible_module_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_method_from_exported_interface_is_using_inaccessible_module_0; + } + } else if (!isSetter && declAST.kind() !== 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_exported_function_is_using_inaccessible_module_0; + } + } else { + if (isGetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type_0; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_0; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type_0; + } else if (decl.kind === 4194304 /* IndexSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type_0; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type_0; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_method_from_exported_class_has_or_is_using_private_type_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_method_from_exported_interface_has_or_is_using_private_type_0; + } + } else if (!isSetter && declAST.kind() !== 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_exported_function_has_or_is_using_private_type_0; + } + } + + if (messageCode) { + var messageArguments = [typeSymbolName]; + var reportOnFuncDecl = false; + + if (returnTypeAnnotation) { + var returnExpressionSymbol = this.resolveTypeReference(returnTypeAnnotation, context); + + if (TypeScript.PullHelpers.typeSymbolsAreIdentical(returnExpressionSymbol, funcReturnType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, messageCode, messageArguments)); + } + } + + if (block) { + var reportErrorOnReturnExpressions = function (ast, walker) { + var go = true; + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + go = false; + break; + + case 150 /* ReturnStatement */: + var returnStatement = ast; + var returnExpressionSymbol = _this.resolveAST(returnStatement.expression, false, context).type; + + if (TypeScript.PullHelpers.typeSymbolsAreIdentical(returnExpressionSymbol, funcReturnType)) { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(returnStatement, messageCode, messageArguments)); + } else { + reportOnFuncDecl = true; + } + go = false; + break; + + default: + break; + } + + walker.options.goChildren = go; + return ast; + }; + + TypeScript.getAstWalkerFactory().walk(block, reportErrorOnReturnExpressions); + } + + if (reportOnFuncDecl) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(declAST, messageCode, messageArguments)); + } + } + }; + + PullTypeResolver.prototype.enclosingClassIsDerived = function (classDecl) { + TypeScript.Debug.assert(classDecl.kind === 8 /* Class */); + + var classSymbol = classDecl.getSymbol(); + return classSymbol.getExtendedTypes().length > 0; + }; + + PullTypeResolver.prototype.isSuperInvocationExpression = function (ast) { + if (ast.kind() === 213 /* InvocationExpression */) { + var invocationExpression = ast; + if (invocationExpression.expression.kind() === 50 /* SuperKeyword */) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.isSuperInvocationExpressionStatement = function (node) { + if (node && node.kind() === 149 /* ExpressionStatement */) { + var expressionStatement = node; + if (this.isSuperInvocationExpression(expressionStatement.expression)) { + return true; + } + } + return false; + }; + + PullTypeResolver.prototype.getFirstStatementOfBlockOrNull = function (block) { + if (block && block.statements && block.statements.childCount() > 0) { + return block.statements.childAt(0); + } + + return null; + }; + + PullTypeResolver.prototype.superCallMustBeFirstStatementInConstructor = function (constructorDecl) { + TypeScript.Debug.assert(constructorDecl.kind === 32768 /* ConstructorMethod */); + + if (constructorDecl) { + var enclosingClass = constructorDecl.getParentDecl(); + + var classSymbol = enclosingClass.getSymbol(); + if (classSymbol.getExtendedTypes().length === 0) { + return false; + } + + var classMembers = classSymbol.getMembers(); + for (var i = 0, n1 = classMembers.length; i < n1; i++) { + var member = classMembers[i]; + + if (member.kind === 4096 /* Property */) { + var declarations = member.getDeclarations(); + for (var j = 0, n2 = declarations.length; j < n2; j++) { + var declaration = declarations[j]; + var ast = this.semanticInfoChain.getASTForDecl(declaration); + if (ast.kind() === 242 /* Parameter */) { + return true; + } + + if (ast.kind() === 136 /* MemberVariableDeclaration */) { + var variableDeclarator = ast; + if (variableDeclarator.variableDeclarator.equalsValueClause) { + return true; + } + } + } + } + } + } + + return false; + }; + + PullTypeResolver.prototype.checkForThisCaptureInArrowFunction = function (expression) { + var enclosingDecl = this.getEnclosingDeclForAST(expression); + + var declPath = enclosingDecl.getParentPath(); + + if (declPath.length) { + var inArrowFunction = false; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.kind; + var declFlags = decl.flags; + + if (declKind === 131072 /* FunctionExpression */ && TypeScript.hasFlag(declFlags, 8192 /* ArrowFunction */)) { + inArrowFunction = true; + continue; + } + + if (inArrowFunction) { + if (declKind === 16384 /* Function */ || declKind === 65536 /* Method */ || declKind === 32768 /* ConstructorMethod */ || declKind === 262144 /* GetAccessor */ || declKind === 524288 /* SetAccessor */ || declKind === 131072 /* FunctionExpression */ || declKind === 8 /* Class */ || declKind === 4 /* Container */ || declKind === 32 /* DynamicModule */ || declKind === 1 /* Script */) { + decl.setFlags(decl.flags | 262144 /* MustCaptureThis */); + + if (declKind === 8 /* Class */) { + var constructorSymbol = decl.getSymbol().getConstructorMethod(); + var constructorDecls = constructorSymbol.getDeclarations(); + for (var i = 0; i < constructorDecls.length; i++) { + constructorDecls[i].flags = constructorDecls[i].flags | 262144 /* MustCaptureThis */; + } + } + break; + } + } else if (declKind === 16384 /* Function */ || declKind === 131072 /* FunctionExpression */) { + break; + } + } + } + }; + + PullTypeResolver.prototype.typeCheckMembersAgainstIndexer = function (containerType, containerTypeDecl, context) { + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(containerType, context); + var stringSignature = indexSignatures.stringSignature; + var numberSignature = indexSignatures.numericSignature; + + if (stringSignature || numberSignature) { + var members = containerTypeDecl.getChildDecls(); + for (var i = 0; i < members.length; i++) { + var member = members[i]; + if ((member.name || (member.kind === 4096 /* Property */ && member.name === "")) && member.kind !== 32768 /* ConstructorMethod */ && !TypeScript.hasFlag(member.flags, 16 /* Static */)) { + var memberSymbol = member.getSymbol(); + var relevantSignature = this.determineRelevantIndexerForMember(memberSymbol, numberSignature, stringSignature); + if (relevantSignature) { + var comparisonInfo = new TypeComparisonInfo(); + if (!this.sourceIsAssignableToTarget(memberSymbol.type, relevantSignature.returnType, member.ast(), context, comparisonInfo)) { + this.reportErrorThatMemberIsNotSubtypeOfIndexer(memberSymbol, relevantSignature, member.ast(), context, comparisonInfo); + } + } + } + } + } + }; + + PullTypeResolver.prototype.determineRelevantIndexerForMember = function (member, numberIndexSignature, stringIndexSignature) { + if (numberIndexSignature && TypeScript.PullHelpers.isNameNumeric(member.name)) { + return numberIndexSignature; + } else if (stringIndexSignature) { + return stringIndexSignature; + } + + return null; + }; + + PullTypeResolver.prototype.reportErrorThatMemberIsNotSubtypeOfIndexer = function (member, indexSignature, astForError, context, comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(astForError); + if (indexSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol) { + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); + } + } else { + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_assignable_to_string_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_assignable_to_string_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); + } + } + }; + + PullTypeResolver.prototype.typeCheckIfTypeMemberPropertyOkToOverride = function (typeSymbol, extendedType, typeMember, extendedTypeMember, enclosingDecl, comparisonInfo) { + if (!typeSymbol.isClass()) { + return true; + } + + var typeMemberKind = typeMember.kind; + var extendedMemberKind = extendedTypeMember.kind; + + if (typeMemberKind === extendedMemberKind) { + return true; + } + + var errorCode; + if (typeMemberKind === 4096 /* Property */) { + if (typeMember.isAccessor()) { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } else { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + } else if (typeMemberKind === 65536 /* Method */) { + if (extendedTypeMember.isAccessor()) { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } else { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + + var message = TypeScript.getDiagnosticMessage(errorCode, [typeSymbol.toString(), typeMember.getScopedNameEx().toString(), extendedType.toString()]); + comparisonInfo.addMessage(message); + return false; + }; + + PullTypeResolver.prototype.typeCheckIfTypeExtendsType = function (classOrInterface, name, typeSymbol, extendedType, enclosingDecl, context) { + var typeMembers = typeSymbol.getMembers(); + + var comparisonInfo = new TypeComparisonInfo(); + var foundError = false; + var foundError1 = false; + var foundError2 = false; + + for (var i = 0; i < typeMembers.length; i++) { + var propName = typeMembers[i].name; + var extendedTypeProp = extendedType.findMember(propName, true); + if (extendedTypeProp) { + this.resolveDeclaredSymbol(extendedTypeProp, context); + foundError1 = !this.typeCheckIfTypeMemberPropertyOkToOverride(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, enclosingDecl, comparisonInfo); + + if (!foundError1) { + foundError2 = !this.sourcePropertyIsAssignableToTargetProperty(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, classOrInterface, context, comparisonInfo); + } + + if (foundError1 || foundError2) { + foundError = true; + break; + } + } + } + + if (!foundError && typeSymbol.hasOwnCallSignatures()) { + foundError = !this.sourceCallSignaturesAreAssignableToTargetCallSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + } + + if (!foundError && typeSymbol.hasOwnConstructSignatures()) { + foundError = !this.sourceConstructSignaturesAreAssignableToTargetConstructSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + } + + if (!foundError && typeSymbol.hasOwnIndexSignatures()) { + foundError = !this.sourceIndexSignaturesAreAssignableToTargetIndexSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + } + + if (!foundError && typeSymbol.isClass()) { + var typeConstructorType = typeSymbol.getConstructorMethod().type; + var typeConstructorTypeMembers = typeConstructorType.getMembers(); + if (typeConstructorTypeMembers.length) { + var extendedConstructorType = extendedType.getConstructorMethod().type; + var comparisonInfoForPropTypeCheck = new TypeComparisonInfo(comparisonInfo); + + for (var i = 0; i < typeConstructorTypeMembers.length; i++) { + var propName = typeConstructorTypeMembers[i].name; + var extendedConstructorTypeProp = extendedConstructorType.findMember(propName, true); + if (extendedConstructorTypeProp) { + if (!extendedConstructorTypeProp.isResolved) { + this.resolveDeclaredSymbol(extendedConstructorTypeProp, context); + } + + if (!this.sourcePropertyIsAssignableToTargetProperty(typeConstructorType, extendedConstructorType, typeConstructorTypeMembers[i], extendedConstructorTypeProp, classOrInterface, context, comparisonInfo)) { + foundError = true; + break; + } + } + } + } + } + + if (foundError) { + var errorCode; + if (typeSymbol.isClass()) { + errorCode = TypeScript.DiagnosticCode.Class_0_cannot_extend_class_1_NL_2; + } else { + if (extendedType.isClass()) { + errorCode = TypeScript.DiagnosticCode.Interface_0_cannot_extend_class_1_NL_2; + } else { + errorCode = TypeScript.DiagnosticCode.Interface_0_cannot_extend_interface_1_NL_2; + } + } + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, errorCode, [typeSymbol.getScopedName(), extendedType.getScopedName(), comparisonInfo.message])); + } + }; + + PullTypeResolver.prototype.typeCheckIfClassImplementsType = function (classDecl, classSymbol, implementedType, enclosingDecl, context) { + var comparisonInfo = new TypeComparisonInfo(); + var foundError = !this.sourceMembersAreAssignableToTargetMembers(classSymbol, implementedType, classDecl, context, comparisonInfo); + if (!foundError) { + foundError = !this.sourceCallSignaturesAreAssignableToTargetCallSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + if (!foundError) { + foundError = !this.sourceConstructSignaturesAreAssignableToTargetConstructSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + if (!foundError) { + foundError = !this.sourceIndexSignaturesAreAssignableToTargetIndexSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + } + } + } + + if (foundError) { + var enclosingSymbol = this.getEnclosingSymbolForAST(classDecl); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(classDecl.identifier, TypeScript.DiagnosticCode.Class_0_declares_interface_1_but_does_not_implement_it_NL_2, [classSymbol.getScopedName(enclosingSymbol), implementedType.getScopedName(enclosingSymbol), comparisonInfo.message])); + } + }; + + PullTypeResolver.prototype.computeValueSymbolFromAST = function (valueDeclAST, context) { + var prevInTypeCheck = context.inTypeCheck; + context.inTypeCheck = false; + + var typeSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(valueDeclAST); + + if (valueDeclAST.kind() == 11 /* IdentifierName */) { + var valueSymbol = this.computeNameExpression(valueDeclAST, context); + } else { + TypeScript.Debug.assert(valueDeclAST.kind() == 121 /* QualifiedName */); + var qualifiedName = valueDeclAST; + + var lhs = this.computeValueSymbolFromAST(qualifiedName.left, context); + var valueSymbol = this.computeDottedNameExpressionFromLHS(lhs.symbol, qualifiedName.left, qualifiedName.right, context, false); + } + var valueSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(valueDeclAST); + + this.semanticInfoChain.setAliasSymbolForAST(valueDeclAST, typeSymbolAlias); + context.inTypeCheck = prevInTypeCheck; + + return { symbol: valueSymbol, alias: valueSymbolAlias }; + }; + + PullTypeResolver.prototype.hasClassTypeSymbolConflictAsValue = function (baseDeclAST, typeSymbol, enclosingDecl, context) { + var typeSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(baseDeclAST); + + var valueDeclAST = baseDeclAST.kind() == 126 /* GenericType */ ? baseDeclAST.name : baseDeclAST; + var valueSymbolInfo = this.computeValueSymbolFromAST(valueDeclAST, context); + var valueSymbol = valueSymbolInfo.symbol; + var valueSymbolAlias = valueSymbolInfo.alias; + + if (typeSymbolAlias && valueSymbolAlias) { + return typeSymbolAlias !== valueSymbolAlias; + } + + if (!valueSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */)) { + return true; + } + + var associatedContainerType = valueSymbol.type ? valueSymbol.type.getAssociatedContainerType() : null; + + if (associatedContainerType) { + return associatedContainerType !== typeSymbol.getRootSymbol(); + } + + return true; + }; + + PullTypeResolver.prototype.typeCheckBase = function (classOrInterface, name, typeSymbol, baseDeclAST, isExtendedType, enclosingDecl, context) { + var _this = this; + var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); + + var baseType = this.resolveTypeReference(baseDeclAST, context).type; + + if (!baseType) { + return; + } + + var typeDeclIsClass = typeSymbol.isClass(); + + if (!typeSymbol.isValidBaseKind(baseType, isExtendedType)) { + if (!baseType.isError()) { + if (isExtendedType) { + if (typeDeclIsClass) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.A_class_may_only_extend_another_class)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.An_interface_may_only_extend_another_class_or_interface)); + } + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.A_class_may_only_implement_another_class_or_interface)); + } + } + return; + } else if (typeDeclIsClass && isExtendedType) { + if (this.hasClassTypeSymbolConflictAsValue(baseDeclAST, baseType, enclosingDecl, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_1, [TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(baseDeclAST.kind() == 126 /* GenericType */ ? baseDeclAST.name : baseDeclAST), baseType.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + } + } + + if (baseType.hasBase(typeSymbol)) { + typeSymbol.setHasBaseTypeConflict(); + baseType.setHasBaseTypeConflict(); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, typeDeclIsClass ? TypeScript.DiagnosticCode.Class_0_is_recursively_referenced_as_a_base_type_of_itself : TypeScript.DiagnosticCode.Interface_0_is_recursively_referenced_as_a_base_type_of_itself, [typeSymbol.getScopedName()])); + return; + } + + if (isExtendedType) { + this.typeCheckCallBacks.push(function (context) { + return _this.typeCheckIfTypeExtendsType(classOrInterface, name, typeSymbol, baseType, enclosingDecl, context); + }); + } else { + TypeScript.Debug.assert(classOrInterface.kind() === 131 /* ClassDeclaration */); + + this.typeCheckCallBacks.push(function (context) { + return _this.typeCheckIfClassImplementsType(classOrInterface, typeSymbol, baseType, enclosingDecl, context); + }); + } + + this.checkSymbolPrivacy(typeSymbol, baseType, function (errorSymbol) { + return _this.baseListPrivacyErrorReporter(classOrInterface, typeSymbol, baseDeclAST, isExtendedType, errorSymbol, context); + }); + }; + + PullTypeResolver.prototype.typeCheckBases = function (classOrInterface, name, heritageClauses, typeSymbol, enclosingDecl, context) { + var _this = this; + var extendsClause = TypeScript.ASTHelpers.getExtendsHeritageClause(heritageClauses); + var implementsClause = TypeScript.ASTHelpers.getImplementsHeritageClause(heritageClauses); + if (!extendsClause && !implementsClause) { + return; + } + + if (extendsClause) { + for (var i = 0; i < extendsClause.typeNames.nonSeparatorCount(); i++) { + this.typeCheckBase(classOrInterface, name, typeSymbol, extendsClause.typeNames.nonSeparatorAt(i), true, enclosingDecl, context); + } + } + + if (typeSymbol.isClass()) { + if (implementsClause) { + for (var i = 0; i < implementsClause.typeNames.nonSeparatorCount(); i++) { + this.typeCheckBase(classOrInterface, name, typeSymbol, implementsClause.typeNames.nonSeparatorAt(i), false, enclosingDecl, context); + } + } + } else if (extendsClause && !typeSymbol.hasBaseTypeConflict() && typeSymbol.getExtendedTypes().length > 1) { + var firstInterfaceASTWithExtendsClause = TypeScript.ArrayUtilities.firstOrDefault(typeSymbol.getDeclarations(), function (decl) { + return decl.ast().heritageClauses !== null; + }).ast(); + if (classOrInterface === firstInterfaceASTWithExtendsClause) { + this.typeCheckCallBacks.push(function (context) { + _this.checkTypeCompatibilityBetweenBases(classOrInterface.identifier, typeSymbol, context); + }); + } + } + }; + + PullTypeResolver.prototype.checkTypeCompatibilityBetweenBases = function (name, typeSymbol, context) { + var derivedIndexSignatures = typeSymbol.getOwnIndexSignatures(); + + var inheritedMembersMap = TypeScript.createIntrinsicsObject(); + var inheritedIndexSignatures = new InheritedIndexSignatureInfo(); + + var typeHasOwnNumberIndexer = false; + var typeHasOwnStringIndexer = false; + + if (typeSymbol.hasOwnIndexSignatures()) { + var ownIndexSignatures = typeSymbol.getOwnIndexSignatures(); + for (var i = 0; i < ownIndexSignatures.length; i++) { + if (ownIndexSignatures[i].parameters[0].type === this.semanticInfoChain.numberTypeSymbol) { + typeHasOwnNumberIndexer = true; + } else { + typeHasOwnStringIndexer = true; + } + } + } + var baseTypes = typeSymbol.getExtendedTypes(); + for (var i = 0; i < baseTypes.length; i++) { + if (this.checkNamedPropertyIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedMembersMap, context) || this.checkIndexSignatureIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedIndexSignatures, typeHasOwnNumberIndexer, typeHasOwnStringIndexer, context)) { + return; + } + } + + if (this.checkThatInheritedNumberSignatureIsSubtypeOfInheritedStringSignature(name, typeSymbol, inheritedIndexSignatures, context)) { + return; + } + + this.checkInheritedMembersAgainstInheritedIndexSignatures(name, typeSymbol, inheritedIndexSignatures, inheritedMembersMap, context); + }; + + PullTypeResolver.prototype.checkNamedPropertyIdentityBetweenBases = function (interfaceName, interfaceSymbol, baseTypeSymbol, inheritedMembersMap, context) { + var baseMembers = baseTypeSymbol.getAllMembers(4096 /* Property */ | 65536 /* Method */, 0 /* all */); + for (var i = 0; i < baseMembers.length; i++) { + var member = baseMembers[i]; + var memberName = member.name; + + if (interfaceSymbol.findMember(memberName, false)) { + continue; + } + + this.resolveDeclaredSymbol(member, context); + + if (inheritedMembersMap[memberName]) { + var prevMember = inheritedMembersMap[memberName]; + if (prevMember.baseOrigin !== baseTypeSymbol && !this.propertiesAreIdenticalWithNewEnclosingTypes(baseTypeSymbol, prevMember.baseOrigin, member, prevMember.memberSymbol, context)) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Named_properties_0_of_types_1_and_2_are_not_identical, [memberName, prevMember.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), prevMember.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); + return true; + } + } else { + inheritedMembersMap[memberName] = new MemberWithBaseOrigin(member, baseTypeSymbol); + } + } + + return false; + }; + + PullTypeResolver.prototype.checkIndexSignatureIdentityBetweenBases = function (interfaceName, interfaceSymbol, baseTypeSymbol, allInheritedSignatures, derivedTypeHasOwnNumberSignature, derivedTypeHasOwnStringSignature, context) { + if (derivedTypeHasOwnNumberSignature && derivedTypeHasOwnStringSignature) { + return false; + } + + var indexSignaturesFromThisBaseType = baseTypeSymbol.getIndexSignatures(); + for (var i = 0; i < indexSignaturesFromThisBaseType.length; i++) { + var currentInheritedSignature = indexSignaturesFromThisBaseType[i]; + + var parameterTypeIsString = currentInheritedSignature.parameters[0].type === this.semanticInfoChain.stringTypeSymbol; + var parameterTypeIsNumber = currentInheritedSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol; + + if (parameterTypeIsString && derivedTypeHasOwnStringSignature || parameterTypeIsNumber && derivedTypeHasOwnNumberSignature) { + continue; + } + + if (parameterTypeIsString) { + if (allInheritedSignatures.stringSignatureWithBaseOrigin) { + if (allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.stringSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType, context)) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_string_indexer_of_types_0_and_1_are_not_identical, [allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); + return true; + } + } else { + allInheritedSignatures.stringSignatureWithBaseOrigin = new SignatureWithBaseOrigin(currentInheritedSignature, baseTypeSymbol); + } + } else if (parameterTypeIsNumber) { + if (allInheritedSignatures.numberSignatureWithBaseOrigin) { + if (allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.numberSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType, context)) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_number_indexer_of_types_0_and_1_are_not_identical, [allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); + return true; + } + } else { + allInheritedSignatures.numberSignatureWithBaseOrigin = new SignatureWithBaseOrigin(currentInheritedSignature, baseTypeSymbol); + } + } + } + + return false; + }; + + PullTypeResolver.prototype.checkInheritedMembersAgainstInheritedIndexSignatures = function (interfaceName, interfaceSymbol, inheritedIndexSignatures, inheritedMembers, context) { + if (!inheritedIndexSignatures.stringSignatureWithBaseOrigin && !inheritedIndexSignatures.numberSignatureWithBaseOrigin) { + return false; + } + + var comparisonInfo = new TypeComparisonInfo(); + var stringSignature = inheritedIndexSignatures.stringSignatureWithBaseOrigin && inheritedIndexSignatures.stringSignatureWithBaseOrigin.signature; + var numberSignature = inheritedIndexSignatures.numberSignatureWithBaseOrigin && inheritedIndexSignatures.numberSignatureWithBaseOrigin.signature; + for (var memberName in inheritedMembers) { + var memberWithBaseOrigin = inheritedMembers[memberName]; + if (!memberWithBaseOrigin) { + continue; + } + + var relevantSignature = this.determineRelevantIndexerForMember(memberWithBaseOrigin.memberSymbol, numberSignature, stringSignature); + if (!relevantSignature) { + continue; + } + + var relevantSignatureIsNumberSignature = relevantSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol; + var signatureBaseOrigin = relevantSignatureIsNumberSignature ? inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin : inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin; + + if (signatureBaseOrigin === memberWithBaseOrigin.baseOrigin) { + continue; + } + + var memberIsSubtype = this.sourceIsAssignableToTarget(memberWithBaseOrigin.memberSymbol.type, relevantSignature.returnType, interfaceName, context, comparisonInfo); + + if (!memberIsSubtype) { + var enclosingSymbol = this.getEnclosingSymbolForAST(interfaceName); + if (relevantSignatureIsNumberSignature) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_assignable_to_number_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(enclosingSymbol), memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); + } else { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_assignable_to_string_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(enclosingSymbol), memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); + } + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.checkThatInheritedNumberSignatureIsSubtypeOfInheritedStringSignature = function (interfaceName, interfaceSymbol, inheritedIndexSignatures, context) { + if (inheritedIndexSignatures.numberSignatureWithBaseOrigin && inheritedIndexSignatures.stringSignatureWithBaseOrigin) { + if (inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin === inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin) { + return false; + } + + var comparisonInfo = new TypeComparisonInfo(); + var signatureIsSubtype = this.sourceIsAssignableToTarget(inheritedIndexSignatures.numberSignatureWithBaseOrigin.signature.returnType, inheritedIndexSignatures.stringSignatureWithBaseOrigin.signature.returnType, interfaceName, context, comparisonInfo); + + if (!signatureIsSubtype) { + var enclosingSymbol = this.getEnclosingSymbolForAST(interfaceName); + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_number_indexer_in_type_0_is_not_assignable_to_string_indexer_type_in_type_1_NL_2, [ + inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), + inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [ + interfaceSymbol.getDisplayName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), + inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.checkAssignability = function (ast, source, target, context) { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(source, target, ast, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)])); + } + } + }; + + PullTypeResolver.prototype.isReference = function (ast, astSymbol) { + if (ast.kind() === 217 /* ParenthesizedExpression */) { + return this.isReference(ast.expression, astSymbol); + } + + if (ast.kind() !== 11 /* IdentifierName */ && ast.kind() !== 212 /* MemberAccessExpression */ && ast.kind() !== 221 /* ElementAccessExpression */) { + return false; + } + + if (ast.kind() === 11 /* IdentifierName */) { + if (astSymbol.kind === 512 /* Variable */ && astSymbol.anyDeclHasFlag(4096 /* Enum */)) { + return false; + } + + if (astSymbol.kind === 512 /* Variable */ && astSymbol.anyDeclHasFlag(102400 /* SomeInitializedModule */)) { + return false; + } + + if (astSymbol.kind === 32768 /* ConstructorMethod */ || astSymbol.kind === 16384 /* Function */) { + return false; + } + } + + if (ast.kind() === 212 /* MemberAccessExpression */ && astSymbol.kind === 67108864 /* EnumMember */) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.checkForSuperMemberAccess = function (expression, name, resolvedName, context) { + if (resolvedName) { + if (expression.kind() === 50 /* SuperKeyword */ && !resolvedName.isError() && resolvedName.kind !== 65536 /* Method */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword)); + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.getEnclosingDeclForAST = function (ast) { + return this.semanticInfoChain.getEnclosingDecl(ast); + }; + + PullTypeResolver.prototype.getEnclosingSymbolForAST = function (ast) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + return enclosingDecl ? enclosingDecl.getSymbol() : null; + }; + + PullTypeResolver.prototype.checkForPrivateMemberAccess = function (name, expressionType, resolvedName, context) { + if (resolvedName) { + if (resolvedName.anyDeclHasFlag(2 /* Private */)) { + var memberContainer = resolvedName.getContainer(); + if (memberContainer && memberContainer.kind === 33554432 /* ConstructorType */) { + memberContainer = memberContainer.getAssociatedContainerType(); + } + + if (memberContainer && memberContainer.isClass()) { + var memberClass = memberContainer.getDeclarations()[0].ast(); + TypeScript.Debug.assert(memberClass); + + var containingClass = this.getEnclosingClassDeclaration(name); + + if (!containingClass || containingClass !== memberClass) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode._0_1_is_inaccessible, [memberContainer.toString(null, false), name.text()])); + return true; + } + } + } + } + + return false; + }; + + PullTypeResolver.prototype.instantiateType = function (type, typeParameterArgumentMap) { + if (type.isPrimitive()) { + return type; + } + + if (type.isError()) { + return type; + } + + if (typeParameterArgumentMap[type.pullSymbolID]) { + return typeParameterArgumentMap[type.pullSymbolID]; + } + + type._resolveDeclaredSymbol(); + if (type.isTypeParameter()) { + return this.instantiateTypeParameter(type, typeParameterArgumentMap); + } + + if (type.wrapsSomeTypeParameter(typeParameterArgumentMap)) { + return TypeScript.PullInstantiatedTypeReferenceSymbol.create(this, type, typeParameterArgumentMap); + } + + return type; + }; + + PullTypeResolver.prototype.instantiateTypeParameter = function (typeParameter, typeParameterArgumentMap) { + var constraint = typeParameter.getConstraint(); + if (!constraint) { + return typeParameter; + } + + var instantiatedConstraint = this.instantiateType(constraint, typeParameterArgumentMap); + + if (instantiatedConstraint == constraint) { + return typeParameter; + } + + var rootTypeParameter = typeParameter.getRootSymbol(); + var instantiation = rootTypeParameter.getSpecialization([instantiatedConstraint]); + if (instantiation) { + return instantiation; + } + + instantiation = new TypeScript.PullInstantiatedTypeParameterSymbol(rootTypeParameter, instantiatedConstraint); + return instantiation; + }; + + PullTypeResolver.prototype.instantiateSignature = function (signature, typeParameterArgumentMap) { + if (!signature.wrapsSomeTypeParameter(typeParameterArgumentMap)) { + return signature; + } + + var rootSignature = signature.getRootSymbol(); + var mutableTypeParameterMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(typeParameterArgumentMap); + TypeScript.PullInstantiationHelpers.instantiateTypeArgument(this, signature, mutableTypeParameterMap); + + var instantiatedSignature = rootSignature.getSpecialization(mutableTypeParameterMap.typeParameterArgumentMap); + if (instantiatedSignature) { + return instantiatedSignature; + } + + TypeScript.PullInstantiationHelpers.cleanUpTypeArgumentMap(signature, mutableTypeParameterMap); + typeParameterArgumentMap = mutableTypeParameterMap.typeParameterArgumentMap; + + instantiatedSignature = new TypeScript.PullInstantiatedSignatureSymbol(rootSignature, typeParameterArgumentMap); + + instantiatedSignature.returnType = this.instantiateType((rootSignature.returnType || this.semanticInfoChain.anyTypeSymbol), typeParameterArgumentMap); + instantiatedSignature.functionType = this.instantiateType(rootSignature.functionType, typeParameterArgumentMap); + + var parameters = rootSignature.parameters; + var parameter = null; + + if (parameters) { + for (var j = 0; j < parameters.length; j++) { + parameter = new TypeScript.PullSymbol(parameters[j].name, 2048 /* Parameter */); + parameter.setRootSymbol(parameters[j]); + + if (parameters[j].isOptional) { + parameter.isOptional = true; + } + if (parameters[j].isVarArg) { + parameter.isVarArg = true; + instantiatedSignature.hasVarArgs = true; + } + instantiatedSignature.addParameter(parameter, parameter.isOptional); + + parameter.type = this.instantiateType(parameters[j].type, typeParameterArgumentMap); + } + } + + return instantiatedSignature; + }; + PullTypeResolver.globalTypeCheckPhase = 0; + return PullTypeResolver; + })(); + TypeScript.PullTypeResolver = PullTypeResolver; + + var TypeComparisonInfo = (function () { + function TypeComparisonInfo(sourceComparisonInfo, useSameIndent) { + this.onlyCaptureFirstError = false; + this.flags = 0 /* SuccessfulComparison */; + this.message = ""; + this.stringConstantVal = null; + this.indent = 1; + if (sourceComparisonInfo) { + this.flags = sourceComparisonInfo.flags; + this.onlyCaptureFirstError = sourceComparisonInfo.onlyCaptureFirstError; + this.stringConstantVal = sourceComparisonInfo.stringConstantVal; + this.indent = sourceComparisonInfo.indent; + if (!useSameIndent) { + this.indent++; + } + } + } + TypeComparisonInfo.prototype.indentString = function () { + var result = ""; + + for (var i = 0; i < this.indent; i++) { + result += "\t"; + } + + return result; + }; + + TypeComparisonInfo.prototype.addMessage = function (message) { + if (!this.onlyCaptureFirstError && this.message) { + this.message = this.message + TypeScript.newLine() + this.indentString() + message; + } else { + this.message = this.indentString() + message; + } + }; + return TypeComparisonInfo; + })(); + TypeScript.TypeComparisonInfo = TypeComparisonInfo; + + function getPropertyAssignmentNameTextFromIdentifier(identifier) { + if (identifier.kind() === 11 /* IdentifierName */) { + return { actualText: identifier.text(), memberName: identifier.valueText() }; + } else if (identifier.kind() === 14 /* StringLiteral */) { + return { actualText: identifier.text(), memberName: identifier.valueText() }; + } else if (identifier.kind() === 13 /* NumericLiteral */) { + return { actualText: identifier.text(), memberName: identifier.valueText() }; + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + TypeScript.getPropertyAssignmentNameTextFromIdentifier = getPropertyAssignmentNameTextFromIdentifier; + + function isTypesOnlyLocation(ast) { + while (ast && ast.parent) { + switch (ast.parent.kind()) { + case 244 /* TypeAnnotation */: + return true; + case 127 /* TypeQuery */: + return false; + case 125 /* ConstructorType */: + var constructorType = ast.parent; + if (constructorType.type === ast) { + return true; + } + break; + case 123 /* FunctionType */: + var functionType = ast.parent; + if (functionType.type === ast) { + return true; + } + break; + case 239 /* Constraint */: + var constraint = ast.parent; + if (constraint.type === ast) { + return true; + } + break; + case 220 /* CastExpression */: + var castExpression = ast.parent; + return castExpression.type === ast; + case 230 /* ExtendsHeritageClause */: + case 231 /* ImplementsHeritageClause */: + return true; + case 228 /* TypeArgumentList */: + return true; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + case 129 /* FunctionDeclaration */: + case 145 /* MethodSignature */: + case 212 /* MemberAccessExpression */: + case 242 /* Parameter */: + return false; + } + + ast = ast.parent; + } + + return false; + } + TypeScript.isTypesOnlyLocation = isTypesOnlyLocation; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.declCacheHit = 0; + TypeScript.declCacheMiss = 0; + TypeScript.symbolCacheHit = 0; + TypeScript.symbolCacheMiss = 0; + + var sentinalEmptyArray = []; + + var SemanticInfoChain = (function () { + function SemanticInfoChain(compiler, logger) { + this.compiler = compiler; + this.logger = logger; + this.documents = []; + this.fileNameToDocument = TypeScript.createIntrinsicsObject(); + this.anyTypeDecl = null; + this.booleanTypeDecl = null; + this.numberTypeDecl = null; + this.stringTypeDecl = null; + this.nullTypeDecl = null; + this.undefinedTypeDecl = null; + this.voidTypeDecl = null; + this.undefinedValueDecl = null; + this.anyTypeSymbol = null; + this.booleanTypeSymbol = null; + this.numberTypeSymbol = null; + this.stringTypeSymbol = null; + this.nullTypeSymbol = null; + this.undefinedTypeSymbol = null; + this.voidTypeSymbol = null; + this.undefinedValueSymbol = null; + this.emptyTypeSymbol = null; + this.astSymbolMap = []; + this.astAliasSymbolMap = []; + this.astCallResolutionDataMap = []; + this.declSymbolMap = []; + this.declSignatureSymbolMap = []; + this.declCache = null; + this.symbolCache = null; + this.fileNameToDiagnostics = null; + this._binder = null; + this._resolver = null; + this._topLevelDecls = null; + this._fileNames = null; + var globalDecl = new TypeScript.RootPullDecl("", "", 0 /* Global */, 0 /* None */, this, false); + this.documents[0] = new TypeScript.Document(this.compiler, this, "", [], null, 0 /* None */, 0, false, null, globalDecl); + + this.anyTypeDecl = new TypeScript.NormalPullDecl("any", "any", 2 /* Primitive */, 0 /* None */, globalDecl); + this.booleanTypeDecl = new TypeScript.NormalPullDecl("boolean", "boolean", 2 /* Primitive */, 0 /* None */, globalDecl); + this.numberTypeDecl = new TypeScript.NormalPullDecl("number", "number", 2 /* Primitive */, 0 /* None */, globalDecl); + this.stringTypeDecl = new TypeScript.NormalPullDecl("string", "string", 2 /* Primitive */, 0 /* None */, globalDecl); + this.voidTypeDecl = new TypeScript.NormalPullDecl("void", "void", 2 /* Primitive */, 0 /* None */, globalDecl); + + this.nullTypeDecl = new TypeScript.RootPullDecl("null", "", 2 /* Primitive */, 0 /* None */, this, false); + this.undefinedTypeDecl = new TypeScript.RootPullDecl("undefined", "", 2 /* Primitive */, 0 /* None */, this, false); + this.undefinedValueDecl = new TypeScript.NormalPullDecl("undefined", "undefined", 512 /* Variable */, 8 /* Ambient */, globalDecl); + + this.invalidate(); + } + SemanticInfoChain.prototype.getDocument = function (fileName) { + var document = this.fileNameToDocument[fileName]; + return document || null; + }; + + SemanticInfoChain.prototype.lineMap = function (fileName) { + return this.getDocument(fileName).lineMap(); + }; + + SemanticInfoChain.prototype.fileNames = function () { + if (this._fileNames === null) { + this._fileNames = this.documents.slice(1).map(function (s) { + return s.fileName; + }); + } + + return this._fileNames; + }; + + SemanticInfoChain.prototype.bindPrimitiveSymbol = function (decl, newSymbol) { + newSymbol.addDeclaration(decl); + decl.setSymbol(newSymbol); + newSymbol.setResolved(); + + return newSymbol; + }; + + SemanticInfoChain.prototype.addPrimitiveTypeSymbol = function (decl) { + var newSymbol = new TypeScript.PullPrimitiveTypeSymbol(decl.name); + return this.bindPrimitiveSymbol(decl, newSymbol); + }; + + SemanticInfoChain.prototype.addPrimitiveValueSymbol = function (decl, type) { + var newSymbol = new TypeScript.PullSymbol(decl.name, 512 /* Variable */); + newSymbol.type = type; + return this.bindPrimitiveSymbol(decl, newSymbol); + }; + + SemanticInfoChain.prototype.resetGlobalSymbols = function () { + this.anyTypeSymbol = this.addPrimitiveTypeSymbol(this.anyTypeDecl); + this.booleanTypeSymbol = this.addPrimitiveTypeSymbol(this.booleanTypeDecl); + this.numberTypeSymbol = this.addPrimitiveTypeSymbol(this.numberTypeDecl); + this.stringTypeSymbol = this.addPrimitiveTypeSymbol(this.stringTypeDecl); + this.voidTypeSymbol = this.addPrimitiveTypeSymbol(this.voidTypeDecl); + this.nullTypeSymbol = this.addPrimitiveTypeSymbol(this.nullTypeDecl); + this.undefinedTypeSymbol = this.addPrimitiveTypeSymbol(this.undefinedTypeDecl); + this.undefinedValueSymbol = this.addPrimitiveValueSymbol(this.undefinedValueDecl, this.undefinedTypeSymbol); + + var emptyTypeDecl = new TypeScript.PullSynthesizedDecl("{}", "{}", 8388608 /* ObjectType */, 0 /* None */, null, this); + var emptyTypeSymbol = new TypeScript.PullTypeSymbol("{}", 8388608 /* ObjectType */); + emptyTypeDecl.setSymbol(emptyTypeSymbol); + emptyTypeSymbol.addDeclaration(emptyTypeDecl); + emptyTypeSymbol.setResolved(); + this.emptyTypeSymbol = emptyTypeSymbol; + }; + + SemanticInfoChain.prototype.addDocument = function (document) { + var fileName = document.fileName; + + var existingIndex = TypeScript.ArrayUtilities.indexOf(this.documents, function (u) { + return u.fileName === fileName; + }); + if (existingIndex < 0) { + this.documents.push(document); + } else { + this.documents[existingIndex] = document; + } + + this.fileNameToDocument[fileName] = document; + + this.invalidate(); + }; + + SemanticInfoChain.prototype.removeDocument = function (fileName) { + TypeScript.Debug.assert(fileName !== "", "Can't remove the semantic info for the global decl."); + var index = TypeScript.ArrayUtilities.indexOf(this.documents, function (u) { + return u.fileName === fileName; + }); + if (index > 0) { + this.fileNameToDocument[fileName] = undefined; + this.documents.splice(index, 1); + this.invalidate(); + } + }; + + SemanticInfoChain.prototype.getDeclPathCacheID = function (declPath, declKind) { + var cacheID = ""; + + for (var i = 0; i < declPath.length; i++) { + cacheID += "#" + declPath[i]; + } + + return cacheID + "#" + declKind.toString(); + }; + + SemanticInfoChain.prototype.findTopLevelSymbol = function (name, kind, doNotGoPastThisDecl) { + var cacheID = this.getDeclPathCacheID([name], kind); + + var symbol = this.symbolCache[cacheID]; + + if (!symbol) { + for (var i = 0, n = this.documents.length; i < n; i++) { + var topLevelDecl = this.documents[i].topLevelDecl(); + + var symbol = this.findTopLevelSymbolInDecl(topLevelDecl, name, kind, doNotGoPastThisDecl); + if (symbol) { + break; + } + + if (doNotGoPastThisDecl && topLevelDecl.name === doNotGoPastThisDecl.fileName()) { + return null; + } + } + + if (symbol) { + this.symbolCache[cacheID] = symbol; + } + } + + return symbol; + }; + + SemanticInfoChain.prototype.findTopLevelSymbolInDecl = function (topLevelDecl, name, kind, doNotGoPastThisDecl) { + var doNotGoPastThisPosition = doNotGoPastThisDecl && doNotGoPastThisDecl.fileName() === topLevelDecl.fileName() ? doNotGoPastThisDecl.ast().start() : -1; + + var foundDecls = topLevelDecl.searchChildDecls(name, kind); + + for (var j = 0; j < foundDecls.length; j++) { + var foundDecl = foundDecls[j]; + + if (doNotGoPastThisPosition !== -1 && foundDecl.ast() && foundDecl.ast().start() > doNotGoPastThisPosition) { + break; + } + + var symbol = foundDecls[j].getSymbol(); + if (symbol) { + return symbol; + } + } + + return null; + }; + + SemanticInfoChain.prototype.findExternalModule = function (id) { + id = TypeScript.normalizePath(id); + + var tsFile = id + ".ts"; + var tsCacheID = this.getDeclPathCacheID([tsFile], 32 /* DynamicModule */); + symbol = this.symbolCache[tsCacheID]; + if (symbol != undefined) { + return symbol; + } + + var dtsFile = id + ".d.ts"; + var dtsCacheID = this.getDeclPathCacheID([dtsFile], 32 /* DynamicModule */); + var symbol = this.symbolCache[dtsCacheID]; + if (symbol) { + return symbol; + } + + var dtsSymbol; + for (var i = 0; i < this.documents.length; i++) { + var document = this.documents[i]; + var topLevelDecl = document.topLevelDecl(); + + if (topLevelDecl.isExternalModule()) { + var isTsFile = document.fileName === tsFile; + if (isTsFile || document.fileName === dtsFile) { + var dynamicModuleDecl = topLevelDecl.getChildDecls()[0]; + symbol = dynamicModuleDecl.getSymbol(); + + if (isTsFile) { + this.symbolCache[tsCacheID] = symbol; + + return symbol; + } else { + dtsSymbol = symbol; + } + } + } + } + + if (dtsSymbol) { + this.symbolCache[dtsCacheID] = symbol; + return dtsSymbol; + } + + this.symbolCache[dtsCacheID] = null; + this.symbolCache[tsCacheID] = null; + + return null; + }; + + SemanticInfoChain.prototype.findAmbientExternalModuleInGlobalContext = function (id) { + var cacheID = this.getDeclPathCacheID([id], 32 /* DynamicModule */); + + var symbol = this.symbolCache[cacheID]; + if (symbol == undefined) { + symbol = null; + for (var i = 0; i < this.documents.length; i++) { + var document = this.documents[i]; + var topLevelDecl = document.topLevelDecl(); + + if (!topLevelDecl.isExternalModule()) { + var dynamicModules = topLevelDecl.searchChildDecls(id, 32 /* DynamicModule */); + if (dynamicModules.length) { + symbol = dynamicModules[0].getSymbol(); + break; + } + } + } + + this.symbolCache[cacheID] = symbol; + } + + return symbol; + }; + + SemanticInfoChain.prototype.findDecls = function (declPath, declKind) { + var cacheID = this.getDeclPathCacheID(declPath, declKind); + + if (declPath.length) { + var cachedDecls = this.declCache[cacheID]; + + if (cachedDecls && cachedDecls.length) { + TypeScript.declCacheHit++; + return cachedDecls; + } + } + + TypeScript.declCacheMiss++; + + var declsToSearch = this.topLevelDecls(); + + var decls = TypeScript.sentinelEmptyArray; + var path; + var foundDecls = TypeScript.sentinelEmptyArray; + + for (var i = 0; i < declPath.length; i++) { + path = declPath[i]; + decls = TypeScript.sentinelEmptyArray; + + var kind = (i === declPath.length - 1) ? declKind : 164 /* SomeContainer */; + for (var j = 0; j < declsToSearch.length; j++) { + foundDecls = declsToSearch[j].searchChildDecls(path, kind); + + for (var k = 0; k < foundDecls.length; k++) { + if (decls === TypeScript.sentinelEmptyArray) { + decls = []; + } + decls[decls.length] = foundDecls[k]; + } + } + + declsToSearch = decls; + + if (!declsToSearch) { + break; + } + } + + if (decls.length) { + this.declCache[cacheID] = decls; + } + + return decls; + }; + + SemanticInfoChain.prototype.findDeclsFromPath = function (declPath, declKind) { + var declString = []; + + for (var i = 0, n = declPath.length; i < n; i++) { + if (declPath[i].kind & 1 /* Script */) { + continue; + } + + declString.push(declPath[i].name); + } + + return this.findDecls(declString, declKind); + }; + + SemanticInfoChain.prototype.findSymbol = function (declPath, declType) { + var cacheID = this.getDeclPathCacheID(declPath, declType); + + if (declPath.length) { + var cachedSymbol = this.symbolCache[cacheID]; + + if (cachedSymbol) { + TypeScript.symbolCacheHit++; + return cachedSymbol; + } + } + + TypeScript.symbolCacheMiss++; + + var decls = this.findDecls(declPath, declType); + var symbol = null; + + if (decls.length) { + var decl = decls[0]; + if (TypeScript.hasFlag(decl.kind, 164 /* SomeContainer */)) { + var valueDecl = decl.getValueDecl(); + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + } + symbol = decl.getSymbol(); + + if (symbol) { + for (var i = 1; i < decls.length; i++) { + decls[i].ensureSymbolIsBound(); + } + + this.symbolCache[cacheID] = symbol; + } + } + + return symbol; + }; + + SemanticInfoChain.prototype.cacheGlobalSymbol = function (symbol, kind) { + var cacheID1 = this.getDeclPathCacheID([symbol.name], kind); + var cacheID2 = this.getDeclPathCacheID([symbol.name], symbol.kind); + + if (!this.symbolCache[cacheID1]) { + this.symbolCache[cacheID1] = symbol; + } + + if (!this.symbolCache[cacheID2]) { + this.symbolCache[cacheID2] = symbol; + } + }; + + SemanticInfoChain.prototype.invalidate = function (oldSettings, newSettings) { + if (typeof oldSettings === "undefined") { oldSettings = null; } + if (typeof newSettings === "undefined") { newSettings = null; } + TypeScript.PullTypeResolver.globalTypeCheckPhase++; + + var cleanStart = new Date().getTime(); + + this.astSymbolMap.length = 0; + this.astAliasSymbolMap.length = 0; + this.astCallResolutionDataMap.length = 0; + + this.declCache = TypeScript.createIntrinsicsObject(); + this.symbolCache = TypeScript.createIntrinsicsObject(); + this.fileNameToDiagnostics = TypeScript.createIntrinsicsObject(); + this._binder = null; + this._resolver = null; + this._topLevelDecls = null; + this._fileNames = null; + + this.declSymbolMap.length = 0; + this.declSignatureSymbolMap.length = 0; + + if (oldSettings && newSettings) { + if (this.settingsChangeAffectsSyntax(oldSettings, newSettings)) { + for (var i = 1, n = this.documents.length; i < n; i++) { + this.documents[i].invalidate(); + } + } + } + + TypeScript.pullSymbolID = 0; + + this.resetGlobalSymbols(); + + var cleanEnd = new Date().getTime(); + }; + + SemanticInfoChain.prototype.settingsChangeAffectsSyntax = function (before, after) { + return before.allowAutomaticSemicolonInsertion() !== after.allowAutomaticSemicolonInsertion() || before.codeGenTarget() !== after.codeGenTarget() || before.propagateEnumConstants() !== after.propagateEnumConstants(); + }; + + SemanticInfoChain.prototype.setSymbolForAST = function (ast, symbol) { + this.astSymbolMap[ast.syntaxID()] = symbol; + }; + + SemanticInfoChain.prototype.getSymbolForAST = function (ast) { + return this.astSymbolMap[ast.syntaxID()] || null; + }; + + SemanticInfoChain.prototype.setAliasSymbolForAST = function (ast, symbol) { + this.astAliasSymbolMap[ast.syntaxID()] = symbol; + }; + + SemanticInfoChain.prototype.getAliasSymbolForAST = function (ast) { + return this.astAliasSymbolMap[ast.syntaxID()]; + }; + + SemanticInfoChain.prototype.getCallResolutionDataForAST = function (ast) { + return this.astCallResolutionDataMap[ast.syntaxID()]; + }; + + SemanticInfoChain.prototype.setCallResolutionDataForAST = function (ast, callResolutionData) { + if (callResolutionData) { + this.astCallResolutionDataMap[ast.syntaxID()] = callResolutionData; + } + }; + + SemanticInfoChain.prototype.setSymbolForDecl = function (decl, symbol) { + this.declSymbolMap[decl.declID] = symbol; + }; + + SemanticInfoChain.prototype.getSymbolForDecl = function (decl) { + return this.declSymbolMap[decl.declID]; + }; + + SemanticInfoChain.prototype.setSignatureSymbolForDecl = function (decl, signatureSymbol) { + this.declSignatureSymbolMap[decl.declID] = signatureSymbol; + }; + + SemanticInfoChain.prototype.getSignatureSymbolForDecl = function (decl) { + return this.declSignatureSymbolMap[decl.declID]; + }; + + SemanticInfoChain.prototype.addDiagnostic = function (diagnostic) { + var fileName = diagnostic.fileName(); + var diagnostics = this.fileNameToDiagnostics[fileName]; + if (!diagnostics) { + diagnostics = []; + this.fileNameToDiagnostics[fileName] = diagnostics; + } + + diagnostics.push(diagnostic); + }; + + SemanticInfoChain.prototype.getDiagnostics = function (fileName) { + var diagnostics = this.fileNameToDiagnostics[fileName]; + return diagnostics || []; + }; + + SemanticInfoChain.prototype.getBinder = function () { + if (!this._binder) { + this._binder = new TypeScript.PullSymbolBinder(this); + } + + return this._binder; + }; + + SemanticInfoChain.prototype.getResolver = function () { + if (!this._resolver) { + this._resolver = new TypeScript.PullTypeResolver(this.compiler.compilationSettings(), this); + } + + return this._resolver; + }; + + SemanticInfoChain.prototype.addSyntheticIndexSignature = function (containingDecl, containingSymbol, ast, indexParamName, indexParamType, returnType) { + var indexSignature = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + var indexParameterSymbol = new TypeScript.PullSymbol(indexParamName, 2048 /* Parameter */); + indexParameterSymbol.type = indexParamType; + indexSignature.addParameter(indexParameterSymbol); + indexSignature.returnType = returnType; + indexSignature.setResolved(); + indexParameterSymbol.setResolved(); + + containingSymbol.addIndexSignature(indexSignature); + + var indexSigDecl = new TypeScript.PullSynthesizedDecl("", "", 4194304 /* IndexSignature */, 2048 /* Signature */, containingDecl, containingDecl.semanticInfoChain); + var indexParamDecl = new TypeScript.PullSynthesizedDecl(indexParamName, indexParamName, 2048 /* Parameter */, 0 /* None */, indexSigDecl, containingDecl.semanticInfoChain); + indexSigDecl.setSignatureSymbol(indexSignature); + indexParamDecl.setSymbol(indexParameterSymbol); + indexSignature.addDeclaration(indexSigDecl); + indexParameterSymbol.addDeclaration(indexParamDecl); + }; + + SemanticInfoChain.prototype.getDeclForAST = function (ast) { + var document = this.getDocument(ast.fileName()); + + if (document) { + return document._getDeclForAST(ast); + } + + return null; + }; + + SemanticInfoChain.prototype.getEnclosingDecl = function (ast) { + return this.getDocument(ast.fileName()).getEnclosingDecl(ast); + }; + + SemanticInfoChain.prototype.setDeclForAST = function (ast, decl) { + this.getDocument(decl.fileName())._setDeclForAST(ast, decl); + }; + + SemanticInfoChain.prototype.getASTForDecl = function (decl) { + var document = this.getDocument(decl.fileName()); + if (document) { + return document._getASTForDecl(decl); + } + + return null; + }; + + SemanticInfoChain.prototype.setASTForDecl = function (decl, ast) { + this.getDocument(decl.fileName())._setASTForDecl(decl, ast); + }; + + SemanticInfoChain.prototype.topLevelDecl = function (fileName) { + var document = this.getDocument(fileName); + if (document) { + return document.topLevelDecl(); + } + + return null; + }; + + SemanticInfoChain.prototype.topLevelDecls = function () { + if (!this._topLevelDecls) { + this._topLevelDecls = TypeScript.ArrayUtilities.select(this.documents, function (u) { + return u.topLevelDecl(); + }); + } + + return this._topLevelDecls; + }; + + SemanticInfoChain.prototype.addDiagnosticFromAST = function (ast, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + this.addDiagnostic(this.diagnosticFromAST(ast, diagnosticKey, _arguments, additionalLocations)); + }; + + SemanticInfoChain.prototype.diagnosticFromAST = function (ast, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + return new TypeScript.Diagnostic(ast.fileName(), this.lineMap(ast.fileName()), ast.start(), ast.width(), diagnosticKey, _arguments, additionalLocations); + }; + + SemanticInfoChain.prototype.locationFromAST = function (ast) { + return new TypeScript.Location(ast.fileName(), this.lineMap(ast.fileName()), ast.start(), ast.width()); + }; + + SemanticInfoChain.prototype.duplicateIdentifierDiagnosticFromAST = function (ast, identifier, additionalLocationAST) { + return this.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_0, [identifier], additionalLocationAST ? [this.locationFromAST(additionalLocationAST)] : null); + }; + + SemanticInfoChain.prototype.addDuplicateIdentifierDiagnosticFromAST = function (ast, identifier, additionalLocationAST) { + this.addDiagnostic(this.duplicateIdentifierDiagnosticFromAST(ast, identifier, additionalLocationAST)); + }; + return SemanticInfoChain; + })(); + TypeScript.SemanticInfoChain = SemanticInfoChain; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DeclCollectionContext = (function () { + function DeclCollectionContext(document, semanticInfoChain, propagateEnumConstants) { + this.document = document; + this.semanticInfoChain = semanticInfoChain; + this.propagateEnumConstants = propagateEnumConstants; + this.isDeclareFile = false; + this.parentChain = []; + } + DeclCollectionContext.prototype.getParent = function () { + return this.parentChain ? this.parentChain[this.parentChain.length - 1] : null; + }; + + DeclCollectionContext.prototype.pushParent = function (parentDecl) { + if (parentDecl) { + this.parentChain[this.parentChain.length] = parentDecl; + } + }; + + DeclCollectionContext.prototype.popParent = function () { + this.parentChain.length--; + }; + return DeclCollectionContext; + })(); + + function moduleElementsHasExportAssignment(moduleElements) { + return moduleElements.any(function (m) { + return m.kind() === 134 /* ExportAssignment */; + }); + } + + function containingModuleHasExportAssignment(ast) { + ast = ast.parent; + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + var moduleDecl = ast; + return moduleElementsHasExportAssignment(moduleDecl.moduleElements); + } else if (ast.kind() === 120 /* SourceUnit */) { + var sourceUnit = ast; + return moduleElementsHasExportAssignment(sourceUnit.moduleElements); + } + + ast = ast.parent; + } + + return false; + } + + function isParsingAmbientModule(ast, context) { + ast = ast.parent; + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + if (TypeScript.hasModifier(ast.modifiers, 8 /* Ambient */)) { + return true; + } + } + + ast = ast.parent; + } + + return false; + } + + function preCollectImportDecls(ast, context) { + var importDecl = ast; + var declFlags = 0 /* None */; + + var parent = context.getParent(); + + if (TypeScript.hasModifier(importDecl.modifiers, 1 /* Exported */) && !containingModuleHasExportAssignment(ast)) { + declFlags |= 1 /* Exported */; + } + + var decl = new TypeScript.NormalPullDecl(importDecl.identifier.valueText(), importDecl.identifier.text(), 128 /* TypeAlias */, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + } + + function preCollectScriptDecls(sourceUnit, context) { + var fileName = sourceUnit.fileName(); + + var isExternalModule = context.document.isExternalModule(); + + var decl = new TypeScript.RootPullDecl(fileName, fileName, 1 /* Script */, 0 /* None */, context.semanticInfoChain, isExternalModule); + context.semanticInfoChain.setDeclForAST(sourceUnit, decl); + context.semanticInfoChain.setASTForDecl(decl, sourceUnit); + + context.isDeclareFile = context.document.isDeclareFile(); + + context.pushParent(decl); + + if (isExternalModule) { + var declFlags = 1 /* Exported */; + if (TypeScript.isDTSFile(fileName)) { + declFlags |= 8 /* Ambient */; + } + + var moduleContainsExecutableCode = containsExecutableCode(sourceUnit.moduleElements); + var kind = 32 /* DynamicModule */; + var valueText = TypeScript.quoteStr(fileName); + + var decl = new TypeScript.NormalPullDecl(valueText, fileName, kind, declFlags, context.getParent()); + + context.semanticInfoChain.setASTForDecl(decl, sourceUnit); + + context.semanticInfoChain.setDeclForAST(sourceUnit, decl); + + if (!moduleElementsHasExportAssignment(sourceUnit.moduleElements) || moduleContainsExecutableCode) { + createModuleVariableDecl(decl, sourceUnit, context); + } + + context.pushParent(decl); + } + } + + function preCollectEnumDecls(enumDecl, context) { + var declFlags = 0 /* None */; + var enumName = enumDecl.identifier.valueText(); + + if ((TypeScript.hasModifier(enumDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(enumDecl, context)) && !containingModuleHasExportAssignment(enumDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(enumDecl.modifiers, 8 /* Ambient */) || isParsingAmbientModule(enumDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + declFlags |= 4096 /* Enum */; + var kind = 64 /* Enum */; + + var enumDeclaration = new TypeScript.NormalPullDecl(enumName, enumDecl.identifier.text(), kind, declFlags, context.getParent()); + context.semanticInfoChain.setDeclForAST(enumDecl, enumDeclaration); + context.semanticInfoChain.setASTForDecl(enumDeclaration, enumDecl); + + var valueDecl = new TypeScript.NormalPullDecl(enumDeclaration.name, enumDeclaration.getDisplayName(), 512 /* Variable */, enumDeclaration.flags, context.getParent()); + enumDeclaration.setValueDecl(valueDecl); + context.semanticInfoChain.setASTForDecl(valueDecl, enumDecl); + + context.pushParent(enumDeclaration); + } + + function createEnumElementDecls(propertyDecl, context) { + var parent = context.getParent(); + + var decl = new TypeScript.PullEnumElementDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), parent); + context.semanticInfoChain.setDeclForAST(propertyDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyDecl); + } + + function preCollectModuleDecls(moduleDecl, context) { + var declFlags = 0 /* None */; + + var moduleContainsExecutableCode = containsExecutableCode(moduleDecl.moduleElements); + + var isDynamic = moduleDecl.stringLiteral !== null; + + if ((TypeScript.hasModifier(moduleDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(moduleDecl, context)) && !containingModuleHasExportAssignment(moduleDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(moduleDecl.modifiers, 8 /* Ambient */) || isParsingAmbientModule(moduleDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + var kind = isDynamic ? 32 /* DynamicModule */ : 4 /* Container */; + + if (moduleDecl.stringLiteral) { + var valueText = TypeScript.quoteStr(moduleDecl.stringLiteral.valueText()); + var text = moduleDecl.stringLiteral.text(); + + var decl = new TypeScript.NormalPullDecl(valueText, text, kind, declFlags, context.getParent()); + + context.semanticInfoChain.setDeclForAST(moduleDecl, decl); + context.semanticInfoChain.setDeclForAST(moduleDecl.stringLiteral, decl); + context.semanticInfoChain.setASTForDecl(decl, moduleDecl.stringLiteral); + + if (!moduleElementsHasExportAssignment(moduleDecl.moduleElements) || moduleContainsExecutableCode) { + createModuleVariableDecl(decl, moduleDecl.stringLiteral, context); + } + + context.pushParent(decl); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDecl.name); + for (var i = 0, n = moduleNames.length; i < n; i++) { + var moduleName = moduleNames[i]; + + var specificFlags = declFlags; + if (i > 0) { + specificFlags |= 1 /* Exported */; + } + + var decl = new TypeScript.NormalPullDecl(moduleName.valueText(), moduleName.text(), kind, specificFlags, context.getParent()); + + context.semanticInfoChain.setDeclForAST(moduleDecl, decl); + context.semanticInfoChain.setDeclForAST(moduleName, decl); + context.semanticInfoChain.setASTForDecl(decl, moduleName); + + if (moduleContainsExecutableCode) { + createModuleVariableDecl(decl, moduleName, context); + } + + context.pushParent(decl); + } + } + } + + function createModuleVariableDecl(decl, moduleNameAST, context) { + decl.setFlags(decl.flags | getInitializationFlag(decl)); + + var valueDecl = new TypeScript.NormalPullDecl(decl.name, decl.getDisplayName(), 512 /* Variable */, decl.flags, context.getParent()); + decl.setValueDecl(valueDecl); + context.semanticInfoChain.setASTForDecl(valueDecl, moduleNameAST); + } + + function containsExecutableCode(members) { + for (var i = 0, n = members.childCount(); i < n; i++) { + var member = members.childAt(i); + + if (member.kind() === 130 /* ModuleDeclaration */) { + var moduleDecl = member; + + if (containsExecutableCode(moduleDecl.moduleElements)) { + return true; + } + } else if (member.kind() === 133 /* ImportDeclaration */) { + if (TypeScript.hasModifier(member.modifiers, 1 /* Exported */)) { + return true; + } + } else if (member.kind() !== 128 /* InterfaceDeclaration */ && member.kind() !== 134 /* ExportAssignment */) { + return true; + } + } + + return false; + } + + function preCollectClassDecls(classDecl, context) { + var declFlags = 0 /* None */; + + if ((TypeScript.hasModifier(classDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(classDecl, context)) && !containingModuleHasExportAssignment(classDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(classDecl.modifiers, 8 /* Ambient */) || isParsingAmbientModule(classDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), 8 /* Class */, declFlags, parent); + + var constructorDecl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), 512 /* Variable */, declFlags | 16384 /* ClassConstructorVariable */, parent); + + decl.setValueDecl(constructorDecl); + + context.semanticInfoChain.setDeclForAST(classDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, classDecl); + context.semanticInfoChain.setASTForDecl(constructorDecl, classDecl); + + context.pushParent(decl); + } + + function preCollectObjectTypeDecls(objectType, context) { + if (objectType.parent.kind() === 128 /* InterfaceDeclaration */) { + return; + } + + var declFlags = 0 /* None */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", 8388608 /* ObjectType */, declFlags, parent); + context.semanticInfoChain.setDeclForAST(objectType, decl); + context.semanticInfoChain.setASTForDecl(decl, objectType); + + context.pushParent(decl); + } + + function preCollectInterfaceDecls(interfaceDecl, context) { + var declFlags = 0 /* None */; + + if ((TypeScript.hasModifier(interfaceDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(interfaceDecl, context)) && !containingModuleHasExportAssignment(interfaceDecl)) { + declFlags |= 1 /* Exported */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(interfaceDecl.identifier.valueText(), interfaceDecl.identifier.text(), 16 /* Interface */, declFlags, parent); + context.semanticInfoChain.setDeclForAST(interfaceDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, interfaceDecl); + + context.pushParent(decl); + } + + function preCollectParameterDecl(argDecl, context) { + var declFlags = 0 /* None */; + + if (TypeScript.hasModifier(argDecl.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (argDecl.questionToken !== null || argDecl.equalsValueClause !== null || argDecl.dotDotDotToken !== null) { + declFlags |= 128 /* Optional */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 2048 /* Parameter */, declFlags, parent); + + if (argDecl.equalsValueClause) { + parent.flags |= 33554432 /* HasDefaultArgs */; + } + + if (parent.kind === 32768 /* ConstructorMethod */) { + decl.setFlag(67108864 /* ConstructorParameter */); + } + + var isPublicOrPrivate = TypeScript.hasModifier(argDecl.modifiers, 4 /* Public */ | 2 /* Private */); + var isInConstructor = parent.kind === 32768 /* ConstructorMethod */; + if (isPublicOrPrivate && isInConstructor) { + var parentsParent = context.parentChain[context.parentChain.length - 2]; + + var propDeclFlags = declFlags & ~128 /* Optional */; + var propDecl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 4096 /* Property */, propDeclFlags, parentsParent); + propDecl.setValueDecl(decl); + decl.setFlag(8388608 /* PropertyParameter */); + propDecl.setFlag(8388608 /* PropertyParameter */); + + if (parent.kind === 32768 /* ConstructorMethod */) { + propDecl.setFlag(67108864 /* ConstructorParameter */); + } + + context.semanticInfoChain.setASTForDecl(decl, argDecl); + context.semanticInfoChain.setASTForDecl(propDecl, argDecl); + context.semanticInfoChain.setDeclForAST(argDecl, propDecl); + } else { + context.semanticInfoChain.setASTForDecl(decl, argDecl); + context.semanticInfoChain.setDeclForAST(argDecl, decl); + } + + parent.addVariableDeclToGroup(decl); + } + + function preCollectTypeParameterDecl(typeParameterDecl, context) { + var declFlags = 0 /* None */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(typeParameterDecl.identifier.valueText(), typeParameterDecl.identifier.text(), 8192 /* TypeParameter */, declFlags, parent); + context.semanticInfoChain.setASTForDecl(decl, typeParameterDecl); + context.semanticInfoChain.setDeclForAST(typeParameterDecl, decl); + } + + function createPropertySignature(propertyDecl, context) { + var declFlags = 4 /* Public */; + var parent = context.getParent(); + var declType = 4096 /* Property */; + + if (propertyDecl.questionToken !== null) { + declFlags |= 128 /* Optional */; + } + + var decl = new TypeScript.NormalPullDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(propertyDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyDecl); + } + + function createMemberVariableDeclaration(memberDecl, context) { + var declFlags = 0 /* None */; + var declType = 4096 /* Property */; + + if (TypeScript.hasModifier(memberDecl.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (TypeScript.hasModifier(memberDecl.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(memberDecl.variableDeclarator.propertyName.valueText(), memberDecl.variableDeclarator.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(memberDecl, decl); + context.semanticInfoChain.setDeclForAST(memberDecl.variableDeclarator, decl); + context.semanticInfoChain.setASTForDecl(decl, memberDecl); + } + + function createVariableDeclaration(varDecl, context) { + var declFlags = 0 /* None */; + var declType = 512 /* Variable */; + + var modifiers = TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl); + if ((TypeScript.hasModifier(modifiers, 1 /* Exported */) || isParsingAmbientModule(varDecl, context)) && !containingModuleHasExportAssignment(varDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(modifiers, 8 /* Ambient */) || isParsingAmbientModule(varDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(varDecl.propertyName.valueText(), varDecl.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(varDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, varDecl); + + if (parent) { + parent.addVariableDeclToGroup(decl); + } + } + + function preCollectVarDecls(ast, context) { + if (ast.parent.kind() === 136 /* MemberVariableDeclaration */) { + return; + } + + var varDecl = ast; + createVariableDeclaration(varDecl, context); + } + + function createFunctionTypeDeclaration(functionTypeDeclAST, context) { + var declFlags = 2048 /* Signature */; + var declType = 16777216 /* FunctionType */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(functionTypeDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, functionTypeDeclAST); + + context.pushParent(decl); + } + + function createConstructorTypeDeclaration(constructorTypeDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 33554432 /* ConstructorType */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(constructorTypeDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, constructorTypeDeclAST); + + context.pushParent(decl); + } + + function createFunctionDeclaration(funcDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 16384 /* Function */; + + if ((TypeScript.hasModifier(funcDeclAST.modifiers, 1 /* Exported */) || isParsingAmbientModule(funcDeclAST, context)) && !containingModuleHasExportAssignment(funcDeclAST)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(funcDeclAST.modifiers, 8 /* Ambient */) || isParsingAmbientModule(funcDeclAST, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + if (!funcDeclAST.block) { + declFlags |= 2048 /* Signature */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(funcDeclAST.identifier.valueText(), funcDeclAST.identifier.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(funcDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, funcDeclAST); + + context.pushParent(decl); + } + + function createAnyFunctionExpressionDeclaration(functionExpressionDeclAST, id, context, displayName) { + if (typeof displayName === "undefined") { displayName = null; } + var declFlags = 0 /* None */; + + if (functionExpressionDeclAST.kind() === 219 /* SimpleArrowFunctionExpression */ || functionExpressionDeclAST.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { + declFlags |= 8192 /* ArrowFunction */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var name = id ? id.text() : ""; + var displayNameText = displayName ? displayName.text() : ""; + var decl = new TypeScript.PullFunctionExpressionDecl(name, declFlags, parent, displayNameText); + context.semanticInfoChain.setDeclForAST(functionExpressionDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, functionExpressionDeclAST); + + context.pushParent(decl); + + if (functionExpressionDeclAST.kind() === 219 /* SimpleArrowFunctionExpression */) { + var simpleArrow = functionExpressionDeclAST; + var declFlags = 4 /* Public */; + + var parent = context.getParent(); + + if (TypeScript.hasFlag(parent.flags, 2097152 /* DeclaredInAWithBlock */)) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(simpleArrow.identifier.valueText(), simpleArrow.identifier.text(), 2048 /* Parameter */, declFlags, parent); + + context.semanticInfoChain.setASTForDecl(decl, simpleArrow.identifier); + context.semanticInfoChain.setDeclForAST(simpleArrow.identifier, decl); + + parent.addVariableDeclToGroup(decl); + } + } + + function createMemberFunctionDeclaration(funcDecl, context) { + var declFlags = 0 /* None */; + var declType = 65536 /* Method */; + + if (TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasModifier(funcDecl.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (!funcDecl.block) { + declFlags |= 2048 /* Signature */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(funcDecl.propertyName.valueText(), funcDecl.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(funcDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, funcDecl); + + context.pushParent(decl); + } + + function createIndexSignatureDeclaration(indexSignatureDeclAST, context) { + var declFlags = 2048 /* Signature */; + var declType = 4194304 /* IndexSignature */; + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(indexSignatureDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, indexSignatureDeclAST); + + context.pushParent(decl); + } + + function createCallSignatureDeclaration(callSignature, context) { + var isChildOfObjectType = callSignature.parent && callSignature.parent.parent && callSignature.parent.kind() === 2 /* SeparatedList */ && callSignature.parent.parent.kind() === 122 /* ObjectType */; + + if (!isChildOfObjectType) { + return; + } + + var declFlags = 2048 /* Signature */; + var declType = 1048576 /* CallSignature */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(callSignature, decl); + context.semanticInfoChain.setASTForDecl(decl, callSignature); + + context.pushParent(decl); + } + + function createMethodSignatureDeclaration(method, context) { + var declFlags = 0 /* None */; + var declType = 65536 /* Method */; + + declFlags |= 4 /* Public */; + declFlags |= 2048 /* Signature */; + + if (method.questionToken !== null) { + declFlags |= 128 /* Optional */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(method.propertyName.valueText(), method.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(method, decl); + context.semanticInfoChain.setASTForDecl(decl, method); + + context.pushParent(decl); + } + + function createConstructSignatureDeclaration(constructSignatureDeclAST, context) { + var declFlags = 2048 /* Signature */; + var declType = 2097152 /* ConstructSignature */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(constructSignatureDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, constructSignatureDeclAST); + + context.pushParent(decl); + } + + function createClassConstructorDeclaration(constructorDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 32768 /* ConstructorMethod */; + + if (!constructorDeclAST.block) { + declFlags |= 2048 /* Signature */; + } + + var parent = context.getParent(); + + if (parent) { + var parentFlags = parent.flags; + + if (parentFlags & 1 /* Exported */) { + declFlags |= 1 /* Exported */; + } + } + + var decl = new TypeScript.NormalPullDecl(parent.name, parent.getDisplayName(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(constructorDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, constructorDeclAST); + + context.pushParent(decl); + } + + function createGetAccessorDeclaration(getAccessorDeclAST, context) { + var declFlags = 4 /* Public */; + var declType = 262144 /* GetAccessor */; + + if (TypeScript.hasModifier(getAccessorDeclAST.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasModifier(getAccessorDeclAST.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(getAccessorDeclAST.propertyName.valueText(), getAccessorDeclAST.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(getAccessorDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, getAccessorDeclAST); + + context.pushParent(decl); + } + + function createFunctionExpressionDeclaration(expression, context) { + createAnyFunctionExpressionDeclaration(expression, expression.identifier, context); + } + + function createSetAccessorDeclaration(setAccessorDeclAST, context) { + var declFlags = 4 /* Public */; + var declType = 524288 /* SetAccessor */; + + if (TypeScript.hasModifier(setAccessorDeclAST.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasModifier(setAccessorDeclAST.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(setAccessorDeclAST.propertyName.valueText(), setAccessorDeclAST.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(setAccessorDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, setAccessorDeclAST); + + context.pushParent(decl); + } + + function preCollectCatchDecls(ast, context) { + var declFlags = 0 /* None */; + var declType = 268435456 /* CatchBlock */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + + context.pushParent(decl); + + var declFlags = 0 /* None */; + var declType = 1024 /* CatchVariable */; + + var parent = context.getParent(); + + if (TypeScript.hasFlag(parent.flags, 2097152 /* DeclaredInAWithBlock */)) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(ast.identifier.valueText(), ast.identifier.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast.identifier, decl); + context.semanticInfoChain.setASTForDecl(decl, ast.identifier); + + if (parent) { + parent.addVariableDeclToGroup(decl); + } + } + + function preCollectWithDecls(ast, context) { + var declFlags = 0 /* None */; + var declType = 134217728 /* WithBlock */; + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + + context.pushParent(decl); + } + + function preCollectObjectLiteralDecls(ast, context) { + var decl = new TypeScript.NormalPullDecl("", "", 256 /* ObjectLiteral */, 0 /* None */, context.getParent()); + + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + + context.pushParent(decl); + } + + function preCollectSimplePropertyAssignmentDecls(propertyAssignment, context) { + var assignmentText = TypeScript.getPropertyAssignmentNameTextFromIdentifier(propertyAssignment.propertyName); + var span = TypeScript.TextSpan.fromBounds(propertyAssignment.start(), propertyAssignment.end()); + + var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent()); + + context.semanticInfoChain.setDeclForAST(propertyAssignment, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyAssignment); + } + + function preCollectFunctionPropertyAssignmentDecls(propertyAssignment, context) { + var assignmentText = TypeScript.getPropertyAssignmentNameTextFromIdentifier(propertyAssignment.propertyName); + + var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent()); + + context.semanticInfoChain.setDeclForAST(propertyAssignment, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyAssignment); + + createAnyFunctionExpressionDeclaration(propertyAssignment, propertyAssignment.propertyName, context, propertyAssignment.propertyName); + } + + function preCollectDecls(ast, context) { + switch (ast.kind()) { + case 120 /* SourceUnit */: + preCollectScriptDecls(ast, context); + break; + case 132 /* EnumDeclaration */: + preCollectEnumDecls(ast, context); + break; + case 243 /* EnumElement */: + createEnumElementDecls(ast, context); + break; + case 130 /* ModuleDeclaration */: + preCollectModuleDecls(ast, context); + break; + case 131 /* ClassDeclaration */: + preCollectClassDecls(ast, context); + break; + case 128 /* InterfaceDeclaration */: + preCollectInterfaceDecls(ast, context); + break; + case 122 /* ObjectType */: + preCollectObjectTypeDecls(ast, context); + break; + case 242 /* Parameter */: + preCollectParameterDecl(ast, context); + break; + case 136 /* MemberVariableDeclaration */: + createMemberVariableDeclaration(ast, context); + break; + case 141 /* PropertySignature */: + createPropertySignature(ast, context); + break; + case 225 /* VariableDeclarator */: + preCollectVarDecls(ast, context); + break; + case 137 /* ConstructorDeclaration */: + createClassConstructorDeclaration(ast, context); + break; + case 139 /* GetAccessor */: + createGetAccessorDeclaration(ast, context); + break; + case 140 /* SetAccessor */: + createSetAccessorDeclaration(ast, context); + break; + case 222 /* FunctionExpression */: + createFunctionExpressionDeclaration(ast, context); + break; + case 135 /* MemberFunctionDeclaration */: + createMemberFunctionDeclaration(ast, context); + break; + case 144 /* IndexSignature */: + createIndexSignatureDeclaration(ast, context); + break; + case 123 /* FunctionType */: + createFunctionTypeDeclaration(ast, context); + break; + case 125 /* ConstructorType */: + createConstructorTypeDeclaration(ast, context); + break; + case 142 /* CallSignature */: + createCallSignatureDeclaration(ast, context); + break; + case 143 /* ConstructSignature */: + createConstructSignatureDeclaration(ast, context); + break; + case 145 /* MethodSignature */: + createMethodSignatureDeclaration(ast, context); + break; + case 129 /* FunctionDeclaration */: + createFunctionDeclaration(ast, context); + break; + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + createAnyFunctionExpressionDeclaration(ast, null, context); + break; + case 133 /* ImportDeclaration */: + preCollectImportDecls(ast, context); + break; + case 238 /* TypeParameter */: + preCollectTypeParameterDecl(ast, context); + break; + case 236 /* CatchClause */: + preCollectCatchDecls(ast, context); + break; + case 163 /* WithStatement */: + preCollectWithDecls(ast, context); + break; + case 215 /* ObjectLiteralExpression */: + preCollectObjectLiteralDecls(ast, context); + break; + case 240 /* SimplePropertyAssignment */: + preCollectSimplePropertyAssignmentDecls(ast, context); + break; + case 241 /* FunctionPropertyAssignment */: + preCollectFunctionPropertyAssignmentDecls(ast, context); + break; + } + } + + function isContainer(decl) { + return decl.kind === 4 /* Container */ || decl.kind === 32 /* DynamicModule */ || decl.kind === 64 /* Enum */; + } + + function getInitializationFlag(decl) { + if (decl.kind & 4 /* Container */) { + return 32768 /* InitializedModule */; + } else if (decl.kind & 32 /* DynamicModule */) { + return 65536 /* InitializedDynamicModule */; + } + + return 0 /* None */; + } + + function hasInitializationFlag(decl) { + var kind = decl.kind; + + if (kind & 4 /* Container */) { + return (decl.flags & 32768 /* InitializedModule */) !== 0; + } else if (kind & 32 /* DynamicModule */) { + return (decl.flags & 65536 /* InitializedDynamicModule */) !== 0; + } + + return false; + } + + function postCollectDecls(ast, context) { + var currentDecl = context.getParent(); + + if (ast.kind() === 11 /* IdentifierName */ || ast.kind() === 14 /* StringLiteral */) { + if (currentDecl.kind === 4 /* Container */ || currentDecl.kind === 32 /* DynamicModule */) { + return; + } + } + + if (ast.kind() === 130 /* ModuleDeclaration */) { + var moduleDeclaration = ast; + if (moduleDeclaration.stringLiteral) { + TypeScript.Debug.assert(currentDecl.ast() === moduleDeclaration.stringLiteral); + context.popParent(); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDeclaration.name); + for (var i = moduleNames.length - 1; i >= 0; i--) { + var moduleName = moduleNames[i]; + TypeScript.Debug.assert(currentDecl.ast() === moduleName); + context.popParent(); + currentDecl = context.getParent(); + } + } + } + + if (ast.kind() === 132 /* EnumDeclaration */) { + computeEnumElementConstantValues(ast, currentDecl, context); + } + + while (currentDecl.getParentDecl() && currentDecl.ast() === ast) { + context.popParent(); + currentDecl = context.getParent(); + } + } + + function computeEnumElementConstantValues(ast, enumDecl, context) { + TypeScript.Debug.assert(enumDecl.kind === 64 /* Enum */); + + var isAmbientEnum = TypeScript.hasFlag(enumDecl.flags, 8 /* Ambient */); + var inConstantSection = !isAmbientEnum; + var currentConstantValue = 0; + var enumMemberDecls = enumDecl.getChildDecls(); + + for (var i = 0, n = ast.enumElements.nonSeparatorCount(); i < n; i++) { + var enumElement = ast.enumElements.nonSeparatorAt(i); + var enumElementDecl = TypeScript.ArrayUtilities.first(enumMemberDecls, function (d) { + return context.semanticInfoChain.getASTForDecl(d) === enumElement; + }); + + TypeScript.Debug.assert(enumElementDecl.kind === 67108864 /* EnumMember */); + + if (enumElement.equalsValueClause === null) { + if (inConstantSection) { + enumElementDecl.constantValue = currentConstantValue; + currentConstantValue++; + } + } else { + enumElementDecl.constantValue = computeEnumElementConstantValue(enumElement.equalsValueClause.value, enumMemberDecls, context); + if (enumElementDecl.constantValue !== null && !isAmbientEnum) { + inConstantSection = true; + currentConstantValue = enumElementDecl.constantValue + 1; + } else { + inConstantSection = false; + } + } + + TypeScript.Debug.assert(enumElementDecl.constantValue !== undefined); + } + } + + function computeEnumElementConstantValue(expression, enumMemberDecls, context) { + TypeScript.Debug.assert(expression); + + if (TypeScript.ASTHelpers.isIntegerLiteralAST(expression)) { + var token; + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + token = expression.operand; + break; + default: + token = expression; + } + + var value = token.value(); + return value && expression.kind() === 165 /* NegateExpression */ ? -value : value; + } else if (context.propagateEnumConstants) { + switch (expression.kind()) { + case 11 /* IdentifierName */: + var name = expression; + var matchingEnumElement = TypeScript.ArrayUtilities.firstOrDefault(enumMemberDecls, function (d) { + return d.name === name.valueText(); + }); + + return matchingEnumElement ? matchingEnumElement.constantValue : null; + + case 202 /* LeftShiftExpression */: + var binaryExpression = expression; + var left = computeEnumElementConstantValue(binaryExpression.left, enumMemberDecls, context); + var right = computeEnumElementConstantValue(binaryExpression.right, enumMemberDecls, context); + if (left === null || right === null) { + return null; + } + + return left << right; + + case 189 /* BitwiseOrExpression */: + var binaryExpression = expression; + var left = computeEnumElementConstantValue(binaryExpression.left, enumMemberDecls, context); + var right = computeEnumElementConstantValue(binaryExpression.right, enumMemberDecls, context); + if (left === null || right === null) { + return null; + } + + return left | right; + } + + return null; + } else { + return null; + } + } + + (function (DeclarationCreator) { + function create(document, semanticInfoChain, compilationSettings) { + var declCollectionContext = new DeclCollectionContext(document, semanticInfoChain, compilationSettings.propagateEnumConstants()); + + TypeScript.getAstWalkerFactory().simpleWalk(document.sourceUnit(), preCollectDecls, postCollectDecls, declCollectionContext); + + return declCollectionContext.getParent(); + } + DeclarationCreator.create = create; + })(TypeScript.DeclarationCreator || (TypeScript.DeclarationCreator = {})); + var DeclarationCreator = TypeScript.DeclarationCreator; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PullSymbolBinder = (function () { + function PullSymbolBinder(semanticInfoChain) { + this.semanticInfoChain = semanticInfoChain; + this.declsBeingBound = []; + this.inBindingOtherDeclsWalker = new TypeScript.PullHelpers.OtherPullDeclsWalker(); + } + PullSymbolBinder.prototype.getParent = function (decl, returnInstanceType) { + if (typeof returnInstanceType === "undefined") { returnInstanceType = false; } + var parentDecl = decl.getParentDecl(); + + if (parentDecl.kind === 1 /* Script */) { + return null; + } + + var parent = parentDecl.getSymbol(); + + if (!parent && parentDecl && !parentDecl.hasBeenBound()) { + this.bindDeclToPullSymbol(parentDecl); + } + + parent = parentDecl.getSymbol(); + if (parent) { + var parentDeclKind = parentDecl.kind; + if (parentDeclKind === 262144 /* GetAccessor */) { + parent = parent.getGetter(); + } else if (parentDeclKind === 524288 /* SetAccessor */) { + parent = parent.getSetter(); + } + } + + if (parent) { + if (returnInstanceType && parent.isType() && parent.isContainer()) { + var instanceSymbol = parent.getInstanceSymbol(); + + if (instanceSymbol) { + return instanceSymbol.type; + } + } + + return parent.type; + } + + return null; + }; + + PullSymbolBinder.prototype.findDeclsInContext = function (startingDecl, declKind, searchGlobally) { + if (!searchGlobally) { + var parentDecl = startingDecl.getParentDecl(); + return parentDecl.searchChildDecls(startingDecl.name, declKind); + } + + var contextSymbolPath = startingDecl.getParentPath(); + + if (contextSymbolPath.length) { + var copyOfContextSymbolPath = []; + + for (var i = 0; i < contextSymbolPath.length; i++) { + if (contextSymbolPath[i].kind & 1 /* Script */) { + continue; + } + copyOfContextSymbolPath[copyOfContextSymbolPath.length] = contextSymbolPath[i].name; + } + + return this.semanticInfoChain.findDecls(copyOfContextSymbolPath, declKind); + } + }; + + PullSymbolBinder.prototype.getExistingSymbol = function (decl, searchKind, parent) { + var lookingForValue = (searchKind & 68147712 /* SomeValue */) !== 0; + var lookingForType = (searchKind & 58728795 /* SomeType */) !== 0; + var lookingForContainer = (searchKind & 164 /* SomeContainer */) !== 0; + var name = decl.name; + if (parent) { + var isExported = (decl.flags & 1 /* Exported */) !== 0; + + var prevSymbol = null; + if (lookingForValue) { + prevSymbol = parent.findContainedNonMember(name); + } else if (lookingForType) { + prevSymbol = parent.findContainedNonMemberType(name, searchKind); + } else if (lookingForContainer) { + prevSymbol = parent.findContainedNonMemberContainer(name, searchKind); + } + var prevIsExported = !prevSymbol; + if (!prevSymbol) { + if (lookingForValue) { + prevSymbol = parent.findMember(name, false); + } else if (lookingForType) { + prevSymbol = parent.findNestedType(name, searchKind); + } else if (lookingForContainer) { + prevSymbol = parent.findNestedContainer(name, searchKind); + } + } + + if (isExported && prevIsExported) { + return prevSymbol; + } + if (prevSymbol) { + var prevDecls = prevSymbol.getDeclarations(); + var lastPrevDecl = prevDecls[prevDecls.length - 1]; + var parentDecl = decl.getParentDecl(); + var prevParentDecl = lastPrevDecl && lastPrevDecl.getParentDecl(); + if (parentDecl !== prevParentDecl) { + return null; + } + + return prevSymbol; + } + } else { + var parentDecl = decl.getParentDecl(); + if (parentDecl && parentDecl.kind === 1 /* Script */) { + return this.semanticInfoChain.findTopLevelSymbol(name, searchKind, decl); + } else { + var prevDecls = parentDecl && parentDecl.searchChildDecls(name, searchKind); + return prevDecls[0] && prevDecls[0].getSymbol(); + } + } + + return null; + }; + + PullSymbolBinder.prototype.checkThatExportsMatch = function (decl, prevSymbol, reportError) { + if (typeof reportError === "undefined") { reportError = true; } + var isExported = (decl.flags & 1 /* Exported */) !== 0; + var prevDecls = prevSymbol.getDeclarations(); + var prevIsExported = (prevDecls[prevDecls.length - 1].flags & 1 /* Exported */) !== 0; + if ((isExported !== prevIsExported) && !prevSymbol.isSignature() && (decl.kind & 7340032 /* SomeSignature */) === 0) { + if (reportError) { + var ast = this.semanticInfoChain.getASTForDecl(decl); + this.semanticInfoChain.addDiagnosticFromAST(ast, TypeScript.DiagnosticCode.All_declarations_of_merged_declaration_0_must_be_exported_or_not_exported, [decl.getDisplayName()]); + } + return false; + } + + return true; + }; + + PullSymbolBinder.prototype.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList = function (signature, currentSignatures) { + var signatureDecl = signature.getDeclarations()[0]; + TypeScript.Debug.assert(signatureDecl); + var enclosingDecl = signatureDecl.getParentDecl(); + var indexToInsert = TypeScript.ArrayUtilities.indexOf(currentSignatures, function (someSignature) { + return someSignature.getDeclarations()[0].getParentDecl() !== enclosingDecl; + }); + return indexToInsert < 0 ? currentSignatures.length : indexToInsert; + }; + + PullSymbolBinder.prototype.bindEnumDeclarationToPullSymbol = function (enumContainerDecl) { + var enumName = enumContainerDecl.name; + + var enumContainerSymbol = null; + var enumInstanceSymbol = null; + var moduleInstanceTypeSymbol = null; + + var enumInstanceDecl = enumContainerDecl.getValueDecl(); + + var enumDeclKind = enumContainerDecl.kind; + + var parent = this.getParent(enumContainerDecl); + var parentInstanceSymbol = this.getParent(enumContainerDecl, true); + var parentDecl = enumContainerDecl.getParentDecl(); + var enumAST = this.semanticInfoChain.getASTForDecl(enumContainerDecl); + + var isExported = enumContainerDecl.flags & 1 /* Exported */; + + var createdNewSymbol = false; + + enumContainerSymbol = this.getExistingSymbol(enumContainerDecl, 64 /* Enum */, parent); + + if (enumContainerSymbol) { + if (enumContainerSymbol.kind !== enumDeclKind) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(enumAST.identifier, enumContainerDecl.getDisplayName(), enumContainerSymbol.getDeclarations()[0].ast()); + enumContainerSymbol = null; + } else if (!this.checkThatExportsMatch(enumContainerDecl, enumContainerSymbol)) { + enumContainerSymbol = null; + } + } + + if (enumContainerSymbol) { + enumInstanceSymbol = enumContainerSymbol.getInstanceSymbol(); + } else { + enumContainerSymbol = new TypeScript.PullContainerSymbol(enumName, enumDeclKind); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(enumContainerSymbol, 64 /* Enum */); + } + } + + enumContainerSymbol.addDeclaration(enumContainerDecl); + enumContainerDecl.setSymbol(enumContainerSymbol); + + this.semanticInfoChain.setSymbolForAST(enumAST.identifier, enumContainerSymbol); + this.semanticInfoChain.setSymbolForAST(enumAST, enumContainerSymbol); + + if (!enumInstanceSymbol) { + var variableSymbol = null; + if (parentInstanceSymbol) { + if (isExported) { + variableSymbol = parentInstanceSymbol.findMember(enumName, false); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findContainedNonMember(enumName); + } + } else { + variableSymbol = parentInstanceSymbol.findContainedNonMember(enumName); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findMember(enumName, false); + } + } + + if (variableSymbol) { + var declarations = variableSymbol.getDeclarations(); + + if (declarations.length) { + var variableSymbolParentDecl = declarations[0].getParentDecl(); + + if (parentDecl !== variableSymbolParentDecl) { + variableSymbol = null; + } + } + } + } else if (!(enumContainerDecl.flags & 1 /* Exported */)) { + var siblingDecls = parentDecl.getChildDecls(); + var augmentedDecl = null; + + for (var i = 0; i < siblingDecls.length; i++) { + if (siblingDecls[i] === enumContainerDecl) { + break; + } + + if ((siblingDecls[i].name === enumName) && (siblingDecls[i].kind & 68147712 /* SomeValue */)) { + augmentedDecl = siblingDecls[i]; + break; + } + } + + if (augmentedDecl) { + variableSymbol = augmentedDecl.getSymbol(); + + if (variableSymbol) { + if (variableSymbol.isContainer()) { + variableSymbol = variableSymbol.getInstanceSymbol(); + } else if (variableSymbol && variableSymbol.isType()) { + variableSymbol = variableSymbol.getConstructorMethod(); + } + } + } + } + + if (variableSymbol) { + enumInstanceSymbol = variableSymbol; + moduleInstanceTypeSymbol = variableSymbol.type; + } else { + enumInstanceSymbol = new TypeScript.PullSymbol(enumName, 512 /* Variable */); + } + + enumContainerSymbol.setInstanceSymbol(enumInstanceSymbol); + + if (!moduleInstanceTypeSymbol) { + moduleInstanceTypeSymbol = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + enumInstanceSymbol.type = moduleInstanceTypeSymbol; + } + + moduleInstanceTypeSymbol.addDeclaration(enumContainerDecl); + + if (!moduleInstanceTypeSymbol.getAssociatedContainerType()) { + moduleInstanceTypeSymbol.setAssociatedContainerType(enumContainerSymbol); + } + } + + if (createdNewSymbol && parent) { + if (enumContainerDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberType(enumContainerSymbol); + } else { + parent.addEnclosedNonMemberType(enumContainerSymbol); + } + } + + if (createdNewSymbol) { + this.bindEnumIndexerDeclsToPullSymbols(enumContainerSymbol); + } + var valueDecl = enumContainerDecl.getValueDecl(); + + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + }; + + PullSymbolBinder.prototype.bindEnumIndexerDeclsToPullSymbols = function (enumContainerSymbol) { + var enumContainerInstanceTypeSymbol = enumContainerSymbol.getInstanceSymbol().type; + + var syntheticIndexerParameterSymbol = new TypeScript.PullSymbol("x", 2048 /* Parameter */); + syntheticIndexerParameterSymbol.type = this.semanticInfoChain.numberTypeSymbol; + syntheticIndexerParameterSymbol.setResolved(); + syntheticIndexerParameterSymbol.setIsSynthesized(); + + var syntheticIndexerSignatureSymbol = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + syntheticIndexerSignatureSymbol.addParameter(syntheticIndexerParameterSymbol); + syntheticIndexerSignatureSymbol.returnType = this.semanticInfoChain.stringTypeSymbol; + syntheticIndexerSignatureSymbol.setResolved(); + syntheticIndexerSignatureSymbol.setIsSynthesized(); + + enumContainerInstanceTypeSymbol.addIndexSignature(syntheticIndexerSignatureSymbol); + }; + + PullSymbolBinder.prototype.findExistingVariableSymbolForModuleValueDecl = function (decl) { + var isExported = TypeScript.hasFlag(decl.flags, 1 /* Exported */); + var modName = decl.name; + var parentInstanceSymbol = this.getParent(decl, true); + var parentDecl = decl.getParentDecl(); + + var variableSymbol = null; + + if (parentInstanceSymbol) { + if (isExported) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); + } + } else { + variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + } + } + + if (variableSymbol) { + var declarations = variableSymbol.getDeclarations(); + + if (declarations.length) { + var variableSymbolParentDecl = declarations[0].getParentDecl(); + var isExportedOrHasTheSameParent = isExported || (parentDecl === variableSymbolParentDecl); + + var canReuseVariableSymbol = isExportedOrHasTheSameParent && this.checkThatExportsMatch(decl, variableSymbol, false); + + if (!canReuseVariableSymbol) { + variableSymbol = null; + } + } + } + } else if (!isExported) { + var siblingDecls = parentDecl.getChildDecls(); + + for (var i = 0; i < siblingDecls.length; i++) { + var sibling = siblingDecls[i]; + + var siblingIsSomeValue = TypeScript.hasFlag(sibling.kind, 68147712 /* SomeValue */); + var siblingIsFunctionOrHasImplictVarFlag = TypeScript.hasFlag(sibling.kind, 1032192 /* SomeFunction */) || TypeScript.hasFlag(sibling.flags, 118784 /* ImplicitVariable */); + + var isSiblingAnAugmentableVariable = sibling !== decl && sibling !== decl.getValueDecl() && sibling.name === modName && siblingIsSomeValue && siblingIsFunctionOrHasImplictVarFlag; + + if (isSiblingAnAugmentableVariable) { + if (sibling.hasSymbol()) { + variableSymbol = sibling.getSymbol(); + if (variableSymbol.isContainer()) { + variableSymbol = variableSymbol.getInstanceSymbol(); + } else if (variableSymbol && variableSymbol.isType()) { + variableSymbol = variableSymbol.getConstructorMethod(); + } + + break; + } + } + } + } + return variableSymbol; + }; + + PullSymbolBinder.prototype.bindModuleDeclarationToPullSymbol = function (moduleContainerDecl) { + var modName = moduleContainerDecl.name; + + var moduleContainerTypeSymbol = null; + var moduleKind = moduleContainerDecl.kind; + + var parent = this.getParent(moduleContainerDecl); + var parentInstanceSymbol = this.getParent(moduleContainerDecl, true); + var parentDecl = moduleContainerDecl.getParentDecl(); + var moduleNameAST = this.semanticInfoChain.getASTForDecl(moduleContainerDecl); + var moduleDeclAST = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(moduleNameAST); + if (!moduleDeclAST) { + TypeScript.Debug.assert(moduleKind === 32 /* DynamicModule */); + TypeScript.Debug.assert(moduleNameAST.kind() === 120 /* SourceUnit */); + + moduleDeclAST = moduleNameAST; + } + + var isExported = TypeScript.hasFlag(moduleContainerDecl.flags, 1 /* Exported */); + var searchKind = 164 /* SomeContainer */; + var isInitializedModule = (moduleContainerDecl.flags & 102400 /* SomeInitializedModule */) !== 0; + + if (parent && moduleKind === 32 /* DynamicModule */) { + this.semanticInfoChain.addDiagnosticFromAST(moduleNameAST, TypeScript.DiagnosticCode.Ambient_external_module_declaration_must_be_defined_in_global_context, null); + } + + var createdNewSymbol = false; + + moduleContainerTypeSymbol = this.getExistingSymbol(moduleContainerDecl, searchKind, parent); + + if (moduleContainerTypeSymbol) { + if (moduleContainerTypeSymbol.kind !== moduleKind) { + if (isInitializedModule) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(moduleNameAST, moduleContainerDecl.getDisplayName(), moduleContainerTypeSymbol.getDeclarations()[0].ast()); + } + + moduleContainerTypeSymbol = null; + } else if (moduleKind === 32 /* DynamicModule */) { + this.semanticInfoChain.addDiagnosticFromAST(moduleNameAST, TypeScript.DiagnosticCode.Ambient_external_module_declaration_cannot_be_reopened); + } else if (!this.checkThatExportsMatch(moduleContainerDecl, moduleContainerTypeSymbol)) { + moduleContainerTypeSymbol = null; + } + } + + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = new TypeScript.PullContainerSymbol(modName, moduleKind); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(moduleContainerTypeSymbol, searchKind); + } + } + + moduleContainerTypeSymbol.addDeclaration(moduleContainerDecl); + moduleContainerDecl.setSymbol(moduleContainerTypeSymbol); + + this.semanticInfoChain.setSymbolForAST(moduleNameAST, moduleContainerTypeSymbol); + this.semanticInfoChain.setSymbolForAST(moduleDeclAST, moduleContainerTypeSymbol); + + var currentModuleValueDecl = moduleContainerDecl.getValueDecl(); + + var moduleDeclarations = moduleContainerTypeSymbol.getDeclarations(); + + if (createdNewSymbol) { + if (parent) { + if (moduleContainerDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberContainer(moduleContainerTypeSymbol); + } else { + parent.addEnclosedNonMemberContainer(moduleContainerTypeSymbol); + } + } + } + + if (currentModuleValueDecl) { + currentModuleValueDecl.ensureSymbolIsBound(); + + var instanceSymbol = null; + var instanceTypeSymbol = null; + if (currentModuleValueDecl.hasSymbol()) { + instanceSymbol = currentModuleValueDecl.getSymbol(); + } else { + instanceSymbol = new TypeScript.PullSymbol(modName, 512 /* Variable */); + currentModuleValueDecl.setSymbol(instanceSymbol); + if (!instanceSymbol.hasDeclaration(currentModuleValueDecl)) { + instanceSymbol.addDeclaration(currentModuleValueDecl); + } + } + + if (!instanceSymbol.type) { + instanceSymbol.type = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + } + + moduleContainerTypeSymbol.setInstanceSymbol(instanceSymbol); + + if (!instanceSymbol.type.getAssociatedContainerType()) { + instanceSymbol.type.setAssociatedContainerType(moduleContainerTypeSymbol); + } + } + }; + + PullSymbolBinder.prototype.bindImportDeclaration = function (importDeclaration) { + var declFlags = importDeclaration.flags; + var declKind = importDeclaration.kind; + var importDeclAST = this.semanticInfoChain.getASTForDecl(importDeclaration); + + var isExported = false; + var importSymbol = null; + var declName = importDeclaration.name; + var parentHadSymbol = false; + var parent = this.getParent(importDeclaration); + + importSymbol = this.getExistingSymbol(importDeclaration, 164 /* SomeContainer */, parent); + + if (importSymbol) { + parentHadSymbol = true; + } + + if (importSymbol) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(importDeclAST, importDeclaration.getDisplayName(), importSymbol.getDeclarations()[0].ast()); + importSymbol = null; + } + + if (!importSymbol) { + importSymbol = new TypeScript.PullTypeAliasSymbol(declName); + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(importSymbol, 164 /* SomeContainer */); + } + } + + importSymbol.addDeclaration(importDeclaration); + importDeclaration.setSymbol(importSymbol); + + this.semanticInfoChain.setSymbolForAST(importDeclAST, importSymbol); + + if (parent && !parentHadSymbol) { + if (declFlags & 1 /* Exported */) { + parent.addEnclosedMemberContainer(importSymbol); + } else { + parent.addEnclosedNonMemberContainer(importSymbol); + } + } + }; + + PullSymbolBinder.prototype.ensurePriorDeclarationsAreBound = function (container, currentDecl) { + if (!container) { + return; + } + + var parentDecls = container.getDeclarations(); + for (var i = 0; i < parentDecls.length; ++i) { + var parentDecl = parentDecls[i]; + var childDecls = parentDecl.getChildDecls(); + for (var j = 0; j < childDecls.length; ++j) { + var childDecl = childDecls[j]; + if (childDecl === currentDecl) { + return; + } + + if (childDecl.name === currentDecl.name) { + childDecl.ensureSymbolIsBound(); + } + } + } + }; + + PullSymbolBinder.prototype.bindClassDeclarationToPullSymbol = function (classDecl) { + var className = classDecl.name; + var classSymbol = null; + + var constructorSymbol = null; + var constructorTypeSymbol = null; + + var classAST = this.semanticInfoChain.getASTForDecl(classDecl); + + var parent = this.getParent(classDecl); + + this.ensurePriorDeclarationsAreBound(parent, classDecl); + + var parentDecl = classDecl.getParentDecl(); + var isExported = classDecl.flags & 1 /* Exported */; + var isGeneric = false; + + classSymbol = this.getExistingSymbol(classDecl, 58728795 /* SomeType */, parent); + + if (classSymbol && classSymbol.kind === 16 /* Interface */) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(classAST.identifier, classDecl.getDisplayName(), classSymbol.getDeclarations()[0].ast()); + classSymbol = null; + } + + classSymbol = new TypeScript.PullTypeSymbol(className, 8 /* Class */); + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(classSymbol, 8 /* Class */); + } + + classSymbol.addDeclaration(classDecl); + + classDecl.setSymbol(classSymbol); + + this.semanticInfoChain.setSymbolForAST(classAST.identifier, classSymbol); + this.semanticInfoChain.setSymbolForAST(classAST, classSymbol); + + if (parent) { + if (classDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberType(classSymbol); + } else { + parent.addEnclosedNonMemberType(classSymbol); + } + } + + var typeParameterDecls = classDecl.getTypeParameters(); + + for (var i = 0; i < typeParameterDecls.length; i++) { + var typeParameterSymbol = classSymbol.findTypeParameter(typeParameterDecls[i].name); + + if (typeParameterSymbol) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterSymbol.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameterSymbol.getName()]); + } + + typeParameterSymbol = new TypeScript.PullTypeParameterSymbol(typeParameterDecls[i].name); + + classSymbol.addTypeParameter(typeParameterSymbol); + typeParameterSymbol.addDeclaration(typeParameterDecls[i]); + typeParameterDecls[i].setSymbol(typeParameterSymbol); + } + + constructorSymbol = classSymbol.getConstructorMethod(); + constructorTypeSymbol = constructorSymbol ? constructorSymbol.type : null; + + if (!constructorSymbol) { + var siblingValueDecls = null; + if (parentDecl) { + siblingValueDecls = parentDecl.searchChildDecls(className, 68147712 /* SomeValue */); + + if (siblingValueDecls && siblingValueDecls[0] && siblingValueDecls[0].hasSymbol()) { + constructorSymbol = siblingValueDecls[0].getSymbol(); + } + } + + if (constructorSymbol) { + constructorTypeSymbol = constructorSymbol.type; + } else { + constructorSymbol = new TypeScript.PullSymbol(className, 32768 /* ConstructorMethod */); + constructorTypeSymbol = new TypeScript.PullTypeSymbol("", 33554432 /* ConstructorType */); + constructorSymbol.setIsSynthesized(); + constructorSymbol.type = constructorTypeSymbol; + } + + classSymbol.setConstructorMethod(constructorSymbol); + classSymbol.setHasDefaultConstructor(); + } + + if (constructorSymbol.getIsSynthesized()) { + constructorSymbol.addDeclaration(classDecl.getValueDecl()); + constructorTypeSymbol.addDeclaration(classDecl); + } else { + classSymbol.setHasDefaultConstructor(false); + } + + constructorTypeSymbol.setAssociatedContainerType(classSymbol); + + var valueDecl = classDecl.getValueDecl(); + + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + + this.bindStaticPrototypePropertyOfClass(classAST, classSymbol, constructorTypeSymbol); + }; + + PullSymbolBinder.prototype.bindInterfaceDeclarationToPullSymbol = function (interfaceDecl) { + var interfaceName = interfaceDecl.name; + var interfaceSymbol = null; + + var interfaceAST = this.semanticInfoChain.getASTForDecl(interfaceDecl); + var createdNewSymbol = false; + var parent = this.getParent(interfaceDecl); + + var acceptableSharedKind = 16 /* Interface */; + + interfaceSymbol = this.getExistingSymbol(interfaceDecl, 58728795 /* SomeType */, parent); + + if (interfaceSymbol) { + if (!(interfaceSymbol.kind & acceptableSharedKind)) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(interfaceAST.identifier, interfaceDecl.getDisplayName(), interfaceSymbol.getDeclarations()[0].ast()); + interfaceSymbol = null; + } else if (!this.checkThatExportsMatch(interfaceDecl, interfaceSymbol)) { + interfaceSymbol = null; + } + } + + if (!interfaceSymbol) { + interfaceSymbol = new TypeScript.PullTypeSymbol(interfaceName, 16 /* Interface */); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(interfaceSymbol, acceptableSharedKind); + } + } + + interfaceSymbol.addDeclaration(interfaceDecl); + interfaceDecl.setSymbol(interfaceSymbol); + + if (createdNewSymbol) { + if (parent) { + if (interfaceDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberType(interfaceSymbol); + } else { + parent.addEnclosedNonMemberType(interfaceSymbol); + } + } + } + + var typeParameters = interfaceDecl.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = interfaceSymbol.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + interfaceSymbol.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + for (var j = 0; j < typeParameterDecls.length; j++) { + var typeParameterDeclParent = typeParameterDecls[j].getParentDecl(); + + if (typeParameterDeclParent && typeParameterDeclParent === interfaceDecl) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + + break; + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + }; + + PullSymbolBinder.prototype.bindObjectTypeDeclarationToPullSymbol = function (objectDecl) { + var objectSymbolAST = this.semanticInfoChain.getASTForDecl(objectDecl); + + var objectSymbol = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + + objectSymbol.addDeclaration(objectDecl); + objectDecl.setSymbol(objectSymbol); + + this.semanticInfoChain.setSymbolForAST(objectSymbolAST, objectSymbol); + + var childDecls = objectDecl.getChildDecls(); + + for (var i = 0; i < childDecls.length; i++) { + this.bindDeclToPullSymbol(childDecls[i]); + } + }; + + PullSymbolBinder.prototype.bindConstructorTypeDeclarationToPullSymbol = function (constructorTypeDeclaration) { + var declKind = constructorTypeDeclaration.kind; + var declFlags = constructorTypeDeclaration.flags; + var constructorTypeAST = this.semanticInfoChain.getASTForDecl(constructorTypeDeclaration); + + var constructorTypeSymbol = new TypeScript.PullTypeSymbol("", 33554432 /* ConstructorType */); + + constructorTypeDeclaration.setSymbol(constructorTypeSymbol); + constructorTypeSymbol.addDeclaration(constructorTypeDeclaration); + this.semanticInfoChain.setSymbolForAST(constructorTypeAST, constructorTypeSymbol); + + var signature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + + var funcDecl = this.semanticInfoChain.getASTForDecl(constructorTypeDeclaration); + if (TypeScript.lastParameterIsRest(funcDecl.parameterList)) { + signature.hasVarArgs = true; + } + + signature.addDeclaration(constructorTypeDeclaration); + constructorTypeDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList), constructorTypeSymbol, signature); + + var typeParameters = constructorTypeDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = constructorTypeSymbol.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.name]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + constructorTypeSymbol.appendConstructSignature(signature); + }; + + PullSymbolBinder.prototype.bindVariableDeclarationToPullSymbol = function (variableDeclaration) { + var declFlags = variableDeclaration.flags; + var declKind = variableDeclaration.kind; + var varDeclAST = this.semanticInfoChain.getASTForDecl(variableDeclaration); + var nameAST = varDeclAST.kind() === 131 /* ClassDeclaration */ ? varDeclAST.identifier : varDeclAST.kind() === 225 /* VariableDeclarator */ ? varDeclAST.propertyName : varDeclAST.kind() === 132 /* EnumDeclaration */ ? varDeclAST.identifier : varDeclAST; + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var variableSymbol = null; + + var declName = variableDeclaration.name; + + var parentHadSymbol = false; + + var parent = this.getParent(variableDeclaration, true); + + var parentDecl = variableDeclaration.getParentDecl(); + + var isImplicit = (declFlags & 118784 /* ImplicitVariable */) !== 0; + var isModuleValue = (declFlags & (32768 /* InitializedModule */)) !== 0; + var isEnumValue = (declFlags & 4096 /* Enum */) !== 0; + var isClassConstructorVariable = (declFlags & 16384 /* ClassConstructorVariable */) !== 0; + variableSymbol = this.getExistingSymbol(variableDeclaration, 68147712 /* SomeValue */, parent); + + if (!variableSymbol && isModuleValue) { + variableSymbol = this.findExistingVariableSymbolForModuleValueDecl(variableDeclaration.getContainerDecl()); + } + + if (variableSymbol && !variableSymbol.isType()) { + parentHadSymbol = true; + } + + var decl; + var decls; + var ast; + var members; + + if (variableSymbol) { + var prevKind = variableSymbol.kind; + var prevIsEnum = variableSymbol.anyDeclHasFlag(4096 /* Enum */); + var prevIsClassConstructorVariable = variableSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */); + var prevIsModuleValue = variableSymbol.allDeclsHaveFlag(32768 /* InitializedModule */); + var prevIsImplicit = variableSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */); + var prevIsFunction = TypeScript.ArrayUtilities.any(variableSymbol.getDeclarations(), function (decl) { + return decl.kind === 16384 /* Function */; + }); + var prevIsAmbient = variableSymbol.allDeclsHaveFlag(8 /* Ambient */); + var isAmbientOrPrevIsAmbient = prevIsAmbient || (variableDeclaration.flags & 8 /* Ambient */) !== 0; + var prevDecl = variableSymbol.getDeclarations()[0]; + var prevParentDecl = prevDecl.getParentDecl(); + var bothAreGlobal = parentDecl && (parentDecl.kind === 1 /* Script */) && (prevParentDecl.kind === 1 /* Script */); + var shareParent = bothAreGlobal || prevDecl.getParentDecl() === variableDeclaration.getParentDecl(); + var prevIsParam = shareParent && prevKind === 2048 /* Parameter */ && declKind == 512 /* Variable */; + + var acceptableRedeclaration = prevIsParam || (isImplicit && ((!isEnumValue && !isClassConstructorVariable && prevIsFunction) || ((isModuleValue || isEnumValue) && (prevIsModuleValue || prevIsEnum)) || (isClassConstructorVariable && prevIsModuleValue && isAmbientOrPrevIsAmbient) || (isModuleValue && prevIsClassConstructorVariable))); + + if (acceptableRedeclaration && (prevIsClassConstructorVariable || prevIsFunction) && !isAmbientOrPrevIsAmbient) { + if (prevDecl.fileName() !== variableDeclaration.fileName()) { + this.semanticInfoChain.addDiagnostic(TypeScript.PullHelpers.diagnosticFromDecl(variableDeclaration, TypeScript.DiagnosticCode.Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2, [declName, declName, prevDecl.fileName()])); + variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); + } + } + + if (!acceptableRedeclaration || prevIsParam) { + if (!prevIsParam && (isImplicit || prevIsImplicit || TypeScript.hasFlag(prevKind, 1032192 /* SomeFunction */)) || !shareParent) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(nameAST, variableDeclaration.getDisplayName(), variableSymbol.getDeclarations()[0].ast()); + variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); + } else { + this.checkThatExportsMatch(variableDeclaration, variableSymbol); + variableSymbol = null; + parentHadSymbol = false; + } + } + + if (variableSymbol && !(variableSymbol.type && variableSymbol.type.isError()) && !this.checkThatExportsMatch(variableDeclaration, variableSymbol, !(isModuleValue && prevIsModuleValue))) { + variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); + } + } + + if ((declFlags & 118784 /* ImplicitVariable */) === 0) { + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + if (!parent && parentDecl.kind === 1 /* Script */) { + this.semanticInfoChain.cacheGlobalSymbol(variableSymbol, declKind); + } + } + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + this.semanticInfoChain.setSymbolForAST(nameAST, variableSymbol); + this.semanticInfoChain.setSymbolForAST(varDeclAST, variableSymbol); + } else if (!parentHadSymbol) { + if (isClassConstructorVariable) { + var classTypeSymbol = variableSymbol; + + if (parent) { + members = parent.getMembers(); + + for (var i = 0; i < members.length; i++) { + if ((members[i].name === declName) && (members[i].kind === 8 /* Class */)) { + classTypeSymbol = members[i]; + break; + } + } + } + + if (!classTypeSymbol) { + var containerDecl = variableDeclaration.getContainerDecl(); + classTypeSymbol = containerDecl.getSymbol(); + if (!classTypeSymbol) { + classTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 58728795 /* SomeType */, variableDeclaration); + } + } + + if (classTypeSymbol && (classTypeSymbol.kind !== 8 /* Class */)) { + classTypeSymbol = null; + } + + if (classTypeSymbol && classTypeSymbol.isClass()) { + variableSymbol = classTypeSymbol.getConstructorMethod(); + variableDeclaration.setSymbol(variableSymbol); + + decls = classTypeSymbol.getDeclarations(); + + if (decls.length) { + decl = decls[decls.length - 1]; + ast = this.semanticInfoChain.getASTForDecl(decl); + } + } else { + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + } + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + variableSymbol.type = this.semanticInfoChain.anyTypeSymbol; + } + } else if (declFlags & 102400 /* SomeInitializedModule */) { + var moduleContainerTypeSymbol = null; + var moduleParent = this.getParent(variableDeclaration); + + if (moduleParent) { + members = moduleParent.getMembers(); + + for (var i = 0; i < members.length; i++) { + if ((members[i].name === declName) && (members[i].isContainer())) { + moduleContainerTypeSymbol = members[i]; + break; + } + } + } + + if (!moduleContainerTypeSymbol) { + var containerDecl = variableDeclaration.getContainerDecl(); + moduleContainerTypeSymbol = containerDecl.getSymbol(); + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 164 /* SomeContainer */, variableDeclaration); + + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 64 /* Enum */, variableDeclaration); + } + } + } + + if (moduleContainerTypeSymbol && (!moduleContainerTypeSymbol.isContainer())) { + moduleContainerTypeSymbol = null; + } + + if (moduleContainerTypeSymbol) { + variableSymbol = moduleContainerTypeSymbol.getInstanceSymbol(); + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + variableSymbol.type = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + } + + if (!variableSymbol.hasDeclaration(variableDeclaration)) { + variableSymbol.addDeclaration(variableDeclaration); + } + variableDeclaration.setSymbol(variableSymbol); + } else { + TypeScript.Debug.assert(false, "Attempted to bind invalid implicit variable symbol"); + } + } + } else { + if (!variableSymbol.hasDeclaration(variableDeclaration)) { + variableSymbol.addDeclaration(variableDeclaration); + } + variableDeclaration.setSymbol(variableSymbol); + } + + var containerDecl = variableDeclaration.getContainerDecl(); + if (variableSymbol && variableSymbol.type && containerDecl && !variableSymbol.type.hasDeclaration(containerDecl)) { + variableSymbol.type.addDeclaration(containerDecl); + } + + if (parent && !parentHadSymbol) { + if (declFlags & 1 /* Exported */) { + parent.addMember(variableSymbol); + } else { + parent.addEnclosedNonMember(variableSymbol); + } + } + }; + + PullSymbolBinder.prototype.bindCatchVariableToPullSymbol = function (variableDeclaration) { + var declFlags = variableDeclaration.flags; + var declKind = variableDeclaration.kind; + var identifier = this.semanticInfoChain.getASTForDecl(variableDeclaration); + + var declName = variableDeclaration.name; + + var variableSymbol = new TypeScript.PullSymbol(declName, declKind); + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + variableSymbol.type = this.semanticInfoChain.anyTypeSymbol; + + this.semanticInfoChain.setSymbolForAST(identifier, variableSymbol); + }; + + PullSymbolBinder.prototype.bindEnumMemberDeclarationToPullSymbol = function (propertyDeclaration) { + var declFlags = propertyDeclaration.flags; + var declKind = propertyDeclaration.kind; + var propDeclAST = this.semanticInfoChain.getASTForDecl(propertyDeclaration); + + var declName = propertyDeclaration.name; + + var parentHadSymbol = false; + + var parent = this.getParent(propertyDeclaration, true); + + var propertySymbol = parent.findMember(declName, false); + + if (propertySymbol) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(propDeclAST.propertyName, propertyDeclaration.getDisplayName(), propertySymbol.getDeclarations()[0].ast()); + } + + if (propertySymbol) { + parentHadSymbol = true; + } + + if (!parentHadSymbol) { + propertySymbol = new TypeScript.PullSymbol(declName, declKind); + } + + propertySymbol.addDeclaration(propertyDeclaration); + propertyDeclaration.setSymbol(propertySymbol); + + this.semanticInfoChain.setSymbolForAST(propDeclAST.propertyName, propertySymbol); + this.semanticInfoChain.setSymbolForAST(propDeclAST, propertySymbol); + + if (parent && !parentHadSymbol) { + parent.addMember(propertySymbol); + } + }; + + PullSymbolBinder.prototype.bindPropertyDeclarationToPullSymbol = function (propertyDeclaration) { + var declFlags = propertyDeclaration.flags; + var declKind = propertyDeclaration.kind; + + var ast = this.semanticInfoChain.getASTForDecl(propertyDeclaration); + var astName = ast.kind() === 136 /* MemberVariableDeclaration */ ? ast.variableDeclarator.propertyName : ast.kind() === 141 /* PropertySignature */ ? ast.propertyName : ast.kind() === 242 /* Parameter */ ? ast.identifier : ast.propertyName; + + var isStatic = false; + var isOptional = false; + + var propertySymbol = null; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + if (TypeScript.hasFlag(declFlags, 128 /* Optional */)) { + isOptional = true; + } + + var declName = propertyDeclaration.name; + + var parentHadSymbol = false; + + var parent = this.getParent(propertyDeclaration, true); + + if (parent.isClass() && isStatic) { + parent = parent.getConstructorMethod().type; + } + + propertySymbol = parent.findMember(declName, false); + + if (propertySymbol) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(astName, propertyDeclaration.getDisplayName(), propertySymbol.getDeclarations()[0].ast()); + } + + if (propertySymbol) { + parentHadSymbol = true; + } + + var classTypeSymbol; + + if (!parentHadSymbol) { + propertySymbol = new TypeScript.PullSymbol(declName, declKind); + } + + propertySymbol.addDeclaration(propertyDeclaration); + propertyDeclaration.setSymbol(propertySymbol); + + this.semanticInfoChain.setSymbolForAST(astName, propertySymbol); + this.semanticInfoChain.setSymbolForAST(ast, propertySymbol); + + if (isOptional) { + propertySymbol.isOptional = true; + } + + if (parent && !parentHadSymbol) { + parent.addMember(propertySymbol); + } + }; + + PullSymbolBinder.prototype.bindParameterSymbols = function (functionDeclaration, parameterList, funcType, signatureSymbol) { + var parameters = []; + var params = TypeScript.createIntrinsicsObject(); + var funcDecl = this.semanticInfoChain.getDeclForAST(functionDeclaration); + + if (parameterList) { + for (var i = 0, n = parameterList.length; i < n; i++) { + var argDecl = parameterList.astAt(i); + var id = parameterList.identifierAt(i); + var decl = this.semanticInfoChain.getDeclForAST(argDecl); + var isProperty = TypeScript.hasFlag(decl.flags, 8388608 /* PropertyParameter */); + var parameterSymbol = new TypeScript.PullSymbol(id.valueText(), 2048 /* Parameter */); + + if ((i === (n - 1)) && parameterList.lastParameterIsRest()) { + parameterSymbol.isVarArg = true; + } + + if (params[id.valueText()]) { + this.semanticInfoChain.addDiagnosticFromAST(argDecl, TypeScript.DiagnosticCode.Duplicate_identifier_0, [id.text()]); + } else { + params[id.valueText()] = true; + } + + if (decl) { + var isParameterOptional = false; + + if (isProperty) { + decl.ensureSymbolIsBound(); + var valDecl = decl.getValueDecl(); + + if (valDecl) { + isParameterOptional = TypeScript.hasFlag(valDecl.flags, 128 /* Optional */); + + valDecl.setSymbol(parameterSymbol); + parameterSymbol.addDeclaration(valDecl); + } + } else { + isParameterOptional = TypeScript.hasFlag(decl.flags, 128 /* Optional */); + + parameterSymbol.addDeclaration(decl); + decl.setSymbol(parameterSymbol); + } + + parameterSymbol.isOptional = isParameterOptional; + } + + signatureSymbol.addParameter(parameterSymbol, parameterSymbol.isOptional); + + if (signatureSymbol.isDefinition()) { + funcType.addEnclosedNonMember(parameterSymbol); + } + } + } + }; + + PullSymbolBinder.prototype.bindFunctionDeclarationToPullSymbol = function (functionDeclaration) { + var declKind = functionDeclaration.kind; + var declFlags = functionDeclaration.flags; + var funcDeclAST = this.semanticInfoChain.getASTForDecl(functionDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = functionDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(functionDeclaration, true); + + var parentDecl = functionDeclaration.getParentDecl(); + var parentHadSymbol = false; + + var functionSymbol = null; + var functionTypeSymbol = null; + + functionSymbol = this.getExistingSymbol(functionDeclaration, 68147712 /* SomeValue */, parent); + + if (functionSymbol) { + var acceptableRedeclaration; + + if (functionSymbol.kind === 16384 /* Function */) { + acceptableRedeclaration = isSignature || functionSymbol.allDeclsHaveFlag(2048 /* Signature */); + } else { + var isCurrentDeclAmbient = TypeScript.hasFlag(functionDeclaration.flags, 8 /* Ambient */); + acceptableRedeclaration = TypeScript.ArrayUtilities.all(functionSymbol.getDeclarations(), function (decl) { + var isInitializedModuleOrAmbientDecl = TypeScript.hasFlag(decl.flags, 32768 /* InitializedModule */) && (isCurrentDeclAmbient || TypeScript.hasFlag(decl.flags, 8 /* Ambient */)); + var isSignature = TypeScript.hasFlag(decl.flags, 2048 /* Signature */); + return isInitializedModuleOrAmbientDecl || isSignature; + }); + } + + if (!acceptableRedeclaration) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.identifier, functionDeclaration.getDisplayName(), functionSymbol.getDeclarations()[0].ast()); + functionSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(funcName); + } + } + + if (functionSymbol) { + functionTypeSymbol = functionSymbol.type; + parentHadSymbol = true; + } + + if (!functionSymbol) { + functionSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + } + + if (!functionTypeSymbol) { + functionTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + functionSymbol.type = functionTypeSymbol; + functionTypeSymbol.setFunctionSymbol(functionSymbol); + } + + functionDeclaration.setSymbol(functionSymbol); + functionSymbol.addDeclaration(functionDeclaration); + functionTypeSymbol.addDeclaration(functionDeclaration); + + this.semanticInfoChain.setSymbolForAST(funcDeclAST.identifier, functionSymbol); + this.semanticInfoChain.setSymbolForAST(funcDeclAST, functionSymbol); + + if (parent && !parentHadSymbol) { + if (isExported) { + parent.addMember(functionSymbol); + } else { + parent.addEnclosedNonMember(functionSymbol); + } + } + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + signature.addDeclaration(functionDeclaration); + functionDeclaration.setSignatureSymbol(signature); + + if (TypeScript.lastParameterIsRest(funcDeclAST.callSignature.parameterList)) { + signature.hasVarArgs = true; + } + + var funcDecl = this.semanticInfoChain.getASTForDecl(functionDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), functionTypeSymbol, signature); + + var typeParameters = functionDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.name]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + functionTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindFunctionExpressionToPullSymbol = function (functionExpressionDeclaration) { + var declKind = functionExpressionDeclaration.kind; + var declFlags = functionExpressionDeclaration.flags; + var ast = this.semanticInfoChain.getASTForDecl(functionExpressionDeclaration); + + var parameters = ast.kind() === 219 /* SimpleArrowFunctionExpression */ ? TypeScript.ASTHelpers.parametersFromIdentifier(ast.identifier) : TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(ast)); + var funcExpAST = ast; + + var functionName = declKind === 131072 /* FunctionExpression */ ? functionExpressionDeclaration.getFunctionExpressionName() : functionExpressionDeclaration.name; + var functionSymbol = new TypeScript.PullSymbol(functionName, declKind); + var functionTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + functionTypeSymbol.setFunctionSymbol(functionSymbol); + + functionSymbol.type = functionTypeSymbol; + + functionExpressionDeclaration.setSymbol(functionSymbol); + functionSymbol.addDeclaration(functionExpressionDeclaration); + functionTypeSymbol.addDeclaration(functionExpressionDeclaration); + + var name = funcExpAST.kind() === 222 /* FunctionExpression */ ? funcExpAST.identifier : funcExpAST.kind() === 241 /* FunctionPropertyAssignment */ ? funcExpAST.propertyName : null; + if (name) { + this.semanticInfoChain.setSymbolForAST(name, functionSymbol); + } + + this.semanticInfoChain.setSymbolForAST(funcExpAST, functionSymbol); + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, true); + + if (parameters.lastParameterIsRest()) { + signature.hasVarArgs = true; + } + + var typeParameters = functionExpressionDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(functionExpressionDeclaration); + functionExpressionDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcExpAST, parameters, functionTypeSymbol, signature); + + functionTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindFunctionTypeDeclarationToPullSymbol = function (functionTypeDeclaration) { + var declKind = functionTypeDeclaration.kind; + var declFlags = functionTypeDeclaration.flags; + var funcTypeAST = this.semanticInfoChain.getASTForDecl(functionTypeDeclaration); + + var functionTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + + functionTypeDeclaration.setSymbol(functionTypeSymbol); + functionTypeSymbol.addDeclaration(functionTypeDeclaration); + this.semanticInfoChain.setSymbolForAST(funcTypeAST, functionTypeSymbol); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + if (TypeScript.lastParameterIsRest(funcTypeAST.parameterList)) { + signature.hasVarArgs = true; + } + + var typeParameters = functionTypeDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.name]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(functionTypeDeclaration); + functionTypeDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcTypeAST, TypeScript.ASTHelpers.parametersFromParameterList(funcTypeAST.parameterList), functionTypeSymbol, signature); + + functionTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindMethodDeclarationToPullSymbol = function (methodDeclaration) { + var declKind = methodDeclaration.kind; + var declFlags = methodDeclaration.flags; + var methodAST = this.semanticInfoChain.getASTForDecl(methodDeclaration); + + var isPrivate = (declFlags & 2 /* Private */) !== 0; + var isStatic = (declFlags & 16 /* Static */) !== 0; + var isOptional = (declFlags & 128 /* Optional */) !== 0; + + var methodName = methodDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(methodDeclaration, true); + var parentHadSymbol = false; + + var methodSymbol = null; + var methodTypeSymbol = null; + + if (parent.isClass() && isStatic) { + parent = parent.getConstructorMethod().type; + } + + methodSymbol = parent.findMember(methodName, false); + + if (methodSymbol && (methodSymbol.kind !== 65536 /* Method */ || (!isSignature && !methodSymbol.allDeclsHaveFlag(2048 /* Signature */)))) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(methodAST, methodDeclaration.getDisplayName(), methodSymbol.getDeclarations()[0].ast()); + methodSymbol = null; + } + + if (methodSymbol) { + methodTypeSymbol = methodSymbol.type; + parentHadSymbol = true; + } + + if (!methodSymbol) { + methodSymbol = new TypeScript.PullSymbol(methodName, 65536 /* Method */); + } + + if (!methodTypeSymbol) { + methodTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + methodSymbol.type = methodTypeSymbol; + methodTypeSymbol.setFunctionSymbol(methodSymbol); + } + + methodDeclaration.setSymbol(methodSymbol); + methodSymbol.addDeclaration(methodDeclaration); + methodTypeSymbol.addDeclaration(methodDeclaration); + + var nameAST = methodAST.kind() === 135 /* MemberFunctionDeclaration */ ? methodAST.propertyName : methodAST.propertyName; + + TypeScript.Debug.assert(nameAST); + + this.semanticInfoChain.setSymbolForAST(nameAST, methodSymbol); + this.semanticInfoChain.setSymbolForAST(methodAST, methodSymbol); + + if (isOptional) { + methodSymbol.isOptional = true; + } + + if (!parentHadSymbol) { + parent.addMember(methodSymbol); + } + + var sigKind = 1048576 /* CallSignature */; + + var signature = new TypeScript.PullSignatureSymbol(sigKind, !isSignature); + + var parameterList = TypeScript.ASTHelpers.getParameterList(methodAST); + if (TypeScript.lastParameterIsRest(parameterList)) { + signature.hasVarArgs = true; + } + + var typeParameters = methodDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterName; + var typeParameterAST; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameterName = typeParameters[i].name; + typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameters[i]); + + typeParameter = signature.findTypeParameter(typeParameterName); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameterName); + signature.addTypeParameter(typeParameter); + } else { + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(methodDeclaration); + methodDeclaration.setSignatureSymbol(signature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(methodDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(funcDecl)), methodTypeSymbol, signature); + + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(signature, methodTypeSymbol.getOwnCallSignatures()); + methodTypeSymbol.insertCallSignatureAtIndex(signature, signatureIndex); + }; + + PullSymbolBinder.prototype.bindStaticPrototypePropertyOfClass = function (classAST, classTypeSymbol, constructorTypeSymbol) { + var prototypeStr = "prototype"; + + var prototypeSymbol = constructorTypeSymbol.findMember(prototypeStr, false); + if (prototypeSymbol && !prototypeSymbol.getIsSynthesized()) { + this.semanticInfoChain.addDiagnostic(TypeScript.PullHelpers.diagnosticFromDecl(prototypeSymbol.getDeclarations()[0], TypeScript.DiagnosticCode.Duplicate_identifier_0, [prototypeSymbol.getDisplayName()])); + } + + if (!prototypeSymbol || !prototypeSymbol.getIsSynthesized()) { + var prototypeDecl = new TypeScript.PullSynthesizedDecl(prototypeStr, prototypeStr, 4096 /* Property */, 4 /* Public */ | 16 /* Static */, constructorTypeSymbol.getDeclarations()[0], this.semanticInfoChain); + + prototypeSymbol = new TypeScript.PullSymbol(prototypeStr, 4096 /* Property */); + prototypeSymbol.setIsSynthesized(); + prototypeSymbol.addDeclaration(prototypeDecl); + prototypeSymbol.type = classTypeSymbol; + constructorTypeSymbol.addMember(prototypeSymbol); + + if (prototypeSymbol.type && prototypeSymbol.type.isGeneric()) { + var resolver = this.semanticInfoChain.getResolver(); + prototypeSymbol.type = resolver.instantiateTypeToAny(prototypeSymbol.type, new TypeScript.PullTypeResolutionContext(resolver)); + } + prototypeSymbol.setResolved(); + } + }; + + PullSymbolBinder.prototype.bindConstructorDeclarationToPullSymbol = function (constructorDeclaration) { + var declKind = constructorDeclaration.kind; + var declFlags = constructorDeclaration.flags; + var constructorAST = this.semanticInfoChain.getASTForDecl(constructorDeclaration); + + var constructorName = constructorDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(constructorDeclaration, true); + + var parentHadSymbol = false; + + var constructorSymbol = parent.getConstructorMethod(); + var constructorTypeSymbol = null; + + if (constructorSymbol && (constructorSymbol.kind !== 32768 /* ConstructorMethod */ || (!isSignature && constructorSymbol.type && constructorSymbol.type.hasOwnConstructSignatures()))) { + var hasDefinitionSignature = false; + var constructorSigs = constructorSymbol.type.getOwnDeclaredConstructSignatures(); + + for (var i = 0; i < constructorSigs.length; i++) { + if (!constructorSigs[i].anyDeclHasFlag(2048 /* Signature */)) { + hasDefinitionSignature = true; + break; + } + } + + if (hasDefinitionSignature) { + this.semanticInfoChain.addDiagnosticFromAST(constructorAST, TypeScript.DiagnosticCode.Multiple_constructor_implementations_are_not_allowed); + + constructorSymbol = null; + } + } + + if (constructorSymbol) { + constructorTypeSymbol = constructorSymbol.type; + } else { + constructorSymbol = new TypeScript.PullSymbol(constructorName, 32768 /* ConstructorMethod */); + constructorTypeSymbol = new TypeScript.PullTypeSymbol("", 33554432 /* ConstructorType */); + } + + parent.setConstructorMethod(constructorSymbol); + constructorSymbol.type = constructorTypeSymbol; + + constructorDeclaration.setSymbol(constructorSymbol); + constructorSymbol.addDeclaration(constructorDeclaration); + constructorTypeSymbol.addDeclaration(constructorDeclaration); + constructorSymbol.setIsSynthesized(false); + this.semanticInfoChain.setSymbolForAST(constructorAST, constructorSymbol); + + var constructSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */, !isSignature); + constructSignature.returnType = parent; + constructSignature.addTypeParametersFromReturnType(); + + constructSignature.addDeclaration(constructorDeclaration); + constructorDeclaration.setSignatureSymbol(constructSignature); + + this.bindParameterSymbols(constructorAST, TypeScript.ASTHelpers.parametersFromParameterList(constructorAST.callSignature.parameterList), constructorTypeSymbol, constructSignature); + + if (TypeScript.lastParameterIsRest(constructorAST.callSignature.parameterList)) { + constructSignature.hasVarArgs = true; + } + + constructorTypeSymbol.appendConstructSignature(constructSignature); + }; + + PullSymbolBinder.prototype.bindConstructSignatureDeclarationToPullSymbol = function (constructSignatureDeclaration) { + var parent = this.getParent(constructSignatureDeclaration, true); + var constructorAST = this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration); + + var constructSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + + if (TypeScript.lastParameterIsRest(constructorAST.callSignature.parameterList)) { + constructSignature.hasVarArgs = true; + } + + var typeParameters = constructSignatureDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = constructSignature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + constructSignature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + constructSignature.addDeclaration(constructSignatureDeclaration); + constructSignatureDeclaration.setSignatureSymbol(constructSignature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(funcDecl)), null, constructSignature); + + this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration), constructSignature); + + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(constructSignature, parent.getOwnDeclaredConstructSignatures()); + parent.insertConstructSignatureAtIndex(constructSignature, signatureIndex); + }; + + PullSymbolBinder.prototype.bindCallSignatureDeclarationToPullSymbol = function (callSignatureDeclaration) { + var parent = this.getParent(callSignatureDeclaration, true); + var callSignatureAST = this.semanticInfoChain.getASTForDecl(callSignatureDeclaration); + + var callSignature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */); + + if (TypeScript.lastParameterIsRest(callSignatureAST.parameterList)) { + callSignature.hasVarArgs = true; + } + + var typeParameters = callSignatureDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = callSignature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + callSignature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + callSignature.addDeclaration(callSignatureDeclaration); + callSignatureDeclaration.setSignatureSymbol(callSignature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(callSignatureDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList), null, callSignature); + + this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(callSignatureDeclaration), callSignature); + + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(callSignature, parent.getOwnCallSignatures()); + parent.insertCallSignatureAtIndex(callSignature, signatureIndex); + }; + + PullSymbolBinder.prototype.bindIndexSignatureDeclarationToPullSymbol = function (indexSignatureDeclaration) { + var indexSignature = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + + indexSignature.addDeclaration(indexSignatureDeclaration); + indexSignatureDeclaration.setSignatureSymbol(indexSignature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(indexSignatureDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameter(funcDecl.parameter), null, indexSignature); + + this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(indexSignatureDeclaration), indexSignature); + + var parent = this.getParent(indexSignatureDeclaration); + parent.addIndexSignature(indexSignature); + indexSignature.setContainer(parent); + }; + + PullSymbolBinder.prototype.bindGetAccessorDeclarationToPullSymbol = function (getAccessorDeclaration) { + var declKind = getAccessorDeclaration.kind; + var declFlags = getAccessorDeclaration.flags; + var funcDeclAST = this.semanticInfoChain.getASTForDecl(getAccessorDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = getAccessorDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var isStatic = false; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + var parent = this.getParent(getAccessorDeclaration, true); + var parentHadSymbol = false; + + var accessorSymbol = null; + var getterSymbol = null; + var getterTypeSymbol = null; + + if (isStatic) { + parent = parent.getConstructorMethod().type; + } + + accessorSymbol = parent.findMember(funcName, false); + + if (accessorSymbol) { + if (!accessorSymbol.isAccessor()) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.propertyName, getAccessorDeclaration.getDisplayName(), accessorSymbol.getDeclarations()[0].ast()); + accessorSymbol = null; + } else { + getterSymbol = accessorSymbol.getGetter(); + + if (getterSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Getter_0_already_declared, [getAccessorDeclaration.getDisplayName()]); + accessorSymbol = null; + getterSymbol = null; + } + } + } + + if (accessorSymbol) { + parentHadSymbol = true; + } + + if (accessorSymbol && getterSymbol) { + getterTypeSymbol = getterSymbol.type; + } + + if (!accessorSymbol) { + accessorSymbol = new TypeScript.PullAccessorSymbol(funcName); + } + + if (!getterSymbol) { + getterSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + getterTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + getterTypeSymbol.setFunctionSymbol(getterSymbol); + + getterSymbol.type = getterTypeSymbol; + + accessorSymbol.setGetter(getterSymbol); + } + + getAccessorDeclaration.setSymbol(accessorSymbol); + accessorSymbol.addDeclaration(getAccessorDeclaration); + getterSymbol.addDeclaration(getAccessorDeclaration); + + var nameAST = funcDeclAST.propertyName; + this.semanticInfoChain.setSymbolForAST(nameAST, accessorSymbol); + this.semanticInfoChain.setSymbolForAST(funcDeclAST, getterSymbol); + + if (!parentHadSymbol) { + parent.addMember(accessorSymbol); + } + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + signature.addDeclaration(getAccessorDeclaration); + getAccessorDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcDeclAST, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), getterTypeSymbol, signature); + + getterTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindSetAccessorDeclarationToPullSymbol = function (setAccessorDeclaration) { + var declKind = setAccessorDeclaration.kind; + var declFlags = setAccessorDeclaration.flags; + var funcDeclAST = this.semanticInfoChain.getASTForDecl(setAccessorDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = setAccessorDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var isStatic = false; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + var parent = this.getParent(setAccessorDeclaration, true); + var parentHadSymbol = false; + + var accessorSymbol = null; + var setterSymbol = null; + var setterTypeSymbol = null; + + if (isStatic) { + parent = parent.getConstructorMethod().type; + } + + accessorSymbol = parent.findMember(funcName, false); + + if (accessorSymbol) { + if (!accessorSymbol.isAccessor()) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.propertyName, setAccessorDeclaration.getDisplayName(), accessorSymbol.getDeclarations()[0].ast()); + accessorSymbol = null; + } else { + setterSymbol = accessorSymbol.getSetter(); + + if (setterSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Setter_0_already_declared, [setAccessorDeclaration.getDisplayName()]); + accessorSymbol = null; + setterSymbol = null; + } + } + } + + if (accessorSymbol) { + parentHadSymbol = true; + + if (setterSymbol) { + setterTypeSymbol = setterSymbol.type; + } + } + + if (!accessorSymbol) { + accessorSymbol = new TypeScript.PullAccessorSymbol(funcName); + } + + if (!setterSymbol) { + setterSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + setterTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + setterTypeSymbol.setFunctionSymbol(setterSymbol); + + setterSymbol.type = setterTypeSymbol; + + accessorSymbol.setSetter(setterSymbol); + } + + setAccessorDeclaration.setSymbol(accessorSymbol); + accessorSymbol.addDeclaration(setAccessorDeclaration); + setterSymbol.addDeclaration(setAccessorDeclaration); + + var nameAST = funcDeclAST.propertyName; + this.semanticInfoChain.setSymbolForAST(nameAST, accessorSymbol); + this.semanticInfoChain.setSymbolForAST(funcDeclAST, setterSymbol); + + if (!parentHadSymbol) { + parent.addMember(accessorSymbol); + } + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + signature.addDeclaration(setAccessorDeclaration); + setAccessorDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcDeclAST, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), setterTypeSymbol, signature); + + setterTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.getDeclsToBind = function (decl) { + var decls; + switch (decl.kind) { + case 64 /* Enum */: + case 32 /* DynamicModule */: + case 4 /* Container */: + case 16 /* Interface */: + decls = this.findDeclsInContext(decl, decl.kind, true); + break; + + case 512 /* Variable */: + case 16384 /* Function */: + case 65536 /* Method */: + case 32768 /* ConstructorMethod */: + decls = this.findDeclsInContext(decl, decl.kind, false); + break; + + default: + decls = [decl]; + } + TypeScript.Debug.assert(decls && decls.length > 0); + TypeScript.Debug.assert(TypeScript.ArrayUtilities.contains(decls, decl)); + return decls; + }; + + PullSymbolBinder.prototype.shouldBindDeclaration = function (decl) { + return !decl.hasBeenBound() && this.declsBeingBound.indexOf(decl.declID) < 0; + }; + + PullSymbolBinder.prototype.bindDeclToPullSymbol = function (decl) { + if (this.shouldBindDeclaration(decl)) { + this.bindAllDeclsToPullSymbol(decl); + } + }; + + PullSymbolBinder.prototype.bindAllDeclsToPullSymbol = function (askedDecl) { + var allDecls = this.getDeclsToBind(askedDecl); + for (var i = 0; i < allDecls.length; i++) { + var decl = allDecls[i]; + + if (this.shouldBindDeclaration(decl)) { + this.bindSingleDeclToPullSymbol(decl); + } + } + }; + + PullSymbolBinder.prototype.bindSingleDeclToPullSymbol = function (decl) { + this.declsBeingBound.push(decl.declID); + + switch (decl.kind) { + case 1 /* Script */: + var childDecls = decl.getChildDecls(); + for (var i = 0; i < childDecls.length; i++) { + this.bindDeclToPullSymbol(childDecls[i]); + } + break; + + case 64 /* Enum */: + this.bindEnumDeclarationToPullSymbol(decl); + break; + + case 32 /* DynamicModule */: + case 4 /* Container */: + this.bindModuleDeclarationToPullSymbol(decl); + break; + + case 16 /* Interface */: + this.bindInterfaceDeclarationToPullSymbol(decl); + break; + + case 8 /* Class */: + this.bindClassDeclarationToPullSymbol(decl); + break; + + case 16384 /* Function */: + this.bindFunctionDeclarationToPullSymbol(decl); + break; + + case 512 /* Variable */: + this.bindVariableDeclarationToPullSymbol(decl); + break; + + case 1024 /* CatchVariable */: + this.bindCatchVariableToPullSymbol(decl); + break; + + case 67108864 /* EnumMember */: + this.bindEnumMemberDeclarationToPullSymbol(decl); + break; + + case 4096 /* Property */: + this.bindPropertyDeclarationToPullSymbol(decl); + break; + + case 65536 /* Method */: + this.bindMethodDeclarationToPullSymbol(decl); + break; + + case 32768 /* ConstructorMethod */: + this.bindConstructorDeclarationToPullSymbol(decl); + break; + + case 1048576 /* CallSignature */: + this.bindCallSignatureDeclarationToPullSymbol(decl); + break; + + case 2097152 /* ConstructSignature */: + this.bindConstructSignatureDeclarationToPullSymbol(decl); + break; + + case 4194304 /* IndexSignature */: + this.bindIndexSignatureDeclarationToPullSymbol(decl); + break; + + case 262144 /* GetAccessor */: + this.bindGetAccessorDeclarationToPullSymbol(decl); + break; + + case 524288 /* SetAccessor */: + this.bindSetAccessorDeclarationToPullSymbol(decl); + break; + + case 8388608 /* ObjectType */: + this.bindObjectTypeDeclarationToPullSymbol(decl); + break; + + case 16777216 /* FunctionType */: + this.bindFunctionTypeDeclarationToPullSymbol(decl); + break; + + case 33554432 /* ConstructorType */: + this.bindConstructorTypeDeclarationToPullSymbol(decl); + break; + + case 131072 /* FunctionExpression */: + this.bindFunctionExpressionToPullSymbol(decl); + break; + + case 128 /* TypeAlias */: + this.bindImportDeclaration(decl); + break; + + case 2048 /* Parameter */: + case 8192 /* TypeParameter */: + decl.getParentDecl().getSymbol(); + break; + + case 268435456 /* CatchBlock */: + case 134217728 /* WithBlock */: + break; + + default: + TypeScript.CompilerDiagnostics.assert(false, "Unrecognized type declaration"); + } + + TypeScript.Debug.assert(TypeScript.ArrayUtilities.last(this.declsBeingBound) === decl.declID); + this.declsBeingBound.pop(); + }; + return PullSymbolBinder; + })(); + TypeScript.PullSymbolBinder = PullSymbolBinder; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (PullHelpers) { + function diagnosticFromDecl(decl, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + var ast = decl.ast(); + return decl.semanticInfoChain.diagnosticFromAST(ast, diagnosticKey, _arguments, additionalLocations); + } + PullHelpers.diagnosticFromDecl = diagnosticFromDecl; + + function resolveDeclaredSymbolToUseType(symbol) { + if (symbol.isSignature()) { + if (!symbol.returnType) { + symbol._resolveDeclaredSymbol(); + } + } else if (!symbol.type) { + symbol._resolveDeclaredSymbol(); + } + } + PullHelpers.resolveDeclaredSymbolToUseType = resolveDeclaredSymbolToUseType; + + function getSignatureForFuncDecl(functionDecl) { + var funcDecl = functionDecl.ast(); + var funcSymbol = functionDecl.getSymbol(); + + if (!funcSymbol) { + funcSymbol = functionDecl.getSignatureSymbol(); + } + + var functionSignature = null; + var typeSymbolWithAllSignatures = null; + if (funcSymbol.isSignature()) { + functionSignature = funcSymbol; + var parent = functionDecl.getParentDecl(); + typeSymbolWithAllSignatures = parent.getSymbol().type; + } else { + functionSignature = functionDecl.getSignatureSymbol(); + typeSymbolWithAllSignatures = funcSymbol.type; + } + var signatures; + + if (funcDecl.kind() === 137 /* ConstructorDeclaration */ || functionDecl.kind === 2097152 /* ConstructSignature */) { + signatures = typeSymbolWithAllSignatures.getConstructSignatures(); + } else if (functionDecl.kind === 4194304 /* IndexSignature */) { + signatures = typeSymbolWithAllSignatures.getIndexSignatures(); + } else { + signatures = typeSymbolWithAllSignatures.getCallSignatures(); + } + + return { + signature: functionSignature, + allSignatures: signatures + }; + } + PullHelpers.getSignatureForFuncDecl = getSignatureForFuncDecl; + + function getAccessorSymbol(getterOrSetter, semanticInfoChain) { + var functionDecl = semanticInfoChain.getDeclForAST(getterOrSetter); + var getterOrSetterSymbol = functionDecl.getSymbol(); + + return getterOrSetterSymbol; + } + PullHelpers.getAccessorSymbol = getAccessorSymbol; + + function getGetterAndSetterFunction(funcDecl, semanticInfoChain) { + var accessorSymbol = PullHelpers.getAccessorSymbol(funcDecl, semanticInfoChain); + var result = { + getter: null, + setter: null + }; + var getter = accessorSymbol.getGetter(); + if (getter) { + var getterDecl = getter.getDeclarations()[0]; + result.getter = semanticInfoChain.getASTForDecl(getterDecl); + } + var setter = accessorSymbol.getSetter(); + if (setter) { + var setterDecl = setter.getDeclarations()[0]; + result.setter = semanticInfoChain.getASTForDecl(setterDecl); + } + + return result; + } + PullHelpers.getGetterAndSetterFunction = getGetterAndSetterFunction; + + function symbolIsEnum(source) { + return source && (source.kind & (64 /* Enum */ | 67108864 /* EnumMember */)) !== 0; + } + PullHelpers.symbolIsEnum = symbolIsEnum; + + function symbolIsModule(symbol) { + return symbol && (symbol.kind === 4 /* Container */ || isOneDeclarationOfKind(symbol, 4 /* Container */)); + } + PullHelpers.symbolIsModule = symbolIsModule; + + function isOneDeclarationOfKind(symbol, kind) { + var decls = symbol.getDeclarations(); + for (var i = 0; i < decls.length; i++) { + if (decls[i].kind === kind) { + return true; + } + } + + return false; + } + + function isNameNumeric(name) { + return isFinite(+name); + } + PullHelpers.isNameNumeric = isNameNumeric; + + function typeSymbolsAreIdentical(a, b) { + if (a.isTypeReference() && !a.getIsSpecialized()) { + a = a.referencedTypeSymbol; + } + + if (b.isTypeReference() && !b.getIsSpecialized()) { + b = b.referencedTypeSymbol; + } + + return a === b; + } + PullHelpers.typeSymbolsAreIdentical = typeSymbolsAreIdentical; + + function getRootType(type) { + var rootType = type.getRootSymbol(); + + while (true) { + if (type === rootType) { + return type; + } + + type = rootType; + rootType = type.getRootSymbol(); + } + } + PullHelpers.getRootType = getRootType; + + function isSymbolLocal(symbol) { + var container = symbol.getContainer(); + if (container) { + var containerKind = container.kind; + if (containerKind & (1032192 /* SomeFunction */ | 16777216 /* FunctionType */)) { + return true; + } + + if (containerKind === 33554432 /* ConstructorType */ && !symbol.anyDeclHasFlag(16 /* Static */ | 1 /* Exported */)) { + return true; + } + } + + return false; + } + PullHelpers.isSymbolLocal = isSymbolLocal; + + function isExportedSymbolInClodule(symbol) { + var container = symbol.getContainer(); + return container && container.kind === 33554432 /* ConstructorType */ && symbolIsModule(container) && symbol.anyDeclHasFlag(1 /* Exported */); + } + PullHelpers.isExportedSymbolInClodule = isExportedSymbolInClodule; + + function isSymbolDeclaredInScopeChain(symbol, scopeSymbol) { + TypeScript.Debug.assert(symbol); + var symbolDeclarationScope = symbol.getContainer(); + + while (scopeSymbol) { + if (scopeSymbol === symbolDeclarationScope) { + return true; + } + + scopeSymbol = scopeSymbol.getContainer(); + } + + if (scopeSymbol === null && symbolDeclarationScope === null) { + return true; + } + + return false; + } + PullHelpers.isSymbolDeclaredInScopeChain = isSymbolDeclaredInScopeChain; + + + + function walkSignatureSymbol(signatureSymbol, walker) { + var continueWalk = true; + var parameters = signatureSymbol.parameters; + if (parameters) { + for (var i = 0; continueWalk && i < parameters.length; i++) { + continueWalk = walker.signatureParameterWalk(parameters[i]); + } + } + + if (continueWalk) { + continueWalk = walker.signatureReturnTypeWalk(signatureSymbol.returnType); + } + + return continueWalk; + } + + function walkPullTypeSymbolStructure(typeSymbol, walker) { + var continueWalk = true; + + var members = typeSymbol.getMembers(); + for (var i = 0; continueWalk && i < members.length; i++) { + continueWalk = walker.memberSymbolWalk(members[i]); + } + + if (continueWalk) { + var callSigantures = typeSymbol.getCallSignatures(); + for (var i = 0; continueWalk && i < callSigantures.length; i++) { + continueWalk = walker.callSignatureWalk(callSigantures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(callSigantures[i], walker); + } + } + } + + if (continueWalk) { + var constructSignatures = typeSymbol.getConstructSignatures(); + for (var i = 0; continueWalk && i < constructSignatures.length; i++) { + continueWalk = walker.constructSignatureWalk(constructSignatures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(constructSignatures[i], walker); + } + } + } + + if (continueWalk) { + var indexSignatures = typeSymbol.getIndexSignatures(); + for (var i = 0; continueWalk && i < indexSignatures.length; i++) { + continueWalk = walker.indexSignatureWalk(indexSignatures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(indexSignatures[i], walker); + } + } + } + } + PullHelpers.walkPullTypeSymbolStructure = walkPullTypeSymbolStructure; + + var OtherPullDeclsWalker = (function () { + function OtherPullDeclsWalker() { + this.currentlyWalkingOtherDecls = []; + } + OtherPullDeclsWalker.prototype.walkOtherPullDecls = function (currentDecl, otherDecls, callBack) { + if (otherDecls) { + var isAlreadyWalkingOtherDecl = TypeScript.ArrayUtilities.any(this.currentlyWalkingOtherDecls, function (inWalkingOtherDecl) { + return TypeScript.ArrayUtilities.contains(otherDecls, inWalkingOtherDecl); + }); + + if (!isAlreadyWalkingOtherDecl) { + this.currentlyWalkingOtherDecls.push(currentDecl); + for (var i = 0; i < otherDecls.length; i++) { + if (otherDecls[i] !== currentDecl) { + callBack(otherDecls[i]); + } + } + var currentlyWalkingOtherDeclsDecl = this.currentlyWalkingOtherDecls.pop(); + TypeScript.Debug.assert(currentlyWalkingOtherDeclsDecl == currentDecl); + } + } + }; + return OtherPullDeclsWalker; + })(); + PullHelpers.OtherPullDeclsWalker = OtherPullDeclsWalker; + })(TypeScript.PullHelpers || (TypeScript.PullHelpers = {})); + var PullHelpers = TypeScript.PullHelpers; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var WrapsTypeParameterCache = (function () { + function WrapsTypeParameterCache() { + this._wrapsTypeParameterCache = TypeScript.BitVector.getBitVector(true); + } + WrapsTypeParameterCache.prototype.getWrapsTypeParameter = function (typeParameterArgumentMap) { + var mapHasTypeParameterNotCached = false; + for (var typeParameterID in typeParameterArgumentMap) { + if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + var cachedValue = this._wrapsTypeParameterCache.valueAt(typeParameterID); + if (cachedValue) { + return typeParameterID; + } + mapHasTypeParameterNotCached = mapHasTypeParameterNotCached || cachedValue === undefined; + } + } + + if (!mapHasTypeParameterNotCached) { + return 0; + } + + return undefined; + }; + + WrapsTypeParameterCache.prototype.setWrapsTypeParameter = function (typeParameterArgumentMap, wrappingTypeParameterID) { + if (wrappingTypeParameterID) { + this._wrapsTypeParameterCache.setValueAt(wrappingTypeParameterID, true); + } else { + for (var typeParameterID in typeParameterArgumentMap) { + if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + this._wrapsTypeParameterCache.setValueAt(typeParameterID, false); + } + } + } + }; + return WrapsTypeParameterCache; + })(); + TypeScript.WrapsTypeParameterCache = WrapsTypeParameterCache; + + (function (PullInstantiationHelpers) { + var MutableTypeArgumentMap = (function () { + function MutableTypeArgumentMap(typeParameterArgumentMap) { + this.typeParameterArgumentMap = typeParameterArgumentMap; + this.createdDuplicateTypeArgumentMap = false; + } + MutableTypeArgumentMap.prototype.ensureTypeArgumentCopy = function () { + if (!this.createdDuplicateTypeArgumentMap) { + var passedInTypeArgumentMap = this.typeParameterArgumentMap; + this.typeParameterArgumentMap = []; + for (var typeParameterID in passedInTypeArgumentMap) { + if (passedInTypeArgumentMap.hasOwnProperty(typeParameterID)) { + this.typeParameterArgumentMap[typeParameterID] = passedInTypeArgumentMap[typeParameterID]; + } + } + this.createdDuplicateTypeArgumentMap = true; + } + }; + return MutableTypeArgumentMap; + })(); + PullInstantiationHelpers.MutableTypeArgumentMap = MutableTypeArgumentMap; + + function instantiateTypeArgument(resolver, symbol, mutableTypeParameterMap) { + if (symbol.getIsSpecialized()) { + var rootTypeArgumentMap = symbol.getTypeParameterArgumentMap(); + var newTypeArgumentMap = []; + var allowedTypeParameters = symbol.getAllowedToReferenceTypeParameters(); + for (var i = 0; i < allowedTypeParameters.length; i++) { + var typeParameterID = allowedTypeParameters[i].pullSymbolID; + var typeArg = rootTypeArgumentMap[typeParameterID]; + if (typeArg) { + newTypeArgumentMap[typeParameterID] = resolver.instantiateType(typeArg, mutableTypeParameterMap.typeParameterArgumentMap); + } + } + + for (var i = 0; i < allowedTypeParameters.length; i++) { + var typeParameterID = allowedTypeParameters[i].pullSymbolID; + if (newTypeArgumentMap[typeParameterID] && mutableTypeParameterMap.typeParameterArgumentMap[typeParameterID] != newTypeArgumentMap[typeParameterID]) { + mutableTypeParameterMap.ensureTypeArgumentCopy(); + mutableTypeParameterMap.typeParameterArgumentMap[typeParameterID] = newTypeArgumentMap[typeParameterID]; + } + } + } + } + PullInstantiationHelpers.instantiateTypeArgument = instantiateTypeArgument; + + function cleanUpTypeArgumentMap(symbol, mutableTypeArgumentMap) { + var allowedToReferenceTypeParameters = symbol.getAllowedToReferenceTypeParameters(); + for (var typeParameterID in mutableTypeArgumentMap.typeParameterArgumentMap) { + if (mutableTypeArgumentMap.typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + if (!TypeScript.ArrayUtilities.any(allowedToReferenceTypeParameters, function (typeParameter) { + return typeParameter.pullSymbolID == typeParameterID; + })) { + mutableTypeArgumentMap.ensureTypeArgumentCopy(); + delete mutableTypeArgumentMap.typeParameterArgumentMap[typeParameterID]; + } + } + } + } + PullInstantiationHelpers.cleanUpTypeArgumentMap = cleanUpTypeArgumentMap; + + function getAllowedToReferenceTypeParametersFromDecl(decl) { + var allowedToReferenceTypeParameters = []; + + var allowedToUseDeclTypeParameters = false; + var getTypeParametersFromParentDecl = false; + + switch (decl.kind) { + case 65536 /* Method */: + if (TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + allowedToUseDeclTypeParameters = true; + break; + } + + case 16777216 /* FunctionType */: + case 33554432 /* ConstructorType */: + case 2097152 /* ConstructSignature */: + case 1048576 /* CallSignature */: + case 131072 /* FunctionExpression */: + case 16384 /* Function */: + allowedToUseDeclTypeParameters = true; + getTypeParametersFromParentDecl = true; + break; + + case 4096 /* Property */: + if (TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + break; + } + + case 2048 /* Parameter */: + case 262144 /* GetAccessor */: + case 524288 /* SetAccessor */: + case 32768 /* ConstructorMethod */: + case 4194304 /* IndexSignature */: + case 8388608 /* ObjectType */: + case 256 /* ObjectLiteral */: + case 8192 /* TypeParameter */: + getTypeParametersFromParentDecl = true; + break; + + case 8 /* Class */: + case 16 /* Interface */: + allowedToUseDeclTypeParameters = true; + break; + } + + if (getTypeParametersFromParentDecl) { + allowedToReferenceTypeParameters = allowedToReferenceTypeParameters.concat(getAllowedToReferenceTypeParametersFromDecl(decl.getParentDecl())); + } + + if (allowedToUseDeclTypeParameters) { + var typeParameterDecls = decl.getTypeParameters(); + for (var i = 0; i < typeParameterDecls.length; i++) { + allowedToReferenceTypeParameters.push(typeParameterDecls[i].getSymbol()); + } + } + + return allowedToReferenceTypeParameters; + } + PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl = getAllowedToReferenceTypeParametersFromDecl; + + function createTypeParameterArgumentMap(typeParameters, typeArguments) { + return updateTypeParameterArgumentMap(typeParameters, typeArguments, {}); + } + PullInstantiationHelpers.createTypeParameterArgumentMap = createTypeParameterArgumentMap; + + function updateTypeParameterArgumentMap(typeParameters, typeArguments, typeParameterArgumentMap) { + for (var i = 0; i < typeParameters.length; i++) { + typeParameterArgumentMap[typeParameters[i].getRootSymbol().pullSymbolID] = typeArguments[i]; + } + return typeParameterArgumentMap; + } + PullInstantiationHelpers.updateTypeParameterArgumentMap = updateTypeParameterArgumentMap; + + function updateMutableTypeParameterArgumentMap(typeParameters, typeArguments, mutableMap) { + for (var i = 0; i < typeParameters.length; i++) { + var typeParameterId = typeParameters[i].getRootSymbol().pullSymbolID; + if (mutableMap.typeParameterArgumentMap[typeParameterId] !== typeArguments[i]) { + mutableMap.ensureTypeArgumentCopy(); + mutableMap.typeParameterArgumentMap[typeParameterId] = typeArguments[i]; + } + } + } + PullInstantiationHelpers.updateMutableTypeParameterArgumentMap = updateMutableTypeParameterArgumentMap; + + function twoTypesAreInstantiationsOfSameNamedGenericType(type1, type2) { + var type1IsGeneric = type1.isGeneric() && type1.getTypeArguments() !== null; + var type2IsGeneric = type2.isGeneric() && type2.getTypeArguments() !== null; + + if (type1IsGeneric && type2IsGeneric) { + var type1Root = TypeScript.PullHelpers.getRootType(type1); + var type2Root = TypeScript.PullHelpers.getRootType(type2); + return type1Root === type2Root; + } + + return false; + } + PullInstantiationHelpers.twoTypesAreInstantiationsOfSameNamedGenericType = twoTypesAreInstantiationsOfSameNamedGenericType; + })(TypeScript.PullInstantiationHelpers || (TypeScript.PullInstantiationHelpers = {})); + var PullInstantiationHelpers = TypeScript.PullInstantiationHelpers; +})(TypeScript || (TypeScript = {})); +if (Error) + Error.stackTraceLimit = 1000; + +var TypeScript; +(function (TypeScript) { + TypeScript.fileResolutionTime = 0; + TypeScript.fileResolutionIOTime = 0; + TypeScript.fileResolutionScanImportsTime = 0; + TypeScript.fileResolutionImportFileSearchTime = 0; + TypeScript.fileResolutionGetDefaultLibraryTime = 0; + TypeScript.sourceCharactersCompiled = 0; + TypeScript.syntaxTreeParseTime = 0; + TypeScript.syntaxDiagnosticsTime = 0; + TypeScript.astTranslationTime = 0; + TypeScript.typeCheckTime = 0; + + TypeScript.compilerResolvePathTime = 0; + TypeScript.compilerDirectoryNameTime = 0; + TypeScript.compilerDirectoryExistsTime = 0; + TypeScript.compilerFileExistsTime = 0; + + TypeScript.emitTime = 0; + TypeScript.emitWriteFileTime = 0; + + TypeScript.declarationEmitTime = 0; + TypeScript.declarationEmitIsExternallyVisibleTime = 0; + TypeScript.declarationEmitTypeSignatureTime = 0; + TypeScript.declarationEmitGetBoundDeclTypeTime = 0; + TypeScript.declarationEmitIsOverloadedCallSignatureTime = 0; + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime = 0; + TypeScript.declarationEmitGetBaseTypeTime = 0; + TypeScript.declarationEmitGetAccessorFunctionTime = 0; + TypeScript.declarationEmitGetTypeParameterSymbolTime = 0; + TypeScript.declarationEmitGetImportDeclarationSymbolTime = 0; + + TypeScript.ioHostResolvePathTime = 0; + TypeScript.ioHostDirectoryNameTime = 0; + TypeScript.ioHostCreateDirectoryStructureTime = 0; + TypeScript.ioHostWriteFileTime = 0; + + (function (EmitOutputResult) { + EmitOutputResult[EmitOutputResult["Succeeded"] = 0] = "Succeeded"; + EmitOutputResult[EmitOutputResult["FailedBecauseOfSyntaxErrors"] = 1] = "FailedBecauseOfSyntaxErrors"; + EmitOutputResult[EmitOutputResult["FailedBecauseOfCompilerOptionsErrors"] = 2] = "FailedBecauseOfCompilerOptionsErrors"; + EmitOutputResult[EmitOutputResult["FailedToGenerateDeclarationsBecauseOfSemanticErrors"] = 3] = "FailedToGenerateDeclarationsBecauseOfSemanticErrors"; + })(TypeScript.EmitOutputResult || (TypeScript.EmitOutputResult = {})); + var EmitOutputResult = TypeScript.EmitOutputResult; + + var EmitOutput = (function () { + function EmitOutput(emitOutputResult) { + if (typeof emitOutputResult === "undefined") { emitOutputResult = 0 /* Succeeded */; } + this.outputFiles = []; + this.emitOutputResult = emitOutputResult; + } + return EmitOutput; + })(); + TypeScript.EmitOutput = EmitOutput; + + (function (OutputFileType) { + OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; + OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; + OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; + })(TypeScript.OutputFileType || (TypeScript.OutputFileType = {})); + var OutputFileType = TypeScript.OutputFileType; + + var OutputFile = (function () { + function OutputFile(name, writeByteOrderMark, text, fileType, sourceMapEntries) { + if (typeof sourceMapEntries === "undefined") { sourceMapEntries = []; } + this.name = name; + this.writeByteOrderMark = writeByteOrderMark; + this.text = text; + this.fileType = fileType; + this.sourceMapEntries = sourceMapEntries; + } + return OutputFile; + })(); + TypeScript.OutputFile = OutputFile; + + var CompileResult = (function () { + function CompileResult() { + this.diagnostics = []; + this.outputFiles = []; + } + CompileResult.fromDiagnostics = function (diagnostics) { + var result = new CompileResult(); + result.diagnostics = diagnostics; + return result; + }; + + CompileResult.fromOutputFiles = function (outputFiles) { + var result = new CompileResult(); + result.outputFiles = outputFiles; + return result; + }; + return CompileResult; + })(); + TypeScript.CompileResult = CompileResult; + + var TypeScriptCompiler = (function () { + function TypeScriptCompiler(logger, _settings) { + if (typeof logger === "undefined") { logger = new TypeScript.NullLogger(); } + if (typeof _settings === "undefined") { _settings = TypeScript.ImmutableCompilationSettings.defaultSettings(); } + this.logger = logger; + this._settings = _settings; + this.semanticInfoChain = null; + this.semanticInfoChain = new TypeScript.SemanticInfoChain(this, logger); + } + TypeScriptCompiler.prototype.compilationSettings = function () { + return this._settings; + }; + + TypeScriptCompiler.prototype.setCompilationSettings = function (newSettings) { + var oldSettings = this._settings; + this._settings = newSettings; + + if (!compareDataObjects(oldSettings, newSettings)) { + this.semanticInfoChain.invalidate(oldSettings, newSettings); + } + }; + + TypeScriptCompiler.prototype.getDocument = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + return this.semanticInfoChain.getDocument(fileName); + }; + + TypeScriptCompiler.prototype.cleanupSemanticCache = function () { + this.semanticInfoChain.invalidate(); + }; + + TypeScriptCompiler.prototype.addFile = function (fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles) { + if (typeof referencedFiles === "undefined") { referencedFiles = []; } + fileName = TypeScript.switchToForwardSlashes(fileName); + + TypeScript.sourceCharactersCompiled += scriptSnapshot.getLength(); + + var document = TypeScript.Document.create(this, this.semanticInfoChain, fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles); + + this.semanticInfoChain.addDocument(document); + }; + + TypeScriptCompiler.prototype.updateFile = function (fileName, scriptSnapshot, version, isOpen, textChangeRange) { + fileName = TypeScript.switchToForwardSlashes(fileName); + + var document = this.getDocument(fileName); + var updatedDocument = document.update(scriptSnapshot, version, isOpen, textChangeRange); + + this.semanticInfoChain.addDocument(updatedDocument); + }; + + TypeScriptCompiler.prototype.removeFile = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + this.semanticInfoChain.removeDocument(fileName); + }; + + TypeScriptCompiler.prototype.mapOutputFileName = function (document, emitOptions, extensionChanger) { + if (document.emitToOwnOutputFile()) { + var updatedFileName = document.fileName; + if (emitOptions.outputDirectory() !== "") { + updatedFileName = document.fileName.replace(emitOptions.commonDirectoryPath(), ""); + updatedFileName = emitOptions.outputDirectory() + updatedFileName; + } + return extensionChanger(updatedFileName, false); + } else { + return extensionChanger(emitOptions.sharedOutputFile(), true); + } + }; + + TypeScriptCompiler.prototype.writeByteOrderMarkForDocument = function (document) { + var printReason = false; + + if (document.emitToOwnOutputFile()) { + var result = document.byteOrderMark !== 0 /* None */; + if (printReason) { + TypeScript.Environment.standardOut.WriteLine("Emitting byte order mark because of: " + document.fileName); + } + return result; + } else { + var fileNames = this.fileNames(); + + var result = false; + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = this.getDocument(fileNames[i]); + + if (document.isExternalModule()) { + continue; + } + + if (document.byteOrderMark !== 0 /* None */) { + if (printReason) { + TypeScript.Environment.standardOut.WriteLine("Emitting byte order mark because of: " + document.fileName); + result = true; + } else { + return true; + } + } + } + + return result; + } + }; + + TypeScriptCompiler.mapToDTSFileName = function (fileName, wholeFileNameReplaced) { + return TypeScript.getDeclareFilePath(fileName); + }; + + TypeScriptCompiler.prototype._shouldEmit = function (document) { + return !document.isDeclareFile(); + }; + + TypeScriptCompiler.prototype._shouldEmitDeclarations = function (document) { + if (!this.compilationSettings().generateDeclarationFiles()) { + return false; + } + + return this._shouldEmit(document); + }; + + TypeScriptCompiler.prototype.emitDocumentDeclarationsWorker = function (document, emitOptions, declarationEmitter) { + var sourceUnit = document.sourceUnit(); + TypeScript.Debug.assert(this._shouldEmitDeclarations(document)); + + if (declarationEmitter) { + declarationEmitter.document = document; + } else { + var declareFileName = this.mapOutputFileName(document, emitOptions, TypeScriptCompiler.mapToDTSFileName); + declarationEmitter = new TypeScript.DeclarationEmitter(declareFileName, document, this, emitOptions, this.semanticInfoChain); + } + + declarationEmitter.emitDeclarations(sourceUnit); + return declarationEmitter; + }; + + TypeScriptCompiler.prototype._emitDocumentDeclarations = function (document, emitOptions, onSingleFileEmitComplete, sharedEmitter) { + if (this._shouldEmitDeclarations(document)) { + if (document.emitToOwnOutputFile()) { + var singleEmitter = this.emitDocumentDeclarationsWorker(document, emitOptions); + if (singleEmitter) { + onSingleFileEmitComplete(singleEmitter.getOutputFile()); + } + } else { + sharedEmitter = this.emitDocumentDeclarationsWorker(document, emitOptions, sharedEmitter); + } + } + + return sharedEmitter; + }; + + TypeScriptCompiler.prototype.emitAllDeclarations = function (resolvePath) { + var start = new Date().getTime(); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var sharedEmitter = null; + var fileNames = this.fileNames(); + + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + + var document = this.getDocument(fileNames[i]); + + sharedEmitter = this._emitDocumentDeclarations(document, emitOptions, function (file) { + return emitOutput.outputFiles.push(file); + }, sharedEmitter); + } + + if (sharedEmitter) { + emitOutput.outputFiles.push(sharedEmitter.getOutputFile()); + } + + TypeScript.declarationEmitTime += new Date().getTime() - start; + + return emitOutput; + }; + + TypeScriptCompiler.prototype.emitDeclarations = function (fileName, resolvePath) { + fileName = TypeScript.switchToForwardSlashes(fileName); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var document = this.getDocument(fileName); + + if (document.emitToOwnOutputFile()) { + this._emitDocumentDeclarations(document, emitOptions, function (file) { + return emitOutput.outputFiles.push(file); + }, null); + return emitOutput; + } else { + return this.emitAllDeclarations(resolvePath); + } + }; + + TypeScriptCompiler.prototype.canEmitDeclarations = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + var document = this.getDocument(fileName); + return this._shouldEmitDeclarations(document); + }; + + TypeScriptCompiler.mapToFileNameExtension = function (extension, fileName, wholeFileNameReplaced) { + if (wholeFileNameReplaced) { + return fileName; + } else { + var splitFname = fileName.split("."); + splitFname.pop(); + return splitFname.join(".") + extension; + } + }; + + TypeScriptCompiler.mapToJSFileName = function (fileName, wholeFileNameReplaced) { + return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced); + }; + + TypeScriptCompiler.prototype.emitDocumentWorker = function (document, emitOptions, emitter) { + var sourceUnit = document.sourceUnit(); + TypeScript.Debug.assert(this._shouldEmit(document)); + + var typeScriptFileName = document.fileName; + if (!emitter) { + var javaScriptFileName = this.mapOutputFileName(document, emitOptions, TypeScriptCompiler.mapToJSFileName); + var outFile = new TypeScript.TextWriter(javaScriptFileName, this.writeByteOrderMarkForDocument(document), 0 /* JavaScript */); + + emitter = new TypeScript.Emitter(javaScriptFileName, outFile, emitOptions, this.semanticInfoChain); + + if (this.compilationSettings().mapSourceFiles()) { + var sourceMapFile = new TypeScript.TextWriter(javaScriptFileName + TypeScript.SourceMapper.MapFileExtension, false, 1 /* SourceMap */); + emitter.createSourceMapper(document, javaScriptFileName, outFile, sourceMapFile, emitOptions.resolvePath); + } + } else if (this.compilationSettings().mapSourceFiles()) { + emitter.setSourceMapperNewSourceFile(document); + } + + emitter.setDocument(document); + emitter.emitJavascript(sourceUnit, false); + + return emitter; + }; + + TypeScriptCompiler.prototype._emitDocument = function (document, emitOptions, onSingleFileEmitComplete, sharedEmitter) { + if (this._shouldEmit(document)) { + if (document.emitToOwnOutputFile()) { + var singleEmitter = this.emitDocumentWorker(document, emitOptions); + if (singleEmitter) { + onSingleFileEmitComplete(singleEmitter.getOutputFiles()); + } + } else { + sharedEmitter = this.emitDocumentWorker(document, emitOptions, sharedEmitter); + } + } + + return sharedEmitter; + }; + + TypeScriptCompiler.prototype.emitAll = function (resolvePath) { + var start = new Date().getTime(); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var fileNames = this.fileNames(); + var sharedEmitter = null; + + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + + var document = this.getDocument(fileName); + + sharedEmitter = this._emitDocument(document, emitOptions, function (files) { + return emitOutput.outputFiles.push.apply(emitOutput.outputFiles, files); + }, sharedEmitter); + } + + if (sharedEmitter) { + emitOutput.outputFiles.push.apply(emitOutput.outputFiles, sharedEmitter.getOutputFiles()); + } + + TypeScript.emitTime += new Date().getTime() - start; + return emitOutput; + }; + + TypeScriptCompiler.prototype.emit = function (fileName, resolvePath) { + fileName = TypeScript.switchToForwardSlashes(fileName); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var document = this.getDocument(fileName); + + if (document.emitToOwnOutputFile()) { + this._emitDocument(document, emitOptions, function (files) { + return emitOutput.outputFiles.push.apply(emitOutput.outputFiles, files); + }, null); + return emitOutput; + } else { + return this.emitAll(resolvePath); + } + }; + + TypeScriptCompiler.prototype.compile = function (resolvePath, continueOnDiagnostics) { + if (typeof continueOnDiagnostics === "undefined") { continueOnDiagnostics = false; } + return new CompilerIterator(this, resolvePath, continueOnDiagnostics); + }; + + TypeScriptCompiler.prototype.getSyntacticDiagnostics = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + return this.getDocument(fileName).diagnostics(); + }; + + TypeScriptCompiler.prototype.getSyntaxTree = function (fileName) { + return this.getDocument(fileName).syntaxTree(); + }; + + TypeScriptCompiler.prototype.getSourceUnit = function (fileName) { + return this.getDocument(fileName).sourceUnit(); + }; + + TypeScriptCompiler.prototype.getSemanticDiagnostics = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + + var document = this.getDocument(fileName); + + var startTime = (new Date()).getTime(); + TypeScript.PullTypeResolver.typeCheck(this.compilationSettings(), this.semanticInfoChain, document); + var endTime = (new Date()).getTime(); + + TypeScript.typeCheckTime += endTime - startTime; + + var errors = this.semanticInfoChain.getDiagnostics(fileName); + + errors = TypeScript.ArrayUtilities.distinct(errors, TypeScript.Diagnostic.equals); + errors.sort(function (d1, d2) { + if (d1.fileName() < d2.fileName()) { + return -1; + } else if (d1.fileName() > d2.fileName()) { + return 1; + } + + if (d1.start() < d2.start()) { + return -1; + } else if (d1.start() > d2.start()) { + return 1; + } + + var code1 = TypeScript.diagnosticInformationMap[d1.diagnosticKey()].code; + var code2 = TypeScript.diagnosticInformationMap[d2.diagnosticKey()].code; + if (code1 < code2) { + return -1; + } else if (code1 > code2) { + return 1; + } + + return 0; + }); + + return errors; + }; + + TypeScriptCompiler.prototype.getCompilerOptionsDiagnostics = function (resolvePath) { + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + var emitDiagnostic = emitOptions.diagnostic(); + if (emitDiagnostic) { + return [emitDiagnostic]; + } + return TypeScript.sentinelEmptyArray; + }; + + TypeScriptCompiler.prototype.resolveAllFiles = function () { + var fileNames = this.fileNames(); + for (var i = 0, n = fileNames.length; i < n; i++) { + this.getSemanticDiagnostics(fileNames[i]); + } + }; + + TypeScriptCompiler.prototype.getSymbolOfDeclaration = function (decl) { + if (!decl) { + return null; + } + + var resolver = this.semanticInfoChain.getResolver(); + var ast = this.semanticInfoChain.getASTForDecl(decl); + if (!ast) { + return null; + } + + var enclosingDecl = resolver.getEnclosingDecl(decl); + if (ast.kind() === 139 /* GetAccessor */ || ast.kind() === 140 /* SetAccessor */) { + return this.getSymbolOfDeclaration(enclosingDecl); + } + + return resolver.resolveAST(ast, false, new TypeScript.PullTypeResolutionContext(resolver)); + }; + + TypeScriptCompiler.prototype.extractResolutionContextFromAST = function (resolver, ast, document, propagateContextualTypes) { + var scriptName = document.fileName; + + var enclosingDecl = null; + var enclosingDeclAST = null; + var inContextuallyTypedAssignment = false; + var inWithBlock = false; + + var resolutionContext = new TypeScript.PullTypeResolutionContext(resolver); + + if (!ast) { + return null; + } + + var path = this.getASTPath(ast); + + for (var i = 0, n = path.length; i < n; i++) { + var current = path[i]; + + switch (current.kind()) { + case 222 /* FunctionExpression */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + if (propagateContextualTypes) { + resolver.resolveAST(current, true, resolutionContext); + } + break; + + case 136 /* MemberVariableDeclaration */: + var memberVariable = current; + inContextuallyTypedAssignment = memberVariable.variableDeclarator.typeAnnotation !== null; + + this.extractResolutionContextForVariable(inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, memberVariable, memberVariable.variableDeclarator.equalsValueClause); + break; + + case 225 /* VariableDeclarator */: + var variableDeclarator = current; + inContextuallyTypedAssignment = variableDeclarator.typeAnnotation !== null; + + this.extractResolutionContextForVariable(inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, variableDeclarator, variableDeclarator.equalsValueClause); + break; + + case 213 /* InvocationExpression */: + case 216 /* ObjectCreationExpression */: + if (propagateContextualTypes) { + var isNew = current.kind() === 216 /* ObjectCreationExpression */; + var callExpression = current; + var contextualType = null; + + if ((i + 2 < n) && callExpression.argumentList === path[i + 1] && callExpression.argumentList.arguments === path[i + 2]) { + var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); + if (isNew) { + resolver.resolveObjectCreationExpression(callExpression, resolutionContext, callResolutionResults); + } else { + resolver.resolveInvocationExpression(callExpression, resolutionContext, callResolutionResults); + } + + if (callResolutionResults.actualParametersContextTypeSymbols) { + var argExpression = path[i + 3]; + if (argExpression) { + for (var j = 0, m = callExpression.argumentList.arguments.nonSeparatorCount(); j < m; j++) { + if (callExpression.argumentList.arguments.nonSeparatorAt(j) === argExpression) { + var callContextualType = callResolutionResults.actualParametersContextTypeSymbols[j]; + if (callContextualType) { + contextualType = callContextualType; + break; + } + } + } + } + } + } else { + if (isNew) { + resolver.resolveObjectCreationExpression(callExpression, resolutionContext); + } else { + resolver.resolveInvocationExpression(callExpression, resolutionContext); + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 214 /* ArrayLiteralExpression */: + if (propagateContextualTypes) { + var contextualType = null; + var currentContextualType = resolutionContext.getContextualType(); + if (currentContextualType && currentContextualType.isArrayNamedTypeReference()) { + contextualType = currentContextualType.getElementType(); + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 215 /* ObjectLiteralExpression */: + if (propagateContextualTypes) { + var objectLiteralExpression = current; + var objectLiteralResolutionContext = new TypeScript.PullAdditionalObjectLiteralResolutionData(); + resolver.resolveObjectLiteralExpression(objectLiteralExpression, inContextuallyTypedAssignment, resolutionContext, objectLiteralResolutionContext); + + var memeberAST = (path[i + 1] && path[i + 1].kind() === 2 /* SeparatedList */) ? path[i + 2] : path[i + 1]; + if (memeberAST) { + var contextualType = null; + var memberDecls = objectLiteralExpression.propertyAssignments; + if (memberDecls && objectLiteralResolutionContext.membersContextTypeSymbols) { + for (var j = 0, m = memberDecls.nonSeparatorCount(); j < m; j++) { + if (memberDecls.nonSeparatorAt(j) === memeberAST) { + var memberContextualType = objectLiteralResolutionContext.membersContextTypeSymbols[j]; + if (memberContextualType) { + contextualType = memberContextualType; + break; + } + } + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + } + + break; + + case 174 /* AssignmentExpression */: + if (propagateContextualTypes) { + var assignmentExpression = current; + var contextualType = null; + + if (path[i + 1] && path[i + 1] === assignmentExpression.right) { + var leftType = resolver.resolveAST(assignmentExpression.left, inContextuallyTypedAssignment, resolutionContext).type; + if (leftType) { + inContextuallyTypedAssignment = true; + contextualType = leftType; + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 220 /* CastExpression */: + var castExpression = current; + if (!(i + 1 < n && path[i + 1] === castExpression.type)) { + if (propagateContextualTypes) { + var contextualType = null; + var typeSymbol = resolver.resolveAST(castExpression, inContextuallyTypedAssignment, resolutionContext).type; + + if (typeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = typeSymbol; + } + + resolutionContext.pushNewContextualType(contextualType); + } + } + + break; + + case 150 /* ReturnStatement */: + if (propagateContextualTypes) { + var returnStatement = current; + var contextualType = null; + + if (enclosingDecl && (enclosingDecl.kind & 1032192 /* SomeFunction */)) { + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); + if (typeAnnotation) { + var returnTypeSymbol = resolver.resolveTypeReference(typeAnnotation, resolutionContext); + if (returnTypeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = returnTypeSymbol; + } + } else { + var currentContextualType = resolutionContext.getContextualType(); + if (currentContextualType && currentContextualType.isFunction()) { + var contextualSignatures = currentContextualType.kind == 33554432 /* ConstructorType */ ? currentContextualType.getConstructSignatures() : currentContextualType.getCallSignatures(); + var currentContextualTypeSignatureSymbol = contextualSignatures[0]; + var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.returnType; + if (currentContextualTypeReturnTypeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = currentContextualTypeReturnTypeSymbol; + } + } + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 122 /* ObjectType */: + if (propagateContextualTypes && TypeScript.isTypesOnlyLocation(current)) { + resolver.resolveAST(current, false, resolutionContext); + } + + break; + + case 163 /* WithStatement */: + inWithBlock = true; + break; + + case 146 /* Block */: + inContextuallyTypedAssignment = false; + break; + } + + var decl = this.semanticInfoChain.getDeclForAST(current); + if (decl) { + enclosingDecl = decl; + enclosingDeclAST = current; + } + } + + if (ast && ast.parent && ast.kind() === 11 /* IdentifierName */) { + if (ast.parent.kind() === 212 /* MemberAccessExpression */) { + if (ast.parent.name === ast) { + ast = ast.parent; + } + } else if (ast.parent.kind() === 121 /* QualifiedName */) { + if (ast.parent.right === ast) { + ast = ast.parent; + } + } + } + + return { + ast: ast, + enclosingDecl: enclosingDecl, + resolutionContext: resolutionContext, + inContextuallyTypedAssignment: inContextuallyTypedAssignment, + inWithBlock: inWithBlock + }; + }; + + TypeScriptCompiler.prototype.extractResolutionContextForVariable = function (inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, assigningAST, init) { + if (inContextuallyTypedAssignment) { + if (propagateContextualTypes) { + resolver.resolveAST(assigningAST, false, resolutionContext); + var varSymbol = this.semanticInfoChain.getSymbolForAST(assigningAST); + + var contextualType = null; + if (varSymbol && inContextuallyTypedAssignment) { + contextualType = varSymbol.type; + } + + resolutionContext.pushNewContextualType(contextualType); + + if (init) { + resolver.resolveAST(init, inContextuallyTypedAssignment, resolutionContext); + } + } + } + }; + + TypeScriptCompiler.prototype.getASTPath = function (ast) { + var result = []; + + while (ast) { + result.unshift(ast); + ast = ast.parent; + } + + return result; + }; + + TypeScriptCompiler.prototype.pullGetSymbolInformationFromAST = function (ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + ast = context.ast; + var symbol = resolver.resolveAST(ast, context.inContextuallyTypedAssignment, context.resolutionContext); + + if (!symbol) { + TypeScript.Debug.assert(ast.kind() === 120 /* SourceUnit */, "No symbol was found for ast and ast was not source unit. Ast Kind: " + TypeScript.SyntaxKind[ast.kind()]); + return null; + } + + if (symbol.isTypeReference()) { + symbol = symbol.getReferencedTypeSymbol(); + } + + var aliasSymbol = this.semanticInfoChain.getAliasSymbolForAST(ast); + + return { + symbol: symbol, + aliasSymbol: aliasSymbol, + ast: ast, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetCallInformationFromAST = function (ast, document) { + if (ast.kind() !== 213 /* InvocationExpression */ && ast.kind() !== 216 /* ObjectCreationExpression */) { + return null; + } + + var isNew = ast.kind() === 216 /* ObjectCreationExpression */; + + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); + + if (isNew) { + resolver.resolveObjectCreationExpression(ast, context.resolutionContext, callResolutionResults); + } else { + resolver.resolveInvocationExpression(ast, context.resolutionContext, callResolutionResults); + } + + return { + targetSymbol: callResolutionResults.targetSymbol, + resolvedSignatures: callResolutionResults.resolvedSignatures, + candidateSignature: callResolutionResults.candidateSignature, + ast: ast, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl), + isConstructorCall: isNew + }; + }; + + TypeScriptCompiler.prototype.pullGetVisibleMemberSymbolsFromAST = function (ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var symbols = resolver.getVisibleMembersFromExpression(ast, context.enclosingDecl, context.resolutionContext); + if (!symbols) { + return null; + } + + return { + symbols: symbols, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetVisibleDeclsFromAST = function (ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, false); + if (!context || context.inWithBlock) { + return null; + } + + return resolver.getVisibleDecls(context.enclosingDecl); + }; + + TypeScriptCompiler.prototype.pullGetContextualMembersFromAST = function (ast, document) { + if (ast.kind() !== 215 /* ObjectLiteralExpression */) { + return null; + } + + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var members = resolver.getVisibleContextSymbols(context.enclosingDecl, context.resolutionContext); + + return { + symbols: members, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetDeclInformation = function (decl, ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var astForDecl = decl.ast(); + if (!astForDecl) { + return null; + } + + var astForDeclContext = this.extractResolutionContextFromAST(resolver, astForDecl, this.getDocument(astForDecl.fileName()), true); + if (!astForDeclContext) { + return null; + } + + var symbol = decl.getSymbol(); + resolver.resolveDeclaredSymbol(symbol, context.resolutionContext); + symbol.setUnresolved(); + + return { + symbol: symbol, + aliasSymbol: null, + ast: ast, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.topLevelDeclaration = function (fileName) { + return this.semanticInfoChain.topLevelDecl(fileName); + }; + + TypeScriptCompiler.prototype.getDeclForAST = function (ast) { + return this.semanticInfoChain.getDeclForAST(ast); + }; + + TypeScriptCompiler.prototype.fileNames = function () { + return this.semanticInfoChain.fileNames(); + }; + + TypeScriptCompiler.prototype.topLevelDecl = function (fileName) { + return this.semanticInfoChain.topLevelDecl(fileName); + }; + + TypeScriptCompiler.getLocationText = function (location, resolvePath) { + return resolvePath(location.fileName()) + "(" + (location.line() + 1) + "," + (location.character() + 1) + ")"; + }; + + TypeScriptCompiler.getFullDiagnosticText = function (diagnostic, resolvePath) { + var result = ""; + if (diagnostic.fileName()) { + result += this.getLocationText(diagnostic, resolvePath) + ": "; + } + + result += diagnostic.message(); + + var additionalLocations = diagnostic.additionalLocations(); + if (additionalLocations.length > 0) { + result += " " + TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Additional_locations, null) + TypeScript.Environment.newLine; + + for (var i = 0, n = additionalLocations.length; i < n; i++) { + result += "\t" + this.getLocationText(additionalLocations[i], resolvePath) + TypeScript.Environment.newLine; + } + } else { + result += TypeScript.Environment.newLine; + } + + return result; + }; + return TypeScriptCompiler; + })(); + TypeScript.TypeScriptCompiler = TypeScriptCompiler; + + var CompilerPhase; + (function (CompilerPhase) { + CompilerPhase[CompilerPhase["Syntax"] = 0] = "Syntax"; + CompilerPhase[CompilerPhase["Semantics"] = 1] = "Semantics"; + CompilerPhase[CompilerPhase["EmitOptionsValidation"] = 2] = "EmitOptionsValidation"; + CompilerPhase[CompilerPhase["Emit"] = 3] = "Emit"; + CompilerPhase[CompilerPhase["DeclarationEmit"] = 4] = "DeclarationEmit"; + })(CompilerPhase || (CompilerPhase = {})); + + var CompilerIterator = (function () { + function CompilerIterator(compiler, resolvePath, continueOnDiagnostics, startingPhase) { + if (typeof startingPhase === "undefined") { startingPhase = 0 /* Syntax */; } + this.compiler = compiler; + this.resolvePath = resolvePath; + this.continueOnDiagnostics = continueOnDiagnostics; + this.index = -1; + this.fileNames = null; + this._current = null; + this._emitOptions = null; + this._sharedEmitter = null; + this._sharedDeclarationEmitter = null; + this.hadSyntacticDiagnostics = false; + this.hadSemanticDiagnostics = false; + this.hadEmitDiagnostics = false; + this.fileNames = compiler.fileNames(); + this.compilerPhase = startingPhase; + } + CompilerIterator.prototype.current = function () { + return this._current; + }; + + CompilerIterator.prototype.moveNext = function () { + this._current = null; + + while (this.moveNextInternal()) { + if (this._current) { + return true; + } + } + + return false; + }; + + CompilerIterator.prototype.moveNextInternal = function () { + this.index++; + + while (this.shouldMoveToNextPhase()) { + this.index = 0; + this.compilerPhase++; + } + + if (this.compilerPhase > 4 /* DeclarationEmit */) { + return false; + } + + switch (this.compilerPhase) { + case 0 /* Syntax */: + return this.moveNextSyntaxPhase(); + case 1 /* Semantics */: + return this.moveNextSemanticsPhase(); + case 2 /* EmitOptionsValidation */: + return this.moveNextEmitOptionsValidationPhase(); + case 3 /* Emit */: + return this.moveNextEmitPhase(); + case 4 /* DeclarationEmit */: + return this.moveNextDeclarationEmitPhase(); + } + }; + + CompilerIterator.prototype.shouldMoveToNextPhase = function () { + switch (this.compilerPhase) { + case 2 /* EmitOptionsValidation */: + return this.index === 1; + + case 0 /* Syntax */: + case 1 /* Semantics */: + return this.index === this.fileNames.length; + + case 3 /* Emit */: + case 4 /* DeclarationEmit */: + return this.index === (this.fileNames.length + 1); + } + + return false; + }; + + CompilerIterator.prototype.moveNextSyntaxPhase = function () { + TypeScript.Debug.assert(this.index >= 0 && this.index < this.fileNames.length); + var fileName = this.fileNames[this.index]; + + var diagnostics = this.compiler.getSyntacticDiagnostics(fileName); + if (diagnostics.length) { + if (!this.continueOnDiagnostics) { + this.hadSyntacticDiagnostics = true; + } + + this._current = CompileResult.fromDiagnostics(diagnostics); + } + + return true; + }; + + CompilerIterator.prototype.moveNextSemanticsPhase = function () { + if (this.hadSyntacticDiagnostics) { + return false; + } + + TypeScript.Debug.assert(this.index >= 0 && this.index < this.fileNames.length); + var fileName = this.fileNames[this.index]; + var diagnostics = this.compiler.getSemanticDiagnostics(fileName); + if (diagnostics.length) { + if (!this.continueOnDiagnostics) { + this.hadSemanticDiagnostics = true; + } + + this._current = CompileResult.fromDiagnostics(diagnostics); + } + + return true; + }; + + CompilerIterator.prototype.moveNextEmitOptionsValidationPhase = function () { + TypeScript.Debug.assert(!this.hadSyntacticDiagnostics); + + if (!this._emitOptions) { + this._emitOptions = new TypeScript.EmitOptions(this.compiler, this.resolvePath); + } + + if (this._emitOptions.diagnostic()) { + if (!this.continueOnDiagnostics) { + this.hadEmitDiagnostics = true; + } + + this._current = CompileResult.fromDiagnostics([this._emitOptions.diagnostic()]); + } + + return true; + }; + + CompilerIterator.prototype.moveNextEmitPhase = function () { + var _this = this; + TypeScript.Debug.assert(!this.hadSyntacticDiagnostics); + TypeScript.Debug.assert(this._emitOptions); + + if (this.hadEmitDiagnostics) { + return false; + } + + TypeScript.Debug.assert(this.index >= 0 && this.index <= this.fileNames.length); + if (this.index < this.fileNames.length) { + var fileName = this.fileNames[this.index]; + var document = this.compiler.getDocument(fileName); + + this._sharedEmitter = this.compiler._emitDocument(document, this._emitOptions, function (outputFiles) { + _this._current = CompileResult.fromOutputFiles(outputFiles); + }, this._sharedEmitter); + return true; + } + + if (this.index === this.fileNames.length && this._sharedEmitter) { + this._current = CompileResult.fromOutputFiles(this._sharedEmitter.getOutputFiles()); + } + + return true; + }; + + CompilerIterator.prototype.moveNextDeclarationEmitPhase = function () { + var _this = this; + TypeScript.Debug.assert(!this.hadSyntacticDiagnostics); + TypeScript.Debug.assert(!this.hadEmitDiagnostics); + if (this.hadSemanticDiagnostics) { + return false; + } + + if (!this.compiler.compilationSettings().generateDeclarationFiles()) { + return false; + } + + TypeScript.Debug.assert(this.index >= 0 && this.index <= this.fileNames.length); + if (this.index < this.fileNames.length) { + var fileName = this.fileNames[this.index]; + var document = this.compiler.getDocument(fileName); + + this._sharedDeclarationEmitter = this.compiler._emitDocumentDeclarations(document, this._emitOptions, function (file) { + _this._current = CompileResult.fromOutputFiles([file]); + }, this._sharedDeclarationEmitter); + return true; + } + + if (this.index === this.fileNames.length && this._sharedDeclarationEmitter) { + this._current = CompileResult.fromOutputFiles([this._sharedDeclarationEmitter.getOutputFile()]); + } + + return true; + }; + return CompilerIterator; + })(); + + function compareDataObjects(dst, src) { + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) + return false; + } else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) + return false; + } + } + return true; + } + TypeScript.compareDataObjects = compareDataObjects; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (GenerativeTypeClassification) { + GenerativeTypeClassification[GenerativeTypeClassification["Unknown"] = 0] = "Unknown"; + GenerativeTypeClassification[GenerativeTypeClassification["Open"] = 1] = "Open"; + GenerativeTypeClassification[GenerativeTypeClassification["Closed"] = 2] = "Closed"; + GenerativeTypeClassification[GenerativeTypeClassification["InfinitelyExpanding"] = 3] = "InfinitelyExpanding"; + })(TypeScript.GenerativeTypeClassification || (TypeScript.GenerativeTypeClassification = {})); + var GenerativeTypeClassification = TypeScript.GenerativeTypeClassification; + + var PullTypeReferenceSymbol = (function (_super) { + __extends(PullTypeReferenceSymbol, _super); + function PullTypeReferenceSymbol(referencedTypeSymbol) { + _super.call(this, referencedTypeSymbol.name, referencedTypeSymbol.kind); + this.referencedTypeSymbol = referencedTypeSymbol; + this.isResolved = true; + + TypeScript.Debug.assert(referencedTypeSymbol !== null, "Type root symbol may not be null"); + + this.setRootSymbol(referencedTypeSymbol); + + this.typeReference = this; + } + PullTypeReferenceSymbol.createTypeReference = function (type) { + if (type.isTypeReference()) { + return type; + } + + var typeReference = type.typeReference; + + if (!typeReference) { + typeReference = new PullTypeReferenceSymbol(type); + type.typeReference = typeReference; + } + + return typeReference; + }; + + PullTypeReferenceSymbol.prototype.isTypeReference = function () { + return true; + }; + + PullTypeReferenceSymbol.prototype.setResolved = function () { + }; + + PullTypeReferenceSymbol.prototype.setUnresolved = function () { + }; + PullTypeReferenceSymbol.prototype.invalidate = function () { + }; + + PullTypeReferenceSymbol.prototype.ensureReferencedTypeIsResolved = function () { + this._getResolver().resolveDeclaredSymbol(this.referencedTypeSymbol); + }; + + PullTypeReferenceSymbol.prototype.getReferencedTypeSymbol = function () { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol; + }; + + PullTypeReferenceSymbol.prototype._getResolver = function () { + return this.referencedTypeSymbol._getResolver(); + }; + + PullTypeReferenceSymbol.prototype.hasMembers = function () { + return this.referencedTypeSymbol.hasMembers(); + }; + + PullTypeReferenceSymbol.prototype.setAssociatedContainerType = function (type) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": setAssociatedContainerType"); + }; + + PullTypeReferenceSymbol.prototype.getAssociatedContainerType = function () { + return this.referencedTypeSymbol.getAssociatedContainerType(); + }; + + PullTypeReferenceSymbol.prototype.getFunctionSymbol = function () { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.getFunctionSymbol(); + }; + PullTypeReferenceSymbol.prototype.setFunctionSymbol = function (symbol) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": setFunctionSymbol"); + }; + + PullTypeReferenceSymbol.prototype.addContainedNonMember = function (nonMember) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addContainedNonMember"); + }; + PullTypeReferenceSymbol.prototype.findContainedNonMemberContainer = function (containerName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.findContainedNonMemberContainer(containerName, kind); + }; + + PullTypeReferenceSymbol.prototype.addMember = function (memberSymbol) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addMember"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedMemberType = function (enclosedType) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedMemberType"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedMemberContainer = function (enclosedContainer) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedMemberContainer"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedNonMember = function (enclosedNonMember) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedNonMember"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedNonMemberType = function (enclosedNonMemberType) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedNonMemberType"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedNonMemberContainer = function (enclosedNonMemberContainer) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedNonMemberContainer"); + }; + PullTypeReferenceSymbol.prototype.addTypeParameter = function (typeParameter) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addTypeParameter"); + }; + PullTypeReferenceSymbol.prototype.addConstructorTypeParameter = function (typeParameter) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addConstructorTypeParameter"); + }; + + PullTypeReferenceSymbol.prototype.findContainedNonMember = function (name) { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findContainedNonMember(name); + }; + + PullTypeReferenceSymbol.prototype.findContainedNonMemberType = function (typeName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findContainedNonMemberType(typeName, kind); + }; + + PullTypeReferenceSymbol.prototype.getMembers = function () { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.getMembers(); + }; + + PullTypeReferenceSymbol.prototype.setHasDefaultConstructor = function (hasOne) { + if (typeof hasOne === "undefined") { hasOne = true; } + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ":setHasDefaultConstructor"); + }; + PullTypeReferenceSymbol.prototype.getHasDefaultConstructor = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getHasDefaultConstructor(); + }; + PullTypeReferenceSymbol.prototype.getConstructorMethod = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getConstructorMethod(); + }; + PullTypeReferenceSymbol.prototype.setConstructorMethod = function (constructorMethod) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": setConstructorMethod"); + }; + PullTypeReferenceSymbol.prototype.getTypeParameters = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypeParameters(); + }; + + PullTypeReferenceSymbol.prototype.isGeneric = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.isGeneric(); + }; + + PullTypeReferenceSymbol.prototype.addSpecialization = function (specializedVersionOfThisType, substitutingTypes) { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.addSpecialization(specializedVersionOfThisType, substitutingTypes); + }; + PullTypeReferenceSymbol.prototype.getSpecialization = function (substitutingTypes) { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getSpecialization(substitutingTypes); + }; + PullTypeReferenceSymbol.prototype.getKnownSpecializations = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getKnownSpecializations(); + }; + PullTypeReferenceSymbol.prototype.getTypeArguments = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypeArguments(); + }; + PullTypeReferenceSymbol.prototype.getTypeArgumentsOrTypeParameters = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypeArgumentsOrTypeParameters(); + }; + + PullTypeReferenceSymbol.prototype.appendCallSignature = function (callSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": appendCallSignature"); + }; + PullTypeReferenceSymbol.prototype.insertCallSignatureAtIndex = function (callSignature, index) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": insertCallSignatureAtIndex"); + }; + PullTypeReferenceSymbol.prototype.appendConstructSignature = function (callSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": appendConstructSignature"); + }; + PullTypeReferenceSymbol.prototype.insertConstructSignatureAtIndex = function (callSignature, index) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": insertConstructSignatureAtIndex"); + }; + PullTypeReferenceSymbol.prototype.addIndexSignature = function (indexSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addIndexSignature"); + }; + + PullTypeReferenceSymbol.prototype.hasOwnCallSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.hasOwnCallSignatures(); + }; + PullTypeReferenceSymbol.prototype.getCallSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getCallSignatures(); + }; + PullTypeReferenceSymbol.prototype.hasOwnConstructSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.hasOwnConstructSignatures(); + }; + PullTypeReferenceSymbol.prototype.getConstructSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getConstructSignatures(); + }; + PullTypeReferenceSymbol.prototype.hasOwnIndexSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.hasOwnIndexSignatures(); + }; + PullTypeReferenceSymbol.prototype.getIndexSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getIndexSignatures(); + }; + + PullTypeReferenceSymbol.prototype.addImplementedType = function (implementedType) { + this.referencedTypeSymbol.addImplementedType(implementedType); + }; + PullTypeReferenceSymbol.prototype.getImplementedTypes = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getImplementedTypes(); + }; + PullTypeReferenceSymbol.prototype.addExtendedType = function (extendedType) { + this.referencedTypeSymbol.addExtendedType(extendedType); + }; + PullTypeReferenceSymbol.prototype.getExtendedTypes = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getExtendedTypes(); + }; + PullTypeReferenceSymbol.prototype.addTypeThatExtendsThisType = function (type) { + this.referencedTypeSymbol.addTypeThatExtendsThisType(type); + }; + PullTypeReferenceSymbol.prototype.getTypesThatExtendThisType = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypesThatExtendThisType(); + }; + PullTypeReferenceSymbol.prototype.addTypeThatExplicitlyImplementsThisType = function (type) { + this.referencedTypeSymbol.addTypeThatExplicitlyImplementsThisType(type); + }; + PullTypeReferenceSymbol.prototype.getTypesThatExplicitlyImplementThisType = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypesThatExplicitlyImplementThisType(); + }; + + PullTypeReferenceSymbol.prototype.isValidBaseKind = function (baseType, isExtendedType) { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.isValidBaseKind(baseType, isExtendedType); + }; + + PullTypeReferenceSymbol.prototype.findMember = function (name, lookInParent) { + if (typeof lookInParent === "undefined") { lookInParent = true; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findMember(name, lookInParent); + }; + PullTypeReferenceSymbol.prototype.findNestedType = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findNestedType(name, kind); + }; + PullTypeReferenceSymbol.prototype.findNestedContainer = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findNestedContainer(name, kind); + }; + PullTypeReferenceSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisiblity) { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.getAllMembers(searchDeclKind, memberVisiblity); + }; + + PullTypeReferenceSymbol.prototype.findTypeParameter = function (name) { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findTypeParameter(name); + }; + + PullTypeReferenceSymbol.prototype.hasOnlyOverloadCallSignatures = function () { + return this.referencedTypeSymbol.hasOnlyOverloadCallSignatures(); + }; + return PullTypeReferenceSymbol; + })(TypeScript.PullTypeSymbol); + TypeScript.PullTypeReferenceSymbol = PullTypeReferenceSymbol; + + TypeScript.nSpecializationsCreated = 0; + TypeScript.nSpecializedSignaturesCreated = 0; + TypeScript.nSpecializedTypeParameterCreated = 0; + + var PullInstantiatedTypeReferenceSymbol = (function (_super) { + __extends(PullInstantiatedTypeReferenceSymbol, _super); + function PullInstantiatedTypeReferenceSymbol(referencedTypeSymbol, _typeParameterArgumentMap, isInstanceReferenceType) { + _super.call(this, referencedTypeSymbol); + this.referencedTypeSymbol = referencedTypeSymbol; + this._typeParameterArgumentMap = _typeParameterArgumentMap; + this.isInstanceReferenceType = isInstanceReferenceType; + this._instantiatedMembers = null; + this._allInstantiatedMemberNameCache = null; + this._instantiatedMemberNameCache = TypeScript.createIntrinsicsObject(); + this._instantiatedCallSignatures = null; + this._instantiatedConstructSignatures = null; + this._instantiatedIndexSignatures = null; + this._typeArgumentReferences = undefined; + this._instantiatedConstructorMethod = null; + this._instantiatedAssociatedContainerType = null; + this._isArray = undefined; + this._generativeTypeClassification = []; + + TypeScript.nSpecializationsCreated++; + } + PullInstantiatedTypeReferenceSymbol.prototype.getIsSpecialized = function () { + return !this.isInstanceReferenceType; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getGenerativeTypeClassification = function (enclosingType) { + if (!this.isNamedTypeSymbol()) { + return 0 /* Unknown */; + } + + var generativeTypeClassification = this._generativeTypeClassification[enclosingType.pullSymbolID] || 0 /* Unknown */; + if (generativeTypeClassification === 0 /* Unknown */) { + var typeParameters = enclosingType.getTypeParameters(); + var enclosingTypeParameterMap = []; + for (var i = 0; i < typeParameters.length; i++) { + enclosingTypeParameterMap[typeParameters[i].pullSymbolID] = typeParameters[i]; + } + + var typeArguments = this.getTypeArguments(); + for (var i = 0; i < typeArguments.length; i++) { + if (typeArguments[i].wrapsSomeTypeParameter(enclosingTypeParameterMap, true)) { + generativeTypeClassification = 1 /* Open */; + break; + } + } + + if (generativeTypeClassification === 1 /* Open */) { + if (this.wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType)) { + generativeTypeClassification = 3 /* InfinitelyExpanding */; + } + } else { + generativeTypeClassification = 2 /* Closed */; + } + + this._generativeTypeClassification[enclosingType.pullSymbolID] = generativeTypeClassification; + } + + return generativeTypeClassification; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.isArrayNamedTypeReference = function () { + if (this._isArray === undefined) { + this._isArray = this.getRootSymbol().isArrayNamedTypeReference() || (this.getRootSymbol() === this._getResolver().getArrayNamedType()); + } + return this._isArray; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getElementType = function () { + if (!this.isArrayNamedTypeReference()) { + return null; + } + + var typeArguments = this.getTypeArguments(); + return typeArguments ? typeArguments[0] : null; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getReferencedTypeSymbol = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.getIsSpecialized()) { + return this; + } + + return this.referencedTypeSymbol; + }; + + PullInstantiatedTypeReferenceSymbol.create = function (resolver, type, typeParameterArgumentMap) { + TypeScript.Debug.assert(resolver); + + var mutableTypeParameterMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(typeParameterArgumentMap); + + TypeScript.PullInstantiationHelpers.instantiateTypeArgument(resolver, type, mutableTypeParameterMap); + + var rootType = type.getRootSymbol(); + var instantiation = rootType.getSpecialization(mutableTypeParameterMap.typeParameterArgumentMap); + if (instantiation) { + return instantiation; + } + + TypeScript.PullInstantiationHelpers.cleanUpTypeArgumentMap(type, mutableTypeParameterMap); + typeParameterArgumentMap = mutableTypeParameterMap.typeParameterArgumentMap; + + var isInstanceReferenceType = (type.kind & 8216 /* SomeInstantiatableType */) != 0; + var resolvedTypeParameterArgumentMap = typeParameterArgumentMap; + if (isInstanceReferenceType) { + var typeParameters = rootType.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + if (!TypeScript.PullHelpers.typeSymbolsAreIdentical(typeParameters[i], typeParameterArgumentMap[typeParameters[i].pullSymbolID])) { + isInstanceReferenceType = false; + break; + } + } + + if (isInstanceReferenceType) { + typeParameterArgumentMap = []; + } + } + + instantiation = new PullInstantiatedTypeReferenceSymbol(rootType, typeParameterArgumentMap, isInstanceReferenceType); + + rootType.addSpecialization(instantiation, resolvedTypeParameterArgumentMap); + + return instantiation; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.isGeneric = function () { + return this.getRootSymbol().isGeneric(); + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getTypeParameterArgumentMap = function () { + return this._typeParameterArgumentMap; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getTypeArguments = function () { + if (this.isInstanceReferenceType) { + return this.getTypeParameters(); + } + + if (this._typeArgumentReferences === undefined) { + var typeParameters = this.referencedTypeSymbol.getTypeParameters(); + + if (typeParameters.length) { + var typeArgument = null; + var typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArgument = this._typeParameterArgumentMap[typeParameters[i].pullSymbolID]; + + if (!typeArgument) { + TypeScript.Debug.fail("type argument count mismatch"); + } + + if (typeArgument) { + typeArguments[typeArguments.length] = typeArgument; + } + } + + this._typeArgumentReferences = typeArguments; + } else { + this._typeArgumentReferences = null; + } + } + + return this._typeArgumentReferences; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getTypeArgumentsOrTypeParameters = function () { + return this.getTypeArguments(); + }; + + PullInstantiatedTypeReferenceSymbol.prototype.populateInstantiatedMemberFromReferencedMember = function (referencedMember) { + var instantiatedMember; + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(referencedMember); + + if (!referencedMember.type.wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + instantiatedMember = referencedMember; + } else { + instantiatedMember = new TypeScript.PullSymbol(referencedMember.name, referencedMember.kind); + instantiatedMember.setRootSymbol(referencedMember); + instantiatedMember.type = this._getResolver().instantiateType(referencedMember.type, this._typeParameterArgumentMap); + instantiatedMember.isOptional = referencedMember.isOptional; + } + this._instantiatedMemberNameCache[instantiatedMember.name] = instantiatedMember; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getMembers = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getMembers(); + } + + if (!this._instantiatedMembers) { + var referencedMembers = this.referencedTypeSymbol.getMembers(); + var referencedMember = null; + var instantiatedMember = null; + + this._instantiatedMembers = []; + + for (var i = 0; i < referencedMembers.length; i++) { + referencedMember = referencedMembers[i]; + + this._getResolver().resolveDeclaredSymbol(referencedMember); + + if (!this._instantiatedMemberNameCache[referencedMember.name]) { + this.populateInstantiatedMemberFromReferencedMember(referencedMember); + } + + this._instantiatedMembers[this._instantiatedMembers.length] = this._instantiatedMemberNameCache[referencedMember.name]; + } + } + + return this._instantiatedMembers; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.findMember = function (name, lookInParent) { + if (typeof lookInParent === "undefined") { lookInParent = true; } + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.findMember(name, lookInParent); + } + + var memberSymbol = this._instantiatedMemberNameCache[name]; + + if (!memberSymbol) { + var referencedMemberSymbol = this.referencedTypeSymbol.findMember(name, lookInParent); + + if (referencedMemberSymbol) { + this.populateInstantiatedMemberFromReferencedMember(referencedMemberSymbol); + memberSymbol = this._instantiatedMemberNameCache[name]; + } else { + memberSymbol = null; + } + } + + return memberSymbol; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisiblity) { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getAllMembers(searchDeclKind, memberVisiblity); + } + + var requestedMembers = []; + var allReferencedMembers = this.referencedTypeSymbol.getAllMembers(searchDeclKind, memberVisiblity); + + if (!this._allInstantiatedMemberNameCache) { + this._allInstantiatedMemberNameCache = TypeScript.createIntrinsicsObject(); + + var members = this.getMembers(); + + for (var i = 0; i < members.length; i++) { + this._allInstantiatedMemberNameCache[members[i].name] = members[i]; + } + } + + var referencedMember = null; + var requestedMember = null; + + for (var i = 0; i < allReferencedMembers.length; i++) { + referencedMember = allReferencedMembers[i]; + + this._getResolver().resolveDeclaredSymbol(referencedMember); + + if (this._allInstantiatedMemberNameCache[referencedMember.name]) { + requestedMembers[requestedMembers.length] = this._allInstantiatedMemberNameCache[referencedMember.name]; + } else { + if (!referencedMember.type.wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._allInstantiatedMemberNameCache[referencedMember.name] = referencedMember; + requestedMembers[requestedMembers.length] = referencedMember; + } else { + requestedMember = new TypeScript.PullSymbol(referencedMember.name, referencedMember.kind); + requestedMember.setRootSymbol(referencedMember); + + requestedMember.type = this._getResolver().instantiateType(referencedMember.type, this._typeParameterArgumentMap); + requestedMember.isOptional = referencedMember.isOptional; + + this._allInstantiatedMemberNameCache[requestedMember.name] = requestedMember; + requestedMembers[requestedMembers.length] = requestedMember; + } + } + } + + return requestedMembers; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getConstructorMethod = function () { + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getConstructorMethod(); + } + + if (!this._instantiatedConstructorMethod) { + var referencedConstructorMethod = this.referencedTypeSymbol.getConstructorMethod(); + this._instantiatedConstructorMethod = new TypeScript.PullSymbol(referencedConstructorMethod.name, referencedConstructorMethod.kind); + this._instantiatedConstructorMethod.setRootSymbol(referencedConstructorMethod); + this._instantiatedConstructorMethod.setResolved(); + + this._instantiatedConstructorMethod.type = PullInstantiatedTypeReferenceSymbol.create(this._getResolver(), referencedConstructorMethod.type, this._typeParameterArgumentMap); + } + + return this._instantiatedConstructorMethod; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getAssociatedContainerType = function () { + if (!this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getAssociatedContainerType(); + } + + if (!this._instantiatedAssociatedContainerType) { + var referencedAssociatedContainerType = this.referencedTypeSymbol.getAssociatedContainerType(); + + if (referencedAssociatedContainerType) { + this._instantiatedAssociatedContainerType = PullInstantiatedTypeReferenceSymbol.create(this._getResolver(), referencedAssociatedContainerType, this._typeParameterArgumentMap); + } + } + + return this._instantiatedAssociatedContainerType; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getCallSignatures = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getCallSignatures(); + } + + if (this._instantiatedCallSignatures) { + return this._instantiatedCallSignatures; + } + + var referencedCallSignatures = this.referencedTypeSymbol.getCallSignatures(); + this._instantiatedCallSignatures = []; + + for (var i = 0; i < referencedCallSignatures.length; i++) { + this._getResolver().resolveDeclaredSymbol(referencedCallSignatures[i]); + + if (!referencedCallSignatures[i].wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._instantiatedCallSignatures[this._instantiatedCallSignatures.length] = referencedCallSignatures[i]; + } else { + this._instantiatedCallSignatures[this._instantiatedCallSignatures.length] = this._getResolver().instantiateSignature(referencedCallSignatures[i], this._typeParameterArgumentMap); + this._instantiatedCallSignatures[this._instantiatedCallSignatures.length - 1].functionType = this; + } + } + + return this._instantiatedCallSignatures; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getConstructSignatures = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getConstructSignatures(); + } + + if (this._instantiatedConstructSignatures) { + return this._instantiatedConstructSignatures; + } + + var referencedConstructSignatures = this.referencedTypeSymbol.getConstructSignatures(); + this._instantiatedConstructSignatures = []; + + for (var i = 0; i < referencedConstructSignatures.length; i++) { + this._getResolver().resolveDeclaredSymbol(referencedConstructSignatures[i]); + + if (!referencedConstructSignatures[i].wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._instantiatedConstructSignatures[this._instantiatedConstructSignatures.length] = referencedConstructSignatures[i]; + } else { + this._instantiatedConstructSignatures[this._instantiatedConstructSignatures.length] = this._getResolver().instantiateSignature(referencedConstructSignatures[i], this._typeParameterArgumentMap); + this._instantiatedConstructSignatures[this._instantiatedConstructSignatures.length - 1].functionType = this; + } + } + + return this._instantiatedConstructSignatures; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getIndexSignatures = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getIndexSignatures(); + } + + if (this._instantiatedIndexSignatures) { + return this._instantiatedIndexSignatures; + } + + var referencedIndexSignatures = this.referencedTypeSymbol.getIndexSignatures(); + this._instantiatedIndexSignatures = []; + + for (var i = 0; i < referencedIndexSignatures.length; i++) { + this._getResolver().resolveDeclaredSymbol(referencedIndexSignatures[i]); + + if (!referencedIndexSignatures[i].wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._instantiatedIndexSignatures[this._instantiatedIndexSignatures.length] = referencedIndexSignatures[i]; + } else { + this._instantiatedIndexSignatures[this._instantiatedIndexSignatures.length] = this._getResolver().instantiateSignature(referencedIndexSignatures[i], this._typeParameterArgumentMap); + this._instantiatedIndexSignatures[this._instantiatedIndexSignatures.length - 1].functionType = this; + } + } + + return this._instantiatedIndexSignatures; + }; + return PullInstantiatedTypeReferenceSymbol; + })(PullTypeReferenceSymbol); + TypeScript.PullInstantiatedTypeReferenceSymbol = PullInstantiatedTypeReferenceSymbol; + + var PullInstantiatedSignatureSymbol = (function (_super) { + __extends(PullInstantiatedSignatureSymbol, _super); + function PullInstantiatedSignatureSymbol(rootSignature, _typeParameterArgumentMap) { + _super.call(this, rootSignature.kind, rootSignature.isDefinition()); + this._typeParameterArgumentMap = _typeParameterArgumentMap; + this.setRootSymbol(rootSignature); + TypeScript.nSpecializedSignaturesCreated++; + + rootSignature.addSpecialization(this, _typeParameterArgumentMap); + } + PullInstantiatedSignatureSymbol.prototype.getTypeParameterArgumentMap = function () { + return this._typeParameterArgumentMap; + }; + + PullInstantiatedSignatureSymbol.prototype.getIsSpecialized = function () { + return true; + }; + + PullInstantiatedSignatureSymbol.prototype._getResolver = function () { + return this.getRootSymbol()._getResolver(); + }; + + PullInstantiatedSignatureSymbol.prototype.getTypeParameters = function () { + var _this = this; + if (!this._typeParameters) { + var rootSymbol = this.getRootSymbol(); + var typeParameters = rootSymbol.getTypeParameters(); + var hasInstantiatedTypeParametersOfThisSignature = TypeScript.ArrayUtilities.all(typeParameters, function (typeParameter) { + return _this._typeParameterArgumentMap[typeParameter.pullSymbolID] !== undefined; + }); + + if (!hasInstantiatedTypeParametersOfThisSignature && typeParameters.length) { + this._typeParameters = []; + for (var i = 0; i < typeParameters.length; i++) { + this._typeParameters[this._typeParameters.length] = this._getResolver().instantiateTypeParameter(typeParameters[i], this._typeParameterArgumentMap); + } + } else { + this._typeParameters = TypeScript.sentinelEmptyArray; + } + } + + return this._typeParameters; + }; + + PullInstantiatedSignatureSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + var rootSymbol = this.getRootSymbol(); + return rootSymbol.getAllowedToReferenceTypeParameters(); + }; + return PullInstantiatedSignatureSymbol; + })(TypeScript.PullSignatureSymbol); + TypeScript.PullInstantiatedSignatureSymbol = PullInstantiatedSignatureSymbol; + + var PullInstantiatedTypeParameterSymbol = (function (_super) { + __extends(PullInstantiatedTypeParameterSymbol, _super); + function PullInstantiatedTypeParameterSymbol(rootTypeParameter, constraintType) { + _super.call(this, rootTypeParameter.name); + TypeScript.nSpecializedTypeParameterCreated++; + + this.setRootSymbol(rootTypeParameter); + this.setConstraint(constraintType); + + rootTypeParameter.addSpecialization(this, [constraintType]); + } + PullInstantiatedTypeParameterSymbol.prototype._getResolver = function () { + return this.getRootSymbol()._getResolver(); + }; + return PullInstantiatedTypeParameterSymbol; + })(TypeScript.PullTypeParameterSymbol); + TypeScript.PullInstantiatedTypeParameterSymbol = PullInstantiatedTypeParameterSymbol; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTreeToAstVisitor = (function () { + function SyntaxTreeToAstVisitor(fileName, lineMap, compilationSettings) { + this.fileName = fileName; + this.lineMap = lineMap; + this.compilationSettings = compilationSettings; + this.position = 0; + this.previousTokenTrailingComments = null; + } + SyntaxTreeToAstVisitor.visit = function (syntaxTree, fileName, compilationSettings, incrementalAST) { + var visitor = incrementalAST ? new SyntaxTreeToIncrementalAstVisitor(fileName, syntaxTree.lineMap(), compilationSettings) : new SyntaxTreeToAstVisitor(fileName, syntaxTree.lineMap(), compilationSettings); + return syntaxTree.sourceUnit().accept(visitor); + }; + + SyntaxTreeToAstVisitor.prototype.movePast = function (element) { + if (element !== null) { + this.position += element.fullWidth(); + } + }; + + SyntaxTreeToAstVisitor.prototype.moveTo = function (element1, element2) { + if (element2 !== null) { + this.position += TypeScript.Syntax.childOffset(element1, element2); + } + }; + + SyntaxTreeToAstVisitor.prototype.setCommentsAndSpan = function (ast, fullStart, node) { + var firstToken = node.firstToken(); + var lastToken = node.lastToken(); + + this.setSpan(ast, fullStart, node, firstToken, lastToken); + ast.setPreComments(this.convertTokenLeadingComments(firstToken, fullStart)); + ast.setPostComments(this.convertNodeTrailingComments(node, lastToken, fullStart)); + }; + + SyntaxTreeToAstVisitor.prototype.createTokenSpan = function (fullStart, element) { + if (element === null) { + return null; + } + + if (element.fullWidth() === 0) { + return new TypeScript.ASTSpan(-1, -1); + } + + var leadingTriviaWidth = element.leadingTriviaWidth(); + var trailingTriviaWidth = element.trailingTriviaWidth(); + + var start = fullStart + leadingTriviaWidth; + var end = fullStart + element.fullWidth() - trailingTriviaWidth; + + return new TypeScript.ASTSpan(start, end); + }; + + SyntaxTreeToAstVisitor.prototype.setSpan = function (span, fullStart, element, firstToken, lastToken) { + if (typeof firstToken === "undefined") { firstToken = element.firstToken(); } + if (typeof lastToken === "undefined") { lastToken = element.lastToken(); } + var leadingTriviaWidth = firstToken ? firstToken.leadingTriviaWidth() : 0; + var trailingTriviaWidth = lastToken ? lastToken.trailingTriviaWidth() : 0; + + var desiredMinChar = fullStart + leadingTriviaWidth; + var desiredLimChar = fullStart + element.fullWidth() - trailingTriviaWidth; + + this.setSpanExplicit(span, desiredMinChar, desiredLimChar); + + span._trailingTriviaWidth = trailingTriviaWidth; + }; + + SyntaxTreeToAstVisitor.prototype.setSpanExplicit = function (span, start, end) { + span._start = start; + span._end = end; + }; + + SyntaxTreeToAstVisitor.prototype.visitSyntaxList = function (node) { + var start = this.position; + var array = new Array(node.childCount()); + + for (var i = 0, n = node.childCount(); i < n; i++) { + array[i] = node.childAt(i).accept(this); + } + + var result = new TypeScript.ISyntaxList2(this.fileName, array); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSeparatedSyntaxList = function (list) { + var start = this.position; + var array = new Array(list.nonSeparatorCount()); + + for (var i = 0, n = list.childCount(); i < n; i++) { + if (i % 2 === 0) { + array[i / 2] = list.childAt(i).accept(this); + this.previousTokenTrailingComments = null; + } else { + var separatorToken = list.childAt(i); + this.previousTokenTrailingComments = this.convertTokenTrailingComments(separatorToken, this.position + separatorToken.leadingTriviaWidth() + separatorToken.width()); + this.movePast(separatorToken); + } + } + + var result = new TypeScript.ISeparatedSyntaxList2(this.fileName, array, list.separatorCount()); + this.setSpan(result, start, list); + + result.setPostComments(this.previousTokenTrailingComments); + this.previousTokenTrailingComments = null; + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.convertComment = function (trivia, commentStartPosition, hasTrailingNewLine) { + var comment = new TypeScript.Comment(trivia, hasTrailingNewLine, commentStartPosition, commentStartPosition + trivia.fullWidth()); + + return comment; + }; + + SyntaxTreeToAstVisitor.prototype.convertComments = function (triviaList, commentStartPosition) { + var result = []; + + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + if (trivia.isComment()) { + var hasTrailingNewLine = ((i + 1) < n) && triviaList.syntaxTriviaAt(i + 1).isNewLine(); + result.push(this.convertComment(trivia, commentStartPosition, hasTrailingNewLine)); + } + + commentStartPosition += trivia.fullWidth(); + } + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.mergeComments = function (comments1, comments2) { + if (comments1 === null) { + return comments2; + } + + if (comments2 === null) { + return comments1; + } + + return comments1.concat(comments2); + }; + + SyntaxTreeToAstVisitor.prototype.convertTokenLeadingComments = function (token, commentStartPosition) { + if (token === null) { + return null; + } + + var preComments = token.hasLeadingComment() ? this.convertComments(token.leadingTrivia(), commentStartPosition) : null; + + var previousTokenTrailingComments = this.previousTokenTrailingComments; + this.previousTokenTrailingComments = null; + + return this.mergeComments(previousTokenTrailingComments, preComments); + }; + + SyntaxTreeToAstVisitor.prototype.convertTokenTrailingComments = function (token, commentStartPosition) { + if (token === null || !token.hasTrailingComment() || token.hasTrailingNewLine()) { + return null; + } + + return this.convertComments(token.trailingTrivia(), commentStartPosition); + }; + + SyntaxTreeToAstVisitor.prototype.convertNodeTrailingComments = function (node, lastToken, nodeStart) { + if (lastToken === null || !lastToken.hasTrailingComment() || lastToken.hasTrailingNewLine()) { + return null; + } + + return this.convertComments(lastToken.trailingTrivia(), nodeStart + node.fullWidth() - lastToken.trailingTriviaWidth()); + }; + + SyntaxTreeToAstVisitor.prototype.visitIdentifier = function (token) { + return this.visitToken(token); + }; + + SyntaxTreeToAstVisitor.prototype.visitToken = function (token) { + var fullStart = this.position; + + var result = this.visitTokenWorker(token); + + this.movePast(token); + + var start = fullStart + token.leadingTriviaWidth(); + this.setSpanExplicit(result, start, start + token.width()); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTokenWorker = function (token) { + switch (token.tokenKind) { + case 60 /* AnyKeyword */: + return new TypeScript.BuiltInType(60 /* AnyKeyword */, token.text(), token.valueText()); + case 61 /* BooleanKeyword */: + return new TypeScript.BuiltInType(61 /* BooleanKeyword */, token.text(), token.valueText()); + case 67 /* NumberKeyword */: + return new TypeScript.BuiltInType(67 /* NumberKeyword */, token.text(), token.valueText()); + case 69 /* StringKeyword */: + return new TypeScript.BuiltInType(69 /* StringKeyword */, token.text(), token.valueText()); + case 41 /* VoidKeyword */: + return new TypeScript.BuiltInType(41 /* VoidKeyword */, token.text(), token.valueText()); + case 35 /* ThisKeyword */: + return new TypeScript.ThisExpression(token.text(), token.valueText()); + case 50 /* SuperKeyword */: + return new TypeScript.SuperExpression(token.text(), token.valueText()); + case 37 /* TrueKeyword */: + return new TypeScript.LiteralExpression(37 /* TrueKeyword */, token.text(), token.valueText()); + case 24 /* FalseKeyword */: + return new TypeScript.LiteralExpression(24 /* FalseKeyword */, token.text(), token.valueText()); + case 32 /* NullKeyword */: + return new TypeScript.LiteralExpression(32 /* NullKeyword */, token.text(), token.valueText()); + case 14 /* StringLiteral */: + return new TypeScript.StringLiteral(token.text(), token.valueText()); + case 12 /* RegularExpressionLiteral */: + return new TypeScript.RegularExpressionLiteral(token.text(), token.valueText()); + case 13 /* NumericLiteral */: + var fullStart = this.position; + var preComments = this.convertTokenLeadingComments(token, fullStart); + + var result = new TypeScript.NumericLiteral(token.value(), token.text(), token.valueText()); + + result.setPreComments(preComments); + return result; + case 11 /* IdentifierName */: + return new TypeScript.Identifier(token.text()); + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SyntaxTreeToAstVisitor.prototype.visitSourceUnit = function (node) { + var start = this.position; + TypeScript.Debug.assert(start === 0); + + var bod = this.visitSyntaxList(node.moduleElements); + var comments = this.convertTokenLeadingComments(node.endOfFileToken, TypeScript.Syntax.childOffset(node, node.endOfFileToken)); + var result = new TypeScript.SourceUnit(bod, comments, this.fileName); + this.setSpanExplicit(result, start, start + node.fullWidth()); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitExternalModuleReference = function (node) { + var start = this.position; + + this.moveTo(node, node.stringLiteral); + var stringLiteral = node.stringLiteral.accept(this); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ExternalModuleReference(stringLiteral); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitModuleNameModuleReference = function (node) { + var start = this.position; + var moduleName = node.moduleName.accept(this); + + var result = new TypeScript.ModuleNameModuleReference(moduleName); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitClassDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var heritageClauses = node.heritageClauses ? this.visitSyntaxList(node.heritageClauses) : null; + + this.movePast(node.openBraceToken); + var members = this.visitSyntaxList(node.classElements); + + var closeBraceToken = this.createTokenSpan(this.position, node.closeBraceToken); + this.movePast(node.closeBraceToken); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.ClassDeclaration(modifiers, name, typeParameters, heritageClauses, members, closeBraceToken); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitModifiers = function (modifiers) { + var result = null; + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 47 /* ExportKeyword */)) { + result = result || []; + result.push(1 /* Exported */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 63 /* DeclareKeyword */)) { + result = result || []; + result.push(8 /* Ambient */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 58 /* StaticKeyword */)) { + result = result || []; + result.push(16 /* Static */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 57 /* PublicKeyword */)) { + result = result || []; + result.push(4 /* Public */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 55 /* PrivateKeyword */)) { + result = result || []; + result.push(2 /* Private */); + } + + return result || TypeScript.sentinelEmptyArray; + }; + + SyntaxTreeToAstVisitor.prototype.visitInterfaceDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var heritageClauses = node.heritageClauses ? this.visitSyntaxList(node.heritageClauses) : null; + + var body = this.visitObjectType(node.body); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.InterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, body); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitHeritageClause = function (node) { + var start = this.position; + + this.movePast(node.extendsOrImplementsKeyword); + var typeNames = this.visitSeparatedSyntaxList(node.typeNames); + + var result = new TypeScript.HeritageClause(node.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */ ? 230 /* ExtendsHeritageClause */ : 231 /* ImplementsHeritageClause */, typeNames); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitModuleDeclaration = function (node) { + var start = this.position; + + var modifiers = this.visitModifiers(node.modifiers); + + this.moveTo(node, node.moduleKeyword); + this.movePast(node.moduleKeyword); + + var moduleName = node.name ? node.name.accept(this) : null; + var stringLiteral = node.stringLiteral ? node.stringLiteral.accept(this) : null; + + this.movePast(node.openBraceToken); + + var moduleElements = this.visitSyntaxList(node.moduleElements); + + var closeBraceToken = this.createTokenSpan(this.position, node.closeBraceToken); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.ModuleDeclaration(modifiers, moduleName, stringLiteral, moduleElements, closeBraceToken); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + + var callSignature = this.visitCallSignature(node.callSignature); + var block = node.block ? this.visitBlock(node.block) : null; + + this.movePast(node.semicolonToken); + + var result = new TypeScript.FunctionDeclaration(this.visitModifiers(node.modifiers), name, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEnumDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var identifier = this.visitIdentifier(node.identifier); + + this.movePast(node.openBraceToken); + + var enumElements = this.visitSeparatedSyntaxList(node.enumElements); + + this.movePast(node.closeBraceToken); + + var result = new TypeScript.EnumDeclaration(this.visitModifiers(node.modifiers), identifier, enumElements); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEnumElement = function (node) { + var start = this.position; + + var memberName = this.visitToken(node.propertyName); + + var value = node.equalsValueClause !== null ? this.visitEqualsValueClause(node.equalsValueClause) : null; + + var result = new TypeScript.EnumElement(memberName, value); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitImportDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + this.movePast(node.equalsToken); + var alias = node.moduleReference.accept(this); + this.movePast(node.semicolonToken); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.ImportDeclaration(modifiers, name, alias); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitExportAssignment = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + this.movePast(node.semicolonToken); + + var result = new TypeScript.ExportAssignment(name); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.variableDeclaration); + + var declaration = node.variableDeclaration.accept(this); + this.movePast(node.semicolonToken); + + var modifiers = this.visitModifiers(node.modifiers); + + var result = new TypeScript.VariableStatement(modifiers, declaration); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.variableDeclarators); + var variableDecls = this.visitSeparatedSyntaxList(node.variableDeclarators); + + var result = new TypeScript.VariableDeclaration(variableDecls); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableDeclarator = function (node) { + var start = this.position; + var propertyName = this.visitToken(node.propertyName); + var typeExpr = this.visitTypeAnnotation(node.typeAnnotation); + var init = node.equalsValueClause ? this.visitEqualsValueClause(node.equalsValueClause) : null; + + var result = new TypeScript.VariableDeclarator(propertyName, typeExpr, init); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEqualsValueClause = function (node) { + var start = this.position; + var afterEqualsComments = this.convertTokenTrailingComments(node.equalsToken, this.position + node.equalsToken.leadingTriviaWidth() + node.equalsToken.width()); + + this.movePast(node.equalsToken); + var value = node.value.accept(this); + value.setPreComments(this.mergeComments(afterEqualsComments, value.preComments())); + + var result = new TypeScript.EqualsValueClause(value); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPrefixUnaryExpression = function (node) { + var start = this.position; + + this.movePast(node.operatorToken); + var operand = node.operand.accept(this); + + var result = new TypeScript.PrefixUnaryExpression(node.kind(), operand); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArrayLiteralExpression = function (node) { + var start = this.position; + var openStart = this.position + node.openBracketToken.leadingTriviaWidth(); + this.movePast(node.openBracketToken); + + var expressions = this.visitSeparatedSyntaxList(node.expressions); + + var closeStart = this.position + node.closeBracketToken.leadingTriviaWidth(); + this.movePast(node.closeBracketToken); + + var result = new TypeScript.ArrayLiteralExpression(expressions); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitOmittedExpression = function (node) { + var start = this.position; + + var result = new TypeScript.OmittedExpression(); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParenthesizedExpression = function (node) { + var start = this.position; + + var openParenToken = node.openParenToken; + var openParenTrailingComments = this.convertTokenTrailingComments(openParenToken, start + openParenToken.leadingTriviaWidth() + openParenToken.width()); + + this.movePast(openParenToken); + + var expr = node.expression.accept(this); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ParenthesizedExpression(openParenTrailingComments, expr); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + var start = this.position; + + var identifier = node.identifier.accept(this); + this.movePast(node.equalsGreaterThanToken); + + var block = node.block ? this.visitBlock(node.block) : null; + var expression = node.expression ? node.expression.accept(this) : null; + + var result = new TypeScript.SimpleArrowFunctionExpression(identifier, block, expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + var start = this.position; + + var callSignature = this.visitCallSignature(node.callSignature); + this.movePast(node.equalsGreaterThanToken); + + var block = node.block ? this.visitBlock(node.block) : null; + var expression = node.expression ? node.expression.accept(this) : null; + + var result = new TypeScript.ParenthesizedArrowFunctionExpression(callSignature, block, expression); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitType = function (type) { + return type ? type.accept(this) : null; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeQuery = function (node) { + var start = this.position; + this.movePast(node.typeOfKeyword); + var name = node.name.accept(this); + + var result = new TypeScript.TypeQuery(name); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitQualifiedName = function (node) { + var start = this.position; + var left = this.visitType(node.left); + this.movePast(node.dotToken); + var right = this.visitIdentifier(node.right); + + var result = new TypeScript.QualifiedName(left, right); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeArgumentList = function (node) { + if (node === null) { + return null; + } + + var start = this.position; + this.movePast(node.lessThanToken); + var typeArguments = this.visitSeparatedSyntaxList(node.typeArguments); + this.movePast(node.greaterThanToken); + + var result = new TypeScript.TypeArgumentList(typeArguments); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructorType = function (node) { + var start = this.position; + + this.movePast(node.newKeyword); + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var parameters = this.visitParameterList(node.parameterList); + this.movePast(node.equalsGreaterThanToken); + var returnType = this.visitType(node.type); + + var result = new TypeScript.ConstructorType(typeParameters, parameters, returnType); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionType = function (node) { + var start = this.position; + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var parameters = this.visitParameterList(node.parameterList); + this.movePast(node.equalsGreaterThanToken); + var returnType = this.visitType(node.type); + + var result = new TypeScript.FunctionType(typeParameters, parameters, returnType); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectType = function (node) { + var start = this.position; + + this.movePast(node.openBraceToken); + var typeMembers = this.visitSeparatedSyntaxList(node.typeMembers); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.ObjectType(typeMembers); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArrayType = function (node) { + var start = this.position; + + var underlying = this.visitType(node.type); + this.movePast(node.openBracketToken); + this.movePast(node.closeBracketToken); + + var result = new TypeScript.ArrayType(underlying); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitGenericType = function (node) { + var start = this.position; + + var underlying = this.visitType(node.name); + var typeArguments = this.visitTypeArgumentList(node.typeArgumentList); + + var result = new TypeScript.GenericType(underlying, typeArguments); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeAnnotation = function (node) { + if (!node) { + return null; + } + + var start = this.position; + this.movePast(node.colonToken); + var type = this.visitType(node.type); + + var result = new TypeScript.TypeAnnotation(type); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitBlock = function (node) { + if (!node) { + return null; + } + + var start = this.position; + + this.movePast(node.openBraceToken); + var statements = this.visitSyntaxList(node.statements); + var closeBracePosition = this.position; + + var closeBraceLeadingComments = this.convertTokenLeadingComments(node.closeBraceToken, this.position); + var closeBraceToken = this.createTokenSpan(this.position, node.closeBraceToken); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.Block(statements, closeBraceLeadingComments, closeBraceToken); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParameter = function (node) { + var start = this.position; + + var dotDotDotToken = this.createTokenSpan(this.position, node.dotDotDotToken); + + this.moveTo(node, node.identifier); + var identifier = this.visitIdentifier(node.identifier); + + var questionToken = this.createTokenSpan(this.position, node.questionToken); + this.movePast(node.questionToken); + var typeExpr = this.visitTypeAnnotation(node.typeAnnotation); + var init = node.equalsValueClause ? node.equalsValueClause.accept(this) : null; + + var modifiers = this.visitModifiers(node.modifiers); + + var result = new TypeScript.Parameter(dotDotDotToken, modifiers, identifier, questionToken, typeExpr, init); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberAccessExpression = function (node) { + var start = this.position; + + var expression = node.expression.accept(this); + this.movePast(node.dotToken); + var name = this.visitIdentifier(node.name); + + var result = new TypeScript.MemberAccessExpression(expression, name); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPostfixUnaryExpression = function (node) { + var start = this.position; + + var operand = node.operand.accept(this); + this.movePast(node.operatorToken); + + var result = new TypeScript.PostfixUnaryExpression(node.kind() === 210 /* PostIncrementExpression */ ? 210 /* PostIncrementExpression */ : 211 /* PostDecrementExpression */, operand); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitElementAccessExpression = function (node) { + var start = this.position; + + var expression = node.expression.accept(this); + this.movePast(node.openBracketToken); + var argumentExpression = node.argumentExpression.accept(this); + this.movePast(node.closeBracketToken); + + var result = new TypeScript.ElementAccessExpression(expression, argumentExpression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitInvocationExpression = function (node) { + var start = this.position; + + var expression = node.expression.accept(this); + var argumentList = this.visitArgumentList(node.argumentList); + + var result = new TypeScript.InvocationExpression(expression, argumentList); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArgumentList = function (node) { + if (node === null) { + return null; + } + + var start = this.position; + + var typeArguments = this.visitTypeArgumentList(node.typeArgumentList); + + this.movePast(node.openParenToken); + + var _arguments = this.visitSeparatedSyntaxList(node.arguments); + + if (node.arguments.fullWidth() === 0 && node.closeParenToken.fullWidth() === 0) { + var openParenTokenEnd = start + node.openParenToken.leadingTriviaWidth() + node.openParenToken.width(); + this.setSpanExplicit(_arguments, openParenTokenEnd, openParenTokenEnd + node.openParenToken.trailingTriviaWidth()); + } + + var closeParenToken = this.createTokenSpan(this.position, node.closeParenToken); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ArgumentList(typeArguments, _arguments, closeParenToken); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitBinaryExpression = function (node) { + var start = this.position; + + var left = node.left.accept(this); + this.movePast(node.operatorToken); + var right = node.right.accept(this); + + var result = new TypeScript.BinaryExpression(node.kind(), left, right); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConditionalExpression = function (node) { + var start = this.position; + + var condition = node.condition.accept(this); + this.movePast(node.questionToken); + var whenTrue = node.whenTrue.accept(this); + this.movePast(node.colonToken); + var whenFalse = node.whenFalse.accept(this); + + var result = new TypeScript.ConditionalExpression(condition, whenTrue, whenFalse); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructSignature = function (node) { + var start = this.position; + + this.movePast(node.newKeyword); + var callSignature = this.visitCallSignature(node.callSignature); + + var result = new TypeScript.ConstructSignature(callSignature); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMethodSignature = function (node) { + var start = this.position; + + var name = this.visitToken(node.propertyName); + + var questionToken = this.createTokenSpan(this.position, node.questionToken); + this.movePast(node.questionToken); + + var callSignature = this.visitCallSignature(node.callSignature); + + var result = new TypeScript.MethodSignature(name, questionToken, callSignature); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitIndexSignature = function (node) { + var start = this.position; + + this.movePast(node.openBracketToken); + + var parameter = node.parameter.accept(this); + + this.movePast(node.closeBracketToken); + var returnType = this.visitTypeAnnotation(node.typeAnnotation); + + var result = new TypeScript.IndexSignature(parameter, returnType); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPropertySignature = function (node) { + var start = this.position; + + var name = this.visitToken(node.propertyName); + + var questionToken = this.createTokenSpan(this.position, node.questionToken); + this.movePast(node.questionToken); + var typeExpr = this.visitTypeAnnotation(node.typeAnnotation); + + var result = new TypeScript.PropertySignature(name, questionToken, typeExpr); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParameterList = function (node) { + if (!node) { + return null; + } + + var start = this.position; + + var openParenToken = node.openParenToken; + + this.previousTokenTrailingComments = this.convertTokenTrailingComments(openParenToken, start + openParenToken.leadingTriviaWidth() + openParenToken.width()); + var openParenTrailingComments = null; + if (node.parameters.childCount() === 0) { + openParenTrailingComments = this.previousTokenTrailingComments; + this.previousTokenTrailingComments = null; + } + + this.movePast(node.openParenToken); + var parameters = this.visitSeparatedSyntaxList(node.parameters); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ParameterList(openParenTrailingComments, parameters); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCallSignature = function (node) { + var start = this.position; + + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var parameters = this.visitParameterList(node.parameterList); + var returnType = this.visitTypeAnnotation(node.typeAnnotation); + + var result = new TypeScript.CallSignature(typeParameters, parameters, returnType); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeParameterList = function (node) { + if (!node) { + return null; + } + + var start = this.position; + this.movePast(node.lessThanToken); + var typeParameters = this.visitSeparatedSyntaxList(node.typeParameters); + this.movePast(node.greaterThanToken); + + var result = new TypeScript.TypeParameterList(typeParameters); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeParameter = function (node) { + var start = this.position; + + var identifier = this.visitIdentifier(node.identifier); + var constraint = node.constraint ? node.constraint.accept(this) : null; + + var result = new TypeScript.TypeParameter(identifier, constraint); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstraint = function (node) { + var start = this.position; + this.movePast(node.extendsKeyword); + var type = this.visitType(node.type); + + var result = new TypeScript.Constraint(type); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitIfStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var thenBod = node.statement.accept(this); + var elseBod = node.elseClause ? node.elseClause.accept(this) : null; + + var result = new TypeScript.IfStatement(condition, thenBod, elseBod); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitElseClause = function (node) { + var start = this.position; + + this.movePast(node.elseKeyword); + var statement = node.statement.accept(this); + + var result = new TypeScript.ElseClause(statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitExpressionStatement = function (node) { + var start = this.position; + + var preComments = this.convertTokenLeadingComments(node.firstToken(), start); + var expression = node.expression.accept(this); + + var semicolonPosition = this.position; + + var postComments = this.convertComments(node.semicolonToken.trailingTrivia(), this.position + node.semicolonToken.leadingTriviaWidth() + node.semicolonToken.width()); + this.movePast(node.semicolonToken); + + var result = new TypeScript.ExpressionStatement(expression); + this.setSpan(result, start, node); + + result.setPreComments(preComments); + result.setPostComments(postComments); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructorDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.callSignature); + var callSignature = this.visitCallSignature(node.callSignature); + + var block = node.block ? node.block.accept(this) : null; + + this.movePast(node.semicolonToken); + + var result = new TypeScript.ConstructorDeclaration(callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitIndexMemberDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.indexSignature); + var indexSignature = node.indexSignature.accept(this); + + this.movePast(node.semicolonToken); + + var result = new TypeScript.IndexMemberDeclaration(indexSignature); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.propertyName); + var name = this.visitToken(node.propertyName); + + var callSignature = this.visitCallSignature(node.callSignature); + var block = node.block ? this.visitBlock(node.block) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.MemberFunctionDeclaration(this.visitModifiers(node.modifiers), name, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitGetAccessor = function (node) { + var start = this.position; + + this.moveTo(node, node.propertyName); + var name = this.visitToken(node.propertyName); + var parameters = this.visitParameterList(node.parameterList); + var returnType = this.visitTypeAnnotation(node.typeAnnotation); + + var block = node.block ? node.block.accept(this) : null; + var result = new TypeScript.GetAccessor(this.visitModifiers(node.modifiers), name, parameters, returnType, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSetAccessor = function (node) { + var start = this.position; + + this.moveTo(node, node.propertyName); + var name = this.visitToken(node.propertyName); + var parameters = this.visitParameterList(node.parameterList); + var block = node.block ? node.block.accept(this) : null; + var result = new TypeScript.SetAccessor(this.visitModifiers(node.modifiers), name, parameters, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberVariableDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.variableDeclarator); + var variableDeclarator = node.variableDeclarator.accept(this); + this.movePast(node.semicolonToken); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.MemberVariableDeclaration(modifiers, variableDeclarator); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitThrowStatement = function (node) { + var start = this.position; + + this.movePast(node.throwKeyword); + var expression = node.expression.accept(this); + this.movePast(node.semicolonToken); + + var result = new TypeScript.ThrowStatement(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitReturnStatement = function (node) { + var start = this.position; + + this.movePast(node.returnKeyword); + var expression = node.expression ? node.expression.accept(this) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.ReturnStatement(expression); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectCreationExpression = function (node) { + var start = this.position; + + this.movePast(node.newKeyword); + var expression = node.expression.accept(this); + var argumentList = this.visitArgumentList(node.argumentList); + + var result = new TypeScript.ObjectCreationExpression(expression, argumentList); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSwitchStatement = function (node) { + var start = this.position; + + this.movePast(node.switchKeyword); + this.movePast(node.openParenToken); + var expression = node.expression.accept(this); + + var closeParenToken = this.createTokenSpan(this.position, node.closeParenToken); + this.movePast(node.closeParenToken); + this.movePast(node.openBraceToken); + var switchClauses = this.visitSyntaxList(node.switchClauses); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.SwitchStatement(expression, closeParenToken, switchClauses); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCaseSwitchClause = function (node) { + var start = this.position; + + this.movePast(node.caseKeyword); + var expression = node.expression.accept(this); + this.movePast(node.colonToken); + var statements = this.visitSyntaxList(node.statements); + + var result = new TypeScript.CaseSwitchClause(expression, statements); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDefaultSwitchClause = function (node) { + var start = this.position; + + this.movePast(node.defaultKeyword); + this.movePast(node.colonToken); + var statements = this.visitSyntaxList(node.statements); + + var result = new TypeScript.DefaultSwitchClause(statements); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitBreakStatement = function (node) { + var start = this.position; + + this.movePast(node.breakKeyword); + var identifier = node.identifier ? node.identifier.accept(this) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.BreakStatement(identifier); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitContinueStatement = function (node) { + var start = this.position; + + this.movePast(node.continueKeyword); + var identifier = node.identifier ? node.identifier.accept(this) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.ContinueStatement(identifier); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitForStatement = function (node) { + var start = this.position; + + this.movePast(node.forKeyword); + this.movePast(node.openParenToken); + var variableDeclaration = node.variableDeclaration ? node.variableDeclaration.accept(this) : null; + var initializer = node.initializer ? node.initializer.accept(this) : null; + + this.movePast(node.firstSemicolonToken); + var cond = node.condition ? node.condition.accept(this) : null; + this.movePast(node.secondSemicolonToken); + var incr = node.incrementor ? node.incrementor.accept(this) : null; + this.movePast(node.closeParenToken); + var body = node.statement.accept(this); + + var result = new TypeScript.ForStatement(variableDeclaration, initializer, cond, incr, body); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitForInStatement = function (node) { + var start = this.position; + + this.movePast(node.forKeyword); + this.movePast(node.openParenToken); + var variableDeclaration = node.variableDeclaration ? node.variableDeclaration.accept(this) : null; + var left = node.left ? node.left.accept(this) : null; + + this.movePast(node.inKeyword); + var expression = node.expression.accept(this); + this.movePast(node.closeParenToken); + var body = node.statement.accept(this); + + var result = new TypeScript.ForInStatement(variableDeclaration, left, expression, body); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitWhileStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var statement = node.statement.accept(this); + + var result = new TypeScript.WhileStatement(condition, statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitWithStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var statement = node.statement.accept(this); + + var result = new TypeScript.WithStatement(condition, statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCastExpression = function (node) { + var start = this.position; + + this.movePast(node.lessThanToken); + var castTerm = this.visitType(node.type); + this.movePast(node.greaterThanToken); + var expression = node.expression.accept(this); + + var result = new TypeScript.CastExpression(castTerm, expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectLiteralExpression = function (node) { + var start = this.position; + + var openStart = this.position + node.openBraceToken.leadingTriviaWidth(); + this.movePast(node.openBraceToken); + + var propertyAssignments = this.visitSeparatedSyntaxList(node.propertyAssignments); + + var closeStart = this.position + node.closeBraceToken.leadingTriviaWidth(); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.ObjectLiteralExpression(propertyAssignments); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSimplePropertyAssignment = function (node) { + var start = this.position; + + var preComments = this.convertTokenLeadingComments(node.firstToken(), start); + var postComments = this.convertNodeTrailingComments(node, node.lastToken(), start); + + var propertyName = node.propertyName.accept(this); + + var afterColonComments = this.convertTokenTrailingComments(node.colonToken, this.position + node.colonToken.leadingTriviaWidth() + node.colonToken.width()); + + this.movePast(node.colonToken); + var expression = node.expression.accept(this); + expression.setPreComments(this.mergeComments(afterColonComments, expression.preComments())); + + var result = new TypeScript.SimplePropertyAssignment(propertyName, expression); + this.setSpan(result, start, node); + + result.setPreComments(preComments); + result.setPostComments(postComments); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + var start = this.position; + + var propertyName = node.propertyName.accept(this); + var callSignature = this.visitCallSignature(node.callSignature); + var block = this.visitBlock(node.block); + + var result = new TypeScript.FunctionPropertyAssignment(propertyName, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionExpression = function (node) { + var start = this.position; + + this.movePast(node.functionKeyword); + var name = node.identifier === null ? null : this.visitIdentifier(node.identifier); + + var callSignature = this.visitCallSignature(node.callSignature); + var block = node.block ? node.block.accept(this) : null; + + var result = new TypeScript.FunctionExpression(name, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEmptyStatement = function (node) { + var start = this.position; + + this.movePast(node.semicolonToken); + + var result = new TypeScript.EmptyStatement(); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTryStatement = function (node) { + var start = this.position; + + this.movePast(node.tryKeyword); + var tryBody = node.block.accept(this); + + var catchClause = null; + if (node.catchClause !== null) { + catchClause = node.catchClause.accept(this); + } + + var finallyBody = null; + if (node.finallyClause !== null) { + finallyBody = node.finallyClause.accept(this); + } + + var result = new TypeScript.TryStatement(tryBody, catchClause, finallyBody); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCatchClause = function (node) { + var start = this.position; + + this.movePast(node.catchKeyword); + this.movePast(node.openParenToken); + var identifier = this.visitIdentifier(node.identifier); + var typeAnnotation = this.visitTypeAnnotation(node.typeAnnotation); + this.movePast(node.closeParenToken); + var block = node.block.accept(this); + + var result = new TypeScript.CatchClause(identifier, typeAnnotation, block); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFinallyClause = function (node) { + var start = this.position; + this.movePast(node.finallyKeyword); + var block = node.block.accept(this); + + var result = new TypeScript.FinallyClause(block); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitLabeledStatement = function (node) { + var start = this.position; + + var identifier = this.visitIdentifier(node.identifier); + this.movePast(node.colonToken); + var statement = node.statement.accept(this); + + var result = new TypeScript.LabeledStatement(identifier, statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDoStatement = function (node) { + var start = this.position; + + this.movePast(node.doKeyword); + var statement = node.statement.accept(this); + var whileKeyword = this.createTokenSpan(this.position, node.whileKeyword); + + this.movePast(node.whileKeyword); + this.movePast(node.openParenToken); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + this.movePast(node.semicolonToken); + + var result = new TypeScript.DoStatement(statement, whileKeyword, condition); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeOfExpression = function (node) { + var start = this.position; + + this.movePast(node.typeOfKeyword); + var expression = node.expression.accept(this); + + var result = new TypeScript.TypeOfExpression(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDeleteExpression = function (node) { + var start = this.position; + + this.movePast(node.deleteKeyword); + var expression = node.expression.accept(this); + + var result = new TypeScript.DeleteExpression(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVoidExpression = function (node) { + var start = this.position; + + this.movePast(node.voidKeyword); + var expression = node.expression.accept(this); + + var result = new TypeScript.VoidExpression(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDebuggerStatement = function (node) { + var start = this.position; + + this.movePast(node.debuggerKeyword); + this.movePast(node.semicolonToken); + + var result = new TypeScript.DebuggerStatement(); + this.setSpan(result, start, node); + + return result; + }; + return SyntaxTreeToAstVisitor; + })(); + TypeScript.SyntaxTreeToAstVisitor = SyntaxTreeToAstVisitor; + + function applyDelta(ast, delta) { + if (ast) { + if (ast._start !== -1) { + ast._start += delta; + } + + if (ast._end !== -1) { + ast._end += delta; + } + } + } + + function applyDeltaToComments(comments, delta) { + if (comments && comments.length > 0) { + for (var i = 0; i < comments.length; i++) { + var comment = comments[i]; + applyDelta(comment, delta); + } + } + } + + var SyntaxTreeToIncrementalAstVisitor = (function (_super) { + __extends(SyntaxTreeToIncrementalAstVisitor, _super); + function SyntaxTreeToIncrementalAstVisitor() { + _super.apply(this, arguments); + } + SyntaxTreeToIncrementalAstVisitor.prototype.applyDelta = function (ast, delta) { + if (delta === 0) { + return; + } + + var pre = function (cur) { + applyDelta(cur, delta); + applyDeltaToComments(cur.preComments(), delta); + applyDeltaToComments(cur.postComments(), delta); + + switch (cur.kind()) { + case 146 /* Block */: + applyDelta(cur.closeBraceToken, delta); + break; + + case 226 /* ArgumentList */: + applyDelta(cur.closeParenToken, delta); + break; + + case 130 /* ModuleDeclaration */: + applyDelta(cur.endingToken, delta); + break; + + case 131 /* ClassDeclaration */: + applyDelta(cur.closeBraceToken, delta); + break; + + case 161 /* DoStatement */: + applyDelta(cur.whileKeyword, delta); + break; + + case 151 /* SwitchStatement */: + applyDelta(cur.closeParenToken, delta); + break; + } + }; + + TypeScript.getAstWalkerFactory().simpleWalk(ast, pre); + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.setSpanExplicit = function (span, start, end) { + if (span._start !== -1) { + var delta = start - span._start; + this.applyDelta(span, delta); + + span._end = end; + } else { + _super.prototype.setSpanExplicit.call(this, span, start, end); + } + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.getAndMovePastAST = function (element) { + if (this.previousTokenTrailingComments !== null) { + return null; + } + + var result = element._ast; + if (!result) { + return null; + } + + var start = this.position; + this.movePast(element); + this.setSpan(result, start, element); + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.setAST = function (element, ast) { + element._ast = ast; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSyntaxList = function (list) { + var result = this.getAndMovePastAST(list); + if (!result) { + result = _super.prototype.visitSyntaxList.call(this, list); + + if (list.childCount() > 0) { + this.setAST(list, result); + } + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSeparatedSyntaxList = function (list) { + var result = this.getAndMovePastAST(list); + if (!result) { + result = _super.prototype.visitSeparatedSyntaxList.call(this, list); + + if (list.childCount() > 0) { + this.setAST(list, result); + } + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitToken = function (token) { + var result = this.getAndMovePastAST(token); + + if (!result) { + result = _super.prototype.visitToken.call(this, token); + this.setAST(token, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitClassDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitClassDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitInterfaceDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitInterfaceDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitHeritageClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitHeritageClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitModuleDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitModuleDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitImportDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitImportDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitExportAssignment = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitExportAssignment.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitPrefixUnaryExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitPrefixUnaryExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitArrayLiteralExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitArrayLiteralExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitOmittedExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitOmittedExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitParenthesizedExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitParenthesizedExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSimpleArrowFunctionExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitParenthesizedArrowFunctionExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitQualifiedName = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + var result = _super.prototype.visitQualifiedName.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConstructorType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConstructorType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitObjectType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitObjectType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitArrayType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitArrayType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitGenericType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitGenericType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitBlock = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitBlock.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitParameter = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitParameter.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMemberAccessExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMemberAccessExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitPostfixUnaryExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitPostfixUnaryExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitElementAccessExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitElementAccessExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitInvocationExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitInvocationExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitBinaryExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitBinaryExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConditionalExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConditionalExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConstructSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConstructSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMethodSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMethodSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitIndexSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitIndexSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitPropertySignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitPropertySignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCallSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCallSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitTypeParameter = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitTypeParameter.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitIfStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitIfStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitExpressionStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitExpressionStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConstructorDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConstructorDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMemberFunctionDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitGetAccessor = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitGetAccessor.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSetAccessor = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSetAccessor.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMemberVariableDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMemberVariableDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitThrowStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitThrowStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitReturnStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitReturnStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitObjectCreationExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitObjectCreationExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSwitchStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSwitchStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCaseSwitchClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCaseSwitchClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDefaultSwitchClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDefaultSwitchClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitBreakStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitBreakStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitContinueStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitContinueStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitForStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitForStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitForInStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitForInStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitWhileStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitWhileStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitWithStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitWithStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCastExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCastExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitObjectLiteralExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitObjectLiteralExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSimplePropertyAssignment = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSimplePropertyAssignment.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionPropertyAssignment.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitEmptyStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitEmptyStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitTryStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitTryStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCatchClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCatchClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitLabeledStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitLabeledStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDoStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDoStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitTypeOfExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitTypeOfExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDeleteExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDeleteExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitVoidExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitVoidExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDebuggerStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDebuggerStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + return SyntaxTreeToIncrementalAstVisitor; + })(SyntaxTreeToAstVisitor); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ASTSpan = (function () { + function ASTSpan(_start, _end) { + this._start = _start; + this._end = _end; + } + ASTSpan.prototype.start = function () { + return this._start; + }; + + ASTSpan.prototype.end = function () { + return this._end; + }; + return ASTSpan; + })(); + TypeScript.ASTSpan = ASTSpan; + + var astID = 0; + + function structuralEqualsNotIncludingPosition(ast1, ast2) { + return structuralEquals(ast1, ast2, false); + } + TypeScript.structuralEqualsNotIncludingPosition = structuralEqualsNotIncludingPosition; + + function structuralEqualsIncludingPosition(ast1, ast2) { + return structuralEquals(ast1, ast2, true); + } + TypeScript.structuralEqualsIncludingPosition = structuralEqualsIncludingPosition; + + function commentStructuralEqualsNotIncludingPosition(ast1, ast2) { + return commentStructuralEquals(ast1, ast2, false); + } + + function commentStructuralEqualsIncludingPosition(ast1, ast2) { + return commentStructuralEquals(ast1, ast2, true); + } + + function structuralEquals(ast1, ast2, includingPosition) { + if (ast1 === ast2) { + return true; + } + + return ast1 !== null && ast2 !== null && ast1.kind() === ast2.kind() && ast1.structuralEquals(ast2, includingPosition); + } + + function commentStructuralEquals(ast1, ast2, includingPosition) { + if (ast1 === ast2) { + return true; + } + + return ast1 !== null && ast2 !== null && ast1.structuralEquals(ast2, includingPosition); + } + + function astArrayStructuralEquals(array1, array2, includingPosition) { + return TypeScript.ArrayUtilities.sequenceEquals(array1, array2, includingPosition ? structuralEqualsIncludingPosition : structuralEqualsNotIncludingPosition); + } + + function commentArrayStructuralEquals(array1, array2, includingPosition) { + return TypeScript.ArrayUtilities.sequenceEquals(array1, array2, includingPosition ? commentStructuralEqualsIncludingPosition : commentStructuralEqualsNotIncludingPosition); + } + + var AST = (function () { + function AST() { + this.parent = null; + this._start = -1; + this._end = -1; + this._trailingTriviaWidth = 0; + this._astID = astID++; + this._preComments = null; + this._postComments = null; + } + AST.prototype.syntaxID = function () { + return this._astID; + }; + + AST.prototype.start = function () { + return this._start; + }; + + AST.prototype.end = function () { + return this._end; + }; + + AST.prototype.trailingTriviaWidth = function () { + return this._trailingTriviaWidth; + }; + + AST.prototype.fileName = function () { + return this.parent.fileName(); + }; + + AST.prototype.kind = function () { + throw TypeScript.Errors.abstract(); + }; + + AST.prototype.preComments = function () { + return this._preComments; + }; + + AST.prototype.postComments = function () { + return this._postComments; + }; + + AST.prototype.setPreComments = function (comments) { + if (comments && comments.length) { + this._preComments = comments; + } else if (this._preComments) { + this._preComments = null; + } + }; + + AST.prototype.setPostComments = function (comments) { + if (comments && comments.length) { + this._postComments = comments; + } else if (this._postComments) { + this._postComments = null; + } + }; + + AST.prototype.width = function () { + return this.end() - this.start(); + }; + + AST.prototype.structuralEquals = function (ast, includingPosition) { + if (includingPosition) { + if (this.start() !== ast.start() || this.end() !== ast.end()) { + return false; + } + } + + return commentArrayStructuralEquals(this.preComments(), ast.preComments(), includingPosition) && commentArrayStructuralEquals(this.postComments(), ast.postComments(), includingPosition); + }; + + AST.prototype.isExpression = function () { + return false; + }; + return AST; + })(); + TypeScript.AST = AST; + + var ISyntaxList2 = (function (_super) { + __extends(ISyntaxList2, _super); + function ISyntaxList2(_fileName, members) { + _super.call(this); + this._fileName = _fileName; + this.members = members; + + for (var i = 0, n = members.length; i < n; i++) { + members[i].parent = this; + } + } + ISyntaxList2.prototype.childCount = function () { + return this.members.length; + }; + + ISyntaxList2.prototype.childAt = function (index) { + return this.members[index]; + }; + + ISyntaxList2.prototype.fileName = function () { + return this._fileName; + }; + + ISyntaxList2.prototype.kind = function () { + return 1 /* List */; + }; + + ISyntaxList2.prototype.firstOrDefault = function (func) { + return TypeScript.ArrayUtilities.firstOrDefault(this.members, func); + }; + + ISyntaxList2.prototype.lastOrDefault = function (func) { + return TypeScript.ArrayUtilities.lastOrDefault(this.members, func); + }; + + ISyntaxList2.prototype.any = function (func) { + return TypeScript.ArrayUtilities.any(this.members, func); + }; + + ISyntaxList2.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && astArrayStructuralEquals(this.members, ast.members, includingPosition); + }; + return ISyntaxList2; + })(AST); + TypeScript.ISyntaxList2 = ISyntaxList2; + + var ISeparatedSyntaxList2 = (function (_super) { + __extends(ISeparatedSyntaxList2, _super); + function ISeparatedSyntaxList2(_fileName, members, _separatorCount) { + _super.call(this); + this._fileName = _fileName; + this.members = members; + this._separatorCount = _separatorCount; + + for (var i = 0, n = members.length; i < n; i++) { + members[i].parent = this; + } + } + ISeparatedSyntaxList2.prototype.nonSeparatorCount = function () { + return this.members.length; + }; + + ISeparatedSyntaxList2.prototype.separatorCount = function () { + return this._separatorCount; + }; + + ISeparatedSyntaxList2.prototype.nonSeparatorAt = function (index) { + return this.members[index]; + }; + + ISeparatedSyntaxList2.prototype.nonSeparatorIndexOf = function (ast) { + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + if (this.nonSeparatorAt(i) === ast) { + return i; + } + } + + return -1; + }; + + ISeparatedSyntaxList2.prototype.fileName = function () { + return this._fileName; + }; + + ISeparatedSyntaxList2.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + ISeparatedSyntaxList2.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && astArrayStructuralEquals(this.members, ast.members, includingPosition); + }; + return ISeparatedSyntaxList2; + })(AST); + TypeScript.ISeparatedSyntaxList2 = ISeparatedSyntaxList2; + + var SourceUnit = (function (_super) { + __extends(SourceUnit, _super); + function SourceUnit(moduleElements, endOfFileTokenLeadingComments, _fileName) { + _super.call(this); + this.moduleElements = moduleElements; + this.endOfFileTokenLeadingComments = endOfFileTokenLeadingComments; + this._fileName = _fileName; + moduleElements && (moduleElements.parent = this); + } + SourceUnit.prototype.fileName = function () { + return this._fileName; + }; + + SourceUnit.prototype.kind = function () { + return 120 /* SourceUnit */; + }; + + SourceUnit.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.moduleElements, ast.moduleElements, includingPosition); + }; + return SourceUnit; + })(AST); + TypeScript.SourceUnit = SourceUnit; + + var Identifier = (function (_super) { + __extends(Identifier, _super); + function Identifier(_text) { + _super.call(this); + this._text = _text; + this._valueText = null; + } + Identifier.prototype.text = function () { + return this._text; + }; + Identifier.prototype.valueText = function () { + if (!this._valueText) { + var text = this._text; + if (text === "__proto__") { + this._valueText = "#__proto__"; + } else { + this._valueText = TypeScript.Syntax.massageEscapes(text); + } + } + + return this._valueText; + }; + + Identifier.prototype.kind = function () { + return 11 /* IdentifierName */; + }; + + Identifier.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._text === ast._text; + }; + + Identifier.prototype.isExpression = function () { + return true; + }; + return Identifier; + })(AST); + TypeScript.Identifier = Identifier; + + var LiteralExpression = (function (_super) { + __extends(LiteralExpression, _super); + function LiteralExpression(_nodeType, _text, _valueText) { + _super.call(this); + this._nodeType = _nodeType; + this._text = _text; + this._valueText = _valueText; + } + LiteralExpression.prototype.text = function () { + return this._text; + }; + + LiteralExpression.prototype.valueText = function () { + return this._valueText; + }; + + LiteralExpression.prototype.kind = function () { + return this._nodeType; + }; + + LiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + LiteralExpression.prototype.isExpression = function () { + return true; + }; + return LiteralExpression; + })(AST); + TypeScript.LiteralExpression = LiteralExpression; + + var ThisExpression = (function (_super) { + __extends(ThisExpression, _super); + function ThisExpression(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + } + ThisExpression.prototype.text = function () { + return this._text; + }; + + ThisExpression.prototype.valueText = function () { + return this._valueText; + }; + + ThisExpression.prototype.kind = function () { + return 35 /* ThisKeyword */; + }; + + ThisExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + ThisExpression.prototype.isExpression = function () { + return true; + }; + return ThisExpression; + })(AST); + TypeScript.ThisExpression = ThisExpression; + + var SuperExpression = (function (_super) { + __extends(SuperExpression, _super); + function SuperExpression(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + } + SuperExpression.prototype.text = function () { + return this._text; + }; + + SuperExpression.prototype.valueText = function () { + return this._valueText; + }; + + SuperExpression.prototype.kind = function () { + return 50 /* SuperKeyword */; + }; + + SuperExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + SuperExpression.prototype.isExpression = function () { + return true; + }; + return SuperExpression; + })(AST); + TypeScript.SuperExpression = SuperExpression; + + var NumericLiteral = (function (_super) { + __extends(NumericLiteral, _super); + function NumericLiteral(_value, _text, _valueText) { + _super.call(this); + this._value = _value; + this._text = _text; + this._valueText = _valueText; + } + NumericLiteral.prototype.text = function () { + return this._text; + }; + NumericLiteral.prototype.valueText = function () { + return this._valueText; + }; + NumericLiteral.prototype.value = function () { + return this._value; + }; + + NumericLiteral.prototype.kind = function () { + return 13 /* NumericLiteral */; + }; + + NumericLiteral.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && (this._value === ast._value || (isNaN(this._value) && isNaN(ast._value))) && this._text === ast._text; + }; + + NumericLiteral.prototype.isExpression = function () { + return true; + }; + return NumericLiteral; + })(AST); + TypeScript.NumericLiteral = NumericLiteral; + + var RegularExpressionLiteral = (function (_super) { + __extends(RegularExpressionLiteral, _super); + function RegularExpressionLiteral(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + } + RegularExpressionLiteral.prototype.text = function () { + return this._text; + }; + + RegularExpressionLiteral.prototype.valueText = function () { + return this._valueText; + }; + + RegularExpressionLiteral.prototype.kind = function () { + return 12 /* RegularExpressionLiteral */; + }; + + RegularExpressionLiteral.prototype.isExpression = function () { + return true; + }; + return RegularExpressionLiteral; + })(AST); + TypeScript.RegularExpressionLiteral = RegularExpressionLiteral; + + var StringLiteral = (function (_super) { + __extends(StringLiteral, _super); + function StringLiteral(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + this._valueText = _valueText === "__proto__" ? "#__proto__" : _valueText; + } + StringLiteral.prototype.text = function () { + return this._text; + }; + StringLiteral.prototype.valueText = function () { + return this._valueText; + }; + + StringLiteral.prototype.kind = function () { + return 14 /* StringLiteral */; + }; + + StringLiteral.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._text === ast._text; + }; + + StringLiteral.prototype.isExpression = function () { + return true; + }; + return StringLiteral; + })(AST); + TypeScript.StringLiteral = StringLiteral; + + var TypeAnnotation = (function (_super) { + __extends(TypeAnnotation, _super); + function TypeAnnotation(type) { + _super.call(this); + this.type = type; + type && (type.parent = this); + } + TypeAnnotation.prototype.kind = function () { + return 244 /* TypeAnnotation */; + }; + return TypeAnnotation; + })(AST); + TypeScript.TypeAnnotation = TypeAnnotation; + + var BuiltInType = (function (_super) { + __extends(BuiltInType, _super); + function BuiltInType(_nodeType, _text, _valueText) { + _super.call(this); + this._nodeType = _nodeType; + this._text = _text; + this._valueText = _valueText; + } + BuiltInType.prototype.text = function () { + return this._text; + }; + + BuiltInType.prototype.valueText = function () { + return this._valueText; + }; + + BuiltInType.prototype.kind = function () { + return this._nodeType; + }; + return BuiltInType; + })(AST); + TypeScript.BuiltInType = BuiltInType; + + var ExternalModuleReference = (function (_super) { + __extends(ExternalModuleReference, _super); + function ExternalModuleReference(stringLiteral) { + _super.call(this); + this.stringLiteral = stringLiteral; + stringLiteral && (stringLiteral.parent = this); + } + ExternalModuleReference.prototype.kind = function () { + return 245 /* ExternalModuleReference */; + }; + return ExternalModuleReference; + })(AST); + TypeScript.ExternalModuleReference = ExternalModuleReference; + + var ModuleNameModuleReference = (function (_super) { + __extends(ModuleNameModuleReference, _super); + function ModuleNameModuleReference(moduleName) { + _super.call(this); + this.moduleName = moduleName; + moduleName && (moduleName.parent = this); + } + ModuleNameModuleReference.prototype.kind = function () { + return 246 /* ModuleNameModuleReference */; + }; + return ModuleNameModuleReference; + })(AST); + TypeScript.ModuleNameModuleReference = ModuleNameModuleReference; + + var ImportDeclaration = (function (_super) { + __extends(ImportDeclaration, _super); + function ImportDeclaration(modifiers, identifier, moduleReference) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.moduleReference = moduleReference; + identifier && (identifier.parent = this); + moduleReference && (moduleReference.parent = this); + } + ImportDeclaration.prototype.kind = function () { + return 133 /* ImportDeclaration */; + }; + + ImportDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.moduleReference, ast.moduleReference, includingPosition); + }; + return ImportDeclaration; + })(AST); + TypeScript.ImportDeclaration = ImportDeclaration; + + var ExportAssignment = (function (_super) { + __extends(ExportAssignment, _super); + function ExportAssignment(identifier) { + _super.call(this); + this.identifier = identifier; + identifier && (identifier.parent = this); + } + ExportAssignment.prototype.kind = function () { + return 134 /* ExportAssignment */; + }; + + ExportAssignment.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition); + }; + return ExportAssignment; + })(AST); + TypeScript.ExportAssignment = ExportAssignment; + + var TypeParameterList = (function (_super) { + __extends(TypeParameterList, _super); + function TypeParameterList(typeParameters) { + _super.call(this); + this.typeParameters = typeParameters; + typeParameters && (typeParameters.parent = this); + } + TypeParameterList.prototype.kind = function () { + return 229 /* TypeParameterList */; + }; + return TypeParameterList; + })(AST); + TypeScript.TypeParameterList = TypeParameterList; + + var ClassDeclaration = (function (_super) { + __extends(ClassDeclaration, _super); + function ClassDeclaration(modifiers, identifier, typeParameterList, heritageClauses, classElements, closeBraceToken) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.classElements = classElements; + this.closeBraceToken = closeBraceToken; + identifier && (identifier.parent = this); + typeParameterList && (typeParameterList.parent = this); + heritageClauses && (heritageClauses.parent = this); + classElements && (classElements.parent = this); + } + ClassDeclaration.prototype.kind = function () { + return 131 /* ClassDeclaration */; + }; + + ClassDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.classElements, ast.classElements, includingPosition) && structuralEquals(this.typeParameterList, ast.typeParameterList, includingPosition) && structuralEquals(this.heritageClauses, ast.heritageClauses, includingPosition); + }; + return ClassDeclaration; + })(AST); + TypeScript.ClassDeclaration = ClassDeclaration; + + var InterfaceDeclaration = (function (_super) { + __extends(InterfaceDeclaration, _super); + function InterfaceDeclaration(modifiers, identifier, typeParameterList, heritageClauses, body) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.body = body; + identifier && (identifier.parent = this); + typeParameterList && (typeParameterList.parent = this); + body && (body.parent = this); + heritageClauses && (heritageClauses.parent = this); + } + InterfaceDeclaration.prototype.kind = function () { + return 128 /* InterfaceDeclaration */; + }; + + InterfaceDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.body, ast.body, includingPosition) && structuralEquals(this.typeParameterList, ast.typeParameterList, includingPosition) && structuralEquals(this.heritageClauses, ast.heritageClauses, includingPosition); + }; + return InterfaceDeclaration; + })(AST); + TypeScript.InterfaceDeclaration = InterfaceDeclaration; + + var HeritageClause = (function (_super) { + __extends(HeritageClause, _super); + function HeritageClause(_nodeType, typeNames) { + _super.call(this); + this._nodeType = _nodeType; + this.typeNames = typeNames; + typeNames && (typeNames.parent = this); + } + HeritageClause.prototype.kind = function () { + return this._nodeType; + }; + + HeritageClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.typeNames, ast.typeNames, includingPosition); + }; + return HeritageClause; + })(AST); + TypeScript.HeritageClause = HeritageClause; + + var ModuleDeclaration = (function (_super) { + __extends(ModuleDeclaration, _super); + function ModuleDeclaration(modifiers, name, stringLiteral, moduleElements, endingToken) { + _super.call(this); + this.modifiers = modifiers; + this.name = name; + this.stringLiteral = stringLiteral; + this.moduleElements = moduleElements; + this.endingToken = endingToken; + name && (name.parent = this); + stringLiteral && (stringLiteral.parent = this); + moduleElements && (moduleElements.parent = this); + } + ModuleDeclaration.prototype.kind = function () { + return 130 /* ModuleDeclaration */; + }; + + ModuleDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.moduleElements, ast.moduleElements, includingPosition); + }; + return ModuleDeclaration; + })(AST); + TypeScript.ModuleDeclaration = ModuleDeclaration; + + var FunctionDeclaration = (function (_super) { + __extends(FunctionDeclaration, _super); + function FunctionDeclaration(modifiers, identifier, callSignature, block) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + identifier && (identifier.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + FunctionDeclaration.prototype.kind = function () { + return 129 /* FunctionDeclaration */; + }; + + FunctionDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.block, ast.block, includingPosition) && structuralEquals(this.callSignature, ast.callSignature, includingPosition); + }; + return FunctionDeclaration; + })(AST); + TypeScript.FunctionDeclaration = FunctionDeclaration; + + var VariableStatement = (function (_super) { + __extends(VariableStatement, _super); + function VariableStatement(modifiers, declaration) { + _super.call(this); + this.modifiers = modifiers; + this.declaration = declaration; + declaration && (declaration.parent = this); + } + VariableStatement.prototype.kind = function () { + return 148 /* VariableStatement */; + }; + + VariableStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.declaration, ast.declaration, includingPosition); + }; + return VariableStatement; + })(AST); + TypeScript.VariableStatement = VariableStatement; + + var VariableDeclaration = (function (_super) { + __extends(VariableDeclaration, _super); + function VariableDeclaration(declarators) { + _super.call(this); + this.declarators = declarators; + declarators && (declarators.parent = this); + } + VariableDeclaration.prototype.kind = function () { + return 224 /* VariableDeclaration */; + }; + + VariableDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.declarators, ast.declarators, includingPosition); + }; + return VariableDeclaration; + })(AST); + TypeScript.VariableDeclaration = VariableDeclaration; + + var VariableDeclarator = (function (_super) { + __extends(VariableDeclarator, _super); + function VariableDeclarator(propertyName, typeAnnotation, equalsValueClause) { + _super.call(this); + this.propertyName = propertyName; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + propertyName && (propertyName.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + equalsValueClause && (equalsValueClause.parent = this); + } + VariableDeclarator.prototype.kind = function () { + return 225 /* VariableDeclarator */; + }; + return VariableDeclarator; + })(AST); + TypeScript.VariableDeclarator = VariableDeclarator; + + var EqualsValueClause = (function (_super) { + __extends(EqualsValueClause, _super); + function EqualsValueClause(value) { + _super.call(this); + this.value = value; + value && (value.parent = this); + } + EqualsValueClause.prototype.kind = function () { + return 232 /* EqualsValueClause */; + }; + return EqualsValueClause; + })(AST); + TypeScript.EqualsValueClause = EqualsValueClause; + + var PrefixUnaryExpression = (function (_super) { + __extends(PrefixUnaryExpression, _super); + function PrefixUnaryExpression(_nodeType, operand) { + _super.call(this); + this._nodeType = _nodeType; + this.operand = operand; + operand && (operand.parent = this); + } + PrefixUnaryExpression.prototype.kind = function () { + return this._nodeType; + }; + + PrefixUnaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand, ast.operand, includingPosition); + }; + + PrefixUnaryExpression.prototype.isExpression = function () { + return true; + }; + return PrefixUnaryExpression; + })(AST); + TypeScript.PrefixUnaryExpression = PrefixUnaryExpression; + + var ArrayLiteralExpression = (function (_super) { + __extends(ArrayLiteralExpression, _super); + function ArrayLiteralExpression(expressions) { + _super.call(this); + this.expressions = expressions; + expressions && (expressions.parent = this); + } + ArrayLiteralExpression.prototype.kind = function () { + return 214 /* ArrayLiteralExpression */; + }; + + ArrayLiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expressions, ast.expressions, includingPosition); + }; + + ArrayLiteralExpression.prototype.isExpression = function () { + return true; + }; + return ArrayLiteralExpression; + })(AST); + TypeScript.ArrayLiteralExpression = ArrayLiteralExpression; + + var OmittedExpression = (function (_super) { + __extends(OmittedExpression, _super); + function OmittedExpression() { + _super.apply(this, arguments); + } + OmittedExpression.prototype.kind = function () { + return 223 /* OmittedExpression */; + }; + + OmittedExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + OmittedExpression.prototype.isExpression = function () { + return true; + }; + return OmittedExpression; + })(AST); + TypeScript.OmittedExpression = OmittedExpression; + + var ParenthesizedExpression = (function (_super) { + __extends(ParenthesizedExpression, _super); + function ParenthesizedExpression(openParenTrailingComments, expression) { + _super.call(this); + this.openParenTrailingComments = openParenTrailingComments; + this.expression = expression; + expression && (expression.parent = this); + } + ParenthesizedExpression.prototype.kind = function () { + return 217 /* ParenthesizedExpression */; + }; + + ParenthesizedExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + ParenthesizedExpression.prototype.isExpression = function () { + return true; + }; + return ParenthesizedExpression; + })(AST); + TypeScript.ParenthesizedExpression = ParenthesizedExpression; + + var SimpleArrowFunctionExpression = (function (_super) { + __extends(SimpleArrowFunctionExpression, _super); + function SimpleArrowFunctionExpression(identifier, block, expression) { + _super.call(this); + this.identifier = identifier; + this.block = block; + this.expression = expression; + identifier && (identifier.parent = this); + block && (block.parent = this); + expression && (expression.parent = this); + } + SimpleArrowFunctionExpression.prototype.kind = function () { + return 219 /* SimpleArrowFunctionExpression */; + }; + + SimpleArrowFunctionExpression.prototype.isExpression = function () { + return true; + }; + return SimpleArrowFunctionExpression; + })(AST); + TypeScript.SimpleArrowFunctionExpression = SimpleArrowFunctionExpression; + + var ParenthesizedArrowFunctionExpression = (function (_super) { + __extends(ParenthesizedArrowFunctionExpression, _super); + function ParenthesizedArrowFunctionExpression(callSignature, block, expression) { + _super.call(this); + this.callSignature = callSignature; + this.block = block; + this.expression = expression; + callSignature && (callSignature.parent = this); + block && (block.parent = this); + expression && (expression.parent = this); + } + ParenthesizedArrowFunctionExpression.prototype.kind = function () { + return 218 /* ParenthesizedArrowFunctionExpression */; + }; + + ParenthesizedArrowFunctionExpression.prototype.isExpression = function () { + return true; + }; + return ParenthesizedArrowFunctionExpression; + })(AST); + TypeScript.ParenthesizedArrowFunctionExpression = ParenthesizedArrowFunctionExpression; + + var QualifiedName = (function (_super) { + __extends(QualifiedName, _super); + function QualifiedName(left, right) { + _super.call(this); + this.left = left; + this.right = right; + left && (left.parent = this); + right && (right.parent = this); + } + QualifiedName.prototype.kind = function () { + return 121 /* QualifiedName */; + }; + + QualifiedName.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.left, ast.left, includingPosition) && structuralEquals(this.right, ast.right, includingPosition); + }; + return QualifiedName; + })(AST); + TypeScript.QualifiedName = QualifiedName; + + var ParameterList = (function (_super) { + __extends(ParameterList, _super); + function ParameterList(openParenTrailingComments, parameters) { + _super.call(this); + this.openParenTrailingComments = openParenTrailingComments; + this.parameters = parameters; + parameters && (parameters.parent = this); + } + ParameterList.prototype.kind = function () { + return 227 /* ParameterList */; + }; + return ParameterList; + })(AST); + TypeScript.ParameterList = ParameterList; + + var ConstructorType = (function (_super) { + __extends(ConstructorType, _super); + function ConstructorType(typeParameterList, parameterList, type) { + _super.call(this); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.type = type; + typeParameterList && (typeParameterList.parent = this); + parameterList && (parameterList.parent = this); + type && (type.parent = this); + } + ConstructorType.prototype.kind = function () { + return 125 /* ConstructorType */; + }; + return ConstructorType; + })(AST); + TypeScript.ConstructorType = ConstructorType; + + var FunctionType = (function (_super) { + __extends(FunctionType, _super); + function FunctionType(typeParameterList, parameterList, type) { + _super.call(this); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.type = type; + typeParameterList && (typeParameterList.parent = this); + parameterList && (parameterList.parent = this); + type && (type.parent = this); + } + FunctionType.prototype.kind = function () { + return 123 /* FunctionType */; + }; + return FunctionType; + })(AST); + TypeScript.FunctionType = FunctionType; + + var ObjectType = (function (_super) { + __extends(ObjectType, _super); + function ObjectType(typeMembers) { + _super.call(this); + this.typeMembers = typeMembers; + typeMembers && (typeMembers.parent = this); + } + ObjectType.prototype.kind = function () { + return 122 /* ObjectType */; + }; + + ObjectType.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.typeMembers, ast.typeMembers, includingPosition); + }; + return ObjectType; + })(AST); + TypeScript.ObjectType = ObjectType; + + var ArrayType = (function (_super) { + __extends(ArrayType, _super); + function ArrayType(type) { + _super.call(this); + this.type = type; + type && (type.parent = this); + } + ArrayType.prototype.kind = function () { + return 124 /* ArrayType */; + }; + + ArrayType.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.type, ast.type, includingPosition); + }; + return ArrayType; + })(AST); + TypeScript.ArrayType = ArrayType; + + var TypeArgumentList = (function (_super) { + __extends(TypeArgumentList, _super); + function TypeArgumentList(typeArguments) { + _super.call(this); + this.typeArguments = typeArguments; + typeArguments && (typeArguments.parent = this); + } + TypeArgumentList.prototype.kind = function () { + return 228 /* TypeArgumentList */; + }; + return TypeArgumentList; + })(AST); + TypeScript.TypeArgumentList = TypeArgumentList; + + var GenericType = (function (_super) { + __extends(GenericType, _super); + function GenericType(name, typeArgumentList) { + _super.call(this); + this.name = name; + this.typeArgumentList = typeArgumentList; + name && (name.parent = this); + typeArgumentList && (typeArgumentList.parent = this); + } + GenericType.prototype.kind = function () { + return 126 /* GenericType */; + }; + + GenericType.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.typeArgumentList, ast.typeArgumentList, includingPosition); + }; + return GenericType; + })(AST); + TypeScript.GenericType = GenericType; + + var TypeQuery = (function (_super) { + __extends(TypeQuery, _super); + function TypeQuery(name) { + _super.call(this); + this.name = name; + name && (name.parent = this); + } + TypeQuery.prototype.kind = function () { + return 127 /* TypeQuery */; + }; + + TypeQuery.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition); + }; + return TypeQuery; + })(AST); + TypeScript.TypeQuery = TypeQuery; + + var Block = (function (_super) { + __extends(Block, _super); + function Block(statements, closeBraceLeadingComments, closeBraceToken) { + _super.call(this); + this.statements = statements; + this.closeBraceLeadingComments = closeBraceLeadingComments; + this.closeBraceToken = closeBraceToken; + statements && (statements.parent = this); + } + Block.prototype.kind = function () { + return 146 /* Block */; + }; + + Block.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statements, ast.statements, includingPosition); + }; + return Block; + })(AST); + TypeScript.Block = Block; + + var Parameter = (function (_super) { + __extends(Parameter, _super); + function Parameter(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + _super.call(this); + this.dotDotDotToken = dotDotDotToken; + this.modifiers = modifiers; + this.identifier = identifier; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + identifier && (identifier.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + equalsValueClause && (equalsValueClause.parent = this); + } + Parameter.prototype.kind = function () { + return 242 /* Parameter */; + }; + return Parameter; + })(AST); + TypeScript.Parameter = Parameter; + + var MemberAccessExpression = (function (_super) { + __extends(MemberAccessExpression, _super); + function MemberAccessExpression(expression, name) { + _super.call(this); + this.expression = expression; + this.name = name; + expression && (expression.parent = this); + name && (name.parent = this); + } + MemberAccessExpression.prototype.kind = function () { + return 212 /* MemberAccessExpression */; + }; + + MemberAccessExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.name, ast.name, includingPosition); + }; + + MemberAccessExpression.prototype.isExpression = function () { + return true; + }; + return MemberAccessExpression; + })(AST); + TypeScript.MemberAccessExpression = MemberAccessExpression; + + var PostfixUnaryExpression = (function (_super) { + __extends(PostfixUnaryExpression, _super); + function PostfixUnaryExpression(_nodeType, operand) { + _super.call(this); + this._nodeType = _nodeType; + this.operand = operand; + operand && (operand.parent = this); + } + PostfixUnaryExpression.prototype.kind = function () { + return this._nodeType; + }; + + PostfixUnaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand, ast.operand, includingPosition); + }; + + PostfixUnaryExpression.prototype.isExpression = function () { + return true; + }; + return PostfixUnaryExpression; + })(AST); + TypeScript.PostfixUnaryExpression = PostfixUnaryExpression; + + var ElementAccessExpression = (function (_super) { + __extends(ElementAccessExpression, _super); + function ElementAccessExpression(expression, argumentExpression) { + _super.call(this); + this.expression = expression; + this.argumentExpression = argumentExpression; + expression && (expression.parent = this); + argumentExpression && (argumentExpression.parent = this); + } + ElementAccessExpression.prototype.kind = function () { + return 221 /* ElementAccessExpression */; + }; + + ElementAccessExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentExpression, ast.argumentExpression, includingPosition); + }; + + ElementAccessExpression.prototype.isExpression = function () { + return true; + }; + return ElementAccessExpression; + })(AST); + TypeScript.ElementAccessExpression = ElementAccessExpression; + + var InvocationExpression = (function (_super) { + __extends(InvocationExpression, _super); + function InvocationExpression(expression, argumentList) { + _super.call(this); + this.expression = expression; + this.argumentList = argumentList; + expression && (expression.parent = this); + argumentList && (argumentList.parent = this); + } + InvocationExpression.prototype.kind = function () { + return 213 /* InvocationExpression */; + }; + + InvocationExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentList, ast.argumentList, includingPosition); + }; + + InvocationExpression.prototype.isExpression = function () { + return true; + }; + return InvocationExpression; + })(AST); + TypeScript.InvocationExpression = InvocationExpression; + + var ArgumentList = (function (_super) { + __extends(ArgumentList, _super); + function ArgumentList(typeArgumentList, _arguments, closeParenToken) { + _super.call(this); + this.typeArgumentList = typeArgumentList; + this.closeParenToken = closeParenToken; + this.arguments = _arguments; + + typeArgumentList && (typeArgumentList.parent = this); + _arguments && (_arguments.parent = this); + } + ArgumentList.prototype.kind = function () { + return 226 /* ArgumentList */; + }; + return ArgumentList; + })(AST); + TypeScript.ArgumentList = ArgumentList; + + var BinaryExpression = (function (_super) { + __extends(BinaryExpression, _super); + function BinaryExpression(_nodeType, left, right) { + _super.call(this); + this._nodeType = _nodeType; + this.left = left; + this.right = right; + left && (left.parent = this); + right && (right.parent = this); + } + BinaryExpression.prototype.kind = function () { + return this._nodeType; + }; + + BinaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.left, ast.left, includingPosition) && structuralEquals(this.right, ast.right, includingPosition); + }; + + BinaryExpression.prototype.isExpression = function () { + return true; + }; + return BinaryExpression; + })(AST); + TypeScript.BinaryExpression = BinaryExpression; + + var ConditionalExpression = (function (_super) { + __extends(ConditionalExpression, _super); + function ConditionalExpression(condition, whenTrue, whenFalse) { + _super.call(this); + this.condition = condition; + this.whenTrue = whenTrue; + this.whenFalse = whenFalse; + condition && (condition.parent = this); + whenTrue && (whenTrue.parent = this); + whenFalse && (whenFalse.parent = this); + } + ConditionalExpression.prototype.kind = function () { + return 186 /* ConditionalExpression */; + }; + + ConditionalExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.whenTrue, ast.whenTrue, includingPosition) && structuralEquals(this.whenFalse, ast.whenFalse, includingPosition); + }; + + ConditionalExpression.prototype.isExpression = function () { + return true; + }; + return ConditionalExpression; + })(AST); + TypeScript.ConditionalExpression = ConditionalExpression; + + var ConstructSignature = (function (_super) { + __extends(ConstructSignature, _super); + function ConstructSignature(callSignature) { + _super.call(this); + this.callSignature = callSignature; + callSignature && (callSignature.parent = this); + } + ConstructSignature.prototype.kind = function () { + return 143 /* ConstructSignature */; + }; + return ConstructSignature; + })(AST); + TypeScript.ConstructSignature = ConstructSignature; + + var MethodSignature = (function (_super) { + __extends(MethodSignature, _super); + function MethodSignature(propertyName, questionToken, callSignature) { + _super.call(this); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.callSignature = callSignature; + propertyName && (propertyName.parent = this); + callSignature && (callSignature.parent = this); + } + MethodSignature.prototype.kind = function () { + return 145 /* MethodSignature */; + }; + return MethodSignature; + })(AST); + TypeScript.MethodSignature = MethodSignature; + + var IndexSignature = (function (_super) { + __extends(IndexSignature, _super); + function IndexSignature(parameter, typeAnnotation) { + _super.call(this); + this.parameter = parameter; + this.typeAnnotation = typeAnnotation; + parameter && (parameter.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + } + IndexSignature.prototype.kind = function () { + return 144 /* IndexSignature */; + }; + return IndexSignature; + })(AST); + TypeScript.IndexSignature = IndexSignature; + + var PropertySignature = (function (_super) { + __extends(PropertySignature, _super); + function PropertySignature(propertyName, questionToken, typeAnnotation) { + _super.call(this); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + propertyName && (propertyName.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + } + PropertySignature.prototype.kind = function () { + return 141 /* PropertySignature */; + }; + return PropertySignature; + })(AST); + TypeScript.PropertySignature = PropertySignature; + + var CallSignature = (function (_super) { + __extends(CallSignature, _super); + function CallSignature(typeParameterList, parameterList, typeAnnotation) { + _super.call(this); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + typeParameterList && (typeParameterList.parent = this); + parameterList && (parameterList.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + } + CallSignature.prototype.kind = function () { + return 142 /* CallSignature */; + }; + return CallSignature; + })(AST); + TypeScript.CallSignature = CallSignature; + + var TypeParameter = (function (_super) { + __extends(TypeParameter, _super); + function TypeParameter(identifier, constraint) { + _super.call(this); + this.identifier = identifier; + this.constraint = constraint; + identifier && (identifier.parent = this); + constraint && (constraint.parent = this); + } + TypeParameter.prototype.kind = function () { + return 238 /* TypeParameter */; + }; + + TypeParameter.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.constraint, ast.constraint, includingPosition); + }; + return TypeParameter; + })(AST); + TypeScript.TypeParameter = TypeParameter; + + var Constraint = (function (_super) { + __extends(Constraint, _super); + function Constraint(type) { + _super.call(this); + this.type = type; + type && (type.parent = this); + } + Constraint.prototype.kind = function () { + return 239 /* Constraint */; + }; + return Constraint; + })(AST); + TypeScript.Constraint = Constraint; + + var ElseClause = (function (_super) { + __extends(ElseClause, _super); + function ElseClause(statement) { + _super.call(this); + this.statement = statement; + statement && (statement.parent = this); + } + ElseClause.prototype.kind = function () { + return 235 /* ElseClause */; + }; + + ElseClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return ElseClause; + })(AST); + TypeScript.ElseClause = ElseClause; + + var IfStatement = (function (_super) { + __extends(IfStatement, _super); + function IfStatement(condition, statement, elseClause) { + _super.call(this); + this.condition = condition; + this.statement = statement; + this.elseClause = elseClause; + condition && (condition.parent = this); + statement && (statement.parent = this); + elseClause && (elseClause.parent = this); + } + IfStatement.prototype.kind = function () { + return 147 /* IfStatement */; + }; + + IfStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition) && structuralEquals(this.elseClause, ast.elseClause, includingPosition); + }; + return IfStatement; + })(AST); + TypeScript.IfStatement = IfStatement; + + var ExpressionStatement = (function (_super) { + __extends(ExpressionStatement, _super); + function ExpressionStatement(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + ExpressionStatement.prototype.kind = function () { + return 149 /* ExpressionStatement */; + }; + + ExpressionStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ExpressionStatement; + })(AST); + TypeScript.ExpressionStatement = ExpressionStatement; + + var ConstructorDeclaration = (function (_super) { + __extends(ConstructorDeclaration, _super); + function ConstructorDeclaration(callSignature, block) { + _super.call(this); + this.callSignature = callSignature; + this.block = block; + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + ConstructorDeclaration.prototype.kind = function () { + return 137 /* ConstructorDeclaration */; + }; + return ConstructorDeclaration; + })(AST); + TypeScript.ConstructorDeclaration = ConstructorDeclaration; + + var MemberFunctionDeclaration = (function (_super) { + __extends(MemberFunctionDeclaration, _super); + function MemberFunctionDeclaration(modifiers, propertyName, callSignature, block) { + _super.call(this); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + propertyName && (propertyName.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + MemberFunctionDeclaration.prototype.kind = function () { + return 135 /* MemberFunctionDeclaration */; + }; + return MemberFunctionDeclaration; + })(AST); + TypeScript.MemberFunctionDeclaration = MemberFunctionDeclaration; + + var GetAccessor = (function (_super) { + __extends(GetAccessor, _super); + function GetAccessor(modifiers, propertyName, parameterList, typeAnnotation, block) { + _super.call(this); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + this.block = block; + propertyName && (propertyName.parent = this); + parameterList && (parameterList.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + block && (block.parent = this); + } + GetAccessor.prototype.kind = function () { + return 139 /* GetAccessor */; + }; + return GetAccessor; + })(AST); + TypeScript.GetAccessor = GetAccessor; + + var SetAccessor = (function (_super) { + __extends(SetAccessor, _super); + function SetAccessor(modifiers, propertyName, parameterList, block) { + _super.call(this); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.block = block; + propertyName && (propertyName.parent = this); + parameterList && (parameterList.parent = this); + block && (block.parent = this); + } + SetAccessor.prototype.kind = function () { + return 140 /* SetAccessor */; + }; + return SetAccessor; + })(AST); + TypeScript.SetAccessor = SetAccessor; + + var MemberVariableDeclaration = (function (_super) { + __extends(MemberVariableDeclaration, _super); + function MemberVariableDeclaration(modifiers, variableDeclarator) { + _super.call(this); + this.modifiers = modifiers; + this.variableDeclarator = variableDeclarator; + variableDeclarator && (variableDeclarator.parent = this); + } + MemberVariableDeclaration.prototype.kind = function () { + return 136 /* MemberVariableDeclaration */; + }; + return MemberVariableDeclaration; + })(AST); + TypeScript.MemberVariableDeclaration = MemberVariableDeclaration; + + var IndexMemberDeclaration = (function (_super) { + __extends(IndexMemberDeclaration, _super); + function IndexMemberDeclaration(indexSignature) { + _super.call(this); + this.indexSignature = indexSignature; + indexSignature && (indexSignature.parent = this); + } + IndexMemberDeclaration.prototype.kind = function () { + return 138 /* IndexMemberDeclaration */; + }; + return IndexMemberDeclaration; + })(AST); + TypeScript.IndexMemberDeclaration = IndexMemberDeclaration; + + var ThrowStatement = (function (_super) { + __extends(ThrowStatement, _super); + function ThrowStatement(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + ThrowStatement.prototype.kind = function () { + return 157 /* ThrowStatement */; + }; + + ThrowStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ThrowStatement; + })(AST); + TypeScript.ThrowStatement = ThrowStatement; + + var ReturnStatement = (function (_super) { + __extends(ReturnStatement, _super); + function ReturnStatement(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + ReturnStatement.prototype.kind = function () { + return 150 /* ReturnStatement */; + }; + + ReturnStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ReturnStatement; + })(AST); + TypeScript.ReturnStatement = ReturnStatement; + + var ObjectCreationExpression = (function (_super) { + __extends(ObjectCreationExpression, _super); + function ObjectCreationExpression(expression, argumentList) { + _super.call(this); + this.expression = expression; + this.argumentList = argumentList; + expression && (expression.parent = this); + argumentList && (argumentList.parent = this); + } + ObjectCreationExpression.prototype.kind = function () { + return 216 /* ObjectCreationExpression */; + }; + + ObjectCreationExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentList, ast.argumentList, includingPosition); + }; + + ObjectCreationExpression.prototype.isExpression = function () { + return true; + }; + return ObjectCreationExpression; + })(AST); + TypeScript.ObjectCreationExpression = ObjectCreationExpression; + + var SwitchStatement = (function (_super) { + __extends(SwitchStatement, _super); + function SwitchStatement(expression, closeParenToken, switchClauses) { + _super.call(this); + this.expression = expression; + this.closeParenToken = closeParenToken; + this.switchClauses = switchClauses; + expression && (expression.parent = this); + switchClauses && (switchClauses.parent = this); + } + SwitchStatement.prototype.kind = function () { + return 151 /* SwitchStatement */; + }; + + SwitchStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.switchClauses, ast.switchClauses, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return SwitchStatement; + })(AST); + TypeScript.SwitchStatement = SwitchStatement; + + var CaseSwitchClause = (function (_super) { + __extends(CaseSwitchClause, _super); + function CaseSwitchClause(expression, statements) { + _super.call(this); + this.expression = expression; + this.statements = statements; + expression && (expression.parent = this); + statements && (statements.parent = this); + } + CaseSwitchClause.prototype.kind = function () { + return 233 /* CaseSwitchClause */; + }; + + CaseSwitchClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.statements, ast.statements, includingPosition); + }; + return CaseSwitchClause; + })(AST); + TypeScript.CaseSwitchClause = CaseSwitchClause; + + var DefaultSwitchClause = (function (_super) { + __extends(DefaultSwitchClause, _super); + function DefaultSwitchClause(statements) { + _super.call(this); + this.statements = statements; + statements && (statements.parent = this); + } + DefaultSwitchClause.prototype.kind = function () { + return 234 /* DefaultSwitchClause */; + }; + + DefaultSwitchClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statements, ast.statements, includingPosition); + }; + return DefaultSwitchClause; + })(AST); + TypeScript.DefaultSwitchClause = DefaultSwitchClause; + + var BreakStatement = (function (_super) { + __extends(BreakStatement, _super); + function BreakStatement(identifier) { + _super.call(this); + this.identifier = identifier; + } + BreakStatement.prototype.kind = function () { + return 152 /* BreakStatement */; + }; + + BreakStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return BreakStatement; + })(AST); + TypeScript.BreakStatement = BreakStatement; + + var ContinueStatement = (function (_super) { + __extends(ContinueStatement, _super); + function ContinueStatement(identifier) { + _super.call(this); + this.identifier = identifier; + } + ContinueStatement.prototype.kind = function () { + return 153 /* ContinueStatement */; + }; + + ContinueStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return ContinueStatement; + })(AST); + TypeScript.ContinueStatement = ContinueStatement; + + var ForStatement = (function (_super) { + __extends(ForStatement, _super); + function ForStatement(variableDeclaration, initializer, condition, incrementor, statement) { + _super.call(this); + this.variableDeclaration = variableDeclaration; + this.initializer = initializer; + this.condition = condition; + this.incrementor = incrementor; + this.statement = statement; + variableDeclaration && (variableDeclaration.parent = this); + initializer && (initializer.parent = this); + condition && (condition.parent = this); + incrementor && (incrementor.parent = this); + statement && (statement.parent = this); + } + ForStatement.prototype.kind = function () { + return 154 /* ForStatement */; + }; + + ForStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.initializer, ast.initializer, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.incrementor, ast.incrementor, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return ForStatement; + })(AST); + TypeScript.ForStatement = ForStatement; + + var ForInStatement = (function (_super) { + __extends(ForInStatement, _super); + function ForInStatement(variableDeclaration, left, expression, statement) { + _super.call(this); + this.variableDeclaration = variableDeclaration; + this.left = left; + this.expression = expression; + this.statement = statement; + variableDeclaration && (variableDeclaration.parent = this); + left && (left.parent = this); + expression && (expression.parent = this); + statement && (statement.parent = this); + } + ForInStatement.prototype.kind = function () { + return 155 /* ForInStatement */; + }; + + ForInStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.variableDeclaration, ast.variableDeclaration, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return ForInStatement; + })(AST); + TypeScript.ForInStatement = ForInStatement; + + var WhileStatement = (function (_super) { + __extends(WhileStatement, _super); + function WhileStatement(condition, statement) { + _super.call(this); + this.condition = condition; + this.statement = statement; + condition && (condition.parent = this); + statement && (statement.parent = this); + } + WhileStatement.prototype.kind = function () { + return 158 /* WhileStatement */; + }; + + WhileStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return WhileStatement; + })(AST); + TypeScript.WhileStatement = WhileStatement; + + var WithStatement = (function (_super) { + __extends(WithStatement, _super); + function WithStatement(condition, statement) { + _super.call(this); + this.condition = condition; + this.statement = statement; + condition && (condition.parent = this); + statement && (statement.parent = this); + } + WithStatement.prototype.kind = function () { + return 163 /* WithStatement */; + }; + + WithStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return WithStatement; + })(AST); + TypeScript.WithStatement = WithStatement; + + var EnumDeclaration = (function (_super) { + __extends(EnumDeclaration, _super); + function EnumDeclaration(modifiers, identifier, enumElements) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.enumElements = enumElements; + identifier && (identifier.parent = this); + enumElements && (enumElements.parent = this); + } + EnumDeclaration.prototype.kind = function () { + return 132 /* EnumDeclaration */; + }; + return EnumDeclaration; + })(AST); + TypeScript.EnumDeclaration = EnumDeclaration; + + var EnumElement = (function (_super) { + __extends(EnumElement, _super); + function EnumElement(propertyName, equalsValueClause) { + _super.call(this); + this.propertyName = propertyName; + this.equalsValueClause = equalsValueClause; + propertyName && (propertyName.parent = this); + equalsValueClause && (equalsValueClause.parent = this); + } + EnumElement.prototype.kind = function () { + return 243 /* EnumElement */; + }; + return EnumElement; + })(AST); + TypeScript.EnumElement = EnumElement; + + var CastExpression = (function (_super) { + __extends(CastExpression, _super); + function CastExpression(type, expression) { + _super.call(this); + this.type = type; + this.expression = expression; + type && (type.parent = this); + expression && (expression.parent = this); + } + CastExpression.prototype.kind = function () { + return 220 /* CastExpression */; + }; + + CastExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.type, ast.type, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + CastExpression.prototype.isExpression = function () { + return true; + }; + return CastExpression; + })(AST); + TypeScript.CastExpression = CastExpression; + + var ObjectLiteralExpression = (function (_super) { + __extends(ObjectLiteralExpression, _super); + function ObjectLiteralExpression(propertyAssignments) { + _super.call(this); + this.propertyAssignments = propertyAssignments; + propertyAssignments && (propertyAssignments.parent = this); + } + ObjectLiteralExpression.prototype.kind = function () { + return 215 /* ObjectLiteralExpression */; + }; + + ObjectLiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.propertyAssignments, ast.propertyAssignments, includingPosition); + }; + + ObjectLiteralExpression.prototype.isExpression = function () { + return true; + }; + return ObjectLiteralExpression; + })(AST); + TypeScript.ObjectLiteralExpression = ObjectLiteralExpression; + + var SimplePropertyAssignment = (function (_super) { + __extends(SimplePropertyAssignment, _super); + function SimplePropertyAssignment(propertyName, expression) { + _super.call(this); + this.propertyName = propertyName; + this.expression = expression; + propertyName && (propertyName.parent = this); + expression && (expression.parent = this); + } + SimplePropertyAssignment.prototype.kind = function () { + return 240 /* SimplePropertyAssignment */; + }; + return SimplePropertyAssignment; + })(AST); + TypeScript.SimplePropertyAssignment = SimplePropertyAssignment; + + var FunctionPropertyAssignment = (function (_super) { + __extends(FunctionPropertyAssignment, _super); + function FunctionPropertyAssignment(propertyName, callSignature, block) { + _super.call(this); + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + propertyName && (propertyName.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + FunctionPropertyAssignment.prototype.kind = function () { + return 241 /* FunctionPropertyAssignment */; + }; + return FunctionPropertyAssignment; + })(AST); + TypeScript.FunctionPropertyAssignment = FunctionPropertyAssignment; + + var FunctionExpression = (function (_super) { + __extends(FunctionExpression, _super); + function FunctionExpression(identifier, callSignature, block) { + _super.call(this); + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + identifier && (identifier.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + FunctionExpression.prototype.kind = function () { + return 222 /* FunctionExpression */; + }; + + FunctionExpression.prototype.isExpression = function () { + return true; + }; + return FunctionExpression; + })(AST); + TypeScript.FunctionExpression = FunctionExpression; + + var EmptyStatement = (function (_super) { + __extends(EmptyStatement, _super); + function EmptyStatement() { + _super.apply(this, arguments); + } + EmptyStatement.prototype.kind = function () { + return 156 /* EmptyStatement */; + }; + + EmptyStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return EmptyStatement; + })(AST); + TypeScript.EmptyStatement = EmptyStatement; + + var TryStatement = (function (_super) { + __extends(TryStatement, _super); + function TryStatement(block, catchClause, finallyClause) { + _super.call(this); + this.block = block; + this.catchClause = catchClause; + this.finallyClause = finallyClause; + block && (block.parent = this); + catchClause && (catchClause.parent = this); + finallyClause && (finallyClause.parent = this); + } + TryStatement.prototype.kind = function () { + return 159 /* TryStatement */; + }; + + TryStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.block, ast.block, includingPosition) && structuralEquals(this.catchClause, ast.catchClause, includingPosition) && structuralEquals(this.finallyClause, ast.finallyClause, includingPosition); + }; + return TryStatement; + })(AST); + TypeScript.TryStatement = TryStatement; + + var CatchClause = (function (_super) { + __extends(CatchClause, _super); + function CatchClause(identifier, typeAnnotation, block) { + _super.call(this); + this.identifier = identifier; + this.typeAnnotation = typeAnnotation; + this.block = block; + identifier && (identifier.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + block && (block.parent = this); + } + CatchClause.prototype.kind = function () { + return 236 /* CatchClause */; + }; + + CatchClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.typeAnnotation, ast.typeAnnotation, includingPosition) && structuralEquals(this.block, ast.block, includingPosition); + }; + return CatchClause; + })(AST); + TypeScript.CatchClause = CatchClause; + + var FinallyClause = (function (_super) { + __extends(FinallyClause, _super); + function FinallyClause(block) { + _super.call(this); + this.block = block; + block && (block.parent = this); + } + FinallyClause.prototype.kind = function () { + return 237 /* FinallyClause */; + }; + + FinallyClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.block, ast.block, includingPosition); + }; + return FinallyClause; + })(AST); + TypeScript.FinallyClause = FinallyClause; + + var LabeledStatement = (function (_super) { + __extends(LabeledStatement, _super); + function LabeledStatement(identifier, statement) { + _super.call(this); + this.identifier = identifier; + this.statement = statement; + identifier && (identifier.parent = this); + statement && (statement.parent = this); + } + LabeledStatement.prototype.kind = function () { + return 160 /* LabeledStatement */; + }; + + LabeledStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return LabeledStatement; + })(AST); + TypeScript.LabeledStatement = LabeledStatement; + + var DoStatement = (function (_super) { + __extends(DoStatement, _super); + function DoStatement(statement, whileKeyword, condition) { + _super.call(this); + this.statement = statement; + this.whileKeyword = whileKeyword; + this.condition = condition; + statement && (statement.parent = this); + condition && (condition.parent = this); + } + DoStatement.prototype.kind = function () { + return 161 /* DoStatement */; + }; + + DoStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition); + }; + return DoStatement; + })(AST); + TypeScript.DoStatement = DoStatement; + + var TypeOfExpression = (function (_super) { + __extends(TypeOfExpression, _super); + function TypeOfExpression(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + TypeOfExpression.prototype.kind = function () { + return 171 /* TypeOfExpression */; + }; + + TypeOfExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + TypeOfExpression.prototype.isExpression = function () { + return true; + }; + return TypeOfExpression; + })(AST); + TypeScript.TypeOfExpression = TypeOfExpression; + + var DeleteExpression = (function (_super) { + __extends(DeleteExpression, _super); + function DeleteExpression(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + DeleteExpression.prototype.kind = function () { + return 170 /* DeleteExpression */; + }; + + DeleteExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + DeleteExpression.prototype.isExpression = function () { + return true; + }; + return DeleteExpression; + })(AST); + TypeScript.DeleteExpression = DeleteExpression; + + var VoidExpression = (function (_super) { + __extends(VoidExpression, _super); + function VoidExpression(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + VoidExpression.prototype.kind = function () { + return 172 /* VoidExpression */; + }; + + VoidExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + VoidExpression.prototype.isExpression = function () { + return true; + }; + return VoidExpression; + })(AST); + TypeScript.VoidExpression = VoidExpression; + + var DebuggerStatement = (function (_super) { + __extends(DebuggerStatement, _super); + function DebuggerStatement() { + _super.apply(this, arguments); + } + DebuggerStatement.prototype.kind = function () { + return 162 /* DebuggerStatement */; + }; + return DebuggerStatement; + })(AST); + TypeScript.DebuggerStatement = DebuggerStatement; + + var Comment = (function () { + function Comment(_trivia, endsLine, _start, _end) { + this._trivia = _trivia; + this.endsLine = endsLine; + this._start = _start; + this._end = _end; + } + Comment.prototype.start = function () { + return this._start; + }; + + Comment.prototype.end = function () { + return this._end; + }; + + Comment.prototype.fullText = function () { + return this._trivia.fullText(); + }; + + Comment.prototype.kind = function () { + return this._trivia.kind(); + }; + + Comment.prototype.structuralEquals = function (ast, includingPosition) { + if (includingPosition) { + if (this.start() !== ast.start() || this.end() !== ast.end()) { + return false; + } + } + + return this._trivia.fullText() === ast._trivia.fullText() && this.endsLine === ast.endsLine; + }; + return Comment; + })(); + TypeScript.Comment = Comment; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (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 writeFileAndFolderStructure(ioHost, fileName, contents, writeByteOrderMark) { + var start = new Date().getTime(); + var path = ioHost.resolvePath(fileName); + TypeScript.ioHostResolvePathTime += new Date().getTime() - start; + + var start = new Date().getTime(); + var dirName = ioHost.dirName(path); + TypeScript.ioHostDirectoryNameTime += new Date().getTime() - start; + + var start = new Date().getTime(); + createDirectoryStructure(ioHost, dirName); + TypeScript.ioHostCreateDirectoryStructureTime += new Date().getTime() - start; + + var start = new Date().getTime(); + ioHost.writeFile(path, contents, writeByteOrderMark); + TypeScript.ioHostWriteFileTime += new Date().getTime() - start; + } + IOUtils.writeFileAndFolderStructure = writeFileAndFolderStructure; + + function throwIOError(message, error) { + var errorMessage = message; + if (error && error.message) { + errorMessage += (" " + error.message); + } + throw new Error(errorMessage); + } + IOUtils.throwIOError = throwIOError; + + function combine(prefix, suffix) { + return prefix + "/" + suffix; + } + IOUtils.combine = combine; + + 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; + })(TypeScript.IOUtils || (TypeScript.IOUtils = {})); + var IOUtils = TypeScript.IOUtils; + + TypeScript.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 { + appendFile: function (path, content) { + var txtFile = fso.OpenTextFile(path, 8, true); + txtFile.Write(content); + txtFile.Close(); + }, + readFile: function (path, codepage) { + return TypeScript.Environment.readFile(path, codepage); + }, + writeFile: function (path, contents, writeByteOrderMark) { + TypeScript.Environment.writeFile(path, contents, writeByteOrderMark); + }, + 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)) { + return { fileInformation: this.readFile(path), path: path }; + } 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(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Could_not_delete_file_0, [path]), e); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + createDirectory: function (path) { + try { + if (!this.directoryExists(path)) { + fso.CreateFolder(path); + } + } catch (e) { + IOUtils.throwIOError(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Could_not_create_directory_0, [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(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Error_while_executing_file_0, [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 { + appendFile: function (path, content) { + _fs.appendFileSync(path, content); + }, + readFile: function (file, codepage) { + return TypeScript.Environment.readFile(file, codepage); + }, + writeFile: function (path, contents, writeByteOrderMark) { + TypeScript.Environment.writeFile(path, contents, writeByteOrderMark); + }, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + IOUtils.throwIOError(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Could_not_delete_file_0, [path]), e); + } + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + dir: function dir(path, spec, options) { + options = options || {}; + + function filesInFolder(folder) { + var paths = []; + + try { + 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]); + } + } + } catch (err) { + } + + return paths; + } + + return filesInFolder(path); + }, + createDirectory: function (path) { + try { + if (!this.directoryExists(path)) { + _fs.mkdirSync(path); + } + } catch (e) { + IOUtils.throwIOError(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Could_not_create_directory_0, [path]), e); + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); + }, + resolvePath: function (path) { + return _path.resolve(path); + }, + dirName: function (path) { + var dirPath = _path.dirname(path); + + if (dirPath === path) { + dirPath = null; + } + + return dirPath; + }, + findFile: function (rootPath, partialFilePath) { + var path = rootPath + "/" + partialFilePath; + + while (true) { + if (_fs.existsSync(path)) { + return { fileInformation: this.readFile(path), path: path }; + } 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: function (code) { + var stderrFlushed = process.stderr.write(''); + var stdoutFlushed = process.stdout.write(''); + process.stderr.on('drain', function () { + stderrFlushed = true; + if (stdoutFlushed) { + process.exit(code); + } + }); + process.stdout.on('drain', function () { + stdoutFlushed = true; + if (stderrFlushed) { + process.exit(code); + } + }); + setTimeout(function () { + process.exit(code); + }, 5); + } + }; + } + ; + + if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") + return getWindowsScriptHostIO(); + else if (typeof module !== 'undefined' && module.exports) + return getNodeIO(); + else + return null; + })(); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var OptionsParser = (function () { + function OptionsParser(host, version) { + this.host = host; + this.version = version; + this.DEFAULT_SHORT_FLAG = "-"; + this.DEFAULT_LONG_FLAG = "--"; + this.printedVersion = false; + this.unnamed = []; + this.options = []; + } + OptionsParser.prototype.findOption = function (arg) { + var upperCaseArg = arg && arg.toUpperCase(); + + for (var i = 0; i < this.options.length; i++) { + var current = this.options[i]; + + if (upperCaseArg === (current.short && current.short.toUpperCase()) || upperCaseArg === (current.name && current.name.toUpperCase())) { + return current; + } + } + + return null; + }; + + OptionsParser.prototype.printUsage = function () { + this.printVersion(); + + var optionsWord = TypeScript.getLocalizedText(TypeScript.DiagnosticCode.options, null); + var fileWord = TypeScript.getLocalizedText(TypeScript.DiagnosticCode.file1, null); + var tscSyntax = "tsc [" + optionsWord + "] [" + fileWord + " ..]"; + var syntaxHelp = TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Syntax_0, [tscSyntax]); + this.host.printLine(syntaxHelp); + this.host.printLine(""); + this.host.printLine(TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Examples, null) + " tsc hello.ts"); + this.host.printLine(" tsc --out foo.js foo.ts"); + this.host.printLine(" tsc @args.txt"); + this.host.printLine(""); + this.host.printLine(TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Options, null)); + + var output = []; + var maxLength = 0; + var i = 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 (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 ? (" " + TypeScript.getLocalizedText(option.type, null)) : ""; + + if (option.short) { + usageString += this.DEFAULT_SHORT_FLAG + option.short + type + ", "; + } + + usageString += this.DEFAULT_LONG_FLAG + option.name + type; + + output.push([usageString, TypeScript.getLocalizedText(option.usage.locCode, option.usage.args)]); + + if (usageString.length > maxLength) { + maxLength = usageString.length; + } + } + + var fileDescription = TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Insert_command_line_options_and_files_from_a_file, null); + output.push([" @<" + fileWord + ">", fileDescription]); + + for (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.printVersion = function () { + if (!this.printedVersion) { + this.host.printLine(TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Version_0, [this.version])); + this.printedVersion = true; + } + }; + + 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], null).contents); + } else { + var arg = match[2]; + var option = this.findOption(arg); + + if (option === null) { + this.host.printLine(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Unknown_option_0, [arg])); + this.host.printLine(TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Use_the_0_flag_to_see_options, ["--help"])); + } else { + if (!option.flag) { + value = consume(); + if (value === undefined) { + this.host.printLine(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Option_0_specified_without_1, [arg, TypeScript.getLocalizedText(option.type, null)])); + this.host.printLine(TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Use_the_0_flag_to_see_options, ["--help"])); + continue; + } + } + + option.set(value); + } + } + } else { + this.unnamed.push(current); + } + } + }; + return OptionsParser; + })(); + TypeScript.OptionsParser = OptionsParser; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceFile = (function () { + function SourceFile(scriptSnapshot, byteOrderMark) { + this.scriptSnapshot = scriptSnapshot; + this.byteOrderMark = byteOrderMark; + } + return SourceFile; + })(); + + var DiagnosticsLogger = (function () { + function DiagnosticsLogger(ioHost) { + this.ioHost = ioHost; + } + DiagnosticsLogger.prototype.information = function () { + return false; + }; + DiagnosticsLogger.prototype.debug = function () { + return false; + }; + DiagnosticsLogger.prototype.warning = function () { + return false; + }; + DiagnosticsLogger.prototype.error = function () { + return false; + }; + DiagnosticsLogger.prototype.fatal = function () { + return false; + }; + DiagnosticsLogger.prototype.log = function (s) { + this.ioHost.stdout.WriteLine(s); + }; + return DiagnosticsLogger; + })(); + + var FileLogger = (function () { + function FileLogger(ioHost) { + this.ioHost = ioHost; + var file = "tsc." + Date.now() + ".log"; + + this.fileName = this.ioHost.resolvePath(file); + } + FileLogger.prototype.information = function () { + return false; + }; + FileLogger.prototype.debug = function () { + return false; + }; + FileLogger.prototype.warning = function () { + return false; + }; + FileLogger.prototype.error = function () { + return false; + }; + FileLogger.prototype.fatal = function () { + return false; + }; + FileLogger.prototype.log = function (s) { + this.ioHost.appendFile(this.fileName, s + '\r\n'); + }; + return FileLogger; + })(); + + var BatchCompiler = (function () { + function BatchCompiler(ioHost) { + this.ioHost = ioHost; + this.compilerVersion = "1.0.1.0"; + this.inputFiles = []; + this.resolvedFiles = []; + this.fileNameToSourceFile = new TypeScript.StringHashTable(); + this.hasErrors = false; + this.logger = null; + this.fileExistsCache = TypeScript.createIntrinsicsObject(); + this.resolvePathCache = TypeScript.createIntrinsicsObject(); + } + BatchCompiler.prototype.batchCompile = function () { + var _this = this; + var start = new Date().getTime(); + + TypeScript.CompilerDiagnostics.diagnosticWriter = { Alert: function (s) { + _this.ioHost.printLine(s); + } }; + + if (this.parseOptions()) { + if (this.compilationSettings.createFileLog()) { + this.logger = new FileLogger(this.ioHost); + } else if (this.compilationSettings.gatherDiagnostics()) { + this.logger = new DiagnosticsLogger(this.ioHost); + } else { + this.logger = new TypeScript.NullLogger(); + } + + if (this.compilationSettings.watch()) { + this.watchFiles(); + return; + } + + this.resolve(); + + this.compile(); + + if (this.compilationSettings.createFileLog()) { + this.logger.log("Compilation settings:"); + this.logger.log(" propagateEnumConstants " + this.compilationSettings.propagateEnumConstants()); + this.logger.log(" removeComments " + this.compilationSettings.removeComments()); + this.logger.log(" watch " + this.compilationSettings.watch()); + this.logger.log(" noResolve " + this.compilationSettings.noResolve()); + this.logger.log(" noImplicitAny " + this.compilationSettings.noImplicitAny()); + this.logger.log(" nolib " + this.compilationSettings.noLib()); + this.logger.log(" target " + this.compilationSettings.codeGenTarget()); + this.logger.log(" module " + this.compilationSettings.moduleGenTarget()); + this.logger.log(" out " + this.compilationSettings.outFileOption()); + this.logger.log(" outDir " + this.compilationSettings.outDirOption()); + this.logger.log(" sourcemap " + this.compilationSettings.mapSourceFiles()); + this.logger.log(" mapRoot " + this.compilationSettings.mapRoot()); + this.logger.log(" sourceroot " + this.compilationSettings.sourceRoot()); + this.logger.log(" declaration " + this.compilationSettings.generateDeclarationFiles()); + this.logger.log(" useCaseSensitiveFileResolution " + this.compilationSettings.useCaseSensitiveFileResolution()); + this.logger.log(" diagnostics " + this.compilationSettings.gatherDiagnostics()); + this.logger.log(" codepage " + this.compilationSettings.codepage()); + + this.logger.log(""); + + this.logger.log("Input files:"); + this.inputFiles.forEach(function (file) { + _this.logger.log(" " + file); + }); + + this.logger.log(""); + + this.logger.log("Resolved Files:"); + this.resolvedFiles.forEach(function (file) { + file.importedFiles.forEach(function (file) { + _this.logger.log(" " + file); + }); + file.referencedFiles.forEach(function (file) { + _this.logger.log(" " + file); + }); + }); + } + + if (this.compilationSettings.gatherDiagnostics()) { + this.logger.log(""); + this.logger.log("File resolution time: " + TypeScript.fileResolutionTime); + this.logger.log(" file read: " + TypeScript.fileResolutionIOTime); + this.logger.log(" scan imports: " + TypeScript.fileResolutionScanImportsTime); + this.logger.log(" import search: " + TypeScript.fileResolutionImportFileSearchTime); + this.logger.log(" get lib.d.ts: " + TypeScript.fileResolutionGetDefaultLibraryTime); + + this.logger.log("SyntaxTree parse time: " + TypeScript.syntaxTreeParseTime); + this.logger.log("Syntax Diagnostics time: " + TypeScript.syntaxDiagnosticsTime); + this.logger.log("AST translation time: " + TypeScript.astTranslationTime); + this.logger.log(""); + this.logger.log("Type check time: " + TypeScript.typeCheckTime); + this.logger.log(""); + this.logger.log("Emit time: " + TypeScript.emitTime); + this.logger.log("Declaration emit time: " + TypeScript.declarationEmitTime); + + this.logger.log("Total number of symbols created: " + TypeScript.pullSymbolID); + this.logger.log("Specialized types created: " + TypeScript.nSpecializationsCreated); + this.logger.log("Specialized signatures created: " + TypeScript.nSpecializedSignaturesCreated); + + this.logger.log(" IsExternallyVisibleTime: " + TypeScript.declarationEmitIsExternallyVisibleTime); + this.logger.log(" TypeSignatureTime: " + TypeScript.declarationEmitTypeSignatureTime); + this.logger.log(" GetBoundDeclTypeTime: " + TypeScript.declarationEmitGetBoundDeclTypeTime); + this.logger.log(" IsOverloadedCallSignatureTime: " + TypeScript.declarationEmitIsOverloadedCallSignatureTime); + this.logger.log(" FunctionDeclarationGetSymbolTime: " + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime); + this.logger.log(" GetBaseTypeTime: " + TypeScript.declarationEmitGetBaseTypeTime); + this.logger.log(" GetAccessorFunctionTime: " + TypeScript.declarationEmitGetAccessorFunctionTime); + this.logger.log(" GetTypeParameterSymbolTime: " + TypeScript.declarationEmitGetTypeParameterSymbolTime); + this.logger.log(" GetImportDeclarationSymbolTime: " + TypeScript.declarationEmitGetImportDeclarationSymbolTime); + + this.logger.log("Emit write file time: " + TypeScript.emitWriteFileTime); + + this.logger.log("Compiler resolve path time: " + TypeScript.compilerResolvePathTime); + this.logger.log("Compiler directory name time: " + TypeScript.compilerDirectoryNameTime); + this.logger.log("Compiler directory exists time: " + TypeScript.compilerDirectoryExistsTime); + this.logger.log("Compiler file exists time: " + TypeScript.compilerFileExistsTime); + + this.logger.log("IO host resolve path time: " + TypeScript.ioHostResolvePathTime); + this.logger.log("IO host directory name time: " + TypeScript.ioHostDirectoryNameTime); + this.logger.log("IO host create directory structure time: " + TypeScript.ioHostCreateDirectoryStructureTime); + this.logger.log("IO host write file time: " + TypeScript.ioHostWriteFileTime); + + this.logger.log("Node make directory time: " + TypeScript.nodeMakeDirectoryTime); + this.logger.log("Node writeFileSync time: " + TypeScript.nodeWriteFileSyncTime); + this.logger.log("Node createBuffer time: " + TypeScript.nodeCreateBufferTime); + } + } + + this.ioHost.quit(this.hasErrors ? 1 : 0); + }; + + BatchCompiler.prototype.resolve = function () { + var _this = this; + var includeDefaultLibrary = !this.compilationSettings.noLib(); + var resolvedFiles = []; + + var start = new Date().getTime(); + + if (!this.compilationSettings.noResolve()) { + var resolutionResults = TypeScript.ReferenceResolver.resolve(this.inputFiles, this, this.compilationSettings.useCaseSensitiveFileResolution()); + resolvedFiles = resolutionResults.resolvedFiles; + + includeDefaultLibrary = !this.compilationSettings.noLib() && !resolutionResults.seenNoDefaultLibTag; + + resolutionResults.diagnostics.forEach(function (d) { + return _this.addDiagnostic(d); + }); + } else { + for (var i = 0, n = this.inputFiles.length; i < n; i++) { + var inputFile = this.inputFiles[i]; + var referencedFiles = []; + var importedFiles = []; + + if (this.compilationSettings.generateDeclarationFiles()) { + var references = TypeScript.getReferencedFiles(inputFile, this.getScriptSnapshot(inputFile)); + for (var j = 0; j < references.length; j++) { + referencedFiles.push(references[j].path); + } + + inputFile = this.resolvePath(inputFile); + } + + resolvedFiles.push({ + path: inputFile, + referencedFiles: referencedFiles, + importedFiles: importedFiles + }); + } + } + + var defaultLibStart = new Date().getTime(); + if (includeDefaultLibrary) { + var libraryResolvedFile = { + path: this.getDefaultLibraryFilePath(), + referencedFiles: [], + importedFiles: [] + }; + + resolvedFiles = [libraryResolvedFile].concat(resolvedFiles); + } + TypeScript.fileResolutionGetDefaultLibraryTime += new Date().getTime() - defaultLibStart; + + this.resolvedFiles = resolvedFiles; + + TypeScript.fileResolutionTime = new Date().getTime() - start; + }; + + BatchCompiler.prototype.compile = function () { + var _this = this; + var compiler = new TypeScript.TypeScriptCompiler(this.logger, this.compilationSettings); + + this.resolvedFiles.forEach(function (resolvedFile) { + var sourceFile = _this.getSourceFile(resolvedFile.path); + compiler.addFile(resolvedFile.path, sourceFile.scriptSnapshot, sourceFile.byteOrderMark, 0, false, resolvedFile.referencedFiles); + }); + + for (var it = compiler.compile(function (path) { + return _this.resolvePath(path); + }); it.moveNext();) { + var result = it.current(); + + result.diagnostics.forEach(function (d) { + return _this.addDiagnostic(d); + }); + if (!this.tryWriteOutputFiles(result.outputFiles)) { + return; + } + } + }; + + BatchCompiler.prototype.parseOptions = function () { + var _this = this; + var opts = new TypeScript.OptionsParser(this.ioHost, this.compilerVersion); + + var mutableSettings = new TypeScript.CompilationSettings(); + opts.option('out', { + usage: { + locCode: TypeScript.DiagnosticCode.Concatenate_and_emit_output_to_single_file, + args: null + }, + type: TypeScript.DiagnosticCode.file2, + set: function (str) { + mutableSettings.outFileOption = str; + } + }); + + opts.option('outDir', { + usage: { + locCode: TypeScript.DiagnosticCode.Redirect_output_structure_to_the_directory, + args: null + }, + type: TypeScript.DiagnosticCode.DIRECTORY, + set: function (str) { + mutableSettings.outDirOption = str; + } + }); + + opts.flag('sourcemap', { + usage: { + locCode: TypeScript.DiagnosticCode.Generates_corresponding_0_file, + args: ['.map'] + }, + set: function () { + mutableSettings.mapSourceFiles = true; + } + }); + + opts.option('mapRoot', { + usage: { + locCode: TypeScript.DiagnosticCode.Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, + args: null + }, + type: TypeScript.DiagnosticCode.LOCATION, + set: function (str) { + mutableSettings.mapRoot = str; + } + }); + + opts.option('sourceRoot', { + usage: { + locCode: TypeScript.DiagnosticCode.Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, + args: null + }, + type: TypeScript.DiagnosticCode.LOCATION, + set: function (str) { + mutableSettings.sourceRoot = str; + } + }); + + opts.flag('declaration', { + usage: { + locCode: TypeScript.DiagnosticCode.Generates_corresponding_0_file, + args: ['.d.ts'] + }, + set: function () { + mutableSettings.generateDeclarationFiles = true; + } + }, 'd'); + + if (this.ioHost.watchFile) { + opts.flag('watch', { + usage: { + locCode: TypeScript.DiagnosticCode.Watch_input_files, + args: null + }, + set: function () { + mutableSettings.watch = true; + } + }, 'w'); + } + + opts.flag('propagateEnumConstants', { + experimental: true, + set: function () { + mutableSettings.propagateEnumConstants = true; + } + }); + + opts.flag('removeComments', { + usage: { + locCode: TypeScript.DiagnosticCode.Do_not_emit_comments_to_output, + args: null + }, + set: function () { + mutableSettings.removeComments = true; + } + }); + + opts.flag('noResolve', { + experimental: true, + usage: { + locCode: TypeScript.DiagnosticCode.Skip_resolution_and_preprocessing, + args: null + }, + set: function () { + mutableSettings.noResolve = true; + } + }); + + opts.flag('noLib', { + experimental: true, + set: function () { + mutableSettings.noLib = true; + } + }); + + opts.flag('diagnostics', { + experimental: true, + set: function () { + mutableSettings.gatherDiagnostics = true; + } + }); + + opts.flag('logFile', { + experimental: true, + set: function () { + mutableSettings.createFileLog = true; + } + }); + + opts.option('target', { + usage: { + locCode: TypeScript.DiagnosticCode.Specify_ECMAScript_target_version_0_default_or_1, + args: ['ES3', 'ES5'] + }, + type: TypeScript.DiagnosticCode.VERSION, + set: function (type) { + type = type.toLowerCase(); + + if (type === 'es3') { + mutableSettings.codeGenTarget = 0 /* EcmaScript3 */; + } else if (type === 'es5') { + mutableSettings.codeGenTarget = 1 /* EcmaScript5 */; + } else { + _this.addDiagnostic(new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.ECMAScript_target_version_0_not_supported_Specify_a_valid_target_version_1_default_or_2, [type, "ES3", "ES5"])); + } + } + }, 't'); + + opts.option('module', { + usage: { + locCode: TypeScript.DiagnosticCode.Specify_module_code_generation_0_or_1, + args: ['commonjs', 'amd'] + }, + type: TypeScript.DiagnosticCode.KIND, + set: function (type) { + type = type.toLowerCase(); + + if (type === 'commonjs') { + mutableSettings.moduleGenTarget = 1 /* Synchronous */; + } else if (type === 'amd') { + mutableSettings.moduleGenTarget = 2 /* Asynchronous */; + } else { + _this.addDiagnostic(new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Module_code_generation_0_not_supported, [type])); + } + } + }, 'm'); + + var needsHelp = false; + opts.flag('help', { + usage: { + locCode: TypeScript.DiagnosticCode.Print_this_message, + args: null + }, + set: function () { + needsHelp = true; + } + }, 'h'); + + opts.flag('useCaseSensitiveFileResolution', { + experimental: true, + set: function () { + mutableSettings.useCaseSensitiveFileResolution = true; + } + }); + var shouldPrintVersionOnly = false; + opts.flag('version', { + usage: { + locCode: TypeScript.DiagnosticCode.Print_the_compiler_s_version_0, + args: [this.compilerVersion] + }, + set: function () { + shouldPrintVersionOnly = true; + } + }, 'v'); + + var locale = null; + opts.option('locale', { + experimental: true, + usage: { + locCode: TypeScript.DiagnosticCode.Specify_locale_for_errors_and_messages_For_example_0_or_1, + args: ['en', 'ja-jp'] + }, + type: TypeScript.DiagnosticCode.STRING, + set: function (value) { + locale = value; + } + }); + + opts.flag('noImplicitAny', { + usage: { + locCode: TypeScript.DiagnosticCode.Warn_on_expressions_and_declarations_with_an_implied_any_type, + args: null + }, + set: function () { + mutableSettings.noImplicitAny = true; + } + }); + + if (TypeScript.Environment.supportsCodePage()) { + opts.option('codepage', { + usage: { + locCode: TypeScript.DiagnosticCode.Specify_the_codepage_to_use_when_opening_source_files, + args: null + }, + type: TypeScript.DiagnosticCode.NUMBER, + set: function (arg) { + mutableSettings.codepage = parseInt(arg, 10); + } + }); + } + + opts.parse(this.ioHost.arguments); + + this.compilationSettings = TypeScript.ImmutableCompilationSettings.fromCompilationSettings(mutableSettings); + + if (locale) { + if (!this.setLocale(locale)) { + return false; + } + } + + this.inputFiles.push.apply(this.inputFiles, opts.unnamed); + + if (shouldPrintVersionOnly) { + opts.printVersion(); + return false; + } else if (this.inputFiles.length === 0 || needsHelp) { + opts.printUsage(); + return false; + } + + return !this.hasErrors; + }; + + BatchCompiler.prototype.setLocale = function (locale) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + this.addDiagnostic(new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, ['en', 'ja-jp'])); + return false; + } + + var language = matchResult[1]; + var territory = matchResult[3]; + + if (!this.setLanguageAndTerritory(language, territory) && !this.setLanguageAndTerritory(language, null)) { + this.addDiagnostic(new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Unsupported_locale_0, [locale])); + return false; + } + + return true; + }; + + BatchCompiler.prototype.setLanguageAndTerritory = function (language, territory) { + var compilerFilePath = this.ioHost.getExecutingFilePath(); + var containingDirectoryPath = this.ioHost.dirName(compilerFilePath); + + var filePath = TypeScript.IOUtils.combine(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + + filePath = this.resolvePath(TypeScript.IOUtils.combine(filePath, "diagnosticMessages.generated.json")); + + if (!this.fileExists(filePath)) { + return false; + } + + var fileContents = this.ioHost.readFile(filePath, this.compilationSettings.codepage()); + TypeScript.LocalizedDiagnosticMessages = JSON.parse(fileContents.contents); + return true; + }; + + BatchCompiler.prototype.watchFiles = function () { + var _this = this; + if (!this.ioHost.watchFile) { + this.addDiagnostic(new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Current_host_does_not_support_0_option, ['-w[atch]'])); + return; + } + + var lastResolvedFileSet = []; + var watchers = {}; + var firstTime = true; + + 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.hasErrors = false; + + _this.fileNameToSourceFile = new TypeScript.StringHashTable(); + + _this.resolve(); + + var oldFiles = lastResolvedFileSet; + var newFiles = _this.resolvedFiles.map(function (resolvedFile) { + return resolvedFile.path; + }).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 (k = j; k < newFiles.length; k++) { + addWatcher(newFiles[k]); + } + + lastResolvedFileSet = newFiles; + + if (!firstTime) { + var fileNames = ""; + for (var k = 0; k < lastResolvedFileSet.length; k++) { + fileNames += TypeScript.Environment.newLine + " " + lastResolvedFileSet[k]; + } + _this.ioHost.printLine(TypeScript.getLocalizedText(TypeScript.DiagnosticCode.NL_Recompiling_0, [fileNames])); + } else { + firstTime = false; + } + + _this.compile(); + }; + + this.ioHost.stderr = this.ioHost.stdout; + + onWatchedFileChange(); + }; + + BatchCompiler.prototype.getSourceFile = function (fileName) { + var sourceFile = this.fileNameToSourceFile.lookup(fileName); + if (!sourceFile) { + var fileInformation; + + try { + fileInformation = this.ioHost.readFile(fileName, this.compilationSettings.codepage()); + } catch (e) { + this.addDiagnostic(new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Cannot_read_file_0_1, [fileName, e.message])); + fileInformation = new TypeScript.FileInformation("", 0 /* None */); + } + + var snapshot = TypeScript.ScriptSnapshot.fromString(fileInformation.contents); + var sourceFile = new SourceFile(snapshot, fileInformation.byteOrderMark); + this.fileNameToSourceFile.add(fileName, sourceFile); + } + + return sourceFile; + }; + + BatchCompiler.prototype.getDefaultLibraryFilePath = function () { + var compilerFilePath = this.ioHost.getExecutingFilePath(); + var containingDirectoryPath = this.ioHost.dirName(compilerFilePath); + var libraryFilePath = this.resolvePath(TypeScript.IOUtils.combine(containingDirectoryPath, "lib.d.ts")); + + return libraryFilePath; + }; + + BatchCompiler.prototype.getScriptSnapshot = function (fileName) { + return this.getSourceFile(fileName).scriptSnapshot; + }; + + BatchCompiler.prototype.resolveRelativePath = function (path, directory) { + var start = new Date().getTime(); + + var unQuotedPath = TypeScript.stripStartAndEndQuotes(path); + var normalizedPath; + + if (TypeScript.isRooted(unQuotedPath) || !directory) { + normalizedPath = unQuotedPath; + } else { + normalizedPath = TypeScript.IOUtils.combine(directory, unQuotedPath); + } + + normalizedPath = this.resolvePath(normalizedPath); + + normalizedPath = TypeScript.switchToForwardSlashes(normalizedPath); + + return normalizedPath; + }; + + BatchCompiler.prototype.fileExists = function (path) { + var exists = this.fileExistsCache[path]; + if (exists === undefined) { + var start = new Date().getTime(); + exists = this.ioHost.fileExists(path); + this.fileExistsCache[path] = exists; + TypeScript.compilerFileExistsTime += new Date().getTime() - start; + } + + return exists; + }; + + BatchCompiler.prototype.getParentDirectory = function (path) { + var start = new Date().getTime(); + var result = this.ioHost.dirName(path); + TypeScript.compilerDirectoryNameTime += new Date().getTime() - start; + + return result; + }; + + BatchCompiler.prototype.addDiagnostic = function (diagnostic) { + var _this = this; + var diagnosticInfo = diagnostic.info(); + if (diagnosticInfo.category === 1 /* Error */) { + this.hasErrors = true; + } + + this.ioHost.stderr.Write(TypeScript.TypeScriptCompiler.getFullDiagnosticText(diagnostic, function (path) { + return _this.resolvePath(path); + })); + }; + + BatchCompiler.prototype.tryWriteOutputFiles = function (outputFiles) { + for (var i = 0, n = outputFiles.length; i < n; i++) { + var outputFile = outputFiles[i]; + + try { + this.writeFile(outputFile.name, outputFile.text, outputFile.writeByteOrderMark); + } catch (e) { + this.addDiagnostic(new TypeScript.Diagnostic(outputFile.name, null, 0, 0, TypeScript.DiagnosticCode.Emit_Error_0, [e.message])); + return false; + } + } + + return true; + }; + + BatchCompiler.prototype.writeFile = function (fileName, contents, writeByteOrderMark) { + var start = new Date().getTime(); + TypeScript.IOUtils.writeFileAndFolderStructure(this.ioHost, fileName, contents, writeByteOrderMark); + TypeScript.emitWriteFileTime += new Date().getTime() - start; + }; + + BatchCompiler.prototype.directoryExists = function (path) { + var start = new Date().getTime(); + var result = this.ioHost.directoryExists(path); + TypeScript.compilerDirectoryExistsTime += new Date().getTime() - start; + return result; + }; + + BatchCompiler.prototype.resolvePath = function (path) { + var cachedValue = this.resolvePathCache[path]; + if (!cachedValue) { + var start = new Date().getTime(); + cachedValue = this.ioHost.resolvePath(path); + this.resolvePathCache[path] = cachedValue; + TypeScript.compilerResolvePathTime += new Date().getTime() - start; + } + + return cachedValue; + }; + return BatchCompiler; + })(); + TypeScript.BatchCompiler = BatchCompiler; + + var batch = new TypeScript.BatchCompiler(TypeScript.IO); + batch.batchCompile(); +})(TypeScript || (TypeScript = {})); diff --git a/_infrastructure/tests/typescript/1.0.1/typescript.js b/_infrastructure/tests/typescript/1.0.1/typescript.js new file mode 100644 index 0000000000..bc994ab347 --- /dev/null +++ b/_infrastructure/tests/typescript/1.0.1/typescript.js @@ -0,0 +1,61516 @@ +/*! ***************************************************************************** +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) { + TypeScript.DiagnosticCode = { + error_TS_0_1: "error TS{0}: {1}", + warning_TS_0_1: "warning TS{0}: {1}", + Unrecognized_escape_sequence: "Unrecognized escape sequence.", + Unexpected_character_0: "Unexpected character {0}.", + Missing_close_quote_character: "Missing close quote character.", + Identifier_expected: "Identifier expected.", + _0_keyword_expected: "'{0}' keyword expected.", + _0_expected: "'{0}' expected.", + Identifier_expected_0_is_a_keyword: "Identifier expected; '{0}' is a keyword.", + Automatic_semicolon_insertion_not_allowed: "Automatic semicolon insertion not allowed.", + Unexpected_token_0_expected: "Unexpected token; '{0}' expected.", + Trailing_separator_not_allowed: "Trailing separator not allowed.", + AsteriskSlash_expected: "'*/' expected.", + public_or_private_modifier_must_precede_static: "'public' or 'private' modifier must precede 'static'.", + Unexpected_token: "Unexpected token.", + Catch_clause_parameter_cannot_have_a_type_annotation: "Catch clause parameter cannot have a type annotation.", + Rest_parameter_must_be_last_in_list: "Rest parameter must be last in list.", + Parameter_cannot_have_question_mark_and_initializer: "Parameter cannot have question mark and initializer.", + Required_parameter_cannot_follow_optional_parameter: "Required parameter cannot follow optional parameter.", + Index_signatures_cannot_have_rest_parameters: "Index signatures cannot have rest parameters.", + Index_signature_parameter_cannot_have_accessibility_modifiers: "Index signature parameter cannot have accessibility modifiers.", + Index_signature_parameter_cannot_have_a_question_mark: "Index signature parameter cannot have a question mark.", + Index_signature_parameter_cannot_have_an_initializer: "Index signature parameter cannot have an initializer.", + Index_signature_must_have_a_type_annotation: "Index signature must have a type annotation.", + Index_signature_parameter_must_have_a_type_annotation: "Index signature parameter must have a type annotation.", + Index_signature_parameter_type_must_be_string_or_number: "Index signature parameter type must be 'string' or 'number'.", + extends_clause_already_seen: "'extends' clause already seen.", + extends_clause_must_precede_implements_clause: "'extends' clause must precede 'implements' clause.", + Classes_can_only_extend_a_single_class: "Classes can only extend a single class.", + implements_clause_already_seen: "'implements' clause already seen.", + Accessibility_modifier_already_seen: "Accessibility modifier already seen.", + _0_modifier_must_precede_1_modifier: "'{0}' modifier must precede '{1}' modifier.", + _0_modifier_already_seen: "'{0}' modifier already seen.", + _0_modifier_cannot_appear_on_a_class_element: "'{0}' modifier cannot appear on a class element.", + Interface_declaration_cannot_have_implements_clause: "Interface declaration cannot have 'implements' clause.", + super_invocation_cannot_have_type_arguments: "'super' invocation cannot have type arguments.", + Only_ambient_modules_can_use_quoted_names: "Only ambient modules can use quoted names.", + Statements_are_not_allowed_in_ambient_contexts: "Statements are not allowed in ambient contexts.", + Implementations_are_not_allowed_in_ambient_contexts: "Implementations are not allowed in ambient contexts.", + declare_modifier_not_allowed_for_code_already_in_an_ambient_context: "'declare' modifier not allowed for code already in an ambient context.", + Initializers_are_not_allowed_in_ambient_contexts: "Initializers are not allowed in ambient contexts.", + Parameter_property_declarations_can_only_be_used_in_a_non_ambient_constructor_declaration: "Parameter property declarations can only be used in a non-ambient constructor declaration.", + Function_implementation_expected: "Function implementation expected.", + Constructor_implementation_expected: "Constructor implementation expected.", + Function_overload_name_must_be_0: "Function overload name must be '{0}'.", + _0_modifier_cannot_appear_on_a_module_element: "'{0}' modifier cannot appear on a module element.", + declare_modifier_cannot_appear_on_an_interface_declaration: "'declare' modifier cannot appear on an interface declaration.", + declare_modifier_required_for_top_level_element: "'declare' modifier required for top level element.", + Rest_parameter_cannot_be_optional: "Rest parameter cannot be optional.", + Rest_parameter_cannot_have_an_initializer: "Rest parameter cannot have an initializer.", + set_accessor_must_have_one_and_only_one_parameter: "'set' accessor must have one and only one parameter.", + set_accessor_parameter_cannot_be_optional: "'set' accessor parameter cannot be optional.", + set_accessor_parameter_cannot_have_an_initializer: "'set' accessor parameter cannot have an initializer.", + set_accessor_cannot_have_rest_parameter: "'set' accessor cannot have rest parameter.", + get_accessor_cannot_have_parameters: "'get' accessor cannot have parameters.", + Modifiers_cannot_appear_here: "Modifiers cannot appear here.", + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: "Accessors are only available when targeting ECMAScript 5 and higher.", + Class_name_cannot_be_0: "Class name cannot be '{0}'.", + Interface_name_cannot_be_0: "Interface name cannot be '{0}'.", + Enum_name_cannot_be_0: "Enum name cannot be '{0}'.", + Module_name_cannot_be_0: "Module name cannot be '{0}'.", + Enum_member_must_have_initializer: "Enum member must have initializer.", + Export_assignment_cannot_be_used_in_internal_modules: "Export assignment cannot be used in internal modules.", + Export_assignment_not_allowed_in_module_with_exported_element: "Export assignment not allowed in module with exported element.", + Module_cannot_have_multiple_export_assignments: "Module cannot have multiple export assignments.", + Ambient_enum_elements_can_only_have_integer_literal_initializers: "Ambient enum elements can only have integer literal initializers.", + module_class_interface_enum_import_or_statement: "module, class, interface, enum, import or statement", + constructor_function_accessor_or_variable: "constructor, function, accessor or variable", + statement: "statement", + case_or_default_clause: "case or default clause", + identifier: "identifier", + call_construct_index_property_or_function_signature: "call, construct, index, property or function signature", + expression: "expression", + type_name: "type name", + property_or_accessor: "property or accessor", + parameter: "parameter", + type: "type", + type_parameter: "type parameter", + declare_modifier_not_allowed_on_import_declaration: "'declare' modifier not allowed on import declaration.", + Function_overload_must_be_static: "Function overload must be static.", + Function_overload_must_not_be_static: "Function overload must not be static.", + Parameter_property_declarations_cannot_be_used_in_a_constructor_overload: "Parameter property declarations cannot be used in a constructor overload.", + Invalid_reference_directive_syntax: "Invalid 'reference' directive syntax.", + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: "Octal literals are not available when targeting ECMAScript 5 and higher.", + Accessors_are_not_allowed_in_ambient_contexts: "Accessors are not allowed in ambient contexts.", + _0_modifier_cannot_appear_on_a_constructor_declaration: "'{0}' modifier cannot appear on a constructor declaration.", + _0_modifier_cannot_appear_on_a_parameter: "'{0}' modifier cannot appear on a parameter.", + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: "Only a single variable declaration is allowed in a 'for...in' statement.", + Type_parameters_cannot_appear_on_a_constructor_declaration: "Type parameters cannot appear on a constructor declaration.", + Type_annotation_cannot_appear_on_a_constructor_declaration: "Type annotation cannot appear on a constructor declaration.", + Duplicate_identifier_0: "Duplicate identifier '{0}'.", + The_name_0_does_not_exist_in_the_current_scope: "The name '{0}' does not exist in the current scope.", + The_name_0_does_not_refer_to_a_value: "The name '{0}' does not refer to a value.", + super_can_only_be_used_inside_a_class_instance_method: "'super' can only be used inside a class instance method.", + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_property_or_indexer: "The left-hand side of an assignment expression must be a variable, property or indexer.", + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: "Value of type '{0}' is not callable. Did you mean to include 'new'?", + Value_of_type_0_is_not_callable: "Value of type '{0}' is not callable.", + Value_of_type_0_is_not_newable: "Value of type '{0}' is not newable.", + Value_of_type_0_is_not_indexable_by_type_1: "Value of type '{0}' is not indexable by type '{1}'.", + Operator_0_cannot_be_applied_to_types_1_and_2: "Operator '{0}' cannot be applied to types '{1}' and '{2}'.", + Operator_0_cannot_be_applied_to_types_1_and_2_3: "Operator '{0}' cannot be applied to types '{1}' and '{2}': {3}", + Cannot_convert_0_to_1: "Cannot convert '{0}' to '{1}'.", + Cannot_convert_0_to_1_NL_2: "Cannot convert '{0}' to '{1}':{NL}{2}", + Expected_var_class_interface_or_module: "Expected var, class, interface, or module.", + Operator_0_cannot_be_applied_to_type_1: "Operator '{0}' cannot be applied to type '{1}'.", + Getter_0_already_declared: "Getter '{0}' already declared.", + Setter_0_already_declared: "Setter '{0}' already declared.", + Exported_class_0_extends_private_class_1: "Exported class '{0}' extends private class '{1}'.", + Exported_class_0_implements_private_interface_1: "Exported class '{0}' implements private interface '{1}'.", + Exported_interface_0_extends_private_interface_1: "Exported interface '{0}' extends private interface '{1}'.", + Exported_class_0_extends_class_from_inaccessible_module_1: "Exported class '{0}' extends class from inaccessible module {1}.", + Exported_class_0_implements_interface_from_inaccessible_module_1: "Exported class '{0}' implements interface from inaccessible module {1}.", + Exported_interface_0_extends_interface_from_inaccessible_module_1: "Exported interface '{0}' extends interface from inaccessible module {1}.", + Public_static_property_0_of_exported_class_has_or_is_using_private_type_1: "Public static property '{0}' of exported class has or is using private type '{1}'.", + Public_property_0_of_exported_class_has_or_is_using_private_type_1: "Public property '{0}' of exported class has or is using private type '{1}'.", + Property_0_of_exported_interface_has_or_is_using_private_type_1: "Property '{0}' of exported interface has or is using private type '{1}'.", + Exported_variable_0_has_or_is_using_private_type_1: "Exported variable '{0}' has or is using private type '{1}'.", + Public_static_property_0_of_exported_class_is_using_inaccessible_module_1: "Public static property '{0}' of exported class is using inaccessible module {1}.", + Public_property_0_of_exported_class_is_using_inaccessible_module_1: "Public property '{0}' of exported class is using inaccessible module {1}.", + Property_0_of_exported_interface_is_using_inaccessible_module_1: "Property '{0}' of exported interface is using inaccessible module {1}.", + Exported_variable_0_is_using_inaccessible_module_1: "Exported variable '{0}' is using inaccessible module {1}.", + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of constructor from exported class has or is using private type '{1}'.", + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public static property setter from exported class has or is using private type '{1}'.", + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public property setter from exported class has or is using private type '{1}'.", + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.", + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of call signature from exported interface has or is using private type '{1}'.", + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public static method from exported class has or is using private type '{1}'.", + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public method from exported class has or is using private type '{1}'.", + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of method from exported interface has or is using private type '{1}'.", + Parameter_0_of_exported_function_has_or_is_using_private_type_1: "Parameter '{0}' of exported function has or is using private type '{1}'.", + Parameter_0_of_constructor_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of constructor from exported class is using inaccessible module {1}.", + Parameter_0_of_public_static_property_setter_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public static property setter from exported class is using inaccessible module {1}.", + Parameter_0_of_public_property_setter_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public property setter from exported class is using inaccessible module {1}.", + Parameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.", + Parameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of call signature from exported interface is using inaccessible module {1}", + Parameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public static method from exported class is using inaccessible module {1}.", + Parameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public method from exported class is using inaccessible module {1}.", + Parameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of method from exported interface is using inaccessible module {1}.", + Parameter_0_of_exported_function_is_using_inaccessible_module_1: "Parameter '{0}' of exported function is using inaccessible module {1}.", + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type_0: "Return type of public static property getter from exported class has or is using private type '{0}'.", + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type_0: "Return type of public property getter from exported class has or is using private type '{0}'.", + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of constructor signature from exported interface has or is using private type '{0}'.", + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of call signature from exported interface has or is using private type '{0}'.", + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of index signature from exported interface has or is using private type '{0}'.", + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type_0: "Return type of public static method from exported class has or is using private type '{0}'.", + Return_type_of_public_method_from_exported_class_has_or_is_using_private_type_0: "Return type of public method from exported class has or is using private type '{0}'.", + Return_type_of_method_from_exported_interface_has_or_is_using_private_type_0: "Return type of method from exported interface has or is using private type '{0}'.", + Return_type_of_exported_function_has_or_is_using_private_type_0: "Return type of exported function has or is using private type '{0}'.", + Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module_0: "Return type of public static property getter from exported class is using inaccessible module {0}.", + Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module_0: "Return type of public property getter from exported class is using inaccessible module {0}.", + Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of constructor signature from exported interface is using inaccessible module {0}.", + Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of call signature from exported interface is using inaccessible module {0}.", + Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of index signature from exported interface is using inaccessible module {0}.", + Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module_0: "Return type of public static method from exported class is using inaccessible module {0}.", + Return_type_of_public_method_from_exported_class_is_using_inaccessible_module_0: "Return type of public method from exported class is using inaccessible module {0}.", + Return_type_of_method_from_exported_interface_is_using_inaccessible_module_0: "Return type of method from exported interface is using inaccessible module {0}.", + Return_type_of_exported_function_is_using_inaccessible_module_0: "Return type of exported function is using inaccessible module {0}.", + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: "'new T[]' cannot be used to create an array. Use 'new Array()' instead.", + A_parameter_list_must_follow_a_generic_type_argument_list_expected: "A parameter list must follow a generic type argument list. '(' expected.", + Multiple_constructor_implementations_are_not_allowed: "Multiple constructor implementations are not allowed.", + Unable_to_resolve_external_module_0: "Unable to resolve external module '{0}'.", + Module_cannot_be_aliased_to_a_non_module_type: "Module cannot be aliased to a non-module type.", + A_class_may_only_extend_another_class: "A class may only extend another class.", + A_class_may_only_implement_another_class_or_interface: "A class may only implement another class or interface.", + An_interface_may_only_extend_another_class_or_interface: "An interface may only extend another class or interface.", + Unable_to_resolve_type: "Unable to resolve type.", + Unable_to_resolve_type_of_0: "Unable to resolve type of '{0}'.", + Unable_to_resolve_type_parameter_constraint: "Unable to resolve type parameter constraint.", + Type_parameter_constraint_cannot_be_a_primitive_type: "Type parameter constraint cannot be a primitive type.", + Supplied_parameters_do_not_match_any_signature_of_call_target: "Supplied parameters do not match any signature of call target.", + Supplied_parameters_do_not_match_any_signature_of_call_target_NL_0: "Supplied parameters do not match any signature of call target:{NL}{0}", + Invalid_new_expression: "Invalid 'new' expression.", + Call_signatures_used_in_a_new_expression_must_have_a_void_return_type: "Call signatures used in a 'new' expression must have a 'void' return type.", + Could_not_select_overload_for_new_expression: "Could not select overload for 'new' expression.", + Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2: "Type '{0}' does not satisfy the constraint '{1}' for type parameter '{2}'.", + Could_not_select_overload_for_call_expression: "Could not select overload for 'call' expression.", + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: "Cannot invoke an expression whose type lacks a call signature.", + Calls_to_super_are_only_valid_inside_a_class: "Calls to 'super' are only valid inside a class.", + Generic_type_0_requires_1_type_argument_s: "Generic type '{0}' requires {1} type argument(s).", + Type_of_array_literal_cannot_be_determined_Best_common_type_could_not_be_found_for_array_elements: "Type of array literal cannot be determined. Best common type could not be found for array elements.", + Could_not_find_enclosing_symbol_for_dotted_name_0: "Could not find enclosing symbol for dotted name '{0}'.", + The_property_0_does_not_exist_on_value_of_type_1: "The property '{0}' does not exist on value of type '{1}'.", + Could_not_find_symbol_0: "Could not find symbol '{0}'.", + get_and_set_accessor_must_have_the_same_type: "'get' and 'set' accessor must have the same type.", + this_cannot_be_referenced_in_current_location: "'this' cannot be referenced in current location.", + Static_members_cannot_reference_class_type_parameters: "Static members cannot reference class type parameters.", + Class_0_is_recursively_referenced_as_a_base_type_of_itself: "Class '{0}' is recursively referenced as a base type of itself.", + Interface_0_is_recursively_referenced_as_a_base_type_of_itself: "Interface '{0}' is recursively referenced as a base type of itself.", + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class.", + super_cannot_be_referenced_in_non_derived_classes: "'super' cannot be referenced in non-derived classes.", + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.", + Constructors_for_derived_classes_must_contain_a_super_call: "Constructors for derived classes must contain a 'super' call.", + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: "Super calls are not permitted outside constructors or in nested functions inside constructors.", + _0_1_is_inaccessible: "'{0}.{1}' is inaccessible.", + this_cannot_be_referenced_within_module_bodies: "'this' cannot be referenced within module bodies.", + Invalid_expression_types_not_known_to_support_the_addition_operator: "Invalid '+' expression - types not known to support the addition operator.", + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type_any_number_or_an_enum_type: "The type of a unary arithmetic operation operand must be of type 'any', 'number' or an enum type.", + Variable_declarations_of_a_for_statement_cannot_use_a_type_annotation: "Variable declarations of a 'for' statement cannot use a type annotation.", + Variable_declarations_of_a_for_statement_must_be_of_types_string_or_any: "Variable declarations of a 'for' statement must be of types 'string' or 'any'.", + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter.", + The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number: "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'.", + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.", + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.", + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.", + Setters_cannot_return_a_value: "Setters cannot return a value.", + Tried_to_query_type_of_uninitialized_module_0: "Tried to query type of uninitialized module '{0}'.", + Tried_to_set_variable_type_to_uninitialized_module_type_0: "Tried to set variable type to uninitialized module type '{0}'.", + Type_0_does_not_have_type_parameters: "Type '{0}' does not have type parameters.", + Getters_must_return_a_value: "Getters must return a value.", + Getter_and_setter_accessors_do_not_agree_in_visibility: "Getter and setter accessors do not agree in visibility.", + Invalid_left_hand_side_of_assignment_expression: "Invalid left-hand side of assignment expression.", + Function_declared_a_non_void_return_type_but_has_no_return_expression: "Function declared a non-void return type, but has no return expression.", + Cannot_resolve_return_type_reference: "Cannot resolve return type reference.", + Constructors_cannot_have_a_return_type_of_void: "Constructors cannot have a return type of 'void'.", + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'.", + All_symbols_within_a_with_block_will_be_resolved_to_any: "All symbols within a with block will be resolved to 'any'.", + Import_declarations_in_an_internal_module_cannot_reference_an_external_module: "Import declarations in an internal module cannot reference an external module.", + Class_0_declares_interface_1_but_does_not_implement_it_NL_2: "Class {0} declares interface {1} but does not implement it:{NL}{2}", + Class_0_declares_class_1_as_an_interface_but_does_not_implement_it_NL_2: "Class {0} declares class {1} as an interface but does not implement it:{NL}{2}", + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: "The operand of an increment or decrement operator must be a variable, property or indexer.", + this_cannot_be_referenced_in_static_initializers_in_a_class_body: "'this' cannot be referenced in static initializers in a class body.", + Class_0_cannot_extend_class_1_NL_2: "Class '{0}' cannot extend class '{1}':{NL}{2}", + Interface_0_cannot_extend_class_1_NL_2: "Interface '{0}' cannot extend class '{1}':{NL}{2}", + Interface_0_cannot_extend_interface_1_NL_2: "Interface '{0}' cannot extend interface '{1}':{NL}{2}", + Duplicate_overload_signature_for_0: "Duplicate overload signature for '{0}'.", + Duplicate_constructor_overload_signature: "Duplicate constructor overload signature.", + Duplicate_overload_call_signature: "Duplicate overload call signature.", + Duplicate_overload_construct_signature: "Duplicate overload construct signature.", + Overload_signature_is_not_compatible_with_function_definition: "Overload signature is not compatible with function definition.", + Overload_signature_is_not_compatible_with_function_definition_NL_0: "Overload signature is not compatible with function definition:{NL}{0}", + Overload_signatures_must_all_be_public_or_private: "Overload signatures must all be public or private.", + Overload_signatures_must_all_be_exported_or_not_exported: "Overload signatures must all be exported or not exported.", + Overload_signatures_must_all_be_ambient_or_non_ambient: "Overload signatures must all be ambient or non-ambient.", + Overload_signatures_must_all_be_optional_or_required: "Overload signatures must all be optional or required.", + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: "Specialized overload signature is not assignable to any non-specialized signature.", + this_cannot_be_referenced_in_constructor_arguments: "'this' cannot be referenced in constructor arguments.", + Instance_member_cannot_be_accessed_off_a_class: "Instance member cannot be accessed off a class.", + Untyped_function_calls_may_not_accept_type_arguments: "Untyped function calls may not accept type arguments.", + Non_generic_functions_may_not_accept_type_arguments: "Non-generic functions may not accept type arguments.", + A_generic_type_may_not_reference_itself_with_a_wrapped_form_of_its_own_type_parameters: "A generic type may not reference itself with a wrapped form of its own type parameters.", + Rest_parameters_must_be_array_types: "Rest parameters must be array types.", + Overload_signature_implementation_cannot_use_specialized_type: "Overload signature implementation cannot use specialized type.", + Export_assignments_may_only_be_used_at_the_top_level_of_external_modules: "Export assignments may only be used at the top-level of external modules.", + Export_assignments_may_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: "Export assignments may only be made with variables, functions, classes, interfaces, enums and internal modules.", + Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword: "Only public methods of the base class are accessible via the 'super' keyword.", + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1: "Numeric indexer type '{0}' must be assignable to string indexer type '{1}'.", + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1_NL_2: "Numeric indexer type '{0}' must be assignable to string indexer type '{1}':{NL}{2}", + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0: "All numerically named properties must be assignable to numeric indexer type '{0}'.", + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0_NL_1: "All numerically named properties must be assignable to numeric indexer type '{0}':{NL}{1}", + All_named_properties_must_be_assignable_to_string_indexer_type_0: "All named properties must be assignable to string indexer type '{0}'.", + All_named_properties_must_be_assignable_to_string_indexer_type_0_NL_1: "All named properties must be assignable to string indexer type '{0}':{NL}{1}", + Generic_type_references_must_include_all_type_arguments: "Generic type references must include all type arguments.", + Default_arguments_are_only_allowed_in_implementation: "Default arguments are only allowed in implementation.", + Overloads_cannot_differ_only_by_return_type: "Overloads cannot differ only by return type.", + Function_expression_declared_a_non_void_return_type_but_has_no_return_expression: "Function expression declared a non-void return type, but has no return expression.", + Import_declaration_referencing_identifier_from_internal_module_can_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: "Import declaration referencing identifier from internal module can only be made with variables, functions, classes, interfaces, enums and internal modules.", + Could_not_find_symbol_0_in_module_1: "Could not find symbol '{0}' in module '{1}'.", + Unable_to_resolve_module_reference_0: "Unable to resolve module reference '{0}'.", + Could_not_find_module_0_in_module_1: "Could not find module '{0}' in module '{1}'.", + Exported_import_declaration_0_is_assigned_value_with_type_that_has_or_is_using_private_type_1: "Exported import declaration '{0}' is assigned value with type that has or is using private type '{1}'.", + Exported_import_declaration_0_is_assigned_value_with_type_that_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned value with type that is using inaccessible module '{1}'.", + Exported_import_declaration_0_is_assigned_type_that_has_or_is_using_private_type_1: "Exported import declaration '{0}' is assigned type that has or is using private type '{1}'.", + Exported_import_declaration_0_is_assigned_type_that_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned type that is using inaccessible module '{1}'.", + Exported_import_declaration_0_is_assigned_container_that_is_or_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned container that is or is using inaccessible module '{1}'.", + Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_1: "Type name '{0}' in extends clause does not reference constructor function for '{1}'.", + Internal_module_reference_0_in_import_declaration_does_not_reference_module_instance_for_1: "Internal module reference '{0}' in import declaration does not reference module instance for '{1}'.", + Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2: "Module '{0}' cannot merge with previous declaration of '{1}' in a different file '{2}'.", + Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':{NL}{3}", + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it.", + Ambient_external_module_declaration_cannot_be_reopened: "Ambient external module declaration cannot be reopened.", + All_declarations_of_merged_declaration_0_must_be_exported_or_not_exported: "All declarations of merged declaration '{0}' must be exported or not exported.", + super_cannot_be_referenced_in_constructor_arguments: "'super' cannot be referenced in constructor arguments.", + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: "Return type of constructor signature must be assignable to the instance type of the class.", + Ambient_external_module_declaration_must_be_defined_in_global_context: "Ambient external module declaration must be defined in global context.", + Ambient_external_module_declaration_cannot_specify_relative_module_name: "Ambient external module declaration cannot specify relative module name.", + Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name: "Import declaration in an ambient external module declaration cannot reference external module through relative external module name.", + Could_not_find_the_best_common_type_of_types_of_all_return_statement_expressions: "Could not find the best common type of types of all return statement expressions.", + Import_declaration_cannot_refer_to_external_module_reference_when_noResolve_option_is_set: "Import declaration cannot refer to external module reference when --noResolve option is set.", + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference.", + continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: "'continue' statement can only be used within an enclosing iteration statement.", + break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: "'break' statement can only be used within an enclosing iteration or switch statement.", + Jump_target_not_found: "Jump target not found.", + Jump_target_cannot_cross_function_boundary: "Jump target cannot cross function boundary.", + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference.", + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference.", + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: "Expression resolves to '_super' that compiler uses to capture base class reference.", + TypeParameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of call signature from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of public static method from exported class has or is using private type '{1}'.", + TypeParameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of public method from exported class has or is using private type '{1}'.", + TypeParameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of method from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_exported_function_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported function has or is using private type '{1}'.", + TypeParameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.", + TypeParameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of call signature from exported interface is using inaccessible module {1}", + TypeParameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of public static method from exported class is using inaccessible module {1}.", + TypeParameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of public method from exported class is using inaccessible module {1}.", + TypeParameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of method from exported interface is using inaccessible module {1}.", + TypeParameter_0_of_exported_function_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported function is using inaccessible module {1}.", + TypeParameter_0_of_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported class has or is using private type '{1}'.", + TypeParameter_0_of_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported interface has or is using private type '{1}'.", + TypeParameter_0_of_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported class is using inaccessible module {1}.", + TypeParameter_0_of_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported interface is using inaccessible module {1}.", + Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter: "Duplicate identifier '_i'. Compiler uses '_i' to initialize rest parameter.", + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters.", + Type_of_conditional_0_must_be_identical_to_1_or_2: "Type of conditional '{0}' must be identical to '{1}' or '{2}'.", + Type_of_conditional_0_must_be_identical_to_1_2_or_3: "Type of conditional '{0}' must be identical to '{1}', '{2}' or '{3}'.", + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of an external module.", + Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.", + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.", + Parameter_0_cannot_be_referenced_in_its_initializer: "Parameter '{0}' cannot be referenced in its initializer.", + Duplicate_string_index_signature: "Duplicate string index signature.", + Duplicate_number_index_signature: "Duplicate number index signature.", + All_declarations_of_an_interface_must_have_identical_type_parameters: "All declarations of an interface must have identical type parameters.", + Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter: "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter.", + Type_0_is_missing_property_1_from_type_2: "Type '{0}' is missing property '{1}' from type '{2}'.", + Types_of_property_0_of_types_1_and_2_are_incompatible: "Types of property '{0}' of types '{1}' and '{2}' are incompatible.", + Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3: "Types of property '{0}' of types '{1}' and '{2}' are incompatible:{NL}{3}", + Property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2: "Property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.", + Property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2: "Property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.", + Types_0_and_1_define_property_2_as_private: "Types '{0}' and '{1}' define property '{2}' as private.", + Call_signatures_of_types_0_and_1_are_incompatible: "Call signatures of types '{0}' and '{1}' are incompatible.", + Call_signatures_of_types_0_and_1_are_incompatible_NL_2: "Call signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Type_0_requires_a_call_signature_but_type_1_lacks_one: "Type '{0}' requires a call signature, but type '{1}' lacks one.", + Construct_signatures_of_types_0_and_1_are_incompatible: "Construct signatures of types '{0}' and '{1}' are incompatible.", + Construct_signatures_of_types_0_and_1_are_incompatible_NL_2: "Construct signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Type_0_requires_a_construct_signature_but_type_1_lacks_one: "Type '{0}' requires a construct signature, but type '{1}' lacks one.", + Index_signatures_of_types_0_and_1_are_incompatible: "Index signatures of types '{0}' and '{1}' are incompatible.", + Index_signatures_of_types_0_and_1_are_incompatible_NL_2: "Index signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Call_signature_expects_0_or_fewer_parameters: "Call signature expects {0} or fewer parameters.", + Could_not_apply_type_0_to_argument_1_which_is_of_type_2: "Could not apply type '{0}' to argument {1} which is of type '{2}'.", + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function.", + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.", + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor.", + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.", + Types_of_static_property_0_of_class_1_and_class_2_are_incompatible: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible.", + Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible:{NL}{3}", + Type_reference_cannot_refer_to_container_0: "Type reference cannot refer to container '{0}'.", + Type_reference_must_refer_to_type: "Type reference must refer to type.", + In_enums_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_the_first_enum_element: "In enums with multiple declarations only one declaration can omit an initializer for the first enum element.", + _0_overload_s: " (+ {0} overload(s))", + Variable_declaration_cannot_have_the_same_name_as_an_import_declaration: "Variable declaration cannot have the same name as an import declaration.", + Signature_expected_0_type_arguments_got_1_instead: "Signature expected {0} type arguments, got {1} instead.", + Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2: "Property '{0}' defined as optional in type '{1}', but is required in type '{2}'.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_do_not_refer_to_same_named_type: "Types '{0}' and '{1}' originating in infinitely expanding type reference do not refer to same named type.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments: "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2: "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments:{NL}{2}", + Named_properties_0_of_types_1_and_2_are_not_identical: "Named properties '{0}' of types '{1}' and '{2}' are not identical.", + Types_of_string_indexer_of_types_0_and_1_are_not_identical: "Types of string indexer of types '{0}' and '{1}' are not identical.", + Types_of_number_indexer_of_types_0_and_1_are_not_identical: "Types of number indexer of types '{0}' and '{1}' are not identical.", + Type_of_number_indexer_in_type_0_is_not_assignable_to_string_indexer_type_in_type_1_NL_2: "Type of number indexer in type '{0}' is not assignable to string indexer type in type '{1}'.{NL}{2}", + Type_of_property_0_in_type_1_is_not_assignable_to_string_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not assignable to string indexer type in type '{2}'.{NL}{3}", + Type_of_property_0_in_type_1_is_not_assignable_to_number_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not assignable to number indexer type in type '{2}'.{NL}{3}", + Static_property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2: "Static property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.", + Static_property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2: "Static property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.", + Types_0_and_1_define_static_property_2_as_private: "Types '{0}' and '{1}' define static property '{2}' as private.", + Current_host_does_not_support_0_option: "Current host does not support '{0}' option.", + ECMAScript_target_version_0_not_supported_Specify_a_valid_target_version_1_default_or_2: "ECMAScript target version '{0}' not supported. Specify a valid target version: '{1}' (default), or '{2}'", + Module_code_generation_0_not_supported: "Module code generation '{0}' not supported.", + Could_not_find_file_0: "Could not find file: '{0}'.", + A_file_cannot_have_a_reference_to_itself: "A file cannot have a reference to itself.", + Cannot_resolve_referenced_file_0: "Cannot resolve referenced file: '{0}'.", + Cannot_find_the_common_subdirectory_path_for_the_input_files: "Cannot find the common subdirectory path for the input files.", + Emit_Error_0: "Emit Error: {0}.", + Cannot_read_file_0_1: "Cannot read file '{0}': {1}", + Unsupported_file_encoding: "Unsupported file encoding.", + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: "Locale must be of the form or -. For example '{0}' or '{1}'.", + Unsupported_locale_0: "Unsupported locale: '{0}'.", + Execution_Failed_NL: "Execution Failed.{NL}", + Invalid_call_to_up: "Invalid call to 'up'", + Invalid_call_to_down: "Invalid call to 'down'", + Base64_value_0_finished_with_a_continuation_bit: "Base64 value '{0}' finished with a continuation bit.", + Unknown_option_0: "Unknown option '{0}'", + Expected_0_arguments_to_message_got_1_instead: "Expected {0} arguments to message, got {1} instead.", + Expected_the_message_0_to_have_1_arguments_but_it_had_2: "Expected the message '{0}' to have {1} arguments, but it had {2}", + Could_not_delete_file_0: "Could not delete file '{0}'", + Could_not_create_directory_0: "Could not create directory '{0}'", + Error_while_executing_file_0: "Error while executing file '{0}': ", + Cannot_compile_external_modules_unless_the_module_flag_is_provided: "Cannot compile external modules unless the '--module' flag is provided.", + Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: "Option mapRoot cannot be specified without specifying sourcemap option.", + Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: "Option sourceRoot cannot be specified without specifying sourcemap option.", + Options_mapRoot_and_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: "Options mapRoot and sourceRoot cannot be specified without specifying sourcemap option.", + Option_0_specified_without_1: "Option '{0}' specified without '{1}'", + codepage_option_not_supported_on_current_platform: "'codepage' option not supported on current platform.", + Concatenate_and_emit_output_to_single_file: "Concatenate and emit output to single file.", + Generates_corresponding_0_file: "Generates corresponding {0} file.", + Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: "Specifies the location where debugger should locate map files instead of generated locations.", + Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: "Specifies the location where debugger should locate TypeScript files instead of source locations.", + Watch_input_files: "Watch input files.", + Redirect_output_structure_to_the_directory: "Redirect output structure to the directory.", + Do_not_emit_comments_to_output: "Do not emit comments to output.", + Skip_resolution_and_preprocessing: "Skip resolution and preprocessing.", + Specify_ECMAScript_target_version_0_default_or_1: "Specify ECMAScript target version: '{0}' (default), or '{1}'", + Specify_module_code_generation_0_or_1: "Specify module code generation: '{0}' or '{1}'", + Print_this_message: "Print this message.", + Print_the_compiler_s_version_0: "Print the compiler's version: {0}", + Allow_use_of_deprecated_0_keyword_when_referencing_an_external_module: "Allow use of deprecated '{0}' keyword when referencing an external module.", + Specify_locale_for_errors_and_messages_For_example_0_or_1: "Specify locale for errors and messages. For example '{0}' or '{1}'", + Syntax_0: "Syntax: {0}", + options: "options", + file1: "file", + Examples: "Examples:", + Options: "Options:", + Insert_command_line_options_and_files_from_a_file: "Insert command line options and files from a file.", + Version_0: "Version {0}", + Use_the_0_flag_to_see_options: "Use the '{0}' flag to see options.", + NL_Recompiling_0: "{NL}Recompiling ({0}):", + STRING: "STRING", + KIND: "KIND", + file2: "FILE", + VERSION: "VERSION", + LOCATION: "LOCATION", + DIRECTORY: "DIRECTORY", + NUMBER: "NUMBER", + Specify_the_codepage_to_use_when_opening_source_files: "Specify the codepage to use when opening source files.", + Additional_locations: "Additional locations:", + This_version_of_the_Javascript_runtime_does_not_support_the_0_function: "This version of the Javascript runtime does not support the '{0}' function.", + Unknown_rule: "Unknown rule.", + Invalid_line_number_0: "Invalid line number ({0})", + Warn_on_expressions_and_declarations_with_an_implied_any_type: "Warn on expressions and declarations with an implied 'any' type.", + Variable_0_implicitly_has_an_any_type: "Variable '{0}' implicitly has an 'any' type.", + Parameter_0_of_1_implicitly_has_an_any_type: "Parameter '{0}' of '{1}' implicitly has an 'any' type.", + Parameter_0_of_function_type_implicitly_has_an_any_type: "Parameter '{0}' of function type implicitly has an 'any' type.", + Member_0_of_object_type_implicitly_has_an_any_type: "Member '{0}' of object type implicitly has an 'any' type.", + new_expression_which_lacks_a_constructor_signature_implicitly_has_an_any_type: "'new' expression, which lacks a constructor signature, implicitly has an 'any' type.", + _0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "'{0}', which lacks return-type annotation, implicitly has an 'any' return type.", + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Function expression, which lacks return-type annotation, implicitly has an 'any' return type.", + Parameter_0_of_lambda_function_implicitly_has_an_any_type: "Parameter '{0}' of lambda function implicitly has an 'any' type.", + Constructor_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Constructor signature, which lacks return-type annotation, implicitly has an 'any' return type.", + Lambda_Function_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Lambda Function, which lacks return-type annotation, implicitly has an 'any' return type.", + Array_Literal_implicitly_has_an_any_type_from_widening: "Array Literal implicitly has an 'any' type from widening.", + _0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type: "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type.", + Index_signature_of_object_type_implicitly_has_an_any_type: "Index signature of object type implicitly has an 'any' type.", + Object_literal_s_property_0_implicitly_has_an_any_type_from_widening: "Object literal's property '{0}' implicitly has an 'any' type from widening." + }; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ArrayUtilities = (function () { + function ArrayUtilities() { + } + ArrayUtilities.isArray = function (value) { + return Object.prototype.toString.apply(value, []) === '[object Array]'; + }; + + ArrayUtilities.sequenceEquals = function (array1, array2, equals) { + if (array1 === array2) { + return true; + } + + if (array1 === null || array2 === null) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0, n = array1.length; i < n; i++) { + if (!equals(array1[i], array2[i])) { + return false; + } + } + + return true; + }; + + ArrayUtilities.contains = function (array, value) { + for (var i = 0; i < array.length; i++) { + if (array[i] === value) { + return true; + } + } + + return false; + }; + + ArrayUtilities.groupBy = function (array, func) { + var result = {}; + + for (var i = 0, n = array.length; i < n; i++) { + var v = array[i]; + var k = func(v); + + var list = result[k] || []; + list.push(v); + result[k] = list; + } + + return result; + }; + + ArrayUtilities.distinct = function (array, equalsFn) { + var result = []; + + for (var i = 0, n = array.length; i < n; i++) { + var current = array[i]; + for (var j = 0; j < result.length; j++) { + if (equalsFn(result[j], current)) { + break; + } + } + + if (j === result.length) { + result.push(current); + } + } + + return result; + }; + + ArrayUtilities.min = function (array, func) { + var min = func(array[0]); + + for (var i = 1; i < array.length; i++) { + var next = func(array[i]); + if (next < min) { + min = next; + } + } + + return min; + }; + + ArrayUtilities.max = function (array, func) { + var max = func(array[0]); + + for (var i = 1; i < array.length; i++) { + var next = func(array[i]); + if (next > max) { + max = next; + } + } + + return max; + }; + + ArrayUtilities.last = function (array) { + if (array.length === 0) { + throw TypeScript.Errors.argumentOutOfRange('array'); + } + + return array[array.length - 1]; + }; + + ArrayUtilities.lastOrDefault = function (array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var v = array[i]; + if (predicate(v, i)) { + return v; + } + } + + return null; + }; + + ArrayUtilities.firstOrDefault = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + var value = array[i]; + if (func(value, i)) { + return value; + } + } + + return null; + }; + + ArrayUtilities.first = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + var value = array[i]; + if (!func || func(value, i)) { + return value; + } + } + + throw TypeScript.Errors.invalidOperation(); + }; + + ArrayUtilities.sum = function (array, func) { + var result = 0; + + for (var i = 0, n = array.length; i < n; i++) { + result += func(array[i]); + } + + return result; + }; + + ArrayUtilities.select = function (values, func) { + var result = new Array(values.length); + + for (var i = 0; i < values.length; i++) { + result[i] = func(values[i]); + } + + return result; + }; + + ArrayUtilities.where = function (values, func) { + var result = new Array(); + + for (var i = 0; i < values.length; i++) { + if (func(values[i])) { + result.push(values[i]); + } + } + + return result; + }; + + ArrayUtilities.any = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + if (func(array[i])) { + return true; + } + } + + return false; + }; + + ArrayUtilities.all = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + if (!func(array[i])) { + return false; + } + } + + return true; + }; + + ArrayUtilities.binarySearch = function (array, value) { + var low = 0; + var high = array.length - 1; + + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midValue = array[middle]; + + if (midValue === value) { + return middle; + } else if (midValue > value) { + high = middle - 1; + } else { + low = middle + 1; + } + } + + return ~low; + }; + + ArrayUtilities.createArray = function (length, defaultValue) { + var result = new Array(length); + for (var i = 0; i < length; i++) { + result[i] = defaultValue; + } + + return result; + }; + + ArrayUtilities.grow = function (array, length, defaultValue) { + var count = length - array.length; + for (var i = 0; i < count; i++) { + array.push(defaultValue); + } + }; + + ArrayUtilities.copy = function (sourceArray, sourceIndex, destinationArray, destinationIndex, length) { + for (var i = 0; i < length; i++) { + destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i]; + } + }; + + ArrayUtilities.indexOf = function (array, predicate) { + for (var i = 0, n = array.length; i < n; i++) { + if (predicate(array[i])) { + return i; + } + } + + return -1; + }; + return ArrayUtilities; + })(); + TypeScript.ArrayUtilities = ArrayUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (BitVector) { + var pool = []; + var Constants; + (function (Constants) { + Constants[Constants["MaxBitsPerEncodedNumber"] = 30] = "MaxBitsPerEncodedNumber"; + Constants[Constants["BitsPerEncodedBiStateValue"] = 1] = "BitsPerEncodedBiStateValue"; + + Constants[Constants["BitsPerEncodedTriStateValue"] = 2] = "BitsPerEncodedTriStateValue"; + + Constants[Constants["BiStateEncodedTrue"] = 1] = "BiStateEncodedTrue"; + Constants[Constants["BiStateClearBitsMask"] = 1] = "BiStateClearBitsMask"; + + Constants[Constants["TriStateEncodedFalse"] = 1] = "TriStateEncodedFalse"; + Constants[Constants["TriStateEncodedTrue"] = 2] = "TriStateEncodedTrue"; + Constants[Constants["TriStateClearBitsMask"] = 3] = "TriStateClearBitsMask"; + })(Constants || (Constants = {})); + + var BitVectorImpl = (function () { + function BitVectorImpl(allowUndefinedValues) { + this.allowUndefinedValues = allowUndefinedValues; + this.isReleased = false; + this.bits = []; + } + BitVectorImpl.prototype.computeTriStateArrayIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 2 /* BitsPerEncodedTriStateValue */; + + return (index / encodedValuesPerNumber) >>> 0; + }; + + BitVectorImpl.prototype.computeBiStateArrayIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 1 /* BitsPerEncodedBiStateValue */; + + return (index / encodedValuesPerNumber) >>> 0; + }; + + BitVectorImpl.prototype.computeTriStateEncodedValueIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 2 /* BitsPerEncodedTriStateValue */; + + return (index % encodedValuesPerNumber) * 2 /* BitsPerEncodedTriStateValue */; + }; + + BitVectorImpl.prototype.computeBiStateEncodedValueIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 1 /* BitsPerEncodedBiStateValue */; + + return (index % encodedValuesPerNumber) * 1 /* BitsPerEncodedBiStateValue */; + }; + + BitVectorImpl.prototype.valueAt = function (index) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + if (this.allowUndefinedValues) { + var arrayIndex = this.computeTriStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + return undefined; + } + + var bitIndex = this.computeTriStateEncodedValueIndex(index); + if (encoded & (2 /* TriStateEncodedTrue */ << bitIndex)) { + return true; + } else if (encoded & (1 /* TriStateEncodedFalse */ << bitIndex)) { + return false; + } else { + return undefined; + } + } else { + var arrayIndex = this.computeBiStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + return false; + } + + var bitIndex = this.computeBiStateEncodedValueIndex(index); + if (encoded & (1 /* BiStateEncodedTrue */ << bitIndex)) { + return true; + } else { + return false; + } + } + }; + + BitVectorImpl.prototype.setValueAt = function (index, value) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + if (this.allowUndefinedValues) { + TypeScript.Debug.assert(value === true || value === false || value === undefined, "value must only be true, false or undefined."); + + var arrayIndex = this.computeTriStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + if (value === undefined) { + return; + } + + encoded = 0; + } + + var bitIndex = this.computeTriStateEncodedValueIndex(index); + + var clearMask = ~(3 /* TriStateClearBitsMask */ << bitIndex); + encoded = encoded & clearMask; + + if (value === true) { + encoded = encoded | (2 /* TriStateEncodedTrue */ << bitIndex); + } else if (value === false) { + encoded = encoded | (1 /* TriStateEncodedFalse */ << bitIndex); + } + + this.bits[arrayIndex] = encoded; + } else { + TypeScript.Debug.assert(value === true || value === false, "value must only be true or false."); + + var arrayIndex = this.computeBiStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + if (value === false) { + return; + } + + encoded = 0; + } + + var bitIndex = this.computeBiStateEncodedValueIndex(index); + + encoded = encoded & ~(1 /* BiStateClearBitsMask */ << bitIndex); + + if (value) { + encoded = encoded | (1 /* BiStateEncodedTrue */ << bitIndex); + } + + this.bits[arrayIndex] = encoded; + } + }; + + BitVectorImpl.prototype.release = function () { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + this.isReleased = true; + this.bits.length = 0; + pool.push(this); + }; + return BitVectorImpl; + })(); + + function getBitVector(allowUndefinedValues) { + if (pool.length === 0) { + return new BitVectorImpl(allowUndefinedValues); + } + + var vector = pool.pop(); + vector.isReleased = false; + vector.allowUndefinedValues = allowUndefinedValues; + + return vector; + } + BitVector.getBitVector = getBitVector; + })(TypeScript.BitVector || (TypeScript.BitVector = {})); + var BitVector = TypeScript.BitVector; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (BitMatrix) { + var pool = []; + + var BitMatrixImpl = (function () { + function BitMatrixImpl(allowUndefinedValues) { + this.allowUndefinedValues = allowUndefinedValues; + this.isReleased = false; + this.vectors = []; + } + BitMatrixImpl.prototype.valueAt = function (x, y) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + var vector = this.vectors[x]; + if (!vector) { + return this.allowUndefinedValues ? undefined : false; + } + + return vector.valueAt(y); + }; + + BitMatrixImpl.prototype.setValueAt = function (x, y, value) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + var vector = this.vectors[x]; + if (!vector) { + if (value === undefined) { + return; + } + + vector = TypeScript.BitVector.getBitVector(this.allowUndefinedValues); + this.vectors[x] = vector; + } + + vector.setValueAt(y, value); + }; + + BitMatrixImpl.prototype.release = function () { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + this.isReleased = true; + + for (var name in this.vectors) { + if (this.vectors.hasOwnProperty(name)) { + var vector = this.vectors[name]; + vector.release(); + } + } + + this.vectors.length = 0; + pool.push(this); + }; + return BitMatrixImpl; + })(); + + function getBitMatrix(allowUndefinedValues) { + if (pool.length === 0) { + return new BitMatrixImpl(allowUndefinedValues); + } + + var matrix = pool.pop(); + matrix.isReleased = false; + matrix.allowUndefinedValues = allowUndefinedValues; + + return matrix; + } + BitMatrix.getBitMatrix = getBitMatrix; + })(TypeScript.BitMatrix || (TypeScript.BitMatrix = {})); + var BitMatrix = TypeScript.BitMatrix; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Constants) { + Constants[Constants["Max31BitInteger"] = 1073741823] = "Max31BitInteger"; + Constants[Constants["Min31BitInteger"] = -1073741824] = "Min31BitInteger"; + })(TypeScript.Constants || (TypeScript.Constants = {})); + var Constants = TypeScript.Constants; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(TypeScript.AssertionLevel || (TypeScript.AssertionLevel = {})); + var AssertionLevel = TypeScript.AssertionLevel; + + var Debug = (function () { + function Debug() { + } + Debug.shouldAssert = function (level) { + return this.currentAssertionLevel >= level; + }; + + Debug.assert = function (expression, message, verboseDebugInfo) { + if (typeof message === "undefined") { message = ""; } + if (typeof verboseDebugInfo === "undefined") { verboseDebugInfo = null; } + if (!expression) { + var verboseDebugString = ""; + if (verboseDebugInfo) { + verboseDebugString = "\r\nVerbose Debug Information:" + verboseDebugInfo(); + } + + throw new Error("Debug Failure. False expression: " + message + verboseDebugString); + } + }; + + Debug.fail = function (message) { + Debug.assert(false, message); + }; + Debug.currentAssertionLevel = 0 /* None */; + return Debug; + })(); + TypeScript.Debug = Debug; +})(TypeScript || (TypeScript = {})); +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var TypeScript; +(function (TypeScript) { + TypeScript.LocalizedDiagnosticMessages = null; + + var Location = (function () { + function Location(fileName, lineMap, start, length) { + this._fileName = fileName; + this._lineMap = lineMap; + this._start = start; + this._length = length; + } + Location.prototype.fileName = function () { + return this._fileName; + }; + + Location.prototype.lineMap = function () { + return this._lineMap; + }; + + Location.prototype.line = function () { + return this._lineMap ? this._lineMap.getLineNumberFromPosition(this.start()) : 0; + }; + + Location.prototype.character = function () { + return this._lineMap ? this._lineMap.getLineAndCharacterFromPosition(this.start()).character() : 0; + }; + + Location.prototype.start = function () { + return this._start; + }; + + Location.prototype.length = function () { + return this._length; + }; + + Location.equals = function (location1, location2) { + return location1._fileName === location2._fileName && location1._start === location2._start && location1._length === location2._length; + }; + return Location; + })(); + TypeScript.Location = Location; + + var Diagnostic = (function (_super) { + __extends(Diagnostic, _super); + function Diagnostic(fileName, lineMap, start, length, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + _super.call(this, fileName, lineMap, start, length); + this._diagnosticKey = diagnosticKey; + this._arguments = (_arguments && _arguments.length > 0) ? _arguments : null; + this._additionalLocations = (additionalLocations && additionalLocations.length > 0) ? additionalLocations : null; + } + Diagnostic.prototype.toJSON = function (key) { + var result = {}; + result.start = this.start(); + result.length = this.length(); + + result.diagnosticCode = this._diagnosticKey; + + var _arguments = this.arguments(); + if (_arguments && _arguments.length > 0) { + result.arguments = _arguments; + } + + return result; + }; + + Diagnostic.prototype.diagnosticKey = function () { + return this._diagnosticKey; + }; + + Diagnostic.prototype.arguments = function () { + return this._arguments; + }; + + Diagnostic.prototype.text = function () { + return TypeScript.getLocalizedText(this._diagnosticKey, this._arguments); + }; + + Diagnostic.prototype.message = function () { + return TypeScript.getDiagnosticMessage(this._diagnosticKey, this._arguments); + }; + + Diagnostic.prototype.additionalLocations = function () { + return this._additionalLocations || []; + }; + + Diagnostic.equals = function (diagnostic1, diagnostic2) { + return Location.equals(diagnostic1, diagnostic2) && diagnostic1._diagnosticKey === diagnostic2._diagnosticKey && TypeScript.ArrayUtilities.sequenceEquals(diagnostic1._arguments, diagnostic2._arguments, function (v1, v2) { + return v1 === v2; + }); + }; + + Diagnostic.prototype.info = function () { + return getDiagnosticInfoFromKey(this.diagnosticKey()); + }; + return Diagnostic; + })(Location); + TypeScript.Diagnostic = Diagnostic; + + function newLine() { + return TypeScript.Environment ? TypeScript.Environment.newLine : "\r\n"; + } + TypeScript.newLine = newLine; + + function getLargestIndex(diagnostic) { + var largest = -1; + var regex = /\{(\d+)\}/g; + + var match; + while (match = regex.exec(diagnostic)) { + var val = parseInt(match[1]); + if (!isNaN(val) && val > largest) { + largest = val; + } + } + + return largest; + } + + function getDiagnosticInfoFromKey(diagnosticKey) { + var result = TypeScript.diagnosticInformationMap[diagnosticKey]; + TypeScript.Debug.assert(result); + return result; + } + + function getLocalizedText(diagnosticKey, args) { + if (TypeScript.LocalizedDiagnosticMessages) { + } + + var diagnosticMessageText = TypeScript.LocalizedDiagnosticMessages ? TypeScript.LocalizedDiagnosticMessages[diagnosticKey] : diagnosticKey; + TypeScript.Debug.assert(diagnosticMessageText !== undefined && diagnosticMessageText !== null); + + var actualCount = args ? args.length : 0; + + var expectedCount = 1 + getLargestIndex(diagnosticKey); + + if (expectedCount !== actualCount) { + throw new Error(getLocalizedText(TypeScript.DiagnosticCode.Expected_0_arguments_to_message_got_1_instead, [expectedCount, actualCount])); + } + + var valueCount = 1 + getLargestIndex(diagnosticMessageText); + if (valueCount !== expectedCount) { + throw new Error(getLocalizedText(TypeScript.DiagnosticCode.Expected_the_message_0_to_have_1_arguments_but_it_had_2, [diagnosticMessageText, expectedCount, valueCount])); + } + + diagnosticMessageText = diagnosticMessageText.replace(/{(\d+)}/g, function (match, num) { + return typeof args[num] !== 'undefined' ? args[num] : match; + }); + + diagnosticMessageText = diagnosticMessageText.replace(/{(NL)}/g, function (match) { + return TypeScript.newLine(); + }); + + return diagnosticMessageText; + } + TypeScript.getLocalizedText = getLocalizedText; + + function getDiagnosticMessage(diagnosticKey, args) { + var diagnostic = getDiagnosticInfoFromKey(diagnosticKey); + var diagnosticMessageText = getLocalizedText(diagnosticKey, args); + + var message; + if (diagnostic.category === 1 /* Error */) { + message = getLocalizedText(TypeScript.DiagnosticCode.error_TS_0_1, [diagnostic.code, diagnosticMessageText]); + } else if (diagnostic.category === 0 /* Warning */) { + message = getLocalizedText(TypeScript.DiagnosticCode.warning_TS_0_1, [diagnostic.code, diagnosticMessageText]); + } else { + message = diagnosticMessageText; + } + + return message; + } + TypeScript.getDiagnosticMessage = getDiagnosticMessage; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Errors = (function () { + function Errors() { + } + Errors.argument = function (argument, message) { + return new Error("Invalid argument: " + argument + ". " + message); + }; + + Errors.argumentOutOfRange = function (argument) { + return new Error("Argument out of range: " + argument); + }; + + Errors.argumentNull = function (argument) { + return new Error("Argument null: " + argument); + }; + + Errors.abstract = function () { + return new Error("Operation not implemented properly by subclass."); + }; + + Errors.notYetImplemented = function () { + return new Error("Not yet implemented."); + }; + + Errors.invalidOperation = function (message) { + return new Error("Invalid operation: " + message); + }; + return Errors; + })(); + TypeScript.Errors = Errors; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Hash = (function () { + function Hash() { + } + Hash.computeFnv1aCharArrayHashCode = function (text, start, len) { + var hashCode = Hash.FNV_BASE; + var end = start + len; + + for (var i = start; i < end; i++) { + hashCode = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(hashCode ^ text[i], Hash.FNV_PRIME); + } + + return hashCode; + }; + + Hash.computeSimple31BitCharArrayHashCode = function (key, start, len) { + var hash = 0; + + for (var i = 0; i < len; i++) { + var ch = key[start + i]; + + hash = ((((hash << 5) - hash) | 0) + ch) | 0; + } + + return hash & 0x7FFFFFFF; + }; + + Hash.computeSimple31BitStringHashCode = function (key) { + var hash = 0; + + var start = 0; + var len = key.length; + + for (var i = 0; i < len; i++) { + var ch = key.charCodeAt(start + i); + + hash = ((((hash << 5) - hash) | 0) + ch) | 0; + } + + return hash & 0x7FFFFFFF; + }; + + Hash.computeMurmur2StringHashCode = function (key, seed) { + var m = 0x5bd1e995; + var r = 24; + + var numberOfCharsLeft = key.length; + var h = Math.abs(seed ^ numberOfCharsLeft); + + var index = 0; + while (numberOfCharsLeft >= 2) { + var c1 = key.charCodeAt(index); + var c2 = key.charCodeAt(index + 1); + + var k = Math.abs(c1 | (c2 << 16)); + + k = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(k, m); + k ^= k >> r; + k = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(k, m); + + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + h ^= k; + + index += 2; + numberOfCharsLeft -= 2; + } + + if (numberOfCharsLeft === 1) { + h ^= key.charCodeAt(index); + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + } + + h ^= h >> 13; + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + h ^= h >> 15; + + return h; + }; + + Hash.getPrime = function (min) { + for (var i = 0; i < Hash.primes.length; i++) { + var num = Hash.primes[i]; + if (num >= min) { + return num; + } + } + + throw TypeScript.Errors.notYetImplemented(); + }; + + Hash.expandPrime = function (oldSize) { + var num = oldSize << 1; + if (num > 2146435069 && 2146435069 > oldSize) { + return 2146435069; + } + return Hash.getPrime(num); + }; + + Hash.combine = function (value, currentHash) { + return (((currentHash << 5) + currentHash) + value) & 0x7FFFFFFF; + }; + Hash.FNV_BASE = 2166136261; + Hash.FNV_PRIME = 16777619; + + Hash.primes = [ + 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, + 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, + 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, + 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, + 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, + 4166287, 4999559, 5999471, 7199369]; + return Hash; + })(); + TypeScript.Hash = Hash; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Collections) { + Collections.DefaultHashTableCapacity = 1024; + + var HashTableEntry = (function () { + function HashTableEntry(Key, Value, HashCode, Next) { + this.Key = Key; + this.Value = Value; + this.HashCode = HashCode; + this.Next = Next; + } + return HashTableEntry; + })(); + + var HashTable = (function () { + function HashTable(capacity, hash) { + this.hash = hash; + this.count = 0; + var size = TypeScript.Hash.getPrime(capacity); + this.entries = TypeScript.ArrayUtilities.createArray(size, null); + } + HashTable.prototype.set = function (key, value) { + this.addOrSet(key, value, false); + }; + + HashTable.prototype.add = function (key, value) { + this.addOrSet(key, value, true); + }; + + HashTable.prototype.containsKey = function (key) { + var hashCode = this.computeHashCode(key); + var entry = this.findEntry(key, hashCode); + return entry !== null; + }; + + HashTable.prototype.get = function (key) { + var hashCode = this.computeHashCode(key); + var entry = this.findEntry(key, hashCode); + + return entry === null ? null : entry.Value; + }; + + HashTable.prototype.computeHashCode = function (key) { + var hashCode = this.hash === null ? key.hashCode : this.hash(key); + + hashCode = hashCode & 0x7FFFFFFF; + TypeScript.Debug.assert(hashCode >= 0); + + return hashCode; + }; + + HashTable.prototype.addOrSet = function (key, value, throwOnExistingEntry) { + var hashCode = this.computeHashCode(key); + + var entry = this.findEntry(key, hashCode); + if (entry !== null) { + if (throwOnExistingEntry) { + throw TypeScript.Errors.argument('key', "Key was already in table."); + } + + entry.Key = key; + entry.Value = value; + return; + } + + return this.addEntry(key, value, hashCode); + }; + + HashTable.prototype.findEntry = function (key, hashCode) { + for (var e = this.entries[hashCode % this.entries.length]; e !== null; e = e.Next) { + if (e.HashCode === hashCode && key === e.Key) { + return e; + } + } + + return null; + }; + + HashTable.prototype.addEntry = function (key, value, hashCode) { + var index = hashCode % this.entries.length; + + var e = new HashTableEntry(key, value, hashCode, this.entries[index]); + + this.entries[index] = e; + + if (this.count >= (this.entries.length / 2)) { + this.grow(); + } + + this.count++; + return e.Key; + }; + + HashTable.prototype.grow = function () { + var newSize = TypeScript.Hash.expandPrime(this.entries.length); + + var oldEntries = this.entries; + var newEntries = TypeScript.ArrayUtilities.createArray(newSize, null); + + this.entries = newEntries; + + for (var i = 0; i < oldEntries.length; i++) { + var e = oldEntries[i]; + + while (e !== null) { + var newIndex = e.HashCode % newSize; + var tmp = e.Next; + e.Next = newEntries[newIndex]; + newEntries[newIndex] = e; + e = tmp; + } + } + }; + return HashTable; + })(); + Collections.HashTable = HashTable; + + function createHashTable(capacity, hash) { + if (typeof capacity === "undefined") { capacity = Collections.DefaultHashTableCapacity; } + if (typeof hash === "undefined") { hash = null; } + return new HashTable(capacity, hash); + } + Collections.createHashTable = createHashTable; + + var currentHashCode = 1; + function identityHashCode(value) { + if (value.__hash === undefined) { + value.__hash = currentHashCode; + currentHashCode++; + } + + return value.__hash; + } + Collections.identityHashCode = identityHashCode; + })(TypeScript.Collections || (TypeScript.Collections = {})); + var Collections = TypeScript.Collections; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + TypeScript.nodeMakeDirectoryTime = 0; + TypeScript.nodeCreateBufferTime = 0; + TypeScript.nodeWriteFileSyncTime = 0; + + (function (ByteOrderMark) { + ByteOrderMark[ByteOrderMark["None"] = 0] = "None"; + ByteOrderMark[ByteOrderMark["Utf8"] = 1] = "Utf8"; + ByteOrderMark[ByteOrderMark["Utf16BigEndian"] = 2] = "Utf16BigEndian"; + ByteOrderMark[ByteOrderMark["Utf16LittleEndian"] = 3] = "Utf16LittleEndian"; + })(TypeScript.ByteOrderMark || (TypeScript.ByteOrderMark = {})); + var ByteOrderMark = TypeScript.ByteOrderMark; + + var FileInformation = (function () { + function FileInformation(contents, byteOrderMark) { + this.contents = contents; + this.byteOrderMark = byteOrderMark; + } + return FileInformation; + })(); + TypeScript.FileInformation = FileInformation; + + TypeScript.Environment = (function () { + function getWindowsScriptHostEnvironment() { + try { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + } catch (e) { + return null; + } + + 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 { + newLine: "\r\n", + currentDirectory: function () { + return WScript.CreateObject("WScript.Shell").CurrentDirectory; + }, + supportsCodePage: function () { + return WScript.ReadFile; + }, + readFile: function (path, codepage) { + try { + if (codepage !== null && this.supportsCodePage()) { + try { + var contents = WScript.ReadFile(path, codepage); + return new FileInformation(contents, 0 /* None */); + } catch (e) { + } + } + + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; + + streamObj.Charset = 'x-ansi'; + + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); + + streamObj.Position = 0; + + var byteOrderMark = 0 /* None */; + + if (bomChar.charCodeAt(0) === 0xFE && bomChar.charCodeAt(1) === 0xFF) { + streamObj.Charset = 'unicode'; + byteOrderMark = 2 /* Utf16BigEndian */; + } else if (bomChar.charCodeAt(0) === 0xFF && bomChar.charCodeAt(1) === 0xFE) { + streamObj.Charset = 'unicode'; + byteOrderMark = 3 /* Utf16LittleEndian */; + } else if (bomChar.charCodeAt(0) === 0xEF && bomChar.charCodeAt(1) === 0xBB) { + streamObj.Charset = 'utf-8'; + byteOrderMark = 1 /* Utf8 */; + } else { + streamObj.Charset = 'utf-8'; + } + + var contents = streamObj.ReadText(-1); + streamObj.Close(); + releaseStreamObject(streamObj); + return new FileInformation(contents, byteOrderMark); + } catch (err) { + var message; + if (err.number === -2147024809) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Unsupported_file_encoding, null); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Cannot_read_file_0_1, [path, err.message]); + } + + throw new Error(message); + } + }, + writeFile: function (path, contents, writeByteOrderMark) { + var textStream = getStreamObject(); + textStream.Charset = 'utf-8'; + textStream.Open(); + textStream.WriteText(contents, 0); + + if (!writeByteOrderMark) { + textStream.Position = 3; + } else { + textStream.Position = 0; + } + + var fileStream = getStreamObject(); + fileStream.Type = 1; + fileStream.Open(); + + textStream.CopyTo(fileStream); + + fileStream.Flush(); + fileStream.SaveToFile(path, 2); + fileStream.Close(); + + textStream.Flush(); + textStream.Close(); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + deleteFile: function (path) { + if (fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + listFiles: 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); + }, + arguments: args, + standardOut: WScript.StdOut + }; + } + ; + + function getNodeEnvironment() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + var _os = require('os'); + + return { + newLine: _os.EOL, + currentDirectory: function () { + return process.cwd(); + }, + supportsCodePage: function () { + return false; + }, + readFile: function (file, codepage) { + if (codepage !== null) { + throw new Error(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.codepage_option_not_supported_on_current_platform, null)); + } + + 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 new FileInformation(buffer.toString("ucs2", 2), 2 /* Utf16BigEndian */); + } + break; + case 0xFF: + if (buffer[1] === 0xFE) { + return new FileInformation(buffer.toString("ucs2", 2), 3 /* Utf16LittleEndian */); + } + break; + case 0xEF: + if (buffer[1] === 0xBB) { + return new FileInformation(buffer.toString("utf8", 3), 1 /* Utf8 */); + } + } + + return new FileInformation(buffer.toString("utf8", 0), 0 /* None */); + }, + writeFile: function (path, contents, writeByteOrderMark) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if (stats.isFile()) { + throw "\"" + path + "\" exists but isn't a directory."; + } else if (stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 509); + } + } + var start = new Date().getTime(); + mkdirRecursiveSync(_path.dirname(path)); + TypeScript.nodeMakeDirectoryTime += new Date().getTime() - start; + + if (writeByteOrderMark) { + contents = '\uFEFF' + contents; + } + + var start = new Date().getTime(); + + var chunkLength = 4 * 1024; + var fileDescriptor = _fs.openSync(path, "w"); + try { + for (var index = 0; index < contents.length; index += chunkLength) { + var bufferStart = new Date().getTime(); + var buffer = new Buffer(contents.substr(index, chunkLength), "utf8"); + TypeScript.nodeCreateBufferTime += new Date().getTime() - bufferStart; + + _fs.writeSync(fileDescriptor, buffer, 0, buffer.length, null); + } + } finally { + _fs.closeSync(fileDescriptor); + } + + TypeScript.nodeWriteFileSyncTime += new Date().getTime() - start; + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); + }, + listFiles: 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); + }, + arguments: process.argv.slice(2), + standardOut: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + } + }; + } + ; + + if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { + return getWindowsScriptHostEnvironment(); + } else if (typeof module !== 'undefined' && module.exports) { + return getNodeEnvironment(); + } else { + return null; + } + })(); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (IntegerUtilities) { + function integerDivide(numerator, denominator) { + return (numerator / denominator) >> 0; + } + IntegerUtilities.integerDivide = integerDivide; + + function integerMultiplyLow32Bits(n1, n2) { + var n1Low16 = n1 & 0x0000ffff; + var n1High16 = n1 >>> 16; + + var n2Low16 = n2 & 0x0000ffff; + var n2High16 = n2 >>> 16; + + var resultLow32 = (((n1 & 0xffff0000) * n2) >>> 0) + (((n1 & 0x0000ffff) * n2) >>> 0) >>> 0; + return resultLow32; + } + IntegerUtilities.integerMultiplyLow32Bits = integerMultiplyLow32Bits; + + function integerMultiplyHigh32Bits(n1, n2) { + var n1Low16 = n1 & 0x0000ffff; + var n1High16 = n1 >>> 16; + + var n2Low16 = n2 & 0x0000ffff; + var n2High16 = n2 >>> 16; + + var resultHigh32 = n1High16 * n2High16 + ((((n1Low16 * n2Low16) >>> 17) + n1Low16 * n2High16) >>> 15); + return resultHigh32; + } + IntegerUtilities.integerMultiplyHigh32Bits = integerMultiplyHigh32Bits; + + function isInteger(text) { + return /^[0-9]+$/.test(text); + } + IntegerUtilities.isInteger = isInteger; + + function isHexInteger(text) { + return /^0(x|X)[0-9a-fA-F]+$/.test(text); + } + IntegerUtilities.isHexInteger = isHexInteger; + })(TypeScript.IntegerUtilities || (TypeScript.IntegerUtilities = {})); + var IntegerUtilities = TypeScript.IntegerUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var LineMap = (function () { + function LineMap(_computeLineStarts, length) { + this._computeLineStarts = _computeLineStarts; + this.length = length; + this._lineStarts = null; + } + LineMap.prototype.toJSON = function (key) { + return { lineStarts: this.lineStarts(), length: this.length }; + }; + + LineMap.prototype.equals = function (other) { + return this.length === other.length && TypeScript.ArrayUtilities.sequenceEquals(this.lineStarts(), other.lineStarts(), function (v1, v2) { + return v1 === v2; + }); + }; + + LineMap.prototype.lineStarts = function () { + if (this._lineStarts === null) { + this._lineStarts = this._computeLineStarts(); + } + + return this._lineStarts; + }; + + LineMap.prototype.lineCount = function () { + return this.lineStarts().length; + }; + + LineMap.prototype.getPosition = function (line, character) { + return this.lineStarts()[line] + character; + }; + + LineMap.prototype.getLineNumberFromPosition = function (position) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + if (position === this.length) { + return this.lineCount() - 1; + } + + var lineNumber = TypeScript.ArrayUtilities.binarySearch(this.lineStarts(), position); + if (lineNumber < 0) { + lineNumber = (~lineNumber) - 1; + } + + return lineNumber; + }; + + LineMap.prototype.getLineStartPosition = function (lineNumber) { + return this.lineStarts()[lineNumber]; + }; + + LineMap.prototype.fillLineAndCharacterFromPosition = function (position, lineAndCharacter) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + lineAndCharacter.line = lineNumber; + lineAndCharacter.character = position - this.lineStarts()[lineNumber]; + }; + + LineMap.prototype.getLineAndCharacterFromPosition = function (position) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + + return new TypeScript.LineAndCharacter(lineNumber, position - this.lineStarts()[lineNumber]); + }; + LineMap.empty = new LineMap(function () { + return [0]; + }, 0); + return LineMap; + })(); + TypeScript.LineMap = LineMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var LineAndCharacter = (function () { + function LineAndCharacter(line, character) { + this._line = 0; + this._character = 0; + if (line < 0) { + throw TypeScript.Errors.argumentOutOfRange("line"); + } + + if (character < 0) { + throw TypeScript.Errors.argumentOutOfRange("character"); + } + + this._line = line; + this._character = character; + } + LineAndCharacter.prototype.line = function () { + return this._line; + }; + + LineAndCharacter.prototype.character = function () { + return this._character; + }; + return LineAndCharacter; + })(); + TypeScript.LineAndCharacter = LineAndCharacter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var MathPrototype = (function () { + function MathPrototype() { + } + MathPrototype.max = function (a, b) { + return a >= b ? a : b; + }; + + MathPrototype.min = function (a, b) { + return a <= b ? a : b; + }; + return MathPrototype; + })(); + TypeScript.MathPrototype = MathPrototype; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Collections) { + Collections.DefaultStringTableCapacity = 256; + + var StringTableEntry = (function () { + function StringTableEntry(Text, HashCode, Next) { + this.Text = Text; + this.HashCode = HashCode; + this.Next = Next; + } + return StringTableEntry; + })(); + + var StringTable = (function () { + function StringTable(capacity) { + this.count = 0; + var size = TypeScript.Hash.getPrime(capacity); + this.entries = TypeScript.ArrayUtilities.createArray(size, null); + } + StringTable.prototype.addCharArray = function (key, start, len) { + var hashCode = TypeScript.Hash.computeSimple31BitCharArrayHashCode(key, start, len) & 0x7FFFFFFF; + + var entry = this.findCharArrayEntry(key, start, len, hashCode); + if (entry !== null) { + return entry.Text; + } + + var slice = key.slice(start, start + len); + return this.addEntry(TypeScript.StringUtilities.fromCharCodeArray(slice), hashCode); + }; + + StringTable.prototype.findCharArrayEntry = function (key, start, len, hashCode) { + for (var e = this.entries[hashCode % this.entries.length]; e !== null; e = e.Next) { + if (e.HashCode === hashCode && StringTable.textCharArrayEquals(e.Text, key, start, len)) { + return e; + } + } + + return null; + }; + + StringTable.prototype.addEntry = function (text, hashCode) { + var index = hashCode % this.entries.length; + + var e = new StringTableEntry(text, hashCode, this.entries[index]); + + this.entries[index] = e; + + if (this.count === this.entries.length) { + this.grow(); + } + + this.count++; + return e.Text; + }; + + StringTable.prototype.grow = function () { + var newSize = TypeScript.Hash.expandPrime(this.entries.length); + + var oldEntries = this.entries; + var newEntries = TypeScript.ArrayUtilities.createArray(newSize, null); + + this.entries = newEntries; + + for (var i = 0; i < oldEntries.length; i++) { + var e = oldEntries[i]; + while (e !== null) { + var newIndex = e.HashCode % newSize; + var tmp = e.Next; + e.Next = newEntries[newIndex]; + newEntries[newIndex] = e; + e = tmp; + } + } + }; + + StringTable.textCharArrayEquals = function (text, array, start, length) { + if (text.length !== length) { + return false; + } + + var s = start; + for (var i = 0; i < length; i++) { + if (text.charCodeAt(i) !== array[s]) { + return false; + } + + s++; + } + + return true; + }; + return StringTable; + })(); + Collections.StringTable = StringTable; + + Collections.DefaultStringTable = new StringTable(Collections.DefaultStringTableCapacity); + })(TypeScript.Collections || (TypeScript.Collections = {})); + var Collections = TypeScript.Collections; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var StringUtilities = (function () { + function StringUtilities() { + } + StringUtilities.isString = function (value) { + return Object.prototype.toString.apply(value, []) === '[object String]'; + }; + + StringUtilities.fromCharCodeArray = function (array) { + return String.fromCharCode.apply(null, array); + }; + + StringUtilities.endsWith = function (string, value) { + return string.substring(string.length - value.length, string.length) === value; + }; + + StringUtilities.startsWith = function (string, value) { + return string.substr(0, value.length) === value; + }; + + StringUtilities.copyTo = function (source, sourceIndex, destination, destinationIndex, count) { + for (var i = 0; i < count; i++) { + destination[destinationIndex + i] = source.charCodeAt(sourceIndex + i); + } + }; + + StringUtilities.repeat = function (value, count) { + return Array(count + 1).join(value); + }; + + StringUtilities.stringEquals = function (val1, val2) { + return val1 === val2; + }; + return StringUtilities; + })(); + TypeScript.StringUtilities = StringUtilities; +})(TypeScript || (TypeScript = {})); +var global = Function("return this").call(null); + +var TypeScript; +(function (TypeScript) { + var Clock; + (function (Clock) { + Clock.now; + Clock.resolution; + + if (typeof WScript !== "undefined" && typeof global['WScript'].InitializeProjection !== "undefined") { + global['WScript'].InitializeProjection(); + + Clock.now = function () { + return TestUtilities.QueryPerformanceCounter(); + }; + + Clock.resolution = TestUtilities.QueryPerformanceFrequency(); + } else { + Clock.now = function () { + return Date.now(); + }; + + Clock.resolution = 1000; + } + })(Clock || (Clock = {})); + + var Timer = (function () { + function Timer() { + this.time = 0; + } + Timer.prototype.start = function () { + this.time = 0; + this.startTime = Clock.now(); + }; + + Timer.prototype.end = function () { + this.time = (Clock.now() - this.startTime); + }; + return Timer; + })(); + TypeScript.Timer = Timer; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + DiagnosticCategory[DiagnosticCategory["NoPrefix"] = 3] = "NoPrefix"; + })(TypeScript.DiagnosticCategory || (TypeScript.DiagnosticCategory = {})); + var DiagnosticCategory = TypeScript.DiagnosticCategory; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.diagnosticInformationMap = { + "error TS{0}: {1}": { + "code": 0, + "category": 3 /* NoPrefix */ + }, + "warning TS{0}: {1}": { + "code": 1, + "category": 3 /* NoPrefix */ + }, + "Unrecognized escape sequence.": { + "code": 1000, + "category": 1 /* Error */ + }, + "Unexpected character {0}.": { + "code": 1001, + "category": 1 /* Error */ + }, + "Missing close quote character.": { + "code": 1002, + "category": 1 /* Error */ + }, + "Identifier expected.": { + "code": 1003, + "category": 1 /* Error */ + }, + "'{0}' keyword expected.": { + "code": 1004, + "category": 1 /* Error */ + }, + "'{0}' expected.": { + "code": 1005, + "category": 1 /* Error */ + }, + "Identifier expected; '{0}' is a keyword.": { + "code": 1006, + "category": 1 /* Error */ + }, + "Automatic semicolon insertion not allowed.": { + "code": 1007, + "category": 1 /* Error */ + }, + "Unexpected token; '{0}' expected.": { + "code": 1008, + "category": 1 /* Error */ + }, + "Trailing separator not allowed.": { + "code": 1009, + "category": 1 /* Error */ + }, + "'*/' expected.": { + "code": 1010, + "category": 1 /* Error */ + }, + "'public' or 'private' modifier must precede 'static'.": { + "code": 1011, + "category": 1 /* Error */ + }, + "Unexpected token.": { + "code": 1012, + "category": 1 /* Error */ + }, + "Catch clause parameter cannot have a type annotation.": { + "code": 1013, + "category": 1 /* Error */ + }, + "Rest parameter must be last in list.": { + "code": 1014, + "category": 1 /* Error */ + }, + "Parameter cannot have question mark and initializer.": { + "code": 1015, + "category": 1 /* Error */ + }, + "Required parameter cannot follow optional parameter.": { + "code": 1016, + "category": 1 /* Error */ + }, + "Index signatures cannot have rest parameters.": { + "code": 1017, + "category": 1 /* Error */ + }, + "Index signature parameter cannot have accessibility modifiers.": { + "code": 1018, + "category": 1 /* Error */ + }, + "Index signature parameter cannot have a question mark.": { + "code": 1019, + "category": 1 /* Error */ + }, + "Index signature parameter cannot have an initializer.": { + "code": 1020, + "category": 1 /* Error */ + }, + "Index signature must have a type annotation.": { + "code": 1021, + "category": 1 /* Error */ + }, + "Index signature parameter must have a type annotation.": { + "code": 1022, + "category": 1 /* Error */ + }, + "Index signature parameter type must be 'string' or 'number'.": { + "code": 1023, + "category": 1 /* Error */ + }, + "'extends' clause already seen.": { + "code": 1024, + "category": 1 /* Error */ + }, + "'extends' clause must precede 'implements' clause.": { + "code": 1025, + "category": 1 /* Error */ + }, + "Classes can only extend a single class.": { + "code": 1026, + "category": 1 /* Error */ + }, + "'implements' clause already seen.": { + "code": 1027, + "category": 1 /* Error */ + }, + "Accessibility modifier already seen.": { + "code": 1028, + "category": 1 /* Error */ + }, + "'{0}' modifier must precede '{1}' modifier.": { + "code": 1029, + "category": 1 /* Error */ + }, + "'{0}' modifier already seen.": { + "code": 1030, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a class element.": { + "code": 1031, + "category": 1 /* Error */ + }, + "Interface declaration cannot have 'implements' clause.": { + "code": 1032, + "category": 1 /* Error */ + }, + "'super' invocation cannot have type arguments.": { + "code": 1034, + "category": 1 /* Error */ + }, + "Only ambient modules can use quoted names.": { + "code": 1035, + "category": 1 /* Error */ + }, + "Statements are not allowed in ambient contexts.": { + "code": 1036, + "category": 1 /* Error */ + }, + "Implementations are not allowed in ambient contexts.": { + "code": 1037, + "category": 1 /* Error */ + }, + "'declare' modifier not allowed for code already in an ambient context.": { + "code": 1038, + "category": 1 /* Error */ + }, + "Initializers are not allowed in ambient contexts.": { + "code": 1039, + "category": 1 /* Error */ + }, + "Parameter property declarations can only be used in a non-ambient constructor declaration.": { + "code": 1040, + "category": 1 /* Error */ + }, + "Function implementation expected.": { + "code": 1041, + "category": 1 /* Error */ + }, + "Constructor implementation expected.": { + "code": 1042, + "category": 1 /* Error */ + }, + "Function overload name must be '{0}'.": { + "code": 1043, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a module element.": { + "code": 1044, + "category": 1 /* Error */ + }, + "'declare' modifier cannot appear on an interface declaration.": { + "code": 1045, + "category": 1 /* Error */ + }, + "'declare' modifier required for top level element.": { + "code": 1046, + "category": 1 /* Error */ + }, + "Rest parameter cannot be optional.": { + "code": 1047, + "category": 1 /* Error */ + }, + "Rest parameter cannot have an initializer.": { + "code": 1048, + "category": 1 /* Error */ + }, + "'set' accessor must have one and only one parameter.": { + "code": 1049, + "category": 1 /* Error */ + }, + "'set' accessor parameter cannot be optional.": { + "code": 1051, + "category": 1 /* Error */ + }, + "'set' accessor parameter cannot have an initializer.": { + "code": 1052, + "category": 1 /* Error */ + }, + "'set' accessor cannot have rest parameter.": { + "code": 1053, + "category": 1 /* Error */ + }, + "'get' accessor cannot have parameters.": { + "code": 1054, + "category": 1 /* Error */ + }, + "Modifiers cannot appear here.": { + "code": 1055, + "category": 1 /* Error */ + }, + "Accessors are only available when targeting ECMAScript 5 and higher.": { + "code": 1056, + "category": 1 /* Error */ + }, + "Class name cannot be '{0}'.": { + "code": 1057, + "category": 1 /* Error */ + }, + "Interface name cannot be '{0}'.": { + "code": 1058, + "category": 1 /* Error */ + }, + "Enum name cannot be '{0}'.": { + "code": 1059, + "category": 1 /* Error */ + }, + "Module name cannot be '{0}'.": { + "code": 1060, + "category": 1 /* Error */ + }, + "Enum member must have initializer.": { + "code": 1061, + "category": 1 /* Error */ + }, + "Export assignment cannot be used in internal modules.": { + "code": 1063, + "category": 1 /* Error */ + }, + "Export assignment not allowed in module with exported element.": { + "code": 1064, + "category": 1 /* Error */ + }, + "Module cannot have multiple export assignments.": { + "code": 1065, + "category": 1 /* Error */ + }, + "Ambient enum elements can only have integer literal initializers.": { + "code": 1066, + "category": 1 /* Error */ + }, + "module, class, interface, enum, import or statement": { + "code": 1067, + "category": 3 /* NoPrefix */ + }, + "constructor, function, accessor or variable": { + "code": 1068, + "category": 3 /* NoPrefix */ + }, + "statement": { + "code": 1069, + "category": 3 /* NoPrefix */ + }, + "case or default clause": { + "code": 1070, + "category": 3 /* NoPrefix */ + }, + "identifier": { + "code": 1071, + "category": 3 /* NoPrefix */ + }, + "call, construct, index, property or function signature": { + "code": 1072, + "category": 3 /* NoPrefix */ + }, + "expression": { + "code": 1073, + "category": 3 /* NoPrefix */ + }, + "type name": { + "code": 1074, + "category": 3 /* NoPrefix */ + }, + "property or accessor": { + "code": 1075, + "category": 3 /* NoPrefix */ + }, + "parameter": { + "code": 1076, + "category": 3 /* NoPrefix */ + }, + "type": { + "code": 1077, + "category": 3 /* NoPrefix */ + }, + "type parameter": { + "code": 1078, + "category": 3 /* NoPrefix */ + }, + "'declare' modifier not allowed on import declaration.": { + "code": 1079, + "category": 1 /* Error */ + }, + "Function overload must be static.": { + "code": 1080, + "category": 1 /* Error */ + }, + "Function overload must not be static.": { + "code": 1081, + "category": 1 /* Error */ + }, + "Parameter property declarations cannot be used in a constructor overload.": { + "code": 1083, + "category": 1 /* Error */ + }, + "Invalid 'reference' directive syntax.": { + "code": 1084, + "category": 1 /* Error */ + }, + "Octal literals are not available when targeting ECMAScript 5 and higher.": { + "code": 1085, + "category": 1 /* Error */ + }, + "Accessors are not allowed in ambient contexts.": { + "code": 1086, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a constructor declaration.": { + "code": 1089, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a parameter.": { + "code": 1090, + "category": 1 /* Error */ + }, + "Only a single variable declaration is allowed in a 'for...in' statement.": { + "code": 1091, + "category": 1 /* Error */ + }, + "Type parameters cannot appear on a constructor declaration.": { + "code": 1091, + "category": 1 /* Error */ + }, + "Type annotation cannot appear on a constructor declaration.": { + "code": 1092, + "category": 1 /* Error */ + }, + "Duplicate identifier '{0}'.": { + "code": 2000, + "category": 1 /* Error */ + }, + "The name '{0}' does not exist in the current scope.": { + "code": 2001, + "category": 1 /* Error */ + }, + "The name '{0}' does not refer to a value.": { + "code": 2002, + "category": 1 /* Error */ + }, + "'super' can only be used inside a class instance method.": { + "code": 2003, + "category": 1 /* Error */ + }, + "The left-hand side of an assignment expression must be a variable, property or indexer.": { + "code": 2004, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not callable. Did you mean to include 'new'?": { + "code": 2161, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not callable.": { + "code": 2006, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not newable.": { + "code": 2007, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not indexable by type '{1}'.": { + "code": 2008, + "category": 1 /* Error */ + }, + "Operator '{0}' cannot be applied to types '{1}' and '{2}'.": { + "code": 2009, + "category": 1 /* Error */ + }, + "Operator '{0}' cannot be applied to types '{1}' and '{2}': {3}": { + "code": 2010, + "category": 1 /* Error */ + }, + "Cannot convert '{0}' to '{1}'.": { + "code": 2011, + "category": 1 /* Error */ + }, + "Cannot convert '{0}' to '{1}':{NL}{2}": { + "code": 2012, + "category": 1 /* Error */ + }, + "Expected var, class, interface, or module.": { + "code": 2013, + "category": 1 /* Error */ + }, + "Operator '{0}' cannot be applied to type '{1}'.": { + "code": 2014, + "category": 1 /* Error */ + }, + "Getter '{0}' already declared.": { + "code": 2015, + "category": 1 /* Error */ + }, + "Setter '{0}' already declared.": { + "code": 2016, + "category": 1 /* Error */ + }, + "Exported class '{0}' extends private class '{1}'.": { + "code": 2018, + "category": 1 /* Error */ + }, + "Exported class '{0}' implements private interface '{1}'.": { + "code": 2019, + "category": 1 /* Error */ + }, + "Exported interface '{0}' extends private interface '{1}'.": { + "code": 2020, + "category": 1 /* Error */ + }, + "Exported class '{0}' extends class from inaccessible module {1}.": { + "code": 2021, + "category": 1 /* Error */ + }, + "Exported class '{0}' implements interface from inaccessible module {1}.": { + "code": 2022, + "category": 1 /* Error */ + }, + "Exported interface '{0}' extends interface from inaccessible module {1}.": { + "code": 2023, + "category": 1 /* Error */ + }, + "Public static property '{0}' of exported class has or is using private type '{1}'.": { + "code": 2024, + "category": 1 /* Error */ + }, + "Public property '{0}' of exported class has or is using private type '{1}'.": { + "code": 2025, + "category": 1 /* Error */ + }, + "Property '{0}' of exported interface has or is using private type '{1}'.": { + "code": 2026, + "category": 1 /* Error */ + }, + "Exported variable '{0}' has or is using private type '{1}'.": { + "code": 2027, + "category": 1 /* Error */ + }, + "Public static property '{0}' of exported class is using inaccessible module {1}.": { + "code": 2028, + "category": 1 /* Error */ + }, + "Public property '{0}' of exported class is using inaccessible module {1}.": { + "code": 2029, + "category": 1 /* Error */ + }, + "Property '{0}' of exported interface is using inaccessible module {1}.": { + "code": 2030, + "category": 1 /* Error */ + }, + "Exported variable '{0}' is using inaccessible module {1}.": { + "code": 2031, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor from exported class has or is using private type '{1}'.": { + "code": 2032, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static property setter from exported class has or is using private type '{1}'.": { + "code": 2033, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public property setter from exported class has or is using private type '{1}'.": { + "code": 2034, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.": { + "code": 2035, + "category": 1 /* Error */ + }, + "Parameter '{0}' of call signature from exported interface has or is using private type '{1}'.": { + "code": 2036, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static method from exported class has or is using private type '{1}'.": { + "code": 2037, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public method from exported class has or is using private type '{1}'.": { + "code": 2038, + "category": 1 /* Error */ + }, + "Parameter '{0}' of method from exported interface has or is using private type '{1}'.": { + "code": 2039, + "category": 1 /* Error */ + }, + "Parameter '{0}' of exported function has or is using private type '{1}'.": { + "code": 2040, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor from exported class is using inaccessible module {1}.": { + "code": 2041, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static property setter from exported class is using inaccessible module {1}.": { + "code": 2042, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public property setter from exported class is using inaccessible module {1}.": { + "code": 2043, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.": { + "code": 2044, + "category": 1 /* Error */ + }, + "Parameter '{0}' of call signature from exported interface is using inaccessible module {1}": { + "code": 2045, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static method from exported class is using inaccessible module {1}.": { + "code": 2046, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public method from exported class is using inaccessible module {1}.": { + "code": 2047, + "category": 1 /* Error */ + }, + "Parameter '{0}' of method from exported interface is using inaccessible module {1}.": { + "code": 2048, + "category": 1 /* Error */ + }, + "Parameter '{0}' of exported function is using inaccessible module {1}.": { + "code": 2049, + "category": 1 /* Error */ + }, + "Return type of public static property getter from exported class has or is using private type '{0}'.": { + "code": 2050, + "category": 1 /* Error */ + }, + "Return type of public property getter from exported class has or is using private type '{0}'.": { + "code": 2051, + "category": 1 /* Error */ + }, + "Return type of constructor signature from exported interface has or is using private type '{0}'.": { + "code": 2052, + "category": 1 /* Error */ + }, + "Return type of call signature from exported interface has or is using private type '{0}'.": { + "code": 2053, + "category": 1 /* Error */ + }, + "Return type of index signature from exported interface has or is using private type '{0}'.": { + "code": 2054, + "category": 1 /* Error */ + }, + "Return type of public static method from exported class has or is using private type '{0}'.": { + "code": 2055, + "category": 1 /* Error */ + }, + "Return type of public method from exported class has or is using private type '{0}'.": { + "code": 2056, + "category": 1 /* Error */ + }, + "Return type of method from exported interface has or is using private type '{0}'.": { + "code": 2057, + "category": 1 /* Error */ + }, + "Return type of exported function has or is using private type '{0}'.": { + "code": 2058, + "category": 1 /* Error */ + }, + "Return type of public static property getter from exported class is using inaccessible module {0}.": { + "code": 2059, + "category": 1 /* Error */ + }, + "Return type of public property getter from exported class is using inaccessible module {0}.": { + "code": 2060, + "category": 1 /* Error */ + }, + "Return type of constructor signature from exported interface is using inaccessible module {0}.": { + "code": 2061, + "category": 1 /* Error */ + }, + "Return type of call signature from exported interface is using inaccessible module {0}.": { + "code": 2062, + "category": 1 /* Error */ + }, + "Return type of index signature from exported interface is using inaccessible module {0}.": { + "code": 2063, + "category": 1 /* Error */ + }, + "Return type of public static method from exported class is using inaccessible module {0}.": { + "code": 2064, + "category": 1 /* Error */ + }, + "Return type of public method from exported class is using inaccessible module {0}.": { + "code": 2065, + "category": 1 /* Error */ + }, + "Return type of method from exported interface is using inaccessible module {0}.": { + "code": 2066, + "category": 1 /* Error */ + }, + "Return type of exported function is using inaccessible module {0}.": { + "code": 2067, + "category": 1 /* Error */ + }, + "'new T[]' cannot be used to create an array. Use 'new Array()' instead.": { + "code": 2068, + "category": 1 /* Error */ + }, + "A parameter list must follow a generic type argument list. '(' expected.": { + "code": 2069, + "category": 1 /* Error */ + }, + "Multiple constructor implementations are not allowed.": { + "code": 2070, + "category": 1 /* Error */ + }, + "Unable to resolve external module '{0}'.": { + "code": 2071, + "category": 1 /* Error */ + }, + "Module cannot be aliased to a non-module type.": { + "code": 2072, + "category": 1 /* Error */ + }, + "A class may only extend another class.": { + "code": 2073, + "category": 1 /* Error */ + }, + "A class may only implement another class or interface.": { + "code": 2074, + "category": 1 /* Error */ + }, + "An interface may only extend another class or interface.": { + "code": 2075, + "category": 1 /* Error */ + }, + "Unable to resolve type.": { + "code": 2077, + "category": 1 /* Error */ + }, + "Unable to resolve type of '{0}'.": { + "code": 2078, + "category": 1 /* Error */ + }, + "Unable to resolve type parameter constraint.": { + "code": 2079, + "category": 1 /* Error */ + }, + "Type parameter constraint cannot be a primitive type.": { + "code": 2080, + "category": 1 /* Error */ + }, + "Supplied parameters do not match any signature of call target.": { + "code": 2081, + "category": 1 /* Error */ + }, + "Supplied parameters do not match any signature of call target:{NL}{0}": { + "code": 2082, + "category": 1 /* Error */ + }, + "Invalid 'new' expression.": { + "code": 2083, + "category": 1 /* Error */ + }, + "Call signatures used in a 'new' expression must have a 'void' return type.": { + "code": 2084, + "category": 1 /* Error */ + }, + "Could not select overload for 'new' expression.": { + "code": 2085, + "category": 1 /* Error */ + }, + "Type '{0}' does not satisfy the constraint '{1}' for type parameter '{2}'.": { + "code": 2086, + "category": 1 /* Error */ + }, + "Could not select overload for 'call' expression.": { + "code": 2087, + "category": 1 /* Error */ + }, + "Cannot invoke an expression whose type lacks a call signature.": { + "code": 2088, + "category": 1 /* Error */ + }, + "Calls to 'super' are only valid inside a class.": { + "code": 2089, + "category": 1 /* Error */ + }, + "Generic type '{0}' requires {1} type argument(s).": { + "code": 2090, + "category": 1 /* Error */ + }, + "Type of array literal cannot be determined. Best common type could not be found for array elements.": { + "code": 2092, + "category": 1 /* Error */ + }, + "Could not find enclosing symbol for dotted name '{0}'.": { + "code": 2093, + "category": 1 /* Error */ + }, + "The property '{0}' does not exist on value of type '{1}'.": { + "code": 2094, + "category": 1 /* Error */ + }, + "Could not find symbol '{0}'.": { + "code": 2095, + "category": 1 /* Error */ + }, + "'get' and 'set' accessor must have the same type.": { + "code": 2096, + "category": 1 /* Error */ + }, + "'this' cannot be referenced in current location.": { + "code": 2097, + "category": 1 /* Error */ + }, + "Static members cannot reference class type parameters.": { + "code": 2099, + "category": 1 /* Error */ + }, + "Class '{0}' is recursively referenced as a base type of itself.": { + "code": 2100, + "category": 1 /* Error */ + }, + "Interface '{0}' is recursively referenced as a base type of itself.": { + "code": 2101, + "category": 1 /* Error */ + }, + "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class.": { + "code": 2102, + "category": 1 /* Error */ + }, + "'super' cannot be referenced in non-derived classes.": { + "code": 2103, + "category": 1 /* Error */ + }, + "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.": { + "code": 2104, + "category": 1 /* Error */ + }, + "Constructors for derived classes must contain a 'super' call.": { + "code": 2105, + "category": 1 /* Error */ + }, + "Super calls are not permitted outside constructors or in nested functions inside constructors.": { + "code": 2106, + "category": 1 /* Error */ + }, + "'{0}.{1}' is inaccessible.": { + "code": 2107, + "category": 1 /* Error */ + }, + "'this' cannot be referenced within module bodies.": { + "code": 2108, + "category": 1 /* Error */ + }, + "Invalid '+' expression - types not known to support the addition operator.": { + "code": 2111, + "category": 1 /* Error */ + }, + "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.": { + "code": 2112, + "category": 1 /* Error */ + }, + "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.": { + "code": 2113, + "category": 1 /* Error */ + }, + "The type of a unary arithmetic operation operand must be of type 'any', 'number' or an enum type.": { + "code": 2114, + "category": 1 /* Error */ + }, + "Variable declarations of a 'for' statement cannot use a type annotation.": { + "code": 2115, + "category": 1 /* Error */ + }, + "Variable declarations of a 'for' statement must be of types 'string' or 'any'.": { + "code": 2116, + "category": 1 /* Error */ + }, + "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter.": { + "code": 2117, + "category": 1 /* Error */ + }, + "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'.": { + "code": 2118, + "category": 1 /* Error */ + }, + "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.": { + "code": 2119, + "category": 1 /* Error */ + }, + "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.": { + "code": 2120, + "category": 1 /* Error */ + }, + "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.": { + "code": 2121, + "category": 1 /* Error */ + }, + "Setters cannot return a value.": { + "code": 2122, + "category": 1 /* Error */ + }, + "Tried to query type of uninitialized module '{0}'.": { + "code": 2123, + "category": 1 /* Error */ + }, + "Tried to set variable type to uninitialized module type '{0}'.": { + "code": 2124, + "category": 1 /* Error */ + }, + "Type '{0}' does not have type parameters.": { + "code": 2125, + "category": 1 /* Error */ + }, + "Getters must return a value.": { + "code": 2126, + "category": 1 /* Error */ + }, + "Getter and setter accessors do not agree in visibility.": { + "code": 2127, + "category": 1 /* Error */ + }, + "Invalid left-hand side of assignment expression.": { + "code": 2130, + "category": 1 /* Error */ + }, + "Function declared a non-void return type, but has no return expression.": { + "code": 2131, + "category": 1 /* Error */ + }, + "Cannot resolve return type reference.": { + "code": 2132, + "category": 1 /* Error */ + }, + "Constructors cannot have a return type of 'void'.": { + "code": 2133, + "category": 1 /* Error */ + }, + "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'.": { + "code": 2134, + "category": 1 /* Error */ + }, + "All symbols within a with block will be resolved to 'any'.": { + "code": 2135, + "category": 1 /* Error */ + }, + "Import declarations in an internal module cannot reference an external module.": { + "code": 2136, + "category": 1 /* Error */ + }, + "Class {0} declares interface {1} but does not implement it:{NL}{2}": { + "code": 2137, + "category": 1 /* Error */ + }, + "Class {0} declares class {1} as an interface but does not implement it:{NL}{2}": { + "code": 2138, + "category": 1 /* Error */ + }, + "The operand of an increment or decrement operator must be a variable, property or indexer.": { + "code": 2139, + "category": 1 /* Error */ + }, + "'this' cannot be referenced in static initializers in a class body.": { + "code": 2140, + "category": 1 /* Error */ + }, + "Class '{0}' cannot extend class '{1}':{NL}{2}": { + "code": 2141, + "category": 1 /* Error */ + }, + "Interface '{0}' cannot extend class '{1}':{NL}{2}": { + "code": 2142, + "category": 1 /* Error */ + }, + "Interface '{0}' cannot extend interface '{1}':{NL}{2}": { + "code": 2143, + "category": 1 /* Error */ + }, + "Duplicate overload signature for '{0}'.": { + "code": 2144, + "category": 1 /* Error */ + }, + "Duplicate constructor overload signature.": { + "code": 2145, + "category": 1 /* Error */ + }, + "Duplicate overload call signature.": { + "code": 2146, + "category": 1 /* Error */ + }, + "Duplicate overload construct signature.": { + "code": 2147, + "category": 1 /* Error */ + }, + "Overload signature is not compatible with function definition.": { + "code": 2148, + "category": 1 /* Error */ + }, + "Overload signature is not compatible with function definition:{NL}{0}": { + "code": 2149, + "category": 1 /* Error */ + }, + "Overload signatures must all be public or private.": { + "code": 2150, + "category": 1 /* Error */ + }, + "Overload signatures must all be exported or not exported.": { + "code": 2151, + "category": 1 /* Error */ + }, + "Overload signatures must all be ambient or non-ambient.": { + "code": 2152, + "category": 1 /* Error */ + }, + "Overload signatures must all be optional or required.": { + "code": 2153, + "category": 1 /* Error */ + }, + "Specialized overload signature is not assignable to any non-specialized signature.": { + "code": 2154, + "category": 1 /* Error */ + }, + "'this' cannot be referenced in constructor arguments.": { + "code": 2155, + "category": 1 /* Error */ + }, + "Instance member cannot be accessed off a class.": { + "code": 2157, + "category": 1 /* Error */ + }, + "Untyped function calls may not accept type arguments.": { + "code": 2158, + "category": 1 /* Error */ + }, + "Non-generic functions may not accept type arguments.": { + "code": 2159, + "category": 1 /* Error */ + }, + "A generic type may not reference itself with a wrapped form of its own type parameters.": { + "code": 2160, + "category": 1 /* Error */ + }, + "Rest parameters must be array types.": { + "code": 2162, + "category": 1 /* Error */ + }, + "Overload signature implementation cannot use specialized type.": { + "code": 2163, + "category": 1 /* Error */ + }, + "Export assignments may only be used at the top-level of external modules.": { + "code": 2164, + "category": 1 /* Error */ + }, + "Export assignments may only be made with variables, functions, classes, interfaces, enums and internal modules.": { + "code": 2165, + "category": 1 /* Error */ + }, + "Only public methods of the base class are accessible via the 'super' keyword.": { + "code": 2166, + "category": 1 /* Error */ + }, + "Numeric indexer type '{0}' must be assignable to string indexer type '{1}'.": { + "code": 2167, + "category": 1 /* Error */ + }, + "Numeric indexer type '{0}' must be assignable to string indexer type '{1}':{NL}{2}": { + "code": 2168, + "category": 1 /* Error */ + }, + "All numerically named properties must be assignable to numeric indexer type '{0}'.": { + "code": 2169, + "category": 1 /* Error */ + }, + "All numerically named properties must be assignable to numeric indexer type '{0}':{NL}{1}": { + "code": 2170, + "category": 1 /* Error */ + }, + "All named properties must be assignable to string indexer type '{0}'.": { + "code": 2171, + "category": 1 /* Error */ + }, + "All named properties must be assignable to string indexer type '{0}':{NL}{1}": { + "code": 2172, + "category": 1 /* Error */ + }, + "Generic type references must include all type arguments.": { + "code": 2173, + "category": 1 /* Error */ + }, + "Default arguments are only allowed in implementation.": { + "code": 2174, + "category": 1 /* Error */ + }, + "Overloads cannot differ only by return type.": { + "code": 2175, + "category": 1 /* Error */ + }, + "Function expression declared a non-void return type, but has no return expression.": { + "code": 2176, + "category": 1 /* Error */ + }, + "Import declaration referencing identifier from internal module can only be made with variables, functions, classes, interfaces, enums and internal modules.": { + "code": 2177, + "category": 1 /* Error */ + }, + "Could not find symbol '{0}' in module '{1}'.": { + "code": 2178, + "category": 1 /* Error */ + }, + "Unable to resolve module reference '{0}'.": { + "code": 2179, + "category": 1 /* Error */ + }, + "Could not find module '{0}' in module '{1}'.": { + "code": 2180, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned value with type that has or is using private type '{1}'.": { + "code": 2181, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned value with type that is using inaccessible module '{1}'.": { + "code": 2182, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned type that has or is using private type '{1}'.": { + "code": 2183, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned type that is using inaccessible module '{1}'.": { + "code": 2184, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned container that is or is using inaccessible module '{1}'.": { + "code": 2185, + "category": 1 /* Error */ + }, + "Type name '{0}' in extends clause does not reference constructor function for '{1}'.": { + "code": 2186, + "category": 1 /* Error */ + }, + "Internal module reference '{0}' in import declaration does not reference module instance for '{1}'.": { + "code": 2187, + "category": 1 /* Error */ + }, + "Module '{0}' cannot merge with previous declaration of '{1}' in a different file '{2}'.": { + "code": 2188, + "category": 1 /* Error */ + }, + "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':{NL}{3}": { + "code": 2189, + "category": 1 /* Error */ + }, + "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it.": { + "code": 2190, + "category": 1 /* Error */ + }, + "Ambient external module declaration cannot be reopened.": { + "code": 2191, + "category": 1 /* Error */ + }, + "All declarations of merged declaration '{0}' must be exported or not exported.": { + "code": 2192, + "category": 1 /* Error */ + }, + "'super' cannot be referenced in constructor arguments.": { + "code": 2193, + "category": 1 /* Error */ + }, + "Return type of constructor signature must be assignable to the instance type of the class.": { + "code": 2194, + "category": 1 /* Error */ + }, + "Ambient external module declaration must be defined in global context.": { + "code": 2195, + "category": 1 /* Error */ + }, + "Ambient external module declaration cannot specify relative module name.": { + "code": 2196, + "category": 1 /* Error */ + }, + "Import declaration in an ambient external module declaration cannot reference external module through relative external module name.": { + "code": 2197, + "category": 1 /* Error */ + }, + "Could not find the best common type of types of all return statement expressions.": { + "code": 2198, + "category": 1 /* Error */ + }, + "Import declaration cannot refer to external module reference when --noResolve option is set.": { + "code": 2199, + "category": 1 /* Error */ + }, + "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference.": { + "code": 2200, + "category": 1 /* Error */ + }, + "'continue' statement can only be used within an enclosing iteration statement.": { + "code": 2201, + "category": 1 /* Error */ + }, + "'break' statement can only be used within an enclosing iteration or switch statement.": { + "code": 2202, + "category": 1 /* Error */ + }, + "Jump target not found.": { + "code": 2203, + "category": 1 /* Error */ + }, + "Jump target cannot cross function boundary.": { + "code": 2204, + "category": 1 /* Error */ + }, + "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference.": { + "code": 2205, + "category": 1 /* Error */ + }, + "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference.": { + "code": 2206, + "category": 1 /* Error */ + }, + "Expression resolves to '_super' that compiler uses to capture base class reference.": { + "code": 2207, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.": { + "code": 2208, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of call signature from exported interface has or is using private type '{1}'.": { + "code": 2209, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public static method from exported class has or is using private type '{1}'.": { + "code": 2210, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public method from exported class has or is using private type '{1}'.": { + "code": 2211, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of method from exported interface has or is using private type '{1}'.": { + "code": 2212, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported function has or is using private type '{1}'.": { + "code": 2213, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.": { + "code": 2214, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of call signature from exported interface is using inaccessible module {1}": { + "code": 2215, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public static method from exported class is using inaccessible module {1}.": { + "code": 2216, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public method from exported class is using inaccessible module {1}.": { + "code": 2217, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of method from exported interface is using inaccessible module {1}.": { + "code": 2218, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported function is using inaccessible module {1}.": { + "code": 2219, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported class has or is using private type '{1}'.": { + "code": 2220, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported interface has or is using private type '{1}'.": { + "code": 2221, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported class is using inaccessible module {1}.": { + "code": 2222, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported interface is using inaccessible module {1}.": { + "code": 2223, + "category": 1 /* Error */ + }, + "Duplicate identifier '_i'. Compiler uses '_i' to initialize rest parameter.": { + "code": 2224, + "category": 1 /* Error */ + }, + "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters.": { + "code": 2225, + "category": 1 /* Error */ + }, + "Type of conditional '{0}' must be identical to '{1}' or '{2}'.": { + "code": 2226, + "category": 1 /* Error */ + }, + "Type of conditional '{0}' must be identical to '{1}', '{2}' or '{3}'.": { + "code": 2227, + "category": 1 /* Error */ + }, + "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of an external module.": { + "code": 2228, + "category": 1 /* Error */ + }, + "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.": { + "code": 2229, + "category": 1 /* Error */ + }, + "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.": { + "code": 2230, + "category": 1 /* Error */ + }, + "Parameter '{0}' cannot be referenced in its initializer.": { + "code": 2231, + "category": 1 /* Error */ + }, + "Duplicate string index signature.": { + "code": 2232, + "category": 1 /* Error */ + }, + "Duplicate number index signature.": { + "code": 2233, + "category": 1 /* Error */ + }, + "All declarations of an interface must have identical type parameters.": { + "code": 2234, + "category": 1 /* Error */ + }, + "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter.": { + "code": 2235, + "category": 1 /* Error */ + }, + "Type '{0}' is missing property '{1}' from type '{2}'.": { + "code": 4000, + "category": 3 /* NoPrefix */ + }, + "Types of property '{0}' of types '{1}' and '{2}' are incompatible.": { + "code": 4001, + "category": 3 /* NoPrefix */ + }, + "Types of property '{0}' of types '{1}' and '{2}' are incompatible:{NL}{3}": { + "code": 4002, + "category": 3 /* NoPrefix */ + }, + "Property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.": { + "code": 4003, + "category": 3 /* NoPrefix */ + }, + "Property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.": { + "code": 4004, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' define property '{2}' as private.": { + "code": 4005, + "category": 3 /* NoPrefix */ + }, + "Call signatures of types '{0}' and '{1}' are incompatible.": { + "code": 4006, + "category": 3 /* NoPrefix */ + }, + "Call signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { + "code": 4007, + "category": 3 /* NoPrefix */ + }, + "Type '{0}' requires a call signature, but type '{1}' lacks one.": { + "code": 4008, + "category": 3 /* NoPrefix */ + }, + "Construct signatures of types '{0}' and '{1}' are incompatible.": { + "code": 4009, + "category": 3 /* NoPrefix */ + }, + "Construct signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { + "code": 4010, + "category": 3 /* NoPrefix */ + }, + "Type '{0}' requires a construct signature, but type '{1}' lacks one.": { + "code": 4011, + "category": 3 /* NoPrefix */ + }, + "Index signatures of types '{0}' and '{1}' are incompatible.": { + "code": 4012, + "category": 3 /* NoPrefix */ + }, + "Index signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { + "code": 4013, + "category": 3 /* NoPrefix */ + }, + "Call signature expects {0} or fewer parameters.": { + "code": 4014, + "category": 3 /* NoPrefix */ + }, + "Could not apply type '{0}' to argument {1} which is of type '{2}'.": { + "code": 4015, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function.": { + "code": 4016, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.": { + "code": 4017, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor.": { + "code": 4018, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.": { + "code": 4019, + "category": 3 /* NoPrefix */ + }, + "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible.": { + "code": 4020, + "category": 3 /* NoPrefix */ + }, + "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible:{NL}{3}": { + "code": 4021, + "category": 3 /* NoPrefix */ + }, + "Type reference cannot refer to container '{0}'.": { + "code": 4022, + "category": 1 /* Error */ + }, + "Type reference must refer to type.": { + "code": 4023, + "category": 1 /* Error */ + }, + "In enums with multiple declarations only one declaration can omit an initializer for the first enum element.": { + "code": 4024, + "category": 1 /* Error */ + }, + " (+ {0} overload(s))": { + "code": 4025, + "category": 2 /* Message */ + }, + "Variable declaration cannot have the same name as an import declaration.": { + "code": 4026, + "category": 1 /* Error */ + }, + "Signature expected {0} type arguments, got {1} instead.": { + "code": 4027, + "category": 1 /* Error */ + }, + "Property '{0}' defined as optional in type '{1}', but is required in type '{2}'.": { + "code": 4028, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference do not refer to same named type.": { + "code": 4029, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments.": { + "code": 4030, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments:{NL}{2}": { + "code": 4031, + "category": 3 /* NoPrefix */ + }, + "Named properties '{0}' of types '{1}' and '{2}' are not identical.": { + "code": 4032, + "category": 3 /* NoPrefix */ + }, + "Types of string indexer of types '{0}' and '{1}' are not identical.": { + "code": 4033, + "category": 3 /* NoPrefix */ + }, + "Types of number indexer of types '{0}' and '{1}' are not identical.": { + "code": 4034, + "category": 3 /* NoPrefix */ + }, + "Type of number indexer in type '{0}' is not assignable to string indexer type in type '{1}'.{NL}{2}": { + "code": 4035, + "category": 3 /* NoPrefix */ + }, + "Type of property '{0}' in type '{1}' is not assignable to string indexer type in type '{2}'.{NL}{3}": { + "code": 4036, + "category": 3 /* NoPrefix */ + }, + "Type of property '{0}' in type '{1}' is not assignable to number indexer type in type '{2}'.{NL}{3}": { + "code": 4037, + "category": 3 /* NoPrefix */ + }, + "Static property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.": { + "code": 4038, + "category": 3 /* NoPrefix */ + }, + "Static property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.": { + "code": 4039, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' define static property '{2}' as private.": { + "code": 4040, + "category": 3 /* NoPrefix */ + }, + "Current host does not support '{0}' option.": { + "code": 5001, + "category": 1 /* Error */ + }, + "ECMAScript target version '{0}' not supported. Specify a valid target version: '{1}' (default), or '{2}'": { + "code": 5002, + "category": 1 /* Error */ + }, + "Module code generation '{0}' not supported.": { + "code": 5003, + "category": 1 /* Error */ + }, + "Could not find file: '{0}'.": { + "code": 5004, + "category": 1 /* Error */ + }, + "A file cannot have a reference to itself.": { + "code": 5006, + "category": 1 /* Error */ + }, + "Cannot resolve referenced file: '{0}'.": { + "code": 5007, + "category": 1 /* Error */ + }, + "Cannot find the common subdirectory path for the input files.": { + "code": 5009, + "category": 1 /* Error */ + }, + "Emit Error: {0}.": { + "code": 5011, + "category": 1 /* Error */ + }, + "Cannot read file '{0}': {1}": { + "code": 5012, + "category": 1 /* Error */ + }, + "Unsupported file encoding.": { + "code": 5013, + "category": 3 /* NoPrefix */ + }, + "Locale must be of the form or -. For example '{0}' or '{1}'.": { + "code": 5014, + "category": 1 /* Error */ + }, + "Unsupported locale: '{0}'.": { + "code": 5015, + "category": 1 /* Error */ + }, + "Execution Failed.{NL}": { + "code": 5016, + "category": 1 /* Error */ + }, + "Invalid call to 'up'": { + "code": 5019, + "category": 1 /* Error */ + }, + "Invalid call to 'down'": { + "code": 5020, + "category": 1 /* Error */ + }, + "Base64 value '{0}' finished with a continuation bit.": { + "code": 5021, + "category": 1 /* Error */ + }, + "Unknown option '{0}'": { + "code": 5023, + "category": 1 /* Error */ + }, + "Expected {0} arguments to message, got {1} instead.": { + "code": 5024, + "category": 1 /* Error */ + }, + "Expected the message '{0}' to have {1} arguments, but it had {2}": { + "code": 5025, + "category": 1 /* Error */ + }, + "Could not delete file '{0}'": { + "code": 5034, + "category": 1 /* Error */ + }, + "Could not create directory '{0}'": { + "code": 5035, + "category": 1 /* Error */ + }, + "Error while executing file '{0}': ": { + "code": 5036, + "category": 1 /* Error */ + }, + "Cannot compile external modules unless the '--module' flag is provided.": { + "code": 5037, + "category": 1 /* Error */ + }, + "Option mapRoot cannot be specified without specifying sourcemap option.": { + "code": 5038, + "category": 1 /* Error */ + }, + "Option sourceRoot cannot be specified without specifying sourcemap option.": { + "code": 5039, + "category": 1 /* Error */ + }, + "Options mapRoot and sourceRoot cannot be specified without specifying sourcemap option.": { + "code": 5040, + "category": 1 /* Error */ + }, + "Option '{0}' specified without '{1}'": { + "code": 5041, + "category": 1 /* Error */ + }, + "'codepage' option not supported on current platform.": { + "code": 5042, + "category": 1 /* Error */ + }, + "Concatenate and emit output to single file.": { + "code": 6001, + "category": 2 /* Message */ + }, + "Generates corresponding {0} file.": { + "code": 6002, + "category": 2 /* Message */ + }, + "Specifies the location where debugger should locate map files instead of generated locations.": { + "code": 6003, + "category": 2 /* Message */ + }, + "Specifies the location where debugger should locate TypeScript files instead of source locations.": { + "code": 6004, + "category": 2 /* Message */ + }, + "Watch input files.": { + "code": 6005, + "category": 2 /* Message */ + }, + "Redirect output structure to the directory.": { + "code": 6006, + "category": 2 /* Message */ + }, + "Do not emit comments to output.": { + "code": 6009, + "category": 2 /* Message */ + }, + "Skip resolution and preprocessing.": { + "code": 6010, + "category": 2 /* Message */ + }, + "Specify ECMAScript target version: '{0}' (default), or '{1}'": { + "code": 6015, + "category": 2 /* Message */ + }, + "Specify module code generation: '{0}' or '{1}'": { + "code": 6016, + "category": 2 /* Message */ + }, + "Print this message.": { + "code": 6017, + "category": 2 /* Message */ + }, + "Print the compiler's version: {0}": { + "code": 6019, + "category": 2 /* Message */ + }, + "Allow use of deprecated '{0}' keyword when referencing an external module.": { + "code": 6021, + "category": 2 /* Message */ + }, + "Specify locale for errors and messages. For example '{0}' or '{1}'": { + "code": 6022, + "category": 2 /* Message */ + }, + "Syntax: {0}": { + "code": 6023, + "category": 2 /* Message */ + }, + "options": { + "code": 6024, + "category": 2 /* Message */ + }, + "file1": { + "code": 6025, + "category": 2 /* Message */ + }, + "Examples:": { + "code": 6026, + "category": 2 /* Message */ + }, + "Options:": { + "code": 6027, + "category": 2 /* Message */ + }, + "Insert command line options and files from a file.": { + "code": 6030, + "category": 2 /* Message */ + }, + "Version {0}": { + "code": 6029, + "category": 2 /* Message */ + }, + "Use the '{0}' flag to see options.": { + "code": 6031, + "category": 2 /* Message */ + }, + "{NL}Recompiling ({0}):": { + "code": 6032, + "category": 2 /* Message */ + }, + "STRING": { + "code": 6033, + "category": 2 /* Message */ + }, + "KIND": { + "code": 6034, + "category": 2 /* Message */ + }, + "file2": { + "code": 6035, + "category": 2 /* Message */ + }, + "VERSION": { + "code": 6036, + "category": 2 /* Message */ + }, + "LOCATION": { + "code": 6037, + "category": 2 /* Message */ + }, + "DIRECTORY": { + "code": 6038, + "category": 2 /* Message */ + }, + "NUMBER": { + "code": 6039, + "category": 2 /* Message */ + }, + "Specify the codepage to use when opening source files.": { + "code": 6040, + "category": 2 /* Message */ + }, + "Additional locations:": { + "code": 6041, + "category": 2 /* Message */ + }, + "This version of the Javascript runtime does not support the '{0}' function.": { + "code": 7000, + "category": 1 /* Error */ + }, + "Unknown rule.": { + "code": 7002, + "category": 1 /* Error */ + }, + "Invalid line number ({0})": { + "code": 7003, + "category": 1 /* Error */ + }, + "Warn on expressions and declarations with an implied 'any' type.": { + "code": 7004, + "category": 2 /* Message */ + }, + "Variable '{0}' implicitly has an 'any' type.": { + "code": 7005, + "category": 1 /* Error */ + }, + "Parameter '{0}' of '{1}' implicitly has an 'any' type.": { + "code": 7006, + "category": 1 /* Error */ + }, + "Parameter '{0}' of function type implicitly has an 'any' type.": { + "code": 7007, + "category": 1 /* Error */ + }, + "Member '{0}' of object type implicitly has an 'any' type.": { + "code": 7008, + "category": 1 /* Error */ + }, + "'new' expression, which lacks a constructor signature, implicitly has an 'any' type.": { + "code": 7009, + "category": 1 /* Error */ + }, + "'{0}', which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7010, + "category": 1 /* Error */ + }, + "Function expression, which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7011, + "category": 1 /* Error */ + }, + "Parameter '{0}' of lambda function implicitly has an 'any' type.": { + "code": 7012, + "category": 1 /* Error */ + }, + "Constructor signature, which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7013, + "category": 1 /* Error */ + }, + "Lambda Function, which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7014, + "category": 1 /* Error */ + }, + "Array Literal implicitly has an 'any' type from widening.": { + "code": 7015, + "category": 1 /* Error */ + }, + "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type.": { + "code": 7016, + "category": 1 /* Error */ + }, + "Index signature of object type implicitly has an 'any' type.": { + "code": 7017, + "category": 1 /* Error */ + }, + "Object literal's property '{0}' implicitly has an 'any' type from widening.": { + "code": 7018, + "category": 1 /* Error */ + } + }; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 0x2028] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 0x2029] = "paragraphSeparator"; + + CharacterCodes[CharacterCodes["nextLine"] = 0x0085] = "nextLine"; + + CharacterCodes[CharacterCodes["space"] = 0x0020] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 0x00A0] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 0x2000] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 0x2001] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 0x2002] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 0x2003] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 0x2004] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 0x2005] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 0x2006] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 0x2007] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 0x2008] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 0x2009] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 0x200A] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 0x200B] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 0x202F] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 0x3000] = "ideographicSpace"; + + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 0xFEFF] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(TypeScript.CharacterCodes || (TypeScript.CharacterCodes = {})); + var CharacterCodes = TypeScript.CharacterCodes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + + + (function (ScriptSnapshot) { + var StringScriptSnapshot = (function () { + function StringScriptSnapshot(text) { + this.text = text; + this._lineStartPositions = null; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + + StringScriptSnapshot.prototype.getLineStartPositions = function () { + if (!this._lineStartPositions) { + this._lineStartPositions = TypeScript.TextUtilities.parseLineStarts(this.text); + } + + return this._lineStartPositions; + }; + + StringScriptSnapshot.prototype.getTextChangeRangeSinceVersion = function (scriptVersion) { + throw TypeScript.Errors.notYetImplemented(); + }; + return StringScriptSnapshot; + })(); + + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(TypeScript.ScriptSnapshot || (TypeScript.ScriptSnapshot = {})); + var ScriptSnapshot = TypeScript.ScriptSnapshot; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (LineMap1) { + function fromSimpleText(text) { + return new TypeScript.LineMap(function () { + return TypeScript.TextUtilities.parseLineStarts({ charCodeAt: function (index) { + return text.charCodeAt(index); + }, length: text.length() }); + }, text.length()); + } + LineMap1.fromSimpleText = fromSimpleText; + + function fromScriptSnapshot(scriptSnapshot) { + return new TypeScript.LineMap(function () { + return scriptSnapshot.getLineStartPositions(); + }, scriptSnapshot.getLength()); + } + LineMap1.fromScriptSnapshot = fromScriptSnapshot; + + function fromString(text) { + return new TypeScript.LineMap(function () { + return TypeScript.TextUtilities.parseLineStarts(text); + }, text.length); + } + LineMap1.fromString = fromString; + })(TypeScript.LineMap1 || (TypeScript.LineMap1 = {})); + var LineMap1 = TypeScript.LineMap1; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TextFactory) { + function getStartAndLengthOfLineBreakEndingAt(text, index, info) { + var c = text.charCodeAt(index); + if (c === 10 /* lineFeed */) { + if (index > 0 && text.charCodeAt(index - 1) === 13 /* carriageReturn */) { + info.startPosition = index - 1; + info.length = 2; + } else { + info.startPosition = index; + info.length = 1; + } + } else if (TypeScript.TextUtilities.isAnyLineBreakCharacter(c)) { + info.startPosition = index; + info.length = 1; + } else { + info.startPosition = index + 1; + info.length = 0; + } + } + + var LinebreakInfo = (function () { + function LinebreakInfo(startPosition, length) { + this.startPosition = startPosition; + this.length = length; + } + return LinebreakInfo; + })(); + + var TextLine = (function () { + function TextLine(text, body, lineBreakLength, lineNumber) { + this._text = null; + this._textSpan = null; + if (text === null) { + throw TypeScript.Errors.argumentNull('text'); + } + TypeScript.Debug.assert(lineBreakLength >= 0); + TypeScript.Debug.assert(lineNumber >= 0); + this._text = text; + this._textSpan = body; + this._lineBreakLength = lineBreakLength; + this._lineNumber = lineNumber; + } + TextLine.prototype.start = function () { + return this._textSpan.start(); + }; + + TextLine.prototype.end = function () { + return this._textSpan.end(); + }; + + TextLine.prototype.endIncludingLineBreak = function () { + return this.end() + this._lineBreakLength; + }; + + TextLine.prototype.extent = function () { + return this._textSpan; + }; + + TextLine.prototype.extentIncludingLineBreak = function () { + return TypeScript.TextSpan.fromBounds(this.start(), this.endIncludingLineBreak()); + }; + + TextLine.prototype.toString = function () { + return this._text.toString(this._textSpan); + }; + + TextLine.prototype.lineNumber = function () { + return this._lineNumber; + }; + return TextLine; + })(); + + var TextBase = (function () { + function TextBase() { + this.linebreakInfo = new LinebreakInfo(0, 0); + this.lastLineFoundForPosition = null; + } + TextBase.prototype.length = function () { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.charCodeAt = function (position) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.checkSubSpan = function (span) { + if (span.start() < 0 || span.start() > this.length() || span.end() > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("span"); + } + }; + + TextBase.prototype.toString = function (span) { + if (typeof span === "undefined") { span = null; } + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SubText(this, span); + }; + + TextBase.prototype.substr = function (start, length, intern) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.lineCount = function () { + return this._lineStarts().length; + }; + + TextBase.prototype.lines = function () { + var lines = []; + + var length = this.lineCount(); + for (var i = 0; i < length; ++i) { + lines[i] = this.getLineFromLineNumber(i); + } + + return lines; + }; + + TextBase.prototype.lineMap = function () { + var _this = this; + return new TypeScript.LineMap(function () { + return _this._lineStarts(); + }, this.length()); + }; + + TextBase.prototype._lineStarts = function () { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.getLineFromLineNumber = function (lineNumber) { + var lineStarts = this._lineStarts(); + + if (lineNumber < 0 || lineNumber >= lineStarts.length) { + throw TypeScript.Errors.argumentOutOfRange("lineNumber"); + } + + var first = lineStarts[lineNumber]; + if (lineNumber === lineStarts.length - 1) { + return new TextLine(this, new TypeScript.TextSpan(first, this.length() - first), 0, lineNumber); + } else { + getStartAndLengthOfLineBreakEndingAt(this, lineStarts[lineNumber + 1] - 1, this.linebreakInfo); + return new TextLine(this, new TypeScript.TextSpan(first, this.linebreakInfo.startPosition - first), this.linebreakInfo.length, lineNumber); + } + }; + + TextBase.prototype.getLineFromPosition = function (position) { + var lastFound = this.lastLineFoundForPosition; + if (lastFound !== null && lastFound.start() <= position && lastFound.endIncludingLineBreak() > position) { + return lastFound; + } + + var lineNumber = this.getLineNumberFromPosition(position); + + var result = this.getLineFromLineNumber(lineNumber); + this.lastLineFoundForPosition = result; + return result; + }; + + TextBase.prototype.getLineNumberFromPosition = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + if (position === this.length()) { + return this.lineCount() - 1; + } + + var lineNumber = TypeScript.ArrayUtilities.binarySearch(this._lineStarts(), position); + if (lineNumber < 0) { + lineNumber = (~lineNumber) - 1; + } + + return lineNumber; + }; + + TextBase.prototype.getLinePosition = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + + return new TypeScript.LineAndCharacter(lineNumber, position - this._lineStarts()[lineNumber]); + }; + return TextBase; + })(); + + var SubText = (function (_super) { + __extends(SubText, _super); + function SubText(text, span) { + _super.call(this); + this._lazyLineStarts = null; + + if (text === null) { + throw TypeScript.Errors.argumentNull("text"); + } + + if (span.start() < 0 || span.start() >= text.length() || span.end() < 0 || span.end() > text.length()) { + throw TypeScript.Errors.argument("span"); + } + + this.text = text; + this.span = span; + } + SubText.prototype.length = function () { + return this.span.length(); + }; + + SubText.prototype.charCodeAt = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + return this.text.charCodeAt(this.span.start() + position); + }; + + SubText.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SubText(this.text, this.getCompositeSpan(span.start(), span.length())); + }; + + SubText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var span = this.getCompositeSpan(sourceIndex, count); + this.text.copyTo(span.start(), destination, destinationIndex, span.length()); + }; + + SubText.prototype.substr = function (start, length, intern) { + var startInOriginalText = this.span.start() + start; + return this.text.substr(startInOriginalText, length, intern); + }; + + SubText.prototype.getCompositeSpan = function (start, length) { + var compositeStart = TypeScript.MathPrototype.min(this.text.length(), this.span.start() + start); + var compositeEnd = TypeScript.MathPrototype.min(this.text.length(), compositeStart + length); + return new TypeScript.TextSpan(compositeStart, compositeEnd - compositeStart); + }; + + SubText.prototype._lineStarts = function () { + var _this = this; + if (!this._lazyLineStarts) { + this._lazyLineStarts = TypeScript.TextUtilities.parseLineStarts({ charCodeAt: function (index) { + return _this.charCodeAt(index); + }, length: this.length() }); + } + + return this._lazyLineStarts; + }; + return SubText; + })(TextBase); + + var StringText = (function (_super) { + __extends(StringText, _super); + function StringText(data) { + _super.call(this); + this.source = null; + this._lazyLineStarts = null; + + if (data === null) { + throw TypeScript.Errors.argumentNull("data"); + } + + this.source = data; + } + StringText.prototype.length = function () { + return this.source.length; + }; + + StringText.prototype.charCodeAt = function (position) { + if (position < 0 || position >= this.source.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + return this.source.charCodeAt(position); + }; + + StringText.prototype.substr = function (start, length, intern) { + return this.source.substr(start, length); + }; + + StringText.prototype.toString = function (span) { + if (typeof span === "undefined") { span = null; } + if (span === null) { + span = new TypeScript.TextSpan(0, this.length()); + } + + this.checkSubSpan(span); + + if (span.start() === 0 && span.length() === this.length()) { + return this.source; + } + + return this.source.substr(span.start(), span.length()); + }; + + StringText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + TypeScript.StringUtilities.copyTo(this.source, sourceIndex, destination, destinationIndex, count); + }; + + StringText.prototype._lineStarts = function () { + if (this._lazyLineStarts === null) { + this._lazyLineStarts = TypeScript.TextUtilities.parseLineStarts(this.source); + } + + return this._lazyLineStarts; + }; + return StringText; + })(TextBase); + + function createText(value) { + return new StringText(value); + } + TextFactory.createText = createText; + })(TypeScript.TextFactory || (TypeScript.TextFactory = {})); + var TextFactory = TypeScript.TextFactory; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (SimpleText) { + var SimpleSubText = (function () { + function SimpleSubText(text, span) { + this.text = null; + this.span = null; + if (text === null) { + throw TypeScript.Errors.argumentNull("text"); + } + + if (span.start() < 0 || span.start() >= text.length() || span.end() < 0 || span.end() > text.length()) { + throw TypeScript.Errors.argument("span"); + } + + this.text = text; + this.span = span; + } + SimpleSubText.prototype.checkSubSpan = function (span) { + if (span.start() < 0 || span.start() > this.length() || span.end() > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("span"); + } + }; + + SimpleSubText.prototype.checkSubPosition = function (position) { + if (position < 0 || position >= this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + }; + + SimpleSubText.prototype.length = function () { + return this.span.length(); + }; + + SimpleSubText.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SimpleSubText(this.text, this.getCompositeSpan(span.start(), span.length())); + }; + + SimpleSubText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var span = this.getCompositeSpan(sourceIndex, count); + this.text.copyTo(span.start(), destination, destinationIndex, span.length()); + }; + + SimpleSubText.prototype.substr = function (start, length, intern) { + var span = this.getCompositeSpan(start, length); + return this.text.substr(span.start(), span.length(), intern); + }; + + SimpleSubText.prototype.getCompositeSpan = function (start, length) { + var compositeStart = TypeScript.MathPrototype.min(this.text.length(), this.span.start() + start); + var compositeEnd = TypeScript.MathPrototype.min(this.text.length(), compositeStart + length); + return new TypeScript.TextSpan(compositeStart, compositeEnd - compositeStart); + }; + + SimpleSubText.prototype.charCodeAt = function (index) { + this.checkSubPosition(index); + return this.text.charCodeAt(this.span.start() + index); + }; + + SimpleSubText.prototype.lineMap = function () { + return TypeScript.LineMap1.fromSimpleText(this); + }; + return SimpleSubText; + })(); + + var SimpleStringText = (function () { + function SimpleStringText(value) { + this.value = value; + this._lineMap = null; + } + SimpleStringText.prototype.length = function () { + return this.value.length; + }; + + SimpleStringText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + TypeScript.StringUtilities.copyTo(this.value, sourceIndex, destination, destinationIndex, count); + }; + + SimpleStringText.prototype.substr = function (start, length, intern) { + if (intern) { + var array = length <= SimpleStringText.charArray.length ? SimpleStringText.charArray : TypeScript.ArrayUtilities.createArray(length, 0); + this.copyTo(start, array, 0, length); + return TypeScript.Collections.DefaultStringTable.addCharArray(array, 0, length); + } + + return this.value.substr(start, length); + }; + + SimpleStringText.prototype.subText = function (span) { + return new SimpleSubText(this, span); + }; + + SimpleStringText.prototype.charCodeAt = function (index) { + return this.value.charCodeAt(index); + }; + + SimpleStringText.prototype.lineMap = function () { + if (!this._lineMap) { + this._lineMap = TypeScript.LineMap1.fromString(this.value); + } + + return this._lineMap; + }; + SimpleStringText.charArray = TypeScript.ArrayUtilities.createArray(1024, 0); + return SimpleStringText; + })(); + + var SimpleScriptSnapshotText = (function () { + function SimpleScriptSnapshotText(scriptSnapshot) { + this.scriptSnapshot = scriptSnapshot; + } + SimpleScriptSnapshotText.prototype.charCodeAt = function (index) { + return this.scriptSnapshot.getText(index, index + 1).charCodeAt(0); + }; + + SimpleScriptSnapshotText.prototype.length = function () { + return this.scriptSnapshot.getLength(); + }; + + SimpleScriptSnapshotText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var text = this.scriptSnapshot.getText(sourceIndex, sourceIndex + count); + TypeScript.StringUtilities.copyTo(text, 0, destination, destinationIndex, count); + }; + + SimpleScriptSnapshotText.prototype.substr = function (start, length, intern) { + return this.scriptSnapshot.getText(start, start + length); + }; + + SimpleScriptSnapshotText.prototype.subText = function (span) { + return new SimpleSubText(this, span); + }; + + SimpleScriptSnapshotText.prototype.lineMap = function () { + var _this = this; + return new TypeScript.LineMap(function () { + return _this.scriptSnapshot.getLineStartPositions(); + }, this.length()); + }; + return SimpleScriptSnapshotText; + })(); + + function fromString(value) { + return new SimpleStringText(value); + } + SimpleText.fromString = fromString; + + function fromScriptSnapshot(scriptSnapshot) { + return new SimpleScriptSnapshotText(scriptSnapshot); + } + SimpleText.fromScriptSnapshot = fromScriptSnapshot; + })(TypeScript.SimpleText || (TypeScript.SimpleText = {})); + var SimpleText = TypeScript.SimpleText; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TextUtilities) { + function parseLineStarts(text) { + var length = text.length; + + if (0 === length) { + var result = new Array(); + result.push(0); + return result; + } + + var position = 0; + var index = 0; + var arrayBuilder = new Array(); + var lineNumber = 0; + + while (index < length) { + var c = text.charCodeAt(index); + var lineBreakLength; + + if (c > 13 /* carriageReturn */ && c <= 127) { + index++; + continue; + } else if (c === 13 /* carriageReturn */ && index + 1 < length && text.charCodeAt(index + 1) === 10 /* lineFeed */) { + lineBreakLength = 2; + } else if (c === 10 /* lineFeed */) { + lineBreakLength = 1; + } else { + lineBreakLength = TextUtilities.getLengthOfLineBreak(text, index); + } + + if (0 === lineBreakLength) { + index++; + } else { + arrayBuilder.push(position); + index += lineBreakLength; + position = index; + lineNumber++; + } + } + + arrayBuilder.push(position); + + return arrayBuilder; + } + TextUtilities.parseLineStarts = parseLineStarts; + + function getLengthOfLineBreakSlow(text, index, c) { + if (c === 13 /* carriageReturn */) { + var next = index + 1; + return (next < text.length) && 10 /* lineFeed */ === text.charCodeAt(next) ? 2 : 1; + } else if (isAnyLineBreakCharacter(c)) { + return 1; + } else { + return 0; + } + } + TextUtilities.getLengthOfLineBreakSlow = getLengthOfLineBreakSlow; + + function getLengthOfLineBreak(text, index) { + var c = text.charCodeAt(index); + + if (c > 13 /* carriageReturn */ && c <= 127) { + return 0; + } + + return getLengthOfLineBreakSlow(text, index, c); + } + TextUtilities.getLengthOfLineBreak = getLengthOfLineBreak; + + function isAnyLineBreakCharacter(c) { + return c === 10 /* lineFeed */ || c === 13 /* carriageReturn */ || c === 133 /* nextLine */ || c === 8232 /* lineSeparator */ || c === 8233 /* paragraphSeparator */; + } + TextUtilities.isAnyLineBreakCharacter = isAnyLineBreakCharacter; + })(TypeScript.TextUtilities || (TypeScript.TextUtilities = {})); + var TextUtilities = TypeScript.TextUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextSpan = (function () { + function TextSpan(start, length) { + if (start < 0) { + TypeScript.Errors.argument("start"); + } + + if (length < 0) { + TypeScript.Errors.argument("length"); + } + + this._start = start; + this._length = length; + } + TextSpan.prototype.start = function () { + return this._start; + }; + + TextSpan.prototype.length = function () { + return this._length; + }; + + TextSpan.prototype.end = function () { + return this._start + this._length; + }; + + TextSpan.prototype.isEmpty = function () { + return this._length === 0; + }; + + TextSpan.prototype.containsPosition = function (position) { + return position >= this._start && position < this.end(); + }; + + TextSpan.prototype.containsTextSpan = function (span) { + return span._start >= this._start && span.end() <= this.end(); + }; + + TextSpan.prototype.overlapsWith = function (span) { + var overlapStart = TypeScript.MathPrototype.max(this._start, span._start); + var overlapEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + return overlapStart < overlapEnd; + }; + + TextSpan.prototype.overlap = function (span) { + var overlapStart = TypeScript.MathPrototype.max(this._start, span._start); + var overlapEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + if (overlapStart < overlapEnd) { + return TextSpan.fromBounds(overlapStart, overlapEnd); + } + + return null; + }; + + TextSpan.prototype.intersectsWithTextSpan = function (span) { + return span._start <= this.end() && span.end() >= this._start; + }; + + TextSpan.prototype.intersectsWith = function (start, length) { + var end = start + length; + return start <= this.end() && end >= this._start; + }; + + TextSpan.prototype.intersectsWithPosition = function (position) { + return position <= this.end() && position >= this._start; + }; + + TextSpan.prototype.intersection = function (span) { + var intersectStart = TypeScript.MathPrototype.max(this._start, span._start); + var intersectEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + if (intersectStart <= intersectEnd) { + return TextSpan.fromBounds(intersectStart, intersectEnd); + } + + return null; + }; + + TextSpan.fromBounds = function (start, end) { + TypeScript.Debug.assert(start >= 0); + TypeScript.Debug.assert(end - start >= 0); + return new TextSpan(start, end - start); + }; + return TextSpan; + })(); + TypeScript.TextSpan = TextSpan; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextChangeRange = (function () { + function TextChangeRange(span, newLength) { + if (newLength < 0) { + throw TypeScript.Errors.argumentOutOfRange("newLength"); + } + + this._span = span; + this._newLength = newLength; + } + TextChangeRange.prototype.span = function () { + return this._span; + }; + + TextChangeRange.prototype.newLength = function () { + return this._newLength; + }; + + TextChangeRange.prototype.newSpan = function () { + return new TypeScript.TextSpan(this.span().start(), this.newLength()); + }; + + TextChangeRange.prototype.isUnchanged = function () { + return this.span().isEmpty() && this.newLength() === 0; + }; + + TextChangeRange.collapseChangesFromSingleVersion = function (changes) { + var diff = 0; + var start = 1073741823 /* Max31BitInteger */; + var end = 0; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + diff += change.newLength() - change.span().length(); + + if (change.span().start() < start) { + start = change.span().start(); + } + + if (change.span().end() > end) { + end = change.span().end(); + } + } + + if (start > end) { + return null; + } + + var combined = TypeScript.TextSpan.fromBounds(start, end); + var newLen = combined.length() + diff; + + return new TextChangeRange(combined, newLen); + }; + + TextChangeRange.collapseChangesAcrossMultipleVersions = function (changes) { + if (changes.length === 0) { + return TextChangeRange.unchanged; + } + + if (changes.length === 1) { + return changes[0]; + } + + var change0 = changes[0]; + + var oldStartN = change0.span().start(); + var oldEndN = change0.span().end(); + var newEndN = oldStartN + change0.newLength(); + + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + + var oldStart2 = nextChange.span().start(); + var oldEnd2 = nextChange.span().end(); + var newEnd2 = oldStart2 + nextChange.newLength(); + + oldStartN = TypeScript.MathPrototype.min(oldStart1, oldStart2); + oldEndN = TypeScript.MathPrototype.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = TypeScript.MathPrototype.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + + return new TextChangeRange(TypeScript.TextSpan.fromBounds(oldStartN, oldEndN), newEndN - oldStartN); + }; + TextChangeRange.unchanged = new TextChangeRange(new TypeScript.TextSpan(0, 0), 0); + return TextChangeRange; + })(); + TypeScript.TextChangeRange = TextChangeRange; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CharacterInfo = (function () { + function CharacterInfo() { + } + CharacterInfo.isDecimalDigit = function (c) { + return c >= 48 /* _0 */ && c <= 57 /* _9 */; + }; + CharacterInfo.isOctalDigit = function (c) { + return c >= 48 /* _0 */ && c <= 55 /* _7 */; + }; + + CharacterInfo.isHexDigit = function (c) { + return CharacterInfo.isDecimalDigit(c) || (c >= 65 /* A */ && c <= 70 /* F */) || (c >= 97 /* a */ && c <= 102 /* f */); + }; + + CharacterInfo.hexValue = function (c) { + return CharacterInfo.isDecimalDigit(c) ? (c - 48 /* _0 */) : (c >= 65 /* A */ && c <= 70 /* F */) ? c - 65 /* A */ + 10 : c - 97 /* a */ + 10; + }; + + CharacterInfo.isWhitespace = function (ch) { + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + return true; + } + + return false; + }; + + CharacterInfo.isLineTerminator = function (ch) { + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + return true; + } + + return false; + }; + return CharacterInfo; + })(); + TypeScript.CharacterInfo = CharacterInfo; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxConstants) { + SyntaxConstants[SyntaxConstants["TriviaNewLineMask"] = 0x00000001] = "TriviaNewLineMask"; + SyntaxConstants[SyntaxConstants["TriviaCommentMask"] = 0x00000002] = "TriviaCommentMask"; + SyntaxConstants[SyntaxConstants["TriviaFullWidthShift"] = 2] = "TriviaFullWidthShift"; + + SyntaxConstants[SyntaxConstants["NodeDataComputed"] = 0x00000001] = "NodeDataComputed"; + SyntaxConstants[SyntaxConstants["NodeIncrementallyUnusableMask"] = 0x00000002] = "NodeIncrementallyUnusableMask"; + SyntaxConstants[SyntaxConstants["NodeParsedInStrictModeMask"] = 0x00000004] = "NodeParsedInStrictModeMask"; + SyntaxConstants[SyntaxConstants["NodeFullWidthShift"] = 3] = "NodeFullWidthShift"; + + SyntaxConstants[SyntaxConstants["IsVariableWidthKeyword"] = 1 << 31] = "IsVariableWidthKeyword"; + })(TypeScript.SyntaxConstants || (TypeScript.SyntaxConstants = {})); + var SyntaxConstants = TypeScript.SyntaxConstants; +})(TypeScript || (TypeScript = {})); +var FormattingOptions = (function () { + function FormattingOptions(useTabs, spacesPerTab, indentSpaces, newLineCharacter) { + this.useTabs = useTabs; + this.spacesPerTab = spacesPerTab; + this.indentSpaces = indentSpaces; + this.newLineCharacter = newLineCharacter; + } + FormattingOptions.defaultOptions = new FormattingOptions(false, 4, 4, "\r\n"); + return FormattingOptions; +})(); +var TypeScript; +(function (TypeScript) { + (function (Indentation) { + function columnForEndOfToken(token, syntaxInformationMap, options) { + return columnForStartOfToken(token, syntaxInformationMap, options) + token.width(); + } + Indentation.columnForEndOfToken = columnForEndOfToken; + + function columnForStartOfToken(token, syntaxInformationMap, options) { + var firstTokenInLine = syntaxInformationMap.firstTokenInLineContainingToken(token); + var leadingTextInReverse = []; + + var current = token; + while (current !== firstTokenInLine) { + current = syntaxInformationMap.previousToken(current); + + if (current === firstTokenInLine) { + leadingTextInReverse.push(current.trailingTrivia().fullText()); + leadingTextInReverse.push(current.text()); + } else { + leadingTextInReverse.push(current.fullText()); + } + } + + collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse); + + return columnForLeadingTextInReverse(leadingTextInReverse, options); + } + Indentation.columnForStartOfToken = columnForStartOfToken; + + function columnForStartOfFirstTokenInLineContainingToken(token, syntaxInformationMap, options) { + var firstTokenInLine = syntaxInformationMap.firstTokenInLineContainingToken(token); + var leadingTextInReverse = []; + + collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse); + + return columnForLeadingTextInReverse(leadingTextInReverse, options); + } + Indentation.columnForStartOfFirstTokenInLineContainingToken = columnForStartOfFirstTokenInLineContainingToken; + + function collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse) { + var leadingTrivia = firstTokenInLine.leadingTrivia(); + + for (var i = leadingTrivia.count() - 1; i >= 0; i--) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.kind() === 5 /* NewLineTrivia */) { + break; + } + + if (trivia.kind() === 6 /* MultiLineCommentTrivia */) { + var lineSegments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + leadingTextInReverse.push(TypeScript.ArrayUtilities.last(lineSegments)); + + if (lineSegments.length > 0) { + break; + } + } + + leadingTextInReverse.push(trivia.fullText()); + } + } + + function columnForLeadingTextInReverse(leadingTextInReverse, options) { + var column = 0; + + for (var i = leadingTextInReverse.length - 1; i >= 0; i--) { + var text = leadingTextInReverse[i]; + column = columnForPositionInStringWorker(text, text.length, column, options); + } + + return column; + } + + function columnForPositionInString(input, position, options) { + return columnForPositionInStringWorker(input, position, 0, options); + } + Indentation.columnForPositionInString = columnForPositionInString; + + function columnForPositionInStringWorker(input, position, startColumn, options) { + var column = startColumn; + var spacesPerTab = options.spacesPerTab; + + for (var j = 0; j < position; j++) { + var ch = input.charCodeAt(j); + + if (ch === 9 /* tab */) { + column += spacesPerTab - column % spacesPerTab; + } else { + column++; + } + } + + return column; + } + + function indentationString(column, options) { + var numberOfTabs = 0; + var numberOfSpaces = TypeScript.MathPrototype.max(0, column); + + if (options.useTabs) { + numberOfTabs = Math.floor(column / options.spacesPerTab); + numberOfSpaces -= numberOfTabs * options.spacesPerTab; + } + + return TypeScript.StringUtilities.repeat('\t', numberOfTabs) + TypeScript.StringUtilities.repeat(' ', numberOfSpaces); + } + Indentation.indentationString = indentationString; + + function indentationTrivia(column, options) { + return TypeScript.Syntax.whitespace(this.indentationString(column, options)); + } + Indentation.indentationTrivia = indentationTrivia; + + function firstNonWhitespacePosition(value) { + for (var i = 0; i < value.length; i++) { + var ch = value.charCodeAt(i); + if (!TypeScript.CharacterInfo.isWhitespace(ch)) { + return i; + } + } + + return value.length; + } + Indentation.firstNonWhitespacePosition = firstNonWhitespacePosition; + })(TypeScript.Indentation || (TypeScript.Indentation = {})); + var Indentation = TypeScript.Indentation; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (LanguageVersion) { + LanguageVersion[LanguageVersion["EcmaScript3"] = 0] = "EcmaScript3"; + LanguageVersion[LanguageVersion["EcmaScript5"] = 1] = "EcmaScript5"; + })(TypeScript.LanguageVersion || (TypeScript.LanguageVersion = {})); + var LanguageVersion = TypeScript.LanguageVersion; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ParseOptions = (function () { + function ParseOptions(languageVersion, allowAutomaticSemicolonInsertion) { + this._languageVersion = languageVersion; + this._allowAutomaticSemicolonInsertion = allowAutomaticSemicolonInsertion; + } + ParseOptions.prototype.toJSON = function (key) { + return { allowAutomaticSemicolonInsertion: this._allowAutomaticSemicolonInsertion }; + }; + + ParseOptions.prototype.languageVersion = function () { + return this._languageVersion; + }; + + ParseOptions.prototype.allowAutomaticSemicolonInsertion = function () { + return this._allowAutomaticSemicolonInsertion; + }; + return ParseOptions; + })(); + TypeScript.ParseOptions = ParseOptions; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PositionedElement = (function () { + function PositionedElement(parent, element, fullStart) { + this._parent = parent; + this._element = element; + this._fullStart = fullStart; + } + PositionedElement.create = function (parent, element, fullStart) { + if (element === null) { + return null; + } + + if (element.isNode()) { + return new PositionedNode(parent, element, fullStart); + } else if (element.isToken()) { + return new PositionedToken(parent, element, fullStart); + } else if (element.isList()) { + return new PositionedList(parent, element, fullStart); + } else if (element.isSeparatedList()) { + return new PositionedSeparatedList(parent, element, fullStart); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + PositionedElement.prototype.parent = function () { + return this._parent; + }; + + PositionedElement.prototype.parentElement = function () { + return this._parent && this._parent._element; + }; + + PositionedElement.prototype.element = function () { + return this._element; + }; + + PositionedElement.prototype.kind = function () { + return this.element().kind(); + }; + + PositionedElement.prototype.childIndex = function (child) { + return TypeScript.Syntax.childIndex(this.element(), child); + }; + + PositionedElement.prototype.childCount = function () { + return this.element().childCount(); + }; + + PositionedElement.prototype.childAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + return PositionedElement.create(this, this.element().childAt(index), this.fullStart() + offset); + }; + + PositionedElement.prototype.childStart = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return this.fullStart() + offset + child.leadingTriviaWidth(); + }; + + PositionedElement.prototype.childEnd = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return this.fullStart() + offset + child.leadingTriviaWidth() + child.width(); + }; + + PositionedElement.prototype.childStartAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + var child = this.element().childAt(index); + return this.fullStart() + offset + child.leadingTriviaWidth(); + }; + + PositionedElement.prototype.childEndAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + var child = this.element().childAt(index); + return this.fullStart() + offset + child.leadingTriviaWidth() + child.width(); + }; + + PositionedElement.prototype.getPositionedChild = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return PositionedElement.create(this, child, this.fullStart() + offset); + }; + + PositionedElement.prototype.fullStart = function () { + return this._fullStart; + }; + + PositionedElement.prototype.fullEnd = function () { + return this.fullStart() + this.element().fullWidth(); + }; + + PositionedElement.prototype.fullWidth = function () { + return this.element().fullWidth(); + }; + + PositionedElement.prototype.start = function () { + return this.fullStart() + this.element().leadingTriviaWidth(); + }; + + PositionedElement.prototype.end = function () { + return this.fullStart() + this.element().leadingTriviaWidth() + this.element().width(); + }; + + PositionedElement.prototype.root = function () { + var current = this; + while (current.parent() !== null) { + current = current.parent(); + } + + return current; + }; + + PositionedElement.prototype.containingNode = function () { + var current = this.parent(); + + while (current !== null && !current.element().isNode()) { + current = current.parent(); + } + + return current; + }; + return PositionedElement; + })(); + TypeScript.PositionedElement = PositionedElement; + + var PositionedNodeOrToken = (function (_super) { + __extends(PositionedNodeOrToken, _super); + function PositionedNodeOrToken(parent, nodeOrToken, fullStart) { + _super.call(this, parent, nodeOrToken, fullStart); + } + PositionedNodeOrToken.prototype.nodeOrToken = function () { + return this.element(); + }; + return PositionedNodeOrToken; + })(PositionedElement); + TypeScript.PositionedNodeOrToken = PositionedNodeOrToken; + + var PositionedNode = (function (_super) { + __extends(PositionedNode, _super); + function PositionedNode(parent, node, fullStart) { + _super.call(this, parent, node, fullStart); + } + PositionedNode.prototype.node = function () { + return this.element(); + }; + return PositionedNode; + })(PositionedNodeOrToken); + TypeScript.PositionedNode = PositionedNode; + + var PositionedToken = (function (_super) { + __extends(PositionedToken, _super); + function PositionedToken(parent, token, fullStart) { + _super.call(this, parent, token, fullStart); + } + PositionedToken.prototype.token = function () { + return this.element(); + }; + + PositionedToken.prototype.previousToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var triviaList = this.token().leadingTrivia(); + if (includeSkippedTokens && triviaList && triviaList.hasSkippedToken()) { + var currentTriviaEndPosition = this.start(); + for (var i = triviaList.count() - 1; i >= 0; i--) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isSkippedToken()) { + return new PositionedSkippedToken(this, trivia.skippedToken(), currentTriviaEndPosition - trivia.fullWidth()); + } + + currentTriviaEndPosition -= trivia.fullWidth(); + } + } + + var start = this.fullStart(); + if (start === 0) { + return null; + } + + return this.root().node().findToken(start - 1, includeSkippedTokens); + }; + + PositionedToken.prototype.nextToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + if (this.token().tokenKind === 10 /* EndOfFileToken */) { + return null; + } + + var triviaList = this.token().trailingTrivia(); + if (includeSkippedTokens && triviaList && triviaList.hasSkippedToken()) { + var fullStart = this.end(); + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isSkippedToken()) { + return new PositionedSkippedToken(this, trivia.skippedToken(), fullStart); + } + + fullStart += trivia.fullWidth(); + } + } + + return this.root().node().findToken(this.fullEnd(), includeSkippedTokens); + }; + return PositionedToken; + })(PositionedNodeOrToken); + TypeScript.PositionedToken = PositionedToken; + + var PositionedList = (function (_super) { + __extends(PositionedList, _super); + function PositionedList(parent, list, fullStart) { + _super.call(this, parent, list, fullStart); + } + PositionedList.prototype.list = function () { + return this.element(); + }; + return PositionedList; + })(PositionedElement); + TypeScript.PositionedList = PositionedList; + + var PositionedSeparatedList = (function (_super) { + __extends(PositionedSeparatedList, _super); + function PositionedSeparatedList(parent, list, fullStart) { + _super.call(this, parent, list, fullStart); + } + PositionedSeparatedList.prototype.list = function () { + return this.element(); + }; + return PositionedSeparatedList; + })(PositionedElement); + TypeScript.PositionedSeparatedList = PositionedSeparatedList; + + var PositionedSkippedToken = (function (_super) { + __extends(PositionedSkippedToken, _super); + function PositionedSkippedToken(parentToken, token, fullStart) { + _super.call(this, parentToken.parent(), token, fullStart); + this._parentToken = parentToken; + } + PositionedSkippedToken.prototype.parentToken = function () { + return this._parentToken; + }; + + PositionedSkippedToken.prototype.previousToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var start = this.fullStart(); + + if (includeSkippedTokens) { + var previousToken; + + if (start >= this.parentToken().end()) { + previousToken = TypeScript.Syntax.findSkippedTokenInTrailingTriviaList(this.parentToken(), start - 1); + + if (previousToken) { + return previousToken; + } + + return this.parentToken(); + } else { + previousToken = TypeScript.Syntax.findSkippedTokenInLeadingTriviaList(this.parentToken(), start - 1); + + if (previousToken) { + return previousToken; + } + } + } + + var start = this.parentToken().fullStart(); + if (start === 0) { + return null; + } + + return this.root().node().findToken(start - 1, includeSkippedTokens); + }; + + PositionedSkippedToken.prototype.nextToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + if (this.token().tokenKind === 10 /* EndOfFileToken */) { + return null; + } + + if (includeSkippedTokens) { + var end = this.end(); + var nextToken; + + if (end <= this.parentToken().start()) { + nextToken = TypeScript.Syntax.findSkippedTokenInLeadingTriviaList(this.parentToken(), end); + + if (nextToken) { + return nextToken; + } + + return this.parentToken(); + } else { + nextToken = TypeScript.Syntax.findSkippedTokenInTrailingTriviaList(this.parentToken(), end); + + if (nextToken) { + return nextToken; + } + } + } + + return this.root().node().findToken(this.parentToken().fullEnd(), includeSkippedTokens); + }; + return PositionedSkippedToken; + })(PositionedToken); + TypeScript.PositionedSkippedToken = PositionedSkippedToken; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["None"] = 0] = "None"; + SyntaxKind[SyntaxKind["List"] = 1] = "List"; + SyntaxKind[SyntaxKind["SeparatedList"] = 2] = "SeparatedList"; + SyntaxKind[SyntaxKind["TriviaList"] = 3] = "TriviaList"; + + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 4] = "WhitespaceTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 5] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 6] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 7] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["SkippedTokenTrivia"] = 8] = "SkippedTokenTrivia"; + + SyntaxKind[SyntaxKind["ErrorToken"] = 9] = "ErrorToken"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 10] = "EndOfFileToken"; + + SyntaxKind[SyntaxKind["IdentifierName"] = 11] = "IdentifierName"; + + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 13] = "NumericLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 14] = "StringLiteral"; + + SyntaxKind[SyntaxKind["BreakKeyword"] = 15] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 16] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 17] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 18] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 19] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 20] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 21] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 22] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 23] = "ElseKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 24] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 25] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 26] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 27] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 28] = "IfKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 29] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 30] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 31] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 32] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 33] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 34] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 35] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 36] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 37] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 38] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 39] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 40] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 41] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 42] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 43] = "WithKeyword"; + + SyntaxKind[SyntaxKind["ClassKeyword"] = 44] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 45] = "ConstKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 46] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 47] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 48] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 49] = "ImportKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 50] = "SuperKeyword"; + + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 51] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 52] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 53] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 54] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 55] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 56] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 57] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 58] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 59] = "YieldKeyword"; + + SyntaxKind[SyntaxKind["AnyKeyword"] = 60] = "AnyKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 61] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 62] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 63] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 64] = "GetKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 65] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 66] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 67] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 68] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 69] = "StringKeyword"; + + SyntaxKind[SyntaxKind["OpenBraceToken"] = 70] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 71] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 72] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 73] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 74] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 75] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 76] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 77] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 78] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 79] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 80] = "LessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 81] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 82] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 83] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 84] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 85] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 86] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 87] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 88] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 89] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 90] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 91] = "AsteriskToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 92] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 93] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 94] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 95] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 96] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 97] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 98] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 99] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 100] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 101] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 102] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 103] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 104] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 105] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 106] = "ColonToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 107] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 108] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 109] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 110] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 111] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 112] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 113] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 114] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 115] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 116] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 117] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 118] = "SlashToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 119] = "SlashEqualsToken"; + + SyntaxKind[SyntaxKind["SourceUnit"] = 120] = "SourceUnit"; + + SyntaxKind[SyntaxKind["QualifiedName"] = 121] = "QualifiedName"; + + SyntaxKind[SyntaxKind["ObjectType"] = 122] = "ObjectType"; + SyntaxKind[SyntaxKind["FunctionType"] = 123] = "FunctionType"; + SyntaxKind[SyntaxKind["ArrayType"] = 124] = "ArrayType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 125] = "ConstructorType"; + SyntaxKind[SyntaxKind["GenericType"] = 126] = "GenericType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 127] = "TypeQuery"; + + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 128] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 129] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 130] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 131] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 132] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 133] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 134] = "ExportAssignment"; + + SyntaxKind[SyntaxKind["MemberFunctionDeclaration"] = 135] = "MemberFunctionDeclaration"; + SyntaxKind[SyntaxKind["MemberVariableDeclaration"] = 136] = "MemberVariableDeclaration"; + SyntaxKind[SyntaxKind["ConstructorDeclaration"] = 137] = "ConstructorDeclaration"; + SyntaxKind[SyntaxKind["IndexMemberDeclaration"] = 138] = "IndexMemberDeclaration"; + + SyntaxKind[SyntaxKind["GetAccessor"] = 139] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 140] = "SetAccessor"; + + SyntaxKind[SyntaxKind["PropertySignature"] = 141] = "PropertySignature"; + SyntaxKind[SyntaxKind["CallSignature"] = 142] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 143] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 144] = "IndexSignature"; + SyntaxKind[SyntaxKind["MethodSignature"] = 145] = "MethodSignature"; + + SyntaxKind[SyntaxKind["Block"] = 146] = "Block"; + SyntaxKind[SyntaxKind["IfStatement"] = 147] = "IfStatement"; + SyntaxKind[SyntaxKind["VariableStatement"] = 148] = "VariableStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 149] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 150] = "ReturnStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 151] = "SwitchStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 152] = "BreakStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 153] = "ContinueStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 154] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 155] = "ForInStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 156] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 157] = "ThrowStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 158] = "WhileStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 159] = "TryStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 160] = "LabeledStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 161] = "DoStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 162] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 163] = "WithStatement"; + + SyntaxKind[SyntaxKind["PlusExpression"] = 164] = "PlusExpression"; + SyntaxKind[SyntaxKind["NegateExpression"] = 165] = "NegateExpression"; + SyntaxKind[SyntaxKind["BitwiseNotExpression"] = 166] = "BitwiseNotExpression"; + SyntaxKind[SyntaxKind["LogicalNotExpression"] = 167] = "LogicalNotExpression"; + SyntaxKind[SyntaxKind["PreIncrementExpression"] = 168] = "PreIncrementExpression"; + SyntaxKind[SyntaxKind["PreDecrementExpression"] = 169] = "PreDecrementExpression"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 170] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 171] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 172] = "VoidExpression"; + SyntaxKind[SyntaxKind["CommaExpression"] = 173] = "CommaExpression"; + SyntaxKind[SyntaxKind["AssignmentExpression"] = 174] = "AssignmentExpression"; + SyntaxKind[SyntaxKind["AddAssignmentExpression"] = 175] = "AddAssignmentExpression"; + SyntaxKind[SyntaxKind["SubtractAssignmentExpression"] = 176] = "SubtractAssignmentExpression"; + SyntaxKind[SyntaxKind["MultiplyAssignmentExpression"] = 177] = "MultiplyAssignmentExpression"; + SyntaxKind[SyntaxKind["DivideAssignmentExpression"] = 178] = "DivideAssignmentExpression"; + SyntaxKind[SyntaxKind["ModuloAssignmentExpression"] = 179] = "ModuloAssignmentExpression"; + SyntaxKind[SyntaxKind["AndAssignmentExpression"] = 180] = "AndAssignmentExpression"; + SyntaxKind[SyntaxKind["ExclusiveOrAssignmentExpression"] = 181] = "ExclusiveOrAssignmentExpression"; + SyntaxKind[SyntaxKind["OrAssignmentExpression"] = 182] = "OrAssignmentExpression"; + SyntaxKind[SyntaxKind["LeftShiftAssignmentExpression"] = 183] = "LeftShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["SignedRightShiftAssignmentExpression"] = 184] = "SignedRightShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["UnsignedRightShiftAssignmentExpression"] = 185] = "UnsignedRightShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 186] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["LogicalOrExpression"] = 187] = "LogicalOrExpression"; + SyntaxKind[SyntaxKind["LogicalAndExpression"] = 188] = "LogicalAndExpression"; + SyntaxKind[SyntaxKind["BitwiseOrExpression"] = 189] = "BitwiseOrExpression"; + SyntaxKind[SyntaxKind["BitwiseExclusiveOrExpression"] = 190] = "BitwiseExclusiveOrExpression"; + SyntaxKind[SyntaxKind["BitwiseAndExpression"] = 191] = "BitwiseAndExpression"; + SyntaxKind[SyntaxKind["EqualsWithTypeConversionExpression"] = 192] = "EqualsWithTypeConversionExpression"; + SyntaxKind[SyntaxKind["NotEqualsWithTypeConversionExpression"] = 193] = "NotEqualsWithTypeConversionExpression"; + SyntaxKind[SyntaxKind["EqualsExpression"] = 194] = "EqualsExpression"; + SyntaxKind[SyntaxKind["NotEqualsExpression"] = 195] = "NotEqualsExpression"; + SyntaxKind[SyntaxKind["LessThanExpression"] = 196] = "LessThanExpression"; + SyntaxKind[SyntaxKind["GreaterThanExpression"] = 197] = "GreaterThanExpression"; + SyntaxKind[SyntaxKind["LessThanOrEqualExpression"] = 198] = "LessThanOrEqualExpression"; + SyntaxKind[SyntaxKind["GreaterThanOrEqualExpression"] = 199] = "GreaterThanOrEqualExpression"; + SyntaxKind[SyntaxKind["InstanceOfExpression"] = 200] = "InstanceOfExpression"; + SyntaxKind[SyntaxKind["InExpression"] = 201] = "InExpression"; + SyntaxKind[SyntaxKind["LeftShiftExpression"] = 202] = "LeftShiftExpression"; + SyntaxKind[SyntaxKind["SignedRightShiftExpression"] = 203] = "SignedRightShiftExpression"; + SyntaxKind[SyntaxKind["UnsignedRightShiftExpression"] = 204] = "UnsignedRightShiftExpression"; + SyntaxKind[SyntaxKind["MultiplyExpression"] = 205] = "MultiplyExpression"; + SyntaxKind[SyntaxKind["DivideExpression"] = 206] = "DivideExpression"; + SyntaxKind[SyntaxKind["ModuloExpression"] = 207] = "ModuloExpression"; + SyntaxKind[SyntaxKind["AddExpression"] = 208] = "AddExpression"; + SyntaxKind[SyntaxKind["SubtractExpression"] = 209] = "SubtractExpression"; + SyntaxKind[SyntaxKind["PostIncrementExpression"] = 210] = "PostIncrementExpression"; + SyntaxKind[SyntaxKind["PostDecrementExpression"] = 211] = "PostDecrementExpression"; + SyntaxKind[SyntaxKind["MemberAccessExpression"] = 212] = "MemberAccessExpression"; + SyntaxKind[SyntaxKind["InvocationExpression"] = 213] = "InvocationExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 214] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 215] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectCreationExpression"] = 216] = "ObjectCreationExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 217] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["ParenthesizedArrowFunctionExpression"] = 218] = "ParenthesizedArrowFunctionExpression"; + SyntaxKind[SyntaxKind["SimpleArrowFunctionExpression"] = 219] = "SimpleArrowFunctionExpression"; + SyntaxKind[SyntaxKind["CastExpression"] = 220] = "CastExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 221] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 222] = "FunctionExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 223] = "OmittedExpression"; + + SyntaxKind[SyntaxKind["VariableDeclaration"] = 224] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarator"] = 225] = "VariableDeclarator"; + + SyntaxKind[SyntaxKind["ArgumentList"] = 226] = "ArgumentList"; + SyntaxKind[SyntaxKind["ParameterList"] = 227] = "ParameterList"; + SyntaxKind[SyntaxKind["TypeArgumentList"] = 228] = "TypeArgumentList"; + SyntaxKind[SyntaxKind["TypeParameterList"] = 229] = "TypeParameterList"; + + SyntaxKind[SyntaxKind["ExtendsHeritageClause"] = 230] = "ExtendsHeritageClause"; + SyntaxKind[SyntaxKind["ImplementsHeritageClause"] = 231] = "ImplementsHeritageClause"; + SyntaxKind[SyntaxKind["EqualsValueClause"] = 232] = "EqualsValueClause"; + SyntaxKind[SyntaxKind["CaseSwitchClause"] = 233] = "CaseSwitchClause"; + SyntaxKind[SyntaxKind["DefaultSwitchClause"] = 234] = "DefaultSwitchClause"; + SyntaxKind[SyntaxKind["ElseClause"] = 235] = "ElseClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 236] = "CatchClause"; + SyntaxKind[SyntaxKind["FinallyClause"] = 237] = "FinallyClause"; + + SyntaxKind[SyntaxKind["TypeParameter"] = 238] = "TypeParameter"; + SyntaxKind[SyntaxKind["Constraint"] = 239] = "Constraint"; + + SyntaxKind[SyntaxKind["SimplePropertyAssignment"] = 240] = "SimplePropertyAssignment"; + + SyntaxKind[SyntaxKind["FunctionPropertyAssignment"] = 241] = "FunctionPropertyAssignment"; + + SyntaxKind[SyntaxKind["Parameter"] = 242] = "Parameter"; + SyntaxKind[SyntaxKind["EnumElement"] = 243] = "EnumElement"; + SyntaxKind[SyntaxKind["TypeAnnotation"] = 244] = "TypeAnnotation"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 245] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ModuleNameModuleReference"] = 246] = "ModuleNameModuleReference"; + SyntaxKind[SyntaxKind["Last"] = SyntaxKind.ModuleNameModuleReference] = "Last"; + + SyntaxKind[SyntaxKind["FirstStandardKeyword"] = SyntaxKind.BreakKeyword] = "FirstStandardKeyword"; + SyntaxKind[SyntaxKind["LastStandardKeyword"] = SyntaxKind.WithKeyword] = "LastStandardKeyword"; + + SyntaxKind[SyntaxKind["FirstFutureReservedKeyword"] = SyntaxKind.ClassKeyword] = "FirstFutureReservedKeyword"; + SyntaxKind[SyntaxKind["LastFutureReservedKeyword"] = SyntaxKind.SuperKeyword] = "LastFutureReservedKeyword"; + + SyntaxKind[SyntaxKind["FirstFutureReservedStrictKeyword"] = SyntaxKind.ImplementsKeyword] = "FirstFutureReservedStrictKeyword"; + SyntaxKind[SyntaxKind["LastFutureReservedStrictKeyword"] = SyntaxKind.YieldKeyword] = "LastFutureReservedStrictKeyword"; + + SyntaxKind[SyntaxKind["FirstTypeScriptKeyword"] = SyntaxKind.AnyKeyword] = "FirstTypeScriptKeyword"; + SyntaxKind[SyntaxKind["LastTypeScriptKeyword"] = SyntaxKind.StringKeyword] = "LastTypeScriptKeyword"; + + SyntaxKind[SyntaxKind["FirstKeyword"] = SyntaxKind.FirstStandardKeyword] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = SyntaxKind.LastTypeScriptKeyword] = "LastKeyword"; + + SyntaxKind[SyntaxKind["FirstToken"] = SyntaxKind.ErrorToken] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = SyntaxKind.SlashEqualsToken] = "LastToken"; + + SyntaxKind[SyntaxKind["FirstPunctuation"] = SyntaxKind.OpenBraceToken] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = SyntaxKind.SlashEqualsToken] = "LastPunctuation"; + + SyntaxKind[SyntaxKind["FirstFixedWidth"] = SyntaxKind.FirstKeyword] = "FirstFixedWidth"; + SyntaxKind[SyntaxKind["LastFixedWidth"] = SyntaxKind.LastPunctuation] = "LastFixedWidth"; + + SyntaxKind[SyntaxKind["FirstTrivia"] = SyntaxKind.WhitespaceTrivia] = "FirstTrivia"; + SyntaxKind[SyntaxKind["LastTrivia"] = SyntaxKind.SkippedTokenTrivia] = "LastTrivia"; + })(TypeScript.SyntaxKind || (TypeScript.SyntaxKind = {})); + var SyntaxKind = TypeScript.SyntaxKind; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxFacts) { + var textToKeywordKind = { + "any": 60 /* AnyKeyword */, + "boolean": 61 /* BooleanKeyword */, + "break": 15 /* BreakKeyword */, + "case": 16 /* CaseKeyword */, + "catch": 17 /* CatchKeyword */, + "class": 44 /* ClassKeyword */, + "continue": 18 /* ContinueKeyword */, + "const": 45 /* ConstKeyword */, + "constructor": 62 /* ConstructorKeyword */, + "debugger": 19 /* DebuggerKeyword */, + "declare": 63 /* DeclareKeyword */, + "default": 20 /* DefaultKeyword */, + "delete": 21 /* DeleteKeyword */, + "do": 22 /* DoKeyword */, + "else": 23 /* ElseKeyword */, + "enum": 46 /* EnumKeyword */, + "export": 47 /* ExportKeyword */, + "extends": 48 /* ExtendsKeyword */, + "false": 24 /* FalseKeyword */, + "finally": 25 /* FinallyKeyword */, + "for": 26 /* ForKeyword */, + "function": 27 /* FunctionKeyword */, + "get": 64 /* GetKeyword */, + "if": 28 /* IfKeyword */, + "implements": 51 /* ImplementsKeyword */, + "import": 49 /* ImportKeyword */, + "in": 29 /* InKeyword */, + "instanceof": 30 /* InstanceOfKeyword */, + "interface": 52 /* InterfaceKeyword */, + "let": 53 /* LetKeyword */, + "module": 65 /* ModuleKeyword */, + "new": 31 /* NewKeyword */, + "null": 32 /* NullKeyword */, + "number": 67 /* NumberKeyword */, + "package": 54 /* PackageKeyword */, + "private": 55 /* PrivateKeyword */, + "protected": 56 /* ProtectedKeyword */, + "public": 57 /* PublicKeyword */, + "require": 66 /* RequireKeyword */, + "return": 33 /* ReturnKeyword */, + "set": 68 /* SetKeyword */, + "static": 58 /* StaticKeyword */, + "string": 69 /* StringKeyword */, + "super": 50 /* SuperKeyword */, + "switch": 34 /* SwitchKeyword */, + "this": 35 /* ThisKeyword */, + "throw": 36 /* ThrowKeyword */, + "true": 37 /* TrueKeyword */, + "try": 38 /* TryKeyword */, + "typeof": 39 /* TypeOfKeyword */, + "var": 40 /* VarKeyword */, + "void": 41 /* VoidKeyword */, + "while": 42 /* WhileKeyword */, + "with": 43 /* WithKeyword */, + "yield": 59 /* YieldKeyword */, + "{": 70 /* OpenBraceToken */, + "}": 71 /* CloseBraceToken */, + "(": 72 /* OpenParenToken */, + ")": 73 /* CloseParenToken */, + "[": 74 /* OpenBracketToken */, + "]": 75 /* CloseBracketToken */, + ".": 76 /* DotToken */, + "...": 77 /* DotDotDotToken */, + ";": 78 /* SemicolonToken */, + ",": 79 /* CommaToken */, + "<": 80 /* LessThanToken */, + ">": 81 /* GreaterThanToken */, + "<=": 82 /* LessThanEqualsToken */, + ">=": 83 /* GreaterThanEqualsToken */, + "==": 84 /* EqualsEqualsToken */, + "=>": 85 /* EqualsGreaterThanToken */, + "!=": 86 /* ExclamationEqualsToken */, + "===": 87 /* EqualsEqualsEqualsToken */, + "!==": 88 /* ExclamationEqualsEqualsToken */, + "+": 89 /* PlusToken */, + "-": 90 /* MinusToken */, + "*": 91 /* AsteriskToken */, + "%": 92 /* PercentToken */, + "++": 93 /* PlusPlusToken */, + "--": 94 /* MinusMinusToken */, + "<<": 95 /* LessThanLessThanToken */, + ">>": 96 /* GreaterThanGreaterThanToken */, + ">>>": 97 /* GreaterThanGreaterThanGreaterThanToken */, + "&": 98 /* AmpersandToken */, + "|": 99 /* BarToken */, + "^": 100 /* CaretToken */, + "!": 101 /* ExclamationToken */, + "~": 102 /* TildeToken */, + "&&": 103 /* AmpersandAmpersandToken */, + "||": 104 /* BarBarToken */, + "?": 105 /* QuestionToken */, + ":": 106 /* ColonToken */, + "=": 107 /* EqualsToken */, + "+=": 108 /* PlusEqualsToken */, + "-=": 109 /* MinusEqualsToken */, + "*=": 110 /* AsteriskEqualsToken */, + "%=": 111 /* PercentEqualsToken */, + "<<=": 112 /* LessThanLessThanEqualsToken */, + ">>=": 113 /* GreaterThanGreaterThanEqualsToken */, + ">>>=": 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */, + "&=": 115 /* AmpersandEqualsToken */, + "|=": 116 /* BarEqualsToken */, + "^=": 117 /* CaretEqualsToken */, + "/": 118 /* SlashToken */, + "/=": 119 /* SlashEqualsToken */ + }; + + var kindToText = new Array(); + + for (var name in textToKeywordKind) { + if (textToKeywordKind.hasOwnProperty(name)) { + kindToText[textToKeywordKind[name]] = name; + } + } + + kindToText[62 /* ConstructorKeyword */] = "constructor"; + + function getTokenKind(text) { + if (textToKeywordKind.hasOwnProperty(text)) { + return textToKeywordKind[text]; + } + + return 0 /* None */; + } + SyntaxFacts.getTokenKind = getTokenKind; + + function getText(kind) { + var result = kindToText[kind]; + return result !== undefined ? result : null; + } + SyntaxFacts.getText = getText; + + function isTokenKind(kind) { + return kind >= 9 /* FirstToken */ && kind <= 119 /* LastToken */; + } + SyntaxFacts.isTokenKind = isTokenKind; + + function isAnyKeyword(kind) { + return kind >= 15 /* FirstKeyword */ && kind <= 69 /* LastKeyword */; + } + SyntaxFacts.isAnyKeyword = isAnyKeyword; + + function isStandardKeyword(kind) { + return kind >= 15 /* FirstStandardKeyword */ && kind <= 43 /* LastStandardKeyword */; + } + SyntaxFacts.isStandardKeyword = isStandardKeyword; + + function isFutureReservedKeyword(kind) { + return kind >= 44 /* FirstFutureReservedKeyword */ && kind <= 50 /* LastFutureReservedKeyword */; + } + SyntaxFacts.isFutureReservedKeyword = isFutureReservedKeyword; + + function isFutureReservedStrictKeyword(kind) { + return kind >= 51 /* FirstFutureReservedStrictKeyword */ && kind <= 59 /* LastFutureReservedStrictKeyword */; + } + SyntaxFacts.isFutureReservedStrictKeyword = isFutureReservedStrictKeyword; + + function isAnyPunctuation(kind) { + return kind >= 70 /* FirstPunctuation */ && kind <= 119 /* LastPunctuation */; + } + SyntaxFacts.isAnyPunctuation = isAnyPunctuation; + + function isPrefixUnaryExpressionOperatorToken(tokenKind) { + return getPrefixUnaryExpressionFromOperatorToken(tokenKind) !== 0 /* None */; + } + SyntaxFacts.isPrefixUnaryExpressionOperatorToken = isPrefixUnaryExpressionOperatorToken; + + function isBinaryExpressionOperatorToken(tokenKind) { + return getBinaryExpressionFromOperatorToken(tokenKind) !== 0 /* None */; + } + SyntaxFacts.isBinaryExpressionOperatorToken = isBinaryExpressionOperatorToken; + + function getPrefixUnaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 89 /* PlusToken */: + return 164 /* PlusExpression */; + case 90 /* MinusToken */: + return 165 /* NegateExpression */; + case 102 /* TildeToken */: + return 166 /* BitwiseNotExpression */; + case 101 /* ExclamationToken */: + return 167 /* LogicalNotExpression */; + case 93 /* PlusPlusToken */: + return 168 /* PreIncrementExpression */; + case 94 /* MinusMinusToken */: + return 169 /* PreDecrementExpression */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getPrefixUnaryExpressionFromOperatorToken = getPrefixUnaryExpressionFromOperatorToken; + + function getPostfixUnaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 93 /* PlusPlusToken */: + return 210 /* PostIncrementExpression */; + case 94 /* MinusMinusToken */: + return 211 /* PostDecrementExpression */; + default: + return 0 /* None */; + } + } + SyntaxFacts.getPostfixUnaryExpressionFromOperatorToken = getPostfixUnaryExpressionFromOperatorToken; + + function getBinaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 91 /* AsteriskToken */: + return 205 /* MultiplyExpression */; + + case 118 /* SlashToken */: + return 206 /* DivideExpression */; + + case 92 /* PercentToken */: + return 207 /* ModuloExpression */; + + case 89 /* PlusToken */: + return 208 /* AddExpression */; + + case 90 /* MinusToken */: + return 209 /* SubtractExpression */; + + case 95 /* LessThanLessThanToken */: + return 202 /* LeftShiftExpression */; + + case 96 /* GreaterThanGreaterThanToken */: + return 203 /* SignedRightShiftExpression */; + + case 97 /* GreaterThanGreaterThanGreaterThanToken */: + return 204 /* UnsignedRightShiftExpression */; + + case 80 /* LessThanToken */: + return 196 /* LessThanExpression */; + + case 81 /* GreaterThanToken */: + return 197 /* GreaterThanExpression */; + + case 82 /* LessThanEqualsToken */: + return 198 /* LessThanOrEqualExpression */; + + case 83 /* GreaterThanEqualsToken */: + return 199 /* GreaterThanOrEqualExpression */; + + case 30 /* InstanceOfKeyword */: + return 200 /* InstanceOfExpression */; + + case 29 /* InKeyword */: + return 201 /* InExpression */; + + case 84 /* EqualsEqualsToken */: + return 192 /* EqualsWithTypeConversionExpression */; + + case 86 /* ExclamationEqualsToken */: + return 193 /* NotEqualsWithTypeConversionExpression */; + + case 87 /* EqualsEqualsEqualsToken */: + return 194 /* EqualsExpression */; + + case 88 /* ExclamationEqualsEqualsToken */: + return 195 /* NotEqualsExpression */; + + case 98 /* AmpersandToken */: + return 191 /* BitwiseAndExpression */; + + case 100 /* CaretToken */: + return 190 /* BitwiseExclusiveOrExpression */; + + case 99 /* BarToken */: + return 189 /* BitwiseOrExpression */; + + case 103 /* AmpersandAmpersandToken */: + return 188 /* LogicalAndExpression */; + + case 104 /* BarBarToken */: + return 187 /* LogicalOrExpression */; + + case 116 /* BarEqualsToken */: + return 182 /* OrAssignmentExpression */; + + case 115 /* AmpersandEqualsToken */: + return 180 /* AndAssignmentExpression */; + + case 117 /* CaretEqualsToken */: + return 181 /* ExclusiveOrAssignmentExpression */; + + case 112 /* LessThanLessThanEqualsToken */: + return 183 /* LeftShiftAssignmentExpression */; + + case 113 /* GreaterThanGreaterThanEqualsToken */: + return 184 /* SignedRightShiftAssignmentExpression */; + + case 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + return 185 /* UnsignedRightShiftAssignmentExpression */; + + case 108 /* PlusEqualsToken */: + return 175 /* AddAssignmentExpression */; + + case 109 /* MinusEqualsToken */: + return 176 /* SubtractAssignmentExpression */; + + case 110 /* AsteriskEqualsToken */: + return 177 /* MultiplyAssignmentExpression */; + + case 119 /* SlashEqualsToken */: + return 178 /* DivideAssignmentExpression */; + + case 111 /* PercentEqualsToken */: + return 179 /* ModuloAssignmentExpression */; + + case 107 /* EqualsToken */: + return 174 /* AssignmentExpression */; + + case 79 /* CommaToken */: + return 173 /* CommaExpression */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getBinaryExpressionFromOperatorToken = getBinaryExpressionFromOperatorToken; + + function getOperatorTokenFromBinaryExpression(tokenKind) { + switch (tokenKind) { + case 205 /* MultiplyExpression */: + return 91 /* AsteriskToken */; + + case 206 /* DivideExpression */: + return 118 /* SlashToken */; + + case 207 /* ModuloExpression */: + return 92 /* PercentToken */; + + case 208 /* AddExpression */: + return 89 /* PlusToken */; + + case 209 /* SubtractExpression */: + return 90 /* MinusToken */; + + case 202 /* LeftShiftExpression */: + return 95 /* LessThanLessThanToken */; + + case 203 /* SignedRightShiftExpression */: + return 96 /* GreaterThanGreaterThanToken */; + + case 204 /* UnsignedRightShiftExpression */: + return 97 /* GreaterThanGreaterThanGreaterThanToken */; + + case 196 /* LessThanExpression */: + return 80 /* LessThanToken */; + + case 197 /* GreaterThanExpression */: + return 81 /* GreaterThanToken */; + + case 198 /* LessThanOrEqualExpression */: + return 82 /* LessThanEqualsToken */; + + case 199 /* GreaterThanOrEqualExpression */: + return 83 /* GreaterThanEqualsToken */; + + case 200 /* InstanceOfExpression */: + return 30 /* InstanceOfKeyword */; + + case 201 /* InExpression */: + return 29 /* InKeyword */; + + case 192 /* EqualsWithTypeConversionExpression */: + return 84 /* EqualsEqualsToken */; + + case 193 /* NotEqualsWithTypeConversionExpression */: + return 86 /* ExclamationEqualsToken */; + + case 194 /* EqualsExpression */: + return 87 /* EqualsEqualsEqualsToken */; + + case 195 /* NotEqualsExpression */: + return 88 /* ExclamationEqualsEqualsToken */; + + case 191 /* BitwiseAndExpression */: + return 98 /* AmpersandToken */; + + case 190 /* BitwiseExclusiveOrExpression */: + return 100 /* CaretToken */; + + case 189 /* BitwiseOrExpression */: + return 99 /* BarToken */; + + case 188 /* LogicalAndExpression */: + return 103 /* AmpersandAmpersandToken */; + + case 187 /* LogicalOrExpression */: + return 104 /* BarBarToken */; + + case 182 /* OrAssignmentExpression */: + return 116 /* BarEqualsToken */; + + case 180 /* AndAssignmentExpression */: + return 115 /* AmpersandEqualsToken */; + + case 181 /* ExclusiveOrAssignmentExpression */: + return 117 /* CaretEqualsToken */; + + case 183 /* LeftShiftAssignmentExpression */: + return 112 /* LessThanLessThanEqualsToken */; + + case 184 /* SignedRightShiftAssignmentExpression */: + return 113 /* GreaterThanGreaterThanEqualsToken */; + + case 185 /* UnsignedRightShiftAssignmentExpression */: + return 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + + case 175 /* AddAssignmentExpression */: + return 108 /* PlusEqualsToken */; + + case 176 /* SubtractAssignmentExpression */: + return 109 /* MinusEqualsToken */; + + case 177 /* MultiplyAssignmentExpression */: + return 110 /* AsteriskEqualsToken */; + + case 178 /* DivideAssignmentExpression */: + return 119 /* SlashEqualsToken */; + + case 179 /* ModuloAssignmentExpression */: + return 111 /* PercentEqualsToken */; + + case 174 /* AssignmentExpression */: + return 107 /* EqualsToken */; + + case 173 /* CommaExpression */: + return 79 /* CommaToken */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getOperatorTokenFromBinaryExpression = getOperatorTokenFromBinaryExpression; + + function isAnyDivideToken(kind) { + switch (kind) { + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + return true; + default: + return false; + } + } + SyntaxFacts.isAnyDivideToken = isAnyDivideToken; + + function isAnyDivideOrRegularExpressionToken(kind) { + switch (kind) { + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + case 12 /* RegularExpressionLiteral */: + return true; + default: + return false; + } + } + SyntaxFacts.isAnyDivideOrRegularExpressionToken = isAnyDivideOrRegularExpressionToken; + })(TypeScript.SyntaxFacts || (TypeScript.SyntaxFacts = {})); + var SyntaxFacts = TypeScript.SyntaxFacts; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var isKeywordStartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + var isIdentifierStartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + var isIdentifierPartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + var isNumericLiteralStart = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + + for (var character = 0; character < 127 /* maxAsciiCharacter */; character++) { + if (character >= 97 /* a */ && character <= 122 /* z */) { + isIdentifierStartCharacter[character] = true; + isIdentifierPartCharacter[character] = true; + } else if ((character >= 65 /* A */ && character <= 90 /* Z */) || character === 95 /* _ */ || character === 36 /* $ */) { + isIdentifierStartCharacter[character] = true; + isIdentifierPartCharacter[character] = true; + } else if (character >= 48 /* _0 */ && character <= 57 /* _9 */) { + isIdentifierPartCharacter[character] = true; + isNumericLiteralStart[character] = true; + } + } + + isNumericLiteralStart[46 /* dot */] = true; + + for (var keywordKind = 15 /* FirstKeyword */; keywordKind <= 69 /* LastKeyword */; keywordKind++) { + var keyword = TypeScript.SyntaxFacts.getText(keywordKind); + isKeywordStartCharacter[keyword.charCodeAt(0)] = true; + } + + var Scanner = (function () { + function Scanner(fileName, text, languageVersion, window) { + if (typeof window === "undefined") { window = TypeScript.ArrayUtilities.createArray(2048, 0); } + this.slidingWindow = new TypeScript.SlidingWindow(this, window, 0, text.length()); + this.fileName = fileName; + this.text = text; + this._languageVersion = languageVersion; + } + Scanner.prototype.languageVersion = function () { + return this._languageVersion; + }; + + Scanner.prototype.fetchMoreItems = function (argument, sourceIndex, window, destinationIndex, spaceAvailable) { + var charactersRemaining = this.text.length() - sourceIndex; + var amountToRead = TypeScript.MathPrototype.min(charactersRemaining, spaceAvailable); + this.text.copyTo(sourceIndex, window, destinationIndex, amountToRead); + return amountToRead; + }; + + Scanner.prototype.currentCharCode = function () { + return this.slidingWindow.currentItem(null); + }; + + Scanner.prototype.absoluteIndex = function () { + return this.slidingWindow.absoluteIndex(); + }; + + Scanner.prototype.setAbsoluteIndex = function (index) { + this.slidingWindow.setAbsoluteIndex(index); + }; + + Scanner.prototype.scan = function (diagnostics, allowRegularExpression) { + var diagnosticsLength = diagnostics.length; + var fullStart = this.slidingWindow.absoluteIndex(); + var leadingTriviaInfo = this.scanTriviaInfo(diagnostics, false); + + var start = this.slidingWindow.absoluteIndex(); + var kindAndFlags = this.scanSyntaxToken(diagnostics, allowRegularExpression); + var end = this.slidingWindow.absoluteIndex(); + + var trailingTriviaInfo = this.scanTriviaInfo(diagnostics, true); + var fullEnd = this.slidingWindow.absoluteIndex(); + + var isVariableWidthKeyword = (kindAndFlags & -2147483648 /* IsVariableWidthKeyword */) !== 0; + var kind = kindAndFlags & ~-2147483648 /* IsVariableWidthKeyword */; + + var token = this.createToken(fullStart, leadingTriviaInfo, start, kind, end, fullEnd, trailingTriviaInfo, isVariableWidthKeyword); + + return diagnosticsLength !== diagnostics.length ? TypeScript.Syntax.realizeToken(token) : token; + }; + + Scanner.prototype.createToken = function (fullStart, leadingTriviaInfo, start, kind, end, fullEnd, trailingTriviaInfo, isVariableWidthKeyword) { + if (!isVariableWidthKeyword && kind >= 15 /* FirstFixedWidth */) { + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.FixedWidthTokenWithNoTrivia(kind); + } else { + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo); + } else { + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo); + } + } else { + var width = end - start; + + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.VariableWidthTokenWithNoTrivia(fullText, kind); + } else { + return new TypeScript.Syntax.VariableWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.VariableWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo); + } else { + return new TypeScript.Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo); + } + } + }; + + Scanner.scanTrivia = function (text, start, length, isTrailing) { + var scanner = new Scanner(null, text.subText(new TypeScript.TextSpan(start, length)), 1 /* EcmaScript5 */, Scanner.triviaWindow); + return scanner.scanTrivia(text, start, isTrailing); + }; + + Scanner.prototype.scanTrivia = function (underlyingText, underlyingTextStart, isTrailing) { + var trivia = new Array(); + + while (true) { + if (!this.slidingWindow.isAtEndOfSource()) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + trivia.push(this.scanWhitespaceTrivia(underlyingText, underlyingTextStart)); + continue; + + case 47 /* slash */: + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 47 /* slash */) { + trivia.push(this.scanSingleLineCommentTrivia(underlyingText, underlyingTextStart)); + continue; + } + + if (ch2 === 42 /* asterisk */) { + trivia.push(this.scanMultiLineCommentTrivia(underlyingText, underlyingTextStart)); + continue; + } + + throw TypeScript.Errors.invalidOperation(); + + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + trivia.push(this.scanLineTerminatorSequenceTrivia(ch)); + + if (!isTrailing) { + continue; + } + + break; + + default: + throw TypeScript.Errors.invalidOperation(); + } + } + + return TypeScript.Syntax.triviaList(trivia); + } + }; + + Scanner.prototype.scanTriviaInfo = function (diagnostics, isTrailing) { + var width = 0; + var hasCommentOrNewLine = 0; + + while (true) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + this.slidingWindow.moveToNextItem(); + width++; + continue; + + case 47 /* slash */: + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 47 /* slash */) { + hasCommentOrNewLine |= 2 /* TriviaCommentMask */; + width += this.scanSingleLineCommentTriviaLength(); + continue; + } + + if (ch2 === 42 /* asterisk */) { + hasCommentOrNewLine |= 2 /* TriviaCommentMask */; + width += this.scanMultiLineCommentTriviaLength(diagnostics); + continue; + } + + break; + + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + hasCommentOrNewLine |= 1 /* TriviaNewLineMask */; + width += this.scanLineTerminatorSequenceLength(ch); + + if (!isTrailing) { + continue; + } + + break; + } + + return (width << 2 /* TriviaFullWidthShift */) | hasCommentOrNewLine; + } + }; + + Scanner.prototype.isNewLineCharacter = function (ch) { + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + return true; + default: + return false; + } + }; + + Scanner.prototype.scanWhitespaceTrivia = function (underlyingText, underlyingTextStart) { + var absoluteStartIndex = this.absoluteIndex(); + + var width = 0; + while (true) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + this.slidingWindow.moveToNextItem(); + width++; + continue; + } + + break; + } + + return TypeScript.Syntax.deferredTrivia(4 /* WhitespaceTrivia */, underlyingText, underlyingTextStart + absoluteStartIndex, width); + }; + + Scanner.prototype.scanSingleLineCommentTrivia = function (underlyingText, underlyingTextStart) { + var absoluteStartIndex = this.slidingWindow.absoluteIndex(); + var width = this.scanSingleLineCommentTriviaLength(); + + return TypeScript.Syntax.deferredTrivia(7 /* SingleLineCommentTrivia */, underlyingText, underlyingTextStart + absoluteStartIndex, width); + }; + + Scanner.prototype.scanSingleLineCommentTriviaLength = function () { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + var width = 2; + while (true) { + if (this.slidingWindow.isAtEndOfSource() || this.isNewLineCharacter(this.currentCharCode())) { + return width; + } + + this.slidingWindow.moveToNextItem(); + width++; + } + }; + + Scanner.prototype.scanMultiLineCommentTrivia = function (underlyingText, underlyingTextStart) { + var absoluteStartIndex = this.absoluteIndex(); + var width = this.scanMultiLineCommentTriviaLength(null); + + return TypeScript.Syntax.deferredTrivia(6 /* MultiLineCommentTrivia */, underlyingText, underlyingTextStart + absoluteStartIndex, width); + }; + + Scanner.prototype.scanMultiLineCommentTriviaLength = function (diagnostics) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + var width = 2; + while (true) { + if (this.slidingWindow.isAtEndOfSource()) { + if (diagnostics !== null) { + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), this.slidingWindow.absoluteIndex(), 0, TypeScript.DiagnosticCode.AsteriskSlash_expected, null)); + } + + return width; + } + + var ch = this.currentCharCode(); + if (ch === 42 /* asterisk */ && this.slidingWindow.peekItemN(1) === 47 /* slash */) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + width += 2; + return width; + } + + this.slidingWindow.moveToNextItem(); + width++; + } + }; + + Scanner.prototype.scanLineTerminatorSequenceTrivia = function (ch) { + var absoluteStartIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + var width = this.scanLineTerminatorSequenceLength(ch); + + var text = this.substring(absoluteStartIndex, absoluteStartIndex + width, false); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(absoluteStartIndex); + + return TypeScript.Syntax.trivia(5 /* NewLineTrivia */, text); + }; + + Scanner.prototype.scanLineTerminatorSequenceLength = function (ch) { + this.slidingWindow.moveToNextItem(); + + if (ch === 13 /* carriageReturn */ && this.currentCharCode() === 10 /* lineFeed */) { + this.slidingWindow.moveToNextItem(); + return 2; + } else { + return 1; + } + }; + + Scanner.prototype.scanSyntaxToken = function (diagnostics, allowRegularExpression) { + if (this.slidingWindow.isAtEndOfSource()) { + return 10 /* EndOfFileToken */; + } + + var character = this.currentCharCode(); + + switch (character) { + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + return this.scanStringLiteral(diagnostics); + + case 47 /* slash */: + return this.scanSlashToken(allowRegularExpression); + + case 46 /* dot */: + return this.scanDotToken(diagnostics); + + case 45 /* minus */: + return this.scanMinusToken(); + + case 33 /* exclamation */: + return this.scanExclamationToken(); + + case 61 /* equals */: + return this.scanEqualsToken(); + + case 124 /* bar */: + return this.scanBarToken(); + + case 42 /* asterisk */: + return this.scanAsteriskToken(); + + case 43 /* plus */: + return this.scanPlusToken(); + + case 37 /* percent */: + return this.scanPercentToken(); + + case 38 /* ampersand */: + return this.scanAmpersandToken(); + + case 94 /* caret */: + return this.scanCaretToken(); + + case 60 /* lessThan */: + return this.scanLessThanToken(); + + case 62 /* greaterThan */: + return this.advanceAndSetTokenKind(81 /* GreaterThanToken */); + + case 44 /* comma */: + return this.advanceAndSetTokenKind(79 /* CommaToken */); + + case 58 /* colon */: + return this.advanceAndSetTokenKind(106 /* ColonToken */); + + case 59 /* semicolon */: + return this.advanceAndSetTokenKind(78 /* SemicolonToken */); + + case 126 /* tilde */: + return this.advanceAndSetTokenKind(102 /* TildeToken */); + + case 40 /* openParen */: + return this.advanceAndSetTokenKind(72 /* OpenParenToken */); + + case 41 /* closeParen */: + return this.advanceAndSetTokenKind(73 /* CloseParenToken */); + + case 123 /* openBrace */: + return this.advanceAndSetTokenKind(70 /* OpenBraceToken */); + + case 125 /* closeBrace */: + return this.advanceAndSetTokenKind(71 /* CloseBraceToken */); + + case 91 /* openBracket */: + return this.advanceAndSetTokenKind(74 /* OpenBracketToken */); + + case 93 /* closeBracket */: + return this.advanceAndSetTokenKind(75 /* CloseBracketToken */); + + case 63 /* question */: + return this.advanceAndSetTokenKind(105 /* QuestionToken */); + } + + if (isNumericLiteralStart[character]) { + return this.scanNumericLiteral(diagnostics); + } + + if (isIdentifierStartCharacter[character]) { + var result = this.tryFastScanIdentifierOrKeyword(character); + if (result !== 0 /* None */) { + return result; + } + } + + if (this.isIdentifierStart(this.peekCharOrUnicodeEscape())) { + return this.slowScanIdentifierOrKeyword(diagnostics); + } + + return this.scanDefaultCharacter(character, diagnostics); + }; + + Scanner.prototype.isIdentifierStart = function (interpretedChar) { + if (isIdentifierStartCharacter[interpretedChar]) { + return true; + } + + return interpretedChar > 127 /* maxAsciiCharacter */ && TypeScript.Unicode.isIdentifierStart(interpretedChar, this._languageVersion); + }; + + Scanner.prototype.isIdentifierPart = function (interpretedChar) { + if (isIdentifierPartCharacter[interpretedChar]) { + return true; + } + + return interpretedChar > 127 /* maxAsciiCharacter */ && TypeScript.Unicode.isIdentifierPart(interpretedChar, this._languageVersion); + }; + + Scanner.prototype.tryFastScanIdentifierOrKeyword = function (firstCharacter) { + var slidingWindow = this.slidingWindow; + var window = slidingWindow.window; + + var startIndex = slidingWindow.currentRelativeItemIndex; + var endIndex = slidingWindow.windowCount; + var currentIndex = startIndex; + var character = 0; + + while (currentIndex < endIndex) { + character = window[currentIndex]; + if (!isIdentifierPartCharacter[character]) { + break; + } + + currentIndex++; + } + + if (currentIndex === endIndex) { + return 0 /* None */; + } else if (character === 92 /* backslash */ || character > 127 /* maxAsciiCharacter */) { + return 0 /* None */; + } else { + var kind; + var identifierLength = currentIndex - startIndex; + if (isKeywordStartCharacter[firstCharacter]) { + kind = TypeScript.ScannerUtilities.identifierKind(window, startIndex, identifierLength); + } else { + kind = 11 /* IdentifierName */; + } + + slidingWindow.setAbsoluteIndex(slidingWindow.absoluteIndex() + identifierLength); + + return kind; + } + }; + + Scanner.prototype.slowScanIdentifierOrKeyword = function (diagnostics) { + var startIndex = this.slidingWindow.absoluteIndex(); + var sawUnicodeEscape = false; + + do { + var unicodeEscape = this.scanCharOrUnicodeEscape(diagnostics); + sawUnicodeEscape = sawUnicodeEscape || unicodeEscape; + } while(this.isIdentifierPart(this.peekCharOrUnicodeEscape())); + + var length = this.slidingWindow.absoluteIndex() - startIndex; + var text = this.text.substr(startIndex, length, false); + var valueText = TypeScript.Syntax.massageEscapes(text); + + var keywordKind = TypeScript.SyntaxFacts.getTokenKind(valueText); + if (keywordKind >= 15 /* FirstKeyword */ && keywordKind <= 69 /* LastKeyword */) { + if (sawUnicodeEscape) { + return keywordKind | -2147483648 /* IsVariableWidthKeyword */; + } else { + return keywordKind; + } + } + + return 11 /* IdentifierName */; + }; + + Scanner.prototype.scanNumericLiteral = function (diagnostics) { + if (this.isHexNumericLiteral()) { + this.scanHexNumericLiteral(); + } else if (this.isOctalNumericLiteral()) { + this.scanOctalNumericLiteral(diagnostics); + } else { + this.scanDecimalNumericLiteral(); + } + + return 13 /* NumericLiteral */; + }; + + Scanner.prototype.isOctalNumericLiteral = function () { + return this.currentCharCode() === 48 /* _0 */ && TypeScript.CharacterInfo.isOctalDigit(this.slidingWindow.peekItemN(1)); + }; + + Scanner.prototype.scanOctalNumericLiteral = function (diagnostics) { + var position = this.absoluteIndex(); + + while (TypeScript.CharacterInfo.isOctalDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + + if (this.languageVersion() >= 1 /* EcmaScript5 */) { + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), position, this.absoluteIndex() - position, TypeScript.DiagnosticCode.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher, null)); + } + }; + + Scanner.prototype.scanDecimalDigits = function () { + while (TypeScript.CharacterInfo.isDecimalDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + }; + + Scanner.prototype.scanDecimalNumericLiteral = function () { + this.scanDecimalDigits(); + + if (this.currentCharCode() === 46 /* dot */) { + this.slidingWindow.moveToNextItem(); + } + + this.scanDecimalDigits(); + + var ch = this.currentCharCode(); + if (ch === 101 /* e */ || ch === 69 /* E */) { + var nextChar1 = this.slidingWindow.peekItemN(1); + + if (TypeScript.CharacterInfo.isDecimalDigit(nextChar1)) { + this.slidingWindow.moveToNextItem(); + this.scanDecimalDigits(); + } else if (nextChar1 === 45 /* minus */ || nextChar1 === 43 /* plus */) { + var nextChar2 = this.slidingWindow.peekItemN(2); + if (TypeScript.CharacterInfo.isDecimalDigit(nextChar2)) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + this.scanDecimalDigits(); + } + } + } + }; + + Scanner.prototype.scanHexNumericLiteral = function () { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + while (TypeScript.CharacterInfo.isHexDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + }; + + Scanner.prototype.isHexNumericLiteral = function () { + if (this.currentCharCode() === 48 /* _0 */) { + var ch = this.slidingWindow.peekItemN(1); + + if (ch === 120 /* x */ || ch === 88 /* X */) { + ch = this.slidingWindow.peekItemN(2); + + return TypeScript.CharacterInfo.isHexDigit(ch); + } + } + + return false; + }; + + Scanner.prototype.advanceAndSetTokenKind = function (kind) { + this.slidingWindow.moveToNextItem(); + return kind; + }; + + Scanner.prototype.scanLessThanToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 82 /* LessThanEqualsToken */; + } else if (this.currentCharCode() === 60 /* lessThan */) { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 112 /* LessThanLessThanEqualsToken */; + } else { + return 95 /* LessThanLessThanToken */; + } + } else { + return 80 /* LessThanToken */; + } + }; + + Scanner.prototype.scanBarToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 116 /* BarEqualsToken */; + } else if (this.currentCharCode() === 124 /* bar */) { + this.slidingWindow.moveToNextItem(); + return 104 /* BarBarToken */; + } else { + return 99 /* BarToken */; + } + }; + + Scanner.prototype.scanCaretToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 117 /* CaretEqualsToken */; + } else { + return 100 /* CaretToken */; + } + }; + + Scanner.prototype.scanAmpersandToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 115 /* AmpersandEqualsToken */; + } else if (this.currentCharCode() === 38 /* ampersand */) { + this.slidingWindow.moveToNextItem(); + return 103 /* AmpersandAmpersandToken */; + } else { + return 98 /* AmpersandToken */; + } + }; + + Scanner.prototype.scanPercentToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 111 /* PercentEqualsToken */; + } else { + return 92 /* PercentToken */; + } + }; + + Scanner.prototype.scanMinusToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 109 /* MinusEqualsToken */; + } else if (character === 45 /* minus */) { + this.slidingWindow.moveToNextItem(); + return 94 /* MinusMinusToken */; + } else { + return 90 /* MinusToken */; + } + }; + + Scanner.prototype.scanPlusToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 108 /* PlusEqualsToken */; + } else if (character === 43 /* plus */) { + this.slidingWindow.moveToNextItem(); + return 93 /* PlusPlusToken */; + } else { + return 89 /* PlusToken */; + } + }; + + Scanner.prototype.scanAsteriskToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 110 /* AsteriskEqualsToken */; + } else { + return 91 /* AsteriskToken */; + } + }; + + Scanner.prototype.scanEqualsToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + return 87 /* EqualsEqualsEqualsToken */; + } else { + return 84 /* EqualsEqualsToken */; + } + } else if (character === 62 /* greaterThan */) { + this.slidingWindow.moveToNextItem(); + return 85 /* EqualsGreaterThanToken */; + } else { + return 107 /* EqualsToken */; + } + }; + + Scanner.prototype.isDotPrefixedNumericLiteral = function () { + if (this.currentCharCode() === 46 /* dot */) { + var ch = this.slidingWindow.peekItemN(1); + return TypeScript.CharacterInfo.isDecimalDigit(ch); + } + + return false; + }; + + Scanner.prototype.scanDotToken = function (diagnostics) { + if (this.isDotPrefixedNumericLiteral()) { + return this.scanNumericLiteral(diagnostics); + } + + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 46 /* dot */ && this.slidingWindow.peekItemN(1) === 46 /* dot */) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + return 77 /* DotDotDotToken */; + } else { + return 76 /* DotToken */; + } + }; + + Scanner.prototype.scanSlashToken = function (allowRegularExpression) { + if (allowRegularExpression) { + var result = this.tryScanRegularExpressionToken(); + if (result !== 0 /* None */) { + return result; + } + } + + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 119 /* SlashEqualsToken */; + } else { + return 118 /* SlashToken */; + } + }; + + Scanner.prototype.tryScanRegularExpressionToken = function () { + var startIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + this.slidingWindow.moveToNextItem(); + + var inEscape = false; + var inCharacterClass = false; + while (true) { + var ch = this.currentCharCode(); + + if (this.isNewLineCharacter(ch) || this.slidingWindow.isAtEndOfSource()) { + this.slidingWindow.rewindToPinnedIndex(startIndex); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + return 0 /* None */; + } + + this.slidingWindow.moveToNextItem(); + if (inEscape) { + inEscape = false; + continue; + } + + switch (ch) { + case 92 /* backslash */: + inEscape = true; + continue; + + case 91 /* openBracket */: + inCharacterClass = true; + continue; + + case 93 /* closeBracket */: + inCharacterClass = false; + continue; + + case 47 /* slash */: + if (inCharacterClass) { + continue; + } + + break; + + default: + continue; + } + + break; + } + + while (isIdentifierPartCharacter[this.currentCharCode()]) { + this.slidingWindow.moveToNextItem(); + } + + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + return 12 /* RegularExpressionLiteral */; + }; + + Scanner.prototype.scanExclamationToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + return 88 /* ExclamationEqualsEqualsToken */; + } else { + return 86 /* ExclamationEqualsToken */; + } + } else { + return 101 /* ExclamationToken */; + } + }; + + Scanner.prototype.scanDefaultCharacter = function (character, diagnostics) { + var position = this.slidingWindow.absoluteIndex(); + this.slidingWindow.moveToNextItem(); + + var text = String.fromCharCode(character); + var messageText = this.getErrorMessageText(text); + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), position, 1, TypeScript.DiagnosticCode.Unexpected_character_0, [messageText])); + + return 9 /* ErrorToken */; + }; + + Scanner.prototype.getErrorMessageText = function (text) { + if (text === "\\") { + return '"\\"'; + } + + return JSON.stringify(text); + }; + + Scanner.prototype.skipEscapeSequence = function (diagnostics) { + var rewindPoint = this.slidingWindow.getAndPinAbsoluteIndex(); + + this.slidingWindow.moveToNextItem(); + + var ch = this.currentCharCode(); + this.slidingWindow.moveToNextItem(); + switch (ch) { + case 120 /* x */: + case 117 /* u */: + this.slidingWindow.rewindToPinnedIndex(rewindPoint); + var value = this.scanUnicodeOrHexEscape(diagnostics); + break; + + case 13 /* carriageReturn */: + if (this.currentCharCode() === 10 /* lineFeed */) { + this.slidingWindow.moveToNextItem(); + } + break; + + default: + break; + } + + this.slidingWindow.releaseAndUnpinAbsoluteIndex(rewindPoint); + }; + + Scanner.prototype.scanStringLiteral = function (diagnostics) { + var quoteCharacter = this.currentCharCode(); + + this.slidingWindow.moveToNextItem(); + + while (true) { + var ch = this.currentCharCode(); + if (ch === 92 /* backslash */) { + this.skipEscapeSequence(diagnostics); + } else if (ch === quoteCharacter) { + this.slidingWindow.moveToNextItem(); + break; + } else if (this.isNewLineCharacter(ch) || this.slidingWindow.isAtEndOfSource()) { + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), TypeScript.MathPrototype.min(this.slidingWindow.absoluteIndex(), this.text.length()), 1, TypeScript.DiagnosticCode.Missing_close_quote_character, null)); + break; + } else { + this.slidingWindow.moveToNextItem(); + } + } + + return 14 /* StringLiteral */; + }; + + Scanner.prototype.isUnicodeEscape = function (character) { + if (character === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 117 /* u */) { + return true; + } + } + + return false; + }; + + Scanner.prototype.peekCharOrUnicodeEscape = function () { + var character = this.currentCharCode(); + if (this.isUnicodeEscape(character)) { + return this.peekUnicodeOrHexEscape(); + } else { + return character; + } + }; + + Scanner.prototype.peekUnicodeOrHexEscape = function () { + var startIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + var ch = this.scanUnicodeOrHexEscape(null); + + this.slidingWindow.rewindToPinnedIndex(startIndex); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + + return ch; + }; + + Scanner.prototype.scanCharOrUnicodeEscape = function (errors) { + var ch = this.currentCharCode(); + if (ch === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 117 /* u */) { + this.scanUnicodeOrHexEscape(errors); + return true; + } + } + + this.slidingWindow.moveToNextItem(); + return false; + }; + + Scanner.prototype.scanUnicodeOrHexEscape = function (errors) { + var start = this.slidingWindow.absoluteIndex(); + var character = this.currentCharCode(); + + this.slidingWindow.moveToNextItem(); + + character = this.currentCharCode(); + + var intChar = 0; + this.slidingWindow.moveToNextItem(); + + var count = character === 117 /* u */ ? 4 : 2; + + for (var i = 0; i < count; i++) { + var ch2 = this.currentCharCode(); + if (!TypeScript.CharacterInfo.isHexDigit(ch2)) { + if (errors !== null) { + var end = this.slidingWindow.absoluteIndex(); + var info = this.createIllegalEscapeDiagnostic(start, end); + errors.push(info); + } + + break; + } + + intChar = (intChar << 4) + TypeScript.CharacterInfo.hexValue(ch2); + this.slidingWindow.moveToNextItem(); + } + + return intChar; + }; + + Scanner.prototype.substring = function (start, end, intern) { + var length = end - start; + var offset = start - this.slidingWindow.windowAbsoluteStartIndex; + + if (intern) { + return TypeScript.Collections.DefaultStringTable.addCharArray(this.slidingWindow.window, offset, length); + } else { + return TypeScript.StringUtilities.fromCharCodeArray(this.slidingWindow.window.slice(offset, offset + length)); + } + }; + + Scanner.prototype.createIllegalEscapeDiagnostic = function (start, end) { + return new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), start, end - start, TypeScript.DiagnosticCode.Unrecognized_escape_sequence, null); + }; + + Scanner.isValidIdentifier = function (text, languageVersion) { + var scanner = new Scanner(null, text, languageVersion, Scanner.triviaWindow); + var errors = new Array(); + var token = scanner.scan(errors, false); + + return errors.length === 0 && TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token) && token.width() === text.length(); + }; + Scanner.triviaWindow = TypeScript.ArrayUtilities.createArray(2048, 0); + return Scanner; + })(); + TypeScript.Scanner = Scanner; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScannerUtilities = (function () { + function ScannerUtilities() { + } + ScannerUtilities.identifierKind = function (array, startIndex, length) { + switch (length) { + case 2: + switch (array[startIndex]) { + case 100 /* d */: + return (array[startIndex + 1] === 111 /* o */) ? 22 /* DoKeyword */ : 11 /* IdentifierName */; + case 105 /* i */: + switch (array[startIndex + 1]) { + case 102 /* f */: + return 28 /* IfKeyword */; + case 110 /* n */: + return 29 /* InKeyword */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 3: + switch (array[startIndex]) { + case 102 /* f */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 114 /* r */) ? 26 /* ForKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 119 /* w */) ? 31 /* NewKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 121 /* y */) ? 38 /* TryKeyword */ : 11 /* IdentifierName */; + case 118 /* v */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 114 /* r */) ? 40 /* VarKeyword */ : 11 /* IdentifierName */; + case 108 /* l */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 53 /* LetKeyword */ : 11 /* IdentifierName */; + case 97 /* a */: + return (array[startIndex + 1] === 110 /* n */ && array[startIndex + 2] === 121 /* y */) ? 60 /* AnyKeyword */ : 11 /* IdentifierName */; + case 103 /* g */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 64 /* GetKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 68 /* SetKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 4: + switch (array[startIndex]) { + case 99 /* c */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 101 /* e */) ? 16 /* CaseKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + switch (array[startIndex + 1]) { + case 108 /* l */: + return (array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 101 /* e */) ? 23 /* ElseKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 2] === 117 /* u */ && array[startIndex + 3] === 109 /* m */) ? 46 /* EnumKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 110 /* n */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 108 /* l */) ? 32 /* NullKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + switch (array[startIndex + 1]) { + case 104 /* h */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 115 /* s */) ? 35 /* ThisKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 2] === 117 /* u */ && array[startIndex + 3] === 101 /* e */) ? 37 /* TrueKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 118 /* v */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 100 /* d */) ? 41 /* VoidKeyword */ : 11 /* IdentifierName */; + case 119 /* w */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 104 /* h */) ? 43 /* WithKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 5: + switch (array[startIndex]) { + case 98 /* b */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 101 /* e */ && array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 107 /* k */) ? 15 /* BreakKeyword */ : 11 /* IdentifierName */; + case 99 /* c */: + switch (array[startIndex + 1]) { + case 97 /* a */: + return (array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 99 /* c */ && array[startIndex + 4] === 104 /* h */) ? 17 /* CatchKeyword */ : 11 /* IdentifierName */; + case 108 /* l */: + return (array[startIndex + 2] === 97 /* a */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 115 /* s */) ? 44 /* ClassKeyword */ : 11 /* IdentifierName */; + case 111 /* o */: + return (array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 116 /* t */) ? 45 /* ConstKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 102 /* f */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 101 /* e */) ? 24 /* FalseKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + return (array[startIndex + 1] === 104 /* h */ && array[startIndex + 2] === 114 /* r */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 119 /* w */) ? 36 /* ThrowKeyword */ : 11 /* IdentifierName */; + case 119 /* w */: + return (array[startIndex + 1] === 104 /* h */ && array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */) ? 42 /* WhileKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 114 /* r */) ? 50 /* SuperKeyword */ : 11 /* IdentifierName */; + case 121 /* y */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 101 /* e */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 100 /* d */) ? 59 /* YieldKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 6: + switch (array[startIndex]) { + case 100 /* d */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 101 /* e */) ? 21 /* DeleteKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 110 /* n */) ? 33 /* ReturnKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + switch (array[startIndex + 1]) { + case 119 /* w */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 99 /* c */ && array[startIndex + 5] === 104 /* h */) ? 34 /* SwitchKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + switch (array[startIndex + 2]) { + case 97 /* a */: + return (array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 99 /* c */) ? 58 /* StaticKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 3] === 105 /* i */ && array[startIndex + 4] === 110 /* n */ && array[startIndex + 5] === 103 /* g */) ? 69 /* StringKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 116 /* t */: + return (array[startIndex + 1] === 121 /* y */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 111 /* o */ && array[startIndex + 5] === 102 /* f */) ? 39 /* TypeOfKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + return (array[startIndex + 1] === 120 /* x */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 116 /* t */) ? 47 /* ExportKeyword */ : 11 /* IdentifierName */; + case 105 /* i */: + return (array[startIndex + 1] === 109 /* m */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 116 /* t */) ? 49 /* ImportKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 98 /* b */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 99 /* c */) ? 57 /* PublicKeyword */ : 11 /* IdentifierName */; + case 109 /* m */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 100 /* d */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 108 /* l */ && array[startIndex + 5] === 101 /* e */) ? 65 /* ModuleKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 109 /* m */ && array[startIndex + 3] === 98 /* b */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 114 /* r */) ? 67 /* NumberKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 7: + switch (array[startIndex]) { + case 100 /* d */: + switch (array[startIndex + 1]) { + case 101 /* e */: + switch (array[startIndex + 2]) { + case 102 /* f */: + return (array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 117 /* u */ && array[startIndex + 5] === 108 /* l */ && array[startIndex + 6] === 116 /* t */) ? 20 /* DefaultKeyword */ : 11 /* IdentifierName */; + case 99 /* c */: + return (array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 101 /* e */) ? 63 /* DeclareKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 102 /* f */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 108 /* l */ && array[startIndex + 5] === 108 /* l */ && array[startIndex + 6] === 121 /* y */) ? 25 /* FinallyKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + return (array[startIndex + 1] === 120 /* x */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 110 /* n */ && array[startIndex + 5] === 100 /* d */ && array[startIndex + 6] === 115 /* s */) ? 48 /* ExtendsKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + switch (array[startIndex + 1]) { + case 97 /* a */: + return (array[startIndex + 2] === 99 /* c */ && array[startIndex + 3] === 107 /* k */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 103 /* g */ && array[startIndex + 6] === 101 /* e */) ? 54 /* PackageKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 118 /* v */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 116 /* t */ && array[startIndex + 6] === 101 /* e */) ? 55 /* PrivateKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 98 /* b */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 111 /* o */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 97 /* a */ && array[startIndex + 6] === 110 /* n */) ? 61 /* BooleanKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 113 /* q */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 101 /* e */) ? 66 /* RequireKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 8: + switch (array[startIndex]) { + case 99 /* c */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 110 /* n */ && array[startIndex + 6] === 117 /* u */ && array[startIndex + 7] === 101 /* e */) ? 18 /* ContinueKeyword */ : 11 /* IdentifierName */; + case 100 /* d */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 98 /* b */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 103 /* g */ && array[startIndex + 5] === 103 /* g */ && array[startIndex + 6] === 101 /* e */ && array[startIndex + 7] === 114 /* r */) ? 19 /* DebuggerKeyword */ : 11 /* IdentifierName */; + case 102 /* f */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 99 /* c */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 105 /* i */ && array[startIndex + 6] === 111 /* o */ && array[startIndex + 7] === 110 /* n */) ? 27 /* FunctionKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 9: + switch (array[startIndex]) { + case 105 /* i */: + return (array[startIndex + 1] === 110 /* n */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 102 /* f */ && array[startIndex + 6] === 97 /* a */ && array[startIndex + 7] === 99 /* c */ && array[startIndex + 8] === 101 /* e */) ? 52 /* InterfaceKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 111 /* o */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 99 /* c */ && array[startIndex + 6] === 116 /* t */ && array[startIndex + 7] === 101 /* e */ && array[startIndex + 8] === 100 /* d */) ? 56 /* ProtectedKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 10: + switch (array[startIndex]) { + case 105 /* i */: + switch (array[startIndex + 1]) { + case 110 /* n */: + return (array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 110 /* n */ && array[startIndex + 6] === 99 /* c */ && array[startIndex + 7] === 101 /* e */ && array[startIndex + 8] === 111 /* o */ && array[startIndex + 9] === 102 /* f */) ? 30 /* InstanceOfKeyword */ : 11 /* IdentifierName */; + case 109 /* m */: + return (array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 109 /* m */ && array[startIndex + 6] === 101 /* e */ && array[startIndex + 7] === 110 /* n */ && array[startIndex + 8] === 116 /* t */ && array[startIndex + 9] === 115 /* s */) ? 51 /* ImplementsKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 11: + return (array[startIndex] === 99 /* c */ && array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 117 /* u */ && array[startIndex + 7] === 99 /* c */ && array[startIndex + 8] === 116 /* t */ && array[startIndex + 9] === 111 /* o */ && array[startIndex + 10] === 114 /* r */) ? 62 /* ConstructorKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + }; + return ScannerUtilities; + })(); + TypeScript.ScannerUtilities = ScannerUtilities; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var EmptySeparatedSyntaxList = (function () { + function EmptySeparatedSyntaxList() { + } + EmptySeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + EmptySeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isList = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + + EmptySeparatedSyntaxList.prototype.toJSON = function (key) { + return []; + }; + + EmptySeparatedSyntaxList.prototype.childCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.separatorCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.toArray = function () { + return []; + }; + + EmptySeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + return []; + }; + + EmptySeparatedSyntaxList.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.separatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.collectTextElements = function (elements) { + }; + + EmptySeparatedSyntaxList.prototype.firstToken = function () { + return null; + }; + + EmptySeparatedSyntaxList.prototype.lastToken = function () { + return null; + }; + + EmptySeparatedSyntaxList.prototype.fullWidth = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.fullText = function () { + return ""; + }; + + EmptySeparatedSyntaxList.prototype.width = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + throw TypeScript.Errors.invalidOperation(); + }; + + EmptySeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + }; + + EmptySeparatedSyntaxList.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySeparatedSyntaxList.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return 0; + }; + return EmptySeparatedSyntaxList; + })(); + + Syntax.emptySeparatedList = new EmptySeparatedSyntaxList(); + + var SingletonSeparatedSyntaxList = (function () { + function SingletonSeparatedSyntaxList(item) { + this.item = item; + } + SingletonSeparatedSyntaxList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + SingletonSeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isList = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + + SingletonSeparatedSyntaxList.prototype.childCount = function () { + return 1; + }; + SingletonSeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return 1; + }; + SingletonSeparatedSyntaxList.prototype.separatorCount = function () { + return 0; + }; + + SingletonSeparatedSyntaxList.prototype.toArray = function () { + return [this.item]; + }; + SingletonSeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + return [this.item]; + }; + + SingletonSeparatedSyntaxList.prototype.childAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSeparatedSyntaxList.prototype.separatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + SingletonSeparatedSyntaxList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSeparatedSyntaxList.prototype.firstToken = function () { + return this.item.firstToken(); + }; + + SingletonSeparatedSyntaxList.prototype.lastToken = function () { + return this.item.lastToken(); + }; + + SingletonSeparatedSyntaxList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.width = function () { + return this.item.width(); + }; + + SingletonSeparatedSyntaxList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSeparatedSyntaxList.prototype.leadingTrivia = function () { + return this.item.leadingTrivia(); + }; + + SingletonSeparatedSyntaxList.prototype.trailingTrivia = function () { + return this.item.trailingTrivia(); + }; + + SingletonSeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return this.item.leadingTriviaWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return this.item.trailingTriviaWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + return this.item.isTypeScriptSpecific(); + }; + + SingletonSeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return this.item.isIncrementallyUnusable(); + }; + + SingletonSeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + return this.item.findTokenInternal(new TypeScript.PositionedSeparatedList(parent, this, fullStart), position, fullStart); + }; + + SingletonSeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + array.splice(index, 0, this.item); + }; + return SingletonSeparatedSyntaxList; + })(); + + var NormalSeparatedSyntaxList = (function () { + function NormalSeparatedSyntaxList(elements) { + this._data = 0; + this.elements = elements; + } + NormalSeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + NormalSeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isList = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + NormalSeparatedSyntaxList.prototype.toJSON = function (key) { + return this.elements; + }; + + NormalSeparatedSyntaxList.prototype.childCount = function () { + return this.elements.length; + }; + NormalSeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return TypeScript.IntegerUtilities.integerDivide(this.elements.length + 1, 2); + }; + NormalSeparatedSyntaxList.prototype.separatorCount = function () { + return TypeScript.IntegerUtilities.integerDivide(this.elements.length, 2); + }; + + NormalSeparatedSyntaxList.prototype.toArray = function () { + return this.elements.slice(0); + }; + + NormalSeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + var result = []; + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + result.push(this.nonSeparatorAt(i)); + } + + return result; + }; + + NormalSeparatedSyntaxList.prototype.childAt = function (index) { + if (index < 0 || index >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[index]; + }; + + NormalSeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + var value = index * 2; + if (value < 0 || value >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[value]; + }; + + NormalSeparatedSyntaxList.prototype.separatorAt = function (index) { + var value = index * 2 + 1; + if (value < 0 || value >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[value]; + }; + + NormalSeparatedSyntaxList.prototype.firstToken = function () { + var token; + for (var i = 0, n = this.elements.length; i < n; i++) { + if (i % 2 === 0) { + var nodeOrToken = this.elements[i]; + token = nodeOrToken.firstToken(); + if (token !== null) { + return token; + } + } else { + token = this.elements[i]; + if (token.width() > 0) { + return token; + } + } + } + + return null; + }; + + NormalSeparatedSyntaxList.prototype.lastToken = function () { + var token; + for (var i = this.elements.length - 1; i >= 0; i--) { + if (i % 2 === 0) { + var nodeOrToken = this.elements[i]; + token = nodeOrToken.lastToken(); + if (token !== null) { + return token; + } + } else { + token = this.elements[i]; + if (token.width() > 0) { + return token; + } + } + } + + return null; + }; + + NormalSeparatedSyntaxList.prototype.fullText = function () { + var elements = []; + this.collectTextElements(elements); + return elements.join(""); + }; + + NormalSeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + if (this.nonSeparatorAt(i).isTypeScriptSpecific()) { + return true; + } + } + + return false; + }; + + NormalSeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + NormalSeparatedSyntaxList.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + NormalSeparatedSyntaxList.prototype.width = function () { + var fullWidth = this.fullWidth(); + return fullWidth - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.leadingTrivia = function () { + return this.firstToken().leadingTrivia(); + }; + + NormalSeparatedSyntaxList.prototype.trailingTrivia = function () { + return this.lastToken().trailingTrivia(); + }; + + NormalSeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return this.firstToken().leadingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return this.lastToken().trailingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.computeData = function () { + var fullWidth = 0; + var isIncrementallyUnusable = false; + + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + + var childWidth = element.fullWidth(); + fullWidth += childWidth; + + isIncrementallyUnusable = isIncrementallyUnusable || element.isIncrementallyUnusable(); + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + NormalSeparatedSyntaxList.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data = this.computeData(); + } + + return this._data; + }; + + NormalSeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedSeparatedList(parent, this, fullStart); + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + + var childWidth = element.fullWidth(); + if (position < childWidth) { + return element.findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + NormalSeparatedSyntaxList.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + element.collectTextElements(elements); + } + }; + + NormalSeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + if (index === 0) { + array.unshift.apply(array, this.elements); + } else { + array.splice.apply(array, [index, 0].concat(this.elements)); + } + }; + return NormalSeparatedSyntaxList; + })(); + + function separatedList(nodes) { + return separatedListAndValidate(nodes, false); + } + Syntax.separatedList = separatedList; + + function separatedListAndValidate(nodes, validate) { + if (nodes === undefined || nodes === null || nodes.length === 0) { + return Syntax.emptySeparatedList; + } + + if (validate) { + for (var i = 0; i < nodes.length; i++) { + var item = nodes[i]; + + if (i % 2 === 1) { + } + } + } + + if (nodes.length === 1) { + return new SingletonSeparatedSyntaxList(nodes[0]); + } + + return new NormalSeparatedSyntaxList(nodes); + } + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SlidingWindow = (function () { + function SlidingWindow(source, window, defaultValue, sourceLength) { + if (typeof sourceLength === "undefined") { sourceLength = -1; } + this.source = source; + this.window = window; + this.defaultValue = defaultValue; + this.sourceLength = sourceLength; + this.windowCount = 0; + this.windowAbsoluteStartIndex = 0; + this.currentRelativeItemIndex = 0; + this._pinCount = 0; + this.firstPinnedAbsoluteIndex = -1; + } + SlidingWindow.prototype.windowAbsoluteEndIndex = function () { + return this.windowAbsoluteStartIndex + this.windowCount; + }; + + SlidingWindow.prototype.addMoreItemsToWindow = function (argument) { + if (this.sourceLength >= 0 && this.absoluteIndex() >= this.sourceLength) { + return false; + } + + if (this.windowCount >= this.window.length) { + this.tryShiftOrGrowWindow(); + } + + var spaceAvailable = this.window.length - this.windowCount; + var amountFetched = this.source.fetchMoreItems(argument, this.windowAbsoluteEndIndex(), this.window, this.windowCount, spaceAvailable); + + this.windowCount += amountFetched; + return amountFetched > 0; + }; + + SlidingWindow.prototype.tryShiftOrGrowWindow = function () { + var currentIndexIsPastWindowHalfwayPoint = this.currentRelativeItemIndex > (this.window.length >>> 1); + + var isAllowedToShift = this.firstPinnedAbsoluteIndex === -1 || this.firstPinnedAbsoluteIndex > this.windowAbsoluteStartIndex; + + if (currentIndexIsPastWindowHalfwayPoint && isAllowedToShift) { + var shiftStartIndex = this.firstPinnedAbsoluteIndex === -1 ? this.currentRelativeItemIndex : this.firstPinnedAbsoluteIndex - this.windowAbsoluteStartIndex; + + var shiftCount = this.windowCount - shiftStartIndex; + + if (shiftCount > 0) { + TypeScript.ArrayUtilities.copy(this.window, shiftStartIndex, this.window, 0, shiftCount); + } + + this.windowAbsoluteStartIndex += shiftStartIndex; + + this.windowCount -= shiftStartIndex; + + this.currentRelativeItemIndex -= shiftStartIndex; + } else { + TypeScript.ArrayUtilities.grow(this.window, this.window.length * 2, this.defaultValue); + } + }; + + SlidingWindow.prototype.absoluteIndex = function () { + return this.windowAbsoluteStartIndex + this.currentRelativeItemIndex; + }; + + SlidingWindow.prototype.isAtEndOfSource = function () { + return this.absoluteIndex() >= this.sourceLength; + }; + + SlidingWindow.prototype.getAndPinAbsoluteIndex = function () { + var absoluteIndex = this.absoluteIndex(); + var pinCount = this._pinCount++; + if (pinCount === 0) { + this.firstPinnedAbsoluteIndex = absoluteIndex; + } + + return absoluteIndex; + }; + + SlidingWindow.prototype.releaseAndUnpinAbsoluteIndex = function (absoluteIndex) { + this._pinCount--; + if (this._pinCount === 0) { + this.firstPinnedAbsoluteIndex = -1; + } + }; + + SlidingWindow.prototype.rewindToPinnedIndex = function (absoluteIndex) { + var relativeIndex = absoluteIndex - this.windowAbsoluteStartIndex; + + this.currentRelativeItemIndex = relativeIndex; + }; + + SlidingWindow.prototype.currentItem = function (argument) { + if (this.currentRelativeItemIndex >= this.windowCount) { + if (!this.addMoreItemsToWindow(argument)) { + return this.defaultValue; + } + } + + return this.window[this.currentRelativeItemIndex]; + }; + + SlidingWindow.prototype.peekItemN = function (n) { + while (this.currentRelativeItemIndex + n >= this.windowCount) { + if (!this.addMoreItemsToWindow(null)) { + return this.defaultValue; + } + } + + return this.window[this.currentRelativeItemIndex + n]; + }; + + SlidingWindow.prototype.moveToNextItem = function () { + this.currentRelativeItemIndex++; + }; + + SlidingWindow.prototype.disgardAllItemsFromCurrentIndexOnwards = function () { + this.windowCount = this.currentRelativeItemIndex; + }; + + SlidingWindow.prototype.setAbsoluteIndex = function (absoluteIndex) { + if (this.absoluteIndex() === absoluteIndex) { + return; + } + + if (this._pinCount > 0) { + } + + if (absoluteIndex >= this.windowAbsoluteStartIndex && absoluteIndex < this.windowAbsoluteEndIndex()) { + this.currentRelativeItemIndex = (absoluteIndex - this.windowAbsoluteStartIndex); + } else { + this.windowAbsoluteStartIndex = absoluteIndex; + + this.windowCount = 0; + + this.currentRelativeItemIndex = 0; + } + }; + + SlidingWindow.prototype.pinCount = function () { + return this._pinCount; + }; + return SlidingWindow; + })(); + TypeScript.SlidingWindow = SlidingWindow; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + function emptySourceUnit() { + return Syntax.normalModeFactory.sourceUnit(Syntax.emptyList, Syntax.token(10 /* EndOfFileToken */, { text: "" })); + } + Syntax.emptySourceUnit = emptySourceUnit; + + function getStandaloneExpression(positionedToken) { + var token = positionedToken.token(); + if (positionedToken !== null && positionedToken.kind() === 11 /* IdentifierName */) { + var parentPositionedNode = positionedToken.containingNode(); + var parentNode = parentPositionedNode.node(); + + if (parentNode.kind() === 121 /* QualifiedName */ && parentNode.right === token) { + return parentPositionedNode; + } else if (parentNode.kind() === 212 /* MemberAccessExpression */ && parentNode.name === token) { + return parentPositionedNode; + } + } + + return positionedToken; + } + Syntax.getStandaloneExpression = getStandaloneExpression; + + function isInModuleOrTypeContext(positionedToken) { + if (positionedToken !== null) { + var positionedNodeOrToken = Syntax.getStandaloneExpression(positionedToken); + var parent = positionedNodeOrToken.containingNode(); + + if (parent !== null) { + switch (parent.kind()) { + case 246 /* ModuleNameModuleReference */: + return true; + case 121 /* QualifiedName */: + return true; + default: + return isInTypeOnlyContext(positionedToken); + } + } + } + + return false; + } + Syntax.isInModuleOrTypeContext = isInModuleOrTypeContext; + + function isInTypeOnlyContext(positionedToken) { + var positionedNodeOrToken = Syntax.getStandaloneExpression(positionedToken); + var positionedParent = positionedNodeOrToken.containingNode(); + + var parent = positionedParent.node(); + var nodeOrToken = positionedNodeOrToken.nodeOrToken(); + + if (parent !== null) { + switch (parent.kind()) { + case 124 /* ArrayType */: + return parent.type === nodeOrToken; + case 220 /* CastExpression */: + return parent.type === nodeOrToken; + case 244 /* TypeAnnotation */: + case 230 /* ExtendsHeritageClause */: + case 231 /* ImplementsHeritageClause */: + case 228 /* TypeArgumentList */: + return true; + } + } + + return false; + } + Syntax.isInTypeOnlyContext = isInTypeOnlyContext; + + function childOffset(parent, child) { + var offset = 0; + for (var i = 0, n = parent.childCount(); i < n; i++) { + var current = parent.childAt(i); + if (current === child) { + return offset; + } + + if (current !== null) { + offset += current.fullWidth(); + } + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.childOffset = childOffset; + + function childOffsetAt(parent, index) { + var offset = 0; + for (var i = 0; i < index; i++) { + var current = parent.childAt(i); + if (current !== null) { + offset += current.fullWidth(); + } + } + + return offset; + } + Syntax.childOffsetAt = childOffsetAt; + + function childIndex(parent, child) { + for (var i = 0, n = parent.childCount(); i < n; i++) { + var current = parent.childAt(i); + if (current === child) { + return i; + } + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.childIndex = childIndex; + + function nodeStructuralEquals(node1, node2) { + if (node1 === null) { + return node2 === null; + } + + return node1.structuralEquals(node2); + } + Syntax.nodeStructuralEquals = nodeStructuralEquals; + + function nodeOrTokenStructuralEquals(node1, node2) { + if (node1 === node2) { + return true; + } + + if (node1 === null || node2 === null) { + return false; + } + + if (node1.isToken()) { + return node2.isToken() ? tokenStructuralEquals(node1, node2) : false; + } + + return node2.isNode() ? nodeStructuralEquals(node1, node2) : false; + } + Syntax.nodeOrTokenStructuralEquals = nodeOrTokenStructuralEquals; + + function tokenStructuralEquals(token1, token2) { + if (token1 === token2) { + return true; + } + + if (token1 === null || token2 === null) { + return false; + } + + return token1.kind() === token2.kind() && token1.width() === token2.width() && token1.fullWidth() === token2.fullWidth() && token1.text() === token2.text() && Syntax.triviaListStructuralEquals(token1.leadingTrivia(), token2.leadingTrivia()) && Syntax.triviaListStructuralEquals(token1.trailingTrivia(), token2.trailingTrivia()); + } + Syntax.tokenStructuralEquals = tokenStructuralEquals; + + function triviaListStructuralEquals(triviaList1, triviaList2) { + if (triviaList1.count() !== triviaList2.count()) { + return false; + } + + for (var i = 0, n = triviaList1.count(); i < n; i++) { + if (!Syntax.triviaStructuralEquals(triviaList1.syntaxTriviaAt(i), triviaList2.syntaxTriviaAt(i))) { + return false; + } + } + + return true; + } + Syntax.triviaListStructuralEquals = triviaListStructuralEquals; + + function triviaStructuralEquals(trivia1, trivia2) { + return trivia1.kind() === trivia2.kind() && trivia1.fullWidth() === trivia2.fullWidth() && trivia1.fullText() === trivia2.fullText(); + } + Syntax.triviaStructuralEquals = triviaStructuralEquals; + + function listStructuralEquals(list1, list2) { + if (list1.childCount() !== list2.childCount()) { + return false; + } + + for (var i = 0, n = list1.childCount(); i < n; i++) { + var child1 = list1.childAt(i); + var child2 = list2.childAt(i); + + if (!Syntax.nodeOrTokenStructuralEquals(child1, child2)) { + return false; + } + } + + return true; + } + Syntax.listStructuralEquals = listStructuralEquals; + + function separatedListStructuralEquals(list1, list2) { + if (list1.childCount() !== list2.childCount()) { + return false; + } + + for (var i = 0, n = list1.childCount(); i < n; i++) { + var element1 = list1.childAt(i); + var element2 = list2.childAt(i); + if (!Syntax.nodeOrTokenStructuralEquals(element1, element2)) { + return false; + } + } + + return true; + } + Syntax.separatedListStructuralEquals = separatedListStructuralEquals; + + function elementStructuralEquals(element1, element2) { + if (element1 === element2) { + return true; + } + + if (element1 === null || element2 === null) { + return false; + } + + if (element2.kind() !== element2.kind()) { + return false; + } + + if (element1.isToken()) { + return tokenStructuralEquals(element1, element2); + } else if (element1.isNode()) { + return nodeStructuralEquals(element1, element2); + } else if (element1.isList()) { + return listStructuralEquals(element1, element2); + } else if (element1.isSeparatedList()) { + return separatedListStructuralEquals(element1, element2); + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.elementStructuralEquals = elementStructuralEquals; + + function identifierName(text, info) { + if (typeof info === "undefined") { info = null; } + return Syntax.identifier(text); + } + Syntax.identifierName = identifierName; + + function trueExpression() { + return Syntax.token(37 /* TrueKeyword */); + } + Syntax.trueExpression = trueExpression; + + function falseExpression() { + return Syntax.token(24 /* FalseKeyword */); + } + Syntax.falseExpression = falseExpression; + + function numericLiteralExpression(text) { + return Syntax.token(13 /* NumericLiteral */, { text: text }); + } + Syntax.numericLiteralExpression = numericLiteralExpression; + + function stringLiteralExpression(text) { + return Syntax.token(14 /* StringLiteral */, { text: text }); + } + Syntax.stringLiteralExpression = stringLiteralExpression; + + function isSuperInvocationExpression(node) { + return node.kind() === 213 /* InvocationExpression */ && node.expression.kind() === 50 /* SuperKeyword */; + } + Syntax.isSuperInvocationExpression = isSuperInvocationExpression; + + function isSuperInvocationExpressionStatement(node) { + return node.kind() === 149 /* ExpressionStatement */ && isSuperInvocationExpression(node.expression); + } + Syntax.isSuperInvocationExpressionStatement = isSuperInvocationExpressionStatement; + + function isSuperMemberAccessExpression(node) { + return node.kind() === 212 /* MemberAccessExpression */ && node.expression.kind() === 50 /* SuperKeyword */; + } + Syntax.isSuperMemberAccessExpression = isSuperMemberAccessExpression; + + function isSuperMemberAccessInvocationExpression(node) { + return node.kind() === 213 /* InvocationExpression */ && isSuperMemberAccessExpression(node.expression); + } + Syntax.isSuperMemberAccessInvocationExpression = isSuperMemberAccessInvocationExpression; + + function assignmentExpression(left, token, right) { + return Syntax.normalModeFactory.binaryExpression(174 /* AssignmentExpression */, left, token, right); + } + Syntax.assignmentExpression = assignmentExpression; + + function nodeHasSkippedOrMissingTokens(node) { + for (var i = 0; i < node.childCount(); i++) { + var child = node.childAt(i); + if (child !== null && child.isToken()) { + var token = child; + + if (token.hasSkippedToken() || (token.width() === 0 && token.kind() !== 10 /* EndOfFileToken */)) { + return true; + } + } + } + return false; + } + Syntax.nodeHasSkippedOrMissingTokens = nodeHasSkippedOrMissingTokens; + + function isUnterminatedStringLiteral(token) { + if (token && token.kind() === 14 /* StringLiteral */) { + var text = token.text(); + return text.length < 2 || text.charCodeAt(text.length - 1) !== text.charCodeAt(0); + } + + return false; + } + Syntax.isUnterminatedStringLiteral = isUnterminatedStringLiteral; + + function isUnterminatedMultilineCommentTrivia(trivia) { + if (trivia && trivia.kind() === 6 /* MultiLineCommentTrivia */) { + var text = trivia.fullText(); + return text.length < 4 || text.substring(text.length - 2) !== "*/"; + } + return false; + } + Syntax.isUnterminatedMultilineCommentTrivia = isUnterminatedMultilineCommentTrivia; + + function isEntirelyInsideCommentTrivia(trivia, fullStart, position) { + if (trivia && trivia.isComment() && position > fullStart) { + var end = fullStart + trivia.fullWidth(); + if (position < end) { + return true; + } else if (position === end) { + return trivia.kind() === 7 /* SingleLineCommentTrivia */ || isUnterminatedMultilineCommentTrivia(trivia); + } + } + + return false; + } + Syntax.isEntirelyInsideCommentTrivia = isEntirelyInsideCommentTrivia; + + function isEntirelyInsideComment(sourceUnit, position) { + var positionedToken = sourceUnit.findToken(position); + var fullStart = positionedToken.fullStart(); + var triviaList = null; + var lastTriviaBeforeToken = null; + + if (positionedToken.kind() === 10 /* EndOfFileToken */) { + if (positionedToken.token().hasLeadingTrivia()) { + triviaList = positionedToken.token().leadingTrivia(); + } else { + positionedToken = positionedToken.previousToken(); + if (positionedToken) { + if (positionedToken && positionedToken.token().hasTrailingTrivia()) { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + } + } + } else { + if (position <= (fullStart + positionedToken.token().leadingTriviaWidth())) { + triviaList = positionedToken.token().leadingTrivia(); + } else if (position >= (fullStart + positionedToken.token().width())) { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + } + + if (triviaList) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (position <= fullStart) { + break; + } else if (position <= fullStart + trivia.fullWidth() && trivia.isComment()) { + lastTriviaBeforeToken = trivia; + break; + } + + fullStart += trivia.fullWidth(); + } + } + + return lastTriviaBeforeToken && isEntirelyInsideCommentTrivia(lastTriviaBeforeToken, fullStart, position); + } + Syntax.isEntirelyInsideComment = isEntirelyInsideComment; + + function isEntirelyInStringOrRegularExpressionLiteral(sourceUnit, position) { + var positionedToken = sourceUnit.findToken(position); + + if (positionedToken) { + if (positionedToken.kind() === 10 /* EndOfFileToken */) { + positionedToken = positionedToken.previousToken(); + return positionedToken && positionedToken.token().trailingTriviaWidth() === 0 && isUnterminatedStringLiteral(positionedToken.token()); + } else if (position > positionedToken.start()) { + return (position < positionedToken.end() && (positionedToken.kind() === 14 /* StringLiteral */ || positionedToken.kind() === 12 /* RegularExpressionLiteral */)) || (position <= positionedToken.end() && isUnterminatedStringLiteral(positionedToken.token())); + } + } + + return false; + } + Syntax.isEntirelyInStringOrRegularExpressionLiteral = isEntirelyInStringOrRegularExpressionLiteral; + + function findSkippedTokenInTriviaList(positionedToken, position, lookInLeadingTriviaList) { + var triviaList = null; + var fullStart; + + if (lookInLeadingTriviaList) { + triviaList = positionedToken.token().leadingTrivia(); + fullStart = positionedToken.fullStart(); + } else { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + + if (triviaList && triviaList.hasSkippedToken()) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + var triviaWidth = trivia.fullWidth(); + + if (trivia.isSkippedToken() && position >= fullStart && position <= fullStart + triviaWidth) { + return new TypeScript.PositionedSkippedToken(positionedToken, trivia.skippedToken(), fullStart); + } + + fullStart += triviaWidth; + } + } + + return null; + } + + function findSkippedTokenOnLeftInTriviaList(positionedToken, position, lookInLeadingTriviaList) { + var triviaList = null; + var fullEnd; + + if (lookInLeadingTriviaList) { + triviaList = positionedToken.token().leadingTrivia(); + fullEnd = positionedToken.fullStart() + triviaList.fullWidth(); + } else { + triviaList = positionedToken.token().trailingTrivia(); + fullEnd = positionedToken.fullEnd(); + } + + if (triviaList && triviaList.hasSkippedToken()) { + for (var i = triviaList.count() - 1; i >= 0; i--) { + var trivia = triviaList.syntaxTriviaAt(i); + var triviaWidth = trivia.fullWidth(); + + if (trivia.isSkippedToken() && position >= fullEnd) { + return new TypeScript.PositionedSkippedToken(positionedToken, trivia.skippedToken(), fullEnd - triviaWidth); + } + + fullEnd -= triviaWidth; + } + } + + return null; + } + + function findSkippedTokenInLeadingTriviaList(positionedToken, position) { + return findSkippedTokenInTriviaList(positionedToken, position, true); + } + Syntax.findSkippedTokenInLeadingTriviaList = findSkippedTokenInLeadingTriviaList; + + function findSkippedTokenInTrailingTriviaList(positionedToken, position) { + return findSkippedTokenInTriviaList(positionedToken, position, false); + } + Syntax.findSkippedTokenInTrailingTriviaList = findSkippedTokenInTrailingTriviaList; + + function findSkippedTokenInPositionedToken(positionedToken, position) { + var positionInLeadingTriviaList = (position < positionedToken.start()); + return findSkippedTokenInTriviaList(positionedToken, position, positionInLeadingTriviaList); + } + Syntax.findSkippedTokenInPositionedToken = findSkippedTokenInPositionedToken; + + function findSkippedTokenOnLeft(positionedToken, position) { + var positionInLeadingTriviaList = (position < positionedToken.start()); + return findSkippedTokenOnLeftInTriviaList(positionedToken, position, positionInLeadingTriviaList); + } + Syntax.findSkippedTokenOnLeft = findSkippedTokenOnLeft; + + function getAncestorOfKind(positionedToken, kind) { + while (positionedToken && positionedToken.parent()) { + if (positionedToken.parent().kind() === kind) { + return positionedToken.parent(); + } + + positionedToken = positionedToken.parent(); + } + + return null; + } + Syntax.getAncestorOfKind = getAncestorOfKind; + + function hasAncestorOfKind(positionedToken, kind) { + return Syntax.getAncestorOfKind(positionedToken, kind) !== null; + } + Syntax.hasAncestorOfKind = hasAncestorOfKind; + + function isIntegerLiteral(expression) { + if (expression) { + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + expression = expression.operand; + return expression.isToken() && TypeScript.IntegerUtilities.isInteger(expression.text()); + + case 13 /* NumericLiteral */: + var text = expression.text(); + return TypeScript.IntegerUtilities.isInteger(text) || TypeScript.IntegerUtilities.isHexInteger(text); + } + } + + return false; + } + Syntax.isIntegerLiteral = isIntegerLiteral; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var NormalModeFactory = (function () { + function NormalModeFactory() { + } + NormalModeFactory.prototype.sourceUnit = function (moduleElements, endOfFileToken) { + return new TypeScript.SourceUnitSyntax(moduleElements, endOfFileToken, false); + }; + NormalModeFactory.prototype.externalModuleReference = function (requireKeyword, openParenToken, stringLiteral, closeParenToken) { + return new TypeScript.ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, false); + }; + NormalModeFactory.prototype.moduleNameModuleReference = function (moduleName) { + return new TypeScript.ModuleNameModuleReferenceSyntax(moduleName, false); + }; + NormalModeFactory.prototype.importDeclaration = function (modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new TypeScript.ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, false); + }; + NormalModeFactory.prototype.exportAssignment = function (exportKeyword, equalsToken, identifier, semicolonToken) { + return new TypeScript.ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.classDeclaration = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + return new TypeScript.ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.interfaceDeclaration = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + return new TypeScript.InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, false); + }; + NormalModeFactory.prototype.heritageClause = function (kind, extendsOrImplementsKeyword, typeNames) { + return new TypeScript.HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, false); + }; + NormalModeFactory.prototype.moduleDeclaration = function (modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + return new TypeScript.ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.functionDeclaration = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + return new TypeScript.FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.variableStatement = function (modifiers, variableDeclaration, semicolonToken) { + return new TypeScript.VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, false); + }; + NormalModeFactory.prototype.variableDeclaration = function (varKeyword, variableDeclarators) { + return new TypeScript.VariableDeclarationSyntax(varKeyword, variableDeclarators, false); + }; + NormalModeFactory.prototype.variableDeclarator = function (propertyName, typeAnnotation, equalsValueClause) { + return new TypeScript.VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, false); + }; + NormalModeFactory.prototype.equalsValueClause = function (equalsToken, value) { + return new TypeScript.EqualsValueClauseSyntax(equalsToken, value, false); + }; + NormalModeFactory.prototype.prefixUnaryExpression = function (kind, operatorToken, operand) { + return new TypeScript.PrefixUnaryExpressionSyntax(kind, operatorToken, operand, false); + }; + NormalModeFactory.prototype.arrayLiteralExpression = function (openBracketToken, expressions, closeBracketToken) { + return new TypeScript.ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, false); + }; + NormalModeFactory.prototype.omittedExpression = function () { + return new TypeScript.OmittedExpressionSyntax(false); + }; + NormalModeFactory.prototype.parenthesizedExpression = function (openParenToken, expression, closeParenToken) { + return new TypeScript.ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, false); + }; + NormalModeFactory.prototype.simpleArrowFunctionExpression = function (identifier, equalsGreaterThanToken, block, expression) { + return new TypeScript.SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, false); + }; + NormalModeFactory.prototype.parenthesizedArrowFunctionExpression = function (callSignature, equalsGreaterThanToken, block, expression) { + return new TypeScript.ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, false); + }; + NormalModeFactory.prototype.qualifiedName = function (left, dotToken, right) { + return new TypeScript.QualifiedNameSyntax(left, dotToken, right, false); + }; + NormalModeFactory.prototype.typeArgumentList = function (lessThanToken, typeArguments, greaterThanToken) { + return new TypeScript.TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, false); + }; + NormalModeFactory.prototype.constructorType = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, false); + }; + NormalModeFactory.prototype.functionType = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, false); + }; + NormalModeFactory.prototype.objectType = function (openBraceToken, typeMembers, closeBraceToken) { + return new TypeScript.ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, false); + }; + NormalModeFactory.prototype.arrayType = function (type, openBracketToken, closeBracketToken) { + return new TypeScript.ArrayTypeSyntax(type, openBracketToken, closeBracketToken, false); + }; + NormalModeFactory.prototype.genericType = function (name, typeArgumentList) { + return new TypeScript.GenericTypeSyntax(name, typeArgumentList, false); + }; + NormalModeFactory.prototype.typeQuery = function (typeOfKeyword, name) { + return new TypeScript.TypeQuerySyntax(typeOfKeyword, name, false); + }; + NormalModeFactory.prototype.typeAnnotation = function (colonToken, type) { + return new TypeScript.TypeAnnotationSyntax(colonToken, type, false); + }; + NormalModeFactory.prototype.block = function (openBraceToken, statements, closeBraceToken) { + return new TypeScript.BlockSyntax(openBraceToken, statements, closeBraceToken, false); + }; + NormalModeFactory.prototype.parameter = function (dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + return new TypeScript.ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, false); + }; + NormalModeFactory.prototype.memberAccessExpression = function (expression, dotToken, name) { + return new TypeScript.MemberAccessExpressionSyntax(expression, dotToken, name, false); + }; + NormalModeFactory.prototype.postfixUnaryExpression = function (kind, operand, operatorToken) { + return new TypeScript.PostfixUnaryExpressionSyntax(kind, operand, operatorToken, false); + }; + NormalModeFactory.prototype.elementAccessExpression = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + return new TypeScript.ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, false); + }; + NormalModeFactory.prototype.invocationExpression = function (expression, argumentList) { + return new TypeScript.InvocationExpressionSyntax(expression, argumentList, false); + }; + NormalModeFactory.prototype.argumentList = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + return new TypeScript.ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, false); + }; + NormalModeFactory.prototype.binaryExpression = function (kind, left, operatorToken, right) { + return new TypeScript.BinaryExpressionSyntax(kind, left, operatorToken, right, false); + }; + NormalModeFactory.prototype.conditionalExpression = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + return new TypeScript.ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, false); + }; + NormalModeFactory.prototype.constructSignature = function (newKeyword, callSignature) { + return new TypeScript.ConstructSignatureSyntax(newKeyword, callSignature, false); + }; + NormalModeFactory.prototype.methodSignature = function (propertyName, questionToken, callSignature) { + return new TypeScript.MethodSignatureSyntax(propertyName, questionToken, callSignature, false); + }; + NormalModeFactory.prototype.indexSignature = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + return new TypeScript.IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, false); + }; + NormalModeFactory.prototype.propertySignature = function (propertyName, questionToken, typeAnnotation) { + return new TypeScript.PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, false); + }; + NormalModeFactory.prototype.callSignature = function (typeParameterList, parameterList, typeAnnotation) { + return new TypeScript.CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, false); + }; + NormalModeFactory.prototype.parameterList = function (openParenToken, parameters, closeParenToken) { + return new TypeScript.ParameterListSyntax(openParenToken, parameters, closeParenToken, false); + }; + NormalModeFactory.prototype.typeParameterList = function (lessThanToken, typeParameters, greaterThanToken) { + return new TypeScript.TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, false); + }; + NormalModeFactory.prototype.typeParameter = function (identifier, constraint) { + return new TypeScript.TypeParameterSyntax(identifier, constraint, false); + }; + NormalModeFactory.prototype.constraint = function (extendsKeyword, type) { + return new TypeScript.ConstraintSyntax(extendsKeyword, type, false); + }; + NormalModeFactory.prototype.elseClause = function (elseKeyword, statement) { + return new TypeScript.ElseClauseSyntax(elseKeyword, statement, false); + }; + NormalModeFactory.prototype.ifStatement = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + return new TypeScript.IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, false); + }; + NormalModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { + return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, false); + }; + NormalModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { + return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.getAccessor = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + return new TypeScript.GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, false); + }; + NormalModeFactory.prototype.setAccessor = function (modifiers, setKeyword, propertyName, parameterList, block) { + return new TypeScript.SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, false); + }; + NormalModeFactory.prototype.memberVariableDeclaration = function (modifiers, variableDeclarator, semicolonToken) { + return new TypeScript.MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, false); + }; + NormalModeFactory.prototype.indexMemberDeclaration = function (modifiers, indexSignature, semicolonToken) { + return new TypeScript.IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, false); + }; + NormalModeFactory.prototype.throwStatement = function (throwKeyword, expression, semicolonToken) { + return new TypeScript.ThrowStatementSyntax(throwKeyword, expression, semicolonToken, false); + }; + NormalModeFactory.prototype.returnStatement = function (returnKeyword, expression, semicolonToken) { + return new TypeScript.ReturnStatementSyntax(returnKeyword, expression, semicolonToken, false); + }; + NormalModeFactory.prototype.objectCreationExpression = function (newKeyword, expression, argumentList) { + return new TypeScript.ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, false); + }; + NormalModeFactory.prototype.switchStatement = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + return new TypeScript.SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, false); + }; + NormalModeFactory.prototype.caseSwitchClause = function (caseKeyword, expression, colonToken, statements) { + return new TypeScript.CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, false); + }; + NormalModeFactory.prototype.defaultSwitchClause = function (defaultKeyword, colonToken, statements) { + return new TypeScript.DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, false); + }; + NormalModeFactory.prototype.breakStatement = function (breakKeyword, identifier, semicolonToken) { + return new TypeScript.BreakStatementSyntax(breakKeyword, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.continueStatement = function (continueKeyword, identifier, semicolonToken) { + return new TypeScript.ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.forStatement = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + return new TypeScript.ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.forInStatement = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + return new TypeScript.ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.whileStatement = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.withStatement = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.enumDeclaration = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + return new TypeScript.EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.enumElement = function (propertyName, equalsValueClause) { + return new TypeScript.EnumElementSyntax(propertyName, equalsValueClause, false); + }; + NormalModeFactory.prototype.castExpression = function (lessThanToken, type, greaterThanToken, expression) { + return new TypeScript.CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, false); + }; + NormalModeFactory.prototype.objectLiteralExpression = function (openBraceToken, propertyAssignments, closeBraceToken) { + return new TypeScript.ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, false); + }; + NormalModeFactory.prototype.simplePropertyAssignment = function (propertyName, colonToken, expression) { + return new TypeScript.SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, false); + }; + NormalModeFactory.prototype.functionPropertyAssignment = function (propertyName, callSignature, block) { + return new TypeScript.FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, false); + }; + NormalModeFactory.prototype.functionExpression = function (functionKeyword, identifier, callSignature, block) { + return new TypeScript.FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, false); + }; + NormalModeFactory.prototype.emptyStatement = function (semicolonToken) { + return new TypeScript.EmptyStatementSyntax(semicolonToken, false); + }; + NormalModeFactory.prototype.tryStatement = function (tryKeyword, block, catchClause, finallyClause) { + return new TypeScript.TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, false); + }; + NormalModeFactory.prototype.catchClause = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + return new TypeScript.CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, false); + }; + NormalModeFactory.prototype.finallyClause = function (finallyKeyword, block) { + return new TypeScript.FinallyClauseSyntax(finallyKeyword, block, false); + }; + NormalModeFactory.prototype.labeledStatement = function (identifier, colonToken, statement) { + return new TypeScript.LabeledStatementSyntax(identifier, colonToken, statement, false); + }; + NormalModeFactory.prototype.doStatement = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + return new TypeScript.DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, false); + }; + NormalModeFactory.prototype.typeOfExpression = function (typeOfKeyword, expression) { + return new TypeScript.TypeOfExpressionSyntax(typeOfKeyword, expression, false); + }; + NormalModeFactory.prototype.deleteExpression = function (deleteKeyword, expression) { + return new TypeScript.DeleteExpressionSyntax(deleteKeyword, expression, false); + }; + NormalModeFactory.prototype.voidExpression = function (voidKeyword, expression) { + return new TypeScript.VoidExpressionSyntax(voidKeyword, expression, false); + }; + NormalModeFactory.prototype.debuggerStatement = function (debuggerKeyword, semicolonToken) { + return new TypeScript.DebuggerStatementSyntax(debuggerKeyword, semicolonToken, false); + }; + return NormalModeFactory; + })(); + Syntax.NormalModeFactory = NormalModeFactory; + + var StrictModeFactory = (function () { + function StrictModeFactory() { + } + StrictModeFactory.prototype.sourceUnit = function (moduleElements, endOfFileToken) { + return new TypeScript.SourceUnitSyntax(moduleElements, endOfFileToken, true); + }; + StrictModeFactory.prototype.externalModuleReference = function (requireKeyword, openParenToken, stringLiteral, closeParenToken) { + return new TypeScript.ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, true); + }; + StrictModeFactory.prototype.moduleNameModuleReference = function (moduleName) { + return new TypeScript.ModuleNameModuleReferenceSyntax(moduleName, true); + }; + StrictModeFactory.prototype.importDeclaration = function (modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new TypeScript.ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, true); + }; + StrictModeFactory.prototype.exportAssignment = function (exportKeyword, equalsToken, identifier, semicolonToken) { + return new TypeScript.ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.classDeclaration = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + return new TypeScript.ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.interfaceDeclaration = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + return new TypeScript.InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, true); + }; + StrictModeFactory.prototype.heritageClause = function (kind, extendsOrImplementsKeyword, typeNames) { + return new TypeScript.HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, true); + }; + StrictModeFactory.prototype.moduleDeclaration = function (modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + return new TypeScript.ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.functionDeclaration = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + return new TypeScript.FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.variableStatement = function (modifiers, variableDeclaration, semicolonToken) { + return new TypeScript.VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, true); + }; + StrictModeFactory.prototype.variableDeclaration = function (varKeyword, variableDeclarators) { + return new TypeScript.VariableDeclarationSyntax(varKeyword, variableDeclarators, true); + }; + StrictModeFactory.prototype.variableDeclarator = function (propertyName, typeAnnotation, equalsValueClause) { + return new TypeScript.VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, true); + }; + StrictModeFactory.prototype.equalsValueClause = function (equalsToken, value) { + return new TypeScript.EqualsValueClauseSyntax(equalsToken, value, true); + }; + StrictModeFactory.prototype.prefixUnaryExpression = function (kind, operatorToken, operand) { + return new TypeScript.PrefixUnaryExpressionSyntax(kind, operatorToken, operand, true); + }; + StrictModeFactory.prototype.arrayLiteralExpression = function (openBracketToken, expressions, closeBracketToken) { + return new TypeScript.ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, true); + }; + StrictModeFactory.prototype.omittedExpression = function () { + return new TypeScript.OmittedExpressionSyntax(true); + }; + StrictModeFactory.prototype.parenthesizedExpression = function (openParenToken, expression, closeParenToken) { + return new TypeScript.ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, true); + }; + StrictModeFactory.prototype.simpleArrowFunctionExpression = function (identifier, equalsGreaterThanToken, block, expression) { + return new TypeScript.SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, true); + }; + StrictModeFactory.prototype.parenthesizedArrowFunctionExpression = function (callSignature, equalsGreaterThanToken, block, expression) { + return new TypeScript.ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, true); + }; + StrictModeFactory.prototype.qualifiedName = function (left, dotToken, right) { + return new TypeScript.QualifiedNameSyntax(left, dotToken, right, true); + }; + StrictModeFactory.prototype.typeArgumentList = function (lessThanToken, typeArguments, greaterThanToken) { + return new TypeScript.TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, true); + }; + StrictModeFactory.prototype.constructorType = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, true); + }; + StrictModeFactory.prototype.functionType = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, true); + }; + StrictModeFactory.prototype.objectType = function (openBraceToken, typeMembers, closeBraceToken) { + return new TypeScript.ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, true); + }; + StrictModeFactory.prototype.arrayType = function (type, openBracketToken, closeBracketToken) { + return new TypeScript.ArrayTypeSyntax(type, openBracketToken, closeBracketToken, true); + }; + StrictModeFactory.prototype.genericType = function (name, typeArgumentList) { + return new TypeScript.GenericTypeSyntax(name, typeArgumentList, true); + }; + StrictModeFactory.prototype.typeQuery = function (typeOfKeyword, name) { + return new TypeScript.TypeQuerySyntax(typeOfKeyword, name, true); + }; + StrictModeFactory.prototype.typeAnnotation = function (colonToken, type) { + return new TypeScript.TypeAnnotationSyntax(colonToken, type, true); + }; + StrictModeFactory.prototype.block = function (openBraceToken, statements, closeBraceToken) { + return new TypeScript.BlockSyntax(openBraceToken, statements, closeBraceToken, true); + }; + StrictModeFactory.prototype.parameter = function (dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + return new TypeScript.ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, true); + }; + StrictModeFactory.prototype.memberAccessExpression = function (expression, dotToken, name) { + return new TypeScript.MemberAccessExpressionSyntax(expression, dotToken, name, true); + }; + StrictModeFactory.prototype.postfixUnaryExpression = function (kind, operand, operatorToken) { + return new TypeScript.PostfixUnaryExpressionSyntax(kind, operand, operatorToken, true); + }; + StrictModeFactory.prototype.elementAccessExpression = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + return new TypeScript.ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, true); + }; + StrictModeFactory.prototype.invocationExpression = function (expression, argumentList) { + return new TypeScript.InvocationExpressionSyntax(expression, argumentList, true); + }; + StrictModeFactory.prototype.argumentList = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + return new TypeScript.ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, true); + }; + StrictModeFactory.prototype.binaryExpression = function (kind, left, operatorToken, right) { + return new TypeScript.BinaryExpressionSyntax(kind, left, operatorToken, right, true); + }; + StrictModeFactory.prototype.conditionalExpression = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + return new TypeScript.ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, true); + }; + StrictModeFactory.prototype.constructSignature = function (newKeyword, callSignature) { + return new TypeScript.ConstructSignatureSyntax(newKeyword, callSignature, true); + }; + StrictModeFactory.prototype.methodSignature = function (propertyName, questionToken, callSignature) { + return new TypeScript.MethodSignatureSyntax(propertyName, questionToken, callSignature, true); + }; + StrictModeFactory.prototype.indexSignature = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + return new TypeScript.IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, true); + }; + StrictModeFactory.prototype.propertySignature = function (propertyName, questionToken, typeAnnotation) { + return new TypeScript.PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, true); + }; + StrictModeFactory.prototype.callSignature = function (typeParameterList, parameterList, typeAnnotation) { + return new TypeScript.CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, true); + }; + StrictModeFactory.prototype.parameterList = function (openParenToken, parameters, closeParenToken) { + return new TypeScript.ParameterListSyntax(openParenToken, parameters, closeParenToken, true); + }; + StrictModeFactory.prototype.typeParameterList = function (lessThanToken, typeParameters, greaterThanToken) { + return new TypeScript.TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, true); + }; + StrictModeFactory.prototype.typeParameter = function (identifier, constraint) { + return new TypeScript.TypeParameterSyntax(identifier, constraint, true); + }; + StrictModeFactory.prototype.constraint = function (extendsKeyword, type) { + return new TypeScript.ConstraintSyntax(extendsKeyword, type, true); + }; + StrictModeFactory.prototype.elseClause = function (elseKeyword, statement) { + return new TypeScript.ElseClauseSyntax(elseKeyword, statement, true); + }; + StrictModeFactory.prototype.ifStatement = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + return new TypeScript.IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, true); + }; + StrictModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { + return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, true); + }; + StrictModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { + return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.getAccessor = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + return new TypeScript.GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, true); + }; + StrictModeFactory.prototype.setAccessor = function (modifiers, setKeyword, propertyName, parameterList, block) { + return new TypeScript.SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, true); + }; + StrictModeFactory.prototype.memberVariableDeclaration = function (modifiers, variableDeclarator, semicolonToken) { + return new TypeScript.MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, true); + }; + StrictModeFactory.prototype.indexMemberDeclaration = function (modifiers, indexSignature, semicolonToken) { + return new TypeScript.IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, true); + }; + StrictModeFactory.prototype.throwStatement = function (throwKeyword, expression, semicolonToken) { + return new TypeScript.ThrowStatementSyntax(throwKeyword, expression, semicolonToken, true); + }; + StrictModeFactory.prototype.returnStatement = function (returnKeyword, expression, semicolonToken) { + return new TypeScript.ReturnStatementSyntax(returnKeyword, expression, semicolonToken, true); + }; + StrictModeFactory.prototype.objectCreationExpression = function (newKeyword, expression, argumentList) { + return new TypeScript.ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, true); + }; + StrictModeFactory.prototype.switchStatement = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + return new TypeScript.SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, true); + }; + StrictModeFactory.prototype.caseSwitchClause = function (caseKeyword, expression, colonToken, statements) { + return new TypeScript.CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, true); + }; + StrictModeFactory.prototype.defaultSwitchClause = function (defaultKeyword, colonToken, statements) { + return new TypeScript.DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, true); + }; + StrictModeFactory.prototype.breakStatement = function (breakKeyword, identifier, semicolonToken) { + return new TypeScript.BreakStatementSyntax(breakKeyword, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.continueStatement = function (continueKeyword, identifier, semicolonToken) { + return new TypeScript.ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.forStatement = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + return new TypeScript.ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.forInStatement = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + return new TypeScript.ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.whileStatement = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.withStatement = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.enumDeclaration = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + return new TypeScript.EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.enumElement = function (propertyName, equalsValueClause) { + return new TypeScript.EnumElementSyntax(propertyName, equalsValueClause, true); + }; + StrictModeFactory.prototype.castExpression = function (lessThanToken, type, greaterThanToken, expression) { + return new TypeScript.CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, true); + }; + StrictModeFactory.prototype.objectLiteralExpression = function (openBraceToken, propertyAssignments, closeBraceToken) { + return new TypeScript.ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, true); + }; + StrictModeFactory.prototype.simplePropertyAssignment = function (propertyName, colonToken, expression) { + return new TypeScript.SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, true); + }; + StrictModeFactory.prototype.functionPropertyAssignment = function (propertyName, callSignature, block) { + return new TypeScript.FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, true); + }; + StrictModeFactory.prototype.functionExpression = function (functionKeyword, identifier, callSignature, block) { + return new TypeScript.FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, true); + }; + StrictModeFactory.prototype.emptyStatement = function (semicolonToken) { + return new TypeScript.EmptyStatementSyntax(semicolonToken, true); + }; + StrictModeFactory.prototype.tryStatement = function (tryKeyword, block, catchClause, finallyClause) { + return new TypeScript.TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, true); + }; + StrictModeFactory.prototype.catchClause = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + return new TypeScript.CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, true); + }; + StrictModeFactory.prototype.finallyClause = function (finallyKeyword, block) { + return new TypeScript.FinallyClauseSyntax(finallyKeyword, block, true); + }; + StrictModeFactory.prototype.labeledStatement = function (identifier, colonToken, statement) { + return new TypeScript.LabeledStatementSyntax(identifier, colonToken, statement, true); + }; + StrictModeFactory.prototype.doStatement = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + return new TypeScript.DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, true); + }; + StrictModeFactory.prototype.typeOfExpression = function (typeOfKeyword, expression) { + return new TypeScript.TypeOfExpressionSyntax(typeOfKeyword, expression, true); + }; + StrictModeFactory.prototype.deleteExpression = function (deleteKeyword, expression) { + return new TypeScript.DeleteExpressionSyntax(deleteKeyword, expression, true); + }; + StrictModeFactory.prototype.voidExpression = function (voidKeyword, expression) { + return new TypeScript.VoidExpressionSyntax(voidKeyword, expression, true); + }; + StrictModeFactory.prototype.debuggerStatement = function (debuggerKeyword, semicolonToken) { + return new TypeScript.DebuggerStatementSyntax(debuggerKeyword, semicolonToken, true); + }; + return StrictModeFactory; + })(); + Syntax.StrictModeFactory = StrictModeFactory; + + Syntax.normalModeFactory = new NormalModeFactory(); + Syntax.strictModeFactory = new StrictModeFactory(); + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxFacts) { + function isDirectivePrologueElement(node) { + if (node.kind() === 149 /* ExpressionStatement */) { + var expressionStatement = node; + var expression = expressionStatement.expression; + + if (expression.kind() === 14 /* StringLiteral */) { + return true; + } + } + + return false; + } + SyntaxFacts.isDirectivePrologueElement = isDirectivePrologueElement; + + function isUseStrictDirective(node) { + var expressionStatement = node; + var stringLiteral = expressionStatement.expression; + + var text = stringLiteral.text(); + return text === '"use strict"' || text === "'use strict'"; + } + SyntaxFacts.isUseStrictDirective = isUseStrictDirective; + + function isIdentifierNameOrAnyKeyword(token) { + var tokenKind = token.tokenKind; + return tokenKind === 11 /* IdentifierName */ || SyntaxFacts.isAnyKeyword(tokenKind); + } + SyntaxFacts.isIdentifierNameOrAnyKeyword = isIdentifierNameOrAnyKeyword; + })(TypeScript.SyntaxFacts || (TypeScript.SyntaxFacts = {})); + var SyntaxFacts = TypeScript.SyntaxFacts; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var EmptySyntaxList = (function () { + function EmptySyntaxList() { + } + EmptySyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + EmptySyntaxList.prototype.isNode = function () { + return false; + }; + EmptySyntaxList.prototype.isToken = function () { + return false; + }; + EmptySyntaxList.prototype.isList = function () { + return true; + }; + EmptySyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + EmptySyntaxList.prototype.toJSON = function (key) { + return []; + }; + + EmptySyntaxList.prototype.childCount = function () { + return 0; + }; + + EmptySyntaxList.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySyntaxList.prototype.toArray = function () { + return []; + }; + + EmptySyntaxList.prototype.collectTextElements = function (elements) { + }; + + EmptySyntaxList.prototype.firstToken = function () { + return null; + }; + + EmptySyntaxList.prototype.lastToken = function () { + return null; + }; + + EmptySyntaxList.prototype.fullWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.width = function () { + return 0; + }; + + EmptySyntaxList.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySyntaxList.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySyntaxList.prototype.leadingTriviaWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.trailingTriviaWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.fullText = function () { + return ""; + }; + + EmptySyntaxList.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptySyntaxList.prototype.isIncrementallyUnusable = function () { + return false; + }; + + EmptySyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + throw TypeScript.Errors.invalidOperation(); + }; + + EmptySyntaxList.prototype.insertChildrenInto = function (array, index) { + }; + return EmptySyntaxList; + })(); + Syntax.EmptySyntaxList = EmptySyntaxList; + + Syntax.emptyList = new EmptySyntaxList(); + + var SingletonSyntaxList = (function () { + function SingletonSyntaxList(item) { + this.item = item; + } + SingletonSyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + SingletonSyntaxList.prototype.isToken = function () { + return false; + }; + SingletonSyntaxList.prototype.isNode = function () { + return false; + }; + SingletonSyntaxList.prototype.isList = function () { + return true; + }; + SingletonSyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + SingletonSyntaxList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSyntaxList.prototype.childCount = function () { + return 1; + }; + + SingletonSyntaxList.prototype.childAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSyntaxList.prototype.toArray = function () { + return [this.item]; + }; + + SingletonSyntaxList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSyntaxList.prototype.firstToken = function () { + return this.item.firstToken(); + }; + + SingletonSyntaxList.prototype.lastToken = function () { + return this.item.lastToken(); + }; + + SingletonSyntaxList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSyntaxList.prototype.width = function () { + return this.item.width(); + }; + + SingletonSyntaxList.prototype.leadingTrivia = function () { + return this.item.leadingTrivia(); + }; + + SingletonSyntaxList.prototype.trailingTrivia = function () { + return this.item.trailingTrivia(); + }; + + SingletonSyntaxList.prototype.leadingTriviaWidth = function () { + return this.item.leadingTriviaWidth(); + }; + + SingletonSyntaxList.prototype.trailingTriviaWidth = function () { + return this.item.trailingTriviaWidth(); + }; + + SingletonSyntaxList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSyntaxList.prototype.isTypeScriptSpecific = function () { + return this.item.isTypeScriptSpecific(); + }; + + SingletonSyntaxList.prototype.isIncrementallyUnusable = function () { + return this.item.isIncrementallyUnusable(); + }; + + SingletonSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + return this.item.findTokenInternal(new TypeScript.PositionedList(parent, this, fullStart), position, fullStart); + }; + + SingletonSyntaxList.prototype.insertChildrenInto = function (array, index) { + array.splice(index, 0, this.item); + }; + return SingletonSyntaxList; + })(); + + var NormalSyntaxList = (function () { + function NormalSyntaxList(nodeOrTokens) { + this._data = 0; + this.nodeOrTokens = nodeOrTokens; + } + NormalSyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + NormalSyntaxList.prototype.isNode = function () { + return false; + }; + NormalSyntaxList.prototype.isToken = function () { + return false; + }; + NormalSyntaxList.prototype.isList = function () { + return true; + }; + NormalSyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + NormalSyntaxList.prototype.toJSON = function (key) { + return this.nodeOrTokens; + }; + + NormalSyntaxList.prototype.childCount = function () { + return this.nodeOrTokens.length; + }; + + NormalSyntaxList.prototype.childAt = function (index) { + if (index < 0 || index >= this.nodeOrTokens.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.nodeOrTokens[index]; + }; + + NormalSyntaxList.prototype.toArray = function () { + return this.nodeOrTokens.slice(0); + }; + + NormalSyntaxList.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var element = this.nodeOrTokens[i]; + element.collectTextElements(elements); + } + }; + + NormalSyntaxList.prototype.firstToken = function () { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var token = this.nodeOrTokens[i].firstToken(); + if (token !== null) { + return token; + } + } + + return null; + }; + + NormalSyntaxList.prototype.lastToken = function () { + for (var i = this.nodeOrTokens.length - 1; i >= 0; i--) { + var token = this.nodeOrTokens[i].lastToken(); + if (token !== null) { + return token; + } + } + + return null; + }; + + NormalSyntaxList.prototype.fullText = function () { + var elements = new Array(); + this.collectTextElements(elements); + return elements.join(""); + }; + + NormalSyntaxList.prototype.isTypeScriptSpecific = function () { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + if (this.nodeOrTokens[i].isTypeScriptSpecific()) { + return true; + } + } + + return false; + }; + + NormalSyntaxList.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + NormalSyntaxList.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + NormalSyntaxList.prototype.width = function () { + var fullWidth = this.fullWidth(); + return fullWidth - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + NormalSyntaxList.prototype.leadingTrivia = function () { + return this.firstToken().leadingTrivia(); + }; + + NormalSyntaxList.prototype.trailingTrivia = function () { + return this.lastToken().trailingTrivia(); + }; + + NormalSyntaxList.prototype.leadingTriviaWidth = function () { + return this.firstToken().leadingTriviaWidth(); + }; + + NormalSyntaxList.prototype.trailingTriviaWidth = function () { + return this.lastToken().trailingTriviaWidth(); + }; + + NormalSyntaxList.prototype.computeData = function () { + var fullWidth = 0; + var isIncrementallyUnusable = false; + + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var node = this.nodeOrTokens[i]; + fullWidth += node.fullWidth(); + isIncrementallyUnusable = isIncrementallyUnusable || node.isIncrementallyUnusable(); + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + NormalSyntaxList.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data = this.computeData(); + } + + return this._data; + }; + + NormalSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedList(parent, this, fullStart); + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var nodeOrToken = this.nodeOrTokens[i]; + + var childWidth = nodeOrToken.fullWidth(); + if (position < childWidth) { + return nodeOrToken.findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + NormalSyntaxList.prototype.insertChildrenInto = function (array, index) { + if (index === 0) { + array.unshift.apply(array, this.nodeOrTokens); + } else { + array.splice.apply(array, [index, 0].concat(this.nodeOrTokens)); + } + }; + return NormalSyntaxList; + })(); + + function list(nodes) { + if (nodes === undefined || nodes === null || nodes.length === 0) { + return Syntax.emptyList; + } + + if (nodes.length === 1) { + var item = nodes[0]; + return new SingletonSyntaxList(item); + } + + return new NormalSyntaxList(nodes); + } + Syntax.list = list; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxNode = (function () { + function SyntaxNode(parsedInStrictMode) { + this._data = parsedInStrictMode ? 4 /* NodeParsedInStrictModeMask */ : 0; + } + SyntaxNode.prototype.isNode = function () { + return true; + }; + SyntaxNode.prototype.isToken = function () { + return false; + }; + SyntaxNode.prototype.isList = function () { + return false; + }; + SyntaxNode.prototype.isSeparatedList = function () { + return false; + }; + + SyntaxNode.prototype.kind = function () { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.childCount = function () { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.childAt = function (slot) { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.firstToken = function () { + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + if (element.fullWidth() > 0 || element.kind() === 10 /* EndOfFileToken */) { + return element.firstToken(); + } + } + } + + return null; + }; + + SyntaxNode.prototype.lastToken = function () { + for (var i = this.childCount() - 1; i >= 0; i--) { + var element = this.childAt(i); + + if (element !== null) { + if (element.fullWidth() > 0 || element.kind() === 10 /* EndOfFileToken */) { + return element.lastToken(); + } + } + } + + return null; + }; + + SyntaxNode.prototype.insertChildrenInto = function (array, index) { + for (var i = this.childCount() - 1; i >= 0; i--) { + var element = this.childAt(i); + + if (element !== null) { + if (element.isNode() || element.isToken()) { + array.splice(index, 0, element); + } else if (element.isList()) { + element.insertChildrenInto(array, index); + } else if (element.isSeparatedList()) { + element.insertChildrenInto(array, index); + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + } + }; + + SyntaxNode.prototype.leadingTrivia = function () { + var firstToken = this.firstToken(); + return firstToken ? firstToken.leadingTrivia() : TypeScript.Syntax.emptyTriviaList; + }; + + SyntaxNode.prototype.trailingTrivia = function () { + var lastToken = this.lastToken(); + return lastToken ? lastToken.trailingTrivia() : TypeScript.Syntax.emptyTriviaList; + }; + + SyntaxNode.prototype.toJSON = function (key) { + var result = { + kind: TypeScript.SyntaxKind[this.kind()], + fullWidth: this.fullWidth() + }; + + if (this.isIncrementallyUnusable()) { + result.isIncrementallyUnusable = true; + } + + if (this.parsedInStrictMode()) { + result.parsedInStrictMode = true; + } + + var thisAsIndexable = this; + for (var i = 0, n = this.childCount(); i < n; i++) { + var value = this.childAt(i); + + if (value) { + for (var name in this) { + if (value === thisAsIndexable[name]) { + result[name] = value; + break; + } + } + } + } + + return result; + }; + + SyntaxNode.prototype.accept = function (visitor) { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.fullText = function () { + var elements = []; + this.collectTextElements(elements); + return elements.join(""); + }; + + SyntaxNode.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + element.collectTextElements(elements); + } + } + }; + + SyntaxNode.prototype.replaceToken = function (token1, token2) { + if (token1 === token2) { + return this; + } + + return this.accept(new TypeScript.SyntaxTokenReplacer(token1, token2)); + }; + + SyntaxNode.prototype.withLeadingTrivia = function (trivia) { + return this.replaceToken(this.firstToken(), this.firstToken().withLeadingTrivia(trivia)); + }; + + SyntaxNode.prototype.withTrailingTrivia = function (trivia) { + return this.replaceToken(this.lastToken(), this.lastToken().withTrailingTrivia(trivia)); + }; + + SyntaxNode.prototype.hasLeadingTrivia = function () { + return this.lastToken().hasLeadingTrivia(); + }; + + SyntaxNode.prototype.hasTrailingTrivia = function () { + return this.lastToken().hasTrailingTrivia(); + }; + + SyntaxNode.prototype.isTypeScriptSpecific = function () { + return false; + }; + + SyntaxNode.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + SyntaxNode.prototype.parsedInStrictMode = function () { + return (this.data() & 4 /* NodeParsedInStrictModeMask */) !== 0; + }; + + SyntaxNode.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + SyntaxNode.prototype.computeData = function () { + var slotCount = this.childCount(); + + var fullWidth = 0; + var childWidth = 0; + + var isIncrementallyUnusable = ((this._data & 2 /* NodeIncrementallyUnusableMask */) !== 0) || slotCount === 0; + + for (var i = 0, n = slotCount; i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + childWidth = element.fullWidth(); + fullWidth += childWidth; + + if (!isIncrementallyUnusable) { + isIncrementallyUnusable = element.isIncrementallyUnusable(); + } + } + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + SyntaxNode.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data |= this.computeData(); + } + + return this._data; + }; + + SyntaxNode.prototype.findToken = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var endOfFileToken = this.tryGetEndOfFileAt(position); + if (endOfFileToken !== null) { + return endOfFileToken; + } + + if (position < 0 || position >= this.fullWidth()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var positionedToken = this.findTokenInternal(null, position, 0); + + if (includeSkippedTokens) { + return TypeScript.Syntax.findSkippedTokenInPositionedToken(positionedToken, position) || positionedToken; + } + + return positionedToken; + }; + + SyntaxNode.prototype.tryGetEndOfFileAt = function (position) { + if (this.kind() === 120 /* SourceUnit */ && position === this.fullWidth()) { + var sourceUnit = this; + return new TypeScript.PositionedToken(new TypeScript.PositionedNode(null, sourceUnit, 0), sourceUnit.endOfFileToken, sourceUnit.moduleElements.fullWidth()); + } + + return null; + }; + + SyntaxNode.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedNode(parent, this, fullStart); + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + var childWidth = element.fullWidth(); + + if (position < childWidth) { + return element.findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + } + + throw TypeScript.Errors.invalidOperation(); + }; + + SyntaxNode.prototype.findTokenOnLeft = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var positionedToken = this.findToken(position, false); + var start = positionedToken.start(); + + if (includeSkippedTokens) { + positionedToken = TypeScript.Syntax.findSkippedTokenOnLeft(positionedToken, position) || positionedToken; + } + + if (position > start) { + return positionedToken; + } + + if (positionedToken.fullStart() === 0) { + return null; + } + + return positionedToken.previousToken(includeSkippedTokens); + }; + + SyntaxNode.prototype.findCompleteTokenOnLeft = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var positionedToken = this.findToken(position, false); + + if (includeSkippedTokens) { + positionedToken = TypeScript.Syntax.findSkippedTokenOnLeft(positionedToken, position) || positionedToken; + } + + if (positionedToken.token().width() > 0 && position >= positionedToken.end()) { + return positionedToken; + } + + return positionedToken.previousToken(includeSkippedTokens); + }; + + SyntaxNode.prototype.isModuleElement = function () { + return false; + }; + + SyntaxNode.prototype.isClassElement = function () { + return false; + }; + + SyntaxNode.prototype.isTypeMember = function () { + return false; + }; + + SyntaxNode.prototype.isStatement = function () { + return false; + }; + + SyntaxNode.prototype.isExpression = function () { + return false; + }; + + SyntaxNode.prototype.isSwitchClause = function () { + return false; + }; + + SyntaxNode.prototype.structuralEquals = function (node) { + if (this === node) { + return true; + } + if (node === null) { + return false; + } + if (this.kind() !== node.kind()) { + return false; + } + + for (var i = 0, n = this.childCount(); i < n; i++) { + var element1 = this.childAt(i); + var element2 = node.childAt(i); + + if (!TypeScript.Syntax.elementStructuralEquals(element1, element2)) { + return false; + } + } + + return true; + }; + + SyntaxNode.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + SyntaxNode.prototype.leadingTriviaWidth = function () { + var firstToken = this.firstToken(); + return firstToken === null ? 0 : firstToken.leadingTriviaWidth(); + }; + + SyntaxNode.prototype.trailingTriviaWidth = function () { + var lastToken = this.lastToken(); + return lastToken === null ? 0 : lastToken.trailingTriviaWidth(); + }; + return SyntaxNode; + })(); + TypeScript.SyntaxNode = SyntaxNode; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceUnitSyntax = (function (_super) { + __extends(SourceUnitSyntax, _super); + function SourceUnitSyntax(moduleElements, endOfFileToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.moduleElements = moduleElements; + this.endOfFileToken = endOfFileToken; + } + SourceUnitSyntax.prototype.accept = function (visitor) { + return visitor.visitSourceUnit(this); + }; + + SourceUnitSyntax.prototype.kind = function () { + return 120 /* SourceUnit */; + }; + + SourceUnitSyntax.prototype.childCount = function () { + return 2; + }; + + SourceUnitSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.moduleElements; + case 1: + return this.endOfFileToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SourceUnitSyntax.prototype.update = function (moduleElements, endOfFileToken) { + if (this.moduleElements === moduleElements && this.endOfFileToken === endOfFileToken) { + return this; + } + + return new SourceUnitSyntax(moduleElements, endOfFileToken, this.parsedInStrictMode()); + }; + + SourceUnitSyntax.create = function (endOfFileToken) { + return new SourceUnitSyntax(TypeScript.Syntax.emptyList, endOfFileToken, false); + }; + + SourceUnitSyntax.create1 = function (endOfFileToken) { + return new SourceUnitSyntax(TypeScript.Syntax.emptyList, endOfFileToken, false); + }; + + SourceUnitSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SourceUnitSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SourceUnitSyntax.prototype.withModuleElements = function (moduleElements) { + return this.update(moduleElements, this.endOfFileToken); + }; + + SourceUnitSyntax.prototype.withModuleElement = function (moduleElement) { + return this.withModuleElements(TypeScript.Syntax.list([moduleElement])); + }; + + SourceUnitSyntax.prototype.withEndOfFileToken = function (endOfFileToken) { + return this.update(this.moduleElements, endOfFileToken); + }; + + SourceUnitSyntax.prototype.isTypeScriptSpecific = function () { + if (this.moduleElements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SourceUnitSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SourceUnitSyntax = SourceUnitSyntax; + + var ExternalModuleReferenceSyntax = (function (_super) { + __extends(ExternalModuleReferenceSyntax, _super); + function ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.requireKeyword = requireKeyword; + this.openParenToken = openParenToken; + this.stringLiteral = stringLiteral; + this.closeParenToken = closeParenToken; + } + ExternalModuleReferenceSyntax.prototype.accept = function (visitor) { + return visitor.visitExternalModuleReference(this); + }; + + ExternalModuleReferenceSyntax.prototype.kind = function () { + return 245 /* ExternalModuleReference */; + }; + + ExternalModuleReferenceSyntax.prototype.childCount = function () { + return 4; + }; + + ExternalModuleReferenceSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.requireKeyword; + case 1: + return this.openParenToken; + case 2: + return this.stringLiteral; + case 3: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExternalModuleReferenceSyntax.prototype.isModuleReference = function () { + return true; + }; + + ExternalModuleReferenceSyntax.prototype.update = function (requireKeyword, openParenToken, stringLiteral, closeParenToken) { + if (this.requireKeyword === requireKeyword && this.openParenToken === openParenToken && this.stringLiteral === stringLiteral && this.closeParenToken === closeParenToken) { + return this; + } + + return new ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, this.parsedInStrictMode()); + }; + + ExternalModuleReferenceSyntax.create1 = function (stringLiteral) { + return new ExternalModuleReferenceSyntax(TypeScript.Syntax.token(66 /* RequireKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), stringLiteral, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ExternalModuleReferenceSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExternalModuleReferenceSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExternalModuleReferenceSyntax.prototype.withRequireKeyword = function (requireKeyword) { + return this.update(requireKeyword, this.openParenToken, this.stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.requireKeyword, openParenToken, this.stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withStringLiteral = function (stringLiteral) { + return this.update(this.requireKeyword, this.openParenToken, stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.requireKeyword, this.openParenToken, this.stringLiteral, closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ExternalModuleReferenceSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExternalModuleReferenceSyntax = ExternalModuleReferenceSyntax; + + var ModuleNameModuleReferenceSyntax = (function (_super) { + __extends(ModuleNameModuleReferenceSyntax, _super); + function ModuleNameModuleReferenceSyntax(moduleName, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.moduleName = moduleName; + } + ModuleNameModuleReferenceSyntax.prototype.accept = function (visitor) { + return visitor.visitModuleNameModuleReference(this); + }; + + ModuleNameModuleReferenceSyntax.prototype.kind = function () { + return 246 /* ModuleNameModuleReference */; + }; + + ModuleNameModuleReferenceSyntax.prototype.childCount = function () { + return 1; + }; + + ModuleNameModuleReferenceSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.moduleName; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ModuleNameModuleReferenceSyntax.prototype.isModuleReference = function () { + return true; + }; + + ModuleNameModuleReferenceSyntax.prototype.update = function (moduleName) { + if (this.moduleName === moduleName) { + return this; + } + + return new ModuleNameModuleReferenceSyntax(moduleName, this.parsedInStrictMode()); + }; + + ModuleNameModuleReferenceSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ModuleNameModuleReferenceSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ModuleNameModuleReferenceSyntax.prototype.withModuleName = function (moduleName) { + return this.update(moduleName); + }; + + ModuleNameModuleReferenceSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ModuleNameModuleReferenceSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ModuleNameModuleReferenceSyntax = ModuleNameModuleReferenceSyntax; + + var ImportDeclarationSyntax = (function (_super) { + __extends(ImportDeclarationSyntax, _super); + function ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.importKeyword = importKeyword; + this.identifier = identifier; + this.equalsToken = equalsToken; + this.moduleReference = moduleReference; + this.semicolonToken = semicolonToken; + } + ImportDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitImportDeclaration(this); + }; + + ImportDeclarationSyntax.prototype.kind = function () { + return 133 /* ImportDeclaration */; + }; + + ImportDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + ImportDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.importKeyword; + case 2: + return this.identifier; + case 3: + return this.equalsToken; + case 4: + return this.moduleReference; + case 5: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ImportDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ImportDeclarationSyntax.prototype.update = function (modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + if (this.modifiers === modifiers && this.importKeyword === importKeyword && this.identifier === identifier && this.equalsToken === equalsToken && this.moduleReference === moduleReference && this.semicolonToken === semicolonToken) { + return this; + } + + return new ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, this.parsedInStrictMode()); + }; + + ImportDeclarationSyntax.create = function (importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new ImportDeclarationSyntax(TypeScript.Syntax.emptyList, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, false); + }; + + ImportDeclarationSyntax.create1 = function (identifier, moduleReference) { + return new ImportDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(49 /* ImportKeyword */), identifier, TypeScript.Syntax.token(107 /* EqualsToken */), moduleReference, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ImportDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ImportDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ImportDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.importKeyword, this.identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ImportDeclarationSyntax.prototype.withImportKeyword = function (importKeyword) { + return this.update(this.modifiers, importKeyword, this.identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.importKeyword, identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(this.modifiers, this.importKeyword, this.identifier, equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withModuleReference = function (moduleReference) { + return this.update(this.modifiers, this.importKeyword, this.identifier, this.equalsToken, moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.importKeyword, this.identifier, this.equalsToken, this.moduleReference, semicolonToken); + }; + + ImportDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ImportDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ImportDeclarationSyntax = ImportDeclarationSyntax; + + var ExportAssignmentSyntax = (function (_super) { + __extends(ExportAssignmentSyntax, _super); + function ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.exportKeyword = exportKeyword; + this.equalsToken = equalsToken; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + ExportAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitExportAssignment(this); + }; + + ExportAssignmentSyntax.prototype.kind = function () { + return 134 /* ExportAssignment */; + }; + + ExportAssignmentSyntax.prototype.childCount = function () { + return 4; + }; + + ExportAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.exportKeyword; + case 1: + return this.equalsToken; + case 2: + return this.identifier; + case 3: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExportAssignmentSyntax.prototype.isModuleElement = function () { + return true; + }; + + ExportAssignmentSyntax.prototype.update = function (exportKeyword, equalsToken, identifier, semicolonToken) { + if (this.exportKeyword === exportKeyword && this.equalsToken === equalsToken && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + ExportAssignmentSyntax.create1 = function (identifier) { + return new ExportAssignmentSyntax(TypeScript.Syntax.token(47 /* ExportKeyword */), TypeScript.Syntax.token(107 /* EqualsToken */), identifier, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ExportAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExportAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExportAssignmentSyntax.prototype.withExportKeyword = function (exportKeyword) { + return this.update(exportKeyword, this.equalsToken, this.identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(this.exportKeyword, equalsToken, this.identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.exportKeyword, this.equalsToken, identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.exportKeyword, this.equalsToken, this.identifier, semicolonToken); + }; + + ExportAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ExportAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExportAssignmentSyntax = ExportAssignmentSyntax; + + var ClassDeclarationSyntax = (function (_super) { + __extends(ClassDeclarationSyntax, _super); + function ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.classKeyword = classKeyword; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.openBraceToken = openBraceToken; + this.classElements = classElements; + this.closeBraceToken = closeBraceToken; + } + ClassDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitClassDeclaration(this); + }; + + ClassDeclarationSyntax.prototype.kind = function () { + return 131 /* ClassDeclaration */; + }; + + ClassDeclarationSyntax.prototype.childCount = function () { + return 8; + }; + + ClassDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.classKeyword; + case 2: + return this.identifier; + case 3: + return this.typeParameterList; + case 4: + return this.heritageClauses; + case 5: + return this.openBraceToken; + case 6: + return this.classElements; + case 7: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ClassDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ClassDeclarationSyntax.prototype.update = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + if (this.modifiers === modifiers && this.classKeyword === classKeyword && this.identifier === identifier && this.typeParameterList === typeParameterList && this.heritageClauses === heritageClauses && this.openBraceToken === openBraceToken && this.classElements === classElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, this.parsedInStrictMode()); + }; + + ClassDeclarationSyntax.create = function (classKeyword, identifier, openBraceToken, closeBraceToken) { + return new ClassDeclarationSyntax(TypeScript.Syntax.emptyList, classKeyword, identifier, null, TypeScript.Syntax.emptyList, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + ClassDeclarationSyntax.create1 = function (identifier) { + return new ClassDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(44 /* ClassKeyword */), identifier, null, TypeScript.Syntax.emptyList, TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ClassDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ClassDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ClassDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ClassDeclarationSyntax.prototype.withClassKeyword = function (classKeyword) { + return this.update(this.modifiers, classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.classKeyword, identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.modifiers, this.classKeyword, this.identifier, typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withHeritageClauses = function (heritageClauses) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withHeritageClause = function (heritageClause) { + return this.withHeritageClauses(TypeScript.Syntax.list([heritageClause])); + }; + + ClassDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withClassElements = function (classElements) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withClassElement = function (classElement) { + return this.withClassElements(TypeScript.Syntax.list([classElement])); + }; + + ClassDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ClassDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ClassDeclarationSyntax = ClassDeclarationSyntax; + + var InterfaceDeclarationSyntax = (function (_super) { + __extends(InterfaceDeclarationSyntax, _super); + function InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.interfaceKeyword = interfaceKeyword; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.body = body; + } + InterfaceDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitInterfaceDeclaration(this); + }; + + InterfaceDeclarationSyntax.prototype.kind = function () { + return 128 /* InterfaceDeclaration */; + }; + + InterfaceDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + InterfaceDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.interfaceKeyword; + case 2: + return this.identifier; + case 3: + return this.typeParameterList; + case 4: + return this.heritageClauses; + case 5: + return this.body; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + InterfaceDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + InterfaceDeclarationSyntax.prototype.update = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + if (this.modifiers === modifiers && this.interfaceKeyword === interfaceKeyword && this.identifier === identifier && this.typeParameterList === typeParameterList && this.heritageClauses === heritageClauses && this.body === body) { + return this; + } + + return new InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, this.parsedInStrictMode()); + }; + + InterfaceDeclarationSyntax.create = function (interfaceKeyword, identifier, body) { + return new InterfaceDeclarationSyntax(TypeScript.Syntax.emptyList, interfaceKeyword, identifier, null, TypeScript.Syntax.emptyList, body, false); + }; + + InterfaceDeclarationSyntax.create1 = function (identifier) { + return new InterfaceDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(52 /* InterfaceKeyword */), identifier, null, TypeScript.Syntax.emptyList, ObjectTypeSyntax.create1(), false); + }; + + InterfaceDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + InterfaceDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + InterfaceDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + InterfaceDeclarationSyntax.prototype.withInterfaceKeyword = function (interfaceKeyword) { + return this.update(this.modifiers, interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.interfaceKeyword, identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withHeritageClauses = function (heritageClauses) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withHeritageClause = function (heritageClause) { + return this.withHeritageClauses(TypeScript.Syntax.list([heritageClause])); + }; + + InterfaceDeclarationSyntax.prototype.withBody = function (body) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, body); + }; + + InterfaceDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return InterfaceDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.InterfaceDeclarationSyntax = InterfaceDeclarationSyntax; + + var HeritageClauseSyntax = (function (_super) { + __extends(HeritageClauseSyntax, _super); + function HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.extendsOrImplementsKeyword = extendsOrImplementsKeyword; + this.typeNames = typeNames; + + this._kind = kind; + } + HeritageClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitHeritageClause(this); + }; + + HeritageClauseSyntax.prototype.childCount = function () { + return 2; + }; + + HeritageClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.extendsOrImplementsKeyword; + case 1: + return this.typeNames; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + HeritageClauseSyntax.prototype.kind = function () { + return this._kind; + }; + + HeritageClauseSyntax.prototype.update = function (kind, extendsOrImplementsKeyword, typeNames) { + if (this._kind === kind && this.extendsOrImplementsKeyword === extendsOrImplementsKeyword && this.typeNames === typeNames) { + return this; + } + + return new HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, this.parsedInStrictMode()); + }; + + HeritageClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + HeritageClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + HeritageClauseSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.extendsOrImplementsKeyword, this.typeNames); + }; + + HeritageClauseSyntax.prototype.withExtendsOrImplementsKeyword = function (extendsOrImplementsKeyword) { + return this.update(this._kind, extendsOrImplementsKeyword, this.typeNames); + }; + + HeritageClauseSyntax.prototype.withTypeNames = function (typeNames) { + return this.update(this._kind, this.extendsOrImplementsKeyword, typeNames); + }; + + HeritageClauseSyntax.prototype.withTypeName = function (typeName) { + return this.withTypeNames(TypeScript.Syntax.separatedList([typeName])); + }; + + HeritageClauseSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return HeritageClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.HeritageClauseSyntax = HeritageClauseSyntax; + + var ModuleDeclarationSyntax = (function (_super) { + __extends(ModuleDeclarationSyntax, _super); + function ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.moduleKeyword = moduleKeyword; + this.name = name; + this.stringLiteral = stringLiteral; + this.openBraceToken = openBraceToken; + this.moduleElements = moduleElements; + this.closeBraceToken = closeBraceToken; + } + ModuleDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitModuleDeclaration(this); + }; + + ModuleDeclarationSyntax.prototype.kind = function () { + return 130 /* ModuleDeclaration */; + }; + + ModuleDeclarationSyntax.prototype.childCount = function () { + return 7; + }; + + ModuleDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.moduleKeyword; + case 2: + return this.name; + case 3: + return this.stringLiteral; + case 4: + return this.openBraceToken; + case 5: + return this.moduleElements; + case 6: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ModuleDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ModuleDeclarationSyntax.prototype.update = function (modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + if (this.modifiers === modifiers && this.moduleKeyword === moduleKeyword && this.name === name && this.stringLiteral === stringLiteral && this.openBraceToken === openBraceToken && this.moduleElements === moduleElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, this.parsedInStrictMode()); + }; + + ModuleDeclarationSyntax.create = function (moduleKeyword, openBraceToken, closeBraceToken) { + return new ModuleDeclarationSyntax(TypeScript.Syntax.emptyList, moduleKeyword, null, null, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + ModuleDeclarationSyntax.create1 = function () { + return new ModuleDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(65 /* ModuleKeyword */), null, null, TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ModuleDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ModuleDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ModuleDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ModuleDeclarationSyntax.prototype.withModuleKeyword = function (moduleKeyword) { + return this.update(this.modifiers, moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withName = function (name) { + return this.update(this.modifiers, this.moduleKeyword, name, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withStringLiteral = function (stringLiteral) { + return this.update(this.modifiers, this.moduleKeyword, this.name, stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.moduleKeyword, this.name, this.stringLiteral, openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModuleElements = function (moduleElements) { + return this.update(this.modifiers, this.moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModuleElement = function (moduleElement) { + return this.withModuleElements(TypeScript.Syntax.list([moduleElement])); + }; + + ModuleDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, this.moduleElements, closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ModuleDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ModuleDeclarationSyntax = ModuleDeclarationSyntax; + + var FunctionDeclarationSyntax = (function (_super) { + __extends(FunctionDeclarationSyntax, _super); + function FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.functionKeyword = functionKeyword; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + FunctionDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionDeclaration(this); + }; + + FunctionDeclarationSyntax.prototype.kind = function () { + return 129 /* FunctionDeclaration */; + }; + + FunctionDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + FunctionDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.functionKeyword; + case 2: + return this.identifier; + case 3: + return this.callSignature; + case 4: + return this.block; + case 5: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionDeclarationSyntax.prototype.isStatement = function () { + return true; + }; + + FunctionDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + FunctionDeclarationSyntax.prototype.update = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.functionKeyword === functionKeyword && this.identifier === identifier && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + FunctionDeclarationSyntax.create = function (functionKeyword, identifier, callSignature) { + return new FunctionDeclarationSyntax(TypeScript.Syntax.emptyList, functionKeyword, identifier, callSignature, null, null, false); + }; + + FunctionDeclarationSyntax.create1 = function (identifier) { + return new FunctionDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(27 /* FunctionKeyword */), identifier, CallSignatureSyntax.create1(), null, null, false); + }; + + FunctionDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.functionKeyword, this.identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + FunctionDeclarationSyntax.prototype.withFunctionKeyword = function (functionKeyword) { + return this.update(this.modifiers, functionKeyword, this.identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.functionKeyword, identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, this.callSignature, block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, this.callSignature, this.block, semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.childCount() > 0) { + return true; + } + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block !== null && this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionDeclarationSyntax = FunctionDeclarationSyntax; + + var VariableStatementSyntax = (function (_super) { + __extends(VariableStatementSyntax, _super); + function VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.variableDeclaration = variableDeclaration; + this.semicolonToken = semicolonToken; + } + VariableStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableStatement(this); + }; + + VariableStatementSyntax.prototype.kind = function () { + return 148 /* VariableStatement */; + }; + + VariableStatementSyntax.prototype.childCount = function () { + return 3; + }; + + VariableStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.variableDeclaration; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableStatementSyntax.prototype.isStatement = function () { + return true; + }; + + VariableStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + VariableStatementSyntax.prototype.update = function (modifiers, variableDeclaration, semicolonToken) { + if (this.modifiers === modifiers && this.variableDeclaration === variableDeclaration && this.semicolonToken === semicolonToken) { + return this; + } + + return new VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, this.parsedInStrictMode()); + }; + + VariableStatementSyntax.create = function (variableDeclaration, semicolonToken) { + return new VariableStatementSyntax(TypeScript.Syntax.emptyList, variableDeclaration, semicolonToken, false); + }; + + VariableStatementSyntax.create1 = function (variableDeclaration) { + return new VariableStatementSyntax(TypeScript.Syntax.emptyList, variableDeclaration, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + VariableStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableStatementSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.variableDeclaration, this.semicolonToken); + }; + + VariableStatementSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + VariableStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.modifiers, variableDeclaration, this.semicolonToken); + }; + + VariableStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.variableDeclaration, semicolonToken); + }; + + VariableStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.childCount() > 0) { + return true; + } + if (this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableStatementSyntax = VariableStatementSyntax; + + var VariableDeclarationSyntax = (function (_super) { + __extends(VariableDeclarationSyntax, _super); + function VariableDeclarationSyntax(varKeyword, variableDeclarators, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.varKeyword = varKeyword; + this.variableDeclarators = variableDeclarators; + } + VariableDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableDeclaration(this); + }; + + VariableDeclarationSyntax.prototype.kind = function () { + return 224 /* VariableDeclaration */; + }; + + VariableDeclarationSyntax.prototype.childCount = function () { + return 2; + }; + + VariableDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.varKeyword; + case 1: + return this.variableDeclarators; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableDeclarationSyntax.prototype.update = function (varKeyword, variableDeclarators) { + if (this.varKeyword === varKeyword && this.variableDeclarators === variableDeclarators) { + return this; + } + + return new VariableDeclarationSyntax(varKeyword, variableDeclarators, this.parsedInStrictMode()); + }; + + VariableDeclarationSyntax.create1 = function (variableDeclarators) { + return new VariableDeclarationSyntax(TypeScript.Syntax.token(40 /* VarKeyword */), variableDeclarators, false); + }; + + VariableDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableDeclarationSyntax.prototype.withVarKeyword = function (varKeyword) { + return this.update(varKeyword, this.variableDeclarators); + }; + + VariableDeclarationSyntax.prototype.withVariableDeclarators = function (variableDeclarators) { + return this.update(this.varKeyword, variableDeclarators); + }; + + VariableDeclarationSyntax.prototype.withVariableDeclarator = function (variableDeclarator) { + return this.withVariableDeclarators(TypeScript.Syntax.separatedList([variableDeclarator])); + }; + + VariableDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclarators.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableDeclarationSyntax = VariableDeclarationSyntax; + + var VariableDeclaratorSyntax = (function (_super) { + __extends(VariableDeclaratorSyntax, _super); + function VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + } + VariableDeclaratorSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableDeclarator(this); + }; + + VariableDeclaratorSyntax.prototype.kind = function () { + return 225 /* VariableDeclarator */; + }; + + VariableDeclaratorSyntax.prototype.childCount = function () { + return 3; + }; + + VariableDeclaratorSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.typeAnnotation; + case 2: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableDeclaratorSyntax.prototype.update = function (propertyName, typeAnnotation, equalsValueClause) { + if (this.propertyName === propertyName && this.typeAnnotation === typeAnnotation && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, this.parsedInStrictMode()); + }; + + VariableDeclaratorSyntax.create = function (propertyName) { + return new VariableDeclaratorSyntax(propertyName, null, null, false); + }; + + VariableDeclaratorSyntax.create1 = function (propertyName) { + return new VariableDeclaratorSyntax(propertyName, null, null, false); + }; + + VariableDeclaratorSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableDeclaratorSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableDeclaratorSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.typeAnnotation, this.equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.propertyName, typeAnnotation, this.equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.propertyName, this.typeAnnotation, equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeAnnotation !== null) { + return true; + } + if (this.equalsValueClause !== null && this.equalsValueClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableDeclaratorSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableDeclaratorSyntax = VariableDeclaratorSyntax; + + var EqualsValueClauseSyntax = (function (_super) { + __extends(EqualsValueClauseSyntax, _super); + function EqualsValueClauseSyntax(equalsToken, value, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.equalsToken = equalsToken; + this.value = value; + } + EqualsValueClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitEqualsValueClause(this); + }; + + EqualsValueClauseSyntax.prototype.kind = function () { + return 232 /* EqualsValueClause */; + }; + + EqualsValueClauseSyntax.prototype.childCount = function () { + return 2; + }; + + EqualsValueClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.equalsToken; + case 1: + return this.value; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EqualsValueClauseSyntax.prototype.update = function (equalsToken, value) { + if (this.equalsToken === equalsToken && this.value === value) { + return this; + } + + return new EqualsValueClauseSyntax(equalsToken, value, this.parsedInStrictMode()); + }; + + EqualsValueClauseSyntax.create1 = function (value) { + return new EqualsValueClauseSyntax(TypeScript.Syntax.token(107 /* EqualsToken */), value, false); + }; + + EqualsValueClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EqualsValueClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EqualsValueClauseSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(equalsToken, this.value); + }; + + EqualsValueClauseSyntax.prototype.withValue = function (value) { + return this.update(this.equalsToken, value); + }; + + EqualsValueClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.value.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return EqualsValueClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EqualsValueClauseSyntax = EqualsValueClauseSyntax; + + var PrefixUnaryExpressionSyntax = (function (_super) { + __extends(PrefixUnaryExpressionSyntax, _super); + function PrefixUnaryExpressionSyntax(kind, operatorToken, operand, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.operatorToken = operatorToken; + this.operand = operand; + + this._kind = kind; + } + PrefixUnaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitPrefixUnaryExpression(this); + }; + + PrefixUnaryExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + PrefixUnaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.operatorToken; + case 1: + return this.operand; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PrefixUnaryExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + PrefixUnaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + PrefixUnaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + PrefixUnaryExpressionSyntax.prototype.update = function (kind, operatorToken, operand) { + if (this._kind === kind && this.operatorToken === operatorToken && this.operand === operand) { + return this; + } + + return new PrefixUnaryExpressionSyntax(kind, operatorToken, operand, this.parsedInStrictMode()); + }; + + PrefixUnaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PrefixUnaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PrefixUnaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.operatorToken, this.operand); + }; + + PrefixUnaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, operatorToken, this.operand); + }; + + PrefixUnaryExpressionSyntax.prototype.withOperand = function (operand) { + return this.update(this._kind, this.operatorToken, operand); + }; + + PrefixUnaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.operand.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return PrefixUnaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PrefixUnaryExpressionSyntax = PrefixUnaryExpressionSyntax; + + var ArrayLiteralExpressionSyntax = (function (_super) { + __extends(ArrayLiteralExpressionSyntax, _super); + function ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBracketToken = openBracketToken; + this.expressions = expressions; + this.closeBracketToken = closeBracketToken; + } + ArrayLiteralExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitArrayLiteralExpression(this); + }; + + ArrayLiteralExpressionSyntax.prototype.kind = function () { + return 214 /* ArrayLiteralExpression */; + }; + + ArrayLiteralExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ArrayLiteralExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBracketToken; + case 1: + return this.expressions; + case 2: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArrayLiteralExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.update = function (openBracketToken, expressions, closeBracketToken) { + if (this.openBracketToken === openBracketToken && this.expressions === expressions && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, this.parsedInStrictMode()); + }; + + ArrayLiteralExpressionSyntax.create = function (openBracketToken, closeBracketToken) { + return new ArrayLiteralExpressionSyntax(openBracketToken, TypeScript.Syntax.emptySeparatedList, closeBracketToken, false); + }; + + ArrayLiteralExpressionSyntax.create1 = function () { + return new ArrayLiteralExpressionSyntax(TypeScript.Syntax.token(74 /* OpenBracketToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(75 /* CloseBracketToken */), false); + }; + + ArrayLiteralExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArrayLiteralExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArrayLiteralExpressionSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(openBracketToken, this.expressions, this.closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.withExpressions = function (expressions) { + return this.update(this.openBracketToken, expressions, this.closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.withExpression = function (expression) { + return this.withExpressions(TypeScript.Syntax.separatedList([expression])); + }; + + ArrayLiteralExpressionSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.openBracketToken, this.expressions, closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expressions.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ArrayLiteralExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArrayLiteralExpressionSyntax = ArrayLiteralExpressionSyntax; + + var OmittedExpressionSyntax = (function (_super) { + __extends(OmittedExpressionSyntax, _super); + function OmittedExpressionSyntax(parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + } + OmittedExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitOmittedExpression(this); + }; + + OmittedExpressionSyntax.prototype.kind = function () { + return 223 /* OmittedExpression */; + }; + + OmittedExpressionSyntax.prototype.childCount = function () { + return 0; + }; + + OmittedExpressionSyntax.prototype.childAt = function (slot) { + throw TypeScript.Errors.invalidOperation(); + }; + + OmittedExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + OmittedExpressionSyntax.prototype.update = function () { + return this; + }; + + OmittedExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + OmittedExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + OmittedExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return OmittedExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.OmittedExpressionSyntax = OmittedExpressionSyntax; + + var ParenthesizedExpressionSyntax = (function (_super) { + __extends(ParenthesizedExpressionSyntax, _super); + function ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openParenToken = openParenToken; + this.expression = expression; + this.closeParenToken = closeParenToken; + } + ParenthesizedExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitParenthesizedExpression(this); + }; + + ParenthesizedExpressionSyntax.prototype.kind = function () { + return 217 /* ParenthesizedExpression */; + }; + + ParenthesizedExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ParenthesizedExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openParenToken; + case 1: + return this.expression; + case 2: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParenthesizedExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.update = function (openParenToken, expression, closeParenToken) { + if (this.openParenToken === openParenToken && this.expression === expression && this.closeParenToken === closeParenToken) { + return this; + } + + return new ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, this.parsedInStrictMode()); + }; + + ParenthesizedExpressionSyntax.create1 = function (expression) { + return new ParenthesizedExpressionSyntax(TypeScript.Syntax.token(72 /* OpenParenToken */), expression, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ParenthesizedExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParenthesizedExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParenthesizedExpressionSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(openParenToken, this.expression, this.closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.openParenToken, expression, this.closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.openParenToken, this.expression, closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ParenthesizedExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParenthesizedExpressionSyntax = ParenthesizedExpressionSyntax; + + var SimpleArrowFunctionExpressionSyntax = (function (_super) { + __extends(SimpleArrowFunctionExpressionSyntax, _super); + function SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.block = block; + this.expression = expression; + } + SimpleArrowFunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitSimpleArrowFunctionExpression(this); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.kind = function () { + return 219 /* SimpleArrowFunctionExpression */; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.equalsGreaterThanToken; + case 2: + return this.block; + case 3: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isArrowFunctionExpression = function () { + return true; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.update = function (identifier, equalsGreaterThanToken, block, expression) { + if (this.identifier === identifier && this.equalsGreaterThanToken === equalsGreaterThanToken && this.block === block && this.expression === expression) { + return this; + } + + return new SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, this.parsedInStrictMode()); + }; + + SimpleArrowFunctionExpressionSyntax.create = function (identifier, equalsGreaterThanToken) { + return new SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, null, null, false); + }; + + SimpleArrowFunctionExpressionSyntax.create1 = function (identifier) { + return new SimpleArrowFunctionExpressionSyntax(identifier, TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), null, null, false); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.equalsGreaterThanToken, this.block, this.expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.identifier, equalsGreaterThanToken, this.block, this.expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withBlock = function (block) { + return this.update(this.identifier, this.equalsGreaterThanToken, block, this.expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.identifier, this.equalsGreaterThanToken, this.block, expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return SimpleArrowFunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SimpleArrowFunctionExpressionSyntax = SimpleArrowFunctionExpressionSyntax; + + var ParenthesizedArrowFunctionExpressionSyntax = (function (_super) { + __extends(ParenthesizedArrowFunctionExpressionSyntax, _super); + function ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.callSignature = callSignature; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.block = block; + this.expression = expression; + } + ParenthesizedArrowFunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitParenthesizedArrowFunctionExpression(this); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.kind = function () { + return 218 /* ParenthesizedArrowFunctionExpression */; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.callSignature; + case 1: + return this.equalsGreaterThanToken; + case 2: + return this.block; + case 3: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isArrowFunctionExpression = function () { + return true; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.update = function (callSignature, equalsGreaterThanToken, block, expression) { + if (this.callSignature === callSignature && this.equalsGreaterThanToken === equalsGreaterThanToken && this.block === block && this.expression === expression) { + return this; + } + + return new ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, this.parsedInStrictMode()); + }; + + ParenthesizedArrowFunctionExpressionSyntax.create = function (callSignature, equalsGreaterThanToken) { + return new ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, null, null, false); + }; + + ParenthesizedArrowFunctionExpressionSyntax.create1 = function () { + return new ParenthesizedArrowFunctionExpressionSyntax(CallSignatureSyntax.create1(), TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), null, null, false); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(callSignature, this.equalsGreaterThanToken, this.block, this.expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.callSignature, equalsGreaterThanToken, this.block, this.expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withBlock = function (block) { + return this.update(this.callSignature, this.equalsGreaterThanToken, block, this.expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.callSignature, this.equalsGreaterThanToken, this.block, expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ParenthesizedArrowFunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParenthesizedArrowFunctionExpressionSyntax = ParenthesizedArrowFunctionExpressionSyntax; + + var QualifiedNameSyntax = (function (_super) { + __extends(QualifiedNameSyntax, _super); + function QualifiedNameSyntax(left, dotToken, right, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.left = left; + this.dotToken = dotToken; + this.right = right; + } + QualifiedNameSyntax.prototype.accept = function (visitor) { + return visitor.visitQualifiedName(this); + }; + + QualifiedNameSyntax.prototype.kind = function () { + return 121 /* QualifiedName */; + }; + + QualifiedNameSyntax.prototype.childCount = function () { + return 3; + }; + + QualifiedNameSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.left; + case 1: + return this.dotToken; + case 2: + return this.right; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + QualifiedNameSyntax.prototype.isName = function () { + return true; + }; + + QualifiedNameSyntax.prototype.isType = function () { + return true; + }; + + QualifiedNameSyntax.prototype.update = function (left, dotToken, right) { + if (this.left === left && this.dotToken === dotToken && this.right === right) { + return this; + } + + return new QualifiedNameSyntax(left, dotToken, right, this.parsedInStrictMode()); + }; + + QualifiedNameSyntax.create1 = function (left, right) { + return new QualifiedNameSyntax(left, TypeScript.Syntax.token(76 /* DotToken */), right, false); + }; + + QualifiedNameSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + QualifiedNameSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + QualifiedNameSyntax.prototype.withLeft = function (left) { + return this.update(left, this.dotToken, this.right); + }; + + QualifiedNameSyntax.prototype.withDotToken = function (dotToken) { + return this.update(this.left, dotToken, this.right); + }; + + QualifiedNameSyntax.prototype.withRight = function (right) { + return this.update(this.left, this.dotToken, right); + }; + + QualifiedNameSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return QualifiedNameSyntax; + })(TypeScript.SyntaxNode); + TypeScript.QualifiedNameSyntax = QualifiedNameSyntax; + + var TypeArgumentListSyntax = (function (_super) { + __extends(TypeArgumentListSyntax, _super); + function TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.typeArguments = typeArguments; + this.greaterThanToken = greaterThanToken; + } + TypeArgumentListSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeArgumentList(this); + }; + + TypeArgumentListSyntax.prototype.kind = function () { + return 228 /* TypeArgumentList */; + }; + + TypeArgumentListSyntax.prototype.childCount = function () { + return 3; + }; + + TypeArgumentListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.typeArguments; + case 2: + return this.greaterThanToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeArgumentListSyntax.prototype.update = function (lessThanToken, typeArguments, greaterThanToken) { + if (this.lessThanToken === lessThanToken && this.typeArguments === typeArguments && this.greaterThanToken === greaterThanToken) { + return this; + } + + return new TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, this.parsedInStrictMode()); + }; + + TypeArgumentListSyntax.create = function (lessThanToken, greaterThanToken) { + return new TypeArgumentListSyntax(lessThanToken, TypeScript.Syntax.emptySeparatedList, greaterThanToken, false); + }; + + TypeArgumentListSyntax.create1 = function () { + return new TypeArgumentListSyntax(TypeScript.Syntax.token(80 /* LessThanToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(81 /* GreaterThanToken */), false); + }; + + TypeArgumentListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeArgumentListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeArgumentListSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.typeArguments, this.greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.withTypeArguments = function (typeArguments) { + return this.update(this.lessThanToken, typeArguments, this.greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.withTypeArgument = function (typeArgument) { + return this.withTypeArguments(TypeScript.Syntax.separatedList([typeArgument])); + }; + + TypeArgumentListSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.typeArguments, greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeArgumentListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeArgumentListSyntax = TypeArgumentListSyntax; + + var ConstructorTypeSyntax = (function (_super) { + __extends(ConstructorTypeSyntax, _super); + function ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.type = type; + } + ConstructorTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructorType(this); + }; + + ConstructorTypeSyntax.prototype.kind = function () { + return 125 /* ConstructorType */; + }; + + ConstructorTypeSyntax.prototype.childCount = function () { + return 5; + }; + + ConstructorTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.typeParameterList; + case 2: + return this.parameterList; + case 3: + return this.equalsGreaterThanToken; + case 4: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructorTypeSyntax.prototype.isType = function () { + return true; + }; + + ConstructorTypeSyntax.prototype.update = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + if (this.newKeyword === newKeyword && this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.equalsGreaterThanToken === equalsGreaterThanToken && this.type === type) { + return this; + } + + return new ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, this.parsedInStrictMode()); + }; + + ConstructorTypeSyntax.create = function (newKeyword, parameterList, equalsGreaterThanToken, type) { + return new ConstructorTypeSyntax(newKeyword, null, parameterList, equalsGreaterThanToken, type, false); + }; + + ConstructorTypeSyntax.create1 = function (type) { + return new ConstructorTypeSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), null, ParameterListSyntax.create1(), TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), type, false); + }; + + ConstructorTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructorTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructorTypeSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.newKeyword, typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.newKeyword, this.typeParameterList, parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.newKeyword, this.typeParameterList, this.parameterList, equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withType = function (type) { + return this.update(this.newKeyword, this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, type); + }; + + ConstructorTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructorTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructorTypeSyntax = ConstructorTypeSyntax; + + var FunctionTypeSyntax = (function (_super) { + __extends(FunctionTypeSyntax, _super); + function FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.type = type; + } + FunctionTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionType(this); + }; + + FunctionTypeSyntax.prototype.kind = function () { + return 123 /* FunctionType */; + }; + + FunctionTypeSyntax.prototype.childCount = function () { + return 4; + }; + + FunctionTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeParameterList; + case 1: + return this.parameterList; + case 2: + return this.equalsGreaterThanToken; + case 3: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionTypeSyntax.prototype.isType = function () { + return true; + }; + + FunctionTypeSyntax.prototype.update = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + if (this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.equalsGreaterThanToken === equalsGreaterThanToken && this.type === type) { + return this; + } + + return new FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, this.parsedInStrictMode()); + }; + + FunctionTypeSyntax.create = function (parameterList, equalsGreaterThanToken, type) { + return new FunctionTypeSyntax(null, parameterList, equalsGreaterThanToken, type, false); + }; + + FunctionTypeSyntax.create1 = function (type) { + return new FunctionTypeSyntax(null, ParameterListSyntax.create1(), TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), type, false); + }; + + FunctionTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionTypeSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.typeParameterList, parameterList, this.equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.typeParameterList, this.parameterList, equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withType = function (type) { + return this.update(this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, type); + }; + + FunctionTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return FunctionTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionTypeSyntax = FunctionTypeSyntax; + + var ObjectTypeSyntax = (function (_super) { + __extends(ObjectTypeSyntax, _super); + function ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.typeMembers = typeMembers; + this.closeBraceToken = closeBraceToken; + } + ObjectTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectType(this); + }; + + ObjectTypeSyntax.prototype.kind = function () { + return 122 /* ObjectType */; + }; + + ObjectTypeSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.typeMembers; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectTypeSyntax.prototype.isType = function () { + return true; + }; + + ObjectTypeSyntax.prototype.update = function (openBraceToken, typeMembers, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.typeMembers === typeMembers && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, this.parsedInStrictMode()); + }; + + ObjectTypeSyntax.create = function (openBraceToken, closeBraceToken) { + return new ObjectTypeSyntax(openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + ObjectTypeSyntax.create1 = function () { + return new ObjectTypeSyntax(TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ObjectTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectTypeSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.typeMembers, this.closeBraceToken); + }; + + ObjectTypeSyntax.prototype.withTypeMembers = function (typeMembers) { + return this.update(this.openBraceToken, typeMembers, this.closeBraceToken); + }; + + ObjectTypeSyntax.prototype.withTypeMember = function (typeMember) { + return this.withTypeMembers(TypeScript.Syntax.separatedList([typeMember])); + }; + + ObjectTypeSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.typeMembers, closeBraceToken); + }; + + ObjectTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ObjectTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectTypeSyntax = ObjectTypeSyntax; + + var ArrayTypeSyntax = (function (_super) { + __extends(ArrayTypeSyntax, _super); + function ArrayTypeSyntax(type, openBracketToken, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.type = type; + this.openBracketToken = openBracketToken; + this.closeBracketToken = closeBracketToken; + } + ArrayTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitArrayType(this); + }; + + ArrayTypeSyntax.prototype.kind = function () { + return 124 /* ArrayType */; + }; + + ArrayTypeSyntax.prototype.childCount = function () { + return 3; + }; + + ArrayTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.type; + case 1: + return this.openBracketToken; + case 2: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArrayTypeSyntax.prototype.isType = function () { + return true; + }; + + ArrayTypeSyntax.prototype.update = function (type, openBracketToken, closeBracketToken) { + if (this.type === type && this.openBracketToken === openBracketToken && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ArrayTypeSyntax(type, openBracketToken, closeBracketToken, this.parsedInStrictMode()); + }; + + ArrayTypeSyntax.create1 = function (type) { + return new ArrayTypeSyntax(type, TypeScript.Syntax.token(74 /* OpenBracketToken */), TypeScript.Syntax.token(75 /* CloseBracketToken */), false); + }; + + ArrayTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArrayTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArrayTypeSyntax.prototype.withType = function (type) { + return this.update(type, this.openBracketToken, this.closeBracketToken); + }; + + ArrayTypeSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(this.type, openBracketToken, this.closeBracketToken); + }; + + ArrayTypeSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.type, this.openBracketToken, closeBracketToken); + }; + + ArrayTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ArrayTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArrayTypeSyntax = ArrayTypeSyntax; + + var GenericTypeSyntax = (function (_super) { + __extends(GenericTypeSyntax, _super); + function GenericTypeSyntax(name, typeArgumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.name = name; + this.typeArgumentList = typeArgumentList; + } + GenericTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitGenericType(this); + }; + + GenericTypeSyntax.prototype.kind = function () { + return 126 /* GenericType */; + }; + + GenericTypeSyntax.prototype.childCount = function () { + return 2; + }; + + GenericTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.name; + case 1: + return this.typeArgumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + GenericTypeSyntax.prototype.isType = function () { + return true; + }; + + GenericTypeSyntax.prototype.update = function (name, typeArgumentList) { + if (this.name === name && this.typeArgumentList === typeArgumentList) { + return this; + } + + return new GenericTypeSyntax(name, typeArgumentList, this.parsedInStrictMode()); + }; + + GenericTypeSyntax.create1 = function (name) { + return new GenericTypeSyntax(name, TypeArgumentListSyntax.create1(), false); + }; + + GenericTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + GenericTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + GenericTypeSyntax.prototype.withName = function (name) { + return this.update(name, this.typeArgumentList); + }; + + GenericTypeSyntax.prototype.withTypeArgumentList = function (typeArgumentList) { + return this.update(this.name, typeArgumentList); + }; + + GenericTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return GenericTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.GenericTypeSyntax = GenericTypeSyntax; + + var TypeQuerySyntax = (function (_super) { + __extends(TypeQuerySyntax, _super); + function TypeQuerySyntax(typeOfKeyword, name, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeOfKeyword = typeOfKeyword; + this.name = name; + } + TypeQuerySyntax.prototype.accept = function (visitor) { + return visitor.visitTypeQuery(this); + }; + + TypeQuerySyntax.prototype.kind = function () { + return 127 /* TypeQuery */; + }; + + TypeQuerySyntax.prototype.childCount = function () { + return 2; + }; + + TypeQuerySyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeOfKeyword; + case 1: + return this.name; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeQuerySyntax.prototype.isType = function () { + return true; + }; + + TypeQuerySyntax.prototype.update = function (typeOfKeyword, name) { + if (this.typeOfKeyword === typeOfKeyword && this.name === name) { + return this; + } + + return new TypeQuerySyntax(typeOfKeyword, name, this.parsedInStrictMode()); + }; + + TypeQuerySyntax.create1 = function (name) { + return new TypeQuerySyntax(TypeScript.Syntax.token(39 /* TypeOfKeyword */), name, false); + }; + + TypeQuerySyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeQuerySyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeQuerySyntax.prototype.withTypeOfKeyword = function (typeOfKeyword) { + return this.update(typeOfKeyword, this.name); + }; + + TypeQuerySyntax.prototype.withName = function (name) { + return this.update(this.typeOfKeyword, name); + }; + + TypeQuerySyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeQuerySyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeQuerySyntax = TypeQuerySyntax; + + var TypeAnnotationSyntax = (function (_super) { + __extends(TypeAnnotationSyntax, _super); + function TypeAnnotationSyntax(colonToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.colonToken = colonToken; + this.type = type; + } + TypeAnnotationSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeAnnotation(this); + }; + + TypeAnnotationSyntax.prototype.kind = function () { + return 244 /* TypeAnnotation */; + }; + + TypeAnnotationSyntax.prototype.childCount = function () { + return 2; + }; + + TypeAnnotationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.colonToken; + case 1: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeAnnotationSyntax.prototype.update = function (colonToken, type) { + if (this.colonToken === colonToken && this.type === type) { + return this; + } + + return new TypeAnnotationSyntax(colonToken, type, this.parsedInStrictMode()); + }; + + TypeAnnotationSyntax.create1 = function (type) { + return new TypeAnnotationSyntax(TypeScript.Syntax.token(106 /* ColonToken */), type, false); + }; + + TypeAnnotationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeAnnotationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeAnnotationSyntax.prototype.withColonToken = function (colonToken) { + return this.update(colonToken, this.type); + }; + + TypeAnnotationSyntax.prototype.withType = function (type) { + return this.update(this.colonToken, type); + }; + + TypeAnnotationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeAnnotationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeAnnotationSyntax = TypeAnnotationSyntax; + + var BlockSyntax = (function (_super) { + __extends(BlockSyntax, _super); + function BlockSyntax(openBraceToken, statements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.statements = statements; + this.closeBraceToken = closeBraceToken; + } + BlockSyntax.prototype.accept = function (visitor) { + return visitor.visitBlock(this); + }; + + BlockSyntax.prototype.kind = function () { + return 146 /* Block */; + }; + + BlockSyntax.prototype.childCount = function () { + return 3; + }; + + BlockSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.statements; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BlockSyntax.prototype.isStatement = function () { + return true; + }; + + BlockSyntax.prototype.isModuleElement = function () { + return true; + }; + + BlockSyntax.prototype.update = function (openBraceToken, statements, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.statements === statements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new BlockSyntax(openBraceToken, statements, closeBraceToken, this.parsedInStrictMode()); + }; + + BlockSyntax.create = function (openBraceToken, closeBraceToken) { + return new BlockSyntax(openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + BlockSyntax.create1 = function () { + return new BlockSyntax(TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + BlockSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BlockSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BlockSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.statements, this.closeBraceToken); + }; + + BlockSyntax.prototype.withStatements = function (statements) { + return this.update(this.openBraceToken, statements, this.closeBraceToken); + }; + + BlockSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + BlockSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.statements, closeBraceToken); + }; + + BlockSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return BlockSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BlockSyntax = BlockSyntax; + + var ParameterSyntax = (function (_super) { + __extends(ParameterSyntax, _super); + function ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.dotDotDotToken = dotDotDotToken; + this.modifiers = modifiers; + this.identifier = identifier; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + } + ParameterSyntax.prototype.accept = function (visitor) { + return visitor.visitParameter(this); + }; + + ParameterSyntax.prototype.kind = function () { + return 242 /* Parameter */; + }; + + ParameterSyntax.prototype.childCount = function () { + return 6; + }; + + ParameterSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.dotDotDotToken; + case 1: + return this.modifiers; + case 2: + return this.identifier; + case 3: + return this.questionToken; + case 4: + return this.typeAnnotation; + case 5: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParameterSyntax.prototype.update = function (dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + if (this.dotDotDotToken === dotDotDotToken && this.modifiers === modifiers && this.identifier === identifier && this.questionToken === questionToken && this.typeAnnotation === typeAnnotation && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, this.parsedInStrictMode()); + }; + + ParameterSyntax.create = function (identifier) { + return new ParameterSyntax(null, TypeScript.Syntax.emptyList, identifier, null, null, null, false); + }; + + ParameterSyntax.create1 = function (identifier) { + return new ParameterSyntax(null, TypeScript.Syntax.emptyList, identifier, null, null, null, false); + }; + + ParameterSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParameterSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParameterSyntax.prototype.withDotDotDotToken = function (dotDotDotToken) { + return this.update(dotDotDotToken, this.modifiers, this.identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withModifiers = function (modifiers) { + return this.update(this.dotDotDotToken, modifiers, this.identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ParameterSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.dotDotDotToken, this.modifiers, identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.dotDotDotToken, this.modifiers, this.identifier, questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.dotDotDotToken, this.modifiers, this.identifier, this.questionToken, typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.dotDotDotToken, this.modifiers, this.identifier, this.questionToken, this.typeAnnotation, equalsValueClause); + }; + + ParameterSyntax.prototype.isTypeScriptSpecific = function () { + if (this.dotDotDotToken !== null) { + return true; + } + if (this.modifiers.isTypeScriptSpecific()) { + return true; + } + if (this.questionToken !== null) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + if (this.equalsValueClause !== null) { + return true; + } + return false; + }; + return ParameterSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParameterSyntax = ParameterSyntax; + + var MemberAccessExpressionSyntax = (function (_super) { + __extends(MemberAccessExpressionSyntax, _super); + function MemberAccessExpressionSyntax(expression, dotToken, name, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.dotToken = dotToken; + this.name = name; + } + MemberAccessExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberAccessExpression(this); + }; + + MemberAccessExpressionSyntax.prototype.kind = function () { + return 212 /* MemberAccessExpression */; + }; + + MemberAccessExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + MemberAccessExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.dotToken; + case 2: + return this.name; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberAccessExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.update = function (expression, dotToken, name) { + if (this.expression === expression && this.dotToken === dotToken && this.name === name) { + return this; + } + + return new MemberAccessExpressionSyntax(expression, dotToken, name, this.parsedInStrictMode()); + }; + + MemberAccessExpressionSyntax.create1 = function (expression, name) { + return new MemberAccessExpressionSyntax(expression, TypeScript.Syntax.token(76 /* DotToken */), name, false); + }; + + MemberAccessExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberAccessExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberAccessExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.dotToken, this.name); + }; + + MemberAccessExpressionSyntax.prototype.withDotToken = function (dotToken) { + return this.update(this.expression, dotToken, this.name); + }; + + MemberAccessExpressionSyntax.prototype.withName = function (name) { + return this.update(this.expression, this.dotToken, name); + }; + + MemberAccessExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return MemberAccessExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberAccessExpressionSyntax = MemberAccessExpressionSyntax; + + var PostfixUnaryExpressionSyntax = (function (_super) { + __extends(PostfixUnaryExpressionSyntax, _super); + function PostfixUnaryExpressionSyntax(kind, operand, operatorToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.operand = operand; + this.operatorToken = operatorToken; + + this._kind = kind; + } + PostfixUnaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitPostfixUnaryExpression(this); + }; + + PostfixUnaryExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + PostfixUnaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.operand; + case 1: + return this.operatorToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PostfixUnaryExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + PostfixUnaryExpressionSyntax.prototype.update = function (kind, operand, operatorToken) { + if (this._kind === kind && this.operand === operand && this.operatorToken === operatorToken) { + return this; + } + + return new PostfixUnaryExpressionSyntax(kind, operand, operatorToken, this.parsedInStrictMode()); + }; + + PostfixUnaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PostfixUnaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PostfixUnaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.operand, this.operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.withOperand = function (operand) { + return this.update(this._kind, operand, this.operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, this.operand, operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.operand.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return PostfixUnaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PostfixUnaryExpressionSyntax = PostfixUnaryExpressionSyntax; + + var ElementAccessExpressionSyntax = (function (_super) { + __extends(ElementAccessExpressionSyntax, _super); + function ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.openBracketToken = openBracketToken; + this.argumentExpression = argumentExpression; + this.closeBracketToken = closeBracketToken; + } + ElementAccessExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitElementAccessExpression(this); + }; + + ElementAccessExpressionSyntax.prototype.kind = function () { + return 221 /* ElementAccessExpression */; + }; + + ElementAccessExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + ElementAccessExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.openBracketToken; + case 2: + return this.argumentExpression; + case 3: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ElementAccessExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.update = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + if (this.expression === expression && this.openBracketToken === openBracketToken && this.argumentExpression === argumentExpression && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, this.parsedInStrictMode()); + }; + + ElementAccessExpressionSyntax.create1 = function (expression, argumentExpression) { + return new ElementAccessExpressionSyntax(expression, TypeScript.Syntax.token(74 /* OpenBracketToken */), argumentExpression, TypeScript.Syntax.token(75 /* CloseBracketToken */), false); + }; + + ElementAccessExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ElementAccessExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ElementAccessExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.openBracketToken, this.argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(this.expression, openBracketToken, this.argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withArgumentExpression = function (argumentExpression) { + return this.update(this.expression, this.openBracketToken, argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.expression, this.openBracketToken, this.argumentExpression, closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentExpression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ElementAccessExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ElementAccessExpressionSyntax = ElementAccessExpressionSyntax; + + var InvocationExpressionSyntax = (function (_super) { + __extends(InvocationExpressionSyntax, _super); + function InvocationExpressionSyntax(expression, argumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.argumentList = argumentList; + } + InvocationExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitInvocationExpression(this); + }; + + InvocationExpressionSyntax.prototype.kind = function () { + return 213 /* InvocationExpression */; + }; + + InvocationExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + InvocationExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.argumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + InvocationExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.update = function (expression, argumentList) { + if (this.expression === expression && this.argumentList === argumentList) { + return this; + } + + return new InvocationExpressionSyntax(expression, argumentList, this.parsedInStrictMode()); + }; + + InvocationExpressionSyntax.create1 = function (expression) { + return new InvocationExpressionSyntax(expression, ArgumentListSyntax.create1(), false); + }; + + InvocationExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + InvocationExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + InvocationExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.argumentList); + }; + + InvocationExpressionSyntax.prototype.withArgumentList = function (argumentList) { + return this.update(this.expression, argumentList); + }; + + InvocationExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentList.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return InvocationExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.InvocationExpressionSyntax = InvocationExpressionSyntax; + + var ArgumentListSyntax = (function (_super) { + __extends(ArgumentListSyntax, _super); + function ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeArgumentList = typeArgumentList; + this.openParenToken = openParenToken; + this.closeParenToken = closeParenToken; + + this.arguments = _arguments; + } + ArgumentListSyntax.prototype.accept = function (visitor) { + return visitor.visitArgumentList(this); + }; + + ArgumentListSyntax.prototype.kind = function () { + return 226 /* ArgumentList */; + }; + + ArgumentListSyntax.prototype.childCount = function () { + return 4; + }; + + ArgumentListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeArgumentList; + case 1: + return this.openParenToken; + case 2: + return this.arguments; + case 3: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArgumentListSyntax.prototype.update = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + if (this.typeArgumentList === typeArgumentList && this.openParenToken === openParenToken && this.arguments === _arguments && this.closeParenToken === closeParenToken) { + return this; + } + + return new ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, this.parsedInStrictMode()); + }; + + ArgumentListSyntax.create = function (openParenToken, closeParenToken) { + return new ArgumentListSyntax(null, openParenToken, TypeScript.Syntax.emptySeparatedList, closeParenToken, false); + }; + + ArgumentListSyntax.create1 = function () { + return new ArgumentListSyntax(null, TypeScript.Syntax.token(72 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ArgumentListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArgumentListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArgumentListSyntax.prototype.withTypeArgumentList = function (typeArgumentList) { + return this.update(typeArgumentList, this.openParenToken, this.arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.typeArgumentList, openParenToken, this.arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withArguments = function (_arguments) { + return this.update(this.typeArgumentList, this.openParenToken, _arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withArgument = function (_argument) { + return this.withArguments(TypeScript.Syntax.separatedList([_argument])); + }; + + ArgumentListSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.typeArgumentList, this.openParenToken, this.arguments, closeParenToken); + }; + + ArgumentListSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeArgumentList !== null && this.typeArgumentList.isTypeScriptSpecific()) { + return true; + } + if (this.arguments.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ArgumentListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArgumentListSyntax = ArgumentListSyntax; + + var BinaryExpressionSyntax = (function (_super) { + __extends(BinaryExpressionSyntax, _super); + function BinaryExpressionSyntax(kind, left, operatorToken, right, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.left = left; + this.operatorToken = operatorToken; + this.right = right; + + this._kind = kind; + } + BinaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitBinaryExpression(this); + }; + + BinaryExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + BinaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.left; + case 1: + return this.operatorToken; + case 2: + return this.right; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BinaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + BinaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + BinaryExpressionSyntax.prototype.update = function (kind, left, operatorToken, right) { + if (this._kind === kind && this.left === left && this.operatorToken === operatorToken && this.right === right) { + return this; + } + + return new BinaryExpressionSyntax(kind, left, operatorToken, right, this.parsedInStrictMode()); + }; + + BinaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BinaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BinaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.left, this.operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withLeft = function (left) { + return this.update(this._kind, left, this.operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, this.left, operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withRight = function (right) { + return this.update(this._kind, this.left, this.operatorToken, right); + }; + + BinaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.left.isTypeScriptSpecific()) { + return true; + } + if (this.right.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return BinaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BinaryExpressionSyntax = BinaryExpressionSyntax; + + var ConditionalExpressionSyntax = (function (_super) { + __extends(ConditionalExpressionSyntax, _super); + function ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.condition = condition; + this.questionToken = questionToken; + this.whenTrue = whenTrue; + this.colonToken = colonToken; + this.whenFalse = whenFalse; + } + ConditionalExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitConditionalExpression(this); + }; + + ConditionalExpressionSyntax.prototype.kind = function () { + return 186 /* ConditionalExpression */; + }; + + ConditionalExpressionSyntax.prototype.childCount = function () { + return 5; + }; + + ConditionalExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.condition; + case 1: + return this.questionToken; + case 2: + return this.whenTrue; + case 3: + return this.colonToken; + case 4: + return this.whenFalse; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConditionalExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ConditionalExpressionSyntax.prototype.update = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + if (this.condition === condition && this.questionToken === questionToken && this.whenTrue === whenTrue && this.colonToken === colonToken && this.whenFalse === whenFalse) { + return this; + } + + return new ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, this.parsedInStrictMode()); + }; + + ConditionalExpressionSyntax.create1 = function (condition, whenTrue, whenFalse) { + return new ConditionalExpressionSyntax(condition, TypeScript.Syntax.token(105 /* QuestionToken */), whenTrue, TypeScript.Syntax.token(106 /* ColonToken */), whenFalse, false); + }; + + ConditionalExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConditionalExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConditionalExpressionSyntax.prototype.withCondition = function (condition) { + return this.update(condition, this.questionToken, this.whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.condition, questionToken, this.whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withWhenTrue = function (whenTrue) { + return this.update(this.condition, this.questionToken, whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.condition, this.questionToken, this.whenTrue, colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withWhenFalse = function (whenFalse) { + return this.update(this.condition, this.questionToken, this.whenTrue, this.colonToken, whenFalse); + }; + + ConditionalExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.whenTrue.isTypeScriptSpecific()) { + return true; + } + if (this.whenFalse.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ConditionalExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConditionalExpressionSyntax = ConditionalExpressionSyntax; + + var ConstructSignatureSyntax = (function (_super) { + __extends(ConstructSignatureSyntax, _super); + function ConstructSignatureSyntax(newKeyword, callSignature, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.callSignature = callSignature; + } + ConstructSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructSignature(this); + }; + + ConstructSignatureSyntax.prototype.kind = function () { + return 143 /* ConstructSignature */; + }; + + ConstructSignatureSyntax.prototype.childCount = function () { + return 2; + }; + + ConstructSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.callSignature; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + ConstructSignatureSyntax.prototype.update = function (newKeyword, callSignature) { + if (this.newKeyword === newKeyword && this.callSignature === callSignature) { + return this; + } + + return new ConstructSignatureSyntax(newKeyword, callSignature, this.parsedInStrictMode()); + }; + + ConstructSignatureSyntax.create1 = function () { + return new ConstructSignatureSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), CallSignatureSyntax.create1(), false); + }; + + ConstructSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructSignatureSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.callSignature); + }; + + ConstructSignatureSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.newKeyword, callSignature); + }; + + ConstructSignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructSignatureSyntax = ConstructSignatureSyntax; + + var MethodSignatureSyntax = (function (_super) { + __extends(MethodSignatureSyntax, _super); + function MethodSignatureSyntax(propertyName, questionToken, callSignature, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.callSignature = callSignature; + } + MethodSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitMethodSignature(this); + }; + + MethodSignatureSyntax.prototype.kind = function () { + return 145 /* MethodSignature */; + }; + + MethodSignatureSyntax.prototype.childCount = function () { + return 3; + }; + + MethodSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.questionToken; + case 2: + return this.callSignature; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MethodSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + MethodSignatureSyntax.prototype.update = function (propertyName, questionToken, callSignature) { + if (this.propertyName === propertyName && this.questionToken === questionToken && this.callSignature === callSignature) { + return this; + } + + return new MethodSignatureSyntax(propertyName, questionToken, callSignature, this.parsedInStrictMode()); + }; + + MethodSignatureSyntax.create = function (propertyName, callSignature) { + return new MethodSignatureSyntax(propertyName, null, callSignature, false); + }; + + MethodSignatureSyntax.create1 = function (propertyName) { + return new MethodSignatureSyntax(propertyName, null, CallSignatureSyntax.create1(), false); + }; + + MethodSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MethodSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MethodSignatureSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.questionToken, this.callSignature); + }; + + MethodSignatureSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.propertyName, questionToken, this.callSignature); + }; + + MethodSignatureSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.propertyName, this.questionToken, callSignature); + }; + + MethodSignatureSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return MethodSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MethodSignatureSyntax = MethodSignatureSyntax; + + var IndexSignatureSyntax = (function (_super) { + __extends(IndexSignatureSyntax, _super); + function IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBracketToken = openBracketToken; + this.parameter = parameter; + this.closeBracketToken = closeBracketToken; + this.typeAnnotation = typeAnnotation; + } + IndexSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitIndexSignature(this); + }; + + IndexSignatureSyntax.prototype.kind = function () { + return 144 /* IndexSignature */; + }; + + IndexSignatureSyntax.prototype.childCount = function () { + return 4; + }; + + IndexSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBracketToken; + case 1: + return this.parameter; + case 2: + return this.closeBracketToken; + case 3: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IndexSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + IndexSignatureSyntax.prototype.update = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + if (this.openBracketToken === openBracketToken && this.parameter === parameter && this.closeBracketToken === closeBracketToken && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, this.parsedInStrictMode()); + }; + + IndexSignatureSyntax.create = function (openBracketToken, parameter, closeBracketToken) { + return new IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, null, false); + }; + + IndexSignatureSyntax.create1 = function (parameter) { + return new IndexSignatureSyntax(TypeScript.Syntax.token(74 /* OpenBracketToken */), parameter, TypeScript.Syntax.token(75 /* CloseBracketToken */), null, false); + }; + + IndexSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IndexSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IndexSignatureSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(openBracketToken, this.parameter, this.closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withParameter = function (parameter) { + return this.update(this.openBracketToken, parameter, this.closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.openBracketToken, this.parameter, closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.openBracketToken, this.parameter, this.closeBracketToken, typeAnnotation); + }; + + IndexSignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return IndexSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IndexSignatureSyntax = IndexSignatureSyntax; + + var PropertySignatureSyntax = (function (_super) { + __extends(PropertySignatureSyntax, _super); + function PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + } + PropertySignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitPropertySignature(this); + }; + + PropertySignatureSyntax.prototype.kind = function () { + return 141 /* PropertySignature */; + }; + + PropertySignatureSyntax.prototype.childCount = function () { + return 3; + }; + + PropertySignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.questionToken; + case 2: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PropertySignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + PropertySignatureSyntax.prototype.update = function (propertyName, questionToken, typeAnnotation) { + if (this.propertyName === propertyName && this.questionToken === questionToken && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, this.parsedInStrictMode()); + }; + + PropertySignatureSyntax.create = function (propertyName) { + return new PropertySignatureSyntax(propertyName, null, null, false); + }; + + PropertySignatureSyntax.create1 = function (propertyName) { + return new PropertySignatureSyntax(propertyName, null, null, false); + }; + + PropertySignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PropertySignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PropertySignatureSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.questionToken, this.typeAnnotation); + }; + + PropertySignatureSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.propertyName, questionToken, this.typeAnnotation); + }; + + PropertySignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.propertyName, this.questionToken, typeAnnotation); + }; + + PropertySignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return PropertySignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PropertySignatureSyntax = PropertySignatureSyntax; + + var CallSignatureSyntax = (function (_super) { + __extends(CallSignatureSyntax, _super); + function CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + } + CallSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitCallSignature(this); + }; + + CallSignatureSyntax.prototype.kind = function () { + return 142 /* CallSignature */; + }; + + CallSignatureSyntax.prototype.childCount = function () { + return 3; + }; + + CallSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeParameterList; + case 1: + return this.parameterList; + case 2: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CallSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + CallSignatureSyntax.prototype.update = function (typeParameterList, parameterList, typeAnnotation) { + if (this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, this.parsedInStrictMode()); + }; + + CallSignatureSyntax.create = function (parameterList) { + return new CallSignatureSyntax(null, parameterList, null, false); + }; + + CallSignatureSyntax.create1 = function () { + return new CallSignatureSyntax(null, ParameterListSyntax.create1(), null, false); + }; + + CallSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CallSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CallSignatureSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(typeParameterList, this.parameterList, this.typeAnnotation); + }; + + CallSignatureSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.typeParameterList, parameterList, this.typeAnnotation); + }; + + CallSignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.typeParameterList, this.parameterList, typeAnnotation); + }; + + CallSignatureSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeParameterList !== null) { + return true; + } + if (this.parameterList.isTypeScriptSpecific()) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + return false; + }; + return CallSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CallSignatureSyntax = CallSignatureSyntax; + + var ParameterListSyntax = (function (_super) { + __extends(ParameterListSyntax, _super); + function ParameterListSyntax(openParenToken, parameters, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openParenToken = openParenToken; + this.parameters = parameters; + this.closeParenToken = closeParenToken; + } + ParameterListSyntax.prototype.accept = function (visitor) { + return visitor.visitParameterList(this); + }; + + ParameterListSyntax.prototype.kind = function () { + return 227 /* ParameterList */; + }; + + ParameterListSyntax.prototype.childCount = function () { + return 3; + }; + + ParameterListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openParenToken; + case 1: + return this.parameters; + case 2: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParameterListSyntax.prototype.update = function (openParenToken, parameters, closeParenToken) { + if (this.openParenToken === openParenToken && this.parameters === parameters && this.closeParenToken === closeParenToken) { + return this; + } + + return new ParameterListSyntax(openParenToken, parameters, closeParenToken, this.parsedInStrictMode()); + }; + + ParameterListSyntax.create = function (openParenToken, closeParenToken) { + return new ParameterListSyntax(openParenToken, TypeScript.Syntax.emptySeparatedList, closeParenToken, false); + }; + + ParameterListSyntax.create1 = function () { + return new ParameterListSyntax(TypeScript.Syntax.token(72 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ParameterListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParameterListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParameterListSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(openParenToken, this.parameters, this.closeParenToken); + }; + + ParameterListSyntax.prototype.withParameters = function (parameters) { + return this.update(this.openParenToken, parameters, this.closeParenToken); + }; + + ParameterListSyntax.prototype.withParameter = function (parameter) { + return this.withParameters(TypeScript.Syntax.separatedList([parameter])); + }; + + ParameterListSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.openParenToken, this.parameters, closeParenToken); + }; + + ParameterListSyntax.prototype.isTypeScriptSpecific = function () { + if (this.parameters.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ParameterListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParameterListSyntax = ParameterListSyntax; + + var TypeParameterListSyntax = (function (_super) { + __extends(TypeParameterListSyntax, _super); + function TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.typeParameters = typeParameters; + this.greaterThanToken = greaterThanToken; + } + TypeParameterListSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeParameterList(this); + }; + + TypeParameterListSyntax.prototype.kind = function () { + return 229 /* TypeParameterList */; + }; + + TypeParameterListSyntax.prototype.childCount = function () { + return 3; + }; + + TypeParameterListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.typeParameters; + case 2: + return this.greaterThanToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeParameterListSyntax.prototype.update = function (lessThanToken, typeParameters, greaterThanToken) { + if (this.lessThanToken === lessThanToken && this.typeParameters === typeParameters && this.greaterThanToken === greaterThanToken) { + return this; + } + + return new TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, this.parsedInStrictMode()); + }; + + TypeParameterListSyntax.create = function (lessThanToken, greaterThanToken) { + return new TypeParameterListSyntax(lessThanToken, TypeScript.Syntax.emptySeparatedList, greaterThanToken, false); + }; + + TypeParameterListSyntax.create1 = function () { + return new TypeParameterListSyntax(TypeScript.Syntax.token(80 /* LessThanToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(81 /* GreaterThanToken */), false); + }; + + TypeParameterListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeParameterListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeParameterListSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.typeParameters, this.greaterThanToken); + }; + + TypeParameterListSyntax.prototype.withTypeParameters = function (typeParameters) { + return this.update(this.lessThanToken, typeParameters, this.greaterThanToken); + }; + + TypeParameterListSyntax.prototype.withTypeParameter = function (typeParameter) { + return this.withTypeParameters(TypeScript.Syntax.separatedList([typeParameter])); + }; + + TypeParameterListSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.typeParameters, greaterThanToken); + }; + + TypeParameterListSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeParameterListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeParameterListSyntax = TypeParameterListSyntax; + + var TypeParameterSyntax = (function (_super) { + __extends(TypeParameterSyntax, _super); + function TypeParameterSyntax(identifier, constraint, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.constraint = constraint; + } + TypeParameterSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeParameter(this); + }; + + TypeParameterSyntax.prototype.kind = function () { + return 238 /* TypeParameter */; + }; + + TypeParameterSyntax.prototype.childCount = function () { + return 2; + }; + + TypeParameterSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.constraint; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeParameterSyntax.prototype.update = function (identifier, constraint) { + if (this.identifier === identifier && this.constraint === constraint) { + return this; + } + + return new TypeParameterSyntax(identifier, constraint, this.parsedInStrictMode()); + }; + + TypeParameterSyntax.create = function (identifier) { + return new TypeParameterSyntax(identifier, null, false); + }; + + TypeParameterSyntax.create1 = function (identifier) { + return new TypeParameterSyntax(identifier, null, false); + }; + + TypeParameterSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeParameterSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeParameterSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.constraint); + }; + + TypeParameterSyntax.prototype.withConstraint = function (constraint) { + return this.update(this.identifier, constraint); + }; + + TypeParameterSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeParameterSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeParameterSyntax = TypeParameterSyntax; + + var ConstraintSyntax = (function (_super) { + __extends(ConstraintSyntax, _super); + function ConstraintSyntax(extendsKeyword, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.extendsKeyword = extendsKeyword; + this.type = type; + } + ConstraintSyntax.prototype.accept = function (visitor) { + return visitor.visitConstraint(this); + }; + + ConstraintSyntax.prototype.kind = function () { + return 239 /* Constraint */; + }; + + ConstraintSyntax.prototype.childCount = function () { + return 2; + }; + + ConstraintSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.extendsKeyword; + case 1: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstraintSyntax.prototype.update = function (extendsKeyword, type) { + if (this.extendsKeyword === extendsKeyword && this.type === type) { + return this; + } + + return new ConstraintSyntax(extendsKeyword, type, this.parsedInStrictMode()); + }; + + ConstraintSyntax.create1 = function (type) { + return new ConstraintSyntax(TypeScript.Syntax.token(48 /* ExtendsKeyword */), type, false); + }; + + ConstraintSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstraintSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstraintSyntax.prototype.withExtendsKeyword = function (extendsKeyword) { + return this.update(extendsKeyword, this.type); + }; + + ConstraintSyntax.prototype.withType = function (type) { + return this.update(this.extendsKeyword, type); + }; + + ConstraintSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstraintSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstraintSyntax = ConstraintSyntax; + + var ElseClauseSyntax = (function (_super) { + __extends(ElseClauseSyntax, _super); + function ElseClauseSyntax(elseKeyword, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.elseKeyword = elseKeyword; + this.statement = statement; + } + ElseClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitElseClause(this); + }; + + ElseClauseSyntax.prototype.kind = function () { + return 235 /* ElseClause */; + }; + + ElseClauseSyntax.prototype.childCount = function () { + return 2; + }; + + ElseClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.elseKeyword; + case 1: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ElseClauseSyntax.prototype.update = function (elseKeyword, statement) { + if (this.elseKeyword === elseKeyword && this.statement === statement) { + return this; + } + + return new ElseClauseSyntax(elseKeyword, statement, this.parsedInStrictMode()); + }; + + ElseClauseSyntax.create1 = function (statement) { + return new ElseClauseSyntax(TypeScript.Syntax.token(23 /* ElseKeyword */), statement, false); + }; + + ElseClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ElseClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ElseClauseSyntax.prototype.withElseKeyword = function (elseKeyword) { + return this.update(elseKeyword, this.statement); + }; + + ElseClauseSyntax.prototype.withStatement = function (statement) { + return this.update(this.elseKeyword, statement); + }; + + ElseClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ElseClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ElseClauseSyntax = ElseClauseSyntax; + + var IfStatementSyntax = (function (_super) { + __extends(IfStatementSyntax, _super); + function IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.ifKeyword = ifKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + this.elseClause = elseClause; + } + IfStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitIfStatement(this); + }; + + IfStatementSyntax.prototype.kind = function () { + return 147 /* IfStatement */; + }; + + IfStatementSyntax.prototype.childCount = function () { + return 6; + }; + + IfStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.ifKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + case 5: + return this.elseClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IfStatementSyntax.prototype.isStatement = function () { + return true; + }; + + IfStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + IfStatementSyntax.prototype.update = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + if (this.ifKeyword === ifKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement && this.elseClause === elseClause) { + return this; + } + + return new IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, this.parsedInStrictMode()); + }; + + IfStatementSyntax.create = function (ifKeyword, openParenToken, condition, closeParenToken, statement) { + return new IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, null, false); + }; + + IfStatementSyntax.create1 = function (condition, statement) { + return new IfStatementSyntax(TypeScript.Syntax.token(28 /* IfKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, null, false); + }; + + IfStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IfStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IfStatementSyntax.prototype.withIfKeyword = function (ifKeyword) { + return this.update(ifKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.ifKeyword, openParenToken, this.condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.ifKeyword, this.openParenToken, condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, this.closeParenToken, statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withElseClause = function (elseClause) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement, elseClause); + }; + + IfStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + if (this.elseClause !== null && this.elseClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return IfStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IfStatementSyntax = IfStatementSyntax; + + var ExpressionStatementSyntax = (function (_super) { + __extends(ExpressionStatementSyntax, _super); + function ExpressionStatementSyntax(expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ExpressionStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitExpressionStatement(this); + }; + + ExpressionStatementSyntax.prototype.kind = function () { + return 149 /* ExpressionStatement */; + }; + + ExpressionStatementSyntax.prototype.childCount = function () { + return 2; + }; + + ExpressionStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExpressionStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ExpressionStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ExpressionStatementSyntax.prototype.update = function (expression, semicolonToken) { + if (this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ExpressionStatementSyntax(expression, semicolonToken, this.parsedInStrictMode()); + }; + + ExpressionStatementSyntax.create1 = function (expression) { + return new ExpressionStatementSyntax(expression, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ExpressionStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExpressionStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExpressionStatementSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.semicolonToken); + }; + + ExpressionStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.expression, semicolonToken); + }; + + ExpressionStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ExpressionStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExpressionStatementSyntax = ExpressionStatementSyntax; + + var ConstructorDeclarationSyntax = (function (_super) { + __extends(ConstructorDeclarationSyntax, _super); + function ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.constructorKeyword = constructorKeyword; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + ConstructorDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructorDeclaration(this); + }; + + ConstructorDeclarationSyntax.prototype.kind = function () { + return 137 /* ConstructorDeclaration */; + }; + + ConstructorDeclarationSyntax.prototype.childCount = function () { + return 5; + }; + + ConstructorDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.constructorKeyword; + case 2: + return this.callSignature; + case 3: + return this.block; + case 4: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructorDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + ConstructorDeclarationSyntax.prototype.update = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.constructorKeyword === constructorKeyword && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + ConstructorDeclarationSyntax.create = function (constructorKeyword, callSignature) { + return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, constructorKeyword, callSignature, null, null, false); + }; + + ConstructorDeclarationSyntax.create1 = function () { + return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(62 /* ConstructorKeyword */), CallSignatureSyntax.create1(), null, null, false); + }; + + ConstructorDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructorDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructorDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.constructorKeyword, this.callSignature, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ConstructorDeclarationSyntax.prototype.withConstructorKeyword = function (constructorKeyword) { + return this.update(this.modifiers, constructorKeyword, this.callSignature, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.constructorKeyword, callSignature, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.constructorKeyword, this.callSignature, block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.constructorKeyword, this.callSignature, this.block, semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructorDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructorDeclarationSyntax = ConstructorDeclarationSyntax; + + var MemberFunctionDeclarationSyntax = (function (_super) { + __extends(MemberFunctionDeclarationSyntax, _super); + function MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + MemberFunctionDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberFunctionDeclaration(this); + }; + + MemberFunctionDeclarationSyntax.prototype.kind = function () { + return 135 /* MemberFunctionDeclaration */; + }; + + MemberFunctionDeclarationSyntax.prototype.childCount = function () { + return 5; + }; + + MemberFunctionDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.propertyName; + case 2: + return this.callSignature; + case 3: + return this.block; + case 4: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberFunctionDeclarationSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + MemberFunctionDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + MemberFunctionDeclarationSyntax.prototype.update = function (modifiers, propertyName, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.propertyName === propertyName && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + MemberFunctionDeclarationSyntax.create = function (propertyName, callSignature) { + return new MemberFunctionDeclarationSyntax(TypeScript.Syntax.emptyList, propertyName, callSignature, null, null, false); + }; + + MemberFunctionDeclarationSyntax.create1 = function (propertyName) { + return new MemberFunctionDeclarationSyntax(TypeScript.Syntax.emptyList, propertyName, CallSignatureSyntax.create1(), null, null, false); + }; + + MemberFunctionDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberFunctionDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberFunctionDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.propertyName, this.callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + MemberFunctionDeclarationSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, propertyName, this.callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.propertyName, callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.propertyName, this.callSignature, block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.propertyName, this.callSignature, this.block, semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return MemberFunctionDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberFunctionDeclarationSyntax = MemberFunctionDeclarationSyntax; + + var GetAccessorSyntax = (function (_super) { + __extends(GetAccessorSyntax, _super); + function GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.getKeyword = getKeyword; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + this.block = block; + } + GetAccessorSyntax.prototype.accept = function (visitor) { + return visitor.visitGetAccessor(this); + }; + + GetAccessorSyntax.prototype.kind = function () { + return 139 /* GetAccessor */; + }; + + GetAccessorSyntax.prototype.childCount = function () { + return 6; + }; + + GetAccessorSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.getKeyword; + case 2: + return this.propertyName; + case 3: + return this.parameterList; + case 4: + return this.typeAnnotation; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + GetAccessorSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + GetAccessorSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + GetAccessorSyntax.prototype.isClassElement = function () { + return true; + }; + + GetAccessorSyntax.prototype.update = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + if (this.modifiers === modifiers && this.getKeyword === getKeyword && this.propertyName === propertyName && this.parameterList === parameterList && this.typeAnnotation === typeAnnotation && this.block === block) { + return this; + } + + return new GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, this.parsedInStrictMode()); + }; + + GetAccessorSyntax.create = function (getKeyword, propertyName, parameterList, block) { + return new GetAccessorSyntax(TypeScript.Syntax.emptyList, getKeyword, propertyName, parameterList, null, block, false); + }; + + GetAccessorSyntax.create1 = function (propertyName) { + return new GetAccessorSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(64 /* GetKeyword */), propertyName, ParameterListSyntax.create1(), null, BlockSyntax.create1(), false); + }; + + GetAccessorSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + GetAccessorSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + GetAccessorSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + GetAccessorSyntax.prototype.withGetKeyword = function (getKeyword) { + return this.update(this.modifiers, getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, this.getKeyword, propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, this.parameterList, typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, block); + }; + + GetAccessorSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.childCount() > 0) { + return true; + } + if (this.parameterList.isTypeScriptSpecific()) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return GetAccessorSyntax; + })(TypeScript.SyntaxNode); + TypeScript.GetAccessorSyntax = GetAccessorSyntax; + + var SetAccessorSyntax = (function (_super) { + __extends(SetAccessorSyntax, _super); + function SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.setKeyword = setKeyword; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.block = block; + } + SetAccessorSyntax.prototype.accept = function (visitor) { + return visitor.visitSetAccessor(this); + }; + + SetAccessorSyntax.prototype.kind = function () { + return 140 /* SetAccessor */; + }; + + SetAccessorSyntax.prototype.childCount = function () { + return 5; + }; + + SetAccessorSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.setKeyword; + case 2: + return this.propertyName; + case 3: + return this.parameterList; + case 4: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SetAccessorSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + SetAccessorSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + SetAccessorSyntax.prototype.isClassElement = function () { + return true; + }; + + SetAccessorSyntax.prototype.update = function (modifiers, setKeyword, propertyName, parameterList, block) { + if (this.modifiers === modifiers && this.setKeyword === setKeyword && this.propertyName === propertyName && this.parameterList === parameterList && this.block === block) { + return this; + } + + return new SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, this.parsedInStrictMode()); + }; + + SetAccessorSyntax.create = function (setKeyword, propertyName, parameterList, block) { + return new SetAccessorSyntax(TypeScript.Syntax.emptyList, setKeyword, propertyName, parameterList, block, false); + }; + + SetAccessorSyntax.create1 = function (propertyName) { + return new SetAccessorSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(68 /* SetKeyword */), propertyName, ParameterListSyntax.create1(), BlockSyntax.create1(), false); + }; + + SetAccessorSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SetAccessorSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SetAccessorSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.setKeyword, this.propertyName, this.parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + SetAccessorSyntax.prototype.withSetKeyword = function (setKeyword) { + return this.update(this.modifiers, setKeyword, this.propertyName, this.parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, this.setKeyword, propertyName, this.parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.modifiers, this.setKeyword, this.propertyName, parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.setKeyword, this.propertyName, this.parameterList, block); + }; + + SetAccessorSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return SetAccessorSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SetAccessorSyntax = SetAccessorSyntax; + + var MemberVariableDeclarationSyntax = (function (_super) { + __extends(MemberVariableDeclarationSyntax, _super); + function MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.variableDeclarator = variableDeclarator; + this.semicolonToken = semicolonToken; + } + MemberVariableDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberVariableDeclaration(this); + }; + + MemberVariableDeclarationSyntax.prototype.kind = function () { + return 136 /* MemberVariableDeclaration */; + }; + + MemberVariableDeclarationSyntax.prototype.childCount = function () { + return 3; + }; + + MemberVariableDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.variableDeclarator; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberVariableDeclarationSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + MemberVariableDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + MemberVariableDeclarationSyntax.prototype.update = function (modifiers, variableDeclarator, semicolonToken) { + if (this.modifiers === modifiers && this.variableDeclarator === variableDeclarator && this.semicolonToken === semicolonToken) { + return this; + } + + return new MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, this.parsedInStrictMode()); + }; + + MemberVariableDeclarationSyntax.create = function (variableDeclarator, semicolonToken) { + return new MemberVariableDeclarationSyntax(TypeScript.Syntax.emptyList, variableDeclarator, semicolonToken, false); + }; + + MemberVariableDeclarationSyntax.create1 = function (variableDeclarator) { + return new MemberVariableDeclarationSyntax(TypeScript.Syntax.emptyList, variableDeclarator, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + MemberVariableDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberVariableDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberVariableDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.variableDeclarator, this.semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + MemberVariableDeclarationSyntax.prototype.withVariableDeclarator = function (variableDeclarator) { + return this.update(this.modifiers, variableDeclarator, this.semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.variableDeclarator, semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return MemberVariableDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberVariableDeclarationSyntax = MemberVariableDeclarationSyntax; + + var IndexMemberDeclarationSyntax = (function (_super) { + __extends(IndexMemberDeclarationSyntax, _super); + function IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.indexSignature = indexSignature; + this.semicolonToken = semicolonToken; + } + IndexMemberDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitIndexMemberDeclaration(this); + }; + + IndexMemberDeclarationSyntax.prototype.kind = function () { + return 138 /* IndexMemberDeclaration */; + }; + + IndexMemberDeclarationSyntax.prototype.childCount = function () { + return 3; + }; + + IndexMemberDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.indexSignature; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IndexMemberDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + IndexMemberDeclarationSyntax.prototype.update = function (modifiers, indexSignature, semicolonToken) { + if (this.modifiers === modifiers && this.indexSignature === indexSignature && this.semicolonToken === semicolonToken) { + return this; + } + + return new IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, this.parsedInStrictMode()); + }; + + IndexMemberDeclarationSyntax.create = function (indexSignature, semicolonToken) { + return new IndexMemberDeclarationSyntax(TypeScript.Syntax.emptyList, indexSignature, semicolonToken, false); + }; + + IndexMemberDeclarationSyntax.create1 = function (indexSignature) { + return new IndexMemberDeclarationSyntax(TypeScript.Syntax.emptyList, indexSignature, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + IndexMemberDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IndexMemberDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IndexMemberDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.indexSignature, this.semicolonToken); + }; + + IndexMemberDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + IndexMemberDeclarationSyntax.prototype.withIndexSignature = function (indexSignature) { + return this.update(this.modifiers, indexSignature, this.semicolonToken); + }; + + IndexMemberDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.indexSignature, semicolonToken); + }; + + IndexMemberDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return IndexMemberDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IndexMemberDeclarationSyntax = IndexMemberDeclarationSyntax; + + var ThrowStatementSyntax = (function (_super) { + __extends(ThrowStatementSyntax, _super); + function ThrowStatementSyntax(throwKeyword, expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.throwKeyword = throwKeyword; + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ThrowStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitThrowStatement(this); + }; + + ThrowStatementSyntax.prototype.kind = function () { + return 157 /* ThrowStatement */; + }; + + ThrowStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ThrowStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.throwKeyword; + case 1: + return this.expression; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ThrowStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ThrowStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ThrowStatementSyntax.prototype.update = function (throwKeyword, expression, semicolonToken) { + if (this.throwKeyword === throwKeyword && this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ThrowStatementSyntax(throwKeyword, expression, semicolonToken, this.parsedInStrictMode()); + }; + + ThrowStatementSyntax.create1 = function (expression) { + return new ThrowStatementSyntax(TypeScript.Syntax.token(36 /* ThrowKeyword */), expression, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ThrowStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ThrowStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ThrowStatementSyntax.prototype.withThrowKeyword = function (throwKeyword) { + return this.update(throwKeyword, this.expression, this.semicolonToken); + }; + + ThrowStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.throwKeyword, expression, this.semicolonToken); + }; + + ThrowStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.throwKeyword, this.expression, semicolonToken); + }; + + ThrowStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ThrowStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ThrowStatementSyntax = ThrowStatementSyntax; + + var ReturnStatementSyntax = (function (_super) { + __extends(ReturnStatementSyntax, _super); + function ReturnStatementSyntax(returnKeyword, expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.returnKeyword = returnKeyword; + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ReturnStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitReturnStatement(this); + }; + + ReturnStatementSyntax.prototype.kind = function () { + return 150 /* ReturnStatement */; + }; + + ReturnStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ReturnStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.returnKeyword; + case 1: + return this.expression; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ReturnStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ReturnStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ReturnStatementSyntax.prototype.update = function (returnKeyword, expression, semicolonToken) { + if (this.returnKeyword === returnKeyword && this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ReturnStatementSyntax(returnKeyword, expression, semicolonToken, this.parsedInStrictMode()); + }; + + ReturnStatementSyntax.create = function (returnKeyword, semicolonToken) { + return new ReturnStatementSyntax(returnKeyword, null, semicolonToken, false); + }; + + ReturnStatementSyntax.create1 = function () { + return new ReturnStatementSyntax(TypeScript.Syntax.token(33 /* ReturnKeyword */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ReturnStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ReturnStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ReturnStatementSyntax.prototype.withReturnKeyword = function (returnKeyword) { + return this.update(returnKeyword, this.expression, this.semicolonToken); + }; + + ReturnStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.returnKeyword, expression, this.semicolonToken); + }; + + ReturnStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.returnKeyword, this.expression, semicolonToken); + }; + + ReturnStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression !== null && this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ReturnStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ReturnStatementSyntax = ReturnStatementSyntax; + + var ObjectCreationExpressionSyntax = (function (_super) { + __extends(ObjectCreationExpressionSyntax, _super); + function ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.expression = expression; + this.argumentList = argumentList; + } + ObjectCreationExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectCreationExpression(this); + }; + + ObjectCreationExpressionSyntax.prototype.kind = function () { + return 216 /* ObjectCreationExpression */; + }; + + ObjectCreationExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectCreationExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.expression; + case 2: + return this.argumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectCreationExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.update = function (newKeyword, expression, argumentList) { + if (this.newKeyword === newKeyword && this.expression === expression && this.argumentList === argumentList) { + return this; + } + + return new ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, this.parsedInStrictMode()); + }; + + ObjectCreationExpressionSyntax.create = function (newKeyword, expression) { + return new ObjectCreationExpressionSyntax(newKeyword, expression, null, false); + }; + + ObjectCreationExpressionSyntax.create1 = function (expression) { + return new ObjectCreationExpressionSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), expression, null, false); + }; + + ObjectCreationExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectCreationExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectCreationExpressionSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.expression, this.argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.newKeyword, expression, this.argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.withArgumentList = function (argumentList) { + return this.update(this.newKeyword, this.expression, argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentList !== null && this.argumentList.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ObjectCreationExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectCreationExpressionSyntax = ObjectCreationExpressionSyntax; + + var SwitchStatementSyntax = (function (_super) { + __extends(SwitchStatementSyntax, _super); + function SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.switchKeyword = switchKeyword; + this.openParenToken = openParenToken; + this.expression = expression; + this.closeParenToken = closeParenToken; + this.openBraceToken = openBraceToken; + this.switchClauses = switchClauses; + this.closeBraceToken = closeBraceToken; + } + SwitchStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitSwitchStatement(this); + }; + + SwitchStatementSyntax.prototype.kind = function () { + return 151 /* SwitchStatement */; + }; + + SwitchStatementSyntax.prototype.childCount = function () { + return 7; + }; + + SwitchStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.switchKeyword; + case 1: + return this.openParenToken; + case 2: + return this.expression; + case 3: + return this.closeParenToken; + case 4: + return this.openBraceToken; + case 5: + return this.switchClauses; + case 6: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SwitchStatementSyntax.prototype.isStatement = function () { + return true; + }; + + SwitchStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + SwitchStatementSyntax.prototype.update = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + if (this.switchKeyword === switchKeyword && this.openParenToken === openParenToken && this.expression === expression && this.closeParenToken === closeParenToken && this.openBraceToken === openBraceToken && this.switchClauses === switchClauses && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, this.parsedInStrictMode()); + }; + + SwitchStatementSyntax.create = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, closeBraceToken) { + return new SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + SwitchStatementSyntax.create1 = function (expression) { + return new SwitchStatementSyntax(TypeScript.Syntax.token(34 /* SwitchKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), expression, TypeScript.Syntax.token(73 /* CloseParenToken */), TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + SwitchStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SwitchStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SwitchStatementSyntax.prototype.withSwitchKeyword = function (switchKeyword) { + return this.update(switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.switchKeyword, openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.switchKeyword, this.openParenToken, expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withSwitchClauses = function (switchClauses) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withSwitchClause = function (switchClause) { + return this.withSwitchClauses(TypeScript.Syntax.list([switchClause])); + }; + + SwitchStatementSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, closeBraceToken); + }; + + SwitchStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.switchClauses.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SwitchStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SwitchStatementSyntax = SwitchStatementSyntax; + + var CaseSwitchClauseSyntax = (function (_super) { + __extends(CaseSwitchClauseSyntax, _super); + function CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.caseKeyword = caseKeyword; + this.expression = expression; + this.colonToken = colonToken; + this.statements = statements; + } + CaseSwitchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitCaseSwitchClause(this); + }; + + CaseSwitchClauseSyntax.prototype.kind = function () { + return 233 /* CaseSwitchClause */; + }; + + CaseSwitchClauseSyntax.prototype.childCount = function () { + return 4; + }; + + CaseSwitchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.caseKeyword; + case 1: + return this.expression; + case 2: + return this.colonToken; + case 3: + return this.statements; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CaseSwitchClauseSyntax.prototype.isSwitchClause = function () { + return true; + }; + + CaseSwitchClauseSyntax.prototype.update = function (caseKeyword, expression, colonToken, statements) { + if (this.caseKeyword === caseKeyword && this.expression === expression && this.colonToken === colonToken && this.statements === statements) { + return this; + } + + return new CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, this.parsedInStrictMode()); + }; + + CaseSwitchClauseSyntax.create = function (caseKeyword, expression, colonToken) { + return new CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, TypeScript.Syntax.emptyList, false); + }; + + CaseSwitchClauseSyntax.create1 = function (expression) { + return new CaseSwitchClauseSyntax(TypeScript.Syntax.token(16 /* CaseKeyword */), expression, TypeScript.Syntax.token(106 /* ColonToken */), TypeScript.Syntax.emptyList, false); + }; + + CaseSwitchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CaseSwitchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CaseSwitchClauseSyntax.prototype.withCaseKeyword = function (caseKeyword) { + return this.update(caseKeyword, this.expression, this.colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withExpression = function (expression) { + return this.update(this.caseKeyword, expression, this.colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.caseKeyword, this.expression, colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withStatements = function (statements) { + return this.update(this.caseKeyword, this.expression, this.colonToken, statements); + }; + + CaseSwitchClauseSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + CaseSwitchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return CaseSwitchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CaseSwitchClauseSyntax = CaseSwitchClauseSyntax; + + var DefaultSwitchClauseSyntax = (function (_super) { + __extends(DefaultSwitchClauseSyntax, _super); + function DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.defaultKeyword = defaultKeyword; + this.colonToken = colonToken; + this.statements = statements; + } + DefaultSwitchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitDefaultSwitchClause(this); + }; + + DefaultSwitchClauseSyntax.prototype.kind = function () { + return 234 /* DefaultSwitchClause */; + }; + + DefaultSwitchClauseSyntax.prototype.childCount = function () { + return 3; + }; + + DefaultSwitchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.defaultKeyword; + case 1: + return this.colonToken; + case 2: + return this.statements; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DefaultSwitchClauseSyntax.prototype.isSwitchClause = function () { + return true; + }; + + DefaultSwitchClauseSyntax.prototype.update = function (defaultKeyword, colonToken, statements) { + if (this.defaultKeyword === defaultKeyword && this.colonToken === colonToken && this.statements === statements) { + return this; + } + + return new DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, this.parsedInStrictMode()); + }; + + DefaultSwitchClauseSyntax.create = function (defaultKeyword, colonToken) { + return new DefaultSwitchClauseSyntax(defaultKeyword, colonToken, TypeScript.Syntax.emptyList, false); + }; + + DefaultSwitchClauseSyntax.create1 = function () { + return new DefaultSwitchClauseSyntax(TypeScript.Syntax.token(20 /* DefaultKeyword */), TypeScript.Syntax.token(106 /* ColonToken */), TypeScript.Syntax.emptyList, false); + }; + + DefaultSwitchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DefaultSwitchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DefaultSwitchClauseSyntax.prototype.withDefaultKeyword = function (defaultKeyword) { + return this.update(defaultKeyword, this.colonToken, this.statements); + }; + + DefaultSwitchClauseSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.defaultKeyword, colonToken, this.statements); + }; + + DefaultSwitchClauseSyntax.prototype.withStatements = function (statements) { + return this.update(this.defaultKeyword, this.colonToken, statements); + }; + + DefaultSwitchClauseSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + DefaultSwitchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DefaultSwitchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DefaultSwitchClauseSyntax = DefaultSwitchClauseSyntax; + + var BreakStatementSyntax = (function (_super) { + __extends(BreakStatementSyntax, _super); + function BreakStatementSyntax(breakKeyword, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.breakKeyword = breakKeyword; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + BreakStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitBreakStatement(this); + }; + + BreakStatementSyntax.prototype.kind = function () { + return 152 /* BreakStatement */; + }; + + BreakStatementSyntax.prototype.childCount = function () { + return 3; + }; + + BreakStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.breakKeyword; + case 1: + return this.identifier; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BreakStatementSyntax.prototype.isStatement = function () { + return true; + }; + + BreakStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + BreakStatementSyntax.prototype.update = function (breakKeyword, identifier, semicolonToken) { + if (this.breakKeyword === breakKeyword && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new BreakStatementSyntax(breakKeyword, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + BreakStatementSyntax.create = function (breakKeyword, semicolonToken) { + return new BreakStatementSyntax(breakKeyword, null, semicolonToken, false); + }; + + BreakStatementSyntax.create1 = function () { + return new BreakStatementSyntax(TypeScript.Syntax.token(15 /* BreakKeyword */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + BreakStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BreakStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BreakStatementSyntax.prototype.withBreakKeyword = function (breakKeyword) { + return this.update(breakKeyword, this.identifier, this.semicolonToken); + }; + + BreakStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.breakKeyword, identifier, this.semicolonToken); + }; + + BreakStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.breakKeyword, this.identifier, semicolonToken); + }; + + BreakStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return BreakStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BreakStatementSyntax = BreakStatementSyntax; + + var ContinueStatementSyntax = (function (_super) { + __extends(ContinueStatementSyntax, _super); + function ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.continueKeyword = continueKeyword; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + ContinueStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitContinueStatement(this); + }; + + ContinueStatementSyntax.prototype.kind = function () { + return 153 /* ContinueStatement */; + }; + + ContinueStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ContinueStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.continueKeyword; + case 1: + return this.identifier; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ContinueStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ContinueStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ContinueStatementSyntax.prototype.update = function (continueKeyword, identifier, semicolonToken) { + if (this.continueKeyword === continueKeyword && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + ContinueStatementSyntax.create = function (continueKeyword, semicolonToken) { + return new ContinueStatementSyntax(continueKeyword, null, semicolonToken, false); + }; + + ContinueStatementSyntax.create1 = function () { + return new ContinueStatementSyntax(TypeScript.Syntax.token(18 /* ContinueKeyword */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ContinueStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ContinueStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ContinueStatementSyntax.prototype.withContinueKeyword = function (continueKeyword) { + return this.update(continueKeyword, this.identifier, this.semicolonToken); + }; + + ContinueStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.continueKeyword, identifier, this.semicolonToken); + }; + + ContinueStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.continueKeyword, this.identifier, semicolonToken); + }; + + ContinueStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return ContinueStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ContinueStatementSyntax = ContinueStatementSyntax; + + var ForStatementSyntax = (function (_super) { + __extends(ForStatementSyntax, _super); + function ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.forKeyword = forKeyword; + this.openParenToken = openParenToken; + this.variableDeclaration = variableDeclaration; + this.initializer = initializer; + this.firstSemicolonToken = firstSemicolonToken; + this.condition = condition; + this.secondSemicolonToken = secondSemicolonToken; + this.incrementor = incrementor; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + ForStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitForStatement(this); + }; + + ForStatementSyntax.prototype.kind = function () { + return 154 /* ForStatement */; + }; + + ForStatementSyntax.prototype.childCount = function () { + return 10; + }; + + ForStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.forKeyword; + case 1: + return this.openParenToken; + case 2: + return this.variableDeclaration; + case 3: + return this.initializer; + case 4: + return this.firstSemicolonToken; + case 5: + return this.condition; + case 6: + return this.secondSemicolonToken; + case 7: + return this.incrementor; + case 8: + return this.closeParenToken; + case 9: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ForStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + ForStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ForStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ForStatementSyntax.prototype.update = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + if (this.forKeyword === forKeyword && this.openParenToken === openParenToken && this.variableDeclaration === variableDeclaration && this.initializer === initializer && this.firstSemicolonToken === firstSemicolonToken && this.condition === condition && this.secondSemicolonToken === secondSemicolonToken && this.incrementor === incrementor && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, this.parsedInStrictMode()); + }; + + ForStatementSyntax.create = function (forKeyword, openParenToken, firstSemicolonToken, secondSemicolonToken, closeParenToken, statement) { + return new ForStatementSyntax(forKeyword, openParenToken, null, null, firstSemicolonToken, null, secondSemicolonToken, null, closeParenToken, statement, false); + }; + + ForStatementSyntax.create1 = function (statement) { + return new ForStatementSyntax(TypeScript.Syntax.token(26 /* ForKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), null, null, TypeScript.Syntax.token(78 /* SemicolonToken */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), null, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + ForStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ForStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ForStatementSyntax.prototype.withForKeyword = function (forKeyword) { + return this.update(forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.forKeyword, openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.forKeyword, this.openParenToken, variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withInitializer = function (initializer) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withFirstSemicolonToken = function (firstSemicolonToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withSecondSemicolonToken = function (secondSemicolonToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withIncrementor = function (incrementor) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, statement); + }; + + ForStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclaration !== null && this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + if (this.initializer !== null && this.initializer.isTypeScriptSpecific()) { + return true; + } + if (this.condition !== null && this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.incrementor !== null && this.incrementor.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ForStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ForStatementSyntax = ForStatementSyntax; + + var ForInStatementSyntax = (function (_super) { + __extends(ForInStatementSyntax, _super); + function ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.forKeyword = forKeyword; + this.openParenToken = openParenToken; + this.variableDeclaration = variableDeclaration; + this.left = left; + this.inKeyword = inKeyword; + this.expression = expression; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + ForInStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitForInStatement(this); + }; + + ForInStatementSyntax.prototype.kind = function () { + return 155 /* ForInStatement */; + }; + + ForInStatementSyntax.prototype.childCount = function () { + return 8; + }; + + ForInStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.forKeyword; + case 1: + return this.openParenToken; + case 2: + return this.variableDeclaration; + case 3: + return this.left; + case 4: + return this.inKeyword; + case 5: + return this.expression; + case 6: + return this.closeParenToken; + case 7: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ForInStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + ForInStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ForInStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ForInStatementSyntax.prototype.update = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + if (this.forKeyword === forKeyword && this.openParenToken === openParenToken && this.variableDeclaration === variableDeclaration && this.left === left && this.inKeyword === inKeyword && this.expression === expression && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, this.parsedInStrictMode()); + }; + + ForInStatementSyntax.create = function (forKeyword, openParenToken, inKeyword, expression, closeParenToken, statement) { + return new ForInStatementSyntax(forKeyword, openParenToken, null, null, inKeyword, expression, closeParenToken, statement, false); + }; + + ForInStatementSyntax.create1 = function (expression, statement) { + return new ForInStatementSyntax(TypeScript.Syntax.token(26 /* ForKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), null, null, TypeScript.Syntax.token(29 /* InKeyword */), expression, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + ForInStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ForInStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ForInStatementSyntax.prototype.withForKeyword = function (forKeyword) { + return this.update(forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.forKeyword, openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.forKeyword, this.openParenToken, variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withLeft = function (left) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withInKeyword = function (inKeyword) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, statement); + }; + + ForInStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclaration !== null && this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + if (this.left !== null && this.left.isTypeScriptSpecific()) { + return true; + } + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ForInStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ForInStatementSyntax = ForInStatementSyntax; + + var WhileStatementSyntax = (function (_super) { + __extends(WhileStatementSyntax, _super); + function WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.whileKeyword = whileKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + WhileStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitWhileStatement(this); + }; + + WhileStatementSyntax.prototype.kind = function () { + return 158 /* WhileStatement */; + }; + + WhileStatementSyntax.prototype.childCount = function () { + return 5; + }; + + WhileStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.whileKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + WhileStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + WhileStatementSyntax.prototype.isStatement = function () { + return true; + }; + + WhileStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + WhileStatementSyntax.prototype.update = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + if (this.whileKeyword === whileKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, this.parsedInStrictMode()); + }; + + WhileStatementSyntax.create1 = function (condition, statement) { + return new WhileStatementSyntax(TypeScript.Syntax.token(42 /* WhileKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + WhileStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + WhileStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + WhileStatementSyntax.prototype.withWhileKeyword = function (whileKeyword) { + return this.update(whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.whileKeyword, openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.whileKeyword, this.openParenToken, condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.whileKeyword, this.openParenToken, this.condition, closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, statement); + }; + + WhileStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return WhileStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.WhileStatementSyntax = WhileStatementSyntax; + + var WithStatementSyntax = (function (_super) { + __extends(WithStatementSyntax, _super); + function WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.withKeyword = withKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + WithStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitWithStatement(this); + }; + + WithStatementSyntax.prototype.kind = function () { + return 163 /* WithStatement */; + }; + + WithStatementSyntax.prototype.childCount = function () { + return 5; + }; + + WithStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.withKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + WithStatementSyntax.prototype.isStatement = function () { + return true; + }; + + WithStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + WithStatementSyntax.prototype.update = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + if (this.withKeyword === withKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, this.parsedInStrictMode()); + }; + + WithStatementSyntax.create1 = function (condition, statement) { + return new WithStatementSyntax(TypeScript.Syntax.token(43 /* WithKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + WithStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + WithStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + WithStatementSyntax.prototype.withWithKeyword = function (withKeyword) { + return this.update(withKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.withKeyword, openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.withKeyword, this.openParenToken, condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.withKeyword, this.openParenToken, this.condition, closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.withKeyword, this.openParenToken, this.condition, this.closeParenToken, statement); + }; + + WithStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return WithStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.WithStatementSyntax = WithStatementSyntax; + + var EnumDeclarationSyntax = (function (_super) { + __extends(EnumDeclarationSyntax, _super); + function EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.enumKeyword = enumKeyword; + this.identifier = identifier; + this.openBraceToken = openBraceToken; + this.enumElements = enumElements; + this.closeBraceToken = closeBraceToken; + } + EnumDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitEnumDeclaration(this); + }; + + EnumDeclarationSyntax.prototype.kind = function () { + return 132 /* EnumDeclaration */; + }; + + EnumDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + EnumDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.enumKeyword; + case 2: + return this.identifier; + case 3: + return this.openBraceToken; + case 4: + return this.enumElements; + case 5: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EnumDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + EnumDeclarationSyntax.prototype.update = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + if (this.modifiers === modifiers && this.enumKeyword === enumKeyword && this.identifier === identifier && this.openBraceToken === openBraceToken && this.enumElements === enumElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, this.parsedInStrictMode()); + }; + + EnumDeclarationSyntax.create = function (enumKeyword, identifier, openBraceToken, closeBraceToken) { + return new EnumDeclarationSyntax(TypeScript.Syntax.emptyList, enumKeyword, identifier, openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + EnumDeclarationSyntax.create1 = function (identifier) { + return new EnumDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(46 /* EnumKeyword */), identifier, TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + EnumDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EnumDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EnumDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.enumKeyword, this.identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + EnumDeclarationSyntax.prototype.withEnumKeyword = function (enumKeyword) { + return this.update(this.modifiers, enumKeyword, this.identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.enumKeyword, identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withEnumElements = function (enumElements) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, this.openBraceToken, enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withEnumElement = function (enumElement) { + return this.withEnumElements(TypeScript.Syntax.separatedList([enumElement])); + }; + + EnumDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, this.openBraceToken, this.enumElements, closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return EnumDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EnumDeclarationSyntax = EnumDeclarationSyntax; + + var EnumElementSyntax = (function (_super) { + __extends(EnumElementSyntax, _super); + function EnumElementSyntax(propertyName, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.equalsValueClause = equalsValueClause; + } + EnumElementSyntax.prototype.accept = function (visitor) { + return visitor.visitEnumElement(this); + }; + + EnumElementSyntax.prototype.kind = function () { + return 243 /* EnumElement */; + }; + + EnumElementSyntax.prototype.childCount = function () { + return 2; + }; + + EnumElementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EnumElementSyntax.prototype.update = function (propertyName, equalsValueClause) { + if (this.propertyName === propertyName && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new EnumElementSyntax(propertyName, equalsValueClause, this.parsedInStrictMode()); + }; + + EnumElementSyntax.create = function (propertyName) { + return new EnumElementSyntax(propertyName, null, false); + }; + + EnumElementSyntax.create1 = function (propertyName) { + return new EnumElementSyntax(propertyName, null, false); + }; + + EnumElementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EnumElementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EnumElementSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.equalsValueClause); + }; + + EnumElementSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.propertyName, equalsValueClause); + }; + + EnumElementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.equalsValueClause !== null && this.equalsValueClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return EnumElementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EnumElementSyntax = EnumElementSyntax; + + var CastExpressionSyntax = (function (_super) { + __extends(CastExpressionSyntax, _super); + function CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.type = type; + this.greaterThanToken = greaterThanToken; + this.expression = expression; + } + CastExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitCastExpression(this); + }; + + CastExpressionSyntax.prototype.kind = function () { + return 220 /* CastExpression */; + }; + + CastExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + CastExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.type; + case 2: + return this.greaterThanToken; + case 3: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CastExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + CastExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + CastExpressionSyntax.prototype.update = function (lessThanToken, type, greaterThanToken, expression) { + if (this.lessThanToken === lessThanToken && this.type === type && this.greaterThanToken === greaterThanToken && this.expression === expression) { + return this; + } + + return new CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, this.parsedInStrictMode()); + }; + + CastExpressionSyntax.create1 = function (type, expression) { + return new CastExpressionSyntax(TypeScript.Syntax.token(80 /* LessThanToken */), type, TypeScript.Syntax.token(81 /* GreaterThanToken */), expression, false); + }; + + CastExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CastExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CastExpressionSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.type, this.greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withType = function (type) { + return this.update(this.lessThanToken, type, this.greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.type, greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.lessThanToken, this.type, this.greaterThanToken, expression); + }; + + CastExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return CastExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CastExpressionSyntax = CastExpressionSyntax; + + var ObjectLiteralExpressionSyntax = (function (_super) { + __extends(ObjectLiteralExpressionSyntax, _super); + function ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.propertyAssignments = propertyAssignments; + this.closeBraceToken = closeBraceToken; + } + ObjectLiteralExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectLiteralExpression(this); + }; + + ObjectLiteralExpressionSyntax.prototype.kind = function () { + return 215 /* ObjectLiteralExpression */; + }; + + ObjectLiteralExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectLiteralExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.propertyAssignments; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectLiteralExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.update = function (openBraceToken, propertyAssignments, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.propertyAssignments === propertyAssignments && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, this.parsedInStrictMode()); + }; + + ObjectLiteralExpressionSyntax.create = function (openBraceToken, closeBraceToken) { + return new ObjectLiteralExpressionSyntax(openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + ObjectLiteralExpressionSyntax.create1 = function () { + return new ObjectLiteralExpressionSyntax(TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ObjectLiteralExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectLiteralExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectLiteralExpressionSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.propertyAssignments, this.closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.withPropertyAssignments = function (propertyAssignments) { + return this.update(this.openBraceToken, propertyAssignments, this.closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.withPropertyAssignment = function (propertyAssignment) { + return this.withPropertyAssignments(TypeScript.Syntax.separatedList([propertyAssignment])); + }; + + ObjectLiteralExpressionSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.propertyAssignments, closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.propertyAssignments.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ObjectLiteralExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectLiteralExpressionSyntax = ObjectLiteralExpressionSyntax; + + var SimplePropertyAssignmentSyntax = (function (_super) { + __extends(SimplePropertyAssignmentSyntax, _super); + function SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.colonToken = colonToken; + this.expression = expression; + } + SimplePropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitSimplePropertyAssignment(this); + }; + + SimplePropertyAssignmentSyntax.prototype.kind = function () { + return 240 /* SimplePropertyAssignment */; + }; + + SimplePropertyAssignmentSyntax.prototype.childCount = function () { + return 3; + }; + + SimplePropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.colonToken; + case 2: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SimplePropertyAssignmentSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + SimplePropertyAssignmentSyntax.prototype.update = function (propertyName, colonToken, expression) { + if (this.propertyName === propertyName && this.colonToken === colonToken && this.expression === expression) { + return this; + } + + return new SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, this.parsedInStrictMode()); + }; + + SimplePropertyAssignmentSyntax.create1 = function (propertyName, expression) { + return new SimplePropertyAssignmentSyntax(propertyName, TypeScript.Syntax.token(106 /* ColonToken */), expression, false); + }; + + SimplePropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SimplePropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SimplePropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.colonToken, this.expression); + }; + + SimplePropertyAssignmentSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.propertyName, colonToken, this.expression); + }; + + SimplePropertyAssignmentSyntax.prototype.withExpression = function (expression) { + return this.update(this.propertyName, this.colonToken, expression); + }; + + SimplePropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SimplePropertyAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SimplePropertyAssignmentSyntax = SimplePropertyAssignmentSyntax; + + var FunctionPropertyAssignmentSyntax = (function (_super) { + __extends(FunctionPropertyAssignmentSyntax, _super); + function FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + } + FunctionPropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionPropertyAssignment(this); + }; + + FunctionPropertyAssignmentSyntax.prototype.kind = function () { + return 241 /* FunctionPropertyAssignment */; + }; + + FunctionPropertyAssignmentSyntax.prototype.childCount = function () { + return 3; + }; + + FunctionPropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.callSignature; + case 2: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionPropertyAssignmentSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + FunctionPropertyAssignmentSyntax.prototype.update = function (propertyName, callSignature, block) { + if (this.propertyName === propertyName && this.callSignature === callSignature && this.block === block) { + return this; + } + + return new FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, this.parsedInStrictMode()); + }; + + FunctionPropertyAssignmentSyntax.create1 = function (propertyName) { + return new FunctionPropertyAssignmentSyntax(propertyName, CallSignatureSyntax.create1(), BlockSyntax.create1(), false); + }; + + FunctionPropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionPropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionPropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.callSignature, this.block); + }; + + FunctionPropertyAssignmentSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.propertyName, callSignature, this.block); + }; + + FunctionPropertyAssignmentSyntax.prototype.withBlock = function (block) { + return this.update(this.propertyName, this.callSignature, block); + }; + + FunctionPropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionPropertyAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionPropertyAssignmentSyntax = FunctionPropertyAssignmentSyntax; + + var FunctionExpressionSyntax = (function (_super) { + __extends(FunctionExpressionSyntax, _super); + function FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.functionKeyword = functionKeyword; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + } + FunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionExpression(this); + }; + + FunctionExpressionSyntax.prototype.kind = function () { + return 222 /* FunctionExpression */; + }; + + FunctionExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + FunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.functionKeyword; + case 1: + return this.identifier; + case 2: + return this.callSignature; + case 3: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.update = function (functionKeyword, identifier, callSignature, block) { + if (this.functionKeyword === functionKeyword && this.identifier === identifier && this.callSignature === callSignature && this.block === block) { + return this; + } + + return new FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, this.parsedInStrictMode()); + }; + + FunctionExpressionSyntax.create = function (functionKeyword, callSignature, block) { + return new FunctionExpressionSyntax(functionKeyword, null, callSignature, block, false); + }; + + FunctionExpressionSyntax.create1 = function () { + return new FunctionExpressionSyntax(TypeScript.Syntax.token(27 /* FunctionKeyword */), null, CallSignatureSyntax.create1(), BlockSyntax.create1(), false); + }; + + FunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionExpressionSyntax.prototype.withFunctionKeyword = function (functionKeyword) { + return this.update(functionKeyword, this.identifier, this.callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.functionKeyword, identifier, this.callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.functionKeyword, this.identifier, callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withBlock = function (block) { + return this.update(this.functionKeyword, this.identifier, this.callSignature, block); + }; + + FunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionExpressionSyntax = FunctionExpressionSyntax; + + var EmptyStatementSyntax = (function (_super) { + __extends(EmptyStatementSyntax, _super); + function EmptyStatementSyntax(semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.semicolonToken = semicolonToken; + } + EmptyStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitEmptyStatement(this); + }; + + EmptyStatementSyntax.prototype.kind = function () { + return 156 /* EmptyStatement */; + }; + + EmptyStatementSyntax.prototype.childCount = function () { + return 1; + }; + + EmptyStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EmptyStatementSyntax.prototype.isStatement = function () { + return true; + }; + + EmptyStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + EmptyStatementSyntax.prototype.update = function (semicolonToken) { + if (this.semicolonToken === semicolonToken) { + return this; + } + + return new EmptyStatementSyntax(semicolonToken, this.parsedInStrictMode()); + }; + + EmptyStatementSyntax.create1 = function () { + return new EmptyStatementSyntax(TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + EmptyStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EmptyStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EmptyStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(semicolonToken); + }; + + EmptyStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return EmptyStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EmptyStatementSyntax = EmptyStatementSyntax; + + var TryStatementSyntax = (function (_super) { + __extends(TryStatementSyntax, _super); + function TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.tryKeyword = tryKeyword; + this.block = block; + this.catchClause = catchClause; + this.finallyClause = finallyClause; + } + TryStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitTryStatement(this); + }; + + TryStatementSyntax.prototype.kind = function () { + return 159 /* TryStatement */; + }; + + TryStatementSyntax.prototype.childCount = function () { + return 4; + }; + + TryStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.tryKeyword; + case 1: + return this.block; + case 2: + return this.catchClause; + case 3: + return this.finallyClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TryStatementSyntax.prototype.isStatement = function () { + return true; + }; + + TryStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + TryStatementSyntax.prototype.update = function (tryKeyword, block, catchClause, finallyClause) { + if (this.tryKeyword === tryKeyword && this.block === block && this.catchClause === catchClause && this.finallyClause === finallyClause) { + return this; + } + + return new TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, this.parsedInStrictMode()); + }; + + TryStatementSyntax.create = function (tryKeyword, block) { + return new TryStatementSyntax(tryKeyword, block, null, null, false); + }; + + TryStatementSyntax.create1 = function () { + return new TryStatementSyntax(TypeScript.Syntax.token(38 /* TryKeyword */), BlockSyntax.create1(), null, null, false); + }; + + TryStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TryStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TryStatementSyntax.prototype.withTryKeyword = function (tryKeyword) { + return this.update(tryKeyword, this.block, this.catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withBlock = function (block) { + return this.update(this.tryKeyword, block, this.catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withCatchClause = function (catchClause) { + return this.update(this.tryKeyword, this.block, catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withFinallyClause = function (finallyClause) { + return this.update(this.tryKeyword, this.block, this.catchClause, finallyClause); + }; + + TryStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.block.isTypeScriptSpecific()) { + return true; + } + if (this.catchClause !== null && this.catchClause.isTypeScriptSpecific()) { + return true; + } + if (this.finallyClause !== null && this.finallyClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return TryStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TryStatementSyntax = TryStatementSyntax; + + var CatchClauseSyntax = (function (_super) { + __extends(CatchClauseSyntax, _super); + function CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.catchKeyword = catchKeyword; + this.openParenToken = openParenToken; + this.identifier = identifier; + this.typeAnnotation = typeAnnotation; + this.closeParenToken = closeParenToken; + this.block = block; + } + CatchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitCatchClause(this); + }; + + CatchClauseSyntax.prototype.kind = function () { + return 236 /* CatchClause */; + }; + + CatchClauseSyntax.prototype.childCount = function () { + return 6; + }; + + CatchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.catchKeyword; + case 1: + return this.openParenToken; + case 2: + return this.identifier; + case 3: + return this.typeAnnotation; + case 4: + return this.closeParenToken; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CatchClauseSyntax.prototype.update = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + if (this.catchKeyword === catchKeyword && this.openParenToken === openParenToken && this.identifier === identifier && this.typeAnnotation === typeAnnotation && this.closeParenToken === closeParenToken && this.block === block) { + return this; + } + + return new CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, this.parsedInStrictMode()); + }; + + CatchClauseSyntax.create = function (catchKeyword, openParenToken, identifier, closeParenToken, block) { + return new CatchClauseSyntax(catchKeyword, openParenToken, identifier, null, closeParenToken, block, false); + }; + + CatchClauseSyntax.create1 = function (identifier) { + return new CatchClauseSyntax(TypeScript.Syntax.token(17 /* CatchKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), identifier, null, TypeScript.Syntax.token(73 /* CloseParenToken */), BlockSyntax.create1(), false); + }; + + CatchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CatchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CatchClauseSyntax.prototype.withCatchKeyword = function (catchKeyword) { + return this.update(catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.catchKeyword, openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.catchKeyword, this.openParenToken, identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withBlock = function (block) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, block); + }; + + CatchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeAnnotation !== null && this.typeAnnotation.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return CatchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CatchClauseSyntax = CatchClauseSyntax; + + var FinallyClauseSyntax = (function (_super) { + __extends(FinallyClauseSyntax, _super); + function FinallyClauseSyntax(finallyKeyword, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.finallyKeyword = finallyKeyword; + this.block = block; + } + FinallyClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitFinallyClause(this); + }; + + FinallyClauseSyntax.prototype.kind = function () { + return 237 /* FinallyClause */; + }; + + FinallyClauseSyntax.prototype.childCount = function () { + return 2; + }; + + FinallyClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.finallyKeyword; + case 1: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FinallyClauseSyntax.prototype.update = function (finallyKeyword, block) { + if (this.finallyKeyword === finallyKeyword && this.block === block) { + return this; + } + + return new FinallyClauseSyntax(finallyKeyword, block, this.parsedInStrictMode()); + }; + + FinallyClauseSyntax.create1 = function () { + return new FinallyClauseSyntax(TypeScript.Syntax.token(25 /* FinallyKeyword */), BlockSyntax.create1(), false); + }; + + FinallyClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FinallyClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FinallyClauseSyntax.prototype.withFinallyKeyword = function (finallyKeyword) { + return this.update(finallyKeyword, this.block); + }; + + FinallyClauseSyntax.prototype.withBlock = function (block) { + return this.update(this.finallyKeyword, block); + }; + + FinallyClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FinallyClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FinallyClauseSyntax = FinallyClauseSyntax; + + var LabeledStatementSyntax = (function (_super) { + __extends(LabeledStatementSyntax, _super); + function LabeledStatementSyntax(identifier, colonToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.colonToken = colonToken; + this.statement = statement; + } + LabeledStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitLabeledStatement(this); + }; + + LabeledStatementSyntax.prototype.kind = function () { + return 160 /* LabeledStatement */; + }; + + LabeledStatementSyntax.prototype.childCount = function () { + return 3; + }; + + LabeledStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.colonToken; + case 2: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + LabeledStatementSyntax.prototype.isStatement = function () { + return true; + }; + + LabeledStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + LabeledStatementSyntax.prototype.update = function (identifier, colonToken, statement) { + if (this.identifier === identifier && this.colonToken === colonToken && this.statement === statement) { + return this; + } + + return new LabeledStatementSyntax(identifier, colonToken, statement, this.parsedInStrictMode()); + }; + + LabeledStatementSyntax.create1 = function (identifier, statement) { + return new LabeledStatementSyntax(identifier, TypeScript.Syntax.token(106 /* ColonToken */), statement, false); + }; + + LabeledStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + LabeledStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + LabeledStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.colonToken, this.statement); + }; + + LabeledStatementSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.identifier, colonToken, this.statement); + }; + + LabeledStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.identifier, this.colonToken, statement); + }; + + LabeledStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return LabeledStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.LabeledStatementSyntax = LabeledStatementSyntax; + + var DoStatementSyntax = (function (_super) { + __extends(DoStatementSyntax, _super); + function DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.doKeyword = doKeyword; + this.statement = statement; + this.whileKeyword = whileKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.semicolonToken = semicolonToken; + } + DoStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitDoStatement(this); + }; + + DoStatementSyntax.prototype.kind = function () { + return 161 /* DoStatement */; + }; + + DoStatementSyntax.prototype.childCount = function () { + return 7; + }; + + DoStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.doKeyword; + case 1: + return this.statement; + case 2: + return this.whileKeyword; + case 3: + return this.openParenToken; + case 4: + return this.condition; + case 5: + return this.closeParenToken; + case 6: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DoStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + DoStatementSyntax.prototype.isStatement = function () { + return true; + }; + + DoStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + DoStatementSyntax.prototype.update = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + if (this.doKeyword === doKeyword && this.statement === statement && this.whileKeyword === whileKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.semicolonToken === semicolonToken) { + return this; + } + + return new DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, this.parsedInStrictMode()); + }; + + DoStatementSyntax.create1 = function (statement, condition) { + return new DoStatementSyntax(TypeScript.Syntax.token(22 /* DoKeyword */), statement, TypeScript.Syntax.token(42 /* WhileKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + DoStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DoStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DoStatementSyntax.prototype.withDoKeyword = function (doKeyword) { + return this.update(doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.doKeyword, statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withWhileKeyword = function (whileKeyword) { + return this.update(this.doKeyword, this.statement, whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, semicolonToken); + }; + + DoStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + if (this.condition.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DoStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DoStatementSyntax = DoStatementSyntax; + + var TypeOfExpressionSyntax = (function (_super) { + __extends(TypeOfExpressionSyntax, _super); + function TypeOfExpressionSyntax(typeOfKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeOfKeyword = typeOfKeyword; + this.expression = expression; + } + TypeOfExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeOfExpression(this); + }; + + TypeOfExpressionSyntax.prototype.kind = function () { + return 171 /* TypeOfExpression */; + }; + + TypeOfExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + TypeOfExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeOfKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeOfExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + TypeOfExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + TypeOfExpressionSyntax.prototype.update = function (typeOfKeyword, expression) { + if (this.typeOfKeyword === typeOfKeyword && this.expression === expression) { + return this; + } + + return new TypeOfExpressionSyntax(typeOfKeyword, expression, this.parsedInStrictMode()); + }; + + TypeOfExpressionSyntax.create1 = function (expression) { + return new TypeOfExpressionSyntax(TypeScript.Syntax.token(39 /* TypeOfKeyword */), expression, false); + }; + + TypeOfExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeOfExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeOfExpressionSyntax.prototype.withTypeOfKeyword = function (typeOfKeyword) { + return this.update(typeOfKeyword, this.expression); + }; + + TypeOfExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.typeOfKeyword, expression); + }; + + TypeOfExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return TypeOfExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeOfExpressionSyntax = TypeOfExpressionSyntax; + + var DeleteExpressionSyntax = (function (_super) { + __extends(DeleteExpressionSyntax, _super); + function DeleteExpressionSyntax(deleteKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.deleteKeyword = deleteKeyword; + this.expression = expression; + } + DeleteExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitDeleteExpression(this); + }; + + DeleteExpressionSyntax.prototype.kind = function () { + return 170 /* DeleteExpression */; + }; + + DeleteExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + DeleteExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.deleteKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DeleteExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + DeleteExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + DeleteExpressionSyntax.prototype.update = function (deleteKeyword, expression) { + if (this.deleteKeyword === deleteKeyword && this.expression === expression) { + return this; + } + + return new DeleteExpressionSyntax(deleteKeyword, expression, this.parsedInStrictMode()); + }; + + DeleteExpressionSyntax.create1 = function (expression) { + return new DeleteExpressionSyntax(TypeScript.Syntax.token(21 /* DeleteKeyword */), expression, false); + }; + + DeleteExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DeleteExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DeleteExpressionSyntax.prototype.withDeleteKeyword = function (deleteKeyword) { + return this.update(deleteKeyword, this.expression); + }; + + DeleteExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.deleteKeyword, expression); + }; + + DeleteExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DeleteExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DeleteExpressionSyntax = DeleteExpressionSyntax; + + var VoidExpressionSyntax = (function (_super) { + __extends(VoidExpressionSyntax, _super); + function VoidExpressionSyntax(voidKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.voidKeyword = voidKeyword; + this.expression = expression; + } + VoidExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitVoidExpression(this); + }; + + VoidExpressionSyntax.prototype.kind = function () { + return 172 /* VoidExpression */; + }; + + VoidExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + VoidExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.voidKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VoidExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + VoidExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + VoidExpressionSyntax.prototype.update = function (voidKeyword, expression) { + if (this.voidKeyword === voidKeyword && this.expression === expression) { + return this; + } + + return new VoidExpressionSyntax(voidKeyword, expression, this.parsedInStrictMode()); + }; + + VoidExpressionSyntax.create1 = function (expression) { + return new VoidExpressionSyntax(TypeScript.Syntax.token(41 /* VoidKeyword */), expression, false); + }; + + VoidExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VoidExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VoidExpressionSyntax.prototype.withVoidKeyword = function (voidKeyword) { + return this.update(voidKeyword, this.expression); + }; + + VoidExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.voidKeyword, expression); + }; + + VoidExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VoidExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VoidExpressionSyntax = VoidExpressionSyntax; + + var DebuggerStatementSyntax = (function (_super) { + __extends(DebuggerStatementSyntax, _super); + function DebuggerStatementSyntax(debuggerKeyword, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.debuggerKeyword = debuggerKeyword; + this.semicolonToken = semicolonToken; + } + DebuggerStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitDebuggerStatement(this); + }; + + DebuggerStatementSyntax.prototype.kind = function () { + return 162 /* DebuggerStatement */; + }; + + DebuggerStatementSyntax.prototype.childCount = function () { + return 2; + }; + + DebuggerStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.debuggerKeyword; + case 1: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DebuggerStatementSyntax.prototype.isStatement = function () { + return true; + }; + + DebuggerStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + DebuggerStatementSyntax.prototype.update = function (debuggerKeyword, semicolonToken) { + if (this.debuggerKeyword === debuggerKeyword && this.semicolonToken === semicolonToken) { + return this; + } + + return new DebuggerStatementSyntax(debuggerKeyword, semicolonToken, this.parsedInStrictMode()); + }; + + DebuggerStatementSyntax.create1 = function () { + return new DebuggerStatementSyntax(TypeScript.Syntax.token(19 /* DebuggerKeyword */), TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + DebuggerStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DebuggerStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DebuggerStatementSyntax.prototype.withDebuggerKeyword = function (debuggerKeyword) { + return this.update(debuggerKeyword, this.semicolonToken); + }; + + DebuggerStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.debuggerKeyword, semicolonToken); + }; + + DebuggerStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return DebuggerStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DebuggerStatementSyntax = DebuggerStatementSyntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxRewriter = (function () { + function SyntaxRewriter() { + } + SyntaxRewriter.prototype.visitToken = function (token) { + return token; + }; + + SyntaxRewriter.prototype.visitNode = function (node) { + return node.accept(this); + }; + + SyntaxRewriter.prototype.visitNodeOrToken = function (node) { + return node.isToken() ? this.visitToken(node) : this.visitNode(node); + }; + + SyntaxRewriter.prototype.visitList = function (list) { + var newItems = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + var newItem = this.visitNodeOrToken(item); + + if (item !== newItem && newItems === null) { + newItems = []; + for (var j = 0; j < i; j++) { + newItems.push(list.childAt(j)); + } + } + + if (newItems) { + newItems.push(newItem); + } + } + + return newItems === null ? list : TypeScript.Syntax.list(newItems); + }; + + SyntaxRewriter.prototype.visitSeparatedList = function (list) { + var newItems = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + var newItem = item.isToken() ? this.visitToken(item) : this.visitNode(item); + + if (item !== newItem && newItems === null) { + newItems = []; + for (var j = 0; j < i; j++) { + newItems.push(list.childAt(j)); + } + } + + if (newItems) { + newItems.push(newItem); + } + } + + return newItems === null ? list : TypeScript.Syntax.separatedList(newItems); + }; + + SyntaxRewriter.prototype.visitSourceUnit = function (node) { + return node.update(this.visitList(node.moduleElements), this.visitToken(node.endOfFileToken)); + }; + + SyntaxRewriter.prototype.visitExternalModuleReference = function (node) { + return node.update(this.visitToken(node.requireKeyword), this.visitToken(node.openParenToken), this.visitToken(node.stringLiteral), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitModuleNameModuleReference = function (node) { + return node.update(this.visitNodeOrToken(node.moduleName)); + }; + + SyntaxRewriter.prototype.visitImportDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.importKeyword), this.visitToken(node.identifier), this.visitToken(node.equalsToken), this.visitNodeOrToken(node.moduleReference), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitExportAssignment = function (node) { + return node.update(this.visitToken(node.exportKeyword), this.visitToken(node.equalsToken), this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitClassDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.classKeyword), this.visitToken(node.identifier), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitList(node.heritageClauses), this.visitToken(node.openBraceToken), this.visitList(node.classElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitInterfaceDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.interfaceKeyword), this.visitToken(node.identifier), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitList(node.heritageClauses), this.visitNode(node.body)); + }; + + SyntaxRewriter.prototype.visitHeritageClause = function (node) { + return node.update(node.kind(), this.visitToken(node.extendsOrImplementsKeyword), this.visitSeparatedList(node.typeNames)); + }; + + SyntaxRewriter.prototype.visitModuleDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.moduleKeyword), node.name === null ? null : this.visitNodeOrToken(node.name), node.stringLiteral === null ? null : this.visitToken(node.stringLiteral), this.visitToken(node.openBraceToken), this.visitList(node.moduleElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitFunctionDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.functionKeyword), this.visitToken(node.identifier), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitVariableStatement = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.variableDeclaration), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitVariableDeclaration = function (node) { + return node.update(this.visitToken(node.varKeyword), this.visitSeparatedList(node.variableDeclarators)); + }; + + SyntaxRewriter.prototype.visitVariableDeclarator = function (node) { + return node.update(this.visitToken(node.propertyName), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitEqualsValueClause = function (node) { + return node.update(this.visitToken(node.equalsToken), this.visitNodeOrToken(node.value)); + }; + + SyntaxRewriter.prototype.visitPrefixUnaryExpression = function (node) { + return node.update(node.kind(), this.visitToken(node.operatorToken), this.visitNodeOrToken(node.operand)); + }; + + SyntaxRewriter.prototype.visitArrayLiteralExpression = function (node) { + return node.update(this.visitToken(node.openBracketToken), this.visitSeparatedList(node.expressions), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitOmittedExpression = function (node) { + return node; + }; + + SyntaxRewriter.prototype.visitParenthesizedExpression = function (node) { + return node.update(this.visitToken(node.openParenToken), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitSimpleArrowFunctionExpression = function (node) { + return node.update(this.visitToken(node.identifier), this.visitToken(node.equalsGreaterThanToken), node.block === null ? null : this.visitNode(node.block), node.expression === null ? null : this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + return node.update(this.visitNode(node.callSignature), this.visitToken(node.equalsGreaterThanToken), node.block === null ? null : this.visitNode(node.block), node.expression === null ? null : this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitQualifiedName = function (node) { + return node.update(this.visitNodeOrToken(node.left), this.visitToken(node.dotToken), this.visitToken(node.right)); + }; + + SyntaxRewriter.prototype.visitTypeArgumentList = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitSeparatedList(node.typeArguments), this.visitToken(node.greaterThanToken)); + }; + + SyntaxRewriter.prototype.visitConstructorType = function (node) { + return node.update(this.visitToken(node.newKeyword), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitFunctionType = function (node) { + return node.update(node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitObjectType = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitSeparatedList(node.typeMembers), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitArrayType = function (node) { + return node.update(this.visitNodeOrToken(node.type), this.visitToken(node.openBracketToken), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitGenericType = function (node) { + return node.update(this.visitNodeOrToken(node.name), this.visitNode(node.typeArgumentList)); + }; + + SyntaxRewriter.prototype.visitTypeQuery = function (node) { + return node.update(this.visitToken(node.typeOfKeyword), this.visitNodeOrToken(node.name)); + }; + + SyntaxRewriter.prototype.visitTypeAnnotation = function (node) { + return node.update(this.visitToken(node.colonToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitBlock = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitList(node.statements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitParameter = function (node) { + return node.update(node.dotDotDotToken === null ? null : this.visitToken(node.dotDotDotToken), this.visitList(node.modifiers), this.visitToken(node.identifier), node.questionToken === null ? null : this.visitToken(node.questionToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitMemberAccessExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.dotToken), this.visitToken(node.name)); + }; + + SyntaxRewriter.prototype.visitPostfixUnaryExpression = function (node) { + return node.update(node.kind(), this.visitNodeOrToken(node.operand), this.visitToken(node.operatorToken)); + }; + + SyntaxRewriter.prototype.visitElementAccessExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.openBracketToken), this.visitNodeOrToken(node.argumentExpression), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitInvocationExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitNode(node.argumentList)); + }; + + SyntaxRewriter.prototype.visitArgumentList = function (node) { + return node.update(node.typeArgumentList === null ? null : this.visitNode(node.typeArgumentList), this.visitToken(node.openParenToken), this.visitSeparatedList(node.arguments), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitBinaryExpression = function (node) { + return node.update(node.kind(), this.visitNodeOrToken(node.left), this.visitToken(node.operatorToken), this.visitNodeOrToken(node.right)); + }; + + SyntaxRewriter.prototype.visitConditionalExpression = function (node) { + return node.update(this.visitNodeOrToken(node.condition), this.visitToken(node.questionToken), this.visitNodeOrToken(node.whenTrue), this.visitToken(node.colonToken), this.visitNodeOrToken(node.whenFalse)); + }; + + SyntaxRewriter.prototype.visitConstructSignature = function (node) { + return node.update(this.visitToken(node.newKeyword), this.visitNode(node.callSignature)); + }; + + SyntaxRewriter.prototype.visitMethodSignature = function (node) { + return node.update(this.visitToken(node.propertyName), node.questionToken === null ? null : this.visitToken(node.questionToken), this.visitNode(node.callSignature)); + }; + + SyntaxRewriter.prototype.visitIndexSignature = function (node) { + return node.update(this.visitToken(node.openBracketToken), this.visitNode(node.parameter), this.visitToken(node.closeBracketToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitPropertySignature = function (node) { + return node.update(this.visitToken(node.propertyName), node.questionToken === null ? null : this.visitToken(node.questionToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitCallSignature = function (node) { + return node.update(node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitParameterList = function (node) { + return node.update(this.visitToken(node.openParenToken), this.visitSeparatedList(node.parameters), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitTypeParameterList = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitSeparatedList(node.typeParameters), this.visitToken(node.greaterThanToken)); + }; + + SyntaxRewriter.prototype.visitTypeParameter = function (node) { + return node.update(this.visitToken(node.identifier), node.constraint === null ? null : this.visitNode(node.constraint)); + }; + + SyntaxRewriter.prototype.visitConstraint = function (node) { + return node.update(this.visitToken(node.extendsKeyword), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitElseClause = function (node) { + return node.update(this.visitToken(node.elseKeyword), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitIfStatement = function (node) { + return node.update(this.visitToken(node.ifKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement), node.elseClause === null ? null : this.visitNode(node.elseClause)); + }; + + SyntaxRewriter.prototype.visitExpressionStatement = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitConstructorDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.constructorKeyword), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitMemberFunctionDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.propertyName), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitGetAccessor = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.getKeyword), this.visitToken(node.propertyName), this.visitNode(node.parameterList), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitSetAccessor = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.setKeyword), this.visitToken(node.propertyName), this.visitNode(node.parameterList), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitMemberVariableDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.variableDeclarator), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitIndexMemberDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.indexSignature), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitThrowStatement = function (node) { + return node.update(this.visitToken(node.throwKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitReturnStatement = function (node) { + return node.update(this.visitToken(node.returnKeyword), node.expression === null ? null : this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitObjectCreationExpression = function (node) { + return node.update(this.visitToken(node.newKeyword), this.visitNodeOrToken(node.expression), node.argumentList === null ? null : this.visitNode(node.argumentList)); + }; + + SyntaxRewriter.prototype.visitSwitchStatement = function (node) { + return node.update(this.visitToken(node.switchKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken), this.visitToken(node.openBraceToken), this.visitList(node.switchClauses), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitCaseSwitchClause = function (node) { + return node.update(this.visitToken(node.caseKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.colonToken), this.visitList(node.statements)); + }; + + SyntaxRewriter.prototype.visitDefaultSwitchClause = function (node) { + return node.update(this.visitToken(node.defaultKeyword), this.visitToken(node.colonToken), this.visitList(node.statements)); + }; + + SyntaxRewriter.prototype.visitBreakStatement = function (node) { + return node.update(this.visitToken(node.breakKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitContinueStatement = function (node) { + return node.update(this.visitToken(node.continueKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitForStatement = function (node) { + return node.update(this.visitToken(node.forKeyword), this.visitToken(node.openParenToken), node.variableDeclaration === null ? null : this.visitNode(node.variableDeclaration), node.initializer === null ? null : this.visitNodeOrToken(node.initializer), this.visitToken(node.firstSemicolonToken), node.condition === null ? null : this.visitNodeOrToken(node.condition), this.visitToken(node.secondSemicolonToken), node.incrementor === null ? null : this.visitNodeOrToken(node.incrementor), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitForInStatement = function (node) { + return node.update(this.visitToken(node.forKeyword), this.visitToken(node.openParenToken), node.variableDeclaration === null ? null : this.visitNode(node.variableDeclaration), node.left === null ? null : this.visitNodeOrToken(node.left), this.visitToken(node.inKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitWhileStatement = function (node) { + return node.update(this.visitToken(node.whileKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitWithStatement = function (node) { + return node.update(this.visitToken(node.withKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitEnumDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.enumKeyword), this.visitToken(node.identifier), this.visitToken(node.openBraceToken), this.visitSeparatedList(node.enumElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitEnumElement = function (node) { + return node.update(this.visitToken(node.propertyName), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitCastExpression = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitNodeOrToken(node.type), this.visitToken(node.greaterThanToken), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitObjectLiteralExpression = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitSeparatedList(node.propertyAssignments), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitSimplePropertyAssignment = function (node) { + return node.update(this.visitToken(node.propertyName), this.visitToken(node.colonToken), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitFunctionPropertyAssignment = function (node) { + return node.update(this.visitToken(node.propertyName), this.visitNode(node.callSignature), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitFunctionExpression = function (node) { + return node.update(this.visitToken(node.functionKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitNode(node.callSignature), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitEmptyStatement = function (node) { + return node.update(this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitTryStatement = function (node) { + return node.update(this.visitToken(node.tryKeyword), this.visitNode(node.block), node.catchClause === null ? null : this.visitNode(node.catchClause), node.finallyClause === null ? null : this.visitNode(node.finallyClause)); + }; + + SyntaxRewriter.prototype.visitCatchClause = function (node) { + return node.update(this.visitToken(node.catchKeyword), this.visitToken(node.openParenToken), this.visitToken(node.identifier), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), this.visitToken(node.closeParenToken), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitFinallyClause = function (node) { + return node.update(this.visitToken(node.finallyKeyword), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitLabeledStatement = function (node) { + return node.update(this.visitToken(node.identifier), this.visitToken(node.colonToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitDoStatement = function (node) { + return node.update(this.visitToken(node.doKeyword), this.visitNodeOrToken(node.statement), this.visitToken(node.whileKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitTypeOfExpression = function (node) { + return node.update(this.visitToken(node.typeOfKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitDeleteExpression = function (node) { + return node.update(this.visitToken(node.deleteKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitVoidExpression = function (node) { + return node.update(this.visitToken(node.voidKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitDebuggerStatement = function (node) { + return node.update(this.visitToken(node.debuggerKeyword), this.visitToken(node.semicolonToken)); + }; + return SyntaxRewriter; + })(); + TypeScript.SyntaxRewriter = SyntaxRewriter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxDedenter = (function (_super) { + __extends(SyntaxDedenter, _super); + function SyntaxDedenter(dedentFirstToken, dedentationAmount, minimumIndent, options) { + _super.call(this); + this.dedentationAmount = dedentationAmount; + this.minimumIndent = minimumIndent; + this.options = options; + this.lastTriviaWasNewLine = dedentFirstToken; + } + SyntaxDedenter.prototype.abort = function () { + this.lastTriviaWasNewLine = false; + this.dedentationAmount = 0; + }; + + SyntaxDedenter.prototype.isAborted = function () { + return this.dedentationAmount === 0; + }; + + SyntaxDedenter.prototype.visitToken = function (token) { + if (token.width() === 0) { + return token; + } + + var result = token; + if (this.lastTriviaWasNewLine) { + result = token.withLeadingTrivia(this.dedentTriviaList(token.leadingTrivia())); + } + + if (this.isAborted()) { + return token; + } + + this.lastTriviaWasNewLine = token.hasTrailingNewLine(); + return result; + }; + + SyntaxDedenter.prototype.dedentTriviaList = function (triviaList) { + var result = []; + var dedentNextWhitespace = true; + + for (var i = 0, n = triviaList.count(); i < n && !this.isAborted(); i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + var dedentThisTrivia = dedentNextWhitespace; + dedentNextWhitespace = false; + + if (dedentThisTrivia) { + if (trivia.kind() === 4 /* WhitespaceTrivia */) { + var hasFollowingNewLine = (i < triviaList.count() - 1) && triviaList.syntaxTriviaAt(i + 1).kind() === 5 /* NewLineTrivia */; + result.push(this.dedentWhitespace(trivia, hasFollowingNewLine)); + continue; + } else if (trivia.kind() !== 5 /* NewLineTrivia */) { + this.abort(); + break; + } + } + + if (trivia.kind() === 6 /* MultiLineCommentTrivia */) { + result.push(this.dedentMultiLineComment(trivia)); + continue; + } + + result.push(trivia); + if (trivia.kind() === 5 /* NewLineTrivia */) { + dedentNextWhitespace = true; + } + } + + if (dedentNextWhitespace) { + this.abort(); + } + + if (this.isAborted()) { + return triviaList; + } + + return TypeScript.Syntax.triviaList(result); + }; + + SyntaxDedenter.prototype.dedentSegment = function (segment, hasFollowingNewLineTrivia) { + var firstNonWhitespacePosition = TypeScript.Indentation.firstNonWhitespacePosition(segment); + + if (firstNonWhitespacePosition === segment.length) { + if (hasFollowingNewLineTrivia) { + return ""; + } + } else if (TypeScript.CharacterInfo.isLineTerminator(segment.charCodeAt(firstNonWhitespacePosition))) { + return segment.substring(firstNonWhitespacePosition); + } + + var firstNonWhitespaceColumn = TypeScript.Indentation.columnForPositionInString(segment, firstNonWhitespacePosition, this.options); + + var newFirstNonWhitespaceColumn = TypeScript.MathPrototype.min(firstNonWhitespaceColumn, TypeScript.MathPrototype.max(firstNonWhitespaceColumn - this.dedentationAmount, this.minimumIndent)); + + if (newFirstNonWhitespaceColumn === firstNonWhitespaceColumn) { + this.abort(); + return segment; + } + + this.dedentationAmount = firstNonWhitespaceColumn - newFirstNonWhitespaceColumn; + TypeScript.Debug.assert(this.dedentationAmount >= 0); + + var indentationString = TypeScript.Indentation.indentationString(newFirstNonWhitespaceColumn, this.options); + + return indentationString + segment.substring(firstNonWhitespacePosition); + }; + + SyntaxDedenter.prototype.dedentWhitespace = function (trivia, hasFollowingNewLineTrivia) { + var newIndentation = this.dedentSegment(trivia.fullText(), hasFollowingNewLineTrivia); + return TypeScript.Syntax.whitespace(newIndentation); + }; + + SyntaxDedenter.prototype.dedentMultiLineComment = function (trivia) { + var segments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + if (segments.length === 1) { + return trivia; + } + + for (var i = 1; i < segments.length; i++) { + var segment = segments[i]; + segments[i] = this.dedentSegment(segment, false); + } + + var result = segments.join(""); + + return TypeScript.Syntax.multiLineComment(result); + }; + + SyntaxDedenter.dedentNode = function (node, dedentFirstToken, dedentAmount, minimumIndent, options) { + var dedenter = new SyntaxDedenter(dedentFirstToken, dedentAmount, minimumIndent, options); + var result = node.accept(dedenter); + + if (dedenter.isAborted()) { + return node; + } + + return result; + }; + return SyntaxDedenter; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxDedenter = SyntaxDedenter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxIndenter = (function (_super) { + __extends(SyntaxIndenter, _super); + function SyntaxIndenter(indentFirstToken, indentationAmount, options) { + _super.call(this); + this.indentationAmount = indentationAmount; + this.options = options; + this.lastTriviaWasNewLine = indentFirstToken; + this.indentationTrivia = TypeScript.Indentation.indentationTrivia(this.indentationAmount, this.options); + } + SyntaxIndenter.prototype.visitToken = function (token) { + if (token.width() === 0) { + return token; + } + + var result = token; + if (this.lastTriviaWasNewLine) { + result = token.withLeadingTrivia(this.indentTriviaList(token.leadingTrivia())); + } + + this.lastTriviaWasNewLine = token.hasTrailingNewLine(); + return result; + }; + + SyntaxIndenter.prototype.indentTriviaList = function (triviaList) { + var result = []; + + var indentNextTrivia = true; + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + var indentThisTrivia = indentNextTrivia; + indentNextTrivia = false; + + switch (trivia.kind()) { + case 6 /* MultiLineCommentTrivia */: + this.indentMultiLineComment(trivia, indentThisTrivia, result); + continue; + + case 7 /* SingleLineCommentTrivia */: + case 8 /* SkippedTokenTrivia */: + this.indentSingleLineOrSkippedText(trivia, indentThisTrivia, result); + continue; + + case 4 /* WhitespaceTrivia */: + this.indentWhitespace(trivia, indentThisTrivia, result); + continue; + + case 5 /* NewLineTrivia */: + result.push(trivia); + indentNextTrivia = true; + continue; + + default: + throw TypeScript.Errors.invalidOperation(); + } + } + + if (indentNextTrivia) { + result.push(this.indentationTrivia); + } + + return TypeScript.Syntax.triviaList(result); + }; + + SyntaxIndenter.prototype.indentSegment = function (segment) { + var firstNonWhitespacePosition = TypeScript.Indentation.firstNonWhitespacePosition(segment); + + if (firstNonWhitespacePosition < segment.length && TypeScript.CharacterInfo.isLineTerminator(segment.charCodeAt(firstNonWhitespacePosition))) { + return segment; + } + + var firstNonWhitespaceColumn = TypeScript.Indentation.columnForPositionInString(segment, firstNonWhitespacePosition, this.options); + + var newFirstNonWhitespaceColumn = firstNonWhitespaceColumn + this.indentationAmount; + + var indentationString = TypeScript.Indentation.indentationString(newFirstNonWhitespaceColumn, this.options); + + return indentationString + segment.substring(firstNonWhitespacePosition); + }; + + SyntaxIndenter.prototype.indentWhitespace = function (trivia, indentThisTrivia, result) { + if (!indentThisTrivia) { + result.push(trivia); + return; + } + + var newIndentation = this.indentSegment(trivia.fullText()); + result.push(TypeScript.Syntax.whitespace(newIndentation)); + }; + + SyntaxIndenter.prototype.indentSingleLineOrSkippedText = function (trivia, indentThisTrivia, result) { + if (indentThisTrivia) { + result.push(this.indentationTrivia); + } + + result.push(trivia); + }; + + SyntaxIndenter.prototype.indentMultiLineComment = function (trivia, indentThisTrivia, result) { + if (indentThisTrivia) { + result.push(this.indentationTrivia); + } + + var segments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + + for (var i = 1; i < segments.length; i++) { + segments[i] = this.indentSegment(segments[i]); + } + + var newText = segments.join(""); + result.push(TypeScript.Syntax.multiLineComment(newText)); + }; + + SyntaxIndenter.indentNode = function (node, indentFirstToken, indentAmount, options) { + var indenter = new SyntaxIndenter(indentFirstToken, indentAmount, options); + return node.accept(indenter); + }; + + SyntaxIndenter.indentNodes = function (nodes, indentFirstToken, indentAmount, options) { + var indenter = new SyntaxIndenter(indentFirstToken, indentAmount, options); + var result = TypeScript.ArrayUtilities.select(nodes, function (n) { + return n.accept(indenter); + }); + + return result; + }; + return SyntaxIndenter; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxIndenter = SyntaxIndenter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var VariableWidthTokenWithNoTrivia = (function () { + function VariableWidthTokenWithNoTrivia(fullText, kind) { + this._fullText = fullText; + this.tokenKind = kind; + } + VariableWidthTokenWithNoTrivia.prototype.clone = function () { + return new VariableWidthTokenWithNoTrivia(this._fullText, this.tokenKind); + }; + + VariableWidthTokenWithNoTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithNoTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithNoTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithNoTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithNoTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithNoTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithNoTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithNoTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithNoTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithNoTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingComment = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingComment = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithNoTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithNoTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithNoTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithNoTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithNoTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithNoTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithNoTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithNoTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithNoTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithNoTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithNoTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithNoTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithNoTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithNoTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithNoTrivia; + })(); + Syntax.VariableWidthTokenWithNoTrivia = VariableWidthTokenWithNoTrivia; + + var VariableWidthTokenWithLeadingTrivia = (function () { + function VariableWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + } + VariableWidthTokenWithLeadingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithLeadingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithLeadingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithLeadingTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithLeadingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingComment = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithLeadingTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithLeadingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithLeadingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithLeadingTrivia; + })(); + Syntax.VariableWidthTokenWithLeadingTrivia = VariableWidthTokenWithLeadingTrivia; + + var VariableWidthTokenWithTrailingTrivia = (function () { + function VariableWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._trailingTriviaInfo = trailingTriviaInfo; + } + VariableWidthTokenWithTrailingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithTrailingTrivia(this._fullText, this.tokenKind, this._trailingTriviaInfo); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithTrailingTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingComment = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithTrailingTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithTrailingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithTrailingTrivia; + })(); + Syntax.VariableWidthTokenWithTrailingTrivia = VariableWidthTokenWithTrailingTrivia; + + var VariableWidthTokenWithLeadingAndTrailingTrivia = (function () { + function VariableWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + this._trailingTriviaInfo = trailingTriviaInfo; + } + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithLeadingAndTrailingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithLeadingAndTrailingTrivia; + })(); + Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia = VariableWidthTokenWithLeadingAndTrailingTrivia; + + var FixedWidthTokenWithNoTrivia = (function () { + function FixedWidthTokenWithNoTrivia(kind) { + this.tokenKind = kind; + } + FixedWidthTokenWithNoTrivia.prototype.clone = function () { + return new FixedWidthTokenWithNoTrivia(this.tokenKind); + }; + + FixedWidthTokenWithNoTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithNoTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithNoTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithNoTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithNoTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithNoTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithNoTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithNoTrivia.prototype.fullText = function () { + return this.text(); + }; + + FixedWidthTokenWithNoTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithNoTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingComment = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithNoTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingComment = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithNoTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithNoTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithNoTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithNoTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithNoTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithNoTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithNoTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithNoTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithNoTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithNoTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithNoTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithNoTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithNoTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithNoTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithNoTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithNoTrivia; + })(); + Syntax.FixedWidthTokenWithNoTrivia = FixedWidthTokenWithNoTrivia; + + var FixedWidthTokenWithLeadingTrivia = (function () { + function FixedWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + } + FixedWidthTokenWithLeadingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithLeadingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithLeadingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithLeadingTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithLeadingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingComment = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithLeadingTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithLeadingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithLeadingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithLeadingTrivia; + })(); + Syntax.FixedWidthTokenWithLeadingTrivia = FixedWidthTokenWithLeadingTrivia; + + var FixedWidthTokenWithTrailingTrivia = (function () { + function FixedWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._trailingTriviaInfo = trailingTriviaInfo; + } + FixedWidthTokenWithTrailingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithTrailingTrivia(this._fullText, this.tokenKind, this._trailingTriviaInfo); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithTrailingTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingComment = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithTrailingTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithTrailingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithTrailingTrivia; + })(); + Syntax.FixedWidthTokenWithTrailingTrivia = FixedWidthTokenWithTrailingTrivia; + + var FixedWidthTokenWithLeadingAndTrailingTrivia = (function () { + function FixedWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + this._trailingTriviaInfo = trailingTriviaInfo; + } + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithLeadingAndTrailingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithLeadingAndTrailingTrivia; + })(); + Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia = FixedWidthTokenWithLeadingAndTrailingTrivia; + + function collectTokenTextElements(token, elements) { + token.leadingTrivia().collectTextElements(elements); + elements.push(token.text()); + token.trailingTrivia().collectTextElements(elements); + } + + function getTriviaWidth(value) { + return value >>> 2 /* TriviaFullWidthShift */; + } + + function hasTriviaComment(value) { + return (value & 2 /* TriviaCommentMask */) !== 0; + } + + function hasTriviaNewLine(value) { + return (value & 1 /* TriviaNewLineMask */) !== 0; + } + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + function isExpression(token) { + switch (token.tokenKind) { + case 11 /* IdentifierName */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NumericLiteral */: + case 14 /* StringLiteral */: + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 50 /* SuperKeyword */: + return true; + } + + return false; + } + Syntax.isExpression = isExpression; + + function realizeToken(token) { + return new RealizedToken(token.tokenKind, token.leadingTrivia(), token.text(), token.value(), token.valueText(), token.trailingTrivia()); + } + Syntax.realizeToken = realizeToken; + + function convertToIdentifierName(token) { + TypeScript.Debug.assert(TypeScript.SyntaxFacts.isAnyKeyword(token.tokenKind)); + return new RealizedToken(11 /* IdentifierName */, token.leadingTrivia(), token.text(), token.text(), token.text(), token.trailingTrivia()); + } + Syntax.convertToIdentifierName = convertToIdentifierName; + + function tokenToJSON(token) { + var result = {}; + + for (var name in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind[name] === token.kind()) { + result.kind = name; + break; + } + } + + result.width = token.width(); + if (token.fullWidth() !== token.width()) { + result.fullWidth = token.fullWidth(); + } + + result.text = token.text(); + + var value = token.value(); + if (value !== null) { + result.value = value; + result.valueText = token.valueText(); + } + + if (token.hasLeadingTrivia()) { + result.hasLeadingTrivia = true; + } + + if (token.hasLeadingComment()) { + result.hasLeadingComment = true; + } + + if (token.hasLeadingNewLine()) { + result.hasLeadingNewLine = true; + } + + if (token.hasLeadingSkippedText()) { + result.hasLeadingSkippedText = true; + } + + if (token.hasTrailingTrivia()) { + result.hasTrailingTrivia = true; + } + + if (token.hasTrailingComment()) { + result.hasTrailingComment = true; + } + + if (token.hasTrailingNewLine()) { + result.hasTrailingNewLine = true; + } + + if (token.hasTrailingSkippedText()) { + result.hasTrailingSkippedText = true; + } + + var trivia = token.leadingTrivia(); + if (trivia.count() > 0) { + result.leadingTrivia = trivia; + } + + trivia = token.trailingTrivia(); + if (trivia.count() > 0) { + result.trailingTrivia = trivia; + } + + return result; + } + Syntax.tokenToJSON = tokenToJSON; + + function value(token) { + return value1(token.tokenKind, token.text()); + } + Syntax.value = value; + + function hexValue(text, start, length) { + var intChar = 0; + for (var i = 0; i < length; i++) { + var ch2 = text.charCodeAt(start + i); + if (!TypeScript.CharacterInfo.isHexDigit(ch2)) { + break; + } + + intChar = (intChar << 4) + TypeScript.CharacterInfo.hexValue(ch2); + } + + return intChar; + } + + var characterArray = []; + + function convertEscapes(text) { + characterArray.length = 0; + var result = ""; + + for (var i = 0, n = text.length; i < n; i++) { + var ch = text.charCodeAt(i); + + if (ch === 92 /* backslash */) { + i++; + if (i < n) { + ch = text.charCodeAt(i); + switch (ch) { + case 48 /* _0 */: + characterArray.push(0 /* nullCharacter */); + continue; + + case 98 /* b */: + characterArray.push(8 /* backspace */); + continue; + + case 102 /* f */: + characterArray.push(12 /* formFeed */); + continue; + + case 110 /* n */: + characterArray.push(10 /* lineFeed */); + continue; + + case 114 /* r */: + characterArray.push(13 /* carriageReturn */); + continue; + + case 116 /* t */: + characterArray.push(9 /* tab */); + continue; + + case 118 /* v */: + characterArray.push(11 /* verticalTab */); + continue; + + case 120 /* x */: + characterArray.push(hexValue(text, i + 1, 2)); + i += 2; + continue; + + case 117 /* u */: + characterArray.push(hexValue(text, i + 1, 4)); + i += 4; + continue; + + case 13 /* carriageReturn */: + var nextIndex = i + 1; + if (nextIndex < text.length && text.charCodeAt(nextIndex) === 10 /* lineFeed */) { + i++; + } + continue; + + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + continue; + + default: + } + } + } + + characterArray.push(ch); + + if (i && !(i % 1024)) { + result = result.concat(String.fromCharCode.apply(null, characterArray)); + characterArray.length = 0; + } + } + + if (characterArray.length) { + result = result.concat(String.fromCharCode.apply(null, characterArray)); + } + + return result; + } + + function massageEscapes(text) { + return text.indexOf("\\") >= 0 ? convertEscapes(text) : text; + } + Syntax.massageEscapes = massageEscapes; + + function value1(kind, text) { + if (kind === 11 /* IdentifierName */) { + return massageEscapes(text); + } + + switch (kind) { + case 37 /* TrueKeyword */: + return true; + case 24 /* FalseKeyword */: + return false; + case 32 /* NullKeyword */: + return null; + } + + if (TypeScript.SyntaxFacts.isAnyKeyword(kind) || TypeScript.SyntaxFacts.isAnyPunctuation(kind)) { + return TypeScript.SyntaxFacts.getText(kind); + } + + if (kind === 13 /* NumericLiteral */) { + return TypeScript.IntegerUtilities.isHexInteger(text) ? parseInt(text, 16) : parseFloat(text); + } else if (kind === 14 /* StringLiteral */) { + if (text.length > 1 && text.charCodeAt(text.length - 1) === text.charCodeAt(0)) { + return massageEscapes(text.substr(1, text.length - 2)); + } else { + return massageEscapes(text.substr(1)); + } + } else if (kind === 12 /* RegularExpressionLiteral */) { + return regularExpressionValue(text); + } else if (kind === 10 /* EndOfFileToken */ || kind === 9 /* ErrorToken */) { + return null; + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + + function regularExpressionValue(text) { + try { + var lastSlash = text.lastIndexOf("/"); + var body = text.substring(1, lastSlash); + var flags = text.substring(lastSlash + 1); + return new RegExp(body, flags); + } catch (e) { + return null; + } + } + + function valueText1(kind, text) { + var value = value1(kind, text); + return value === null ? "" : value.toString(); + } + + function valueText(token) { + var value = token.value(); + return value === null ? "" : value.toString(); + } + Syntax.valueText = valueText; + + var EmptyToken = (function () { + function EmptyToken(kind) { + this.tokenKind = kind; + } + EmptyToken.prototype.clone = function () { + return new EmptyToken(this.tokenKind); + }; + + EmptyToken.prototype.kind = function () { + return this.tokenKind; + }; + + EmptyToken.prototype.isToken = function () { + return true; + }; + EmptyToken.prototype.isNode = function () { + return false; + }; + EmptyToken.prototype.isList = function () { + return false; + }; + EmptyToken.prototype.isSeparatedList = function () { + return false; + }; + + EmptyToken.prototype.childCount = function () { + return 0; + }; + + EmptyToken.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptyToken.prototype.toJSON = function (key) { + return tokenToJSON(this); + }; + EmptyToken.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + + EmptyToken.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + EmptyToken.prototype.firstToken = function () { + return this; + }; + EmptyToken.prototype.lastToken = function () { + return this; + }; + EmptyToken.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptyToken.prototype.isIncrementallyUnusable = function () { + return true; + }; + + EmptyToken.prototype.fullWidth = function () { + return 0; + }; + EmptyToken.prototype.width = function () { + return 0; + }; + EmptyToken.prototype.text = function () { + return ""; + }; + EmptyToken.prototype.fullText = function () { + return ""; + }; + EmptyToken.prototype.value = function () { + return null; + }; + EmptyToken.prototype.valueText = function () { + return ""; + }; + + EmptyToken.prototype.hasLeadingTrivia = function () { + return false; + }; + EmptyToken.prototype.hasLeadingComment = function () { + return false; + }; + EmptyToken.prototype.hasLeadingNewLine = function () { + return false; + }; + EmptyToken.prototype.hasLeadingSkippedText = function () { + return false; + }; + EmptyToken.prototype.leadingTriviaWidth = function () { + return 0; + }; + EmptyToken.prototype.hasTrailingTrivia = function () { + return false; + }; + EmptyToken.prototype.hasTrailingComment = function () { + return false; + }; + EmptyToken.prototype.hasTrailingNewLine = function () { + return false; + }; + EmptyToken.prototype.hasTrailingSkippedText = function () { + return false; + }; + EmptyToken.prototype.hasSkippedToken = function () { + return false; + }; + + EmptyToken.prototype.trailingTriviaWidth = function () { + return 0; + }; + EmptyToken.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + EmptyToken.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + EmptyToken.prototype.realize = function () { + return realizeToken(this); + }; + EmptyToken.prototype.collectTextElements = function (elements) { + }; + + EmptyToken.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + EmptyToken.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + EmptyToken.prototype.isExpression = function () { + return isExpression(this); + }; + + EmptyToken.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + EmptyToken.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + EmptyToken.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + EmptyToken.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return EmptyToken; + })(); + + function emptyToken(kind) { + return new EmptyToken(kind); + } + Syntax.emptyToken = emptyToken; + + var RealizedToken = (function () { + function RealizedToken(tokenKind, leadingTrivia, text, value, valueText, trailingTrivia) { + this.tokenKind = tokenKind; + this._leadingTrivia = leadingTrivia; + this._text = text; + this._value = value; + this._valueText = valueText; + this._trailingTrivia = trailingTrivia; + } + RealizedToken.prototype.clone = function () { + return new RealizedToken(this.tokenKind, this._leadingTrivia, this._text, this._value, this._valueText, this._trailingTrivia); + }; + + RealizedToken.prototype.kind = function () { + return this.tokenKind; + }; + RealizedToken.prototype.toJSON = function (key) { + return tokenToJSON(this); + }; + RealizedToken.prototype.firstToken = function () { + return this; + }; + RealizedToken.prototype.lastToken = function () { + return this; + }; + RealizedToken.prototype.isTypeScriptSpecific = function () { + return false; + }; + + RealizedToken.prototype.isIncrementallyUnusable = function () { + return true; + }; + + RealizedToken.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + + RealizedToken.prototype.childCount = function () { + return 0; + }; + + RealizedToken.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + RealizedToken.prototype.isToken = function () { + return true; + }; + RealizedToken.prototype.isNode = function () { + return false; + }; + RealizedToken.prototype.isList = function () { + return false; + }; + RealizedToken.prototype.isSeparatedList = function () { + return false; + }; + RealizedToken.prototype.isTrivia = function () { + return false; + }; + RealizedToken.prototype.isTriviaList = function () { + return false; + }; + + RealizedToken.prototype.fullWidth = function () { + return this._leadingTrivia.fullWidth() + this.width() + this._trailingTrivia.fullWidth(); + }; + RealizedToken.prototype.width = function () { + return this.text().length; + }; + + RealizedToken.prototype.text = function () { + return this._text; + }; + RealizedToken.prototype.fullText = function () { + return this._leadingTrivia.fullText() + this.text() + this._trailingTrivia.fullText(); + }; + + RealizedToken.prototype.value = function () { + return this._value; + }; + RealizedToken.prototype.valueText = function () { + return this._valueText; + }; + + RealizedToken.prototype.hasLeadingTrivia = function () { + return this._leadingTrivia.count() > 0; + }; + RealizedToken.prototype.hasLeadingComment = function () { + return this._leadingTrivia.hasComment(); + }; + RealizedToken.prototype.hasLeadingNewLine = function () { + return this._leadingTrivia.hasNewLine(); + }; + RealizedToken.prototype.hasLeadingSkippedText = function () { + return this._leadingTrivia.hasSkippedToken(); + }; + RealizedToken.prototype.leadingTriviaWidth = function () { + return this._leadingTrivia.fullWidth(); + }; + + RealizedToken.prototype.hasTrailingTrivia = function () { + return this._trailingTrivia.count() > 0; + }; + RealizedToken.prototype.hasTrailingComment = function () { + return this._trailingTrivia.hasComment(); + }; + RealizedToken.prototype.hasTrailingNewLine = function () { + return this._trailingTrivia.hasNewLine(); + }; + RealizedToken.prototype.hasTrailingSkippedText = function () { + return this._trailingTrivia.hasSkippedToken(); + }; + RealizedToken.prototype.trailingTriviaWidth = function () { + return this._trailingTrivia.fullWidth(); + }; + + RealizedToken.prototype.hasSkippedToken = function () { + return this.hasLeadingSkippedText() || this.hasTrailingSkippedText(); + }; + + RealizedToken.prototype.leadingTrivia = function () { + return this._leadingTrivia; + }; + RealizedToken.prototype.trailingTrivia = function () { + return this._trailingTrivia; + }; + + RealizedToken.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + RealizedToken.prototype.collectTextElements = function (elements) { + this.leadingTrivia().collectTextElements(elements); + elements.push(this.text()); + this.trailingTrivia().collectTextElements(elements); + }; + + RealizedToken.prototype.withLeadingTrivia = function (leadingTrivia) { + return new RealizedToken(this.tokenKind, leadingTrivia, this._text, this._value, this._valueText, this._trailingTrivia); + }; + + RealizedToken.prototype.withTrailingTrivia = function (trailingTrivia) { + return new RealizedToken(this.tokenKind, this._leadingTrivia, this._text, this._value, this._valueText, trailingTrivia); + }; + + RealizedToken.prototype.isExpression = function () { + return isExpression(this); + }; + + RealizedToken.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + RealizedToken.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + RealizedToken.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + RealizedToken.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return RealizedToken; + })(); + + function token(kind, info) { + if (typeof info === "undefined") { info = null; } + var text = (info !== null && info.text !== undefined) ? info.text : TypeScript.SyntaxFacts.getText(kind); + + return new RealizedToken(kind, Syntax.triviaList(info === null ? null : info.leadingTrivia), text, value1(kind, text), valueText1(kind, text), Syntax.triviaList(info === null ? null : info.trailingTrivia)); + } + Syntax.token = token; + + function identifier(text, info) { + if (typeof info === "undefined") { info = null; } + info = info || {}; + info.text = text; + return token(11 /* IdentifierName */, info); + } + Syntax.identifier = identifier; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTokenReplacer = (function (_super) { + __extends(SyntaxTokenReplacer, _super); + function SyntaxTokenReplacer(token1, token2) { + _super.call(this); + this.token1 = token1; + this.token2 = token2; + } + SyntaxTokenReplacer.prototype.visitToken = function (token) { + if (token === this.token1) { + var result = this.token2; + this.token1 = null; + this.token2 = null; + + return result; + } + + return token; + }; + + SyntaxTokenReplacer.prototype.visitNode = function (node) { + if (this.token1 === null) { + return node; + } + + return _super.prototype.visitNode.call(this, node); + }; + + SyntaxTokenReplacer.prototype.visitList = function (list) { + if (this.token1 === null) { + return list; + } + + return _super.prototype.visitList.call(this, list); + }; + + SyntaxTokenReplacer.prototype.visitSeparatedList = function (list) { + if (this.token1 === null) { + return list; + } + + return _super.prototype.visitSeparatedList.call(this, list); + }; + return SyntaxTokenReplacer; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxTokenReplacer = SyntaxTokenReplacer; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var AbstractTrivia = (function () { + function AbstractTrivia(_kind) { + this._kind = _kind; + } + AbstractTrivia.prototype.fullWidth = function () { + throw TypeScript.Errors.abstract(); + }; + + AbstractTrivia.prototype.fullText = function () { + throw TypeScript.Errors.abstract(); + }; + + AbstractTrivia.prototype.skippedToken = function () { + throw TypeScript.Errors.abstract(); + }; + + AbstractTrivia.prototype.toJSON = function (key) { + var result = {}; + + for (var name in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind[name] === this._kind) { + result.kind = name; + break; + } + } + + if (this.isSkippedToken()) { + result.skippedToken = this.skippedToken(); + } else { + result.text = this.fullText(); + } + return result; + }; + + AbstractTrivia.prototype.kind = function () { + return this._kind; + }; + + AbstractTrivia.prototype.isWhitespace = function () { + return this.kind() === 4 /* WhitespaceTrivia */; + }; + + AbstractTrivia.prototype.isComment = function () { + return this.kind() === 7 /* SingleLineCommentTrivia */ || this.kind() === 6 /* MultiLineCommentTrivia */; + }; + + AbstractTrivia.prototype.isNewLine = function () { + return this.kind() === 5 /* NewLineTrivia */; + }; + + AbstractTrivia.prototype.isSkippedToken = function () { + return this.kind() === 8 /* SkippedTokenTrivia */; + }; + + AbstractTrivia.prototype.collectTextElements = function (elements) { + elements.push(this.fullText()); + }; + return AbstractTrivia; + })(); + + var NormalTrivia = (function (_super) { + __extends(NormalTrivia, _super); + function NormalTrivia(kind, _text) { + _super.call(this, kind); + this._text = _text; + } + NormalTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + + NormalTrivia.prototype.fullText = function () { + return this._text; + }; + + NormalTrivia.prototype.skippedToken = function () { + throw TypeScript.Errors.invalidOperation(); + }; + return NormalTrivia; + })(AbstractTrivia); + + var SkippedTokenTrivia = (function (_super) { + __extends(SkippedTokenTrivia, _super); + function SkippedTokenTrivia(_skippedToken) { + _super.call(this, 8 /* SkippedTokenTrivia */); + this._skippedToken = _skippedToken; + } + SkippedTokenTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + + SkippedTokenTrivia.prototype.fullText = function () { + return this.skippedToken().fullText(); + }; + + SkippedTokenTrivia.prototype.skippedToken = function () { + return this._skippedToken; + }; + return SkippedTokenTrivia; + })(AbstractTrivia); + + var DeferredTrivia = (function (_super) { + __extends(DeferredTrivia, _super); + function DeferredTrivia(kind, _text, _fullStart, _fullWidth) { + _super.call(this, kind); + this._text = _text; + this._fullStart = _fullStart; + this._fullWidth = _fullWidth; + this._fullText = null; + } + DeferredTrivia.prototype.fullWidth = function () { + return this._fullWidth; + }; + + DeferredTrivia.prototype.fullText = function () { + if (!this._fullText) { + this._fullText = this._text.substr(this._fullStart, this._fullWidth, false); + this._text = null; + } + + return this._fullText; + }; + + DeferredTrivia.prototype.skippedToken = function () { + throw TypeScript.Errors.invalidOperation(); + }; + return DeferredTrivia; + })(AbstractTrivia); + + function deferredTrivia(kind, text, fullStart, fullWidth) { + return new DeferredTrivia(kind, text, fullStart, fullWidth); + } + Syntax.deferredTrivia = deferredTrivia; + + function trivia(kind, text) { + return new NormalTrivia(kind, text); + } + Syntax.trivia = trivia; + + function skippedTokenTrivia(token) { + TypeScript.Debug.assert(!token.hasLeadingTrivia()); + TypeScript.Debug.assert(!token.hasTrailingTrivia()); + TypeScript.Debug.assert(token.fullWidth() > 0); + return new SkippedTokenTrivia(token); + } + Syntax.skippedTokenTrivia = skippedTokenTrivia; + + function spaces(count) { + return trivia(4 /* WhitespaceTrivia */, TypeScript.StringUtilities.repeat(" ", count)); + } + Syntax.spaces = spaces; + + function whitespace(text) { + return trivia(4 /* WhitespaceTrivia */, text); + } + Syntax.whitespace = whitespace; + + function multiLineComment(text) { + return trivia(6 /* MultiLineCommentTrivia */, text); + } + Syntax.multiLineComment = multiLineComment; + + function singleLineComment(text) { + return trivia(7 /* SingleLineCommentTrivia */, text); + } + Syntax.singleLineComment = singleLineComment; + + Syntax.spaceTrivia = spaces(1); + Syntax.lineFeedTrivia = trivia(5 /* NewLineTrivia */, "\n"); + Syntax.carriageReturnTrivia = trivia(5 /* NewLineTrivia */, "\r"); + Syntax.carriageReturnLineFeedTrivia = trivia(5 /* NewLineTrivia */, "\r\n"); + + function splitMultiLineCommentTriviaIntoMultipleLines(trivia) { + var result = []; + + var triviaText = trivia.fullText(); + var currentIndex = 0; + + for (var i = 0; i < triviaText.length; i++) { + var ch = triviaText.charCodeAt(i); + + var isCarriageReturnLineFeed = false; + switch (ch) { + case 13 /* carriageReturn */: + if (i < triviaText.length - 1 && triviaText.charCodeAt(i + 1) === 10 /* lineFeed */) { + i++; + } + + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + result.push(triviaText.substring(currentIndex, i + 1)); + + currentIndex = i + 1; + continue; + } + } + + result.push(triviaText.substring(currentIndex)); + return result; + } + Syntax.splitMultiLineCommentTriviaIntoMultipleLines = splitMultiLineCommentTriviaIntoMultipleLines; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + Syntax.emptyTriviaList = { + kind: function () { + return 3 /* TriviaList */; + }, + count: function () { + return 0; + }, + syntaxTriviaAt: function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }, + last: function () { + throw TypeScript.Errors.argumentOutOfRange("index"); + }, + fullWidth: function () { + return 0; + }, + fullText: function () { + return ""; + }, + hasComment: function () { + return false; + }, + hasNewLine: function () { + return false; + }, + hasSkippedToken: function () { + return false; + }, + toJSON: function (key) { + return []; + }, + collectTextElements: function (elements) { + }, + toArray: function () { + return []; + }, + concat: function (trivia) { + return trivia; + } + }; + + function concatTrivia(list1, list2) { + if (list1.count() === 0) { + return list2; + } + + if (list2.count() === 0) { + return list1; + } + + var trivia = list1.toArray(); + trivia.push.apply(trivia, list2.toArray()); + + return triviaList(trivia); + } + + function isComment(trivia) { + return trivia.kind() === 6 /* MultiLineCommentTrivia */ || trivia.kind() === 7 /* SingleLineCommentTrivia */; + } + + var SingletonSyntaxTriviaList = (function () { + function SingletonSyntaxTriviaList(item) { + this.item = item; + } + SingletonSyntaxTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + + SingletonSyntaxTriviaList.prototype.count = function () { + return 1; + }; + + SingletonSyntaxTriviaList.prototype.syntaxTriviaAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSyntaxTriviaList.prototype.last = function () { + return this.item; + }; + + SingletonSyntaxTriviaList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSyntaxTriviaList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSyntaxTriviaList.prototype.hasComment = function () { + return isComment(this.item); + }; + + SingletonSyntaxTriviaList.prototype.hasNewLine = function () { + return this.item.kind() === 5 /* NewLineTrivia */; + }; + + SingletonSyntaxTriviaList.prototype.hasSkippedToken = function () { + return this.item.kind() === 8 /* SkippedTokenTrivia */; + }; + + SingletonSyntaxTriviaList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSyntaxTriviaList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSyntaxTriviaList.prototype.toArray = function () { + return [this.item]; + }; + + SingletonSyntaxTriviaList.prototype.concat = function (trivia) { + return concatTrivia(this, trivia); + }; + return SingletonSyntaxTriviaList; + })(); + + var NormalSyntaxTriviaList = (function () { + function NormalSyntaxTriviaList(trivia) { + this.trivia = trivia; + } + NormalSyntaxTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + + NormalSyntaxTriviaList.prototype.count = function () { + return this.trivia.length; + }; + + NormalSyntaxTriviaList.prototype.syntaxTriviaAt = function (index) { + if (index < 0 || index >= this.trivia.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.trivia[index]; + }; + + NormalSyntaxTriviaList.prototype.last = function () { + return this.trivia[this.trivia.length - 1]; + }; + + NormalSyntaxTriviaList.prototype.fullWidth = function () { + return TypeScript.ArrayUtilities.sum(this.trivia, function (t) { + return t.fullWidth(); + }); + }; + + NormalSyntaxTriviaList.prototype.fullText = function () { + var result = ""; + + for (var i = 0, n = this.trivia.length; i < n; i++) { + result += this.trivia[i].fullText(); + } + + return result; + }; + + NormalSyntaxTriviaList.prototype.hasComment = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (isComment(this.trivia[i])) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.hasNewLine = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (this.trivia[i].kind() === 5 /* NewLineTrivia */) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.hasSkippedToken = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (this.trivia[i].kind() === 8 /* SkippedTokenTrivia */) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.toJSON = function (key) { + return this.trivia; + }; + + NormalSyntaxTriviaList.prototype.collectTextElements = function (elements) { + for (var i = 0; i < this.trivia.length; i++) { + this.trivia[i].collectTextElements(elements); + } + }; + + NormalSyntaxTriviaList.prototype.toArray = function () { + return this.trivia.slice(0); + }; + + NormalSyntaxTriviaList.prototype.concat = function (trivia) { + return concatTrivia(this, trivia); + }; + return NormalSyntaxTriviaList; + })(); + + function triviaList(trivia) { + if (trivia === undefined || trivia === null || trivia.length === 0) { + return Syntax.emptyTriviaList; + } + + if (trivia.length === 1) { + return new SingletonSyntaxTriviaList(trivia[0]); + } + + return new NormalSyntaxTriviaList(trivia); + } + Syntax.triviaList = triviaList; + + Syntax.spaceTriviaList = triviaList([Syntax.spaceTrivia]); + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxUtilities = (function () { + function SyntaxUtilities() { + } + SyntaxUtilities.isAngleBracket = function (positionedElement) { + var element = positionedElement.element(); + var parent = positionedElement.parentElement(); + if (parent !== null && (element.kind() === 80 /* LessThanToken */ || element.kind() === 81 /* GreaterThanToken */)) { + switch (parent.kind()) { + case 228 /* TypeArgumentList */: + case 229 /* TypeParameterList */: + case 220 /* CastExpression */: + return true; + } + } + + return false; + }; + + SyntaxUtilities.getToken = function (list, kind) { + for (var i = 0, n = list.childCount(); i < n; i++) { + var token = list.childAt(i); + if (token.tokenKind === kind) { + return token; + } + } + + return null; + }; + + SyntaxUtilities.containsToken = function (list, kind) { + return SyntaxUtilities.getToken(list, kind) !== null; + }; + + SyntaxUtilities.hasExportKeyword = function (moduleElement) { + return SyntaxUtilities.getExportKeyword(moduleElement) !== null; + }; + + SyntaxUtilities.getExportKeyword = function (moduleElement) { + switch (moduleElement.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 148 /* VariableStatement */: + case 132 /* EnumDeclaration */: + case 128 /* InterfaceDeclaration */: + case 133 /* ImportDeclaration */: + return SyntaxUtilities.getToken(moduleElement.modifiers, 47 /* ExportKeyword */); + default: + return null; + } + }; + + SyntaxUtilities.isAmbientDeclarationSyntax = function (positionNode) { + if (!positionNode) { + return false; + } + + var node = positionNode.node(); + switch (node.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 148 /* VariableStatement */: + case 132 /* EnumDeclaration */: + if (SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */)) { + return true; + } + + case 133 /* ImportDeclaration */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 136 /* MemberVariableDeclaration */: + if (node.isClassElement() || node.isModuleElement()) { + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode()); + } + + case 243 /* EnumElement */: + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode().containingNode()); + + default: + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode()); + } + }; + return SyntaxUtilities; + })(); + TypeScript.SyntaxUtilities = SyntaxUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxVisitor = (function () { + function SyntaxVisitor() { + } + SyntaxVisitor.prototype.defaultVisit = function (node) { + return null; + }; + + SyntaxVisitor.prototype.visitToken = function (token) { + return this.defaultVisit(token); + }; + + SyntaxVisitor.prototype.visitSourceUnit = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExternalModuleReference = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitModuleNameModuleReference = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitImportDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExportAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitClassDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitInterfaceDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitHeritageClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitModuleDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableDeclarator = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEqualsValueClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPrefixUnaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArrayLiteralExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitOmittedExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParenthesizedExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitQualifiedName = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeArgumentList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructorType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArrayType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitGenericType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeQuery = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeAnnotation = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBlock = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParameter = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberAccessExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPostfixUnaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitElementAccessExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitInvocationExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArgumentList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBinaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConditionalExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMethodSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIndexSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPropertySignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCallSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParameterList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeParameterList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeParameter = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstraint = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitElseClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIfStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExpressionStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructorDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitGetAccessor = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSetAccessor = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberVariableDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIndexMemberDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitThrowStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitReturnStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectCreationExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSwitchStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCaseSwitchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDefaultSwitchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBreakStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitContinueStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitForStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitForInStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitWhileStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitWithStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEnumDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEnumElement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCastExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectLiteralExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSimplePropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEmptyStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTryStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCatchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFinallyClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitLabeledStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDoStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeOfExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDeleteExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVoidExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDebuggerStatement = function (node) { + return this.defaultVisit(node); + }; + return SyntaxVisitor; + })(); + TypeScript.SyntaxVisitor = SyntaxVisitor; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxWalker = (function () { + function SyntaxWalker() { + } + SyntaxWalker.prototype.visitToken = function (token) { + }; + + SyntaxWalker.prototype.visitNode = function (node) { + node.accept(this); + }; + + SyntaxWalker.prototype.visitNodeOrToken = function (nodeOrToken) { + if (nodeOrToken.isToken()) { + this.visitToken(nodeOrToken); + } else { + this.visitNode(nodeOrToken); + } + }; + + SyntaxWalker.prototype.visitOptionalToken = function (token) { + if (token === null) { + return; + } + + this.visitToken(token); + }; + + SyntaxWalker.prototype.visitOptionalNode = function (node) { + if (node === null) { + return; + } + + this.visitNode(node); + }; + + SyntaxWalker.prototype.visitOptionalNodeOrToken = function (nodeOrToken) { + if (nodeOrToken === null) { + return; + } + + this.visitNodeOrToken(nodeOrToken); + }; + + SyntaxWalker.prototype.visitList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + this.visitNodeOrToken(list.childAt(i)); + } + }; + + SyntaxWalker.prototype.visitSeparatedList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + this.visitNodeOrToken(item); + } + }; + + SyntaxWalker.prototype.visitSourceUnit = function (node) { + this.visitList(node.moduleElements); + this.visitToken(node.endOfFileToken); + }; + + SyntaxWalker.prototype.visitExternalModuleReference = function (node) { + this.visitToken(node.requireKeyword); + this.visitToken(node.openParenToken); + this.visitToken(node.stringLiteral); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitModuleNameModuleReference = function (node) { + this.visitNodeOrToken(node.moduleName); + }; + + SyntaxWalker.prototype.visitImportDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.importKeyword); + this.visitToken(node.identifier); + this.visitToken(node.equalsToken); + this.visitNodeOrToken(node.moduleReference); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitExportAssignment = function (node) { + this.visitToken(node.exportKeyword); + this.visitToken(node.equalsToken); + this.visitToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitClassDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.classKeyword); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeParameterList); + this.visitList(node.heritageClauses); + this.visitToken(node.openBraceToken); + this.visitList(node.classElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitInterfaceDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.interfaceKeyword); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeParameterList); + this.visitList(node.heritageClauses); + this.visitNode(node.body); + }; + + SyntaxWalker.prototype.visitHeritageClause = function (node) { + this.visitToken(node.extendsOrImplementsKeyword); + this.visitSeparatedList(node.typeNames); + }; + + SyntaxWalker.prototype.visitModuleDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.moduleKeyword); + this.visitOptionalNodeOrToken(node.name); + this.visitOptionalToken(node.stringLiteral); + this.visitToken(node.openBraceToken); + this.visitList(node.moduleElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitFunctionDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.functionKeyword); + this.visitToken(node.identifier); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitVariableStatement = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.variableDeclaration); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitVariableDeclaration = function (node) { + this.visitToken(node.varKeyword); + this.visitSeparatedList(node.variableDeclarators); + }; + + SyntaxWalker.prototype.visitVariableDeclarator = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalNode(node.typeAnnotation); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitEqualsValueClause = function (node) { + this.visitToken(node.equalsToken); + this.visitNodeOrToken(node.value); + }; + + SyntaxWalker.prototype.visitPrefixUnaryExpression = function (node) { + this.visitToken(node.operatorToken); + this.visitNodeOrToken(node.operand); + }; + + SyntaxWalker.prototype.visitArrayLiteralExpression = function (node) { + this.visitToken(node.openBracketToken); + this.visitSeparatedList(node.expressions); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitOmittedExpression = function (node) { + }; + + SyntaxWalker.prototype.visitParenthesizedExpression = function (node) { + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitSimpleArrowFunctionExpression = function (node) { + this.visitToken(node.identifier); + this.visitToken(node.equalsGreaterThanToken); + this.visitOptionalNode(node.block); + this.visitOptionalNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + this.visitNode(node.callSignature); + this.visitToken(node.equalsGreaterThanToken); + this.visitOptionalNode(node.block); + this.visitOptionalNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitQualifiedName = function (node) { + this.visitNodeOrToken(node.left); + this.visitToken(node.dotToken); + this.visitToken(node.right); + }; + + SyntaxWalker.prototype.visitTypeArgumentList = function (node) { + this.visitToken(node.lessThanToken); + this.visitSeparatedList(node.typeArguments); + this.visitToken(node.greaterThanToken); + }; + + SyntaxWalker.prototype.visitConstructorType = function (node) { + this.visitToken(node.newKeyword); + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitFunctionType = function (node) { + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitObjectType = function (node) { + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.typeMembers); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitArrayType = function (node) { + this.visitNodeOrToken(node.type); + this.visitToken(node.openBracketToken); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitGenericType = function (node) { + this.visitNodeOrToken(node.name); + this.visitNode(node.typeArgumentList); + }; + + SyntaxWalker.prototype.visitTypeQuery = function (node) { + this.visitToken(node.typeOfKeyword); + this.visitNodeOrToken(node.name); + }; + + SyntaxWalker.prototype.visitTypeAnnotation = function (node) { + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitBlock = function (node) { + this.visitToken(node.openBraceToken); + this.visitList(node.statements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitParameter = function (node) { + this.visitOptionalToken(node.dotDotDotToken); + this.visitList(node.modifiers); + this.visitToken(node.identifier); + this.visitOptionalToken(node.questionToken); + this.visitOptionalNode(node.typeAnnotation); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitMemberAccessExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.dotToken); + this.visitToken(node.name); + }; + + SyntaxWalker.prototype.visitPostfixUnaryExpression = function (node) { + this.visitNodeOrToken(node.operand); + this.visitToken(node.operatorToken); + }; + + SyntaxWalker.prototype.visitElementAccessExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.openBracketToken); + this.visitNodeOrToken(node.argumentExpression); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitInvocationExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitNode(node.argumentList); + }; + + SyntaxWalker.prototype.visitArgumentList = function (node) { + this.visitOptionalNode(node.typeArgumentList); + this.visitToken(node.openParenToken); + this.visitSeparatedList(node.arguments); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitBinaryExpression = function (node) { + this.visitNodeOrToken(node.left); + this.visitToken(node.operatorToken); + this.visitNodeOrToken(node.right); + }; + + SyntaxWalker.prototype.visitConditionalExpression = function (node) { + this.visitNodeOrToken(node.condition); + this.visitToken(node.questionToken); + this.visitNodeOrToken(node.whenTrue); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.whenFalse); + }; + + SyntaxWalker.prototype.visitConstructSignature = function (node) { + this.visitToken(node.newKeyword); + this.visitNode(node.callSignature); + }; + + SyntaxWalker.prototype.visitMethodSignature = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalToken(node.questionToken); + this.visitNode(node.callSignature); + }; + + SyntaxWalker.prototype.visitIndexSignature = function (node) { + this.visitToken(node.openBracketToken); + this.visitNode(node.parameter); + this.visitToken(node.closeBracketToken); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitPropertySignature = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalToken(node.questionToken); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitCallSignature = function (node) { + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitParameterList = function (node) { + this.visitToken(node.openParenToken); + this.visitSeparatedList(node.parameters); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitTypeParameterList = function (node) { + this.visitToken(node.lessThanToken); + this.visitSeparatedList(node.typeParameters); + this.visitToken(node.greaterThanToken); + }; + + SyntaxWalker.prototype.visitTypeParameter = function (node) { + this.visitToken(node.identifier); + this.visitOptionalNode(node.constraint); + }; + + SyntaxWalker.prototype.visitConstraint = function (node) { + this.visitToken(node.extendsKeyword); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitElseClause = function (node) { + this.visitToken(node.elseKeyword); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitIfStatement = function (node) { + this.visitToken(node.ifKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + this.visitOptionalNode(node.elseClause); + }; + + SyntaxWalker.prototype.visitExpressionStatement = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitConstructorDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.constructorKeyword); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitMemberFunctionDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitGetAccessor = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.getKeyword); + this.visitToken(node.propertyName); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.typeAnnotation); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitSetAccessor = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.setKeyword); + this.visitToken(node.propertyName); + this.visitNode(node.parameterList); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitMemberVariableDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.variableDeclarator); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitIndexMemberDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.indexSignature); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitThrowStatement = function (node) { + this.visitToken(node.throwKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitReturnStatement = function (node) { + this.visitToken(node.returnKeyword); + this.visitOptionalNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitObjectCreationExpression = function (node) { + this.visitToken(node.newKeyword); + this.visitNodeOrToken(node.expression); + this.visitOptionalNode(node.argumentList); + }; + + SyntaxWalker.prototype.visitSwitchStatement = function (node) { + this.visitToken(node.switchKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + this.visitToken(node.openBraceToken); + this.visitList(node.switchClauses); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitCaseSwitchClause = function (node) { + this.visitToken(node.caseKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.colonToken); + this.visitList(node.statements); + }; + + SyntaxWalker.prototype.visitDefaultSwitchClause = function (node) { + this.visitToken(node.defaultKeyword); + this.visitToken(node.colonToken); + this.visitList(node.statements); + }; + + SyntaxWalker.prototype.visitBreakStatement = function (node) { + this.visitToken(node.breakKeyword); + this.visitOptionalToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitContinueStatement = function (node) { + this.visitToken(node.continueKeyword); + this.visitOptionalToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitForStatement = function (node) { + this.visitToken(node.forKeyword); + this.visitToken(node.openParenToken); + this.visitOptionalNode(node.variableDeclaration); + this.visitOptionalNodeOrToken(node.initializer); + this.visitToken(node.firstSemicolonToken); + this.visitOptionalNodeOrToken(node.condition); + this.visitToken(node.secondSemicolonToken); + this.visitOptionalNodeOrToken(node.incrementor); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitForInStatement = function (node) { + this.visitToken(node.forKeyword); + this.visitToken(node.openParenToken); + this.visitOptionalNode(node.variableDeclaration); + this.visitOptionalNodeOrToken(node.left); + this.visitToken(node.inKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitWhileStatement = function (node) { + this.visitToken(node.whileKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitWithStatement = function (node) { + this.visitToken(node.withKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitEnumDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.enumKeyword); + this.visitToken(node.identifier); + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.enumElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitEnumElement = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitCastExpression = function (node) { + this.visitToken(node.lessThanToken); + this.visitNodeOrToken(node.type); + this.visitToken(node.greaterThanToken); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitObjectLiteralExpression = function (node) { + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.propertyAssignments); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitSimplePropertyAssignment = function (node) { + this.visitToken(node.propertyName); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitFunctionPropertyAssignment = function (node) { + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitFunctionExpression = function (node) { + this.visitToken(node.functionKeyword); + this.visitOptionalToken(node.identifier); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitEmptyStatement = function (node) { + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitTryStatement = function (node) { + this.visitToken(node.tryKeyword); + this.visitNode(node.block); + this.visitOptionalNode(node.catchClause); + this.visitOptionalNode(node.finallyClause); + }; + + SyntaxWalker.prototype.visitCatchClause = function (node) { + this.visitToken(node.catchKeyword); + this.visitToken(node.openParenToken); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeAnnotation); + this.visitToken(node.closeParenToken); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitFinallyClause = function (node) { + this.visitToken(node.finallyKeyword); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitLabeledStatement = function (node) { + this.visitToken(node.identifier); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitDoStatement = function (node) { + this.visitToken(node.doKeyword); + this.visitNodeOrToken(node.statement); + this.visitToken(node.whileKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitTypeOfExpression = function (node) { + this.visitToken(node.typeOfKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitDeleteExpression = function (node) { + this.visitToken(node.deleteKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitVoidExpression = function (node) { + this.visitToken(node.voidKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitDebuggerStatement = function (node) { + this.visitToken(node.debuggerKeyword); + this.visitToken(node.semicolonToken); + }; + return SyntaxWalker; + })(); + TypeScript.SyntaxWalker = SyntaxWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PositionTrackingWalker = (function (_super) { + __extends(PositionTrackingWalker, _super); + function PositionTrackingWalker() { + _super.apply(this, arguments); + this._position = 0; + } + PositionTrackingWalker.prototype.visitToken = function (token) { + this._position += token.fullWidth(); + }; + + PositionTrackingWalker.prototype.position = function () { + return this._position; + }; + + PositionTrackingWalker.prototype.skip = function (element) { + this._position += element.fullWidth(); + }; + return PositionTrackingWalker; + })(TypeScript.SyntaxWalker); + TypeScript.PositionTrackingWalker = PositionTrackingWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxInformationMap = (function (_super) { + __extends(SyntaxInformationMap, _super); + function SyntaxInformationMap(trackParents, trackPreviousToken) { + _super.call(this); + this.trackParents = trackParents; + this.trackPreviousToken = trackPreviousToken; + this.tokenToInformation = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this.elementToPosition = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this._previousToken = null; + this._previousTokenInformation = null; + this._currentPosition = 0; + this._elementToParent = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this._parentStack = []; + this._parentStack.push(null); + } + SyntaxInformationMap.create = function (node, trackParents, trackPreviousToken) { + var map = new SyntaxInformationMap(trackParents, trackPreviousToken); + map.visitNode(node); + return map; + }; + + SyntaxInformationMap.prototype.visitNode = function (node) { + this.trackParents && this._elementToParent.add(node, TypeScript.ArrayUtilities.last(this._parentStack)); + this.elementToPosition.add(node, this._currentPosition); + + this.trackParents && this._parentStack.push(node); + _super.prototype.visitNode.call(this, node); + this.trackParents && this._parentStack.pop(); + }; + + SyntaxInformationMap.prototype.visitToken = function (token) { + this.trackParents && this._elementToParent.add(token, TypeScript.ArrayUtilities.last(this._parentStack)); + + if (this.trackPreviousToken) { + var tokenInformation = { + previousToken: this._previousToken, + nextToken: null + }; + + if (this._previousTokenInformation !== null) { + this._previousTokenInformation.nextToken = token; + } + + this._previousToken = token; + this._previousTokenInformation = tokenInformation; + + this.tokenToInformation.add(token, tokenInformation); + } + + this.elementToPosition.add(token, this._currentPosition); + this._currentPosition += token.fullWidth(); + }; + + SyntaxInformationMap.prototype.parent = function (element) { + return this._elementToParent.get(element); + }; + + SyntaxInformationMap.prototype.fullStart = function (element) { + return this.elementToPosition.get(element); + }; + + SyntaxInformationMap.prototype.start = function (element) { + return this.fullStart(element) + element.leadingTriviaWidth(); + }; + + SyntaxInformationMap.prototype.end = function (element) { + return this.start(element) + element.width(); + }; + + SyntaxInformationMap.prototype.previousToken = function (token) { + return this.tokenInformation(token).previousToken; + }; + + SyntaxInformationMap.prototype.tokenInformation = function (token) { + return this.tokenToInformation.get(token); + }; + + SyntaxInformationMap.prototype.firstTokenInLineContainingToken = function (token) { + var current = token; + while (true) { + var information = this.tokenInformation(current); + if (this.isFirstTokenInLineWorker(information)) { + break; + } + + current = information.previousToken; + } + + return current; + }; + + SyntaxInformationMap.prototype.isFirstTokenInLine = function (token) { + var information = this.tokenInformation(token); + return this.isFirstTokenInLineWorker(information); + }; + + SyntaxInformationMap.prototype.isFirstTokenInLineWorker = function (information) { + return information.previousToken === null || information.previousToken.hasTrailingNewLine(); + }; + return SyntaxInformationMap; + })(TypeScript.SyntaxWalker); + TypeScript.SyntaxInformationMap = SyntaxInformationMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxNodeInvariantsChecker = (function (_super) { + __extends(SyntaxNodeInvariantsChecker, _super); + function SyntaxNodeInvariantsChecker() { + _super.apply(this, arguments); + this.tokenTable = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + } + SyntaxNodeInvariantsChecker.checkInvariants = function (node) { + node.accept(new SyntaxNodeInvariantsChecker()); + }; + + SyntaxNodeInvariantsChecker.prototype.visitToken = function (token) { + this.tokenTable.add(token, token); + }; + return SyntaxNodeInvariantsChecker; + })(TypeScript.SyntaxWalker); + TypeScript.SyntaxNodeInvariantsChecker = SyntaxNodeInvariantsChecker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DepthLimitedWalker = (function (_super) { + __extends(DepthLimitedWalker, _super); + function DepthLimitedWalker(maximumDepth) { + _super.call(this); + this._depth = 0; + this._maximumDepth = 0; + this._maximumDepth = maximumDepth; + } + DepthLimitedWalker.prototype.visitNode = function (node) { + if (this._depth < this._maximumDepth) { + this._depth++; + _super.prototype.visitNode.call(this, node); + this._depth--; + } else { + this.skip(node); + } + }; + return DepthLimitedWalker; + })(TypeScript.PositionTrackingWalker); + TypeScript.DepthLimitedWalker = DepthLimitedWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Parser) { + + + var ExpressionPrecedence; + (function (ExpressionPrecedence) { + ExpressionPrecedence[ExpressionPrecedence["CommaExpressionPrecedence"] = 1] = "CommaExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["AssignmentExpressionPrecedence"] = 2] = "AssignmentExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["ConditionalExpressionPrecedence"] = 3] = "ConditionalExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["ArrowFunctionPrecedence"] = 4] = "ArrowFunctionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["LogicalOrExpressionPrecedence"] = 5] = "LogicalOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["LogicalAndExpressionPrecedence"] = 6] = "LogicalAndExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseOrExpressionPrecedence"] = 7] = "BitwiseOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseExclusiveOrExpressionPrecedence"] = 8] = "BitwiseExclusiveOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseAndExpressionPrecedence"] = 9] = "BitwiseAndExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["EqualityExpressionPrecedence"] = 10] = "EqualityExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["RelationalExpressionPrecedence"] = 11] = "RelationalExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["ShiftExpressionPrecdence"] = 12] = "ShiftExpressionPrecdence"; + ExpressionPrecedence[ExpressionPrecedence["AdditiveExpressionPrecedence"] = 13] = "AdditiveExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["MultiplicativeExpressionPrecedence"] = 14] = "MultiplicativeExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["UnaryExpressionPrecedence"] = 15] = "UnaryExpressionPrecedence"; + })(ExpressionPrecedence || (ExpressionPrecedence = {})); + + var ListParsingState; + (function (ListParsingState) { + ListParsingState[ListParsingState["SourceUnit_ModuleElements"] = 1 << 0] = "SourceUnit_ModuleElements"; + ListParsingState[ListParsingState["ClassDeclaration_ClassElements"] = 1 << 1] = "ClassDeclaration_ClassElements"; + ListParsingState[ListParsingState["ModuleDeclaration_ModuleElements"] = 1 << 2] = "ModuleDeclaration_ModuleElements"; + ListParsingState[ListParsingState["SwitchStatement_SwitchClauses"] = 1 << 3] = "SwitchStatement_SwitchClauses"; + ListParsingState[ListParsingState["SwitchClause_Statements"] = 1 << 4] = "SwitchClause_Statements"; + ListParsingState[ListParsingState["Block_Statements"] = 1 << 5] = "Block_Statements"; + ListParsingState[ListParsingState["TryBlock_Statements"] = 1 << 6] = "TryBlock_Statements"; + ListParsingState[ListParsingState["CatchBlock_Statements"] = 1 << 7] = "CatchBlock_Statements"; + ListParsingState[ListParsingState["EnumDeclaration_EnumElements"] = 1 << 8] = "EnumDeclaration_EnumElements"; + ListParsingState[ListParsingState["ObjectType_TypeMembers"] = 1 << 9] = "ObjectType_TypeMembers"; + ListParsingState[ListParsingState["ClassOrInterfaceDeclaration_HeritageClauses"] = 1 << 10] = "ClassOrInterfaceDeclaration_HeritageClauses"; + ListParsingState[ListParsingState["HeritageClause_TypeNameList"] = 1 << 11] = "HeritageClause_TypeNameList"; + ListParsingState[ListParsingState["VariableDeclaration_VariableDeclarators_AllowIn"] = 1 << 12] = "VariableDeclaration_VariableDeclarators_AllowIn"; + ListParsingState[ListParsingState["VariableDeclaration_VariableDeclarators_DisallowIn"] = 1 << 13] = "VariableDeclaration_VariableDeclarators_DisallowIn"; + ListParsingState[ListParsingState["ArgumentList_AssignmentExpressions"] = 1 << 14] = "ArgumentList_AssignmentExpressions"; + ListParsingState[ListParsingState["ObjectLiteralExpression_PropertyAssignments"] = 1 << 15] = "ObjectLiteralExpression_PropertyAssignments"; + ListParsingState[ListParsingState["ArrayLiteralExpression_AssignmentExpressions"] = 1 << 16] = "ArrayLiteralExpression_AssignmentExpressions"; + ListParsingState[ListParsingState["ParameterList_Parameters"] = 1 << 17] = "ParameterList_Parameters"; + ListParsingState[ListParsingState["TypeArgumentList_Types"] = 1 << 18] = "TypeArgumentList_Types"; + ListParsingState[ListParsingState["TypeParameterList_TypeParameters"] = 1 << 19] = "TypeParameterList_TypeParameters"; + + ListParsingState[ListParsingState["FirstListParsingState"] = ListParsingState.SourceUnit_ModuleElements] = "FirstListParsingState"; + ListParsingState[ListParsingState["LastListParsingState"] = ListParsingState.TypeParameterList_TypeParameters] = "LastListParsingState"; + })(ListParsingState || (ListParsingState = {})); + + var SyntaxCursor = (function () { + function SyntaxCursor(sourceUnit) { + this._elements = []; + this._index = 0; + this._pinCount = 0; + sourceUnit.insertChildrenInto(this._elements, 0); + } + SyntaxCursor.prototype.isFinished = function () { + return this._index === this._elements.length; + }; + + SyntaxCursor.prototype.currentElement = function () { + if (this.isFinished()) { + return null; + } + + return this._elements[this._index]; + }; + + SyntaxCursor.prototype.currentNode = function () { + var element = this.currentElement(); + return element !== null && element.isNode() ? element : null; + }; + + SyntaxCursor.prototype.moveToFirstChild = function () { + if (this.isFinished()) { + return; + } + + var element = this._elements[this._index]; + if (element.isToken()) { + return; + } + + var node = element; + + this._elements.splice(this._index, 1); + + node.insertChildrenInto(this._elements, this._index); + }; + + SyntaxCursor.prototype.moveToNextSibling = function () { + if (this.isFinished()) { + return; + } + + if (this._pinCount > 0) { + this._index++; + return; + } + + this._elements.shift(); + }; + + SyntaxCursor.prototype.getAndPinCursorIndex = function () { + this._pinCount++; + return this._index; + }; + + SyntaxCursor.prototype.releaseAndUnpinCursorIndex = function (index) { + this._pinCount--; + if (this._pinCount === 0) { + } + }; + + SyntaxCursor.prototype.rewindToPinnedCursorIndex = function (index) { + this._index = index; + }; + + SyntaxCursor.prototype.pinCount = function () { + return this._pinCount; + }; + + SyntaxCursor.prototype.moveToFirstToken = function () { + var element; + + while (!this.isFinished()) { + element = this.currentElement(); + if (element.isNode()) { + this.moveToFirstChild(); + continue; + } + + return; + } + }; + + SyntaxCursor.prototype.currentToken = function () { + this.moveToFirstToken(); + if (this.isFinished()) { + return null; + } + + var element = this.currentElement(); + + return element; + }; + + SyntaxCursor.prototype.peekToken = function (n) { + this.moveToFirstToken(); + var pin = this.getAndPinCursorIndex(); + + for (var i = 0; i < n; i++) { + this.moveToNextSibling(); + this.moveToFirstToken(); + } + + var result = this.currentToken(); + this.rewindToPinnedCursorIndex(pin); + this.releaseAndUnpinCursorIndex(pin); + + return result; + }; + return SyntaxCursor; + })(); + + + + var NormalParserSource = (function () { + function NormalParserSource(fileName, text, languageVersion) { + this._previousToken = null; + this._absolutePosition = 0; + this._tokenDiagnostics = []; + this.rewindPointPool = []; + this.rewindPointPoolCount = 0; + this.slidingWindow = new TypeScript.SlidingWindow(this, TypeScript.ArrayUtilities.createArray(32, null), null); + this.scanner = new TypeScript.Scanner(fileName, text, languageVersion); + } + NormalParserSource.prototype.currentNode = function () { + return null; + }; + + NormalParserSource.prototype.moveToNextNode = function () { + throw TypeScript.Errors.invalidOperation(); + }; + + NormalParserSource.prototype.absolutePosition = function () { + return this._absolutePosition; + }; + + NormalParserSource.prototype.previousToken = function () { + return this._previousToken; + }; + + NormalParserSource.prototype.tokenDiagnostics = function () { + return this._tokenDiagnostics; + }; + + NormalParserSource.prototype.getOrCreateRewindPoint = function () { + if (this.rewindPointPoolCount === 0) { + return {}; + } + + this.rewindPointPoolCount--; + var result = this.rewindPointPool[this.rewindPointPoolCount]; + this.rewindPointPool[this.rewindPointPoolCount] = null; + return result; + }; + + NormalParserSource.prototype.getRewindPoint = function () { + var slidingWindowIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + var rewindPoint = this.getOrCreateRewindPoint(); + + rewindPoint.slidingWindowIndex = slidingWindowIndex; + rewindPoint.previousToken = this._previousToken; + rewindPoint.absolutePosition = this._absolutePosition; + + rewindPoint.pinCount = this.slidingWindow.pinCount(); + + return rewindPoint; + }; + + NormalParserSource.prototype.isPinned = function () { + return this.slidingWindow.pinCount() > 0; + }; + + NormalParserSource.prototype.rewind = function (rewindPoint) { + this.slidingWindow.rewindToPinnedIndex(rewindPoint.slidingWindowIndex); + + this._previousToken = rewindPoint.previousToken; + this._absolutePosition = rewindPoint.absolutePosition; + }; + + NormalParserSource.prototype.releaseRewindPoint = function (rewindPoint) { + this.slidingWindow.releaseAndUnpinAbsoluteIndex(rewindPoint.absoluteIndex); + + this.rewindPointPool[this.rewindPointPoolCount] = rewindPoint; + this.rewindPointPoolCount++; + }; + + NormalParserSource.prototype.fetchMoreItems = function (allowRegularExpression, sourceIndex, window, destinationIndex, spaceAvailable) { + window[destinationIndex] = this.scanner.scan(this._tokenDiagnostics, allowRegularExpression); + return 1; + }; + + NormalParserSource.prototype.peekToken = function (n) { + return this.slidingWindow.peekItemN(n); + }; + + NormalParserSource.prototype.moveToNextToken = function () { + var currentToken = this.currentToken(); + this._absolutePosition += currentToken.fullWidth(); + this._previousToken = currentToken; + + this.slidingWindow.moveToNextItem(); + }; + + NormalParserSource.prototype.currentToken = function () { + return this.slidingWindow.currentItem(false); + }; + + NormalParserSource.prototype.removeDiagnosticsOnOrAfterPosition = function (position) { + var tokenDiagnosticsLength = this._tokenDiagnostics.length; + while (tokenDiagnosticsLength > 0) { + var diagnostic = this._tokenDiagnostics[tokenDiagnosticsLength - 1]; + if (diagnostic.start() >= position) { + tokenDiagnosticsLength--; + } else { + break; + } + } + + this._tokenDiagnostics.length = tokenDiagnosticsLength; + }; + + NormalParserSource.prototype.resetToPosition = function (absolutePosition, previousToken) { + this._absolutePosition = absolutePosition; + this._previousToken = previousToken; + + this.removeDiagnosticsOnOrAfterPosition(absolutePosition); + + this.slidingWindow.disgardAllItemsFromCurrentIndexOnwards(); + + this.scanner.setAbsoluteIndex(absolutePosition); + }; + + NormalParserSource.prototype.currentTokenAllowingRegularExpression = function () { + this.resetToPosition(this._absolutePosition, this._previousToken); + + var token = this.slidingWindow.currentItem(true); + + return token; + }; + return NormalParserSource; + })(); + + var IncrementalParserSource = (function () { + function IncrementalParserSource(oldSyntaxTree, textChangeRange, newText) { + this._changeDelta = 0; + var oldSourceUnit = oldSyntaxTree.sourceUnit(); + this._oldSourceUnitCursor = new SyntaxCursor(oldSourceUnit); + + this._changeRange = IncrementalParserSource.extendToAffectedRange(textChangeRange, oldSourceUnit); + + if (TypeScript.Debug.shouldAssert(2 /* Aggressive */)) { + TypeScript.Debug.assert((oldSourceUnit.fullWidth() - this._changeRange.span().length() + this._changeRange.newLength()) === newText.length()); + } + + this._normalParserSource = new NormalParserSource(oldSyntaxTree.fileName(), newText, oldSyntaxTree.parseOptions().languageVersion()); + } + IncrementalParserSource.extendToAffectedRange = function (changeRange, sourceUnit) { + var maxLookahead = 1; + + var start = changeRange.span().start(); + + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var token = sourceUnit.findToken(start); + + var position = token.fullStart(); + + start = TypeScript.MathPrototype.max(0, position - 1); + } + + var finalSpan = TypeScript.TextSpan.fromBounds(start, changeRange.span().end()); + var finalLength = changeRange.newLength() + (changeRange.span().start() - start); + + return new TypeScript.TextChangeRange(finalSpan, finalLength); + }; + + IncrementalParserSource.prototype.absolutePosition = function () { + return this._normalParserSource.absolutePosition(); + }; + + IncrementalParserSource.prototype.previousToken = function () { + return this._normalParserSource.previousToken(); + }; + + IncrementalParserSource.prototype.tokenDiagnostics = function () { + return this._normalParserSource.tokenDiagnostics(); + }; + + IncrementalParserSource.prototype.getRewindPoint = function () { + var rewindPoint = this._normalParserSource.getRewindPoint(); + var oldSourceUnitCursorIndex = this._oldSourceUnitCursor.getAndPinCursorIndex(); + + rewindPoint.changeDelta = this._changeDelta; + rewindPoint.changeRange = this._changeRange; + rewindPoint.oldSourceUnitCursorIndex = oldSourceUnitCursorIndex; + + return rewindPoint; + }; + + IncrementalParserSource.prototype.rewind = function (rewindPoint) { + this._changeRange = rewindPoint.changeRange; + this._changeDelta = rewindPoint.changeDelta; + this._oldSourceUnitCursor.rewindToPinnedCursorIndex(rewindPoint.oldSourceUnitCursorIndex); + + this._normalParserSource.rewind(rewindPoint); + }; + + IncrementalParserSource.prototype.releaseRewindPoint = function (rewindPoint) { + this._oldSourceUnitCursor.releaseAndUnpinCursorIndex(rewindPoint.oldSourceUnitCursorIndex); + this._normalParserSource.releaseRewindPoint(rewindPoint); + }; + + IncrementalParserSource.prototype.canReadFromOldSourceUnit = function () { + if (this._normalParserSource.isPinned()) { + return false; + } + + if (this._changeRange !== null && this._changeRange.newSpan().intersectsWithPosition(this.absolutePosition())) { + return false; + } + + this.syncCursorToNewTextIfBehind(); + + return this._changeDelta === 0 && !this._oldSourceUnitCursor.isFinished(); + }; + + IncrementalParserSource.prototype.currentNode = function () { + if (this.canReadFromOldSourceUnit()) { + return this.tryGetNodeFromOldSourceUnit(); + } + + return null; + }; + + IncrementalParserSource.prototype.currentToken = function () { + if (this.canReadFromOldSourceUnit()) { + var token = this.tryGetTokenFromOldSourceUnit(); + if (token !== null) { + return token; + } + } + + return this._normalParserSource.currentToken(); + }; + + IncrementalParserSource.prototype.currentTokenAllowingRegularExpression = function () { + return this._normalParserSource.currentTokenAllowingRegularExpression(); + }; + + IncrementalParserSource.prototype.syncCursorToNewTextIfBehind = function () { + while (true) { + if (this._oldSourceUnitCursor.isFinished()) { + break; + } + + if (this._changeDelta >= 0) { + break; + } + + var currentElement = this._oldSourceUnitCursor.currentElement(); + + if (currentElement.isNode() && (currentElement.fullWidth() > Math.abs(this._changeDelta))) { + this._oldSourceUnitCursor.moveToFirstChild(); + } else { + this._oldSourceUnitCursor.moveToNextSibling(); + + this._changeDelta += currentElement.fullWidth(); + } + } + }; + + IncrementalParserSource.prototype.intersectsWithChangeRangeSpanInOriginalText = function (start, length) { + return this._changeRange !== null && this._changeRange.span().intersectsWith(start, length); + }; + + IncrementalParserSource.prototype.tryGetNodeFromOldSourceUnit = function () { + while (true) { + var node = this._oldSourceUnitCursor.currentNode(); + if (node === null) { + return null; + } + + if (!this.intersectsWithChangeRangeSpanInOriginalText(this.absolutePosition(), node.fullWidth())) { + if (!node.isIncrementallyUnusable()) { + return node; + } + } + + this._oldSourceUnitCursor.moveToFirstChild(); + } + }; + + IncrementalParserSource.prototype.canReuseTokenFromOldSourceUnit = function (position, token) { + if (token !== null) { + if (!this.intersectsWithChangeRangeSpanInOriginalText(position, token.fullWidth())) { + if (!token.isIncrementallyUnusable()) { + return true; + } + } + } + + return false; + }; + + IncrementalParserSource.prototype.tryGetTokenFromOldSourceUnit = function () { + var token = this._oldSourceUnitCursor.currentToken(); + + return this.canReuseTokenFromOldSourceUnit(this.absolutePosition(), token) ? token : null; + }; + + IncrementalParserSource.prototype.peekToken = function (n) { + if (this.canReadFromOldSourceUnit()) { + var token = this.tryPeekTokenFromOldSourceUnit(n); + if (token !== null) { + return token; + } + } + + return this._normalParserSource.peekToken(n); + }; + + IncrementalParserSource.prototype.tryPeekTokenFromOldSourceUnit = function (n) { + var currentPosition = this.absolutePosition(); + for (var i = 0; i < n; i++) { + var interimToken = this._oldSourceUnitCursor.peekToken(i); + if (!this.canReuseTokenFromOldSourceUnit(currentPosition, interimToken)) { + return null; + } + + currentPosition += interimToken.fullWidth(); + } + + var token = this._oldSourceUnitCursor.peekToken(n); + return this.canReuseTokenFromOldSourceUnit(currentPosition, token) ? token : null; + }; + + IncrementalParserSource.prototype.moveToNextNode = function () { + var currentElement = this._oldSourceUnitCursor.currentElement(); + var currentNode = this._oldSourceUnitCursor.currentNode(); + + this._oldSourceUnitCursor.moveToNextSibling(); + + var absolutePosition = this.absolutePosition() + currentNode.fullWidth(); + var previousToken = currentNode.lastToken(); + this._normalParserSource.resetToPosition(absolutePosition, previousToken); + + if (this._changeRange !== null) { + } + }; + + IncrementalParserSource.prototype.moveToNextToken = function () { + var currentToken = this.currentToken(); + + if (this._oldSourceUnitCursor.currentToken() === currentToken) { + this._oldSourceUnitCursor.moveToNextSibling(); + + var absolutePosition = this.absolutePosition() + currentToken.fullWidth(); + var previousToken = currentToken; + this._normalParserSource.resetToPosition(absolutePosition, previousToken); + + if (this._changeRange !== null) { + } + } else { + this._changeDelta -= currentToken.fullWidth(); + + this._normalParserSource.moveToNextToken(); + + if (this._changeRange !== null) { + var changeRangeSpanInNewText = this._changeRange.newSpan(); + if (this.absolutePosition() >= changeRangeSpanInNewText.end()) { + this._changeDelta += this._changeRange.newLength() - this._changeRange.span().length(); + this._changeRange = null; + } + } + } + }; + return IncrementalParserSource; + })(); + + var ParserImpl = (function () { + function ParserImpl(fileName, lineMap, source, parseOptions, newText_forDebuggingPurposesOnly) { + this.newText_forDebuggingPurposesOnly = newText_forDebuggingPurposesOnly; + this.listParsingState = 0; + this.isInStrictMode = false; + this.diagnostics = []; + this.factory = TypeScript.Syntax.normalModeFactory; + this.mergeTokensStorage = []; + this.arrayPool = []; + this.fileName = fileName; + this.lineMap = lineMap; + this.source = source; + this.parseOptions = parseOptions; + } + ParserImpl.prototype.getRewindPoint = function () { + var rewindPoint = this.source.getRewindPoint(); + + rewindPoint.diagnosticsCount = this.diagnostics.length; + + rewindPoint.isInStrictMode = this.isInStrictMode; + rewindPoint.listParsingState = this.listParsingState; + + return rewindPoint; + }; + + ParserImpl.prototype.rewind = function (rewindPoint) { + this.source.rewind(rewindPoint); + + this.diagnostics.length = rewindPoint.diagnosticsCount; + }; + + ParserImpl.prototype.releaseRewindPoint = function (rewindPoint) { + this.source.releaseRewindPoint(rewindPoint); + }; + + ParserImpl.prototype.currentTokenStart = function () { + return this.source.absolutePosition() + this.currentToken().leadingTriviaWidth(); + }; + + ParserImpl.prototype.previousTokenStart = function () { + if (this.previousToken() === null) { + return 0; + } + + return this.source.absolutePosition() - this.previousToken().fullWidth() + this.previousToken().leadingTriviaWidth(); + }; + + ParserImpl.prototype.previousTokenEnd = function () { + if (this.previousToken() === null) { + return 0; + } + + return this.previousTokenStart() + this.previousToken().width(); + }; + + ParserImpl.prototype.currentNode = function () { + var node = this.source.currentNode(); + + if (node === null || node.parsedInStrictMode() !== this.isInStrictMode) { + return null; + } + + return node; + }; + + ParserImpl.prototype.currentToken = function () { + return this.source.currentToken(); + }; + + ParserImpl.prototype.currentTokenAllowingRegularExpression = function () { + return this.source.currentTokenAllowingRegularExpression(); + }; + + ParserImpl.prototype.peekToken = function (n) { + return this.source.peekToken(n); + }; + + ParserImpl.prototype.eatAnyToken = function () { + var token = this.currentToken(); + this.moveToNextToken(); + return token; + }; + + ParserImpl.prototype.moveToNextToken = function () { + this.source.moveToNextToken(); + }; + + ParserImpl.prototype.previousToken = function () { + return this.source.previousToken(); + }; + + ParserImpl.prototype.eatNode = function () { + var node = this.source.currentNode(); + this.source.moveToNextNode(); + return node; + }; + + ParserImpl.prototype.eatToken = function (kind) { + var token = this.currentToken(); + if (token.tokenKind === kind) { + this.moveToNextToken(); + return token; + } + + return this.createMissingToken(kind, token); + }; + + ParserImpl.prototype.tryEatToken = function (kind) { + if (this.currentToken().tokenKind === kind) { + return this.eatToken(kind); + } + + return null; + }; + + ParserImpl.prototype.eatKeyword = function (kind) { + var token = this.currentToken(); + if (token.tokenKind === kind) { + this.moveToNextToken(); + return token; + } + + return this.createMissingToken(kind, token); + }; + + ParserImpl.prototype.isIdentifier = function (token) { + var tokenKind = token.tokenKind; + + if (tokenKind === 11 /* IdentifierName */) { + return true; + } + + if (tokenKind >= 51 /* FirstFutureReservedStrictKeyword */) { + if (tokenKind <= 59 /* LastFutureReservedStrictKeyword */) { + return !this.isInStrictMode; + } + + return tokenKind <= 69 /* LastTypeScriptKeyword */; + } + + return false; + }; + + ParserImpl.prototype.eatIdentifierNameToken = function () { + var token = this.currentToken(); + + if (token.tokenKind === 11 /* IdentifierName */) { + this.moveToNextToken(); + return token; + } + + if (TypeScript.SyntaxFacts.isAnyKeyword(token.tokenKind)) { + this.moveToNextToken(); + return TypeScript.Syntax.convertToIdentifierName(token); + } + + return this.createMissingToken(11 /* IdentifierName */, token); + }; + + ParserImpl.prototype.eatIdentifierToken = function () { + var token = this.currentToken(); + if (this.isIdentifier(token)) { + this.moveToNextToken(); + + if (token.tokenKind === 11 /* IdentifierName */) { + return token; + } + + return TypeScript.Syntax.convertToIdentifierName(token); + } + + return this.createMissingToken(11 /* IdentifierName */, token); + }; + + ParserImpl.prototype.canEatAutomaticSemicolon = function (allowWithoutNewLine) { + var token = this.currentToken(); + + if (token.tokenKind === 10 /* EndOfFileToken */) { + return true; + } + + if (token.tokenKind === 71 /* CloseBraceToken */) { + return true; + } + + if (allowWithoutNewLine) { + return true; + } + + if (this.previousToken() !== null && this.previousToken().hasTrailingNewLine()) { + return true; + } + + return false; + }; + + ParserImpl.prototype.canEatExplicitOrAutomaticSemicolon = function (allowWithoutNewline) { + var token = this.currentToken(); + + if (token.tokenKind === 78 /* SemicolonToken */) { + return true; + } + + return this.canEatAutomaticSemicolon(allowWithoutNewline); + }; + + ParserImpl.prototype.eatExplicitOrAutomaticSemicolon = function (allowWithoutNewline) { + var token = this.currentToken(); + + if (token.tokenKind === 78 /* SemicolonToken */) { + return this.eatToken(78 /* SemicolonToken */); + } + + if (this.canEatAutomaticSemicolon(allowWithoutNewline)) { + var semicolonToken = TypeScript.Syntax.emptyToken(78 /* SemicolonToken */); + + if (!this.parseOptions.allowAutomaticSemicolonInsertion()) { + this.addDiagnostic(new TypeScript.Diagnostic(this.fileName, this.lineMap, this.previousTokenEnd(), 0, TypeScript.DiagnosticCode.Automatic_semicolon_insertion_not_allowed, null)); + } + + return semicolonToken; + } + + return this.eatToken(78 /* SemicolonToken */); + }; + + ParserImpl.prototype.isKeyword = function (kind) { + if (kind >= 15 /* FirstKeyword */) { + if (kind <= 50 /* LastFutureReservedKeyword */) { + return true; + } + + if (this.isInStrictMode) { + return kind <= 59 /* LastFutureReservedStrictKeyword */; + } + } + + return false; + }; + + ParserImpl.prototype.createMissingToken = function (expectedKind, actual) { + var diagnostic = this.getExpectedTokenDiagnostic(expectedKind, actual); + this.addDiagnostic(diagnostic); + + return TypeScript.Syntax.emptyToken(expectedKind); + }; + + ParserImpl.prototype.getExpectedTokenDiagnostic = function (expectedKind, actual) { + var token = this.currentToken(); + + if (TypeScript.SyntaxFacts.isAnyKeyword(expectedKind) || TypeScript.SyntaxFacts.isAnyPunctuation(expectedKind)) { + return new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode._0_expected, [TypeScript.SyntaxFacts.getText(expectedKind)]); + } else { + if (actual !== null && TypeScript.SyntaxFacts.isAnyKeyword(actual.tokenKind)) { + return new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode.Identifier_expected_0_is_a_keyword, [TypeScript.SyntaxFacts.getText(actual.tokenKind)]); + } else { + return new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode.Identifier_expected, null); + } + } + }; + + ParserImpl.getPrecedence = function (expressionKind) { + switch (expressionKind) { + case 173 /* CommaExpression */: + return 1 /* CommaExpressionPrecedence */; + + case 174 /* AssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + return 2 /* AssignmentExpressionPrecedence */; + + case 186 /* ConditionalExpression */: + return 3 /* ConditionalExpressionPrecedence */; + + case 187 /* LogicalOrExpression */: + return 5 /* LogicalOrExpressionPrecedence */; + + case 188 /* LogicalAndExpression */: + return 6 /* LogicalAndExpressionPrecedence */; + + case 189 /* BitwiseOrExpression */: + return 7 /* BitwiseOrExpressionPrecedence */; + + case 190 /* BitwiseExclusiveOrExpression */: + return 8 /* BitwiseExclusiveOrExpressionPrecedence */; + + case 191 /* BitwiseAndExpression */: + return 9 /* BitwiseAndExpressionPrecedence */; + + case 192 /* EqualsWithTypeConversionExpression */: + case 193 /* NotEqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + return 10 /* EqualityExpressionPrecedence */; + + case 196 /* LessThanExpression */: + case 197 /* GreaterThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 200 /* InstanceOfExpression */: + case 201 /* InExpression */: + return 11 /* RelationalExpressionPrecedence */; + + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + return 12 /* ShiftExpressionPrecdence */; + + case 208 /* AddExpression */: + case 209 /* SubtractExpression */: + return 13 /* AdditiveExpressionPrecedence */; + + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + return 14 /* MultiplicativeExpressionPrecedence */; + + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + case 166 /* BitwiseNotExpression */: + case 167 /* LogicalNotExpression */: + case 170 /* DeleteExpression */: + case 171 /* TypeOfExpression */: + case 172 /* VoidExpression */: + case 168 /* PreIncrementExpression */: + case 169 /* PreDecrementExpression */: + return 15 /* UnaryExpressionPrecedence */; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + ParserImpl.prototype.addSkippedTokenAfterNodeOrToken = function (nodeOrToken, skippedToken) { + if (nodeOrToken.isToken()) { + return this.addSkippedTokenAfterToken(nodeOrToken, skippedToken); + } else if (nodeOrToken.isNode()) { + return this.addSkippedTokenAfterNode(nodeOrToken, skippedToken); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.addSkippedTokenAfterNode = function (node, skippedToken) { + var oldToken = node.lastToken(); + var newToken = this.addSkippedTokenAfterToken(oldToken, skippedToken); + + return node.replaceToken(oldToken, newToken); + }; + + ParserImpl.prototype.addSkippedTokensBeforeNode = function (node, skippedTokens) { + if (skippedTokens.length > 0) { + var oldToken = node.firstToken(); + var newToken = this.addSkippedTokensBeforeToken(oldToken, skippedTokens); + + return node.replaceToken(oldToken, newToken); + } + + return node; + }; + + ParserImpl.prototype.addSkippedTokensBeforeToken = function (token, skippedTokens) { + var leadingTrivia = []; + for (var i = 0, n = skippedTokens.length; i < n; i++) { + this.addSkippedTokenToTriviaArray(leadingTrivia, skippedTokens[i]); + } + + this.addTriviaTo(token.leadingTrivia(), leadingTrivia); + + this.returnArray(skippedTokens); + return token.withLeadingTrivia(TypeScript.Syntax.triviaList(leadingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokensAfterToken = function (token, skippedTokens) { + if (skippedTokens.length === 0) { + this.returnArray(skippedTokens); + return token; + } + + var trailingTrivia = token.trailingTrivia().toArray(); + + for (var i = 0, n = skippedTokens.length; i < n; i++) { + this.addSkippedTokenToTriviaArray(trailingTrivia, skippedTokens[i]); + } + + this.returnArray(skippedTokens); + return token.withTrailingTrivia(TypeScript.Syntax.triviaList(trailingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokenAfterToken = function (token, skippedToken) { + var trailingTrivia = token.trailingTrivia().toArray(); + this.addSkippedTokenToTriviaArray(trailingTrivia, skippedToken); + + return token.withTrailingTrivia(TypeScript.Syntax.triviaList(trailingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokenToTriviaArray = function (array, skippedToken) { + this.addTriviaTo(skippedToken.leadingTrivia(), array); + + var trimmedToken = skippedToken.withLeadingTrivia(TypeScript.Syntax.emptyTriviaList).withTrailingTrivia(TypeScript.Syntax.emptyTriviaList); + array.push(TypeScript.Syntax.skippedTokenTrivia(trimmedToken)); + + this.addTriviaTo(skippedToken.trailingTrivia(), array); + }; + + ParserImpl.prototype.addTriviaTo = function (list, array) { + for (var i = 0, n = list.count(); i < n; i++) { + array.push(list.syntaxTriviaAt(i)); + } + }; + + ParserImpl.prototype.parseSyntaxTree = function (isDeclaration) { + var sourceUnit = this.parseSourceUnit(); + + var allDiagnostics = this.source.tokenDiagnostics().concat(this.diagnostics); + allDiagnostics.sort(function (a, b) { + return a.start() - b.start(); + }); + + return new TypeScript.SyntaxTree(sourceUnit, isDeclaration, allDiagnostics, this.fileName, this.lineMap, this.parseOptions); + }; + + ParserImpl.prototype.setStrictMode = function (isInStrictMode) { + this.isInStrictMode = isInStrictMode; + this.factory = isInStrictMode ? TypeScript.Syntax.strictModeFactory : TypeScript.Syntax.normalModeFactory; + }; + + ParserImpl.prototype.parseSourceUnit = function () { + var savedIsInStrictMode = this.isInStrictMode; + + var result = this.parseSyntaxList(1 /* SourceUnit_ModuleElements */, ParserImpl.updateStrictModeState); + var moduleElements = result.list; + + this.setStrictMode(savedIsInStrictMode); + + var sourceUnit = this.factory.sourceUnit(moduleElements, this.currentToken()); + sourceUnit = this.addSkippedTokensBeforeNode(sourceUnit, result.skippedTokens); + + if (TypeScript.Debug.shouldAssert(2 /* Aggressive */)) { + TypeScript.Debug.assert(sourceUnit.fullWidth() === this.newText_forDebuggingPurposesOnly.length()); + + if (TypeScript.Debug.shouldAssert(3 /* VeryAggressive */)) { + TypeScript.Debug.assert(sourceUnit.fullText() === this.newText_forDebuggingPurposesOnly.substr(0, this.newText_forDebuggingPurposesOnly.length(), false)); + } + } + + return sourceUnit; + }; + + ParserImpl.updateStrictModeState = function (parser, items) { + if (!parser.isInStrictMode) { + for (var i = 0; i < items.length; i++) { + var item = items[i]; + if (!TypeScript.SyntaxFacts.isDirectivePrologueElement(item)) { + return; + } + } + + parser.setStrictMode(TypeScript.SyntaxFacts.isUseStrictDirective(items[items.length - 1])); + } + }; + + ParserImpl.prototype.isModuleElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isModuleElement()) { + return true; + } + + var modifierCount = this.modifierCount(); + return this.isImportDeclaration(modifierCount) || this.isExportAssignment() || this.isModuleDeclaration(modifierCount) || this.isInterfaceDeclaration(modifierCount) || this.isClassDeclaration(modifierCount) || this.isEnumDeclaration(modifierCount) || this.isStatement(inErrorRecovery); + }; + + ParserImpl.prototype.parseModuleElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isModuleElement()) { + return this.eatNode(); + } + + var modifierCount = this.modifierCount(); + if (this.isImportDeclaration(modifierCount)) { + return this.parseImportDeclaration(); + } else if (this.isExportAssignment()) { + return this.parseExportAssignment(); + } else if (this.isModuleDeclaration(modifierCount)) { + return this.parseModuleDeclaration(); + } else if (this.isInterfaceDeclaration(modifierCount)) { + return this.parseInterfaceDeclaration(); + } else if (this.isClassDeclaration(modifierCount)) { + return this.parseClassDeclaration(); + } else if (this.isEnumDeclaration(modifierCount)) { + return this.parseEnumDeclaration(); + } else if (this.isStatement(inErrorRecovery)) { + return this.parseStatement(inErrorRecovery); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isImportDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 49 /* ImportKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 49 /* ImportKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseImportDeclaration = function () { + var modifiers = this.parseModifiers(); + var importKeyword = this.eatKeyword(49 /* ImportKeyword */); + var identifier = this.eatIdentifierToken(); + var equalsToken = this.eatToken(107 /* EqualsToken */); + var moduleReference = this.parseModuleReference(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.importDeclaration(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken); + }; + + ParserImpl.prototype.isExportAssignment = function () { + return this.currentToken().tokenKind === 47 /* ExportKeyword */ && this.peekToken(1).tokenKind === 107 /* EqualsToken */; + }; + + ParserImpl.prototype.parseExportAssignment = function () { + var exportKeyword = this.eatKeyword(47 /* ExportKeyword */); + var equalsToken = this.eatToken(107 /* EqualsToken */); + var identifier = this.eatIdentifierToken(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.exportAssignment(exportKeyword, equalsToken, identifier, semicolonToken); + }; + + ParserImpl.prototype.parseModuleReference = function () { + if (this.isExternalModuleReference()) { + return this.parseExternalModuleReference(); + } else { + return this.parseModuleNameModuleReference(); + } + }; + + ParserImpl.prototype.isExternalModuleReference = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 66 /* RequireKeyword */) { + return this.peekToken(1).tokenKind === 72 /* OpenParenToken */; + } + + return false; + }; + + ParserImpl.prototype.parseExternalModuleReference = function () { + var requireKeyword = this.eatKeyword(66 /* RequireKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var stringLiteral = this.eatToken(14 /* StringLiteral */); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + return this.factory.externalModuleReference(requireKeyword, openParenToken, stringLiteral, closeParenToken); + }; + + ParserImpl.prototype.parseModuleNameModuleReference = function () { + var name = this.parseName(); + return this.factory.moduleNameModuleReference(name); + }; + + ParserImpl.prototype.parseIdentifierName = function () { + var identifierName = this.eatIdentifierNameToken(); + return identifierName; + }; + + ParserImpl.prototype.tryParseTypeArgumentList = function (inExpression) { + if (this.currentToken().kind() !== 80 /* LessThanToken */) { + return null; + } + + var lessThanToken; + var greaterThanToken; + var result; + var typeArguments; + + if (!inExpression) { + lessThanToken = this.eatToken(80 /* LessThanToken */); + + result = this.parseSeparatedSyntaxList(262144 /* TypeArgumentList_Types */); + typeArguments = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + + return this.factory.typeArgumentList(lessThanToken, typeArguments, greaterThanToken); + } + + var rewindPoint = this.getRewindPoint(); + + lessThanToken = this.eatToken(80 /* LessThanToken */); + + result = this.parseSeparatedSyntaxList(262144 /* TypeArgumentList_Types */); + typeArguments = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + + if (greaterThanToken.fullWidth() === 0 || !this.canFollowTypeArgumentListInExpression(this.currentToken().kind())) { + this.rewind(rewindPoint); + + this.releaseRewindPoint(rewindPoint); + return null; + } else { + this.releaseRewindPoint(rewindPoint); + var typeArgumentList = this.factory.typeArgumentList(lessThanToken, typeArguments, greaterThanToken); + + return typeArgumentList; + } + }; + + ParserImpl.prototype.canFollowTypeArgumentListInExpression = function (kind) { + switch (kind) { + case 72 /* OpenParenToken */: + case 76 /* DotToken */: + + case 73 /* CloseParenToken */: + case 75 /* CloseBracketToken */: + case 106 /* ColonToken */: + case 78 /* SemicolonToken */: + case 79 /* CommaToken */: + case 105 /* QuestionToken */: + case 84 /* EqualsEqualsToken */: + case 87 /* EqualsEqualsEqualsToken */: + case 86 /* ExclamationEqualsToken */: + case 88 /* ExclamationEqualsEqualsToken */: + case 103 /* AmpersandAmpersandToken */: + case 104 /* BarBarToken */: + case 100 /* CaretToken */: + case 98 /* AmpersandToken */: + case 99 /* BarToken */: + case 71 /* CloseBraceToken */: + case 10 /* EndOfFileToken */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.parseName = function () { + var shouldContinue = this.isIdentifier(this.currentToken()); + var current = this.eatIdentifierToken(); + + while (shouldContinue && this.currentToken().tokenKind === 76 /* DotToken */) { + var dotToken = this.eatToken(76 /* DotToken */); + + var currentToken = this.currentToken(); + var identifierName; + + if (TypeScript.SyntaxFacts.isAnyKeyword(currentToken.tokenKind) && this.previousToken().hasTrailingNewLine() && !currentToken.hasTrailingNewLine() && TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(this.peekToken(1))) { + identifierName = this.createMissingToken(11 /* IdentifierName */, currentToken); + } else { + identifierName = this.eatIdentifierNameToken(); + } + + current = this.factory.qualifiedName(current, dotToken, identifierName); + + shouldContinue = identifierName.fullWidth() > 0; + } + + return current; + }; + + ParserImpl.prototype.isEnumDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 46 /* EnumKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 46 /* EnumKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseEnumDeclaration = function () { + var modifiers = this.parseModifiers(); + var enumKeyword = this.eatKeyword(46 /* EnumKeyword */); + var identifier = this.eatIdentifierToken(); + + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + var enumElements = TypeScript.Syntax.emptySeparatedList; + + if (openBraceToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(256 /* EnumDeclaration_EnumElements */); + enumElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.enumDeclaration(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken); + }; + + ParserImpl.prototype.isEnumElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().kind() === 243 /* EnumElement */) { + return true; + } + + return this.isPropertyName(this.currentToken(), inErrorRecovery); + }; + + ParserImpl.prototype.parseEnumElement = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 243 /* EnumElement */) { + return this.eatNode(); + } + + var propertyName = this.eatPropertyName(); + var equalsValueClause = null; + if (this.isEqualsValueClause(false)) { + equalsValueClause = this.parseEqualsValueClause(true); + } + + return this.factory.enumElement(propertyName, equalsValueClause); + }; + + ParserImpl.isModifier = function (token) { + switch (token.tokenKind) { + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + case 47 /* ExportKeyword */: + case 63 /* DeclareKeyword */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.modifierCount = function () { + var modifierCount = 0; + while (true) { + if (ParserImpl.isModifier(this.peekToken(modifierCount))) { + modifierCount++; + continue; + } + + break; + } + + return modifierCount; + }; + + ParserImpl.prototype.parseModifiers = function () { + var tokens = this.getArray(); + + while (true) { + if (ParserImpl.isModifier(this.currentToken())) { + tokens.push(this.eatAnyToken()); + continue; + } + + break; + } + + var result = TypeScript.Syntax.list(tokens); + + this.returnZeroOrOneLengthArray(tokens); + + return result; + }; + + ParserImpl.prototype.isClassDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 44 /* ClassKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 44 /* ClassKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseHeritageClauses = function () { + var heritageClauses = TypeScript.Syntax.emptyList; + + if (this.isHeritageClause()) { + var result = this.parseSyntaxList(1024 /* ClassOrInterfaceDeclaration_HeritageClauses */); + heritageClauses = result.list; + TypeScript.Debug.assert(result.skippedTokens.length === 0); + } + + return heritageClauses; + }; + + ParserImpl.prototype.parseClassDeclaration = function () { + var modifiers = this.parseModifiers(); + + var classKeyword = this.eatKeyword(44 /* ClassKeyword */); + var identifier = this.eatIdentifierToken(); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var heritageClauses = this.parseHeritageClauses(); + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + var classElements = TypeScript.Syntax.emptyList; + + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(2 /* ClassDeclaration_ClassElements */); + + classElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + return this.factory.classDeclaration(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken); + }; + + ParserImpl.isPublicOrPrivateKeyword = function (token) { + return token.tokenKind === 57 /* PublicKeyword */ || token.tokenKind === 55 /* PrivateKeyword */; + }; + + ParserImpl.prototype.isAccessor = function (inErrorRecovery) { + var index = this.modifierCount(); + + if (this.peekToken(index).tokenKind !== 64 /* GetKeyword */ && this.peekToken(index).tokenKind !== 68 /* SetKeyword */) { + return false; + } + + index++; + return this.isPropertyName(this.peekToken(index), inErrorRecovery); + }; + + ParserImpl.prototype.parseAccessor = function (checkForStrictMode) { + var modifiers = this.parseModifiers(); + + if (this.currentToken().tokenKind === 64 /* GetKeyword */) { + return this.parseGetMemberAccessorDeclaration(modifiers, checkForStrictMode); + } else if (this.currentToken().tokenKind === 68 /* SetKeyword */) { + return this.parseSetMemberAccessorDeclaration(modifiers, checkForStrictMode); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseGetMemberAccessorDeclaration = function (modifiers, checkForStrictMode) { + var getKeyword = this.eatKeyword(64 /* GetKeyword */); + var propertyName = this.eatPropertyName(); + var parameterList = this.parseParameterList(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + var block = this.parseBlock(false, checkForStrictMode); + + return this.factory.getAccessor(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block); + }; + + ParserImpl.prototype.parseSetMemberAccessorDeclaration = function (modifiers, checkForStrictMode) { + var setKeyword = this.eatKeyword(68 /* SetKeyword */); + var propertyName = this.eatPropertyName(); + var parameterList = this.parseParameterList(); + var block = this.parseBlock(false, checkForStrictMode); + + return this.factory.setAccessor(modifiers, setKeyword, propertyName, parameterList, block); + }; + + ParserImpl.prototype.isClassElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isClassElement()) { + return true; + } + + return this.isConstructorDeclaration() || this.isMemberFunctionDeclaration(inErrorRecovery) || this.isAccessor(inErrorRecovery) || this.isMemberVariableDeclaration(inErrorRecovery) || this.isIndexMemberDeclaration(); + }; + + ParserImpl.prototype.parseClassElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isClassElement()) { + return this.eatNode(); + } + + if (this.isConstructorDeclaration()) { + return this.parseConstructorDeclaration(); + } else if (this.isMemberFunctionDeclaration(inErrorRecovery)) { + return this.parseMemberFunctionDeclaration(); + } else if (this.isAccessor(inErrorRecovery)) { + return this.parseAccessor(false); + } else if (this.isMemberVariableDeclaration(inErrorRecovery)) { + return this.parseMemberVariableDeclaration(); + } else if (this.isIndexMemberDeclaration()) { + return this.parseIndexMemberDeclaration(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isConstructorDeclaration = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 62 /* ConstructorKeyword */; + }; + + ParserImpl.prototype.parseConstructorDeclaration = function () { + var modifiers = this.parseModifiers(); + var constructorKeyword = this.eatKeyword(62 /* ConstructorKeyword */); + var callSignature = this.parseCallSignature(false); + + var semicolonToken = null; + var block = null; + + if (this.isBlock()) { + block = this.parseBlock(false, true); + } else { + semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.constructorDeclaration(modifiers, constructorKeyword, callSignature, block, semicolonToken); + }; + + ParserImpl.prototype.isMemberFunctionDeclaration = function (inErrorRecovery) { + var index = 0; + + while (true) { + var token = this.peekToken(index); + if (this.isPropertyName(token, inErrorRecovery) && this.isCallSignature(index + 1)) { + return true; + } + + if (ParserImpl.isModifier(token)) { + index++; + continue; + } + + return false; + } + }; + + ParserImpl.prototype.parseMemberFunctionDeclaration = function () { + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (this.isPropertyName(currentToken, false) && this.isCallSignature(1)) { + break; + } + + TypeScript.Debug.assert(ParserImpl.isModifier(currentToken)); + modifierArray.push(this.eatAnyToken()); + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var propertyName = this.eatPropertyName(); + var callSignature = this.parseCallSignature(false); + + var parseBlockEvenWithNoOpenBrace = false; + var newCallSignature = this.tryAddUnexpectedEqualsGreaterThanToken(callSignature); + if (newCallSignature !== callSignature) { + parseBlockEvenWithNoOpenBrace = true; + callSignature = newCallSignature; + } + + var block = null; + var semicolon = null; + + if (parseBlockEvenWithNoOpenBrace || this.isBlock()) { + block = this.parseBlock(parseBlockEvenWithNoOpenBrace, true); + } else { + semicolon = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.memberFunctionDeclaration(modifiers, propertyName, callSignature, block, semicolon); + }; + + ParserImpl.prototype.isDefinitelyMemberVariablePropertyName = function (index) { + if (TypeScript.SyntaxFacts.isAnyKeyword(this.peekToken(index).tokenKind)) { + switch (this.peekToken(index + 1).tokenKind) { + case 78 /* SemicolonToken */: + case 107 /* EqualsToken */: + case 106 /* ColonToken */: + case 71 /* CloseBraceToken */: + case 10 /* EndOfFileToken */: + return true; + default: + return false; + } + } else { + return true; + } + }; + + ParserImpl.prototype.isMemberVariableDeclaration = function (inErrorRecovery) { + var index = 0; + + while (true) { + var token = this.peekToken(index); + if (this.isPropertyName(token, inErrorRecovery) && this.isDefinitelyMemberVariablePropertyName(index)) { + return true; + } + + if (ParserImpl.isModifier(this.peekToken(index))) { + index++; + continue; + } + + return false; + } + }; + + ParserImpl.prototype.parseMemberVariableDeclaration = function () { + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (this.isPropertyName(currentToken, false) && this.isDefinitelyMemberVariablePropertyName(0)) { + break; + } + + TypeScript.Debug.assert(ParserImpl.isModifier(currentToken)); + modifierArray.push(this.eatAnyToken()); + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var variableDeclarator = this.parseVariableDeclarator(true, true); + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.memberVariableDeclaration(modifiers, variableDeclarator, semicolon); + }; + + ParserImpl.prototype.isIndexMemberDeclaration = function () { + var index = this.modifierCount(); + return this.isIndexSignature(index); + }; + + ParserImpl.prototype.parseIndexMemberDeclaration = function () { + var modifiers = this.parseModifiers(); + var indexSignature = this.parseIndexSignature(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.indexMemberDeclaration(modifiers, indexSignature, semicolonToken); + }; + + ParserImpl.prototype.tryAddUnexpectedEqualsGreaterThanToken = function (callSignature) { + var token0 = this.currentToken(); + + var hasEqualsGreaterThanToken = token0.tokenKind === 85 /* EqualsGreaterThanToken */; + if (hasEqualsGreaterThanToken) { + if (callSignature.lastToken()) { + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token0.width(), TypeScript.DiagnosticCode.Unexpected_token_0_expected, [TypeScript.SyntaxFacts.getText(70 /* OpenBraceToken */)]); + this.addDiagnostic(diagnostic); + + var token = this.eatAnyToken(); + return this.addSkippedTokenAfterNode(callSignature, token0); + } + } + + return callSignature; + }; + + ParserImpl.prototype.isFunctionDeclaration = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 27 /* FunctionKeyword */; + }; + + ParserImpl.prototype.parseFunctionDeclaration = function () { + var modifiers = this.parseModifiers(); + var functionKeyword = this.eatKeyword(27 /* FunctionKeyword */); + var identifier = this.eatIdentifierToken(); + var callSignature = this.parseCallSignature(false); + + var parseBlockEvenWithNoOpenBrace = false; + var newCallSignature = this.tryAddUnexpectedEqualsGreaterThanToken(callSignature); + if (newCallSignature !== callSignature) { + parseBlockEvenWithNoOpenBrace = true; + callSignature = newCallSignature; + } + + var semicolonToken = null; + var block = null; + + if (parseBlockEvenWithNoOpenBrace || this.isBlock()) { + block = this.parseBlock(parseBlockEvenWithNoOpenBrace, true); + } else { + semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.functionDeclaration(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken); + }; + + ParserImpl.prototype.isModuleDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 65 /* ModuleKeyword */) { + return true; + } + + if (this.currentToken().tokenKind === 65 /* ModuleKeyword */) { + var token1 = this.peekToken(1); + return this.isIdentifier(token1) || token1.tokenKind === 14 /* StringLiteral */; + } + + return false; + }; + + ParserImpl.prototype.parseModuleDeclaration = function () { + var modifiers = this.parseModifiers(); + var moduleKeyword = this.eatKeyword(65 /* ModuleKeyword */); + + var moduleName = null; + var stringLiteral = null; + + if (this.currentToken().tokenKind === 14 /* StringLiteral */) { + stringLiteral = this.eatToken(14 /* StringLiteral */); + } else { + moduleName = this.parseName(); + } + + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var moduleElements = TypeScript.Syntax.emptyList; + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(4 /* ModuleDeclaration_ModuleElements */); + moduleElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.moduleDeclaration(modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken); + }; + + ParserImpl.prototype.isInterfaceDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 52 /* InterfaceKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 52 /* InterfaceKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseInterfaceDeclaration = function () { + var modifiers = this.parseModifiers(); + var interfaceKeyword = this.eatKeyword(52 /* InterfaceKeyword */); + var identifier = this.eatIdentifierToken(); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var heritageClauses = this.parseHeritageClauses(); + + var objectType = this.parseObjectType(); + return this.factory.interfaceDeclaration(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, objectType); + }; + + ParserImpl.prototype.parseObjectType = function () { + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var typeMembers = TypeScript.Syntax.emptySeparatedList; + if (openBraceToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(512 /* ObjectType_TypeMembers */); + typeMembers = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + return this.factory.objectType(openBraceToken, typeMembers, closeBraceToken); + }; + + ParserImpl.prototype.isTypeMember = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isTypeMember()) { + return true; + } + + return this.isCallSignature(0) || this.isConstructSignature() || this.isIndexSignature(0) || this.isMethodSignature(inErrorRecovery) || this.isPropertySignature(inErrorRecovery); + }; + + ParserImpl.prototype.parseTypeMember = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isTypeMember()) { + return this.eatNode(); + } + + if (this.isCallSignature(0)) { + return this.parseCallSignature(false); + } else if (this.isConstructSignature()) { + return this.parseConstructSignature(); + } else if (this.isIndexSignature(0)) { + return this.parseIndexSignature(); + } else if (this.isMethodSignature(inErrorRecovery)) { + return this.parseMethodSignature(); + } else if (this.isPropertySignature(inErrorRecovery)) { + return this.parsePropertySignature(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseConstructSignature = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + var callSignature = this.parseCallSignature(false); + + return this.factory.constructSignature(newKeyword, callSignature); + }; + + ParserImpl.prototype.parseIndexSignature = function () { + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + var parameter = this.parseParameter(); + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.indexSignature(openBracketToken, parameter, closeBracketToken, typeAnnotation); + }; + + ParserImpl.prototype.parseMethodSignature = function () { + var propertyName = this.eatPropertyName(); + var questionToken = this.tryEatToken(105 /* QuestionToken */); + var callSignature = this.parseCallSignature(false); + + return this.factory.methodSignature(propertyName, questionToken, callSignature); + }; + + ParserImpl.prototype.parsePropertySignature = function () { + var propertyName = this.eatPropertyName(); + var questionToken = this.tryEatToken(105 /* QuestionToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.propertySignature(propertyName, questionToken, typeAnnotation); + }; + + ParserImpl.prototype.isCallSignature = function (tokenIndex) { + var tokenKind = this.peekToken(tokenIndex).tokenKind; + return tokenKind === 72 /* OpenParenToken */ || tokenKind === 80 /* LessThanToken */; + }; + + ParserImpl.prototype.isConstructSignature = function () { + if (this.currentToken().tokenKind !== 31 /* NewKeyword */) { + return false; + } + + var token1 = this.peekToken(1); + return token1.tokenKind === 80 /* LessThanToken */ || token1.tokenKind === 72 /* OpenParenToken */; + }; + + ParserImpl.prototype.isIndexSignature = function (tokenIndex) { + return this.peekToken(tokenIndex).tokenKind === 74 /* OpenBracketToken */; + }; + + ParserImpl.prototype.isMethodSignature = function (inErrorRecovery) { + if (this.isPropertyName(this.currentToken(), inErrorRecovery)) { + if (this.isCallSignature(1)) { + return true; + } + + if (this.peekToken(1).tokenKind === 105 /* QuestionToken */ && this.isCallSignature(2)) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.isPropertySignature = function (inErrorRecovery) { + var currentToken = this.currentToken(); + + if (ParserImpl.isModifier(currentToken) && !currentToken.hasTrailingNewLine() && this.isPropertyName(this.peekToken(1), inErrorRecovery)) { + return false; + } + + return this.isPropertyName(currentToken, inErrorRecovery); + }; + + ParserImpl.prototype.isHeritageClause = function () { + var token0 = this.currentToken(); + return token0.tokenKind === 48 /* ExtendsKeyword */ || token0.tokenKind === 51 /* ImplementsKeyword */; + }; + + ParserImpl.prototype.isNotHeritageClauseTypeName = function () { + if (this.currentToken().tokenKind === 51 /* ImplementsKeyword */ || this.currentToken().tokenKind === 48 /* ExtendsKeyword */) { + return this.isIdentifier(this.peekToken(1)); + } + + return false; + }; + + ParserImpl.prototype.isHeritageClauseTypeName = function () { + if (this.isIdentifier(this.currentToken())) { + return !this.isNotHeritageClauseTypeName(); + } + + return false; + }; + + ParserImpl.prototype.parseHeritageClause = function () { + var extendsOrImplementsKeyword = this.eatAnyToken(); + TypeScript.Debug.assert(extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */ || extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + + var result = this.parseSeparatedSyntaxList(2048 /* HeritageClause_TypeNameList */); + var typeNames = result.list; + extendsOrImplementsKeyword = this.addSkippedTokensAfterToken(extendsOrImplementsKeyword, result.skippedTokens); + + return this.factory.heritageClause(extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */ ? 230 /* ExtendsHeritageClause */ : 231 /* ImplementsHeritageClause */, extendsOrImplementsKeyword, typeNames); + }; + + ParserImpl.prototype.isStatement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isStatement()) { + return true; + } + + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + switch (currentTokenKind) { + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + var token1 = this.peekToken(1); + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token1)) { + return false; + } + + break; + + case 28 /* IfKeyword */: + case 70 /* OpenBraceToken */: + case 33 /* ReturnKeyword */: + case 34 /* SwitchKeyword */: + case 36 /* ThrowKeyword */: + case 15 /* BreakKeyword */: + case 18 /* ContinueKeyword */: + case 26 /* ForKeyword */: + case 42 /* WhileKeyword */: + case 43 /* WithKeyword */: + case 22 /* DoKeyword */: + case 38 /* TryKeyword */: + case 19 /* DebuggerKeyword */: + return true; + } + + if (this.isInterfaceDeclaration(0) || this.isClassDeclaration(0) || this.isEnumDeclaration(0) || this.isModuleDeclaration(0)) { + return false; + } + + return this.isLabeledStatement(currentToken) || this.isVariableStatement() || this.isFunctionDeclaration() || this.isEmptyStatement(currentToken, inErrorRecovery) || this.isExpressionStatement(currentToken); + }; + + ParserImpl.prototype.parseStatement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isStatement()) { + return this.eatNode(); + } + + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + + switch (currentTokenKind) { + case 28 /* IfKeyword */: + return this.parseIfStatement(); + case 70 /* OpenBraceToken */: + return this.parseBlock(false, false); + case 33 /* ReturnKeyword */: + return this.parseReturnStatement(); + case 34 /* SwitchKeyword */: + return this.parseSwitchStatement(); + case 36 /* ThrowKeyword */: + return this.parseThrowStatement(); + case 15 /* BreakKeyword */: + return this.parseBreakStatement(); + case 18 /* ContinueKeyword */: + return this.parseContinueStatement(); + case 26 /* ForKeyword */: + return this.parseForOrForInStatement(); + case 42 /* WhileKeyword */: + return this.parseWhileStatement(); + case 43 /* WithKeyword */: + return this.parseWithStatement(); + case 22 /* DoKeyword */: + return this.parseDoStatement(); + case 38 /* TryKeyword */: + return this.parseTryStatement(); + case 19 /* DebuggerKeyword */: + return this.parseDebuggerStatement(); + } + + if (this.isVariableStatement()) { + return this.parseVariableStatement(); + } else if (this.isLabeledStatement(currentToken)) { + return this.parseLabeledStatement(); + } else if (this.isFunctionDeclaration()) { + return this.parseFunctionDeclaration(); + } else if (this.isEmptyStatement(currentToken, inErrorRecovery)) { + return this.parseEmptyStatement(); + } else { + return this.parseExpressionStatement(); + } + }; + + ParserImpl.prototype.parseDebuggerStatement = function () { + var debuggerKeyword = this.eatKeyword(19 /* DebuggerKeyword */); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.debuggerStatement(debuggerKeyword, semicolonToken); + }; + + ParserImpl.prototype.parseDoStatement = function () { + var doKeyword = this.eatKeyword(22 /* DoKeyword */); + var statement = this.parseStatement(false); + var whileKeyword = this.eatKeyword(42 /* WhileKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(true); + + return this.factory.doStatement(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); + }; + + ParserImpl.prototype.isLabeledStatement = function (currentToken) { + return this.isIdentifier(currentToken) && this.peekToken(1).tokenKind === 106 /* ColonToken */; + }; + + ParserImpl.prototype.parseLabeledStatement = function () { + var identifier = this.eatIdentifierToken(); + var colonToken = this.eatToken(106 /* ColonToken */); + var statement = this.parseStatement(false); + + return this.factory.labeledStatement(identifier, colonToken, statement); + }; + + ParserImpl.prototype.parseTryStatement = function () { + var tryKeyword = this.eatKeyword(38 /* TryKeyword */); + + var savedListParsingState = this.listParsingState; + this.listParsingState |= 64 /* TryBlock_Statements */; + var block = this.parseBlock(false, false); + this.listParsingState = savedListParsingState; + + var catchClause = null; + if (this.isCatchClause()) { + catchClause = this.parseCatchClause(); + } + + var finallyClause = null; + if (catchClause === null || this.isFinallyClause()) { + finallyClause = this.parseFinallyClause(); + } + + return this.factory.tryStatement(tryKeyword, block, catchClause, finallyClause); + }; + + ParserImpl.prototype.isCatchClause = function () { + return this.currentToken().tokenKind === 17 /* CatchKeyword */; + }; + + ParserImpl.prototype.parseCatchClause = function () { + var catchKeyword = this.eatKeyword(17 /* CatchKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var identifier = this.eatIdentifierToken(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + var savedListParsingState = this.listParsingState; + this.listParsingState |= 128 /* CatchBlock_Statements */; + var block = this.parseBlock(false, false); + this.listParsingState = savedListParsingState; + + return this.factory.catchClause(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block); + }; + + ParserImpl.prototype.isFinallyClause = function () { + return this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.parseFinallyClause = function () { + var finallyKeyword = this.eatKeyword(25 /* FinallyKeyword */); + var block = this.parseBlock(false, false); + + return this.factory.finallyClause(finallyKeyword, block); + }; + + ParserImpl.prototype.parseWithStatement = function () { + var withKeyword = this.eatKeyword(43 /* WithKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.withStatement(withKeyword, openParenToken, condition, closeParenToken, statement); + }; + + ParserImpl.prototype.parseWhileStatement = function () { + var whileKeyword = this.eatKeyword(42 /* WhileKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.whileStatement(whileKeyword, openParenToken, condition, closeParenToken, statement); + }; + + ParserImpl.prototype.isEmptyStatement = function (currentToken, inErrorRecovery) { + if (inErrorRecovery) { + return false; + } + + return currentToken.tokenKind === 78 /* SemicolonToken */; + }; + + ParserImpl.prototype.parseEmptyStatement = function () { + var semicolonToken = this.eatToken(78 /* SemicolonToken */); + return this.factory.emptyStatement(semicolonToken); + }; + + ParserImpl.prototype.parseForOrForInStatement = function () { + var forKeyword = this.eatKeyword(26 /* ForKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + + var currentToken = this.currentToken(); + if (currentToken.tokenKind === 40 /* VarKeyword */) { + return this.parseForOrForInStatementWithVariableDeclaration(forKeyword, openParenToken); + } else if (currentToken.tokenKind === 78 /* SemicolonToken */) { + return this.parseForStatementWithNoVariableDeclarationOrInitializer(forKeyword, openParenToken); + } else { + return this.parseForOrForInStatementWithInitializer(forKeyword, openParenToken); + } + }; + + ParserImpl.prototype.parseForOrForInStatementWithVariableDeclaration = function (forKeyword, openParenToken) { + var variableDeclaration = this.parseVariableDeclaration(false); + + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return this.parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null); + } + + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null); + }; + + ParserImpl.prototype.parseForInStatementWithVariableDeclarationOrInitializer = function (forKeyword, openParenToken, variableDeclaration, initializer) { + var inKeyword = this.eatKeyword(29 /* InKeyword */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.forInStatement(forKeyword, openParenToken, variableDeclaration, initializer, inKeyword, expression, closeParenToken, statement); + }; + + ParserImpl.prototype.parseForOrForInStatementWithInitializer = function (forKeyword, openParenToken) { + var initializer = this.parseExpression(false); + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return this.parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + } else { + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + } + }; + + ParserImpl.prototype.parseForStatementWithNoVariableDeclarationOrInitializer = function (forKeyword, openParenToken) { + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, null); + }; + + ParserImpl.prototype.parseForStatementWithVariableDeclarationOrInitializer = function (forKeyword, openParenToken, variableDeclaration, initializer) { + var firstSemicolonToken = this.eatToken(78 /* SemicolonToken */); + + var condition = null; + if (this.currentToken().tokenKind !== 78 /* SemicolonToken */ && this.currentToken().tokenKind !== 73 /* CloseParenToken */ && this.currentToken().tokenKind !== 10 /* EndOfFileToken */) { + condition = this.parseExpression(true); + } + + var secondSemicolonToken = this.eatToken(78 /* SemicolonToken */); + + var incrementor = null; + if (this.currentToken().tokenKind !== 73 /* CloseParenToken */ && this.currentToken().tokenKind !== 10 /* EndOfFileToken */) { + incrementor = this.parseExpression(true); + } + + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.forStatement(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement); + }; + + ParserImpl.prototype.parseBreakStatement = function () { + var breakKeyword = this.eatKeyword(15 /* BreakKeyword */); + + var identifier = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + } + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + return this.factory.breakStatement(breakKeyword, identifier, semicolon); + }; + + ParserImpl.prototype.parseContinueStatement = function () { + var continueKeyword = this.eatKeyword(18 /* ContinueKeyword */); + + var identifier = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + } + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + return this.factory.continueStatement(continueKeyword, identifier, semicolon); + }; + + ParserImpl.prototype.parseSwitchStatement = function () { + var switchKeyword = this.eatKeyword(34 /* SwitchKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var switchClauses = TypeScript.Syntax.emptyList; + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(8 /* SwitchStatement_SwitchClauses */); + switchClauses = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + return this.factory.switchStatement(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken); + }; + + ParserImpl.prototype.isCaseSwitchClause = function () { + return this.currentToken().tokenKind === 16 /* CaseKeyword */; + }; + + ParserImpl.prototype.isDefaultSwitchClause = function () { + return this.currentToken().tokenKind === 20 /* DefaultKeyword */; + }; + + ParserImpl.prototype.isSwitchClause = function () { + if (this.currentNode() !== null && this.currentNode().isSwitchClause()) { + return true; + } + + return this.isCaseSwitchClause() || this.isDefaultSwitchClause(); + }; + + ParserImpl.prototype.parseSwitchClause = function () { + if (this.currentNode() !== null && this.currentNode().isSwitchClause()) { + return this.eatNode(); + } + + if (this.isCaseSwitchClause()) { + return this.parseCaseSwitchClause(); + } else if (this.isDefaultSwitchClause()) { + return this.parseDefaultSwitchClause(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseCaseSwitchClause = function () { + var caseKeyword = this.eatKeyword(16 /* CaseKeyword */); + var expression = this.parseExpression(true); + var colonToken = this.eatToken(106 /* ColonToken */); + var statements = TypeScript.Syntax.emptyList; + + if (colonToken.fullWidth() > 0) { + var result = this.parseSyntaxList(16 /* SwitchClause_Statements */); + statements = result.list; + colonToken = this.addSkippedTokensAfterToken(colonToken, result.skippedTokens); + } + + return this.factory.caseSwitchClause(caseKeyword, expression, colonToken, statements); + }; + + ParserImpl.prototype.parseDefaultSwitchClause = function () { + var defaultKeyword = this.eatKeyword(20 /* DefaultKeyword */); + var colonToken = this.eatToken(106 /* ColonToken */); + var statements = TypeScript.Syntax.emptyList; + + if (colonToken.fullWidth() > 0) { + var result = this.parseSyntaxList(16 /* SwitchClause_Statements */); + statements = result.list; + colonToken = this.addSkippedTokensAfterToken(colonToken, result.skippedTokens); + } + + return this.factory.defaultSwitchClause(defaultKeyword, colonToken, statements); + }; + + ParserImpl.prototype.parseThrowStatement = function () { + var throwKeyword = this.eatKeyword(36 /* ThrowKeyword */); + + var expression = null; + if (this.canEatExplicitOrAutomaticSemicolon(false)) { + var token = this.createMissingToken(11 /* IdentifierName */, null); + expression = token; + } else { + expression = this.parseExpression(true); + } + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.throwStatement(throwKeyword, expression, semicolonToken); + }; + + ParserImpl.prototype.parseReturnStatement = function () { + var returnKeyword = this.eatKeyword(33 /* ReturnKeyword */); + + var expression = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + expression = this.parseExpression(true); + } + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.returnStatement(returnKeyword, expression, semicolonToken); + }; + + ParserImpl.prototype.isExpressionStatement = function (currentToken) { + var kind = currentToken.tokenKind; + if (kind === 70 /* OpenBraceToken */ || kind === 27 /* FunctionKeyword */) { + return false; + } + + return this.isExpression(currentToken); + }; + + ParserImpl.prototype.isAssignmentOrOmittedExpression = function () { + var currentToken = this.currentToken(); + if (currentToken.tokenKind === 79 /* CommaToken */) { + return true; + } + + return this.isExpression(currentToken); + }; + + ParserImpl.prototype.parseAssignmentOrOmittedExpression = function () { + if (this.currentToken().tokenKind === 79 /* CommaToken */) { + return this.factory.omittedExpression(); + } + + return this.parseAssignmentExpression(true); + }; + + ParserImpl.prototype.isExpression = function (currentToken) { + switch (currentToken.tokenKind) { + case 13 /* NumericLiteral */: + case 14 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + + case 74 /* OpenBracketToken */: + + case 72 /* OpenParenToken */: + + case 80 /* LessThanToken */: + + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + case 89 /* PlusToken */: + case 90 /* MinusToken */: + case 102 /* TildeToken */: + case 101 /* ExclamationToken */: + + case 70 /* OpenBraceToken */: + + case 85 /* EqualsGreaterThanToken */: + + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + + case 50 /* SuperKeyword */: + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + + case 31 /* NewKeyword */: + + case 21 /* DeleteKeyword */: + case 41 /* VoidKeyword */: + case 39 /* TypeOfKeyword */: + + case 27 /* FunctionKeyword */: + return true; + } + + return this.isIdentifier(currentToken); + }; + + ParserImpl.prototype.parseExpressionStatement = function () { + var expression = this.parseExpression(true); + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.expressionStatement(expression, semicolon); + }; + + ParserImpl.prototype.parseIfStatement = function () { + var ifKeyword = this.eatKeyword(28 /* IfKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + var elseClause = null; + if (this.isElseClause()) { + elseClause = this.parseElseClause(); + } + + return this.factory.ifStatement(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause); + }; + + ParserImpl.prototype.isElseClause = function () { + return this.currentToken().tokenKind === 23 /* ElseKeyword */; + }; + + ParserImpl.prototype.parseElseClause = function () { + var elseKeyword = this.eatKeyword(23 /* ElseKeyword */); + var statement = this.parseStatement(false); + + return this.factory.elseClause(elseKeyword, statement); + }; + + ParserImpl.prototype.isVariableStatement = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 40 /* VarKeyword */; + }; + + ParserImpl.prototype.parseVariableStatement = function () { + var modifiers = this.parseModifiers(); + var variableDeclaration = this.parseVariableDeclaration(true); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.variableStatement(modifiers, variableDeclaration, semicolonToken); + }; + + ParserImpl.prototype.parseVariableDeclaration = function (allowIn) { + var varKeyword = this.eatKeyword(40 /* VarKeyword */); + + var listParsingState = allowIn ? 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */ : 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */; + + var result = this.parseSeparatedSyntaxList(listParsingState); + var variableDeclarators = result.list; + varKeyword = this.addSkippedTokensAfterToken(varKeyword, result.skippedTokens); + + return this.factory.variableDeclaration(varKeyword, variableDeclarators); + }; + + ParserImpl.prototype.isVariableDeclarator = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 225 /* VariableDeclarator */) { + return true; + } + + return this.isIdentifier(this.currentToken()); + }; + + ParserImpl.prototype.canReuseVariableDeclaratorNode = function (node) { + if (node === null || node.kind() !== 225 /* VariableDeclarator */) { + return false; + } + + var variableDeclarator = node; + return variableDeclarator.equalsValueClause === null; + }; + + ParserImpl.prototype.parseVariableDeclarator = function (allowIn, allowPropertyName) { + if (this.canReuseVariableDeclaratorNode(this.currentNode())) { + return this.eatNode(); + } + + var propertyName = allowPropertyName ? this.eatPropertyName() : this.eatIdentifierToken(); + var equalsValueClause = null; + var typeAnnotation = null; + + if (propertyName.width() > 0) { + typeAnnotation = this.parseOptionalTypeAnnotation(false); + + if (this.isEqualsValueClause(false)) { + equalsValueClause = this.parseEqualsValueClause(allowIn); + } + } + + return this.factory.variableDeclarator(propertyName, typeAnnotation, equalsValueClause); + }; + + ParserImpl.prototype.isColonValueClause = function () { + return this.currentToken().tokenKind === 106 /* ColonToken */; + }; + + ParserImpl.prototype.isEqualsValueClause = function (inParameter) { + var token0 = this.currentToken(); + if (token0.tokenKind === 107 /* EqualsToken */) { + return true; + } + + if (!this.previousToken().hasTrailingNewLine()) { + if (token0.tokenKind === 85 /* EqualsGreaterThanToken */) { + return false; + } + + if (token0.tokenKind === 70 /* OpenBraceToken */ && inParameter) { + return false; + } + + return this.isExpression(token0); + } + + return false; + }; + + ParserImpl.prototype.parseEqualsValueClause = function (allowIn) { + var equalsToken = this.eatToken(107 /* EqualsToken */); + var value = this.parseAssignmentExpression(allowIn); + + return this.factory.equalsValueClause(equalsToken, value); + }; + + ParserImpl.prototype.parseExpression = function (allowIn) { + return this.parseSubExpression(0, allowIn); + }; + + ParserImpl.prototype.parseAssignmentExpression = function (allowIn) { + return this.parseSubExpression(2 /* AssignmentExpressionPrecedence */, allowIn); + }; + + ParserImpl.prototype.parseUnaryExpressionOrLower = function () { + var currentTokenKind = this.currentToken().tokenKind; + if (TypeScript.SyntaxFacts.isPrefixUnaryExpressionOperatorToken(currentTokenKind)) { + var operatorKind = TypeScript.SyntaxFacts.getPrefixUnaryExpressionFromOperatorToken(currentTokenKind); + + var operatorToken = this.eatAnyToken(); + + var operand = this.parseUnaryExpressionOrLower(); + return this.factory.prefixUnaryExpression(operatorKind, operatorToken, operand); + } else if (currentTokenKind === 39 /* TypeOfKeyword */) { + return this.parseTypeOfExpression(); + } else if (currentTokenKind === 41 /* VoidKeyword */) { + return this.parseVoidExpression(); + } else if (currentTokenKind === 21 /* DeleteKeyword */) { + return this.parseDeleteExpression(); + } else if (currentTokenKind === 80 /* LessThanToken */) { + return this.parseCastExpression(); + } else { + return this.parsePostfixExpressionOrLower(); + } + }; + + ParserImpl.prototype.parseSubExpression = function (precedence, allowIn) { + if (precedence <= 2 /* AssignmentExpressionPrecedence */) { + if (this.isSimpleArrowFunctionExpression()) { + return this.parseSimpleArrowFunctionExpression(); + } + + var parethesizedArrowFunction = this.tryParseParenthesizedArrowFunctionExpression(); + if (parethesizedArrowFunction !== null) { + return parethesizedArrowFunction; + } + } + + var leftOperand = this.parseUnaryExpressionOrLower(); + return this.parseBinaryOrConditionalExpressions(precedence, allowIn, leftOperand); + }; + + ParserImpl.prototype.parseBinaryOrConditionalExpressions = function (precedence, allowIn, leftOperand) { + while (true) { + var token0 = this.currentToken(); + var token0Kind = token0.tokenKind; + + if (TypeScript.SyntaxFacts.isBinaryExpressionOperatorToken(token0Kind)) { + if (token0Kind === 29 /* InKeyword */ && !allowIn) { + break; + } + + var mergedToken = this.tryMergeBinaryExpressionTokens(); + var tokenKind = mergedToken === null ? token0Kind : mergedToken.syntaxKind; + + var binaryExpressionKind = TypeScript.SyntaxFacts.getBinaryExpressionFromOperatorToken(tokenKind); + var newPrecedence = ParserImpl.getPrecedence(binaryExpressionKind); + + if (newPrecedence < precedence) { + break; + } + + if (newPrecedence === precedence && !this.isRightAssociative(binaryExpressionKind)) { + break; + } + + var operatorToken = mergedToken === null ? token0 : TypeScript.Syntax.token(mergedToken.syntaxKind).withLeadingTrivia(token0.leadingTrivia()).withTrailingTrivia(this.peekToken(mergedToken.tokenCount - 1).trailingTrivia()); + + var skipCount = mergedToken === null ? 1 : mergedToken.tokenCount; + for (var i = 0; i < skipCount; i++) { + this.eatAnyToken(); + } + + leftOperand = this.factory.binaryExpression(binaryExpressionKind, leftOperand, operatorToken, this.parseSubExpression(newPrecedence, allowIn)); + continue; + } + + if (token0Kind === 105 /* QuestionToken */ && precedence <= 3 /* ConditionalExpressionPrecedence */) { + var questionToken = this.eatToken(105 /* QuestionToken */); + + var whenTrueExpression = this.parseAssignmentExpression(allowIn); + var colon = this.eatToken(106 /* ColonToken */); + + var whenFalseExpression = this.parseAssignmentExpression(allowIn); + leftOperand = this.factory.conditionalExpression(leftOperand, questionToken, whenTrueExpression, colon, whenFalseExpression); + continue; + } + + break; + } + + return leftOperand; + }; + + ParserImpl.prototype.tryMergeBinaryExpressionTokens = function () { + var token0 = this.currentToken(); + + if (token0.tokenKind === 81 /* GreaterThanToken */ && !token0.hasTrailingTrivia()) { + var storage = this.mergeTokensStorage; + storage[0] = 0 /* None */; + storage[1] = 0 /* None */; + storage[2] = 0 /* None */; + + for (var i = 0; i < storage.length; i++) { + var nextToken = this.peekToken(i + 1); + + if (!nextToken.hasLeadingTrivia()) { + storage[i] = nextToken.tokenKind; + } + + if (nextToken.hasTrailingTrivia()) { + break; + } + } + + if (storage[0] === 81 /* GreaterThanToken */) { + if (storage[1] === 81 /* GreaterThanToken */) { + if (storage[2] === 107 /* EqualsToken */) { + return { tokenCount: 4, syntaxKind: 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */ }; + } else { + return { tokenCount: 3, syntaxKind: 97 /* GreaterThanGreaterThanGreaterThanToken */ }; + } + } else if (storage[1] === 107 /* EqualsToken */) { + return { tokenCount: 3, syntaxKind: 113 /* GreaterThanGreaterThanEqualsToken */ }; + } else { + return { tokenCount: 2, syntaxKind: 96 /* GreaterThanGreaterThanToken */ }; + } + } else if (storage[0] === 107 /* EqualsToken */) { + return { tokenCount: 2, syntaxKind: 83 /* GreaterThanEqualsToken */ }; + } + } + + return null; + }; + + ParserImpl.prototype.isRightAssociative = function (expressionKind) { + switch (expressionKind) { + case 174 /* AssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + return true; + default: + return false; + } + }; + + ParserImpl.prototype.parseMemberExpressionOrLower = function (inObjectCreation) { + if (this.currentToken().tokenKind === 31 /* NewKeyword */) { + return this.parseObjectCreationExpression(); + } + + var expression = this.parsePrimaryExpression(); + if (expression === null) { + return this.eatIdentifierToken(); + } + + return this.parseMemberExpressionRest(expression, false, inObjectCreation); + }; + + ParserImpl.prototype.parseCallExpressionOrLower = function () { + var expression; + if (this.currentToken().tokenKind === 50 /* SuperKeyword */) { + expression = this.eatKeyword(50 /* SuperKeyword */); + + var currentTokenKind = this.currentToken().tokenKind; + if (currentTokenKind !== 72 /* OpenParenToken */ && currentTokenKind !== 76 /* DotToken */) { + expression = this.factory.memberAccessExpression(expression, this.eatToken(76 /* DotToken */), this.eatIdentifierNameToken()); + } + } else { + expression = this.parseMemberExpressionOrLower(false); + } + + return this.parseMemberExpressionRest(expression, true, false); + }; + + ParserImpl.prototype.parseMemberExpressionRest = function (expression, allowArguments, inObjectCreation) { + while (true) { + var currentTokenKind = this.currentToken().tokenKind; + + switch (currentTokenKind) { + case 72 /* OpenParenToken */: + if (!allowArguments) { + return expression; + } + + expression = this.factory.invocationExpression(expression, this.parseArgumentList(null)); + continue; + + case 80 /* LessThanToken */: + if (!allowArguments) { + return expression; + } + + var argumentList = this.tryParseArgumentList(); + if (argumentList !== null) { + expression = this.factory.invocationExpression(expression, argumentList); + continue; + } + + break; + + case 74 /* OpenBracketToken */: + expression = this.parseElementAccessExpression(expression, inObjectCreation); + continue; + + case 76 /* DotToken */: + expression = this.factory.memberAccessExpression(expression, this.eatToken(76 /* DotToken */), this.eatIdentifierNameToken()); + continue; + } + + return expression; + } + }; + + ParserImpl.prototype.parseLeftHandSideExpressionOrLower = function () { + if (this.currentToken().tokenKind === 31 /* NewKeyword */) { + return this.parseObjectCreationExpression(); + } else { + return this.parseCallExpressionOrLower(); + } + }; + + ParserImpl.prototype.parsePostfixExpressionOrLower = function () { + var expression = this.parseLeftHandSideExpressionOrLower(); + if (expression === null) { + return this.eatIdentifierToken(); + } + + var currentTokenKind = this.currentToken().tokenKind; + + switch (currentTokenKind) { + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + if (this.previousToken() !== null && this.previousToken().hasTrailingNewLine()) { + break; + } + + return this.factory.postfixUnaryExpression(TypeScript.SyntaxFacts.getPostfixUnaryExpressionFromOperatorToken(currentTokenKind), expression, this.eatAnyToken()); + } + + return expression; + }; + + ParserImpl.prototype.tryParseGenericArgumentList = function () { + var rewindPoint = this.getRewindPoint(); + + var typeArgumentList = this.tryParseTypeArgumentList(true); + var token0 = this.currentToken(); + + var isOpenParen = token0.tokenKind === 72 /* OpenParenToken */; + var isDot = token0.tokenKind === 76 /* DotToken */; + var isOpenParenOrDot = isOpenParen || isDot; + + var argumentList = null; + if (typeArgumentList === null || !isOpenParenOrDot) { + this.rewind(rewindPoint); + this.releaseRewindPoint(rewindPoint); + return null; + } else { + this.releaseRewindPoint(rewindPoint); + + if (isDot) { + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token0.width(), TypeScript.DiagnosticCode.A_parameter_list_must_follow_a_generic_type_argument_list_expected, null); + this.addDiagnostic(diagnostic); + + return this.factory.argumentList(typeArgumentList, TypeScript.Syntax.emptyToken(72 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.emptyToken(73 /* CloseParenToken */)); + } else { + return this.parseArgumentList(typeArgumentList); + } + } + }; + + ParserImpl.prototype.tryParseArgumentList = function () { + if (this.currentToken().tokenKind === 80 /* LessThanToken */) { + return this.tryParseGenericArgumentList(); + } + + if (this.currentToken().tokenKind === 72 /* OpenParenToken */) { + return this.parseArgumentList(null); + } + + return null; + }; + + ParserImpl.prototype.parseArgumentList = function (typeArgumentList) { + var openParenToken = this.eatToken(72 /* OpenParenToken */); + + var _arguments = TypeScript.Syntax.emptySeparatedList; + + if (openParenToken.fullWidth() > 0) { + var result = this.parseSeparatedSyntaxList(16384 /* ArgumentList_AssignmentExpressions */); + _arguments = result.list; + openParenToken = this.addSkippedTokensAfterToken(openParenToken, result.skippedTokens); + } + + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + return this.factory.argumentList(typeArgumentList, openParenToken, _arguments, closeParenToken); + }; + + ParserImpl.prototype.parseElementAccessExpression = function (expression, inObjectCreation) { + var start = this.currentTokenStart(); + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + var argumentExpression; + + if (this.currentToken().tokenKind === 75 /* CloseBracketToken */ && inObjectCreation) { + var end = this.currentTokenStart() + this.currentToken().width(); + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, start, end - start, TypeScript.DiagnosticCode.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead, null); + this.addDiagnostic(diagnostic); + + argumentExpression = TypeScript.Syntax.emptyToken(11 /* IdentifierName */); + } else { + argumentExpression = this.parseExpression(true); + } + + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + + return this.factory.elementAccessExpression(expression, openBracketToken, argumentExpression, closeBracketToken); + }; + + ParserImpl.prototype.parsePrimaryExpression = function () { + var currentToken = this.currentToken(); + + if (this.isIdentifier(currentToken)) { + return this.eatIdentifierToken(); + } + + var currentTokenKind = currentToken.tokenKind; + switch (currentTokenKind) { + case 35 /* ThisKeyword */: + return this.parseThisExpression(); + + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return this.parseLiteralExpression(); + + case 32 /* NullKeyword */: + return this.parseLiteralExpression(); + + case 27 /* FunctionKeyword */: + return this.parseFunctionExpression(); + + case 13 /* NumericLiteral */: + return this.parseLiteralExpression(); + + case 12 /* RegularExpressionLiteral */: + return this.parseLiteralExpression(); + + case 14 /* StringLiteral */: + return this.parseLiteralExpression(); + + case 74 /* OpenBracketToken */: + return this.parseArrayLiteralExpression(); + + case 70 /* OpenBraceToken */: + return this.parseObjectLiteralExpression(); + + case 72 /* OpenParenToken */: + return this.parseParenthesizedExpression(); + + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + var result = this.tryReparseDivideAsRegularExpression(); + if (result !== null) { + return result; + } + break; + } + + return null; + }; + + ParserImpl.prototype.tryReparseDivideAsRegularExpression = function () { + var currentToken = this.currentToken(); + + if (this.previousToken() !== null) { + var previousTokenKind = this.previousToken().tokenKind; + switch (previousTokenKind) { + case 11 /* IdentifierName */: + return null; + + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return null; + + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + case 12 /* RegularExpressionLiteral */: + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + case 75 /* CloseBracketToken */: + return null; + } + } + + currentToken = this.currentTokenAllowingRegularExpression(); + + if (currentToken.tokenKind === 118 /* SlashToken */ || currentToken.tokenKind === 119 /* SlashEqualsToken */) { + return null; + } else if (currentToken.tokenKind === 12 /* RegularExpressionLiteral */) { + return this.parseLiteralExpression(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseTypeOfExpression = function () { + var typeOfKeyword = this.eatKeyword(39 /* TypeOfKeyword */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.typeOfExpression(typeOfKeyword, expression); + }; + + ParserImpl.prototype.parseDeleteExpression = function () { + var deleteKeyword = this.eatKeyword(21 /* DeleteKeyword */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.deleteExpression(deleteKeyword, expression); + }; + + ParserImpl.prototype.parseVoidExpression = function () { + var voidKeyword = this.eatKeyword(41 /* VoidKeyword */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.voidExpression(voidKeyword, expression); + }; + + ParserImpl.prototype.parseFunctionExpression = function () { + var functionKeyword = this.eatKeyword(27 /* FunctionKeyword */); + var identifier = null; + + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + + var callSignature = this.parseCallSignature(false); + var block = this.parseBlock(false, true); + + return this.factory.functionExpression(functionKeyword, identifier, callSignature, block); + }; + + ParserImpl.prototype.parseObjectCreationExpression = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + + var expression = this.parseObjectCreationExpressionOrLower(true); + var argumentList = this.tryParseArgumentList(); + + var result = this.factory.objectCreationExpression(newKeyword, expression, argumentList); + return this.parseMemberExpressionRest(result, true, false); + }; + + ParserImpl.prototype.parseObjectCreationExpressionOrLower = function (inObjectCreation) { + if (this.currentToken().tokenKind === 31 /* NewKeyword */) { + return this.parseObjectCreationExpression(); + } else { + return this.parseMemberExpressionOrLower(inObjectCreation); + } + }; + + ParserImpl.prototype.parseCastExpression = function () { + var lessThanToken = this.eatToken(80 /* LessThanToken */); + var type = this.parseType(); + var greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.castExpression(lessThanToken, type, greaterThanToken, expression); + }; + + ParserImpl.prototype.parseParenthesizedExpression = function () { + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + return this.factory.parenthesizedExpression(openParenToken, expression, closeParenToken); + }; + + ParserImpl.prototype.tryParseParenthesizedArrowFunctionExpression = function () { + var tokenKind = this.currentToken().tokenKind; + if (tokenKind !== 72 /* OpenParenToken */ && tokenKind !== 80 /* LessThanToken */) { + return null; + } + + if (this.isDefinitelyArrowFunctionExpression()) { + return this.parseParenthesizedArrowFunctionExpression(false); + } + + if (!this.isPossiblyArrowFunctionExpression()) { + return null; + } + + var rewindPoint = this.getRewindPoint(); + + var arrowFunction = this.parseParenthesizedArrowFunctionExpression(true); + if (arrowFunction === null) { + this.rewind(rewindPoint); + } + + this.releaseRewindPoint(rewindPoint); + return arrowFunction; + }; + + ParserImpl.prototype.parseParenthesizedArrowFunctionExpression = function (requireArrow) { + var currentToken = this.currentToken(); + + var callSignature = this.parseCallSignature(true); + + if (requireArrow && this.currentToken().tokenKind !== 85 /* EqualsGreaterThanToken */) { + return null; + } + + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + + var block = this.tryParseArrowFunctionBlock(); + var expression = null; + if (block === null) { + expression = this.parseAssignmentExpression(true); + } + + return this.factory.parenthesizedArrowFunctionExpression(callSignature, equalsGreaterThanToken, block, expression); + }; + + ParserImpl.prototype.tryParseArrowFunctionBlock = function () { + if (this.isBlock()) { + return this.parseBlock(false, false); + } else { + if (this.isStatement(false) && !this.isExpressionStatement(this.currentToken()) && !this.isFunctionDeclaration()) { + return this.parseBlock(true, false); + } else { + return null; + } + } + }; + + ParserImpl.prototype.isSimpleArrowFunctionExpression = function () { + if (this.currentToken().tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + + return this.isIdentifier(this.currentToken()) && this.peekToken(1).tokenKind === 85 /* EqualsGreaterThanToken */; + }; + + ParserImpl.prototype.parseSimpleArrowFunctionExpression = function () { + var identifier = this.eatIdentifierToken(); + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + + var block = this.tryParseArrowFunctionBlock(); + var expression = null; + if (block === null) { + expression = this.parseAssignmentExpression(true); + } + + return this.factory.simpleArrowFunctionExpression(identifier, equalsGreaterThanToken, block, expression); + }; + + ParserImpl.prototype.isBlock = function () { + return this.currentToken().tokenKind === 70 /* OpenBraceToken */; + }; + + ParserImpl.prototype.isDefinitelyArrowFunctionExpression = function () { + var token0 = this.currentToken(); + if (token0.tokenKind !== 72 /* OpenParenToken */) { + return false; + } + + var token1 = this.peekToken(1); + var token2; + + if (token1.tokenKind === 73 /* CloseParenToken */) { + token2 = this.peekToken(2); + return token2.tokenKind === 106 /* ColonToken */ || token2.tokenKind === 85 /* EqualsGreaterThanToken */ || token2.tokenKind === 70 /* OpenBraceToken */; + } + + if (token1.tokenKind === 77 /* DotDotDotToken */) { + return true; + } + + token2 = this.peekToken(2); + if (token1.tokenKind === 57 /* PublicKeyword */ || token1.tokenKind === 55 /* PrivateKeyword */) { + if (this.isIdentifier(token2)) { + return true; + } + } + + if (!this.isIdentifier(token1)) { + return false; + } + + if (token2.tokenKind === 106 /* ColonToken */) { + return true; + } + + var token3 = this.peekToken(3); + if (token2.tokenKind === 105 /* QuestionToken */) { + if (token3.tokenKind === 106 /* ColonToken */ || token3.tokenKind === 73 /* CloseParenToken */ || token3.tokenKind === 79 /* CommaToken */) { + return true; + } + } + + if (token2.tokenKind === 73 /* CloseParenToken */) { + if (token3.tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.isPossiblyArrowFunctionExpression = function () { + var token0 = this.currentToken(); + if (token0.tokenKind !== 72 /* OpenParenToken */) { + return true; + } + + var token1 = this.peekToken(1); + + if (!this.isIdentifier(token1)) { + return false; + } + + var token2 = this.peekToken(2); + if (token2.tokenKind === 107 /* EqualsToken */) { + return true; + } + + if (token2.tokenKind === 79 /* CommaToken */) { + return true; + } + + if (token2.tokenKind === 73 /* CloseParenToken */) { + var token3 = this.peekToken(3); + if (token3.tokenKind === 106 /* ColonToken */) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.parseObjectLiteralExpression = function () { + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var result = this.parseSeparatedSyntaxList(32768 /* ObjectLiteralExpression_PropertyAssignments */); + var propertyAssignments = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.objectLiteralExpression(openBraceToken, propertyAssignments, closeBraceToken); + }; + + ParserImpl.prototype.parsePropertyAssignment = function (inErrorRecovery) { + if (this.isAccessor(inErrorRecovery)) { + return this.parseAccessor(true); + } else if (this.isFunctionPropertyAssignment(inErrorRecovery)) { + return this.parseFunctionPropertyAssignment(); + } else if (this.isSimplePropertyAssignment(inErrorRecovery)) { + return this.parseSimplePropertyAssignment(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isPropertyAssignment = function (inErrorRecovery) { + return this.isAccessor(inErrorRecovery) || this.isFunctionPropertyAssignment(inErrorRecovery) || this.isSimplePropertyAssignment(inErrorRecovery); + }; + + ParserImpl.prototype.eatPropertyName = function () { + return TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(this.currentToken()) ? this.eatIdentifierNameToken() : this.eatAnyToken(); + }; + + ParserImpl.prototype.isFunctionPropertyAssignment = function (inErrorRecovery) { + return this.isPropertyName(this.currentToken(), inErrorRecovery) && this.isCallSignature(1); + }; + + ParserImpl.prototype.parseFunctionPropertyAssignment = function () { + var propertyName = this.eatPropertyName(); + var callSignature = this.parseCallSignature(false); + var block = this.parseBlock(false, true); + + return this.factory.functionPropertyAssignment(propertyName, callSignature, block); + }; + + ParserImpl.prototype.isSimplePropertyAssignment = function (inErrorRecovery) { + return this.isPropertyName(this.currentToken(), inErrorRecovery); + }; + + ParserImpl.prototype.parseSimplePropertyAssignment = function () { + var propertyName = this.eatPropertyName(); + var colonToken = this.eatToken(106 /* ColonToken */); + var expression = this.parseAssignmentExpression(true); + + return this.factory.simplePropertyAssignment(propertyName, colonToken, expression); + }; + + ParserImpl.prototype.isPropertyName = function (token, inErrorRecovery) { + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) { + if (inErrorRecovery) { + return this.isIdentifier(token); + } else { + return true; + } + } + + switch (token.tokenKind) { + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.parseArrayLiteralExpression = function () { + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + + var result = this.parseSeparatedSyntaxList(65536 /* ArrayLiteralExpression_AssignmentExpressions */); + var expressions = result.list; + openBracketToken = this.addSkippedTokensAfterToken(openBracketToken, result.skippedTokens); + + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + + return this.factory.arrayLiteralExpression(openBracketToken, expressions, closeBracketToken); + }; + + ParserImpl.prototype.parseLiteralExpression = function () { + return this.eatAnyToken(); + }; + + ParserImpl.prototype.parseThisExpression = function () { + return this.eatKeyword(35 /* ThisKeyword */); + }; + + ParserImpl.prototype.parseBlock = function (parseBlockEvenWithNoOpenBrace, checkForStrictMode) { + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var statements = TypeScript.Syntax.emptyList; + + if (parseBlockEvenWithNoOpenBrace || openBraceToken.width() > 0) { + var savedIsInStrictMode = this.isInStrictMode; + + var processItems = checkForStrictMode ? ParserImpl.updateStrictModeState : null; + var result = this.parseSyntaxList(32 /* Block_Statements */, processItems); + statements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + + this.setStrictMode(savedIsInStrictMode); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.block(openBraceToken, statements, closeBraceToken); + }; + + ParserImpl.prototype.parseCallSignature = function (requireCompleteTypeParameterList) { + var typeParameterList = this.parseOptionalTypeParameterList(requireCompleteTypeParameterList); + var parameterList = this.parseParameterList(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.callSignature(typeParameterList, parameterList, typeAnnotation); + }; + + ParserImpl.prototype.parseOptionalTypeParameterList = function (requireCompleteTypeParameterList) { + if (this.currentToken().tokenKind !== 80 /* LessThanToken */) { + return null; + } + + var rewindPoint = this.getRewindPoint(); + + var lessThanToken = this.eatToken(80 /* LessThanToken */); + + var result = this.parseSeparatedSyntaxList(524288 /* TypeParameterList_TypeParameters */); + var typeParameters = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + var greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + + if (requireCompleteTypeParameterList && greaterThanToken.fullWidth() === 0) { + this.rewind(rewindPoint); + this.releaseRewindPoint(rewindPoint); + return null; + } else { + this.releaseRewindPoint(rewindPoint); + var typeParameterList = this.factory.typeParameterList(lessThanToken, typeParameters, greaterThanToken); + + return typeParameterList; + } + }; + + ParserImpl.prototype.isTypeParameter = function () { + return this.isIdentifier(this.currentToken()); + }; + + ParserImpl.prototype.parseTypeParameter = function () { + var identifier = this.eatIdentifierToken(); + var constraint = this.parseOptionalConstraint(); + + return this.factory.typeParameter(identifier, constraint); + }; + + ParserImpl.prototype.parseOptionalConstraint = function () { + if (this.currentToken().kind() !== 48 /* ExtendsKeyword */) { + return null; + } + + var extendsKeyword = this.eatKeyword(48 /* ExtendsKeyword */); + var type = this.parseType(); + + return this.factory.constraint(extendsKeyword, type); + }; + + ParserImpl.prototype.parseParameterList = function () { + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var parameters = TypeScript.Syntax.emptySeparatedList; + + if (openParenToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(131072 /* ParameterList_Parameters */); + parameters = result.list; + openParenToken = this.addSkippedTokensAfterToken(openParenToken, result.skippedTokens); + } + + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + return this.factory.parameterList(openParenToken, parameters, closeParenToken); + }; + + ParserImpl.prototype.isTypeAnnotation = function () { + return this.currentToken().tokenKind === 106 /* ColonToken */; + }; + + ParserImpl.prototype.parseOptionalTypeAnnotation = function (allowStringLiteral) { + return this.isTypeAnnotation() ? this.parseTypeAnnotation(allowStringLiteral) : null; + }; + + ParserImpl.prototype.parseTypeAnnotation = function (allowStringLiteral) { + var colonToken = this.eatToken(106 /* ColonToken */); + var type = allowStringLiteral && this.currentToken().tokenKind === 14 /* StringLiteral */ ? this.eatToken(14 /* StringLiteral */) : this.parseType(); + + return this.factory.typeAnnotation(colonToken, type); + }; + + ParserImpl.prototype.isType = function () { + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + + switch (currentTokenKind) { + case 39 /* TypeOfKeyword */: + + case 60 /* AnyKeyword */: + case 67 /* NumberKeyword */: + case 61 /* BooleanKeyword */: + case 69 /* StringKeyword */: + case 41 /* VoidKeyword */: + + case 70 /* OpenBraceToken */: + + case 72 /* OpenParenToken */: + case 80 /* LessThanToken */: + + case 31 /* NewKeyword */: + return true; + } + + return this.isIdentifier(currentToken); + }; + + ParserImpl.prototype.parseType = function () { + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + + var type = this.parseNonArrayType(currentToken); + + while (this.currentToken().tokenKind === 74 /* OpenBracketToken */) { + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + + type = this.factory.arrayType(type, openBracketToken, closeBracketToken); + } + + return type; + }; + + ParserImpl.prototype.isTypeQuery = function () { + return this.currentToken().tokenKind === 39 /* TypeOfKeyword */; + }; + + ParserImpl.prototype.parseTypeQuery = function () { + var typeOfKeyword = this.eatToken(39 /* TypeOfKeyword */); + var name = this.parseName(); + + return this.factory.typeQuery(typeOfKeyword, name); + }; + + ParserImpl.prototype.parseNonArrayType = function (currentToken) { + var currentTokenKind = currentToken.tokenKind; + switch (currentTokenKind) { + case 60 /* AnyKeyword */: + case 67 /* NumberKeyword */: + case 61 /* BooleanKeyword */: + case 69 /* StringKeyword */: + case 41 /* VoidKeyword */: + return this.eatAnyToken(); + + case 70 /* OpenBraceToken */: + return this.parseObjectType(); + + case 72 /* OpenParenToken */: + case 80 /* LessThanToken */: + return this.parseFunctionType(); + + case 31 /* NewKeyword */: + return this.parseConstructorType(); + + case 39 /* TypeOfKeyword */: + return this.parseTypeQuery(); + } + + return this.parseNameOrGenericType(); + }; + + ParserImpl.prototype.parseNameOrGenericType = function () { + var name = this.parseName(); + var typeArgumentList = this.tryParseTypeArgumentList(false); + + return typeArgumentList === null ? name : this.factory.genericType(name, typeArgumentList); + }; + + ParserImpl.prototype.parseFunctionType = function () { + var typeParameterList = this.parseOptionalTypeParameterList(false); + var parameterList = this.parseParameterList(); + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + var returnType = this.parseType(); + + return this.factory.functionType(typeParameterList, parameterList, equalsGreaterThanToken, returnType); + }; + + ParserImpl.prototype.parseConstructorType = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var parameterList = this.parseParameterList(); + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + var type = this.parseType(); + + return this.factory.constructorType(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type); + }; + + ParserImpl.prototype.isParameter = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 242 /* Parameter */) { + return true; + } + + var token = this.currentToken(); + var tokenKind = token.tokenKind; + if (tokenKind === 77 /* DotDotDotToken */) { + return true; + } + + if (ParserImpl.isModifier(token) && !this.isModifierUsedAsParameterIdentifier(token)) { + return true; + } + + return this.isIdentifier(token); + }; + + ParserImpl.prototype.isModifierUsedAsParameterIdentifier = function (token) { + if (this.isIdentifier(token)) { + var nextTokenKind = this.peekToken(1).tokenKind; + switch (nextTokenKind) { + case 73 /* CloseParenToken */: + case 106 /* ColonToken */: + case 107 /* EqualsToken */: + case 79 /* CommaToken */: + case 105 /* QuestionToken */: + return true; + } + } + + return false; + }; + + ParserImpl.prototype.parseParameter = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 242 /* Parameter */) { + return this.eatNode(); + } + + var dotDotDotToken = this.tryEatToken(77 /* DotDotDotToken */); + + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (ParserImpl.isModifier(currentToken) && !this.isModifierUsedAsParameterIdentifier(currentToken)) { + modifierArray.push(this.eatAnyToken()); + continue; + } + + break; + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var identifier = this.eatIdentifierToken(); + var questionToken = this.tryEatToken(105 /* QuestionToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(true); + + var equalsValueClause = null; + if (this.isEqualsValueClause(true)) { + equalsValueClause = this.parseEqualsValueClause(true); + } + + return this.factory.parameter(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause); + }; + + ParserImpl.prototype.parseSyntaxList = function (currentListType, processItems) { + if (typeof processItems === "undefined") { processItems = null; } + var savedListParsingState = this.listParsingState; + this.listParsingState |= currentListType; + + var result = this.parseSyntaxListWorker(currentListType, processItems); + + this.listParsingState = savedListParsingState; + + return result; + }; + + ParserImpl.prototype.parseSeparatedSyntaxList = function (currentListType) { + var savedListParsingState = this.listParsingState; + this.listParsingState |= currentListType; + + var result = this.parseSeparatedSyntaxListWorker(currentListType); + + this.listParsingState = savedListParsingState; + + return result; + }; + + ParserImpl.prototype.abortParsingListOrMoveToNextToken = function (currentListType, items, skippedTokens) { + this.reportUnexpectedTokenDiagnostic(currentListType); + + for (var state = 524288 /* LastListParsingState */; state >= 1 /* FirstListParsingState */; state >>= 1) { + if ((this.listParsingState & state) !== 0) { + if (this.isExpectedListTerminator(state) || this.isExpectedListItem(state, true)) { + return true; + } + } + } + + var skippedToken = this.currentToken(); + + this.moveToNextToken(); + + this.addSkippedTokenToList(items, skippedTokens, skippedToken); + + return false; + }; + + ParserImpl.prototype.addSkippedTokenToList = function (items, skippedTokens, skippedToken) { + for (var i = items.length - 1; i >= 0; i--) { + var item = items[i]; + var lastToken = item.lastToken(); + if (lastToken.fullWidth() > 0) { + items[i] = this.addSkippedTokenAfterNodeOrToken(item, skippedToken); + return; + } + } + + skippedTokens.push(skippedToken); + }; + + ParserImpl.prototype.tryParseExpectedListItem = function (currentListType, inErrorRecovery, items, processItems) { + if (this.isExpectedListItem(currentListType, inErrorRecovery)) { + var item = this.parseExpectedListItem(currentListType, inErrorRecovery); + + items.push(item); + + if (processItems !== null) { + processItems(this, items); + } + } + }; + + ParserImpl.prototype.listIsTerminated = function (currentListType) { + return this.isExpectedListTerminator(currentListType) || this.currentToken().tokenKind === 10 /* EndOfFileToken */; + }; + + ParserImpl.prototype.getArray = function () { + if (this.arrayPool.length > 0) { + return this.arrayPool.pop(); + } + + return []; + }; + + ParserImpl.prototype.returnZeroOrOneLengthArray = function (array) { + if (array.length <= 1) { + this.returnArray(array); + } + }; + + ParserImpl.prototype.returnArray = function (array) { + array.length = 0; + this.arrayPool.push(array); + }; + + ParserImpl.prototype.parseSyntaxListWorker = function (currentListType, processItems) { + var items = this.getArray(); + var skippedTokens = this.getArray(); + + while (true) { + var oldItemsCount = items.length; + this.tryParseExpectedListItem(currentListType, false, items, processItems); + + var newItemsCount = items.length; + if (newItemsCount === oldItemsCount) { + if (this.listIsTerminated(currentListType)) { + break; + } + + var abort = this.abortParsingListOrMoveToNextToken(currentListType, items, skippedTokens); + if (abort) { + break; + } + } + } + + var result = TypeScript.Syntax.list(items); + + this.returnZeroOrOneLengthArray(items); + + return { skippedTokens: skippedTokens, list: result }; + }; + + ParserImpl.prototype.parseSeparatedSyntaxListWorker = function (currentListType) { + var items = this.getArray(); + var skippedTokens = this.getArray(); + TypeScript.Debug.assert(items.length === 0); + TypeScript.Debug.assert(skippedTokens.length === 0); + TypeScript.Debug.assert(skippedTokens !== items); + + var separatorKind = this.separatorKind(currentListType); + var allowAutomaticSemicolonInsertion = separatorKind === 78 /* SemicolonToken */; + + var inErrorRecovery = false; + var listWasTerminated = false; + while (true) { + var oldItemsCount = items.length; + + this.tryParseExpectedListItem(currentListType, inErrorRecovery, items, null); + + var newItemsCount = items.length; + if (newItemsCount === oldItemsCount) { + if (this.listIsTerminated(currentListType)) { + listWasTerminated = true; + break; + } + + var abort = this.abortParsingListOrMoveToNextToken(currentListType, items, skippedTokens); + if (abort) { + break; + } else { + inErrorRecovery = true; + continue; + } + } + + inErrorRecovery = false; + + var currentToken = this.currentToken(); + if (currentToken.tokenKind === separatorKind || currentToken.tokenKind === 79 /* CommaToken */) { + items.push(this.eatAnyToken()); + continue; + } + + if (this.listIsTerminated(currentListType)) { + listWasTerminated = true; + break; + } + + if (allowAutomaticSemicolonInsertion && this.canEatAutomaticSemicolon(false)) { + items.push(this.eatExplicitOrAutomaticSemicolon(false)); + + continue; + } + + items.push(this.eatToken(separatorKind)); + + inErrorRecovery = true; + } + + var result = TypeScript.Syntax.separatedList(items); + + this.returnZeroOrOneLengthArray(items); + + return { skippedTokens: skippedTokens, list: result }; + }; + + ParserImpl.prototype.separatorKind = function (currentListType) { + switch (currentListType) { + case 2048 /* HeritageClause_TypeNameList */: + case 16384 /* ArgumentList_AssignmentExpressions */: + case 256 /* EnumDeclaration_EnumElements */: + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + case 131072 /* ParameterList_Parameters */: + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + case 262144 /* TypeArgumentList_Types */: + case 524288 /* TypeParameterList_TypeParameters */: + return 79 /* CommaToken */; + + case 512 /* ObjectType_TypeMembers */: + return 78 /* SemicolonToken */; + + case 1 /* SourceUnit_ModuleElements */: + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + case 2 /* ClassDeclaration_ClassElements */: + case 4 /* ModuleDeclaration_ModuleElements */: + case 8 /* SwitchStatement_SwitchClauses */: + case 16 /* SwitchClause_Statements */: + case 32 /* Block_Statements */: + default: + throw TypeScript.Errors.notYetImplemented(); + } + }; + + ParserImpl.prototype.reportUnexpectedTokenDiagnostic = function (listType) { + var token = this.currentToken(); + + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode.Unexpected_token_0_expected, [this.getExpectedListElementType(listType)]); + this.addDiagnostic(diagnostic); + }; + + ParserImpl.prototype.addDiagnostic = function (diagnostic) { + if (this.diagnostics.length > 0 && this.diagnostics[this.diagnostics.length - 1].start() === diagnostic.start()) { + return; + } + + this.diagnostics.push(diagnostic); + }; + + ParserImpl.prototype.isExpectedListTerminator = function (currentListType) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.isExpectedSourceUnit_ModuleElementsTerminator(); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.isExpectedClassDeclaration_ClassElementsTerminator(); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.isExpectedModuleDeclaration_ModuleElementsTerminator(); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.isExpectedSwitchStatement_SwitchClausesTerminator(); + + case 16 /* SwitchClause_Statements */: + return this.isExpectedSwitchClause_StatementsTerminator(); + + case 32 /* Block_Statements */: + return this.isExpectedBlock_StatementsTerminator(); + + case 64 /* TryBlock_Statements */: + return this.isExpectedTryBlock_StatementsTerminator(); + + case 128 /* CatchBlock_Statements */: + return this.isExpectedCatchBlock_StatementsTerminator(); + + case 256 /* EnumDeclaration_EnumElements */: + return this.isExpectedEnumDeclaration_EnumElementsTerminator(); + + case 512 /* ObjectType_TypeMembers */: + return this.isExpectedObjectType_TypeMembersTerminator(); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.isExpectedArgumentList_AssignmentExpressionsTerminator(); + + case 2048 /* HeritageClause_TypeNameList */: + return this.isExpectedHeritageClause_TypeNameListTerminator(); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return this.isExpectedVariableDeclaration_VariableDeclarators_AllowInTerminator(); + + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.isExpectedVariableDeclaration_VariableDeclarators_DisallowInTerminator(); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.isExpectedObjectLiteralExpression_PropertyAssignmentsTerminator(); + + case 131072 /* ParameterList_Parameters */: + return this.isExpectedParameterList_ParametersTerminator(); + + case 262144 /* TypeArgumentList_Types */: + return this.isExpectedTypeArgumentList_TypesTerminator(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.isExpectedTypeParameterList_TypeParametersTerminator(); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.isExpectedLiteralExpression_AssignmentExpressionsTerminator(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isExpectedSourceUnit_ModuleElementsTerminator = function () { + return this.currentToken().tokenKind === 10 /* EndOfFileToken */; + }; + + ParserImpl.prototype.isExpectedEnumDeclaration_EnumElementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedModuleDeclaration_ModuleElementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedObjectType_TypeMembersTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedObjectLiteralExpression_PropertyAssignmentsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedLiteralExpression_AssignmentExpressionsTerminator = function () { + return this.currentToken().tokenKind === 75 /* CloseBracketToken */; + }; + + ParserImpl.prototype.isExpectedTypeArgumentList_TypesTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 81 /* GreaterThanToken */) { + return true; + } + + if (this.canFollowTypeArgumentListInExpression(token.tokenKind)) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedTypeParameterList_TypeParametersTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 81 /* GreaterThanToken */) { + return true; + } + + if (token.tokenKind === 72 /* OpenParenToken */ || token.tokenKind === 70 /* OpenBraceToken */ || token.tokenKind === 48 /* ExtendsKeyword */ || token.tokenKind === 51 /* ImplementsKeyword */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedParameterList_ParametersTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 73 /* CloseParenToken */) { + return true; + } + + if (token.tokenKind === 70 /* OpenBraceToken */) { + return true; + } + + if (token.tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedVariableDeclaration_VariableDeclarators_DisallowInTerminator = function () { + if (this.currentToken().tokenKind === 78 /* SemicolonToken */ || this.currentToken().tokenKind === 73 /* CloseParenToken */) { + return true; + } + + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedVariableDeclaration_VariableDeclarators_AllowInTerminator = function () { + if (this.previousToken().tokenKind === 79 /* CommaToken */) { + return false; + } + + if (this.currentToken().tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + + return this.canEatExplicitOrAutomaticSemicolon(false); + }; + + ParserImpl.prototype.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 70 /* OpenBraceToken */ || token0.tokenKind === 71 /* CloseBraceToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedHeritageClause_TypeNameListTerminator = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 48 /* ExtendsKeyword */ || token0.tokenKind === 51 /* ImplementsKeyword */) { + return true; + } + + if (this.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator()) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedArgumentList_AssignmentExpressionsTerminator = function () { + var token0 = this.currentToken(); + return token0.tokenKind === 73 /* CloseParenToken */ || token0.tokenKind === 78 /* SemicolonToken */; + }; + + ParserImpl.prototype.isExpectedClassDeclaration_ClassElementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedSwitchStatement_SwitchClausesTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedSwitchClause_StatementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */ || this.isSwitchClause(); + }; + + ParserImpl.prototype.isExpectedBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedTryBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 17 /* CatchKeyword */ || this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.isExpectedCatchBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.isExpectedListItem = function (currentListType, inErrorRecovery) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.isModuleElement(inErrorRecovery); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.isHeritageClause(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.isClassElement(inErrorRecovery); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.isModuleElement(inErrorRecovery); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.isSwitchClause(); + + case 16 /* SwitchClause_Statements */: + return this.isStatement(inErrorRecovery); + + case 32 /* Block_Statements */: + return this.isStatement(inErrorRecovery); + + case 64 /* TryBlock_Statements */: + case 128 /* CatchBlock_Statements */: + return false; + + case 256 /* EnumDeclaration_EnumElements */: + return this.isEnumElement(inErrorRecovery); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.isVariableDeclarator(); + + case 512 /* ObjectType_TypeMembers */: + return this.isTypeMember(inErrorRecovery); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.isExpectedArgumentList_AssignmentExpression(); + + case 2048 /* HeritageClause_TypeNameList */: + return this.isHeritageClauseTypeName(); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.isPropertyAssignment(inErrorRecovery); + + case 131072 /* ParameterList_Parameters */: + return this.isParameter(); + + case 262144 /* TypeArgumentList_Types */: + return this.isType(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.isTypeParameter(); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.isAssignmentOrOmittedExpression(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isExpectedArgumentList_AssignmentExpression = function () { + var currentToken = this.currentToken(); + if (this.isExpression(currentToken)) { + return true; + } + + if (currentToken.tokenKind === 79 /* CommaToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.parseExpectedListItem = function (currentListType, inErrorRecovery) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.parseModuleElement(inErrorRecovery); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.parseHeritageClause(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.parseClassElement(inErrorRecovery); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.parseModuleElement(inErrorRecovery); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.parseSwitchClause(); + + case 16 /* SwitchClause_Statements */: + return this.parseStatement(inErrorRecovery); + + case 32 /* Block_Statements */: + return this.parseStatement(inErrorRecovery); + + case 256 /* EnumDeclaration_EnumElements */: + return this.parseEnumElement(); + + case 512 /* ObjectType_TypeMembers */: + return this.parseTypeMember(inErrorRecovery); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.parseAssignmentExpression(true); + + case 2048 /* HeritageClause_TypeNameList */: + return this.parseNameOrGenericType(); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return this.parseVariableDeclarator(true, false); + + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.parseVariableDeclarator(false, false); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.parsePropertyAssignment(inErrorRecovery); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.parseAssignmentOrOmittedExpression(); + + case 131072 /* ParameterList_Parameters */: + return this.parseParameter(); + + case 262144 /* TypeArgumentList_Types */: + return this.parseType(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.parseTypeParameter(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.getExpectedListElementType = function (currentListType) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.module_class_interface_enum_import_or_statement, null); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return '{'; + + case 2 /* ClassDeclaration_ClassElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.constructor_function_accessor_or_variable, null); + + case 4 /* ModuleDeclaration_ModuleElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.module_class_interface_enum_import_or_statement, null); + + case 8 /* SwitchStatement_SwitchClauses */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.case_or_default_clause, null); + + case 16 /* SwitchClause_Statements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.statement, null); + + case 32 /* Block_Statements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.statement, null); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null); + + case 256 /* EnumDeclaration_EnumElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null); + + case 512 /* ObjectType_TypeMembers */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.call_construct_index_property_or_function_signature, null); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + + case 2048 /* HeritageClause_TypeNameList */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_name, null); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.property_or_accessor, null); + + case 131072 /* ParameterList_Parameters */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.parameter, null); + + case 262144 /* TypeArgumentList_Types */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type, null); + + case 524288 /* TypeParameterList_TypeParameters */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_parameter, null); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + return ParserImpl; + })(); + + function parse(fileName, text, isDeclaration, options) { + var source = new NormalParserSource(fileName, text, options.languageVersion()); + + return new ParserImpl(fileName, text.lineMap(), source, options, text).parseSyntaxTree(isDeclaration); + } + Parser.parse = parse; + + function incrementalParse(oldSyntaxTree, textChangeRange, newText) { + if (textChangeRange.isUnchanged()) { + return oldSyntaxTree; + } + + var source = new IncrementalParserSource(oldSyntaxTree, textChangeRange, newText); + + return new ParserImpl(oldSyntaxTree.fileName(), newText.lineMap(), source, oldSyntaxTree.parseOptions(), newText).parseSyntaxTree(oldSyntaxTree.isDeclaration()); + } + Parser.incrementalParse = incrementalParse; + })(TypeScript.Parser || (TypeScript.Parser = {})); + var Parser = TypeScript.Parser; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTree = (function () { + function SyntaxTree(sourceUnit, isDeclaration, diagnostics, fileName, lineMap, parseOtions) { + this._allDiagnostics = null; + this._sourceUnit = sourceUnit; + this._isDeclaration = isDeclaration; + this._parserDiagnostics = diagnostics; + this._fileName = fileName; + this._lineMap = lineMap; + this._parseOptions = parseOtions; + } + SyntaxTree.prototype.toJSON = function (key) { + var result = {}; + + result.isDeclaration = this._isDeclaration; + result.languageVersion = TypeScript.LanguageVersion[this._parseOptions.languageVersion()]; + result.parseOptions = this._parseOptions; + + if (this.diagnostics().length > 0) { + result.diagnostics = this.diagnostics(); + } + + result.sourceUnit = this._sourceUnit; + result.lineMap = this._lineMap; + + return result; + }; + + SyntaxTree.prototype.sourceUnit = function () { + return this._sourceUnit; + }; + + SyntaxTree.prototype.isDeclaration = function () { + return this._isDeclaration; + }; + + SyntaxTree.prototype.computeDiagnostics = function () { + if (this._parserDiagnostics.length > 0) { + return this._parserDiagnostics; + } + + var diagnostics = []; + this.sourceUnit().accept(new GrammarCheckerWalker(this, diagnostics)); + + return diagnostics; + }; + + SyntaxTree.prototype.diagnostics = function () { + if (this._allDiagnostics === null) { + this._allDiagnostics = this.computeDiagnostics(); + } + + return this._allDiagnostics; + }; + + SyntaxTree.prototype.fileName = function () { + return this._fileName; + }; + + SyntaxTree.prototype.lineMap = function () { + return this._lineMap; + }; + + SyntaxTree.prototype.parseOptions = function () { + return this._parseOptions; + }; + + SyntaxTree.prototype.structuralEquals = function (tree) { + return TypeScript.ArrayUtilities.sequenceEquals(this.diagnostics(), tree.diagnostics(), TypeScript.Diagnostic.equals) && this.sourceUnit().structuralEquals(tree.sourceUnit()); + }; + return SyntaxTree; + })(); + TypeScript.SyntaxTree = SyntaxTree; + + var GrammarCheckerWalker = (function (_super) { + __extends(GrammarCheckerWalker, _super); + function GrammarCheckerWalker(syntaxTree, diagnostics) { + _super.call(this); + this.syntaxTree = syntaxTree; + this.diagnostics = diagnostics; + this.inAmbientDeclaration = false; + this.inBlock = false; + this.inObjectLiteralExpression = false; + this.currentConstructor = null; + } + GrammarCheckerWalker.prototype.childFullStart = function (parent, child) { + return this.position() + TypeScript.Syntax.childOffset(parent, child); + }; + + GrammarCheckerWalker.prototype.childStart = function (parent, child) { + return this.childFullStart(parent, child) + child.leadingTriviaWidth(); + }; + + GrammarCheckerWalker.prototype.pushDiagnostic = function (start, length, diagnosticKey, args) { + if (typeof args === "undefined") { args = null; } + this.diagnostics.push(new TypeScript.Diagnostic(this.syntaxTree.fileName(), this.syntaxTree.lineMap(), start, length, diagnosticKey, args)); + }; + + GrammarCheckerWalker.prototype.pushDiagnostic1 = function (elementFullStart, element, diagnosticKey, args) { + if (typeof args === "undefined") { args = null; } + this.diagnostics.push(new TypeScript.Diagnostic(this.syntaxTree.fileName(), this.syntaxTree.lineMap(), elementFullStart + element.leadingTriviaWidth(), element.width(), diagnosticKey, args)); + }; + + GrammarCheckerWalker.prototype.visitCatchClause = function (node) { + if (node.typeAnnotation) { + this.pushDiagnostic(this.childStart(node, node.typeAnnotation), node.typeAnnotation.width(), TypeScript.DiagnosticCode.Catch_clause_parameter_cannot_have_a_type_annotation); + } + + _super.prototype.visitCatchClause.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkParameterListOrder = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameters); + + var seenOptionalParameter = false; + var parameterCount = node.parameters.nonSeparatorCount(); + + for (var i = 0, n = node.parameters.childCount(); i < n; i++) { + var nodeOrToken = node.parameters.childAt(i); + if (i % 2 === 0) { + var parameterIndex = i / 2; + var parameter = node.parameters.childAt(i); + + if (parameter.dotDotDotToken) { + if (parameterIndex !== (parameterCount - 1)) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Rest_parameter_must_be_last_in_list); + return true; + } + + if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Rest_parameter_cannot_be_optional); + return true; + } + + if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Rest_parameter_cannot_have_an_initializer); + return true; + } + } else if (parameter.questionToken || parameter.equalsValueClause) { + seenOptionalParameter = true; + + if (parameter.questionToken && parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Parameter_cannot_have_question_mark_and_initializer); + return true; + } + } else { + if (seenOptionalParameter) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Required_parameter_cannot_follow_optional_parameter); + return true; + } + } + } + + parameterFullStart += nodeOrToken.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkParameterListAcessibilityModifiers = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameters); + + for (var i = 0, n = node.parameters.childCount(); i < n; i++) { + var nodeOrToken = node.parameters.childAt(i); + if (i % 2 === 0) { + var parameter = node.parameters.childAt(i); + + if (this.checkParameterAccessibilityModifiers(node, parameter, parameterFullStart)) { + return true; + } + } + + parameterFullStart += nodeOrToken.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkParameterAccessibilityModifiers = function (parameterList, parameter, parameterFullStart) { + if (parameter.modifiers.childCount() > 0) { + var modifiers = parameter.modifiers; + var modifierFullStart = parameterFullStart + TypeScript.Syntax.childOffset(parameter, modifiers); + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + + if (this.checkParameterAccessibilityModifier(parameterList, modifier, modifierFullStart, i)) { + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkParameterAccessibilityModifier = function (parameterList, modifier, modifierFullStart, modifierIndex) { + if (modifier.tokenKind !== 57 /* PublicKeyword */ && modifier.tokenKind !== 55 /* PrivateKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_parameter, [modifier.text()]); + return true; + } else { + if (modifierIndex > 0) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return true; + } + + if (!this.inAmbientDeclaration && this.currentConstructor && !this.currentConstructor.block && this.currentConstructor.callSignature.parameterList === parameterList) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_cannot_be_used_in_a_constructor_overload); + return true; + } else if (this.inAmbientDeclaration || this.currentConstructor === null || this.currentConstructor.callSignature.parameterList !== parameterList) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_can_only_be_used_in_a_non_ambient_constructor_declaration); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForTrailingSeparator = function (parent, list) { + if (list.childCount() === 0 || list.childCount() % 2 === 1) { + return false; + } + + var currentElementFullStart = this.childFullStart(parent, list); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var child = list.childAt(i); + if (i === n - 1) { + this.pushDiagnostic1(currentElementFullStart, child, TypeScript.DiagnosticCode.Trailing_separator_not_allowed); + } + + currentElementFullStart += child.fullWidth(); + } + + return true; + }; + + GrammarCheckerWalker.prototype.checkForAtLeastOneElement = function (parent, list, expected) { + if (list.childCount() > 0) { + return false; + } + + var listFullStart = this.childFullStart(parent, list); + var tokenAtStart = this.syntaxTree.sourceUnit().findToken(listFullStart); + + this.pushDiagnostic1(listFullStart, tokenAtStart.token(), TypeScript.DiagnosticCode.Unexpected_token_0_expected, [expected]); + + return true; + }; + + GrammarCheckerWalker.prototype.visitParameterList = function (node) { + if (this.checkParameterListAcessibilityModifiers(node) || this.checkParameterListOrder(node) || this.checkForTrailingSeparator(node, node.parameters)) { + this.skip(node); + return; + } + + _super.prototype.visitParameterList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitHeritageClause = function (node) { + if (this.checkForTrailingSeparator(node, node.typeNames) || this.checkForAtLeastOneElement(node, node.typeNames, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_name, null))) { + this.skip(node); + return; + } + + _super.prototype.visitHeritageClause.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitArgumentList = function (node) { + if (this.checkForTrailingSeparator(node, node.arguments)) { + this.skip(node); + return; + } + + _super.prototype.visitArgumentList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitVariableDeclaration = function (node) { + if (this.checkForTrailingSeparator(node, node.variableDeclarators) || this.checkForAtLeastOneElement(node, node.variableDeclarators, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null))) { + this.skip(node); + return; + } + + _super.prototype.visitVariableDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTypeArgumentList = function (node) { + if (this.checkForTrailingSeparator(node, node.typeArguments) || this.checkForAtLeastOneElement(node, node.typeArguments, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null))) { + this.skip(node); + return; + } + + _super.prototype.visitTypeArgumentList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTypeParameterList = function (node) { + if (this.checkForTrailingSeparator(node, node.typeParameters) || this.checkForAtLeastOneElement(node, node.typeParameters, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null))) { + this.skip(node); + return; + } + + _super.prototype.visitTypeParameterList.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkIndexSignatureParameter = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameter); + var parameter = node.parameter; + + if (parameter.dotDotDotToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signatures_cannot_have_rest_parameters); + return true; + } else if (parameter.modifiers.childCount() > 0) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_accessibility_modifiers); + return true; + } else if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_a_question_mark); + return true; + } else if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_an_initializer); + return true; + } else if (!parameter.typeAnnotation) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_must_have_a_type_annotation); + return true; + } else if (parameter.typeAnnotation.type.kind() !== 69 /* StringKeyword */ && parameter.typeAnnotation.type.kind() !== 67 /* NumberKeyword */) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_type_must_be_string_or_number); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitIndexSignature = function (node) { + if (this.checkIndexSignatureParameter(node)) { + this.skip(node); + return; + } + + if (!node.typeAnnotation) { + this.pushDiagnostic1(this.position(), node, TypeScript.DiagnosticCode.Index_signature_must_have_a_type_annotation); + this.skip(node); + return; + } + + _super.prototype.visitIndexSignature.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkClassDeclarationHeritageClauses = function (node) { + var heritageClauseFullStart = this.childFullStart(node, node.heritageClauses); + + var seenExtendsClause = false; + var seenImplementsClause = false; + + for (var i = 0, n = node.heritageClauses.childCount(); i < n; i++) { + TypeScript.Debug.assert(i <= 2); + var heritageClause = node.heritageClauses.childAt(i); + + if (heritageClause.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */) { + if (seenExtendsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.extends_clause_already_seen); + return true; + } + + if (seenImplementsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.extends_clause_must_precede_implements_clause); + return true; + } + + if (heritageClause.typeNames.nonSeparatorCount() > 1) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.Classes_can_only_extend_a_single_class); + return true; + } + + seenExtendsClause = true; + } else { + TypeScript.Debug.assert(heritageClause.extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + if (seenImplementsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.implements_clause_already_seen); + return true; + } + + seenImplementsClause = true; + } + + heritageClauseFullStart += heritageClause.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedDeclareModifier = function (modifiers) { + if (this.inAmbientDeclaration) { + var declareToken = TypeScript.SyntaxUtilities.getToken(modifiers, 63 /* DeclareKeyword */); + + if (declareToken) { + this.pushDiagnostic1(this.childFullStart(modifiers, declareToken), declareToken, TypeScript.DiagnosticCode.declare_modifier_not_allowed_for_code_already_in_an_ambient_context); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForRequiredDeclareModifier = function (moduleElement, typeKeyword, modifiers) { + if (!this.inAmbientDeclaration && this.syntaxTree.isDeclaration()) { + if (!TypeScript.SyntaxUtilities.containsToken(modifiers, 63 /* DeclareKeyword */)) { + this.pushDiagnostic1(this.childFullStart(moduleElement, typeKeyword), typeKeyword.firstToken(), TypeScript.DiagnosticCode.declare_modifier_required_for_top_level_element); + return true; + } + } + }; + + GrammarCheckerWalker.prototype.checkFunctionOverloads = function (node, moduleElements) { + if (!this.inAmbientDeclaration && !this.syntaxTree.isDeclaration()) { + var moduleElementFullStart = this.childFullStart(node, moduleElements); + + var inFunctionOverloadChain = false; + var functionOverloadChainName = null; + + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var moduleElement = moduleElements.childAt(i); + var lastElement = i === (n - 1); + + if (inFunctionOverloadChain) { + if (moduleElement.kind() !== 129 /* FunctionDeclaration */) { + this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + + var functionDeclaration = moduleElement; + if (functionDeclaration.identifier.valueText() !== functionOverloadChainName) { + var identifierFullStart = moduleElementFullStart + TypeScript.Syntax.childOffset(moduleElement, functionDeclaration.identifier); + this.pushDiagnostic1(identifierFullStart, functionDeclaration.identifier, TypeScript.DiagnosticCode.Function_overload_name_must_be_0, [functionOverloadChainName]); + return true; + } + } + + if (moduleElement.kind() === 129 /* FunctionDeclaration */) { + functionDeclaration = moduleElement; + if (!TypeScript.SyntaxUtilities.containsToken(functionDeclaration.modifiers, 63 /* DeclareKeyword */)) { + inFunctionOverloadChain = functionDeclaration.block === null; + functionOverloadChainName = functionDeclaration.identifier.valueText(); + + if (inFunctionOverloadChain) { + if (lastElement) { + this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } else { + var nextElement = moduleElements.childAt(i + 1); + if (nextElement.kind() === 129 /* FunctionDeclaration */) { + var nextFunction = nextElement; + + if (nextFunction.identifier.valueText() !== functionOverloadChainName && nextFunction.block === null) { + var identifierFullStart = moduleElementFullStart + TypeScript.Syntax.childOffset(moduleElement, functionDeclaration.identifier); + this.pushDiagnostic1(identifierFullStart, functionDeclaration.identifier, TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + } + } + } + } else { + inFunctionOverloadChain = false; + functionOverloadChainName = ""; + } + } + + moduleElementFullStart += moduleElement.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkClassOverloads = function (node) { + if (!this.inAmbientDeclaration && !TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */)) { + var classElementFullStart = this.childFullStart(node, node.classElements); + + var inFunctionOverloadChain = false; + var inConstructorOverloadChain = false; + + var functionOverloadChainName = null; + var isInStaticOverloadChain = null; + var memberFunctionDeclaration = null; + + for (var i = 0, n = node.classElements.childCount(); i < n; i++) { + var classElement = node.classElements.childAt(i); + var lastElement = i === (n - 1); + var isStaticOverload = null; + + if (inFunctionOverloadChain) { + if (classElement.kind() !== 135 /* MemberFunctionDeclaration */) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + + memberFunctionDeclaration = classElement; + if (memberFunctionDeclaration.propertyName.valueText() !== functionOverloadChainName) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, TypeScript.DiagnosticCode.Function_overload_name_must_be_0, [functionOverloadChainName]); + return true; + } + + isStaticOverload = TypeScript.SyntaxUtilities.containsToken(memberFunctionDeclaration.modifiers, 58 /* StaticKeyword */); + if (isStaticOverload !== isInStaticOverloadChain) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + var diagnostic = isInStaticOverloadChain ? TypeScript.DiagnosticCode.Function_overload_must_be_static : TypeScript.DiagnosticCode.Function_overload_must_not_be_static; + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, diagnostic, null); + return true; + } + } else if (inConstructorOverloadChain) { + if (classElement.kind() !== 137 /* ConstructorDeclaration */) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Constructor_implementation_expected); + return true; + } + } + + if (classElement.kind() === 135 /* MemberFunctionDeclaration */) { + memberFunctionDeclaration = classElement; + + inFunctionOverloadChain = memberFunctionDeclaration.block === null; + functionOverloadChainName = memberFunctionDeclaration.propertyName.valueText(); + isInStaticOverloadChain = TypeScript.SyntaxUtilities.containsToken(memberFunctionDeclaration.modifiers, 58 /* StaticKeyword */); + + if (inFunctionOverloadChain) { + if (lastElement) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } else { + var nextElement = node.classElements.childAt(i + 1); + if (nextElement.kind() === 135 /* MemberFunctionDeclaration */) { + var nextMemberFunction = nextElement; + + if (nextMemberFunction.propertyName.valueText() !== functionOverloadChainName && nextMemberFunction.block === null) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + } + } + } + } else if (classElement.kind() === 137 /* ConstructorDeclaration */) { + var constructorDeclaration = classElement; + + inConstructorOverloadChain = constructorDeclaration.block === null; + if (lastElement && inConstructorOverloadChain) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Constructor_implementation_expected); + return true; + } + } + + classElementFullStart += classElement.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForReservedName = function (parent, name, diagnosticKey) { + var nameFullStart = this.childFullStart(parent, name); + var token; + var tokenFullStart; + + var current = name; + while (current !== null) { + if (current.kind() === 121 /* QualifiedName */) { + var qualifiedName = current; + token = qualifiedName.right; + tokenFullStart = nameFullStart + this.childFullStart(qualifiedName, token); + current = qualifiedName.left; + } else { + TypeScript.Debug.assert(current.kind() === 11 /* IdentifierName */); + token = current; + tokenFullStart = nameFullStart; + current = null; + } + + switch (token.valueText()) { + case "any": + case "number": + case "boolean": + case "string": + case "void": + this.pushDiagnostic(tokenFullStart + token.leadingTriviaWidth(), token.width(), diagnosticKey, [token.valueText()]); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitClassDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, TypeScript.DiagnosticCode.Class_name_cannot_be_0) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.classKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkClassDeclarationHeritageClauses(node) || this.checkClassOverloads(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitClassDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkInterfaceDeclarationHeritageClauses = function (node) { + var heritageClauseFullStart = this.childFullStart(node, node.heritageClauses); + + var seenExtendsClause = false; + + for (var i = 0, n = node.heritageClauses.childCount(); i < n; i++) { + TypeScript.Debug.assert(i <= 1); + var heritageClause = node.heritageClauses.childAt(i); + + if (heritageClause.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */) { + if (seenExtendsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.extends_clause_already_seen); + return true; + } + + seenExtendsClause = true; + } else { + TypeScript.Debug.assert(heritageClause.extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.Interface_declaration_cannot_have_implements_clause); + return true; + } + + heritageClauseFullStart += heritageClause.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkInterfaceModifiers = function (modifiers) { + var modifierFullStart = this.position(); + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + if (modifier.tokenKind === 63 /* DeclareKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.declare_modifier_cannot_appear_on_an_interface_declaration); + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitInterfaceDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, TypeScript.DiagnosticCode.Interface_name_cannot_be_0) || this.checkInterfaceModifiers(node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkInterfaceDeclarationHeritageClauses(node)) { + this.skip(node); + return; + } + + _super.prototype.visitInterfaceDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkClassElementModifiers = function (list) { + var modifierFullStart = this.position(); + + var seenAccessibilityModifier = false; + var seenStaticModifier = false; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var modifier = list.childAt(i); + if (modifier.tokenKind === 57 /* PublicKeyword */ || modifier.tokenKind === 55 /* PrivateKeyword */) { + if (seenAccessibilityModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return true; + } + + if (seenStaticModifier) { + var previousToken = list.childAt(i - 1); + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_must_precede_1_modifier, [modifier.text(), previousToken.text()]); + return true; + } + + seenAccessibilityModifier = true; + } else if (modifier.tokenKind === 58 /* StaticKeyword */) { + if (seenStaticModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_already_seen, [modifier.text()]); + return true; + } + + seenStaticModifier = true; + } else { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_class_element, [modifier.text()]); + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitMemberVariableDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitMemberVariableDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitMemberFunctionDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitMemberFunctionDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkGetAccessorParameter = function (node, getKeyword, parameterList) { + var getKeywordFullStart = this.childFullStart(node, getKeyword); + if (parameterList.parameters.childCount() !== 0) { + this.pushDiagnostic1(getKeywordFullStart, getKeyword, TypeScript.DiagnosticCode.get_accessor_cannot_have_parameters); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitIndexMemberDeclaration = function (node) { + if (this.checkIndexMemberModifiers(node)) { + this.skip(node); + return; + } + + _super.prototype.visitIndexMemberDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkIndexMemberModifiers = function (node) { + if (node.modifiers.childCount() > 0) { + var modifierFullStart = this.childFullStart(node, node.modifiers); + this.pushDiagnostic1(modifierFullStart, node.modifiers.childAt(0), TypeScript.DiagnosticCode.Modifiers_cannot_appear_here); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkEcmaScriptVersionIsAtLeast = function (parent, node, languageVersion, diagnosticKey) { + if (this.syntaxTree.parseOptions().languageVersion() < languageVersion) { + var nodeFullStart = this.childFullStart(parent, node); + this.pushDiagnostic1(nodeFullStart, node, diagnosticKey); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitObjectLiteralExpression = function (node) { + var savedInObjectLiteralExpression = this.inObjectLiteralExpression; + this.inObjectLiteralExpression = true; + _super.prototype.visitObjectLiteralExpression.call(this, node); + this.inObjectLiteralExpression = savedInObjectLiteralExpression; + }; + + GrammarCheckerWalker.prototype.visitGetAccessor = function (node) { + if (this.checkForAccessorDeclarationInAmbientContext(node) || this.checkEcmaScriptVersionIsAtLeast(node, node.getKeyword, 1 /* EcmaScript5 */, TypeScript.DiagnosticCode.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkClassElementModifiers(node.modifiers) || this.checkGetAccessorParameter(node, node.getKeyword, node.parameterList)) { + this.skip(node); + return; + } + + _super.prototype.visitGetAccessor.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkForAccessorDeclarationInAmbientContext = function (accessor) { + if (this.inAmbientDeclaration) { + this.pushDiagnostic1(this.position(), accessor, TypeScript.DiagnosticCode.Accessors_are_not_allowed_in_ambient_contexts, null); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkSetAccessorParameter = function (node, setKeyword, parameterList) { + var setKeywordFullStart = this.childFullStart(node, setKeyword); + if (parameterList.parameters.childCount() !== 1) { + this.pushDiagnostic1(setKeywordFullStart, setKeyword, TypeScript.DiagnosticCode.set_accessor_must_have_one_and_only_one_parameter); + return true; + } + + var parameterListFullStart = this.childFullStart(node, parameterList); + var parameterFullStart = parameterListFullStart + TypeScript.Syntax.childOffset(parameterList, parameterList.openParenToken); + var parameter = parameterList.parameters.childAt(0); + + if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.set_accessor_parameter_cannot_be_optional); + return true; + } + + if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.set_accessor_parameter_cannot_have_an_initializer); + return true; + } + + if (parameter.dotDotDotToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.set_accessor_cannot_have_rest_parameter); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitSetAccessor = function (node) { + if (this.checkForAccessorDeclarationInAmbientContext(node) || this.checkEcmaScriptVersionIsAtLeast(node, node.setKeyword, 1 /* EcmaScript5 */, TypeScript.DiagnosticCode.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkClassElementModifiers(node.modifiers) || this.checkSetAccessorParameter(node, node.setKeyword, node.parameterList)) { + this.skip(node); + return; + } + + _super.prototype.visitSetAccessor.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitEnumDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, TypeScript.DiagnosticCode.Enum_name_cannot_be_0) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.enumKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers), this.checkEnumElements(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitEnumDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkEnumElements = function (node) { + var enumElementFullStart = this.childFullStart(node, node.enumElements); + + var previousValueWasComputed = false; + for (var i = 0, n = node.enumElements.childCount(); i < n; i++) { + var child = node.enumElements.childAt(i); + + if (i % 2 === 0) { + var enumElement = child; + + if (!enumElement.equalsValueClause && previousValueWasComputed) { + this.pushDiagnostic1(enumElementFullStart, enumElement, TypeScript.DiagnosticCode.Enum_member_must_have_initializer, null); + return true; + } + + if (enumElement.equalsValueClause) { + var value = enumElement.equalsValueClause.value; + previousValueWasComputed = !TypeScript.Syntax.isIntegerLiteral(value); + } + } + + enumElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitEnumElement = function (node) { + if (this.inAmbientDeclaration && node.equalsValueClause) { + var expression = node.equalsValueClause.value; + if (!TypeScript.Syntax.isIntegerLiteral(expression)) { + this.pushDiagnostic1(this.childFullStart(node, node.equalsValueClause), node.equalsValueClause.firstToken(), TypeScript.DiagnosticCode.Ambient_enum_elements_can_only_have_integer_literal_initializers); + this.skip(node); + return; + } + } + + _super.prototype.visitEnumElement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitInvocationExpression = function (node) { + if (node.expression.kind() === 50 /* SuperKeyword */ && node.argumentList.typeArgumentList !== null) { + this.pushDiagnostic1(this.position(), node, TypeScript.DiagnosticCode.super_invocation_cannot_have_type_arguments); + } + + _super.prototype.visitInvocationExpression.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkModuleElementModifiers = function (modifiers) { + var modifierFullStart = this.position(); + var seenExportModifier = false; + var seenDeclareModifier = false; + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + if (modifier.tokenKind === 57 /* PublicKeyword */ || modifier.tokenKind === 55 /* PrivateKeyword */ || modifier.tokenKind === 58 /* StaticKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_module_element, [modifier.text()]); + return true; + } + + if (modifier.tokenKind === 63 /* DeclareKeyword */) { + if (seenDeclareModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return; + } + + seenDeclareModifier = true; + } else if (modifier.tokenKind === 47 /* ExportKeyword */) { + if (seenExportModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_already_seen, [modifier.text()]); + return; + } + + if (seenDeclareModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_must_precede_1_modifier, [TypeScript.SyntaxFacts.getText(47 /* ExportKeyword */), TypeScript.SyntaxFacts.getText(63 /* DeclareKeyword */)]); + return; + } + + seenExportModifier = true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedImportDeclaration = function (node) { + var currentElementFullStart = this.childFullStart(node, node.moduleElements); + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var child = node.moduleElements.childAt(i); + if (child.kind() === 133 /* ImportDeclaration */) { + var importDeclaration = child; + if (importDeclaration.moduleReference.kind() === 245 /* ExternalModuleReference */) { + if (node.stringLiteral === null) { + this.pushDiagnostic1(currentElementFullStart, importDeclaration, TypeScript.DiagnosticCode.Import_declarations_in_an_internal_module_cannot_reference_an_external_module, null); + } + } + } + + currentElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedDeclareModifierOnImportDeclaration = function (modifiers) { + var declareToken = TypeScript.SyntaxUtilities.getToken(modifiers, 63 /* DeclareKeyword */); + + if (declareToken) { + this.pushDiagnostic1(this.childFullStart(modifiers, declareToken), declareToken, TypeScript.DiagnosticCode.declare_modifier_not_allowed_on_import_declaration); + return true; + } + }; + + GrammarCheckerWalker.prototype.visitImportDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifierOnImportDeclaration(node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitImportDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitModuleDeclaration = function (node) { + if (this.checkForReservedName(node, node.name, TypeScript.DiagnosticCode.Module_name_cannot_be_0) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.moduleKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkForDisallowedImportDeclaration(node) || this.checkForDisallowedExports(node, node.moduleElements) || this.checkForMultipleExportAssignments(node, node.moduleElements)) { + this.skip(node); + return; + } + + if (!TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */) && this.checkFunctionOverloads(node, node.moduleElements)) { + this.skip(node); + return; + } + + if (node.stringLiteral) { + if (!this.inAmbientDeclaration && !TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */)) { + var stringLiteralFullStart = this.childFullStart(node, node.stringLiteral); + this.pushDiagnostic1(stringLiteralFullStart, node.stringLiteral, TypeScript.DiagnosticCode.Only_ambient_modules_can_use_quoted_names); + this.skip(node); + return; + } + } + + if (!node.stringLiteral && this.checkForDisallowedExportAssignment(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitModuleDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedExports = function (node, moduleElements) { + var seenExportedElement = false; + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + + if (TypeScript.SyntaxUtilities.hasExportKeyword(child)) { + seenExportedElement = true; + break; + } + } + + var moduleElementFullStart = this.childFullStart(node, moduleElements); + if (seenExportedElement) { + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + + if (child.kind() === 134 /* ExportAssignment */) { + this.pushDiagnostic1(moduleElementFullStart, child, TypeScript.DiagnosticCode.Export_assignment_not_allowed_in_module_with_exported_element); + return true; + } + + moduleElementFullStart += child.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForMultipleExportAssignments = function (node, moduleElements) { + var moduleElementFullStart = this.childFullStart(node, moduleElements); + var seenExportAssignment = false; + var errorFound = false; + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + if (child.kind() === 134 /* ExportAssignment */) { + if (seenExportAssignment) { + this.pushDiagnostic1(moduleElementFullStart, child, TypeScript.DiagnosticCode.Module_cannot_have_multiple_export_assignments); + errorFound = true; + } + seenExportAssignment = true; + } + + moduleElementFullStart += child.fullWidth(); + } + + return errorFound; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedExportAssignment = function (node) { + var moduleElementFullStart = this.childFullStart(node, node.moduleElements); + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var child = node.moduleElements.childAt(i); + + if (child.kind() === 134 /* ExportAssignment */) { + this.pushDiagnostic1(moduleElementFullStart, child, TypeScript.DiagnosticCode.Export_assignment_cannot_be_used_in_internal_modules); + + return true; + } + + moduleElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitBlock = function (node) { + if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) { + this.pushDiagnostic1(this.position(), node.firstToken(), TypeScript.DiagnosticCode.Implementations_are_not_allowed_in_ambient_contexts); + this.skip(node); + return; + } + + if (this.checkFunctionOverloads(node, node.statements)) { + this.skip(node); + return; + } + + var savedInBlock = this.inBlock; + this.inBlock = true; + _super.prototype.visitBlock.call(this, node); + this.inBlock = savedInBlock; + }; + + GrammarCheckerWalker.prototype.checkForStatementInAmbientContxt = function (node) { + if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) { + this.pushDiagnostic1(this.position(), node.firstToken(), TypeScript.DiagnosticCode.Statements_are_not_allowed_in_ambient_contexts); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitBreakStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitBreakStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitContinueStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitContinueStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitDebuggerStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitDebuggerStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitDoStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitDoStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitEmptyStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitEmptyStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitExpressionStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitExpressionStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitForInStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node) || this.checkForInStatementVariableDeclaration(node)) { + this.skip(node); + return; + } + + _super.prototype.visitForInStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkForInStatementVariableDeclaration = function (node) { + if (node.variableDeclaration && node.variableDeclaration.variableDeclarators.nonSeparatorCount() > 1) { + var variableDeclarationFullStart = this.childFullStart(node, node.variableDeclaration); + + this.pushDiagnostic1(variableDeclarationFullStart, node.variableDeclaration, TypeScript.DiagnosticCode.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitForStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitForStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitIfStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitIfStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitLabeledStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitLabeledStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitReturnStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitReturnStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitSwitchStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitSwitchStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitThrowStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitThrowStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTryStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitTryStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitWhileStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitWhileStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitWithStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitWithStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkForDisallowedModifiers = function (parent, modifiers) { + if (this.inBlock || this.inObjectLiteralExpression) { + if (modifiers.childCount() > 0) { + var modifierFullStart = this.childFullStart(parent, modifiers); + this.pushDiagnostic1(modifierFullStart, modifiers.childAt(0), TypeScript.DiagnosticCode.Modifiers_cannot_appear_here); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitFunctionDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkForRequiredDeclareModifier(node, node.functionKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitFunctionDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitVariableStatement = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkForRequiredDeclareModifier(node, node.variableDeclaration, node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitVariableStatement.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkListSeparators = function (parent, list, kind) { + var currentElementFullStart = this.childFullStart(parent, list); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var child = list.childAt(i); + if (i % 2 === 1 && child.kind() !== kind) { + this.pushDiagnostic1(currentElementFullStart, child, TypeScript.DiagnosticCode._0_expected, [TypeScript.SyntaxFacts.getText(kind)]); + } + + currentElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitObjectType = function (node) { + if (this.checkListSeparators(node, node.typeMembers, 78 /* SemicolonToken */)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitObjectType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitArrayType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitArrayType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitFunctionType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitFunctionType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitConstructorType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitConstructorType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitVariableDeclarator = function (node) { + if (this.inAmbientDeclaration && node.equalsValueClause) { + this.pushDiagnostic1(this.childFullStart(node, node.equalsValueClause), node.equalsValueClause.firstToken(), TypeScript.DiagnosticCode.Initializers_are_not_allowed_in_ambient_contexts); + this.skip(node); + return; + } + + _super.prototype.visitVariableDeclarator.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitConstructorDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers) || this.checkConstructorModifiers(node.modifiers) || this.checkConstructorTypeParameterList(node) || this.checkConstructorTypeAnnotation(node)) { + this.skip(node); + return; + } + + var savedCurrentConstructor = this.currentConstructor; + this.currentConstructor = node; + _super.prototype.visitConstructorDeclaration.call(this, node); + this.currentConstructor = savedCurrentConstructor; + }; + + GrammarCheckerWalker.prototype.checkConstructorModifiers = function (modifiers) { + var currentElementFullStart = this.position(); + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var child = modifiers.childAt(i); + if (child.kind() !== 57 /* PublicKeyword */) { + this.pushDiagnostic1(currentElementFullStart, child, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_constructor_declaration, [TypeScript.SyntaxFacts.getText(child.kind())]); + return true; + } + + currentElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkConstructorTypeParameterList = function (node) { + var currentElementFullStart = this.position(); + + if (node.callSignature.typeParameterList) { + var callSignatureFullStart = this.childFullStart(node, node.callSignature); + var typeParameterListFullStart = callSignatureFullStart + TypeScript.Syntax.childOffset(node.callSignature, node.callSignature.typeAnnotation); + this.pushDiagnostic1(callSignatureFullStart, node.callSignature.typeParameterList, TypeScript.DiagnosticCode.Type_parameters_cannot_appear_on_a_constructor_declaration); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkConstructorTypeAnnotation = function (node) { + var currentElementFullStart = this.position(); + + if (node.callSignature.typeAnnotation) { + var callSignatureFullStart = this.childFullStart(node, node.callSignature); + var typeAnnotationFullStart = callSignatureFullStart + TypeScript.Syntax.childOffset(node.callSignature, node.callSignature.typeAnnotation); + this.pushDiagnostic1(typeAnnotationFullStart, node.callSignature.typeAnnotation, TypeScript.DiagnosticCode.Type_annotation_cannot_appear_on_a_constructor_declaration); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitSourceUnit = function (node) { + if (this.checkFunctionOverloads(node, node.moduleElements) || this.checkForDisallowedExports(node, node.moduleElements) || this.checkForMultipleExportAssignments(node, node.moduleElements)) { + this.skip(node); + return; + } + + _super.prototype.visitSourceUnit.call(this, node); + }; + return GrammarCheckerWalker; + })(TypeScript.PositionTrackingWalker); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Unicode = (function () { + function Unicode() { + } + Unicode.lookupInUnicodeMap = function (code, map) { + if (code < map[0]) { + return false; + } + + 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; + }; + + Unicode.isIdentifierStart = function (code, languageVersion) { + if (languageVersion === 0 /* EcmaScript3 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES3IdentifierStart); + } else if (languageVersion === 1 /* EcmaScript5 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES5IdentifierStart); + } else { + throw TypeScript.Errors.argumentOutOfRange("languageVersion"); + } + }; + + Unicode.isIdentifierPart = function (code, languageVersion) { + if (languageVersion === 0 /* EcmaScript3 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES3IdentifierPart); + } else if (languageVersion === 1 /* EcmaScript5 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES5IdentifierPart); + } else { + throw TypeScript.Errors.argumentOutOfRange("languageVersion"); + } + }; + Unicode.unicodeES3IdentifierStart = [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]; + Unicode.unicodeES3IdentifierPart = [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, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 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, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 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, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 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, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + + Unicode.unicodeES5IdentifierStart = [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]; + Unicode.unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 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, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 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, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 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, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 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, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + return Unicode; + })(); + TypeScript.Unicode = Unicode; +})(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; + + function timeFunction(logger, funcDescription, func) { + var start = (new Date()).getTime(); + var result = func(); + var end = (new Date()).getTime(); + if (logger.information()) { + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + } + return result; + } + TypeScript.timeFunction = timeFunction; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Document = (function () { + function Document(_compiler, _semanticInfoChain, fileName, referencedFiles, _scriptSnapshot, byteOrderMark, version, isOpen, _syntaxTree, _topLevelDecl) { + this._compiler = _compiler; + this._semanticInfoChain = _semanticInfoChain; + this.fileName = fileName; + this.referencedFiles = referencedFiles; + this._scriptSnapshot = _scriptSnapshot; + this.byteOrderMark = byteOrderMark; + this.version = version; + this.isOpen = isOpen; + this._syntaxTree = _syntaxTree; + this._topLevelDecl = _topLevelDecl; + this._diagnostics = null; + this._bloomFilter = null; + this._sourceUnit = null; + this._lineMap = null; + this._declASTMap = []; + this._astDeclMap = []; + this._amdDependencies = undefined; + this._externalModuleIndicatorSpan = undefined; + } + Document.prototype.invalidate = function () { + this._declASTMap.length = 0; + this._astDeclMap.length = 0; + this._topLevelDecl = null; + + this._syntaxTree = null; + this._sourceUnit = null; + this._diagnostics = null; + this._bloomFilter = null; + }; + + Document.prototype.isDeclareFile = function () { + return TypeScript.isDTSFile(this.fileName); + }; + + Document.prototype.cacheSyntaxTreeInfo = function (syntaxTree) { + var start = new Date().getTime(); + this._diagnostics = syntaxTree.diagnostics(); + TypeScript.syntaxDiagnosticsTime += new Date().getTime() - start; + + this._lineMap = syntaxTree.lineMap(); + + var sourceUnit = syntaxTree.sourceUnit(); + var leadingTrivia = sourceUnit.leadingTrivia(); + + this._externalModuleIndicatorSpan = this.getImplicitImportSpan(leadingTrivia) || this.getTopLevelImportOrExportSpan(sourceUnit); + + var amdDependencies = []; + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.isComment()) { + var amdDependency = this.getAmdDependency(trivia.fullText()); + if (amdDependency) { + amdDependencies.push(amdDependency); + } + } + } + + this._amdDependencies = amdDependencies; + }; + + Document.prototype.getAmdDependency = function (comment) { + var amdDependencyRegEx = /^\/\/\/\s*/gim; + var match = implicitImportRegEx.exec(trivia.fullText()); + + if (match) { + return new TypeScript.TextSpan(position, trivia.fullWidth()); + } + + return null; + }; + + Document.prototype.getTopLevelImportOrExportSpan = function (node) { + var firstToken; + var position = 0; + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var moduleElement = node.moduleElements.childAt(i); + + firstToken = moduleElement.firstToken(); + if (firstToken !== null && firstToken.tokenKind === 47 /* ExportKeyword */) { + return new TypeScript.TextSpan(position + firstToken.leadingTriviaWidth(), firstToken.width()); + } + + if (moduleElement.kind() === 133 /* ImportDeclaration */) { + var importDecl = moduleElement; + if (importDecl.moduleReference.kind() === 245 /* ExternalModuleReference */) { + return new TypeScript.TextSpan(position + importDecl.leadingTriviaWidth(), importDecl.width()); + } + } + + position += moduleElement.fullWidth(); + } + + return null; + ; + }; + + Document.prototype.sourceUnit = function () { + if (!this._sourceUnit) { + var start = new Date().getTime(); + var syntaxTree = this.syntaxTree(); + this._sourceUnit = TypeScript.SyntaxTreeToAstVisitor.visit(syntaxTree, this.fileName, this._compiler.compilationSettings(), this.isOpen); + TypeScript.astTranslationTime += new Date().getTime() - start; + + if (!this.isOpen) { + this._syntaxTree = null; + } + } + + return this._sourceUnit; + }; + + Document.prototype.diagnostics = function () { + if (this._diagnostics === null) { + this.syntaxTree(); + TypeScript.Debug.assert(this._diagnostics); + } + + return this._diagnostics; + }; + + Document.prototype.lineMap = function () { + if (this._lineMap === null) { + this.syntaxTree(); + TypeScript.Debug.assert(this._lineMap); + } + + return this._lineMap; + }; + + Document.prototype.isExternalModule = function () { + return this.externalModuleIndicatorSpan() !== null; + }; + + Document.prototype.externalModuleIndicatorSpan = function () { + if (this._externalModuleIndicatorSpan === undefined) { + this.syntaxTree(); + TypeScript.Debug.assert(this._externalModuleIndicatorSpan !== undefined); + } + + return this._externalModuleIndicatorSpan; + }; + + Document.prototype.amdDependencies = function () { + if (this._amdDependencies === undefined) { + this.syntaxTree(); + TypeScript.Debug.assert(this._amdDependencies !== undefined); + } + + return this._amdDependencies; + }; + + Document.prototype.syntaxTree = function () { + var result = this._syntaxTree; + if (!result) { + var start = new Date().getTime(); + + result = TypeScript.Parser.parse(this.fileName, TypeScript.SimpleText.fromScriptSnapshot(this._scriptSnapshot), TypeScript.isDTSFile(this.fileName), TypeScript.getParseOptions(this._compiler.compilationSettings())); + + TypeScript.syntaxTreeParseTime += new Date().getTime() - start; + + if (this.isOpen || !this._sourceUnit) { + this._syntaxTree = result; + } + } + + this.cacheSyntaxTreeInfo(result); + return result; + }; + + Document.prototype.bloomFilter = function () { + if (!this._bloomFilter) { + var identifiers = TypeScript.createIntrinsicsObject(); + var pre = function (cur) { + if (TypeScript.ASTHelpers.isValidAstNode(cur)) { + if (cur.kind() === 11 /* IdentifierName */) { + var nodeText = cur.valueText(); + + identifiers[nodeText] = true; + } + } + }; + + TypeScript.getAstWalkerFactory().simpleWalk(this.sourceUnit(), pre, null, identifiers); + + var identifierCount = 0; + for (var name in identifiers) { + if (identifiers[name]) { + identifierCount++; + } + } + + this._bloomFilter = new TypeScript.BloomFilter(identifierCount); + this._bloomFilter.addKeys(identifiers); + } + return this._bloomFilter; + }; + + Document.prototype.emitToOwnOutputFile = function () { + return !this._compiler.compilationSettings().outFileOption() || this.isExternalModule(); + }; + + Document.prototype.update = function (scriptSnapshot, version, isOpen, textChangeRange) { + var oldSyntaxTree = this._syntaxTree; + + if (textChangeRange !== null && TypeScript.Debug.shouldAssert(1 /* Normal */)) { + var oldText = this._scriptSnapshot; + var newText = scriptSnapshot; + + TypeScript.Debug.assert((oldText.getLength() - textChangeRange.span().length() + textChangeRange.newLength()) === newText.getLength()); + + if (TypeScript.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldTextPrefix = oldText.getText(0, textChangeRange.span().start()); + var newTextPrefix = newText.getText(0, textChangeRange.span().start()); + TypeScript.Debug.assert(oldTextPrefix === newTextPrefix); + + var oldTextSuffix = oldText.getText(textChangeRange.span().end(), oldText.getLength()); + var newTextSuffix = newText.getText(textChangeRange.newSpan().end(), newText.getLength()); + TypeScript.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + + var text = TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot); + + var newSyntaxTree = textChangeRange === null || oldSyntaxTree === null ? TypeScript.Parser.parse(this.fileName, text, TypeScript.isDTSFile(this.fileName), TypeScript.getParseOptions(this._compiler.compilationSettings())) : TypeScript.Parser.incrementalParse(oldSyntaxTree, textChangeRange, text); + + return new Document(this._compiler, this._semanticInfoChain, this.fileName, this.referencedFiles, scriptSnapshot, this.byteOrderMark, version, isOpen, newSyntaxTree, null); + }; + + Document.create = function (compiler, semanticInfoChain, fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles) { + return new Document(compiler, semanticInfoChain, fileName, referencedFiles, scriptSnapshot, byteOrderMark, version, isOpen, null, null); + }; + + Document.prototype.topLevelDecl = function () { + if (this._topLevelDecl === null) { + this._topLevelDecl = TypeScript.DeclarationCreator.create(this, this._semanticInfoChain, this._compiler.compilationSettings()); + } + + return this._topLevelDecl; + }; + + Document.prototype._getDeclForAST = function (ast) { + this.topLevelDecl(); + return this._astDeclMap[ast.syntaxID()]; + }; + + Document.prototype.getEnclosingDecl = function (ast) { + if (ast.kind() === 120 /* SourceUnit */) { + return this._getDeclForAST(ast); + } + + ast = ast.parent; + var decl = null; + while (ast) { + decl = this._getDeclForAST(ast); + + if (decl) { + break; + } + + ast = ast.parent; + } + + return decl._getEnclosingDeclFromParentDecl(); + }; + + Document.prototype._setDeclForAST = function (ast, decl) { + TypeScript.Debug.assert(decl.fileName() === this.fileName); + this._astDeclMap[ast.syntaxID()] = decl; + }; + + Document.prototype._getASTForDecl = function (decl) { + return this._declASTMap[decl.declID]; + }; + + Document.prototype._setASTForDecl = function (decl, ast) { + TypeScript.Debug.assert(decl.fileName() === this.fileName); + this._declASTMap[decl.declID] = ast; + }; + return Document; + })(); + TypeScript.Document = Document; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function hasFlag(val, flag) { + return (val & flag) !== 0; + } + TypeScript.hasFlag = hasFlag; + + (function (TypeRelationshipFlags) { + TypeRelationshipFlags[TypeRelationshipFlags["SuccessfulComparison"] = 0] = "SuccessfulComparison"; + TypeRelationshipFlags[TypeRelationshipFlags["RequiredPropertyIsMissing"] = 1 << 1] = "RequiredPropertyIsMissing"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleSignatures"] = 1 << 2] = "IncompatibleSignatures"; + TypeRelationshipFlags[TypeRelationshipFlags["SourceSignatureHasTooManyParameters"] = 3] = "SourceSignatureHasTooManyParameters"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleReturnTypes"] = 1 << 4] = "IncompatibleReturnTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatiblePropertyTypes"] = 1 << 5] = "IncompatiblePropertyTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleParameterTypes"] = 1 << 6] = "IncompatibleParameterTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["InconsistantPropertyAccesibility"] = 1 << 7] = "InconsistantPropertyAccesibility"; + })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); + var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; + + (function (ModuleGenTarget) { + ModuleGenTarget[ModuleGenTarget["Unspecified"] = 0] = "Unspecified"; + ModuleGenTarget[ModuleGenTarget["Synchronous"] = 1] = "Synchronous"; + ModuleGenTarget[ModuleGenTarget["Asynchronous"] = 2] = "Asynchronous"; + })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); + var ModuleGenTarget = TypeScript.ModuleGenTarget; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var proto = "__proto__"; + + 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; + + this[proto] = null; + this[proto] = undefined; + } + return BlockIntrinsics; + })(); + + function createIntrinsicsObject() { + return new BlockIntrinsics(); + } + TypeScript.createIntrinsicsObject = createIntrinsicsObject; + + var StringHashTable = (function () { + function StringHashTable() { + this.itemCount = 0; + this.table = createIntrinsicsObject(); + } + StringHashTable.prototype.getAllKeys = function () { + var result = []; + + for (var k in this.table) { + if (this.table[k] !== undefined) { + result.push(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]; + return data === undefined ? null : data; + }; + + StringHashTable.prototype.remove = function (key) { + if (this.table[key] !== undefined) { + this.table[key] = undefined; + this.itemCount--; + } + }; + return StringHashTable; + })(); + TypeScript.StringHashTable = StringHashTable; + + var IdentiferNameHashTable = (function (_super) { + __extends(IdentiferNameHashTable, _super); + function IdentiferNameHashTable() { + _super.apply(this, arguments); + } + IdentiferNameHashTable.prototype.getAllKeys = function () { + var result = []; + + _super.prototype.map.call(this, function (k, v, c) { + if (v !== undefined) { + result.push(k.substring(1)); + } + }, null); + + return result; + }; + + IdentiferNameHashTable.prototype.add = function (key, data) { + return _super.prototype.add.call(this, "#" + key, data); + }; + + IdentiferNameHashTable.prototype.addOrUpdate = function (key, data) { + return _super.prototype.addOrUpdate.call(this, "#" + key, data); + }; + + IdentiferNameHashTable.prototype.map = function (fn, context) { + return _super.prototype.map.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.every = function (fn, context) { + return _super.prototype.every.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.some = function (fn, context) { + return _super.prototype.some.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.lookup = function (key) { + return _super.prototype.lookup.call(this, "#" + key); + }; + return IdentiferNameHashTable; + })(StringHashTable); + TypeScript.IdentiferNameHashTable = IdentiferNameHashTable; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (ASTHelpers) { + function scriptIsElided(sourceUnit) { + return TypeScript.isDTSFile(sourceUnit.fileName()) || moduleMembersAreElided(sourceUnit.moduleElements); + } + ASTHelpers.scriptIsElided = scriptIsElided; + + function moduleIsElided(declaration) { + return TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) || moduleMembersAreElided(declaration.moduleElements); + } + ASTHelpers.moduleIsElided = moduleIsElided; + + function moduleMembersAreElided(members) { + for (var i = 0, n = members.childCount(); i < n; i++) { + var member = members.childAt(i); + + if (member.kind() === 130 /* ModuleDeclaration */) { + if (!moduleIsElided(member)) { + return false; + } + } else if (member.kind() !== 128 /* InterfaceDeclaration */) { + return false; + } + } + + return true; + } + + function enumIsElided(declaration) { + if (TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */)) { + return true; + } + + return false; + } + ASTHelpers.enumIsElided = enumIsElided; + + function isValidAstNode(ast) { + if (!ast) + return false; + + if (ast.start() === -1 || ast.end() === -1) + return false; + + return true; + } + ASTHelpers.isValidAstNode = isValidAstNode; + + function getAstAtPosition(script, pos, useTrailingTriviaAsLimChar, forceInclusive) { + if (typeof useTrailingTriviaAsLimChar === "undefined") { useTrailingTriviaAsLimChar = true; } + if (typeof forceInclusive === "undefined") { forceInclusive = false; } + var top = null; + + var pre = function (cur, walker) { + if (isValidAstNode(cur)) { + var isInvalid1 = cur.kind() === 149 /* ExpressionStatement */ && cur.width() === 0; + + if (isInvalid1) { + walker.options.goChildren = false; + } else { + var inclusive = forceInclusive || cur.kind() === 11 /* IdentifierName */ || cur.kind() === 212 /* MemberAccessExpression */ || cur.kind() === 121 /* QualifiedName */ || cur.kind() === 224 /* VariableDeclaration */ || cur.kind() === 225 /* VariableDeclarator */ || cur.kind() === 213 /* InvocationExpression */ || pos === script.end() + script.trailingTriviaWidth(); + + var minChar = cur.start(); + var limChar = cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0) + (inclusive ? 1 : 0); + if (pos >= minChar && pos < limChar) { + if ((cur.kind() !== 1 /* List */ && cur.kind() !== 2 /* SeparatedList */) || cur.end() > cur.start()) { + if (top === null) { + top = cur; + } else if (cur.start() >= top.start() && (cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0)) <= (top.end() + (useTrailingTriviaAsLimChar ? top.trailingTriviaWidth() : 0))) { + if (top.width() !== 0 || cur.width() !== 0) { + top = cur; + } + } + } + } + + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + }; + + TypeScript.getAstWalkerFactory().walk(script, pre); + return top; + } + ASTHelpers.getAstAtPosition = getAstAtPosition; + + function getExtendsHeritageClause(clauses) { + if (!clauses) { + return null; + } + + return clauses.firstOrDefault(function (c) { + return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 230 /* ExtendsHeritageClause */; + }); + } + ASTHelpers.getExtendsHeritageClause = getExtendsHeritageClause; + + function getImplementsHeritageClause(clauses) { + if (!clauses) { + return null; + } + + return clauses.firstOrDefault(function (c) { + return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 231 /* ImplementsHeritageClause */; + }); + } + ASTHelpers.getImplementsHeritageClause = getImplementsHeritageClause; + + function isCallExpression(ast) { + return (ast && ast.kind() === 213 /* InvocationExpression */) || (ast && ast.kind() === 216 /* ObjectCreationExpression */); + } + ASTHelpers.isCallExpression = isCallExpression; + + function isCallExpressionTarget(ast) { + if (!ast) { + return false; + } + + var current = ast; + + while (current && current.parent) { + if (current.parent.kind() === 212 /* MemberAccessExpression */ && current.parent.name === current) { + current = current.parent; + continue; + } + + break; + } + + if (current && current.parent) { + if (current.parent.kind() === 213 /* InvocationExpression */ || current.parent.kind() === 216 /* ObjectCreationExpression */) { + return current === current.parent.expression; + } + } + + return false; + } + ASTHelpers.isCallExpressionTarget = isCallExpressionTarget; + + function isNameOfSomeDeclaration(ast) { + if (ast === null || ast.parent === null) { + return false; + } + if (ast.kind() !== 11 /* IdentifierName */) { + return false; + } + + switch (ast.parent.kind()) { + case 131 /* ClassDeclaration */: + return ast.parent.identifier === ast; + case 128 /* InterfaceDeclaration */: + return ast.parent.identifier === ast; + case 132 /* EnumDeclaration */: + return ast.parent.identifier === ast; + case 130 /* ModuleDeclaration */: + return ast.parent.name === ast || ast.parent.stringLiteral === ast; + case 225 /* VariableDeclarator */: + return ast.parent.propertyName === ast; + case 129 /* FunctionDeclaration */: + return ast.parent.identifier === ast; + case 135 /* MemberFunctionDeclaration */: + return ast.parent.propertyName === ast; + case 242 /* Parameter */: + return ast.parent.identifier === ast; + case 238 /* TypeParameter */: + return ast.parent.identifier === ast; + case 240 /* SimplePropertyAssignment */: + return ast.parent.propertyName === ast; + case 241 /* FunctionPropertyAssignment */: + return ast.parent.propertyName === ast; + case 243 /* EnumElement */: + return ast.parent.propertyName === ast; + case 133 /* ImportDeclaration */: + return ast.parent.identifier === ast; + } + + return false; + } + + function isDeclarationASTOrDeclarationNameAST(ast) { + return isNameOfSomeDeclaration(ast) || isDeclarationAST(ast); + } + ASTHelpers.isDeclarationASTOrDeclarationNameAST = isDeclarationASTOrDeclarationNameAST; + + function getEnclosingParameterForInitializer(ast) { + var current = ast; + while (current) { + switch (current.kind()) { + case 232 /* EqualsValueClause */: + if (current.parent && current.parent.kind() === 242 /* Parameter */) { + return current.parent; + } + break; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + return null; + } + + current = current.parent; + } + return null; + } + ASTHelpers.getEnclosingParameterForInitializer = getEnclosingParameterForInitializer; + + function getEnclosingMemberVariableDeclaration(ast) { + var current = ast; + + while (current) { + switch (current.kind()) { + case 136 /* MemberVariableDeclaration */: + return current; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + return null; + } + current = current.parent; + } + + return null; + } + ASTHelpers.getEnclosingMemberVariableDeclaration = getEnclosingMemberVariableDeclaration; + + function isNameOfFunction(ast) { + return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 129 /* FunctionDeclaration */ && ast.parent.identifier === ast; + } + ASTHelpers.isNameOfFunction = isNameOfFunction; + + function isNameOfMemberFunction(ast) { + return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 135 /* MemberFunctionDeclaration */ && ast.parent.propertyName === ast; + } + ASTHelpers.isNameOfMemberFunction = isNameOfMemberFunction; + + function isNameOfMemberAccessExpression(ast) { + if (ast && ast.parent && ast.parent.kind() === 212 /* MemberAccessExpression */ && ast.parent.name === ast) { + return true; + } + + return false; + } + ASTHelpers.isNameOfMemberAccessExpression = isNameOfMemberAccessExpression; + + function isRightSideOfQualifiedName(ast) { + if (ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast) { + return true; + } + + return false; + } + ASTHelpers.isRightSideOfQualifiedName = isRightSideOfQualifiedName; + + function parentIsModuleDeclaration(ast) { + return ast.parent && ast.parent.kind() === 130 /* ModuleDeclaration */; + } + ASTHelpers.parentIsModuleDeclaration = parentIsModuleDeclaration; + + function parametersFromIdentifier(id) { + return { + length: 1, + lastParameterIsRest: function () { + return false; + }, + ast: id, + astAt: function (index) { + return id; + }, + identifierAt: function (index) { + return id; + }, + typeAt: function (index) { + return null; + }, + initializerAt: function (index) { + return null; + }, + isOptionalAt: function (index) { + return false; + } + }; + } + ASTHelpers.parametersFromIdentifier = parametersFromIdentifier; + + function parametersFromParameter(parameter) { + return { + length: 1, + lastParameterIsRest: function () { + return parameter.dotDotDotToken !== null; + }, + ast: parameter, + astAt: function (index) { + return parameter; + }, + identifierAt: function (index) { + return parameter.identifier; + }, + typeAt: function (index) { + return getType(parameter); + }, + initializerAt: function (index) { + return parameter.equalsValueClause; + }, + isOptionalAt: function (index) { + return parameterIsOptional(parameter); + } + }; + } + ASTHelpers.parametersFromParameter = parametersFromParameter; + + function parameterIsOptional(parameter) { + return parameter.questionToken !== null || parameter.equalsValueClause !== null; + } + + function parametersFromParameterList(list) { + return { + length: list.parameters.nonSeparatorCount(), + lastParameterIsRest: function () { + return TypeScript.lastParameterIsRest(list); + }, + ast: list.parameters, + astAt: function (index) { + return list.parameters.nonSeparatorAt(index); + }, + identifierAt: function (index) { + return list.parameters.nonSeparatorAt(index).identifier; + }, + typeAt: function (index) { + return getType(list.parameters.nonSeparatorAt(index)); + }, + initializerAt: function (index) { + return list.parameters.nonSeparatorAt(index).equalsValueClause; + }, + isOptionalAt: function (index) { + return parameterIsOptional(list.parameters.nonSeparatorAt(index)); + } + }; + } + ASTHelpers.parametersFromParameterList = parametersFromParameterList; + + function isDeclarationAST(ast) { + switch (ast.kind()) { + case 225 /* VariableDeclarator */: + return getVariableStatement(ast) !== null; + + case 133 /* ImportDeclaration */: + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 242 /* Parameter */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 144 /* IndexSignature */: + case 129 /* FunctionDeclaration */: + case 130 /* ModuleDeclaration */: + case 124 /* ArrayType */: + case 122 /* ObjectType */: + case 238 /* TypeParameter */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 136 /* MemberVariableDeclaration */: + case 138 /* IndexMemberDeclaration */: + case 132 /* EnumDeclaration */: + case 243 /* EnumElement */: + case 240 /* SimplePropertyAssignment */: + case 241 /* FunctionPropertyAssignment */: + case 222 /* FunctionExpression */: + case 142 /* CallSignature */: + case 143 /* ConstructSignature */: + case 145 /* MethodSignature */: + case 141 /* PropertySignature */: + return true; + default: + return false; + } + } + ASTHelpers.isDeclarationAST = isDeclarationAST; + + function docComments(ast) { + if (isDeclarationAST(ast)) { + var preComments = ast.kind() === 225 /* VariableDeclarator */ ? getVariableStatement(ast).preComments() : ast.preComments(); + + if (preComments && preComments.length > 0) { + var preCommentsLength = preComments.length; + var docComments = new Array(); + for (var i = preCommentsLength - 1; i >= 0; i--) { + if (isDocComment(preComments[i])) { + docComments.push(preComments[i]); + continue; + } + + break; + } + + return docComments.reverse(); + } + } + + return TypeScript.sentinelEmptyArray; + } + ASTHelpers.docComments = docComments; + + function isDocComment(comment) { + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + var fullText = comment.fullText(); + return fullText.charAt(2) === "*" && fullText.charAt(3) !== "/"; + } + + return false; + } + + function getParameterList(ast) { + if (ast) { + switch (ast.kind()) { + case 137 /* ConstructorDeclaration */: + return getParameterList(ast.callSignature); + case 129 /* FunctionDeclaration */: + return getParameterList(ast.callSignature); + case 218 /* ParenthesizedArrowFunctionExpression */: + return getParameterList(ast.callSignature); + case 143 /* ConstructSignature */: + return getParameterList(ast.callSignature); + case 135 /* MemberFunctionDeclaration */: + return getParameterList(ast.callSignature); + case 241 /* FunctionPropertyAssignment */: + return getParameterList(ast.callSignature); + case 222 /* FunctionExpression */: + return getParameterList(ast.callSignature); + case 145 /* MethodSignature */: + return getParameterList(ast.callSignature); + case 125 /* ConstructorType */: + return ast.parameterList; + case 123 /* FunctionType */: + return ast.parameterList; + case 142 /* CallSignature */: + return ast.parameterList; + case 139 /* GetAccessor */: + return ast.parameterList; + case 140 /* SetAccessor */: + return ast.parameterList; + } + } + + return null; + } + ASTHelpers.getParameterList = getParameterList; + + function getType(ast) { + if (ast) { + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + return getType(ast.callSignature); + case 218 /* ParenthesizedArrowFunctionExpression */: + return getType(ast.callSignature); + case 143 /* ConstructSignature */: + return getType(ast.callSignature); + case 135 /* MemberFunctionDeclaration */: + return getType(ast.callSignature); + case 241 /* FunctionPropertyAssignment */: + return getType(ast.callSignature); + case 222 /* FunctionExpression */: + return getType(ast.callSignature); + case 145 /* MethodSignature */: + return getType(ast.callSignature); + case 142 /* CallSignature */: + return getType(ast.typeAnnotation); + case 144 /* IndexSignature */: + return getType(ast.typeAnnotation); + case 141 /* PropertySignature */: + return getType(ast.typeAnnotation); + case 139 /* GetAccessor */: + return getType(ast.typeAnnotation); + case 242 /* Parameter */: + return getType(ast.typeAnnotation); + case 136 /* MemberVariableDeclaration */: + return getType(ast.variableDeclarator); + case 225 /* VariableDeclarator */: + return getType(ast.typeAnnotation); + case 236 /* CatchClause */: + return getType(ast.typeAnnotation); + case 125 /* ConstructorType */: + return ast.type; + case 123 /* FunctionType */: + return ast.type; + case 244 /* TypeAnnotation */: + return ast.type; + } + } + + return null; + } + ASTHelpers.getType = getType; + + function getVariableStatement(variableDeclarator) { + if (variableDeclarator && variableDeclarator.parent && variableDeclarator.parent.parent && variableDeclarator.parent.parent.parent && variableDeclarator.parent.kind() === 2 /* SeparatedList */ && variableDeclarator.parent.parent.kind() === 224 /* VariableDeclaration */ && variableDeclarator.parent.parent.parent.kind() === 148 /* VariableStatement */) { + return variableDeclarator.parent.parent.parent; + } + + return null; + } + + function getVariableDeclaratorModifiers(variableDeclarator) { + var variableStatement = getVariableStatement(variableDeclarator); + return variableStatement ? variableStatement.modifiers : TypeScript.sentinelEmptyArray; + } + ASTHelpers.getVariableDeclaratorModifiers = getVariableDeclaratorModifiers; + + function isIntegerLiteralAST(expression) { + if (expression) { + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + expression = expression.operand; + return expression.kind() === 13 /* NumericLiteral */ && TypeScript.IntegerUtilities.isInteger(expression.text()); + + case 13 /* NumericLiteral */: + var text = expression.text(); + return TypeScript.IntegerUtilities.isInteger(text) || TypeScript.IntegerUtilities.isHexInteger(text); + } + } + + return false; + } + ASTHelpers.isIntegerLiteralAST = isIntegerLiteralAST; + + function getEnclosingModuleDeclaration(ast) { + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + return ast; + } + + ast = ast.parent; + } + + return null; + } + ASTHelpers.getEnclosingModuleDeclaration = getEnclosingModuleDeclaration; + + function isEntireNameOfModuleDeclaration(nameAST) { + return parentIsModuleDeclaration(nameAST) && nameAST.parent.name === nameAST; + } + + function getModuleDeclarationFromNameAST(ast) { + if (ast) { + switch (ast.kind()) { + case 14 /* StringLiteral */: + if (parentIsModuleDeclaration(ast) && ast.parent.stringLiteral === ast) { + return ast.parent; + } + return null; + + case 11 /* IdentifierName */: + case 121 /* QualifiedName */: + if (isEntireNameOfModuleDeclaration(ast)) { + return ast.parent; + } + break; + + default: + return null; + } + + for (ast = ast.parent; ast && ast.kind() === 121 /* QualifiedName */; ast = ast.parent) { + if (isEntireNameOfModuleDeclaration(ast)) { + return ast.parent; + } + } + } + + return null; + } + ASTHelpers.getModuleDeclarationFromNameAST = getModuleDeclarationFromNameAST; + + function isLastNameOfModule(ast, astName) { + if (ast) { + if (ast.stringLiteral) { + return astName === ast.stringLiteral; + } else if (ast.name.kind() === 121 /* QualifiedName */) { + return astName === ast.name.right; + } else { + return astName === ast.name; + } + } + + return false; + } + ASTHelpers.isLastNameOfModule = isLastNameOfModule; + + function getNameOfIdenfierOrQualifiedName(name) { + if (name.kind() === 11 /* IdentifierName */) { + return name.text(); + } else { + TypeScript.Debug.assert(name.kind() == 121 /* QualifiedName */); + var dotExpr = name; + return getNameOfIdenfierOrQualifiedName(dotExpr.left) + "." + getNameOfIdenfierOrQualifiedName(dotExpr.right); + } + } + ASTHelpers.getNameOfIdenfierOrQualifiedName = getNameOfIdenfierOrQualifiedName; + + function getModuleNames(name, result) { + result = result || []; + + if (name.kind() === 121 /* QualifiedName */) { + getModuleNames(name.left, result); + result.push(name.right); + } else { + result.push(name); + } + + return result; + } + ASTHelpers.getModuleNames = getModuleNames; + })(TypeScript.ASTHelpers || (TypeScript.ASTHelpers = {})); + var ASTHelpers = TypeScript.ASTHelpers; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function walkListChildren(preAst, walker) { + for (var i = 0, n = preAst.childCount(); i < n; i++) { + walker.walk(preAst.childAt(i)); + } + } + + function walkThrowStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkPrefixUnaryExpressionChildren(preAst, walker) { + walker.walk(preAst.operand); + } + + function walkPostfixUnaryExpressionChildren(preAst, walker) { + walker.walk(preAst.operand); + } + + function walkDeleteExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkTypeArgumentListChildren(preAst, walker) { + walker.walk(preAst.typeArguments); + } + + function walkTypeOfExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkVoidExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkArgumentListChildren(preAst, walker) { + walker.walk(preAst.typeArgumentList); + walker.walk(preAst.arguments); + } + + function walkArrayLiteralExpressionChildren(preAst, walker) { + walker.walk(preAst.expressions); + } + + function walkSimplePropertyAssignmentChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.expression); + } + + function walkFunctionPropertyAssignmentChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkGetAccessorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.parameterList); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.block); + } + + function walkSeparatedListChildren(preAst, walker) { + for (var i = 0, n = preAst.nonSeparatorCount(); i < n; i++) { + walker.walk(preAst.nonSeparatorAt(i)); + } + } + + function walkSetAccessorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.parameterList); + walker.walk(preAst.block); + } + + function walkObjectLiteralExpressionChildren(preAst, walker) { + walker.walk(preAst.propertyAssignments); + } + + function walkCastExpressionChildren(preAst, walker) { + walker.walk(preAst.type); + walker.walk(preAst.expression); + } + + function walkParenthesizedExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkElementAccessExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentExpression); + } + + function walkMemberAccessExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.name); + } + + function walkQualifiedNameChildren(preAst, walker) { + walker.walk(preAst.left); + walker.walk(preAst.right); + } + + function walkBinaryExpressionChildren(preAst, walker) { + walker.walk(preAst.left); + walker.walk(preAst.right); + } + + function walkEqualsValueClauseChildren(preAst, walker) { + walker.walk(preAst.value); + } + + function walkTypeParameterChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.constraint); + } + + function walkTypeParameterListChildren(preAst, walker) { + walker.walk(preAst.typeParameters); + } + + function walkGenericTypeChildren(preAst, walker) { + walker.walk(preAst.name); + walker.walk(preAst.typeArgumentList); + } + + function walkTypeAnnotationChildren(preAst, walker) { + walker.walk(preAst.type); + } + + function walkTypeQueryChildren(preAst, walker) { + walker.walk(preAst.name); + } + + function walkInvocationExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentList); + } + + function walkObjectCreationExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentList); + } + + function walkTrinaryExpressionChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.whenTrue); + walker.walk(preAst.whenFalse); + } + + function walkFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkFunctionTypeChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.type); + } + + function walkParenthesizedArrowFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + walker.walk(preAst.expression); + } + + function walkSimpleArrowFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.block); + walker.walk(preAst.expression); + } + + function walkMemberFunctionDeclarationChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkFuncDeclChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkIndexMemberDeclarationChildren(preAst, walker) { + walker.walk(preAst.indexSignature); + } + + function walkIndexSignatureChildren(preAst, walker) { + walker.walk(preAst.parameter); + walker.walk(preAst.typeAnnotation); + } + + function walkCallSignatureChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.typeAnnotation); + } + + function walkConstraintChildren(preAst, walker) { + walker.walk(preAst.type); + } + + function walkConstructorDeclarationChildren(preAst, walker) { + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkConstructorTypeChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.type); + } + + function walkConstructSignatureChildren(preAst, walker) { + walker.walk(preAst.callSignature); + } + + function walkParameterChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.equalsValueClause); + } + + function walkParameterListChildren(preAst, walker) { + walker.walk(preAst.parameters); + } + + function walkPropertySignatureChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.typeAnnotation); + } + + function walkVariableDeclaratorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.equalsValueClause); + } + + function walkMemberVariableDeclarationChildren(preAst, walker) { + walker.walk(preAst.variableDeclarator); + } + + function walkMethodSignatureChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + } + + function walkReturnStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkForStatementChildren(preAst, walker) { + walker.walk(preAst.variableDeclaration); + walker.walk(preAst.initializer); + walker.walk(preAst.condition); + walker.walk(preAst.incrementor); + walker.walk(preAst.statement); + } + + function walkForInStatementChildren(preAst, walker) { + walker.walk(preAst.variableDeclaration); + walker.walk(preAst.left); + walker.walk(preAst.expression); + walker.walk(preAst.statement); + } + + function walkIfStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + walker.walk(preAst.elseClause); + } + + function walkElseClauseChildren(preAst, walker) { + walker.walk(preAst.statement); + } + + function walkWhileStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + + function walkDoStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + + function walkBlockChildren(preAst, walker) { + walker.walk(preAst.statements); + } + + function walkVariableDeclarationChildren(preAst, walker) { + walker.walk(preAst.declarators); + } + + function walkCaseSwitchClauseChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.statements); + } + + function walkDefaultSwitchClauseChildren(preAst, walker) { + walker.walk(preAst.statements); + } + + function walkSwitchStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.switchClauses); + } + + function walkTryStatementChildren(preAst, walker) { + walker.walk(preAst.block); + walker.walk(preAst.catchClause); + walker.walk(preAst.finallyClause); + } + + function walkCatchClauseChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.block); + } + + function walkExternalModuleReferenceChildren(preAst, walker) { + walker.walk(preAst.stringLiteral); + } + + function walkFinallyClauseChildren(preAst, walker) { + walker.walk(preAst.block); + } + + function walkClassDeclChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeParameterList); + walker.walk(preAst.heritageClauses); + walker.walk(preAst.classElements); + } + + function walkScriptChildren(preAst, walker) { + walker.walk(preAst.moduleElements); + } + + function walkHeritageClauseChildren(preAst, walker) { + walker.walk(preAst.typeNames); + } + + function walkInterfaceDeclerationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeParameterList); + walker.walk(preAst.heritageClauses); + walker.walk(preAst.body); + } + + function walkObjectTypeChildren(preAst, walker) { + walker.walk(preAst.typeMembers); + } + + function walkArrayTypeChildren(preAst, walker) { + walker.walk(preAst.type); + } + + function walkModuleDeclarationChildren(preAst, walker) { + walker.walk(preAst.name); + walker.walk(preAst.stringLiteral); + walker.walk(preAst.moduleElements); + } + + function walkModuleNameModuleReferenceChildren(preAst, walker) { + walker.walk(preAst.moduleName); + } + + function walkEnumDeclarationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.enumElements); + } + + function walkEnumElementChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.equalsValueClause); + } + + function walkImportDeclarationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.moduleReference); + } + + function walkExportAssignmentChildren(preAst, walker) { + walker.walk(preAst.identifier); + } + + function walkWithStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + + function walkExpressionStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkLabeledStatementChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.statement); + } + + function walkVariableStatementChildren(preAst, walker) { + walker.walk(preAst.declaration); + } + + var childrenWalkers = new Array(246 /* Last */ + 1); + + for (var i = 9 /* FirstToken */, n = 119 /* LastToken */; i <= n; i++) { + childrenWalkers[i] = null; + } + for (var i = 4 /* FirstTrivia */, n = 8 /* LastTrivia */; i <= n; i++) { + childrenWalkers[i] = null; + } + + childrenWalkers[175 /* AddAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[208 /* AddExpression */] = walkBinaryExpressionChildren; + childrenWalkers[180 /* AndAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[60 /* AnyKeyword */] = null; + childrenWalkers[226 /* ArgumentList */] = walkArgumentListChildren; + childrenWalkers[214 /* ArrayLiteralExpression */] = walkArrayLiteralExpressionChildren; + childrenWalkers[124 /* ArrayType */] = walkArrayTypeChildren; + childrenWalkers[219 /* SimpleArrowFunctionExpression */] = walkSimpleArrowFunctionExpressionChildren; + childrenWalkers[218 /* ParenthesizedArrowFunctionExpression */] = walkParenthesizedArrowFunctionExpressionChildren; + childrenWalkers[174 /* AssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[191 /* BitwiseAndExpression */] = walkBinaryExpressionChildren; + childrenWalkers[190 /* BitwiseExclusiveOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[166 /* BitwiseNotExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[189 /* BitwiseOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[146 /* Block */] = walkBlockChildren; + childrenWalkers[61 /* BooleanKeyword */] = null; + childrenWalkers[152 /* BreakStatement */] = null; + childrenWalkers[142 /* CallSignature */] = walkCallSignatureChildren; + childrenWalkers[233 /* CaseSwitchClause */] = walkCaseSwitchClauseChildren; + childrenWalkers[220 /* CastExpression */] = walkCastExpressionChildren; + childrenWalkers[236 /* CatchClause */] = walkCatchClauseChildren; + childrenWalkers[131 /* ClassDeclaration */] = walkClassDeclChildren; + childrenWalkers[173 /* CommaExpression */] = walkBinaryExpressionChildren; + childrenWalkers[186 /* ConditionalExpression */] = walkTrinaryExpressionChildren; + childrenWalkers[239 /* Constraint */] = walkConstraintChildren; + childrenWalkers[137 /* ConstructorDeclaration */] = walkConstructorDeclarationChildren; + childrenWalkers[143 /* ConstructSignature */] = walkConstructSignatureChildren; + childrenWalkers[153 /* ContinueStatement */] = null; + childrenWalkers[125 /* ConstructorType */] = walkConstructorTypeChildren; + childrenWalkers[162 /* DebuggerStatement */] = null; + childrenWalkers[234 /* DefaultSwitchClause */] = walkDefaultSwitchClauseChildren; + childrenWalkers[170 /* DeleteExpression */] = walkDeleteExpressionChildren; + childrenWalkers[178 /* DivideAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[206 /* DivideExpression */] = walkBinaryExpressionChildren; + childrenWalkers[161 /* DoStatement */] = walkDoStatementChildren; + childrenWalkers[221 /* ElementAccessExpression */] = walkElementAccessExpressionChildren; + childrenWalkers[235 /* ElseClause */] = walkElseClauseChildren; + childrenWalkers[156 /* EmptyStatement */] = null; + childrenWalkers[132 /* EnumDeclaration */] = walkEnumDeclarationChildren; + childrenWalkers[243 /* EnumElement */] = walkEnumElementChildren; + childrenWalkers[194 /* EqualsExpression */] = walkBinaryExpressionChildren; + childrenWalkers[232 /* EqualsValueClause */] = walkEqualsValueClauseChildren; + childrenWalkers[192 /* EqualsWithTypeConversionExpression */] = walkBinaryExpressionChildren; + childrenWalkers[181 /* ExclusiveOrAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[134 /* ExportAssignment */] = walkExportAssignmentChildren; + childrenWalkers[149 /* ExpressionStatement */] = walkExpressionStatementChildren; + childrenWalkers[230 /* ExtendsHeritageClause */] = walkHeritageClauseChildren; + childrenWalkers[245 /* ExternalModuleReference */] = walkExternalModuleReferenceChildren; + childrenWalkers[24 /* FalseKeyword */] = null; + childrenWalkers[237 /* FinallyClause */] = walkFinallyClauseChildren; + childrenWalkers[155 /* ForInStatement */] = walkForInStatementChildren; + childrenWalkers[154 /* ForStatement */] = walkForStatementChildren; + childrenWalkers[129 /* FunctionDeclaration */] = walkFuncDeclChildren; + childrenWalkers[222 /* FunctionExpression */] = walkFunctionExpressionChildren; + childrenWalkers[241 /* FunctionPropertyAssignment */] = walkFunctionPropertyAssignmentChildren; + childrenWalkers[123 /* FunctionType */] = walkFunctionTypeChildren; + childrenWalkers[126 /* GenericType */] = walkGenericTypeChildren; + childrenWalkers[139 /* GetAccessor */] = walkGetAccessorChildren; + childrenWalkers[197 /* GreaterThanExpression */] = walkBinaryExpressionChildren; + childrenWalkers[199 /* GreaterThanOrEqualExpression */] = walkBinaryExpressionChildren; + childrenWalkers[147 /* IfStatement */] = walkIfStatementChildren; + childrenWalkers[231 /* ImplementsHeritageClause */] = walkHeritageClauseChildren; + childrenWalkers[133 /* ImportDeclaration */] = walkImportDeclarationChildren; + childrenWalkers[138 /* IndexMemberDeclaration */] = walkIndexMemberDeclarationChildren; + childrenWalkers[144 /* IndexSignature */] = walkIndexSignatureChildren; + childrenWalkers[201 /* InExpression */] = walkBinaryExpressionChildren; + childrenWalkers[200 /* InstanceOfExpression */] = walkBinaryExpressionChildren; + childrenWalkers[128 /* InterfaceDeclaration */] = walkInterfaceDeclerationChildren; + childrenWalkers[213 /* InvocationExpression */] = walkInvocationExpressionChildren; + childrenWalkers[160 /* LabeledStatement */] = walkLabeledStatementChildren; + childrenWalkers[183 /* LeftShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[202 /* LeftShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[196 /* LessThanExpression */] = walkBinaryExpressionChildren; + childrenWalkers[198 /* LessThanOrEqualExpression */] = walkBinaryExpressionChildren; + childrenWalkers[1 /* List */] = walkListChildren; + childrenWalkers[188 /* LogicalAndExpression */] = walkBinaryExpressionChildren; + childrenWalkers[167 /* LogicalNotExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[187 /* LogicalOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[212 /* MemberAccessExpression */] = walkMemberAccessExpressionChildren; + childrenWalkers[135 /* MemberFunctionDeclaration */] = walkMemberFunctionDeclarationChildren; + childrenWalkers[136 /* MemberVariableDeclaration */] = walkMemberVariableDeclarationChildren; + childrenWalkers[145 /* MethodSignature */] = walkMethodSignatureChildren; + childrenWalkers[130 /* ModuleDeclaration */] = walkModuleDeclarationChildren; + childrenWalkers[246 /* ModuleNameModuleReference */] = walkModuleNameModuleReferenceChildren; + childrenWalkers[179 /* ModuloAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[207 /* ModuloExpression */] = walkBinaryExpressionChildren; + childrenWalkers[177 /* MultiplyAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[205 /* MultiplyExpression */] = walkBinaryExpressionChildren; + childrenWalkers[11 /* IdentifierName */] = null; + childrenWalkers[165 /* NegateExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[0 /* None */] = null; + childrenWalkers[195 /* NotEqualsExpression */] = walkBinaryExpressionChildren; + childrenWalkers[193 /* NotEqualsWithTypeConversionExpression */] = walkBinaryExpressionChildren; + childrenWalkers[32 /* NullKeyword */] = null; + childrenWalkers[67 /* NumberKeyword */] = null; + childrenWalkers[13 /* NumericLiteral */] = null; + childrenWalkers[216 /* ObjectCreationExpression */] = walkObjectCreationExpressionChildren; + childrenWalkers[215 /* ObjectLiteralExpression */] = walkObjectLiteralExpressionChildren; + childrenWalkers[122 /* ObjectType */] = walkObjectTypeChildren; + childrenWalkers[223 /* OmittedExpression */] = null; + childrenWalkers[182 /* OrAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[242 /* Parameter */] = walkParameterChildren; + childrenWalkers[227 /* ParameterList */] = walkParameterListChildren; + childrenWalkers[217 /* ParenthesizedExpression */] = walkParenthesizedExpressionChildren; + childrenWalkers[164 /* PlusExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[211 /* PostDecrementExpression */] = walkPostfixUnaryExpressionChildren; + childrenWalkers[210 /* PostIncrementExpression */] = walkPostfixUnaryExpressionChildren; + childrenWalkers[169 /* PreDecrementExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[168 /* PreIncrementExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[141 /* PropertySignature */] = walkPropertySignatureChildren; + childrenWalkers[121 /* QualifiedName */] = walkQualifiedNameChildren; + childrenWalkers[12 /* RegularExpressionLiteral */] = null; + childrenWalkers[150 /* ReturnStatement */] = walkReturnStatementChildren; + childrenWalkers[120 /* SourceUnit */] = walkScriptChildren; + childrenWalkers[2 /* SeparatedList */] = walkSeparatedListChildren; + childrenWalkers[140 /* SetAccessor */] = walkSetAccessorChildren; + childrenWalkers[184 /* SignedRightShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[203 /* SignedRightShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[240 /* SimplePropertyAssignment */] = walkSimplePropertyAssignmentChildren; + childrenWalkers[14 /* StringLiteral */] = null; + childrenWalkers[69 /* StringKeyword */] = null; + childrenWalkers[176 /* SubtractAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[209 /* SubtractExpression */] = walkBinaryExpressionChildren; + childrenWalkers[50 /* SuperKeyword */] = null; + childrenWalkers[151 /* SwitchStatement */] = walkSwitchStatementChildren; + childrenWalkers[35 /* ThisKeyword */] = null; + childrenWalkers[157 /* ThrowStatement */] = walkThrowStatementChildren; + childrenWalkers[3 /* TriviaList */] = null; + childrenWalkers[37 /* TrueKeyword */] = null; + childrenWalkers[159 /* TryStatement */] = walkTryStatementChildren; + childrenWalkers[244 /* TypeAnnotation */] = walkTypeAnnotationChildren; + childrenWalkers[228 /* TypeArgumentList */] = walkTypeArgumentListChildren; + childrenWalkers[171 /* TypeOfExpression */] = walkTypeOfExpressionChildren; + childrenWalkers[238 /* TypeParameter */] = walkTypeParameterChildren; + childrenWalkers[229 /* TypeParameterList */] = walkTypeParameterListChildren; + childrenWalkers[127 /* TypeQuery */] = walkTypeQueryChildren; + childrenWalkers[185 /* UnsignedRightShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[204 /* UnsignedRightShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[224 /* VariableDeclaration */] = walkVariableDeclarationChildren; + childrenWalkers[225 /* VariableDeclarator */] = walkVariableDeclaratorChildren; + childrenWalkers[148 /* VariableStatement */] = walkVariableStatementChildren; + childrenWalkers[172 /* VoidExpression */] = walkVoidExpressionChildren; + childrenWalkers[41 /* VoidKeyword */] = null; + childrenWalkers[158 /* WhileStatement */] = walkWhileStatementChildren; + childrenWalkers[163 /* WithStatement */] = walkWithStatementChildren; + + for (var e in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind.hasOwnProperty(e) && TypeScript.StringUtilities.isString(TypeScript.SyntaxKind[e])) { + TypeScript.Debug.assert(childrenWalkers[e] !== undefined, "Fix initWalkers: " + TypeScript.SyntaxKind[e]); + } + } + + var AstWalkOptions = (function () { + function AstWalkOptions() { + this.goChildren = true; + this.stopWalking = false; + } + return AstWalkOptions; + })(); + TypeScript.AstWalkOptions = AstWalkOptions; + + var SimplePreAstWalker = (function () { + function SimplePreAstWalker(pre, state) { + this.pre = pre; + this.state = state; + this.options = new AstWalkOptions(); + } + SimplePreAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + + this.pre(ast, this.state); + + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + }; + return SimplePreAstWalker; + })(); + + var SimplePrePostAstWalker = (function () { + function SimplePrePostAstWalker(pre, post, state) { + this.pre = pre; + this.post = post; + this.state = state; + this.options = new AstWalkOptions(); + } + SimplePrePostAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + + this.pre(ast, this.state); + + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + + this.post(ast, this.state); + }; + return SimplePrePostAstWalker; + })(); + + var NormalAstWalker = (function () { + function NormalAstWalker(pre, post, state) { + this.pre = pre; + this.post = post; + this.state = state; + this.options = new AstWalkOptions(); + } + NormalAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + + if (this.options.stopWalking) { + return; + } + + this.pre(ast, this); + + if (this.options.stopWalking) { + return; + } + + if (this.options.goChildren) { + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + } else { + this.options.goChildren = true; + } + + if (this.post) { + this.post(ast, this); + } + }; + return NormalAstWalker; + })(); + + var AstWalkerFactory = (function () { + function AstWalkerFactory() { + } + AstWalkerFactory.prototype.walk = function (ast, pre, post, state) { + new NormalAstWalker(pre, post, state).walk(ast); + }; + + AstWalkerFactory.prototype.simpleWalk = function (ast, pre, post, state) { + if (post) { + new SimplePrePostAstWalker(pre, post, state).walk(ast); + } else { + new SimplePreAstWalker(pre, state).walk(ast); + } + }; + return AstWalkerFactory; + })(); + TypeScript.AstWalkerFactory = AstWalkerFactory; + + var globalAstWalkerFactory = new AstWalkerFactory(); + + function getAstWalkerFactory() { + return globalAstWalkerFactory; + } + TypeScript.getAstWalkerFactory = getAstWalkerFactory; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Base64Format = (function () { + function Base64Format() { + } + Base64Format.encode = function (inValue) { + if (inValue < 64) { + return Base64Format.encodedValues.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + }; + + Base64Format.decodeChar = function (inChar) { + if (inChar.length === 1) { + return Base64Format.encodedValues.indexOf(inChar); + } else { + throw TypeError('"' + inChar + '" must have length 1'); + } + }; + Base64Format.encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + return Base64Format; + })(); + + var Base64VLQFormat = (function () { + function Base64VLQFormat() { + } + Base64VLQFormat.encode = function (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 (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(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Base64_value_0_finished_with_a_continuation_bit, [inString])); + }; + return Base64VLQFormat; + })(); + TypeScript.Base64VLQFormat = Base64VLQFormat; +})(TypeScript || (TypeScript = {})); +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 SourceMapEntry = (function () { + function SourceMapEntry(emittedFile, emittedLine, emittedColumn, sourceFile, sourceLine, sourceColumn, sourceName) { + this.emittedFile = emittedFile; + this.emittedLine = emittedLine; + this.emittedColumn = emittedColumn; + this.sourceFile = sourceFile; + this.sourceLine = sourceLine; + this.sourceColumn = sourceColumn; + this.sourceName = sourceName; + TypeScript.Debug.assert(isFinite(emittedLine)); + TypeScript.Debug.assert(isFinite(emittedColumn)); + TypeScript.Debug.assert(isFinite(sourceColumn)); + TypeScript.Debug.assert(isFinite(sourceLine)); + } + return SourceMapEntry; + })(); + TypeScript.SourceMapEntry = SourceMapEntry; + + var SourceMapper = (function () { + function SourceMapper(jsFile, sourceMapOut, document, jsFilePath, emitOptions, resolvePath) { + this.jsFile = jsFile; + this.sourceMapOut = sourceMapOut; + this.names = []; + this.mappingLevel = []; + this.tsFilePaths = []; + this.allSourceMappings = []; + this.sourceMapEntries = []; + this.setSourceMapOptions(document, jsFilePath, emitOptions, resolvePath); + this.setNewSourceFile(document, emitOptions); + } + SourceMapper.prototype.getOutputFile = function () { + var result = this.sourceMapOut.getOutputFile(); + result.sourceMapEntries = this.sourceMapEntries; + + return result; + }; + + SourceMapper.prototype.increaseMappingLevel = function (ast) { + this.mappingLevel.push(ast); + }; + + SourceMapper.prototype.decreaseMappingLevel = function (ast) { + TypeScript.Debug.assert(this.mappingLevel.length > 0, "Mapping level should never be less than 0. This suggests a missing start call."); + var expectedAst = this.mappingLevel.pop(); + var expectedAstInfo = expectedAst.kind ? TypeScript.SyntaxKind[expectedAst.kind()] : [expectedAst.start(), expectedAst.end()]; + var astInfo = ast.kind ? TypeScript.SyntaxKind[ast.kind()] : [ast.start(), ast.end()]; + TypeScript.Debug.assert(ast === expectedAst, "Provided ast is not the expected AST, Expected: " + expectedAstInfo + " Given: " + astInfo); + }; + + SourceMapper.prototype.setNewSourceFile = function (document, emitOptions) { + var sourceMappings = []; + this.allSourceMappings.push(sourceMappings); + this.currentMappings = [sourceMappings]; + this.currentNameIndex = []; + + this.setNewSourceFilePath(document, emitOptions); + }; + + SourceMapper.prototype.setSourceMapOptions = function (document, jsFilePath, emitOptions, resolvePath) { + var prettyJsFileName = TypeScript.getPrettyName(jsFilePath, false, true); + var prettyMapFileName = prettyJsFileName + SourceMapper.MapFileExtension; + this.jsFileName = prettyJsFileName; + + if (emitOptions.sourceMapRootDirectory()) { + this.sourceMapDirectory = emitOptions.sourceMapRootDirectory(); + if (document.emitToOwnOutputFile()) { + this.sourceMapDirectory = this.sourceMapDirectory + TypeScript.switchToForwardSlashes(TypeScript.getRootFilePath((document.fileName)).replace(emitOptions.commonDirectoryPath(), "")); + } + + if (TypeScript.isRelative(this.sourceMapDirectory)) { + this.sourceMapDirectory = emitOptions.commonDirectoryPath() + this.sourceMapDirectory; + this.sourceMapDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(resolvePath(this.sourceMapDirectory))); + this.sourceMapPath = TypeScript.getRelativePathToFixedPath(TypeScript.getRootFilePath(jsFilePath), this.sourceMapDirectory + prettyMapFileName); + } else { + this.sourceMapPath = this.sourceMapDirectory + prettyMapFileName; + } + } else { + this.sourceMapPath = prettyMapFileName; + this.sourceMapDirectory = TypeScript.getRootFilePath(jsFilePath); + } + this.sourceRoot = emitOptions.sourceRootDirectory(); + }; + + SourceMapper.prototype.setNewSourceFilePath = function (document, emitOptions) { + var tsFilePath = TypeScript.switchToForwardSlashes(document.fileName); + if (emitOptions.sourceRootDirectory()) { + tsFilePath = TypeScript.getRelativePathToFixedPath(emitOptions.commonDirectoryPath(), tsFilePath); + } else { + tsFilePath = TypeScript.getRelativePathToFixedPath(this.sourceMapDirectory, tsFilePath); + } + this.tsFilePaths.push(tsFilePath); + }; + + SourceMapper.prototype.emitSourceMapping = function () { + var _this = this; + TypeScript.Debug.assert(this.mappingLevel.length === 0, "Mapping level is not 0. This suggest a missing end call. Value: " + this.mappingLevel.map(function (item) { + return ['Node of type', TypeScript.SyntaxKind[item.kind()], 'at', item.start(), 'to', item.end()].join(' '); + }).join(', ')); + + this.jsFile.WriteLine("//# sourceMappingURL=" + this.sourceMapPath); + + var mappingsString = ""; + + var prevEmittedColumn = 0; + var prevEmittedLine = 0; + var prevSourceColumn = 0; + var prevSourceLine = 0; + var prevSourceIndex = 0; + var prevNameIndex = 0; + var emitComma = false; + + var recordedPosition = null; + for (var sourceIndex = 0; sourceIndex < this.tsFilePaths.length; sourceIndex++) { + 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 + ","; + } + + _this.sourceMapEntries.push(new SourceMapEntry(_this.jsFileName, mappedPosition.emittedLine + 1, mappedPosition.emittedColumn + 1, _this.tsFilePaths[sourceIndex], mappedPosition.sourceLine, mappedPosition.sourceColumn + 1, nameIndex >= 0 ? _this.names[nameIndex] : undefined)); + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.emittedColumn - prevEmittedColumn); + prevEmittedColumn = mappedPosition.emittedColumn; + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(sourceIndex - prevSourceIndex); + prevSourceIndex = sourceIndex; + + 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(nameIndex - prevNameIndex); + prevNameIndex = 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(this.allSourceMappings[sourceIndex]); + } + + this.sourceMapOut.Write(JSON.stringify({ + version: 3, + file: this.jsFileName, + sourceRoot: this.sourceRoot, + sources: this.tsFilePaths, + names: this.names, + mappings: mappingsString + })); + + this.sourceMapOut.Close(); + }; + SourceMapper.MapFileExtension = ".map"; + return SourceMapper; + })(); + TypeScript.SourceMapper = SourceMapper; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (EmitContainer) { + EmitContainer[EmitContainer["Prog"] = 0] = "Prog"; + EmitContainer[EmitContainer["Module"] = 1] = "Module"; + EmitContainer[EmitContainer["DynamicModule"] = 2] = "DynamicModule"; + EmitContainer[EmitContainer["Class"] = 3] = "Class"; + EmitContainer[EmitContainer["Constructor"] = 4] = "Constructor"; + EmitContainer[EmitContainer["Function"] = 5] = "Function"; + EmitContainer[EmitContainer["Args"] = 6] = "Args"; + EmitContainer[EmitContainer["Interface"] = 7] = "Interface"; + })(TypeScript.EmitContainer || (TypeScript.EmitContainer = {})); + var EmitContainer = TypeScript.EmitContainer; + + var EmitState = (function () { + function EmitState() { + this.column = 0; + this.line = 0; + this.container = 0 /* Prog */; + } + return EmitState; + })(); + TypeScript.EmitState = EmitState; + + var EmitOptions = (function () { + function EmitOptions(compiler, resolvePath) { + this.resolvePath = resolvePath; + this._diagnostic = null; + this._settings = null; + this._commonDirectoryPath = ""; + this._sharedOutputFile = ""; + this._sourceRootDirectory = ""; + this._sourceMapRootDirectory = ""; + this._outputDirectory = ""; + var settings = compiler.compilationSettings(); + this._settings = settings; + + if (settings.moduleGenTarget() === 0 /* Unspecified */) { + var fileNames = compiler.fileNames(); + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = compiler.getDocument(fileNames[i]); + if (!document.isDeclareFile() && document.isExternalModule()) { + var errorSpan = document.externalModuleIndicatorSpan(); + this._diagnostic = new TypeScript.Diagnostic(document.fileName, document.lineMap(), errorSpan.start(), errorSpan.length(), TypeScript.DiagnosticCode.Cannot_compile_external_modules_unless_the_module_flag_is_provided); + + return; + } + } + } + + if (!settings.mapSourceFiles()) { + if (settings.mapRoot()) { + if (settings.sourceRoot()) { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Options_mapRoot_and_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option, null); + return; + } else { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option, null); + return; + } + } else if (settings.sourceRoot()) { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option, null); + return; + } + } + + this._sourceMapRootDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(settings.mapRoot())); + this._sourceRootDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(settings.sourceRoot())); + + if (settings.outFileOption() || settings.outDirOption() || settings.mapRoot() || settings.sourceRoot()) { + if (settings.outFileOption()) { + this._sharedOutputFile = TypeScript.switchToForwardSlashes(resolvePath(settings.outFileOption())); + } + + if (settings.outDirOption()) { + this._outputDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(resolvePath(settings.outDirOption()))); + } + + if (this._outputDirectory || this._sourceMapRootDirectory || this.sourceRootDirectory) { + this.determineCommonDirectoryPath(compiler); + } + } + } + EmitOptions.prototype.diagnostic = function () { + return this._diagnostic; + }; + + EmitOptions.prototype.commonDirectoryPath = function () { + return this._commonDirectoryPath; + }; + EmitOptions.prototype.sharedOutputFile = function () { + return this._sharedOutputFile; + }; + EmitOptions.prototype.sourceRootDirectory = function () { + return this._sourceRootDirectory; + }; + EmitOptions.prototype.sourceMapRootDirectory = function () { + return this._sourceMapRootDirectory; + }; + EmitOptions.prototype.outputDirectory = function () { + return this._outputDirectory; + }; + + EmitOptions.prototype.compilationSettings = function () { + return this._settings; + }; + + EmitOptions.prototype.determineCommonDirectoryPath = function (compiler) { + var commonComponents = []; + var commonComponentsLength = -1; + + var fileNames = compiler.fileNames(); + for (var i = 0, len = fileNames.length; i < len; i++) { + var fileName = fileNames[i]; + var document = compiler.getDocument(fileNames[i]); + var sourceUnit = document.sourceUnit(); + + if (!document.isDeclareFile()) { + 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) { + var isDynamicModuleCompilation = TypeScript.ArrayUtilities.any(fileNames, function (fileName) { + document = compiler.getDocument(fileName); + return !document.isDeclareFile() && document.isExternalModule(); + }); + + if (this._outputDirectory || this._sourceRootDirectory || (this._sourceMapRootDirectory && (!this._sharedOutputFile || isDynamicModuleCompilation))) { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Cannot_find_the_common_subdirectory_path_for_the_input_files, null); + return; + } + + return; + } + + break; + } + } + + if (!updatedPath && fileComponents.length < commonComponentsLength) { + commonComponentsLength = fileComponents.length; + } + } + } + } + + this._commonDirectoryPath = commonComponents.slice(0, commonComponentsLength).join("/") + "/"; + }; + return EmitOptions; + })(); + TypeScript.EmitOptions = EmitOptions; + + var Indenter = (function () { + function Indenter() { + this.indentAmt = 0; + } + 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; + }; + Indenter.indentStep = 4; + Indenter.indentStepString = " "; + Indenter.indentStrings = []; + return Indenter; + })(); + TypeScript.Indenter = Indenter; + + function lastParameterIsRest(parameterList) { + var parameters = parameterList.parameters; + return parameters.nonSeparatorCount() > 0 && parameters.nonSeparatorAt(parameters.nonSeparatorCount() - 1).dotDotDotToken !== null; + } + TypeScript.lastParameterIsRest = lastParameterIsRest; + + var Emitter = (function () { + function Emitter(emittingFileName, outfile, emitOptions, semanticInfoChain) { + this.emittingFileName = emittingFileName; + this.outfile = outfile; + this.emitOptions = emitOptions; + this.semanticInfoChain = semanticInfoChain; + this.globalThisCapturePrologueEmitted = false; + this.extendsPrologueEmitted = false; + this.thisClassNode = null; + this.inArrowFunction = false; + this.moduleName = ""; + this.emitState = new EmitState(); + this.indenter = new Indenter(); + this.sourceMapper = null; + this.captureThisStmtString = "var _this = this;"; + this.declStack = []; + this.exportAssignment = null; + this.inWithBlock = false; + this.document = null; + this.detachedCommentsElement = null; + } + Emitter.prototype.pushDecl = function (decl) { + if (decl) { + this.declStack[this.declStack.length] = decl; + } + }; + + Emitter.prototype.popDecl = function (decl) { + if (decl) { + this.declStack.length--; + } + }; + + Emitter.prototype.getEnclosingDecl = function () { + var declStackLen = this.declStack.length; + var enclosingDecl = declStackLen > 0 ? this.declStack[declStackLen - 1] : null; + return enclosingDecl; + }; + + Emitter.prototype.setExportAssignment = function (exportAssignment) { + this.exportAssignment = exportAssignment; + }; + + Emitter.prototype.getExportAssignment = function () { + return this.exportAssignment; + }; + + Emitter.prototype.setDocument = function (document) { + this.document = document; + }; + + Emitter.prototype.shouldEmitImportDeclaration = function (importDeclAST) { + var isExternalModuleReference = importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */; + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); + var isExported = TypeScript.hasFlag(importDecl.flags, 1 /* Exported */); + var isAmdCodeGen = this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */; + + if (isExternalModuleReference && !isExported && isAmdCodeGen) { + return false; + } + + var importSymbol = importDecl.getSymbol(); + if (importSymbol.isUsedAsValue()) { + return true; + } + + if (importDeclAST.moduleReference.kind() !== 245 /* ExternalModuleReference */) { + var canBeUsedExternally = isExported || importSymbol.typeUsedExternally() || importSymbol.isUsedInExportedAlias(); + if (!canBeUsedExternally && !this.document.isExternalModule()) { + canBeUsedExternally = TypeScript.hasFlag(importDecl.getParentDecl().kind, 1 /* Script */ | 32 /* DynamicModule */); + } + + if (canBeUsedExternally) { + if (importSymbol.getExportAssignedValueSymbol()) { + return true; + } + + var containerSymbol = importSymbol.getExportAssignedContainerSymbol(); + if (containerSymbol && containerSymbol.getInstanceSymbol()) { + return true; + } + } + } + + return false; + }; + + Emitter.prototype.emitImportDeclaration = function (importDeclAST) { + var isExternalModuleReference = importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */; + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); + var isExported = TypeScript.hasFlag(importDecl.flags, 1 /* Exported */); + var isAmdCodeGen = this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */; + + this.emitComments(importDeclAST, true); + + var importSymbol = importDecl.getSymbol(); + + var parentSymbol = importSymbol.getContainer(); + var parentKind = parentSymbol ? parentSymbol.kind : 0 /* None */; + var associatedParentSymbol = parentSymbol ? parentSymbol.getAssociatedContainerType() : null; + var associatedParentSymbolKind = associatedParentSymbol ? associatedParentSymbol.kind : 0 /* None */; + + var needsPropertyAssignment = false; + var usePropertyAssignmentInsteadOfVarDecl = false; + var moduleNamePrefix; + + if (isExported && (parentKind === 4 /* Container */ || parentKind === 32 /* DynamicModule */ || associatedParentSymbolKind === 4 /* Container */ || associatedParentSymbolKind === 32 /* DynamicModule */)) { + if (importSymbol.getExportAssignedTypeSymbol() || importSymbol.getExportAssignedContainerSymbol()) { + needsPropertyAssignment = true; + } else { + var valueSymbol = importSymbol.getExportAssignedValueSymbol(); + if (valueSymbol && (valueSymbol.kind === 65536 /* Method */ || valueSymbol.kind === 16384 /* Function */)) { + needsPropertyAssignment = true; + } else { + usePropertyAssignmentInsteadOfVarDecl = true; + } + } + + if (this.emitState.container === 2 /* DynamicModule */) { + moduleNamePrefix = "exports."; + } else { + moduleNamePrefix = this.moduleName + "."; + } + } + + if (isAmdCodeGen && isExternalModuleReference) { + needsPropertyAssignment = true; + } else { + this.recordSourceMappingStart(importDeclAST); + if (usePropertyAssignmentInsteadOfVarDecl) { + this.writeToOutput(moduleNamePrefix); + } else { + this.writeToOutput("var "); + } + this.writeToOutput(importDeclAST.identifier.text() + " = "); + var aliasAST = importDeclAST.moduleReference; + + if (isExternalModuleReference) { + this.writeToOutput("require(" + aliasAST.stringLiteral.text() + ")"); + } else { + this.emitJavascript(aliasAST.moduleName, false); + } + + this.recordSourceMappingEnd(importDeclAST); + this.writeToOutput(";"); + + if (needsPropertyAssignment) { + this.writeLineToOutput(""); + this.emitIndent(); + } + } + + if (needsPropertyAssignment) { + this.writeToOutputWithSourceMapRecord(moduleNamePrefix + importDeclAST.identifier.text() + " = " + importDeclAST.identifier.text(), importDeclAST); + this.writeToOutput(";"); + } + this.emitComments(importDeclAST, false); + }; + + Emitter.prototype.createSourceMapper = function (document, jsFileName, jsFile, sourceMapOut, resolvePath) { + this.sourceMapper = new TypeScript.SourceMapper(jsFile, sourceMapOut, document, jsFileName, this.emitOptions, resolvePath); + }; + + Emitter.prototype.setSourceMapperNewSourceFile = function (document) { + this.sourceMapper.setNewSourceFile(document, this.emitOptions); + }; + + Emitter.prototype.updateLineAndColumn = function (s) { + var lineNumbers = TypeScript.TextUtilities.parseLineStarts(s); + if (lineNumbers.length > 1) { + this.emitState.line += lineNumbers.length - 1; + this.emitState.column = s.length - lineNumbers[lineNumbers.length - 1]; + } else { + this.emitState.column += s.length; + } + }; + + Emitter.prototype.writeToOutputWithSourceMapRecord = function (s, astSpan) { + this.recordSourceMappingStart(astSpan); + this.writeToOutput(s); + this.recordSourceMappingEnd(astSpan); + }; + + Emitter.prototype.writeToOutput = function (s) { + this.outfile.Write(s); + this.updateLineAndColumn(s); + }; + + Emitter.prototype.writeLineToOutput = function (s, force) { + if (typeof force === "undefined") { force = false; } + if (!force && s === "" && this.emitState.column === 0) { + return; + } + + this.outfile.WriteLine(s); + this.updateLineAndColumn(s); + this.emitState.column = 0; + this.emitState.line++; + }; + + Emitter.prototype.writeCaptureThisStatement = function (ast) { + this.emitIndent(); + this.writeToOutputWithSourceMapRecord(this.captureThisStmtString, ast); + this.writeLineToOutput(""); + }; + + Emitter.prototype.setContainer = function (c) { + var temp = this.emitState.container; + this.emitState.container = c; + return temp; + }; + + Emitter.prototype.getIndentString = function () { + return this.indenter.getIndent(); + }; + + Emitter.prototype.emitIndent = function () { + this.writeToOutput(this.getIndentString()); + }; + + Emitter.prototype.emitComment = function (comment, trailing, first) { + if (this.emitOptions.compilationSettings().removeComments()) { + return; + } + + var text = getTrimmedTextLines(comment); + var emitColumn = this.emitState.column; + + if (emitColumn === 0) { + this.emitIndent(); + } else if (trailing && first) { + this.writeToOutput(" "); + } + + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + 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(""); + } else { + this.recordSourceMappingEnd(comment); + this.writeToOutput(" "); + return; + } + } else { + this.recordSourceMappingStart(comment); + this.writeToOutput(text[0]); + this.recordSourceMappingEnd(comment); + this.writeLineToOutput(""); + } + + if (!trailing && emitColumn !== 0) { + this.emitIndent(); + } + }; + + Emitter.prototype.emitComments = function (ast, pre, onlyPinnedOrTripleSlashComments) { + var _this = this; + if (typeof onlyPinnedOrTripleSlashComments === "undefined") { onlyPinnedOrTripleSlashComments = false; } + if (ast && ast.kind() !== 146 /* Block */) { + if (ast.parent.kind() === 219 /* SimpleArrowFunctionExpression */ || ast.parent.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { + return; + } + } + + if (pre) { + var preComments = ast.preComments(); + + if (preComments && ast === this.detachedCommentsElement) { + var detachedComments = this.getDetachedComments(ast); + preComments = preComments.slice(detachedComments.length); + this.detachedCommentsElement = null; + } + + if (preComments && onlyPinnedOrTripleSlashComments) { + preComments = TypeScript.ArrayUtilities.where(preComments, function (c) { + return _this.isPinnedOrTripleSlash(c); + }); + } + + this.emitCommentsArray(preComments, false); + } else { + this.emitCommentsArray(ast.postComments(), true); + } + }; + + Emitter.prototype.isPinnedOrTripleSlash = function (comment) { + var fullText = comment.fullText(); + if (fullText.match(TypeScript.tripleSlashReferenceRegExp)) { + return true; + } else { + return fullText.indexOf("/*!") === 0; + } + }; + + Emitter.prototype.emitCommentsArray = function (comments, trailing) { + if (!this.emitOptions.compilationSettings().removeComments() && comments) { + for (var i = 0, n = comments.length; i < n; i++) { + this.emitComment(comments[i], trailing, i === 0); + } + } + }; + + Emitter.prototype.emitObjectLiteralExpression = function (objectLiteral) { + this.recordSourceMappingStart(objectLiteral); + + this.writeToOutput("{"); + this.emitCommaSeparatedList(objectLiteral, objectLiteral.propertyAssignments, " ", true); + this.writeToOutput("}"); + + this.recordSourceMappingEnd(objectLiteral); + }; + + Emitter.prototype.emitArrayLiteralExpression = function (arrayLiteral) { + this.recordSourceMappingStart(arrayLiteral); + + this.writeToOutput("["); + this.emitCommaSeparatedList(arrayLiteral, arrayLiteral.expressions, "", true); + this.writeToOutput("]"); + + this.recordSourceMappingEnd(arrayLiteral); + }; + + Emitter.prototype.emitObjectCreationExpression = function (objectCreationExpression) { + this.recordSourceMappingStart(objectCreationExpression); + this.writeToOutput("new "); + var target = objectCreationExpression.expression; + + this.emit(target); + if (objectCreationExpression.argumentList) { + this.recordSourceMappingStart(objectCreationExpression.argumentList); + this.writeToOutput("("); + this.emitCommaSeparatedList(objectCreationExpression.argumentList, objectCreationExpression.argumentList.arguments, "", false); + this.writeToOutputWithSourceMapRecord(")", objectCreationExpression.argumentList.closeParenToken); + this.recordSourceMappingEnd(objectCreationExpression.argumentList); + } + + this.recordSourceMappingEnd(objectCreationExpression); + }; + + Emitter.prototype.getConstantDecl = function (dotExpr) { + var pullSymbol = this.semanticInfoChain.getSymbolForAST(dotExpr); + if (pullSymbol && pullSymbol.kind === 67108864 /* EnumMember */) { + var pullDecls = pullSymbol.getDeclarations(); + if (pullDecls.length === 1) { + var pullDecl = pullDecls[0]; + if (pullDecl.kind === 67108864 /* EnumMember */) { + return pullDecl; + } + } + } + + return null; + }; + + Emitter.prototype.tryEmitConstant = function (dotExpr) { + var propertyName = dotExpr.name; + var boundDecl = this.getConstantDecl(dotExpr); + if (boundDecl) { + var value = boundDecl.constantValue; + if (value !== null) { + this.recordSourceMappingStart(dotExpr); + this.writeToOutput(value.toString()); + var comment = " /* "; + comment += propertyName.text(); + comment += " */"; + this.writeToOutput(comment); + this.recordSourceMappingEnd(dotExpr); + return true; + } + } + + return false; + }; + + Emitter.prototype.emitInvocationExpression = function (callNode) { + this.recordSourceMappingStart(callNode); + var target = callNode.expression; + var args = callNode.argumentList.arguments; + + if (target.kind() === 212 /* MemberAccessExpression */ && target.expression.kind() === 50 /* SuperKeyword */) { + this.emit(target); + this.writeToOutput(".call"); + this.recordSourceMappingStart(args); + this.writeToOutput("("); + this.emitThis(); + if (args && args.nonSeparatorCount() > 0) { + this.writeToOutput(", "); + this.emitCommaSeparatedList(callNode.argumentList, args, "", false); + } + } else { + if (callNode.expression.kind() === 50 /* SuperKeyword */ && this.emitState.container === 4 /* Constructor */) { + this.writeToOutput("_super.call"); + } else { + this.emitJavascript(target, false); + } + this.recordSourceMappingStart(args); + this.writeToOutput("("); + if (callNode.expression.kind() === 50 /* SuperKeyword */ && this.emitState.container === 4 /* Constructor */) { + this.writeToOutput("this"); + if (args && args.nonSeparatorCount() > 0) { + this.writeToOutput(", "); + } + } + this.emitCommaSeparatedList(callNode.argumentList, args, "", false); + } + + this.writeToOutputWithSourceMapRecord(")", callNode.argumentList.closeParenToken); + this.recordSourceMappingEnd(args); + this.recordSourceMappingEnd(callNode); + }; + + Emitter.prototype.emitParameterList = function (list) { + this.writeToOutput("("); + this.emitCommentsArray(list.openParenTrailingComments, true); + this.emitFunctionParameters(TypeScript.ASTHelpers.parametersFromParameterList(list)); + this.writeToOutput(")"); + }; + + Emitter.prototype.emitFunctionParameters = function (parameters) { + var argsLen = 0; + + if (parameters) { + this.emitComments(parameters.ast, true); + + var tempContainer = this.setContainer(6 /* Args */); + argsLen = parameters.length; + var printLen = argsLen; + if (parameters.lastParameterIsRest()) { + printLen--; + } + for (var i = 0; i < printLen; i++) { + var arg = parameters.astAt(i); + this.emit(arg); + + if (i < (printLen - 1)) { + this.writeToOutput(", "); + } + } + this.setContainer(tempContainer); + + this.emitComments(parameters.ast, false); + } + }; + + Emitter.prototype.emitFunctionBodyStatements = function (name, funcDecl, parameterList, block, bodyExpression) { + this.writeLineToOutput(" {"); + if (name) { + this.recordSourceMappingNameStart(name); + } + + this.indenter.increaseIndent(); + + if (block) { + this.emitDetachedComments(block.statements); + } + + if (this.shouldCaptureThis(funcDecl)) { + this.writeCaptureThisStatement(funcDecl); + } + + if (parameterList) { + this.emitDefaultValueAssignments(parameterList); + this.emitRestParameterInitializer(parameterList); + } + + if (block) { + this.emitList(block.statements); + this.emitCommentsArray(block.closeBraceLeadingComments, false); + } else { + this.emitIndent(); + this.emitCommentsArray(bodyExpression.preComments(), false); + this.writeToOutput("return "); + this.emit(bodyExpression); + this.writeLineToOutput(";"); + this.emitCommentsArray(bodyExpression.postComments(), true); + } + + this.indenter.decreaseIndent(); + this.emitIndent(); + + if (block) { + this.writeToOutputWithSourceMapRecord("}", block.closeBraceToken); + } else { + this.writeToOutputWithSourceMapRecord("}", bodyExpression); + } + + if (name) { + this.recordSourceMappingNameEnd(); + } + }; + + Emitter.prototype.emitDefaultValueAssignments = function (parameters) { + var n = parameters.length; + if (parameters.lastParameterIsRest()) { + n--; + } + + for (var i = 0; i < n; i++) { + var arg = parameters.astAt(i); + var id = parameters.identifierAt(i); + var equalsValueClause = parameters.initializerAt(i); + if (equalsValueClause) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.writeToOutput("if (typeof " + id.text() + " === \"undefined\") { "); + this.writeToOutputWithSourceMapRecord(id.text(), id); + this.emitJavascript(equalsValueClause, false); + this.writeLineToOutput("; }"); + this.recordSourceMappingEnd(arg); + } + } + }; + + Emitter.prototype.emitRestParameterInitializer = function (parameters) { + if (parameters.lastParameterIsRest()) { + var n = parameters.length; + var lastArg = parameters.astAt(n - 1); + var id = parameters.identifierAt(n - 1); + this.emitIndent(); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var "); + this.writeToOutputWithSourceMapRecord(id.text(), id); + this.writeLineToOutput(" = [];"); + this.recordSourceMappingEnd(lastArg); + this.emitIndent(); + this.writeToOutput("for ("); + this.writeToOutputWithSourceMapRecord("var _i = 0;", lastArg); + this.writeToOutput(" "); + this.writeToOutputWithSourceMapRecord("_i < (arguments.length - " + (n - 1) + ")", lastArg); + this.writeToOutput("; "); + this.writeToOutputWithSourceMapRecord("_i++", lastArg); + this.writeLineToOutput(") {"); + this.indenter.increaseIndent(); + this.emitIndent(); + + this.writeToOutputWithSourceMapRecord(id.text() + "[_i] = arguments[_i + " + (n - 1) + "];", lastArg); + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + } + }; + + Emitter.prototype.getImportDecls = function (fileName) { + var topLevelDecl = this.semanticInfoChain.topLevelDecl(this.document.fileName); + var result = []; + + var dynamicModuleDecl = topLevelDecl.getChildDecls()[0]; + var queue = dynamicModuleDecl.getChildDecls(); + + for (var i = 0, n = queue.length; i < n; i++) { + var decl = queue[i]; + + if (decl.kind & 128 /* TypeAlias */) { + var importStatementAST = this.semanticInfoChain.getASTForDecl(decl); + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + var symbol = decl.getSymbol(); + var typeSymbol = symbol && symbol.type; + if (typeSymbol && typeSymbol !== this.semanticInfoChain.anyTypeSymbol && !typeSymbol.isError()) { + result.push(decl); + } + } + } + } + + return result; + }; + + Emitter.prototype.getModuleImportAndDependencyList = function (sourceUnit) { + var importList = ""; + var dependencyList = ""; + + var importDecls = this.getImportDecls(this.document.fileName); + + if (importDecls.length) { + for (var i = 0; i < importDecls.length; i++) { + var importStatementDecl = importDecls[i]; + var importStatementSymbol = importStatementDecl.getSymbol(); + var importStatementAST = this.semanticInfoChain.getASTForDecl(importStatementDecl); + + if (importStatementSymbol.isUsedAsValue()) { + if (i <= importDecls.length - 1) { + dependencyList += ", "; + importList += ", "; + } + + importList += importStatementDecl.name; + dependencyList += importStatementAST.moduleReference.stringLiteral.text(); + } + } + } + + var amdDependencies = this.document.amdDependencies(); + for (var i = 0; i < amdDependencies.length; i++) { + dependencyList += ", \"" + amdDependencies[i] + "\""; + } + + return { + importList: importList, + dependencyList: dependencyList + }; + }; + + Emitter.prototype.shouldCaptureThis = function (ast) { + if (ast.kind() === 120 /* SourceUnit */) { + var scriptDecl = this.semanticInfoChain.topLevelDecl(this.document.fileName); + return TypeScript.hasFlag(scriptDecl.flags, 262144 /* MustCaptureThis */); + } + + var decl = this.semanticInfoChain.getDeclForAST(ast); + if (decl) { + return TypeScript.hasFlag(decl.flags, 262144 /* MustCaptureThis */); + } + + return false; + }; + + Emitter.prototype.emitEnum = function (moduleDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(moduleDecl); + this.pushDecl(pullDecl); + + var svModuleName = this.moduleName; + this.moduleName = moduleDecl.identifier.text(); + + var temp = this.setContainer(1 /* Module */); + var isExported = TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */); + + if (!isExported) { + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("var "); + this.recordSourceMappingStart(moduleDecl.identifier); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.identifier); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(moduleDecl); + this.emitIndent(); + } + + this.writeToOutput("("); + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("function ("); + this.writeToOutputWithSourceMapRecord(this.moduleName, moduleDecl.identifier); + this.writeLineToOutput(") {"); + + this.recordSourceMappingNameStart(this.moduleName); + + this.indenter.increaseIndent(); + + if (this.shouldCaptureThis(moduleDecl)) { + this.writeCaptureThisStatement(moduleDecl); + } + + this.emitSeparatedList(moduleDecl.enumElements); + this.indenter.decreaseIndent(); + this.emitIndent(); + + var parentIsDynamic = temp === 2 /* DynamicModule */; + if (temp === 0 /* Prog */ && isExported) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); + } else if (isExported || temp === 0 /* Prog */) { + var dotMod = svModuleName !== "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); + } else if (!isExported && temp !== 0 /* Prog */) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); + } else { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")();"); + } + + this.recordSourceMappingEnd(moduleDecl); + if (temp !== 0 /* Prog */ && isExported) { + this.recordSourceMappingStart(moduleDecl); + if (parentIsDynamic) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); + } else { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); + } + this.recordSourceMappingEnd(moduleDecl); + } + + this.setContainer(temp); + this.moduleName = svModuleName; + + this.popDecl(pullDecl); + }; + + Emitter.prototype.getModuleDeclToVerifyChildNameCollision = function (moduleDecl, changeNameIfAnyDeclarationInContext) { + if (TypeScript.ArrayUtilities.contains(this.declStack, moduleDecl)) { + return moduleDecl; + } else if (changeNameIfAnyDeclarationInContext) { + var symbol = moduleDecl.getSymbol(); + if (symbol) { + var otherDecls = symbol.getDeclarations(); + for (var i = 0; i < otherDecls.length; i++) { + if (TypeScript.ArrayUtilities.contains(this.declStack, otherDecls[i])) { + return otherDecls[i]; + } + } + } + } + + return null; + }; + + Emitter.prototype.hasChildNameCollision = function (moduleName, parentDecl) { + var _this = this; + var childDecls = parentDecl.getChildDecls(); + return TypeScript.ArrayUtilities.any(childDecls, function (childDecl) { + var childAST = _this.semanticInfoChain.getASTForDecl(childDecl); + + if (childDecl.kind != 67108864 /* EnumMember */ && _this.shouldEmit(childAST)) { + if (childDecl.name === moduleName) { + if (parentDecl.kind != 8 /* Class */) { + return true; + } + + if (!(childDecl.kind == 65536 /* Method */ || childDecl.kind == 4096 /* Property */ || childDecl.kind == 524288 /* SetAccessor */ || childDecl.kind == 262144 /* GetAccessor */)) { + return true; + } + } + + if (_this.hasChildNameCollision(moduleName, childDecl)) { + return true; + } + } + return false; + }); + }; + + Emitter.prototype.getModuleName = function (moduleDecl, changeNameIfAnyDeclarationInContext) { + var moduleName = moduleDecl.name; + var moduleDisplayName = moduleDecl.getDisplayName(); + + moduleDecl = this.getModuleDeclToVerifyChildNameCollision(moduleDecl, changeNameIfAnyDeclarationInContext); + if (moduleDecl && moduleDecl.kind != 64 /* Enum */) { + while (this.hasChildNameCollision(moduleName, moduleDecl)) { + moduleName = "_" + moduleName; + moduleDisplayName = "_" + moduleDisplayName; + } + } + + return moduleDisplayName; + }; + + Emitter.prototype.emitModuleDeclarationWorker = function (moduleDecl) { + if (moduleDecl.stringLiteral) { + this.emitSingleModuleDeclaration(moduleDecl, moduleDecl.stringLiteral); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDecl.name); + this.emitSingleModuleDeclaration(moduleDecl, moduleNames[0]); + } + }; + + Emitter.prototype.emitSingleModuleDeclaration = function (moduleDecl, moduleName) { + var isLastName = TypeScript.ASTHelpers.isLastNameOfModule(moduleDecl, moduleName); + + if (isLastName) { + this.emitComments(moduleDecl, true); + } + + var pullDecl = this.semanticInfoChain.getDeclForAST(moduleName); + this.pushDecl(pullDecl); + + var svModuleName = this.moduleName; + + if (moduleDecl.stringLiteral) { + this.moduleName = moduleDecl.stringLiteral.valueText(); + if (TypeScript.isTSFile(this.moduleName)) { + this.moduleName = this.moduleName.substring(0, this.moduleName.length - ".ts".length); + } + } else { + this.moduleName = moduleName.text(); + } + + var temp = this.setContainer(1 /* Module */); + var isExported = TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */); + + if (!isExported) { + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("var "); + this.recordSourceMappingStart(moduleName); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleName); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(moduleDecl); + this.emitIndent(); + } + + this.writeToOutput("("); + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("function ("); + + this.moduleName = this.getModuleName(pullDecl); + this.writeToOutputWithSourceMapRecord(this.moduleName, moduleName); + this.writeLineToOutput(") {"); + + this.recordSourceMappingNameStart(moduleName.text()); + + this.indenter.increaseIndent(); + + if (this.shouldCaptureThis(moduleDecl)) { + this.writeCaptureThisStatement(moduleDecl); + } + + if (moduleName === moduleDecl.stringLiteral) { + this.emitList(moduleDecl.moduleElements); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDecl.name); + var nameIndex = moduleNames.indexOf(moduleName); + TypeScript.Debug.assert(nameIndex >= 0); + + if (isLastName) { + this.emitList(moduleDecl.moduleElements); + } else { + this.emitIndent(); + this.emitSingleModuleDeclaration(moduleDecl, moduleNames[nameIndex + 1]); + this.writeLineToOutput(""); + } + } + + this.moduleName = moduleName.text(); + this.indenter.decreaseIndent(); + this.emitIndent(); + + var parentIsDynamic = temp === 2 /* DynamicModule */; + this.recordSourceMappingStart(moduleDecl.endingToken); + if (temp === 0 /* Prog */ && isExported) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); + } else if (isExported || temp === 0 /* Prog */) { + var dotMod = svModuleName !== "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); + } else if (!isExported && temp !== 0 /* Prog */) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); + } else { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")();"); + } + + this.recordSourceMappingEnd(moduleDecl); + if (temp !== 0 /* Prog */ && isExported) { + this.recordSourceMappingStart(moduleDecl); + if (parentIsDynamic) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); + } else { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); + } + this.recordSourceMappingEnd(moduleDecl); + } + + this.setContainer(temp); + this.moduleName = svModuleName; + + this.popDecl(pullDecl); + + if (isLastName) { + this.emitComments(moduleDecl, false); + } + }; + + Emitter.prototype.emitEnumElement = function (varDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(varDecl); + TypeScript.Debug.assert(pullDecl && pullDecl.kind === 67108864 /* EnumMember */); + + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + var name = varDecl.propertyName.text(); + var quoted = TypeScript.isQuoted(name); + this.writeToOutput(this.moduleName); + this.writeToOutput('['); + this.writeToOutput(this.moduleName); + this.writeToOutput('['); + this.writeToOutput(quoted ? name : '"' + name + '"'); + this.writeToOutput(']'); + + if (varDecl.equalsValueClause) { + this.emit(varDecl.equalsValueClause); + } else if (pullDecl.constantValue !== null) { + this.writeToOutput(' = '); + this.writeToOutput(pullDecl.constantValue.toString()); + } else { + this.writeToOutput(' = null'); + } + + this.writeToOutput('] = '); + this.writeToOutput(quoted ? name : '"' + name + '"'); + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + this.writeToOutput(';'); + }; + + Emitter.prototype.emitElementAccessExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.emit(expression.expression); + this.writeToOutput("["); + this.emit(expression.argumentExpression); + this.writeToOutput("]"); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitSimpleArrowFunctionExpression = function (arrowFunction) { + this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromIdentifier(arrowFunction.identifier), arrowFunction.block, arrowFunction.expression); + }; + + Emitter.prototype.emitParenthesizedArrowFunctionExpression = function (arrowFunction) { + this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), arrowFunction.block, arrowFunction.expression); + }; + + Emitter.prototype.emitAnyArrowFunctionExpression = function (arrowFunction, funcName, parameters, block, expression) { + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = true; + + var temp = this.setContainer(5 /* Function */); + + this.recordSourceMappingStart(arrowFunction); + + var pullDecl = this.semanticInfoChain.getDeclForAST(arrowFunction); + this.pushDecl(pullDecl); + + this.emitComments(arrowFunction, true); + + this.recordSourceMappingStart(arrowFunction); + this.writeToOutput("function "); + this.writeToOutput("("); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(funcName, arrowFunction, parameters, block, expression); + + this.recordSourceMappingEnd(arrowFunction); + + this.recordSourceMappingEnd(arrowFunction); + + this.emitComments(arrowFunction, false); + + this.popDecl(pullDecl); + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + }; + + Emitter.prototype.emitConstructor = function (funcDecl) { + if (!funcDecl.block) { + return; + } + var temp = this.setContainer(4 /* Constructor */); + + this.recordSourceMappingStart(funcDecl); + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.emitComments(funcDecl, true); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + this.writeToOutput(this.thisClassNode.identifier.text()); + this.writeToOutput("("); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionParameters(parameters); + this.writeLineToOutput(") {"); + + this.recordSourceMappingNameStart("constructor"); + this.indenter.increaseIndent(); + + this.emitDefaultValueAssignments(parameters); + this.emitRestParameterInitializer(parameters); + + if (this.shouldCaptureThis(funcDecl)) { + this.writeCaptureThisStatement(funcDecl); + } + + this.emitConstructorStatements(funcDecl); + this.emitCommentsArray(funcDecl.block.closeBraceLeadingComments, false); + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("}", funcDecl.block.closeBraceToken); + + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.popDecl(pullDecl); + this.setContainer(temp); + }; + + Emitter.prototype.emitGetAccessor = function (accessor) { + this.recordSourceMappingStart(accessor); + this.writeToOutput("get "); + + var temp = this.setContainer(5 /* Function */); + + this.recordSourceMappingStart(accessor); + + var pullDecl = this.semanticInfoChain.getDeclForAST(accessor); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(accessor); + + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(accessor, this.semanticInfoChain); + var container = accessorSymbol.getContainer(); + var containerKind = container.kind; + + this.recordSourceMappingNameStart(accessor.propertyName.text()); + this.writeToOutput(accessor.propertyName.text()); + this.writeToOutput("("); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(null, accessor, TypeScript.ASTHelpers.parametersFromParameterList(accessor.parameterList), accessor.block, null); + + this.recordSourceMappingEnd(accessor); + + this.recordSourceMappingEnd(accessor); + + this.popDecl(pullDecl); + this.setContainer(temp); + this.recordSourceMappingEnd(accessor); + }; + + Emitter.prototype.emitSetAccessor = function (accessor) { + this.recordSourceMappingStart(accessor); + this.writeToOutput("set "); + + var temp = this.setContainer(5 /* Function */); + + this.recordSourceMappingStart(accessor); + + var pullDecl = this.semanticInfoChain.getDeclForAST(accessor); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(accessor); + + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(accessor, this.semanticInfoChain); + var container = accessorSymbol.getContainer(); + var containerKind = container.kind; + + this.recordSourceMappingNameStart(accessor.propertyName.text()); + this.writeToOutput(accessor.propertyName.text()); + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(accessor.parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(null, accessor, parameters, accessor.block, null); + + this.recordSourceMappingEnd(accessor); + + this.recordSourceMappingEnd(accessor); + + this.popDecl(pullDecl); + this.setContainer(temp); + this.recordSourceMappingEnd(accessor); + }; + + Emitter.prototype.emitFunctionExpression = function (funcDecl) { + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = false; + + var temp = this.setContainer(5 /* Function */); + + var funcName = funcDecl.identifier ? funcDecl.identifier.text() : null; + + this.recordSourceMappingStart(funcDecl); + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + if (funcDecl.identifier) { + this.recordSourceMappingStart(funcDecl.identifier); + this.writeToOutput(funcDecl.identifier.text()); + this.recordSourceMappingEnd(funcDecl.identifier); + } + + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(funcName, funcDecl, parameters, funcDecl.block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.popDecl(pullDecl); + + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + }; + + Emitter.prototype.emitFunction = function (funcDecl) { + if (funcDecl.block === null) { + return; + } + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = false; + + var temp = this.setContainer(5 /* Function */); + + var funcName = funcDecl.identifier.text(); + + this.recordSourceMappingStart(funcDecl); + + var printName = funcDecl.identifier !== null; + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.emitComments(funcDecl, true); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + if (printName) { + var id = funcDecl.identifier.text(); + if (id) { + if (funcDecl.identifier) { + this.recordSourceMappingStart(funcDecl.identifier); + } + this.writeToOutput(id); + if (funcDecl.identifier) { + this.recordSourceMappingEnd(funcDecl.identifier); + } + } + } + + this.emitParameterList(funcDecl.callSignature.parameterList); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionBodyStatements(funcDecl.identifier.text(), funcDecl, parameters, funcDecl.block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.popDecl(pullDecl); + + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + + if (funcDecl.block) { + var pullFunctionDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + if ((this.emitState.container === 1 /* Module */ || this.emitState.container === 2 /* DynamicModule */) && pullFunctionDecl && TypeScript.hasFlag(pullFunctionDecl.flags, 1 /* Exported */)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = this.emitState.container === 1 /* Module */ ? this.moduleName : "exports"; + this.recordSourceMappingStart(funcDecl); + this.writeToOutput(modName + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + }; + + Emitter.prototype.emitAmbientVarDecl = function (varDecl) { + this.recordSourceMappingStart(this.currentVariableDeclaration); + if (varDecl.equalsValueClause) { + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + this.writeToOutputWithSourceMapRecord(varDecl.propertyName.text(), varDecl.propertyName); + this.emitJavascript(varDecl.equalsValueClause, false); + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + } + }; + + Emitter.prototype.emitVarDeclVar = function () { + if (this.currentVariableDeclaration) { + this.writeToOutput("var "); + } + }; + + Emitter.prototype.emitVariableDeclaration = function (declaration) { + var varDecl = declaration.declarators.nonSeparatorAt(0); + + var symbol = this.semanticInfoChain.getSymbolForAST(varDecl); + + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentKind = parentSymbol ? parentSymbol.kind : 0 /* None */; + + this.emitComments(declaration, true); + + var pullVarDecl = this.semanticInfoChain.getDeclForAST(varDecl); + var isAmbientWithoutInit = pullVarDecl && TypeScript.hasFlag(pullVarDecl.flags, 8 /* Ambient */) && varDecl.equalsValueClause === null; + if (!isAmbientWithoutInit) { + var prevVariableDeclaration = this.currentVariableDeclaration; + this.currentVariableDeclaration = declaration; + + for (var i = 0, n = declaration.declarators.nonSeparatorCount(); i < n; i++) { + var declarator = declaration.declarators.nonSeparatorAt(i); + + if (i > 0) { + this.writeToOutput(", "); + } + + this.emit(declarator); + } + this.currentVariableDeclaration = prevVariableDeclaration; + + this.recordSourceMappingEnd(declaration); + } + + this.emitComments(declaration, false); + }; + + Emitter.prototype.emitMemberVariableDeclaration = function (varDecl) { + TypeScript.Debug.assert(!TypeScript.hasModifier(varDecl.modifiers, 16 /* Static */) && varDecl.variableDeclarator.equalsValueClause); + + var pullDecl = this.semanticInfoChain.getDeclForAST(varDecl); + this.pushDecl(pullDecl); + + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + + var varDeclName = varDecl.variableDeclarator.propertyName.text(); + var quotedOrNumber = TypeScript.isQuoted(varDeclName) || varDecl.variableDeclarator.propertyName.kind() !== 11 /* IdentifierName */; + + var symbol = this.semanticInfoChain.getSymbolForAST(varDecl); + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentDecl = pullDecl && pullDecl.getParentDecl(); + + if (quotedOrNumber) { + this.writeToOutput("this["); + } else { + this.writeToOutput("this."); + } + + this.writeToOutputWithSourceMapRecord(varDecl.variableDeclarator.propertyName.text(), varDecl.variableDeclarator.propertyName); + + if (quotedOrNumber) { + this.writeToOutput("]"); + } + + if (varDecl.variableDeclarator.equalsValueClause) { + var prevVariableDeclaration = this.currentVariableDeclaration; + this.emit(varDecl.variableDeclarator.equalsValueClause); + this.currentVariableDeclaration = prevVariableDeclaration; + } + + if (this.emitState.container !== 6 /* Args */) { + this.writeToOutput(";"); + } + + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitVariableDeclarator = function (varDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(varDecl); + this.pushDecl(pullDecl); + if (pullDecl && (pullDecl.flags & 8 /* Ambient */) === 8 /* Ambient */) { + this.emitAmbientVarDecl(varDecl); + } else { + this.emitComments(varDecl, true); + this.recordSourceMappingStart(this.currentVariableDeclaration); + this.recordSourceMappingStart(varDecl); + + var varDeclName = varDecl.propertyName.text(); + + var symbol = this.semanticInfoChain.getSymbolForAST(varDecl); + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentDecl = pullDecl && pullDecl.getParentDecl(); + var parentIsModule = parentDecl && (parentDecl.flags & 102400 /* SomeInitializedModule */); + + if (parentIsModule) { + if (!TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */)) { + this.emitVarDeclVar(); + } else { + if (this.emitState.container === 2 /* DynamicModule */) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(this.moduleName + "."); + } + } + } else { + this.emitVarDeclVar(); + } + + this.writeToOutputWithSourceMapRecord(varDecl.propertyName.text(), varDecl.propertyName); + + if (varDecl.equalsValueClause) { + var prevVariableDeclaration = this.currentVariableDeclaration; + this.emit(varDecl.equalsValueClause); + this.currentVariableDeclaration = prevVariableDeclaration; + } + + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + } + this.currentVariableDeclaration = undefined; + this.popDecl(pullDecl); + }; + + Emitter.prototype.symbolIsUsedInItsEnclosingContainer = function (symbol, dynamic) { + if (typeof dynamic === "undefined") { dynamic = false; } + var symDecls = symbol.getDeclarations(); + + if (symDecls.length) { + var enclosingDecl = this.getEnclosingDecl(); + if (enclosingDecl) { + var parentDecl = symDecls[0].getParentDecl(); + if (parentDecl) { + var symbolDeclarationEnclosingContainer = parentDecl; + var enclosingContainer = enclosingDecl; + + while (symbolDeclarationEnclosingContainer) { + if (symbolDeclarationEnclosingContainer.kind === (dynamic ? 32 /* DynamicModule */ : 4 /* Container */)) { + break; + } + symbolDeclarationEnclosingContainer = symbolDeclarationEnclosingContainer.getParentDecl(); + } + + if (symbolDeclarationEnclosingContainer) { + while (enclosingContainer) { + if (enclosingContainer.kind === (dynamic ? 32 /* DynamicModule */ : 4 /* Container */)) { + break; + } + + enclosingContainer = enclosingContainer.getParentDecl(); + } + } + + if (symbolDeclarationEnclosingContainer && enclosingContainer) { + var same = symbolDeclarationEnclosingContainer === enclosingContainer; + + if (!same && symbol.anyDeclHasFlag(32768 /* InitializedModule */)) { + same = symbolDeclarationEnclosingContainer === enclosingContainer.getParentDecl(); + } + + return same; + } + } + } + } + + return false; + }; + + Emitter.prototype.shouldQualifySymbolNameWithParentName = function (symbol) { + var enclosingContextDeclPath = this.declStack; + var symbolDeclarations = symbol.getDeclarations(); + for (var i = 0; i < symbolDeclarations.length; i++) { + var currentDecl = symbolDeclarations[i]; + var declParent = currentDecl.getParentDecl(); + + if (currentDecl.kind === 67108864 /* EnumMember */) { + return true; + } + + if (!TypeScript.hasFlag(currentDecl.flags, 1 /* Exported */)) { + return false; + } + + if (currentDecl.kind === 512 /* Variable */ && !TypeScript.hasFlag(currentDecl.flags, 118784 /* ImplicitVariable */)) { + return true; + } + + if (TypeScript.ArrayUtilities.contains(this.declStack, declParent)) { + return false; + } + } + + return true; + }; + + Emitter.prototype.getSymbolForEmit = function (ast) { + var pullSymbol = this.semanticInfoChain.getSymbolForAST(ast); + var pullSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(ast); + if (pullSymbol && pullSymbolAlias) { + var symbolToCompare = TypeScript.isTypesOnlyLocation(ast) ? pullSymbolAlias.getExportAssignedTypeSymbol() : pullSymbolAlias.getExportAssignedValueSymbol(); + + if (pullSymbol === symbolToCompare) { + pullSymbol = pullSymbolAlias; + pullSymbolAlias = null; + } + } + return { symbol: pullSymbol, aliasSymbol: pullSymbolAlias }; + }; + + Emitter.prototype.emitName = function (name, addThis) { + this.emitComments(name, true); + this.recordSourceMappingStart(name); + if (name.text().length > 0) { + var symbolForEmit = this.getSymbolForEmit(name); + var pullSymbol = symbolForEmit.symbol; + if (!pullSymbol) { + pullSymbol = this.semanticInfoChain.anyTypeSymbol; + } + var pullSymbolAlias = symbolForEmit.aliasSymbol; + var pullSymbolKind = pullSymbol.kind; + var isLocalAlias = pullSymbolAlias && (pullSymbolAlias.getDeclarations()[0].getParentDecl() === this.getEnclosingDecl()); + if (addThis && (this.emitState.container !== 6 /* Args */) && pullSymbol) { + var pullSymbolContainer = pullSymbol.getContainer(); + + if (pullSymbolContainer) { + var pullSymbolContainerKind = pullSymbolContainer.kind; + + if (TypeScript.PullHelpers.symbolIsModule(pullSymbolContainer) || pullSymbolContainerKind === 64 /* Enum */ || pullSymbolContainer.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */)) { + var needToEmitParentName = this.shouldQualifySymbolNameWithParentName(pullSymbol); + if (needToEmitParentName) { + var parentDecl = pullSymbol.getDeclarations()[0].getParentDecl(); + TypeScript.Debug.assert(parentDecl && !parentDecl.isRootDecl()); + this.writeToOutput(this.getModuleName(parentDecl, true) + "."); + } + } else if (pullSymbolContainerKind === 32 /* DynamicModule */ || pullSymbolContainer.anyDeclHasFlag(65536 /* InitializedDynamicModule */)) { + if (pullSymbolKind === 4096 /* Property */) { + this.writeToOutput("exports."); + } else if (pullSymbol.anyDeclHasFlag(1 /* Exported */) && !isLocalAlias && !pullSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */) && pullSymbol.kind !== 32768 /* ConstructorMethod */ && pullSymbol.kind !== 8 /* Class */ && pullSymbol.kind !== 64 /* Enum */) { + this.writeToOutput("exports."); + } + } + } + } + + this.writeToOutput(name.text()); + } + + this.recordSourceMappingEnd(name); + this.emitComments(name, false); + }; + + Emitter.prototype.recordSourceMappingNameStart = function (name) { + if (this.sourceMapper) { + var nameIndex = -1; + if (name) { + if (this.sourceMapper.currentNameIndex.length > 0) { + var parentNameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; + if (parentNameIndex !== -1) { + name = this.sourceMapper.names[parentNameIndex] + "." + name; + } + } + + var nameIndex = this.sourceMapper.names.length - 1; + for (nameIndex; nameIndex >= 0; nameIndex--) { + if (this.sourceMapper.names[nameIndex] === name) { + break; + } + } + + if (nameIndex === -1) { + nameIndex = this.sourceMapper.names.length; + this.sourceMapper.names.push(name); + } + } + this.sourceMapper.currentNameIndex.push(nameIndex); + } + }; + + Emitter.prototype.recordSourceMappingNameEnd = function () { + if (this.sourceMapper) { + this.sourceMapper.currentNameIndex.pop(); + } + }; + + Emitter.prototype.recordSourceMappingStart = function (ast) { + if (this.sourceMapper && TypeScript.ASTHelpers.isValidAstNode(ast)) { + var lineCol = { line: -1, character: -1 }; + var sourceMapping = new TypeScript.SourceMapping(); + sourceMapping.start.emittedColumn = this.emitState.column; + sourceMapping.start.emittedLine = this.emitState.line; + + var lineMap = this.document.lineMap(); + lineMap.fillLineAndCharacterFromPosition(ast.start(), lineCol); + sourceMapping.start.sourceColumn = lineCol.character; + sourceMapping.start.sourceLine = lineCol.line + 1; + lineMap.fillLineAndCharacterFromPosition(ast.end(), lineCol); + sourceMapping.end.sourceColumn = lineCol.character; + sourceMapping.end.sourceLine = lineCol.line + 1; + + TypeScript.Debug.assert(!isNaN(sourceMapping.start.emittedColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.start.emittedLine)); + TypeScript.Debug.assert(!isNaN(sourceMapping.start.sourceColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.start.sourceLine)); + TypeScript.Debug.assert(!isNaN(sourceMapping.end.sourceColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.end.sourceLine)); + + 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); + this.sourceMapper.increaseMappingLevel(ast); + } + }; + + Emitter.prototype.recordSourceMappingEnd = function (ast) { + if (this.sourceMapper && TypeScript.ASTHelpers.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; + + TypeScript.Debug.assert(!isNaN(sourceMapping.end.emittedColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.end.emittedLine)); + + this.sourceMapper.decreaseMappingLevel(ast); + } + }; + + Emitter.prototype.getOutputFiles = function () { + var result = []; + if (this.sourceMapper !== null) { + this.sourceMapper.emitSourceMapping(); + result.push(this.sourceMapper.getOutputFile()); + } + + result.push(this.outfile.getOutputFile()); + return result; + }; + + Emitter.prototype.emitParameterPropertyAndMemberVariableAssignments = function () { + var constructorDecl = getLastConstructor(this.thisClassNode); + + if (constructorDecl) { + for (var i = 0, n = constructorDecl.callSignature.parameterList.parameters.nonSeparatorCount(); i < n; i++) { + var parameter = constructorDecl.callSignature.parameterList.parameters.nonSeparatorAt(i); + var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter); + if (TypeScript.hasFlag(parameterDecl.flags, 8388608 /* PropertyParameter */)) { + this.emitIndent(); + this.recordSourceMappingStart(parameter); + this.writeToOutputWithSourceMapRecord("this." + parameter.identifier.text(), parameter.identifier); + this.writeToOutput(" = "); + this.writeToOutputWithSourceMapRecord(parameter.identifier.text(), parameter.identifier); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(parameter); + } + } + } + + for (var i = 0, n = this.thisClassNode.classElements.childCount(); i < n; i++) { + if (this.thisClassNode.classElements.childAt(i).kind() === 136 /* MemberVariableDeclaration */) { + var varDecl = this.thisClassNode.classElements.childAt(i); + if (!TypeScript.hasModifier(varDecl.modifiers, 16 /* Static */) && varDecl.variableDeclarator.equalsValueClause) { + this.emitIndent(); + this.emitMemberVariableDeclaration(varDecl); + this.writeLineToOutput(""); + } + } + } + }; + + Emitter.prototype.isOnSameLine = function (pos1, pos2) { + var lineMap = this.document.lineMap(); + return lineMap.getLineNumberFromPosition(pos1) === lineMap.getLineNumberFromPosition(pos2); + }; + + Emitter.prototype.emitCommaSeparatedList = function (parent, list, buffer, preserveNewLines) { + if (list === null || list.nonSeparatorCount() === 0) { + return; + } + + var startLine = preserveNewLines && !this.isOnSameLine(parent.end(), list.nonSeparatorAt(0).end()); + + if (preserveNewLines) { + this.indenter.increaseIndent(); + } + + if (startLine) { + this.writeLineToOutput(""); + } else { + this.writeToOutput(buffer); + } + + for (var i = 0, n = list.nonSeparatorCount(); i < n; i++) { + var emitNode = list.nonSeparatorAt(i); + + this.emitJavascript(emitNode, startLine); + + if (i < (n - 1)) { + startLine = preserveNewLines && !this.isOnSameLine(emitNode.end(), list.nonSeparatorAt(i + 1).start()); + if (startLine) { + this.writeLineToOutput(","); + } else { + this.writeToOutput(", "); + } + } + } + + if (preserveNewLines) { + this.indenter.decreaseIndent(); + } + + if (preserveNewLines && !this.isOnSameLine(parent.end(), list.nonSeparatorAt(list.nonSeparatorCount() - 1).end())) { + this.writeLineToOutput(""); + this.emitIndent(); + } else { + this.writeToOutput(buffer); + } + }; + + Emitter.prototype.emitList = function (list, useNewLineSeparator, startInclusive, endExclusive) { + if (typeof useNewLineSeparator === "undefined") { useNewLineSeparator = true; } + if (typeof startInclusive === "undefined") { startInclusive = 0; } + if (typeof endExclusive === "undefined") { endExclusive = list.childCount(); } + if (list === null) { + return; + } + + this.emitComments(list, true); + var lastEmittedNode = null; + + for (var i = startInclusive; i < endExclusive; i++) { + var node = list.childAt(i); + + if (this.shouldEmit(node)) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + if (useNewLineSeparator) { + this.writeLineToOutput(""); + } + + lastEmittedNode = node; + } + } + + this.emitComments(list, false); + }; + + Emitter.prototype.emitSeparatedList = function (list, useNewLineSeparator, startInclusive, endExclusive) { + if (typeof useNewLineSeparator === "undefined") { useNewLineSeparator = true; } + if (typeof startInclusive === "undefined") { startInclusive = 0; } + if (typeof endExclusive === "undefined") { endExclusive = list.nonSeparatorCount(); } + if (list === null) { + return; + } + + this.emitComments(list, true); + var lastEmittedNode = null; + + for (var i = startInclusive; i < endExclusive; i++) { + var node = list.nonSeparatorAt(i); + + if (this.shouldEmit(node)) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + if (useNewLineSeparator) { + this.writeLineToOutput(""); + } + + lastEmittedNode = node; + } + } + + this.emitComments(list, false); + }; + + Emitter.prototype.isDirectivePrologueElement = function (node) { + if (node.kind() === 149 /* ExpressionStatement */) { + var exprStatement = node; + return exprStatement.expression.kind() === 14 /* StringLiteral */; + } + + return false; + }; + + Emitter.prototype.emitSpaceBetweenConstructs = function (node1, node2) { + if (node1 === null || node2 === null) { + return; + } + + if (node1.start() === -1 || node1.end() === -1 || node2.start() === -1 || node2.end() === -1) { + return; + } + + var lineMap = this.document.lineMap(); + var node1EndLine = lineMap.getLineNumberFromPosition(node1.end()); + var node2StartLine = lineMap.getLineNumberFromPosition(node2.start()); + + if ((node2StartLine - node1EndLine) > 1) { + this.writeLineToOutput("", true); + } + }; + + Emitter.prototype.getDetachedComments = function (element) { + var preComments = element.preComments(); + if (preComments) { + var lineMap = this.document.lineMap(); + + var detachedComments = []; + var lastComment = null; + + for (var i = 0, n = preComments.length; i < n; i++) { + var comment = preComments[i]; + + if (lastComment) { + var lastCommentLine = lineMap.getLineNumberFromPosition(lastComment.end()); + var commentLine = lineMap.getLineNumberFromPosition(comment.start()); + + if (commentLine >= lastCommentLine + 2) { + return detachedComments; + } + } + + detachedComments.push(comment); + lastComment = comment; + } + + var lastCommentLine = lineMap.getLineNumberFromPosition(TypeScript.ArrayUtilities.last(detachedComments).end()); + var astLine = lineMap.getLineNumberFromPosition(element.start()); + if (astLine >= lastCommentLine + 2) { + return detachedComments; + } + } + + return []; + }; + + Emitter.prototype.emitPossibleCopyrightHeaders = function (script) { + this.emitDetachedComments(script.moduleElements); + }; + + Emitter.prototype.emitDetachedComments = function (list) { + if (list.childCount() > 0) { + var firstElement = list.childAt(0); + + this.detachedCommentsElement = firstElement; + this.emitCommentsArray(this.getDetachedComments(this.detachedCommentsElement), false); + } + }; + + Emitter.prototype.emitScriptElements = function (sourceUnit) { + var list = sourceUnit.moduleElements; + + this.emitPossibleCopyrightHeaders(sourceUnit); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var node = list.childAt(i); + + if (!this.isDirectivePrologueElement(node)) { + break; + } + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + } + + this.emitPrologue(sourceUnit); + + var isExternalModule = this.document.isExternalModule(); + var isNonElidedExternalModule = isExternalModule && !TypeScript.ASTHelpers.scriptIsElided(sourceUnit); + if (isNonElidedExternalModule) { + this.recordSourceMappingStart(sourceUnit); + + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + var dependencyList = "[\"require\", \"exports\""; + var importList = "require, exports"; + + var importAndDependencyList = this.getModuleImportAndDependencyList(sourceUnit); + importList += importAndDependencyList.importList; + dependencyList += importAndDependencyList.dependencyList + "]"; + + this.writeLineToOutput("define(" + dependencyList + "," + " function(" + importList + ") {"); + } + } + + if (isExternalModule) { + var temp = this.setContainer(2 /* DynamicModule */); + + var svModuleName = this.moduleName; + this.moduleName = sourceUnit.fileName(); + if (TypeScript.isTSFile(this.moduleName)) { + this.moduleName = this.moduleName.substring(0, this.moduleName.length - ".ts".length); + } + + this.setExportAssignment(null); + + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + this.indenter.increaseIndent(); + } + + var externalModule = this.semanticInfoChain.getDeclForAST(this.document.sourceUnit()); + + if (TypeScript.hasFlag(externalModule.flags, 262144 /* MustCaptureThis */)) { + this.writeCaptureThisStatement(sourceUnit); + } + + this.pushDecl(externalModule); + } + + this.emitList(list, true, i, n); + + if (isExternalModule) { + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + this.indenter.decreaseIndent(); + } + + if (isNonElidedExternalModule) { + var exportAssignment = this.getExportAssignment(); + var exportAssignmentIdentifierText = exportAssignment ? exportAssignment.identifier.text() : null; + var exportAssignmentValueSymbol = externalModule.getSymbol().getExportAssignedValueSymbol(); + + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + if (exportAssignmentIdentifierText && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { + this.indenter.increaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("return " + exportAssignmentIdentifierText, exportAssignment); + this.writeLineToOutput(";"); + this.indenter.decreaseIndent(); + } + this.writeToOutput("});"); + } else if (exportAssignmentIdentifierText && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("module.exports = " + exportAssignmentIdentifierText, exportAssignment); + this.writeToOutput(";"); + } + + this.recordSourceMappingEnd(sourceUnit); + this.writeLineToOutput(""); + } + + this.setContainer(temp); + this.moduleName = svModuleName; + this.popDecl(externalModule); + } + }; + + Emitter.prototype.emitConstructorStatements = function (funcDecl) { + var list = funcDecl.block.statements; + + if (list === null) { + return; + } + + this.emitComments(list, true); + + var emitPropertyAssignmentsAfterSuperCall = TypeScript.ASTHelpers.getExtendsHeritageClause(this.thisClassNode.heritageClauses) !== null; + var propertyAssignmentIndex = emitPropertyAssignmentsAfterSuperCall ? 1 : 0; + var lastEmittedNode = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + if (i === propertyAssignmentIndex) { + this.emitParameterPropertyAndMemberVariableAssignments(); + } + + var node = list.childAt(i); + + if (this.shouldEmit(node)) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + + lastEmittedNode = node; + } + } + + if (i === propertyAssignmentIndex) { + this.emitParameterPropertyAndMemberVariableAssignments(); + } + + this.emitComments(list, false); + }; + + Emitter.prototype.emitJavascript = function (ast, startLine) { + if (ast === null) { + return; + } + + if (startLine && this.indenter.indentAmt > 0) { + this.emitIndent(); + } + + this.emit(ast); + }; + + Emitter.prototype.emitAccessorMemberDeclaration = function (funcDecl, name, className, isProto) { + if (funcDecl.kind() !== 139 /* GetAccessor */) { + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain); + if (accessorSymbol.getGetter()) { + return; + } + } + + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + + this.writeToOutput("Object.defineProperty(" + className); + if (isProto) { + this.writeToOutput(".prototype, "); + } else { + this.writeToOutput(", "); + } + + var functionName = name.text(); + if (TypeScript.isQuoted(functionName)) { + this.writeToOutput(functionName); + } else { + this.writeToOutput('"' + functionName + '"'); + } + + this.writeLineToOutput(", {"); + + this.indenter.increaseIndent(); + + var accessors = TypeScript.PullHelpers.getGetterAndSetterFunction(funcDecl, this.semanticInfoChain); + if (accessors.getter) { + this.emitIndent(); + this.recordSourceMappingStart(accessors.getter); + this.emitComments(accessors.getter, true); + this.writeToOutput("get: "); + this.emitAccessorBody(accessors.getter, accessors.getter.parameterList, accessors.getter.block); + this.writeLineToOutput(","); + } + + if (accessors.setter) { + this.emitIndent(); + this.recordSourceMappingStart(accessors.setter); + this.emitComments(accessors.setter, true); + this.writeToOutput("set: "); + this.emitAccessorBody(accessors.setter, accessors.setter.parameterList, accessors.setter.block); + this.writeLineToOutput(","); + } + + this.emitIndent(); + this.writeLineToOutput("enumerable: true,"); + this.emitIndent(); + this.writeLineToOutput("configurable: true"); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("});"); + this.recordSourceMappingEnd(funcDecl); + }; + + Emitter.prototype.emitAccessorBody = function (funcDecl, parameterList, block) { + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(null, funcDecl, parameters, block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitClass = function (classDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(classDecl); + this.pushDecl(pullDecl); + + var svClassNode = this.thisClassNode; + this.thisClassNode = classDecl; + var className = classDecl.identifier.text(); + this.emitComments(classDecl, true); + var temp = this.setContainer(3 /* Class */); + + this.recordSourceMappingStart(classDecl); + this.writeToOutput("var " + className); + + var hasBaseClass = TypeScript.ASTHelpers.getExtendsHeritageClause(classDecl.heritageClauses) !== null; + var baseTypeReference = null; + var varDecl = null; + + if (hasBaseClass) { + this.writeLineToOutput(" = (function (_super) {"); + } else { + this.writeLineToOutput(" = (function () {"); + } + + this.recordSourceMappingNameStart(className); + this.indenter.increaseIndent(); + + if (hasBaseClass) { + baseTypeReference = TypeScript.ASTHelpers.getExtendsHeritageClause(classDecl.heritageClauses).typeNames.nonSeparatorAt(0); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("__extends(" + className + ", _super)", baseTypeReference); + this.writeLineToOutput(";"); + } + + this.emitIndent(); + + var constrDecl = getLastConstructor(classDecl); + + if (constrDecl) { + this.emit(constrDecl); + this.writeLineToOutput(""); + } else { + this.recordSourceMappingStart(classDecl); + + this.indenter.increaseIndent(); + this.writeLineToOutput("function " + classDecl.identifier.text() + "() {"); + this.recordSourceMappingNameStart("constructor"); + if (hasBaseClass) { + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("_super.apply(this, arguments)", baseTypeReference); + this.writeLineToOutput(";"); + } + + if (this.shouldCaptureThis(classDecl)) { + this.writeCaptureThisStatement(classDecl); + } + + this.emitParameterPropertyAndMemberVariableAssignments(); + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("}", classDecl.closeBraceToken); + this.writeLineToOutput(""); + + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl); + } + + this.emitClassMembers(classDecl); + + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("return " + className + ";", classDecl.closeBraceToken); + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("}", classDecl.closeBraceToken); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingStart(classDecl); + this.writeToOutput(")("); + if (hasBaseClass) { + this.emitJavascript(baseTypeReference, false); + } + this.writeToOutput(");"); + this.recordSourceMappingEnd(classDecl); + + if ((temp === 1 /* Module */ || temp === 2 /* DynamicModule */) && TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = temp === 1 /* Module */ ? this.moduleName : "exports"; + this.writeToOutputWithSourceMapRecord(modName + "." + className + " = " + className + ";", classDecl); + } + + this.recordSourceMappingEnd(classDecl); + this.emitComments(classDecl, false); + this.setContainer(temp); + this.thisClassNode = svClassNode; + + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitClassMembers = function (classDecl) { + var lastEmittedMember = null; + + for (var i = 0, n = classDecl.classElements.childCount(); i < n; i++) { + var memberDecl = classDecl.classElements.childAt(i); + + if (memberDecl.kind() === 139 /* GetAccessor */) { + this.emitSpaceBetweenConstructs(lastEmittedMember, memberDecl); + var getter = memberDecl; + this.emitAccessorMemberDeclaration(getter, getter.propertyName, classDecl.identifier.text(), !TypeScript.hasModifier(getter.modifiers, 16 /* Static */)); + lastEmittedMember = memberDecl; + } else if (memberDecl.kind() === 140 /* SetAccessor */) { + this.emitSpaceBetweenConstructs(lastEmittedMember, memberDecl); + var setter = memberDecl; + this.emitAccessorMemberDeclaration(setter, setter.propertyName, classDecl.identifier.text(), !TypeScript.hasModifier(setter.modifiers, 16 /* Static */)); + lastEmittedMember = memberDecl; + } else if (memberDecl.kind() === 135 /* MemberFunctionDeclaration */) { + var memberFunction = memberDecl; + + if (memberFunction.block) { + this.emitSpaceBetweenConstructs(lastEmittedMember, memberDecl); + + this.emitClassMemberFunctionDeclaration(classDecl, memberFunction); + lastEmittedMember = memberDecl; + } + } + } + + for (var i = 0, n = classDecl.classElements.childCount(); i < n; i++) { + var memberDecl = classDecl.classElements.childAt(i); + + if (memberDecl.kind() === 136 /* MemberVariableDeclaration */) { + var varDecl = memberDecl; + + if (TypeScript.hasModifier(varDecl.modifiers, 16 /* Static */) && varDecl.variableDeclarator.equalsValueClause) { + this.emitSpaceBetweenConstructs(lastEmittedMember, varDecl); + + this.emitIndent(); + this.recordSourceMappingStart(varDecl); + + var varDeclName = varDecl.variableDeclarator.propertyName.text(); + if (TypeScript.isQuoted(varDeclName) || varDecl.variableDeclarator.propertyName.kind() !== 11 /* IdentifierName */) { + this.writeToOutput(classDecl.identifier.text() + "[" + varDeclName + "]"); + } else { + this.writeToOutput(classDecl.identifier.text() + "." + varDeclName); + } + + this.emit(varDecl.variableDeclarator.equalsValueClause); + + this.recordSourceMappingEnd(varDecl); + this.writeLineToOutput(";"); + + lastEmittedMember = varDecl; + } + } + } + }; + + Emitter.prototype.emitClassMemberFunctionDeclaration = function (classDecl, funcDecl) { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.emitComments(funcDecl, true); + var functionName = funcDecl.propertyName.text(); + + this.writeToOutput(classDecl.identifier.text()); + + if (!TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */)) { + this.writeToOutput(".prototype"); + } + + if (TypeScript.isQuoted(functionName) || funcDecl.propertyName.kind() !== 11 /* IdentifierName */) { + this.writeToOutput("[" + functionName + "] = "); + } else { + this.writeToOutput("." + functionName + " = "); + } + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + this.emitParameterList(funcDecl.callSignature.parameterList); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionBodyStatements(funcDecl.propertyName.text(), funcDecl, parameters, funcDecl.block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.recordSourceMappingEnd(funcDecl); + this.popDecl(pullDecl); + + this.writeLineToOutput(";"); + }; + + Emitter.prototype.requiresExtendsBlock = function (moduleElements) { + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var moduleElement = moduleElements.childAt(i); + + if (moduleElement.kind() === 130 /* ModuleDeclaration */) { + var moduleAST = moduleElement; + + if (!TypeScript.hasModifier(moduleAST.modifiers, 8 /* Ambient */) && this.requiresExtendsBlock(moduleAST.moduleElements)) { + return true; + } + } else if (moduleElement.kind() === 131 /* ClassDeclaration */) { + var classDeclaration = moduleElement; + + if (!TypeScript.hasModifier(classDeclaration.modifiers, 8 /* Ambient */) && TypeScript.ASTHelpers.getExtendsHeritageClause(classDeclaration.heritageClauses) !== null) { + return true; + } + } + } + + return false; + }; + + Emitter.prototype.emitPrologue = function (sourceUnit) { + if (!this.extendsPrologueEmitted) { + if (this.requiresExtendsBlock(sourceUnit.moduleElements)) { + this.extendsPrologueEmitted = true; + this.writeLineToOutput("var __extends = this.__extends || function (d, b) {"); + this.writeLineToOutput(" for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];"); + this.writeLineToOutput(" function __() { this.constructor = d; }"); + this.writeLineToOutput(" __.prototype = b.prototype;"); + this.writeLineToOutput(" d.prototype = new __();"); + this.writeLineToOutput("};"); + } + } + + if (!this.globalThisCapturePrologueEmitted) { + if (this.shouldCaptureThis(sourceUnit)) { + this.globalThisCapturePrologueEmitted = true; + this.writeLineToOutput(this.captureThisStmtString); + } + } + }; + + Emitter.prototype.emitThis = function () { + if (!this.inWithBlock && this.inArrowFunction) { + this.writeToOutput("_this"); + } else { + this.writeToOutput("this"); + } + }; + + Emitter.prototype.emitBlockOrStatement = function (node) { + if (node.kind() === 146 /* Block */) { + this.emit(node); + } else { + this.writeLineToOutput(""); + this.indenter.increaseIndent(); + this.emitJavascript(node, true); + this.indenter.decreaseIndent(); + } + }; + + Emitter.prototype.emitLiteralExpression = function (expression) { + switch (expression.kind()) { + case 32 /* NullKeyword */: + this.writeToOutputWithSourceMapRecord("null", expression); + break; + case 24 /* FalseKeyword */: + this.writeToOutputWithSourceMapRecord("false", expression); + break; + case 37 /* TrueKeyword */: + this.writeToOutputWithSourceMapRecord("true", expression); + break; + default: + throw TypeScript.Errors.abstract(); + } + }; + + Emitter.prototype.emitThisExpression = function (expression) { + if (!this.inWithBlock && this.inArrowFunction) { + this.writeToOutputWithSourceMapRecord("_this", expression); + } else { + this.writeToOutputWithSourceMapRecord("this", expression); + } + }; + + Emitter.prototype.emitSuperExpression = function (expression) { + this.writeToOutputWithSourceMapRecord("_super.prototype", expression); + }; + + Emitter.prototype.emitParenthesizedExpression = function (parenthesizedExpression) { + var omitParentheses = false; + + if (parenthesizedExpression.expression.kind() === 220 /* CastExpression */ && parenthesizedExpression.openParenTrailingComments === null) { + var castedExpression = parenthesizedExpression.expression.expression; + + while (castedExpression.kind() == 220 /* CastExpression */) { + castedExpression = castedExpression.expression; + } + + switch (castedExpression.kind()) { + case 217 /* ParenthesizedExpression */: + case 11 /* IdentifierName */: + case 32 /* NullKeyword */: + case 35 /* ThisKeyword */: + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + case 12 /* RegularExpressionLiteral */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + case 214 /* ArrayLiteralExpression */: + case 215 /* ObjectLiteralExpression */: + case 212 /* MemberAccessExpression */: + case 221 /* ElementAccessExpression */: + omitParentheses = true; + break; + + case 213 /* InvocationExpression */: + if (parenthesizedExpression.parent.kind() !== 216 /* ObjectCreationExpression */) { + omitParentheses = true; + } + + break; + } + } + + if (omitParentheses) { + this.emit(parenthesizedExpression.expression); + } else { + this.recordSourceMappingStart(parenthesizedExpression); + this.writeToOutput("("); + this.emitCommentsArray(parenthesizedExpression.openParenTrailingComments, false); + this.emit(parenthesizedExpression.expression); + this.writeToOutput(")"); + this.recordSourceMappingEnd(parenthesizedExpression); + } + }; + + Emitter.prototype.emitCastExpression = function (expression) { + this.emit(expression.expression); + }; + + Emitter.prototype.emitPrefixUnaryExpression = function (expression) { + var nodeType = expression.kind(); + + this.recordSourceMappingStart(expression); + switch (nodeType) { + case 167 /* LogicalNotExpression */: + this.writeToOutput("!"); + this.emit(expression.operand); + break; + case 166 /* BitwiseNotExpression */: + this.writeToOutput("~"); + this.emit(expression.operand); + break; + case 165 /* NegateExpression */: + this.writeToOutput("-"); + if (expression.operand.kind() === 165 /* NegateExpression */ || expression.operand.kind() === 169 /* PreDecrementExpression */) { + this.writeToOutput(" "); + } + this.emit(expression.operand); + break; + case 164 /* PlusExpression */: + this.writeToOutput("+"); + if (expression.operand.kind() === 164 /* PlusExpression */ || expression.operand.kind() === 168 /* PreIncrementExpression */) { + this.writeToOutput(" "); + } + this.emit(expression.operand); + break; + case 168 /* PreIncrementExpression */: + this.writeToOutput("++"); + this.emit(expression.operand); + break; + case 169 /* PreDecrementExpression */: + this.writeToOutput("--"); + this.emit(expression.operand); + break; + default: + throw TypeScript.Errors.abstract(); + } + + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitPostfixUnaryExpression = function (expression) { + var nodeType = expression.kind(); + + this.recordSourceMappingStart(expression); + switch (nodeType) { + case 210 /* PostIncrementExpression */: + this.emit(expression.operand); + this.writeToOutput("++"); + break; + case 211 /* PostDecrementExpression */: + this.emit(expression.operand); + this.writeToOutput("--"); + break; + default: + throw TypeScript.Errors.abstract(); + } + + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitTypeOfExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.writeToOutput("typeof "); + this.emit(expression.expression); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitDeleteExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.writeToOutput("delete "); + this.emit(expression.expression); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitVoidExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.writeToOutput("void "); + this.emit(expression.expression); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.canEmitDottedNameMemberAccessExpression = function (expression) { + var memberExpressionNodeType = expression.expression.kind(); + + if (memberExpressionNodeType === 11 /* IdentifierName */ || memberExpressionNodeType == 212 /* MemberAccessExpression */) { + var memberAccessSymbol = this.getSymbolForEmit(expression).symbol; + var memberAccessExpressionSymbol = this.getSymbolForEmit(expression.expression).symbol; + if (memberAccessSymbol && memberAccessExpressionSymbol && !this.semanticInfoChain.getAliasSymbolForAST(expression.expression) && (TypeScript.PullHelpers.symbolIsModule(memberAccessExpressionSymbol) || memberAccessExpressionSymbol.kind === 64 /* Enum */ || memberAccessExpressionSymbol.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */))) { + var memberAccessSymbolKind = memberAccessSymbol.kind; + if (memberAccessSymbolKind === 4096 /* Property */ || memberAccessSymbolKind === 67108864 /* EnumMember */ || (memberAccessSymbol.anyDeclHasFlag(1 /* Exported */) && memberAccessSymbolKind === 512 /* Variable */ && !memberAccessSymbol.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */)) || ((memberAccessSymbol.anyDeclHasFlag(1 /* Exported */) && !this.symbolIsUsedInItsEnclosingContainer(memberAccessSymbol)))) { + if (memberExpressionNodeType === 212 /* MemberAccessExpression */) { + return this.canEmitDottedNameMemberAccessExpression(expression.expression); + } + + return true; + } + } + } + + return false; + }; + + Emitter.prototype.emitDottedNameMemberAccessExpression = function (expression) { + this.recordSourceMappingStart(expression); + if (expression.expression.kind() === 212 /* MemberAccessExpression */) { + this.emitDottedNameMemberAccessExpressionRecurse(expression.expression); + } else { + this.emitName(expression.expression, true); + } + + this.writeToOutput("."); + this.emitName(expression.name, false); + + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitDottedNameMemberAccessExpressionRecurse = function (expression) { + this.emitComments(expression, true); + this.emitDottedNameMemberAccessExpression(expression); + this.emitComments(expression, false); + }; + + Emitter.prototype.emitMemberAccessExpression = function (expression) { + if (!this.tryEmitConstant(expression)) { + if (this.canEmitDottedNameMemberAccessExpression(expression)) { + this.emitDottedNameMemberAccessExpression(expression); + } else { + this.recordSourceMappingStart(expression); + this.emit(expression.expression); + this.writeToOutput("."); + this.emitName(expression.name, false); + this.recordSourceMappingEnd(expression); + } + } + }; + + Emitter.prototype.emitQualifiedName = function (name) { + this.recordSourceMappingStart(name); + + this.emit(name.left); + this.writeToOutput("."); + this.emitName(name.right, false); + + this.recordSourceMappingEnd(name); + }; + + Emitter.prototype.emitBinaryExpression = function (expression) { + this.recordSourceMappingStart(expression); + switch (expression.kind()) { + case 173 /* CommaExpression */: + this.emit(expression.left); + this.writeToOutput(", "); + this.emit(expression.right); + break; + default: { + this.emit(expression.left); + var binOp = TypeScript.SyntaxFacts.getText(TypeScript.SyntaxFacts.getOperatorTokenFromBinaryExpression(expression.kind())); + if (binOp === "instanceof") { + this.writeToOutput(" instanceof "); + } else if (binOp === "in") { + this.writeToOutput(" in "); + } else { + this.writeToOutput(" " + binOp + " "); + } + this.emit(expression.right); + } + } + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitSimplePropertyAssignment = function (property) { + this.recordSourceMappingStart(property); + this.emit(property.propertyName); + this.writeToOutput(": "); + this.emit(property.expression); + this.recordSourceMappingEnd(property); + }; + + Emitter.prototype.emitFunctionPropertyAssignment = function (funcProp) { + this.recordSourceMappingStart(funcProp); + + this.emit(funcProp.propertyName); + this.writeToOutput(": "); + + var pullFunctionDecl = this.semanticInfoChain.getDeclForAST(funcProp); + + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = false; + + var temp = this.setContainer(5 /* Function */); + var funcName = funcProp.propertyName; + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcProp); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcProp); + this.writeToOutput("function "); + + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(funcProp.propertyName.text(), funcProp, parameters, funcProp.block, null); + + this.recordSourceMappingEnd(funcProp); + + this.recordSourceMappingEnd(funcProp); + + this.emitComments(funcProp, false); + + this.popDecl(pullDecl); + + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + }; + + Emitter.prototype.emitConditionalExpression = function (expression) { + this.emit(expression.condition); + this.writeToOutput(" ? "); + this.emit(expression.whenTrue); + this.writeToOutput(" : "); + this.emit(expression.whenFalse); + }; + + Emitter.prototype.emitThrowStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("throw "); + this.emit(statement.expression); + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitExpressionStatement = function (statement) { + var isArrowExpression = statement.expression.kind() === 219 /* SimpleArrowFunctionExpression */ || statement.expression.kind() === 218 /* ParenthesizedArrowFunctionExpression */; + + this.recordSourceMappingStart(statement); + if (isArrowExpression) { + this.writeToOutput("("); + } + + this.emit(statement.expression); + + if (isArrowExpression) { + this.writeToOutput(")"); + } + + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitLabeledStatement = function (statement) { + this.writeToOutputWithSourceMapRecord(statement.identifier.text(), statement.identifier); + this.writeLineToOutput(":"); + this.emitJavascript(statement.statement, true); + }; + + Emitter.prototype.emitBlock = function (block) { + this.recordSourceMappingStart(block); + this.writeLineToOutput(" {"); + this.indenter.increaseIndent(); + if (block.statements) { + this.emitList(block.statements); + } + this.emitCommentsArray(block.closeBraceLeadingComments, false); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + this.recordSourceMappingEnd(block); + }; + + Emitter.prototype.emitBreakStatement = function (jump) { + this.recordSourceMappingStart(jump); + this.writeToOutput("break"); + + if (jump.identifier) { + this.writeToOutput(" " + jump.identifier.text()); + } + + this.recordSourceMappingEnd(jump); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitContinueStatement = function (jump) { + this.recordSourceMappingStart(jump); + this.writeToOutput("continue"); + + if (jump.identifier) { + this.writeToOutput(" " + jump.identifier.text()); + } + + this.recordSourceMappingEnd(jump); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitWhileStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("while ("); + this.emit(statement.condition); + this.writeToOutput(")"); + this.emitBlockOrStatement(statement.statement); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitDoStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("do"); + this.emitBlockOrStatement(statement.statement); + this.writeToOutputWithSourceMapRecord(" while", statement.whileKeyword); + this.writeToOutput('('); + this.emit(statement.condition); + this.writeToOutput(")"); + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitIfStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("if ("); + this.emit(statement.condition); + this.writeToOutput(")"); + + this.emitBlockOrStatement(statement.statement); + + if (statement.elseClause) { + if (statement.statement.kind() !== 146 /* Block */) { + this.writeLineToOutput(""); + this.emitIndent(); + } else { + this.writeToOutput(" "); + } + + this.emit(statement.elseClause); + } + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitElseClause = function (elseClause) { + if (elseClause.statement.kind() === 147 /* IfStatement */) { + this.writeToOutput("else "); + this.emit(elseClause.statement); + } else { + this.writeToOutput("else"); + this.emitBlockOrStatement(elseClause.statement); + } + }; + + Emitter.prototype.emitReturnStatement = function (statement) { + this.recordSourceMappingStart(statement); + if (statement.expression) { + this.writeToOutput("return "); + this.emit(statement.expression); + } else { + this.writeToOutput("return"); + } + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitForInStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("for ("); + if (statement.left) { + this.emit(statement.left); + } else { + this.emit(statement.variableDeclaration); + } + this.writeToOutput(" in "); + this.emit(statement.expression); + this.writeToOutput(")"); + this.emitBlockOrStatement(statement.statement); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitForStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("for ("); + if (statement.variableDeclaration) { + this.emit(statement.variableDeclaration); + } else if (statement.initializer) { + this.emit(statement.initializer); + } + + this.writeToOutput("; "); + this.emitJavascript(statement.condition, false); + this.writeToOutput(";"); + if (statement.incrementor) { + this.writeToOutput(" "); + this.emitJavascript(statement.incrementor, false); + } + this.writeToOutput(")"); + this.emitBlockOrStatement(statement.statement); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitWithStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("with ("); + if (statement.condition) { + this.emit(statement.condition); + } + + this.writeToOutput(")"); + var prevInWithBlock = this.inWithBlock; + this.inWithBlock = true; + this.emitBlockOrStatement(statement.statement); + this.inWithBlock = prevInWithBlock; + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitSwitchStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("switch ("); + this.emit(statement.expression); + this.recordSourceMappingStart(statement.closeParenToken); + this.writeToOutput(")"); + this.recordSourceMappingEnd(statement.closeParenToken); + this.writeLineToOutput(" {"); + this.indenter.increaseIndent(); + this.emitList(statement.switchClauses, false); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitCaseSwitchClause = function (clause) { + this.recordSourceMappingStart(clause); + this.writeToOutput("case "); + this.emit(clause.expression); + this.writeToOutput(":"); + + this.emitSwitchClauseBody(clause.statements); + this.recordSourceMappingEnd(clause); + }; + + Emitter.prototype.emitSwitchClauseBody = function (body) { + if (body.childCount() === 1 && body.childAt(0).kind() === 146 /* Block */) { + this.emit(body.childAt(0)); + this.writeLineToOutput(""); + } else { + this.writeLineToOutput(""); + this.indenter.increaseIndent(); + this.emit(body); + this.indenter.decreaseIndent(); + } + }; + + Emitter.prototype.emitDefaultSwitchClause = function (clause) { + this.recordSourceMappingStart(clause); + this.writeToOutput("default:"); + + this.emitSwitchClauseBody(clause.statements); + this.recordSourceMappingEnd(clause); + }; + + Emitter.prototype.emitTryStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("try "); + this.emit(statement.block); + this.emitJavascript(statement.catchClause, false); + + if (statement.finallyClause) { + this.emit(statement.finallyClause); + } + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitCatchClause = function (clause) { + this.writeToOutput(" "); + this.recordSourceMappingStart(clause); + this.writeToOutput("catch ("); + this.emit(clause.identifier); + this.writeToOutput(")"); + this.emit(clause.block); + this.recordSourceMappingEnd(clause); + }; + + Emitter.prototype.emitFinallyClause = function (clause) { + this.writeToOutput(" finally"); + this.emit(clause.block); + }; + + Emitter.prototype.emitDebuggerStatement = function (statement) { + this.writeToOutputWithSourceMapRecord("debugger", statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitNumericLiteral = function (literal) { + this.writeToOutputWithSourceMapRecord(literal.text(), literal); + }; + + Emitter.prototype.emitRegularExpressionLiteral = function (literal) { + this.writeToOutputWithSourceMapRecord(literal.text(), literal); + }; + + Emitter.prototype.emitStringLiteral = function (literal) { + this.writeToOutputWithSourceMapRecord(literal.text(), literal); + }; + + Emitter.prototype.emitEqualsValueClause = function (clause) { + this.writeToOutput(" = "); + this.emit(clause.value); + }; + + Emitter.prototype.emitParameter = function (parameter) { + this.writeToOutputWithSourceMapRecord(parameter.identifier.text(), parameter); + }; + + Emitter.prototype.emitConstructorDeclaration = function (declaration) { + if (declaration.block) { + this.emitConstructor(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitFunctionDeclaration = function (declaration) { + return declaration.preComments() !== null || (!TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) && declaration.block !== null); + }; + + Emitter.prototype.emitFunctionDeclaration = function (declaration) { + if (!TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) && declaration.block !== null) { + this.emitFunction(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.emitSourceUnit = function (sourceUnit) { + if (!this.document.isDeclareFile()) { + var pullDecl = this.semanticInfoChain.getDeclForAST(sourceUnit); + this.pushDecl(pullDecl); + this.emitScriptElements(sourceUnit); + this.popDecl(pullDecl); + + this.emitCommentsArray(sourceUnit.endOfFileTokenLeadingComments, false); + } + }; + + Emitter.prototype.shouldEmitEnumDeclaration = function (declaration) { + return declaration.preComments() !== null || !TypeScript.ASTHelpers.enumIsElided(declaration); + }; + + Emitter.prototype.emitEnumDeclaration = function (declaration) { + if (!TypeScript.ASTHelpers.enumIsElided(declaration)) { + this.emitComments(declaration, true); + this.emitEnum(declaration); + this.emitComments(declaration, false); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitModuleDeclaration = function (declaration) { + return declaration.preComments() !== null || !TypeScript.ASTHelpers.moduleIsElided(declaration); + }; + + Emitter.prototype.emitModuleDeclaration = function (declaration) { + if (!TypeScript.ASTHelpers.moduleIsElided(declaration)) { + this.emitModuleDeclarationWorker(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitClassDeclaration = function (declaration) { + return declaration.preComments() !== null || !TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */); + }; + + Emitter.prototype.emitClassDeclaration = function (declaration) { + if (!TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */)) { + this.emitClass(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitInterfaceDeclaration = function (declaration) { + return declaration.preComments() !== null; + }; + + Emitter.prototype.emitInterfaceDeclaration = function (declaration) { + this.emitComments(declaration, true, true); + }; + + Emitter.prototype.firstVariableDeclarator = function (statement) { + return statement.declaration.declarators.nonSeparatorAt(0); + }; + + Emitter.prototype.isNotAmbientOrHasInitializer = function (variableStatement) { + return !TypeScript.hasModifier(variableStatement.modifiers, 8 /* Ambient */) || this.firstVariableDeclarator(variableStatement).equalsValueClause !== null; + }; + + Emitter.prototype.shouldEmitVariableStatement = function (statement) { + return statement.preComments() !== null || this.isNotAmbientOrHasInitializer(statement); + }; + + Emitter.prototype.emitVariableStatement = function (statement) { + if (this.isNotAmbientOrHasInitializer(statement)) { + this.emitComments(statement, true); + this.emit(statement.declaration); + this.writeToOutput(";"); + this.emitComments(statement, false); + } else { + this.emitComments(statement, true, true); + } + }; + + Emitter.prototype.emitGenericType = function (type) { + this.emit(type.name); + }; + + Emitter.prototype.shouldEmit = function (ast) { + if (!ast) { + return false; + } + + switch (ast.kind()) { + case 133 /* ImportDeclaration */: + return this.shouldEmitImportDeclaration(ast); + case 131 /* ClassDeclaration */: + return this.shouldEmitClassDeclaration(ast); + case 128 /* InterfaceDeclaration */: + return this.shouldEmitInterfaceDeclaration(ast); + case 129 /* FunctionDeclaration */: + return this.shouldEmitFunctionDeclaration(ast); + case 130 /* ModuleDeclaration */: + return this.shouldEmitModuleDeclaration(ast); + case 148 /* VariableStatement */: + return this.shouldEmitVariableStatement(ast); + case 223 /* OmittedExpression */: + return false; + case 132 /* EnumDeclaration */: + return this.shouldEmitEnumDeclaration(ast); + } + + return true; + }; + + Emitter.prototype.emit = function (ast) { + if (!ast) { + return; + } + + switch (ast.kind()) { + case 2 /* SeparatedList */: + return this.emitSeparatedList(ast); + case 1 /* List */: + return this.emitList(ast); + case 120 /* SourceUnit */: + return this.emitSourceUnit(ast); + case 133 /* ImportDeclaration */: + return this.emitImportDeclaration(ast); + case 134 /* ExportAssignment */: + return this.setExportAssignment(ast); + case 131 /* ClassDeclaration */: + return this.emitClassDeclaration(ast); + case 128 /* InterfaceDeclaration */: + return this.emitInterfaceDeclaration(ast); + case 11 /* IdentifierName */: + return this.emitName(ast, true); + case 225 /* VariableDeclarator */: + return this.emitVariableDeclarator(ast); + case 219 /* SimpleArrowFunctionExpression */: + return this.emitSimpleArrowFunctionExpression(ast); + case 218 /* ParenthesizedArrowFunctionExpression */: + return this.emitParenthesizedArrowFunctionExpression(ast); + case 129 /* FunctionDeclaration */: + return this.emitFunctionDeclaration(ast); + case 130 /* ModuleDeclaration */: + return this.emitModuleDeclaration(ast); + case 224 /* VariableDeclaration */: + return this.emitVariableDeclaration(ast); + case 126 /* GenericType */: + return this.emitGenericType(ast); + case 137 /* ConstructorDeclaration */: + return this.emitConstructorDeclaration(ast); + case 132 /* EnumDeclaration */: + return this.emitEnumDeclaration(ast); + case 243 /* EnumElement */: + return this.emitEnumElement(ast); + case 222 /* FunctionExpression */: + return this.emitFunctionExpression(ast); + case 148 /* VariableStatement */: + return this.emitVariableStatement(ast); + } + + this.emitComments(ast, true); + this.emitWorker(ast); + this.emitComments(ast, false); + }; + + Emitter.prototype.emitWorker = function (ast) { + if (!ast) { + return; + } + + switch (ast.kind()) { + case 13 /* NumericLiteral */: + return this.emitNumericLiteral(ast); + case 12 /* RegularExpressionLiteral */: + return this.emitRegularExpressionLiteral(ast); + case 14 /* StringLiteral */: + return this.emitStringLiteral(ast); + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + case 37 /* TrueKeyword */: + return this.emitLiteralExpression(ast); + case 35 /* ThisKeyword */: + return this.emitThisExpression(ast); + case 50 /* SuperKeyword */: + return this.emitSuperExpression(ast); + case 217 /* ParenthesizedExpression */: + return this.emitParenthesizedExpression(ast); + case 214 /* ArrayLiteralExpression */: + return this.emitArrayLiteralExpression(ast); + case 211 /* PostDecrementExpression */: + case 210 /* PostIncrementExpression */: + return this.emitPostfixUnaryExpression(ast); + case 167 /* LogicalNotExpression */: + case 166 /* BitwiseNotExpression */: + case 165 /* NegateExpression */: + case 164 /* PlusExpression */: + case 168 /* PreIncrementExpression */: + case 169 /* PreDecrementExpression */: + return this.emitPrefixUnaryExpression(ast); + case 213 /* InvocationExpression */: + return this.emitInvocationExpression(ast); + case 221 /* ElementAccessExpression */: + return this.emitElementAccessExpression(ast); + case 212 /* MemberAccessExpression */: + return this.emitMemberAccessExpression(ast); + case 121 /* QualifiedName */: + return this.emitQualifiedName(ast); + case 173 /* CommaExpression */: + case 174 /* AssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 187 /* LogicalOrExpression */: + case 188 /* LogicalAndExpression */: + case 189 /* BitwiseOrExpression */: + case 190 /* BitwiseExclusiveOrExpression */: + case 191 /* BitwiseAndExpression */: + case 192 /* EqualsWithTypeConversionExpression */: + case 193 /* NotEqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + case 196 /* LessThanExpression */: + case 197 /* GreaterThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 200 /* InstanceOfExpression */: + case 201 /* InExpression */: + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + case 208 /* AddExpression */: + case 209 /* SubtractExpression */: + return this.emitBinaryExpression(ast); + case 186 /* ConditionalExpression */: + return this.emitConditionalExpression(ast); + case 232 /* EqualsValueClause */: + return this.emitEqualsValueClause(ast); + case 242 /* Parameter */: + return this.emitParameter(ast); + case 146 /* Block */: + return this.emitBlock(ast); + case 235 /* ElseClause */: + return this.emitElseClause(ast); + case 147 /* IfStatement */: + return this.emitIfStatement(ast); + case 149 /* ExpressionStatement */: + return this.emitExpressionStatement(ast); + case 139 /* GetAccessor */: + return this.emitGetAccessor(ast); + case 140 /* SetAccessor */: + return this.emitSetAccessor(ast); + case 157 /* ThrowStatement */: + return this.emitThrowStatement(ast); + case 150 /* ReturnStatement */: + return this.emitReturnStatement(ast); + case 216 /* ObjectCreationExpression */: + return this.emitObjectCreationExpression(ast); + case 151 /* SwitchStatement */: + return this.emitSwitchStatement(ast); + case 233 /* CaseSwitchClause */: + return this.emitCaseSwitchClause(ast); + case 234 /* DefaultSwitchClause */: + return this.emitDefaultSwitchClause(ast); + case 152 /* BreakStatement */: + return this.emitBreakStatement(ast); + case 153 /* ContinueStatement */: + return this.emitContinueStatement(ast); + case 154 /* ForStatement */: + return this.emitForStatement(ast); + case 155 /* ForInStatement */: + return this.emitForInStatement(ast); + case 158 /* WhileStatement */: + return this.emitWhileStatement(ast); + case 163 /* WithStatement */: + return this.emitWithStatement(ast); + case 220 /* CastExpression */: + return this.emitCastExpression(ast); + case 215 /* ObjectLiteralExpression */: + return this.emitObjectLiteralExpression(ast); + case 240 /* SimplePropertyAssignment */: + return this.emitSimplePropertyAssignment(ast); + case 241 /* FunctionPropertyAssignment */: + return this.emitFunctionPropertyAssignment(ast); + case 156 /* EmptyStatement */: + return this.writeToOutputWithSourceMapRecord(";", ast); + case 159 /* TryStatement */: + return this.emitTryStatement(ast); + case 236 /* CatchClause */: + return this.emitCatchClause(ast); + case 237 /* FinallyClause */: + return this.emitFinallyClause(ast); + case 160 /* LabeledStatement */: + return this.emitLabeledStatement(ast); + case 161 /* DoStatement */: + return this.emitDoStatement(ast); + case 171 /* TypeOfExpression */: + return this.emitTypeOfExpression(ast); + case 170 /* DeleteExpression */: + return this.emitDeleteExpression(ast); + case 172 /* VoidExpression */: + return this.emitVoidExpression(ast); + case 162 /* DebuggerStatement */: + return this.emitDebuggerStatement(ast); + } + }; + return Emitter; + })(); + TypeScript.Emitter = Emitter; + + function getLastConstructor(classDecl) { + return classDecl.classElements.lastOrDefault(function (e) { + return e.kind() === 137 /* ConstructorDeclaration */; + }); + } + TypeScript.getLastConstructor = getLastConstructor; + + function getTrimmedTextLines(comment) { + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + return comment.fullText().split("\n").map(function (s) { + return s.trim(); + }); + } else { + return [comment.fullText().trim()]; + } + } + TypeScript.getTrimmedTextLines = getTrimmedTextLines; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var MemberName = (function () { + function MemberName() { + this.prefix = ""; + this.suffix = ""; + } + MemberName.prototype.isString = function () { + return false; + }; + MemberName.prototype.isArray = function () { + return false; + }; + MemberName.prototype.isMarker = function () { + return !this.isString() && !this.isArray(); + }; + + MemberName.prototype.toString = function () { + return MemberName.memberNameToString(this); + }; + + MemberName.memberNameToString = function (memberName, markerInfo, markerBaseLength) { + if (typeof markerBaseLength === "undefined") { markerBaseLength = 0; } + var result = memberName.prefix; + + if (memberName.isString()) { + result += memberName.text; + } else if (memberName.isArray()) { + var ar = memberName; + for (var index = 0; index < ar.entries.length; index++) { + if (ar.entries[index].isMarker()) { + if (markerInfo) { + markerInfo.push(markerBaseLength + result.length); + } + continue; + } + + result += MemberName.memberNameToString(ar.entries[index], markerInfo, markerBaseLength + result.length); + result += ar.delim; + } + } + + result += memberName.suffix; + return result; + }; + + MemberName.create = function (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.call(this); + 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; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function stripStartAndEndQuotes(str) { + var firstCharCode = str && str.charCodeAt(0); + if (str && str.length >= 2 && firstCharCode === str.charCodeAt(str.length - 1) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { + return str.substring(1, str.length - 1); + } + + return str; + } + TypeScript.stripStartAndEndQuotes = stripStartAndEndQuotes; + + function isSingleQuoted(str) { + return str && str.length >= 2 && str.charCodeAt(0) === str.charCodeAt(str.length - 1) && str.charCodeAt(0) === 39 /* singleQuote */; + } + TypeScript.isSingleQuoted = isSingleQuoted; + + function isDoubleQuoted(str) { + return str && str.length >= 2 && str.charCodeAt(0) === str.charCodeAt(str.length - 1) && str.charCodeAt(0) === 34 /* doubleQuote */; + } + TypeScript.isDoubleQuoted = isDoubleQuoted; + + function isQuoted(str) { + return isDoubleQuoted(str) || isSingleQuoted(str); + } + TypeScript.isQuoted = isQuoted; + + function quoteStr(str) { + return "\"" + str + "\""; + } + TypeScript.quoteStr = quoteStr; + + var switchToForwardSlashesRegEx = /\\/g; + function switchToForwardSlashes(path) { + return path.replace(switchToForwardSlashesRegEx, "/"); + } + TypeScript.switchToForwardSlashes = switchToForwardSlashes; + + function trimModName(modName) { + 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 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 isTSFile(fname) { + return isFileOfExtension(fname, ".ts"); + } + TypeScript.isTSFile = isTSFile; + + 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(stripStartAndEndQuotes(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, isAbsoultePathURL) { + if (typeof isAbsoultePathURL === "undefined") { isAbsoultePathURL = true; } + 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("/"); + } + + if (isAbsoultePathURL && absoluteModPath.indexOf("://") === -1) { + absoluteModPath = "file:///" + absoluteModPath; + } + + return absoluteModPath; + } + TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; + + function changePathToDTS(modPath) { + return trimModName(stripStartAndEndQuotes(modPath)) + ".d.ts"; + } + TypeScript.changePathToDTS = changePathToDTS; + + function isRelative(path) { + return path.length > 0 && path.charAt(0) === "."; + } + TypeScript.isRelative = isRelative; + function isRooted(path) { + return path.length > 0 && (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 convertToDirectoryPath(dirPath) { + if (dirPath && dirPath.charAt(dirPath.length - 1) !== "/") { + dirPath += "/"; + } + + return dirPath; + } + TypeScript.convertToDirectoryPath = convertToDirectoryPath; + + var normalizePathRegEx = /^\\\\[^\\]/; + function normalizePath(path) { + if (normalizePathRegEx.test(path)) { + path = "file:" + path; + } + var parts = this.getPathComponents(switchToForwardSlashes(path)); + var normalizedParts = []; + + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + if (part === ".") { + continue; + } + + if (normalizedParts.length > 0 && TypeScript.ArrayUtilities.last(normalizedParts) !== ".." && part === "..") { + normalizedParts.pop(); + continue; + } + + normalizedParts.push(part); + } + + return normalizedParts.join("/"); + } + TypeScript.normalizePath = normalizePath; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + + + function isNoDefaultLibMatch(comment) { + var isNoDefaultLibRegex = /^(\/\/\/\s*/gim; + return isNoDefaultLibRegex.exec(comment); + } + + TypeScript.tripleSlashReferenceRegExp = /^(\/\/\/\s*/; + + function getFileReferenceFromReferencePath(fileName, lineMap, position, comment, diagnostics) { + var simpleReferenceRegEx = /^\/\/\/\s*= 7 && fullReference[6] === "true"; + if (isResident) { + TypeScript.CompilerDiagnostics.debugPrint(path + " is resident"); + } + return { + line: 0, + character: 0, + position: 0, + length: 0, + path: TypeScript.switchToForwardSlashes(adjustedPath), + isResident: isResident + }; + } + } + } + + return null; + } + + var scannerWindow = TypeScript.ArrayUtilities.createArray(2048, 0); + var scannerDiagnostics = []; + + function processImports(lineMap, scanner, token, importedFiles) { + var position = 0; + var lineChar = { line: -1, character: -1 }; + + var start = new Date().getTime(); + + while (token.tokenKind !== 10 /* EndOfFileToken */) { + if (token.tokenKind === 49 /* ImportKeyword */) { + var importStart = position + token.leadingTriviaWidth(); + token = scanner.scan(scannerDiagnostics, false); + + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 107 /* EqualsToken */) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 65 /* ModuleKeyword */ || token.tokenKind === 66 /* RequireKeyword */) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 72 /* OpenParenToken */) { + var afterOpenParenPosition = scanner.absoluteIndex(); + token = scanner.scan(scannerDiagnostics, false); + + lineMap.fillLineAndCharacterFromPosition(importStart, lineChar); + + if (token.tokenKind === 14 /* StringLiteral */) { + var ref = { + line: lineChar.line, + character: lineChar.character, + position: afterOpenParenPosition + token.leadingTriviaWidth(), + length: token.width(), + path: TypeScript.stripStartAndEndQuotes(TypeScript.switchToForwardSlashes(token.text())), + isResident: false + }; + importedFiles.push(ref); + } + } + } + } + } + } + + position = scanner.absoluteIndex(); + token = scanner.scan(scannerDiagnostics, false); + } + + var totalTime = new Date().getTime() - start; + TypeScript.fileResolutionScanImportsTime += totalTime; + } + + function processTripleSlashDirectives(fileName, lineMap, firstToken) { + var leadingTrivia = firstToken.leadingTrivia(); + + var position = 0; + var lineChar = { line: -1, character: -1 }; + var noDefaultLib = false; + var diagnostics = []; + var referencedFiles = []; + + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + + if (trivia.kind() === 7 /* SingleLineCommentTrivia */) { + var triviaText = trivia.fullText(); + var referencedCode = getFileReferenceFromReferencePath(fileName, lineMap, position, triviaText, diagnostics); + + if (referencedCode) { + lineMap.fillLineAndCharacterFromPosition(position, lineChar); + referencedCode.position = position; + referencedCode.length = trivia.fullWidth(); + referencedCode.line = lineChar.line; + referencedCode.character = lineChar.character; + + referencedFiles.push(referencedCode); + } + + var isNoDefaultLib = isNoDefaultLibMatch(triviaText); + if (isNoDefaultLib) { + noDefaultLib = isNoDefaultLib[3] === "true"; + } + } + + position += trivia.fullWidth(); + } + + return { noDefaultLib: noDefaultLib, diagnostics: diagnostics, referencedFiles: referencedFiles }; + } + + function preProcessFile(fileName, sourceText, readImportFiles) { + if (typeof readImportFiles === "undefined") { readImportFiles = true; } + var text = TypeScript.SimpleText.fromScriptSnapshot(sourceText); + var scanner = new TypeScript.Scanner(fileName, text, 1 /* EcmaScript5 */, scannerWindow); + + var firstToken = scanner.scan(scannerDiagnostics, false); + + var importedFiles = []; + if (readImportFiles) { + processImports(text.lineMap(), scanner, firstToken, importedFiles); + } + + var properties = processTripleSlashDirectives(fileName, text.lineMap(), firstToken); + + scannerDiagnostics.length = 0; + return { referencedFiles: properties.referencedFiles, importedFiles: importedFiles, isLibFile: properties.noDefaultLib, diagnostics: properties.diagnostics }; + } + TypeScript.preProcessFile = preProcessFile; + + function getParseOptions(settings) { + return new TypeScript.ParseOptions(settings.codeGenTarget(), settings.allowAutomaticSemicolonInsertion()); + } + TypeScript.getParseOptions = getParseOptions; + + function getReferencedFiles(fileName, sourceText) { + return preProcessFile(fileName, sourceText, false).referencedFiles; + } + TypeScript.getReferencedFiles = getReferencedFiles; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ReferenceResolutionResult = (function () { + function ReferenceResolutionResult() { + this.resolvedFiles = []; + this.diagnostics = []; + this.seenNoDefaultLibTag = false; + } + return ReferenceResolutionResult; + })(); + TypeScript.ReferenceResolutionResult = ReferenceResolutionResult; + + var ReferenceLocation = (function () { + function ReferenceLocation(filePath, lineMap, position, length, isImported) { + this.filePath = filePath; + this.lineMap = lineMap; + this.position = position; + this.length = length; + this.isImported = isImported; + } + return ReferenceLocation; + })(); + + var ReferenceResolver = (function () { + function ReferenceResolver(inputFileNames, host, useCaseSensitiveFileResolution) { + this.useCaseSensitiveFileResolution = useCaseSensitiveFileResolution; + this.inputFileNames = inputFileNames; + this.host = host; + this.visited = {}; + } + ReferenceResolver.resolve = function (inputFileNames, host, useCaseSensitiveFileResolution) { + var resolver = new ReferenceResolver(inputFileNames, host, useCaseSensitiveFileResolution); + return resolver.resolveInputFiles(); + }; + + ReferenceResolver.prototype.resolveInputFiles = function () { + var _this = this; + var result = new ReferenceResolutionResult(); + + if (!this.inputFileNames || this.inputFileNames.length <= 0) { + return result; + } + + var referenceLocation = new ReferenceLocation(null, null, 0, 0, false); + this.inputFileNames.forEach(function (fileName) { + return _this.resolveIncludedFile(fileName, referenceLocation, result); + }); + + return result; + }; + + ReferenceResolver.prototype.resolveIncludedFile = function (path, referenceLocation, resolutionResult) { + var normalizedPath = this.getNormalizedFilePath(path, referenceLocation.filePath); + + if (this.isSameFile(normalizedPath, referenceLocation.filePath)) { + if (!referenceLocation.isImported) { + resolutionResult.diagnostics.push(new TypeScript.Diagnostic(referenceLocation.filePath, referenceLocation.lineMap, referenceLocation.position, referenceLocation.length, TypeScript.DiagnosticCode.A_file_cannot_have_a_reference_to_itself, null)); + } + + return normalizedPath; + } + + if (!TypeScript.isTSFile(normalizedPath) && !TypeScript.isDTSFile(normalizedPath)) { + var dtsFile = normalizedPath + ".d.ts"; + var tsFile = normalizedPath + ".ts"; + + if (this.host.fileExists(tsFile)) { + normalizedPath = tsFile; + } else { + normalizedPath = dtsFile; + } + } + + if (!this.host.fileExists(normalizedPath)) { + if (!referenceLocation.isImported) { + resolutionResult.diagnostics.push(new TypeScript.Diagnostic(referenceLocation.filePath, referenceLocation.lineMap, referenceLocation.position, referenceLocation.length, TypeScript.DiagnosticCode.Cannot_resolve_referenced_file_0, [path])); + } + + return normalizedPath; + } + + return this.resolveFile(normalizedPath, resolutionResult); + }; + + ReferenceResolver.prototype.resolveImportedFile = function (path, referenceLocation, resolutionResult) { + var isRelativePath = TypeScript.isRelative(path); + var isRootedPath = isRelativePath ? false : TypeScript.isRooted(path); + + if (isRelativePath || isRootedPath) { + return this.resolveIncludedFile(path, referenceLocation, resolutionResult); + } else { + var parentDirectory = this.host.getParentDirectory(referenceLocation.filePath); + var searchFilePath = null; + var dtsFileName = path + ".d.ts"; + var tsFilePath = path + ".ts"; + + var start = new Date().getTime(); + + do { + currentFilePath = this.host.resolveRelativePath(tsFilePath, parentDirectory); + if (this.host.fileExists(currentFilePath)) { + searchFilePath = currentFilePath; + break; + } + + var currentFilePath = this.host.resolveRelativePath(dtsFileName, parentDirectory); + if (this.host.fileExists(currentFilePath)) { + searchFilePath = currentFilePath; + break; + } + + parentDirectory = this.host.getParentDirectory(parentDirectory); + } while(parentDirectory); + + TypeScript.fileResolutionImportFileSearchTime += new Date().getTime() - start; + + if (!searchFilePath) { + return path; + } + + return this.resolveFile(searchFilePath, resolutionResult); + } + }; + + ReferenceResolver.prototype.resolveFile = function (normalizedPath, resolutionResult) { + var _this = this; + var visitedPath = this.isVisited(normalizedPath); + if (!visitedPath) { + this.recordVisitedFile(normalizedPath); + + var start = new Date().getTime(); + var scriptSnapshot = this.host.getScriptSnapshot(normalizedPath); + var totalTime = new Date().getTime() - start; + TypeScript.fileResolutionIOTime += totalTime; + + var lineMap = TypeScript.LineMap1.fromScriptSnapshot(scriptSnapshot); + var preprocessedFileInformation = TypeScript.preProcessFile(normalizedPath, scriptSnapshot); + resolutionResult.diagnostics.push.apply(resolutionResult.diagnostics, preprocessedFileInformation.diagnostics); + + if (preprocessedFileInformation.isLibFile) { + resolutionResult.seenNoDefaultLibTag = true; + } + + var normalizedReferencePaths = []; + preprocessedFileInformation.referencedFiles.forEach(function (fileReference) { + var currentReferenceLocation = new ReferenceLocation(normalizedPath, lineMap, fileReference.position, fileReference.length, false); + var normalizedReferencePath = _this.resolveIncludedFile(fileReference.path, currentReferenceLocation, resolutionResult); + normalizedReferencePaths.push(normalizedReferencePath); + }); + + var normalizedImportPaths = []; + for (var i = 0; i < preprocessedFileInformation.importedFiles.length; i++) { + var fileImport = preprocessedFileInformation.importedFiles[i]; + var currentReferenceLocation = new ReferenceLocation(normalizedPath, lineMap, fileImport.position, fileImport.length, true); + var normalizedImportPath = this.resolveImportedFile(fileImport.path, currentReferenceLocation, resolutionResult); + normalizedImportPaths.push(normalizedImportPath); + } + + resolutionResult.resolvedFiles.push({ + path: normalizedPath, + referencedFiles: normalizedReferencePaths, + importedFiles: normalizedImportPaths + }); + } else { + normalizedPath = visitedPath; + } + + return normalizedPath; + }; + + ReferenceResolver.prototype.getNormalizedFilePath = function (path, parentFilePath) { + var parentFileDirectory = parentFilePath ? this.host.getParentDirectory(parentFilePath) : ""; + var normalizedPath = this.host.resolveRelativePath(path, parentFileDirectory); + return normalizedPath; + }; + + ReferenceResolver.prototype.getUniqueFileId = function (filePath) { + return this.useCaseSensitiveFileResolution ? filePath : filePath.toLocaleUpperCase(); + }; + + ReferenceResolver.prototype.recordVisitedFile = function (filePath) { + this.visited[this.getUniqueFileId(filePath)] = filePath; + }; + + ReferenceResolver.prototype.isVisited = function (filePath) { + return this.visited[this.getUniqueFileId(filePath)]; + }; + + ReferenceResolver.prototype.isSameFile = function (filePath1, filePath2) { + if (!filePath1 || !filePath2) { + return false; + } + + if (this.useCaseSensitiveFileResolution) { + return filePath1 === filePath2; + } else { + return filePath1.toLocaleUpperCase() === filePath2.toLocaleUpperCase(); + } + }; + return ReferenceResolver; + })(); + TypeScript.ReferenceResolver = ReferenceResolver; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextWriter = (function () { + function TextWriter(name, writeByteOrderMark, outputFileType) { + this.name = name; + this.writeByteOrderMark = writeByteOrderMark; + this.outputFileType = outputFileType; + this.contents = ""; + this.onNewLine = true; + } + TextWriter.prototype.Write = function (s) { + this.contents += s; + this.onNewLine = false; + }; + + TextWriter.prototype.WriteLine = function (s) { + this.contents += s; + this.contents += TypeScript.newLine(); + this.onNewLine = true; + }; + + TextWriter.prototype.Close = function () { + }; + + TextWriter.prototype.getOutputFile = function () { + return new TypeScript.OutputFile(this.name, this.writeByteOrderMark, this.contents, this.outputFileType); + }; + return TextWriter; + })(); + TypeScript.TextWriter = TextWriter; + + var DeclarationEmitter = (function () { + function DeclarationEmitter(emittingFileName, document, compiler, emitOptions, semanticInfoChain) { + this.emittingFileName = emittingFileName; + this.document = document; + this.compiler = compiler; + this.emitOptions = emitOptions; + this.semanticInfoChain = semanticInfoChain; + this.declFile = null; + this.indenter = new TypeScript.Indenter(); + this.emittedReferencePaths = false; + this.declFile = new TextWriter(emittingFileName, this.document.byteOrderMark !== 0 /* None */, 2 /* Declaration */); + } + DeclarationEmitter.prototype.getOutputFile = function () { + return this.declFile.getOutputFile(); + }; + + DeclarationEmitter.prototype.emitDeclarations = function (sourceUnit) { + this.emitDeclarationsForSourceUnit(sourceUnit); + }; + + DeclarationEmitter.prototype.emitDeclarationsForList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + this.emitDeclarationsForAST(list.childAt(i)); + } + }; + + DeclarationEmitter.prototype.emitSeparatedList = function (list) { + for (var i = 0, n = list.nonSeparatorCount(); i < n; i++) { + this.emitDeclarationsForAST(list.nonSeparatorAt(i)); + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForAST = function (ast) { + switch (ast.kind()) { + case 148 /* VariableStatement */: + return this.emitDeclarationsForVariableStatement(ast); + case 141 /* PropertySignature */: + return this.emitPropertySignature(ast); + case 225 /* VariableDeclarator */: + return this.emitVariableDeclarator(ast, true, true); + case 136 /* MemberVariableDeclaration */: + return this.emitDeclarationsForMemberVariableDeclaration(ast); + case 137 /* ConstructorDeclaration */: + return this.emitDeclarationsForConstructorDeclaration(ast); + case 139 /* GetAccessor */: + return this.emitDeclarationsForGetAccessor(ast); + case 140 /* SetAccessor */: + return this.emitDeclarationsForSetAccessor(ast); + case 138 /* IndexMemberDeclaration */: + return this.emitIndexMemberDeclaration(ast); + case 144 /* IndexSignature */: + return this.emitIndexSignature(ast); + case 142 /* CallSignature */: + return this.emitCallSignature(ast); + case 143 /* ConstructSignature */: + return this.emitConstructSignature(ast); + case 145 /* MethodSignature */: + return this.emitMethodSignature(ast); + case 129 /* FunctionDeclaration */: + return this.emitDeclarationsForFunctionDeclaration(ast); + case 135 /* MemberFunctionDeclaration */: + return this.emitMemberFunctionDeclaration(ast); + case 131 /* ClassDeclaration */: + return this.emitDeclarationsForClassDeclaration(ast); + case 128 /* InterfaceDeclaration */: + return this.emitDeclarationsForInterfaceDeclaration(ast); + case 133 /* ImportDeclaration */: + return this.emitDeclarationsForImportDeclaration(ast); + case 130 /* ModuleDeclaration */: + return this.emitDeclarationsForModuleDeclaration(ast); + case 132 /* EnumDeclaration */: + return this.emitDeclarationsForEnumDeclaration(ast); + case 134 /* ExportAssignment */: + return this.emitDeclarationsForExportAssignment(ast); + } + }; + + DeclarationEmitter.prototype.getIndentString = function (declIndent) { + if (typeof declIndent === "undefined") { declIndent = false; } + return this.indenter.getIndent(); + }; + + DeclarationEmitter.prototype.emitIndent = function () { + this.declFile.Write(this.getIndentString()); + }; + + DeclarationEmitter.prototype.canEmitDeclarations = function (declAST) { + var container = DeclarationEmitter.getEnclosingContainer(declAST); + if (container.kind() === 130 /* ModuleDeclaration */ || container.kind() === 120 /* SourceUnit */) { + var pullDecl = this.semanticInfoChain.getDeclForAST(declAST); + if (!TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */)) { + var start = new Date().getTime(); + var declSymbol = this.semanticInfoChain.getSymbolForAST(declAST); + var result = declSymbol && declSymbol.isExternallyVisible(); + TypeScript.declarationEmitIsExternallyVisibleTime += new Date().getTime() - start; + + return result; + } + } + + return true; + }; + + DeclarationEmitter.prototype.getDeclFlagsString = function (pullDecl, typeString) { + var result = this.getIndentString(); + var pullFlags = pullDecl.flags; + + if (TypeScript.hasFlag(pullFlags, 16 /* Static */)) { + if (TypeScript.hasFlag(pullFlags, 2 /* Private */)) { + result += "private "; + } + result += "static "; + } else { + if (TypeScript.hasFlag(pullFlags, 2 /* Private */)) { + result += "private "; + } else if (TypeScript.hasFlag(pullFlags, 4 /* Public */)) { + result += "public "; + } else { + var emitDeclare = !TypeScript.hasFlag(pullFlags, 1 /* Exported */); + + var declAST = this.semanticInfoChain.getASTForDecl(pullDecl); + var container = DeclarationEmitter.getEnclosingContainer(declAST); + + var isExternalModule = container.kind() === 120 /* SourceUnit */ && this.document.isExternalModule(); + + if (isExternalModule && TypeScript.hasFlag(pullFlags, 1 /* Exported */)) { + result += "export "; + emitDeclare = true; + } + + if (isExternalModule || container.kind() === 120 /* SourceUnit */) { + if (emitDeclare && typeString !== "interface" && typeString !== "import") { + result += "declare "; + } + } + + result += typeString + " "; + } + } + + return result; + }; + + DeclarationEmitter.prototype.emitDeclFlags = function (declarationAST, typeString) { + this.declFile.Write(this.getDeclFlagsString(this.semanticInfoChain.getDeclForAST(declarationAST), typeString)); + }; + + 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 if (memberName.isArray()) { + 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 (ast, type) { + var declarationContainerAst = DeclarationEmitter.getEnclosingContainer(ast); + + var start = new Date().getTime(); + var declarationContainerDecl = this.semanticInfoChain.getDeclForAST(declarationContainerAst); + + var declarationPullSymbol = declarationContainerDecl.getSymbol(); + TypeScript.declarationEmitTypeSignatureTime += new Date().getTime() - start; + + var isNotAGenericType = ast.kind() !== 126 /* GenericType */; + + var typeNameMembers = type.getScopedNameEx(declarationPullSymbol, false, false, false, false, false, isNotAGenericType); + this.emitTypeNamesMember(typeNameMembers); + }; + + DeclarationEmitter.prototype.emitComment = function (comment) { + var text = TypeScript.getTrimmedTextLines(comment); + if (this.declFile.onNewLine) { + this.emitIndent(); + } else if (comment.kind() !== 6 /* MultiLineCommentTrivia */) { + 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.kind() !== 6 /* MultiLineCommentTrivia */) { + this.declFile.WriteLine(""); + } else { + this.declFile.Write(" "); + } + }; + + DeclarationEmitter.prototype.emitDeclarationComments = function (astOrSymbol, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + if (this.emitOptions.compilationSettings().removeComments()) { + return; + } + + var declComments = astOrSymbol.docComments ? astOrSymbol.docComments() : TypeScript.ASTHelpers.docComments(astOrSymbol); + this.writeDeclarationComments(declComments, endLine); + }; + + DeclarationEmitter.prototype.writeDeclarationComments = function (declComments, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + 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.emitTypeOfVariableDeclaratorOrParameter = function (boundDecl) { + var start = new Date().getTime(); + var decl = this.semanticInfoChain.getDeclForAST(boundDecl); + var pullSymbol = decl.getSymbol(); + TypeScript.declarationEmitGetBoundDeclTypeTime += new Date().getTime() - start; + + var type = pullSymbol.type; + TypeScript.Debug.assert(type); + + this.declFile.Write(": "); + this.emitTypeSignature(boundDecl, type); + }; + + DeclarationEmitter.prototype.emitPropertySignature = function (varDecl) { + this.emitDeclarationComments(varDecl); + this.emitIndent(); + this.declFile.Write(varDecl.propertyName.text()); + if (varDecl.questionToken) { + this.declFile.Write("?"); + } + + this.emitTypeOfVariableDeclaratorOrParameter(varDecl); + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitVariableDeclarator = function (varDecl, isFirstVarInList, isLastVarInList) { + if (this.canEmitDeclarations(varDecl)) { + this.emitDeclarationComments(varDecl); + + if (isFirstVarInList) { + this.emitDeclFlags(varDecl, "var"); + } + + this.declFile.Write(varDecl.propertyName.text()); + + if (!TypeScript.hasModifier(TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), 2 /* Private */)) { + this.emitTypeOfVariableDeclaratorOrParameter(varDecl); + } + + if (isLastVarInList) { + this.declFile.WriteLine(";"); + } else { + this.declFile.Write(", "); + } + } + }; + + DeclarationEmitter.prototype.emitClassElementModifiers = function (modifiers) { + if (TypeScript.hasModifier(modifiers, 16 /* Static */)) { + if (TypeScript.hasModifier(modifiers, 2 /* Private */)) { + this.declFile.Write("private "); + } + this.declFile.Write("static "); + } else { + if (TypeScript.hasModifier(modifiers, 2 /* Private */)) { + this.declFile.Write("private "); + } else { + this.declFile.Write("public "); + } + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForMemberVariableDeclaration = function (varDecl) { + if (this.canEmitDeclarations(varDecl)) { + this.emitDeclarationComments(varDecl); + + this.declFile.Write(this.getIndentString()); + this.emitClassElementModifiers(varDecl.modifiers); + ; + + this.declFile.Write(varDecl.variableDeclarator.propertyName.text()); + + if (!TypeScript.hasModifier(varDecl.modifiers, 2 /* Private */)) { + this.emitTypeOfVariableDeclaratorOrParameter(varDecl); + } + + this.declFile.WriteLine(";"); + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForVariableStatement = function (variableStatement) { + this.emitDeclarationsForVariableDeclaration(variableStatement.declaration); + }; + + DeclarationEmitter.prototype.emitDeclarationsForVariableDeclaration = function (variableDeclaration) { + var varListCount = variableDeclaration.declarators.nonSeparatorCount(); + for (var i = 0; i < varListCount; i++) { + this.emitVariableDeclarator(variableDeclaration.declarators.nonSeparatorAt(i), i === 0, i === varListCount - 1); + } + }; + + DeclarationEmitter.prototype.emitArgDecl = function (argDecl, id, isOptional, isPrivate) { + this.indenter.increaseIndent(); + + this.emitDeclarationComments(argDecl, false); + this.declFile.Write(id.text()); + if (isOptional) { + this.declFile.Write("?"); + } + + this.indenter.decreaseIndent(); + + if (!isPrivate) { + this.emitTypeOfVariableDeclaratorOrParameter(argDecl); + } + }; + + DeclarationEmitter.prototype.isOverloadedCallSignature = function (funcDecl) { + var start = new Date().getTime(); + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSymbol = functionDecl.getSymbol(); + TypeScript.declarationEmitIsOverloadedCallSignatureTime += new Date().getTime() - start; + + var funcTypeSymbol = funcSymbol.type; + var signatures = funcTypeSymbol.getCallSignatures(); + var result = signatures && signatures.length > 1; + + return result; + }; + + DeclarationEmitter.prototype.emitDeclarationsForConstructorDeclaration = function (funcDecl) { + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + var funcTypeSymbol = funcSymbol.type; + if (funcDecl.block) { + var constructSignatures = funcTypeSymbol.getConstructSignatures(); + if (constructSignatures && constructSignatures.length > 1) { + return; + } + } + + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write("constructor"); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitParameterList = function (isPrivate, parameterList) { + this.declFile.Write("("); + this.emitParameters(isPrivate, TypeScript.ASTHelpers.parametersFromParameterList(parameterList)); + this.declFile.Write(")"); + }; + + DeclarationEmitter.prototype.emitParameters = function (isPrivate, parameterList) { + var hasLastParameterRestParameter = parameterList.lastParameterIsRest(); + var argsLen = parameterList.length; + if (hasLastParameterRestParameter) { + argsLen--; + } + + for (var i = 0; i < argsLen; i++) { + this.emitArgDecl(parameterList.astAt(i), parameterList.identifierAt(i), parameterList.isOptionalAt(i), isPrivate); + if (i < (argsLen - 1)) { + this.declFile.Write(", "); + } + } + + if (hasLastParameterRestParameter) { + if (parameterList.length > 1) { + this.declFile.Write(", ..."); + } else { + this.declFile.Write("..."); + } + + var index = parameterList.length - 1; + this.emitArgDecl(parameterList.astAt(index), parameterList.identifierAt(index), parameterList.isOptionalAt(index), isPrivate); + } + }; + + DeclarationEmitter.prototype.emitMemberFunctionDeclaration = function (funcDecl) { + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + var funcTypeSymbol = funcSymbol.type; + if (funcDecl.block) { + var constructSignatures = funcTypeSymbol.getConstructSignatures(); + if (constructSignatures && constructSignatures.length > 1) { + return; + } else if (this.isOverloadedCallSignature(funcDecl)) { + return; + } + } else if (TypeScript.hasModifier(funcDecl.modifiers, 2 /* Private */) && this.isOverloadedCallSignature(funcDecl)) { + var callSignatures = funcTypeSymbol.getCallSignatures(); + TypeScript.Debug.assert(callSignatures && callSignatures.length > 1); + var firstSignature = callSignatures[0].isDefinition() ? callSignatures[1] : callSignatures[0]; + var firstSignatureDecl = firstSignature.getDeclarations()[0]; + var firstFuncDecl = this.semanticInfoChain.getASTForDecl(firstSignatureDecl); + if (firstFuncDecl !== funcDecl) { + return; + } + } + + if (!this.canEmitDeclarations(funcDecl)) { + return; + } + + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitDeclarationComments(funcDecl); + + this.emitDeclFlags(funcDecl, "function"); + var id = funcDecl.propertyName.text(); + this.declFile.Write(id); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + var isPrivate = TypeScript.hasModifier(funcDecl.modifiers, 2 /* Private */); + + this.emitParameterList(isPrivate, funcDecl.callSignature.parameterList); + + if (!isPrivate) { + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + this.emitTypeSignature(funcDecl, returnType); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitCallSignature = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + this.emitDeclarationComments(funcDecl); + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.typeParameterList, funcSignature); + + this.emitIndent(); + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitConstructSignature = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write("new"); + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitMethodSignature = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write(funcDecl.propertyName.text()); + if (funcDecl.questionToken) { + this.declFile.Write("? "); + } + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForFunctionDeclaration = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + if (funcDecl.block) { + var funcTypeSymbol = funcSymbol.type; + var constructSignatures = funcTypeSymbol.getConstructSignatures(); + if (constructSignatures && constructSignatures.length > 1) { + return; + } else if (this.isOverloadedCallSignature(funcDecl)) { + return; + } + } + + if (!this.canEmitDeclarations(funcDecl)) { + return; + } + + this.emitDeclarationComments(funcDecl); + + var id = funcDecl.identifier.text(); + this.emitDeclFlags(funcDecl, "function"); + if (id !== "" || !funcDecl.identifier || funcDecl.identifier.text().length > 0) { + this.declFile.Write(id); + } else if (funcPullDecl.kind === 2097152 /* ConstructSignature */) { + this.declFile.Write("new"); + } + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitIndexMemberDeclaration = function (funcDecl) { + this.emitDeclarationsForAST(funcDecl.indexSignature); + }; + + DeclarationEmitter.prototype.emitIndexSignature = function (funcDecl) { + if (!this.canEmitDeclarations(funcDecl)) { + return; + } + + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write("["); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameter(funcDecl.parameter)); + this.declFile.Write("]"); + + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSignature = funcPullDecl.getSignatureSymbol(); + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + this.emitTypeSignature(funcDecl, returnType); + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitBaseList = function (bases, useExtendsList) { + if (bases && (bases.nonSeparatorCount() > 0)) { + var qual = useExtendsList ? "extends" : "implements"; + this.declFile.Write(" " + qual + " "); + var basesLen = bases.nonSeparatorCount(); + for (var i = 0; i < basesLen; i++) { + if (i > 0) { + this.declFile.Write(", "); + } + var base = bases.nonSeparatorAt(i); + var baseType = this.semanticInfoChain.getSymbolForAST(base); + this.emitTypeSignature(base, baseType); + } + } + }; + + DeclarationEmitter.prototype.emitAccessorDeclarationComments = function (funcDecl) { + if (this.emitOptions.compilationSettings().removeComments()) { + return; + } + + var start = new Date().getTime(); + var accessors = TypeScript.PullHelpers.getGetterAndSetterFunction(funcDecl, this.semanticInfoChain); + TypeScript.declarationEmitGetAccessorFunctionTime += new Date().getTime(); + + var comments = []; + if (accessors.getter) { + comments = comments.concat(TypeScript.ASTHelpers.docComments(accessors.getter)); + } + if (accessors.setter) { + comments = comments.concat(TypeScript.ASTHelpers.docComments(accessors.setter)); + } + + this.writeDeclarationComments(comments); + }; + + DeclarationEmitter.prototype.emitDeclarationsForGetAccessor = function (funcDecl) { + this.emitMemberAccessorDeclaration(funcDecl, funcDecl.modifiers, funcDecl.propertyName); + }; + + DeclarationEmitter.prototype.emitDeclarationsForSetAccessor = function (funcDecl) { + this.emitMemberAccessorDeclaration(funcDecl, funcDecl.modifiers, funcDecl.propertyName); + }; + + DeclarationEmitter.prototype.emitMemberAccessorDeclaration = function (funcDecl, modifiers, name) { + var start = new Date().getTime(); + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain); + TypeScript.declarationEmitGetAccessorFunctionTime += new Date().getTime(); + + if (funcDecl.kind() === 140 /* SetAccessor */ && accessorSymbol.getGetter()) { + return; + } + + var isPrivate = TypeScript.hasModifier(modifiers, 2 /* Private */); + this.emitAccessorDeclarationComments(funcDecl); + this.declFile.Write(this.getIndentString()); + this.emitClassElementModifiers(modifiers); + this.declFile.Write(name.text()); + if (!isPrivate) { + this.declFile.Write(" : "); + var type = accessorSymbol.type; + this.emitTypeSignature(funcDecl, type); + } + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { + var argsLen = funcDecl.callSignature.parameterList.parameters.nonSeparatorCount(); + if (TypeScript.lastParameterIsRest(funcDecl.callSignature.parameterList)) { + argsLen--; + } + + for (var i = 0; i < argsLen; i++) { + var parameter = funcDecl.callSignature.parameterList.parameters.nonSeparatorAt(i); + var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter); + if (TypeScript.hasFlag(parameterDecl.flags, 8388608 /* PropertyParameter */)) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.emitDeclarationComments(parameter); + this.declFile.Write(this.getIndentString()); + this.emitClassElementModifiers(parameter.modifiers); + this.declFile.Write(parameter.identifier.text()); + + if (!TypeScript.hasModifier(parameter.modifiers, 2 /* Private */)) { + this.emitTypeOfVariableDeclaratorOrParameter(parameter); + } + this.declFile.WriteLine(";"); + } + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForClassDeclaration = function (classDecl) { + if (!this.canEmitDeclarations(classDecl)) { + return; + } + + var className = classDecl.identifier.text(); + this.emitDeclarationComments(classDecl); + var classPullDecl = this.semanticInfoChain.getDeclForAST(classDecl); + this.emitDeclFlags(classDecl, "class"); + this.declFile.Write(className); + + this.emitTypeParameters(classDecl.typeParameterList); + this.emitHeritageClauses(classDecl.heritageClauses); + this.declFile.WriteLine(" {"); + + this.indenter.increaseIndent(); + var constructorDecl = TypeScript.getLastConstructor(classDecl); + if (constructorDecl) { + this.emitClassMembersFromConstructorDefinition(constructorDecl); + } + + this.emitDeclarationsForList(classDecl.classElements); + + this.indenter.decreaseIndent(); + + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitHeritageClauses = function (clauses) { + if (clauses) { + for (var i = 0, n = clauses.childCount(); i < n; i++) { + this.emitHeritageClause(clauses.childAt(i)); + } + } + }; + + DeclarationEmitter.prototype.emitHeritageClause = function (clause) { + this.emitBaseList(clause.typeNames, clause.kind() === 230 /* ExtendsHeritageClause */); + }; + + DeclarationEmitter.getEnclosingContainer = function (ast) { + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(ast); + ast = enclosingModule || ast; + + ast = ast.parent; + while (ast) { + if (ast.kind() === 131 /* ClassDeclaration */ || ast.kind() === 128 /* InterfaceDeclaration */ || ast.kind() === 130 /* ModuleDeclaration */ || ast.kind() === 120 /* SourceUnit */) { + return ast; + } + + ast = ast.parent; + } + + return null; + }; + + DeclarationEmitter.prototype.emitTypeParameters = function (typeParams, funcSignature) { + if (!typeParams || !typeParams.typeParameters.nonSeparatorCount()) { + return; + } + + this.declFile.Write("<"); + var containerAst = DeclarationEmitter.getEnclosingContainer(typeParams); + + var start = new Date().getTime(); + var containerDecl = this.semanticInfoChain.getDeclForAST(containerAst); + var containerSymbol = containerDecl.getSymbol(); + TypeScript.declarationEmitGetTypeParameterSymbolTime += new Date().getTime() - start; + + var typars; + if (funcSignature) { + typars = funcSignature.getTypeParameters(); + } else { + typars = containerSymbol.getTypeArgumentsOrTypeParameters(); + } + + for (var i = 0; i < typars.length; i++) { + if (i) { + this.declFile.Write(", "); + } + + var memberName = typars[i].getScopedNameEx(containerSymbol, false, true); + this.emitTypeNamesMember(memberName); + } + + this.declFile.Write(">"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForInterfaceDeclaration = function (interfaceDecl) { + if (!this.canEmitDeclarations(interfaceDecl)) { + return; + } + + var interfaceName = interfaceDecl.identifier.text(); + this.emitDeclarationComments(interfaceDecl); + var interfacePullDecl = this.semanticInfoChain.getDeclForAST(interfaceDecl); + this.emitDeclFlags(interfaceDecl, "interface"); + this.declFile.Write(interfaceName); + + this.emitTypeParameters(interfaceDecl.typeParameterList); + this.emitHeritageClauses(interfaceDecl.heritageClauses); + this.declFile.WriteLine(" {"); + + this.indenter.increaseIndent(); + + this.emitSeparatedList(interfaceDecl.body.typeMembers); + + this.indenter.decreaseIndent(); + + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForImportDeclaration = function (importDeclAST) { + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); + var importSymbol = importDecl.getSymbol(); + var isExportedImportDecl = TypeScript.hasModifier(importDeclAST.modifiers, 1 /* Exported */); + + if (isExportedImportDecl || importSymbol.typeUsedExternally() || TypeScript.PullContainerSymbol.usedAsSymbol(importSymbol.getContainer(), importSymbol)) { + this.emitDeclarationComments(importDeclAST); + this.emitIndent(); + if (isExportedImportDecl) { + this.declFile.Write("export "); + } + this.declFile.Write("import "); + this.declFile.Write(importDeclAST.identifier.text() + " = "); + if (importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + this.declFile.WriteLine("require(" + importDeclAST.moduleReference.stringLiteral.text() + ");"); + } else { + this.declFile.WriteLine(TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(importDeclAST.moduleReference.moduleName) + ";"); + } + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForEnumDeclaration = function (moduleDecl) { + if (!this.canEmitDeclarations(moduleDecl)) { + return; + } + + this.emitDeclarationComments(moduleDecl); + var modulePullDecl = this.semanticInfoChain.getDeclForAST(moduleDecl); + this.emitDeclFlags(moduleDecl, "enum"); + this.declFile.WriteLine(moduleDecl.identifier.text() + " {"); + + this.indenter.increaseIndent(); + var membersLen = moduleDecl.enumElements.nonSeparatorCount(); + for (var j = 0; j < membersLen; j++) { + var memberDecl = moduleDecl.enumElements.nonSeparatorAt(j); + var enumElement = memberDecl; + var enumElementDecl = this.semanticInfoChain.getDeclForAST(enumElement); + this.emitDeclarationComments(enumElement); + this.emitIndent(); + this.declFile.Write(enumElement.propertyName.text()); + if (enumElementDecl.constantValue !== null) { + this.declFile.Write(" = " + enumElementDecl.constantValue); + } + this.declFile.WriteLine(","); + } + this.indenter.decreaseIndent(); + + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForModuleDeclaration = function (moduleDecl) { + var name = moduleDecl.stringLiteral || TypeScript.ArrayUtilities.first(TypeScript.ASTHelpers.getModuleNames(moduleDecl.name)); + if (!this.canEmitDeclarations(name)) { + return; + } + + this.emitDeclarationComments(moduleDecl); + this.emitDeclFlags(name, "module"); + + if (moduleDecl.stringLiteral) { + this.declFile.Write(moduleDecl.stringLiteral.text()); + } else { + this.declFile.Write(TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(moduleDecl.name)); + } + + this.declFile.WriteLine(" {"); + this.indenter.increaseIndent(); + + this.emitDeclarationsForList(moduleDecl.moduleElements); + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForExportAssignment = function (ast) { + this.emitIndent(); + this.declFile.Write("export = "); + this.declFile.Write(ast.identifier.text()); + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.resolveScriptReference = function (document, reference) { + if (!this.emitOptions.compilationSettings().noResolve() || TypeScript.isRooted(reference)) { + return reference; + } + + var documentDir = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(TypeScript.getRootFilePath(document.fileName))); + var resolvedReferencePath = this.emitOptions.resolvePath(documentDir + reference); + return resolvedReferencePath; + }; + + DeclarationEmitter.prototype.emitReferencePaths = function (sourceUnit) { + if (this.emittedReferencePaths) { + return; + } + + var documents = []; + if (this.document.emitToOwnOutputFile()) { + var scriptReferences = this.document.referencedFiles; + var addedGlobalDocument = false; + for (var j = 0; j < scriptReferences.length; j++) { + var currentReference = this.resolveScriptReference(this.document, scriptReferences[j]); + var document = this.compiler.getDocument(currentReference); + + if (document && (document.emitToOwnOutputFile() || document.isDeclareFile() || !addedGlobalDocument)) { + documents = documents.concat(document); + + if (!document.isDeclareFile() && document.isExternalModule()) { + addedGlobalDocument = true; + } + } + } + } else { + var fileNames = this.compiler.fileNames(); + for (var i = 0; i < fileNames.length; i++) { + var doc = this.compiler.getDocument(fileNames[i]); + if (!doc.isDeclareFile() && !doc.isExternalModule()) { + var scriptReferences = doc.referencedFiles; + for (var j = 0; j < scriptReferences.length; j++) { + var currentReference = this.resolveScriptReference(doc, scriptReferences[j]); + var document = this.compiler.getDocument(currentReference); + + if (document && (document.isDeclareFile() || document.isExternalModule())) { + for (var k = 0; k < documents.length; k++) { + if (documents[k] === document) { + break; + } + } + + if (k === documents.length) { + documents = documents.concat(document); + } + } + } + } + } + } + + var emittingFilePath = documents.length ? TypeScript.getRootFilePath(this.emittingFileName) : null; + for (var i = 0; i < documents.length; i++) { + var document = documents[i]; + var declFileName; + if (document.isDeclareFile()) { + declFileName = document.fileName; + } else { + declFileName = this.compiler.mapOutputFileName(document, this.emitOptions, TypeScript.TypeScriptCompiler.mapToDTSFileName); + } + + declFileName = TypeScript.getRelativePathToFixedPath(emittingFilePath, declFileName, false); + this.declFile.WriteLine('/// '); + } + + this.emittedReferencePaths = true; + }; + + DeclarationEmitter.prototype.emitDeclarationsForSourceUnit = function (sourceUnit) { + this.emitReferencePaths(sourceUnit); + this.emitDeclarationsForList(sourceUnit.moduleElements); + }; + return DeclarationEmitter; + })(); + TypeScript.DeclarationEmitter = DeclarationEmitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var BloomFilter = (function () { + function BloomFilter(expectedCount) { + var m = Math.max(1, BloomFilter.computeM(expectedCount)); + var k = Math.max(1, BloomFilter.computeK(expectedCount)); + ; + + var sizeInEvenBytes = (m + 7) & ~7; + + this.bitArray = []; + for (var i = 0, len = sizeInEvenBytes; i < len; i++) { + this.bitArray[i] = false; + } + this.hashFunctionCount = k; + } + BloomFilter.computeM = function (expectedCount) { + var p = BloomFilter.falsePositiveProbability; + var n = expectedCount; + + var numerator = n * Math.log(p); + var denominator = Math.log(1.0 / Math.pow(2.0, Math.log(2.0))); + return Math.ceil(numerator / denominator); + }; + + BloomFilter.computeK = function (expectedCount) { + var n = expectedCount; + var m = BloomFilter.computeM(expectedCount); + + var temp = Math.log(2.0) * m / n; + return Math.round(temp); + }; + + BloomFilter.prototype.computeHash = function (key, seed) { + return TypeScript.Hash.computeMurmur2StringHashCode(key, seed); + }; + + BloomFilter.prototype.addKeys = function (keys) { + for (var name in keys) { + if (keys[name]) { + this.add(name); + } + } + }; + + BloomFilter.prototype.add = function (value) { + for (var i = 0; i < this.hashFunctionCount; i++) { + var hash = this.computeHash(value, i); + hash = hash % this.bitArray.length; + this.bitArray[Math.abs(hash)] = true; + } + }; + + BloomFilter.prototype.probablyContains = function (value) { + for (var i = 0; i < this.hashFunctionCount; i++) { + var hash = this.computeHash(value, i); + hash = hash % this.bitArray.length; + if (!this.bitArray[Math.abs(hash)]) { + return false; + } + } + + return true; + }; + + BloomFilter.prototype.isEquivalent = function (filter) { + return BloomFilter.isEquivalent(this.bitArray, filter.bitArray) && this.hashFunctionCount === filter.hashFunctionCount; + }; + + BloomFilter.isEquivalent = function (array1, array2) { + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; i++) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; + }; + BloomFilter.falsePositiveProbability = 0.0001; + return BloomFilter; + })(); + TypeScript.BloomFilter = BloomFilter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var IdentifierWalker = (function (_super) { + __extends(IdentifierWalker, _super); + function IdentifierWalker(list) { + _super.call(this); + this.list = list; + } + IdentifierWalker.prototype.visitToken = function (token) { + this.list[token.text()] = true; + }; + return IdentifierWalker; + })(TypeScript.SyntaxWalker); + TypeScript.IdentifierWalker = IdentifierWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CompilationSettings = (function () { + function CompilationSettings() { + this.propagateEnumConstants = false; + this.removeComments = false; + this.watch = false; + this.noResolve = false; + this.allowAutomaticSemicolonInsertion = true; + this.noImplicitAny = false; + this.noLib = false; + this.codeGenTarget = 0 /* EcmaScript3 */; + this.moduleGenTarget = 0 /* Unspecified */; + this.outFileOption = ""; + this.outDirOption = ""; + this.mapSourceFiles = false; + this.mapRoot = ""; + this.sourceRoot = ""; + this.generateDeclarationFiles = false; + this.useCaseSensitiveFileResolution = false; + this.gatherDiagnostics = false; + this.codepage = null; + this.createFileLog = false; + } + return CompilationSettings; + })(); + TypeScript.CompilationSettings = CompilationSettings; + + var ImmutableCompilationSettings = (function () { + function ImmutableCompilationSettings(propagateEnumConstants, removeComments, watch, noResolve, allowAutomaticSemicolonInsertion, noImplicitAny, noLib, codeGenTarget, moduleGenTarget, outFileOption, outDirOption, mapSourceFiles, mapRoot, sourceRoot, generateDeclarationFiles, useCaseSensitiveFileResolution, gatherDiagnostics, codepage, createFileLog) { + this._propagateEnumConstants = propagateEnumConstants; + this._removeComments = removeComments; + this._watch = watch; + this._noResolve = noResolve; + this._allowAutomaticSemicolonInsertion = allowAutomaticSemicolonInsertion; + this._noImplicitAny = noImplicitAny; + this._noLib = noLib; + this._codeGenTarget = codeGenTarget; + this._moduleGenTarget = moduleGenTarget; + this._outFileOption = outFileOption; + this._outDirOption = outDirOption; + this._mapSourceFiles = mapSourceFiles; + this._mapRoot = mapRoot; + this._sourceRoot = sourceRoot; + this._generateDeclarationFiles = generateDeclarationFiles; + this._useCaseSensitiveFileResolution = useCaseSensitiveFileResolution; + this._gatherDiagnostics = gatherDiagnostics; + this._codepage = codepage; + this._createFileLog = createFileLog; + } + ImmutableCompilationSettings.prototype.propagateEnumConstants = function () { + return this._propagateEnumConstants; + }; + ImmutableCompilationSettings.prototype.removeComments = function () { + return this._removeComments; + }; + ImmutableCompilationSettings.prototype.watch = function () { + return this._watch; + }; + ImmutableCompilationSettings.prototype.noResolve = function () { + return this._noResolve; + }; + ImmutableCompilationSettings.prototype.allowAutomaticSemicolonInsertion = function () { + return this._allowAutomaticSemicolonInsertion; + }; + ImmutableCompilationSettings.prototype.noImplicitAny = function () { + return this._noImplicitAny; + }; + ImmutableCompilationSettings.prototype.noLib = function () { + return this._noLib; + }; + ImmutableCompilationSettings.prototype.codeGenTarget = function () { + return this._codeGenTarget; + }; + ImmutableCompilationSettings.prototype.moduleGenTarget = function () { + return this._moduleGenTarget; + }; + ImmutableCompilationSettings.prototype.outFileOption = function () { + return this._outFileOption; + }; + ImmutableCompilationSettings.prototype.outDirOption = function () { + return this._outDirOption; + }; + ImmutableCompilationSettings.prototype.mapSourceFiles = function () { + return this._mapSourceFiles; + }; + ImmutableCompilationSettings.prototype.mapRoot = function () { + return this._mapRoot; + }; + ImmutableCompilationSettings.prototype.sourceRoot = function () { + return this._sourceRoot; + }; + ImmutableCompilationSettings.prototype.generateDeclarationFiles = function () { + return this._generateDeclarationFiles; + }; + ImmutableCompilationSettings.prototype.useCaseSensitiveFileResolution = function () { + return this._useCaseSensitiveFileResolution; + }; + ImmutableCompilationSettings.prototype.gatherDiagnostics = function () { + return this._gatherDiagnostics; + }; + ImmutableCompilationSettings.prototype.codepage = function () { + return this._codepage; + }; + ImmutableCompilationSettings.prototype.createFileLog = function () { + return this._createFileLog; + }; + + ImmutableCompilationSettings.defaultSettings = function () { + if (!ImmutableCompilationSettings._defaultSettings) { + ImmutableCompilationSettings._defaultSettings = ImmutableCompilationSettings.fromCompilationSettings(new CompilationSettings()); + } + + return ImmutableCompilationSettings._defaultSettings; + }; + + ImmutableCompilationSettings.fromCompilationSettings = function (settings) { + return new ImmutableCompilationSettings(settings.propagateEnumConstants, settings.removeComments, settings.watch, settings.noResolve, settings.allowAutomaticSemicolonInsertion, settings.noImplicitAny, settings.noLib, settings.codeGenTarget, settings.moduleGenTarget, settings.outFileOption, settings.outDirOption, settings.mapSourceFiles, settings.mapRoot, settings.sourceRoot, settings.generateDeclarationFiles, settings.useCaseSensitiveFileResolution, settings.gatherDiagnostics, settings.codepage, settings.createFileLog); + }; + + ImmutableCompilationSettings.prototype.toCompilationSettings = function () { + var result = new CompilationSettings(); + + var thisAsIndexable = this; + var resultAsIndexable = result; + for (var name in this) { + if (this.hasOwnProperty(name) && TypeScript.StringUtilities.startsWith(name, "_")) { + resultAsIndexable[name.substr(1)] = thisAsIndexable[name]; + } + } + + return result; + }; + return ImmutableCompilationSettings; + })(); + TypeScript.ImmutableCompilationSettings = ImmutableCompilationSettings; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (PullElementFlags) { + PullElementFlags[PullElementFlags["None"] = 0] = "None"; + PullElementFlags[PullElementFlags["Exported"] = 1] = "Exported"; + PullElementFlags[PullElementFlags["Private"] = 1 << 1] = "Private"; + PullElementFlags[PullElementFlags["Public"] = 1 << 2] = "Public"; + PullElementFlags[PullElementFlags["Ambient"] = 1 << 3] = "Ambient"; + PullElementFlags[PullElementFlags["Static"] = 1 << 4] = "Static"; + PullElementFlags[PullElementFlags["Optional"] = 1 << 7] = "Optional"; + PullElementFlags[PullElementFlags["Signature"] = 1 << 11] = "Signature"; + PullElementFlags[PullElementFlags["Enum"] = 1 << 12] = "Enum"; + PullElementFlags[PullElementFlags["ArrowFunction"] = 1 << 13] = "ArrowFunction"; + + PullElementFlags[PullElementFlags["ClassConstructorVariable"] = 1 << 14] = "ClassConstructorVariable"; + PullElementFlags[PullElementFlags["InitializedModule"] = 1 << 15] = "InitializedModule"; + PullElementFlags[PullElementFlags["InitializedDynamicModule"] = 1 << 16] = "InitializedDynamicModule"; + + PullElementFlags[PullElementFlags["MustCaptureThis"] = 1 << 18] = "MustCaptureThis"; + + PullElementFlags[PullElementFlags["DeclaredInAWithBlock"] = 1 << 21] = "DeclaredInAWithBlock"; + + PullElementFlags[PullElementFlags["HasReturnStatement"] = 1 << 22] = "HasReturnStatement"; + + PullElementFlags[PullElementFlags["PropertyParameter"] = 1 << 23] = "PropertyParameter"; + + PullElementFlags[PullElementFlags["IsAnnotatedWithAny"] = 1 << 24] = "IsAnnotatedWithAny"; + + PullElementFlags[PullElementFlags["HasDefaultArgs"] = 1 << 25] = "HasDefaultArgs"; + + PullElementFlags[PullElementFlags["ConstructorParameter"] = 1 << 26] = "ConstructorParameter"; + + PullElementFlags[PullElementFlags["ImplicitVariable"] = PullElementFlags.ClassConstructorVariable | PullElementFlags.InitializedModule | PullElementFlags.InitializedDynamicModule | PullElementFlags.Enum] = "ImplicitVariable"; + PullElementFlags[PullElementFlags["SomeInitializedModule"] = PullElementFlags.InitializedModule | PullElementFlags.InitializedDynamicModule | PullElementFlags.Enum] = "SomeInitializedModule"; + })(TypeScript.PullElementFlags || (TypeScript.PullElementFlags = {})); + var PullElementFlags = TypeScript.PullElementFlags; + + function hasModifier(modifiers, flag) { + for (var i = 0, n = modifiers.length; i < n; i++) { + if (TypeScript.hasFlag(modifiers[i], flag)) { + return true; + } + } + + return false; + } + TypeScript.hasModifier = hasModifier; + + (function (PullElementKind) { + PullElementKind[PullElementKind["None"] = 0] = "None"; + PullElementKind[PullElementKind["Global"] = 0] = "Global"; + + PullElementKind[PullElementKind["Script"] = 1 << 0] = "Script"; + PullElementKind[PullElementKind["Primitive"] = 1 << 1] = "Primitive"; + + PullElementKind[PullElementKind["Container"] = 1 << 2] = "Container"; + PullElementKind[PullElementKind["Class"] = 1 << 3] = "Class"; + PullElementKind[PullElementKind["Interface"] = 1 << 4] = "Interface"; + PullElementKind[PullElementKind["DynamicModule"] = 1 << 5] = "DynamicModule"; + PullElementKind[PullElementKind["Enum"] = 1 << 6] = "Enum"; + PullElementKind[PullElementKind["TypeAlias"] = 1 << 7] = "TypeAlias"; + PullElementKind[PullElementKind["ObjectLiteral"] = 1 << 8] = "ObjectLiteral"; + + PullElementKind[PullElementKind["Variable"] = 1 << 9] = "Variable"; + PullElementKind[PullElementKind["CatchVariable"] = 1 << 10] = "CatchVariable"; + PullElementKind[PullElementKind["Parameter"] = 1 << 11] = "Parameter"; + PullElementKind[PullElementKind["Property"] = 1 << 12] = "Property"; + PullElementKind[PullElementKind["TypeParameter"] = 1 << 13] = "TypeParameter"; + + PullElementKind[PullElementKind["Function"] = 1 << 14] = "Function"; + PullElementKind[PullElementKind["ConstructorMethod"] = 1 << 15] = "ConstructorMethod"; + PullElementKind[PullElementKind["Method"] = 1 << 16] = "Method"; + PullElementKind[PullElementKind["FunctionExpression"] = 1 << 17] = "FunctionExpression"; + + PullElementKind[PullElementKind["GetAccessor"] = 1 << 18] = "GetAccessor"; + PullElementKind[PullElementKind["SetAccessor"] = 1 << 19] = "SetAccessor"; + + PullElementKind[PullElementKind["CallSignature"] = 1 << 20] = "CallSignature"; + PullElementKind[PullElementKind["ConstructSignature"] = 1 << 21] = "ConstructSignature"; + PullElementKind[PullElementKind["IndexSignature"] = 1 << 22] = "IndexSignature"; + + PullElementKind[PullElementKind["ObjectType"] = 1 << 23] = "ObjectType"; + PullElementKind[PullElementKind["FunctionType"] = 1 << 24] = "FunctionType"; + PullElementKind[PullElementKind["ConstructorType"] = 1 << 25] = "ConstructorType"; + + PullElementKind[PullElementKind["EnumMember"] = 1 << 26] = "EnumMember"; + + PullElementKind[PullElementKind["WithBlock"] = 1 << 27] = "WithBlock"; + PullElementKind[PullElementKind["CatchBlock"] = 1 << 28] = "CatchBlock"; + + PullElementKind[PullElementKind["All"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Container | PullElementKind.Class | PullElementKind.Interface | PullElementKind.DynamicModule | PullElementKind.Enum | PullElementKind.TypeAlias | PullElementKind.ObjectLiteral | PullElementKind.Variable | PullElementKind.Parameter | PullElementKind.Property | PullElementKind.TypeParameter | PullElementKind.Function | PullElementKind.ConstructorMethod | PullElementKind.Method | PullElementKind.FunctionExpression | PullElementKind.GetAccessor | PullElementKind.SetAccessor | PullElementKind.CallSignature | PullElementKind.ConstructSignature | PullElementKind.IndexSignature | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.EnumMember | PullElementKind.WithBlock | PullElementKind.CatchBlock] = "All"; + + PullElementKind[PullElementKind["SomeFunction"] = PullElementKind.Function | PullElementKind.ConstructorMethod | PullElementKind.Method | PullElementKind.FunctionExpression | PullElementKind.GetAccessor | PullElementKind.SetAccessor] = "SomeFunction"; + + PullElementKind[PullElementKind["SomeValue"] = PullElementKind.Variable | PullElementKind.Parameter | PullElementKind.Property | PullElementKind.EnumMember | PullElementKind.SomeFunction] = "SomeValue"; + + PullElementKind[PullElementKind["SomeType"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.ObjectLiteral | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.TypeParameter] = "SomeType"; + + PullElementKind[PullElementKind["AcceptableAlias"] = PullElementKind.Variable | PullElementKind.SomeFunction | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.Container | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType] = "AcceptableAlias"; + + PullElementKind[PullElementKind["SomeContainer"] = PullElementKind.Container | PullElementKind.DynamicModule | PullElementKind.TypeAlias] = "SomeContainer"; + + PullElementKind[PullElementKind["SomeSignature"] = PullElementKind.CallSignature | PullElementKind.ConstructSignature | PullElementKind.IndexSignature] = "SomeSignature"; + + PullElementKind[PullElementKind["SomeTypeReference"] = PullElementKind.Interface | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType] = "SomeTypeReference"; + + PullElementKind[PullElementKind["SomeInstantiatableType"] = PullElementKind.Class | PullElementKind.Interface | PullElementKind.TypeParameter] = "SomeInstantiatableType"; + })(TypeScript.PullElementKind || (TypeScript.PullElementKind = {})); + var PullElementKind = TypeScript.PullElementKind; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var pullDeclID = 0; + var sentinelEmptyPullDeclArray = []; + + var PullDecl = (function () { + function PullDecl(declName, displayName, kind, declFlags, semanticInfoChain) { + this.declID = pullDeclID++; + this.flags = 0 /* None */; + this.declGroups = null; + this.childDecls = null; + this.typeParameters = null; + this.synthesizedValDecl = null; + this.containerDecl = null; + this.childDeclTypeCache = null; + this.childDeclValueCache = null; + this.childDeclNamespaceCache = null; + this.childDeclTypeParameterCache = null; + this.name = declName; + this.kind = kind; + this.flags = declFlags; + this.semanticInfoChain = semanticInfoChain; + + if (displayName !== this.name) { + this.declDisplayName = displayName; + } + } + PullDecl.prototype.fileName = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.getParentPath = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.getParentDecl = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.isExternalModule = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.getEnclosingDecl = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype._getEnclosingDeclFromParentDecl = function () { + var decl = this; + while (decl) { + switch (decl.kind) { + default: + return decl; + case 512 /* Variable */: + case 8192 /* TypeParameter */: + case 2048 /* Parameter */: + case 128 /* TypeAlias */: + case 67108864 /* EnumMember */: + } + + decl = decl.getParentDecl(); + } + + TypeScript.Debug.fail(); + }; + + PullDecl.prototype.getDisplayName = function () { + return this.declDisplayName === undefined ? this.name : this.declDisplayName; + }; + + PullDecl.prototype.setSymbol = function (symbol) { + this.semanticInfoChain.setSymbolForDecl(this, symbol); + }; + + PullDecl.prototype.ensureSymbolIsBound = function () { + if (!this.hasBeenBound() && this.kind !== 1 /* Script */) { + var binder = this.semanticInfoChain.getBinder(); + binder.bindDeclToPullSymbol(this); + } + }; + + PullDecl.prototype.getSymbol = function () { + if (this.kind === 1 /* Script */) { + return null; + } + + this.ensureSymbolIsBound(); + + return this.semanticInfoChain.getSymbolForDecl(this); + }; + + PullDecl.prototype.hasSymbol = function () { + var symbol = this.semanticInfoChain.getSymbolForDecl(this); + return !!symbol; + }; + + PullDecl.prototype.setSignatureSymbol = function (signatureSymbol) { + this.semanticInfoChain.setSignatureSymbolForDecl(this, signatureSymbol); + }; + + PullDecl.prototype.getSignatureSymbol = function () { + this.ensureSymbolIsBound(); + return this.semanticInfoChain.getSignatureSymbolForDecl(this); + }; + + PullDecl.prototype.hasSignatureSymbol = function () { + var signatureSymbol = this.semanticInfoChain.getSignatureSymbolForDecl(this); + return !!signatureSymbol; + }; + + PullDecl.prototype.setFlags = function (flags) { + this.flags = flags; + }; + + PullDecl.prototype.setFlag = function (flags) { + this.flags |= flags; + }; + + PullDecl.prototype.setValueDecl = function (valDecl) { + this.synthesizedValDecl = valDecl; + valDecl.containerDecl = this; + }; + + PullDecl.prototype.getValueDecl = function () { + return this.synthesizedValDecl; + }; + + PullDecl.prototype.getContainerDecl = function () { + return this.containerDecl; + }; + + PullDecl.prototype.getChildDeclCache = function (declKind) { + if (declKind === 8192 /* TypeParameter */) { + if (!this.childDeclTypeParameterCache) { + this.childDeclTypeParameterCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclTypeParameterCache; + } else if (TypeScript.hasFlag(declKind, 164 /* SomeContainer */)) { + if (!this.childDeclNamespaceCache) { + this.childDeclNamespaceCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclNamespaceCache; + } else if (TypeScript.hasFlag(declKind, 58728795 /* SomeType */)) { + if (!this.childDeclTypeCache) { + this.childDeclTypeCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclTypeCache; + } else { + if (!this.childDeclValueCache) { + this.childDeclValueCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclValueCache; + } + }; + + PullDecl.prototype.addChildDecl = function (childDecl) { + if (childDecl.kind === 8192 /* TypeParameter */) { + if (!this.typeParameters) { + this.typeParameters = []; + } + this.typeParameters[this.typeParameters.length] = childDecl; + } else { + if (!this.childDecls) { + this.childDecls = []; + } + this.childDecls[this.childDecls.length] = childDecl; + } + + var declName = childDecl.name; + + if (!(childDecl.kind & 7340032 /* SomeSignature */)) { + var cache = this.getChildDeclCache(childDecl.kind); + var childrenOfName = cache[declName]; + if (!childrenOfName) { + childrenOfName = []; + } + + childrenOfName.push(childDecl); + cache[declName] = childrenOfName; + } + }; + + PullDecl.prototype.searchChildDecls = function (declName, searchKind) { + var cacheVal = null; + + if (searchKind & 58728795 /* SomeType */) { + cacheVal = this.childDeclTypeCache ? this.childDeclTypeCache[declName] : null; + } else if (searchKind & 164 /* SomeContainer */) { + cacheVal = this.childDeclNamespaceCache ? this.childDeclNamespaceCache[declName] : null; + } else { + cacheVal = this.childDeclValueCache ? this.childDeclValueCache[declName] : null; + } + + if (cacheVal) { + return cacheVal; + } else { + if (searchKind & 58728795 /* SomeType */) { + cacheVal = this.childDeclTypeParameterCache ? this.childDeclTypeParameterCache[declName] : null; + + if (cacheVal) { + return cacheVal; + } + } + + return sentinelEmptyPullDeclArray; + } + }; + + PullDecl.prototype.getChildDecls = function () { + return this.childDecls || sentinelEmptyPullDeclArray; + }; + + PullDecl.prototype.getTypeParameters = function () { + return this.typeParameters || sentinelEmptyPullDeclArray; + }; + + PullDecl.prototype.addVariableDeclToGroup = function (decl) { + if (!this.declGroups) { + this.declGroups = TypeScript.createIntrinsicsObject(); + } + + var declGroup = this.declGroups[decl.name]; + if (declGroup) { + declGroup.addDecl(decl); + } else { + declGroup = new PullDeclGroup(decl.name); + declGroup.addDecl(decl); + this.declGroups[decl.name] = declGroup; + } + }; + + PullDecl.prototype.getVariableDeclGroups = function () { + var declGroups = null; + + if (this.declGroups) { + for (var declName in this.declGroups) { + if (this.declGroups[declName]) { + if (declGroups === null) { + declGroups = []; + } + + declGroups.push(this.declGroups[declName].getDecls()); + } + } + } + + return declGroups || sentinelEmptyPullDeclArray; + }; + + PullDecl.prototype.hasBeenBound = function () { + return this.hasSymbol() || this.hasSignatureSymbol(); + }; + + PullDecl.prototype.isSynthesized = function () { + return false; + }; + + PullDecl.prototype.ast = function () { + return this.semanticInfoChain.getASTForDecl(this); + }; + + PullDecl.prototype.isRootDecl = function () { + throw TypeScript.Errors.abstract(); + }; + return PullDecl; + })(); + TypeScript.PullDecl = PullDecl; + + var RootPullDecl = (function (_super) { + __extends(RootPullDecl, _super); + function RootPullDecl(name, fileName, kind, declFlags, semanticInfoChain, isExternalModule) { + _super.call(this, name, name, kind, declFlags, semanticInfoChain); + this.semanticInfoChain = semanticInfoChain; + this._isExternalModule = isExternalModule; + this._fileName = fileName; + } + RootPullDecl.prototype.fileName = function () { + return this._fileName; + }; + + RootPullDecl.prototype.getParentPath = function () { + return [this]; + }; + + RootPullDecl.prototype.getParentDecl = function () { + return null; + }; + + RootPullDecl.prototype.isExternalModule = function () { + return this._isExternalModule; + }; + + RootPullDecl.prototype.getEnclosingDecl = function () { + return this; + }; + + RootPullDecl.prototype.isRootDecl = function () { + return true; + }; + return RootPullDecl; + })(PullDecl); + TypeScript.RootPullDecl = RootPullDecl; + + var NormalPullDecl = (function (_super) { + __extends(NormalPullDecl, _super); + function NormalPullDecl(declName, displayName, kind, declFlags, parentDecl, addToParent) { + if (typeof addToParent === "undefined") { addToParent = true; } + _super.call(this, declName, displayName, kind, declFlags, parentDecl ? parentDecl.semanticInfoChain : null); + this.parentDecl = null; + this.parentPath = null; + + this.parentDecl = parentDecl; + if (addToParent) { + parentDecl.addChildDecl(this); + } + + if (this.parentDecl) { + if (this.parentDecl.isRootDecl()) { + this._rootDecl = this.parentDecl; + } else { + this._rootDecl = this.parentDecl._rootDecl; + } + } else { + TypeScript.Debug.assert(this.isSynthesized()); + this._rootDecl = null; + } + } + NormalPullDecl.prototype.fileName = function () { + return this._rootDecl.fileName(); + }; + + NormalPullDecl.prototype.getParentDecl = function () { + return this.parentDecl; + }; + + NormalPullDecl.prototype.getParentPath = function () { + if (!this.parentPath) { + var path = [this]; + var parentDecl = this.parentDecl; + + while (parentDecl) { + if (parentDecl && path[path.length - 1] !== parentDecl && !(parentDecl.kind & (256 /* ObjectLiteral */ | 8388608 /* ObjectType */))) { + path.unshift(parentDecl); + } + + parentDecl = parentDecl.getParentDecl(); + } + + this.parentPath = path; + } + + return this.parentPath; + }; + + NormalPullDecl.prototype.isExternalModule = function () { + return false; + }; + + NormalPullDecl.prototype.getEnclosingDecl = function () { + return this.parentDecl && this.parentDecl._getEnclosingDeclFromParentDecl(); + }; + + NormalPullDecl.prototype.isRootDecl = function () { + return false; + }; + return NormalPullDecl; + })(PullDecl); + TypeScript.NormalPullDecl = NormalPullDecl; + + var PullEnumElementDecl = (function (_super) { + __extends(PullEnumElementDecl, _super); + function PullEnumElementDecl(declName, displayName, parentDecl) { + _super.call(this, declName, displayName, 67108864 /* EnumMember */, 4 /* Public */, parentDecl); + this.constantValue = null; + } + return PullEnumElementDecl; + })(NormalPullDecl); + TypeScript.PullEnumElementDecl = PullEnumElementDecl; + + var PullFunctionExpressionDecl = (function (_super) { + __extends(PullFunctionExpressionDecl, _super); + function PullFunctionExpressionDecl(expressionName, declFlags, parentDecl, displayName) { + if (typeof displayName === "undefined") { displayName = ""; } + _super.call(this, "", displayName, 131072 /* FunctionExpression */, declFlags, parentDecl); + this.functionExpressionName = expressionName; + } + PullFunctionExpressionDecl.prototype.getFunctionExpressionName = function () { + return this.functionExpressionName; + }; + return PullFunctionExpressionDecl; + })(NormalPullDecl); + TypeScript.PullFunctionExpressionDecl = PullFunctionExpressionDecl; + + var PullSynthesizedDecl = (function (_super) { + __extends(PullSynthesizedDecl, _super); + function PullSynthesizedDecl(declName, displayName, kind, declFlags, parentDecl, semanticInfoChain) { + _super.call(this, declName, displayName, kind, declFlags, parentDecl, false); + this.semanticInfoChain = semanticInfoChain; + } + PullSynthesizedDecl.prototype.isSynthesized = function () { + return true; + }; + + PullSynthesizedDecl.prototype.fileName = function () { + return this._rootDecl ? this._rootDecl.fileName() : ""; + }; + return PullSynthesizedDecl; + })(NormalPullDecl); + TypeScript.PullSynthesizedDecl = PullSynthesizedDecl; + + var PullDeclGroup = (function () { + function PullDeclGroup(name) { + this.name = name; + this._decls = []; + } + PullDeclGroup.prototype.addDecl = function (decl) { + if (decl.name === this.name) { + this._decls[this._decls.length] = decl; + } + }; + + PullDeclGroup.prototype.getDecls = function () { + return this._decls; + }; + return PullDeclGroup; + })(); + TypeScript.PullDeclGroup = PullDeclGroup; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.pullSymbolID = 0; + TypeScript.sentinelEmptyArray = []; + + var PullSymbol = (function () { + function PullSymbol(name, declKind) { + this.pullSymbolID = ++TypeScript.pullSymbolID; + this._container = null; + this.type = null; + this._declarations = null; + this.isResolved = false; + this.isOptional = false; + this.inResolution = false; + this.isSynthesized = false; + this.isVarArg = false; + this.rootSymbol = null; + this._enclosingSignature = null; + this._docComments = null; + this.isPrinting = false; + this.name = name; + this.kind = declKind; + } + PullSymbol.prototype.isAny = function () { + return false; + }; + + PullSymbol.prototype.isType = function () { + return (this.kind & 58728795 /* SomeType */) !== 0; + }; + + PullSymbol.prototype.isTypeReference = function () { + return false; + }; + + PullSymbol.prototype.isSignature = function () { + return (this.kind & 7340032 /* SomeSignature */) !== 0; + }; + + PullSymbol.prototype.isArrayNamedTypeReference = function () { + return false; + }; + + PullSymbol.prototype.isPrimitive = function () { + return this.kind === 2 /* Primitive */; + }; + + PullSymbol.prototype.isAccessor = function () { + return false; + }; + + PullSymbol.prototype.isError = function () { + return false; + }; + + PullSymbol.prototype.isInterface = function () { + return this.kind === 16 /* Interface */; + }; + + PullSymbol.prototype.isMethod = function () { + return this.kind === 65536 /* Method */; + }; + + PullSymbol.prototype.isProperty = function () { + return this.kind === 4096 /* Property */; + }; + + PullSymbol.prototype.isAlias = function () { + return false; + }; + + PullSymbol.prototype.isContainer = function () { + return false; + }; + + PullSymbol.prototype.findAliasedTypeSymbols = function (scopeSymbol, skipScopeSymbolAliasesLookIn, lookIntoOnlyExportedAlias, aliasSymbols, visitedScopeDeclarations) { + if (typeof aliasSymbols === "undefined") { aliasSymbols = []; } + if (typeof visitedScopeDeclarations === "undefined") { visitedScopeDeclarations = []; } + var scopeDeclarations = scopeSymbol.getDeclarations(); + var scopeSymbolAliasesToLookIn = []; + + for (var i = 0; i < scopeDeclarations.length; i++) { + var scopeDecl = scopeDeclarations[i]; + if (!TypeScript.ArrayUtilities.contains(visitedScopeDeclarations, scopeDecl)) { + visitedScopeDeclarations.push(scopeDecl); + + var childDecls = scopeDecl.getChildDecls(); + for (var j = 0; j < childDecls.length; j++) { + var childDecl = childDecls[j]; + if (childDecl.kind === 128 /* TypeAlias */ && (!lookIntoOnlyExportedAlias || (childDecl.flags & 1 /* Exported */))) { + var symbol = childDecl.getSymbol(); + + if (PullContainerSymbol.usedAsSymbol(symbol, this) || (this.rootSymbol && PullContainerSymbol.usedAsSymbol(symbol, this.rootSymbol))) { + aliasSymbols.push(symbol); + return aliasSymbols; + } + + if (!skipScopeSymbolAliasesLookIn && PullSymbol._isExternalModuleReferenceAlias(symbol) && (!symbol.assignedContainer().hasExportAssignment() || (symbol.assignedContainer().getExportAssignedContainerSymbol() && symbol.assignedContainer().getExportAssignedContainerSymbol().kind === 32 /* DynamicModule */))) { + scopeSymbolAliasesToLookIn.push(symbol); + } + } + } + } + } + + for (var i = 0; i < scopeSymbolAliasesToLookIn.length; i++) { + var scopeSymbolAlias = scopeSymbolAliasesToLookIn[i]; + + aliasSymbols.push(scopeSymbolAlias); + var result = this.findAliasedTypeSymbols(scopeSymbolAlias.assignedContainer().hasExportAssignment() ? scopeSymbolAlias.assignedContainer().getExportAssignedContainerSymbol() : scopeSymbolAlias.assignedContainer(), false, true, aliasSymbols, visitedScopeDeclarations); + if (result) { + return result; + } + + aliasSymbols.pop(); + } + + return null; + }; + + PullSymbol.prototype.getExternalAliasedSymbols = function (scopeSymbol) { + if (!scopeSymbol) { + return null; + } + + var scopePath = scopeSymbol.pathToRoot(); + if (scopePath.length && scopePath[scopePath.length - 1].kind === 32 /* DynamicModule */) { + var symbols = this.findAliasedTypeSymbols(scopePath[scopePath.length - 1]); + return symbols; + } + + return null; + }; + + PullSymbol._isExternalModuleReferenceAlias = function (aliasSymbol) { + if (aliasSymbol) { + if (aliasSymbol.assignedValue()) { + return false; + } + + if (aliasSymbol.assignedType() && aliasSymbol.assignedType() !== aliasSymbol.assignedContainer()) { + return false; + } + + if (aliasSymbol.assignedContainer() && aliasSymbol.assignedContainer().kind !== 32 /* DynamicModule */) { + return false; + } + + return true; + } + + return false; + }; + + PullSymbol.prototype.getExportedInternalAliasSymbol = function (scopeSymbol) { + if (scopeSymbol) { + if (this.kind !== 128 /* TypeAlias */) { + var scopePath = scopeSymbol.pathToRoot(); + for (var i = 0; i < scopePath.length; i++) { + var internalAliases = this.findAliasedTypeSymbols(scopeSymbol, true, true); + if (internalAliases) { + TypeScript.Debug.assert(internalAliases.length === 1); + return internalAliases[0]; + } + } + } + } + + return null; + }; + + PullSymbol.prototype.getAliasSymbolName = function (scopeSymbol, aliasNameGetter, aliasPartsNameGetter, skipInternalAlias) { + if (!skipInternalAlias) { + var internalAlias = this.getExportedInternalAliasSymbol(scopeSymbol); + if (internalAlias) { + return aliasNameGetter(internalAlias); + } + } + + var externalAliases = this.getExternalAliasedSymbols(scopeSymbol); + + if (externalAliases && externalAliases[0] != this && PullSymbol._isExternalModuleReferenceAlias(externalAliases[externalAliases.length - 1])) { + var aliasFullName = aliasNameGetter(externalAliases[0]); + if (!aliasFullName) { + return null; + } + for (var i = 1, symbolsLen = externalAliases.length; i < symbolsLen; i++) { + aliasFullName = aliasFullName + "." + aliasPartsNameGetter(externalAliases[i]); + } + return aliasFullName; + } + + return null; + }; + + PullSymbol.prototype._getResolver = function () { + TypeScript.Debug.assert(this._declarations && this._declarations.length > 0); + return this._declarations[0].semanticInfoChain.getResolver(); + }; + + PullSymbol.prototype._resolveDeclaredSymbol = function () { + return this._getResolver().resolveDeclaredSymbol(this); + }; + + PullSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + var aliasName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getName(scopeSymbol, useConstraintInName); + }, function (symbol) { + return symbol.getName(); + }); + return aliasName || this.name; + }; + + PullSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { + var aliasDisplayName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getDisplayName(scopeSymbol, useConstraintInName); + }, function (symbol) { + return symbol.getDisplayName(); + }, skipInternalAliasName); + if (aliasDisplayName) { + return aliasDisplayName; + } + + var decls = this.getDeclarations(); + var name = decls.length && decls[0].getDisplayName(); + + return (name && name.length) ? name : this.name; + }; + + PullSymbol.prototype.getIsSpecialized = function () { + return false; + }; + + PullSymbol.prototype.getRootSymbol = function () { + if (!this.rootSymbol) { + return this; + } + return this.rootSymbol; + }; + PullSymbol.prototype.setRootSymbol = function (symbol) { + this.rootSymbol = symbol; + }; + + PullSymbol.prototype.setIsSynthesized = function (value) { + if (typeof value === "undefined") { value = true; } + TypeScript.Debug.assert(this.rootSymbol == null); + this.isSynthesized = value; + }; + + PullSymbol.prototype.getIsSynthesized = function () { + if (this.rootSymbol) { + return this.rootSymbol.getIsSynthesized(); + } + return this.isSynthesized; + }; + + PullSymbol.prototype.setEnclosingSignature = function (signature) { + this._enclosingSignature = signature; + }; + + PullSymbol.prototype.getEnclosingSignature = function () { + return this._enclosingSignature; + }; + + PullSymbol.prototype.addDeclaration = function (decl) { + TypeScript.Debug.assert(!!decl); + + if (this.rootSymbol) { + return; + } + + if (!this._declarations) { + this._declarations = [decl]; + } else { + this._declarations[this._declarations.length] = decl; + } + }; + + PullSymbol.prototype.getDeclarations = function () { + if (this.rootSymbol) { + return this.rootSymbol.getDeclarations(); + } + + if (!this._declarations) { + this._declarations = []; + } + + return this._declarations; + }; + + PullSymbol.prototype.hasDeclaration = function (decl) { + if (!this._declarations) { + return false; + } + + return TypeScript.ArrayUtilities.any(this._declarations, function (eachDecl) { + return eachDecl === decl; + }); + }; + + PullSymbol.prototype.setContainer = function (containerSymbol) { + if (this.rootSymbol) { + return; + } + + this._container = containerSymbol; + }; + + PullSymbol.prototype.getContainer = function () { + if (this.rootSymbol) { + return this.rootSymbol.getContainer(); + } + + return this._container; + }; + + PullSymbol.prototype.setResolved = function () { + this.isResolved = true; + this.inResolution = false; + }; + + PullSymbol.prototype.startResolving = function () { + this.inResolution = true; + }; + + PullSymbol.prototype.setUnresolved = function () { + this.isResolved = false; + this.inResolution = false; + }; + + PullSymbol.prototype.anyDeclHasFlag = function (flag) { + var declarations = this.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + if (TypeScript.hasFlag(declarations[i].flags, flag)) { + return true; + } + } + return false; + }; + + PullSymbol.prototype.allDeclsHaveFlag = function (flag) { + var declarations = this.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + if (!TypeScript.hasFlag(declarations[i].flags, flag)) { + return false; + } + } + return true; + }; + + PullSymbol.prototype.pathToRoot = function () { + var path = []; + var node = this; + while (node) { + if (node.isType()) { + var associatedContainerSymbol = node.getAssociatedContainerType(); + if (associatedContainerSymbol) { + node = associatedContainerSymbol; + } + } + path[path.length] = node; + var nodeKind = node.kind; + if (nodeKind === 2048 /* Parameter */) { + break; + } else { + node = node.getContainer(); + } + } + return path; + }; + + PullSymbol.unqualifiedNameReferencesDifferentSymbolInScope = function (symbol, scopePath, endScopePathIndex) { + var declPath = scopePath[0].getDeclarations()[0].getParentPath(); + for (var i = 0, declIndex = declPath.length - 1; i <= endScopePathIndex; i++, declIndex--) { + if (scopePath[i].isContainer()) { + var scopeContainer = scopePath[i]; + if (symbol.isContainer()) { + var memberSymbol = scopeContainer.findContainedNonMemberContainer(symbol.name, 164 /* SomeContainer */); + if (memberSymbol && memberSymbol != symbol && memberSymbol.getDeclarations()[0].getParentDecl() == declPath[declIndex]) { + return true; + } + + var memberSymbol = scopeContainer.findNestedContainer(symbol.name, 164 /* SomeContainer */); + if (memberSymbol && memberSymbol != symbol) { + return true; + } + } else if (symbol.isType()) { + var memberSymbol = scopeContainer.findContainedNonMemberType(symbol.name, 58728795 /* SomeType */); + var symbolRootType = TypeScript.PullHelpers.getRootType(symbol); + if (memberSymbol && TypeScript.PullHelpers.getRootType(memberSymbol) != symbolRootType && memberSymbol.getDeclarations()[0].getParentDecl() == declPath[declIndex]) { + return true; + } + + var memberSymbol = scopeContainer.findNestedType(symbol.name, 58728795 /* SomeType */); + if (memberSymbol && TypeScript.PullHelpers.getRootType(memberSymbol) != symbolRootType) { + return true; + } + } + } + } + + return false; + }; + + PullSymbol.prototype.findQualifyingSymbolPathInScopeSymbol = function (scopeSymbol) { + var thisPath = this.pathToRoot(); + if (thisPath.length === 1) { + return thisPath; + } + + var scopeSymbolPath; + if (scopeSymbol) { + scopeSymbolPath = scopeSymbol.pathToRoot(); + } else { + return thisPath; + } + + var thisCommonAncestorIndex = TypeScript.ArrayUtilities.indexOf(thisPath, function (thisNode) { + return TypeScript.ArrayUtilities.contains(scopeSymbolPath, thisNode); + }); + if (thisCommonAncestorIndex > 0) { + var thisCommonAncestor = thisPath[thisCommonAncestorIndex]; + var scopeCommonAncestorIndex = TypeScript.ArrayUtilities.indexOf(scopeSymbolPath, function (scopeNode) { + return scopeNode === thisCommonAncestor; + }); + TypeScript.Debug.assert(thisPath.length - thisCommonAncestorIndex === scopeSymbolPath.length - scopeCommonAncestorIndex); + + for (; thisCommonAncestorIndex < thisPath.length; thisCommonAncestorIndex++, scopeCommonAncestorIndex++) { + if (!PullSymbol.unqualifiedNameReferencesDifferentSymbolInScope(thisPath[thisCommonAncestorIndex - 1], scopeSymbolPath, scopeCommonAncestorIndex)) { + break; + } + } + } + + if (thisCommonAncestorIndex >= 0 && thisCommonAncestorIndex < thisPath.length) { + return thisPath.slice(0, thisCommonAncestorIndex); + } else { + return thisPath; + } + }; + + PullSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + var str = this.getNameAndTypeName(scopeSymbol); + return str; + }; + + PullSymbol.prototype.getNamePartForFullName = function () { + return this.getDisplayName(null, true); + }; + + PullSymbol.prototype.fullName = function (scopeSymbol) { + var _this = this; + var path = this.pathToRoot(); + var fullName = ""; + + var aliasFullName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.fullName(scopeSymbol); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }); + if (aliasFullName) { + return aliasFullName; + } + + for (var i = 1; i < path.length; i++) { + var aliasFullName = path[i].getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol === _this ? null : symbol.fullName(scopeSymbol); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }); + if (aliasFullName) { + fullName = aliasFullName + "." + fullName; + break; + } + + var scopedName = path[i].getNamePartForFullName(); + if (path[i].kind === 32 /* DynamicModule */ && !TypeScript.isQuoted(scopedName)) { + break; + } + + if (scopedName === "") { + break; + } + + fullName = scopedName + "." + fullName; + } + + fullName = fullName + this.getNamePartForFullName(); + return fullName; + }; + + PullSymbol.prototype.getScopedName = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName) { + var path = this.findQualifyingSymbolPathInScopeSymbol(scopeSymbol); + var fullName = ""; + + var aliasFullName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getScopedName(scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }, skipInternalAliasName); + if (aliasFullName) { + return aliasFullName; + } + + for (var i = 1; i < path.length; i++) { + var kind = path[i].kind; + if (kind === 4 /* Container */ || kind === 32 /* DynamicModule */) { + var aliasFullName = path[i].getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getScopedName(scopeSymbol, skipTypeParametersInName, false, skipInternalAliasName); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }, skipInternalAliasName); + if (aliasFullName) { + fullName = aliasFullName + "." + fullName; + break; + } + + if (kind === 4 /* Container */) { + fullName = path[i].getDisplayName() + "." + fullName; + } else { + var displayName = path[i].getDisplayName(); + if (TypeScript.isQuoted(displayName)) { + fullName = displayName + "." + fullName; + } + break; + } + } else { + break; + } + } + fullName = fullName + this.getDisplayName(scopeSymbol, useConstraintInName, skipInternalAliasName); + return fullName; + }; + + PullSymbol.prototype.getScopedNameEx = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName) { + var name = this.getScopedName(scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName); + return TypeScript.MemberName.create(name); + }; + + PullSymbol.prototype.getTypeName = function (scopeSymbol, getPrettyTypeName) { + var memberName = this.getTypeNameEx(scopeSymbol, getPrettyTypeName); + return memberName.toString(); + }; + + PullSymbol.prototype.getTypeNameEx = function (scopeSymbol, getPrettyTypeName) { + var type = this.type; + if (type) { + var memberName = getPrettyTypeName ? this.getTypeNameForFunctionSignature("", scopeSymbol, getPrettyTypeName) : null; + if (!memberName) { + memberName = type.getScopedNameEx(scopeSymbol, false, true, getPrettyTypeName); + } + + return memberName; + } + return TypeScript.MemberName.create(""); + }; + + PullSymbol.prototype.getTypeNameForFunctionSignature = function (prefix, scopeSymbol, getPrettyTypeName) { + var type = this.type; + if (type && !type.isNamedTypeSymbol() && this.kind !== 4096 /* Property */ && this.kind !== 512 /* Variable */ && this.kind !== 2048 /* Parameter */) { + var signatures = type.getCallSignatures(); + if (signatures.length === 1 || (getPrettyTypeName && signatures.length)) { + var typeName = new TypeScript.MemberNameArray(); + var signatureName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, prefix, false, false, scopeSymbol, getPrettyTypeName); + typeName.addAll(signatureName); + return typeName; + } + } + + return null; + }; + + PullSymbol.prototype.getNameAndTypeName = function (scopeSymbol) { + var nameAndTypeName = this.getNameAndTypeNameEx(scopeSymbol); + return nameAndTypeName.toString(); + }; + + PullSymbol.prototype.getNameAndTypeNameEx = function (scopeSymbol) { + var type = this.type; + var nameStr = this.getDisplayName(scopeSymbol); + if (type) { + nameStr = nameStr + (this.isOptional ? "?" : ""); + var memberName = this.getTypeNameForFunctionSignature(nameStr, scopeSymbol); + if (!memberName) { + var typeNameEx = type.getScopedNameEx(scopeSymbol); + memberName = TypeScript.MemberName.create(typeNameEx, nameStr + ": ", ""); + } + return memberName; + } + return TypeScript.MemberName.create(nameStr); + }; + + PullSymbol.getTypeParameterString = function (typars, scopeSymbol, useContraintInName) { + return PullSymbol.getTypeParameterStringEx(typars, scopeSymbol, undefined, useContraintInName).toString(); + }; + + PullSymbol.getTypeParameterStringEx = function (typeParameters, scopeSymbol, getTypeParamMarkerInfo, useContraintInName) { + var builder = new TypeScript.MemberNameArray(); + builder.prefix = ""; + + if (typeParameters && typeParameters.length) { + builder.add(TypeScript.MemberName.create("<")); + + for (var i = 0; i < typeParameters.length; i++) { + if (i) { + builder.add(TypeScript.MemberName.create(", ")); + } + + if (getTypeParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + + builder.add(typeParameters[i].getScopedNameEx(scopeSymbol, false, useContraintInName)); + + if (getTypeParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + } + + builder.add(TypeScript.MemberName.create(">")); + } + + return builder; + }; + + PullSymbol.getIsExternallyVisible = function (symbol, fromIsExternallyVisibleSymbol, inIsExternallyVisibleSymbols) { + if (inIsExternallyVisibleSymbols) { + for (var i = 0; i < inIsExternallyVisibleSymbols.length; i++) { + if (inIsExternallyVisibleSymbols[i] === symbol) { + return true; + } + } + } else { + inIsExternallyVisibleSymbols = []; + } + + if (fromIsExternallyVisibleSymbol === symbol) { + return true; + } + + inIsExternallyVisibleSymbols.push(fromIsExternallyVisibleSymbol); + + var result = symbol.isExternallyVisible(inIsExternallyVisibleSymbols); + + TypeScript.Debug.assert(TypeScript.ArrayUtilities.last(inIsExternallyVisibleSymbols) === fromIsExternallyVisibleSymbol); + inIsExternallyVisibleSymbols.pop(); + + return result; + }; + + PullSymbol.prototype.isExternallyVisible = function (inIsExternallyVisibleSymbols) { + var kind = this.kind; + if (kind === 2 /* Primitive */) { + return true; + } + + if (this.rootSymbol) { + return PullSymbol.getIsExternallyVisible(this.rootSymbol, this, inIsExternallyVisibleSymbols); + } + + if (this.isType()) { + var associatedContainerSymbol = this.getAssociatedContainerType(); + if (associatedContainerSymbol) { + return PullSymbol.getIsExternallyVisible(associatedContainerSymbol, this, inIsExternallyVisibleSymbols); + } + } + + if (this.anyDeclHasFlag(2 /* Private */)) { + return false; + } + + var container = this.getContainer(); + if (container === null) { + var decls = this.getDeclarations(); + if (decls.length) { + var parentDecl = decls[0].getParentDecl(); + if (parentDecl) { + var parentSymbol = parentDecl.getSymbol(); + if (!parentSymbol || parentDecl.kind === 1 /* Script */) { + return true; + } + + return PullSymbol.getIsExternallyVisible(parentSymbol, this, inIsExternallyVisibleSymbols); + } + } + + return true; + } + + if (container.kind === 32 /* DynamicModule */ || (container.getAssociatedContainerType() && container.getAssociatedContainerType().kind === 32 /* DynamicModule */)) { + var containerSymbol = container.kind === 32 /* DynamicModule */ ? container : container.getAssociatedContainerType(); + if (PullContainerSymbol.usedAsSymbol(containerSymbol, this)) { + return true; + } + } + + if (!this.anyDeclHasFlag(1 /* Exported */) && kind !== 4096 /* Property */ && kind !== 65536 /* Method */) { + return false; + } + + return PullSymbol.getIsExternallyVisible(container, this, inIsExternallyVisibleSymbols); + }; + + PullSymbol.prototype.getDocCommentsOfDecl = function (decl) { + var ast = decl.ast(); + + if (ast) { + var enclosingModuleDeclaration = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(ast); + if (TypeScript.ASTHelpers.isLastNameOfModule(enclosingModuleDeclaration, ast)) { + return TypeScript.ASTHelpers.docComments(enclosingModuleDeclaration); + } + + if (ast.kind() !== 130 /* ModuleDeclaration */ || decl.kind !== 512 /* Variable */) { + return TypeScript.ASTHelpers.docComments(ast); + } + } + + return []; + }; + + PullSymbol.prototype.getDocCommentArray = function (symbol) { + var docComments = []; + if (!symbol) { + return docComments; + } + + var isParameter = symbol.kind === 2048 /* Parameter */; + var decls = symbol.getDeclarations(); + for (var i = 0; i < decls.length; i++) { + if (isParameter && decls[i].kind === 4096 /* Property */) { + continue; + } + docComments = docComments.concat(this.getDocCommentsOfDecl(decls[i])); + } + return docComments; + }; + + PullSymbol.getDefaultConstructorSymbolForDocComments = function (classSymbol) { + if (classSymbol.getHasDefaultConstructor()) { + var extendedTypes = classSymbol.getExtendedTypes(); + if (extendedTypes.length) { + return PullSymbol.getDefaultConstructorSymbolForDocComments(extendedTypes[0]); + } + } + + return classSymbol.type.getConstructSignatures()[0]; + }; + + PullSymbol.prototype.getDocCommentText = function (comments) { + var docCommentText = new Array(); + for (var c = 0; c < comments.length; c++) { + var commentText = this.getDocCommentTextValue(comments[c]); + if (commentText !== "") { + docCommentText.push(commentText); + } + } + return docCommentText.join("\n"); + }; + + PullSymbol.prototype.getDocCommentTextValue = function (comment) { + return this.cleanJSDocComment(comment.fullText()); + }; + + PullSymbol.prototype.docComments = function (useConstructorAsClass) { + var decls = this.getDeclarations(); + if (useConstructorAsClass && decls.length && decls[0].kind === 32768 /* ConstructorMethod */) { + var classDecl = decls[0].getParentDecl(); + return this.getDocCommentText(this.getDocCommentsOfDecl(classDecl)); + } + + if (this._docComments === null) { + var docComments = ""; + if (!useConstructorAsClass && this.kind === 2097152 /* ConstructSignature */ && decls.length && decls[0].kind === 8 /* Class */) { + var classSymbol = this.returnType; + var extendedTypes = classSymbol.getExtendedTypes(); + if (extendedTypes.length) { + docComments = extendedTypes[0].getConstructorMethod().docComments(); + } else { + docComments = ""; + } + } else if (this.kind === 2048 /* Parameter */) { + var parameterComments = []; + + var funcContainer = this.getEnclosingSignature(); + var funcDocComments = this.getDocCommentArray(funcContainer); + var paramComment = this.getParameterDocCommentText(this.getDisplayName(), funcDocComments); + if (paramComment != "") { + parameterComments.push(paramComment); + } + + var paramSelfComment = this.getDocCommentText(this.getDocCommentArray(this)); + if (paramSelfComment != "") { + parameterComments.push(paramSelfComment); + } + docComments = parameterComments.join("\n"); + } else { + var getSymbolComments = true; + if (this.kind === 16777216 /* FunctionType */) { + var functionSymbol = this.getFunctionSymbol(); + + if (functionSymbol) { + docComments = functionSymbol._docComments || ""; + getSymbolComments = false; + } else { + var declarationList = this.getDeclarations(); + if (declarationList.length > 0) { + docComments = declarationList[0].getSymbol()._docComments || ""; + getSymbolComments = false; + } + } + } + if (getSymbolComments) { + docComments = this.getDocCommentText(this.getDocCommentArray(this)); + if (docComments === "") { + if (this.kind === 1048576 /* CallSignature */) { + var callTypeSymbol = this.functionType; + if (callTypeSymbol && callTypeSymbol.getCallSignatures().length === 1) { + docComments = callTypeSymbol.docComments(); + } + } + } + } + } + + this._docComments = docComments; + } + + return this._docComments; + }; + + PullSymbol.prototype.getParameterDocCommentText = function (param, fncDocComments) { + if (fncDocComments.length === 0 || fncDocComments[0].kind() !== 6 /* MultiLineCommentTrivia */) { + return ""; + } + + for (var i = 0; i < fncDocComments.length; i++) { + var commentContents = fncDocComments[i].fullText(); + for (var j = commentContents.indexOf("@param", 0); 0 <= j; j = commentContents.indexOf("@param", j)) { + j += 6; + if (!this.isSpaceChar(commentContents, j)) { + continue; + } + + j = this.consumeLeadingSpace(commentContents, j); + if (j === -1) { + break; + } + + if (commentContents.charCodeAt(j) === 123 /* openBrace */) { + j++; + + var charCode = 0; + for (var curlies = 1; j < commentContents.length; j++) { + charCode = commentContents.charCodeAt(j); + + if (charCode === 123 /* openBrace */) { + curlies++; + continue; + } + + if (charCode === 125 /* closeBrace */) { + curlies--; + if (curlies === 0) { + break; + } else { + continue; + } + } + + if (charCode === 64 /* at */) { + break; + } + } + + if (j === commentContents.length) { + break; + } + + if (charCode === 64 /* at */) { + continue; + } + + j = this.consumeLeadingSpace(commentContents, j + 1); + if (j === -1) { + break; + } + } + + if (param !== commentContents.substr(j, param.length) || !this.isSpaceChar(commentContents, j + param.length)) { + continue; + } + + j = this.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 = this.consumeLeadingSpace(commentContents, paramLineIndex); + if (startSpaceRemovalIndex !== j && commentContents.charAt(startSpaceRemovalIndex) === "*") { + paramSpacesToRemove = j - startSpaceRemovalIndex - 1; + } + + return this.cleanJSDocComment(paramHelpString, paramSpacesToRemove); + } + } + + return ""; + }; + + PullSymbol.prototype.cleanJSDocComment = function (content, spacesToRemove) { + var docCommentLines = new Array(); + 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 = this.cleanDocCommentLine(line, true, spacesToRemove); + if (!cleanLinePos) { + continue; + } + + var docCommentText = ""; + var prevPos = cleanLinePos.start; + for (var i = line.indexOf("@", cleanLinePos.start); 0 <= i && i < cleanLinePos.end; i = line.indexOf("@", i + 1)) { + var wasInParamtag = inParamTag; + + if (line.indexOf("param", i + 1) === i + 1 && this.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.end); + } + + var newCleanPos = this.cleanDocCommentLine(docCommentText, false); + if (newCleanPos) { + if (spacesToRemove === undefined) { + spacesToRemove = cleanLinePos.jsDocSpacesRemoved; + } + docCommentLines.push(docCommentText); + } + } + + return docCommentLines.join("\n"); + }; + + PullSymbol.prototype.consumeLeadingSpace = function (line, startIndex, maxSpacesToRemove) { + var endIndex = line.length; + if (maxSpacesToRemove !== undefined) { + endIndex = TypeScript.MathPrototype.min(startIndex + maxSpacesToRemove, endIndex); + } + + for (; startIndex < endIndex; startIndex++) { + var charCode = line.charCodeAt(startIndex); + if (charCode !== 32 /* space */ && charCode !== 9 /* tab */) { + return startIndex; + } + } + + if (endIndex !== line.length) { + return endIndex; + } + + return -1; + }; + + PullSymbol.prototype.isSpaceChar = function (line, index) { + var length = line.length; + if (index < length) { + var charCode = line.charCodeAt(index); + + return charCode === 32 /* space */ || charCode === 9 /* tab */; + } + + return index === length; + }; + + PullSymbol.prototype.cleanDocCommentLine = function (line, jsDocStyleComment, jsDocLineSpaceToRemove) { + var nonSpaceIndex = this.consumeLeadingSpace(line, 0); + if (nonSpaceIndex !== -1) { + var jsDocSpacesRemoved = nonSpaceIndex; + if (jsDocStyleComment && line.charAt(nonSpaceIndex) === '*') { + var startIndex = nonSpaceIndex + 1; + nonSpaceIndex = this.consumeLeadingSpace(line, startIndex, jsDocLineSpaceToRemove); + + if (nonSpaceIndex !== -1) { + jsDocSpacesRemoved = nonSpaceIndex - startIndex; + } else { + return null; + } + } + + return { + start: nonSpaceIndex, + end: line.charAt(line.length - 1) === "\r" ? line.length - 1 : line.length, + jsDocSpacesRemoved: jsDocSpacesRemoved + }; + } + + return null; + }; + return PullSymbol; + })(); + TypeScript.PullSymbol = PullSymbol; + + + + var PullSignatureSymbol = (function (_super) { + __extends(PullSignatureSymbol, _super); + function PullSignatureSymbol(kind, _isDefinition) { + if (typeof _isDefinition === "undefined") { _isDefinition = false; } + _super.call(this, "", kind); + this._isDefinition = _isDefinition; + this._memberTypeParameterNameCache = null; + this._stringConstantOverload = undefined; + this.parameters = TypeScript.sentinelEmptyArray; + this._typeParameters = null; + this.returnType = null; + this.functionType = null; + this.hasOptionalParam = false; + this.nonOptionalParamCount = 0; + this.hasVarArgs = false; + this._allowedToReferenceTypeParameters = null; + this._instantiationCache = null; + this.hasBeenChecked = false; + this.inWrapCheck = false; + this.inWrapInfiniteExpandingReferenceCheck = false; + } + PullSignatureSymbol.prototype.isDefinition = function () { + return this._isDefinition; + }; + + PullSignatureSymbol.prototype.isGeneric = function () { + var typeParameters = this.getTypeParameters(); + return !!typeParameters && typeParameters.length !== 0; + }; + + PullSignatureSymbol.prototype.addParameter = function (parameter, isOptional) { + if (typeof isOptional === "undefined") { isOptional = false; } + if (this.parameters === TypeScript.sentinelEmptyArray) { + this.parameters = []; + } + + this.parameters[this.parameters.length] = parameter; + this.hasOptionalParam = isOptional; + + if (!parameter.getEnclosingSignature()) { + parameter.setEnclosingSignature(this); + } + + if (!isOptional) { + this.nonOptionalParamCount++; + } + }; + + PullSignatureSymbol.prototype.addTypeParameter = function (typeParameter) { + if (!this._typeParameters) { + this._typeParameters = []; + } + + if (!this._memberTypeParameterNameCache) { + this._memberTypeParameterNameCache = TypeScript.createIntrinsicsObject(); + } + + this._typeParameters[this._typeParameters.length] = typeParameter; + + this._memberTypeParameterNameCache[typeParameter.getName()] = typeParameter; + }; + + PullSignatureSymbol.prototype.addTypeParametersFromReturnType = function () { + var typeParameters = this.returnType.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + this.addTypeParameter(typeParameters[i]); + } + }; + + PullSignatureSymbol.prototype.getTypeParameters = function () { + if (!this._typeParameters) { + this._typeParameters = []; + } + + return this._typeParameters; + }; + + PullSignatureSymbol.prototype.findTypeParameter = function (name) { + var memberSymbol; + + if (!this._memberTypeParameterNameCache) { + this._memberTypeParameterNameCache = TypeScript.createIntrinsicsObject(); + + for (var i = 0; i < this.getTypeParameters().length; i++) { + this._memberTypeParameterNameCache[this._typeParameters[i].getName()] = this._typeParameters[i]; + } + } + + memberSymbol = this._memberTypeParameterNameCache[name]; + + return memberSymbol; + }; + + PullSignatureSymbol.prototype.getTypeParameterArgumentMap = function () { + return null; + }; + + PullSignatureSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._allowedToReferenceTypeParameters) { + this._allowedToReferenceTypeParameters = TypeScript.PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl(this.getDeclarations()[0]); + } + + return this._allowedToReferenceTypeParameters; + }; + + PullSignatureSymbol.prototype.addSpecialization = function (specializedVersionOfThisSignature, typeArgumentMap) { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._instantiationCache) { + this._instantiationCache = TypeScript.createIntrinsicsObject(); + } + + this._instantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)] = specializedVersionOfThisSignature; + }; + + PullSignatureSymbol.prototype.getSpecialization = function (typeArgumentMap) { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._instantiationCache) { + return null; + } + + var result = this._instantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)]; + return result || null; + }; + + PullSignatureSymbol.prototype.isStringConstantOverloadSignature = function () { + if (this._stringConstantOverload === undefined) { + var params = this.parameters; + this._stringConstantOverload = false; + for (var i = 0; i < params.length; i++) { + var paramType = params[i].type; + if (paramType && paramType.isPrimitive() && paramType.isStringConstant()) { + this._stringConstantOverload = true; + } + } + } + + return this._stringConstantOverload; + }; + + PullSignatureSymbol.prototype.getParameterTypeAtIndex = function (iParam) { + if (iParam < this.parameters.length - 1 || (iParam < this.parameters.length && !this.hasVarArgs)) { + return this.parameters[iParam].type; + } else if (this.hasVarArgs) { + var paramType = this.parameters[this.parameters.length - 1].type; + if (paramType.isArrayNamedTypeReference()) { + paramType = paramType.getElementType(); + } + return paramType; + } + + return null; + }; + + PullSignatureSymbol.getSignatureTypeMemberName = function (candidateSignature, signatures, scopeSymbol) { + var allMemberNames = new TypeScript.MemberNameArray(); + var signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, "", false, false, scopeSymbol, true, candidateSignature); + allMemberNames.addAll(signatureMemberName); + return allMemberNames; + }; + + PullSignatureSymbol.getSignaturesTypeNameEx = function (signatures, prefix, shortform, brackets, scopeSymbol, getPrettyTypeName, candidateSignature) { + var result = []; + if (!signatures) { + return result; + } + + var len = signatures.length; + if (!getPrettyTypeName && len > 1) { + shortform = false; + } + + var foundDefinition = false; + if (candidateSignature && candidateSignature.isDefinition() && len > 1) { + candidateSignature = null; + } + + for (var i = 0; i < len; i++) { + if (len > 1 && signatures[i].isDefinition()) { + foundDefinition = true; + continue; + } + + var signature = signatures[i]; + if (getPrettyTypeName && candidateSignature) { + signature = candidateSignature; + } + + result.push(signature.getSignatureTypeNameEx(prefix, shortform, brackets, scopeSymbol)); + if (getPrettyTypeName) { + break; + } + } + + if (getPrettyTypeName && result.length && len > 1) { + var lastMemberName = result[result.length - 1]; + for (var i = i + 1; i < len; i++) { + if (signatures[i].isDefinition()) { + foundDefinition = true; + break; + } + } + var overloadString = TypeScript.getLocalizedText(TypeScript.DiagnosticCode._0_overload_s, [foundDefinition ? len - 2 : len - 1]); + lastMemberName.add(TypeScript.MemberName.create(overloadString)); + } + + return result; + }; + + PullSignatureSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + var s = this.getSignatureTypeNameEx(this.getScopedNameEx().toString(), false, false, scopeSymbol, undefined, useConstraintInName).toString(); + return s; + }; + + PullSignatureSymbol.prototype.getSignatureTypeNameEx = function (prefix, shortform, brackets, scopeSymbol, getParamMarkerInfo, getTypeParamMarkerInfo) { + var typeParamterBuilder = new TypeScript.MemberNameArray(); + + typeParamterBuilder.add(PullSymbol.getTypeParameterStringEx(this.getTypeParameters(), scopeSymbol, getTypeParamMarkerInfo, true)); + + if (brackets) { + typeParamterBuilder.add(TypeScript.MemberName.create("[")); + } else { + typeParamterBuilder.add(TypeScript.MemberName.create("(")); + } + + var builder = new TypeScript.MemberNameArray(); + builder.prefix = prefix; + + if (getTypeParamMarkerInfo) { + builder.prefix = prefix; + builder.addAll(typeParamterBuilder.entries); + } else { + builder.prefix = prefix + typeParamterBuilder.toString(); + } + + var params = this.parameters; + var paramLen = params.length; + for (var i = 0; i < paramLen; i++) { + var paramType = params[i].type; + var typeString = paramType ? ": " : ""; + var paramIsVarArg = params[i].isVarArg; + var varArgPrefix = paramIsVarArg ? "..." : ""; + var optionalString = (!paramIsVarArg && params[i].isOptional) ? "?" : ""; + if (getParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + builder.add(TypeScript.MemberName.create(varArgPrefix + params[i].getScopedNameEx(scopeSymbol).toString() + optionalString + typeString)); + if (paramType) { + builder.add(paramType.getScopedNameEx(scopeSymbol)); + } + if (getParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + if (i < paramLen - 1) { + builder.add(TypeScript.MemberName.create(", ")); + } + } + + 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) { + builder.add(this.returnType.getScopedNameEx(scopeSymbol)); + } else { + builder.add(TypeScript.MemberName.create("any")); + } + + return builder; + }; + + PullSignatureSymbol.prototype.forAllParameterTypes = function (length, predicate) { + if (this.parameters.length < length && !this.hasVarArgs) { + length = this.parameters.length; + } + + for (var i = 0; i < length; i++) { + var paramType = this.getParameterTypeAtIndex(i); + if (!predicate(paramType, i)) { + return false; + } + } + + return true; + }; + + PullSignatureSymbol.prototype.forAllCorrespondingParameterTypesInThisAndOtherSignature = function (otherSignature, predicate) { + var length; + if (this.hasVarArgs) { + length = otherSignature.hasVarArgs ? Math.max(this.parameters.length, otherSignature.parameters.length) : otherSignature.parameters.length; + } else { + length = otherSignature.hasVarArgs ? this.parameters.length : Math.min(this.parameters.length, otherSignature.parameters.length); + } + + for (var i = 0; i < length; i++) { + var thisParamType = this.getParameterTypeAtIndex(i); + var otherParamType = otherSignature.getParameterTypeAtIndex(i); + if (!predicate(thisParamType, otherParamType, i)) { + return false; + } + } + + return true; + }; + + PullSignatureSymbol.prototype.wrapsSomeTypeParameter = function (typeParameterArgumentMap) { + return this.getWrappingTypeParameterID(typeParameterArgumentMap) !== 0; + }; + + PullSignatureSymbol.prototype.getWrappingTypeParameterID = function (typeParameterArgumentMap) { + var signature = this; + if (signature.inWrapCheck) { + return 0; + } + + this._wrapsTypeParameterCache = this._wrapsTypeParameterCache || new TypeScript.WrapsTypeParameterCache(); + + var wrappingTypeParameterID = this._wrapsTypeParameterCache.getWrapsTypeParameter(typeParameterArgumentMap); + if (wrappingTypeParameterID === undefined) { + wrappingTypeParameterID = this.getWrappingTypeParameterIDWorker(typeParameterArgumentMap); + this._wrapsTypeParameterCache.setWrapsTypeParameter(typeParameterArgumentMap, wrappingTypeParameterID); + } + + return wrappingTypeParameterID; + }; + + PullSignatureSymbol.prototype.getWrappingTypeParameterIDWorker = function (typeParameterArgumentMap) { + var signature = this; + signature.inWrapCheck = true; + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(signature); + var wrappingTypeParameterID = signature.returnType ? signature.returnType.getWrappingTypeParameterID(typeParameterArgumentMap) : 0; + + var parameters = signature.parameters; + for (var i = 0; !wrappingTypeParameterID && i < parameters.length; i++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(parameters[i]); + wrappingTypeParameterID = parameters[i].type.getWrappingTypeParameterID(typeParameterArgumentMap); + } + + signature.inWrapCheck = false; + + return wrappingTypeParameterID; + }; + + PullSignatureSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference = function (enclosingType, knownWrapMap) { + var wrapsIntoInfinitelyExpandingTypeReference = knownWrapMap.valueAt(this.pullSymbolID, enclosingType.pullSymbolID); + if (wrapsIntoInfinitelyExpandingTypeReference != undefined) { + return wrapsIntoInfinitelyExpandingTypeReference; + } + + if (this.inWrapInfiniteExpandingReferenceCheck) { + return false; + } + + this.inWrapInfiniteExpandingReferenceCheck = true; + wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker(enclosingType, knownWrapMap); + knownWrapMap.setValueAt(this.pullSymbolID, enclosingType.pullSymbolID, wrapsIntoInfinitelyExpandingTypeReference); + this.inWrapInfiniteExpandingReferenceCheck = false; + + return wrapsIntoInfinitelyExpandingTypeReference; + }; + + PullSignatureSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker = function (enclosingType, knownWrapMap) { + if (this.returnType && this.returnType._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; + } + + var parameters = this.parameters; + + for (var i = 0; i < parameters.length; i++) { + if (parameters[i].type && parameters[i].type._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; + } + } + + return false; + }; + return PullSignatureSymbol; + })(PullSymbol); + TypeScript.PullSignatureSymbol = PullSignatureSymbol; + + var PullTypeSymbol = (function (_super) { + __extends(PullTypeSymbol, _super); + function PullTypeSymbol(name, kind) { + _super.call(this, name, kind); + this._members = TypeScript.sentinelEmptyArray; + this._enclosedMemberTypes = null; + this._enclosedMemberContainers = null; + this._typeParameters = null; + this._allowedToReferenceTypeParameters = null; + this._specializedVersionsOfThisType = null; + this._arrayVersionOfThisType = null; + this._implementedTypes = null; + this._extendedTypes = null; + this._typesThatExplicitlyImplementThisType = null; + this._typesThatExtendThisType = null; + this._callSignatures = null; + this._allCallSignatures = null; + this._constructSignatures = null; + this._allConstructSignatures = null; + this._indexSignatures = null; + this._allIndexSignatures = null; + this._allIndexSignaturesOfAugmentedType = null; + this._memberNameCache = null; + this._enclosedTypeNameCache = null; + this._enclosedContainerCache = null; + this._typeParameterNameCache = null; + this._containedNonMemberNameCache = null; + this._containedNonMemberTypeNameCache = null; + this._containedNonMemberContainerCache = null; + this._simpleInstantiationCache = null; + this._complexInstantiationCache = null; + this._hasGenericSignature = false; + this._hasGenericMember = false; + this._hasBaseTypeConflict = false; + this._knownBaseTypeCount = 0; + this._associatedContainerTypeSymbol = null; + this._constructorMethod = null; + this._hasDefaultConstructor = false; + this._functionSymbol = null; + this._inMemberTypeNameEx = false; + this.inSymbolPrivacyCheck = false; + this.inWrapCheck = false; + this.inWrapInfiniteExpandingReferenceCheck = false; + this.typeReference = null; + this._widenedType = null; + this._isArrayNamedTypeReference = undefined; + this.type = this; + } + PullTypeSymbol.prototype.isArrayNamedTypeReference = function () { + if (this._isArrayNamedTypeReference === undefined) { + this._isArrayNamedTypeReference = this.computeIsArrayNamedTypeReference(); + } + + return this._isArrayNamedTypeReference; + }; + + PullTypeSymbol.prototype.computeIsArrayNamedTypeReference = function () { + var typeArgs = this.getTypeArguments(); + if (typeArgs && this.getTypeArguments().length === 1 && this.name === "Array") { + var declaration = this.getDeclarations()[0]; + + if (declaration && declaration.getParentDecl() && declaration.getParentDecl().getParentDecl() === null) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.isType = function () { + return true; + }; + PullTypeSymbol.prototype.isClass = function () { + return this.kind === 8 /* Class */ || (this._constructorMethod !== null); + }; + PullTypeSymbol.prototype.isFunction = function () { + return (this.kind & (33554432 /* ConstructorType */ | 16777216 /* FunctionType */)) !== 0; + }; + PullTypeSymbol.prototype.isConstructor = function () { + return this.kind === 33554432 /* ConstructorType */ || (this._associatedContainerTypeSymbol && this._associatedContainerTypeSymbol.isClass()); + }; + PullTypeSymbol.prototype.isTypeParameter = function () { + return false; + }; + PullTypeSymbol.prototype.isTypeVariable = function () { + return false; + }; + PullTypeSymbol.prototype.isError = function () { + return false; + }; + PullTypeSymbol.prototype.isEnum = function () { + return this.kind === 64 /* Enum */; + }; + + PullTypeSymbol.prototype.getTypeParameterArgumentMap = function () { + return null; + }; + + PullTypeSymbol.prototype.isObject = function () { + return TypeScript.hasFlag(this.kind, 8 /* Class */ | 33554432 /* ConstructorType */ | 64 /* Enum */ | 16777216 /* FunctionType */ | 16 /* Interface */ | 8388608 /* ObjectType */ | 256 /* ObjectLiteral */); + }; + + PullTypeSymbol.prototype.isFunctionType = function () { + return this.getCallSignatures().length > 0 || this.getConstructSignatures().length > 0; + }; + + PullTypeSymbol.prototype.getKnownBaseTypeCount = function () { + return this._knownBaseTypeCount; + }; + PullTypeSymbol.prototype.resetKnownBaseTypeCount = function () { + this._knownBaseTypeCount = 0; + }; + PullTypeSymbol.prototype.incrementKnownBaseCount = function () { + this._knownBaseTypeCount++; + }; + + PullTypeSymbol.prototype.setHasBaseTypeConflict = function () { + this._hasBaseTypeConflict = true; + }; + PullTypeSymbol.prototype.hasBaseTypeConflict = function () { + return this._hasBaseTypeConflict; + }; + + PullTypeSymbol.prototype.hasMembers = function () { + if (this._members !== TypeScript.sentinelEmptyArray) { + return true; + } + + var parents = this.getExtendedTypes(); + + for (var i = 0; i < parents.length; i++) { + if (parents[i].hasMembers()) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.setHasGenericSignature = function () { + this._hasGenericSignature = true; + }; + PullTypeSymbol.prototype.getHasGenericSignature = function () { + return this._hasGenericSignature; + }; + + PullTypeSymbol.prototype.setHasGenericMember = function () { + this._hasGenericMember = true; + }; + PullTypeSymbol.prototype.getHasGenericMember = function () { + return this._hasGenericMember; + }; + + PullTypeSymbol.prototype.setAssociatedContainerType = function (type) { + this._associatedContainerTypeSymbol = type; + }; + + PullTypeSymbol.prototype.getAssociatedContainerType = function () { + return this._associatedContainerTypeSymbol; + }; + + PullTypeSymbol.prototype.getArrayType = function () { + return this._arrayVersionOfThisType; + }; + + PullTypeSymbol.prototype.getElementType = function () { + return null; + }; + + PullTypeSymbol.prototype.setArrayType = function (arrayType) { + this._arrayVersionOfThisType = arrayType; + }; + + PullTypeSymbol.prototype.getFunctionSymbol = function () { + return this._functionSymbol; + }; + + PullTypeSymbol.prototype.setFunctionSymbol = function (symbol) { + if (symbol) { + this._functionSymbol = symbol; + } + }; + + PullTypeSymbol.prototype.findContainedNonMember = function (name) { + if (!this._containedNonMemberNameCache) { + return null; + } + + return this._containedNonMemberNameCache[name]; + }; + + PullTypeSymbol.prototype.findContainedNonMemberType = function (typeName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + if (!this._containedNonMemberTypeNameCache) { + return null; + } + + var nonMemberSymbol = this._containedNonMemberTypeNameCache[typeName]; + + if (nonMemberSymbol && kind !== 0 /* None */) { + nonMemberSymbol = TypeScript.hasFlag(nonMemberSymbol.kind, kind) ? nonMemberSymbol : null; + } + + return nonMemberSymbol; + }; + + PullTypeSymbol.prototype.findContainedNonMemberContainer = function (containerName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + if (!this._containedNonMemberContainerCache) { + return null; + } + + var nonMemberSymbol = this._containedNonMemberContainerCache[containerName]; + + if (nonMemberSymbol && kind !== 0 /* None */) { + nonMemberSymbol = TypeScript.hasFlag(nonMemberSymbol.kind, kind) ? nonMemberSymbol : null; + } + + return nonMemberSymbol; + }; + + PullTypeSymbol.prototype.addMember = function (memberSymbol) { + if (!memberSymbol) { + return; + } + + memberSymbol.setContainer(this); + + if (!this._memberNameCache) { + this._memberNameCache = TypeScript.createIntrinsicsObject(); + } + + if (this._members === TypeScript.sentinelEmptyArray) { + this._members = []; + } + + this._members.push(memberSymbol); + this._memberNameCache[memberSymbol.name] = memberSymbol; + }; + + PullTypeSymbol.prototype.addEnclosedMemberType = function (enclosedType) { + if (!enclosedType) { + return; + } + + enclosedType.setContainer(this); + + if (!this._enclosedTypeNameCache) { + this._enclosedTypeNameCache = TypeScript.createIntrinsicsObject(); + } + + if (!this._enclosedMemberTypes) { + this._enclosedMemberTypes = []; + } + + this._enclosedMemberTypes[this._enclosedMemberTypes.length] = enclosedType; + this._enclosedTypeNameCache[enclosedType.name] = enclosedType; + }; + + PullTypeSymbol.prototype.addEnclosedMemberContainer = function (enclosedContainer) { + if (!enclosedContainer) { + return; + } + + enclosedContainer.setContainer(this); + + if (!this._enclosedContainerCache) { + this._enclosedContainerCache = TypeScript.createIntrinsicsObject(); + } + + if (!this._enclosedMemberContainers) { + this._enclosedMemberContainers = []; + } + + this._enclosedMemberContainers[this._enclosedMemberContainers.length] = enclosedContainer; + this._enclosedContainerCache[enclosedContainer.name] = enclosedContainer; + }; + + PullTypeSymbol.prototype.addEnclosedNonMember = function (enclosedNonMember) { + if (!enclosedNonMember) { + return; + } + + enclosedNonMember.setContainer(this); + + if (!this._containedNonMemberNameCache) { + this._containedNonMemberNameCache = TypeScript.createIntrinsicsObject(); + } + + this._containedNonMemberNameCache[enclosedNonMember.name] = enclosedNonMember; + }; + + PullTypeSymbol.prototype.addEnclosedNonMemberType = function (enclosedNonMemberType) { + if (!enclosedNonMemberType) { + return; + } + + enclosedNonMemberType.setContainer(this); + + if (!this._containedNonMemberTypeNameCache) { + this._containedNonMemberTypeNameCache = TypeScript.createIntrinsicsObject(); + } + + this._containedNonMemberTypeNameCache[enclosedNonMemberType.name] = enclosedNonMemberType; + }; + + PullTypeSymbol.prototype.addEnclosedNonMemberContainer = function (enclosedNonMemberContainer) { + if (!enclosedNonMemberContainer) { + return; + } + + enclosedNonMemberContainer.setContainer(this); + + if (!this._containedNonMemberContainerCache) { + this._containedNonMemberContainerCache = TypeScript.createIntrinsicsObject(); + } + + this._containedNonMemberContainerCache[enclosedNonMemberContainer.name] = enclosedNonMemberContainer; + }; + + PullTypeSymbol.prototype.addTypeParameter = function (typeParameter) { + if (!typeParameter) { + return; + } + + if (!typeParameter.getContainer()) { + typeParameter.setContainer(this); + } + + if (!this._typeParameterNameCache) { + this._typeParameterNameCache = TypeScript.createIntrinsicsObject(); + } + + if (!this._typeParameters) { + this._typeParameters = []; + } + + this._typeParameters[this._typeParameters.length] = typeParameter; + this._typeParameterNameCache[typeParameter.getName()] = typeParameter; + }; + + PullTypeSymbol.prototype.getMembers = function () { + return this._members; + }; + + PullTypeSymbol.prototype.setHasDefaultConstructor = function (hasOne) { + if (typeof hasOne === "undefined") { hasOne = true; } + this._hasDefaultConstructor = hasOne; + }; + + PullTypeSymbol.prototype.getHasDefaultConstructor = function () { + return this._hasDefaultConstructor; + }; + + PullTypeSymbol.prototype.getConstructorMethod = function () { + return this._constructorMethod; + }; + + PullTypeSymbol.prototype.setConstructorMethod = function (constructorMethod) { + this._constructorMethod = constructorMethod; + }; + + PullTypeSymbol.prototype.getTypeParameters = function () { + if (!this._typeParameters) { + return TypeScript.sentinelEmptyArray; + } + + return this._typeParameters; + }; + + PullTypeSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + if (!!(this.kind && 8216 /* SomeInstantiatableType */) && this.isNamedTypeSymbol() && !this.isTypeParameter()) { + return this.getTypeParameters(); + } + + if (!this._allowedToReferenceTypeParameters) { + this._allowedToReferenceTypeParameters = TypeScript.PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl(this.getDeclarations()[0]); + } + + return this._allowedToReferenceTypeParameters; + }; + + PullTypeSymbol.prototype.isGeneric = function () { + return (this._typeParameters && this._typeParameters.length > 0) || this._hasGenericSignature || this._hasGenericMember || this.isArrayNamedTypeReference(); + }; + + PullTypeSymbol.prototype.canUseSimpleInstantiationCache = function (typeArgumentMap) { + if (this.isTypeParameter()) { + return true; + } + + var typeParameters = this.getTypeParameters(); + return typeArgumentMap && this.isNamedTypeSymbol() && typeParameters.length === 1 && typeArgumentMap[typeParameters[0].pullSymbolID].kind !== 8388608 /* ObjectType */; + }; + + PullTypeSymbol.prototype.getSimpleInstantiationCacheId = function (typeArgumentMap) { + if (this.isTypeParameter()) { + return typeArgumentMap[0].pullSymbolID; + } + + return typeArgumentMap[this.getTypeParameters()[0].pullSymbolID].pullSymbolID; + }; + + PullTypeSymbol.prototype.addSpecialization = function (specializedVersionOfThisType, typeArgumentMap) { + if (this.canUseSimpleInstantiationCache(typeArgumentMap)) { + if (!this._simpleInstantiationCache) { + this._simpleInstantiationCache = []; + } + + this._simpleInstantiationCache[this.getSimpleInstantiationCacheId(typeArgumentMap)] = specializedVersionOfThisType; + } else { + if (!this._complexInstantiationCache) { + this._complexInstantiationCache = TypeScript.createIntrinsicsObject(); + } + + this._complexInstantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)] = specializedVersionOfThisType; + } + + if (!this._specializedVersionsOfThisType) { + this._specializedVersionsOfThisType = []; + } + + this._specializedVersionsOfThisType.push(specializedVersionOfThisType); + }; + + PullTypeSymbol.prototype.getSpecialization = function (typeArgumentMap) { + if (this.canUseSimpleInstantiationCache(typeArgumentMap)) { + if (!this._simpleInstantiationCache) { + return null; + } + + var result = this._simpleInstantiationCache[this.getSimpleInstantiationCacheId(typeArgumentMap)]; + return result || null; + } else { + if (!this._complexInstantiationCache) { + return null; + } + + if (this.getAllowedToReferenceTypeParameters().length == 0) { + return this; + } + + var result = this._complexInstantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)]; + return result || null; + } + }; + + PullTypeSymbol.prototype.getKnownSpecializations = function () { + if (!this._specializedVersionsOfThisType) { + return TypeScript.sentinelEmptyArray; + } + + return this._specializedVersionsOfThisType; + }; + + PullTypeSymbol.prototype.getTypeArguments = function () { + return null; + }; + + PullTypeSymbol.prototype.getTypeArgumentsOrTypeParameters = function () { + return this.getTypeParameters(); + }; + + PullTypeSymbol.prototype.addCallOrConstructSignaturePrerequisiteBase = function (signature) { + if (signature.isGeneric()) { + this._hasGenericSignature = true; + } + + signature.functionType = this; + }; + + PullTypeSymbol.prototype.addCallSignaturePrerequisite = function (callSignature) { + if (!this._callSignatures) { + this._callSignatures = []; + } + + this.addCallOrConstructSignaturePrerequisiteBase(callSignature); + }; + + PullTypeSymbol.prototype.appendCallSignature = function (callSignature) { + this.addCallSignaturePrerequisite(callSignature); + this._callSignatures.push(callSignature); + }; + + PullTypeSymbol.prototype.insertCallSignatureAtIndex = function (callSignature, index) { + this.addCallSignaturePrerequisite(callSignature); + TypeScript.Debug.assert(index <= this._callSignatures.length); + if (index === this._callSignatures.length) { + this._callSignatures.push(callSignature); + } else { + this._callSignatures.splice(index, 0, callSignature); + } + }; + + PullTypeSymbol.prototype.addConstructSignaturePrerequisite = function (constructSignature) { + if (!this._constructSignatures) { + this._constructSignatures = []; + } + + this.addCallOrConstructSignaturePrerequisiteBase(constructSignature); + }; + + PullTypeSymbol.prototype.appendConstructSignature = function (constructSignature) { + this.addConstructSignaturePrerequisite(constructSignature); + this._constructSignatures.push(constructSignature); + }; + + PullTypeSymbol.prototype.insertConstructSignatureAtIndex = function (constructSignature, index) { + this.addConstructSignaturePrerequisite(constructSignature); + TypeScript.Debug.assert(index <= this._constructSignatures.length); + if (index === this._constructSignatures.length) { + this._constructSignatures.push(constructSignature); + } else { + this._constructSignatures.splice(index, 0, constructSignature); + } + }; + + PullTypeSymbol.prototype.addIndexSignature = function (indexSignature) { + if (!this._indexSignatures) { + this._indexSignatures = []; + } + + this._indexSignatures[this._indexSignatures.length] = indexSignature; + + if (indexSignature.isGeneric()) { + this._hasGenericSignature = true; + } + + indexSignature.functionType = this; + }; + + PullTypeSymbol.prototype.hasOwnCallSignatures = function () { + return this._callSignatures !== null; + }; + + PullTypeSymbol.prototype.getOwnCallSignatures = function () { + return this._callSignatures || TypeScript.sentinelEmptyArray; + }; + + PullTypeSymbol.prototype.getCallSignatures = function () { + if (this._allCallSignatures) { + return this._allCallSignatures; + } + + var signatures = []; + + if (this._callSignatures) { + signatures = signatures.concat(this._callSignatures); + } + + if (this._extendedTypes && this.kind === 16 /* Interface */) { + for (var i = 0; i < this._extendedTypes.length; i++) { + if (this._extendedTypes[i].hasBase(this)) { + continue; + } + + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._callSignatures, this._extendedTypes[i].getCallSignatures(), signatures); + } + } + + this._allCallSignatures = signatures; + + return signatures; + }; + + PullTypeSymbol.prototype.hasOwnConstructSignatures = function () { + return this._constructSignatures !== null; + }; + + PullTypeSymbol.prototype.getOwnDeclaredConstructSignatures = function () { + return this._constructSignatures || TypeScript.sentinelEmptyArray; + }; + + PullTypeSymbol.prototype.getConstructSignatures = function () { + if (this._allConstructSignatures) { + return this._allConstructSignatures; + } + + var signatures = []; + + if (this._constructSignatures) { + signatures = signatures.concat(this._constructSignatures); + } else if (this.isConstructor()) { + if (this._extendedTypes && this._extendedTypes.length > 0) { + signatures = this.getBaseClassConstructSignatures(this._extendedTypes[0]); + } else { + signatures = [this.getDefaultClassConstructSignature()]; + } + } + + if (this._extendedTypes && this.kind === 16 /* Interface */) { + for (var i = 0; i < this._extendedTypes.length; i++) { + if (this._extendedTypes[i].hasBase(this)) { + continue; + } + + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._constructSignatures, this._extendedTypes[i].getConstructSignatures(), signatures); + } + } + + this._allConstructSignatures = signatures; + + return signatures; + }; + + PullTypeSymbol.prototype.hasOwnIndexSignatures = function () { + return this._indexSignatures !== null; + }; + + PullTypeSymbol.prototype.getOwnIndexSignatures = function () { + return this._indexSignatures || TypeScript.sentinelEmptyArray; + }; + + PullTypeSymbol.prototype.getIndexSignatures = function () { + if (this._allIndexSignatures) { + return this._allIndexSignatures; + } + + var signatures = []; + + if (this._indexSignatures) { + signatures = signatures.concat(this._indexSignatures); + } + + if (this._extendedTypes) { + for (var i = 0; i < this._extendedTypes.length; i++) { + if (this._extendedTypes[i].hasBase(this)) { + continue; + } + + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._indexSignatures, this._extendedTypes[i].getIndexSignatures(), signatures); + } + } + + this._allIndexSignatures = signatures; + + return signatures; + }; + + PullTypeSymbol.prototype.getIndexSignaturesOfAugmentedType = function (resolver, globalFunctionInterface, globalObjectInterface) { + if (!this._allIndexSignaturesOfAugmentedType) { + var initialIndexSignatures = this.getIndexSignatures(); + var shouldAddFunctionSignatures = false; + var shouldAddObjectSignatures = false; + + if (globalFunctionInterface && this.isFunctionType() && this !== globalFunctionInterface) { + var functionIndexSignatures = globalFunctionInterface.getIndexSignatures(); + if (functionIndexSignatures.length) { + shouldAddFunctionSignatures = true; + } + } + + if (globalObjectInterface && this !== globalObjectInterface) { + var objectIndexSignatures = globalObjectInterface.getIndexSignatures(); + if (objectIndexSignatures.length) { + shouldAddObjectSignatures = true; + } + } + + if (shouldAddFunctionSignatures || shouldAddObjectSignatures) { + this._allIndexSignaturesOfAugmentedType = initialIndexSignatures.slice(0); + if (shouldAddFunctionSignatures) { + resolver._addUnhiddenSignaturesFromBaseType(initialIndexSignatures, functionIndexSignatures, this._allIndexSignaturesOfAugmentedType); + } + if (shouldAddObjectSignatures) { + if (shouldAddFunctionSignatures) { + initialIndexSignatures = initialIndexSignatures.concat(functionIndexSignatures); + } + resolver._addUnhiddenSignaturesFromBaseType(initialIndexSignatures, objectIndexSignatures, this._allIndexSignaturesOfAugmentedType); + } + } else { + this._allIndexSignaturesOfAugmentedType = initialIndexSignatures; + } + } + + return this._allIndexSignaturesOfAugmentedType; + }; + + PullTypeSymbol.prototype.getBaseClassConstructSignatures = function (baseType) { + TypeScript.Debug.assert(this.isConstructor() && baseType.isConstructor()); + var instanceTypeSymbol = this.getAssociatedContainerType(); + TypeScript.Debug.assert(instanceTypeSymbol.getDeclarations().length === 1); + if (baseType.hasBase(this)) { + return null; + } + + var baseConstructSignatures = baseType.getConstructSignatures(); + var signatures = []; + for (var i = 0; i < baseConstructSignatures.length; i++) { + var baseSignature = baseConstructSignatures[i]; + + baseSignature._resolveDeclaredSymbol(); + var currentSignature = new PullSignatureSymbol(2097152 /* ConstructSignature */, baseSignature.isDefinition()); + currentSignature.returnType = instanceTypeSymbol; + currentSignature.addTypeParametersFromReturnType(); + for (var j = 0; j < baseSignature.parameters.length; j++) { + currentSignature.addParameter(baseSignature.parameters[j], baseSignature.parameters[j].isOptional); + } + if (baseSignature.parameters.length > 0) { + currentSignature.hasVarArgs = baseSignature.parameters[baseSignature.parameters.length - 1].isVarArg; + } + + currentSignature.addDeclaration(instanceTypeSymbol.getDeclarations()[0]); + this.addCallOrConstructSignaturePrerequisiteBase(currentSignature); + signatures.push(currentSignature); + } + + return signatures; + }; + + PullTypeSymbol.prototype.getDefaultClassConstructSignature = function () { + TypeScript.Debug.assert(this.isConstructor()); + var instanceTypeSymbol = this.getAssociatedContainerType(); + TypeScript.Debug.assert(instanceTypeSymbol.getDeclarations().length == 1); + var signature = new PullSignatureSymbol(2097152 /* ConstructSignature */, true); + signature.returnType = instanceTypeSymbol; + signature.addTypeParametersFromReturnType(); + signature.addDeclaration(instanceTypeSymbol.getDeclarations()[0]); + this.addCallOrConstructSignaturePrerequisiteBase(signature); + + return signature; + }; + + PullTypeSymbol.prototype.addImplementedType = function (implementedType) { + if (!implementedType) { + return; + } + + if (!this._implementedTypes) { + this._implementedTypes = []; + } + + this._implementedTypes[this._implementedTypes.length] = implementedType; + + implementedType.addTypeThatExplicitlyImplementsThisType(this); + }; + + PullTypeSymbol.prototype.getImplementedTypes = function () { + if (!this._implementedTypes) { + return TypeScript.sentinelEmptyArray; + } + + return this._implementedTypes; + }; + + PullTypeSymbol.prototype.addExtendedType = function (extendedType) { + if (!extendedType) { + return; + } + + if (!this._extendedTypes) { + this._extendedTypes = []; + } + + this._extendedTypes[this._extendedTypes.length] = extendedType; + + extendedType.addTypeThatExtendsThisType(this); + }; + + PullTypeSymbol.prototype.getExtendedTypes = function () { + if (!this._extendedTypes) { + return TypeScript.sentinelEmptyArray; + } + + return this._extendedTypes; + }; + + PullTypeSymbol.prototype.addTypeThatExtendsThisType = function (type) { + if (!type) { + return; + } + + if (!this._typesThatExtendThisType) { + this._typesThatExtendThisType = []; + } + + this._typesThatExtendThisType[this._typesThatExtendThisType.length] = type; + }; + + PullTypeSymbol.prototype.getTypesThatExtendThisType = function () { + if (!this._typesThatExtendThisType) { + this._typesThatExtendThisType = []; + } + + return this._typesThatExtendThisType; + }; + + PullTypeSymbol.prototype.addTypeThatExplicitlyImplementsThisType = function (type) { + if (!type) { + return; + } + + if (!this._typesThatExplicitlyImplementThisType) { + this._typesThatExplicitlyImplementThisType = []; + } + + this._typesThatExplicitlyImplementThisType[this._typesThatExplicitlyImplementThisType.length] = type; + }; + + PullTypeSymbol.prototype.getTypesThatExplicitlyImplementThisType = function () { + if (!this._typesThatExplicitlyImplementThisType) { + this._typesThatExplicitlyImplementThisType = []; + } + + return this._typesThatExplicitlyImplementThisType; + }; + + PullTypeSymbol.prototype.hasBase = function (potentialBase, visited) { + if (typeof visited === "undefined") { visited = []; } + if (this === potentialBase || this.getRootSymbol() === potentialBase || this === potentialBase.getRootSymbol()) { + return true; + } + + if (TypeScript.ArrayUtilities.contains(visited, this)) { + return true; + } + + visited.push(this); + + var extendedTypes = this.getExtendedTypes(); + + for (var i = 0; i < extendedTypes.length; i++) { + if (extendedTypes[i].hasBase(potentialBase, visited)) { + return true; + } + } + + var implementedTypes = this.getImplementedTypes(); + + for (var i = 0; i < implementedTypes.length; i++) { + if (implementedTypes[i].hasBase(potentialBase, visited)) { + return true; + } + } + + visited.pop(); + + return false; + }; + + PullTypeSymbol.prototype.isValidBaseKind = function (baseType, isExtendedType) { + if (baseType.isError()) { + return false; + } + + var thisIsClass = this.isClass(); + if (isExtendedType) { + if (thisIsClass) { + return baseType.kind === 8 /* Class */; + } + } else { + if (!thisIsClass) { + return false; + } + } + + return !!(baseType.kind & (16 /* Interface */ | 8 /* Class */)); + }; + + PullTypeSymbol.prototype.findMember = function (name, lookInParent) { + var memberSymbol = null; + + if (this._memberNameCache) { + memberSymbol = this._memberNameCache[name]; + } + + if (memberSymbol || !lookInParent) { + return memberSymbol; + } + + if (this._extendedTypes) { + for (var i = 0; i < this._extendedTypes.length; i++) { + memberSymbol = this._extendedTypes[i].findMember(name, lookInParent); + + if (memberSymbol) { + return memberSymbol; + } + } + } + + return null; + }; + + PullTypeSymbol.prototype.findNestedType = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + var memberSymbol; + + if (!this._enclosedTypeNameCache) { + return null; + } + + memberSymbol = this._enclosedTypeNameCache[name]; + + if (memberSymbol && kind !== 0 /* None */) { + memberSymbol = TypeScript.hasFlag(memberSymbol.kind, kind) ? memberSymbol : null; + } + + return memberSymbol; + }; + + PullTypeSymbol.prototype.findNestedContainer = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + var memberSymbol; + + if (!this._enclosedContainerCache) { + return null; + } + + memberSymbol = this._enclosedContainerCache[name]; + + if (memberSymbol && kind !== 0 /* None */) { + memberSymbol = TypeScript.hasFlag(memberSymbol.kind, kind) ? memberSymbol : null; + } + + return memberSymbol; + }; + + PullTypeSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisiblity) { + var allMembers = []; + + if (this._members !== TypeScript.sentinelEmptyArray) { + for (var i = 0, n = this._members.length; i < n; i++) { + var member = this._members[i]; + if ((member.kind & searchDeclKind) && (memberVisiblity !== 2 /* externallyVisible */ || !member.anyDeclHasFlag(2 /* Private */))) { + allMembers[allMembers.length] = member; + } + } + } + + if (this._extendedTypes) { + var extenedMembersVisibility = memberVisiblity !== 0 /* all */ ? 2 /* externallyVisible */ : 0 /* all */; + + for (var i = 0, n = this._extendedTypes.length; i < n; i++) { + var extendedMembers = this._extendedTypes[i].getAllMembers(searchDeclKind, extenedMembersVisibility); + + for (var j = 0, m = extendedMembers.length; j < m; j++) { + var extendedMember = extendedMembers[j]; + if (!(this._memberNameCache && this._memberNameCache[extendedMember.name])) { + allMembers[allMembers.length] = extendedMember; + } + } + } + } + + if (this.isContainer()) { + if (this._enclosedMemberTypes) { + for (var i = 0; i < this._enclosedMemberTypes.length; i++) { + allMembers[allMembers.length] = this._enclosedMemberTypes[i]; + } + } + if (this._enclosedMemberContainers) { + for (var i = 0; i < this._enclosedMemberContainers.length; i++) { + allMembers[allMembers.length] = this._enclosedMemberContainers[i]; + } + } + } + + return allMembers; + }; + + PullTypeSymbol.prototype.findTypeParameter = function (name) { + if (!this._typeParameterNameCache) { + return null; + } + + return this._typeParameterNameCache[name]; + }; + + PullTypeSymbol.prototype.setResolved = function () { + _super.prototype.setResolved.call(this); + }; + + PullTypeSymbol.prototype.getNamePartForFullName = function () { + var name = _super.prototype.getNamePartForFullName.call(this); + + var typars = this.getTypeArgumentsOrTypeParameters(); + var typarString = PullSymbol.getTypeParameterString(typars, this, true); + return name + typarString; + }; + + PullTypeSymbol.prototype.getScopedName = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName) { + return this.getScopedNameEx(scopeSymbol, skipTypeParametersInName, useConstraintInName, false, false, skipInternalAliasName).toString(); + }; + + PullTypeSymbol.prototype.isNamedTypeSymbol = function () { + var kind = this.kind; + if (kind === 2 /* Primitive */ || kind === 8 /* Class */ || kind === 4 /* Container */ || kind === 32 /* DynamicModule */ || kind === 128 /* TypeAlias */ || kind === 64 /* Enum */ || kind === 8192 /* TypeParameter */ || ((kind === 16 /* Interface */ || kind === 8388608 /* ObjectType */) && this.name !== "")) { + return true; + } + + return false; + }; + + PullTypeSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + var s = this.getScopedNameEx(scopeSymbol, false, useConstraintInName).toString(); + return s; + }; + + PullTypeSymbol.prototype.getScopedNameEx = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName, shouldAllowArrayType) { + if (typeof shouldAllowArrayType === "undefined") { shouldAllowArrayType = true; } + if (this.isArrayNamedTypeReference() && shouldAllowArrayType) { + var elementType = this.getElementType(); + var elementMemberName = elementType ? (elementType.isArrayNamedTypeReference() || elementType.isNamedTypeSymbol() ? elementType.getScopedNameEx(scopeSymbol, false, false, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName) : elementType.getMemberTypeNameEx(false, scopeSymbol, getPrettyTypeName)) : TypeScript.MemberName.create("any"); + return TypeScript.MemberName.create(elementMemberName, "", "[]"); + } + + if (!this.isNamedTypeSymbol()) { + return this.getMemberTypeNameEx(true, scopeSymbol, getPrettyTypeName); + } + + if (skipTypeParametersInName) { + return TypeScript.MemberName.create(_super.prototype.getScopedName.call(this, scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName)); + } else { + var builder = new TypeScript.MemberNameArray(); + builder.prefix = _super.prototype.getScopedName.call(this, scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName); + + var typars = this.getTypeArgumentsOrTypeParameters(); + builder.add(PullSymbol.getTypeParameterStringEx(typars, scopeSymbol, getTypeParamMarkerInfo, useConstraintInName)); + + return builder; + } + }; + + PullTypeSymbol.prototype.hasOnlyOverloadCallSignatures = function () { + var members = this.getMembers(); + var callSignatures = this.getCallSignatures(); + var constructSignatures = this.getConstructSignatures(); + return members.length === 0 && constructSignatures.length === 0 && callSignatures.length > 1; + }; + + PullTypeSymbol.prototype.getTypeOfSymbol = function () { + var associatedContainerType = this.getAssociatedContainerType(); + if (associatedContainerType && associatedContainerType.isNamedTypeSymbol()) { + return associatedContainerType; + } + + var functionSymbol = this.getFunctionSymbol(); + if (functionSymbol && functionSymbol.kind === 16384 /* Function */ && !TypeScript.PullHelpers.isSymbolLocal(functionSymbol)) { + return TypeScript.PullHelpers.isExportedSymbolInClodule(functionSymbol) ? null : functionSymbol; + } + + return null; + }; + + PullTypeSymbol.prototype.getMemberTypeNameEx = function (topLevel, scopeSymbol, getPrettyTypeName) { + var members = this.getMembers(); + var callSignatures = this.getCallSignatures(); + var constructSignatures = this.getConstructSignatures(); + var indexSignatures = this.getIndexSignatures(); + + var typeOfSymbol = this.getTypeOfSymbol(); + if (typeOfSymbol) { + var nameForTypeOf = typeOfSymbol.getScopedNameEx(scopeSymbol, true); + return TypeScript.MemberName.create(nameForTypeOf, "typeof ", ""); + } + + if (members.length > 0 || callSignatures.length > 0 || constructSignatures.length > 0 || indexSignatures.length > 0) { + if (this._inMemberTypeNameEx) { + return TypeScript.MemberName.create("any"); + } + + this._inMemberTypeNameEx = true; + + var allMemberNames = new TypeScript.MemberNameArray(); + var curlies = !topLevel || indexSignatures.length !== 0; + var delim = "; "; + for (var i = 0; i < members.length; i++) { + if (members[i].kind === 65536 /* Method */ && members[i].type.hasOnlyOverloadCallSignatures()) { + var methodCallSignatures = members[i].type.getCallSignatures(); + var nameStr = members[i].getDisplayName(scopeSymbol) + (members[i].isOptional ? "?" : ""); + ; + var methodMemberNames = PullSignatureSymbol.getSignaturesTypeNameEx(methodCallSignatures, nameStr, false, false, scopeSymbol); + allMemberNames.addAll(methodMemberNames); + } else { + var memberTypeName = members[i].getNameAndTypeNameEx(scopeSymbol); + if (memberTypeName.isArray() && memberTypeName.delim === delim) { + allMemberNames.addAll(memberTypeName.entries); + } else { + allMemberNames.add(memberTypeName); + } + } + curlies = true; + } + + var getPrettyFunctionOverload = getPrettyTypeName && !curlies && this.hasOnlyOverloadCallSignatures(); + + var signatureCount = callSignatures.length + constructSignatures.length + indexSignatures.length; + var useShortFormSignature = !curlies && (signatureCount === 1); + var signatureMemberName; + + if (callSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(callSignatures, "", useShortFormSignature, false, scopeSymbol, getPrettyFunctionOverload); + allMemberNames.addAll(signatureMemberName); + } + + if (constructSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(constructSignatures, "new", useShortFormSignature, false, scopeSymbol); + allMemberNames.addAll(signatureMemberName); + } + + if (indexSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(indexSignatures, "", useShortFormSignature, true, scopeSymbol); + allMemberNames.addAll(signatureMemberName); + } + + if ((curlies) || (!getPrettyFunctionOverload && (signatureCount > 1) && topLevel)) { + allMemberNames.prefix = "{ "; + allMemberNames.suffix = "}"; + allMemberNames.delim = delim; + } else if (allMemberNames.entries.length > 1) { + allMemberNames.delim = delim; + } + + this._inMemberTypeNameEx = false; + + return allMemberNames; + } + + return TypeScript.MemberName.create("{}"); + }; + + PullTypeSymbol.prototype.getGenerativeTypeClassification = function (enclosingType) { + return 2 /* Closed */; + }; + + PullTypeSymbol.prototype.wrapsSomeTypeParameter = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + return this.getWrappingTypeParameterID(typeParameterArgumentMap, skipTypeArgumentCheck) != 0; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterID = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + var type = this; + + if (type.isTypeParameter()) { + if (typeParameterArgumentMap[type.pullSymbolID] || typeParameterArgumentMap[type.getRootSymbol().pullSymbolID]) { + return type.pullSymbolID; + } + + var constraint = type.getConstraint(); + var wrappingTypeParameterID = constraint ? constraint.getWrappingTypeParameterID(typeParameterArgumentMap) : 0; + return wrappingTypeParameterID; + } + + if (type.inWrapCheck) { + return 0; + } + + this._wrapsTypeParameterCache = this._wrapsTypeParameterCache || new TypeScript.WrapsTypeParameterCache(); + var wrappingTypeParameterID = this._wrapsTypeParameterCache.getWrapsTypeParameter(typeParameterArgumentMap); + if (wrappingTypeParameterID === undefined) { + wrappingTypeParameterID = this.getWrappingTypeParameterIDWorker(typeParameterArgumentMap, skipTypeArgumentCheck); + + this._wrapsTypeParameterCache.setWrapsTypeParameter(typeParameterArgumentMap, wrappingTypeParameterID); + } + return wrappingTypeParameterID; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterIDFromSignatures = function (signatures, typeParameterArgumentMap) { + for (var i = 0; i < signatures.length; i++) { + var wrappingTypeParameterID = signatures[i].getWrappingTypeParameterID(typeParameterArgumentMap); + if (wrappingTypeParameterID !== 0) { + return wrappingTypeParameterID; + } + } + + return 0; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterIDWorker = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + var type = this; + var wrappingTypeParameterID = 0; + + if (!skipTypeArgumentCheck) { + type.inWrapCheck = true; + + var typeArguments = type.getTypeArguments(); + + if (type.isGeneric() && !typeArguments) { + typeArguments = type.getTypeParameters(); + } + + if (typeArguments) { + for (var i = 0; !wrappingTypeParameterID && i < typeArguments.length; i++) { + wrappingTypeParameterID = typeArguments[i].getWrappingTypeParameterID(typeParameterArgumentMap); + } + } + } + + if (skipTypeArgumentCheck || !(type.kind & 8216 /* SomeInstantiatableType */) || !type.name) { + var members = type.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + for (var i = 0; !wrappingTypeParameterID && i < members.length; i++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(members[i]); + wrappingTypeParameterID = members[i].type.getWrappingTypeParameterID(typeParameterArgumentMap); + } + + wrappingTypeParameterID = wrappingTypeParameterID || this.getWrappingTypeParameterIDFromSignatures(type.getCallSignatures(), typeParameterArgumentMap) || this.getWrappingTypeParameterIDFromSignatures(type.getConstructSignatures(), typeParameterArgumentMap) || this.getWrappingTypeParameterIDFromSignatures(type.getIndexSignatures(), typeParameterArgumentMap); + } + + if (!skipTypeArgumentCheck) { + type.inWrapCheck = false; + } + + return wrappingTypeParameterID; + }; + + PullTypeSymbol.prototype.wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference = function (enclosingType) { + TypeScript.Debug.assert(this.isNamedTypeSymbol()); + TypeScript.Debug.assert(TypeScript.PullHelpers.getRootType(enclosingType) == enclosingType); + var knownWrapMap = TypeScript.BitMatrix.getBitMatrix(true); + var wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap); + knownWrapMap.release(); + return wrapsIntoInfinitelyExpandingTypeReference; + }; + + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse = function (enclosingType, knownWrapMap) { + var wrapsIntoInfinitelyExpandingTypeReference = knownWrapMap.valueAt(this.pullSymbolID, enclosingType.pullSymbolID); + if (wrapsIntoInfinitelyExpandingTypeReference != undefined) { + return wrapsIntoInfinitelyExpandingTypeReference; + } + + if (this.inWrapInfiniteExpandingReferenceCheck) { + return false; + } + + this.inWrapInfiniteExpandingReferenceCheck = true; + wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker(enclosingType, knownWrapMap); + knownWrapMap.setValueAt(this.pullSymbolID, enclosingType.pullSymbolID, wrapsIntoInfinitelyExpandingTypeReference); + this.inWrapInfiniteExpandingReferenceCheck = false; + + return wrapsIntoInfinitelyExpandingTypeReference; + }; + + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker = function (enclosingType, knownWrapMap) { + var thisRootType = TypeScript.PullHelpers.getRootType(this); + + if (thisRootType != enclosingType) { + var thisIsNamedType = this.isNamedTypeSymbol(); + + if (thisIsNamedType) { + if (thisRootType.inWrapInfiniteExpandingReferenceCheck) { + return false; + } + + thisRootType.inWrapInfiniteExpandingReferenceCheck = true; + } + + var wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceStructure(enclosingType, knownWrapMap); + + if (thisIsNamedType) { + thisRootType.inWrapInfiniteExpandingReferenceCheck = false; + } + + return wrapsIntoInfinitelyExpandingTypeReference; + } + + var enclosingTypeParameters = enclosingType.getTypeParameters(); + var typeArguments = this.getTypeArguments(); + for (var i = 0; i < typeArguments.length; i++) { + if (TypeScript.ArrayUtilities.contains(enclosingTypeParameters, typeArguments[i])) { + continue; + } + + if (typeArguments[i].wrapsSomeTypeParameter(this.getTypeParameterArgumentMap())) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceStructure = function (enclosingType, knownWrapMap) { + var members = this.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + for (var i = 0; i < members.length; i++) { + if (members[i].type && members[i].type._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; + } + } + + var sigs = this.getCallSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + sigs = this.getConstructSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + sigs = this.getIndexSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.widenedType = function (resolver, ast, context) { + if (!this._widenedType) { + this._widenedType = resolver.widenType(this, ast, context); + } + return this._widenedType; + }; + return PullTypeSymbol; + })(PullSymbol); + TypeScript.PullTypeSymbol = PullTypeSymbol; + + var PullPrimitiveTypeSymbol = (function (_super) { + __extends(PullPrimitiveTypeSymbol, _super); + function PullPrimitiveTypeSymbol(name) { + _super.call(this, name, 2 /* Primitive */); + + this.isResolved = true; + } + PullPrimitiveTypeSymbol.prototype.isAny = function () { + return !this.isStringConstant() && this.name === "any"; + }; + + PullPrimitiveTypeSymbol.prototype.isNull = function () { + return !this.isStringConstant() && this.name === "null"; + }; + + PullPrimitiveTypeSymbol.prototype.isUndefined = function () { + return !this.isStringConstant() && this.name === "undefined"; + }; + + PullPrimitiveTypeSymbol.prototype.isStringConstant = function () { + return false; + }; + + PullPrimitiveTypeSymbol.prototype.setUnresolved = function () { + }; + + PullPrimitiveTypeSymbol.prototype.getDisplayName = function () { + if (this.isNull() || this.isUndefined()) { + return "any"; + } else { + return _super.prototype.getDisplayName.call(this); + } + }; + return PullPrimitiveTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullPrimitiveTypeSymbol = PullPrimitiveTypeSymbol; + + var PullStringConstantTypeSymbol = (function (_super) { + __extends(PullStringConstantTypeSymbol, _super); + function PullStringConstantTypeSymbol(name) { + _super.call(this, name); + } + PullStringConstantTypeSymbol.prototype.isStringConstant = function () { + return true; + }; + return PullStringConstantTypeSymbol; + })(PullPrimitiveTypeSymbol); + TypeScript.PullStringConstantTypeSymbol = PullStringConstantTypeSymbol; + + var PullErrorTypeSymbol = (function (_super) { + __extends(PullErrorTypeSymbol, _super); + function PullErrorTypeSymbol(_anyType, name) { + _super.call(this, name); + this._anyType = _anyType; + + TypeScript.Debug.assert(this._anyType); + this.isResolved = true; + } + PullErrorTypeSymbol.prototype.isError = function () { + return true; + }; + + PullErrorTypeSymbol.prototype._getResolver = function () { + return this._anyType._getResolver(); + }; + + PullErrorTypeSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + return this._anyType.getName(scopeSymbol, useConstraintInName); + }; + + PullErrorTypeSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { + return this._anyType.getName(scopeSymbol, useConstraintInName); + }; + + PullErrorTypeSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + return this._anyType.getName(scopeSymbol, useConstraintInName); + }; + return PullErrorTypeSymbol; + })(PullPrimitiveTypeSymbol); + TypeScript.PullErrorTypeSymbol = PullErrorTypeSymbol; + + var PullContainerSymbol = (function (_super) { + __extends(PullContainerSymbol, _super); + function PullContainerSymbol(name, kind) { + _super.call(this, name, kind); + this.instanceSymbol = null; + this.assignedValue = null; + this.assignedType = null; + this.assignedContainer = null; + } + PullContainerSymbol.prototype.isContainer = function () { + return true; + }; + + PullContainerSymbol.prototype.setInstanceSymbol = function (symbol) { + this.instanceSymbol = symbol; + }; + + PullContainerSymbol.prototype.getInstanceSymbol = function () { + return this.instanceSymbol; + }; + + PullContainerSymbol.prototype.setExportAssignedValueSymbol = function (symbol) { + this.assignedValue = symbol; + }; + + PullContainerSymbol.prototype.getExportAssignedValueSymbol = function () { + return this.assignedValue; + }; + + PullContainerSymbol.prototype.setExportAssignedTypeSymbol = function (type) { + this.assignedType = type; + }; + + PullContainerSymbol.prototype.getExportAssignedTypeSymbol = function () { + return this.assignedType; + }; + + PullContainerSymbol.prototype.setExportAssignedContainerSymbol = function (container) { + this.assignedContainer = container; + }; + + PullContainerSymbol.prototype.getExportAssignedContainerSymbol = function () { + return this.assignedContainer; + }; + + PullContainerSymbol.prototype.hasExportAssignment = function () { + return !!this.assignedValue || !!this.assignedType || !!this.assignedContainer; + }; + + PullContainerSymbol.usedAsSymbol = function (containerSymbol, symbol) { + if (!containerSymbol || !containerSymbol.isContainer()) { + return false; + } + + if (!containerSymbol.isAlias() && containerSymbol.type === symbol) { + return true; + } + + var moduleSymbol = containerSymbol; + var valueExportSymbol = moduleSymbol.getExportAssignedValueSymbol(); + var typeExportSymbol = moduleSymbol.getExportAssignedTypeSymbol(); + var containerExportSymbol = moduleSymbol.getExportAssignedContainerSymbol(); + if (valueExportSymbol || typeExportSymbol || containerExportSymbol) { + if (valueExportSymbol === symbol || typeExportSymbol == symbol || containerExportSymbol == symbol) { + return true; + } + + if (containerExportSymbol != containerSymbol) { + return PullContainerSymbol.usedAsSymbol(containerExportSymbol, symbol); + } + } + + return false; + }; + + PullContainerSymbol.prototype.getInstanceType = function () { + return this.instanceSymbol ? this.instanceSymbol.type : null; + }; + return PullContainerSymbol; + })(PullTypeSymbol); + TypeScript.PullContainerSymbol = PullContainerSymbol; + + var PullTypeAliasSymbol = (function (_super) { + __extends(PullTypeAliasSymbol, _super); + function PullTypeAliasSymbol(name) { + _super.call(this, name, 128 /* TypeAlias */); + this._assignedValue = null; + this._assignedType = null; + this._assignedContainer = null; + this._isUsedAsValue = false; + this._typeUsedExternally = false; + this._isUsedInExportAlias = false; + this.retrievingExportAssignment = false; + this.linkedAliasSymbols = null; + } + PullTypeAliasSymbol.prototype.isUsedInExportedAlias = function () { + this._resolveDeclaredSymbol(); + return this._isUsedInExportAlias; + }; + + PullTypeAliasSymbol.prototype.typeUsedExternally = function () { + this._resolveDeclaredSymbol(); + return this._typeUsedExternally; + }; + + PullTypeAliasSymbol.prototype.isUsedAsValue = function () { + this._resolveDeclaredSymbol(); + return this._isUsedAsValue; + }; + + PullTypeAliasSymbol.prototype.setTypeUsedExternally = function () { + this._typeUsedExternally = true; + }; + + PullTypeAliasSymbol.prototype.setIsUsedInExportedAlias = function () { + this._isUsedInExportAlias = true; + if (this.linkedAliasSymbols) { + this.linkedAliasSymbols.forEach(function (s) { + return s.setIsUsedInExportedAlias(); + }); + } + }; + + PullTypeAliasSymbol.prototype.addLinkedAliasSymbol = function (contingentValueSymbol) { + if (!this.linkedAliasSymbols) { + this.linkedAliasSymbols = [contingentValueSymbol]; + } else { + this.linkedAliasSymbols.push(contingentValueSymbol); + } + }; + + PullTypeAliasSymbol.prototype.setIsUsedAsValue = function () { + this._isUsedAsValue = true; + if (this.linkedAliasSymbols) { + this.linkedAliasSymbols.forEach(function (s) { + return s.setIsUsedAsValue(); + }); + } + }; + + PullTypeAliasSymbol.prototype.assignedValue = function () { + this._resolveDeclaredSymbol(); + return this._assignedValue; + }; + + PullTypeAliasSymbol.prototype.assignedType = function () { + this._resolveDeclaredSymbol(); + return this._assignedType; + }; + + PullTypeAliasSymbol.prototype.assignedContainer = function () { + this._resolveDeclaredSymbol(); + return this._assignedContainer; + }; + + PullTypeAliasSymbol.prototype.isAlias = function () { + return true; + }; + PullTypeAliasSymbol.prototype.isContainer = function () { + return true; + }; + + PullTypeAliasSymbol.prototype.setAssignedValueSymbol = function (symbol) { + this._assignedValue = symbol; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedValueSymbol = function () { + if (this._assignedValue) { + return this._assignedValue; + } + + if (this.retrievingExportAssignment) { + return null; + } + + if (this._assignedContainer) { + if (this._assignedContainer.hasExportAssignment()) { + this.retrievingExportAssignment = true; + var sym = this._assignedContainer.getExportAssignedValueSymbol(); + this.retrievingExportAssignment = false; + return sym; + } + + return this._assignedContainer.getInstanceSymbol(); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.setAssignedTypeSymbol = function (type) { + this._assignedType = type; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedTypeSymbol = function () { + if (this.retrievingExportAssignment) { + return null; + } + + if (this._assignedType) { + if (this._assignedType.isAlias()) { + this.retrievingExportAssignment = true; + var sym = this._assignedType.getExportAssignedTypeSymbol(); + this.retrievingExportAssignment = false; + } else if (this._assignedType !== this._assignedContainer) { + return this._assignedType; + } + } + + if (this._assignedContainer) { + this.retrievingExportAssignment = true; + var sym = this._assignedContainer.getExportAssignedTypeSymbol(); + this.retrievingExportAssignment = false; + if (sym) { + return sym; + } + } + + return this._assignedContainer; + }; + + PullTypeAliasSymbol.prototype.setAssignedContainerSymbol = function (container) { + this._assignedContainer = container; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedContainerSymbol = function () { + if (this.retrievingExportAssignment) { + return null; + } + + if (this._assignedContainer) { + this.retrievingExportAssignment = true; + var sym = this._assignedContainer.getExportAssignedContainerSymbol(); + this.retrievingExportAssignment = false; + if (sym) { + return sym; + } + } + + return this._assignedContainer; + }; + + PullTypeAliasSymbol.prototype.getMembers = function () { + if (this._assignedType) { + return this._assignedType.getMembers(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.getCallSignatures = function () { + if (this._assignedType) { + return this._assignedType.getCallSignatures(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.getConstructSignatures = function () { + if (this._assignedType) { + return this._assignedType.getConstructSignatures(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.getIndexSignatures = function () { + if (this._assignedType) { + return this._assignedType.getIndexSignatures(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.findMember = function (name) { + if (this._assignedType) { + return this._assignedType.findMember(name, true); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.findNestedType = function (name) { + if (this._assignedType) { + return this._assignedType.findNestedType(name); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.findNestedContainer = function (name) { + if (this._assignedType) { + return this._assignedType.findNestedContainer(name); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisibility) { + if (this._assignedType) { + return this._assignedType.getAllMembers(searchDeclKind, memberVisibility); + } + + return TypeScript.sentinelEmptyArray; + }; + return PullTypeAliasSymbol; + })(PullTypeSymbol); + TypeScript.PullTypeAliasSymbol = PullTypeAliasSymbol; + + var PullTypeParameterSymbol = (function (_super) { + __extends(PullTypeParameterSymbol, _super); + function PullTypeParameterSymbol(name) { + _super.call(this, name, 8192 /* TypeParameter */); + this._constraint = null; + } + PullTypeParameterSymbol.prototype.isTypeParameter = function () { + return true; + }; + + PullTypeParameterSymbol.prototype.setConstraint = function (constraintType) { + this._constraint = constraintType; + }; + + PullTypeParameterSymbol.prototype.getConstraint = function () { + return this._constraint; + }; + + PullTypeParameterSymbol.prototype.getBaseConstraint = function (semanticInfoChain) { + var preBaseConstraint = this.getConstraintRecursively({}); + TypeScript.Debug.assert(preBaseConstraint === null || !preBaseConstraint.isTypeParameter()); + return preBaseConstraint || semanticInfoChain.emptyTypeSymbol; + }; + + PullTypeParameterSymbol.prototype.getConstraintRecursively = function (visitedTypeParameters) { + var constraint = this.getConstraint(); + + if (constraint) { + if (constraint.isTypeParameter()) { + var constraintAsTypeParameter = constraint; + if (!visitedTypeParameters[constraintAsTypeParameter.pullSymbolID]) { + visitedTypeParameters[constraintAsTypeParameter.pullSymbolID] = constraintAsTypeParameter; + return constraintAsTypeParameter.getConstraintRecursively(visitedTypeParameters); + } + } else { + return constraint; + } + } + + return null; + }; + + PullTypeParameterSymbol.prototype.getDefaultConstraint = function (semanticInfoChain) { + return this._constraint || semanticInfoChain.emptyTypeSymbol; + }; + + PullTypeParameterSymbol.prototype.getCallSignatures = function () { + if (this._constraint) { + return this._constraint.getCallSignatures(); + } + + return _super.prototype.getCallSignatures.call(this); + }; + + PullTypeParameterSymbol.prototype.getConstructSignatures = function () { + if (this._constraint) { + return this._constraint.getConstructSignatures(); + } + + return _super.prototype.getConstructSignatures.call(this); + }; + + PullTypeParameterSymbol.prototype.getIndexSignatures = function () { + if (this._constraint) { + return this._constraint.getIndexSignatures(); + } + + return _super.prototype.getIndexSignatures.call(this); + }; + + PullTypeParameterSymbol.prototype.isGeneric = function () { + return true; + }; + + PullTypeParameterSymbol.prototype.fullName = function (scopeSymbol) { + var name = this.getDisplayName(scopeSymbol); + var container = this.getContainer(); + if (container) { + var containerName = container.fullName(scopeSymbol); + name = name + " in " + containerName; + } + + return name; + }; + + PullTypeParameterSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + var name = _super.prototype.getName.call(this, scopeSymbol); + + if (this.isPrinting) { + return name; + } + + this.isPrinting = true; + + if (useConstraintInName && this._constraint) { + name += " extends " + this._constraint.toString(scopeSymbol); + } + + this.isPrinting = false; + + return name; + }; + + PullTypeParameterSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { + var name = _super.prototype.getDisplayName.call(this, scopeSymbol, useConstraintInName, skipInternalAliasName); + + if (this.isPrinting) { + return name; + } + + this.isPrinting = true; + + if (useConstraintInName && this._constraint) { + name += " extends " + this._constraint.toString(scopeSymbol); + } + + this.isPrinting = false; + + return name; + }; + + PullTypeParameterSymbol.prototype.isExternallyVisible = function (inIsExternallyVisibleSymbols) { + return true; + }; + return PullTypeParameterSymbol; + })(PullTypeSymbol); + TypeScript.PullTypeParameterSymbol = PullTypeParameterSymbol; + + var PullAccessorSymbol = (function (_super) { + __extends(PullAccessorSymbol, _super); + function PullAccessorSymbol(name) { + _super.call(this, name, 4096 /* Property */); + this._getterSymbol = null; + this._setterSymbol = null; + } + PullAccessorSymbol.prototype.isAccessor = function () { + return true; + }; + + PullAccessorSymbol.prototype.setSetter = function (setter) { + if (!setter) { + return; + } + + this._setterSymbol = setter; + }; + + PullAccessorSymbol.prototype.getSetter = function () { + return this._setterSymbol; + }; + + PullAccessorSymbol.prototype.setGetter = function (getter) { + if (!getter) { + return; + } + + this._getterSymbol = getter; + }; + + PullAccessorSymbol.prototype.getGetter = function () { + return this._getterSymbol; + }; + return PullAccessorSymbol; + })(PullSymbol); + TypeScript.PullAccessorSymbol = PullAccessorSymbol; + + function getIDForTypeSubstitutions(instantiatingTypeOrSignature, typeArgumentMap) { + var substitution = ""; + var members = null; + + var allowedToReferenceTypeParameters = instantiatingTypeOrSignature.getAllowedToReferenceTypeParameters(); + for (var i = 0; i < allowedToReferenceTypeParameters.length; i++) { + var typeParameter = allowedToReferenceTypeParameters[i]; + var typeParameterID = typeParameter.pullSymbolID; + var typeArg = typeArgumentMap[typeParameterID]; + if (!typeArg) { + typeArg = typeParameter; + } + substitution += typeParameterID + ":" + getIDForTypeSubstitutionsOfType(typeArg); + } + + return substitution; + } + TypeScript.getIDForTypeSubstitutions = getIDForTypeSubstitutions; + + function getIDForTypeSubstitutionsOfType(type) { + var structure; + if (type.isError()) { + structure = "E" + getIDForTypeSubstitutionsOfType(type._anyType); + } else if (!type.isNamedTypeSymbol()) { + structure = getIDForTypeSubstitutionsFromObjectType(type); + } + + if (!structure) { + structure = type.pullSymbolID + "#"; + } + + return structure; + } + + function getIDForTypeSubstitutionsFromObjectType(type) { + if (type.isResolved) { + var getIDForTypeSubStitutionWalker = new GetIDForTypeSubStitutionWalker(); + TypeScript.PullHelpers.walkPullTypeSymbolStructure(type, getIDForTypeSubStitutionWalker); + } + + return null; + } + + var GetIDForTypeSubStitutionWalker = (function () { + function GetIDForTypeSubStitutionWalker() { + this.structure = ""; + } + GetIDForTypeSubStitutionWalker.prototype.memberSymbolWalk = function (memberSymbol) { + this.structure += memberSymbol.name + "@" + getIDForTypeSubstitutionsOfType(memberSymbol.type); + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.callSignatureWalk = function (signatureSymbol) { + this.structure += "("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.constructSignatureWalk = function (signatureSymbol) { + this.structure += "new("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.indexSignatureWalk = function (signatureSymbol) { + this.structure += "[]("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.signatureParameterWalk = function (parameterSymbol) { + this.structure += parameterSymbol.name + "@" + getIDForTypeSubstitutionsOfType(parameterSymbol.type); + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.signatureReturnTypeWalk = function (returnType) { + this.structure += ")" + getIDForTypeSubstitutionsOfType(returnType); + return true; + }; + return GetIDForTypeSubStitutionWalker; + })(); + + (function (GetAllMembersVisiblity) { + GetAllMembersVisiblity[GetAllMembersVisiblity["all"] = 0] = "all"; + + GetAllMembersVisiblity[GetAllMembersVisiblity["internallyVisible"] = 1] = "internallyVisible"; + + GetAllMembersVisiblity[GetAllMembersVisiblity["externallyVisible"] = 2] = "externallyVisible"; + })(TypeScript.GetAllMembersVisiblity || (TypeScript.GetAllMembersVisiblity = {})); + var GetAllMembersVisiblity = TypeScript.GetAllMembersVisiblity; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var EnclosingTypeWalkerState = (function () { + function EnclosingTypeWalkerState() { + } + EnclosingTypeWalkerState.getDefaultEnclosingTypeWalkerState = function () { + var defaultEnclosingTypeWalkerState = new EnclosingTypeWalkerState(); + defaultEnclosingTypeWalkerState._hasSetEnclosingType = false; + return defaultEnclosingTypeWalkerState; + }; + + EnclosingTypeWalkerState.getNonGenericEnclosingTypeWalkerState = function () { + var defaultEnclosingTypeWalkerState = new EnclosingTypeWalkerState(); + defaultEnclosingTypeWalkerState._hasSetEnclosingType = true; + return defaultEnclosingTypeWalkerState; + }; + + EnclosingTypeWalkerState.getGenericEnclosingTypeWalkerState = function (genericEnclosingType) { + var defaultEnclosingTypeWalkerState = new EnclosingTypeWalkerState(); + defaultEnclosingTypeWalkerState._hasSetEnclosingType = true; + defaultEnclosingTypeWalkerState._currentSymbols = [TypeScript.PullHelpers.getRootType(genericEnclosingType)]; + return defaultEnclosingTypeWalkerState; + }; + return EnclosingTypeWalkerState; + })(); + TypeScript.EnclosingTypeWalkerState = EnclosingTypeWalkerState; + + var PullTypeEnclosingTypeWalker = (function () { + function PullTypeEnclosingTypeWalker() { + this.setDefaultTypeWalkerState(); + } + PullTypeEnclosingTypeWalker.prototype.setDefaultTypeWalkerState = function () { + this.enclosingTypeWalkerState = PullTypeEnclosingTypeWalker._defaultEnclosingTypeWalkerState; + }; + + PullTypeEnclosingTypeWalker.prototype.setNonGenericEnclosingTypeWalkerState = function () { + this.enclosingTypeWalkerState = PullTypeEnclosingTypeWalker._nonGenericEnclosingTypeWalkerState; + }; + + PullTypeEnclosingTypeWalker.prototype.canSymbolOrDeclBeUsedAsEnclosingTypeHelper = function (name, kind) { + return name && (kind === 8 /* Class */ || kind === 16 /* Interface */); + }; + + PullTypeEnclosingTypeWalker.prototype.canDeclBeUsedAsEnclosingType = function (decl) { + return this.canSymbolOrDeclBeUsedAsEnclosingTypeHelper(decl.name, decl.kind); + }; + + PullTypeEnclosingTypeWalker.prototype.canSymbolBeUsedAsEnclosingType = function (symbol) { + return this.canSymbolOrDeclBeUsedAsEnclosingTypeHelper(symbol.name, symbol.kind); + }; + + PullTypeEnclosingTypeWalker.prototype.getEnclosingType = function () { + var currentSymbols = this.enclosingTypeWalkerState._currentSymbols; + if (currentSymbols) { + TypeScript.Debug.assert(currentSymbols.length > 0); + return currentSymbols[0]; + } + + return null; + }; + + PullTypeEnclosingTypeWalker.prototype._canWalkStructure = function () { + var enclosingType = this.getEnclosingType(); + TypeScript.Debug.assert(!enclosingType || enclosingType.isGeneric()); + return !!enclosingType; + }; + + PullTypeEnclosingTypeWalker.prototype._getCurrentSymbol = function () { + var currentSymbols = this.enclosingTypeWalkerState._currentSymbols; + if (currentSymbols && currentSymbols.length) { + return currentSymbols[currentSymbols.length - 1]; + } + + return null; + }; + + PullTypeEnclosingTypeWalker.prototype.getGenerativeClassification = function () { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + if (!currentType) { + return 0 /* Unknown */; + } + + var variableNeededToFixNodeJitterBug = this.getEnclosingType(); + + return currentType.getGenerativeTypeClassification(variableNeededToFixNodeJitterBug); + } + + return 2 /* Closed */; + }; + + PullTypeEnclosingTypeWalker.prototype._pushSymbol = function (symbol) { + return this.enclosingTypeWalkerState._currentSymbols.push(symbol); + }; + + PullTypeEnclosingTypeWalker.prototype._popSymbol = function () { + return this.enclosingTypeWalkerState._currentSymbols.pop(); + }; + + PullTypeEnclosingTypeWalker.prototype.setSymbolAsEnclosingType = function (type) { + if (type.isGeneric()) { + this.enclosingTypeWalkerState = EnclosingTypeWalkerState.getGenericEnclosingTypeWalkerState(type); + } else { + this.setNonGenericEnclosingTypeWalkerState(); + } + }; + + PullTypeEnclosingTypeWalker.prototype._setEnclosingTypeOfParentDecl = function (decl, setSignature) { + var parentDecl = decl.getParentDecl(); + + if (parentDecl && !(parentDecl.kind & (164 /* SomeContainer */ | 1 /* Script */))) { + if (this.canDeclBeUsedAsEnclosingType(parentDecl)) { + this.setSymbolAsEnclosingType(parentDecl.getSymbol()); + } else { + this._setEnclosingTypeOfParentDecl(parentDecl, true); + } + + if (this._canWalkStructure()) { + var symbol = decl.getSymbol(); + if (symbol) { + if (!symbol.isType() && !symbol.isSignature()) { + symbol = symbol.type; + } + + this._pushSymbol(symbol); + } + + if (setSignature) { + var signature = decl.getSignatureSymbol(); + if (signature) { + this._pushSymbol(signature); + } + } + } + } + }; + + PullTypeEnclosingTypeWalker.prototype.setEnclosingTypeForSymbol = function (symbol) { + var currentEnclosingTypeWalkerState = this.enclosingTypeWalkerState; + if (this.canSymbolBeUsedAsEnclosingType(symbol)) { + this.setSymbolAsEnclosingType(symbol); + } else { + this.setDefaultTypeWalkerState(); + + var decls = symbol.getDeclarations(); + for (var i = 0; i < decls.length; i++) { + var decl = decls[i]; + this._setEnclosingTypeOfParentDecl(decl, symbol.isSignature()); + + if (this.enclosingTypeWalkerState._hasSetEnclosingType) { + break; + } + } + + if (!this.enclosingTypeWalkerState._hasSetEnclosingType) { + this.setNonGenericEnclosingTypeWalkerState(); + } + } + return currentEnclosingTypeWalkerState; + }; + + PullTypeEnclosingTypeWalker.prototype.startWalkingType = function (symbol) { + var currentState = this.enclosingTypeWalkerState; + + var setEnclosingTypeForSymbol = !this.enclosingTypeWalkerState._hasSetEnclosingType || this.canSymbolBeUsedAsEnclosingType(symbol); + if (setEnclosingTypeForSymbol) { + this.setEnclosingTypeForSymbol(symbol); + } + return currentState; + }; + + PullTypeEnclosingTypeWalker.prototype.endWalkingType = function (stateWhenStartedWalkingTypes) { + this.enclosingTypeWalkerState = stateWhenStartedWalkingTypes; + }; + + PullTypeEnclosingTypeWalker.prototype.walkMemberType = function (memberName, resolver) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + var memberSymbol = currentType ? resolver._getNamedPropertySymbolOfAugmentedType(memberName, currentType) : null; + this._pushSymbol(memberSymbol ? memberSymbol.type : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkMemberType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkSignature = function (kind, index) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + var signatures; + if (currentType) { + if (kind == 1048576 /* CallSignature */) { + signatures = currentType.getCallSignatures(); + } else if (kind == 2097152 /* ConstructSignature */) { + signatures = currentType.getConstructSignatures(); + } else { + signatures = currentType.getIndexSignatures(); + } + } + + this._pushSymbol(signatures ? signatures[index] : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkSignature = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkTypeArgument = function (index) { + if (this._canWalkStructure()) { + var typeArgument = null; + var currentType = this._getCurrentSymbol(); + if (currentType) { + var typeArguments = currentType.getTypeArguments(); + typeArgument = typeArguments ? typeArguments[index] : null; + } + this._pushSymbol(typeArgument); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkTypeArgument = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkTypeParameterConstraint = function (index) { + if (this._canWalkStructure()) { + var typeParameters; + var currentSymbol = this._getCurrentSymbol(); + if (currentSymbol) { + if (currentSymbol.isSignature()) { + typeParameters = currentSymbol.getTypeParameters(); + } else { + TypeScript.Debug.assert(currentSymbol.isType()); + typeParameters = currentSymbol.getTypeParameters(); + } + } + this._pushSymbol(typeParameters ? typeParameters[index].getConstraint() : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkTypeParameterConstraint = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkReturnType = function () { + if (this._canWalkStructure()) { + var currentSignature = this._getCurrentSymbol(); + this._pushSymbol(currentSignature ? currentSignature.returnType : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkReturnType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkParameterType = function (iParam) { + if (this._canWalkStructure()) { + var currentSignature = this._getCurrentSymbol(); + this._pushSymbol(currentSignature ? currentSignature.getParameterTypeAtIndex(iParam) : null); + } + }; + PullTypeEnclosingTypeWalker.prototype.postWalkParameterType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.getBothKindOfIndexSignatures = function (resolver, context, includeAugmentedType) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + if (currentType) { + return resolver._getBothKindsOfIndexSignatures(currentType, context, includeAugmentedType); + } + } + return null; + }; + + PullTypeEnclosingTypeWalker.prototype.walkIndexSignatureReturnType = function (indexSigInfo, useStringIndexSignature, onlySignature) { + if (this._canWalkStructure()) { + var indexSig = indexSigInfo ? (useStringIndexSignature ? indexSigInfo.stringSignature : indexSigInfo.numericSignature) : null; + this._pushSymbol(indexSig); + if (!onlySignature) { + this._pushSymbol(indexSig ? indexSig.returnType : null); + } + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkIndexSignatureReturnType = function (onlySignature) { + if (this._canWalkStructure()) { + if (!onlySignature) { + this._popSymbol(); + } + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.resetEnclosingTypeWalkerState = function () { + var currentState = this.enclosingTypeWalkerState; + this.setDefaultTypeWalkerState(); + return currentState; + }; + + PullTypeEnclosingTypeWalker.prototype.setEnclosingTypeWalkerState = function (enclosingTypeWalkerState) { + if (enclosingTypeWalkerState) { + this.enclosingTypeWalkerState = enclosingTypeWalkerState; + } else { + this.setDefaultTypeWalkerState(); + } + }; + PullTypeEnclosingTypeWalker._defaultEnclosingTypeWalkerState = EnclosingTypeWalkerState.getDefaultEnclosingTypeWalkerState(); + + PullTypeEnclosingTypeWalker._nonGenericEnclosingTypeWalkerState = EnclosingTypeWalkerState.getNonGenericEnclosingTypeWalkerState(); + return PullTypeEnclosingTypeWalker; + })(); + TypeScript.PullTypeEnclosingTypeWalker = PullTypeEnclosingTypeWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CandidateInferenceInfo = (function () { + function CandidateInferenceInfo() { + this.typeParameter = null; + this._inferredTypeAfterFixing = null; + this.inferenceCandidates = []; + } + CandidateInferenceInfo.prototype.addCandidate = function (candidate) { + if (!this._inferredTypeAfterFixing) { + this.inferenceCandidates[this.inferenceCandidates.length] = candidate; + } + }; + + CandidateInferenceInfo.prototype.isFixed = function () { + return !!this._inferredTypeAfterFixing; + }; + + CandidateInferenceInfo.prototype.fixTypeParameter = function (resolver, context) { + var _this = this; + if (!this._inferredTypeAfterFixing) { + var collection = { + getLength: function () { + return _this.inferenceCandidates.length; + }, + getTypeAtIndex: function (index) { + return _this.inferenceCandidates[index].type; + } + }; + + var bestCommonType = resolver.findBestCommonType(collection, context, new TypeScript.TypeComparisonInfo()); + this._inferredTypeAfterFixing = bestCommonType.widenedType(resolver, null, context); + } + }; + return CandidateInferenceInfo; + })(); + TypeScript.CandidateInferenceInfo = CandidateInferenceInfo; + + var TypeArgumentInferenceContext = (function () { + function TypeArgumentInferenceContext(resolver, context, signatureBeingInferred) { + this.resolver = resolver; + this.context = context; + this.signatureBeingInferred = signatureBeingInferred; + this.inferenceCache = TypeScript.BitMatrix.getBitMatrix(false); + this.candidateCache = []; + var typeParameters = signatureBeingInferred.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + this.addInferenceRoot(typeParameters[i]); + } + } + TypeArgumentInferenceContext.prototype.alreadyRelatingTypes = function (objectType, parameterType) { + if (this.inferenceCache.valueAt(objectType.pullSymbolID, parameterType.pullSymbolID)) { + return true; + } else { + this.inferenceCache.setValueAt(objectType.pullSymbolID, parameterType.pullSymbolID, true); + return false; + } + }; + + TypeArgumentInferenceContext.prototype.resetRelationshipCache = function () { + this.inferenceCache.release(); + this.inferenceCache = TypeScript.BitMatrix.getBitMatrix(false); + }; + + TypeArgumentInferenceContext.prototype.addInferenceRoot = function (param) { + var info = this.candidateCache[param.pullSymbolID]; + + if (!info) { + info = new CandidateInferenceInfo(); + info.typeParameter = param; + this.candidateCache[param.pullSymbolID] = info; + } + }; + + TypeArgumentInferenceContext.prototype.getInferenceInfo = function (param) { + return this.candidateCache[param.pullSymbolID]; + }; + + TypeArgumentInferenceContext.prototype.addCandidateForInference = function (param, candidate) { + var info = this.getInferenceInfo(param); + + if (info && candidate && info.inferenceCandidates.indexOf(candidate) < 0) { + info.addCandidate(candidate); + } + }; + + TypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + throw TypeScript.Errors.abstract(); + }; + + TypeArgumentInferenceContext.prototype.fixTypeParameter = function (typeParameter) { + var candidateInfo = this.candidateCache[typeParameter.pullSymbolID]; + if (candidateInfo) { + candidateInfo.fixTypeParameter(this.resolver, this.context); + } + }; + + TypeArgumentInferenceContext.prototype._finalizeInferredTypeArguments = function () { + var results = []; + var typeParameters = this.signatureBeingInferred.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + var info = this.candidateCache[typeParameters[i].pullSymbolID]; + + info.fixTypeParameter(this.resolver, this.context); + + for (var i = 0; i < results.length; i++) { + if (results[i].type === info.typeParameter) { + results[i].type = info._inferredTypeAfterFixing; + } + } + + results.push(info._inferredTypeAfterFixing); + } + + return results; + }; + + TypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + throw TypeScript.Errors.abstract(); + }; + return TypeArgumentInferenceContext; + })(); + TypeScript.TypeArgumentInferenceContext = TypeArgumentInferenceContext; + + var InvocationTypeArgumentInferenceContext = (function (_super) { + __extends(InvocationTypeArgumentInferenceContext, _super); + function InvocationTypeArgumentInferenceContext(resolver, context, signatureBeingInferred, argumentASTs) { + _super.call(this, resolver, context, signatureBeingInferred); + this.argumentASTs = argumentASTs; + } + InvocationTypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + return true; + }; + + InvocationTypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + var _this = this; + this.signatureBeingInferred.forAllParameterTypes(this.argumentASTs.nonSeparatorCount(), function (parameterType, argumentIndex) { + var argumentAST = _this.argumentASTs.nonSeparatorAt(argumentIndex); + + _this.context.pushInferentialType(parameterType, _this); + var argumentType = _this.resolver.resolveAST(argumentAST, true, _this.context).type; + _this.resolver.relateTypeToTypeParametersWithNewEnclosingTypes(argumentType, parameterType, _this, _this.context); + _this.context.popAnyContextualType(); + + return true; + }); + + return this._finalizeInferredTypeArguments(); + }; + return InvocationTypeArgumentInferenceContext; + })(TypeArgumentInferenceContext); + TypeScript.InvocationTypeArgumentInferenceContext = InvocationTypeArgumentInferenceContext; + + var ContextualSignatureInstantiationTypeArgumentInferenceContext = (function (_super) { + __extends(ContextualSignatureInstantiationTypeArgumentInferenceContext, _super); + function ContextualSignatureInstantiationTypeArgumentInferenceContext(resolver, context, signatureBeingInferred, contextualSignature, shouldFixContextualSignatureParameterTypes) { + _super.call(this, resolver, context, signatureBeingInferred); + this.contextualSignature = contextualSignature; + this.shouldFixContextualSignatureParameterTypes = shouldFixContextualSignatureParameterTypes; + } + ContextualSignatureInstantiationTypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + return false; + }; + + ContextualSignatureInstantiationTypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + var _this = this; + var relateTypesCallback = function (parameterTypeBeingInferred, contextualParameterType) { + if (_this.shouldFixContextualSignatureParameterTypes) { + contextualParameterType = _this.context.fixAllTypeParametersReferencedByType(contextualParameterType, _this.resolver, _this); + } + _this.resolver.relateTypeToTypeParametersWithNewEnclosingTypes(contextualParameterType, parameterTypeBeingInferred, _this, _this.context); + + return true; + }; + + this.signatureBeingInferred.forAllCorrespondingParameterTypesInThisAndOtherSignature(this.contextualSignature, relateTypesCallback); + + return this._finalizeInferredTypeArguments(); + }; + return ContextualSignatureInstantiationTypeArgumentInferenceContext; + })(TypeArgumentInferenceContext); + TypeScript.ContextualSignatureInstantiationTypeArgumentInferenceContext = ContextualSignatureInstantiationTypeArgumentInferenceContext; + + var PullContextualTypeContext = (function () { + function PullContextualTypeContext(contextualType, provisional, isInferentiallyTyping, typeArgumentInferenceContext) { + this.contextualType = contextualType; + this.provisional = provisional; + this.isInferentiallyTyping = isInferentiallyTyping; + this.typeArgumentInferenceContext = typeArgumentInferenceContext; + this.provisionallyTypedSymbols = []; + this.hasProvisionalErrors = false; + this.astSymbolMap = []; + } + PullContextualTypeContext.prototype.recordProvisionallyTypedSymbol = function (symbol) { + this.provisionallyTypedSymbols[this.provisionallyTypedSymbols.length] = symbol; + }; + + PullContextualTypeContext.prototype.invalidateProvisionallyTypedSymbols = function () { + for (var i = 0; i < this.provisionallyTypedSymbols.length; i++) { + this.provisionallyTypedSymbols[i].setUnresolved(); + } + }; + + PullContextualTypeContext.prototype.setSymbolForAST = function (ast, symbol) { + this.astSymbolMap[ast.syntaxID()] = symbol; + }; + + PullContextualTypeContext.prototype.getSymbolForAST = function (ast) { + return this.astSymbolMap[ast.syntaxID()]; + }; + return PullContextualTypeContext; + })(); + TypeScript.PullContextualTypeContext = PullContextualTypeContext; + + var PullTypeResolutionContext = (function () { + function PullTypeResolutionContext(resolver, inTypeCheck, fileName) { + if (typeof inTypeCheck === "undefined") { inTypeCheck = false; } + if (typeof fileName === "undefined") { fileName = null; } + this.resolver = resolver; + this.inTypeCheck = inTypeCheck; + this.fileName = fileName; + this.contextStack = []; + this.typeCheckedNodes = null; + this.enclosingTypeWalker1 = null; + this.enclosingTypeWalker2 = null; + this.inBaseTypeResolution = false; + if (inTypeCheck) { + TypeScript.Debug.assert(fileName, "A file name must be provided if you are typechecking"); + this.typeCheckedNodes = TypeScript.BitVector.getBitVector(false); + } + } + PullTypeResolutionContext.prototype.setTypeChecked = function (ast) { + if (!this.inProvisionalResolution()) { + this.typeCheckedNodes.setValueAt(ast.syntaxID(), true); + } + }; + + PullTypeResolutionContext.prototype.canTypeCheckAST = function (ast) { + return this.typeCheck() && !this.typeCheckedNodes.valueAt(ast.syntaxID()) && this.fileName === ast.fileName(); + }; + + PullTypeResolutionContext.prototype._pushAnyContextualType = function (type, provisional, isInferentiallyTyping, argContext) { + this.contextStack.push(new PullContextualTypeContext(type, provisional, isInferentiallyTyping, argContext)); + }; + + PullTypeResolutionContext.prototype.pushNewContextualType = function (type) { + this._pushAnyContextualType(type, this.inProvisionalResolution(), false, null); + }; + + PullTypeResolutionContext.prototype.propagateContextualType = function (type) { + this._pushAnyContextualType(type, this.inProvisionalResolution(), this.isInferentiallyTyping(), this.getCurrentTypeArgumentInferenceContext()); + }; + + PullTypeResolutionContext.prototype.pushInferentialType = function (type, typeArgumentInferenceContext) { + this._pushAnyContextualType(type, true, true, typeArgumentInferenceContext); + }; + + PullTypeResolutionContext.prototype.pushProvisionalType = function (type) { + this._pushAnyContextualType(type, true, false, null); + }; + + PullTypeResolutionContext.prototype.popAnyContextualType = function () { + var tc = this.contextStack.pop(); + + tc.invalidateProvisionallyTypedSymbols(); + + if (tc.hasProvisionalErrors && this.inProvisionalResolution()) { + this.contextStack[this.contextStack.length - 1].hasProvisionalErrors = true; + } + + return tc; + }; + + PullTypeResolutionContext.prototype.hasProvisionalErrors = function () { + return this.contextStack.length ? this.contextStack[this.contextStack.length - 1].hasProvisionalErrors : false; + }; + + PullTypeResolutionContext.prototype.getContextualType = function () { + var context = !this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]; + + if (context) { + var type = context.contextualType; + + if (!type) { + return null; + } + + return type; + } + + return null; + }; + + PullTypeResolutionContext.prototype.fixAllTypeParametersReferencedByType = function (type, resolver, argContext) { + var argContext = this.getCurrentTypeArgumentInferenceContext(); + if (type.wrapsSomeTypeParameter(argContext.candidateCache)) { + var typeParameterArgumentMap = []; + + for (var n in argContext.candidateCache) { + var typeParameter = argContext.candidateCache[n] && argContext.candidateCache[n].typeParameter; + if (typeParameter) { + var dummyMap = []; + dummyMap[typeParameter.pullSymbolID] = typeParameter; + if (type.wrapsSomeTypeParameter(dummyMap)) { + argContext.fixTypeParameter(typeParameter); + TypeScript.Debug.assert(argContext.candidateCache[n]._inferredTypeAfterFixing); + typeParameterArgumentMap[typeParameter.pullSymbolID] = argContext.candidateCache[n]._inferredTypeAfterFixing; + } + } + } + + return resolver.instantiateType(type, typeParameterArgumentMap); + } + + return type; + }; + + PullTypeResolutionContext.prototype.getCurrentTypeArgumentInferenceContext = function () { + return this.contextStack.length ? this.contextStack[this.contextStack.length - 1].typeArgumentInferenceContext : null; + }; + + PullTypeResolutionContext.prototype.isInferentiallyTyping = function () { + return this.contextStack.length > 0 && this.contextStack[this.contextStack.length - 1].isInferentiallyTyping; + }; + + PullTypeResolutionContext.prototype.inProvisionalResolution = function () { + return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); + }; + + PullTypeResolutionContext.prototype.isInBaseTypeResolution = function () { + return this.inBaseTypeResolution; + }; + + PullTypeResolutionContext.prototype.startBaseTypeResolution = function () { + var wasInBaseTypeResoltion = this.inBaseTypeResolution; + this.inBaseTypeResolution = true; + return wasInBaseTypeResoltion; + }; + + PullTypeResolutionContext.prototype.doneBaseTypeResolution = function (wasInBaseTypeResolution) { + this.inBaseTypeResolution = wasInBaseTypeResolution; + }; + + PullTypeResolutionContext.prototype.setTypeInContext = function (symbol, type) { + if (symbol.type && symbol.type.isError() && !type.isError()) { + return; + } + symbol.type = type; + + if (this.contextStack.length && this.inProvisionalResolution()) { + this.contextStack[this.contextStack.length - 1].recordProvisionallyTypedSymbol(symbol); + } + }; + + PullTypeResolutionContext.prototype.postDiagnostic = function (diagnostic) { + if (diagnostic) { + if (this.inProvisionalResolution()) { + (this.contextStack[this.contextStack.length - 1]).hasProvisionalErrors = true; + } else if (this.inTypeCheck && this.resolver) { + this.resolver.semanticInfoChain.addDiagnostic(diagnostic); + } + } + }; + + PullTypeResolutionContext.prototype.typeCheck = function () { + return this.inTypeCheck && !this.inProvisionalResolution(); + }; + + PullTypeResolutionContext.prototype.setSymbolForAST = function (ast, symbol) { + this.contextStack[this.contextStack.length - 1].setSymbolForAST(ast, symbol); + }; + + PullTypeResolutionContext.prototype.getSymbolForAST = function (ast) { + for (var i = this.contextStack.length - 1; i >= 0; i--) { + var typeContext = this.contextStack[i]; + if (!typeContext.provisional) { + break; + } + + var symbol = typeContext.getSymbolForAST(ast); + if (symbol) { + return symbol; + } + } + + return null; + }; + + PullTypeResolutionContext.prototype.startWalkingTypes = function (symbol1, symbol2) { + if (!this.enclosingTypeWalker1) { + this.enclosingTypeWalker1 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var stateWhenStartedWalkingTypes1 = this.enclosingTypeWalker1.startWalkingType(symbol1); + if (!this.enclosingTypeWalker2) { + this.enclosingTypeWalker2 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var stateWhenStartedWalkingTypes2 = this.enclosingTypeWalker2.startWalkingType(symbol2); + return { + stateWhenStartedWalkingTypes1: stateWhenStartedWalkingTypes1, + stateWhenStartedWalkingTypes2: stateWhenStartedWalkingTypes2 + }; + }; + + PullTypeResolutionContext.prototype.endWalkingTypes = function (statesWhenStartedWalkingTypes) { + this.enclosingTypeWalker1.endWalkingType(statesWhenStartedWalkingTypes.stateWhenStartedWalkingTypes1); + this.enclosingTypeWalker2.endWalkingType(statesWhenStartedWalkingTypes.stateWhenStartedWalkingTypes2); + }; + + PullTypeResolutionContext.prototype.setEnclosingTypeForSymbols = function (symbol1, symbol2) { + if (!this.enclosingTypeWalker1) { + this.enclosingTypeWalker1 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var enclosingTypeWalkerState1 = this.enclosingTypeWalker1.setEnclosingTypeForSymbol(symbol1); + if (!this.enclosingTypeWalker2) { + this.enclosingTypeWalker2 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var enclosingTypeWalkerState2 = this.enclosingTypeWalker2.setEnclosingTypeForSymbol(symbol2); + return { + enclosingTypeWalkerState1: enclosingTypeWalkerState1, + enclosingTypeWalkerState2: enclosingTypeWalkerState2 + }; + }; + + PullTypeResolutionContext.prototype.walkMemberTypes = function (memberName) { + this.enclosingTypeWalker1.walkMemberType(memberName, this.resolver); + this.enclosingTypeWalker2.walkMemberType(memberName, this.resolver); + }; + + PullTypeResolutionContext.prototype.postWalkMemberTypes = function () { + this.enclosingTypeWalker1.postWalkMemberType(); + this.enclosingTypeWalker2.postWalkMemberType(); + }; + + PullTypeResolutionContext.prototype.walkSignatures = function (kind, index, index2) { + this.enclosingTypeWalker1.walkSignature(kind, index); + this.enclosingTypeWalker2.walkSignature(kind, index2 == undefined ? index : index2); + }; + + PullTypeResolutionContext.prototype.postWalkSignatures = function () { + this.enclosingTypeWalker1.postWalkSignature(); + this.enclosingTypeWalker2.postWalkSignature(); + }; + + PullTypeResolutionContext.prototype.walkTypeParameterConstraints = function (index) { + this.enclosingTypeWalker1.walkTypeParameterConstraint(index); + this.enclosingTypeWalker2.walkTypeParameterConstraint(index); + }; + + PullTypeResolutionContext.prototype.postWalkTypeParameterConstraints = function () { + this.enclosingTypeWalker1.postWalkTypeParameterConstraint(); + this.enclosingTypeWalker2.postWalkTypeParameterConstraint(); + }; + + PullTypeResolutionContext.prototype.walkTypeArgument = function (index) { + this.enclosingTypeWalker1.walkTypeArgument(index); + this.enclosingTypeWalker2.walkTypeArgument(index); + }; + + PullTypeResolutionContext.prototype.postWalkTypeArgument = function () { + this.enclosingTypeWalker1.postWalkTypeArgument(); + this.enclosingTypeWalker2.postWalkTypeArgument(); + }; + + PullTypeResolutionContext.prototype.walkReturnTypes = function () { + this.enclosingTypeWalker1.walkReturnType(); + this.enclosingTypeWalker2.walkReturnType(); + }; + + PullTypeResolutionContext.prototype.postWalkReturnTypes = function () { + this.enclosingTypeWalker1.postWalkReturnType(); + this.enclosingTypeWalker2.postWalkReturnType(); + }; + + PullTypeResolutionContext.prototype.walkParameterTypes = function (iParam) { + this.enclosingTypeWalker1.walkParameterType(iParam); + this.enclosingTypeWalker2.walkParameterType(iParam); + }; + + PullTypeResolutionContext.prototype.postWalkParameterTypes = function () { + this.enclosingTypeWalker1.postWalkParameterType(); + this.enclosingTypeWalker2.postWalkParameterType(); + }; + + PullTypeResolutionContext.prototype.getBothKindOfIndexSignatures = function (includeAugmentedType1, includeAugmentedType2) { + var indexSigs1 = this.enclosingTypeWalker1.getBothKindOfIndexSignatures(this.resolver, this, includeAugmentedType1); + var indexSigs2 = this.enclosingTypeWalker2.getBothKindOfIndexSignatures(this.resolver, this, includeAugmentedType2); + return { indexSigs1: indexSigs1, indexSigs2: indexSigs2 }; + }; + + PullTypeResolutionContext.prototype.walkIndexSignatureReturnTypes = function (indexSigs, useStringIndexSignature1, useStringIndexSignature2, onlySignature) { + this.enclosingTypeWalker1.walkIndexSignatureReturnType(indexSigs.indexSigs1, useStringIndexSignature1, onlySignature); + this.enclosingTypeWalker2.walkIndexSignatureReturnType(indexSigs.indexSigs2, useStringIndexSignature2, onlySignature); + }; + + PullTypeResolutionContext.prototype.postWalkIndexSignatureReturnTypes = function (onlySignature) { + this.enclosingTypeWalker1.postWalkIndexSignatureReturnType(onlySignature); + this.enclosingTypeWalker2.postWalkIndexSignatureReturnType(onlySignature); + }; + + PullTypeResolutionContext.prototype.swapEnclosingTypeWalkers = function () { + var tempEnclosingWalker1 = this.enclosingTypeWalker1; + this.enclosingTypeWalker1 = this.enclosingTypeWalker2; + this.enclosingTypeWalker2 = tempEnclosingWalker1; + }; + + PullTypeResolutionContext.prototype.oneOfClassificationsIsInfinitelyExpanding = function () { + var generativeClassification1 = this.enclosingTypeWalker1.getGenerativeClassification(); + if (generativeClassification1 === 3 /* InfinitelyExpanding */) { + return true; + } + var generativeClassification2 = this.enclosingTypeWalker2.getGenerativeClassification(); + if (generativeClassification2 === 3 /* InfinitelyExpanding */) { + return true; + } + + return false; + }; + + PullTypeResolutionContext.prototype.resetEnclosingTypeWalkerStates = function () { + var enclosingTypeWalkerState1 = this.enclosingTypeWalker1 ? this.enclosingTypeWalker1.resetEnclosingTypeWalkerState() : null; + var enclosingTypeWalkerState2 = this.enclosingTypeWalker2 ? this.enclosingTypeWalker2.resetEnclosingTypeWalkerState() : null; + return { + enclosingTypeWalkerState1: enclosingTypeWalkerState1, + enclosingTypeWalkerState2: enclosingTypeWalkerState2 + }; + }; + + PullTypeResolutionContext.prototype.setEnclosingTypeWalkerStates = function (enclosingTypeWalkerStates) { + TypeScript.Debug.assert(this.enclosingTypeWalker1 || !enclosingTypeWalkerStates.enclosingTypeWalkerState1); + if (this.enclosingTypeWalker1) { + this.enclosingTypeWalker1.setEnclosingTypeWalkerState(enclosingTypeWalkerStates.enclosingTypeWalkerState1); + } + TypeScript.Debug.assert(this.enclosingTypeWalker2 || !enclosingTypeWalkerStates.enclosingTypeWalkerState2); + if (this.enclosingTypeWalker2) { + this.enclosingTypeWalker2.setEnclosingTypeWalkerState(enclosingTypeWalkerStates.enclosingTypeWalkerState2); + } + }; + return PullTypeResolutionContext; + })(); + TypeScript.PullTypeResolutionContext = PullTypeResolutionContext; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var OverloadApplicabilityStatus; + (function (OverloadApplicabilityStatus) { + OverloadApplicabilityStatus[OverloadApplicabilityStatus["NotAssignable"] = 0] = "NotAssignable"; + OverloadApplicabilityStatus[OverloadApplicabilityStatus["AssignableButWithProvisionalErrors"] = 1] = "AssignableButWithProvisionalErrors"; + OverloadApplicabilityStatus[OverloadApplicabilityStatus["AssignableWithNoProvisionalErrors"] = 2] = "AssignableWithNoProvisionalErrors"; + OverloadApplicabilityStatus[OverloadApplicabilityStatus["Subtype"] = 3] = "Subtype"; + })(OverloadApplicabilityStatus || (OverloadApplicabilityStatus = {})); + + var PullAdditionalCallResolutionData = (function () { + function PullAdditionalCallResolutionData() { + this.targetSymbol = null; + this.resolvedSignatures = null; + this.candidateSignature = null; + this.actualParametersContextTypeSymbols = null; + this.diagnosticsFromOverloadResolution = []; + } + return PullAdditionalCallResolutionData; + })(); + TypeScript.PullAdditionalCallResolutionData = PullAdditionalCallResolutionData; + + var PullAdditionalObjectLiteralResolutionData = (function () { + function PullAdditionalObjectLiteralResolutionData() { + this.membersContextTypeSymbols = null; + } + return PullAdditionalObjectLiteralResolutionData; + })(); + TypeScript.PullAdditionalObjectLiteralResolutionData = PullAdditionalObjectLiteralResolutionData; + + var MemberWithBaseOrigin = (function () { + function MemberWithBaseOrigin(memberSymbol, baseOrigin) { + this.memberSymbol = memberSymbol; + this.baseOrigin = baseOrigin; + } + return MemberWithBaseOrigin; + })(); + + var SignatureWithBaseOrigin = (function () { + function SignatureWithBaseOrigin(signature, baseOrigin) { + this.signature = signature; + this.baseOrigin = baseOrigin; + } + return SignatureWithBaseOrigin; + })(); + + var InheritedIndexSignatureInfo = (function () { + function InheritedIndexSignatureInfo() { + } + return InheritedIndexSignatureInfo; + })(); + + var CompilerReservedName; + (function (CompilerReservedName) { + CompilerReservedName[CompilerReservedName["_this"] = 1] = "_this"; + CompilerReservedName[CompilerReservedName["_super"] = 2] = "_super"; + CompilerReservedName[CompilerReservedName["arguments"] = 3] = "arguments"; + CompilerReservedName[CompilerReservedName["_i"] = 4] = "_i"; + CompilerReservedName[CompilerReservedName["require"] = 5] = "require"; + CompilerReservedName[CompilerReservedName["exports"] = 6] = "exports"; + })(CompilerReservedName || (CompilerReservedName = {})); + + function getCompilerReservedName(name) { + var nameText = name.valueText(); + return CompilerReservedName[nameText]; + } + + var PullTypeResolver = (function () { + function PullTypeResolver(compilationSettings, semanticInfoChain) { + this.compilationSettings = compilationSettings; + this.semanticInfoChain = semanticInfoChain; + this._cachedArrayInterfaceType = null; + this._cachedNumberInterfaceType = null; + this._cachedStringInterfaceType = null; + this._cachedBooleanInterfaceType = null; + this._cachedObjectInterfaceType = null; + this._cachedFunctionInterfaceType = null; + this._cachedIArgumentsInterfaceType = null; + this._cachedRegExpInterfaceType = null; + this._cachedAnyTypeArgs = null; + this.typeCheckCallBacks = []; + this.postTypeCheckWorkitems = []; + this._cachedFunctionArgumentsSymbol = null; + this.assignableCache = TypeScript.BitMatrix.getBitMatrix(true); + this.subtypeCache = TypeScript.BitMatrix.getBitMatrix(true); + this.identicalCache = TypeScript.BitMatrix.getBitMatrix(true); + this.inResolvingOtherDeclsWalker = new TypeScript.PullHelpers.OtherPullDeclsWalker(); + } + PullTypeResolver.prototype.cachedArrayInterfaceType = function () { + if (!this._cachedArrayInterfaceType) { + this._cachedArrayInterfaceType = this.getSymbolFromDeclPath("Array", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (!this._cachedArrayInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedArrayInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedArrayInterfaceType; + }; + + PullTypeResolver.prototype.getArrayNamedType = function () { + return this.cachedArrayInterfaceType(); + }; + + PullTypeResolver.prototype.cachedNumberInterfaceType = function () { + if (!this._cachedNumberInterfaceType) { + this._cachedNumberInterfaceType = this.getSymbolFromDeclPath("Number", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedNumberInterfaceType && !this._cachedNumberInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedNumberInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedNumberInterfaceType; + }; + + PullTypeResolver.prototype.cachedStringInterfaceType = function () { + if (!this._cachedStringInterfaceType) { + this._cachedStringInterfaceType = this.getSymbolFromDeclPath("String", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedStringInterfaceType && !this._cachedStringInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedStringInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedStringInterfaceType; + }; + + PullTypeResolver.prototype.cachedBooleanInterfaceType = function () { + if (!this._cachedBooleanInterfaceType) { + this._cachedBooleanInterfaceType = this.getSymbolFromDeclPath("Boolean", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedBooleanInterfaceType && !this._cachedBooleanInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedBooleanInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedBooleanInterfaceType; + }; + + PullTypeResolver.prototype.cachedObjectInterfaceType = function () { + if (!this._cachedObjectInterfaceType) { + this._cachedObjectInterfaceType = this.getSymbolFromDeclPath("Object", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (!this._cachedObjectInterfaceType) { + this._cachedObjectInterfaceType = this.semanticInfoChain.anyTypeSymbol; + } + + if (!this._cachedObjectInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedObjectInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedObjectInterfaceType; + }; + + PullTypeResolver.prototype.cachedFunctionInterfaceType = function () { + if (!this._cachedFunctionInterfaceType) { + this._cachedFunctionInterfaceType = this.getSymbolFromDeclPath("Function", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedFunctionInterfaceType && !this._cachedFunctionInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedFunctionInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedFunctionInterfaceType; + }; + + PullTypeResolver.prototype.cachedIArgumentsInterfaceType = function () { + if (!this._cachedIArgumentsInterfaceType) { + this._cachedIArgumentsInterfaceType = this.getSymbolFromDeclPath("IArguments", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedIArgumentsInterfaceType && !this._cachedIArgumentsInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedIArgumentsInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedIArgumentsInterfaceType; + }; + + PullTypeResolver.prototype.cachedRegExpInterfaceType = function () { + if (!this._cachedRegExpInterfaceType) { + this._cachedRegExpInterfaceType = this.getSymbolFromDeclPath("RegExp", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedRegExpInterfaceType && !this._cachedRegExpInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedRegExpInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedRegExpInterfaceType; + }; + + PullTypeResolver.prototype.cachedFunctionArgumentsSymbol = function () { + if (!this._cachedFunctionArgumentsSymbol) { + this._cachedFunctionArgumentsSymbol = new TypeScript.PullSymbol("arguments", 512 /* Variable */); + this._cachedFunctionArgumentsSymbol.type = this.cachedIArgumentsInterfaceType() || this.semanticInfoChain.anyTypeSymbol; + this._cachedFunctionArgumentsSymbol.setResolved(); + + var functionArgumentsDecl = new TypeScript.PullSynthesizedDecl("arguments", "arguments", 2048 /* Parameter */, 0 /* None */, null, this.semanticInfoChain); + functionArgumentsDecl.setSymbol(this._cachedFunctionArgumentsSymbol); + this._cachedFunctionArgumentsSymbol.addDeclaration(functionArgumentsDecl); + } + + return this._cachedFunctionArgumentsSymbol; + }; + + PullTypeResolver.prototype.getApparentType = function (type) { + if (type.isTypeParameter()) { + var baseConstraint = type.getBaseConstraint(this.semanticInfoChain); + if (baseConstraint === this.semanticInfoChain.anyTypeSymbol) { + return this.semanticInfoChain.emptyTypeSymbol; + } else { + type = baseConstraint; + } + } + if (type.isPrimitive()) { + if (type === this.semanticInfoChain.numberTypeSymbol) { + return this.cachedNumberInterfaceType(); + } + if (type === this.semanticInfoChain.booleanTypeSymbol) { + return this.cachedBooleanInterfaceType(); + } + if (type === this.semanticInfoChain.stringTypeSymbol) { + return this.cachedStringInterfaceType(); + } + return type; + } + if (type.isEnum()) { + return this.cachedNumberInterfaceType(); + } + return type; + }; + + PullTypeResolver.prototype.setTypeChecked = function (ast, context) { + context.setTypeChecked(ast); + }; + + PullTypeResolver.prototype.canTypeCheckAST = function (ast, context) { + return context.canTypeCheckAST(ast); + }; + + PullTypeResolver.prototype.setSymbolForAST = function (ast, symbol, context) { + if (context && context.inProvisionalResolution()) { + context.setSymbolForAST(ast, symbol); + } else { + this.semanticInfoChain.setSymbolForAST(ast, symbol); + } + }; + + PullTypeResolver.prototype.getSymbolForAST = function (ast, context) { + var symbol = this.semanticInfoChain.getSymbolForAST(ast); + + if (!symbol) { + if (context && context.inProvisionalResolution()) { + symbol = context.getSymbolForAST(ast); + } + } + + return symbol; + }; + + PullTypeResolver.prototype.getASTForDecl = function (decl) { + return this.semanticInfoChain.getASTForDecl(decl); + }; + + PullTypeResolver.prototype.getNewErrorTypeSymbol = function (name) { + if (typeof name === "undefined") { name = null; } + return new TypeScript.PullErrorTypeSymbol(this.semanticInfoChain.anyTypeSymbol, name); + }; + + PullTypeResolver.prototype.getEnclosingDecl = function (decl) { + var declPath = decl.getParentPath(); + + if (declPath.length > 1 && declPath[declPath.length - 1] === decl) { + return declPath[declPath.length - 2]; + } else { + return declPath[declPath.length - 1]; + } + }; + + PullTypeResolver.prototype.getExportedMemberSymbol = function (symbol, parent) { + if (!(symbol.kind & (65536 /* Method */ | 4096 /* Property */))) { + var isContainer = (parent.kind & (4 /* Container */ | 32 /* DynamicModule */)) !== 0; + var containerType = !isContainer ? parent.getAssociatedContainerType() : parent; + + if (isContainer && containerType) { + if (symbol.anyDeclHasFlag(1 /* Exported */)) { + return symbol; + } + + return null; + } + } + + return symbol; + }; + + PullTypeResolver.prototype._getNamedPropertySymbolOfAugmentedType = function (symbolName, parent) { + var memberSymbol = this.getNamedPropertySymbol(symbolName, 68147712 /* SomeValue */, parent); + if (memberSymbol) { + return memberSymbol; + } + + if (this.cachedFunctionInterfaceType() && parent.isFunctionType()) { + memberSymbol = this.cachedFunctionInterfaceType().findMember(symbolName, true); + if (memberSymbol) { + return memberSymbol; + } + } + + if (this.cachedObjectInterfaceType()) { + return this.cachedObjectInterfaceType().findMember(symbolName, true); + } + + return null; + }; + + PullTypeResolver.prototype.getNamedPropertySymbol = function (symbolName, declSearchKind, parent) { + var member = null; + + if (declSearchKind & 68147712 /* SomeValue */) { + member = parent.findMember(symbolName, true); + } else if (declSearchKind & 58728795 /* SomeType */) { + member = parent.findNestedType(symbolName); + } else if (declSearchKind & 164 /* SomeContainer */) { + member = parent.findNestedContainer(symbolName); + } + + if (member) { + return this.getExportedMemberSymbol(member, parent); + } + + var containerType = parent.getAssociatedContainerType(); + + if (containerType) { + if (containerType.isClass()) { + return null; + } + + parent = containerType; + + if (declSearchKind & 68147712 /* SomeValue */) { + member = parent.findMember(symbolName, true); + } else if (declSearchKind & 58728795 /* SomeType */) { + member = parent.findNestedType(symbolName); + } else if (declSearchKind & 164 /* SomeContainer */) { + member = parent.findNestedContainer(symbolName); + } + + if (member) { + return this.getExportedMemberSymbol(member, parent); + } + } + + if (parent.kind & 164 /* SomeContainer */) { + var typeDeclarations = parent.getDeclarations(); + var childDecls = null; + + for (var j = 0; j < typeDeclarations.length; j++) { + childDecls = typeDeclarations[j].searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + member = childDecls[0].getSymbol(); + + if (!member) { + member = childDecls[0].getSignatureSymbol(); + } + return this.getExportedMemberSymbol(member, parent); + } + + if ((declSearchKind & 58728795 /* SomeType */) !== 0 || (declSearchKind & 68147712 /* SomeValue */) !== 0) { + childDecls = typeDeclarations[j].searchChildDecls(symbolName, 128 /* TypeAlias */); + if (childDecls.length && childDecls[0].kind === 128 /* TypeAlias */) { + var aliasSymbol = this.getExportedMemberSymbol(childDecls[0].getSymbol(), parent); + if (aliasSymbol) { + if ((declSearchKind & 58728795 /* SomeType */) !== 0) { + var typeSymbol = aliasSymbol.getExportAssignedTypeSymbol(); + if (typeSymbol) { + return typeSymbol; + } + } else { + var valueSymbol = aliasSymbol.getExportAssignedValueSymbol(); + if (valueSymbol) { + aliasSymbol.setIsUsedAsValue(); + return valueSymbol; + } + } + + return aliasSymbol; + } + } + } + } + } + }; + + PullTypeResolver.prototype.getSymbolFromDeclPath = function (symbolName, declPath, declSearchKind) { + var _this = this; + var symbol = null; + + var decl = null; + var childDecls; + var declSymbol = null; + var declMembers; + var pathDeclKind; + var valDecl = null; + var kind; + var instanceSymbol = null; + var instanceType = null; + var childSymbol = null; + + var allowedContainerDeclKind = 4 /* Container */ | 32 /* DynamicModule */; + if (TypeScript.hasFlag(declSearchKind, 67108864 /* EnumMember */)) { + allowedContainerDeclKind |= 64 /* Enum */; + } + + var isAcceptableAlias = function (symbol) { + if (symbol.isAlias()) { + _this.resolveDeclaredSymbol(symbol); + if (TypeScript.hasFlag(declSearchKind, 164 /* SomeContainer */)) { + if (symbol.assignedContainer() || symbol.getExportAssignedContainerSymbol()) { + return true; + } + } else if (TypeScript.hasFlag(declSearchKind, 58728795 /* SomeType */)) { + var type = symbol.getExportAssignedTypeSymbol(); + if (type && type.kind !== 32 /* DynamicModule */) { + return true; + } + + var type = symbol.assignedType(); + if (type && type.kind !== 32 /* DynamicModule */) { + return true; + } + } else if (TypeScript.hasFlag(declSearchKind, 68147712 /* SomeValue */ & ~67108864 /* EnumMember */)) { + if (symbol.assignedType() && symbol.assignedType().isError()) { + return true; + } else if (symbol.assignedValue() || symbol.getExportAssignedValueSymbol()) { + return true; + } else { + var assignedType = symbol.assignedType(); + if (assignedType && assignedType.isContainer() && assignedType.getInstanceType()) { + return true; + } + + var decls = symbol.getDeclarations(); + var ast = decls[0].ast(); + return ast.moduleReference.kind() === 245 /* ExternalModuleReference */; + } + } + } + + return false; + }; + + var tryFindAlias = function (decl) { + var childDecls = decl.searchChildDecls(symbolName, 128 /* TypeAlias */); + + if (childDecls.length) { + var sym = childDecls[0].getSymbol(); + if (isAcceptableAlias(sym)) { + return sym; + } + } + return null; + }; + + for (var i = declPath.length - 1; i >= 0; i--) { + decl = declPath[i]; + pathDeclKind = decl.kind; + + if (decl.flags & 2097152 /* DeclaredInAWithBlock */) { + return this.semanticInfoChain.anyTypeSymbol; + } + + if (pathDeclKind & allowedContainerDeclKind) { + childDecls = decl.searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + return childDecls[0].getSymbol(); + } + + var alias = tryFindAlias(decl); + if (alias) { + return alias; + } + + if (declSearchKind & 68147712 /* SomeValue */) { + instanceSymbol = decl.getSymbol().getInstanceSymbol(); + + if (instanceSymbol) { + instanceType = instanceSymbol.type; + + childSymbol = this.getNamedPropertySymbol(symbolName, declSearchKind, instanceType); + + if (childSymbol && (childSymbol.kind & declSearchKind) && !childSymbol.anyDeclHasFlag(16 /* Static */)) { + return childSymbol; + } + } + + valDecl = decl.getValueDecl(); + + if (valDecl) { + decl = valDecl; + } + } + + declSymbol = decl.getSymbol().type; + + var childSymbol = this.getNamedPropertySymbol(symbolName, declSearchKind, declSymbol); + + if (childSymbol && (childSymbol.kind & declSearchKind) && !childSymbol.anyDeclHasFlag(16 /* Static */)) { + return childSymbol; + } + } else if ((declSearchKind & (58728795 /* SomeType */ | 164 /* SomeContainer */)) || !(pathDeclKind & 8 /* Class */)) { + var candidateSymbol = null; + + if (pathDeclKind === 131072 /* FunctionExpression */ && symbolName === decl.getFunctionExpressionName()) { + candidateSymbol = decl.getSymbol(); + } + + childDecls = decl.searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + if (decl.kind & 1032192 /* SomeFunction */) { + decl.ensureSymbolIsBound(); + } + return childDecls[0].getSymbol(); + } + + if (candidateSymbol) { + return candidateSymbol; + } + + var alias = tryFindAlias(decl); + if (alias) { + return alias; + } + } + } + + symbol = this.semanticInfoChain.findSymbol([symbolName], declSearchKind); + if (symbol) { + return symbol; + } + + if (!TypeScript.hasFlag(declSearchKind, 128 /* TypeAlias */)) { + symbol = this.semanticInfoChain.findSymbol([symbolName], 128 /* TypeAlias */); + if (symbol && isAcceptableAlias(symbol)) { + return symbol; + } + } + + return null; + }; + + PullTypeResolver.prototype.getVisibleDeclsFromDeclPath = function (declPath, declSearchKind) { + var result = []; + var decl = null; + var childDecls; + var pathDeclKind; + + for (var i = declPath.length - 1; i >= 0; i--) { + decl = declPath[i]; + pathDeclKind = decl.kind; + + var declKind = decl.kind; + + if (declKind !== 8 /* Class */ && declKind !== 16 /* Interface */) { + this.addFilteredDecls(decl.getChildDecls(), declSearchKind, result); + } + + switch (declKind) { + case 4 /* Container */: + case 32 /* DynamicModule */: + var otherDecls = this.semanticInfoChain.findDeclsFromPath(declPath.slice(0, i + 1), 164 /* SomeContainer */); + for (var j = 0, m = otherDecls.length; j < m; j++) { + var otherDecl = otherDecls[j]; + if (otherDecl === decl) { + continue; + } + + var otherDeclChildren = otherDecl.getChildDecls(); + for (var k = 0, s = otherDeclChildren.length; k < s; k++) { + var otherDeclChild = otherDeclChildren[k]; + if ((otherDeclChild.flags & 1 /* Exported */) && (otherDeclChild.kind & declSearchKind)) { + result.push(otherDeclChild); + } + } + } + + break; + + case 8 /* Class */: + case 16 /* Interface */: + var parameters = decl.getTypeParameters(); + if (parameters && parameters.length) { + this.addFilteredDecls(parameters, declSearchKind, result); + } + + break; + + case 131072 /* FunctionExpression */: + var functionExpressionName = decl.getFunctionExpressionName(); + if (functionExpressionName) { + result.push(decl); + } + + case 16384 /* Function */: + case 32768 /* ConstructorMethod */: + case 65536 /* Method */: + var parameters = decl.getTypeParameters(); + if (parameters && parameters.length) { + this.addFilteredDecls(parameters, declSearchKind, result); + } + + break; + } + } + + var topLevelDecls = this.semanticInfoChain.topLevelDecls(); + for (var i = 0, n = topLevelDecls.length; i < n; i++) { + var topLevelDecl = topLevelDecls[i]; + if (declPath.length > 0 && topLevelDecl.fileName() === declPath[0].fileName()) { + continue; + } + + if (!topLevelDecl.isExternalModule()) { + this.addFilteredDecls(topLevelDecl.getChildDecls(), declSearchKind, result); + } + } + + return result; + }; + + PullTypeResolver.prototype.addFilteredDecls = function (decls, declSearchKind, result) { + if (decls.length) { + for (var i = 0, n = decls.length; i < n; i++) { + var decl = decls[i]; + if (decl.kind & declSearchKind) { + result.push(decl); + } + } + } + }; + + PullTypeResolver.prototype.getVisibleDecls = function (enclosingDecl) { + var declPath = enclosingDecl.getParentPath(); + + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + + return this.getVisibleDeclsFromDeclPath(declPath, declSearchKind); + }; + + PullTypeResolver.prototype.getVisibleContextSymbols = function (enclosingDecl, context) { + var contextualTypeSymbol = context.getContextualType(); + if (!contextualTypeSymbol || this.isAnyOrEquivalent(contextualTypeSymbol)) { + return null; + } + + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + var members = contextualTypeSymbol.getAllMembers(declSearchKind, 2 /* externallyVisible */); + + for (var i = 0; i < members.length; i++) { + members[i].setUnresolved(); + } + + return members; + }; + + PullTypeResolver.prototype.getVisibleMembersFromExpression = function (expression, enclosingDecl, context) { + var lhs = this.resolveAST(expression, false, context); + + if (isTypesOnlyLocation(expression) && (lhs.kind === 8 /* Class */ || lhs.kind === 16 /* Interface */ || lhs.kind === 64 /* Enum */)) { + return null; + } + + var lhsType = lhs.type; + if (!lhsType) { + return null; + } + + this.resolveDeclaredSymbol(lhsType, context); + + if (lhsType.isContainer() && lhsType.isAlias()) { + lhsType = lhsType.getExportAssignedTypeSymbol(); + } + + if (this.isAnyOrEquivalent(lhsType)) { + return null; + } + + var memberVisibilty = 2 /* externallyVisible */; + var containerSymbol = lhsType; + if (containerSymbol.kind === 33554432 /* ConstructorType */) { + containerSymbol = containerSymbol.getConstructSignatures()[0].returnType; + } + + if (containerSymbol && containerSymbol.isClass()) { + var declPath = enclosingDecl.getParentPath(); + if (declPath && declPath.length) { + var declarations = containerSymbol.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + var declaration = declarations[i]; + if (TypeScript.ArrayUtilities.contains(declPath, declaration)) { + memberVisibilty = 1 /* internallyVisible */; + break; + } + } + } + } + + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + + var members = []; + + if (lhsType.isContainer()) { + var exportedAssignedContainerSymbol = lhsType.getExportAssignedContainerSymbol(); + if (exportedAssignedContainerSymbol) { + lhsType = exportedAssignedContainerSymbol; + } + } + + lhsType = this.getApparentType(lhsType); + + if (!lhsType.isResolved) { + var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, context); + + if (potentiallySpecializedType !== lhsType) { + if (!lhs.isType()) { + context.setTypeInContext(lhs, potentiallySpecializedType); + } + + lhsType = potentiallySpecializedType; + } + } + + members = lhsType.getAllMembers(declSearchKind, memberVisibilty); + + if (lhsType.isContainer()) { + var associatedInstance = lhsType.getInstanceSymbol(); + if (associatedInstance) { + var instanceType = associatedInstance.type; + this.resolveDeclaredSymbol(instanceType, context); + var instanceMembers = instanceType.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(instanceMembers); + } + + var exportedContainer = lhsType.getExportAssignedContainerSymbol(); + if (exportedContainer) { + var exportedContainerMembers = exportedContainer.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(exportedContainerMembers); + } + } else if (!lhsType.isConstructor() && !lhsType.isEnum()) { + var associatedContainerSymbol = lhsType.getAssociatedContainerType(); + if (associatedContainerSymbol) { + var containerType = associatedContainerSymbol.type; + this.resolveDeclaredSymbol(containerType, context); + var containerMembers = containerType.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(containerMembers); + } + } + + if (lhsType.isFunctionType() && this.cachedFunctionInterfaceType()) { + members = members.concat(this.cachedFunctionInterfaceType().getAllMembers(declSearchKind, 2 /* externallyVisible */)); + } + + return members; + }; + + PullTypeResolver.prototype.isAnyOrEquivalent = function (type) { + return (type === this.semanticInfoChain.anyTypeSymbol) || type.isError(); + }; + + PullTypeResolver.prototype.resolveExternalModuleReference = function (idText, currentFileName) { + var originalIdText = idText; + var symbol = null; + + if (TypeScript.isRelative(originalIdText)) { + var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); + symbol = this.semanticInfoChain.findExternalModule(path + idText); + } else { + idText = originalIdText; + + symbol = this.semanticInfoChain.findAmbientExternalModuleInGlobalContext(TypeScript.quoteStr(originalIdText)); + + if (!symbol) { + var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); + + while (symbol === null && path != "") { + symbol = this.semanticInfoChain.findExternalModule(path + idText); + if (symbol === null) { + if (path === '/') { + path = ''; + } else { + path = TypeScript.normalizePath(path + ".."); + path = path && path != '/' ? path + '/' : path; + } + } + } + } + } + + return symbol; + }; + + PullTypeResolver.prototype.resolveDeclaredSymbol = function (symbol, context) { + if (!symbol || symbol.isResolved || symbol.isTypeReference()) { + return symbol; + } + + if (!context) { + context = new TypeScript.PullTypeResolutionContext(this); + } + + return this.resolveDeclaredSymbolWorker(symbol, context); + }; + + PullTypeResolver.prototype.resolveDeclaredSymbolWorker = function (symbol, context) { + if (!symbol || symbol.isResolved) { + return symbol; + } + + if (symbol.inResolution) { + if (!symbol.type && !symbol.isType()) { + symbol.type = this.semanticInfoChain.anyTypeSymbol; + } + + return symbol; + } + + var decls = symbol.getDeclarations(); + + for (var i = 0; i < decls.length; i++) { + var decl = decls[i]; + + var ast = this.semanticInfoChain.getASTForDecl(decl); + + if (!ast || (ast.kind() === 139 /* GetAccessor */ && ast.parent.parent.kind() === 215 /* ObjectLiteralExpression */) || (ast.kind() === 140 /* SetAccessor */ && ast.parent.parent.kind() === 215 /* ObjectLiteralExpression */)) { + return symbol; + } + + if (ast.parent && ast.parent.kind() === 236 /* CatchClause */ && ast.parent.identifier === ast) { + return symbol; + } + + if (ast.parent && ast.parent.kind() === 219 /* SimpleArrowFunctionExpression */ && ast.parent.identifier === ast) { + return symbol; + } + + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(ast); + var resolvedSymbol; + if (enclosingModule) { + resolvedSymbol = this.resolveSingleModuleDeclaration(enclosingModule, ast, context); + } else if (ast.kind() === 120 /* SourceUnit */ && decl.kind === 32 /* DynamicModule */) { + resolvedSymbol = this.resolveModuleSymbol(decl.getSymbol(), context, null, null, ast); + } else { + TypeScript.Debug.assert(ast.kind() !== 11 /* IdentifierName */ && ast.kind() !== 212 /* MemberAccessExpression */); + resolvedSymbol = this.resolveAST(ast, false, context); + } + + if (decl.kind === 2048 /* Parameter */ && !symbol.isResolved && !symbol.type && resolvedSymbol && symbol.anyDeclHasFlag(8388608 /* PropertyParameter */ | 67108864 /* ConstructorParameter */)) { + symbol.type = resolvedSymbol.type; + symbol.setResolved(); + } + } + + if (!symbol.isResolved) { + TypeScript.Debug.assert(!symbol.inResolution); + + symbol.setResolved(); + } + + return symbol; + }; + + PullTypeResolver.prototype.resolveOtherDecl = function (otherDecl, context) { + var astForOtherDecl = this.getASTForDecl(otherDecl); + var moduleDecl = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(astForOtherDecl); + if (moduleDecl) { + this.resolveSingleModuleDeclaration(moduleDecl, astForOtherDecl, context); + } else { + this.resolveAST(astForOtherDecl, false, context); + } + }; + + PullTypeResolver.prototype.resolveOtherDeclarations = function (astName, context) { + var _this = this; + var resolvedDecl = this.semanticInfoChain.getDeclForAST(astName); + var symbol = resolvedDecl.getSymbol(); + + var allDecls = symbol.getDeclarations(); + this.inResolvingOtherDeclsWalker.walkOtherPullDecls(resolvedDecl, symbol.getDeclarations(), function (otherDecl) { + return _this.resolveOtherDecl(otherDecl, context); + }); + }; + + PullTypeResolver.prototype.resolveSourceUnit = function (sourceUnit, context) { + var enclosingDecl = this.getEnclosingDeclForAST(sourceUnit); + var moduleSymbol = enclosingDecl.getSymbol(); + this.ensureAllSymbolsAreBound(moduleSymbol); + + this.resolveFirstExportAssignmentStatement(sourceUnit.moduleElements, context); + this.resolveAST(sourceUnit.moduleElements, false, context); + + if (this.canTypeCheckAST(sourceUnit, context)) { + this.typeCheckSourceUnit(sourceUnit, context); + } + + return moduleSymbol; + }; + + PullTypeResolver.prototype.typeCheckSourceUnit = function (sourceUnit, context) { + var _this = this; + this.setTypeChecked(sourceUnit, context); + + this.resolveAST(sourceUnit.moduleElements, false, context); + + this.typeCheckCallBacks.push(function (context) { + return _this.verifyUniquenessOfImportNamesInSourceUnit(sourceUnit); + }); + }; + + PullTypeResolver.prototype.verifyUniquenessOfImportNamesInSourceUnit = function (sourceUnit) { + var _this = this; + var enclosingDecl = this.semanticInfoChain.getDeclForAST(sourceUnit); + + var doesImportNameExistInOtherFiles = function (name) { + var importSymbol = _this.semanticInfoChain.findTopLevelSymbol(name, 128 /* TypeAlias */, null); + return importSymbol && importSymbol.isAlias(); + }; + + this.checkUniquenessOfImportNames([enclosingDecl], doesImportNameExistInOtherFiles); + }; + + PullTypeResolver.prototype.resolveEnumDeclaration = function (ast, context) { + var containerDecl = this.semanticInfoChain.getDeclForAST(ast); + var containerSymbol = containerDecl.getSymbol(); + + if (containerSymbol.isResolved || containerSymbol.inResolution) { + return containerSymbol; + } + + containerSymbol.inResolution = true; + + var containerDecls = containerSymbol.getDeclarations(); + + for (var i = 0; i < containerDecls.length; i++) { + var childDecls = containerDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + + containerSymbol.setResolved(); + + this.resolveOtherDeclarations(ast, context); + + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckEnumDeclaration(ast, context); + } + + return containerSymbol; + }; + + PullTypeResolver.prototype.typeCheckEnumDeclaration = function (ast, context) { + var _this = this; + this.setTypeChecked(ast, context); + + this.resolveAST(ast.enumElements, false, context); + var containerDecl = this.semanticInfoChain.getDeclForAST(ast); + this.validateVariableDeclarationGroups(containerDecl, context); + + this.typeCheckCallBacks.push(function (context) { + return _this.checkInitializersInEnumDeclarations(containerDecl, context); + }); + + if (!TypeScript.ASTHelpers.enumIsElided(ast)) { + this.checkNameForCompilerGeneratedDeclarationCollision(ast, true, ast.identifier, context); + } + }; + + PullTypeResolver.prototype.postTypeCheckEnumDeclaration = function (ast, context) { + this.checkThisCaptureVariableCollides(ast, true, context); + }; + + PullTypeResolver.prototype.checkInitializersInEnumDeclarations = function (decl, context) { + var symbol = decl.getSymbol(); + + var declarations = symbol.getDeclarations(); + if (decl !== declarations[0]) { + return; + } + + var seenEnumDeclWithNoFirstMember = false; + for (var i = 0; i < declarations.length; ++i) { + var currentDecl = declarations[i]; + + var ast = currentDecl.ast(); + if (ast.enumElements.nonSeparatorCount() === 0) { + continue; + } + + var firstVariable = ast.enumElements.nonSeparatorAt(0); + if (!firstVariable.equalsValueClause) { + if (!seenEnumDeclWithNoFirstMember) { + seenEnumDeclWithNoFirstMember = true; + } else { + this.semanticInfoChain.addDiagnosticFromAST(firstVariable, TypeScript.DiagnosticCode.In_enums_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_the_first_enum_element); + } + } + } + }; + + PullTypeResolver.prototype.resolveModuleDeclaration = function (ast, context) { + var result; + + if (ast.stringLiteral) { + result = this.resolveSingleModuleDeclaration(ast, ast.stringLiteral, context); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(ast.name); + for (var i = 0, n = moduleNames.length; i < n; i++) { + result = this.resolveSingleModuleDeclaration(ast, moduleNames[i], context); + } + } + + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckModuleDeclaration(ast, context); + } + + return result; + }; + + PullTypeResolver.prototype.ensureAllSymbolsAreBound = function (containerSymbol) { + if (containerSymbol) { + var containerDecls = containerSymbol.getDeclarations(); + + for (var i = 0; i < containerDecls.length; i++) { + var childDecls = containerDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + } + }; + + PullTypeResolver.prototype.resolveModuleSymbol = function (containerSymbol, context, moduleDeclAST, moduleDeclNameAST, sourceUnitAST) { + if (containerSymbol.isResolved || containerSymbol.inResolution) { + return containerSymbol; + } + + containerSymbol.inResolution = true; + this.ensureAllSymbolsAreBound(containerSymbol); + + var instanceSymbol = containerSymbol.getInstanceSymbol(); + + if (instanceSymbol) { + this.resolveDeclaredSymbol(instanceSymbol, context); + } + + var isLastName = TypeScript.ASTHelpers.isLastNameOfModule(moduleDeclAST, moduleDeclNameAST); + if (isLastName) { + this.resolveFirstExportAssignmentStatement(moduleDeclAST.moduleElements, context); + } else if (sourceUnitAST) { + this.resolveFirstExportAssignmentStatement(sourceUnitAST.moduleElements, context); + } + + containerSymbol.setResolved(); + + if (moduleDeclNameAST) { + this.resolveOtherDeclarations(moduleDeclNameAST, context); + } + + return containerSymbol; + }; + + PullTypeResolver.prototype.resolveFirstExportAssignmentStatement = function (moduleElements, context) { + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var moduleElement = moduleElements.childAt(i); + if (moduleElement.kind() === 134 /* ExportAssignment */) { + this.resolveExportAssignmentStatement(moduleElement, context); + return; + } + } + }; + + PullTypeResolver.prototype.resolveSingleModuleDeclaration = function (ast, astName, context) { + var containerDecl = this.semanticInfoChain.getDeclForAST(astName); + var containerSymbol = containerDecl.getSymbol(); + + return this.resolveModuleSymbol(containerSymbol, context, ast, astName, null); + }; + + PullTypeResolver.prototype.typeCheckModuleDeclaration = function (ast, context) { + if (ast.stringLiteral) { + this.typeCheckSingleModuleDeclaration(ast, ast.stringLiteral, context); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(ast.name); + for (var i = 0, n = moduleNames.length; i < n; i++) { + this.typeCheckSingleModuleDeclaration(ast, moduleNames[i], context); + } + } + }; + + PullTypeResolver.prototype.typeCheckSingleModuleDeclaration = function (ast, astName, context) { + var _this = this; + this.setTypeChecked(ast, context); + + if (TypeScript.ASTHelpers.isLastNameOfModule(ast, astName)) { + this.resolveAST(ast.moduleElements, false, context); + } + + var containerDecl = this.semanticInfoChain.getDeclForAST(astName); + this.validateVariableDeclarationGroups(containerDecl, context); + + if (ast.stringLiteral) { + if (TypeScript.isRelative(ast.stringLiteral.valueText())) { + this.semanticInfoChain.addDiagnosticFromAST(ast.stringLiteral, TypeScript.DiagnosticCode.Ambient_external_module_declaration_cannot_specify_relative_module_name); + } + } + + if (!TypeScript.ASTHelpers.moduleIsElided(ast) && !ast.stringLiteral) { + this.checkNameForCompilerGeneratedDeclarationCollision(astName, true, astName, context); + } + + this.typeCheckCallBacks.push(function (context) { + return _this.verifyUniquenessOfImportNamesInModule(containerDecl); + }); + }; + + PullTypeResolver.prototype.verifyUniquenessOfImportNamesInModule = function (decl) { + var symbol = decl.getSymbol(); + if (!symbol) { + return; + } + + var decls = symbol.getDeclarations(); + + if (decls[0] !== decl) { + return; + } + + this.checkUniquenessOfImportNames(decls); + }; + + PullTypeResolver.prototype.checkUniquenessOfImportNames = function (decls, doesNameExistOutside) { + var _this = this; + var importDeclarationNames; + + for (var i = 0; i < decls.length; ++i) { + var childDecls = decls[i].getChildDecls(); + for (var j = 0; j < childDecls.length; ++j) { + var childDecl = childDecls[j]; + if (childDecl.kind === 128 /* TypeAlias */) { + importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); + importDeclarationNames[childDecl.name] = true; + } + } + } + + if (!importDeclarationNames && !doesNameExistOutside) { + return; + } + + for (var i = 0; i < decls.length; ++i) { + this.scanVariableDeclarationGroups(decls[i], function (firstDeclInGroup) { + var nameConflict = importDeclarationNames && importDeclarationNames[firstDeclInGroup.name]; + if (!nameConflict) { + nameConflict = doesNameExistOutside && doesNameExistOutside(firstDeclInGroup.name); + if (nameConflict) { + importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); + importDeclarationNames[firstDeclInGroup.name] = true; + } + } + + if (nameConflict) { + _this.semanticInfoChain.addDiagnosticFromAST(firstDeclInGroup.ast(), TypeScript.DiagnosticCode.Variable_declaration_cannot_have_the_same_name_as_an_import_declaration); + } + }); + } + }; + + PullTypeResolver.prototype.scanVariableDeclarationGroups = function (enclosingDecl, firstDeclHandler, subsequentDeclHandler) { + var declGroups = enclosingDecl.getVariableDeclGroups(); + + for (var i = 0; i < declGroups.length; i++) { + var firstSymbol = null; + var enclosingDeclForFirstSymbol = null; + + if (enclosingDecl.kind === 1 /* Script */ && declGroups[i].length) { + var name = declGroups[i][0].name; + var candidateSymbol = this.semanticInfoChain.findTopLevelSymbol(name, 512 /* Variable */, enclosingDecl); + if (candidateSymbol) { + if (!candidateSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */)) { + if (!candidateSymbol.isResolved) { + this.resolveDeclaredSymbol(candidateSymbol); + } + firstSymbol = candidateSymbol; + } + } + } + + for (var j = 0; j < declGroups[i].length; j++) { + var decl = declGroups[i][j]; + + var name = decl.name; + + var symbol = decl.getSymbol(); + + if (j === 0) { + firstDeclHandler(decl); + if (!subsequentDeclHandler) { + break; + } + + if (!firstSymbol || !firstSymbol.type) { + firstSymbol = symbol; + continue; + } + } + + subsequentDeclHandler(decl, firstSymbol); + } + } + }; + + PullTypeResolver.prototype.postTypeCheckModuleDeclaration = function (ast, context) { + this.checkThisCaptureVariableCollides(ast, true, context); + }; + + PullTypeResolver.prototype.isTypeRefWithoutTypeArgs = function (term) { + if (term.kind() === 11 /* IdentifierName */) { + return true; + } else if (term.kind() === 121 /* QualifiedName */) { + var binex = term; + + if (binex.right.kind() === 11 /* IdentifierName */) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.createInstantiatedType = function (type, typeArguments) { + if (!type.isGeneric()) { + return type; + } + + var typeParameters = type.getTypeArgumentsOrTypeParameters(); + + var typeParameterArgumentMap = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameterArgumentMap[typeParameters[i].pullSymbolID] = typeArguments[i] || new TypeScript.PullErrorTypeSymbol(this.semanticInfoChain.anyTypeSymbol, typeParameters[i].name); + } + + return TypeScript.PullInstantiatedTypeReferenceSymbol.create(this, type, typeParameterArgumentMap); + }; + + PullTypeResolver.prototype.resolveReferenceTypeDeclaration = function (classOrInterface, name, heritageClauses, context) { + var _this = this; + var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var enclosingDecl = this.getEnclosingDecl(typeDecl); + var typeDeclSymbol = typeDecl.getSymbol(); + var typeDeclIsClass = classOrInterface.kind() === 131 /* ClassDeclaration */; + var hasVisited = this.getSymbolForAST(classOrInterface, context) !== null; + + if ((typeDeclSymbol.isResolved && hasVisited) || (typeDeclSymbol.inResolution && !context.isInBaseTypeResolution())) { + return typeDeclSymbol; + } + + var wasResolving = typeDeclSymbol.inResolution; + typeDeclSymbol.startResolving(); + + var typeRefDecls = typeDeclSymbol.getDeclarations(); + + for (var i = 0; i < typeRefDecls.length; i++) { + var childDecls = typeRefDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + + if (!typeDeclSymbol.isResolved) { + var typeDeclTypeParameters = typeDeclSymbol.getTypeParameters(); + for (var i = 0; i < typeDeclTypeParameters.length; i++) { + this.resolveDeclaredSymbol(typeDeclTypeParameters[i], context); + } + } + + var wasInBaseTypeResolution = context.startBaseTypeResolution(); + + if (!typeDeclIsClass && !hasVisited) { + typeDeclSymbol.resetKnownBaseTypeCount(); + } + + var extendsClause = TypeScript.ASTHelpers.getExtendsHeritageClause(heritageClauses); + if (extendsClause) { + for (var i = typeDeclSymbol.getKnownBaseTypeCount(); i < extendsClause.typeNames.nonSeparatorCount(); i = typeDeclSymbol.getKnownBaseTypeCount()) { + typeDeclSymbol.incrementKnownBaseCount(); + var parentType = this.resolveTypeReference(extendsClause.typeNames.nonSeparatorAt(i), context); + + if (typeDeclSymbol.isValidBaseKind(parentType, true)) { + this.setSymbolForAST(extendsClause.typeNames.nonSeparatorAt(i), parentType, null); + + if (!typeDeclSymbol.hasBase(parentType) && !parentType.hasBase(typeDeclSymbol)) { + typeDeclSymbol.addExtendedType(parentType); + + var specializations = typeDeclSymbol.getKnownSpecializations(); + + for (var j = 0; j < specializations.length; j++) { + specializations[j].addExtendedType(parentType); + } + } + } else if (parentType && !this.getSymbolForAST(extendsClause.typeNames.nonSeparatorAt(i), context)) { + this.setSymbolForAST(extendsClause.typeNames.nonSeparatorAt(i), parentType, null); + } + } + } + + var implementsClause = TypeScript.ASTHelpers.getImplementsHeritageClause(heritageClauses); + if (implementsClause && typeDeclIsClass) { + var extendsCount = extendsClause ? extendsClause.typeNames.nonSeparatorCount() : 0; + for (var i = typeDeclSymbol.getKnownBaseTypeCount(); ((i - extendsCount) >= 0) && ((i - extendsCount) < implementsClause.typeNames.nonSeparatorCount()); i = typeDeclSymbol.getKnownBaseTypeCount()) { + typeDeclSymbol.incrementKnownBaseCount(); + var implementedTypeAST = implementsClause.typeNames.nonSeparatorAt(i - extendsCount); + var implementedType = this.resolveTypeReference(implementedTypeAST, context); + + if (typeDeclSymbol.isValidBaseKind(implementedType, false)) { + this.setSymbolForAST(implementsClause.typeNames.nonSeparatorAt(i - extendsCount), implementedType, null); + + if (!typeDeclSymbol.hasBase(implementedType) && !implementedType.hasBase(typeDeclSymbol)) { + typeDeclSymbol.addImplementedType(implementedType); + } + } else if (implementedType && !this.getSymbolForAST(implementsClause.typeNames.nonSeparatorAt(i - extendsCount), context)) { + this.setSymbolForAST(implementsClause.typeNames.nonSeparatorAt(i - extendsCount), implementedType, null); + } + } + } + + context.doneBaseTypeResolution(wasInBaseTypeResolution); + + if (wasInBaseTypeResolution) { + typeDeclSymbol.inResolution = false; + + this.typeCheckCallBacks.push(function (context) { + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + _this.resolveClassDeclaration(classOrInterface, context); + } else { + _this.resolveInterfaceDeclaration(classOrInterface, context); + } + }); + + return typeDeclSymbol; + } + + this.setSymbolForAST(name, typeDeclSymbol, context); + this.setSymbolForAST(classOrInterface, typeDeclSymbol, context); + + typeDeclSymbol.setResolved(); + + return typeDeclSymbol; + }; + + PullTypeResolver.prototype.resolveClassDeclaration = function (classDeclAST, context) { + var classDecl = this.semanticInfoChain.getDeclForAST(classDeclAST); + var classDeclSymbol = classDecl.getSymbol(); + + if (!classDeclSymbol.isResolved) { + this.resolveReferenceTypeDeclaration(classDeclAST, classDeclAST.identifier, classDeclAST.heritageClauses, context); + + var constructorMethod = classDeclSymbol.getConstructorMethod(); + var extendedTypes = classDeclSymbol.getExtendedTypes(); + var parentType = extendedTypes.length ? extendedTypes[0] : null; + + if (constructorMethod) { + if (parentType) { + var parentConstructorSymbol = parentType.getConstructorMethod(); + + if (parentConstructorSymbol) { + var parentConstructorTypeSymbol = parentConstructorSymbol.type; + var constructorTypeSymbol = constructorMethod.type; + if (!constructorTypeSymbol.hasBase(parentConstructorTypeSymbol)) { + constructorTypeSymbol.addExtendedType(parentConstructorTypeSymbol); + } + } + } + + if (!classDeclSymbol.isResolved) { + return classDeclSymbol; + } + } + + this.resolveOtherDeclarations(classDeclAST, context); + } + + if (this.canTypeCheckAST(classDeclAST, context)) { + this.typeCheckClassDeclaration(classDeclAST, context); + } + + return classDeclSymbol; + }; + + PullTypeResolver.prototype.typeCheckTypeParametersOfTypeDeclaration = function (classOrInterface, context) { + var _this = this; + var typeParametersList = classOrInterface.kind() == 131 /* ClassDeclaration */ ? classOrInterface.typeParameterList : classOrInterface.typeParameterList; + + if (typeParametersList) { + var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var typeDeclSymbol = typeDecl.getSymbol(); + + for (var i = 0; i < typeParametersList.typeParameters.nonSeparatorCount(); i++) { + var typeParameterAST = typeParametersList.typeParameters.nonSeparatorAt(i); + this.resolveTypeParameterDeclaration(typeParameterAST, context); + + var typeParameterDecl = this.semanticInfoChain.getDeclForAST(typeParameterAST); + var typeParameterSymbol = typeParameterDecl.getSymbol(); + + this.checkSymbolPrivacy(typeDeclSymbol, typeParameterSymbol, function (symbol) { + return _this.typeParameterOfTypeDeclarationPrivacyErrorReporter(classOrInterface, typeParameterAST, typeParameterSymbol, symbol, context); + }); + } + } + }; + + PullTypeResolver.prototype.typeCheckClassDeclaration = function (classDeclAST, context) { + this.setTypeChecked(classDeclAST, context); + + var classDecl = this.semanticInfoChain.getDeclForAST(classDeclAST); + var classDeclSymbol = classDecl.getSymbol(); + + this.checkNameForCompilerGeneratedDeclarationCollision(classDeclAST, true, classDeclAST.identifier, context); + this.resolveAST(classDeclAST.classElements, false, context); + + this.typeCheckTypeParametersOfTypeDeclaration(classDeclAST, context); + this.typeCheckBases(classDeclAST, classDeclAST.identifier, classDeclAST.heritageClauses, classDeclSymbol, this.getEnclosingDecl(classDecl), context); + + if (!classDeclSymbol.hasBaseTypeConflict()) { + this.typeCheckMembersAgainstIndexer(classDeclSymbol, classDecl, context); + } + + this.checkTypeForDuplicateIndexSignatures(classDeclSymbol); + }; + + PullTypeResolver.prototype.postTypeCheckClassDeclaration = function (classDeclAST, context) { + this.checkThisCaptureVariableCollides(classDeclAST, true, context); + }; + + PullTypeResolver.prototype.resolveTypeSymbolSignatures = function (typeSymbol, context) { + var callSignatures = typeSymbol.getCallSignatures(); + for (var i = 0; i < callSignatures.length; i++) { + this.resolveDeclaredSymbol(callSignatures[i], context); + } + + var constructSignatures = typeSymbol.getConstructSignatures(); + for (var i = 0; i < constructSignatures.length; i++) { + this.resolveDeclaredSymbol(constructSignatures[i], context); + } + + var indexSignatures = typeSymbol.getIndexSignatures(); + for (var i = 0; i < indexSignatures.length; i++) { + this.resolveDeclaredSymbol(indexSignatures[i], context); + } + }; + + PullTypeResolver.prototype.resolveInterfaceDeclaration = function (interfaceDeclAST, context) { + this.resolveReferenceTypeDeclaration(interfaceDeclAST, interfaceDeclAST.identifier, interfaceDeclAST.heritageClauses, context); + + var interfaceDecl = this.semanticInfoChain.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + this.resolveTypeSymbolSignatures(interfaceDeclSymbol, context); + + if (interfaceDeclSymbol.isResolved) { + this.resolveOtherDeclarations(interfaceDeclAST, context); + + if (this.canTypeCheckAST(interfaceDeclAST, context)) { + this.typeCheckInterfaceDeclaration(interfaceDeclAST, context); + } + } + + return interfaceDeclSymbol; + }; + + PullTypeResolver.prototype.typeCheckInterfaceDeclaration = function (interfaceDeclAST, context) { + this.setTypeChecked(interfaceDeclAST, context); + + var interfaceDecl = this.semanticInfoChain.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + this.resolveAST(interfaceDeclAST.body.typeMembers, false, context); + + this.typeCheckTypeParametersOfTypeDeclaration(interfaceDeclAST, context); + this.typeCheckBases(interfaceDeclAST, interfaceDeclAST.identifier, interfaceDeclAST.heritageClauses, interfaceDeclSymbol, this.getEnclosingDecl(interfaceDecl), context); + + if (!interfaceDeclSymbol.hasBaseTypeConflict()) { + this.typeCheckMembersAgainstIndexer(interfaceDeclSymbol, interfaceDecl, context); + } + + var allInterfaceDecls = interfaceDeclSymbol.getDeclarations(); + if (interfaceDecl === allInterfaceDecls[allInterfaceDecls.length - 1]) { + this.checkTypeForDuplicateIndexSignatures(interfaceDeclSymbol); + } + + if (!this.checkInterfaceDeclForIdenticalTypeParameters(interfaceDeclAST, context)) { + this.semanticInfoChain.addDiagnosticFromAST(interfaceDeclAST.identifier, TypeScript.DiagnosticCode.All_declarations_of_an_interface_must_have_identical_type_parameters); + } + }; + + PullTypeResolver.prototype.checkInterfaceDeclForIdenticalTypeParameters = function (interfaceDeclAST, context) { + var interfaceDecl = this.semanticInfoChain.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + if (!interfaceDeclSymbol.isGeneric()) { + return true; + } + + var firstInterfaceDecl = interfaceDeclSymbol.getDeclarations()[0]; + if (firstInterfaceDecl == interfaceDecl) { + return true; + } + + var typeParameters = interfaceDecl.getTypeParameters(); + var firstInterfaceDeclTypeParameters = firstInterfaceDecl.getTypeParameters(); + + if (typeParameters.length != firstInterfaceDeclTypeParameters.length) { + return false; + } + + for (var i = 0; i < typeParameters.length; i++) { + var typeParameter = typeParameters[i]; + var firstInterfaceDeclTypeParameter = firstInterfaceDeclTypeParameters[i]; + + if (typeParameter.name != firstInterfaceDeclTypeParameter.name) { + return false; + } + + var typeParameterSymbol = typeParameter.getSymbol(); + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter); + var firstInterfaceDeclTypeParameterAST = this.semanticInfoChain.getASTForDecl(firstInterfaceDeclTypeParameter); + + if (!!typeParameterAST.constraint != !!firstInterfaceDeclTypeParameterAST.constraint) { + return false; + } + + if (typeParameterAST.constraint) { + var typeParameterConstraint = this.resolveAST(typeParameterAST.constraint, false, context); + if (!this.typesAreIdenticalWithNewEnclosingTypes(typeParameterConstraint, typeParameterSymbol.getConstraint(), context)) { + return false; + } + } + } + + return true; + }; + + PullTypeResolver.prototype.checkTypeForDuplicateIndexSignatures = function (enclosingTypeSymbol) { + var indexSignatures = enclosingTypeSymbol.getOwnIndexSignatures(); + var firstStringIndexer = null; + var firstNumberIndexer = null; + for (var i = 0; i < indexSignatures.length; i++) { + var currentIndexer = indexSignatures[i]; + var currentParameterType = currentIndexer.parameters[0].type; + TypeScript.Debug.assert(currentParameterType); + if (currentParameterType === this.semanticInfoChain.stringTypeSymbol) { + if (firstStringIndexer) { + this.semanticInfoChain.addDiagnosticFromAST(currentIndexer.getDeclarations()[0].ast(), TypeScript.DiagnosticCode.Duplicate_string_index_signature, null, [this.semanticInfoChain.locationFromAST(firstStringIndexer.getDeclarations()[0].ast())]); + return; + } else { + firstStringIndexer = currentIndexer; + } + } else if (currentParameterType === this.semanticInfoChain.numberTypeSymbol) { + if (firstNumberIndexer) { + this.semanticInfoChain.addDiagnosticFromAST(currentIndexer.getDeclarations()[0].ast(), TypeScript.DiagnosticCode.Duplicate_number_index_signature, null, [this.semanticInfoChain.locationFromAST(firstNumberIndexer.getDeclarations()[0].ast())]); + return; + } else { + firstNumberIndexer = currentIndexer; + } + } + } + }; + + PullTypeResolver.prototype.filterSymbol = function (symbol, kind, enclosingDecl, context) { + if (symbol) { + if (symbol.kind & kind) { + return symbol; + } + + if (symbol.isAlias()) { + this.resolveDeclaredSymbol(symbol, context); + + var alias = symbol; + if (kind & 164 /* SomeContainer */) { + return alias.getExportAssignedContainerSymbol(); + } else if (kind & 58728795 /* SomeType */) { + return alias.getExportAssignedTypeSymbol(); + } else if (kind & 68147712 /* SomeValue */) { + return alias.getExportAssignedValueSymbol(); + } + } + } + return null; + }; + + PullTypeResolver.prototype.getMemberSymbolOfKind = function (symbolName, kind, pullTypeSymbol, enclosingDecl, context) { + var memberSymbol = this.getNamedPropertySymbol(symbolName, kind, pullTypeSymbol); + + return { + symbol: this.filterSymbol(memberSymbol, kind, enclosingDecl, context), + aliasSymbol: memberSymbol && memberSymbol.isAlias() ? memberSymbol : null + }; + }; + + PullTypeResolver.prototype.resolveIdentifierOfInternalModuleReference = function (importDecl, identifier, moduleSymbol, enclosingDecl, context) { + var rhsName = identifier.valueText(); + if (rhsName.length === 0) { + return null; + } + + var moduleTypeSymbol = moduleSymbol.type; + var memberSymbol = this.getMemberSymbolOfKind(rhsName, 164 /* SomeContainer */, moduleTypeSymbol, enclosingDecl, context); + var containerSymbol = memberSymbol.symbol; + var valueSymbol = null; + var typeSymbol = null; + var aliasSymbol = null; + + var acceptableAlias = true; + + if (containerSymbol) { + acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) !== 0; + aliasSymbol = memberSymbol.aliasSymbol; + } + + if (!acceptableAlias && containerSymbol && containerSymbol.kind === 128 /* TypeAlias */) { + this.resolveDeclaredSymbol(containerSymbol, context); + var aliasedAssignedValue = containerSymbol.getExportAssignedValueSymbol(); + var aliasedAssignedType = containerSymbol.getExportAssignedTypeSymbol(); + var aliasedAssignedContainer = containerSymbol.getExportAssignedContainerSymbol(); + + if (aliasedAssignedValue || aliasedAssignedType || aliasedAssignedContainer) { + aliasSymbol = containerSymbol; + valueSymbol = aliasedAssignedValue; + typeSymbol = aliasedAssignedType; + containerSymbol = aliasedAssignedContainer; + acceptableAlias = true; + } + } + + if (!acceptableAlias) { + this.semanticInfoChain.addDiagnosticFromAST(identifier, TypeScript.DiagnosticCode.Import_declaration_referencing_identifier_from_internal_module_can_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules); + return null; + } + + if (!valueSymbol) { + if (moduleTypeSymbol.getInstanceSymbol()) { + memberSymbol = this.getMemberSymbolOfKind(rhsName, 68147712 /* SomeValue */, moduleTypeSymbol.getInstanceSymbol().type, enclosingDecl, context); + valueSymbol = memberSymbol.symbol; + if (valueSymbol && memberSymbol.aliasSymbol) { + aliasSymbol = memberSymbol.aliasSymbol; + } + } + } + + if (!typeSymbol) { + memberSymbol = this.getMemberSymbolOfKind(rhsName, 58728795 /* SomeType */, moduleTypeSymbol, enclosingDecl, context); + typeSymbol = memberSymbol.symbol; + if (typeSymbol && memberSymbol.aliasSymbol) { + aliasSymbol = memberSymbol.aliasSymbol; + } + } + + if (!valueSymbol && !typeSymbol && !containerSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(identifier, TypeScript.DiagnosticCode.Could_not_find_symbol_0_in_module_1, [rhsName, moduleSymbol.toString()]); + return null; + } + + if (!typeSymbol && containerSymbol) { + typeSymbol = containerSymbol; + } + + return { + valueSymbol: valueSymbol, + typeSymbol: typeSymbol, + containerSymbol: containerSymbol, + aliasSymbol: aliasSymbol + }; + }; + + PullTypeResolver.prototype.resolveModuleReference = function (importDecl, moduleNameExpr, enclosingDecl, context, declPath) { + TypeScript.Debug.assert(moduleNameExpr.kind() === 121 /* QualifiedName */ || moduleNameExpr.kind() === 11 /* IdentifierName */ || moduleNameExpr.kind() === 14 /* StringLiteral */, "resolving module reference should always be either name or member reference"); + + var moduleSymbol = null; + var moduleName; + + if (moduleNameExpr.kind() === 121 /* QualifiedName */) { + var dottedNameAST = moduleNameExpr; + var moduleContainer = this.resolveModuleReference(importDecl, dottedNameAST.left, enclosingDecl, context, declPath); + if (moduleContainer) { + moduleName = dottedNameAST.right.valueText(); + + moduleSymbol = this.getMemberSymbolOfKind(moduleName, 4 /* Container */, moduleContainer.type, enclosingDecl, context).symbol; + if (!moduleSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(dottedNameAST.right, TypeScript.DiagnosticCode.Could_not_find_module_0_in_module_1, [moduleName, moduleContainer.toString()]); + } + } + } else { + var valueText = moduleNameExpr.kind() === 11 /* IdentifierName */ ? moduleNameExpr.valueText() : moduleNameExpr.valueText(); + var text = moduleNameExpr.kind() === 11 /* IdentifierName */ ? moduleNameExpr.text() : moduleNameExpr.text(); + + if (text.length > 0) { + var resolvedModuleNameSymbol = this.getSymbolFromDeclPath(valueText, declPath, 4 /* Container */); + moduleSymbol = this.filterSymbol(resolvedModuleNameSymbol, 4 /* Container */, enclosingDecl, context); + if (moduleSymbol) { + this.semanticInfoChain.setSymbolForAST(moduleNameExpr, moduleSymbol); + if (resolvedModuleNameSymbol.isAlias()) { + this.semanticInfoChain.setAliasSymbolForAST(moduleNameExpr, resolvedModuleNameSymbol); + var importDeclSymbol = importDecl.getSymbol(); + importDeclSymbol.addLinkedAliasSymbol(resolvedModuleNameSymbol); + } + } else { + this.semanticInfoChain.addDiagnosticFromAST(moduleNameExpr, TypeScript.DiagnosticCode.Unable_to_resolve_module_reference_0, [valueText]); + } + } + } + + return moduleSymbol; + }; + + PullTypeResolver.prototype.resolveInternalModuleReference = function (importStatementAST, context) { + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var enclosingDecl = this.getEnclosingDecl(importDecl); + + var moduleReference = importStatementAST.moduleReference; + + var aliasExpr = moduleReference.kind() === 245 /* ExternalModuleReference */ ? moduleReference.stringLiteral : moduleReference.moduleName; + + var declPath = enclosingDecl.getParentPath(); + var aliasedType = null; + var importDeclSymbol = importDecl.getSymbol(); + + if (aliasExpr.kind() === 11 /* IdentifierName */ || aliasExpr.kind() === 14 /* StringLiteral */) { + var moduleSymbol = this.resolveModuleReference(importDecl, aliasExpr, enclosingDecl, context, declPath); + if (moduleSymbol) { + aliasedType = moduleSymbol.type; + this.semanticInfoChain.setAliasSymbolForAST(moduleReference, this.semanticInfoChain.getAliasSymbolForAST(aliasExpr)); + if (aliasedType.anyDeclHasFlag(32768 /* InitializedModule */)) { + var moduleName = aliasExpr.kind() === 11 /* IdentifierName */ ? aliasExpr.valueText() : aliasExpr.valueText(); + var valueSymbol = this.getSymbolFromDeclPath(moduleName, declPath, 68147712 /* SomeValue */); + var instanceSymbol = aliasedType.getInstanceSymbol(); + + if (valueSymbol && (instanceSymbol != valueSymbol || valueSymbol.type === aliasedType)) { + var text = aliasExpr.kind() === 11 /* IdentifierName */ ? aliasExpr.text() : aliasExpr.text(); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(aliasExpr, TypeScript.DiagnosticCode.Internal_module_reference_0_in_import_declaration_does_not_reference_module_instance_for_1, [text, moduleSymbol.type.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + } else { + importDeclSymbol.setAssignedValueSymbol(valueSymbol); + } + } + } else { + aliasedType = this.getNewErrorTypeSymbol(); + } + } else if (aliasExpr.kind() === 121 /* QualifiedName */) { + var dottedNameAST = aliasExpr; + var moduleSymbol = this.resolveModuleReference(importDecl, dottedNameAST.left, enclosingDecl, context, declPath); + if (moduleSymbol) { + var identifierResolution = this.resolveIdentifierOfInternalModuleReference(importDecl, dottedNameAST.right, moduleSymbol, enclosingDecl, context); + if (identifierResolution) { + importDeclSymbol.setAssignedValueSymbol(identifierResolution.valueSymbol); + importDeclSymbol.setAssignedTypeSymbol(identifierResolution.typeSymbol); + importDeclSymbol.setAssignedContainerSymbol(identifierResolution.containerSymbol); + this.semanticInfoChain.setAliasSymbolForAST(moduleReference, identifierResolution.aliasSymbol); + return null; + } + } + } + + if (!aliasedType) { + importDeclSymbol.setAssignedTypeSymbol(this.getNewErrorTypeSymbol()); + } + + return aliasedType; + }; + + PullTypeResolver.prototype.resolveImportDeclaration = function (importStatementAST, context) { + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var enclosingDecl = this.getEnclosingDecl(importDecl); + var importDeclSymbol = importDecl.getSymbol(); + + var aliasedType = null; + + if (importDeclSymbol.isResolved) { + return importDeclSymbol; + } + + importDeclSymbol.startResolving(); + + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + var modPath = importStatementAST.moduleReference.stringLiteral.valueText(); + var declPath = enclosingDecl.getParentPath(); + + aliasedType = this.resolveExternalModuleReference(modPath, importDecl.fileName()); + + if (!aliasedType) { + var path = importStatementAST.moduleReference.stringLiteral.text(); + this.semanticInfoChain.addDiagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Unable_to_resolve_external_module_0, [path]); + aliasedType = this.getNewErrorTypeSymbol(); + } + } else { + aliasedType = this.resolveInternalModuleReference(importStatementAST, context); + } + + if (aliasedType) { + if (!aliasedType.isContainer()) { + this.semanticInfoChain.addDiagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Module_cannot_be_aliased_to_a_non_module_type); + if (!aliasedType.isError()) { + aliasedType = this.getNewErrorTypeSymbol(); + } + } + + if (aliasedType.isContainer()) { + importDeclSymbol.setAssignedContainerSymbol(aliasedType); + } + importDeclSymbol.setAssignedTypeSymbol(aliasedType); + + this.setSymbolForAST(importStatementAST.moduleReference, aliasedType, null); + } + + importDeclSymbol.setResolved(); + + this.resolveDeclaredSymbol(importDeclSymbol.assignedValue(), context); + this.resolveDeclaredSymbol(importDeclSymbol.assignedType(), context); + this.resolveDeclaredSymbol(importDeclSymbol.assignedContainer(), context); + + if (aliasedType && importDeclSymbol.anyDeclHasFlag(1 /* Exported */)) { + importDeclSymbol.setIsUsedInExportedAlias(); + + if (aliasedType.isContainer() && aliasedType.getExportAssignedValueSymbol()) { + importDeclSymbol.setIsUsedAsValue(); + } + } + + if (this.canTypeCheckAST(importStatementAST, context)) { + this.typeCheckImportDeclaration(importStatementAST, context); + } + + return importDeclSymbol; + }; + + PullTypeResolver.prototype.typeCheckImportDeclaration = function (importStatementAST, context) { + var _this = this; + this.setTypeChecked(importStatementAST, context); + + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var enclosingDecl = this.getEnclosingDecl(importDecl); + var importDeclSymbol = importDecl.getSymbol(); + + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + if (this.compilationSettings.noResolve()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Import_declaration_cannot_refer_to_external_module_reference_when_noResolve_option_is_set, null)); + } + + var modPath = importStatementAST.moduleReference.stringLiteral.valueText(); + if (enclosingDecl.kind === 32 /* DynamicModule */) { + var ast = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(this.getASTForDecl(enclosingDecl)); + if (ast && ast.kind() === 130 /* ModuleDeclaration */) { + if (TypeScript.isRelative(modPath)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name)); + } + } + } + } + + var checkPrivacy; + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + var containerSymbol = importDeclSymbol.getExportAssignedContainerSymbol(); + var container = containerSymbol ? containerSymbol.getContainer() : null; + if (container && container.kind === 32 /* DynamicModule */) { + checkPrivacy = true; + } + } else { + checkPrivacy = true; + } + + if (checkPrivacy) { + var typeSymbol = importDeclSymbol.getExportAssignedTypeSymbol(); + var containerSymbol = importDeclSymbol.getExportAssignedContainerSymbol(); + var valueSymbol = importDeclSymbol.getExportAssignedValueSymbol(); + + this.checkSymbolPrivacy(importDeclSymbol, containerSymbol, function (symbol) { + var messageCode = TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_container_that_is_or_is_using_inaccessible_module_1; + var messageArguments = [importDeclSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null), symbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null, false, false, true)]; + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(importStatementAST, messageCode, messageArguments)); + }); + + if (typeSymbol !== containerSymbol) { + this.checkSymbolPrivacy(importDeclSymbol, typeSymbol, function (symbol) { + var messageCode = symbol.isContainer() && !symbol.isEnum() ? TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_type_that_is_using_inaccessible_module_1 : TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_type_that_has_or_is_using_private_type_1; + + var messageArguments = [importDeclSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null), symbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null, false, false, true)]; + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(importStatementAST, messageCode, messageArguments)); + }); + } + + if (valueSymbol) { + this.checkSymbolPrivacy(importDeclSymbol, valueSymbol.type, function (symbol) { + var messageCode = symbol.isContainer() && !symbol.isEnum() ? TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_value_with_type_that_is_using_inaccessible_module_1 : TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_value_with_type_that_has_or_is_using_private_type_1; + var messageArguments = [importDeclSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null), symbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null, false, false, true)]; + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(importStatementAST, messageCode, messageArguments)); + }); + } + } + + this.checkNameForCompilerGeneratedDeclarationCollision(importStatementAST, true, importStatementAST.identifier, context); + }; + + PullTypeResolver.prototype.postTypeCheckImportDeclaration = function (importStatementAST, context) { + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var importSymbol = importDecl.getSymbol(); + + var isUsedAsValue = importSymbol.isUsedAsValue(); + var hasAssignedValue = importStatementAST.moduleReference.kind() !== 245 /* ExternalModuleReference */ && importSymbol.getExportAssignedValueSymbol() !== null; + + if (isUsedAsValue || hasAssignedValue) { + this.checkThisCaptureVariableCollides(importStatementAST, true, context); + } + }; + + PullTypeResolver.prototype.resolveExportAssignmentStatement = function (exportAssignmentAST, context) { + var id = exportAssignmentAST.identifier.valueText(); + if (id.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var valueSymbol = null; + var typeSymbol = null; + var containerSymbol = null; + + var enclosingDecl = this.getEnclosingDeclForAST(exportAssignmentAST); + var parentSymbol = enclosingDecl.getSymbol(); + + if (!parentSymbol.isType() && parentSymbol.isContainer()) { + this.semanticInfoChain.addDiagnosticFromAST(exportAssignmentAST, TypeScript.DiagnosticCode.Export_assignments_may_only_be_used_at_the_top_level_of_external_modules); + return this.semanticInfoChain.anyTypeSymbol; + } + + var declPath = enclosingDecl !== null ? [enclosingDecl] : []; + + containerSymbol = this.getSymbolFromDeclPath(id, declPath, 164 /* SomeContainer */); + + var acceptableAlias = true; + + if (containerSymbol) { + acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) !== 0; + } + + if (!acceptableAlias && containerSymbol && containerSymbol.kind === 128 /* TypeAlias */) { + this.resolveDeclaredSymbol(containerSymbol, context); + + var aliasSymbol = containerSymbol; + var aliasedAssignedValue = aliasSymbol.getExportAssignedValueSymbol(); + var aliasedAssignedType = aliasSymbol.getExportAssignedTypeSymbol(); + var aliasedAssignedContainer = aliasSymbol.getExportAssignedContainerSymbol(); + + if (aliasedAssignedValue || aliasedAssignedType || aliasedAssignedContainer) { + valueSymbol = aliasedAssignedValue; + typeSymbol = aliasedAssignedType; + containerSymbol = aliasedAssignedContainer; + aliasSymbol.setTypeUsedExternally(); + if (valueSymbol) { + aliasSymbol.setIsUsedAsValue(); + } + acceptableAlias = true; + } + } + + if (!acceptableAlias) { + this.semanticInfoChain.addDiagnosticFromAST(exportAssignmentAST, TypeScript.DiagnosticCode.Export_assignments_may_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules); + return this.semanticInfoChain.voidTypeSymbol; + } + + if (!valueSymbol) { + valueSymbol = this.getSymbolFromDeclPath(id, declPath, 68147712 /* SomeValue */); + } + if (!typeSymbol) { + typeSymbol = this.getSymbolFromDeclPath(id, declPath, 58728795 /* SomeType */); + } + + if (!valueSymbol && !typeSymbol && !containerSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(exportAssignmentAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [id])); + return this.semanticInfoChain.voidTypeSymbol; + } + + if (valueSymbol) { + parentSymbol.setExportAssignedValueSymbol(valueSymbol); + } + if (typeSymbol) { + parentSymbol.setExportAssignedTypeSymbol(typeSymbol); + } + if (containerSymbol) { + parentSymbol.setExportAssignedContainerSymbol(containerSymbol); + } + + this.resolveDeclaredSymbol(valueSymbol, context); + this.resolveDeclaredSymbol(typeSymbol, context); + this.resolveDeclaredSymbol(containerSymbol, context); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveAnyFunctionTypeSignature = function (funcDeclAST, typeParameters, parameterList, returnTypeAnnotation, context) { + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + TypeScript.Debug.assert(functionDecl); + + var funcDeclSymbol = functionDecl.getSymbol(); + + var signature = funcDeclSymbol.kind === 33554432 /* ConstructorType */ ? funcDeclSymbol.getConstructSignatures()[0] : funcDeclSymbol.getCallSignatures()[0]; + + if (returnTypeAnnotation) { + signature.returnType = this.resolveTypeReference(returnTypeAnnotation, context); + } + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + if (parameterList) { + for (var i = 0; i < parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveFunctionTypeSignatureParameter(parameterList.parameters.nonSeparatorAt(i), signature, functionDecl, context); + } + } + + funcDeclSymbol.setResolved(); + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.setTypeChecked(funcDeclAST, context); + this.typeCheckFunctionOverloads(funcDeclAST, context); + } + + return funcDeclSymbol; + }; + + PullTypeResolver.prototype.resolveFunctionTypeSignatureParameter = function (argDeclAST, signature, enclosingDecl, context) { + var paramDecl = this.semanticInfoChain.getDeclForAST(argDeclAST); + var paramSymbol = paramDecl.getSymbol(); + + if (argDeclAST.typeAnnotation) { + var typeRef = this.resolveTypeReference(TypeScript.ASTHelpers.getType(argDeclAST), context); + + if (paramSymbol.isVarArg && !typeRef.isArrayNamedTypeReference()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); + typeRef = this.getNewErrorTypeSymbol(); + } + + context.setTypeInContext(paramSymbol, typeRef); + } else { + if (paramSymbol.isVarArg) { + if (this.cachedArrayInterfaceType()) { + context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [this.semanticInfoChain.anyTypeSymbol])); + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_function_type_implicitly_has_an_any_type, [argDeclAST.identifier.text()])); + } + } + + if (TypeScript.hasFlag(paramDecl.flags, 128 /* Optional */) && argDeclAST.equalsValueClause && isTypesOnlyLocation(argDeclAST)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Default_arguments_are_only_allowed_in_implementation)); + } + + paramSymbol.setResolved(); + }; + + PullTypeResolver.prototype.resolveFunctionExpressionParameter = function (argDeclAST, id, typeExpr, equalsValueClause, contextParam, enclosingDecl, context) { + var paramDecl = this.semanticInfoChain.getDeclForAST(argDeclAST); + var paramSymbol = paramDecl.getSymbol(); + var contextualType = contextParam && contextParam.type; + var isImplicitAny = false; + + if (typeExpr) { + var typeRef = this.resolveTypeReference(typeExpr, context); + + if (paramSymbol.isVarArg && !typeRef.isArrayNamedTypeReference()) { + var diagnostic = context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); + typeRef = this.getNewErrorTypeSymbol(); + } + + contextualType = typeRef || contextualType; + } + if (contextualType) { + if (context.isInferentiallyTyping()) { + contextualType = context.fixAllTypeParametersReferencedByType(contextualType, this); + } + context.setTypeInContext(paramSymbol, contextualType); + } else if (paramSymbol.isVarArg) { + if (this.cachedArrayInterfaceType()) { + context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [this.semanticInfoChain.anyTypeSymbol])); + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + isImplicitAny = true; + } + + var canTypeCheckAST = this.canTypeCheckAST(argDeclAST, context); + if (equalsValueClause && (canTypeCheckAST || !contextualType)) { + if (contextualType) { + context.propagateContextualType(contextualType); + } + + var initExprSymbol = this.resolveAST(equalsValueClause, contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + } + + if (!initExprSymbol || !initExprSymbol.type) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Unable_to_resolve_type_of_0, [id.text()])); + + if (!contextualType) { + context.setTypeInContext(paramSymbol, this.getNewErrorTypeSymbol(paramSymbol.name)); + } + } else { + var initTypeSymbol = this.getInstanceTypeForAssignment(argDeclAST, initExprSymbol.type, context); + if (!contextualType) { + context.setTypeInContext(paramSymbol, initTypeSymbol.widenedType(this, equalsValueClause, context)); + isImplicitAny = initTypeSymbol !== paramSymbol.type; + } else { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(initTypeSymbol, contextualType, argDeclAST, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(argDeclAST); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [initTypeSymbol.toString(enclosingSymbol), contextualType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [initTypeSymbol.toString(enclosingSymbol), contextualType.toString(enclosingSymbol)])); + } + } + } + } + } + + if (!contextualType && !paramSymbol.isVarArg && !initTypeSymbol) { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + isImplicitAny = true; + } + + if (isImplicitAny && this.compilationSettings.noImplicitAny()) { + var functionExpressionName = paramDecl.getParentDecl().getFunctionExpressionName(); + if (functionExpressionName) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [id.text(), functionExpressionName])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_lambda_function_implicitly_has_an_any_type, [id.text()])); + } + } + + if (canTypeCheckAST) { + this.checkNameForCompilerGeneratedDeclarationCollision(argDeclAST, true, id, context); + } + + paramSymbol.setResolved(); + }; + + PullTypeResolver.prototype.checkNameForCompilerGeneratedDeclarationCollision = function (astWithName, isDeclaration, name, context) { + var compilerReservedName = getCompilerReservedName(name); + switch (compilerReservedName) { + case 1 /* _this */: + this.postTypeCheckWorkitems.push(astWithName); + return; + + case 2 /* _super */: + this.checkSuperCaptureVariableCollides(astWithName, isDeclaration, context); + return; + + case 3 /* arguments */: + this.checkArgumentsCollides(astWithName, context); + return; + + case 4 /* _i */: + this.checkIndexOfRestArgumentInitializationCollides(astWithName, isDeclaration, context); + return; + + case 5 /* require */: + case 6 /* exports */: + if (isDeclaration) { + this.checkExternalModuleRequireExportsCollides(astWithName, name, context); + } + return; + } + }; + + PullTypeResolver.prototype.hasRestParameterCodeGen = function (someFunctionDecl) { + var enclosingAST = this.getASTForDecl(someFunctionDecl); + var nodeType = enclosingAST.kind(); + + if (nodeType === 129 /* FunctionDeclaration */) { + var functionDeclaration = enclosingAST; + return !TypeScript.hasFlag(someFunctionDecl.kind === 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && functionDeclaration.block && TypeScript.lastParameterIsRest(functionDeclaration.callSignature.parameterList); + } else if (nodeType === 135 /* MemberFunctionDeclaration */) { + var memberFunction = enclosingAST; + return !TypeScript.hasFlag(someFunctionDecl.kind === 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && memberFunction.block && TypeScript.lastParameterIsRest(memberFunction.callSignature.parameterList); + } else if (nodeType === 137 /* ConstructorDeclaration */) { + var constructorDeclaration = enclosingAST; + return !TypeScript.hasFlag(someFunctionDecl.getParentDecl().flags, 8 /* Ambient */) && constructorDeclaration.block && TypeScript.lastParameterIsRest(constructorDeclaration.callSignature.parameterList); + } else if (nodeType === 218 /* ParenthesizedArrowFunctionExpression */) { + var arrowFunctionExpression = enclosingAST; + return TypeScript.lastParameterIsRest(arrowFunctionExpression.callSignature.parameterList); + } else if (nodeType === 222 /* FunctionExpression */) { + var functionExpression = enclosingAST; + return TypeScript.lastParameterIsRest(functionExpression.callSignature.parameterList); + } + + return false; + }; + + PullTypeResolver.prototype.checkArgumentsCollides = function (ast, context) { + if (ast.kind() === 242 /* Parameter */) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + if (TypeScript.hasFlag(enclosingDecl.kind, 1032192 /* SomeFunction */)) { + if (this.hasRestParameterCodeGen(enclosingDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters)); + } + } + } + }; + + PullTypeResolver.prototype.checkIndexOfRestArgumentInitializationCollides = function (ast, isDeclaration, context) { + if (!isDeclaration || ast.kind() === 242 /* Parameter */) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + var declPath = isDeclaration ? [enclosingDecl] : (enclosingDecl ? enclosingDecl.getParentPath() : []); + var resolvedSymbol = null; + var resolvedSymbolContainer; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + if (!isDeclaration) { + if (!resolvedSymbol) { + resolvedSymbol = this.resolveNameExpression(ast, context); + if (resolvedSymbol.isError()) { + return; + } + + resolvedSymbolContainer = resolvedSymbol.getContainer(); + } + + if (resolvedSymbolContainer && TypeScript.ArrayUtilities.contains(resolvedSymbolContainer.getDeclarations(), decl)) { + break; + } + } + + if (TypeScript.hasFlag(decl.kind, 1032192 /* SomeFunction */)) { + if (this.hasRestParameterCodeGen(decl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, isDeclaration ? TypeScript.DiagnosticCode.Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter : TypeScript.DiagnosticCode.Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter)); + } + } + } + } + }; + + PullTypeResolver.prototype.checkExternalModuleRequireExportsCollides = function (ast, name, context) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(name); + if (enclosingModule) { + enclosingDecl = this.getEnclosingDeclForAST(enclosingModule); + } + + if (enclosingDecl && enclosingDecl.kind === 32 /* DynamicModule */) { + var decl = this.semanticInfoChain.getDeclForAST(ast); + + if (!TypeScript.hasFlag(decl.flags, 8 /* Ambient */)) { + var nameText = name.valueText(); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module, [nameText, nameText])); + } + } + }; + + PullTypeResolver.prototype.resolveObjectTypeTypeReference = function (objectType, context) { + var interfaceDecl = this.semanticInfoChain.getDeclForAST(objectType); + TypeScript.Debug.assert(interfaceDecl); + + var interfaceSymbol = interfaceDecl.getSymbol(); + TypeScript.Debug.assert(interfaceSymbol); + + if (objectType.typeMembers) { + var memberDecl = null; + var memberSymbol = null; + var memberType = null; + var typeMembers = objectType.typeMembers; + + for (var i = 0; i < typeMembers.nonSeparatorCount(); i++) { + memberDecl = this.semanticInfoChain.getDeclForAST(typeMembers.nonSeparatorAt(i)); + memberSymbol = (memberDecl.kind & 7340032 /* SomeSignature */) ? memberDecl.getSignatureSymbol() : memberDecl.getSymbol(); + + this.resolveAST(typeMembers.nonSeparatorAt(i), false, context); + + memberType = memberSymbol.type; + + if ((memberType && memberType.isGeneric()) || (memberSymbol.isSignature() && memberSymbol.isGeneric())) { + interfaceSymbol.setHasGenericMember(); + } + } + } + + interfaceSymbol.setResolved(); + + if (this.canTypeCheckAST(objectType, context)) { + this.typeCheckObjectTypeTypeReference(objectType, context); + } + + return interfaceSymbol; + }; + + PullTypeResolver.prototype.typeCheckObjectTypeTypeReference = function (objectType, context) { + this.setTypeChecked(objectType, context); + var objectTypeDecl = this.semanticInfoChain.getDeclForAST(objectType); + var objectTypeSymbol = objectTypeDecl.getSymbol(); + + this.typeCheckMembersAgainstIndexer(objectTypeSymbol, objectTypeDecl, context); + this.checkTypeForDuplicateIndexSignatures(objectTypeSymbol); + }; + + PullTypeResolver.prototype.resolveTypeAnnotation = function (typeAnnotation, context) { + return this.resolveTypeReference(typeAnnotation.type, context); + }; + + PullTypeResolver.prototype.resolveTypeReference = function (typeRef, context) { + if (typeRef === null) { + return null; + } + + TypeScript.Debug.assert(typeRef.kind() !== 244 /* TypeAnnotation */); + + var aliasType = null; + var type = this.computeTypeReferenceSymbol(typeRef, context); + + if (type.kind === 4 /* Container */) { + var container = type; + var instanceSymbol = container.getInstanceSymbol(); + + if (instanceSymbol && (instanceSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */) || instanceSymbol.kind === 32768 /* ConstructorMethod */)) { + type = instanceSymbol.type.getAssociatedContainerType(); + } + } + + if (type && type.isAlias()) { + aliasType = type; + type = aliasType.getExportAssignedTypeSymbol(); + } + + if (type && !type.isGeneric()) { + if (aliasType) { + this.semanticInfoChain.setAliasSymbolForAST(typeRef, aliasType); + } + } + + if (type && !type.isError()) { + if ((type.kind & 58728795 /* SomeType */) === 0) { + if (type.kind & 164 /* SomeContainer */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeRef, TypeScript.DiagnosticCode.Type_reference_cannot_refer_to_container_0, [aliasType ? aliasType.toString() : type.toString()])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeRef, TypeScript.DiagnosticCode.Type_reference_must_refer_to_type)); + } + } + } + + if (this.canTypeCheckAST(typeRef, context)) { + this.setTypeChecked(typeRef, context); + } + + return type; + }; + + PullTypeResolver.prototype.getArrayType = function (elementType) { + var arraySymbol = elementType.getArrayType(); + + if (!arraySymbol) { + arraySymbol = this.createInstantiatedType(this.cachedArrayInterfaceType(), [elementType]); + + if (!arraySymbol) { + arraySymbol = this.semanticInfoChain.anyTypeSymbol; + } + + elementType.setArrayType(arraySymbol); + } + + return arraySymbol; + }; + + PullTypeResolver.prototype.computeTypeReferenceSymbol = function (term, context) { + switch (term.kind()) { + case 60 /* AnyKeyword */: + return this.semanticInfoChain.anyTypeSymbol; + case 61 /* BooleanKeyword */: + return this.semanticInfoChain.booleanTypeSymbol; + case 67 /* NumberKeyword */: + return this.semanticInfoChain.numberTypeSymbol; + case 69 /* StringKeyword */: + return this.semanticInfoChain.stringTypeSymbol; + case 41 /* VoidKeyword */: + return this.semanticInfoChain.voidTypeSymbol; + } + + var typeDeclSymbol = null; + + if (term.kind() === 11 /* IdentifierName */) { + typeDeclSymbol = this.resolveTypeNameExpression(term, context); + } else if (term.kind() === 123 /* FunctionType */) { + var functionType = term; + typeDeclSymbol = this.resolveAnyFunctionTypeSignature(functionType, functionType.typeParameterList, functionType.parameterList, functionType.type, context); + } else if (term.kind() === 125 /* ConstructorType */) { + var constructorType = term; + typeDeclSymbol = this.resolveAnyFunctionTypeSignature(constructorType, constructorType.typeParameterList, constructorType.parameterList, constructorType.type, context); + } else if (term.kind() === 122 /* ObjectType */) { + typeDeclSymbol = this.resolveObjectTypeTypeReference(term, context); + } else if (term.kind() === 126 /* GenericType */) { + typeDeclSymbol = this.resolveGenericTypeReference(term, context); + } else if (term.kind() === 121 /* QualifiedName */) { + typeDeclSymbol = this.resolveQualifiedName(term, context); + } else if (term.kind() === 14 /* StringLiteral */) { + var stringConstantAST = term; + var enclosingDecl = this.getEnclosingDeclForAST(term); + typeDeclSymbol = new TypeScript.PullStringConstantTypeSymbol(stringConstantAST.text()); + var decl = new TypeScript.PullSynthesizedDecl(stringConstantAST.text(), stringConstantAST.text(), typeDeclSymbol.kind, null, enclosingDecl, enclosingDecl.semanticInfoChain); + typeDeclSymbol.addDeclaration(decl); + } else if (term.kind() === 127 /* TypeQuery */) { + var typeQuery = term; + + var typeQueryTerm = typeQuery.name; + + var valueSymbol = this.resolveAST(typeQueryTerm, false, context); + + if (valueSymbol && valueSymbol.isAlias()) { + if (valueSymbol.assignedValue()) { + valueSymbol = valueSymbol.assignedValue(); + } else { + var containerSymbol = valueSymbol.getExportAssignedContainerSymbol(); + valueSymbol = (containerSymbol && containerSymbol.isContainer() && !containerSymbol.isEnum()) ? containerSymbol.getInstanceSymbol() : null; + } + } + + if (valueSymbol) { + typeDeclSymbol = valueSymbol.type.widenedType(this, typeQueryTerm, context); + } else { + typeDeclSymbol = this.getNewErrorTypeSymbol(); + } + } else if (term.kind() === 124 /* ArrayType */) { + var arrayType = term; + var underlying = this.resolveTypeReference(arrayType.type, context); + typeDeclSymbol = this.getArrayType(underlying); + } else { + throw TypeScript.Errors.invalidOperation("unknown type"); + } + + if (!typeDeclSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(term, TypeScript.DiagnosticCode.Unable_to_resolve_type)); + return this.getNewErrorTypeSymbol(); + } + + if (typeDeclSymbol.isError()) { + return typeDeclSymbol; + } + + if (this.genericTypeIsUsedWithoutRequiredTypeArguments(typeDeclSymbol, term, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(term, TypeScript.DiagnosticCode.Generic_type_references_must_include_all_type_arguments)); + typeDeclSymbol = this.instantiateTypeToAny(typeDeclSymbol, context); + } + + return typeDeclSymbol; + }; + + PullTypeResolver.prototype.genericTypeIsUsedWithoutRequiredTypeArguments = function (typeSymbol, term, context) { + if (!typeSymbol) { + return false; + } + + if (typeSymbol.isAlias()) { + return this.genericTypeIsUsedWithoutRequiredTypeArguments(typeSymbol.getExportAssignedTypeSymbol(), term, context); + } + + return typeSymbol.isNamedTypeSymbol() && typeSymbol.isGeneric() && !typeSymbol.isTypeParameter() && (typeSymbol.isResolved || typeSymbol.inResolution) && !typeSymbol.getIsSpecialized() && typeSymbol.getTypeParameters().length && typeSymbol.getTypeArguments() === null && this.isTypeRefWithoutTypeArgs(term); + }; + + PullTypeResolver.prototype.resolveMemberVariableDeclaration = function (varDecl, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.ASTHelpers.getType(varDecl.variableDeclarator), varDecl.variableDeclarator.equalsValueClause, context); + }; + + PullTypeResolver.prototype.resolvePropertySignature = function (varDecl, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), null, context); + }; + + PullTypeResolver.prototype.resolveVariableDeclarator = function (varDecl, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.equalsValueClause, context); + }; + + PullTypeResolver.prototype.resolveParameterList = function (list, context) { + return this.resolveSeparatedList(list.parameters, context); + }; + + PullTypeResolver.prototype.resolveParameter = function (parameter, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.ASTHelpers.getType(parameter), parameter.equalsValueClause, context); + }; + + PullTypeResolver.prototype.getEnumTypeSymbol = function (enumElement, context) { + var enumDeclaration = enumElement.parent.parent; + var decl = this.semanticInfoChain.getDeclForAST(enumDeclaration); + var symbol = decl.getSymbol(); + this.resolveDeclaredSymbol(symbol, context); + + return symbol; + }; + + PullTypeResolver.prototype.resolveEnumElement = function (enumElement, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(enumElement, TypeScript.sentinelEmptyArray, enumElement.propertyName, null, enumElement.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckEnumElement = function (enumElement, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(enumElement, TypeScript.sentinelEmptyArray, enumElement.propertyName, null, enumElement.equalsValueClause, context); + }; + + PullTypeResolver.prototype.resolveEqualsValueClause = function (clause, isContextuallyTyped, context) { + if (this.canTypeCheckAST(clause, context)) { + this.setTypeChecked(clause, context); + } + + return this.resolveAST(clause.value, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveVariableDeclaratorOrParameterOrEnumElement = function (varDeclOrParameter, modifiers, name, typeExpr, init, context) { + var hasTypeExpr = typeExpr !== null || varDeclOrParameter.kind() === 243 /* EnumElement */; + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + + if (enclosingDecl && decl.kind === 2048 /* Parameter */) { + enclosingDecl.ensureSymbolIsBound(); + } + + var declSymbol = decl.getSymbol(); + var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; + + if (declSymbol.isResolved) { + var declType = declSymbol.type; + var valDecl = decl.getValueDecl(); + + if (valDecl) { + var valSymbol = valDecl.getSymbol(); + + if (valSymbol && !valSymbol.isResolved) { + valSymbol.type = declType; + valSymbol.setResolved(); + } + } + } else { + if (declSymbol.inResolution) { + declSymbol.type = this.semanticInfoChain.anyTypeSymbol; + declSymbol.setResolved(); + return declSymbol; + } + + if (!declSymbol.type || !declSymbol.type.isError()) { + declSymbol.startResolving(); + + var typeExprSymbol = this.resolveAndTypeCheckVariableDeclarationTypeExpr(varDeclOrParameter, name, typeExpr, context); + + if (!hasTypeExpr) { + this.resolveAndTypeCheckVariableDeclaratorOrParameterInitExpr(varDeclOrParameter, name, typeExpr, init, context, typeExprSymbol); + } + + if (!(hasTypeExpr || init)) { + var defaultType = this.semanticInfoChain.anyTypeSymbol; + + if (declSymbol.isVarArg && this.cachedArrayInterfaceType()) { + defaultType = this.createInstantiatedType(this.cachedArrayInterfaceType(), [defaultType]); + } + + context.setTypeInContext(declSymbol, defaultType); + + if (declParameterSymbol) { + declParameterSymbol.type = defaultType; + } + } + declSymbol.setResolved(); + + if (declParameterSymbol) { + declParameterSymbol.setResolved(); + } + } + } + + if (this.canTypeCheckAST(varDeclOrParameter, context)) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDeclOrParameter, modifiers, name, typeExpr, init, context); + } + + return declSymbol; + }; + + PullTypeResolver.prototype.resolveAndTypeCheckVariableDeclarationTypeExpr = function (varDeclOrParameter, name, typeExpr, context) { + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + var declSymbol = decl.getSymbol(); + var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; + + if (varDeclOrParameter.kind() === 243 /* EnumElement */) { + var result = this.getEnumTypeSymbol(varDeclOrParameter, context); + declSymbol.type = result; + return result; + } + + if (!typeExpr) { + return null; + } + + var wrapperDecl = this.getEnclosingDecl(decl); + wrapperDecl = wrapperDecl || enclosingDecl; + + var typeExprSymbol = this.resolveTypeReference(typeExpr, context); + + if (!typeExprSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Unable_to_resolve_type_of_0, [name.text()])); + declSymbol.type = this.getNewErrorTypeSymbol(); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } else if (typeExprSymbol.isError()) { + context.setTypeInContext(declSymbol, typeExprSymbol); + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, typeExprSymbol); + } + } else { + if (typeExprSymbol === this.semanticInfoChain.anyTypeSymbol) { + decl.setFlag(16777216 /* IsAnnotatedWithAny */); + } + + if (typeExprSymbol.isContainer()) { + var exportedTypeSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + + if (exportedTypeSymbol) { + typeExprSymbol = exportedTypeSymbol; + } else { + typeExprSymbol = typeExprSymbol.type; + + if (typeExprSymbol.isAlias()) { + typeExprSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + } + + if (typeExprSymbol && typeExprSymbol.isContainer() && !typeExprSymbol.isEnum()) { + var instanceSymbol = typeExprSymbol.getInstanceSymbol(); + + if (!instanceSymbol || !TypeScript.PullHelpers.symbolIsEnum(instanceSymbol)) { + typeExprSymbol = this.getNewErrorTypeSymbol(); + } else { + typeExprSymbol = instanceSymbol.type; + } + } + } + } else if (declSymbol.isVarArg && !(typeExprSymbol.isArrayNamedTypeReference() || typeExprSymbol === this.cachedArrayInterfaceType())) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); + typeExprSymbol = this.getNewErrorTypeSymbol(); + } + + context.setTypeInContext(declSymbol, typeExprSymbol); + + if (declParameterSymbol) { + declParameterSymbol.type = typeExprSymbol; + } + + if (typeExprSymbol.kind === 16777216 /* FunctionType */ && !typeExprSymbol.getFunctionSymbol()) { + typeExprSymbol.setFunctionSymbol(declSymbol); + } + } + + return typeExprSymbol; + }; + + PullTypeResolver.prototype.resolveAndTypeCheckVariableDeclaratorOrParameterInitExpr = function (varDeclOrParameter, name, typeExpr, init, context, typeExprSymbol) { + if (!init) { + return null; + } + + var hasTypeExpr = typeExpr !== null || varDeclOrParameter.kind() === 243 /* EnumElement */; + if (typeExprSymbol) { + context.pushNewContextualType(typeExprSymbol); + } + + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + var declSymbol = decl.getSymbol(); + var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; + + var wrapperDecl = this.getEnclosingDecl(decl); + wrapperDecl = wrapperDecl || enclosingDecl; + + var initExprSymbol = this.resolveAST(init, typeExprSymbol !== null, context); + + if (typeExprSymbol) { + context.popAnyContextualType(); + } + + if (!initExprSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Unable_to_resolve_type_of_0, [name.text()])); + + if (!hasTypeExpr) { + context.setTypeInContext(declSymbol, this.getNewErrorTypeSymbol()); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } + } else { + var initTypeSymbol = initExprSymbol.type; + + if (!hasTypeExpr) { + var widenedInitTypeSymbol = initTypeSymbol.widenedType(this, init.value, context); + context.setTypeInContext(declSymbol, widenedInitTypeSymbol); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, widenedInitTypeSymbol); + } + + if (this.compilationSettings.noImplicitAny()) { + if ((widenedInitTypeSymbol !== initTypeSymbol) && (widenedInitTypeSymbol === this.semanticInfoChain.anyTypeSymbol)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Variable_0_implicitly_has_an_any_type, [name.text()])); + } + } + + return widenedInitTypeSymbol; + } + } + + return initTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckPropertySignature = function (varDecl, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckMemberVariableDeclaration = function (varDecl, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.variableDeclarator.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckVariableDeclarator = function (varDecl, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckParameter = function (parameter, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.ASTHelpers.getType(parameter), parameter.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckVariableDeclaratorOrParameterOrEnumElement = function (varDeclOrParameter, modifiers, name, typeExpr, init, context) { + var _this = this; + this.setTypeChecked(varDeclOrParameter, context); + + var hasTypeExpr = typeExpr !== null || varDeclOrParameter.kind() === 243 /* EnumElement */; + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + var declSymbol = decl.getSymbol(); + + var typeExprSymbol = this.resolveAndTypeCheckVariableDeclarationTypeExpr(varDeclOrParameter, name, typeExpr, context); + + var initTypeSymbol = this.resolveAndTypeCheckVariableDeclaratorOrParameterInitExpr(varDeclOrParameter, name, typeExpr, init, context, typeExprSymbol); + + if (hasTypeExpr || init) { + if (typeExprSymbol && typeExprSymbol.isAlias()) { + typeExprSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + } + + if (typeExprSymbol && typeExprSymbol.kind === 32 /* DynamicModule */) { + var exportedTypeSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + + if (exportedTypeSymbol) { + typeExprSymbol = exportedTypeSymbol; + } else { + var instanceTypeSymbol = typeExprSymbol.getInstanceType(); + + if (!instanceTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Tried_to_set_variable_type_to_uninitialized_module_type_0, [typeExprSymbol.toString()])); + typeExprSymbol = null; + } else { + typeExprSymbol = instanceTypeSymbol; + } + } + } + + initTypeSymbol = this.getInstanceTypeForAssignment(varDeclOrParameter, initTypeSymbol, context); + + if (initTypeSymbol && typeExprSymbol) { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(initTypeSymbol, typeExprSymbol, varDeclOrParameter, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(varDeclOrParameter); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [initTypeSymbol.toString(enclosingSymbol), typeExprSymbol.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [initTypeSymbol.toString(enclosingSymbol), typeExprSymbol.toString(enclosingSymbol)])); + } + } + } + } else if (varDeclOrParameter.kind() !== 243 /* EnumElement */ && this.compilationSettings.noImplicitAny() && !this.isForInVariableDeclarator(varDeclOrParameter)) { + var wrapperDecl = this.getEnclosingDecl(decl); + wrapperDecl = wrapperDecl || enclosingDecl; + + var needReportError = function (containerDecl, selfDecl) { + if (!TypeScript.hasFlag(containerDecl.flags, 8 /* Ambient */)) { + return true; + } + + return selfDecl && !TypeScript.hasFlag(selfDecl.flags, 2 /* Private */); + }; + + if ((wrapperDecl.kind === 16384 /* Function */ || wrapperDecl.kind === 32768 /* ConstructorMethod */ || wrapperDecl.kind === 2097152 /* ConstructSignature */)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [name.text(), enclosingDecl.name])); + } else if (wrapperDecl.kind === 65536 /* Method */) { + var parentDecl = wrapperDecl.getParentDecl(); + + if (needReportError(parentDecl, wrapperDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [name.text(), enclosingDecl.name])); + } + } else if (decl.kind === 4096 /* Property */ && !declSymbol.getContainer().isNamedTypeSymbol()) { + if (needReportError(wrapperDecl, decl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Member_0_of_object_type_implicitly_has_an_any_type, [name.text()])); + } + } else if (wrapperDecl.kind !== 268435456 /* CatchBlock */) { + if (needReportError(wrapperDecl) || !TypeScript.hasModifier(modifiers, 2 /* Private */)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Variable_0_implicitly_has_an_any_type, [name.text()])); + } + } + } + + if (init && varDeclOrParameter.kind() === 242 /* Parameter */) { + var containerSignature = enclosingDecl.getSignatureSymbol(); + if (containerSignature && !containerSignature.isDefinition()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Default_arguments_are_only_allowed_in_implementation)); + } + } + if (declSymbol.kind !== 2048 /* Parameter */ && (declSymbol.kind !== 4096 /* Property */ || declSymbol.getContainer().isNamedTypeSymbol())) { + this.checkSymbolPrivacy(declSymbol, declSymbol.type, function (symbol) { + return _this.variablePrivacyErrorReporter(varDeclOrParameter, declSymbol, symbol, context); + }); + } + + if ((declSymbol.kind !== 4096 /* Property */ && declSymbol.kind !== 67108864 /* EnumMember */) || declSymbol.anyDeclHasFlag(8388608 /* PropertyParameter */)) { + this.checkNameForCompilerGeneratedDeclarationCollision(varDeclOrParameter, true, name, context); + } + }; + + PullTypeResolver.prototype.isForInVariableDeclarator = function (ast) { + return ast.kind() === 225 /* VariableDeclarator */ && ast.parent && ast.parent.parent && ast.parent.parent.parent && ast.parent.kind() === 2 /* SeparatedList */ && ast.parent.parent.kind() === 224 /* VariableDeclaration */ && ast.parent.parent.parent.kind() === 155 /* ForInStatement */ && ast.parent.parent.parent.variableDeclaration === ast.parent.parent; + }; + + PullTypeResolver.prototype.checkSuperCaptureVariableCollides = function (superAST, isDeclaration, context) { + var enclosingDecl = this.getEnclosingDeclForAST(superAST); + + var classSymbol = this.getContextualClassSymbolForEnclosingDecl(superAST, enclosingDecl); + + if (classSymbol && !classSymbol.anyDeclHasFlag(8 /* Ambient */)) { + if (superAST.kind() === 242 /* Parameter */) { + var enclosingAST = this.getASTForDecl(enclosingDecl); + if (enclosingAST.kind() !== 218 /* ParenthesizedArrowFunctionExpression */ && enclosingAST.kind() !== 219 /* SimpleArrowFunctionExpression */) { + var block = enclosingDecl.kind === 65536 /* Method */ ? enclosingAST.block : enclosingAST.block; + if (!block) { + return; + } + } + } + + this.resolveDeclaredSymbol(classSymbol, context); + + var parents = classSymbol.getExtendedTypes(); + if (parents.length) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(superAST, isDeclaration ? TypeScript.DiagnosticCode.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference : TypeScript.DiagnosticCode.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference)); + } + } + }; + + PullTypeResolver.prototype.checkThisCaptureVariableCollides = function (_thisAST, isDeclaration, context) { + if (isDeclaration) { + var decl = this.semanticInfoChain.getDeclForAST(_thisAST); + if (TypeScript.hasFlag(decl.flags, 8 /* Ambient */)) { + return; + } + } + + var enclosingDecl = this.getEnclosingDeclForAST(_thisAST); + + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(_thisAST); + if (enclosingModule) { + enclosingDecl = this.getEnclosingDeclForAST(enclosingModule); + } + + var declPath = enclosingDecl.getParentPath(); + + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.kind; + if (declKind === 131072 /* FunctionExpression */ && TypeScript.hasFlag(decl.flags, 8192 /* ArrowFunction */)) { + continue; + } + + if (declKind === 16384 /* Function */ || declKind === 65536 /* Method */ || declKind === 32768 /* ConstructorMethod */ || declKind === 262144 /* GetAccessor */ || declKind === 524288 /* SetAccessor */ || declKind === 131072 /* FunctionExpression */ || declKind === 8 /* Class */ || declKind === 4 /* Container */ || declKind === 32 /* DynamicModule */ || declKind === 1 /* Script */) { + if (TypeScript.hasFlag(decl.flags, 262144 /* MustCaptureThis */)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(_thisAST, isDeclaration ? TypeScript.DiagnosticCode.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference : TypeScript.DiagnosticCode.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference)); + } + break; + } + } + }; + + PullTypeResolver.prototype.postTypeCheckVariableDeclaratorOrParameter = function (varDeclOrParameter, context) { + this.checkThisCaptureVariableCollides(varDeclOrParameter, true, context); + }; + + PullTypeResolver.prototype.resolveTypeParameterDeclaration = function (typeParameterAST, context) { + var typeParameterDecl = this.semanticInfoChain.getDeclForAST(typeParameterAST); + var typeParameterSymbol = typeParameterDecl.getSymbol(); + + this.resolveFirstTypeParameterDeclaration(typeParameterSymbol, context); + + if (typeParameterSymbol.isResolved && this.canTypeCheckAST(typeParameterAST, context)) { + this.typeCheckTypeParameterDeclaration(typeParameterAST, context); + } + + return typeParameterSymbol; + }; + + PullTypeResolver.prototype.resolveFirstTypeParameterDeclaration = function (typeParameterSymbol, context) { + var typeParameterDecl = typeParameterSymbol.getDeclarations()[0]; + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecl); + + if (typeParameterSymbol.isResolved || typeParameterSymbol.inResolution) { + return; + } + + typeParameterSymbol.startResolving(); + + if (typeParameterAST.constraint) { + var constraintTypeSymbol = this.resolveTypeReference(typeParameterAST.constraint.type, context); + + if (constraintTypeSymbol) { + typeParameterSymbol.setConstraint(constraintTypeSymbol); + } + } + + typeParameterSymbol.setResolved(); + }; + + PullTypeResolver.prototype.typeCheckTypeParameterDeclaration = function (typeParameterAST, context) { + this.setTypeChecked(typeParameterAST, context); + + var constraint = this.resolveAST(typeParameterAST.constraint, false, context); + + if (constraint) { + var typeParametersAST = typeParameterAST.parent; + var typeParameters = []; + for (var i = 0; i < typeParametersAST.nonSeparatorCount(); i++) { + var currentTypeParameterAST = typeParametersAST.nonSeparatorAt(i); + var currentTypeParameterDecl = this.semanticInfoChain.getDeclForAST(currentTypeParameterAST); + var currentTypeParameter = this.semanticInfoChain.getSymbolForDecl(currentTypeParameterDecl); + typeParameters[currentTypeParameter.pullSymbolID] = currentTypeParameter; + } + + if (constraint.wrapsSomeTypeParameter(typeParameters)) { + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); + } + } + }; + + PullTypeResolver.prototype.resolveConstraint = function (constraint, context) { + if (this.canTypeCheckAST(constraint, context)) { + this.setTypeChecked(constraint, context); + } + + return this.resolveTypeReference(constraint.type, context); + }; + + PullTypeResolver.prototype.resolveFunctionBodyReturnTypes = function (funcDeclAST, block, bodyExpression, signature, useContextualType, enclosingDecl, context) { + var _this = this; + var returnStatementsExpressions = []; + + var enclosingDeclStack = [enclosingDecl]; + + var preFindReturnExpressionTypes = function (ast, walker) { + var go = true; + + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 215 /* ObjectLiteralExpression */: + go = false; + break; + + case 150 /* ReturnStatement */: + var returnStatement = ast; + enclosingDecl.setFlag(4194304 /* HasReturnStatement */); + returnStatementsExpressions.push({ expression: returnStatement.expression, enclosingDecl: enclosingDeclStack[enclosingDeclStack.length - 1] }); + go = false; + break; + + case 236 /* CatchClause */: + case 163 /* WithStatement */: + enclosingDeclStack[enclosingDeclStack.length] = _this.semanticInfoChain.getDeclForAST(ast); + break; + + default: + break; + } + + walker.options.goChildren = go; + + return ast; + }; + + var postFindReturnExpressionEnclosingDecls = function (ast, walker) { + switch (ast.kind()) { + case 236 /* CatchClause */: + case 163 /* WithStatement */: + enclosingDeclStack.length--; + break; + default: + break; + } + + walker.options.goChildren = true; + + return ast; + }; + + if (block) { + TypeScript.getAstWalkerFactory().walk(block, preFindReturnExpressionTypes, postFindReturnExpressionEnclosingDecls); + } else { + returnStatementsExpressions.push({ expression: bodyExpression, enclosingDecl: enclosingDecl }); + enclosingDecl.setFlag(4194304 /* HasReturnStatement */); + } + + if (!returnStatementsExpressions.length) { + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + } else { + var returnExpressionSymbols = []; + var returnExpressions = []; + + for (var i = 0; i < returnStatementsExpressions.length; i++) { + var returnExpression = returnStatementsExpressions[i].expression; + if (returnExpression) { + var returnType = this.resolveAST(returnExpression, useContextualType, context).type; + + if (returnType.isError()) { + signature.returnType = returnType; + return; + } else { + if (returnExpression.parent.kind() === 150 /* ReturnStatement */) { + this.setSymbolForAST(returnExpression.parent, returnType, context); + } + } + + returnExpressionSymbols.push(returnType); + returnExpressions.push(returnExpression); + } + } + + if (!returnExpressionSymbols.length) { + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + } else { + var collection = { + getLength: function () { + return returnExpressionSymbols.length; + }, + getTypeAtIndex: function (index) { + return returnExpressionSymbols[index].type; + } + }; + + var bestCommonReturnType = this.findBestCommonType(collection, context, new TypeComparisonInfo()); + var returnType = bestCommonReturnType; + var returnExpression = returnExpressions[returnExpressionSymbols.indexOf(returnType)]; + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var functionSymbol = functionDecl.getSymbol(); + + if (returnType) { + var previousReturnType = returnType; + var newReturnType = returnType.widenedType(this, returnExpression, context); + signature.returnType = newReturnType; + + if (!TypeScript.ArrayUtilities.contains(returnExpressionSymbols, bestCommonReturnType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Could_not_find_the_best_common_type_of_types_of_all_return_statement_expressions)); + } + + if (this.compilationSettings.noImplicitAny()) { + if (previousReturnType !== newReturnType && newReturnType === this.semanticInfoChain.anyTypeSymbol) { + var functionName = enclosingDecl.name; + if (functionName === "") { + functionName = enclosingDecl.getFunctionExpressionName(); + } + + if (functionName != "") { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type, [functionName])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + } + } + + if (!functionSymbol.type && functionSymbol.isAccessor()) { + functionSymbol.type = signature.returnType; + } + } + } + }; + + PullTypeResolver.prototype.typeCheckConstructorDeclaration = function (funcDeclAST, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + for (var i = 0; i < funcDeclAST.callSignature.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveAST(funcDeclAST.callSignature.parameterList.parameters.nonSeparatorAt(i), false, context); + } + + this.resolveAST(funcDeclAST.block, false, context); + + if (funcDecl.getSignatureSymbol() && funcDecl.getSignatureSymbol().isDefinition() && this.enclosingClassIsDerived(funcDecl.getParentDecl())) { + if (!this.constructorHasSuperCall(funcDeclAST)) { + context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), "constructor".length, TypeScript.DiagnosticCode.Constructors_for_derived_classes_must_contain_a_super_call)); + } else if (this.superCallMustBeFirstStatementInConstructor(funcDecl)) { + var firstStatement = this.getFirstStatementOfBlockOrNull(funcDeclAST.block); + if (!firstStatement || !this.isSuperInvocationExpressionStatement(firstStatement)) { + context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), "constructor".length, TypeScript.DiagnosticCode.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties)); + } + } + } + + this.validateVariableDeclarationGroups(funcDecl, context); + + this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.callSignature.parameterList), null, funcDeclAST.block, context); + + this.typeCheckCallBacks.push(function (context) { + _this.typeCheckFunctionOverloads(funcDeclAST, context); + }); + }; + + PullTypeResolver.prototype.constructorHasSuperCall = function (constructorDecl) { + var _this = this; + if (constructorDecl.block) { + var foundSuperCall = false; + var pre = function (ast, walker) { + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 215 /* ObjectLiteralExpression */: + walker.options.goChildren = false; + default: + if (_this.isSuperInvocationExpression(ast)) { + foundSuperCall = true; + walker.options.stopWalking = true; + } + } + }; + + TypeScript.getAstWalkerFactory().walk(constructorDecl.block, pre); + return foundSuperCall; + } + + return false; + }; + + PullTypeResolver.prototype.typeCheckFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + this.typeCheckAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), funcDecl.callSignature.typeAnnotation, funcDecl.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckCallSignature = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckConstructSignature = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckMethodSignature = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, false, funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckMemberFunctionDeclaration = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + }; + + PullTypeResolver.prototype.containsSingleThrowStatement = function (block) { + return block !== null && block.statements.childCount() === 1 && block.statements.childAt(0).kind() === 157 /* ThrowStatement */; + }; + + PullTypeResolver.prototype.typeCheckAnyFunctionDeclaration = function (funcDeclAST, isStatic, name, typeParameters, parameters, returnTypeAnnotation, block, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + this.resolveAST(parameters, false, context); + + this.resolveAST(block, false, context); + var enclosingDecl = this.getEnclosingDecl(funcDecl); + + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); + this.validateVariableDeclarationGroups(funcDecl, context); + + this.checkFunctionTypePrivacy(funcDeclAST, isStatic, typeParameters, TypeScript.ASTHelpers.parametersFromParameterList(parameters), returnTypeAnnotation, block, context); + + this.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement(funcDecl, returnTypeAnnotation, funcDecl.getSignatureSymbol().returnType, block, context); + + if (funcDecl.kind === 16384 /* Function */) { + this.checkNameForCompilerGeneratedDeclarationCollision(funcDeclAST, true, name, context); + } + + this.typeCheckCallBacks.push(function (context) { + _this.typeCheckFunctionOverloads(funcDeclAST, context); + }); + }; + + PullTypeResolver.prototype.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement = function (functionDecl, returnTypeAnnotation, returnTypeSymbol, block, context) { + var hasReturn = TypeScript.hasFlag(functionDecl.flags, 4194304 /* HasReturnStatement */); + + if (block !== null && returnTypeAnnotation !== null && !hasReturn) { + var isVoidOrAny = this.isAnyOrEquivalent(returnTypeSymbol) || returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol; + + if (!isVoidOrAny && !this.containsSingleThrowStatement(block)) { + var funcName = functionDecl.getDisplayName() || TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Function_declared_a_non_void_return_type_but_has_no_return_expression)); + } + } + }; + + PullTypeResolver.prototype.typeCheckIndexSignature = function (funcDeclAST, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + this.resolveAST(funcDeclAST.parameter, false, context); + + var enclosingDecl = this.getEnclosingDecl(funcDecl); + + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); + this.validateVariableDeclarationGroups(funcDecl, context); + + this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.ASTHelpers.parametersFromParameter(funcDeclAST.parameter), TypeScript.ASTHelpers.getType(funcDeclAST), null, context); + + var signature = funcDecl.getSignatureSymbol(); + + this.typeCheckCallBacks.push(function (context) { + var parentSymbol = funcDecl.getSignatureSymbol().getContainer(); + var allIndexSignatures = _this.getBothKindsOfIndexSignaturesExcludingAugmentedType(parentSymbol, context); + var stringIndexSignature = allIndexSignatures.stringSignature; + var numberIndexSignature = allIndexSignatures.numericSignature; + var isNumericIndexer = numberIndexSignature === signature; + + if (numberIndexSignature && stringIndexSignature && (isNumericIndexer || stringIndexSignature.getDeclarations()[0].getParentDecl() !== numberIndexSignature.getDeclarations()[0].getParentDecl())) { + var comparisonInfo = new TypeComparisonInfo(); + + if (!_this.sourceIsAssignableToTarget(numberIndexSignature.returnType, stringIndexSignature.returnType, funcDeclAST, context, comparisonInfo)) { + var enclosingSymbol = _this.getEnclosingSymbolForAST(funcDeclAST); + if (comparisonInfo.message) { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1_NL_2, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol)])); + } + } + } + + var allMembers = parentSymbol.type.getAllMembers(536869887 /* All */, 0 /* all */); + for (var i = 0; i < allMembers.length; i++) { + var member = allMembers[i]; + var name = member.name; + if (name || (member.kind === 4096 /* Property */ && name === "")) { + if (!allMembers[i].isResolved) { + _this.resolveDeclaredSymbol(allMembers[i], context); + } + + if (parentSymbol !== allMembers[i].getContainer()) { + var isMemberNumeric = TypeScript.PullHelpers.isNameNumeric(name); + var indexerKindMatchesMemberNameKind = isNumericIndexer === isMemberNumeric; + var onlyStringIndexerIsPresent = !numberIndexSignature; + + if (indexerKindMatchesMemberNameKind || onlyStringIndexerIsPresent) { + var comparisonInfo = new TypeComparisonInfo(); + if (!_this.sourceIsAssignableToTarget(allMembers[i].type, signature.returnType, funcDeclAST, context, comparisonInfo, false)) { + _this.reportErrorThatMemberIsNotSubtypeOfIndexer(allMembers[i], signature, funcDeclAST, context, comparisonInfo); + } + } + } + } + } + }); + }; + + PullTypeResolver.prototype.postTypeCheckFunctionDeclaration = function (funcDeclAST, context) { + this.checkThisCaptureVariableCollides(funcDeclAST, true, context); + }; + + PullTypeResolver.prototype.resolveReturnTypeAnnotationOfFunctionDeclaration = function (funcDeclAST, returnTypeAnnotation, context) { + var returnTypeSymbol = null; + + if (returnTypeAnnotation) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + returnTypeSymbol = this.resolveTypeReference(returnTypeAnnotation, context); + + if (!returnTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); + } else { + var isConstructor = funcDeclAST.kind() === 137 /* ConstructorDeclaration */ || funcDeclAST.kind() === 143 /* ConstructSignature */; + if (isConstructor && returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Constructors_cannot_have_a_return_type_of_void)); + } + } + } + + return returnTypeSymbol; + }; + + PullTypeResolver.prototype.resolveMemberFunctionDeclaration = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + }; + + PullTypeResolver.prototype.resolveCallSignature = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.resolveConstructSignature = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.resolveMethodSignature = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, false, funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.resolveAnyFunctionDeclaration = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + }; + + PullTypeResolver.prototype.resolveFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveSimpleArrowFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcDecl, null, TypeScript.ASTHelpers.parametersFromIdentifier(funcDecl.identifier), null, funcDecl.block, funcDecl.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveParenthesizedArrowFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, funcDecl.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.getEnclosingClassDeclaration = function (ast) { + while (ast) { + if (ast.kind() === 131 /* ClassDeclaration */) { + return ast; + } + + ast = ast.parent; + } + + return null; + }; + + PullTypeResolver.prototype.resolveConstructorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcSymbol = funcDecl.getSymbol(); + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckConstructorDeclaration(funcDeclAST, context); + } + return funcSymbol; + } + + if (!signature.inResolution) { + var classAST = this.getEnclosingClassDeclaration(funcDeclAST); + + if (classAST) { + var classDecl = this.semanticInfoChain.getDeclForAST(classAST); + var classSymbol = classDecl.getSymbol(); + + if (!classSymbol.isResolved && !classSymbol.inResolution) { + this.resolveDeclaredSymbol(classSymbol, context); + } + } + } + + var functionTypeSymbol = funcSymbol && funcSymbol.type; + + if (signature.inResolution) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + return funcSymbol; + } + + if (funcSymbol) { + funcSymbol.startResolving(); + } + signature.startResolving(); + + var prevInTypeCheck = context.inTypeCheck; + + context.inTypeCheck = false; + + for (var i = 0; i < funcDeclAST.callSignature.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(funcDeclAST.callSignature.parameterList.parameters.nonSeparatorAt(i), context); + } + + context.inTypeCheck = prevInTypeCheck; + + if (signature.isGeneric()) { + if (funcSymbol) { + funcSymbol.type.setHasGenericSignature(); + } + } + + if (!hadError) { + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + } + } + + if (funcSymbol) { + this.resolveOtherDeclarations(funcDeclAST, context); + } + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckConstructorDeclaration(funcDeclAST, context); + } + + return funcSymbol; + }; + + PullTypeResolver.prototype.resolveIndexMemberDeclaration = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + } + + return this.resolveIndexSignature(ast.indexSignature, context); + }; + + PullTypeResolver.prototype.resolveIndexSignature = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcSymbol = funcDecl.getSymbol(); + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckIndexSignature(funcDeclAST, context); + } + return funcSymbol; + } + + var functionTypeSymbol = funcSymbol && funcSymbol.type; + + if (signature.inResolution) { + if (funcDeclAST.typeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(TypeScript.ASTHelpers.getType(funcDeclAST), context); + if (!returnTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(TypeScript.ASTHelpers.getType(funcDeclAST), TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + } + + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + return funcSymbol; + } + + if (funcSymbol) { + funcSymbol.startResolving(); + } + signature.startResolving(); + + if (funcDeclAST.parameter) { + var prevInTypeCheck = context.inTypeCheck; + + context.inTypeCheck = false; + this.resolveParameter(funcDeclAST.parameter, context); + context.inTypeCheck = prevInTypeCheck; + } + + if (funcDeclAST.typeAnnotation) { + returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); + + if (!returnTypeSymbol) { + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + } + + if (!hadError) { + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + } + } + + if (funcSymbol) { + this.resolveOtherDeclarations(funcDeclAST, context); + } + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckIndexSignature(funcDeclAST, context); + } + + return funcSymbol; + }; + + PullTypeResolver.prototype.resolveFunctionDeclaration = function (funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcSymbol = funcDecl.getSymbol(); + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + var isConstructor = funcDeclAST.kind() === 143 /* ConstructSignature */; + + if (signature) { + if (signature.isResolved) { + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckAnyFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); + } + return funcSymbol; + } + + if (isConstructor && !signature.inResolution) { + var classAST = this.getEnclosingClassDeclaration(funcDeclAST); + + if (classAST) { + var classDecl = this.semanticInfoChain.getDeclForAST(classAST); + var classSymbol = classDecl.getSymbol(); + + if (!classSymbol.isResolved && !classSymbol.inResolution) { + this.resolveDeclaredSymbol(classSymbol, context); + } + } + } + + var functionTypeSymbol = funcSymbol && funcSymbol.type; + + if (signature.inResolution) { + if (returnTypeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(returnTypeAnnotation, context); + if (!returnTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + + if (isConstructor && returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Constructors_cannot_have_a_return_type_of_void)); + } + } + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + } + + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + return funcSymbol; + } + + if (funcSymbol) { + funcSymbol.startResolving(); + } + signature.startResolving(); + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + if (parameterList) { + var prevInTypeCheck = context.inTypeCheck; + + context.inTypeCheck = false; + + for (var i = 0; i < parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(parameterList.parameters.nonSeparatorAt(i), context); + } + + context.inTypeCheck = prevInTypeCheck; + } + + if (returnTypeAnnotation) { + returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); + + if (!returnTypeSymbol) { + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else if (funcDecl.kind !== 2097152 /* ConstructSignature */) { + if (TypeScript.hasFlag(funcDecl.flags, 2048 /* Signature */)) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + var parentDeclFlags = 0 /* None */; + if (TypeScript.hasFlag(funcDecl.kind, 65536 /* Method */) || TypeScript.hasFlag(funcDecl.kind, 32768 /* ConstructorMethod */)) { + var parentDecl = funcDecl.getParentDecl(); + parentDeclFlags = parentDecl.flags; + } + + if (this.compilationSettings.noImplicitAny() && (!TypeScript.hasFlag(parentDeclFlags, 8 /* Ambient */) || (TypeScript.hasFlag(parentDeclFlags, 8 /* Ambient */) && !TypeScript.hasFlag(funcDecl.flags, 2 /* Private */)))) { + var funcDeclASTName = name; + if (funcDeclASTName) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type, [funcDeclASTName.text()])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Lambda_Function_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + } else { + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, null, signature, false, funcDecl, context); + } + } else if (funcDecl.kind === 2097152 /* ConstructSignature */) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Constructor_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + + if (!hadError) { + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + } + } + + if (funcSymbol) { + this.resolveOtherDeclarations(funcDeclAST, context); + } + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckAnyFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); + } + + return funcSymbol; + }; + + PullTypeResolver.prototype.resolveGetterReturnTypeAnnotation = function (getterFunctionDeclarationAst, enclosingDecl, context) { + if (getterFunctionDeclarationAst && getterFunctionDeclarationAst.typeAnnotation) { + return this.resolveTypeReference(TypeScript.ASTHelpers.getType(getterFunctionDeclarationAst), context); + } + + return null; + }; + + PullTypeResolver.prototype.resolveSetterArgumentTypeAnnotation = function (setterFunctionDeclarationAst, enclosingDecl, context) { + if (setterFunctionDeclarationAst && setterFunctionDeclarationAst.parameterList && setterFunctionDeclarationAst.parameterList.parameters.nonSeparatorCount() > 0) { + var parameter = setterFunctionDeclarationAst.parameterList.parameters.nonSeparatorAt(0); + return this.resolveTypeReference(TypeScript.ASTHelpers.getType(parameter), context); + } + + return null; + }; + + PullTypeResolver.prototype.resolveAccessorDeclaration = function (funcDeclAst, context) { + var functionDeclaration = this.semanticInfoChain.getDeclForAST(funcDeclAst); + var accessorSymbol = functionDeclaration.getSymbol(); + + if (accessorSymbol.inResolution) { + accessorSymbol.type = this.semanticInfoChain.anyTypeSymbol; + accessorSymbol.setResolved(); + + return accessorSymbol; + } + + if (accessorSymbol.isResolved) { + if (!accessorSymbol.type) { + accessorSymbol.type = this.semanticInfoChain.anyTypeSymbol; + } + } else { + var getterSymbol = accessorSymbol.getGetter(); + var getterFunctionDeclarationAst = getterSymbol ? getterSymbol.getDeclarations()[0].ast() : null; + var hasGetter = getterSymbol !== null; + + var setterSymbol = accessorSymbol.getSetter(); + var setterFunctionDeclarationAst = setterSymbol ? setterSymbol.getDeclarations()[0].ast() : null; + var hasSetter = setterSymbol !== null; + + var getterAnnotatedType = this.resolveGetterReturnTypeAnnotation(getterFunctionDeclarationAst, functionDeclaration, context); + var getterHasTypeAnnotation = getterAnnotatedType !== null; + + var setterAnnotatedType = this.resolveSetterArgumentTypeAnnotation(setterFunctionDeclarationAst, functionDeclaration, context); + var setterHasTypeAnnotation = setterAnnotatedType !== null; + + accessorSymbol.startResolving(); + + if (hasGetter) { + getterSymbol = this.resolveGetAccessorDeclaration(getterFunctionDeclarationAst, getterFunctionDeclarationAst.parameterList, TypeScript.ASTHelpers.getType(getterFunctionDeclarationAst), getterFunctionDeclarationAst.block, setterAnnotatedType, context); + } + + if (hasSetter) { + setterSymbol = this.resolveSetAccessorDeclaration(setterFunctionDeclarationAst, setterFunctionDeclarationAst.parameterList, context); + } + + if (hasGetter && hasSetter) { + var setterSig = setterSymbol.type.getCallSignatures()[0]; + var setterParameters = setterSig.parameters; + var setterHasParameters = setterParameters.length > 0; + var getterSig = getterSymbol.type.getCallSignatures()[0]; + + var setterSuppliedTypeSymbol = setterHasParameters ? setterParameters[0].type : null; + var getterSuppliedTypeSymbol = getterSig.returnType; + + if (setterHasTypeAnnotation && !getterHasTypeAnnotation) { + getterSuppliedTypeSymbol = setterSuppliedTypeSymbol; + getterSig.returnType = setterSuppliedTypeSymbol; + } else if ((getterHasTypeAnnotation && !setterHasTypeAnnotation) || (!getterHasTypeAnnotation && !setterHasTypeAnnotation)) { + setterSuppliedTypeSymbol = getterSuppliedTypeSymbol; + + if (setterHasParameters) { + setterParameters[0].type = getterSuppliedTypeSymbol; + } + } + + if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol, context)) { + accessorSymbol.type = this.getNewErrorTypeSymbol(); + } else { + accessorSymbol.type = getterSuppliedTypeSymbol; + } + } else if (hasSetter) { + var setterSig = setterSymbol.type.getCallSignatures()[0]; + var setterParameters = setterSig.parameters; + var setterHasParameters = setterParameters.length > 0; + + accessorSymbol.type = setterHasParameters ? setterParameters[0].type : this.semanticInfoChain.anyTypeSymbol; + } else { + var getterSig = getterSymbol.type.getCallSignatures()[0]; + accessorSymbol.type = getterSig.returnType; + } + + accessorSymbol.setResolved(); + } + + if (this.canTypeCheckAST(funcDeclAst, context)) { + this.typeCheckAccessorDeclaration(funcDeclAst, context); + } + + return accessorSymbol; + }; + + PullTypeResolver.prototype.typeCheckAccessorDeclaration = function (funcDeclAst, context) { + this.setTypeChecked(funcDeclAst, context); + var functionDeclaration = this.semanticInfoChain.getDeclForAST(funcDeclAst); + var accessorSymbol = functionDeclaration.getSymbol(); + var getterSymbol = accessorSymbol.getGetter(); + var setterSymbol = accessorSymbol.getSetter(); + + var isGetter = funcDeclAst.kind() === 139 /* GetAccessor */; + if (isGetter) { + var getterFunctionDeclarationAst = funcDeclAst; + context.pushNewContextualType(getterSymbol.type); + this.typeCheckGetAccessorDeclaration(getterFunctionDeclarationAst, context); + context.popAnyContextualType(); + } else { + var setterFunctionDeclarationAst = funcDeclAst; + this.typeCheckSetAccessorDeclaration(setterFunctionDeclarationAst, context); + } + }; + + PullTypeResolver.prototype.resolveGetAccessorDeclaration = function (funcDeclAST, parameters, returnTypeAnnotation, block, setterAnnotatedType, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + var getterSymbol = accessorSymbol.getGetter(); + var getterTypeSymbol = getterSymbol.type; + + var signature = getterTypeSymbol.getCallSignatures()[0]; + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + return getterSymbol; + } + + if (signature.inResolution) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + signature.setResolved(); + + return getterSymbol; + } + + signature.startResolving(); + + if (returnTypeAnnotation) { + var returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); + + if (!returnTypeSymbol) { + signature.returnType = this.getNewErrorTypeSymbol(); + + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else { + if (!setterAnnotatedType) { + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, null, signature, false, funcDecl, context); + } else { + signature.returnType = setterAnnotatedType; + } + } + + if (!hadError) { + signature.setResolved(); + } + } + + return getterSymbol; + }; + + PullTypeResolver.prototype.checkIfGetterAndSetterTypeMatch = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + var getter = accessorSymbol.getGetter(); + var setter = accessorSymbol.getSetter(); + + if (getter && setter) { + var getterAST = getter.getDeclarations()[0].ast(); + var setterAST = setter.getDeclarations()[0].ast(); + + if (getterAST.typeAnnotation && PullTypeResolver.hasSetAccessorParameterTypeAnnotation(setterAST)) { + var setterSig = setter.type.getCallSignatures()[0]; + var setterParameters = setterSig.parameters; + + var getter = accessorSymbol.getGetter(); + var getterSig = getter.type.getCallSignatures()[0]; + + var setterSuppliedTypeSymbol = setterParameters[0].type; + var getterSuppliedTypeSymbol = getterSig.returnType; + + if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.get_and_set_accessor_must_have_the_same_type)); + } + } + } + }; + + PullTypeResolver.prototype.typeCheckGetAccessorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); + + this.resolveAST(funcDeclAST.block, false, context); + + this.validateVariableDeclarationGroups(funcDecl, context); + + var enclosingDecl = this.getEnclosingDecl(funcDecl); + + var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) !== 0; + var funcNameAST = funcDeclAST.propertyName; + + if (!hasReturn && !this.containsSingleThrowStatement(funcDeclAST.block)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getters_must_return_a_value)); + } + + var setter = accessorSymbol.getSetter(); + if (setter) { + var setterDecl = setter.getDeclarations()[0]; + var setterIsPrivate = TypeScript.hasFlag(setterDecl.flags, 2 /* Private */); + var getterIsPrivate = TypeScript.hasModifier(funcDeclAST.modifiers, 2 /* Private */); + + if (getterIsPrivate !== setterIsPrivate) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getter_and_setter_accessors_do_not_agree_in_visibility)); + } + + this.checkIfGetterAndSetterTypeMatch(funcDeclAST, context); + } + + this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), TypeScript.ASTHelpers.getType(funcDeclAST), funcDeclAST.block, context); + }; + + PullTypeResolver.hasSetAccessorParameterTypeAnnotation = function (setAccessor) { + return setAccessor.parameterList && setAccessor.parameterList.parameters.nonSeparatorCount() > 0 && setAccessor.parameterList.parameters.nonSeparatorAt(0).typeAnnotation !== null; + }; + + PullTypeResolver.prototype.resolveSetAccessorDeclaration = function (funcDeclAST, parameterList, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + var setterSymbol = accessorSymbol.getSetter(); + var setterTypeSymbol = setterSymbol.type; + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + return setterSymbol; + } + + if (signature.inResolution) { + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + signature.setResolved(); + return setterSymbol; + } + + signature.startResolving(); + + if (parameterList) { + for (var i = 0; i < parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(parameterList.parameters.nonSeparatorAt(i), context); + } + } + + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + + if (!hadError) { + signature.setResolved(); + } + } + + return setterSymbol; + }; + + PullTypeResolver.prototype.typeCheckSetAccessorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + if (funcDeclAST.parameterList) { + for (var i = 0; i < funcDeclAST.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(funcDeclAST.parameterList.parameters.nonSeparatorAt(i), context); + } + } + + this.resolveAST(funcDeclAST.block, false, context); + + this.validateVariableDeclarationGroups(funcDecl, context); + + var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) !== 0; + + var getter = accessorSymbol.getGetter(); + + var funcNameAST = funcDeclAST.propertyName; + + if (getter) { + var getterDecl = getter.getDeclarations()[0]; + var getterIsPrivate = TypeScript.hasFlag(getterDecl.flags, 2 /* Private */); + var setterIsPrivate = TypeScript.hasModifier(funcDeclAST.modifiers, 2 /* Private */); + + if (getterIsPrivate !== setterIsPrivate) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getter_and_setter_accessors_do_not_agree_in_visibility)); + } + + this.checkIfGetterAndSetterTypeMatch(funcDeclAST, context); + } else { + if (this.compilationSettings.noImplicitAny()) { + var setterFunctionDeclarationAst = funcDeclAST; + if (!PullTypeResolver.hasSetAccessorParameterTypeAnnotation(setterFunctionDeclarationAst) && accessorSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type, [setterFunctionDeclarationAst.propertyName.text()])); + } + } + } + + this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), null, funcDeclAST.block, context); + }; + + PullTypeResolver.prototype.resolveList = function (list, context) { + if (this.canTypeCheckAST(list, context)) { + this.setTypeChecked(list, context); + + for (var i = 0, n = list.childCount(); i < n; i++) { + this.resolveAST(list.childAt(i), false, context); + } + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveSeparatedList = function (list, context) { + if (this.canTypeCheckAST(list, context)) { + this.setTypeChecked(list, context); + + for (var i = 0, n = list.nonSeparatorCount(); i < n; i++) { + this.resolveAST(list.nonSeparatorAt(i), false, context); + } + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveVoidExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.undefinedTypeSymbol; + }; + + PullTypeResolver.prototype.resolveLogicalOperation = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckLogicalOperation(ast, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckLogicalOperation = function (binex, context) { + this.setTypeChecked(binex, context); + + var leftType = this.resolveAST(binex.left, false, context).type; + var rightType = this.resolveAST(binex.right, false, context).type; + + var comparisonInfo = new TypeComparisonInfo(); + if (!this.sourceIsAssignableToTarget(leftType, rightType, binex, context, comparisonInfo) && !this.sourceIsAssignableToTarget(rightType, leftType, binex, context, comparisonInfo)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(binex); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binex, TypeScript.DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2, [ + TypeScript.SyntaxFacts.getText(TypeScript.SyntaxFacts.getOperatorTokenFromBinaryExpression(binex.kind())), + leftType.toString(enclosingSymbol), rightType.toString(enclosingSymbol)])); + } + }; + + PullTypeResolver.prototype.resolveLogicalNotExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.operand, false, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.resolveUnaryArithmeticOperation = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckUnaryArithmeticOperation(ast, context); + } + + return this.semanticInfoChain.numberTypeSymbol; + }; + + PullTypeResolver.prototype.resolvePostfixUnaryExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckPostfixUnaryExpression(ast, context); + } + + return this.semanticInfoChain.numberTypeSymbol; + }; + + PullTypeResolver.prototype.isAnyOrNumberOrEnum = function (type) { + return this.isAnyOrEquivalent(type) || type === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(type); + }; + + PullTypeResolver.prototype.typeCheckUnaryArithmeticOperation = function (unaryExpression, context) { + this.setTypeChecked(unaryExpression, context); + + var nodeType = unaryExpression.kind(); + var expression = this.resolveAST(unaryExpression.operand, false, context); + + if (nodeType === 164 /* PlusExpression */ || nodeType == 165 /* NegateExpression */ || nodeType == 166 /* BitwiseNotExpression */) { + return; + } + + TypeScript.Debug.assert(nodeType === 168 /* PreIncrementExpression */ || nodeType === 169 /* PreDecrementExpression */); + + var operandType = expression.type; + if (!this.isAnyOrNumberOrEnum(operandType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type_any_number_or_an_enum_type)); + } + + if (!this.isReference(unaryExpression.operand, expression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer)); + } + }; + + PullTypeResolver.prototype.typeCheckPostfixUnaryExpression = function (unaryExpression, context) { + this.setTypeChecked(unaryExpression, context); + + var nodeType = unaryExpression.kind(); + var expression = this.resolveAST(unaryExpression.operand, false, context); + + TypeScript.Debug.assert(nodeType === 210 /* PostIncrementExpression */ || nodeType === 211 /* PostDecrementExpression */); + + var operandType = expression.type; + if (!this.isAnyOrNumberOrEnum(operandType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type_any_number_or_an_enum_type)); + } + + if (!this.isReference(unaryExpression.operand, expression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer)); + } + }; + + PullTypeResolver.prototype.resolveBinaryArithmeticExpression = function (binaryExpression, context) { + if (this.canTypeCheckAST(binaryExpression, context)) { + this.typeCheckBinaryArithmeticExpression(binaryExpression, context); + } + + return this.semanticInfoChain.numberTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckBinaryArithmeticExpression = function (binaryExpression, context) { + this.setTypeChecked(binaryExpression, context); + + var lhsSymbol = this.resolveAST(binaryExpression.left, false, context); + + var lhsType = lhsSymbol.type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + if (lhsType === this.semanticInfoChain.nullTypeSymbol || lhsType === this.semanticInfoChain.undefinedTypeSymbol) { + lhsType = rhsType; + } + + if (rhsType === this.semanticInfoChain.nullTypeSymbol || rhsType === this.semanticInfoChain.undefinedTypeSymbol) { + rhsType = lhsType; + } + + var lhsIsFit = this.isAnyOrNumberOrEnum(lhsType); + var rhsIsFit = this.isAnyOrNumberOrEnum(rhsType); + + if (!rhsIsFit) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type)); + } + + if (!lhsIsFit) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type)); + } + + if (lhsIsFit && rhsIsFit) { + switch (binaryExpression.kind()) { + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + if (!this.isReference(binaryExpression.left, lhsSymbol)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_left_hand_side_of_assignment_expression)); + } + + this.checkAssignability(binaryExpression.left, rhsType, lhsType, context); + } + } + }; + + PullTypeResolver.prototype.resolveTypeOfExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.stringTypeSymbol; + }; + + PullTypeResolver.prototype.resolveThrowStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveDeleteExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.resolveInstanceOfExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckInstanceOfExpression(ast, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckInstanceOfExpression = function (binaryExpression, context) { + this.setTypeChecked(binaryExpression, context); + + var lhsType = this.resolveAST(binaryExpression.left, false, context).type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + var enclosingSymbol = this.getEnclosingSymbolForAST(binaryExpression); + var isValidLHS = this.isAnyOrEquivalent(lhsType) || lhsType.isObject() || lhsType.isTypeParameter(); + var isValidRHS = this.isAnyOrEquivalent(rhsType) || this.typeIsAssignableToFunction(rhsType, binaryExpression, context); + + if (!isValidLHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter)); + } + + if (!isValidRHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type)); + } + }; + + PullTypeResolver.prototype.resolveCommaExpression = function (commaExpression, context) { + if (this.canTypeCheckAST(commaExpression, context)) { + this.setTypeChecked(commaExpression, context); + + this.resolveAST(commaExpression.left, false, context); + } + + return this.resolveAST(commaExpression.right, false, context).type; + }; + + PullTypeResolver.prototype.resolveInExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckInExpression(ast, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckInExpression = function (binaryExpression, context) { + this.setTypeChecked(binaryExpression, context); + + var lhsType = this.resolveAST(binaryExpression.left, false, context).type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + var isValidLHS = this.isAnyOrEquivalent(lhsType.type) || lhsType.type === this.semanticInfoChain.stringTypeSymbol || lhsType.type === this.semanticInfoChain.numberTypeSymbol; + + var isValidRHS = this.isAnyOrEquivalent(rhsType) || rhsType.isObject() || rhsType.isTypeParameter(); + + if (!isValidLHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number)); + } + + if (!isValidRHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter)); + } + }; + + PullTypeResolver.prototype.resolveForStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.variableDeclaration, false, context); + this.resolveAST(ast.initializer, false, context); + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.incrementor, false, context); + this.resolveAST(ast.statement, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveForInStatement = function (forInStatement, context) { + if (this.canTypeCheckAST(forInStatement, context)) { + this.typeCheckForInStatement(forInStatement, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckForInStatement = function (forInStatement, context) { + this.setTypeChecked(forInStatement, context); + + if (forInStatement.variableDeclaration) { + var declaration = forInStatement.variableDeclaration; + + if (declaration.declarators.nonSeparatorCount() === 1) { + var varDecl = declaration.declarators.nonSeparatorAt(0); + + if (varDecl.typeAnnotation) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(declaration, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_cannot_use_a_type_annotation)); + } + } + } else { + var varSym = this.resolveAST(forInStatement.left, false, context); + var isStringOrNumber = varSym.type === this.semanticInfoChain.stringTypeSymbol || this.isAnyOrEquivalent(varSym.type); + + if (!isStringOrNumber) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(forInStatement.left, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_must_be_of_types_string_or_any)); + } + } + + var rhsType = this.resolveAST(forInStatement.expression, false, context).type; + var isValidRHS = rhsType && (this.isAnyOrEquivalent(rhsType) || rhsType.isObject() || rhsType.isTypeParameter()); + + if (!isValidRHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(forInStatement.expression, TypeScript.DiagnosticCode.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter)); + } + + this.resolveAST(forInStatement.statement, false, context); + }; + + PullTypeResolver.prototype.resolveWhileStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckWhileStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckWhileStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.resolveDoStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckDoStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckDoStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.resolveIfStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckIfStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckIfStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.statement, false, context); + this.resolveAST(ast.elseClause, false, context); + }; + + PullTypeResolver.prototype.resolveElseClause = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckElseClause(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckElseClause = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.resolveBlock = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.statements, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveVariableStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.declaration, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveVariableDeclarationList = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.declarators, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveWithStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckWithStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckWithStatement = function (ast, context) { + this.setTypeChecked(ast, context); + var withStatement = ast; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(withStatement.condition, TypeScript.DiagnosticCode.All_symbols_within_a_with_block_will_be_resolved_to_any)); + }; + + PullTypeResolver.prototype.resolveTryStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckTryStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckTryStatement = function (ast, context) { + this.setTypeChecked(ast, context); + var tryStatement = ast; + + this.resolveAST(tryStatement.block, false, context); + this.resolveAST(tryStatement.catchClause, false, context); + this.resolveAST(tryStatement.finallyClause, false, context); + }; + + PullTypeResolver.prototype.resolveCatchClause = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckCatchClause(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckCatchClause = function (ast, context) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.block, false, context); + + var catchDecl = this.semanticInfoChain.getDeclForAST(ast); + this.validateVariableDeclarationGroups(catchDecl, context); + }; + + PullTypeResolver.prototype.resolveFinallyClause = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckFinallyClause(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckFinallyClause = function (ast, context) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.block, false, context); + }; + + PullTypeResolver.prototype.getEnclosingFunctionDeclaration = function (ast) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + + while (enclosingDecl) { + if (enclosingDecl.kind & 1032192 /* SomeFunction */) { + return enclosingDecl; + } + + enclosingDecl = enclosingDecl.getParentDecl(); + } + + return null; + }; + + PullTypeResolver.prototype.resolveReturnExpression = function (expression, enclosingFunction, context) { + if (enclosingFunction) { + enclosingFunction.setFlag(4194304 /* HasReturnStatement */); + } + + var isContextuallyTyped = false; + + if (enclosingFunction) { + var enclosingDeclAST = this.getASTForDecl(enclosingFunction); + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); + if (typeAnnotation) { + var returnTypeAnnotationSymbol = this.resolveTypeReference(typeAnnotation, context); + if (returnTypeAnnotationSymbol) { + isContextuallyTyped = true; + context.pushNewContextualType(returnTypeAnnotationSymbol); + } + } else { + var currentContextualType = context.getContextualType(); + if (currentContextualType && currentContextualType.isFunction()) { + var contextualSignatures = currentContextualType.kind == 33554432 /* ConstructorType */ ? currentContextualType.getConstructSignatures() : currentContextualType.getCallSignatures(); + var currentContextualTypeSignatureSymbol = contextualSignatures[0]; + + var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.returnType; + if (currentContextualTypeReturnTypeSymbol) { + isContextuallyTyped = true; + context.propagateContextualType(currentContextualTypeReturnTypeSymbol); + } + } + } + } + + var result = this.resolveAST(expression, isContextuallyTyped, context).type; + if (isContextuallyTyped) { + context.popAnyContextualType(); + } + + return result; + }; + + PullTypeResolver.prototype.typeCheckReturnExpression = function (expression, expressionType, enclosingFunction, context) { + if (enclosingFunction && enclosingFunction.kind === 32768 /* ConstructorMethod */) { + var classDecl = enclosingFunction.getParentDecl(); + if (classDecl) { + var classSymbol = classDecl.getSymbol(); + this.resolveDeclaredSymbol(classSymbol, context); + + var comparisonInfo = new TypeComparisonInfo(); + var isAssignable = this.sourceIsAssignableToTarget(expressionType, classSymbol.type, expression, context, comparisonInfo); + if (!isAssignable) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class)); + } + } + } + + if (enclosingFunction && enclosingFunction.kind === 524288 /* SetAccessor */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Setters_cannot_return_a_value)); + } + + if (enclosingFunction) { + var enclosingDeclAST = this.getASTForDecl(enclosingFunction); + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); + if (typeAnnotation || enclosingFunction.kind === 262144 /* GetAccessor */) { + var signatureSymbol = enclosingFunction.getSignatureSymbol(); + var sigReturnType = signatureSymbol.returnType; + + if (expressionType && sigReturnType) { + var comparisonInfo = new TypeComparisonInfo(); + var upperBound = null; + + this.resolveDeclaredSymbol(expressionType, context); + this.resolveDeclaredSymbol(sigReturnType, context); + + var isAssignable = this.sourceIsAssignableToTarget(expressionType, sigReturnType, expression, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(expression); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [expressionType.toString(enclosingSymbol), sigReturnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [expressionType.toString(enclosingSymbol), sigReturnType.toString(enclosingSymbol)])); + } + } + } + } + } + }; + + PullTypeResolver.prototype.resolveReturnStatement = function (returnAST, context) { + var enclosingFunction = this.getEnclosingFunctionDeclaration(returnAST); + if (enclosingFunction) { + enclosingFunction.setFlag(4194304 /* HasReturnStatement */); + } + + var returnType = this.getSymbolForAST(returnAST, context); + var canTypeCheckAST = this.canTypeCheckAST(returnAST, context); + if (!returnType || canTypeCheckAST) { + var returnExpr = returnAST.expression; + + var resolvedReturnType = returnExpr === null ? this.semanticInfoChain.voidTypeSymbol : this.resolveReturnExpression(returnExpr, enclosingFunction, context); + + if (!returnType) { + returnType = resolvedReturnType; + this.setSymbolForAST(returnAST, resolvedReturnType, context); + } + + if (returnExpr && canTypeCheckAST) { + this.setTypeChecked(returnExpr, context); + this.typeCheckReturnExpression(returnExpr, resolvedReturnType, enclosingFunction, context); + } + } + + return returnType; + }; + + PullTypeResolver.prototype.resolveSwitchStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckSwitchStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckSwitchStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + var expressionType = this.resolveAST(ast.expression, false, context).type; + + for (var i = 0, n = ast.switchClauses.childCount(); i < n; i++) { + var switchClause = ast.switchClauses.childAt(i); + if (switchClause.kind() === 233 /* CaseSwitchClause */) { + var caseSwitchClause = switchClause; + + var caseClauseExpressionType = this.resolveAST(caseSwitchClause.expression, false, context).type; + this.resolveAST(caseSwitchClause.statements, false, context); + + var comparisonInfo = new TypeComparisonInfo(); + if (!this.sourceIsAssignableToTarget(expressionType, caseClauseExpressionType, caseSwitchClause.expression, context, comparisonInfo) && !this.sourceIsAssignableToTarget(caseClauseExpressionType, expressionType, caseSwitchClause.expression, context, comparisonInfo)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(caseSwitchClause.expression); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(caseSwitchClause.expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [caseClauseExpressionType.toString(enclosingSymbol), expressionType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(caseSwitchClause.expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [caseClauseExpressionType.toString(enclosingSymbol), expressionType.toString(enclosingSymbol)])); + } + } + } else { + var defaultSwitchClause = switchClause; + this.resolveAST(defaultSwitchClause.statements, false, context); + } + } + }; + + PullTypeResolver.prototype.resolveLabeledStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckLabeledStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckLabeledStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + var labelIdentifier = ast.identifier.valueText(); + + var breakableLabels = this.getEnclosingLabels(ast, true, false); + + var matchingLabel = TypeScript.ArrayUtilities.firstOrDefault(breakableLabels, function (s) { + return s.identifier.valueText() === labelIdentifier; + }); + if (matchingLabel) { + context.postDiagnostic(this.semanticInfoChain.duplicateIdentifierDiagnosticFromAST(ast.identifier, labelIdentifier, matchingLabel)); + } + + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.labelIsOnContinuableConstruct = function (statement) { + switch (statement.kind()) { + case 160 /* LabeledStatement */: + return this.labelIsOnContinuableConstruct(statement.statement); + + case 158 /* WhileStatement */: + case 154 /* ForStatement */: + case 155 /* ForInStatement */: + case 161 /* DoStatement */: + return true; + + default: + return false; + } + }; + + PullTypeResolver.prototype.resolveContinueStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckContinueStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.isIterationStatement = function (ast) { + switch (ast.kind()) { + case 154 /* ForStatement */: + case 155 /* ForInStatement */: + case 158 /* WhileStatement */: + case 161 /* DoStatement */: + return true; + } + + return false; + }; + + PullTypeResolver.prototype.isAnyFunctionExpressionOrDeclaration = function (ast) { + switch (ast.kind()) { + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 129 /* FunctionDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 241 /* FunctionPropertyAssignment */: + case 137 /* ConstructorDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + return true; + } + + return false; + }; + + PullTypeResolver.prototype.inSwitchStatement = function (ast) { + while (ast) { + if (ast.kind() === 151 /* SwitchStatement */) { + return true; + } + + if (this.isAnyFunctionExpressionOrDeclaration(ast)) { + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inIterationStatement = function (ast, crossFunctions) { + while (ast) { + if (this.isIterationStatement(ast)) { + return true; + } + + if (!crossFunctions && this.isAnyFunctionExpressionOrDeclaration(ast)) { + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.getEnclosingLabels = function (ast, breakable, crossFunctions) { + var result = []; + + ast = ast.parent; + while (ast) { + if (ast.kind() === 160 /* LabeledStatement */) { + var labeledStatement = ast; + if (breakable) { + result.push(labeledStatement); + } else { + if (this.labelIsOnContinuableConstruct(labeledStatement.statement)) { + result.push(labeledStatement); + } + } + } + + if (!crossFunctions && this.isAnyFunctionExpressionOrDeclaration(ast)) { + break; + } + + ast = ast.parent; + } + + return result; + }; + + PullTypeResolver.prototype.typeCheckContinueStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + if (!this.inIterationStatement(ast, false)) { + if (this.inIterationStatement(ast, true)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.continue_statement_can_only_be_used_within_an_enclosing_iteration_statement)); + } + } else if (ast.identifier) { + var continuableLabels = this.getEnclosingLabels(ast, false, false); + + if (!TypeScript.ArrayUtilities.any(continuableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + var continuableLabels = this.getEnclosingLabels(ast, false, true); + + if (TypeScript.ArrayUtilities.any(continuableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_not_found)); + } + } + } + }; + + PullTypeResolver.prototype.resolveBreakStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckBreakStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckBreakStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + if (ast.identifier) { + var breakableLabels = this.getEnclosingLabels(ast, true, false); + + if (!TypeScript.ArrayUtilities.any(breakableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + var breakableLabels = this.getEnclosingLabels(ast, true, true); + if (TypeScript.ArrayUtilities.any(breakableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_not_found)); + } + } + } else if (!this.inIterationStatement(ast, false) && !this.inSwitchStatement(ast)) { + if (this.inIterationStatement(ast, true)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement)); + } + } + }; + + PullTypeResolver.prototype.resolveAST = function (ast, isContextuallyTyped, context) { + if (!ast) { + return; + } + + var symbol = this.getSymbolForAST(ast, context); + if (symbol && symbol.isResolved) { + this.typeCheckAST(ast, isContextuallyTyped, context); + return symbol; + } + + if (ast.isExpression() && !isTypesOnlyLocation(ast)) { + return this.resolveExpressionAST(ast, isContextuallyTyped, context); + } + + var nodeType = ast.kind(); + + switch (nodeType) { + case 124 /* ArrayType */: + case 126 /* GenericType */: + case 122 /* ObjectType */: + case 127 /* TypeQuery */: + case 125 /* ConstructorType */: + case 123 /* FunctionType */: + return this.resolveTypeReference(ast, context); + + case 1 /* List */: + return this.resolveList(ast, context); + + case 2 /* SeparatedList */: + return this.resolveSeparatedList(ast, context); + + case 120 /* SourceUnit */: + return this.resolveSourceUnit(ast, context); + + case 132 /* EnumDeclaration */: + return this.resolveEnumDeclaration(ast, context); + + case 130 /* ModuleDeclaration */: + return this.resolveModuleDeclaration(ast, context); + + case 128 /* InterfaceDeclaration */: + return this.resolveInterfaceDeclaration(ast, context); + + case 131 /* ClassDeclaration */: + return this.resolveClassDeclaration(ast, context); + + case 224 /* VariableDeclaration */: + return this.resolveVariableDeclarationList(ast, context); + + case 136 /* MemberVariableDeclaration */: + return this.resolveMemberVariableDeclaration(ast, context); + + case 225 /* VariableDeclarator */: + return this.resolveVariableDeclarator(ast, context); + + case 141 /* PropertySignature */: + return this.resolvePropertySignature(ast, context); + + case 227 /* ParameterList */: + return this.resolveParameterList(ast, context); + + case 242 /* Parameter */: + return this.resolveParameter(ast, context); + + case 243 /* EnumElement */: + return this.resolveEnumElement(ast, context); + + case 232 /* EqualsValueClause */: + return this.resolveEqualsValueClause(ast, isContextuallyTyped, context); + + case 238 /* TypeParameter */: + return this.resolveTypeParameterDeclaration(ast, context); + + case 239 /* Constraint */: + return this.resolveConstraint(ast, context); + + case 133 /* ImportDeclaration */: + return this.resolveImportDeclaration(ast, context); + + case 240 /* SimplePropertyAssignment */: + return this.resolveSimplePropertyAssignment(ast, isContextuallyTyped, context); + + case 241 /* FunctionPropertyAssignment */: + return this.resolveFunctionPropertyAssignment(ast, isContextuallyTyped, context); + + case 11 /* IdentifierName */: + TypeScript.Debug.assert(isTypesOnlyLocation(ast)); + return this.resolveTypeNameExpression(ast, context); + + case 121 /* QualifiedName */: + return this.resolveQualifiedName(ast, context); + + case 137 /* ConstructorDeclaration */: + return this.resolveConstructorDeclaration(ast, context); + + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + return this.resolveAccessorDeclaration(ast, context); + + case 138 /* IndexMemberDeclaration */: + return this.resolveIndexMemberDeclaration(ast, context); + + case 144 /* IndexSignature */: + return this.resolveIndexSignature(ast, context); + + case 135 /* MemberFunctionDeclaration */: + return this.resolveMemberFunctionDeclaration(ast, context); + + case 142 /* CallSignature */: + return this.resolveCallSignature(ast, context); + + case 143 /* ConstructSignature */: + return this.resolveConstructSignature(ast, context); + + case 145 /* MethodSignature */: + return this.resolveMethodSignature(ast, context); + + case 129 /* FunctionDeclaration */: + return this.resolveAnyFunctionDeclaration(ast, context); + + case 244 /* TypeAnnotation */: + return this.resolveTypeAnnotation(ast, context); + + case 134 /* ExportAssignment */: + return this.resolveExportAssignmentStatement(ast, context); + + case 157 /* ThrowStatement */: + return this.resolveThrowStatement(ast, context); + + case 149 /* ExpressionStatement */: + return this.resolveExpressionStatement(ast, context); + + case 154 /* ForStatement */: + return this.resolveForStatement(ast, context); + + case 155 /* ForInStatement */: + return this.resolveForInStatement(ast, context); + + case 158 /* WhileStatement */: + return this.resolveWhileStatement(ast, context); + + case 161 /* DoStatement */: + return this.resolveDoStatement(ast, context); + + case 147 /* IfStatement */: + return this.resolveIfStatement(ast, context); + + case 235 /* ElseClause */: + return this.resolveElseClause(ast, context); + + case 146 /* Block */: + return this.resolveBlock(ast, context); + + case 148 /* VariableStatement */: + return this.resolveVariableStatement(ast, context); + + case 163 /* WithStatement */: + return this.resolveWithStatement(ast, context); + + case 159 /* TryStatement */: + return this.resolveTryStatement(ast, context); + + case 236 /* CatchClause */: + return this.resolveCatchClause(ast, context); + + case 237 /* FinallyClause */: + return this.resolveFinallyClause(ast, context); + + case 150 /* ReturnStatement */: + return this.resolveReturnStatement(ast, context); + + case 151 /* SwitchStatement */: + return this.resolveSwitchStatement(ast, context); + + case 153 /* ContinueStatement */: + return this.resolveContinueStatement(ast, context); + + case 152 /* BreakStatement */: + return this.resolveBreakStatement(ast, context); + + case 160 /* LabeledStatement */: + return this.resolveLabeledStatement(ast, context); + } + + return this.semanticInfoChain.anyTypeSymbol; + }; + + PullTypeResolver.prototype.resolveExpressionAST = function (ast, isContextuallyOrInferentiallyTyped, context) { + var expressionSymbol = this.resolveExpressionWorker(ast, isContextuallyOrInferentiallyTyped, context); + + if (isContextuallyOrInferentiallyTyped && context.isInferentiallyTyping()) { + return this.alterPotentialGenericFunctionTypeToInstantiatedFunctionTypeForTypeArgumentInference(expressionSymbol, context); + } else { + return expressionSymbol; + } + }; + + PullTypeResolver.prototype.resolveExpressionWorker = function (ast, isContextuallyTyped, context) { + switch (ast.kind()) { + case 215 /* ObjectLiteralExpression */: + return this.resolveObjectLiteralExpression(ast, isContextuallyTyped, context); + + case 11 /* IdentifierName */: + return this.resolveNameExpression(ast, context); + + case 212 /* MemberAccessExpression */: + return this.resolveMemberAccessExpression(ast, context); + + case 222 /* FunctionExpression */: + return this.resolveFunctionExpression(ast, isContextuallyTyped, context); + + case 219 /* SimpleArrowFunctionExpression */: + return this.resolveSimpleArrowFunctionExpression(ast, isContextuallyTyped, context); + + case 218 /* ParenthesizedArrowFunctionExpression */: + return this.resolveParenthesizedArrowFunctionExpression(ast, isContextuallyTyped, context); + + case 214 /* ArrayLiteralExpression */: + return this.resolveArrayLiteralExpression(ast, isContextuallyTyped, context); + + case 35 /* ThisKeyword */: + return this.resolveThisExpression(ast, context); + + case 50 /* SuperKeyword */: + return this.resolveSuperExpression(ast, context); + + case 213 /* InvocationExpression */: + return this.resolveInvocationExpression(ast, context); + + case 216 /* ObjectCreationExpression */: + return this.resolveObjectCreationExpression(ast, context); + + case 220 /* CastExpression */: + return this.resolveCastExpression(ast, context); + + case 13 /* NumericLiteral */: + return this.semanticInfoChain.numberTypeSymbol; + + case 14 /* StringLiteral */: + return this.semanticInfoChain.stringTypeSymbol; + + case 32 /* NullKeyword */: + return this.semanticInfoChain.nullTypeSymbol; + + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return this.semanticInfoChain.booleanTypeSymbol; + + case 172 /* VoidExpression */: + return this.resolveVoidExpression(ast, context); + + case 174 /* AssignmentExpression */: + return this.resolveAssignmentExpression(ast, context); + + case 167 /* LogicalNotExpression */: + return this.resolveLogicalNotExpression(ast, context); + + case 193 /* NotEqualsWithTypeConversionExpression */: + case 192 /* EqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + case 196 /* LessThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 197 /* GreaterThanExpression */: + return this.resolveLogicalOperation(ast, context); + + case 208 /* AddExpression */: + case 175 /* AddAssignmentExpression */: + return this.resolveBinaryAdditionOperation(ast, context); + + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + case 166 /* BitwiseNotExpression */: + case 168 /* PreIncrementExpression */: + case 169 /* PreDecrementExpression */: + return this.resolveUnaryArithmeticOperation(ast, context); + + case 210 /* PostIncrementExpression */: + case 211 /* PostDecrementExpression */: + return this.resolvePostfixUnaryExpression(ast, context); + + case 209 /* SubtractExpression */: + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + case 189 /* BitwiseOrExpression */: + case 191 /* BitwiseAndExpression */: + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + case 190 /* BitwiseExclusiveOrExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + return this.resolveBinaryArithmeticExpression(ast, context); + + case 221 /* ElementAccessExpression */: + return this.resolveElementAccessExpression(ast, context); + + case 187 /* LogicalOrExpression */: + return this.resolveLogicalOrExpression(ast, isContextuallyTyped, context); + + case 188 /* LogicalAndExpression */: + return this.resolveLogicalAndExpression(ast, context); + + case 171 /* TypeOfExpression */: + return this.resolveTypeOfExpression(ast, context); + + case 170 /* DeleteExpression */: + return this.resolveDeleteExpression(ast, context); + + case 186 /* ConditionalExpression */: + return this.resolveConditionalExpression(ast, isContextuallyTyped, context); + + case 12 /* RegularExpressionLiteral */: + return this.resolveRegularExpressionLiteral(); + + case 217 /* ParenthesizedExpression */: + return this.resolveParenthesizedExpression(ast, context); + + case 200 /* InstanceOfExpression */: + return this.resolveInstanceOfExpression(ast, context); + + case 173 /* CommaExpression */: + return this.resolveCommaExpression(ast, context); + + case 201 /* InExpression */: + return this.resolveInExpression(ast, context); + + case 223 /* OmittedExpression */: + return this.semanticInfoChain.undefinedTypeSymbol; + } + + TypeScript.Debug.fail("resolveExpressionASTWorker: Missing expression kind: " + TypeScript.SyntaxKind[ast.kind()]); + }; + + PullTypeResolver.prototype.typeCheckAST = function (ast, isContextuallyTyped, context) { + if (!this.canTypeCheckAST(ast, context)) { + return; + } + + var nodeType = ast.kind(); + switch (nodeType) { + case 120 /* SourceUnit */: + this.typeCheckSourceUnit(ast, context); + return; + + case 132 /* EnumDeclaration */: + this.typeCheckEnumDeclaration(ast, context); + return; + + case 130 /* ModuleDeclaration */: + this.typeCheckModuleDeclaration(ast, context); + return; + + case 128 /* InterfaceDeclaration */: + this.typeCheckInterfaceDeclaration(ast, context); + return; + + case 131 /* ClassDeclaration */: + this.typeCheckClassDeclaration(ast, context); + return; + + case 243 /* EnumElement */: + this.typeCheckEnumElement(ast, context); + return; + + case 136 /* MemberVariableDeclaration */: + this.typeCheckMemberVariableDeclaration(ast, context); + return; + + case 225 /* VariableDeclarator */: + this.typeCheckVariableDeclarator(ast, context); + return; + + case 141 /* PropertySignature */: + this.typeCheckPropertySignature(ast, context); + return; + + case 242 /* Parameter */: + this.typeCheckParameter(ast, context); + return; + + case 133 /* ImportDeclaration */: + this.typeCheckImportDeclaration(ast, context); + return; + + case 215 /* ObjectLiteralExpression */: + this.resolveObjectLiteralExpression(ast, isContextuallyTyped, context); + return; + + case 241 /* FunctionPropertyAssignment */: + this.typeCheckFunctionPropertyAssignment(ast, isContextuallyTyped, context); + return; + + case 11 /* IdentifierName */: + if (isTypesOnlyLocation(ast)) { + this.resolveTypeNameExpression(ast, context); + } else { + this.resolveNameExpression(ast, context); + } + return; + + case 212 /* MemberAccessExpression */: + this.resolveMemberAccessExpression(ast, context); + return; + + case 121 /* QualifiedName */: + this.resolveQualifiedName(ast, context); + return; + + case 222 /* FunctionExpression */: + this.typeCheckFunctionExpression(ast, isContextuallyTyped, context); + return; + + case 137 /* ConstructorDeclaration */: + this.typeCheckConstructorDeclaration(ast, context); + return; + + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + this.typeCheckAccessorDeclaration(ast, context); + return; + + case 135 /* MemberFunctionDeclaration */: + this.typeCheckMemberFunctionDeclaration(ast, context); + return; + + case 145 /* MethodSignature */: + this.typeCheckMethodSignature(ast, context); + return; + + case 144 /* IndexSignature */: + this.typeCheckIndexSignature(ast, context); + break; + + case 142 /* CallSignature */: + this.typeCheckCallSignature(ast, context); + return; + + case 143 /* ConstructSignature */: + this.typeCheckConstructSignature(ast, context); + return; + + case 129 /* FunctionDeclaration */: { + var funcDecl = ast; + this.typeCheckAnyFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + return; + } + + case 219 /* SimpleArrowFunctionExpression */: + this.typeCheckSimpleArrowFunctionExpression(ast, isContextuallyTyped, context); + return; + + case 218 /* ParenthesizedArrowFunctionExpression */: + this.typeCheckParenthesizedArrowFunctionExpression(ast, isContextuallyTyped, context); + return; + + case 214 /* ArrayLiteralExpression */: + this.resolveArrayLiteralExpression(ast, isContextuallyTyped, context); + return; + + case 213 /* InvocationExpression */: + this.typeCheckInvocationExpression(ast, context); + return; + + case 216 /* ObjectCreationExpression */: + this.typeCheckObjectCreationExpression(ast, context); + return; + + case 150 /* ReturnStatement */: + this.resolveReturnStatement(ast, context); + return; + + default: + TypeScript.Debug.assert(false, "Failure nodeType: " + TypeScript.SyntaxKind[ast.kind()] + ". Implement typeCheck when symbol is set for the ast as part of resolution."); + } + }; + + PullTypeResolver.prototype.processPostTypeCheckWorkItems = function (context) { + while (this.postTypeCheckWorkitems.length) { + var ast = this.postTypeCheckWorkitems.pop(); + this.postTypeCheck(ast, context); + } + }; + + PullTypeResolver.prototype.postTypeCheck = function (ast, context) { + var nodeType = ast.kind(); + + switch (nodeType) { + case 242 /* Parameter */: + case 225 /* VariableDeclarator */: + this.postTypeCheckVariableDeclaratorOrParameter(ast, context); + return; + + case 131 /* ClassDeclaration */: + this.postTypeCheckClassDeclaration(ast, context); + return; + + case 129 /* FunctionDeclaration */: + this.postTypeCheckFunctionDeclaration(ast, context); + return; + + case 130 /* ModuleDeclaration */: + this.postTypeCheckModuleDeclaration(ast, context); + return; + + case 132 /* EnumDeclaration */: + this.postTypeCheckEnumDeclaration(ast, context); + return; + + case 133 /* ImportDeclaration */: + this.postTypeCheckImportDeclaration(ast, context); + return; + + case 11 /* IdentifierName */: + this.postTypeCheckNameExpression(ast, context); + return; + + default: + TypeScript.Debug.assert(false, "Implement postTypeCheck clause to handle the postTypeCheck work, nodeType: " + TypeScript.SyntaxKind[ast.kind()]); + } + }; + + PullTypeResolver.prototype.resolveRegularExpressionLiteral = function () { + if (this.cachedRegExpInterfaceType()) { + return this.cachedRegExpInterfaceType(); + } else { + return this.semanticInfoChain.anyTypeSymbol; + } + }; + + PullTypeResolver.prototype.postTypeCheckNameExpression = function (nameAST, context) { + this.checkThisCaptureVariableCollides(nameAST, false, context); + }; + + PullTypeResolver.prototype.typeCheckNameExpression = function (nameAST, context) { + this.setTypeChecked(nameAST, context); + this.checkNameForCompilerGeneratedDeclarationCollision(nameAST, false, nameAST, context); + }; + + PullTypeResolver.prototype.resolveNameExpression = function (nameAST, context) { + var nameSymbol = this.getSymbolForAST(nameAST, context); + var foundCached = nameSymbol !== null; + + if (!foundCached || this.canTypeCheckAST(nameAST, context)) { + if (this.canTypeCheckAST(nameAST, context)) { + this.typeCheckNameExpression(nameAST, context); + } + nameSymbol = this.computeNameExpression(nameAST, context); + } + + this.resolveDeclaredSymbol(nameSymbol, context); + + if (nameSymbol && (nameSymbol.type !== this.semanticInfoChain.anyTypeSymbol || nameSymbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { + this.setSymbolForAST(nameAST, nameSymbol, context); + } + + return nameSymbol; + }; + + PullTypeResolver.prototype.isInEnumDecl = function (decl) { + if (decl.kind & 64 /* Enum */) { + return true; + } + + var declPath = decl.getParentPath(); + + var disallowedKinds = 164 /* SomeContainer */ | 58728795 /* SomeType */; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + + if (decl.kind & 64 /* Enum */) { + return true; + } + + if (decl.kind & disallowedKinds) { + return false; + } + } + return false; + }; + + PullTypeResolver.prototype.getSomeInnermostFunctionScopeDecl = function (declPath) { + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + if (decl.kind & 1032192 /* SomeFunction */) { + return decl; + } + } + + return null; + }; + + PullTypeResolver.prototype.isFromFunctionScope = function (nameSymbol, functionScopeDecl) { + var _this = this; + return TypeScript.ArrayUtilities.any(nameSymbol.getDeclarations(), function (nameSymbolDecl) { + return _this.getSomeInnermostFunctionScopeDecl(nameSymbolDecl.getParentPath()) === functionScopeDecl; + }); + }; + + PullTypeResolver.prototype.findConstructorDeclOfEnclosingType = function (decl) { + var current = decl; + while (current) { + if (TypeScript.hasFlag(current.kind, 4096 /* Property */)) { + var parentDecl = current.getParentDecl(); + if (TypeScript.hasFlag(parentDecl.kind, 8 /* Class */)) { + return TypeScript.ArrayUtilities.lastOrDefault(parentDecl.getChildDecls(), function (decl) { + return TypeScript.hasFlag(decl.kind, 32768 /* ConstructorMethod */); + }); + } + } + + if (TypeScript.hasFlag(current.kind, 164 /* SomeContainer */)) { + return null; + } + + current = current.getParentDecl(); + } + return null; + }; + + PullTypeResolver.prototype.checkNameAsPartOfInitializerExpressionForInstanceMemberVariable = function (nameAST, nameSymbol, context) { + var id = nameAST.valueText(); + if (id.length === 0) { + return false; + } + + var memberVariableDeclarationAST = TypeScript.ASTHelpers.getEnclosingMemberVariableDeclaration(nameAST); + if (memberVariableDeclarationAST) { + var memberVariableDecl = this.semanticInfoChain.getDeclForAST(memberVariableDeclarationAST); + if (!TypeScript.hasFlag(memberVariableDecl.flags, 16 /* Static */)) { + var constructorDecl = this.findConstructorDeclOfEnclosingType(memberVariableDecl); + + if (constructorDecl) { + var childDecls = constructorDecl.searchChildDecls(id, 68147712 /* SomeValue */); + if (childDecls.length) { + if (TypeScript.PullHelpers.isSymbolDeclaredInScopeChain(nameSymbol, constructorDecl.getSymbol().getContainer())) { + var memberVariableSymbol = memberVariableDecl.getSymbol(); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, [memberVariableSymbol.getScopedName(constructorDecl.getSymbol()), nameAST.text()])); + return true; + } + } + } + } + } + return false; + }; + + PullTypeResolver.prototype.computeNameExpression = function (nameAST, context) { + var id = nameAST.valueText(); + if (id.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var nameSymbol = null; + var enclosingDecl = this.getEnclosingDeclForAST(nameAST); + + if (TypeScript.hasFlag(enclosingDecl.flags, 8388608 /* PropertyParameter */)) { + var valueDecl = enclosingDecl.getValueDecl(); + if (valueDecl && TypeScript.hasFlag(valueDecl.kind, 2048 /* Parameter */)) { + enclosingDecl = valueDecl; + } + } + + var isDeclarationASTOrDeclarationNameAST = TypeScript.ASTHelpers.isDeclarationASTOrDeclarationNameAST(nameAST); + if (isDeclarationASTOrDeclarationNameAST) { + nameSymbol = this.semanticInfoChain.getDeclForAST(nameAST.parent).getSymbol(); + } + + var declPath = enclosingDecl.getParentPath(); + + if (!nameSymbol) { + var searchKind = 68147712 /* SomeValue */; + + if (!this.isInEnumDecl(enclosingDecl)) { + searchKind = searchKind & ~(67108864 /* EnumMember */); + } + + var nameSymbol = this.getSymbolFromDeclPath(id, declPath, searchKind); + } + + if (id === "arguments") { + var functionScopeDecl = this.getSomeInnermostFunctionScopeDecl(declPath); + if (functionScopeDecl) { + if (!nameSymbol || !this.isFromFunctionScope(nameSymbol, functionScopeDecl)) { + nameSymbol = this.cachedFunctionArgumentsSymbol(); + this.resolveDeclaredSymbol(this.cachedIArgumentsInterfaceType(), context); + } + } + } + + var aliasSymbol = null; + if (nameSymbol && nameSymbol.isAlias() && !isDeclarationASTOrDeclarationNameAST) { + aliasSymbol = nameSymbol; + if (!this.inTypeQuery(nameAST)) { + aliasSymbol.setIsUsedAsValue(); + } + + this.resolveDeclaredSymbol(nameSymbol, context); + + this.resolveDeclaredSymbol(aliasSymbol.assignedValue(), context); + this.resolveDeclaredSymbol(aliasSymbol.assignedContainer(), context); + + nameSymbol = aliasSymbol.getExportAssignedValueSymbol(); + if (!nameSymbol) { + aliasSymbol = null; + } + } + + if (!nameSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [nameAST.text()])); + return this.getNewErrorTypeSymbol(id); + } else if (this.checkNameAsPartOfInitializerExpressionForInstanceMemberVariable(nameAST, nameSymbol, context)) { + return this.getNewErrorTypeSymbol(id); + } + + var nameDeclaration = nameSymbol.getDeclarations()[0]; + var nameParentDecl = nameDeclaration.getParentDecl(); + if (nameParentDecl && (nameParentDecl.kind & 1032192 /* SomeFunction */) && (nameParentDecl.flags & 33554432 /* HasDefaultArgs */)) { + var enclosingFunctionAST = this.semanticInfoChain.getASTForDecl(nameParentDecl); + var currentParameterIndex = this.getCurrentParameterIndexForFunction(nameAST, enclosingFunctionAST); + + var parameterList = TypeScript.ASTHelpers.getParameterList(enclosingFunctionAST); + + if (currentParameterIndex >= 0) { + var matchingParameter; + if (parameterList) { + for (var i = 0; i <= currentParameterIndex; i++) { + var candidateParameter = parameterList.parameters.nonSeparatorAt(i); + if (candidateParameter && candidateParameter.identifier.valueText() === id) { + matchingParameter = candidateParameter; + break; + } + } + } + + if (!matchingParameter) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, [parameterList.parameters.nonSeparatorAt(currentParameterIndex).identifier.text(), nameAST.text()])); + return this.getNewErrorTypeSymbol(id); + } else if (matchingParameter === TypeScript.ASTHelpers.getEnclosingParameterForInitializer(nameAST)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Parameter_0_cannot_be_referenced_in_its_initializer, [parameterList.parameters.nonSeparatorAt(currentParameterIndex).identifier.text()])); + return this.getNewErrorTypeSymbol(id); + } + } + } + + if (aliasSymbol) { + this.semanticInfoChain.setAliasSymbolForAST(nameAST, aliasSymbol); + } + + return nameSymbol; + }; + + PullTypeResolver.prototype.getCurrentParameterIndexForFunction = function (parameter, funcDecl) { + var parameterList = TypeScript.ASTHelpers.getParameterList(funcDecl); + if (parameterList) { + while (parameter && parameter.parent) { + if (parameter.parent.parent === parameterList) { + return parameterList.parameters.nonSeparatorIndexOf(parameter); + } + + parameter = parameter.parent; + } + } + + return -1; + }; + + PullTypeResolver.prototype.resolveMemberAccessExpression = function (dottedNameAST, context) { + return this.resolveDottedNameExpression(dottedNameAST, dottedNameAST.expression, dottedNameAST.name, context); + }; + + PullTypeResolver.prototype.resolveDottedNameExpression = function (dottedNameAST, expression, name, context) { + var symbol = this.getSymbolForAST(dottedNameAST, context); + var foundCached = symbol !== null; + + if (!foundCached || this.canTypeCheckAST(dottedNameAST, context)) { + var canTypeCheckDottedNameAST = this.canTypeCheckAST(dottedNameAST, context); + if (canTypeCheckDottedNameAST) { + this.setTypeChecked(dottedNameAST, context); + } + + symbol = this.computeDottedNameExpression(expression, name, context, canTypeCheckDottedNameAST); + } + + this.resolveDeclaredSymbol(symbol, context); + + if (symbol && (symbol.type !== this.semanticInfoChain.anyTypeSymbol || symbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { + this.setSymbolForAST(dottedNameAST, symbol, context); + this.setSymbolForAST(name, symbol, context); + } + + return symbol; + }; + + PullTypeResolver.prototype.computeDottedNameExpression = function (expression, name, context, checkSuperPrivateAndStaticAccess) { + var rhsName = name.valueText(); + if (rhsName.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var lhs = this.resolveAST(expression, false, context); + return this.computeDottedNameExpressionFromLHS(lhs, expression, name, context, checkSuperPrivateAndStaticAccess); + }; + + PullTypeResolver.prototype.computeDottedNameExpressionFromLHS = function (lhs, expression, name, context, checkSuperPrivateAndStaticAccess) { + var rhsName = name.valueText(); + if (rhsName.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var lhsType = lhs.type; + + if (lhs.isAlias()) { + var lhsAlias = lhs; + if (!this.inTypeQuery(expression)) { + lhsAlias.setIsUsedAsValue(); + } + lhsType = lhsAlias.getExportAssignedTypeSymbol(); + } + + if (lhsType.isAlias()) { + lhsType = lhsType.getExportAssignedTypeSymbol(); + } + + if (!lhsType) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.Could_not_find_enclosing_symbol_for_dotted_name_0, [name.text()])); + return this.getNewErrorTypeSymbol(); + } + + if (!lhsType.isResolved) { + var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, context); + + if (potentiallySpecializedType !== lhsType) { + if (!lhs.isType()) { + context.setTypeInContext(lhs, potentiallySpecializedType); + } + + lhsType = potentiallySpecializedType; + } + } + + if (lhsType.isContainer() && !lhsType.isAlias() && !lhsType.isEnum()) { + var instanceSymbol = lhsType.getInstanceSymbol(); + + if (instanceSymbol) { + lhsType = instanceSymbol.type; + } + } + + var originalLhsTypeForErrorReporting = lhsType; + + lhsType = this.getApparentType(lhsType).widenedType(this, expression, context); + + if (this.isAnyOrEquivalent(lhsType)) { + return lhsType; + } + + var nameSymbol = this._getNamedPropertySymbolOfAugmentedType(rhsName, lhsType); + + if (!nameSymbol) { + if (lhsType.kind === 32 /* DynamicModule */) { + var container = lhsType; + var associatedInstance = container.getInstanceSymbol(); + + if (associatedInstance) { + var instanceType = associatedInstance.type; + + nameSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, instanceType); + } + } else { + var associatedType = lhsType.getAssociatedContainerType(); + + if (associatedType && !associatedType.isClass()) { + nameSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, associatedType); + } + } + + if (!nameSymbol) { + var enclosingDecl = this.getEnclosingDeclForAST(expression); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.The_property_0_does_not_exist_on_value_of_type_1, [name.text(), originalLhsTypeForErrorReporting.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + return this.getNewErrorTypeSymbol(rhsName); + } + } + + if (checkSuperPrivateAndStaticAccess) { + this.checkForSuperMemberAccess(expression, name, nameSymbol, context) || this.checkForPrivateMemberAccess(name, lhsType, nameSymbol, context); + } + + return nameSymbol; + }; + + PullTypeResolver.prototype.resolveTypeNameExpression = function (nameAST, context) { + var typeNameSymbol = this.getSymbolForAST(nameAST, context); + + if (!typeNameSymbol || !typeNameSymbol.isType() || this.canTypeCheckAST(nameAST, context)) { + if (this.canTypeCheckAST(nameAST, context)) { + this.setTypeChecked(nameAST, context); + } + typeNameSymbol = this.computeTypeNameExpression(nameAST, context); + this.setSymbolForAST(nameAST, typeNameSymbol, context); + } + + this.resolveDeclaredSymbol(typeNameSymbol, context); + + return typeNameSymbol; + }; + + PullTypeResolver.prototype.computeTypeNameExpression = function (nameAST, context) { + var id = nameAST.valueText(); + if (id.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var enclosingDecl = this.getEnclosingDeclForAST(nameAST); + + var declPath = enclosingDecl.getParentPath(); + + var onLeftOfDot = this.isLeftSideOfQualifiedName(nameAST); + + var kindToCheckFirst = onLeftOfDot ? 164 /* SomeContainer */ : 58728795 /* SomeType */; + var kindToCheckSecond = onLeftOfDot ? 58728795 /* SomeType */ : 164 /* SomeContainer */; + + var typeNameSymbol = this.getSymbolFromDeclPath(id, declPath, kindToCheckFirst); + + if (!typeNameSymbol) { + typeNameSymbol = this.getSymbolFromDeclPath(id, declPath, kindToCheckSecond); + } + + if (!typeNameSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [nameAST.text()])); + return this.getNewErrorTypeSymbol(id); + } + + var typeNameSymbolAlias = null; + if (typeNameSymbol.isAlias()) { + typeNameSymbolAlias = typeNameSymbol; + this.resolveDeclaredSymbol(typeNameSymbol, context); + + var aliasedType = typeNameSymbolAlias.getExportAssignedTypeSymbol(); + + this.resolveDeclaredSymbol(aliasedType, context); + } + + if (typeNameSymbol.isTypeParameter()) { + if (this.isInStaticMemberContext(enclosingDecl)) { + var parentDecl = typeNameSymbol.getDeclarations()[0].getParentDecl(); + + if (parentDecl.kind === 8 /* Class */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Static_members_cannot_reference_class_type_parameters)); + return this.getNewErrorTypeSymbol(); + } + } + } + + if (!typeNameSymbol.isGeneric() && (typeNameSymbol.isClass() || typeNameSymbol.isInterface())) { + typeNameSymbol = TypeScript.PullTypeReferenceSymbol.createTypeReference(typeNameSymbol); + } + + return typeNameSymbol; + }; + + PullTypeResolver.prototype.isInStaticMemberContext = function (decl) { + while (decl) { + if (TypeScript.hasFlag(decl.kind, 1032192 /* SomeFunction */ | 4096 /* Property */) && TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + return true; + } + + if (TypeScript.hasFlag(decl.kind, 164 /* SomeContainer */)) { + return false; + } + + decl = decl.getParentDecl(); + } + + return false; + }; + + PullTypeResolver.prototype.isLeftSideOfQualifiedName = function (ast) { + return ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.left === ast; + }; + + PullTypeResolver.prototype.resolveGenericTypeReference = function (genericTypeAST, context) { + var _this = this; + var genericTypeSymbol = this.resolveAST(genericTypeAST.name, false, context).type; + + if (genericTypeSymbol.isError()) { + return genericTypeSymbol; + } + + if (!genericTypeSymbol.inResolution && !genericTypeSymbol.isResolved) { + this.resolveDeclaredSymbol(genericTypeSymbol, context); + } + + if (genericTypeSymbol.isAlias()) { + if (this.inClassExtendsHeritageClause(genericTypeAST) && !this.inTypeArgumentList(genericTypeAST)) { + genericTypeSymbol.setIsUsedAsValue(); + } + genericTypeSymbol = genericTypeSymbol.getExportAssignedTypeSymbol(); + } + + var typeParameters = genericTypeSymbol.getTypeParameters(); + if (typeParameters.length === 0) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Type_0_does_not_have_type_parameters, [genericTypeSymbol.toString()])); + return this.getNewErrorTypeSymbol(); + } + + var typeArgs = []; + + if (genericTypeAST.typeArgumentList && genericTypeAST.typeArgumentList.typeArguments.nonSeparatorCount()) { + for (var i = 0; i < genericTypeAST.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { + typeArgs[i] = this.resolveTypeReference(genericTypeAST.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + + if (typeArgs[i].isError()) { + typeArgs[i] = this.semanticInfoChain.anyTypeSymbol; + } + } + } + + if (typeArgs.length && typeArgs.length !== typeParameters.length) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Generic_type_0_requires_1_type_argument_s, [genericTypeSymbol.toString(), genericTypeSymbol.getTypeParameters().length])); + return this.getNewErrorTypeSymbol(); + } + + if (!genericTypeSymbol.isResolved) { + var typeDecls = genericTypeSymbol.getDeclarations(); + var childDecls = null; + + for (var i = 0; i < typeDecls.length; i++) { + childDecls = typeDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + } + + var specializedSymbol = this.createInstantiatedType(genericTypeSymbol, typeArgs); + + var upperBound = null; + + typeParameters = specializedSymbol.getTypeParameters(); + + var typeConstraintSubstitutionMap = []; + + var instantiatedSubstitutionMap = specializedSymbol.getTypeParameterArgumentMap(); + + for (var i = 0; i < typeParameters.length; i++) { + typeConstraintSubstitutionMap[typeParameters[i].pullSymbolID] = typeParameters[i]; + } + + for (var id in instantiatedSubstitutionMap) { + typeConstraintSubstitutionMap[id] = instantiatedSubstitutionMap[id]; + } + + for (var iArg = 0; (iArg < typeArgs.length) && (iArg < typeParameters.length); iArg++) { + var typeArg = typeArgs[iArg]; + var typeParameter = typeParameters[iArg]; + var typeConstraint = typeParameter.getConstraint(); + + typeConstraintSubstitutionMap[typeParameter.pullSymbolID] = typeArg; + + if (typeConstraint) { + if (typeConstraint.isTypeParameter()) { + for (var j = 0; j < typeParameters.length && j < typeArgs.length; j++) { + if (typeParameters[j] === typeConstraint) { + typeConstraint = typeArgs[j]; + } + } + } else if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeConstraintSubstitutionMap); + } + + if (typeArg.isTypeParameter()) { + upperBound = typeArg.getConstraint(); + + if (upperBound) { + typeArg = upperBound; + } + } + + if (typeArg.inResolution || (typeArg.isTypeReference() && typeArg.referencedTypeSymbol.inResolution)) { + return specializedSymbol; + } + + if (context.canTypeCheckAST(genericTypeAST)) { + this.typeCheckCallBacks.push(function (context) { + if (!_this.sourceIsAssignableToTarget(typeArg, typeConstraint, genericTypeAST, context)) { + var enclosingSymbol = _this.getEnclosingSymbolForAST(genericTypeAST); + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [typeArg.toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameter.toString(enclosingSymbol, true)])); + } + }); + } + } + } + + return specializedSymbol; + }; + + PullTypeResolver.prototype.resolveQualifiedName = function (dottedNameAST, context) { + if (this.inTypeQuery(dottedNameAST)) { + return this.resolveDottedNameExpression(dottedNameAST, dottedNameAST.left, dottedNameAST.right, context).type; + } + + var symbol = this.getSymbolForAST(dottedNameAST, context); + if (!symbol || this.canTypeCheckAST(dottedNameAST, context)) { + var canTypeCheck = this.canTypeCheckAST(dottedNameAST, context); + if (canTypeCheck) { + this.setTypeChecked(dottedNameAST, context); + } + + symbol = this.computeQualifiedName(dottedNameAST, context); + this.setSymbolForAST(dottedNameAST, symbol, context); + } + + this.resolveDeclaredSymbol(symbol, context); + + return symbol; + }; + + PullTypeResolver.prototype.isLastNameOfModuleNameModuleReference = function (ast) { + return ast.kind() === 11 /* IdentifierName */ && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast && ast.parent.parent && ast.parent.parent.kind() === 246 /* ModuleNameModuleReference */; + }; + + PullTypeResolver.prototype.computeQualifiedName = function (dottedNameAST, context) { + var rhsName = dottedNameAST.right.valueText(); + if (rhsName.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var enclosingDecl = this.getEnclosingDeclForAST(dottedNameAST); + var lhs = this.resolveAST(dottedNameAST.left, false, context); + + var lhsType = lhs.isAlias() ? lhs.getExportAssignedContainerSymbol() : lhs.type; + + if (this.inClassExtendsHeritageClause(dottedNameAST) && !this.inTypeArgumentList(dottedNameAST)) { + if (lhs.isAlias()) { + lhs.setIsUsedAsValue(); + } + } + + if (!lhsType) { + return this.getNewErrorTypeSymbol(); + } + + if (this.isAnyOrEquivalent(lhsType)) { + return lhsType; + } + + var onLeftOfDot = this.isLeftSideOfQualifiedName(dottedNameAST); + var isNameOfModule = dottedNameAST.parent.kind() === 130 /* ModuleDeclaration */ && dottedNameAST.parent.name === dottedNameAST; + + var memberKind = (onLeftOfDot || isNameOfModule) ? 164 /* SomeContainer */ : 58728795 /* SomeType */; + + var childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, lhsType); + + if (!childTypeSymbol && !isNameOfModule && this.isLastNameOfModuleNameModuleReference(dottedNameAST.right)) { + childTypeSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, lhsType); + } + + if (!childTypeSymbol && lhsType.isContainer()) { + var exportedContainer = lhsType.getExportAssignedContainerSymbol(); + + if (exportedContainer) { + childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, exportedContainer); + } + } + + if (!childTypeSymbol && enclosingDecl) { + var parentDecl = enclosingDecl; + + while (parentDecl) { + if (parentDecl.kind & 164 /* SomeContainer */) { + break; + } + + parentDecl = parentDecl.getParentDecl(); + } + + if (parentDecl) { + var enclosingSymbolType = parentDecl.getSymbol().type; + + if (enclosingSymbolType === lhsType) { + childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, lhsType); + } + } + } + + if (!childTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(dottedNameAST.right, TypeScript.DiagnosticCode.The_property_0_does_not_exist_on_value_of_type_1, [dottedNameAST.right.text(), lhsType.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + return this.getNewErrorTypeSymbol(rhsName); + } + + return childTypeSymbol; + }; + + PullTypeResolver.prototype.shouldContextuallyTypeAnyFunctionExpression = function (functionExpressionAST, typeParameters, parameters, returnTypeAnnotation, context) { + if (typeParameters && typeParameters.typeParameters.nonSeparatorCount() > 0) { + return false; + } + + if (returnTypeAnnotation) { + return false; + } + + if (parameters) { + for (var i = 0, n = parameters.length; i < n; i++) { + if (parameters.typeAt(i)) { + return false; + } + } + } + + var contextualFunctionTypeSymbol = context.getContextualType(); + + if (contextualFunctionTypeSymbol) { + this.resolveDeclaredSymbol(contextualFunctionTypeSymbol, context); + var callSignatures = contextualFunctionTypeSymbol.getCallSignatures(); + var exactlyOneCallSignature = callSignatures && callSignatures.length === 1; + if (!exactlyOneCallSignature) { + return false; + } + + var callSignatureIsGeneric = callSignatures[0].getTypeParameters().length > 0; + return !callSignatureIsGeneric; + } + + return false; + }; + + PullTypeResolver.prototype.resolveAnyFunctionExpression = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context) { + var funcDeclSymbol = null; + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + TypeScript.Debug.assert(functionDecl); + + if (functionDecl && functionDecl.hasSymbol()) { + funcDeclSymbol = functionDecl.getSymbol(); + if (funcDeclSymbol.isResolved || funcDeclSymbol.inResolution) { + return funcDeclSymbol; + } + } + + funcDeclSymbol = functionDecl.getSymbol(); + TypeScript.Debug.assert(funcDeclSymbol); + + var funcDeclType = funcDeclSymbol.type; + var signature = funcDeclType.getCallSignatures()[0]; + funcDeclSymbol.startResolving(); + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + var assigningFunctionSignature = null; + if (isContextuallyTyped && this.shouldContextuallyTypeAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, context)) { + assigningFunctionSignature = context.getContextualType().getCallSignatures()[0]; + } + + this.resolveAnyFunctionExpressionParameters(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context); + + if (returnTypeAnnotation) { + signature.returnType = this.resolveTypeReference(returnTypeAnnotation, context); + } else { + if (assigningFunctionSignature) { + var returnType = assigningFunctionSignature.returnType; + + if (returnType) { + context.propagateContextualType(returnType); + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, bodyExpression, signature, true, functionDecl, context); + context.popAnyContextualType(); + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + + if (this.compilationSettings.noImplicitAny()) { + var functionExpressionName = functionDecl.getFunctionExpressionName(); + + if (functionExpressionName != "") { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type, [functionExpressionName])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + } + } else { + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, bodyExpression, signature, false, functionDecl, context); + } + } + + context.setTypeInContext(funcDeclSymbol, funcDeclType); + funcDeclSymbol.setResolved(); + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context); + } + + return funcDeclSymbol; + }; + + PullTypeResolver.prototype.resolveAnyFunctionExpressionParameters = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context) { + if (!parameters) { + return; + } + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var contextParams = []; + + var assigningFunctionSignature = null; + if (isContextuallyTyped && this.shouldContextuallyTypeAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, context)) { + assigningFunctionSignature = context.getContextualType().getCallSignatures()[0]; + } + + if (assigningFunctionSignature) { + contextParams = assigningFunctionSignature.parameters; + } + + var contextualParametersCount = contextParams.length; + for (var i = 0, n = parameters.length; i < n; i++) { + var actualParameterIsVarArgParameter = (i === (n - 1)) && parameters.lastParameterIsRest(); + var correspondingContextualParameter = null; + var contextualParameterType = null; + + if (i < contextualParametersCount) { + correspondingContextualParameter = contextParams[i]; + } else if (contextualParametersCount && contextParams[contextualParametersCount - 1].isVarArg) { + correspondingContextualParameter = contextParams[contextualParametersCount - 1]; + } + + if (correspondingContextualParameter) { + if (correspondingContextualParameter.isVarArg === actualParameterIsVarArgParameter) { + contextualParameterType = correspondingContextualParameter.type; + } else if (correspondingContextualParameter.isVarArg) { + contextualParameterType = correspondingContextualParameter.type.getElementType(); + } + } + + this.resolveFunctionExpressionParameter(parameters.astAt(i), parameters.identifierAt(i), parameters.typeAt(i), parameters.initializerAt(i), contextualParameterType, functionDecl, context); + } + }; + + PullTypeResolver.prototype.typeCheckSimpleArrowFunctionExpression = function (arrowFunction, isContextuallyTyped, context) { + return this.typeCheckAnyFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromIdentifier(arrowFunction.identifier), null, arrowFunction.block, arrowFunction.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckParenthesizedArrowFunctionExpression = function (arrowFunction, isContextuallyTyped, context) { + return this.typeCheckAnyFunctionExpression(arrowFunction, arrowFunction.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), TypeScript.ASTHelpers.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckAnyFunctionExpression = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcDeclSymbol = functionDecl.getSymbol(); + var funcDeclType = funcDeclSymbol.type; + var signature = funcDeclType.getCallSignatures()[0]; + var returnTypeSymbol = signature.returnType; + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + this.resolveAnyFunctionExpressionParameters(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context); + + context.pushNewContextualType(null); + if (block) { + this.resolveAST(block, false, context); + } else { + var bodyExpressionType = this.resolveReturnExpression(bodyExpression, functionDecl, context); + this.typeCheckReturnExpression(bodyExpression, bodyExpressionType, functionDecl, context); + } + + context.popAnyContextualType(); + + this.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement(functionDecl, returnTypeAnnotation, returnTypeSymbol, block, context); + + this.validateVariableDeclarationGroups(functionDecl, context); + + this.typeCheckCallBacks.push(function (context) { + _this.typeCheckFunctionOverloads(funcDeclAST, context); + }); + }; + + PullTypeResolver.prototype.resolveThisExpression = function (thisExpression, context) { + var enclosingDecl = this.getEnclosingDeclForAST(thisExpression); + var thisTypeSymbol = this.getContextualClassSymbolForEnclosingDecl(thisExpression, enclosingDecl) || this.semanticInfoChain.anyTypeSymbol; + + if (this.canTypeCheckAST(thisExpression, context)) { + this.typeCheckThisExpression(thisExpression, context, enclosingDecl); + } + + return thisTypeSymbol; + }; + + PullTypeResolver.prototype.inTypeArgumentList = function (ast) { + var previous = null; + var current = ast; + + while (current) { + switch (current.kind()) { + case 126 /* GenericType */: + var genericType = current; + if (genericType.typeArgumentList === previous) { + return true; + } + break; + + case 226 /* ArgumentList */: + var argumentList = current; + return argumentList.typeArgumentList === previous; + } + + previous = current; + current = current.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inClassExtendsHeritageClause = function (ast) { + while (ast) { + switch (ast.kind()) { + case 230 /* ExtendsHeritageClause */: + var heritageClause = ast; + + return heritageClause.parent.parent.kind() === 131 /* ClassDeclaration */; + + case 137 /* ConstructorDeclaration */: + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inTypeQuery = function (ast) { + while (ast) { + switch (ast.kind()) { + case 127 /* TypeQuery */: + return true; + case 129 /* FunctionDeclaration */: + case 213 /* InvocationExpression */: + case 137 /* ConstructorDeclaration */: + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inArgumentListOfSuperInvocation = function (ast) { + var previous = null; + var current = ast; + while (current) { + switch (current.kind()) { + case 213 /* InvocationExpression */: + var invocationExpression = current; + if (previous === invocationExpression.argumentList && invocationExpression.expression.kind() === 50 /* SuperKeyword */) { + return true; + } + break; + + case 137 /* ConstructorDeclaration */: + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + previous = current; + current = current.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inConstructorParameterList = function (ast) { + var previous = null; + var current = ast; + while (current) { + switch (current.kind()) { + case 142 /* CallSignature */: + var callSignature = current; + if (previous === callSignature.parameterList && callSignature.parent.kind() === 137 /* ConstructorDeclaration */) { + return true; + } + + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + previous = current; + current = current.parent; + } + + return false; + }; + PullTypeResolver.prototype.isFunctionAccessorOrNonArrowFunctionExpression = function (decl) { + if (decl.kind === 262144 /* GetAccessor */ || decl.kind === 524288 /* SetAccessor */) { + return true; + } + + return this.isFunctionOrNonArrowFunctionExpression(decl); + }; + + PullTypeResolver.prototype.isFunctionOrNonArrowFunctionExpression = function (decl) { + if (decl.kind === 16384 /* Function */) { + return true; + } else if (decl.kind === 131072 /* FunctionExpression */ && !TypeScript.hasFlag(decl.flags, 8192 /* ArrowFunction */)) { + return true; + } + + return false; + }; + + PullTypeResolver.prototype.typeCheckThisExpression = function (thisExpression, context, enclosingDecl) { + this.checkForThisCaptureInArrowFunction(thisExpression); + + if (this.inConstructorParameterList(thisExpression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_constructor_arguments)); + return; + } + + for (var currentDecl = enclosingDecl; currentDecl !== null; currentDecl = currentDecl.getParentDecl()) { + if (this.isFunctionAccessorOrNonArrowFunctionExpression(currentDecl)) { + return; + } else if (currentDecl.kind === 4 /* Container */ || currentDecl.kind === 32 /* DynamicModule */) { + if (currentDecl.getParentDecl() === null) { + return; + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_within_module_bodies)); + return; + } + } else if (currentDecl.kind === 64 /* Enum */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_current_location)); + return; + } else if (currentDecl.kind === 32768 /* ConstructorMethod */) { + if (this.inArgumentListOfSuperInvocation(thisExpression) && this.superCallMustBeFirstStatementInConstructor(currentDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_current_location)); + } + + return; + } else if (currentDecl.kind === 8 /* Class */) { + if (this.inStaticMemberVariableDeclaration(thisExpression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_static_initializers_in_a_class_body)); + } + + return; + } + } + }; + + PullTypeResolver.prototype.getContextualClassSymbolForEnclosingDecl = function (ast, enclosingDecl) { + var declPath = enclosingDecl.getParentPath(); + + if (declPath.length) { + var isStaticContext = false; + + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.kind; + var declFlags = decl.flags; + + if (declFlags & 16 /* Static */) { + isStaticContext = true; + } else if (declKind === 131072 /* FunctionExpression */ && !TypeScript.hasFlag(declFlags, 8192 /* ArrowFunction */)) { + return null; + } else if (declKind === 16384 /* Function */) { + return null; + } else if (declKind === 8 /* Class */) { + if (this.inStaticMemberVariableDeclaration(ast)) { + return this.getNewErrorTypeSymbol(); + } else { + var classSymbol = decl.getSymbol(); + if (isStaticContext) { + var constructorSymbol = classSymbol.getConstructorMethod(); + return constructorSymbol.type; + } else { + return classSymbol; + } + } + } + } + } + + return null; + }; + + PullTypeResolver.prototype.inStaticMemberVariableDeclaration = function (ast) { + while (ast) { + if (ast.kind() === 136 /* MemberVariableDeclaration */ && TypeScript.hasModifier(ast.modifiers, 16 /* Static */)) { + return true; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.resolveSuperExpression = function (ast, context) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + var superType = this.semanticInfoChain.anyTypeSymbol; + + var classSymbol = this.getContextualClassSymbolForEnclosingDecl(ast, enclosingDecl); + + if (classSymbol) { + this.resolveDeclaredSymbol(classSymbol, context); + + var parents = classSymbol.getExtendedTypes(); + + if (parents.length) { + superType = parents[0]; + } + } + + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckSuperExpression(ast, context, enclosingDecl); + } + + return superType; + }; + + PullTypeResolver.prototype.typeCheckSuperExpression = function (ast, context, enclosingDecl) { + this.setTypeChecked(ast, context); + + this.checkForThisCaptureInArrowFunction(ast); + + var isSuperCall = ast.parent.kind() === 213 /* InvocationExpression */; + var isSuperPropertyAccess = ast.parent.kind() === 212 /* MemberAccessExpression */; + TypeScript.Debug.assert(isSuperCall || isSuperPropertyAccess); + + if (isSuperPropertyAccess) { + for (var currentDecl = enclosingDecl; currentDecl !== null; currentDecl = currentDecl.getParentDecl()) { + if (this.isFunctionOrNonArrowFunctionExpression(currentDecl)) { + break; + } else if (currentDecl.kind === 8 /* Class */) { + if (!this.enclosingClassIsDerived(currentDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_non_derived_classes)); + return; + } else if (this.inConstructorParameterList(ast)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_constructor_arguments)); + return; + } else if (this.inStaticMemberVariableDeclaration(ast)) { + break; + } + + return; + } + } + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class)); + return; + } else { + if (enclosingDecl.kind === 32768 /* ConstructorMethod */) { + var classDecl = enclosingDecl.getParentDecl(); + + if (!this.enclosingClassIsDerived(classDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_non_derived_classes)); + return; + } else if (this.inConstructorParameterList(ast)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_constructor_arguments)); + return; + } + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors)); + } + } + }; + + PullTypeResolver.prototype.resolveSimplePropertyAssignment = function (propertyAssignment, isContextuallyTyped, context) { + return this.resolveAST(propertyAssignment.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveFunctionPropertyAssignment = function (funcProp, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcProp), funcProp.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckFunctionPropertyAssignment = function (funcProp, isContextuallyTyped, context) { + this.typeCheckAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcProp), funcProp.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveObjectLiteralExpression = function (expressionAST, isContextuallyTyped, context, additionalResults) { + var symbol = this.getSymbolForAST(expressionAST, context); + var hasResolvedSymbol = symbol && symbol.isResolved; + + if (!hasResolvedSymbol || additionalResults || this.canTypeCheckAST(expressionAST, context)) { + if (this.canTypeCheckAST(expressionAST, context)) { + this.setTypeChecked(expressionAST, context); + } + symbol = this.computeObjectLiteralExpression(expressionAST, isContextuallyTyped, context, additionalResults); + this.setSymbolForAST(expressionAST, symbol, context); + } + + return symbol; + }; + + PullTypeResolver.prototype.bindObjectLiteralMembers = function (objectLiteralDeclaration, objectLiteralTypeSymbol, objectLiteralMembers, isUsingExistingSymbol, pullTypeContext) { + var boundMemberSymbols = []; + var memberSymbol; + for (var i = 0, len = objectLiteralMembers.nonSeparatorCount(); i < len; i++) { + var propertyAssignment = objectLiteralMembers.nonSeparatorAt(i); + + var id = this.getPropertyAssignmentName(propertyAssignment); + var assignmentText = getPropertyAssignmentNameTextFromIdentifier(id); + + var isAccessor = propertyAssignment.kind() === 139 /* GetAccessor */ || propertyAssignment.kind() === 140 /* SetAccessor */; + var decl = this.semanticInfoChain.getDeclForAST(propertyAssignment); + TypeScript.Debug.assert(decl); + + if (propertyAssignment.kind() === 240 /* SimplePropertyAssignment */) { + if (!isUsingExistingSymbol) { + memberSymbol = new TypeScript.PullSymbol(assignmentText.memberName, 4096 /* Property */); + memberSymbol.addDeclaration(decl); + decl.setSymbol(memberSymbol); + } else { + memberSymbol = decl.getSymbol(); + } + } else if (propertyAssignment.kind() === 241 /* FunctionPropertyAssignment */) { + memberSymbol = decl.getSymbol(); + } else { + TypeScript.Debug.assert(isAccessor); + memberSymbol = decl.getSymbol(); + } + + if (!isUsingExistingSymbol && !isAccessor) { + var existingMember = objectLiteralTypeSymbol.findMember(memberSymbol.name, true); + if (existingMember) { + pullTypeContext.postDiagnostic(this.semanticInfoChain.duplicateIdentifierDiagnosticFromAST(propertyAssignment, assignmentText.actualText, existingMember.getDeclarations()[0].ast())); + } + + objectLiteralTypeSymbol.addMember(memberSymbol); + } + + boundMemberSymbols.push(memberSymbol); + } + + return boundMemberSymbols; + }; + + PullTypeResolver.prototype.resolveObjectLiteralMembers = function (objectLiteralDeclaration, objectLiteralTypeSymbol, objectLiteralContextualType, objectLiteralMembers, stringIndexerSignature, numericIndexerSignature, allMemberTypes, allNumericMemberTypes, boundMemberSymbols, isUsingExistingSymbol, pullTypeContext, additionalResults) { + for (var i = 0, len = objectLiteralMembers.nonSeparatorCount(); i < len; i++) { + var propertyAssignment = objectLiteralMembers.nonSeparatorAt(i); + + var acceptedContextualType = false; + var assigningSymbol = null; + + var id = this.getPropertyAssignmentName(propertyAssignment); + var memberSymbol = boundMemberSymbols[i]; + var contextualMemberType = null; + + if (objectLiteralContextualType) { + assigningSymbol = this.getNamedPropertySymbol(memberSymbol.name, 68147712 /* SomeValue */, objectLiteralContextualType); + + if (!assigningSymbol) { + if (numericIndexerSignature && TypeScript.PullHelpers.isNameNumeric(memberSymbol.name)) { + assigningSymbol = numericIndexerSignature; + } else if (stringIndexerSignature) { + assigningSymbol = stringIndexerSignature; + } + } + + if (assigningSymbol) { + this.resolveDeclaredSymbol(assigningSymbol, pullTypeContext); + + contextualMemberType = assigningSymbol.kind === 4194304 /* IndexSignature */ ? assigningSymbol.returnType : assigningSymbol.type; + pullTypeContext.propagateContextualType(contextualMemberType); + + acceptedContextualType = true; + + if (additionalResults) { + additionalResults.membersContextTypeSymbols[i] = contextualMemberType; + } + } + } + + var memberSymbolType = this.resolveAST(propertyAssignment, contextualMemberType !== null, pullTypeContext).type; + + if (memberSymbolType) { + if (memberSymbolType.isGeneric()) { + objectLiteralTypeSymbol.setHasGenericMember(); + } + + if (stringIndexerSignature) { + allMemberTypes.push(memberSymbolType); + } + if (numericIndexerSignature && TypeScript.PullHelpers.isNameNumeric(memberSymbol.name)) { + allNumericMemberTypes.push(memberSymbolType); + } + } + + if (acceptedContextualType) { + pullTypeContext.popAnyContextualType(); + } + + var isAccessor = propertyAssignment.kind() === 140 /* SetAccessor */ || propertyAssignment.kind() === 139 /* GetAccessor */; + if (!memberSymbol.isResolved) { + if (isAccessor) { + this.setSymbolForAST(id, memberSymbolType, pullTypeContext); + } else { + pullTypeContext.setTypeInContext(memberSymbol, memberSymbolType); + memberSymbol.setResolved(); + + this.setSymbolForAST(id, memberSymbol, pullTypeContext); + } + } + } + }; + + PullTypeResolver.prototype.computeObjectLiteralExpression = function (objectLitAST, isContextuallyTyped, context, additionalResults) { + var objectLitDecl = this.semanticInfoChain.getDeclForAST(objectLitAST); + TypeScript.Debug.assert(objectLitDecl); + + var typeSymbol = this.getSymbolForAST(objectLitAST, context); + var isUsingExistingSymbol = !!typeSymbol; + + if (!typeSymbol) { + typeSymbol = new TypeScript.PullTypeSymbol("", 256 /* ObjectLiteral */); + typeSymbol.addDeclaration(objectLitDecl); + this.setSymbolForAST(objectLitAST, typeSymbol, context); + objectLitDecl.setSymbol(typeSymbol); + } + + var propertyAssignments = objectLitAST.propertyAssignments; + var contextualType = null; + + if (isContextuallyTyped) { + contextualType = context.getContextualType(); + this.resolveDeclaredSymbol(contextualType, context); + } + + var stringIndexerSignature = null; + var numericIndexerSignature = null; + var allMemberTypes = null; + var allNumericMemberTypes = null; + + if (contextualType) { + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(contextualType, context); + + stringIndexerSignature = indexSignatures.stringSignature; + numericIndexerSignature = indexSignatures.numericSignature; + + var inInferentialTyping = context.isInferentiallyTyping(); + if (stringIndexerSignature) { + allMemberTypes = inInferentialTyping ? [] : [stringIndexerSignature.returnType]; + } + + if (numericIndexerSignature) { + allNumericMemberTypes = inInferentialTyping ? [] : [numericIndexerSignature.returnType]; + } + } + + if (propertyAssignments) { + if (additionalResults) { + additionalResults.membersContextTypeSymbols = []; + } + + var boundMemberSymbols = this.bindObjectLiteralMembers(objectLitDecl, typeSymbol, propertyAssignments, isUsingExistingSymbol, context); + + this.resolveObjectLiteralMembers(objectLitDecl, typeSymbol, contextualType, propertyAssignments, stringIndexerSignature, numericIndexerSignature, allMemberTypes, allNumericMemberTypes, boundMemberSymbols, isUsingExistingSymbol, context, additionalResults); + + if (!isUsingExistingSymbol) { + this.stampObjectLiteralWithIndexSignature(typeSymbol, allMemberTypes, stringIndexerSignature, context); + this.stampObjectLiteralWithIndexSignature(typeSymbol, allNumericMemberTypes, numericIndexerSignature, context); + } + } + + typeSymbol.setResolved(); + return typeSymbol; + }; + + PullTypeResolver.prototype.getPropertyAssignmentName = function (propertyAssignment) { + if (propertyAssignment.kind() === 240 /* SimplePropertyAssignment */) { + return propertyAssignment.propertyName; + } else if (propertyAssignment.kind() === 241 /* FunctionPropertyAssignment */) { + return propertyAssignment.propertyName; + } else if (propertyAssignment.kind() === 139 /* GetAccessor */) { + return propertyAssignment.propertyName; + } else if (propertyAssignment.kind() === 140 /* SetAccessor */) { + return propertyAssignment.propertyName; + } else { + TypeScript.Debug.assert(false); + } + }; + + PullTypeResolver.prototype.stampObjectLiteralWithIndexSignature = function (objectLiteralSymbol, indexerTypeCandidates, contextualIndexSignature, context) { + if (contextualIndexSignature) { + var typeCollection = { + getLength: function () { + return indexerTypeCandidates.length; + }, + getTypeAtIndex: function (index) { + return indexerTypeCandidates[index]; + } + }; + var decl = objectLiteralSymbol.getDeclarations()[0]; + var indexerReturnType = this.findBestCommonType(typeCollection, context).widenedType(this, null, context); + if (indexerReturnType === contextualIndexSignature.returnType) { + objectLiteralSymbol.addIndexSignature(contextualIndexSignature); + } else { + this.semanticInfoChain.addSyntheticIndexSignature(decl, objectLiteralSymbol, this.getASTForDecl(decl), contextualIndexSignature.parameters[0].name, contextualIndexSignature.parameters[0].type, indexerReturnType); + } + } + }; + + PullTypeResolver.prototype.resolveArrayLiteralExpression = function (arrayLit, isContextuallyTyped, context) { + var symbol = this.getSymbolForAST(arrayLit, context); + if (!symbol || this.canTypeCheckAST(arrayLit, context)) { + if (this.canTypeCheckAST(arrayLit, context)) { + this.setTypeChecked(arrayLit, context); + } + symbol = this.computeArrayLiteralExpressionSymbol(arrayLit, isContextuallyTyped, context); + this.setSymbolForAST(arrayLit, symbol, context); + } + + return symbol; + }; + + PullTypeResolver.prototype.computeArrayLiteralExpressionSymbol = function (arrayLit, isContextuallyTyped, context) { + var elements = arrayLit.expressions; + var elementType = null; + var elementTypes = []; + var comparisonInfo = new TypeComparisonInfo(); + var contextualElementType = null; + comparisonInfo.onlyCaptureFirstError = true; + + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + + this.resolveDeclaredSymbol(contextualType, context); + + if (contextualType) { + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(contextualType, context); + if (indexSignatures.numericSignature) { + contextualElementType = indexSignatures.numericSignature.returnType; + } + } + } + + if (elements) { + if (contextualElementType) { + context.propagateContextualType(contextualElementType); + } + + for (var i = 0, n = elements.nonSeparatorCount(); i < n; i++) { + elementTypes.push(this.resolveAST(elements.nonSeparatorAt(i), contextualElementType !== null, context).type); + } + + if (contextualElementType) { + context.popAnyContextualType(); + } + } + + if (elementTypes.length) { + elementType = elementTypes[0]; + } + var collection; + + if (contextualElementType && !context.isInferentiallyTyping()) { + if (!elementType) { + elementType = contextualElementType; + } + + collection = { + getLength: function () { + return elements.nonSeparatorCount() + 1; + }, + getTypeAtIndex: function (index) { + return index === 0 ? contextualElementType : elementTypes[index - 1]; + } + }; + } else { + collection = { + getLength: function () { + return elements.nonSeparatorCount(); + }, + getTypeAtIndex: function (index) { + return elementTypes[index]; + } + }; + } + + elementType = elementType ? this.findBestCommonType(collection, context, comparisonInfo) : elementType; + + if (!elementType) { + elementType = this.semanticInfoChain.undefinedTypeSymbol; + } + + return this.getArrayType(elementType); + }; + + PullTypeResolver.prototype.resolveElementAccessExpression = function (callEx, context) { + var symbolAndDiagnostic = this.computeElementAccessExpressionSymbolAndDiagnostic(callEx, context); + + if (this.canTypeCheckAST(callEx, context)) { + this.typeCheckElementAccessExpression(callEx, context, symbolAndDiagnostic); + } + + return symbolAndDiagnostic.symbol; + }; + + PullTypeResolver.prototype.typeCheckElementAccessExpression = function (callEx, context, symbolAndDiagnostic) { + this.setTypeChecked(callEx, context); + context.postDiagnostic(symbolAndDiagnostic.diagnostic); + }; + + PullTypeResolver.prototype.computeElementAccessExpressionSymbolAndDiagnostic = function (callEx, context) { + var targetSymbol = this.resolveAST(callEx.expression, false, context); + var indexType = this.resolveAST(callEx.argumentExpression, false, context).type; + + var targetTypeSymbol = targetSymbol.type; + + targetTypeSymbol = this.getApparentType(targetTypeSymbol); + + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + return { symbol: targetTypeSymbol }; + } + + var elementType = targetTypeSymbol.getElementType(); + + var isNumberIndex = indexType === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(indexType); + + if (elementType && isNumberIndex) { + return { symbol: elementType }; + } + + if (callEx.argumentExpression.kind() === 14 /* StringLiteral */ || callEx.argumentExpression.kind() === 13 /* NumericLiteral */) { + var memberName = callEx.argumentExpression.kind() === 14 /* StringLiteral */ ? TypeScript.stripStartAndEndQuotes(callEx.argumentExpression.text()) : callEx.argumentExpression.valueText(); + + var member = this._getNamedPropertySymbolOfAugmentedType(memberName, targetTypeSymbol); + + if (member) { + this.resolveDeclaredSymbol(member, context); + + return { symbol: member.type }; + } + } + + var signatures = this.getBothKindsOfIndexSignaturesIncludingAugmentedType(targetTypeSymbol, context); + + var stringSignature = signatures.stringSignature; + var numberSignature = signatures.numericSignature; + + if (numberSignature && (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol)) { + return { symbol: numberSignature.returnType || this.semanticInfoChain.anyTypeSymbol }; + } else if (stringSignature && (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol)) { + return { symbol: stringSignature.returnType || this.semanticInfoChain.anyTypeSymbol }; + } else if (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol) { + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(callEx.argumentExpression, TypeScript.DiagnosticCode.Index_signature_of_object_type_implicitly_has_an_any_type)); + } + return { symbol: this.semanticInfoChain.anyTypeSymbol }; + } else { + return { + symbol: this.getNewErrorTypeSymbol(), + diagnostic: this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.Value_of_type_0_is_not_indexable_by_type_1, [targetTypeSymbol.toString(), indexType.toString()]) + }; + } + }; + + PullTypeResolver.prototype.getBothKindsOfIndexSignaturesIncludingAugmentedType = function (enclosingType, context) { + return this._getBothKindsOfIndexSignatures(enclosingType, context, true); + }; + + PullTypeResolver.prototype.getBothKindsOfIndexSignaturesExcludingAugmentedType = function (enclosingType, context) { + return this._getBothKindsOfIndexSignatures(enclosingType, context, false); + }; + + PullTypeResolver.prototype._getBothKindsOfIndexSignatures = function (enclosingType, context, includeAugmentedType) { + var signatures = includeAugmentedType ? enclosingType.getIndexSignaturesOfAugmentedType(this, this.cachedFunctionInterfaceType(), this.cachedObjectInterfaceType()) : enclosingType.getIndexSignatures(); + + var stringSignature = null; + var numberSignature = null; + var signature = null; + var paramSymbols; + var paramType; + + for (var i = 0; i < signatures.length; i++) { + if (stringSignature && numberSignature) { + break; + } + + signature = signatures[i]; + if (!signature.isResolved) { + this.resolveDeclaredSymbol(signature, context); + } + + paramSymbols = signature.parameters; + + if (paramSymbols.length) { + paramType = paramSymbols[0].type; + + if (!stringSignature && paramType === this.semanticInfoChain.stringTypeSymbol) { + stringSignature = signature; + continue; + } else if (!numberSignature && paramType === this.semanticInfoChain.numberTypeSymbol) { + numberSignature = signature; + continue; + } + } + } + + return { + numericSignature: numberSignature, + stringSignature: stringSignature + }; + }; + + PullTypeResolver.prototype._addUnhiddenSignaturesFromBaseType = function (derivedTypeSignatures, baseTypeSignatures, signaturesBeingAggregated) { + var _this = this; + if (!derivedTypeSignatures) { + signaturesBeingAggregated.push.apply(signaturesBeingAggregated, baseTypeSignatures); + return; + } + + var context = new TypeScript.PullTypeResolutionContext(this); + for (var i = 0; i < baseTypeSignatures.length; i++) { + var baseSignature = baseTypeSignatures[i]; + + var signatureIsHidden = TypeScript.ArrayUtilities.any(derivedTypeSignatures, function (sig) { + return _this.signaturesAreIdenticalWithNewEnclosingTypes(baseSignature, sig, context, false); + }); + + if (!signatureIsHidden) { + signaturesBeingAggregated.push(baseSignature); + } + } + }; + + PullTypeResolver.prototype.resolveBinaryAdditionOperation = function (binaryExpression, context) { + var lhsExpression = this.resolveAST(binaryExpression.left, false, context); + var lhsType = lhsExpression.type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + if (TypeScript.PullHelpers.symbolIsEnum(lhsType)) { + lhsType = this.semanticInfoChain.numberTypeSymbol; + } + + if (TypeScript.PullHelpers.symbolIsEnum(rhsType)) { + rhsType = this.semanticInfoChain.numberTypeSymbol; + } + + var isLhsTypeNullOrUndefined = lhsType === this.semanticInfoChain.nullTypeSymbol || lhsType === this.semanticInfoChain.undefinedTypeSymbol; + var isRhsTypeNullOrUndefined = rhsType === this.semanticInfoChain.nullTypeSymbol || rhsType === this.semanticInfoChain.undefinedTypeSymbol; + + if (isLhsTypeNullOrUndefined) { + if (isRhsTypeNullOrUndefined) { + lhsType = rhsType = this.semanticInfoChain.anyTypeSymbol; + } else { + lhsType = rhsType; + } + } else if (isRhsTypeNullOrUndefined) { + rhsType = lhsType; + } + + var exprType = null; + + if (lhsType === this.semanticInfoChain.stringTypeSymbol || rhsType === this.semanticInfoChain.stringTypeSymbol) { + exprType = this.semanticInfoChain.stringTypeSymbol; + } else if (this.isAnyOrEquivalent(lhsType) || this.isAnyOrEquivalent(rhsType)) { + exprType = this.semanticInfoChain.anyTypeSymbol; + } else if (rhsType === this.semanticInfoChain.numberTypeSymbol && lhsType === this.semanticInfoChain.numberTypeSymbol) { + exprType = this.semanticInfoChain.numberTypeSymbol; + } + + if (this.canTypeCheckAST(binaryExpression, context)) { + this.setTypeChecked(binaryExpression, context); + + if (exprType) { + if (binaryExpression.kind() === 175 /* AddAssignmentExpression */) { + if (!this.isReference(binaryExpression.left, lhsExpression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_left_hand_side_of_assignment_expression)); + } + + this.checkAssignability(binaryExpression.left, exprType, lhsType, context); + } + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_expression_types_not_known_to_support_the_addition_operator)); + } + } + + if (!exprType) { + exprType = this.semanticInfoChain.anyTypeSymbol; + } + + return exprType; + }; + + PullTypeResolver.prototype.bestCommonTypeOfTwoTypes = function (type1, type2, context) { + return this.findBestCommonType({ + getLength: function () { + return 2; + }, + getTypeAtIndex: function (index) { + switch (index) { + case 0: + return type1; + case 1: + return type2; + } + } + }, context); + }; + + PullTypeResolver.prototype.bestCommonTypeOfThreeTypes = function (type1, type2, type3, context) { + return this.findBestCommonType({ + getLength: function () { + return 3; + }, + getTypeAtIndex: function (index) { + switch (index) { + case 0: + return type1; + case 1: + return type2; + case 2: + return type3; + } + } + }, context); + }; + + PullTypeResolver.prototype.resolveLogicalOrExpression = function (binex, isContextuallyTyped, context) { + if (this.canTypeCheckAST(binex, context)) { + this.setTypeChecked(binex, context); + } + + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + var leftType = this.resolveAST(binex.left, isContextuallyTyped, context).type; + var rightType = this.resolveAST(binex.right, isContextuallyTyped, context).type; + + return context.isInferentiallyTyping() ? this.bestCommonTypeOfTwoTypes(leftType, rightType, context) : this.bestCommonTypeOfThreeTypes(contextualType, leftType, rightType, context); + } else { + var leftType = this.resolveAST(binex.left, false, context).type; + + context.pushNewContextualType(leftType); + var rightType = this.resolveAST(binex.right, true, context).type; + context.popAnyContextualType(); + + return this.bestCommonTypeOfTwoTypes(leftType, rightType, context); + } + }; + + PullTypeResolver.prototype.resolveLogicalAndExpression = function (binex, context) { + if (this.canTypeCheckAST(binex, context)) { + this.setTypeChecked(binex, context); + + this.resolveAST(binex.left, false, context); + } + + return this.resolveAST(binex.right, false, context).type; + }; + + PullTypeResolver.prototype.computeTypeOfConditionalExpression = function (leftType, rightType, isContextuallyTyped, context) { + if (isContextuallyTyped && !context.isInferentiallyTyping()) { + var contextualType = context.getContextualType(); + return this.bestCommonTypeOfThreeTypes(contextualType, leftType, rightType, context); + } else { + return this.bestCommonTypeOfTwoTypes(leftType, rightType, context); + } + }; + + PullTypeResolver.prototype.resolveConditionalExpression = function (trinex, isContextuallyTyped, context) { + var leftType = this.resolveAST(trinex.whenTrue, isContextuallyTyped, context).type; + var rightType = this.resolveAST(trinex.whenFalse, isContextuallyTyped, context).type; + + var expressionType = this.computeTypeOfConditionalExpression(leftType, rightType, isContextuallyTyped, context); + + var conditionalTypesAreValid = this.conditionExpressionTypesAreValid(leftType, rightType, expressionType, isContextuallyTyped, context); + + if (this.canTypeCheckAST(trinex, context)) { + this.setTypeChecked(trinex, context); + this.resolveAST(trinex.condition, false, context); + + if (!this.conditionExpressionTypesAreValid(leftType, rightType, expressionType, isContextuallyTyped, context)) { + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(trinex, TypeScript.DiagnosticCode.Type_of_conditional_0_must_be_identical_to_1_2_or_3, [expressionType.toString(), leftType.toString(), rightType.toString(), contextualType.toString()])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(trinex, TypeScript.DiagnosticCode.Type_of_conditional_0_must_be_identical_to_1_or_2, [expressionType.toString(), leftType.toString(), rightType.toString()])); + } + } + } + + if (!conditionalTypesAreValid) { + return this.getNewErrorTypeSymbol(); + } + + return expressionType; + }; + + PullTypeResolver.prototype.conditionExpressionTypesAreValid = function (leftType, rightType, expressionType, isContextuallyTyped, context) { + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + if (this.typesAreIdentical(expressionType, leftType, context) || this.typesAreIdentical(expressionType, rightType, context) || this.typesAreIdentical(expressionType, contextualType, context)) { + return true; + } + } else { + if (this.typesAreIdentical(expressionType, leftType, context) || this.typesAreIdentical(expressionType, rightType, context)) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.resolveParenthesizedExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + } + + return this.resolveAST(ast.expression, false, context); + }; + + PullTypeResolver.prototype.resolveExpressionStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveInvocationExpression = function (callEx, context, additionalResults) { + var symbol = this.getSymbolForAST(callEx, context); + + if (!symbol || !symbol.isResolved) { + if (!additionalResults) { + additionalResults = new PullAdditionalCallResolutionData(); + } + symbol = this.computeInvocationExpressionSymbol(callEx, context, additionalResults); + if (this.canTypeCheckAST(callEx, context)) { + this.setTypeChecked(callEx, context); + } + if (symbol !== this.semanticInfoChain.anyTypeSymbol) { + this.setSymbolForAST(callEx, symbol, context); + } + this.semanticInfoChain.setCallResolutionDataForAST(callEx, additionalResults); + } else { + if (this.canTypeCheckAST(callEx, context)) { + this.typeCheckInvocationExpression(callEx, context); + } + + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + if (additionalResults && (callResolutionData !== additionalResults)) { + additionalResults.actualParametersContextTypeSymbols = callResolutionData.actualParametersContextTypeSymbols; + additionalResults.candidateSignature = callResolutionData.candidateSignature; + additionalResults.resolvedSignatures = callResolutionData.resolvedSignatures; + additionalResults.targetSymbol = callResolutionData.targetSymbol; + } + } + + return symbol; + }; + + PullTypeResolver.prototype.typeCheckInvocationExpression = function (callEx, context) { + this.setTypeChecked(callEx, context); + var targetSymbol = this.resolveAST(callEx.expression, false, context); + + if (callEx.argumentList.arguments) { + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + + var len = callEx.argumentList.arguments.nonSeparatorCount(); + for (var i = 0; i < len; i++) { + var contextualType = callResolutionData.actualParametersContextTypeSymbols ? callResolutionData.actualParametersContextTypeSymbols[i] : null; + if (contextualType) { + context.pushNewContextualType(contextualType); + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + for (var i = 0; i < callResolutionData.diagnosticsFromOverloadResolution.length; i++) { + context.postDiagnostic(callResolutionData.diagnosticsFromOverloadResolution[i]); + } + }; + + PullTypeResolver.prototype.computeInvocationExpressionSymbol = function (callEx, context, additionalResults) { + var targetSymbol = this.resolveAST(callEx.expression, false, context); + var targetAST = this.getCallTargetErrorSpanAST(callEx); + + var targetTypeSymbol = targetSymbol.type; + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + this.resolveAST(callEx.argumentList.arguments, false, context); + + if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { + if (targetTypeSymbol === this.semanticInfoChain.anyTypeSymbol) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Untyped_function_calls_may_not_accept_type_arguments), additionalResults, context); + return this.getNewErrorTypeSymbol(); + } + } + + return this.semanticInfoChain.anyTypeSymbol; + } + + var isSuperCall = false; + + if (callEx.expression.kind() === 50 /* SuperKeyword */) { + isSuperCall = true; + + if (targetTypeSymbol.isClass()) { + targetSymbol = targetTypeSymbol.getConstructorMethod(); + this.resolveDeclaredSymbol(targetSymbol, context); + targetTypeSymbol = targetSymbol.type; + } else { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Calls_to_super_are_only_valid_inside_a_class), additionalResults, context); + this.resolveAST(callEx.argumentList.arguments, false, context); + + return this.getNewErrorTypeSymbol(); + } + } + + var signatures = isSuperCall ? targetTypeSymbol.getConstructSignatures() : targetTypeSymbol.getCallSignatures(); + + if (!signatures.length && (targetTypeSymbol.kind === 33554432 /* ConstructorType */)) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, [targetTypeSymbol.toString()]), additionalResults, context); + } + + var explicitTypeArgs = null; + var couldNotFindGenericOverload = false; + var couldNotAssignToConstraint; + var constraintDiagnostic = null; + var typeArgumentCountDiagnostic = null; + var diagnostics = []; + + if (callEx.argumentList.typeArgumentList) { + explicitTypeArgs = []; + + if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { + for (var i = 0; i < callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { + explicitTypeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + } + } + } + + var triedToInferTypeArgs = false; + + var resolvedSignatures = []; + var inferredOrExplicitTypeArgs; + var specializedSignature; + var typeParameters; + var typeConstraint = null; + var beforeResolutionSignatures = signatures; + var targetTypeReplacementMap = targetTypeSymbol.getTypeParameterArgumentMap(); + + for (var i = 0; i < signatures.length; i++) { + typeParameters = signatures[i].getTypeParameters(); + couldNotAssignToConstraint = false; + + if (signatures[i].isGeneric() && typeParameters.length) { + if (isSuperCall && targetTypeSymbol.isGeneric() && !callEx.argumentList.typeArgumentList) { + explicitTypeArgs = signatures[i].returnType.getTypeArguments(); + } + + if (explicitTypeArgs) { + if (explicitTypeArgs.length === typeParameters.length) { + inferredOrExplicitTypeArgs = explicitTypeArgs; + } else { + typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, explicitTypeArgs.length]); + continue; + } + } else { + TypeScript.Debug.assert(callEx.argumentList); + var typeArgumentInferenceContext = new TypeScript.InvocationTypeArgumentInferenceContext(this, context, signatures[i], callEx.argumentList.arguments); + inferredOrExplicitTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); + triedToInferTypeArgs = true; + } + + TypeScript.Debug.assert(inferredOrExplicitTypeArgs && inferredOrExplicitTypeArgs.length == typeParameters.length); + + var mutableTypeReplacementMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(targetTypeReplacementMap ? targetTypeReplacementMap : []); + TypeScript.PullInstantiationHelpers.updateMutableTypeParameterArgumentMap(typeParameters, inferredOrExplicitTypeArgs, mutableTypeReplacementMap); + var typeReplacementMap = mutableTypeReplacementMap.typeParameterArgumentMap; + + if (explicitTypeArgs) { + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); + } + + if (!this.sourceIsAssignableToTarget(inferredOrExplicitTypeArgs[j], typeConstraint, targetAST, context, null, true)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); + constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredOrExplicitTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); + couldNotAssignToConstraint = true; + } + + if (couldNotAssignToConstraint) { + break; + } + } + } + } + + if (couldNotAssignToConstraint) { + continue; + } + + specializedSignature = this.instantiateSignature(signatures[i], typeReplacementMap); + + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; + } + } else { + if (!(callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount())) { + resolvedSignatures[resolvedSignatures.length] = signatures[i]; + } + } + } + + if (signatures.length && !resolvedSignatures.length) { + couldNotFindGenericOverload = true; + } + + signatures = resolvedSignatures; + + var errorCondition = null; + if (!signatures.length) { + additionalResults.targetSymbol = targetSymbol; + additionalResults.resolvedSignatures = beforeResolutionSignatures; + additionalResults.candidateSignature = beforeResolutionSignatures && beforeResolutionSignatures.length ? beforeResolutionSignatures[0] : null; + + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + + this.resolveAST(callEx.argumentList.arguments, false, context); + + if (!couldNotFindGenericOverload) { + if (this.cachedFunctionInterfaceType() && this.sourceIsAssignableToTarget(targetTypeSymbol, this.cachedFunctionInterfaceType(), targetAST, context)) { + if (callEx.argumentList.typeArgumentList) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Non_generic_functions_may_not_accept_type_arguments), additionalResults, context); + } + return this.semanticInfoChain.anyTypeSymbol; + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature), additionalResults, context); + } else if (constraintDiagnostic) { + this.postOverloadResolutionDiagnostics(constraintDiagnostic, additionalResults, context); + } else if (typeArgumentCountDiagnostic) { + this.postOverloadResolutionDiagnostics(typeArgumentCountDiagnostic, additionalResults, context); + } else { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.Could_not_select_overload_for_call_expression), additionalResults, context); + } + + return this.getNewErrorTypeSymbol(); + } + + var signature = this.resolveOverloads(callEx, signatures, callEx.argumentList.typeArgumentList !== null, context, diagnostics); + var useBeforeResolutionSignatures = signature == null; + + if (!signature) { + for (var i = 0; i < diagnostics.length; i++) { + this.postOverloadResolutionDiagnostics(diagnostics[i], additionalResults, context); + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Could_not_select_overload_for_call_expression), additionalResults, context); + + errorCondition = this.getNewErrorTypeSymbol(); + + if (!signatures.length) { + return errorCondition; + } + + signature = signatures[0]; + } + + var rootSignature = signature.getRootSymbol(); + if (!rootSignature.isGeneric() && callEx.argumentList.typeArgumentList) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Non_generic_functions_may_not_accept_type_arguments), additionalResults, context); + } else if (rootSignature.isGeneric() && callEx.argumentList.typeArgumentList && rootSignature.getTypeParameters() && (callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount() !== rootSignature.getTypeParameters().length)) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [rootSignature.getTypeParameters().length, callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()]), additionalResults, context); + } + + var returnType = isSuperCall ? this.semanticInfoChain.voidTypeSymbol : signature.returnType; + + var actualParametersContextTypeSymbols = []; + if (callEx.argumentList.arguments) { + var len = callEx.argumentList.arguments.nonSeparatorCount(); + var params = signature.parameters; + var contextualType = null; + var signatureDecl = signature.getDeclarations()[0]; + + for (var i = 0; i < len; i++) { + if (params.length) { + if (i < params.length - 1 || (i < params.length && !signature.hasVarArgs)) { + this.resolveDeclaredSymbol(params[i], context); + contextualType = params[i].type; + } else if (signature.hasVarArgs) { + contextualType = params[params.length - 1].type; + if (contextualType.isArrayNamedTypeReference()) { + contextualType = contextualType.getElementType(); + } + } + } + + if (contextualType) { + context.pushNewContextualType(contextualType); + actualParametersContextTypeSymbols[i] = contextualType; + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + additionalResults.targetSymbol = targetSymbol; + if (useBeforeResolutionSignatures && beforeResolutionSignatures) { + additionalResults.resolvedSignatures = beforeResolutionSignatures; + additionalResults.candidateSignature = beforeResolutionSignatures[0]; + } else { + additionalResults.resolvedSignatures = signatures; + additionalResults.candidateSignature = signature; + } + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + + if (errorCondition) { + return errorCondition; + } + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return returnType; + }; + + PullTypeResolver.prototype.resolveObjectCreationExpression = function (callEx, context, additionalResults) { + var symbol = this.getSymbolForAST(callEx, context); + + if (!symbol || !symbol.isResolved) { + if (!additionalResults) { + additionalResults = new PullAdditionalCallResolutionData(); + } + symbol = this.computeObjectCreationExpressionSymbol(callEx, context, additionalResults); + if (this.canTypeCheckAST(callEx, context)) { + this.setTypeChecked(callEx, context); + } + this.setSymbolForAST(callEx, symbol, context); + this.semanticInfoChain.setCallResolutionDataForAST(callEx, additionalResults); + } else { + if (this.canTypeCheckAST(callEx, context)) { + this.typeCheckObjectCreationExpression(callEx, context); + } + + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + if (additionalResults && (callResolutionData !== additionalResults)) { + additionalResults.actualParametersContextTypeSymbols = callResolutionData.actualParametersContextTypeSymbols; + additionalResults.candidateSignature = callResolutionData.candidateSignature; + additionalResults.resolvedSignatures = callResolutionData.resolvedSignatures; + additionalResults.targetSymbol = callResolutionData.targetSymbol; + } + } + + return symbol; + }; + + PullTypeResolver.prototype.typeCheckObjectCreationExpression = function (callEx, context) { + this.setTypeChecked(callEx, context); + this.resolveAST(callEx.expression, false, context); + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + if (callEx.argumentList) { + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + var len = callEx.argumentList.arguments.nonSeparatorCount(); + + for (var i = 0; i < len; i++) { + var contextualType = callResolutionData.actualParametersContextTypeSymbols ? callResolutionData.actualParametersContextTypeSymbols[i] : null; + if (contextualType) { + context.pushNewContextualType(contextualType); + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + for (var i = 0; i < callResolutionData.diagnosticsFromOverloadResolution.length; i++) { + context.postDiagnostic(callResolutionData.diagnosticsFromOverloadResolution[i]); + } + }; + + PullTypeResolver.prototype.postOverloadResolutionDiagnostics = function (diagnostic, additionalResults, context) { + if (!context.inProvisionalResolution()) { + additionalResults.diagnosticsFromOverloadResolution.push(diagnostic); + } + context.postDiagnostic(diagnostic); + }; + + PullTypeResolver.prototype.computeObjectCreationExpressionSymbol = function (callEx, context, additionalResults) { + var _this = this; + var returnType = null; + + var targetSymbol = this.resolveAST(callEx.expression, false, context); + var targetTypeSymbol = targetSymbol.isType() ? targetSymbol : targetSymbol.type; + + var targetAST = this.getCallTargetErrorSpanAST(callEx); + + var constructSignatures = targetTypeSymbol.getConstructSignatures(); + + var explicitTypeArgs = null; + var usedCallSignaturesInstead = false; + var couldNotAssignToConstraint; + var constraintDiagnostic = null; + var typeArgumentCountDiagnostic = null; + var diagnostics = []; + + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + if (callEx.argumentList) { + this.resolveAST(callEx.argumentList.arguments, false, context); + } + + return targetTypeSymbol; + } + + if (!constructSignatures.length) { + constructSignatures = targetTypeSymbol.getCallSignatures(); + usedCallSignaturesInstead = true; + + if (this.compilationSettings.noImplicitAny()) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.new_expression_which_lacks_a_constructor_signature_implicitly_has_an_any_type), additionalResults, context); + } + } + + if (constructSignatures.length) { + if (callEx.argumentList && callEx.argumentList.typeArgumentList) { + explicitTypeArgs = []; + + if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { + for (var i = 0; i < callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { + explicitTypeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + } + } + } + + if (targetTypeSymbol.isGeneric()) { + var resolvedSignatures = []; + var inferredOrExplicitTypeArgs; + var specializedSignature; + var typeParameters; + var typeConstraint = null; + var triedToInferTypeArgs; + var targetTypeReplacementMap = targetTypeSymbol.getTypeParameterArgumentMap(); + + for (var i = 0; i < constructSignatures.length; i++) { + couldNotAssignToConstraint = false; + + if (constructSignatures[i].isGeneric()) { + typeParameters = constructSignatures[i].getTypeParameters(); + + if (explicitTypeArgs) { + if (explicitTypeArgs.length === typeParameters.length) { + inferredOrExplicitTypeArgs = explicitTypeArgs; + } else { + typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, explicitTypeArgs.length]); + continue; + } + } else if (callEx.argumentList) { + var typeArgumentInferenceContext = new TypeScript.InvocationTypeArgumentInferenceContext(this, context, constructSignatures[i], callEx.argumentList.arguments); + inferredOrExplicitTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); + triedToInferTypeArgs = true; + } else { + inferredOrExplicitTypeArgs = TypeScript.ArrayUtilities.select(typeParameters, function (typeParameter) { + return typeParameter.getDefaultConstraint(_this.semanticInfoChain); + }); + } + + TypeScript.Debug.assert(inferredOrExplicitTypeArgs && inferredOrExplicitTypeArgs.length == typeParameters.length); + + var mutableTypeReplacementMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(targetTypeReplacementMap ? targetTypeReplacementMap : []); + TypeScript.PullInstantiationHelpers.updateMutableTypeParameterArgumentMap(typeParameters, inferredOrExplicitTypeArgs, mutableTypeReplacementMap); + var typeReplacementMap = mutableTypeReplacementMap.typeParameterArgumentMap; + + if (explicitTypeArgs) { + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); + } + + if (!this.sourceIsAssignableToTarget(inferredOrExplicitTypeArgs[j], typeConstraint, targetAST, context, null, true)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); + constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredOrExplicitTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); + couldNotAssignToConstraint = true; + } + + if (couldNotAssignToConstraint) { + break; + } + } + } + } + + if (couldNotAssignToConstraint) { + continue; + } + + specializedSignature = this.instantiateSignature(constructSignatures[i], typeReplacementMap); + + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; + } + } else { + if (!(callEx.argumentList && callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount())) { + resolvedSignatures[resolvedSignatures.length] = constructSignatures[i]; + } + } + } + + constructSignatures = resolvedSignatures; + } + + var signature = this.resolveOverloads(callEx, constructSignatures, callEx.argumentList && callEx.argumentList.typeArgumentList !== null, context, diagnostics); + + additionalResults.targetSymbol = targetSymbol; + additionalResults.resolvedSignatures = constructSignatures; + additionalResults.candidateSignature = signature; + additionalResults.actualParametersContextTypeSymbols = []; + + if (!constructSignatures.length) { + if (constraintDiagnostic) { + this.postOverloadResolutionDiagnostics(constraintDiagnostic, additionalResults, context); + } else if (typeArgumentCountDiagnostic) { + this.postOverloadResolutionDiagnostics(typeArgumentCountDiagnostic, additionalResults, context); + } + + return this.getNewErrorTypeSymbol(); + } + + var errorCondition = null; + + if (!signature) { + for (var i = 0; i < diagnostics.length; i++) { + this.postOverloadResolutionDiagnostics(diagnostics[i], additionalResults, context); + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Could_not_select_overload_for_new_expression), additionalResults, context); + + errorCondition = this.getNewErrorTypeSymbol(); + + if (!constructSignatures.length) { + return errorCondition; + } + + signature = constructSignatures[0]; + } + + returnType = signature.returnType; + + if (returnType && !signature.isGeneric() && returnType.isGeneric() && !returnType.getIsSpecialized()) { + if (explicitTypeArgs && explicitTypeArgs.length) { + returnType = this.createInstantiatedType(returnType, explicitTypeArgs); + } else { + returnType = this.instantiateTypeToAny(returnType, context); + } + } + + if (usedCallSignaturesInstead) { + if (returnType !== this.semanticInfoChain.voidTypeSymbol) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Call_signatures_used_in_a_new_expression_must_have_a_void_return_type), additionalResults, context); + + return this.getNewErrorTypeSymbol(); + } else { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + } + + if (!returnType) { + returnType = signature.returnType; + + if (!returnType) { + returnType = targetTypeSymbol; + } + } + + var actualParametersContextTypeSymbols = []; + if (callEx.argumentList && callEx.argumentList.arguments) { + var len = callEx.argumentList.arguments.nonSeparatorCount(); + var params = signature.parameters; + var contextualType = null; + var signatureDecl = signature.getDeclarations()[0]; + + for (var i = 0; i < len; i++) { + if (params.length) { + if (i < params.length - 1 || (i < params.length && !signature.hasVarArgs)) { + this.resolveDeclaredSymbol(params[i], context); + contextualType = params[i].type; + } else if (signature.hasVarArgs) { + contextualType = params[params.length - 1].type; + if (contextualType.isArrayNamedTypeReference()) { + contextualType = contextualType.getElementType(); + } + } + } + + if (contextualType) { + context.pushNewContextualType(contextualType); + actualParametersContextTypeSymbols[i] = contextualType; + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + additionalResults.targetSymbol = targetSymbol; + additionalResults.resolvedSignatures = constructSignatures; + additionalResults.candidateSignature = signature; + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + + if (errorCondition) { + return errorCondition; + } + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return returnType; + } else if (callEx.argumentList) { + this.resolveAST(callEx.argumentList.arguments, false, context); + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Invalid_new_expression), additionalResults, context); + + return this.getNewErrorTypeSymbol(); + }; + + PullTypeResolver.prototype.instantiateSignatureInContext = function (signatureAToInstantiate, contextualSignatureB, context, shouldFixContextualSignatureParameterTypes) { + var typeReplacementMap = []; + var inferredTypeArgs; + var specializedSignature; + var typeParameters = signatureAToInstantiate.getTypeParameters(); + var typeConstraint = null; + + var typeArgumentInferenceContext = new TypeScript.ContextualSignatureInstantiationTypeArgumentInferenceContext(this, context, signatureAToInstantiate, contextualSignatureB, shouldFixContextualSignatureParameterTypes); + inferredTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); + + var functionTypeA = signatureAToInstantiate.functionType; + var functionTypeB = contextualSignatureB.functionType; + var enclosingTypeParameterMap; + + if (functionTypeA) { + enclosingTypeParameterMap = functionTypeA.getTypeParameterArgumentMap(); + + for (var id in enclosingTypeParameterMap) { + typeReplacementMap[id] = enclosingTypeParameterMap[id]; + } + } + + if (functionTypeB) { + enclosingTypeParameterMap = functionTypeB.getTypeParameterArgumentMap(); + + for (var id in enclosingTypeParameterMap) { + typeReplacementMap[id] = enclosingTypeParameterMap[id]; + } + } + + TypeScript.PullInstantiationHelpers.updateTypeParameterArgumentMap(typeParameters, inferredTypeArgs, typeReplacementMap); + + return this.instantiateSignature(signatureAToInstantiate, typeReplacementMap); + }; + + PullTypeResolver.prototype.resolveCastExpression = function (assertionExpression, context) { + var typeAssertionType = this.resolveTypeReference(assertionExpression.type, context).type; + + if (this.canTypeCheckAST(assertionExpression, context)) { + this.typeCheckCastExpression(assertionExpression, context, typeAssertionType); + } + + return typeAssertionType; + }; + + PullTypeResolver.prototype.typeCheckCastExpression = function (assertionExpression, context, typeAssertionType) { + this.setTypeChecked(assertionExpression, context); + + context.pushNewContextualType(typeAssertionType); + var exprType = this.resolveAST(assertionExpression.expression, true, context).type; + context.popAnyContextualType(); + + this.resolveDeclaredSymbol(typeAssertionType, context); + this.resolveDeclaredSymbol(exprType, context); + + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(exprType, typeAssertionType, assertionExpression, context, comparisonInfo); + + if (!isAssignable) { + var widenedExprType = exprType.widenedType(this, assertionExpression.expression, context); + isAssignable = this.sourceIsAssignableToTarget(typeAssertionType, widenedExprType, assertionExpression, context, comparisonInfo); + } + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(assertionExpression); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(assertionExpression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [exprType.toString(enclosingSymbol), typeAssertionType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(assertionExpression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [exprType.toString(enclosingSymbol), typeAssertionType.toString(enclosingSymbol)])); + } + } + }; + + PullTypeResolver.prototype.resolveAssignmentExpression = function (binaryExpression, context) { + var leftExpr = this.resolveAST(binaryExpression.left, false, context); + var leftType = leftExpr.type; + + context.pushNewContextualType(leftType); + var rightType = this.resolveAST(binaryExpression.right, true, context).type; + context.popAnyContextualType(); + + rightType = this.getInstanceTypeForAssignment(binaryExpression.left, rightType, context); + + if (this.canTypeCheckAST(binaryExpression, context)) { + this.setTypeChecked(binaryExpression, context); + + if (!this.isReference(binaryExpression.left, leftExpr)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_left_hand_side_of_assignment_expression)); + } else { + this.checkAssignability(binaryExpression.left, rightType, leftExpr.type, context); + } + } + + return rightType; + }; + + PullTypeResolver.prototype.getInstanceTypeForAssignment = function (lhs, type, context) { + var typeToReturn = type; + if (typeToReturn && typeToReturn.isAlias()) { + typeToReturn = typeToReturn.getExportAssignedTypeSymbol(); + } + + if (typeToReturn && typeToReturn.isContainer() && !typeToReturn.isEnum()) { + var instanceTypeSymbol = typeToReturn.getInstanceType(); + + if (!instanceTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(lhs, TypeScript.DiagnosticCode.Tried_to_set_variable_type_to_uninitialized_module_type_0, [type.toString()])); + typeToReturn = null; + } else { + typeToReturn = instanceTypeSymbol; + } + } + + return typeToReturn; + }; + + PullTypeResolver.prototype.widenType = function (type, ast, context) { + if (type === this.semanticInfoChain.undefinedTypeSymbol || type === this.semanticInfoChain.nullTypeSymbol || type.isError()) { + return this.semanticInfoChain.anyTypeSymbol; + } + + if (type.isArrayNamedTypeReference()) { + return this.widenArrayType(type, ast, context); + } else if (type.kind === 256 /* ObjectLiteral */) { + return this.widenObjectLiteralType(type, ast, context); + } + + return type; + }; + + PullTypeResolver.prototype.widenArrayType = function (type, ast, context) { + var elementType = type.getElementType().widenedType(this, ast, context); + + if (this.compilationSettings.noImplicitAny() && ast) { + if (elementType === this.semanticInfoChain.anyTypeSymbol && type.getElementType() !== this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Array_Literal_implicitly_has_an_any_type_from_widening)); + } + } + + return this.getArrayType(elementType); + }; + + PullTypeResolver.prototype.widenObjectLiteralType = function (type, ast, context) { + if (!this.needsToWidenObjectLiteralType(type, ast, context)) { + return type; + } + + TypeScript.Debug.assert(type.name === ""); + var newObjectTypeSymbol = new TypeScript.PullTypeSymbol(type.name, type.kind); + var declsOfObjectType = type.getDeclarations(); + TypeScript.Debug.assert(declsOfObjectType.length === 1); + newObjectTypeSymbol.addDeclaration(declsOfObjectType[0]); + var members = type.getMembers(); + + for (var i = 0; i < members.length; i++) { + var memberType = members[i].type; + + var widenedMemberType = members[i].type.widenedType(this, ast, context); + var newMember = new TypeScript.PullSymbol(members[i].name, members[i].kind); + + var declsOfMember = members[i].getDeclarations(); + + newMember.addDeclaration(declsOfMember[0]); + newMember.type = widenedMemberType; + newObjectTypeSymbol.addMember(newMember); + newMember.setResolved(); + + if (this.compilationSettings.noImplicitAny() && ast && widenedMemberType === this.semanticInfoChain.anyTypeSymbol && memberType !== this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Object_literal_s_property_0_implicitly_has_an_any_type_from_widening, [members[i].name])); + } + } + + var indexers = type.getIndexSignatures(); + for (var i = 0; i < indexers.length; i++) { + var newIndexer = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + var parameter = indexers[i].parameters[0]; + var newParameter = new TypeScript.PullSymbol(parameter.name, parameter.kind); + newParameter.type = parameter.type; + newIndexer.addParameter(newParameter); + newIndexer.returnType = indexers[i].returnType; + newObjectTypeSymbol.addIndexSignature(newIndexer); + } + + return newObjectTypeSymbol; + }; + + PullTypeResolver.prototype.needsToWidenObjectLiteralType = function (type, ast, context) { + var members = type.getMembers(); + for (var i = 0; i < members.length; i++) { + var memberType = members[i].type; + if (memberType !== memberType.widenedType(this, ast, context)) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.findBestCommonType = function (collection, context, comparisonInfo) { + var len = collection.getLength(); + + for (var i = 0; i < len; i++) { + var candidateType = collection.getTypeAtIndex(i); + if (this.typeIsBestCommonTypeCandidate(candidateType, collection, context)) { + return candidateType; + } + } + + return this.semanticInfoChain.emptyTypeSymbol; + }; + + PullTypeResolver.prototype.typeIsBestCommonTypeCandidate = function (candidateType, collection, context) { + for (var i = 0; i < collection.getLength(); i++) { + var otherType = collection.getTypeAtIndex(i); + if (candidateType === otherType) { + continue; + } + + if (!this.sourceIsSubtypeOfTarget(otherType, candidateType, null, context)) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.typesAreIdenticalInEnclosingTypes = function (t1, t2, context) { + t1 = this.getSymbolForRelationshipCheck(t1); + t2 = this.getSymbolForRelationshipCheck(t2); + + if (t1 === t2) { + return true; + } + + if (t1 && t2) { + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + return this.infinitelyExpandingTypesAreIdentical(t1, t2, context); + } + } + + return this.typesAreIdentical(t1, t2, context); + }; + + PullTypeResolver.prototype.typesAreIdenticalWithNewEnclosingTypes = function (t1, t2, context) { + var enclosingTypeWalkerStates = context.resetEnclosingTypeWalkerStates(); + var areTypesIdentical = this.typesAreIdentical(t1, t2, context); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areTypesIdentical; + }; + + PullTypeResolver.prototype.typesAreIdentical = function (t1, t2, context) { + t1 = this.getSymbolForRelationshipCheck(t1); + t2 = this.getSymbolForRelationshipCheck(t2); + + if (t1 === t2) { + return true; + } + + if (!t1 || !t2) { + return false; + } + + if (TypeScript.hasFlag(t1.kind, 64 /* Enum */) || TypeScript.hasFlag(t2.kind, 64 /* Enum */)) { + return false; + } + + if (t1.isPrimitive() && t1.isStringConstant() && t2.isPrimitive() && t2.isStringConstant()) { + return TypeScript.stripStartAndEndQuotes(t1.name) === TypeScript.stripStartAndEndQuotes(t2.name); + } + + if (t1.isPrimitive() || t2.isPrimitive()) { + return false; + } + + if (t1.isError() && t2.isError()) { + return true; + } + + var isIdentical = this.identicalCache.valueAt(t1.pullSymbolID, t2.pullSymbolID); + if (isIdentical != undefined) { + return isIdentical; + } + + if (t1.isTypeParameter() !== t2.isTypeParameter()) { + return false; + } else if (t1.isTypeParameter()) { + var t1ParentDeclaration = t1.getDeclarations()[0].getParentDecl(); + var t2ParentDeclaration = t2.getDeclarations()[0].getParentDecl(); + + if (t1ParentDeclaration === t2ParentDeclaration) { + return this.symbolsShareDeclaration(t1, t2); + } else { + return false; + } + } + + if (t1.isPrimitive() !== t2.isPrimitive()) { + return false; + } + + this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, true); + var statesWhenStartedWalkingTypes = context.startWalkingTypes(t1, t2); + isIdentical = this.typesAreIdenticalWorker(t1, t2, context); + context.endWalkingTypes(statesWhenStartedWalkingTypes); + this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, isIdentical); + + return isIdentical; + }; + + PullTypeResolver.prototype.typesAreIdenticalWorker = function (t1, t2, context) { + if (t1.getIsSpecialized() && t2.getIsSpecialized()) { + if (TypeScript.PullHelpers.getRootType(t1) === TypeScript.PullHelpers.getRootType(t2) && TypeScript.PullHelpers.getRootType(t1).isNamedTypeSymbol()) { + var t1TypeArguments = t1.getTypeArguments(); + var t2TypeArguments = t2.getTypeArguments(); + + if (t1TypeArguments && t2TypeArguments) { + for (var i = 0; i < t1TypeArguments.length; i++) { + if (!this.typesAreIdenticalWithNewEnclosingTypes(t1TypeArguments[i], t2TypeArguments[i], context)) { + return false; + } + } + } + + return true; + } + } + + if (t1.hasMembers() && t2.hasMembers()) { + var t1Members = t1.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + var t2Members = t2.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + + if (t1Members.length !== t2Members.length) { + return false; + } + + var t1MemberSymbol = null; + var t2MemberSymbol = null; + + var t1MemberType = null; + var t2MemberType = null; + + for (var iMember = 0; iMember < t1Members.length; iMember++) { + t1MemberSymbol = t1Members[iMember]; + t2MemberSymbol = this.getNamedPropertySymbol(t1MemberSymbol.name, 68147712 /* SomeValue */, t2); + + if (!this.propertiesAreIdentical(t1MemberSymbol, t2MemberSymbol, context)) { + return false; + } + } + } else if (t1.hasMembers() || t2.hasMembers()) { + return false; + } + + var t1CallSigs = t1.getCallSignatures(); + var t2CallSigs = t2.getCallSignatures(); + + var t1ConstructSigs = t1.getConstructSignatures(); + var t2ConstructSigs = t2.getConstructSignatures(); + + var t1IndexSigs = t1.getIndexSignatures(); + var t2IndexSigs = t2.getIndexSignatures(); + + if (!this.signatureGroupsAreIdentical(t1CallSigs, t2CallSigs, context)) { + return false; + } + + if (!this.signatureGroupsAreIdentical(t1ConstructSigs, t2ConstructSigs, context)) { + return false; + } + + if (!this.signatureGroupsAreIdentical(t1IndexSigs, t2IndexSigs, context)) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.propertiesAreIdentical = function (propertySymbol1, propertySymbol2, context) { + if (!propertySymbol2 || (propertySymbol1.isOptional !== propertySymbol2.isOptional)) { + return false; + } + + var t1MemberSymbolIsPrivate = propertySymbol1.anyDeclHasFlag(2 /* Private */); + var t2MemberSymbolIsPrivate = propertySymbol2.anyDeclHasFlag(2 /* Private */); + + if (t1MemberSymbolIsPrivate !== t2MemberSymbolIsPrivate) { + return false; + } else if (t2MemberSymbolIsPrivate && t1MemberSymbolIsPrivate) { + var t1MemberSymbolDecl = propertySymbol1.getDeclarations()[0]; + var sourceDecl = propertySymbol2.getDeclarations()[0]; + if (t1MemberSymbolDecl !== sourceDecl) { + return false; + } + } + + var t1MemberType = propertySymbol1.type; + var t2MemberType = propertySymbol2.type; + + context.walkMemberTypes(propertySymbol1.name); + var areMemberTypesIdentical = this.typesAreIdenticalInEnclosingTypes(t1MemberType, t2MemberType, context); + context.postWalkMemberTypes(); + return areMemberTypesIdentical; + }; + + PullTypeResolver.prototype.propertiesAreIdenticalWithNewEnclosingTypes = function (type1, type2, property1, property2, context) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(type1, type2); + var arePropertiesIdentical = this.propertiesAreIdentical(property1, property2, context); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return arePropertiesIdentical; + }; + + PullTypeResolver.prototype.signatureGroupsAreIdentical = function (sg1, sg2, context) { + if (sg1 === sg2) { + return true; + } + + if (!sg1 || !sg2) { + return false; + } + + if (sg1.length !== sg2.length) { + return false; + } + + for (var i = 0; i < sg1.length; i++) { + context.walkSignatures(sg1[i].kind, i); + var areSignaturesIdentical = this.signaturesAreIdentical(sg1[i], sg2[i], context, true); + context.postWalkSignatures(); + if (!areSignaturesIdentical) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.typeParametersAreIdentical = function (tp1, tp2, context) { + var typeParamsAreIdentical = this.typeParametersAreIdenticalWorker(tp1, tp2, context); + + this.setTypeParameterIdentity(tp1, tp2, undefined); + + return typeParamsAreIdentical; + }; + + PullTypeResolver.prototype.typeParametersAreIdenticalWorker = function (tp1, tp2, context) { + if (!!(tp1 && tp1.length) !== !!(tp2 && tp2.length)) { + return false; + } + + if (tp1 && tp2 && (tp1.length !== tp2.length)) { + return false; + } + + if (tp1 && tp2) { + for (var i = 0; i < tp1.length; i++) { + context.walkTypeParameterConstraints(i); + var areConstraintsIdentical = this.typesAreIdentical(tp1[i].getConstraint(), tp2[i].getConstraint(), context); + context.postWalkTypeParameterConstraints(); + if (!areConstraintsIdentical) { + return false; + } + } + } + + return true; + }; + + PullTypeResolver.prototype.setTypeParameterIdentity = function (tp1, tp2, val) { + if (tp1 && tp2 && tp1.length === tp2.length) { + for (var i = 0; i < tp1.length; i++) { + this.identicalCache.setValueAt(tp1[i].pullSymbolID, tp2[i].pullSymbolID, val); + } + } + }; + + PullTypeResolver.prototype.signaturesAreIdenticalWithNewEnclosingTypes = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(s1, s2); + var areSignaturesIdentical = this.signaturesAreIdentical(s1, s2, context, includingReturnType); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSignaturesIdentical; + }; + + PullTypeResolver.prototype.signaturesAreIdentical = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + if (s1 === s2) { + return true; + } + + var signaturesIdentical = this.identicalCache.valueAt(s1.pullSymbolID, s2.pullSymbolID); + if (signaturesIdentical || (signaturesIdentical != undefined && includingReturnType)) { + return signaturesIdentical; + } + + var oldValue = signaturesIdentical; + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, true); + + signaturesIdentical = this.signaturesAreIdenticalWorker(s1, s2, context, includingReturnType); + + if (includingReturnType) { + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, signaturesIdentical); + } else { + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, oldValue); + } + + return signaturesIdentical; + }; + + PullTypeResolver.prototype.signaturesAreIdenticalWorker = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + if (s1.hasVarArgs !== s2.hasVarArgs) { + return false; + } + + if (s1.nonOptionalParamCount !== s2.nonOptionalParamCount) { + return false; + } + + if (s1.parameters.length !== s2.parameters.length) { + return false; + } + + var s1TypeParameters = s1.getTypeParameters(); + var s2TypeParameters = s2.getTypeParameters(); + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, true); + + var typeParametersParametersAndReturnTypesAreIdentical = this.signatureTypeParametersParametersAndReturnTypesAreIdentical(s1, s2, context, includingReturnType); + + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, undefined); + return typeParametersParametersAndReturnTypesAreIdentical; + }; + + PullTypeResolver.prototype.signatureTypeParametersParametersAndReturnTypesAreIdentical = function (s1, s2, context, includingReturnType) { + if (!this.typeParametersAreIdenticalWorker(s1.getTypeParameters(), s2.getTypeParameters(), context)) { + return false; + } + + if (includingReturnType) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s1); + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s2); + context.walkReturnTypes(); + var areReturnTypesIdentical = this.typesAreIdenticalInEnclosingTypes(s1.returnType, s2.returnType, context); + context.postWalkReturnTypes(); + if (!areReturnTypesIdentical) { + return false; + } + } + + var s1Params = s1.parameters; + var s2Params = s2.parameters; + + for (var iParam = 0; iParam < s1Params.length; iParam++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s1Params[iParam]); + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s2Params[iParam]); + context.walkParameterTypes(iParam); + var areParameterTypesIdentical = this.typesAreIdenticalInEnclosingTypes(s1Params[iParam].type, s2Params[iParam].type, context); + context.postWalkParameterTypes(); + + if (!areParameterTypesIdentical) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.signatureReturnTypesAreIdentical = function (s1, s2, context) { + var s1TypeParameters = s1.getTypeParameters(); + var s2TypeParameters = s2.getTypeParameters(); + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, true); + + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(s1, s2); + context.walkReturnTypes(); + var returnTypeIsIdentical = this.typesAreIdenticalInEnclosingTypes(s1.returnType, s2.returnType, context); + + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, undefined); + + return returnTypeIsIdentical; + }; + + PullTypeResolver.prototype.symbolsShareDeclaration = function (symbol1, symbol2) { + var decls1 = symbol1.getDeclarations(); + var decls2 = symbol2.getDeclarations(); + + if (decls1.length && decls2.length) { + return decls1[0] === decls2[0]; + } + + return false; + }; + + PullTypeResolver.prototype.sourceIsSubtypeOfTarget = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.sourceMembersAreAssignableToTargetMembers = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceMembersAreAssignableToTargetMembers = this.sourceMembersAreRelatableToTargetMembers(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceMembersAreAssignableToTargetMembers; + }; + + PullTypeResolver.prototype.sourcePropertyIsAssignableToTargetProperty = function (source, target, sourceProp, targetProp, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var isSourcePropertyIsAssignableToTargetProperty = this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return isSourcePropertyIsAssignableToTargetProperty; + }; + + PullTypeResolver.prototype.sourceCallSignaturesAreAssignableToTargetCallSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceCallSignaturesAssignableToTargetCallSignatures = this.sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceCallSignaturesAssignableToTargetCallSignatures; + }; + + PullTypeResolver.prototype.sourceConstructSignaturesAreAssignableToTargetConstructSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceConstructSignaturesAssignableToTargetConstructSignatures = this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceConstructSignaturesAssignableToTargetConstructSignatures; + }; + + PullTypeResolver.prototype.sourceIndexSignaturesAreAssignableToTargetIndexSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceIndexSignaturesAssignableToTargetIndexSignatures = this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceIndexSignaturesAssignableToTargetIndexSignatures; + }; + + PullTypeResolver.prototype.typeIsAssignableToFunction = function (source, ast, context) { + if (source.isFunctionType()) { + return true; + } + + return this.cachedFunctionInterfaceType() && this.sourceIsAssignableToTarget(source, this.cachedFunctionInterfaceType(), ast, context); + }; + + PullTypeResolver.prototype.signatureIsAssignableToTarget = function (s1, s2, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(s1, s2); + var isSignatureIsAssignableToTarget = this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return isSignatureIsAssignableToTarget; + }; + + PullTypeResolver.prototype.sourceIsAssignableToTarget = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + return this.sourceIsRelatableToTarget(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.sourceIsAssignableToTargetWithNewEnclosingTypes = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + return this.sourceIsRelatableToTargetWithNewEnclosingTypes(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.getSymbolForRelationshipCheck = function (symbol) { + if (symbol && symbol.isTypeReference()) { + return symbol.getReferencedTypeSymbol(); + } + + return symbol; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetInEnclosingTypes = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + source = this.getSymbolForRelationshipCheck(source); + target = this.getSymbolForRelationshipCheck(target); + + if (source === target) { + return true; + } + + if (source && target) { + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + return this.infinitelyExpandingSourceTypeIsRelatableToTargetType(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + } + } + + return this.sourceIsRelatableToTarget(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetWithNewEnclosingTypes = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.resetEnclosingTypeWalkerStates(); + var isSourceRelatable = this.sourceIsRelatableToTarget(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return isSourceRelatable; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetInCache = function (source, target, comparisonCache, comparisonInfo) { + var isRelatable = comparisonCache.valueAt(source.pullSymbolID, target.pullSymbolID); + + if (isRelatable) { + return { isRelatable: isRelatable }; + } + + if (isRelatable != undefined && !comparisonInfo) { + return { isRelatable: isRelatable }; + } + + return null; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + source = this.getSymbolForRelationshipCheck(source); + target = this.getSymbolForRelationshipCheck(target); + + if (source === target) { + return true; + } + + if (!(source && target)) { + return true; + } + + var sourceApparentType = this.getApparentType(source); + + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(source, target, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; + } + + if (source === this.semanticInfoChain.stringTypeSymbol && target.isPrimitive() && target.isStringConstant()) { + return comparisonInfo && comparisonInfo.stringConstantVal && (comparisonInfo.stringConstantVal.kind() === 14 /* StringLiteral */) && (TypeScript.stripStartAndEndQuotes(comparisonInfo.stringConstantVal.text()) === TypeScript.stripStartAndEndQuotes(target.name)); + } + + if (assignableTo) { + if (this.isAnyOrEquivalent(source) || this.isAnyOrEquivalent(target)) { + return true; + } + } else { + if (this.isAnyOrEquivalent(target)) { + return true; + } + } + + if (target === this.semanticInfoChain.stringTypeSymbol && source.isPrimitive() && source.isStringConstant()) { + return true; + } + + if (source.isPrimitive() && source.isStringConstant() && target.isPrimitive() && target.isStringConstant()) { + return TypeScript.stripStartAndEndQuotes(source.name) === TypeScript.stripStartAndEndQuotes(target.name); + } + + if (source === this.semanticInfoChain.undefinedTypeSymbol) { + return true; + } + + if ((source === this.semanticInfoChain.nullTypeSymbol) && (target !== this.semanticInfoChain.undefinedTypeSymbol && target != this.semanticInfoChain.voidTypeSymbol)) { + return true; + } + + if (target === this.semanticInfoChain.voidTypeSymbol) { + if (source === this.semanticInfoChain.undefinedTypeSymbol || source == this.semanticInfoChain.nullTypeSymbol) { + return true; + } + + return false; + } else if (source === this.semanticInfoChain.voidTypeSymbol) { + if (target === this.semanticInfoChain.anyTypeSymbol) { + return true; + } + + return false; + } + + if (target === this.semanticInfoChain.numberTypeSymbol && TypeScript.PullHelpers.symbolIsEnum(source)) { + return true; + } + + if (source === this.semanticInfoChain.numberTypeSymbol && TypeScript.PullHelpers.symbolIsEnum(target)) { + return assignableTo; + } + + if (TypeScript.PullHelpers.symbolIsEnum(target) && TypeScript.PullHelpers.symbolIsEnum(source)) { + return this.symbolsShareDeclaration(target, source); + } + + if ((source.kind & 64 /* Enum */) || (target.kind & 64 /* Enum */)) { + return false; + } + + if (source.getIsSpecialized() && target.getIsSpecialized()) { + if (TypeScript.PullHelpers.getRootType(source) === TypeScript.PullHelpers.getRootType(target) && TypeScript.PullHelpers.getRootType(source).isNamedTypeSymbol()) { + var sourceTypeArguments = source.getTypeArguments(); + var targetTypeArguments = target.getTypeArguments(); + + if (sourceTypeArguments && targetTypeArguments) { + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, true); + + for (var i = 0; i < sourceTypeArguments.length; i++) { + if (!this.sourceIsRelatableToTargetWithNewEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, null, isComparingInstantiatedSignatures)) { + break; + } + } + + if (i === sourceTypeArguments.length) { + return true; + } else { + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, undefined); + } + } + } + } + + if (target.isTypeParameter()) { + if (source.isTypeParameter()) { + if (!source.getConstraint()) { + return this.typesAreIdentical(target, source, context); + } else { + return this.isSourceTypeParameterConstrainedToTargetTypeParameter(source, target); + } + } else { + if (isComparingInstantiatedSignatures) { + target = target.getBaseConstraint(this.semanticInfoChain); + } else { + return this.typesAreIdentical(target, sourceApparentType, context); + } + } + } + + if (sourceApparentType.isPrimitive() || target.isPrimitive()) { + return false; + } + + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, true); + + var symbolsWhenStartedWalkingTypes = context.startWalkingTypes(sourceApparentType, target); + var isRelatable = this.sourceIsRelatableToTargetWorker(sourceApparentType, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.endWalkingTypes(symbolsWhenStartedWalkingTypes); + + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.isSourceTypeParameterConstrainedToTargetTypeParameter = function (source, target) { + var current = source; + while (current && current.isTypeParameter()) { + if (current === target) { + return true; + } + + current = current.getConstraint(); + } + return false; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetWorker = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + if (target.hasMembers() && !this.sourceMembersAreRelatableToTargetMembers(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.sourceMembersAreRelatableToTargetMembers = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetProps = target.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + + for (var itargetProp = 0; itargetProp < targetProps.length; itargetProp++) { + var targetProp = targetProps[itargetProp]; + + var sourceProp = this._getNamedPropertySymbolOfAugmentedType(targetProp.name, source); + + this.resolveDeclaredSymbol(targetProp, context); + + var targetPropType = targetProp.type; + + if (!sourceProp) { + if (!(targetProp.isOptional)) { + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_is_missing_property_1_from_type_2, [source.toString(enclosingSymbol), targetProp.getScopedNameEx().toString(), target.toString(enclosingSymbol)])); + } + return false; + } + continue; + } + + if (!this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.infinitelyExpandingSourceTypeIsRelatableToTargetType = function (sourceType, targetType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var widenedTargetType = targetType.widenedType(this, null, context); + var widenedSourceType = sourceType.widenedType(this, null, context); + + if ((widenedSourceType !== this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType !== this.semanticInfoChain.anyTypeSymbol)) { + var sourceTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(sourceType); + var targetTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(targetType); + + if (sourceTypeNamedTypeReference !== targetTypeNamedTypeReference) { + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_do_not_refer_to_same_named_type, [sourceType.getScopedNameEx(enclosingSymbol).toString(), targetType.toString(enclosingSymbol)])); + } + return false; + } + + var sourceTypeArguments = sourceType.getTypeArguments(); + var targetTypeArguments = targetType.getTypeArguments(); + + if (!sourceTypeArguments && !targetTypeArguments) { + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, true); + return true; + } + + if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length !== targetTypeArguments.length) { + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)])); + } + return false; + } + + var comparisonInfoTypeArgumentsCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoTypeArgumentsCheck = new TypeComparisonInfo(comparisonInfo); + } + var isRelatable = true; + for (var i = 0; i < sourceTypeArguments.length && isRelatable; i++) { + context.walkTypeArgument(i); + + if (!this.sourceIsRelatableToTargetInEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, comparisonInfoTypeArgumentsCheck, isComparingInstantiatedSignatures)) { + isRelatable = false; + if (comparisonInfo) { + var message; + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + + if (comparisonInfoTypeArgumentsCheck && comparisonInfoTypeArgumentsCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol), comparisonInfoTypeArgumentsCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)]); + } + comparisonInfo.addMessage(message); + } + } + + context.postWalkTypeArgument(); + } + } + + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.infinitelyExpandingTypesAreIdentical = function (sourceType, targetType, context) { + var widenedTargetType = targetType.widenedType(this, null, null); + var widenedSourceType = sourceType.widenedType(this, null, null); + + if ((widenedSourceType !== this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType !== this.semanticInfoChain.anyTypeSymbol)) { + var sourceTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(sourceType); + var targetTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(targetType); + if (sourceTypeNamedTypeReference !== targetTypeNamedTypeReference) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + return false; + } + + var sourceTypeArguments = sourceType.getTypeArguments(); + var targetTypeArguments = targetType.getTypeArguments(); + + if (!sourceTypeArguments && !targetTypeArguments) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, true); + return true; + } + + if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length !== targetTypeArguments.length) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + return false; + } + + for (var i = 0; i < sourceTypeArguments.length; i++) { + context.walkTypeArgument(i); + var areIdentical = this.typesAreIdenticalInEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], context); + context.postWalkTypeArgument(); + + if (!areIdentical) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + return false; + } + } + } + + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, true); + return true; + }; + + PullTypeResolver.prototype.sourcePropertyIsRelatableToTargetProperty = function (source, target, sourceProp, targetProp, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var _this = this; + var sourceAndTargetAreConstructors = source.isConstructor() && target.isConstructor(); + + var getNames = function (takeTypesFromPropertyContainers) { + var enclosingSymbol = _this.getEnclosingSymbolForAST(ast); + var sourceType = takeTypesFromPropertyContainers ? sourceProp.getContainer() : source; + var targetType = takeTypesFromPropertyContainers ? targetProp.getContainer() : target; + if (sourceAndTargetAreConstructors) { + sourceType = sourceType.getAssociatedContainerType(); + targetType = targetType.getAssociatedContainerType(); + } + return { + propertyName: targetProp.getScopedNameEx().toString(), + sourceTypeName: sourceType.toString(enclosingSymbol), + targetTypeName: targetType.toString(enclosingSymbol) + }; + }; + + var targetPropIsPrivate = targetProp.anyDeclHasFlag(2 /* Private */); + var sourcePropIsPrivate = sourceProp.anyDeclHasFlag(2 /* Private */); + + if (targetPropIsPrivate !== sourcePropIsPrivate) { + if (comparisonInfo) { + var names = getNames(true); + var code; + if (targetPropIsPrivate) { + code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Static_property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2 : TypeScript.DiagnosticCode.Property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2; + } else { + code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Static_property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2 : TypeScript.DiagnosticCode.Property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2; + } + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName])); + comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; + } + return false; + } else if (sourcePropIsPrivate && targetPropIsPrivate) { + var targetDecl = targetProp.getDeclarations()[0]; + var sourceDecl = sourceProp.getDeclarations()[0]; + + if (targetDecl !== sourceDecl) { + if (comparisonInfo) { + var names = getNames(true); + + comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_0_and_1_define_static_property_2_as_private : TypeScript.DiagnosticCode.Types_0_and_1_define_property_2_as_private; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(code, [names.sourceTypeName, names.targetTypeName, names.propertyName])); + } + + return false; + } + } + + if (sourceProp.isOptional && !targetProp.isOptional) { + if (comparisonInfo) { + var names = getNames(true); + comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2, [names.propertyName, names.sourceTypeName, names.targetTypeName])); + } + return false; + } + + this.resolveDeclaredSymbol(sourceProp, context); + + var sourcePropType = sourceProp.type; + var targetPropType = targetProp.type; + + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(sourcePropType, targetPropType, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; + } + + var comparisonInfoPropertyTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoPropertyTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + context.walkMemberTypes(targetProp.name); + var isSourcePropertyRelatableToTargetProperty = this.sourceIsRelatableToTargetInEnclosingTypes(sourcePropType, targetPropType, assignableTo, comparisonCache, ast, context, comparisonInfoPropertyTypeCheck, isComparingInstantiatedSignatures); + context.postWalkMemberTypes(); + + if (!isSourcePropertyRelatableToTargetProperty && comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.flags |= 32 /* IncompatiblePropertyTypes */; + var message; + var names = getNames(false); + if (comparisonInfoPropertyTypeCheck && comparisonInfoPropertyTypeCheck.message) { + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3 : TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3; + message = TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName, comparisonInfoPropertyTypeCheck.message]); + } else { + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible : TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible; + message = TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName]); + } + comparisonInfo.addMessage(message); + } + + return isSourcePropertyRelatableToTargetProperty; + }; + + PullTypeResolver.prototype.sourceCallSignaturesAreRelatableToTargetCallSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetCallSigs = target.getCallSignatures(); + + if (targetCallSigs.length) { + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + var sourceCallSigs = source.getCallSignatures(); + if (!this.signatureGroupIsRelatableToTarget(source, target, sourceCallSigs, targetCallSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { + if (comparisonInfo) { + var message; + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + if (sourceCallSigs.length && targetCallSigs.length) { + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signatures_of_types_0_and_1_are_incompatible_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signatures_of_types_0_and_1_are_incompatible, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)]); + } + } else { + var hasSig = targetCallSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + var lacksSig = !targetCallSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_requires_a_call_signature_but_type_1_lacks_one, [hasSig, lacksSig]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.sourceConstructSignaturesAreRelatableToTargetConstructSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetConstructSigs = target.getConstructSignatures(); + if (targetConstructSigs.length) { + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + var sourceConstructSigs = source.getConstructSignatures(); + if (!this.signatureGroupIsRelatableToTarget(source, target, sourceConstructSigs, targetConstructSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + var message; + if (sourceConstructSigs.length && targetConstructSigs.length) { + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Construct_signatures_of_types_0_and_1_are_incompatible_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Construct_signatures_of_types_0_and_1_are_incompatible, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)]); + } + } else { + var hasSig = targetConstructSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + var lacksSig = !targetConstructSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_requires_a_construct_signature_but_type_1_lacks_one, [hasSig, lacksSig]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.sourceIndexSignaturesAreRelatableToTargetIndexSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetIndexSigs = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(target, context); + var targetStringSig = targetIndexSigs.stringSignature; + var targetNumberSig = targetIndexSigs.numericSignature; + + if (targetStringSig || targetNumberSig) { + var sourceIndexSigs = this.getBothKindsOfIndexSignaturesIncludingAugmentedType(source, context); + var enclosingTypeIndexSigs = context.getBothKindOfIndexSignatures(true, false); + var sourceStringSig = sourceIndexSigs.stringSignature; + var sourceNumberSig = sourceIndexSigs.numericSignature; + + var comparable = true; + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + if (targetStringSig) { + if (sourceStringSig) { + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, true, true); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceStringSig.returnType, targetStringSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); + } else { + comparable = false; + } + } + + if (comparable && targetNumberSig) { + if (sourceNumberSig) { + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, false, false); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceNumberSig.returnType, targetNumberSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); + } else if (sourceStringSig) { + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, true, false); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceStringSig.returnType, targetNumberSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); + } else { + comparable = false; + } + } + + if (!comparable) { + if (comparisonInfo) { + var message; + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Index_signatures_of_types_0_and_1_are_incompatible_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Index_signatures_of_types_0_and_1_are_incompatible, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.signatureGroupIsRelatableToTarget = function (source, target, sourceSG, targetSG, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + if (sourceSG === targetSG) { + return true; + } + + if (!(sourceSG.length && targetSG.length)) { + return false; + } + + var foundMatch = false; + + var targetExcludeDefinition = targetSG.length > 1; + var sourceExcludeDefinition = sourceSG.length > 1; + var sigsCompared = 0; + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo, true); + comparisonInfoSignatuesTypeCheck.message = comparisonInfo.message; + } + for (var iMSig = 0; iMSig < targetSG.length; iMSig++) { + var mSig = targetSG[iMSig]; + + if (mSig.isStringConstantOverloadSignature() || (targetExcludeDefinition && mSig.isDefinition())) { + continue; + } + + for (var iNSig = 0; iNSig < sourceSG.length; iNSig++) { + var nSig = sourceSG[iNSig]; + + if (nSig.isStringConstantOverloadSignature() || (sourceExcludeDefinition && nSig.isDefinition())) { + continue; + } + + context.walkSignatures(nSig.kind, iNSig, iMSig); + var isSignatureRelatableToTarget = this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, ast, context, sigsCompared == 0 ? comparisonInfoSignatuesTypeCheck : null, isComparingInstantiatedSignatures); + context.postWalkSignatures(); + + sigsCompared++; + + if (isSignatureRelatableToTarget) { + foundMatch = true; + break; + } + } + + if (foundMatch) { + foundMatch = false; + continue; + } + + if (comparisonInfo && sigsCompared == 1) { + comparisonInfo.message = comparisonInfoSignatuesTypeCheck.message; + } + + return false; + } + + return true; + }; + + PullTypeResolver.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(sourceSig, targetSig, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; + } + + comparisonCache.setValueAt(sourceSig.pullSymbolID, targetSig.pullSymbolID, true); + var isRelatable = this.signatureIsRelatableToTargetWorker(sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + comparisonCache.setValueAt(sourceSig.pullSymbolID, targetSig.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.signatureIsRelatableToTargetWorker = function (sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var _this = this; + var sourceParameters = sourceSig.parameters; + var targetParameters = targetSig.parameters; + + if (!sourceParameters || !targetParameters) { + return false; + } + + var targetNonOptionalParamCount = targetSig.nonOptionalParamCount; + var sourceNonOptionalParamCount = sourceSig.nonOptionalParamCount; + + if (!targetSig.hasVarArgs && sourceNonOptionalParamCount > targetParameters.length) { + if (comparisonInfo) { + comparisonInfo.flags |= 3 /* SourceSignatureHasTooManyParameters */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signature_expects_0_or_fewer_parameters, [targetParameters.length])); + } + return false; + } + + if (this.signaturesAreIdentical(sourceSig, targetSig, context)) { + return true; + } + + if (targetSig.isGeneric()) { + targetSig = this.instantiateSignatureToAny(targetSig); + } + + if (sourceSig.isGeneric()) { + sourceSig = this.instantiateSignatureToAny(sourceSig); + } + + var sourceReturnType = sourceSig.returnType; + var targetReturnType = targetSig.returnType; + + if (targetReturnType !== this.semanticInfoChain.voidTypeSymbol) { + context.walkReturnTypes(); + var returnTypesAreRelatable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceReturnType, targetReturnType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.postWalkReturnTypes(); + if (!returnTypesAreRelatable) { + if (comparisonInfo) { + comparisonInfo.flags |= 16 /* IncompatibleReturnTypes */; + } + + return false; + } + } + + return targetSig.forAllCorrespondingParameterTypesInThisAndOtherSignature(sourceSig, function (targetParamType, sourceParamType, iParam) { + context.walkParameterTypes(iParam); + var areParametersRelatable = _this.sourceIsRelatableToTargetInEnclosingTypes(sourceParamType, targetParamType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + if (!areParametersRelatable) { + context.swapEnclosingTypeWalkers(); + areParametersRelatable = _this.sourceIsRelatableToTargetInEnclosingTypes(targetParamType, sourceParamType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.swapEnclosingTypeWalkers(); + } + context.postWalkParameterTypes(); + + if (!areParametersRelatable) { + if (comparisonInfo) { + comparisonInfo.flags |= 64 /* IncompatibleParameterTypes */; + } + } + + return areParametersRelatable; + }); + }; + + PullTypeResolver.prototype.resolveOverloads = function (application, group, haveTypeArgumentsAtCallSite, context, diagnostics) { + var _this = this; + var hasOverloads = group.length > 1; + var comparisonInfo = new TypeComparisonInfo(); + var args = application.argumentList ? application.argumentList.arguments : null; + + var initialCandidates = TypeScript.ArrayUtilities.where(group, function (signature) { + if (hasOverloads && signature.isDefinition()) { + return false; + } + + var rootSignature = signature.getRootSymbol(); + if (haveTypeArgumentsAtCallSite && !rootSignature.isGeneric()) { + return false; + } + + return _this.overloadHasCorrectArity(signature, args); + }); + + var firstAssignableButNotSupertypeSignature = null; + var firstAssignableWithProvisionalErrorsSignature = null; + + for (var i = 0; i < initialCandidates.length; i++) { + var applicability = this.overloadIsApplicable(initialCandidates[i], args, context, comparisonInfo); + if (applicability === 3 /* Subtype */) { + return initialCandidates[i]; + } else if (applicability === 2 /* AssignableWithNoProvisionalErrors */ && !firstAssignableButNotSupertypeSignature) { + firstAssignableButNotSupertypeSignature = initialCandidates[i]; + } else if (applicability === 1 /* AssignableButWithProvisionalErrors */ && !firstAssignableWithProvisionalErrorsSignature) { + firstAssignableWithProvisionalErrorsSignature = initialCandidates[i]; + } + } + + if (firstAssignableButNotSupertypeSignature || firstAssignableWithProvisionalErrorsSignature) { + return firstAssignableButNotSupertypeSignature || firstAssignableWithProvisionalErrorsSignature; + } else { + var target = this.getCallTargetErrorSpanAST(application); + if (comparisonInfo.message) { + diagnostics.push(this.semanticInfoChain.diagnosticFromAST(target, TypeScript.DiagnosticCode.Supplied_parameters_do_not_match_any_signature_of_call_target_NL_0, [comparisonInfo.message])); + } else { + diagnostics.push(this.semanticInfoChain.diagnosticFromAST(target, TypeScript.DiagnosticCode.Supplied_parameters_do_not_match_any_signature_of_call_target, null)); + } + } + + return null; + }; + + PullTypeResolver.prototype.getCallTargetErrorSpanAST = function (callEx) { + return (callEx.expression.kind() === 212 /* MemberAccessExpression */) ? callEx.expression.name : callEx.expression; + }; + + PullTypeResolver.prototype.overloadHasCorrectArity = function (signature, args) { + if (args == null) { + return signature.nonOptionalParamCount === 0; + } + + var numberOfArgs = (args.nonSeparatorCount() && args.nonSeparatorCount() === args.separatorCount()) ? args.separatorCount() + 1 : args.nonSeparatorCount(); + if (numberOfArgs < signature.nonOptionalParamCount) { + return false; + } + if (!signature.hasVarArgs && numberOfArgs > signature.parameters.length) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.overloadIsApplicable = function (signature, args, context, comparisonInfo) { + if (args === null) { + return 3 /* Subtype */; + } + + var isInVarArg = false; + var parameters = signature.parameters; + var paramType = null; + + var overloadApplicability = 3 /* Subtype */; + + for (var i = 0; i < args.nonSeparatorCount(); i++) { + if (!isInVarArg) { + this.resolveDeclaredSymbol(parameters[i], context); + + if (parameters[i].isVarArg) { + paramType = parameters[i].type.getElementType() || this.getNewErrorTypeSymbol(parameters[i].type.getName()); + isInVarArg = true; + } else { + paramType = parameters[i].type; + } + } + + var statusOfCurrentArgument = this.overloadIsApplicableForArgument(paramType, args.nonSeparatorAt(i), i, context, comparisonInfo); + + if (statusOfCurrentArgument === 0 /* NotAssignable */) { + return 0 /* NotAssignable */; + } else if (statusOfCurrentArgument === 1 /* AssignableButWithProvisionalErrors */) { + overloadApplicability = 1 /* AssignableButWithProvisionalErrors */; + } else if (overloadApplicability !== 1 /* AssignableButWithProvisionalErrors */ && statusOfCurrentArgument === 2 /* AssignableWithNoProvisionalErrors */) { + overloadApplicability = 2 /* AssignableWithNoProvisionalErrors */; + } + } + + return overloadApplicability; + }; + + PullTypeResolver.prototype.overloadIsApplicableForArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + if (paramType.isAny()) { + return 3 /* Subtype */; + } else if (paramType.isError()) { + return 1 /* AssignableButWithProvisionalErrors */; + } else if (arg.kind() === 219 /* SimpleArrowFunctionExpression */) { + var simpleArrowFunction = arg; + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, null, TypeScript.ASTHelpers.parametersFromIdentifier(simpleArrowFunction.identifier), null, simpleArrowFunction.block, simpleArrowFunction.expression, argIndex, context, comparisonInfo); + } else if (arg.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { + var arrowFunction = arg; + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, arrowFunction.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), TypeScript.ASTHelpers.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, argIndex, context, comparisonInfo); + } else if (arg.kind() === 222 /* FunctionExpression */) { + var functionExpression = arg; + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, functionExpression.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(functionExpression.callSignature.parameterList), TypeScript.ASTHelpers.getType(functionExpression), functionExpression.block, null, argIndex, context, comparisonInfo); + } else if (arg.kind() === 215 /* ObjectLiteralExpression */) { + return this.overloadIsApplicableForObjectLiteralArgument(paramType, arg, argIndex, context, comparisonInfo); + } else if (arg.kind() === 214 /* ArrayLiteralExpression */) { + return this.overloadIsApplicableForArrayLiteralArgument(paramType, arg, argIndex, context, comparisonInfo); + } else { + return this.overloadIsApplicableForOtherArgument(paramType, arg, argIndex, context, comparisonInfo); + } + }; + + PullTypeResolver.prototype.overloadIsApplicableForAnyFunctionExpressionArgument = function (paramType, arg, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, argIndex, context, comparisonInfo) { + if (this.cachedFunctionInterfaceType() && paramType === this.cachedFunctionInterfaceType()) { + return 2 /* AssignableWithNoProvisionalErrors */; + } + + context.pushProvisionalType(paramType); + + var argSym = this.resolveAnyFunctionExpression(arg, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, true, context); + + var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + + context.popAnyContextualType(); + + return applicabilityStatus; + }; + + PullTypeResolver.prototype.overloadIsApplicableForObjectLiteralArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + if (this.cachedObjectInterfaceType() && paramType === this.cachedObjectInterfaceType()) { + return 2 /* AssignableWithNoProvisionalErrors */; + } + + context.pushProvisionalType(paramType); + var argSym = this.resolveObjectLiteralExpression(arg, true, context); + + var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + + context.popAnyContextualType(); + + return applicabilityStatus; + }; + + PullTypeResolver.prototype.overloadIsApplicableForArrayLiteralArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + if (paramType === this.cachedArrayInterfaceType()) { + return 2 /* AssignableWithNoProvisionalErrors */; + } + + context.pushProvisionalType(paramType); + var argSym = this.resolveArrayLiteralExpression(arg, true, context); + + var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + + context.popAnyContextualType(); + + return applicabilityStatus; + }; + + PullTypeResolver.prototype.overloadIsApplicableForOtherArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + var argSym = this.resolveAST(arg, false, context); + + if (argSym.type.isAlias()) { + var aliasSym = argSym.type; + argSym = aliasSym.getExportAssignedTypeSymbol(); + } + + comparisonInfo.stringConstantVal = arg; + return this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + }; + + PullTypeResolver.prototype.overloadIsApplicableForArgumentHelper = function (paramType, argSym, argumentIndex, comparisonInfo, arg, context) { + var tempComparisonInfo = new TypeComparisonInfo(); + tempComparisonInfo.stringConstantVal = comparisonInfo.stringConstantVal; + if (!context.hasProvisionalErrors() && this.sourceIsSubtypeOfTarget(argSym.type, paramType, arg, context, tempComparisonInfo)) { + return 3 /* Subtype */; + } + + if (this.sourceIsAssignableToTarget(argSym.type, paramType, arg, context, comparisonInfo.message ? tempComparisonInfo : comparisonInfo)) { + return context.hasProvisionalErrors() ? 1 /* AssignableButWithProvisionalErrors */ : 2 /* AssignableWithNoProvisionalErrors */; + } + + if (!comparisonInfo.message) { + var enclosingSymbol = this.getEnclosingSymbolForAST(arg); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Could_not_apply_type_0_to_argument_1_which_is_of_type_2, [paramType.toString(enclosingSymbol), (argumentIndex + 1), argSym.getTypeName(enclosingSymbol)])); + } + + return 0 /* NotAssignable */; + }; + + PullTypeResolver.prototype.inferArgumentTypesForSignature = function (argContext, comparisonInfo, context) { + var inferenceResultTypes = argContext.inferTypeArguments(); + var typeParameters = argContext.signatureBeingInferred.getTypeParameters(); + TypeScript.Debug.assert(typeParameters.length == inferenceResultTypes.length); + + var typeReplacementMapForConstraints = null; + for (var i = 0; i < inferenceResultTypes.length; i++) { + if (typeParameters[i].getConstraint()) { + typeReplacementMapForConstraints = typeReplacementMapForConstraints || TypeScript.PullInstantiationHelpers.createTypeParameterArgumentMap(typeParameters, inferenceResultTypes); + var associatedConstraint = this.instantiateType(typeParameters[i].getConstraint(), typeReplacementMapForConstraints); + if (!this.sourceIsAssignableToTargetWithNewEnclosingTypes(inferenceResultTypes[i], associatedConstraint, null, context, null, false)) { + inferenceResultTypes[i] = associatedConstraint; + } + } + } + + if (argContext.isInvocationInferenceContext()) { + var invocationContext = argContext; + if (!this.typeParametersAreInScopeAtArgumentList(typeParameters, invocationContext.argumentASTs)) { + for (var i = 0; i < inferenceResultTypes.length; i++) { + if (inferenceResultTypes[i].wrapsSomeTypeParameter(argContext.candidateCache)) { + inferenceResultTypes[i] = this.semanticInfoChain.anyTypeSymbol; + } + } + } + } + + return inferenceResultTypes; + }; + + PullTypeResolver.prototype.typeParametersAreInScopeAtArgumentList = function (typeParameters, args) { + var enclosingDecl = this.getEnclosingDeclForAST(args); + var typeParameterParentDecl = typeParameters[0].getDeclarations()[0].getParentDecl(); + return enclosingDecl.getParentPath().indexOf(typeParameterParentDecl) > -1; + }; + + PullTypeResolver.prototype.relateTypeToTypeParametersInEnclosingType = function (expressionType, parameterType, argContext, context) { + if (expressionType && parameterType) { + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + this.relateInifinitelyExpandingTypeToTypeParameters(expressionType, parameterType, argContext, context); + return; + } + } + this.relateTypeToTypeParameters(expressionType, parameterType, argContext, context); + }; + + PullTypeResolver.prototype.relateTypeToTypeParametersWithNewEnclosingTypes = function (expressionType, parameterType, argContext, context) { + var enclosingTypeWalkerStates = context.resetEnclosingTypeWalkerStates(); + this.relateTypeToTypeParameters(expressionType, parameterType, argContext, context); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + }; + + PullTypeResolver.prototype.relateTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { + if (!expressionType || !parameterType) { + return; + } + + if (expressionType.isError()) { + expressionType = this.semanticInfoChain.anyTypeSymbol; + } + + if (parameterType.isTypeParameter()) { + var typeParameter = parameterType; + argContext.addCandidateForInference(typeParameter, expressionType); + return; + } + + if (parameterType.isNamedTypeSymbol() && !parameterType.isGeneric() && !parameterType.getTypeArguments()) { + return; + } + + if (TypeScript.PullInstantiationHelpers.twoTypesAreInstantiationsOfSameNamedGenericType(expressionType, parameterType)) { + this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, argContext, context); + } else { + var symbolsWhenStartedWalkingTypes = context.startWalkingTypes(expressionType, parameterType); + this.relateObjectTypeToTypeParameters(expressionType, parameterType, argContext, context); + context.endWalkingTypes(symbolsWhenStartedWalkingTypes); + } + }; + + PullTypeResolver.prototype.relateTypeArgumentsOfTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { + var parameterSideTypeArguments = parameterType.getTypeArguments(); + var argumentSideTypeArguments = expressionType.getTypeArguments(); + + TypeScript.Debug.assert(parameterSideTypeArguments && argumentSideTypeArguments && parameterSideTypeArguments.length === argumentSideTypeArguments.length); + for (var i = 0; i < parameterSideTypeArguments.length; i++) { + this.relateTypeToTypeParametersWithNewEnclosingTypes(argumentSideTypeArguments[i], parameterSideTypeArguments[i], argContext, context); + } + }; + + PullTypeResolver.prototype.relateInifinitelyExpandingTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { + if (!expressionType || !parameterType) { + return; + } + + var expressionTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(expressionType); + var parameterTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(parameterType); + if (expressionTypeNamedTypeReference !== parameterTypeNamedTypeReference) { + return; + } + + var expressionTypeTypeArguments = expressionType.getTypeArguments(); + var parameterTypeArguments = parameterType.getTypeArguments(); + + if (expressionTypeTypeArguments && parameterTypeArguments && expressionTypeTypeArguments.length === parameterTypeArguments.length) { + for (var i = 0; i < expressionTypeTypeArguments.length; i++) { + this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, argContext, context); + } + } + }; + + PullTypeResolver.prototype.relateFunctionSignatureToTypeParameters = function (expressionSignature, parameterSignature, argContext, context) { + var _this = this; + var expressionReturnType = expressionSignature.returnType; + var parameterReturnType = parameterSignature.returnType; + + parameterSignature.forAllCorrespondingParameterTypesInThisAndOtherSignature(expressionSignature, function (parameterSignatureParameterType, expressionSignatureParameterType, i) { + context.walkParameterTypes(i); + _this.relateTypeToTypeParametersInEnclosingType(expressionSignatureParameterType, parameterSignatureParameterType, argContext, context); + context.postWalkParameterTypes(); + return true; + }); + + context.walkReturnTypes(); + this.relateTypeToTypeParametersInEnclosingType(expressionReturnType, parameterReturnType, argContext, context); + context.postWalkReturnTypes(); + }; + + PullTypeResolver.prototype.relateObjectTypeToTypeParameters = function (objectType, parameterType, argContext, context) { + var parameterTypeMembers = parameterType.getMembers(); + var parameterSignatures; + + var objectMember; + var objectSignatures; + + if (argContext.alreadyRelatingTypes(objectType, parameterType)) { + return; + } + + for (var i = 0; i < parameterTypeMembers.length; i++) { + objectMember = this.getNamedPropertySymbol(parameterTypeMembers[i].name, 68147712 /* SomeValue */, objectType); + if (objectMember) { + this.resolveDeclaredSymbol(objectMember); + this.resolveDeclaredSymbol(parameterTypeMembers[i]); + context.walkMemberTypes(parameterTypeMembers[i].name); + this.relateTypeToTypeParametersInEnclosingType(objectMember.type, parameterTypeMembers[i].type, argContext, context); + context.postWalkMemberTypes(); + } + } + + this.relateSignatureGroupToTypeParameters(objectType.getCallSignatures(), parameterType.getCallSignatures(), 1048576 /* CallSignature */, argContext, context); + + this.relateSignatureGroupToTypeParameters(objectType.getConstructSignatures(), parameterType.getConstructSignatures(), 2097152 /* ConstructSignature */, argContext, context); + + var parameterIndexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(parameterType, context); + var objectIndexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(objectType, context); + var indexSigInfo = context.getBothKindOfIndexSignatures(false, false); + + if (parameterIndexSignatures.stringSignature && objectIndexSignatures.stringSignature) { + context.walkIndexSignatureReturnTypes(indexSigInfo, true, true, true); + this.relateFunctionSignatureToTypeParameters(objectIndexSignatures.stringSignature, parameterIndexSignatures.stringSignature, argContext, context); + context.postWalkIndexSignatureReturnTypes(true); + } + if (parameterIndexSignatures.numericSignature && objectIndexSignatures.numericSignature) { + context.walkIndexSignatureReturnTypes(indexSigInfo, false, false, true); + this.relateFunctionSignatureToTypeParameters(objectIndexSignatures.numericSignature, parameterIndexSignatures.numericSignature, argContext, context); + context.postWalkIndexSignatureReturnTypes(true); + } + }; + + PullTypeResolver.prototype.relateSignatureGroupToTypeParameters = function (argumentSignatures, parameterSignatures, signatureKind, argContext, context) { + for (var i = 0; i < parameterSignatures.length; i++) { + var paramSignature = parameterSignatures[i]; + if (argumentSignatures.length > 0 && paramSignature.isGeneric()) { + paramSignature = this.instantiateSignatureToAny(paramSignature); + } + for (var j = 0; j < argumentSignatures.length; j++) { + var argumentSignature = argumentSignatures[j]; + if (argumentSignature.nonOptionalParamCount > paramSignature.nonOptionalParamCount) { + continue; + } + + if (argumentSignature.isGeneric()) { + argumentSignature = this.instantiateSignatureToAny(argumentSignature); + } + + context.walkSignatures(signatureKind, j, i); + this.relateFunctionSignatureToTypeParameters(argumentSignature, paramSignature, argContext, context); + context.postWalkSignatures(); + } + } + }; + + PullTypeResolver.prototype.alterPotentialGenericFunctionTypeToInstantiatedFunctionTypeForTypeArgumentInference = function (expressionSymbol, context) { + var inferentialType = context.getContextualType(); + TypeScript.Debug.assert(inferentialType); + var expressionType = expressionSymbol.type; + if (this.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers(expressionType, true) && this.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers(inferentialType, false)) { + var genericExpressionSignature = expressionType.getCallSignatures()[0]; + var contextualSignature = inferentialType.getCallSignatures()[0]; + + var instantiatedSignature = this.instantiateSignatureInContext(genericExpressionSignature, contextualSignature, context, true); + if (instantiatedSignature === null) { + return expressionSymbol; + } + + var newType = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + newType.appendCallSignature(instantiatedSignature); + return newType; + } + + return expressionSymbol; + }; + + PullTypeResolver.prototype.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers = function (type, callSignatureShouldBeGeneric) { + TypeScript.Debug.assert(type); + if (type.getCallSignatures().length !== 1) { + return false; + } + + var callSignatureIsGeneric = type.getCallSignatures()[0].isGeneric(); + if (callSignatureIsGeneric !== callSignatureShouldBeGeneric) { + return false; + } + + var typeHasOtherMembers = type.getConstructSignatures().length || type.getIndexSignatures().length || type.getAllMembers(68147712 /* SomeValue */, 0 /* all */).length; + if (typeHasOtherMembers) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.instantiateTypeToAny = function (typeToSpecialize, context) { + var typeParameters = typeToSpecialize.getTypeParameters(); + + if (!typeParameters.length) { + return typeToSpecialize; + } + + var typeArguments = null; + + if (!this._cachedAnyTypeArgs) { + this._cachedAnyTypeArgs = [ + [this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol] + ]; + } + + if (typeParameters.length < this._cachedAnyTypeArgs.length) { + typeArguments = this._cachedAnyTypeArgs[typeParameters.length - 1]; + } else { + typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArguments[typeArguments.length] = this.semanticInfoChain.anyTypeSymbol; + } + } + + var type = this.createInstantiatedType(typeToSpecialize, typeArguments); + + return type; + }; + + PullTypeResolver.prototype.instantiateSignatureToAny = function (signature) { + var typeParameters = signature.getTypeParameters(); + if (!this._cachedAnyTypeArgs) { + this._cachedAnyTypeArgs = [ + [this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol] + ]; + } + + if (typeParameters.length < this._cachedAnyTypeArgs.length) { + var typeArguments = this._cachedAnyTypeArgs[typeParameters.length - 1]; + } else { + var typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArguments[typeArguments.length] = this.semanticInfoChain.anyTypeSymbol; + } + } + + var typeParameterArgumentMap = TypeScript.PullInstantiationHelpers.createTypeParameterArgumentMap(typeParameters, typeArguments); + return this.instantiateSignature(signature, typeParameterArgumentMap); + }; + + PullTypeResolver.typeCheck = function (compilationSettings, semanticInfoChain, document) { + var sourceUnit = document.sourceUnit(); + + var resolver = semanticInfoChain.getResolver(); + var context = new TypeScript.PullTypeResolutionContext(resolver, true, sourceUnit.fileName()); + + if (resolver.canTypeCheckAST(sourceUnit, context)) { + resolver.resolveAST(sourceUnit, false, context); + resolver.validateVariableDeclarationGroups(semanticInfoChain.getDeclForAST(sourceUnit), context); + + while (resolver.typeCheckCallBacks.length) { + var callBack = resolver.typeCheckCallBacks.pop(); + callBack(context); + } + + resolver.processPostTypeCheckWorkItems(context); + } + }; + + PullTypeResolver.prototype.validateVariableDeclarationGroups = function (enclosingDecl, context) { + var _this = this; + this.scanVariableDeclarationGroups(enclosingDecl, function (_) { + }, function (subsequentDecl, firstSymbol) { + if (TypeScript.hasFlag(subsequentDecl.kind, 2048 /* Parameter */) || TypeScript.hasFlag(subsequentDecl.flags, 8388608 /* PropertyParameter */)) { + return; + } + + var boundDeclAST = _this.semanticInfoChain.getASTForDecl(subsequentDecl); + + var symbol = subsequentDecl.getSymbol(); + var symbolType = symbol.type; + var firstSymbolType = firstSymbol.type; + + if (symbolType && firstSymbolType && symbolType !== firstSymbolType && !_this.typesAreIdentical(symbolType, firstSymbolType, context)) { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(boundDeclAST, TypeScript.DiagnosticCode.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, [symbol.getScopedName(), firstSymbolType.toString(firstSymbol), symbolType.toString(symbol)])); + } + }); + }; + + PullTypeResolver.prototype.typeCheckFunctionOverloads = function (funcDecl, context, signature, allSignatures) { + if (!signature) { + var functionSignatureInfo = TypeScript.PullHelpers.getSignatureForFuncDecl(this.semanticInfoChain.getDeclForAST(funcDecl)); + signature = functionSignatureInfo.signature; + allSignatures = functionSignatureInfo.allSignatures; + } + var functionDeclaration = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSymbol = functionDeclaration.getSymbol(); + + var definitionSignature = null; + for (var i = allSignatures.length - 1; i >= 0; i--) { + if (allSignatures[i].isDefinition()) { + definitionSignature = allSignatures[i]; + break; + } + } + + if (!signature.isDefinition()) { + var signatureParentDecl = signature.getDeclarations()[0].getParentDecl(); + for (var i = 0; i < allSignatures.length; i++) { + if (allSignatures[i] === signature) { + break; + } + + var allSignaturesParentDecl = allSignatures[i].getDeclarations()[0].getParentDecl(); + if (allSignaturesParentDecl !== signatureParentDecl) { + continue; + } + + if (this.signaturesAreIdenticalWithNewEnclosingTypes(allSignatures[i], signature, context, false)) { + if (!this.signatureReturnTypesAreIdentical(allSignatures[i], signature, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overloads_cannot_differ_only_by_return_type)); + } else if (funcDecl.kind() === 137 /* ConstructorDeclaration */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_constructor_overload_signature)); + } else if (functionDeclaration.kind === 2097152 /* ConstructSignature */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_overload_construct_signature)); + } else if (functionDeclaration.kind === 1048576 /* CallSignature */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_overload_call_signature)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_overload_signature_for_0, [funcSymbol.getScopedNameEx().toString()])); + } + + break; + } + } + } + + var isConstantOverloadSignature = signature.isStringConstantOverloadSignature(); + if (isConstantOverloadSignature) { + if (signature.isDefinition()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overload_signature_implementation_cannot_use_specialized_type)); + } else { + var foundSubtypeSignature = false; + for (var i = 0; i < allSignatures.length; i++) { + if (allSignatures[i].isDefinition() || allSignatures[i] === signature) { + continue; + } + + if (!allSignatures[i].isResolved) { + this.resolveDeclaredSymbol(allSignatures[i], context); + } + + if (allSignatures[i].isStringConstantOverloadSignature()) { + continue; + } + + if (this.signatureIsAssignableToTarget(signature, allSignatures[i], null, context)) { + foundSubtypeSignature = true; + break; + } + } + + if (!foundSubtypeSignature) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature)); + } + } + } else if (definitionSignature && definitionSignature !== signature) { + var comparisonInfo = new TypeComparisonInfo(); + + if (!definitionSignature.isResolved) { + this.resolveDeclaredSymbol(definitionSignature, context); + } + + if (!this.signatureIsAssignableToTarget(definitionSignature, signature, funcDecl, context, comparisonInfo)) { + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overload_signature_is_not_compatible_with_function_definition_NL_0, [comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overload_signature_is_not_compatible_with_function_definition)); + } + } + } + + var signatureForVisibilityCheck = definitionSignature; + if (!definitionSignature) { + if (allSignatures[0] === signature) { + return; + } + signatureForVisibilityCheck = allSignatures[0]; + } + + if (funcDecl.kind() !== 137 /* ConstructorDeclaration */ && functionDeclaration.kind !== 2097152 /* ConstructSignature */ && signatureForVisibilityCheck && signature !== signatureForVisibilityCheck) { + var errorCode; + + if (signatureForVisibilityCheck.anyDeclHasFlag(2 /* Private */) !== signature.anyDeclHasFlag(2 /* Private */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_public_or_private; + } else if (signatureForVisibilityCheck.anyDeclHasFlag(1 /* Exported */) !== signature.anyDeclHasFlag(1 /* Exported */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_exported_or_not_exported; + } else if (signatureForVisibilityCheck.anyDeclHasFlag(8 /* Ambient */) !== signature.anyDeclHasFlag(8 /* Ambient */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_ambient_or_non_ambient; + } else if (signatureForVisibilityCheck.anyDeclHasFlag(128 /* Optional */) !== signature.anyDeclHasFlag(128 /* Optional */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_optional_or_required; + } + + if (errorCode) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, errorCode)); + } + } + }; + + PullTypeResolver.prototype.checkSymbolPrivacy = function (declSymbol, symbol, privacyErrorReporter) { + if (!symbol || symbol.kind === 2 /* Primitive */) { + return; + } + + if (symbol.isType()) { + var typeSymbol = symbol; + var isNamedType = typeSymbol.isNamedTypeSymbol(); + + if (typeSymbol.isArrayNamedTypeReference()) { + this.checkSymbolPrivacy(declSymbol, typeSymbol.getElementType(), privacyErrorReporter); + return; + } + + if (!isNamedType) { + var typeOfSymbol = typeSymbol.getTypeOfSymbol(); + if (typeOfSymbol) { + this.checkSymbolPrivacy(declSymbol, typeOfSymbol, privacyErrorReporter); + return; + } + } + + if (typeSymbol.inSymbolPrivacyCheck) { + return; + } + + typeSymbol.inSymbolPrivacyCheck = true; + + var typars = typeSymbol.getTypeArgumentsOrTypeParameters(); + if (typars) { + for (var i = 0; i < typars.length; i++) { + this.checkSymbolPrivacy(declSymbol, typars[i], privacyErrorReporter); + } + } + + if (!isNamedType) { + var members = typeSymbol.getMembers(); + for (var i = 0; i < members.length; i++) { + this.checkSymbolPrivacy(declSymbol, members[i].type, privacyErrorReporter); + } + + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getCallSignatures(), privacyErrorReporter); + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getConstructSignatures(), privacyErrorReporter); + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getIndexSignatures(), privacyErrorReporter); + } else if (typeSymbol.kind === 8192 /* TypeParameter */) { + this.checkSymbolPrivacy(declSymbol, typeSymbol.getConstraint(), privacyErrorReporter); + } + + typeSymbol.inSymbolPrivacyCheck = false; + + if (!isNamedType) { + return; + } + } + + if (declSymbol.isExternallyVisible()) { + var symbolIsVisible = symbol.isExternallyVisible(); + + if (symbolIsVisible && symbol.kind !== 8192 /* TypeParameter */) { + var symbolPath = symbol.pathToRoot(); + var declSymbolPath = declSymbol.pathToRoot(); + + if (symbolPath[symbolPath.length - 1].kind === 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1].kind === 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1] !== symbolPath[symbolPath.length - 1]) { + symbolIsVisible = false; + var declSymbolScope = declSymbolPath[declSymbolPath.length - 1]; + for (var i = symbolPath.length - 1; i >= 0; i--) { + var aliasSymbols = symbolPath[i].getExternalAliasedSymbols(declSymbolScope); + if (aliasSymbols) { + symbolIsVisible = true; + aliasSymbols[0].setTypeUsedExternally(); + break; + } + } + symbol = symbolPath[symbolPath.length - 1]; + } + } else if (symbol.kind === 128 /* TypeAlias */) { + var aliasSymbol = symbol; + symbolIsVisible = true; + aliasSymbol.setTypeUsedExternally(); + } + + if (!symbolIsVisible) { + privacyErrorReporter(symbol); + } + } + }; + + PullTypeResolver.prototype.checkTypePrivacyOfSignatures = function (declSymbol, signatures, privacyErrorReporter) { + for (var i = 0; i < signatures.length; i++) { + var signature = signatures[i]; + if (signatures.length > 1 && signature.isDefinition()) { + continue; + } + + var typeParams = signature.getTypeParameters(); + for (var j = 0; j < typeParams.length; j++) { + this.checkSymbolPrivacy(declSymbol, typeParams[j], privacyErrorReporter); + } + + var params = signature.parameters; + for (var j = 0; j < params.length; j++) { + var paramType = params[j].type; + this.checkSymbolPrivacy(declSymbol, paramType, privacyErrorReporter); + } + + var returnType = signature.returnType; + this.checkSymbolPrivacy(declSymbol, returnType, privacyErrorReporter); + } + }; + + PullTypeResolver.prototype.typeParameterOfTypeDeclarationPrivacyErrorReporter = function (classOrInterface, typeParameterAST, typeParameter, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + var messageCode; + + var typeParameters = classOrInterface.kind() === 131 /* ClassDeclaration */ ? classOrInterface.typeParameterList : classOrInterface.typeParameterList; + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_interface_is_using_inaccessible_module_1; + } + } else { + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_interface_has_or_is_using_private_type_1; + } + } + + var messageArguments = [typeParameter.getScopedName(enclosingSymbol, false, true), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeParameterAST, messageCode, messageArguments)); + }; + + PullTypeResolver.prototype.baseListPrivacyErrorReporter = function (classOrInterface, declSymbol, baseAst, isExtendedType, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + var messageCode; + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + if (isExtendedType) { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_extends_class_from_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_implements_interface_from_inaccessible_module_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_interface_0_extends_interface_from_inaccessible_module_1; + } + } else { + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + if (isExtendedType) { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_extends_private_class_1; + } else { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_implements_private_interface_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_interface_0_extends_private_interface_1; + } + } + + var messageArguments = [declSymbol.getScopedName(enclosingSymbol), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseAst, messageCode, messageArguments)); + }; + + PullTypeResolver.prototype.variablePrivacyErrorReporter = function (declAST, declSymbol, symbol, context) { + var typeSymbol = symbol; + var enclosingDecl = this.getEnclosingDecl(declSymbol.getDeclarations()[0]); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + + var isProperty = declSymbol.kind === 4096 /* Property */; + var isPropertyOfClass = false; + var declParent = declSymbol.getContainer(); + if (declParent && (declParent.kind === 8 /* Class */ || declParent.kind === 32768 /* ConstructorMethod */)) { + isPropertyOfClass = true; + } + + var messageCode; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (declSymbol.anyDeclHasFlag(16 /* Static */)) { + messageCode = TypeScript.DiagnosticCode.Public_static_property_0_of_exported_class_is_using_inaccessible_module_1; + } else if (isProperty) { + if (isPropertyOfClass) { + messageCode = TypeScript.DiagnosticCode.Public_property_0_of_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Property_0_of_exported_interface_is_using_inaccessible_module_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_variable_0_is_using_inaccessible_module_1; + } + } else { + if (declSymbol.anyDeclHasFlag(16 /* Static */)) { + messageCode = TypeScript.DiagnosticCode.Public_static_property_0_of_exported_class_has_or_is_using_private_type_1; + } else if (isProperty) { + if (isPropertyOfClass) { + messageCode = TypeScript.DiagnosticCode.Public_property_0_of_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.Property_0_of_exported_interface_has_or_is_using_private_type_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_variable_0_has_or_is_using_private_type_1; + } + } + + var messageArguments = [declSymbol.getScopedName(enclosingSymbol), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(declAST, messageCode, messageArguments)); + }; + + PullTypeResolver.prototype.checkFunctionTypePrivacy = function (funcDeclAST, isStatic, typeParameters, parameters, returnTypeAnnotation, block, context) { + var _this = this; + if (funcDeclAST.kind() === 222 /* FunctionExpression */ || funcDeclAST.kind() === 241 /* FunctionPropertyAssignment */ || (funcDeclAST.kind() === 139 /* GetAccessor */ && funcDeclAST.parent.parent.kind() === 215 /* ObjectLiteralExpression */) || (funcDeclAST.kind() === 140 /* SetAccessor */ && funcDeclAST.parent.parent.kind() === 215 /* ObjectLiteralExpression */)) { + return; + } + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var functionSymbol = functionDecl.getSymbol(); + ; + var functionSignature; + + var isGetter = funcDeclAST.kind() === 139 /* GetAccessor */; + var isSetter = funcDeclAST.kind() === 140 /* SetAccessor */; + var isIndexSignature = functionDecl.kind === 4194304 /* IndexSignature */; + + if (isGetter || isSetter) { + var accessorSymbol = functionSymbol; + functionSignature = (isGetter ? accessorSymbol.getGetter() : accessorSymbol.getSetter()).type.getCallSignatures()[0]; + } else { + if (!functionSymbol) { + var parentDecl = functionDecl.getParentDecl(); + functionSymbol = parentDecl.getSymbol(); + if (functionSymbol && functionSymbol.isType() && !functionSymbol.isNamedTypeSymbol()) { + return; + } + } else if (functionSymbol.kind === 65536 /* Method */ && !isStatic && !functionSymbol.getContainer().isNamedTypeSymbol()) { + return; + } + functionSignature = functionDecl.getSignatureSymbol(); + } + + if (typeParameters && !isGetter && !isSetter && !isIndexSignature && funcDeclAST.kind() !== 137 /* ConstructorDeclaration */) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + var typeParameterAST = typeParameters.typeParameters.nonSeparatorAt(i); + var typeParameter = this.resolveTypeParameterDeclaration(typeParameterAST, context); + this.checkSymbolPrivacy(functionSymbol, typeParameter, function (symbol) { + return _this.functionTypeArgumentArgumentTypePrivacyErrorReporter(funcDeclAST, isStatic, typeParameterAST, typeParameter, symbol, context); + }); + } + } + + if (!isGetter && !isIndexSignature) { + var funcParams = functionSignature.parameters; + for (var i = 0; i < funcParams.length; i++) { + this.checkSymbolPrivacy(functionSymbol, funcParams[i].type, function (symbol) { + return _this.functionArgumentTypePrivacyErrorReporter(funcDeclAST, isStatic, parameters, i, funcParams[i], symbol, context); + }); + } + } + + if (!isSetter) { + this.checkSymbolPrivacy(functionSymbol, functionSignature.returnType, function (symbol) { + return _this.functionReturnTypePrivacyErrorReporter(funcDeclAST, isStatic, returnTypeAnnotation, block, functionSignature.returnType, symbol, context); + }); + } + }; + + PullTypeResolver.prototype.functionTypeArgumentArgumentTypePrivacyErrorReporter = function (declAST, isStatic, typeParameterAST, typeParameter, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(declAST); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + + var isMethod = decl.kind === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.kind === 8 /* Class */ || isStatic)) { + isMethodOfClass = true; + } + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + var messageCode; + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_function_is_using_inaccessible_module_1; + } + } else { + if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_function_has_or_is_using_private_type_1; + } + } + + if (messageCode) { + var messageArgs = [typeParameter.getScopedName(enclosingSymbol, false, true), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeParameterAST, messageCode, messageArgs)); + } + }; + + PullTypeResolver.prototype.functionArgumentTypePrivacyErrorReporter = function (declAST, isStatic, parameters, argIndex, paramSymbol, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(declAST); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + + var isGetter = declAST.kind() === 139 /* GetAccessor */; + var isSetter = declAST.kind() === 140 /* SetAccessor */; + var isMethod = decl.kind === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.kind === 8 /* Class */ || isStatic)) { + isMethodOfClass = true; + } + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + var messageCode; + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (declAST.kind() === 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_from_exported_class_is_using_inaccessible_module_1; + } else if (isSetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_property_setter_from_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_property_setter_from_exported_class_is_using_inaccessible_module_1; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1; + } + } else if (!isGetter) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_exported_function_is_using_inaccessible_module_1; + } + } else { + if (declAST.kind() === 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_type_1; + } else if (isSetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_type_1; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1; + } + } else if (!isGetter && decl.kind !== 4194304 /* IndexSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_exported_function_has_or_is_using_private_type_1; + } + } + + if (messageCode) { + var parameter = parameters.astAt(argIndex); + + var messageArgs = [paramSymbol.getScopedName(enclosingSymbol), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(parameter, messageCode, messageArgs)); + } + }; + + PullTypeResolver.prototype.functionReturnTypePrivacyErrorReporter = function (declAST, isStatic, returnTypeAnnotation, block, funcReturnType, symbol, context) { + var _this = this; + var decl = this.semanticInfoChain.getDeclForAST(declAST); + var enclosingDecl = this.getEnclosingDecl(decl); + + var isGetter = declAST.kind() === 139 /* GetAccessor */; + var isSetter = declAST.kind() === 140 /* SetAccessor */; + var isMethod = decl.kind === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.kind === 8 /* Class */ || isStatic)) { + isMethodOfClass = true; + } + + var messageCode = null; + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (isGetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module_0; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_0; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module_0; + } else if (decl.kind === 4194304 /* IndexSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module_0; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module_0; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_method_from_exported_class_is_using_inaccessible_module_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_method_from_exported_interface_is_using_inaccessible_module_0; + } + } else if (!isSetter && declAST.kind() !== 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_exported_function_is_using_inaccessible_module_0; + } + } else { + if (isGetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type_0; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_0; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type_0; + } else if (decl.kind === 4194304 /* IndexSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type_0; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type_0; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_method_from_exported_class_has_or_is_using_private_type_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_method_from_exported_interface_has_or_is_using_private_type_0; + } + } else if (!isSetter && declAST.kind() !== 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_exported_function_has_or_is_using_private_type_0; + } + } + + if (messageCode) { + var messageArguments = [typeSymbolName]; + var reportOnFuncDecl = false; + + if (returnTypeAnnotation) { + var returnExpressionSymbol = this.resolveTypeReference(returnTypeAnnotation, context); + + if (TypeScript.PullHelpers.typeSymbolsAreIdentical(returnExpressionSymbol, funcReturnType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, messageCode, messageArguments)); + } + } + + if (block) { + var reportErrorOnReturnExpressions = function (ast, walker) { + var go = true; + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + go = false; + break; + + case 150 /* ReturnStatement */: + var returnStatement = ast; + var returnExpressionSymbol = _this.resolveAST(returnStatement.expression, false, context).type; + + if (TypeScript.PullHelpers.typeSymbolsAreIdentical(returnExpressionSymbol, funcReturnType)) { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(returnStatement, messageCode, messageArguments)); + } else { + reportOnFuncDecl = true; + } + go = false; + break; + + default: + break; + } + + walker.options.goChildren = go; + return ast; + }; + + TypeScript.getAstWalkerFactory().walk(block, reportErrorOnReturnExpressions); + } + + if (reportOnFuncDecl) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(declAST, messageCode, messageArguments)); + } + } + }; + + PullTypeResolver.prototype.enclosingClassIsDerived = function (classDecl) { + TypeScript.Debug.assert(classDecl.kind === 8 /* Class */); + + var classSymbol = classDecl.getSymbol(); + return classSymbol.getExtendedTypes().length > 0; + }; + + PullTypeResolver.prototype.isSuperInvocationExpression = function (ast) { + if (ast.kind() === 213 /* InvocationExpression */) { + var invocationExpression = ast; + if (invocationExpression.expression.kind() === 50 /* SuperKeyword */) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.isSuperInvocationExpressionStatement = function (node) { + if (node && node.kind() === 149 /* ExpressionStatement */) { + var expressionStatement = node; + if (this.isSuperInvocationExpression(expressionStatement.expression)) { + return true; + } + } + return false; + }; + + PullTypeResolver.prototype.getFirstStatementOfBlockOrNull = function (block) { + if (block && block.statements && block.statements.childCount() > 0) { + return block.statements.childAt(0); + } + + return null; + }; + + PullTypeResolver.prototype.superCallMustBeFirstStatementInConstructor = function (constructorDecl) { + TypeScript.Debug.assert(constructorDecl.kind === 32768 /* ConstructorMethod */); + + if (constructorDecl) { + var enclosingClass = constructorDecl.getParentDecl(); + + var classSymbol = enclosingClass.getSymbol(); + if (classSymbol.getExtendedTypes().length === 0) { + return false; + } + + var classMembers = classSymbol.getMembers(); + for (var i = 0, n1 = classMembers.length; i < n1; i++) { + var member = classMembers[i]; + + if (member.kind === 4096 /* Property */) { + var declarations = member.getDeclarations(); + for (var j = 0, n2 = declarations.length; j < n2; j++) { + var declaration = declarations[j]; + var ast = this.semanticInfoChain.getASTForDecl(declaration); + if (ast.kind() === 242 /* Parameter */) { + return true; + } + + if (ast.kind() === 136 /* MemberVariableDeclaration */) { + var variableDeclarator = ast; + if (variableDeclarator.variableDeclarator.equalsValueClause) { + return true; + } + } + } + } + } + } + + return false; + }; + + PullTypeResolver.prototype.checkForThisCaptureInArrowFunction = function (expression) { + var enclosingDecl = this.getEnclosingDeclForAST(expression); + + var declPath = enclosingDecl.getParentPath(); + + if (declPath.length) { + var inArrowFunction = false; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.kind; + var declFlags = decl.flags; + + if (declKind === 131072 /* FunctionExpression */ && TypeScript.hasFlag(declFlags, 8192 /* ArrowFunction */)) { + inArrowFunction = true; + continue; + } + + if (inArrowFunction) { + if (declKind === 16384 /* Function */ || declKind === 65536 /* Method */ || declKind === 32768 /* ConstructorMethod */ || declKind === 262144 /* GetAccessor */ || declKind === 524288 /* SetAccessor */ || declKind === 131072 /* FunctionExpression */ || declKind === 8 /* Class */ || declKind === 4 /* Container */ || declKind === 32 /* DynamicModule */ || declKind === 1 /* Script */) { + decl.setFlags(decl.flags | 262144 /* MustCaptureThis */); + + if (declKind === 8 /* Class */) { + var constructorSymbol = decl.getSymbol().getConstructorMethod(); + var constructorDecls = constructorSymbol.getDeclarations(); + for (var i = 0; i < constructorDecls.length; i++) { + constructorDecls[i].flags = constructorDecls[i].flags | 262144 /* MustCaptureThis */; + } + } + break; + } + } else if (declKind === 16384 /* Function */ || declKind === 131072 /* FunctionExpression */) { + break; + } + } + } + }; + + PullTypeResolver.prototype.typeCheckMembersAgainstIndexer = function (containerType, containerTypeDecl, context) { + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(containerType, context); + var stringSignature = indexSignatures.stringSignature; + var numberSignature = indexSignatures.numericSignature; + + if (stringSignature || numberSignature) { + var members = containerTypeDecl.getChildDecls(); + for (var i = 0; i < members.length; i++) { + var member = members[i]; + if ((member.name || (member.kind === 4096 /* Property */ && member.name === "")) && member.kind !== 32768 /* ConstructorMethod */ && !TypeScript.hasFlag(member.flags, 16 /* Static */)) { + var memberSymbol = member.getSymbol(); + var relevantSignature = this.determineRelevantIndexerForMember(memberSymbol, numberSignature, stringSignature); + if (relevantSignature) { + var comparisonInfo = new TypeComparisonInfo(); + if (!this.sourceIsAssignableToTarget(memberSymbol.type, relevantSignature.returnType, member.ast(), context, comparisonInfo)) { + this.reportErrorThatMemberIsNotSubtypeOfIndexer(memberSymbol, relevantSignature, member.ast(), context, comparisonInfo); + } + } + } + } + } + }; + + PullTypeResolver.prototype.determineRelevantIndexerForMember = function (member, numberIndexSignature, stringIndexSignature) { + if (numberIndexSignature && TypeScript.PullHelpers.isNameNumeric(member.name)) { + return numberIndexSignature; + } else if (stringIndexSignature) { + return stringIndexSignature; + } + + return null; + }; + + PullTypeResolver.prototype.reportErrorThatMemberIsNotSubtypeOfIndexer = function (member, indexSignature, astForError, context, comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(astForError); + if (indexSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol) { + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); + } + } else { + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_assignable_to_string_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_assignable_to_string_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); + } + } + }; + + PullTypeResolver.prototype.typeCheckIfTypeMemberPropertyOkToOverride = function (typeSymbol, extendedType, typeMember, extendedTypeMember, enclosingDecl, comparisonInfo) { + if (!typeSymbol.isClass()) { + return true; + } + + var typeMemberKind = typeMember.kind; + var extendedMemberKind = extendedTypeMember.kind; + + if (typeMemberKind === extendedMemberKind) { + return true; + } + + var errorCode; + if (typeMemberKind === 4096 /* Property */) { + if (typeMember.isAccessor()) { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } else { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + } else if (typeMemberKind === 65536 /* Method */) { + if (extendedTypeMember.isAccessor()) { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } else { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + + var message = TypeScript.getDiagnosticMessage(errorCode, [typeSymbol.toString(), typeMember.getScopedNameEx().toString(), extendedType.toString()]); + comparisonInfo.addMessage(message); + return false; + }; + + PullTypeResolver.prototype.typeCheckIfTypeExtendsType = function (classOrInterface, name, typeSymbol, extendedType, enclosingDecl, context) { + var typeMembers = typeSymbol.getMembers(); + + var comparisonInfo = new TypeComparisonInfo(); + var foundError = false; + var foundError1 = false; + var foundError2 = false; + + for (var i = 0; i < typeMembers.length; i++) { + var propName = typeMembers[i].name; + var extendedTypeProp = extendedType.findMember(propName, true); + if (extendedTypeProp) { + this.resolveDeclaredSymbol(extendedTypeProp, context); + foundError1 = !this.typeCheckIfTypeMemberPropertyOkToOverride(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, enclosingDecl, comparisonInfo); + + if (!foundError1) { + foundError2 = !this.sourcePropertyIsAssignableToTargetProperty(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, classOrInterface, context, comparisonInfo); + } + + if (foundError1 || foundError2) { + foundError = true; + break; + } + } + } + + if (!foundError && typeSymbol.hasOwnCallSignatures()) { + foundError = !this.sourceCallSignaturesAreAssignableToTargetCallSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + } + + if (!foundError && typeSymbol.hasOwnConstructSignatures()) { + foundError = !this.sourceConstructSignaturesAreAssignableToTargetConstructSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + } + + if (!foundError && typeSymbol.hasOwnIndexSignatures()) { + foundError = !this.sourceIndexSignaturesAreAssignableToTargetIndexSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + } + + if (!foundError && typeSymbol.isClass()) { + var typeConstructorType = typeSymbol.getConstructorMethod().type; + var typeConstructorTypeMembers = typeConstructorType.getMembers(); + if (typeConstructorTypeMembers.length) { + var extendedConstructorType = extendedType.getConstructorMethod().type; + var comparisonInfoForPropTypeCheck = new TypeComparisonInfo(comparisonInfo); + + for (var i = 0; i < typeConstructorTypeMembers.length; i++) { + var propName = typeConstructorTypeMembers[i].name; + var extendedConstructorTypeProp = extendedConstructorType.findMember(propName, true); + if (extendedConstructorTypeProp) { + if (!extendedConstructorTypeProp.isResolved) { + this.resolveDeclaredSymbol(extendedConstructorTypeProp, context); + } + + if (!this.sourcePropertyIsAssignableToTargetProperty(typeConstructorType, extendedConstructorType, typeConstructorTypeMembers[i], extendedConstructorTypeProp, classOrInterface, context, comparisonInfo)) { + foundError = true; + break; + } + } + } + } + } + + if (foundError) { + var errorCode; + if (typeSymbol.isClass()) { + errorCode = TypeScript.DiagnosticCode.Class_0_cannot_extend_class_1_NL_2; + } else { + if (extendedType.isClass()) { + errorCode = TypeScript.DiagnosticCode.Interface_0_cannot_extend_class_1_NL_2; + } else { + errorCode = TypeScript.DiagnosticCode.Interface_0_cannot_extend_interface_1_NL_2; + } + } + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, errorCode, [typeSymbol.getScopedName(), extendedType.getScopedName(), comparisonInfo.message])); + } + }; + + PullTypeResolver.prototype.typeCheckIfClassImplementsType = function (classDecl, classSymbol, implementedType, enclosingDecl, context) { + var comparisonInfo = new TypeComparisonInfo(); + var foundError = !this.sourceMembersAreAssignableToTargetMembers(classSymbol, implementedType, classDecl, context, comparisonInfo); + if (!foundError) { + foundError = !this.sourceCallSignaturesAreAssignableToTargetCallSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + if (!foundError) { + foundError = !this.sourceConstructSignaturesAreAssignableToTargetConstructSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + if (!foundError) { + foundError = !this.sourceIndexSignaturesAreAssignableToTargetIndexSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + } + } + } + + if (foundError) { + var enclosingSymbol = this.getEnclosingSymbolForAST(classDecl); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(classDecl.identifier, TypeScript.DiagnosticCode.Class_0_declares_interface_1_but_does_not_implement_it_NL_2, [classSymbol.getScopedName(enclosingSymbol), implementedType.getScopedName(enclosingSymbol), comparisonInfo.message])); + } + }; + + PullTypeResolver.prototype.computeValueSymbolFromAST = function (valueDeclAST, context) { + var prevInTypeCheck = context.inTypeCheck; + context.inTypeCheck = false; + + var typeSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(valueDeclAST); + + if (valueDeclAST.kind() == 11 /* IdentifierName */) { + var valueSymbol = this.computeNameExpression(valueDeclAST, context); + } else { + TypeScript.Debug.assert(valueDeclAST.kind() == 121 /* QualifiedName */); + var qualifiedName = valueDeclAST; + + var lhs = this.computeValueSymbolFromAST(qualifiedName.left, context); + var valueSymbol = this.computeDottedNameExpressionFromLHS(lhs.symbol, qualifiedName.left, qualifiedName.right, context, false); + } + var valueSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(valueDeclAST); + + this.semanticInfoChain.setAliasSymbolForAST(valueDeclAST, typeSymbolAlias); + context.inTypeCheck = prevInTypeCheck; + + return { symbol: valueSymbol, alias: valueSymbolAlias }; + }; + + PullTypeResolver.prototype.hasClassTypeSymbolConflictAsValue = function (baseDeclAST, typeSymbol, enclosingDecl, context) { + var typeSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(baseDeclAST); + + var valueDeclAST = baseDeclAST.kind() == 126 /* GenericType */ ? baseDeclAST.name : baseDeclAST; + var valueSymbolInfo = this.computeValueSymbolFromAST(valueDeclAST, context); + var valueSymbol = valueSymbolInfo.symbol; + var valueSymbolAlias = valueSymbolInfo.alias; + + if (typeSymbolAlias && valueSymbolAlias) { + return typeSymbolAlias !== valueSymbolAlias; + } + + if (!valueSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */)) { + return true; + } + + var associatedContainerType = valueSymbol.type ? valueSymbol.type.getAssociatedContainerType() : null; + + if (associatedContainerType) { + return associatedContainerType !== typeSymbol.getRootSymbol(); + } + + return true; + }; + + PullTypeResolver.prototype.typeCheckBase = function (classOrInterface, name, typeSymbol, baseDeclAST, isExtendedType, enclosingDecl, context) { + var _this = this; + var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); + + var baseType = this.resolveTypeReference(baseDeclAST, context).type; + + if (!baseType) { + return; + } + + var typeDeclIsClass = typeSymbol.isClass(); + + if (!typeSymbol.isValidBaseKind(baseType, isExtendedType)) { + if (!baseType.isError()) { + if (isExtendedType) { + if (typeDeclIsClass) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.A_class_may_only_extend_another_class)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.An_interface_may_only_extend_another_class_or_interface)); + } + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.A_class_may_only_implement_another_class_or_interface)); + } + } + return; + } else if (typeDeclIsClass && isExtendedType) { + if (this.hasClassTypeSymbolConflictAsValue(baseDeclAST, baseType, enclosingDecl, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_1, [TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(baseDeclAST.kind() == 126 /* GenericType */ ? baseDeclAST.name : baseDeclAST), baseType.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + } + } + + if (baseType.hasBase(typeSymbol)) { + typeSymbol.setHasBaseTypeConflict(); + baseType.setHasBaseTypeConflict(); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, typeDeclIsClass ? TypeScript.DiagnosticCode.Class_0_is_recursively_referenced_as_a_base_type_of_itself : TypeScript.DiagnosticCode.Interface_0_is_recursively_referenced_as_a_base_type_of_itself, [typeSymbol.getScopedName()])); + return; + } + + if (isExtendedType) { + this.typeCheckCallBacks.push(function (context) { + return _this.typeCheckIfTypeExtendsType(classOrInterface, name, typeSymbol, baseType, enclosingDecl, context); + }); + } else { + TypeScript.Debug.assert(classOrInterface.kind() === 131 /* ClassDeclaration */); + + this.typeCheckCallBacks.push(function (context) { + return _this.typeCheckIfClassImplementsType(classOrInterface, typeSymbol, baseType, enclosingDecl, context); + }); + } + + this.checkSymbolPrivacy(typeSymbol, baseType, function (errorSymbol) { + return _this.baseListPrivacyErrorReporter(classOrInterface, typeSymbol, baseDeclAST, isExtendedType, errorSymbol, context); + }); + }; + + PullTypeResolver.prototype.typeCheckBases = function (classOrInterface, name, heritageClauses, typeSymbol, enclosingDecl, context) { + var _this = this; + var extendsClause = TypeScript.ASTHelpers.getExtendsHeritageClause(heritageClauses); + var implementsClause = TypeScript.ASTHelpers.getImplementsHeritageClause(heritageClauses); + if (!extendsClause && !implementsClause) { + return; + } + + if (extendsClause) { + for (var i = 0; i < extendsClause.typeNames.nonSeparatorCount(); i++) { + this.typeCheckBase(classOrInterface, name, typeSymbol, extendsClause.typeNames.nonSeparatorAt(i), true, enclosingDecl, context); + } + } + + if (typeSymbol.isClass()) { + if (implementsClause) { + for (var i = 0; i < implementsClause.typeNames.nonSeparatorCount(); i++) { + this.typeCheckBase(classOrInterface, name, typeSymbol, implementsClause.typeNames.nonSeparatorAt(i), false, enclosingDecl, context); + } + } + } else if (extendsClause && !typeSymbol.hasBaseTypeConflict() && typeSymbol.getExtendedTypes().length > 1) { + var firstInterfaceASTWithExtendsClause = TypeScript.ArrayUtilities.firstOrDefault(typeSymbol.getDeclarations(), function (decl) { + return decl.ast().heritageClauses !== null; + }).ast(); + if (classOrInterface === firstInterfaceASTWithExtendsClause) { + this.typeCheckCallBacks.push(function (context) { + _this.checkTypeCompatibilityBetweenBases(classOrInterface.identifier, typeSymbol, context); + }); + } + } + }; + + PullTypeResolver.prototype.checkTypeCompatibilityBetweenBases = function (name, typeSymbol, context) { + var derivedIndexSignatures = typeSymbol.getOwnIndexSignatures(); + + var inheritedMembersMap = TypeScript.createIntrinsicsObject(); + var inheritedIndexSignatures = new InheritedIndexSignatureInfo(); + + var typeHasOwnNumberIndexer = false; + var typeHasOwnStringIndexer = false; + + if (typeSymbol.hasOwnIndexSignatures()) { + var ownIndexSignatures = typeSymbol.getOwnIndexSignatures(); + for (var i = 0; i < ownIndexSignatures.length; i++) { + if (ownIndexSignatures[i].parameters[0].type === this.semanticInfoChain.numberTypeSymbol) { + typeHasOwnNumberIndexer = true; + } else { + typeHasOwnStringIndexer = true; + } + } + } + var baseTypes = typeSymbol.getExtendedTypes(); + for (var i = 0; i < baseTypes.length; i++) { + if (this.checkNamedPropertyIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedMembersMap, context) || this.checkIndexSignatureIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedIndexSignatures, typeHasOwnNumberIndexer, typeHasOwnStringIndexer, context)) { + return; + } + } + + if (this.checkThatInheritedNumberSignatureIsSubtypeOfInheritedStringSignature(name, typeSymbol, inheritedIndexSignatures, context)) { + return; + } + + this.checkInheritedMembersAgainstInheritedIndexSignatures(name, typeSymbol, inheritedIndexSignatures, inheritedMembersMap, context); + }; + + PullTypeResolver.prototype.checkNamedPropertyIdentityBetweenBases = function (interfaceName, interfaceSymbol, baseTypeSymbol, inheritedMembersMap, context) { + var baseMembers = baseTypeSymbol.getAllMembers(4096 /* Property */ | 65536 /* Method */, 0 /* all */); + for (var i = 0; i < baseMembers.length; i++) { + var member = baseMembers[i]; + var memberName = member.name; + + if (interfaceSymbol.findMember(memberName, false)) { + continue; + } + + this.resolveDeclaredSymbol(member, context); + + if (inheritedMembersMap[memberName]) { + var prevMember = inheritedMembersMap[memberName]; + if (prevMember.baseOrigin !== baseTypeSymbol && !this.propertiesAreIdenticalWithNewEnclosingTypes(baseTypeSymbol, prevMember.baseOrigin, member, prevMember.memberSymbol, context)) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Named_properties_0_of_types_1_and_2_are_not_identical, [memberName, prevMember.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), prevMember.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); + return true; + } + } else { + inheritedMembersMap[memberName] = new MemberWithBaseOrigin(member, baseTypeSymbol); + } + } + + return false; + }; + + PullTypeResolver.prototype.checkIndexSignatureIdentityBetweenBases = function (interfaceName, interfaceSymbol, baseTypeSymbol, allInheritedSignatures, derivedTypeHasOwnNumberSignature, derivedTypeHasOwnStringSignature, context) { + if (derivedTypeHasOwnNumberSignature && derivedTypeHasOwnStringSignature) { + return false; + } + + var indexSignaturesFromThisBaseType = baseTypeSymbol.getIndexSignatures(); + for (var i = 0; i < indexSignaturesFromThisBaseType.length; i++) { + var currentInheritedSignature = indexSignaturesFromThisBaseType[i]; + + var parameterTypeIsString = currentInheritedSignature.parameters[0].type === this.semanticInfoChain.stringTypeSymbol; + var parameterTypeIsNumber = currentInheritedSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol; + + if (parameterTypeIsString && derivedTypeHasOwnStringSignature || parameterTypeIsNumber && derivedTypeHasOwnNumberSignature) { + continue; + } + + if (parameterTypeIsString) { + if (allInheritedSignatures.stringSignatureWithBaseOrigin) { + if (allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.stringSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType, context)) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_string_indexer_of_types_0_and_1_are_not_identical, [allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); + return true; + } + } else { + allInheritedSignatures.stringSignatureWithBaseOrigin = new SignatureWithBaseOrigin(currentInheritedSignature, baseTypeSymbol); + } + } else if (parameterTypeIsNumber) { + if (allInheritedSignatures.numberSignatureWithBaseOrigin) { + if (allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.numberSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType, context)) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_number_indexer_of_types_0_and_1_are_not_identical, [allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); + return true; + } + } else { + allInheritedSignatures.numberSignatureWithBaseOrigin = new SignatureWithBaseOrigin(currentInheritedSignature, baseTypeSymbol); + } + } + } + + return false; + }; + + PullTypeResolver.prototype.checkInheritedMembersAgainstInheritedIndexSignatures = function (interfaceName, interfaceSymbol, inheritedIndexSignatures, inheritedMembers, context) { + if (!inheritedIndexSignatures.stringSignatureWithBaseOrigin && !inheritedIndexSignatures.numberSignatureWithBaseOrigin) { + return false; + } + + var comparisonInfo = new TypeComparisonInfo(); + var stringSignature = inheritedIndexSignatures.stringSignatureWithBaseOrigin && inheritedIndexSignatures.stringSignatureWithBaseOrigin.signature; + var numberSignature = inheritedIndexSignatures.numberSignatureWithBaseOrigin && inheritedIndexSignatures.numberSignatureWithBaseOrigin.signature; + for (var memberName in inheritedMembers) { + var memberWithBaseOrigin = inheritedMembers[memberName]; + if (!memberWithBaseOrigin) { + continue; + } + + var relevantSignature = this.determineRelevantIndexerForMember(memberWithBaseOrigin.memberSymbol, numberSignature, stringSignature); + if (!relevantSignature) { + continue; + } + + var relevantSignatureIsNumberSignature = relevantSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol; + var signatureBaseOrigin = relevantSignatureIsNumberSignature ? inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin : inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin; + + if (signatureBaseOrigin === memberWithBaseOrigin.baseOrigin) { + continue; + } + + var memberIsSubtype = this.sourceIsAssignableToTarget(memberWithBaseOrigin.memberSymbol.type, relevantSignature.returnType, interfaceName, context, comparisonInfo); + + if (!memberIsSubtype) { + var enclosingSymbol = this.getEnclosingSymbolForAST(interfaceName); + if (relevantSignatureIsNumberSignature) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_assignable_to_number_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(enclosingSymbol), memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); + } else { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_assignable_to_string_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(enclosingSymbol), memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); + } + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.checkThatInheritedNumberSignatureIsSubtypeOfInheritedStringSignature = function (interfaceName, interfaceSymbol, inheritedIndexSignatures, context) { + if (inheritedIndexSignatures.numberSignatureWithBaseOrigin && inheritedIndexSignatures.stringSignatureWithBaseOrigin) { + if (inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin === inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin) { + return false; + } + + var comparisonInfo = new TypeComparisonInfo(); + var signatureIsSubtype = this.sourceIsAssignableToTarget(inheritedIndexSignatures.numberSignatureWithBaseOrigin.signature.returnType, inheritedIndexSignatures.stringSignatureWithBaseOrigin.signature.returnType, interfaceName, context, comparisonInfo); + + if (!signatureIsSubtype) { + var enclosingSymbol = this.getEnclosingSymbolForAST(interfaceName); + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_number_indexer_in_type_0_is_not_assignable_to_string_indexer_type_in_type_1_NL_2, [ + inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), + inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [ + interfaceSymbol.getDisplayName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), + inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.checkAssignability = function (ast, source, target, context) { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(source, target, ast, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)])); + } + } + }; + + PullTypeResolver.prototype.isReference = function (ast, astSymbol) { + if (ast.kind() === 217 /* ParenthesizedExpression */) { + return this.isReference(ast.expression, astSymbol); + } + + if (ast.kind() !== 11 /* IdentifierName */ && ast.kind() !== 212 /* MemberAccessExpression */ && ast.kind() !== 221 /* ElementAccessExpression */) { + return false; + } + + if (ast.kind() === 11 /* IdentifierName */) { + if (astSymbol.kind === 512 /* Variable */ && astSymbol.anyDeclHasFlag(4096 /* Enum */)) { + return false; + } + + if (astSymbol.kind === 512 /* Variable */ && astSymbol.anyDeclHasFlag(102400 /* SomeInitializedModule */)) { + return false; + } + + if (astSymbol.kind === 32768 /* ConstructorMethod */ || astSymbol.kind === 16384 /* Function */) { + return false; + } + } + + if (ast.kind() === 212 /* MemberAccessExpression */ && astSymbol.kind === 67108864 /* EnumMember */) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.checkForSuperMemberAccess = function (expression, name, resolvedName, context) { + if (resolvedName) { + if (expression.kind() === 50 /* SuperKeyword */ && !resolvedName.isError() && resolvedName.kind !== 65536 /* Method */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword)); + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.getEnclosingDeclForAST = function (ast) { + return this.semanticInfoChain.getEnclosingDecl(ast); + }; + + PullTypeResolver.prototype.getEnclosingSymbolForAST = function (ast) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + return enclosingDecl ? enclosingDecl.getSymbol() : null; + }; + + PullTypeResolver.prototype.checkForPrivateMemberAccess = function (name, expressionType, resolvedName, context) { + if (resolvedName) { + if (resolvedName.anyDeclHasFlag(2 /* Private */)) { + var memberContainer = resolvedName.getContainer(); + if (memberContainer && memberContainer.kind === 33554432 /* ConstructorType */) { + memberContainer = memberContainer.getAssociatedContainerType(); + } + + if (memberContainer && memberContainer.isClass()) { + var memberClass = memberContainer.getDeclarations()[0].ast(); + TypeScript.Debug.assert(memberClass); + + var containingClass = this.getEnclosingClassDeclaration(name); + + if (!containingClass || containingClass !== memberClass) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode._0_1_is_inaccessible, [memberContainer.toString(null, false), name.text()])); + return true; + } + } + } + } + + return false; + }; + + PullTypeResolver.prototype.instantiateType = function (type, typeParameterArgumentMap) { + if (type.isPrimitive()) { + return type; + } + + if (type.isError()) { + return type; + } + + if (typeParameterArgumentMap[type.pullSymbolID]) { + return typeParameterArgumentMap[type.pullSymbolID]; + } + + type._resolveDeclaredSymbol(); + if (type.isTypeParameter()) { + return this.instantiateTypeParameter(type, typeParameterArgumentMap); + } + + if (type.wrapsSomeTypeParameter(typeParameterArgumentMap)) { + return TypeScript.PullInstantiatedTypeReferenceSymbol.create(this, type, typeParameterArgumentMap); + } + + return type; + }; + + PullTypeResolver.prototype.instantiateTypeParameter = function (typeParameter, typeParameterArgumentMap) { + var constraint = typeParameter.getConstraint(); + if (!constraint) { + return typeParameter; + } + + var instantiatedConstraint = this.instantiateType(constraint, typeParameterArgumentMap); + + if (instantiatedConstraint == constraint) { + return typeParameter; + } + + var rootTypeParameter = typeParameter.getRootSymbol(); + var instantiation = rootTypeParameter.getSpecialization([instantiatedConstraint]); + if (instantiation) { + return instantiation; + } + + instantiation = new TypeScript.PullInstantiatedTypeParameterSymbol(rootTypeParameter, instantiatedConstraint); + return instantiation; + }; + + PullTypeResolver.prototype.instantiateSignature = function (signature, typeParameterArgumentMap) { + if (!signature.wrapsSomeTypeParameter(typeParameterArgumentMap)) { + return signature; + } + + var rootSignature = signature.getRootSymbol(); + var mutableTypeParameterMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(typeParameterArgumentMap); + TypeScript.PullInstantiationHelpers.instantiateTypeArgument(this, signature, mutableTypeParameterMap); + + var instantiatedSignature = rootSignature.getSpecialization(mutableTypeParameterMap.typeParameterArgumentMap); + if (instantiatedSignature) { + return instantiatedSignature; + } + + TypeScript.PullInstantiationHelpers.cleanUpTypeArgumentMap(signature, mutableTypeParameterMap); + typeParameterArgumentMap = mutableTypeParameterMap.typeParameterArgumentMap; + + instantiatedSignature = new TypeScript.PullInstantiatedSignatureSymbol(rootSignature, typeParameterArgumentMap); + + instantiatedSignature.returnType = this.instantiateType((rootSignature.returnType || this.semanticInfoChain.anyTypeSymbol), typeParameterArgumentMap); + instantiatedSignature.functionType = this.instantiateType(rootSignature.functionType, typeParameterArgumentMap); + + var parameters = rootSignature.parameters; + var parameter = null; + + if (parameters) { + for (var j = 0; j < parameters.length; j++) { + parameter = new TypeScript.PullSymbol(parameters[j].name, 2048 /* Parameter */); + parameter.setRootSymbol(parameters[j]); + + if (parameters[j].isOptional) { + parameter.isOptional = true; + } + if (parameters[j].isVarArg) { + parameter.isVarArg = true; + instantiatedSignature.hasVarArgs = true; + } + instantiatedSignature.addParameter(parameter, parameter.isOptional); + + parameter.type = this.instantiateType(parameters[j].type, typeParameterArgumentMap); + } + } + + return instantiatedSignature; + }; + PullTypeResolver.globalTypeCheckPhase = 0; + return PullTypeResolver; + })(); + TypeScript.PullTypeResolver = PullTypeResolver; + + var TypeComparisonInfo = (function () { + function TypeComparisonInfo(sourceComparisonInfo, useSameIndent) { + this.onlyCaptureFirstError = false; + this.flags = 0 /* SuccessfulComparison */; + this.message = ""; + this.stringConstantVal = null; + this.indent = 1; + if (sourceComparisonInfo) { + this.flags = sourceComparisonInfo.flags; + this.onlyCaptureFirstError = sourceComparisonInfo.onlyCaptureFirstError; + this.stringConstantVal = sourceComparisonInfo.stringConstantVal; + this.indent = sourceComparisonInfo.indent; + if (!useSameIndent) { + this.indent++; + } + } + } + TypeComparisonInfo.prototype.indentString = function () { + var result = ""; + + for (var i = 0; i < this.indent; i++) { + result += "\t"; + } + + return result; + }; + + TypeComparisonInfo.prototype.addMessage = function (message) { + if (!this.onlyCaptureFirstError && this.message) { + this.message = this.message + TypeScript.newLine() + this.indentString() + message; + } else { + this.message = this.indentString() + message; + } + }; + return TypeComparisonInfo; + })(); + TypeScript.TypeComparisonInfo = TypeComparisonInfo; + + function getPropertyAssignmentNameTextFromIdentifier(identifier) { + if (identifier.kind() === 11 /* IdentifierName */) { + return { actualText: identifier.text(), memberName: identifier.valueText() }; + } else if (identifier.kind() === 14 /* StringLiteral */) { + return { actualText: identifier.text(), memberName: identifier.valueText() }; + } else if (identifier.kind() === 13 /* NumericLiteral */) { + return { actualText: identifier.text(), memberName: identifier.valueText() }; + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + TypeScript.getPropertyAssignmentNameTextFromIdentifier = getPropertyAssignmentNameTextFromIdentifier; + + function isTypesOnlyLocation(ast) { + while (ast && ast.parent) { + switch (ast.parent.kind()) { + case 244 /* TypeAnnotation */: + return true; + case 127 /* TypeQuery */: + return false; + case 125 /* ConstructorType */: + var constructorType = ast.parent; + if (constructorType.type === ast) { + return true; + } + break; + case 123 /* FunctionType */: + var functionType = ast.parent; + if (functionType.type === ast) { + return true; + } + break; + case 239 /* Constraint */: + var constraint = ast.parent; + if (constraint.type === ast) { + return true; + } + break; + case 220 /* CastExpression */: + var castExpression = ast.parent; + return castExpression.type === ast; + case 230 /* ExtendsHeritageClause */: + case 231 /* ImplementsHeritageClause */: + return true; + case 228 /* TypeArgumentList */: + return true; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + case 129 /* FunctionDeclaration */: + case 145 /* MethodSignature */: + case 212 /* MemberAccessExpression */: + case 242 /* Parameter */: + return false; + } + + ast = ast.parent; + } + + return false; + } + TypeScript.isTypesOnlyLocation = isTypesOnlyLocation; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.declCacheHit = 0; + TypeScript.declCacheMiss = 0; + TypeScript.symbolCacheHit = 0; + TypeScript.symbolCacheMiss = 0; + + var sentinalEmptyArray = []; + + var SemanticInfoChain = (function () { + function SemanticInfoChain(compiler, logger) { + this.compiler = compiler; + this.logger = logger; + this.documents = []; + this.fileNameToDocument = TypeScript.createIntrinsicsObject(); + this.anyTypeDecl = null; + this.booleanTypeDecl = null; + this.numberTypeDecl = null; + this.stringTypeDecl = null; + this.nullTypeDecl = null; + this.undefinedTypeDecl = null; + this.voidTypeDecl = null; + this.undefinedValueDecl = null; + this.anyTypeSymbol = null; + this.booleanTypeSymbol = null; + this.numberTypeSymbol = null; + this.stringTypeSymbol = null; + this.nullTypeSymbol = null; + this.undefinedTypeSymbol = null; + this.voidTypeSymbol = null; + this.undefinedValueSymbol = null; + this.emptyTypeSymbol = null; + this.astSymbolMap = []; + this.astAliasSymbolMap = []; + this.astCallResolutionDataMap = []; + this.declSymbolMap = []; + this.declSignatureSymbolMap = []; + this.declCache = null; + this.symbolCache = null; + this.fileNameToDiagnostics = null; + this._binder = null; + this._resolver = null; + this._topLevelDecls = null; + this._fileNames = null; + var globalDecl = new TypeScript.RootPullDecl("", "", 0 /* Global */, 0 /* None */, this, false); + this.documents[0] = new TypeScript.Document(this.compiler, this, "", [], null, 0 /* None */, 0, false, null, globalDecl); + + this.anyTypeDecl = new TypeScript.NormalPullDecl("any", "any", 2 /* Primitive */, 0 /* None */, globalDecl); + this.booleanTypeDecl = new TypeScript.NormalPullDecl("boolean", "boolean", 2 /* Primitive */, 0 /* None */, globalDecl); + this.numberTypeDecl = new TypeScript.NormalPullDecl("number", "number", 2 /* Primitive */, 0 /* None */, globalDecl); + this.stringTypeDecl = new TypeScript.NormalPullDecl("string", "string", 2 /* Primitive */, 0 /* None */, globalDecl); + this.voidTypeDecl = new TypeScript.NormalPullDecl("void", "void", 2 /* Primitive */, 0 /* None */, globalDecl); + + this.nullTypeDecl = new TypeScript.RootPullDecl("null", "", 2 /* Primitive */, 0 /* None */, this, false); + this.undefinedTypeDecl = new TypeScript.RootPullDecl("undefined", "", 2 /* Primitive */, 0 /* None */, this, false); + this.undefinedValueDecl = new TypeScript.NormalPullDecl("undefined", "undefined", 512 /* Variable */, 8 /* Ambient */, globalDecl); + + this.invalidate(); + } + SemanticInfoChain.prototype.getDocument = function (fileName) { + var document = this.fileNameToDocument[fileName]; + return document || null; + }; + + SemanticInfoChain.prototype.lineMap = function (fileName) { + return this.getDocument(fileName).lineMap(); + }; + + SemanticInfoChain.prototype.fileNames = function () { + if (this._fileNames === null) { + this._fileNames = this.documents.slice(1).map(function (s) { + return s.fileName; + }); + } + + return this._fileNames; + }; + + SemanticInfoChain.prototype.bindPrimitiveSymbol = function (decl, newSymbol) { + newSymbol.addDeclaration(decl); + decl.setSymbol(newSymbol); + newSymbol.setResolved(); + + return newSymbol; + }; + + SemanticInfoChain.prototype.addPrimitiveTypeSymbol = function (decl) { + var newSymbol = new TypeScript.PullPrimitiveTypeSymbol(decl.name); + return this.bindPrimitiveSymbol(decl, newSymbol); + }; + + SemanticInfoChain.prototype.addPrimitiveValueSymbol = function (decl, type) { + var newSymbol = new TypeScript.PullSymbol(decl.name, 512 /* Variable */); + newSymbol.type = type; + return this.bindPrimitiveSymbol(decl, newSymbol); + }; + + SemanticInfoChain.prototype.resetGlobalSymbols = function () { + this.anyTypeSymbol = this.addPrimitiveTypeSymbol(this.anyTypeDecl); + this.booleanTypeSymbol = this.addPrimitiveTypeSymbol(this.booleanTypeDecl); + this.numberTypeSymbol = this.addPrimitiveTypeSymbol(this.numberTypeDecl); + this.stringTypeSymbol = this.addPrimitiveTypeSymbol(this.stringTypeDecl); + this.voidTypeSymbol = this.addPrimitiveTypeSymbol(this.voidTypeDecl); + this.nullTypeSymbol = this.addPrimitiveTypeSymbol(this.nullTypeDecl); + this.undefinedTypeSymbol = this.addPrimitiveTypeSymbol(this.undefinedTypeDecl); + this.undefinedValueSymbol = this.addPrimitiveValueSymbol(this.undefinedValueDecl, this.undefinedTypeSymbol); + + var emptyTypeDecl = new TypeScript.PullSynthesizedDecl("{}", "{}", 8388608 /* ObjectType */, 0 /* None */, null, this); + var emptyTypeSymbol = new TypeScript.PullTypeSymbol("{}", 8388608 /* ObjectType */); + emptyTypeDecl.setSymbol(emptyTypeSymbol); + emptyTypeSymbol.addDeclaration(emptyTypeDecl); + emptyTypeSymbol.setResolved(); + this.emptyTypeSymbol = emptyTypeSymbol; + }; + + SemanticInfoChain.prototype.addDocument = function (document) { + var fileName = document.fileName; + + var existingIndex = TypeScript.ArrayUtilities.indexOf(this.documents, function (u) { + return u.fileName === fileName; + }); + if (existingIndex < 0) { + this.documents.push(document); + } else { + this.documents[existingIndex] = document; + } + + this.fileNameToDocument[fileName] = document; + + this.invalidate(); + }; + + SemanticInfoChain.prototype.removeDocument = function (fileName) { + TypeScript.Debug.assert(fileName !== "", "Can't remove the semantic info for the global decl."); + var index = TypeScript.ArrayUtilities.indexOf(this.documents, function (u) { + return u.fileName === fileName; + }); + if (index > 0) { + this.fileNameToDocument[fileName] = undefined; + this.documents.splice(index, 1); + this.invalidate(); + } + }; + + SemanticInfoChain.prototype.getDeclPathCacheID = function (declPath, declKind) { + var cacheID = ""; + + for (var i = 0; i < declPath.length; i++) { + cacheID += "#" + declPath[i]; + } + + return cacheID + "#" + declKind.toString(); + }; + + SemanticInfoChain.prototype.findTopLevelSymbol = function (name, kind, doNotGoPastThisDecl) { + var cacheID = this.getDeclPathCacheID([name], kind); + + var symbol = this.symbolCache[cacheID]; + + if (!symbol) { + for (var i = 0, n = this.documents.length; i < n; i++) { + var topLevelDecl = this.documents[i].topLevelDecl(); + + var symbol = this.findTopLevelSymbolInDecl(topLevelDecl, name, kind, doNotGoPastThisDecl); + if (symbol) { + break; + } + + if (doNotGoPastThisDecl && topLevelDecl.name === doNotGoPastThisDecl.fileName()) { + return null; + } + } + + if (symbol) { + this.symbolCache[cacheID] = symbol; + } + } + + return symbol; + }; + + SemanticInfoChain.prototype.findTopLevelSymbolInDecl = function (topLevelDecl, name, kind, doNotGoPastThisDecl) { + var doNotGoPastThisPosition = doNotGoPastThisDecl && doNotGoPastThisDecl.fileName() === topLevelDecl.fileName() ? doNotGoPastThisDecl.ast().start() : -1; + + var foundDecls = topLevelDecl.searchChildDecls(name, kind); + + for (var j = 0; j < foundDecls.length; j++) { + var foundDecl = foundDecls[j]; + + if (doNotGoPastThisPosition !== -1 && foundDecl.ast() && foundDecl.ast().start() > doNotGoPastThisPosition) { + break; + } + + var symbol = foundDecls[j].getSymbol(); + if (symbol) { + return symbol; + } + } + + return null; + }; + + SemanticInfoChain.prototype.findExternalModule = function (id) { + id = TypeScript.normalizePath(id); + + var tsFile = id + ".ts"; + var tsCacheID = this.getDeclPathCacheID([tsFile], 32 /* DynamicModule */); + symbol = this.symbolCache[tsCacheID]; + if (symbol != undefined) { + return symbol; + } + + var dtsFile = id + ".d.ts"; + var dtsCacheID = this.getDeclPathCacheID([dtsFile], 32 /* DynamicModule */); + var symbol = this.symbolCache[dtsCacheID]; + if (symbol) { + return symbol; + } + + var dtsSymbol; + for (var i = 0; i < this.documents.length; i++) { + var document = this.documents[i]; + var topLevelDecl = document.topLevelDecl(); + + if (topLevelDecl.isExternalModule()) { + var isTsFile = document.fileName === tsFile; + if (isTsFile || document.fileName === dtsFile) { + var dynamicModuleDecl = topLevelDecl.getChildDecls()[0]; + symbol = dynamicModuleDecl.getSymbol(); + + if (isTsFile) { + this.symbolCache[tsCacheID] = symbol; + + return symbol; + } else { + dtsSymbol = symbol; + } + } + } + } + + if (dtsSymbol) { + this.symbolCache[dtsCacheID] = symbol; + return dtsSymbol; + } + + this.symbolCache[dtsCacheID] = null; + this.symbolCache[tsCacheID] = null; + + return null; + }; + + SemanticInfoChain.prototype.findAmbientExternalModuleInGlobalContext = function (id) { + var cacheID = this.getDeclPathCacheID([id], 32 /* DynamicModule */); + + var symbol = this.symbolCache[cacheID]; + if (symbol == undefined) { + symbol = null; + for (var i = 0; i < this.documents.length; i++) { + var document = this.documents[i]; + var topLevelDecl = document.topLevelDecl(); + + if (!topLevelDecl.isExternalModule()) { + var dynamicModules = topLevelDecl.searchChildDecls(id, 32 /* DynamicModule */); + if (dynamicModules.length) { + symbol = dynamicModules[0].getSymbol(); + break; + } + } + } + + this.symbolCache[cacheID] = symbol; + } + + return symbol; + }; + + SemanticInfoChain.prototype.findDecls = function (declPath, declKind) { + var cacheID = this.getDeclPathCacheID(declPath, declKind); + + if (declPath.length) { + var cachedDecls = this.declCache[cacheID]; + + if (cachedDecls && cachedDecls.length) { + TypeScript.declCacheHit++; + return cachedDecls; + } + } + + TypeScript.declCacheMiss++; + + var declsToSearch = this.topLevelDecls(); + + var decls = TypeScript.sentinelEmptyArray; + var path; + var foundDecls = TypeScript.sentinelEmptyArray; + + for (var i = 0; i < declPath.length; i++) { + path = declPath[i]; + decls = TypeScript.sentinelEmptyArray; + + var kind = (i === declPath.length - 1) ? declKind : 164 /* SomeContainer */; + for (var j = 0; j < declsToSearch.length; j++) { + foundDecls = declsToSearch[j].searchChildDecls(path, kind); + + for (var k = 0; k < foundDecls.length; k++) { + if (decls === TypeScript.sentinelEmptyArray) { + decls = []; + } + decls[decls.length] = foundDecls[k]; + } + } + + declsToSearch = decls; + + if (!declsToSearch) { + break; + } + } + + if (decls.length) { + this.declCache[cacheID] = decls; + } + + return decls; + }; + + SemanticInfoChain.prototype.findDeclsFromPath = function (declPath, declKind) { + var declString = []; + + for (var i = 0, n = declPath.length; i < n; i++) { + if (declPath[i].kind & 1 /* Script */) { + continue; + } + + declString.push(declPath[i].name); + } + + return this.findDecls(declString, declKind); + }; + + SemanticInfoChain.prototype.findSymbol = function (declPath, declType) { + var cacheID = this.getDeclPathCacheID(declPath, declType); + + if (declPath.length) { + var cachedSymbol = this.symbolCache[cacheID]; + + if (cachedSymbol) { + TypeScript.symbolCacheHit++; + return cachedSymbol; + } + } + + TypeScript.symbolCacheMiss++; + + var decls = this.findDecls(declPath, declType); + var symbol = null; + + if (decls.length) { + var decl = decls[0]; + if (TypeScript.hasFlag(decl.kind, 164 /* SomeContainer */)) { + var valueDecl = decl.getValueDecl(); + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + } + symbol = decl.getSymbol(); + + if (symbol) { + for (var i = 1; i < decls.length; i++) { + decls[i].ensureSymbolIsBound(); + } + + this.symbolCache[cacheID] = symbol; + } + } + + return symbol; + }; + + SemanticInfoChain.prototype.cacheGlobalSymbol = function (symbol, kind) { + var cacheID1 = this.getDeclPathCacheID([symbol.name], kind); + var cacheID2 = this.getDeclPathCacheID([symbol.name], symbol.kind); + + if (!this.symbolCache[cacheID1]) { + this.symbolCache[cacheID1] = symbol; + } + + if (!this.symbolCache[cacheID2]) { + this.symbolCache[cacheID2] = symbol; + } + }; + + SemanticInfoChain.prototype.invalidate = function (oldSettings, newSettings) { + if (typeof oldSettings === "undefined") { oldSettings = null; } + if (typeof newSettings === "undefined") { newSettings = null; } + TypeScript.PullTypeResolver.globalTypeCheckPhase++; + + var cleanStart = new Date().getTime(); + + this.astSymbolMap.length = 0; + this.astAliasSymbolMap.length = 0; + this.astCallResolutionDataMap.length = 0; + + this.declCache = TypeScript.createIntrinsicsObject(); + this.symbolCache = TypeScript.createIntrinsicsObject(); + this.fileNameToDiagnostics = TypeScript.createIntrinsicsObject(); + this._binder = null; + this._resolver = null; + this._topLevelDecls = null; + this._fileNames = null; + + this.declSymbolMap.length = 0; + this.declSignatureSymbolMap.length = 0; + + if (oldSettings && newSettings) { + if (this.settingsChangeAffectsSyntax(oldSettings, newSettings)) { + for (var i = 1, n = this.documents.length; i < n; i++) { + this.documents[i].invalidate(); + } + } + } + + TypeScript.pullSymbolID = 0; + + this.resetGlobalSymbols(); + + var cleanEnd = new Date().getTime(); + }; + + SemanticInfoChain.prototype.settingsChangeAffectsSyntax = function (before, after) { + return before.allowAutomaticSemicolonInsertion() !== after.allowAutomaticSemicolonInsertion() || before.codeGenTarget() !== after.codeGenTarget() || before.propagateEnumConstants() !== after.propagateEnumConstants(); + }; + + SemanticInfoChain.prototype.setSymbolForAST = function (ast, symbol) { + this.astSymbolMap[ast.syntaxID()] = symbol; + }; + + SemanticInfoChain.prototype.getSymbolForAST = function (ast) { + return this.astSymbolMap[ast.syntaxID()] || null; + }; + + SemanticInfoChain.prototype.setAliasSymbolForAST = function (ast, symbol) { + this.astAliasSymbolMap[ast.syntaxID()] = symbol; + }; + + SemanticInfoChain.prototype.getAliasSymbolForAST = function (ast) { + return this.astAliasSymbolMap[ast.syntaxID()]; + }; + + SemanticInfoChain.prototype.getCallResolutionDataForAST = function (ast) { + return this.astCallResolutionDataMap[ast.syntaxID()]; + }; + + SemanticInfoChain.prototype.setCallResolutionDataForAST = function (ast, callResolutionData) { + if (callResolutionData) { + this.astCallResolutionDataMap[ast.syntaxID()] = callResolutionData; + } + }; + + SemanticInfoChain.prototype.setSymbolForDecl = function (decl, symbol) { + this.declSymbolMap[decl.declID] = symbol; + }; + + SemanticInfoChain.prototype.getSymbolForDecl = function (decl) { + return this.declSymbolMap[decl.declID]; + }; + + SemanticInfoChain.prototype.setSignatureSymbolForDecl = function (decl, signatureSymbol) { + this.declSignatureSymbolMap[decl.declID] = signatureSymbol; + }; + + SemanticInfoChain.prototype.getSignatureSymbolForDecl = function (decl) { + return this.declSignatureSymbolMap[decl.declID]; + }; + + SemanticInfoChain.prototype.addDiagnostic = function (diagnostic) { + var fileName = diagnostic.fileName(); + var diagnostics = this.fileNameToDiagnostics[fileName]; + if (!diagnostics) { + diagnostics = []; + this.fileNameToDiagnostics[fileName] = diagnostics; + } + + diagnostics.push(diagnostic); + }; + + SemanticInfoChain.prototype.getDiagnostics = function (fileName) { + var diagnostics = this.fileNameToDiagnostics[fileName]; + return diagnostics || []; + }; + + SemanticInfoChain.prototype.getBinder = function () { + if (!this._binder) { + this._binder = new TypeScript.PullSymbolBinder(this); + } + + return this._binder; + }; + + SemanticInfoChain.prototype.getResolver = function () { + if (!this._resolver) { + this._resolver = new TypeScript.PullTypeResolver(this.compiler.compilationSettings(), this); + } + + return this._resolver; + }; + + SemanticInfoChain.prototype.addSyntheticIndexSignature = function (containingDecl, containingSymbol, ast, indexParamName, indexParamType, returnType) { + var indexSignature = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + var indexParameterSymbol = new TypeScript.PullSymbol(indexParamName, 2048 /* Parameter */); + indexParameterSymbol.type = indexParamType; + indexSignature.addParameter(indexParameterSymbol); + indexSignature.returnType = returnType; + indexSignature.setResolved(); + indexParameterSymbol.setResolved(); + + containingSymbol.addIndexSignature(indexSignature); + + var indexSigDecl = new TypeScript.PullSynthesizedDecl("", "", 4194304 /* IndexSignature */, 2048 /* Signature */, containingDecl, containingDecl.semanticInfoChain); + var indexParamDecl = new TypeScript.PullSynthesizedDecl(indexParamName, indexParamName, 2048 /* Parameter */, 0 /* None */, indexSigDecl, containingDecl.semanticInfoChain); + indexSigDecl.setSignatureSymbol(indexSignature); + indexParamDecl.setSymbol(indexParameterSymbol); + indexSignature.addDeclaration(indexSigDecl); + indexParameterSymbol.addDeclaration(indexParamDecl); + }; + + SemanticInfoChain.prototype.getDeclForAST = function (ast) { + var document = this.getDocument(ast.fileName()); + + if (document) { + return document._getDeclForAST(ast); + } + + return null; + }; + + SemanticInfoChain.prototype.getEnclosingDecl = function (ast) { + return this.getDocument(ast.fileName()).getEnclosingDecl(ast); + }; + + SemanticInfoChain.prototype.setDeclForAST = function (ast, decl) { + this.getDocument(decl.fileName())._setDeclForAST(ast, decl); + }; + + SemanticInfoChain.prototype.getASTForDecl = function (decl) { + var document = this.getDocument(decl.fileName()); + if (document) { + return document._getASTForDecl(decl); + } + + return null; + }; + + SemanticInfoChain.prototype.setASTForDecl = function (decl, ast) { + this.getDocument(decl.fileName())._setASTForDecl(decl, ast); + }; + + SemanticInfoChain.prototype.topLevelDecl = function (fileName) { + var document = this.getDocument(fileName); + if (document) { + return document.topLevelDecl(); + } + + return null; + }; + + SemanticInfoChain.prototype.topLevelDecls = function () { + if (!this._topLevelDecls) { + this._topLevelDecls = TypeScript.ArrayUtilities.select(this.documents, function (u) { + return u.topLevelDecl(); + }); + } + + return this._topLevelDecls; + }; + + SemanticInfoChain.prototype.addDiagnosticFromAST = function (ast, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + this.addDiagnostic(this.diagnosticFromAST(ast, diagnosticKey, _arguments, additionalLocations)); + }; + + SemanticInfoChain.prototype.diagnosticFromAST = function (ast, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + return new TypeScript.Diagnostic(ast.fileName(), this.lineMap(ast.fileName()), ast.start(), ast.width(), diagnosticKey, _arguments, additionalLocations); + }; + + SemanticInfoChain.prototype.locationFromAST = function (ast) { + return new TypeScript.Location(ast.fileName(), this.lineMap(ast.fileName()), ast.start(), ast.width()); + }; + + SemanticInfoChain.prototype.duplicateIdentifierDiagnosticFromAST = function (ast, identifier, additionalLocationAST) { + return this.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_0, [identifier], additionalLocationAST ? [this.locationFromAST(additionalLocationAST)] : null); + }; + + SemanticInfoChain.prototype.addDuplicateIdentifierDiagnosticFromAST = function (ast, identifier, additionalLocationAST) { + this.addDiagnostic(this.duplicateIdentifierDiagnosticFromAST(ast, identifier, additionalLocationAST)); + }; + return SemanticInfoChain; + })(); + TypeScript.SemanticInfoChain = SemanticInfoChain; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DeclCollectionContext = (function () { + function DeclCollectionContext(document, semanticInfoChain, propagateEnumConstants) { + this.document = document; + this.semanticInfoChain = semanticInfoChain; + this.propagateEnumConstants = propagateEnumConstants; + this.isDeclareFile = false; + this.parentChain = []; + } + DeclCollectionContext.prototype.getParent = function () { + return this.parentChain ? this.parentChain[this.parentChain.length - 1] : null; + }; + + DeclCollectionContext.prototype.pushParent = function (parentDecl) { + if (parentDecl) { + this.parentChain[this.parentChain.length] = parentDecl; + } + }; + + DeclCollectionContext.prototype.popParent = function () { + this.parentChain.length--; + }; + return DeclCollectionContext; + })(); + + function moduleElementsHasExportAssignment(moduleElements) { + return moduleElements.any(function (m) { + return m.kind() === 134 /* ExportAssignment */; + }); + } + + function containingModuleHasExportAssignment(ast) { + ast = ast.parent; + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + var moduleDecl = ast; + return moduleElementsHasExportAssignment(moduleDecl.moduleElements); + } else if (ast.kind() === 120 /* SourceUnit */) { + var sourceUnit = ast; + return moduleElementsHasExportAssignment(sourceUnit.moduleElements); + } + + ast = ast.parent; + } + + return false; + } + + function isParsingAmbientModule(ast, context) { + ast = ast.parent; + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + if (TypeScript.hasModifier(ast.modifiers, 8 /* Ambient */)) { + return true; + } + } + + ast = ast.parent; + } + + return false; + } + + function preCollectImportDecls(ast, context) { + var importDecl = ast; + var declFlags = 0 /* None */; + + var parent = context.getParent(); + + if (TypeScript.hasModifier(importDecl.modifiers, 1 /* Exported */) && !containingModuleHasExportAssignment(ast)) { + declFlags |= 1 /* Exported */; + } + + var decl = new TypeScript.NormalPullDecl(importDecl.identifier.valueText(), importDecl.identifier.text(), 128 /* TypeAlias */, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + } + + function preCollectScriptDecls(sourceUnit, context) { + var fileName = sourceUnit.fileName(); + + var isExternalModule = context.document.isExternalModule(); + + var decl = new TypeScript.RootPullDecl(fileName, fileName, 1 /* Script */, 0 /* None */, context.semanticInfoChain, isExternalModule); + context.semanticInfoChain.setDeclForAST(sourceUnit, decl); + context.semanticInfoChain.setASTForDecl(decl, sourceUnit); + + context.isDeclareFile = context.document.isDeclareFile(); + + context.pushParent(decl); + + if (isExternalModule) { + var declFlags = 1 /* Exported */; + if (TypeScript.isDTSFile(fileName)) { + declFlags |= 8 /* Ambient */; + } + + var moduleContainsExecutableCode = containsExecutableCode(sourceUnit.moduleElements); + var kind = 32 /* DynamicModule */; + var valueText = TypeScript.quoteStr(fileName); + + var decl = new TypeScript.NormalPullDecl(valueText, fileName, kind, declFlags, context.getParent()); + + context.semanticInfoChain.setASTForDecl(decl, sourceUnit); + + context.semanticInfoChain.setDeclForAST(sourceUnit, decl); + + if (!moduleElementsHasExportAssignment(sourceUnit.moduleElements) || moduleContainsExecutableCode) { + createModuleVariableDecl(decl, sourceUnit, context); + } + + context.pushParent(decl); + } + } + + function preCollectEnumDecls(enumDecl, context) { + var declFlags = 0 /* None */; + var enumName = enumDecl.identifier.valueText(); + + if ((TypeScript.hasModifier(enumDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(enumDecl, context)) && !containingModuleHasExportAssignment(enumDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(enumDecl.modifiers, 8 /* Ambient */) || isParsingAmbientModule(enumDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + declFlags |= 4096 /* Enum */; + var kind = 64 /* Enum */; + + var enumDeclaration = new TypeScript.NormalPullDecl(enumName, enumDecl.identifier.text(), kind, declFlags, context.getParent()); + context.semanticInfoChain.setDeclForAST(enumDecl, enumDeclaration); + context.semanticInfoChain.setASTForDecl(enumDeclaration, enumDecl); + + var valueDecl = new TypeScript.NormalPullDecl(enumDeclaration.name, enumDeclaration.getDisplayName(), 512 /* Variable */, enumDeclaration.flags, context.getParent()); + enumDeclaration.setValueDecl(valueDecl); + context.semanticInfoChain.setASTForDecl(valueDecl, enumDecl); + + context.pushParent(enumDeclaration); + } + + function createEnumElementDecls(propertyDecl, context) { + var parent = context.getParent(); + + var decl = new TypeScript.PullEnumElementDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), parent); + context.semanticInfoChain.setDeclForAST(propertyDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyDecl); + } + + function preCollectModuleDecls(moduleDecl, context) { + var declFlags = 0 /* None */; + + var moduleContainsExecutableCode = containsExecutableCode(moduleDecl.moduleElements); + + var isDynamic = moduleDecl.stringLiteral !== null; + + if ((TypeScript.hasModifier(moduleDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(moduleDecl, context)) && !containingModuleHasExportAssignment(moduleDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(moduleDecl.modifiers, 8 /* Ambient */) || isParsingAmbientModule(moduleDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + var kind = isDynamic ? 32 /* DynamicModule */ : 4 /* Container */; + + if (moduleDecl.stringLiteral) { + var valueText = TypeScript.quoteStr(moduleDecl.stringLiteral.valueText()); + var text = moduleDecl.stringLiteral.text(); + + var decl = new TypeScript.NormalPullDecl(valueText, text, kind, declFlags, context.getParent()); + + context.semanticInfoChain.setDeclForAST(moduleDecl, decl); + context.semanticInfoChain.setDeclForAST(moduleDecl.stringLiteral, decl); + context.semanticInfoChain.setASTForDecl(decl, moduleDecl.stringLiteral); + + if (!moduleElementsHasExportAssignment(moduleDecl.moduleElements) || moduleContainsExecutableCode) { + createModuleVariableDecl(decl, moduleDecl.stringLiteral, context); + } + + context.pushParent(decl); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDecl.name); + for (var i = 0, n = moduleNames.length; i < n; i++) { + var moduleName = moduleNames[i]; + + var specificFlags = declFlags; + if (i > 0) { + specificFlags |= 1 /* Exported */; + } + + var decl = new TypeScript.NormalPullDecl(moduleName.valueText(), moduleName.text(), kind, specificFlags, context.getParent()); + + context.semanticInfoChain.setDeclForAST(moduleDecl, decl); + context.semanticInfoChain.setDeclForAST(moduleName, decl); + context.semanticInfoChain.setASTForDecl(decl, moduleName); + + if (moduleContainsExecutableCode) { + createModuleVariableDecl(decl, moduleName, context); + } + + context.pushParent(decl); + } + } + } + + function createModuleVariableDecl(decl, moduleNameAST, context) { + decl.setFlags(decl.flags | getInitializationFlag(decl)); + + var valueDecl = new TypeScript.NormalPullDecl(decl.name, decl.getDisplayName(), 512 /* Variable */, decl.flags, context.getParent()); + decl.setValueDecl(valueDecl); + context.semanticInfoChain.setASTForDecl(valueDecl, moduleNameAST); + } + + function containsExecutableCode(members) { + for (var i = 0, n = members.childCount(); i < n; i++) { + var member = members.childAt(i); + + if (member.kind() === 130 /* ModuleDeclaration */) { + var moduleDecl = member; + + if (containsExecutableCode(moduleDecl.moduleElements)) { + return true; + } + } else if (member.kind() === 133 /* ImportDeclaration */) { + if (TypeScript.hasModifier(member.modifiers, 1 /* Exported */)) { + return true; + } + } else if (member.kind() !== 128 /* InterfaceDeclaration */ && member.kind() !== 134 /* ExportAssignment */) { + return true; + } + } + + return false; + } + + function preCollectClassDecls(classDecl, context) { + var declFlags = 0 /* None */; + + if ((TypeScript.hasModifier(classDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(classDecl, context)) && !containingModuleHasExportAssignment(classDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(classDecl.modifiers, 8 /* Ambient */) || isParsingAmbientModule(classDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), 8 /* Class */, declFlags, parent); + + var constructorDecl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), 512 /* Variable */, declFlags | 16384 /* ClassConstructorVariable */, parent); + + decl.setValueDecl(constructorDecl); + + context.semanticInfoChain.setDeclForAST(classDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, classDecl); + context.semanticInfoChain.setASTForDecl(constructorDecl, classDecl); + + context.pushParent(decl); + } + + function preCollectObjectTypeDecls(objectType, context) { + if (objectType.parent.kind() === 128 /* InterfaceDeclaration */) { + return; + } + + var declFlags = 0 /* None */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", 8388608 /* ObjectType */, declFlags, parent); + context.semanticInfoChain.setDeclForAST(objectType, decl); + context.semanticInfoChain.setASTForDecl(decl, objectType); + + context.pushParent(decl); + } + + function preCollectInterfaceDecls(interfaceDecl, context) { + var declFlags = 0 /* None */; + + if ((TypeScript.hasModifier(interfaceDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(interfaceDecl, context)) && !containingModuleHasExportAssignment(interfaceDecl)) { + declFlags |= 1 /* Exported */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(interfaceDecl.identifier.valueText(), interfaceDecl.identifier.text(), 16 /* Interface */, declFlags, parent); + context.semanticInfoChain.setDeclForAST(interfaceDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, interfaceDecl); + + context.pushParent(decl); + } + + function preCollectParameterDecl(argDecl, context) { + var declFlags = 0 /* None */; + + if (TypeScript.hasModifier(argDecl.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (argDecl.questionToken !== null || argDecl.equalsValueClause !== null || argDecl.dotDotDotToken !== null) { + declFlags |= 128 /* Optional */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 2048 /* Parameter */, declFlags, parent); + + if (argDecl.equalsValueClause) { + parent.flags |= 33554432 /* HasDefaultArgs */; + } + + if (parent.kind === 32768 /* ConstructorMethod */) { + decl.setFlag(67108864 /* ConstructorParameter */); + } + + var isPublicOrPrivate = TypeScript.hasModifier(argDecl.modifiers, 4 /* Public */ | 2 /* Private */); + var isInConstructor = parent.kind === 32768 /* ConstructorMethod */; + if (isPublicOrPrivate && isInConstructor) { + var parentsParent = context.parentChain[context.parentChain.length - 2]; + + var propDeclFlags = declFlags & ~128 /* Optional */; + var propDecl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 4096 /* Property */, propDeclFlags, parentsParent); + propDecl.setValueDecl(decl); + decl.setFlag(8388608 /* PropertyParameter */); + propDecl.setFlag(8388608 /* PropertyParameter */); + + if (parent.kind === 32768 /* ConstructorMethod */) { + propDecl.setFlag(67108864 /* ConstructorParameter */); + } + + context.semanticInfoChain.setASTForDecl(decl, argDecl); + context.semanticInfoChain.setASTForDecl(propDecl, argDecl); + context.semanticInfoChain.setDeclForAST(argDecl, propDecl); + } else { + context.semanticInfoChain.setASTForDecl(decl, argDecl); + context.semanticInfoChain.setDeclForAST(argDecl, decl); + } + + parent.addVariableDeclToGroup(decl); + } + + function preCollectTypeParameterDecl(typeParameterDecl, context) { + var declFlags = 0 /* None */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(typeParameterDecl.identifier.valueText(), typeParameterDecl.identifier.text(), 8192 /* TypeParameter */, declFlags, parent); + context.semanticInfoChain.setASTForDecl(decl, typeParameterDecl); + context.semanticInfoChain.setDeclForAST(typeParameterDecl, decl); + } + + function createPropertySignature(propertyDecl, context) { + var declFlags = 4 /* Public */; + var parent = context.getParent(); + var declType = 4096 /* Property */; + + if (propertyDecl.questionToken !== null) { + declFlags |= 128 /* Optional */; + } + + var decl = new TypeScript.NormalPullDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(propertyDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyDecl); + } + + function createMemberVariableDeclaration(memberDecl, context) { + var declFlags = 0 /* None */; + var declType = 4096 /* Property */; + + if (TypeScript.hasModifier(memberDecl.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (TypeScript.hasModifier(memberDecl.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(memberDecl.variableDeclarator.propertyName.valueText(), memberDecl.variableDeclarator.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(memberDecl, decl); + context.semanticInfoChain.setDeclForAST(memberDecl.variableDeclarator, decl); + context.semanticInfoChain.setASTForDecl(decl, memberDecl); + } + + function createVariableDeclaration(varDecl, context) { + var declFlags = 0 /* None */; + var declType = 512 /* Variable */; + + var modifiers = TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl); + if ((TypeScript.hasModifier(modifiers, 1 /* Exported */) || isParsingAmbientModule(varDecl, context)) && !containingModuleHasExportAssignment(varDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(modifiers, 8 /* Ambient */) || isParsingAmbientModule(varDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(varDecl.propertyName.valueText(), varDecl.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(varDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, varDecl); + + if (parent) { + parent.addVariableDeclToGroup(decl); + } + } + + function preCollectVarDecls(ast, context) { + if (ast.parent.kind() === 136 /* MemberVariableDeclaration */) { + return; + } + + var varDecl = ast; + createVariableDeclaration(varDecl, context); + } + + function createFunctionTypeDeclaration(functionTypeDeclAST, context) { + var declFlags = 2048 /* Signature */; + var declType = 16777216 /* FunctionType */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(functionTypeDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, functionTypeDeclAST); + + context.pushParent(decl); + } + + function createConstructorTypeDeclaration(constructorTypeDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 33554432 /* ConstructorType */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(constructorTypeDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, constructorTypeDeclAST); + + context.pushParent(decl); + } + + function createFunctionDeclaration(funcDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 16384 /* Function */; + + if ((TypeScript.hasModifier(funcDeclAST.modifiers, 1 /* Exported */) || isParsingAmbientModule(funcDeclAST, context)) && !containingModuleHasExportAssignment(funcDeclAST)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(funcDeclAST.modifiers, 8 /* Ambient */) || isParsingAmbientModule(funcDeclAST, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + if (!funcDeclAST.block) { + declFlags |= 2048 /* Signature */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(funcDeclAST.identifier.valueText(), funcDeclAST.identifier.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(funcDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, funcDeclAST); + + context.pushParent(decl); + } + + function createAnyFunctionExpressionDeclaration(functionExpressionDeclAST, id, context, displayName) { + if (typeof displayName === "undefined") { displayName = null; } + var declFlags = 0 /* None */; + + if (functionExpressionDeclAST.kind() === 219 /* SimpleArrowFunctionExpression */ || functionExpressionDeclAST.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { + declFlags |= 8192 /* ArrowFunction */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var name = id ? id.text() : ""; + var displayNameText = displayName ? displayName.text() : ""; + var decl = new TypeScript.PullFunctionExpressionDecl(name, declFlags, parent, displayNameText); + context.semanticInfoChain.setDeclForAST(functionExpressionDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, functionExpressionDeclAST); + + context.pushParent(decl); + + if (functionExpressionDeclAST.kind() === 219 /* SimpleArrowFunctionExpression */) { + var simpleArrow = functionExpressionDeclAST; + var declFlags = 4 /* Public */; + + var parent = context.getParent(); + + if (TypeScript.hasFlag(parent.flags, 2097152 /* DeclaredInAWithBlock */)) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(simpleArrow.identifier.valueText(), simpleArrow.identifier.text(), 2048 /* Parameter */, declFlags, parent); + + context.semanticInfoChain.setASTForDecl(decl, simpleArrow.identifier); + context.semanticInfoChain.setDeclForAST(simpleArrow.identifier, decl); + + parent.addVariableDeclToGroup(decl); + } + } + + function createMemberFunctionDeclaration(funcDecl, context) { + var declFlags = 0 /* None */; + var declType = 65536 /* Method */; + + if (TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasModifier(funcDecl.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (!funcDecl.block) { + declFlags |= 2048 /* Signature */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(funcDecl.propertyName.valueText(), funcDecl.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(funcDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, funcDecl); + + context.pushParent(decl); + } + + function createIndexSignatureDeclaration(indexSignatureDeclAST, context) { + var declFlags = 2048 /* Signature */; + var declType = 4194304 /* IndexSignature */; + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(indexSignatureDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, indexSignatureDeclAST); + + context.pushParent(decl); + } + + function createCallSignatureDeclaration(callSignature, context) { + var isChildOfObjectType = callSignature.parent && callSignature.parent.parent && callSignature.parent.kind() === 2 /* SeparatedList */ && callSignature.parent.parent.kind() === 122 /* ObjectType */; + + if (!isChildOfObjectType) { + return; + } + + var declFlags = 2048 /* Signature */; + var declType = 1048576 /* CallSignature */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(callSignature, decl); + context.semanticInfoChain.setASTForDecl(decl, callSignature); + + context.pushParent(decl); + } + + function createMethodSignatureDeclaration(method, context) { + var declFlags = 0 /* None */; + var declType = 65536 /* Method */; + + declFlags |= 4 /* Public */; + declFlags |= 2048 /* Signature */; + + if (method.questionToken !== null) { + declFlags |= 128 /* Optional */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(method.propertyName.valueText(), method.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(method, decl); + context.semanticInfoChain.setASTForDecl(decl, method); + + context.pushParent(decl); + } + + function createConstructSignatureDeclaration(constructSignatureDeclAST, context) { + var declFlags = 2048 /* Signature */; + var declType = 2097152 /* ConstructSignature */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(constructSignatureDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, constructSignatureDeclAST); + + context.pushParent(decl); + } + + function createClassConstructorDeclaration(constructorDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 32768 /* ConstructorMethod */; + + if (!constructorDeclAST.block) { + declFlags |= 2048 /* Signature */; + } + + var parent = context.getParent(); + + if (parent) { + var parentFlags = parent.flags; + + if (parentFlags & 1 /* Exported */) { + declFlags |= 1 /* Exported */; + } + } + + var decl = new TypeScript.NormalPullDecl(parent.name, parent.getDisplayName(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(constructorDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, constructorDeclAST); + + context.pushParent(decl); + } + + function createGetAccessorDeclaration(getAccessorDeclAST, context) { + var declFlags = 4 /* Public */; + var declType = 262144 /* GetAccessor */; + + if (TypeScript.hasModifier(getAccessorDeclAST.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasModifier(getAccessorDeclAST.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(getAccessorDeclAST.propertyName.valueText(), getAccessorDeclAST.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(getAccessorDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, getAccessorDeclAST); + + context.pushParent(decl); + } + + function createFunctionExpressionDeclaration(expression, context) { + createAnyFunctionExpressionDeclaration(expression, expression.identifier, context); + } + + function createSetAccessorDeclaration(setAccessorDeclAST, context) { + var declFlags = 4 /* Public */; + var declType = 524288 /* SetAccessor */; + + if (TypeScript.hasModifier(setAccessorDeclAST.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasModifier(setAccessorDeclAST.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(setAccessorDeclAST.propertyName.valueText(), setAccessorDeclAST.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(setAccessorDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, setAccessorDeclAST); + + context.pushParent(decl); + } + + function preCollectCatchDecls(ast, context) { + var declFlags = 0 /* None */; + var declType = 268435456 /* CatchBlock */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + + context.pushParent(decl); + + var declFlags = 0 /* None */; + var declType = 1024 /* CatchVariable */; + + var parent = context.getParent(); + + if (TypeScript.hasFlag(parent.flags, 2097152 /* DeclaredInAWithBlock */)) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(ast.identifier.valueText(), ast.identifier.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast.identifier, decl); + context.semanticInfoChain.setASTForDecl(decl, ast.identifier); + + if (parent) { + parent.addVariableDeclToGroup(decl); + } + } + + function preCollectWithDecls(ast, context) { + var declFlags = 0 /* None */; + var declType = 134217728 /* WithBlock */; + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + + context.pushParent(decl); + } + + function preCollectObjectLiteralDecls(ast, context) { + var decl = new TypeScript.NormalPullDecl("", "", 256 /* ObjectLiteral */, 0 /* None */, context.getParent()); + + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + + context.pushParent(decl); + } + + function preCollectSimplePropertyAssignmentDecls(propertyAssignment, context) { + var assignmentText = TypeScript.getPropertyAssignmentNameTextFromIdentifier(propertyAssignment.propertyName); + var span = TypeScript.TextSpan.fromBounds(propertyAssignment.start(), propertyAssignment.end()); + + var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent()); + + context.semanticInfoChain.setDeclForAST(propertyAssignment, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyAssignment); + } + + function preCollectFunctionPropertyAssignmentDecls(propertyAssignment, context) { + var assignmentText = TypeScript.getPropertyAssignmentNameTextFromIdentifier(propertyAssignment.propertyName); + + var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent()); + + context.semanticInfoChain.setDeclForAST(propertyAssignment, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyAssignment); + + createAnyFunctionExpressionDeclaration(propertyAssignment, propertyAssignment.propertyName, context, propertyAssignment.propertyName); + } + + function preCollectDecls(ast, context) { + switch (ast.kind()) { + case 120 /* SourceUnit */: + preCollectScriptDecls(ast, context); + break; + case 132 /* EnumDeclaration */: + preCollectEnumDecls(ast, context); + break; + case 243 /* EnumElement */: + createEnumElementDecls(ast, context); + break; + case 130 /* ModuleDeclaration */: + preCollectModuleDecls(ast, context); + break; + case 131 /* ClassDeclaration */: + preCollectClassDecls(ast, context); + break; + case 128 /* InterfaceDeclaration */: + preCollectInterfaceDecls(ast, context); + break; + case 122 /* ObjectType */: + preCollectObjectTypeDecls(ast, context); + break; + case 242 /* Parameter */: + preCollectParameterDecl(ast, context); + break; + case 136 /* MemberVariableDeclaration */: + createMemberVariableDeclaration(ast, context); + break; + case 141 /* PropertySignature */: + createPropertySignature(ast, context); + break; + case 225 /* VariableDeclarator */: + preCollectVarDecls(ast, context); + break; + case 137 /* ConstructorDeclaration */: + createClassConstructorDeclaration(ast, context); + break; + case 139 /* GetAccessor */: + createGetAccessorDeclaration(ast, context); + break; + case 140 /* SetAccessor */: + createSetAccessorDeclaration(ast, context); + break; + case 222 /* FunctionExpression */: + createFunctionExpressionDeclaration(ast, context); + break; + case 135 /* MemberFunctionDeclaration */: + createMemberFunctionDeclaration(ast, context); + break; + case 144 /* IndexSignature */: + createIndexSignatureDeclaration(ast, context); + break; + case 123 /* FunctionType */: + createFunctionTypeDeclaration(ast, context); + break; + case 125 /* ConstructorType */: + createConstructorTypeDeclaration(ast, context); + break; + case 142 /* CallSignature */: + createCallSignatureDeclaration(ast, context); + break; + case 143 /* ConstructSignature */: + createConstructSignatureDeclaration(ast, context); + break; + case 145 /* MethodSignature */: + createMethodSignatureDeclaration(ast, context); + break; + case 129 /* FunctionDeclaration */: + createFunctionDeclaration(ast, context); + break; + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + createAnyFunctionExpressionDeclaration(ast, null, context); + break; + case 133 /* ImportDeclaration */: + preCollectImportDecls(ast, context); + break; + case 238 /* TypeParameter */: + preCollectTypeParameterDecl(ast, context); + break; + case 236 /* CatchClause */: + preCollectCatchDecls(ast, context); + break; + case 163 /* WithStatement */: + preCollectWithDecls(ast, context); + break; + case 215 /* ObjectLiteralExpression */: + preCollectObjectLiteralDecls(ast, context); + break; + case 240 /* SimplePropertyAssignment */: + preCollectSimplePropertyAssignmentDecls(ast, context); + break; + case 241 /* FunctionPropertyAssignment */: + preCollectFunctionPropertyAssignmentDecls(ast, context); + break; + } + } + + function isContainer(decl) { + return decl.kind === 4 /* Container */ || decl.kind === 32 /* DynamicModule */ || decl.kind === 64 /* Enum */; + } + + function getInitializationFlag(decl) { + if (decl.kind & 4 /* Container */) { + return 32768 /* InitializedModule */; + } else if (decl.kind & 32 /* DynamicModule */) { + return 65536 /* InitializedDynamicModule */; + } + + return 0 /* None */; + } + + function hasInitializationFlag(decl) { + var kind = decl.kind; + + if (kind & 4 /* Container */) { + return (decl.flags & 32768 /* InitializedModule */) !== 0; + } else if (kind & 32 /* DynamicModule */) { + return (decl.flags & 65536 /* InitializedDynamicModule */) !== 0; + } + + return false; + } + + function postCollectDecls(ast, context) { + var currentDecl = context.getParent(); + + if (ast.kind() === 11 /* IdentifierName */ || ast.kind() === 14 /* StringLiteral */) { + if (currentDecl.kind === 4 /* Container */ || currentDecl.kind === 32 /* DynamicModule */) { + return; + } + } + + if (ast.kind() === 130 /* ModuleDeclaration */) { + var moduleDeclaration = ast; + if (moduleDeclaration.stringLiteral) { + TypeScript.Debug.assert(currentDecl.ast() === moduleDeclaration.stringLiteral); + context.popParent(); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDeclaration.name); + for (var i = moduleNames.length - 1; i >= 0; i--) { + var moduleName = moduleNames[i]; + TypeScript.Debug.assert(currentDecl.ast() === moduleName); + context.popParent(); + currentDecl = context.getParent(); + } + } + } + + if (ast.kind() === 132 /* EnumDeclaration */) { + computeEnumElementConstantValues(ast, currentDecl, context); + } + + while (currentDecl.getParentDecl() && currentDecl.ast() === ast) { + context.popParent(); + currentDecl = context.getParent(); + } + } + + function computeEnumElementConstantValues(ast, enumDecl, context) { + TypeScript.Debug.assert(enumDecl.kind === 64 /* Enum */); + + var isAmbientEnum = TypeScript.hasFlag(enumDecl.flags, 8 /* Ambient */); + var inConstantSection = !isAmbientEnum; + var currentConstantValue = 0; + var enumMemberDecls = enumDecl.getChildDecls(); + + for (var i = 0, n = ast.enumElements.nonSeparatorCount(); i < n; i++) { + var enumElement = ast.enumElements.nonSeparatorAt(i); + var enumElementDecl = TypeScript.ArrayUtilities.first(enumMemberDecls, function (d) { + return context.semanticInfoChain.getASTForDecl(d) === enumElement; + }); + + TypeScript.Debug.assert(enumElementDecl.kind === 67108864 /* EnumMember */); + + if (enumElement.equalsValueClause === null) { + if (inConstantSection) { + enumElementDecl.constantValue = currentConstantValue; + currentConstantValue++; + } + } else { + enumElementDecl.constantValue = computeEnumElementConstantValue(enumElement.equalsValueClause.value, enumMemberDecls, context); + if (enumElementDecl.constantValue !== null && !isAmbientEnum) { + inConstantSection = true; + currentConstantValue = enumElementDecl.constantValue + 1; + } else { + inConstantSection = false; + } + } + + TypeScript.Debug.assert(enumElementDecl.constantValue !== undefined); + } + } + + function computeEnumElementConstantValue(expression, enumMemberDecls, context) { + TypeScript.Debug.assert(expression); + + if (TypeScript.ASTHelpers.isIntegerLiteralAST(expression)) { + var token; + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + token = expression.operand; + break; + default: + token = expression; + } + + var value = token.value(); + return value && expression.kind() === 165 /* NegateExpression */ ? -value : value; + } else if (context.propagateEnumConstants) { + switch (expression.kind()) { + case 11 /* IdentifierName */: + var name = expression; + var matchingEnumElement = TypeScript.ArrayUtilities.firstOrDefault(enumMemberDecls, function (d) { + return d.name === name.valueText(); + }); + + return matchingEnumElement ? matchingEnumElement.constantValue : null; + + case 202 /* LeftShiftExpression */: + var binaryExpression = expression; + var left = computeEnumElementConstantValue(binaryExpression.left, enumMemberDecls, context); + var right = computeEnumElementConstantValue(binaryExpression.right, enumMemberDecls, context); + if (left === null || right === null) { + return null; + } + + return left << right; + + case 189 /* BitwiseOrExpression */: + var binaryExpression = expression; + var left = computeEnumElementConstantValue(binaryExpression.left, enumMemberDecls, context); + var right = computeEnumElementConstantValue(binaryExpression.right, enumMemberDecls, context); + if (left === null || right === null) { + return null; + } + + return left | right; + } + + return null; + } else { + return null; + } + } + + (function (DeclarationCreator) { + function create(document, semanticInfoChain, compilationSettings) { + var declCollectionContext = new DeclCollectionContext(document, semanticInfoChain, compilationSettings.propagateEnumConstants()); + + TypeScript.getAstWalkerFactory().simpleWalk(document.sourceUnit(), preCollectDecls, postCollectDecls, declCollectionContext); + + return declCollectionContext.getParent(); + } + DeclarationCreator.create = create; + })(TypeScript.DeclarationCreator || (TypeScript.DeclarationCreator = {})); + var DeclarationCreator = TypeScript.DeclarationCreator; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PullSymbolBinder = (function () { + function PullSymbolBinder(semanticInfoChain) { + this.semanticInfoChain = semanticInfoChain; + this.declsBeingBound = []; + this.inBindingOtherDeclsWalker = new TypeScript.PullHelpers.OtherPullDeclsWalker(); + } + PullSymbolBinder.prototype.getParent = function (decl, returnInstanceType) { + if (typeof returnInstanceType === "undefined") { returnInstanceType = false; } + var parentDecl = decl.getParentDecl(); + + if (parentDecl.kind === 1 /* Script */) { + return null; + } + + var parent = parentDecl.getSymbol(); + + if (!parent && parentDecl && !parentDecl.hasBeenBound()) { + this.bindDeclToPullSymbol(parentDecl); + } + + parent = parentDecl.getSymbol(); + if (parent) { + var parentDeclKind = parentDecl.kind; + if (parentDeclKind === 262144 /* GetAccessor */) { + parent = parent.getGetter(); + } else if (parentDeclKind === 524288 /* SetAccessor */) { + parent = parent.getSetter(); + } + } + + if (parent) { + if (returnInstanceType && parent.isType() && parent.isContainer()) { + var instanceSymbol = parent.getInstanceSymbol(); + + if (instanceSymbol) { + return instanceSymbol.type; + } + } + + return parent.type; + } + + return null; + }; + + PullSymbolBinder.prototype.findDeclsInContext = function (startingDecl, declKind, searchGlobally) { + if (!searchGlobally) { + var parentDecl = startingDecl.getParentDecl(); + return parentDecl.searchChildDecls(startingDecl.name, declKind); + } + + var contextSymbolPath = startingDecl.getParentPath(); + + if (contextSymbolPath.length) { + var copyOfContextSymbolPath = []; + + for (var i = 0; i < contextSymbolPath.length; i++) { + if (contextSymbolPath[i].kind & 1 /* Script */) { + continue; + } + copyOfContextSymbolPath[copyOfContextSymbolPath.length] = contextSymbolPath[i].name; + } + + return this.semanticInfoChain.findDecls(copyOfContextSymbolPath, declKind); + } + }; + + PullSymbolBinder.prototype.getExistingSymbol = function (decl, searchKind, parent) { + var lookingForValue = (searchKind & 68147712 /* SomeValue */) !== 0; + var lookingForType = (searchKind & 58728795 /* SomeType */) !== 0; + var lookingForContainer = (searchKind & 164 /* SomeContainer */) !== 0; + var name = decl.name; + if (parent) { + var isExported = (decl.flags & 1 /* Exported */) !== 0; + + var prevSymbol = null; + if (lookingForValue) { + prevSymbol = parent.findContainedNonMember(name); + } else if (lookingForType) { + prevSymbol = parent.findContainedNonMemberType(name, searchKind); + } else if (lookingForContainer) { + prevSymbol = parent.findContainedNonMemberContainer(name, searchKind); + } + var prevIsExported = !prevSymbol; + if (!prevSymbol) { + if (lookingForValue) { + prevSymbol = parent.findMember(name, false); + } else if (lookingForType) { + prevSymbol = parent.findNestedType(name, searchKind); + } else if (lookingForContainer) { + prevSymbol = parent.findNestedContainer(name, searchKind); + } + } + + if (isExported && prevIsExported) { + return prevSymbol; + } + if (prevSymbol) { + var prevDecls = prevSymbol.getDeclarations(); + var lastPrevDecl = prevDecls[prevDecls.length - 1]; + var parentDecl = decl.getParentDecl(); + var prevParentDecl = lastPrevDecl && lastPrevDecl.getParentDecl(); + if (parentDecl !== prevParentDecl) { + return null; + } + + return prevSymbol; + } + } else { + var parentDecl = decl.getParentDecl(); + if (parentDecl && parentDecl.kind === 1 /* Script */) { + return this.semanticInfoChain.findTopLevelSymbol(name, searchKind, decl); + } else { + var prevDecls = parentDecl && parentDecl.searchChildDecls(name, searchKind); + return prevDecls[0] && prevDecls[0].getSymbol(); + } + } + + return null; + }; + + PullSymbolBinder.prototype.checkThatExportsMatch = function (decl, prevSymbol, reportError) { + if (typeof reportError === "undefined") { reportError = true; } + var isExported = (decl.flags & 1 /* Exported */) !== 0; + var prevDecls = prevSymbol.getDeclarations(); + var prevIsExported = (prevDecls[prevDecls.length - 1].flags & 1 /* Exported */) !== 0; + if ((isExported !== prevIsExported) && !prevSymbol.isSignature() && (decl.kind & 7340032 /* SomeSignature */) === 0) { + if (reportError) { + var ast = this.semanticInfoChain.getASTForDecl(decl); + this.semanticInfoChain.addDiagnosticFromAST(ast, TypeScript.DiagnosticCode.All_declarations_of_merged_declaration_0_must_be_exported_or_not_exported, [decl.getDisplayName()]); + } + return false; + } + + return true; + }; + + PullSymbolBinder.prototype.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList = function (signature, currentSignatures) { + var signatureDecl = signature.getDeclarations()[0]; + TypeScript.Debug.assert(signatureDecl); + var enclosingDecl = signatureDecl.getParentDecl(); + var indexToInsert = TypeScript.ArrayUtilities.indexOf(currentSignatures, function (someSignature) { + return someSignature.getDeclarations()[0].getParentDecl() !== enclosingDecl; + }); + return indexToInsert < 0 ? currentSignatures.length : indexToInsert; + }; + + PullSymbolBinder.prototype.bindEnumDeclarationToPullSymbol = function (enumContainerDecl) { + var enumName = enumContainerDecl.name; + + var enumContainerSymbol = null; + var enumInstanceSymbol = null; + var moduleInstanceTypeSymbol = null; + + var enumInstanceDecl = enumContainerDecl.getValueDecl(); + + var enumDeclKind = enumContainerDecl.kind; + + var parent = this.getParent(enumContainerDecl); + var parentInstanceSymbol = this.getParent(enumContainerDecl, true); + var parentDecl = enumContainerDecl.getParentDecl(); + var enumAST = this.semanticInfoChain.getASTForDecl(enumContainerDecl); + + var isExported = enumContainerDecl.flags & 1 /* Exported */; + + var createdNewSymbol = false; + + enumContainerSymbol = this.getExistingSymbol(enumContainerDecl, 64 /* Enum */, parent); + + if (enumContainerSymbol) { + if (enumContainerSymbol.kind !== enumDeclKind) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(enumAST.identifier, enumContainerDecl.getDisplayName(), enumContainerSymbol.getDeclarations()[0].ast()); + enumContainerSymbol = null; + } else if (!this.checkThatExportsMatch(enumContainerDecl, enumContainerSymbol)) { + enumContainerSymbol = null; + } + } + + if (enumContainerSymbol) { + enumInstanceSymbol = enumContainerSymbol.getInstanceSymbol(); + } else { + enumContainerSymbol = new TypeScript.PullContainerSymbol(enumName, enumDeclKind); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(enumContainerSymbol, 64 /* Enum */); + } + } + + enumContainerSymbol.addDeclaration(enumContainerDecl); + enumContainerDecl.setSymbol(enumContainerSymbol); + + this.semanticInfoChain.setSymbolForAST(enumAST.identifier, enumContainerSymbol); + this.semanticInfoChain.setSymbolForAST(enumAST, enumContainerSymbol); + + if (!enumInstanceSymbol) { + var variableSymbol = null; + if (parentInstanceSymbol) { + if (isExported) { + variableSymbol = parentInstanceSymbol.findMember(enumName, false); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findContainedNonMember(enumName); + } + } else { + variableSymbol = parentInstanceSymbol.findContainedNonMember(enumName); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findMember(enumName, false); + } + } + + if (variableSymbol) { + var declarations = variableSymbol.getDeclarations(); + + if (declarations.length) { + var variableSymbolParentDecl = declarations[0].getParentDecl(); + + if (parentDecl !== variableSymbolParentDecl) { + variableSymbol = null; + } + } + } + } else if (!(enumContainerDecl.flags & 1 /* Exported */)) { + var siblingDecls = parentDecl.getChildDecls(); + var augmentedDecl = null; + + for (var i = 0; i < siblingDecls.length; i++) { + if (siblingDecls[i] === enumContainerDecl) { + break; + } + + if ((siblingDecls[i].name === enumName) && (siblingDecls[i].kind & 68147712 /* SomeValue */)) { + augmentedDecl = siblingDecls[i]; + break; + } + } + + if (augmentedDecl) { + variableSymbol = augmentedDecl.getSymbol(); + + if (variableSymbol) { + if (variableSymbol.isContainer()) { + variableSymbol = variableSymbol.getInstanceSymbol(); + } else if (variableSymbol && variableSymbol.isType()) { + variableSymbol = variableSymbol.getConstructorMethod(); + } + } + } + } + + if (variableSymbol) { + enumInstanceSymbol = variableSymbol; + moduleInstanceTypeSymbol = variableSymbol.type; + } else { + enumInstanceSymbol = new TypeScript.PullSymbol(enumName, 512 /* Variable */); + } + + enumContainerSymbol.setInstanceSymbol(enumInstanceSymbol); + + if (!moduleInstanceTypeSymbol) { + moduleInstanceTypeSymbol = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + enumInstanceSymbol.type = moduleInstanceTypeSymbol; + } + + moduleInstanceTypeSymbol.addDeclaration(enumContainerDecl); + + if (!moduleInstanceTypeSymbol.getAssociatedContainerType()) { + moduleInstanceTypeSymbol.setAssociatedContainerType(enumContainerSymbol); + } + } + + if (createdNewSymbol && parent) { + if (enumContainerDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberType(enumContainerSymbol); + } else { + parent.addEnclosedNonMemberType(enumContainerSymbol); + } + } + + if (createdNewSymbol) { + this.bindEnumIndexerDeclsToPullSymbols(enumContainerSymbol); + } + var valueDecl = enumContainerDecl.getValueDecl(); + + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + }; + + PullSymbolBinder.prototype.bindEnumIndexerDeclsToPullSymbols = function (enumContainerSymbol) { + var enumContainerInstanceTypeSymbol = enumContainerSymbol.getInstanceSymbol().type; + + var syntheticIndexerParameterSymbol = new TypeScript.PullSymbol("x", 2048 /* Parameter */); + syntheticIndexerParameterSymbol.type = this.semanticInfoChain.numberTypeSymbol; + syntheticIndexerParameterSymbol.setResolved(); + syntheticIndexerParameterSymbol.setIsSynthesized(); + + var syntheticIndexerSignatureSymbol = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + syntheticIndexerSignatureSymbol.addParameter(syntheticIndexerParameterSymbol); + syntheticIndexerSignatureSymbol.returnType = this.semanticInfoChain.stringTypeSymbol; + syntheticIndexerSignatureSymbol.setResolved(); + syntheticIndexerSignatureSymbol.setIsSynthesized(); + + enumContainerInstanceTypeSymbol.addIndexSignature(syntheticIndexerSignatureSymbol); + }; + + PullSymbolBinder.prototype.findExistingVariableSymbolForModuleValueDecl = function (decl) { + var isExported = TypeScript.hasFlag(decl.flags, 1 /* Exported */); + var modName = decl.name; + var parentInstanceSymbol = this.getParent(decl, true); + var parentDecl = decl.getParentDecl(); + + var variableSymbol = null; + + if (parentInstanceSymbol) { + if (isExported) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); + } + } else { + variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + } + } + + if (variableSymbol) { + var declarations = variableSymbol.getDeclarations(); + + if (declarations.length) { + var variableSymbolParentDecl = declarations[0].getParentDecl(); + var isExportedOrHasTheSameParent = isExported || (parentDecl === variableSymbolParentDecl); + + var canReuseVariableSymbol = isExportedOrHasTheSameParent && this.checkThatExportsMatch(decl, variableSymbol, false); + + if (!canReuseVariableSymbol) { + variableSymbol = null; + } + } + } + } else if (!isExported) { + var siblingDecls = parentDecl.getChildDecls(); + + for (var i = 0; i < siblingDecls.length; i++) { + var sibling = siblingDecls[i]; + + var siblingIsSomeValue = TypeScript.hasFlag(sibling.kind, 68147712 /* SomeValue */); + var siblingIsFunctionOrHasImplictVarFlag = TypeScript.hasFlag(sibling.kind, 1032192 /* SomeFunction */) || TypeScript.hasFlag(sibling.flags, 118784 /* ImplicitVariable */); + + var isSiblingAnAugmentableVariable = sibling !== decl && sibling !== decl.getValueDecl() && sibling.name === modName && siblingIsSomeValue && siblingIsFunctionOrHasImplictVarFlag; + + if (isSiblingAnAugmentableVariable) { + if (sibling.hasSymbol()) { + variableSymbol = sibling.getSymbol(); + if (variableSymbol.isContainer()) { + variableSymbol = variableSymbol.getInstanceSymbol(); + } else if (variableSymbol && variableSymbol.isType()) { + variableSymbol = variableSymbol.getConstructorMethod(); + } + + break; + } + } + } + } + return variableSymbol; + }; + + PullSymbolBinder.prototype.bindModuleDeclarationToPullSymbol = function (moduleContainerDecl) { + var modName = moduleContainerDecl.name; + + var moduleContainerTypeSymbol = null; + var moduleKind = moduleContainerDecl.kind; + + var parent = this.getParent(moduleContainerDecl); + var parentInstanceSymbol = this.getParent(moduleContainerDecl, true); + var parentDecl = moduleContainerDecl.getParentDecl(); + var moduleNameAST = this.semanticInfoChain.getASTForDecl(moduleContainerDecl); + var moduleDeclAST = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(moduleNameAST); + if (!moduleDeclAST) { + TypeScript.Debug.assert(moduleKind === 32 /* DynamicModule */); + TypeScript.Debug.assert(moduleNameAST.kind() === 120 /* SourceUnit */); + + moduleDeclAST = moduleNameAST; + } + + var isExported = TypeScript.hasFlag(moduleContainerDecl.flags, 1 /* Exported */); + var searchKind = 164 /* SomeContainer */; + var isInitializedModule = (moduleContainerDecl.flags & 102400 /* SomeInitializedModule */) !== 0; + + if (parent && moduleKind === 32 /* DynamicModule */) { + this.semanticInfoChain.addDiagnosticFromAST(moduleNameAST, TypeScript.DiagnosticCode.Ambient_external_module_declaration_must_be_defined_in_global_context, null); + } + + var createdNewSymbol = false; + + moduleContainerTypeSymbol = this.getExistingSymbol(moduleContainerDecl, searchKind, parent); + + if (moduleContainerTypeSymbol) { + if (moduleContainerTypeSymbol.kind !== moduleKind) { + if (isInitializedModule) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(moduleNameAST, moduleContainerDecl.getDisplayName(), moduleContainerTypeSymbol.getDeclarations()[0].ast()); + } + + moduleContainerTypeSymbol = null; + } else if (moduleKind === 32 /* DynamicModule */) { + this.semanticInfoChain.addDiagnosticFromAST(moduleNameAST, TypeScript.DiagnosticCode.Ambient_external_module_declaration_cannot_be_reopened); + } else if (!this.checkThatExportsMatch(moduleContainerDecl, moduleContainerTypeSymbol)) { + moduleContainerTypeSymbol = null; + } + } + + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = new TypeScript.PullContainerSymbol(modName, moduleKind); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(moduleContainerTypeSymbol, searchKind); + } + } + + moduleContainerTypeSymbol.addDeclaration(moduleContainerDecl); + moduleContainerDecl.setSymbol(moduleContainerTypeSymbol); + + this.semanticInfoChain.setSymbolForAST(moduleNameAST, moduleContainerTypeSymbol); + this.semanticInfoChain.setSymbolForAST(moduleDeclAST, moduleContainerTypeSymbol); + + var currentModuleValueDecl = moduleContainerDecl.getValueDecl(); + + var moduleDeclarations = moduleContainerTypeSymbol.getDeclarations(); + + if (createdNewSymbol) { + if (parent) { + if (moduleContainerDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberContainer(moduleContainerTypeSymbol); + } else { + parent.addEnclosedNonMemberContainer(moduleContainerTypeSymbol); + } + } + } + + if (currentModuleValueDecl) { + currentModuleValueDecl.ensureSymbolIsBound(); + + var instanceSymbol = null; + var instanceTypeSymbol = null; + if (currentModuleValueDecl.hasSymbol()) { + instanceSymbol = currentModuleValueDecl.getSymbol(); + } else { + instanceSymbol = new TypeScript.PullSymbol(modName, 512 /* Variable */); + currentModuleValueDecl.setSymbol(instanceSymbol); + if (!instanceSymbol.hasDeclaration(currentModuleValueDecl)) { + instanceSymbol.addDeclaration(currentModuleValueDecl); + } + } + + if (!instanceSymbol.type) { + instanceSymbol.type = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + } + + moduleContainerTypeSymbol.setInstanceSymbol(instanceSymbol); + + if (!instanceSymbol.type.getAssociatedContainerType()) { + instanceSymbol.type.setAssociatedContainerType(moduleContainerTypeSymbol); + } + } + }; + + PullSymbolBinder.prototype.bindImportDeclaration = function (importDeclaration) { + var declFlags = importDeclaration.flags; + var declKind = importDeclaration.kind; + var importDeclAST = this.semanticInfoChain.getASTForDecl(importDeclaration); + + var isExported = false; + var importSymbol = null; + var declName = importDeclaration.name; + var parentHadSymbol = false; + var parent = this.getParent(importDeclaration); + + importSymbol = this.getExistingSymbol(importDeclaration, 164 /* SomeContainer */, parent); + + if (importSymbol) { + parentHadSymbol = true; + } + + if (importSymbol) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(importDeclAST, importDeclaration.getDisplayName(), importSymbol.getDeclarations()[0].ast()); + importSymbol = null; + } + + if (!importSymbol) { + importSymbol = new TypeScript.PullTypeAliasSymbol(declName); + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(importSymbol, 164 /* SomeContainer */); + } + } + + importSymbol.addDeclaration(importDeclaration); + importDeclaration.setSymbol(importSymbol); + + this.semanticInfoChain.setSymbolForAST(importDeclAST, importSymbol); + + if (parent && !parentHadSymbol) { + if (declFlags & 1 /* Exported */) { + parent.addEnclosedMemberContainer(importSymbol); + } else { + parent.addEnclosedNonMemberContainer(importSymbol); + } + } + }; + + PullSymbolBinder.prototype.ensurePriorDeclarationsAreBound = function (container, currentDecl) { + if (!container) { + return; + } + + var parentDecls = container.getDeclarations(); + for (var i = 0; i < parentDecls.length; ++i) { + var parentDecl = parentDecls[i]; + var childDecls = parentDecl.getChildDecls(); + for (var j = 0; j < childDecls.length; ++j) { + var childDecl = childDecls[j]; + if (childDecl === currentDecl) { + return; + } + + if (childDecl.name === currentDecl.name) { + childDecl.ensureSymbolIsBound(); + } + } + } + }; + + PullSymbolBinder.prototype.bindClassDeclarationToPullSymbol = function (classDecl) { + var className = classDecl.name; + var classSymbol = null; + + var constructorSymbol = null; + var constructorTypeSymbol = null; + + var classAST = this.semanticInfoChain.getASTForDecl(classDecl); + + var parent = this.getParent(classDecl); + + this.ensurePriorDeclarationsAreBound(parent, classDecl); + + var parentDecl = classDecl.getParentDecl(); + var isExported = classDecl.flags & 1 /* Exported */; + var isGeneric = false; + + classSymbol = this.getExistingSymbol(classDecl, 58728795 /* SomeType */, parent); + + if (classSymbol && classSymbol.kind === 16 /* Interface */) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(classAST.identifier, classDecl.getDisplayName(), classSymbol.getDeclarations()[0].ast()); + classSymbol = null; + } + + classSymbol = new TypeScript.PullTypeSymbol(className, 8 /* Class */); + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(classSymbol, 8 /* Class */); + } + + classSymbol.addDeclaration(classDecl); + + classDecl.setSymbol(classSymbol); + + this.semanticInfoChain.setSymbolForAST(classAST.identifier, classSymbol); + this.semanticInfoChain.setSymbolForAST(classAST, classSymbol); + + if (parent) { + if (classDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberType(classSymbol); + } else { + parent.addEnclosedNonMemberType(classSymbol); + } + } + + var typeParameterDecls = classDecl.getTypeParameters(); + + for (var i = 0; i < typeParameterDecls.length; i++) { + var typeParameterSymbol = classSymbol.findTypeParameter(typeParameterDecls[i].name); + + if (typeParameterSymbol) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterSymbol.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameterSymbol.getName()]); + } + + typeParameterSymbol = new TypeScript.PullTypeParameterSymbol(typeParameterDecls[i].name); + + classSymbol.addTypeParameter(typeParameterSymbol); + typeParameterSymbol.addDeclaration(typeParameterDecls[i]); + typeParameterDecls[i].setSymbol(typeParameterSymbol); + } + + constructorSymbol = classSymbol.getConstructorMethod(); + constructorTypeSymbol = constructorSymbol ? constructorSymbol.type : null; + + if (!constructorSymbol) { + var siblingValueDecls = null; + if (parentDecl) { + siblingValueDecls = parentDecl.searchChildDecls(className, 68147712 /* SomeValue */); + + if (siblingValueDecls && siblingValueDecls[0] && siblingValueDecls[0].hasSymbol()) { + constructorSymbol = siblingValueDecls[0].getSymbol(); + } + } + + if (constructorSymbol) { + constructorTypeSymbol = constructorSymbol.type; + } else { + constructorSymbol = new TypeScript.PullSymbol(className, 32768 /* ConstructorMethod */); + constructorTypeSymbol = new TypeScript.PullTypeSymbol("", 33554432 /* ConstructorType */); + constructorSymbol.setIsSynthesized(); + constructorSymbol.type = constructorTypeSymbol; + } + + classSymbol.setConstructorMethod(constructorSymbol); + classSymbol.setHasDefaultConstructor(); + } + + if (constructorSymbol.getIsSynthesized()) { + constructorSymbol.addDeclaration(classDecl.getValueDecl()); + constructorTypeSymbol.addDeclaration(classDecl); + } else { + classSymbol.setHasDefaultConstructor(false); + } + + constructorTypeSymbol.setAssociatedContainerType(classSymbol); + + var valueDecl = classDecl.getValueDecl(); + + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + + this.bindStaticPrototypePropertyOfClass(classAST, classSymbol, constructorTypeSymbol); + }; + + PullSymbolBinder.prototype.bindInterfaceDeclarationToPullSymbol = function (interfaceDecl) { + var interfaceName = interfaceDecl.name; + var interfaceSymbol = null; + + var interfaceAST = this.semanticInfoChain.getASTForDecl(interfaceDecl); + var createdNewSymbol = false; + var parent = this.getParent(interfaceDecl); + + var acceptableSharedKind = 16 /* Interface */; + + interfaceSymbol = this.getExistingSymbol(interfaceDecl, 58728795 /* SomeType */, parent); + + if (interfaceSymbol) { + if (!(interfaceSymbol.kind & acceptableSharedKind)) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(interfaceAST.identifier, interfaceDecl.getDisplayName(), interfaceSymbol.getDeclarations()[0].ast()); + interfaceSymbol = null; + } else if (!this.checkThatExportsMatch(interfaceDecl, interfaceSymbol)) { + interfaceSymbol = null; + } + } + + if (!interfaceSymbol) { + interfaceSymbol = new TypeScript.PullTypeSymbol(interfaceName, 16 /* Interface */); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(interfaceSymbol, acceptableSharedKind); + } + } + + interfaceSymbol.addDeclaration(interfaceDecl); + interfaceDecl.setSymbol(interfaceSymbol); + + if (createdNewSymbol) { + if (parent) { + if (interfaceDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberType(interfaceSymbol); + } else { + parent.addEnclosedNonMemberType(interfaceSymbol); + } + } + } + + var typeParameters = interfaceDecl.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = interfaceSymbol.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + interfaceSymbol.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + for (var j = 0; j < typeParameterDecls.length; j++) { + var typeParameterDeclParent = typeParameterDecls[j].getParentDecl(); + + if (typeParameterDeclParent && typeParameterDeclParent === interfaceDecl) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + + break; + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + }; + + PullSymbolBinder.prototype.bindObjectTypeDeclarationToPullSymbol = function (objectDecl) { + var objectSymbolAST = this.semanticInfoChain.getASTForDecl(objectDecl); + + var objectSymbol = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + + objectSymbol.addDeclaration(objectDecl); + objectDecl.setSymbol(objectSymbol); + + this.semanticInfoChain.setSymbolForAST(objectSymbolAST, objectSymbol); + + var childDecls = objectDecl.getChildDecls(); + + for (var i = 0; i < childDecls.length; i++) { + this.bindDeclToPullSymbol(childDecls[i]); + } + }; + + PullSymbolBinder.prototype.bindConstructorTypeDeclarationToPullSymbol = function (constructorTypeDeclaration) { + var declKind = constructorTypeDeclaration.kind; + var declFlags = constructorTypeDeclaration.flags; + var constructorTypeAST = this.semanticInfoChain.getASTForDecl(constructorTypeDeclaration); + + var constructorTypeSymbol = new TypeScript.PullTypeSymbol("", 33554432 /* ConstructorType */); + + constructorTypeDeclaration.setSymbol(constructorTypeSymbol); + constructorTypeSymbol.addDeclaration(constructorTypeDeclaration); + this.semanticInfoChain.setSymbolForAST(constructorTypeAST, constructorTypeSymbol); + + var signature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + + var funcDecl = this.semanticInfoChain.getASTForDecl(constructorTypeDeclaration); + if (TypeScript.lastParameterIsRest(funcDecl.parameterList)) { + signature.hasVarArgs = true; + } + + signature.addDeclaration(constructorTypeDeclaration); + constructorTypeDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList), constructorTypeSymbol, signature); + + var typeParameters = constructorTypeDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = constructorTypeSymbol.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.name]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + constructorTypeSymbol.appendConstructSignature(signature); + }; + + PullSymbolBinder.prototype.bindVariableDeclarationToPullSymbol = function (variableDeclaration) { + var declFlags = variableDeclaration.flags; + var declKind = variableDeclaration.kind; + var varDeclAST = this.semanticInfoChain.getASTForDecl(variableDeclaration); + var nameAST = varDeclAST.kind() === 131 /* ClassDeclaration */ ? varDeclAST.identifier : varDeclAST.kind() === 225 /* VariableDeclarator */ ? varDeclAST.propertyName : varDeclAST.kind() === 132 /* EnumDeclaration */ ? varDeclAST.identifier : varDeclAST; + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var variableSymbol = null; + + var declName = variableDeclaration.name; + + var parentHadSymbol = false; + + var parent = this.getParent(variableDeclaration, true); + + var parentDecl = variableDeclaration.getParentDecl(); + + var isImplicit = (declFlags & 118784 /* ImplicitVariable */) !== 0; + var isModuleValue = (declFlags & (32768 /* InitializedModule */)) !== 0; + var isEnumValue = (declFlags & 4096 /* Enum */) !== 0; + var isClassConstructorVariable = (declFlags & 16384 /* ClassConstructorVariable */) !== 0; + variableSymbol = this.getExistingSymbol(variableDeclaration, 68147712 /* SomeValue */, parent); + + if (!variableSymbol && isModuleValue) { + variableSymbol = this.findExistingVariableSymbolForModuleValueDecl(variableDeclaration.getContainerDecl()); + } + + if (variableSymbol && !variableSymbol.isType()) { + parentHadSymbol = true; + } + + var decl; + var decls; + var ast; + var members; + + if (variableSymbol) { + var prevKind = variableSymbol.kind; + var prevIsEnum = variableSymbol.anyDeclHasFlag(4096 /* Enum */); + var prevIsClassConstructorVariable = variableSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */); + var prevIsModuleValue = variableSymbol.allDeclsHaveFlag(32768 /* InitializedModule */); + var prevIsImplicit = variableSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */); + var prevIsFunction = TypeScript.ArrayUtilities.any(variableSymbol.getDeclarations(), function (decl) { + return decl.kind === 16384 /* Function */; + }); + var prevIsAmbient = variableSymbol.allDeclsHaveFlag(8 /* Ambient */); + var isAmbientOrPrevIsAmbient = prevIsAmbient || (variableDeclaration.flags & 8 /* Ambient */) !== 0; + var prevDecl = variableSymbol.getDeclarations()[0]; + var prevParentDecl = prevDecl.getParentDecl(); + var bothAreGlobal = parentDecl && (parentDecl.kind === 1 /* Script */) && (prevParentDecl.kind === 1 /* Script */); + var shareParent = bothAreGlobal || prevDecl.getParentDecl() === variableDeclaration.getParentDecl(); + var prevIsParam = shareParent && prevKind === 2048 /* Parameter */ && declKind == 512 /* Variable */; + + var acceptableRedeclaration = prevIsParam || (isImplicit && ((!isEnumValue && !isClassConstructorVariable && prevIsFunction) || ((isModuleValue || isEnumValue) && (prevIsModuleValue || prevIsEnum)) || (isClassConstructorVariable && prevIsModuleValue && isAmbientOrPrevIsAmbient) || (isModuleValue && prevIsClassConstructorVariable))); + + if (acceptableRedeclaration && (prevIsClassConstructorVariable || prevIsFunction) && !isAmbientOrPrevIsAmbient) { + if (prevDecl.fileName() !== variableDeclaration.fileName()) { + this.semanticInfoChain.addDiagnostic(TypeScript.PullHelpers.diagnosticFromDecl(variableDeclaration, TypeScript.DiagnosticCode.Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2, [declName, declName, prevDecl.fileName()])); + variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); + } + } + + if (!acceptableRedeclaration || prevIsParam) { + if (!prevIsParam && (isImplicit || prevIsImplicit || TypeScript.hasFlag(prevKind, 1032192 /* SomeFunction */)) || !shareParent) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(nameAST, variableDeclaration.getDisplayName(), variableSymbol.getDeclarations()[0].ast()); + variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); + } else { + this.checkThatExportsMatch(variableDeclaration, variableSymbol); + variableSymbol = null; + parentHadSymbol = false; + } + } + + if (variableSymbol && !(variableSymbol.type && variableSymbol.type.isError()) && !this.checkThatExportsMatch(variableDeclaration, variableSymbol, !(isModuleValue && prevIsModuleValue))) { + variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); + } + } + + if ((declFlags & 118784 /* ImplicitVariable */) === 0) { + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + if (!parent && parentDecl.kind === 1 /* Script */) { + this.semanticInfoChain.cacheGlobalSymbol(variableSymbol, declKind); + } + } + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + this.semanticInfoChain.setSymbolForAST(nameAST, variableSymbol); + this.semanticInfoChain.setSymbolForAST(varDeclAST, variableSymbol); + } else if (!parentHadSymbol) { + if (isClassConstructorVariable) { + var classTypeSymbol = variableSymbol; + + if (parent) { + members = parent.getMembers(); + + for (var i = 0; i < members.length; i++) { + if ((members[i].name === declName) && (members[i].kind === 8 /* Class */)) { + classTypeSymbol = members[i]; + break; + } + } + } + + if (!classTypeSymbol) { + var containerDecl = variableDeclaration.getContainerDecl(); + classTypeSymbol = containerDecl.getSymbol(); + if (!classTypeSymbol) { + classTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 58728795 /* SomeType */, variableDeclaration); + } + } + + if (classTypeSymbol && (classTypeSymbol.kind !== 8 /* Class */)) { + classTypeSymbol = null; + } + + if (classTypeSymbol && classTypeSymbol.isClass()) { + variableSymbol = classTypeSymbol.getConstructorMethod(); + variableDeclaration.setSymbol(variableSymbol); + + decls = classTypeSymbol.getDeclarations(); + + if (decls.length) { + decl = decls[decls.length - 1]; + ast = this.semanticInfoChain.getASTForDecl(decl); + } + } else { + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + } + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + variableSymbol.type = this.semanticInfoChain.anyTypeSymbol; + } + } else if (declFlags & 102400 /* SomeInitializedModule */) { + var moduleContainerTypeSymbol = null; + var moduleParent = this.getParent(variableDeclaration); + + if (moduleParent) { + members = moduleParent.getMembers(); + + for (var i = 0; i < members.length; i++) { + if ((members[i].name === declName) && (members[i].isContainer())) { + moduleContainerTypeSymbol = members[i]; + break; + } + } + } + + if (!moduleContainerTypeSymbol) { + var containerDecl = variableDeclaration.getContainerDecl(); + moduleContainerTypeSymbol = containerDecl.getSymbol(); + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 164 /* SomeContainer */, variableDeclaration); + + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 64 /* Enum */, variableDeclaration); + } + } + } + + if (moduleContainerTypeSymbol && (!moduleContainerTypeSymbol.isContainer())) { + moduleContainerTypeSymbol = null; + } + + if (moduleContainerTypeSymbol) { + variableSymbol = moduleContainerTypeSymbol.getInstanceSymbol(); + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + variableSymbol.type = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + } + + if (!variableSymbol.hasDeclaration(variableDeclaration)) { + variableSymbol.addDeclaration(variableDeclaration); + } + variableDeclaration.setSymbol(variableSymbol); + } else { + TypeScript.Debug.assert(false, "Attempted to bind invalid implicit variable symbol"); + } + } + } else { + if (!variableSymbol.hasDeclaration(variableDeclaration)) { + variableSymbol.addDeclaration(variableDeclaration); + } + variableDeclaration.setSymbol(variableSymbol); + } + + var containerDecl = variableDeclaration.getContainerDecl(); + if (variableSymbol && variableSymbol.type && containerDecl && !variableSymbol.type.hasDeclaration(containerDecl)) { + variableSymbol.type.addDeclaration(containerDecl); + } + + if (parent && !parentHadSymbol) { + if (declFlags & 1 /* Exported */) { + parent.addMember(variableSymbol); + } else { + parent.addEnclosedNonMember(variableSymbol); + } + } + }; + + PullSymbolBinder.prototype.bindCatchVariableToPullSymbol = function (variableDeclaration) { + var declFlags = variableDeclaration.flags; + var declKind = variableDeclaration.kind; + var identifier = this.semanticInfoChain.getASTForDecl(variableDeclaration); + + var declName = variableDeclaration.name; + + var variableSymbol = new TypeScript.PullSymbol(declName, declKind); + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + variableSymbol.type = this.semanticInfoChain.anyTypeSymbol; + + this.semanticInfoChain.setSymbolForAST(identifier, variableSymbol); + }; + + PullSymbolBinder.prototype.bindEnumMemberDeclarationToPullSymbol = function (propertyDeclaration) { + var declFlags = propertyDeclaration.flags; + var declKind = propertyDeclaration.kind; + var propDeclAST = this.semanticInfoChain.getASTForDecl(propertyDeclaration); + + var declName = propertyDeclaration.name; + + var parentHadSymbol = false; + + var parent = this.getParent(propertyDeclaration, true); + + var propertySymbol = parent.findMember(declName, false); + + if (propertySymbol) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(propDeclAST.propertyName, propertyDeclaration.getDisplayName(), propertySymbol.getDeclarations()[0].ast()); + } + + if (propertySymbol) { + parentHadSymbol = true; + } + + if (!parentHadSymbol) { + propertySymbol = new TypeScript.PullSymbol(declName, declKind); + } + + propertySymbol.addDeclaration(propertyDeclaration); + propertyDeclaration.setSymbol(propertySymbol); + + this.semanticInfoChain.setSymbolForAST(propDeclAST.propertyName, propertySymbol); + this.semanticInfoChain.setSymbolForAST(propDeclAST, propertySymbol); + + if (parent && !parentHadSymbol) { + parent.addMember(propertySymbol); + } + }; + + PullSymbolBinder.prototype.bindPropertyDeclarationToPullSymbol = function (propertyDeclaration) { + var declFlags = propertyDeclaration.flags; + var declKind = propertyDeclaration.kind; + + var ast = this.semanticInfoChain.getASTForDecl(propertyDeclaration); + var astName = ast.kind() === 136 /* MemberVariableDeclaration */ ? ast.variableDeclarator.propertyName : ast.kind() === 141 /* PropertySignature */ ? ast.propertyName : ast.kind() === 242 /* Parameter */ ? ast.identifier : ast.propertyName; + + var isStatic = false; + var isOptional = false; + + var propertySymbol = null; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + if (TypeScript.hasFlag(declFlags, 128 /* Optional */)) { + isOptional = true; + } + + var declName = propertyDeclaration.name; + + var parentHadSymbol = false; + + var parent = this.getParent(propertyDeclaration, true); + + if (parent.isClass() && isStatic) { + parent = parent.getConstructorMethod().type; + } + + propertySymbol = parent.findMember(declName, false); + + if (propertySymbol) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(astName, propertyDeclaration.getDisplayName(), propertySymbol.getDeclarations()[0].ast()); + } + + if (propertySymbol) { + parentHadSymbol = true; + } + + var classTypeSymbol; + + if (!parentHadSymbol) { + propertySymbol = new TypeScript.PullSymbol(declName, declKind); + } + + propertySymbol.addDeclaration(propertyDeclaration); + propertyDeclaration.setSymbol(propertySymbol); + + this.semanticInfoChain.setSymbolForAST(astName, propertySymbol); + this.semanticInfoChain.setSymbolForAST(ast, propertySymbol); + + if (isOptional) { + propertySymbol.isOptional = true; + } + + if (parent && !parentHadSymbol) { + parent.addMember(propertySymbol); + } + }; + + PullSymbolBinder.prototype.bindParameterSymbols = function (functionDeclaration, parameterList, funcType, signatureSymbol) { + var parameters = []; + var params = TypeScript.createIntrinsicsObject(); + var funcDecl = this.semanticInfoChain.getDeclForAST(functionDeclaration); + + if (parameterList) { + for (var i = 0, n = parameterList.length; i < n; i++) { + var argDecl = parameterList.astAt(i); + var id = parameterList.identifierAt(i); + var decl = this.semanticInfoChain.getDeclForAST(argDecl); + var isProperty = TypeScript.hasFlag(decl.flags, 8388608 /* PropertyParameter */); + var parameterSymbol = new TypeScript.PullSymbol(id.valueText(), 2048 /* Parameter */); + + if ((i === (n - 1)) && parameterList.lastParameterIsRest()) { + parameterSymbol.isVarArg = true; + } + + if (params[id.valueText()]) { + this.semanticInfoChain.addDiagnosticFromAST(argDecl, TypeScript.DiagnosticCode.Duplicate_identifier_0, [id.text()]); + } else { + params[id.valueText()] = true; + } + + if (decl) { + var isParameterOptional = false; + + if (isProperty) { + decl.ensureSymbolIsBound(); + var valDecl = decl.getValueDecl(); + + if (valDecl) { + isParameterOptional = TypeScript.hasFlag(valDecl.flags, 128 /* Optional */); + + valDecl.setSymbol(parameterSymbol); + parameterSymbol.addDeclaration(valDecl); + } + } else { + isParameterOptional = TypeScript.hasFlag(decl.flags, 128 /* Optional */); + + parameterSymbol.addDeclaration(decl); + decl.setSymbol(parameterSymbol); + } + + parameterSymbol.isOptional = isParameterOptional; + } + + signatureSymbol.addParameter(parameterSymbol, parameterSymbol.isOptional); + + if (signatureSymbol.isDefinition()) { + funcType.addEnclosedNonMember(parameterSymbol); + } + } + } + }; + + PullSymbolBinder.prototype.bindFunctionDeclarationToPullSymbol = function (functionDeclaration) { + var declKind = functionDeclaration.kind; + var declFlags = functionDeclaration.flags; + var funcDeclAST = this.semanticInfoChain.getASTForDecl(functionDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = functionDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(functionDeclaration, true); + + var parentDecl = functionDeclaration.getParentDecl(); + var parentHadSymbol = false; + + var functionSymbol = null; + var functionTypeSymbol = null; + + functionSymbol = this.getExistingSymbol(functionDeclaration, 68147712 /* SomeValue */, parent); + + if (functionSymbol) { + var acceptableRedeclaration; + + if (functionSymbol.kind === 16384 /* Function */) { + acceptableRedeclaration = isSignature || functionSymbol.allDeclsHaveFlag(2048 /* Signature */); + } else { + var isCurrentDeclAmbient = TypeScript.hasFlag(functionDeclaration.flags, 8 /* Ambient */); + acceptableRedeclaration = TypeScript.ArrayUtilities.all(functionSymbol.getDeclarations(), function (decl) { + var isInitializedModuleOrAmbientDecl = TypeScript.hasFlag(decl.flags, 32768 /* InitializedModule */) && (isCurrentDeclAmbient || TypeScript.hasFlag(decl.flags, 8 /* Ambient */)); + var isSignature = TypeScript.hasFlag(decl.flags, 2048 /* Signature */); + return isInitializedModuleOrAmbientDecl || isSignature; + }); + } + + if (!acceptableRedeclaration) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.identifier, functionDeclaration.getDisplayName(), functionSymbol.getDeclarations()[0].ast()); + functionSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(funcName); + } + } + + if (functionSymbol) { + functionTypeSymbol = functionSymbol.type; + parentHadSymbol = true; + } + + if (!functionSymbol) { + functionSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + } + + if (!functionTypeSymbol) { + functionTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + functionSymbol.type = functionTypeSymbol; + functionTypeSymbol.setFunctionSymbol(functionSymbol); + } + + functionDeclaration.setSymbol(functionSymbol); + functionSymbol.addDeclaration(functionDeclaration); + functionTypeSymbol.addDeclaration(functionDeclaration); + + this.semanticInfoChain.setSymbolForAST(funcDeclAST.identifier, functionSymbol); + this.semanticInfoChain.setSymbolForAST(funcDeclAST, functionSymbol); + + if (parent && !parentHadSymbol) { + if (isExported) { + parent.addMember(functionSymbol); + } else { + parent.addEnclosedNonMember(functionSymbol); + } + } + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + signature.addDeclaration(functionDeclaration); + functionDeclaration.setSignatureSymbol(signature); + + if (TypeScript.lastParameterIsRest(funcDeclAST.callSignature.parameterList)) { + signature.hasVarArgs = true; + } + + var funcDecl = this.semanticInfoChain.getASTForDecl(functionDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), functionTypeSymbol, signature); + + var typeParameters = functionDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.name]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + functionTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindFunctionExpressionToPullSymbol = function (functionExpressionDeclaration) { + var declKind = functionExpressionDeclaration.kind; + var declFlags = functionExpressionDeclaration.flags; + var ast = this.semanticInfoChain.getASTForDecl(functionExpressionDeclaration); + + var parameters = ast.kind() === 219 /* SimpleArrowFunctionExpression */ ? TypeScript.ASTHelpers.parametersFromIdentifier(ast.identifier) : TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(ast)); + var funcExpAST = ast; + + var functionName = declKind === 131072 /* FunctionExpression */ ? functionExpressionDeclaration.getFunctionExpressionName() : functionExpressionDeclaration.name; + var functionSymbol = new TypeScript.PullSymbol(functionName, declKind); + var functionTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + functionTypeSymbol.setFunctionSymbol(functionSymbol); + + functionSymbol.type = functionTypeSymbol; + + functionExpressionDeclaration.setSymbol(functionSymbol); + functionSymbol.addDeclaration(functionExpressionDeclaration); + functionTypeSymbol.addDeclaration(functionExpressionDeclaration); + + var name = funcExpAST.kind() === 222 /* FunctionExpression */ ? funcExpAST.identifier : funcExpAST.kind() === 241 /* FunctionPropertyAssignment */ ? funcExpAST.propertyName : null; + if (name) { + this.semanticInfoChain.setSymbolForAST(name, functionSymbol); + } + + this.semanticInfoChain.setSymbolForAST(funcExpAST, functionSymbol); + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, true); + + if (parameters.lastParameterIsRest()) { + signature.hasVarArgs = true; + } + + var typeParameters = functionExpressionDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(functionExpressionDeclaration); + functionExpressionDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcExpAST, parameters, functionTypeSymbol, signature); + + functionTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindFunctionTypeDeclarationToPullSymbol = function (functionTypeDeclaration) { + var declKind = functionTypeDeclaration.kind; + var declFlags = functionTypeDeclaration.flags; + var funcTypeAST = this.semanticInfoChain.getASTForDecl(functionTypeDeclaration); + + var functionTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + + functionTypeDeclaration.setSymbol(functionTypeSymbol); + functionTypeSymbol.addDeclaration(functionTypeDeclaration); + this.semanticInfoChain.setSymbolForAST(funcTypeAST, functionTypeSymbol); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + if (TypeScript.lastParameterIsRest(funcTypeAST.parameterList)) { + signature.hasVarArgs = true; + } + + var typeParameters = functionTypeDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.name]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(functionTypeDeclaration); + functionTypeDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcTypeAST, TypeScript.ASTHelpers.parametersFromParameterList(funcTypeAST.parameterList), functionTypeSymbol, signature); + + functionTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindMethodDeclarationToPullSymbol = function (methodDeclaration) { + var declKind = methodDeclaration.kind; + var declFlags = methodDeclaration.flags; + var methodAST = this.semanticInfoChain.getASTForDecl(methodDeclaration); + + var isPrivate = (declFlags & 2 /* Private */) !== 0; + var isStatic = (declFlags & 16 /* Static */) !== 0; + var isOptional = (declFlags & 128 /* Optional */) !== 0; + + var methodName = methodDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(methodDeclaration, true); + var parentHadSymbol = false; + + var methodSymbol = null; + var methodTypeSymbol = null; + + if (parent.isClass() && isStatic) { + parent = parent.getConstructorMethod().type; + } + + methodSymbol = parent.findMember(methodName, false); + + if (methodSymbol && (methodSymbol.kind !== 65536 /* Method */ || (!isSignature && !methodSymbol.allDeclsHaveFlag(2048 /* Signature */)))) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(methodAST, methodDeclaration.getDisplayName(), methodSymbol.getDeclarations()[0].ast()); + methodSymbol = null; + } + + if (methodSymbol) { + methodTypeSymbol = methodSymbol.type; + parentHadSymbol = true; + } + + if (!methodSymbol) { + methodSymbol = new TypeScript.PullSymbol(methodName, 65536 /* Method */); + } + + if (!methodTypeSymbol) { + methodTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + methodSymbol.type = methodTypeSymbol; + methodTypeSymbol.setFunctionSymbol(methodSymbol); + } + + methodDeclaration.setSymbol(methodSymbol); + methodSymbol.addDeclaration(methodDeclaration); + methodTypeSymbol.addDeclaration(methodDeclaration); + + var nameAST = methodAST.kind() === 135 /* MemberFunctionDeclaration */ ? methodAST.propertyName : methodAST.propertyName; + + TypeScript.Debug.assert(nameAST); + + this.semanticInfoChain.setSymbolForAST(nameAST, methodSymbol); + this.semanticInfoChain.setSymbolForAST(methodAST, methodSymbol); + + if (isOptional) { + methodSymbol.isOptional = true; + } + + if (!parentHadSymbol) { + parent.addMember(methodSymbol); + } + + var sigKind = 1048576 /* CallSignature */; + + var signature = new TypeScript.PullSignatureSymbol(sigKind, !isSignature); + + var parameterList = TypeScript.ASTHelpers.getParameterList(methodAST); + if (TypeScript.lastParameterIsRest(parameterList)) { + signature.hasVarArgs = true; + } + + var typeParameters = methodDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterName; + var typeParameterAST; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameterName = typeParameters[i].name; + typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameters[i]); + + typeParameter = signature.findTypeParameter(typeParameterName); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameterName); + signature.addTypeParameter(typeParameter); + } else { + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(methodDeclaration); + methodDeclaration.setSignatureSymbol(signature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(methodDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(funcDecl)), methodTypeSymbol, signature); + + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(signature, methodTypeSymbol.getOwnCallSignatures()); + methodTypeSymbol.insertCallSignatureAtIndex(signature, signatureIndex); + }; + + PullSymbolBinder.prototype.bindStaticPrototypePropertyOfClass = function (classAST, classTypeSymbol, constructorTypeSymbol) { + var prototypeStr = "prototype"; + + var prototypeSymbol = constructorTypeSymbol.findMember(prototypeStr, false); + if (prototypeSymbol && !prototypeSymbol.getIsSynthesized()) { + this.semanticInfoChain.addDiagnostic(TypeScript.PullHelpers.diagnosticFromDecl(prototypeSymbol.getDeclarations()[0], TypeScript.DiagnosticCode.Duplicate_identifier_0, [prototypeSymbol.getDisplayName()])); + } + + if (!prototypeSymbol || !prototypeSymbol.getIsSynthesized()) { + var prototypeDecl = new TypeScript.PullSynthesizedDecl(prototypeStr, prototypeStr, 4096 /* Property */, 4 /* Public */ | 16 /* Static */, constructorTypeSymbol.getDeclarations()[0], this.semanticInfoChain); + + prototypeSymbol = new TypeScript.PullSymbol(prototypeStr, 4096 /* Property */); + prototypeSymbol.setIsSynthesized(); + prototypeSymbol.addDeclaration(prototypeDecl); + prototypeSymbol.type = classTypeSymbol; + constructorTypeSymbol.addMember(prototypeSymbol); + + if (prototypeSymbol.type && prototypeSymbol.type.isGeneric()) { + var resolver = this.semanticInfoChain.getResolver(); + prototypeSymbol.type = resolver.instantiateTypeToAny(prototypeSymbol.type, new TypeScript.PullTypeResolutionContext(resolver)); + } + prototypeSymbol.setResolved(); + } + }; + + PullSymbolBinder.prototype.bindConstructorDeclarationToPullSymbol = function (constructorDeclaration) { + var declKind = constructorDeclaration.kind; + var declFlags = constructorDeclaration.flags; + var constructorAST = this.semanticInfoChain.getASTForDecl(constructorDeclaration); + + var constructorName = constructorDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(constructorDeclaration, true); + + var parentHadSymbol = false; + + var constructorSymbol = parent.getConstructorMethod(); + var constructorTypeSymbol = null; + + if (constructorSymbol && (constructorSymbol.kind !== 32768 /* ConstructorMethod */ || (!isSignature && constructorSymbol.type && constructorSymbol.type.hasOwnConstructSignatures()))) { + var hasDefinitionSignature = false; + var constructorSigs = constructorSymbol.type.getOwnDeclaredConstructSignatures(); + + for (var i = 0; i < constructorSigs.length; i++) { + if (!constructorSigs[i].anyDeclHasFlag(2048 /* Signature */)) { + hasDefinitionSignature = true; + break; + } + } + + if (hasDefinitionSignature) { + this.semanticInfoChain.addDiagnosticFromAST(constructorAST, TypeScript.DiagnosticCode.Multiple_constructor_implementations_are_not_allowed); + + constructorSymbol = null; + } + } + + if (constructorSymbol) { + constructorTypeSymbol = constructorSymbol.type; + } else { + constructorSymbol = new TypeScript.PullSymbol(constructorName, 32768 /* ConstructorMethod */); + constructorTypeSymbol = new TypeScript.PullTypeSymbol("", 33554432 /* ConstructorType */); + } + + parent.setConstructorMethod(constructorSymbol); + constructorSymbol.type = constructorTypeSymbol; + + constructorDeclaration.setSymbol(constructorSymbol); + constructorSymbol.addDeclaration(constructorDeclaration); + constructorTypeSymbol.addDeclaration(constructorDeclaration); + constructorSymbol.setIsSynthesized(false); + this.semanticInfoChain.setSymbolForAST(constructorAST, constructorSymbol); + + var constructSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */, !isSignature); + constructSignature.returnType = parent; + constructSignature.addTypeParametersFromReturnType(); + + constructSignature.addDeclaration(constructorDeclaration); + constructorDeclaration.setSignatureSymbol(constructSignature); + + this.bindParameterSymbols(constructorAST, TypeScript.ASTHelpers.parametersFromParameterList(constructorAST.callSignature.parameterList), constructorTypeSymbol, constructSignature); + + if (TypeScript.lastParameterIsRest(constructorAST.callSignature.parameterList)) { + constructSignature.hasVarArgs = true; + } + + constructorTypeSymbol.appendConstructSignature(constructSignature); + }; + + PullSymbolBinder.prototype.bindConstructSignatureDeclarationToPullSymbol = function (constructSignatureDeclaration) { + var parent = this.getParent(constructSignatureDeclaration, true); + var constructorAST = this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration); + + var constructSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + + if (TypeScript.lastParameterIsRest(constructorAST.callSignature.parameterList)) { + constructSignature.hasVarArgs = true; + } + + var typeParameters = constructSignatureDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = constructSignature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + constructSignature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + constructSignature.addDeclaration(constructSignatureDeclaration); + constructSignatureDeclaration.setSignatureSymbol(constructSignature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(funcDecl)), null, constructSignature); + + this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration), constructSignature); + + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(constructSignature, parent.getOwnDeclaredConstructSignatures()); + parent.insertConstructSignatureAtIndex(constructSignature, signatureIndex); + }; + + PullSymbolBinder.prototype.bindCallSignatureDeclarationToPullSymbol = function (callSignatureDeclaration) { + var parent = this.getParent(callSignatureDeclaration, true); + var callSignatureAST = this.semanticInfoChain.getASTForDecl(callSignatureDeclaration); + + var callSignature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */); + + if (TypeScript.lastParameterIsRest(callSignatureAST.parameterList)) { + callSignature.hasVarArgs = true; + } + + var typeParameters = callSignatureDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = callSignature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + callSignature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + callSignature.addDeclaration(callSignatureDeclaration); + callSignatureDeclaration.setSignatureSymbol(callSignature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(callSignatureDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList), null, callSignature); + + this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(callSignatureDeclaration), callSignature); + + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(callSignature, parent.getOwnCallSignatures()); + parent.insertCallSignatureAtIndex(callSignature, signatureIndex); + }; + + PullSymbolBinder.prototype.bindIndexSignatureDeclarationToPullSymbol = function (indexSignatureDeclaration) { + var indexSignature = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + + indexSignature.addDeclaration(indexSignatureDeclaration); + indexSignatureDeclaration.setSignatureSymbol(indexSignature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(indexSignatureDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameter(funcDecl.parameter), null, indexSignature); + + this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(indexSignatureDeclaration), indexSignature); + + var parent = this.getParent(indexSignatureDeclaration); + parent.addIndexSignature(indexSignature); + indexSignature.setContainer(parent); + }; + + PullSymbolBinder.prototype.bindGetAccessorDeclarationToPullSymbol = function (getAccessorDeclaration) { + var declKind = getAccessorDeclaration.kind; + var declFlags = getAccessorDeclaration.flags; + var funcDeclAST = this.semanticInfoChain.getASTForDecl(getAccessorDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = getAccessorDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var isStatic = false; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + var parent = this.getParent(getAccessorDeclaration, true); + var parentHadSymbol = false; + + var accessorSymbol = null; + var getterSymbol = null; + var getterTypeSymbol = null; + + if (isStatic) { + parent = parent.getConstructorMethod().type; + } + + accessorSymbol = parent.findMember(funcName, false); + + if (accessorSymbol) { + if (!accessorSymbol.isAccessor()) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.propertyName, getAccessorDeclaration.getDisplayName(), accessorSymbol.getDeclarations()[0].ast()); + accessorSymbol = null; + } else { + getterSymbol = accessorSymbol.getGetter(); + + if (getterSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Getter_0_already_declared, [getAccessorDeclaration.getDisplayName()]); + accessorSymbol = null; + getterSymbol = null; + } + } + } + + if (accessorSymbol) { + parentHadSymbol = true; + } + + if (accessorSymbol && getterSymbol) { + getterTypeSymbol = getterSymbol.type; + } + + if (!accessorSymbol) { + accessorSymbol = new TypeScript.PullAccessorSymbol(funcName); + } + + if (!getterSymbol) { + getterSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + getterTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + getterTypeSymbol.setFunctionSymbol(getterSymbol); + + getterSymbol.type = getterTypeSymbol; + + accessorSymbol.setGetter(getterSymbol); + } + + getAccessorDeclaration.setSymbol(accessorSymbol); + accessorSymbol.addDeclaration(getAccessorDeclaration); + getterSymbol.addDeclaration(getAccessorDeclaration); + + var nameAST = funcDeclAST.propertyName; + this.semanticInfoChain.setSymbolForAST(nameAST, accessorSymbol); + this.semanticInfoChain.setSymbolForAST(funcDeclAST, getterSymbol); + + if (!parentHadSymbol) { + parent.addMember(accessorSymbol); + } + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + signature.addDeclaration(getAccessorDeclaration); + getAccessorDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcDeclAST, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), getterTypeSymbol, signature); + + getterTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindSetAccessorDeclarationToPullSymbol = function (setAccessorDeclaration) { + var declKind = setAccessorDeclaration.kind; + var declFlags = setAccessorDeclaration.flags; + var funcDeclAST = this.semanticInfoChain.getASTForDecl(setAccessorDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = setAccessorDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var isStatic = false; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + var parent = this.getParent(setAccessorDeclaration, true); + var parentHadSymbol = false; + + var accessorSymbol = null; + var setterSymbol = null; + var setterTypeSymbol = null; + + if (isStatic) { + parent = parent.getConstructorMethod().type; + } + + accessorSymbol = parent.findMember(funcName, false); + + if (accessorSymbol) { + if (!accessorSymbol.isAccessor()) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.propertyName, setAccessorDeclaration.getDisplayName(), accessorSymbol.getDeclarations()[0].ast()); + accessorSymbol = null; + } else { + setterSymbol = accessorSymbol.getSetter(); + + if (setterSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Setter_0_already_declared, [setAccessorDeclaration.getDisplayName()]); + accessorSymbol = null; + setterSymbol = null; + } + } + } + + if (accessorSymbol) { + parentHadSymbol = true; + + if (setterSymbol) { + setterTypeSymbol = setterSymbol.type; + } + } + + if (!accessorSymbol) { + accessorSymbol = new TypeScript.PullAccessorSymbol(funcName); + } + + if (!setterSymbol) { + setterSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + setterTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + setterTypeSymbol.setFunctionSymbol(setterSymbol); + + setterSymbol.type = setterTypeSymbol; + + accessorSymbol.setSetter(setterSymbol); + } + + setAccessorDeclaration.setSymbol(accessorSymbol); + accessorSymbol.addDeclaration(setAccessorDeclaration); + setterSymbol.addDeclaration(setAccessorDeclaration); + + var nameAST = funcDeclAST.propertyName; + this.semanticInfoChain.setSymbolForAST(nameAST, accessorSymbol); + this.semanticInfoChain.setSymbolForAST(funcDeclAST, setterSymbol); + + if (!parentHadSymbol) { + parent.addMember(accessorSymbol); + } + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + signature.addDeclaration(setAccessorDeclaration); + setAccessorDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcDeclAST, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), setterTypeSymbol, signature); + + setterTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.getDeclsToBind = function (decl) { + var decls; + switch (decl.kind) { + case 64 /* Enum */: + case 32 /* DynamicModule */: + case 4 /* Container */: + case 16 /* Interface */: + decls = this.findDeclsInContext(decl, decl.kind, true); + break; + + case 512 /* Variable */: + case 16384 /* Function */: + case 65536 /* Method */: + case 32768 /* ConstructorMethod */: + decls = this.findDeclsInContext(decl, decl.kind, false); + break; + + default: + decls = [decl]; + } + TypeScript.Debug.assert(decls && decls.length > 0); + TypeScript.Debug.assert(TypeScript.ArrayUtilities.contains(decls, decl)); + return decls; + }; + + PullSymbolBinder.prototype.shouldBindDeclaration = function (decl) { + return !decl.hasBeenBound() && this.declsBeingBound.indexOf(decl.declID) < 0; + }; + + PullSymbolBinder.prototype.bindDeclToPullSymbol = function (decl) { + if (this.shouldBindDeclaration(decl)) { + this.bindAllDeclsToPullSymbol(decl); + } + }; + + PullSymbolBinder.prototype.bindAllDeclsToPullSymbol = function (askedDecl) { + var allDecls = this.getDeclsToBind(askedDecl); + for (var i = 0; i < allDecls.length; i++) { + var decl = allDecls[i]; + + if (this.shouldBindDeclaration(decl)) { + this.bindSingleDeclToPullSymbol(decl); + } + } + }; + + PullSymbolBinder.prototype.bindSingleDeclToPullSymbol = function (decl) { + this.declsBeingBound.push(decl.declID); + + switch (decl.kind) { + case 1 /* Script */: + var childDecls = decl.getChildDecls(); + for (var i = 0; i < childDecls.length; i++) { + this.bindDeclToPullSymbol(childDecls[i]); + } + break; + + case 64 /* Enum */: + this.bindEnumDeclarationToPullSymbol(decl); + break; + + case 32 /* DynamicModule */: + case 4 /* Container */: + this.bindModuleDeclarationToPullSymbol(decl); + break; + + case 16 /* Interface */: + this.bindInterfaceDeclarationToPullSymbol(decl); + break; + + case 8 /* Class */: + this.bindClassDeclarationToPullSymbol(decl); + break; + + case 16384 /* Function */: + this.bindFunctionDeclarationToPullSymbol(decl); + break; + + case 512 /* Variable */: + this.bindVariableDeclarationToPullSymbol(decl); + break; + + case 1024 /* CatchVariable */: + this.bindCatchVariableToPullSymbol(decl); + break; + + case 67108864 /* EnumMember */: + this.bindEnumMemberDeclarationToPullSymbol(decl); + break; + + case 4096 /* Property */: + this.bindPropertyDeclarationToPullSymbol(decl); + break; + + case 65536 /* Method */: + this.bindMethodDeclarationToPullSymbol(decl); + break; + + case 32768 /* ConstructorMethod */: + this.bindConstructorDeclarationToPullSymbol(decl); + break; + + case 1048576 /* CallSignature */: + this.bindCallSignatureDeclarationToPullSymbol(decl); + break; + + case 2097152 /* ConstructSignature */: + this.bindConstructSignatureDeclarationToPullSymbol(decl); + break; + + case 4194304 /* IndexSignature */: + this.bindIndexSignatureDeclarationToPullSymbol(decl); + break; + + case 262144 /* GetAccessor */: + this.bindGetAccessorDeclarationToPullSymbol(decl); + break; + + case 524288 /* SetAccessor */: + this.bindSetAccessorDeclarationToPullSymbol(decl); + break; + + case 8388608 /* ObjectType */: + this.bindObjectTypeDeclarationToPullSymbol(decl); + break; + + case 16777216 /* FunctionType */: + this.bindFunctionTypeDeclarationToPullSymbol(decl); + break; + + case 33554432 /* ConstructorType */: + this.bindConstructorTypeDeclarationToPullSymbol(decl); + break; + + case 131072 /* FunctionExpression */: + this.bindFunctionExpressionToPullSymbol(decl); + break; + + case 128 /* TypeAlias */: + this.bindImportDeclaration(decl); + break; + + case 2048 /* Parameter */: + case 8192 /* TypeParameter */: + decl.getParentDecl().getSymbol(); + break; + + case 268435456 /* CatchBlock */: + case 134217728 /* WithBlock */: + break; + + default: + TypeScript.CompilerDiagnostics.assert(false, "Unrecognized type declaration"); + } + + TypeScript.Debug.assert(TypeScript.ArrayUtilities.last(this.declsBeingBound) === decl.declID); + this.declsBeingBound.pop(); + }; + return PullSymbolBinder; + })(); + TypeScript.PullSymbolBinder = PullSymbolBinder; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (PullHelpers) { + function diagnosticFromDecl(decl, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + var ast = decl.ast(); + return decl.semanticInfoChain.diagnosticFromAST(ast, diagnosticKey, _arguments, additionalLocations); + } + PullHelpers.diagnosticFromDecl = diagnosticFromDecl; + + function resolveDeclaredSymbolToUseType(symbol) { + if (symbol.isSignature()) { + if (!symbol.returnType) { + symbol._resolveDeclaredSymbol(); + } + } else if (!symbol.type) { + symbol._resolveDeclaredSymbol(); + } + } + PullHelpers.resolveDeclaredSymbolToUseType = resolveDeclaredSymbolToUseType; + + function getSignatureForFuncDecl(functionDecl) { + var funcDecl = functionDecl.ast(); + var funcSymbol = functionDecl.getSymbol(); + + if (!funcSymbol) { + funcSymbol = functionDecl.getSignatureSymbol(); + } + + var functionSignature = null; + var typeSymbolWithAllSignatures = null; + if (funcSymbol.isSignature()) { + functionSignature = funcSymbol; + var parent = functionDecl.getParentDecl(); + typeSymbolWithAllSignatures = parent.getSymbol().type; + } else { + functionSignature = functionDecl.getSignatureSymbol(); + typeSymbolWithAllSignatures = funcSymbol.type; + } + var signatures; + + if (funcDecl.kind() === 137 /* ConstructorDeclaration */ || functionDecl.kind === 2097152 /* ConstructSignature */) { + signatures = typeSymbolWithAllSignatures.getConstructSignatures(); + } else if (functionDecl.kind === 4194304 /* IndexSignature */) { + signatures = typeSymbolWithAllSignatures.getIndexSignatures(); + } else { + signatures = typeSymbolWithAllSignatures.getCallSignatures(); + } + + return { + signature: functionSignature, + allSignatures: signatures + }; + } + PullHelpers.getSignatureForFuncDecl = getSignatureForFuncDecl; + + function getAccessorSymbol(getterOrSetter, semanticInfoChain) { + var functionDecl = semanticInfoChain.getDeclForAST(getterOrSetter); + var getterOrSetterSymbol = functionDecl.getSymbol(); + + return getterOrSetterSymbol; + } + PullHelpers.getAccessorSymbol = getAccessorSymbol; + + function getGetterAndSetterFunction(funcDecl, semanticInfoChain) { + var accessorSymbol = PullHelpers.getAccessorSymbol(funcDecl, semanticInfoChain); + var result = { + getter: null, + setter: null + }; + var getter = accessorSymbol.getGetter(); + if (getter) { + var getterDecl = getter.getDeclarations()[0]; + result.getter = semanticInfoChain.getASTForDecl(getterDecl); + } + var setter = accessorSymbol.getSetter(); + if (setter) { + var setterDecl = setter.getDeclarations()[0]; + result.setter = semanticInfoChain.getASTForDecl(setterDecl); + } + + return result; + } + PullHelpers.getGetterAndSetterFunction = getGetterAndSetterFunction; + + function symbolIsEnum(source) { + return source && (source.kind & (64 /* Enum */ | 67108864 /* EnumMember */)) !== 0; + } + PullHelpers.symbolIsEnum = symbolIsEnum; + + function symbolIsModule(symbol) { + return symbol && (symbol.kind === 4 /* Container */ || isOneDeclarationOfKind(symbol, 4 /* Container */)); + } + PullHelpers.symbolIsModule = symbolIsModule; + + function isOneDeclarationOfKind(symbol, kind) { + var decls = symbol.getDeclarations(); + for (var i = 0; i < decls.length; i++) { + if (decls[i].kind === kind) { + return true; + } + } + + return false; + } + + function isNameNumeric(name) { + return isFinite(+name); + } + PullHelpers.isNameNumeric = isNameNumeric; + + function typeSymbolsAreIdentical(a, b) { + if (a.isTypeReference() && !a.getIsSpecialized()) { + a = a.referencedTypeSymbol; + } + + if (b.isTypeReference() && !b.getIsSpecialized()) { + b = b.referencedTypeSymbol; + } + + return a === b; + } + PullHelpers.typeSymbolsAreIdentical = typeSymbolsAreIdentical; + + function getRootType(type) { + var rootType = type.getRootSymbol(); + + while (true) { + if (type === rootType) { + return type; + } + + type = rootType; + rootType = type.getRootSymbol(); + } + } + PullHelpers.getRootType = getRootType; + + function isSymbolLocal(symbol) { + var container = symbol.getContainer(); + if (container) { + var containerKind = container.kind; + if (containerKind & (1032192 /* SomeFunction */ | 16777216 /* FunctionType */)) { + return true; + } + + if (containerKind === 33554432 /* ConstructorType */ && !symbol.anyDeclHasFlag(16 /* Static */ | 1 /* Exported */)) { + return true; + } + } + + return false; + } + PullHelpers.isSymbolLocal = isSymbolLocal; + + function isExportedSymbolInClodule(symbol) { + var container = symbol.getContainer(); + return container && container.kind === 33554432 /* ConstructorType */ && symbolIsModule(container) && symbol.anyDeclHasFlag(1 /* Exported */); + } + PullHelpers.isExportedSymbolInClodule = isExportedSymbolInClodule; + + function isSymbolDeclaredInScopeChain(symbol, scopeSymbol) { + TypeScript.Debug.assert(symbol); + var symbolDeclarationScope = symbol.getContainer(); + + while (scopeSymbol) { + if (scopeSymbol === symbolDeclarationScope) { + return true; + } + + scopeSymbol = scopeSymbol.getContainer(); + } + + if (scopeSymbol === null && symbolDeclarationScope === null) { + return true; + } + + return false; + } + PullHelpers.isSymbolDeclaredInScopeChain = isSymbolDeclaredInScopeChain; + + + + function walkSignatureSymbol(signatureSymbol, walker) { + var continueWalk = true; + var parameters = signatureSymbol.parameters; + if (parameters) { + for (var i = 0; continueWalk && i < parameters.length; i++) { + continueWalk = walker.signatureParameterWalk(parameters[i]); + } + } + + if (continueWalk) { + continueWalk = walker.signatureReturnTypeWalk(signatureSymbol.returnType); + } + + return continueWalk; + } + + function walkPullTypeSymbolStructure(typeSymbol, walker) { + var continueWalk = true; + + var members = typeSymbol.getMembers(); + for (var i = 0; continueWalk && i < members.length; i++) { + continueWalk = walker.memberSymbolWalk(members[i]); + } + + if (continueWalk) { + var callSigantures = typeSymbol.getCallSignatures(); + for (var i = 0; continueWalk && i < callSigantures.length; i++) { + continueWalk = walker.callSignatureWalk(callSigantures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(callSigantures[i], walker); + } + } + } + + if (continueWalk) { + var constructSignatures = typeSymbol.getConstructSignatures(); + for (var i = 0; continueWalk && i < constructSignatures.length; i++) { + continueWalk = walker.constructSignatureWalk(constructSignatures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(constructSignatures[i], walker); + } + } + } + + if (continueWalk) { + var indexSignatures = typeSymbol.getIndexSignatures(); + for (var i = 0; continueWalk && i < indexSignatures.length; i++) { + continueWalk = walker.indexSignatureWalk(indexSignatures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(indexSignatures[i], walker); + } + } + } + } + PullHelpers.walkPullTypeSymbolStructure = walkPullTypeSymbolStructure; + + var OtherPullDeclsWalker = (function () { + function OtherPullDeclsWalker() { + this.currentlyWalkingOtherDecls = []; + } + OtherPullDeclsWalker.prototype.walkOtherPullDecls = function (currentDecl, otherDecls, callBack) { + if (otherDecls) { + var isAlreadyWalkingOtherDecl = TypeScript.ArrayUtilities.any(this.currentlyWalkingOtherDecls, function (inWalkingOtherDecl) { + return TypeScript.ArrayUtilities.contains(otherDecls, inWalkingOtherDecl); + }); + + if (!isAlreadyWalkingOtherDecl) { + this.currentlyWalkingOtherDecls.push(currentDecl); + for (var i = 0; i < otherDecls.length; i++) { + if (otherDecls[i] !== currentDecl) { + callBack(otherDecls[i]); + } + } + var currentlyWalkingOtherDeclsDecl = this.currentlyWalkingOtherDecls.pop(); + TypeScript.Debug.assert(currentlyWalkingOtherDeclsDecl == currentDecl); + } + } + }; + return OtherPullDeclsWalker; + })(); + PullHelpers.OtherPullDeclsWalker = OtherPullDeclsWalker; + })(TypeScript.PullHelpers || (TypeScript.PullHelpers = {})); + var PullHelpers = TypeScript.PullHelpers; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var WrapsTypeParameterCache = (function () { + function WrapsTypeParameterCache() { + this._wrapsTypeParameterCache = TypeScript.BitVector.getBitVector(true); + } + WrapsTypeParameterCache.prototype.getWrapsTypeParameter = function (typeParameterArgumentMap) { + var mapHasTypeParameterNotCached = false; + for (var typeParameterID in typeParameterArgumentMap) { + if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + var cachedValue = this._wrapsTypeParameterCache.valueAt(typeParameterID); + if (cachedValue) { + return typeParameterID; + } + mapHasTypeParameterNotCached = mapHasTypeParameterNotCached || cachedValue === undefined; + } + } + + if (!mapHasTypeParameterNotCached) { + return 0; + } + + return undefined; + }; + + WrapsTypeParameterCache.prototype.setWrapsTypeParameter = function (typeParameterArgumentMap, wrappingTypeParameterID) { + if (wrappingTypeParameterID) { + this._wrapsTypeParameterCache.setValueAt(wrappingTypeParameterID, true); + } else { + for (var typeParameterID in typeParameterArgumentMap) { + if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + this._wrapsTypeParameterCache.setValueAt(typeParameterID, false); + } + } + } + }; + return WrapsTypeParameterCache; + })(); + TypeScript.WrapsTypeParameterCache = WrapsTypeParameterCache; + + (function (PullInstantiationHelpers) { + var MutableTypeArgumentMap = (function () { + function MutableTypeArgumentMap(typeParameterArgumentMap) { + this.typeParameterArgumentMap = typeParameterArgumentMap; + this.createdDuplicateTypeArgumentMap = false; + } + MutableTypeArgumentMap.prototype.ensureTypeArgumentCopy = function () { + if (!this.createdDuplicateTypeArgumentMap) { + var passedInTypeArgumentMap = this.typeParameterArgumentMap; + this.typeParameterArgumentMap = []; + for (var typeParameterID in passedInTypeArgumentMap) { + if (passedInTypeArgumentMap.hasOwnProperty(typeParameterID)) { + this.typeParameterArgumentMap[typeParameterID] = passedInTypeArgumentMap[typeParameterID]; + } + } + this.createdDuplicateTypeArgumentMap = true; + } + }; + return MutableTypeArgumentMap; + })(); + PullInstantiationHelpers.MutableTypeArgumentMap = MutableTypeArgumentMap; + + function instantiateTypeArgument(resolver, symbol, mutableTypeParameterMap) { + if (symbol.getIsSpecialized()) { + var rootTypeArgumentMap = symbol.getTypeParameterArgumentMap(); + var newTypeArgumentMap = []; + var allowedTypeParameters = symbol.getAllowedToReferenceTypeParameters(); + for (var i = 0; i < allowedTypeParameters.length; i++) { + var typeParameterID = allowedTypeParameters[i].pullSymbolID; + var typeArg = rootTypeArgumentMap[typeParameterID]; + if (typeArg) { + newTypeArgumentMap[typeParameterID] = resolver.instantiateType(typeArg, mutableTypeParameterMap.typeParameterArgumentMap); + } + } + + for (var i = 0; i < allowedTypeParameters.length; i++) { + var typeParameterID = allowedTypeParameters[i].pullSymbolID; + if (newTypeArgumentMap[typeParameterID] && mutableTypeParameterMap.typeParameterArgumentMap[typeParameterID] != newTypeArgumentMap[typeParameterID]) { + mutableTypeParameterMap.ensureTypeArgumentCopy(); + mutableTypeParameterMap.typeParameterArgumentMap[typeParameterID] = newTypeArgumentMap[typeParameterID]; + } + } + } + } + PullInstantiationHelpers.instantiateTypeArgument = instantiateTypeArgument; + + function cleanUpTypeArgumentMap(symbol, mutableTypeArgumentMap) { + var allowedToReferenceTypeParameters = symbol.getAllowedToReferenceTypeParameters(); + for (var typeParameterID in mutableTypeArgumentMap.typeParameterArgumentMap) { + if (mutableTypeArgumentMap.typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + if (!TypeScript.ArrayUtilities.any(allowedToReferenceTypeParameters, function (typeParameter) { + return typeParameter.pullSymbolID == typeParameterID; + })) { + mutableTypeArgumentMap.ensureTypeArgumentCopy(); + delete mutableTypeArgumentMap.typeParameterArgumentMap[typeParameterID]; + } + } + } + } + PullInstantiationHelpers.cleanUpTypeArgumentMap = cleanUpTypeArgumentMap; + + function getAllowedToReferenceTypeParametersFromDecl(decl) { + var allowedToReferenceTypeParameters = []; + + var allowedToUseDeclTypeParameters = false; + var getTypeParametersFromParentDecl = false; + + switch (decl.kind) { + case 65536 /* Method */: + if (TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + allowedToUseDeclTypeParameters = true; + break; + } + + case 16777216 /* FunctionType */: + case 33554432 /* ConstructorType */: + case 2097152 /* ConstructSignature */: + case 1048576 /* CallSignature */: + case 131072 /* FunctionExpression */: + case 16384 /* Function */: + allowedToUseDeclTypeParameters = true; + getTypeParametersFromParentDecl = true; + break; + + case 4096 /* Property */: + if (TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + break; + } + + case 2048 /* Parameter */: + case 262144 /* GetAccessor */: + case 524288 /* SetAccessor */: + case 32768 /* ConstructorMethod */: + case 4194304 /* IndexSignature */: + case 8388608 /* ObjectType */: + case 256 /* ObjectLiteral */: + case 8192 /* TypeParameter */: + getTypeParametersFromParentDecl = true; + break; + + case 8 /* Class */: + case 16 /* Interface */: + allowedToUseDeclTypeParameters = true; + break; + } + + if (getTypeParametersFromParentDecl) { + allowedToReferenceTypeParameters = allowedToReferenceTypeParameters.concat(getAllowedToReferenceTypeParametersFromDecl(decl.getParentDecl())); + } + + if (allowedToUseDeclTypeParameters) { + var typeParameterDecls = decl.getTypeParameters(); + for (var i = 0; i < typeParameterDecls.length; i++) { + allowedToReferenceTypeParameters.push(typeParameterDecls[i].getSymbol()); + } + } + + return allowedToReferenceTypeParameters; + } + PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl = getAllowedToReferenceTypeParametersFromDecl; + + function createTypeParameterArgumentMap(typeParameters, typeArguments) { + return updateTypeParameterArgumentMap(typeParameters, typeArguments, {}); + } + PullInstantiationHelpers.createTypeParameterArgumentMap = createTypeParameterArgumentMap; + + function updateTypeParameterArgumentMap(typeParameters, typeArguments, typeParameterArgumentMap) { + for (var i = 0; i < typeParameters.length; i++) { + typeParameterArgumentMap[typeParameters[i].getRootSymbol().pullSymbolID] = typeArguments[i]; + } + return typeParameterArgumentMap; + } + PullInstantiationHelpers.updateTypeParameterArgumentMap = updateTypeParameterArgumentMap; + + function updateMutableTypeParameterArgumentMap(typeParameters, typeArguments, mutableMap) { + for (var i = 0; i < typeParameters.length; i++) { + var typeParameterId = typeParameters[i].getRootSymbol().pullSymbolID; + if (mutableMap.typeParameterArgumentMap[typeParameterId] !== typeArguments[i]) { + mutableMap.ensureTypeArgumentCopy(); + mutableMap.typeParameterArgumentMap[typeParameterId] = typeArguments[i]; + } + } + } + PullInstantiationHelpers.updateMutableTypeParameterArgumentMap = updateMutableTypeParameterArgumentMap; + + function twoTypesAreInstantiationsOfSameNamedGenericType(type1, type2) { + var type1IsGeneric = type1.isGeneric() && type1.getTypeArguments() !== null; + var type2IsGeneric = type2.isGeneric() && type2.getTypeArguments() !== null; + + if (type1IsGeneric && type2IsGeneric) { + var type1Root = TypeScript.PullHelpers.getRootType(type1); + var type2Root = TypeScript.PullHelpers.getRootType(type2); + return type1Root === type2Root; + } + + return false; + } + PullInstantiationHelpers.twoTypesAreInstantiationsOfSameNamedGenericType = twoTypesAreInstantiationsOfSameNamedGenericType; + })(TypeScript.PullInstantiationHelpers || (TypeScript.PullInstantiationHelpers = {})); + var PullInstantiationHelpers = TypeScript.PullInstantiationHelpers; +})(TypeScript || (TypeScript = {})); +if (Error) + Error.stackTraceLimit = 1000; + +var TypeScript; +(function (TypeScript) { + TypeScript.fileResolutionTime = 0; + TypeScript.fileResolutionIOTime = 0; + TypeScript.fileResolutionScanImportsTime = 0; + TypeScript.fileResolutionImportFileSearchTime = 0; + TypeScript.fileResolutionGetDefaultLibraryTime = 0; + TypeScript.sourceCharactersCompiled = 0; + TypeScript.syntaxTreeParseTime = 0; + TypeScript.syntaxDiagnosticsTime = 0; + TypeScript.astTranslationTime = 0; + TypeScript.typeCheckTime = 0; + + TypeScript.compilerResolvePathTime = 0; + TypeScript.compilerDirectoryNameTime = 0; + TypeScript.compilerDirectoryExistsTime = 0; + TypeScript.compilerFileExistsTime = 0; + + TypeScript.emitTime = 0; + TypeScript.emitWriteFileTime = 0; + + TypeScript.declarationEmitTime = 0; + TypeScript.declarationEmitIsExternallyVisibleTime = 0; + TypeScript.declarationEmitTypeSignatureTime = 0; + TypeScript.declarationEmitGetBoundDeclTypeTime = 0; + TypeScript.declarationEmitIsOverloadedCallSignatureTime = 0; + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime = 0; + TypeScript.declarationEmitGetBaseTypeTime = 0; + TypeScript.declarationEmitGetAccessorFunctionTime = 0; + TypeScript.declarationEmitGetTypeParameterSymbolTime = 0; + TypeScript.declarationEmitGetImportDeclarationSymbolTime = 0; + + TypeScript.ioHostResolvePathTime = 0; + TypeScript.ioHostDirectoryNameTime = 0; + TypeScript.ioHostCreateDirectoryStructureTime = 0; + TypeScript.ioHostWriteFileTime = 0; + + (function (EmitOutputResult) { + EmitOutputResult[EmitOutputResult["Succeeded"] = 0] = "Succeeded"; + EmitOutputResult[EmitOutputResult["FailedBecauseOfSyntaxErrors"] = 1] = "FailedBecauseOfSyntaxErrors"; + EmitOutputResult[EmitOutputResult["FailedBecauseOfCompilerOptionsErrors"] = 2] = "FailedBecauseOfCompilerOptionsErrors"; + EmitOutputResult[EmitOutputResult["FailedToGenerateDeclarationsBecauseOfSemanticErrors"] = 3] = "FailedToGenerateDeclarationsBecauseOfSemanticErrors"; + })(TypeScript.EmitOutputResult || (TypeScript.EmitOutputResult = {})); + var EmitOutputResult = TypeScript.EmitOutputResult; + + var EmitOutput = (function () { + function EmitOutput(emitOutputResult) { + if (typeof emitOutputResult === "undefined") { emitOutputResult = 0 /* Succeeded */; } + this.outputFiles = []; + this.emitOutputResult = emitOutputResult; + } + return EmitOutput; + })(); + TypeScript.EmitOutput = EmitOutput; + + (function (OutputFileType) { + OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; + OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; + OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; + })(TypeScript.OutputFileType || (TypeScript.OutputFileType = {})); + var OutputFileType = TypeScript.OutputFileType; + + var OutputFile = (function () { + function OutputFile(name, writeByteOrderMark, text, fileType, sourceMapEntries) { + if (typeof sourceMapEntries === "undefined") { sourceMapEntries = []; } + this.name = name; + this.writeByteOrderMark = writeByteOrderMark; + this.text = text; + this.fileType = fileType; + this.sourceMapEntries = sourceMapEntries; + } + return OutputFile; + })(); + TypeScript.OutputFile = OutputFile; + + var CompileResult = (function () { + function CompileResult() { + this.diagnostics = []; + this.outputFiles = []; + } + CompileResult.fromDiagnostics = function (diagnostics) { + var result = new CompileResult(); + result.diagnostics = diagnostics; + return result; + }; + + CompileResult.fromOutputFiles = function (outputFiles) { + var result = new CompileResult(); + result.outputFiles = outputFiles; + return result; + }; + return CompileResult; + })(); + TypeScript.CompileResult = CompileResult; + + var TypeScriptCompiler = (function () { + function TypeScriptCompiler(logger, _settings) { + if (typeof logger === "undefined") { logger = new TypeScript.NullLogger(); } + if (typeof _settings === "undefined") { _settings = TypeScript.ImmutableCompilationSettings.defaultSettings(); } + this.logger = logger; + this._settings = _settings; + this.semanticInfoChain = null; + this.semanticInfoChain = new TypeScript.SemanticInfoChain(this, logger); + } + TypeScriptCompiler.prototype.compilationSettings = function () { + return this._settings; + }; + + TypeScriptCompiler.prototype.setCompilationSettings = function (newSettings) { + var oldSettings = this._settings; + this._settings = newSettings; + + if (!compareDataObjects(oldSettings, newSettings)) { + this.semanticInfoChain.invalidate(oldSettings, newSettings); + } + }; + + TypeScriptCompiler.prototype.getDocument = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + return this.semanticInfoChain.getDocument(fileName); + }; + + TypeScriptCompiler.prototype.cleanupSemanticCache = function () { + this.semanticInfoChain.invalidate(); + }; + + TypeScriptCompiler.prototype.addFile = function (fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles) { + if (typeof referencedFiles === "undefined") { referencedFiles = []; } + fileName = TypeScript.switchToForwardSlashes(fileName); + + TypeScript.sourceCharactersCompiled += scriptSnapshot.getLength(); + + var document = TypeScript.Document.create(this, this.semanticInfoChain, fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles); + + this.semanticInfoChain.addDocument(document); + }; + + TypeScriptCompiler.prototype.updateFile = function (fileName, scriptSnapshot, version, isOpen, textChangeRange) { + fileName = TypeScript.switchToForwardSlashes(fileName); + + var document = this.getDocument(fileName); + var updatedDocument = document.update(scriptSnapshot, version, isOpen, textChangeRange); + + this.semanticInfoChain.addDocument(updatedDocument); + }; + + TypeScriptCompiler.prototype.removeFile = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + this.semanticInfoChain.removeDocument(fileName); + }; + + TypeScriptCompiler.prototype.mapOutputFileName = function (document, emitOptions, extensionChanger) { + if (document.emitToOwnOutputFile()) { + var updatedFileName = document.fileName; + if (emitOptions.outputDirectory() !== "") { + updatedFileName = document.fileName.replace(emitOptions.commonDirectoryPath(), ""); + updatedFileName = emitOptions.outputDirectory() + updatedFileName; + } + return extensionChanger(updatedFileName, false); + } else { + return extensionChanger(emitOptions.sharedOutputFile(), true); + } + }; + + TypeScriptCompiler.prototype.writeByteOrderMarkForDocument = function (document) { + var printReason = false; + + if (document.emitToOwnOutputFile()) { + var result = document.byteOrderMark !== 0 /* None */; + if (printReason) { + TypeScript.Environment.standardOut.WriteLine("Emitting byte order mark because of: " + document.fileName); + } + return result; + } else { + var fileNames = this.fileNames(); + + var result = false; + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = this.getDocument(fileNames[i]); + + if (document.isExternalModule()) { + continue; + } + + if (document.byteOrderMark !== 0 /* None */) { + if (printReason) { + TypeScript.Environment.standardOut.WriteLine("Emitting byte order mark because of: " + document.fileName); + result = true; + } else { + return true; + } + } + } + + return result; + } + }; + + TypeScriptCompiler.mapToDTSFileName = function (fileName, wholeFileNameReplaced) { + return TypeScript.getDeclareFilePath(fileName); + }; + + TypeScriptCompiler.prototype._shouldEmit = function (document) { + return !document.isDeclareFile(); + }; + + TypeScriptCompiler.prototype._shouldEmitDeclarations = function (document) { + if (!this.compilationSettings().generateDeclarationFiles()) { + return false; + } + + return this._shouldEmit(document); + }; + + TypeScriptCompiler.prototype.emitDocumentDeclarationsWorker = function (document, emitOptions, declarationEmitter) { + var sourceUnit = document.sourceUnit(); + TypeScript.Debug.assert(this._shouldEmitDeclarations(document)); + + if (declarationEmitter) { + declarationEmitter.document = document; + } else { + var declareFileName = this.mapOutputFileName(document, emitOptions, TypeScriptCompiler.mapToDTSFileName); + declarationEmitter = new TypeScript.DeclarationEmitter(declareFileName, document, this, emitOptions, this.semanticInfoChain); + } + + declarationEmitter.emitDeclarations(sourceUnit); + return declarationEmitter; + }; + + TypeScriptCompiler.prototype._emitDocumentDeclarations = function (document, emitOptions, onSingleFileEmitComplete, sharedEmitter) { + if (this._shouldEmitDeclarations(document)) { + if (document.emitToOwnOutputFile()) { + var singleEmitter = this.emitDocumentDeclarationsWorker(document, emitOptions); + if (singleEmitter) { + onSingleFileEmitComplete(singleEmitter.getOutputFile()); + } + } else { + sharedEmitter = this.emitDocumentDeclarationsWorker(document, emitOptions, sharedEmitter); + } + } + + return sharedEmitter; + }; + + TypeScriptCompiler.prototype.emitAllDeclarations = function (resolvePath) { + var start = new Date().getTime(); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var sharedEmitter = null; + var fileNames = this.fileNames(); + + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + + var document = this.getDocument(fileNames[i]); + + sharedEmitter = this._emitDocumentDeclarations(document, emitOptions, function (file) { + return emitOutput.outputFiles.push(file); + }, sharedEmitter); + } + + if (sharedEmitter) { + emitOutput.outputFiles.push(sharedEmitter.getOutputFile()); + } + + TypeScript.declarationEmitTime += new Date().getTime() - start; + + return emitOutput; + }; + + TypeScriptCompiler.prototype.emitDeclarations = function (fileName, resolvePath) { + fileName = TypeScript.switchToForwardSlashes(fileName); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var document = this.getDocument(fileName); + + if (document.emitToOwnOutputFile()) { + this._emitDocumentDeclarations(document, emitOptions, function (file) { + return emitOutput.outputFiles.push(file); + }, null); + return emitOutput; + } else { + return this.emitAllDeclarations(resolvePath); + } + }; + + TypeScriptCompiler.prototype.canEmitDeclarations = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + var document = this.getDocument(fileName); + return this._shouldEmitDeclarations(document); + }; + + TypeScriptCompiler.mapToFileNameExtension = function (extension, fileName, wholeFileNameReplaced) { + if (wholeFileNameReplaced) { + return fileName; + } else { + var splitFname = fileName.split("."); + splitFname.pop(); + return splitFname.join(".") + extension; + } + }; + + TypeScriptCompiler.mapToJSFileName = function (fileName, wholeFileNameReplaced) { + return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced); + }; + + TypeScriptCompiler.prototype.emitDocumentWorker = function (document, emitOptions, emitter) { + var sourceUnit = document.sourceUnit(); + TypeScript.Debug.assert(this._shouldEmit(document)); + + var typeScriptFileName = document.fileName; + if (!emitter) { + var javaScriptFileName = this.mapOutputFileName(document, emitOptions, TypeScriptCompiler.mapToJSFileName); + var outFile = new TypeScript.TextWriter(javaScriptFileName, this.writeByteOrderMarkForDocument(document), 0 /* JavaScript */); + + emitter = new TypeScript.Emitter(javaScriptFileName, outFile, emitOptions, this.semanticInfoChain); + + if (this.compilationSettings().mapSourceFiles()) { + var sourceMapFile = new TypeScript.TextWriter(javaScriptFileName + TypeScript.SourceMapper.MapFileExtension, false, 1 /* SourceMap */); + emitter.createSourceMapper(document, javaScriptFileName, outFile, sourceMapFile, emitOptions.resolvePath); + } + } else if (this.compilationSettings().mapSourceFiles()) { + emitter.setSourceMapperNewSourceFile(document); + } + + emitter.setDocument(document); + emitter.emitJavascript(sourceUnit, false); + + return emitter; + }; + + TypeScriptCompiler.prototype._emitDocument = function (document, emitOptions, onSingleFileEmitComplete, sharedEmitter) { + if (this._shouldEmit(document)) { + if (document.emitToOwnOutputFile()) { + var singleEmitter = this.emitDocumentWorker(document, emitOptions); + if (singleEmitter) { + onSingleFileEmitComplete(singleEmitter.getOutputFiles()); + } + } else { + sharedEmitter = this.emitDocumentWorker(document, emitOptions, sharedEmitter); + } + } + + return sharedEmitter; + }; + + TypeScriptCompiler.prototype.emitAll = function (resolvePath) { + var start = new Date().getTime(); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var fileNames = this.fileNames(); + var sharedEmitter = null; + + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + + var document = this.getDocument(fileName); + + sharedEmitter = this._emitDocument(document, emitOptions, function (files) { + return emitOutput.outputFiles.push.apply(emitOutput.outputFiles, files); + }, sharedEmitter); + } + + if (sharedEmitter) { + emitOutput.outputFiles.push.apply(emitOutput.outputFiles, sharedEmitter.getOutputFiles()); + } + + TypeScript.emitTime += new Date().getTime() - start; + return emitOutput; + }; + + TypeScriptCompiler.prototype.emit = function (fileName, resolvePath) { + fileName = TypeScript.switchToForwardSlashes(fileName); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var document = this.getDocument(fileName); + + if (document.emitToOwnOutputFile()) { + this._emitDocument(document, emitOptions, function (files) { + return emitOutput.outputFiles.push.apply(emitOutput.outputFiles, files); + }, null); + return emitOutput; + } else { + return this.emitAll(resolvePath); + } + }; + + TypeScriptCompiler.prototype.compile = function (resolvePath, continueOnDiagnostics) { + if (typeof continueOnDiagnostics === "undefined") { continueOnDiagnostics = false; } + return new CompilerIterator(this, resolvePath, continueOnDiagnostics); + }; + + TypeScriptCompiler.prototype.getSyntacticDiagnostics = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + return this.getDocument(fileName).diagnostics(); + }; + + TypeScriptCompiler.prototype.getSyntaxTree = function (fileName) { + return this.getDocument(fileName).syntaxTree(); + }; + + TypeScriptCompiler.prototype.getSourceUnit = function (fileName) { + return this.getDocument(fileName).sourceUnit(); + }; + + TypeScriptCompiler.prototype.getSemanticDiagnostics = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + + var document = this.getDocument(fileName); + + var startTime = (new Date()).getTime(); + TypeScript.PullTypeResolver.typeCheck(this.compilationSettings(), this.semanticInfoChain, document); + var endTime = (new Date()).getTime(); + + TypeScript.typeCheckTime += endTime - startTime; + + var errors = this.semanticInfoChain.getDiagnostics(fileName); + + errors = TypeScript.ArrayUtilities.distinct(errors, TypeScript.Diagnostic.equals); + errors.sort(function (d1, d2) { + if (d1.fileName() < d2.fileName()) { + return -1; + } else if (d1.fileName() > d2.fileName()) { + return 1; + } + + if (d1.start() < d2.start()) { + return -1; + } else if (d1.start() > d2.start()) { + return 1; + } + + var code1 = TypeScript.diagnosticInformationMap[d1.diagnosticKey()].code; + var code2 = TypeScript.diagnosticInformationMap[d2.diagnosticKey()].code; + if (code1 < code2) { + return -1; + } else if (code1 > code2) { + return 1; + } + + return 0; + }); + + return errors; + }; + + TypeScriptCompiler.prototype.getCompilerOptionsDiagnostics = function (resolvePath) { + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + var emitDiagnostic = emitOptions.diagnostic(); + if (emitDiagnostic) { + return [emitDiagnostic]; + } + return TypeScript.sentinelEmptyArray; + }; + + TypeScriptCompiler.prototype.resolveAllFiles = function () { + var fileNames = this.fileNames(); + for (var i = 0, n = fileNames.length; i < n; i++) { + this.getSemanticDiagnostics(fileNames[i]); + } + }; + + TypeScriptCompiler.prototype.getSymbolOfDeclaration = function (decl) { + if (!decl) { + return null; + } + + var resolver = this.semanticInfoChain.getResolver(); + var ast = this.semanticInfoChain.getASTForDecl(decl); + if (!ast) { + return null; + } + + var enclosingDecl = resolver.getEnclosingDecl(decl); + if (ast.kind() === 139 /* GetAccessor */ || ast.kind() === 140 /* SetAccessor */) { + return this.getSymbolOfDeclaration(enclosingDecl); + } + + return resolver.resolveAST(ast, false, new TypeScript.PullTypeResolutionContext(resolver)); + }; + + TypeScriptCompiler.prototype.extractResolutionContextFromAST = function (resolver, ast, document, propagateContextualTypes) { + var scriptName = document.fileName; + + var enclosingDecl = null; + var enclosingDeclAST = null; + var inContextuallyTypedAssignment = false; + var inWithBlock = false; + + var resolutionContext = new TypeScript.PullTypeResolutionContext(resolver); + + if (!ast) { + return null; + } + + var path = this.getASTPath(ast); + + for (var i = 0, n = path.length; i < n; i++) { + var current = path[i]; + + switch (current.kind()) { + case 222 /* FunctionExpression */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + if (propagateContextualTypes) { + resolver.resolveAST(current, true, resolutionContext); + } + break; + + case 136 /* MemberVariableDeclaration */: + var memberVariable = current; + inContextuallyTypedAssignment = memberVariable.variableDeclarator.typeAnnotation !== null; + + this.extractResolutionContextForVariable(inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, memberVariable, memberVariable.variableDeclarator.equalsValueClause); + break; + + case 225 /* VariableDeclarator */: + var variableDeclarator = current; + inContextuallyTypedAssignment = variableDeclarator.typeAnnotation !== null; + + this.extractResolutionContextForVariable(inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, variableDeclarator, variableDeclarator.equalsValueClause); + break; + + case 213 /* InvocationExpression */: + case 216 /* ObjectCreationExpression */: + if (propagateContextualTypes) { + var isNew = current.kind() === 216 /* ObjectCreationExpression */; + var callExpression = current; + var contextualType = null; + + if ((i + 2 < n) && callExpression.argumentList === path[i + 1] && callExpression.argumentList.arguments === path[i + 2]) { + var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); + if (isNew) { + resolver.resolveObjectCreationExpression(callExpression, resolutionContext, callResolutionResults); + } else { + resolver.resolveInvocationExpression(callExpression, resolutionContext, callResolutionResults); + } + + if (callResolutionResults.actualParametersContextTypeSymbols) { + var argExpression = path[i + 3]; + if (argExpression) { + for (var j = 0, m = callExpression.argumentList.arguments.nonSeparatorCount(); j < m; j++) { + if (callExpression.argumentList.arguments.nonSeparatorAt(j) === argExpression) { + var callContextualType = callResolutionResults.actualParametersContextTypeSymbols[j]; + if (callContextualType) { + contextualType = callContextualType; + break; + } + } + } + } + } + } else { + if (isNew) { + resolver.resolveObjectCreationExpression(callExpression, resolutionContext); + } else { + resolver.resolveInvocationExpression(callExpression, resolutionContext); + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 214 /* ArrayLiteralExpression */: + if (propagateContextualTypes) { + var contextualType = null; + var currentContextualType = resolutionContext.getContextualType(); + if (currentContextualType && currentContextualType.isArrayNamedTypeReference()) { + contextualType = currentContextualType.getElementType(); + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 215 /* ObjectLiteralExpression */: + if (propagateContextualTypes) { + var objectLiteralExpression = current; + var objectLiteralResolutionContext = new TypeScript.PullAdditionalObjectLiteralResolutionData(); + resolver.resolveObjectLiteralExpression(objectLiteralExpression, inContextuallyTypedAssignment, resolutionContext, objectLiteralResolutionContext); + + var memeberAST = (path[i + 1] && path[i + 1].kind() === 2 /* SeparatedList */) ? path[i + 2] : path[i + 1]; + if (memeberAST) { + var contextualType = null; + var memberDecls = objectLiteralExpression.propertyAssignments; + if (memberDecls && objectLiteralResolutionContext.membersContextTypeSymbols) { + for (var j = 0, m = memberDecls.nonSeparatorCount(); j < m; j++) { + if (memberDecls.nonSeparatorAt(j) === memeberAST) { + var memberContextualType = objectLiteralResolutionContext.membersContextTypeSymbols[j]; + if (memberContextualType) { + contextualType = memberContextualType; + break; + } + } + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + } + + break; + + case 174 /* AssignmentExpression */: + if (propagateContextualTypes) { + var assignmentExpression = current; + var contextualType = null; + + if (path[i + 1] && path[i + 1] === assignmentExpression.right) { + var leftType = resolver.resolveAST(assignmentExpression.left, inContextuallyTypedAssignment, resolutionContext).type; + if (leftType) { + inContextuallyTypedAssignment = true; + contextualType = leftType; + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 220 /* CastExpression */: + var castExpression = current; + if (!(i + 1 < n && path[i + 1] === castExpression.type)) { + if (propagateContextualTypes) { + var contextualType = null; + var typeSymbol = resolver.resolveAST(castExpression, inContextuallyTypedAssignment, resolutionContext).type; + + if (typeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = typeSymbol; + } + + resolutionContext.pushNewContextualType(contextualType); + } + } + + break; + + case 150 /* ReturnStatement */: + if (propagateContextualTypes) { + var returnStatement = current; + var contextualType = null; + + if (enclosingDecl && (enclosingDecl.kind & 1032192 /* SomeFunction */)) { + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); + if (typeAnnotation) { + var returnTypeSymbol = resolver.resolveTypeReference(typeAnnotation, resolutionContext); + if (returnTypeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = returnTypeSymbol; + } + } else { + var currentContextualType = resolutionContext.getContextualType(); + if (currentContextualType && currentContextualType.isFunction()) { + var contextualSignatures = currentContextualType.kind == 33554432 /* ConstructorType */ ? currentContextualType.getConstructSignatures() : currentContextualType.getCallSignatures(); + var currentContextualTypeSignatureSymbol = contextualSignatures[0]; + var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.returnType; + if (currentContextualTypeReturnTypeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = currentContextualTypeReturnTypeSymbol; + } + } + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 122 /* ObjectType */: + if (propagateContextualTypes && TypeScript.isTypesOnlyLocation(current)) { + resolver.resolveAST(current, false, resolutionContext); + } + + break; + + case 163 /* WithStatement */: + inWithBlock = true; + break; + + case 146 /* Block */: + inContextuallyTypedAssignment = false; + break; + } + + var decl = this.semanticInfoChain.getDeclForAST(current); + if (decl) { + enclosingDecl = decl; + enclosingDeclAST = current; + } + } + + if (ast && ast.parent && ast.kind() === 11 /* IdentifierName */) { + if (ast.parent.kind() === 212 /* MemberAccessExpression */) { + if (ast.parent.name === ast) { + ast = ast.parent; + } + } else if (ast.parent.kind() === 121 /* QualifiedName */) { + if (ast.parent.right === ast) { + ast = ast.parent; + } + } + } + + return { + ast: ast, + enclosingDecl: enclosingDecl, + resolutionContext: resolutionContext, + inContextuallyTypedAssignment: inContextuallyTypedAssignment, + inWithBlock: inWithBlock + }; + }; + + TypeScriptCompiler.prototype.extractResolutionContextForVariable = function (inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, assigningAST, init) { + if (inContextuallyTypedAssignment) { + if (propagateContextualTypes) { + resolver.resolveAST(assigningAST, false, resolutionContext); + var varSymbol = this.semanticInfoChain.getSymbolForAST(assigningAST); + + var contextualType = null; + if (varSymbol && inContextuallyTypedAssignment) { + contextualType = varSymbol.type; + } + + resolutionContext.pushNewContextualType(contextualType); + + if (init) { + resolver.resolveAST(init, inContextuallyTypedAssignment, resolutionContext); + } + } + } + }; + + TypeScriptCompiler.prototype.getASTPath = function (ast) { + var result = []; + + while (ast) { + result.unshift(ast); + ast = ast.parent; + } + + return result; + }; + + TypeScriptCompiler.prototype.pullGetSymbolInformationFromAST = function (ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + ast = context.ast; + var symbol = resolver.resolveAST(ast, context.inContextuallyTypedAssignment, context.resolutionContext); + + if (!symbol) { + TypeScript.Debug.assert(ast.kind() === 120 /* SourceUnit */, "No symbol was found for ast and ast was not source unit. Ast Kind: " + TypeScript.SyntaxKind[ast.kind()]); + return null; + } + + if (symbol.isTypeReference()) { + symbol = symbol.getReferencedTypeSymbol(); + } + + var aliasSymbol = this.semanticInfoChain.getAliasSymbolForAST(ast); + + return { + symbol: symbol, + aliasSymbol: aliasSymbol, + ast: ast, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetCallInformationFromAST = function (ast, document) { + if (ast.kind() !== 213 /* InvocationExpression */ && ast.kind() !== 216 /* ObjectCreationExpression */) { + return null; + } + + var isNew = ast.kind() === 216 /* ObjectCreationExpression */; + + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); + + if (isNew) { + resolver.resolveObjectCreationExpression(ast, context.resolutionContext, callResolutionResults); + } else { + resolver.resolveInvocationExpression(ast, context.resolutionContext, callResolutionResults); + } + + return { + targetSymbol: callResolutionResults.targetSymbol, + resolvedSignatures: callResolutionResults.resolvedSignatures, + candidateSignature: callResolutionResults.candidateSignature, + ast: ast, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl), + isConstructorCall: isNew + }; + }; + + TypeScriptCompiler.prototype.pullGetVisibleMemberSymbolsFromAST = function (ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var symbols = resolver.getVisibleMembersFromExpression(ast, context.enclosingDecl, context.resolutionContext); + if (!symbols) { + return null; + } + + return { + symbols: symbols, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetVisibleDeclsFromAST = function (ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, false); + if (!context || context.inWithBlock) { + return null; + } + + return resolver.getVisibleDecls(context.enclosingDecl); + }; + + TypeScriptCompiler.prototype.pullGetContextualMembersFromAST = function (ast, document) { + if (ast.kind() !== 215 /* ObjectLiteralExpression */) { + return null; + } + + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var members = resolver.getVisibleContextSymbols(context.enclosingDecl, context.resolutionContext); + + return { + symbols: members, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetDeclInformation = function (decl, ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var astForDecl = decl.ast(); + if (!astForDecl) { + return null; + } + + var astForDeclContext = this.extractResolutionContextFromAST(resolver, astForDecl, this.getDocument(astForDecl.fileName()), true); + if (!astForDeclContext) { + return null; + } + + var symbol = decl.getSymbol(); + resolver.resolveDeclaredSymbol(symbol, context.resolutionContext); + symbol.setUnresolved(); + + return { + symbol: symbol, + aliasSymbol: null, + ast: ast, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.topLevelDeclaration = function (fileName) { + return this.semanticInfoChain.topLevelDecl(fileName); + }; + + TypeScriptCompiler.prototype.getDeclForAST = function (ast) { + return this.semanticInfoChain.getDeclForAST(ast); + }; + + TypeScriptCompiler.prototype.fileNames = function () { + return this.semanticInfoChain.fileNames(); + }; + + TypeScriptCompiler.prototype.topLevelDecl = function (fileName) { + return this.semanticInfoChain.topLevelDecl(fileName); + }; + + TypeScriptCompiler.getLocationText = function (location, resolvePath) { + return resolvePath(location.fileName()) + "(" + (location.line() + 1) + "," + (location.character() + 1) + ")"; + }; + + TypeScriptCompiler.getFullDiagnosticText = function (diagnostic, resolvePath) { + var result = ""; + if (diagnostic.fileName()) { + result += this.getLocationText(diagnostic, resolvePath) + ": "; + } + + result += diagnostic.message(); + + var additionalLocations = diagnostic.additionalLocations(); + if (additionalLocations.length > 0) { + result += " " + TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Additional_locations, null) + TypeScript.Environment.newLine; + + for (var i = 0, n = additionalLocations.length; i < n; i++) { + result += "\t" + this.getLocationText(additionalLocations[i], resolvePath) + TypeScript.Environment.newLine; + } + } else { + result += TypeScript.Environment.newLine; + } + + return result; + }; + return TypeScriptCompiler; + })(); + TypeScript.TypeScriptCompiler = TypeScriptCompiler; + + var CompilerPhase; + (function (CompilerPhase) { + CompilerPhase[CompilerPhase["Syntax"] = 0] = "Syntax"; + CompilerPhase[CompilerPhase["Semantics"] = 1] = "Semantics"; + CompilerPhase[CompilerPhase["EmitOptionsValidation"] = 2] = "EmitOptionsValidation"; + CompilerPhase[CompilerPhase["Emit"] = 3] = "Emit"; + CompilerPhase[CompilerPhase["DeclarationEmit"] = 4] = "DeclarationEmit"; + })(CompilerPhase || (CompilerPhase = {})); + + var CompilerIterator = (function () { + function CompilerIterator(compiler, resolvePath, continueOnDiagnostics, startingPhase) { + if (typeof startingPhase === "undefined") { startingPhase = 0 /* Syntax */; } + this.compiler = compiler; + this.resolvePath = resolvePath; + this.continueOnDiagnostics = continueOnDiagnostics; + this.index = -1; + this.fileNames = null; + this._current = null; + this._emitOptions = null; + this._sharedEmitter = null; + this._sharedDeclarationEmitter = null; + this.hadSyntacticDiagnostics = false; + this.hadSemanticDiagnostics = false; + this.hadEmitDiagnostics = false; + this.fileNames = compiler.fileNames(); + this.compilerPhase = startingPhase; + } + CompilerIterator.prototype.current = function () { + return this._current; + }; + + CompilerIterator.prototype.moveNext = function () { + this._current = null; + + while (this.moveNextInternal()) { + if (this._current) { + return true; + } + } + + return false; + }; + + CompilerIterator.prototype.moveNextInternal = function () { + this.index++; + + while (this.shouldMoveToNextPhase()) { + this.index = 0; + this.compilerPhase++; + } + + if (this.compilerPhase > 4 /* DeclarationEmit */) { + return false; + } + + switch (this.compilerPhase) { + case 0 /* Syntax */: + return this.moveNextSyntaxPhase(); + case 1 /* Semantics */: + return this.moveNextSemanticsPhase(); + case 2 /* EmitOptionsValidation */: + return this.moveNextEmitOptionsValidationPhase(); + case 3 /* Emit */: + return this.moveNextEmitPhase(); + case 4 /* DeclarationEmit */: + return this.moveNextDeclarationEmitPhase(); + } + }; + + CompilerIterator.prototype.shouldMoveToNextPhase = function () { + switch (this.compilerPhase) { + case 2 /* EmitOptionsValidation */: + return this.index === 1; + + case 0 /* Syntax */: + case 1 /* Semantics */: + return this.index === this.fileNames.length; + + case 3 /* Emit */: + case 4 /* DeclarationEmit */: + return this.index === (this.fileNames.length + 1); + } + + return false; + }; + + CompilerIterator.prototype.moveNextSyntaxPhase = function () { + TypeScript.Debug.assert(this.index >= 0 && this.index < this.fileNames.length); + var fileName = this.fileNames[this.index]; + + var diagnostics = this.compiler.getSyntacticDiagnostics(fileName); + if (diagnostics.length) { + if (!this.continueOnDiagnostics) { + this.hadSyntacticDiagnostics = true; + } + + this._current = CompileResult.fromDiagnostics(diagnostics); + } + + return true; + }; + + CompilerIterator.prototype.moveNextSemanticsPhase = function () { + if (this.hadSyntacticDiagnostics) { + return false; + } + + TypeScript.Debug.assert(this.index >= 0 && this.index < this.fileNames.length); + var fileName = this.fileNames[this.index]; + var diagnostics = this.compiler.getSemanticDiagnostics(fileName); + if (diagnostics.length) { + if (!this.continueOnDiagnostics) { + this.hadSemanticDiagnostics = true; + } + + this._current = CompileResult.fromDiagnostics(diagnostics); + } + + return true; + }; + + CompilerIterator.prototype.moveNextEmitOptionsValidationPhase = function () { + TypeScript.Debug.assert(!this.hadSyntacticDiagnostics); + + if (!this._emitOptions) { + this._emitOptions = new TypeScript.EmitOptions(this.compiler, this.resolvePath); + } + + if (this._emitOptions.diagnostic()) { + if (!this.continueOnDiagnostics) { + this.hadEmitDiagnostics = true; + } + + this._current = CompileResult.fromDiagnostics([this._emitOptions.diagnostic()]); + } + + return true; + }; + + CompilerIterator.prototype.moveNextEmitPhase = function () { + var _this = this; + TypeScript.Debug.assert(!this.hadSyntacticDiagnostics); + TypeScript.Debug.assert(this._emitOptions); + + if (this.hadEmitDiagnostics) { + return false; + } + + TypeScript.Debug.assert(this.index >= 0 && this.index <= this.fileNames.length); + if (this.index < this.fileNames.length) { + var fileName = this.fileNames[this.index]; + var document = this.compiler.getDocument(fileName); + + this._sharedEmitter = this.compiler._emitDocument(document, this._emitOptions, function (outputFiles) { + _this._current = CompileResult.fromOutputFiles(outputFiles); + }, this._sharedEmitter); + return true; + } + + if (this.index === this.fileNames.length && this._sharedEmitter) { + this._current = CompileResult.fromOutputFiles(this._sharedEmitter.getOutputFiles()); + } + + return true; + }; + + CompilerIterator.prototype.moveNextDeclarationEmitPhase = function () { + var _this = this; + TypeScript.Debug.assert(!this.hadSyntacticDiagnostics); + TypeScript.Debug.assert(!this.hadEmitDiagnostics); + if (this.hadSemanticDiagnostics) { + return false; + } + + if (!this.compiler.compilationSettings().generateDeclarationFiles()) { + return false; + } + + TypeScript.Debug.assert(this.index >= 0 && this.index <= this.fileNames.length); + if (this.index < this.fileNames.length) { + var fileName = this.fileNames[this.index]; + var document = this.compiler.getDocument(fileName); + + this._sharedDeclarationEmitter = this.compiler._emitDocumentDeclarations(document, this._emitOptions, function (file) { + _this._current = CompileResult.fromOutputFiles([file]); + }, this._sharedDeclarationEmitter); + return true; + } + + if (this.index === this.fileNames.length && this._sharedDeclarationEmitter) { + this._current = CompileResult.fromOutputFiles([this._sharedDeclarationEmitter.getOutputFile()]); + } + + return true; + }; + return CompilerIterator; + })(); + + function compareDataObjects(dst, src) { + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) + return false; + } else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) + return false; + } + } + return true; + } + TypeScript.compareDataObjects = compareDataObjects; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (GenerativeTypeClassification) { + GenerativeTypeClassification[GenerativeTypeClassification["Unknown"] = 0] = "Unknown"; + GenerativeTypeClassification[GenerativeTypeClassification["Open"] = 1] = "Open"; + GenerativeTypeClassification[GenerativeTypeClassification["Closed"] = 2] = "Closed"; + GenerativeTypeClassification[GenerativeTypeClassification["InfinitelyExpanding"] = 3] = "InfinitelyExpanding"; + })(TypeScript.GenerativeTypeClassification || (TypeScript.GenerativeTypeClassification = {})); + var GenerativeTypeClassification = TypeScript.GenerativeTypeClassification; + + var PullTypeReferenceSymbol = (function (_super) { + __extends(PullTypeReferenceSymbol, _super); + function PullTypeReferenceSymbol(referencedTypeSymbol) { + _super.call(this, referencedTypeSymbol.name, referencedTypeSymbol.kind); + this.referencedTypeSymbol = referencedTypeSymbol; + this.isResolved = true; + + TypeScript.Debug.assert(referencedTypeSymbol !== null, "Type root symbol may not be null"); + + this.setRootSymbol(referencedTypeSymbol); + + this.typeReference = this; + } + PullTypeReferenceSymbol.createTypeReference = function (type) { + if (type.isTypeReference()) { + return type; + } + + var typeReference = type.typeReference; + + if (!typeReference) { + typeReference = new PullTypeReferenceSymbol(type); + type.typeReference = typeReference; + } + + return typeReference; + }; + + PullTypeReferenceSymbol.prototype.isTypeReference = function () { + return true; + }; + + PullTypeReferenceSymbol.prototype.setResolved = function () { + }; + + PullTypeReferenceSymbol.prototype.setUnresolved = function () { + }; + PullTypeReferenceSymbol.prototype.invalidate = function () { + }; + + PullTypeReferenceSymbol.prototype.ensureReferencedTypeIsResolved = function () { + this._getResolver().resolveDeclaredSymbol(this.referencedTypeSymbol); + }; + + PullTypeReferenceSymbol.prototype.getReferencedTypeSymbol = function () { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol; + }; + + PullTypeReferenceSymbol.prototype._getResolver = function () { + return this.referencedTypeSymbol._getResolver(); + }; + + PullTypeReferenceSymbol.prototype.hasMembers = function () { + return this.referencedTypeSymbol.hasMembers(); + }; + + PullTypeReferenceSymbol.prototype.setAssociatedContainerType = function (type) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": setAssociatedContainerType"); + }; + + PullTypeReferenceSymbol.prototype.getAssociatedContainerType = function () { + return this.referencedTypeSymbol.getAssociatedContainerType(); + }; + + PullTypeReferenceSymbol.prototype.getFunctionSymbol = function () { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.getFunctionSymbol(); + }; + PullTypeReferenceSymbol.prototype.setFunctionSymbol = function (symbol) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": setFunctionSymbol"); + }; + + PullTypeReferenceSymbol.prototype.addContainedNonMember = function (nonMember) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addContainedNonMember"); + }; + PullTypeReferenceSymbol.prototype.findContainedNonMemberContainer = function (containerName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.findContainedNonMemberContainer(containerName, kind); + }; + + PullTypeReferenceSymbol.prototype.addMember = function (memberSymbol) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addMember"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedMemberType = function (enclosedType) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedMemberType"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedMemberContainer = function (enclosedContainer) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedMemberContainer"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedNonMember = function (enclosedNonMember) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedNonMember"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedNonMemberType = function (enclosedNonMemberType) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedNonMemberType"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedNonMemberContainer = function (enclosedNonMemberContainer) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedNonMemberContainer"); + }; + PullTypeReferenceSymbol.prototype.addTypeParameter = function (typeParameter) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addTypeParameter"); + }; + PullTypeReferenceSymbol.prototype.addConstructorTypeParameter = function (typeParameter) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addConstructorTypeParameter"); + }; + + PullTypeReferenceSymbol.prototype.findContainedNonMember = function (name) { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findContainedNonMember(name); + }; + + PullTypeReferenceSymbol.prototype.findContainedNonMemberType = function (typeName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findContainedNonMemberType(typeName, kind); + }; + + PullTypeReferenceSymbol.prototype.getMembers = function () { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.getMembers(); + }; + + PullTypeReferenceSymbol.prototype.setHasDefaultConstructor = function (hasOne) { + if (typeof hasOne === "undefined") { hasOne = true; } + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ":setHasDefaultConstructor"); + }; + PullTypeReferenceSymbol.prototype.getHasDefaultConstructor = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getHasDefaultConstructor(); + }; + PullTypeReferenceSymbol.prototype.getConstructorMethod = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getConstructorMethod(); + }; + PullTypeReferenceSymbol.prototype.setConstructorMethod = function (constructorMethod) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": setConstructorMethod"); + }; + PullTypeReferenceSymbol.prototype.getTypeParameters = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypeParameters(); + }; + + PullTypeReferenceSymbol.prototype.isGeneric = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.isGeneric(); + }; + + PullTypeReferenceSymbol.prototype.addSpecialization = function (specializedVersionOfThisType, substitutingTypes) { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.addSpecialization(specializedVersionOfThisType, substitutingTypes); + }; + PullTypeReferenceSymbol.prototype.getSpecialization = function (substitutingTypes) { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getSpecialization(substitutingTypes); + }; + PullTypeReferenceSymbol.prototype.getKnownSpecializations = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getKnownSpecializations(); + }; + PullTypeReferenceSymbol.prototype.getTypeArguments = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypeArguments(); + }; + PullTypeReferenceSymbol.prototype.getTypeArgumentsOrTypeParameters = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypeArgumentsOrTypeParameters(); + }; + + PullTypeReferenceSymbol.prototype.appendCallSignature = function (callSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": appendCallSignature"); + }; + PullTypeReferenceSymbol.prototype.insertCallSignatureAtIndex = function (callSignature, index) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": insertCallSignatureAtIndex"); + }; + PullTypeReferenceSymbol.prototype.appendConstructSignature = function (callSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": appendConstructSignature"); + }; + PullTypeReferenceSymbol.prototype.insertConstructSignatureAtIndex = function (callSignature, index) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": insertConstructSignatureAtIndex"); + }; + PullTypeReferenceSymbol.prototype.addIndexSignature = function (indexSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addIndexSignature"); + }; + + PullTypeReferenceSymbol.prototype.hasOwnCallSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.hasOwnCallSignatures(); + }; + PullTypeReferenceSymbol.prototype.getCallSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getCallSignatures(); + }; + PullTypeReferenceSymbol.prototype.hasOwnConstructSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.hasOwnConstructSignatures(); + }; + PullTypeReferenceSymbol.prototype.getConstructSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getConstructSignatures(); + }; + PullTypeReferenceSymbol.prototype.hasOwnIndexSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.hasOwnIndexSignatures(); + }; + PullTypeReferenceSymbol.prototype.getIndexSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getIndexSignatures(); + }; + + PullTypeReferenceSymbol.prototype.addImplementedType = function (implementedType) { + this.referencedTypeSymbol.addImplementedType(implementedType); + }; + PullTypeReferenceSymbol.prototype.getImplementedTypes = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getImplementedTypes(); + }; + PullTypeReferenceSymbol.prototype.addExtendedType = function (extendedType) { + this.referencedTypeSymbol.addExtendedType(extendedType); + }; + PullTypeReferenceSymbol.prototype.getExtendedTypes = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getExtendedTypes(); + }; + PullTypeReferenceSymbol.prototype.addTypeThatExtendsThisType = function (type) { + this.referencedTypeSymbol.addTypeThatExtendsThisType(type); + }; + PullTypeReferenceSymbol.prototype.getTypesThatExtendThisType = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypesThatExtendThisType(); + }; + PullTypeReferenceSymbol.prototype.addTypeThatExplicitlyImplementsThisType = function (type) { + this.referencedTypeSymbol.addTypeThatExplicitlyImplementsThisType(type); + }; + PullTypeReferenceSymbol.prototype.getTypesThatExplicitlyImplementThisType = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypesThatExplicitlyImplementThisType(); + }; + + PullTypeReferenceSymbol.prototype.isValidBaseKind = function (baseType, isExtendedType) { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.isValidBaseKind(baseType, isExtendedType); + }; + + PullTypeReferenceSymbol.prototype.findMember = function (name, lookInParent) { + if (typeof lookInParent === "undefined") { lookInParent = true; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findMember(name, lookInParent); + }; + PullTypeReferenceSymbol.prototype.findNestedType = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findNestedType(name, kind); + }; + PullTypeReferenceSymbol.prototype.findNestedContainer = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findNestedContainer(name, kind); + }; + PullTypeReferenceSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisiblity) { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.getAllMembers(searchDeclKind, memberVisiblity); + }; + + PullTypeReferenceSymbol.prototype.findTypeParameter = function (name) { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findTypeParameter(name); + }; + + PullTypeReferenceSymbol.prototype.hasOnlyOverloadCallSignatures = function () { + return this.referencedTypeSymbol.hasOnlyOverloadCallSignatures(); + }; + return PullTypeReferenceSymbol; + })(TypeScript.PullTypeSymbol); + TypeScript.PullTypeReferenceSymbol = PullTypeReferenceSymbol; + + TypeScript.nSpecializationsCreated = 0; + TypeScript.nSpecializedSignaturesCreated = 0; + TypeScript.nSpecializedTypeParameterCreated = 0; + + var PullInstantiatedTypeReferenceSymbol = (function (_super) { + __extends(PullInstantiatedTypeReferenceSymbol, _super); + function PullInstantiatedTypeReferenceSymbol(referencedTypeSymbol, _typeParameterArgumentMap, isInstanceReferenceType) { + _super.call(this, referencedTypeSymbol); + this.referencedTypeSymbol = referencedTypeSymbol; + this._typeParameterArgumentMap = _typeParameterArgumentMap; + this.isInstanceReferenceType = isInstanceReferenceType; + this._instantiatedMembers = null; + this._allInstantiatedMemberNameCache = null; + this._instantiatedMemberNameCache = TypeScript.createIntrinsicsObject(); + this._instantiatedCallSignatures = null; + this._instantiatedConstructSignatures = null; + this._instantiatedIndexSignatures = null; + this._typeArgumentReferences = undefined; + this._instantiatedConstructorMethod = null; + this._instantiatedAssociatedContainerType = null; + this._isArray = undefined; + this._generativeTypeClassification = []; + + TypeScript.nSpecializationsCreated++; + } + PullInstantiatedTypeReferenceSymbol.prototype.getIsSpecialized = function () { + return !this.isInstanceReferenceType; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getGenerativeTypeClassification = function (enclosingType) { + if (!this.isNamedTypeSymbol()) { + return 0 /* Unknown */; + } + + var generativeTypeClassification = this._generativeTypeClassification[enclosingType.pullSymbolID] || 0 /* Unknown */; + if (generativeTypeClassification === 0 /* Unknown */) { + var typeParameters = enclosingType.getTypeParameters(); + var enclosingTypeParameterMap = []; + for (var i = 0; i < typeParameters.length; i++) { + enclosingTypeParameterMap[typeParameters[i].pullSymbolID] = typeParameters[i]; + } + + var typeArguments = this.getTypeArguments(); + for (var i = 0; i < typeArguments.length; i++) { + if (typeArguments[i].wrapsSomeTypeParameter(enclosingTypeParameterMap, true)) { + generativeTypeClassification = 1 /* Open */; + break; + } + } + + if (generativeTypeClassification === 1 /* Open */) { + if (this.wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType)) { + generativeTypeClassification = 3 /* InfinitelyExpanding */; + } + } else { + generativeTypeClassification = 2 /* Closed */; + } + + this._generativeTypeClassification[enclosingType.pullSymbolID] = generativeTypeClassification; + } + + return generativeTypeClassification; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.isArrayNamedTypeReference = function () { + if (this._isArray === undefined) { + this._isArray = this.getRootSymbol().isArrayNamedTypeReference() || (this.getRootSymbol() === this._getResolver().getArrayNamedType()); + } + return this._isArray; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getElementType = function () { + if (!this.isArrayNamedTypeReference()) { + return null; + } + + var typeArguments = this.getTypeArguments(); + return typeArguments ? typeArguments[0] : null; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getReferencedTypeSymbol = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.getIsSpecialized()) { + return this; + } + + return this.referencedTypeSymbol; + }; + + PullInstantiatedTypeReferenceSymbol.create = function (resolver, type, typeParameterArgumentMap) { + TypeScript.Debug.assert(resolver); + + var mutableTypeParameterMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(typeParameterArgumentMap); + + TypeScript.PullInstantiationHelpers.instantiateTypeArgument(resolver, type, mutableTypeParameterMap); + + var rootType = type.getRootSymbol(); + var instantiation = rootType.getSpecialization(mutableTypeParameterMap.typeParameterArgumentMap); + if (instantiation) { + return instantiation; + } + + TypeScript.PullInstantiationHelpers.cleanUpTypeArgumentMap(type, mutableTypeParameterMap); + typeParameterArgumentMap = mutableTypeParameterMap.typeParameterArgumentMap; + + var isInstanceReferenceType = (type.kind & 8216 /* SomeInstantiatableType */) != 0; + var resolvedTypeParameterArgumentMap = typeParameterArgumentMap; + if (isInstanceReferenceType) { + var typeParameters = rootType.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + if (!TypeScript.PullHelpers.typeSymbolsAreIdentical(typeParameters[i], typeParameterArgumentMap[typeParameters[i].pullSymbolID])) { + isInstanceReferenceType = false; + break; + } + } + + if (isInstanceReferenceType) { + typeParameterArgumentMap = []; + } + } + + instantiation = new PullInstantiatedTypeReferenceSymbol(rootType, typeParameterArgumentMap, isInstanceReferenceType); + + rootType.addSpecialization(instantiation, resolvedTypeParameterArgumentMap); + + return instantiation; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.isGeneric = function () { + return this.getRootSymbol().isGeneric(); + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getTypeParameterArgumentMap = function () { + return this._typeParameterArgumentMap; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getTypeArguments = function () { + if (this.isInstanceReferenceType) { + return this.getTypeParameters(); + } + + if (this._typeArgumentReferences === undefined) { + var typeParameters = this.referencedTypeSymbol.getTypeParameters(); + + if (typeParameters.length) { + var typeArgument = null; + var typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArgument = this._typeParameterArgumentMap[typeParameters[i].pullSymbolID]; + + if (!typeArgument) { + TypeScript.Debug.fail("type argument count mismatch"); + } + + if (typeArgument) { + typeArguments[typeArguments.length] = typeArgument; + } + } + + this._typeArgumentReferences = typeArguments; + } else { + this._typeArgumentReferences = null; + } + } + + return this._typeArgumentReferences; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getTypeArgumentsOrTypeParameters = function () { + return this.getTypeArguments(); + }; + + PullInstantiatedTypeReferenceSymbol.prototype.populateInstantiatedMemberFromReferencedMember = function (referencedMember) { + var instantiatedMember; + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(referencedMember); + + if (!referencedMember.type.wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + instantiatedMember = referencedMember; + } else { + instantiatedMember = new TypeScript.PullSymbol(referencedMember.name, referencedMember.kind); + instantiatedMember.setRootSymbol(referencedMember); + instantiatedMember.type = this._getResolver().instantiateType(referencedMember.type, this._typeParameterArgumentMap); + instantiatedMember.isOptional = referencedMember.isOptional; + } + this._instantiatedMemberNameCache[instantiatedMember.name] = instantiatedMember; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getMembers = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getMembers(); + } + + if (!this._instantiatedMembers) { + var referencedMembers = this.referencedTypeSymbol.getMembers(); + var referencedMember = null; + var instantiatedMember = null; + + this._instantiatedMembers = []; + + for (var i = 0; i < referencedMembers.length; i++) { + referencedMember = referencedMembers[i]; + + this._getResolver().resolveDeclaredSymbol(referencedMember); + + if (!this._instantiatedMemberNameCache[referencedMember.name]) { + this.populateInstantiatedMemberFromReferencedMember(referencedMember); + } + + this._instantiatedMembers[this._instantiatedMembers.length] = this._instantiatedMemberNameCache[referencedMember.name]; + } + } + + return this._instantiatedMembers; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.findMember = function (name, lookInParent) { + if (typeof lookInParent === "undefined") { lookInParent = true; } + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.findMember(name, lookInParent); + } + + var memberSymbol = this._instantiatedMemberNameCache[name]; + + if (!memberSymbol) { + var referencedMemberSymbol = this.referencedTypeSymbol.findMember(name, lookInParent); + + if (referencedMemberSymbol) { + this.populateInstantiatedMemberFromReferencedMember(referencedMemberSymbol); + memberSymbol = this._instantiatedMemberNameCache[name]; + } else { + memberSymbol = null; + } + } + + return memberSymbol; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisiblity) { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getAllMembers(searchDeclKind, memberVisiblity); + } + + var requestedMembers = []; + var allReferencedMembers = this.referencedTypeSymbol.getAllMembers(searchDeclKind, memberVisiblity); + + if (!this._allInstantiatedMemberNameCache) { + this._allInstantiatedMemberNameCache = TypeScript.createIntrinsicsObject(); + + var members = this.getMembers(); + + for (var i = 0; i < members.length; i++) { + this._allInstantiatedMemberNameCache[members[i].name] = members[i]; + } + } + + var referencedMember = null; + var requestedMember = null; + + for (var i = 0; i < allReferencedMembers.length; i++) { + referencedMember = allReferencedMembers[i]; + + this._getResolver().resolveDeclaredSymbol(referencedMember); + + if (this._allInstantiatedMemberNameCache[referencedMember.name]) { + requestedMembers[requestedMembers.length] = this._allInstantiatedMemberNameCache[referencedMember.name]; + } else { + if (!referencedMember.type.wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._allInstantiatedMemberNameCache[referencedMember.name] = referencedMember; + requestedMembers[requestedMembers.length] = referencedMember; + } else { + requestedMember = new TypeScript.PullSymbol(referencedMember.name, referencedMember.kind); + requestedMember.setRootSymbol(referencedMember); + + requestedMember.type = this._getResolver().instantiateType(referencedMember.type, this._typeParameterArgumentMap); + requestedMember.isOptional = referencedMember.isOptional; + + this._allInstantiatedMemberNameCache[requestedMember.name] = requestedMember; + requestedMembers[requestedMembers.length] = requestedMember; + } + } + } + + return requestedMembers; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getConstructorMethod = function () { + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getConstructorMethod(); + } + + if (!this._instantiatedConstructorMethod) { + var referencedConstructorMethod = this.referencedTypeSymbol.getConstructorMethod(); + this._instantiatedConstructorMethod = new TypeScript.PullSymbol(referencedConstructorMethod.name, referencedConstructorMethod.kind); + this._instantiatedConstructorMethod.setRootSymbol(referencedConstructorMethod); + this._instantiatedConstructorMethod.setResolved(); + + this._instantiatedConstructorMethod.type = PullInstantiatedTypeReferenceSymbol.create(this._getResolver(), referencedConstructorMethod.type, this._typeParameterArgumentMap); + } + + return this._instantiatedConstructorMethod; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getAssociatedContainerType = function () { + if (!this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getAssociatedContainerType(); + } + + if (!this._instantiatedAssociatedContainerType) { + var referencedAssociatedContainerType = this.referencedTypeSymbol.getAssociatedContainerType(); + + if (referencedAssociatedContainerType) { + this._instantiatedAssociatedContainerType = PullInstantiatedTypeReferenceSymbol.create(this._getResolver(), referencedAssociatedContainerType, this._typeParameterArgumentMap); + } + } + + return this._instantiatedAssociatedContainerType; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getCallSignatures = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getCallSignatures(); + } + + if (this._instantiatedCallSignatures) { + return this._instantiatedCallSignatures; + } + + var referencedCallSignatures = this.referencedTypeSymbol.getCallSignatures(); + this._instantiatedCallSignatures = []; + + for (var i = 0; i < referencedCallSignatures.length; i++) { + this._getResolver().resolveDeclaredSymbol(referencedCallSignatures[i]); + + if (!referencedCallSignatures[i].wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._instantiatedCallSignatures[this._instantiatedCallSignatures.length] = referencedCallSignatures[i]; + } else { + this._instantiatedCallSignatures[this._instantiatedCallSignatures.length] = this._getResolver().instantiateSignature(referencedCallSignatures[i], this._typeParameterArgumentMap); + this._instantiatedCallSignatures[this._instantiatedCallSignatures.length - 1].functionType = this; + } + } + + return this._instantiatedCallSignatures; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getConstructSignatures = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getConstructSignatures(); + } + + if (this._instantiatedConstructSignatures) { + return this._instantiatedConstructSignatures; + } + + var referencedConstructSignatures = this.referencedTypeSymbol.getConstructSignatures(); + this._instantiatedConstructSignatures = []; + + for (var i = 0; i < referencedConstructSignatures.length; i++) { + this._getResolver().resolveDeclaredSymbol(referencedConstructSignatures[i]); + + if (!referencedConstructSignatures[i].wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._instantiatedConstructSignatures[this._instantiatedConstructSignatures.length] = referencedConstructSignatures[i]; + } else { + this._instantiatedConstructSignatures[this._instantiatedConstructSignatures.length] = this._getResolver().instantiateSignature(referencedConstructSignatures[i], this._typeParameterArgumentMap); + this._instantiatedConstructSignatures[this._instantiatedConstructSignatures.length - 1].functionType = this; + } + } + + return this._instantiatedConstructSignatures; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getIndexSignatures = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getIndexSignatures(); + } + + if (this._instantiatedIndexSignatures) { + return this._instantiatedIndexSignatures; + } + + var referencedIndexSignatures = this.referencedTypeSymbol.getIndexSignatures(); + this._instantiatedIndexSignatures = []; + + for (var i = 0; i < referencedIndexSignatures.length; i++) { + this._getResolver().resolveDeclaredSymbol(referencedIndexSignatures[i]); + + if (!referencedIndexSignatures[i].wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._instantiatedIndexSignatures[this._instantiatedIndexSignatures.length] = referencedIndexSignatures[i]; + } else { + this._instantiatedIndexSignatures[this._instantiatedIndexSignatures.length] = this._getResolver().instantiateSignature(referencedIndexSignatures[i], this._typeParameterArgumentMap); + this._instantiatedIndexSignatures[this._instantiatedIndexSignatures.length - 1].functionType = this; + } + } + + return this._instantiatedIndexSignatures; + }; + return PullInstantiatedTypeReferenceSymbol; + })(PullTypeReferenceSymbol); + TypeScript.PullInstantiatedTypeReferenceSymbol = PullInstantiatedTypeReferenceSymbol; + + var PullInstantiatedSignatureSymbol = (function (_super) { + __extends(PullInstantiatedSignatureSymbol, _super); + function PullInstantiatedSignatureSymbol(rootSignature, _typeParameterArgumentMap) { + _super.call(this, rootSignature.kind, rootSignature.isDefinition()); + this._typeParameterArgumentMap = _typeParameterArgumentMap; + this.setRootSymbol(rootSignature); + TypeScript.nSpecializedSignaturesCreated++; + + rootSignature.addSpecialization(this, _typeParameterArgumentMap); + } + PullInstantiatedSignatureSymbol.prototype.getTypeParameterArgumentMap = function () { + return this._typeParameterArgumentMap; + }; + + PullInstantiatedSignatureSymbol.prototype.getIsSpecialized = function () { + return true; + }; + + PullInstantiatedSignatureSymbol.prototype._getResolver = function () { + return this.getRootSymbol()._getResolver(); + }; + + PullInstantiatedSignatureSymbol.prototype.getTypeParameters = function () { + var _this = this; + if (!this._typeParameters) { + var rootSymbol = this.getRootSymbol(); + var typeParameters = rootSymbol.getTypeParameters(); + var hasInstantiatedTypeParametersOfThisSignature = TypeScript.ArrayUtilities.all(typeParameters, function (typeParameter) { + return _this._typeParameterArgumentMap[typeParameter.pullSymbolID] !== undefined; + }); + + if (!hasInstantiatedTypeParametersOfThisSignature && typeParameters.length) { + this._typeParameters = []; + for (var i = 0; i < typeParameters.length; i++) { + this._typeParameters[this._typeParameters.length] = this._getResolver().instantiateTypeParameter(typeParameters[i], this._typeParameterArgumentMap); + } + } else { + this._typeParameters = TypeScript.sentinelEmptyArray; + } + } + + return this._typeParameters; + }; + + PullInstantiatedSignatureSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + var rootSymbol = this.getRootSymbol(); + return rootSymbol.getAllowedToReferenceTypeParameters(); + }; + return PullInstantiatedSignatureSymbol; + })(TypeScript.PullSignatureSymbol); + TypeScript.PullInstantiatedSignatureSymbol = PullInstantiatedSignatureSymbol; + + var PullInstantiatedTypeParameterSymbol = (function (_super) { + __extends(PullInstantiatedTypeParameterSymbol, _super); + function PullInstantiatedTypeParameterSymbol(rootTypeParameter, constraintType) { + _super.call(this, rootTypeParameter.name); + TypeScript.nSpecializedTypeParameterCreated++; + + this.setRootSymbol(rootTypeParameter); + this.setConstraint(constraintType); + + rootTypeParameter.addSpecialization(this, [constraintType]); + } + PullInstantiatedTypeParameterSymbol.prototype._getResolver = function () { + return this.getRootSymbol()._getResolver(); + }; + return PullInstantiatedTypeParameterSymbol; + })(TypeScript.PullTypeParameterSymbol); + TypeScript.PullInstantiatedTypeParameterSymbol = PullInstantiatedTypeParameterSymbol; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTreeToAstVisitor = (function () { + function SyntaxTreeToAstVisitor(fileName, lineMap, compilationSettings) { + this.fileName = fileName; + this.lineMap = lineMap; + this.compilationSettings = compilationSettings; + this.position = 0; + this.previousTokenTrailingComments = null; + } + SyntaxTreeToAstVisitor.visit = function (syntaxTree, fileName, compilationSettings, incrementalAST) { + var visitor = incrementalAST ? new SyntaxTreeToIncrementalAstVisitor(fileName, syntaxTree.lineMap(), compilationSettings) : new SyntaxTreeToAstVisitor(fileName, syntaxTree.lineMap(), compilationSettings); + return syntaxTree.sourceUnit().accept(visitor); + }; + + SyntaxTreeToAstVisitor.prototype.movePast = function (element) { + if (element !== null) { + this.position += element.fullWidth(); + } + }; + + SyntaxTreeToAstVisitor.prototype.moveTo = function (element1, element2) { + if (element2 !== null) { + this.position += TypeScript.Syntax.childOffset(element1, element2); + } + }; + + SyntaxTreeToAstVisitor.prototype.setCommentsAndSpan = function (ast, fullStart, node) { + var firstToken = node.firstToken(); + var lastToken = node.lastToken(); + + this.setSpan(ast, fullStart, node, firstToken, lastToken); + ast.setPreComments(this.convertTokenLeadingComments(firstToken, fullStart)); + ast.setPostComments(this.convertNodeTrailingComments(node, lastToken, fullStart)); + }; + + SyntaxTreeToAstVisitor.prototype.createTokenSpan = function (fullStart, element) { + if (element === null) { + return null; + } + + if (element.fullWidth() === 0) { + return new TypeScript.ASTSpan(-1, -1); + } + + var leadingTriviaWidth = element.leadingTriviaWidth(); + var trailingTriviaWidth = element.trailingTriviaWidth(); + + var start = fullStart + leadingTriviaWidth; + var end = fullStart + element.fullWidth() - trailingTriviaWidth; + + return new TypeScript.ASTSpan(start, end); + }; + + SyntaxTreeToAstVisitor.prototype.setSpan = function (span, fullStart, element, firstToken, lastToken) { + if (typeof firstToken === "undefined") { firstToken = element.firstToken(); } + if (typeof lastToken === "undefined") { lastToken = element.lastToken(); } + var leadingTriviaWidth = firstToken ? firstToken.leadingTriviaWidth() : 0; + var trailingTriviaWidth = lastToken ? lastToken.trailingTriviaWidth() : 0; + + var desiredMinChar = fullStart + leadingTriviaWidth; + var desiredLimChar = fullStart + element.fullWidth() - trailingTriviaWidth; + + this.setSpanExplicit(span, desiredMinChar, desiredLimChar); + + span._trailingTriviaWidth = trailingTriviaWidth; + }; + + SyntaxTreeToAstVisitor.prototype.setSpanExplicit = function (span, start, end) { + span._start = start; + span._end = end; + }; + + SyntaxTreeToAstVisitor.prototype.visitSyntaxList = function (node) { + var start = this.position; + var array = new Array(node.childCount()); + + for (var i = 0, n = node.childCount(); i < n; i++) { + array[i] = node.childAt(i).accept(this); + } + + var result = new TypeScript.ISyntaxList2(this.fileName, array); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSeparatedSyntaxList = function (list) { + var start = this.position; + var array = new Array(list.nonSeparatorCount()); + + for (var i = 0, n = list.childCount(); i < n; i++) { + if (i % 2 === 0) { + array[i / 2] = list.childAt(i).accept(this); + this.previousTokenTrailingComments = null; + } else { + var separatorToken = list.childAt(i); + this.previousTokenTrailingComments = this.convertTokenTrailingComments(separatorToken, this.position + separatorToken.leadingTriviaWidth() + separatorToken.width()); + this.movePast(separatorToken); + } + } + + var result = new TypeScript.ISeparatedSyntaxList2(this.fileName, array, list.separatorCount()); + this.setSpan(result, start, list); + + result.setPostComments(this.previousTokenTrailingComments); + this.previousTokenTrailingComments = null; + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.convertComment = function (trivia, commentStartPosition, hasTrailingNewLine) { + var comment = new TypeScript.Comment(trivia, hasTrailingNewLine, commentStartPosition, commentStartPosition + trivia.fullWidth()); + + return comment; + }; + + SyntaxTreeToAstVisitor.prototype.convertComments = function (triviaList, commentStartPosition) { + var result = []; + + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + if (trivia.isComment()) { + var hasTrailingNewLine = ((i + 1) < n) && triviaList.syntaxTriviaAt(i + 1).isNewLine(); + result.push(this.convertComment(trivia, commentStartPosition, hasTrailingNewLine)); + } + + commentStartPosition += trivia.fullWidth(); + } + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.mergeComments = function (comments1, comments2) { + if (comments1 === null) { + return comments2; + } + + if (comments2 === null) { + return comments1; + } + + return comments1.concat(comments2); + }; + + SyntaxTreeToAstVisitor.prototype.convertTokenLeadingComments = function (token, commentStartPosition) { + if (token === null) { + return null; + } + + var preComments = token.hasLeadingComment() ? this.convertComments(token.leadingTrivia(), commentStartPosition) : null; + + var previousTokenTrailingComments = this.previousTokenTrailingComments; + this.previousTokenTrailingComments = null; + + return this.mergeComments(previousTokenTrailingComments, preComments); + }; + + SyntaxTreeToAstVisitor.prototype.convertTokenTrailingComments = function (token, commentStartPosition) { + if (token === null || !token.hasTrailingComment() || token.hasTrailingNewLine()) { + return null; + } + + return this.convertComments(token.trailingTrivia(), commentStartPosition); + }; + + SyntaxTreeToAstVisitor.prototype.convertNodeTrailingComments = function (node, lastToken, nodeStart) { + if (lastToken === null || !lastToken.hasTrailingComment() || lastToken.hasTrailingNewLine()) { + return null; + } + + return this.convertComments(lastToken.trailingTrivia(), nodeStart + node.fullWidth() - lastToken.trailingTriviaWidth()); + }; + + SyntaxTreeToAstVisitor.prototype.visitIdentifier = function (token) { + return this.visitToken(token); + }; + + SyntaxTreeToAstVisitor.prototype.visitToken = function (token) { + var fullStart = this.position; + + var result = this.visitTokenWorker(token); + + this.movePast(token); + + var start = fullStart + token.leadingTriviaWidth(); + this.setSpanExplicit(result, start, start + token.width()); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTokenWorker = function (token) { + switch (token.tokenKind) { + case 60 /* AnyKeyword */: + return new TypeScript.BuiltInType(60 /* AnyKeyword */, token.text(), token.valueText()); + case 61 /* BooleanKeyword */: + return new TypeScript.BuiltInType(61 /* BooleanKeyword */, token.text(), token.valueText()); + case 67 /* NumberKeyword */: + return new TypeScript.BuiltInType(67 /* NumberKeyword */, token.text(), token.valueText()); + case 69 /* StringKeyword */: + return new TypeScript.BuiltInType(69 /* StringKeyword */, token.text(), token.valueText()); + case 41 /* VoidKeyword */: + return new TypeScript.BuiltInType(41 /* VoidKeyword */, token.text(), token.valueText()); + case 35 /* ThisKeyword */: + return new TypeScript.ThisExpression(token.text(), token.valueText()); + case 50 /* SuperKeyword */: + return new TypeScript.SuperExpression(token.text(), token.valueText()); + case 37 /* TrueKeyword */: + return new TypeScript.LiteralExpression(37 /* TrueKeyword */, token.text(), token.valueText()); + case 24 /* FalseKeyword */: + return new TypeScript.LiteralExpression(24 /* FalseKeyword */, token.text(), token.valueText()); + case 32 /* NullKeyword */: + return new TypeScript.LiteralExpression(32 /* NullKeyword */, token.text(), token.valueText()); + case 14 /* StringLiteral */: + return new TypeScript.StringLiteral(token.text(), token.valueText()); + case 12 /* RegularExpressionLiteral */: + return new TypeScript.RegularExpressionLiteral(token.text(), token.valueText()); + case 13 /* NumericLiteral */: + var fullStart = this.position; + var preComments = this.convertTokenLeadingComments(token, fullStart); + + var result = new TypeScript.NumericLiteral(token.value(), token.text(), token.valueText()); + + result.setPreComments(preComments); + return result; + case 11 /* IdentifierName */: + return new TypeScript.Identifier(token.text()); + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SyntaxTreeToAstVisitor.prototype.visitSourceUnit = function (node) { + var start = this.position; + TypeScript.Debug.assert(start === 0); + + var bod = this.visitSyntaxList(node.moduleElements); + var comments = this.convertTokenLeadingComments(node.endOfFileToken, TypeScript.Syntax.childOffset(node, node.endOfFileToken)); + var result = new TypeScript.SourceUnit(bod, comments, this.fileName); + this.setSpanExplicit(result, start, start + node.fullWidth()); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitExternalModuleReference = function (node) { + var start = this.position; + + this.moveTo(node, node.stringLiteral); + var stringLiteral = node.stringLiteral.accept(this); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ExternalModuleReference(stringLiteral); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitModuleNameModuleReference = function (node) { + var start = this.position; + var moduleName = node.moduleName.accept(this); + + var result = new TypeScript.ModuleNameModuleReference(moduleName); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitClassDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var heritageClauses = node.heritageClauses ? this.visitSyntaxList(node.heritageClauses) : null; + + this.movePast(node.openBraceToken); + var members = this.visitSyntaxList(node.classElements); + + var closeBraceToken = this.createTokenSpan(this.position, node.closeBraceToken); + this.movePast(node.closeBraceToken); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.ClassDeclaration(modifiers, name, typeParameters, heritageClauses, members, closeBraceToken); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitModifiers = function (modifiers) { + var result = null; + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 47 /* ExportKeyword */)) { + result = result || []; + result.push(1 /* Exported */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 63 /* DeclareKeyword */)) { + result = result || []; + result.push(8 /* Ambient */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 58 /* StaticKeyword */)) { + result = result || []; + result.push(16 /* Static */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 57 /* PublicKeyword */)) { + result = result || []; + result.push(4 /* Public */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 55 /* PrivateKeyword */)) { + result = result || []; + result.push(2 /* Private */); + } + + return result || TypeScript.sentinelEmptyArray; + }; + + SyntaxTreeToAstVisitor.prototype.visitInterfaceDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var heritageClauses = node.heritageClauses ? this.visitSyntaxList(node.heritageClauses) : null; + + var body = this.visitObjectType(node.body); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.InterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, body); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitHeritageClause = function (node) { + var start = this.position; + + this.movePast(node.extendsOrImplementsKeyword); + var typeNames = this.visitSeparatedSyntaxList(node.typeNames); + + var result = new TypeScript.HeritageClause(node.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */ ? 230 /* ExtendsHeritageClause */ : 231 /* ImplementsHeritageClause */, typeNames); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitModuleDeclaration = function (node) { + var start = this.position; + + var modifiers = this.visitModifiers(node.modifiers); + + this.moveTo(node, node.moduleKeyword); + this.movePast(node.moduleKeyword); + + var moduleName = node.name ? node.name.accept(this) : null; + var stringLiteral = node.stringLiteral ? node.stringLiteral.accept(this) : null; + + this.movePast(node.openBraceToken); + + var moduleElements = this.visitSyntaxList(node.moduleElements); + + var closeBraceToken = this.createTokenSpan(this.position, node.closeBraceToken); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.ModuleDeclaration(modifiers, moduleName, stringLiteral, moduleElements, closeBraceToken); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + + var callSignature = this.visitCallSignature(node.callSignature); + var block = node.block ? this.visitBlock(node.block) : null; + + this.movePast(node.semicolonToken); + + var result = new TypeScript.FunctionDeclaration(this.visitModifiers(node.modifiers), name, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEnumDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var identifier = this.visitIdentifier(node.identifier); + + this.movePast(node.openBraceToken); + + var enumElements = this.visitSeparatedSyntaxList(node.enumElements); + + this.movePast(node.closeBraceToken); + + var result = new TypeScript.EnumDeclaration(this.visitModifiers(node.modifiers), identifier, enumElements); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEnumElement = function (node) { + var start = this.position; + + var memberName = this.visitToken(node.propertyName); + + var value = node.equalsValueClause !== null ? this.visitEqualsValueClause(node.equalsValueClause) : null; + + var result = new TypeScript.EnumElement(memberName, value); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitImportDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + this.movePast(node.equalsToken); + var alias = node.moduleReference.accept(this); + this.movePast(node.semicolonToken); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.ImportDeclaration(modifiers, name, alias); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitExportAssignment = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + this.movePast(node.semicolonToken); + + var result = new TypeScript.ExportAssignment(name); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.variableDeclaration); + + var declaration = node.variableDeclaration.accept(this); + this.movePast(node.semicolonToken); + + var modifiers = this.visitModifiers(node.modifiers); + + var result = new TypeScript.VariableStatement(modifiers, declaration); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.variableDeclarators); + var variableDecls = this.visitSeparatedSyntaxList(node.variableDeclarators); + + var result = new TypeScript.VariableDeclaration(variableDecls); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableDeclarator = function (node) { + var start = this.position; + var propertyName = this.visitToken(node.propertyName); + var typeExpr = this.visitTypeAnnotation(node.typeAnnotation); + var init = node.equalsValueClause ? this.visitEqualsValueClause(node.equalsValueClause) : null; + + var result = new TypeScript.VariableDeclarator(propertyName, typeExpr, init); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEqualsValueClause = function (node) { + var start = this.position; + var afterEqualsComments = this.convertTokenTrailingComments(node.equalsToken, this.position + node.equalsToken.leadingTriviaWidth() + node.equalsToken.width()); + + this.movePast(node.equalsToken); + var value = node.value.accept(this); + value.setPreComments(this.mergeComments(afterEqualsComments, value.preComments())); + + var result = new TypeScript.EqualsValueClause(value); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPrefixUnaryExpression = function (node) { + var start = this.position; + + this.movePast(node.operatorToken); + var operand = node.operand.accept(this); + + var result = new TypeScript.PrefixUnaryExpression(node.kind(), operand); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArrayLiteralExpression = function (node) { + var start = this.position; + var openStart = this.position + node.openBracketToken.leadingTriviaWidth(); + this.movePast(node.openBracketToken); + + var expressions = this.visitSeparatedSyntaxList(node.expressions); + + var closeStart = this.position + node.closeBracketToken.leadingTriviaWidth(); + this.movePast(node.closeBracketToken); + + var result = new TypeScript.ArrayLiteralExpression(expressions); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitOmittedExpression = function (node) { + var start = this.position; + + var result = new TypeScript.OmittedExpression(); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParenthesizedExpression = function (node) { + var start = this.position; + + var openParenToken = node.openParenToken; + var openParenTrailingComments = this.convertTokenTrailingComments(openParenToken, start + openParenToken.leadingTriviaWidth() + openParenToken.width()); + + this.movePast(openParenToken); + + var expr = node.expression.accept(this); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ParenthesizedExpression(openParenTrailingComments, expr); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + var start = this.position; + + var identifier = node.identifier.accept(this); + this.movePast(node.equalsGreaterThanToken); + + var block = node.block ? this.visitBlock(node.block) : null; + var expression = node.expression ? node.expression.accept(this) : null; + + var result = new TypeScript.SimpleArrowFunctionExpression(identifier, block, expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + var start = this.position; + + var callSignature = this.visitCallSignature(node.callSignature); + this.movePast(node.equalsGreaterThanToken); + + var block = node.block ? this.visitBlock(node.block) : null; + var expression = node.expression ? node.expression.accept(this) : null; + + var result = new TypeScript.ParenthesizedArrowFunctionExpression(callSignature, block, expression); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitType = function (type) { + return type ? type.accept(this) : null; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeQuery = function (node) { + var start = this.position; + this.movePast(node.typeOfKeyword); + var name = node.name.accept(this); + + var result = new TypeScript.TypeQuery(name); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitQualifiedName = function (node) { + var start = this.position; + var left = this.visitType(node.left); + this.movePast(node.dotToken); + var right = this.visitIdentifier(node.right); + + var result = new TypeScript.QualifiedName(left, right); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeArgumentList = function (node) { + if (node === null) { + return null; + } + + var start = this.position; + this.movePast(node.lessThanToken); + var typeArguments = this.visitSeparatedSyntaxList(node.typeArguments); + this.movePast(node.greaterThanToken); + + var result = new TypeScript.TypeArgumentList(typeArguments); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructorType = function (node) { + var start = this.position; + + this.movePast(node.newKeyword); + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var parameters = this.visitParameterList(node.parameterList); + this.movePast(node.equalsGreaterThanToken); + var returnType = this.visitType(node.type); + + var result = new TypeScript.ConstructorType(typeParameters, parameters, returnType); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionType = function (node) { + var start = this.position; + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var parameters = this.visitParameterList(node.parameterList); + this.movePast(node.equalsGreaterThanToken); + var returnType = this.visitType(node.type); + + var result = new TypeScript.FunctionType(typeParameters, parameters, returnType); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectType = function (node) { + var start = this.position; + + this.movePast(node.openBraceToken); + var typeMembers = this.visitSeparatedSyntaxList(node.typeMembers); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.ObjectType(typeMembers); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArrayType = function (node) { + var start = this.position; + + var underlying = this.visitType(node.type); + this.movePast(node.openBracketToken); + this.movePast(node.closeBracketToken); + + var result = new TypeScript.ArrayType(underlying); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitGenericType = function (node) { + var start = this.position; + + var underlying = this.visitType(node.name); + var typeArguments = this.visitTypeArgumentList(node.typeArgumentList); + + var result = new TypeScript.GenericType(underlying, typeArguments); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeAnnotation = function (node) { + if (!node) { + return null; + } + + var start = this.position; + this.movePast(node.colonToken); + var type = this.visitType(node.type); + + var result = new TypeScript.TypeAnnotation(type); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitBlock = function (node) { + if (!node) { + return null; + } + + var start = this.position; + + this.movePast(node.openBraceToken); + var statements = this.visitSyntaxList(node.statements); + var closeBracePosition = this.position; + + var closeBraceLeadingComments = this.convertTokenLeadingComments(node.closeBraceToken, this.position); + var closeBraceToken = this.createTokenSpan(this.position, node.closeBraceToken); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.Block(statements, closeBraceLeadingComments, closeBraceToken); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParameter = function (node) { + var start = this.position; + + var dotDotDotToken = this.createTokenSpan(this.position, node.dotDotDotToken); + + this.moveTo(node, node.identifier); + var identifier = this.visitIdentifier(node.identifier); + + var questionToken = this.createTokenSpan(this.position, node.questionToken); + this.movePast(node.questionToken); + var typeExpr = this.visitTypeAnnotation(node.typeAnnotation); + var init = node.equalsValueClause ? node.equalsValueClause.accept(this) : null; + + var modifiers = this.visitModifiers(node.modifiers); + + var result = new TypeScript.Parameter(dotDotDotToken, modifiers, identifier, questionToken, typeExpr, init); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberAccessExpression = function (node) { + var start = this.position; + + var expression = node.expression.accept(this); + this.movePast(node.dotToken); + var name = this.visitIdentifier(node.name); + + var result = new TypeScript.MemberAccessExpression(expression, name); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPostfixUnaryExpression = function (node) { + var start = this.position; + + var operand = node.operand.accept(this); + this.movePast(node.operatorToken); + + var result = new TypeScript.PostfixUnaryExpression(node.kind() === 210 /* PostIncrementExpression */ ? 210 /* PostIncrementExpression */ : 211 /* PostDecrementExpression */, operand); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitElementAccessExpression = function (node) { + var start = this.position; + + var expression = node.expression.accept(this); + this.movePast(node.openBracketToken); + var argumentExpression = node.argumentExpression.accept(this); + this.movePast(node.closeBracketToken); + + var result = new TypeScript.ElementAccessExpression(expression, argumentExpression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitInvocationExpression = function (node) { + var start = this.position; + + var expression = node.expression.accept(this); + var argumentList = this.visitArgumentList(node.argumentList); + + var result = new TypeScript.InvocationExpression(expression, argumentList); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArgumentList = function (node) { + if (node === null) { + return null; + } + + var start = this.position; + + var typeArguments = this.visitTypeArgumentList(node.typeArgumentList); + + this.movePast(node.openParenToken); + + var _arguments = this.visitSeparatedSyntaxList(node.arguments); + + if (node.arguments.fullWidth() === 0 && node.closeParenToken.fullWidth() === 0) { + var openParenTokenEnd = start + node.openParenToken.leadingTriviaWidth() + node.openParenToken.width(); + this.setSpanExplicit(_arguments, openParenTokenEnd, openParenTokenEnd + node.openParenToken.trailingTriviaWidth()); + } + + var closeParenToken = this.createTokenSpan(this.position, node.closeParenToken); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ArgumentList(typeArguments, _arguments, closeParenToken); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitBinaryExpression = function (node) { + var start = this.position; + + var left = node.left.accept(this); + this.movePast(node.operatorToken); + var right = node.right.accept(this); + + var result = new TypeScript.BinaryExpression(node.kind(), left, right); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConditionalExpression = function (node) { + var start = this.position; + + var condition = node.condition.accept(this); + this.movePast(node.questionToken); + var whenTrue = node.whenTrue.accept(this); + this.movePast(node.colonToken); + var whenFalse = node.whenFalse.accept(this); + + var result = new TypeScript.ConditionalExpression(condition, whenTrue, whenFalse); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructSignature = function (node) { + var start = this.position; + + this.movePast(node.newKeyword); + var callSignature = this.visitCallSignature(node.callSignature); + + var result = new TypeScript.ConstructSignature(callSignature); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMethodSignature = function (node) { + var start = this.position; + + var name = this.visitToken(node.propertyName); + + var questionToken = this.createTokenSpan(this.position, node.questionToken); + this.movePast(node.questionToken); + + var callSignature = this.visitCallSignature(node.callSignature); + + var result = new TypeScript.MethodSignature(name, questionToken, callSignature); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitIndexSignature = function (node) { + var start = this.position; + + this.movePast(node.openBracketToken); + + var parameter = node.parameter.accept(this); + + this.movePast(node.closeBracketToken); + var returnType = this.visitTypeAnnotation(node.typeAnnotation); + + var result = new TypeScript.IndexSignature(parameter, returnType); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPropertySignature = function (node) { + var start = this.position; + + var name = this.visitToken(node.propertyName); + + var questionToken = this.createTokenSpan(this.position, node.questionToken); + this.movePast(node.questionToken); + var typeExpr = this.visitTypeAnnotation(node.typeAnnotation); + + var result = new TypeScript.PropertySignature(name, questionToken, typeExpr); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParameterList = function (node) { + if (!node) { + return null; + } + + var start = this.position; + + var openParenToken = node.openParenToken; + + this.previousTokenTrailingComments = this.convertTokenTrailingComments(openParenToken, start + openParenToken.leadingTriviaWidth() + openParenToken.width()); + var openParenTrailingComments = null; + if (node.parameters.childCount() === 0) { + openParenTrailingComments = this.previousTokenTrailingComments; + this.previousTokenTrailingComments = null; + } + + this.movePast(node.openParenToken); + var parameters = this.visitSeparatedSyntaxList(node.parameters); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ParameterList(openParenTrailingComments, parameters); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCallSignature = function (node) { + var start = this.position; + + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var parameters = this.visitParameterList(node.parameterList); + var returnType = this.visitTypeAnnotation(node.typeAnnotation); + + var result = new TypeScript.CallSignature(typeParameters, parameters, returnType); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeParameterList = function (node) { + if (!node) { + return null; + } + + var start = this.position; + this.movePast(node.lessThanToken); + var typeParameters = this.visitSeparatedSyntaxList(node.typeParameters); + this.movePast(node.greaterThanToken); + + var result = new TypeScript.TypeParameterList(typeParameters); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeParameter = function (node) { + var start = this.position; + + var identifier = this.visitIdentifier(node.identifier); + var constraint = node.constraint ? node.constraint.accept(this) : null; + + var result = new TypeScript.TypeParameter(identifier, constraint); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstraint = function (node) { + var start = this.position; + this.movePast(node.extendsKeyword); + var type = this.visitType(node.type); + + var result = new TypeScript.Constraint(type); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitIfStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var thenBod = node.statement.accept(this); + var elseBod = node.elseClause ? node.elseClause.accept(this) : null; + + var result = new TypeScript.IfStatement(condition, thenBod, elseBod); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitElseClause = function (node) { + var start = this.position; + + this.movePast(node.elseKeyword); + var statement = node.statement.accept(this); + + var result = new TypeScript.ElseClause(statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitExpressionStatement = function (node) { + var start = this.position; + + var preComments = this.convertTokenLeadingComments(node.firstToken(), start); + var expression = node.expression.accept(this); + + var semicolonPosition = this.position; + + var postComments = this.convertComments(node.semicolonToken.trailingTrivia(), this.position + node.semicolonToken.leadingTriviaWidth() + node.semicolonToken.width()); + this.movePast(node.semicolonToken); + + var result = new TypeScript.ExpressionStatement(expression); + this.setSpan(result, start, node); + + result.setPreComments(preComments); + result.setPostComments(postComments); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructorDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.callSignature); + var callSignature = this.visitCallSignature(node.callSignature); + + var block = node.block ? node.block.accept(this) : null; + + this.movePast(node.semicolonToken); + + var result = new TypeScript.ConstructorDeclaration(callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitIndexMemberDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.indexSignature); + var indexSignature = node.indexSignature.accept(this); + + this.movePast(node.semicolonToken); + + var result = new TypeScript.IndexMemberDeclaration(indexSignature); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.propertyName); + var name = this.visitToken(node.propertyName); + + var callSignature = this.visitCallSignature(node.callSignature); + var block = node.block ? this.visitBlock(node.block) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.MemberFunctionDeclaration(this.visitModifiers(node.modifiers), name, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitGetAccessor = function (node) { + var start = this.position; + + this.moveTo(node, node.propertyName); + var name = this.visitToken(node.propertyName); + var parameters = this.visitParameterList(node.parameterList); + var returnType = this.visitTypeAnnotation(node.typeAnnotation); + + var block = node.block ? node.block.accept(this) : null; + var result = new TypeScript.GetAccessor(this.visitModifiers(node.modifiers), name, parameters, returnType, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSetAccessor = function (node) { + var start = this.position; + + this.moveTo(node, node.propertyName); + var name = this.visitToken(node.propertyName); + var parameters = this.visitParameterList(node.parameterList); + var block = node.block ? node.block.accept(this) : null; + var result = new TypeScript.SetAccessor(this.visitModifiers(node.modifiers), name, parameters, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberVariableDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.variableDeclarator); + var variableDeclarator = node.variableDeclarator.accept(this); + this.movePast(node.semicolonToken); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.MemberVariableDeclaration(modifiers, variableDeclarator); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitThrowStatement = function (node) { + var start = this.position; + + this.movePast(node.throwKeyword); + var expression = node.expression.accept(this); + this.movePast(node.semicolonToken); + + var result = new TypeScript.ThrowStatement(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitReturnStatement = function (node) { + var start = this.position; + + this.movePast(node.returnKeyword); + var expression = node.expression ? node.expression.accept(this) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.ReturnStatement(expression); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectCreationExpression = function (node) { + var start = this.position; + + this.movePast(node.newKeyword); + var expression = node.expression.accept(this); + var argumentList = this.visitArgumentList(node.argumentList); + + var result = new TypeScript.ObjectCreationExpression(expression, argumentList); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSwitchStatement = function (node) { + var start = this.position; + + this.movePast(node.switchKeyword); + this.movePast(node.openParenToken); + var expression = node.expression.accept(this); + + var closeParenToken = this.createTokenSpan(this.position, node.closeParenToken); + this.movePast(node.closeParenToken); + this.movePast(node.openBraceToken); + var switchClauses = this.visitSyntaxList(node.switchClauses); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.SwitchStatement(expression, closeParenToken, switchClauses); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCaseSwitchClause = function (node) { + var start = this.position; + + this.movePast(node.caseKeyword); + var expression = node.expression.accept(this); + this.movePast(node.colonToken); + var statements = this.visitSyntaxList(node.statements); + + var result = new TypeScript.CaseSwitchClause(expression, statements); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDefaultSwitchClause = function (node) { + var start = this.position; + + this.movePast(node.defaultKeyword); + this.movePast(node.colonToken); + var statements = this.visitSyntaxList(node.statements); + + var result = new TypeScript.DefaultSwitchClause(statements); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitBreakStatement = function (node) { + var start = this.position; + + this.movePast(node.breakKeyword); + var identifier = node.identifier ? node.identifier.accept(this) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.BreakStatement(identifier); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitContinueStatement = function (node) { + var start = this.position; + + this.movePast(node.continueKeyword); + var identifier = node.identifier ? node.identifier.accept(this) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.ContinueStatement(identifier); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitForStatement = function (node) { + var start = this.position; + + this.movePast(node.forKeyword); + this.movePast(node.openParenToken); + var variableDeclaration = node.variableDeclaration ? node.variableDeclaration.accept(this) : null; + var initializer = node.initializer ? node.initializer.accept(this) : null; + + this.movePast(node.firstSemicolonToken); + var cond = node.condition ? node.condition.accept(this) : null; + this.movePast(node.secondSemicolonToken); + var incr = node.incrementor ? node.incrementor.accept(this) : null; + this.movePast(node.closeParenToken); + var body = node.statement.accept(this); + + var result = new TypeScript.ForStatement(variableDeclaration, initializer, cond, incr, body); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitForInStatement = function (node) { + var start = this.position; + + this.movePast(node.forKeyword); + this.movePast(node.openParenToken); + var variableDeclaration = node.variableDeclaration ? node.variableDeclaration.accept(this) : null; + var left = node.left ? node.left.accept(this) : null; + + this.movePast(node.inKeyword); + var expression = node.expression.accept(this); + this.movePast(node.closeParenToken); + var body = node.statement.accept(this); + + var result = new TypeScript.ForInStatement(variableDeclaration, left, expression, body); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitWhileStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var statement = node.statement.accept(this); + + var result = new TypeScript.WhileStatement(condition, statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitWithStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var statement = node.statement.accept(this); + + var result = new TypeScript.WithStatement(condition, statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCastExpression = function (node) { + var start = this.position; + + this.movePast(node.lessThanToken); + var castTerm = this.visitType(node.type); + this.movePast(node.greaterThanToken); + var expression = node.expression.accept(this); + + var result = new TypeScript.CastExpression(castTerm, expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectLiteralExpression = function (node) { + var start = this.position; + + var openStart = this.position + node.openBraceToken.leadingTriviaWidth(); + this.movePast(node.openBraceToken); + + var propertyAssignments = this.visitSeparatedSyntaxList(node.propertyAssignments); + + var closeStart = this.position + node.closeBraceToken.leadingTriviaWidth(); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.ObjectLiteralExpression(propertyAssignments); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSimplePropertyAssignment = function (node) { + var start = this.position; + + var preComments = this.convertTokenLeadingComments(node.firstToken(), start); + var postComments = this.convertNodeTrailingComments(node, node.lastToken(), start); + + var propertyName = node.propertyName.accept(this); + + var afterColonComments = this.convertTokenTrailingComments(node.colonToken, this.position + node.colonToken.leadingTriviaWidth() + node.colonToken.width()); + + this.movePast(node.colonToken); + var expression = node.expression.accept(this); + expression.setPreComments(this.mergeComments(afterColonComments, expression.preComments())); + + var result = new TypeScript.SimplePropertyAssignment(propertyName, expression); + this.setSpan(result, start, node); + + result.setPreComments(preComments); + result.setPostComments(postComments); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + var start = this.position; + + var propertyName = node.propertyName.accept(this); + var callSignature = this.visitCallSignature(node.callSignature); + var block = this.visitBlock(node.block); + + var result = new TypeScript.FunctionPropertyAssignment(propertyName, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionExpression = function (node) { + var start = this.position; + + this.movePast(node.functionKeyword); + var name = node.identifier === null ? null : this.visitIdentifier(node.identifier); + + var callSignature = this.visitCallSignature(node.callSignature); + var block = node.block ? node.block.accept(this) : null; + + var result = new TypeScript.FunctionExpression(name, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEmptyStatement = function (node) { + var start = this.position; + + this.movePast(node.semicolonToken); + + var result = new TypeScript.EmptyStatement(); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTryStatement = function (node) { + var start = this.position; + + this.movePast(node.tryKeyword); + var tryBody = node.block.accept(this); + + var catchClause = null; + if (node.catchClause !== null) { + catchClause = node.catchClause.accept(this); + } + + var finallyBody = null; + if (node.finallyClause !== null) { + finallyBody = node.finallyClause.accept(this); + } + + var result = new TypeScript.TryStatement(tryBody, catchClause, finallyBody); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCatchClause = function (node) { + var start = this.position; + + this.movePast(node.catchKeyword); + this.movePast(node.openParenToken); + var identifier = this.visitIdentifier(node.identifier); + var typeAnnotation = this.visitTypeAnnotation(node.typeAnnotation); + this.movePast(node.closeParenToken); + var block = node.block.accept(this); + + var result = new TypeScript.CatchClause(identifier, typeAnnotation, block); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFinallyClause = function (node) { + var start = this.position; + this.movePast(node.finallyKeyword); + var block = node.block.accept(this); + + var result = new TypeScript.FinallyClause(block); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitLabeledStatement = function (node) { + var start = this.position; + + var identifier = this.visitIdentifier(node.identifier); + this.movePast(node.colonToken); + var statement = node.statement.accept(this); + + var result = new TypeScript.LabeledStatement(identifier, statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDoStatement = function (node) { + var start = this.position; + + this.movePast(node.doKeyword); + var statement = node.statement.accept(this); + var whileKeyword = this.createTokenSpan(this.position, node.whileKeyword); + + this.movePast(node.whileKeyword); + this.movePast(node.openParenToken); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + this.movePast(node.semicolonToken); + + var result = new TypeScript.DoStatement(statement, whileKeyword, condition); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeOfExpression = function (node) { + var start = this.position; + + this.movePast(node.typeOfKeyword); + var expression = node.expression.accept(this); + + var result = new TypeScript.TypeOfExpression(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDeleteExpression = function (node) { + var start = this.position; + + this.movePast(node.deleteKeyword); + var expression = node.expression.accept(this); + + var result = new TypeScript.DeleteExpression(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVoidExpression = function (node) { + var start = this.position; + + this.movePast(node.voidKeyword); + var expression = node.expression.accept(this); + + var result = new TypeScript.VoidExpression(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDebuggerStatement = function (node) { + var start = this.position; + + this.movePast(node.debuggerKeyword); + this.movePast(node.semicolonToken); + + var result = new TypeScript.DebuggerStatement(); + this.setSpan(result, start, node); + + return result; + }; + return SyntaxTreeToAstVisitor; + })(); + TypeScript.SyntaxTreeToAstVisitor = SyntaxTreeToAstVisitor; + + function applyDelta(ast, delta) { + if (ast) { + if (ast._start !== -1) { + ast._start += delta; + } + + if (ast._end !== -1) { + ast._end += delta; + } + } + } + + function applyDeltaToComments(comments, delta) { + if (comments && comments.length > 0) { + for (var i = 0; i < comments.length; i++) { + var comment = comments[i]; + applyDelta(comment, delta); + } + } + } + + var SyntaxTreeToIncrementalAstVisitor = (function (_super) { + __extends(SyntaxTreeToIncrementalAstVisitor, _super); + function SyntaxTreeToIncrementalAstVisitor() { + _super.apply(this, arguments); + } + SyntaxTreeToIncrementalAstVisitor.prototype.applyDelta = function (ast, delta) { + if (delta === 0) { + return; + } + + var pre = function (cur) { + applyDelta(cur, delta); + applyDeltaToComments(cur.preComments(), delta); + applyDeltaToComments(cur.postComments(), delta); + + switch (cur.kind()) { + case 146 /* Block */: + applyDelta(cur.closeBraceToken, delta); + break; + + case 226 /* ArgumentList */: + applyDelta(cur.closeParenToken, delta); + break; + + case 130 /* ModuleDeclaration */: + applyDelta(cur.endingToken, delta); + break; + + case 131 /* ClassDeclaration */: + applyDelta(cur.closeBraceToken, delta); + break; + + case 161 /* DoStatement */: + applyDelta(cur.whileKeyword, delta); + break; + + case 151 /* SwitchStatement */: + applyDelta(cur.closeParenToken, delta); + break; + } + }; + + TypeScript.getAstWalkerFactory().simpleWalk(ast, pre); + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.setSpanExplicit = function (span, start, end) { + if (span._start !== -1) { + var delta = start - span._start; + this.applyDelta(span, delta); + + span._end = end; + } else { + _super.prototype.setSpanExplicit.call(this, span, start, end); + } + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.getAndMovePastAST = function (element) { + if (this.previousTokenTrailingComments !== null) { + return null; + } + + var result = element._ast; + if (!result) { + return null; + } + + var start = this.position; + this.movePast(element); + this.setSpan(result, start, element); + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.setAST = function (element, ast) { + element._ast = ast; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSyntaxList = function (list) { + var result = this.getAndMovePastAST(list); + if (!result) { + result = _super.prototype.visitSyntaxList.call(this, list); + + if (list.childCount() > 0) { + this.setAST(list, result); + } + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSeparatedSyntaxList = function (list) { + var result = this.getAndMovePastAST(list); + if (!result) { + result = _super.prototype.visitSeparatedSyntaxList.call(this, list); + + if (list.childCount() > 0) { + this.setAST(list, result); + } + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitToken = function (token) { + var result = this.getAndMovePastAST(token); + + if (!result) { + result = _super.prototype.visitToken.call(this, token); + this.setAST(token, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitClassDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitClassDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitInterfaceDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitInterfaceDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitHeritageClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitHeritageClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitModuleDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitModuleDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitImportDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitImportDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitExportAssignment = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitExportAssignment.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitPrefixUnaryExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitPrefixUnaryExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitArrayLiteralExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitArrayLiteralExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitOmittedExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitOmittedExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitParenthesizedExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitParenthesizedExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSimpleArrowFunctionExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitParenthesizedArrowFunctionExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitQualifiedName = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + var result = _super.prototype.visitQualifiedName.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConstructorType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConstructorType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitObjectType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitObjectType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitArrayType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitArrayType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitGenericType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitGenericType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitBlock = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitBlock.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitParameter = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitParameter.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMemberAccessExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMemberAccessExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitPostfixUnaryExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitPostfixUnaryExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitElementAccessExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitElementAccessExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitInvocationExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitInvocationExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitBinaryExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitBinaryExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConditionalExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConditionalExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConstructSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConstructSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMethodSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMethodSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitIndexSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitIndexSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitPropertySignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitPropertySignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCallSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCallSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitTypeParameter = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitTypeParameter.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitIfStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitIfStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitExpressionStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitExpressionStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConstructorDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConstructorDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMemberFunctionDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitGetAccessor = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitGetAccessor.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSetAccessor = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSetAccessor.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMemberVariableDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMemberVariableDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitThrowStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitThrowStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitReturnStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitReturnStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitObjectCreationExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitObjectCreationExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSwitchStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSwitchStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCaseSwitchClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCaseSwitchClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDefaultSwitchClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDefaultSwitchClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitBreakStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitBreakStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitContinueStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitContinueStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitForStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitForStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitForInStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitForInStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitWhileStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitWhileStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitWithStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitWithStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCastExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCastExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitObjectLiteralExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitObjectLiteralExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSimplePropertyAssignment = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSimplePropertyAssignment.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionPropertyAssignment.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitEmptyStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitEmptyStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitTryStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitTryStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCatchClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCatchClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitLabeledStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitLabeledStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDoStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDoStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitTypeOfExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitTypeOfExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDeleteExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDeleteExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitVoidExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitVoidExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDebuggerStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDebuggerStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + return SyntaxTreeToIncrementalAstVisitor; + })(SyntaxTreeToAstVisitor); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ASTSpan = (function () { + function ASTSpan(_start, _end) { + this._start = _start; + this._end = _end; + } + ASTSpan.prototype.start = function () { + return this._start; + }; + + ASTSpan.prototype.end = function () { + return this._end; + }; + return ASTSpan; + })(); + TypeScript.ASTSpan = ASTSpan; + + var astID = 0; + + function structuralEqualsNotIncludingPosition(ast1, ast2) { + return structuralEquals(ast1, ast2, false); + } + TypeScript.structuralEqualsNotIncludingPosition = structuralEqualsNotIncludingPosition; + + function structuralEqualsIncludingPosition(ast1, ast2) { + return structuralEquals(ast1, ast2, true); + } + TypeScript.structuralEqualsIncludingPosition = structuralEqualsIncludingPosition; + + function commentStructuralEqualsNotIncludingPosition(ast1, ast2) { + return commentStructuralEquals(ast1, ast2, false); + } + + function commentStructuralEqualsIncludingPosition(ast1, ast2) { + return commentStructuralEquals(ast1, ast2, true); + } + + function structuralEquals(ast1, ast2, includingPosition) { + if (ast1 === ast2) { + return true; + } + + return ast1 !== null && ast2 !== null && ast1.kind() === ast2.kind() && ast1.structuralEquals(ast2, includingPosition); + } + + function commentStructuralEquals(ast1, ast2, includingPosition) { + if (ast1 === ast2) { + return true; + } + + return ast1 !== null && ast2 !== null && ast1.structuralEquals(ast2, includingPosition); + } + + function astArrayStructuralEquals(array1, array2, includingPosition) { + return TypeScript.ArrayUtilities.sequenceEquals(array1, array2, includingPosition ? structuralEqualsIncludingPosition : structuralEqualsNotIncludingPosition); + } + + function commentArrayStructuralEquals(array1, array2, includingPosition) { + return TypeScript.ArrayUtilities.sequenceEquals(array1, array2, includingPosition ? commentStructuralEqualsIncludingPosition : commentStructuralEqualsNotIncludingPosition); + } + + var AST = (function () { + function AST() { + this.parent = null; + this._start = -1; + this._end = -1; + this._trailingTriviaWidth = 0; + this._astID = astID++; + this._preComments = null; + this._postComments = null; + } + AST.prototype.syntaxID = function () { + return this._astID; + }; + + AST.prototype.start = function () { + return this._start; + }; + + AST.prototype.end = function () { + return this._end; + }; + + AST.prototype.trailingTriviaWidth = function () { + return this._trailingTriviaWidth; + }; + + AST.prototype.fileName = function () { + return this.parent.fileName(); + }; + + AST.prototype.kind = function () { + throw TypeScript.Errors.abstract(); + }; + + AST.prototype.preComments = function () { + return this._preComments; + }; + + AST.prototype.postComments = function () { + return this._postComments; + }; + + AST.prototype.setPreComments = function (comments) { + if (comments && comments.length) { + this._preComments = comments; + } else if (this._preComments) { + this._preComments = null; + } + }; + + AST.prototype.setPostComments = function (comments) { + if (comments && comments.length) { + this._postComments = comments; + } else if (this._postComments) { + this._postComments = null; + } + }; + + AST.prototype.width = function () { + return this.end() - this.start(); + }; + + AST.prototype.structuralEquals = function (ast, includingPosition) { + if (includingPosition) { + if (this.start() !== ast.start() || this.end() !== ast.end()) { + return false; + } + } + + return commentArrayStructuralEquals(this.preComments(), ast.preComments(), includingPosition) && commentArrayStructuralEquals(this.postComments(), ast.postComments(), includingPosition); + }; + + AST.prototype.isExpression = function () { + return false; + }; + return AST; + })(); + TypeScript.AST = AST; + + var ISyntaxList2 = (function (_super) { + __extends(ISyntaxList2, _super); + function ISyntaxList2(_fileName, members) { + _super.call(this); + this._fileName = _fileName; + this.members = members; + + for (var i = 0, n = members.length; i < n; i++) { + members[i].parent = this; + } + } + ISyntaxList2.prototype.childCount = function () { + return this.members.length; + }; + + ISyntaxList2.prototype.childAt = function (index) { + return this.members[index]; + }; + + ISyntaxList2.prototype.fileName = function () { + return this._fileName; + }; + + ISyntaxList2.prototype.kind = function () { + return 1 /* List */; + }; + + ISyntaxList2.prototype.firstOrDefault = function (func) { + return TypeScript.ArrayUtilities.firstOrDefault(this.members, func); + }; + + ISyntaxList2.prototype.lastOrDefault = function (func) { + return TypeScript.ArrayUtilities.lastOrDefault(this.members, func); + }; + + ISyntaxList2.prototype.any = function (func) { + return TypeScript.ArrayUtilities.any(this.members, func); + }; + + ISyntaxList2.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && astArrayStructuralEquals(this.members, ast.members, includingPosition); + }; + return ISyntaxList2; + })(AST); + TypeScript.ISyntaxList2 = ISyntaxList2; + + var ISeparatedSyntaxList2 = (function (_super) { + __extends(ISeparatedSyntaxList2, _super); + function ISeparatedSyntaxList2(_fileName, members, _separatorCount) { + _super.call(this); + this._fileName = _fileName; + this.members = members; + this._separatorCount = _separatorCount; + + for (var i = 0, n = members.length; i < n; i++) { + members[i].parent = this; + } + } + ISeparatedSyntaxList2.prototype.nonSeparatorCount = function () { + return this.members.length; + }; + + ISeparatedSyntaxList2.prototype.separatorCount = function () { + return this._separatorCount; + }; + + ISeparatedSyntaxList2.prototype.nonSeparatorAt = function (index) { + return this.members[index]; + }; + + ISeparatedSyntaxList2.prototype.nonSeparatorIndexOf = function (ast) { + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + if (this.nonSeparatorAt(i) === ast) { + return i; + } + } + + return -1; + }; + + ISeparatedSyntaxList2.prototype.fileName = function () { + return this._fileName; + }; + + ISeparatedSyntaxList2.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + ISeparatedSyntaxList2.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && astArrayStructuralEquals(this.members, ast.members, includingPosition); + }; + return ISeparatedSyntaxList2; + })(AST); + TypeScript.ISeparatedSyntaxList2 = ISeparatedSyntaxList2; + + var SourceUnit = (function (_super) { + __extends(SourceUnit, _super); + function SourceUnit(moduleElements, endOfFileTokenLeadingComments, _fileName) { + _super.call(this); + this.moduleElements = moduleElements; + this.endOfFileTokenLeadingComments = endOfFileTokenLeadingComments; + this._fileName = _fileName; + moduleElements && (moduleElements.parent = this); + } + SourceUnit.prototype.fileName = function () { + return this._fileName; + }; + + SourceUnit.prototype.kind = function () { + return 120 /* SourceUnit */; + }; + + SourceUnit.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.moduleElements, ast.moduleElements, includingPosition); + }; + return SourceUnit; + })(AST); + TypeScript.SourceUnit = SourceUnit; + + var Identifier = (function (_super) { + __extends(Identifier, _super); + function Identifier(_text) { + _super.call(this); + this._text = _text; + this._valueText = null; + } + Identifier.prototype.text = function () { + return this._text; + }; + Identifier.prototype.valueText = function () { + if (!this._valueText) { + var text = this._text; + if (text === "__proto__") { + this._valueText = "#__proto__"; + } else { + this._valueText = TypeScript.Syntax.massageEscapes(text); + } + } + + return this._valueText; + }; + + Identifier.prototype.kind = function () { + return 11 /* IdentifierName */; + }; + + Identifier.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._text === ast._text; + }; + + Identifier.prototype.isExpression = function () { + return true; + }; + return Identifier; + })(AST); + TypeScript.Identifier = Identifier; + + var LiteralExpression = (function (_super) { + __extends(LiteralExpression, _super); + function LiteralExpression(_nodeType, _text, _valueText) { + _super.call(this); + this._nodeType = _nodeType; + this._text = _text; + this._valueText = _valueText; + } + LiteralExpression.prototype.text = function () { + return this._text; + }; + + LiteralExpression.prototype.valueText = function () { + return this._valueText; + }; + + LiteralExpression.prototype.kind = function () { + return this._nodeType; + }; + + LiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + LiteralExpression.prototype.isExpression = function () { + return true; + }; + return LiteralExpression; + })(AST); + TypeScript.LiteralExpression = LiteralExpression; + + var ThisExpression = (function (_super) { + __extends(ThisExpression, _super); + function ThisExpression(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + } + ThisExpression.prototype.text = function () { + return this._text; + }; + + ThisExpression.prototype.valueText = function () { + return this._valueText; + }; + + ThisExpression.prototype.kind = function () { + return 35 /* ThisKeyword */; + }; + + ThisExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + ThisExpression.prototype.isExpression = function () { + return true; + }; + return ThisExpression; + })(AST); + TypeScript.ThisExpression = ThisExpression; + + var SuperExpression = (function (_super) { + __extends(SuperExpression, _super); + function SuperExpression(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + } + SuperExpression.prototype.text = function () { + return this._text; + }; + + SuperExpression.prototype.valueText = function () { + return this._valueText; + }; + + SuperExpression.prototype.kind = function () { + return 50 /* SuperKeyword */; + }; + + SuperExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + SuperExpression.prototype.isExpression = function () { + return true; + }; + return SuperExpression; + })(AST); + TypeScript.SuperExpression = SuperExpression; + + var NumericLiteral = (function (_super) { + __extends(NumericLiteral, _super); + function NumericLiteral(_value, _text, _valueText) { + _super.call(this); + this._value = _value; + this._text = _text; + this._valueText = _valueText; + } + NumericLiteral.prototype.text = function () { + return this._text; + }; + NumericLiteral.prototype.valueText = function () { + return this._valueText; + }; + NumericLiteral.prototype.value = function () { + return this._value; + }; + + NumericLiteral.prototype.kind = function () { + return 13 /* NumericLiteral */; + }; + + NumericLiteral.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && (this._value === ast._value || (isNaN(this._value) && isNaN(ast._value))) && this._text === ast._text; + }; + + NumericLiteral.prototype.isExpression = function () { + return true; + }; + return NumericLiteral; + })(AST); + TypeScript.NumericLiteral = NumericLiteral; + + var RegularExpressionLiteral = (function (_super) { + __extends(RegularExpressionLiteral, _super); + function RegularExpressionLiteral(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + } + RegularExpressionLiteral.prototype.text = function () { + return this._text; + }; + + RegularExpressionLiteral.prototype.valueText = function () { + return this._valueText; + }; + + RegularExpressionLiteral.prototype.kind = function () { + return 12 /* RegularExpressionLiteral */; + }; + + RegularExpressionLiteral.prototype.isExpression = function () { + return true; + }; + return RegularExpressionLiteral; + })(AST); + TypeScript.RegularExpressionLiteral = RegularExpressionLiteral; + + var StringLiteral = (function (_super) { + __extends(StringLiteral, _super); + function StringLiteral(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + this._valueText = _valueText === "__proto__" ? "#__proto__" : _valueText; + } + StringLiteral.prototype.text = function () { + return this._text; + }; + StringLiteral.prototype.valueText = function () { + return this._valueText; + }; + + StringLiteral.prototype.kind = function () { + return 14 /* StringLiteral */; + }; + + StringLiteral.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._text === ast._text; + }; + + StringLiteral.prototype.isExpression = function () { + return true; + }; + return StringLiteral; + })(AST); + TypeScript.StringLiteral = StringLiteral; + + var TypeAnnotation = (function (_super) { + __extends(TypeAnnotation, _super); + function TypeAnnotation(type) { + _super.call(this); + this.type = type; + type && (type.parent = this); + } + TypeAnnotation.prototype.kind = function () { + return 244 /* TypeAnnotation */; + }; + return TypeAnnotation; + })(AST); + TypeScript.TypeAnnotation = TypeAnnotation; + + var BuiltInType = (function (_super) { + __extends(BuiltInType, _super); + function BuiltInType(_nodeType, _text, _valueText) { + _super.call(this); + this._nodeType = _nodeType; + this._text = _text; + this._valueText = _valueText; + } + BuiltInType.prototype.text = function () { + return this._text; + }; + + BuiltInType.prototype.valueText = function () { + return this._valueText; + }; + + BuiltInType.prototype.kind = function () { + return this._nodeType; + }; + return BuiltInType; + })(AST); + TypeScript.BuiltInType = BuiltInType; + + var ExternalModuleReference = (function (_super) { + __extends(ExternalModuleReference, _super); + function ExternalModuleReference(stringLiteral) { + _super.call(this); + this.stringLiteral = stringLiteral; + stringLiteral && (stringLiteral.parent = this); + } + ExternalModuleReference.prototype.kind = function () { + return 245 /* ExternalModuleReference */; + }; + return ExternalModuleReference; + })(AST); + TypeScript.ExternalModuleReference = ExternalModuleReference; + + var ModuleNameModuleReference = (function (_super) { + __extends(ModuleNameModuleReference, _super); + function ModuleNameModuleReference(moduleName) { + _super.call(this); + this.moduleName = moduleName; + moduleName && (moduleName.parent = this); + } + ModuleNameModuleReference.prototype.kind = function () { + return 246 /* ModuleNameModuleReference */; + }; + return ModuleNameModuleReference; + })(AST); + TypeScript.ModuleNameModuleReference = ModuleNameModuleReference; + + var ImportDeclaration = (function (_super) { + __extends(ImportDeclaration, _super); + function ImportDeclaration(modifiers, identifier, moduleReference) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.moduleReference = moduleReference; + identifier && (identifier.parent = this); + moduleReference && (moduleReference.parent = this); + } + ImportDeclaration.prototype.kind = function () { + return 133 /* ImportDeclaration */; + }; + + ImportDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.moduleReference, ast.moduleReference, includingPosition); + }; + return ImportDeclaration; + })(AST); + TypeScript.ImportDeclaration = ImportDeclaration; + + var ExportAssignment = (function (_super) { + __extends(ExportAssignment, _super); + function ExportAssignment(identifier) { + _super.call(this); + this.identifier = identifier; + identifier && (identifier.parent = this); + } + ExportAssignment.prototype.kind = function () { + return 134 /* ExportAssignment */; + }; + + ExportAssignment.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition); + }; + return ExportAssignment; + })(AST); + TypeScript.ExportAssignment = ExportAssignment; + + var TypeParameterList = (function (_super) { + __extends(TypeParameterList, _super); + function TypeParameterList(typeParameters) { + _super.call(this); + this.typeParameters = typeParameters; + typeParameters && (typeParameters.parent = this); + } + TypeParameterList.prototype.kind = function () { + return 229 /* TypeParameterList */; + }; + return TypeParameterList; + })(AST); + TypeScript.TypeParameterList = TypeParameterList; + + var ClassDeclaration = (function (_super) { + __extends(ClassDeclaration, _super); + function ClassDeclaration(modifiers, identifier, typeParameterList, heritageClauses, classElements, closeBraceToken) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.classElements = classElements; + this.closeBraceToken = closeBraceToken; + identifier && (identifier.parent = this); + typeParameterList && (typeParameterList.parent = this); + heritageClauses && (heritageClauses.parent = this); + classElements && (classElements.parent = this); + } + ClassDeclaration.prototype.kind = function () { + return 131 /* ClassDeclaration */; + }; + + ClassDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.classElements, ast.classElements, includingPosition) && structuralEquals(this.typeParameterList, ast.typeParameterList, includingPosition) && structuralEquals(this.heritageClauses, ast.heritageClauses, includingPosition); + }; + return ClassDeclaration; + })(AST); + TypeScript.ClassDeclaration = ClassDeclaration; + + var InterfaceDeclaration = (function (_super) { + __extends(InterfaceDeclaration, _super); + function InterfaceDeclaration(modifiers, identifier, typeParameterList, heritageClauses, body) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.body = body; + identifier && (identifier.parent = this); + typeParameterList && (typeParameterList.parent = this); + body && (body.parent = this); + heritageClauses && (heritageClauses.parent = this); + } + InterfaceDeclaration.prototype.kind = function () { + return 128 /* InterfaceDeclaration */; + }; + + InterfaceDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.body, ast.body, includingPosition) && structuralEquals(this.typeParameterList, ast.typeParameterList, includingPosition) && structuralEquals(this.heritageClauses, ast.heritageClauses, includingPosition); + }; + return InterfaceDeclaration; + })(AST); + TypeScript.InterfaceDeclaration = InterfaceDeclaration; + + var HeritageClause = (function (_super) { + __extends(HeritageClause, _super); + function HeritageClause(_nodeType, typeNames) { + _super.call(this); + this._nodeType = _nodeType; + this.typeNames = typeNames; + typeNames && (typeNames.parent = this); + } + HeritageClause.prototype.kind = function () { + return this._nodeType; + }; + + HeritageClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.typeNames, ast.typeNames, includingPosition); + }; + return HeritageClause; + })(AST); + TypeScript.HeritageClause = HeritageClause; + + var ModuleDeclaration = (function (_super) { + __extends(ModuleDeclaration, _super); + function ModuleDeclaration(modifiers, name, stringLiteral, moduleElements, endingToken) { + _super.call(this); + this.modifiers = modifiers; + this.name = name; + this.stringLiteral = stringLiteral; + this.moduleElements = moduleElements; + this.endingToken = endingToken; + name && (name.parent = this); + stringLiteral && (stringLiteral.parent = this); + moduleElements && (moduleElements.parent = this); + } + ModuleDeclaration.prototype.kind = function () { + return 130 /* ModuleDeclaration */; + }; + + ModuleDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.moduleElements, ast.moduleElements, includingPosition); + }; + return ModuleDeclaration; + })(AST); + TypeScript.ModuleDeclaration = ModuleDeclaration; + + var FunctionDeclaration = (function (_super) { + __extends(FunctionDeclaration, _super); + function FunctionDeclaration(modifiers, identifier, callSignature, block) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + identifier && (identifier.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + FunctionDeclaration.prototype.kind = function () { + return 129 /* FunctionDeclaration */; + }; + + FunctionDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.block, ast.block, includingPosition) && structuralEquals(this.callSignature, ast.callSignature, includingPosition); + }; + return FunctionDeclaration; + })(AST); + TypeScript.FunctionDeclaration = FunctionDeclaration; + + var VariableStatement = (function (_super) { + __extends(VariableStatement, _super); + function VariableStatement(modifiers, declaration) { + _super.call(this); + this.modifiers = modifiers; + this.declaration = declaration; + declaration && (declaration.parent = this); + } + VariableStatement.prototype.kind = function () { + return 148 /* VariableStatement */; + }; + + VariableStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.declaration, ast.declaration, includingPosition); + }; + return VariableStatement; + })(AST); + TypeScript.VariableStatement = VariableStatement; + + var VariableDeclaration = (function (_super) { + __extends(VariableDeclaration, _super); + function VariableDeclaration(declarators) { + _super.call(this); + this.declarators = declarators; + declarators && (declarators.parent = this); + } + VariableDeclaration.prototype.kind = function () { + return 224 /* VariableDeclaration */; + }; + + VariableDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.declarators, ast.declarators, includingPosition); + }; + return VariableDeclaration; + })(AST); + TypeScript.VariableDeclaration = VariableDeclaration; + + var VariableDeclarator = (function (_super) { + __extends(VariableDeclarator, _super); + function VariableDeclarator(propertyName, typeAnnotation, equalsValueClause) { + _super.call(this); + this.propertyName = propertyName; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + propertyName && (propertyName.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + equalsValueClause && (equalsValueClause.parent = this); + } + VariableDeclarator.prototype.kind = function () { + return 225 /* VariableDeclarator */; + }; + return VariableDeclarator; + })(AST); + TypeScript.VariableDeclarator = VariableDeclarator; + + var EqualsValueClause = (function (_super) { + __extends(EqualsValueClause, _super); + function EqualsValueClause(value) { + _super.call(this); + this.value = value; + value && (value.parent = this); + } + EqualsValueClause.prototype.kind = function () { + return 232 /* EqualsValueClause */; + }; + return EqualsValueClause; + })(AST); + TypeScript.EqualsValueClause = EqualsValueClause; + + var PrefixUnaryExpression = (function (_super) { + __extends(PrefixUnaryExpression, _super); + function PrefixUnaryExpression(_nodeType, operand) { + _super.call(this); + this._nodeType = _nodeType; + this.operand = operand; + operand && (operand.parent = this); + } + PrefixUnaryExpression.prototype.kind = function () { + return this._nodeType; + }; + + PrefixUnaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand, ast.operand, includingPosition); + }; + + PrefixUnaryExpression.prototype.isExpression = function () { + return true; + }; + return PrefixUnaryExpression; + })(AST); + TypeScript.PrefixUnaryExpression = PrefixUnaryExpression; + + var ArrayLiteralExpression = (function (_super) { + __extends(ArrayLiteralExpression, _super); + function ArrayLiteralExpression(expressions) { + _super.call(this); + this.expressions = expressions; + expressions && (expressions.parent = this); + } + ArrayLiteralExpression.prototype.kind = function () { + return 214 /* ArrayLiteralExpression */; + }; + + ArrayLiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expressions, ast.expressions, includingPosition); + }; + + ArrayLiteralExpression.prototype.isExpression = function () { + return true; + }; + return ArrayLiteralExpression; + })(AST); + TypeScript.ArrayLiteralExpression = ArrayLiteralExpression; + + var OmittedExpression = (function (_super) { + __extends(OmittedExpression, _super); + function OmittedExpression() { + _super.apply(this, arguments); + } + OmittedExpression.prototype.kind = function () { + return 223 /* OmittedExpression */; + }; + + OmittedExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + OmittedExpression.prototype.isExpression = function () { + return true; + }; + return OmittedExpression; + })(AST); + TypeScript.OmittedExpression = OmittedExpression; + + var ParenthesizedExpression = (function (_super) { + __extends(ParenthesizedExpression, _super); + function ParenthesizedExpression(openParenTrailingComments, expression) { + _super.call(this); + this.openParenTrailingComments = openParenTrailingComments; + this.expression = expression; + expression && (expression.parent = this); + } + ParenthesizedExpression.prototype.kind = function () { + return 217 /* ParenthesizedExpression */; + }; + + ParenthesizedExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + ParenthesizedExpression.prototype.isExpression = function () { + return true; + }; + return ParenthesizedExpression; + })(AST); + TypeScript.ParenthesizedExpression = ParenthesizedExpression; + + var SimpleArrowFunctionExpression = (function (_super) { + __extends(SimpleArrowFunctionExpression, _super); + function SimpleArrowFunctionExpression(identifier, block, expression) { + _super.call(this); + this.identifier = identifier; + this.block = block; + this.expression = expression; + identifier && (identifier.parent = this); + block && (block.parent = this); + expression && (expression.parent = this); + } + SimpleArrowFunctionExpression.prototype.kind = function () { + return 219 /* SimpleArrowFunctionExpression */; + }; + + SimpleArrowFunctionExpression.prototype.isExpression = function () { + return true; + }; + return SimpleArrowFunctionExpression; + })(AST); + TypeScript.SimpleArrowFunctionExpression = SimpleArrowFunctionExpression; + + var ParenthesizedArrowFunctionExpression = (function (_super) { + __extends(ParenthesizedArrowFunctionExpression, _super); + function ParenthesizedArrowFunctionExpression(callSignature, block, expression) { + _super.call(this); + this.callSignature = callSignature; + this.block = block; + this.expression = expression; + callSignature && (callSignature.parent = this); + block && (block.parent = this); + expression && (expression.parent = this); + } + ParenthesizedArrowFunctionExpression.prototype.kind = function () { + return 218 /* ParenthesizedArrowFunctionExpression */; + }; + + ParenthesizedArrowFunctionExpression.prototype.isExpression = function () { + return true; + }; + return ParenthesizedArrowFunctionExpression; + })(AST); + TypeScript.ParenthesizedArrowFunctionExpression = ParenthesizedArrowFunctionExpression; + + var QualifiedName = (function (_super) { + __extends(QualifiedName, _super); + function QualifiedName(left, right) { + _super.call(this); + this.left = left; + this.right = right; + left && (left.parent = this); + right && (right.parent = this); + } + QualifiedName.prototype.kind = function () { + return 121 /* QualifiedName */; + }; + + QualifiedName.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.left, ast.left, includingPosition) && structuralEquals(this.right, ast.right, includingPosition); + }; + return QualifiedName; + })(AST); + TypeScript.QualifiedName = QualifiedName; + + var ParameterList = (function (_super) { + __extends(ParameterList, _super); + function ParameterList(openParenTrailingComments, parameters) { + _super.call(this); + this.openParenTrailingComments = openParenTrailingComments; + this.parameters = parameters; + parameters && (parameters.parent = this); + } + ParameterList.prototype.kind = function () { + return 227 /* ParameterList */; + }; + return ParameterList; + })(AST); + TypeScript.ParameterList = ParameterList; + + var ConstructorType = (function (_super) { + __extends(ConstructorType, _super); + function ConstructorType(typeParameterList, parameterList, type) { + _super.call(this); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.type = type; + typeParameterList && (typeParameterList.parent = this); + parameterList && (parameterList.parent = this); + type && (type.parent = this); + } + ConstructorType.prototype.kind = function () { + return 125 /* ConstructorType */; + }; + return ConstructorType; + })(AST); + TypeScript.ConstructorType = ConstructorType; + + var FunctionType = (function (_super) { + __extends(FunctionType, _super); + function FunctionType(typeParameterList, parameterList, type) { + _super.call(this); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.type = type; + typeParameterList && (typeParameterList.parent = this); + parameterList && (parameterList.parent = this); + type && (type.parent = this); + } + FunctionType.prototype.kind = function () { + return 123 /* FunctionType */; + }; + return FunctionType; + })(AST); + TypeScript.FunctionType = FunctionType; + + var ObjectType = (function (_super) { + __extends(ObjectType, _super); + function ObjectType(typeMembers) { + _super.call(this); + this.typeMembers = typeMembers; + typeMembers && (typeMembers.parent = this); + } + ObjectType.prototype.kind = function () { + return 122 /* ObjectType */; + }; + + ObjectType.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.typeMembers, ast.typeMembers, includingPosition); + }; + return ObjectType; + })(AST); + TypeScript.ObjectType = ObjectType; + + var ArrayType = (function (_super) { + __extends(ArrayType, _super); + function ArrayType(type) { + _super.call(this); + this.type = type; + type && (type.parent = this); + } + ArrayType.prototype.kind = function () { + return 124 /* ArrayType */; + }; + + ArrayType.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.type, ast.type, includingPosition); + }; + return ArrayType; + })(AST); + TypeScript.ArrayType = ArrayType; + + var TypeArgumentList = (function (_super) { + __extends(TypeArgumentList, _super); + function TypeArgumentList(typeArguments) { + _super.call(this); + this.typeArguments = typeArguments; + typeArguments && (typeArguments.parent = this); + } + TypeArgumentList.prototype.kind = function () { + return 228 /* TypeArgumentList */; + }; + return TypeArgumentList; + })(AST); + TypeScript.TypeArgumentList = TypeArgumentList; + + var GenericType = (function (_super) { + __extends(GenericType, _super); + function GenericType(name, typeArgumentList) { + _super.call(this); + this.name = name; + this.typeArgumentList = typeArgumentList; + name && (name.parent = this); + typeArgumentList && (typeArgumentList.parent = this); + } + GenericType.prototype.kind = function () { + return 126 /* GenericType */; + }; + + GenericType.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.typeArgumentList, ast.typeArgumentList, includingPosition); + }; + return GenericType; + })(AST); + TypeScript.GenericType = GenericType; + + var TypeQuery = (function (_super) { + __extends(TypeQuery, _super); + function TypeQuery(name) { + _super.call(this); + this.name = name; + name && (name.parent = this); + } + TypeQuery.prototype.kind = function () { + return 127 /* TypeQuery */; + }; + + TypeQuery.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition); + }; + return TypeQuery; + })(AST); + TypeScript.TypeQuery = TypeQuery; + + var Block = (function (_super) { + __extends(Block, _super); + function Block(statements, closeBraceLeadingComments, closeBraceToken) { + _super.call(this); + this.statements = statements; + this.closeBraceLeadingComments = closeBraceLeadingComments; + this.closeBraceToken = closeBraceToken; + statements && (statements.parent = this); + } + Block.prototype.kind = function () { + return 146 /* Block */; + }; + + Block.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statements, ast.statements, includingPosition); + }; + return Block; + })(AST); + TypeScript.Block = Block; + + var Parameter = (function (_super) { + __extends(Parameter, _super); + function Parameter(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + _super.call(this); + this.dotDotDotToken = dotDotDotToken; + this.modifiers = modifiers; + this.identifier = identifier; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + identifier && (identifier.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + equalsValueClause && (equalsValueClause.parent = this); + } + Parameter.prototype.kind = function () { + return 242 /* Parameter */; + }; + return Parameter; + })(AST); + TypeScript.Parameter = Parameter; + + var MemberAccessExpression = (function (_super) { + __extends(MemberAccessExpression, _super); + function MemberAccessExpression(expression, name) { + _super.call(this); + this.expression = expression; + this.name = name; + expression && (expression.parent = this); + name && (name.parent = this); + } + MemberAccessExpression.prototype.kind = function () { + return 212 /* MemberAccessExpression */; + }; + + MemberAccessExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.name, ast.name, includingPosition); + }; + + MemberAccessExpression.prototype.isExpression = function () { + return true; + }; + return MemberAccessExpression; + })(AST); + TypeScript.MemberAccessExpression = MemberAccessExpression; + + var PostfixUnaryExpression = (function (_super) { + __extends(PostfixUnaryExpression, _super); + function PostfixUnaryExpression(_nodeType, operand) { + _super.call(this); + this._nodeType = _nodeType; + this.operand = operand; + operand && (operand.parent = this); + } + PostfixUnaryExpression.prototype.kind = function () { + return this._nodeType; + }; + + PostfixUnaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand, ast.operand, includingPosition); + }; + + PostfixUnaryExpression.prototype.isExpression = function () { + return true; + }; + return PostfixUnaryExpression; + })(AST); + TypeScript.PostfixUnaryExpression = PostfixUnaryExpression; + + var ElementAccessExpression = (function (_super) { + __extends(ElementAccessExpression, _super); + function ElementAccessExpression(expression, argumentExpression) { + _super.call(this); + this.expression = expression; + this.argumentExpression = argumentExpression; + expression && (expression.parent = this); + argumentExpression && (argumentExpression.parent = this); + } + ElementAccessExpression.prototype.kind = function () { + return 221 /* ElementAccessExpression */; + }; + + ElementAccessExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentExpression, ast.argumentExpression, includingPosition); + }; + + ElementAccessExpression.prototype.isExpression = function () { + return true; + }; + return ElementAccessExpression; + })(AST); + TypeScript.ElementAccessExpression = ElementAccessExpression; + + var InvocationExpression = (function (_super) { + __extends(InvocationExpression, _super); + function InvocationExpression(expression, argumentList) { + _super.call(this); + this.expression = expression; + this.argumentList = argumentList; + expression && (expression.parent = this); + argumentList && (argumentList.parent = this); + } + InvocationExpression.prototype.kind = function () { + return 213 /* InvocationExpression */; + }; + + InvocationExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentList, ast.argumentList, includingPosition); + }; + + InvocationExpression.prototype.isExpression = function () { + return true; + }; + return InvocationExpression; + })(AST); + TypeScript.InvocationExpression = InvocationExpression; + + var ArgumentList = (function (_super) { + __extends(ArgumentList, _super); + function ArgumentList(typeArgumentList, _arguments, closeParenToken) { + _super.call(this); + this.typeArgumentList = typeArgumentList; + this.closeParenToken = closeParenToken; + this.arguments = _arguments; + + typeArgumentList && (typeArgumentList.parent = this); + _arguments && (_arguments.parent = this); + } + ArgumentList.prototype.kind = function () { + return 226 /* ArgumentList */; + }; + return ArgumentList; + })(AST); + TypeScript.ArgumentList = ArgumentList; + + var BinaryExpression = (function (_super) { + __extends(BinaryExpression, _super); + function BinaryExpression(_nodeType, left, right) { + _super.call(this); + this._nodeType = _nodeType; + this.left = left; + this.right = right; + left && (left.parent = this); + right && (right.parent = this); + } + BinaryExpression.prototype.kind = function () { + return this._nodeType; + }; + + BinaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.left, ast.left, includingPosition) && structuralEquals(this.right, ast.right, includingPosition); + }; + + BinaryExpression.prototype.isExpression = function () { + return true; + }; + return BinaryExpression; + })(AST); + TypeScript.BinaryExpression = BinaryExpression; + + var ConditionalExpression = (function (_super) { + __extends(ConditionalExpression, _super); + function ConditionalExpression(condition, whenTrue, whenFalse) { + _super.call(this); + this.condition = condition; + this.whenTrue = whenTrue; + this.whenFalse = whenFalse; + condition && (condition.parent = this); + whenTrue && (whenTrue.parent = this); + whenFalse && (whenFalse.parent = this); + } + ConditionalExpression.prototype.kind = function () { + return 186 /* ConditionalExpression */; + }; + + ConditionalExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.whenTrue, ast.whenTrue, includingPosition) && structuralEquals(this.whenFalse, ast.whenFalse, includingPosition); + }; + + ConditionalExpression.prototype.isExpression = function () { + return true; + }; + return ConditionalExpression; + })(AST); + TypeScript.ConditionalExpression = ConditionalExpression; + + var ConstructSignature = (function (_super) { + __extends(ConstructSignature, _super); + function ConstructSignature(callSignature) { + _super.call(this); + this.callSignature = callSignature; + callSignature && (callSignature.parent = this); + } + ConstructSignature.prototype.kind = function () { + return 143 /* ConstructSignature */; + }; + return ConstructSignature; + })(AST); + TypeScript.ConstructSignature = ConstructSignature; + + var MethodSignature = (function (_super) { + __extends(MethodSignature, _super); + function MethodSignature(propertyName, questionToken, callSignature) { + _super.call(this); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.callSignature = callSignature; + propertyName && (propertyName.parent = this); + callSignature && (callSignature.parent = this); + } + MethodSignature.prototype.kind = function () { + return 145 /* MethodSignature */; + }; + return MethodSignature; + })(AST); + TypeScript.MethodSignature = MethodSignature; + + var IndexSignature = (function (_super) { + __extends(IndexSignature, _super); + function IndexSignature(parameter, typeAnnotation) { + _super.call(this); + this.parameter = parameter; + this.typeAnnotation = typeAnnotation; + parameter && (parameter.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + } + IndexSignature.prototype.kind = function () { + return 144 /* IndexSignature */; + }; + return IndexSignature; + })(AST); + TypeScript.IndexSignature = IndexSignature; + + var PropertySignature = (function (_super) { + __extends(PropertySignature, _super); + function PropertySignature(propertyName, questionToken, typeAnnotation) { + _super.call(this); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + propertyName && (propertyName.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + } + PropertySignature.prototype.kind = function () { + return 141 /* PropertySignature */; + }; + return PropertySignature; + })(AST); + TypeScript.PropertySignature = PropertySignature; + + var CallSignature = (function (_super) { + __extends(CallSignature, _super); + function CallSignature(typeParameterList, parameterList, typeAnnotation) { + _super.call(this); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + typeParameterList && (typeParameterList.parent = this); + parameterList && (parameterList.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + } + CallSignature.prototype.kind = function () { + return 142 /* CallSignature */; + }; + return CallSignature; + })(AST); + TypeScript.CallSignature = CallSignature; + + var TypeParameter = (function (_super) { + __extends(TypeParameter, _super); + function TypeParameter(identifier, constraint) { + _super.call(this); + this.identifier = identifier; + this.constraint = constraint; + identifier && (identifier.parent = this); + constraint && (constraint.parent = this); + } + TypeParameter.prototype.kind = function () { + return 238 /* TypeParameter */; + }; + + TypeParameter.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.constraint, ast.constraint, includingPosition); + }; + return TypeParameter; + })(AST); + TypeScript.TypeParameter = TypeParameter; + + var Constraint = (function (_super) { + __extends(Constraint, _super); + function Constraint(type) { + _super.call(this); + this.type = type; + type && (type.parent = this); + } + Constraint.prototype.kind = function () { + return 239 /* Constraint */; + }; + return Constraint; + })(AST); + TypeScript.Constraint = Constraint; + + var ElseClause = (function (_super) { + __extends(ElseClause, _super); + function ElseClause(statement) { + _super.call(this); + this.statement = statement; + statement && (statement.parent = this); + } + ElseClause.prototype.kind = function () { + return 235 /* ElseClause */; + }; + + ElseClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return ElseClause; + })(AST); + TypeScript.ElseClause = ElseClause; + + var IfStatement = (function (_super) { + __extends(IfStatement, _super); + function IfStatement(condition, statement, elseClause) { + _super.call(this); + this.condition = condition; + this.statement = statement; + this.elseClause = elseClause; + condition && (condition.parent = this); + statement && (statement.parent = this); + elseClause && (elseClause.parent = this); + } + IfStatement.prototype.kind = function () { + return 147 /* IfStatement */; + }; + + IfStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition) && structuralEquals(this.elseClause, ast.elseClause, includingPosition); + }; + return IfStatement; + })(AST); + TypeScript.IfStatement = IfStatement; + + var ExpressionStatement = (function (_super) { + __extends(ExpressionStatement, _super); + function ExpressionStatement(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + ExpressionStatement.prototype.kind = function () { + return 149 /* ExpressionStatement */; + }; + + ExpressionStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ExpressionStatement; + })(AST); + TypeScript.ExpressionStatement = ExpressionStatement; + + var ConstructorDeclaration = (function (_super) { + __extends(ConstructorDeclaration, _super); + function ConstructorDeclaration(callSignature, block) { + _super.call(this); + this.callSignature = callSignature; + this.block = block; + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + ConstructorDeclaration.prototype.kind = function () { + return 137 /* ConstructorDeclaration */; + }; + return ConstructorDeclaration; + })(AST); + TypeScript.ConstructorDeclaration = ConstructorDeclaration; + + var MemberFunctionDeclaration = (function (_super) { + __extends(MemberFunctionDeclaration, _super); + function MemberFunctionDeclaration(modifiers, propertyName, callSignature, block) { + _super.call(this); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + propertyName && (propertyName.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + MemberFunctionDeclaration.prototype.kind = function () { + return 135 /* MemberFunctionDeclaration */; + }; + return MemberFunctionDeclaration; + })(AST); + TypeScript.MemberFunctionDeclaration = MemberFunctionDeclaration; + + var GetAccessor = (function (_super) { + __extends(GetAccessor, _super); + function GetAccessor(modifiers, propertyName, parameterList, typeAnnotation, block) { + _super.call(this); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + this.block = block; + propertyName && (propertyName.parent = this); + parameterList && (parameterList.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + block && (block.parent = this); + } + GetAccessor.prototype.kind = function () { + return 139 /* GetAccessor */; + }; + return GetAccessor; + })(AST); + TypeScript.GetAccessor = GetAccessor; + + var SetAccessor = (function (_super) { + __extends(SetAccessor, _super); + function SetAccessor(modifiers, propertyName, parameterList, block) { + _super.call(this); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.block = block; + propertyName && (propertyName.parent = this); + parameterList && (parameterList.parent = this); + block && (block.parent = this); + } + SetAccessor.prototype.kind = function () { + return 140 /* SetAccessor */; + }; + return SetAccessor; + })(AST); + TypeScript.SetAccessor = SetAccessor; + + var MemberVariableDeclaration = (function (_super) { + __extends(MemberVariableDeclaration, _super); + function MemberVariableDeclaration(modifiers, variableDeclarator) { + _super.call(this); + this.modifiers = modifiers; + this.variableDeclarator = variableDeclarator; + variableDeclarator && (variableDeclarator.parent = this); + } + MemberVariableDeclaration.prototype.kind = function () { + return 136 /* MemberVariableDeclaration */; + }; + return MemberVariableDeclaration; + })(AST); + TypeScript.MemberVariableDeclaration = MemberVariableDeclaration; + + var IndexMemberDeclaration = (function (_super) { + __extends(IndexMemberDeclaration, _super); + function IndexMemberDeclaration(indexSignature) { + _super.call(this); + this.indexSignature = indexSignature; + indexSignature && (indexSignature.parent = this); + } + IndexMemberDeclaration.prototype.kind = function () { + return 138 /* IndexMemberDeclaration */; + }; + return IndexMemberDeclaration; + })(AST); + TypeScript.IndexMemberDeclaration = IndexMemberDeclaration; + + var ThrowStatement = (function (_super) { + __extends(ThrowStatement, _super); + function ThrowStatement(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + ThrowStatement.prototype.kind = function () { + return 157 /* ThrowStatement */; + }; + + ThrowStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ThrowStatement; + })(AST); + TypeScript.ThrowStatement = ThrowStatement; + + var ReturnStatement = (function (_super) { + __extends(ReturnStatement, _super); + function ReturnStatement(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + ReturnStatement.prototype.kind = function () { + return 150 /* ReturnStatement */; + }; + + ReturnStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ReturnStatement; + })(AST); + TypeScript.ReturnStatement = ReturnStatement; + + var ObjectCreationExpression = (function (_super) { + __extends(ObjectCreationExpression, _super); + function ObjectCreationExpression(expression, argumentList) { + _super.call(this); + this.expression = expression; + this.argumentList = argumentList; + expression && (expression.parent = this); + argumentList && (argumentList.parent = this); + } + ObjectCreationExpression.prototype.kind = function () { + return 216 /* ObjectCreationExpression */; + }; + + ObjectCreationExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentList, ast.argumentList, includingPosition); + }; + + ObjectCreationExpression.prototype.isExpression = function () { + return true; + }; + return ObjectCreationExpression; + })(AST); + TypeScript.ObjectCreationExpression = ObjectCreationExpression; + + var SwitchStatement = (function (_super) { + __extends(SwitchStatement, _super); + function SwitchStatement(expression, closeParenToken, switchClauses) { + _super.call(this); + this.expression = expression; + this.closeParenToken = closeParenToken; + this.switchClauses = switchClauses; + expression && (expression.parent = this); + switchClauses && (switchClauses.parent = this); + } + SwitchStatement.prototype.kind = function () { + return 151 /* SwitchStatement */; + }; + + SwitchStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.switchClauses, ast.switchClauses, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return SwitchStatement; + })(AST); + TypeScript.SwitchStatement = SwitchStatement; + + var CaseSwitchClause = (function (_super) { + __extends(CaseSwitchClause, _super); + function CaseSwitchClause(expression, statements) { + _super.call(this); + this.expression = expression; + this.statements = statements; + expression && (expression.parent = this); + statements && (statements.parent = this); + } + CaseSwitchClause.prototype.kind = function () { + return 233 /* CaseSwitchClause */; + }; + + CaseSwitchClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.statements, ast.statements, includingPosition); + }; + return CaseSwitchClause; + })(AST); + TypeScript.CaseSwitchClause = CaseSwitchClause; + + var DefaultSwitchClause = (function (_super) { + __extends(DefaultSwitchClause, _super); + function DefaultSwitchClause(statements) { + _super.call(this); + this.statements = statements; + statements && (statements.parent = this); + } + DefaultSwitchClause.prototype.kind = function () { + return 234 /* DefaultSwitchClause */; + }; + + DefaultSwitchClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statements, ast.statements, includingPosition); + }; + return DefaultSwitchClause; + })(AST); + TypeScript.DefaultSwitchClause = DefaultSwitchClause; + + var BreakStatement = (function (_super) { + __extends(BreakStatement, _super); + function BreakStatement(identifier) { + _super.call(this); + this.identifier = identifier; + } + BreakStatement.prototype.kind = function () { + return 152 /* BreakStatement */; + }; + + BreakStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return BreakStatement; + })(AST); + TypeScript.BreakStatement = BreakStatement; + + var ContinueStatement = (function (_super) { + __extends(ContinueStatement, _super); + function ContinueStatement(identifier) { + _super.call(this); + this.identifier = identifier; + } + ContinueStatement.prototype.kind = function () { + return 153 /* ContinueStatement */; + }; + + ContinueStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return ContinueStatement; + })(AST); + TypeScript.ContinueStatement = ContinueStatement; + + var ForStatement = (function (_super) { + __extends(ForStatement, _super); + function ForStatement(variableDeclaration, initializer, condition, incrementor, statement) { + _super.call(this); + this.variableDeclaration = variableDeclaration; + this.initializer = initializer; + this.condition = condition; + this.incrementor = incrementor; + this.statement = statement; + variableDeclaration && (variableDeclaration.parent = this); + initializer && (initializer.parent = this); + condition && (condition.parent = this); + incrementor && (incrementor.parent = this); + statement && (statement.parent = this); + } + ForStatement.prototype.kind = function () { + return 154 /* ForStatement */; + }; + + ForStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.initializer, ast.initializer, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.incrementor, ast.incrementor, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return ForStatement; + })(AST); + TypeScript.ForStatement = ForStatement; + + var ForInStatement = (function (_super) { + __extends(ForInStatement, _super); + function ForInStatement(variableDeclaration, left, expression, statement) { + _super.call(this); + this.variableDeclaration = variableDeclaration; + this.left = left; + this.expression = expression; + this.statement = statement; + variableDeclaration && (variableDeclaration.parent = this); + left && (left.parent = this); + expression && (expression.parent = this); + statement && (statement.parent = this); + } + ForInStatement.prototype.kind = function () { + return 155 /* ForInStatement */; + }; + + ForInStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.variableDeclaration, ast.variableDeclaration, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return ForInStatement; + })(AST); + TypeScript.ForInStatement = ForInStatement; + + var WhileStatement = (function (_super) { + __extends(WhileStatement, _super); + function WhileStatement(condition, statement) { + _super.call(this); + this.condition = condition; + this.statement = statement; + condition && (condition.parent = this); + statement && (statement.parent = this); + } + WhileStatement.prototype.kind = function () { + return 158 /* WhileStatement */; + }; + + WhileStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return WhileStatement; + })(AST); + TypeScript.WhileStatement = WhileStatement; + + var WithStatement = (function (_super) { + __extends(WithStatement, _super); + function WithStatement(condition, statement) { + _super.call(this); + this.condition = condition; + this.statement = statement; + condition && (condition.parent = this); + statement && (statement.parent = this); + } + WithStatement.prototype.kind = function () { + return 163 /* WithStatement */; + }; + + WithStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return WithStatement; + })(AST); + TypeScript.WithStatement = WithStatement; + + var EnumDeclaration = (function (_super) { + __extends(EnumDeclaration, _super); + function EnumDeclaration(modifiers, identifier, enumElements) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.enumElements = enumElements; + identifier && (identifier.parent = this); + enumElements && (enumElements.parent = this); + } + EnumDeclaration.prototype.kind = function () { + return 132 /* EnumDeclaration */; + }; + return EnumDeclaration; + })(AST); + TypeScript.EnumDeclaration = EnumDeclaration; + + var EnumElement = (function (_super) { + __extends(EnumElement, _super); + function EnumElement(propertyName, equalsValueClause) { + _super.call(this); + this.propertyName = propertyName; + this.equalsValueClause = equalsValueClause; + propertyName && (propertyName.parent = this); + equalsValueClause && (equalsValueClause.parent = this); + } + EnumElement.prototype.kind = function () { + return 243 /* EnumElement */; + }; + return EnumElement; + })(AST); + TypeScript.EnumElement = EnumElement; + + var CastExpression = (function (_super) { + __extends(CastExpression, _super); + function CastExpression(type, expression) { + _super.call(this); + this.type = type; + this.expression = expression; + type && (type.parent = this); + expression && (expression.parent = this); + } + CastExpression.prototype.kind = function () { + return 220 /* CastExpression */; + }; + + CastExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.type, ast.type, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + CastExpression.prototype.isExpression = function () { + return true; + }; + return CastExpression; + })(AST); + TypeScript.CastExpression = CastExpression; + + var ObjectLiteralExpression = (function (_super) { + __extends(ObjectLiteralExpression, _super); + function ObjectLiteralExpression(propertyAssignments) { + _super.call(this); + this.propertyAssignments = propertyAssignments; + propertyAssignments && (propertyAssignments.parent = this); + } + ObjectLiteralExpression.prototype.kind = function () { + return 215 /* ObjectLiteralExpression */; + }; + + ObjectLiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.propertyAssignments, ast.propertyAssignments, includingPosition); + }; + + ObjectLiteralExpression.prototype.isExpression = function () { + return true; + }; + return ObjectLiteralExpression; + })(AST); + TypeScript.ObjectLiteralExpression = ObjectLiteralExpression; + + var SimplePropertyAssignment = (function (_super) { + __extends(SimplePropertyAssignment, _super); + function SimplePropertyAssignment(propertyName, expression) { + _super.call(this); + this.propertyName = propertyName; + this.expression = expression; + propertyName && (propertyName.parent = this); + expression && (expression.parent = this); + } + SimplePropertyAssignment.prototype.kind = function () { + return 240 /* SimplePropertyAssignment */; + }; + return SimplePropertyAssignment; + })(AST); + TypeScript.SimplePropertyAssignment = SimplePropertyAssignment; + + var FunctionPropertyAssignment = (function (_super) { + __extends(FunctionPropertyAssignment, _super); + function FunctionPropertyAssignment(propertyName, callSignature, block) { + _super.call(this); + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + propertyName && (propertyName.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + FunctionPropertyAssignment.prototype.kind = function () { + return 241 /* FunctionPropertyAssignment */; + }; + return FunctionPropertyAssignment; + })(AST); + TypeScript.FunctionPropertyAssignment = FunctionPropertyAssignment; + + var FunctionExpression = (function (_super) { + __extends(FunctionExpression, _super); + function FunctionExpression(identifier, callSignature, block) { + _super.call(this); + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + identifier && (identifier.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + FunctionExpression.prototype.kind = function () { + return 222 /* FunctionExpression */; + }; + + FunctionExpression.prototype.isExpression = function () { + return true; + }; + return FunctionExpression; + })(AST); + TypeScript.FunctionExpression = FunctionExpression; + + var EmptyStatement = (function (_super) { + __extends(EmptyStatement, _super); + function EmptyStatement() { + _super.apply(this, arguments); + } + EmptyStatement.prototype.kind = function () { + return 156 /* EmptyStatement */; + }; + + EmptyStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return EmptyStatement; + })(AST); + TypeScript.EmptyStatement = EmptyStatement; + + var TryStatement = (function (_super) { + __extends(TryStatement, _super); + function TryStatement(block, catchClause, finallyClause) { + _super.call(this); + this.block = block; + this.catchClause = catchClause; + this.finallyClause = finallyClause; + block && (block.parent = this); + catchClause && (catchClause.parent = this); + finallyClause && (finallyClause.parent = this); + } + TryStatement.prototype.kind = function () { + return 159 /* TryStatement */; + }; + + TryStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.block, ast.block, includingPosition) && structuralEquals(this.catchClause, ast.catchClause, includingPosition) && structuralEquals(this.finallyClause, ast.finallyClause, includingPosition); + }; + return TryStatement; + })(AST); + TypeScript.TryStatement = TryStatement; + + var CatchClause = (function (_super) { + __extends(CatchClause, _super); + function CatchClause(identifier, typeAnnotation, block) { + _super.call(this); + this.identifier = identifier; + this.typeAnnotation = typeAnnotation; + this.block = block; + identifier && (identifier.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + block && (block.parent = this); + } + CatchClause.prototype.kind = function () { + return 236 /* CatchClause */; + }; + + CatchClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.typeAnnotation, ast.typeAnnotation, includingPosition) && structuralEquals(this.block, ast.block, includingPosition); + }; + return CatchClause; + })(AST); + TypeScript.CatchClause = CatchClause; + + var FinallyClause = (function (_super) { + __extends(FinallyClause, _super); + function FinallyClause(block) { + _super.call(this); + this.block = block; + block && (block.parent = this); + } + FinallyClause.prototype.kind = function () { + return 237 /* FinallyClause */; + }; + + FinallyClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.block, ast.block, includingPosition); + }; + return FinallyClause; + })(AST); + TypeScript.FinallyClause = FinallyClause; + + var LabeledStatement = (function (_super) { + __extends(LabeledStatement, _super); + function LabeledStatement(identifier, statement) { + _super.call(this); + this.identifier = identifier; + this.statement = statement; + identifier && (identifier.parent = this); + statement && (statement.parent = this); + } + LabeledStatement.prototype.kind = function () { + return 160 /* LabeledStatement */; + }; + + LabeledStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return LabeledStatement; + })(AST); + TypeScript.LabeledStatement = LabeledStatement; + + var DoStatement = (function (_super) { + __extends(DoStatement, _super); + function DoStatement(statement, whileKeyword, condition) { + _super.call(this); + this.statement = statement; + this.whileKeyword = whileKeyword; + this.condition = condition; + statement && (statement.parent = this); + condition && (condition.parent = this); + } + DoStatement.prototype.kind = function () { + return 161 /* DoStatement */; + }; + + DoStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition); + }; + return DoStatement; + })(AST); + TypeScript.DoStatement = DoStatement; + + var TypeOfExpression = (function (_super) { + __extends(TypeOfExpression, _super); + function TypeOfExpression(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + TypeOfExpression.prototype.kind = function () { + return 171 /* TypeOfExpression */; + }; + + TypeOfExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + TypeOfExpression.prototype.isExpression = function () { + return true; + }; + return TypeOfExpression; + })(AST); + TypeScript.TypeOfExpression = TypeOfExpression; + + var DeleteExpression = (function (_super) { + __extends(DeleteExpression, _super); + function DeleteExpression(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + DeleteExpression.prototype.kind = function () { + return 170 /* DeleteExpression */; + }; + + DeleteExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + DeleteExpression.prototype.isExpression = function () { + return true; + }; + return DeleteExpression; + })(AST); + TypeScript.DeleteExpression = DeleteExpression; + + var VoidExpression = (function (_super) { + __extends(VoidExpression, _super); + function VoidExpression(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + VoidExpression.prototype.kind = function () { + return 172 /* VoidExpression */; + }; + + VoidExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + VoidExpression.prototype.isExpression = function () { + return true; + }; + return VoidExpression; + })(AST); + TypeScript.VoidExpression = VoidExpression; + + var DebuggerStatement = (function (_super) { + __extends(DebuggerStatement, _super); + function DebuggerStatement() { + _super.apply(this, arguments); + } + DebuggerStatement.prototype.kind = function () { + return 162 /* DebuggerStatement */; + }; + return DebuggerStatement; + })(AST); + TypeScript.DebuggerStatement = DebuggerStatement; + + var Comment = (function () { + function Comment(_trivia, endsLine, _start, _end) { + this._trivia = _trivia; + this.endsLine = endsLine; + this._start = _start; + this._end = _end; + } + Comment.prototype.start = function () { + return this._start; + }; + + Comment.prototype.end = function () { + return this._end; + }; + + Comment.prototype.fullText = function () { + return this._trivia.fullText(); + }; + + Comment.prototype.kind = function () { + return this._trivia.kind(); + }; + + Comment.prototype.structuralEquals = function (ast, includingPosition) { + if (includingPosition) { + if (this.start() !== ast.start() || this.end() !== ast.end()) { + return false; + } + } + + return this._trivia.fullText() === ast._trivia.fullText() && this.endsLine === ast.endsLine; + }; + return Comment; + })(); + TypeScript.Comment = Comment; +})(TypeScript || (TypeScript = {})); diff --git a/_infrastructure/tests/typescript/1.0.2.1-225bad/lib.d.ts b/_infrastructure/tests/typescript/1.0.2.1-225bad/lib.d.ts new file mode 100644 index 0000000000..d3e57e7e63 --- /dev/null +++ b/_infrastructure/tests/typescript/1.0.2.1-225bad/lib.d.ts @@ -0,0 +1,14958 @@ +/* ***************************************************************************** +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): boolean; + +/** + * Determines whether a supplied number is finite. + * @param number Any numeric value. + */ +declare function isFinite(number: number): boolean; + +/** + * 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?: boolean; + enumerable?: boolean; + value?: any; + writable?: boolean; + get? (): any; + set? (v: any): void; +} + +interface PropertyDescriptorMap { + [s: string]: PropertyDescriptor; +} + +interface Object { + /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ + constructor: Function; + + /** 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): boolean; + + /** + * 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): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: string): boolean; +} + +/** + * 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): boolean; + + /** + * 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): boolean; + + /** + * Returns a value that indicates whether new properties can be added to an object. + * @param o Object to test. + */ + isExtensible(o: any): boolean; + + /** + * 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 number indicating the beginning of the substring. + * @param end Zero-based index number 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; + + [index: 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): boolean; + prototype: Boolean; +} + +interface Number { + /** + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. + */ + toString(radix?: number): string; + + /** + * Returns a string representing a number in fixed-point notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toFixed(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented in exponential notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toExponential(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. + * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. + */ + 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 number 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 number 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 number. + * @param x The value to be rounded to the nearest number. + */ + 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; + /** Returns a value as a string value appropriate to the host environment's current locale. */ + 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): number; + /** + * Sets the milliseconds value in the Date object using local time. + * @param ms A numeric value equal to the millisecond value. + */ + setMilliseconds(ms: number): number; + /** + * 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): number; + + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** + * 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): number; + /** 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; +} + +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 number between 0 and 11 (January to December). + * @param date The date as an number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. + * @param ms An number 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(separator?: 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[]) => boolean, thisArg?: any): boolean; + some(callbackfn: (value: string, index: number, array: string[]) => boolean, thisArg?: any): boolean; + 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[]) => boolean, 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): boolean; + + /** 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: boolean; + + /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ + ignoreCase: boolean; + + /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ + multiline: boolean; + + 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 { + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: U[]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Removes the last element from an array and returns it. + */ + pop(): T; + /** + * Appends new elements to an array, and returns the new length of the array. + * @param items New elements of the Array. + */ + push(...items: T[]): number; + /** + * Reverses the elements in an Array. + */ + reverse(): T[]; + /** + * Removes the first element from an array and returns it. + */ + shift(): T; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: T, b: T) => number): T[]; + + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + */ + splice(start: number): T[]; + + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param items Elements to insert into the array in place of the deleted elements. + */ + splice(start: number, deleteCount: number, ...items: T[]): T[]; + + /** + * Inserts new elements at the start of an array. + * @param items Elements to insert at the start of the Array. + */ + unshift(...items: T[]): number; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; + + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + /** + * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. + */ + length: number; + + [n: number]: T; +} +declare var Array: { + new (arrayLength?: number): any[]; + new (arrayLength: number): T[]; + new (...items: T[]): T[]; + (arrayLength?: number): any[]; + (arrayLength: number): T[]; + (...items: T[]): T[]; + isArray(arg: any): boolean; + prototype: Array; +} + + +///////////////////////////// +/// IE10 ECMAScript Extensions +///////////////////////////// + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + /** + * Read-only. The length of the ArrayBuffer (in bytes). + */ + byteLength: number; +} + +declare var ArrayBuffer: { + prototype: ArrayBuffer; + new (byteLength: number): ArrayBuffer; +} + +interface ArrayBufferView { + buffer: ArrayBuffer; + byteOffset: number; + byteLength: number; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Int8Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Int8Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Uint8Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Uint8Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * A typed array of 16-bit integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Int16Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Int16Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Uint16Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Uint16Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * A typed array of 32-bit integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Int32Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Int32Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Uint32Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Int8Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Float32Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Float32Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Float32Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. + */ +interface Float64Array extends ArrayBufferView { + /** + * The size in bytes of each element in the array. + */ + BYTES_PER_ELEMENT: number; + + /** + * The length of the array. + */ + length: number; + [index: number]: number; + + /** + * Gets the element at the specified index. + * @param index The index at which to get the element of the array. + */ + get(index: number): number; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Float64Array, offset?: number): void; + + /** + * Sets a value or an array of values. + * @param A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: number[], offset?: number): void; + + /** + * Gets a new Float64Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + 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; +} + +/** + * You can use a DataView object to read and write the different kinds of binary data to any location in the ArrayBuffer. + */ +interface DataView extends ArrayBufferView { + /** + * Gets the Int8 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt8(byteOffset: number): number; + + /** + * Gets the Uint8 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint8(byteOffset: number): number; + + /** + * Gets the Int16 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt16(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint16 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint16(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Int32 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint32 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Float32 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Float64 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat64(byteOffset: number, littleEndian?: boolean): number; + + /** + * Stores an Int8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setInt8(byteOffset: number, value: number): void; + + /** + * Stores an Uint8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setUint8(byteOffset: number, value: number): void; + + /** + * Stores an Int16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. + */ + setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. + */ + setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. + */ + setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. + */ + setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Float32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. + */ + setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Float64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. + */ + setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; +} +declare var DataView: { + prototype: DataView; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): DataView; +} + +///////////////////////////// +/// IE11 ECMAScript Extensions +///////////////////////////// + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; + get(key: K): V; + has(key: K): boolean; + set(key: K, value: V): Map; + size: number; +} +declare var Map: { + new (): Map; +} + +interface WeakMap { + clear(): void; + delete(key: K): boolean; + get(key: K): V; + has(key: K): boolean; + set(key: K, value: V): WeakMap; +} +declare var WeakMap: { + new (): WeakMap; +} + +interface Set { + add(value: T): Set; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + size: number; +} +declare var Set: { + new (): Set; +} + +declare module Intl { + + interface CollatorOptions { + usage?: string; + localeMatcher?: string; + numeric?: boolean; + caseFirst?: string; + sensitivity?: string; + ignorePunctuation?: boolean; + } + + interface ResolvedCollatorOptions { + locale: string; + usage: string; + sensitivity: string; + ignorePunctuation: boolean; + collation: string; + caseFirst: string; + numeric: boolean; + } + + interface Collator { + compare(x: string, y: string): number; + resolvedOptions(): ResolvedCollatorOptions; + } + var Collator: { + new (locales?: string[], options?: CollatorOptions): Collator; + new (locale?: string, options?: CollatorOptions): Collator; + (locales?: string[], options?: CollatorOptions): Collator; + (locale?: string, options?: CollatorOptions): Collator; + supportedLocalesOf(locales: string[], options?: CollatorOptions): string[]; + supportedLocalesOf(locale: string, options?: CollatorOptions): string[]; + } + + interface NumberFormatOptions { + localeMatcher?: string; + style?: string; + currency?: string; + currencyDisplay?: string; + useGrouping?: boolean; + } + + interface ResolvedNumberFormatOptions { + locale: string; + numberingSystem: string; + style: string; + currency?: string; + currencyDisplay?: string; + minimumintegerDigits: number; + minimumFractionDigits: number; + maximumFractionDigits: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + useGrouping: boolean; + } + + interface NumberFormat { + format(value: number): string; + resolvedOptions(): ResolvedNumberFormatOptions; + } + var NumberFormat: { + new (locales?: string[], options?: NumberFormatOptions): Collator; + new (locale?: string, options?: NumberFormatOptions): Collator; + (locales?: string[], options?: NumberFormatOptions): Collator; + (locale?: string, options?: NumberFormatOptions): Collator; + supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[]; + supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[]; + } + + interface DateTimeFormatOptions { + localeMatcher?: string; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + formatMatcher?: string; + hour12: boolean; + } + + interface ResolvedDateTimeFormatOptions { + locale: string; + calendar: string; + numberingSystem: string; + timeZone: string; + hour12?: boolean; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + } + + interface DateTimeFormat { + format(date: number): string; + resolvedOptions(): ResolvedDateTimeFormatOptions; + } + var DateTimeFormat: { + new (locales?: string[], options?: DateTimeFormatOptions): Collator; + new (locale?: string, options?: DateTimeFormatOptions): Collator; + (locales?: string[], options?: DateTimeFormatOptions): Collator; + (locale?: string, options?: DateTimeFormatOptions): Collator; + supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[]; + supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[]; + } +} + +interface String { + localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number; + localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number; +} + +interface Number { + toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string; + toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string; +} + +interface Date { + toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string; + toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string; +} + + +///////////////////////////// +/// IE9 DOM APIs +///////////////////////////// + +interface PositionOptions { + enableHighAccuracy?: boolean; + timeout?: number; + maximumAge?: number; +} + +interface NavigatorID { + appVersion: string; + appName: string; + userAgent: string; + platform: string; +} + +interface HTMLTableElement extends HTMLElement, MSDataBindingTableExtensions, MSDataBindingExtensions, DOML2DeprecatedBackgroundStyle, DOML2DeprecatedBackgroundColorStyle { + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Sets or retrieves the color for one of the two colors used to draw the 3-D border of the object. + */ + borderColorLight: any; + /** + * Sets or retrieves the amount of space between cells in a table. + */ + cellSpacing: string; + /** + * Retrieves the tFoot object of the table. + */ + tFoot: HTMLTableSectionElement; + /** + * Sets or retrieves the way the border frame around the table is displayed. + */ + frame: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: HTMLCollection; + /** + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ + rules: string; + /** + * Sets or retrieves the number of columns in the table. + */ + cols: number; + /** + * Sets or retrieves a description and/or structure of the object. + */ + summary: string; + /** + * Retrieves the caption object of a table. + */ + caption: HTMLTableCaptionElement; + /** + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ + tBodies: HTMLCollection; + /** + * Retrieves the tHead object of the table. + */ + tHead: HTMLTableSectionElement; + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + /** + * Retrieves a collection of all cells in the table row or in the entire table. + */ + cells: HTMLCollection; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ + cellPadding: string; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + border: string; + /** + * Sets or retrieves the color for one of the two colors used to draw the 3-D border of the object. + */ + borderColorDark: any; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index?: number): void; + /** + * Creates an empty tBody element in the table. + */ + createTBody(): HTMLElement; + /** + * Deletes the caption element and its contents from the table. + */ + deleteCaption(): void; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLElement; + /** + * Deletes the tFoot element and its contents from the table. + */ + deleteTFoot(): void; + /** + * Returns the tHead element object if successful, or null otherwise. + */ + createTHead(): HTMLElement; + /** + * Deletes the tHead element and its contents from the table. + */ + deleteTHead(): void; + /** + * Creates an empty caption element in the table. + */ + createCaption(): HTMLElement; + /** + * Moves a table row to a new position. + * @param indexFrom Number that specifies the index in the rows collection of the table row that is moved. + * @param indexTo Number that specifies where the row is moved within the rows collection. + */ + moveRow(indexFrom?: number, indexTo?: number): Object; + /** + * Creates an empty tFoot element in the table. + */ + createTFoot(): HTMLElement; +} +declare var HTMLTableElement: { + prototype: HTMLTableElement; + new (): HTMLTableElement; +} + +interface TreeWalker { + whatToShow: number; + filter: NodeFilter; + root: Node; + currentNode: Node; + expandEntityReferences: boolean; + previousSibling(): Node; + lastChild(): Node; + nextSibling(): Node; + nextNode(): Node; + parentNode(): Node; + firstChild(): Node; + previousNode(): Node; +} +declare var TreeWalker: { + prototype: TreeWalker; + new (): TreeWalker; +} + +interface GetSVGDocument { + getSVGDocument(): Document; +} + +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; + getEntriesByType(entryType: string): any; + toJSON(): any; + getMeasures(measureName?: string): any; + clearMarks(markName?: string): void; + getMarks(markName?: string): any; + clearResourceTimings(): void; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + getEntriesByName(name: string, entryType?: string): any; + getEntries(): any; + clearMeasures(measureName?: string): void; + setResourceTimingBufferSize(maxSize: number): void; +} +declare var Performance: { + prototype: Performance; + new (): Performance; +} + +interface MSDataBindingTableExtensions { + dataPageSize: number; + nextPage(): void; + firstPage(): void; + refresh(): void; + previousPage(): void; + lastPage(): void; +} + +interface CompositionEvent extends UIEvent { + data: string; + locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} +declare var CompositionEvent: { + prototype: CompositionEvent; + new (): CompositionEvent; +} + +interface WindowTimers { + clearTimeout(handle: number): void; + setTimeout(handler: any, timeout?: any, ...args: any[]): number; + clearInterval(handle: number): void; + setInterval(handler: any, timeout?: any, ...args: any[]): number; +} + +interface SVGMarkerElement extends SVGElement, SVGStylable, SVGLangSpace, SVGFitToViewBox, SVGExternalResourcesRequired { + 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 CSSStyleDeclaration { + backgroundAttachment: string; + visibility: string; + textAlignLast: string; + borderRightStyle: string; + counterIncrement: string; + orphans: string; + cssText: string; + borderStyle: string; + pointerEvents: string; + borderTopColor: string; + markerEnd: string; + textIndent: string; + listStyleImage: string; + cursor: string; + listStylePosition: string; + wordWrap: string; + borderTopStyle: string; + alignmentBaseline: string; + opacity: string; + direction: string; + strokeMiterlimit: string; + maxWidth: string; + color: string; + clip: string; + borderRightWidth: string; + verticalAlign: string; + overflow: string; + mask: string; + borderLeftStyle: string; + emptyCells: string; + stopOpacity: string; + paddingRight: string; + parentRule: CSSRule; + background: string; + boxSizing: string; + textJustify: string; + height: string; + paddingTop: string; + length: number; + right: string; + baselineShift: string; + borderLeft: string; + widows: string; + lineHeight: string; + left: string; + textUnderlinePosition: string; + glyphOrientationHorizontal: string; + display: string; + textAnchor: string; + cssFloat: string; + strokeDasharray: string; + rubyAlign: string; + fontSizeAdjust: string; + borderLeftColor: string; + backgroundImage: string; + listStyleType: string; + strokeWidth: string; + textOverflow: string; + fillRule: string; + borderBottomColor: string; + zIndex: string; + position: string; + listStyle: string; + msTransformOrigin: string; + dominantBaseline: string; + overflowY: string; + fill: string; + captionSide: string; + borderCollapse: string; + boxShadow: string; + quotes: string; + tableLayout: string; + unicodeBidi: string; + borderBottomWidth: string; + backgroundSize: string; + textDecoration: string; + strokeDashoffset: string; + fontSize: string; + border: string; + pageBreakBefore: string; + borderTopRightRadius: string; + msTransform: string; + borderBottomLeftRadius: string; + textTransform: string; + rubyPosition: string; + strokeLinejoin: string; + clipPath: string; + borderRightColor: string; + fontFamily: string; + clear: string; + content: string; + backgroundClip: string; + marginBottom: string; + counterReset: string; + outlineWidth: string; + marginRight: string; + paddingLeft: string; + borderBottom: string; + wordBreak: string; + marginTop: string; + top: string; + fontWeight: string; + borderRight: string; + width: string; + kerning: string; + pageBreakAfter: string; + borderBottomStyle: string; + fontStretch: string; + padding: string; + strokeOpacity: string; + markerStart: string; + bottom: string; + borderLeftWidth: string; + clipRule: string; + backgroundPosition: string; + backgroundColor: string; + pageBreakInside: string; + backgroundOrigin: string; + strokeLinecap: string; + borderTopWidth: string; + outlineStyle: string; + borderTop: string; + outlineColor: string; + paddingBottom: string; + marginLeft: string; + font: string; + outline: string; + wordSpacing: string; + maxHeight: string; + fillOpacity: string; + letterSpacing: string; + borderSpacing: string; + backgroundRepeat: string; + borderRadius: string; + borderWidth: string; + borderBottomRightRadius: string; + whiteSpace: string; + fontStyle: string; + minWidth: string; + stopColor: string; + borderTopLeftRadius: string; + borderColor: string; + marker: string; + glyphOrientationVertical: string; + markerMid: string; + fontVariant: string; + minHeight: string; + stroke: string; + rubyOverhang: string; + overflowX: string; + textAlign: string; + margin: string; + 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, SVGExternalResourcesRequired { +} +declare var SVGGElement: { + prototype: SVGGElement; + new (): SVGGElement; +} + +interface MSStyleCSSProperties extends MSCSSProperties { + pixelWidth: number; + posHeight: number; + posLeft: number; + pixelTop: number; + pixelBottom: number; + textDecorationNone: boolean; + pixelLeft: number; + posTop: number; + posBottom: number; + textDecorationOverline: boolean; + posWidth: number; + textDecorationLineThrough: boolean; + pixelHeight: number; + textDecorationBlink: boolean; + posRight: number; + pixelRight: number; + textDecorationUnderline: boolean; +} +declare var MSStyleCSSProperties: { + prototype: MSStyleCSSProperties; + new (): MSStyleCSSProperties; +} + +interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, MSNavigatorExtensions, NavigatorGeolocation, MSNavigatorDoNotTrack, NavigatorStorageUtils { +} +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 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 { +} +declare var HTMLTableDataCellElement: { + prototype: HTMLTableDataCellElement; + new (): HTMLTableDataCellElement; +} + +interface HTMLBaseElement extends HTMLElement { + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Gets or sets the baseline URL on which relative links are based. + */ + 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 { + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createDocument(namespaceURI: string, qualifiedName: string, doctype: DocumentType): Document; + hasFeature(feature: string, version?: string): boolean; + createHTMLDocument(title: string): Document; +} +declare var DOMImplementation: { + prototype: DOMImplementation; + new (): DOMImplementation; +} + +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 Element extends Node, NodeSelector, ElementTraversal { + 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): boolean; + getBoundingClientRect(): ClientRect; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + msMatchesSelector(selectors: string): boolean; + hasAttribute(name: string): boolean; + removeAttribute(name?: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + getAttributeNode(name: string): Attr; + fireEvent(eventName: string, eventObj?: any): boolean; + getElementsByTagName(name: "a"): NodeListOf; + getElementsByTagName(name: "abbr"): NodeListOf; + getElementsByTagName(name: "address"): NodeListOf; + getElementsByTagName(name: "area"): NodeListOf; + getElementsByTagName(name: "article"): NodeListOf; + getElementsByTagName(name: "aside"): NodeListOf; + getElementsByTagName(name: "audio"): NodeListOf; + getElementsByTagName(name: "b"): NodeListOf; + getElementsByTagName(name: "base"): NodeListOf; + getElementsByTagName(name: "bdi"): NodeListOf; + getElementsByTagName(name: "bdo"): NodeListOf; + getElementsByTagName(name: "blockquote"): NodeListOf; + getElementsByTagName(name: "body"): NodeListOf; + getElementsByTagName(name: "br"): NodeListOf; + getElementsByTagName(name: "button"): NodeListOf; + getElementsByTagName(name: "canvas"): NodeListOf; + getElementsByTagName(name: "caption"): NodeListOf; + getElementsByTagName(name: "cite"): NodeListOf; + getElementsByTagName(name: "code"): NodeListOf; + getElementsByTagName(name: "col"): NodeListOf; + getElementsByTagName(name: "colgroup"): NodeListOf; + getElementsByTagName(name: "datalist"): NodeListOf; + getElementsByTagName(name: "dd"): NodeListOf; + getElementsByTagName(name: "del"): NodeListOf; + getElementsByTagName(name: "dfn"): NodeListOf; + getElementsByTagName(name: "div"): NodeListOf; + getElementsByTagName(name: "dl"): NodeListOf; + getElementsByTagName(name: "dt"): NodeListOf; + getElementsByTagName(name: "em"): NodeListOf; + getElementsByTagName(name: "embed"): NodeListOf; + getElementsByTagName(name: "fieldset"): NodeListOf; + getElementsByTagName(name: "figcaption"): NodeListOf; + getElementsByTagName(name: "figure"): NodeListOf; + getElementsByTagName(name: "footer"): NodeListOf; + getElementsByTagName(name: "form"): NodeListOf; + getElementsByTagName(name: "h1"): NodeListOf; + getElementsByTagName(name: "h2"): NodeListOf; + getElementsByTagName(name: "h3"): NodeListOf; + getElementsByTagName(name: "h4"): NodeListOf; + getElementsByTagName(name: "h5"): NodeListOf; + getElementsByTagName(name: "h6"): NodeListOf; + getElementsByTagName(name: "head"): NodeListOf; + getElementsByTagName(name: "header"): NodeListOf; + getElementsByTagName(name: "hgroup"): NodeListOf; + getElementsByTagName(name: "hr"): NodeListOf; + getElementsByTagName(name: "html"): NodeListOf; + getElementsByTagName(name: "i"): NodeListOf; + getElementsByTagName(name: "iframe"): NodeListOf; + getElementsByTagName(name: "img"): NodeListOf; + getElementsByTagName(name: "input"): NodeListOf; + getElementsByTagName(name: "ins"): NodeListOf; + getElementsByTagName(name: "kbd"): NodeListOf; + getElementsByTagName(name: "label"): NodeListOf; + getElementsByTagName(name: "legend"): NodeListOf; + getElementsByTagName(name: "li"): NodeListOf; + getElementsByTagName(name: "link"): NodeListOf; + getElementsByTagName(name: "main"): NodeListOf; + getElementsByTagName(name: "map"): NodeListOf; + getElementsByTagName(name: "mark"): NodeListOf; + getElementsByTagName(name: "menu"): NodeListOf; + getElementsByTagName(name: "meta"): NodeListOf; + getElementsByTagName(name: "nav"): NodeListOf; + getElementsByTagName(name: "noscript"): NodeListOf; + getElementsByTagName(name: "object"): NodeListOf; + getElementsByTagName(name: "ol"): NodeListOf; + getElementsByTagName(name: "optgroup"): NodeListOf; + getElementsByTagName(name: "option"): NodeListOf; + getElementsByTagName(name: "p"): NodeListOf; + getElementsByTagName(name: "param"): NodeListOf; + getElementsByTagName(name: "pre"): NodeListOf; + getElementsByTagName(name: "progress"): NodeListOf; + getElementsByTagName(name: "q"): NodeListOf; + getElementsByTagName(name: "rp"): NodeListOf; + getElementsByTagName(name: "rt"): NodeListOf; + getElementsByTagName(name: "ruby"): NodeListOf; + getElementsByTagName(name: "s"): NodeListOf; + getElementsByTagName(name: "samp"): NodeListOf; + getElementsByTagName(name: "script"): NodeListOf; + getElementsByTagName(name: "section"): NodeListOf; + getElementsByTagName(name: "select"): NodeListOf; + getElementsByTagName(name: "small"): NodeListOf; + getElementsByTagName(name: "source"): NodeListOf; + getElementsByTagName(name: "span"): NodeListOf; + getElementsByTagName(name: "strong"): NodeListOf; + getElementsByTagName(name: "style"): NodeListOf; + getElementsByTagName(name: "sub"): NodeListOf; + getElementsByTagName(name: "summary"): NodeListOf; + getElementsByTagName(name: "sup"): NodeListOf; + getElementsByTagName(name: "table"): NodeListOf; + getElementsByTagName(name: "tbody"): NodeListOf; + getElementsByTagName(name: "td"): NodeListOf; + getElementsByTagName(name: "textarea"): NodeListOf; + getElementsByTagName(name: "tfoot"): NodeListOf; + getElementsByTagName(name: "th"): NodeListOf; + getElementsByTagName(name: "thead"): NodeListOf; + getElementsByTagName(name: "title"): NodeListOf; + getElementsByTagName(name: "tr"): NodeListOf; + getElementsByTagName(name: "track"): NodeListOf; + getElementsByTagName(name: "u"): NodeListOf; + getElementsByTagName(name: "ul"): NodeListOf; + getElementsByTagName(name: "var"): NodeListOf; + getElementsByTagName(name: "video"): NodeListOf; + getElementsByTagName(name: "wbr"): NodeListOf; + getElementsByTagName(name: string): NodeList; + getClientRects(): ClientRectList; + setAttributeNode(newAttr: Attr): Attr; + removeAttributeNode(oldAttr: Attr): Attr; + setAttribute(name?: string, value?: string): void; + removeAttributeNS(namespaceURI: string, localName: string): void; +} +declare var Element: { + prototype: Element; + new (): Element; +} + +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, SVGExternalResourcesRequired { + y1: SVGAnimatedLength; + x2: SVGAnimatedLength; + x1: SVGAnimatedLength; + y2: SVGAnimatedLength; +} +declare var SVGLineElement: { + prototype: SVGLineElement; + new (): SVGLineElement; +} + +interface HTMLParagraphElement extends HTMLElement, DOML2DeprecatedTextFlowControl { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; +} +declare var HTMLParagraphElement: { + prototype: HTMLParagraphElement; + new (): HTMLParagraphElement; +} + +interface HTMLAreasCollection extends HTMLCollection { + /** + * Removes an element from the collection. + */ + remove(index?: number): void; + /** + * Adds an element to the areas, controlRange, or options collection. + */ + 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: NamedNodeMap; + firstChild: Node; + prefix: string; + removeChild(oldChild: Node): Node; + appendChild(newChild: Node): Node; + isSupported(feature: string, version: string): boolean; + isEqualNode(arg: Node): boolean; + lookupPrefix(namespaceURI: string): string; + isDefaultNamespace(namespaceURI: string): boolean; + compareDocumentPosition(other: Node): number; + normalize(): void; + isSameNode(other: Node): boolean; + hasAttributes(): boolean; + lookupNamespaceURI(prefix: string): string; + cloneNode(deep?: boolean): Node; + hasChildNodes(): boolean; + 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 SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { + y: number; + x: number; +} +declare var SVGPathSegCurvetoQuadraticSmoothRel: { + prototype: SVGPathSegCurvetoQuadraticSmoothRel; + new (): SVGPathSegCurvetoQuadraticSmoothRel; +} + +interface DOML2DeprecatedListSpaceReduction { + compact: boolean; +} + +interface MSScriptHost { +} +declare var MSScriptHost: { + prototype: MSScriptHost; + new (): MSScriptHost; +} + +interface SVGClipPathElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { + clipPathUnits: SVGAnimatedEnumeration; +} +declare var SVGClipPathElement: { + prototype: SVGClipPathElement; + new (): SVGClipPathElement; +} + +interface MouseEvent extends UIEvent { + toElement: Element; + layerY: number; + fromElement: Element; + which: number; + pageX: number; + offsetY: number; + x: number; + y: number; + metaKey: boolean; + altKey: boolean; + ctrlKey: boolean; + offsetX: number; + screenX: number; + clientY: number; + shiftKey: boolean; + layerX: number; + screenY: number; + relatedTarget: EventTarget; + button: number; + pageY: number; + buttons: number; + clientX: number; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget): void; + getModifierState(keyArg: string): boolean; +} +declare var MouseEvent: { + prototype: MouseEvent; + new (): MouseEvent; +} + +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 SVGTextPositioningElement extends SVGTextContentElement { + y: SVGAnimatedLengthList; + rotate: SVGAnimatedNumberList; + dy: SVGAnimatedLengthList; + x: SVGAnimatedLengthList; + dx: SVGAnimatedLengthList; +} +declare var SVGTextPositioningElement: { + prototype: SVGTextPositioningElement; + new (): SVGTextPositioningElement; +} + +interface HTMLAppletElement extends HTMLElement, DOML2DeprecatedMarginStyle, DOML2DeprecatedBorderStyle, DOML2DeprecatedAlignmentStyle, MSDataBindingExtensions, MSDataBindingRecordSetExtensions { + width: number; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + object: string; + form: HTMLFormElement; + code: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the class identifier for the object. + */ + classid: string; + /** + * Sets or retrieves the shape of the object. + */ + name: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ + contentDocument: Document; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ + declare: boolean; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + BaseHref: string; +} +declare var HTMLAppletElement: { + prototype: HTMLAppletElement; + new (): HTMLAppletElement; +} + +interface TextMetrics { + width: number; +} +declare var TextMetrics: { + prototype: TextMetrics; + new (): TextMetrics; +} + +interface DocumentEvent { + createEvent(eventInterface: string): Event; +} + +interface HTMLOListElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, DOML2DeprecatedListNumberingAndBulletStyle { + /** + * The starting number. + */ + start: number; +} +declare var HTMLOListElement: { + prototype: HTMLOListElement; + new (): HTMLOListElement; +} + +interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { + y: number; +} +declare var SVGPathSegLinetoVerticalRel: { + prototype: SVGPathSegLinetoVerticalRel; + new (): SVGPathSegLinetoVerticalRel; +} + +interface SVGAnimatedString { + animVal: string; + baseVal: string; +} +declare var SVGAnimatedString: { + prototype: SVGAnimatedString; + new (): SVGAnimatedString; +} + +interface CDATASection extends Text { +} +declare var CDATASection: { + prototype: CDATASection; + new (): CDATASection; +} + +interface StyleMedia { + type: string; + matchMedium(mediaquery: string): boolean; +} +declare var StyleMedia: { + prototype: StyleMedia; + new (): StyleMedia; +} + +interface HTMLSelectElement extends HTMLElement, MSHTMLCollectionExtensions, MSDataBindingExtensions { + options: HTMLSelectElement; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Sets or retrieves the number of rows in the list box. + */ + size: number; + /** + * Sets or retrieves the number of objects in a collection. + */ + length: number; + /** + * Sets or retrieves the index of the selected option in a select object. + */ + selectedIndex: number; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ + type: string; + /** + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ + remove(index?: number): void; + /** + * Adds an element to the areas, controlRange, or options collection. + * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + */ + add(element: HTMLElement, before?: any): void; + /** + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(name?: any, index?: any): any; + /** + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ + namedItem(name: string): any; + [name: string]: any; +} +declare var HTMLSelectElement: { + prototype: HTMLSelectElement; + new (): HTMLSelectElement; +} + +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): boolean; + scrollIntoView(fStart?: boolean): void; + findText(string: string, count?: number, flags?: number): boolean; + execCommand(cmdID: string, showUI?: boolean, value?: any): boolean; + getBoundingClientRect(): ClientRect; + moveToBookmark(bookmark: string): boolean; + isEqual(range: TextRange): boolean; + duplicate(): TextRange; + collapse(start?: boolean): void; + queryCommandText(cmdID: string): string; + select(): void; + pasteHTML(html: string): void; + inRange(range: TextRange): boolean; + moveEnd(unit: string, count?: number): number; + getClientRects(): ClientRectList; + moveStart(unit: string, count?: number): number; + parentElement(): Element; + queryCommandState(cmdID: string): boolean; + compareEndPoints(how: string, sourceRange: TextRange): number; + execCommandShowHelp(cmdID: string): boolean; + moveToElementText(element: Element): void; + expand(Unit: string): boolean; + queryCommandSupported(cmdID: string): boolean; + setEndPoint(how: string, SourceRange: TextRange): void; + queryCommandEnabled(cmdID: string): boolean; +} +declare var TextRange: { + prototype: TextRange; + new (): TextRange; +} + +interface SVGTests { + requiredFeatures: SVGStringList; + requiredExtensions: SVGStringList; + systemLanguage: SVGStringList; + hasExtension(extension: string): boolean; +} + +interface HTMLBlockElement extends HTMLElement, DOML2DeprecatedTextFlowControl { + /** + * Sets or retrieves the width of the object. + */ + width: number; + /** + * Sets or retrieves reference information about the object. + */ + cite: string; +} +declare var HTMLBlockElement: { + prototype: HTMLBlockElement; + new (): HTMLBlockElement; +} + +interface CSSStyleSheet extends StyleSheet { + owningElement: Element; + imports: StyleSheetList; + isAlternate: boolean; + rules: MSCSSRuleList; + isPrefAlternate: boolean; + readOnly: boolean; + cssText: string; + ownerRule: CSSRule; + href: string; + cssRules: CSSRuleList; + id: string; + pages: StyleSheetPageList; + addImport(bstrURL: string, lIndex?: number): number; + addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; + insertRule(rule: string, index?: number): number; + removeRule(lIndex: number): void; + deleteRule(index?: number): void; + addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; + removeImport(lIndex: number): void; +} +declare var CSSStyleSheet: { + prototype: CSSStyleSheet; + new (): CSSStyleSheet; +} + +interface MSSelection { + type: string; + typeDetail: string; + createRange(): TextRange; + clear(): void; + createRangeCollection(): TextRangeCollection; + empty(): void; +} +declare var MSSelection: { + prototype: MSSelection; + new (): MSSelection; +} + +interface HTMLMetaElement extends HTMLElement { + /** + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ + httpEquiv: string; + /** + * Sets or retrieves the value specified in the content attribute of the meta object. + */ + name: string; + /** + * Gets or sets meta-information to associate with httpEquiv or name. + */ + content: string; + /** + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ + url: string; + /** + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ + scheme: string; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; +} +declare var HTMLMetaElement: { + prototype: HTMLMetaElement; + new (): HTMLMetaElement; +} + +interface SVGPatternElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGTests, SVGFitToViewBox, SVGExternalResourcesRequired, SVGURIReference { + patternUnits: SVGAnimatedEnumeration; + y: SVGAnimatedLength; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + patternContentUnits: SVGAnimatedEnumeration; + patternTransform: SVGAnimatedTransformList; + height: SVGAnimatedLength; +} +declare var SVGPatternElement: { + prototype: SVGPatternElement; + new (): SVGPatternElement; +} + +interface SVGAnimatedAngle { + animVal: SVGAngle; + baseVal: SVGAngle; +} +declare var SVGAnimatedAngle: { + prototype: SVGAnimatedAngle; + new (): SVGAnimatedAngle; +} + +interface Selection { + isCollapsed: boolean; + 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 SVGScriptElement extends SVGElement, SVGExternalResourcesRequired, SVGURIReference { + type: string; +} +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new (): SVGScriptElement; +} + +interface HTMLDDElement extends HTMLElement { + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; +} +declare var HTMLDDElement: { + prototype: HTMLDDElement; + new (): HTMLDDElement; +} + +interface MSDataBindingRecordSetReadonlyExtensions { + recordset: Object; + namedRecordset(dataMember: string, hierarchy?: any): Object; +} + +interface CSSStyleRule extends CSSRule { + selectorText: string; + style: MSStyleCSSProperties; + readOnly: boolean; +} +declare var CSSStyleRule: { + prototype: CSSStyleRule; + new (): CSSStyleRule; +} + +interface NodeIterator { + whatToShow: number; + filter: NodeFilter; + root: Node; + expandEntityReferences: boolean; + nextNode(): Node; + detach(): void; + previousNode(): Node; +} +declare var NodeIterator: { + prototype: NodeIterator; + new (): NodeIterator; +} + +interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox, SVGExternalResourcesRequired { + viewTarget: SVGStringList; +} +declare var SVGViewElement: { + prototype: SVGViewElement; + new (): SVGViewElement; +} + +interface HTMLLinkElement extends HTMLElement, LinkStyle { + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rev: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; +} +declare var HTMLLinkElement: { + prototype: HTMLLinkElement; + new (): HTMLLinkElement; +} + +interface SVGLocatable { + farthestViewportElement: SVGElement; + nearestViewportElement: SVGElement; + getBBox(): SVGRect; + getTransformToElement(element: SVGElement): SVGMatrix; + getCTM(): SVGMatrix; + getScreenCTM(): SVGMatrix; +} + +interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves the current typeface family. + */ + face: string; +} +declare var HTMLFontElement: { + prototype: HTMLFontElement; + new (): HTMLFontElement; +} + +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): boolean; + scrollIntoView(varargStart?: any): void; + item(index: number): Element; + [index: number]: Element; + execCommand(cmdID: string, showUI?: boolean, value?: any): boolean; + addElement(item: Element): void; + queryCommandState(cmdID: string): boolean; + queryCommandSupported(cmdID: string): boolean; + queryCommandEnabled(cmdID: string): boolean; + queryCommandText(cmdID: string): string; + select(): void; +} +declare var ControlRangeCollection: { + prototype: ControlRangeCollection; + new (): ControlRangeCollection; +} + +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 { + /** + * Sets or retrieves the alignment of the caption or legend. + */ + align: string; + /** + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ + vAlign: string; +} +declare var HTMLTableCaptionElement: { + prototype: HTMLTableCaptionElement; + new (): HTMLTableCaptionElement; +} + +interface HTMLOptionElement extends HTMLElement, MSDataBindingExtensions { + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + index: number; + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + /** + * Sets or retrieves the text string specified by the option tag. + */ + text: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; + create(): HTMLOptionElement; +} +declare var HTMLOptionElement: { + prototype: HTMLOptionElement; + new (): HTMLOptionElement; +} + +interface HTMLMapElement extends HTMLElement { + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Retrieves a collection of the area objects defined for the given map object. + */ + areas: HTMLAreasCollection; +} +declare var HTMLMapElement: { + prototype: HTMLMapElement; + new (): HTMLMapElement; +} + +interface HTMLMenuElement extends HTMLElement, DOML2DeprecatedListSpaceReduction { + type: string; +} +declare var HTMLMenuElement: { + prototype: HTMLMenuElement; + new (): HTMLMenuElement; +} + +interface MouseWheelEvent extends MouseEvent { + wheelDelta: number; + initMouseWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, 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 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 SVGAnimatedLengthList { + animVal: SVGLengthList; + baseVal: SVGLengthList; +} +declare var SVGAnimatedLengthList: { + prototype: SVGAnimatedLengthList; + new (): SVGAnimatedLengthList; +} + +interface Window extends EventTarget, MSEventAttachmentTarget, WindowLocalStorage, MSWindowExtensions, 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; + screenX: number; + onmouseover: (ev: MouseEvent) => any; + ondragleave: (ev: DragEvent) => any; + history: History; + pageXOffset: number; + 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; + innerHeight: number; + 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; + outerWidth: number; + onstalled: (ev: Event) => any; + onmousemove: (ev: MouseEvent) => any; + innerWidth: number; + onoffline: (ev: Event) => any; + length: number; + screen: Screen; + 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; + document: Document; + onprogress: (ev: any) => any; + ondblclick: (ev: MouseEvent) => any; + pageYOffset: number; + oncontextmenu: (ev: MouseEvent) => any; + onchange: (ev: Event) => any; + onloadedmetadata: (ev: Event) => any; + onplay: (ev: Event) => any; + onerror: ErrorEventHandler; + onplaying: (ev: Event) => any; + parent: Window; + location: Location; + oncanplaythrough: (ev: Event) => any; + onabort: (ev: UIEvent) => any; + onreadystatechange: (ev: Event) => any; + outerHeight: number; + 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; + onselect: (ev: UIEvent) => any; + navigator: Navigator; + styleMedia: StyleMedia; + ondrop: (ev: DragEvent) => any; + onmouseout: (ev: MouseEvent) => any; + onended: (ev: Event) => any; + onhashchange: (ev: Event) => any; + onunload: (ev: Event) => any; + onscroll: (ev: UIEvent) => any; + screenY: number; + onmousewheel: (ev: MouseWheelEvent) => any; + onload: (ev: Event) => any; + onvolumechange: (ev: Event) => any; + oninput: (ev: Event) => any; + performance: Performance; + alert(message?: any): void; + scroll(x?: number, y?: number): void; + focus(): void; + scrollTo(x?: number, y?: number): void; + print(): void; + prompt(message?: string, defaul?: string): string; + toString(): string; + open(url?: string, target?: string, features?: string, replace?: boolean): Window; + scrollBy(x?: number, y?: number): void; + confirm(message?: string): boolean; + close(): void; + postMessage(message: any, targetOrigin: string, ports?: any): void; + showModalDialog(url?: string, argument?: any, options?: any): any; + blur(): void; + getSelection(): Selection; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; +} +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 DOML2DeprecatedTextFlowControl { + clear: string; +} + +interface StyleSheetPageList { + length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new (): StyleSheetPageList; +} + +interface MSCSSProperties extends CSSStyleDeclaration { + 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; + getAttribute(attributeName: string, flags?: number): any; + setAttribute(attributeName: string, AttributeValue: any, flags?: number): void; + removeAttribute(attributeName: string, flags?: number): boolean; +} +declare var MSCSSProperties: { + prototype: MSCSSProperties; + new (): MSCSSProperties; +} + +interface HTMLCollection extends MSHTMLCollectionExtensions { + /** + * Sets or retrieves the number of objects in a collection. + */ + length: number; + /** + * Retrieves an object from various collections. + */ + item(nameOrIndex?: any, optionalIndex?: any): Element; + /** + * Retrieves a select object or an object from an options collection. + */ + namedItem(name: string): Element; + [name: number]: Element; +} +declare var HTMLCollection: { + prototype: HTMLCollection; + new (): HTMLCollection; +} + +interface SVGExternalResourcesRequired { + externalResourcesRequired: SVGAnimatedBoolean; +} + +interface HTMLImageElement extends HTMLElement, MSImageResourceExtensions, MSDataBindingExtensions, MSResourceMetadata { + /** + * Sets or retrieves the width of the object. + */ + width: number; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * The original height of the image resource before sizing. + */ + naturalHeight: number; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * The original width of the image resource before sizing. + */ + naturalWidth: number; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Sets or retrieves the height of the object. + */ + height: number; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + hspace: number; + /** + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ + longDesc: string; + /** + * Contains the hypertext reference (HREF) of the URL. + */ + href: string; + /** + * Sets or retrieves whether the image is a server-side image map. + */ + isMap: boolean; + /** + * Retrieves whether the object is fully loaded. + */ + complete: boolean; + create(): HTMLImageElement; +} +declare var HTMLImageElement: { + prototype: HTMLImageElement; + new (): HTMLImageElement; +} + +interface HTMLAreaElement extends HTMLElement { + /** + * Sets or retrieves the protocol portion of a URL. + */ + protocol: string; + /** + * Sets or retrieves the substring of the href property that follows the question mark. + */ + search: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + /** + * Sets or retrieves the host name part of the location or URL. + */ + hostname: string; + /** + * Sets or retrieves the port number associated with a URL. + */ + port: string; + /** + * Sets or retrieves the file name or path specified by the object. + */ + pathname: string; + /** + * Sets or retrieves the hostname and port number of the location or URL. + */ + host: string; + /** + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ + hash: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or gets whether clicks in this region cause action. + */ + noHref: boolean; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + /** + * Returns a string representation of an object. + */ + toString(): string; +} +declare var HTMLAreaElement: { + prototype: HTMLAreaElement; + new (): HTMLAreaElement; +} + +interface EventTarget { + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; + removeEventListener(type: string, listener: EventListener, useCapture?: boolean): void; + dispatchEvent(evt: Event): boolean; +} + +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, MSDataBindingExtensions { + /** + * Sets or retrieves the default or selected value of the control. + */ + value: string; + status: any; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets the classification and default behavior of the button. + */ + type: string; + /** + * Creates a TextRange object for the element. + */ + createTextRange(): TextRange; +} +declare var HTMLButtonElement: { + prototype: HTMLButtonElement; + new (): HTMLButtonElement; +} + +interface HTMLSourceElement extends HTMLElement { + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + /** + * Gets or sets the intended media type of the media source. + */ + media: string; + /** + * Gets or sets the MIME type of a media resource. + */ + 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 { + location: number; + keyCode: number; + shiftKey: boolean; + which: number; + locale: string; + key: string; + altKey: boolean; + metaKey: boolean; + char: string; + ctrlKey: boolean; + repeat: boolean; + charCode: number; + getModifierState(keyArg: string): boolean; + initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, 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, NodeSelector, MSEventAttachmentTarget, DocumentEvent, MSResourceMetadata, MSNodeExtensions { + /** + * Retrieves the collection of user agents and versions declared in the X-UA-Compatible + */ + compatible: MSCompatibleInfoCollection; + /** + * Fires when the user presses a key. + * @param ev The keyboard event + */ + onkeydown: (ev: KeyboardEvent) => any; + /** + * Fires when the user releases a key. + * @param ev The keyboard event + */ + onkeyup: (ev: KeyboardEvent) => any; + + /** + * Gets the implementation object of the current document. + */ + implementation: DOMImplementation; + /** + * Fires when the user resets a form. + * @param ev The event. + */ + onreset: (ev: Event) => any; + + /** + * Retrieves a collection of all script objects in the document. + */ + scripts: HTMLCollection; + + /** + * Fires when the user presses the F1 key while the browser is the active window. + * @param ev The event. + */ + onhelp: (ev: Event) => any; + + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ + ondragleave: (ev: DragEvent) => any; + + /** + * Gets or sets the character set used to encode the object. + */ + charset: string; + + /** + * Fires for an element just prior to setting focus on that element. + * @param ev The focus event + */ + onfocusin: (ev: FocusEvent) => any; + + + /** + * Sets or gets the color of the links that the user has visited. + */ + vlinkColor: string; + + /** + * Occurs when the seek operation ends. + * @param ev The event. + */ + onseeked: (ev: Event) => any; + + security: string; + + /** + * Contains the title of the document. + */ + title: string; + + /** + * Retrieves a collection of namespace objects. + */ + namespaces: MSNamespaceInfoCollection; + + /** + * Gets the default character set from the current regional language settings. + */ + defaultCharset: string; + + /** + * Retrieves a collection of all embed objects in the document. + */ + embeds: HTMLCollection; + + /** + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ + styleSheets: StyleSheetList; + + /** + * Retrieves a collection of all window objects defined by the given document or defined by the document associated with the given window. + */ + frames: Window; + + /** + * Occurs when the duration attribute is updated. + * @param ev The event. + */ + ondurationchange: (ev: Event) => any; + + + /** + * Returns a reference to the collection of elements contained by the object. + */ + all: HTMLCollection; + + /** + * Retrieves a collection, in source order, of all form objects in the document. + */ + forms: HTMLCollection; + + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ + onblur: (ev: FocusEvent) => any; + + + /** + * Sets or retrieves a value that indicates the reading order of the object. + */ + dir: string; + + /** + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ + onemptied: (ev: Event) => any; + + + /** + * Sets or gets a value that indicates whether the document can be edited. + */ + designMode: string; + + /** + * Occurs when the current playback position is moved. + * @param ev The event. + */ + onseeking: (ev: Event) => any; + + + /** + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ + ondeactivate: (ev: UIEvent) => any; + + + /** + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ + oncanplay: (ev: Event) => any; + + + /** + * Fires when the data set exposed by a data source object changes. + * @param ev The event. + */ + ondatasetchanged: (ev: MSEventObj) => any; + + + /** + * Fires when rows are about to be deleted from the recordset. + * @param ev The event + */ + onrowsdelete: (ev: MSEventObj) => any; + + Script: MSScriptHost; + + /** + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ + onloadstart: (ev: Event) => any; + + + /** + * Gets the URL for the document, stripped of any character encoding. + */ + URLUnencoded: string; + + defaultView: Window; + + /** + * Fires when the user is about to make a control selection of the object. + * @param ev The event. + */ + oncontrolselect: (ev: MSEventObj) => any; + + + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ + ondragenter: (ev: DragEvent) => any; + + onsubmit: (ev: Event) => any; + + /** + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ + inputEncoding: string; + + /** + * Gets the object that has the focus when the parent document has focus. + */ + activeElement: Element; + + /** + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ + onchange: (ev: Event) => any; + + + /** + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ + links: HTMLCollection; + + /** + * Retrieves an autogenerated, unique identifier for the object. + */ + uniqueID: string; + + /** + * Sets or gets the URL for the current document. + */ + URL: string; + + /** + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ + onbeforeactivate: (ev: UIEvent) => any; + + head: HTMLHeadElement; + cookie: string; + xmlEncoding: string; + oncanplaythrough: (ev: Event) => any; + + /** + * Retrieves the document compatibility mode of the document. + */ + documentMode: number; + + characterSet: string; + + /** + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ + anchors: HTMLCollection; + + onbeforeupdate: (ev: MSEventObj) => any; + + /** + * Fires to indicate that all data is available from the data source object. + * @param ev The event. + */ + ondatasetcomplete: (ev: MSEventObj) => any; + + plugins: HTMLCollection; + + /** + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ + onsuspend: (ev: Event) => any; + + + /** + * Gets the root svg element in the document hierarchy. + */ + rootElement: SVGSVGElement; + + /** + * Retrieves a value that indicates the current state of the object. + */ + readyState: string; + + /** + * Gets the URL of the location that referred the user to the current page. + */ + referrer: string; + + /** + * Sets or gets the color of all active links in the document. + */ + alinkColor: string; + + /** + * Fires on a databound object when an error occurs while updating the associated data in the data source object. + * @param ev The event. + */ + onerrorupdate: (ev: MSEventObj) => any; + + + /** + * Gets a reference to the container object of the window. + */ + parentWindow: Window; + + /** + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ + onmouseout: (ev: MouseEvent) => any; + + + /** + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ + onmsthumbnailclick: (ev: MSSiteModeEvent) => any; + + + /** + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ + onmousewheel: (ev: MouseWheelEvent) => any; + + + /** + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ + onvolumechange: (ev: Event) => any; + + + /** + * Fires when data changes in the data provider. + * @param ev The event. + */ + oncellchange: (ev: MSEventObj) => any; + + + /** + * Fires just before the data source control changes the current row in the object. + * @param ev The event. + */ + onrowexit: (ev: MSEventObj) => any; + + + /** + * Fires just after new rows are inserted in the current recordset. + * @param ev The event. + */ + onrowsinserted: (ev: MSEventObj) => any; + + + /** + * Gets or sets the version attribute specified in the declaration of an XML document. + */ + xmlVersion: string; + + msCapsLockWarningOff: boolean; + + /** + * Fires when a property changes on the object. + * @param ev The event. + */ + onpropertychange: (ev: MSEventObj) => any; + + + /** + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ + ondragend: (ev: DragEvent) => any; + + + /** + * Gets an object representing the document type declaration associated with the current document. + */ + doctype: DocumentType; + + /** + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ + ondragover: (ev: DragEvent) => any; + + + /** + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ + bgColor: string; + + /** + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ + ondragstart: (ev: DragEvent) => any; + + + /** + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ + onmouseup: (ev: MouseEvent) => any; + + + /** + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ + ondrag: (ev: DragEvent) => any; + + + /** + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ + onmouseover: (ev: MouseEvent) => any; + + + /** + * Sets or gets the color of the document links. + */ + linkColor: string; + + /** + * Occurs when playback is paused. + * @param ev The event. + */ + onpause: (ev: Event) => any; + + + /** + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ + onmousedown: (ev: MouseEvent) => any; + + + /** + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ + onclick: (ev: MouseEvent) => any; + + + /** + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ + onwaiting: (ev: Event) => any; + + + /** + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ + onstop: (ev: Event) => any; + + /** + * false (false)[rolls + */ + + /** + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ + onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; + + + /** + * Retrieves a collection of all applet objects in the document. + */ + applets: HTMLCollection; + + /** + * Specifies the beginning and end of the document body. + */ + body: HTMLElement; + + /** + * Sets or gets the security domain of the document. + */ + domain: string; + + xmlStandalone: boolean; + + /** + * Represents the active selection, which is a highlighted block of text or other elements in the document that a user or a script can carry out some action on. + */ + selection: MSSelection; + + /** + * Occurs when the download has stopped. + * @param ev The event. + */ + onstalled: (ev: Event) => any; + + + /** + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ + onmousemove: (ev: MouseEvent) => any; + + + /** + * Gets a reference to the root node of the document. + */ + documentElement: HTMLElement; + + /** + * Fires before an object contained in an editable element enters a UI-activated state or when an editable container object is control selected. + * @param ev The event. + */ + onbeforeeditfocus: (ev: MSEventObj) => any; + + + /** + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ + onratechange: (ev: Event) => any; + + + /** + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ + onprogress: (ev: any) => any; + + + /** + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ + ondblclick: (ev: MouseEvent) => any; + + + /** + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ + oncontextmenu: (ev: MouseEvent) => any; + + + /** + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ + onloadedmetadata: (ev: Event) => any; + + media: string; + + /** + * Fires when an error occurs during object loading. + * @param ev The event. + */ + onerror: (ev: Event) => any; + + + /** + * Occurs when the play method is requested. + * @param ev The event. + */ + onplay: (ev: Event) => any; + + onafterupdate: (ev: MSEventObj) => any; + + /** + * Occurs when the audio or video has started playing. + * @param ev The event. + */ + onplaying: (ev: Event) => any; + + + /** + * Retrieves a collection, in source order, of img objects in the document. + */ + images: HTMLCollection; + + /** + * Contains information about the current URL. + */ + location: Location; + + /** + * Fires when the user aborts the download. + * @param ev The event. + */ + onabort: (ev: UIEvent) => any; + + + /** + * Fires for the current element with focus immediately after moving focus to another element. + * @param ev The event. + */ + onfocusout: (ev: FocusEvent) => any; + + + /** + * Fires when the selection state of a document changes. + * @param ev The event. + */ + onselectionchange: (ev: Event) => any; + + + /** + * Fires when a local DOM Storage area is written to disk. + * @param ev The event. + */ + onstoragecommit: (ev: StorageEvent) => any; + + + /** + * Fires periodically as data arrives from data source objects that asynchronously transmit their data. + * @param ev The event. + */ + ondataavailable: (ev: MSEventObj) => any; + + + /** + * Fires when the state of the object has changed. + * @param ev The event + */ + onreadystatechange: (ev: Event) => any; + + + /** + * Gets the date that the page was last modified, if the page supplies one. + */ + lastModified: string; + + /** + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ + onkeypress: (ev: KeyboardEvent) => any; + + + /** + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ + onloadeddata: (ev: Event) => any; + + + /** + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ + onbeforedeactivate: (ev: UIEvent) => any; + + + /** + * Fires when the object is set as the active element. + * @param ev The event. + */ + onactivate: (ev: UIEvent) => any; + + + onselectstart: (ev: Event) => any; + + /** + * Fires when the object receives focus. + * @param ev The event. + */ + onfocus: (ev: FocusEvent) => any; + + + /** + * Sets or gets the foreground (text) color of the document. + */ + fgColor: string; + + /** + * Occurs to indicate the current playback position. + * @param ev The event. + */ + ontimeupdate: (ev: Event) => any; + + + /** + * Fires when the current selection changes. + * @param ev The event. + */ + onselect: (ev: UIEvent) => any; + + ondrop: (ev: DragEvent) => any; + + /** + * Occurs when the end of playback is reached. + * @param ev The event + */ + onended: (ev: Event) => any; + + + /** + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ + compatMode: string; + + /** + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ + onscroll: (ev: UIEvent) => any; + + + /** + * Fires to indicate that the current row has changed in the data source and new data values are available on the object. + * @param ev The event. + */ + onrowenter: (ev: MSEventObj) => any; + + + /** + * Fires immediately after the browser loads the object. + * @param ev The event. + */ + onload: (ev: Event) => any; + + oninput: (ev: Event) => any; + + /** + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ + queryCommandValue(commandId: string): string; + + adoptNode(source: Node): Node; + + /** + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ + queryCommandIndeterm(commandId: string): boolean; + + getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList; + createProcessingInstruction(target: string, data: string): ProcessingInstruction; + + /** + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ + execCommand(commandId: string, showUI?: boolean, value?: any): boolean; + + /** + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ + elementFromPoint(x: number, y: number): Element; + createCDATASection(data: string): CDATASection; + + /** + * Retrieves the string associated with a command. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + */ + queryCommandText(commandId: string): string; + + /** + * Writes one or more HTML expressions to a document in the specified window. + * @param content Specifies the text and HTML tags to write. + */ + write(...content: string[]): void; + + /** + * Allows updating the print settings for the page. + */ + updateSettings(): void; + + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "a"): HTMLAnchorElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "abbr"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "address"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "area"): HTMLAreaElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "article"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "aside"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "audio"): HTMLAudioElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "b"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "base"): HTMLBaseElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "bdi"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "bdo"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "blockquote"): HTMLQuoteElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "body"): HTMLBodyElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "br"): HTMLBRElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "button"): HTMLButtonElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "canvas"): HTMLCanvasElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "caption"): HTMLTableCaptionElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "cite"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "code"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "col"): HTMLTableColElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "colgroup"): HTMLTableColElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "datalist"): HTMLDataListElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "dd"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "del"): HTMLModElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "dfn"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "div"): HTMLDivElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "dl"): HTMLDListElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "dt"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "em"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "embed"): HTMLEmbedElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "fieldset"): HTMLFieldSetElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "figcaption"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "figure"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "footer"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "form"): HTMLFormElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "h1"): HTMLHeadingElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "h2"): HTMLHeadingElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "h3"): HTMLHeadingElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "h4"): HTMLHeadingElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "h5"): HTMLHeadingElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "h6"): HTMLHeadingElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "head"): HTMLHeadElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "header"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "hgroup"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "hr"): HTMLHRElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "html"): HTMLHtmlElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "i"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "iframe"): HTMLIFrameElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "img"): HTMLImageElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "input"): HTMLInputElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "ins"): HTMLModElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "kbd"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "label"): HTMLLabelElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "legend"): HTMLLegendElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "li"): HTMLLIElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "link"): HTMLLinkElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "main"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "map"): HTMLMapElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "mark"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "menu"): HTMLMenuElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "meta"): HTMLMetaElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "nav"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "noscript"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "object"): HTMLObjectElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "ol"): HTMLOListElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "optgroup"): HTMLOptGroupElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "option"): HTMLOptionElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "p"): HTMLParagraphElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "param"): HTMLParamElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "pre"): HTMLPreElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "progress"): HTMLProgressElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "q"): HTMLQuoteElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "rp"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "rt"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "ruby"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "s"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "samp"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "script"): HTMLScriptElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "section"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "select"): HTMLSelectElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "small"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "source"): HTMLSourceElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "span"): HTMLSpanElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "strong"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "style"): HTMLStyleElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "sub"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "summary"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "sup"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "table"): HTMLTableElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "tbody"): HTMLTableSectionElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "td"): HTMLTableDataCellElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "textarea"): HTMLTextAreaElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "tfoot"): HTMLTableSectionElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "th"): HTMLTableHeaderCellElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "thead"): HTMLTableSectionElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "title"): HTMLTitleElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "tr"): HTMLTableRowElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "track"): HTMLTrackElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "u"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "ul"): HTMLUListElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "var"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "video"): HTMLVideoElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "wbr"): HTMLElement; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: string): HTMLElement; + + /** + * Removes mouse capture from the object in the current document. + */ + releaseCapture(): void; + + /** + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * @param content The text and HTML tags to write. + */ + writeln(...content: string[]): void; + createElementNS(namespaceURI: string, qualifiedName: string): Element; + + /** + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @param replace Specifies whether the existing entry for the document is replaced in the history list. + */ + open(url?: string, name?: string, features?: string, replace?: boolean): any; + + /** + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ + queryCommandSupported(commandId: string): boolean; + + /** + * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + createTreeWalker(root: Node, whatToShow: number, filter: NodeFilter, entityReferenceExpansion: boolean): TreeWalker; + createAttributeNS(namespaceURI: string, qualifiedName: string): Attr; + + /** + * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. + * @param commandId Specifies a command identifier. + */ + queryCommandEnabled(commandId: string): boolean; + + /** + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ + focus(): void; + + /** + * Closes an output stream and forces the sent data to display. + */ + close(): void; + + getElementsByClassName(classNames: string): NodeList; + importNode(importedNode: Node, deep: boolean): Node; + + /** + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + */ + createRange(): Range; + + /** + * Fires a specified event on the object. + * @param eventName Specifies the name of the event to fire. + * @param eventObj Object that specifies the event object from which to obtain event object properties. + */ + fireEvent(eventName: string, eventObj?: any): boolean; + + /** + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ + createComment(data: string): Comment; + + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "a"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "abbr"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "address"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "area"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "article"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "aside"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "audio"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "b"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "base"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "bdi"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "bdo"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "blockquote"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "body"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "br"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "button"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "canvas"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "caption"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "cite"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "code"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "col"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "colgroup"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "datalist"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "dd"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "del"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "dfn"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "div"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "dl"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "dt"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "em"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "embed"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "fieldset"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "figcaption"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "figure"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "footer"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "form"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "h1"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "h2"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "h3"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "h4"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "h5"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "h6"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "head"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "header"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "hgroup"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "hr"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "html"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "i"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "iframe"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "img"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "input"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "ins"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "kbd"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "label"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "legend"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "li"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "link"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "main"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "map"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "mark"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "menu"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "meta"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "nav"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "noscript"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "object"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "ol"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "optgroup"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "option"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "p"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "param"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "pre"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "progress"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "q"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "rp"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "rt"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "ruby"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "s"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "samp"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "script"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "section"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "select"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "small"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "source"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "span"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "strong"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "style"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "sub"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "summary"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "sup"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "table"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "tbody"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "td"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "textarea"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "tfoot"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "th"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "thead"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "title"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "tr"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "track"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "u"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "ul"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "var"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "video"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: "wbr"): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(name: string): NodeList; + + /** + * Creates a new document. + */ + createDocumentFragment(): DocumentFragment; + + /** + * Creates a style sheet for the document. + * @param href Specifies how to add the style sheet to the document. If a file name is specified for the URL, the style information is added as a link object. If the URL contains style information, it is added to the style object. + * @param index Specifies the index that indicates where the new style sheet is inserted in the styleSheets collection. The default is to insert the new style sheet at the end of the collection. + */ + createStyleSheet(href?: string, index?: number): CSSStyleSheet; + + /** + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ + getElementsByName(elementName: string): NodeList; + + /** + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ + queryCommandState(commandId: string): boolean; + + /** + * Gets a value indicating whether the object currently has focus. + */ + hasFocus(): boolean; + + /** + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ + execCommandShowHelp(commandId: string): boolean; + + /** + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ + createAttribute(name: string): Attr; + + /** + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ + createTextNode(data: string): Text; + + /** + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + createNodeIterator(root: Node, whatToShow: number, filter: NodeFilter, entityReferenceExpansion: boolean): NodeIterator; + + /** + * Generates an event object to pass event context information when you use the fireEvent method. + * @param eventObj An object that specifies an existing event object on which to base the new object. + */ + createEventObject(eventObj?: any): MSEventObj; + + /** + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ + getSelection(): Selection; + + /** + * Returns a reference to the first object with the specified value of the ID or NAME attribute. + * @param elementId String that specifies the ID value. Case-insensitive. + */ + 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: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} +declare var MessageEvent: { + prototype: MessageEvent; + new (): MessageEvent; +} + +interface SVGElement extends Element { + onmouseover: (ev: MouseEvent) => any; + viewportElement: SVGElement; + onmousemove: (ev: MouseEvent) => any; + onmouseout: (ev: MouseEvent) => any; + ondblclick: (ev: MouseEvent) => any; + onfocusout: (ev: FocusEvent) => any; + onfocusin: (ev: FocusEvent) => any; + xmlbase: string; + onmousedown: (ev: MouseEvent) => any; + onload: (ev: Event) => any; + onmouseup: (ev: MouseEvent) => any; + onclick: (ev: MouseEvent) => any; + ownerSVGElement: SVGSVGElement; + id: string; +} +declare var SVGElement: { + prototype: SVGElement; + new (): SVGElement; +} + +interface HTMLScriptElement extends HTMLElement { + /** + * Sets or retrieves the status of the script. + */ + defer: boolean; + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + /** + * Retrieves the URL to an external file that contains the source code or data. + */ + src: string; + /** + * Sets or retrieves the object that is bound to the event script. + */ + htmlFor: string; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the MIME type for the associated scripting engine. + */ + type: string; + /** + * Sets or retrieves the event for which the script is written. + */ + event: string; +} +declare var HTMLScriptElement: { + prototype: HTMLScriptElement; + new (): HTMLScriptElement; +} + +interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment, DOML2DeprecatedBackgroundColorStyle { + /** + * Retrieves the position of the object in the rows collection for the table. + */ + rowIndex: number; + /** + * Retrieves a collection of all cells in the table row. + */ + cells: HTMLCollection; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves the color for one of the two colors used to draw the 3-D border of the object. + */ + borderColorLight: any; + /** + * Retrieves the position of the object in the collection. + */ + sectionRowIndex: number; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves the color for one of the two colors used to draw the 3-D border of the object. + */ + borderColorDark: any; + /** + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ + deleteCell(index?: number): void; + /** + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ + insertCell(index?: number): HTMLElement; +} +declare var HTMLTableRowElement: { + prototype: HTMLTableRowElement; + new (): HTMLTableRowElement; +} + +interface CanvasRenderingContext2D { + miterLimit: number; + font: string; + globalCompositeOperation: string; + msFillRule: string; + lineCap: string; + msImageSmoothingEnabled: boolean; + lineDashOffset: number; + shadowColor: string; + lineJoin: string; + shadowOffsetX: number; + lineWidth: number; + canvas: HTMLCanvasElement; + strokeStyle: any; + globalAlpha: number; + shadowOffsetY: number; + fillStyle: any; + shadowBlur: number; + textAlign: string; + textBaseline: 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?: boolean): void; + measureText(text: string): TextMetrics; + isPointInPath(x: number, y: number, fillRule?: string): boolean; + 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; + getLineDash(): Array; + fill(fillRule?: string): void; + createImageData(imageDataOrSw: any, sh?: number): ImageData; + createPattern(image: HTMLElement, repetition: string): CanvasPattern; + closePath(): void; + rect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: string): void; + 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; + setLineDash(segments: Array): 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 MSCSSRuleList { + length: number; + item(index?: number): CSSStyleRule; + [index: number]: CSSStyleRule; +} +declare var MSCSSRuleList: { + prototype: MSCSSRuleList; + new (): MSCSSRuleList; +} + +interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { + x: number; +} +declare var SVGPathSegLinetoHorizontalAbs: { + prototype: SVGPathSegLinetoHorizontalAbs; + new (): SVGPathSegLinetoHorizontalAbs; +} + +interface SVGPathSegArcAbs extends SVGPathSeg { + y: number; + sweepFlag: boolean; + r2: number; + x: number; + angle: number; + r1: number; + largeArcFlag: boolean; +} +declare var SVGPathSegArcAbs: { + prototype: SVGPathSegArcAbs; + new (): SVGPathSegArcAbs; +} + +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 HTMLHtmlElement extends HTMLElement { + /** + * Sets or retrieves the DTD version that governs the current document. + */ + version: string; +} +declare var HTMLHtmlElement: { + prototype: HTMLHtmlElement; + new (): HTMLHtmlElement; +} + +interface SVGPathSegClosePath extends SVGPathSeg { +} +declare var SVGPathSegClosePath: { + prototype: SVGPathSegClosePath; + new (): SVGPathSegClosePath; +} + +interface HTMLFrameElement extends HTMLElement, GetSVGDocument, MSDataBindingExtensions { + /** + * Sets or retrieves the width of the object. + */ + width: any; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + scrolling: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + marginWidth: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + noResize: boolean; + /** + * Retrieves the object of the specified. + */ + contentWindow: Window; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Retrieves the document object of the page or frame. + */ + contentDocument: Document; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Sets or retrieves a URI to a long description of the object. + */ + longDesc: string; + /** + * Raised when the object has been completely received from the server. + */ + onload: (ev: Event) => any; + /** + * Sets the value indicating whether the source file of a frame or iframe has specific security restrictions applied. + */ + security: any; +} +declare var HTMLFrameElement: { + prototype: HTMLFrameElement; + new (): HTMLFrameElement; +} + +interface SVGAnimatedLength { + animVal: SVGLength; + baseVal: SVGLength; +} +declare var SVGAnimatedLength: { + prototype: SVGAnimatedLength; + new (): SVGAnimatedLength; +} + +interface SVGAnimatedPoints { + points: SVGPointList; + animatedPoints: SVGPointList; +} + +interface SVGDefsElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { +} +declare var SVGDefsElement: { + prototype: SVGDefsElement; + new (): SVGDefsElement; +} + +interface HTMLQuoteElement extends HTMLElement { + /** + * Sets or retrieves the date and time of a modification to the object. + */ + dateTime: string; + /** + * Sets or retrieves reference information about the object. + */ + cite: string; +} +declare var HTMLQuoteElement: { + prototype: HTMLQuoteElement; + new (): HTMLQuoteElement; +} + +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 WindowModal { + dialogArguments: any; + returnValue: any; +} + +interface XMLHttpRequest extends EventTarget { + responseBody: any; + status: number; + readyState: number; + responseText: string; + responseXML: Document; + ontimeout: (ev: Event) => any; + statusText: string; + onreadystatechange: (ev: Event) => any; + timeout: number; + onload: (ev: Event) => any; + open(method: string, url: string, async?: boolean, user?: string, password?: string): void; + create(): XMLHttpRequest; + 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 { + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; +} +declare var HTMLTableHeaderCellElement: { + prototype: HTMLTableHeaderCellElement; + new (): HTMLTableHeaderCellElement; +} + +interface HTMLDListElement extends HTMLElement, DOML2DeprecatedListSpaceReduction { +} +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new (): HTMLDListElement; +} + +interface MSDataBindingExtensions { + dataSrc: string; + dataFormatAs: string; + dataFld: string; +} + +interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { + x: number; +} +declare var SVGPathSegLinetoHorizontalRel: { + prototype: SVGPathSegLinetoHorizontalRel; + new (): SVGPathSegLinetoHorizontalRel; +} + +interface SVGEllipseElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { + ry: SVGAnimatedLength; + cx: SVGAnimatedLength; + rx: SVGAnimatedLength; + cy: SVGAnimatedLength; +} +declare var SVGEllipseElement: { + prototype: SVGEllipseElement; + new (): SVGEllipseElement; +} + +interface SVGAElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired, SVGURIReference { + target: SVGAnimatedString; +} +declare var SVGAElement: { + prototype: SVGAElement; + new (): SVGAElement; +} + +interface SVGStylable { + className: SVGAnimatedString; + style: CSSStyleDeclaration; +} + +interface SVGTransformable extends SVGLocatable { + transform: SVGAnimatedTransformList; +} + +interface HTMLFrameSetElement extends HTMLElement { + ononline: (ev: Event) => any; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves the frame heights of the object. + */ + rows: string; + /** + * Sets or retrieves the frame widths of the object. + */ + cols: string; + /** + * Fires when the object loses the input focus. + */ + onblur: (ev: FocusEvent) => any; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Fires when the object receives focus. + */ + onfocus: (ev: FocusEvent) => any; + onmessage: (ev: MessageEvent) => any; + onerror: (ev: Event) => any; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + onresize: (ev: UIEvent) => any; + name: string; + onafterprint: (ev: Event) => any; + onbeforeprint: (ev: Event) => any; + onoffline: (ev: Event) => any; + border: string; + onunload: (ev: Event) => any; + onhashchange: (ev: Event) => any; + onload: (ev: Event) => any; + onbeforeunload: (ev: BeforeUnloadEvent) => any; + onstorage: (ev: StorageEvent) => any; +} +declare var HTMLFrameSetElement: { + prototype: HTMLFrameSetElement; + new (): HTMLFrameSetElement; +} + +interface Screen { + width: number; + deviceXDPI: number; + fontSmoothingEnabled: boolean; + bufferDepth: number; + logicalXDPI: number; + systemXDPI: number; + availHeight: number; + height: number; + logicalYDPI: number; + systemYDPI: number; + updateInterval: number; + colorDepth: number; + availWidth: number; + deviceYDPI: number; + pixelDepth: number; +} +declare var Screen: { + prototype: Screen; + new (): Screen; +} + +interface Coordinates { + altitudeAccuracy: number; + longitude: number; + latitude: number; + speed: number; + heading: number; + altitude: number; + accuracy: number; +} +declare var Coordinates: { + prototype: Coordinates; + new (): Coordinates; +} + +interface NavigatorGeolocation { + geolocation: Geolocation; +} + +interface NavigatorContentUtils { +} + +interface EventListener { + (evt: Event): void; +} + +interface SVGLangSpace { + xmllang: string; + xmlspace: string; +} + +interface DataTransfer { + effectAllowed: string; + dropEffect: string; + clearData(format?: string): boolean; + setData(format: string, data: string): boolean; + getData(format: string): string; +} +declare var DataTransfer: { + prototype: DataTransfer; + new (): DataTransfer; +} + +interface FocusEvent extends UIEvent { + relatedTarget: EventTarget; + initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void; +} +declare var FocusEvent: { + prototype: FocusEvent; + new (): FocusEvent; +} + +interface Range { + startOffset: number; + collapsed: boolean; + 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: boolean): 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 SVGPoint { + y: number; + x: number; + matrixTransform(matrix: SVGMatrix): SVGPoint; +} +declare var SVGPoint: { + prototype: SVGPoint; + new (): SVGPoint; +} + +interface MSPluginsCollection { + length: number; + refresh(reload?: boolean): void; +} +declare var MSPluginsCollection: { + prototype: MSPluginsCollection; + new (): MSPluginsCollection; +} + +interface SVGAnimatedNumberList { + animVal: SVGNumberList; + baseVal: SVGNumberList; +} +declare var SVGAnimatedNumberList: { + prototype: SVGAnimatedNumberList; + new (): SVGAnimatedNumberList; +} + +interface SVGSVGElement extends SVGElement, SVGStylable, SVGZoomAndPan, DocumentEvent, SVGLangSpace, SVGLocatable, SVGTests, SVGFitToViewBox, SVGExternalResourcesRequired { + width: SVGAnimatedLength; + x: SVGAnimatedLength; + contentStyleType: string; + onzoom: (ev: any) => any; + y: SVGAnimatedLength; + viewport: SVGRect; + onerror: (ev: Event) => any; + pixelUnitToMillimeterY: number; + onresize: (ev: UIEvent) => any; + screenPixelToMillimeterY: number; + height: SVGAnimatedLength; + onabort: (ev: UIEvent) => any; + contentScriptType: string; + pixelUnitToMillimeterX: number; + currentTranslate: SVGPoint; + onunload: (ev: Event) => any; + currentScale: number; + onscroll: (ev: UIEvent) => any; + screenPixelToMillimeterX: number; + setCurrentTime(seconds: number): void; + createSVGLength(): SVGLength; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeList; + unpauseAnimations(): void; + createSVGRect(): SVGRect; + checkIntersection(element: SVGElement, rect: SVGRect): boolean; + 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): boolean; + createSVGMatrix(): SVGMatrix; + createSVGPoint(): SVGPoint; + createSVGNumber(): SVGNumber; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; + getElementById(elementId: string): Element; +} +declare var SVGSVGElement: { + prototype: SVGSVGElement; + new (): SVGSVGElement; +} + +interface HTMLLabelElement extends HTMLElement, MSDataBindingExtensions { + /** + * Sets or retrieves the object to which the given label object is assigned. + */ + htmlFor: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + 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 HTMLLegendElement extends HTMLElement, MSDataBindingExtensions { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + align: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; +} +declare var HTMLLegendElement: { + prototype: HTMLLegendElement; + new (): HTMLLegendElement; +} + +interface HTMLDirectoryElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, DOML2DeprecatedListNumberingAndBulletStyle { +} +declare var HTMLDirectoryElement: { + prototype: HTMLDirectoryElement; + new (): HTMLDirectoryElement; +} + +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 { + /** + * Sets or retrieves the value of a list item. + */ + value: number; +} +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new (): HTMLLIElement; +} + +interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { + y: number; +} +declare var SVGPathSegLinetoVerticalAbs: { + prototype: SVGPathSegLinetoVerticalAbs; + new (): SVGPathSegLinetoVerticalAbs; +} + +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 MSHTMLCollectionExtensions { + urns(urn: any): Object; + tags(tagName: any): Object; +} + +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 HTMLIFrameElement extends HTMLElement, GetSVGDocument, MSDataBindingExtensions { + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + scrolling: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + marginWidth: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + noResize: boolean; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Retrieves the object of the specified. + */ + contentWindow: Window; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Retrieves the document object of the page or frame. + */ + contentDocument: Document; + /** + * Sets or retrieves the horizontal margin for the object. + */ + hspace: number; + /** + * Sets or retrieves a URI to a long description of the object. + */ + longDesc: string; + /** + * Sets the value indicating whether the source file of a frame or iframe has specific security restrictions applied. + */ + security: any; + /** + * Raised when the object has been completely received from the server. + */ + onload: (ev: Event) => any; +} +declare var HTMLIFrameElement: { + prototype: HTMLIFrameElement; + new (): HTMLIFrameElement; +} + +interface TextRangeCollection { + length: number; + item(index: number): TextRange; + [index: number]: TextRange; +} +declare var TextRangeCollection: { + prototype: TextRangeCollection; + new (): TextRangeCollection; +} + +interface HTMLBodyElement extends HTMLElement, DOML2DeprecatedBackgroundStyle, DOML2DeprecatedBackgroundColorStyle { + scroll: string; + ononline: (ev: Event) => any; + onblur: (ev: FocusEvent) => any; + noWrap: boolean; + onfocus: (ev: FocusEvent) => any; + onmessage: (ev: MessageEvent) => any; + text: any; + onerror: (ev: Event) => any; + bgProperties: string; + onresize: (ev: UIEvent) => any; + link: any; + aLink: any; + bottomMargin: any; + topMargin: any; + onafterprint: (ev: Event) => any; + vLink: any; + onbeforeprint: (ev: Event) => any; + onoffline: (ev: Event) => any; + onunload: (ev: Event) => any; + onhashchange: (ev: Event) => any; + onload: (ev: Event) => any; + rightMargin: any; + onbeforeunload: (ev: BeforeUnloadEvent) => any; + leftMargin: any; + onstorage: (ev: StorageEvent) => any; + createTextRange(): TextRange; +} +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 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: boolean, cancelableArg: boolean, 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: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; +} +declare var DragEvent: { + prototype: DragEvent; + new (): DragEvent; +} + +interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment, DOML2DeprecatedBackgroundColorStyle { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: HTMLCollection; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index?: number): void; + /** + * Moves a table row to a new position. + * @param indexFrom Number that specifies the index in the rows collection of the table row that is moved. + * @param indexTo Number that specifies where the row is moved within the rows collection. + */ + moveRow(indexFrom?: number, indexTo?: number): Object; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLElement; +} +declare var HTMLTableSectionElement: { + prototype: HTMLTableSectionElement; + new (): HTMLTableSectionElement; +} + +interface DOML2DeprecatedListNumberingAndBulletStyle { + type: string; +} + +interface HTMLInputElement extends HTMLElement, MSDataBindingExtensions { + /** + * Sets or retrieves the width of the object. + */ + width: string; + status: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + indeterminate: boolean; + readOnly: boolean; + size: number; + loop: number; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Sets or retrieves the URL of the virtual reality modeling language (VRML) world to be displayed in the window. + */ + vrml: string; + /** + * Sets or retrieves a lower resolution image to display. + */ + lowsrc: string; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Sets or retrieves a comma-separated list of content types. + */ + accept: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves the state of the check box or radio button. + */ + defaultChecked: boolean; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Returns the value of the data at the cursor's current position. + */ + value: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + border: string; + dynsrc: string; + /** + * Sets or retrieves the state of the check box or radio button. + */ + checked: boolean; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + hspace: number; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + /** + * Retrieves whether the object is fully loaded. + */ + complete: boolean; + start: string; + /** + * Creates a TextRange object for the element. + */ + createTextRange(): TextRange; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ + setSelectionRange(start: number, end: number): void; + /** + * Makes the selection equal to the current object. + */ + select(): void; +} +declare var HTMLInputElement: { + prototype: HTMLInputElement; + new (): HTMLInputElement; +} + +interface HTMLAnchorElement extends HTMLElement, MSDataBindingExtensions { + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + /** + * Contains the protocol of the URL. + */ + protocol: string; + /** + * Sets or retrieves the substring of the href property that follows the question mark. + */ + search: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + /** + * Contains the hostname of a URL. + */ + hostname: string; + /** + * Contains the pathname of the URL. + */ + pathname: string; + Methods: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + protocolLong: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the shape of the object. + */ + name: string; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; + /** + * Sets or retrieves the port number associated with a URL. + */ + port: string; + /** + * Contains the hostname and port values of the URL. + */ + host: string; + /** + * Contains the anchor portion of the URL including the hash sign (#). + */ + hash: string; + nameProp: string; + urn: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rev: string; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + type: string; + mimeType: string; + /** + * Returns a string representation of an object. + */ + toString(): string; +} +declare var HTMLAnchorElement: { + prototype: HTMLAnchorElement; + new (): HTMLAnchorElement; +} + +interface HTMLParamElement extends HTMLElement { + /** + * Sets or retrieves the value of an input parameter for an element. + */ + value: string; + /** + * Sets or retrieves the name of an input parameter for an element. + */ + name: string; + /** + * Sets or retrieves the content type of the resource designated by the value attribute. + */ + type: string; + /** + * Sets or retrieves the data type of the value attribute. + */ + valueType: string; +} +declare var HTMLParamElement: { + prototype: HTMLParamElement; + new (): HTMLParamElement; +} + +interface SVGImageElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired, SVGURIReference { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGImageElement: { + prototype: SVGImageElement; + new (): SVGImageElement; +} + +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 HTMLPreElement extends HTMLElement, DOML2DeprecatedTextFlowControl { + /** + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ + width: number; + /** + * Indicates a citation by rendering text in italic type. + */ + cite: string; +} +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 MSNavigatorDoNotTrack { + msDoNotTrack: string; +} + +interface NavigatorOnLine { + onLine: boolean; +} + +interface WindowLocalStorage { + localStorage: Storage; +} + +interface SVGMetadataElement extends SVGElement { +} +declare var SVGMetadataElement: { + prototype: SVGMetadataElement; + new (): SVGMetadataElement; +} + +interface SVGPathSegArcRel extends SVGPathSeg { + y: number; + sweepFlag: boolean; + r2: number; + x: number; + angle: number; + r1: number; + largeArcFlag: boolean; +} +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; + create(): XDomainRequest; + 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, SVGExternalResourcesRequired { +} +declare var SVGPolygonElement: { + prototype: SVGPolygonElement; + new (): SVGPolygonElement; +} + +interface HTMLPhraseElement extends HTMLElement { + /** + * Sets or retrieves the date and time of a modification to the object. + */ + dateTime: string; + /** + * Sets or retrieves reference information about the object. + */ + cite: string; +} +declare var HTMLPhraseElement: { + prototype: HTMLPhraseElement; + new (): HTMLPhraseElement; +} + +interface NavigatorStorageUtils { +} + +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 extends Event { + 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: boolean; + altLeft: boolean; + behaviorCookie: number; + bookmarks: BookmarkCollection; + type: string; + repeat: boolean; + srcElement: Element; + source: Window; + fromElement: Element; + offsetY: number; + x: number; + behaviorPart: number; + qualifier: string; + altKey: boolean; + ctrlKey: boolean; + clientY: number; + shiftKey: boolean; + shiftLeft: boolean; + contentOverflow: boolean; + screenY: number; + ctrlLeft: boolean; + 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): boolean; +} +declare var MSEventObj: { + prototype: MSEventObj; + new (): MSEventObj; +} + +interface SVGTextContentElement extends SVGElement, SVGStylable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { + 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 HTMLCanvasElement extends HTMLElement { + /** + * Gets or sets the width of a canvas element on a document. + */ + width: number; + /** + * Gets or sets the height of a canvas element on a document. + */ + height: number; + /** + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. + */ + toDataURL(type?: string, ...args: any[]): string; + /** + * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. + * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); + */ + getContext(contextId: "2d"): CanvasRenderingContext2D; + getContext(contextId: "experimental-webgl"): WebGLRenderingContext; + getContext(contextId: string, ...args: any[]): any; +} +declare var HTMLCanvasElement: { + prototype: HTMLCanvasElement; + new (): HTMLCanvasElement; +} + +interface Location { + hash: string; + protocol: string; + search: string; + href: string; + hostname: string; + port: string; + pathname: string; + host: string; + reload(flag?: boolean): void; + replace(url: string): void; + assign(url: string): void; + toString(): string; +} +declare var Location: { + prototype: Location; + new (): Location; +} + +interface HTMLTitleElement extends HTMLElement { + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; +} +declare var HTMLTitleElement: { + prototype: HTMLTitleElement; + new (): HTMLTitleElement; +} + +interface HTMLStyleElement extends HTMLElement, LinkStyle { + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Retrieves the CSS language in which the style sheet is written. + */ + type: string; +} +declare var HTMLStyleElement: { + prototype: HTMLStyleElement; + new (): HTMLStyleElement; +} + +interface PerformanceEntry { + name: string; + startTime: number; + duration: number; + entryType: string; +} +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new (): PerformanceEntry; +} + +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 UIEvent extends Event { + detail: number; + view: Window; + initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void; +} +declare var UIEvent: { + prototype: UIEvent; + new (): UIEvent; +} + +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: { + prototype: SVGPathSeg; + new (): 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: boolean, cancelableArg: boolean, viewArg: Window, 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 MSEventAttachmentTarget { + attachEvent(event: string, listener: EventListener): boolean; + 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, SVGExternalResourcesRequired { + 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: boolean, sweepFlag: boolean): 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: boolean, sweepFlag: boolean): SVGPathSegArcAbs; +} +declare var SVGPathElement: { + prototype: SVGPathElement; + new (): SVGPathElement; +} + +interface MSCompatibleInfo { + version: string; + userAgent: string; +} +declare var MSCompatibleInfo: { + prototype: MSCompatibleInfo; + new (): MSCompatibleInfo; +} + +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 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 HTMLUnknownElement extends HTMLElement, MSDataBindingRecordSetReadonlyExtensions { +} +declare var HTMLUnknownElement: { + prototype: HTMLUnknownElement; + new (): HTMLUnknownElement; +} + +interface HTMLAudioElement extends HTMLMediaElement { +} +declare var HTMLAudioElement: { + prototype: HTMLAudioElement; + new (): HTMLAudioElement; +} + +interface MSImageResourceExtensions { + dynsrc: string; + vrml: string; + lowsrc: string; + start: string; + loop: number; +} + +interface PositionError { + code: number; + message: string; + toString(): string; + POSITION_UNAVAILABLE: number; + PERMISSION_DENIED: number; + TIMEOUT: number; +} +declare var PositionError: { + prototype: PositionError; + new (): PositionError; + POSITION_UNAVAILABLE: number; + PERMISSION_DENIED: number; + TIMEOUT: number; +} + +interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment, DOML2DeprecatedBackgroundStyle, DOML2DeprecatedBackgroundColorStyle { + /** + * Sets or retrieves the width of the object. + */ + width: number; + /** + * Sets or retrieves a list of header cells that provide information for the object. + */ + headers: string; + /** + * Retrieves the position of the object in the cells collection of a row. + */ + cellIndex: number; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves the color for one of the two colors used to draw the 3-D border of the object. + */ + borderColorLight: any; + /** + * Sets or retrieves the number columns in the table that the object should span. + */ + colSpan: number; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ + axis: string; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; + /** + * Sets or retrieves abbreviated text for the object. + */ + abbr: string; + /** + * Sets or retrieves how many rows in a table the cell should span. + */ + rowSpan: number; + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; + /** + * Sets or retrieves the color for one of the two colors used to draw the 3-D border of the object. + */ + borderColorDark: any; +} +declare var HTMLTableCellElement: { + prototype: HTMLTableCellElement; + new (): HTMLTableCellElement; +} + +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 MSNamespaceInfoCollection { + length: number; + add(namespace?: string, urn?: string, implementationUrl?: any): Object; + item(index: any): Object; + [index: string]: Object; +} +declare var MSNamespaceInfoCollection: { + prototype: MSNamespaceInfoCollection; + new (): MSNamespaceInfoCollection; +} + +interface SVGCircleElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { + cx: SVGAnimatedLength; + r: SVGAnimatedLength; + cy: SVGAnimatedLength; +} +declare var SVGCircleElement: { + prototype: SVGCircleElement; + new (): SVGCircleElement; +} + +interface StyleSheetList { + length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; +} +declare var StyleSheetList: { + prototype: StyleSheetList; + new (): StyleSheetList; +} + +interface CSSImportRule extends CSSRule { + styleSheet: CSSStyleSheet; + href: string; + media: MediaList; +} +declare var CSSImportRule: { + prototype: CSSImportRule; + new (): CSSImportRule; +} + +interface CustomEvent extends Event { + detail: any; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; +} +declare var CustomEvent: { + prototype: CustomEvent; + new (): CustomEvent; +} + +interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { + /** + * Sets or retrieves the current typeface family. + */ + face: string; + /** + * Sets or retrieves the font size of the object. + */ + size: number; +} +declare var HTMLBaseFontElement: { + prototype: HTMLBaseFontElement; + new (): HTMLBaseFontElement; +} + +interface HTMLTextAreaElement extends HTMLElement, MSDataBindingExtensions { + /** + * Retrieves or sets the text in the entry field of the textArea element. + */ + value: string; + /** + * Sets or retrieves the value indicating whether the control is selected. + */ + status: any; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: number; + /** + * Sets or retrieves the width of the object. + */ + cols: number; + /** + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ + readOnly: boolean; + /** + * Sets or retrieves how to handle wordwrapping in the object. + */ + wrap: string; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Retrieves the type of control. + */ + type: string; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + /** + * Creates a TextRange object for the element. + */ + createTextRange(): TextRange; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ + setSelectionRange(start: number, end: number): void; + /** + * Highlights the input area of a form element. + */ + select(): void; +} +declare var HTMLTextAreaElement: { + prototype: HTMLTextAreaElement; + new (): HTMLTextAreaElement; +} + +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 DOML2DeprecatedMarginStyle { + vspace: number; + hspace: number; +} + +interface MSWindowModeless { + dialogTop: any; + dialogLeft: any; + dialogWidth: any; + dialogHeight: any; + menuArguments: any; +} + +interface DOML2DeprecatedAlignmentStyle { + align: string; +} + +interface HTMLMarqueeElement extends HTMLElement, MSDataBindingExtensions, DOML2DeprecatedBackgroundColorStyle { + width: string; + onbounce: (ev: Event) => any; + vspace: number; + trueSpeed: boolean; + scrollAmount: number; + scrollDelay: number; + behavior: string; + height: string; + loop: number; + direction: string; + hspace: number; + 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?: boolean): Node; + replaceNode(replacement: Node): Node; +} + +interface History { + length: number; + back(distance?: any): void; + forward(distance?: any): void; + go(delta?: any): void; +} +declare var History: { + prototype: History; + new (): History; +} + +interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { + y: number; + y1: number; + x2: number; + x: number; + x1: number; + y2: number; +} +declare var SVGPathSegCurvetoCubicAbs: { + prototype: SVGPathSegCurvetoCubicAbs; + new (): SVGPathSegCurvetoCubicAbs; +} + +interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { + y: number; + y1: number; + x: number; + x1: number; +} +declare var SVGPathSegCurvetoQuadraticAbs: { + prototype: SVGPathSegCurvetoQuadraticAbs; + new (): SVGPathSegCurvetoQuadraticAbs; +} + +interface TimeRanges { + length: number; + start(index: number): number; + end(index: number): number; +} +declare var TimeRanges: { + prototype: TimeRanges; + new (): TimeRanges; +} + +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 HTMLModElement extends HTMLElement { + /** + * Sets or retrieves the date and time of a modification to the object. + */ + dateTime: string; + /** + * Sets or retrieves reference information about the object. + */ + cite: string; +} +declare var HTMLModElement: { + prototype: HTMLModElement; + new (): HTMLModElement; +} + +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 MSPopupWindow { + document: Document; + isOpen: boolean; + show(x: number, y: number, w: number, h: number, element?: any): void; + hide(): void; +} +declare var MSPopupWindow: { + prototype: MSPopupWindow; + new (): MSPopupWindow; +} + +interface BeforeUnloadEvent extends Event { + returnValue: string; +} +declare var BeforeUnloadEvent: { + prototype: BeforeUnloadEvent; + new (): BeforeUnloadEvent; +} + +interface SVGUseElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired, SVGURIReference { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + animatedInstanceRoot: SVGElementInstance; + instanceRoot: SVGElementInstance; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGUseElement: { + prototype: SVGUseElement; + new (): SVGUseElement; +} + +interface Event { + timeStamp: number; + defaultPrevented: boolean; + isTrusted: boolean; + currentTarget: EventTarget; + cancelBubble: boolean; + target: EventTarget; + eventPhase: number; + cancelable: boolean; + type: string; + srcElement: Element; + bubbles: boolean; + initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): 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: Uint8Array; + height: number; +} +declare var ImageData: { + prototype: ImageData; + new (): ImageData; +} + +interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves the width of the object. + */ + width: any; + /** + * Sets or retrieves the alignment of the object relative to the display or table. + */ + align: string; + /** + * Sets or retrieves the number of columns in the group. + */ + span: number; +} +declare var HTMLTableColElement: { + prototype: HTMLTableColElement; + new (): HTMLTableColElement; +} + +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 SVGLinearGradientElement extends SVGGradientElement { + y1: SVGAnimatedLength; + x2: SVGAnimatedLength; + x1: SVGAnimatedLength; + y2: SVGAnimatedLength; +} +declare var SVGLinearGradientElement: { + prototype: SVGLinearGradientElement; + new (): SVGLinearGradientElement; +} + +interface HTMLTableAlignment { + /** + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ + ch: string; + /** + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ + vAlign: string; + /** + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ + chOff: string; +} + +interface SVGAnimatedEnumeration { + animVal: number; + baseVal: number; +} +declare var SVGAnimatedEnumeration: { + prototype: SVGAnimatedEnumeration; + new (): SVGAnimatedEnumeration; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface HTMLUListElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, DOML2DeprecatedListNumberingAndBulletStyle { +} +declare var HTMLUListElement: { + prototype: HTMLUListElement; + new (): HTMLUListElement; +} + +interface SVGRectElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + ry: SVGAnimatedLength; + rx: SVGAnimatedLength; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGRectElement: { + prototype: SVGRectElement; + new (): SVGRectElement; +} + +interface ErrorEventHandler { + (event: Event, source: string, fileno: number, columnNumber: number): void; + (message: any, uri: string, lineNumber: number, columnNumber?: number): void; +} + +interface HTMLDivElement extends HTMLElement, MSDataBindingExtensions { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; +} +declare var HTMLDivElement: { + prototype: HTMLDivElement; + new (): HTMLDivElement; +} + +interface DOML2DeprecatedBorderStyle { + border: string; +} + +interface NamedNodeMap { + length: number; + removeNamedItemNS(namespaceURI: string, localName: string): Attr; + item(index: number): Attr; + [index: number]: Attr; + removeNamedItem(name: string): Attr; + getNamedItem(name: string): Attr; + setNamedItem(arg: Attr): Attr; + getNamedItemNS(namespaceURI: string, localName: string): Attr; + setNamedItemNS(arg: Attr): Attr; +} +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 SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { + y: number; + x2: number; + x: number; + y2: number; +} +declare var SVGPathSegCurvetoCubicSmoothRel: { + prototype: SVGPathSegCurvetoCubicSmoothRel; + new (): SVGPathSegCurvetoCubicSmoothRel; +} + +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 ProcessingInstruction extends Node { + target: string; + data: string; +} +declare var ProcessingInstruction: { + prototype: ProcessingInstruction; + new (): ProcessingInstruction; +} + +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: boolean; + onhelp: (ev: Event) => any; + external: External; + 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 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: boolean, cancelableArg: boolean, viewArg: Window, 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 DocumentFragment extends Node, NodeSelector, MSEventAttachmentTarget, MSNodeExtensions { +} +declare var DocumentFragment: { + prototype: DocumentFragment; + new (): DocumentFragment; +} + +interface SVGPolylineElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGAnimatedPoints, SVGTests, SVGExternalResourcesRequired { +} +declare var SVGPolylineElement: { + prototype: SVGPolylineElement; + new (): SVGPolylineElement; +} + +interface SVGAnimatedPathData { + pathSegList: SVGPathSegList; +} + +interface Position { + timestamp: number; + 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 PerformanceMark extends PerformanceEntry { +} +declare var PerformanceMark: { + prototype: PerformanceMark; + new (): PerformanceMark; +} + +interface CSSPageRule extends CSSRule { + pseudoClass: string; + selectorText: string; + selector: string; + style: CSSStyleDeclaration; +} +declare var CSSPageRule: { + prototype: CSSPageRule; + new (): CSSPageRule; +} + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; +} +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new (): HTMLBRElement; +} + +interface MSNavigatorExtensions { + userLanguage: string; + plugins: MSPluginsCollection; + cookieEnabled: boolean; + appCodeName: string; + cpuClass: string; + appMinorVersion: string; + connectionSpeed: number; + browserLanguage: string; + mimeTypes: MSMimeTypesCollection; + systemLanguage: string; + javaEnabled(): boolean; + taintEnabled(): boolean; +} + +interface HTMLSpanElement extends HTMLElement, MSDataBindingExtensions { +} +declare var HTMLSpanElement: { + prototype: HTMLSpanElement; + new (): HTMLSpanElement; +} + +interface HTMLHeadElement extends HTMLElement { + profile: string; +} +declare var HTMLHeadElement: { + prototype: HTMLHeadElement; + new (): HTMLHeadElement; +} + +interface HTMLHeadingElement extends HTMLElement, DOML2DeprecatedTextFlowControl { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; +} +declare var HTMLHeadingElement: { + prototype: HTMLHeadingElement; + new (): HTMLHeadingElement; +} + +interface HTMLFormElement extends HTMLElement, MSHTMLCollectionExtensions { + /** + * Sets or retrieves the number of objects in a collection. + */ + length: number; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ + acceptCharset: string; + /** + * Sets or retrieves the encoding type for the form. + */ + enctype: string; + /** + * Retrieves a collection, in source order, of all controls in a given form. + */ + elements: HTMLCollection; + /** + * Sets or retrieves the URL to which the form content is sent for processing. + */ + action: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Sets or retrieves how to send the form data to the server. + */ + method: string; + /** + * Sets or retrieves the MIME encoding for the form. + */ + encoding: string; + /** + * Fires when the user resets a form. + */ + reset(): void; + /** + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(name?: any, index?: any): any; + /** + * Fires when a FORM is about to be submitted. + */ + submit(): void; + /** + * Retrieves a form object or an object from an elements collection. + */ + namedItem(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 HTMLMediaElement extends HTMLElement { + /** + * Gets the earliest possible position, in seconds, that the playback can begin. + */ + initialTime: number; + /** + * Gets TimeRanges for the current media resource that has been played. + */ + played: TimeRanges; + /** + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ + currentSrc: string; + readyState: any; + /** + * The autobuffer element is not supported by Internet Explorer 9. Use the preload element instead. + */ + autobuffer: boolean; + /** + * Gets or sets a flag to specify whether playback should restart after it completes. + */ + loop: boolean; + /** + * Gets information about whether the playback has ended or not. + */ + ended: boolean; + /** + * Gets a collection of buffered time ranges. + */ + buffered: TimeRanges; + /** + * Returns an object representing the current error state of the audio or video element. + */ + error: MediaError; + /** + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ + seekable: TimeRanges; + /** + * Gets or sets a value that indicates whether to start playing the media automatically. + */ + autoplay: boolean; + /** + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ + controls: boolean; + /** + * Gets or sets the volume level for audio portions of the media element. + */ + volume: number; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + /** + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ + playbackRate: number; + /** + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ + duration: number; + /** + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ + muted: boolean; + /** + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ + defaultPlaybackRate: number; + /** + * Gets a flag that specifies whether playback is paused. + */ + paused: boolean; + /** + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ + seeking: boolean; + /** + * Gets or sets the current playback position, in seconds. + */ + currentTime: number; + /** + * Gets or sets the current playback position, in seconds. + */ + preload: string; + /** + * Gets the current network activity for the element. + */ + networkState: number; + /** + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ + pause(): void; + /** + * Loads and starts playback of a media resource. + */ + play(): void; + /** + * Fires immediately after the client loads the object. + */ + load(): void; + /** + * Returns a string that specifies whether the client can play a given media resource type. + */ + 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 { + runtimeStyle: MSStyleCSSProperties; + currentStyle: MSCurrentStyleCSSProperties; + doScroll(component?: any): void; + componentFromPoint(x: number, y: number): string; +} + +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: boolean; + ownerNode: Node; + parentStyleSheet: StyleSheet; + href: string; + media: MediaList; + type: string; + title: string; +} +declare var StyleSheet: { + prototype: StyleSheet; + new (): StyleSheet; +} + +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 HTMLDTElement extends HTMLElement { + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; +} +declare var HTMLDTElement: { + prototype: HTMLDTElement; + new (): HTMLDTElement; +} + +interface NodeList { + length: number; + item(index: number): Node; + [index: number]: Node; +} +declare var NodeList: { + prototype: NodeList; + new (): NodeList; +} + +interface NodeListOf extends NodeList { + length: number; + item(index: number): TNode; + [index: number]: TNode; +} + +interface XMLSerializer { + serializeToString(target: Node): string; +} +declare var XMLSerializer: { + prototype: XMLSerializer; + new (): XMLSerializer; +} + +interface PerformanceMeasure extends PerformanceEntry { +} +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new (): PerformanceMeasure; +} + +interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGExternalResourcesRequired, 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 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 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 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 HTMLFieldSetElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; +} +declare var HTMLFieldSetElement: { + prototype: HTMLFieldSetElement; + new (): HTMLFieldSetElement; +} + +interface HTMLBGSoundElement extends HTMLElement { + /** + * Sets or gets the value indicating how the volume of the background sound is divided between the left speaker and the right speaker. + */ + balance: any; + /** + * Sets or gets the volume setting for the sound. + */ + volume: any; + /** + * Sets or gets the URL of a sound to play. + */ + src: string; + /** + * Sets or retrieves the number of times a sound or video clip will loop when activated. + */ + loop: number; +} +declare var HTMLBGSoundElement: { + prototype: HTMLBGSoundElement; + new (): HTMLBGSoundElement; +} + +interface HTMLElement extends Element, ElementCSSInlineStyle, MSEventAttachmentTarget, MSNodeExtensions { + onmouseleave: (ev: MouseEvent) => any; + onbeforecut: (ev: DragEvent) => any; + onkeydown: (ev: KeyboardEvent) => any; + onmove: (ev: MSEventObj) => any; + onkeyup: (ev: KeyboardEvent) => any; + onreset: (ev: Event) => any; + onhelp: (ev: Event) => any; + ondragleave: (ev: DragEvent) => any; + className: string; + onfocusin: (ev: FocusEvent) => any; + onseeked: (ev: Event) => any; + recordNumber: any; + title: string; + parentTextEdit: Element; + outerHTML: string; + ondurationchange: (ev: Event) => any; + offsetHeight: number; + all: HTMLCollection; + onblur: (ev: FocusEvent) => any; + dir: string; + onemptied: (ev: Event) => any; + onseeking: (ev: Event) => any; + oncanplay: (ev: Event) => any; + ondeactivate: (ev: UIEvent) => any; + ondatasetchanged: (ev: MSEventObj) => any; + onrowsdelete: (ev: MSEventObj) => any; + sourceIndex: number; + onloadstart: (ev: Event) => any; + onlosecapture: (ev: MSEventObj) => any; + ondragenter: (ev: DragEvent) => any; + oncontrolselect: (ev: MSEventObj) => any; + onsubmit: (ev: Event) => any; + behaviorUrns: MSBehaviorUrnsCollection; + scopeName: string; + onchange: (ev: Event) => any; + id: string; + onlayoutcomplete: (ev: MSEventObj) => any; + uniqueID: string; + onbeforeactivate: (ev: UIEvent) => any; + oncanplaythrough: (ev: Event) => any; + onbeforeupdate: (ev: MSEventObj) => any; + onfilterchange: (ev: MSEventObj) => any; + offsetParent: Element; + ondatasetcomplete: (ev: MSEventObj) => any; + onsuspend: (ev: Event) => any; + readyState: any; + onmouseenter: (ev: MouseEvent) => any; + innerText: string; + onerrorupdate: (ev: MSEventObj) => any; + onmouseout: (ev: MouseEvent) => any; + parentElement: HTMLElement; + onmousewheel: (ev: MouseWheelEvent) => any; + onvolumechange: (ev: Event) => any; + oncellchange: (ev: MSEventObj) => any; + onrowexit: (ev: MSEventObj) => any; + onrowsinserted: (ev: MSEventObj) => any; + onpropertychange: (ev: MSEventObj) => any; + filters: Object; + children: HTMLCollection; + ondragend: (ev: DragEvent) => any; + onbeforepaste: (ev: DragEvent) => any; + ondragover: (ev: DragEvent) => any; + offsetTop: number; + onmouseup: (ev: MouseEvent) => any; + ondragstart: (ev: DragEvent) => any; + onbeforecopy: (ev: DragEvent) => any; + ondrag: (ev: DragEvent) => any; + innerHTML: string; + onmouseover: (ev: MouseEvent) => any; + lang: string; + uniqueNumber: number; + onpause: (ev: Event) => any; + tagUrn: string; + onmousedown: (ev: MouseEvent) => any; + onclick: (ev: MouseEvent) => any; + onwaiting: (ev: Event) => any; + onresizestart: (ev: MSEventObj) => any; + offsetLeft: number; + isTextEdit: boolean; + isDisabled: boolean; + onpaste: (ev: DragEvent) => any; + canHaveHTML: boolean; + onmoveend: (ev: MSEventObj) => any; + language: string; + onstalled: (ev: Event) => any; + onmousemove: (ev: MouseEvent) => any; + style: MSStyleCSSProperties; + isContentEditable: boolean; + onbeforeeditfocus: (ev: MSEventObj) => any; + onratechange: (ev: Event) => any; + contentEditable: string; + tabIndex: number; + document: Document; + onprogress: (ev: any) => any; + ondblclick: (ev: MouseEvent) => any; + oncontextmenu: (ev: MouseEvent) => any; + onloadedmetadata: (ev: Event) => any; + onafterupdate: (ev: MSEventObj) => any; + onerror: (ev: Event) => any; + onplay: (ev: Event) => any; + onresizeend: (ev: MSEventObj) => any; + onplaying: (ev: Event) => any; + isMultiLine: boolean; + onfocusout: (ev: FocusEvent) => any; + onabort: (ev: UIEvent) => any; + ondataavailable: (ev: MSEventObj) => any; + hideFocus: boolean; + onreadystatechange: (ev: Event) => any; + onkeypress: (ev: KeyboardEvent) => any; + onloadeddata: (ev: Event) => any; + onbeforedeactivate: (ev: UIEvent) => any; + outerText: string; + disabled: boolean; + onactivate: (ev: UIEvent) => any; + accessKey: string; + onmovestart: (ev: MSEventObj) => any; + onselectstart: (ev: Event) => any; + onfocus: (ev: FocusEvent) => any; + ontimeupdate: (ev: Event) => any; + onresize: (ev: UIEvent) => any; + oncut: (ev: DragEvent) => any; + onselect: (ev: UIEvent) => any; + ondrop: (ev: DragEvent) => any; + offsetWidth: number; + oncopy: (ev: DragEvent) => any; + onended: (ev: Event) => any; + onscroll: (ev: UIEvent) => any; + onrowenter: (ev: MSEventObj) => any; + onload: (ev: Event) => any; + canHaveChildren: boolean; + oninput: (ev: Event) => any; + dragDrop(): boolean; + scrollIntoView(top?: boolean): void; + addFilter(filter: Object): void; + setCapture(containerCapture?: boolean): void; + focus(): void; + getAdjacentText(where: string): string; + insertAdjacentText(where: string, text: string): void; + getElementsByClassName(classNames: string): NodeList; + setActive(): void; + removeFilter(filter: Object): void; + blur(): void; + clearAttributes(): void; + releaseCapture(): void; + createControlRange(): ControlRangeCollection; + removeBehavior(cookie: number): boolean; + contains(child: HTMLElement): boolean; + click(): void; + insertAdjacentElement(position: string, insertedElement: Element): Element; + mergeAttributes(source: HTMLElement, preserveIdentity?: boolean): void; + replaceAdjacentText(where: string, newText: string): string; + applyElement(apply: Element, where?: string): Element; + addBehavior(bstrUrl: string, factory?: any): number; + insertAdjacentHTML(where: string, html: string): void; +} +declare var HTMLElement: { + prototype: HTMLElement; + new (): HTMLElement; +} + +interface Comment extends CharacterData { + text: string; +} +declare var Comment: { + prototype: Comment; + new (): Comment; +} + +interface PerformanceResourceTiming extends PerformanceEntry { + redirectStart: number; + redirectEnd: number; + domainLookupEnd: number; + responseStart: number; + domainLookupStart: number; + fetchStart: number; + requestStart: number; + connectEnd: number; + connectStart: number; + initiatorType: string; + responseEnd: number; +} +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new (): PerformanceResourceTiming; +} + +interface CanvasPattern { +} +declare var CanvasPattern: { + prototype: CanvasPattern; + new (): CanvasPattern; +} + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves the width of the object. + */ + width: number; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; +} +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new (): HTMLHRElement; +} + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument, DOML2DeprecatedMarginStyle, DOML2DeprecatedBorderStyle, DOML2DeprecatedAlignmentStyle, MSDataBindingExtensions, MSDataBindingRecordSetExtensions { + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the contained object. + */ + object: Object; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves the class identifier for the object. + */ + classid: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Retrieves the document object of the page or frame. + */ + contentDocument: Document; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + declare: boolean; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + BaseHref: string; +} +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new (): HTMLObjectElement; +} + +interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Retrieves the palette used for the embedded document. + */ + palette: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Retrieves the URL of the plug-in used to view an embedded document. + */ + pluginspage: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves the height and width units of the embed object. + */ + units: string; +} +declare var HTMLEmbedElement: { + prototype: HTMLEmbedElement; + new (): HTMLEmbedElement; +} + +interface StorageEvent extends Event { + oldValue: any; + newValue: any; + url: string; + storageArea: Storage; + key: string; + initStorageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, keyArg: string, oldValueArg: any, newValueArg: any, urlArg: string, storageAreaArg: Storage): void; +} +declare var StorageEvent: { + prototype: StorageEvent; + new (): StorageEvent; +} + +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 HTMLOptGroupElement extends HTMLElement, MSDataBindingExtensions { + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + index: number; + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + /** + * Sets or retrieves the text string specified by the option tag. + */ + text: string; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; +} +declare var HTMLOptGroupElement: { + prototype: HTMLOptGroupElement; + new (): HTMLOptGroupElement; +} + +interface HTMLIsIndexElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the URL to which the form content is sent for processing. + */ + action: string; + 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 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 SVGAnimatedBoolean { + animVal: boolean; + baseVal: boolean; +} +declare var SVGAnimatedBoolean: { + prototype: SVGAnimatedBoolean; + new (): SVGAnimatedBoolean; +} + +interface MSCompatibleInfoCollection { + length: number; + item(index: number): MSCompatibleInfo; +} +declare var MSCompatibleInfoCollection: { + prototype: MSCompatibleInfoCollection; + new (): MSCompatibleInfoCollection; +} + +interface SVGSwitchElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { +} +declare var SVGSwitchElement: { + prototype: SVGSwitchElement; + new (): SVGSwitchElement; +} + +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 { + expando: boolean; + specified: boolean; + ownerElement: Element; + value: string; + name: string; +} +declare var Attr: { + prototype: Attr; + new (): Attr; +} + +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 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, SVGExternalResourcesRequired { +} +declare var SVGSymbolElement: { + prototype: SVGSymbolElement; + new (): SVGSymbolElement; +} + +interface SVGElementInstanceList { + length: number; + item(index: number): SVGElementInstance; +} +declare var SVGElementInstanceList: { + prototype: SVGElementInstanceList; + new (): SVGElementInstanceList; +} + +interface CSSRuleList { + length: number; + item(index: number): CSSRule; + [index: number]: CSSRule; +} +declare var CSSRuleList: { + prototype: CSSRuleList; + new (): CSSRuleList; +} + +interface MSDataBindingRecordSetExtensions { + recordset: Object; + namedRecordset(dataMember: string, hierarchy?: any): Object; +} + +interface LinkStyle { + styleSheet: StyleSheet; + sheet: StyleSheet; +} + +interface HTMLVideoElement extends HTMLMediaElement { + /** + * Gets or sets the width of the video element. + */ + width: number; + /** + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ + videoWidth: number; + /** + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ + videoHeight: number; + /** + * Gets or sets the height of the video element. + */ + height: number; + /** + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ + poster: string; +} +declare var HTMLVideoElement: { + prototype: HTMLVideoElement; + new (): HTMLVideoElement; +} + +interface ClientRectList { + length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} +declare var ClientRectList: { + prototype: ClientRectList; + new (): ClientRectList; +} + +interface SVGMaskElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGTests, SVGExternalResourcesRequired { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + maskUnits: SVGAnimatedEnumeration; + maskContentUnits: SVGAnimatedEnumeration; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGMaskElement: { + prototype: SVGMaskElement; + new (): SVGMaskElement; +} + +interface External { +} +declare var External: { + prototype: External; + new (): External; +} + +declare var Audio: { new (src?: string): HTMLAudioElement; }; +declare var Option: { new (text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): 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 screenX: number; +declare var onmouseover: (ev: MouseEvent) => any; +declare var ondragleave: (ev: DragEvent) => any; +declare var history: History; +declare var pageXOffset: number; +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 innerHeight: number; +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 outerWidth: number; +declare var onstalled: (ev: Event) => any; +declare var onmousemove: (ev: MouseEvent) => any; +declare var innerWidth: number; +declare var onoffline: (ev: Event) => any; +declare var length: number; +declare var screen: Screen; +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 document: Document; +declare var onprogress: (ev: any) => any; +declare var ondblclick: (ev: MouseEvent) => any; +declare var pageYOffset: number; +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: ErrorEventHandler; +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 outerHeight: number; +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 onselect: (ev: UIEvent) => any; +declare var navigator: Navigator; +declare var styleMedia: StyleMedia; +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 screenY: number; +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 var performance: Performance; +declare function alert(message?: any): void; +declare function scroll(x?: number, y?: number): void; +declare function focus(): void; +declare function scrollTo(x?: number, y?: number): 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?: boolean): Window; +declare function scrollBy(x?: number, y?: number): void; +declare function confirm(message?: string): boolean; +declare function close(): void; +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 removeEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +declare function dispatchEvent(evt: Event): boolean; +declare function attachEvent(event: string, listener: EventListener): boolean; +declare function detachEvent(event: string, listener: EventListener): void; +declare var localStorage: Storage; +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: boolean; +declare var onhelp: (ev: Event) => any; +declare var external: External; +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 sessionStorage: Storage; +declare function clearTimeout(handle: number): void; +declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; +declare function clearInterval(handle: number): void; +declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; + + +///////////////////////////// +/// IE10 DOM APIs +///////////////////////////// + + +interface ObjectURLOptions { + oneTimeOnly?: boolean; +} + +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: boolean, cancelableArg: boolean, viewArg: Window, 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: { + MSGESTURE_FLAG_BEGIN: number; + MSGESTURE_FLAG_END: number; + MSGESTURE_FLAG_CANCEL: number; + MSGESTURE_FLAG_INERTIA: number; + MSGESTURE_FLAG_NONE: number; +} + +interface HTMLAnchorElement { + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; +} + +interface HTMLInputElement { + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Returns a FileList object on a file type input object. + */ + files: FileList; + /** + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ + max: string; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ + step: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Returns the input field value as a number. + */ + valueAsNumber: number; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Specifies the ID of a pre-defined datalist of options for an input element. + */ + list: HTMLElement; + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ + min: string; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Gets or sets a string containing a regular expression that the user's input must match. + */ + pattern: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: string; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ + stepDown(n?: number): void; + /** + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ + stepUp(n?: number): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; +} + +interface ErrorEvent extends Event { + colno: number; + filename: string; + error: any; + lineno: number; + message: string; + initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; +} + +interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + filterResX: SVGAnimatedInteger; + filterUnits: SVGAnimatedEnumeration; + primitiveUnits: SVGAnimatedEnumeration; + x: SVGAnimatedLength; + height: SVGAnimatedLength; + filterResY: SVGAnimatedInteger; + setFilterRes(filterResX: number, filterResY: number): void; +} + +interface TrackEvent extends Event { + track: any; +} + +interface SVGFEMergeNodeElement extends SVGElement { + in1: SVGAnimatedString; +} + +interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { +} + +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: boolean; + id: string; + startTime: number; + onexit: (ev: Event) => any; + getCueAsHTML(): DocumentFragment; +} +declare var TextTrackCue: { + prototype: TextTrackCue; + new (): TextTrackCue; +} + +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 DOMTokenList { + length: number; + contains(token: string): boolean; + remove(token: string): void; + toggle(token: string): boolean; + add(token: string): void; + item(index: number): string; + [index: number]: string; + toString(): string; +} + +interface EventException { + name: string; +} + +interface Performance { + now(): number; +} + +interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { +} + +interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; +} + +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: { + 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 { +} + +interface CSSStyleDeclaration { + animationFillMode: string; + floodColor: string; + animationIterationCount: string; + textShadow: string; + backfaceVisibility: string; + msAnimationIterationCount: string; + animationDelay: string; + animationTimingFunction: string; + columnWidth: any; + msScrollSnapX: string; + columnRuleColor: any; + columnRuleWidth: any; + transitionDelay: string; + transition: string; + msFlowFrom: string; + msScrollSnapType: string; + msContentZoomSnapType: string; + msGridColumns: string; + msAnimationName: string; + msGridRowAlign: string; + msContentZoomChaining: string; + msGridColumn: any; + msHyphenateLimitZone: any; + msScrollRails: string; + msAnimationDelay: string; + enableBackground: string; + msWrapThrough: string; + columnRuleStyle: string; + msAnimation: string; + msFlexFlow: string; + msScrollSnapY: string; + msHyphenateLimitLines: any; + msTouchAction: string; + msScrollLimit: string; + animation: string; + transform: string; + filter: string; + colorInterpolationFilters: string; + transitionTimingFunction: string; + msBackfaceVisibility: string; + animationPlayState: string; + transformOrigin: string; + msScrollLimitYMin: any; + msFontFeatureSettings: string; + msContentZoomLimitMin: any; + columnGap: any; + transitionProperty: string; + msAnimationDuration: string; + msAnimationFillMode: string; + msFlexDirection: string; + msTransitionDuration: string; + fontFeatureSettings: string; + breakBefore: string; + msFlexWrap: string; + perspective: string; + msFlowInto: string; + msTransformStyle: string; + msScrollTranslation: string; + msTransitionProperty: string; + msUserSelect: string; + msOverflowStyle: string; + msScrollSnapPointsY: string; + animationDirection: string; + animationDuration: string; + msFlex: string; + msTransitionTimingFunction: string; + animationName: string; + columnRule: string; + msGridColumnSpan: any; + msFlexNegative: string; + columnFill: string; + msGridRow: any; + msFlexOrder: string; + msFlexItemAlign: string; + msFlexPositive: string; + msContentZoomLimitMax: any; + msScrollLimitYMax: any; + msGridColumnAlign: string; + perspectiveOrigin: string; + lightingColor: string; + columns: string; + msScrollChaining: string; + msHyphenateLimitChars: string; + msTouchSelect: string; + floodOpacity: string; + msAnimationDirection: string; + msAnimationPlayState: string; + columnSpan: string; + msContentZooming: string; + msPerspective: string; + msFlexPack: string; + msScrollSnapPointsX: string; + msContentZoomSnapPoints: string; + msGridRowSpan: any; + msContentZoomSnap: string; + msScrollLimitXMin: any; + breakInside: string; + msHighContrastAdjust: string; + msFlexLinePack: string; + msGridRows: string; + transitionDuration: string; + msHyphens: string; + breakAfter: string; + msTransition: string; + msPerspectiveOrigin: string; + msContentZoomLimit: string; + msScrollLimitXMax: any; + msFlexAlign: string; + msWrapMargin: any; + columnCount: any; + msAnimationTimingFunction: string; + msTransitionDelay: string; + transformStyle: string; + msWrapFlow: string; + msFlexPreferredSize: string; +} + +interface MessageChannel { + port2: MessagePort; + port1: MessagePort; +} +declare var MessageChannel: { + prototype: MessageChannel; + new (): MessageChannel; +} + +interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { +} + +interface Navigator extends MSFileSaver { + msMaxTouchPoints: number; + msPointerEnabled: boolean; + msManipulationViewsEnabled: boolean; + msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; +} + +interface TransitionEvent extends Event { + propertyName: string; + elapsedTime: number; + initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void; +} + +interface MediaQueryList { + matches: boolean; + media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +interface DOMError { + name: string; + toString(): string; +} + +interface CloseEvent extends Event { + wasClean: boolean; + reason: string; + code: number; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +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 SVGFEPointLightElement extends SVGElement { + y: SVGAnimatedNumber; + x: SVGAnimatedNumber; + z: SVGAnimatedNumber; +} + +interface ProgressEvent extends Event { + loaded: number; + lengthComputable: boolean; + total: number; + initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; +} + +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; + delete(key: any): IDBRequest; +} + +interface HTMLCanvasElement { + /** + * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. + */ + msToBlob(): Blob; +} + +interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + stdDeviationX: SVGAnimatedNumber; + in1: SVGAnimatedString; + stdDeviationY: SVGAnimatedNumber; + setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; +} + +interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + height: SVGAnimatedLength; + result: SVGAnimatedString; +} + +interface Element { + 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; +} + +interface IDBVersionChangeEvent extends Event { + newVersion: number; + oldVersion: number; +} + +interface IDBIndex { + unique: boolean; + 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; +} + +interface WheelEvent { + getCurrentPoint(element: Element): void; +} + +interface FileList { + length: number; + item(index: number): File; + [index: number]: File; +} + +interface IDBCursor { + source: any; + direction: string; + key: any; + primaryKey: any; + advance(count: number): void; + delete(): IDBRequest; + continue(key?: any): void; + update(value: any): IDBRequest; +} + +interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + kernelUnitLengthY: SVGAnimatedNumber; + surfaceScale: SVGAnimatedNumber; + specularExponent: SVGAnimatedNumber; + in1: SVGAnimatedString; + kernelUnitLengthX: SVGAnimatedNumber; + specularConstant: SVGAnimatedNumber; +} + +interface File extends Blob { + lastModifiedDate: any; + name: string; +} + +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; +} + +interface HTMLTextAreaElement { + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + 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; +} + +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; +} + +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 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: { + SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; + SVG_MORPHOLOGY_OPERATOR_ERODE: number; + SVG_MORPHOLOGY_OPERATOR_DILATE: number; +} + +interface HTMLSelectElement { + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; +} + +interface CSSRule { + KEYFRAMES_RULE: number; + KEYFRAME_RULE: number; + VIEWPORT_RULE: number; +} +//declare var CSSRule: { +// KEYFRAMES_RULE: number; +// KEYFRAME_RULE: number; +// VIEWPORT_RULE: number; +//} + +interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { +} + +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: { + SVG_CHANNEL_B: number; + SVG_CHANNEL_R: number; + SVG_CHANNEL_G: number; + SVG_CHANNEL_UNKNOWN: number; + SVG_CHANNEL_A: number; +} + +interface AnimationEvent extends Event { + animationName: string; + elapsedTime: number; + initAnimationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, animationNameArg: string, elapsedTimeArg: number): void; +} + +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: { + 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; +} + +interface SVGFEDistantLightElement extends SVGElement { + azimuth: SVGAnimatedNumber; + elevation: SVGAnimatedNumber; +} + +interface SVGException { + name: string; +} + +interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { +} + +interface IDBKeyRange { + upper: any; + upperOpen: boolean; + lower: any; + lowerOpen: boolean; + bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; + only(value: any): IDBKeyRange; + lowerBound(bound: any, open?: boolean): IDBKeyRange; + upperBound(bound: any, open?: boolean): IDBKeyRange; +} + +interface WindowConsole { + console: Console; +} + +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; +} + +interface AudioTrack { + kind: string; + language: string; + id: string; + label: string; + enabled: boolean; +} + +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: { + 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; +} + +interface CSSKeyframesRule extends CSSRule { + name: string; + cssRules: CSSRuleList; + findRule(rule: string): CSSKeyframeRule; + deleteRule(rule: string): void; + appendRule(rule: string): void; +} + +interface Window extends WindowBase64, IDBEnvironment, WindowConsole { + onmspointerdown: (ev: any) => any; + animationStartTime: number; + 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; + msAnimationStartTime: number; + applicationCache: ApplicationCache; + onmsinertiastart: (ev: any) => any; + onmspointerover: (ev: any) => any; + onpopstate: (ev: PopStateEvent) => any; + onmspointerup: (ev: any) => any; + msCancelRequestAnimationFrame(handle: number): void; + matchMedia(mediaQuery: string): MediaQueryList; + cancelAnimationFrame(handle: number): void; + msIsStaticHTML(html: string): boolean; + msMatchMedia(mediaQuery: string): MediaQueryList; + requestAnimationFrame(callback: FrameRequestCallback): number; + msRequestAnimationFrame(callback: FrameRequestCallback): number; +} + +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: { + 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; +} + +interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { +} + +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: { + 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(message?: any, ...optionalParams: any[]): void; + profile(reportName?: string): void; + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + clear(): void; + dir(value?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; + error(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + profileEnd(): void; +} + +interface SVGFESpotLightElement extends SVGElement { + pointsAtY: SVGAnimatedNumber; + y: SVGAnimatedNumber; + limitingConeAngle: SVGAnimatedNumber; + specularExponent: SVGAnimatedNumber; + x: SVGAnimatedNumber; + pointsAtZ: SVGAnimatedNumber; + z: SVGAnimatedNumber; + pointsAtX: SVGAnimatedNumber; +} + +interface HTMLImageElement { + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + msPlayToSource: any; +} + +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; +} + +interface DOMStringList { + length: number; + contains(str: string): boolean; + item(index: number): string; + [index: number]: string; +} + +interface HTMLButtonElement { + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: string; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; +} + +interface IDBOpenDBRequest extends IDBRequest { + onupgradeneeded: (ev: IDBVersionChangeEvent) => any; + onblocked: (ev: Event) => any; +} + +interface HTMLProgressElement extends HTMLElement { + /** + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ + value: number; + /** + * Defines the maximum, or "done" value for a progress element. + */ + max: number; + /** + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ + position: number; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; +} + +interface MSLaunchUriCallback { + (): void; +} + +interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + dy: SVGAnimatedNumber; + in1: SVGAnimatedString; + dx: SVGAnimatedNumber; +} + +interface HTMLFormElement { + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Designates a form that is not validated when submitted. + */ + noValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; +} + +interface MSUnsafeFunctionCallback { + (): any; +} + +interface Document { + onmspointerdown: (ev: any) => any; + msHidden: boolean; + msVisibilityState: string; + onmsgesturedoubletap: (ev: any) => any; + visibilityState: string; + onmsmanipulationstatechanged: (ev: any) => any; + onmspointerhover: (ev: any) => any; + onmscontentzoom: (ev: any) => any; + onmspointermove: (ev: any) => any; + onmsgesturehold: (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; + msCSSOMElementFloatMetrics: boolean; + onmspointerover: (ev: any) => any; + hidden: boolean; + onmspointerup: (ev: any) => any; + msElementsFromPoint(x: number, y: number): NodeList; + msElementsFromRect(left: number, top: number, width: number, height: number): NodeList; + clear(): void; +} + +interface MessageEvent extends Event { + ports: any; +} + +interface HTMLScriptElement { + async: boolean; +} + +interface HTMLMediaElement { + /** + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ + msAudioCategory: string; + /** + * Specifies whether or not to enable low-latency playback on the media element. + */ + msRealTime: boolean; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + textTracks: TextTrackList; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ + audioTracks: AudioTrackList; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + msPlayToSource: any; + /** + * Specifies the output device id that the audio will be sent to. + */ + msAudioDeviceType: string; + /** + * Clears all effects from the media pipeline. + */ + msClearEffects(): void; + /** + * Specifies the media protection manager for a given media pipeline. + */ + msSetMediaProtectionManager(mediaProtectionManager?: any): void; + /** + * Inserts the specified audio effect into media pipeline. + */ + msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; +} + +interface TextTrack extends EventTarget { + language: string; + mode: any; + readyState: number; + 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: { + 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; +} + +interface MessagePort extends EventTarget { + onmessage: (ev: any) => any; + close(): void; + postMessage(message?: any, ports?: any): void; + start(): void; +} + +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 BlobPropertyBag { + type?: string; + endings?: string; +} + +interface Blob { + type: string; + size: number; + msDetachStream(): any; + slice(start?: number, end?: number, contentType?: string): Blob; + msClose(): void; +} +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: { + CHECKING: number; + UNCACHED: number; + UPDATEREADY: number; + DOWNLOADING: number; + IDLE: number; + OBSOLETE: number; +} + +interface FrameRequestCallback { + (time: number): void; +} + +interface XMLHttpRequest { + response: any; + withCredentials: boolean; + onprogress: (ev: ProgressEvent) => any; + onabort: (ev: any) => any; + responseType: string; + onloadend: (ev: ProgressEvent) => any; + upload: XMLHttpRequestEventTarget; + onerror: (ev: ErrorEvent) => any; + onloadstart: (ev: any) => any; +} + +interface PopStateEvent extends Event { + state: any; + initPopStateEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, stateArg: any): void; +} + +interface CSSKeyframeRule extends CSSRule { + keyText: string; + style: CSSStyleDeclaration; +} + +interface MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +interface MSStream { + type: string; + msDetachStream(): any; + msClose(): void; +} + +interface MediaError { + msExtendedCode: number; +} + +interface HTMLFieldSetElement { + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; +} + +interface MSBlobBuilder { + append(data: any, endings?: string): void; + getBlob(contentType?: string): Blob; +} +declare var MSBlobBuilder: { + prototype: MSBlobBuilder; + new (): MSBlobBuilder; +} + +interface HTMLElement { + onmscontentzoom: (ev: any) => any; + oncuechange: (ev: Event) => any; + spellcheck: boolean; + classList: DOMTokenList; + onmsmanipulationstatechanged: (ev: any) => any; + draggable: boolean; +} + +interface DataTransfer { + types: DOMStringList; + files: FileList; +} + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +interface IDBFactory { + open(name: string, version?: number): IDBOpenDBRequest; + cmp(first: any, second: any): number; + deleteDatabase(name: string): IDBOpenDBRequest; +} + +interface Range { + createContextualFragment(fragment: string): DocumentFragment; +} + +interface HTMLObjectElement { + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; +} + +interface MSPointerEvent extends MouseEvent { + width: number; + rotation: number; + pressure: number; + pointerType: any; + isPrimary: boolean; + tiltY: number; + height: number; + intermediatePoints: any; + currentPoint: any; + tiltX: number; + hwTimestamp: number; + pointerId: number; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + MSPOINTER_TYPE_PEN: number; + MSPOINTER_TYPE_MOUSE: number; + MSPOINTER_TYPE_TOUCH: number; +} +declare var MSPointerEvent: { + MSPOINTER_TYPE_PEN: number; + MSPOINTER_TYPE_MOUSE: number; + MSPOINTER_TYPE_TOUCH: number; +} + +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 MSManipulationEvent extends UIEvent { + lastState: number; + currentState: number; + initMSManipulationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, 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: { + 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 (form?: HTMLFormElement): FormData; +} + +interface HTMLDataListElement extends HTMLElement { + options: HTMLCollection; +} + +interface SVGFEImageElement extends SVGElement, SVGLangSpace, SVGFilterPrimitiveStandardAttributes, SVGURIReference, SVGExternalResourcesRequired { + preserveAspectRatio: SVGAnimatedPreserveAspectRatio; +} + +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: { + 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: boolean; + valueMissing: boolean; + stepMismatch: boolean; + rangeUnderflow: boolean; + rangeOverflow: boolean; + typeMismatch: boolean; + patternMismatch: boolean; + tooLong: boolean; + valid: boolean; +} + +interface HTMLTrackElement extends HTMLElement { + kind: string; + src: string; + srclang: string; + track: TextTrack; + label: string; + default: boolean; +} + +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): any; + addPublicLocalApplicationUri(uri: string): void; + createDataPackageFromSelection(): any; +} +declare var MSApp: MSApp; + +interface HTMLVideoElement { + msIsStereo3D: boolean; + msStereo3DPackingMode: string; + onMSVideoOptimalLayoutChanged: (ev: any) => any; + onMSVideoFrameStepCompleted: (ev: any) => any; + msStereo3DRenderMode: string; + msIsLayoutOptimalForPlayback: boolean; + msHorizontalMirror: boolean; + onMSVideoFormatChanged: (ev: any) => any; + msZoom: boolean; + msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; + msFrameStep(forward: boolean): void; +} + +interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; +} + +interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + kernelUnitLengthY: SVGAnimatedNumber; + surfaceScale: SVGAnimatedNumber; + in1: SVGAnimatedString; + kernelUnitLengthX: SVGAnimatedNumber; + diffuseConstant: SVGAnimatedNumber; +} + +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; +} + +declare var onmspointerdown: (ev: any) => any; +declare var animationStartTime: number; +declare var onmsgesturedoubletap: (ev: any) => any; +declare var onmspointerhover: (ev: any) => any; +declare var onmsgesturehold: (ev: any) => any; +declare var onmspointermove: (ev: any) => any; +declare var onmsgesturechange: (ev: any) => any; +declare var onmsgesturestart: (ev: any) => any; +declare var onmspointercancel: (ev: any) => any; +declare var onmsgestureend: (ev: any) => any; +declare var onmsgesturetap: (ev: any) => any; +declare var onmspointerout: (ev: any) => any; +declare var msAnimationStartTime: number; +declare var applicationCache: ApplicationCache; +declare var onmsinertiastart: (ev: any) => any; +declare var onmspointerover: (ev: any) => any; +declare var onpopstate: (ev: PopStateEvent) => any; +declare var onmspointerup: (ev: any) => any; +declare function msCancelRequestAnimationFrame(handle: number): void; +declare function matchMedia(mediaQuery: string): MediaQueryList; +declare function cancelAnimationFrame(handle: number): void; +declare function msIsStaticHTML(html: string): boolean; +declare function msMatchMedia(mediaQuery: string): MediaQueryList; +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; + + +///////////////////////////// +/// IE11 DOM APIs +///////////////////////////// + + +interface StoreExceptionsInformation extends ExceptionInformation { + siteName?: string; + explanationString?: string; + detailURI?: string; +} + +interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { + arrayOfDomainStrings?: Array; +} + +interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { + arrayOfDomainStrings?: Array; +} + +interface AlgorithmParameters { +} + +interface MutationObserverInit { + childList?: boolean; + attributes?: boolean; + characterData?: boolean; + subtree?: boolean; + attributeOldValue?: boolean; + characterDataOldValue?: boolean; + attributeFilter?: Array; +} + +interface ExceptionInformation { + domain?: string; +} + +interface MsZoomToOptions { + contentX?: number; + contentY?: number; + viewportX?: string; + viewportY?: string; + scaleFactor?: number; + animate?: string; +} + +interface DeviceAccelerationDict { + x?: number; + y?: number; + z?: number; +} + +interface DeviceRotationRateDict { + alpha?: number; + beta?: number; + gamma?: number; +} + +interface Algorithm { + name?: string; + params?: AlgorithmParameters; +} + +interface NavigatorID { + product: string; + vendor: string; +} + +interface HTMLBodyElement { + onpageshow: (ev: PageTransitionEvent) => any; + onpagehide: (ev: PageTransitionEvent) => any; +} + +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} + +interface MSWindowExtensions { + captureEvents(): void; + releaseEvents(): void; +} + +interface MSGraphicsTrust { + status: string; + constrictionActive: boolean; +} + +interface AudioTrack { + sourceBuffer: SourceBuffer; +} + +interface DragEvent { + msConvertURL(file: File, targetType: string, targetURL?: string): void; +} + +interface SubtleCrypto { + unwrapKey(wrappedKey: ArrayBufferView, keyAlgorithm: any, keyEncryptionKey: Key, extractable?: boolean, keyUsages?: string[]): KeyOperation; + encrypt(algorithm: any, key: Key, buffer?: ArrayBufferView): CryptoOperation; + importKey(format: string, keyData: ArrayBufferView, algorithm: any, extractable?: boolean, keyUsages?: string[]): KeyOperation; + wrapKey(key: Key, keyEncryptionKey: Key, keyWrappingAlgorithm: any): KeyOperation; + verify(algorithm: any, key: Key, signature: ArrayBufferView, buffer?: ArrayBufferView): CryptoOperation; + deriveKey(algorithm: any, baseKey: Key, derivedKeyType: any, extractable?: boolean, keyUsages?: string[]): KeyOperation; + digest(algorithm: any, buffer?: ArrayBufferView): CryptoOperation; + exportKey(format: string, key: Key): KeyOperation; + generateKey(algorithm: any, extractable?: boolean, keyUsages?: string[]): KeyOperation; + sign(algorithm: any, key: Key, buffer?: ArrayBufferView): CryptoOperation; + decrypt(algorithm: any, key: Key, buffer?: ArrayBufferView): CryptoOperation; +} + +interface Crypto extends RandomSource { + subtle: SubtleCrypto; +} + +interface VideoPlaybackQuality { + totalFrameDelay: number; + creationTime: number; + totalVideoFrames: number; + droppedVideoFrames: number; +} + +interface GlobalEventHandlers { + onpointerenter: (ev: PointerEvent) => any; + onpointerout: (ev: PointerEvent) => any; + onpointerdown: (ev: PointerEvent) => any; + onpointerup: (ev: PointerEvent) => any; + onpointercancel: (ev: PointerEvent) => any; + onpointerover: (ev: PointerEvent) => any; + onpointermove: (ev: PointerEvent) => any; + onpointerleave: (ev: PointerEvent) => any; +} + +interface Window extends GlobalEventHandlers { + onpageshow: (ev: PageTransitionEvent) => any; + ondevicemotion: (ev: DeviceMotionEvent) => any; + devicePixelRatio: number; + msCrypto: Crypto; + ondeviceorientation: (ev: DeviceOrientationEvent) => any; + doNotTrack: string; + onmspointerenter: (ev: any) => any; + onpagehide: (ev: PageTransitionEvent) => any; + onmspointerleave: (ev: any) => any; +} + +interface Key { + algorithm: Algorithm; + type: string; + extractable: boolean; + keyUsage: string[]; +} + +interface TextTrackList extends EventTarget { + onaddtrack: (ev: any) => any; +} + +interface DeviceAcceleration { + y: number; + x: number; + z: number; +} + +interface Console { + count(countTitle?: string): void; + groupEnd(): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(): void; + group(groupTitle?: string): void; + dirxml(value: any): void; + debug(message?: string, ...optionalParams: any[]): void; + groupCollapsed(groupTitle?: string): void; + select(element: Element): void; +} + +interface MSNavigatorDoNotTrack { + removeSiteSpecificTrackingException(args: ExceptionInformation): void; + removeWebWideTrackingException(args: ExceptionInformation): void; + storeWebWideTrackingException(args: StoreExceptionsInformation): void; + storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void; + confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean; + confirmWebWideTrackingException(args: ExceptionInformation): boolean; +} + +interface HTMLImageElement { + crossOrigin: string; + msPlayToPreferredSourceUri: string; +} + +interface HTMLAllCollection extends HTMLCollection { + namedItem(name: string): Element; + //[name: string]: Element; +} + +interface MSNavigatorExtensions { + language: string; +} + +interface AesGcmEncryptResult { + ciphertext: ArrayBuffer; + tag: ArrayBuffer; +} + +interface HTMLSourceElement { + msKeySystem: string; +} + +interface CSSStyleDeclaration { + alignItems: string; + borderImageSource: string; + flexBasis: string; + borderImageWidth: string; + borderImageRepeat: string; + order: string; + flex: string; + alignContent: string; + msImeAlign: string; + flexShrink: string; + flexGrow: string; + borderImageSlice: string; + flexWrap: string; + borderImageOutset: string; + flexDirection: string; + touchAction: string; + flexFlow: string; + borderImage: string; + justifyContent: string; + alignSelf: string; + msTextCombineHorizontal: string; +} + +interface NavigationCompletedEvent extends NavigationEvent { + webErrorStatus: number; + isSuccess: boolean; +} + +interface MutationRecord { + oldValue: string; + previousSibling: Node; + addedNodes: NodeList; + attributeName: string; + removedNodes: NodeList; + target: Node; + nextSibling: Node; + attributeNamespace: string; + type: string; +} + +interface Navigator { + pointerEnabled: boolean; + maxTouchPoints: number; +} + +interface Document extends MSDocumentExtensions, GlobalEventHandlers { + msFullscreenEnabled: boolean; + onmsfullscreenerror: (ev: any) => any; + onmspointerenter: (ev: any) => any; + msFullscreenElement: Element; + onmsfullscreenchange: (ev: any) => any; + onmspointerleave: (ev: any) => any; + msExitFullscreen(): void; +} + +interface MimeTypeArray { + length: number; + item(index: number): Plugin; + [index: number]: Plugin; + namedItem(type: string): Plugin; + //[type: string]: Plugin; +} + +interface HTMLMediaElement { + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + onmsneedkey: (ev: MSMediaKeyNeededEvent) => any; + /** + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ + msKeys: MSMediaKeys; + msGraphicsTrustStatus: MSGraphicsTrust; + msSetMediaKeys(mediaKeys: MSMediaKeys): void; + addTextTrack(kind: string, label?: string, language?: string): TextTrack; +} + +interface TextTrack { + addCue(cue: TextTrackCue): void; + removeCue(cue: TextTrackCue): void; +} + +interface KeyOperation extends EventTarget { + oncomplete: (ev: any) => any; + onerror: (ev: any) => any; + result: any; +} + +interface DOMStringMap { +} + +interface DeviceOrientationEvent extends Event { + gamma: number; + alpha: number; + absolute: boolean; + beta: number; + initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number, beta: number, gamma: number, absolute: boolean): void; +} + +interface MSMediaKeys { + keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; + isTypeSupported(keySystem: string, type?: string): boolean; +} +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new (): MSMediaKeys; +} + +interface MSMediaKeyMessageEvent extends Event { + destinationURL: string; + message: Uint8Array; +} + +interface MSHTMLWebViewElement extends HTMLElement { + documentTitle: string; + width: number; + src: string; + canGoForward: boolean; + height: number; + canGoBack: boolean; + navigateWithHttpRequestMessage(requestMessage: any): void; + goBack(): void; + navigate(uri: string): void; + stop(): void; + navigateToString(contents: string): void; + captureSelectedContentToDataPackageAsync(): MSWebViewAsyncOperation; + capturePreviewToBlobAsync(): MSWebViewAsyncOperation; + refresh(): void; + goForward(): void; + navigateToLocalStreamUri(source: string, streamResolver: any): void; + invokeScriptAsync(scriptName: string, ...args: any[]): MSWebViewAsyncOperation; + buildLocalStreamUri(contentIdentifier: string, relativePath: string): string; +} + +interface NavigationEvent extends Event { + uri: string; +} + +interface Element extends GlobalEventHandlers { + onlostpointercapture: (ev: PointerEvent) => any; + onmspointerenter: (ev: any) => any; + ongotpointercapture: (ev: PointerEvent) => any; + onmspointerleave: (ev: any) => any; + msZoomTo(args: MsZoomToOptions): void; + setPointerCapture(pointerId: number): void; + msGetUntransformedBounds(): ClientRect; + releasePointerCapture(pointerId: number): void; + msRequestFullscreen(): void; +} + +interface RandomSource { + getRandomValues(array: ArrayBufferView): ArrayBufferView; +} + +interface XMLHttpRequest { + msCaching: string; + msCachingEnabled(): boolean; + overrideMimeType(mime: string): void; +} + +interface SourceBuffer extends EventTarget { + updating: boolean; + appendWindowStart: number; + appendWindowEnd: number; + buffered: TimeRanges; + timestampOffset: number; + audioTracks: AudioTrackList; + appendBuffer(data: ArrayBuffer): void; + remove(start: number, end: number): void; + abort(): void; + appendStream(stream: MSStream, maxSize?: number): void; +} + +interface MSInputMethodContext extends EventTarget { + oncandidatewindowshow: (ev: any) => any; + target: HTMLElement; + compositionStartOffset: number; + oncandidatewindowhide: (ev: any) => any; + oncandidatewindowupdate: (ev: any) => any; + compositionEndOffset: number; + getCompositionAlternatives(): string[]; + getCandidateWindowClientRect(): ClientRect; + hasComposition(): boolean; + isCandidateWindowVisible(): boolean; +} + +interface DeviceRotationRate { + gamma: number; + alpha: number; + beta: number; +} + +interface PluginArray { + length: number; + refresh(reload?: boolean): void; + item(index: number): Plugin; + [index: number]: Plugin; + namedItem(name: string): Plugin; + //[name: string]: Plugin; +} + +interface MSMediaKeyError { + systemCode: number; + code: number; + MS_MEDIA_KEYERR_SERVICE: number; + MS_MEDIA_KEYERR_HARDWARECHANGE: number; + MS_MEDIA_KEYERR_OUTPUT: number; + MS_MEDIA_KEYERR_DOMAIN: number; + MS_MEDIA_KEYERR_UNKNOWN: number; + MS_MEDIA_KEYERR_CLIENT: number; +} +declare var MSMediaKeyError: { + MS_MEDIA_KEYERR_SERVICE: number; + MS_MEDIA_KEYERR_HARDWARECHANGE: number; + MS_MEDIA_KEYERR_OUTPUT: number; + MS_MEDIA_KEYERR_DOMAIN: number; + MS_MEDIA_KEYERR_UNKNOWN: number; + MS_MEDIA_KEYERR_CLIENT: number; +} + +interface Plugin { + length: number; + filename: string; + version: string; + name: string; + description: string; + item(index: number): MimeType; + [index: number]: MimeType; + namedItem(type: string): MimeType; + //[type: string]: MimeType; +} + +interface HTMLFrameSetElement { + onpageshow: (ev: PageTransitionEvent) => any; + onpagehide: (ev: PageTransitionEvent) => any; +} + +interface Screen extends EventTarget { + msOrientation: string; + onmsorientationchange: (ev: any) => any; + msLockOrientation(orientation: string): boolean; + msLockOrientation(orientations: string[]): boolean; + msUnlockOrientation(): void; +} + +interface MediaSource extends EventTarget { + sourceBuffers: SourceBufferList; + duration: number; + readyState: string; + activeSourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: string): void; + isTypeSupported(type: string): boolean; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} +declare var MediaSource: { + prototype: MediaSource; + new (): MediaSource; +} + +interface MediaError { + MS_MEDIA_ERR_ENCRYPTED: number; +} +//declare var MediaError: { +// MS_MEDIA_ERR_ENCRYPTED: number; +//} + +interface SourceBufferList extends EventTarget { + length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +interface XMLDocument extends Document { +} + +interface DeviceMotionEvent extends Event { + rotationRate: DeviceRotationRate; + acceleration: DeviceAcceleration; + interval: number; + accelerationIncludingGravity: DeviceAcceleration; + initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict, accelerationIncludingGravity: DeviceAccelerationDict, rotationRate: DeviceRotationRateDict, interval: number): void; +} + +interface MimeType { + enabledPlugin: Plugin; + suffixes: string; + type: string; + description: string; +} + +interface PointerEvent extends MouseEvent { + width: number; + rotation: number; + pressure: number; + pointerType: any; + isPrimary: boolean; + tiltY: number; + height: number; + intermediatePoints: any; + currentPoint: any; + tiltX: number; + hwTimestamp: number; + pointerId: number; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; +} + +interface MSDocumentExtensions { + captureEvents(): void; + releaseEvents(): void; +} + +interface HTMLElement { + dataset: DOMStringMap; + hidden: boolean; + msGetInputContext(): MSInputMethodContext; +} + +interface MutationObserver { + observe(target: Node, options: MutationObserverInit): void; + takeRecords(): MutationRecord[]; + disconnect(): void; +} +declare var MutationObserver: { + prototype: MutationObserver; + new (callback: (arr: MutationRecord[], observer: MutationObserver)=>any): MutationObserver; +} + +interface AudioTrackList { + onremovetrack: (ev: PluginArray) => any; +} + +interface HTMLObjectElement { + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + readyState: number; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + msPlayToSource: any; +} + +interface HTMLEmbedElement { + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + readyState: string; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + msPlayToSource: any; +} + +interface MSWebViewAsyncOperation extends EventTarget { + target: MSHTMLWebViewElement; + oncomplete: (ev: any) => any; + error: DOMError; + onerror: (ev: any) => any; + readyState: number; + type: number; + result: any; + start(): void; + ERROR: number; + TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; + TYPE_INVOKE_SCRIPT: number; + COMPLETED: number; + TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; + STARTED: number; +} +declare var MSWebViewAsyncOperation: { + ERROR: number; + TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; + TYPE_INVOKE_SCRIPT: number; + COMPLETED: number; + TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; + STARTED: number; +} + +interface ScriptNotifyEvent extends Event { + value: string; + callingUri: string; +} + +interface PerformanceNavigationTiming extends PerformanceEntry { + redirectStart: number; + domainLookupEnd: number; + responseStart: number; + domComplete: number; + domainLookupStart: number; + loadEventStart: number; + unloadEventEnd: number; + fetchStart: number; + requestStart: number; + domInteractive: number; + navigationStart: number; + connectEnd: number; + loadEventEnd: number; + connectStart: number; + responseEnd: number; + domLoading: number; + redirectEnd: number; + redirectCount: number; + unloadEventStart: number; + domContentLoadedEventStart: number; + domContentLoadedEventEnd: number; + type: string; +} + +interface MSMediaKeyNeededEvent extends Event { + initData: Uint8Array; +} + +interface MSManipulationEvent { + MS_MANIPULATION_STATE_SELECTING: number; + MS_MANIPULATION_STATE_COMMITTED: number; + MS_MANIPULATION_STATE_PRESELECT: number; + MS_MANIPULATION_STATE_DRAGGING: number; + MS_MANIPULATION_STATE_CANCELLED: number; +} +//declare var MSManipulationEvent: { +// MS_MANIPULATION_STATE_SELECTING: number; +// MS_MANIPULATION_STATE_COMMITTED: number; +// MS_MANIPULATION_STATE_PRESELECT: number; +// MS_MANIPULATION_STATE_DRAGGING: number; +// MS_MANIPULATION_STATE_CANCELLED: number; +//} + +interface LongRunningScriptDetectedEvent extends Event { + stopPageScriptExecution: boolean; + executionTime: number; +} + +interface MSAppView { + viewId: number; + close(): void; + postMessage(message: any, targetOrigin: string, ports?: any): void; +} + +interface PerfWidgetExternal { + maxCpuSpeed: number; + independentRenderingEnabled: boolean; + irDisablingContentString: string; + irStatusAvailable: boolean; + performanceCounter: number; + averagePaintTime: number; + activeNetworkRequestCount: number; + paintRequestsPerSecond: number; + extraInformationEnabled: boolean; + performanceCounterFrequency: number; + averageFrameTime: number; + repositionWindow(x: number, y: number): void; + getRecentMemoryUsage(last: number): any; + getMemoryUsage(): number; + resizeWindow(width: number, height: number): void; + getProcessCpuUsage(): number; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; + removeEventListener(eventType: string, callback: (ev: any) => any): void; + getRecentCpuUsage(last: number): any; + addEventListener(eventType: string, callback: (ev: any) => any): void; + getRecentFrames(last: number): any; + getRecentPaintRequests(last: number): any; +} + +interface PageTransitionEvent extends Event { + persisted: boolean; +} + +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} + +interface HTMLDocument extends Document { +} + +interface KeyPair { + privateKey: Key; + publicKey: Key; +} + +interface MSApp { + getViewOpener(): MSAppView; + suppressSubdownloadCredentialPrompts(suppress: boolean): void; + execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void; + isTaskScheduledAtPriorityOrHigher(priority: string): boolean; + execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any; + createNewView(uri: string): MSAppView; + getCurrentPriority(): string; + NORMAL: string; + HIGH: string; + IDLE: string; + CURRENT: string; +} +//declare var MSApp: { +// NORMAL: string; +// HIGH: string; +// IDLE: string; +// CURRENT: string; +//} + +interface MSMediaKeySession extends EventTarget { + sessionId: string; + error: MSMediaKeyError; + keySystem: string; + close(): void; + update(key: Uint8Array): void; +} + +interface HTMLTrackElement { + readyState: number; + ERROR: number; + LOADING: number; + LOADED: number; + NONE: number; +} +//declare var HTMLTrackElement: { +// ERROR: number; +// LOADING: number; +// LOADED: number; +// NONE: number; +//} + +interface HTMLVideoElement { + getVideoPlaybackQuality(): VideoPlaybackQuality; +} + +interface UnviewableContentIdentifiedEvent extends NavigationEvent { + referrer: string; +} + +interface CryptoOperation extends EventTarget { + algorithm: Algorithm; + oncomplete: (ev: any) => any; + onerror: (ev: any) => any; + onprogress: (ev: any) => any; + onabort: (ev: any) => any; + key: Key; + result: any; + abort(): void; + finish(): void; + process(buffer: ArrayBufferView): void; +} + +declare var onpageshow: (ev: PageTransitionEvent) => any; +declare var ondevicemotion: (ev: DeviceMotionEvent) => any; +declare var devicePixelRatio: number; +declare var msCrypto: Crypto; +declare var ondeviceorientation: (ev: DeviceOrientationEvent) => any; +declare var doNotTrack: string; +declare var onmspointerenter: (ev: any) => any; +declare var onpagehide: (ev: PageTransitionEvent) => any; +declare var onmspointerleave: (ev: any) => any; +declare var onpointerenter: (ev: PointerEvent) => any; +declare var onpointerout: (ev: PointerEvent) => any; +declare var onpointerdown: (ev: PointerEvent) => any; +declare var onpointerup: (ev: PointerEvent) => any; +declare var onpointercancel: (ev: PointerEvent) => any; +declare var onpointerover: (ev: PointerEvent) => any; +declare var onpointermove: (ev: PointerEvent) => any; +declare var onpointerleave: (ev: PointerEvent) => any; + + +///////////////////////////// +/// WebGL APIs +///////////////////////////// + + +interface WebGLTexture extends WebGLObject { +} + +interface OES_texture_float { +} + +interface WebGLContextEvent extends Event { + statusMessage: string; +} +declare var WebGLContextEvent: { + prototype: WebGLContextEvent; + new (): WebGLContextEvent; +} + +interface WebGLRenderbuffer extends WebGLObject { +} + +interface WebGLUniformLocation { +} + +interface WebGLActiveInfo { + name: string; + type: number; + size: number; +} + +interface WEBGL_compressed_texture_s3tc { + COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} +declare var WEBGL_compressed_texture_s3tc: { + COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +interface WebGLContextAttributes { + alpha: boolean; + depth: boolean; + stencil: boolean; + antialias: boolean; + premultipliedAlpha: boolean; + preserveDrawingBuffer: boolean; +} + +interface WebGLRenderingContext { + drawingBufferWidth: number; + drawingBufferHeight: number; + canvas: HTMLCanvasElement; + getUniformLocation(program: WebGLProgram, name: string): WebGLUniformLocation; + bindTexture(target: number, texture: WebGLTexture): void; + bufferData(target: number, data: ArrayBufferView, usage: number): void; + bufferData(target: number, data: ArrayBuffer, usage: number): void; + bufferData(target: number, size: number, usage: number): void; + depthMask(flag: boolean): void; + getUniform(program: WebGLProgram, location: WebGLUniformLocation): any; + vertexAttrib3fv(indx: number, values: number[]): void; + vertexAttrib3fv(indx: number, values: Float32Array): void; + linkProgram(program: WebGLProgram): void; + getSupportedExtensions(): string[]; + bufferSubData(target: number, offset: number, data: ArrayBuffer): void; + bufferSubData(target: number, offset: number, data: ArrayBufferView): void; + vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void; + polygonOffset(factor: number, units: number): void; + blendColor(red: number, green: number, blue: number, alpha: number): void; + createTexture(): WebGLTexture; + hint(target: number, mode: number): void; + getVertexAttrib(index: number, pname: number): any; + enableVertexAttribArray(index: number): void; + depthRange(zNear: number, zFar: number): void; + cullFace(mode: number): void; + createFramebuffer(): WebGLFramebuffer; + uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: number[]): void; + uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; + framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture, level: number): void; + deleteFramebuffer(framebuffer: WebGLFramebuffer): void; + colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: ArrayBufferView): void; + uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: number[]): void; + uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; + getExtension(name: string): Object; + createProgram(): WebGLProgram; + deleteShader(shader: WebGLShader): void; + getAttachedShaders(program: WebGLProgram): WebGLShader[]; + enable(cap: number): void; + blendEquation(mode: number): void; + texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, image: HTMLImageElement): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, canvas: HTMLCanvasElement): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, video: HTMLVideoElement): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageData): void; + createBuffer(): WebGLBuffer; + deleteTexture(texture: WebGLTexture): void; + useProgram(program: WebGLProgram): void; + vertexAttrib2fv(indx: number, values: number[]): void; + vertexAttrib2fv(indx: number, values: Float32Array): void; + checkFramebufferStatus(target: number): number; + frontFace(mode: number): void; + getBufferParameter(target: number, pname: number): any; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, image: HTMLImageElement): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, canvas: HTMLCanvasElement): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, video: HTMLVideoElement): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void; + copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void; + getVertexAttribOffset(index: number, pname: number): number; + disableVertexAttribArray(index: number): void; + blendFunc(sfactor: number, dfactor: number): void; + drawElements(mode: number, count: number, type: number, offset: number): void; + isFramebuffer(framebuffer: WebGLFramebuffer): boolean; + uniform3iv(location: WebGLUniformLocation, v: number[]): void; + uniform3iv(location: WebGLUniformLocation, v: Int32Array): void; + lineWidth(width: number): void; + getShaderInfoLog(shader: WebGLShader): string; + getTexParameter(target: number, pname: number): any; + getParameter(pname: number): any; + getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat; + getContextAttributes(): WebGLContextAttributes; + vertexAttrib1f(indx: number, x: number): void; + bindFramebuffer(target: number, framebuffer: WebGLFramebuffer): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: ArrayBufferView): void; + isContextLost(): boolean; + uniform1iv(location: WebGLUniformLocation, v: number[]): void; + uniform1iv(location: WebGLUniformLocation, v: Int32Array): void; + getRenderbufferParameter(target: number, pname: number): any; + uniform2fv(location: WebGLUniformLocation, v: number[]): void; + uniform2fv(location: WebGLUniformLocation, v: Float32Array): void; + isTexture(texture: WebGLTexture): boolean; + getError(): number; + shaderSource(shader: WebGLShader, source: string): void; + deleteRenderbuffer(renderbuffer: WebGLRenderbuffer): void; + stencilMask(mask: number): void; + bindBuffer(target: number, buffer: WebGLBuffer): void; + getAttribLocation(program: WebGLProgram, name: string): number; + uniform3i(location: WebGLUniformLocation, x: number, y: number, z: number): void; + blendEquationSeparate(modeRGB: number, modeAlpha: number): void; + clear(mask: number): void; + blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void; + stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; + scissor(x: number, y: number, width: number, height: number): void; + uniform2i(location: WebGLUniformLocation, x: number, y: number): void; + getActiveAttrib(program: WebGLProgram, index: number): WebGLActiveInfo; + getShaderSource(shader: WebGLShader): string; + generateMipmap(target: number): void; + bindAttribLocation(program: WebGLProgram, index: number, name: string): void; + uniform1fv(location: WebGLUniformLocation, v: number[]): void; + uniform1fv(location: WebGLUniformLocation, v: Float32Array): void; + uniform2iv(location: WebGLUniformLocation, v: number[]): void; + uniform2iv(location: WebGLUniformLocation, v: Int32Array): void; + stencilOp(fail: number, zfail: number, zpass: number): void; + uniform4fv(location: WebGLUniformLocation, v: number[]): void; + uniform4fv(location: WebGLUniformLocation, v: Float32Array): void; + vertexAttrib1fv(indx: number, values: number[]): void; + vertexAttrib1fv(indx: number, values: Float32Array): void; + flush(): void; + uniform4f(location: WebGLUniformLocation, x: number, y: number, z: number, w: number): void; + deleteProgram(program: WebGLProgram): void; + isRenderbuffer(renderbuffer: WebGLRenderbuffer): boolean; + uniform1i(location: WebGLUniformLocation, x: number): void; + getProgramParameter(program: WebGLProgram, pname: number): any; + getActiveUniform(program: WebGLProgram, index: number): WebGLActiveInfo; + stencilFunc(func: number, ref: number, mask: number): void; + pixelStorei(pname: number, param: number): void; + disable(cap: number): void; + vertexAttrib4fv(indx: number, values: number[]): void; + vertexAttrib4fv(indx: number, values: Float32Array): void; + createRenderbuffer(): WebGLRenderbuffer; + isBuffer(buffer: WebGLBuffer): boolean; + stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; + getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; + uniform4i(location: WebGLUniformLocation, x: number, y: number, z: number, w: number): void; + sampleCoverage(value: number, invert: boolean): void; + depthFunc(func: number): void; + texParameterf(target: number, pname: number, param: number): void; + vertexAttrib3f(indx: number, x: number, y: number, z: number): void; + drawArrays(mode: number, first: number, count: number): void; + texParameteri(target: number, pname: number, param: number): void; + vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void; + getShaderParameter(shader: WebGLShader, pname: number): any; + clearDepth(depth: number): void; + activeTexture(texture: number): void; + viewport(x: number, y: number, width: number, height: number): void; + detachShader(program: WebGLProgram, shader: WebGLShader): void; + uniform1f(location: WebGLUniformLocation, x: number): void; + uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: number[]): void; + uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; + deleteBuffer(buffer: WebGLBuffer): void; + copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void; + uniform3fv(location: WebGLUniformLocation, v: number[]): void; + uniform3fv(location: WebGLUniformLocation, v: Float32Array): void; + stencilMaskSeparate(face: number, mask: number): void; + attachShader(program: WebGLProgram, shader: WebGLShader): void; + compileShader(shader: WebGLShader): void; + clearColor(red: number, green: number, blue: number, alpha: number): void; + isShader(shader: WebGLShader): boolean; + clearStencil(s: number): void; + framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer): void; + finish(): void; + uniform2f(location: WebGLUniformLocation, x: number, y: number): void; + renderbufferStorage(target: number, internalformat: number, width: number, height: number): void; + uniform3f(location: WebGLUniformLocation, x: number, y: number, z: number): void; + getProgramInfoLog(program: WebGLProgram): string; + validateProgram(program: WebGLProgram): void; + isEnabled(cap: number): boolean; + vertexAttrib2f(indx: number, x: number, y: number): void; + isProgram(program: WebGLProgram): boolean; + createShader(type: number): WebGLShader; + bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer): void; + uniform4iv(location: WebGLUniformLocation, v: number[]): void; + uniform4iv(location: WebGLUniformLocation, v: Int32Array): void; + DEPTH_FUNC: number; + DEPTH_COMPONENT16: number; + REPLACE: number; + REPEAT: number; + VERTEX_ATTRIB_ARRAY_ENABLED: number; + FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + STENCIL_BUFFER_BIT: number; + RENDERER: number; + STENCIL_BACK_REF: number; + TEXTURE26: number; + RGB565: number; + DITHER: number; + CONSTANT_COLOR: number; + GENERATE_MIPMAP_HINT: number; + POINTS: number; + DECR: number; + INT_VEC3: number; + TEXTURE28: number; + ONE_MINUS_CONSTANT_ALPHA: number; + BACK: number; + RENDERBUFFER_STENCIL_SIZE: number; + UNPACK_FLIP_Y_WEBGL: number; + BLEND: number; + TEXTURE9: number; + ARRAY_BUFFER_BINDING: number; + MAX_VIEWPORT_DIMS: number; + INVALID_FRAMEBUFFER_OPERATION: number; + TEXTURE: number; + TEXTURE0: number; + TEXTURE31: number; + TEXTURE24: number; + HIGH_INT: number; + RENDERBUFFER_BINDING: number; + BLEND_COLOR: number; + FASTEST: number; + STENCIL_WRITEMASK: number; + ALIASED_POINT_SIZE_RANGE: number; + TEXTURE12: number; + DST_ALPHA: number; + BLEND_EQUATION_RGB: number; + FRAMEBUFFER_COMPLETE: number; + NEAREST_MIPMAP_NEAREST: number; + VERTEX_ATTRIB_ARRAY_SIZE: number; + TEXTURE3: number; + DEPTH_WRITEMASK: number; + CONTEXT_LOST_WEBGL: number; + INVALID_VALUE: number; + TEXTURE_MAG_FILTER: number; + ONE_MINUS_CONSTANT_COLOR: number; + ONE_MINUS_SRC_ALPHA: number; + TEXTURE_CUBE_MAP_POSITIVE_Z: number; + NOTEQUAL: number; + ALPHA: number; + DEPTH_STENCIL: number; + MAX_VERTEX_UNIFORM_VECTORS: number; + DEPTH_COMPONENT: number; + RENDERBUFFER_RED_SIZE: number; + TEXTURE20: number; + RED_BITS: number; + RENDERBUFFER_BLUE_SIZE: number; + SCISSOR_BOX: number; + VENDOR: number; + FRONT_AND_BACK: number; + CONSTANT_ALPHA: number; + VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + NEAREST: number; + CULL_FACE: number; + ALIASED_LINE_WIDTH_RANGE: number; + TEXTURE19: number; + FRONT: number; + DEPTH_CLEAR_VALUE: number; + GREEN_BITS: number; + TEXTURE29: number; + TEXTURE23: number; + MAX_RENDERBUFFER_SIZE: number; + STENCIL_ATTACHMENT: number; + TEXTURE27: number; + BOOL_VEC2: number; + OUT_OF_MEMORY: number; + MIRRORED_REPEAT: number; + POLYGON_OFFSET_UNITS: number; + TEXTURE_MIN_FILTER: number; + STENCIL_BACK_PASS_DEPTH_PASS: number; + LINE_LOOP: number; + FLOAT_MAT3: number; + TEXTURE14: number; + LINEAR: number; + RGB5_A1: number; + ONE_MINUS_SRC_COLOR: number; + SAMPLE_COVERAGE_INVERT: number; + DONT_CARE: number; + FRAMEBUFFER_BINDING: number; + RENDERBUFFER_ALPHA_SIZE: number; + STENCIL_REF: number; + ZERO: number; + DECR_WRAP: number; + SAMPLE_COVERAGE: number; + STENCIL_BACK_FUNC: number; + TEXTURE30: number; + VIEWPORT: number; + STENCIL_BITS: number; + FLOAT: number; + COLOR_WRITEMASK: number; + SAMPLE_COVERAGE_VALUE: number; + TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + STENCIL_BACK_FAIL: number; + FLOAT_MAT4: number; + UNSIGNED_SHORT_4_4_4_4: number; + TEXTURE6: number; + RENDERBUFFER_WIDTH: number; + RGBA4: number; + ALWAYS: number; + BLEND_EQUATION_ALPHA: number; + COLOR_BUFFER_BIT: number; + TEXTURE_CUBE_MAP: number; + DEPTH_BUFFER_BIT: number; + STENCIL_CLEAR_VALUE: number; + BLEND_EQUATION: number; + RENDERBUFFER_GREEN_SIZE: number; + NEAREST_MIPMAP_LINEAR: number; + VERTEX_ATTRIB_ARRAY_TYPE: number; + INCR_WRAP: number; + ONE_MINUS_DST_COLOR: number; + HIGH_FLOAT: number; + BYTE: number; + FRONT_FACE: number; + SAMPLE_ALPHA_TO_COVERAGE: number; + CCW: number; + TEXTURE13: number; + MAX_VERTEX_ATTRIBS: number; + MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + TEXTURE_WRAP_T: number; + UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + FLOAT_VEC2: number; + LUMINANCE: number; + GREATER: number; + INT_VEC2: number; + VALIDATE_STATUS: number; + FRAMEBUFFER: number; + FRAMEBUFFER_UNSUPPORTED: number; + TEXTURE5: number; + FUNC_SUBTRACT: number; + BLEND_DST_ALPHA: number; + SAMPLER_CUBE: number; + ONE_MINUS_DST_ALPHA: number; + LESS: number; + TEXTURE_CUBE_MAP_POSITIVE_X: number; + BLUE_BITS: number; + DEPTH_TEST: number; + VERTEX_ATTRIB_ARRAY_STRIDE: number; + DELETE_STATUS: number; + TEXTURE18: number; + POLYGON_OFFSET_FACTOR: number; + UNSIGNED_INT: number; + TEXTURE_2D: number; + DST_COLOR: number; + FLOAT_MAT2: number; + COMPRESSED_TEXTURE_FORMATS: number; + MAX_FRAGMENT_UNIFORM_VECTORS: number; + DEPTH_STENCIL_ATTACHMENT: number; + LUMINANCE_ALPHA: number; + CW: number; + VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + LINEAR_MIPMAP_LINEAR: number; + BUFFER_SIZE: number; + SAMPLE_BUFFERS: number; + TEXTURE15: number; + ACTIVE_TEXTURE: number; + VERTEX_SHADER: number; + TEXTURE22: number; + VERTEX_ATTRIB_ARRAY_POINTER: number; + INCR: number; + COMPILE_STATUS: number; + MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + TEXTURE7: number; + UNSIGNED_SHORT_5_5_5_1: number; + DEPTH_BITS: number; + RGBA: number; + TRIANGLE_STRIP: number; + COLOR_CLEAR_VALUE: number; + BROWSER_DEFAULT_WEBGL: number; + INVALID_ENUM: number; + SCISSOR_TEST: number; + LINE_STRIP: number; + FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + STENCIL_FUNC: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + RENDERBUFFER_HEIGHT: number; + TEXTURE8: number; + TRIANGLES: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + STENCIL_BACK_VALUE_MASK: number; + TEXTURE25: number; + RENDERBUFFER: number; + LEQUAL: number; + TEXTURE1: number; + STENCIL_INDEX8: number; + FUNC_ADD: number; + STENCIL_FAIL: number; + BLEND_SRC_ALPHA: number; + BOOL: number; + ALPHA_BITS: number; + LOW_INT: number; + TEXTURE10: number; + SRC_COLOR: number; + MAX_VARYING_VECTORS: number; + BLEND_DST_RGB: number; + TEXTURE_BINDING_CUBE_MAP: number; + STENCIL_INDEX: number; + TEXTURE_BINDING_2D: number; + MEDIUM_INT: number; + SHADER_TYPE: number; + POLYGON_OFFSET_FILL: number; + DYNAMIC_DRAW: number; + TEXTURE4: number; + STENCIL_BACK_PASS_DEPTH_FAIL: number; + STREAM_DRAW: number; + MAX_CUBE_MAP_TEXTURE_SIZE: number; + TEXTURE17: number; + TRIANGLE_FAN: number; + UNPACK_ALIGNMENT: number; + CURRENT_PROGRAM: number; + LINES: number; + INVALID_OPERATION: number; + FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + LINEAR_MIPMAP_NEAREST: number; + CLAMP_TO_EDGE: number; + RENDERBUFFER_DEPTH_SIZE: number; + TEXTURE_WRAP_S: number; + ELEMENT_ARRAY_BUFFER: number; + UNSIGNED_SHORT_5_6_5: number; + ACTIVE_UNIFORMS: number; + FLOAT_VEC3: number; + NO_ERROR: number; + ATTACHED_SHADERS: number; + DEPTH_ATTACHMENT: number; + TEXTURE11: number; + STENCIL_TEST: number; + ONE: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + STATIC_DRAW: number; + GEQUAL: number; + BOOL_VEC4: number; + COLOR_ATTACHMENT0: number; + PACK_ALIGNMENT: number; + MAX_TEXTURE_SIZE: number; + STENCIL_PASS_DEPTH_FAIL: number; + CULL_FACE_MODE: number; + TEXTURE16: number; + STENCIL_BACK_WRITEMASK: number; + SRC_ALPHA: number; + UNSIGNED_SHORT: number; + TEXTURE21: number; + FUNC_REVERSE_SUBTRACT: number; + SHADING_LANGUAGE_VERSION: number; + EQUAL: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + BOOL_VEC3: number; + SAMPLER_2D: number; + TEXTURE_CUBE_MAP_NEGATIVE_X: number; + MAX_TEXTURE_IMAGE_UNITS: number; + TEXTURE_CUBE_MAP_POSITIVE_Y: number; + RENDERBUFFER_INTERNAL_FORMAT: number; + STENCIL_VALUE_MASK: number; + ELEMENT_ARRAY_BUFFER_BINDING: number; + ARRAY_BUFFER: number; + DEPTH_RANGE: number; + NICEST: number; + ACTIVE_ATTRIBUTES: number; + NEVER: number; + FLOAT_VEC4: number; + CURRENT_VERTEX_ATTRIB: number; + STENCIL_PASS_DEPTH_PASS: number; + INVERT: number; + LINK_STATUS: number; + RGB: number; + INT_VEC4: number; + TEXTURE2: number; + UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + MEDIUM_FLOAT: number; + SRC_ALPHA_SATURATE: number; + BUFFER_USAGE: number; + SHORT: number; + NONE: number; + UNSIGNED_BYTE: number; + INT: number; + SUBPIXEL_BITS: number; + KEEP: number; + SAMPLES: number; + FRAGMENT_SHADER: number; + LINE_WIDTH: number; + BLEND_SRC_RGB: number; + LOW_FLOAT: number; + VERSION: number; +} +declare var WebGLRenderingContext: { + DEPTH_FUNC: number; + DEPTH_COMPONENT16: number; + REPLACE: number; + REPEAT: number; + VERTEX_ATTRIB_ARRAY_ENABLED: number; + FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + STENCIL_BUFFER_BIT: number; + RENDERER: number; + STENCIL_BACK_REF: number; + TEXTURE26: number; + RGB565: number; + DITHER: number; + CONSTANT_COLOR: number; + GENERATE_MIPMAP_HINT: number; + POINTS: number; + DECR: number; + INT_VEC3: number; + TEXTURE28: number; + ONE_MINUS_CONSTANT_ALPHA: number; + BACK: number; + RENDERBUFFER_STENCIL_SIZE: number; + UNPACK_FLIP_Y_WEBGL: number; + BLEND: number; + TEXTURE9: number; + ARRAY_BUFFER_BINDING: number; + MAX_VIEWPORT_DIMS: number; + INVALID_FRAMEBUFFER_OPERATION: number; + TEXTURE: number; + TEXTURE0: number; + TEXTURE31: number; + TEXTURE24: number; + HIGH_INT: number; + RENDERBUFFER_BINDING: number; + BLEND_COLOR: number; + FASTEST: number; + STENCIL_WRITEMASK: number; + ALIASED_POINT_SIZE_RANGE: number; + TEXTURE12: number; + DST_ALPHA: number; + BLEND_EQUATION_RGB: number; + FRAMEBUFFER_COMPLETE: number; + NEAREST_MIPMAP_NEAREST: number; + VERTEX_ATTRIB_ARRAY_SIZE: number; + TEXTURE3: number; + DEPTH_WRITEMASK: number; + CONTEXT_LOST_WEBGL: number; + INVALID_VALUE: number; + TEXTURE_MAG_FILTER: number; + ONE_MINUS_CONSTANT_COLOR: number; + ONE_MINUS_SRC_ALPHA: number; + TEXTURE_CUBE_MAP_POSITIVE_Z: number; + NOTEQUAL: number; + ALPHA: number; + DEPTH_STENCIL: number; + MAX_VERTEX_UNIFORM_VECTORS: number; + DEPTH_COMPONENT: number; + RENDERBUFFER_RED_SIZE: number; + TEXTURE20: number; + RED_BITS: number; + RENDERBUFFER_BLUE_SIZE: number; + SCISSOR_BOX: number; + VENDOR: number; + FRONT_AND_BACK: number; + CONSTANT_ALPHA: number; + VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + NEAREST: number; + CULL_FACE: number; + ALIASED_LINE_WIDTH_RANGE: number; + TEXTURE19: number; + FRONT: number; + DEPTH_CLEAR_VALUE: number; + GREEN_BITS: number; + TEXTURE29: number; + TEXTURE23: number; + MAX_RENDERBUFFER_SIZE: number; + STENCIL_ATTACHMENT: number; + TEXTURE27: number; + BOOL_VEC2: number; + OUT_OF_MEMORY: number; + MIRRORED_REPEAT: number; + POLYGON_OFFSET_UNITS: number; + TEXTURE_MIN_FILTER: number; + STENCIL_BACK_PASS_DEPTH_PASS: number; + LINE_LOOP: number; + FLOAT_MAT3: number; + TEXTURE14: number; + LINEAR: number; + RGB5_A1: number; + ONE_MINUS_SRC_COLOR: number; + SAMPLE_COVERAGE_INVERT: number; + DONT_CARE: number; + FRAMEBUFFER_BINDING: number; + RENDERBUFFER_ALPHA_SIZE: number; + STENCIL_REF: number; + ZERO: number; + DECR_WRAP: number; + SAMPLE_COVERAGE: number; + STENCIL_BACK_FUNC: number; + TEXTURE30: number; + VIEWPORT: number; + STENCIL_BITS: number; + FLOAT: number; + COLOR_WRITEMASK: number; + SAMPLE_COVERAGE_VALUE: number; + TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + STENCIL_BACK_FAIL: number; + FLOAT_MAT4: number; + UNSIGNED_SHORT_4_4_4_4: number; + TEXTURE6: number; + RENDERBUFFER_WIDTH: number; + RGBA4: number; + ALWAYS: number; + BLEND_EQUATION_ALPHA: number; + COLOR_BUFFER_BIT: number; + TEXTURE_CUBE_MAP: number; + DEPTH_BUFFER_BIT: number; + STENCIL_CLEAR_VALUE: number; + BLEND_EQUATION: number; + RENDERBUFFER_GREEN_SIZE: number; + NEAREST_MIPMAP_LINEAR: number; + VERTEX_ATTRIB_ARRAY_TYPE: number; + INCR_WRAP: number; + ONE_MINUS_DST_COLOR: number; + HIGH_FLOAT: number; + BYTE: number; + FRONT_FACE: number; + SAMPLE_ALPHA_TO_COVERAGE: number; + CCW: number; + TEXTURE13: number; + MAX_VERTEX_ATTRIBS: number; + MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + TEXTURE_WRAP_T: number; + UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + FLOAT_VEC2: number; + LUMINANCE: number; + GREATER: number; + INT_VEC2: number; + VALIDATE_STATUS: number; + FRAMEBUFFER: number; + FRAMEBUFFER_UNSUPPORTED: number; + TEXTURE5: number; + FUNC_SUBTRACT: number; + BLEND_DST_ALPHA: number; + SAMPLER_CUBE: number; + ONE_MINUS_DST_ALPHA: number; + LESS: number; + TEXTURE_CUBE_MAP_POSITIVE_X: number; + BLUE_BITS: number; + DEPTH_TEST: number; + VERTEX_ATTRIB_ARRAY_STRIDE: number; + DELETE_STATUS: number; + TEXTURE18: number; + POLYGON_OFFSET_FACTOR: number; + UNSIGNED_INT: number; + TEXTURE_2D: number; + DST_COLOR: number; + FLOAT_MAT2: number; + COMPRESSED_TEXTURE_FORMATS: number; + MAX_FRAGMENT_UNIFORM_VECTORS: number; + DEPTH_STENCIL_ATTACHMENT: number; + LUMINANCE_ALPHA: number; + CW: number; + VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + LINEAR_MIPMAP_LINEAR: number; + BUFFER_SIZE: number; + SAMPLE_BUFFERS: number; + TEXTURE15: number; + ACTIVE_TEXTURE: number; + VERTEX_SHADER: number; + TEXTURE22: number; + VERTEX_ATTRIB_ARRAY_POINTER: number; + INCR: number; + COMPILE_STATUS: number; + MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + TEXTURE7: number; + UNSIGNED_SHORT_5_5_5_1: number; + DEPTH_BITS: number; + RGBA: number; + TRIANGLE_STRIP: number; + COLOR_CLEAR_VALUE: number; + BROWSER_DEFAULT_WEBGL: number; + INVALID_ENUM: number; + SCISSOR_TEST: number; + LINE_STRIP: number; + FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + STENCIL_FUNC: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + RENDERBUFFER_HEIGHT: number; + TEXTURE8: number; + TRIANGLES: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + STENCIL_BACK_VALUE_MASK: number; + TEXTURE25: number; + RENDERBUFFER: number; + LEQUAL: number; + TEXTURE1: number; + STENCIL_INDEX8: number; + FUNC_ADD: number; + STENCIL_FAIL: number; + BLEND_SRC_ALPHA: number; + BOOL: number; + ALPHA_BITS: number; + LOW_INT: number; + TEXTURE10: number; + SRC_COLOR: number; + MAX_VARYING_VECTORS: number; + BLEND_DST_RGB: number; + TEXTURE_BINDING_CUBE_MAP: number; + STENCIL_INDEX: number; + TEXTURE_BINDING_2D: number; + MEDIUM_INT: number; + SHADER_TYPE: number; + POLYGON_OFFSET_FILL: number; + DYNAMIC_DRAW: number; + TEXTURE4: number; + STENCIL_BACK_PASS_DEPTH_FAIL: number; + STREAM_DRAW: number; + MAX_CUBE_MAP_TEXTURE_SIZE: number; + TEXTURE17: number; + TRIANGLE_FAN: number; + UNPACK_ALIGNMENT: number; + CURRENT_PROGRAM: number; + LINES: number; + INVALID_OPERATION: number; + FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + LINEAR_MIPMAP_NEAREST: number; + CLAMP_TO_EDGE: number; + RENDERBUFFER_DEPTH_SIZE: number; + TEXTURE_WRAP_S: number; + ELEMENT_ARRAY_BUFFER: number; + UNSIGNED_SHORT_5_6_5: number; + ACTIVE_UNIFORMS: number; + FLOAT_VEC3: number; + NO_ERROR: number; + ATTACHED_SHADERS: number; + DEPTH_ATTACHMENT: number; + TEXTURE11: number; + STENCIL_TEST: number; + ONE: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + STATIC_DRAW: number; + GEQUAL: number; + BOOL_VEC4: number; + COLOR_ATTACHMENT0: number; + PACK_ALIGNMENT: number; + MAX_TEXTURE_SIZE: number; + STENCIL_PASS_DEPTH_FAIL: number; + CULL_FACE_MODE: number; + TEXTURE16: number; + STENCIL_BACK_WRITEMASK: number; + SRC_ALPHA: number; + UNSIGNED_SHORT: number; + TEXTURE21: number; + FUNC_REVERSE_SUBTRACT: number; + SHADING_LANGUAGE_VERSION: number; + EQUAL: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + BOOL_VEC3: number; + SAMPLER_2D: number; + TEXTURE_CUBE_MAP_NEGATIVE_X: number; + MAX_TEXTURE_IMAGE_UNITS: number; + TEXTURE_CUBE_MAP_POSITIVE_Y: number; + RENDERBUFFER_INTERNAL_FORMAT: number; + STENCIL_VALUE_MASK: number; + ELEMENT_ARRAY_BUFFER_BINDING: number; + ARRAY_BUFFER: number; + DEPTH_RANGE: number; + NICEST: number; + ACTIVE_ATTRIBUTES: number; + NEVER: number; + FLOAT_VEC4: number; + CURRENT_VERTEX_ATTRIB: number; + STENCIL_PASS_DEPTH_PASS: number; + INVERT: number; + LINK_STATUS: number; + RGB: number; + INT_VEC4: number; + TEXTURE2: number; + UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + MEDIUM_FLOAT: number; + SRC_ALPHA_SATURATE: number; + BUFFER_USAGE: number; + SHORT: number; + NONE: number; + UNSIGNED_BYTE: number; + INT: number; + SUBPIXEL_BITS: number; + KEEP: number; + SAMPLES: number; + FRAGMENT_SHADER: number; + LINE_WIDTH: number; + BLEND_SRC_RGB: number; + LOW_FLOAT: number; + VERSION: number; +} + +interface WebGLProgram extends WebGLObject { +} + +interface OES_standard_derivatives { + FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} +declare var OES_standard_derivatives: { + FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} + +interface WebGLFramebuffer extends WebGLObject { +} + +interface WebGLShader extends WebGLObject { +} + +interface OES_texture_float_linear { +} + +interface WebGLObject { +} + +interface WebGLBuffer extends WebGLObject { +} + +interface WebGLShaderPrecisionFormat { + rangeMin: number; + rangeMax: number; + precision: number; +} + +interface EXT_texture_filter_anisotropic { + TEXTURE_MAX_ANISOTROPY_EXT: number; + MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; +} +declare var EXT_texture_filter_anisotropic: { + TEXTURE_MAX_ANISOTROPY_EXT: number; + MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; +} + + +///////////////////////////// +/// addEventListener overloads +///////////////////////////// + +interface HTMLElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface Document { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "msthumbnailclick", listener: (ev: MSSiteModeEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stop", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mssitemodejumplistitemremoved", listener: (ev: MSSiteModeEvent) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectionchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "storagecommit", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msfullscreenerror", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msfullscreenchange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface Element { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSNamespaceInfo { + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface Window { + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "devicemotion", listener: (ev: DeviceMotionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "deviceorientation", listener: (ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface SVGElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLFrameElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface XMLHttpRequest { + addEventListener(type: "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLFrameSetElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface Screen { + addEventListener(type: "msorientationchange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface SVGSVGElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "zoom", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLIFrameElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLBodyElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface XDomainRequest { + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLMarqueeElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "bounce", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "start", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "finish", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSWindowExtensions { + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLMediaElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msneedkey", listener: (ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface HTMLVideoElement { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgotpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mslostpointercapture", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "move", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "datasetchanged", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsdelete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "losecapture", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "controlselect", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "layoutcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "filterchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "datasetcomplete", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "errorupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cellchange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowexit", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "rowsinserted", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "propertychange", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "moveend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeeditfocus", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "afterupdate", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resizeend", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dataavailable", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "movestart", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "rowenter", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mscontentzoom", listener: (ev: MSEventObj) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "msmanipulationstatechanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "msneedkey", listener: (ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSVideoOptimalLayoutChanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "MSVideoFrameStepCompleted", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "MSVideoFormatChanged", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface TextTrackCue { + addEventListener(type: "enter", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "exit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface WebSocket { + addEventListener(type: "open", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "close", listener: (ev: CloseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface XMLHttpRequestEventTarget { + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface AudioTrackList { + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "addtrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: "removetrack", listener: (ev: any /*PluginArray*/) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSBaseReader { + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} +interface IDBTransaction { + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface TextTrackList { + addEventListener(type: "addtrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface IDBDatabase { + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface IDBOpenDBRequest { + addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "upgradeneeded", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blocked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface TextTrack { + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface IDBRequest { + addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MessagePort { + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface ApplicationCache { + addEventListener(type: "downloading", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "updateready", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cached", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "obsolete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "checking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "noupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface AbstractWorker { + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} +interface Worker { + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface GlobalEventHandlers { + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} +interface KeyOperation { + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSInputMethodContext { + addEventListener(type: "candidatewindowshow", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "candidatewindowhide", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: "candidatewindowupdate", listener: (ev: any) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface MSWebViewAsyncOperation { + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + +interface CryptoOperation { + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; +} + + +declare function addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "help", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "contextmenu", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "hashchange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerdown", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturedoubletap", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerhover", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturehold", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointermove", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturechange", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturestart", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointercancel", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgestureend", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msgesturetap", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerout", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "msinertiastart", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerover", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerup", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "devicemotion", listener: (ev: DeviceMotionEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "deviceorientation", listener: (ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerenter", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mspointerleave", listener: (ev: any) => any, useCapture?: boolean): void; +declare function addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; + + +///////////////////////////// +/// WorkerGlobalScope APIs +///////////////////////////// +// TODO: These are only available in a Web Worker - should be in a separate 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: any): void; + StdErr: ITextWriter; + StdOut: ITextWriter; + Arguments: { length: number; Item(n: number): string; }; + ScriptFullName: string; + Quit(exitCode?: number): number; +} diff --git a/_infrastructure/tests/typescript/1.0.2.1-225bad/tsc b/_infrastructure/tests/typescript/1.0.2.1-225bad/tsc new file mode 100644 index 0000000000..3c0dab574f --- /dev/null +++ b/_infrastructure/tests/typescript/1.0.2.1-225bad/tsc @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('./tsc.js') diff --git a/_infrastructure/tests/typescript/1.0.2.1-225bad/tsc.js b/_infrastructure/tests/typescript/1.0.2.1-225bad/tsc.js new file mode 100644 index 0000000000..097b4477b4 --- /dev/null +++ b/_infrastructure/tests/typescript/1.0.2.1-225bad/tsc.js @@ -0,0 +1,62929 @@ +/*! ***************************************************************************** +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) { + TypeScript.DiagnosticCode = { + error_TS_0_1: "error TS{0}: {1}", + warning_TS_0_1: "warning TS{0}: {1}", + Unrecognized_escape_sequence: "Unrecognized escape sequence.", + Unexpected_character_0: "Unexpected character {0}.", + Missing_close_quote_character: "Missing close quote character.", + Identifier_expected: "Identifier expected.", + _0_keyword_expected: "'{0}' keyword expected.", + _0_expected: "'{0}' expected.", + Identifier_expected_0_is_a_keyword: "Identifier expected; '{0}' is a keyword.", + Automatic_semicolon_insertion_not_allowed: "Automatic semicolon insertion not allowed.", + Unexpected_token_0_expected: "Unexpected token; '{0}' expected.", + Trailing_separator_not_allowed: "Trailing separator not allowed.", + AsteriskSlash_expected: "'*/' expected.", + public_or_private_modifier_must_precede_static: "'public' or 'private' modifier must precede 'static'.", + Unexpected_token: "Unexpected token.", + Catch_clause_parameter_cannot_have_a_type_annotation: "Catch clause parameter cannot have a type annotation.", + Rest_parameter_must_be_last_in_list: "Rest parameter must be last in list.", + Parameter_cannot_have_question_mark_and_initializer: "Parameter cannot have question mark and initializer.", + Required_parameter_cannot_follow_optional_parameter: "Required parameter cannot follow optional parameter.", + Index_signatures_cannot_have_rest_parameters: "Index signatures cannot have rest parameters.", + Index_signature_parameter_cannot_have_accessibility_modifiers: "Index signature parameter cannot have accessibility modifiers.", + Index_signature_parameter_cannot_have_a_question_mark: "Index signature parameter cannot have a question mark.", + Index_signature_parameter_cannot_have_an_initializer: "Index signature parameter cannot have an initializer.", + Index_signature_must_have_a_type_annotation: "Index signature must have a type annotation.", + Index_signature_parameter_must_have_a_type_annotation: "Index signature parameter must have a type annotation.", + Index_signature_parameter_type_must_be_string_or_number: "Index signature parameter type must be 'string' or 'number'.", + extends_clause_already_seen: "'extends' clause already seen.", + extends_clause_must_precede_implements_clause: "'extends' clause must precede 'implements' clause.", + Classes_can_only_extend_a_single_class: "Classes can only extend a single class.", + implements_clause_already_seen: "'implements' clause already seen.", + Accessibility_modifier_already_seen: "Accessibility modifier already seen.", + _0_modifier_must_precede_1_modifier: "'{0}' modifier must precede '{1}' modifier.", + _0_modifier_already_seen: "'{0}' modifier already seen.", + _0_modifier_cannot_appear_on_a_class_element: "'{0}' modifier cannot appear on a class element.", + Interface_declaration_cannot_have_implements_clause: "Interface declaration cannot have 'implements' clause.", + super_invocation_cannot_have_type_arguments: "'super' invocation cannot have type arguments.", + Only_ambient_modules_can_use_quoted_names: "Only ambient modules can use quoted names.", + Statements_are_not_allowed_in_ambient_contexts: "Statements are not allowed in ambient contexts.", + Implementations_are_not_allowed_in_ambient_contexts: "Implementations are not allowed in ambient contexts.", + declare_modifier_not_allowed_for_code_already_in_an_ambient_context: "'declare' modifier not allowed for code already in an ambient context.", + Initializers_are_not_allowed_in_ambient_contexts: "Initializers are not allowed in ambient contexts.", + Parameter_property_declarations_can_only_be_used_in_a_non_ambient_constructor_declaration: "Parameter property declarations can only be used in a non-ambient constructor declaration.", + Function_implementation_expected: "Function implementation expected.", + Constructor_implementation_expected: "Constructor implementation expected.", + Function_overload_name_must_be_0: "Function overload name must be '{0}'.", + _0_modifier_cannot_appear_on_a_module_element: "'{0}' modifier cannot appear on a module element.", + declare_modifier_cannot_appear_on_an_interface_declaration: "'declare' modifier cannot appear on an interface declaration.", + declare_modifier_required_for_top_level_element: "'declare' modifier required for top level element.", + Rest_parameter_cannot_be_optional: "Rest parameter cannot be optional.", + Rest_parameter_cannot_have_an_initializer: "Rest parameter cannot have an initializer.", + set_accessor_must_have_one_and_only_one_parameter: "'set' accessor must have one and only one parameter.", + set_accessor_parameter_cannot_be_optional: "'set' accessor parameter cannot be optional.", + set_accessor_parameter_cannot_have_an_initializer: "'set' accessor parameter cannot have an initializer.", + set_accessor_cannot_have_rest_parameter: "'set' accessor cannot have rest parameter.", + get_accessor_cannot_have_parameters: "'get' accessor cannot have parameters.", + Modifiers_cannot_appear_here: "Modifiers cannot appear here.", + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: "Accessors are only available when targeting ECMAScript 5 and higher.", + Class_name_cannot_be_0: "Class name cannot be '{0}'.", + Interface_name_cannot_be_0: "Interface name cannot be '{0}'.", + Enum_name_cannot_be_0: "Enum name cannot be '{0}'.", + Module_name_cannot_be_0: "Module name cannot be '{0}'.", + Enum_member_must_have_initializer: "Enum member must have initializer.", + Export_assignment_cannot_be_used_in_internal_modules: "Export assignment cannot be used in internal modules.", + Export_assignment_not_allowed_in_module_with_exported_element: "Export assignment not allowed in module with exported element.", + Module_cannot_have_multiple_export_assignments: "Module cannot have multiple export assignments.", + Ambient_enum_elements_can_only_have_integer_literal_initializers: "Ambient enum elements can only have integer literal initializers.", + module_class_interface_enum_import_or_statement: "module, class, interface, enum, import or statement", + constructor_function_accessor_or_variable: "constructor, function, accessor or variable", + statement: "statement", + case_or_default_clause: "case or default clause", + identifier: "identifier", + call_construct_index_property_or_function_signature: "call, construct, index, property or function signature", + expression: "expression", + type_name: "type name", + property_or_accessor: "property or accessor", + parameter: "parameter", + type: "type", + type_parameter: "type parameter", + declare_modifier_not_allowed_on_import_declaration: "'declare' modifier not allowed on import declaration.", + Function_overload_must_be_static: "Function overload must be static.", + Function_overload_must_not_be_static: "Function overload must not be static.", + Parameter_property_declarations_cannot_be_used_in_a_constructor_overload: "Parameter property declarations cannot be used in a constructor overload.", + Invalid_reference_directive_syntax: "Invalid 'reference' directive syntax.", + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: "Octal literals are not available when targeting ECMAScript 5 and higher.", + Accessors_are_not_allowed_in_ambient_contexts: "Accessors are not allowed in ambient contexts.", + _0_modifier_cannot_appear_on_a_constructor_declaration: "'{0}' modifier cannot appear on a constructor declaration.", + _0_modifier_cannot_appear_on_a_parameter: "'{0}' modifier cannot appear on a parameter.", + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: "Only a single variable declaration is allowed in a 'for...in' statement.", + Type_parameters_cannot_appear_on_a_constructor_declaration: "Type parameters cannot appear on a constructor declaration.", + Type_annotation_cannot_appear_on_a_constructor_declaration: "Type annotation cannot appear on a constructor declaration.", + Duplicate_identifier_0: "Duplicate identifier '{0}'.", + The_name_0_does_not_exist_in_the_current_scope: "The name '{0}' does not exist in the current scope.", + The_name_0_does_not_refer_to_a_value: "The name '{0}' does not refer to a value.", + super_can_only_be_used_inside_a_class_instance_method: "'super' can only be used inside a class instance method.", + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_property_or_indexer: "The left-hand side of an assignment expression must be a variable, property or indexer.", + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: "Value of type '{0}' is not callable. Did you mean to include 'new'?", + Value_of_type_0_is_not_callable: "Value of type '{0}' is not callable.", + Value_of_type_0_is_not_newable: "Value of type '{0}' is not newable.", + Value_of_type_0_is_not_indexable_by_type_1: "Value of type '{0}' is not indexable by type '{1}'.", + Operator_0_cannot_be_applied_to_types_1_and_2: "Operator '{0}' cannot be applied to types '{1}' and '{2}'.", + Operator_0_cannot_be_applied_to_types_1_and_2_3: "Operator '{0}' cannot be applied to types '{1}' and '{2}': {3}", + Cannot_convert_0_to_1: "Cannot convert '{0}' to '{1}'.", + Cannot_convert_0_to_1_NL_2: "Cannot convert '{0}' to '{1}':{NL}{2}", + Expected_var_class_interface_or_module: "Expected var, class, interface, or module.", + Operator_0_cannot_be_applied_to_type_1: "Operator '{0}' cannot be applied to type '{1}'.", + Getter_0_already_declared: "Getter '{0}' already declared.", + Setter_0_already_declared: "Setter '{0}' already declared.", + Exported_class_0_extends_private_class_1: "Exported class '{0}' extends private class '{1}'.", + Exported_class_0_implements_private_interface_1: "Exported class '{0}' implements private interface '{1}'.", + Exported_interface_0_extends_private_interface_1: "Exported interface '{0}' extends private interface '{1}'.", + Exported_class_0_extends_class_from_inaccessible_module_1: "Exported class '{0}' extends class from inaccessible module {1}.", + Exported_class_0_implements_interface_from_inaccessible_module_1: "Exported class '{0}' implements interface from inaccessible module {1}.", + Exported_interface_0_extends_interface_from_inaccessible_module_1: "Exported interface '{0}' extends interface from inaccessible module {1}.", + Public_static_property_0_of_exported_class_has_or_is_using_private_type_1: "Public static property '{0}' of exported class has or is using private type '{1}'.", + Public_property_0_of_exported_class_has_or_is_using_private_type_1: "Public property '{0}' of exported class has or is using private type '{1}'.", + Property_0_of_exported_interface_has_or_is_using_private_type_1: "Property '{0}' of exported interface has or is using private type '{1}'.", + Exported_variable_0_has_or_is_using_private_type_1: "Exported variable '{0}' has or is using private type '{1}'.", + Public_static_property_0_of_exported_class_is_using_inaccessible_module_1: "Public static property '{0}' of exported class is using inaccessible module {1}.", + Public_property_0_of_exported_class_is_using_inaccessible_module_1: "Public property '{0}' of exported class is using inaccessible module {1}.", + Property_0_of_exported_interface_is_using_inaccessible_module_1: "Property '{0}' of exported interface is using inaccessible module {1}.", + Exported_variable_0_is_using_inaccessible_module_1: "Exported variable '{0}' is using inaccessible module {1}.", + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of constructor from exported class has or is using private type '{1}'.", + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public static property setter from exported class has or is using private type '{1}'.", + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public property setter from exported class has or is using private type '{1}'.", + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.", + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of call signature from exported interface has or is using private type '{1}'.", + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public static method from exported class has or is using private type '{1}'.", + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public method from exported class has or is using private type '{1}'.", + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of method from exported interface has or is using private type '{1}'.", + Parameter_0_of_exported_function_has_or_is_using_private_type_1: "Parameter '{0}' of exported function has or is using private type '{1}'.", + Parameter_0_of_constructor_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of constructor from exported class is using inaccessible module {1}.", + Parameter_0_of_public_static_property_setter_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public static property setter from exported class is using inaccessible module {1}.", + Parameter_0_of_public_property_setter_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public property setter from exported class is using inaccessible module {1}.", + Parameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.", + Parameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of call signature from exported interface is using inaccessible module {1}", + Parameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public static method from exported class is using inaccessible module {1}.", + Parameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public method from exported class is using inaccessible module {1}.", + Parameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of method from exported interface is using inaccessible module {1}.", + Parameter_0_of_exported_function_is_using_inaccessible_module_1: "Parameter '{0}' of exported function is using inaccessible module {1}.", + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type_0: "Return type of public static property getter from exported class has or is using private type '{0}'.", + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type_0: "Return type of public property getter from exported class has or is using private type '{0}'.", + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of constructor signature from exported interface has or is using private type '{0}'.", + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of call signature from exported interface has or is using private type '{0}'.", + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of index signature from exported interface has or is using private type '{0}'.", + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type_0: "Return type of public static method from exported class has or is using private type '{0}'.", + Return_type_of_public_method_from_exported_class_has_or_is_using_private_type_0: "Return type of public method from exported class has or is using private type '{0}'.", + Return_type_of_method_from_exported_interface_has_or_is_using_private_type_0: "Return type of method from exported interface has or is using private type '{0}'.", + Return_type_of_exported_function_has_or_is_using_private_type_0: "Return type of exported function has or is using private type '{0}'.", + Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module_0: "Return type of public static property getter from exported class is using inaccessible module {0}.", + Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module_0: "Return type of public property getter from exported class is using inaccessible module {0}.", + Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of constructor signature from exported interface is using inaccessible module {0}.", + Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of call signature from exported interface is using inaccessible module {0}.", + Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of index signature from exported interface is using inaccessible module {0}.", + Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module_0: "Return type of public static method from exported class is using inaccessible module {0}.", + Return_type_of_public_method_from_exported_class_is_using_inaccessible_module_0: "Return type of public method from exported class is using inaccessible module {0}.", + Return_type_of_method_from_exported_interface_is_using_inaccessible_module_0: "Return type of method from exported interface is using inaccessible module {0}.", + Return_type_of_exported_function_is_using_inaccessible_module_0: "Return type of exported function is using inaccessible module {0}.", + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: "'new T[]' cannot be used to create an array. Use 'new Array()' instead.", + A_parameter_list_must_follow_a_generic_type_argument_list_expected: "A parameter list must follow a generic type argument list. '(' expected.", + Multiple_constructor_implementations_are_not_allowed: "Multiple constructor implementations are not allowed.", + Unable_to_resolve_external_module_0: "Unable to resolve external module '{0}'.", + Module_cannot_be_aliased_to_a_non_module_type: "Module cannot be aliased to a non-module type.", + A_class_may_only_extend_another_class: "A class may only extend another class.", + A_class_may_only_implement_another_class_or_interface: "A class may only implement another class or interface.", + An_interface_may_only_extend_another_class_or_interface: "An interface may only extend another class or interface.", + Unable_to_resolve_type: "Unable to resolve type.", + Unable_to_resolve_type_of_0: "Unable to resolve type of '{0}'.", + Unable_to_resolve_type_parameter_constraint: "Unable to resolve type parameter constraint.", + Type_parameter_constraint_cannot_be_a_primitive_type: "Type parameter constraint cannot be a primitive type.", + Supplied_parameters_do_not_match_any_signature_of_call_target: "Supplied parameters do not match any signature of call target.", + Supplied_parameters_do_not_match_any_signature_of_call_target_NL_0: "Supplied parameters do not match any signature of call target:{NL}{0}", + Invalid_new_expression: "Invalid 'new' expression.", + Call_signatures_used_in_a_new_expression_must_have_a_void_return_type: "Call signatures used in a 'new' expression must have a 'void' return type.", + Could_not_select_overload_for_new_expression: "Could not select overload for 'new' expression.", + Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2: "Type '{0}' does not satisfy the constraint '{1}' for type parameter '{2}'.", + Could_not_select_overload_for_call_expression: "Could not select overload for 'call' expression.", + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: "Cannot invoke an expression whose type lacks a call signature.", + Calls_to_super_are_only_valid_inside_a_class: "Calls to 'super' are only valid inside a class.", + Generic_type_0_requires_1_type_argument_s: "Generic type '{0}' requires {1} type argument(s).", + Type_of_array_literal_cannot_be_determined_Best_common_type_could_not_be_found_for_array_elements: "Type of array literal cannot be determined. Best common type could not be found for array elements.", + Could_not_find_enclosing_symbol_for_dotted_name_0: "Could not find enclosing symbol for dotted name '{0}'.", + The_property_0_does_not_exist_on_value_of_type_1: "The property '{0}' does not exist on value of type '{1}'.", + Could_not_find_symbol_0: "Could not find symbol '{0}'.", + get_and_set_accessor_must_have_the_same_type: "'get' and 'set' accessor must have the same type.", + this_cannot_be_referenced_in_current_location: "'this' cannot be referenced in current location.", + Static_members_cannot_reference_class_type_parameters: "Static members cannot reference class type parameters.", + Class_0_is_recursively_referenced_as_a_base_type_of_itself: "Class '{0}' is recursively referenced as a base type of itself.", + Interface_0_is_recursively_referenced_as_a_base_type_of_itself: "Interface '{0}' is recursively referenced as a base type of itself.", + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class.", + super_cannot_be_referenced_in_non_derived_classes: "'super' cannot be referenced in non-derived classes.", + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.", + Constructors_for_derived_classes_must_contain_a_super_call: "Constructors for derived classes must contain a 'super' call.", + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: "Super calls are not permitted outside constructors or in nested functions inside constructors.", + _0_1_is_inaccessible: "'{0}.{1}' is inaccessible.", + this_cannot_be_referenced_within_module_bodies: "'this' cannot be referenced within module bodies.", + Invalid_expression_types_not_known_to_support_the_addition_operator: "Invalid '+' expression - types not known to support the addition operator.", + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type_any_number_or_an_enum_type: "The type of a unary arithmetic operation operand must be of type 'any', 'number' or an enum type.", + Variable_declarations_of_a_for_statement_cannot_use_a_type_annotation: "Variable declarations of a 'for' statement cannot use a type annotation.", + Variable_declarations_of_a_for_statement_must_be_of_types_string_or_any: "Variable declarations of a 'for' statement must be of types 'string' or 'any'.", + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter.", + The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number: "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'.", + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.", + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.", + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.", + Setters_cannot_return_a_value: "Setters cannot return a value.", + Tried_to_query_type_of_uninitialized_module_0: "Tried to query type of uninitialized module '{0}'.", + Tried_to_set_variable_type_to_uninitialized_module_type_0: "Tried to set variable type to uninitialized module type '{0}'.", + Type_0_does_not_have_type_parameters: "Type '{0}' does not have type parameters.", + Getters_must_return_a_value: "Getters must return a value.", + Getter_and_setter_accessors_do_not_agree_in_visibility: "Getter and setter accessors do not agree in visibility.", + Invalid_left_hand_side_of_assignment_expression: "Invalid left-hand side of assignment expression.", + Function_declared_a_non_void_return_type_but_has_no_return_expression: "Function declared a non-void return type, but has no return expression.", + Cannot_resolve_return_type_reference: "Cannot resolve return type reference.", + Constructors_cannot_have_a_return_type_of_void: "Constructors cannot have a return type of 'void'.", + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'.", + All_symbols_within_a_with_block_will_be_resolved_to_any: "All symbols within a with block will be resolved to 'any'.", + Import_declarations_in_an_internal_module_cannot_reference_an_external_module: "Import declarations in an internal module cannot reference an external module.", + Class_0_declares_interface_1_but_does_not_implement_it_NL_2: "Class {0} declares interface {1} but does not implement it:{NL}{2}", + Class_0_declares_class_1_as_an_interface_but_does_not_implement_it_NL_2: "Class {0} declares class {1} as an interface but does not implement it:{NL}{2}", + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: "The operand of an increment or decrement operator must be a variable, property or indexer.", + this_cannot_be_referenced_in_static_initializers_in_a_class_body: "'this' cannot be referenced in static initializers in a class body.", + Class_0_cannot_extend_class_1_NL_2: "Class '{0}' cannot extend class '{1}':{NL}{2}", + Interface_0_cannot_extend_class_1_NL_2: "Interface '{0}' cannot extend class '{1}':{NL}{2}", + Interface_0_cannot_extend_interface_1_NL_2: "Interface '{0}' cannot extend interface '{1}':{NL}{2}", + Duplicate_overload_signature_for_0: "Duplicate overload signature for '{0}'.", + Duplicate_constructor_overload_signature: "Duplicate constructor overload signature.", + Duplicate_overload_call_signature: "Duplicate overload call signature.", + Duplicate_overload_construct_signature: "Duplicate overload construct signature.", + Overload_signature_is_not_compatible_with_function_definition: "Overload signature is not compatible with function definition.", + Overload_signature_is_not_compatible_with_function_definition_NL_0: "Overload signature is not compatible with function definition:{NL}{0}", + Overload_signatures_must_all_be_public_or_private: "Overload signatures must all be public or private.", + Overload_signatures_must_all_be_exported_or_not_exported: "Overload signatures must all be exported or not exported.", + Overload_signatures_must_all_be_ambient_or_non_ambient: "Overload signatures must all be ambient or non-ambient.", + Overload_signatures_must_all_be_optional_or_required: "Overload signatures must all be optional or required.", + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: "Specialized overload signature is not assignable to any non-specialized signature.", + this_cannot_be_referenced_in_constructor_arguments: "'this' cannot be referenced in constructor arguments.", + Instance_member_cannot_be_accessed_off_a_class: "Instance member cannot be accessed off a class.", + Untyped_function_calls_may_not_accept_type_arguments: "Untyped function calls may not accept type arguments.", + Non_generic_functions_may_not_accept_type_arguments: "Non-generic functions may not accept type arguments.", + A_generic_type_may_not_reference_itself_with_a_wrapped_form_of_its_own_type_parameters: "A generic type may not reference itself with a wrapped form of its own type parameters.", + Rest_parameters_must_be_array_types: "Rest parameters must be array types.", + Overload_signature_implementation_cannot_use_specialized_type: "Overload signature implementation cannot use specialized type.", + Export_assignments_may_only_be_used_at_the_top_level_of_external_modules: "Export assignments may only be used at the top-level of external modules.", + Export_assignments_may_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: "Export assignments may only be made with variables, functions, classes, interfaces, enums and internal modules.", + Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword: "Only public methods of the base class are accessible via the 'super' keyword.", + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1: "Numeric indexer type '{0}' must be assignable to string indexer type '{1}'.", + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1_NL_2: "Numeric indexer type '{0}' must be assignable to string indexer type '{1}':{NL}{2}", + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0: "All numerically named properties must be assignable to numeric indexer type '{0}'.", + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0_NL_1: "All numerically named properties must be assignable to numeric indexer type '{0}':{NL}{1}", + All_named_properties_must_be_assignable_to_string_indexer_type_0: "All named properties must be assignable to string indexer type '{0}'.", + All_named_properties_must_be_assignable_to_string_indexer_type_0_NL_1: "All named properties must be assignable to string indexer type '{0}':{NL}{1}", + Generic_type_references_must_include_all_type_arguments: "Generic type references must include all type arguments.", + Default_arguments_are_only_allowed_in_implementation: "Default arguments are only allowed in implementation.", + Overloads_cannot_differ_only_by_return_type: "Overloads cannot differ only by return type.", + Function_expression_declared_a_non_void_return_type_but_has_no_return_expression: "Function expression declared a non-void return type, but has no return expression.", + Import_declaration_referencing_identifier_from_internal_module_can_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: "Import declaration referencing identifier from internal module can only be made with variables, functions, classes, interfaces, enums and internal modules.", + Could_not_find_symbol_0_in_module_1: "Could not find symbol '{0}' in module '{1}'.", + Unable_to_resolve_module_reference_0: "Unable to resolve module reference '{0}'.", + Could_not_find_module_0_in_module_1: "Could not find module '{0}' in module '{1}'.", + Exported_import_declaration_0_is_assigned_value_with_type_that_has_or_is_using_private_type_1: "Exported import declaration '{0}' is assigned value with type that has or is using private type '{1}'.", + Exported_import_declaration_0_is_assigned_value_with_type_that_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned value with type that is using inaccessible module '{1}'.", + Exported_import_declaration_0_is_assigned_type_that_has_or_is_using_private_type_1: "Exported import declaration '{0}' is assigned type that has or is using private type '{1}'.", + Exported_import_declaration_0_is_assigned_type_that_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned type that is using inaccessible module '{1}'.", + Exported_import_declaration_0_is_assigned_container_that_is_or_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned container that is or is using inaccessible module '{1}'.", + Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_1: "Type name '{0}' in extends clause does not reference constructor function for '{1}'.", + Internal_module_reference_0_in_import_declaration_does_not_reference_module_instance_for_1: "Internal module reference '{0}' in import declaration does not reference module instance for '{1}'.", + Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2: "Module '{0}' cannot merge with previous declaration of '{1}' in a different file '{2}'.", + Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':{NL}{3}", + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it.", + Ambient_external_module_declaration_cannot_be_reopened: "Ambient external module declaration cannot be reopened.", + All_declarations_of_merged_declaration_0_must_be_exported_or_not_exported: "All declarations of merged declaration '{0}' must be exported or not exported.", + super_cannot_be_referenced_in_constructor_arguments: "'super' cannot be referenced in constructor arguments.", + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: "Return type of constructor signature must be assignable to the instance type of the class.", + Ambient_external_module_declaration_must_be_defined_in_global_context: "Ambient external module declaration must be defined in global context.", + Ambient_external_module_declaration_cannot_specify_relative_module_name: "Ambient external module declaration cannot specify relative module name.", + Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name: "Import declaration in an ambient external module declaration cannot reference external module through relative external module name.", + Could_not_find_the_best_common_type_of_types_of_all_return_statement_expressions: "Could not find the best common type of types of all return statement expressions.", + Import_declaration_cannot_refer_to_external_module_reference_when_noResolve_option_is_set: "Import declaration cannot refer to external module reference when --noResolve option is set.", + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference.", + continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: "'continue' statement can only be used within an enclosing iteration statement.", + break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: "'break' statement can only be used within an enclosing iteration or switch statement.", + Jump_target_not_found: "Jump target not found.", + Jump_target_cannot_cross_function_boundary: "Jump target cannot cross function boundary.", + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference.", + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference.", + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: "Expression resolves to '_super' that compiler uses to capture base class reference.", + TypeParameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of call signature from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of public static method from exported class has or is using private type '{1}'.", + TypeParameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of public method from exported class has or is using private type '{1}'.", + TypeParameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of method from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_exported_function_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported function has or is using private type '{1}'.", + TypeParameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.", + TypeParameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of call signature from exported interface is using inaccessible module {1}", + TypeParameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of public static method from exported class is using inaccessible module {1}.", + TypeParameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of public method from exported class is using inaccessible module {1}.", + TypeParameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of method from exported interface is using inaccessible module {1}.", + TypeParameter_0_of_exported_function_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported function is using inaccessible module {1}.", + TypeParameter_0_of_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported class has or is using private type '{1}'.", + TypeParameter_0_of_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported interface has or is using private type '{1}'.", + TypeParameter_0_of_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported class is using inaccessible module {1}.", + TypeParameter_0_of_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported interface is using inaccessible module {1}.", + Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter: "Duplicate identifier '_i'. Compiler uses '_i' to initialize rest parameter.", + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters.", + Type_of_conditional_0_must_be_identical_to_1_or_2: "Type of conditional '{0}' must be identical to '{1}' or '{2}'.", + Type_of_conditional_0_must_be_identical_to_1_2_or_3: "Type of conditional '{0}' must be identical to '{1}', '{2}' or '{3}'.", + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of an external module.", + Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.", + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.", + Parameter_0_cannot_be_referenced_in_its_initializer: "Parameter '{0}' cannot be referenced in its initializer.", + Duplicate_string_index_signature: "Duplicate string index signature.", + Duplicate_number_index_signature: "Duplicate number index signature.", + All_declarations_of_an_interface_must_have_identical_type_parameters: "All declarations of an interface must have identical type parameters.", + Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter: "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter.", + Type_0_is_missing_property_1_from_type_2: "Type '{0}' is missing property '{1}' from type '{2}'.", + Types_of_property_0_of_types_1_and_2_are_incompatible: "Types of property '{0}' of types '{1}' and '{2}' are incompatible.", + Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3: "Types of property '{0}' of types '{1}' and '{2}' are incompatible:{NL}{3}", + Property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2: "Property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.", + Property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2: "Property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.", + Types_0_and_1_define_property_2_as_private: "Types '{0}' and '{1}' define property '{2}' as private.", + Call_signatures_of_types_0_and_1_are_incompatible: "Call signatures of types '{0}' and '{1}' are incompatible.", + Call_signatures_of_types_0_and_1_are_incompatible_NL_2: "Call signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Type_0_requires_a_call_signature_but_type_1_lacks_one: "Type '{0}' requires a call signature, but type '{1}' lacks one.", + Construct_signatures_of_types_0_and_1_are_incompatible: "Construct signatures of types '{0}' and '{1}' are incompatible.", + Construct_signatures_of_types_0_and_1_are_incompatible_NL_2: "Construct signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Type_0_requires_a_construct_signature_but_type_1_lacks_one: "Type '{0}' requires a construct signature, but type '{1}' lacks one.", + Index_signatures_of_types_0_and_1_are_incompatible: "Index signatures of types '{0}' and '{1}' are incompatible.", + Index_signatures_of_types_0_and_1_are_incompatible_NL_2: "Index signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Call_signature_expects_0_or_fewer_parameters: "Call signature expects {0} or fewer parameters.", + Could_not_apply_type_0_to_argument_1_which_is_of_type_2: "Could not apply type '{0}' to argument {1} which is of type '{2}'.", + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function.", + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.", + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor.", + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.", + Types_of_static_property_0_of_class_1_and_class_2_are_incompatible: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible.", + Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible:{NL}{3}", + Type_reference_cannot_refer_to_container_0: "Type reference cannot refer to container '{0}'.", + Type_reference_must_refer_to_type: "Type reference must refer to type.", + In_enums_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_the_first_enum_element: "In enums with multiple declarations only one declaration can omit an initializer for the first enum element.", + _0_overload_s: " (+ {0} overload(s))", + Variable_declaration_cannot_have_the_same_name_as_an_import_declaration: "Variable declaration cannot have the same name as an import declaration.", + Signature_expected_0_type_arguments_got_1_instead: "Signature expected {0} type arguments, got {1} instead.", + Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2: "Property '{0}' defined as optional in type '{1}', but is required in type '{2}'.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_do_not_refer_to_same_named_type: "Types '{0}' and '{1}' originating in infinitely expanding type reference do not refer to same named type.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments: "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2: "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments:{NL}{2}", + Named_properties_0_of_types_1_and_2_are_not_identical: "Named properties '{0}' of types '{1}' and '{2}' are not identical.", + Types_of_string_indexer_of_types_0_and_1_are_not_identical: "Types of string indexer of types '{0}' and '{1}' are not identical.", + Types_of_number_indexer_of_types_0_and_1_are_not_identical: "Types of number indexer of types '{0}' and '{1}' are not identical.", + Type_of_number_indexer_in_type_0_is_not_assignable_to_string_indexer_type_in_type_1_NL_2: "Type of number indexer in type '{0}' is not assignable to string indexer type in type '{1}'.{NL}{2}", + Type_of_property_0_in_type_1_is_not_assignable_to_string_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not assignable to string indexer type in type '{2}'.{NL}{3}", + Type_of_property_0_in_type_1_is_not_assignable_to_number_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not assignable to number indexer type in type '{2}'.{NL}{3}", + Static_property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2: "Static property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.", + Static_property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2: "Static property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.", + Types_0_and_1_define_static_property_2_as_private: "Types '{0}' and '{1}' define static property '{2}' as private.", + Current_host_does_not_support_0_option: "Current host does not support '{0}' option.", + ECMAScript_target_version_0_not_supported_Specify_a_valid_target_version_1_default_or_2: "ECMAScript target version '{0}' not supported. Specify a valid target version: '{1}' (default), or '{2}'", + Module_code_generation_0_not_supported: "Module code generation '{0}' not supported.", + Could_not_find_file_0: "Could not find file: '{0}'.", + A_file_cannot_have_a_reference_to_itself: "A file cannot have a reference to itself.", + Cannot_resolve_referenced_file_0: "Cannot resolve referenced file: '{0}'.", + Cannot_find_the_common_subdirectory_path_for_the_input_files: "Cannot find the common subdirectory path for the input files.", + Emit_Error_0: "Emit Error: {0}.", + Cannot_read_file_0_1: "Cannot read file '{0}': {1}", + Unsupported_file_encoding: "Unsupported file encoding.", + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: "Locale must be of the form or -. For example '{0}' or '{1}'.", + Unsupported_locale_0: "Unsupported locale: '{0}'.", + Execution_Failed_NL: "Execution Failed.{NL}", + Invalid_call_to_up: "Invalid call to 'up'", + Invalid_call_to_down: "Invalid call to 'down'", + Base64_value_0_finished_with_a_continuation_bit: "Base64 value '{0}' finished with a continuation bit.", + Unknown_option_0: "Unknown option '{0}'", + Expected_0_arguments_to_message_got_1_instead: "Expected {0} arguments to message, got {1} instead.", + Expected_the_message_0_to_have_1_arguments_but_it_had_2: "Expected the message '{0}' to have {1} arguments, but it had {2}", + Could_not_delete_file_0: "Could not delete file '{0}'", + Could_not_create_directory_0: "Could not create directory '{0}'", + Error_while_executing_file_0: "Error while executing file '{0}': ", + Cannot_compile_external_modules_unless_the_module_flag_is_provided: "Cannot compile external modules unless the '--module' flag is provided.", + Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: "Option mapRoot cannot be specified without specifying sourcemap option.", + Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: "Option sourceRoot cannot be specified without specifying sourcemap option.", + Options_mapRoot_and_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: "Options mapRoot and sourceRoot cannot be specified without specifying sourcemap option.", + Option_0_specified_without_1: "Option '{0}' specified without '{1}'", + codepage_option_not_supported_on_current_platform: "'codepage' option not supported on current platform.", + Concatenate_and_emit_output_to_single_file: "Concatenate and emit output to single file.", + Generates_corresponding_0_file: "Generates corresponding {0} file.", + Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: "Specifies the location where debugger should locate map files instead of generated locations.", + Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: "Specifies the location where debugger should locate TypeScript files instead of source locations.", + Watch_input_files: "Watch input files.", + Redirect_output_structure_to_the_directory: "Redirect output structure to the directory.", + Do_not_emit_comments_to_output: "Do not emit comments to output.", + Skip_resolution_and_preprocessing: "Skip resolution and preprocessing.", + Specify_ECMAScript_target_version_0_default_or_1: "Specify ECMAScript target version: '{0}' (default), or '{1}'", + Specify_module_code_generation_0_or_1: "Specify module code generation: '{0}' or '{1}'", + Print_this_message: "Print this message.", + Print_the_compiler_s_version_0: "Print the compiler's version: {0}", + Allow_use_of_deprecated_0_keyword_when_referencing_an_external_module: "Allow use of deprecated '{0}' keyword when referencing an external module.", + Specify_locale_for_errors_and_messages_For_example_0_or_1: "Specify locale for errors and messages. For example '{0}' or '{1}'", + Syntax_0: "Syntax: {0}", + options: "options", + file1: "file", + Examples: "Examples:", + Options: "Options:", + Insert_command_line_options_and_files_from_a_file: "Insert command line options and files from a file.", + Version_0: "Version {0}", + Use_the_0_flag_to_see_options: "Use the '{0}' flag to see options.", + NL_Recompiling_0: "{NL}Recompiling ({0}):", + STRING: "STRING", + KIND: "KIND", + file2: "FILE", + VERSION: "VERSION", + LOCATION: "LOCATION", + DIRECTORY: "DIRECTORY", + NUMBER: "NUMBER", + Specify_the_codepage_to_use_when_opening_source_files: "Specify the codepage to use when opening source files.", + Additional_locations: "Additional locations:", + This_version_of_the_Javascript_runtime_does_not_support_the_0_function: "This version of the Javascript runtime does not support the '{0}' function.", + Unknown_rule: "Unknown rule.", + Invalid_line_number_0: "Invalid line number ({0})", + Warn_on_expressions_and_declarations_with_an_implied_any_type: "Warn on expressions and declarations with an implied 'any' type.", + Variable_0_implicitly_has_an_any_type: "Variable '{0}' implicitly has an 'any' type.", + Parameter_0_of_1_implicitly_has_an_any_type: "Parameter '{0}' of '{1}' implicitly has an 'any' type.", + Parameter_0_of_function_type_implicitly_has_an_any_type: "Parameter '{0}' of function type implicitly has an 'any' type.", + Member_0_of_object_type_implicitly_has_an_any_type: "Member '{0}' of object type implicitly has an 'any' type.", + new_expression_which_lacks_a_constructor_signature_implicitly_has_an_any_type: "'new' expression, which lacks a constructor signature, implicitly has an 'any' type.", + _0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "'{0}', which lacks return-type annotation, implicitly has an 'any' return type.", + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Function expression, which lacks return-type annotation, implicitly has an 'any' return type.", + Parameter_0_of_lambda_function_implicitly_has_an_any_type: "Parameter '{0}' of lambda function implicitly has an 'any' type.", + Constructor_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Constructor signature, which lacks return-type annotation, implicitly has an 'any' return type.", + Lambda_Function_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Lambda Function, which lacks return-type annotation, implicitly has an 'any' return type.", + Array_Literal_implicitly_has_an_any_type_from_widening: "Array Literal implicitly has an 'any' type from widening.", + _0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type: "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type.", + Index_signature_of_object_type_implicitly_has_an_any_type: "Index signature of object type implicitly has an 'any' type.", + Object_literal_s_property_0_implicitly_has_an_any_type_from_widening: "Object literal's property '{0}' implicitly has an 'any' type from widening." + }; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ArrayUtilities = (function () { + function ArrayUtilities() { + } + ArrayUtilities.isArray = function (value) { + return Object.prototype.toString.apply(value, []) === '[object Array]'; + }; + + ArrayUtilities.sequenceEquals = function (array1, array2, equals) { + if (array1 === array2) { + return true; + } + + if (array1 === null || array2 === null) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0, n = array1.length; i < n; i++) { + if (!equals(array1[i], array2[i])) { + return false; + } + } + + return true; + }; + + ArrayUtilities.contains = function (array, value) { + for (var i = 0; i < array.length; i++) { + if (array[i] === value) { + return true; + } + } + + return false; + }; + + ArrayUtilities.groupBy = function (array, func) { + var result = {}; + + for (var i = 0, n = array.length; i < n; i++) { + var v = array[i]; + var k = func(v); + + var list = result[k] || []; + list.push(v); + result[k] = list; + } + + return result; + }; + + ArrayUtilities.distinct = function (array, equalsFn) { + var result = []; + + for (var i = 0, n = array.length; i < n; i++) { + var current = array[i]; + for (var j = 0; j < result.length; j++) { + if (equalsFn(result[j], current)) { + break; + } + } + + if (j === result.length) { + result.push(current); + } + } + + return result; + }; + + ArrayUtilities.min = function (array, func) { + var min = func(array[0]); + + for (var i = 1; i < array.length; i++) { + var next = func(array[i]); + if (next < min) { + min = next; + } + } + + return min; + }; + + ArrayUtilities.max = function (array, func) { + var max = func(array[0]); + + for (var i = 1; i < array.length; i++) { + var next = func(array[i]); + if (next > max) { + max = next; + } + } + + return max; + }; + + ArrayUtilities.last = function (array) { + if (array.length === 0) { + throw TypeScript.Errors.argumentOutOfRange('array'); + } + + return array[array.length - 1]; + }; + + ArrayUtilities.lastOrDefault = function (array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var v = array[i]; + if (predicate(v, i)) { + return v; + } + } + + return null; + }; + + ArrayUtilities.firstOrDefault = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + var value = array[i]; + if (func(value, i)) { + return value; + } + } + + return null; + }; + + ArrayUtilities.first = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + var value = array[i]; + if (!func || func(value, i)) { + return value; + } + } + + throw TypeScript.Errors.invalidOperation(); + }; + + ArrayUtilities.sum = function (array, func) { + var result = 0; + + for (var i = 0, n = array.length; i < n; i++) { + result += func(array[i]); + } + + return result; + }; + + ArrayUtilities.select = function (values, func) { + var result = new Array(values.length); + + for (var i = 0; i < values.length; i++) { + result[i] = func(values[i]); + } + + return result; + }; + + ArrayUtilities.where = function (values, func) { + var result = new Array(); + + for (var i = 0; i < values.length; i++) { + if (func(values[i])) { + result.push(values[i]); + } + } + + return result; + }; + + ArrayUtilities.any = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + if (func(array[i])) { + return true; + } + } + + return false; + }; + + ArrayUtilities.all = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + if (!func(array[i])) { + return false; + } + } + + return true; + }; + + ArrayUtilities.binarySearch = function (array, value) { + var low = 0; + var high = array.length - 1; + + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midValue = array[middle]; + + if (midValue === value) { + return middle; + } else if (midValue > value) { + high = middle - 1; + } else { + low = middle + 1; + } + } + + return ~low; + }; + + ArrayUtilities.createArray = function (length, defaultValue) { + var result = new Array(length); + for (var i = 0; i < length; i++) { + result[i] = defaultValue; + } + + return result; + }; + + ArrayUtilities.grow = function (array, length, defaultValue) { + var count = length - array.length; + for (var i = 0; i < count; i++) { + array.push(defaultValue); + } + }; + + ArrayUtilities.copy = function (sourceArray, sourceIndex, destinationArray, destinationIndex, length) { + for (var i = 0; i < length; i++) { + destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i]; + } + }; + + ArrayUtilities.indexOf = function (array, predicate) { + for (var i = 0, n = array.length; i < n; i++) { + if (predicate(array[i])) { + return i; + } + } + + return -1; + }; + return ArrayUtilities; + })(); + TypeScript.ArrayUtilities = ArrayUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (BitVector) { + var pool = []; + var Constants; + (function (Constants) { + Constants[Constants["MaxBitsPerEncodedNumber"] = 30] = "MaxBitsPerEncodedNumber"; + Constants[Constants["BitsPerEncodedBiStateValue"] = 1] = "BitsPerEncodedBiStateValue"; + + Constants[Constants["BitsPerEncodedTriStateValue"] = 2] = "BitsPerEncodedTriStateValue"; + + Constants[Constants["BiStateEncodedTrue"] = 1] = "BiStateEncodedTrue"; + Constants[Constants["BiStateClearBitsMask"] = 1] = "BiStateClearBitsMask"; + + Constants[Constants["TriStateEncodedFalse"] = 1] = "TriStateEncodedFalse"; + Constants[Constants["TriStateEncodedTrue"] = 2] = "TriStateEncodedTrue"; + Constants[Constants["TriStateClearBitsMask"] = 3] = "TriStateClearBitsMask"; + })(Constants || (Constants = {})); + + var BitVectorImpl = (function () { + function BitVectorImpl(allowUndefinedValues) { + this.allowUndefinedValues = allowUndefinedValues; + this.isReleased = false; + this.bits = []; + } + BitVectorImpl.prototype.computeTriStateArrayIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 2 /* BitsPerEncodedTriStateValue */; + + return (index / encodedValuesPerNumber) >>> 0; + }; + + BitVectorImpl.prototype.computeBiStateArrayIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 1 /* BitsPerEncodedBiStateValue */; + + return (index / encodedValuesPerNumber) >>> 0; + }; + + BitVectorImpl.prototype.computeTriStateEncodedValueIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 2 /* BitsPerEncodedTriStateValue */; + + return (index % encodedValuesPerNumber) * 2 /* BitsPerEncodedTriStateValue */; + }; + + BitVectorImpl.prototype.computeBiStateEncodedValueIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 1 /* BitsPerEncodedBiStateValue */; + + return (index % encodedValuesPerNumber) * 1 /* BitsPerEncodedBiStateValue */; + }; + + BitVectorImpl.prototype.valueAt = function (index) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + if (this.allowUndefinedValues) { + var arrayIndex = this.computeTriStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + return undefined; + } + + var bitIndex = this.computeTriStateEncodedValueIndex(index); + if (encoded & (2 /* TriStateEncodedTrue */ << bitIndex)) { + return true; + } else if (encoded & (1 /* TriStateEncodedFalse */ << bitIndex)) { + return false; + } else { + return undefined; + } + } else { + var arrayIndex = this.computeBiStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + return false; + } + + var bitIndex = this.computeBiStateEncodedValueIndex(index); + if (encoded & (1 /* BiStateEncodedTrue */ << bitIndex)) { + return true; + } else { + return false; + } + } + }; + + BitVectorImpl.prototype.setValueAt = function (index, value) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + if (this.allowUndefinedValues) { + TypeScript.Debug.assert(value === true || value === false || value === undefined, "value must only be true, false or undefined."); + + var arrayIndex = this.computeTriStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + if (value === undefined) { + return; + } + + encoded = 0; + } + + var bitIndex = this.computeTriStateEncodedValueIndex(index); + + var clearMask = ~(3 /* TriStateClearBitsMask */ << bitIndex); + encoded = encoded & clearMask; + + if (value === true) { + encoded = encoded | (2 /* TriStateEncodedTrue */ << bitIndex); + } else if (value === false) { + encoded = encoded | (1 /* TriStateEncodedFalse */ << bitIndex); + } + + this.bits[arrayIndex] = encoded; + } else { + TypeScript.Debug.assert(value === true || value === false, "value must only be true or false."); + + var arrayIndex = this.computeBiStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + if (value === false) { + return; + } + + encoded = 0; + } + + var bitIndex = this.computeBiStateEncodedValueIndex(index); + + encoded = encoded & ~(1 /* BiStateClearBitsMask */ << bitIndex); + + if (value) { + encoded = encoded | (1 /* BiStateEncodedTrue */ << bitIndex); + } + + this.bits[arrayIndex] = encoded; + } + }; + + BitVectorImpl.prototype.release = function () { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + this.isReleased = true; + this.bits.length = 0; + pool.push(this); + }; + return BitVectorImpl; + })(); + + function getBitVector(allowUndefinedValues) { + if (pool.length === 0) { + return new BitVectorImpl(allowUndefinedValues); + } + + var vector = pool.pop(); + vector.isReleased = false; + vector.allowUndefinedValues = allowUndefinedValues; + + return vector; + } + BitVector.getBitVector = getBitVector; + })(TypeScript.BitVector || (TypeScript.BitVector = {})); + var BitVector = TypeScript.BitVector; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (BitMatrix) { + var pool = []; + + var BitMatrixImpl = (function () { + function BitMatrixImpl(allowUndefinedValues) { + this.allowUndefinedValues = allowUndefinedValues; + this.isReleased = false; + this.vectors = []; + } + BitMatrixImpl.prototype.valueAt = function (x, y) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + var vector = this.vectors[x]; + if (!vector) { + return this.allowUndefinedValues ? undefined : false; + } + + return vector.valueAt(y); + }; + + BitMatrixImpl.prototype.setValueAt = function (x, y, value) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + var vector = this.vectors[x]; + if (!vector) { + if (value === undefined) { + return; + } + + vector = TypeScript.BitVector.getBitVector(this.allowUndefinedValues); + this.vectors[x] = vector; + } + + vector.setValueAt(y, value); + }; + + BitMatrixImpl.prototype.release = function () { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + this.isReleased = true; + + for (var name in this.vectors) { + if (this.vectors.hasOwnProperty(name)) { + var vector = this.vectors[name]; + vector.release(); + } + } + + this.vectors.length = 0; + pool.push(this); + }; + return BitMatrixImpl; + })(); + + function getBitMatrix(allowUndefinedValues) { + if (pool.length === 0) { + return new BitMatrixImpl(allowUndefinedValues); + } + + var matrix = pool.pop(); + matrix.isReleased = false; + matrix.allowUndefinedValues = allowUndefinedValues; + + return matrix; + } + BitMatrix.getBitMatrix = getBitMatrix; + })(TypeScript.BitMatrix || (TypeScript.BitMatrix = {})); + var BitMatrix = TypeScript.BitMatrix; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Constants) { + Constants[Constants["Max31BitInteger"] = 1073741823] = "Max31BitInteger"; + Constants[Constants["Min31BitInteger"] = -1073741824] = "Min31BitInteger"; + })(TypeScript.Constants || (TypeScript.Constants = {})); + var Constants = TypeScript.Constants; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(TypeScript.AssertionLevel || (TypeScript.AssertionLevel = {})); + var AssertionLevel = TypeScript.AssertionLevel; + + var Debug = (function () { + function Debug() { + } + Debug.shouldAssert = function (level) { + return this.currentAssertionLevel >= level; + }; + + Debug.assert = function (expression, message, verboseDebugInfo) { + if (typeof message === "undefined") { message = ""; } + if (typeof verboseDebugInfo === "undefined") { verboseDebugInfo = null; } + if (!expression) { + var verboseDebugString = ""; + if (verboseDebugInfo) { + verboseDebugString = "\r\nVerbose Debug Information:" + verboseDebugInfo(); + } + + throw new Error("Debug Failure. False expression: " + message + verboseDebugString); + } + }; + + Debug.fail = function (message) { + Debug.assert(false, message); + }; + Debug.currentAssertionLevel = 0 /* None */; + return Debug; + })(); + TypeScript.Debug = Debug; +})(TypeScript || (TypeScript = {})); +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var TypeScript; +(function (TypeScript) { + TypeScript.LocalizedDiagnosticMessages = null; + + var Location = (function () { + function Location(fileName, lineMap, start, length) { + this._fileName = fileName; + this._lineMap = lineMap; + this._start = start; + this._length = length; + } + Location.prototype.fileName = function () { + return this._fileName; + }; + + Location.prototype.lineMap = function () { + return this._lineMap; + }; + + Location.prototype.line = function () { + return this._lineMap ? this._lineMap.getLineNumberFromPosition(this.start()) : 0; + }; + + Location.prototype.character = function () { + return this._lineMap ? this._lineMap.getLineAndCharacterFromPosition(this.start()).character() : 0; + }; + + Location.prototype.start = function () { + return this._start; + }; + + Location.prototype.length = function () { + return this._length; + }; + + Location.equals = function (location1, location2) { + return location1._fileName === location2._fileName && location1._start === location2._start && location1._length === location2._length; + }; + return Location; + })(); + TypeScript.Location = Location; + + var Diagnostic = (function (_super) { + __extends(Diagnostic, _super); + function Diagnostic(fileName, lineMap, start, length, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + _super.call(this, fileName, lineMap, start, length); + this._diagnosticKey = diagnosticKey; + this._arguments = (_arguments && _arguments.length > 0) ? _arguments : null; + this._additionalLocations = (additionalLocations && additionalLocations.length > 0) ? additionalLocations : null; + } + Diagnostic.prototype.toJSON = function (key) { + var result = {}; + result.start = this.start(); + result.length = this.length(); + + result.diagnosticCode = this._diagnosticKey; + + var _arguments = this.arguments(); + if (_arguments && _arguments.length > 0) { + result.arguments = _arguments; + } + + return result; + }; + + Diagnostic.prototype.diagnosticKey = function () { + return this._diagnosticKey; + }; + + Diagnostic.prototype.arguments = function () { + return this._arguments; + }; + + Diagnostic.prototype.text = function () { + return TypeScript.getLocalizedText(this._diagnosticKey, this._arguments); + }; + + Diagnostic.prototype.message = function () { + return TypeScript.getDiagnosticMessage(this._diagnosticKey, this._arguments); + }; + + Diagnostic.prototype.additionalLocations = function () { + return this._additionalLocations || []; + }; + + Diagnostic.equals = function (diagnostic1, diagnostic2) { + return Location.equals(diagnostic1, diagnostic2) && diagnostic1._diagnosticKey === diagnostic2._diagnosticKey && TypeScript.ArrayUtilities.sequenceEquals(diagnostic1._arguments, diagnostic2._arguments, function (v1, v2) { + return v1 === v2; + }); + }; + + Diagnostic.prototype.info = function () { + return getDiagnosticInfoFromKey(this.diagnosticKey()); + }; + return Diagnostic; + })(Location); + TypeScript.Diagnostic = Diagnostic; + + function newLine() { + return TypeScript.Environment ? TypeScript.Environment.newLine : "\r\n"; + } + TypeScript.newLine = newLine; + + function getLargestIndex(diagnostic) { + var largest = -1; + var regex = /\{(\d+)\}/g; + + var match; + while (match = regex.exec(diagnostic)) { + var val = parseInt(match[1]); + if (!isNaN(val) && val > largest) { + largest = val; + } + } + + return largest; + } + + function getDiagnosticInfoFromKey(diagnosticKey) { + var result = TypeScript.diagnosticInformationMap[diagnosticKey]; + TypeScript.Debug.assert(result); + return result; + } + + function getLocalizedText(diagnosticKey, args) { + if (TypeScript.LocalizedDiagnosticMessages) { + } + + var diagnosticMessageText = TypeScript.LocalizedDiagnosticMessages ? TypeScript.LocalizedDiagnosticMessages[diagnosticKey] : diagnosticKey; + TypeScript.Debug.assert(diagnosticMessageText !== undefined && diagnosticMessageText !== null); + + var actualCount = args ? args.length : 0; + + var expectedCount = 1 + getLargestIndex(diagnosticKey); + + if (expectedCount !== actualCount) { + throw new Error(getLocalizedText(TypeScript.DiagnosticCode.Expected_0_arguments_to_message_got_1_instead, [expectedCount, actualCount])); + } + + var valueCount = 1 + getLargestIndex(diagnosticMessageText); + if (valueCount !== expectedCount) { + throw new Error(getLocalizedText(TypeScript.DiagnosticCode.Expected_the_message_0_to_have_1_arguments_but_it_had_2, [diagnosticMessageText, expectedCount, valueCount])); + } + + diagnosticMessageText = diagnosticMessageText.replace(/{(\d+)}/g, function (match, num) { + return typeof args[num] !== 'undefined' ? args[num] : match; + }); + + diagnosticMessageText = diagnosticMessageText.replace(/{(NL)}/g, function (match) { + return TypeScript.newLine(); + }); + + return diagnosticMessageText; + } + TypeScript.getLocalizedText = getLocalizedText; + + function getDiagnosticMessage(diagnosticKey, args) { + var diagnostic = getDiagnosticInfoFromKey(diagnosticKey); + var diagnosticMessageText = getLocalizedText(diagnosticKey, args); + + var message; + if (diagnostic.category === 1 /* Error */) { + message = getLocalizedText(TypeScript.DiagnosticCode.error_TS_0_1, [diagnostic.code, diagnosticMessageText]); + } else if (diagnostic.category === 0 /* Warning */) { + message = getLocalizedText(TypeScript.DiagnosticCode.warning_TS_0_1, [diagnostic.code, diagnosticMessageText]); + } else { + message = diagnosticMessageText; + } + + return message; + } + TypeScript.getDiagnosticMessage = getDiagnosticMessage; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Errors = (function () { + function Errors() { + } + Errors.argument = function (argument, message) { + return new Error("Invalid argument: " + argument + ". " + message); + }; + + Errors.argumentOutOfRange = function (argument) { + return new Error("Argument out of range: " + argument); + }; + + Errors.argumentNull = function (argument) { + return new Error("Argument null: " + argument); + }; + + Errors.abstract = function () { + return new Error("Operation not implemented properly by subclass."); + }; + + Errors.notYetImplemented = function () { + return new Error("Not yet implemented."); + }; + + Errors.invalidOperation = function (message) { + return new Error("Invalid operation: " + message); + }; + return Errors; + })(); + TypeScript.Errors = Errors; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Hash = (function () { + function Hash() { + } + Hash.computeFnv1aCharArrayHashCode = function (text, start, len) { + var hashCode = Hash.FNV_BASE; + var end = start + len; + + for (var i = start; i < end; i++) { + hashCode = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(hashCode ^ text[i], Hash.FNV_PRIME); + } + + return hashCode; + }; + + Hash.computeSimple31BitCharArrayHashCode = function (key, start, len) { + var hash = 0; + + for (var i = 0; i < len; i++) { + var ch = key[start + i]; + + hash = ((((hash << 5) - hash) | 0) + ch) | 0; + } + + return hash & 0x7FFFFFFF; + }; + + Hash.computeSimple31BitStringHashCode = function (key) { + var hash = 0; + + var start = 0; + var len = key.length; + + for (var i = 0; i < len; i++) { + var ch = key.charCodeAt(start + i); + + hash = ((((hash << 5) - hash) | 0) + ch) | 0; + } + + return hash & 0x7FFFFFFF; + }; + + Hash.computeMurmur2StringHashCode = function (key, seed) { + var m = 0x5bd1e995; + var r = 24; + + var numberOfCharsLeft = key.length; + var h = Math.abs(seed ^ numberOfCharsLeft); + + var index = 0; + while (numberOfCharsLeft >= 2) { + var c1 = key.charCodeAt(index); + var c2 = key.charCodeAt(index + 1); + + var k = Math.abs(c1 | (c2 << 16)); + + k = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(k, m); + k ^= k >> r; + k = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(k, m); + + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + h ^= k; + + index += 2; + numberOfCharsLeft -= 2; + } + + if (numberOfCharsLeft === 1) { + h ^= key.charCodeAt(index); + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + } + + h ^= h >> 13; + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + h ^= h >> 15; + + return h; + }; + + Hash.getPrime = function (min) { + for (var i = 0; i < Hash.primes.length; i++) { + var num = Hash.primes[i]; + if (num >= min) { + return num; + } + } + + throw TypeScript.Errors.notYetImplemented(); + }; + + Hash.expandPrime = function (oldSize) { + var num = oldSize << 1; + if (num > 2146435069 && 2146435069 > oldSize) { + return 2146435069; + } + return Hash.getPrime(num); + }; + + Hash.combine = function (value, currentHash) { + return (((currentHash << 5) + currentHash) + value) & 0x7FFFFFFF; + }; + Hash.FNV_BASE = 2166136261; + Hash.FNV_PRIME = 16777619; + + Hash.primes = [ + 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, + 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, + 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, + 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, + 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, + 4166287, 4999559, 5999471, 7199369]; + return Hash; + })(); + TypeScript.Hash = Hash; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Collections) { + Collections.DefaultHashTableCapacity = 1024; + + var HashTableEntry = (function () { + function HashTableEntry(Key, Value, HashCode, Next) { + this.Key = Key; + this.Value = Value; + this.HashCode = HashCode; + this.Next = Next; + } + return HashTableEntry; + })(); + + var HashTable = (function () { + function HashTable(capacity, hash) { + this.hash = hash; + this.count = 0; + var size = TypeScript.Hash.getPrime(capacity); + this.entries = TypeScript.ArrayUtilities.createArray(size, null); + } + HashTable.prototype.set = function (key, value) { + this.addOrSet(key, value, false); + }; + + HashTable.prototype.add = function (key, value) { + this.addOrSet(key, value, true); + }; + + HashTable.prototype.containsKey = function (key) { + var hashCode = this.computeHashCode(key); + var entry = this.findEntry(key, hashCode); + return entry !== null; + }; + + HashTable.prototype.get = function (key) { + var hashCode = this.computeHashCode(key); + var entry = this.findEntry(key, hashCode); + + return entry === null ? null : entry.Value; + }; + + HashTable.prototype.computeHashCode = function (key) { + var hashCode = this.hash === null ? key.hashCode : this.hash(key); + + hashCode = hashCode & 0x7FFFFFFF; + TypeScript.Debug.assert(hashCode >= 0); + + return hashCode; + }; + + HashTable.prototype.addOrSet = function (key, value, throwOnExistingEntry) { + var hashCode = this.computeHashCode(key); + + var entry = this.findEntry(key, hashCode); + if (entry !== null) { + if (throwOnExistingEntry) { + throw TypeScript.Errors.argument('key', "Key was already in table."); + } + + entry.Key = key; + entry.Value = value; + return; + } + + return this.addEntry(key, value, hashCode); + }; + + HashTable.prototype.findEntry = function (key, hashCode) { + for (var e = this.entries[hashCode % this.entries.length]; e !== null; e = e.Next) { + if (e.HashCode === hashCode && key === e.Key) { + return e; + } + } + + return null; + }; + + HashTable.prototype.addEntry = function (key, value, hashCode) { + var index = hashCode % this.entries.length; + + var e = new HashTableEntry(key, value, hashCode, this.entries[index]); + + this.entries[index] = e; + + if (this.count >= (this.entries.length / 2)) { + this.grow(); + } + + this.count++; + return e.Key; + }; + + HashTable.prototype.grow = function () { + var newSize = TypeScript.Hash.expandPrime(this.entries.length); + + var oldEntries = this.entries; + var newEntries = TypeScript.ArrayUtilities.createArray(newSize, null); + + this.entries = newEntries; + + for (var i = 0; i < oldEntries.length; i++) { + var e = oldEntries[i]; + + while (e !== null) { + var newIndex = e.HashCode % newSize; + var tmp = e.Next; + e.Next = newEntries[newIndex]; + newEntries[newIndex] = e; + e = tmp; + } + } + }; + return HashTable; + })(); + Collections.HashTable = HashTable; + + function createHashTable(capacity, hash) { + if (typeof capacity === "undefined") { capacity = Collections.DefaultHashTableCapacity; } + if (typeof hash === "undefined") { hash = null; } + return new HashTable(capacity, hash); + } + Collections.createHashTable = createHashTable; + + var currentHashCode = 1; + function identityHashCode(value) { + if (value.__hash === undefined) { + value.__hash = currentHashCode; + currentHashCode++; + } + + return value.__hash; + } + Collections.identityHashCode = identityHashCode; + })(TypeScript.Collections || (TypeScript.Collections = {})); + var Collections = TypeScript.Collections; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + TypeScript.nodeMakeDirectoryTime = 0; + TypeScript.nodeCreateBufferTime = 0; + TypeScript.nodeWriteFileSyncTime = 0; + + (function (ByteOrderMark) { + ByteOrderMark[ByteOrderMark["None"] = 0] = "None"; + ByteOrderMark[ByteOrderMark["Utf8"] = 1] = "Utf8"; + ByteOrderMark[ByteOrderMark["Utf16BigEndian"] = 2] = "Utf16BigEndian"; + ByteOrderMark[ByteOrderMark["Utf16LittleEndian"] = 3] = "Utf16LittleEndian"; + })(TypeScript.ByteOrderMark || (TypeScript.ByteOrderMark = {})); + var ByteOrderMark = TypeScript.ByteOrderMark; + + var FileInformation = (function () { + function FileInformation(contents, byteOrderMark) { + this.contents = contents; + this.byteOrderMark = byteOrderMark; + } + return FileInformation; + })(); + TypeScript.FileInformation = FileInformation; + + TypeScript.Environment = (function () { + function getWindowsScriptHostEnvironment() { + try { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + } catch (e) { + return null; + } + + 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 { + newLine: "\r\n", + currentDirectory: function () { + return WScript.CreateObject("WScript.Shell").CurrentDirectory; + }, + supportsCodePage: function () { + return WScript.ReadFile; + }, + readFile: function (path, codepage) { + try { + if (codepage !== null && this.supportsCodePage()) { + try { + var contents = WScript.ReadFile(path, codepage); + return new FileInformation(contents, 0 /* None */); + } catch (e) { + } + } + + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; + + streamObj.Charset = 'x-ansi'; + + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); + + streamObj.Position = 0; + + var byteOrderMark = 0 /* None */; + + if (bomChar.charCodeAt(0) === 0xFE && bomChar.charCodeAt(1) === 0xFF) { + streamObj.Charset = 'unicode'; + byteOrderMark = 2 /* Utf16BigEndian */; + } else if (bomChar.charCodeAt(0) === 0xFF && bomChar.charCodeAt(1) === 0xFE) { + streamObj.Charset = 'unicode'; + byteOrderMark = 3 /* Utf16LittleEndian */; + } else if (bomChar.charCodeAt(0) === 0xEF && bomChar.charCodeAt(1) === 0xBB) { + streamObj.Charset = 'utf-8'; + byteOrderMark = 1 /* Utf8 */; + } else { + streamObj.Charset = 'utf-8'; + } + + var contents = streamObj.ReadText(-1); + streamObj.Close(); + releaseStreamObject(streamObj); + return new FileInformation(contents, byteOrderMark); + } catch (err) { + var message; + if (err.number === -2147024809) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Unsupported_file_encoding, null); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Cannot_read_file_0_1, [path, err.message]); + } + + throw new Error(message); + } + }, + writeFile: function (path, contents, writeByteOrderMark) { + var textStream = getStreamObject(); + textStream.Charset = 'utf-8'; + textStream.Open(); + textStream.WriteText(contents, 0); + + if (!writeByteOrderMark) { + textStream.Position = 3; + } else { + textStream.Position = 0; + } + + var fileStream = getStreamObject(); + fileStream.Type = 1; + fileStream.Open(); + + textStream.CopyTo(fileStream); + + fileStream.Flush(); + fileStream.SaveToFile(path, 2); + fileStream.Close(); + + textStream.Flush(); + textStream.Close(); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + deleteFile: function (path) { + if (fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + listFiles: 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); + }, + arguments: args, + standardOut: WScript.StdOut + }; + } + ; + + function getNodeEnvironment() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + var _os = require('os'); + + return { + newLine: _os.EOL, + currentDirectory: function () { + return process.cwd(); + }, + supportsCodePage: function () { + return false; + }, + readFile: function (file, codepage) { + if (codepage !== null) { + throw new Error(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.codepage_option_not_supported_on_current_platform, null)); + } + + 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 new FileInformation(buffer.toString("ucs2", 2), 2 /* Utf16BigEndian */); + } + break; + case 0xFF: + if (buffer[1] === 0xFE) { + return new FileInformation(buffer.toString("ucs2", 2), 3 /* Utf16LittleEndian */); + } + break; + case 0xEF: + if (buffer[1] === 0xBB) { + return new FileInformation(buffer.toString("utf8", 3), 1 /* Utf8 */); + } + } + + return new FileInformation(buffer.toString("utf8", 0), 0 /* None */); + }, + writeFile: function (path, contents, writeByteOrderMark) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if (stats.isFile()) { + throw "\"" + path + "\" exists but isn't a directory."; + } else if (stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 509); + } + } + var start = new Date().getTime(); + mkdirRecursiveSync(_path.dirname(path)); + TypeScript.nodeMakeDirectoryTime += new Date().getTime() - start; + + if (writeByteOrderMark) { + contents = '\uFEFF' + contents; + } + + var start = new Date().getTime(); + + var chunkLength = 4 * 1024; + var fileDescriptor = _fs.openSync(path, "w"); + try { + for (var index = 0; index < contents.length; index += chunkLength) { + var bufferStart = new Date().getTime(); + var buffer = new Buffer(contents.substr(index, chunkLength), "utf8"); + TypeScript.nodeCreateBufferTime += new Date().getTime() - bufferStart; + + _fs.writeSync(fileDescriptor, buffer, 0, buffer.length, null); + } + } finally { + _fs.closeSync(fileDescriptor); + } + + TypeScript.nodeWriteFileSyncTime += new Date().getTime() - start; + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); + }, + listFiles: 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); + }, + arguments: process.argv.slice(2), + standardOut: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + } + }; + } + ; + + if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { + return getWindowsScriptHostEnvironment(); + } else if (typeof module !== 'undefined' && module.exports) { + return getNodeEnvironment(); + } else { + return null; + } + })(); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (IntegerUtilities) { + function integerDivide(numerator, denominator) { + return (numerator / denominator) >> 0; + } + IntegerUtilities.integerDivide = integerDivide; + + function integerMultiplyLow32Bits(n1, n2) { + var n1Low16 = n1 & 0x0000ffff; + var n1High16 = n1 >>> 16; + + var n2Low16 = n2 & 0x0000ffff; + var n2High16 = n2 >>> 16; + + var resultLow32 = (((n1 & 0xffff0000) * n2) >>> 0) + (((n1 & 0x0000ffff) * n2) >>> 0) >>> 0; + return resultLow32; + } + IntegerUtilities.integerMultiplyLow32Bits = integerMultiplyLow32Bits; + + function integerMultiplyHigh32Bits(n1, n2) { + var n1Low16 = n1 & 0x0000ffff; + var n1High16 = n1 >>> 16; + + var n2Low16 = n2 & 0x0000ffff; + var n2High16 = n2 >>> 16; + + var resultHigh32 = n1High16 * n2High16 + ((((n1Low16 * n2Low16) >>> 17) + n1Low16 * n2High16) >>> 15); + return resultHigh32; + } + IntegerUtilities.integerMultiplyHigh32Bits = integerMultiplyHigh32Bits; + + function isInteger(text) { + return /^[0-9]+$/.test(text); + } + IntegerUtilities.isInteger = isInteger; + + function isHexInteger(text) { + return /^0(x|X)[0-9a-fA-F]+$/.test(text); + } + IntegerUtilities.isHexInteger = isHexInteger; + })(TypeScript.IntegerUtilities || (TypeScript.IntegerUtilities = {})); + var IntegerUtilities = TypeScript.IntegerUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var LineMap = (function () { + function LineMap(_computeLineStarts, length) { + this._computeLineStarts = _computeLineStarts; + this.length = length; + this._lineStarts = null; + } + LineMap.prototype.toJSON = function (key) { + return { lineStarts: this.lineStarts(), length: this.length }; + }; + + LineMap.prototype.equals = function (other) { + return this.length === other.length && TypeScript.ArrayUtilities.sequenceEquals(this.lineStarts(), other.lineStarts(), function (v1, v2) { + return v1 === v2; + }); + }; + + LineMap.prototype.lineStarts = function () { + if (this._lineStarts === null) { + this._lineStarts = this._computeLineStarts(); + } + + return this._lineStarts; + }; + + LineMap.prototype.lineCount = function () { + return this.lineStarts().length; + }; + + LineMap.prototype.getPosition = function (line, character) { + return this.lineStarts()[line] + character; + }; + + LineMap.prototype.getLineNumberFromPosition = function (position) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + if (position === this.length) { + return this.lineCount() - 1; + } + + var lineNumber = TypeScript.ArrayUtilities.binarySearch(this.lineStarts(), position); + if (lineNumber < 0) { + lineNumber = (~lineNumber) - 1; + } + + return lineNumber; + }; + + LineMap.prototype.getLineStartPosition = function (lineNumber) { + return this.lineStarts()[lineNumber]; + }; + + LineMap.prototype.fillLineAndCharacterFromPosition = function (position, lineAndCharacter) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + lineAndCharacter.line = lineNumber; + lineAndCharacter.character = position - this.lineStarts()[lineNumber]; + }; + + LineMap.prototype.getLineAndCharacterFromPosition = function (position) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + + return new TypeScript.LineAndCharacter(lineNumber, position - this.lineStarts()[lineNumber]); + }; + LineMap.empty = new LineMap(function () { + return [0]; + }, 0); + return LineMap; + })(); + TypeScript.LineMap = LineMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var LineAndCharacter = (function () { + function LineAndCharacter(line, character) { + this._line = 0; + this._character = 0; + if (line < 0) { + throw TypeScript.Errors.argumentOutOfRange("line"); + } + + if (character < 0) { + throw TypeScript.Errors.argumentOutOfRange("character"); + } + + this._line = line; + this._character = character; + } + LineAndCharacter.prototype.line = function () { + return this._line; + }; + + LineAndCharacter.prototype.character = function () { + return this._character; + }; + return LineAndCharacter; + })(); + TypeScript.LineAndCharacter = LineAndCharacter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var MathPrototype = (function () { + function MathPrototype() { + } + MathPrototype.max = function (a, b) { + return a >= b ? a : b; + }; + + MathPrototype.min = function (a, b) { + return a <= b ? a : b; + }; + return MathPrototype; + })(); + TypeScript.MathPrototype = MathPrototype; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Collections) { + Collections.DefaultStringTableCapacity = 256; + + var StringTableEntry = (function () { + function StringTableEntry(Text, HashCode, Next) { + this.Text = Text; + this.HashCode = HashCode; + this.Next = Next; + } + return StringTableEntry; + })(); + + var StringTable = (function () { + function StringTable(capacity) { + this.count = 0; + var size = TypeScript.Hash.getPrime(capacity); + this.entries = TypeScript.ArrayUtilities.createArray(size, null); + } + StringTable.prototype.addCharArray = function (key, start, len) { + var hashCode = TypeScript.Hash.computeSimple31BitCharArrayHashCode(key, start, len) & 0x7FFFFFFF; + + var entry = this.findCharArrayEntry(key, start, len, hashCode); + if (entry !== null) { + return entry.Text; + } + + var slice = key.slice(start, start + len); + return this.addEntry(TypeScript.StringUtilities.fromCharCodeArray(slice), hashCode); + }; + + StringTable.prototype.findCharArrayEntry = function (key, start, len, hashCode) { + for (var e = this.entries[hashCode % this.entries.length]; e !== null; e = e.Next) { + if (e.HashCode === hashCode && StringTable.textCharArrayEquals(e.Text, key, start, len)) { + return e; + } + } + + return null; + }; + + StringTable.prototype.addEntry = function (text, hashCode) { + var index = hashCode % this.entries.length; + + var e = new StringTableEntry(text, hashCode, this.entries[index]); + + this.entries[index] = e; + + if (this.count === this.entries.length) { + this.grow(); + } + + this.count++; + return e.Text; + }; + + StringTable.prototype.grow = function () { + var newSize = TypeScript.Hash.expandPrime(this.entries.length); + + var oldEntries = this.entries; + var newEntries = TypeScript.ArrayUtilities.createArray(newSize, null); + + this.entries = newEntries; + + for (var i = 0; i < oldEntries.length; i++) { + var e = oldEntries[i]; + while (e !== null) { + var newIndex = e.HashCode % newSize; + var tmp = e.Next; + e.Next = newEntries[newIndex]; + newEntries[newIndex] = e; + e = tmp; + } + } + }; + + StringTable.textCharArrayEquals = function (text, array, start, length) { + if (text.length !== length) { + return false; + } + + var s = start; + for (var i = 0; i < length; i++) { + if (text.charCodeAt(i) !== array[s]) { + return false; + } + + s++; + } + + return true; + }; + return StringTable; + })(); + Collections.StringTable = StringTable; + + Collections.DefaultStringTable = new StringTable(Collections.DefaultStringTableCapacity); + })(TypeScript.Collections || (TypeScript.Collections = {})); + var Collections = TypeScript.Collections; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var StringUtilities = (function () { + function StringUtilities() { + } + StringUtilities.isString = function (value) { + return Object.prototype.toString.apply(value, []) === '[object String]'; + }; + + StringUtilities.fromCharCodeArray = function (array) { + return String.fromCharCode.apply(null, array); + }; + + StringUtilities.endsWith = function (string, value) { + return string.substring(string.length - value.length, string.length) === value; + }; + + StringUtilities.startsWith = function (string, value) { + return string.substr(0, value.length) === value; + }; + + StringUtilities.copyTo = function (source, sourceIndex, destination, destinationIndex, count) { + for (var i = 0; i < count; i++) { + destination[destinationIndex + i] = source.charCodeAt(sourceIndex + i); + } + }; + + StringUtilities.repeat = function (value, count) { + return Array(count + 1).join(value); + }; + + StringUtilities.stringEquals = function (val1, val2) { + return val1 === val2; + }; + return StringUtilities; + })(); + TypeScript.StringUtilities = StringUtilities; +})(TypeScript || (TypeScript = {})); +var global = Function("return this").call(null); + +var TypeScript; +(function (TypeScript) { + var Clock; + (function (Clock) { + Clock.now; + Clock.resolution; + + if (typeof WScript !== "undefined" && typeof global['WScript'].InitializeProjection !== "undefined") { + global['WScript'].InitializeProjection(); + + Clock.now = function () { + return TestUtilities.QueryPerformanceCounter(); + }; + + Clock.resolution = TestUtilities.QueryPerformanceFrequency(); + } else { + Clock.now = function () { + return Date.now(); + }; + + Clock.resolution = 1000; + } + })(Clock || (Clock = {})); + + var Timer = (function () { + function Timer() { + this.time = 0; + } + Timer.prototype.start = function () { + this.time = 0; + this.startTime = Clock.now(); + }; + + Timer.prototype.end = function () { + this.time = (Clock.now() - this.startTime); + }; + return Timer; + })(); + TypeScript.Timer = Timer; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + DiagnosticCategory[DiagnosticCategory["NoPrefix"] = 3] = "NoPrefix"; + })(TypeScript.DiagnosticCategory || (TypeScript.DiagnosticCategory = {})); + var DiagnosticCategory = TypeScript.DiagnosticCategory; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.diagnosticInformationMap = { + "error TS{0}: {1}": { + "code": 0, + "category": 3 /* NoPrefix */ + }, + "warning TS{0}: {1}": { + "code": 1, + "category": 3 /* NoPrefix */ + }, + "Unrecognized escape sequence.": { + "code": 1000, + "category": 1 /* Error */ + }, + "Unexpected character {0}.": { + "code": 1001, + "category": 1 /* Error */ + }, + "Missing close quote character.": { + "code": 1002, + "category": 1 /* Error */ + }, + "Identifier expected.": { + "code": 1003, + "category": 1 /* Error */ + }, + "'{0}' keyword expected.": { + "code": 1004, + "category": 1 /* Error */ + }, + "'{0}' expected.": { + "code": 1005, + "category": 1 /* Error */ + }, + "Identifier expected; '{0}' is a keyword.": { + "code": 1006, + "category": 1 /* Error */ + }, + "Automatic semicolon insertion not allowed.": { + "code": 1007, + "category": 1 /* Error */ + }, + "Unexpected token; '{0}' expected.": { + "code": 1008, + "category": 1 /* Error */ + }, + "Trailing separator not allowed.": { + "code": 1009, + "category": 1 /* Error */ + }, + "'*/' expected.": { + "code": 1010, + "category": 1 /* Error */ + }, + "'public' or 'private' modifier must precede 'static'.": { + "code": 1011, + "category": 1 /* Error */ + }, + "Unexpected token.": { + "code": 1012, + "category": 1 /* Error */ + }, + "Catch clause parameter cannot have a type annotation.": { + "code": 1013, + "category": 1 /* Error */ + }, + "Rest parameter must be last in list.": { + "code": 1014, + "category": 1 /* Error */ + }, + "Parameter cannot have question mark and initializer.": { + "code": 1015, + "category": 1 /* Error */ + }, + "Required parameter cannot follow optional parameter.": { + "code": 1016, + "category": 1 /* Error */ + }, + "Index signatures cannot have rest parameters.": { + "code": 1017, + "category": 1 /* Error */ + }, + "Index signature parameter cannot have accessibility modifiers.": { + "code": 1018, + "category": 1 /* Error */ + }, + "Index signature parameter cannot have a question mark.": { + "code": 1019, + "category": 1 /* Error */ + }, + "Index signature parameter cannot have an initializer.": { + "code": 1020, + "category": 1 /* Error */ + }, + "Index signature must have a type annotation.": { + "code": 1021, + "category": 1 /* Error */ + }, + "Index signature parameter must have a type annotation.": { + "code": 1022, + "category": 1 /* Error */ + }, + "Index signature parameter type must be 'string' or 'number'.": { + "code": 1023, + "category": 1 /* Error */ + }, + "'extends' clause already seen.": { + "code": 1024, + "category": 1 /* Error */ + }, + "'extends' clause must precede 'implements' clause.": { + "code": 1025, + "category": 1 /* Error */ + }, + "Classes can only extend a single class.": { + "code": 1026, + "category": 1 /* Error */ + }, + "'implements' clause already seen.": { + "code": 1027, + "category": 1 /* Error */ + }, + "Accessibility modifier already seen.": { + "code": 1028, + "category": 1 /* Error */ + }, + "'{0}' modifier must precede '{1}' modifier.": { + "code": 1029, + "category": 1 /* Error */ + }, + "'{0}' modifier already seen.": { + "code": 1030, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a class element.": { + "code": 1031, + "category": 1 /* Error */ + }, + "Interface declaration cannot have 'implements' clause.": { + "code": 1032, + "category": 1 /* Error */ + }, + "'super' invocation cannot have type arguments.": { + "code": 1034, + "category": 1 /* Error */ + }, + "Only ambient modules can use quoted names.": { + "code": 1035, + "category": 1 /* Error */ + }, + "Statements are not allowed in ambient contexts.": { + "code": 1036, + "category": 1 /* Error */ + }, + "Implementations are not allowed in ambient contexts.": { + "code": 1037, + "category": 1 /* Error */ + }, + "'declare' modifier not allowed for code already in an ambient context.": { + "code": 1038, + "category": 1 /* Error */ + }, + "Initializers are not allowed in ambient contexts.": { + "code": 1039, + "category": 1 /* Error */ + }, + "Parameter property declarations can only be used in a non-ambient constructor declaration.": { + "code": 1040, + "category": 1 /* Error */ + }, + "Function implementation expected.": { + "code": 1041, + "category": 1 /* Error */ + }, + "Constructor implementation expected.": { + "code": 1042, + "category": 1 /* Error */ + }, + "Function overload name must be '{0}'.": { + "code": 1043, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a module element.": { + "code": 1044, + "category": 1 /* Error */ + }, + "'declare' modifier cannot appear on an interface declaration.": { + "code": 1045, + "category": 1 /* Error */ + }, + "'declare' modifier required for top level element.": { + "code": 1046, + "category": 1 /* Error */ + }, + "Rest parameter cannot be optional.": { + "code": 1047, + "category": 1 /* Error */ + }, + "Rest parameter cannot have an initializer.": { + "code": 1048, + "category": 1 /* Error */ + }, + "'set' accessor must have one and only one parameter.": { + "code": 1049, + "category": 1 /* Error */ + }, + "'set' accessor parameter cannot be optional.": { + "code": 1051, + "category": 1 /* Error */ + }, + "'set' accessor parameter cannot have an initializer.": { + "code": 1052, + "category": 1 /* Error */ + }, + "'set' accessor cannot have rest parameter.": { + "code": 1053, + "category": 1 /* Error */ + }, + "'get' accessor cannot have parameters.": { + "code": 1054, + "category": 1 /* Error */ + }, + "Modifiers cannot appear here.": { + "code": 1055, + "category": 1 /* Error */ + }, + "Accessors are only available when targeting ECMAScript 5 and higher.": { + "code": 1056, + "category": 1 /* Error */ + }, + "Class name cannot be '{0}'.": { + "code": 1057, + "category": 1 /* Error */ + }, + "Interface name cannot be '{0}'.": { + "code": 1058, + "category": 1 /* Error */ + }, + "Enum name cannot be '{0}'.": { + "code": 1059, + "category": 1 /* Error */ + }, + "Module name cannot be '{0}'.": { + "code": 1060, + "category": 1 /* Error */ + }, + "Enum member must have initializer.": { + "code": 1061, + "category": 1 /* Error */ + }, + "Export assignment cannot be used in internal modules.": { + "code": 1063, + "category": 1 /* Error */ + }, + "Export assignment not allowed in module with exported element.": { + "code": 1064, + "category": 1 /* Error */ + }, + "Module cannot have multiple export assignments.": { + "code": 1065, + "category": 1 /* Error */ + }, + "Ambient enum elements can only have integer literal initializers.": { + "code": 1066, + "category": 1 /* Error */ + }, + "module, class, interface, enum, import or statement": { + "code": 1067, + "category": 3 /* NoPrefix */ + }, + "constructor, function, accessor or variable": { + "code": 1068, + "category": 3 /* NoPrefix */ + }, + "statement": { + "code": 1069, + "category": 3 /* NoPrefix */ + }, + "case or default clause": { + "code": 1070, + "category": 3 /* NoPrefix */ + }, + "identifier": { + "code": 1071, + "category": 3 /* NoPrefix */ + }, + "call, construct, index, property or function signature": { + "code": 1072, + "category": 3 /* NoPrefix */ + }, + "expression": { + "code": 1073, + "category": 3 /* NoPrefix */ + }, + "type name": { + "code": 1074, + "category": 3 /* NoPrefix */ + }, + "property or accessor": { + "code": 1075, + "category": 3 /* NoPrefix */ + }, + "parameter": { + "code": 1076, + "category": 3 /* NoPrefix */ + }, + "type": { + "code": 1077, + "category": 3 /* NoPrefix */ + }, + "type parameter": { + "code": 1078, + "category": 3 /* NoPrefix */ + }, + "'declare' modifier not allowed on import declaration.": { + "code": 1079, + "category": 1 /* Error */ + }, + "Function overload must be static.": { + "code": 1080, + "category": 1 /* Error */ + }, + "Function overload must not be static.": { + "code": 1081, + "category": 1 /* Error */ + }, + "Parameter property declarations cannot be used in a constructor overload.": { + "code": 1083, + "category": 1 /* Error */ + }, + "Invalid 'reference' directive syntax.": { + "code": 1084, + "category": 1 /* Error */ + }, + "Octal literals are not available when targeting ECMAScript 5 and higher.": { + "code": 1085, + "category": 1 /* Error */ + }, + "Accessors are not allowed in ambient contexts.": { + "code": 1086, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a constructor declaration.": { + "code": 1089, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a parameter.": { + "code": 1090, + "category": 1 /* Error */ + }, + "Only a single variable declaration is allowed in a 'for...in' statement.": { + "code": 1091, + "category": 1 /* Error */ + }, + "Type parameters cannot appear on a constructor declaration.": { + "code": 1091, + "category": 1 /* Error */ + }, + "Type annotation cannot appear on a constructor declaration.": { + "code": 1092, + "category": 1 /* Error */ + }, + "Duplicate identifier '{0}'.": { + "code": 2000, + "category": 1 /* Error */ + }, + "The name '{0}' does not exist in the current scope.": { + "code": 2001, + "category": 1 /* Error */ + }, + "The name '{0}' does not refer to a value.": { + "code": 2002, + "category": 1 /* Error */ + }, + "'super' can only be used inside a class instance method.": { + "code": 2003, + "category": 1 /* Error */ + }, + "The left-hand side of an assignment expression must be a variable, property or indexer.": { + "code": 2004, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not callable. Did you mean to include 'new'?": { + "code": 2161, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not callable.": { + "code": 2006, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not newable.": { + "code": 2007, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not indexable by type '{1}'.": { + "code": 2008, + "category": 1 /* Error */ + }, + "Operator '{0}' cannot be applied to types '{1}' and '{2}'.": { + "code": 2009, + "category": 1 /* Error */ + }, + "Operator '{0}' cannot be applied to types '{1}' and '{2}': {3}": { + "code": 2010, + "category": 1 /* Error */ + }, + "Cannot convert '{0}' to '{1}'.": { + "code": 2011, + "category": 1 /* Error */ + }, + "Cannot convert '{0}' to '{1}':{NL}{2}": { + "code": 2012, + "category": 1 /* Error */ + }, + "Expected var, class, interface, or module.": { + "code": 2013, + "category": 1 /* Error */ + }, + "Operator '{0}' cannot be applied to type '{1}'.": { + "code": 2014, + "category": 1 /* Error */ + }, + "Getter '{0}' already declared.": { + "code": 2015, + "category": 1 /* Error */ + }, + "Setter '{0}' already declared.": { + "code": 2016, + "category": 1 /* Error */ + }, + "Exported class '{0}' extends private class '{1}'.": { + "code": 2018, + "category": 1 /* Error */ + }, + "Exported class '{0}' implements private interface '{1}'.": { + "code": 2019, + "category": 1 /* Error */ + }, + "Exported interface '{0}' extends private interface '{1}'.": { + "code": 2020, + "category": 1 /* Error */ + }, + "Exported class '{0}' extends class from inaccessible module {1}.": { + "code": 2021, + "category": 1 /* Error */ + }, + "Exported class '{0}' implements interface from inaccessible module {1}.": { + "code": 2022, + "category": 1 /* Error */ + }, + "Exported interface '{0}' extends interface from inaccessible module {1}.": { + "code": 2023, + "category": 1 /* Error */ + }, + "Public static property '{0}' of exported class has or is using private type '{1}'.": { + "code": 2024, + "category": 1 /* Error */ + }, + "Public property '{0}' of exported class has or is using private type '{1}'.": { + "code": 2025, + "category": 1 /* Error */ + }, + "Property '{0}' of exported interface has or is using private type '{1}'.": { + "code": 2026, + "category": 1 /* Error */ + }, + "Exported variable '{0}' has or is using private type '{1}'.": { + "code": 2027, + "category": 1 /* Error */ + }, + "Public static property '{0}' of exported class is using inaccessible module {1}.": { + "code": 2028, + "category": 1 /* Error */ + }, + "Public property '{0}' of exported class is using inaccessible module {1}.": { + "code": 2029, + "category": 1 /* Error */ + }, + "Property '{0}' of exported interface is using inaccessible module {1}.": { + "code": 2030, + "category": 1 /* Error */ + }, + "Exported variable '{0}' is using inaccessible module {1}.": { + "code": 2031, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor from exported class has or is using private type '{1}'.": { + "code": 2032, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static property setter from exported class has or is using private type '{1}'.": { + "code": 2033, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public property setter from exported class has or is using private type '{1}'.": { + "code": 2034, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.": { + "code": 2035, + "category": 1 /* Error */ + }, + "Parameter '{0}' of call signature from exported interface has or is using private type '{1}'.": { + "code": 2036, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static method from exported class has or is using private type '{1}'.": { + "code": 2037, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public method from exported class has or is using private type '{1}'.": { + "code": 2038, + "category": 1 /* Error */ + }, + "Parameter '{0}' of method from exported interface has or is using private type '{1}'.": { + "code": 2039, + "category": 1 /* Error */ + }, + "Parameter '{0}' of exported function has or is using private type '{1}'.": { + "code": 2040, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor from exported class is using inaccessible module {1}.": { + "code": 2041, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static property setter from exported class is using inaccessible module {1}.": { + "code": 2042, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public property setter from exported class is using inaccessible module {1}.": { + "code": 2043, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.": { + "code": 2044, + "category": 1 /* Error */ + }, + "Parameter '{0}' of call signature from exported interface is using inaccessible module {1}": { + "code": 2045, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static method from exported class is using inaccessible module {1}.": { + "code": 2046, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public method from exported class is using inaccessible module {1}.": { + "code": 2047, + "category": 1 /* Error */ + }, + "Parameter '{0}' of method from exported interface is using inaccessible module {1}.": { + "code": 2048, + "category": 1 /* Error */ + }, + "Parameter '{0}' of exported function is using inaccessible module {1}.": { + "code": 2049, + "category": 1 /* Error */ + }, + "Return type of public static property getter from exported class has or is using private type '{0}'.": { + "code": 2050, + "category": 1 /* Error */ + }, + "Return type of public property getter from exported class has or is using private type '{0}'.": { + "code": 2051, + "category": 1 /* Error */ + }, + "Return type of constructor signature from exported interface has or is using private type '{0}'.": { + "code": 2052, + "category": 1 /* Error */ + }, + "Return type of call signature from exported interface has or is using private type '{0}'.": { + "code": 2053, + "category": 1 /* Error */ + }, + "Return type of index signature from exported interface has or is using private type '{0}'.": { + "code": 2054, + "category": 1 /* Error */ + }, + "Return type of public static method from exported class has or is using private type '{0}'.": { + "code": 2055, + "category": 1 /* Error */ + }, + "Return type of public method from exported class has or is using private type '{0}'.": { + "code": 2056, + "category": 1 /* Error */ + }, + "Return type of method from exported interface has or is using private type '{0}'.": { + "code": 2057, + "category": 1 /* Error */ + }, + "Return type of exported function has or is using private type '{0}'.": { + "code": 2058, + "category": 1 /* Error */ + }, + "Return type of public static property getter from exported class is using inaccessible module {0}.": { + "code": 2059, + "category": 1 /* Error */ + }, + "Return type of public property getter from exported class is using inaccessible module {0}.": { + "code": 2060, + "category": 1 /* Error */ + }, + "Return type of constructor signature from exported interface is using inaccessible module {0}.": { + "code": 2061, + "category": 1 /* Error */ + }, + "Return type of call signature from exported interface is using inaccessible module {0}.": { + "code": 2062, + "category": 1 /* Error */ + }, + "Return type of index signature from exported interface is using inaccessible module {0}.": { + "code": 2063, + "category": 1 /* Error */ + }, + "Return type of public static method from exported class is using inaccessible module {0}.": { + "code": 2064, + "category": 1 /* Error */ + }, + "Return type of public method from exported class is using inaccessible module {0}.": { + "code": 2065, + "category": 1 /* Error */ + }, + "Return type of method from exported interface is using inaccessible module {0}.": { + "code": 2066, + "category": 1 /* Error */ + }, + "Return type of exported function is using inaccessible module {0}.": { + "code": 2067, + "category": 1 /* Error */ + }, + "'new T[]' cannot be used to create an array. Use 'new Array()' instead.": { + "code": 2068, + "category": 1 /* Error */ + }, + "A parameter list must follow a generic type argument list. '(' expected.": { + "code": 2069, + "category": 1 /* Error */ + }, + "Multiple constructor implementations are not allowed.": { + "code": 2070, + "category": 1 /* Error */ + }, + "Unable to resolve external module '{0}'.": { + "code": 2071, + "category": 1 /* Error */ + }, + "Module cannot be aliased to a non-module type.": { + "code": 2072, + "category": 1 /* Error */ + }, + "A class may only extend another class.": { + "code": 2073, + "category": 1 /* Error */ + }, + "A class may only implement another class or interface.": { + "code": 2074, + "category": 1 /* Error */ + }, + "An interface may only extend another class or interface.": { + "code": 2075, + "category": 1 /* Error */ + }, + "Unable to resolve type.": { + "code": 2077, + "category": 1 /* Error */ + }, + "Unable to resolve type of '{0}'.": { + "code": 2078, + "category": 1 /* Error */ + }, + "Unable to resolve type parameter constraint.": { + "code": 2079, + "category": 1 /* Error */ + }, + "Type parameter constraint cannot be a primitive type.": { + "code": 2080, + "category": 1 /* Error */ + }, + "Supplied parameters do not match any signature of call target.": { + "code": 2081, + "category": 1 /* Error */ + }, + "Supplied parameters do not match any signature of call target:{NL}{0}": { + "code": 2082, + "category": 1 /* Error */ + }, + "Invalid 'new' expression.": { + "code": 2083, + "category": 1 /* Error */ + }, + "Call signatures used in a 'new' expression must have a 'void' return type.": { + "code": 2084, + "category": 1 /* Error */ + }, + "Could not select overload for 'new' expression.": { + "code": 2085, + "category": 1 /* Error */ + }, + "Type '{0}' does not satisfy the constraint '{1}' for type parameter '{2}'.": { + "code": 2086, + "category": 1 /* Error */ + }, + "Could not select overload for 'call' expression.": { + "code": 2087, + "category": 1 /* Error */ + }, + "Cannot invoke an expression whose type lacks a call signature.": { + "code": 2088, + "category": 1 /* Error */ + }, + "Calls to 'super' are only valid inside a class.": { + "code": 2089, + "category": 1 /* Error */ + }, + "Generic type '{0}' requires {1} type argument(s).": { + "code": 2090, + "category": 1 /* Error */ + }, + "Type of array literal cannot be determined. Best common type could not be found for array elements.": { + "code": 2092, + "category": 1 /* Error */ + }, + "Could not find enclosing symbol for dotted name '{0}'.": { + "code": 2093, + "category": 1 /* Error */ + }, + "The property '{0}' does not exist on value of type '{1}'.": { + "code": 2094, + "category": 1 /* Error */ + }, + "Could not find symbol '{0}'.": { + "code": 2095, + "category": 1 /* Error */ + }, + "'get' and 'set' accessor must have the same type.": { + "code": 2096, + "category": 1 /* Error */ + }, + "'this' cannot be referenced in current location.": { + "code": 2097, + "category": 1 /* Error */ + }, + "Static members cannot reference class type parameters.": { + "code": 2099, + "category": 1 /* Error */ + }, + "Class '{0}' is recursively referenced as a base type of itself.": { + "code": 2100, + "category": 1 /* Error */ + }, + "Interface '{0}' is recursively referenced as a base type of itself.": { + "code": 2101, + "category": 1 /* Error */ + }, + "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class.": { + "code": 2102, + "category": 1 /* Error */ + }, + "'super' cannot be referenced in non-derived classes.": { + "code": 2103, + "category": 1 /* Error */ + }, + "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.": { + "code": 2104, + "category": 1 /* Error */ + }, + "Constructors for derived classes must contain a 'super' call.": { + "code": 2105, + "category": 1 /* Error */ + }, + "Super calls are not permitted outside constructors or in nested functions inside constructors.": { + "code": 2106, + "category": 1 /* Error */ + }, + "'{0}.{1}' is inaccessible.": { + "code": 2107, + "category": 1 /* Error */ + }, + "'this' cannot be referenced within module bodies.": { + "code": 2108, + "category": 1 /* Error */ + }, + "Invalid '+' expression - types not known to support the addition operator.": { + "code": 2111, + "category": 1 /* Error */ + }, + "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.": { + "code": 2112, + "category": 1 /* Error */ + }, + "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.": { + "code": 2113, + "category": 1 /* Error */ + }, + "The type of a unary arithmetic operation operand must be of type 'any', 'number' or an enum type.": { + "code": 2114, + "category": 1 /* Error */ + }, + "Variable declarations of a 'for' statement cannot use a type annotation.": { + "code": 2115, + "category": 1 /* Error */ + }, + "Variable declarations of a 'for' statement must be of types 'string' or 'any'.": { + "code": 2116, + "category": 1 /* Error */ + }, + "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter.": { + "code": 2117, + "category": 1 /* Error */ + }, + "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'.": { + "code": 2118, + "category": 1 /* Error */ + }, + "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.": { + "code": 2119, + "category": 1 /* Error */ + }, + "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.": { + "code": 2120, + "category": 1 /* Error */ + }, + "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.": { + "code": 2121, + "category": 1 /* Error */ + }, + "Setters cannot return a value.": { + "code": 2122, + "category": 1 /* Error */ + }, + "Tried to query type of uninitialized module '{0}'.": { + "code": 2123, + "category": 1 /* Error */ + }, + "Tried to set variable type to uninitialized module type '{0}'.": { + "code": 2124, + "category": 1 /* Error */ + }, + "Type '{0}' does not have type parameters.": { + "code": 2125, + "category": 1 /* Error */ + }, + "Getters must return a value.": { + "code": 2126, + "category": 1 /* Error */ + }, + "Getter and setter accessors do not agree in visibility.": { + "code": 2127, + "category": 1 /* Error */ + }, + "Invalid left-hand side of assignment expression.": { + "code": 2130, + "category": 1 /* Error */ + }, + "Function declared a non-void return type, but has no return expression.": { + "code": 2131, + "category": 1 /* Error */ + }, + "Cannot resolve return type reference.": { + "code": 2132, + "category": 1 /* Error */ + }, + "Constructors cannot have a return type of 'void'.": { + "code": 2133, + "category": 1 /* Error */ + }, + "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'.": { + "code": 2134, + "category": 1 /* Error */ + }, + "All symbols within a with block will be resolved to 'any'.": { + "code": 2135, + "category": 1 /* Error */ + }, + "Import declarations in an internal module cannot reference an external module.": { + "code": 2136, + "category": 1 /* Error */ + }, + "Class {0} declares interface {1} but does not implement it:{NL}{2}": { + "code": 2137, + "category": 1 /* Error */ + }, + "Class {0} declares class {1} as an interface but does not implement it:{NL}{2}": { + "code": 2138, + "category": 1 /* Error */ + }, + "The operand of an increment or decrement operator must be a variable, property or indexer.": { + "code": 2139, + "category": 1 /* Error */ + }, + "'this' cannot be referenced in static initializers in a class body.": { + "code": 2140, + "category": 1 /* Error */ + }, + "Class '{0}' cannot extend class '{1}':{NL}{2}": { + "code": 2141, + "category": 1 /* Error */ + }, + "Interface '{0}' cannot extend class '{1}':{NL}{2}": { + "code": 2142, + "category": 1 /* Error */ + }, + "Interface '{0}' cannot extend interface '{1}':{NL}{2}": { + "code": 2143, + "category": 1 /* Error */ + }, + "Duplicate overload signature for '{0}'.": { + "code": 2144, + "category": 1 /* Error */ + }, + "Duplicate constructor overload signature.": { + "code": 2145, + "category": 1 /* Error */ + }, + "Duplicate overload call signature.": { + "code": 2146, + "category": 1 /* Error */ + }, + "Duplicate overload construct signature.": { + "code": 2147, + "category": 1 /* Error */ + }, + "Overload signature is not compatible with function definition.": { + "code": 2148, + "category": 1 /* Error */ + }, + "Overload signature is not compatible with function definition:{NL}{0}": { + "code": 2149, + "category": 1 /* Error */ + }, + "Overload signatures must all be public or private.": { + "code": 2150, + "category": 1 /* Error */ + }, + "Overload signatures must all be exported or not exported.": { + "code": 2151, + "category": 1 /* Error */ + }, + "Overload signatures must all be ambient or non-ambient.": { + "code": 2152, + "category": 1 /* Error */ + }, + "Overload signatures must all be optional or required.": { + "code": 2153, + "category": 1 /* Error */ + }, + "Specialized overload signature is not assignable to any non-specialized signature.": { + "code": 2154, + "category": 1 /* Error */ + }, + "'this' cannot be referenced in constructor arguments.": { + "code": 2155, + "category": 1 /* Error */ + }, + "Instance member cannot be accessed off a class.": { + "code": 2157, + "category": 1 /* Error */ + }, + "Untyped function calls may not accept type arguments.": { + "code": 2158, + "category": 1 /* Error */ + }, + "Non-generic functions may not accept type arguments.": { + "code": 2159, + "category": 1 /* Error */ + }, + "A generic type may not reference itself with a wrapped form of its own type parameters.": { + "code": 2160, + "category": 1 /* Error */ + }, + "Rest parameters must be array types.": { + "code": 2162, + "category": 1 /* Error */ + }, + "Overload signature implementation cannot use specialized type.": { + "code": 2163, + "category": 1 /* Error */ + }, + "Export assignments may only be used at the top-level of external modules.": { + "code": 2164, + "category": 1 /* Error */ + }, + "Export assignments may only be made with variables, functions, classes, interfaces, enums and internal modules.": { + "code": 2165, + "category": 1 /* Error */ + }, + "Only public methods of the base class are accessible via the 'super' keyword.": { + "code": 2166, + "category": 1 /* Error */ + }, + "Numeric indexer type '{0}' must be assignable to string indexer type '{1}'.": { + "code": 2167, + "category": 1 /* Error */ + }, + "Numeric indexer type '{0}' must be assignable to string indexer type '{1}':{NL}{2}": { + "code": 2168, + "category": 1 /* Error */ + }, + "All numerically named properties must be assignable to numeric indexer type '{0}'.": { + "code": 2169, + "category": 1 /* Error */ + }, + "All numerically named properties must be assignable to numeric indexer type '{0}':{NL}{1}": { + "code": 2170, + "category": 1 /* Error */ + }, + "All named properties must be assignable to string indexer type '{0}'.": { + "code": 2171, + "category": 1 /* Error */ + }, + "All named properties must be assignable to string indexer type '{0}':{NL}{1}": { + "code": 2172, + "category": 1 /* Error */ + }, + "Generic type references must include all type arguments.": { + "code": 2173, + "category": 1 /* Error */ + }, + "Default arguments are only allowed in implementation.": { + "code": 2174, + "category": 1 /* Error */ + }, + "Overloads cannot differ only by return type.": { + "code": 2175, + "category": 1 /* Error */ + }, + "Function expression declared a non-void return type, but has no return expression.": { + "code": 2176, + "category": 1 /* Error */ + }, + "Import declaration referencing identifier from internal module can only be made with variables, functions, classes, interfaces, enums and internal modules.": { + "code": 2177, + "category": 1 /* Error */ + }, + "Could not find symbol '{0}' in module '{1}'.": { + "code": 2178, + "category": 1 /* Error */ + }, + "Unable to resolve module reference '{0}'.": { + "code": 2179, + "category": 1 /* Error */ + }, + "Could not find module '{0}' in module '{1}'.": { + "code": 2180, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned value with type that has or is using private type '{1}'.": { + "code": 2181, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned value with type that is using inaccessible module '{1}'.": { + "code": 2182, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned type that has or is using private type '{1}'.": { + "code": 2183, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned type that is using inaccessible module '{1}'.": { + "code": 2184, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned container that is or is using inaccessible module '{1}'.": { + "code": 2185, + "category": 1 /* Error */ + }, + "Type name '{0}' in extends clause does not reference constructor function for '{1}'.": { + "code": 2186, + "category": 1 /* Error */ + }, + "Internal module reference '{0}' in import declaration does not reference module instance for '{1}'.": { + "code": 2187, + "category": 1 /* Error */ + }, + "Module '{0}' cannot merge with previous declaration of '{1}' in a different file '{2}'.": { + "code": 2188, + "category": 1 /* Error */ + }, + "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':{NL}{3}": { + "code": 2189, + "category": 1 /* Error */ + }, + "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it.": { + "code": 2190, + "category": 1 /* Error */ + }, + "Ambient external module declaration cannot be reopened.": { + "code": 2191, + "category": 1 /* Error */ + }, + "All declarations of merged declaration '{0}' must be exported or not exported.": { + "code": 2192, + "category": 1 /* Error */ + }, + "'super' cannot be referenced in constructor arguments.": { + "code": 2193, + "category": 1 /* Error */ + }, + "Return type of constructor signature must be assignable to the instance type of the class.": { + "code": 2194, + "category": 1 /* Error */ + }, + "Ambient external module declaration must be defined in global context.": { + "code": 2195, + "category": 1 /* Error */ + }, + "Ambient external module declaration cannot specify relative module name.": { + "code": 2196, + "category": 1 /* Error */ + }, + "Import declaration in an ambient external module declaration cannot reference external module through relative external module name.": { + "code": 2197, + "category": 1 /* Error */ + }, + "Could not find the best common type of types of all return statement expressions.": { + "code": 2198, + "category": 1 /* Error */ + }, + "Import declaration cannot refer to external module reference when --noResolve option is set.": { + "code": 2199, + "category": 1 /* Error */ + }, + "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference.": { + "code": 2200, + "category": 1 /* Error */ + }, + "'continue' statement can only be used within an enclosing iteration statement.": { + "code": 2201, + "category": 1 /* Error */ + }, + "'break' statement can only be used within an enclosing iteration or switch statement.": { + "code": 2202, + "category": 1 /* Error */ + }, + "Jump target not found.": { + "code": 2203, + "category": 1 /* Error */ + }, + "Jump target cannot cross function boundary.": { + "code": 2204, + "category": 1 /* Error */ + }, + "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference.": { + "code": 2205, + "category": 1 /* Error */ + }, + "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference.": { + "code": 2206, + "category": 1 /* Error */ + }, + "Expression resolves to '_super' that compiler uses to capture base class reference.": { + "code": 2207, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.": { + "code": 2208, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of call signature from exported interface has or is using private type '{1}'.": { + "code": 2209, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public static method from exported class has or is using private type '{1}'.": { + "code": 2210, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public method from exported class has or is using private type '{1}'.": { + "code": 2211, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of method from exported interface has or is using private type '{1}'.": { + "code": 2212, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported function has or is using private type '{1}'.": { + "code": 2213, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.": { + "code": 2214, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of call signature from exported interface is using inaccessible module {1}": { + "code": 2215, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public static method from exported class is using inaccessible module {1}.": { + "code": 2216, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public method from exported class is using inaccessible module {1}.": { + "code": 2217, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of method from exported interface is using inaccessible module {1}.": { + "code": 2218, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported function is using inaccessible module {1}.": { + "code": 2219, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported class has or is using private type '{1}'.": { + "code": 2220, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported interface has or is using private type '{1}'.": { + "code": 2221, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported class is using inaccessible module {1}.": { + "code": 2222, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported interface is using inaccessible module {1}.": { + "code": 2223, + "category": 1 /* Error */ + }, + "Duplicate identifier '_i'. Compiler uses '_i' to initialize rest parameter.": { + "code": 2224, + "category": 1 /* Error */ + }, + "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters.": { + "code": 2225, + "category": 1 /* Error */ + }, + "Type of conditional '{0}' must be identical to '{1}' or '{2}'.": { + "code": 2226, + "category": 1 /* Error */ + }, + "Type of conditional '{0}' must be identical to '{1}', '{2}' or '{3}'.": { + "code": 2227, + "category": 1 /* Error */ + }, + "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of an external module.": { + "code": 2228, + "category": 1 /* Error */ + }, + "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.": { + "code": 2229, + "category": 1 /* Error */ + }, + "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.": { + "code": 2230, + "category": 1 /* Error */ + }, + "Parameter '{0}' cannot be referenced in its initializer.": { + "code": 2231, + "category": 1 /* Error */ + }, + "Duplicate string index signature.": { + "code": 2232, + "category": 1 /* Error */ + }, + "Duplicate number index signature.": { + "code": 2233, + "category": 1 /* Error */ + }, + "All declarations of an interface must have identical type parameters.": { + "code": 2234, + "category": 1 /* Error */ + }, + "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter.": { + "code": 2235, + "category": 1 /* Error */ + }, + "Type '{0}' is missing property '{1}' from type '{2}'.": { + "code": 4000, + "category": 3 /* NoPrefix */ + }, + "Types of property '{0}' of types '{1}' and '{2}' are incompatible.": { + "code": 4001, + "category": 3 /* NoPrefix */ + }, + "Types of property '{0}' of types '{1}' and '{2}' are incompatible:{NL}{3}": { + "code": 4002, + "category": 3 /* NoPrefix */ + }, + "Property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.": { + "code": 4003, + "category": 3 /* NoPrefix */ + }, + "Property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.": { + "code": 4004, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' define property '{2}' as private.": { + "code": 4005, + "category": 3 /* NoPrefix */ + }, + "Call signatures of types '{0}' and '{1}' are incompatible.": { + "code": 4006, + "category": 3 /* NoPrefix */ + }, + "Call signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { + "code": 4007, + "category": 3 /* NoPrefix */ + }, + "Type '{0}' requires a call signature, but type '{1}' lacks one.": { + "code": 4008, + "category": 3 /* NoPrefix */ + }, + "Construct signatures of types '{0}' and '{1}' are incompatible.": { + "code": 4009, + "category": 3 /* NoPrefix */ + }, + "Construct signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { + "code": 4010, + "category": 3 /* NoPrefix */ + }, + "Type '{0}' requires a construct signature, but type '{1}' lacks one.": { + "code": 4011, + "category": 3 /* NoPrefix */ + }, + "Index signatures of types '{0}' and '{1}' are incompatible.": { + "code": 4012, + "category": 3 /* NoPrefix */ + }, + "Index signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { + "code": 4013, + "category": 3 /* NoPrefix */ + }, + "Call signature expects {0} or fewer parameters.": { + "code": 4014, + "category": 3 /* NoPrefix */ + }, + "Could not apply type '{0}' to argument {1} which is of type '{2}'.": { + "code": 4015, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function.": { + "code": 4016, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.": { + "code": 4017, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor.": { + "code": 4018, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.": { + "code": 4019, + "category": 3 /* NoPrefix */ + }, + "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible.": { + "code": 4020, + "category": 3 /* NoPrefix */ + }, + "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible:{NL}{3}": { + "code": 4021, + "category": 3 /* NoPrefix */ + }, + "Type reference cannot refer to container '{0}'.": { + "code": 4022, + "category": 1 /* Error */ + }, + "Type reference must refer to type.": { + "code": 4023, + "category": 1 /* Error */ + }, + "In enums with multiple declarations only one declaration can omit an initializer for the first enum element.": { + "code": 4024, + "category": 1 /* Error */ + }, + " (+ {0} overload(s))": { + "code": 4025, + "category": 2 /* Message */ + }, + "Variable declaration cannot have the same name as an import declaration.": { + "code": 4026, + "category": 1 /* Error */ + }, + "Signature expected {0} type arguments, got {1} instead.": { + "code": 4027, + "category": 1 /* Error */ + }, + "Property '{0}' defined as optional in type '{1}', but is required in type '{2}'.": { + "code": 4028, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference do not refer to same named type.": { + "code": 4029, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments.": { + "code": 4030, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments:{NL}{2}": { + "code": 4031, + "category": 3 /* NoPrefix */ + }, + "Named properties '{0}' of types '{1}' and '{2}' are not identical.": { + "code": 4032, + "category": 3 /* NoPrefix */ + }, + "Types of string indexer of types '{0}' and '{1}' are not identical.": { + "code": 4033, + "category": 3 /* NoPrefix */ + }, + "Types of number indexer of types '{0}' and '{1}' are not identical.": { + "code": 4034, + "category": 3 /* NoPrefix */ + }, + "Type of number indexer in type '{0}' is not assignable to string indexer type in type '{1}'.{NL}{2}": { + "code": 4035, + "category": 3 /* NoPrefix */ + }, + "Type of property '{0}' in type '{1}' is not assignable to string indexer type in type '{2}'.{NL}{3}": { + "code": 4036, + "category": 3 /* NoPrefix */ + }, + "Type of property '{0}' in type '{1}' is not assignable to number indexer type in type '{2}'.{NL}{3}": { + "code": 4037, + "category": 3 /* NoPrefix */ + }, + "Static property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.": { + "code": 4038, + "category": 3 /* NoPrefix */ + }, + "Static property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.": { + "code": 4039, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' define static property '{2}' as private.": { + "code": 4040, + "category": 3 /* NoPrefix */ + }, + "Current host does not support '{0}' option.": { + "code": 5001, + "category": 1 /* Error */ + }, + "ECMAScript target version '{0}' not supported. Specify a valid target version: '{1}' (default), or '{2}'": { + "code": 5002, + "category": 1 /* Error */ + }, + "Module code generation '{0}' not supported.": { + "code": 5003, + "category": 1 /* Error */ + }, + "Could not find file: '{0}'.": { + "code": 5004, + "category": 1 /* Error */ + }, + "A file cannot have a reference to itself.": { + "code": 5006, + "category": 1 /* Error */ + }, + "Cannot resolve referenced file: '{0}'.": { + "code": 5007, + "category": 1 /* Error */ + }, + "Cannot find the common subdirectory path for the input files.": { + "code": 5009, + "category": 1 /* Error */ + }, + "Emit Error: {0}.": { + "code": 5011, + "category": 1 /* Error */ + }, + "Cannot read file '{0}': {1}": { + "code": 5012, + "category": 1 /* Error */ + }, + "Unsupported file encoding.": { + "code": 5013, + "category": 3 /* NoPrefix */ + }, + "Locale must be of the form or -. For example '{0}' or '{1}'.": { + "code": 5014, + "category": 1 /* Error */ + }, + "Unsupported locale: '{0}'.": { + "code": 5015, + "category": 1 /* Error */ + }, + "Execution Failed.{NL}": { + "code": 5016, + "category": 1 /* Error */ + }, + "Invalid call to 'up'": { + "code": 5019, + "category": 1 /* Error */ + }, + "Invalid call to 'down'": { + "code": 5020, + "category": 1 /* Error */ + }, + "Base64 value '{0}' finished with a continuation bit.": { + "code": 5021, + "category": 1 /* Error */ + }, + "Unknown option '{0}'": { + "code": 5023, + "category": 1 /* Error */ + }, + "Expected {0} arguments to message, got {1} instead.": { + "code": 5024, + "category": 1 /* Error */ + }, + "Expected the message '{0}' to have {1} arguments, but it had {2}": { + "code": 5025, + "category": 1 /* Error */ + }, + "Could not delete file '{0}'": { + "code": 5034, + "category": 1 /* Error */ + }, + "Could not create directory '{0}'": { + "code": 5035, + "category": 1 /* Error */ + }, + "Error while executing file '{0}': ": { + "code": 5036, + "category": 1 /* Error */ + }, + "Cannot compile external modules unless the '--module' flag is provided.": { + "code": 5037, + "category": 1 /* Error */ + }, + "Option mapRoot cannot be specified without specifying sourcemap option.": { + "code": 5038, + "category": 1 /* Error */ + }, + "Option sourceRoot cannot be specified without specifying sourcemap option.": { + "code": 5039, + "category": 1 /* Error */ + }, + "Options mapRoot and sourceRoot cannot be specified without specifying sourcemap option.": { + "code": 5040, + "category": 1 /* Error */ + }, + "Option '{0}' specified without '{1}'": { + "code": 5041, + "category": 1 /* Error */ + }, + "'codepage' option not supported on current platform.": { + "code": 5042, + "category": 1 /* Error */ + }, + "Concatenate and emit output to single file.": { + "code": 6001, + "category": 2 /* Message */ + }, + "Generates corresponding {0} file.": { + "code": 6002, + "category": 2 /* Message */ + }, + "Specifies the location where debugger should locate map files instead of generated locations.": { + "code": 6003, + "category": 2 /* Message */ + }, + "Specifies the location where debugger should locate TypeScript files instead of source locations.": { + "code": 6004, + "category": 2 /* Message */ + }, + "Watch input files.": { + "code": 6005, + "category": 2 /* Message */ + }, + "Redirect output structure to the directory.": { + "code": 6006, + "category": 2 /* Message */ + }, + "Do not emit comments to output.": { + "code": 6009, + "category": 2 /* Message */ + }, + "Skip resolution and preprocessing.": { + "code": 6010, + "category": 2 /* Message */ + }, + "Specify ECMAScript target version: '{0}' (default), or '{1}'": { + "code": 6015, + "category": 2 /* Message */ + }, + "Specify module code generation: '{0}' or '{1}'": { + "code": 6016, + "category": 2 /* Message */ + }, + "Print this message.": { + "code": 6017, + "category": 2 /* Message */ + }, + "Print the compiler's version: {0}": { + "code": 6019, + "category": 2 /* Message */ + }, + "Allow use of deprecated '{0}' keyword when referencing an external module.": { + "code": 6021, + "category": 2 /* Message */ + }, + "Specify locale for errors and messages. For example '{0}' or '{1}'": { + "code": 6022, + "category": 2 /* Message */ + }, + "Syntax: {0}": { + "code": 6023, + "category": 2 /* Message */ + }, + "options": { + "code": 6024, + "category": 2 /* Message */ + }, + "file1": { + "code": 6025, + "category": 2 /* Message */ + }, + "Examples:": { + "code": 6026, + "category": 2 /* Message */ + }, + "Options:": { + "code": 6027, + "category": 2 /* Message */ + }, + "Insert command line options and files from a file.": { + "code": 6030, + "category": 2 /* Message */ + }, + "Version {0}": { + "code": 6029, + "category": 2 /* Message */ + }, + "Use the '{0}' flag to see options.": { + "code": 6031, + "category": 2 /* Message */ + }, + "{NL}Recompiling ({0}):": { + "code": 6032, + "category": 2 /* Message */ + }, + "STRING": { + "code": 6033, + "category": 2 /* Message */ + }, + "KIND": { + "code": 6034, + "category": 2 /* Message */ + }, + "file2": { + "code": 6035, + "category": 2 /* Message */ + }, + "VERSION": { + "code": 6036, + "category": 2 /* Message */ + }, + "LOCATION": { + "code": 6037, + "category": 2 /* Message */ + }, + "DIRECTORY": { + "code": 6038, + "category": 2 /* Message */ + }, + "NUMBER": { + "code": 6039, + "category": 2 /* Message */ + }, + "Specify the codepage to use when opening source files.": { + "code": 6040, + "category": 2 /* Message */ + }, + "Additional locations:": { + "code": 6041, + "category": 2 /* Message */ + }, + "This version of the Javascript runtime does not support the '{0}' function.": { + "code": 7000, + "category": 1 /* Error */ + }, + "Unknown rule.": { + "code": 7002, + "category": 1 /* Error */ + }, + "Invalid line number ({0})": { + "code": 7003, + "category": 1 /* Error */ + }, + "Warn on expressions and declarations with an implied 'any' type.": { + "code": 7004, + "category": 2 /* Message */ + }, + "Variable '{0}' implicitly has an 'any' type.": { + "code": 7005, + "category": 1 /* Error */ + }, + "Parameter '{0}' of '{1}' implicitly has an 'any' type.": { + "code": 7006, + "category": 1 /* Error */ + }, + "Parameter '{0}' of function type implicitly has an 'any' type.": { + "code": 7007, + "category": 1 /* Error */ + }, + "Member '{0}' of object type implicitly has an 'any' type.": { + "code": 7008, + "category": 1 /* Error */ + }, + "'new' expression, which lacks a constructor signature, implicitly has an 'any' type.": { + "code": 7009, + "category": 1 /* Error */ + }, + "'{0}', which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7010, + "category": 1 /* Error */ + }, + "Function expression, which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7011, + "category": 1 /* Error */ + }, + "Parameter '{0}' of lambda function implicitly has an 'any' type.": { + "code": 7012, + "category": 1 /* Error */ + }, + "Constructor signature, which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7013, + "category": 1 /* Error */ + }, + "Lambda Function, which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7014, + "category": 1 /* Error */ + }, + "Array Literal implicitly has an 'any' type from widening.": { + "code": 7015, + "category": 1 /* Error */ + }, + "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type.": { + "code": 7016, + "category": 1 /* Error */ + }, + "Index signature of object type implicitly has an 'any' type.": { + "code": 7017, + "category": 1 /* Error */ + }, + "Object literal's property '{0}' implicitly has an 'any' type from widening.": { + "code": 7018, + "category": 1 /* Error */ + } + }; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 0x2028] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 0x2029] = "paragraphSeparator"; + + CharacterCodes[CharacterCodes["nextLine"] = 0x0085] = "nextLine"; + + CharacterCodes[CharacterCodes["space"] = 0x0020] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 0x00A0] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 0x2000] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 0x2001] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 0x2002] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 0x2003] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 0x2004] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 0x2005] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 0x2006] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 0x2007] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 0x2008] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 0x2009] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 0x200A] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 0x200B] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 0x202F] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 0x3000] = "ideographicSpace"; + + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 0xFEFF] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(TypeScript.CharacterCodes || (TypeScript.CharacterCodes = {})); + var CharacterCodes = TypeScript.CharacterCodes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + + + (function (ScriptSnapshot) { + var StringScriptSnapshot = (function () { + function StringScriptSnapshot(text) { + this.text = text; + this._lineStartPositions = null; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + + StringScriptSnapshot.prototype.getLineStartPositions = function () { + if (!this._lineStartPositions) { + this._lineStartPositions = TypeScript.TextUtilities.parseLineStarts(this.text); + } + + return this._lineStartPositions; + }; + + StringScriptSnapshot.prototype.getTextChangeRangeSinceVersion = function (scriptVersion) { + throw TypeScript.Errors.notYetImplemented(); + }; + return StringScriptSnapshot; + })(); + + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(TypeScript.ScriptSnapshot || (TypeScript.ScriptSnapshot = {})); + var ScriptSnapshot = TypeScript.ScriptSnapshot; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (LineMap1) { + function fromSimpleText(text) { + return new TypeScript.LineMap(function () { + return TypeScript.TextUtilities.parseLineStarts({ charCodeAt: function (index) { + return text.charCodeAt(index); + }, length: text.length() }); + }, text.length()); + } + LineMap1.fromSimpleText = fromSimpleText; + + function fromScriptSnapshot(scriptSnapshot) { + return new TypeScript.LineMap(function () { + return scriptSnapshot.getLineStartPositions(); + }, scriptSnapshot.getLength()); + } + LineMap1.fromScriptSnapshot = fromScriptSnapshot; + + function fromString(text) { + return new TypeScript.LineMap(function () { + return TypeScript.TextUtilities.parseLineStarts(text); + }, text.length); + } + LineMap1.fromString = fromString; + })(TypeScript.LineMap1 || (TypeScript.LineMap1 = {})); + var LineMap1 = TypeScript.LineMap1; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TextFactory) { + function getStartAndLengthOfLineBreakEndingAt(text, index, info) { + var c = text.charCodeAt(index); + if (c === 10 /* lineFeed */) { + if (index > 0 && text.charCodeAt(index - 1) === 13 /* carriageReturn */) { + info.startPosition = index - 1; + info.length = 2; + } else { + info.startPosition = index; + info.length = 1; + } + } else if (TypeScript.TextUtilities.isAnyLineBreakCharacter(c)) { + info.startPosition = index; + info.length = 1; + } else { + info.startPosition = index + 1; + info.length = 0; + } + } + + var LinebreakInfo = (function () { + function LinebreakInfo(startPosition, length) { + this.startPosition = startPosition; + this.length = length; + } + return LinebreakInfo; + })(); + + var TextLine = (function () { + function TextLine(text, body, lineBreakLength, lineNumber) { + this._text = null; + this._textSpan = null; + if (text === null) { + throw TypeScript.Errors.argumentNull('text'); + } + TypeScript.Debug.assert(lineBreakLength >= 0); + TypeScript.Debug.assert(lineNumber >= 0); + this._text = text; + this._textSpan = body; + this._lineBreakLength = lineBreakLength; + this._lineNumber = lineNumber; + } + TextLine.prototype.start = function () { + return this._textSpan.start(); + }; + + TextLine.prototype.end = function () { + return this._textSpan.end(); + }; + + TextLine.prototype.endIncludingLineBreak = function () { + return this.end() + this._lineBreakLength; + }; + + TextLine.prototype.extent = function () { + return this._textSpan; + }; + + TextLine.prototype.extentIncludingLineBreak = function () { + return TypeScript.TextSpan.fromBounds(this.start(), this.endIncludingLineBreak()); + }; + + TextLine.prototype.toString = function () { + return this._text.toString(this._textSpan); + }; + + TextLine.prototype.lineNumber = function () { + return this._lineNumber; + }; + return TextLine; + })(); + + var TextBase = (function () { + function TextBase() { + this.linebreakInfo = new LinebreakInfo(0, 0); + this.lastLineFoundForPosition = null; + } + TextBase.prototype.length = function () { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.charCodeAt = function (position) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.checkSubSpan = function (span) { + if (span.start() < 0 || span.start() > this.length() || span.end() > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("span"); + } + }; + + TextBase.prototype.toString = function (span) { + if (typeof span === "undefined") { span = null; } + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SubText(this, span); + }; + + TextBase.prototype.substr = function (start, length, intern) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.lineCount = function () { + return this._lineStarts().length; + }; + + TextBase.prototype.lines = function () { + var lines = []; + + var length = this.lineCount(); + for (var i = 0; i < length; ++i) { + lines[i] = this.getLineFromLineNumber(i); + } + + return lines; + }; + + TextBase.prototype.lineMap = function () { + var _this = this; + return new TypeScript.LineMap(function () { + return _this._lineStarts(); + }, this.length()); + }; + + TextBase.prototype._lineStarts = function () { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.getLineFromLineNumber = function (lineNumber) { + var lineStarts = this._lineStarts(); + + if (lineNumber < 0 || lineNumber >= lineStarts.length) { + throw TypeScript.Errors.argumentOutOfRange("lineNumber"); + } + + var first = lineStarts[lineNumber]; + if (lineNumber === lineStarts.length - 1) { + return new TextLine(this, new TypeScript.TextSpan(first, this.length() - first), 0, lineNumber); + } else { + getStartAndLengthOfLineBreakEndingAt(this, lineStarts[lineNumber + 1] - 1, this.linebreakInfo); + return new TextLine(this, new TypeScript.TextSpan(first, this.linebreakInfo.startPosition - first), this.linebreakInfo.length, lineNumber); + } + }; + + TextBase.prototype.getLineFromPosition = function (position) { + var lastFound = this.lastLineFoundForPosition; + if (lastFound !== null && lastFound.start() <= position && lastFound.endIncludingLineBreak() > position) { + return lastFound; + } + + var lineNumber = this.getLineNumberFromPosition(position); + + var result = this.getLineFromLineNumber(lineNumber); + this.lastLineFoundForPosition = result; + return result; + }; + + TextBase.prototype.getLineNumberFromPosition = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + if (position === this.length()) { + return this.lineCount() - 1; + } + + var lineNumber = TypeScript.ArrayUtilities.binarySearch(this._lineStarts(), position); + if (lineNumber < 0) { + lineNumber = (~lineNumber) - 1; + } + + return lineNumber; + }; + + TextBase.prototype.getLinePosition = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + + return new TypeScript.LineAndCharacter(lineNumber, position - this._lineStarts()[lineNumber]); + }; + return TextBase; + })(); + + var SubText = (function (_super) { + __extends(SubText, _super); + function SubText(text, span) { + _super.call(this); + this._lazyLineStarts = null; + + if (text === null) { + throw TypeScript.Errors.argumentNull("text"); + } + + if (span.start() < 0 || span.start() >= text.length() || span.end() < 0 || span.end() > text.length()) { + throw TypeScript.Errors.argument("span"); + } + + this.text = text; + this.span = span; + } + SubText.prototype.length = function () { + return this.span.length(); + }; + + SubText.prototype.charCodeAt = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + return this.text.charCodeAt(this.span.start() + position); + }; + + SubText.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SubText(this.text, this.getCompositeSpan(span.start(), span.length())); + }; + + SubText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var span = this.getCompositeSpan(sourceIndex, count); + this.text.copyTo(span.start(), destination, destinationIndex, span.length()); + }; + + SubText.prototype.substr = function (start, length, intern) { + var startInOriginalText = this.span.start() + start; + return this.text.substr(startInOriginalText, length, intern); + }; + + SubText.prototype.getCompositeSpan = function (start, length) { + var compositeStart = TypeScript.MathPrototype.min(this.text.length(), this.span.start() + start); + var compositeEnd = TypeScript.MathPrototype.min(this.text.length(), compositeStart + length); + return new TypeScript.TextSpan(compositeStart, compositeEnd - compositeStart); + }; + + SubText.prototype._lineStarts = function () { + var _this = this; + if (!this._lazyLineStarts) { + this._lazyLineStarts = TypeScript.TextUtilities.parseLineStarts({ charCodeAt: function (index) { + return _this.charCodeAt(index); + }, length: this.length() }); + } + + return this._lazyLineStarts; + }; + return SubText; + })(TextBase); + + var StringText = (function (_super) { + __extends(StringText, _super); + function StringText(data) { + _super.call(this); + this.source = null; + this._lazyLineStarts = null; + + if (data === null) { + throw TypeScript.Errors.argumentNull("data"); + } + + this.source = data; + } + StringText.prototype.length = function () { + return this.source.length; + }; + + StringText.prototype.charCodeAt = function (position) { + if (position < 0 || position >= this.source.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + return this.source.charCodeAt(position); + }; + + StringText.prototype.substr = function (start, length, intern) { + return this.source.substr(start, length); + }; + + StringText.prototype.toString = function (span) { + if (typeof span === "undefined") { span = null; } + if (span === null) { + span = new TypeScript.TextSpan(0, this.length()); + } + + this.checkSubSpan(span); + + if (span.start() === 0 && span.length() === this.length()) { + return this.source; + } + + return this.source.substr(span.start(), span.length()); + }; + + StringText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + TypeScript.StringUtilities.copyTo(this.source, sourceIndex, destination, destinationIndex, count); + }; + + StringText.prototype._lineStarts = function () { + if (this._lazyLineStarts === null) { + this._lazyLineStarts = TypeScript.TextUtilities.parseLineStarts(this.source); + } + + return this._lazyLineStarts; + }; + return StringText; + })(TextBase); + + function createText(value) { + return new StringText(value); + } + TextFactory.createText = createText; + })(TypeScript.TextFactory || (TypeScript.TextFactory = {})); + var TextFactory = TypeScript.TextFactory; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (SimpleText) { + var SimpleSubText = (function () { + function SimpleSubText(text, span) { + this.text = null; + this.span = null; + if (text === null) { + throw TypeScript.Errors.argumentNull("text"); + } + + if (span.start() < 0 || span.start() >= text.length() || span.end() < 0 || span.end() > text.length()) { + throw TypeScript.Errors.argument("span"); + } + + this.text = text; + this.span = span; + } + SimpleSubText.prototype.checkSubSpan = function (span) { + if (span.start() < 0 || span.start() > this.length() || span.end() > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("span"); + } + }; + + SimpleSubText.prototype.checkSubPosition = function (position) { + if (position < 0 || position >= this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + }; + + SimpleSubText.prototype.length = function () { + return this.span.length(); + }; + + SimpleSubText.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SimpleSubText(this.text, this.getCompositeSpan(span.start(), span.length())); + }; + + SimpleSubText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var span = this.getCompositeSpan(sourceIndex, count); + this.text.copyTo(span.start(), destination, destinationIndex, span.length()); + }; + + SimpleSubText.prototype.substr = function (start, length, intern) { + var span = this.getCompositeSpan(start, length); + return this.text.substr(span.start(), span.length(), intern); + }; + + SimpleSubText.prototype.getCompositeSpan = function (start, length) { + var compositeStart = TypeScript.MathPrototype.min(this.text.length(), this.span.start() + start); + var compositeEnd = TypeScript.MathPrototype.min(this.text.length(), compositeStart + length); + return new TypeScript.TextSpan(compositeStart, compositeEnd - compositeStart); + }; + + SimpleSubText.prototype.charCodeAt = function (index) { + this.checkSubPosition(index); + return this.text.charCodeAt(this.span.start() + index); + }; + + SimpleSubText.prototype.lineMap = function () { + return TypeScript.LineMap1.fromSimpleText(this); + }; + return SimpleSubText; + })(); + + var SimpleStringText = (function () { + function SimpleStringText(value) { + this.value = value; + this._lineMap = null; + } + SimpleStringText.prototype.length = function () { + return this.value.length; + }; + + SimpleStringText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + TypeScript.StringUtilities.copyTo(this.value, sourceIndex, destination, destinationIndex, count); + }; + + SimpleStringText.prototype.substr = function (start, length, intern) { + if (intern) { + var array = length <= SimpleStringText.charArray.length ? SimpleStringText.charArray : TypeScript.ArrayUtilities.createArray(length, 0); + this.copyTo(start, array, 0, length); + return TypeScript.Collections.DefaultStringTable.addCharArray(array, 0, length); + } + + return this.value.substr(start, length); + }; + + SimpleStringText.prototype.subText = function (span) { + return new SimpleSubText(this, span); + }; + + SimpleStringText.prototype.charCodeAt = function (index) { + return this.value.charCodeAt(index); + }; + + SimpleStringText.prototype.lineMap = function () { + if (!this._lineMap) { + this._lineMap = TypeScript.LineMap1.fromString(this.value); + } + + return this._lineMap; + }; + SimpleStringText.charArray = TypeScript.ArrayUtilities.createArray(1024, 0); + return SimpleStringText; + })(); + + var SimpleScriptSnapshotText = (function () { + function SimpleScriptSnapshotText(scriptSnapshot) { + this.scriptSnapshot = scriptSnapshot; + } + SimpleScriptSnapshotText.prototype.charCodeAt = function (index) { + return this.scriptSnapshot.getText(index, index + 1).charCodeAt(0); + }; + + SimpleScriptSnapshotText.prototype.length = function () { + return this.scriptSnapshot.getLength(); + }; + + SimpleScriptSnapshotText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var text = this.scriptSnapshot.getText(sourceIndex, sourceIndex + count); + TypeScript.StringUtilities.copyTo(text, 0, destination, destinationIndex, count); + }; + + SimpleScriptSnapshotText.prototype.substr = function (start, length, intern) { + return this.scriptSnapshot.getText(start, start + length); + }; + + SimpleScriptSnapshotText.prototype.subText = function (span) { + return new SimpleSubText(this, span); + }; + + SimpleScriptSnapshotText.prototype.lineMap = function () { + var _this = this; + return new TypeScript.LineMap(function () { + return _this.scriptSnapshot.getLineStartPositions(); + }, this.length()); + }; + return SimpleScriptSnapshotText; + })(); + + function fromString(value) { + return new SimpleStringText(value); + } + SimpleText.fromString = fromString; + + function fromScriptSnapshot(scriptSnapshot) { + return new SimpleScriptSnapshotText(scriptSnapshot); + } + SimpleText.fromScriptSnapshot = fromScriptSnapshot; + })(TypeScript.SimpleText || (TypeScript.SimpleText = {})); + var SimpleText = TypeScript.SimpleText; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TextUtilities) { + function parseLineStarts(text) { + var length = text.length; + + if (0 === length) { + var result = new Array(); + result.push(0); + return result; + } + + var position = 0; + var index = 0; + var arrayBuilder = new Array(); + var lineNumber = 0; + + while (index < length) { + var c = text.charCodeAt(index); + var lineBreakLength; + + if (c > 13 /* carriageReturn */ && c <= 127) { + index++; + continue; + } else if (c === 13 /* carriageReturn */ && index + 1 < length && text.charCodeAt(index + 1) === 10 /* lineFeed */) { + lineBreakLength = 2; + } else if (c === 10 /* lineFeed */) { + lineBreakLength = 1; + } else { + lineBreakLength = TextUtilities.getLengthOfLineBreak(text, index); + } + + if (0 === lineBreakLength) { + index++; + } else { + arrayBuilder.push(position); + index += lineBreakLength; + position = index; + lineNumber++; + } + } + + arrayBuilder.push(position); + + return arrayBuilder; + } + TextUtilities.parseLineStarts = parseLineStarts; + + function getLengthOfLineBreakSlow(text, index, c) { + if (c === 13 /* carriageReturn */) { + var next = index + 1; + return (next < text.length) && 10 /* lineFeed */ === text.charCodeAt(next) ? 2 : 1; + } else if (isAnyLineBreakCharacter(c)) { + return 1; + } else { + return 0; + } + } + TextUtilities.getLengthOfLineBreakSlow = getLengthOfLineBreakSlow; + + function getLengthOfLineBreak(text, index) { + var c = text.charCodeAt(index); + + if (c > 13 /* carriageReturn */ && c <= 127) { + return 0; + } + + return getLengthOfLineBreakSlow(text, index, c); + } + TextUtilities.getLengthOfLineBreak = getLengthOfLineBreak; + + function isAnyLineBreakCharacter(c) { + return c === 10 /* lineFeed */ || c === 13 /* carriageReturn */ || c === 133 /* nextLine */ || c === 8232 /* lineSeparator */ || c === 8233 /* paragraphSeparator */; + } + TextUtilities.isAnyLineBreakCharacter = isAnyLineBreakCharacter; + })(TypeScript.TextUtilities || (TypeScript.TextUtilities = {})); + var TextUtilities = TypeScript.TextUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextSpan = (function () { + function TextSpan(start, length) { + if (start < 0) { + TypeScript.Errors.argument("start"); + } + + if (length < 0) { + TypeScript.Errors.argument("length"); + } + + this._start = start; + this._length = length; + } + TextSpan.prototype.start = function () { + return this._start; + }; + + TextSpan.prototype.length = function () { + return this._length; + }; + + TextSpan.prototype.end = function () { + return this._start + this._length; + }; + + TextSpan.prototype.isEmpty = function () { + return this._length === 0; + }; + + TextSpan.prototype.containsPosition = function (position) { + return position >= this._start && position < this.end(); + }; + + TextSpan.prototype.containsTextSpan = function (span) { + return span._start >= this._start && span.end() <= this.end(); + }; + + TextSpan.prototype.overlapsWith = function (span) { + var overlapStart = TypeScript.MathPrototype.max(this._start, span._start); + var overlapEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + return overlapStart < overlapEnd; + }; + + TextSpan.prototype.overlap = function (span) { + var overlapStart = TypeScript.MathPrototype.max(this._start, span._start); + var overlapEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + if (overlapStart < overlapEnd) { + return TextSpan.fromBounds(overlapStart, overlapEnd); + } + + return null; + }; + + TextSpan.prototype.intersectsWithTextSpan = function (span) { + return span._start <= this.end() && span.end() >= this._start; + }; + + TextSpan.prototype.intersectsWith = function (start, length) { + var end = start + length; + return start <= this.end() && end >= this._start; + }; + + TextSpan.prototype.intersectsWithPosition = function (position) { + return position <= this.end() && position >= this._start; + }; + + TextSpan.prototype.intersection = function (span) { + var intersectStart = TypeScript.MathPrototype.max(this._start, span._start); + var intersectEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + if (intersectStart <= intersectEnd) { + return TextSpan.fromBounds(intersectStart, intersectEnd); + } + + return null; + }; + + TextSpan.fromBounds = function (start, end) { + TypeScript.Debug.assert(start >= 0); + TypeScript.Debug.assert(end - start >= 0); + return new TextSpan(start, end - start); + }; + return TextSpan; + })(); + TypeScript.TextSpan = TextSpan; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextChangeRange = (function () { + function TextChangeRange(span, newLength) { + if (newLength < 0) { + throw TypeScript.Errors.argumentOutOfRange("newLength"); + } + + this._span = span; + this._newLength = newLength; + } + TextChangeRange.prototype.span = function () { + return this._span; + }; + + TextChangeRange.prototype.newLength = function () { + return this._newLength; + }; + + TextChangeRange.prototype.newSpan = function () { + return new TypeScript.TextSpan(this.span().start(), this.newLength()); + }; + + TextChangeRange.prototype.isUnchanged = function () { + return this.span().isEmpty() && this.newLength() === 0; + }; + + TextChangeRange.collapseChangesFromSingleVersion = function (changes) { + var diff = 0; + var start = 1073741823 /* Max31BitInteger */; + var end = 0; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + diff += change.newLength() - change.span().length(); + + if (change.span().start() < start) { + start = change.span().start(); + } + + if (change.span().end() > end) { + end = change.span().end(); + } + } + + if (start > end) { + return null; + } + + var combined = TypeScript.TextSpan.fromBounds(start, end); + var newLen = combined.length() + diff; + + return new TextChangeRange(combined, newLen); + }; + + TextChangeRange.collapseChangesAcrossMultipleVersions = function (changes) { + if (changes.length === 0) { + return TextChangeRange.unchanged; + } + + if (changes.length === 1) { + return changes[0]; + } + + var change0 = changes[0]; + + var oldStartN = change0.span().start(); + var oldEndN = change0.span().end(); + var newEndN = oldStartN + change0.newLength(); + + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + + var oldStart2 = nextChange.span().start(); + var oldEnd2 = nextChange.span().end(); + var newEnd2 = oldStart2 + nextChange.newLength(); + + oldStartN = TypeScript.MathPrototype.min(oldStart1, oldStart2); + oldEndN = TypeScript.MathPrototype.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = TypeScript.MathPrototype.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + + return new TextChangeRange(TypeScript.TextSpan.fromBounds(oldStartN, oldEndN), newEndN - oldStartN); + }; + TextChangeRange.unchanged = new TextChangeRange(new TypeScript.TextSpan(0, 0), 0); + return TextChangeRange; + })(); + TypeScript.TextChangeRange = TextChangeRange; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CharacterInfo = (function () { + function CharacterInfo() { + } + CharacterInfo.isDecimalDigit = function (c) { + return c >= 48 /* _0 */ && c <= 57 /* _9 */; + }; + CharacterInfo.isOctalDigit = function (c) { + return c >= 48 /* _0 */ && c <= 55 /* _7 */; + }; + + CharacterInfo.isHexDigit = function (c) { + return CharacterInfo.isDecimalDigit(c) || (c >= 65 /* A */ && c <= 70 /* F */) || (c >= 97 /* a */ && c <= 102 /* f */); + }; + + CharacterInfo.hexValue = function (c) { + return CharacterInfo.isDecimalDigit(c) ? (c - 48 /* _0 */) : (c >= 65 /* A */ && c <= 70 /* F */) ? c - 65 /* A */ + 10 : c - 97 /* a */ + 10; + }; + + CharacterInfo.isWhitespace = function (ch) { + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + return true; + } + + return false; + }; + + CharacterInfo.isLineTerminator = function (ch) { + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + return true; + } + + return false; + }; + return CharacterInfo; + })(); + TypeScript.CharacterInfo = CharacterInfo; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxConstants) { + SyntaxConstants[SyntaxConstants["TriviaNewLineMask"] = 0x00000001] = "TriviaNewLineMask"; + SyntaxConstants[SyntaxConstants["TriviaCommentMask"] = 0x00000002] = "TriviaCommentMask"; + SyntaxConstants[SyntaxConstants["TriviaFullWidthShift"] = 2] = "TriviaFullWidthShift"; + + SyntaxConstants[SyntaxConstants["NodeDataComputed"] = 0x00000001] = "NodeDataComputed"; + SyntaxConstants[SyntaxConstants["NodeIncrementallyUnusableMask"] = 0x00000002] = "NodeIncrementallyUnusableMask"; + SyntaxConstants[SyntaxConstants["NodeParsedInStrictModeMask"] = 0x00000004] = "NodeParsedInStrictModeMask"; + SyntaxConstants[SyntaxConstants["NodeFullWidthShift"] = 3] = "NodeFullWidthShift"; + + SyntaxConstants[SyntaxConstants["IsVariableWidthKeyword"] = 1 << 31] = "IsVariableWidthKeyword"; + })(TypeScript.SyntaxConstants || (TypeScript.SyntaxConstants = {})); + var SyntaxConstants = TypeScript.SyntaxConstants; +})(TypeScript || (TypeScript = {})); +var FormattingOptions = (function () { + function FormattingOptions(useTabs, spacesPerTab, indentSpaces, newLineCharacter) { + this.useTabs = useTabs; + this.spacesPerTab = spacesPerTab; + this.indentSpaces = indentSpaces; + this.newLineCharacter = newLineCharacter; + } + FormattingOptions.defaultOptions = new FormattingOptions(false, 4, 4, "\r\n"); + return FormattingOptions; +})(); +var TypeScript; +(function (TypeScript) { + (function (Indentation) { + function columnForEndOfToken(token, syntaxInformationMap, options) { + return columnForStartOfToken(token, syntaxInformationMap, options) + token.width(); + } + Indentation.columnForEndOfToken = columnForEndOfToken; + + function columnForStartOfToken(token, syntaxInformationMap, options) { + var firstTokenInLine = syntaxInformationMap.firstTokenInLineContainingToken(token); + var leadingTextInReverse = []; + + var current = token; + while (current !== firstTokenInLine) { + current = syntaxInformationMap.previousToken(current); + + if (current === firstTokenInLine) { + leadingTextInReverse.push(current.trailingTrivia().fullText()); + leadingTextInReverse.push(current.text()); + } else { + leadingTextInReverse.push(current.fullText()); + } + } + + collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse); + + return columnForLeadingTextInReverse(leadingTextInReverse, options); + } + Indentation.columnForStartOfToken = columnForStartOfToken; + + function columnForStartOfFirstTokenInLineContainingToken(token, syntaxInformationMap, options) { + var firstTokenInLine = syntaxInformationMap.firstTokenInLineContainingToken(token); + var leadingTextInReverse = []; + + collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse); + + return columnForLeadingTextInReverse(leadingTextInReverse, options); + } + Indentation.columnForStartOfFirstTokenInLineContainingToken = columnForStartOfFirstTokenInLineContainingToken; + + function collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse) { + var leadingTrivia = firstTokenInLine.leadingTrivia(); + + for (var i = leadingTrivia.count() - 1; i >= 0; i--) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.kind() === 5 /* NewLineTrivia */) { + break; + } + + if (trivia.kind() === 6 /* MultiLineCommentTrivia */) { + var lineSegments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + leadingTextInReverse.push(TypeScript.ArrayUtilities.last(lineSegments)); + + if (lineSegments.length > 0) { + break; + } + } + + leadingTextInReverse.push(trivia.fullText()); + } + } + + function columnForLeadingTextInReverse(leadingTextInReverse, options) { + var column = 0; + + for (var i = leadingTextInReverse.length - 1; i >= 0; i--) { + var text = leadingTextInReverse[i]; + column = columnForPositionInStringWorker(text, text.length, column, options); + } + + return column; + } + + function columnForPositionInString(input, position, options) { + return columnForPositionInStringWorker(input, position, 0, options); + } + Indentation.columnForPositionInString = columnForPositionInString; + + function columnForPositionInStringWorker(input, position, startColumn, options) { + var column = startColumn; + var spacesPerTab = options.spacesPerTab; + + for (var j = 0; j < position; j++) { + var ch = input.charCodeAt(j); + + if (ch === 9 /* tab */) { + column += spacesPerTab - column % spacesPerTab; + } else { + column++; + } + } + + return column; + } + + function indentationString(column, options) { + var numberOfTabs = 0; + var numberOfSpaces = TypeScript.MathPrototype.max(0, column); + + if (options.useTabs) { + numberOfTabs = Math.floor(column / options.spacesPerTab); + numberOfSpaces -= numberOfTabs * options.spacesPerTab; + } + + return TypeScript.StringUtilities.repeat('\t', numberOfTabs) + TypeScript.StringUtilities.repeat(' ', numberOfSpaces); + } + Indentation.indentationString = indentationString; + + function indentationTrivia(column, options) { + return TypeScript.Syntax.whitespace(this.indentationString(column, options)); + } + Indentation.indentationTrivia = indentationTrivia; + + function firstNonWhitespacePosition(value) { + for (var i = 0; i < value.length; i++) { + var ch = value.charCodeAt(i); + if (!TypeScript.CharacterInfo.isWhitespace(ch)) { + return i; + } + } + + return value.length; + } + Indentation.firstNonWhitespacePosition = firstNonWhitespacePosition; + })(TypeScript.Indentation || (TypeScript.Indentation = {})); + var Indentation = TypeScript.Indentation; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (LanguageVersion) { + LanguageVersion[LanguageVersion["EcmaScript3"] = 0] = "EcmaScript3"; + LanguageVersion[LanguageVersion["EcmaScript5"] = 1] = "EcmaScript5"; + })(TypeScript.LanguageVersion || (TypeScript.LanguageVersion = {})); + var LanguageVersion = TypeScript.LanguageVersion; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ParseOptions = (function () { + function ParseOptions(languageVersion, allowAutomaticSemicolonInsertion) { + this._languageVersion = languageVersion; + this._allowAutomaticSemicolonInsertion = allowAutomaticSemicolonInsertion; + } + ParseOptions.prototype.toJSON = function (key) { + return { allowAutomaticSemicolonInsertion: this._allowAutomaticSemicolonInsertion }; + }; + + ParseOptions.prototype.languageVersion = function () { + return this._languageVersion; + }; + + ParseOptions.prototype.allowAutomaticSemicolonInsertion = function () { + return this._allowAutomaticSemicolonInsertion; + }; + return ParseOptions; + })(); + TypeScript.ParseOptions = ParseOptions; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PositionedElement = (function () { + function PositionedElement(parent, element, fullStart) { + this._parent = parent; + this._element = element; + this._fullStart = fullStart; + } + PositionedElement.create = function (parent, element, fullStart) { + if (element === null) { + return null; + } + + if (element.isNode()) { + return new PositionedNode(parent, element, fullStart); + } else if (element.isToken()) { + return new PositionedToken(parent, element, fullStart); + } else if (element.isList()) { + return new PositionedList(parent, element, fullStart); + } else if (element.isSeparatedList()) { + return new PositionedSeparatedList(parent, element, fullStart); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + PositionedElement.prototype.parent = function () { + return this._parent; + }; + + PositionedElement.prototype.parentElement = function () { + return this._parent && this._parent._element; + }; + + PositionedElement.prototype.element = function () { + return this._element; + }; + + PositionedElement.prototype.kind = function () { + return this.element().kind(); + }; + + PositionedElement.prototype.childIndex = function (child) { + return TypeScript.Syntax.childIndex(this.element(), child); + }; + + PositionedElement.prototype.childCount = function () { + return this.element().childCount(); + }; + + PositionedElement.prototype.childAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + return PositionedElement.create(this, this.element().childAt(index), this.fullStart() + offset); + }; + + PositionedElement.prototype.childStart = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return this.fullStart() + offset + child.leadingTriviaWidth(); + }; + + PositionedElement.prototype.childEnd = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return this.fullStart() + offset + child.leadingTriviaWidth() + child.width(); + }; + + PositionedElement.prototype.childStartAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + var child = this.element().childAt(index); + return this.fullStart() + offset + child.leadingTriviaWidth(); + }; + + PositionedElement.prototype.childEndAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + var child = this.element().childAt(index); + return this.fullStart() + offset + child.leadingTriviaWidth() + child.width(); + }; + + PositionedElement.prototype.getPositionedChild = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return PositionedElement.create(this, child, this.fullStart() + offset); + }; + + PositionedElement.prototype.fullStart = function () { + return this._fullStart; + }; + + PositionedElement.prototype.fullEnd = function () { + return this.fullStart() + this.element().fullWidth(); + }; + + PositionedElement.prototype.fullWidth = function () { + return this.element().fullWidth(); + }; + + PositionedElement.prototype.start = function () { + return this.fullStart() + this.element().leadingTriviaWidth(); + }; + + PositionedElement.prototype.end = function () { + return this.fullStart() + this.element().leadingTriviaWidth() + this.element().width(); + }; + + PositionedElement.prototype.root = function () { + var current = this; + while (current.parent() !== null) { + current = current.parent(); + } + + return current; + }; + + PositionedElement.prototype.containingNode = function () { + var current = this.parent(); + + while (current !== null && !current.element().isNode()) { + current = current.parent(); + } + + return current; + }; + return PositionedElement; + })(); + TypeScript.PositionedElement = PositionedElement; + + var PositionedNodeOrToken = (function (_super) { + __extends(PositionedNodeOrToken, _super); + function PositionedNodeOrToken(parent, nodeOrToken, fullStart) { + _super.call(this, parent, nodeOrToken, fullStart); + } + PositionedNodeOrToken.prototype.nodeOrToken = function () { + return this.element(); + }; + return PositionedNodeOrToken; + })(PositionedElement); + TypeScript.PositionedNodeOrToken = PositionedNodeOrToken; + + var PositionedNode = (function (_super) { + __extends(PositionedNode, _super); + function PositionedNode(parent, node, fullStart) { + _super.call(this, parent, node, fullStart); + } + PositionedNode.prototype.node = function () { + return this.element(); + }; + return PositionedNode; + })(PositionedNodeOrToken); + TypeScript.PositionedNode = PositionedNode; + + var PositionedToken = (function (_super) { + __extends(PositionedToken, _super); + function PositionedToken(parent, token, fullStart) { + _super.call(this, parent, token, fullStart); + } + PositionedToken.prototype.token = function () { + return this.element(); + }; + + PositionedToken.prototype.previousToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var triviaList = this.token().leadingTrivia(); + if (includeSkippedTokens && triviaList && triviaList.hasSkippedToken()) { + var currentTriviaEndPosition = this.start(); + for (var i = triviaList.count() - 1; i >= 0; i--) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isSkippedToken()) { + return new PositionedSkippedToken(this, trivia.skippedToken(), currentTriviaEndPosition - trivia.fullWidth()); + } + + currentTriviaEndPosition -= trivia.fullWidth(); + } + } + + var start = this.fullStart(); + if (start === 0) { + return null; + } + + return this.root().node().findToken(start - 1, includeSkippedTokens); + }; + + PositionedToken.prototype.nextToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + if (this.token().tokenKind === 10 /* EndOfFileToken */) { + return null; + } + + var triviaList = this.token().trailingTrivia(); + if (includeSkippedTokens && triviaList && triviaList.hasSkippedToken()) { + var fullStart = this.end(); + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isSkippedToken()) { + return new PositionedSkippedToken(this, trivia.skippedToken(), fullStart); + } + + fullStart += trivia.fullWidth(); + } + } + + return this.root().node().findToken(this.fullEnd(), includeSkippedTokens); + }; + return PositionedToken; + })(PositionedNodeOrToken); + TypeScript.PositionedToken = PositionedToken; + + var PositionedList = (function (_super) { + __extends(PositionedList, _super); + function PositionedList(parent, list, fullStart) { + _super.call(this, parent, list, fullStart); + } + PositionedList.prototype.list = function () { + return this.element(); + }; + return PositionedList; + })(PositionedElement); + TypeScript.PositionedList = PositionedList; + + var PositionedSeparatedList = (function (_super) { + __extends(PositionedSeparatedList, _super); + function PositionedSeparatedList(parent, list, fullStart) { + _super.call(this, parent, list, fullStart); + } + PositionedSeparatedList.prototype.list = function () { + return this.element(); + }; + return PositionedSeparatedList; + })(PositionedElement); + TypeScript.PositionedSeparatedList = PositionedSeparatedList; + + var PositionedSkippedToken = (function (_super) { + __extends(PositionedSkippedToken, _super); + function PositionedSkippedToken(parentToken, token, fullStart) { + _super.call(this, parentToken.parent(), token, fullStart); + this._parentToken = parentToken; + } + PositionedSkippedToken.prototype.parentToken = function () { + return this._parentToken; + }; + + PositionedSkippedToken.prototype.previousToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var start = this.fullStart(); + + if (includeSkippedTokens) { + var previousToken; + + if (start >= this.parentToken().end()) { + previousToken = TypeScript.Syntax.findSkippedTokenInTrailingTriviaList(this.parentToken(), start - 1); + + if (previousToken) { + return previousToken; + } + + return this.parentToken(); + } else { + previousToken = TypeScript.Syntax.findSkippedTokenInLeadingTriviaList(this.parentToken(), start - 1); + + if (previousToken) { + return previousToken; + } + } + } + + var start = this.parentToken().fullStart(); + if (start === 0) { + return null; + } + + return this.root().node().findToken(start - 1, includeSkippedTokens); + }; + + PositionedSkippedToken.prototype.nextToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + if (this.token().tokenKind === 10 /* EndOfFileToken */) { + return null; + } + + if (includeSkippedTokens) { + var end = this.end(); + var nextToken; + + if (end <= this.parentToken().start()) { + nextToken = TypeScript.Syntax.findSkippedTokenInLeadingTriviaList(this.parentToken(), end); + + if (nextToken) { + return nextToken; + } + + return this.parentToken(); + } else { + nextToken = TypeScript.Syntax.findSkippedTokenInTrailingTriviaList(this.parentToken(), end); + + if (nextToken) { + return nextToken; + } + } + } + + return this.root().node().findToken(this.parentToken().fullEnd(), includeSkippedTokens); + }; + return PositionedSkippedToken; + })(PositionedToken); + TypeScript.PositionedSkippedToken = PositionedSkippedToken; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["None"] = 0] = "None"; + SyntaxKind[SyntaxKind["List"] = 1] = "List"; + SyntaxKind[SyntaxKind["SeparatedList"] = 2] = "SeparatedList"; + SyntaxKind[SyntaxKind["TriviaList"] = 3] = "TriviaList"; + + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 4] = "WhitespaceTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 5] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 6] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 7] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["SkippedTokenTrivia"] = 8] = "SkippedTokenTrivia"; + + SyntaxKind[SyntaxKind["ErrorToken"] = 9] = "ErrorToken"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 10] = "EndOfFileToken"; + + SyntaxKind[SyntaxKind["IdentifierName"] = 11] = "IdentifierName"; + + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 13] = "NumericLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 14] = "StringLiteral"; + + SyntaxKind[SyntaxKind["BreakKeyword"] = 15] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 16] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 17] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 18] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 19] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 20] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 21] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 22] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 23] = "ElseKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 24] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 25] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 26] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 27] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 28] = "IfKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 29] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 30] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 31] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 32] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 33] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 34] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 35] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 36] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 37] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 38] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 39] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 40] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 41] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 42] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 43] = "WithKeyword"; + + SyntaxKind[SyntaxKind["ClassKeyword"] = 44] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 45] = "ConstKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 46] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 47] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 48] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 49] = "ImportKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 50] = "SuperKeyword"; + + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 51] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 52] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 53] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 54] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 55] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 56] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 57] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 58] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 59] = "YieldKeyword"; + + SyntaxKind[SyntaxKind["AnyKeyword"] = 60] = "AnyKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 61] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 62] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 63] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 64] = "GetKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 65] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 66] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 67] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 68] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 69] = "StringKeyword"; + + SyntaxKind[SyntaxKind["OpenBraceToken"] = 70] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 71] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 72] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 73] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 74] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 75] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 76] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 77] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 78] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 79] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 80] = "LessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 81] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 82] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 83] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 84] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 85] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 86] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 87] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 88] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 89] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 90] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 91] = "AsteriskToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 92] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 93] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 94] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 95] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 96] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 97] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 98] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 99] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 100] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 101] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 102] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 103] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 104] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 105] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 106] = "ColonToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 107] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 108] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 109] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 110] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 111] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 112] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 113] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 114] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 115] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 116] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 117] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 118] = "SlashToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 119] = "SlashEqualsToken"; + + SyntaxKind[SyntaxKind["SourceUnit"] = 120] = "SourceUnit"; + + SyntaxKind[SyntaxKind["QualifiedName"] = 121] = "QualifiedName"; + + SyntaxKind[SyntaxKind["ObjectType"] = 122] = "ObjectType"; + SyntaxKind[SyntaxKind["FunctionType"] = 123] = "FunctionType"; + SyntaxKind[SyntaxKind["ArrayType"] = 124] = "ArrayType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 125] = "ConstructorType"; + SyntaxKind[SyntaxKind["GenericType"] = 126] = "GenericType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 127] = "TypeQuery"; + + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 128] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 129] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 130] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 131] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 132] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 133] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 134] = "ExportAssignment"; + + SyntaxKind[SyntaxKind["MemberFunctionDeclaration"] = 135] = "MemberFunctionDeclaration"; + SyntaxKind[SyntaxKind["MemberVariableDeclaration"] = 136] = "MemberVariableDeclaration"; + SyntaxKind[SyntaxKind["ConstructorDeclaration"] = 137] = "ConstructorDeclaration"; + SyntaxKind[SyntaxKind["IndexMemberDeclaration"] = 138] = "IndexMemberDeclaration"; + + SyntaxKind[SyntaxKind["GetAccessor"] = 139] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 140] = "SetAccessor"; + + SyntaxKind[SyntaxKind["PropertySignature"] = 141] = "PropertySignature"; + SyntaxKind[SyntaxKind["CallSignature"] = 142] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 143] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 144] = "IndexSignature"; + SyntaxKind[SyntaxKind["MethodSignature"] = 145] = "MethodSignature"; + + SyntaxKind[SyntaxKind["Block"] = 146] = "Block"; + SyntaxKind[SyntaxKind["IfStatement"] = 147] = "IfStatement"; + SyntaxKind[SyntaxKind["VariableStatement"] = 148] = "VariableStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 149] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 150] = "ReturnStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 151] = "SwitchStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 152] = "BreakStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 153] = "ContinueStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 154] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 155] = "ForInStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 156] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 157] = "ThrowStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 158] = "WhileStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 159] = "TryStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 160] = "LabeledStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 161] = "DoStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 162] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 163] = "WithStatement"; + + SyntaxKind[SyntaxKind["PlusExpression"] = 164] = "PlusExpression"; + SyntaxKind[SyntaxKind["NegateExpression"] = 165] = "NegateExpression"; + SyntaxKind[SyntaxKind["BitwiseNotExpression"] = 166] = "BitwiseNotExpression"; + SyntaxKind[SyntaxKind["LogicalNotExpression"] = 167] = "LogicalNotExpression"; + SyntaxKind[SyntaxKind["PreIncrementExpression"] = 168] = "PreIncrementExpression"; + SyntaxKind[SyntaxKind["PreDecrementExpression"] = 169] = "PreDecrementExpression"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 170] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 171] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 172] = "VoidExpression"; + SyntaxKind[SyntaxKind["CommaExpression"] = 173] = "CommaExpression"; + SyntaxKind[SyntaxKind["AssignmentExpression"] = 174] = "AssignmentExpression"; + SyntaxKind[SyntaxKind["AddAssignmentExpression"] = 175] = "AddAssignmentExpression"; + SyntaxKind[SyntaxKind["SubtractAssignmentExpression"] = 176] = "SubtractAssignmentExpression"; + SyntaxKind[SyntaxKind["MultiplyAssignmentExpression"] = 177] = "MultiplyAssignmentExpression"; + SyntaxKind[SyntaxKind["DivideAssignmentExpression"] = 178] = "DivideAssignmentExpression"; + SyntaxKind[SyntaxKind["ModuloAssignmentExpression"] = 179] = "ModuloAssignmentExpression"; + SyntaxKind[SyntaxKind["AndAssignmentExpression"] = 180] = "AndAssignmentExpression"; + SyntaxKind[SyntaxKind["ExclusiveOrAssignmentExpression"] = 181] = "ExclusiveOrAssignmentExpression"; + SyntaxKind[SyntaxKind["OrAssignmentExpression"] = 182] = "OrAssignmentExpression"; + SyntaxKind[SyntaxKind["LeftShiftAssignmentExpression"] = 183] = "LeftShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["SignedRightShiftAssignmentExpression"] = 184] = "SignedRightShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["UnsignedRightShiftAssignmentExpression"] = 185] = "UnsignedRightShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 186] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["LogicalOrExpression"] = 187] = "LogicalOrExpression"; + SyntaxKind[SyntaxKind["LogicalAndExpression"] = 188] = "LogicalAndExpression"; + SyntaxKind[SyntaxKind["BitwiseOrExpression"] = 189] = "BitwiseOrExpression"; + SyntaxKind[SyntaxKind["BitwiseExclusiveOrExpression"] = 190] = "BitwiseExclusiveOrExpression"; + SyntaxKind[SyntaxKind["BitwiseAndExpression"] = 191] = "BitwiseAndExpression"; + SyntaxKind[SyntaxKind["EqualsWithTypeConversionExpression"] = 192] = "EqualsWithTypeConversionExpression"; + SyntaxKind[SyntaxKind["NotEqualsWithTypeConversionExpression"] = 193] = "NotEqualsWithTypeConversionExpression"; + SyntaxKind[SyntaxKind["EqualsExpression"] = 194] = "EqualsExpression"; + SyntaxKind[SyntaxKind["NotEqualsExpression"] = 195] = "NotEqualsExpression"; + SyntaxKind[SyntaxKind["LessThanExpression"] = 196] = "LessThanExpression"; + SyntaxKind[SyntaxKind["GreaterThanExpression"] = 197] = "GreaterThanExpression"; + SyntaxKind[SyntaxKind["LessThanOrEqualExpression"] = 198] = "LessThanOrEqualExpression"; + SyntaxKind[SyntaxKind["GreaterThanOrEqualExpression"] = 199] = "GreaterThanOrEqualExpression"; + SyntaxKind[SyntaxKind["InstanceOfExpression"] = 200] = "InstanceOfExpression"; + SyntaxKind[SyntaxKind["InExpression"] = 201] = "InExpression"; + SyntaxKind[SyntaxKind["LeftShiftExpression"] = 202] = "LeftShiftExpression"; + SyntaxKind[SyntaxKind["SignedRightShiftExpression"] = 203] = "SignedRightShiftExpression"; + SyntaxKind[SyntaxKind["UnsignedRightShiftExpression"] = 204] = "UnsignedRightShiftExpression"; + SyntaxKind[SyntaxKind["MultiplyExpression"] = 205] = "MultiplyExpression"; + SyntaxKind[SyntaxKind["DivideExpression"] = 206] = "DivideExpression"; + SyntaxKind[SyntaxKind["ModuloExpression"] = 207] = "ModuloExpression"; + SyntaxKind[SyntaxKind["AddExpression"] = 208] = "AddExpression"; + SyntaxKind[SyntaxKind["SubtractExpression"] = 209] = "SubtractExpression"; + SyntaxKind[SyntaxKind["PostIncrementExpression"] = 210] = "PostIncrementExpression"; + SyntaxKind[SyntaxKind["PostDecrementExpression"] = 211] = "PostDecrementExpression"; + SyntaxKind[SyntaxKind["MemberAccessExpression"] = 212] = "MemberAccessExpression"; + SyntaxKind[SyntaxKind["InvocationExpression"] = 213] = "InvocationExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 214] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 215] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectCreationExpression"] = 216] = "ObjectCreationExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 217] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["ParenthesizedArrowFunctionExpression"] = 218] = "ParenthesizedArrowFunctionExpression"; + SyntaxKind[SyntaxKind["SimpleArrowFunctionExpression"] = 219] = "SimpleArrowFunctionExpression"; + SyntaxKind[SyntaxKind["CastExpression"] = 220] = "CastExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 221] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 222] = "FunctionExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 223] = "OmittedExpression"; + + SyntaxKind[SyntaxKind["VariableDeclaration"] = 224] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarator"] = 225] = "VariableDeclarator"; + + SyntaxKind[SyntaxKind["ArgumentList"] = 226] = "ArgumentList"; + SyntaxKind[SyntaxKind["ParameterList"] = 227] = "ParameterList"; + SyntaxKind[SyntaxKind["TypeArgumentList"] = 228] = "TypeArgumentList"; + SyntaxKind[SyntaxKind["TypeParameterList"] = 229] = "TypeParameterList"; + + SyntaxKind[SyntaxKind["ExtendsHeritageClause"] = 230] = "ExtendsHeritageClause"; + SyntaxKind[SyntaxKind["ImplementsHeritageClause"] = 231] = "ImplementsHeritageClause"; + SyntaxKind[SyntaxKind["EqualsValueClause"] = 232] = "EqualsValueClause"; + SyntaxKind[SyntaxKind["CaseSwitchClause"] = 233] = "CaseSwitchClause"; + SyntaxKind[SyntaxKind["DefaultSwitchClause"] = 234] = "DefaultSwitchClause"; + SyntaxKind[SyntaxKind["ElseClause"] = 235] = "ElseClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 236] = "CatchClause"; + SyntaxKind[SyntaxKind["FinallyClause"] = 237] = "FinallyClause"; + + SyntaxKind[SyntaxKind["TypeParameter"] = 238] = "TypeParameter"; + SyntaxKind[SyntaxKind["Constraint"] = 239] = "Constraint"; + + SyntaxKind[SyntaxKind["SimplePropertyAssignment"] = 240] = "SimplePropertyAssignment"; + + SyntaxKind[SyntaxKind["FunctionPropertyAssignment"] = 241] = "FunctionPropertyAssignment"; + + SyntaxKind[SyntaxKind["Parameter"] = 242] = "Parameter"; + SyntaxKind[SyntaxKind["EnumElement"] = 243] = "EnumElement"; + SyntaxKind[SyntaxKind["TypeAnnotation"] = 244] = "TypeAnnotation"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 245] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ModuleNameModuleReference"] = 246] = "ModuleNameModuleReference"; + SyntaxKind[SyntaxKind["Last"] = SyntaxKind.ModuleNameModuleReference] = "Last"; + + SyntaxKind[SyntaxKind["FirstStandardKeyword"] = SyntaxKind.BreakKeyword] = "FirstStandardKeyword"; + SyntaxKind[SyntaxKind["LastStandardKeyword"] = SyntaxKind.WithKeyword] = "LastStandardKeyword"; + + SyntaxKind[SyntaxKind["FirstFutureReservedKeyword"] = SyntaxKind.ClassKeyword] = "FirstFutureReservedKeyword"; + SyntaxKind[SyntaxKind["LastFutureReservedKeyword"] = SyntaxKind.SuperKeyword] = "LastFutureReservedKeyword"; + + SyntaxKind[SyntaxKind["FirstFutureReservedStrictKeyword"] = SyntaxKind.ImplementsKeyword] = "FirstFutureReservedStrictKeyword"; + SyntaxKind[SyntaxKind["LastFutureReservedStrictKeyword"] = SyntaxKind.YieldKeyword] = "LastFutureReservedStrictKeyword"; + + SyntaxKind[SyntaxKind["FirstTypeScriptKeyword"] = SyntaxKind.AnyKeyword] = "FirstTypeScriptKeyword"; + SyntaxKind[SyntaxKind["LastTypeScriptKeyword"] = SyntaxKind.StringKeyword] = "LastTypeScriptKeyword"; + + SyntaxKind[SyntaxKind["FirstKeyword"] = SyntaxKind.FirstStandardKeyword] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = SyntaxKind.LastTypeScriptKeyword] = "LastKeyword"; + + SyntaxKind[SyntaxKind["FirstToken"] = SyntaxKind.ErrorToken] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = SyntaxKind.SlashEqualsToken] = "LastToken"; + + SyntaxKind[SyntaxKind["FirstPunctuation"] = SyntaxKind.OpenBraceToken] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = SyntaxKind.SlashEqualsToken] = "LastPunctuation"; + + SyntaxKind[SyntaxKind["FirstFixedWidth"] = SyntaxKind.FirstKeyword] = "FirstFixedWidth"; + SyntaxKind[SyntaxKind["LastFixedWidth"] = SyntaxKind.LastPunctuation] = "LastFixedWidth"; + + SyntaxKind[SyntaxKind["FirstTrivia"] = SyntaxKind.WhitespaceTrivia] = "FirstTrivia"; + SyntaxKind[SyntaxKind["LastTrivia"] = SyntaxKind.SkippedTokenTrivia] = "LastTrivia"; + })(TypeScript.SyntaxKind || (TypeScript.SyntaxKind = {})); + var SyntaxKind = TypeScript.SyntaxKind; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxFacts) { + var textToKeywordKind = { + "any": 60 /* AnyKeyword */, + "boolean": 61 /* BooleanKeyword */, + "break": 15 /* BreakKeyword */, + "case": 16 /* CaseKeyword */, + "catch": 17 /* CatchKeyword */, + "class": 44 /* ClassKeyword */, + "continue": 18 /* ContinueKeyword */, + "const": 45 /* ConstKeyword */, + "constructor": 62 /* ConstructorKeyword */, + "debugger": 19 /* DebuggerKeyword */, + "declare": 63 /* DeclareKeyword */, + "default": 20 /* DefaultKeyword */, + "delete": 21 /* DeleteKeyword */, + "do": 22 /* DoKeyword */, + "else": 23 /* ElseKeyword */, + "enum": 46 /* EnumKeyword */, + "export": 47 /* ExportKeyword */, + "extends": 48 /* ExtendsKeyword */, + "false": 24 /* FalseKeyword */, + "finally": 25 /* FinallyKeyword */, + "for": 26 /* ForKeyword */, + "function": 27 /* FunctionKeyword */, + "get": 64 /* GetKeyword */, + "if": 28 /* IfKeyword */, + "implements": 51 /* ImplementsKeyword */, + "import": 49 /* ImportKeyword */, + "in": 29 /* InKeyword */, + "instanceof": 30 /* InstanceOfKeyword */, + "interface": 52 /* InterfaceKeyword */, + "let": 53 /* LetKeyword */, + "module": 65 /* ModuleKeyword */, + "new": 31 /* NewKeyword */, + "null": 32 /* NullKeyword */, + "number": 67 /* NumberKeyword */, + "package": 54 /* PackageKeyword */, + "private": 55 /* PrivateKeyword */, + "protected": 56 /* ProtectedKeyword */, + "public": 57 /* PublicKeyword */, + "require": 66 /* RequireKeyword */, + "return": 33 /* ReturnKeyword */, + "set": 68 /* SetKeyword */, + "static": 58 /* StaticKeyword */, + "string": 69 /* StringKeyword */, + "super": 50 /* SuperKeyword */, + "switch": 34 /* SwitchKeyword */, + "this": 35 /* ThisKeyword */, + "throw": 36 /* ThrowKeyword */, + "true": 37 /* TrueKeyword */, + "try": 38 /* TryKeyword */, + "typeof": 39 /* TypeOfKeyword */, + "var": 40 /* VarKeyword */, + "void": 41 /* VoidKeyword */, + "while": 42 /* WhileKeyword */, + "with": 43 /* WithKeyword */, + "yield": 59 /* YieldKeyword */, + "{": 70 /* OpenBraceToken */, + "}": 71 /* CloseBraceToken */, + "(": 72 /* OpenParenToken */, + ")": 73 /* CloseParenToken */, + "[": 74 /* OpenBracketToken */, + "]": 75 /* CloseBracketToken */, + ".": 76 /* DotToken */, + "...": 77 /* DotDotDotToken */, + ";": 78 /* SemicolonToken */, + ",": 79 /* CommaToken */, + "<": 80 /* LessThanToken */, + ">": 81 /* GreaterThanToken */, + "<=": 82 /* LessThanEqualsToken */, + ">=": 83 /* GreaterThanEqualsToken */, + "==": 84 /* EqualsEqualsToken */, + "=>": 85 /* EqualsGreaterThanToken */, + "!=": 86 /* ExclamationEqualsToken */, + "===": 87 /* EqualsEqualsEqualsToken */, + "!==": 88 /* ExclamationEqualsEqualsToken */, + "+": 89 /* PlusToken */, + "-": 90 /* MinusToken */, + "*": 91 /* AsteriskToken */, + "%": 92 /* PercentToken */, + "++": 93 /* PlusPlusToken */, + "--": 94 /* MinusMinusToken */, + "<<": 95 /* LessThanLessThanToken */, + ">>": 96 /* GreaterThanGreaterThanToken */, + ">>>": 97 /* GreaterThanGreaterThanGreaterThanToken */, + "&": 98 /* AmpersandToken */, + "|": 99 /* BarToken */, + "^": 100 /* CaretToken */, + "!": 101 /* ExclamationToken */, + "~": 102 /* TildeToken */, + "&&": 103 /* AmpersandAmpersandToken */, + "||": 104 /* BarBarToken */, + "?": 105 /* QuestionToken */, + ":": 106 /* ColonToken */, + "=": 107 /* EqualsToken */, + "+=": 108 /* PlusEqualsToken */, + "-=": 109 /* MinusEqualsToken */, + "*=": 110 /* AsteriskEqualsToken */, + "%=": 111 /* PercentEqualsToken */, + "<<=": 112 /* LessThanLessThanEqualsToken */, + ">>=": 113 /* GreaterThanGreaterThanEqualsToken */, + ">>>=": 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */, + "&=": 115 /* AmpersandEqualsToken */, + "|=": 116 /* BarEqualsToken */, + "^=": 117 /* CaretEqualsToken */, + "/": 118 /* SlashToken */, + "/=": 119 /* SlashEqualsToken */ + }; + + var kindToText = new Array(); + + for (var name in textToKeywordKind) { + if (textToKeywordKind.hasOwnProperty(name)) { + kindToText[textToKeywordKind[name]] = name; + } + } + + kindToText[62 /* ConstructorKeyword */] = "constructor"; + + function getTokenKind(text) { + if (textToKeywordKind.hasOwnProperty(text)) { + return textToKeywordKind[text]; + } + + return 0 /* None */; + } + SyntaxFacts.getTokenKind = getTokenKind; + + function getText(kind) { + var result = kindToText[kind]; + return result !== undefined ? result : null; + } + SyntaxFacts.getText = getText; + + function isTokenKind(kind) { + return kind >= 9 /* FirstToken */ && kind <= 119 /* LastToken */; + } + SyntaxFacts.isTokenKind = isTokenKind; + + function isAnyKeyword(kind) { + return kind >= 15 /* FirstKeyword */ && kind <= 69 /* LastKeyword */; + } + SyntaxFacts.isAnyKeyword = isAnyKeyword; + + function isStandardKeyword(kind) { + return kind >= 15 /* FirstStandardKeyword */ && kind <= 43 /* LastStandardKeyword */; + } + SyntaxFacts.isStandardKeyword = isStandardKeyword; + + function isFutureReservedKeyword(kind) { + return kind >= 44 /* FirstFutureReservedKeyword */ && kind <= 50 /* LastFutureReservedKeyword */; + } + SyntaxFacts.isFutureReservedKeyword = isFutureReservedKeyword; + + function isFutureReservedStrictKeyword(kind) { + return kind >= 51 /* FirstFutureReservedStrictKeyword */ && kind <= 59 /* LastFutureReservedStrictKeyword */; + } + SyntaxFacts.isFutureReservedStrictKeyword = isFutureReservedStrictKeyword; + + function isAnyPunctuation(kind) { + return kind >= 70 /* FirstPunctuation */ && kind <= 119 /* LastPunctuation */; + } + SyntaxFacts.isAnyPunctuation = isAnyPunctuation; + + function isPrefixUnaryExpressionOperatorToken(tokenKind) { + return getPrefixUnaryExpressionFromOperatorToken(tokenKind) !== 0 /* None */; + } + SyntaxFacts.isPrefixUnaryExpressionOperatorToken = isPrefixUnaryExpressionOperatorToken; + + function isBinaryExpressionOperatorToken(tokenKind) { + return getBinaryExpressionFromOperatorToken(tokenKind) !== 0 /* None */; + } + SyntaxFacts.isBinaryExpressionOperatorToken = isBinaryExpressionOperatorToken; + + function getPrefixUnaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 89 /* PlusToken */: + return 164 /* PlusExpression */; + case 90 /* MinusToken */: + return 165 /* NegateExpression */; + case 102 /* TildeToken */: + return 166 /* BitwiseNotExpression */; + case 101 /* ExclamationToken */: + return 167 /* LogicalNotExpression */; + case 93 /* PlusPlusToken */: + return 168 /* PreIncrementExpression */; + case 94 /* MinusMinusToken */: + return 169 /* PreDecrementExpression */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getPrefixUnaryExpressionFromOperatorToken = getPrefixUnaryExpressionFromOperatorToken; + + function getPostfixUnaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 93 /* PlusPlusToken */: + return 210 /* PostIncrementExpression */; + case 94 /* MinusMinusToken */: + return 211 /* PostDecrementExpression */; + default: + return 0 /* None */; + } + } + SyntaxFacts.getPostfixUnaryExpressionFromOperatorToken = getPostfixUnaryExpressionFromOperatorToken; + + function getBinaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 91 /* AsteriskToken */: + return 205 /* MultiplyExpression */; + + case 118 /* SlashToken */: + return 206 /* DivideExpression */; + + case 92 /* PercentToken */: + return 207 /* ModuloExpression */; + + case 89 /* PlusToken */: + return 208 /* AddExpression */; + + case 90 /* MinusToken */: + return 209 /* SubtractExpression */; + + case 95 /* LessThanLessThanToken */: + return 202 /* LeftShiftExpression */; + + case 96 /* GreaterThanGreaterThanToken */: + return 203 /* SignedRightShiftExpression */; + + case 97 /* GreaterThanGreaterThanGreaterThanToken */: + return 204 /* UnsignedRightShiftExpression */; + + case 80 /* LessThanToken */: + return 196 /* LessThanExpression */; + + case 81 /* GreaterThanToken */: + return 197 /* GreaterThanExpression */; + + case 82 /* LessThanEqualsToken */: + return 198 /* LessThanOrEqualExpression */; + + case 83 /* GreaterThanEqualsToken */: + return 199 /* GreaterThanOrEqualExpression */; + + case 30 /* InstanceOfKeyword */: + return 200 /* InstanceOfExpression */; + + case 29 /* InKeyword */: + return 201 /* InExpression */; + + case 84 /* EqualsEqualsToken */: + return 192 /* EqualsWithTypeConversionExpression */; + + case 86 /* ExclamationEqualsToken */: + return 193 /* NotEqualsWithTypeConversionExpression */; + + case 87 /* EqualsEqualsEqualsToken */: + return 194 /* EqualsExpression */; + + case 88 /* ExclamationEqualsEqualsToken */: + return 195 /* NotEqualsExpression */; + + case 98 /* AmpersandToken */: + return 191 /* BitwiseAndExpression */; + + case 100 /* CaretToken */: + return 190 /* BitwiseExclusiveOrExpression */; + + case 99 /* BarToken */: + return 189 /* BitwiseOrExpression */; + + case 103 /* AmpersandAmpersandToken */: + return 188 /* LogicalAndExpression */; + + case 104 /* BarBarToken */: + return 187 /* LogicalOrExpression */; + + case 116 /* BarEqualsToken */: + return 182 /* OrAssignmentExpression */; + + case 115 /* AmpersandEqualsToken */: + return 180 /* AndAssignmentExpression */; + + case 117 /* CaretEqualsToken */: + return 181 /* ExclusiveOrAssignmentExpression */; + + case 112 /* LessThanLessThanEqualsToken */: + return 183 /* LeftShiftAssignmentExpression */; + + case 113 /* GreaterThanGreaterThanEqualsToken */: + return 184 /* SignedRightShiftAssignmentExpression */; + + case 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + return 185 /* UnsignedRightShiftAssignmentExpression */; + + case 108 /* PlusEqualsToken */: + return 175 /* AddAssignmentExpression */; + + case 109 /* MinusEqualsToken */: + return 176 /* SubtractAssignmentExpression */; + + case 110 /* AsteriskEqualsToken */: + return 177 /* MultiplyAssignmentExpression */; + + case 119 /* SlashEqualsToken */: + return 178 /* DivideAssignmentExpression */; + + case 111 /* PercentEqualsToken */: + return 179 /* ModuloAssignmentExpression */; + + case 107 /* EqualsToken */: + return 174 /* AssignmentExpression */; + + case 79 /* CommaToken */: + return 173 /* CommaExpression */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getBinaryExpressionFromOperatorToken = getBinaryExpressionFromOperatorToken; + + function getOperatorTokenFromBinaryExpression(tokenKind) { + switch (tokenKind) { + case 205 /* MultiplyExpression */: + return 91 /* AsteriskToken */; + + case 206 /* DivideExpression */: + return 118 /* SlashToken */; + + case 207 /* ModuloExpression */: + return 92 /* PercentToken */; + + case 208 /* AddExpression */: + return 89 /* PlusToken */; + + case 209 /* SubtractExpression */: + return 90 /* MinusToken */; + + case 202 /* LeftShiftExpression */: + return 95 /* LessThanLessThanToken */; + + case 203 /* SignedRightShiftExpression */: + return 96 /* GreaterThanGreaterThanToken */; + + case 204 /* UnsignedRightShiftExpression */: + return 97 /* GreaterThanGreaterThanGreaterThanToken */; + + case 196 /* LessThanExpression */: + return 80 /* LessThanToken */; + + case 197 /* GreaterThanExpression */: + return 81 /* GreaterThanToken */; + + case 198 /* LessThanOrEqualExpression */: + return 82 /* LessThanEqualsToken */; + + case 199 /* GreaterThanOrEqualExpression */: + return 83 /* GreaterThanEqualsToken */; + + case 200 /* InstanceOfExpression */: + return 30 /* InstanceOfKeyword */; + + case 201 /* InExpression */: + return 29 /* InKeyword */; + + case 192 /* EqualsWithTypeConversionExpression */: + return 84 /* EqualsEqualsToken */; + + case 193 /* NotEqualsWithTypeConversionExpression */: + return 86 /* ExclamationEqualsToken */; + + case 194 /* EqualsExpression */: + return 87 /* EqualsEqualsEqualsToken */; + + case 195 /* NotEqualsExpression */: + return 88 /* ExclamationEqualsEqualsToken */; + + case 191 /* BitwiseAndExpression */: + return 98 /* AmpersandToken */; + + case 190 /* BitwiseExclusiveOrExpression */: + return 100 /* CaretToken */; + + case 189 /* BitwiseOrExpression */: + return 99 /* BarToken */; + + case 188 /* LogicalAndExpression */: + return 103 /* AmpersandAmpersandToken */; + + case 187 /* LogicalOrExpression */: + return 104 /* BarBarToken */; + + case 182 /* OrAssignmentExpression */: + return 116 /* BarEqualsToken */; + + case 180 /* AndAssignmentExpression */: + return 115 /* AmpersandEqualsToken */; + + case 181 /* ExclusiveOrAssignmentExpression */: + return 117 /* CaretEqualsToken */; + + case 183 /* LeftShiftAssignmentExpression */: + return 112 /* LessThanLessThanEqualsToken */; + + case 184 /* SignedRightShiftAssignmentExpression */: + return 113 /* GreaterThanGreaterThanEqualsToken */; + + case 185 /* UnsignedRightShiftAssignmentExpression */: + return 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + + case 175 /* AddAssignmentExpression */: + return 108 /* PlusEqualsToken */; + + case 176 /* SubtractAssignmentExpression */: + return 109 /* MinusEqualsToken */; + + case 177 /* MultiplyAssignmentExpression */: + return 110 /* AsteriskEqualsToken */; + + case 178 /* DivideAssignmentExpression */: + return 119 /* SlashEqualsToken */; + + case 179 /* ModuloAssignmentExpression */: + return 111 /* PercentEqualsToken */; + + case 174 /* AssignmentExpression */: + return 107 /* EqualsToken */; + + case 173 /* CommaExpression */: + return 79 /* CommaToken */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getOperatorTokenFromBinaryExpression = getOperatorTokenFromBinaryExpression; + + function isAnyDivideToken(kind) { + switch (kind) { + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + return true; + default: + return false; + } + } + SyntaxFacts.isAnyDivideToken = isAnyDivideToken; + + function isAnyDivideOrRegularExpressionToken(kind) { + switch (kind) { + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + case 12 /* RegularExpressionLiteral */: + return true; + default: + return false; + } + } + SyntaxFacts.isAnyDivideOrRegularExpressionToken = isAnyDivideOrRegularExpressionToken; + })(TypeScript.SyntaxFacts || (TypeScript.SyntaxFacts = {})); + var SyntaxFacts = TypeScript.SyntaxFacts; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var isKeywordStartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + var isIdentifierStartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + var isIdentifierPartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + var isNumericLiteralStart = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + + for (var character = 0; character < 127 /* maxAsciiCharacter */; character++) { + if (character >= 97 /* a */ && character <= 122 /* z */) { + isIdentifierStartCharacter[character] = true; + isIdentifierPartCharacter[character] = true; + } else if ((character >= 65 /* A */ && character <= 90 /* Z */) || character === 95 /* _ */ || character === 36 /* $ */) { + isIdentifierStartCharacter[character] = true; + isIdentifierPartCharacter[character] = true; + } else if (character >= 48 /* _0 */ && character <= 57 /* _9 */) { + isIdentifierPartCharacter[character] = true; + isNumericLiteralStart[character] = true; + } + } + + isNumericLiteralStart[46 /* dot */] = true; + + for (var keywordKind = 15 /* FirstKeyword */; keywordKind <= 69 /* LastKeyword */; keywordKind++) { + var keyword = TypeScript.SyntaxFacts.getText(keywordKind); + isKeywordStartCharacter[keyword.charCodeAt(0)] = true; + } + + var Scanner = (function () { + function Scanner(fileName, text, languageVersion, window) { + if (typeof window === "undefined") { window = TypeScript.ArrayUtilities.createArray(2048, 0); } + this.slidingWindow = new TypeScript.SlidingWindow(this, window, 0, text.length()); + this.fileName = fileName; + this.text = text; + this._languageVersion = languageVersion; + } + Scanner.prototype.languageVersion = function () { + return this._languageVersion; + }; + + Scanner.prototype.fetchMoreItems = function (argument, sourceIndex, window, destinationIndex, spaceAvailable) { + var charactersRemaining = this.text.length() - sourceIndex; + var amountToRead = TypeScript.MathPrototype.min(charactersRemaining, spaceAvailable); + this.text.copyTo(sourceIndex, window, destinationIndex, amountToRead); + return amountToRead; + }; + + Scanner.prototype.currentCharCode = function () { + return this.slidingWindow.currentItem(null); + }; + + Scanner.prototype.absoluteIndex = function () { + return this.slidingWindow.absoluteIndex(); + }; + + Scanner.prototype.setAbsoluteIndex = function (index) { + this.slidingWindow.setAbsoluteIndex(index); + }; + + Scanner.prototype.scan = function (diagnostics, allowRegularExpression) { + var diagnosticsLength = diagnostics.length; + var fullStart = this.slidingWindow.absoluteIndex(); + var leadingTriviaInfo = this.scanTriviaInfo(diagnostics, false); + + var start = this.slidingWindow.absoluteIndex(); + var kindAndFlags = this.scanSyntaxToken(diagnostics, allowRegularExpression); + var end = this.slidingWindow.absoluteIndex(); + + var trailingTriviaInfo = this.scanTriviaInfo(diagnostics, true); + var fullEnd = this.slidingWindow.absoluteIndex(); + + var isVariableWidthKeyword = (kindAndFlags & -2147483648 /* IsVariableWidthKeyword */) !== 0; + var kind = kindAndFlags & ~-2147483648 /* IsVariableWidthKeyword */; + + var token = this.createToken(fullStart, leadingTriviaInfo, start, kind, end, fullEnd, trailingTriviaInfo, isVariableWidthKeyword); + + return diagnosticsLength !== diagnostics.length ? TypeScript.Syntax.realizeToken(token) : token; + }; + + Scanner.prototype.createToken = function (fullStart, leadingTriviaInfo, start, kind, end, fullEnd, trailingTriviaInfo, isVariableWidthKeyword) { + if (!isVariableWidthKeyword && kind >= 15 /* FirstFixedWidth */) { + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.FixedWidthTokenWithNoTrivia(kind); + } else { + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo); + } else { + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo); + } + } else { + var width = end - start; + + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.VariableWidthTokenWithNoTrivia(fullText, kind); + } else { + return new TypeScript.Syntax.VariableWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.VariableWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo); + } else { + return new TypeScript.Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo); + } + } + }; + + Scanner.scanTrivia = function (text, start, length, isTrailing) { + var scanner = new Scanner(null, text.subText(new TypeScript.TextSpan(start, length)), 1 /* EcmaScript5 */, Scanner.triviaWindow); + return scanner.scanTrivia(text, start, isTrailing); + }; + + Scanner.prototype.scanTrivia = function (underlyingText, underlyingTextStart, isTrailing) { + var trivia = new Array(); + + while (true) { + if (!this.slidingWindow.isAtEndOfSource()) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + trivia.push(this.scanWhitespaceTrivia(underlyingText, underlyingTextStart)); + continue; + + case 47 /* slash */: + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 47 /* slash */) { + trivia.push(this.scanSingleLineCommentTrivia(underlyingText, underlyingTextStart)); + continue; + } + + if (ch2 === 42 /* asterisk */) { + trivia.push(this.scanMultiLineCommentTrivia(underlyingText, underlyingTextStart)); + continue; + } + + throw TypeScript.Errors.invalidOperation(); + + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + trivia.push(this.scanLineTerminatorSequenceTrivia(ch)); + + if (!isTrailing) { + continue; + } + + break; + + default: + throw TypeScript.Errors.invalidOperation(); + } + } + + return TypeScript.Syntax.triviaList(trivia); + } + }; + + Scanner.prototype.scanTriviaInfo = function (diagnostics, isTrailing) { + var width = 0; + var hasCommentOrNewLine = 0; + + while (true) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + this.slidingWindow.moveToNextItem(); + width++; + continue; + + case 47 /* slash */: + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 47 /* slash */) { + hasCommentOrNewLine |= 2 /* TriviaCommentMask */; + width += this.scanSingleLineCommentTriviaLength(); + continue; + } + + if (ch2 === 42 /* asterisk */) { + hasCommentOrNewLine |= 2 /* TriviaCommentMask */; + width += this.scanMultiLineCommentTriviaLength(diagnostics); + continue; + } + + break; + + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + hasCommentOrNewLine |= 1 /* TriviaNewLineMask */; + width += this.scanLineTerminatorSequenceLength(ch); + + if (!isTrailing) { + continue; + } + + break; + } + + return (width << 2 /* TriviaFullWidthShift */) | hasCommentOrNewLine; + } + }; + + Scanner.prototype.isNewLineCharacter = function (ch) { + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + return true; + default: + return false; + } + }; + + Scanner.prototype.scanWhitespaceTrivia = function (underlyingText, underlyingTextStart) { + var absoluteStartIndex = this.absoluteIndex(); + + var width = 0; + while (true) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + this.slidingWindow.moveToNextItem(); + width++; + continue; + } + + break; + } + + return TypeScript.Syntax.deferredTrivia(4 /* WhitespaceTrivia */, underlyingText, underlyingTextStart + absoluteStartIndex, width); + }; + + Scanner.prototype.scanSingleLineCommentTrivia = function (underlyingText, underlyingTextStart) { + var absoluteStartIndex = this.slidingWindow.absoluteIndex(); + var width = this.scanSingleLineCommentTriviaLength(); + + return TypeScript.Syntax.deferredTrivia(7 /* SingleLineCommentTrivia */, underlyingText, underlyingTextStart + absoluteStartIndex, width); + }; + + Scanner.prototype.scanSingleLineCommentTriviaLength = function () { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + var width = 2; + while (true) { + if (this.slidingWindow.isAtEndOfSource() || this.isNewLineCharacter(this.currentCharCode())) { + return width; + } + + this.slidingWindow.moveToNextItem(); + width++; + } + }; + + Scanner.prototype.scanMultiLineCommentTrivia = function (underlyingText, underlyingTextStart) { + var absoluteStartIndex = this.absoluteIndex(); + var width = this.scanMultiLineCommentTriviaLength(null); + + return TypeScript.Syntax.deferredTrivia(6 /* MultiLineCommentTrivia */, underlyingText, underlyingTextStart + absoluteStartIndex, width); + }; + + Scanner.prototype.scanMultiLineCommentTriviaLength = function (diagnostics) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + var width = 2; + while (true) { + if (this.slidingWindow.isAtEndOfSource()) { + if (diagnostics !== null) { + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), this.slidingWindow.absoluteIndex(), 0, TypeScript.DiagnosticCode.AsteriskSlash_expected, null)); + } + + return width; + } + + var ch = this.currentCharCode(); + if (ch === 42 /* asterisk */ && this.slidingWindow.peekItemN(1) === 47 /* slash */) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + width += 2; + return width; + } + + this.slidingWindow.moveToNextItem(); + width++; + } + }; + + Scanner.prototype.scanLineTerminatorSequenceTrivia = function (ch) { + var absoluteStartIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + var width = this.scanLineTerminatorSequenceLength(ch); + + var text = this.substring(absoluteStartIndex, absoluteStartIndex + width, false); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(absoluteStartIndex); + + return TypeScript.Syntax.trivia(5 /* NewLineTrivia */, text); + }; + + Scanner.prototype.scanLineTerminatorSequenceLength = function (ch) { + this.slidingWindow.moveToNextItem(); + + if (ch === 13 /* carriageReturn */ && this.currentCharCode() === 10 /* lineFeed */) { + this.slidingWindow.moveToNextItem(); + return 2; + } else { + return 1; + } + }; + + Scanner.prototype.scanSyntaxToken = function (diagnostics, allowRegularExpression) { + if (this.slidingWindow.isAtEndOfSource()) { + return 10 /* EndOfFileToken */; + } + + var character = this.currentCharCode(); + + switch (character) { + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + return this.scanStringLiteral(diagnostics); + + case 47 /* slash */: + return this.scanSlashToken(allowRegularExpression); + + case 46 /* dot */: + return this.scanDotToken(diagnostics); + + case 45 /* minus */: + return this.scanMinusToken(); + + case 33 /* exclamation */: + return this.scanExclamationToken(); + + case 61 /* equals */: + return this.scanEqualsToken(); + + case 124 /* bar */: + return this.scanBarToken(); + + case 42 /* asterisk */: + return this.scanAsteriskToken(); + + case 43 /* plus */: + return this.scanPlusToken(); + + case 37 /* percent */: + return this.scanPercentToken(); + + case 38 /* ampersand */: + return this.scanAmpersandToken(); + + case 94 /* caret */: + return this.scanCaretToken(); + + case 60 /* lessThan */: + return this.scanLessThanToken(); + + case 62 /* greaterThan */: + return this.advanceAndSetTokenKind(81 /* GreaterThanToken */); + + case 44 /* comma */: + return this.advanceAndSetTokenKind(79 /* CommaToken */); + + case 58 /* colon */: + return this.advanceAndSetTokenKind(106 /* ColonToken */); + + case 59 /* semicolon */: + return this.advanceAndSetTokenKind(78 /* SemicolonToken */); + + case 126 /* tilde */: + return this.advanceAndSetTokenKind(102 /* TildeToken */); + + case 40 /* openParen */: + return this.advanceAndSetTokenKind(72 /* OpenParenToken */); + + case 41 /* closeParen */: + return this.advanceAndSetTokenKind(73 /* CloseParenToken */); + + case 123 /* openBrace */: + return this.advanceAndSetTokenKind(70 /* OpenBraceToken */); + + case 125 /* closeBrace */: + return this.advanceAndSetTokenKind(71 /* CloseBraceToken */); + + case 91 /* openBracket */: + return this.advanceAndSetTokenKind(74 /* OpenBracketToken */); + + case 93 /* closeBracket */: + return this.advanceAndSetTokenKind(75 /* CloseBracketToken */); + + case 63 /* question */: + return this.advanceAndSetTokenKind(105 /* QuestionToken */); + } + + if (isNumericLiteralStart[character]) { + return this.scanNumericLiteral(diagnostics); + } + + if (isIdentifierStartCharacter[character]) { + var result = this.tryFastScanIdentifierOrKeyword(character); + if (result !== 0 /* None */) { + return result; + } + } + + if (this.isIdentifierStart(this.peekCharOrUnicodeEscape())) { + return this.slowScanIdentifierOrKeyword(diagnostics); + } + + return this.scanDefaultCharacter(character, diagnostics); + }; + + Scanner.prototype.isIdentifierStart = function (interpretedChar) { + if (isIdentifierStartCharacter[interpretedChar]) { + return true; + } + + return interpretedChar > 127 /* maxAsciiCharacter */ && TypeScript.Unicode.isIdentifierStart(interpretedChar, this._languageVersion); + }; + + Scanner.prototype.isIdentifierPart = function (interpretedChar) { + if (isIdentifierPartCharacter[interpretedChar]) { + return true; + } + + return interpretedChar > 127 /* maxAsciiCharacter */ && TypeScript.Unicode.isIdentifierPart(interpretedChar, this._languageVersion); + }; + + Scanner.prototype.tryFastScanIdentifierOrKeyword = function (firstCharacter) { + var slidingWindow = this.slidingWindow; + var window = slidingWindow.window; + + var startIndex = slidingWindow.currentRelativeItemIndex; + var endIndex = slidingWindow.windowCount; + var currentIndex = startIndex; + var character = 0; + + while (currentIndex < endIndex) { + character = window[currentIndex]; + if (!isIdentifierPartCharacter[character]) { + break; + } + + currentIndex++; + } + + if (currentIndex === endIndex) { + return 0 /* None */; + } else if (character === 92 /* backslash */ || character > 127 /* maxAsciiCharacter */) { + return 0 /* None */; + } else { + var kind; + var identifierLength = currentIndex - startIndex; + if (isKeywordStartCharacter[firstCharacter]) { + kind = TypeScript.ScannerUtilities.identifierKind(window, startIndex, identifierLength); + } else { + kind = 11 /* IdentifierName */; + } + + slidingWindow.setAbsoluteIndex(slidingWindow.absoluteIndex() + identifierLength); + + return kind; + } + }; + + Scanner.prototype.slowScanIdentifierOrKeyword = function (diagnostics) { + var startIndex = this.slidingWindow.absoluteIndex(); + var sawUnicodeEscape = false; + + do { + var unicodeEscape = this.scanCharOrUnicodeEscape(diagnostics); + sawUnicodeEscape = sawUnicodeEscape || unicodeEscape; + } while(this.isIdentifierPart(this.peekCharOrUnicodeEscape())); + + var length = this.slidingWindow.absoluteIndex() - startIndex; + var text = this.text.substr(startIndex, length, false); + var valueText = TypeScript.Syntax.massageEscapes(text); + + var keywordKind = TypeScript.SyntaxFacts.getTokenKind(valueText); + if (keywordKind >= 15 /* FirstKeyword */ && keywordKind <= 69 /* LastKeyword */) { + if (sawUnicodeEscape) { + return keywordKind | -2147483648 /* IsVariableWidthKeyword */; + } else { + return keywordKind; + } + } + + return 11 /* IdentifierName */; + }; + + Scanner.prototype.scanNumericLiteral = function (diagnostics) { + if (this.isHexNumericLiteral()) { + this.scanHexNumericLiteral(); + } else if (this.isOctalNumericLiteral()) { + this.scanOctalNumericLiteral(diagnostics); + } else { + this.scanDecimalNumericLiteral(); + } + + return 13 /* NumericLiteral */; + }; + + Scanner.prototype.isOctalNumericLiteral = function () { + return this.currentCharCode() === 48 /* _0 */ && TypeScript.CharacterInfo.isOctalDigit(this.slidingWindow.peekItemN(1)); + }; + + Scanner.prototype.scanOctalNumericLiteral = function (diagnostics) { + var position = this.absoluteIndex(); + + while (TypeScript.CharacterInfo.isOctalDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + + if (this.languageVersion() >= 1 /* EcmaScript5 */) { + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), position, this.absoluteIndex() - position, TypeScript.DiagnosticCode.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher, null)); + } + }; + + Scanner.prototype.scanDecimalDigits = function () { + while (TypeScript.CharacterInfo.isDecimalDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + }; + + Scanner.prototype.scanDecimalNumericLiteral = function () { + this.scanDecimalDigits(); + + if (this.currentCharCode() === 46 /* dot */) { + this.slidingWindow.moveToNextItem(); + } + + this.scanDecimalDigits(); + + var ch = this.currentCharCode(); + if (ch === 101 /* e */ || ch === 69 /* E */) { + var nextChar1 = this.slidingWindow.peekItemN(1); + + if (TypeScript.CharacterInfo.isDecimalDigit(nextChar1)) { + this.slidingWindow.moveToNextItem(); + this.scanDecimalDigits(); + } else if (nextChar1 === 45 /* minus */ || nextChar1 === 43 /* plus */) { + var nextChar2 = this.slidingWindow.peekItemN(2); + if (TypeScript.CharacterInfo.isDecimalDigit(nextChar2)) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + this.scanDecimalDigits(); + } + } + } + }; + + Scanner.prototype.scanHexNumericLiteral = function () { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + while (TypeScript.CharacterInfo.isHexDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + }; + + Scanner.prototype.isHexNumericLiteral = function () { + if (this.currentCharCode() === 48 /* _0 */) { + var ch = this.slidingWindow.peekItemN(1); + + if (ch === 120 /* x */ || ch === 88 /* X */) { + ch = this.slidingWindow.peekItemN(2); + + return TypeScript.CharacterInfo.isHexDigit(ch); + } + } + + return false; + }; + + Scanner.prototype.advanceAndSetTokenKind = function (kind) { + this.slidingWindow.moveToNextItem(); + return kind; + }; + + Scanner.prototype.scanLessThanToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 82 /* LessThanEqualsToken */; + } else if (this.currentCharCode() === 60 /* lessThan */) { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 112 /* LessThanLessThanEqualsToken */; + } else { + return 95 /* LessThanLessThanToken */; + } + } else { + return 80 /* LessThanToken */; + } + }; + + Scanner.prototype.scanBarToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 116 /* BarEqualsToken */; + } else if (this.currentCharCode() === 124 /* bar */) { + this.slidingWindow.moveToNextItem(); + return 104 /* BarBarToken */; + } else { + return 99 /* BarToken */; + } + }; + + Scanner.prototype.scanCaretToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 117 /* CaretEqualsToken */; + } else { + return 100 /* CaretToken */; + } + }; + + Scanner.prototype.scanAmpersandToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 115 /* AmpersandEqualsToken */; + } else if (this.currentCharCode() === 38 /* ampersand */) { + this.slidingWindow.moveToNextItem(); + return 103 /* AmpersandAmpersandToken */; + } else { + return 98 /* AmpersandToken */; + } + }; + + Scanner.prototype.scanPercentToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 111 /* PercentEqualsToken */; + } else { + return 92 /* PercentToken */; + } + }; + + Scanner.prototype.scanMinusToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 109 /* MinusEqualsToken */; + } else if (character === 45 /* minus */) { + this.slidingWindow.moveToNextItem(); + return 94 /* MinusMinusToken */; + } else { + return 90 /* MinusToken */; + } + }; + + Scanner.prototype.scanPlusToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 108 /* PlusEqualsToken */; + } else if (character === 43 /* plus */) { + this.slidingWindow.moveToNextItem(); + return 93 /* PlusPlusToken */; + } else { + return 89 /* PlusToken */; + } + }; + + Scanner.prototype.scanAsteriskToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 110 /* AsteriskEqualsToken */; + } else { + return 91 /* AsteriskToken */; + } + }; + + Scanner.prototype.scanEqualsToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + return 87 /* EqualsEqualsEqualsToken */; + } else { + return 84 /* EqualsEqualsToken */; + } + } else if (character === 62 /* greaterThan */) { + this.slidingWindow.moveToNextItem(); + return 85 /* EqualsGreaterThanToken */; + } else { + return 107 /* EqualsToken */; + } + }; + + Scanner.prototype.isDotPrefixedNumericLiteral = function () { + if (this.currentCharCode() === 46 /* dot */) { + var ch = this.slidingWindow.peekItemN(1); + return TypeScript.CharacterInfo.isDecimalDigit(ch); + } + + return false; + }; + + Scanner.prototype.scanDotToken = function (diagnostics) { + if (this.isDotPrefixedNumericLiteral()) { + return this.scanNumericLiteral(diagnostics); + } + + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 46 /* dot */ && this.slidingWindow.peekItemN(1) === 46 /* dot */) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + return 77 /* DotDotDotToken */; + } else { + return 76 /* DotToken */; + } + }; + + Scanner.prototype.scanSlashToken = function (allowRegularExpression) { + if (allowRegularExpression) { + var result = this.tryScanRegularExpressionToken(); + if (result !== 0 /* None */) { + return result; + } + } + + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 119 /* SlashEqualsToken */; + } else { + return 118 /* SlashToken */; + } + }; + + Scanner.prototype.tryScanRegularExpressionToken = function () { + var startIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + this.slidingWindow.moveToNextItem(); + + var inEscape = false; + var inCharacterClass = false; + while (true) { + var ch = this.currentCharCode(); + + if (this.isNewLineCharacter(ch) || this.slidingWindow.isAtEndOfSource()) { + this.slidingWindow.rewindToPinnedIndex(startIndex); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + return 0 /* None */; + } + + this.slidingWindow.moveToNextItem(); + if (inEscape) { + inEscape = false; + continue; + } + + switch (ch) { + case 92 /* backslash */: + inEscape = true; + continue; + + case 91 /* openBracket */: + inCharacterClass = true; + continue; + + case 93 /* closeBracket */: + inCharacterClass = false; + continue; + + case 47 /* slash */: + if (inCharacterClass) { + continue; + } + + break; + + default: + continue; + } + + break; + } + + while (isIdentifierPartCharacter[this.currentCharCode()]) { + this.slidingWindow.moveToNextItem(); + } + + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + return 12 /* RegularExpressionLiteral */; + }; + + Scanner.prototype.scanExclamationToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + return 88 /* ExclamationEqualsEqualsToken */; + } else { + return 86 /* ExclamationEqualsToken */; + } + } else { + return 101 /* ExclamationToken */; + } + }; + + Scanner.prototype.scanDefaultCharacter = function (character, diagnostics) { + var position = this.slidingWindow.absoluteIndex(); + this.slidingWindow.moveToNextItem(); + + var text = String.fromCharCode(character); + var messageText = this.getErrorMessageText(text); + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), position, 1, TypeScript.DiagnosticCode.Unexpected_character_0, [messageText])); + + return 9 /* ErrorToken */; + }; + + Scanner.prototype.getErrorMessageText = function (text) { + if (text === "\\") { + return '"\\"'; + } + + return JSON.stringify(text); + }; + + Scanner.prototype.skipEscapeSequence = function (diagnostics) { + var rewindPoint = this.slidingWindow.getAndPinAbsoluteIndex(); + + this.slidingWindow.moveToNextItem(); + + var ch = this.currentCharCode(); + this.slidingWindow.moveToNextItem(); + switch (ch) { + case 120 /* x */: + case 117 /* u */: + this.slidingWindow.rewindToPinnedIndex(rewindPoint); + var value = this.scanUnicodeOrHexEscape(diagnostics); + break; + + case 13 /* carriageReturn */: + if (this.currentCharCode() === 10 /* lineFeed */) { + this.slidingWindow.moveToNextItem(); + } + break; + + default: + break; + } + + this.slidingWindow.releaseAndUnpinAbsoluteIndex(rewindPoint); + }; + + Scanner.prototype.scanStringLiteral = function (diagnostics) { + var quoteCharacter = this.currentCharCode(); + + this.slidingWindow.moveToNextItem(); + + while (true) { + var ch = this.currentCharCode(); + if (ch === 92 /* backslash */) { + this.skipEscapeSequence(diagnostics); + } else if (ch === quoteCharacter) { + this.slidingWindow.moveToNextItem(); + break; + } else if (this.isNewLineCharacter(ch) || this.slidingWindow.isAtEndOfSource()) { + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), TypeScript.MathPrototype.min(this.slidingWindow.absoluteIndex(), this.text.length()), 1, TypeScript.DiagnosticCode.Missing_close_quote_character, null)); + break; + } else { + this.slidingWindow.moveToNextItem(); + } + } + + return 14 /* StringLiteral */; + }; + + Scanner.prototype.isUnicodeEscape = function (character) { + if (character === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 117 /* u */) { + return true; + } + } + + return false; + }; + + Scanner.prototype.peekCharOrUnicodeEscape = function () { + var character = this.currentCharCode(); + if (this.isUnicodeEscape(character)) { + return this.peekUnicodeOrHexEscape(); + } else { + return character; + } + }; + + Scanner.prototype.peekUnicodeOrHexEscape = function () { + var startIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + var ch = this.scanUnicodeOrHexEscape(null); + + this.slidingWindow.rewindToPinnedIndex(startIndex); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + + return ch; + }; + + Scanner.prototype.scanCharOrUnicodeEscape = function (errors) { + var ch = this.currentCharCode(); + if (ch === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 117 /* u */) { + this.scanUnicodeOrHexEscape(errors); + return true; + } + } + + this.slidingWindow.moveToNextItem(); + return false; + }; + + Scanner.prototype.scanUnicodeOrHexEscape = function (errors) { + var start = this.slidingWindow.absoluteIndex(); + var character = this.currentCharCode(); + + this.slidingWindow.moveToNextItem(); + + character = this.currentCharCode(); + + var intChar = 0; + this.slidingWindow.moveToNextItem(); + + var count = character === 117 /* u */ ? 4 : 2; + + for (var i = 0; i < count; i++) { + var ch2 = this.currentCharCode(); + if (!TypeScript.CharacterInfo.isHexDigit(ch2)) { + if (errors !== null) { + var end = this.slidingWindow.absoluteIndex(); + var info = this.createIllegalEscapeDiagnostic(start, end); + errors.push(info); + } + + break; + } + + intChar = (intChar << 4) + TypeScript.CharacterInfo.hexValue(ch2); + this.slidingWindow.moveToNextItem(); + } + + return intChar; + }; + + Scanner.prototype.substring = function (start, end, intern) { + var length = end - start; + var offset = start - this.slidingWindow.windowAbsoluteStartIndex; + + if (intern) { + return TypeScript.Collections.DefaultStringTable.addCharArray(this.slidingWindow.window, offset, length); + } else { + return TypeScript.StringUtilities.fromCharCodeArray(this.slidingWindow.window.slice(offset, offset + length)); + } + }; + + Scanner.prototype.createIllegalEscapeDiagnostic = function (start, end) { + return new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), start, end - start, TypeScript.DiagnosticCode.Unrecognized_escape_sequence, null); + }; + + Scanner.isValidIdentifier = function (text, languageVersion) { + var scanner = new Scanner(null, text, languageVersion, Scanner.triviaWindow); + var errors = new Array(); + var token = scanner.scan(errors, false); + + return errors.length === 0 && TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token) && token.width() === text.length(); + }; + Scanner.triviaWindow = TypeScript.ArrayUtilities.createArray(2048, 0); + return Scanner; + })(); + TypeScript.Scanner = Scanner; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScannerUtilities = (function () { + function ScannerUtilities() { + } + ScannerUtilities.identifierKind = function (array, startIndex, length) { + switch (length) { + case 2: + switch (array[startIndex]) { + case 100 /* d */: + return (array[startIndex + 1] === 111 /* o */) ? 22 /* DoKeyword */ : 11 /* IdentifierName */; + case 105 /* i */: + switch (array[startIndex + 1]) { + case 102 /* f */: + return 28 /* IfKeyword */; + case 110 /* n */: + return 29 /* InKeyword */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 3: + switch (array[startIndex]) { + case 102 /* f */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 114 /* r */) ? 26 /* ForKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 119 /* w */) ? 31 /* NewKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 121 /* y */) ? 38 /* TryKeyword */ : 11 /* IdentifierName */; + case 118 /* v */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 114 /* r */) ? 40 /* VarKeyword */ : 11 /* IdentifierName */; + case 108 /* l */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 53 /* LetKeyword */ : 11 /* IdentifierName */; + case 97 /* a */: + return (array[startIndex + 1] === 110 /* n */ && array[startIndex + 2] === 121 /* y */) ? 60 /* AnyKeyword */ : 11 /* IdentifierName */; + case 103 /* g */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 64 /* GetKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 68 /* SetKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 4: + switch (array[startIndex]) { + case 99 /* c */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 101 /* e */) ? 16 /* CaseKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + switch (array[startIndex + 1]) { + case 108 /* l */: + return (array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 101 /* e */) ? 23 /* ElseKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 2] === 117 /* u */ && array[startIndex + 3] === 109 /* m */) ? 46 /* EnumKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 110 /* n */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 108 /* l */) ? 32 /* NullKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + switch (array[startIndex + 1]) { + case 104 /* h */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 115 /* s */) ? 35 /* ThisKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 2] === 117 /* u */ && array[startIndex + 3] === 101 /* e */) ? 37 /* TrueKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 118 /* v */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 100 /* d */) ? 41 /* VoidKeyword */ : 11 /* IdentifierName */; + case 119 /* w */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 104 /* h */) ? 43 /* WithKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 5: + switch (array[startIndex]) { + case 98 /* b */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 101 /* e */ && array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 107 /* k */) ? 15 /* BreakKeyword */ : 11 /* IdentifierName */; + case 99 /* c */: + switch (array[startIndex + 1]) { + case 97 /* a */: + return (array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 99 /* c */ && array[startIndex + 4] === 104 /* h */) ? 17 /* CatchKeyword */ : 11 /* IdentifierName */; + case 108 /* l */: + return (array[startIndex + 2] === 97 /* a */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 115 /* s */) ? 44 /* ClassKeyword */ : 11 /* IdentifierName */; + case 111 /* o */: + return (array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 116 /* t */) ? 45 /* ConstKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 102 /* f */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 101 /* e */) ? 24 /* FalseKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + return (array[startIndex + 1] === 104 /* h */ && array[startIndex + 2] === 114 /* r */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 119 /* w */) ? 36 /* ThrowKeyword */ : 11 /* IdentifierName */; + case 119 /* w */: + return (array[startIndex + 1] === 104 /* h */ && array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */) ? 42 /* WhileKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 114 /* r */) ? 50 /* SuperKeyword */ : 11 /* IdentifierName */; + case 121 /* y */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 101 /* e */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 100 /* d */) ? 59 /* YieldKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 6: + switch (array[startIndex]) { + case 100 /* d */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 101 /* e */) ? 21 /* DeleteKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 110 /* n */) ? 33 /* ReturnKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + switch (array[startIndex + 1]) { + case 119 /* w */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 99 /* c */ && array[startIndex + 5] === 104 /* h */) ? 34 /* SwitchKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + switch (array[startIndex + 2]) { + case 97 /* a */: + return (array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 99 /* c */) ? 58 /* StaticKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 3] === 105 /* i */ && array[startIndex + 4] === 110 /* n */ && array[startIndex + 5] === 103 /* g */) ? 69 /* StringKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 116 /* t */: + return (array[startIndex + 1] === 121 /* y */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 111 /* o */ && array[startIndex + 5] === 102 /* f */) ? 39 /* TypeOfKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + return (array[startIndex + 1] === 120 /* x */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 116 /* t */) ? 47 /* ExportKeyword */ : 11 /* IdentifierName */; + case 105 /* i */: + return (array[startIndex + 1] === 109 /* m */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 116 /* t */) ? 49 /* ImportKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 98 /* b */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 99 /* c */) ? 57 /* PublicKeyword */ : 11 /* IdentifierName */; + case 109 /* m */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 100 /* d */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 108 /* l */ && array[startIndex + 5] === 101 /* e */) ? 65 /* ModuleKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 109 /* m */ && array[startIndex + 3] === 98 /* b */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 114 /* r */) ? 67 /* NumberKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 7: + switch (array[startIndex]) { + case 100 /* d */: + switch (array[startIndex + 1]) { + case 101 /* e */: + switch (array[startIndex + 2]) { + case 102 /* f */: + return (array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 117 /* u */ && array[startIndex + 5] === 108 /* l */ && array[startIndex + 6] === 116 /* t */) ? 20 /* DefaultKeyword */ : 11 /* IdentifierName */; + case 99 /* c */: + return (array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 101 /* e */) ? 63 /* DeclareKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 102 /* f */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 108 /* l */ && array[startIndex + 5] === 108 /* l */ && array[startIndex + 6] === 121 /* y */) ? 25 /* FinallyKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + return (array[startIndex + 1] === 120 /* x */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 110 /* n */ && array[startIndex + 5] === 100 /* d */ && array[startIndex + 6] === 115 /* s */) ? 48 /* ExtendsKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + switch (array[startIndex + 1]) { + case 97 /* a */: + return (array[startIndex + 2] === 99 /* c */ && array[startIndex + 3] === 107 /* k */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 103 /* g */ && array[startIndex + 6] === 101 /* e */) ? 54 /* PackageKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 118 /* v */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 116 /* t */ && array[startIndex + 6] === 101 /* e */) ? 55 /* PrivateKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 98 /* b */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 111 /* o */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 97 /* a */ && array[startIndex + 6] === 110 /* n */) ? 61 /* BooleanKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 113 /* q */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 101 /* e */) ? 66 /* RequireKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 8: + switch (array[startIndex]) { + case 99 /* c */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 110 /* n */ && array[startIndex + 6] === 117 /* u */ && array[startIndex + 7] === 101 /* e */) ? 18 /* ContinueKeyword */ : 11 /* IdentifierName */; + case 100 /* d */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 98 /* b */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 103 /* g */ && array[startIndex + 5] === 103 /* g */ && array[startIndex + 6] === 101 /* e */ && array[startIndex + 7] === 114 /* r */) ? 19 /* DebuggerKeyword */ : 11 /* IdentifierName */; + case 102 /* f */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 99 /* c */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 105 /* i */ && array[startIndex + 6] === 111 /* o */ && array[startIndex + 7] === 110 /* n */) ? 27 /* FunctionKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 9: + switch (array[startIndex]) { + case 105 /* i */: + return (array[startIndex + 1] === 110 /* n */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 102 /* f */ && array[startIndex + 6] === 97 /* a */ && array[startIndex + 7] === 99 /* c */ && array[startIndex + 8] === 101 /* e */) ? 52 /* InterfaceKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 111 /* o */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 99 /* c */ && array[startIndex + 6] === 116 /* t */ && array[startIndex + 7] === 101 /* e */ && array[startIndex + 8] === 100 /* d */) ? 56 /* ProtectedKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 10: + switch (array[startIndex]) { + case 105 /* i */: + switch (array[startIndex + 1]) { + case 110 /* n */: + return (array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 110 /* n */ && array[startIndex + 6] === 99 /* c */ && array[startIndex + 7] === 101 /* e */ && array[startIndex + 8] === 111 /* o */ && array[startIndex + 9] === 102 /* f */) ? 30 /* InstanceOfKeyword */ : 11 /* IdentifierName */; + case 109 /* m */: + return (array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 109 /* m */ && array[startIndex + 6] === 101 /* e */ && array[startIndex + 7] === 110 /* n */ && array[startIndex + 8] === 116 /* t */ && array[startIndex + 9] === 115 /* s */) ? 51 /* ImplementsKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 11: + return (array[startIndex] === 99 /* c */ && array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 117 /* u */ && array[startIndex + 7] === 99 /* c */ && array[startIndex + 8] === 116 /* t */ && array[startIndex + 9] === 111 /* o */ && array[startIndex + 10] === 114 /* r */) ? 62 /* ConstructorKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + }; + return ScannerUtilities; + })(); + TypeScript.ScannerUtilities = ScannerUtilities; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var EmptySeparatedSyntaxList = (function () { + function EmptySeparatedSyntaxList() { + } + EmptySeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + EmptySeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isList = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + + EmptySeparatedSyntaxList.prototype.toJSON = function (key) { + return []; + }; + + EmptySeparatedSyntaxList.prototype.childCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.separatorCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.toArray = function () { + return []; + }; + + EmptySeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + return []; + }; + + EmptySeparatedSyntaxList.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.separatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.collectTextElements = function (elements) { + }; + + EmptySeparatedSyntaxList.prototype.firstToken = function () { + return null; + }; + + EmptySeparatedSyntaxList.prototype.lastToken = function () { + return null; + }; + + EmptySeparatedSyntaxList.prototype.fullWidth = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.fullText = function () { + return ""; + }; + + EmptySeparatedSyntaxList.prototype.width = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + throw TypeScript.Errors.invalidOperation(); + }; + + EmptySeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + }; + + EmptySeparatedSyntaxList.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySeparatedSyntaxList.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return 0; + }; + return EmptySeparatedSyntaxList; + })(); + + Syntax.emptySeparatedList = new EmptySeparatedSyntaxList(); + + var SingletonSeparatedSyntaxList = (function () { + function SingletonSeparatedSyntaxList(item) { + this.item = item; + } + SingletonSeparatedSyntaxList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + SingletonSeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isList = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + + SingletonSeparatedSyntaxList.prototype.childCount = function () { + return 1; + }; + SingletonSeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return 1; + }; + SingletonSeparatedSyntaxList.prototype.separatorCount = function () { + return 0; + }; + + SingletonSeparatedSyntaxList.prototype.toArray = function () { + return [this.item]; + }; + SingletonSeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + return [this.item]; + }; + + SingletonSeparatedSyntaxList.prototype.childAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSeparatedSyntaxList.prototype.separatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + SingletonSeparatedSyntaxList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSeparatedSyntaxList.prototype.firstToken = function () { + return this.item.firstToken(); + }; + + SingletonSeparatedSyntaxList.prototype.lastToken = function () { + return this.item.lastToken(); + }; + + SingletonSeparatedSyntaxList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.width = function () { + return this.item.width(); + }; + + SingletonSeparatedSyntaxList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSeparatedSyntaxList.prototype.leadingTrivia = function () { + return this.item.leadingTrivia(); + }; + + SingletonSeparatedSyntaxList.prototype.trailingTrivia = function () { + return this.item.trailingTrivia(); + }; + + SingletonSeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return this.item.leadingTriviaWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return this.item.trailingTriviaWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + return this.item.isTypeScriptSpecific(); + }; + + SingletonSeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return this.item.isIncrementallyUnusable(); + }; + + SingletonSeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + return this.item.findTokenInternal(new TypeScript.PositionedSeparatedList(parent, this, fullStart), position, fullStart); + }; + + SingletonSeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + array.splice(index, 0, this.item); + }; + return SingletonSeparatedSyntaxList; + })(); + + var NormalSeparatedSyntaxList = (function () { + function NormalSeparatedSyntaxList(elements) { + this._data = 0; + this.elements = elements; + } + NormalSeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + NormalSeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isList = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + NormalSeparatedSyntaxList.prototype.toJSON = function (key) { + return this.elements; + }; + + NormalSeparatedSyntaxList.prototype.childCount = function () { + return this.elements.length; + }; + NormalSeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return TypeScript.IntegerUtilities.integerDivide(this.elements.length + 1, 2); + }; + NormalSeparatedSyntaxList.prototype.separatorCount = function () { + return TypeScript.IntegerUtilities.integerDivide(this.elements.length, 2); + }; + + NormalSeparatedSyntaxList.prototype.toArray = function () { + return this.elements.slice(0); + }; + + NormalSeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + var result = []; + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + result.push(this.nonSeparatorAt(i)); + } + + return result; + }; + + NormalSeparatedSyntaxList.prototype.childAt = function (index) { + if (index < 0 || index >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[index]; + }; + + NormalSeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + var value = index * 2; + if (value < 0 || value >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[value]; + }; + + NormalSeparatedSyntaxList.prototype.separatorAt = function (index) { + var value = index * 2 + 1; + if (value < 0 || value >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[value]; + }; + + NormalSeparatedSyntaxList.prototype.firstToken = function () { + var token; + for (var i = 0, n = this.elements.length; i < n; i++) { + if (i % 2 === 0) { + var nodeOrToken = this.elements[i]; + token = nodeOrToken.firstToken(); + if (token !== null) { + return token; + } + } else { + token = this.elements[i]; + if (token.width() > 0) { + return token; + } + } + } + + return null; + }; + + NormalSeparatedSyntaxList.prototype.lastToken = function () { + var token; + for (var i = this.elements.length - 1; i >= 0; i--) { + if (i % 2 === 0) { + var nodeOrToken = this.elements[i]; + token = nodeOrToken.lastToken(); + if (token !== null) { + return token; + } + } else { + token = this.elements[i]; + if (token.width() > 0) { + return token; + } + } + } + + return null; + }; + + NormalSeparatedSyntaxList.prototype.fullText = function () { + var elements = []; + this.collectTextElements(elements); + return elements.join(""); + }; + + NormalSeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + if (this.nonSeparatorAt(i).isTypeScriptSpecific()) { + return true; + } + } + + return false; + }; + + NormalSeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + NormalSeparatedSyntaxList.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + NormalSeparatedSyntaxList.prototype.width = function () { + var fullWidth = this.fullWidth(); + return fullWidth - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.leadingTrivia = function () { + return this.firstToken().leadingTrivia(); + }; + + NormalSeparatedSyntaxList.prototype.trailingTrivia = function () { + return this.lastToken().trailingTrivia(); + }; + + NormalSeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return this.firstToken().leadingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return this.lastToken().trailingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.computeData = function () { + var fullWidth = 0; + var isIncrementallyUnusable = false; + + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + + var childWidth = element.fullWidth(); + fullWidth += childWidth; + + isIncrementallyUnusable = isIncrementallyUnusable || element.isIncrementallyUnusable(); + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + NormalSeparatedSyntaxList.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data = this.computeData(); + } + + return this._data; + }; + + NormalSeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedSeparatedList(parent, this, fullStart); + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + + var childWidth = element.fullWidth(); + if (position < childWidth) { + return element.findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + NormalSeparatedSyntaxList.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + element.collectTextElements(elements); + } + }; + + NormalSeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + if (index === 0) { + array.unshift.apply(array, this.elements); + } else { + array.splice.apply(array, [index, 0].concat(this.elements)); + } + }; + return NormalSeparatedSyntaxList; + })(); + + function separatedList(nodes) { + return separatedListAndValidate(nodes, false); + } + Syntax.separatedList = separatedList; + + function separatedListAndValidate(nodes, validate) { + if (nodes === undefined || nodes === null || nodes.length === 0) { + return Syntax.emptySeparatedList; + } + + if (validate) { + for (var i = 0; i < nodes.length; i++) { + var item = nodes[i]; + + if (i % 2 === 1) { + } + } + } + + if (nodes.length === 1) { + return new SingletonSeparatedSyntaxList(nodes[0]); + } + + return new NormalSeparatedSyntaxList(nodes); + } + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SlidingWindow = (function () { + function SlidingWindow(source, window, defaultValue, sourceLength) { + if (typeof sourceLength === "undefined") { sourceLength = -1; } + this.source = source; + this.window = window; + this.defaultValue = defaultValue; + this.sourceLength = sourceLength; + this.windowCount = 0; + this.windowAbsoluteStartIndex = 0; + this.currentRelativeItemIndex = 0; + this._pinCount = 0; + this.firstPinnedAbsoluteIndex = -1; + } + SlidingWindow.prototype.windowAbsoluteEndIndex = function () { + return this.windowAbsoluteStartIndex + this.windowCount; + }; + + SlidingWindow.prototype.addMoreItemsToWindow = function (argument) { + if (this.sourceLength >= 0 && this.absoluteIndex() >= this.sourceLength) { + return false; + } + + if (this.windowCount >= this.window.length) { + this.tryShiftOrGrowWindow(); + } + + var spaceAvailable = this.window.length - this.windowCount; + var amountFetched = this.source.fetchMoreItems(argument, this.windowAbsoluteEndIndex(), this.window, this.windowCount, spaceAvailable); + + this.windowCount += amountFetched; + return amountFetched > 0; + }; + + SlidingWindow.prototype.tryShiftOrGrowWindow = function () { + var currentIndexIsPastWindowHalfwayPoint = this.currentRelativeItemIndex > (this.window.length >>> 1); + + var isAllowedToShift = this.firstPinnedAbsoluteIndex === -1 || this.firstPinnedAbsoluteIndex > this.windowAbsoluteStartIndex; + + if (currentIndexIsPastWindowHalfwayPoint && isAllowedToShift) { + var shiftStartIndex = this.firstPinnedAbsoluteIndex === -1 ? this.currentRelativeItemIndex : this.firstPinnedAbsoluteIndex - this.windowAbsoluteStartIndex; + + var shiftCount = this.windowCount - shiftStartIndex; + + if (shiftCount > 0) { + TypeScript.ArrayUtilities.copy(this.window, shiftStartIndex, this.window, 0, shiftCount); + } + + this.windowAbsoluteStartIndex += shiftStartIndex; + + this.windowCount -= shiftStartIndex; + + this.currentRelativeItemIndex -= shiftStartIndex; + } else { + TypeScript.ArrayUtilities.grow(this.window, this.window.length * 2, this.defaultValue); + } + }; + + SlidingWindow.prototype.absoluteIndex = function () { + return this.windowAbsoluteStartIndex + this.currentRelativeItemIndex; + }; + + SlidingWindow.prototype.isAtEndOfSource = function () { + return this.absoluteIndex() >= this.sourceLength; + }; + + SlidingWindow.prototype.getAndPinAbsoluteIndex = function () { + var absoluteIndex = this.absoluteIndex(); + var pinCount = this._pinCount++; + if (pinCount === 0) { + this.firstPinnedAbsoluteIndex = absoluteIndex; + } + + return absoluteIndex; + }; + + SlidingWindow.prototype.releaseAndUnpinAbsoluteIndex = function (absoluteIndex) { + this._pinCount--; + if (this._pinCount === 0) { + this.firstPinnedAbsoluteIndex = -1; + } + }; + + SlidingWindow.prototype.rewindToPinnedIndex = function (absoluteIndex) { + var relativeIndex = absoluteIndex - this.windowAbsoluteStartIndex; + + this.currentRelativeItemIndex = relativeIndex; + }; + + SlidingWindow.prototype.currentItem = function (argument) { + if (this.currentRelativeItemIndex >= this.windowCount) { + if (!this.addMoreItemsToWindow(argument)) { + return this.defaultValue; + } + } + + return this.window[this.currentRelativeItemIndex]; + }; + + SlidingWindow.prototype.peekItemN = function (n) { + while (this.currentRelativeItemIndex + n >= this.windowCount) { + if (!this.addMoreItemsToWindow(null)) { + return this.defaultValue; + } + } + + return this.window[this.currentRelativeItemIndex + n]; + }; + + SlidingWindow.prototype.moveToNextItem = function () { + this.currentRelativeItemIndex++; + }; + + SlidingWindow.prototype.disgardAllItemsFromCurrentIndexOnwards = function () { + this.windowCount = this.currentRelativeItemIndex; + }; + + SlidingWindow.prototype.setAbsoluteIndex = function (absoluteIndex) { + if (this.absoluteIndex() === absoluteIndex) { + return; + } + + if (this._pinCount > 0) { + } + + if (absoluteIndex >= this.windowAbsoluteStartIndex && absoluteIndex < this.windowAbsoluteEndIndex()) { + this.currentRelativeItemIndex = (absoluteIndex - this.windowAbsoluteStartIndex); + } else { + this.windowAbsoluteStartIndex = absoluteIndex; + + this.windowCount = 0; + + this.currentRelativeItemIndex = 0; + } + }; + + SlidingWindow.prototype.pinCount = function () { + return this._pinCount; + }; + return SlidingWindow; + })(); + TypeScript.SlidingWindow = SlidingWindow; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + function emptySourceUnit() { + return Syntax.normalModeFactory.sourceUnit(Syntax.emptyList, Syntax.token(10 /* EndOfFileToken */, { text: "" })); + } + Syntax.emptySourceUnit = emptySourceUnit; + + function getStandaloneExpression(positionedToken) { + var token = positionedToken.token(); + if (positionedToken !== null && positionedToken.kind() === 11 /* IdentifierName */) { + var parentPositionedNode = positionedToken.containingNode(); + var parentNode = parentPositionedNode.node(); + + if (parentNode.kind() === 121 /* QualifiedName */ && parentNode.right === token) { + return parentPositionedNode; + } else if (parentNode.kind() === 212 /* MemberAccessExpression */ && parentNode.name === token) { + return parentPositionedNode; + } + } + + return positionedToken; + } + Syntax.getStandaloneExpression = getStandaloneExpression; + + function isInModuleOrTypeContext(positionedToken) { + if (positionedToken !== null) { + var positionedNodeOrToken = Syntax.getStandaloneExpression(positionedToken); + var parent = positionedNodeOrToken.containingNode(); + + if (parent !== null) { + switch (parent.kind()) { + case 246 /* ModuleNameModuleReference */: + return true; + case 121 /* QualifiedName */: + return true; + default: + return isInTypeOnlyContext(positionedToken); + } + } + } + + return false; + } + Syntax.isInModuleOrTypeContext = isInModuleOrTypeContext; + + function isInTypeOnlyContext(positionedToken) { + var positionedNodeOrToken = Syntax.getStandaloneExpression(positionedToken); + var positionedParent = positionedNodeOrToken.containingNode(); + + var parent = positionedParent.node(); + var nodeOrToken = positionedNodeOrToken.nodeOrToken(); + + if (parent !== null) { + switch (parent.kind()) { + case 124 /* ArrayType */: + return parent.type === nodeOrToken; + case 220 /* CastExpression */: + return parent.type === nodeOrToken; + case 244 /* TypeAnnotation */: + case 230 /* ExtendsHeritageClause */: + case 231 /* ImplementsHeritageClause */: + case 228 /* TypeArgumentList */: + return true; + } + } + + return false; + } + Syntax.isInTypeOnlyContext = isInTypeOnlyContext; + + function childOffset(parent, child) { + var offset = 0; + for (var i = 0, n = parent.childCount(); i < n; i++) { + var current = parent.childAt(i); + if (current === child) { + return offset; + } + + if (current !== null) { + offset += current.fullWidth(); + } + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.childOffset = childOffset; + + function childOffsetAt(parent, index) { + var offset = 0; + for (var i = 0; i < index; i++) { + var current = parent.childAt(i); + if (current !== null) { + offset += current.fullWidth(); + } + } + + return offset; + } + Syntax.childOffsetAt = childOffsetAt; + + function childIndex(parent, child) { + for (var i = 0, n = parent.childCount(); i < n; i++) { + var current = parent.childAt(i); + if (current === child) { + return i; + } + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.childIndex = childIndex; + + function nodeStructuralEquals(node1, node2) { + if (node1 === null) { + return node2 === null; + } + + return node1.structuralEquals(node2); + } + Syntax.nodeStructuralEquals = nodeStructuralEquals; + + function nodeOrTokenStructuralEquals(node1, node2) { + if (node1 === node2) { + return true; + } + + if (node1 === null || node2 === null) { + return false; + } + + if (node1.isToken()) { + return node2.isToken() ? tokenStructuralEquals(node1, node2) : false; + } + + return node2.isNode() ? nodeStructuralEquals(node1, node2) : false; + } + Syntax.nodeOrTokenStructuralEquals = nodeOrTokenStructuralEquals; + + function tokenStructuralEquals(token1, token2) { + if (token1 === token2) { + return true; + } + + if (token1 === null || token2 === null) { + return false; + } + + return token1.kind() === token2.kind() && token1.width() === token2.width() && token1.fullWidth() === token2.fullWidth() && token1.text() === token2.text() && Syntax.triviaListStructuralEquals(token1.leadingTrivia(), token2.leadingTrivia()) && Syntax.triviaListStructuralEquals(token1.trailingTrivia(), token2.trailingTrivia()); + } + Syntax.tokenStructuralEquals = tokenStructuralEquals; + + function triviaListStructuralEquals(triviaList1, triviaList2) { + if (triviaList1.count() !== triviaList2.count()) { + return false; + } + + for (var i = 0, n = triviaList1.count(); i < n; i++) { + if (!Syntax.triviaStructuralEquals(triviaList1.syntaxTriviaAt(i), triviaList2.syntaxTriviaAt(i))) { + return false; + } + } + + return true; + } + Syntax.triviaListStructuralEquals = triviaListStructuralEquals; + + function triviaStructuralEquals(trivia1, trivia2) { + return trivia1.kind() === trivia2.kind() && trivia1.fullWidth() === trivia2.fullWidth() && trivia1.fullText() === trivia2.fullText(); + } + Syntax.triviaStructuralEquals = triviaStructuralEquals; + + function listStructuralEquals(list1, list2) { + if (list1.childCount() !== list2.childCount()) { + return false; + } + + for (var i = 0, n = list1.childCount(); i < n; i++) { + var child1 = list1.childAt(i); + var child2 = list2.childAt(i); + + if (!Syntax.nodeOrTokenStructuralEquals(child1, child2)) { + return false; + } + } + + return true; + } + Syntax.listStructuralEquals = listStructuralEquals; + + function separatedListStructuralEquals(list1, list2) { + if (list1.childCount() !== list2.childCount()) { + return false; + } + + for (var i = 0, n = list1.childCount(); i < n; i++) { + var element1 = list1.childAt(i); + var element2 = list2.childAt(i); + if (!Syntax.nodeOrTokenStructuralEquals(element1, element2)) { + return false; + } + } + + return true; + } + Syntax.separatedListStructuralEquals = separatedListStructuralEquals; + + function elementStructuralEquals(element1, element2) { + if (element1 === element2) { + return true; + } + + if (element1 === null || element2 === null) { + return false; + } + + if (element2.kind() !== element2.kind()) { + return false; + } + + if (element1.isToken()) { + return tokenStructuralEquals(element1, element2); + } else if (element1.isNode()) { + return nodeStructuralEquals(element1, element2); + } else if (element1.isList()) { + return listStructuralEquals(element1, element2); + } else if (element1.isSeparatedList()) { + return separatedListStructuralEquals(element1, element2); + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.elementStructuralEquals = elementStructuralEquals; + + function identifierName(text, info) { + if (typeof info === "undefined") { info = null; } + return Syntax.identifier(text); + } + Syntax.identifierName = identifierName; + + function trueExpression() { + return Syntax.token(37 /* TrueKeyword */); + } + Syntax.trueExpression = trueExpression; + + function falseExpression() { + return Syntax.token(24 /* FalseKeyword */); + } + Syntax.falseExpression = falseExpression; + + function numericLiteralExpression(text) { + return Syntax.token(13 /* NumericLiteral */, { text: text }); + } + Syntax.numericLiteralExpression = numericLiteralExpression; + + function stringLiteralExpression(text) { + return Syntax.token(14 /* StringLiteral */, { text: text }); + } + Syntax.stringLiteralExpression = stringLiteralExpression; + + function isSuperInvocationExpression(node) { + return node.kind() === 213 /* InvocationExpression */ && node.expression.kind() === 50 /* SuperKeyword */; + } + Syntax.isSuperInvocationExpression = isSuperInvocationExpression; + + function isSuperInvocationExpressionStatement(node) { + return node.kind() === 149 /* ExpressionStatement */ && isSuperInvocationExpression(node.expression); + } + Syntax.isSuperInvocationExpressionStatement = isSuperInvocationExpressionStatement; + + function isSuperMemberAccessExpression(node) { + return node.kind() === 212 /* MemberAccessExpression */ && node.expression.kind() === 50 /* SuperKeyword */; + } + Syntax.isSuperMemberAccessExpression = isSuperMemberAccessExpression; + + function isSuperMemberAccessInvocationExpression(node) { + return node.kind() === 213 /* InvocationExpression */ && isSuperMemberAccessExpression(node.expression); + } + Syntax.isSuperMemberAccessInvocationExpression = isSuperMemberAccessInvocationExpression; + + function assignmentExpression(left, token, right) { + return Syntax.normalModeFactory.binaryExpression(174 /* AssignmentExpression */, left, token, right); + } + Syntax.assignmentExpression = assignmentExpression; + + function nodeHasSkippedOrMissingTokens(node) { + for (var i = 0; i < node.childCount(); i++) { + var child = node.childAt(i); + if (child !== null && child.isToken()) { + var token = child; + + if (token.hasSkippedToken() || (token.width() === 0 && token.kind() !== 10 /* EndOfFileToken */)) { + return true; + } + } + } + return false; + } + Syntax.nodeHasSkippedOrMissingTokens = nodeHasSkippedOrMissingTokens; + + function isUnterminatedStringLiteral(token) { + if (token && token.kind() === 14 /* StringLiteral */) { + var text = token.text(); + return text.length < 2 || text.charCodeAt(text.length - 1) !== text.charCodeAt(0); + } + + return false; + } + Syntax.isUnterminatedStringLiteral = isUnterminatedStringLiteral; + + function isUnterminatedMultilineCommentTrivia(trivia) { + if (trivia && trivia.kind() === 6 /* MultiLineCommentTrivia */) { + var text = trivia.fullText(); + return text.length < 4 || text.substring(text.length - 2) !== "*/"; + } + return false; + } + Syntax.isUnterminatedMultilineCommentTrivia = isUnterminatedMultilineCommentTrivia; + + function isEntirelyInsideCommentTrivia(trivia, fullStart, position) { + if (trivia && trivia.isComment() && position > fullStart) { + var end = fullStart + trivia.fullWidth(); + if (position < end) { + return true; + } else if (position === end) { + return trivia.kind() === 7 /* SingleLineCommentTrivia */ || isUnterminatedMultilineCommentTrivia(trivia); + } + } + + return false; + } + Syntax.isEntirelyInsideCommentTrivia = isEntirelyInsideCommentTrivia; + + function isEntirelyInsideComment(sourceUnit, position) { + var positionedToken = sourceUnit.findToken(position); + var fullStart = positionedToken.fullStart(); + var triviaList = null; + var lastTriviaBeforeToken = null; + + if (positionedToken.kind() === 10 /* EndOfFileToken */) { + if (positionedToken.token().hasLeadingTrivia()) { + triviaList = positionedToken.token().leadingTrivia(); + } else { + positionedToken = positionedToken.previousToken(); + if (positionedToken) { + if (positionedToken && positionedToken.token().hasTrailingTrivia()) { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + } + } + } else { + if (position <= (fullStart + positionedToken.token().leadingTriviaWidth())) { + triviaList = positionedToken.token().leadingTrivia(); + } else if (position >= (fullStart + positionedToken.token().width())) { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + } + + if (triviaList) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (position <= fullStart) { + break; + } else if (position <= fullStart + trivia.fullWidth() && trivia.isComment()) { + lastTriviaBeforeToken = trivia; + break; + } + + fullStart += trivia.fullWidth(); + } + } + + return lastTriviaBeforeToken && isEntirelyInsideCommentTrivia(lastTriviaBeforeToken, fullStart, position); + } + Syntax.isEntirelyInsideComment = isEntirelyInsideComment; + + function isEntirelyInStringOrRegularExpressionLiteral(sourceUnit, position) { + var positionedToken = sourceUnit.findToken(position); + + if (positionedToken) { + if (positionedToken.kind() === 10 /* EndOfFileToken */) { + positionedToken = positionedToken.previousToken(); + return positionedToken && positionedToken.token().trailingTriviaWidth() === 0 && isUnterminatedStringLiteral(positionedToken.token()); + } else if (position > positionedToken.start()) { + return (position < positionedToken.end() && (positionedToken.kind() === 14 /* StringLiteral */ || positionedToken.kind() === 12 /* RegularExpressionLiteral */)) || (position <= positionedToken.end() && isUnterminatedStringLiteral(positionedToken.token())); + } + } + + return false; + } + Syntax.isEntirelyInStringOrRegularExpressionLiteral = isEntirelyInStringOrRegularExpressionLiteral; + + function findSkippedTokenInTriviaList(positionedToken, position, lookInLeadingTriviaList) { + var triviaList = null; + var fullStart; + + if (lookInLeadingTriviaList) { + triviaList = positionedToken.token().leadingTrivia(); + fullStart = positionedToken.fullStart(); + } else { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + + if (triviaList && triviaList.hasSkippedToken()) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + var triviaWidth = trivia.fullWidth(); + + if (trivia.isSkippedToken() && position >= fullStart && position <= fullStart + triviaWidth) { + return new TypeScript.PositionedSkippedToken(positionedToken, trivia.skippedToken(), fullStart); + } + + fullStart += triviaWidth; + } + } + + return null; + } + + function findSkippedTokenOnLeftInTriviaList(positionedToken, position, lookInLeadingTriviaList) { + var triviaList = null; + var fullEnd; + + if (lookInLeadingTriviaList) { + triviaList = positionedToken.token().leadingTrivia(); + fullEnd = positionedToken.fullStart() + triviaList.fullWidth(); + } else { + triviaList = positionedToken.token().trailingTrivia(); + fullEnd = positionedToken.fullEnd(); + } + + if (triviaList && triviaList.hasSkippedToken()) { + for (var i = triviaList.count() - 1; i >= 0; i--) { + var trivia = triviaList.syntaxTriviaAt(i); + var triviaWidth = trivia.fullWidth(); + + if (trivia.isSkippedToken() && position >= fullEnd) { + return new TypeScript.PositionedSkippedToken(positionedToken, trivia.skippedToken(), fullEnd - triviaWidth); + } + + fullEnd -= triviaWidth; + } + } + + return null; + } + + function findSkippedTokenInLeadingTriviaList(positionedToken, position) { + return findSkippedTokenInTriviaList(positionedToken, position, true); + } + Syntax.findSkippedTokenInLeadingTriviaList = findSkippedTokenInLeadingTriviaList; + + function findSkippedTokenInTrailingTriviaList(positionedToken, position) { + return findSkippedTokenInTriviaList(positionedToken, position, false); + } + Syntax.findSkippedTokenInTrailingTriviaList = findSkippedTokenInTrailingTriviaList; + + function findSkippedTokenInPositionedToken(positionedToken, position) { + var positionInLeadingTriviaList = (position < positionedToken.start()); + return findSkippedTokenInTriviaList(positionedToken, position, positionInLeadingTriviaList); + } + Syntax.findSkippedTokenInPositionedToken = findSkippedTokenInPositionedToken; + + function findSkippedTokenOnLeft(positionedToken, position) { + var positionInLeadingTriviaList = (position < positionedToken.start()); + return findSkippedTokenOnLeftInTriviaList(positionedToken, position, positionInLeadingTriviaList); + } + Syntax.findSkippedTokenOnLeft = findSkippedTokenOnLeft; + + function getAncestorOfKind(positionedToken, kind) { + while (positionedToken && positionedToken.parent()) { + if (positionedToken.parent().kind() === kind) { + return positionedToken.parent(); + } + + positionedToken = positionedToken.parent(); + } + + return null; + } + Syntax.getAncestorOfKind = getAncestorOfKind; + + function hasAncestorOfKind(positionedToken, kind) { + return Syntax.getAncestorOfKind(positionedToken, kind) !== null; + } + Syntax.hasAncestorOfKind = hasAncestorOfKind; + + function isIntegerLiteral(expression) { + if (expression) { + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + expression = expression.operand; + return expression.isToken() && TypeScript.IntegerUtilities.isInteger(expression.text()); + + case 13 /* NumericLiteral */: + var text = expression.text(); + return TypeScript.IntegerUtilities.isInteger(text) || TypeScript.IntegerUtilities.isHexInteger(text); + } + } + + return false; + } + Syntax.isIntegerLiteral = isIntegerLiteral; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var NormalModeFactory = (function () { + function NormalModeFactory() { + } + NormalModeFactory.prototype.sourceUnit = function (moduleElements, endOfFileToken) { + return new TypeScript.SourceUnitSyntax(moduleElements, endOfFileToken, false); + }; + NormalModeFactory.prototype.externalModuleReference = function (requireKeyword, openParenToken, stringLiteral, closeParenToken) { + return new TypeScript.ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, false); + }; + NormalModeFactory.prototype.moduleNameModuleReference = function (moduleName) { + return new TypeScript.ModuleNameModuleReferenceSyntax(moduleName, false); + }; + NormalModeFactory.prototype.importDeclaration = function (modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new TypeScript.ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, false); + }; + NormalModeFactory.prototype.exportAssignment = function (exportKeyword, equalsToken, identifier, semicolonToken) { + return new TypeScript.ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.classDeclaration = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + return new TypeScript.ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.interfaceDeclaration = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + return new TypeScript.InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, false); + }; + NormalModeFactory.prototype.heritageClause = function (kind, extendsOrImplementsKeyword, typeNames) { + return new TypeScript.HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, false); + }; + NormalModeFactory.prototype.moduleDeclaration = function (modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + return new TypeScript.ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.functionDeclaration = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + return new TypeScript.FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.variableStatement = function (modifiers, variableDeclaration, semicolonToken) { + return new TypeScript.VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, false); + }; + NormalModeFactory.prototype.variableDeclaration = function (varKeyword, variableDeclarators) { + return new TypeScript.VariableDeclarationSyntax(varKeyword, variableDeclarators, false); + }; + NormalModeFactory.prototype.variableDeclarator = function (propertyName, typeAnnotation, equalsValueClause) { + return new TypeScript.VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, false); + }; + NormalModeFactory.prototype.equalsValueClause = function (equalsToken, value) { + return new TypeScript.EqualsValueClauseSyntax(equalsToken, value, false); + }; + NormalModeFactory.prototype.prefixUnaryExpression = function (kind, operatorToken, operand) { + return new TypeScript.PrefixUnaryExpressionSyntax(kind, operatorToken, operand, false); + }; + NormalModeFactory.prototype.arrayLiteralExpression = function (openBracketToken, expressions, closeBracketToken) { + return new TypeScript.ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, false); + }; + NormalModeFactory.prototype.omittedExpression = function () { + return new TypeScript.OmittedExpressionSyntax(false); + }; + NormalModeFactory.prototype.parenthesizedExpression = function (openParenToken, expression, closeParenToken) { + return new TypeScript.ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, false); + }; + NormalModeFactory.prototype.simpleArrowFunctionExpression = function (identifier, equalsGreaterThanToken, block, expression) { + return new TypeScript.SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, false); + }; + NormalModeFactory.prototype.parenthesizedArrowFunctionExpression = function (callSignature, equalsGreaterThanToken, block, expression) { + return new TypeScript.ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, false); + }; + NormalModeFactory.prototype.qualifiedName = function (left, dotToken, right) { + return new TypeScript.QualifiedNameSyntax(left, dotToken, right, false); + }; + NormalModeFactory.prototype.typeArgumentList = function (lessThanToken, typeArguments, greaterThanToken) { + return new TypeScript.TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, false); + }; + NormalModeFactory.prototype.constructorType = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, false); + }; + NormalModeFactory.prototype.functionType = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, false); + }; + NormalModeFactory.prototype.objectType = function (openBraceToken, typeMembers, closeBraceToken) { + return new TypeScript.ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, false); + }; + NormalModeFactory.prototype.arrayType = function (type, openBracketToken, closeBracketToken) { + return new TypeScript.ArrayTypeSyntax(type, openBracketToken, closeBracketToken, false); + }; + NormalModeFactory.prototype.genericType = function (name, typeArgumentList) { + return new TypeScript.GenericTypeSyntax(name, typeArgumentList, false); + }; + NormalModeFactory.prototype.typeQuery = function (typeOfKeyword, name) { + return new TypeScript.TypeQuerySyntax(typeOfKeyword, name, false); + }; + NormalModeFactory.prototype.typeAnnotation = function (colonToken, type) { + return new TypeScript.TypeAnnotationSyntax(colonToken, type, false); + }; + NormalModeFactory.prototype.block = function (openBraceToken, statements, closeBraceToken) { + return new TypeScript.BlockSyntax(openBraceToken, statements, closeBraceToken, false); + }; + NormalModeFactory.prototype.parameter = function (dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + return new TypeScript.ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, false); + }; + NormalModeFactory.prototype.memberAccessExpression = function (expression, dotToken, name) { + return new TypeScript.MemberAccessExpressionSyntax(expression, dotToken, name, false); + }; + NormalModeFactory.prototype.postfixUnaryExpression = function (kind, operand, operatorToken) { + return new TypeScript.PostfixUnaryExpressionSyntax(kind, operand, operatorToken, false); + }; + NormalModeFactory.prototype.elementAccessExpression = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + return new TypeScript.ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, false); + }; + NormalModeFactory.prototype.invocationExpression = function (expression, argumentList) { + return new TypeScript.InvocationExpressionSyntax(expression, argumentList, false); + }; + NormalModeFactory.prototype.argumentList = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + return new TypeScript.ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, false); + }; + NormalModeFactory.prototype.binaryExpression = function (kind, left, operatorToken, right) { + return new TypeScript.BinaryExpressionSyntax(kind, left, operatorToken, right, false); + }; + NormalModeFactory.prototype.conditionalExpression = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + return new TypeScript.ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, false); + }; + NormalModeFactory.prototype.constructSignature = function (newKeyword, callSignature) { + return new TypeScript.ConstructSignatureSyntax(newKeyword, callSignature, false); + }; + NormalModeFactory.prototype.methodSignature = function (propertyName, questionToken, callSignature) { + return new TypeScript.MethodSignatureSyntax(propertyName, questionToken, callSignature, false); + }; + NormalModeFactory.prototype.indexSignature = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + return new TypeScript.IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, false); + }; + NormalModeFactory.prototype.propertySignature = function (propertyName, questionToken, typeAnnotation) { + return new TypeScript.PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, false); + }; + NormalModeFactory.prototype.callSignature = function (typeParameterList, parameterList, typeAnnotation) { + return new TypeScript.CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, false); + }; + NormalModeFactory.prototype.parameterList = function (openParenToken, parameters, closeParenToken) { + return new TypeScript.ParameterListSyntax(openParenToken, parameters, closeParenToken, false); + }; + NormalModeFactory.prototype.typeParameterList = function (lessThanToken, typeParameters, greaterThanToken) { + return new TypeScript.TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, false); + }; + NormalModeFactory.prototype.typeParameter = function (identifier, constraint) { + return new TypeScript.TypeParameterSyntax(identifier, constraint, false); + }; + NormalModeFactory.prototype.constraint = function (extendsKeyword, type) { + return new TypeScript.ConstraintSyntax(extendsKeyword, type, false); + }; + NormalModeFactory.prototype.elseClause = function (elseKeyword, statement) { + return new TypeScript.ElseClauseSyntax(elseKeyword, statement, false); + }; + NormalModeFactory.prototype.ifStatement = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + return new TypeScript.IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, false); + }; + NormalModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { + return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, false); + }; + NormalModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { + return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.getAccessor = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + return new TypeScript.GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, false); + }; + NormalModeFactory.prototype.setAccessor = function (modifiers, setKeyword, propertyName, parameterList, block) { + return new TypeScript.SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, false); + }; + NormalModeFactory.prototype.memberVariableDeclaration = function (modifiers, variableDeclarator, semicolonToken) { + return new TypeScript.MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, false); + }; + NormalModeFactory.prototype.indexMemberDeclaration = function (modifiers, indexSignature, semicolonToken) { + return new TypeScript.IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, false); + }; + NormalModeFactory.prototype.throwStatement = function (throwKeyword, expression, semicolonToken) { + return new TypeScript.ThrowStatementSyntax(throwKeyword, expression, semicolonToken, false); + }; + NormalModeFactory.prototype.returnStatement = function (returnKeyword, expression, semicolonToken) { + return new TypeScript.ReturnStatementSyntax(returnKeyword, expression, semicolonToken, false); + }; + NormalModeFactory.prototype.objectCreationExpression = function (newKeyword, expression, argumentList) { + return new TypeScript.ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, false); + }; + NormalModeFactory.prototype.switchStatement = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + return new TypeScript.SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, false); + }; + NormalModeFactory.prototype.caseSwitchClause = function (caseKeyword, expression, colonToken, statements) { + return new TypeScript.CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, false); + }; + NormalModeFactory.prototype.defaultSwitchClause = function (defaultKeyword, colonToken, statements) { + return new TypeScript.DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, false); + }; + NormalModeFactory.prototype.breakStatement = function (breakKeyword, identifier, semicolonToken) { + return new TypeScript.BreakStatementSyntax(breakKeyword, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.continueStatement = function (continueKeyword, identifier, semicolonToken) { + return new TypeScript.ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.forStatement = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + return new TypeScript.ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.forInStatement = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + return new TypeScript.ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.whileStatement = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.withStatement = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.enumDeclaration = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + return new TypeScript.EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.enumElement = function (propertyName, equalsValueClause) { + return new TypeScript.EnumElementSyntax(propertyName, equalsValueClause, false); + }; + NormalModeFactory.prototype.castExpression = function (lessThanToken, type, greaterThanToken, expression) { + return new TypeScript.CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, false); + }; + NormalModeFactory.prototype.objectLiteralExpression = function (openBraceToken, propertyAssignments, closeBraceToken) { + return new TypeScript.ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, false); + }; + NormalModeFactory.prototype.simplePropertyAssignment = function (propertyName, colonToken, expression) { + return new TypeScript.SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, false); + }; + NormalModeFactory.prototype.functionPropertyAssignment = function (propertyName, callSignature, block) { + return new TypeScript.FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, false); + }; + NormalModeFactory.prototype.functionExpression = function (functionKeyword, identifier, callSignature, block) { + return new TypeScript.FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, false); + }; + NormalModeFactory.prototype.emptyStatement = function (semicolonToken) { + return new TypeScript.EmptyStatementSyntax(semicolonToken, false); + }; + NormalModeFactory.prototype.tryStatement = function (tryKeyword, block, catchClause, finallyClause) { + return new TypeScript.TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, false); + }; + NormalModeFactory.prototype.catchClause = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + return new TypeScript.CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, false); + }; + NormalModeFactory.prototype.finallyClause = function (finallyKeyword, block) { + return new TypeScript.FinallyClauseSyntax(finallyKeyword, block, false); + }; + NormalModeFactory.prototype.labeledStatement = function (identifier, colonToken, statement) { + return new TypeScript.LabeledStatementSyntax(identifier, colonToken, statement, false); + }; + NormalModeFactory.prototype.doStatement = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + return new TypeScript.DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, false); + }; + NormalModeFactory.prototype.typeOfExpression = function (typeOfKeyword, expression) { + return new TypeScript.TypeOfExpressionSyntax(typeOfKeyword, expression, false); + }; + NormalModeFactory.prototype.deleteExpression = function (deleteKeyword, expression) { + return new TypeScript.DeleteExpressionSyntax(deleteKeyword, expression, false); + }; + NormalModeFactory.prototype.voidExpression = function (voidKeyword, expression) { + return new TypeScript.VoidExpressionSyntax(voidKeyword, expression, false); + }; + NormalModeFactory.prototype.debuggerStatement = function (debuggerKeyword, semicolonToken) { + return new TypeScript.DebuggerStatementSyntax(debuggerKeyword, semicolonToken, false); + }; + return NormalModeFactory; + })(); + Syntax.NormalModeFactory = NormalModeFactory; + + var StrictModeFactory = (function () { + function StrictModeFactory() { + } + StrictModeFactory.prototype.sourceUnit = function (moduleElements, endOfFileToken) { + return new TypeScript.SourceUnitSyntax(moduleElements, endOfFileToken, true); + }; + StrictModeFactory.prototype.externalModuleReference = function (requireKeyword, openParenToken, stringLiteral, closeParenToken) { + return new TypeScript.ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, true); + }; + StrictModeFactory.prototype.moduleNameModuleReference = function (moduleName) { + return new TypeScript.ModuleNameModuleReferenceSyntax(moduleName, true); + }; + StrictModeFactory.prototype.importDeclaration = function (modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new TypeScript.ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, true); + }; + StrictModeFactory.prototype.exportAssignment = function (exportKeyword, equalsToken, identifier, semicolonToken) { + return new TypeScript.ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.classDeclaration = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + return new TypeScript.ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.interfaceDeclaration = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + return new TypeScript.InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, true); + }; + StrictModeFactory.prototype.heritageClause = function (kind, extendsOrImplementsKeyword, typeNames) { + return new TypeScript.HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, true); + }; + StrictModeFactory.prototype.moduleDeclaration = function (modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + return new TypeScript.ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.functionDeclaration = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + return new TypeScript.FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.variableStatement = function (modifiers, variableDeclaration, semicolonToken) { + return new TypeScript.VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, true); + }; + StrictModeFactory.prototype.variableDeclaration = function (varKeyword, variableDeclarators) { + return new TypeScript.VariableDeclarationSyntax(varKeyword, variableDeclarators, true); + }; + StrictModeFactory.prototype.variableDeclarator = function (propertyName, typeAnnotation, equalsValueClause) { + return new TypeScript.VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, true); + }; + StrictModeFactory.prototype.equalsValueClause = function (equalsToken, value) { + return new TypeScript.EqualsValueClauseSyntax(equalsToken, value, true); + }; + StrictModeFactory.prototype.prefixUnaryExpression = function (kind, operatorToken, operand) { + return new TypeScript.PrefixUnaryExpressionSyntax(kind, operatorToken, operand, true); + }; + StrictModeFactory.prototype.arrayLiteralExpression = function (openBracketToken, expressions, closeBracketToken) { + return new TypeScript.ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, true); + }; + StrictModeFactory.prototype.omittedExpression = function () { + return new TypeScript.OmittedExpressionSyntax(true); + }; + StrictModeFactory.prototype.parenthesizedExpression = function (openParenToken, expression, closeParenToken) { + return new TypeScript.ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, true); + }; + StrictModeFactory.prototype.simpleArrowFunctionExpression = function (identifier, equalsGreaterThanToken, block, expression) { + return new TypeScript.SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, true); + }; + StrictModeFactory.prototype.parenthesizedArrowFunctionExpression = function (callSignature, equalsGreaterThanToken, block, expression) { + return new TypeScript.ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, true); + }; + StrictModeFactory.prototype.qualifiedName = function (left, dotToken, right) { + return new TypeScript.QualifiedNameSyntax(left, dotToken, right, true); + }; + StrictModeFactory.prototype.typeArgumentList = function (lessThanToken, typeArguments, greaterThanToken) { + return new TypeScript.TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, true); + }; + StrictModeFactory.prototype.constructorType = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, true); + }; + StrictModeFactory.prototype.functionType = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, true); + }; + StrictModeFactory.prototype.objectType = function (openBraceToken, typeMembers, closeBraceToken) { + return new TypeScript.ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, true); + }; + StrictModeFactory.prototype.arrayType = function (type, openBracketToken, closeBracketToken) { + return new TypeScript.ArrayTypeSyntax(type, openBracketToken, closeBracketToken, true); + }; + StrictModeFactory.prototype.genericType = function (name, typeArgumentList) { + return new TypeScript.GenericTypeSyntax(name, typeArgumentList, true); + }; + StrictModeFactory.prototype.typeQuery = function (typeOfKeyword, name) { + return new TypeScript.TypeQuerySyntax(typeOfKeyword, name, true); + }; + StrictModeFactory.prototype.typeAnnotation = function (colonToken, type) { + return new TypeScript.TypeAnnotationSyntax(colonToken, type, true); + }; + StrictModeFactory.prototype.block = function (openBraceToken, statements, closeBraceToken) { + return new TypeScript.BlockSyntax(openBraceToken, statements, closeBraceToken, true); + }; + StrictModeFactory.prototype.parameter = function (dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + return new TypeScript.ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, true); + }; + StrictModeFactory.prototype.memberAccessExpression = function (expression, dotToken, name) { + return new TypeScript.MemberAccessExpressionSyntax(expression, dotToken, name, true); + }; + StrictModeFactory.prototype.postfixUnaryExpression = function (kind, operand, operatorToken) { + return new TypeScript.PostfixUnaryExpressionSyntax(kind, operand, operatorToken, true); + }; + StrictModeFactory.prototype.elementAccessExpression = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + return new TypeScript.ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, true); + }; + StrictModeFactory.prototype.invocationExpression = function (expression, argumentList) { + return new TypeScript.InvocationExpressionSyntax(expression, argumentList, true); + }; + StrictModeFactory.prototype.argumentList = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + return new TypeScript.ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, true); + }; + StrictModeFactory.prototype.binaryExpression = function (kind, left, operatorToken, right) { + return new TypeScript.BinaryExpressionSyntax(kind, left, operatorToken, right, true); + }; + StrictModeFactory.prototype.conditionalExpression = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + return new TypeScript.ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, true); + }; + StrictModeFactory.prototype.constructSignature = function (newKeyword, callSignature) { + return new TypeScript.ConstructSignatureSyntax(newKeyword, callSignature, true); + }; + StrictModeFactory.prototype.methodSignature = function (propertyName, questionToken, callSignature) { + return new TypeScript.MethodSignatureSyntax(propertyName, questionToken, callSignature, true); + }; + StrictModeFactory.prototype.indexSignature = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + return new TypeScript.IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, true); + }; + StrictModeFactory.prototype.propertySignature = function (propertyName, questionToken, typeAnnotation) { + return new TypeScript.PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, true); + }; + StrictModeFactory.prototype.callSignature = function (typeParameterList, parameterList, typeAnnotation) { + return new TypeScript.CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, true); + }; + StrictModeFactory.prototype.parameterList = function (openParenToken, parameters, closeParenToken) { + return new TypeScript.ParameterListSyntax(openParenToken, parameters, closeParenToken, true); + }; + StrictModeFactory.prototype.typeParameterList = function (lessThanToken, typeParameters, greaterThanToken) { + return new TypeScript.TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, true); + }; + StrictModeFactory.prototype.typeParameter = function (identifier, constraint) { + return new TypeScript.TypeParameterSyntax(identifier, constraint, true); + }; + StrictModeFactory.prototype.constraint = function (extendsKeyword, type) { + return new TypeScript.ConstraintSyntax(extendsKeyword, type, true); + }; + StrictModeFactory.prototype.elseClause = function (elseKeyword, statement) { + return new TypeScript.ElseClauseSyntax(elseKeyword, statement, true); + }; + StrictModeFactory.prototype.ifStatement = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + return new TypeScript.IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, true); + }; + StrictModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { + return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, true); + }; + StrictModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { + return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.getAccessor = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + return new TypeScript.GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, true); + }; + StrictModeFactory.prototype.setAccessor = function (modifiers, setKeyword, propertyName, parameterList, block) { + return new TypeScript.SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, true); + }; + StrictModeFactory.prototype.memberVariableDeclaration = function (modifiers, variableDeclarator, semicolonToken) { + return new TypeScript.MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, true); + }; + StrictModeFactory.prototype.indexMemberDeclaration = function (modifiers, indexSignature, semicolonToken) { + return new TypeScript.IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, true); + }; + StrictModeFactory.prototype.throwStatement = function (throwKeyword, expression, semicolonToken) { + return new TypeScript.ThrowStatementSyntax(throwKeyword, expression, semicolonToken, true); + }; + StrictModeFactory.prototype.returnStatement = function (returnKeyword, expression, semicolonToken) { + return new TypeScript.ReturnStatementSyntax(returnKeyword, expression, semicolonToken, true); + }; + StrictModeFactory.prototype.objectCreationExpression = function (newKeyword, expression, argumentList) { + return new TypeScript.ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, true); + }; + StrictModeFactory.prototype.switchStatement = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + return new TypeScript.SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, true); + }; + StrictModeFactory.prototype.caseSwitchClause = function (caseKeyword, expression, colonToken, statements) { + return new TypeScript.CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, true); + }; + StrictModeFactory.prototype.defaultSwitchClause = function (defaultKeyword, colonToken, statements) { + return new TypeScript.DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, true); + }; + StrictModeFactory.prototype.breakStatement = function (breakKeyword, identifier, semicolonToken) { + return new TypeScript.BreakStatementSyntax(breakKeyword, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.continueStatement = function (continueKeyword, identifier, semicolonToken) { + return new TypeScript.ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.forStatement = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + return new TypeScript.ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.forInStatement = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + return new TypeScript.ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.whileStatement = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.withStatement = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.enumDeclaration = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + return new TypeScript.EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.enumElement = function (propertyName, equalsValueClause) { + return new TypeScript.EnumElementSyntax(propertyName, equalsValueClause, true); + }; + StrictModeFactory.prototype.castExpression = function (lessThanToken, type, greaterThanToken, expression) { + return new TypeScript.CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, true); + }; + StrictModeFactory.prototype.objectLiteralExpression = function (openBraceToken, propertyAssignments, closeBraceToken) { + return new TypeScript.ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, true); + }; + StrictModeFactory.prototype.simplePropertyAssignment = function (propertyName, colonToken, expression) { + return new TypeScript.SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, true); + }; + StrictModeFactory.prototype.functionPropertyAssignment = function (propertyName, callSignature, block) { + return new TypeScript.FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, true); + }; + StrictModeFactory.prototype.functionExpression = function (functionKeyword, identifier, callSignature, block) { + return new TypeScript.FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, true); + }; + StrictModeFactory.prototype.emptyStatement = function (semicolonToken) { + return new TypeScript.EmptyStatementSyntax(semicolonToken, true); + }; + StrictModeFactory.prototype.tryStatement = function (tryKeyword, block, catchClause, finallyClause) { + return new TypeScript.TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, true); + }; + StrictModeFactory.prototype.catchClause = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + return new TypeScript.CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, true); + }; + StrictModeFactory.prototype.finallyClause = function (finallyKeyword, block) { + return new TypeScript.FinallyClauseSyntax(finallyKeyword, block, true); + }; + StrictModeFactory.prototype.labeledStatement = function (identifier, colonToken, statement) { + return new TypeScript.LabeledStatementSyntax(identifier, colonToken, statement, true); + }; + StrictModeFactory.prototype.doStatement = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + return new TypeScript.DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, true); + }; + StrictModeFactory.prototype.typeOfExpression = function (typeOfKeyword, expression) { + return new TypeScript.TypeOfExpressionSyntax(typeOfKeyword, expression, true); + }; + StrictModeFactory.prototype.deleteExpression = function (deleteKeyword, expression) { + return new TypeScript.DeleteExpressionSyntax(deleteKeyword, expression, true); + }; + StrictModeFactory.prototype.voidExpression = function (voidKeyword, expression) { + return new TypeScript.VoidExpressionSyntax(voidKeyword, expression, true); + }; + StrictModeFactory.prototype.debuggerStatement = function (debuggerKeyword, semicolonToken) { + return new TypeScript.DebuggerStatementSyntax(debuggerKeyword, semicolonToken, true); + }; + return StrictModeFactory; + })(); + Syntax.StrictModeFactory = StrictModeFactory; + + Syntax.normalModeFactory = new NormalModeFactory(); + Syntax.strictModeFactory = new StrictModeFactory(); + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxFacts) { + function isDirectivePrologueElement(node) { + if (node.kind() === 149 /* ExpressionStatement */) { + var expressionStatement = node; + var expression = expressionStatement.expression; + + if (expression.kind() === 14 /* StringLiteral */) { + return true; + } + } + + return false; + } + SyntaxFacts.isDirectivePrologueElement = isDirectivePrologueElement; + + function isUseStrictDirective(node) { + var expressionStatement = node; + var stringLiteral = expressionStatement.expression; + + var text = stringLiteral.text(); + return text === '"use strict"' || text === "'use strict'"; + } + SyntaxFacts.isUseStrictDirective = isUseStrictDirective; + + function isIdentifierNameOrAnyKeyword(token) { + var tokenKind = token.tokenKind; + return tokenKind === 11 /* IdentifierName */ || SyntaxFacts.isAnyKeyword(tokenKind); + } + SyntaxFacts.isIdentifierNameOrAnyKeyword = isIdentifierNameOrAnyKeyword; + })(TypeScript.SyntaxFacts || (TypeScript.SyntaxFacts = {})); + var SyntaxFacts = TypeScript.SyntaxFacts; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var EmptySyntaxList = (function () { + function EmptySyntaxList() { + } + EmptySyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + EmptySyntaxList.prototype.isNode = function () { + return false; + }; + EmptySyntaxList.prototype.isToken = function () { + return false; + }; + EmptySyntaxList.prototype.isList = function () { + return true; + }; + EmptySyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + EmptySyntaxList.prototype.toJSON = function (key) { + return []; + }; + + EmptySyntaxList.prototype.childCount = function () { + return 0; + }; + + EmptySyntaxList.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySyntaxList.prototype.toArray = function () { + return []; + }; + + EmptySyntaxList.prototype.collectTextElements = function (elements) { + }; + + EmptySyntaxList.prototype.firstToken = function () { + return null; + }; + + EmptySyntaxList.prototype.lastToken = function () { + return null; + }; + + EmptySyntaxList.prototype.fullWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.width = function () { + return 0; + }; + + EmptySyntaxList.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySyntaxList.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySyntaxList.prototype.leadingTriviaWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.trailingTriviaWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.fullText = function () { + return ""; + }; + + EmptySyntaxList.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptySyntaxList.prototype.isIncrementallyUnusable = function () { + return false; + }; + + EmptySyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + throw TypeScript.Errors.invalidOperation(); + }; + + EmptySyntaxList.prototype.insertChildrenInto = function (array, index) { + }; + return EmptySyntaxList; + })(); + Syntax.EmptySyntaxList = EmptySyntaxList; + + Syntax.emptyList = new EmptySyntaxList(); + + var SingletonSyntaxList = (function () { + function SingletonSyntaxList(item) { + this.item = item; + } + SingletonSyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + SingletonSyntaxList.prototype.isToken = function () { + return false; + }; + SingletonSyntaxList.prototype.isNode = function () { + return false; + }; + SingletonSyntaxList.prototype.isList = function () { + return true; + }; + SingletonSyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + SingletonSyntaxList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSyntaxList.prototype.childCount = function () { + return 1; + }; + + SingletonSyntaxList.prototype.childAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSyntaxList.prototype.toArray = function () { + return [this.item]; + }; + + SingletonSyntaxList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSyntaxList.prototype.firstToken = function () { + return this.item.firstToken(); + }; + + SingletonSyntaxList.prototype.lastToken = function () { + return this.item.lastToken(); + }; + + SingletonSyntaxList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSyntaxList.prototype.width = function () { + return this.item.width(); + }; + + SingletonSyntaxList.prototype.leadingTrivia = function () { + return this.item.leadingTrivia(); + }; + + SingletonSyntaxList.prototype.trailingTrivia = function () { + return this.item.trailingTrivia(); + }; + + SingletonSyntaxList.prototype.leadingTriviaWidth = function () { + return this.item.leadingTriviaWidth(); + }; + + SingletonSyntaxList.prototype.trailingTriviaWidth = function () { + return this.item.trailingTriviaWidth(); + }; + + SingletonSyntaxList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSyntaxList.prototype.isTypeScriptSpecific = function () { + return this.item.isTypeScriptSpecific(); + }; + + SingletonSyntaxList.prototype.isIncrementallyUnusable = function () { + return this.item.isIncrementallyUnusable(); + }; + + SingletonSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + return this.item.findTokenInternal(new TypeScript.PositionedList(parent, this, fullStart), position, fullStart); + }; + + SingletonSyntaxList.prototype.insertChildrenInto = function (array, index) { + array.splice(index, 0, this.item); + }; + return SingletonSyntaxList; + })(); + + var NormalSyntaxList = (function () { + function NormalSyntaxList(nodeOrTokens) { + this._data = 0; + this.nodeOrTokens = nodeOrTokens; + } + NormalSyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + NormalSyntaxList.prototype.isNode = function () { + return false; + }; + NormalSyntaxList.prototype.isToken = function () { + return false; + }; + NormalSyntaxList.prototype.isList = function () { + return true; + }; + NormalSyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + NormalSyntaxList.prototype.toJSON = function (key) { + return this.nodeOrTokens; + }; + + NormalSyntaxList.prototype.childCount = function () { + return this.nodeOrTokens.length; + }; + + NormalSyntaxList.prototype.childAt = function (index) { + if (index < 0 || index >= this.nodeOrTokens.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.nodeOrTokens[index]; + }; + + NormalSyntaxList.prototype.toArray = function () { + return this.nodeOrTokens.slice(0); + }; + + NormalSyntaxList.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var element = this.nodeOrTokens[i]; + element.collectTextElements(elements); + } + }; + + NormalSyntaxList.prototype.firstToken = function () { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var token = this.nodeOrTokens[i].firstToken(); + if (token !== null) { + return token; + } + } + + return null; + }; + + NormalSyntaxList.prototype.lastToken = function () { + for (var i = this.nodeOrTokens.length - 1; i >= 0; i--) { + var token = this.nodeOrTokens[i].lastToken(); + if (token !== null) { + return token; + } + } + + return null; + }; + + NormalSyntaxList.prototype.fullText = function () { + var elements = new Array(); + this.collectTextElements(elements); + return elements.join(""); + }; + + NormalSyntaxList.prototype.isTypeScriptSpecific = function () { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + if (this.nodeOrTokens[i].isTypeScriptSpecific()) { + return true; + } + } + + return false; + }; + + NormalSyntaxList.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + NormalSyntaxList.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + NormalSyntaxList.prototype.width = function () { + var fullWidth = this.fullWidth(); + return fullWidth - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + NormalSyntaxList.prototype.leadingTrivia = function () { + return this.firstToken().leadingTrivia(); + }; + + NormalSyntaxList.prototype.trailingTrivia = function () { + return this.lastToken().trailingTrivia(); + }; + + NormalSyntaxList.prototype.leadingTriviaWidth = function () { + return this.firstToken().leadingTriviaWidth(); + }; + + NormalSyntaxList.prototype.trailingTriviaWidth = function () { + return this.lastToken().trailingTriviaWidth(); + }; + + NormalSyntaxList.prototype.computeData = function () { + var fullWidth = 0; + var isIncrementallyUnusable = false; + + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var node = this.nodeOrTokens[i]; + fullWidth += node.fullWidth(); + isIncrementallyUnusable = isIncrementallyUnusable || node.isIncrementallyUnusable(); + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + NormalSyntaxList.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data = this.computeData(); + } + + return this._data; + }; + + NormalSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedList(parent, this, fullStart); + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var nodeOrToken = this.nodeOrTokens[i]; + + var childWidth = nodeOrToken.fullWidth(); + if (position < childWidth) { + return nodeOrToken.findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + NormalSyntaxList.prototype.insertChildrenInto = function (array, index) { + if (index === 0) { + array.unshift.apply(array, this.nodeOrTokens); + } else { + array.splice.apply(array, [index, 0].concat(this.nodeOrTokens)); + } + }; + return NormalSyntaxList; + })(); + + function list(nodes) { + if (nodes === undefined || nodes === null || nodes.length === 0) { + return Syntax.emptyList; + } + + if (nodes.length === 1) { + var item = nodes[0]; + return new SingletonSyntaxList(item); + } + + return new NormalSyntaxList(nodes); + } + Syntax.list = list; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxNode = (function () { + function SyntaxNode(parsedInStrictMode) { + this._data = parsedInStrictMode ? 4 /* NodeParsedInStrictModeMask */ : 0; + } + SyntaxNode.prototype.isNode = function () { + return true; + }; + SyntaxNode.prototype.isToken = function () { + return false; + }; + SyntaxNode.prototype.isList = function () { + return false; + }; + SyntaxNode.prototype.isSeparatedList = function () { + return false; + }; + + SyntaxNode.prototype.kind = function () { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.childCount = function () { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.childAt = function (slot) { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.firstToken = function () { + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + if (element.fullWidth() > 0 || element.kind() === 10 /* EndOfFileToken */) { + return element.firstToken(); + } + } + } + + return null; + }; + + SyntaxNode.prototype.lastToken = function () { + for (var i = this.childCount() - 1; i >= 0; i--) { + var element = this.childAt(i); + + if (element !== null) { + if (element.fullWidth() > 0 || element.kind() === 10 /* EndOfFileToken */) { + return element.lastToken(); + } + } + } + + return null; + }; + + SyntaxNode.prototype.insertChildrenInto = function (array, index) { + for (var i = this.childCount() - 1; i >= 0; i--) { + var element = this.childAt(i); + + if (element !== null) { + if (element.isNode() || element.isToken()) { + array.splice(index, 0, element); + } else if (element.isList()) { + element.insertChildrenInto(array, index); + } else if (element.isSeparatedList()) { + element.insertChildrenInto(array, index); + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + } + }; + + SyntaxNode.prototype.leadingTrivia = function () { + var firstToken = this.firstToken(); + return firstToken ? firstToken.leadingTrivia() : TypeScript.Syntax.emptyTriviaList; + }; + + SyntaxNode.prototype.trailingTrivia = function () { + var lastToken = this.lastToken(); + return lastToken ? lastToken.trailingTrivia() : TypeScript.Syntax.emptyTriviaList; + }; + + SyntaxNode.prototype.toJSON = function (key) { + var result = { + kind: TypeScript.SyntaxKind[this.kind()], + fullWidth: this.fullWidth() + }; + + if (this.isIncrementallyUnusable()) { + result.isIncrementallyUnusable = true; + } + + if (this.parsedInStrictMode()) { + result.parsedInStrictMode = true; + } + + var thisAsIndexable = this; + for (var i = 0, n = this.childCount(); i < n; i++) { + var value = this.childAt(i); + + if (value) { + for (var name in this) { + if (value === thisAsIndexable[name]) { + result[name] = value; + break; + } + } + } + } + + return result; + }; + + SyntaxNode.prototype.accept = function (visitor) { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.fullText = function () { + var elements = []; + this.collectTextElements(elements); + return elements.join(""); + }; + + SyntaxNode.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + element.collectTextElements(elements); + } + } + }; + + SyntaxNode.prototype.replaceToken = function (token1, token2) { + if (token1 === token2) { + return this; + } + + return this.accept(new TypeScript.SyntaxTokenReplacer(token1, token2)); + }; + + SyntaxNode.prototype.withLeadingTrivia = function (trivia) { + return this.replaceToken(this.firstToken(), this.firstToken().withLeadingTrivia(trivia)); + }; + + SyntaxNode.prototype.withTrailingTrivia = function (trivia) { + return this.replaceToken(this.lastToken(), this.lastToken().withTrailingTrivia(trivia)); + }; + + SyntaxNode.prototype.hasLeadingTrivia = function () { + return this.lastToken().hasLeadingTrivia(); + }; + + SyntaxNode.prototype.hasTrailingTrivia = function () { + return this.lastToken().hasTrailingTrivia(); + }; + + SyntaxNode.prototype.isTypeScriptSpecific = function () { + return false; + }; + + SyntaxNode.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + SyntaxNode.prototype.parsedInStrictMode = function () { + return (this.data() & 4 /* NodeParsedInStrictModeMask */) !== 0; + }; + + SyntaxNode.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + SyntaxNode.prototype.computeData = function () { + var slotCount = this.childCount(); + + var fullWidth = 0; + var childWidth = 0; + + var isIncrementallyUnusable = ((this._data & 2 /* NodeIncrementallyUnusableMask */) !== 0) || slotCount === 0; + + for (var i = 0, n = slotCount; i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + childWidth = element.fullWidth(); + fullWidth += childWidth; + + if (!isIncrementallyUnusable) { + isIncrementallyUnusable = element.isIncrementallyUnusable(); + } + } + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + SyntaxNode.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data |= this.computeData(); + } + + return this._data; + }; + + SyntaxNode.prototype.findToken = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var endOfFileToken = this.tryGetEndOfFileAt(position); + if (endOfFileToken !== null) { + return endOfFileToken; + } + + if (position < 0 || position >= this.fullWidth()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var positionedToken = this.findTokenInternal(null, position, 0); + + if (includeSkippedTokens) { + return TypeScript.Syntax.findSkippedTokenInPositionedToken(positionedToken, position) || positionedToken; + } + + return positionedToken; + }; + + SyntaxNode.prototype.tryGetEndOfFileAt = function (position) { + if (this.kind() === 120 /* SourceUnit */ && position === this.fullWidth()) { + var sourceUnit = this; + return new TypeScript.PositionedToken(new TypeScript.PositionedNode(null, sourceUnit, 0), sourceUnit.endOfFileToken, sourceUnit.moduleElements.fullWidth()); + } + + return null; + }; + + SyntaxNode.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedNode(parent, this, fullStart); + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + var childWidth = element.fullWidth(); + + if (position < childWidth) { + return element.findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + } + + throw TypeScript.Errors.invalidOperation(); + }; + + SyntaxNode.prototype.findTokenOnLeft = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var positionedToken = this.findToken(position, false); + var start = positionedToken.start(); + + if (includeSkippedTokens) { + positionedToken = TypeScript.Syntax.findSkippedTokenOnLeft(positionedToken, position) || positionedToken; + } + + if (position > start) { + return positionedToken; + } + + if (positionedToken.fullStart() === 0) { + return null; + } + + return positionedToken.previousToken(includeSkippedTokens); + }; + + SyntaxNode.prototype.findCompleteTokenOnLeft = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var positionedToken = this.findToken(position, false); + + if (includeSkippedTokens) { + positionedToken = TypeScript.Syntax.findSkippedTokenOnLeft(positionedToken, position) || positionedToken; + } + + if (positionedToken.token().width() > 0 && position >= positionedToken.end()) { + return positionedToken; + } + + return positionedToken.previousToken(includeSkippedTokens); + }; + + SyntaxNode.prototype.isModuleElement = function () { + return false; + }; + + SyntaxNode.prototype.isClassElement = function () { + return false; + }; + + SyntaxNode.prototype.isTypeMember = function () { + return false; + }; + + SyntaxNode.prototype.isStatement = function () { + return false; + }; + + SyntaxNode.prototype.isExpression = function () { + return false; + }; + + SyntaxNode.prototype.isSwitchClause = function () { + return false; + }; + + SyntaxNode.prototype.structuralEquals = function (node) { + if (this === node) { + return true; + } + if (node === null) { + return false; + } + if (this.kind() !== node.kind()) { + return false; + } + + for (var i = 0, n = this.childCount(); i < n; i++) { + var element1 = this.childAt(i); + var element2 = node.childAt(i); + + if (!TypeScript.Syntax.elementStructuralEquals(element1, element2)) { + return false; + } + } + + return true; + }; + + SyntaxNode.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + SyntaxNode.prototype.leadingTriviaWidth = function () { + var firstToken = this.firstToken(); + return firstToken === null ? 0 : firstToken.leadingTriviaWidth(); + }; + + SyntaxNode.prototype.trailingTriviaWidth = function () { + var lastToken = this.lastToken(); + return lastToken === null ? 0 : lastToken.trailingTriviaWidth(); + }; + return SyntaxNode; + })(); + TypeScript.SyntaxNode = SyntaxNode; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceUnitSyntax = (function (_super) { + __extends(SourceUnitSyntax, _super); + function SourceUnitSyntax(moduleElements, endOfFileToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.moduleElements = moduleElements; + this.endOfFileToken = endOfFileToken; + } + SourceUnitSyntax.prototype.accept = function (visitor) { + return visitor.visitSourceUnit(this); + }; + + SourceUnitSyntax.prototype.kind = function () { + return 120 /* SourceUnit */; + }; + + SourceUnitSyntax.prototype.childCount = function () { + return 2; + }; + + SourceUnitSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.moduleElements; + case 1: + return this.endOfFileToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SourceUnitSyntax.prototype.update = function (moduleElements, endOfFileToken) { + if (this.moduleElements === moduleElements && this.endOfFileToken === endOfFileToken) { + return this; + } + + return new SourceUnitSyntax(moduleElements, endOfFileToken, this.parsedInStrictMode()); + }; + + SourceUnitSyntax.create = function (endOfFileToken) { + return new SourceUnitSyntax(TypeScript.Syntax.emptyList, endOfFileToken, false); + }; + + SourceUnitSyntax.create1 = function (endOfFileToken) { + return new SourceUnitSyntax(TypeScript.Syntax.emptyList, endOfFileToken, false); + }; + + SourceUnitSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SourceUnitSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SourceUnitSyntax.prototype.withModuleElements = function (moduleElements) { + return this.update(moduleElements, this.endOfFileToken); + }; + + SourceUnitSyntax.prototype.withModuleElement = function (moduleElement) { + return this.withModuleElements(TypeScript.Syntax.list([moduleElement])); + }; + + SourceUnitSyntax.prototype.withEndOfFileToken = function (endOfFileToken) { + return this.update(this.moduleElements, endOfFileToken); + }; + + SourceUnitSyntax.prototype.isTypeScriptSpecific = function () { + if (this.moduleElements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SourceUnitSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SourceUnitSyntax = SourceUnitSyntax; + + var ExternalModuleReferenceSyntax = (function (_super) { + __extends(ExternalModuleReferenceSyntax, _super); + function ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.requireKeyword = requireKeyword; + this.openParenToken = openParenToken; + this.stringLiteral = stringLiteral; + this.closeParenToken = closeParenToken; + } + ExternalModuleReferenceSyntax.prototype.accept = function (visitor) { + return visitor.visitExternalModuleReference(this); + }; + + ExternalModuleReferenceSyntax.prototype.kind = function () { + return 245 /* ExternalModuleReference */; + }; + + ExternalModuleReferenceSyntax.prototype.childCount = function () { + return 4; + }; + + ExternalModuleReferenceSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.requireKeyword; + case 1: + return this.openParenToken; + case 2: + return this.stringLiteral; + case 3: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExternalModuleReferenceSyntax.prototype.isModuleReference = function () { + return true; + }; + + ExternalModuleReferenceSyntax.prototype.update = function (requireKeyword, openParenToken, stringLiteral, closeParenToken) { + if (this.requireKeyword === requireKeyword && this.openParenToken === openParenToken && this.stringLiteral === stringLiteral && this.closeParenToken === closeParenToken) { + return this; + } + + return new ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, this.parsedInStrictMode()); + }; + + ExternalModuleReferenceSyntax.create1 = function (stringLiteral) { + return new ExternalModuleReferenceSyntax(TypeScript.Syntax.token(66 /* RequireKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), stringLiteral, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ExternalModuleReferenceSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExternalModuleReferenceSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExternalModuleReferenceSyntax.prototype.withRequireKeyword = function (requireKeyword) { + return this.update(requireKeyword, this.openParenToken, this.stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.requireKeyword, openParenToken, this.stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withStringLiteral = function (stringLiteral) { + return this.update(this.requireKeyword, this.openParenToken, stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.requireKeyword, this.openParenToken, this.stringLiteral, closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ExternalModuleReferenceSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExternalModuleReferenceSyntax = ExternalModuleReferenceSyntax; + + var ModuleNameModuleReferenceSyntax = (function (_super) { + __extends(ModuleNameModuleReferenceSyntax, _super); + function ModuleNameModuleReferenceSyntax(moduleName, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.moduleName = moduleName; + } + ModuleNameModuleReferenceSyntax.prototype.accept = function (visitor) { + return visitor.visitModuleNameModuleReference(this); + }; + + ModuleNameModuleReferenceSyntax.prototype.kind = function () { + return 246 /* ModuleNameModuleReference */; + }; + + ModuleNameModuleReferenceSyntax.prototype.childCount = function () { + return 1; + }; + + ModuleNameModuleReferenceSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.moduleName; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ModuleNameModuleReferenceSyntax.prototype.isModuleReference = function () { + return true; + }; + + ModuleNameModuleReferenceSyntax.prototype.update = function (moduleName) { + if (this.moduleName === moduleName) { + return this; + } + + return new ModuleNameModuleReferenceSyntax(moduleName, this.parsedInStrictMode()); + }; + + ModuleNameModuleReferenceSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ModuleNameModuleReferenceSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ModuleNameModuleReferenceSyntax.prototype.withModuleName = function (moduleName) { + return this.update(moduleName); + }; + + ModuleNameModuleReferenceSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ModuleNameModuleReferenceSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ModuleNameModuleReferenceSyntax = ModuleNameModuleReferenceSyntax; + + var ImportDeclarationSyntax = (function (_super) { + __extends(ImportDeclarationSyntax, _super); + function ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.importKeyword = importKeyword; + this.identifier = identifier; + this.equalsToken = equalsToken; + this.moduleReference = moduleReference; + this.semicolonToken = semicolonToken; + } + ImportDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitImportDeclaration(this); + }; + + ImportDeclarationSyntax.prototype.kind = function () { + return 133 /* ImportDeclaration */; + }; + + ImportDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + ImportDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.importKeyword; + case 2: + return this.identifier; + case 3: + return this.equalsToken; + case 4: + return this.moduleReference; + case 5: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ImportDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ImportDeclarationSyntax.prototype.update = function (modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + if (this.modifiers === modifiers && this.importKeyword === importKeyword && this.identifier === identifier && this.equalsToken === equalsToken && this.moduleReference === moduleReference && this.semicolonToken === semicolonToken) { + return this; + } + + return new ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, this.parsedInStrictMode()); + }; + + ImportDeclarationSyntax.create = function (importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new ImportDeclarationSyntax(TypeScript.Syntax.emptyList, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, false); + }; + + ImportDeclarationSyntax.create1 = function (identifier, moduleReference) { + return new ImportDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(49 /* ImportKeyword */), identifier, TypeScript.Syntax.token(107 /* EqualsToken */), moduleReference, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ImportDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ImportDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ImportDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.importKeyword, this.identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ImportDeclarationSyntax.prototype.withImportKeyword = function (importKeyword) { + return this.update(this.modifiers, importKeyword, this.identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.importKeyword, identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(this.modifiers, this.importKeyword, this.identifier, equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withModuleReference = function (moduleReference) { + return this.update(this.modifiers, this.importKeyword, this.identifier, this.equalsToken, moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.importKeyword, this.identifier, this.equalsToken, this.moduleReference, semicolonToken); + }; + + ImportDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ImportDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ImportDeclarationSyntax = ImportDeclarationSyntax; + + var ExportAssignmentSyntax = (function (_super) { + __extends(ExportAssignmentSyntax, _super); + function ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.exportKeyword = exportKeyword; + this.equalsToken = equalsToken; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + ExportAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitExportAssignment(this); + }; + + ExportAssignmentSyntax.prototype.kind = function () { + return 134 /* ExportAssignment */; + }; + + ExportAssignmentSyntax.prototype.childCount = function () { + return 4; + }; + + ExportAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.exportKeyword; + case 1: + return this.equalsToken; + case 2: + return this.identifier; + case 3: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExportAssignmentSyntax.prototype.isModuleElement = function () { + return true; + }; + + ExportAssignmentSyntax.prototype.update = function (exportKeyword, equalsToken, identifier, semicolonToken) { + if (this.exportKeyword === exportKeyword && this.equalsToken === equalsToken && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + ExportAssignmentSyntax.create1 = function (identifier) { + return new ExportAssignmentSyntax(TypeScript.Syntax.token(47 /* ExportKeyword */), TypeScript.Syntax.token(107 /* EqualsToken */), identifier, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ExportAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExportAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExportAssignmentSyntax.prototype.withExportKeyword = function (exportKeyword) { + return this.update(exportKeyword, this.equalsToken, this.identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(this.exportKeyword, equalsToken, this.identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.exportKeyword, this.equalsToken, identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.exportKeyword, this.equalsToken, this.identifier, semicolonToken); + }; + + ExportAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ExportAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExportAssignmentSyntax = ExportAssignmentSyntax; + + var ClassDeclarationSyntax = (function (_super) { + __extends(ClassDeclarationSyntax, _super); + function ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.classKeyword = classKeyword; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.openBraceToken = openBraceToken; + this.classElements = classElements; + this.closeBraceToken = closeBraceToken; + } + ClassDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitClassDeclaration(this); + }; + + ClassDeclarationSyntax.prototype.kind = function () { + return 131 /* ClassDeclaration */; + }; + + ClassDeclarationSyntax.prototype.childCount = function () { + return 8; + }; + + ClassDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.classKeyword; + case 2: + return this.identifier; + case 3: + return this.typeParameterList; + case 4: + return this.heritageClauses; + case 5: + return this.openBraceToken; + case 6: + return this.classElements; + case 7: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ClassDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ClassDeclarationSyntax.prototype.update = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + if (this.modifiers === modifiers && this.classKeyword === classKeyword && this.identifier === identifier && this.typeParameterList === typeParameterList && this.heritageClauses === heritageClauses && this.openBraceToken === openBraceToken && this.classElements === classElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, this.parsedInStrictMode()); + }; + + ClassDeclarationSyntax.create = function (classKeyword, identifier, openBraceToken, closeBraceToken) { + return new ClassDeclarationSyntax(TypeScript.Syntax.emptyList, classKeyword, identifier, null, TypeScript.Syntax.emptyList, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + ClassDeclarationSyntax.create1 = function (identifier) { + return new ClassDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(44 /* ClassKeyword */), identifier, null, TypeScript.Syntax.emptyList, TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ClassDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ClassDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ClassDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ClassDeclarationSyntax.prototype.withClassKeyword = function (classKeyword) { + return this.update(this.modifiers, classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.classKeyword, identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.modifiers, this.classKeyword, this.identifier, typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withHeritageClauses = function (heritageClauses) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withHeritageClause = function (heritageClause) { + return this.withHeritageClauses(TypeScript.Syntax.list([heritageClause])); + }; + + ClassDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withClassElements = function (classElements) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withClassElement = function (classElement) { + return this.withClassElements(TypeScript.Syntax.list([classElement])); + }; + + ClassDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ClassDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ClassDeclarationSyntax = ClassDeclarationSyntax; + + var InterfaceDeclarationSyntax = (function (_super) { + __extends(InterfaceDeclarationSyntax, _super); + function InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.interfaceKeyword = interfaceKeyword; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.body = body; + } + InterfaceDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitInterfaceDeclaration(this); + }; + + InterfaceDeclarationSyntax.prototype.kind = function () { + return 128 /* InterfaceDeclaration */; + }; + + InterfaceDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + InterfaceDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.interfaceKeyword; + case 2: + return this.identifier; + case 3: + return this.typeParameterList; + case 4: + return this.heritageClauses; + case 5: + return this.body; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + InterfaceDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + InterfaceDeclarationSyntax.prototype.update = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + if (this.modifiers === modifiers && this.interfaceKeyword === interfaceKeyword && this.identifier === identifier && this.typeParameterList === typeParameterList && this.heritageClauses === heritageClauses && this.body === body) { + return this; + } + + return new InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, this.parsedInStrictMode()); + }; + + InterfaceDeclarationSyntax.create = function (interfaceKeyword, identifier, body) { + return new InterfaceDeclarationSyntax(TypeScript.Syntax.emptyList, interfaceKeyword, identifier, null, TypeScript.Syntax.emptyList, body, false); + }; + + InterfaceDeclarationSyntax.create1 = function (identifier) { + return new InterfaceDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(52 /* InterfaceKeyword */), identifier, null, TypeScript.Syntax.emptyList, ObjectTypeSyntax.create1(), false); + }; + + InterfaceDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + InterfaceDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + InterfaceDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + InterfaceDeclarationSyntax.prototype.withInterfaceKeyword = function (interfaceKeyword) { + return this.update(this.modifiers, interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.interfaceKeyword, identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withHeritageClauses = function (heritageClauses) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withHeritageClause = function (heritageClause) { + return this.withHeritageClauses(TypeScript.Syntax.list([heritageClause])); + }; + + InterfaceDeclarationSyntax.prototype.withBody = function (body) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, body); + }; + + InterfaceDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return InterfaceDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.InterfaceDeclarationSyntax = InterfaceDeclarationSyntax; + + var HeritageClauseSyntax = (function (_super) { + __extends(HeritageClauseSyntax, _super); + function HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.extendsOrImplementsKeyword = extendsOrImplementsKeyword; + this.typeNames = typeNames; + + this._kind = kind; + } + HeritageClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitHeritageClause(this); + }; + + HeritageClauseSyntax.prototype.childCount = function () { + return 2; + }; + + HeritageClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.extendsOrImplementsKeyword; + case 1: + return this.typeNames; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + HeritageClauseSyntax.prototype.kind = function () { + return this._kind; + }; + + HeritageClauseSyntax.prototype.update = function (kind, extendsOrImplementsKeyword, typeNames) { + if (this._kind === kind && this.extendsOrImplementsKeyword === extendsOrImplementsKeyword && this.typeNames === typeNames) { + return this; + } + + return new HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, this.parsedInStrictMode()); + }; + + HeritageClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + HeritageClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + HeritageClauseSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.extendsOrImplementsKeyword, this.typeNames); + }; + + HeritageClauseSyntax.prototype.withExtendsOrImplementsKeyword = function (extendsOrImplementsKeyword) { + return this.update(this._kind, extendsOrImplementsKeyword, this.typeNames); + }; + + HeritageClauseSyntax.prototype.withTypeNames = function (typeNames) { + return this.update(this._kind, this.extendsOrImplementsKeyword, typeNames); + }; + + HeritageClauseSyntax.prototype.withTypeName = function (typeName) { + return this.withTypeNames(TypeScript.Syntax.separatedList([typeName])); + }; + + HeritageClauseSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return HeritageClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.HeritageClauseSyntax = HeritageClauseSyntax; + + var ModuleDeclarationSyntax = (function (_super) { + __extends(ModuleDeclarationSyntax, _super); + function ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.moduleKeyword = moduleKeyword; + this.name = name; + this.stringLiteral = stringLiteral; + this.openBraceToken = openBraceToken; + this.moduleElements = moduleElements; + this.closeBraceToken = closeBraceToken; + } + ModuleDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitModuleDeclaration(this); + }; + + ModuleDeclarationSyntax.prototype.kind = function () { + return 130 /* ModuleDeclaration */; + }; + + ModuleDeclarationSyntax.prototype.childCount = function () { + return 7; + }; + + ModuleDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.moduleKeyword; + case 2: + return this.name; + case 3: + return this.stringLiteral; + case 4: + return this.openBraceToken; + case 5: + return this.moduleElements; + case 6: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ModuleDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ModuleDeclarationSyntax.prototype.update = function (modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + if (this.modifiers === modifiers && this.moduleKeyword === moduleKeyword && this.name === name && this.stringLiteral === stringLiteral && this.openBraceToken === openBraceToken && this.moduleElements === moduleElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, this.parsedInStrictMode()); + }; + + ModuleDeclarationSyntax.create = function (moduleKeyword, openBraceToken, closeBraceToken) { + return new ModuleDeclarationSyntax(TypeScript.Syntax.emptyList, moduleKeyword, null, null, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + ModuleDeclarationSyntax.create1 = function () { + return new ModuleDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(65 /* ModuleKeyword */), null, null, TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ModuleDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ModuleDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ModuleDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ModuleDeclarationSyntax.prototype.withModuleKeyword = function (moduleKeyword) { + return this.update(this.modifiers, moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withName = function (name) { + return this.update(this.modifiers, this.moduleKeyword, name, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withStringLiteral = function (stringLiteral) { + return this.update(this.modifiers, this.moduleKeyword, this.name, stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.moduleKeyword, this.name, this.stringLiteral, openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModuleElements = function (moduleElements) { + return this.update(this.modifiers, this.moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModuleElement = function (moduleElement) { + return this.withModuleElements(TypeScript.Syntax.list([moduleElement])); + }; + + ModuleDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, this.moduleElements, closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ModuleDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ModuleDeclarationSyntax = ModuleDeclarationSyntax; + + var FunctionDeclarationSyntax = (function (_super) { + __extends(FunctionDeclarationSyntax, _super); + function FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.functionKeyword = functionKeyword; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + FunctionDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionDeclaration(this); + }; + + FunctionDeclarationSyntax.prototype.kind = function () { + return 129 /* FunctionDeclaration */; + }; + + FunctionDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + FunctionDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.functionKeyword; + case 2: + return this.identifier; + case 3: + return this.callSignature; + case 4: + return this.block; + case 5: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionDeclarationSyntax.prototype.isStatement = function () { + return true; + }; + + FunctionDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + FunctionDeclarationSyntax.prototype.update = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.functionKeyword === functionKeyword && this.identifier === identifier && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + FunctionDeclarationSyntax.create = function (functionKeyword, identifier, callSignature) { + return new FunctionDeclarationSyntax(TypeScript.Syntax.emptyList, functionKeyword, identifier, callSignature, null, null, false); + }; + + FunctionDeclarationSyntax.create1 = function (identifier) { + return new FunctionDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(27 /* FunctionKeyword */), identifier, CallSignatureSyntax.create1(), null, null, false); + }; + + FunctionDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.functionKeyword, this.identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + FunctionDeclarationSyntax.prototype.withFunctionKeyword = function (functionKeyword) { + return this.update(this.modifiers, functionKeyword, this.identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.functionKeyword, identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, this.callSignature, block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, this.callSignature, this.block, semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.childCount() > 0) { + return true; + } + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block !== null && this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionDeclarationSyntax = FunctionDeclarationSyntax; + + var VariableStatementSyntax = (function (_super) { + __extends(VariableStatementSyntax, _super); + function VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.variableDeclaration = variableDeclaration; + this.semicolonToken = semicolonToken; + } + VariableStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableStatement(this); + }; + + VariableStatementSyntax.prototype.kind = function () { + return 148 /* VariableStatement */; + }; + + VariableStatementSyntax.prototype.childCount = function () { + return 3; + }; + + VariableStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.variableDeclaration; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableStatementSyntax.prototype.isStatement = function () { + return true; + }; + + VariableStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + VariableStatementSyntax.prototype.update = function (modifiers, variableDeclaration, semicolonToken) { + if (this.modifiers === modifiers && this.variableDeclaration === variableDeclaration && this.semicolonToken === semicolonToken) { + return this; + } + + return new VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, this.parsedInStrictMode()); + }; + + VariableStatementSyntax.create = function (variableDeclaration, semicolonToken) { + return new VariableStatementSyntax(TypeScript.Syntax.emptyList, variableDeclaration, semicolonToken, false); + }; + + VariableStatementSyntax.create1 = function (variableDeclaration) { + return new VariableStatementSyntax(TypeScript.Syntax.emptyList, variableDeclaration, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + VariableStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableStatementSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.variableDeclaration, this.semicolonToken); + }; + + VariableStatementSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + VariableStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.modifiers, variableDeclaration, this.semicolonToken); + }; + + VariableStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.variableDeclaration, semicolonToken); + }; + + VariableStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.childCount() > 0) { + return true; + } + if (this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableStatementSyntax = VariableStatementSyntax; + + var VariableDeclarationSyntax = (function (_super) { + __extends(VariableDeclarationSyntax, _super); + function VariableDeclarationSyntax(varKeyword, variableDeclarators, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.varKeyword = varKeyword; + this.variableDeclarators = variableDeclarators; + } + VariableDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableDeclaration(this); + }; + + VariableDeclarationSyntax.prototype.kind = function () { + return 224 /* VariableDeclaration */; + }; + + VariableDeclarationSyntax.prototype.childCount = function () { + return 2; + }; + + VariableDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.varKeyword; + case 1: + return this.variableDeclarators; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableDeclarationSyntax.prototype.update = function (varKeyword, variableDeclarators) { + if (this.varKeyword === varKeyword && this.variableDeclarators === variableDeclarators) { + return this; + } + + return new VariableDeclarationSyntax(varKeyword, variableDeclarators, this.parsedInStrictMode()); + }; + + VariableDeclarationSyntax.create1 = function (variableDeclarators) { + return new VariableDeclarationSyntax(TypeScript.Syntax.token(40 /* VarKeyword */), variableDeclarators, false); + }; + + VariableDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableDeclarationSyntax.prototype.withVarKeyword = function (varKeyword) { + return this.update(varKeyword, this.variableDeclarators); + }; + + VariableDeclarationSyntax.prototype.withVariableDeclarators = function (variableDeclarators) { + return this.update(this.varKeyword, variableDeclarators); + }; + + VariableDeclarationSyntax.prototype.withVariableDeclarator = function (variableDeclarator) { + return this.withVariableDeclarators(TypeScript.Syntax.separatedList([variableDeclarator])); + }; + + VariableDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclarators.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableDeclarationSyntax = VariableDeclarationSyntax; + + var VariableDeclaratorSyntax = (function (_super) { + __extends(VariableDeclaratorSyntax, _super); + function VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + } + VariableDeclaratorSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableDeclarator(this); + }; + + VariableDeclaratorSyntax.prototype.kind = function () { + return 225 /* VariableDeclarator */; + }; + + VariableDeclaratorSyntax.prototype.childCount = function () { + return 3; + }; + + VariableDeclaratorSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.typeAnnotation; + case 2: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableDeclaratorSyntax.prototype.update = function (propertyName, typeAnnotation, equalsValueClause) { + if (this.propertyName === propertyName && this.typeAnnotation === typeAnnotation && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, this.parsedInStrictMode()); + }; + + VariableDeclaratorSyntax.create = function (propertyName) { + return new VariableDeclaratorSyntax(propertyName, null, null, false); + }; + + VariableDeclaratorSyntax.create1 = function (propertyName) { + return new VariableDeclaratorSyntax(propertyName, null, null, false); + }; + + VariableDeclaratorSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableDeclaratorSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableDeclaratorSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.typeAnnotation, this.equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.propertyName, typeAnnotation, this.equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.propertyName, this.typeAnnotation, equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeAnnotation !== null) { + return true; + } + if (this.equalsValueClause !== null && this.equalsValueClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableDeclaratorSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableDeclaratorSyntax = VariableDeclaratorSyntax; + + var EqualsValueClauseSyntax = (function (_super) { + __extends(EqualsValueClauseSyntax, _super); + function EqualsValueClauseSyntax(equalsToken, value, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.equalsToken = equalsToken; + this.value = value; + } + EqualsValueClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitEqualsValueClause(this); + }; + + EqualsValueClauseSyntax.prototype.kind = function () { + return 232 /* EqualsValueClause */; + }; + + EqualsValueClauseSyntax.prototype.childCount = function () { + return 2; + }; + + EqualsValueClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.equalsToken; + case 1: + return this.value; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EqualsValueClauseSyntax.prototype.update = function (equalsToken, value) { + if (this.equalsToken === equalsToken && this.value === value) { + return this; + } + + return new EqualsValueClauseSyntax(equalsToken, value, this.parsedInStrictMode()); + }; + + EqualsValueClauseSyntax.create1 = function (value) { + return new EqualsValueClauseSyntax(TypeScript.Syntax.token(107 /* EqualsToken */), value, false); + }; + + EqualsValueClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EqualsValueClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EqualsValueClauseSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(equalsToken, this.value); + }; + + EqualsValueClauseSyntax.prototype.withValue = function (value) { + return this.update(this.equalsToken, value); + }; + + EqualsValueClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.value.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return EqualsValueClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EqualsValueClauseSyntax = EqualsValueClauseSyntax; + + var PrefixUnaryExpressionSyntax = (function (_super) { + __extends(PrefixUnaryExpressionSyntax, _super); + function PrefixUnaryExpressionSyntax(kind, operatorToken, operand, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.operatorToken = operatorToken; + this.operand = operand; + + this._kind = kind; + } + PrefixUnaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitPrefixUnaryExpression(this); + }; + + PrefixUnaryExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + PrefixUnaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.operatorToken; + case 1: + return this.operand; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PrefixUnaryExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + PrefixUnaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + PrefixUnaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + PrefixUnaryExpressionSyntax.prototype.update = function (kind, operatorToken, operand) { + if (this._kind === kind && this.operatorToken === operatorToken && this.operand === operand) { + return this; + } + + return new PrefixUnaryExpressionSyntax(kind, operatorToken, operand, this.parsedInStrictMode()); + }; + + PrefixUnaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PrefixUnaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PrefixUnaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.operatorToken, this.operand); + }; + + PrefixUnaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, operatorToken, this.operand); + }; + + PrefixUnaryExpressionSyntax.prototype.withOperand = function (operand) { + return this.update(this._kind, this.operatorToken, operand); + }; + + PrefixUnaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.operand.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return PrefixUnaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PrefixUnaryExpressionSyntax = PrefixUnaryExpressionSyntax; + + var ArrayLiteralExpressionSyntax = (function (_super) { + __extends(ArrayLiteralExpressionSyntax, _super); + function ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBracketToken = openBracketToken; + this.expressions = expressions; + this.closeBracketToken = closeBracketToken; + } + ArrayLiteralExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitArrayLiteralExpression(this); + }; + + ArrayLiteralExpressionSyntax.prototype.kind = function () { + return 214 /* ArrayLiteralExpression */; + }; + + ArrayLiteralExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ArrayLiteralExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBracketToken; + case 1: + return this.expressions; + case 2: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArrayLiteralExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.update = function (openBracketToken, expressions, closeBracketToken) { + if (this.openBracketToken === openBracketToken && this.expressions === expressions && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, this.parsedInStrictMode()); + }; + + ArrayLiteralExpressionSyntax.create = function (openBracketToken, closeBracketToken) { + return new ArrayLiteralExpressionSyntax(openBracketToken, TypeScript.Syntax.emptySeparatedList, closeBracketToken, false); + }; + + ArrayLiteralExpressionSyntax.create1 = function () { + return new ArrayLiteralExpressionSyntax(TypeScript.Syntax.token(74 /* OpenBracketToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(75 /* CloseBracketToken */), false); + }; + + ArrayLiteralExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArrayLiteralExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArrayLiteralExpressionSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(openBracketToken, this.expressions, this.closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.withExpressions = function (expressions) { + return this.update(this.openBracketToken, expressions, this.closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.withExpression = function (expression) { + return this.withExpressions(TypeScript.Syntax.separatedList([expression])); + }; + + ArrayLiteralExpressionSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.openBracketToken, this.expressions, closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expressions.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ArrayLiteralExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArrayLiteralExpressionSyntax = ArrayLiteralExpressionSyntax; + + var OmittedExpressionSyntax = (function (_super) { + __extends(OmittedExpressionSyntax, _super); + function OmittedExpressionSyntax(parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + } + OmittedExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitOmittedExpression(this); + }; + + OmittedExpressionSyntax.prototype.kind = function () { + return 223 /* OmittedExpression */; + }; + + OmittedExpressionSyntax.prototype.childCount = function () { + return 0; + }; + + OmittedExpressionSyntax.prototype.childAt = function (slot) { + throw TypeScript.Errors.invalidOperation(); + }; + + OmittedExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + OmittedExpressionSyntax.prototype.update = function () { + return this; + }; + + OmittedExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + OmittedExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + OmittedExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return OmittedExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.OmittedExpressionSyntax = OmittedExpressionSyntax; + + var ParenthesizedExpressionSyntax = (function (_super) { + __extends(ParenthesizedExpressionSyntax, _super); + function ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openParenToken = openParenToken; + this.expression = expression; + this.closeParenToken = closeParenToken; + } + ParenthesizedExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitParenthesizedExpression(this); + }; + + ParenthesizedExpressionSyntax.prototype.kind = function () { + return 217 /* ParenthesizedExpression */; + }; + + ParenthesizedExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ParenthesizedExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openParenToken; + case 1: + return this.expression; + case 2: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParenthesizedExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.update = function (openParenToken, expression, closeParenToken) { + if (this.openParenToken === openParenToken && this.expression === expression && this.closeParenToken === closeParenToken) { + return this; + } + + return new ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, this.parsedInStrictMode()); + }; + + ParenthesizedExpressionSyntax.create1 = function (expression) { + return new ParenthesizedExpressionSyntax(TypeScript.Syntax.token(72 /* OpenParenToken */), expression, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ParenthesizedExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParenthesizedExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParenthesizedExpressionSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(openParenToken, this.expression, this.closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.openParenToken, expression, this.closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.openParenToken, this.expression, closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ParenthesizedExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParenthesizedExpressionSyntax = ParenthesizedExpressionSyntax; + + var SimpleArrowFunctionExpressionSyntax = (function (_super) { + __extends(SimpleArrowFunctionExpressionSyntax, _super); + function SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.block = block; + this.expression = expression; + } + SimpleArrowFunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitSimpleArrowFunctionExpression(this); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.kind = function () { + return 219 /* SimpleArrowFunctionExpression */; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.equalsGreaterThanToken; + case 2: + return this.block; + case 3: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isArrowFunctionExpression = function () { + return true; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.update = function (identifier, equalsGreaterThanToken, block, expression) { + if (this.identifier === identifier && this.equalsGreaterThanToken === equalsGreaterThanToken && this.block === block && this.expression === expression) { + return this; + } + + return new SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, this.parsedInStrictMode()); + }; + + SimpleArrowFunctionExpressionSyntax.create = function (identifier, equalsGreaterThanToken) { + return new SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, null, null, false); + }; + + SimpleArrowFunctionExpressionSyntax.create1 = function (identifier) { + return new SimpleArrowFunctionExpressionSyntax(identifier, TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), null, null, false); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.equalsGreaterThanToken, this.block, this.expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.identifier, equalsGreaterThanToken, this.block, this.expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withBlock = function (block) { + return this.update(this.identifier, this.equalsGreaterThanToken, block, this.expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.identifier, this.equalsGreaterThanToken, this.block, expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return SimpleArrowFunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SimpleArrowFunctionExpressionSyntax = SimpleArrowFunctionExpressionSyntax; + + var ParenthesizedArrowFunctionExpressionSyntax = (function (_super) { + __extends(ParenthesizedArrowFunctionExpressionSyntax, _super); + function ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.callSignature = callSignature; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.block = block; + this.expression = expression; + } + ParenthesizedArrowFunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitParenthesizedArrowFunctionExpression(this); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.kind = function () { + return 218 /* ParenthesizedArrowFunctionExpression */; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.callSignature; + case 1: + return this.equalsGreaterThanToken; + case 2: + return this.block; + case 3: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isArrowFunctionExpression = function () { + return true; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.update = function (callSignature, equalsGreaterThanToken, block, expression) { + if (this.callSignature === callSignature && this.equalsGreaterThanToken === equalsGreaterThanToken && this.block === block && this.expression === expression) { + return this; + } + + return new ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, this.parsedInStrictMode()); + }; + + ParenthesizedArrowFunctionExpressionSyntax.create = function (callSignature, equalsGreaterThanToken) { + return new ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, null, null, false); + }; + + ParenthesizedArrowFunctionExpressionSyntax.create1 = function () { + return new ParenthesizedArrowFunctionExpressionSyntax(CallSignatureSyntax.create1(), TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), null, null, false); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(callSignature, this.equalsGreaterThanToken, this.block, this.expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.callSignature, equalsGreaterThanToken, this.block, this.expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withBlock = function (block) { + return this.update(this.callSignature, this.equalsGreaterThanToken, block, this.expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.callSignature, this.equalsGreaterThanToken, this.block, expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ParenthesizedArrowFunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParenthesizedArrowFunctionExpressionSyntax = ParenthesizedArrowFunctionExpressionSyntax; + + var QualifiedNameSyntax = (function (_super) { + __extends(QualifiedNameSyntax, _super); + function QualifiedNameSyntax(left, dotToken, right, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.left = left; + this.dotToken = dotToken; + this.right = right; + } + QualifiedNameSyntax.prototype.accept = function (visitor) { + return visitor.visitQualifiedName(this); + }; + + QualifiedNameSyntax.prototype.kind = function () { + return 121 /* QualifiedName */; + }; + + QualifiedNameSyntax.prototype.childCount = function () { + return 3; + }; + + QualifiedNameSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.left; + case 1: + return this.dotToken; + case 2: + return this.right; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + QualifiedNameSyntax.prototype.isName = function () { + return true; + }; + + QualifiedNameSyntax.prototype.isType = function () { + return true; + }; + + QualifiedNameSyntax.prototype.update = function (left, dotToken, right) { + if (this.left === left && this.dotToken === dotToken && this.right === right) { + return this; + } + + return new QualifiedNameSyntax(left, dotToken, right, this.parsedInStrictMode()); + }; + + QualifiedNameSyntax.create1 = function (left, right) { + return new QualifiedNameSyntax(left, TypeScript.Syntax.token(76 /* DotToken */), right, false); + }; + + QualifiedNameSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + QualifiedNameSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + QualifiedNameSyntax.prototype.withLeft = function (left) { + return this.update(left, this.dotToken, this.right); + }; + + QualifiedNameSyntax.prototype.withDotToken = function (dotToken) { + return this.update(this.left, dotToken, this.right); + }; + + QualifiedNameSyntax.prototype.withRight = function (right) { + return this.update(this.left, this.dotToken, right); + }; + + QualifiedNameSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return QualifiedNameSyntax; + })(TypeScript.SyntaxNode); + TypeScript.QualifiedNameSyntax = QualifiedNameSyntax; + + var TypeArgumentListSyntax = (function (_super) { + __extends(TypeArgumentListSyntax, _super); + function TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.typeArguments = typeArguments; + this.greaterThanToken = greaterThanToken; + } + TypeArgumentListSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeArgumentList(this); + }; + + TypeArgumentListSyntax.prototype.kind = function () { + return 228 /* TypeArgumentList */; + }; + + TypeArgumentListSyntax.prototype.childCount = function () { + return 3; + }; + + TypeArgumentListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.typeArguments; + case 2: + return this.greaterThanToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeArgumentListSyntax.prototype.update = function (lessThanToken, typeArguments, greaterThanToken) { + if (this.lessThanToken === lessThanToken && this.typeArguments === typeArguments && this.greaterThanToken === greaterThanToken) { + return this; + } + + return new TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, this.parsedInStrictMode()); + }; + + TypeArgumentListSyntax.create = function (lessThanToken, greaterThanToken) { + return new TypeArgumentListSyntax(lessThanToken, TypeScript.Syntax.emptySeparatedList, greaterThanToken, false); + }; + + TypeArgumentListSyntax.create1 = function () { + return new TypeArgumentListSyntax(TypeScript.Syntax.token(80 /* LessThanToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(81 /* GreaterThanToken */), false); + }; + + TypeArgumentListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeArgumentListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeArgumentListSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.typeArguments, this.greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.withTypeArguments = function (typeArguments) { + return this.update(this.lessThanToken, typeArguments, this.greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.withTypeArgument = function (typeArgument) { + return this.withTypeArguments(TypeScript.Syntax.separatedList([typeArgument])); + }; + + TypeArgumentListSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.typeArguments, greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeArgumentListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeArgumentListSyntax = TypeArgumentListSyntax; + + var ConstructorTypeSyntax = (function (_super) { + __extends(ConstructorTypeSyntax, _super); + function ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.type = type; + } + ConstructorTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructorType(this); + }; + + ConstructorTypeSyntax.prototype.kind = function () { + return 125 /* ConstructorType */; + }; + + ConstructorTypeSyntax.prototype.childCount = function () { + return 5; + }; + + ConstructorTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.typeParameterList; + case 2: + return this.parameterList; + case 3: + return this.equalsGreaterThanToken; + case 4: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructorTypeSyntax.prototype.isType = function () { + return true; + }; + + ConstructorTypeSyntax.prototype.update = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + if (this.newKeyword === newKeyword && this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.equalsGreaterThanToken === equalsGreaterThanToken && this.type === type) { + return this; + } + + return new ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, this.parsedInStrictMode()); + }; + + ConstructorTypeSyntax.create = function (newKeyword, parameterList, equalsGreaterThanToken, type) { + return new ConstructorTypeSyntax(newKeyword, null, parameterList, equalsGreaterThanToken, type, false); + }; + + ConstructorTypeSyntax.create1 = function (type) { + return new ConstructorTypeSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), null, ParameterListSyntax.create1(), TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), type, false); + }; + + ConstructorTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructorTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructorTypeSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.newKeyword, typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.newKeyword, this.typeParameterList, parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.newKeyword, this.typeParameterList, this.parameterList, equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withType = function (type) { + return this.update(this.newKeyword, this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, type); + }; + + ConstructorTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructorTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructorTypeSyntax = ConstructorTypeSyntax; + + var FunctionTypeSyntax = (function (_super) { + __extends(FunctionTypeSyntax, _super); + function FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.type = type; + } + FunctionTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionType(this); + }; + + FunctionTypeSyntax.prototype.kind = function () { + return 123 /* FunctionType */; + }; + + FunctionTypeSyntax.prototype.childCount = function () { + return 4; + }; + + FunctionTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeParameterList; + case 1: + return this.parameterList; + case 2: + return this.equalsGreaterThanToken; + case 3: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionTypeSyntax.prototype.isType = function () { + return true; + }; + + FunctionTypeSyntax.prototype.update = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + if (this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.equalsGreaterThanToken === equalsGreaterThanToken && this.type === type) { + return this; + } + + return new FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, this.parsedInStrictMode()); + }; + + FunctionTypeSyntax.create = function (parameterList, equalsGreaterThanToken, type) { + return new FunctionTypeSyntax(null, parameterList, equalsGreaterThanToken, type, false); + }; + + FunctionTypeSyntax.create1 = function (type) { + return new FunctionTypeSyntax(null, ParameterListSyntax.create1(), TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), type, false); + }; + + FunctionTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionTypeSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.typeParameterList, parameterList, this.equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.typeParameterList, this.parameterList, equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withType = function (type) { + return this.update(this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, type); + }; + + FunctionTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return FunctionTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionTypeSyntax = FunctionTypeSyntax; + + var ObjectTypeSyntax = (function (_super) { + __extends(ObjectTypeSyntax, _super); + function ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.typeMembers = typeMembers; + this.closeBraceToken = closeBraceToken; + } + ObjectTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectType(this); + }; + + ObjectTypeSyntax.prototype.kind = function () { + return 122 /* ObjectType */; + }; + + ObjectTypeSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.typeMembers; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectTypeSyntax.prototype.isType = function () { + return true; + }; + + ObjectTypeSyntax.prototype.update = function (openBraceToken, typeMembers, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.typeMembers === typeMembers && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, this.parsedInStrictMode()); + }; + + ObjectTypeSyntax.create = function (openBraceToken, closeBraceToken) { + return new ObjectTypeSyntax(openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + ObjectTypeSyntax.create1 = function () { + return new ObjectTypeSyntax(TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ObjectTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectTypeSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.typeMembers, this.closeBraceToken); + }; + + ObjectTypeSyntax.prototype.withTypeMembers = function (typeMembers) { + return this.update(this.openBraceToken, typeMembers, this.closeBraceToken); + }; + + ObjectTypeSyntax.prototype.withTypeMember = function (typeMember) { + return this.withTypeMembers(TypeScript.Syntax.separatedList([typeMember])); + }; + + ObjectTypeSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.typeMembers, closeBraceToken); + }; + + ObjectTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ObjectTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectTypeSyntax = ObjectTypeSyntax; + + var ArrayTypeSyntax = (function (_super) { + __extends(ArrayTypeSyntax, _super); + function ArrayTypeSyntax(type, openBracketToken, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.type = type; + this.openBracketToken = openBracketToken; + this.closeBracketToken = closeBracketToken; + } + ArrayTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitArrayType(this); + }; + + ArrayTypeSyntax.prototype.kind = function () { + return 124 /* ArrayType */; + }; + + ArrayTypeSyntax.prototype.childCount = function () { + return 3; + }; + + ArrayTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.type; + case 1: + return this.openBracketToken; + case 2: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArrayTypeSyntax.prototype.isType = function () { + return true; + }; + + ArrayTypeSyntax.prototype.update = function (type, openBracketToken, closeBracketToken) { + if (this.type === type && this.openBracketToken === openBracketToken && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ArrayTypeSyntax(type, openBracketToken, closeBracketToken, this.parsedInStrictMode()); + }; + + ArrayTypeSyntax.create1 = function (type) { + return new ArrayTypeSyntax(type, TypeScript.Syntax.token(74 /* OpenBracketToken */), TypeScript.Syntax.token(75 /* CloseBracketToken */), false); + }; + + ArrayTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArrayTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArrayTypeSyntax.prototype.withType = function (type) { + return this.update(type, this.openBracketToken, this.closeBracketToken); + }; + + ArrayTypeSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(this.type, openBracketToken, this.closeBracketToken); + }; + + ArrayTypeSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.type, this.openBracketToken, closeBracketToken); + }; + + ArrayTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ArrayTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArrayTypeSyntax = ArrayTypeSyntax; + + var GenericTypeSyntax = (function (_super) { + __extends(GenericTypeSyntax, _super); + function GenericTypeSyntax(name, typeArgumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.name = name; + this.typeArgumentList = typeArgumentList; + } + GenericTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitGenericType(this); + }; + + GenericTypeSyntax.prototype.kind = function () { + return 126 /* GenericType */; + }; + + GenericTypeSyntax.prototype.childCount = function () { + return 2; + }; + + GenericTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.name; + case 1: + return this.typeArgumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + GenericTypeSyntax.prototype.isType = function () { + return true; + }; + + GenericTypeSyntax.prototype.update = function (name, typeArgumentList) { + if (this.name === name && this.typeArgumentList === typeArgumentList) { + return this; + } + + return new GenericTypeSyntax(name, typeArgumentList, this.parsedInStrictMode()); + }; + + GenericTypeSyntax.create1 = function (name) { + return new GenericTypeSyntax(name, TypeArgumentListSyntax.create1(), false); + }; + + GenericTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + GenericTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + GenericTypeSyntax.prototype.withName = function (name) { + return this.update(name, this.typeArgumentList); + }; + + GenericTypeSyntax.prototype.withTypeArgumentList = function (typeArgumentList) { + return this.update(this.name, typeArgumentList); + }; + + GenericTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return GenericTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.GenericTypeSyntax = GenericTypeSyntax; + + var TypeQuerySyntax = (function (_super) { + __extends(TypeQuerySyntax, _super); + function TypeQuerySyntax(typeOfKeyword, name, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeOfKeyword = typeOfKeyword; + this.name = name; + } + TypeQuerySyntax.prototype.accept = function (visitor) { + return visitor.visitTypeQuery(this); + }; + + TypeQuerySyntax.prototype.kind = function () { + return 127 /* TypeQuery */; + }; + + TypeQuerySyntax.prototype.childCount = function () { + return 2; + }; + + TypeQuerySyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeOfKeyword; + case 1: + return this.name; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeQuerySyntax.prototype.isType = function () { + return true; + }; + + TypeQuerySyntax.prototype.update = function (typeOfKeyword, name) { + if (this.typeOfKeyword === typeOfKeyword && this.name === name) { + return this; + } + + return new TypeQuerySyntax(typeOfKeyword, name, this.parsedInStrictMode()); + }; + + TypeQuerySyntax.create1 = function (name) { + return new TypeQuerySyntax(TypeScript.Syntax.token(39 /* TypeOfKeyword */), name, false); + }; + + TypeQuerySyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeQuerySyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeQuerySyntax.prototype.withTypeOfKeyword = function (typeOfKeyword) { + return this.update(typeOfKeyword, this.name); + }; + + TypeQuerySyntax.prototype.withName = function (name) { + return this.update(this.typeOfKeyword, name); + }; + + TypeQuerySyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeQuerySyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeQuerySyntax = TypeQuerySyntax; + + var TypeAnnotationSyntax = (function (_super) { + __extends(TypeAnnotationSyntax, _super); + function TypeAnnotationSyntax(colonToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.colonToken = colonToken; + this.type = type; + } + TypeAnnotationSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeAnnotation(this); + }; + + TypeAnnotationSyntax.prototype.kind = function () { + return 244 /* TypeAnnotation */; + }; + + TypeAnnotationSyntax.prototype.childCount = function () { + return 2; + }; + + TypeAnnotationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.colonToken; + case 1: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeAnnotationSyntax.prototype.update = function (colonToken, type) { + if (this.colonToken === colonToken && this.type === type) { + return this; + } + + return new TypeAnnotationSyntax(colonToken, type, this.parsedInStrictMode()); + }; + + TypeAnnotationSyntax.create1 = function (type) { + return new TypeAnnotationSyntax(TypeScript.Syntax.token(106 /* ColonToken */), type, false); + }; + + TypeAnnotationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeAnnotationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeAnnotationSyntax.prototype.withColonToken = function (colonToken) { + return this.update(colonToken, this.type); + }; + + TypeAnnotationSyntax.prototype.withType = function (type) { + return this.update(this.colonToken, type); + }; + + TypeAnnotationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeAnnotationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeAnnotationSyntax = TypeAnnotationSyntax; + + var BlockSyntax = (function (_super) { + __extends(BlockSyntax, _super); + function BlockSyntax(openBraceToken, statements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.statements = statements; + this.closeBraceToken = closeBraceToken; + } + BlockSyntax.prototype.accept = function (visitor) { + return visitor.visitBlock(this); + }; + + BlockSyntax.prototype.kind = function () { + return 146 /* Block */; + }; + + BlockSyntax.prototype.childCount = function () { + return 3; + }; + + BlockSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.statements; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BlockSyntax.prototype.isStatement = function () { + return true; + }; + + BlockSyntax.prototype.isModuleElement = function () { + return true; + }; + + BlockSyntax.prototype.update = function (openBraceToken, statements, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.statements === statements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new BlockSyntax(openBraceToken, statements, closeBraceToken, this.parsedInStrictMode()); + }; + + BlockSyntax.create = function (openBraceToken, closeBraceToken) { + return new BlockSyntax(openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + BlockSyntax.create1 = function () { + return new BlockSyntax(TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + BlockSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BlockSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BlockSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.statements, this.closeBraceToken); + }; + + BlockSyntax.prototype.withStatements = function (statements) { + return this.update(this.openBraceToken, statements, this.closeBraceToken); + }; + + BlockSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + BlockSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.statements, closeBraceToken); + }; + + BlockSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return BlockSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BlockSyntax = BlockSyntax; + + var ParameterSyntax = (function (_super) { + __extends(ParameterSyntax, _super); + function ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.dotDotDotToken = dotDotDotToken; + this.modifiers = modifiers; + this.identifier = identifier; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + } + ParameterSyntax.prototype.accept = function (visitor) { + return visitor.visitParameter(this); + }; + + ParameterSyntax.prototype.kind = function () { + return 242 /* Parameter */; + }; + + ParameterSyntax.prototype.childCount = function () { + return 6; + }; + + ParameterSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.dotDotDotToken; + case 1: + return this.modifiers; + case 2: + return this.identifier; + case 3: + return this.questionToken; + case 4: + return this.typeAnnotation; + case 5: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParameterSyntax.prototype.update = function (dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + if (this.dotDotDotToken === dotDotDotToken && this.modifiers === modifiers && this.identifier === identifier && this.questionToken === questionToken && this.typeAnnotation === typeAnnotation && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, this.parsedInStrictMode()); + }; + + ParameterSyntax.create = function (identifier) { + return new ParameterSyntax(null, TypeScript.Syntax.emptyList, identifier, null, null, null, false); + }; + + ParameterSyntax.create1 = function (identifier) { + return new ParameterSyntax(null, TypeScript.Syntax.emptyList, identifier, null, null, null, false); + }; + + ParameterSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParameterSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParameterSyntax.prototype.withDotDotDotToken = function (dotDotDotToken) { + return this.update(dotDotDotToken, this.modifiers, this.identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withModifiers = function (modifiers) { + return this.update(this.dotDotDotToken, modifiers, this.identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ParameterSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.dotDotDotToken, this.modifiers, identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.dotDotDotToken, this.modifiers, this.identifier, questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.dotDotDotToken, this.modifiers, this.identifier, this.questionToken, typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.dotDotDotToken, this.modifiers, this.identifier, this.questionToken, this.typeAnnotation, equalsValueClause); + }; + + ParameterSyntax.prototype.isTypeScriptSpecific = function () { + if (this.dotDotDotToken !== null) { + return true; + } + if (this.modifiers.isTypeScriptSpecific()) { + return true; + } + if (this.questionToken !== null) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + if (this.equalsValueClause !== null) { + return true; + } + return false; + }; + return ParameterSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParameterSyntax = ParameterSyntax; + + var MemberAccessExpressionSyntax = (function (_super) { + __extends(MemberAccessExpressionSyntax, _super); + function MemberAccessExpressionSyntax(expression, dotToken, name, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.dotToken = dotToken; + this.name = name; + } + MemberAccessExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberAccessExpression(this); + }; + + MemberAccessExpressionSyntax.prototype.kind = function () { + return 212 /* MemberAccessExpression */; + }; + + MemberAccessExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + MemberAccessExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.dotToken; + case 2: + return this.name; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberAccessExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.update = function (expression, dotToken, name) { + if (this.expression === expression && this.dotToken === dotToken && this.name === name) { + return this; + } + + return new MemberAccessExpressionSyntax(expression, dotToken, name, this.parsedInStrictMode()); + }; + + MemberAccessExpressionSyntax.create1 = function (expression, name) { + return new MemberAccessExpressionSyntax(expression, TypeScript.Syntax.token(76 /* DotToken */), name, false); + }; + + MemberAccessExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberAccessExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberAccessExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.dotToken, this.name); + }; + + MemberAccessExpressionSyntax.prototype.withDotToken = function (dotToken) { + return this.update(this.expression, dotToken, this.name); + }; + + MemberAccessExpressionSyntax.prototype.withName = function (name) { + return this.update(this.expression, this.dotToken, name); + }; + + MemberAccessExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return MemberAccessExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberAccessExpressionSyntax = MemberAccessExpressionSyntax; + + var PostfixUnaryExpressionSyntax = (function (_super) { + __extends(PostfixUnaryExpressionSyntax, _super); + function PostfixUnaryExpressionSyntax(kind, operand, operatorToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.operand = operand; + this.operatorToken = operatorToken; + + this._kind = kind; + } + PostfixUnaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitPostfixUnaryExpression(this); + }; + + PostfixUnaryExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + PostfixUnaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.operand; + case 1: + return this.operatorToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PostfixUnaryExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + PostfixUnaryExpressionSyntax.prototype.update = function (kind, operand, operatorToken) { + if (this._kind === kind && this.operand === operand && this.operatorToken === operatorToken) { + return this; + } + + return new PostfixUnaryExpressionSyntax(kind, operand, operatorToken, this.parsedInStrictMode()); + }; + + PostfixUnaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PostfixUnaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PostfixUnaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.operand, this.operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.withOperand = function (operand) { + return this.update(this._kind, operand, this.operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, this.operand, operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.operand.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return PostfixUnaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PostfixUnaryExpressionSyntax = PostfixUnaryExpressionSyntax; + + var ElementAccessExpressionSyntax = (function (_super) { + __extends(ElementAccessExpressionSyntax, _super); + function ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.openBracketToken = openBracketToken; + this.argumentExpression = argumentExpression; + this.closeBracketToken = closeBracketToken; + } + ElementAccessExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitElementAccessExpression(this); + }; + + ElementAccessExpressionSyntax.prototype.kind = function () { + return 221 /* ElementAccessExpression */; + }; + + ElementAccessExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + ElementAccessExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.openBracketToken; + case 2: + return this.argumentExpression; + case 3: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ElementAccessExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.update = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + if (this.expression === expression && this.openBracketToken === openBracketToken && this.argumentExpression === argumentExpression && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, this.parsedInStrictMode()); + }; + + ElementAccessExpressionSyntax.create1 = function (expression, argumentExpression) { + return new ElementAccessExpressionSyntax(expression, TypeScript.Syntax.token(74 /* OpenBracketToken */), argumentExpression, TypeScript.Syntax.token(75 /* CloseBracketToken */), false); + }; + + ElementAccessExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ElementAccessExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ElementAccessExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.openBracketToken, this.argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(this.expression, openBracketToken, this.argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withArgumentExpression = function (argumentExpression) { + return this.update(this.expression, this.openBracketToken, argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.expression, this.openBracketToken, this.argumentExpression, closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentExpression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ElementAccessExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ElementAccessExpressionSyntax = ElementAccessExpressionSyntax; + + var InvocationExpressionSyntax = (function (_super) { + __extends(InvocationExpressionSyntax, _super); + function InvocationExpressionSyntax(expression, argumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.argumentList = argumentList; + } + InvocationExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitInvocationExpression(this); + }; + + InvocationExpressionSyntax.prototype.kind = function () { + return 213 /* InvocationExpression */; + }; + + InvocationExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + InvocationExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.argumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + InvocationExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.update = function (expression, argumentList) { + if (this.expression === expression && this.argumentList === argumentList) { + return this; + } + + return new InvocationExpressionSyntax(expression, argumentList, this.parsedInStrictMode()); + }; + + InvocationExpressionSyntax.create1 = function (expression) { + return new InvocationExpressionSyntax(expression, ArgumentListSyntax.create1(), false); + }; + + InvocationExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + InvocationExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + InvocationExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.argumentList); + }; + + InvocationExpressionSyntax.prototype.withArgumentList = function (argumentList) { + return this.update(this.expression, argumentList); + }; + + InvocationExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentList.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return InvocationExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.InvocationExpressionSyntax = InvocationExpressionSyntax; + + var ArgumentListSyntax = (function (_super) { + __extends(ArgumentListSyntax, _super); + function ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeArgumentList = typeArgumentList; + this.openParenToken = openParenToken; + this.closeParenToken = closeParenToken; + + this.arguments = _arguments; + } + ArgumentListSyntax.prototype.accept = function (visitor) { + return visitor.visitArgumentList(this); + }; + + ArgumentListSyntax.prototype.kind = function () { + return 226 /* ArgumentList */; + }; + + ArgumentListSyntax.prototype.childCount = function () { + return 4; + }; + + ArgumentListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeArgumentList; + case 1: + return this.openParenToken; + case 2: + return this.arguments; + case 3: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArgumentListSyntax.prototype.update = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + if (this.typeArgumentList === typeArgumentList && this.openParenToken === openParenToken && this.arguments === _arguments && this.closeParenToken === closeParenToken) { + return this; + } + + return new ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, this.parsedInStrictMode()); + }; + + ArgumentListSyntax.create = function (openParenToken, closeParenToken) { + return new ArgumentListSyntax(null, openParenToken, TypeScript.Syntax.emptySeparatedList, closeParenToken, false); + }; + + ArgumentListSyntax.create1 = function () { + return new ArgumentListSyntax(null, TypeScript.Syntax.token(72 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ArgumentListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArgumentListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArgumentListSyntax.prototype.withTypeArgumentList = function (typeArgumentList) { + return this.update(typeArgumentList, this.openParenToken, this.arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.typeArgumentList, openParenToken, this.arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withArguments = function (_arguments) { + return this.update(this.typeArgumentList, this.openParenToken, _arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withArgument = function (_argument) { + return this.withArguments(TypeScript.Syntax.separatedList([_argument])); + }; + + ArgumentListSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.typeArgumentList, this.openParenToken, this.arguments, closeParenToken); + }; + + ArgumentListSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeArgumentList !== null && this.typeArgumentList.isTypeScriptSpecific()) { + return true; + } + if (this.arguments.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ArgumentListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArgumentListSyntax = ArgumentListSyntax; + + var BinaryExpressionSyntax = (function (_super) { + __extends(BinaryExpressionSyntax, _super); + function BinaryExpressionSyntax(kind, left, operatorToken, right, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.left = left; + this.operatorToken = operatorToken; + this.right = right; + + this._kind = kind; + } + BinaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitBinaryExpression(this); + }; + + BinaryExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + BinaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.left; + case 1: + return this.operatorToken; + case 2: + return this.right; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BinaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + BinaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + BinaryExpressionSyntax.prototype.update = function (kind, left, operatorToken, right) { + if (this._kind === kind && this.left === left && this.operatorToken === operatorToken && this.right === right) { + return this; + } + + return new BinaryExpressionSyntax(kind, left, operatorToken, right, this.parsedInStrictMode()); + }; + + BinaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BinaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BinaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.left, this.operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withLeft = function (left) { + return this.update(this._kind, left, this.operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, this.left, operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withRight = function (right) { + return this.update(this._kind, this.left, this.operatorToken, right); + }; + + BinaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.left.isTypeScriptSpecific()) { + return true; + } + if (this.right.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return BinaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BinaryExpressionSyntax = BinaryExpressionSyntax; + + var ConditionalExpressionSyntax = (function (_super) { + __extends(ConditionalExpressionSyntax, _super); + function ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.condition = condition; + this.questionToken = questionToken; + this.whenTrue = whenTrue; + this.colonToken = colonToken; + this.whenFalse = whenFalse; + } + ConditionalExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitConditionalExpression(this); + }; + + ConditionalExpressionSyntax.prototype.kind = function () { + return 186 /* ConditionalExpression */; + }; + + ConditionalExpressionSyntax.prototype.childCount = function () { + return 5; + }; + + ConditionalExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.condition; + case 1: + return this.questionToken; + case 2: + return this.whenTrue; + case 3: + return this.colonToken; + case 4: + return this.whenFalse; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConditionalExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ConditionalExpressionSyntax.prototype.update = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + if (this.condition === condition && this.questionToken === questionToken && this.whenTrue === whenTrue && this.colonToken === colonToken && this.whenFalse === whenFalse) { + return this; + } + + return new ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, this.parsedInStrictMode()); + }; + + ConditionalExpressionSyntax.create1 = function (condition, whenTrue, whenFalse) { + return new ConditionalExpressionSyntax(condition, TypeScript.Syntax.token(105 /* QuestionToken */), whenTrue, TypeScript.Syntax.token(106 /* ColonToken */), whenFalse, false); + }; + + ConditionalExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConditionalExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConditionalExpressionSyntax.prototype.withCondition = function (condition) { + return this.update(condition, this.questionToken, this.whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.condition, questionToken, this.whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withWhenTrue = function (whenTrue) { + return this.update(this.condition, this.questionToken, whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.condition, this.questionToken, this.whenTrue, colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withWhenFalse = function (whenFalse) { + return this.update(this.condition, this.questionToken, this.whenTrue, this.colonToken, whenFalse); + }; + + ConditionalExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.whenTrue.isTypeScriptSpecific()) { + return true; + } + if (this.whenFalse.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ConditionalExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConditionalExpressionSyntax = ConditionalExpressionSyntax; + + var ConstructSignatureSyntax = (function (_super) { + __extends(ConstructSignatureSyntax, _super); + function ConstructSignatureSyntax(newKeyword, callSignature, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.callSignature = callSignature; + } + ConstructSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructSignature(this); + }; + + ConstructSignatureSyntax.prototype.kind = function () { + return 143 /* ConstructSignature */; + }; + + ConstructSignatureSyntax.prototype.childCount = function () { + return 2; + }; + + ConstructSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.callSignature; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + ConstructSignatureSyntax.prototype.update = function (newKeyword, callSignature) { + if (this.newKeyword === newKeyword && this.callSignature === callSignature) { + return this; + } + + return new ConstructSignatureSyntax(newKeyword, callSignature, this.parsedInStrictMode()); + }; + + ConstructSignatureSyntax.create1 = function () { + return new ConstructSignatureSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), CallSignatureSyntax.create1(), false); + }; + + ConstructSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructSignatureSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.callSignature); + }; + + ConstructSignatureSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.newKeyword, callSignature); + }; + + ConstructSignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructSignatureSyntax = ConstructSignatureSyntax; + + var MethodSignatureSyntax = (function (_super) { + __extends(MethodSignatureSyntax, _super); + function MethodSignatureSyntax(propertyName, questionToken, callSignature, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.callSignature = callSignature; + } + MethodSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitMethodSignature(this); + }; + + MethodSignatureSyntax.prototype.kind = function () { + return 145 /* MethodSignature */; + }; + + MethodSignatureSyntax.prototype.childCount = function () { + return 3; + }; + + MethodSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.questionToken; + case 2: + return this.callSignature; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MethodSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + MethodSignatureSyntax.prototype.update = function (propertyName, questionToken, callSignature) { + if (this.propertyName === propertyName && this.questionToken === questionToken && this.callSignature === callSignature) { + return this; + } + + return new MethodSignatureSyntax(propertyName, questionToken, callSignature, this.parsedInStrictMode()); + }; + + MethodSignatureSyntax.create = function (propertyName, callSignature) { + return new MethodSignatureSyntax(propertyName, null, callSignature, false); + }; + + MethodSignatureSyntax.create1 = function (propertyName) { + return new MethodSignatureSyntax(propertyName, null, CallSignatureSyntax.create1(), false); + }; + + MethodSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MethodSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MethodSignatureSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.questionToken, this.callSignature); + }; + + MethodSignatureSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.propertyName, questionToken, this.callSignature); + }; + + MethodSignatureSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.propertyName, this.questionToken, callSignature); + }; + + MethodSignatureSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return MethodSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MethodSignatureSyntax = MethodSignatureSyntax; + + var IndexSignatureSyntax = (function (_super) { + __extends(IndexSignatureSyntax, _super); + function IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBracketToken = openBracketToken; + this.parameter = parameter; + this.closeBracketToken = closeBracketToken; + this.typeAnnotation = typeAnnotation; + } + IndexSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitIndexSignature(this); + }; + + IndexSignatureSyntax.prototype.kind = function () { + return 144 /* IndexSignature */; + }; + + IndexSignatureSyntax.prototype.childCount = function () { + return 4; + }; + + IndexSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBracketToken; + case 1: + return this.parameter; + case 2: + return this.closeBracketToken; + case 3: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IndexSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + IndexSignatureSyntax.prototype.update = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + if (this.openBracketToken === openBracketToken && this.parameter === parameter && this.closeBracketToken === closeBracketToken && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, this.parsedInStrictMode()); + }; + + IndexSignatureSyntax.create = function (openBracketToken, parameter, closeBracketToken) { + return new IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, null, false); + }; + + IndexSignatureSyntax.create1 = function (parameter) { + return new IndexSignatureSyntax(TypeScript.Syntax.token(74 /* OpenBracketToken */), parameter, TypeScript.Syntax.token(75 /* CloseBracketToken */), null, false); + }; + + IndexSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IndexSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IndexSignatureSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(openBracketToken, this.parameter, this.closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withParameter = function (parameter) { + return this.update(this.openBracketToken, parameter, this.closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.openBracketToken, this.parameter, closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.openBracketToken, this.parameter, this.closeBracketToken, typeAnnotation); + }; + + IndexSignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return IndexSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IndexSignatureSyntax = IndexSignatureSyntax; + + var PropertySignatureSyntax = (function (_super) { + __extends(PropertySignatureSyntax, _super); + function PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + } + PropertySignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitPropertySignature(this); + }; + + PropertySignatureSyntax.prototype.kind = function () { + return 141 /* PropertySignature */; + }; + + PropertySignatureSyntax.prototype.childCount = function () { + return 3; + }; + + PropertySignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.questionToken; + case 2: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PropertySignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + PropertySignatureSyntax.prototype.update = function (propertyName, questionToken, typeAnnotation) { + if (this.propertyName === propertyName && this.questionToken === questionToken && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, this.parsedInStrictMode()); + }; + + PropertySignatureSyntax.create = function (propertyName) { + return new PropertySignatureSyntax(propertyName, null, null, false); + }; + + PropertySignatureSyntax.create1 = function (propertyName) { + return new PropertySignatureSyntax(propertyName, null, null, false); + }; + + PropertySignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PropertySignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PropertySignatureSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.questionToken, this.typeAnnotation); + }; + + PropertySignatureSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.propertyName, questionToken, this.typeAnnotation); + }; + + PropertySignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.propertyName, this.questionToken, typeAnnotation); + }; + + PropertySignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return PropertySignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PropertySignatureSyntax = PropertySignatureSyntax; + + var CallSignatureSyntax = (function (_super) { + __extends(CallSignatureSyntax, _super); + function CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + } + CallSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitCallSignature(this); + }; + + CallSignatureSyntax.prototype.kind = function () { + return 142 /* CallSignature */; + }; + + CallSignatureSyntax.prototype.childCount = function () { + return 3; + }; + + CallSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeParameterList; + case 1: + return this.parameterList; + case 2: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CallSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + CallSignatureSyntax.prototype.update = function (typeParameterList, parameterList, typeAnnotation) { + if (this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, this.parsedInStrictMode()); + }; + + CallSignatureSyntax.create = function (parameterList) { + return new CallSignatureSyntax(null, parameterList, null, false); + }; + + CallSignatureSyntax.create1 = function () { + return new CallSignatureSyntax(null, ParameterListSyntax.create1(), null, false); + }; + + CallSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CallSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CallSignatureSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(typeParameterList, this.parameterList, this.typeAnnotation); + }; + + CallSignatureSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.typeParameterList, parameterList, this.typeAnnotation); + }; + + CallSignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.typeParameterList, this.parameterList, typeAnnotation); + }; + + CallSignatureSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeParameterList !== null) { + return true; + } + if (this.parameterList.isTypeScriptSpecific()) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + return false; + }; + return CallSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CallSignatureSyntax = CallSignatureSyntax; + + var ParameterListSyntax = (function (_super) { + __extends(ParameterListSyntax, _super); + function ParameterListSyntax(openParenToken, parameters, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openParenToken = openParenToken; + this.parameters = parameters; + this.closeParenToken = closeParenToken; + } + ParameterListSyntax.prototype.accept = function (visitor) { + return visitor.visitParameterList(this); + }; + + ParameterListSyntax.prototype.kind = function () { + return 227 /* ParameterList */; + }; + + ParameterListSyntax.prototype.childCount = function () { + return 3; + }; + + ParameterListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openParenToken; + case 1: + return this.parameters; + case 2: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParameterListSyntax.prototype.update = function (openParenToken, parameters, closeParenToken) { + if (this.openParenToken === openParenToken && this.parameters === parameters && this.closeParenToken === closeParenToken) { + return this; + } + + return new ParameterListSyntax(openParenToken, parameters, closeParenToken, this.parsedInStrictMode()); + }; + + ParameterListSyntax.create = function (openParenToken, closeParenToken) { + return new ParameterListSyntax(openParenToken, TypeScript.Syntax.emptySeparatedList, closeParenToken, false); + }; + + ParameterListSyntax.create1 = function () { + return new ParameterListSyntax(TypeScript.Syntax.token(72 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ParameterListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParameterListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParameterListSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(openParenToken, this.parameters, this.closeParenToken); + }; + + ParameterListSyntax.prototype.withParameters = function (parameters) { + return this.update(this.openParenToken, parameters, this.closeParenToken); + }; + + ParameterListSyntax.prototype.withParameter = function (parameter) { + return this.withParameters(TypeScript.Syntax.separatedList([parameter])); + }; + + ParameterListSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.openParenToken, this.parameters, closeParenToken); + }; + + ParameterListSyntax.prototype.isTypeScriptSpecific = function () { + if (this.parameters.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ParameterListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParameterListSyntax = ParameterListSyntax; + + var TypeParameterListSyntax = (function (_super) { + __extends(TypeParameterListSyntax, _super); + function TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.typeParameters = typeParameters; + this.greaterThanToken = greaterThanToken; + } + TypeParameterListSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeParameterList(this); + }; + + TypeParameterListSyntax.prototype.kind = function () { + return 229 /* TypeParameterList */; + }; + + TypeParameterListSyntax.prototype.childCount = function () { + return 3; + }; + + TypeParameterListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.typeParameters; + case 2: + return this.greaterThanToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeParameterListSyntax.prototype.update = function (lessThanToken, typeParameters, greaterThanToken) { + if (this.lessThanToken === lessThanToken && this.typeParameters === typeParameters && this.greaterThanToken === greaterThanToken) { + return this; + } + + return new TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, this.parsedInStrictMode()); + }; + + TypeParameterListSyntax.create = function (lessThanToken, greaterThanToken) { + return new TypeParameterListSyntax(lessThanToken, TypeScript.Syntax.emptySeparatedList, greaterThanToken, false); + }; + + TypeParameterListSyntax.create1 = function () { + return new TypeParameterListSyntax(TypeScript.Syntax.token(80 /* LessThanToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(81 /* GreaterThanToken */), false); + }; + + TypeParameterListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeParameterListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeParameterListSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.typeParameters, this.greaterThanToken); + }; + + TypeParameterListSyntax.prototype.withTypeParameters = function (typeParameters) { + return this.update(this.lessThanToken, typeParameters, this.greaterThanToken); + }; + + TypeParameterListSyntax.prototype.withTypeParameter = function (typeParameter) { + return this.withTypeParameters(TypeScript.Syntax.separatedList([typeParameter])); + }; + + TypeParameterListSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.typeParameters, greaterThanToken); + }; + + TypeParameterListSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeParameterListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeParameterListSyntax = TypeParameterListSyntax; + + var TypeParameterSyntax = (function (_super) { + __extends(TypeParameterSyntax, _super); + function TypeParameterSyntax(identifier, constraint, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.constraint = constraint; + } + TypeParameterSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeParameter(this); + }; + + TypeParameterSyntax.prototype.kind = function () { + return 238 /* TypeParameter */; + }; + + TypeParameterSyntax.prototype.childCount = function () { + return 2; + }; + + TypeParameterSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.constraint; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeParameterSyntax.prototype.update = function (identifier, constraint) { + if (this.identifier === identifier && this.constraint === constraint) { + return this; + } + + return new TypeParameterSyntax(identifier, constraint, this.parsedInStrictMode()); + }; + + TypeParameterSyntax.create = function (identifier) { + return new TypeParameterSyntax(identifier, null, false); + }; + + TypeParameterSyntax.create1 = function (identifier) { + return new TypeParameterSyntax(identifier, null, false); + }; + + TypeParameterSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeParameterSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeParameterSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.constraint); + }; + + TypeParameterSyntax.prototype.withConstraint = function (constraint) { + return this.update(this.identifier, constraint); + }; + + TypeParameterSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeParameterSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeParameterSyntax = TypeParameterSyntax; + + var ConstraintSyntax = (function (_super) { + __extends(ConstraintSyntax, _super); + function ConstraintSyntax(extendsKeyword, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.extendsKeyword = extendsKeyword; + this.type = type; + } + ConstraintSyntax.prototype.accept = function (visitor) { + return visitor.visitConstraint(this); + }; + + ConstraintSyntax.prototype.kind = function () { + return 239 /* Constraint */; + }; + + ConstraintSyntax.prototype.childCount = function () { + return 2; + }; + + ConstraintSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.extendsKeyword; + case 1: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstraintSyntax.prototype.update = function (extendsKeyword, type) { + if (this.extendsKeyword === extendsKeyword && this.type === type) { + return this; + } + + return new ConstraintSyntax(extendsKeyword, type, this.parsedInStrictMode()); + }; + + ConstraintSyntax.create1 = function (type) { + return new ConstraintSyntax(TypeScript.Syntax.token(48 /* ExtendsKeyword */), type, false); + }; + + ConstraintSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstraintSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstraintSyntax.prototype.withExtendsKeyword = function (extendsKeyword) { + return this.update(extendsKeyword, this.type); + }; + + ConstraintSyntax.prototype.withType = function (type) { + return this.update(this.extendsKeyword, type); + }; + + ConstraintSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstraintSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstraintSyntax = ConstraintSyntax; + + var ElseClauseSyntax = (function (_super) { + __extends(ElseClauseSyntax, _super); + function ElseClauseSyntax(elseKeyword, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.elseKeyword = elseKeyword; + this.statement = statement; + } + ElseClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitElseClause(this); + }; + + ElseClauseSyntax.prototype.kind = function () { + return 235 /* ElseClause */; + }; + + ElseClauseSyntax.prototype.childCount = function () { + return 2; + }; + + ElseClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.elseKeyword; + case 1: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ElseClauseSyntax.prototype.update = function (elseKeyword, statement) { + if (this.elseKeyword === elseKeyword && this.statement === statement) { + return this; + } + + return new ElseClauseSyntax(elseKeyword, statement, this.parsedInStrictMode()); + }; + + ElseClauseSyntax.create1 = function (statement) { + return new ElseClauseSyntax(TypeScript.Syntax.token(23 /* ElseKeyword */), statement, false); + }; + + ElseClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ElseClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ElseClauseSyntax.prototype.withElseKeyword = function (elseKeyword) { + return this.update(elseKeyword, this.statement); + }; + + ElseClauseSyntax.prototype.withStatement = function (statement) { + return this.update(this.elseKeyword, statement); + }; + + ElseClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ElseClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ElseClauseSyntax = ElseClauseSyntax; + + var IfStatementSyntax = (function (_super) { + __extends(IfStatementSyntax, _super); + function IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.ifKeyword = ifKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + this.elseClause = elseClause; + } + IfStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitIfStatement(this); + }; + + IfStatementSyntax.prototype.kind = function () { + return 147 /* IfStatement */; + }; + + IfStatementSyntax.prototype.childCount = function () { + return 6; + }; + + IfStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.ifKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + case 5: + return this.elseClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IfStatementSyntax.prototype.isStatement = function () { + return true; + }; + + IfStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + IfStatementSyntax.prototype.update = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + if (this.ifKeyword === ifKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement && this.elseClause === elseClause) { + return this; + } + + return new IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, this.parsedInStrictMode()); + }; + + IfStatementSyntax.create = function (ifKeyword, openParenToken, condition, closeParenToken, statement) { + return new IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, null, false); + }; + + IfStatementSyntax.create1 = function (condition, statement) { + return new IfStatementSyntax(TypeScript.Syntax.token(28 /* IfKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, null, false); + }; + + IfStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IfStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IfStatementSyntax.prototype.withIfKeyword = function (ifKeyword) { + return this.update(ifKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.ifKeyword, openParenToken, this.condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.ifKeyword, this.openParenToken, condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, this.closeParenToken, statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withElseClause = function (elseClause) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement, elseClause); + }; + + IfStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + if (this.elseClause !== null && this.elseClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return IfStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IfStatementSyntax = IfStatementSyntax; + + var ExpressionStatementSyntax = (function (_super) { + __extends(ExpressionStatementSyntax, _super); + function ExpressionStatementSyntax(expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ExpressionStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitExpressionStatement(this); + }; + + ExpressionStatementSyntax.prototype.kind = function () { + return 149 /* ExpressionStatement */; + }; + + ExpressionStatementSyntax.prototype.childCount = function () { + return 2; + }; + + ExpressionStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExpressionStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ExpressionStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ExpressionStatementSyntax.prototype.update = function (expression, semicolonToken) { + if (this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ExpressionStatementSyntax(expression, semicolonToken, this.parsedInStrictMode()); + }; + + ExpressionStatementSyntax.create1 = function (expression) { + return new ExpressionStatementSyntax(expression, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ExpressionStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExpressionStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExpressionStatementSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.semicolonToken); + }; + + ExpressionStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.expression, semicolonToken); + }; + + ExpressionStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ExpressionStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExpressionStatementSyntax = ExpressionStatementSyntax; + + var ConstructorDeclarationSyntax = (function (_super) { + __extends(ConstructorDeclarationSyntax, _super); + function ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.constructorKeyword = constructorKeyword; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + ConstructorDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructorDeclaration(this); + }; + + ConstructorDeclarationSyntax.prototype.kind = function () { + return 137 /* ConstructorDeclaration */; + }; + + ConstructorDeclarationSyntax.prototype.childCount = function () { + return 5; + }; + + ConstructorDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.constructorKeyword; + case 2: + return this.callSignature; + case 3: + return this.block; + case 4: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructorDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + ConstructorDeclarationSyntax.prototype.update = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.constructorKeyword === constructorKeyword && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + ConstructorDeclarationSyntax.create = function (constructorKeyword, callSignature) { + return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, constructorKeyword, callSignature, null, null, false); + }; + + ConstructorDeclarationSyntax.create1 = function () { + return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(62 /* ConstructorKeyword */), CallSignatureSyntax.create1(), null, null, false); + }; + + ConstructorDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructorDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructorDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.constructorKeyword, this.callSignature, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ConstructorDeclarationSyntax.prototype.withConstructorKeyword = function (constructorKeyword) { + return this.update(this.modifiers, constructorKeyword, this.callSignature, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.constructorKeyword, callSignature, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.constructorKeyword, this.callSignature, block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.constructorKeyword, this.callSignature, this.block, semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructorDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructorDeclarationSyntax = ConstructorDeclarationSyntax; + + var MemberFunctionDeclarationSyntax = (function (_super) { + __extends(MemberFunctionDeclarationSyntax, _super); + function MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + MemberFunctionDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberFunctionDeclaration(this); + }; + + MemberFunctionDeclarationSyntax.prototype.kind = function () { + return 135 /* MemberFunctionDeclaration */; + }; + + MemberFunctionDeclarationSyntax.prototype.childCount = function () { + return 5; + }; + + MemberFunctionDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.propertyName; + case 2: + return this.callSignature; + case 3: + return this.block; + case 4: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberFunctionDeclarationSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + MemberFunctionDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + MemberFunctionDeclarationSyntax.prototype.update = function (modifiers, propertyName, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.propertyName === propertyName && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + MemberFunctionDeclarationSyntax.create = function (propertyName, callSignature) { + return new MemberFunctionDeclarationSyntax(TypeScript.Syntax.emptyList, propertyName, callSignature, null, null, false); + }; + + MemberFunctionDeclarationSyntax.create1 = function (propertyName) { + return new MemberFunctionDeclarationSyntax(TypeScript.Syntax.emptyList, propertyName, CallSignatureSyntax.create1(), null, null, false); + }; + + MemberFunctionDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberFunctionDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberFunctionDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.propertyName, this.callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + MemberFunctionDeclarationSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, propertyName, this.callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.propertyName, callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.propertyName, this.callSignature, block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.propertyName, this.callSignature, this.block, semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return MemberFunctionDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberFunctionDeclarationSyntax = MemberFunctionDeclarationSyntax; + + var GetAccessorSyntax = (function (_super) { + __extends(GetAccessorSyntax, _super); + function GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.getKeyword = getKeyword; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + this.block = block; + } + GetAccessorSyntax.prototype.accept = function (visitor) { + return visitor.visitGetAccessor(this); + }; + + GetAccessorSyntax.prototype.kind = function () { + return 139 /* GetAccessor */; + }; + + GetAccessorSyntax.prototype.childCount = function () { + return 6; + }; + + GetAccessorSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.getKeyword; + case 2: + return this.propertyName; + case 3: + return this.parameterList; + case 4: + return this.typeAnnotation; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + GetAccessorSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + GetAccessorSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + GetAccessorSyntax.prototype.isClassElement = function () { + return true; + }; + + GetAccessorSyntax.prototype.update = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + if (this.modifiers === modifiers && this.getKeyword === getKeyword && this.propertyName === propertyName && this.parameterList === parameterList && this.typeAnnotation === typeAnnotation && this.block === block) { + return this; + } + + return new GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, this.parsedInStrictMode()); + }; + + GetAccessorSyntax.create = function (getKeyword, propertyName, parameterList, block) { + return new GetAccessorSyntax(TypeScript.Syntax.emptyList, getKeyword, propertyName, parameterList, null, block, false); + }; + + GetAccessorSyntax.create1 = function (propertyName) { + return new GetAccessorSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(64 /* GetKeyword */), propertyName, ParameterListSyntax.create1(), null, BlockSyntax.create1(), false); + }; + + GetAccessorSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + GetAccessorSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + GetAccessorSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + GetAccessorSyntax.prototype.withGetKeyword = function (getKeyword) { + return this.update(this.modifiers, getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, this.getKeyword, propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, this.parameterList, typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, block); + }; + + GetAccessorSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.childCount() > 0) { + return true; + } + if (this.parameterList.isTypeScriptSpecific()) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return GetAccessorSyntax; + })(TypeScript.SyntaxNode); + TypeScript.GetAccessorSyntax = GetAccessorSyntax; + + var SetAccessorSyntax = (function (_super) { + __extends(SetAccessorSyntax, _super); + function SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.setKeyword = setKeyword; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.block = block; + } + SetAccessorSyntax.prototype.accept = function (visitor) { + return visitor.visitSetAccessor(this); + }; + + SetAccessorSyntax.prototype.kind = function () { + return 140 /* SetAccessor */; + }; + + SetAccessorSyntax.prototype.childCount = function () { + return 5; + }; + + SetAccessorSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.setKeyword; + case 2: + return this.propertyName; + case 3: + return this.parameterList; + case 4: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SetAccessorSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + SetAccessorSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + SetAccessorSyntax.prototype.isClassElement = function () { + return true; + }; + + SetAccessorSyntax.prototype.update = function (modifiers, setKeyword, propertyName, parameterList, block) { + if (this.modifiers === modifiers && this.setKeyword === setKeyword && this.propertyName === propertyName && this.parameterList === parameterList && this.block === block) { + return this; + } + + return new SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, this.parsedInStrictMode()); + }; + + SetAccessorSyntax.create = function (setKeyword, propertyName, parameterList, block) { + return new SetAccessorSyntax(TypeScript.Syntax.emptyList, setKeyword, propertyName, parameterList, block, false); + }; + + SetAccessorSyntax.create1 = function (propertyName) { + return new SetAccessorSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(68 /* SetKeyword */), propertyName, ParameterListSyntax.create1(), BlockSyntax.create1(), false); + }; + + SetAccessorSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SetAccessorSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SetAccessorSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.setKeyword, this.propertyName, this.parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + SetAccessorSyntax.prototype.withSetKeyword = function (setKeyword) { + return this.update(this.modifiers, setKeyword, this.propertyName, this.parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, this.setKeyword, propertyName, this.parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.modifiers, this.setKeyword, this.propertyName, parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.setKeyword, this.propertyName, this.parameterList, block); + }; + + SetAccessorSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return SetAccessorSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SetAccessorSyntax = SetAccessorSyntax; + + var MemberVariableDeclarationSyntax = (function (_super) { + __extends(MemberVariableDeclarationSyntax, _super); + function MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.variableDeclarator = variableDeclarator; + this.semicolonToken = semicolonToken; + } + MemberVariableDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberVariableDeclaration(this); + }; + + MemberVariableDeclarationSyntax.prototype.kind = function () { + return 136 /* MemberVariableDeclaration */; + }; + + MemberVariableDeclarationSyntax.prototype.childCount = function () { + return 3; + }; + + MemberVariableDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.variableDeclarator; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberVariableDeclarationSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + MemberVariableDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + MemberVariableDeclarationSyntax.prototype.update = function (modifiers, variableDeclarator, semicolonToken) { + if (this.modifiers === modifiers && this.variableDeclarator === variableDeclarator && this.semicolonToken === semicolonToken) { + return this; + } + + return new MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, this.parsedInStrictMode()); + }; + + MemberVariableDeclarationSyntax.create = function (variableDeclarator, semicolonToken) { + return new MemberVariableDeclarationSyntax(TypeScript.Syntax.emptyList, variableDeclarator, semicolonToken, false); + }; + + MemberVariableDeclarationSyntax.create1 = function (variableDeclarator) { + return new MemberVariableDeclarationSyntax(TypeScript.Syntax.emptyList, variableDeclarator, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + MemberVariableDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberVariableDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberVariableDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.variableDeclarator, this.semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + MemberVariableDeclarationSyntax.prototype.withVariableDeclarator = function (variableDeclarator) { + return this.update(this.modifiers, variableDeclarator, this.semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.variableDeclarator, semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return MemberVariableDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberVariableDeclarationSyntax = MemberVariableDeclarationSyntax; + + var IndexMemberDeclarationSyntax = (function (_super) { + __extends(IndexMemberDeclarationSyntax, _super); + function IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.indexSignature = indexSignature; + this.semicolonToken = semicolonToken; + } + IndexMemberDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitIndexMemberDeclaration(this); + }; + + IndexMemberDeclarationSyntax.prototype.kind = function () { + return 138 /* IndexMemberDeclaration */; + }; + + IndexMemberDeclarationSyntax.prototype.childCount = function () { + return 3; + }; + + IndexMemberDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.indexSignature; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IndexMemberDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + IndexMemberDeclarationSyntax.prototype.update = function (modifiers, indexSignature, semicolonToken) { + if (this.modifiers === modifiers && this.indexSignature === indexSignature && this.semicolonToken === semicolonToken) { + return this; + } + + return new IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, this.parsedInStrictMode()); + }; + + IndexMemberDeclarationSyntax.create = function (indexSignature, semicolonToken) { + return new IndexMemberDeclarationSyntax(TypeScript.Syntax.emptyList, indexSignature, semicolonToken, false); + }; + + IndexMemberDeclarationSyntax.create1 = function (indexSignature) { + return new IndexMemberDeclarationSyntax(TypeScript.Syntax.emptyList, indexSignature, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + IndexMemberDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IndexMemberDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IndexMemberDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.indexSignature, this.semicolonToken); + }; + + IndexMemberDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + IndexMemberDeclarationSyntax.prototype.withIndexSignature = function (indexSignature) { + return this.update(this.modifiers, indexSignature, this.semicolonToken); + }; + + IndexMemberDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.indexSignature, semicolonToken); + }; + + IndexMemberDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return IndexMemberDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IndexMemberDeclarationSyntax = IndexMemberDeclarationSyntax; + + var ThrowStatementSyntax = (function (_super) { + __extends(ThrowStatementSyntax, _super); + function ThrowStatementSyntax(throwKeyword, expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.throwKeyword = throwKeyword; + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ThrowStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitThrowStatement(this); + }; + + ThrowStatementSyntax.prototype.kind = function () { + return 157 /* ThrowStatement */; + }; + + ThrowStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ThrowStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.throwKeyword; + case 1: + return this.expression; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ThrowStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ThrowStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ThrowStatementSyntax.prototype.update = function (throwKeyword, expression, semicolonToken) { + if (this.throwKeyword === throwKeyword && this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ThrowStatementSyntax(throwKeyword, expression, semicolonToken, this.parsedInStrictMode()); + }; + + ThrowStatementSyntax.create1 = function (expression) { + return new ThrowStatementSyntax(TypeScript.Syntax.token(36 /* ThrowKeyword */), expression, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ThrowStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ThrowStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ThrowStatementSyntax.prototype.withThrowKeyword = function (throwKeyword) { + return this.update(throwKeyword, this.expression, this.semicolonToken); + }; + + ThrowStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.throwKeyword, expression, this.semicolonToken); + }; + + ThrowStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.throwKeyword, this.expression, semicolonToken); + }; + + ThrowStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ThrowStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ThrowStatementSyntax = ThrowStatementSyntax; + + var ReturnStatementSyntax = (function (_super) { + __extends(ReturnStatementSyntax, _super); + function ReturnStatementSyntax(returnKeyword, expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.returnKeyword = returnKeyword; + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ReturnStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitReturnStatement(this); + }; + + ReturnStatementSyntax.prototype.kind = function () { + return 150 /* ReturnStatement */; + }; + + ReturnStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ReturnStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.returnKeyword; + case 1: + return this.expression; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ReturnStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ReturnStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ReturnStatementSyntax.prototype.update = function (returnKeyword, expression, semicolonToken) { + if (this.returnKeyword === returnKeyword && this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ReturnStatementSyntax(returnKeyword, expression, semicolonToken, this.parsedInStrictMode()); + }; + + ReturnStatementSyntax.create = function (returnKeyword, semicolonToken) { + return new ReturnStatementSyntax(returnKeyword, null, semicolonToken, false); + }; + + ReturnStatementSyntax.create1 = function () { + return new ReturnStatementSyntax(TypeScript.Syntax.token(33 /* ReturnKeyword */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ReturnStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ReturnStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ReturnStatementSyntax.prototype.withReturnKeyword = function (returnKeyword) { + return this.update(returnKeyword, this.expression, this.semicolonToken); + }; + + ReturnStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.returnKeyword, expression, this.semicolonToken); + }; + + ReturnStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.returnKeyword, this.expression, semicolonToken); + }; + + ReturnStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression !== null && this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ReturnStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ReturnStatementSyntax = ReturnStatementSyntax; + + var ObjectCreationExpressionSyntax = (function (_super) { + __extends(ObjectCreationExpressionSyntax, _super); + function ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.expression = expression; + this.argumentList = argumentList; + } + ObjectCreationExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectCreationExpression(this); + }; + + ObjectCreationExpressionSyntax.prototype.kind = function () { + return 216 /* ObjectCreationExpression */; + }; + + ObjectCreationExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectCreationExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.expression; + case 2: + return this.argumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectCreationExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.update = function (newKeyword, expression, argumentList) { + if (this.newKeyword === newKeyword && this.expression === expression && this.argumentList === argumentList) { + return this; + } + + return new ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, this.parsedInStrictMode()); + }; + + ObjectCreationExpressionSyntax.create = function (newKeyword, expression) { + return new ObjectCreationExpressionSyntax(newKeyword, expression, null, false); + }; + + ObjectCreationExpressionSyntax.create1 = function (expression) { + return new ObjectCreationExpressionSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), expression, null, false); + }; + + ObjectCreationExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectCreationExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectCreationExpressionSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.expression, this.argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.newKeyword, expression, this.argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.withArgumentList = function (argumentList) { + return this.update(this.newKeyword, this.expression, argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentList !== null && this.argumentList.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ObjectCreationExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectCreationExpressionSyntax = ObjectCreationExpressionSyntax; + + var SwitchStatementSyntax = (function (_super) { + __extends(SwitchStatementSyntax, _super); + function SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.switchKeyword = switchKeyword; + this.openParenToken = openParenToken; + this.expression = expression; + this.closeParenToken = closeParenToken; + this.openBraceToken = openBraceToken; + this.switchClauses = switchClauses; + this.closeBraceToken = closeBraceToken; + } + SwitchStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitSwitchStatement(this); + }; + + SwitchStatementSyntax.prototype.kind = function () { + return 151 /* SwitchStatement */; + }; + + SwitchStatementSyntax.prototype.childCount = function () { + return 7; + }; + + SwitchStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.switchKeyword; + case 1: + return this.openParenToken; + case 2: + return this.expression; + case 3: + return this.closeParenToken; + case 4: + return this.openBraceToken; + case 5: + return this.switchClauses; + case 6: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SwitchStatementSyntax.prototype.isStatement = function () { + return true; + }; + + SwitchStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + SwitchStatementSyntax.prototype.update = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + if (this.switchKeyword === switchKeyword && this.openParenToken === openParenToken && this.expression === expression && this.closeParenToken === closeParenToken && this.openBraceToken === openBraceToken && this.switchClauses === switchClauses && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, this.parsedInStrictMode()); + }; + + SwitchStatementSyntax.create = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, closeBraceToken) { + return new SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + SwitchStatementSyntax.create1 = function (expression) { + return new SwitchStatementSyntax(TypeScript.Syntax.token(34 /* SwitchKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), expression, TypeScript.Syntax.token(73 /* CloseParenToken */), TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + SwitchStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SwitchStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SwitchStatementSyntax.prototype.withSwitchKeyword = function (switchKeyword) { + return this.update(switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.switchKeyword, openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.switchKeyword, this.openParenToken, expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withSwitchClauses = function (switchClauses) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withSwitchClause = function (switchClause) { + return this.withSwitchClauses(TypeScript.Syntax.list([switchClause])); + }; + + SwitchStatementSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, closeBraceToken); + }; + + SwitchStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.switchClauses.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SwitchStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SwitchStatementSyntax = SwitchStatementSyntax; + + var CaseSwitchClauseSyntax = (function (_super) { + __extends(CaseSwitchClauseSyntax, _super); + function CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.caseKeyword = caseKeyword; + this.expression = expression; + this.colonToken = colonToken; + this.statements = statements; + } + CaseSwitchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitCaseSwitchClause(this); + }; + + CaseSwitchClauseSyntax.prototype.kind = function () { + return 233 /* CaseSwitchClause */; + }; + + CaseSwitchClauseSyntax.prototype.childCount = function () { + return 4; + }; + + CaseSwitchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.caseKeyword; + case 1: + return this.expression; + case 2: + return this.colonToken; + case 3: + return this.statements; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CaseSwitchClauseSyntax.prototype.isSwitchClause = function () { + return true; + }; + + CaseSwitchClauseSyntax.prototype.update = function (caseKeyword, expression, colonToken, statements) { + if (this.caseKeyword === caseKeyword && this.expression === expression && this.colonToken === colonToken && this.statements === statements) { + return this; + } + + return new CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, this.parsedInStrictMode()); + }; + + CaseSwitchClauseSyntax.create = function (caseKeyword, expression, colonToken) { + return new CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, TypeScript.Syntax.emptyList, false); + }; + + CaseSwitchClauseSyntax.create1 = function (expression) { + return new CaseSwitchClauseSyntax(TypeScript.Syntax.token(16 /* CaseKeyword */), expression, TypeScript.Syntax.token(106 /* ColonToken */), TypeScript.Syntax.emptyList, false); + }; + + CaseSwitchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CaseSwitchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CaseSwitchClauseSyntax.prototype.withCaseKeyword = function (caseKeyword) { + return this.update(caseKeyword, this.expression, this.colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withExpression = function (expression) { + return this.update(this.caseKeyword, expression, this.colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.caseKeyword, this.expression, colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withStatements = function (statements) { + return this.update(this.caseKeyword, this.expression, this.colonToken, statements); + }; + + CaseSwitchClauseSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + CaseSwitchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return CaseSwitchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CaseSwitchClauseSyntax = CaseSwitchClauseSyntax; + + var DefaultSwitchClauseSyntax = (function (_super) { + __extends(DefaultSwitchClauseSyntax, _super); + function DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.defaultKeyword = defaultKeyword; + this.colonToken = colonToken; + this.statements = statements; + } + DefaultSwitchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitDefaultSwitchClause(this); + }; + + DefaultSwitchClauseSyntax.prototype.kind = function () { + return 234 /* DefaultSwitchClause */; + }; + + DefaultSwitchClauseSyntax.prototype.childCount = function () { + return 3; + }; + + DefaultSwitchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.defaultKeyword; + case 1: + return this.colonToken; + case 2: + return this.statements; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DefaultSwitchClauseSyntax.prototype.isSwitchClause = function () { + return true; + }; + + DefaultSwitchClauseSyntax.prototype.update = function (defaultKeyword, colonToken, statements) { + if (this.defaultKeyword === defaultKeyword && this.colonToken === colonToken && this.statements === statements) { + return this; + } + + return new DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, this.parsedInStrictMode()); + }; + + DefaultSwitchClauseSyntax.create = function (defaultKeyword, colonToken) { + return new DefaultSwitchClauseSyntax(defaultKeyword, colonToken, TypeScript.Syntax.emptyList, false); + }; + + DefaultSwitchClauseSyntax.create1 = function () { + return new DefaultSwitchClauseSyntax(TypeScript.Syntax.token(20 /* DefaultKeyword */), TypeScript.Syntax.token(106 /* ColonToken */), TypeScript.Syntax.emptyList, false); + }; + + DefaultSwitchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DefaultSwitchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DefaultSwitchClauseSyntax.prototype.withDefaultKeyword = function (defaultKeyword) { + return this.update(defaultKeyword, this.colonToken, this.statements); + }; + + DefaultSwitchClauseSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.defaultKeyword, colonToken, this.statements); + }; + + DefaultSwitchClauseSyntax.prototype.withStatements = function (statements) { + return this.update(this.defaultKeyword, this.colonToken, statements); + }; + + DefaultSwitchClauseSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + DefaultSwitchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DefaultSwitchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DefaultSwitchClauseSyntax = DefaultSwitchClauseSyntax; + + var BreakStatementSyntax = (function (_super) { + __extends(BreakStatementSyntax, _super); + function BreakStatementSyntax(breakKeyword, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.breakKeyword = breakKeyword; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + BreakStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitBreakStatement(this); + }; + + BreakStatementSyntax.prototype.kind = function () { + return 152 /* BreakStatement */; + }; + + BreakStatementSyntax.prototype.childCount = function () { + return 3; + }; + + BreakStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.breakKeyword; + case 1: + return this.identifier; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BreakStatementSyntax.prototype.isStatement = function () { + return true; + }; + + BreakStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + BreakStatementSyntax.prototype.update = function (breakKeyword, identifier, semicolonToken) { + if (this.breakKeyword === breakKeyword && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new BreakStatementSyntax(breakKeyword, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + BreakStatementSyntax.create = function (breakKeyword, semicolonToken) { + return new BreakStatementSyntax(breakKeyword, null, semicolonToken, false); + }; + + BreakStatementSyntax.create1 = function () { + return new BreakStatementSyntax(TypeScript.Syntax.token(15 /* BreakKeyword */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + BreakStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BreakStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BreakStatementSyntax.prototype.withBreakKeyword = function (breakKeyword) { + return this.update(breakKeyword, this.identifier, this.semicolonToken); + }; + + BreakStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.breakKeyword, identifier, this.semicolonToken); + }; + + BreakStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.breakKeyword, this.identifier, semicolonToken); + }; + + BreakStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return BreakStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BreakStatementSyntax = BreakStatementSyntax; + + var ContinueStatementSyntax = (function (_super) { + __extends(ContinueStatementSyntax, _super); + function ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.continueKeyword = continueKeyword; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + ContinueStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitContinueStatement(this); + }; + + ContinueStatementSyntax.prototype.kind = function () { + return 153 /* ContinueStatement */; + }; + + ContinueStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ContinueStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.continueKeyword; + case 1: + return this.identifier; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ContinueStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ContinueStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ContinueStatementSyntax.prototype.update = function (continueKeyword, identifier, semicolonToken) { + if (this.continueKeyword === continueKeyword && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + ContinueStatementSyntax.create = function (continueKeyword, semicolonToken) { + return new ContinueStatementSyntax(continueKeyword, null, semicolonToken, false); + }; + + ContinueStatementSyntax.create1 = function () { + return new ContinueStatementSyntax(TypeScript.Syntax.token(18 /* ContinueKeyword */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ContinueStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ContinueStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ContinueStatementSyntax.prototype.withContinueKeyword = function (continueKeyword) { + return this.update(continueKeyword, this.identifier, this.semicolonToken); + }; + + ContinueStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.continueKeyword, identifier, this.semicolonToken); + }; + + ContinueStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.continueKeyword, this.identifier, semicolonToken); + }; + + ContinueStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return ContinueStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ContinueStatementSyntax = ContinueStatementSyntax; + + var ForStatementSyntax = (function (_super) { + __extends(ForStatementSyntax, _super); + function ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.forKeyword = forKeyword; + this.openParenToken = openParenToken; + this.variableDeclaration = variableDeclaration; + this.initializer = initializer; + this.firstSemicolonToken = firstSemicolonToken; + this.condition = condition; + this.secondSemicolonToken = secondSemicolonToken; + this.incrementor = incrementor; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + ForStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitForStatement(this); + }; + + ForStatementSyntax.prototype.kind = function () { + return 154 /* ForStatement */; + }; + + ForStatementSyntax.prototype.childCount = function () { + return 10; + }; + + ForStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.forKeyword; + case 1: + return this.openParenToken; + case 2: + return this.variableDeclaration; + case 3: + return this.initializer; + case 4: + return this.firstSemicolonToken; + case 5: + return this.condition; + case 6: + return this.secondSemicolonToken; + case 7: + return this.incrementor; + case 8: + return this.closeParenToken; + case 9: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ForStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + ForStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ForStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ForStatementSyntax.prototype.update = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + if (this.forKeyword === forKeyword && this.openParenToken === openParenToken && this.variableDeclaration === variableDeclaration && this.initializer === initializer && this.firstSemicolonToken === firstSemicolonToken && this.condition === condition && this.secondSemicolonToken === secondSemicolonToken && this.incrementor === incrementor && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, this.parsedInStrictMode()); + }; + + ForStatementSyntax.create = function (forKeyword, openParenToken, firstSemicolonToken, secondSemicolonToken, closeParenToken, statement) { + return new ForStatementSyntax(forKeyword, openParenToken, null, null, firstSemicolonToken, null, secondSemicolonToken, null, closeParenToken, statement, false); + }; + + ForStatementSyntax.create1 = function (statement) { + return new ForStatementSyntax(TypeScript.Syntax.token(26 /* ForKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), null, null, TypeScript.Syntax.token(78 /* SemicolonToken */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), null, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + ForStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ForStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ForStatementSyntax.prototype.withForKeyword = function (forKeyword) { + return this.update(forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.forKeyword, openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.forKeyword, this.openParenToken, variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withInitializer = function (initializer) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withFirstSemicolonToken = function (firstSemicolonToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withSecondSemicolonToken = function (secondSemicolonToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withIncrementor = function (incrementor) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, statement); + }; + + ForStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclaration !== null && this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + if (this.initializer !== null && this.initializer.isTypeScriptSpecific()) { + return true; + } + if (this.condition !== null && this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.incrementor !== null && this.incrementor.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ForStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ForStatementSyntax = ForStatementSyntax; + + var ForInStatementSyntax = (function (_super) { + __extends(ForInStatementSyntax, _super); + function ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.forKeyword = forKeyword; + this.openParenToken = openParenToken; + this.variableDeclaration = variableDeclaration; + this.left = left; + this.inKeyword = inKeyword; + this.expression = expression; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + ForInStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitForInStatement(this); + }; + + ForInStatementSyntax.prototype.kind = function () { + return 155 /* ForInStatement */; + }; + + ForInStatementSyntax.prototype.childCount = function () { + return 8; + }; + + ForInStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.forKeyword; + case 1: + return this.openParenToken; + case 2: + return this.variableDeclaration; + case 3: + return this.left; + case 4: + return this.inKeyword; + case 5: + return this.expression; + case 6: + return this.closeParenToken; + case 7: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ForInStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + ForInStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ForInStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ForInStatementSyntax.prototype.update = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + if (this.forKeyword === forKeyword && this.openParenToken === openParenToken && this.variableDeclaration === variableDeclaration && this.left === left && this.inKeyword === inKeyword && this.expression === expression && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, this.parsedInStrictMode()); + }; + + ForInStatementSyntax.create = function (forKeyword, openParenToken, inKeyword, expression, closeParenToken, statement) { + return new ForInStatementSyntax(forKeyword, openParenToken, null, null, inKeyword, expression, closeParenToken, statement, false); + }; + + ForInStatementSyntax.create1 = function (expression, statement) { + return new ForInStatementSyntax(TypeScript.Syntax.token(26 /* ForKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), null, null, TypeScript.Syntax.token(29 /* InKeyword */), expression, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + ForInStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ForInStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ForInStatementSyntax.prototype.withForKeyword = function (forKeyword) { + return this.update(forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.forKeyword, openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.forKeyword, this.openParenToken, variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withLeft = function (left) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withInKeyword = function (inKeyword) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, statement); + }; + + ForInStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclaration !== null && this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + if (this.left !== null && this.left.isTypeScriptSpecific()) { + return true; + } + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ForInStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ForInStatementSyntax = ForInStatementSyntax; + + var WhileStatementSyntax = (function (_super) { + __extends(WhileStatementSyntax, _super); + function WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.whileKeyword = whileKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + WhileStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitWhileStatement(this); + }; + + WhileStatementSyntax.prototype.kind = function () { + return 158 /* WhileStatement */; + }; + + WhileStatementSyntax.prototype.childCount = function () { + return 5; + }; + + WhileStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.whileKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + WhileStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + WhileStatementSyntax.prototype.isStatement = function () { + return true; + }; + + WhileStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + WhileStatementSyntax.prototype.update = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + if (this.whileKeyword === whileKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, this.parsedInStrictMode()); + }; + + WhileStatementSyntax.create1 = function (condition, statement) { + return new WhileStatementSyntax(TypeScript.Syntax.token(42 /* WhileKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + WhileStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + WhileStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + WhileStatementSyntax.prototype.withWhileKeyword = function (whileKeyword) { + return this.update(whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.whileKeyword, openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.whileKeyword, this.openParenToken, condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.whileKeyword, this.openParenToken, this.condition, closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, statement); + }; + + WhileStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return WhileStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.WhileStatementSyntax = WhileStatementSyntax; + + var WithStatementSyntax = (function (_super) { + __extends(WithStatementSyntax, _super); + function WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.withKeyword = withKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + WithStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitWithStatement(this); + }; + + WithStatementSyntax.prototype.kind = function () { + return 163 /* WithStatement */; + }; + + WithStatementSyntax.prototype.childCount = function () { + return 5; + }; + + WithStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.withKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + WithStatementSyntax.prototype.isStatement = function () { + return true; + }; + + WithStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + WithStatementSyntax.prototype.update = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + if (this.withKeyword === withKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, this.parsedInStrictMode()); + }; + + WithStatementSyntax.create1 = function (condition, statement) { + return new WithStatementSyntax(TypeScript.Syntax.token(43 /* WithKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + WithStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + WithStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + WithStatementSyntax.prototype.withWithKeyword = function (withKeyword) { + return this.update(withKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.withKeyword, openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.withKeyword, this.openParenToken, condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.withKeyword, this.openParenToken, this.condition, closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.withKeyword, this.openParenToken, this.condition, this.closeParenToken, statement); + }; + + WithStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return WithStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.WithStatementSyntax = WithStatementSyntax; + + var EnumDeclarationSyntax = (function (_super) { + __extends(EnumDeclarationSyntax, _super); + function EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.enumKeyword = enumKeyword; + this.identifier = identifier; + this.openBraceToken = openBraceToken; + this.enumElements = enumElements; + this.closeBraceToken = closeBraceToken; + } + EnumDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitEnumDeclaration(this); + }; + + EnumDeclarationSyntax.prototype.kind = function () { + return 132 /* EnumDeclaration */; + }; + + EnumDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + EnumDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.enumKeyword; + case 2: + return this.identifier; + case 3: + return this.openBraceToken; + case 4: + return this.enumElements; + case 5: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EnumDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + EnumDeclarationSyntax.prototype.update = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + if (this.modifiers === modifiers && this.enumKeyword === enumKeyword && this.identifier === identifier && this.openBraceToken === openBraceToken && this.enumElements === enumElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, this.parsedInStrictMode()); + }; + + EnumDeclarationSyntax.create = function (enumKeyword, identifier, openBraceToken, closeBraceToken) { + return new EnumDeclarationSyntax(TypeScript.Syntax.emptyList, enumKeyword, identifier, openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + EnumDeclarationSyntax.create1 = function (identifier) { + return new EnumDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(46 /* EnumKeyword */), identifier, TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + EnumDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EnumDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EnumDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.enumKeyword, this.identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + EnumDeclarationSyntax.prototype.withEnumKeyword = function (enumKeyword) { + return this.update(this.modifiers, enumKeyword, this.identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.enumKeyword, identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withEnumElements = function (enumElements) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, this.openBraceToken, enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withEnumElement = function (enumElement) { + return this.withEnumElements(TypeScript.Syntax.separatedList([enumElement])); + }; + + EnumDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, this.openBraceToken, this.enumElements, closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return EnumDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EnumDeclarationSyntax = EnumDeclarationSyntax; + + var EnumElementSyntax = (function (_super) { + __extends(EnumElementSyntax, _super); + function EnumElementSyntax(propertyName, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.equalsValueClause = equalsValueClause; + } + EnumElementSyntax.prototype.accept = function (visitor) { + return visitor.visitEnumElement(this); + }; + + EnumElementSyntax.prototype.kind = function () { + return 243 /* EnumElement */; + }; + + EnumElementSyntax.prototype.childCount = function () { + return 2; + }; + + EnumElementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EnumElementSyntax.prototype.update = function (propertyName, equalsValueClause) { + if (this.propertyName === propertyName && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new EnumElementSyntax(propertyName, equalsValueClause, this.parsedInStrictMode()); + }; + + EnumElementSyntax.create = function (propertyName) { + return new EnumElementSyntax(propertyName, null, false); + }; + + EnumElementSyntax.create1 = function (propertyName) { + return new EnumElementSyntax(propertyName, null, false); + }; + + EnumElementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EnumElementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EnumElementSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.equalsValueClause); + }; + + EnumElementSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.propertyName, equalsValueClause); + }; + + EnumElementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.equalsValueClause !== null && this.equalsValueClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return EnumElementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EnumElementSyntax = EnumElementSyntax; + + var CastExpressionSyntax = (function (_super) { + __extends(CastExpressionSyntax, _super); + function CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.type = type; + this.greaterThanToken = greaterThanToken; + this.expression = expression; + } + CastExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitCastExpression(this); + }; + + CastExpressionSyntax.prototype.kind = function () { + return 220 /* CastExpression */; + }; + + CastExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + CastExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.type; + case 2: + return this.greaterThanToken; + case 3: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CastExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + CastExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + CastExpressionSyntax.prototype.update = function (lessThanToken, type, greaterThanToken, expression) { + if (this.lessThanToken === lessThanToken && this.type === type && this.greaterThanToken === greaterThanToken && this.expression === expression) { + return this; + } + + return new CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, this.parsedInStrictMode()); + }; + + CastExpressionSyntax.create1 = function (type, expression) { + return new CastExpressionSyntax(TypeScript.Syntax.token(80 /* LessThanToken */), type, TypeScript.Syntax.token(81 /* GreaterThanToken */), expression, false); + }; + + CastExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CastExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CastExpressionSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.type, this.greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withType = function (type) { + return this.update(this.lessThanToken, type, this.greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.type, greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.lessThanToken, this.type, this.greaterThanToken, expression); + }; + + CastExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return CastExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CastExpressionSyntax = CastExpressionSyntax; + + var ObjectLiteralExpressionSyntax = (function (_super) { + __extends(ObjectLiteralExpressionSyntax, _super); + function ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.propertyAssignments = propertyAssignments; + this.closeBraceToken = closeBraceToken; + } + ObjectLiteralExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectLiteralExpression(this); + }; + + ObjectLiteralExpressionSyntax.prototype.kind = function () { + return 215 /* ObjectLiteralExpression */; + }; + + ObjectLiteralExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectLiteralExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.propertyAssignments; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectLiteralExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.update = function (openBraceToken, propertyAssignments, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.propertyAssignments === propertyAssignments && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, this.parsedInStrictMode()); + }; + + ObjectLiteralExpressionSyntax.create = function (openBraceToken, closeBraceToken) { + return new ObjectLiteralExpressionSyntax(openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + ObjectLiteralExpressionSyntax.create1 = function () { + return new ObjectLiteralExpressionSyntax(TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ObjectLiteralExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectLiteralExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectLiteralExpressionSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.propertyAssignments, this.closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.withPropertyAssignments = function (propertyAssignments) { + return this.update(this.openBraceToken, propertyAssignments, this.closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.withPropertyAssignment = function (propertyAssignment) { + return this.withPropertyAssignments(TypeScript.Syntax.separatedList([propertyAssignment])); + }; + + ObjectLiteralExpressionSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.propertyAssignments, closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.propertyAssignments.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ObjectLiteralExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectLiteralExpressionSyntax = ObjectLiteralExpressionSyntax; + + var SimplePropertyAssignmentSyntax = (function (_super) { + __extends(SimplePropertyAssignmentSyntax, _super); + function SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.colonToken = colonToken; + this.expression = expression; + } + SimplePropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitSimplePropertyAssignment(this); + }; + + SimplePropertyAssignmentSyntax.prototype.kind = function () { + return 240 /* SimplePropertyAssignment */; + }; + + SimplePropertyAssignmentSyntax.prototype.childCount = function () { + return 3; + }; + + SimplePropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.colonToken; + case 2: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SimplePropertyAssignmentSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + SimplePropertyAssignmentSyntax.prototype.update = function (propertyName, colonToken, expression) { + if (this.propertyName === propertyName && this.colonToken === colonToken && this.expression === expression) { + return this; + } + + return new SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, this.parsedInStrictMode()); + }; + + SimplePropertyAssignmentSyntax.create1 = function (propertyName, expression) { + return new SimplePropertyAssignmentSyntax(propertyName, TypeScript.Syntax.token(106 /* ColonToken */), expression, false); + }; + + SimplePropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SimplePropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SimplePropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.colonToken, this.expression); + }; + + SimplePropertyAssignmentSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.propertyName, colonToken, this.expression); + }; + + SimplePropertyAssignmentSyntax.prototype.withExpression = function (expression) { + return this.update(this.propertyName, this.colonToken, expression); + }; + + SimplePropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SimplePropertyAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SimplePropertyAssignmentSyntax = SimplePropertyAssignmentSyntax; + + var FunctionPropertyAssignmentSyntax = (function (_super) { + __extends(FunctionPropertyAssignmentSyntax, _super); + function FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + } + FunctionPropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionPropertyAssignment(this); + }; + + FunctionPropertyAssignmentSyntax.prototype.kind = function () { + return 241 /* FunctionPropertyAssignment */; + }; + + FunctionPropertyAssignmentSyntax.prototype.childCount = function () { + return 3; + }; + + FunctionPropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.callSignature; + case 2: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionPropertyAssignmentSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + FunctionPropertyAssignmentSyntax.prototype.update = function (propertyName, callSignature, block) { + if (this.propertyName === propertyName && this.callSignature === callSignature && this.block === block) { + return this; + } + + return new FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, this.parsedInStrictMode()); + }; + + FunctionPropertyAssignmentSyntax.create1 = function (propertyName) { + return new FunctionPropertyAssignmentSyntax(propertyName, CallSignatureSyntax.create1(), BlockSyntax.create1(), false); + }; + + FunctionPropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionPropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionPropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.callSignature, this.block); + }; + + FunctionPropertyAssignmentSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.propertyName, callSignature, this.block); + }; + + FunctionPropertyAssignmentSyntax.prototype.withBlock = function (block) { + return this.update(this.propertyName, this.callSignature, block); + }; + + FunctionPropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionPropertyAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionPropertyAssignmentSyntax = FunctionPropertyAssignmentSyntax; + + var FunctionExpressionSyntax = (function (_super) { + __extends(FunctionExpressionSyntax, _super); + function FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.functionKeyword = functionKeyword; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + } + FunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionExpression(this); + }; + + FunctionExpressionSyntax.prototype.kind = function () { + return 222 /* FunctionExpression */; + }; + + FunctionExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + FunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.functionKeyword; + case 1: + return this.identifier; + case 2: + return this.callSignature; + case 3: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.update = function (functionKeyword, identifier, callSignature, block) { + if (this.functionKeyword === functionKeyword && this.identifier === identifier && this.callSignature === callSignature && this.block === block) { + return this; + } + + return new FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, this.parsedInStrictMode()); + }; + + FunctionExpressionSyntax.create = function (functionKeyword, callSignature, block) { + return new FunctionExpressionSyntax(functionKeyword, null, callSignature, block, false); + }; + + FunctionExpressionSyntax.create1 = function () { + return new FunctionExpressionSyntax(TypeScript.Syntax.token(27 /* FunctionKeyword */), null, CallSignatureSyntax.create1(), BlockSyntax.create1(), false); + }; + + FunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionExpressionSyntax.prototype.withFunctionKeyword = function (functionKeyword) { + return this.update(functionKeyword, this.identifier, this.callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.functionKeyword, identifier, this.callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.functionKeyword, this.identifier, callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withBlock = function (block) { + return this.update(this.functionKeyword, this.identifier, this.callSignature, block); + }; + + FunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionExpressionSyntax = FunctionExpressionSyntax; + + var EmptyStatementSyntax = (function (_super) { + __extends(EmptyStatementSyntax, _super); + function EmptyStatementSyntax(semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.semicolonToken = semicolonToken; + } + EmptyStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitEmptyStatement(this); + }; + + EmptyStatementSyntax.prototype.kind = function () { + return 156 /* EmptyStatement */; + }; + + EmptyStatementSyntax.prototype.childCount = function () { + return 1; + }; + + EmptyStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EmptyStatementSyntax.prototype.isStatement = function () { + return true; + }; + + EmptyStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + EmptyStatementSyntax.prototype.update = function (semicolonToken) { + if (this.semicolonToken === semicolonToken) { + return this; + } + + return new EmptyStatementSyntax(semicolonToken, this.parsedInStrictMode()); + }; + + EmptyStatementSyntax.create1 = function () { + return new EmptyStatementSyntax(TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + EmptyStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EmptyStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EmptyStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(semicolonToken); + }; + + EmptyStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return EmptyStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EmptyStatementSyntax = EmptyStatementSyntax; + + var TryStatementSyntax = (function (_super) { + __extends(TryStatementSyntax, _super); + function TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.tryKeyword = tryKeyword; + this.block = block; + this.catchClause = catchClause; + this.finallyClause = finallyClause; + } + TryStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitTryStatement(this); + }; + + TryStatementSyntax.prototype.kind = function () { + return 159 /* TryStatement */; + }; + + TryStatementSyntax.prototype.childCount = function () { + return 4; + }; + + TryStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.tryKeyword; + case 1: + return this.block; + case 2: + return this.catchClause; + case 3: + return this.finallyClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TryStatementSyntax.prototype.isStatement = function () { + return true; + }; + + TryStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + TryStatementSyntax.prototype.update = function (tryKeyword, block, catchClause, finallyClause) { + if (this.tryKeyword === tryKeyword && this.block === block && this.catchClause === catchClause && this.finallyClause === finallyClause) { + return this; + } + + return new TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, this.parsedInStrictMode()); + }; + + TryStatementSyntax.create = function (tryKeyword, block) { + return new TryStatementSyntax(tryKeyword, block, null, null, false); + }; + + TryStatementSyntax.create1 = function () { + return new TryStatementSyntax(TypeScript.Syntax.token(38 /* TryKeyword */), BlockSyntax.create1(), null, null, false); + }; + + TryStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TryStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TryStatementSyntax.prototype.withTryKeyword = function (tryKeyword) { + return this.update(tryKeyword, this.block, this.catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withBlock = function (block) { + return this.update(this.tryKeyword, block, this.catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withCatchClause = function (catchClause) { + return this.update(this.tryKeyword, this.block, catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withFinallyClause = function (finallyClause) { + return this.update(this.tryKeyword, this.block, this.catchClause, finallyClause); + }; + + TryStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.block.isTypeScriptSpecific()) { + return true; + } + if (this.catchClause !== null && this.catchClause.isTypeScriptSpecific()) { + return true; + } + if (this.finallyClause !== null && this.finallyClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return TryStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TryStatementSyntax = TryStatementSyntax; + + var CatchClauseSyntax = (function (_super) { + __extends(CatchClauseSyntax, _super); + function CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.catchKeyword = catchKeyword; + this.openParenToken = openParenToken; + this.identifier = identifier; + this.typeAnnotation = typeAnnotation; + this.closeParenToken = closeParenToken; + this.block = block; + } + CatchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitCatchClause(this); + }; + + CatchClauseSyntax.prototype.kind = function () { + return 236 /* CatchClause */; + }; + + CatchClauseSyntax.prototype.childCount = function () { + return 6; + }; + + CatchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.catchKeyword; + case 1: + return this.openParenToken; + case 2: + return this.identifier; + case 3: + return this.typeAnnotation; + case 4: + return this.closeParenToken; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CatchClauseSyntax.prototype.update = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + if (this.catchKeyword === catchKeyword && this.openParenToken === openParenToken && this.identifier === identifier && this.typeAnnotation === typeAnnotation && this.closeParenToken === closeParenToken && this.block === block) { + return this; + } + + return new CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, this.parsedInStrictMode()); + }; + + CatchClauseSyntax.create = function (catchKeyword, openParenToken, identifier, closeParenToken, block) { + return new CatchClauseSyntax(catchKeyword, openParenToken, identifier, null, closeParenToken, block, false); + }; + + CatchClauseSyntax.create1 = function (identifier) { + return new CatchClauseSyntax(TypeScript.Syntax.token(17 /* CatchKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), identifier, null, TypeScript.Syntax.token(73 /* CloseParenToken */), BlockSyntax.create1(), false); + }; + + CatchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CatchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CatchClauseSyntax.prototype.withCatchKeyword = function (catchKeyword) { + return this.update(catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.catchKeyword, openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.catchKeyword, this.openParenToken, identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withBlock = function (block) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, block); + }; + + CatchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeAnnotation !== null && this.typeAnnotation.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return CatchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CatchClauseSyntax = CatchClauseSyntax; + + var FinallyClauseSyntax = (function (_super) { + __extends(FinallyClauseSyntax, _super); + function FinallyClauseSyntax(finallyKeyword, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.finallyKeyword = finallyKeyword; + this.block = block; + } + FinallyClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitFinallyClause(this); + }; + + FinallyClauseSyntax.prototype.kind = function () { + return 237 /* FinallyClause */; + }; + + FinallyClauseSyntax.prototype.childCount = function () { + return 2; + }; + + FinallyClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.finallyKeyword; + case 1: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FinallyClauseSyntax.prototype.update = function (finallyKeyword, block) { + if (this.finallyKeyword === finallyKeyword && this.block === block) { + return this; + } + + return new FinallyClauseSyntax(finallyKeyword, block, this.parsedInStrictMode()); + }; + + FinallyClauseSyntax.create1 = function () { + return new FinallyClauseSyntax(TypeScript.Syntax.token(25 /* FinallyKeyword */), BlockSyntax.create1(), false); + }; + + FinallyClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FinallyClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FinallyClauseSyntax.prototype.withFinallyKeyword = function (finallyKeyword) { + return this.update(finallyKeyword, this.block); + }; + + FinallyClauseSyntax.prototype.withBlock = function (block) { + return this.update(this.finallyKeyword, block); + }; + + FinallyClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FinallyClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FinallyClauseSyntax = FinallyClauseSyntax; + + var LabeledStatementSyntax = (function (_super) { + __extends(LabeledStatementSyntax, _super); + function LabeledStatementSyntax(identifier, colonToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.colonToken = colonToken; + this.statement = statement; + } + LabeledStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitLabeledStatement(this); + }; + + LabeledStatementSyntax.prototype.kind = function () { + return 160 /* LabeledStatement */; + }; + + LabeledStatementSyntax.prototype.childCount = function () { + return 3; + }; + + LabeledStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.colonToken; + case 2: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + LabeledStatementSyntax.prototype.isStatement = function () { + return true; + }; + + LabeledStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + LabeledStatementSyntax.prototype.update = function (identifier, colonToken, statement) { + if (this.identifier === identifier && this.colonToken === colonToken && this.statement === statement) { + return this; + } + + return new LabeledStatementSyntax(identifier, colonToken, statement, this.parsedInStrictMode()); + }; + + LabeledStatementSyntax.create1 = function (identifier, statement) { + return new LabeledStatementSyntax(identifier, TypeScript.Syntax.token(106 /* ColonToken */), statement, false); + }; + + LabeledStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + LabeledStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + LabeledStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.colonToken, this.statement); + }; + + LabeledStatementSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.identifier, colonToken, this.statement); + }; + + LabeledStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.identifier, this.colonToken, statement); + }; + + LabeledStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return LabeledStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.LabeledStatementSyntax = LabeledStatementSyntax; + + var DoStatementSyntax = (function (_super) { + __extends(DoStatementSyntax, _super); + function DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.doKeyword = doKeyword; + this.statement = statement; + this.whileKeyword = whileKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.semicolonToken = semicolonToken; + } + DoStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitDoStatement(this); + }; + + DoStatementSyntax.prototype.kind = function () { + return 161 /* DoStatement */; + }; + + DoStatementSyntax.prototype.childCount = function () { + return 7; + }; + + DoStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.doKeyword; + case 1: + return this.statement; + case 2: + return this.whileKeyword; + case 3: + return this.openParenToken; + case 4: + return this.condition; + case 5: + return this.closeParenToken; + case 6: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DoStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + DoStatementSyntax.prototype.isStatement = function () { + return true; + }; + + DoStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + DoStatementSyntax.prototype.update = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + if (this.doKeyword === doKeyword && this.statement === statement && this.whileKeyword === whileKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.semicolonToken === semicolonToken) { + return this; + } + + return new DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, this.parsedInStrictMode()); + }; + + DoStatementSyntax.create1 = function (statement, condition) { + return new DoStatementSyntax(TypeScript.Syntax.token(22 /* DoKeyword */), statement, TypeScript.Syntax.token(42 /* WhileKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + DoStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DoStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DoStatementSyntax.prototype.withDoKeyword = function (doKeyword) { + return this.update(doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.doKeyword, statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withWhileKeyword = function (whileKeyword) { + return this.update(this.doKeyword, this.statement, whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, semicolonToken); + }; + + DoStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + if (this.condition.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DoStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DoStatementSyntax = DoStatementSyntax; + + var TypeOfExpressionSyntax = (function (_super) { + __extends(TypeOfExpressionSyntax, _super); + function TypeOfExpressionSyntax(typeOfKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeOfKeyword = typeOfKeyword; + this.expression = expression; + } + TypeOfExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeOfExpression(this); + }; + + TypeOfExpressionSyntax.prototype.kind = function () { + return 171 /* TypeOfExpression */; + }; + + TypeOfExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + TypeOfExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeOfKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeOfExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + TypeOfExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + TypeOfExpressionSyntax.prototype.update = function (typeOfKeyword, expression) { + if (this.typeOfKeyword === typeOfKeyword && this.expression === expression) { + return this; + } + + return new TypeOfExpressionSyntax(typeOfKeyword, expression, this.parsedInStrictMode()); + }; + + TypeOfExpressionSyntax.create1 = function (expression) { + return new TypeOfExpressionSyntax(TypeScript.Syntax.token(39 /* TypeOfKeyword */), expression, false); + }; + + TypeOfExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeOfExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeOfExpressionSyntax.prototype.withTypeOfKeyword = function (typeOfKeyword) { + return this.update(typeOfKeyword, this.expression); + }; + + TypeOfExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.typeOfKeyword, expression); + }; + + TypeOfExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return TypeOfExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeOfExpressionSyntax = TypeOfExpressionSyntax; + + var DeleteExpressionSyntax = (function (_super) { + __extends(DeleteExpressionSyntax, _super); + function DeleteExpressionSyntax(deleteKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.deleteKeyword = deleteKeyword; + this.expression = expression; + } + DeleteExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitDeleteExpression(this); + }; + + DeleteExpressionSyntax.prototype.kind = function () { + return 170 /* DeleteExpression */; + }; + + DeleteExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + DeleteExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.deleteKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DeleteExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + DeleteExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + DeleteExpressionSyntax.prototype.update = function (deleteKeyword, expression) { + if (this.deleteKeyword === deleteKeyword && this.expression === expression) { + return this; + } + + return new DeleteExpressionSyntax(deleteKeyword, expression, this.parsedInStrictMode()); + }; + + DeleteExpressionSyntax.create1 = function (expression) { + return new DeleteExpressionSyntax(TypeScript.Syntax.token(21 /* DeleteKeyword */), expression, false); + }; + + DeleteExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DeleteExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DeleteExpressionSyntax.prototype.withDeleteKeyword = function (deleteKeyword) { + return this.update(deleteKeyword, this.expression); + }; + + DeleteExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.deleteKeyword, expression); + }; + + DeleteExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DeleteExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DeleteExpressionSyntax = DeleteExpressionSyntax; + + var VoidExpressionSyntax = (function (_super) { + __extends(VoidExpressionSyntax, _super); + function VoidExpressionSyntax(voidKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.voidKeyword = voidKeyword; + this.expression = expression; + } + VoidExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitVoidExpression(this); + }; + + VoidExpressionSyntax.prototype.kind = function () { + return 172 /* VoidExpression */; + }; + + VoidExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + VoidExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.voidKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VoidExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + VoidExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + VoidExpressionSyntax.prototype.update = function (voidKeyword, expression) { + if (this.voidKeyword === voidKeyword && this.expression === expression) { + return this; + } + + return new VoidExpressionSyntax(voidKeyword, expression, this.parsedInStrictMode()); + }; + + VoidExpressionSyntax.create1 = function (expression) { + return new VoidExpressionSyntax(TypeScript.Syntax.token(41 /* VoidKeyword */), expression, false); + }; + + VoidExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VoidExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VoidExpressionSyntax.prototype.withVoidKeyword = function (voidKeyword) { + return this.update(voidKeyword, this.expression); + }; + + VoidExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.voidKeyword, expression); + }; + + VoidExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VoidExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VoidExpressionSyntax = VoidExpressionSyntax; + + var DebuggerStatementSyntax = (function (_super) { + __extends(DebuggerStatementSyntax, _super); + function DebuggerStatementSyntax(debuggerKeyword, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.debuggerKeyword = debuggerKeyword; + this.semicolonToken = semicolonToken; + } + DebuggerStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitDebuggerStatement(this); + }; + + DebuggerStatementSyntax.prototype.kind = function () { + return 162 /* DebuggerStatement */; + }; + + DebuggerStatementSyntax.prototype.childCount = function () { + return 2; + }; + + DebuggerStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.debuggerKeyword; + case 1: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DebuggerStatementSyntax.prototype.isStatement = function () { + return true; + }; + + DebuggerStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + DebuggerStatementSyntax.prototype.update = function (debuggerKeyword, semicolonToken) { + if (this.debuggerKeyword === debuggerKeyword && this.semicolonToken === semicolonToken) { + return this; + } + + return new DebuggerStatementSyntax(debuggerKeyword, semicolonToken, this.parsedInStrictMode()); + }; + + DebuggerStatementSyntax.create1 = function () { + return new DebuggerStatementSyntax(TypeScript.Syntax.token(19 /* DebuggerKeyword */), TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + DebuggerStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DebuggerStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DebuggerStatementSyntax.prototype.withDebuggerKeyword = function (debuggerKeyword) { + return this.update(debuggerKeyword, this.semicolonToken); + }; + + DebuggerStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.debuggerKeyword, semicolonToken); + }; + + DebuggerStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return DebuggerStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DebuggerStatementSyntax = DebuggerStatementSyntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxRewriter = (function () { + function SyntaxRewriter() { + } + SyntaxRewriter.prototype.visitToken = function (token) { + return token; + }; + + SyntaxRewriter.prototype.visitNode = function (node) { + return node.accept(this); + }; + + SyntaxRewriter.prototype.visitNodeOrToken = function (node) { + return node.isToken() ? this.visitToken(node) : this.visitNode(node); + }; + + SyntaxRewriter.prototype.visitList = function (list) { + var newItems = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + var newItem = this.visitNodeOrToken(item); + + if (item !== newItem && newItems === null) { + newItems = []; + for (var j = 0; j < i; j++) { + newItems.push(list.childAt(j)); + } + } + + if (newItems) { + newItems.push(newItem); + } + } + + return newItems === null ? list : TypeScript.Syntax.list(newItems); + }; + + SyntaxRewriter.prototype.visitSeparatedList = function (list) { + var newItems = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + var newItem = item.isToken() ? this.visitToken(item) : this.visitNode(item); + + if (item !== newItem && newItems === null) { + newItems = []; + for (var j = 0; j < i; j++) { + newItems.push(list.childAt(j)); + } + } + + if (newItems) { + newItems.push(newItem); + } + } + + return newItems === null ? list : TypeScript.Syntax.separatedList(newItems); + }; + + SyntaxRewriter.prototype.visitSourceUnit = function (node) { + return node.update(this.visitList(node.moduleElements), this.visitToken(node.endOfFileToken)); + }; + + SyntaxRewriter.prototype.visitExternalModuleReference = function (node) { + return node.update(this.visitToken(node.requireKeyword), this.visitToken(node.openParenToken), this.visitToken(node.stringLiteral), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitModuleNameModuleReference = function (node) { + return node.update(this.visitNodeOrToken(node.moduleName)); + }; + + SyntaxRewriter.prototype.visitImportDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.importKeyword), this.visitToken(node.identifier), this.visitToken(node.equalsToken), this.visitNodeOrToken(node.moduleReference), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitExportAssignment = function (node) { + return node.update(this.visitToken(node.exportKeyword), this.visitToken(node.equalsToken), this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitClassDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.classKeyword), this.visitToken(node.identifier), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitList(node.heritageClauses), this.visitToken(node.openBraceToken), this.visitList(node.classElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitInterfaceDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.interfaceKeyword), this.visitToken(node.identifier), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitList(node.heritageClauses), this.visitNode(node.body)); + }; + + SyntaxRewriter.prototype.visitHeritageClause = function (node) { + return node.update(node.kind(), this.visitToken(node.extendsOrImplementsKeyword), this.visitSeparatedList(node.typeNames)); + }; + + SyntaxRewriter.prototype.visitModuleDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.moduleKeyword), node.name === null ? null : this.visitNodeOrToken(node.name), node.stringLiteral === null ? null : this.visitToken(node.stringLiteral), this.visitToken(node.openBraceToken), this.visitList(node.moduleElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitFunctionDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.functionKeyword), this.visitToken(node.identifier), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitVariableStatement = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.variableDeclaration), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitVariableDeclaration = function (node) { + return node.update(this.visitToken(node.varKeyword), this.visitSeparatedList(node.variableDeclarators)); + }; + + SyntaxRewriter.prototype.visitVariableDeclarator = function (node) { + return node.update(this.visitToken(node.propertyName), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitEqualsValueClause = function (node) { + return node.update(this.visitToken(node.equalsToken), this.visitNodeOrToken(node.value)); + }; + + SyntaxRewriter.prototype.visitPrefixUnaryExpression = function (node) { + return node.update(node.kind(), this.visitToken(node.operatorToken), this.visitNodeOrToken(node.operand)); + }; + + SyntaxRewriter.prototype.visitArrayLiteralExpression = function (node) { + return node.update(this.visitToken(node.openBracketToken), this.visitSeparatedList(node.expressions), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitOmittedExpression = function (node) { + return node; + }; + + SyntaxRewriter.prototype.visitParenthesizedExpression = function (node) { + return node.update(this.visitToken(node.openParenToken), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitSimpleArrowFunctionExpression = function (node) { + return node.update(this.visitToken(node.identifier), this.visitToken(node.equalsGreaterThanToken), node.block === null ? null : this.visitNode(node.block), node.expression === null ? null : this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + return node.update(this.visitNode(node.callSignature), this.visitToken(node.equalsGreaterThanToken), node.block === null ? null : this.visitNode(node.block), node.expression === null ? null : this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitQualifiedName = function (node) { + return node.update(this.visitNodeOrToken(node.left), this.visitToken(node.dotToken), this.visitToken(node.right)); + }; + + SyntaxRewriter.prototype.visitTypeArgumentList = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitSeparatedList(node.typeArguments), this.visitToken(node.greaterThanToken)); + }; + + SyntaxRewriter.prototype.visitConstructorType = function (node) { + return node.update(this.visitToken(node.newKeyword), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitFunctionType = function (node) { + return node.update(node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitObjectType = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitSeparatedList(node.typeMembers), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitArrayType = function (node) { + return node.update(this.visitNodeOrToken(node.type), this.visitToken(node.openBracketToken), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitGenericType = function (node) { + return node.update(this.visitNodeOrToken(node.name), this.visitNode(node.typeArgumentList)); + }; + + SyntaxRewriter.prototype.visitTypeQuery = function (node) { + return node.update(this.visitToken(node.typeOfKeyword), this.visitNodeOrToken(node.name)); + }; + + SyntaxRewriter.prototype.visitTypeAnnotation = function (node) { + return node.update(this.visitToken(node.colonToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitBlock = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitList(node.statements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitParameter = function (node) { + return node.update(node.dotDotDotToken === null ? null : this.visitToken(node.dotDotDotToken), this.visitList(node.modifiers), this.visitToken(node.identifier), node.questionToken === null ? null : this.visitToken(node.questionToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitMemberAccessExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.dotToken), this.visitToken(node.name)); + }; + + SyntaxRewriter.prototype.visitPostfixUnaryExpression = function (node) { + return node.update(node.kind(), this.visitNodeOrToken(node.operand), this.visitToken(node.operatorToken)); + }; + + SyntaxRewriter.prototype.visitElementAccessExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.openBracketToken), this.visitNodeOrToken(node.argumentExpression), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitInvocationExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitNode(node.argumentList)); + }; + + SyntaxRewriter.prototype.visitArgumentList = function (node) { + return node.update(node.typeArgumentList === null ? null : this.visitNode(node.typeArgumentList), this.visitToken(node.openParenToken), this.visitSeparatedList(node.arguments), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitBinaryExpression = function (node) { + return node.update(node.kind(), this.visitNodeOrToken(node.left), this.visitToken(node.operatorToken), this.visitNodeOrToken(node.right)); + }; + + SyntaxRewriter.prototype.visitConditionalExpression = function (node) { + return node.update(this.visitNodeOrToken(node.condition), this.visitToken(node.questionToken), this.visitNodeOrToken(node.whenTrue), this.visitToken(node.colonToken), this.visitNodeOrToken(node.whenFalse)); + }; + + SyntaxRewriter.prototype.visitConstructSignature = function (node) { + return node.update(this.visitToken(node.newKeyword), this.visitNode(node.callSignature)); + }; + + SyntaxRewriter.prototype.visitMethodSignature = function (node) { + return node.update(this.visitToken(node.propertyName), node.questionToken === null ? null : this.visitToken(node.questionToken), this.visitNode(node.callSignature)); + }; + + SyntaxRewriter.prototype.visitIndexSignature = function (node) { + return node.update(this.visitToken(node.openBracketToken), this.visitNode(node.parameter), this.visitToken(node.closeBracketToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitPropertySignature = function (node) { + return node.update(this.visitToken(node.propertyName), node.questionToken === null ? null : this.visitToken(node.questionToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitCallSignature = function (node) { + return node.update(node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitParameterList = function (node) { + return node.update(this.visitToken(node.openParenToken), this.visitSeparatedList(node.parameters), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitTypeParameterList = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitSeparatedList(node.typeParameters), this.visitToken(node.greaterThanToken)); + }; + + SyntaxRewriter.prototype.visitTypeParameter = function (node) { + return node.update(this.visitToken(node.identifier), node.constraint === null ? null : this.visitNode(node.constraint)); + }; + + SyntaxRewriter.prototype.visitConstraint = function (node) { + return node.update(this.visitToken(node.extendsKeyword), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitElseClause = function (node) { + return node.update(this.visitToken(node.elseKeyword), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitIfStatement = function (node) { + return node.update(this.visitToken(node.ifKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement), node.elseClause === null ? null : this.visitNode(node.elseClause)); + }; + + SyntaxRewriter.prototype.visitExpressionStatement = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitConstructorDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.constructorKeyword), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitMemberFunctionDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.propertyName), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitGetAccessor = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.getKeyword), this.visitToken(node.propertyName), this.visitNode(node.parameterList), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitSetAccessor = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.setKeyword), this.visitToken(node.propertyName), this.visitNode(node.parameterList), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitMemberVariableDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.variableDeclarator), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitIndexMemberDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.indexSignature), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitThrowStatement = function (node) { + return node.update(this.visitToken(node.throwKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitReturnStatement = function (node) { + return node.update(this.visitToken(node.returnKeyword), node.expression === null ? null : this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitObjectCreationExpression = function (node) { + return node.update(this.visitToken(node.newKeyword), this.visitNodeOrToken(node.expression), node.argumentList === null ? null : this.visitNode(node.argumentList)); + }; + + SyntaxRewriter.prototype.visitSwitchStatement = function (node) { + return node.update(this.visitToken(node.switchKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken), this.visitToken(node.openBraceToken), this.visitList(node.switchClauses), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitCaseSwitchClause = function (node) { + return node.update(this.visitToken(node.caseKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.colonToken), this.visitList(node.statements)); + }; + + SyntaxRewriter.prototype.visitDefaultSwitchClause = function (node) { + return node.update(this.visitToken(node.defaultKeyword), this.visitToken(node.colonToken), this.visitList(node.statements)); + }; + + SyntaxRewriter.prototype.visitBreakStatement = function (node) { + return node.update(this.visitToken(node.breakKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitContinueStatement = function (node) { + return node.update(this.visitToken(node.continueKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitForStatement = function (node) { + return node.update(this.visitToken(node.forKeyword), this.visitToken(node.openParenToken), node.variableDeclaration === null ? null : this.visitNode(node.variableDeclaration), node.initializer === null ? null : this.visitNodeOrToken(node.initializer), this.visitToken(node.firstSemicolonToken), node.condition === null ? null : this.visitNodeOrToken(node.condition), this.visitToken(node.secondSemicolonToken), node.incrementor === null ? null : this.visitNodeOrToken(node.incrementor), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitForInStatement = function (node) { + return node.update(this.visitToken(node.forKeyword), this.visitToken(node.openParenToken), node.variableDeclaration === null ? null : this.visitNode(node.variableDeclaration), node.left === null ? null : this.visitNodeOrToken(node.left), this.visitToken(node.inKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitWhileStatement = function (node) { + return node.update(this.visitToken(node.whileKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitWithStatement = function (node) { + return node.update(this.visitToken(node.withKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitEnumDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.enumKeyword), this.visitToken(node.identifier), this.visitToken(node.openBraceToken), this.visitSeparatedList(node.enumElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitEnumElement = function (node) { + return node.update(this.visitToken(node.propertyName), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitCastExpression = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitNodeOrToken(node.type), this.visitToken(node.greaterThanToken), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitObjectLiteralExpression = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitSeparatedList(node.propertyAssignments), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitSimplePropertyAssignment = function (node) { + return node.update(this.visitToken(node.propertyName), this.visitToken(node.colonToken), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitFunctionPropertyAssignment = function (node) { + return node.update(this.visitToken(node.propertyName), this.visitNode(node.callSignature), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitFunctionExpression = function (node) { + return node.update(this.visitToken(node.functionKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitNode(node.callSignature), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitEmptyStatement = function (node) { + return node.update(this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitTryStatement = function (node) { + return node.update(this.visitToken(node.tryKeyword), this.visitNode(node.block), node.catchClause === null ? null : this.visitNode(node.catchClause), node.finallyClause === null ? null : this.visitNode(node.finallyClause)); + }; + + SyntaxRewriter.prototype.visitCatchClause = function (node) { + return node.update(this.visitToken(node.catchKeyword), this.visitToken(node.openParenToken), this.visitToken(node.identifier), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), this.visitToken(node.closeParenToken), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitFinallyClause = function (node) { + return node.update(this.visitToken(node.finallyKeyword), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitLabeledStatement = function (node) { + return node.update(this.visitToken(node.identifier), this.visitToken(node.colonToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitDoStatement = function (node) { + return node.update(this.visitToken(node.doKeyword), this.visitNodeOrToken(node.statement), this.visitToken(node.whileKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitTypeOfExpression = function (node) { + return node.update(this.visitToken(node.typeOfKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitDeleteExpression = function (node) { + return node.update(this.visitToken(node.deleteKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitVoidExpression = function (node) { + return node.update(this.visitToken(node.voidKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitDebuggerStatement = function (node) { + return node.update(this.visitToken(node.debuggerKeyword), this.visitToken(node.semicolonToken)); + }; + return SyntaxRewriter; + })(); + TypeScript.SyntaxRewriter = SyntaxRewriter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxDedenter = (function (_super) { + __extends(SyntaxDedenter, _super); + function SyntaxDedenter(dedentFirstToken, dedentationAmount, minimumIndent, options) { + _super.call(this); + this.dedentationAmount = dedentationAmount; + this.minimumIndent = minimumIndent; + this.options = options; + this.lastTriviaWasNewLine = dedentFirstToken; + } + SyntaxDedenter.prototype.abort = function () { + this.lastTriviaWasNewLine = false; + this.dedentationAmount = 0; + }; + + SyntaxDedenter.prototype.isAborted = function () { + return this.dedentationAmount === 0; + }; + + SyntaxDedenter.prototype.visitToken = function (token) { + if (token.width() === 0) { + return token; + } + + var result = token; + if (this.lastTriviaWasNewLine) { + result = token.withLeadingTrivia(this.dedentTriviaList(token.leadingTrivia())); + } + + if (this.isAborted()) { + return token; + } + + this.lastTriviaWasNewLine = token.hasTrailingNewLine(); + return result; + }; + + SyntaxDedenter.prototype.dedentTriviaList = function (triviaList) { + var result = []; + var dedentNextWhitespace = true; + + for (var i = 0, n = triviaList.count(); i < n && !this.isAborted(); i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + var dedentThisTrivia = dedentNextWhitespace; + dedentNextWhitespace = false; + + if (dedentThisTrivia) { + if (trivia.kind() === 4 /* WhitespaceTrivia */) { + var hasFollowingNewLine = (i < triviaList.count() - 1) && triviaList.syntaxTriviaAt(i + 1).kind() === 5 /* NewLineTrivia */; + result.push(this.dedentWhitespace(trivia, hasFollowingNewLine)); + continue; + } else if (trivia.kind() !== 5 /* NewLineTrivia */) { + this.abort(); + break; + } + } + + if (trivia.kind() === 6 /* MultiLineCommentTrivia */) { + result.push(this.dedentMultiLineComment(trivia)); + continue; + } + + result.push(trivia); + if (trivia.kind() === 5 /* NewLineTrivia */) { + dedentNextWhitespace = true; + } + } + + if (dedentNextWhitespace) { + this.abort(); + } + + if (this.isAborted()) { + return triviaList; + } + + return TypeScript.Syntax.triviaList(result); + }; + + SyntaxDedenter.prototype.dedentSegment = function (segment, hasFollowingNewLineTrivia) { + var firstNonWhitespacePosition = TypeScript.Indentation.firstNonWhitespacePosition(segment); + + if (firstNonWhitespacePosition === segment.length) { + if (hasFollowingNewLineTrivia) { + return ""; + } + } else if (TypeScript.CharacterInfo.isLineTerminator(segment.charCodeAt(firstNonWhitespacePosition))) { + return segment.substring(firstNonWhitespacePosition); + } + + var firstNonWhitespaceColumn = TypeScript.Indentation.columnForPositionInString(segment, firstNonWhitespacePosition, this.options); + + var newFirstNonWhitespaceColumn = TypeScript.MathPrototype.min(firstNonWhitespaceColumn, TypeScript.MathPrototype.max(firstNonWhitespaceColumn - this.dedentationAmount, this.minimumIndent)); + + if (newFirstNonWhitespaceColumn === firstNonWhitespaceColumn) { + this.abort(); + return segment; + } + + this.dedentationAmount = firstNonWhitespaceColumn - newFirstNonWhitespaceColumn; + TypeScript.Debug.assert(this.dedentationAmount >= 0); + + var indentationString = TypeScript.Indentation.indentationString(newFirstNonWhitespaceColumn, this.options); + + return indentationString + segment.substring(firstNonWhitespacePosition); + }; + + SyntaxDedenter.prototype.dedentWhitespace = function (trivia, hasFollowingNewLineTrivia) { + var newIndentation = this.dedentSegment(trivia.fullText(), hasFollowingNewLineTrivia); + return TypeScript.Syntax.whitespace(newIndentation); + }; + + SyntaxDedenter.prototype.dedentMultiLineComment = function (trivia) { + var segments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + if (segments.length === 1) { + return trivia; + } + + for (var i = 1; i < segments.length; i++) { + var segment = segments[i]; + segments[i] = this.dedentSegment(segment, false); + } + + var result = segments.join(""); + + return TypeScript.Syntax.multiLineComment(result); + }; + + SyntaxDedenter.dedentNode = function (node, dedentFirstToken, dedentAmount, minimumIndent, options) { + var dedenter = new SyntaxDedenter(dedentFirstToken, dedentAmount, minimumIndent, options); + var result = node.accept(dedenter); + + if (dedenter.isAborted()) { + return node; + } + + return result; + }; + return SyntaxDedenter; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxDedenter = SyntaxDedenter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxIndenter = (function (_super) { + __extends(SyntaxIndenter, _super); + function SyntaxIndenter(indentFirstToken, indentationAmount, options) { + _super.call(this); + this.indentationAmount = indentationAmount; + this.options = options; + this.lastTriviaWasNewLine = indentFirstToken; + this.indentationTrivia = TypeScript.Indentation.indentationTrivia(this.indentationAmount, this.options); + } + SyntaxIndenter.prototype.visitToken = function (token) { + if (token.width() === 0) { + return token; + } + + var result = token; + if (this.lastTriviaWasNewLine) { + result = token.withLeadingTrivia(this.indentTriviaList(token.leadingTrivia())); + } + + this.lastTriviaWasNewLine = token.hasTrailingNewLine(); + return result; + }; + + SyntaxIndenter.prototype.indentTriviaList = function (triviaList) { + var result = []; + + var indentNextTrivia = true; + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + var indentThisTrivia = indentNextTrivia; + indentNextTrivia = false; + + switch (trivia.kind()) { + case 6 /* MultiLineCommentTrivia */: + this.indentMultiLineComment(trivia, indentThisTrivia, result); + continue; + + case 7 /* SingleLineCommentTrivia */: + case 8 /* SkippedTokenTrivia */: + this.indentSingleLineOrSkippedText(trivia, indentThisTrivia, result); + continue; + + case 4 /* WhitespaceTrivia */: + this.indentWhitespace(trivia, indentThisTrivia, result); + continue; + + case 5 /* NewLineTrivia */: + result.push(trivia); + indentNextTrivia = true; + continue; + + default: + throw TypeScript.Errors.invalidOperation(); + } + } + + if (indentNextTrivia) { + result.push(this.indentationTrivia); + } + + return TypeScript.Syntax.triviaList(result); + }; + + SyntaxIndenter.prototype.indentSegment = function (segment) { + var firstNonWhitespacePosition = TypeScript.Indentation.firstNonWhitespacePosition(segment); + + if (firstNonWhitespacePosition < segment.length && TypeScript.CharacterInfo.isLineTerminator(segment.charCodeAt(firstNonWhitespacePosition))) { + return segment; + } + + var firstNonWhitespaceColumn = TypeScript.Indentation.columnForPositionInString(segment, firstNonWhitespacePosition, this.options); + + var newFirstNonWhitespaceColumn = firstNonWhitespaceColumn + this.indentationAmount; + + var indentationString = TypeScript.Indentation.indentationString(newFirstNonWhitespaceColumn, this.options); + + return indentationString + segment.substring(firstNonWhitespacePosition); + }; + + SyntaxIndenter.prototype.indentWhitespace = function (trivia, indentThisTrivia, result) { + if (!indentThisTrivia) { + result.push(trivia); + return; + } + + var newIndentation = this.indentSegment(trivia.fullText()); + result.push(TypeScript.Syntax.whitespace(newIndentation)); + }; + + SyntaxIndenter.prototype.indentSingleLineOrSkippedText = function (trivia, indentThisTrivia, result) { + if (indentThisTrivia) { + result.push(this.indentationTrivia); + } + + result.push(trivia); + }; + + SyntaxIndenter.prototype.indentMultiLineComment = function (trivia, indentThisTrivia, result) { + if (indentThisTrivia) { + result.push(this.indentationTrivia); + } + + var segments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + + for (var i = 1; i < segments.length; i++) { + segments[i] = this.indentSegment(segments[i]); + } + + var newText = segments.join(""); + result.push(TypeScript.Syntax.multiLineComment(newText)); + }; + + SyntaxIndenter.indentNode = function (node, indentFirstToken, indentAmount, options) { + var indenter = new SyntaxIndenter(indentFirstToken, indentAmount, options); + return node.accept(indenter); + }; + + SyntaxIndenter.indentNodes = function (nodes, indentFirstToken, indentAmount, options) { + var indenter = new SyntaxIndenter(indentFirstToken, indentAmount, options); + var result = TypeScript.ArrayUtilities.select(nodes, function (n) { + return n.accept(indenter); + }); + + return result; + }; + return SyntaxIndenter; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxIndenter = SyntaxIndenter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var VariableWidthTokenWithNoTrivia = (function () { + function VariableWidthTokenWithNoTrivia(fullText, kind) { + this._fullText = fullText; + this.tokenKind = kind; + } + VariableWidthTokenWithNoTrivia.prototype.clone = function () { + return new VariableWidthTokenWithNoTrivia(this._fullText, this.tokenKind); + }; + + VariableWidthTokenWithNoTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithNoTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithNoTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithNoTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithNoTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithNoTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithNoTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithNoTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithNoTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithNoTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingComment = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingComment = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithNoTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithNoTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithNoTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithNoTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithNoTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithNoTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithNoTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithNoTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithNoTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithNoTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithNoTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithNoTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithNoTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithNoTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithNoTrivia; + })(); + Syntax.VariableWidthTokenWithNoTrivia = VariableWidthTokenWithNoTrivia; + + var VariableWidthTokenWithLeadingTrivia = (function () { + function VariableWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + } + VariableWidthTokenWithLeadingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithLeadingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithLeadingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithLeadingTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithLeadingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingComment = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithLeadingTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithLeadingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithLeadingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithLeadingTrivia; + })(); + Syntax.VariableWidthTokenWithLeadingTrivia = VariableWidthTokenWithLeadingTrivia; + + var VariableWidthTokenWithTrailingTrivia = (function () { + function VariableWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._trailingTriviaInfo = trailingTriviaInfo; + } + VariableWidthTokenWithTrailingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithTrailingTrivia(this._fullText, this.tokenKind, this._trailingTriviaInfo); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithTrailingTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingComment = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithTrailingTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithTrailingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithTrailingTrivia; + })(); + Syntax.VariableWidthTokenWithTrailingTrivia = VariableWidthTokenWithTrailingTrivia; + + var VariableWidthTokenWithLeadingAndTrailingTrivia = (function () { + function VariableWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + this._trailingTriviaInfo = trailingTriviaInfo; + } + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithLeadingAndTrailingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithLeadingAndTrailingTrivia; + })(); + Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia = VariableWidthTokenWithLeadingAndTrailingTrivia; + + var FixedWidthTokenWithNoTrivia = (function () { + function FixedWidthTokenWithNoTrivia(kind) { + this.tokenKind = kind; + } + FixedWidthTokenWithNoTrivia.prototype.clone = function () { + return new FixedWidthTokenWithNoTrivia(this.tokenKind); + }; + + FixedWidthTokenWithNoTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithNoTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithNoTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithNoTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithNoTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithNoTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithNoTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithNoTrivia.prototype.fullText = function () { + return this.text(); + }; + + FixedWidthTokenWithNoTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithNoTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingComment = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithNoTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingComment = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithNoTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithNoTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithNoTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithNoTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithNoTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithNoTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithNoTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithNoTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithNoTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithNoTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithNoTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithNoTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithNoTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithNoTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithNoTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithNoTrivia; + })(); + Syntax.FixedWidthTokenWithNoTrivia = FixedWidthTokenWithNoTrivia; + + var FixedWidthTokenWithLeadingTrivia = (function () { + function FixedWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + } + FixedWidthTokenWithLeadingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithLeadingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithLeadingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithLeadingTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithLeadingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingComment = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithLeadingTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithLeadingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithLeadingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithLeadingTrivia; + })(); + Syntax.FixedWidthTokenWithLeadingTrivia = FixedWidthTokenWithLeadingTrivia; + + var FixedWidthTokenWithTrailingTrivia = (function () { + function FixedWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._trailingTriviaInfo = trailingTriviaInfo; + } + FixedWidthTokenWithTrailingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithTrailingTrivia(this._fullText, this.tokenKind, this._trailingTriviaInfo); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithTrailingTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingComment = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithTrailingTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithTrailingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithTrailingTrivia; + })(); + Syntax.FixedWidthTokenWithTrailingTrivia = FixedWidthTokenWithTrailingTrivia; + + var FixedWidthTokenWithLeadingAndTrailingTrivia = (function () { + function FixedWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + this._trailingTriviaInfo = trailingTriviaInfo; + } + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithLeadingAndTrailingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithLeadingAndTrailingTrivia; + })(); + Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia = FixedWidthTokenWithLeadingAndTrailingTrivia; + + function collectTokenTextElements(token, elements) { + token.leadingTrivia().collectTextElements(elements); + elements.push(token.text()); + token.trailingTrivia().collectTextElements(elements); + } + + function getTriviaWidth(value) { + return value >>> 2 /* TriviaFullWidthShift */; + } + + function hasTriviaComment(value) { + return (value & 2 /* TriviaCommentMask */) !== 0; + } + + function hasTriviaNewLine(value) { + return (value & 1 /* TriviaNewLineMask */) !== 0; + } + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + function isExpression(token) { + switch (token.tokenKind) { + case 11 /* IdentifierName */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NumericLiteral */: + case 14 /* StringLiteral */: + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 50 /* SuperKeyword */: + return true; + } + + return false; + } + Syntax.isExpression = isExpression; + + function realizeToken(token) { + return new RealizedToken(token.tokenKind, token.leadingTrivia(), token.text(), token.value(), token.valueText(), token.trailingTrivia()); + } + Syntax.realizeToken = realizeToken; + + function convertToIdentifierName(token) { + TypeScript.Debug.assert(TypeScript.SyntaxFacts.isAnyKeyword(token.tokenKind)); + return new RealizedToken(11 /* IdentifierName */, token.leadingTrivia(), token.text(), token.text(), token.text(), token.trailingTrivia()); + } + Syntax.convertToIdentifierName = convertToIdentifierName; + + function tokenToJSON(token) { + var result = {}; + + for (var name in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind[name] === token.kind()) { + result.kind = name; + break; + } + } + + result.width = token.width(); + if (token.fullWidth() !== token.width()) { + result.fullWidth = token.fullWidth(); + } + + result.text = token.text(); + + var value = token.value(); + if (value !== null) { + result.value = value; + result.valueText = token.valueText(); + } + + if (token.hasLeadingTrivia()) { + result.hasLeadingTrivia = true; + } + + if (token.hasLeadingComment()) { + result.hasLeadingComment = true; + } + + if (token.hasLeadingNewLine()) { + result.hasLeadingNewLine = true; + } + + if (token.hasLeadingSkippedText()) { + result.hasLeadingSkippedText = true; + } + + if (token.hasTrailingTrivia()) { + result.hasTrailingTrivia = true; + } + + if (token.hasTrailingComment()) { + result.hasTrailingComment = true; + } + + if (token.hasTrailingNewLine()) { + result.hasTrailingNewLine = true; + } + + if (token.hasTrailingSkippedText()) { + result.hasTrailingSkippedText = true; + } + + var trivia = token.leadingTrivia(); + if (trivia.count() > 0) { + result.leadingTrivia = trivia; + } + + trivia = token.trailingTrivia(); + if (trivia.count() > 0) { + result.trailingTrivia = trivia; + } + + return result; + } + Syntax.tokenToJSON = tokenToJSON; + + function value(token) { + return value1(token.tokenKind, token.text()); + } + Syntax.value = value; + + function hexValue(text, start, length) { + var intChar = 0; + for (var i = 0; i < length; i++) { + var ch2 = text.charCodeAt(start + i); + if (!TypeScript.CharacterInfo.isHexDigit(ch2)) { + break; + } + + intChar = (intChar << 4) + TypeScript.CharacterInfo.hexValue(ch2); + } + + return intChar; + } + + var characterArray = []; + + function convertEscapes(text) { + characterArray.length = 0; + var result = ""; + + for (var i = 0, n = text.length; i < n; i++) { + var ch = text.charCodeAt(i); + + if (ch === 92 /* backslash */) { + i++; + if (i < n) { + ch = text.charCodeAt(i); + switch (ch) { + case 48 /* _0 */: + characterArray.push(0 /* nullCharacter */); + continue; + + case 98 /* b */: + characterArray.push(8 /* backspace */); + continue; + + case 102 /* f */: + characterArray.push(12 /* formFeed */); + continue; + + case 110 /* n */: + characterArray.push(10 /* lineFeed */); + continue; + + case 114 /* r */: + characterArray.push(13 /* carriageReturn */); + continue; + + case 116 /* t */: + characterArray.push(9 /* tab */); + continue; + + case 118 /* v */: + characterArray.push(11 /* verticalTab */); + continue; + + case 120 /* x */: + characterArray.push(hexValue(text, i + 1, 2)); + i += 2; + continue; + + case 117 /* u */: + characterArray.push(hexValue(text, i + 1, 4)); + i += 4; + continue; + + case 13 /* carriageReturn */: + var nextIndex = i + 1; + if (nextIndex < text.length && text.charCodeAt(nextIndex) === 10 /* lineFeed */) { + i++; + } + continue; + + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + continue; + + default: + } + } + } + + characterArray.push(ch); + + if (i && !(i % 1024)) { + result = result.concat(String.fromCharCode.apply(null, characterArray)); + characterArray.length = 0; + } + } + + if (characterArray.length) { + result = result.concat(String.fromCharCode.apply(null, characterArray)); + } + + return result; + } + + function massageEscapes(text) { + return text.indexOf("\\") >= 0 ? convertEscapes(text) : text; + } + Syntax.massageEscapes = massageEscapes; + + function value1(kind, text) { + if (kind === 11 /* IdentifierName */) { + return massageEscapes(text); + } + + switch (kind) { + case 37 /* TrueKeyword */: + return true; + case 24 /* FalseKeyword */: + return false; + case 32 /* NullKeyword */: + return null; + } + + if (TypeScript.SyntaxFacts.isAnyKeyword(kind) || TypeScript.SyntaxFacts.isAnyPunctuation(kind)) { + return TypeScript.SyntaxFacts.getText(kind); + } + + if (kind === 13 /* NumericLiteral */) { + return TypeScript.IntegerUtilities.isHexInteger(text) ? parseInt(text, 16) : parseFloat(text); + } else if (kind === 14 /* StringLiteral */) { + if (text.length > 1 && text.charCodeAt(text.length - 1) === text.charCodeAt(0)) { + return massageEscapes(text.substr(1, text.length - 2)); + } else { + return massageEscapes(text.substr(1)); + } + } else if (kind === 12 /* RegularExpressionLiteral */) { + return regularExpressionValue(text); + } else if (kind === 10 /* EndOfFileToken */ || kind === 9 /* ErrorToken */) { + return null; + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + + function regularExpressionValue(text) { + try { + var lastSlash = text.lastIndexOf("/"); + var body = text.substring(1, lastSlash); + var flags = text.substring(lastSlash + 1); + return new RegExp(body, flags); + } catch (e) { + return null; + } + } + + function valueText1(kind, text) { + var value = value1(kind, text); + return value === null ? "" : value.toString(); + } + + function valueText(token) { + var value = token.value(); + return value === null ? "" : value.toString(); + } + Syntax.valueText = valueText; + + var EmptyToken = (function () { + function EmptyToken(kind) { + this.tokenKind = kind; + } + EmptyToken.prototype.clone = function () { + return new EmptyToken(this.tokenKind); + }; + + EmptyToken.prototype.kind = function () { + return this.tokenKind; + }; + + EmptyToken.prototype.isToken = function () { + return true; + }; + EmptyToken.prototype.isNode = function () { + return false; + }; + EmptyToken.prototype.isList = function () { + return false; + }; + EmptyToken.prototype.isSeparatedList = function () { + return false; + }; + + EmptyToken.prototype.childCount = function () { + return 0; + }; + + EmptyToken.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptyToken.prototype.toJSON = function (key) { + return tokenToJSON(this); + }; + EmptyToken.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + + EmptyToken.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + EmptyToken.prototype.firstToken = function () { + return this; + }; + EmptyToken.prototype.lastToken = function () { + return this; + }; + EmptyToken.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptyToken.prototype.isIncrementallyUnusable = function () { + return true; + }; + + EmptyToken.prototype.fullWidth = function () { + return 0; + }; + EmptyToken.prototype.width = function () { + return 0; + }; + EmptyToken.prototype.text = function () { + return ""; + }; + EmptyToken.prototype.fullText = function () { + return ""; + }; + EmptyToken.prototype.value = function () { + return null; + }; + EmptyToken.prototype.valueText = function () { + return ""; + }; + + EmptyToken.prototype.hasLeadingTrivia = function () { + return false; + }; + EmptyToken.prototype.hasLeadingComment = function () { + return false; + }; + EmptyToken.prototype.hasLeadingNewLine = function () { + return false; + }; + EmptyToken.prototype.hasLeadingSkippedText = function () { + return false; + }; + EmptyToken.prototype.leadingTriviaWidth = function () { + return 0; + }; + EmptyToken.prototype.hasTrailingTrivia = function () { + return false; + }; + EmptyToken.prototype.hasTrailingComment = function () { + return false; + }; + EmptyToken.prototype.hasTrailingNewLine = function () { + return false; + }; + EmptyToken.prototype.hasTrailingSkippedText = function () { + return false; + }; + EmptyToken.prototype.hasSkippedToken = function () { + return false; + }; + + EmptyToken.prototype.trailingTriviaWidth = function () { + return 0; + }; + EmptyToken.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + EmptyToken.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + EmptyToken.prototype.realize = function () { + return realizeToken(this); + }; + EmptyToken.prototype.collectTextElements = function (elements) { + }; + + EmptyToken.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + EmptyToken.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + EmptyToken.prototype.isExpression = function () { + return isExpression(this); + }; + + EmptyToken.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + EmptyToken.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + EmptyToken.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + EmptyToken.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return EmptyToken; + })(); + + function emptyToken(kind) { + return new EmptyToken(kind); + } + Syntax.emptyToken = emptyToken; + + var RealizedToken = (function () { + function RealizedToken(tokenKind, leadingTrivia, text, value, valueText, trailingTrivia) { + this.tokenKind = tokenKind; + this._leadingTrivia = leadingTrivia; + this._text = text; + this._value = value; + this._valueText = valueText; + this._trailingTrivia = trailingTrivia; + } + RealizedToken.prototype.clone = function () { + return new RealizedToken(this.tokenKind, this._leadingTrivia, this._text, this._value, this._valueText, this._trailingTrivia); + }; + + RealizedToken.prototype.kind = function () { + return this.tokenKind; + }; + RealizedToken.prototype.toJSON = function (key) { + return tokenToJSON(this); + }; + RealizedToken.prototype.firstToken = function () { + return this; + }; + RealizedToken.prototype.lastToken = function () { + return this; + }; + RealizedToken.prototype.isTypeScriptSpecific = function () { + return false; + }; + + RealizedToken.prototype.isIncrementallyUnusable = function () { + return true; + }; + + RealizedToken.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + + RealizedToken.prototype.childCount = function () { + return 0; + }; + + RealizedToken.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + RealizedToken.prototype.isToken = function () { + return true; + }; + RealizedToken.prototype.isNode = function () { + return false; + }; + RealizedToken.prototype.isList = function () { + return false; + }; + RealizedToken.prototype.isSeparatedList = function () { + return false; + }; + RealizedToken.prototype.isTrivia = function () { + return false; + }; + RealizedToken.prototype.isTriviaList = function () { + return false; + }; + + RealizedToken.prototype.fullWidth = function () { + return this._leadingTrivia.fullWidth() + this.width() + this._trailingTrivia.fullWidth(); + }; + RealizedToken.prototype.width = function () { + return this.text().length; + }; + + RealizedToken.prototype.text = function () { + return this._text; + }; + RealizedToken.prototype.fullText = function () { + return this._leadingTrivia.fullText() + this.text() + this._trailingTrivia.fullText(); + }; + + RealizedToken.prototype.value = function () { + return this._value; + }; + RealizedToken.prototype.valueText = function () { + return this._valueText; + }; + + RealizedToken.prototype.hasLeadingTrivia = function () { + return this._leadingTrivia.count() > 0; + }; + RealizedToken.prototype.hasLeadingComment = function () { + return this._leadingTrivia.hasComment(); + }; + RealizedToken.prototype.hasLeadingNewLine = function () { + return this._leadingTrivia.hasNewLine(); + }; + RealizedToken.prototype.hasLeadingSkippedText = function () { + return this._leadingTrivia.hasSkippedToken(); + }; + RealizedToken.prototype.leadingTriviaWidth = function () { + return this._leadingTrivia.fullWidth(); + }; + + RealizedToken.prototype.hasTrailingTrivia = function () { + return this._trailingTrivia.count() > 0; + }; + RealizedToken.prototype.hasTrailingComment = function () { + return this._trailingTrivia.hasComment(); + }; + RealizedToken.prototype.hasTrailingNewLine = function () { + return this._trailingTrivia.hasNewLine(); + }; + RealizedToken.prototype.hasTrailingSkippedText = function () { + return this._trailingTrivia.hasSkippedToken(); + }; + RealizedToken.prototype.trailingTriviaWidth = function () { + return this._trailingTrivia.fullWidth(); + }; + + RealizedToken.prototype.hasSkippedToken = function () { + return this.hasLeadingSkippedText() || this.hasTrailingSkippedText(); + }; + + RealizedToken.prototype.leadingTrivia = function () { + return this._leadingTrivia; + }; + RealizedToken.prototype.trailingTrivia = function () { + return this._trailingTrivia; + }; + + RealizedToken.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + RealizedToken.prototype.collectTextElements = function (elements) { + this.leadingTrivia().collectTextElements(elements); + elements.push(this.text()); + this.trailingTrivia().collectTextElements(elements); + }; + + RealizedToken.prototype.withLeadingTrivia = function (leadingTrivia) { + return new RealizedToken(this.tokenKind, leadingTrivia, this._text, this._value, this._valueText, this._trailingTrivia); + }; + + RealizedToken.prototype.withTrailingTrivia = function (trailingTrivia) { + return new RealizedToken(this.tokenKind, this._leadingTrivia, this._text, this._value, this._valueText, trailingTrivia); + }; + + RealizedToken.prototype.isExpression = function () { + return isExpression(this); + }; + + RealizedToken.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + RealizedToken.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + RealizedToken.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + RealizedToken.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return RealizedToken; + })(); + + function token(kind, info) { + if (typeof info === "undefined") { info = null; } + var text = (info !== null && info.text !== undefined) ? info.text : TypeScript.SyntaxFacts.getText(kind); + + return new RealizedToken(kind, Syntax.triviaList(info === null ? null : info.leadingTrivia), text, value1(kind, text), valueText1(kind, text), Syntax.triviaList(info === null ? null : info.trailingTrivia)); + } + Syntax.token = token; + + function identifier(text, info) { + if (typeof info === "undefined") { info = null; } + info = info || {}; + info.text = text; + return token(11 /* IdentifierName */, info); + } + Syntax.identifier = identifier; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTokenReplacer = (function (_super) { + __extends(SyntaxTokenReplacer, _super); + function SyntaxTokenReplacer(token1, token2) { + _super.call(this); + this.token1 = token1; + this.token2 = token2; + } + SyntaxTokenReplacer.prototype.visitToken = function (token) { + if (token === this.token1) { + var result = this.token2; + this.token1 = null; + this.token2 = null; + + return result; + } + + return token; + }; + + SyntaxTokenReplacer.prototype.visitNode = function (node) { + if (this.token1 === null) { + return node; + } + + return _super.prototype.visitNode.call(this, node); + }; + + SyntaxTokenReplacer.prototype.visitList = function (list) { + if (this.token1 === null) { + return list; + } + + return _super.prototype.visitList.call(this, list); + }; + + SyntaxTokenReplacer.prototype.visitSeparatedList = function (list) { + if (this.token1 === null) { + return list; + } + + return _super.prototype.visitSeparatedList.call(this, list); + }; + return SyntaxTokenReplacer; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxTokenReplacer = SyntaxTokenReplacer; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var AbstractTrivia = (function () { + function AbstractTrivia(_kind) { + this._kind = _kind; + } + AbstractTrivia.prototype.fullWidth = function () { + throw TypeScript.Errors.abstract(); + }; + + AbstractTrivia.prototype.fullText = function () { + throw TypeScript.Errors.abstract(); + }; + + AbstractTrivia.prototype.skippedToken = function () { + throw TypeScript.Errors.abstract(); + }; + + AbstractTrivia.prototype.toJSON = function (key) { + var result = {}; + + for (var name in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind[name] === this._kind) { + result.kind = name; + break; + } + } + + if (this.isSkippedToken()) { + result.skippedToken = this.skippedToken(); + } else { + result.text = this.fullText(); + } + return result; + }; + + AbstractTrivia.prototype.kind = function () { + return this._kind; + }; + + AbstractTrivia.prototype.isWhitespace = function () { + return this.kind() === 4 /* WhitespaceTrivia */; + }; + + AbstractTrivia.prototype.isComment = function () { + return this.kind() === 7 /* SingleLineCommentTrivia */ || this.kind() === 6 /* MultiLineCommentTrivia */; + }; + + AbstractTrivia.prototype.isNewLine = function () { + return this.kind() === 5 /* NewLineTrivia */; + }; + + AbstractTrivia.prototype.isSkippedToken = function () { + return this.kind() === 8 /* SkippedTokenTrivia */; + }; + + AbstractTrivia.prototype.collectTextElements = function (elements) { + elements.push(this.fullText()); + }; + return AbstractTrivia; + })(); + + var NormalTrivia = (function (_super) { + __extends(NormalTrivia, _super); + function NormalTrivia(kind, _text) { + _super.call(this, kind); + this._text = _text; + } + NormalTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + + NormalTrivia.prototype.fullText = function () { + return this._text; + }; + + NormalTrivia.prototype.skippedToken = function () { + throw TypeScript.Errors.invalidOperation(); + }; + return NormalTrivia; + })(AbstractTrivia); + + var SkippedTokenTrivia = (function (_super) { + __extends(SkippedTokenTrivia, _super); + function SkippedTokenTrivia(_skippedToken) { + _super.call(this, 8 /* SkippedTokenTrivia */); + this._skippedToken = _skippedToken; + } + SkippedTokenTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + + SkippedTokenTrivia.prototype.fullText = function () { + return this.skippedToken().fullText(); + }; + + SkippedTokenTrivia.prototype.skippedToken = function () { + return this._skippedToken; + }; + return SkippedTokenTrivia; + })(AbstractTrivia); + + var DeferredTrivia = (function (_super) { + __extends(DeferredTrivia, _super); + function DeferredTrivia(kind, _text, _fullStart, _fullWidth) { + _super.call(this, kind); + this._text = _text; + this._fullStart = _fullStart; + this._fullWidth = _fullWidth; + this._fullText = null; + } + DeferredTrivia.prototype.fullWidth = function () { + return this._fullWidth; + }; + + DeferredTrivia.prototype.fullText = function () { + if (!this._fullText) { + this._fullText = this._text.substr(this._fullStart, this._fullWidth, false); + this._text = null; + } + + return this._fullText; + }; + + DeferredTrivia.prototype.skippedToken = function () { + throw TypeScript.Errors.invalidOperation(); + }; + return DeferredTrivia; + })(AbstractTrivia); + + function deferredTrivia(kind, text, fullStart, fullWidth) { + return new DeferredTrivia(kind, text, fullStart, fullWidth); + } + Syntax.deferredTrivia = deferredTrivia; + + function trivia(kind, text) { + return new NormalTrivia(kind, text); + } + Syntax.trivia = trivia; + + function skippedTokenTrivia(token) { + TypeScript.Debug.assert(!token.hasLeadingTrivia()); + TypeScript.Debug.assert(!token.hasTrailingTrivia()); + TypeScript.Debug.assert(token.fullWidth() > 0); + return new SkippedTokenTrivia(token); + } + Syntax.skippedTokenTrivia = skippedTokenTrivia; + + function spaces(count) { + return trivia(4 /* WhitespaceTrivia */, TypeScript.StringUtilities.repeat(" ", count)); + } + Syntax.spaces = spaces; + + function whitespace(text) { + return trivia(4 /* WhitespaceTrivia */, text); + } + Syntax.whitespace = whitespace; + + function multiLineComment(text) { + return trivia(6 /* MultiLineCommentTrivia */, text); + } + Syntax.multiLineComment = multiLineComment; + + function singleLineComment(text) { + return trivia(7 /* SingleLineCommentTrivia */, text); + } + Syntax.singleLineComment = singleLineComment; + + Syntax.spaceTrivia = spaces(1); + Syntax.lineFeedTrivia = trivia(5 /* NewLineTrivia */, "\n"); + Syntax.carriageReturnTrivia = trivia(5 /* NewLineTrivia */, "\r"); + Syntax.carriageReturnLineFeedTrivia = trivia(5 /* NewLineTrivia */, "\r\n"); + + function splitMultiLineCommentTriviaIntoMultipleLines(trivia) { + var result = []; + + var triviaText = trivia.fullText(); + var currentIndex = 0; + + for (var i = 0; i < triviaText.length; i++) { + var ch = triviaText.charCodeAt(i); + + var isCarriageReturnLineFeed = false; + switch (ch) { + case 13 /* carriageReturn */: + if (i < triviaText.length - 1 && triviaText.charCodeAt(i + 1) === 10 /* lineFeed */) { + i++; + } + + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + result.push(triviaText.substring(currentIndex, i + 1)); + + currentIndex = i + 1; + continue; + } + } + + result.push(triviaText.substring(currentIndex)); + return result; + } + Syntax.splitMultiLineCommentTriviaIntoMultipleLines = splitMultiLineCommentTriviaIntoMultipleLines; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + Syntax.emptyTriviaList = { + kind: function () { + return 3 /* TriviaList */; + }, + count: function () { + return 0; + }, + syntaxTriviaAt: function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }, + last: function () { + throw TypeScript.Errors.argumentOutOfRange("index"); + }, + fullWidth: function () { + return 0; + }, + fullText: function () { + return ""; + }, + hasComment: function () { + return false; + }, + hasNewLine: function () { + return false; + }, + hasSkippedToken: function () { + return false; + }, + toJSON: function (key) { + return []; + }, + collectTextElements: function (elements) { + }, + toArray: function () { + return []; + }, + concat: function (trivia) { + return trivia; + } + }; + + function concatTrivia(list1, list2) { + if (list1.count() === 0) { + return list2; + } + + if (list2.count() === 0) { + return list1; + } + + var trivia = list1.toArray(); + trivia.push.apply(trivia, list2.toArray()); + + return triviaList(trivia); + } + + function isComment(trivia) { + return trivia.kind() === 6 /* MultiLineCommentTrivia */ || trivia.kind() === 7 /* SingleLineCommentTrivia */; + } + + var SingletonSyntaxTriviaList = (function () { + function SingletonSyntaxTriviaList(item) { + this.item = item; + } + SingletonSyntaxTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + + SingletonSyntaxTriviaList.prototype.count = function () { + return 1; + }; + + SingletonSyntaxTriviaList.prototype.syntaxTriviaAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSyntaxTriviaList.prototype.last = function () { + return this.item; + }; + + SingletonSyntaxTriviaList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSyntaxTriviaList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSyntaxTriviaList.prototype.hasComment = function () { + return isComment(this.item); + }; + + SingletonSyntaxTriviaList.prototype.hasNewLine = function () { + return this.item.kind() === 5 /* NewLineTrivia */; + }; + + SingletonSyntaxTriviaList.prototype.hasSkippedToken = function () { + return this.item.kind() === 8 /* SkippedTokenTrivia */; + }; + + SingletonSyntaxTriviaList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSyntaxTriviaList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSyntaxTriviaList.prototype.toArray = function () { + return [this.item]; + }; + + SingletonSyntaxTriviaList.prototype.concat = function (trivia) { + return concatTrivia(this, trivia); + }; + return SingletonSyntaxTriviaList; + })(); + + var NormalSyntaxTriviaList = (function () { + function NormalSyntaxTriviaList(trivia) { + this.trivia = trivia; + } + NormalSyntaxTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + + NormalSyntaxTriviaList.prototype.count = function () { + return this.trivia.length; + }; + + NormalSyntaxTriviaList.prototype.syntaxTriviaAt = function (index) { + if (index < 0 || index >= this.trivia.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.trivia[index]; + }; + + NormalSyntaxTriviaList.prototype.last = function () { + return this.trivia[this.trivia.length - 1]; + }; + + NormalSyntaxTriviaList.prototype.fullWidth = function () { + return TypeScript.ArrayUtilities.sum(this.trivia, function (t) { + return t.fullWidth(); + }); + }; + + NormalSyntaxTriviaList.prototype.fullText = function () { + var result = ""; + + for (var i = 0, n = this.trivia.length; i < n; i++) { + result += this.trivia[i].fullText(); + } + + return result; + }; + + NormalSyntaxTriviaList.prototype.hasComment = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (isComment(this.trivia[i])) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.hasNewLine = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (this.trivia[i].kind() === 5 /* NewLineTrivia */) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.hasSkippedToken = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (this.trivia[i].kind() === 8 /* SkippedTokenTrivia */) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.toJSON = function (key) { + return this.trivia; + }; + + NormalSyntaxTriviaList.prototype.collectTextElements = function (elements) { + for (var i = 0; i < this.trivia.length; i++) { + this.trivia[i].collectTextElements(elements); + } + }; + + NormalSyntaxTriviaList.prototype.toArray = function () { + return this.trivia.slice(0); + }; + + NormalSyntaxTriviaList.prototype.concat = function (trivia) { + return concatTrivia(this, trivia); + }; + return NormalSyntaxTriviaList; + })(); + + function triviaList(trivia) { + if (trivia === undefined || trivia === null || trivia.length === 0) { + return Syntax.emptyTriviaList; + } + + if (trivia.length === 1) { + return new SingletonSyntaxTriviaList(trivia[0]); + } + + return new NormalSyntaxTriviaList(trivia); + } + Syntax.triviaList = triviaList; + + Syntax.spaceTriviaList = triviaList([Syntax.spaceTrivia]); + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxUtilities = (function () { + function SyntaxUtilities() { + } + SyntaxUtilities.isAngleBracket = function (positionedElement) { + var element = positionedElement.element(); + var parent = positionedElement.parentElement(); + if (parent !== null && (element.kind() === 80 /* LessThanToken */ || element.kind() === 81 /* GreaterThanToken */)) { + switch (parent.kind()) { + case 228 /* TypeArgumentList */: + case 229 /* TypeParameterList */: + case 220 /* CastExpression */: + return true; + } + } + + return false; + }; + + SyntaxUtilities.getToken = function (list, kind) { + for (var i = 0, n = list.childCount(); i < n; i++) { + var token = list.childAt(i); + if (token.tokenKind === kind) { + return token; + } + } + + return null; + }; + + SyntaxUtilities.containsToken = function (list, kind) { + return SyntaxUtilities.getToken(list, kind) !== null; + }; + + SyntaxUtilities.hasExportKeyword = function (moduleElement) { + return SyntaxUtilities.getExportKeyword(moduleElement) !== null; + }; + + SyntaxUtilities.getExportKeyword = function (moduleElement) { + switch (moduleElement.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 148 /* VariableStatement */: + case 132 /* EnumDeclaration */: + case 128 /* InterfaceDeclaration */: + case 133 /* ImportDeclaration */: + return SyntaxUtilities.getToken(moduleElement.modifiers, 47 /* ExportKeyword */); + default: + return null; + } + }; + + SyntaxUtilities.isAmbientDeclarationSyntax = function (positionNode) { + if (!positionNode) { + return false; + } + + var node = positionNode.node(); + switch (node.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 148 /* VariableStatement */: + case 132 /* EnumDeclaration */: + if (SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */)) { + return true; + } + + case 133 /* ImportDeclaration */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 136 /* MemberVariableDeclaration */: + if (node.isClassElement() || node.isModuleElement()) { + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode()); + } + + case 243 /* EnumElement */: + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode().containingNode()); + + default: + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode()); + } + }; + return SyntaxUtilities; + })(); + TypeScript.SyntaxUtilities = SyntaxUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxVisitor = (function () { + function SyntaxVisitor() { + } + SyntaxVisitor.prototype.defaultVisit = function (node) { + return null; + }; + + SyntaxVisitor.prototype.visitToken = function (token) { + return this.defaultVisit(token); + }; + + SyntaxVisitor.prototype.visitSourceUnit = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExternalModuleReference = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitModuleNameModuleReference = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitImportDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExportAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitClassDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitInterfaceDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitHeritageClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitModuleDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableDeclarator = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEqualsValueClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPrefixUnaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArrayLiteralExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitOmittedExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParenthesizedExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitQualifiedName = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeArgumentList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructorType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArrayType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitGenericType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeQuery = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeAnnotation = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBlock = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParameter = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberAccessExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPostfixUnaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitElementAccessExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitInvocationExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArgumentList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBinaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConditionalExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMethodSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIndexSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPropertySignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCallSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParameterList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeParameterList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeParameter = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstraint = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitElseClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIfStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExpressionStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructorDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitGetAccessor = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSetAccessor = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberVariableDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIndexMemberDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitThrowStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitReturnStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectCreationExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSwitchStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCaseSwitchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDefaultSwitchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBreakStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitContinueStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitForStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitForInStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitWhileStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitWithStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEnumDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEnumElement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCastExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectLiteralExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSimplePropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEmptyStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTryStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCatchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFinallyClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitLabeledStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDoStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeOfExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDeleteExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVoidExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDebuggerStatement = function (node) { + return this.defaultVisit(node); + }; + return SyntaxVisitor; + })(); + TypeScript.SyntaxVisitor = SyntaxVisitor; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxWalker = (function () { + function SyntaxWalker() { + } + SyntaxWalker.prototype.visitToken = function (token) { + }; + + SyntaxWalker.prototype.visitNode = function (node) { + node.accept(this); + }; + + SyntaxWalker.prototype.visitNodeOrToken = function (nodeOrToken) { + if (nodeOrToken.isToken()) { + this.visitToken(nodeOrToken); + } else { + this.visitNode(nodeOrToken); + } + }; + + SyntaxWalker.prototype.visitOptionalToken = function (token) { + if (token === null) { + return; + } + + this.visitToken(token); + }; + + SyntaxWalker.prototype.visitOptionalNode = function (node) { + if (node === null) { + return; + } + + this.visitNode(node); + }; + + SyntaxWalker.prototype.visitOptionalNodeOrToken = function (nodeOrToken) { + if (nodeOrToken === null) { + return; + } + + this.visitNodeOrToken(nodeOrToken); + }; + + SyntaxWalker.prototype.visitList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + this.visitNodeOrToken(list.childAt(i)); + } + }; + + SyntaxWalker.prototype.visitSeparatedList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + this.visitNodeOrToken(item); + } + }; + + SyntaxWalker.prototype.visitSourceUnit = function (node) { + this.visitList(node.moduleElements); + this.visitToken(node.endOfFileToken); + }; + + SyntaxWalker.prototype.visitExternalModuleReference = function (node) { + this.visitToken(node.requireKeyword); + this.visitToken(node.openParenToken); + this.visitToken(node.stringLiteral); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitModuleNameModuleReference = function (node) { + this.visitNodeOrToken(node.moduleName); + }; + + SyntaxWalker.prototype.visitImportDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.importKeyword); + this.visitToken(node.identifier); + this.visitToken(node.equalsToken); + this.visitNodeOrToken(node.moduleReference); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitExportAssignment = function (node) { + this.visitToken(node.exportKeyword); + this.visitToken(node.equalsToken); + this.visitToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitClassDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.classKeyword); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeParameterList); + this.visitList(node.heritageClauses); + this.visitToken(node.openBraceToken); + this.visitList(node.classElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitInterfaceDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.interfaceKeyword); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeParameterList); + this.visitList(node.heritageClauses); + this.visitNode(node.body); + }; + + SyntaxWalker.prototype.visitHeritageClause = function (node) { + this.visitToken(node.extendsOrImplementsKeyword); + this.visitSeparatedList(node.typeNames); + }; + + SyntaxWalker.prototype.visitModuleDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.moduleKeyword); + this.visitOptionalNodeOrToken(node.name); + this.visitOptionalToken(node.stringLiteral); + this.visitToken(node.openBraceToken); + this.visitList(node.moduleElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitFunctionDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.functionKeyword); + this.visitToken(node.identifier); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitVariableStatement = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.variableDeclaration); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitVariableDeclaration = function (node) { + this.visitToken(node.varKeyword); + this.visitSeparatedList(node.variableDeclarators); + }; + + SyntaxWalker.prototype.visitVariableDeclarator = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalNode(node.typeAnnotation); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitEqualsValueClause = function (node) { + this.visitToken(node.equalsToken); + this.visitNodeOrToken(node.value); + }; + + SyntaxWalker.prototype.visitPrefixUnaryExpression = function (node) { + this.visitToken(node.operatorToken); + this.visitNodeOrToken(node.operand); + }; + + SyntaxWalker.prototype.visitArrayLiteralExpression = function (node) { + this.visitToken(node.openBracketToken); + this.visitSeparatedList(node.expressions); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitOmittedExpression = function (node) { + }; + + SyntaxWalker.prototype.visitParenthesizedExpression = function (node) { + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitSimpleArrowFunctionExpression = function (node) { + this.visitToken(node.identifier); + this.visitToken(node.equalsGreaterThanToken); + this.visitOptionalNode(node.block); + this.visitOptionalNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + this.visitNode(node.callSignature); + this.visitToken(node.equalsGreaterThanToken); + this.visitOptionalNode(node.block); + this.visitOptionalNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitQualifiedName = function (node) { + this.visitNodeOrToken(node.left); + this.visitToken(node.dotToken); + this.visitToken(node.right); + }; + + SyntaxWalker.prototype.visitTypeArgumentList = function (node) { + this.visitToken(node.lessThanToken); + this.visitSeparatedList(node.typeArguments); + this.visitToken(node.greaterThanToken); + }; + + SyntaxWalker.prototype.visitConstructorType = function (node) { + this.visitToken(node.newKeyword); + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitFunctionType = function (node) { + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitObjectType = function (node) { + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.typeMembers); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitArrayType = function (node) { + this.visitNodeOrToken(node.type); + this.visitToken(node.openBracketToken); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitGenericType = function (node) { + this.visitNodeOrToken(node.name); + this.visitNode(node.typeArgumentList); + }; + + SyntaxWalker.prototype.visitTypeQuery = function (node) { + this.visitToken(node.typeOfKeyword); + this.visitNodeOrToken(node.name); + }; + + SyntaxWalker.prototype.visitTypeAnnotation = function (node) { + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitBlock = function (node) { + this.visitToken(node.openBraceToken); + this.visitList(node.statements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitParameter = function (node) { + this.visitOptionalToken(node.dotDotDotToken); + this.visitList(node.modifiers); + this.visitToken(node.identifier); + this.visitOptionalToken(node.questionToken); + this.visitOptionalNode(node.typeAnnotation); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitMemberAccessExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.dotToken); + this.visitToken(node.name); + }; + + SyntaxWalker.prototype.visitPostfixUnaryExpression = function (node) { + this.visitNodeOrToken(node.operand); + this.visitToken(node.operatorToken); + }; + + SyntaxWalker.prototype.visitElementAccessExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.openBracketToken); + this.visitNodeOrToken(node.argumentExpression); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitInvocationExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitNode(node.argumentList); + }; + + SyntaxWalker.prototype.visitArgumentList = function (node) { + this.visitOptionalNode(node.typeArgumentList); + this.visitToken(node.openParenToken); + this.visitSeparatedList(node.arguments); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitBinaryExpression = function (node) { + this.visitNodeOrToken(node.left); + this.visitToken(node.operatorToken); + this.visitNodeOrToken(node.right); + }; + + SyntaxWalker.prototype.visitConditionalExpression = function (node) { + this.visitNodeOrToken(node.condition); + this.visitToken(node.questionToken); + this.visitNodeOrToken(node.whenTrue); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.whenFalse); + }; + + SyntaxWalker.prototype.visitConstructSignature = function (node) { + this.visitToken(node.newKeyword); + this.visitNode(node.callSignature); + }; + + SyntaxWalker.prototype.visitMethodSignature = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalToken(node.questionToken); + this.visitNode(node.callSignature); + }; + + SyntaxWalker.prototype.visitIndexSignature = function (node) { + this.visitToken(node.openBracketToken); + this.visitNode(node.parameter); + this.visitToken(node.closeBracketToken); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitPropertySignature = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalToken(node.questionToken); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitCallSignature = function (node) { + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitParameterList = function (node) { + this.visitToken(node.openParenToken); + this.visitSeparatedList(node.parameters); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitTypeParameterList = function (node) { + this.visitToken(node.lessThanToken); + this.visitSeparatedList(node.typeParameters); + this.visitToken(node.greaterThanToken); + }; + + SyntaxWalker.prototype.visitTypeParameter = function (node) { + this.visitToken(node.identifier); + this.visitOptionalNode(node.constraint); + }; + + SyntaxWalker.prototype.visitConstraint = function (node) { + this.visitToken(node.extendsKeyword); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitElseClause = function (node) { + this.visitToken(node.elseKeyword); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitIfStatement = function (node) { + this.visitToken(node.ifKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + this.visitOptionalNode(node.elseClause); + }; + + SyntaxWalker.prototype.visitExpressionStatement = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitConstructorDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.constructorKeyword); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitMemberFunctionDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitGetAccessor = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.getKeyword); + this.visitToken(node.propertyName); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.typeAnnotation); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitSetAccessor = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.setKeyword); + this.visitToken(node.propertyName); + this.visitNode(node.parameterList); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitMemberVariableDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.variableDeclarator); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitIndexMemberDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.indexSignature); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitThrowStatement = function (node) { + this.visitToken(node.throwKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitReturnStatement = function (node) { + this.visitToken(node.returnKeyword); + this.visitOptionalNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitObjectCreationExpression = function (node) { + this.visitToken(node.newKeyword); + this.visitNodeOrToken(node.expression); + this.visitOptionalNode(node.argumentList); + }; + + SyntaxWalker.prototype.visitSwitchStatement = function (node) { + this.visitToken(node.switchKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + this.visitToken(node.openBraceToken); + this.visitList(node.switchClauses); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitCaseSwitchClause = function (node) { + this.visitToken(node.caseKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.colonToken); + this.visitList(node.statements); + }; + + SyntaxWalker.prototype.visitDefaultSwitchClause = function (node) { + this.visitToken(node.defaultKeyword); + this.visitToken(node.colonToken); + this.visitList(node.statements); + }; + + SyntaxWalker.prototype.visitBreakStatement = function (node) { + this.visitToken(node.breakKeyword); + this.visitOptionalToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitContinueStatement = function (node) { + this.visitToken(node.continueKeyword); + this.visitOptionalToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitForStatement = function (node) { + this.visitToken(node.forKeyword); + this.visitToken(node.openParenToken); + this.visitOptionalNode(node.variableDeclaration); + this.visitOptionalNodeOrToken(node.initializer); + this.visitToken(node.firstSemicolonToken); + this.visitOptionalNodeOrToken(node.condition); + this.visitToken(node.secondSemicolonToken); + this.visitOptionalNodeOrToken(node.incrementor); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitForInStatement = function (node) { + this.visitToken(node.forKeyword); + this.visitToken(node.openParenToken); + this.visitOptionalNode(node.variableDeclaration); + this.visitOptionalNodeOrToken(node.left); + this.visitToken(node.inKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitWhileStatement = function (node) { + this.visitToken(node.whileKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitWithStatement = function (node) { + this.visitToken(node.withKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitEnumDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.enumKeyword); + this.visitToken(node.identifier); + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.enumElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitEnumElement = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitCastExpression = function (node) { + this.visitToken(node.lessThanToken); + this.visitNodeOrToken(node.type); + this.visitToken(node.greaterThanToken); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitObjectLiteralExpression = function (node) { + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.propertyAssignments); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitSimplePropertyAssignment = function (node) { + this.visitToken(node.propertyName); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitFunctionPropertyAssignment = function (node) { + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitFunctionExpression = function (node) { + this.visitToken(node.functionKeyword); + this.visitOptionalToken(node.identifier); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitEmptyStatement = function (node) { + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitTryStatement = function (node) { + this.visitToken(node.tryKeyword); + this.visitNode(node.block); + this.visitOptionalNode(node.catchClause); + this.visitOptionalNode(node.finallyClause); + }; + + SyntaxWalker.prototype.visitCatchClause = function (node) { + this.visitToken(node.catchKeyword); + this.visitToken(node.openParenToken); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeAnnotation); + this.visitToken(node.closeParenToken); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitFinallyClause = function (node) { + this.visitToken(node.finallyKeyword); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitLabeledStatement = function (node) { + this.visitToken(node.identifier); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitDoStatement = function (node) { + this.visitToken(node.doKeyword); + this.visitNodeOrToken(node.statement); + this.visitToken(node.whileKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitTypeOfExpression = function (node) { + this.visitToken(node.typeOfKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitDeleteExpression = function (node) { + this.visitToken(node.deleteKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitVoidExpression = function (node) { + this.visitToken(node.voidKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitDebuggerStatement = function (node) { + this.visitToken(node.debuggerKeyword); + this.visitToken(node.semicolonToken); + }; + return SyntaxWalker; + })(); + TypeScript.SyntaxWalker = SyntaxWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PositionTrackingWalker = (function (_super) { + __extends(PositionTrackingWalker, _super); + function PositionTrackingWalker() { + _super.apply(this, arguments); + this._position = 0; + } + PositionTrackingWalker.prototype.visitToken = function (token) { + this._position += token.fullWidth(); + }; + + PositionTrackingWalker.prototype.position = function () { + return this._position; + }; + + PositionTrackingWalker.prototype.skip = function (element) { + this._position += element.fullWidth(); + }; + return PositionTrackingWalker; + })(TypeScript.SyntaxWalker); + TypeScript.PositionTrackingWalker = PositionTrackingWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxInformationMap = (function (_super) { + __extends(SyntaxInformationMap, _super); + function SyntaxInformationMap(trackParents, trackPreviousToken) { + _super.call(this); + this.trackParents = trackParents; + this.trackPreviousToken = trackPreviousToken; + this.tokenToInformation = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this.elementToPosition = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this._previousToken = null; + this._previousTokenInformation = null; + this._currentPosition = 0; + this._elementToParent = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this._parentStack = []; + this._parentStack.push(null); + } + SyntaxInformationMap.create = function (node, trackParents, trackPreviousToken) { + var map = new SyntaxInformationMap(trackParents, trackPreviousToken); + map.visitNode(node); + return map; + }; + + SyntaxInformationMap.prototype.visitNode = function (node) { + this.trackParents && this._elementToParent.add(node, TypeScript.ArrayUtilities.last(this._parentStack)); + this.elementToPosition.add(node, this._currentPosition); + + this.trackParents && this._parentStack.push(node); + _super.prototype.visitNode.call(this, node); + this.trackParents && this._parentStack.pop(); + }; + + SyntaxInformationMap.prototype.visitToken = function (token) { + this.trackParents && this._elementToParent.add(token, TypeScript.ArrayUtilities.last(this._parentStack)); + + if (this.trackPreviousToken) { + var tokenInformation = { + previousToken: this._previousToken, + nextToken: null + }; + + if (this._previousTokenInformation !== null) { + this._previousTokenInformation.nextToken = token; + } + + this._previousToken = token; + this._previousTokenInformation = tokenInformation; + + this.tokenToInformation.add(token, tokenInformation); + } + + this.elementToPosition.add(token, this._currentPosition); + this._currentPosition += token.fullWidth(); + }; + + SyntaxInformationMap.prototype.parent = function (element) { + return this._elementToParent.get(element); + }; + + SyntaxInformationMap.prototype.fullStart = function (element) { + return this.elementToPosition.get(element); + }; + + SyntaxInformationMap.prototype.start = function (element) { + return this.fullStart(element) + element.leadingTriviaWidth(); + }; + + SyntaxInformationMap.prototype.end = function (element) { + return this.start(element) + element.width(); + }; + + SyntaxInformationMap.prototype.previousToken = function (token) { + return this.tokenInformation(token).previousToken; + }; + + SyntaxInformationMap.prototype.tokenInformation = function (token) { + return this.tokenToInformation.get(token); + }; + + SyntaxInformationMap.prototype.firstTokenInLineContainingToken = function (token) { + var current = token; + while (true) { + var information = this.tokenInformation(current); + if (this.isFirstTokenInLineWorker(information)) { + break; + } + + current = information.previousToken; + } + + return current; + }; + + SyntaxInformationMap.prototype.isFirstTokenInLine = function (token) { + var information = this.tokenInformation(token); + return this.isFirstTokenInLineWorker(information); + }; + + SyntaxInformationMap.prototype.isFirstTokenInLineWorker = function (information) { + return information.previousToken === null || information.previousToken.hasTrailingNewLine(); + }; + return SyntaxInformationMap; + })(TypeScript.SyntaxWalker); + TypeScript.SyntaxInformationMap = SyntaxInformationMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxNodeInvariantsChecker = (function (_super) { + __extends(SyntaxNodeInvariantsChecker, _super); + function SyntaxNodeInvariantsChecker() { + _super.apply(this, arguments); + this.tokenTable = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + } + SyntaxNodeInvariantsChecker.checkInvariants = function (node) { + node.accept(new SyntaxNodeInvariantsChecker()); + }; + + SyntaxNodeInvariantsChecker.prototype.visitToken = function (token) { + this.tokenTable.add(token, token); + }; + return SyntaxNodeInvariantsChecker; + })(TypeScript.SyntaxWalker); + TypeScript.SyntaxNodeInvariantsChecker = SyntaxNodeInvariantsChecker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DepthLimitedWalker = (function (_super) { + __extends(DepthLimitedWalker, _super); + function DepthLimitedWalker(maximumDepth) { + _super.call(this); + this._depth = 0; + this._maximumDepth = 0; + this._maximumDepth = maximumDepth; + } + DepthLimitedWalker.prototype.visitNode = function (node) { + if (this._depth < this._maximumDepth) { + this._depth++; + _super.prototype.visitNode.call(this, node); + this._depth--; + } else { + this.skip(node); + } + }; + return DepthLimitedWalker; + })(TypeScript.PositionTrackingWalker); + TypeScript.DepthLimitedWalker = DepthLimitedWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Parser) { + + + var ExpressionPrecedence; + (function (ExpressionPrecedence) { + ExpressionPrecedence[ExpressionPrecedence["CommaExpressionPrecedence"] = 1] = "CommaExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["AssignmentExpressionPrecedence"] = 2] = "AssignmentExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["ConditionalExpressionPrecedence"] = 3] = "ConditionalExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["ArrowFunctionPrecedence"] = 4] = "ArrowFunctionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["LogicalOrExpressionPrecedence"] = 5] = "LogicalOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["LogicalAndExpressionPrecedence"] = 6] = "LogicalAndExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseOrExpressionPrecedence"] = 7] = "BitwiseOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseExclusiveOrExpressionPrecedence"] = 8] = "BitwiseExclusiveOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseAndExpressionPrecedence"] = 9] = "BitwiseAndExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["EqualityExpressionPrecedence"] = 10] = "EqualityExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["RelationalExpressionPrecedence"] = 11] = "RelationalExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["ShiftExpressionPrecdence"] = 12] = "ShiftExpressionPrecdence"; + ExpressionPrecedence[ExpressionPrecedence["AdditiveExpressionPrecedence"] = 13] = "AdditiveExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["MultiplicativeExpressionPrecedence"] = 14] = "MultiplicativeExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["UnaryExpressionPrecedence"] = 15] = "UnaryExpressionPrecedence"; + })(ExpressionPrecedence || (ExpressionPrecedence = {})); + + var ListParsingState; + (function (ListParsingState) { + ListParsingState[ListParsingState["SourceUnit_ModuleElements"] = 1 << 0] = "SourceUnit_ModuleElements"; + ListParsingState[ListParsingState["ClassDeclaration_ClassElements"] = 1 << 1] = "ClassDeclaration_ClassElements"; + ListParsingState[ListParsingState["ModuleDeclaration_ModuleElements"] = 1 << 2] = "ModuleDeclaration_ModuleElements"; + ListParsingState[ListParsingState["SwitchStatement_SwitchClauses"] = 1 << 3] = "SwitchStatement_SwitchClauses"; + ListParsingState[ListParsingState["SwitchClause_Statements"] = 1 << 4] = "SwitchClause_Statements"; + ListParsingState[ListParsingState["Block_Statements"] = 1 << 5] = "Block_Statements"; + ListParsingState[ListParsingState["TryBlock_Statements"] = 1 << 6] = "TryBlock_Statements"; + ListParsingState[ListParsingState["CatchBlock_Statements"] = 1 << 7] = "CatchBlock_Statements"; + ListParsingState[ListParsingState["EnumDeclaration_EnumElements"] = 1 << 8] = "EnumDeclaration_EnumElements"; + ListParsingState[ListParsingState["ObjectType_TypeMembers"] = 1 << 9] = "ObjectType_TypeMembers"; + ListParsingState[ListParsingState["ClassOrInterfaceDeclaration_HeritageClauses"] = 1 << 10] = "ClassOrInterfaceDeclaration_HeritageClauses"; + ListParsingState[ListParsingState["HeritageClause_TypeNameList"] = 1 << 11] = "HeritageClause_TypeNameList"; + ListParsingState[ListParsingState["VariableDeclaration_VariableDeclarators_AllowIn"] = 1 << 12] = "VariableDeclaration_VariableDeclarators_AllowIn"; + ListParsingState[ListParsingState["VariableDeclaration_VariableDeclarators_DisallowIn"] = 1 << 13] = "VariableDeclaration_VariableDeclarators_DisallowIn"; + ListParsingState[ListParsingState["ArgumentList_AssignmentExpressions"] = 1 << 14] = "ArgumentList_AssignmentExpressions"; + ListParsingState[ListParsingState["ObjectLiteralExpression_PropertyAssignments"] = 1 << 15] = "ObjectLiteralExpression_PropertyAssignments"; + ListParsingState[ListParsingState["ArrayLiteralExpression_AssignmentExpressions"] = 1 << 16] = "ArrayLiteralExpression_AssignmentExpressions"; + ListParsingState[ListParsingState["ParameterList_Parameters"] = 1 << 17] = "ParameterList_Parameters"; + ListParsingState[ListParsingState["TypeArgumentList_Types"] = 1 << 18] = "TypeArgumentList_Types"; + ListParsingState[ListParsingState["TypeParameterList_TypeParameters"] = 1 << 19] = "TypeParameterList_TypeParameters"; + + ListParsingState[ListParsingState["FirstListParsingState"] = ListParsingState.SourceUnit_ModuleElements] = "FirstListParsingState"; + ListParsingState[ListParsingState["LastListParsingState"] = ListParsingState.TypeParameterList_TypeParameters] = "LastListParsingState"; + })(ListParsingState || (ListParsingState = {})); + + var SyntaxCursor = (function () { + function SyntaxCursor(sourceUnit) { + this._elements = []; + this._index = 0; + this._pinCount = 0; + sourceUnit.insertChildrenInto(this._elements, 0); + } + SyntaxCursor.prototype.isFinished = function () { + return this._index === this._elements.length; + }; + + SyntaxCursor.prototype.currentElement = function () { + if (this.isFinished()) { + return null; + } + + return this._elements[this._index]; + }; + + SyntaxCursor.prototype.currentNode = function () { + var element = this.currentElement(); + return element !== null && element.isNode() ? element : null; + }; + + SyntaxCursor.prototype.moveToFirstChild = function () { + if (this.isFinished()) { + return; + } + + var element = this._elements[this._index]; + if (element.isToken()) { + return; + } + + var node = element; + + this._elements.splice(this._index, 1); + + node.insertChildrenInto(this._elements, this._index); + }; + + SyntaxCursor.prototype.moveToNextSibling = function () { + if (this.isFinished()) { + return; + } + + if (this._pinCount > 0) { + this._index++; + return; + } + + this._elements.shift(); + }; + + SyntaxCursor.prototype.getAndPinCursorIndex = function () { + this._pinCount++; + return this._index; + }; + + SyntaxCursor.prototype.releaseAndUnpinCursorIndex = function (index) { + this._pinCount--; + if (this._pinCount === 0) { + } + }; + + SyntaxCursor.prototype.rewindToPinnedCursorIndex = function (index) { + this._index = index; + }; + + SyntaxCursor.prototype.pinCount = function () { + return this._pinCount; + }; + + SyntaxCursor.prototype.moveToFirstToken = function () { + var element; + + while (!this.isFinished()) { + element = this.currentElement(); + if (element.isNode()) { + this.moveToFirstChild(); + continue; + } + + return; + } + }; + + SyntaxCursor.prototype.currentToken = function () { + this.moveToFirstToken(); + if (this.isFinished()) { + return null; + } + + var element = this.currentElement(); + + return element; + }; + + SyntaxCursor.prototype.peekToken = function (n) { + this.moveToFirstToken(); + var pin = this.getAndPinCursorIndex(); + + for (var i = 0; i < n; i++) { + this.moveToNextSibling(); + this.moveToFirstToken(); + } + + var result = this.currentToken(); + this.rewindToPinnedCursorIndex(pin); + this.releaseAndUnpinCursorIndex(pin); + + return result; + }; + return SyntaxCursor; + })(); + + + + var NormalParserSource = (function () { + function NormalParserSource(fileName, text, languageVersion) { + this._previousToken = null; + this._absolutePosition = 0; + this._tokenDiagnostics = []; + this.rewindPointPool = []; + this.rewindPointPoolCount = 0; + this.slidingWindow = new TypeScript.SlidingWindow(this, TypeScript.ArrayUtilities.createArray(32, null), null); + this.scanner = new TypeScript.Scanner(fileName, text, languageVersion); + } + NormalParserSource.prototype.currentNode = function () { + return null; + }; + + NormalParserSource.prototype.moveToNextNode = function () { + throw TypeScript.Errors.invalidOperation(); + }; + + NormalParserSource.prototype.absolutePosition = function () { + return this._absolutePosition; + }; + + NormalParserSource.prototype.previousToken = function () { + return this._previousToken; + }; + + NormalParserSource.prototype.tokenDiagnostics = function () { + return this._tokenDiagnostics; + }; + + NormalParserSource.prototype.getOrCreateRewindPoint = function () { + if (this.rewindPointPoolCount === 0) { + return {}; + } + + this.rewindPointPoolCount--; + var result = this.rewindPointPool[this.rewindPointPoolCount]; + this.rewindPointPool[this.rewindPointPoolCount] = null; + return result; + }; + + NormalParserSource.prototype.getRewindPoint = function () { + var slidingWindowIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + var rewindPoint = this.getOrCreateRewindPoint(); + + rewindPoint.slidingWindowIndex = slidingWindowIndex; + rewindPoint.previousToken = this._previousToken; + rewindPoint.absolutePosition = this._absolutePosition; + + rewindPoint.pinCount = this.slidingWindow.pinCount(); + + return rewindPoint; + }; + + NormalParserSource.prototype.isPinned = function () { + return this.slidingWindow.pinCount() > 0; + }; + + NormalParserSource.prototype.rewind = function (rewindPoint) { + this.slidingWindow.rewindToPinnedIndex(rewindPoint.slidingWindowIndex); + + this._previousToken = rewindPoint.previousToken; + this._absolutePosition = rewindPoint.absolutePosition; + }; + + NormalParserSource.prototype.releaseRewindPoint = function (rewindPoint) { + this.slidingWindow.releaseAndUnpinAbsoluteIndex(rewindPoint.absoluteIndex); + + this.rewindPointPool[this.rewindPointPoolCount] = rewindPoint; + this.rewindPointPoolCount++; + }; + + NormalParserSource.prototype.fetchMoreItems = function (allowRegularExpression, sourceIndex, window, destinationIndex, spaceAvailable) { + window[destinationIndex] = this.scanner.scan(this._tokenDiagnostics, allowRegularExpression); + return 1; + }; + + NormalParserSource.prototype.peekToken = function (n) { + return this.slidingWindow.peekItemN(n); + }; + + NormalParserSource.prototype.moveToNextToken = function () { + var currentToken = this.currentToken(); + this._absolutePosition += currentToken.fullWidth(); + this._previousToken = currentToken; + + this.slidingWindow.moveToNextItem(); + }; + + NormalParserSource.prototype.currentToken = function () { + return this.slidingWindow.currentItem(false); + }; + + NormalParserSource.prototype.removeDiagnosticsOnOrAfterPosition = function (position) { + var tokenDiagnosticsLength = this._tokenDiagnostics.length; + while (tokenDiagnosticsLength > 0) { + var diagnostic = this._tokenDiagnostics[tokenDiagnosticsLength - 1]; + if (diagnostic.start() >= position) { + tokenDiagnosticsLength--; + } else { + break; + } + } + + this._tokenDiagnostics.length = tokenDiagnosticsLength; + }; + + NormalParserSource.prototype.resetToPosition = function (absolutePosition, previousToken) { + this._absolutePosition = absolutePosition; + this._previousToken = previousToken; + + this.removeDiagnosticsOnOrAfterPosition(absolutePosition); + + this.slidingWindow.disgardAllItemsFromCurrentIndexOnwards(); + + this.scanner.setAbsoluteIndex(absolutePosition); + }; + + NormalParserSource.prototype.currentTokenAllowingRegularExpression = function () { + this.resetToPosition(this._absolutePosition, this._previousToken); + + var token = this.slidingWindow.currentItem(true); + + return token; + }; + return NormalParserSource; + })(); + + var IncrementalParserSource = (function () { + function IncrementalParserSource(oldSyntaxTree, textChangeRange, newText) { + this._changeDelta = 0; + var oldSourceUnit = oldSyntaxTree.sourceUnit(); + this._oldSourceUnitCursor = new SyntaxCursor(oldSourceUnit); + + this._changeRange = IncrementalParserSource.extendToAffectedRange(textChangeRange, oldSourceUnit); + + if (TypeScript.Debug.shouldAssert(2 /* Aggressive */)) { + TypeScript.Debug.assert((oldSourceUnit.fullWidth() - this._changeRange.span().length() + this._changeRange.newLength()) === newText.length()); + } + + this._normalParserSource = new NormalParserSource(oldSyntaxTree.fileName(), newText, oldSyntaxTree.parseOptions().languageVersion()); + } + IncrementalParserSource.extendToAffectedRange = function (changeRange, sourceUnit) { + var maxLookahead = 1; + + var start = changeRange.span().start(); + + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var token = sourceUnit.findToken(start); + + var position = token.fullStart(); + + start = TypeScript.MathPrototype.max(0, position - 1); + } + + var finalSpan = TypeScript.TextSpan.fromBounds(start, changeRange.span().end()); + var finalLength = changeRange.newLength() + (changeRange.span().start() - start); + + return new TypeScript.TextChangeRange(finalSpan, finalLength); + }; + + IncrementalParserSource.prototype.absolutePosition = function () { + return this._normalParserSource.absolutePosition(); + }; + + IncrementalParserSource.prototype.previousToken = function () { + return this._normalParserSource.previousToken(); + }; + + IncrementalParserSource.prototype.tokenDiagnostics = function () { + return this._normalParserSource.tokenDiagnostics(); + }; + + IncrementalParserSource.prototype.getRewindPoint = function () { + var rewindPoint = this._normalParserSource.getRewindPoint(); + var oldSourceUnitCursorIndex = this._oldSourceUnitCursor.getAndPinCursorIndex(); + + rewindPoint.changeDelta = this._changeDelta; + rewindPoint.changeRange = this._changeRange; + rewindPoint.oldSourceUnitCursorIndex = oldSourceUnitCursorIndex; + + return rewindPoint; + }; + + IncrementalParserSource.prototype.rewind = function (rewindPoint) { + this._changeRange = rewindPoint.changeRange; + this._changeDelta = rewindPoint.changeDelta; + this._oldSourceUnitCursor.rewindToPinnedCursorIndex(rewindPoint.oldSourceUnitCursorIndex); + + this._normalParserSource.rewind(rewindPoint); + }; + + IncrementalParserSource.prototype.releaseRewindPoint = function (rewindPoint) { + this._oldSourceUnitCursor.releaseAndUnpinCursorIndex(rewindPoint.oldSourceUnitCursorIndex); + this._normalParserSource.releaseRewindPoint(rewindPoint); + }; + + IncrementalParserSource.prototype.canReadFromOldSourceUnit = function () { + if (this._normalParserSource.isPinned()) { + return false; + } + + if (this._changeRange !== null && this._changeRange.newSpan().intersectsWithPosition(this.absolutePosition())) { + return false; + } + + this.syncCursorToNewTextIfBehind(); + + return this._changeDelta === 0 && !this._oldSourceUnitCursor.isFinished(); + }; + + IncrementalParserSource.prototype.currentNode = function () { + if (this.canReadFromOldSourceUnit()) { + return this.tryGetNodeFromOldSourceUnit(); + } + + return null; + }; + + IncrementalParserSource.prototype.currentToken = function () { + if (this.canReadFromOldSourceUnit()) { + var token = this.tryGetTokenFromOldSourceUnit(); + if (token !== null) { + return token; + } + } + + return this._normalParserSource.currentToken(); + }; + + IncrementalParserSource.prototype.currentTokenAllowingRegularExpression = function () { + return this._normalParserSource.currentTokenAllowingRegularExpression(); + }; + + IncrementalParserSource.prototype.syncCursorToNewTextIfBehind = function () { + while (true) { + if (this._oldSourceUnitCursor.isFinished()) { + break; + } + + if (this._changeDelta >= 0) { + break; + } + + var currentElement = this._oldSourceUnitCursor.currentElement(); + + if (currentElement.isNode() && (currentElement.fullWidth() > Math.abs(this._changeDelta))) { + this._oldSourceUnitCursor.moveToFirstChild(); + } else { + this._oldSourceUnitCursor.moveToNextSibling(); + + this._changeDelta += currentElement.fullWidth(); + } + } + }; + + IncrementalParserSource.prototype.intersectsWithChangeRangeSpanInOriginalText = function (start, length) { + return this._changeRange !== null && this._changeRange.span().intersectsWith(start, length); + }; + + IncrementalParserSource.prototype.tryGetNodeFromOldSourceUnit = function () { + while (true) { + var node = this._oldSourceUnitCursor.currentNode(); + if (node === null) { + return null; + } + + if (!this.intersectsWithChangeRangeSpanInOriginalText(this.absolutePosition(), node.fullWidth())) { + if (!node.isIncrementallyUnusable()) { + return node; + } + } + + this._oldSourceUnitCursor.moveToFirstChild(); + } + }; + + IncrementalParserSource.prototype.canReuseTokenFromOldSourceUnit = function (position, token) { + if (token !== null) { + if (!this.intersectsWithChangeRangeSpanInOriginalText(position, token.fullWidth())) { + if (!token.isIncrementallyUnusable()) { + return true; + } + } + } + + return false; + }; + + IncrementalParserSource.prototype.tryGetTokenFromOldSourceUnit = function () { + var token = this._oldSourceUnitCursor.currentToken(); + + return this.canReuseTokenFromOldSourceUnit(this.absolutePosition(), token) ? token : null; + }; + + IncrementalParserSource.prototype.peekToken = function (n) { + if (this.canReadFromOldSourceUnit()) { + var token = this.tryPeekTokenFromOldSourceUnit(n); + if (token !== null) { + return token; + } + } + + return this._normalParserSource.peekToken(n); + }; + + IncrementalParserSource.prototype.tryPeekTokenFromOldSourceUnit = function (n) { + var currentPosition = this.absolutePosition(); + for (var i = 0; i < n; i++) { + var interimToken = this._oldSourceUnitCursor.peekToken(i); + if (!this.canReuseTokenFromOldSourceUnit(currentPosition, interimToken)) { + return null; + } + + currentPosition += interimToken.fullWidth(); + } + + var token = this._oldSourceUnitCursor.peekToken(n); + return this.canReuseTokenFromOldSourceUnit(currentPosition, token) ? token : null; + }; + + IncrementalParserSource.prototype.moveToNextNode = function () { + var currentElement = this._oldSourceUnitCursor.currentElement(); + var currentNode = this._oldSourceUnitCursor.currentNode(); + + this._oldSourceUnitCursor.moveToNextSibling(); + + var absolutePosition = this.absolutePosition() + currentNode.fullWidth(); + var previousToken = currentNode.lastToken(); + this._normalParserSource.resetToPosition(absolutePosition, previousToken); + + if (this._changeRange !== null) { + } + }; + + IncrementalParserSource.prototype.moveToNextToken = function () { + var currentToken = this.currentToken(); + + if (this._oldSourceUnitCursor.currentToken() === currentToken) { + this._oldSourceUnitCursor.moveToNextSibling(); + + var absolutePosition = this.absolutePosition() + currentToken.fullWidth(); + var previousToken = currentToken; + this._normalParserSource.resetToPosition(absolutePosition, previousToken); + + if (this._changeRange !== null) { + } + } else { + this._changeDelta -= currentToken.fullWidth(); + + this._normalParserSource.moveToNextToken(); + + if (this._changeRange !== null) { + var changeRangeSpanInNewText = this._changeRange.newSpan(); + if (this.absolutePosition() >= changeRangeSpanInNewText.end()) { + this._changeDelta += this._changeRange.newLength() - this._changeRange.span().length(); + this._changeRange = null; + } + } + } + }; + return IncrementalParserSource; + })(); + + var ParserImpl = (function () { + function ParserImpl(fileName, lineMap, source, parseOptions, newText_forDebuggingPurposesOnly) { + this.newText_forDebuggingPurposesOnly = newText_forDebuggingPurposesOnly; + this.listParsingState = 0; + this.isInStrictMode = false; + this.diagnostics = []; + this.factory = TypeScript.Syntax.normalModeFactory; + this.mergeTokensStorage = []; + this.arrayPool = []; + this.fileName = fileName; + this.lineMap = lineMap; + this.source = source; + this.parseOptions = parseOptions; + } + ParserImpl.prototype.getRewindPoint = function () { + var rewindPoint = this.source.getRewindPoint(); + + rewindPoint.diagnosticsCount = this.diagnostics.length; + + rewindPoint.isInStrictMode = this.isInStrictMode; + rewindPoint.listParsingState = this.listParsingState; + + return rewindPoint; + }; + + ParserImpl.prototype.rewind = function (rewindPoint) { + this.source.rewind(rewindPoint); + + this.diagnostics.length = rewindPoint.diagnosticsCount; + }; + + ParserImpl.prototype.releaseRewindPoint = function (rewindPoint) { + this.source.releaseRewindPoint(rewindPoint); + }; + + ParserImpl.prototype.currentTokenStart = function () { + return this.source.absolutePosition() + this.currentToken().leadingTriviaWidth(); + }; + + ParserImpl.prototype.previousTokenStart = function () { + if (this.previousToken() === null) { + return 0; + } + + return this.source.absolutePosition() - this.previousToken().fullWidth() + this.previousToken().leadingTriviaWidth(); + }; + + ParserImpl.prototype.previousTokenEnd = function () { + if (this.previousToken() === null) { + return 0; + } + + return this.previousTokenStart() + this.previousToken().width(); + }; + + ParserImpl.prototype.currentNode = function () { + var node = this.source.currentNode(); + + if (node === null || node.parsedInStrictMode() !== this.isInStrictMode) { + return null; + } + + return node; + }; + + ParserImpl.prototype.currentToken = function () { + return this.source.currentToken(); + }; + + ParserImpl.prototype.currentTokenAllowingRegularExpression = function () { + return this.source.currentTokenAllowingRegularExpression(); + }; + + ParserImpl.prototype.peekToken = function (n) { + return this.source.peekToken(n); + }; + + ParserImpl.prototype.eatAnyToken = function () { + var token = this.currentToken(); + this.moveToNextToken(); + return token; + }; + + ParserImpl.prototype.moveToNextToken = function () { + this.source.moveToNextToken(); + }; + + ParserImpl.prototype.previousToken = function () { + return this.source.previousToken(); + }; + + ParserImpl.prototype.eatNode = function () { + var node = this.source.currentNode(); + this.source.moveToNextNode(); + return node; + }; + + ParserImpl.prototype.eatToken = function (kind) { + var token = this.currentToken(); + if (token.tokenKind === kind) { + this.moveToNextToken(); + return token; + } + + return this.createMissingToken(kind, token); + }; + + ParserImpl.prototype.tryEatToken = function (kind) { + if (this.currentToken().tokenKind === kind) { + return this.eatToken(kind); + } + + return null; + }; + + ParserImpl.prototype.eatKeyword = function (kind) { + var token = this.currentToken(); + if (token.tokenKind === kind) { + this.moveToNextToken(); + return token; + } + + return this.createMissingToken(kind, token); + }; + + ParserImpl.prototype.isIdentifier = function (token) { + var tokenKind = token.tokenKind; + + if (tokenKind === 11 /* IdentifierName */) { + return true; + } + + if (tokenKind >= 51 /* FirstFutureReservedStrictKeyword */) { + if (tokenKind <= 59 /* LastFutureReservedStrictKeyword */) { + return !this.isInStrictMode; + } + + return tokenKind <= 69 /* LastTypeScriptKeyword */; + } + + return false; + }; + + ParserImpl.prototype.eatIdentifierNameToken = function () { + var token = this.currentToken(); + + if (token.tokenKind === 11 /* IdentifierName */) { + this.moveToNextToken(); + return token; + } + + if (TypeScript.SyntaxFacts.isAnyKeyword(token.tokenKind)) { + this.moveToNextToken(); + return TypeScript.Syntax.convertToIdentifierName(token); + } + + return this.createMissingToken(11 /* IdentifierName */, token); + }; + + ParserImpl.prototype.eatIdentifierToken = function () { + var token = this.currentToken(); + if (this.isIdentifier(token)) { + this.moveToNextToken(); + + if (token.tokenKind === 11 /* IdentifierName */) { + return token; + } + + return TypeScript.Syntax.convertToIdentifierName(token); + } + + return this.createMissingToken(11 /* IdentifierName */, token); + }; + + ParserImpl.prototype.canEatAutomaticSemicolon = function (allowWithoutNewLine) { + var token = this.currentToken(); + + if (token.tokenKind === 10 /* EndOfFileToken */) { + return true; + } + + if (token.tokenKind === 71 /* CloseBraceToken */) { + return true; + } + + if (allowWithoutNewLine) { + return true; + } + + if (this.previousToken() !== null && this.previousToken().hasTrailingNewLine()) { + return true; + } + + return false; + }; + + ParserImpl.prototype.canEatExplicitOrAutomaticSemicolon = function (allowWithoutNewline) { + var token = this.currentToken(); + + if (token.tokenKind === 78 /* SemicolonToken */) { + return true; + } + + return this.canEatAutomaticSemicolon(allowWithoutNewline); + }; + + ParserImpl.prototype.eatExplicitOrAutomaticSemicolon = function (allowWithoutNewline) { + var token = this.currentToken(); + + if (token.tokenKind === 78 /* SemicolonToken */) { + return this.eatToken(78 /* SemicolonToken */); + } + + if (this.canEatAutomaticSemicolon(allowWithoutNewline)) { + var semicolonToken = TypeScript.Syntax.emptyToken(78 /* SemicolonToken */); + + if (!this.parseOptions.allowAutomaticSemicolonInsertion()) { + this.addDiagnostic(new TypeScript.Diagnostic(this.fileName, this.lineMap, this.previousTokenEnd(), 0, TypeScript.DiagnosticCode.Automatic_semicolon_insertion_not_allowed, null)); + } + + return semicolonToken; + } + + return this.eatToken(78 /* SemicolonToken */); + }; + + ParserImpl.prototype.isKeyword = function (kind) { + if (kind >= 15 /* FirstKeyword */) { + if (kind <= 50 /* LastFutureReservedKeyword */) { + return true; + } + + if (this.isInStrictMode) { + return kind <= 59 /* LastFutureReservedStrictKeyword */; + } + } + + return false; + }; + + ParserImpl.prototype.createMissingToken = function (expectedKind, actual) { + var diagnostic = this.getExpectedTokenDiagnostic(expectedKind, actual); + this.addDiagnostic(diagnostic); + + return TypeScript.Syntax.emptyToken(expectedKind); + }; + + ParserImpl.prototype.getExpectedTokenDiagnostic = function (expectedKind, actual) { + var token = this.currentToken(); + + if (TypeScript.SyntaxFacts.isAnyKeyword(expectedKind) || TypeScript.SyntaxFacts.isAnyPunctuation(expectedKind)) { + return new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode._0_expected, [TypeScript.SyntaxFacts.getText(expectedKind)]); + } else { + if (actual !== null && TypeScript.SyntaxFacts.isAnyKeyword(actual.tokenKind)) { + return new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode.Identifier_expected_0_is_a_keyword, [TypeScript.SyntaxFacts.getText(actual.tokenKind)]); + } else { + return new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode.Identifier_expected, null); + } + } + }; + + ParserImpl.getPrecedence = function (expressionKind) { + switch (expressionKind) { + case 173 /* CommaExpression */: + return 1 /* CommaExpressionPrecedence */; + + case 174 /* AssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + return 2 /* AssignmentExpressionPrecedence */; + + case 186 /* ConditionalExpression */: + return 3 /* ConditionalExpressionPrecedence */; + + case 187 /* LogicalOrExpression */: + return 5 /* LogicalOrExpressionPrecedence */; + + case 188 /* LogicalAndExpression */: + return 6 /* LogicalAndExpressionPrecedence */; + + case 189 /* BitwiseOrExpression */: + return 7 /* BitwiseOrExpressionPrecedence */; + + case 190 /* BitwiseExclusiveOrExpression */: + return 8 /* BitwiseExclusiveOrExpressionPrecedence */; + + case 191 /* BitwiseAndExpression */: + return 9 /* BitwiseAndExpressionPrecedence */; + + case 192 /* EqualsWithTypeConversionExpression */: + case 193 /* NotEqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + return 10 /* EqualityExpressionPrecedence */; + + case 196 /* LessThanExpression */: + case 197 /* GreaterThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 200 /* InstanceOfExpression */: + case 201 /* InExpression */: + return 11 /* RelationalExpressionPrecedence */; + + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + return 12 /* ShiftExpressionPrecdence */; + + case 208 /* AddExpression */: + case 209 /* SubtractExpression */: + return 13 /* AdditiveExpressionPrecedence */; + + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + return 14 /* MultiplicativeExpressionPrecedence */; + + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + case 166 /* BitwiseNotExpression */: + case 167 /* LogicalNotExpression */: + case 170 /* DeleteExpression */: + case 171 /* TypeOfExpression */: + case 172 /* VoidExpression */: + case 168 /* PreIncrementExpression */: + case 169 /* PreDecrementExpression */: + return 15 /* UnaryExpressionPrecedence */; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + ParserImpl.prototype.addSkippedTokenAfterNodeOrToken = function (nodeOrToken, skippedToken) { + if (nodeOrToken.isToken()) { + return this.addSkippedTokenAfterToken(nodeOrToken, skippedToken); + } else if (nodeOrToken.isNode()) { + return this.addSkippedTokenAfterNode(nodeOrToken, skippedToken); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.addSkippedTokenAfterNode = function (node, skippedToken) { + var oldToken = node.lastToken(); + var newToken = this.addSkippedTokenAfterToken(oldToken, skippedToken); + + return node.replaceToken(oldToken, newToken); + }; + + ParserImpl.prototype.addSkippedTokensBeforeNode = function (node, skippedTokens) { + if (skippedTokens.length > 0) { + var oldToken = node.firstToken(); + var newToken = this.addSkippedTokensBeforeToken(oldToken, skippedTokens); + + return node.replaceToken(oldToken, newToken); + } + + return node; + }; + + ParserImpl.prototype.addSkippedTokensBeforeToken = function (token, skippedTokens) { + var leadingTrivia = []; + for (var i = 0, n = skippedTokens.length; i < n; i++) { + this.addSkippedTokenToTriviaArray(leadingTrivia, skippedTokens[i]); + } + + this.addTriviaTo(token.leadingTrivia(), leadingTrivia); + + this.returnArray(skippedTokens); + return token.withLeadingTrivia(TypeScript.Syntax.triviaList(leadingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokensAfterToken = function (token, skippedTokens) { + if (skippedTokens.length === 0) { + this.returnArray(skippedTokens); + return token; + } + + var trailingTrivia = token.trailingTrivia().toArray(); + + for (var i = 0, n = skippedTokens.length; i < n; i++) { + this.addSkippedTokenToTriviaArray(trailingTrivia, skippedTokens[i]); + } + + this.returnArray(skippedTokens); + return token.withTrailingTrivia(TypeScript.Syntax.triviaList(trailingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokenAfterToken = function (token, skippedToken) { + var trailingTrivia = token.trailingTrivia().toArray(); + this.addSkippedTokenToTriviaArray(trailingTrivia, skippedToken); + + return token.withTrailingTrivia(TypeScript.Syntax.triviaList(trailingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokenToTriviaArray = function (array, skippedToken) { + this.addTriviaTo(skippedToken.leadingTrivia(), array); + + var trimmedToken = skippedToken.withLeadingTrivia(TypeScript.Syntax.emptyTriviaList).withTrailingTrivia(TypeScript.Syntax.emptyTriviaList); + array.push(TypeScript.Syntax.skippedTokenTrivia(trimmedToken)); + + this.addTriviaTo(skippedToken.trailingTrivia(), array); + }; + + ParserImpl.prototype.addTriviaTo = function (list, array) { + for (var i = 0, n = list.count(); i < n; i++) { + array.push(list.syntaxTriviaAt(i)); + } + }; + + ParserImpl.prototype.parseSyntaxTree = function (isDeclaration) { + var sourceUnit = this.parseSourceUnit(); + + var allDiagnostics = this.source.tokenDiagnostics().concat(this.diagnostics); + allDiagnostics.sort(function (a, b) { + return a.start() - b.start(); + }); + + return new TypeScript.SyntaxTree(sourceUnit, isDeclaration, allDiagnostics, this.fileName, this.lineMap, this.parseOptions); + }; + + ParserImpl.prototype.setStrictMode = function (isInStrictMode) { + this.isInStrictMode = isInStrictMode; + this.factory = isInStrictMode ? TypeScript.Syntax.strictModeFactory : TypeScript.Syntax.normalModeFactory; + }; + + ParserImpl.prototype.parseSourceUnit = function () { + var savedIsInStrictMode = this.isInStrictMode; + + var result = this.parseSyntaxList(1 /* SourceUnit_ModuleElements */, ParserImpl.updateStrictModeState); + var moduleElements = result.list; + + this.setStrictMode(savedIsInStrictMode); + + var sourceUnit = this.factory.sourceUnit(moduleElements, this.currentToken()); + sourceUnit = this.addSkippedTokensBeforeNode(sourceUnit, result.skippedTokens); + + if (TypeScript.Debug.shouldAssert(2 /* Aggressive */)) { + TypeScript.Debug.assert(sourceUnit.fullWidth() === this.newText_forDebuggingPurposesOnly.length()); + + if (TypeScript.Debug.shouldAssert(3 /* VeryAggressive */)) { + TypeScript.Debug.assert(sourceUnit.fullText() === this.newText_forDebuggingPurposesOnly.substr(0, this.newText_forDebuggingPurposesOnly.length(), false)); + } + } + + return sourceUnit; + }; + + ParserImpl.updateStrictModeState = function (parser, items) { + if (!parser.isInStrictMode) { + for (var i = 0; i < items.length; i++) { + var item = items[i]; + if (!TypeScript.SyntaxFacts.isDirectivePrologueElement(item)) { + return; + } + } + + parser.setStrictMode(TypeScript.SyntaxFacts.isUseStrictDirective(items[items.length - 1])); + } + }; + + ParserImpl.prototype.isModuleElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isModuleElement()) { + return true; + } + + var modifierCount = this.modifierCount(); + return this.isImportDeclaration(modifierCount) || this.isExportAssignment() || this.isModuleDeclaration(modifierCount) || this.isInterfaceDeclaration(modifierCount) || this.isClassDeclaration(modifierCount) || this.isEnumDeclaration(modifierCount) || this.isStatement(inErrorRecovery); + }; + + ParserImpl.prototype.parseModuleElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isModuleElement()) { + return this.eatNode(); + } + + var modifierCount = this.modifierCount(); + if (this.isImportDeclaration(modifierCount)) { + return this.parseImportDeclaration(); + } else if (this.isExportAssignment()) { + return this.parseExportAssignment(); + } else if (this.isModuleDeclaration(modifierCount)) { + return this.parseModuleDeclaration(); + } else if (this.isInterfaceDeclaration(modifierCount)) { + return this.parseInterfaceDeclaration(); + } else if (this.isClassDeclaration(modifierCount)) { + return this.parseClassDeclaration(); + } else if (this.isEnumDeclaration(modifierCount)) { + return this.parseEnumDeclaration(); + } else if (this.isStatement(inErrorRecovery)) { + return this.parseStatement(inErrorRecovery); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isImportDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 49 /* ImportKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 49 /* ImportKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseImportDeclaration = function () { + var modifiers = this.parseModifiers(); + var importKeyword = this.eatKeyword(49 /* ImportKeyword */); + var identifier = this.eatIdentifierToken(); + var equalsToken = this.eatToken(107 /* EqualsToken */); + var moduleReference = this.parseModuleReference(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.importDeclaration(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken); + }; + + ParserImpl.prototype.isExportAssignment = function () { + return this.currentToken().tokenKind === 47 /* ExportKeyword */ && this.peekToken(1).tokenKind === 107 /* EqualsToken */; + }; + + ParserImpl.prototype.parseExportAssignment = function () { + var exportKeyword = this.eatKeyword(47 /* ExportKeyword */); + var equalsToken = this.eatToken(107 /* EqualsToken */); + var identifier = this.eatIdentifierToken(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.exportAssignment(exportKeyword, equalsToken, identifier, semicolonToken); + }; + + ParserImpl.prototype.parseModuleReference = function () { + if (this.isExternalModuleReference()) { + return this.parseExternalModuleReference(); + } else { + return this.parseModuleNameModuleReference(); + } + }; + + ParserImpl.prototype.isExternalModuleReference = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 66 /* RequireKeyword */) { + return this.peekToken(1).tokenKind === 72 /* OpenParenToken */; + } + + return false; + }; + + ParserImpl.prototype.parseExternalModuleReference = function () { + var requireKeyword = this.eatKeyword(66 /* RequireKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var stringLiteral = this.eatToken(14 /* StringLiteral */); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + return this.factory.externalModuleReference(requireKeyword, openParenToken, stringLiteral, closeParenToken); + }; + + ParserImpl.prototype.parseModuleNameModuleReference = function () { + var name = this.parseName(); + return this.factory.moduleNameModuleReference(name); + }; + + ParserImpl.prototype.parseIdentifierName = function () { + var identifierName = this.eatIdentifierNameToken(); + return identifierName; + }; + + ParserImpl.prototype.tryParseTypeArgumentList = function (inExpression) { + if (this.currentToken().kind() !== 80 /* LessThanToken */) { + return null; + } + + var lessThanToken; + var greaterThanToken; + var result; + var typeArguments; + + if (!inExpression) { + lessThanToken = this.eatToken(80 /* LessThanToken */); + + result = this.parseSeparatedSyntaxList(262144 /* TypeArgumentList_Types */); + typeArguments = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + + return this.factory.typeArgumentList(lessThanToken, typeArguments, greaterThanToken); + } + + var rewindPoint = this.getRewindPoint(); + + lessThanToken = this.eatToken(80 /* LessThanToken */); + + result = this.parseSeparatedSyntaxList(262144 /* TypeArgumentList_Types */); + typeArguments = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + + if (greaterThanToken.fullWidth() === 0 || !this.canFollowTypeArgumentListInExpression(this.currentToken().kind())) { + this.rewind(rewindPoint); + + this.releaseRewindPoint(rewindPoint); + return null; + } else { + this.releaseRewindPoint(rewindPoint); + var typeArgumentList = this.factory.typeArgumentList(lessThanToken, typeArguments, greaterThanToken); + + return typeArgumentList; + } + }; + + ParserImpl.prototype.canFollowTypeArgumentListInExpression = function (kind) { + switch (kind) { + case 72 /* OpenParenToken */: + case 76 /* DotToken */: + + case 73 /* CloseParenToken */: + case 75 /* CloseBracketToken */: + case 106 /* ColonToken */: + case 78 /* SemicolonToken */: + case 79 /* CommaToken */: + case 105 /* QuestionToken */: + case 84 /* EqualsEqualsToken */: + case 87 /* EqualsEqualsEqualsToken */: + case 86 /* ExclamationEqualsToken */: + case 88 /* ExclamationEqualsEqualsToken */: + case 103 /* AmpersandAmpersandToken */: + case 104 /* BarBarToken */: + case 100 /* CaretToken */: + case 98 /* AmpersandToken */: + case 99 /* BarToken */: + case 71 /* CloseBraceToken */: + case 10 /* EndOfFileToken */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.parseName = function () { + var shouldContinue = this.isIdentifier(this.currentToken()); + var current = this.eatIdentifierToken(); + + while (shouldContinue && this.currentToken().tokenKind === 76 /* DotToken */) { + var dotToken = this.eatToken(76 /* DotToken */); + + var currentToken = this.currentToken(); + var identifierName; + + if (TypeScript.SyntaxFacts.isAnyKeyword(currentToken.tokenKind) && this.previousToken().hasTrailingNewLine() && !currentToken.hasTrailingNewLine() && TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(this.peekToken(1))) { + identifierName = this.createMissingToken(11 /* IdentifierName */, currentToken); + } else { + identifierName = this.eatIdentifierNameToken(); + } + + current = this.factory.qualifiedName(current, dotToken, identifierName); + + shouldContinue = identifierName.fullWidth() > 0; + } + + return current; + }; + + ParserImpl.prototype.isEnumDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 46 /* EnumKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 46 /* EnumKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseEnumDeclaration = function () { + var modifiers = this.parseModifiers(); + var enumKeyword = this.eatKeyword(46 /* EnumKeyword */); + var identifier = this.eatIdentifierToken(); + + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + var enumElements = TypeScript.Syntax.emptySeparatedList; + + if (openBraceToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(256 /* EnumDeclaration_EnumElements */); + enumElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.enumDeclaration(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken); + }; + + ParserImpl.prototype.isEnumElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().kind() === 243 /* EnumElement */) { + return true; + } + + return this.isPropertyName(this.currentToken(), inErrorRecovery); + }; + + ParserImpl.prototype.parseEnumElement = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 243 /* EnumElement */) { + return this.eatNode(); + } + + var propertyName = this.eatPropertyName(); + var equalsValueClause = null; + if (this.isEqualsValueClause(false)) { + equalsValueClause = this.parseEqualsValueClause(true); + } + + return this.factory.enumElement(propertyName, equalsValueClause); + }; + + ParserImpl.isModifier = function (token) { + switch (token.tokenKind) { + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + case 47 /* ExportKeyword */: + case 63 /* DeclareKeyword */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.modifierCount = function () { + var modifierCount = 0; + while (true) { + if (ParserImpl.isModifier(this.peekToken(modifierCount))) { + modifierCount++; + continue; + } + + break; + } + + return modifierCount; + }; + + ParserImpl.prototype.parseModifiers = function () { + var tokens = this.getArray(); + + while (true) { + if (ParserImpl.isModifier(this.currentToken())) { + tokens.push(this.eatAnyToken()); + continue; + } + + break; + } + + var result = TypeScript.Syntax.list(tokens); + + this.returnZeroOrOneLengthArray(tokens); + + return result; + }; + + ParserImpl.prototype.isClassDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 44 /* ClassKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 44 /* ClassKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseHeritageClauses = function () { + var heritageClauses = TypeScript.Syntax.emptyList; + + if (this.isHeritageClause()) { + var result = this.parseSyntaxList(1024 /* ClassOrInterfaceDeclaration_HeritageClauses */); + heritageClauses = result.list; + TypeScript.Debug.assert(result.skippedTokens.length === 0); + } + + return heritageClauses; + }; + + ParserImpl.prototype.parseClassDeclaration = function () { + var modifiers = this.parseModifiers(); + + var classKeyword = this.eatKeyword(44 /* ClassKeyword */); + var identifier = this.eatIdentifierToken(); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var heritageClauses = this.parseHeritageClauses(); + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + var classElements = TypeScript.Syntax.emptyList; + + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(2 /* ClassDeclaration_ClassElements */); + + classElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + return this.factory.classDeclaration(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken); + }; + + ParserImpl.isPublicOrPrivateKeyword = function (token) { + return token.tokenKind === 57 /* PublicKeyword */ || token.tokenKind === 55 /* PrivateKeyword */; + }; + + ParserImpl.prototype.isAccessor = function (inErrorRecovery) { + var index = this.modifierCount(); + + if (this.peekToken(index).tokenKind !== 64 /* GetKeyword */ && this.peekToken(index).tokenKind !== 68 /* SetKeyword */) { + return false; + } + + index++; + return this.isPropertyName(this.peekToken(index), inErrorRecovery); + }; + + ParserImpl.prototype.parseAccessor = function (checkForStrictMode) { + var modifiers = this.parseModifiers(); + + if (this.currentToken().tokenKind === 64 /* GetKeyword */) { + return this.parseGetMemberAccessorDeclaration(modifiers, checkForStrictMode); + } else if (this.currentToken().tokenKind === 68 /* SetKeyword */) { + return this.parseSetMemberAccessorDeclaration(modifiers, checkForStrictMode); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseGetMemberAccessorDeclaration = function (modifiers, checkForStrictMode) { + var getKeyword = this.eatKeyword(64 /* GetKeyword */); + var propertyName = this.eatPropertyName(); + var parameterList = this.parseParameterList(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + var block = this.parseBlock(false, checkForStrictMode); + + return this.factory.getAccessor(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block); + }; + + ParserImpl.prototype.parseSetMemberAccessorDeclaration = function (modifiers, checkForStrictMode) { + var setKeyword = this.eatKeyword(68 /* SetKeyword */); + var propertyName = this.eatPropertyName(); + var parameterList = this.parseParameterList(); + var block = this.parseBlock(false, checkForStrictMode); + + return this.factory.setAccessor(modifiers, setKeyword, propertyName, parameterList, block); + }; + + ParserImpl.prototype.isClassElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isClassElement()) { + return true; + } + + return this.isConstructorDeclaration() || this.isMemberFunctionDeclaration(inErrorRecovery) || this.isAccessor(inErrorRecovery) || this.isMemberVariableDeclaration(inErrorRecovery) || this.isIndexMemberDeclaration(); + }; + + ParserImpl.prototype.parseClassElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isClassElement()) { + return this.eatNode(); + } + + if (this.isConstructorDeclaration()) { + return this.parseConstructorDeclaration(); + } else if (this.isMemberFunctionDeclaration(inErrorRecovery)) { + return this.parseMemberFunctionDeclaration(); + } else if (this.isAccessor(inErrorRecovery)) { + return this.parseAccessor(false); + } else if (this.isMemberVariableDeclaration(inErrorRecovery)) { + return this.parseMemberVariableDeclaration(); + } else if (this.isIndexMemberDeclaration()) { + return this.parseIndexMemberDeclaration(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isConstructorDeclaration = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 62 /* ConstructorKeyword */; + }; + + ParserImpl.prototype.parseConstructorDeclaration = function () { + var modifiers = this.parseModifiers(); + var constructorKeyword = this.eatKeyword(62 /* ConstructorKeyword */); + var callSignature = this.parseCallSignature(false); + + var semicolonToken = null; + var block = null; + + if (this.isBlock()) { + block = this.parseBlock(false, true); + } else { + semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.constructorDeclaration(modifiers, constructorKeyword, callSignature, block, semicolonToken); + }; + + ParserImpl.prototype.isMemberFunctionDeclaration = function (inErrorRecovery) { + var index = 0; + + while (true) { + var token = this.peekToken(index); + if (this.isPropertyName(token, inErrorRecovery) && this.isCallSignature(index + 1)) { + return true; + } + + if (ParserImpl.isModifier(token)) { + index++; + continue; + } + + return false; + } + }; + + ParserImpl.prototype.parseMemberFunctionDeclaration = function () { + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (this.isPropertyName(currentToken, false) && this.isCallSignature(1)) { + break; + } + + TypeScript.Debug.assert(ParserImpl.isModifier(currentToken)); + modifierArray.push(this.eatAnyToken()); + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var propertyName = this.eatPropertyName(); + var callSignature = this.parseCallSignature(false); + + var parseBlockEvenWithNoOpenBrace = false; + var newCallSignature = this.tryAddUnexpectedEqualsGreaterThanToken(callSignature); + if (newCallSignature !== callSignature) { + parseBlockEvenWithNoOpenBrace = true; + callSignature = newCallSignature; + } + + var block = null; + var semicolon = null; + + if (parseBlockEvenWithNoOpenBrace || this.isBlock()) { + block = this.parseBlock(parseBlockEvenWithNoOpenBrace, true); + } else { + semicolon = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.memberFunctionDeclaration(modifiers, propertyName, callSignature, block, semicolon); + }; + + ParserImpl.prototype.isDefinitelyMemberVariablePropertyName = function (index) { + if (TypeScript.SyntaxFacts.isAnyKeyword(this.peekToken(index).tokenKind)) { + switch (this.peekToken(index + 1).tokenKind) { + case 78 /* SemicolonToken */: + case 107 /* EqualsToken */: + case 106 /* ColonToken */: + case 71 /* CloseBraceToken */: + case 10 /* EndOfFileToken */: + return true; + default: + return false; + } + } else { + return true; + } + }; + + ParserImpl.prototype.isMemberVariableDeclaration = function (inErrorRecovery) { + var index = 0; + + while (true) { + var token = this.peekToken(index); + if (this.isPropertyName(token, inErrorRecovery) && this.isDefinitelyMemberVariablePropertyName(index)) { + return true; + } + + if (ParserImpl.isModifier(this.peekToken(index))) { + index++; + continue; + } + + return false; + } + }; + + ParserImpl.prototype.parseMemberVariableDeclaration = function () { + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (this.isPropertyName(currentToken, false) && this.isDefinitelyMemberVariablePropertyName(0)) { + break; + } + + TypeScript.Debug.assert(ParserImpl.isModifier(currentToken)); + modifierArray.push(this.eatAnyToken()); + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var variableDeclarator = this.parseVariableDeclarator(true, true); + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.memberVariableDeclaration(modifiers, variableDeclarator, semicolon); + }; + + ParserImpl.prototype.isIndexMemberDeclaration = function () { + var index = this.modifierCount(); + return this.isIndexSignature(index); + }; + + ParserImpl.prototype.parseIndexMemberDeclaration = function () { + var modifiers = this.parseModifiers(); + var indexSignature = this.parseIndexSignature(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.indexMemberDeclaration(modifiers, indexSignature, semicolonToken); + }; + + ParserImpl.prototype.tryAddUnexpectedEqualsGreaterThanToken = function (callSignature) { + var token0 = this.currentToken(); + + var hasEqualsGreaterThanToken = token0.tokenKind === 85 /* EqualsGreaterThanToken */; + if (hasEqualsGreaterThanToken) { + if (callSignature.lastToken()) { + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token0.width(), TypeScript.DiagnosticCode.Unexpected_token_0_expected, [TypeScript.SyntaxFacts.getText(70 /* OpenBraceToken */)]); + this.addDiagnostic(diagnostic); + + var token = this.eatAnyToken(); + return this.addSkippedTokenAfterNode(callSignature, token0); + } + } + + return callSignature; + }; + + ParserImpl.prototype.isFunctionDeclaration = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 27 /* FunctionKeyword */; + }; + + ParserImpl.prototype.parseFunctionDeclaration = function () { + var modifiers = this.parseModifiers(); + var functionKeyword = this.eatKeyword(27 /* FunctionKeyword */); + var identifier = this.eatIdentifierToken(); + var callSignature = this.parseCallSignature(false); + + var parseBlockEvenWithNoOpenBrace = false; + var newCallSignature = this.tryAddUnexpectedEqualsGreaterThanToken(callSignature); + if (newCallSignature !== callSignature) { + parseBlockEvenWithNoOpenBrace = true; + callSignature = newCallSignature; + } + + var semicolonToken = null; + var block = null; + + if (parseBlockEvenWithNoOpenBrace || this.isBlock()) { + block = this.parseBlock(parseBlockEvenWithNoOpenBrace, true); + } else { + semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.functionDeclaration(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken); + }; + + ParserImpl.prototype.isModuleDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 65 /* ModuleKeyword */) { + return true; + } + + if (this.currentToken().tokenKind === 65 /* ModuleKeyword */) { + var token1 = this.peekToken(1); + return this.isIdentifier(token1) || token1.tokenKind === 14 /* StringLiteral */; + } + + return false; + }; + + ParserImpl.prototype.parseModuleDeclaration = function () { + var modifiers = this.parseModifiers(); + var moduleKeyword = this.eatKeyword(65 /* ModuleKeyword */); + + var moduleName = null; + var stringLiteral = null; + + if (this.currentToken().tokenKind === 14 /* StringLiteral */) { + stringLiteral = this.eatToken(14 /* StringLiteral */); + } else { + moduleName = this.parseName(); + } + + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var moduleElements = TypeScript.Syntax.emptyList; + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(4 /* ModuleDeclaration_ModuleElements */); + moduleElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.moduleDeclaration(modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken); + }; + + ParserImpl.prototype.isInterfaceDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 52 /* InterfaceKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 52 /* InterfaceKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseInterfaceDeclaration = function () { + var modifiers = this.parseModifiers(); + var interfaceKeyword = this.eatKeyword(52 /* InterfaceKeyword */); + var identifier = this.eatIdentifierToken(); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var heritageClauses = this.parseHeritageClauses(); + + var objectType = this.parseObjectType(); + return this.factory.interfaceDeclaration(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, objectType); + }; + + ParserImpl.prototype.parseObjectType = function () { + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var typeMembers = TypeScript.Syntax.emptySeparatedList; + if (openBraceToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(512 /* ObjectType_TypeMembers */); + typeMembers = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + return this.factory.objectType(openBraceToken, typeMembers, closeBraceToken); + }; + + ParserImpl.prototype.isTypeMember = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isTypeMember()) { + return true; + } + + return this.isCallSignature(0) || this.isConstructSignature() || this.isIndexSignature(0) || this.isMethodSignature(inErrorRecovery) || this.isPropertySignature(inErrorRecovery); + }; + + ParserImpl.prototype.parseTypeMember = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isTypeMember()) { + return this.eatNode(); + } + + if (this.isCallSignature(0)) { + return this.parseCallSignature(false); + } else if (this.isConstructSignature()) { + return this.parseConstructSignature(); + } else if (this.isIndexSignature(0)) { + return this.parseIndexSignature(); + } else if (this.isMethodSignature(inErrorRecovery)) { + return this.parseMethodSignature(); + } else if (this.isPropertySignature(inErrorRecovery)) { + return this.parsePropertySignature(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseConstructSignature = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + var callSignature = this.parseCallSignature(false); + + return this.factory.constructSignature(newKeyword, callSignature); + }; + + ParserImpl.prototype.parseIndexSignature = function () { + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + var parameter = this.parseParameter(); + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.indexSignature(openBracketToken, parameter, closeBracketToken, typeAnnotation); + }; + + ParserImpl.prototype.parseMethodSignature = function () { + var propertyName = this.eatPropertyName(); + var questionToken = this.tryEatToken(105 /* QuestionToken */); + var callSignature = this.parseCallSignature(false); + + return this.factory.methodSignature(propertyName, questionToken, callSignature); + }; + + ParserImpl.prototype.parsePropertySignature = function () { + var propertyName = this.eatPropertyName(); + var questionToken = this.tryEatToken(105 /* QuestionToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.propertySignature(propertyName, questionToken, typeAnnotation); + }; + + ParserImpl.prototype.isCallSignature = function (tokenIndex) { + var tokenKind = this.peekToken(tokenIndex).tokenKind; + return tokenKind === 72 /* OpenParenToken */ || tokenKind === 80 /* LessThanToken */; + }; + + ParserImpl.prototype.isConstructSignature = function () { + if (this.currentToken().tokenKind !== 31 /* NewKeyword */) { + return false; + } + + var token1 = this.peekToken(1); + return token1.tokenKind === 80 /* LessThanToken */ || token1.tokenKind === 72 /* OpenParenToken */; + }; + + ParserImpl.prototype.isIndexSignature = function (tokenIndex) { + return this.peekToken(tokenIndex).tokenKind === 74 /* OpenBracketToken */; + }; + + ParserImpl.prototype.isMethodSignature = function (inErrorRecovery) { + if (this.isPropertyName(this.currentToken(), inErrorRecovery)) { + if (this.isCallSignature(1)) { + return true; + } + + if (this.peekToken(1).tokenKind === 105 /* QuestionToken */ && this.isCallSignature(2)) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.isPropertySignature = function (inErrorRecovery) { + var currentToken = this.currentToken(); + + if (ParserImpl.isModifier(currentToken) && !currentToken.hasTrailingNewLine() && this.isPropertyName(this.peekToken(1), inErrorRecovery)) { + return false; + } + + return this.isPropertyName(currentToken, inErrorRecovery); + }; + + ParserImpl.prototype.isHeritageClause = function () { + var token0 = this.currentToken(); + return token0.tokenKind === 48 /* ExtendsKeyword */ || token0.tokenKind === 51 /* ImplementsKeyword */; + }; + + ParserImpl.prototype.isNotHeritageClauseTypeName = function () { + if (this.currentToken().tokenKind === 51 /* ImplementsKeyword */ || this.currentToken().tokenKind === 48 /* ExtendsKeyword */) { + return this.isIdentifier(this.peekToken(1)); + } + + return false; + }; + + ParserImpl.prototype.isHeritageClauseTypeName = function () { + if (this.isIdentifier(this.currentToken())) { + return !this.isNotHeritageClauseTypeName(); + } + + return false; + }; + + ParserImpl.prototype.parseHeritageClause = function () { + var extendsOrImplementsKeyword = this.eatAnyToken(); + TypeScript.Debug.assert(extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */ || extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + + var result = this.parseSeparatedSyntaxList(2048 /* HeritageClause_TypeNameList */); + var typeNames = result.list; + extendsOrImplementsKeyword = this.addSkippedTokensAfterToken(extendsOrImplementsKeyword, result.skippedTokens); + + return this.factory.heritageClause(extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */ ? 230 /* ExtendsHeritageClause */ : 231 /* ImplementsHeritageClause */, extendsOrImplementsKeyword, typeNames); + }; + + ParserImpl.prototype.isStatement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isStatement()) { + return true; + } + + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + switch (currentTokenKind) { + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + var token1 = this.peekToken(1); + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token1)) { + return false; + } + + break; + + case 28 /* IfKeyword */: + case 70 /* OpenBraceToken */: + case 33 /* ReturnKeyword */: + case 34 /* SwitchKeyword */: + case 36 /* ThrowKeyword */: + case 15 /* BreakKeyword */: + case 18 /* ContinueKeyword */: + case 26 /* ForKeyword */: + case 42 /* WhileKeyword */: + case 43 /* WithKeyword */: + case 22 /* DoKeyword */: + case 38 /* TryKeyword */: + case 19 /* DebuggerKeyword */: + return true; + } + + if (this.isInterfaceDeclaration(0) || this.isClassDeclaration(0) || this.isEnumDeclaration(0) || this.isModuleDeclaration(0)) { + return false; + } + + return this.isLabeledStatement(currentToken) || this.isVariableStatement() || this.isFunctionDeclaration() || this.isEmptyStatement(currentToken, inErrorRecovery) || this.isExpressionStatement(currentToken); + }; + + ParserImpl.prototype.parseStatement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isStatement()) { + return this.eatNode(); + } + + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + + switch (currentTokenKind) { + case 28 /* IfKeyword */: + return this.parseIfStatement(); + case 70 /* OpenBraceToken */: + return this.parseBlock(false, false); + case 33 /* ReturnKeyword */: + return this.parseReturnStatement(); + case 34 /* SwitchKeyword */: + return this.parseSwitchStatement(); + case 36 /* ThrowKeyword */: + return this.parseThrowStatement(); + case 15 /* BreakKeyword */: + return this.parseBreakStatement(); + case 18 /* ContinueKeyword */: + return this.parseContinueStatement(); + case 26 /* ForKeyword */: + return this.parseForOrForInStatement(); + case 42 /* WhileKeyword */: + return this.parseWhileStatement(); + case 43 /* WithKeyword */: + return this.parseWithStatement(); + case 22 /* DoKeyword */: + return this.parseDoStatement(); + case 38 /* TryKeyword */: + return this.parseTryStatement(); + case 19 /* DebuggerKeyword */: + return this.parseDebuggerStatement(); + } + + if (this.isVariableStatement()) { + return this.parseVariableStatement(); + } else if (this.isLabeledStatement(currentToken)) { + return this.parseLabeledStatement(); + } else if (this.isFunctionDeclaration()) { + return this.parseFunctionDeclaration(); + } else if (this.isEmptyStatement(currentToken, inErrorRecovery)) { + return this.parseEmptyStatement(); + } else { + return this.parseExpressionStatement(); + } + }; + + ParserImpl.prototype.parseDebuggerStatement = function () { + var debuggerKeyword = this.eatKeyword(19 /* DebuggerKeyword */); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.debuggerStatement(debuggerKeyword, semicolonToken); + }; + + ParserImpl.prototype.parseDoStatement = function () { + var doKeyword = this.eatKeyword(22 /* DoKeyword */); + var statement = this.parseStatement(false); + var whileKeyword = this.eatKeyword(42 /* WhileKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(true); + + return this.factory.doStatement(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); + }; + + ParserImpl.prototype.isLabeledStatement = function (currentToken) { + return this.isIdentifier(currentToken) && this.peekToken(1).tokenKind === 106 /* ColonToken */; + }; + + ParserImpl.prototype.parseLabeledStatement = function () { + var identifier = this.eatIdentifierToken(); + var colonToken = this.eatToken(106 /* ColonToken */); + var statement = this.parseStatement(false); + + return this.factory.labeledStatement(identifier, colonToken, statement); + }; + + ParserImpl.prototype.parseTryStatement = function () { + var tryKeyword = this.eatKeyword(38 /* TryKeyword */); + + var savedListParsingState = this.listParsingState; + this.listParsingState |= 64 /* TryBlock_Statements */; + var block = this.parseBlock(false, false); + this.listParsingState = savedListParsingState; + + var catchClause = null; + if (this.isCatchClause()) { + catchClause = this.parseCatchClause(); + } + + var finallyClause = null; + if (catchClause === null || this.isFinallyClause()) { + finallyClause = this.parseFinallyClause(); + } + + return this.factory.tryStatement(tryKeyword, block, catchClause, finallyClause); + }; + + ParserImpl.prototype.isCatchClause = function () { + return this.currentToken().tokenKind === 17 /* CatchKeyword */; + }; + + ParserImpl.prototype.parseCatchClause = function () { + var catchKeyword = this.eatKeyword(17 /* CatchKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var identifier = this.eatIdentifierToken(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + var savedListParsingState = this.listParsingState; + this.listParsingState |= 128 /* CatchBlock_Statements */; + var block = this.parseBlock(false, false); + this.listParsingState = savedListParsingState; + + return this.factory.catchClause(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block); + }; + + ParserImpl.prototype.isFinallyClause = function () { + return this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.parseFinallyClause = function () { + var finallyKeyword = this.eatKeyword(25 /* FinallyKeyword */); + var block = this.parseBlock(false, false); + + return this.factory.finallyClause(finallyKeyword, block); + }; + + ParserImpl.prototype.parseWithStatement = function () { + var withKeyword = this.eatKeyword(43 /* WithKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.withStatement(withKeyword, openParenToken, condition, closeParenToken, statement); + }; + + ParserImpl.prototype.parseWhileStatement = function () { + var whileKeyword = this.eatKeyword(42 /* WhileKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.whileStatement(whileKeyword, openParenToken, condition, closeParenToken, statement); + }; + + ParserImpl.prototype.isEmptyStatement = function (currentToken, inErrorRecovery) { + if (inErrorRecovery) { + return false; + } + + return currentToken.tokenKind === 78 /* SemicolonToken */; + }; + + ParserImpl.prototype.parseEmptyStatement = function () { + var semicolonToken = this.eatToken(78 /* SemicolonToken */); + return this.factory.emptyStatement(semicolonToken); + }; + + ParserImpl.prototype.parseForOrForInStatement = function () { + var forKeyword = this.eatKeyword(26 /* ForKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + + var currentToken = this.currentToken(); + if (currentToken.tokenKind === 40 /* VarKeyword */) { + return this.parseForOrForInStatementWithVariableDeclaration(forKeyword, openParenToken); + } else if (currentToken.tokenKind === 78 /* SemicolonToken */) { + return this.parseForStatementWithNoVariableDeclarationOrInitializer(forKeyword, openParenToken); + } else { + return this.parseForOrForInStatementWithInitializer(forKeyword, openParenToken); + } + }; + + ParserImpl.prototype.parseForOrForInStatementWithVariableDeclaration = function (forKeyword, openParenToken) { + var variableDeclaration = this.parseVariableDeclaration(false); + + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return this.parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null); + } + + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null); + }; + + ParserImpl.prototype.parseForInStatementWithVariableDeclarationOrInitializer = function (forKeyword, openParenToken, variableDeclaration, initializer) { + var inKeyword = this.eatKeyword(29 /* InKeyword */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.forInStatement(forKeyword, openParenToken, variableDeclaration, initializer, inKeyword, expression, closeParenToken, statement); + }; + + ParserImpl.prototype.parseForOrForInStatementWithInitializer = function (forKeyword, openParenToken) { + var initializer = this.parseExpression(false); + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return this.parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + } else { + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + } + }; + + ParserImpl.prototype.parseForStatementWithNoVariableDeclarationOrInitializer = function (forKeyword, openParenToken) { + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, null); + }; + + ParserImpl.prototype.parseForStatementWithVariableDeclarationOrInitializer = function (forKeyword, openParenToken, variableDeclaration, initializer) { + var firstSemicolonToken = this.eatToken(78 /* SemicolonToken */); + + var condition = null; + if (this.currentToken().tokenKind !== 78 /* SemicolonToken */ && this.currentToken().tokenKind !== 73 /* CloseParenToken */ && this.currentToken().tokenKind !== 10 /* EndOfFileToken */) { + condition = this.parseExpression(true); + } + + var secondSemicolonToken = this.eatToken(78 /* SemicolonToken */); + + var incrementor = null; + if (this.currentToken().tokenKind !== 73 /* CloseParenToken */ && this.currentToken().tokenKind !== 10 /* EndOfFileToken */) { + incrementor = this.parseExpression(true); + } + + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.forStatement(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement); + }; + + ParserImpl.prototype.parseBreakStatement = function () { + var breakKeyword = this.eatKeyword(15 /* BreakKeyword */); + + var identifier = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + } + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + return this.factory.breakStatement(breakKeyword, identifier, semicolon); + }; + + ParserImpl.prototype.parseContinueStatement = function () { + var continueKeyword = this.eatKeyword(18 /* ContinueKeyword */); + + var identifier = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + } + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + return this.factory.continueStatement(continueKeyword, identifier, semicolon); + }; + + ParserImpl.prototype.parseSwitchStatement = function () { + var switchKeyword = this.eatKeyword(34 /* SwitchKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var switchClauses = TypeScript.Syntax.emptyList; + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(8 /* SwitchStatement_SwitchClauses */); + switchClauses = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + return this.factory.switchStatement(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken); + }; + + ParserImpl.prototype.isCaseSwitchClause = function () { + return this.currentToken().tokenKind === 16 /* CaseKeyword */; + }; + + ParserImpl.prototype.isDefaultSwitchClause = function () { + return this.currentToken().tokenKind === 20 /* DefaultKeyword */; + }; + + ParserImpl.prototype.isSwitchClause = function () { + if (this.currentNode() !== null && this.currentNode().isSwitchClause()) { + return true; + } + + return this.isCaseSwitchClause() || this.isDefaultSwitchClause(); + }; + + ParserImpl.prototype.parseSwitchClause = function () { + if (this.currentNode() !== null && this.currentNode().isSwitchClause()) { + return this.eatNode(); + } + + if (this.isCaseSwitchClause()) { + return this.parseCaseSwitchClause(); + } else if (this.isDefaultSwitchClause()) { + return this.parseDefaultSwitchClause(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseCaseSwitchClause = function () { + var caseKeyword = this.eatKeyword(16 /* CaseKeyword */); + var expression = this.parseExpression(true); + var colonToken = this.eatToken(106 /* ColonToken */); + var statements = TypeScript.Syntax.emptyList; + + if (colonToken.fullWidth() > 0) { + var result = this.parseSyntaxList(16 /* SwitchClause_Statements */); + statements = result.list; + colonToken = this.addSkippedTokensAfterToken(colonToken, result.skippedTokens); + } + + return this.factory.caseSwitchClause(caseKeyword, expression, colonToken, statements); + }; + + ParserImpl.prototype.parseDefaultSwitchClause = function () { + var defaultKeyword = this.eatKeyword(20 /* DefaultKeyword */); + var colonToken = this.eatToken(106 /* ColonToken */); + var statements = TypeScript.Syntax.emptyList; + + if (colonToken.fullWidth() > 0) { + var result = this.parseSyntaxList(16 /* SwitchClause_Statements */); + statements = result.list; + colonToken = this.addSkippedTokensAfterToken(colonToken, result.skippedTokens); + } + + return this.factory.defaultSwitchClause(defaultKeyword, colonToken, statements); + }; + + ParserImpl.prototype.parseThrowStatement = function () { + var throwKeyword = this.eatKeyword(36 /* ThrowKeyword */); + + var expression = null; + if (this.canEatExplicitOrAutomaticSemicolon(false)) { + var token = this.createMissingToken(11 /* IdentifierName */, null); + expression = token; + } else { + expression = this.parseExpression(true); + } + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.throwStatement(throwKeyword, expression, semicolonToken); + }; + + ParserImpl.prototype.parseReturnStatement = function () { + var returnKeyword = this.eatKeyword(33 /* ReturnKeyword */); + + var expression = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + expression = this.parseExpression(true); + } + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.returnStatement(returnKeyword, expression, semicolonToken); + }; + + ParserImpl.prototype.isExpressionStatement = function (currentToken) { + var kind = currentToken.tokenKind; + if (kind === 70 /* OpenBraceToken */ || kind === 27 /* FunctionKeyword */) { + return false; + } + + return this.isExpression(currentToken); + }; + + ParserImpl.prototype.isAssignmentOrOmittedExpression = function () { + var currentToken = this.currentToken(); + if (currentToken.tokenKind === 79 /* CommaToken */) { + return true; + } + + return this.isExpression(currentToken); + }; + + ParserImpl.prototype.parseAssignmentOrOmittedExpression = function () { + if (this.currentToken().tokenKind === 79 /* CommaToken */) { + return this.factory.omittedExpression(); + } + + return this.parseAssignmentExpression(true); + }; + + ParserImpl.prototype.isExpression = function (currentToken) { + switch (currentToken.tokenKind) { + case 13 /* NumericLiteral */: + case 14 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + + case 74 /* OpenBracketToken */: + + case 72 /* OpenParenToken */: + + case 80 /* LessThanToken */: + + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + case 89 /* PlusToken */: + case 90 /* MinusToken */: + case 102 /* TildeToken */: + case 101 /* ExclamationToken */: + + case 70 /* OpenBraceToken */: + + case 85 /* EqualsGreaterThanToken */: + + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + + case 50 /* SuperKeyword */: + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + + case 31 /* NewKeyword */: + + case 21 /* DeleteKeyword */: + case 41 /* VoidKeyword */: + case 39 /* TypeOfKeyword */: + + case 27 /* FunctionKeyword */: + return true; + } + + return this.isIdentifier(currentToken); + }; + + ParserImpl.prototype.parseExpressionStatement = function () { + var expression = this.parseExpression(true); + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.expressionStatement(expression, semicolon); + }; + + ParserImpl.prototype.parseIfStatement = function () { + var ifKeyword = this.eatKeyword(28 /* IfKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + var elseClause = null; + if (this.isElseClause()) { + elseClause = this.parseElseClause(); + } + + return this.factory.ifStatement(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause); + }; + + ParserImpl.prototype.isElseClause = function () { + return this.currentToken().tokenKind === 23 /* ElseKeyword */; + }; + + ParserImpl.prototype.parseElseClause = function () { + var elseKeyword = this.eatKeyword(23 /* ElseKeyword */); + var statement = this.parseStatement(false); + + return this.factory.elseClause(elseKeyword, statement); + }; + + ParserImpl.prototype.isVariableStatement = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 40 /* VarKeyword */; + }; + + ParserImpl.prototype.parseVariableStatement = function () { + var modifiers = this.parseModifiers(); + var variableDeclaration = this.parseVariableDeclaration(true); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.variableStatement(modifiers, variableDeclaration, semicolonToken); + }; + + ParserImpl.prototype.parseVariableDeclaration = function (allowIn) { + var varKeyword = this.eatKeyword(40 /* VarKeyword */); + + var listParsingState = allowIn ? 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */ : 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */; + + var result = this.parseSeparatedSyntaxList(listParsingState); + var variableDeclarators = result.list; + varKeyword = this.addSkippedTokensAfterToken(varKeyword, result.skippedTokens); + + return this.factory.variableDeclaration(varKeyword, variableDeclarators); + }; + + ParserImpl.prototype.isVariableDeclarator = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 225 /* VariableDeclarator */) { + return true; + } + + return this.isIdentifier(this.currentToken()); + }; + + ParserImpl.prototype.canReuseVariableDeclaratorNode = function (node) { + if (node === null || node.kind() !== 225 /* VariableDeclarator */) { + return false; + } + + var variableDeclarator = node; + return variableDeclarator.equalsValueClause === null; + }; + + ParserImpl.prototype.parseVariableDeclarator = function (allowIn, allowPropertyName) { + if (this.canReuseVariableDeclaratorNode(this.currentNode())) { + return this.eatNode(); + } + + var propertyName = allowPropertyName ? this.eatPropertyName() : this.eatIdentifierToken(); + var equalsValueClause = null; + var typeAnnotation = null; + + if (propertyName.width() > 0) { + typeAnnotation = this.parseOptionalTypeAnnotation(false); + + if (this.isEqualsValueClause(false)) { + equalsValueClause = this.parseEqualsValueClause(allowIn); + } + } + + return this.factory.variableDeclarator(propertyName, typeAnnotation, equalsValueClause); + }; + + ParserImpl.prototype.isColonValueClause = function () { + return this.currentToken().tokenKind === 106 /* ColonToken */; + }; + + ParserImpl.prototype.isEqualsValueClause = function (inParameter) { + var token0 = this.currentToken(); + if (token0.tokenKind === 107 /* EqualsToken */) { + return true; + } + + if (!this.previousToken().hasTrailingNewLine()) { + if (token0.tokenKind === 85 /* EqualsGreaterThanToken */) { + return false; + } + + if (token0.tokenKind === 70 /* OpenBraceToken */ && inParameter) { + return false; + } + + return this.isExpression(token0); + } + + return false; + }; + + ParserImpl.prototype.parseEqualsValueClause = function (allowIn) { + var equalsToken = this.eatToken(107 /* EqualsToken */); + var value = this.parseAssignmentExpression(allowIn); + + return this.factory.equalsValueClause(equalsToken, value); + }; + + ParserImpl.prototype.parseExpression = function (allowIn) { + return this.parseSubExpression(0, allowIn); + }; + + ParserImpl.prototype.parseAssignmentExpression = function (allowIn) { + return this.parseSubExpression(2 /* AssignmentExpressionPrecedence */, allowIn); + }; + + ParserImpl.prototype.parseUnaryExpressionOrLower = function () { + var currentTokenKind = this.currentToken().tokenKind; + if (TypeScript.SyntaxFacts.isPrefixUnaryExpressionOperatorToken(currentTokenKind)) { + var operatorKind = TypeScript.SyntaxFacts.getPrefixUnaryExpressionFromOperatorToken(currentTokenKind); + + var operatorToken = this.eatAnyToken(); + + var operand = this.parseUnaryExpressionOrLower(); + return this.factory.prefixUnaryExpression(operatorKind, operatorToken, operand); + } else if (currentTokenKind === 39 /* TypeOfKeyword */) { + return this.parseTypeOfExpression(); + } else if (currentTokenKind === 41 /* VoidKeyword */) { + return this.parseVoidExpression(); + } else if (currentTokenKind === 21 /* DeleteKeyword */) { + return this.parseDeleteExpression(); + } else if (currentTokenKind === 80 /* LessThanToken */) { + return this.parseCastExpression(); + } else { + return this.parsePostfixExpressionOrLower(); + } + }; + + ParserImpl.prototype.parseSubExpression = function (precedence, allowIn) { + if (precedence <= 2 /* AssignmentExpressionPrecedence */) { + if (this.isSimpleArrowFunctionExpression()) { + return this.parseSimpleArrowFunctionExpression(); + } + + var parethesizedArrowFunction = this.tryParseParenthesizedArrowFunctionExpression(); + if (parethesizedArrowFunction !== null) { + return parethesizedArrowFunction; + } + } + + var leftOperand = this.parseUnaryExpressionOrLower(); + return this.parseBinaryOrConditionalExpressions(precedence, allowIn, leftOperand); + }; + + ParserImpl.prototype.parseBinaryOrConditionalExpressions = function (precedence, allowIn, leftOperand) { + while (true) { + var token0 = this.currentToken(); + var token0Kind = token0.tokenKind; + + if (TypeScript.SyntaxFacts.isBinaryExpressionOperatorToken(token0Kind)) { + if (token0Kind === 29 /* InKeyword */ && !allowIn) { + break; + } + + var mergedToken = this.tryMergeBinaryExpressionTokens(); + var tokenKind = mergedToken === null ? token0Kind : mergedToken.syntaxKind; + + var binaryExpressionKind = TypeScript.SyntaxFacts.getBinaryExpressionFromOperatorToken(tokenKind); + var newPrecedence = ParserImpl.getPrecedence(binaryExpressionKind); + + if (newPrecedence < precedence) { + break; + } + + if (newPrecedence === precedence && !this.isRightAssociative(binaryExpressionKind)) { + break; + } + + var operatorToken = mergedToken === null ? token0 : TypeScript.Syntax.token(mergedToken.syntaxKind).withLeadingTrivia(token0.leadingTrivia()).withTrailingTrivia(this.peekToken(mergedToken.tokenCount - 1).trailingTrivia()); + + var skipCount = mergedToken === null ? 1 : mergedToken.tokenCount; + for (var i = 0; i < skipCount; i++) { + this.eatAnyToken(); + } + + leftOperand = this.factory.binaryExpression(binaryExpressionKind, leftOperand, operatorToken, this.parseSubExpression(newPrecedence, allowIn)); + continue; + } + + if (token0Kind === 105 /* QuestionToken */ && precedence <= 3 /* ConditionalExpressionPrecedence */) { + var questionToken = this.eatToken(105 /* QuestionToken */); + + var whenTrueExpression = this.parseAssignmentExpression(allowIn); + var colon = this.eatToken(106 /* ColonToken */); + + var whenFalseExpression = this.parseAssignmentExpression(allowIn); + leftOperand = this.factory.conditionalExpression(leftOperand, questionToken, whenTrueExpression, colon, whenFalseExpression); + continue; + } + + break; + } + + return leftOperand; + }; + + ParserImpl.prototype.tryMergeBinaryExpressionTokens = function () { + var token0 = this.currentToken(); + + if (token0.tokenKind === 81 /* GreaterThanToken */ && !token0.hasTrailingTrivia()) { + var storage = this.mergeTokensStorage; + storage[0] = 0 /* None */; + storage[1] = 0 /* None */; + storage[2] = 0 /* None */; + + for (var i = 0; i < storage.length; i++) { + var nextToken = this.peekToken(i + 1); + + if (!nextToken.hasLeadingTrivia()) { + storage[i] = nextToken.tokenKind; + } + + if (nextToken.hasTrailingTrivia()) { + break; + } + } + + if (storage[0] === 81 /* GreaterThanToken */) { + if (storage[1] === 81 /* GreaterThanToken */) { + if (storage[2] === 107 /* EqualsToken */) { + return { tokenCount: 4, syntaxKind: 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */ }; + } else { + return { tokenCount: 3, syntaxKind: 97 /* GreaterThanGreaterThanGreaterThanToken */ }; + } + } else if (storage[1] === 107 /* EqualsToken */) { + return { tokenCount: 3, syntaxKind: 113 /* GreaterThanGreaterThanEqualsToken */ }; + } else { + return { tokenCount: 2, syntaxKind: 96 /* GreaterThanGreaterThanToken */ }; + } + } else if (storage[0] === 107 /* EqualsToken */) { + return { tokenCount: 2, syntaxKind: 83 /* GreaterThanEqualsToken */ }; + } + } + + return null; + }; + + ParserImpl.prototype.isRightAssociative = function (expressionKind) { + switch (expressionKind) { + case 174 /* AssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + return true; + default: + return false; + } + }; + + ParserImpl.prototype.parseMemberExpressionOrLower = function (inObjectCreation) { + if (this.currentToken().tokenKind === 31 /* NewKeyword */) { + return this.parseObjectCreationExpression(); + } + + var expression = this.parsePrimaryExpression(); + if (expression === null) { + return this.eatIdentifierToken(); + } + + return this.parseMemberExpressionRest(expression, false, inObjectCreation); + }; + + ParserImpl.prototype.parseCallExpressionOrLower = function () { + var expression; + if (this.currentToken().tokenKind === 50 /* SuperKeyword */) { + expression = this.eatKeyword(50 /* SuperKeyword */); + + var currentTokenKind = this.currentToken().tokenKind; + if (currentTokenKind !== 72 /* OpenParenToken */ && currentTokenKind !== 76 /* DotToken */) { + expression = this.factory.memberAccessExpression(expression, this.eatToken(76 /* DotToken */), this.eatIdentifierNameToken()); + } + } else { + expression = this.parseMemberExpressionOrLower(false); + } + + return this.parseMemberExpressionRest(expression, true, false); + }; + + ParserImpl.prototype.parseMemberExpressionRest = function (expression, allowArguments, inObjectCreation) { + while (true) { + var currentTokenKind = this.currentToken().tokenKind; + + switch (currentTokenKind) { + case 72 /* OpenParenToken */: + if (!allowArguments) { + return expression; + } + + expression = this.factory.invocationExpression(expression, this.parseArgumentList(null)); + continue; + + case 80 /* LessThanToken */: + if (!allowArguments) { + return expression; + } + + var argumentList = this.tryParseArgumentList(); + if (argumentList !== null) { + expression = this.factory.invocationExpression(expression, argumentList); + continue; + } + + break; + + case 74 /* OpenBracketToken */: + expression = this.parseElementAccessExpression(expression, inObjectCreation); + continue; + + case 76 /* DotToken */: + expression = this.factory.memberAccessExpression(expression, this.eatToken(76 /* DotToken */), this.eatIdentifierNameToken()); + continue; + } + + return expression; + } + }; + + ParserImpl.prototype.parseLeftHandSideExpressionOrLower = function () { + if (this.currentToken().tokenKind === 31 /* NewKeyword */) { + return this.parseObjectCreationExpression(); + } else { + return this.parseCallExpressionOrLower(); + } + }; + + ParserImpl.prototype.parsePostfixExpressionOrLower = function () { + var expression = this.parseLeftHandSideExpressionOrLower(); + if (expression === null) { + return this.eatIdentifierToken(); + } + + var currentTokenKind = this.currentToken().tokenKind; + + switch (currentTokenKind) { + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + if (this.previousToken() !== null && this.previousToken().hasTrailingNewLine()) { + break; + } + + return this.factory.postfixUnaryExpression(TypeScript.SyntaxFacts.getPostfixUnaryExpressionFromOperatorToken(currentTokenKind), expression, this.eatAnyToken()); + } + + return expression; + }; + + ParserImpl.prototype.tryParseGenericArgumentList = function () { + var rewindPoint = this.getRewindPoint(); + + var typeArgumentList = this.tryParseTypeArgumentList(true); + var token0 = this.currentToken(); + + var isOpenParen = token0.tokenKind === 72 /* OpenParenToken */; + var isDot = token0.tokenKind === 76 /* DotToken */; + var isOpenParenOrDot = isOpenParen || isDot; + + var argumentList = null; + if (typeArgumentList === null || !isOpenParenOrDot) { + this.rewind(rewindPoint); + this.releaseRewindPoint(rewindPoint); + return null; + } else { + this.releaseRewindPoint(rewindPoint); + + if (isDot) { + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token0.width(), TypeScript.DiagnosticCode.A_parameter_list_must_follow_a_generic_type_argument_list_expected, null); + this.addDiagnostic(diagnostic); + + return this.factory.argumentList(typeArgumentList, TypeScript.Syntax.emptyToken(72 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.emptyToken(73 /* CloseParenToken */)); + } else { + return this.parseArgumentList(typeArgumentList); + } + } + }; + + ParserImpl.prototype.tryParseArgumentList = function () { + if (this.currentToken().tokenKind === 80 /* LessThanToken */) { + return this.tryParseGenericArgumentList(); + } + + if (this.currentToken().tokenKind === 72 /* OpenParenToken */) { + return this.parseArgumentList(null); + } + + return null; + }; + + ParserImpl.prototype.parseArgumentList = function (typeArgumentList) { + var openParenToken = this.eatToken(72 /* OpenParenToken */); + + var _arguments = TypeScript.Syntax.emptySeparatedList; + + if (openParenToken.fullWidth() > 0) { + var result = this.parseSeparatedSyntaxList(16384 /* ArgumentList_AssignmentExpressions */); + _arguments = result.list; + openParenToken = this.addSkippedTokensAfterToken(openParenToken, result.skippedTokens); + } + + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + return this.factory.argumentList(typeArgumentList, openParenToken, _arguments, closeParenToken); + }; + + ParserImpl.prototype.parseElementAccessExpression = function (expression, inObjectCreation) { + var start = this.currentTokenStart(); + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + var argumentExpression; + + if (this.currentToken().tokenKind === 75 /* CloseBracketToken */ && inObjectCreation) { + var end = this.currentTokenStart() + this.currentToken().width(); + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, start, end - start, TypeScript.DiagnosticCode.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead, null); + this.addDiagnostic(diagnostic); + + argumentExpression = TypeScript.Syntax.emptyToken(11 /* IdentifierName */); + } else { + argumentExpression = this.parseExpression(true); + } + + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + + return this.factory.elementAccessExpression(expression, openBracketToken, argumentExpression, closeBracketToken); + }; + + ParserImpl.prototype.parsePrimaryExpression = function () { + var currentToken = this.currentToken(); + + if (this.isIdentifier(currentToken)) { + return this.eatIdentifierToken(); + } + + var currentTokenKind = currentToken.tokenKind; + switch (currentTokenKind) { + case 35 /* ThisKeyword */: + return this.parseThisExpression(); + + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return this.parseLiteralExpression(); + + case 32 /* NullKeyword */: + return this.parseLiteralExpression(); + + case 27 /* FunctionKeyword */: + return this.parseFunctionExpression(); + + case 13 /* NumericLiteral */: + return this.parseLiteralExpression(); + + case 12 /* RegularExpressionLiteral */: + return this.parseLiteralExpression(); + + case 14 /* StringLiteral */: + return this.parseLiteralExpression(); + + case 74 /* OpenBracketToken */: + return this.parseArrayLiteralExpression(); + + case 70 /* OpenBraceToken */: + return this.parseObjectLiteralExpression(); + + case 72 /* OpenParenToken */: + return this.parseParenthesizedExpression(); + + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + var result = this.tryReparseDivideAsRegularExpression(); + if (result !== null) { + return result; + } + break; + } + + return null; + }; + + ParserImpl.prototype.tryReparseDivideAsRegularExpression = function () { + var currentToken = this.currentToken(); + + if (this.previousToken() !== null) { + var previousTokenKind = this.previousToken().tokenKind; + switch (previousTokenKind) { + case 11 /* IdentifierName */: + return null; + + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return null; + + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + case 12 /* RegularExpressionLiteral */: + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + case 75 /* CloseBracketToken */: + return null; + } + } + + currentToken = this.currentTokenAllowingRegularExpression(); + + if (currentToken.tokenKind === 118 /* SlashToken */ || currentToken.tokenKind === 119 /* SlashEqualsToken */) { + return null; + } else if (currentToken.tokenKind === 12 /* RegularExpressionLiteral */) { + return this.parseLiteralExpression(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseTypeOfExpression = function () { + var typeOfKeyword = this.eatKeyword(39 /* TypeOfKeyword */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.typeOfExpression(typeOfKeyword, expression); + }; + + ParserImpl.prototype.parseDeleteExpression = function () { + var deleteKeyword = this.eatKeyword(21 /* DeleteKeyword */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.deleteExpression(deleteKeyword, expression); + }; + + ParserImpl.prototype.parseVoidExpression = function () { + var voidKeyword = this.eatKeyword(41 /* VoidKeyword */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.voidExpression(voidKeyword, expression); + }; + + ParserImpl.prototype.parseFunctionExpression = function () { + var functionKeyword = this.eatKeyword(27 /* FunctionKeyword */); + var identifier = null; + + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + + var callSignature = this.parseCallSignature(false); + var block = this.parseBlock(false, true); + + return this.factory.functionExpression(functionKeyword, identifier, callSignature, block); + }; + + ParserImpl.prototype.parseObjectCreationExpression = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + + var expression = this.parseObjectCreationExpressionOrLower(true); + var argumentList = this.tryParseArgumentList(); + + var result = this.factory.objectCreationExpression(newKeyword, expression, argumentList); + return this.parseMemberExpressionRest(result, true, false); + }; + + ParserImpl.prototype.parseObjectCreationExpressionOrLower = function (inObjectCreation) { + if (this.currentToken().tokenKind === 31 /* NewKeyword */) { + return this.parseObjectCreationExpression(); + } else { + return this.parseMemberExpressionOrLower(inObjectCreation); + } + }; + + ParserImpl.prototype.parseCastExpression = function () { + var lessThanToken = this.eatToken(80 /* LessThanToken */); + var type = this.parseType(); + var greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.castExpression(lessThanToken, type, greaterThanToken, expression); + }; + + ParserImpl.prototype.parseParenthesizedExpression = function () { + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + return this.factory.parenthesizedExpression(openParenToken, expression, closeParenToken); + }; + + ParserImpl.prototype.tryParseParenthesizedArrowFunctionExpression = function () { + var tokenKind = this.currentToken().tokenKind; + if (tokenKind !== 72 /* OpenParenToken */ && tokenKind !== 80 /* LessThanToken */) { + return null; + } + + if (this.isDefinitelyArrowFunctionExpression()) { + return this.parseParenthesizedArrowFunctionExpression(false); + } + + if (!this.isPossiblyArrowFunctionExpression()) { + return null; + } + + var rewindPoint = this.getRewindPoint(); + + var arrowFunction = this.parseParenthesizedArrowFunctionExpression(true); + if (arrowFunction === null) { + this.rewind(rewindPoint); + } + + this.releaseRewindPoint(rewindPoint); + return arrowFunction; + }; + + ParserImpl.prototype.parseParenthesizedArrowFunctionExpression = function (requireArrow) { + var currentToken = this.currentToken(); + + var callSignature = this.parseCallSignature(true); + + if (requireArrow && this.currentToken().tokenKind !== 85 /* EqualsGreaterThanToken */) { + return null; + } + + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + + var block = this.tryParseArrowFunctionBlock(); + var expression = null; + if (block === null) { + expression = this.parseAssignmentExpression(true); + } + + return this.factory.parenthesizedArrowFunctionExpression(callSignature, equalsGreaterThanToken, block, expression); + }; + + ParserImpl.prototype.tryParseArrowFunctionBlock = function () { + if (this.isBlock()) { + return this.parseBlock(false, false); + } else { + if (this.isStatement(false) && !this.isExpressionStatement(this.currentToken()) && !this.isFunctionDeclaration()) { + return this.parseBlock(true, false); + } else { + return null; + } + } + }; + + ParserImpl.prototype.isSimpleArrowFunctionExpression = function () { + if (this.currentToken().tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + + return this.isIdentifier(this.currentToken()) && this.peekToken(1).tokenKind === 85 /* EqualsGreaterThanToken */; + }; + + ParserImpl.prototype.parseSimpleArrowFunctionExpression = function () { + var identifier = this.eatIdentifierToken(); + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + + var block = this.tryParseArrowFunctionBlock(); + var expression = null; + if (block === null) { + expression = this.parseAssignmentExpression(true); + } + + return this.factory.simpleArrowFunctionExpression(identifier, equalsGreaterThanToken, block, expression); + }; + + ParserImpl.prototype.isBlock = function () { + return this.currentToken().tokenKind === 70 /* OpenBraceToken */; + }; + + ParserImpl.prototype.isDefinitelyArrowFunctionExpression = function () { + var token0 = this.currentToken(); + if (token0.tokenKind !== 72 /* OpenParenToken */) { + return false; + } + + var token1 = this.peekToken(1); + var token2; + + if (token1.tokenKind === 73 /* CloseParenToken */) { + token2 = this.peekToken(2); + return token2.tokenKind === 106 /* ColonToken */ || token2.tokenKind === 85 /* EqualsGreaterThanToken */ || token2.tokenKind === 70 /* OpenBraceToken */; + } + + if (token1.tokenKind === 77 /* DotDotDotToken */) { + return true; + } + + token2 = this.peekToken(2); + if (token1.tokenKind === 57 /* PublicKeyword */ || token1.tokenKind === 55 /* PrivateKeyword */) { + if (this.isIdentifier(token2)) { + return true; + } + } + + if (!this.isIdentifier(token1)) { + return false; + } + + if (token2.tokenKind === 106 /* ColonToken */) { + return true; + } + + var token3 = this.peekToken(3); + if (token2.tokenKind === 105 /* QuestionToken */) { + if (token3.tokenKind === 106 /* ColonToken */ || token3.tokenKind === 73 /* CloseParenToken */ || token3.tokenKind === 79 /* CommaToken */) { + return true; + } + } + + if (token2.tokenKind === 73 /* CloseParenToken */) { + if (token3.tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.isPossiblyArrowFunctionExpression = function () { + var token0 = this.currentToken(); + if (token0.tokenKind !== 72 /* OpenParenToken */) { + return true; + } + + var token1 = this.peekToken(1); + + if (!this.isIdentifier(token1)) { + return false; + } + + var token2 = this.peekToken(2); + if (token2.tokenKind === 107 /* EqualsToken */) { + return true; + } + + if (token2.tokenKind === 79 /* CommaToken */) { + return true; + } + + if (token2.tokenKind === 73 /* CloseParenToken */) { + var token3 = this.peekToken(3); + if (token3.tokenKind === 106 /* ColonToken */) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.parseObjectLiteralExpression = function () { + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var result = this.parseSeparatedSyntaxList(32768 /* ObjectLiteralExpression_PropertyAssignments */); + var propertyAssignments = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.objectLiteralExpression(openBraceToken, propertyAssignments, closeBraceToken); + }; + + ParserImpl.prototype.parsePropertyAssignment = function (inErrorRecovery) { + if (this.isAccessor(inErrorRecovery)) { + return this.parseAccessor(true); + } else if (this.isFunctionPropertyAssignment(inErrorRecovery)) { + return this.parseFunctionPropertyAssignment(); + } else if (this.isSimplePropertyAssignment(inErrorRecovery)) { + return this.parseSimplePropertyAssignment(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isPropertyAssignment = function (inErrorRecovery) { + return this.isAccessor(inErrorRecovery) || this.isFunctionPropertyAssignment(inErrorRecovery) || this.isSimplePropertyAssignment(inErrorRecovery); + }; + + ParserImpl.prototype.eatPropertyName = function () { + return TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(this.currentToken()) ? this.eatIdentifierNameToken() : this.eatAnyToken(); + }; + + ParserImpl.prototype.isFunctionPropertyAssignment = function (inErrorRecovery) { + return this.isPropertyName(this.currentToken(), inErrorRecovery) && this.isCallSignature(1); + }; + + ParserImpl.prototype.parseFunctionPropertyAssignment = function () { + var propertyName = this.eatPropertyName(); + var callSignature = this.parseCallSignature(false); + var block = this.parseBlock(false, true); + + return this.factory.functionPropertyAssignment(propertyName, callSignature, block); + }; + + ParserImpl.prototype.isSimplePropertyAssignment = function (inErrorRecovery) { + return this.isPropertyName(this.currentToken(), inErrorRecovery); + }; + + ParserImpl.prototype.parseSimplePropertyAssignment = function () { + var propertyName = this.eatPropertyName(); + var colonToken = this.eatToken(106 /* ColonToken */); + var expression = this.parseAssignmentExpression(true); + + return this.factory.simplePropertyAssignment(propertyName, colonToken, expression); + }; + + ParserImpl.prototype.isPropertyName = function (token, inErrorRecovery) { + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) { + if (inErrorRecovery) { + return this.isIdentifier(token); + } else { + return true; + } + } + + switch (token.tokenKind) { + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.parseArrayLiteralExpression = function () { + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + + var result = this.parseSeparatedSyntaxList(65536 /* ArrayLiteralExpression_AssignmentExpressions */); + var expressions = result.list; + openBracketToken = this.addSkippedTokensAfterToken(openBracketToken, result.skippedTokens); + + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + + return this.factory.arrayLiteralExpression(openBracketToken, expressions, closeBracketToken); + }; + + ParserImpl.prototype.parseLiteralExpression = function () { + return this.eatAnyToken(); + }; + + ParserImpl.prototype.parseThisExpression = function () { + return this.eatKeyword(35 /* ThisKeyword */); + }; + + ParserImpl.prototype.parseBlock = function (parseBlockEvenWithNoOpenBrace, checkForStrictMode) { + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var statements = TypeScript.Syntax.emptyList; + + if (parseBlockEvenWithNoOpenBrace || openBraceToken.width() > 0) { + var savedIsInStrictMode = this.isInStrictMode; + + var processItems = checkForStrictMode ? ParserImpl.updateStrictModeState : null; + var result = this.parseSyntaxList(32 /* Block_Statements */, processItems); + statements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + + this.setStrictMode(savedIsInStrictMode); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.block(openBraceToken, statements, closeBraceToken); + }; + + ParserImpl.prototype.parseCallSignature = function (requireCompleteTypeParameterList) { + var typeParameterList = this.parseOptionalTypeParameterList(requireCompleteTypeParameterList); + var parameterList = this.parseParameterList(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.callSignature(typeParameterList, parameterList, typeAnnotation); + }; + + ParserImpl.prototype.parseOptionalTypeParameterList = function (requireCompleteTypeParameterList) { + if (this.currentToken().tokenKind !== 80 /* LessThanToken */) { + return null; + } + + var rewindPoint = this.getRewindPoint(); + + var lessThanToken = this.eatToken(80 /* LessThanToken */); + + var result = this.parseSeparatedSyntaxList(524288 /* TypeParameterList_TypeParameters */); + var typeParameters = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + var greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + + if (requireCompleteTypeParameterList && greaterThanToken.fullWidth() === 0) { + this.rewind(rewindPoint); + this.releaseRewindPoint(rewindPoint); + return null; + } else { + this.releaseRewindPoint(rewindPoint); + var typeParameterList = this.factory.typeParameterList(lessThanToken, typeParameters, greaterThanToken); + + return typeParameterList; + } + }; + + ParserImpl.prototype.isTypeParameter = function () { + return this.isIdentifier(this.currentToken()); + }; + + ParserImpl.prototype.parseTypeParameter = function () { + var identifier = this.eatIdentifierToken(); + var constraint = this.parseOptionalConstraint(); + + return this.factory.typeParameter(identifier, constraint); + }; + + ParserImpl.prototype.parseOptionalConstraint = function () { + if (this.currentToken().kind() !== 48 /* ExtendsKeyword */) { + return null; + } + + var extendsKeyword = this.eatKeyword(48 /* ExtendsKeyword */); + var type = this.parseType(); + + return this.factory.constraint(extendsKeyword, type); + }; + + ParserImpl.prototype.parseParameterList = function () { + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var parameters = TypeScript.Syntax.emptySeparatedList; + + if (openParenToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(131072 /* ParameterList_Parameters */); + parameters = result.list; + openParenToken = this.addSkippedTokensAfterToken(openParenToken, result.skippedTokens); + } + + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + return this.factory.parameterList(openParenToken, parameters, closeParenToken); + }; + + ParserImpl.prototype.isTypeAnnotation = function () { + return this.currentToken().tokenKind === 106 /* ColonToken */; + }; + + ParserImpl.prototype.parseOptionalTypeAnnotation = function (allowStringLiteral) { + return this.isTypeAnnotation() ? this.parseTypeAnnotation(allowStringLiteral) : null; + }; + + ParserImpl.prototype.parseTypeAnnotation = function (allowStringLiteral) { + var colonToken = this.eatToken(106 /* ColonToken */); + var type = allowStringLiteral && this.currentToken().tokenKind === 14 /* StringLiteral */ ? this.eatToken(14 /* StringLiteral */) : this.parseType(); + + return this.factory.typeAnnotation(colonToken, type); + }; + + ParserImpl.prototype.isType = function () { + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + + switch (currentTokenKind) { + case 39 /* TypeOfKeyword */: + + case 60 /* AnyKeyword */: + case 67 /* NumberKeyword */: + case 61 /* BooleanKeyword */: + case 69 /* StringKeyword */: + case 41 /* VoidKeyword */: + + case 70 /* OpenBraceToken */: + + case 72 /* OpenParenToken */: + case 80 /* LessThanToken */: + + case 31 /* NewKeyword */: + return true; + } + + return this.isIdentifier(currentToken); + }; + + ParserImpl.prototype.parseType = function () { + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + + var type = this.parseNonArrayType(currentToken); + + while (this.currentToken().tokenKind === 74 /* OpenBracketToken */) { + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + + type = this.factory.arrayType(type, openBracketToken, closeBracketToken); + } + + return type; + }; + + ParserImpl.prototype.isTypeQuery = function () { + return this.currentToken().tokenKind === 39 /* TypeOfKeyword */; + }; + + ParserImpl.prototype.parseTypeQuery = function () { + var typeOfKeyword = this.eatToken(39 /* TypeOfKeyword */); + var name = this.parseName(); + + return this.factory.typeQuery(typeOfKeyword, name); + }; + + ParserImpl.prototype.parseNonArrayType = function (currentToken) { + var currentTokenKind = currentToken.tokenKind; + switch (currentTokenKind) { + case 60 /* AnyKeyword */: + case 67 /* NumberKeyword */: + case 61 /* BooleanKeyword */: + case 69 /* StringKeyword */: + case 41 /* VoidKeyword */: + return this.eatAnyToken(); + + case 70 /* OpenBraceToken */: + return this.parseObjectType(); + + case 72 /* OpenParenToken */: + case 80 /* LessThanToken */: + return this.parseFunctionType(); + + case 31 /* NewKeyword */: + return this.parseConstructorType(); + + case 39 /* TypeOfKeyword */: + return this.parseTypeQuery(); + } + + return this.parseNameOrGenericType(); + }; + + ParserImpl.prototype.parseNameOrGenericType = function () { + var name = this.parseName(); + var typeArgumentList = this.tryParseTypeArgumentList(false); + + return typeArgumentList === null ? name : this.factory.genericType(name, typeArgumentList); + }; + + ParserImpl.prototype.parseFunctionType = function () { + var typeParameterList = this.parseOptionalTypeParameterList(false); + var parameterList = this.parseParameterList(); + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + var returnType = this.parseType(); + + return this.factory.functionType(typeParameterList, parameterList, equalsGreaterThanToken, returnType); + }; + + ParserImpl.prototype.parseConstructorType = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var parameterList = this.parseParameterList(); + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + var type = this.parseType(); + + return this.factory.constructorType(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type); + }; + + ParserImpl.prototype.isParameter = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 242 /* Parameter */) { + return true; + } + + var token = this.currentToken(); + var tokenKind = token.tokenKind; + if (tokenKind === 77 /* DotDotDotToken */) { + return true; + } + + if (ParserImpl.isModifier(token) && !this.isModifierUsedAsParameterIdentifier(token)) { + return true; + } + + return this.isIdentifier(token); + }; + + ParserImpl.prototype.isModifierUsedAsParameterIdentifier = function (token) { + if (this.isIdentifier(token)) { + var nextTokenKind = this.peekToken(1).tokenKind; + switch (nextTokenKind) { + case 73 /* CloseParenToken */: + case 106 /* ColonToken */: + case 107 /* EqualsToken */: + case 79 /* CommaToken */: + case 105 /* QuestionToken */: + return true; + } + } + + return false; + }; + + ParserImpl.prototype.parseParameter = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 242 /* Parameter */) { + return this.eatNode(); + } + + var dotDotDotToken = this.tryEatToken(77 /* DotDotDotToken */); + + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (ParserImpl.isModifier(currentToken) && !this.isModifierUsedAsParameterIdentifier(currentToken)) { + modifierArray.push(this.eatAnyToken()); + continue; + } + + break; + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var identifier = this.eatIdentifierToken(); + var questionToken = this.tryEatToken(105 /* QuestionToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(true); + + var equalsValueClause = null; + if (this.isEqualsValueClause(true)) { + equalsValueClause = this.parseEqualsValueClause(true); + } + + return this.factory.parameter(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause); + }; + + ParserImpl.prototype.parseSyntaxList = function (currentListType, processItems) { + if (typeof processItems === "undefined") { processItems = null; } + var savedListParsingState = this.listParsingState; + this.listParsingState |= currentListType; + + var result = this.parseSyntaxListWorker(currentListType, processItems); + + this.listParsingState = savedListParsingState; + + return result; + }; + + ParserImpl.prototype.parseSeparatedSyntaxList = function (currentListType) { + var savedListParsingState = this.listParsingState; + this.listParsingState |= currentListType; + + var result = this.parseSeparatedSyntaxListWorker(currentListType); + + this.listParsingState = savedListParsingState; + + return result; + }; + + ParserImpl.prototype.abortParsingListOrMoveToNextToken = function (currentListType, items, skippedTokens) { + this.reportUnexpectedTokenDiagnostic(currentListType); + + for (var state = 524288 /* LastListParsingState */; state >= 1 /* FirstListParsingState */; state >>= 1) { + if ((this.listParsingState & state) !== 0) { + if (this.isExpectedListTerminator(state) || this.isExpectedListItem(state, true)) { + return true; + } + } + } + + var skippedToken = this.currentToken(); + + this.moveToNextToken(); + + this.addSkippedTokenToList(items, skippedTokens, skippedToken); + + return false; + }; + + ParserImpl.prototype.addSkippedTokenToList = function (items, skippedTokens, skippedToken) { + for (var i = items.length - 1; i >= 0; i--) { + var item = items[i]; + var lastToken = item.lastToken(); + if (lastToken.fullWidth() > 0) { + items[i] = this.addSkippedTokenAfterNodeOrToken(item, skippedToken); + return; + } + } + + skippedTokens.push(skippedToken); + }; + + ParserImpl.prototype.tryParseExpectedListItem = function (currentListType, inErrorRecovery, items, processItems) { + if (this.isExpectedListItem(currentListType, inErrorRecovery)) { + var item = this.parseExpectedListItem(currentListType, inErrorRecovery); + + items.push(item); + + if (processItems !== null) { + processItems(this, items); + } + } + }; + + ParserImpl.prototype.listIsTerminated = function (currentListType) { + return this.isExpectedListTerminator(currentListType) || this.currentToken().tokenKind === 10 /* EndOfFileToken */; + }; + + ParserImpl.prototype.getArray = function () { + if (this.arrayPool.length > 0) { + return this.arrayPool.pop(); + } + + return []; + }; + + ParserImpl.prototype.returnZeroOrOneLengthArray = function (array) { + if (array.length <= 1) { + this.returnArray(array); + } + }; + + ParserImpl.prototype.returnArray = function (array) { + array.length = 0; + this.arrayPool.push(array); + }; + + ParserImpl.prototype.parseSyntaxListWorker = function (currentListType, processItems) { + var items = this.getArray(); + var skippedTokens = this.getArray(); + + while (true) { + var oldItemsCount = items.length; + this.tryParseExpectedListItem(currentListType, false, items, processItems); + + var newItemsCount = items.length; + if (newItemsCount === oldItemsCount) { + if (this.listIsTerminated(currentListType)) { + break; + } + + var abort = this.abortParsingListOrMoveToNextToken(currentListType, items, skippedTokens); + if (abort) { + break; + } + } + } + + var result = TypeScript.Syntax.list(items); + + this.returnZeroOrOneLengthArray(items); + + return { skippedTokens: skippedTokens, list: result }; + }; + + ParserImpl.prototype.parseSeparatedSyntaxListWorker = function (currentListType) { + var items = this.getArray(); + var skippedTokens = this.getArray(); + TypeScript.Debug.assert(items.length === 0); + TypeScript.Debug.assert(skippedTokens.length === 0); + TypeScript.Debug.assert(skippedTokens !== items); + + var separatorKind = this.separatorKind(currentListType); + var allowAutomaticSemicolonInsertion = separatorKind === 78 /* SemicolonToken */; + + var inErrorRecovery = false; + var listWasTerminated = false; + while (true) { + var oldItemsCount = items.length; + + this.tryParseExpectedListItem(currentListType, inErrorRecovery, items, null); + + var newItemsCount = items.length; + if (newItemsCount === oldItemsCount) { + if (this.listIsTerminated(currentListType)) { + listWasTerminated = true; + break; + } + + var abort = this.abortParsingListOrMoveToNextToken(currentListType, items, skippedTokens); + if (abort) { + break; + } else { + inErrorRecovery = true; + continue; + } + } + + inErrorRecovery = false; + + var currentToken = this.currentToken(); + if (currentToken.tokenKind === separatorKind || currentToken.tokenKind === 79 /* CommaToken */) { + items.push(this.eatAnyToken()); + continue; + } + + if (this.listIsTerminated(currentListType)) { + listWasTerminated = true; + break; + } + + if (allowAutomaticSemicolonInsertion && this.canEatAutomaticSemicolon(false)) { + items.push(this.eatExplicitOrAutomaticSemicolon(false)); + + continue; + } + + items.push(this.eatToken(separatorKind)); + + inErrorRecovery = true; + } + + var result = TypeScript.Syntax.separatedList(items); + + this.returnZeroOrOneLengthArray(items); + + return { skippedTokens: skippedTokens, list: result }; + }; + + ParserImpl.prototype.separatorKind = function (currentListType) { + switch (currentListType) { + case 2048 /* HeritageClause_TypeNameList */: + case 16384 /* ArgumentList_AssignmentExpressions */: + case 256 /* EnumDeclaration_EnumElements */: + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + case 131072 /* ParameterList_Parameters */: + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + case 262144 /* TypeArgumentList_Types */: + case 524288 /* TypeParameterList_TypeParameters */: + return 79 /* CommaToken */; + + case 512 /* ObjectType_TypeMembers */: + return 78 /* SemicolonToken */; + + case 1 /* SourceUnit_ModuleElements */: + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + case 2 /* ClassDeclaration_ClassElements */: + case 4 /* ModuleDeclaration_ModuleElements */: + case 8 /* SwitchStatement_SwitchClauses */: + case 16 /* SwitchClause_Statements */: + case 32 /* Block_Statements */: + default: + throw TypeScript.Errors.notYetImplemented(); + } + }; + + ParserImpl.prototype.reportUnexpectedTokenDiagnostic = function (listType) { + var token = this.currentToken(); + + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode.Unexpected_token_0_expected, [this.getExpectedListElementType(listType)]); + this.addDiagnostic(diagnostic); + }; + + ParserImpl.prototype.addDiagnostic = function (diagnostic) { + if (this.diagnostics.length > 0 && this.diagnostics[this.diagnostics.length - 1].start() === diagnostic.start()) { + return; + } + + this.diagnostics.push(diagnostic); + }; + + ParserImpl.prototype.isExpectedListTerminator = function (currentListType) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.isExpectedSourceUnit_ModuleElementsTerminator(); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.isExpectedClassDeclaration_ClassElementsTerminator(); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.isExpectedModuleDeclaration_ModuleElementsTerminator(); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.isExpectedSwitchStatement_SwitchClausesTerminator(); + + case 16 /* SwitchClause_Statements */: + return this.isExpectedSwitchClause_StatementsTerminator(); + + case 32 /* Block_Statements */: + return this.isExpectedBlock_StatementsTerminator(); + + case 64 /* TryBlock_Statements */: + return this.isExpectedTryBlock_StatementsTerminator(); + + case 128 /* CatchBlock_Statements */: + return this.isExpectedCatchBlock_StatementsTerminator(); + + case 256 /* EnumDeclaration_EnumElements */: + return this.isExpectedEnumDeclaration_EnumElementsTerminator(); + + case 512 /* ObjectType_TypeMembers */: + return this.isExpectedObjectType_TypeMembersTerminator(); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.isExpectedArgumentList_AssignmentExpressionsTerminator(); + + case 2048 /* HeritageClause_TypeNameList */: + return this.isExpectedHeritageClause_TypeNameListTerminator(); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return this.isExpectedVariableDeclaration_VariableDeclarators_AllowInTerminator(); + + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.isExpectedVariableDeclaration_VariableDeclarators_DisallowInTerminator(); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.isExpectedObjectLiteralExpression_PropertyAssignmentsTerminator(); + + case 131072 /* ParameterList_Parameters */: + return this.isExpectedParameterList_ParametersTerminator(); + + case 262144 /* TypeArgumentList_Types */: + return this.isExpectedTypeArgumentList_TypesTerminator(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.isExpectedTypeParameterList_TypeParametersTerminator(); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.isExpectedLiteralExpression_AssignmentExpressionsTerminator(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isExpectedSourceUnit_ModuleElementsTerminator = function () { + return this.currentToken().tokenKind === 10 /* EndOfFileToken */; + }; + + ParserImpl.prototype.isExpectedEnumDeclaration_EnumElementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedModuleDeclaration_ModuleElementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedObjectType_TypeMembersTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedObjectLiteralExpression_PropertyAssignmentsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedLiteralExpression_AssignmentExpressionsTerminator = function () { + return this.currentToken().tokenKind === 75 /* CloseBracketToken */; + }; + + ParserImpl.prototype.isExpectedTypeArgumentList_TypesTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 81 /* GreaterThanToken */) { + return true; + } + + if (this.canFollowTypeArgumentListInExpression(token.tokenKind)) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedTypeParameterList_TypeParametersTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 81 /* GreaterThanToken */) { + return true; + } + + if (token.tokenKind === 72 /* OpenParenToken */ || token.tokenKind === 70 /* OpenBraceToken */ || token.tokenKind === 48 /* ExtendsKeyword */ || token.tokenKind === 51 /* ImplementsKeyword */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedParameterList_ParametersTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 73 /* CloseParenToken */) { + return true; + } + + if (token.tokenKind === 70 /* OpenBraceToken */) { + return true; + } + + if (token.tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedVariableDeclaration_VariableDeclarators_DisallowInTerminator = function () { + if (this.currentToken().tokenKind === 78 /* SemicolonToken */ || this.currentToken().tokenKind === 73 /* CloseParenToken */) { + return true; + } + + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedVariableDeclaration_VariableDeclarators_AllowInTerminator = function () { + if (this.previousToken().tokenKind === 79 /* CommaToken */) { + return false; + } + + if (this.currentToken().tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + + return this.canEatExplicitOrAutomaticSemicolon(false); + }; + + ParserImpl.prototype.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 70 /* OpenBraceToken */ || token0.tokenKind === 71 /* CloseBraceToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedHeritageClause_TypeNameListTerminator = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 48 /* ExtendsKeyword */ || token0.tokenKind === 51 /* ImplementsKeyword */) { + return true; + } + + if (this.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator()) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedArgumentList_AssignmentExpressionsTerminator = function () { + var token0 = this.currentToken(); + return token0.tokenKind === 73 /* CloseParenToken */ || token0.tokenKind === 78 /* SemicolonToken */; + }; + + ParserImpl.prototype.isExpectedClassDeclaration_ClassElementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedSwitchStatement_SwitchClausesTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedSwitchClause_StatementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */ || this.isSwitchClause(); + }; + + ParserImpl.prototype.isExpectedBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedTryBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 17 /* CatchKeyword */ || this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.isExpectedCatchBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.isExpectedListItem = function (currentListType, inErrorRecovery) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.isModuleElement(inErrorRecovery); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.isHeritageClause(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.isClassElement(inErrorRecovery); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.isModuleElement(inErrorRecovery); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.isSwitchClause(); + + case 16 /* SwitchClause_Statements */: + return this.isStatement(inErrorRecovery); + + case 32 /* Block_Statements */: + return this.isStatement(inErrorRecovery); + + case 64 /* TryBlock_Statements */: + case 128 /* CatchBlock_Statements */: + return false; + + case 256 /* EnumDeclaration_EnumElements */: + return this.isEnumElement(inErrorRecovery); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.isVariableDeclarator(); + + case 512 /* ObjectType_TypeMembers */: + return this.isTypeMember(inErrorRecovery); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.isExpectedArgumentList_AssignmentExpression(); + + case 2048 /* HeritageClause_TypeNameList */: + return this.isHeritageClauseTypeName(); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.isPropertyAssignment(inErrorRecovery); + + case 131072 /* ParameterList_Parameters */: + return this.isParameter(); + + case 262144 /* TypeArgumentList_Types */: + return this.isType(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.isTypeParameter(); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.isAssignmentOrOmittedExpression(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isExpectedArgumentList_AssignmentExpression = function () { + var currentToken = this.currentToken(); + if (this.isExpression(currentToken)) { + return true; + } + + if (currentToken.tokenKind === 79 /* CommaToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.parseExpectedListItem = function (currentListType, inErrorRecovery) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.parseModuleElement(inErrorRecovery); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.parseHeritageClause(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.parseClassElement(inErrorRecovery); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.parseModuleElement(inErrorRecovery); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.parseSwitchClause(); + + case 16 /* SwitchClause_Statements */: + return this.parseStatement(inErrorRecovery); + + case 32 /* Block_Statements */: + return this.parseStatement(inErrorRecovery); + + case 256 /* EnumDeclaration_EnumElements */: + return this.parseEnumElement(); + + case 512 /* ObjectType_TypeMembers */: + return this.parseTypeMember(inErrorRecovery); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.parseAssignmentExpression(true); + + case 2048 /* HeritageClause_TypeNameList */: + return this.parseNameOrGenericType(); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return this.parseVariableDeclarator(true, false); + + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.parseVariableDeclarator(false, false); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.parsePropertyAssignment(inErrorRecovery); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.parseAssignmentOrOmittedExpression(); + + case 131072 /* ParameterList_Parameters */: + return this.parseParameter(); + + case 262144 /* TypeArgumentList_Types */: + return this.parseType(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.parseTypeParameter(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.getExpectedListElementType = function (currentListType) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.module_class_interface_enum_import_or_statement, null); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return '{'; + + case 2 /* ClassDeclaration_ClassElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.constructor_function_accessor_or_variable, null); + + case 4 /* ModuleDeclaration_ModuleElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.module_class_interface_enum_import_or_statement, null); + + case 8 /* SwitchStatement_SwitchClauses */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.case_or_default_clause, null); + + case 16 /* SwitchClause_Statements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.statement, null); + + case 32 /* Block_Statements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.statement, null); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null); + + case 256 /* EnumDeclaration_EnumElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null); + + case 512 /* ObjectType_TypeMembers */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.call_construct_index_property_or_function_signature, null); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + + case 2048 /* HeritageClause_TypeNameList */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_name, null); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.property_or_accessor, null); + + case 131072 /* ParameterList_Parameters */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.parameter, null); + + case 262144 /* TypeArgumentList_Types */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type, null); + + case 524288 /* TypeParameterList_TypeParameters */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_parameter, null); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + return ParserImpl; + })(); + + function parse(fileName, text, isDeclaration, options) { + var source = new NormalParserSource(fileName, text, options.languageVersion()); + + return new ParserImpl(fileName, text.lineMap(), source, options, text).parseSyntaxTree(isDeclaration); + } + Parser.parse = parse; + + function incrementalParse(oldSyntaxTree, textChangeRange, newText) { + if (textChangeRange.isUnchanged()) { + return oldSyntaxTree; + } + + var source = new IncrementalParserSource(oldSyntaxTree, textChangeRange, newText); + + return new ParserImpl(oldSyntaxTree.fileName(), newText.lineMap(), source, oldSyntaxTree.parseOptions(), newText).parseSyntaxTree(oldSyntaxTree.isDeclaration()); + } + Parser.incrementalParse = incrementalParse; + })(TypeScript.Parser || (TypeScript.Parser = {})); + var Parser = TypeScript.Parser; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTree = (function () { + function SyntaxTree(sourceUnit, isDeclaration, diagnostics, fileName, lineMap, parseOtions) { + this._allDiagnostics = null; + this._sourceUnit = sourceUnit; + this._isDeclaration = isDeclaration; + this._parserDiagnostics = diagnostics; + this._fileName = fileName; + this._lineMap = lineMap; + this._parseOptions = parseOtions; + } + SyntaxTree.prototype.toJSON = function (key) { + var result = {}; + + result.isDeclaration = this._isDeclaration; + result.languageVersion = TypeScript.LanguageVersion[this._parseOptions.languageVersion()]; + result.parseOptions = this._parseOptions; + + if (this.diagnostics().length > 0) { + result.diagnostics = this.diagnostics(); + } + + result.sourceUnit = this._sourceUnit; + result.lineMap = this._lineMap; + + return result; + }; + + SyntaxTree.prototype.sourceUnit = function () { + return this._sourceUnit; + }; + + SyntaxTree.prototype.isDeclaration = function () { + return this._isDeclaration; + }; + + SyntaxTree.prototype.computeDiagnostics = function () { + if (this._parserDiagnostics.length > 0) { + return this._parserDiagnostics; + } + + var diagnostics = []; + this.sourceUnit().accept(new GrammarCheckerWalker(this, diagnostics)); + + return diagnostics; + }; + + SyntaxTree.prototype.diagnostics = function () { + if (this._allDiagnostics === null) { + this._allDiagnostics = this.computeDiagnostics(); + } + + return this._allDiagnostics; + }; + + SyntaxTree.prototype.fileName = function () { + return this._fileName; + }; + + SyntaxTree.prototype.lineMap = function () { + return this._lineMap; + }; + + SyntaxTree.prototype.parseOptions = function () { + return this._parseOptions; + }; + + SyntaxTree.prototype.structuralEquals = function (tree) { + return TypeScript.ArrayUtilities.sequenceEquals(this.diagnostics(), tree.diagnostics(), TypeScript.Diagnostic.equals) && this.sourceUnit().structuralEquals(tree.sourceUnit()); + }; + return SyntaxTree; + })(); + TypeScript.SyntaxTree = SyntaxTree; + + var GrammarCheckerWalker = (function (_super) { + __extends(GrammarCheckerWalker, _super); + function GrammarCheckerWalker(syntaxTree, diagnostics) { + _super.call(this); + this.syntaxTree = syntaxTree; + this.diagnostics = diagnostics; + this.inAmbientDeclaration = false; + this.inBlock = false; + this.inObjectLiteralExpression = false; + this.currentConstructor = null; + } + GrammarCheckerWalker.prototype.childFullStart = function (parent, child) { + return this.position() + TypeScript.Syntax.childOffset(parent, child); + }; + + GrammarCheckerWalker.prototype.childStart = function (parent, child) { + return this.childFullStart(parent, child) + child.leadingTriviaWidth(); + }; + + GrammarCheckerWalker.prototype.pushDiagnostic = function (start, length, diagnosticKey, args) { + if (typeof args === "undefined") { args = null; } + this.diagnostics.push(new TypeScript.Diagnostic(this.syntaxTree.fileName(), this.syntaxTree.lineMap(), start, length, diagnosticKey, args)); + }; + + GrammarCheckerWalker.prototype.pushDiagnostic1 = function (elementFullStart, element, diagnosticKey, args) { + if (typeof args === "undefined") { args = null; } + this.diagnostics.push(new TypeScript.Diagnostic(this.syntaxTree.fileName(), this.syntaxTree.lineMap(), elementFullStart + element.leadingTriviaWidth(), element.width(), diagnosticKey, args)); + }; + + GrammarCheckerWalker.prototype.visitCatchClause = function (node) { + if (node.typeAnnotation) { + this.pushDiagnostic(this.childStart(node, node.typeAnnotation), node.typeAnnotation.width(), TypeScript.DiagnosticCode.Catch_clause_parameter_cannot_have_a_type_annotation); + } + + _super.prototype.visitCatchClause.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkParameterListOrder = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameters); + + var seenOptionalParameter = false; + var parameterCount = node.parameters.nonSeparatorCount(); + + for (var i = 0, n = node.parameters.childCount(); i < n; i++) { + var nodeOrToken = node.parameters.childAt(i); + if (i % 2 === 0) { + var parameterIndex = i / 2; + var parameter = node.parameters.childAt(i); + + if (parameter.dotDotDotToken) { + if (parameterIndex !== (parameterCount - 1)) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Rest_parameter_must_be_last_in_list); + return true; + } + + if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Rest_parameter_cannot_be_optional); + return true; + } + + if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Rest_parameter_cannot_have_an_initializer); + return true; + } + } else if (parameter.questionToken || parameter.equalsValueClause) { + seenOptionalParameter = true; + + if (parameter.questionToken && parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Parameter_cannot_have_question_mark_and_initializer); + return true; + } + } else { + if (seenOptionalParameter) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Required_parameter_cannot_follow_optional_parameter); + return true; + } + } + } + + parameterFullStart += nodeOrToken.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkParameterListAcessibilityModifiers = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameters); + + for (var i = 0, n = node.parameters.childCount(); i < n; i++) { + var nodeOrToken = node.parameters.childAt(i); + if (i % 2 === 0) { + var parameter = node.parameters.childAt(i); + + if (this.checkParameterAccessibilityModifiers(node, parameter, parameterFullStart)) { + return true; + } + } + + parameterFullStart += nodeOrToken.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkParameterAccessibilityModifiers = function (parameterList, parameter, parameterFullStart) { + if (parameter.modifiers.childCount() > 0) { + var modifiers = parameter.modifiers; + var modifierFullStart = parameterFullStart + TypeScript.Syntax.childOffset(parameter, modifiers); + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + + if (this.checkParameterAccessibilityModifier(parameterList, modifier, modifierFullStart, i)) { + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkParameterAccessibilityModifier = function (parameterList, modifier, modifierFullStart, modifierIndex) { + if (modifier.tokenKind !== 57 /* PublicKeyword */ && modifier.tokenKind !== 55 /* PrivateKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_parameter, [modifier.text()]); + return true; + } else { + if (modifierIndex > 0) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return true; + } + + if (!this.inAmbientDeclaration && this.currentConstructor && !this.currentConstructor.block && this.currentConstructor.callSignature.parameterList === parameterList) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_cannot_be_used_in_a_constructor_overload); + return true; + } else if (this.inAmbientDeclaration || this.currentConstructor === null || this.currentConstructor.callSignature.parameterList !== parameterList) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_can_only_be_used_in_a_non_ambient_constructor_declaration); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForTrailingSeparator = function (parent, list) { + if (list.childCount() === 0 || list.childCount() % 2 === 1) { + return false; + } + + var currentElementFullStart = this.childFullStart(parent, list); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var child = list.childAt(i); + if (i === n - 1) { + this.pushDiagnostic1(currentElementFullStart, child, TypeScript.DiagnosticCode.Trailing_separator_not_allowed); + } + + currentElementFullStart += child.fullWidth(); + } + + return true; + }; + + GrammarCheckerWalker.prototype.checkForAtLeastOneElement = function (parent, list, expected) { + if (list.childCount() > 0) { + return false; + } + + var listFullStart = this.childFullStart(parent, list); + var tokenAtStart = this.syntaxTree.sourceUnit().findToken(listFullStart); + + this.pushDiagnostic1(listFullStart, tokenAtStart.token(), TypeScript.DiagnosticCode.Unexpected_token_0_expected, [expected]); + + return true; + }; + + GrammarCheckerWalker.prototype.visitParameterList = function (node) { + if (this.checkParameterListAcessibilityModifiers(node) || this.checkParameterListOrder(node) || this.checkForTrailingSeparator(node, node.parameters)) { + this.skip(node); + return; + } + + _super.prototype.visitParameterList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitHeritageClause = function (node) { + if (this.checkForTrailingSeparator(node, node.typeNames) || this.checkForAtLeastOneElement(node, node.typeNames, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_name, null))) { + this.skip(node); + return; + } + + _super.prototype.visitHeritageClause.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitArgumentList = function (node) { + if (this.checkForTrailingSeparator(node, node.arguments)) { + this.skip(node); + return; + } + + _super.prototype.visitArgumentList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitVariableDeclaration = function (node) { + if (this.checkForTrailingSeparator(node, node.variableDeclarators) || this.checkForAtLeastOneElement(node, node.variableDeclarators, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null))) { + this.skip(node); + return; + } + + _super.prototype.visitVariableDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTypeArgumentList = function (node) { + if (this.checkForTrailingSeparator(node, node.typeArguments) || this.checkForAtLeastOneElement(node, node.typeArguments, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null))) { + this.skip(node); + return; + } + + _super.prototype.visitTypeArgumentList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTypeParameterList = function (node) { + if (this.checkForTrailingSeparator(node, node.typeParameters) || this.checkForAtLeastOneElement(node, node.typeParameters, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null))) { + this.skip(node); + return; + } + + _super.prototype.visitTypeParameterList.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkIndexSignatureParameter = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameter); + var parameter = node.parameter; + + if (parameter.dotDotDotToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signatures_cannot_have_rest_parameters); + return true; + } else if (parameter.modifiers.childCount() > 0) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_accessibility_modifiers); + return true; + } else if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_a_question_mark); + return true; + } else if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_an_initializer); + return true; + } else if (!parameter.typeAnnotation) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_must_have_a_type_annotation); + return true; + } else if (parameter.typeAnnotation.type.kind() !== 69 /* StringKeyword */ && parameter.typeAnnotation.type.kind() !== 67 /* NumberKeyword */) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_type_must_be_string_or_number); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitIndexSignature = function (node) { + if (this.checkIndexSignatureParameter(node)) { + this.skip(node); + return; + } + + if (!node.typeAnnotation) { + this.pushDiagnostic1(this.position(), node, TypeScript.DiagnosticCode.Index_signature_must_have_a_type_annotation); + this.skip(node); + return; + } + + _super.prototype.visitIndexSignature.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkClassDeclarationHeritageClauses = function (node) { + var heritageClauseFullStart = this.childFullStart(node, node.heritageClauses); + + var seenExtendsClause = false; + var seenImplementsClause = false; + + for (var i = 0, n = node.heritageClauses.childCount(); i < n; i++) { + TypeScript.Debug.assert(i <= 2); + var heritageClause = node.heritageClauses.childAt(i); + + if (heritageClause.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */) { + if (seenExtendsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.extends_clause_already_seen); + return true; + } + + if (seenImplementsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.extends_clause_must_precede_implements_clause); + return true; + } + + if (heritageClause.typeNames.nonSeparatorCount() > 1) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.Classes_can_only_extend_a_single_class); + return true; + } + + seenExtendsClause = true; + } else { + TypeScript.Debug.assert(heritageClause.extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + if (seenImplementsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.implements_clause_already_seen); + return true; + } + + seenImplementsClause = true; + } + + heritageClauseFullStart += heritageClause.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedDeclareModifier = function (modifiers) { + if (this.inAmbientDeclaration) { + var declareToken = TypeScript.SyntaxUtilities.getToken(modifiers, 63 /* DeclareKeyword */); + + if (declareToken) { + this.pushDiagnostic1(this.childFullStart(modifiers, declareToken), declareToken, TypeScript.DiagnosticCode.declare_modifier_not_allowed_for_code_already_in_an_ambient_context); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForRequiredDeclareModifier = function (moduleElement, typeKeyword, modifiers) { + if (!this.inAmbientDeclaration && this.syntaxTree.isDeclaration()) { + if (!TypeScript.SyntaxUtilities.containsToken(modifiers, 63 /* DeclareKeyword */)) { + this.pushDiagnostic1(this.childFullStart(moduleElement, typeKeyword), typeKeyword.firstToken(), TypeScript.DiagnosticCode.declare_modifier_required_for_top_level_element); + return true; + } + } + }; + + GrammarCheckerWalker.prototype.checkFunctionOverloads = function (node, moduleElements) { + if (!this.inAmbientDeclaration && !this.syntaxTree.isDeclaration()) { + var moduleElementFullStart = this.childFullStart(node, moduleElements); + + var inFunctionOverloadChain = false; + var functionOverloadChainName = null; + + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var moduleElement = moduleElements.childAt(i); + var lastElement = i === (n - 1); + + if (inFunctionOverloadChain) { + if (moduleElement.kind() !== 129 /* FunctionDeclaration */) { + this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + + var functionDeclaration = moduleElement; + if (functionDeclaration.identifier.valueText() !== functionOverloadChainName) { + var identifierFullStart = moduleElementFullStart + TypeScript.Syntax.childOffset(moduleElement, functionDeclaration.identifier); + this.pushDiagnostic1(identifierFullStart, functionDeclaration.identifier, TypeScript.DiagnosticCode.Function_overload_name_must_be_0, [functionOverloadChainName]); + return true; + } + } + + if (moduleElement.kind() === 129 /* FunctionDeclaration */) { + functionDeclaration = moduleElement; + if (!TypeScript.SyntaxUtilities.containsToken(functionDeclaration.modifiers, 63 /* DeclareKeyword */)) { + inFunctionOverloadChain = functionDeclaration.block === null; + functionOverloadChainName = functionDeclaration.identifier.valueText(); + + if (inFunctionOverloadChain) { + if (lastElement) { + this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } else { + var nextElement = moduleElements.childAt(i + 1); + if (nextElement.kind() === 129 /* FunctionDeclaration */) { + var nextFunction = nextElement; + + if (nextFunction.identifier.valueText() !== functionOverloadChainName && nextFunction.block === null) { + var identifierFullStart = moduleElementFullStart + TypeScript.Syntax.childOffset(moduleElement, functionDeclaration.identifier); + this.pushDiagnostic1(identifierFullStart, functionDeclaration.identifier, TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + } + } + } + } else { + inFunctionOverloadChain = false; + functionOverloadChainName = ""; + } + } + + moduleElementFullStart += moduleElement.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkClassOverloads = function (node) { + if (!this.inAmbientDeclaration && !TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */)) { + var classElementFullStart = this.childFullStart(node, node.classElements); + + var inFunctionOverloadChain = false; + var inConstructorOverloadChain = false; + + var functionOverloadChainName = null; + var isInStaticOverloadChain = null; + var memberFunctionDeclaration = null; + + for (var i = 0, n = node.classElements.childCount(); i < n; i++) { + var classElement = node.classElements.childAt(i); + var lastElement = i === (n - 1); + var isStaticOverload = null; + + if (inFunctionOverloadChain) { + if (classElement.kind() !== 135 /* MemberFunctionDeclaration */) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + + memberFunctionDeclaration = classElement; + if (memberFunctionDeclaration.propertyName.valueText() !== functionOverloadChainName) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, TypeScript.DiagnosticCode.Function_overload_name_must_be_0, [functionOverloadChainName]); + return true; + } + + isStaticOverload = TypeScript.SyntaxUtilities.containsToken(memberFunctionDeclaration.modifiers, 58 /* StaticKeyword */); + if (isStaticOverload !== isInStaticOverloadChain) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + var diagnostic = isInStaticOverloadChain ? TypeScript.DiagnosticCode.Function_overload_must_be_static : TypeScript.DiagnosticCode.Function_overload_must_not_be_static; + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, diagnostic, null); + return true; + } + } else if (inConstructorOverloadChain) { + if (classElement.kind() !== 137 /* ConstructorDeclaration */) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Constructor_implementation_expected); + return true; + } + } + + if (classElement.kind() === 135 /* MemberFunctionDeclaration */) { + memberFunctionDeclaration = classElement; + + inFunctionOverloadChain = memberFunctionDeclaration.block === null; + functionOverloadChainName = memberFunctionDeclaration.propertyName.valueText(); + isInStaticOverloadChain = TypeScript.SyntaxUtilities.containsToken(memberFunctionDeclaration.modifiers, 58 /* StaticKeyword */); + + if (inFunctionOverloadChain) { + if (lastElement) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } else { + var nextElement = node.classElements.childAt(i + 1); + if (nextElement.kind() === 135 /* MemberFunctionDeclaration */) { + var nextMemberFunction = nextElement; + + if (nextMemberFunction.propertyName.valueText() !== functionOverloadChainName && nextMemberFunction.block === null) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + } + } + } + } else if (classElement.kind() === 137 /* ConstructorDeclaration */) { + var constructorDeclaration = classElement; + + inConstructorOverloadChain = constructorDeclaration.block === null; + if (lastElement && inConstructorOverloadChain) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Constructor_implementation_expected); + return true; + } + } + + classElementFullStart += classElement.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForReservedName = function (parent, name, diagnosticKey) { + var nameFullStart = this.childFullStart(parent, name); + var token; + var tokenFullStart; + + var current = name; + while (current !== null) { + if (current.kind() === 121 /* QualifiedName */) { + var qualifiedName = current; + token = qualifiedName.right; + tokenFullStart = nameFullStart + this.childFullStart(qualifiedName, token); + current = qualifiedName.left; + } else { + TypeScript.Debug.assert(current.kind() === 11 /* IdentifierName */); + token = current; + tokenFullStart = nameFullStart; + current = null; + } + + switch (token.valueText()) { + case "any": + case "number": + case "boolean": + case "string": + case "void": + this.pushDiagnostic(tokenFullStart + token.leadingTriviaWidth(), token.width(), diagnosticKey, [token.valueText()]); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitClassDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, TypeScript.DiagnosticCode.Class_name_cannot_be_0) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.classKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkClassDeclarationHeritageClauses(node) || this.checkClassOverloads(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitClassDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkInterfaceDeclarationHeritageClauses = function (node) { + var heritageClauseFullStart = this.childFullStart(node, node.heritageClauses); + + var seenExtendsClause = false; + + for (var i = 0, n = node.heritageClauses.childCount(); i < n; i++) { + TypeScript.Debug.assert(i <= 1); + var heritageClause = node.heritageClauses.childAt(i); + + if (heritageClause.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */) { + if (seenExtendsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.extends_clause_already_seen); + return true; + } + + seenExtendsClause = true; + } else { + TypeScript.Debug.assert(heritageClause.extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.Interface_declaration_cannot_have_implements_clause); + return true; + } + + heritageClauseFullStart += heritageClause.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkInterfaceModifiers = function (modifiers) { + var modifierFullStart = this.position(); + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + if (modifier.tokenKind === 63 /* DeclareKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.declare_modifier_cannot_appear_on_an_interface_declaration); + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitInterfaceDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, TypeScript.DiagnosticCode.Interface_name_cannot_be_0) || this.checkInterfaceModifiers(node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkInterfaceDeclarationHeritageClauses(node)) { + this.skip(node); + return; + } + + _super.prototype.visitInterfaceDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkClassElementModifiers = function (list) { + var modifierFullStart = this.position(); + + var seenAccessibilityModifier = false; + var seenStaticModifier = false; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var modifier = list.childAt(i); + if (modifier.tokenKind === 57 /* PublicKeyword */ || modifier.tokenKind === 55 /* PrivateKeyword */) { + if (seenAccessibilityModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return true; + } + + if (seenStaticModifier) { + var previousToken = list.childAt(i - 1); + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_must_precede_1_modifier, [modifier.text(), previousToken.text()]); + return true; + } + + seenAccessibilityModifier = true; + } else if (modifier.tokenKind === 58 /* StaticKeyword */) { + if (seenStaticModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_already_seen, [modifier.text()]); + return true; + } + + seenStaticModifier = true; + } else { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_class_element, [modifier.text()]); + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitMemberVariableDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitMemberVariableDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitMemberFunctionDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitMemberFunctionDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkGetAccessorParameter = function (node, getKeyword, parameterList) { + var getKeywordFullStart = this.childFullStart(node, getKeyword); + if (parameterList.parameters.childCount() !== 0) { + this.pushDiagnostic1(getKeywordFullStart, getKeyword, TypeScript.DiagnosticCode.get_accessor_cannot_have_parameters); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitIndexMemberDeclaration = function (node) { + if (this.checkIndexMemberModifiers(node)) { + this.skip(node); + return; + } + + _super.prototype.visitIndexMemberDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkIndexMemberModifiers = function (node) { + if (node.modifiers.childCount() > 0) { + var modifierFullStart = this.childFullStart(node, node.modifiers); + this.pushDiagnostic1(modifierFullStart, node.modifiers.childAt(0), TypeScript.DiagnosticCode.Modifiers_cannot_appear_here); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkEcmaScriptVersionIsAtLeast = function (parent, node, languageVersion, diagnosticKey) { + if (this.syntaxTree.parseOptions().languageVersion() < languageVersion) { + var nodeFullStart = this.childFullStart(parent, node); + this.pushDiagnostic1(nodeFullStart, node, diagnosticKey); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitObjectLiteralExpression = function (node) { + var savedInObjectLiteralExpression = this.inObjectLiteralExpression; + this.inObjectLiteralExpression = true; + _super.prototype.visitObjectLiteralExpression.call(this, node); + this.inObjectLiteralExpression = savedInObjectLiteralExpression; + }; + + GrammarCheckerWalker.prototype.visitGetAccessor = function (node) { + if (this.checkForAccessorDeclarationInAmbientContext(node) || this.checkEcmaScriptVersionIsAtLeast(node, node.getKeyword, 1 /* EcmaScript5 */, TypeScript.DiagnosticCode.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkClassElementModifiers(node.modifiers) || this.checkGetAccessorParameter(node, node.getKeyword, node.parameterList)) { + this.skip(node); + return; + } + + _super.prototype.visitGetAccessor.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkForAccessorDeclarationInAmbientContext = function (accessor) { + if (this.inAmbientDeclaration) { + this.pushDiagnostic1(this.position(), accessor, TypeScript.DiagnosticCode.Accessors_are_not_allowed_in_ambient_contexts, null); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkSetAccessorParameter = function (node, setKeyword, parameterList) { + var setKeywordFullStart = this.childFullStart(node, setKeyword); + if (parameterList.parameters.childCount() !== 1) { + this.pushDiagnostic1(setKeywordFullStart, setKeyword, TypeScript.DiagnosticCode.set_accessor_must_have_one_and_only_one_parameter); + return true; + } + + var parameterListFullStart = this.childFullStart(node, parameterList); + var parameterFullStart = parameterListFullStart + TypeScript.Syntax.childOffset(parameterList, parameterList.openParenToken); + var parameter = parameterList.parameters.childAt(0); + + if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.set_accessor_parameter_cannot_be_optional); + return true; + } + + if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.set_accessor_parameter_cannot_have_an_initializer); + return true; + } + + if (parameter.dotDotDotToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.set_accessor_cannot_have_rest_parameter); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitSetAccessor = function (node) { + if (this.checkForAccessorDeclarationInAmbientContext(node) || this.checkEcmaScriptVersionIsAtLeast(node, node.setKeyword, 1 /* EcmaScript5 */, TypeScript.DiagnosticCode.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkClassElementModifiers(node.modifiers) || this.checkSetAccessorParameter(node, node.setKeyword, node.parameterList)) { + this.skip(node); + return; + } + + _super.prototype.visitSetAccessor.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitEnumDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, TypeScript.DiagnosticCode.Enum_name_cannot_be_0) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.enumKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers), this.checkEnumElements(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitEnumDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkEnumElements = function (node) { + var enumElementFullStart = this.childFullStart(node, node.enumElements); + + var previousValueWasComputed = false; + for (var i = 0, n = node.enumElements.childCount(); i < n; i++) { + var child = node.enumElements.childAt(i); + + if (i % 2 === 0) { + var enumElement = child; + + if (!enumElement.equalsValueClause && previousValueWasComputed) { + this.pushDiagnostic1(enumElementFullStart, enumElement, TypeScript.DiagnosticCode.Enum_member_must_have_initializer, null); + return true; + } + + if (enumElement.equalsValueClause) { + var value = enumElement.equalsValueClause.value; + previousValueWasComputed = !TypeScript.Syntax.isIntegerLiteral(value); + } + } + + enumElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitEnumElement = function (node) { + if (this.inAmbientDeclaration && node.equalsValueClause) { + var expression = node.equalsValueClause.value; + if (!TypeScript.Syntax.isIntegerLiteral(expression)) { + this.pushDiagnostic1(this.childFullStart(node, node.equalsValueClause), node.equalsValueClause.firstToken(), TypeScript.DiagnosticCode.Ambient_enum_elements_can_only_have_integer_literal_initializers); + this.skip(node); + return; + } + } + + _super.prototype.visitEnumElement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitInvocationExpression = function (node) { + if (node.expression.kind() === 50 /* SuperKeyword */ && node.argumentList.typeArgumentList !== null) { + this.pushDiagnostic1(this.position(), node, TypeScript.DiagnosticCode.super_invocation_cannot_have_type_arguments); + } + + _super.prototype.visitInvocationExpression.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkModuleElementModifiers = function (modifiers) { + var modifierFullStart = this.position(); + var seenExportModifier = false; + var seenDeclareModifier = false; + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + if (modifier.tokenKind === 57 /* PublicKeyword */ || modifier.tokenKind === 55 /* PrivateKeyword */ || modifier.tokenKind === 58 /* StaticKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_module_element, [modifier.text()]); + return true; + } + + if (modifier.tokenKind === 63 /* DeclareKeyword */) { + if (seenDeclareModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return; + } + + seenDeclareModifier = true; + } else if (modifier.tokenKind === 47 /* ExportKeyword */) { + if (seenExportModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_already_seen, [modifier.text()]); + return; + } + + if (seenDeclareModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_must_precede_1_modifier, [TypeScript.SyntaxFacts.getText(47 /* ExportKeyword */), TypeScript.SyntaxFacts.getText(63 /* DeclareKeyword */)]); + return; + } + + seenExportModifier = true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedImportDeclaration = function (node) { + var currentElementFullStart = this.childFullStart(node, node.moduleElements); + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var child = node.moduleElements.childAt(i); + if (child.kind() === 133 /* ImportDeclaration */) { + var importDeclaration = child; + if (importDeclaration.moduleReference.kind() === 245 /* ExternalModuleReference */) { + if (node.stringLiteral === null) { + this.pushDiagnostic1(currentElementFullStart, importDeclaration, TypeScript.DiagnosticCode.Import_declarations_in_an_internal_module_cannot_reference_an_external_module, null); + } + } + } + + currentElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedDeclareModifierOnImportDeclaration = function (modifiers) { + var declareToken = TypeScript.SyntaxUtilities.getToken(modifiers, 63 /* DeclareKeyword */); + + if (declareToken) { + this.pushDiagnostic1(this.childFullStart(modifiers, declareToken), declareToken, TypeScript.DiagnosticCode.declare_modifier_not_allowed_on_import_declaration); + return true; + } + }; + + GrammarCheckerWalker.prototype.visitImportDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifierOnImportDeclaration(node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitImportDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitModuleDeclaration = function (node) { + if (this.checkForReservedName(node, node.name, TypeScript.DiagnosticCode.Module_name_cannot_be_0) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.moduleKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkForDisallowedImportDeclaration(node) || this.checkForDisallowedExports(node, node.moduleElements) || this.checkForMultipleExportAssignments(node, node.moduleElements)) { + this.skip(node); + return; + } + + if (!TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */) && this.checkFunctionOverloads(node, node.moduleElements)) { + this.skip(node); + return; + } + + if (node.stringLiteral) { + if (!this.inAmbientDeclaration && !TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */)) { + var stringLiteralFullStart = this.childFullStart(node, node.stringLiteral); + this.pushDiagnostic1(stringLiteralFullStart, node.stringLiteral, TypeScript.DiagnosticCode.Only_ambient_modules_can_use_quoted_names); + this.skip(node); + return; + } + } + + if (!node.stringLiteral && this.checkForDisallowedExportAssignment(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitModuleDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedExports = function (node, moduleElements) { + var seenExportedElement = false; + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + + if (TypeScript.SyntaxUtilities.hasExportKeyword(child)) { + seenExportedElement = true; + break; + } + } + + var moduleElementFullStart = this.childFullStart(node, moduleElements); + if (seenExportedElement) { + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + + if (child.kind() === 134 /* ExportAssignment */) { + this.pushDiagnostic1(moduleElementFullStart, child, TypeScript.DiagnosticCode.Export_assignment_not_allowed_in_module_with_exported_element); + return true; + } + + moduleElementFullStart += child.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForMultipleExportAssignments = function (node, moduleElements) { + var moduleElementFullStart = this.childFullStart(node, moduleElements); + var seenExportAssignment = false; + var errorFound = false; + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + if (child.kind() === 134 /* ExportAssignment */) { + if (seenExportAssignment) { + this.pushDiagnostic1(moduleElementFullStart, child, TypeScript.DiagnosticCode.Module_cannot_have_multiple_export_assignments); + errorFound = true; + } + seenExportAssignment = true; + } + + moduleElementFullStart += child.fullWidth(); + } + + return errorFound; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedExportAssignment = function (node) { + var moduleElementFullStart = this.childFullStart(node, node.moduleElements); + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var child = node.moduleElements.childAt(i); + + if (child.kind() === 134 /* ExportAssignment */) { + this.pushDiagnostic1(moduleElementFullStart, child, TypeScript.DiagnosticCode.Export_assignment_cannot_be_used_in_internal_modules); + + return true; + } + + moduleElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitBlock = function (node) { + if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) { + this.pushDiagnostic1(this.position(), node.firstToken(), TypeScript.DiagnosticCode.Implementations_are_not_allowed_in_ambient_contexts); + this.skip(node); + return; + } + + if (this.checkFunctionOverloads(node, node.statements)) { + this.skip(node); + return; + } + + var savedInBlock = this.inBlock; + this.inBlock = true; + _super.prototype.visitBlock.call(this, node); + this.inBlock = savedInBlock; + }; + + GrammarCheckerWalker.prototype.checkForStatementInAmbientContxt = function (node) { + if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) { + this.pushDiagnostic1(this.position(), node.firstToken(), TypeScript.DiagnosticCode.Statements_are_not_allowed_in_ambient_contexts); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitBreakStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitBreakStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitContinueStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitContinueStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitDebuggerStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitDebuggerStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitDoStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitDoStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitEmptyStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitEmptyStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitExpressionStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitExpressionStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitForInStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node) || this.checkForInStatementVariableDeclaration(node)) { + this.skip(node); + return; + } + + _super.prototype.visitForInStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkForInStatementVariableDeclaration = function (node) { + if (node.variableDeclaration && node.variableDeclaration.variableDeclarators.nonSeparatorCount() > 1) { + var variableDeclarationFullStart = this.childFullStart(node, node.variableDeclaration); + + this.pushDiagnostic1(variableDeclarationFullStart, node.variableDeclaration, TypeScript.DiagnosticCode.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitForStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitForStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitIfStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitIfStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitLabeledStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitLabeledStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitReturnStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitReturnStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitSwitchStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitSwitchStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitThrowStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitThrowStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTryStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitTryStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitWhileStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitWhileStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitWithStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitWithStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkForDisallowedModifiers = function (parent, modifiers) { + if (this.inBlock || this.inObjectLiteralExpression) { + if (modifiers.childCount() > 0) { + var modifierFullStart = this.childFullStart(parent, modifiers); + this.pushDiagnostic1(modifierFullStart, modifiers.childAt(0), TypeScript.DiagnosticCode.Modifiers_cannot_appear_here); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitFunctionDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkForRequiredDeclareModifier(node, node.functionKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitFunctionDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitVariableStatement = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkForRequiredDeclareModifier(node, node.variableDeclaration, node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitVariableStatement.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkListSeparators = function (parent, list, kind) { + var currentElementFullStart = this.childFullStart(parent, list); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var child = list.childAt(i); + if (i % 2 === 1 && child.kind() !== kind) { + this.pushDiagnostic1(currentElementFullStart, child, TypeScript.DiagnosticCode._0_expected, [TypeScript.SyntaxFacts.getText(kind)]); + } + + currentElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitObjectType = function (node) { + if (this.checkListSeparators(node, node.typeMembers, 78 /* SemicolonToken */)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitObjectType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitArrayType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitArrayType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitFunctionType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitFunctionType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitConstructorType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitConstructorType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitVariableDeclarator = function (node) { + if (this.inAmbientDeclaration && node.equalsValueClause) { + this.pushDiagnostic1(this.childFullStart(node, node.equalsValueClause), node.equalsValueClause.firstToken(), TypeScript.DiagnosticCode.Initializers_are_not_allowed_in_ambient_contexts); + this.skip(node); + return; + } + + _super.prototype.visitVariableDeclarator.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitConstructorDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers) || this.checkConstructorModifiers(node.modifiers) || this.checkConstructorTypeParameterList(node) || this.checkConstructorTypeAnnotation(node)) { + this.skip(node); + return; + } + + var savedCurrentConstructor = this.currentConstructor; + this.currentConstructor = node; + _super.prototype.visitConstructorDeclaration.call(this, node); + this.currentConstructor = savedCurrentConstructor; + }; + + GrammarCheckerWalker.prototype.checkConstructorModifiers = function (modifiers) { + var currentElementFullStart = this.position(); + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var child = modifiers.childAt(i); + if (child.kind() !== 57 /* PublicKeyword */) { + this.pushDiagnostic1(currentElementFullStart, child, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_constructor_declaration, [TypeScript.SyntaxFacts.getText(child.kind())]); + return true; + } + + currentElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkConstructorTypeParameterList = function (node) { + var currentElementFullStart = this.position(); + + if (node.callSignature.typeParameterList) { + var callSignatureFullStart = this.childFullStart(node, node.callSignature); + var typeParameterListFullStart = callSignatureFullStart + TypeScript.Syntax.childOffset(node.callSignature, node.callSignature.typeAnnotation); + this.pushDiagnostic1(callSignatureFullStart, node.callSignature.typeParameterList, TypeScript.DiagnosticCode.Type_parameters_cannot_appear_on_a_constructor_declaration); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkConstructorTypeAnnotation = function (node) { + var currentElementFullStart = this.position(); + + if (node.callSignature.typeAnnotation) { + var callSignatureFullStart = this.childFullStart(node, node.callSignature); + var typeAnnotationFullStart = callSignatureFullStart + TypeScript.Syntax.childOffset(node.callSignature, node.callSignature.typeAnnotation); + this.pushDiagnostic1(typeAnnotationFullStart, node.callSignature.typeAnnotation, TypeScript.DiagnosticCode.Type_annotation_cannot_appear_on_a_constructor_declaration); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitSourceUnit = function (node) { + if (this.checkFunctionOverloads(node, node.moduleElements) || this.checkForDisallowedExports(node, node.moduleElements) || this.checkForMultipleExportAssignments(node, node.moduleElements)) { + this.skip(node); + return; + } + + _super.prototype.visitSourceUnit.call(this, node); + }; + return GrammarCheckerWalker; + })(TypeScript.PositionTrackingWalker); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Unicode = (function () { + function Unicode() { + } + Unicode.lookupInUnicodeMap = function (code, map) { + if (code < map[0]) { + return false; + } + + 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; + }; + + Unicode.isIdentifierStart = function (code, languageVersion) { + if (languageVersion === 0 /* EcmaScript3 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES3IdentifierStart); + } else if (languageVersion === 1 /* EcmaScript5 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES5IdentifierStart); + } else { + throw TypeScript.Errors.argumentOutOfRange("languageVersion"); + } + }; + + Unicode.isIdentifierPart = function (code, languageVersion) { + if (languageVersion === 0 /* EcmaScript3 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES3IdentifierPart); + } else if (languageVersion === 1 /* EcmaScript5 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES5IdentifierPart); + } else { + throw TypeScript.Errors.argumentOutOfRange("languageVersion"); + } + }; + Unicode.unicodeES3IdentifierStart = [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]; + Unicode.unicodeES3IdentifierPart = [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, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 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, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 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, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 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, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + + Unicode.unicodeES5IdentifierStart = [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]; + Unicode.unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 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, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 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, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 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, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 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, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + return Unicode; + })(); + TypeScript.Unicode = Unicode; +})(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; + + function timeFunction(logger, funcDescription, func) { + var start = (new Date()).getTime(); + var result = func(); + var end = (new Date()).getTime(); + if (logger.information()) { + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + } + return result; + } + TypeScript.timeFunction = timeFunction; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Document = (function () { + function Document(_compiler, _semanticInfoChain, fileName, referencedFiles, _scriptSnapshot, byteOrderMark, version, isOpen, _syntaxTree, _topLevelDecl) { + this._compiler = _compiler; + this._semanticInfoChain = _semanticInfoChain; + this.fileName = fileName; + this.referencedFiles = referencedFiles; + this._scriptSnapshot = _scriptSnapshot; + this.byteOrderMark = byteOrderMark; + this.version = version; + this.isOpen = isOpen; + this._syntaxTree = _syntaxTree; + this._topLevelDecl = _topLevelDecl; + this._diagnostics = null; + this._bloomFilter = null; + this._sourceUnit = null; + this._lineMap = null; + this._declASTMap = []; + this._astDeclMap = []; + this._amdDependencies = undefined; + this._externalModuleIndicatorSpan = undefined; + } + Document.prototype.invalidate = function () { + this._declASTMap.length = 0; + this._astDeclMap.length = 0; + this._topLevelDecl = null; + + this._syntaxTree = null; + this._sourceUnit = null; + this._diagnostics = null; + this._bloomFilter = null; + }; + + Document.prototype.isDeclareFile = function () { + return TypeScript.isDTSFile(this.fileName); + }; + + Document.prototype.cacheSyntaxTreeInfo = function (syntaxTree) { + var start = new Date().getTime(); + this._diagnostics = syntaxTree.diagnostics(); + TypeScript.syntaxDiagnosticsTime += new Date().getTime() - start; + + this._lineMap = syntaxTree.lineMap(); + + var sourceUnit = syntaxTree.sourceUnit(); + var leadingTrivia = sourceUnit.leadingTrivia(); + + this._externalModuleIndicatorSpan = this.getImplicitImportSpan(leadingTrivia) || this.getTopLevelImportOrExportSpan(sourceUnit); + + var amdDependencies = []; + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.isComment()) { + var amdDependency = this.getAmdDependency(trivia.fullText()); + if (amdDependency) { + amdDependencies.push(amdDependency); + } + } + } + + this._amdDependencies = amdDependencies; + }; + + Document.prototype.getAmdDependency = function (comment) { + var amdDependencyRegEx = /^\/\/\/\s*/gim; + var match = implicitImportRegEx.exec(trivia.fullText()); + + if (match) { + return new TypeScript.TextSpan(position, trivia.fullWidth()); + } + + return null; + }; + + Document.prototype.getTopLevelImportOrExportSpan = function (node) { + var firstToken; + var position = 0; + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var moduleElement = node.moduleElements.childAt(i); + + firstToken = moduleElement.firstToken(); + if (firstToken !== null && firstToken.tokenKind === 47 /* ExportKeyword */) { + return new TypeScript.TextSpan(position + firstToken.leadingTriviaWidth(), firstToken.width()); + } + + if (moduleElement.kind() === 133 /* ImportDeclaration */) { + var importDecl = moduleElement; + if (importDecl.moduleReference.kind() === 245 /* ExternalModuleReference */) { + return new TypeScript.TextSpan(position + importDecl.leadingTriviaWidth(), importDecl.width()); + } + } + + position += moduleElement.fullWidth(); + } + + return null; + ; + }; + + Document.prototype.sourceUnit = function () { + if (!this._sourceUnit) { + var start = new Date().getTime(); + var syntaxTree = this.syntaxTree(); + this._sourceUnit = TypeScript.SyntaxTreeToAstVisitor.visit(syntaxTree, this.fileName, this._compiler.compilationSettings(), this.isOpen); + TypeScript.astTranslationTime += new Date().getTime() - start; + + if (!this.isOpen) { + this._syntaxTree = null; + } + } + + return this._sourceUnit; + }; + + Document.prototype.diagnostics = function () { + if (this._diagnostics === null) { + this.syntaxTree(); + TypeScript.Debug.assert(this._diagnostics); + } + + return this._diagnostics; + }; + + Document.prototype.lineMap = function () { + if (this._lineMap === null) { + this.syntaxTree(); + TypeScript.Debug.assert(this._lineMap); + } + + return this._lineMap; + }; + + Document.prototype.isExternalModule = function () { + return this.externalModuleIndicatorSpan() !== null; + }; + + Document.prototype.externalModuleIndicatorSpan = function () { + if (this._externalModuleIndicatorSpan === undefined) { + this.syntaxTree(); + TypeScript.Debug.assert(this._externalModuleIndicatorSpan !== undefined); + } + + return this._externalModuleIndicatorSpan; + }; + + Document.prototype.amdDependencies = function () { + if (this._amdDependencies === undefined) { + this.syntaxTree(); + TypeScript.Debug.assert(this._amdDependencies !== undefined); + } + + return this._amdDependencies; + }; + + Document.prototype.syntaxTree = function () { + var result = this._syntaxTree; + if (!result) { + var start = new Date().getTime(); + + result = TypeScript.Parser.parse(this.fileName, TypeScript.SimpleText.fromScriptSnapshot(this._scriptSnapshot), TypeScript.isDTSFile(this.fileName), TypeScript.getParseOptions(this._compiler.compilationSettings())); + + TypeScript.syntaxTreeParseTime += new Date().getTime() - start; + + if (this.isOpen || !this._sourceUnit) { + this._syntaxTree = result; + } + } + + this.cacheSyntaxTreeInfo(result); + return result; + }; + + Document.prototype.bloomFilter = function () { + if (!this._bloomFilter) { + var identifiers = TypeScript.createIntrinsicsObject(); + var pre = function (cur) { + if (TypeScript.ASTHelpers.isValidAstNode(cur)) { + if (cur.kind() === 11 /* IdentifierName */) { + var nodeText = cur.valueText(); + + identifiers[nodeText] = true; + } + } + }; + + TypeScript.getAstWalkerFactory().simpleWalk(this.sourceUnit(), pre, null, identifiers); + + var identifierCount = 0; + for (var name in identifiers) { + if (identifiers[name]) { + identifierCount++; + } + } + + this._bloomFilter = new TypeScript.BloomFilter(identifierCount); + this._bloomFilter.addKeys(identifiers); + } + return this._bloomFilter; + }; + + Document.prototype.emitToOwnOutputFile = function () { + return !this._compiler.compilationSettings().outFileOption() || this.isExternalModule(); + }; + + Document.prototype.update = function (scriptSnapshot, version, isOpen, textChangeRange) { + var oldSyntaxTree = this._syntaxTree; + + if (textChangeRange !== null && TypeScript.Debug.shouldAssert(1 /* Normal */)) { + var oldText = this._scriptSnapshot; + var newText = scriptSnapshot; + + TypeScript.Debug.assert((oldText.getLength() - textChangeRange.span().length() + textChangeRange.newLength()) === newText.getLength()); + + if (TypeScript.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldTextPrefix = oldText.getText(0, textChangeRange.span().start()); + var newTextPrefix = newText.getText(0, textChangeRange.span().start()); + TypeScript.Debug.assert(oldTextPrefix === newTextPrefix); + + var oldTextSuffix = oldText.getText(textChangeRange.span().end(), oldText.getLength()); + var newTextSuffix = newText.getText(textChangeRange.newSpan().end(), newText.getLength()); + TypeScript.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + + var text = TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot); + + var newSyntaxTree = textChangeRange === null || oldSyntaxTree === null ? TypeScript.Parser.parse(this.fileName, text, TypeScript.isDTSFile(this.fileName), TypeScript.getParseOptions(this._compiler.compilationSettings())) : TypeScript.Parser.incrementalParse(oldSyntaxTree, textChangeRange, text); + + return new Document(this._compiler, this._semanticInfoChain, this.fileName, this.referencedFiles, scriptSnapshot, this.byteOrderMark, version, isOpen, newSyntaxTree, null); + }; + + Document.create = function (compiler, semanticInfoChain, fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles) { + return new Document(compiler, semanticInfoChain, fileName, referencedFiles, scriptSnapshot, byteOrderMark, version, isOpen, null, null); + }; + + Document.prototype.topLevelDecl = function () { + if (this._topLevelDecl === null) { + this._topLevelDecl = TypeScript.DeclarationCreator.create(this, this._semanticInfoChain, this._compiler.compilationSettings()); + } + + return this._topLevelDecl; + }; + + Document.prototype._getDeclForAST = function (ast) { + this.topLevelDecl(); + return this._astDeclMap[ast.syntaxID()]; + }; + + Document.prototype.getEnclosingDecl = function (ast) { + if (ast.kind() === 120 /* SourceUnit */) { + return this._getDeclForAST(ast); + } + + ast = ast.parent; + var decl = null; + while (ast) { + decl = this._getDeclForAST(ast); + + if (decl) { + break; + } + + ast = ast.parent; + } + + return decl._getEnclosingDeclFromParentDecl(); + }; + + Document.prototype._setDeclForAST = function (ast, decl) { + TypeScript.Debug.assert(decl.fileName() === this.fileName); + this._astDeclMap[ast.syntaxID()] = decl; + }; + + Document.prototype._getASTForDecl = function (decl) { + return this._declASTMap[decl.declID]; + }; + + Document.prototype._setASTForDecl = function (decl, ast) { + TypeScript.Debug.assert(decl.fileName() === this.fileName); + this._declASTMap[decl.declID] = ast; + }; + return Document; + })(); + TypeScript.Document = Document; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function hasFlag(val, flag) { + return (val & flag) !== 0; + } + TypeScript.hasFlag = hasFlag; + + (function (TypeRelationshipFlags) { + TypeRelationshipFlags[TypeRelationshipFlags["SuccessfulComparison"] = 0] = "SuccessfulComparison"; + TypeRelationshipFlags[TypeRelationshipFlags["RequiredPropertyIsMissing"] = 1 << 1] = "RequiredPropertyIsMissing"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleSignatures"] = 1 << 2] = "IncompatibleSignatures"; + TypeRelationshipFlags[TypeRelationshipFlags["SourceSignatureHasTooManyParameters"] = 3] = "SourceSignatureHasTooManyParameters"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleReturnTypes"] = 1 << 4] = "IncompatibleReturnTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatiblePropertyTypes"] = 1 << 5] = "IncompatiblePropertyTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleParameterTypes"] = 1 << 6] = "IncompatibleParameterTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["InconsistantPropertyAccesibility"] = 1 << 7] = "InconsistantPropertyAccesibility"; + })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); + var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; + + (function (ModuleGenTarget) { + ModuleGenTarget[ModuleGenTarget["Unspecified"] = 0] = "Unspecified"; + ModuleGenTarget[ModuleGenTarget["Synchronous"] = 1] = "Synchronous"; + ModuleGenTarget[ModuleGenTarget["Asynchronous"] = 2] = "Asynchronous"; + })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); + var ModuleGenTarget = TypeScript.ModuleGenTarget; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var proto = "__proto__"; + + 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; + + this[proto] = null; + this[proto] = undefined; + } + return BlockIntrinsics; + })(); + + function createIntrinsicsObject() { + return new BlockIntrinsics(); + } + TypeScript.createIntrinsicsObject = createIntrinsicsObject; + + var StringHashTable = (function () { + function StringHashTable() { + this.itemCount = 0; + this.table = createIntrinsicsObject(); + } + StringHashTable.prototype.getAllKeys = function () { + var result = []; + + for (var k in this.table) { + if (this.table[k] !== undefined) { + result.push(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]; + return data === undefined ? null : data; + }; + + StringHashTable.prototype.remove = function (key) { + if (this.table[key] !== undefined) { + this.table[key] = undefined; + this.itemCount--; + } + }; + return StringHashTable; + })(); + TypeScript.StringHashTable = StringHashTable; + + var IdentiferNameHashTable = (function (_super) { + __extends(IdentiferNameHashTable, _super); + function IdentiferNameHashTable() { + _super.apply(this, arguments); + } + IdentiferNameHashTable.prototype.getAllKeys = function () { + var result = []; + + _super.prototype.map.call(this, function (k, v, c) { + if (v !== undefined) { + result.push(k.substring(1)); + } + }, null); + + return result; + }; + + IdentiferNameHashTable.prototype.add = function (key, data) { + return _super.prototype.add.call(this, "#" + key, data); + }; + + IdentiferNameHashTable.prototype.addOrUpdate = function (key, data) { + return _super.prototype.addOrUpdate.call(this, "#" + key, data); + }; + + IdentiferNameHashTable.prototype.map = function (fn, context) { + return _super.prototype.map.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.every = function (fn, context) { + return _super.prototype.every.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.some = function (fn, context) { + return _super.prototype.some.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.lookup = function (key) { + return _super.prototype.lookup.call(this, "#" + key); + }; + return IdentiferNameHashTable; + })(StringHashTable); + TypeScript.IdentiferNameHashTable = IdentiferNameHashTable; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (ASTHelpers) { + function scriptIsElided(sourceUnit) { + return TypeScript.isDTSFile(sourceUnit.fileName()) || moduleMembersAreElided(sourceUnit.moduleElements); + } + ASTHelpers.scriptIsElided = scriptIsElided; + + function moduleIsElided(declaration) { + return TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) || moduleMembersAreElided(declaration.moduleElements); + } + ASTHelpers.moduleIsElided = moduleIsElided; + + function moduleMembersAreElided(members) { + for (var i = 0, n = members.childCount(); i < n; i++) { + var member = members.childAt(i); + + if (member.kind() === 130 /* ModuleDeclaration */) { + if (!moduleIsElided(member)) { + return false; + } + } else if (member.kind() !== 128 /* InterfaceDeclaration */) { + return false; + } + } + + return true; + } + + function enumIsElided(declaration) { + if (TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */)) { + return true; + } + + return false; + } + ASTHelpers.enumIsElided = enumIsElided; + + function isValidAstNode(ast) { + if (!ast) + return false; + + if (ast.start() === -1 || ast.end() === -1) + return false; + + return true; + } + ASTHelpers.isValidAstNode = isValidAstNode; + + function getAstAtPosition(script, pos, useTrailingTriviaAsLimChar, forceInclusive) { + if (typeof useTrailingTriviaAsLimChar === "undefined") { useTrailingTriviaAsLimChar = true; } + if (typeof forceInclusive === "undefined") { forceInclusive = false; } + var top = null; + + var pre = function (cur, walker) { + if (isValidAstNode(cur)) { + var isInvalid1 = cur.kind() === 149 /* ExpressionStatement */ && cur.width() === 0; + + if (isInvalid1) { + walker.options.goChildren = false; + } else { + var inclusive = forceInclusive || cur.kind() === 11 /* IdentifierName */ || cur.kind() === 212 /* MemberAccessExpression */ || cur.kind() === 121 /* QualifiedName */ || cur.kind() === 224 /* VariableDeclaration */ || cur.kind() === 225 /* VariableDeclarator */ || cur.kind() === 213 /* InvocationExpression */ || pos === script.end() + script.trailingTriviaWidth(); + + var minChar = cur.start(); + var limChar = cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0) + (inclusive ? 1 : 0); + if (pos >= minChar && pos < limChar) { + if ((cur.kind() !== 1 /* List */ && cur.kind() !== 2 /* SeparatedList */) || cur.end() > cur.start()) { + if (top === null) { + top = cur; + } else if (cur.start() >= top.start() && (cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0)) <= (top.end() + (useTrailingTriviaAsLimChar ? top.trailingTriviaWidth() : 0))) { + if (top.width() !== 0 || cur.width() !== 0) { + top = cur; + } + } + } + } + + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + }; + + TypeScript.getAstWalkerFactory().walk(script, pre); + return top; + } + ASTHelpers.getAstAtPosition = getAstAtPosition; + + function getExtendsHeritageClause(clauses) { + if (!clauses) { + return null; + } + + return clauses.firstOrDefault(function (c) { + return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 230 /* ExtendsHeritageClause */; + }); + } + ASTHelpers.getExtendsHeritageClause = getExtendsHeritageClause; + + function getImplementsHeritageClause(clauses) { + if (!clauses) { + return null; + } + + return clauses.firstOrDefault(function (c) { + return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 231 /* ImplementsHeritageClause */; + }); + } + ASTHelpers.getImplementsHeritageClause = getImplementsHeritageClause; + + function isCallExpression(ast) { + return (ast && ast.kind() === 213 /* InvocationExpression */) || (ast && ast.kind() === 216 /* ObjectCreationExpression */); + } + ASTHelpers.isCallExpression = isCallExpression; + + function isCallExpressionTarget(ast) { + if (!ast) { + return false; + } + + var current = ast; + + while (current && current.parent) { + if (current.parent.kind() === 212 /* MemberAccessExpression */ && current.parent.name === current) { + current = current.parent; + continue; + } + + break; + } + + if (current && current.parent) { + if (current.parent.kind() === 213 /* InvocationExpression */ || current.parent.kind() === 216 /* ObjectCreationExpression */) { + return current === current.parent.expression; + } + } + + return false; + } + ASTHelpers.isCallExpressionTarget = isCallExpressionTarget; + + function isNameOfSomeDeclaration(ast) { + if (ast === null || ast.parent === null) { + return false; + } + if (ast.kind() !== 11 /* IdentifierName */) { + return false; + } + + switch (ast.parent.kind()) { + case 131 /* ClassDeclaration */: + return ast.parent.identifier === ast; + case 128 /* InterfaceDeclaration */: + return ast.parent.identifier === ast; + case 132 /* EnumDeclaration */: + return ast.parent.identifier === ast; + case 130 /* ModuleDeclaration */: + return ast.parent.name === ast || ast.parent.stringLiteral === ast; + case 225 /* VariableDeclarator */: + return ast.parent.propertyName === ast; + case 129 /* FunctionDeclaration */: + return ast.parent.identifier === ast; + case 135 /* MemberFunctionDeclaration */: + return ast.parent.propertyName === ast; + case 242 /* Parameter */: + return ast.parent.identifier === ast; + case 238 /* TypeParameter */: + return ast.parent.identifier === ast; + case 240 /* SimplePropertyAssignment */: + return ast.parent.propertyName === ast; + case 241 /* FunctionPropertyAssignment */: + return ast.parent.propertyName === ast; + case 243 /* EnumElement */: + return ast.parent.propertyName === ast; + case 133 /* ImportDeclaration */: + return ast.parent.identifier === ast; + } + + return false; + } + + function isDeclarationASTOrDeclarationNameAST(ast) { + return isNameOfSomeDeclaration(ast) || isDeclarationAST(ast); + } + ASTHelpers.isDeclarationASTOrDeclarationNameAST = isDeclarationASTOrDeclarationNameAST; + + function getEnclosingParameterForInitializer(ast) { + var current = ast; + while (current) { + switch (current.kind()) { + case 232 /* EqualsValueClause */: + if (current.parent && current.parent.kind() === 242 /* Parameter */) { + return current.parent; + } + break; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + return null; + } + + current = current.parent; + } + return null; + } + ASTHelpers.getEnclosingParameterForInitializer = getEnclosingParameterForInitializer; + + function getEnclosingMemberVariableDeclaration(ast) { + var current = ast; + + while (current) { + switch (current.kind()) { + case 136 /* MemberVariableDeclaration */: + return current; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + return null; + } + current = current.parent; + } + + return null; + } + ASTHelpers.getEnclosingMemberVariableDeclaration = getEnclosingMemberVariableDeclaration; + + function isNameOfFunction(ast) { + return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 129 /* FunctionDeclaration */ && ast.parent.identifier === ast; + } + ASTHelpers.isNameOfFunction = isNameOfFunction; + + function isNameOfMemberFunction(ast) { + return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 135 /* MemberFunctionDeclaration */ && ast.parent.propertyName === ast; + } + ASTHelpers.isNameOfMemberFunction = isNameOfMemberFunction; + + function isNameOfMemberAccessExpression(ast) { + if (ast && ast.parent && ast.parent.kind() === 212 /* MemberAccessExpression */ && ast.parent.name === ast) { + return true; + } + + return false; + } + ASTHelpers.isNameOfMemberAccessExpression = isNameOfMemberAccessExpression; + + function isRightSideOfQualifiedName(ast) { + if (ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast) { + return true; + } + + return false; + } + ASTHelpers.isRightSideOfQualifiedName = isRightSideOfQualifiedName; + + function parentIsModuleDeclaration(ast) { + return ast.parent && ast.parent.kind() === 130 /* ModuleDeclaration */; + } + ASTHelpers.parentIsModuleDeclaration = parentIsModuleDeclaration; + + function parametersFromIdentifier(id) { + return { + length: 1, + lastParameterIsRest: function () { + return false; + }, + ast: id, + astAt: function (index) { + return id; + }, + identifierAt: function (index) { + return id; + }, + typeAt: function (index) { + return null; + }, + initializerAt: function (index) { + return null; + }, + isOptionalAt: function (index) { + return false; + } + }; + } + ASTHelpers.parametersFromIdentifier = parametersFromIdentifier; + + function parametersFromParameter(parameter) { + return { + length: 1, + lastParameterIsRest: function () { + return parameter.dotDotDotToken !== null; + }, + ast: parameter, + astAt: function (index) { + return parameter; + }, + identifierAt: function (index) { + return parameter.identifier; + }, + typeAt: function (index) { + return getType(parameter); + }, + initializerAt: function (index) { + return parameter.equalsValueClause; + }, + isOptionalAt: function (index) { + return parameterIsOptional(parameter); + } + }; + } + ASTHelpers.parametersFromParameter = parametersFromParameter; + + function parameterIsOptional(parameter) { + return parameter.questionToken !== null || parameter.equalsValueClause !== null; + } + + function parametersFromParameterList(list) { + return { + length: list.parameters.nonSeparatorCount(), + lastParameterIsRest: function () { + return TypeScript.lastParameterIsRest(list); + }, + ast: list.parameters, + astAt: function (index) { + return list.parameters.nonSeparatorAt(index); + }, + identifierAt: function (index) { + return list.parameters.nonSeparatorAt(index).identifier; + }, + typeAt: function (index) { + return getType(list.parameters.nonSeparatorAt(index)); + }, + initializerAt: function (index) { + return list.parameters.nonSeparatorAt(index).equalsValueClause; + }, + isOptionalAt: function (index) { + return parameterIsOptional(list.parameters.nonSeparatorAt(index)); + } + }; + } + ASTHelpers.parametersFromParameterList = parametersFromParameterList; + + function isDeclarationAST(ast) { + switch (ast.kind()) { + case 225 /* VariableDeclarator */: + return getVariableStatement(ast) !== null; + + case 133 /* ImportDeclaration */: + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 242 /* Parameter */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 144 /* IndexSignature */: + case 129 /* FunctionDeclaration */: + case 130 /* ModuleDeclaration */: + case 124 /* ArrayType */: + case 122 /* ObjectType */: + case 238 /* TypeParameter */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 136 /* MemberVariableDeclaration */: + case 138 /* IndexMemberDeclaration */: + case 132 /* EnumDeclaration */: + case 243 /* EnumElement */: + case 240 /* SimplePropertyAssignment */: + case 241 /* FunctionPropertyAssignment */: + case 222 /* FunctionExpression */: + case 142 /* CallSignature */: + case 143 /* ConstructSignature */: + case 145 /* MethodSignature */: + case 141 /* PropertySignature */: + return true; + default: + return false; + } + } + ASTHelpers.isDeclarationAST = isDeclarationAST; + + function docComments(ast) { + if (isDeclarationAST(ast)) { + var preComments = ast.kind() === 225 /* VariableDeclarator */ ? getVariableStatement(ast).preComments() : ast.preComments(); + + if (preComments && preComments.length > 0) { + var preCommentsLength = preComments.length; + var docComments = new Array(); + for (var i = preCommentsLength - 1; i >= 0; i--) { + if (isDocComment(preComments[i])) { + docComments.push(preComments[i]); + continue; + } + + break; + } + + return docComments.reverse(); + } + } + + return TypeScript.sentinelEmptyArray; + } + ASTHelpers.docComments = docComments; + + function isDocComment(comment) { + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + var fullText = comment.fullText(); + return fullText.charAt(2) === "*" && fullText.charAt(3) !== "/"; + } + + return false; + } + + function getParameterList(ast) { + if (ast) { + switch (ast.kind()) { + case 137 /* ConstructorDeclaration */: + return getParameterList(ast.callSignature); + case 129 /* FunctionDeclaration */: + return getParameterList(ast.callSignature); + case 218 /* ParenthesizedArrowFunctionExpression */: + return getParameterList(ast.callSignature); + case 143 /* ConstructSignature */: + return getParameterList(ast.callSignature); + case 135 /* MemberFunctionDeclaration */: + return getParameterList(ast.callSignature); + case 241 /* FunctionPropertyAssignment */: + return getParameterList(ast.callSignature); + case 222 /* FunctionExpression */: + return getParameterList(ast.callSignature); + case 145 /* MethodSignature */: + return getParameterList(ast.callSignature); + case 125 /* ConstructorType */: + return ast.parameterList; + case 123 /* FunctionType */: + return ast.parameterList; + case 142 /* CallSignature */: + return ast.parameterList; + case 139 /* GetAccessor */: + return ast.parameterList; + case 140 /* SetAccessor */: + return ast.parameterList; + } + } + + return null; + } + ASTHelpers.getParameterList = getParameterList; + + function getType(ast) { + if (ast) { + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + return getType(ast.callSignature); + case 218 /* ParenthesizedArrowFunctionExpression */: + return getType(ast.callSignature); + case 143 /* ConstructSignature */: + return getType(ast.callSignature); + case 135 /* MemberFunctionDeclaration */: + return getType(ast.callSignature); + case 241 /* FunctionPropertyAssignment */: + return getType(ast.callSignature); + case 222 /* FunctionExpression */: + return getType(ast.callSignature); + case 145 /* MethodSignature */: + return getType(ast.callSignature); + case 142 /* CallSignature */: + return getType(ast.typeAnnotation); + case 144 /* IndexSignature */: + return getType(ast.typeAnnotation); + case 141 /* PropertySignature */: + return getType(ast.typeAnnotation); + case 139 /* GetAccessor */: + return getType(ast.typeAnnotation); + case 242 /* Parameter */: + return getType(ast.typeAnnotation); + case 136 /* MemberVariableDeclaration */: + return getType(ast.variableDeclarator); + case 225 /* VariableDeclarator */: + return getType(ast.typeAnnotation); + case 236 /* CatchClause */: + return getType(ast.typeAnnotation); + case 125 /* ConstructorType */: + return ast.type; + case 123 /* FunctionType */: + return ast.type; + case 244 /* TypeAnnotation */: + return ast.type; + } + } + + return null; + } + ASTHelpers.getType = getType; + + function getVariableStatement(variableDeclarator) { + if (variableDeclarator && variableDeclarator.parent && variableDeclarator.parent.parent && variableDeclarator.parent.parent.parent && variableDeclarator.parent.kind() === 2 /* SeparatedList */ && variableDeclarator.parent.parent.kind() === 224 /* VariableDeclaration */ && variableDeclarator.parent.parent.parent.kind() === 148 /* VariableStatement */) { + return variableDeclarator.parent.parent.parent; + } + + return null; + } + + function getVariableDeclaratorModifiers(variableDeclarator) { + var variableStatement = getVariableStatement(variableDeclarator); + return variableStatement ? variableStatement.modifiers : TypeScript.sentinelEmptyArray; + } + ASTHelpers.getVariableDeclaratorModifiers = getVariableDeclaratorModifiers; + + function isIntegerLiteralAST(expression) { + if (expression) { + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + expression = expression.operand; + return expression.kind() === 13 /* NumericLiteral */ && TypeScript.IntegerUtilities.isInteger(expression.text()); + + case 13 /* NumericLiteral */: + var text = expression.text(); + return TypeScript.IntegerUtilities.isInteger(text) || TypeScript.IntegerUtilities.isHexInteger(text); + } + } + + return false; + } + ASTHelpers.isIntegerLiteralAST = isIntegerLiteralAST; + + function getEnclosingModuleDeclaration(ast) { + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + return ast; + } + + ast = ast.parent; + } + + return null; + } + ASTHelpers.getEnclosingModuleDeclaration = getEnclosingModuleDeclaration; + + function isEntireNameOfModuleDeclaration(nameAST) { + return parentIsModuleDeclaration(nameAST) && nameAST.parent.name === nameAST; + } + + function getModuleDeclarationFromNameAST(ast) { + if (ast) { + switch (ast.kind()) { + case 14 /* StringLiteral */: + if (parentIsModuleDeclaration(ast) && ast.parent.stringLiteral === ast) { + return ast.parent; + } + return null; + + case 11 /* IdentifierName */: + case 121 /* QualifiedName */: + if (isEntireNameOfModuleDeclaration(ast)) { + return ast.parent; + } + break; + + default: + return null; + } + + for (ast = ast.parent; ast && ast.kind() === 121 /* QualifiedName */; ast = ast.parent) { + if (isEntireNameOfModuleDeclaration(ast)) { + return ast.parent; + } + } + } + + return null; + } + ASTHelpers.getModuleDeclarationFromNameAST = getModuleDeclarationFromNameAST; + + function isLastNameOfModule(ast, astName) { + if (ast) { + if (ast.stringLiteral) { + return astName === ast.stringLiteral; + } else if (ast.name.kind() === 121 /* QualifiedName */) { + return astName === ast.name.right; + } else { + return astName === ast.name; + } + } + + return false; + } + ASTHelpers.isLastNameOfModule = isLastNameOfModule; + + function getNameOfIdenfierOrQualifiedName(name) { + if (name.kind() === 11 /* IdentifierName */) { + return name.text(); + } else { + TypeScript.Debug.assert(name.kind() == 121 /* QualifiedName */); + var dotExpr = name; + return getNameOfIdenfierOrQualifiedName(dotExpr.left) + "." + getNameOfIdenfierOrQualifiedName(dotExpr.right); + } + } + ASTHelpers.getNameOfIdenfierOrQualifiedName = getNameOfIdenfierOrQualifiedName; + + function getModuleNames(name, result) { + result = result || []; + + if (name.kind() === 121 /* QualifiedName */) { + getModuleNames(name.left, result); + result.push(name.right); + } else { + result.push(name); + } + + return result; + } + ASTHelpers.getModuleNames = getModuleNames; + })(TypeScript.ASTHelpers || (TypeScript.ASTHelpers = {})); + var ASTHelpers = TypeScript.ASTHelpers; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function walkListChildren(preAst, walker) { + for (var i = 0, n = preAst.childCount(); i < n; i++) { + walker.walk(preAst.childAt(i)); + } + } + + function walkThrowStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkPrefixUnaryExpressionChildren(preAst, walker) { + walker.walk(preAst.operand); + } + + function walkPostfixUnaryExpressionChildren(preAst, walker) { + walker.walk(preAst.operand); + } + + function walkDeleteExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkTypeArgumentListChildren(preAst, walker) { + walker.walk(preAst.typeArguments); + } + + function walkTypeOfExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkVoidExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkArgumentListChildren(preAst, walker) { + walker.walk(preAst.typeArgumentList); + walker.walk(preAst.arguments); + } + + function walkArrayLiteralExpressionChildren(preAst, walker) { + walker.walk(preAst.expressions); + } + + function walkSimplePropertyAssignmentChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.expression); + } + + function walkFunctionPropertyAssignmentChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkGetAccessorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.parameterList); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.block); + } + + function walkSeparatedListChildren(preAst, walker) { + for (var i = 0, n = preAst.nonSeparatorCount(); i < n; i++) { + walker.walk(preAst.nonSeparatorAt(i)); + } + } + + function walkSetAccessorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.parameterList); + walker.walk(preAst.block); + } + + function walkObjectLiteralExpressionChildren(preAst, walker) { + walker.walk(preAst.propertyAssignments); + } + + function walkCastExpressionChildren(preAst, walker) { + walker.walk(preAst.type); + walker.walk(preAst.expression); + } + + function walkParenthesizedExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkElementAccessExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentExpression); + } + + function walkMemberAccessExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.name); + } + + function walkQualifiedNameChildren(preAst, walker) { + walker.walk(preAst.left); + walker.walk(preAst.right); + } + + function walkBinaryExpressionChildren(preAst, walker) { + walker.walk(preAst.left); + walker.walk(preAst.right); + } + + function walkEqualsValueClauseChildren(preAst, walker) { + walker.walk(preAst.value); + } + + function walkTypeParameterChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.constraint); + } + + function walkTypeParameterListChildren(preAst, walker) { + walker.walk(preAst.typeParameters); + } + + function walkGenericTypeChildren(preAst, walker) { + walker.walk(preAst.name); + walker.walk(preAst.typeArgumentList); + } + + function walkTypeAnnotationChildren(preAst, walker) { + walker.walk(preAst.type); + } + + function walkTypeQueryChildren(preAst, walker) { + walker.walk(preAst.name); + } + + function walkInvocationExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentList); + } + + function walkObjectCreationExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentList); + } + + function walkTrinaryExpressionChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.whenTrue); + walker.walk(preAst.whenFalse); + } + + function walkFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkFunctionTypeChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.type); + } + + function walkParenthesizedArrowFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + walker.walk(preAst.expression); + } + + function walkSimpleArrowFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.block); + walker.walk(preAst.expression); + } + + function walkMemberFunctionDeclarationChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkFuncDeclChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkIndexMemberDeclarationChildren(preAst, walker) { + walker.walk(preAst.indexSignature); + } + + function walkIndexSignatureChildren(preAst, walker) { + walker.walk(preAst.parameter); + walker.walk(preAst.typeAnnotation); + } + + function walkCallSignatureChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.typeAnnotation); + } + + function walkConstraintChildren(preAst, walker) { + walker.walk(preAst.type); + } + + function walkConstructorDeclarationChildren(preAst, walker) { + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkConstructorTypeChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.type); + } + + function walkConstructSignatureChildren(preAst, walker) { + walker.walk(preAst.callSignature); + } + + function walkParameterChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.equalsValueClause); + } + + function walkParameterListChildren(preAst, walker) { + walker.walk(preAst.parameters); + } + + function walkPropertySignatureChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.typeAnnotation); + } + + function walkVariableDeclaratorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.equalsValueClause); + } + + function walkMemberVariableDeclarationChildren(preAst, walker) { + walker.walk(preAst.variableDeclarator); + } + + function walkMethodSignatureChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + } + + function walkReturnStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkForStatementChildren(preAst, walker) { + walker.walk(preAst.variableDeclaration); + walker.walk(preAst.initializer); + walker.walk(preAst.condition); + walker.walk(preAst.incrementor); + walker.walk(preAst.statement); + } + + function walkForInStatementChildren(preAst, walker) { + walker.walk(preAst.variableDeclaration); + walker.walk(preAst.left); + walker.walk(preAst.expression); + walker.walk(preAst.statement); + } + + function walkIfStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + walker.walk(preAst.elseClause); + } + + function walkElseClauseChildren(preAst, walker) { + walker.walk(preAst.statement); + } + + function walkWhileStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + + function walkDoStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + + function walkBlockChildren(preAst, walker) { + walker.walk(preAst.statements); + } + + function walkVariableDeclarationChildren(preAst, walker) { + walker.walk(preAst.declarators); + } + + function walkCaseSwitchClauseChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.statements); + } + + function walkDefaultSwitchClauseChildren(preAst, walker) { + walker.walk(preAst.statements); + } + + function walkSwitchStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.switchClauses); + } + + function walkTryStatementChildren(preAst, walker) { + walker.walk(preAst.block); + walker.walk(preAst.catchClause); + walker.walk(preAst.finallyClause); + } + + function walkCatchClauseChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.block); + } + + function walkExternalModuleReferenceChildren(preAst, walker) { + walker.walk(preAst.stringLiteral); + } + + function walkFinallyClauseChildren(preAst, walker) { + walker.walk(preAst.block); + } + + function walkClassDeclChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeParameterList); + walker.walk(preAst.heritageClauses); + walker.walk(preAst.classElements); + } + + function walkScriptChildren(preAst, walker) { + walker.walk(preAst.moduleElements); + } + + function walkHeritageClauseChildren(preAst, walker) { + walker.walk(preAst.typeNames); + } + + function walkInterfaceDeclerationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeParameterList); + walker.walk(preAst.heritageClauses); + walker.walk(preAst.body); + } + + function walkObjectTypeChildren(preAst, walker) { + walker.walk(preAst.typeMembers); + } + + function walkArrayTypeChildren(preAst, walker) { + walker.walk(preAst.type); + } + + function walkModuleDeclarationChildren(preAst, walker) { + walker.walk(preAst.name); + walker.walk(preAst.stringLiteral); + walker.walk(preAst.moduleElements); + } + + function walkModuleNameModuleReferenceChildren(preAst, walker) { + walker.walk(preAst.moduleName); + } + + function walkEnumDeclarationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.enumElements); + } + + function walkEnumElementChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.equalsValueClause); + } + + function walkImportDeclarationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.moduleReference); + } + + function walkExportAssignmentChildren(preAst, walker) { + walker.walk(preAst.identifier); + } + + function walkWithStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + + function walkExpressionStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkLabeledStatementChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.statement); + } + + function walkVariableStatementChildren(preAst, walker) { + walker.walk(preAst.declaration); + } + + var childrenWalkers = new Array(246 /* Last */ + 1); + + for (var i = 9 /* FirstToken */, n = 119 /* LastToken */; i <= n; i++) { + childrenWalkers[i] = null; + } + for (var i = 4 /* FirstTrivia */, n = 8 /* LastTrivia */; i <= n; i++) { + childrenWalkers[i] = null; + } + + childrenWalkers[175 /* AddAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[208 /* AddExpression */] = walkBinaryExpressionChildren; + childrenWalkers[180 /* AndAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[60 /* AnyKeyword */] = null; + childrenWalkers[226 /* ArgumentList */] = walkArgumentListChildren; + childrenWalkers[214 /* ArrayLiteralExpression */] = walkArrayLiteralExpressionChildren; + childrenWalkers[124 /* ArrayType */] = walkArrayTypeChildren; + childrenWalkers[219 /* SimpleArrowFunctionExpression */] = walkSimpleArrowFunctionExpressionChildren; + childrenWalkers[218 /* ParenthesizedArrowFunctionExpression */] = walkParenthesizedArrowFunctionExpressionChildren; + childrenWalkers[174 /* AssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[191 /* BitwiseAndExpression */] = walkBinaryExpressionChildren; + childrenWalkers[190 /* BitwiseExclusiveOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[166 /* BitwiseNotExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[189 /* BitwiseOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[146 /* Block */] = walkBlockChildren; + childrenWalkers[61 /* BooleanKeyword */] = null; + childrenWalkers[152 /* BreakStatement */] = null; + childrenWalkers[142 /* CallSignature */] = walkCallSignatureChildren; + childrenWalkers[233 /* CaseSwitchClause */] = walkCaseSwitchClauseChildren; + childrenWalkers[220 /* CastExpression */] = walkCastExpressionChildren; + childrenWalkers[236 /* CatchClause */] = walkCatchClauseChildren; + childrenWalkers[131 /* ClassDeclaration */] = walkClassDeclChildren; + childrenWalkers[173 /* CommaExpression */] = walkBinaryExpressionChildren; + childrenWalkers[186 /* ConditionalExpression */] = walkTrinaryExpressionChildren; + childrenWalkers[239 /* Constraint */] = walkConstraintChildren; + childrenWalkers[137 /* ConstructorDeclaration */] = walkConstructorDeclarationChildren; + childrenWalkers[143 /* ConstructSignature */] = walkConstructSignatureChildren; + childrenWalkers[153 /* ContinueStatement */] = null; + childrenWalkers[125 /* ConstructorType */] = walkConstructorTypeChildren; + childrenWalkers[162 /* DebuggerStatement */] = null; + childrenWalkers[234 /* DefaultSwitchClause */] = walkDefaultSwitchClauseChildren; + childrenWalkers[170 /* DeleteExpression */] = walkDeleteExpressionChildren; + childrenWalkers[178 /* DivideAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[206 /* DivideExpression */] = walkBinaryExpressionChildren; + childrenWalkers[161 /* DoStatement */] = walkDoStatementChildren; + childrenWalkers[221 /* ElementAccessExpression */] = walkElementAccessExpressionChildren; + childrenWalkers[235 /* ElseClause */] = walkElseClauseChildren; + childrenWalkers[156 /* EmptyStatement */] = null; + childrenWalkers[132 /* EnumDeclaration */] = walkEnumDeclarationChildren; + childrenWalkers[243 /* EnumElement */] = walkEnumElementChildren; + childrenWalkers[194 /* EqualsExpression */] = walkBinaryExpressionChildren; + childrenWalkers[232 /* EqualsValueClause */] = walkEqualsValueClauseChildren; + childrenWalkers[192 /* EqualsWithTypeConversionExpression */] = walkBinaryExpressionChildren; + childrenWalkers[181 /* ExclusiveOrAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[134 /* ExportAssignment */] = walkExportAssignmentChildren; + childrenWalkers[149 /* ExpressionStatement */] = walkExpressionStatementChildren; + childrenWalkers[230 /* ExtendsHeritageClause */] = walkHeritageClauseChildren; + childrenWalkers[245 /* ExternalModuleReference */] = walkExternalModuleReferenceChildren; + childrenWalkers[24 /* FalseKeyword */] = null; + childrenWalkers[237 /* FinallyClause */] = walkFinallyClauseChildren; + childrenWalkers[155 /* ForInStatement */] = walkForInStatementChildren; + childrenWalkers[154 /* ForStatement */] = walkForStatementChildren; + childrenWalkers[129 /* FunctionDeclaration */] = walkFuncDeclChildren; + childrenWalkers[222 /* FunctionExpression */] = walkFunctionExpressionChildren; + childrenWalkers[241 /* FunctionPropertyAssignment */] = walkFunctionPropertyAssignmentChildren; + childrenWalkers[123 /* FunctionType */] = walkFunctionTypeChildren; + childrenWalkers[126 /* GenericType */] = walkGenericTypeChildren; + childrenWalkers[139 /* GetAccessor */] = walkGetAccessorChildren; + childrenWalkers[197 /* GreaterThanExpression */] = walkBinaryExpressionChildren; + childrenWalkers[199 /* GreaterThanOrEqualExpression */] = walkBinaryExpressionChildren; + childrenWalkers[147 /* IfStatement */] = walkIfStatementChildren; + childrenWalkers[231 /* ImplementsHeritageClause */] = walkHeritageClauseChildren; + childrenWalkers[133 /* ImportDeclaration */] = walkImportDeclarationChildren; + childrenWalkers[138 /* IndexMemberDeclaration */] = walkIndexMemberDeclarationChildren; + childrenWalkers[144 /* IndexSignature */] = walkIndexSignatureChildren; + childrenWalkers[201 /* InExpression */] = walkBinaryExpressionChildren; + childrenWalkers[200 /* InstanceOfExpression */] = walkBinaryExpressionChildren; + childrenWalkers[128 /* InterfaceDeclaration */] = walkInterfaceDeclerationChildren; + childrenWalkers[213 /* InvocationExpression */] = walkInvocationExpressionChildren; + childrenWalkers[160 /* LabeledStatement */] = walkLabeledStatementChildren; + childrenWalkers[183 /* LeftShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[202 /* LeftShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[196 /* LessThanExpression */] = walkBinaryExpressionChildren; + childrenWalkers[198 /* LessThanOrEqualExpression */] = walkBinaryExpressionChildren; + childrenWalkers[1 /* List */] = walkListChildren; + childrenWalkers[188 /* LogicalAndExpression */] = walkBinaryExpressionChildren; + childrenWalkers[167 /* LogicalNotExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[187 /* LogicalOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[212 /* MemberAccessExpression */] = walkMemberAccessExpressionChildren; + childrenWalkers[135 /* MemberFunctionDeclaration */] = walkMemberFunctionDeclarationChildren; + childrenWalkers[136 /* MemberVariableDeclaration */] = walkMemberVariableDeclarationChildren; + childrenWalkers[145 /* MethodSignature */] = walkMethodSignatureChildren; + childrenWalkers[130 /* ModuleDeclaration */] = walkModuleDeclarationChildren; + childrenWalkers[246 /* ModuleNameModuleReference */] = walkModuleNameModuleReferenceChildren; + childrenWalkers[179 /* ModuloAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[207 /* ModuloExpression */] = walkBinaryExpressionChildren; + childrenWalkers[177 /* MultiplyAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[205 /* MultiplyExpression */] = walkBinaryExpressionChildren; + childrenWalkers[11 /* IdentifierName */] = null; + childrenWalkers[165 /* NegateExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[0 /* None */] = null; + childrenWalkers[195 /* NotEqualsExpression */] = walkBinaryExpressionChildren; + childrenWalkers[193 /* NotEqualsWithTypeConversionExpression */] = walkBinaryExpressionChildren; + childrenWalkers[32 /* NullKeyword */] = null; + childrenWalkers[67 /* NumberKeyword */] = null; + childrenWalkers[13 /* NumericLiteral */] = null; + childrenWalkers[216 /* ObjectCreationExpression */] = walkObjectCreationExpressionChildren; + childrenWalkers[215 /* ObjectLiteralExpression */] = walkObjectLiteralExpressionChildren; + childrenWalkers[122 /* ObjectType */] = walkObjectTypeChildren; + childrenWalkers[223 /* OmittedExpression */] = null; + childrenWalkers[182 /* OrAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[242 /* Parameter */] = walkParameterChildren; + childrenWalkers[227 /* ParameterList */] = walkParameterListChildren; + childrenWalkers[217 /* ParenthesizedExpression */] = walkParenthesizedExpressionChildren; + childrenWalkers[164 /* PlusExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[211 /* PostDecrementExpression */] = walkPostfixUnaryExpressionChildren; + childrenWalkers[210 /* PostIncrementExpression */] = walkPostfixUnaryExpressionChildren; + childrenWalkers[169 /* PreDecrementExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[168 /* PreIncrementExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[141 /* PropertySignature */] = walkPropertySignatureChildren; + childrenWalkers[121 /* QualifiedName */] = walkQualifiedNameChildren; + childrenWalkers[12 /* RegularExpressionLiteral */] = null; + childrenWalkers[150 /* ReturnStatement */] = walkReturnStatementChildren; + childrenWalkers[120 /* SourceUnit */] = walkScriptChildren; + childrenWalkers[2 /* SeparatedList */] = walkSeparatedListChildren; + childrenWalkers[140 /* SetAccessor */] = walkSetAccessorChildren; + childrenWalkers[184 /* SignedRightShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[203 /* SignedRightShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[240 /* SimplePropertyAssignment */] = walkSimplePropertyAssignmentChildren; + childrenWalkers[14 /* StringLiteral */] = null; + childrenWalkers[69 /* StringKeyword */] = null; + childrenWalkers[176 /* SubtractAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[209 /* SubtractExpression */] = walkBinaryExpressionChildren; + childrenWalkers[50 /* SuperKeyword */] = null; + childrenWalkers[151 /* SwitchStatement */] = walkSwitchStatementChildren; + childrenWalkers[35 /* ThisKeyword */] = null; + childrenWalkers[157 /* ThrowStatement */] = walkThrowStatementChildren; + childrenWalkers[3 /* TriviaList */] = null; + childrenWalkers[37 /* TrueKeyword */] = null; + childrenWalkers[159 /* TryStatement */] = walkTryStatementChildren; + childrenWalkers[244 /* TypeAnnotation */] = walkTypeAnnotationChildren; + childrenWalkers[228 /* TypeArgumentList */] = walkTypeArgumentListChildren; + childrenWalkers[171 /* TypeOfExpression */] = walkTypeOfExpressionChildren; + childrenWalkers[238 /* TypeParameter */] = walkTypeParameterChildren; + childrenWalkers[229 /* TypeParameterList */] = walkTypeParameterListChildren; + childrenWalkers[127 /* TypeQuery */] = walkTypeQueryChildren; + childrenWalkers[185 /* UnsignedRightShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[204 /* UnsignedRightShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[224 /* VariableDeclaration */] = walkVariableDeclarationChildren; + childrenWalkers[225 /* VariableDeclarator */] = walkVariableDeclaratorChildren; + childrenWalkers[148 /* VariableStatement */] = walkVariableStatementChildren; + childrenWalkers[172 /* VoidExpression */] = walkVoidExpressionChildren; + childrenWalkers[41 /* VoidKeyword */] = null; + childrenWalkers[158 /* WhileStatement */] = walkWhileStatementChildren; + childrenWalkers[163 /* WithStatement */] = walkWithStatementChildren; + + for (var e in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind.hasOwnProperty(e) && TypeScript.StringUtilities.isString(TypeScript.SyntaxKind[e])) { + TypeScript.Debug.assert(childrenWalkers[e] !== undefined, "Fix initWalkers: " + TypeScript.SyntaxKind[e]); + } + } + + var AstWalkOptions = (function () { + function AstWalkOptions() { + this.goChildren = true; + this.stopWalking = false; + } + return AstWalkOptions; + })(); + TypeScript.AstWalkOptions = AstWalkOptions; + + var SimplePreAstWalker = (function () { + function SimplePreAstWalker(pre, state) { + this.pre = pre; + this.state = state; + this.options = new AstWalkOptions(); + } + SimplePreAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + + this.pre(ast, this.state); + + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + }; + return SimplePreAstWalker; + })(); + + var SimplePrePostAstWalker = (function () { + function SimplePrePostAstWalker(pre, post, state) { + this.pre = pre; + this.post = post; + this.state = state; + this.options = new AstWalkOptions(); + } + SimplePrePostAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + + this.pre(ast, this.state); + + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + + this.post(ast, this.state); + }; + return SimplePrePostAstWalker; + })(); + + var NormalAstWalker = (function () { + function NormalAstWalker(pre, post, state) { + this.pre = pre; + this.post = post; + this.state = state; + this.options = new AstWalkOptions(); + } + NormalAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + + if (this.options.stopWalking) { + return; + } + + this.pre(ast, this); + + if (this.options.stopWalking) { + return; + } + + if (this.options.goChildren) { + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + } else { + this.options.goChildren = true; + } + + if (this.post) { + this.post(ast, this); + } + }; + return NormalAstWalker; + })(); + + var AstWalkerFactory = (function () { + function AstWalkerFactory() { + } + AstWalkerFactory.prototype.walk = function (ast, pre, post, state) { + new NormalAstWalker(pre, post, state).walk(ast); + }; + + AstWalkerFactory.prototype.simpleWalk = function (ast, pre, post, state) { + if (post) { + new SimplePrePostAstWalker(pre, post, state).walk(ast); + } else { + new SimplePreAstWalker(pre, state).walk(ast); + } + }; + return AstWalkerFactory; + })(); + TypeScript.AstWalkerFactory = AstWalkerFactory; + + var globalAstWalkerFactory = new AstWalkerFactory(); + + function getAstWalkerFactory() { + return globalAstWalkerFactory; + } + TypeScript.getAstWalkerFactory = getAstWalkerFactory; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Base64Format = (function () { + function Base64Format() { + } + Base64Format.encode = function (inValue) { + if (inValue < 64) { + return Base64Format.encodedValues.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + }; + + Base64Format.decodeChar = function (inChar) { + if (inChar.length === 1) { + return Base64Format.encodedValues.indexOf(inChar); + } else { + throw TypeError('"' + inChar + '" must have length 1'); + } + }; + Base64Format.encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + return Base64Format; + })(); + + var Base64VLQFormat = (function () { + function Base64VLQFormat() { + } + Base64VLQFormat.encode = function (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 (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(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Base64_value_0_finished_with_a_continuation_bit, [inString])); + }; + return Base64VLQFormat; + })(); + TypeScript.Base64VLQFormat = Base64VLQFormat; +})(TypeScript || (TypeScript = {})); +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 SourceMapEntry = (function () { + function SourceMapEntry(emittedFile, emittedLine, emittedColumn, sourceFile, sourceLine, sourceColumn, sourceName) { + this.emittedFile = emittedFile; + this.emittedLine = emittedLine; + this.emittedColumn = emittedColumn; + this.sourceFile = sourceFile; + this.sourceLine = sourceLine; + this.sourceColumn = sourceColumn; + this.sourceName = sourceName; + TypeScript.Debug.assert(isFinite(emittedLine)); + TypeScript.Debug.assert(isFinite(emittedColumn)); + TypeScript.Debug.assert(isFinite(sourceColumn)); + TypeScript.Debug.assert(isFinite(sourceLine)); + } + return SourceMapEntry; + })(); + TypeScript.SourceMapEntry = SourceMapEntry; + + var SourceMapper = (function () { + function SourceMapper(jsFile, sourceMapOut, document, jsFilePath, emitOptions, resolvePath) { + this.jsFile = jsFile; + this.sourceMapOut = sourceMapOut; + this.names = []; + this.mappingLevel = []; + this.tsFilePaths = []; + this.allSourceMappings = []; + this.sourceMapEntries = []; + this.setSourceMapOptions(document, jsFilePath, emitOptions, resolvePath); + this.setNewSourceFile(document, emitOptions); + } + SourceMapper.prototype.getOutputFile = function () { + var result = this.sourceMapOut.getOutputFile(); + result.sourceMapEntries = this.sourceMapEntries; + + return result; + }; + + SourceMapper.prototype.increaseMappingLevel = function (ast) { + this.mappingLevel.push(ast); + }; + + SourceMapper.prototype.decreaseMappingLevel = function (ast) { + TypeScript.Debug.assert(this.mappingLevel.length > 0, "Mapping level should never be less than 0. This suggests a missing start call."); + var expectedAst = this.mappingLevel.pop(); + var expectedAstInfo = expectedAst.kind ? TypeScript.SyntaxKind[expectedAst.kind()] : [expectedAst.start(), expectedAst.end()]; + var astInfo = ast.kind ? TypeScript.SyntaxKind[ast.kind()] : [ast.start(), ast.end()]; + TypeScript.Debug.assert(ast === expectedAst, "Provided ast is not the expected AST, Expected: " + expectedAstInfo + " Given: " + astInfo); + }; + + SourceMapper.prototype.setNewSourceFile = function (document, emitOptions) { + var sourceMappings = []; + this.allSourceMappings.push(sourceMappings); + this.currentMappings = [sourceMappings]; + this.currentNameIndex = []; + + this.setNewSourceFilePath(document, emitOptions); + }; + + SourceMapper.prototype.setSourceMapOptions = function (document, jsFilePath, emitOptions, resolvePath) { + var prettyJsFileName = TypeScript.getPrettyName(jsFilePath, false, true); + var prettyMapFileName = prettyJsFileName + SourceMapper.MapFileExtension; + this.jsFileName = prettyJsFileName; + + if (emitOptions.sourceMapRootDirectory()) { + this.sourceMapDirectory = emitOptions.sourceMapRootDirectory(); + if (document.emitToOwnOutputFile()) { + this.sourceMapDirectory = this.sourceMapDirectory + TypeScript.switchToForwardSlashes(TypeScript.getRootFilePath((document.fileName)).replace(emitOptions.commonDirectoryPath(), "")); + } + + if (TypeScript.isRelative(this.sourceMapDirectory)) { + this.sourceMapDirectory = emitOptions.commonDirectoryPath() + this.sourceMapDirectory; + this.sourceMapDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(resolvePath(this.sourceMapDirectory))); + this.sourceMapPath = TypeScript.getRelativePathToFixedPath(TypeScript.getRootFilePath(jsFilePath), this.sourceMapDirectory + prettyMapFileName); + } else { + this.sourceMapPath = this.sourceMapDirectory + prettyMapFileName; + } + } else { + this.sourceMapPath = prettyMapFileName; + this.sourceMapDirectory = TypeScript.getRootFilePath(jsFilePath); + } + this.sourceRoot = emitOptions.sourceRootDirectory(); + }; + + SourceMapper.prototype.setNewSourceFilePath = function (document, emitOptions) { + var tsFilePath = TypeScript.switchToForwardSlashes(document.fileName); + if (emitOptions.sourceRootDirectory()) { + tsFilePath = TypeScript.getRelativePathToFixedPath(emitOptions.commonDirectoryPath(), tsFilePath); + } else { + tsFilePath = TypeScript.getRelativePathToFixedPath(this.sourceMapDirectory, tsFilePath); + } + this.tsFilePaths.push(tsFilePath); + }; + + SourceMapper.prototype.emitSourceMapping = function () { + var _this = this; + TypeScript.Debug.assert(this.mappingLevel.length === 0, "Mapping level is not 0. This suggest a missing end call. Value: " + this.mappingLevel.map(function (item) { + return ['Node of type', TypeScript.SyntaxKind[item.kind()], 'at', item.start(), 'to', item.end()].join(' '); + }).join(', ')); + + this.jsFile.WriteLine("//# sourceMappingURL=" + this.sourceMapPath); + + var mappingsString = ""; + + var prevEmittedColumn = 0; + var prevEmittedLine = 0; + var prevSourceColumn = 0; + var prevSourceLine = 0; + var prevSourceIndex = 0; + var prevNameIndex = 0; + var emitComma = false; + + var recordedPosition = null; + for (var sourceIndex = 0; sourceIndex < this.tsFilePaths.length; sourceIndex++) { + 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 + ","; + } + + _this.sourceMapEntries.push(new SourceMapEntry(_this.jsFileName, mappedPosition.emittedLine + 1, mappedPosition.emittedColumn + 1, _this.tsFilePaths[sourceIndex], mappedPosition.sourceLine, mappedPosition.sourceColumn + 1, nameIndex >= 0 ? _this.names[nameIndex] : undefined)); + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.emittedColumn - prevEmittedColumn); + prevEmittedColumn = mappedPosition.emittedColumn; + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(sourceIndex - prevSourceIndex); + prevSourceIndex = sourceIndex; + + 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(nameIndex - prevNameIndex); + prevNameIndex = 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(this.allSourceMappings[sourceIndex]); + } + + this.sourceMapOut.Write(JSON.stringify({ + version: 3, + file: this.jsFileName, + sourceRoot: this.sourceRoot, + sources: this.tsFilePaths, + names: this.names, + mappings: mappingsString + })); + + this.sourceMapOut.Close(); + }; + SourceMapper.MapFileExtension = ".map"; + return SourceMapper; + })(); + TypeScript.SourceMapper = SourceMapper; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (EmitContainer) { + EmitContainer[EmitContainer["Prog"] = 0] = "Prog"; + EmitContainer[EmitContainer["Module"] = 1] = "Module"; + EmitContainer[EmitContainer["DynamicModule"] = 2] = "DynamicModule"; + EmitContainer[EmitContainer["Class"] = 3] = "Class"; + EmitContainer[EmitContainer["Constructor"] = 4] = "Constructor"; + EmitContainer[EmitContainer["Function"] = 5] = "Function"; + EmitContainer[EmitContainer["Args"] = 6] = "Args"; + EmitContainer[EmitContainer["Interface"] = 7] = "Interface"; + })(TypeScript.EmitContainer || (TypeScript.EmitContainer = {})); + var EmitContainer = TypeScript.EmitContainer; + + var EmitState = (function () { + function EmitState() { + this.column = 0; + this.line = 0; + this.container = 0 /* Prog */; + } + return EmitState; + })(); + TypeScript.EmitState = EmitState; + + var EmitOptions = (function () { + function EmitOptions(compiler, resolvePath) { + this.resolvePath = resolvePath; + this._diagnostic = null; + this._settings = null; + this._commonDirectoryPath = ""; + this._sharedOutputFile = ""; + this._sourceRootDirectory = ""; + this._sourceMapRootDirectory = ""; + this._outputDirectory = ""; + var settings = compiler.compilationSettings(); + this._settings = settings; + + if (settings.moduleGenTarget() === 0 /* Unspecified */) { + var fileNames = compiler.fileNames(); + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = compiler.getDocument(fileNames[i]); + if (!document.isDeclareFile() && document.isExternalModule()) { + var errorSpan = document.externalModuleIndicatorSpan(); + this._diagnostic = new TypeScript.Diagnostic(document.fileName, document.lineMap(), errorSpan.start(), errorSpan.length(), TypeScript.DiagnosticCode.Cannot_compile_external_modules_unless_the_module_flag_is_provided); + + return; + } + } + } + + if (!settings.mapSourceFiles()) { + if (settings.mapRoot()) { + if (settings.sourceRoot()) { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Options_mapRoot_and_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option, null); + return; + } else { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option, null); + return; + } + } else if (settings.sourceRoot()) { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option, null); + return; + } + } + + this._sourceMapRootDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(settings.mapRoot())); + this._sourceRootDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(settings.sourceRoot())); + + if (settings.outFileOption() || settings.outDirOption() || settings.mapRoot() || settings.sourceRoot()) { + if (settings.outFileOption()) { + this._sharedOutputFile = TypeScript.switchToForwardSlashes(resolvePath(settings.outFileOption())); + } + + if (settings.outDirOption()) { + this._outputDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(resolvePath(settings.outDirOption()))); + } + + if (this._outputDirectory || this._sourceMapRootDirectory || this.sourceRootDirectory) { + this.determineCommonDirectoryPath(compiler); + } + } + } + EmitOptions.prototype.diagnostic = function () { + return this._diagnostic; + }; + + EmitOptions.prototype.commonDirectoryPath = function () { + return this._commonDirectoryPath; + }; + EmitOptions.prototype.sharedOutputFile = function () { + return this._sharedOutputFile; + }; + EmitOptions.prototype.sourceRootDirectory = function () { + return this._sourceRootDirectory; + }; + EmitOptions.prototype.sourceMapRootDirectory = function () { + return this._sourceMapRootDirectory; + }; + EmitOptions.prototype.outputDirectory = function () { + return this._outputDirectory; + }; + + EmitOptions.prototype.compilationSettings = function () { + return this._settings; + }; + + EmitOptions.prototype.determineCommonDirectoryPath = function (compiler) { + var commonComponents = []; + var commonComponentsLength = -1; + + var fileNames = compiler.fileNames(); + for (var i = 0, len = fileNames.length; i < len; i++) { + var fileName = fileNames[i]; + var document = compiler.getDocument(fileNames[i]); + var sourceUnit = document.sourceUnit(); + + if (!document.isDeclareFile()) { + 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) { + var isDynamicModuleCompilation = TypeScript.ArrayUtilities.any(fileNames, function (fileName) { + document = compiler.getDocument(fileName); + return !document.isDeclareFile() && document.isExternalModule(); + }); + + if (this._outputDirectory || this._sourceRootDirectory || (this._sourceMapRootDirectory && (!this._sharedOutputFile || isDynamicModuleCompilation))) { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Cannot_find_the_common_subdirectory_path_for_the_input_files, null); + return; + } + + return; + } + + break; + } + } + + if (!updatedPath && fileComponents.length < commonComponentsLength) { + commonComponentsLength = fileComponents.length; + } + } + } + } + + this._commonDirectoryPath = commonComponents.slice(0, commonComponentsLength).join("/") + "/"; + }; + return EmitOptions; + })(); + TypeScript.EmitOptions = EmitOptions; + + var Indenter = (function () { + function Indenter() { + this.indentAmt = 0; + } + 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; + }; + Indenter.indentStep = 4; + Indenter.indentStepString = " "; + Indenter.indentStrings = []; + return Indenter; + })(); + TypeScript.Indenter = Indenter; + + function lastParameterIsRest(parameterList) { + var parameters = parameterList.parameters; + return parameters.nonSeparatorCount() > 0 && parameters.nonSeparatorAt(parameters.nonSeparatorCount() - 1).dotDotDotToken !== null; + } + TypeScript.lastParameterIsRest = lastParameterIsRest; + + var Emitter = (function () { + function Emitter(emittingFileName, outfile, emitOptions, semanticInfoChain) { + this.emittingFileName = emittingFileName; + this.outfile = outfile; + this.emitOptions = emitOptions; + this.semanticInfoChain = semanticInfoChain; + this.globalThisCapturePrologueEmitted = false; + this.extendsPrologueEmitted = false; + this.thisClassNode = null; + this.inArrowFunction = false; + this.moduleName = ""; + this.emitState = new EmitState(); + this.indenter = new Indenter(); + this.sourceMapper = null; + this.captureThisStmtString = "var _this = this;"; + this.declStack = []; + this.exportAssignment = null; + this.inWithBlock = false; + this.document = null; + this.detachedCommentsElement = null; + } + Emitter.prototype.pushDecl = function (decl) { + if (decl) { + this.declStack[this.declStack.length] = decl; + } + }; + + Emitter.prototype.popDecl = function (decl) { + if (decl) { + this.declStack.length--; + } + }; + + Emitter.prototype.getEnclosingDecl = function () { + var declStackLen = this.declStack.length; + var enclosingDecl = declStackLen > 0 ? this.declStack[declStackLen - 1] : null; + return enclosingDecl; + }; + + Emitter.prototype.setExportAssignment = function (exportAssignment) { + this.exportAssignment = exportAssignment; + }; + + Emitter.prototype.getExportAssignment = function () { + return this.exportAssignment; + }; + + Emitter.prototype.setDocument = function (document) { + this.document = document; + }; + + Emitter.prototype.shouldEmitImportDeclaration = function (importDeclAST) { + var isExternalModuleReference = importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */; + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); + var isExported = TypeScript.hasFlag(importDecl.flags, 1 /* Exported */); + var isAmdCodeGen = this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */; + + if (isExternalModuleReference && !isExported && isAmdCodeGen) { + return false; + } + + var importSymbol = importDecl.getSymbol(); + if (importSymbol.isUsedAsValue()) { + return true; + } + + if (importDeclAST.moduleReference.kind() !== 245 /* ExternalModuleReference */) { + var canBeUsedExternally = isExported || importSymbol.typeUsedExternally() || importSymbol.isUsedInExportedAlias(); + if (!canBeUsedExternally && !this.document.isExternalModule()) { + canBeUsedExternally = TypeScript.hasFlag(importDecl.getParentDecl().kind, 1 /* Script */ | 32 /* DynamicModule */); + } + + if (canBeUsedExternally) { + if (importSymbol.getExportAssignedValueSymbol()) { + return true; + } + + var containerSymbol = importSymbol.getExportAssignedContainerSymbol(); + if (containerSymbol && containerSymbol.getInstanceSymbol()) { + return true; + } + } + } + + return false; + }; + + Emitter.prototype.emitImportDeclaration = function (importDeclAST) { + var isExternalModuleReference = importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */; + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); + var isExported = TypeScript.hasFlag(importDecl.flags, 1 /* Exported */); + var isAmdCodeGen = this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */; + + this.emitComments(importDeclAST, true); + + var importSymbol = importDecl.getSymbol(); + + var parentSymbol = importSymbol.getContainer(); + var parentKind = parentSymbol ? parentSymbol.kind : 0 /* None */; + var associatedParentSymbol = parentSymbol ? parentSymbol.getAssociatedContainerType() : null; + var associatedParentSymbolKind = associatedParentSymbol ? associatedParentSymbol.kind : 0 /* None */; + + var needsPropertyAssignment = false; + var usePropertyAssignmentInsteadOfVarDecl = false; + var moduleNamePrefix; + + if (isExported && (parentKind === 4 /* Container */ || parentKind === 32 /* DynamicModule */ || associatedParentSymbolKind === 4 /* Container */ || associatedParentSymbolKind === 32 /* DynamicModule */)) { + if (importSymbol.getExportAssignedTypeSymbol() || importSymbol.getExportAssignedContainerSymbol()) { + needsPropertyAssignment = true; + } else { + var valueSymbol = importSymbol.getExportAssignedValueSymbol(); + if (valueSymbol && (valueSymbol.kind === 65536 /* Method */ || valueSymbol.kind === 16384 /* Function */)) { + needsPropertyAssignment = true; + } else { + usePropertyAssignmentInsteadOfVarDecl = true; + } + } + + if (this.emitState.container === 2 /* DynamicModule */) { + moduleNamePrefix = "exports."; + } else { + moduleNamePrefix = this.moduleName + "."; + } + } + + if (isAmdCodeGen && isExternalModuleReference) { + needsPropertyAssignment = true; + } else { + this.recordSourceMappingStart(importDeclAST); + if (usePropertyAssignmentInsteadOfVarDecl) { + this.writeToOutput(moduleNamePrefix); + } else { + this.writeToOutput("var "); + } + this.writeToOutput(importDeclAST.identifier.text() + " = "); + var aliasAST = importDeclAST.moduleReference; + + if (isExternalModuleReference) { + this.writeToOutput("require(" + aliasAST.stringLiteral.text() + ")"); + } else { + this.emitJavascript(aliasAST.moduleName, false); + } + + this.recordSourceMappingEnd(importDeclAST); + this.writeToOutput(";"); + + if (needsPropertyAssignment) { + this.writeLineToOutput(""); + this.emitIndent(); + } + } + + if (needsPropertyAssignment) { + this.writeToOutputWithSourceMapRecord(moduleNamePrefix + importDeclAST.identifier.text() + " = " + importDeclAST.identifier.text(), importDeclAST); + this.writeToOutput(";"); + } + this.emitComments(importDeclAST, false); + }; + + Emitter.prototype.createSourceMapper = function (document, jsFileName, jsFile, sourceMapOut, resolvePath) { + this.sourceMapper = new TypeScript.SourceMapper(jsFile, sourceMapOut, document, jsFileName, this.emitOptions, resolvePath); + }; + + Emitter.prototype.setSourceMapperNewSourceFile = function (document) { + this.sourceMapper.setNewSourceFile(document, this.emitOptions); + }; + + Emitter.prototype.updateLineAndColumn = function (s) { + var lineNumbers = TypeScript.TextUtilities.parseLineStarts(s); + if (lineNumbers.length > 1) { + this.emitState.line += lineNumbers.length - 1; + this.emitState.column = s.length - lineNumbers[lineNumbers.length - 1]; + } else { + this.emitState.column += s.length; + } + }; + + Emitter.prototype.writeToOutputWithSourceMapRecord = function (s, astSpan) { + this.recordSourceMappingStart(astSpan); + this.writeToOutput(s); + this.recordSourceMappingEnd(astSpan); + }; + + Emitter.prototype.writeToOutput = function (s) { + this.outfile.Write(s); + this.updateLineAndColumn(s); + }; + + Emitter.prototype.writeLineToOutput = function (s, force) { + if (typeof force === "undefined") { force = false; } + if (!force && s === "" && this.emitState.column === 0) { + return; + } + + this.outfile.WriteLine(s); + this.updateLineAndColumn(s); + this.emitState.column = 0; + this.emitState.line++; + }; + + Emitter.prototype.writeCaptureThisStatement = function (ast) { + this.emitIndent(); + this.writeToOutputWithSourceMapRecord(this.captureThisStmtString, ast); + this.writeLineToOutput(""); + }; + + Emitter.prototype.setContainer = function (c) { + var temp = this.emitState.container; + this.emitState.container = c; + return temp; + }; + + Emitter.prototype.getIndentString = function () { + return this.indenter.getIndent(); + }; + + Emitter.prototype.emitIndent = function () { + this.writeToOutput(this.getIndentString()); + }; + + Emitter.prototype.emitComment = function (comment, trailing, first) { + if (this.emitOptions.compilationSettings().removeComments()) { + return; + } + + var text = getTrimmedTextLines(comment); + var emitColumn = this.emitState.column; + + if (emitColumn === 0) { + this.emitIndent(); + } else if (trailing && first) { + this.writeToOutput(" "); + } + + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + 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(""); + } else { + this.recordSourceMappingEnd(comment); + this.writeToOutput(" "); + return; + } + } else { + this.recordSourceMappingStart(comment); + this.writeToOutput(text[0]); + this.recordSourceMappingEnd(comment); + this.writeLineToOutput(""); + } + + if (!trailing && emitColumn !== 0) { + this.emitIndent(); + } + }; + + Emitter.prototype.emitComments = function (ast, pre, onlyPinnedOrTripleSlashComments) { + var _this = this; + if (typeof onlyPinnedOrTripleSlashComments === "undefined") { onlyPinnedOrTripleSlashComments = false; } + if (ast && ast.kind() !== 146 /* Block */) { + if (ast.parent.kind() === 219 /* SimpleArrowFunctionExpression */ || ast.parent.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { + return; + } + } + + if (pre) { + var preComments = ast.preComments(); + + if (preComments && ast === this.detachedCommentsElement) { + var detachedComments = this.getDetachedComments(ast); + preComments = preComments.slice(detachedComments.length); + this.detachedCommentsElement = null; + } + + if (preComments && onlyPinnedOrTripleSlashComments) { + preComments = TypeScript.ArrayUtilities.where(preComments, function (c) { + return _this.isPinnedOrTripleSlash(c); + }); + } + + this.emitCommentsArray(preComments, false); + } else { + this.emitCommentsArray(ast.postComments(), true); + } + }; + + Emitter.prototype.isPinnedOrTripleSlash = function (comment) { + var fullText = comment.fullText(); + if (fullText.match(TypeScript.tripleSlashReferenceRegExp)) { + return true; + } else { + return fullText.indexOf("/*!") === 0; + } + }; + + Emitter.prototype.emitCommentsArray = function (comments, trailing) { + if (!this.emitOptions.compilationSettings().removeComments() && comments) { + for (var i = 0, n = comments.length; i < n; i++) { + this.emitComment(comments[i], trailing, i === 0); + } + } + }; + + Emitter.prototype.emitObjectLiteralExpression = function (objectLiteral) { + this.recordSourceMappingStart(objectLiteral); + + this.writeToOutput("{"); + this.emitCommaSeparatedList(objectLiteral, objectLiteral.propertyAssignments, " ", true); + this.writeToOutput("}"); + + this.recordSourceMappingEnd(objectLiteral); + }; + + Emitter.prototype.emitArrayLiteralExpression = function (arrayLiteral) { + this.recordSourceMappingStart(arrayLiteral); + + this.writeToOutput("["); + this.emitCommaSeparatedList(arrayLiteral, arrayLiteral.expressions, "", true); + this.writeToOutput("]"); + + this.recordSourceMappingEnd(arrayLiteral); + }; + + Emitter.prototype.emitObjectCreationExpression = function (objectCreationExpression) { + this.recordSourceMappingStart(objectCreationExpression); + this.writeToOutput("new "); + var target = objectCreationExpression.expression; + + this.emit(target); + if (objectCreationExpression.argumentList) { + this.recordSourceMappingStart(objectCreationExpression.argumentList); + this.writeToOutput("("); + this.emitCommaSeparatedList(objectCreationExpression.argumentList, objectCreationExpression.argumentList.arguments, "", false); + this.writeToOutputWithSourceMapRecord(")", objectCreationExpression.argumentList.closeParenToken); + this.recordSourceMappingEnd(objectCreationExpression.argumentList); + } + + this.recordSourceMappingEnd(objectCreationExpression); + }; + + Emitter.prototype.getConstantDecl = function (dotExpr) { + var pullSymbol = this.semanticInfoChain.getSymbolForAST(dotExpr); + if (pullSymbol && pullSymbol.kind === 67108864 /* EnumMember */) { + var pullDecls = pullSymbol.getDeclarations(); + if (pullDecls.length === 1) { + var pullDecl = pullDecls[0]; + if (pullDecl.kind === 67108864 /* EnumMember */) { + return pullDecl; + } + } + } + + return null; + }; + + Emitter.prototype.tryEmitConstant = function (dotExpr) { + var propertyName = dotExpr.name; + var boundDecl = this.getConstantDecl(dotExpr); + if (boundDecl) { + var value = boundDecl.constantValue; + if (value !== null) { + this.recordSourceMappingStart(dotExpr); + this.writeToOutput(value.toString()); + var comment = " /* "; + comment += propertyName.text(); + comment += " */"; + this.writeToOutput(comment); + this.recordSourceMappingEnd(dotExpr); + return true; + } + } + + return false; + }; + + Emitter.prototype.emitInvocationExpression = function (callNode) { + this.recordSourceMappingStart(callNode); + var target = callNode.expression; + var args = callNode.argumentList.arguments; + + if (target.kind() === 212 /* MemberAccessExpression */ && target.expression.kind() === 50 /* SuperKeyword */) { + this.emit(target); + this.writeToOutput(".call"); + this.recordSourceMappingStart(args); + this.writeToOutput("("); + this.emitThis(); + if (args && args.nonSeparatorCount() > 0) { + this.writeToOutput(", "); + this.emitCommaSeparatedList(callNode.argumentList, args, "", false); + } + } else { + if (callNode.expression.kind() === 50 /* SuperKeyword */ && this.emitState.container === 4 /* Constructor */) { + this.writeToOutput("_super.call"); + } else { + this.emitJavascript(target, false); + } + this.recordSourceMappingStart(args); + this.writeToOutput("("); + if (callNode.expression.kind() === 50 /* SuperKeyword */ && this.emitState.container === 4 /* Constructor */) { + this.writeToOutput("this"); + if (args && args.nonSeparatorCount() > 0) { + this.writeToOutput(", "); + } + } + this.emitCommaSeparatedList(callNode.argumentList, args, "", false); + } + + this.writeToOutputWithSourceMapRecord(")", callNode.argumentList.closeParenToken); + this.recordSourceMappingEnd(args); + this.recordSourceMappingEnd(callNode); + }; + + Emitter.prototype.emitParameterList = function (list) { + this.writeToOutput("("); + this.emitCommentsArray(list.openParenTrailingComments, true); + this.emitFunctionParameters(TypeScript.ASTHelpers.parametersFromParameterList(list)); + this.writeToOutput(")"); + }; + + Emitter.prototype.emitFunctionParameters = function (parameters) { + var argsLen = 0; + + if (parameters) { + this.emitComments(parameters.ast, true); + + var tempContainer = this.setContainer(6 /* Args */); + argsLen = parameters.length; + var printLen = argsLen; + if (parameters.lastParameterIsRest()) { + printLen--; + } + for (var i = 0; i < printLen; i++) { + var arg = parameters.astAt(i); + this.emit(arg); + + if (i < (printLen - 1)) { + this.writeToOutput(", "); + } + } + this.setContainer(tempContainer); + + this.emitComments(parameters.ast, false); + } + }; + + Emitter.prototype.emitFunctionBodyStatements = function (name, funcDecl, parameterList, block, bodyExpression) { + this.writeLineToOutput(" {"); + if (name) { + this.recordSourceMappingNameStart(name); + } + + this.indenter.increaseIndent(); + + if (block) { + this.emitDetachedComments(block.statements); + } + + if (this.shouldCaptureThis(funcDecl)) { + this.writeCaptureThisStatement(funcDecl); + } + + if (parameterList) { + this.emitDefaultValueAssignments(parameterList); + this.emitRestParameterInitializer(parameterList); + } + + if (block) { + this.emitList(block.statements); + this.emitCommentsArray(block.closeBraceLeadingComments, false); + } else { + this.emitIndent(); + this.emitCommentsArray(bodyExpression.preComments(), false); + this.writeToOutput("return "); + this.emit(bodyExpression); + this.writeLineToOutput(";"); + this.emitCommentsArray(bodyExpression.postComments(), true); + } + + this.indenter.decreaseIndent(); + this.emitIndent(); + + if (block) { + this.writeToOutputWithSourceMapRecord("}", block.closeBraceToken); + } else { + this.writeToOutputWithSourceMapRecord("}", bodyExpression); + } + + if (name) { + this.recordSourceMappingNameEnd(); + } + }; + + Emitter.prototype.emitDefaultValueAssignments = function (parameters) { + var n = parameters.length; + if (parameters.lastParameterIsRest()) { + n--; + } + + for (var i = 0; i < n; i++) { + var arg = parameters.astAt(i); + var id = parameters.identifierAt(i); + var equalsValueClause = parameters.initializerAt(i); + if (equalsValueClause) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.writeToOutput("if (typeof " + id.text() + " === \"undefined\") { "); + this.writeToOutputWithSourceMapRecord(id.text(), id); + this.emitJavascript(equalsValueClause, false); + this.writeLineToOutput("; }"); + this.recordSourceMappingEnd(arg); + } + } + }; + + Emitter.prototype.emitRestParameterInitializer = function (parameters) { + if (parameters.lastParameterIsRest()) { + var n = parameters.length; + var lastArg = parameters.astAt(n - 1); + var id = parameters.identifierAt(n - 1); + this.emitIndent(); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var "); + this.writeToOutputWithSourceMapRecord(id.text(), id); + this.writeLineToOutput(" = [];"); + this.recordSourceMappingEnd(lastArg); + this.emitIndent(); + this.writeToOutput("for ("); + this.writeToOutputWithSourceMapRecord("var _i = 0;", lastArg); + this.writeToOutput(" "); + this.writeToOutputWithSourceMapRecord("_i < (arguments.length - " + (n - 1) + ")", lastArg); + this.writeToOutput("; "); + this.writeToOutputWithSourceMapRecord("_i++", lastArg); + this.writeLineToOutput(") {"); + this.indenter.increaseIndent(); + this.emitIndent(); + + this.writeToOutputWithSourceMapRecord(id.text() + "[_i] = arguments[_i + " + (n - 1) + "];", lastArg); + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + } + }; + + Emitter.prototype.getImportDecls = function (fileName) { + var topLevelDecl = this.semanticInfoChain.topLevelDecl(this.document.fileName); + var result = []; + + var dynamicModuleDecl = topLevelDecl.getChildDecls()[0]; + var queue = dynamicModuleDecl.getChildDecls(); + + for (var i = 0, n = queue.length; i < n; i++) { + var decl = queue[i]; + + if (decl.kind & 128 /* TypeAlias */) { + var importStatementAST = this.semanticInfoChain.getASTForDecl(decl); + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + var symbol = decl.getSymbol(); + var typeSymbol = symbol && symbol.type; + if (typeSymbol && typeSymbol !== this.semanticInfoChain.anyTypeSymbol && !typeSymbol.isError()) { + result.push(decl); + } + } + } + } + + return result; + }; + + Emitter.prototype.getModuleImportAndDependencyList = function (sourceUnit) { + var importList = ""; + var dependencyList = ""; + + var importDecls = this.getImportDecls(this.document.fileName); + + if (importDecls.length) { + for (var i = 0; i < importDecls.length; i++) { + var importStatementDecl = importDecls[i]; + var importStatementSymbol = importStatementDecl.getSymbol(); + var importStatementAST = this.semanticInfoChain.getASTForDecl(importStatementDecl); + + if (importStatementSymbol.isUsedAsValue()) { + if (i <= importDecls.length - 1) { + dependencyList += ", "; + importList += ", "; + } + + importList += importStatementDecl.name; + dependencyList += importStatementAST.moduleReference.stringLiteral.text(); + } + } + } + + var amdDependencies = this.document.amdDependencies(); + for (var i = 0; i < amdDependencies.length; i++) { + dependencyList += ", \"" + amdDependencies[i] + "\""; + } + + return { + importList: importList, + dependencyList: dependencyList + }; + }; + + Emitter.prototype.shouldCaptureThis = function (ast) { + if (ast.kind() === 120 /* SourceUnit */) { + var scriptDecl = this.semanticInfoChain.topLevelDecl(this.document.fileName); + return TypeScript.hasFlag(scriptDecl.flags, 262144 /* MustCaptureThis */); + } + + var decl = this.semanticInfoChain.getDeclForAST(ast); + if (decl) { + return TypeScript.hasFlag(decl.flags, 262144 /* MustCaptureThis */); + } + + return false; + }; + + Emitter.prototype.emitEnum = function (moduleDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(moduleDecl); + this.pushDecl(pullDecl); + + var svModuleName = this.moduleName; + this.moduleName = moduleDecl.identifier.text(); + + var temp = this.setContainer(1 /* Module */); + var isExported = TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */); + + if (!isExported) { + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("var "); + this.recordSourceMappingStart(moduleDecl.identifier); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.identifier); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(moduleDecl); + this.emitIndent(); + } + + this.writeToOutput("("); + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("function ("); + this.writeToOutputWithSourceMapRecord(this.moduleName, moduleDecl.identifier); + this.writeLineToOutput(") {"); + + this.recordSourceMappingNameStart(this.moduleName); + + this.indenter.increaseIndent(); + + if (this.shouldCaptureThis(moduleDecl)) { + this.writeCaptureThisStatement(moduleDecl); + } + + this.emitSeparatedList(moduleDecl.enumElements); + this.indenter.decreaseIndent(); + this.emitIndent(); + + var parentIsDynamic = temp === 2 /* DynamicModule */; + if (temp === 0 /* Prog */ && isExported) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); + } else if (isExported || temp === 0 /* Prog */) { + var dotMod = svModuleName !== "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); + } else if (!isExported && temp !== 0 /* Prog */) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); + } else { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")();"); + } + + this.recordSourceMappingEnd(moduleDecl); + if (temp !== 0 /* Prog */ && isExported) { + this.recordSourceMappingStart(moduleDecl); + if (parentIsDynamic) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); + } else { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); + } + this.recordSourceMappingEnd(moduleDecl); + } + + this.setContainer(temp); + this.moduleName = svModuleName; + + this.popDecl(pullDecl); + }; + + Emitter.prototype.getModuleDeclToVerifyChildNameCollision = function (moduleDecl, changeNameIfAnyDeclarationInContext) { + if (TypeScript.ArrayUtilities.contains(this.declStack, moduleDecl)) { + return moduleDecl; + } else if (changeNameIfAnyDeclarationInContext) { + var symbol = moduleDecl.getSymbol(); + if (symbol) { + var otherDecls = symbol.getDeclarations(); + for (var i = 0; i < otherDecls.length; i++) { + if (TypeScript.ArrayUtilities.contains(this.declStack, otherDecls[i])) { + return otherDecls[i]; + } + } + } + } + + return null; + }; + + Emitter.prototype.hasChildNameCollision = function (moduleName, parentDecl) { + var _this = this; + var childDecls = parentDecl.getChildDecls(); + return TypeScript.ArrayUtilities.any(childDecls, function (childDecl) { + var childAST = _this.semanticInfoChain.getASTForDecl(childDecl); + + if (childDecl.kind != 67108864 /* EnumMember */ && _this.shouldEmit(childAST)) { + if (childDecl.name === moduleName) { + if (parentDecl.kind != 8 /* Class */) { + return true; + } + + if (!(childDecl.kind == 65536 /* Method */ || childDecl.kind == 4096 /* Property */ || childDecl.kind == 524288 /* SetAccessor */ || childDecl.kind == 262144 /* GetAccessor */)) { + return true; + } + } + + if (_this.hasChildNameCollision(moduleName, childDecl)) { + return true; + } + } + return false; + }); + }; + + Emitter.prototype.getModuleName = function (moduleDecl, changeNameIfAnyDeclarationInContext) { + var moduleName = moduleDecl.name; + var moduleDisplayName = moduleDecl.getDisplayName(); + + moduleDecl = this.getModuleDeclToVerifyChildNameCollision(moduleDecl, changeNameIfAnyDeclarationInContext); + if (moduleDecl && moduleDecl.kind != 64 /* Enum */) { + while (this.hasChildNameCollision(moduleName, moduleDecl)) { + moduleName = "_" + moduleName; + moduleDisplayName = "_" + moduleDisplayName; + } + } + + return moduleDisplayName; + }; + + Emitter.prototype.emitModuleDeclarationWorker = function (moduleDecl) { + if (moduleDecl.stringLiteral) { + this.emitSingleModuleDeclaration(moduleDecl, moduleDecl.stringLiteral); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDecl.name); + this.emitSingleModuleDeclaration(moduleDecl, moduleNames[0]); + } + }; + + Emitter.prototype.emitSingleModuleDeclaration = function (moduleDecl, moduleName) { + var isLastName = TypeScript.ASTHelpers.isLastNameOfModule(moduleDecl, moduleName); + + if (isLastName) { + this.emitComments(moduleDecl, true); + } + + var pullDecl = this.semanticInfoChain.getDeclForAST(moduleName); + this.pushDecl(pullDecl); + + var svModuleName = this.moduleName; + + if (moduleDecl.stringLiteral) { + this.moduleName = moduleDecl.stringLiteral.valueText(); + if (TypeScript.isTSFile(this.moduleName)) { + this.moduleName = this.moduleName.substring(0, this.moduleName.length - ".ts".length); + } + } else { + this.moduleName = moduleName.text(); + } + + var temp = this.setContainer(1 /* Module */); + var isExported = TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */); + + if (!isExported) { + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("var "); + this.recordSourceMappingStart(moduleName); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleName); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(moduleDecl); + this.emitIndent(); + } + + this.writeToOutput("("); + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("function ("); + + this.moduleName = this.getModuleName(pullDecl); + this.writeToOutputWithSourceMapRecord(this.moduleName, moduleName); + this.writeLineToOutput(") {"); + + this.recordSourceMappingNameStart(moduleName.text()); + + this.indenter.increaseIndent(); + + if (this.shouldCaptureThis(moduleDecl)) { + this.writeCaptureThisStatement(moduleDecl); + } + + if (moduleName === moduleDecl.stringLiteral) { + this.emitList(moduleDecl.moduleElements); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDecl.name); + var nameIndex = moduleNames.indexOf(moduleName); + TypeScript.Debug.assert(nameIndex >= 0); + + if (isLastName) { + this.emitList(moduleDecl.moduleElements); + } else { + this.emitIndent(); + this.emitSingleModuleDeclaration(moduleDecl, moduleNames[nameIndex + 1]); + this.writeLineToOutput(""); + } + } + + this.moduleName = moduleName.text(); + this.indenter.decreaseIndent(); + this.emitIndent(); + + var parentIsDynamic = temp === 2 /* DynamicModule */; + this.recordSourceMappingStart(moduleDecl.endingToken); + if (temp === 0 /* Prog */ && isExported) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); + } else if (isExported || temp === 0 /* Prog */) { + var dotMod = svModuleName !== "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); + } else if (!isExported && temp !== 0 /* Prog */) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); + } else { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")();"); + } + + this.recordSourceMappingEnd(moduleDecl); + if (temp !== 0 /* Prog */ && isExported) { + this.recordSourceMappingStart(moduleDecl); + if (parentIsDynamic) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); + } else { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); + } + this.recordSourceMappingEnd(moduleDecl); + } + + this.setContainer(temp); + this.moduleName = svModuleName; + + this.popDecl(pullDecl); + + if (isLastName) { + this.emitComments(moduleDecl, false); + } + }; + + Emitter.prototype.emitEnumElement = function (varDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(varDecl); + TypeScript.Debug.assert(pullDecl && pullDecl.kind === 67108864 /* EnumMember */); + + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + var name = varDecl.propertyName.text(); + var quoted = TypeScript.isQuoted(name); + this.writeToOutput(this.moduleName); + this.writeToOutput('['); + this.writeToOutput(this.moduleName); + this.writeToOutput('['); + this.writeToOutput(quoted ? name : '"' + name + '"'); + this.writeToOutput(']'); + + if (varDecl.equalsValueClause) { + this.emit(varDecl.equalsValueClause); + } else if (pullDecl.constantValue !== null) { + this.writeToOutput(' = '); + this.writeToOutput(pullDecl.constantValue.toString()); + } else { + this.writeToOutput(' = null'); + } + + this.writeToOutput('] = '); + this.writeToOutput(quoted ? name : '"' + name + '"'); + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + this.writeToOutput(';'); + }; + + Emitter.prototype.emitElementAccessExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.emit(expression.expression); + this.writeToOutput("["); + this.emit(expression.argumentExpression); + this.writeToOutput("]"); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitSimpleArrowFunctionExpression = function (arrowFunction) { + this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromIdentifier(arrowFunction.identifier), arrowFunction.block, arrowFunction.expression); + }; + + Emitter.prototype.emitParenthesizedArrowFunctionExpression = function (arrowFunction) { + this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), arrowFunction.block, arrowFunction.expression); + }; + + Emitter.prototype.emitAnyArrowFunctionExpression = function (arrowFunction, funcName, parameters, block, expression) { + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = true; + + var temp = this.setContainer(5 /* Function */); + + this.recordSourceMappingStart(arrowFunction); + + var pullDecl = this.semanticInfoChain.getDeclForAST(arrowFunction); + this.pushDecl(pullDecl); + + this.emitComments(arrowFunction, true); + + this.recordSourceMappingStart(arrowFunction); + this.writeToOutput("function "); + this.writeToOutput("("); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(funcName, arrowFunction, parameters, block, expression); + + this.recordSourceMappingEnd(arrowFunction); + + this.recordSourceMappingEnd(arrowFunction); + + this.emitComments(arrowFunction, false); + + this.popDecl(pullDecl); + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + }; + + Emitter.prototype.emitConstructor = function (funcDecl) { + if (!funcDecl.block) { + return; + } + var temp = this.setContainer(4 /* Constructor */); + + this.recordSourceMappingStart(funcDecl); + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.emitComments(funcDecl, true); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + this.writeToOutput(this.thisClassNode.identifier.text()); + this.writeToOutput("("); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionParameters(parameters); + this.writeLineToOutput(") {"); + + this.recordSourceMappingNameStart("constructor"); + this.indenter.increaseIndent(); + + this.emitDefaultValueAssignments(parameters); + this.emitRestParameterInitializer(parameters); + + if (this.shouldCaptureThis(funcDecl)) { + this.writeCaptureThisStatement(funcDecl); + } + + this.emitConstructorStatements(funcDecl); + this.emitCommentsArray(funcDecl.block.closeBraceLeadingComments, false); + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("}", funcDecl.block.closeBraceToken); + + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.popDecl(pullDecl); + this.setContainer(temp); + }; + + Emitter.prototype.emitGetAccessor = function (accessor) { + this.recordSourceMappingStart(accessor); + this.writeToOutput("get "); + + var temp = this.setContainer(5 /* Function */); + + this.recordSourceMappingStart(accessor); + + var pullDecl = this.semanticInfoChain.getDeclForAST(accessor); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(accessor); + + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(accessor, this.semanticInfoChain); + var container = accessorSymbol.getContainer(); + var containerKind = container.kind; + + this.recordSourceMappingNameStart(accessor.propertyName.text()); + this.writeToOutput(accessor.propertyName.text()); + this.writeToOutput("("); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(null, accessor, TypeScript.ASTHelpers.parametersFromParameterList(accessor.parameterList), accessor.block, null); + + this.recordSourceMappingEnd(accessor); + + this.recordSourceMappingEnd(accessor); + + this.popDecl(pullDecl); + this.setContainer(temp); + this.recordSourceMappingEnd(accessor); + }; + + Emitter.prototype.emitSetAccessor = function (accessor) { + this.recordSourceMappingStart(accessor); + this.writeToOutput("set "); + + var temp = this.setContainer(5 /* Function */); + + this.recordSourceMappingStart(accessor); + + var pullDecl = this.semanticInfoChain.getDeclForAST(accessor); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(accessor); + + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(accessor, this.semanticInfoChain); + var container = accessorSymbol.getContainer(); + var containerKind = container.kind; + + this.recordSourceMappingNameStart(accessor.propertyName.text()); + this.writeToOutput(accessor.propertyName.text()); + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(accessor.parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(null, accessor, parameters, accessor.block, null); + + this.recordSourceMappingEnd(accessor); + + this.recordSourceMappingEnd(accessor); + + this.popDecl(pullDecl); + this.setContainer(temp); + this.recordSourceMappingEnd(accessor); + }; + + Emitter.prototype.emitFunctionExpression = function (funcDecl) { + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = false; + + var temp = this.setContainer(5 /* Function */); + + var funcName = funcDecl.identifier ? funcDecl.identifier.text() : null; + + this.recordSourceMappingStart(funcDecl); + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + if (funcDecl.identifier) { + this.recordSourceMappingStart(funcDecl.identifier); + this.writeToOutput(funcDecl.identifier.text()); + this.recordSourceMappingEnd(funcDecl.identifier); + } + + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(funcName, funcDecl, parameters, funcDecl.block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.popDecl(pullDecl); + + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + }; + + Emitter.prototype.emitFunction = function (funcDecl) { + if (funcDecl.block === null) { + return; + } + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = false; + + var temp = this.setContainer(5 /* Function */); + + var funcName = funcDecl.identifier.text(); + + this.recordSourceMappingStart(funcDecl); + + var printName = funcDecl.identifier !== null; + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.emitComments(funcDecl, true); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + if (printName) { + var id = funcDecl.identifier.text(); + if (id) { + if (funcDecl.identifier) { + this.recordSourceMappingStart(funcDecl.identifier); + } + this.writeToOutput(id); + if (funcDecl.identifier) { + this.recordSourceMappingEnd(funcDecl.identifier); + } + } + } + + this.emitParameterList(funcDecl.callSignature.parameterList); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionBodyStatements(funcDecl.identifier.text(), funcDecl, parameters, funcDecl.block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.popDecl(pullDecl); + + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + + if (funcDecl.block) { + var pullFunctionDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + if ((this.emitState.container === 1 /* Module */ || this.emitState.container === 2 /* DynamicModule */) && pullFunctionDecl && TypeScript.hasFlag(pullFunctionDecl.flags, 1 /* Exported */)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = this.emitState.container === 1 /* Module */ ? this.moduleName : "exports"; + this.recordSourceMappingStart(funcDecl); + this.writeToOutput(modName + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + }; + + Emitter.prototype.emitAmbientVarDecl = function (varDecl) { + this.recordSourceMappingStart(this.currentVariableDeclaration); + if (varDecl.equalsValueClause) { + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + this.writeToOutputWithSourceMapRecord(varDecl.propertyName.text(), varDecl.propertyName); + this.emitJavascript(varDecl.equalsValueClause, false); + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + } + }; + + Emitter.prototype.emitVarDeclVar = function () { + if (this.currentVariableDeclaration) { + this.writeToOutput("var "); + } + }; + + Emitter.prototype.emitVariableDeclaration = function (declaration) { + var varDecl = declaration.declarators.nonSeparatorAt(0); + + var symbol = this.semanticInfoChain.getSymbolForAST(varDecl); + + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentKind = parentSymbol ? parentSymbol.kind : 0 /* None */; + + this.emitComments(declaration, true); + + var pullVarDecl = this.semanticInfoChain.getDeclForAST(varDecl); + var isAmbientWithoutInit = pullVarDecl && TypeScript.hasFlag(pullVarDecl.flags, 8 /* Ambient */) && varDecl.equalsValueClause === null; + if (!isAmbientWithoutInit) { + var prevVariableDeclaration = this.currentVariableDeclaration; + this.currentVariableDeclaration = declaration; + + for (var i = 0, n = declaration.declarators.nonSeparatorCount(); i < n; i++) { + var declarator = declaration.declarators.nonSeparatorAt(i); + + if (i > 0) { + this.writeToOutput(", "); + } + + this.emit(declarator); + } + this.currentVariableDeclaration = prevVariableDeclaration; + + this.recordSourceMappingEnd(declaration); + } + + this.emitComments(declaration, false); + }; + + Emitter.prototype.emitMemberVariableDeclaration = function (varDecl) { + TypeScript.Debug.assert(!TypeScript.hasModifier(varDecl.modifiers, 16 /* Static */) && varDecl.variableDeclarator.equalsValueClause); + + var pullDecl = this.semanticInfoChain.getDeclForAST(varDecl); + this.pushDecl(pullDecl); + + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + + var varDeclName = varDecl.variableDeclarator.propertyName.text(); + var quotedOrNumber = TypeScript.isQuoted(varDeclName) || varDecl.variableDeclarator.propertyName.kind() !== 11 /* IdentifierName */; + + var symbol = this.semanticInfoChain.getSymbolForAST(varDecl); + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentDecl = pullDecl && pullDecl.getParentDecl(); + + if (quotedOrNumber) { + this.writeToOutput("this["); + } else { + this.writeToOutput("this."); + } + + this.writeToOutputWithSourceMapRecord(varDecl.variableDeclarator.propertyName.text(), varDecl.variableDeclarator.propertyName); + + if (quotedOrNumber) { + this.writeToOutput("]"); + } + + if (varDecl.variableDeclarator.equalsValueClause) { + var prevVariableDeclaration = this.currentVariableDeclaration; + this.emit(varDecl.variableDeclarator.equalsValueClause); + this.currentVariableDeclaration = prevVariableDeclaration; + } + + if (this.emitState.container !== 6 /* Args */) { + this.writeToOutput(";"); + } + + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitVariableDeclarator = function (varDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(varDecl); + this.pushDecl(pullDecl); + if (pullDecl && (pullDecl.flags & 8 /* Ambient */) === 8 /* Ambient */) { + this.emitAmbientVarDecl(varDecl); + } else { + this.emitComments(varDecl, true); + this.recordSourceMappingStart(this.currentVariableDeclaration); + this.recordSourceMappingStart(varDecl); + + var varDeclName = varDecl.propertyName.text(); + + var symbol = this.semanticInfoChain.getSymbolForAST(varDecl); + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentDecl = pullDecl && pullDecl.getParentDecl(); + var parentIsModule = parentDecl && (parentDecl.flags & 102400 /* SomeInitializedModule */); + + if (parentIsModule) { + if (!TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */)) { + this.emitVarDeclVar(); + } else { + if (this.emitState.container === 2 /* DynamicModule */) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(this.moduleName + "."); + } + } + } else { + this.emitVarDeclVar(); + } + + this.writeToOutputWithSourceMapRecord(varDecl.propertyName.text(), varDecl.propertyName); + + if (varDecl.equalsValueClause) { + var prevVariableDeclaration = this.currentVariableDeclaration; + this.emit(varDecl.equalsValueClause); + this.currentVariableDeclaration = prevVariableDeclaration; + } + + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + } + this.currentVariableDeclaration = undefined; + this.popDecl(pullDecl); + }; + + Emitter.prototype.symbolIsUsedInItsEnclosingContainer = function (symbol, dynamic) { + if (typeof dynamic === "undefined") { dynamic = false; } + var symDecls = symbol.getDeclarations(); + + if (symDecls.length) { + var enclosingDecl = this.getEnclosingDecl(); + if (enclosingDecl) { + var parentDecl = symDecls[0].getParentDecl(); + if (parentDecl) { + var symbolDeclarationEnclosingContainer = parentDecl; + var enclosingContainer = enclosingDecl; + + while (symbolDeclarationEnclosingContainer) { + if (symbolDeclarationEnclosingContainer.kind === (dynamic ? 32 /* DynamicModule */ : 4 /* Container */)) { + break; + } + symbolDeclarationEnclosingContainer = symbolDeclarationEnclosingContainer.getParentDecl(); + } + + if (symbolDeclarationEnclosingContainer) { + while (enclosingContainer) { + if (enclosingContainer.kind === (dynamic ? 32 /* DynamicModule */ : 4 /* Container */)) { + break; + } + + enclosingContainer = enclosingContainer.getParentDecl(); + } + } + + if (symbolDeclarationEnclosingContainer && enclosingContainer) { + var same = symbolDeclarationEnclosingContainer === enclosingContainer; + + if (!same && symbol.anyDeclHasFlag(32768 /* InitializedModule */)) { + same = symbolDeclarationEnclosingContainer === enclosingContainer.getParentDecl(); + } + + return same; + } + } + } + } + + return false; + }; + + Emitter.prototype.shouldQualifySymbolNameWithParentName = function (symbol) { + var enclosingContextDeclPath = this.declStack; + var symbolDeclarations = symbol.getDeclarations(); + for (var i = 0; i < symbolDeclarations.length; i++) { + var currentDecl = symbolDeclarations[i]; + var declParent = currentDecl.getParentDecl(); + + if (currentDecl.kind === 67108864 /* EnumMember */) { + return true; + } + + if (!TypeScript.hasFlag(currentDecl.flags, 1 /* Exported */)) { + return false; + } + + if (currentDecl.kind === 512 /* Variable */ && !TypeScript.hasFlag(currentDecl.flags, 118784 /* ImplicitVariable */)) { + return true; + } + + if (TypeScript.ArrayUtilities.contains(this.declStack, declParent)) { + return false; + } + } + + return true; + }; + + Emitter.prototype.getSymbolForEmit = function (ast) { + var pullSymbol = this.semanticInfoChain.getSymbolForAST(ast); + var pullSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(ast); + if (pullSymbol && pullSymbolAlias) { + var symbolToCompare = TypeScript.isTypesOnlyLocation(ast) ? pullSymbolAlias.getExportAssignedTypeSymbol() : pullSymbolAlias.getExportAssignedValueSymbol(); + + if (pullSymbol === symbolToCompare) { + pullSymbol = pullSymbolAlias; + pullSymbolAlias = null; + } + } + return { symbol: pullSymbol, aliasSymbol: pullSymbolAlias }; + }; + + Emitter.prototype.emitName = function (name, addThis) { + this.emitComments(name, true); + this.recordSourceMappingStart(name); + if (name.text().length > 0) { + var symbolForEmit = this.getSymbolForEmit(name); + var pullSymbol = symbolForEmit.symbol; + if (!pullSymbol) { + pullSymbol = this.semanticInfoChain.anyTypeSymbol; + } + var pullSymbolAlias = symbolForEmit.aliasSymbol; + var pullSymbolKind = pullSymbol.kind; + var isLocalAlias = pullSymbolAlias && (pullSymbolAlias.getDeclarations()[0].getParentDecl() === this.getEnclosingDecl()); + if (addThis && (this.emitState.container !== 6 /* Args */) && pullSymbol) { + var pullSymbolContainer = pullSymbol.getContainer(); + + if (pullSymbolContainer) { + var pullSymbolContainerKind = pullSymbolContainer.kind; + + if (TypeScript.PullHelpers.symbolIsModule(pullSymbolContainer) || pullSymbolContainerKind === 64 /* Enum */ || pullSymbolContainer.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */)) { + var needToEmitParentName = this.shouldQualifySymbolNameWithParentName(pullSymbol); + if (needToEmitParentName) { + var parentDecl = pullSymbol.getDeclarations()[0].getParentDecl(); + TypeScript.Debug.assert(parentDecl && !parentDecl.isRootDecl()); + this.writeToOutput(this.getModuleName(parentDecl, true) + "."); + } + } else if (pullSymbolContainerKind === 32 /* DynamicModule */ || pullSymbolContainer.anyDeclHasFlag(65536 /* InitializedDynamicModule */)) { + if (pullSymbolKind === 4096 /* Property */) { + this.writeToOutput("exports."); + } else if (pullSymbol.anyDeclHasFlag(1 /* Exported */) && !isLocalAlias && !pullSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */) && pullSymbol.kind !== 32768 /* ConstructorMethod */ && pullSymbol.kind !== 8 /* Class */ && pullSymbol.kind !== 64 /* Enum */) { + this.writeToOutput("exports."); + } + } + } + } + + this.writeToOutput(name.text()); + } + + this.recordSourceMappingEnd(name); + this.emitComments(name, false); + }; + + Emitter.prototype.recordSourceMappingNameStart = function (name) { + if (this.sourceMapper) { + var nameIndex = -1; + if (name) { + if (this.sourceMapper.currentNameIndex.length > 0) { + var parentNameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; + if (parentNameIndex !== -1) { + name = this.sourceMapper.names[parentNameIndex] + "." + name; + } + } + + var nameIndex = this.sourceMapper.names.length - 1; + for (nameIndex; nameIndex >= 0; nameIndex--) { + if (this.sourceMapper.names[nameIndex] === name) { + break; + } + } + + if (nameIndex === -1) { + nameIndex = this.sourceMapper.names.length; + this.sourceMapper.names.push(name); + } + } + this.sourceMapper.currentNameIndex.push(nameIndex); + } + }; + + Emitter.prototype.recordSourceMappingNameEnd = function () { + if (this.sourceMapper) { + this.sourceMapper.currentNameIndex.pop(); + } + }; + + Emitter.prototype.recordSourceMappingStart = function (ast) { + if (this.sourceMapper && TypeScript.ASTHelpers.isValidAstNode(ast)) { + var lineCol = { line: -1, character: -1 }; + var sourceMapping = new TypeScript.SourceMapping(); + sourceMapping.start.emittedColumn = this.emitState.column; + sourceMapping.start.emittedLine = this.emitState.line; + + var lineMap = this.document.lineMap(); + lineMap.fillLineAndCharacterFromPosition(ast.start(), lineCol); + sourceMapping.start.sourceColumn = lineCol.character; + sourceMapping.start.sourceLine = lineCol.line + 1; + lineMap.fillLineAndCharacterFromPosition(ast.end(), lineCol); + sourceMapping.end.sourceColumn = lineCol.character; + sourceMapping.end.sourceLine = lineCol.line + 1; + + TypeScript.Debug.assert(!isNaN(sourceMapping.start.emittedColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.start.emittedLine)); + TypeScript.Debug.assert(!isNaN(sourceMapping.start.sourceColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.start.sourceLine)); + TypeScript.Debug.assert(!isNaN(sourceMapping.end.sourceColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.end.sourceLine)); + + 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); + this.sourceMapper.increaseMappingLevel(ast); + } + }; + + Emitter.prototype.recordSourceMappingEnd = function (ast) { + if (this.sourceMapper && TypeScript.ASTHelpers.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; + + TypeScript.Debug.assert(!isNaN(sourceMapping.end.emittedColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.end.emittedLine)); + + this.sourceMapper.decreaseMappingLevel(ast); + } + }; + + Emitter.prototype.getOutputFiles = function () { + var result = []; + if (this.sourceMapper !== null) { + this.sourceMapper.emitSourceMapping(); + result.push(this.sourceMapper.getOutputFile()); + } + + result.push(this.outfile.getOutputFile()); + return result; + }; + + Emitter.prototype.emitParameterPropertyAndMemberVariableAssignments = function () { + var constructorDecl = getLastConstructor(this.thisClassNode); + + if (constructorDecl) { + for (var i = 0, n = constructorDecl.callSignature.parameterList.parameters.nonSeparatorCount(); i < n; i++) { + var parameter = constructorDecl.callSignature.parameterList.parameters.nonSeparatorAt(i); + var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter); + if (TypeScript.hasFlag(parameterDecl.flags, 8388608 /* PropertyParameter */)) { + this.emitIndent(); + this.recordSourceMappingStart(parameter); + this.writeToOutputWithSourceMapRecord("this." + parameter.identifier.text(), parameter.identifier); + this.writeToOutput(" = "); + this.writeToOutputWithSourceMapRecord(parameter.identifier.text(), parameter.identifier); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(parameter); + } + } + } + + for (var i = 0, n = this.thisClassNode.classElements.childCount(); i < n; i++) { + if (this.thisClassNode.classElements.childAt(i).kind() === 136 /* MemberVariableDeclaration */) { + var varDecl = this.thisClassNode.classElements.childAt(i); + if (!TypeScript.hasModifier(varDecl.modifiers, 16 /* Static */) && varDecl.variableDeclarator.equalsValueClause) { + this.emitIndent(); + this.emitMemberVariableDeclaration(varDecl); + this.writeLineToOutput(""); + } + } + } + }; + + Emitter.prototype.isOnSameLine = function (pos1, pos2) { + var lineMap = this.document.lineMap(); + return lineMap.getLineNumberFromPosition(pos1) === lineMap.getLineNumberFromPosition(pos2); + }; + + Emitter.prototype.emitCommaSeparatedList = function (parent, list, buffer, preserveNewLines) { + if (list === null || list.nonSeparatorCount() === 0) { + return; + } + + var startLine = preserveNewLines && !this.isOnSameLine(parent.end(), list.nonSeparatorAt(0).end()); + + if (preserveNewLines) { + this.indenter.increaseIndent(); + } + + if (startLine) { + this.writeLineToOutput(""); + } else { + this.writeToOutput(buffer); + } + + for (var i = 0, n = list.nonSeparatorCount(); i < n; i++) { + var emitNode = list.nonSeparatorAt(i); + + this.emitJavascript(emitNode, startLine); + + if (i < (n - 1)) { + startLine = preserveNewLines && !this.isOnSameLine(emitNode.end(), list.nonSeparatorAt(i + 1).start()); + if (startLine) { + this.writeLineToOutput(","); + } else { + this.writeToOutput(", "); + } + } + } + + if (preserveNewLines) { + this.indenter.decreaseIndent(); + } + + if (preserveNewLines && !this.isOnSameLine(parent.end(), list.nonSeparatorAt(list.nonSeparatorCount() - 1).end())) { + this.writeLineToOutput(""); + this.emitIndent(); + } else { + this.writeToOutput(buffer); + } + }; + + Emitter.prototype.emitList = function (list, useNewLineSeparator, startInclusive, endExclusive) { + if (typeof useNewLineSeparator === "undefined") { useNewLineSeparator = true; } + if (typeof startInclusive === "undefined") { startInclusive = 0; } + if (typeof endExclusive === "undefined") { endExclusive = list.childCount(); } + if (list === null) { + return; + } + + this.emitComments(list, true); + var lastEmittedNode = null; + + for (var i = startInclusive; i < endExclusive; i++) { + var node = list.childAt(i); + + if (this.shouldEmit(node)) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + if (useNewLineSeparator) { + this.writeLineToOutput(""); + } + + lastEmittedNode = node; + } + } + + this.emitComments(list, false); + }; + + Emitter.prototype.emitSeparatedList = function (list, useNewLineSeparator, startInclusive, endExclusive) { + if (typeof useNewLineSeparator === "undefined") { useNewLineSeparator = true; } + if (typeof startInclusive === "undefined") { startInclusive = 0; } + if (typeof endExclusive === "undefined") { endExclusive = list.nonSeparatorCount(); } + if (list === null) { + return; + } + + this.emitComments(list, true); + var lastEmittedNode = null; + + for (var i = startInclusive; i < endExclusive; i++) { + var node = list.nonSeparatorAt(i); + + if (this.shouldEmit(node)) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + if (useNewLineSeparator) { + this.writeLineToOutput(""); + } + + lastEmittedNode = node; + } + } + + this.emitComments(list, false); + }; + + Emitter.prototype.isDirectivePrologueElement = function (node) { + if (node.kind() === 149 /* ExpressionStatement */) { + var exprStatement = node; + return exprStatement.expression.kind() === 14 /* StringLiteral */; + } + + return false; + }; + + Emitter.prototype.emitSpaceBetweenConstructs = function (node1, node2) { + if (node1 === null || node2 === null) { + return; + } + + if (node1.start() === -1 || node1.end() === -1 || node2.start() === -1 || node2.end() === -1) { + return; + } + + var lineMap = this.document.lineMap(); + var node1EndLine = lineMap.getLineNumberFromPosition(node1.end()); + var node2StartLine = lineMap.getLineNumberFromPosition(node2.start()); + + if ((node2StartLine - node1EndLine) > 1) { + this.writeLineToOutput("", true); + } + }; + + Emitter.prototype.getDetachedComments = function (element) { + var preComments = element.preComments(); + if (preComments) { + var lineMap = this.document.lineMap(); + + var detachedComments = []; + var lastComment = null; + + for (var i = 0, n = preComments.length; i < n; i++) { + var comment = preComments[i]; + + if (lastComment) { + var lastCommentLine = lineMap.getLineNumberFromPosition(lastComment.end()); + var commentLine = lineMap.getLineNumberFromPosition(comment.start()); + + if (commentLine >= lastCommentLine + 2) { + return detachedComments; + } + } + + detachedComments.push(comment); + lastComment = comment; + } + + var lastCommentLine = lineMap.getLineNumberFromPosition(TypeScript.ArrayUtilities.last(detachedComments).end()); + var astLine = lineMap.getLineNumberFromPosition(element.start()); + if (astLine >= lastCommentLine + 2) { + return detachedComments; + } + } + + return []; + }; + + Emitter.prototype.emitPossibleCopyrightHeaders = function (script) { + this.emitDetachedComments(script.moduleElements); + }; + + Emitter.prototype.emitDetachedComments = function (list) { + if (list.childCount() > 0) { + var firstElement = list.childAt(0); + + this.detachedCommentsElement = firstElement; + this.emitCommentsArray(this.getDetachedComments(this.detachedCommentsElement), false); + } + }; + + Emitter.prototype.emitScriptElements = function (sourceUnit) { + var list = sourceUnit.moduleElements; + + this.emitPossibleCopyrightHeaders(sourceUnit); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var node = list.childAt(i); + + if (!this.isDirectivePrologueElement(node)) { + break; + } + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + } + + this.emitPrologue(sourceUnit); + + var isExternalModule = this.document.isExternalModule(); + var isNonElidedExternalModule = isExternalModule && !TypeScript.ASTHelpers.scriptIsElided(sourceUnit); + if (isNonElidedExternalModule) { + this.recordSourceMappingStart(sourceUnit); + + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + var dependencyList = "[\"require\", \"exports\""; + var importList = "require, exports"; + + var importAndDependencyList = this.getModuleImportAndDependencyList(sourceUnit); + importList += importAndDependencyList.importList; + dependencyList += importAndDependencyList.dependencyList + "]"; + + this.writeLineToOutput("define(" + dependencyList + "," + " function(" + importList + ") {"); + } + } + + if (isExternalModule) { + var temp = this.setContainer(2 /* DynamicModule */); + + var svModuleName = this.moduleName; + this.moduleName = sourceUnit.fileName(); + if (TypeScript.isTSFile(this.moduleName)) { + this.moduleName = this.moduleName.substring(0, this.moduleName.length - ".ts".length); + } + + this.setExportAssignment(null); + + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + this.indenter.increaseIndent(); + } + + var externalModule = this.semanticInfoChain.getDeclForAST(this.document.sourceUnit()); + + if (TypeScript.hasFlag(externalModule.flags, 262144 /* MustCaptureThis */)) { + this.writeCaptureThisStatement(sourceUnit); + } + + this.pushDecl(externalModule); + } + + this.emitList(list, true, i, n); + + if (isExternalModule) { + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + this.indenter.decreaseIndent(); + } + + if (isNonElidedExternalModule) { + var exportAssignment = this.getExportAssignment(); + var exportAssignmentIdentifierText = exportAssignment ? exportAssignment.identifier.text() : null; + var exportAssignmentValueSymbol = externalModule.getSymbol().getExportAssignedValueSymbol(); + + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + if (exportAssignmentIdentifierText && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { + this.indenter.increaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("return " + exportAssignmentIdentifierText, exportAssignment); + this.writeLineToOutput(";"); + this.indenter.decreaseIndent(); + } + this.writeToOutput("});"); + } else if (exportAssignmentIdentifierText && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("module.exports = " + exportAssignmentIdentifierText, exportAssignment); + this.writeToOutput(";"); + } + + this.recordSourceMappingEnd(sourceUnit); + this.writeLineToOutput(""); + } + + this.setContainer(temp); + this.moduleName = svModuleName; + this.popDecl(externalModule); + } + }; + + Emitter.prototype.emitConstructorStatements = function (funcDecl) { + var list = funcDecl.block.statements; + + if (list === null) { + return; + } + + this.emitComments(list, true); + + var emitPropertyAssignmentsAfterSuperCall = TypeScript.ASTHelpers.getExtendsHeritageClause(this.thisClassNode.heritageClauses) !== null; + var propertyAssignmentIndex = emitPropertyAssignmentsAfterSuperCall ? 1 : 0; + var lastEmittedNode = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + if (i === propertyAssignmentIndex) { + this.emitParameterPropertyAndMemberVariableAssignments(); + } + + var node = list.childAt(i); + + if (this.shouldEmit(node)) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + + lastEmittedNode = node; + } + } + + if (i === propertyAssignmentIndex) { + this.emitParameterPropertyAndMemberVariableAssignments(); + } + + this.emitComments(list, false); + }; + + Emitter.prototype.emitJavascript = function (ast, startLine) { + if (ast === null) { + return; + } + + if (startLine && this.indenter.indentAmt > 0) { + this.emitIndent(); + } + + this.emit(ast); + }; + + Emitter.prototype.emitAccessorMemberDeclaration = function (funcDecl, name, className, isProto) { + if (funcDecl.kind() !== 139 /* GetAccessor */) { + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain); + if (accessorSymbol.getGetter()) { + return; + } + } + + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + + this.writeToOutput("Object.defineProperty(" + className); + if (isProto) { + this.writeToOutput(".prototype, "); + } else { + this.writeToOutput(", "); + } + + var functionName = name.text(); + if (TypeScript.isQuoted(functionName)) { + this.writeToOutput(functionName); + } else { + this.writeToOutput('"' + functionName + '"'); + } + + this.writeLineToOutput(", {"); + + this.indenter.increaseIndent(); + + var accessors = TypeScript.PullHelpers.getGetterAndSetterFunction(funcDecl, this.semanticInfoChain); + if (accessors.getter) { + this.emitIndent(); + this.recordSourceMappingStart(accessors.getter); + this.emitComments(accessors.getter, true); + this.writeToOutput("get: "); + this.emitAccessorBody(accessors.getter, accessors.getter.parameterList, accessors.getter.block); + this.writeLineToOutput(","); + } + + if (accessors.setter) { + this.emitIndent(); + this.recordSourceMappingStart(accessors.setter); + this.emitComments(accessors.setter, true); + this.writeToOutput("set: "); + this.emitAccessorBody(accessors.setter, accessors.setter.parameterList, accessors.setter.block); + this.writeLineToOutput(","); + } + + this.emitIndent(); + this.writeLineToOutput("enumerable: true,"); + this.emitIndent(); + this.writeLineToOutput("configurable: true"); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("});"); + this.recordSourceMappingEnd(funcDecl); + }; + + Emitter.prototype.emitAccessorBody = function (funcDecl, parameterList, block) { + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(null, funcDecl, parameters, block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitClass = function (classDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(classDecl); + this.pushDecl(pullDecl); + + var svClassNode = this.thisClassNode; + this.thisClassNode = classDecl; + var className = classDecl.identifier.text(); + this.emitComments(classDecl, true); + var temp = this.setContainer(3 /* Class */); + + this.recordSourceMappingStart(classDecl); + this.writeToOutput("var " + className); + + var hasBaseClass = TypeScript.ASTHelpers.getExtendsHeritageClause(classDecl.heritageClauses) !== null; + var baseTypeReference = null; + var varDecl = null; + + if (hasBaseClass) { + this.writeLineToOutput(" = (function (_super) {"); + } else { + this.writeLineToOutput(" = (function () {"); + } + + this.recordSourceMappingNameStart(className); + this.indenter.increaseIndent(); + + if (hasBaseClass) { + baseTypeReference = TypeScript.ASTHelpers.getExtendsHeritageClause(classDecl.heritageClauses).typeNames.nonSeparatorAt(0); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("__extends(" + className + ", _super)", baseTypeReference); + this.writeLineToOutput(";"); + } + + this.emitIndent(); + + var constrDecl = getLastConstructor(classDecl); + + if (constrDecl) { + this.emit(constrDecl); + this.writeLineToOutput(""); + } else { + this.recordSourceMappingStart(classDecl); + + this.indenter.increaseIndent(); + this.writeLineToOutput("function " + classDecl.identifier.text() + "() {"); + this.recordSourceMappingNameStart("constructor"); + if (hasBaseClass) { + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("_super.apply(this, arguments)", baseTypeReference); + this.writeLineToOutput(";"); + } + + if (this.shouldCaptureThis(classDecl)) { + this.writeCaptureThisStatement(classDecl); + } + + this.emitParameterPropertyAndMemberVariableAssignments(); + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("}", classDecl.closeBraceToken); + this.writeLineToOutput(""); + + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl); + } + + this.emitClassMembers(classDecl); + + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("return " + className + ";", classDecl.closeBraceToken); + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("}", classDecl.closeBraceToken); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingStart(classDecl); + this.writeToOutput(")("); + if (hasBaseClass) { + this.emitJavascript(baseTypeReference, false); + } + this.writeToOutput(");"); + this.recordSourceMappingEnd(classDecl); + + if ((temp === 1 /* Module */ || temp === 2 /* DynamicModule */) && TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = temp === 1 /* Module */ ? this.moduleName : "exports"; + this.writeToOutputWithSourceMapRecord(modName + "." + className + " = " + className + ";", classDecl); + } + + this.recordSourceMappingEnd(classDecl); + this.emitComments(classDecl, false); + this.setContainer(temp); + this.thisClassNode = svClassNode; + + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitClassMembers = function (classDecl) { + var lastEmittedMember = null; + + for (var i = 0, n = classDecl.classElements.childCount(); i < n; i++) { + var memberDecl = classDecl.classElements.childAt(i); + + if (memberDecl.kind() === 139 /* GetAccessor */) { + this.emitSpaceBetweenConstructs(lastEmittedMember, memberDecl); + var getter = memberDecl; + this.emitAccessorMemberDeclaration(getter, getter.propertyName, classDecl.identifier.text(), !TypeScript.hasModifier(getter.modifiers, 16 /* Static */)); + lastEmittedMember = memberDecl; + } else if (memberDecl.kind() === 140 /* SetAccessor */) { + this.emitSpaceBetweenConstructs(lastEmittedMember, memberDecl); + var setter = memberDecl; + this.emitAccessorMemberDeclaration(setter, setter.propertyName, classDecl.identifier.text(), !TypeScript.hasModifier(setter.modifiers, 16 /* Static */)); + lastEmittedMember = memberDecl; + } else if (memberDecl.kind() === 135 /* MemberFunctionDeclaration */) { + var memberFunction = memberDecl; + + if (memberFunction.block) { + this.emitSpaceBetweenConstructs(lastEmittedMember, memberDecl); + + this.emitClassMemberFunctionDeclaration(classDecl, memberFunction); + lastEmittedMember = memberDecl; + } + } + } + + for (var i = 0, n = classDecl.classElements.childCount(); i < n; i++) { + var memberDecl = classDecl.classElements.childAt(i); + + if (memberDecl.kind() === 136 /* MemberVariableDeclaration */) { + var varDecl = memberDecl; + + if (TypeScript.hasModifier(varDecl.modifiers, 16 /* Static */) && varDecl.variableDeclarator.equalsValueClause) { + this.emitSpaceBetweenConstructs(lastEmittedMember, varDecl); + + this.emitIndent(); + this.recordSourceMappingStart(varDecl); + + var varDeclName = varDecl.variableDeclarator.propertyName.text(); + if (TypeScript.isQuoted(varDeclName) || varDecl.variableDeclarator.propertyName.kind() !== 11 /* IdentifierName */) { + this.writeToOutput(classDecl.identifier.text() + "[" + varDeclName + "]"); + } else { + this.writeToOutput(classDecl.identifier.text() + "." + varDeclName); + } + + this.emit(varDecl.variableDeclarator.equalsValueClause); + + this.recordSourceMappingEnd(varDecl); + this.writeLineToOutput(";"); + + lastEmittedMember = varDecl; + } + } + } + }; + + Emitter.prototype.emitClassMemberFunctionDeclaration = function (classDecl, funcDecl) { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.emitComments(funcDecl, true); + var functionName = funcDecl.propertyName.text(); + + this.writeToOutput(classDecl.identifier.text()); + + if (!TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */)) { + this.writeToOutput(".prototype"); + } + + if (TypeScript.isQuoted(functionName) || funcDecl.propertyName.kind() !== 11 /* IdentifierName */) { + this.writeToOutput("[" + functionName + "] = "); + } else { + this.writeToOutput("." + functionName + " = "); + } + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + this.emitParameterList(funcDecl.callSignature.parameterList); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionBodyStatements(funcDecl.propertyName.text(), funcDecl, parameters, funcDecl.block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.recordSourceMappingEnd(funcDecl); + this.popDecl(pullDecl); + + this.writeLineToOutput(";"); + }; + + Emitter.prototype.requiresExtendsBlock = function (moduleElements) { + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var moduleElement = moduleElements.childAt(i); + + if (moduleElement.kind() === 130 /* ModuleDeclaration */) { + var moduleAST = moduleElement; + + if (!TypeScript.hasModifier(moduleAST.modifiers, 8 /* Ambient */) && this.requiresExtendsBlock(moduleAST.moduleElements)) { + return true; + } + } else if (moduleElement.kind() === 131 /* ClassDeclaration */) { + var classDeclaration = moduleElement; + + if (!TypeScript.hasModifier(classDeclaration.modifiers, 8 /* Ambient */) && TypeScript.ASTHelpers.getExtendsHeritageClause(classDeclaration.heritageClauses) !== null) { + return true; + } + } + } + + return false; + }; + + Emitter.prototype.emitPrologue = function (sourceUnit) { + if (!this.extendsPrologueEmitted) { + if (this.requiresExtendsBlock(sourceUnit.moduleElements)) { + this.extendsPrologueEmitted = true; + this.writeLineToOutput("var __extends = this.__extends || function (d, b) {"); + this.writeLineToOutput(" for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];"); + this.writeLineToOutput(" function __() { this.constructor = d; }"); + this.writeLineToOutput(" __.prototype = b.prototype;"); + this.writeLineToOutput(" d.prototype = new __();"); + this.writeLineToOutput("};"); + } + } + + if (!this.globalThisCapturePrologueEmitted) { + if (this.shouldCaptureThis(sourceUnit)) { + this.globalThisCapturePrologueEmitted = true; + this.writeLineToOutput(this.captureThisStmtString); + } + } + }; + + Emitter.prototype.emitThis = function () { + if (!this.inWithBlock && this.inArrowFunction) { + this.writeToOutput("_this"); + } else { + this.writeToOutput("this"); + } + }; + + Emitter.prototype.emitBlockOrStatement = function (node) { + if (node.kind() === 146 /* Block */) { + this.emit(node); + } else { + this.writeLineToOutput(""); + this.indenter.increaseIndent(); + this.emitJavascript(node, true); + this.indenter.decreaseIndent(); + } + }; + + Emitter.prototype.emitLiteralExpression = function (expression) { + switch (expression.kind()) { + case 32 /* NullKeyword */: + this.writeToOutputWithSourceMapRecord("null", expression); + break; + case 24 /* FalseKeyword */: + this.writeToOutputWithSourceMapRecord("false", expression); + break; + case 37 /* TrueKeyword */: + this.writeToOutputWithSourceMapRecord("true", expression); + break; + default: + throw TypeScript.Errors.abstract(); + } + }; + + Emitter.prototype.emitThisExpression = function (expression) { + if (!this.inWithBlock && this.inArrowFunction) { + this.writeToOutputWithSourceMapRecord("_this", expression); + } else { + this.writeToOutputWithSourceMapRecord("this", expression); + } + }; + + Emitter.prototype.emitSuperExpression = function (expression) { + this.writeToOutputWithSourceMapRecord("_super.prototype", expression); + }; + + Emitter.prototype.emitParenthesizedExpression = function (parenthesizedExpression) { + var omitParentheses = false; + + if (parenthesizedExpression.expression.kind() === 220 /* CastExpression */ && parenthesizedExpression.openParenTrailingComments === null) { + var castedExpression = parenthesizedExpression.expression.expression; + + while (castedExpression.kind() == 220 /* CastExpression */) { + castedExpression = castedExpression.expression; + } + + switch (castedExpression.kind()) { + case 217 /* ParenthesizedExpression */: + case 11 /* IdentifierName */: + case 32 /* NullKeyword */: + case 35 /* ThisKeyword */: + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + case 12 /* RegularExpressionLiteral */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + case 214 /* ArrayLiteralExpression */: + case 215 /* ObjectLiteralExpression */: + case 212 /* MemberAccessExpression */: + case 221 /* ElementAccessExpression */: + omitParentheses = true; + break; + + case 213 /* InvocationExpression */: + if (parenthesizedExpression.parent.kind() !== 216 /* ObjectCreationExpression */) { + omitParentheses = true; + } + + break; + } + } + + if (omitParentheses) { + this.emit(parenthesizedExpression.expression); + } else { + this.recordSourceMappingStart(parenthesizedExpression); + this.writeToOutput("("); + this.emitCommentsArray(parenthesizedExpression.openParenTrailingComments, false); + this.emit(parenthesizedExpression.expression); + this.writeToOutput(")"); + this.recordSourceMappingEnd(parenthesizedExpression); + } + }; + + Emitter.prototype.emitCastExpression = function (expression) { + this.emit(expression.expression); + }; + + Emitter.prototype.emitPrefixUnaryExpression = function (expression) { + var nodeType = expression.kind(); + + this.recordSourceMappingStart(expression); + switch (nodeType) { + case 167 /* LogicalNotExpression */: + this.writeToOutput("!"); + this.emit(expression.operand); + break; + case 166 /* BitwiseNotExpression */: + this.writeToOutput("~"); + this.emit(expression.operand); + break; + case 165 /* NegateExpression */: + this.writeToOutput("-"); + if (expression.operand.kind() === 165 /* NegateExpression */ || expression.operand.kind() === 169 /* PreDecrementExpression */) { + this.writeToOutput(" "); + } + this.emit(expression.operand); + break; + case 164 /* PlusExpression */: + this.writeToOutput("+"); + if (expression.operand.kind() === 164 /* PlusExpression */ || expression.operand.kind() === 168 /* PreIncrementExpression */) { + this.writeToOutput(" "); + } + this.emit(expression.operand); + break; + case 168 /* PreIncrementExpression */: + this.writeToOutput("++"); + this.emit(expression.operand); + break; + case 169 /* PreDecrementExpression */: + this.writeToOutput("--"); + this.emit(expression.operand); + break; + default: + throw TypeScript.Errors.abstract(); + } + + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitPostfixUnaryExpression = function (expression) { + var nodeType = expression.kind(); + + this.recordSourceMappingStart(expression); + switch (nodeType) { + case 210 /* PostIncrementExpression */: + this.emit(expression.operand); + this.writeToOutput("++"); + break; + case 211 /* PostDecrementExpression */: + this.emit(expression.operand); + this.writeToOutput("--"); + break; + default: + throw TypeScript.Errors.abstract(); + } + + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitTypeOfExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.writeToOutput("typeof "); + this.emit(expression.expression); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitDeleteExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.writeToOutput("delete "); + this.emit(expression.expression); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitVoidExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.writeToOutput("void "); + this.emit(expression.expression); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.canEmitDottedNameMemberAccessExpression = function (expression) { + var memberExpressionNodeType = expression.expression.kind(); + + if (memberExpressionNodeType === 11 /* IdentifierName */ || memberExpressionNodeType == 212 /* MemberAccessExpression */) { + var memberAccessSymbol = this.getSymbolForEmit(expression).symbol; + var memberAccessExpressionSymbol = this.getSymbolForEmit(expression.expression).symbol; + if (memberAccessSymbol && memberAccessExpressionSymbol && !this.semanticInfoChain.getAliasSymbolForAST(expression.expression) && (TypeScript.PullHelpers.symbolIsModule(memberAccessExpressionSymbol) || memberAccessExpressionSymbol.kind === 64 /* Enum */ || memberAccessExpressionSymbol.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */))) { + var memberAccessSymbolKind = memberAccessSymbol.kind; + if (memberAccessSymbolKind === 4096 /* Property */ || memberAccessSymbolKind === 67108864 /* EnumMember */ || (memberAccessSymbol.anyDeclHasFlag(1 /* Exported */) && memberAccessSymbolKind === 512 /* Variable */ && !memberAccessSymbol.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */)) || ((memberAccessSymbol.anyDeclHasFlag(1 /* Exported */) && !this.symbolIsUsedInItsEnclosingContainer(memberAccessSymbol)))) { + if (memberExpressionNodeType === 212 /* MemberAccessExpression */) { + return this.canEmitDottedNameMemberAccessExpression(expression.expression); + } + + return true; + } + } + } + + return false; + }; + + Emitter.prototype.emitDottedNameMemberAccessExpression = function (expression) { + this.recordSourceMappingStart(expression); + if (expression.expression.kind() === 212 /* MemberAccessExpression */) { + this.emitDottedNameMemberAccessExpressionRecurse(expression.expression); + } else { + this.emitName(expression.expression, true); + } + + this.writeToOutput("."); + this.emitName(expression.name, false); + + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitDottedNameMemberAccessExpressionRecurse = function (expression) { + this.emitComments(expression, true); + this.emitDottedNameMemberAccessExpression(expression); + this.emitComments(expression, false); + }; + + Emitter.prototype.emitMemberAccessExpression = function (expression) { + if (!this.tryEmitConstant(expression)) { + if (this.canEmitDottedNameMemberAccessExpression(expression)) { + this.emitDottedNameMemberAccessExpression(expression); + } else { + this.recordSourceMappingStart(expression); + this.emit(expression.expression); + this.writeToOutput("."); + this.emitName(expression.name, false); + this.recordSourceMappingEnd(expression); + } + } + }; + + Emitter.prototype.emitQualifiedName = function (name) { + this.recordSourceMappingStart(name); + + this.emit(name.left); + this.writeToOutput("."); + this.emitName(name.right, false); + + this.recordSourceMappingEnd(name); + }; + + Emitter.prototype.emitBinaryExpression = function (expression) { + this.recordSourceMappingStart(expression); + switch (expression.kind()) { + case 173 /* CommaExpression */: + this.emit(expression.left); + this.writeToOutput(", "); + this.emit(expression.right); + break; + default: { + this.emit(expression.left); + var binOp = TypeScript.SyntaxFacts.getText(TypeScript.SyntaxFacts.getOperatorTokenFromBinaryExpression(expression.kind())); + if (binOp === "instanceof") { + this.writeToOutput(" instanceof "); + } else if (binOp === "in") { + this.writeToOutput(" in "); + } else { + this.writeToOutput(" " + binOp + " "); + } + this.emit(expression.right); + } + } + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitSimplePropertyAssignment = function (property) { + this.recordSourceMappingStart(property); + this.emit(property.propertyName); + this.writeToOutput(": "); + this.emit(property.expression); + this.recordSourceMappingEnd(property); + }; + + Emitter.prototype.emitFunctionPropertyAssignment = function (funcProp) { + this.recordSourceMappingStart(funcProp); + + this.emit(funcProp.propertyName); + this.writeToOutput(": "); + + var pullFunctionDecl = this.semanticInfoChain.getDeclForAST(funcProp); + + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = false; + + var temp = this.setContainer(5 /* Function */); + var funcName = funcProp.propertyName; + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcProp); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcProp); + this.writeToOutput("function "); + + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(funcProp.propertyName.text(), funcProp, parameters, funcProp.block, null); + + this.recordSourceMappingEnd(funcProp); + + this.recordSourceMappingEnd(funcProp); + + this.emitComments(funcProp, false); + + this.popDecl(pullDecl); + + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + }; + + Emitter.prototype.emitConditionalExpression = function (expression) { + this.emit(expression.condition); + this.writeToOutput(" ? "); + this.emit(expression.whenTrue); + this.writeToOutput(" : "); + this.emit(expression.whenFalse); + }; + + Emitter.prototype.emitThrowStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("throw "); + this.emit(statement.expression); + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitExpressionStatement = function (statement) { + var isArrowExpression = statement.expression.kind() === 219 /* SimpleArrowFunctionExpression */ || statement.expression.kind() === 218 /* ParenthesizedArrowFunctionExpression */; + + this.recordSourceMappingStart(statement); + if (isArrowExpression) { + this.writeToOutput("("); + } + + this.emit(statement.expression); + + if (isArrowExpression) { + this.writeToOutput(")"); + } + + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitLabeledStatement = function (statement) { + this.writeToOutputWithSourceMapRecord(statement.identifier.text(), statement.identifier); + this.writeLineToOutput(":"); + this.emitJavascript(statement.statement, true); + }; + + Emitter.prototype.emitBlock = function (block) { + this.recordSourceMappingStart(block); + this.writeLineToOutput(" {"); + this.indenter.increaseIndent(); + if (block.statements) { + this.emitList(block.statements); + } + this.emitCommentsArray(block.closeBraceLeadingComments, false); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + this.recordSourceMappingEnd(block); + }; + + Emitter.prototype.emitBreakStatement = function (jump) { + this.recordSourceMappingStart(jump); + this.writeToOutput("break"); + + if (jump.identifier) { + this.writeToOutput(" " + jump.identifier.text()); + } + + this.recordSourceMappingEnd(jump); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitContinueStatement = function (jump) { + this.recordSourceMappingStart(jump); + this.writeToOutput("continue"); + + if (jump.identifier) { + this.writeToOutput(" " + jump.identifier.text()); + } + + this.recordSourceMappingEnd(jump); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitWhileStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("while ("); + this.emit(statement.condition); + this.writeToOutput(")"); + this.emitBlockOrStatement(statement.statement); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitDoStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("do"); + this.emitBlockOrStatement(statement.statement); + this.writeToOutputWithSourceMapRecord(" while", statement.whileKeyword); + this.writeToOutput('('); + this.emit(statement.condition); + this.writeToOutput(")"); + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitIfStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("if ("); + this.emit(statement.condition); + this.writeToOutput(")"); + + this.emitBlockOrStatement(statement.statement); + + if (statement.elseClause) { + if (statement.statement.kind() !== 146 /* Block */) { + this.writeLineToOutput(""); + this.emitIndent(); + } else { + this.writeToOutput(" "); + } + + this.emit(statement.elseClause); + } + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitElseClause = function (elseClause) { + if (elseClause.statement.kind() === 147 /* IfStatement */) { + this.writeToOutput("else "); + this.emit(elseClause.statement); + } else { + this.writeToOutput("else"); + this.emitBlockOrStatement(elseClause.statement); + } + }; + + Emitter.prototype.emitReturnStatement = function (statement) { + this.recordSourceMappingStart(statement); + if (statement.expression) { + this.writeToOutput("return "); + this.emit(statement.expression); + } else { + this.writeToOutput("return"); + } + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitForInStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("for ("); + if (statement.left) { + this.emit(statement.left); + } else { + this.emit(statement.variableDeclaration); + } + this.writeToOutput(" in "); + this.emit(statement.expression); + this.writeToOutput(")"); + this.emitBlockOrStatement(statement.statement); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitForStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("for ("); + if (statement.variableDeclaration) { + this.emit(statement.variableDeclaration); + } else if (statement.initializer) { + this.emit(statement.initializer); + } + + this.writeToOutput("; "); + this.emitJavascript(statement.condition, false); + this.writeToOutput(";"); + if (statement.incrementor) { + this.writeToOutput(" "); + this.emitJavascript(statement.incrementor, false); + } + this.writeToOutput(")"); + this.emitBlockOrStatement(statement.statement); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitWithStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("with ("); + if (statement.condition) { + this.emit(statement.condition); + } + + this.writeToOutput(")"); + var prevInWithBlock = this.inWithBlock; + this.inWithBlock = true; + this.emitBlockOrStatement(statement.statement); + this.inWithBlock = prevInWithBlock; + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitSwitchStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("switch ("); + this.emit(statement.expression); + this.recordSourceMappingStart(statement.closeParenToken); + this.writeToOutput(")"); + this.recordSourceMappingEnd(statement.closeParenToken); + this.writeLineToOutput(" {"); + this.indenter.increaseIndent(); + this.emitList(statement.switchClauses, false); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitCaseSwitchClause = function (clause) { + this.recordSourceMappingStart(clause); + this.writeToOutput("case "); + this.emit(clause.expression); + this.writeToOutput(":"); + + this.emitSwitchClauseBody(clause.statements); + this.recordSourceMappingEnd(clause); + }; + + Emitter.prototype.emitSwitchClauseBody = function (body) { + if (body.childCount() === 1 && body.childAt(0).kind() === 146 /* Block */) { + this.emit(body.childAt(0)); + this.writeLineToOutput(""); + } else { + this.writeLineToOutput(""); + this.indenter.increaseIndent(); + this.emit(body); + this.indenter.decreaseIndent(); + } + }; + + Emitter.prototype.emitDefaultSwitchClause = function (clause) { + this.recordSourceMappingStart(clause); + this.writeToOutput("default:"); + + this.emitSwitchClauseBody(clause.statements); + this.recordSourceMappingEnd(clause); + }; + + Emitter.prototype.emitTryStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("try "); + this.emit(statement.block); + this.emitJavascript(statement.catchClause, false); + + if (statement.finallyClause) { + this.emit(statement.finallyClause); + } + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitCatchClause = function (clause) { + this.writeToOutput(" "); + this.recordSourceMappingStart(clause); + this.writeToOutput("catch ("); + this.emit(clause.identifier); + this.writeToOutput(")"); + this.emit(clause.block); + this.recordSourceMappingEnd(clause); + }; + + Emitter.prototype.emitFinallyClause = function (clause) { + this.writeToOutput(" finally"); + this.emit(clause.block); + }; + + Emitter.prototype.emitDebuggerStatement = function (statement) { + this.writeToOutputWithSourceMapRecord("debugger", statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitNumericLiteral = function (literal) { + this.writeToOutputWithSourceMapRecord(literal.text(), literal); + }; + + Emitter.prototype.emitRegularExpressionLiteral = function (literal) { + this.writeToOutputWithSourceMapRecord(literal.text(), literal); + }; + + Emitter.prototype.emitStringLiteral = function (literal) { + this.writeToOutputWithSourceMapRecord(literal.text(), literal); + }; + + Emitter.prototype.emitEqualsValueClause = function (clause) { + this.writeToOutput(" = "); + this.emit(clause.value); + }; + + Emitter.prototype.emitParameter = function (parameter) { + this.writeToOutputWithSourceMapRecord(parameter.identifier.text(), parameter); + }; + + Emitter.prototype.emitConstructorDeclaration = function (declaration) { + if (declaration.block) { + this.emitConstructor(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitFunctionDeclaration = function (declaration) { + return declaration.preComments() !== null || (!TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) && declaration.block !== null); + }; + + Emitter.prototype.emitFunctionDeclaration = function (declaration) { + if (!TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) && declaration.block !== null) { + this.emitFunction(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.emitSourceUnit = function (sourceUnit) { + if (!this.document.isDeclareFile()) { + var pullDecl = this.semanticInfoChain.getDeclForAST(sourceUnit); + this.pushDecl(pullDecl); + this.emitScriptElements(sourceUnit); + this.popDecl(pullDecl); + + this.emitCommentsArray(sourceUnit.endOfFileTokenLeadingComments, false); + } + }; + + Emitter.prototype.shouldEmitEnumDeclaration = function (declaration) { + return declaration.preComments() !== null || !TypeScript.ASTHelpers.enumIsElided(declaration); + }; + + Emitter.prototype.emitEnumDeclaration = function (declaration) { + if (!TypeScript.ASTHelpers.enumIsElided(declaration)) { + this.emitComments(declaration, true); + this.emitEnum(declaration); + this.emitComments(declaration, false); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitModuleDeclaration = function (declaration) { + return declaration.preComments() !== null || !TypeScript.ASTHelpers.moduleIsElided(declaration); + }; + + Emitter.prototype.emitModuleDeclaration = function (declaration) { + if (!TypeScript.ASTHelpers.moduleIsElided(declaration)) { + this.emitModuleDeclarationWorker(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitClassDeclaration = function (declaration) { + return declaration.preComments() !== null || !TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */); + }; + + Emitter.prototype.emitClassDeclaration = function (declaration) { + if (!TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */)) { + this.emitClass(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitInterfaceDeclaration = function (declaration) { + return declaration.preComments() !== null; + }; + + Emitter.prototype.emitInterfaceDeclaration = function (declaration) { + this.emitComments(declaration, true, true); + }; + + Emitter.prototype.firstVariableDeclarator = function (statement) { + return statement.declaration.declarators.nonSeparatorAt(0); + }; + + Emitter.prototype.isNotAmbientOrHasInitializer = function (variableStatement) { + return !TypeScript.hasModifier(variableStatement.modifiers, 8 /* Ambient */) || this.firstVariableDeclarator(variableStatement).equalsValueClause !== null; + }; + + Emitter.prototype.shouldEmitVariableStatement = function (statement) { + return statement.preComments() !== null || this.isNotAmbientOrHasInitializer(statement); + }; + + Emitter.prototype.emitVariableStatement = function (statement) { + if (this.isNotAmbientOrHasInitializer(statement)) { + this.emitComments(statement, true); + this.emit(statement.declaration); + this.writeToOutput(";"); + this.emitComments(statement, false); + } else { + this.emitComments(statement, true, true); + } + }; + + Emitter.prototype.emitGenericType = function (type) { + this.emit(type.name); + }; + + Emitter.prototype.shouldEmit = function (ast) { + if (!ast) { + return false; + } + + switch (ast.kind()) { + case 133 /* ImportDeclaration */: + return this.shouldEmitImportDeclaration(ast); + case 131 /* ClassDeclaration */: + return this.shouldEmitClassDeclaration(ast); + case 128 /* InterfaceDeclaration */: + return this.shouldEmitInterfaceDeclaration(ast); + case 129 /* FunctionDeclaration */: + return this.shouldEmitFunctionDeclaration(ast); + case 130 /* ModuleDeclaration */: + return this.shouldEmitModuleDeclaration(ast); + case 148 /* VariableStatement */: + return this.shouldEmitVariableStatement(ast); + case 223 /* OmittedExpression */: + return false; + case 132 /* EnumDeclaration */: + return this.shouldEmitEnumDeclaration(ast); + } + + return true; + }; + + Emitter.prototype.emit = function (ast) { + if (!ast) { + return; + } + + switch (ast.kind()) { + case 2 /* SeparatedList */: + return this.emitSeparatedList(ast); + case 1 /* List */: + return this.emitList(ast); + case 120 /* SourceUnit */: + return this.emitSourceUnit(ast); + case 133 /* ImportDeclaration */: + return this.emitImportDeclaration(ast); + case 134 /* ExportAssignment */: + return this.setExportAssignment(ast); + case 131 /* ClassDeclaration */: + return this.emitClassDeclaration(ast); + case 128 /* InterfaceDeclaration */: + return this.emitInterfaceDeclaration(ast); + case 11 /* IdentifierName */: + return this.emitName(ast, true); + case 225 /* VariableDeclarator */: + return this.emitVariableDeclarator(ast); + case 219 /* SimpleArrowFunctionExpression */: + return this.emitSimpleArrowFunctionExpression(ast); + case 218 /* ParenthesizedArrowFunctionExpression */: + return this.emitParenthesizedArrowFunctionExpression(ast); + case 129 /* FunctionDeclaration */: + return this.emitFunctionDeclaration(ast); + case 130 /* ModuleDeclaration */: + return this.emitModuleDeclaration(ast); + case 224 /* VariableDeclaration */: + return this.emitVariableDeclaration(ast); + case 126 /* GenericType */: + return this.emitGenericType(ast); + case 137 /* ConstructorDeclaration */: + return this.emitConstructorDeclaration(ast); + case 132 /* EnumDeclaration */: + return this.emitEnumDeclaration(ast); + case 243 /* EnumElement */: + return this.emitEnumElement(ast); + case 222 /* FunctionExpression */: + return this.emitFunctionExpression(ast); + case 148 /* VariableStatement */: + return this.emitVariableStatement(ast); + } + + this.emitComments(ast, true); + this.emitWorker(ast); + this.emitComments(ast, false); + }; + + Emitter.prototype.emitWorker = function (ast) { + if (!ast) { + return; + } + + switch (ast.kind()) { + case 13 /* NumericLiteral */: + return this.emitNumericLiteral(ast); + case 12 /* RegularExpressionLiteral */: + return this.emitRegularExpressionLiteral(ast); + case 14 /* StringLiteral */: + return this.emitStringLiteral(ast); + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + case 37 /* TrueKeyword */: + return this.emitLiteralExpression(ast); + case 35 /* ThisKeyword */: + return this.emitThisExpression(ast); + case 50 /* SuperKeyword */: + return this.emitSuperExpression(ast); + case 217 /* ParenthesizedExpression */: + return this.emitParenthesizedExpression(ast); + case 214 /* ArrayLiteralExpression */: + return this.emitArrayLiteralExpression(ast); + case 211 /* PostDecrementExpression */: + case 210 /* PostIncrementExpression */: + return this.emitPostfixUnaryExpression(ast); + case 167 /* LogicalNotExpression */: + case 166 /* BitwiseNotExpression */: + case 165 /* NegateExpression */: + case 164 /* PlusExpression */: + case 168 /* PreIncrementExpression */: + case 169 /* PreDecrementExpression */: + return this.emitPrefixUnaryExpression(ast); + case 213 /* InvocationExpression */: + return this.emitInvocationExpression(ast); + case 221 /* ElementAccessExpression */: + return this.emitElementAccessExpression(ast); + case 212 /* MemberAccessExpression */: + return this.emitMemberAccessExpression(ast); + case 121 /* QualifiedName */: + return this.emitQualifiedName(ast); + case 173 /* CommaExpression */: + case 174 /* AssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 187 /* LogicalOrExpression */: + case 188 /* LogicalAndExpression */: + case 189 /* BitwiseOrExpression */: + case 190 /* BitwiseExclusiveOrExpression */: + case 191 /* BitwiseAndExpression */: + case 192 /* EqualsWithTypeConversionExpression */: + case 193 /* NotEqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + case 196 /* LessThanExpression */: + case 197 /* GreaterThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 200 /* InstanceOfExpression */: + case 201 /* InExpression */: + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + case 208 /* AddExpression */: + case 209 /* SubtractExpression */: + return this.emitBinaryExpression(ast); + case 186 /* ConditionalExpression */: + return this.emitConditionalExpression(ast); + case 232 /* EqualsValueClause */: + return this.emitEqualsValueClause(ast); + case 242 /* Parameter */: + return this.emitParameter(ast); + case 146 /* Block */: + return this.emitBlock(ast); + case 235 /* ElseClause */: + return this.emitElseClause(ast); + case 147 /* IfStatement */: + return this.emitIfStatement(ast); + case 149 /* ExpressionStatement */: + return this.emitExpressionStatement(ast); + case 139 /* GetAccessor */: + return this.emitGetAccessor(ast); + case 140 /* SetAccessor */: + return this.emitSetAccessor(ast); + case 157 /* ThrowStatement */: + return this.emitThrowStatement(ast); + case 150 /* ReturnStatement */: + return this.emitReturnStatement(ast); + case 216 /* ObjectCreationExpression */: + return this.emitObjectCreationExpression(ast); + case 151 /* SwitchStatement */: + return this.emitSwitchStatement(ast); + case 233 /* CaseSwitchClause */: + return this.emitCaseSwitchClause(ast); + case 234 /* DefaultSwitchClause */: + return this.emitDefaultSwitchClause(ast); + case 152 /* BreakStatement */: + return this.emitBreakStatement(ast); + case 153 /* ContinueStatement */: + return this.emitContinueStatement(ast); + case 154 /* ForStatement */: + return this.emitForStatement(ast); + case 155 /* ForInStatement */: + return this.emitForInStatement(ast); + case 158 /* WhileStatement */: + return this.emitWhileStatement(ast); + case 163 /* WithStatement */: + return this.emitWithStatement(ast); + case 220 /* CastExpression */: + return this.emitCastExpression(ast); + case 215 /* ObjectLiteralExpression */: + return this.emitObjectLiteralExpression(ast); + case 240 /* SimplePropertyAssignment */: + return this.emitSimplePropertyAssignment(ast); + case 241 /* FunctionPropertyAssignment */: + return this.emitFunctionPropertyAssignment(ast); + case 156 /* EmptyStatement */: + return this.writeToOutputWithSourceMapRecord(";", ast); + case 159 /* TryStatement */: + return this.emitTryStatement(ast); + case 236 /* CatchClause */: + return this.emitCatchClause(ast); + case 237 /* FinallyClause */: + return this.emitFinallyClause(ast); + case 160 /* LabeledStatement */: + return this.emitLabeledStatement(ast); + case 161 /* DoStatement */: + return this.emitDoStatement(ast); + case 171 /* TypeOfExpression */: + return this.emitTypeOfExpression(ast); + case 170 /* DeleteExpression */: + return this.emitDeleteExpression(ast); + case 172 /* VoidExpression */: + return this.emitVoidExpression(ast); + case 162 /* DebuggerStatement */: + return this.emitDebuggerStatement(ast); + } + }; + return Emitter; + })(); + TypeScript.Emitter = Emitter; + + function getLastConstructor(classDecl) { + return classDecl.classElements.lastOrDefault(function (e) { + return e.kind() === 137 /* ConstructorDeclaration */; + }); + } + TypeScript.getLastConstructor = getLastConstructor; + + function getTrimmedTextLines(comment) { + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + return comment.fullText().split("\n").map(function (s) { + return s.trim(); + }); + } else { + return [comment.fullText().trim()]; + } + } + TypeScript.getTrimmedTextLines = getTrimmedTextLines; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var MemberName = (function () { + function MemberName() { + this.prefix = ""; + this.suffix = ""; + } + MemberName.prototype.isString = function () { + return false; + }; + MemberName.prototype.isArray = function () { + return false; + }; + MemberName.prototype.isMarker = function () { + return !this.isString() && !this.isArray(); + }; + + MemberName.prototype.toString = function () { + return MemberName.memberNameToString(this); + }; + + MemberName.memberNameToString = function (memberName, markerInfo, markerBaseLength) { + if (typeof markerBaseLength === "undefined") { markerBaseLength = 0; } + var result = memberName.prefix; + + if (memberName.isString()) { + result += memberName.text; + } else if (memberName.isArray()) { + var ar = memberName; + for (var index = 0; index < ar.entries.length; index++) { + if (ar.entries[index].isMarker()) { + if (markerInfo) { + markerInfo.push(markerBaseLength + result.length); + } + continue; + } + + result += MemberName.memberNameToString(ar.entries[index], markerInfo, markerBaseLength + result.length); + result += ar.delim; + } + } + + result += memberName.suffix; + return result; + }; + + MemberName.create = function (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.call(this); + 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; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function stripStartAndEndQuotes(str) { + var firstCharCode = str && str.charCodeAt(0); + if (str && str.length >= 2 && firstCharCode === str.charCodeAt(str.length - 1) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { + return str.substring(1, str.length - 1); + } + + return str; + } + TypeScript.stripStartAndEndQuotes = stripStartAndEndQuotes; + + function isSingleQuoted(str) { + return str && str.length >= 2 && str.charCodeAt(0) === str.charCodeAt(str.length - 1) && str.charCodeAt(0) === 39 /* singleQuote */; + } + TypeScript.isSingleQuoted = isSingleQuoted; + + function isDoubleQuoted(str) { + return str && str.length >= 2 && str.charCodeAt(0) === str.charCodeAt(str.length - 1) && str.charCodeAt(0) === 34 /* doubleQuote */; + } + TypeScript.isDoubleQuoted = isDoubleQuoted; + + function isQuoted(str) { + return isDoubleQuoted(str) || isSingleQuoted(str); + } + TypeScript.isQuoted = isQuoted; + + function quoteStr(str) { + return "\"" + str + "\""; + } + TypeScript.quoteStr = quoteStr; + + var switchToForwardSlashesRegEx = /\\/g; + function switchToForwardSlashes(path) { + return path.replace(switchToForwardSlashesRegEx, "/"); + } + TypeScript.switchToForwardSlashes = switchToForwardSlashes; + + function trimModName(modName) { + 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 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 isTSFile(fname) { + return isFileOfExtension(fname, ".ts"); + } + TypeScript.isTSFile = isTSFile; + + 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(stripStartAndEndQuotes(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, isAbsoultePathURL) { + if (typeof isAbsoultePathURL === "undefined") { isAbsoultePathURL = true; } + 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("/"); + } + + if (isAbsoultePathURL && absoluteModPath.indexOf("://") === -1) { + absoluteModPath = "file:///" + absoluteModPath; + } + + return absoluteModPath; + } + TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; + + function changePathToDTS(modPath) { + return trimModName(stripStartAndEndQuotes(modPath)) + ".d.ts"; + } + TypeScript.changePathToDTS = changePathToDTS; + + function isRelative(path) { + return path.length > 0 && path.charAt(0) === "."; + } + TypeScript.isRelative = isRelative; + function isRooted(path) { + return path.length > 0 && (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 convertToDirectoryPath(dirPath) { + if (dirPath && dirPath.charAt(dirPath.length - 1) !== "/") { + dirPath += "/"; + } + + return dirPath; + } + TypeScript.convertToDirectoryPath = convertToDirectoryPath; + + var normalizePathRegEx = /^\\\\[^\\]/; + function normalizePath(path) { + if (normalizePathRegEx.test(path)) { + path = "file:" + path; + } + var parts = this.getPathComponents(switchToForwardSlashes(path)); + var normalizedParts = []; + + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + if (part === ".") { + continue; + } + + if (normalizedParts.length > 0 && TypeScript.ArrayUtilities.last(normalizedParts) !== ".." && part === "..") { + normalizedParts.pop(); + continue; + } + + normalizedParts.push(part); + } + + return normalizedParts.join("/"); + } + TypeScript.normalizePath = normalizePath; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + + + function isNoDefaultLibMatch(comment) { + var isNoDefaultLibRegex = /^(\/\/\/\s*/gim; + return isNoDefaultLibRegex.exec(comment); + } + + TypeScript.tripleSlashReferenceRegExp = /^(\/\/\/\s*/; + + function getFileReferenceFromReferencePath(fileName, lineMap, position, comment, diagnostics) { + var simpleReferenceRegEx = /^\/\/\/\s*= 7 && fullReference[6] === "true"; + if (isResident) { + TypeScript.CompilerDiagnostics.debugPrint(path + " is resident"); + } + return { + line: 0, + character: 0, + position: 0, + length: 0, + path: TypeScript.switchToForwardSlashes(adjustedPath), + isResident: isResident + }; + } + } + } + + return null; + } + + var scannerWindow = TypeScript.ArrayUtilities.createArray(2048, 0); + var scannerDiagnostics = []; + + function processImports(lineMap, scanner, token, importedFiles) { + var position = 0; + var lineChar = { line: -1, character: -1 }; + + var start = new Date().getTime(); + + while (token.tokenKind !== 10 /* EndOfFileToken */) { + if (token.tokenKind === 49 /* ImportKeyword */) { + var importStart = position + token.leadingTriviaWidth(); + token = scanner.scan(scannerDiagnostics, false); + + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 107 /* EqualsToken */) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 65 /* ModuleKeyword */ || token.tokenKind === 66 /* RequireKeyword */) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 72 /* OpenParenToken */) { + var afterOpenParenPosition = scanner.absoluteIndex(); + token = scanner.scan(scannerDiagnostics, false); + + lineMap.fillLineAndCharacterFromPosition(importStart, lineChar); + + if (token.tokenKind === 14 /* StringLiteral */) { + var ref = { + line: lineChar.line, + character: lineChar.character, + position: afterOpenParenPosition + token.leadingTriviaWidth(), + length: token.width(), + path: TypeScript.stripStartAndEndQuotes(TypeScript.switchToForwardSlashes(token.text())), + isResident: false + }; + importedFiles.push(ref); + } + } + } + } + } + } + + position = scanner.absoluteIndex(); + token = scanner.scan(scannerDiagnostics, false); + } + + var totalTime = new Date().getTime() - start; + TypeScript.fileResolutionScanImportsTime += totalTime; + } + + function processTripleSlashDirectives(fileName, lineMap, firstToken) { + var leadingTrivia = firstToken.leadingTrivia(); + + var position = 0; + var lineChar = { line: -1, character: -1 }; + var noDefaultLib = false; + var diagnostics = []; + var referencedFiles = []; + + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + + if (trivia.kind() === 7 /* SingleLineCommentTrivia */) { + var triviaText = trivia.fullText(); + var referencedCode = getFileReferenceFromReferencePath(fileName, lineMap, position, triviaText, diagnostics); + + if (referencedCode) { + lineMap.fillLineAndCharacterFromPosition(position, lineChar); + referencedCode.position = position; + referencedCode.length = trivia.fullWidth(); + referencedCode.line = lineChar.line; + referencedCode.character = lineChar.character; + + referencedFiles.push(referencedCode); + } + + var isNoDefaultLib = isNoDefaultLibMatch(triviaText); + if (isNoDefaultLib) { + noDefaultLib = isNoDefaultLib[3] === "true"; + } + } + + position += trivia.fullWidth(); + } + + return { noDefaultLib: noDefaultLib, diagnostics: diagnostics, referencedFiles: referencedFiles }; + } + + function preProcessFile(fileName, sourceText, readImportFiles) { + if (typeof readImportFiles === "undefined") { readImportFiles = true; } + var text = TypeScript.SimpleText.fromScriptSnapshot(sourceText); + var scanner = new TypeScript.Scanner(fileName, text, 1 /* EcmaScript5 */, scannerWindow); + + var firstToken = scanner.scan(scannerDiagnostics, false); + + var importedFiles = []; + if (readImportFiles) { + processImports(text.lineMap(), scanner, firstToken, importedFiles); + } + + var properties = processTripleSlashDirectives(fileName, text.lineMap(), firstToken); + + scannerDiagnostics.length = 0; + return { referencedFiles: properties.referencedFiles, importedFiles: importedFiles, isLibFile: properties.noDefaultLib, diagnostics: properties.diagnostics }; + } + TypeScript.preProcessFile = preProcessFile; + + function getParseOptions(settings) { + return new TypeScript.ParseOptions(settings.codeGenTarget(), settings.allowAutomaticSemicolonInsertion()); + } + TypeScript.getParseOptions = getParseOptions; + + function getReferencedFiles(fileName, sourceText) { + return preProcessFile(fileName, sourceText, false).referencedFiles; + } + TypeScript.getReferencedFiles = getReferencedFiles; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ReferenceResolutionResult = (function () { + function ReferenceResolutionResult() { + this.resolvedFiles = []; + this.diagnostics = []; + this.seenNoDefaultLibTag = false; + } + return ReferenceResolutionResult; + })(); + TypeScript.ReferenceResolutionResult = ReferenceResolutionResult; + + var ReferenceLocation = (function () { + function ReferenceLocation(filePath, lineMap, position, length, isImported) { + this.filePath = filePath; + this.lineMap = lineMap; + this.position = position; + this.length = length; + this.isImported = isImported; + } + return ReferenceLocation; + })(); + + var ReferenceResolver = (function () { + function ReferenceResolver(inputFileNames, host, useCaseSensitiveFileResolution) { + this.useCaseSensitiveFileResolution = useCaseSensitiveFileResolution; + this.inputFileNames = inputFileNames; + this.host = host; + this.visited = {}; + } + ReferenceResolver.resolve = function (inputFileNames, host, useCaseSensitiveFileResolution) { + var resolver = new ReferenceResolver(inputFileNames, host, useCaseSensitiveFileResolution); + return resolver.resolveInputFiles(); + }; + + ReferenceResolver.prototype.resolveInputFiles = function () { + var _this = this; + var result = new ReferenceResolutionResult(); + + if (!this.inputFileNames || this.inputFileNames.length <= 0) { + return result; + } + + var referenceLocation = new ReferenceLocation(null, null, 0, 0, false); + this.inputFileNames.forEach(function (fileName) { + return _this.resolveIncludedFile(fileName, referenceLocation, result); + }); + + return result; + }; + + ReferenceResolver.prototype.resolveIncludedFile = function (path, referenceLocation, resolutionResult) { + var normalizedPath = this.getNormalizedFilePath(path, referenceLocation.filePath); + + if (this.isSameFile(normalizedPath, referenceLocation.filePath)) { + if (!referenceLocation.isImported) { + resolutionResult.diagnostics.push(new TypeScript.Diagnostic(referenceLocation.filePath, referenceLocation.lineMap, referenceLocation.position, referenceLocation.length, TypeScript.DiagnosticCode.A_file_cannot_have_a_reference_to_itself, null)); + } + + return normalizedPath; + } + + if (!TypeScript.isTSFile(normalizedPath) && !TypeScript.isDTSFile(normalizedPath)) { + var dtsFile = normalizedPath + ".d.ts"; + var tsFile = normalizedPath + ".ts"; + + if (this.host.fileExists(tsFile)) { + normalizedPath = tsFile; + } else { + normalizedPath = dtsFile; + } + } + + if (!this.host.fileExists(normalizedPath)) { + if (!referenceLocation.isImported) { + resolutionResult.diagnostics.push(new TypeScript.Diagnostic(referenceLocation.filePath, referenceLocation.lineMap, referenceLocation.position, referenceLocation.length, TypeScript.DiagnosticCode.Cannot_resolve_referenced_file_0, [path])); + } + + return normalizedPath; + } + + return this.resolveFile(normalizedPath, resolutionResult); + }; + + ReferenceResolver.prototype.resolveImportedFile = function (path, referenceLocation, resolutionResult) { + var isRelativePath = TypeScript.isRelative(path); + var isRootedPath = isRelativePath ? false : TypeScript.isRooted(path); + + if (isRelativePath || isRootedPath) { + return this.resolveIncludedFile(path, referenceLocation, resolutionResult); + } else { + var parentDirectory = this.host.getParentDirectory(referenceLocation.filePath); + var searchFilePath = null; + var dtsFileName = path + ".d.ts"; + var tsFilePath = path + ".ts"; + + var start = new Date().getTime(); + + do { + currentFilePath = this.host.resolveRelativePath(tsFilePath, parentDirectory); + if (this.host.fileExists(currentFilePath)) { + searchFilePath = currentFilePath; + break; + } + + var currentFilePath = this.host.resolveRelativePath(dtsFileName, parentDirectory); + if (this.host.fileExists(currentFilePath)) { + searchFilePath = currentFilePath; + break; + } + + parentDirectory = this.host.getParentDirectory(parentDirectory); + } while(parentDirectory); + + TypeScript.fileResolutionImportFileSearchTime += new Date().getTime() - start; + + if (!searchFilePath) { + return path; + } + + return this.resolveFile(searchFilePath, resolutionResult); + } + }; + + ReferenceResolver.prototype.resolveFile = function (normalizedPath, resolutionResult) { + var _this = this; + var visitedPath = this.isVisited(normalizedPath); + if (!visitedPath) { + this.recordVisitedFile(normalizedPath); + + var start = new Date().getTime(); + var scriptSnapshot = this.host.getScriptSnapshot(normalizedPath); + var totalTime = new Date().getTime() - start; + TypeScript.fileResolutionIOTime += totalTime; + + var lineMap = TypeScript.LineMap1.fromScriptSnapshot(scriptSnapshot); + var preprocessedFileInformation = TypeScript.preProcessFile(normalizedPath, scriptSnapshot); + resolutionResult.diagnostics.push.apply(resolutionResult.diagnostics, preprocessedFileInformation.diagnostics); + + if (preprocessedFileInformation.isLibFile) { + resolutionResult.seenNoDefaultLibTag = true; + } + + var normalizedReferencePaths = []; + preprocessedFileInformation.referencedFiles.forEach(function (fileReference) { + var currentReferenceLocation = new ReferenceLocation(normalizedPath, lineMap, fileReference.position, fileReference.length, false); + var normalizedReferencePath = _this.resolveIncludedFile(fileReference.path, currentReferenceLocation, resolutionResult); + normalizedReferencePaths.push(normalizedReferencePath); + }); + + var normalizedImportPaths = []; + for (var i = 0; i < preprocessedFileInformation.importedFiles.length; i++) { + var fileImport = preprocessedFileInformation.importedFiles[i]; + var currentReferenceLocation = new ReferenceLocation(normalizedPath, lineMap, fileImport.position, fileImport.length, true); + var normalizedImportPath = this.resolveImportedFile(fileImport.path, currentReferenceLocation, resolutionResult); + normalizedImportPaths.push(normalizedImportPath); + } + + resolutionResult.resolvedFiles.push({ + path: normalizedPath, + referencedFiles: normalizedReferencePaths, + importedFiles: normalizedImportPaths + }); + } else { + normalizedPath = visitedPath; + } + + return normalizedPath; + }; + + ReferenceResolver.prototype.getNormalizedFilePath = function (path, parentFilePath) { + var parentFileDirectory = parentFilePath ? this.host.getParentDirectory(parentFilePath) : ""; + var normalizedPath = this.host.resolveRelativePath(path, parentFileDirectory); + return normalizedPath; + }; + + ReferenceResolver.prototype.getUniqueFileId = function (filePath) { + return this.useCaseSensitiveFileResolution ? filePath : filePath.toLocaleUpperCase(); + }; + + ReferenceResolver.prototype.recordVisitedFile = function (filePath) { + this.visited[this.getUniqueFileId(filePath)] = filePath; + }; + + ReferenceResolver.prototype.isVisited = function (filePath) { + return this.visited[this.getUniqueFileId(filePath)]; + }; + + ReferenceResolver.prototype.isSameFile = function (filePath1, filePath2) { + if (!filePath1 || !filePath2) { + return false; + } + + if (this.useCaseSensitiveFileResolution) { + return filePath1 === filePath2; + } else { + return filePath1.toLocaleUpperCase() === filePath2.toLocaleUpperCase(); + } + }; + return ReferenceResolver; + })(); + TypeScript.ReferenceResolver = ReferenceResolver; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextWriter = (function () { + function TextWriter(name, writeByteOrderMark, outputFileType) { + this.name = name; + this.writeByteOrderMark = writeByteOrderMark; + this.outputFileType = outputFileType; + this.contents = ""; + this.onNewLine = true; + } + TextWriter.prototype.Write = function (s) { + this.contents += s; + this.onNewLine = false; + }; + + TextWriter.prototype.WriteLine = function (s) { + this.contents += s; + this.contents += TypeScript.newLine(); + this.onNewLine = true; + }; + + TextWriter.prototype.Close = function () { + }; + + TextWriter.prototype.getOutputFile = function () { + return new TypeScript.OutputFile(this.name, this.writeByteOrderMark, this.contents, this.outputFileType); + }; + return TextWriter; + })(); + TypeScript.TextWriter = TextWriter; + + var DeclarationEmitter = (function () { + function DeclarationEmitter(emittingFileName, document, compiler, emitOptions, semanticInfoChain) { + this.emittingFileName = emittingFileName; + this.document = document; + this.compiler = compiler; + this.emitOptions = emitOptions; + this.semanticInfoChain = semanticInfoChain; + this.declFile = null; + this.indenter = new TypeScript.Indenter(); + this.emittedReferencePaths = false; + this.declFile = new TextWriter(emittingFileName, this.document.byteOrderMark !== 0 /* None */, 2 /* Declaration */); + } + DeclarationEmitter.prototype.getOutputFile = function () { + return this.declFile.getOutputFile(); + }; + + DeclarationEmitter.prototype.emitDeclarations = function (sourceUnit) { + this.emitDeclarationsForSourceUnit(sourceUnit); + }; + + DeclarationEmitter.prototype.emitDeclarationsForList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + this.emitDeclarationsForAST(list.childAt(i)); + } + }; + + DeclarationEmitter.prototype.emitSeparatedList = function (list) { + for (var i = 0, n = list.nonSeparatorCount(); i < n; i++) { + this.emitDeclarationsForAST(list.nonSeparatorAt(i)); + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForAST = function (ast) { + switch (ast.kind()) { + case 148 /* VariableStatement */: + return this.emitDeclarationsForVariableStatement(ast); + case 141 /* PropertySignature */: + return this.emitPropertySignature(ast); + case 225 /* VariableDeclarator */: + return this.emitVariableDeclarator(ast, true, true); + case 136 /* MemberVariableDeclaration */: + return this.emitDeclarationsForMemberVariableDeclaration(ast); + case 137 /* ConstructorDeclaration */: + return this.emitDeclarationsForConstructorDeclaration(ast); + case 139 /* GetAccessor */: + return this.emitDeclarationsForGetAccessor(ast); + case 140 /* SetAccessor */: + return this.emitDeclarationsForSetAccessor(ast); + case 138 /* IndexMemberDeclaration */: + return this.emitIndexMemberDeclaration(ast); + case 144 /* IndexSignature */: + return this.emitIndexSignature(ast); + case 142 /* CallSignature */: + return this.emitCallSignature(ast); + case 143 /* ConstructSignature */: + return this.emitConstructSignature(ast); + case 145 /* MethodSignature */: + return this.emitMethodSignature(ast); + case 129 /* FunctionDeclaration */: + return this.emitDeclarationsForFunctionDeclaration(ast); + case 135 /* MemberFunctionDeclaration */: + return this.emitMemberFunctionDeclaration(ast); + case 131 /* ClassDeclaration */: + return this.emitDeclarationsForClassDeclaration(ast); + case 128 /* InterfaceDeclaration */: + return this.emitDeclarationsForInterfaceDeclaration(ast); + case 133 /* ImportDeclaration */: + return this.emitDeclarationsForImportDeclaration(ast); + case 130 /* ModuleDeclaration */: + return this.emitDeclarationsForModuleDeclaration(ast); + case 132 /* EnumDeclaration */: + return this.emitDeclarationsForEnumDeclaration(ast); + case 134 /* ExportAssignment */: + return this.emitDeclarationsForExportAssignment(ast); + } + }; + + DeclarationEmitter.prototype.getIndentString = function (declIndent) { + if (typeof declIndent === "undefined") { declIndent = false; } + return this.indenter.getIndent(); + }; + + DeclarationEmitter.prototype.emitIndent = function () { + this.declFile.Write(this.getIndentString()); + }; + + DeclarationEmitter.prototype.canEmitDeclarations = function (declAST) { + var container = DeclarationEmitter.getEnclosingContainer(declAST); + if (container.kind() === 130 /* ModuleDeclaration */ || container.kind() === 120 /* SourceUnit */) { + var pullDecl = this.semanticInfoChain.getDeclForAST(declAST); + if (!TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */)) { + var start = new Date().getTime(); + var declSymbol = this.semanticInfoChain.getSymbolForAST(declAST); + var result = declSymbol && declSymbol.isExternallyVisible(); + TypeScript.declarationEmitIsExternallyVisibleTime += new Date().getTime() - start; + + return result; + } + } + + return true; + }; + + DeclarationEmitter.prototype.getDeclFlagsString = function (pullDecl, typeString) { + var result = this.getIndentString(); + var pullFlags = pullDecl.flags; + + if (TypeScript.hasFlag(pullFlags, 16 /* Static */)) { + if (TypeScript.hasFlag(pullFlags, 2 /* Private */)) { + result += "private "; + } + result += "static "; + } else { + if (TypeScript.hasFlag(pullFlags, 2 /* Private */)) { + result += "private "; + } else if (TypeScript.hasFlag(pullFlags, 4 /* Public */)) { + result += "public "; + } else { + var emitDeclare = !TypeScript.hasFlag(pullFlags, 1 /* Exported */); + + var declAST = this.semanticInfoChain.getASTForDecl(pullDecl); + var container = DeclarationEmitter.getEnclosingContainer(declAST); + + var isExternalModule = container.kind() === 120 /* SourceUnit */ && this.document.isExternalModule(); + + if (isExternalModule && TypeScript.hasFlag(pullFlags, 1 /* Exported */)) { + result += "export "; + emitDeclare = true; + } + + if (isExternalModule || container.kind() === 120 /* SourceUnit */) { + if (emitDeclare && typeString !== "interface" && typeString !== "import") { + result += "declare "; + } + } + + result += typeString + " "; + } + } + + return result; + }; + + DeclarationEmitter.prototype.emitDeclFlags = function (declarationAST, typeString) { + this.declFile.Write(this.getDeclFlagsString(this.semanticInfoChain.getDeclForAST(declarationAST), typeString)); + }; + + 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 if (memberName.isArray()) { + 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 (ast, type) { + var declarationContainerAst = DeclarationEmitter.getEnclosingContainer(ast); + + var start = new Date().getTime(); + var declarationContainerDecl = this.semanticInfoChain.getDeclForAST(declarationContainerAst); + + var declarationPullSymbol = declarationContainerDecl.getSymbol(); + TypeScript.declarationEmitTypeSignatureTime += new Date().getTime() - start; + + var isNotAGenericType = ast.kind() !== 126 /* GenericType */; + + var typeNameMembers = type.getScopedNameEx(declarationPullSymbol, false, false, false, false, false, isNotAGenericType); + this.emitTypeNamesMember(typeNameMembers); + }; + + DeclarationEmitter.prototype.emitComment = function (comment) { + var text = TypeScript.getTrimmedTextLines(comment); + if (this.declFile.onNewLine) { + this.emitIndent(); + } else if (comment.kind() !== 6 /* MultiLineCommentTrivia */) { + 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.kind() !== 6 /* MultiLineCommentTrivia */) { + this.declFile.WriteLine(""); + } else { + this.declFile.Write(" "); + } + }; + + DeclarationEmitter.prototype.emitDeclarationComments = function (astOrSymbol, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + if (this.emitOptions.compilationSettings().removeComments()) { + return; + } + + var declComments = astOrSymbol.docComments ? astOrSymbol.docComments() : TypeScript.ASTHelpers.docComments(astOrSymbol); + this.writeDeclarationComments(declComments, endLine); + }; + + DeclarationEmitter.prototype.writeDeclarationComments = function (declComments, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + 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.emitTypeOfVariableDeclaratorOrParameter = function (boundDecl) { + var start = new Date().getTime(); + var decl = this.semanticInfoChain.getDeclForAST(boundDecl); + var pullSymbol = decl.getSymbol(); + TypeScript.declarationEmitGetBoundDeclTypeTime += new Date().getTime() - start; + + var type = pullSymbol.type; + TypeScript.Debug.assert(type); + + this.declFile.Write(": "); + this.emitTypeSignature(boundDecl, type); + }; + + DeclarationEmitter.prototype.emitPropertySignature = function (varDecl) { + this.emitDeclarationComments(varDecl); + this.emitIndent(); + this.declFile.Write(varDecl.propertyName.text()); + if (varDecl.questionToken) { + this.declFile.Write("?"); + } + + this.emitTypeOfVariableDeclaratorOrParameter(varDecl); + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitVariableDeclarator = function (varDecl, isFirstVarInList, isLastVarInList) { + if (this.canEmitDeclarations(varDecl)) { + this.emitDeclarationComments(varDecl); + + if (isFirstVarInList) { + this.emitDeclFlags(varDecl, "var"); + } + + this.declFile.Write(varDecl.propertyName.text()); + + if (!TypeScript.hasModifier(TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), 2 /* Private */)) { + this.emitTypeOfVariableDeclaratorOrParameter(varDecl); + } + + if (isLastVarInList) { + this.declFile.WriteLine(";"); + } else { + this.declFile.Write(", "); + } + } + }; + + DeclarationEmitter.prototype.emitClassElementModifiers = function (modifiers) { + if (TypeScript.hasModifier(modifiers, 16 /* Static */)) { + if (TypeScript.hasModifier(modifiers, 2 /* Private */)) { + this.declFile.Write("private "); + } + this.declFile.Write("static "); + } else { + if (TypeScript.hasModifier(modifiers, 2 /* Private */)) { + this.declFile.Write("private "); + } else { + this.declFile.Write("public "); + } + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForMemberVariableDeclaration = function (varDecl) { + if (this.canEmitDeclarations(varDecl)) { + this.emitDeclarationComments(varDecl); + + this.declFile.Write(this.getIndentString()); + this.emitClassElementModifiers(varDecl.modifiers); + ; + + this.declFile.Write(varDecl.variableDeclarator.propertyName.text()); + + if (!TypeScript.hasModifier(varDecl.modifiers, 2 /* Private */)) { + this.emitTypeOfVariableDeclaratorOrParameter(varDecl); + } + + this.declFile.WriteLine(";"); + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForVariableStatement = function (variableStatement) { + this.emitDeclarationsForVariableDeclaration(variableStatement.declaration); + }; + + DeclarationEmitter.prototype.emitDeclarationsForVariableDeclaration = function (variableDeclaration) { + var varListCount = variableDeclaration.declarators.nonSeparatorCount(); + for (var i = 0; i < varListCount; i++) { + this.emitVariableDeclarator(variableDeclaration.declarators.nonSeparatorAt(i), i === 0, i === varListCount - 1); + } + }; + + DeclarationEmitter.prototype.emitArgDecl = function (argDecl, id, isOptional, isPrivate) { + this.indenter.increaseIndent(); + + this.emitDeclarationComments(argDecl, false); + this.declFile.Write(id.text()); + if (isOptional) { + this.declFile.Write("?"); + } + + this.indenter.decreaseIndent(); + + if (!isPrivate) { + this.emitTypeOfVariableDeclaratorOrParameter(argDecl); + } + }; + + DeclarationEmitter.prototype.isOverloadedCallSignature = function (funcDecl) { + var start = new Date().getTime(); + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSymbol = functionDecl.getSymbol(); + TypeScript.declarationEmitIsOverloadedCallSignatureTime += new Date().getTime() - start; + + var funcTypeSymbol = funcSymbol.type; + var signatures = funcTypeSymbol.getCallSignatures(); + var result = signatures && signatures.length > 1; + + return result; + }; + + DeclarationEmitter.prototype.emitDeclarationsForConstructorDeclaration = function (funcDecl) { + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + var funcTypeSymbol = funcSymbol.type; + if (funcDecl.block) { + var constructSignatures = funcTypeSymbol.getConstructSignatures(); + if (constructSignatures && constructSignatures.length > 1) { + return; + } + } + + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write("constructor"); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitParameterList = function (isPrivate, parameterList) { + this.declFile.Write("("); + this.emitParameters(isPrivate, TypeScript.ASTHelpers.parametersFromParameterList(parameterList)); + this.declFile.Write(")"); + }; + + DeclarationEmitter.prototype.emitParameters = function (isPrivate, parameterList) { + var hasLastParameterRestParameter = parameterList.lastParameterIsRest(); + var argsLen = parameterList.length; + if (hasLastParameterRestParameter) { + argsLen--; + } + + for (var i = 0; i < argsLen; i++) { + this.emitArgDecl(parameterList.astAt(i), parameterList.identifierAt(i), parameterList.isOptionalAt(i), isPrivate); + if (i < (argsLen - 1)) { + this.declFile.Write(", "); + } + } + + if (hasLastParameterRestParameter) { + if (parameterList.length > 1) { + this.declFile.Write(", ..."); + } else { + this.declFile.Write("..."); + } + + var index = parameterList.length - 1; + this.emitArgDecl(parameterList.astAt(index), parameterList.identifierAt(index), parameterList.isOptionalAt(index), isPrivate); + } + }; + + DeclarationEmitter.prototype.emitMemberFunctionDeclaration = function (funcDecl) { + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + var funcTypeSymbol = funcSymbol.type; + if (funcDecl.block) { + var constructSignatures = funcTypeSymbol.getConstructSignatures(); + if (constructSignatures && constructSignatures.length > 1) { + return; + } else if (this.isOverloadedCallSignature(funcDecl)) { + return; + } + } else if (TypeScript.hasModifier(funcDecl.modifiers, 2 /* Private */) && this.isOverloadedCallSignature(funcDecl)) { + var callSignatures = funcTypeSymbol.getCallSignatures(); + TypeScript.Debug.assert(callSignatures && callSignatures.length > 1); + var firstSignature = callSignatures[0].isDefinition() ? callSignatures[1] : callSignatures[0]; + var firstSignatureDecl = firstSignature.getDeclarations()[0]; + var firstFuncDecl = this.semanticInfoChain.getASTForDecl(firstSignatureDecl); + if (firstFuncDecl !== funcDecl) { + return; + } + } + + if (!this.canEmitDeclarations(funcDecl)) { + return; + } + + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitDeclarationComments(funcDecl); + + this.emitDeclFlags(funcDecl, "function"); + var id = funcDecl.propertyName.text(); + this.declFile.Write(id); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + var isPrivate = TypeScript.hasModifier(funcDecl.modifiers, 2 /* Private */); + + this.emitParameterList(isPrivate, funcDecl.callSignature.parameterList); + + if (!isPrivate) { + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + this.emitTypeSignature(funcDecl, returnType); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitCallSignature = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + this.emitDeclarationComments(funcDecl); + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.typeParameterList, funcSignature); + + this.emitIndent(); + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitConstructSignature = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write("new"); + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitMethodSignature = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write(funcDecl.propertyName.text()); + if (funcDecl.questionToken) { + this.declFile.Write("? "); + } + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForFunctionDeclaration = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + if (funcDecl.block) { + var funcTypeSymbol = funcSymbol.type; + var constructSignatures = funcTypeSymbol.getConstructSignatures(); + if (constructSignatures && constructSignatures.length > 1) { + return; + } else if (this.isOverloadedCallSignature(funcDecl)) { + return; + } + } + + if (!this.canEmitDeclarations(funcDecl)) { + return; + } + + this.emitDeclarationComments(funcDecl); + + var id = funcDecl.identifier.text(); + this.emitDeclFlags(funcDecl, "function"); + if (id !== "" || !funcDecl.identifier || funcDecl.identifier.text().length > 0) { + this.declFile.Write(id); + } else if (funcPullDecl.kind === 2097152 /* ConstructSignature */) { + this.declFile.Write("new"); + } + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitIndexMemberDeclaration = function (funcDecl) { + this.emitDeclarationsForAST(funcDecl.indexSignature); + }; + + DeclarationEmitter.prototype.emitIndexSignature = function (funcDecl) { + if (!this.canEmitDeclarations(funcDecl)) { + return; + } + + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write("["); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameter(funcDecl.parameter)); + this.declFile.Write("]"); + + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSignature = funcPullDecl.getSignatureSymbol(); + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + this.emitTypeSignature(funcDecl, returnType); + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitBaseList = function (bases, useExtendsList) { + if (bases && (bases.nonSeparatorCount() > 0)) { + var qual = useExtendsList ? "extends" : "implements"; + this.declFile.Write(" " + qual + " "); + var basesLen = bases.nonSeparatorCount(); + for (var i = 0; i < basesLen; i++) { + if (i > 0) { + this.declFile.Write(", "); + } + var base = bases.nonSeparatorAt(i); + var baseType = this.semanticInfoChain.getSymbolForAST(base); + this.emitTypeSignature(base, baseType); + } + } + }; + + DeclarationEmitter.prototype.emitAccessorDeclarationComments = function (funcDecl) { + if (this.emitOptions.compilationSettings().removeComments()) { + return; + } + + var start = new Date().getTime(); + var accessors = TypeScript.PullHelpers.getGetterAndSetterFunction(funcDecl, this.semanticInfoChain); + TypeScript.declarationEmitGetAccessorFunctionTime += new Date().getTime(); + + var comments = []; + if (accessors.getter) { + comments = comments.concat(TypeScript.ASTHelpers.docComments(accessors.getter)); + } + if (accessors.setter) { + comments = comments.concat(TypeScript.ASTHelpers.docComments(accessors.setter)); + } + + this.writeDeclarationComments(comments); + }; + + DeclarationEmitter.prototype.emitDeclarationsForGetAccessor = function (funcDecl) { + this.emitMemberAccessorDeclaration(funcDecl, funcDecl.modifiers, funcDecl.propertyName); + }; + + DeclarationEmitter.prototype.emitDeclarationsForSetAccessor = function (funcDecl) { + this.emitMemberAccessorDeclaration(funcDecl, funcDecl.modifiers, funcDecl.propertyName); + }; + + DeclarationEmitter.prototype.emitMemberAccessorDeclaration = function (funcDecl, modifiers, name) { + var start = new Date().getTime(); + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain); + TypeScript.declarationEmitGetAccessorFunctionTime += new Date().getTime(); + + if (funcDecl.kind() === 140 /* SetAccessor */ && accessorSymbol.getGetter()) { + return; + } + + var isPrivate = TypeScript.hasModifier(modifiers, 2 /* Private */); + this.emitAccessorDeclarationComments(funcDecl); + this.declFile.Write(this.getIndentString()); + this.emitClassElementModifiers(modifiers); + this.declFile.Write(name.text()); + if (!isPrivate) { + this.declFile.Write(" : "); + var type = accessorSymbol.type; + this.emitTypeSignature(funcDecl, type); + } + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { + var argsLen = funcDecl.callSignature.parameterList.parameters.nonSeparatorCount(); + if (TypeScript.lastParameterIsRest(funcDecl.callSignature.parameterList)) { + argsLen--; + } + + for (var i = 0; i < argsLen; i++) { + var parameter = funcDecl.callSignature.parameterList.parameters.nonSeparatorAt(i); + var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter); + if (TypeScript.hasFlag(parameterDecl.flags, 8388608 /* PropertyParameter */)) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.emitDeclarationComments(parameter); + this.declFile.Write(this.getIndentString()); + this.emitClassElementModifiers(parameter.modifiers); + this.declFile.Write(parameter.identifier.text()); + + if (!TypeScript.hasModifier(parameter.modifiers, 2 /* Private */)) { + this.emitTypeOfVariableDeclaratorOrParameter(parameter); + } + this.declFile.WriteLine(";"); + } + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForClassDeclaration = function (classDecl) { + if (!this.canEmitDeclarations(classDecl)) { + return; + } + + var className = classDecl.identifier.text(); + this.emitDeclarationComments(classDecl); + var classPullDecl = this.semanticInfoChain.getDeclForAST(classDecl); + this.emitDeclFlags(classDecl, "class"); + this.declFile.Write(className); + + this.emitTypeParameters(classDecl.typeParameterList); + this.emitHeritageClauses(classDecl.heritageClauses); + this.declFile.WriteLine(" {"); + + this.indenter.increaseIndent(); + var constructorDecl = TypeScript.getLastConstructor(classDecl); + if (constructorDecl) { + this.emitClassMembersFromConstructorDefinition(constructorDecl); + } + + this.emitDeclarationsForList(classDecl.classElements); + + this.indenter.decreaseIndent(); + + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitHeritageClauses = function (clauses) { + if (clauses) { + for (var i = 0, n = clauses.childCount(); i < n; i++) { + this.emitHeritageClause(clauses.childAt(i)); + } + } + }; + + DeclarationEmitter.prototype.emitHeritageClause = function (clause) { + this.emitBaseList(clause.typeNames, clause.kind() === 230 /* ExtendsHeritageClause */); + }; + + DeclarationEmitter.getEnclosingContainer = function (ast) { + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(ast); + ast = enclosingModule || ast; + + ast = ast.parent; + while (ast) { + if (ast.kind() === 131 /* ClassDeclaration */ || ast.kind() === 128 /* InterfaceDeclaration */ || ast.kind() === 130 /* ModuleDeclaration */ || ast.kind() === 120 /* SourceUnit */) { + return ast; + } + + ast = ast.parent; + } + + return null; + }; + + DeclarationEmitter.prototype.emitTypeParameters = function (typeParams, funcSignature) { + if (!typeParams || !typeParams.typeParameters.nonSeparatorCount()) { + return; + } + + this.declFile.Write("<"); + var containerAst = DeclarationEmitter.getEnclosingContainer(typeParams); + + var start = new Date().getTime(); + var containerDecl = this.semanticInfoChain.getDeclForAST(containerAst); + var containerSymbol = containerDecl.getSymbol(); + TypeScript.declarationEmitGetTypeParameterSymbolTime += new Date().getTime() - start; + + var typars; + if (funcSignature) { + typars = funcSignature.getTypeParameters(); + } else { + typars = containerSymbol.getTypeArgumentsOrTypeParameters(); + } + + for (var i = 0; i < typars.length; i++) { + if (i) { + this.declFile.Write(", "); + } + + var memberName = typars[i].getScopedNameEx(containerSymbol, false, true); + this.emitTypeNamesMember(memberName); + } + + this.declFile.Write(">"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForInterfaceDeclaration = function (interfaceDecl) { + if (!this.canEmitDeclarations(interfaceDecl)) { + return; + } + + var interfaceName = interfaceDecl.identifier.text(); + this.emitDeclarationComments(interfaceDecl); + var interfacePullDecl = this.semanticInfoChain.getDeclForAST(interfaceDecl); + this.emitDeclFlags(interfaceDecl, "interface"); + this.declFile.Write(interfaceName); + + this.emitTypeParameters(interfaceDecl.typeParameterList); + this.emitHeritageClauses(interfaceDecl.heritageClauses); + this.declFile.WriteLine(" {"); + + this.indenter.increaseIndent(); + + this.emitSeparatedList(interfaceDecl.body.typeMembers); + + this.indenter.decreaseIndent(); + + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForImportDeclaration = function (importDeclAST) { + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); + var importSymbol = importDecl.getSymbol(); + var isExportedImportDecl = TypeScript.hasModifier(importDeclAST.modifiers, 1 /* Exported */); + + if (isExportedImportDecl || importSymbol.typeUsedExternally() || TypeScript.PullContainerSymbol.usedAsSymbol(importSymbol.getContainer(), importSymbol)) { + this.emitDeclarationComments(importDeclAST); + this.emitIndent(); + if (isExportedImportDecl) { + this.declFile.Write("export "); + } + this.declFile.Write("import "); + this.declFile.Write(importDeclAST.identifier.text() + " = "); + if (importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + this.declFile.WriteLine("require(" + importDeclAST.moduleReference.stringLiteral.text() + ");"); + } else { + this.declFile.WriteLine(TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(importDeclAST.moduleReference.moduleName) + ";"); + } + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForEnumDeclaration = function (moduleDecl) { + if (!this.canEmitDeclarations(moduleDecl)) { + return; + } + + this.emitDeclarationComments(moduleDecl); + var modulePullDecl = this.semanticInfoChain.getDeclForAST(moduleDecl); + this.emitDeclFlags(moduleDecl, "enum"); + this.declFile.WriteLine(moduleDecl.identifier.text() + " {"); + + this.indenter.increaseIndent(); + var membersLen = moduleDecl.enumElements.nonSeparatorCount(); + for (var j = 0; j < membersLen; j++) { + var memberDecl = moduleDecl.enumElements.nonSeparatorAt(j); + var enumElement = memberDecl; + var enumElementDecl = this.semanticInfoChain.getDeclForAST(enumElement); + this.emitDeclarationComments(enumElement); + this.emitIndent(); + this.declFile.Write(enumElement.propertyName.text()); + if (enumElementDecl.constantValue !== null) { + this.declFile.Write(" = " + enumElementDecl.constantValue); + } + this.declFile.WriteLine(","); + } + this.indenter.decreaseIndent(); + + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForModuleDeclaration = function (moduleDecl) { + var name = moduleDecl.stringLiteral || TypeScript.ArrayUtilities.first(TypeScript.ASTHelpers.getModuleNames(moduleDecl.name)); + if (!this.canEmitDeclarations(name)) { + return; + } + + this.emitDeclarationComments(moduleDecl); + this.emitDeclFlags(name, "module"); + + if (moduleDecl.stringLiteral) { + this.declFile.Write(moduleDecl.stringLiteral.text()); + } else { + this.declFile.Write(TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(moduleDecl.name)); + } + + this.declFile.WriteLine(" {"); + this.indenter.increaseIndent(); + + this.emitDeclarationsForList(moduleDecl.moduleElements); + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForExportAssignment = function (ast) { + this.emitIndent(); + this.declFile.Write("export = "); + this.declFile.Write(ast.identifier.text()); + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.resolveScriptReference = function (document, reference) { + if (!this.emitOptions.compilationSettings().noResolve() || TypeScript.isRooted(reference)) { + return reference; + } + + var documentDir = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(TypeScript.getRootFilePath(document.fileName))); + var resolvedReferencePath = this.emitOptions.resolvePath(documentDir + reference); + return resolvedReferencePath; + }; + + DeclarationEmitter.prototype.emitReferencePaths = function (sourceUnit) { + if (this.emittedReferencePaths) { + return; + } + + var documents = []; + if (this.document.emitToOwnOutputFile()) { + var scriptReferences = this.document.referencedFiles; + var addedGlobalDocument = false; + for (var j = 0; j < scriptReferences.length; j++) { + var currentReference = this.resolveScriptReference(this.document, scriptReferences[j]); + var document = this.compiler.getDocument(currentReference); + + if (document && (document.emitToOwnOutputFile() || document.isDeclareFile() || !addedGlobalDocument)) { + documents = documents.concat(document); + + if (!document.isDeclareFile() && document.isExternalModule()) { + addedGlobalDocument = true; + } + } + } + } else { + var fileNames = this.compiler.fileNames(); + for (var i = 0; i < fileNames.length; i++) { + var doc = this.compiler.getDocument(fileNames[i]); + if (!doc.isDeclareFile() && !doc.isExternalModule()) { + var scriptReferences = doc.referencedFiles; + for (var j = 0; j < scriptReferences.length; j++) { + var currentReference = this.resolveScriptReference(doc, scriptReferences[j]); + var document = this.compiler.getDocument(currentReference); + + if (document && (document.isDeclareFile() || document.isExternalModule())) { + for (var k = 0; k < documents.length; k++) { + if (documents[k] === document) { + break; + } + } + + if (k === documents.length) { + documents = documents.concat(document); + } + } + } + } + } + } + + var emittingFilePath = documents.length ? TypeScript.getRootFilePath(this.emittingFileName) : null; + for (var i = 0; i < documents.length; i++) { + var document = documents[i]; + var declFileName; + if (document.isDeclareFile()) { + declFileName = document.fileName; + } else { + declFileName = this.compiler.mapOutputFileName(document, this.emitOptions, TypeScript.TypeScriptCompiler.mapToDTSFileName); + } + + declFileName = TypeScript.getRelativePathToFixedPath(emittingFilePath, declFileName, false); + this.declFile.WriteLine('/// '); + } + + this.emittedReferencePaths = true; + }; + + DeclarationEmitter.prototype.emitDeclarationsForSourceUnit = function (sourceUnit) { + this.emitReferencePaths(sourceUnit); + this.emitDeclarationsForList(sourceUnit.moduleElements); + }; + return DeclarationEmitter; + })(); + TypeScript.DeclarationEmitter = DeclarationEmitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var BloomFilter = (function () { + function BloomFilter(expectedCount) { + var m = Math.max(1, BloomFilter.computeM(expectedCount)); + var k = Math.max(1, BloomFilter.computeK(expectedCount)); + ; + + var sizeInEvenBytes = (m + 7) & ~7; + + this.bitArray = []; + for (var i = 0, len = sizeInEvenBytes; i < len; i++) { + this.bitArray[i] = false; + } + this.hashFunctionCount = k; + } + BloomFilter.computeM = function (expectedCount) { + var p = BloomFilter.falsePositiveProbability; + var n = expectedCount; + + var numerator = n * Math.log(p); + var denominator = Math.log(1.0 / Math.pow(2.0, Math.log(2.0))); + return Math.ceil(numerator / denominator); + }; + + BloomFilter.computeK = function (expectedCount) { + var n = expectedCount; + var m = BloomFilter.computeM(expectedCount); + + var temp = Math.log(2.0) * m / n; + return Math.round(temp); + }; + + BloomFilter.prototype.computeHash = function (key, seed) { + return TypeScript.Hash.computeMurmur2StringHashCode(key, seed); + }; + + BloomFilter.prototype.addKeys = function (keys) { + for (var name in keys) { + if (keys[name]) { + this.add(name); + } + } + }; + + BloomFilter.prototype.add = function (value) { + for (var i = 0; i < this.hashFunctionCount; i++) { + var hash = this.computeHash(value, i); + hash = hash % this.bitArray.length; + this.bitArray[Math.abs(hash)] = true; + } + }; + + BloomFilter.prototype.probablyContains = function (value) { + for (var i = 0; i < this.hashFunctionCount; i++) { + var hash = this.computeHash(value, i); + hash = hash % this.bitArray.length; + if (!this.bitArray[Math.abs(hash)]) { + return false; + } + } + + return true; + }; + + BloomFilter.prototype.isEquivalent = function (filter) { + return BloomFilter.isEquivalent(this.bitArray, filter.bitArray) && this.hashFunctionCount === filter.hashFunctionCount; + }; + + BloomFilter.isEquivalent = function (array1, array2) { + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; i++) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; + }; + BloomFilter.falsePositiveProbability = 0.0001; + return BloomFilter; + })(); + TypeScript.BloomFilter = BloomFilter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var IdentifierWalker = (function (_super) { + __extends(IdentifierWalker, _super); + function IdentifierWalker(list) { + _super.call(this); + this.list = list; + } + IdentifierWalker.prototype.visitToken = function (token) { + this.list[token.text()] = true; + }; + return IdentifierWalker; + })(TypeScript.SyntaxWalker); + TypeScript.IdentifierWalker = IdentifierWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CompilationSettings = (function () { + function CompilationSettings() { + this.propagateEnumConstants = false; + this.removeComments = false; + this.watch = false; + this.noResolve = false; + this.allowAutomaticSemicolonInsertion = true; + this.noImplicitAny = false; + this.noLib = false; + this.codeGenTarget = 0 /* EcmaScript3 */; + this.moduleGenTarget = 0 /* Unspecified */; + this.outFileOption = ""; + this.outDirOption = ""; + this.mapSourceFiles = false; + this.mapRoot = ""; + this.sourceRoot = ""; + this.generateDeclarationFiles = false; + this.useCaseSensitiveFileResolution = false; + this.gatherDiagnostics = false; + this.codepage = null; + this.createFileLog = false; + } + return CompilationSettings; + })(); + TypeScript.CompilationSettings = CompilationSettings; + + var ImmutableCompilationSettings = (function () { + function ImmutableCompilationSettings(propagateEnumConstants, removeComments, watch, noResolve, allowAutomaticSemicolonInsertion, noImplicitAny, noLib, codeGenTarget, moduleGenTarget, outFileOption, outDirOption, mapSourceFiles, mapRoot, sourceRoot, generateDeclarationFiles, useCaseSensitiveFileResolution, gatherDiagnostics, codepage, createFileLog) { + this._propagateEnumConstants = propagateEnumConstants; + this._removeComments = removeComments; + this._watch = watch; + this._noResolve = noResolve; + this._allowAutomaticSemicolonInsertion = allowAutomaticSemicolonInsertion; + this._noImplicitAny = noImplicitAny; + this._noLib = noLib; + this._codeGenTarget = codeGenTarget; + this._moduleGenTarget = moduleGenTarget; + this._outFileOption = outFileOption; + this._outDirOption = outDirOption; + this._mapSourceFiles = mapSourceFiles; + this._mapRoot = mapRoot; + this._sourceRoot = sourceRoot; + this._generateDeclarationFiles = generateDeclarationFiles; + this._useCaseSensitiveFileResolution = useCaseSensitiveFileResolution; + this._gatherDiagnostics = gatherDiagnostics; + this._codepage = codepage; + this._createFileLog = createFileLog; + } + ImmutableCompilationSettings.prototype.propagateEnumConstants = function () { + return this._propagateEnumConstants; + }; + ImmutableCompilationSettings.prototype.removeComments = function () { + return this._removeComments; + }; + ImmutableCompilationSettings.prototype.watch = function () { + return this._watch; + }; + ImmutableCompilationSettings.prototype.noResolve = function () { + return this._noResolve; + }; + ImmutableCompilationSettings.prototype.allowAutomaticSemicolonInsertion = function () { + return this._allowAutomaticSemicolonInsertion; + }; + ImmutableCompilationSettings.prototype.noImplicitAny = function () { + return this._noImplicitAny; + }; + ImmutableCompilationSettings.prototype.noLib = function () { + return this._noLib; + }; + ImmutableCompilationSettings.prototype.codeGenTarget = function () { + return this._codeGenTarget; + }; + ImmutableCompilationSettings.prototype.moduleGenTarget = function () { + return this._moduleGenTarget; + }; + ImmutableCompilationSettings.prototype.outFileOption = function () { + return this._outFileOption; + }; + ImmutableCompilationSettings.prototype.outDirOption = function () { + return this._outDirOption; + }; + ImmutableCompilationSettings.prototype.mapSourceFiles = function () { + return this._mapSourceFiles; + }; + ImmutableCompilationSettings.prototype.mapRoot = function () { + return this._mapRoot; + }; + ImmutableCompilationSettings.prototype.sourceRoot = function () { + return this._sourceRoot; + }; + ImmutableCompilationSettings.prototype.generateDeclarationFiles = function () { + return this._generateDeclarationFiles; + }; + ImmutableCompilationSettings.prototype.useCaseSensitiveFileResolution = function () { + return this._useCaseSensitiveFileResolution; + }; + ImmutableCompilationSettings.prototype.gatherDiagnostics = function () { + return this._gatherDiagnostics; + }; + ImmutableCompilationSettings.prototype.codepage = function () { + return this._codepage; + }; + ImmutableCompilationSettings.prototype.createFileLog = function () { + return this._createFileLog; + }; + + ImmutableCompilationSettings.defaultSettings = function () { + if (!ImmutableCompilationSettings._defaultSettings) { + ImmutableCompilationSettings._defaultSettings = ImmutableCompilationSettings.fromCompilationSettings(new CompilationSettings()); + } + + return ImmutableCompilationSettings._defaultSettings; + }; + + ImmutableCompilationSettings.fromCompilationSettings = function (settings) { + return new ImmutableCompilationSettings(settings.propagateEnumConstants, settings.removeComments, settings.watch, settings.noResolve, settings.allowAutomaticSemicolonInsertion, settings.noImplicitAny, settings.noLib, settings.codeGenTarget, settings.moduleGenTarget, settings.outFileOption, settings.outDirOption, settings.mapSourceFiles, settings.mapRoot, settings.sourceRoot, settings.generateDeclarationFiles, settings.useCaseSensitiveFileResolution, settings.gatherDiagnostics, settings.codepage, settings.createFileLog); + }; + + ImmutableCompilationSettings.prototype.toCompilationSettings = function () { + var result = new CompilationSettings(); + + var thisAsIndexable = this; + var resultAsIndexable = result; + for (var name in this) { + if (this.hasOwnProperty(name) && TypeScript.StringUtilities.startsWith(name, "_")) { + resultAsIndexable[name.substr(1)] = thisAsIndexable[name]; + } + } + + return result; + }; + return ImmutableCompilationSettings; + })(); + TypeScript.ImmutableCompilationSettings = ImmutableCompilationSettings; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (PullElementFlags) { + PullElementFlags[PullElementFlags["None"] = 0] = "None"; + PullElementFlags[PullElementFlags["Exported"] = 1] = "Exported"; + PullElementFlags[PullElementFlags["Private"] = 1 << 1] = "Private"; + PullElementFlags[PullElementFlags["Public"] = 1 << 2] = "Public"; + PullElementFlags[PullElementFlags["Ambient"] = 1 << 3] = "Ambient"; + PullElementFlags[PullElementFlags["Static"] = 1 << 4] = "Static"; + PullElementFlags[PullElementFlags["Optional"] = 1 << 7] = "Optional"; + PullElementFlags[PullElementFlags["Signature"] = 1 << 11] = "Signature"; + PullElementFlags[PullElementFlags["Enum"] = 1 << 12] = "Enum"; + PullElementFlags[PullElementFlags["ArrowFunction"] = 1 << 13] = "ArrowFunction"; + + PullElementFlags[PullElementFlags["ClassConstructorVariable"] = 1 << 14] = "ClassConstructorVariable"; + PullElementFlags[PullElementFlags["InitializedModule"] = 1 << 15] = "InitializedModule"; + PullElementFlags[PullElementFlags["InitializedDynamicModule"] = 1 << 16] = "InitializedDynamicModule"; + + PullElementFlags[PullElementFlags["MustCaptureThis"] = 1 << 18] = "MustCaptureThis"; + + PullElementFlags[PullElementFlags["DeclaredInAWithBlock"] = 1 << 21] = "DeclaredInAWithBlock"; + + PullElementFlags[PullElementFlags["HasReturnStatement"] = 1 << 22] = "HasReturnStatement"; + + PullElementFlags[PullElementFlags["PropertyParameter"] = 1 << 23] = "PropertyParameter"; + + PullElementFlags[PullElementFlags["IsAnnotatedWithAny"] = 1 << 24] = "IsAnnotatedWithAny"; + + PullElementFlags[PullElementFlags["HasDefaultArgs"] = 1 << 25] = "HasDefaultArgs"; + + PullElementFlags[PullElementFlags["ConstructorParameter"] = 1 << 26] = "ConstructorParameter"; + + PullElementFlags[PullElementFlags["ImplicitVariable"] = PullElementFlags.ClassConstructorVariable | PullElementFlags.InitializedModule | PullElementFlags.InitializedDynamicModule | PullElementFlags.Enum] = "ImplicitVariable"; + PullElementFlags[PullElementFlags["SomeInitializedModule"] = PullElementFlags.InitializedModule | PullElementFlags.InitializedDynamicModule | PullElementFlags.Enum] = "SomeInitializedModule"; + })(TypeScript.PullElementFlags || (TypeScript.PullElementFlags = {})); + var PullElementFlags = TypeScript.PullElementFlags; + + function hasModifier(modifiers, flag) { + for (var i = 0, n = modifiers.length; i < n; i++) { + if (TypeScript.hasFlag(modifiers[i], flag)) { + return true; + } + } + + return false; + } + TypeScript.hasModifier = hasModifier; + + (function (PullElementKind) { + PullElementKind[PullElementKind["None"] = 0] = "None"; + PullElementKind[PullElementKind["Global"] = 0] = "Global"; + + PullElementKind[PullElementKind["Script"] = 1 << 0] = "Script"; + PullElementKind[PullElementKind["Primitive"] = 1 << 1] = "Primitive"; + + PullElementKind[PullElementKind["Container"] = 1 << 2] = "Container"; + PullElementKind[PullElementKind["Class"] = 1 << 3] = "Class"; + PullElementKind[PullElementKind["Interface"] = 1 << 4] = "Interface"; + PullElementKind[PullElementKind["DynamicModule"] = 1 << 5] = "DynamicModule"; + PullElementKind[PullElementKind["Enum"] = 1 << 6] = "Enum"; + PullElementKind[PullElementKind["TypeAlias"] = 1 << 7] = "TypeAlias"; + PullElementKind[PullElementKind["ObjectLiteral"] = 1 << 8] = "ObjectLiteral"; + + PullElementKind[PullElementKind["Variable"] = 1 << 9] = "Variable"; + PullElementKind[PullElementKind["CatchVariable"] = 1 << 10] = "CatchVariable"; + PullElementKind[PullElementKind["Parameter"] = 1 << 11] = "Parameter"; + PullElementKind[PullElementKind["Property"] = 1 << 12] = "Property"; + PullElementKind[PullElementKind["TypeParameter"] = 1 << 13] = "TypeParameter"; + + PullElementKind[PullElementKind["Function"] = 1 << 14] = "Function"; + PullElementKind[PullElementKind["ConstructorMethod"] = 1 << 15] = "ConstructorMethod"; + PullElementKind[PullElementKind["Method"] = 1 << 16] = "Method"; + PullElementKind[PullElementKind["FunctionExpression"] = 1 << 17] = "FunctionExpression"; + + PullElementKind[PullElementKind["GetAccessor"] = 1 << 18] = "GetAccessor"; + PullElementKind[PullElementKind["SetAccessor"] = 1 << 19] = "SetAccessor"; + + PullElementKind[PullElementKind["CallSignature"] = 1 << 20] = "CallSignature"; + PullElementKind[PullElementKind["ConstructSignature"] = 1 << 21] = "ConstructSignature"; + PullElementKind[PullElementKind["IndexSignature"] = 1 << 22] = "IndexSignature"; + + PullElementKind[PullElementKind["ObjectType"] = 1 << 23] = "ObjectType"; + PullElementKind[PullElementKind["FunctionType"] = 1 << 24] = "FunctionType"; + PullElementKind[PullElementKind["ConstructorType"] = 1 << 25] = "ConstructorType"; + + PullElementKind[PullElementKind["EnumMember"] = 1 << 26] = "EnumMember"; + + PullElementKind[PullElementKind["WithBlock"] = 1 << 27] = "WithBlock"; + PullElementKind[PullElementKind["CatchBlock"] = 1 << 28] = "CatchBlock"; + + PullElementKind[PullElementKind["All"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Container | PullElementKind.Class | PullElementKind.Interface | PullElementKind.DynamicModule | PullElementKind.Enum | PullElementKind.TypeAlias | PullElementKind.ObjectLiteral | PullElementKind.Variable | PullElementKind.Parameter | PullElementKind.Property | PullElementKind.TypeParameter | PullElementKind.Function | PullElementKind.ConstructorMethod | PullElementKind.Method | PullElementKind.FunctionExpression | PullElementKind.GetAccessor | PullElementKind.SetAccessor | PullElementKind.CallSignature | PullElementKind.ConstructSignature | PullElementKind.IndexSignature | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.EnumMember | PullElementKind.WithBlock | PullElementKind.CatchBlock] = "All"; + + PullElementKind[PullElementKind["SomeFunction"] = PullElementKind.Function | PullElementKind.ConstructorMethod | PullElementKind.Method | PullElementKind.FunctionExpression | PullElementKind.GetAccessor | PullElementKind.SetAccessor] = "SomeFunction"; + + PullElementKind[PullElementKind["SomeValue"] = PullElementKind.Variable | PullElementKind.Parameter | PullElementKind.Property | PullElementKind.EnumMember | PullElementKind.SomeFunction] = "SomeValue"; + + PullElementKind[PullElementKind["SomeType"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.ObjectLiteral | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.TypeParameter] = "SomeType"; + + PullElementKind[PullElementKind["AcceptableAlias"] = PullElementKind.Variable | PullElementKind.SomeFunction | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.Container | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType] = "AcceptableAlias"; + + PullElementKind[PullElementKind["SomeContainer"] = PullElementKind.Container | PullElementKind.DynamicModule | PullElementKind.TypeAlias] = "SomeContainer"; + + PullElementKind[PullElementKind["SomeSignature"] = PullElementKind.CallSignature | PullElementKind.ConstructSignature | PullElementKind.IndexSignature] = "SomeSignature"; + + PullElementKind[PullElementKind["SomeTypeReference"] = PullElementKind.Interface | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType] = "SomeTypeReference"; + + PullElementKind[PullElementKind["SomeInstantiatableType"] = PullElementKind.Class | PullElementKind.Interface | PullElementKind.TypeParameter] = "SomeInstantiatableType"; + })(TypeScript.PullElementKind || (TypeScript.PullElementKind = {})); + var PullElementKind = TypeScript.PullElementKind; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var pullDeclID = 0; + var sentinelEmptyPullDeclArray = []; + + var PullDecl = (function () { + function PullDecl(declName, displayName, kind, declFlags, semanticInfoChain) { + this.declID = pullDeclID++; + this.flags = 0 /* None */; + this.declGroups = null; + this.childDecls = null; + this.typeParameters = null; + this.synthesizedValDecl = null; + this.containerDecl = null; + this.childDeclTypeCache = null; + this.childDeclValueCache = null; + this.childDeclNamespaceCache = null; + this.childDeclTypeParameterCache = null; + this.name = declName; + this.kind = kind; + this.flags = declFlags; + this.semanticInfoChain = semanticInfoChain; + + if (displayName !== this.name) { + this.declDisplayName = displayName; + } + } + PullDecl.prototype.fileName = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.getParentPath = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.getParentDecl = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.isExternalModule = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.getEnclosingDecl = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype._getEnclosingDeclFromParentDecl = function () { + var decl = this; + while (decl) { + switch (decl.kind) { + default: + return decl; + case 512 /* Variable */: + case 8192 /* TypeParameter */: + case 2048 /* Parameter */: + case 128 /* TypeAlias */: + case 67108864 /* EnumMember */: + } + + decl = decl.getParentDecl(); + } + + TypeScript.Debug.fail(); + }; + + PullDecl.prototype.getDisplayName = function () { + return this.declDisplayName === undefined ? this.name : this.declDisplayName; + }; + + PullDecl.prototype.setSymbol = function (symbol) { + this.semanticInfoChain.setSymbolForDecl(this, symbol); + }; + + PullDecl.prototype.ensureSymbolIsBound = function () { + if (!this.hasBeenBound() && this.kind !== 1 /* Script */) { + var binder = this.semanticInfoChain.getBinder(); + binder.bindDeclToPullSymbol(this); + } + }; + + PullDecl.prototype.getSymbol = function () { + if (this.kind === 1 /* Script */) { + return null; + } + + this.ensureSymbolIsBound(); + + return this.semanticInfoChain.getSymbolForDecl(this); + }; + + PullDecl.prototype.hasSymbol = function () { + var symbol = this.semanticInfoChain.getSymbolForDecl(this); + return !!symbol; + }; + + PullDecl.prototype.setSignatureSymbol = function (signatureSymbol) { + this.semanticInfoChain.setSignatureSymbolForDecl(this, signatureSymbol); + }; + + PullDecl.prototype.getSignatureSymbol = function () { + this.ensureSymbolIsBound(); + return this.semanticInfoChain.getSignatureSymbolForDecl(this); + }; + + PullDecl.prototype.hasSignatureSymbol = function () { + var signatureSymbol = this.semanticInfoChain.getSignatureSymbolForDecl(this); + return !!signatureSymbol; + }; + + PullDecl.prototype.setFlags = function (flags) { + this.flags = flags; + }; + + PullDecl.prototype.setFlag = function (flags) { + this.flags |= flags; + }; + + PullDecl.prototype.setValueDecl = function (valDecl) { + this.synthesizedValDecl = valDecl; + valDecl.containerDecl = this; + }; + + PullDecl.prototype.getValueDecl = function () { + return this.synthesizedValDecl; + }; + + PullDecl.prototype.getContainerDecl = function () { + return this.containerDecl; + }; + + PullDecl.prototype.getChildDeclCache = function (declKind) { + if (declKind === 8192 /* TypeParameter */) { + if (!this.childDeclTypeParameterCache) { + this.childDeclTypeParameterCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclTypeParameterCache; + } else if (TypeScript.hasFlag(declKind, 164 /* SomeContainer */)) { + if (!this.childDeclNamespaceCache) { + this.childDeclNamespaceCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclNamespaceCache; + } else if (TypeScript.hasFlag(declKind, 58728795 /* SomeType */)) { + if (!this.childDeclTypeCache) { + this.childDeclTypeCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclTypeCache; + } else { + if (!this.childDeclValueCache) { + this.childDeclValueCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclValueCache; + } + }; + + PullDecl.prototype.addChildDecl = function (childDecl) { + if (childDecl.kind === 8192 /* TypeParameter */) { + if (!this.typeParameters) { + this.typeParameters = []; + } + this.typeParameters[this.typeParameters.length] = childDecl; + } else { + if (!this.childDecls) { + this.childDecls = []; + } + this.childDecls[this.childDecls.length] = childDecl; + } + + var declName = childDecl.name; + + if (!(childDecl.kind & 7340032 /* SomeSignature */)) { + var cache = this.getChildDeclCache(childDecl.kind); + var childrenOfName = cache[declName]; + if (!childrenOfName) { + childrenOfName = []; + } + + childrenOfName.push(childDecl); + cache[declName] = childrenOfName; + } + }; + + PullDecl.prototype.searchChildDecls = function (declName, searchKind) { + var cacheVal = null; + + if (searchKind & 58728795 /* SomeType */) { + cacheVal = this.childDeclTypeCache ? this.childDeclTypeCache[declName] : null; + } else if (searchKind & 164 /* SomeContainer */) { + cacheVal = this.childDeclNamespaceCache ? this.childDeclNamespaceCache[declName] : null; + } else { + cacheVal = this.childDeclValueCache ? this.childDeclValueCache[declName] : null; + } + + if (cacheVal) { + return cacheVal; + } else { + if (searchKind & 58728795 /* SomeType */) { + cacheVal = this.childDeclTypeParameterCache ? this.childDeclTypeParameterCache[declName] : null; + + if (cacheVal) { + return cacheVal; + } + } + + return sentinelEmptyPullDeclArray; + } + }; + + PullDecl.prototype.getChildDecls = function () { + return this.childDecls || sentinelEmptyPullDeclArray; + }; + + PullDecl.prototype.getTypeParameters = function () { + return this.typeParameters || sentinelEmptyPullDeclArray; + }; + + PullDecl.prototype.addVariableDeclToGroup = function (decl) { + if (!this.declGroups) { + this.declGroups = TypeScript.createIntrinsicsObject(); + } + + var declGroup = this.declGroups[decl.name]; + if (declGroup) { + declGroup.addDecl(decl); + } else { + declGroup = new PullDeclGroup(decl.name); + declGroup.addDecl(decl); + this.declGroups[decl.name] = declGroup; + } + }; + + PullDecl.prototype.getVariableDeclGroups = function () { + var declGroups = null; + + if (this.declGroups) { + for (var declName in this.declGroups) { + if (this.declGroups[declName]) { + if (declGroups === null) { + declGroups = []; + } + + declGroups.push(this.declGroups[declName].getDecls()); + } + } + } + + return declGroups || sentinelEmptyPullDeclArray; + }; + + PullDecl.prototype.hasBeenBound = function () { + return this.hasSymbol() || this.hasSignatureSymbol(); + }; + + PullDecl.prototype.isSynthesized = function () { + return false; + }; + + PullDecl.prototype.ast = function () { + return this.semanticInfoChain.getASTForDecl(this); + }; + + PullDecl.prototype.isRootDecl = function () { + throw TypeScript.Errors.abstract(); + }; + return PullDecl; + })(); + TypeScript.PullDecl = PullDecl; + + var RootPullDecl = (function (_super) { + __extends(RootPullDecl, _super); + function RootPullDecl(name, fileName, kind, declFlags, semanticInfoChain, isExternalModule) { + _super.call(this, name, name, kind, declFlags, semanticInfoChain); + this.semanticInfoChain = semanticInfoChain; + this._isExternalModule = isExternalModule; + this._fileName = fileName; + } + RootPullDecl.prototype.fileName = function () { + return this._fileName; + }; + + RootPullDecl.prototype.getParentPath = function () { + return [this]; + }; + + RootPullDecl.prototype.getParentDecl = function () { + return null; + }; + + RootPullDecl.prototype.isExternalModule = function () { + return this._isExternalModule; + }; + + RootPullDecl.prototype.getEnclosingDecl = function () { + return this; + }; + + RootPullDecl.prototype.isRootDecl = function () { + return true; + }; + return RootPullDecl; + })(PullDecl); + TypeScript.RootPullDecl = RootPullDecl; + + var NormalPullDecl = (function (_super) { + __extends(NormalPullDecl, _super); + function NormalPullDecl(declName, displayName, kind, declFlags, parentDecl, addToParent) { + if (typeof addToParent === "undefined") { addToParent = true; } + _super.call(this, declName, displayName, kind, declFlags, parentDecl ? parentDecl.semanticInfoChain : null); + this.parentDecl = null; + this.parentPath = null; + + this.parentDecl = parentDecl; + if (addToParent) { + parentDecl.addChildDecl(this); + } + + if (this.parentDecl) { + if (this.parentDecl.isRootDecl()) { + this._rootDecl = this.parentDecl; + } else { + this._rootDecl = this.parentDecl._rootDecl; + } + } else { + TypeScript.Debug.assert(this.isSynthesized()); + this._rootDecl = null; + } + } + NormalPullDecl.prototype.fileName = function () { + return this._rootDecl.fileName(); + }; + + NormalPullDecl.prototype.getParentDecl = function () { + return this.parentDecl; + }; + + NormalPullDecl.prototype.getParentPath = function () { + if (!this.parentPath) { + var path = [this]; + var parentDecl = this.parentDecl; + + while (parentDecl) { + if (parentDecl && path[path.length - 1] !== parentDecl && !(parentDecl.kind & (256 /* ObjectLiteral */ | 8388608 /* ObjectType */))) { + path.unshift(parentDecl); + } + + parentDecl = parentDecl.getParentDecl(); + } + + this.parentPath = path; + } + + return this.parentPath; + }; + + NormalPullDecl.prototype.isExternalModule = function () { + return false; + }; + + NormalPullDecl.prototype.getEnclosingDecl = function () { + return this.parentDecl && this.parentDecl._getEnclosingDeclFromParentDecl(); + }; + + NormalPullDecl.prototype.isRootDecl = function () { + return false; + }; + return NormalPullDecl; + })(PullDecl); + TypeScript.NormalPullDecl = NormalPullDecl; + + var PullEnumElementDecl = (function (_super) { + __extends(PullEnumElementDecl, _super); + function PullEnumElementDecl(declName, displayName, parentDecl) { + _super.call(this, declName, displayName, 67108864 /* EnumMember */, 4 /* Public */, parentDecl); + this.constantValue = null; + } + return PullEnumElementDecl; + })(NormalPullDecl); + TypeScript.PullEnumElementDecl = PullEnumElementDecl; + + var PullFunctionExpressionDecl = (function (_super) { + __extends(PullFunctionExpressionDecl, _super); + function PullFunctionExpressionDecl(expressionName, declFlags, parentDecl, displayName) { + if (typeof displayName === "undefined") { displayName = ""; } + _super.call(this, "", displayName, 131072 /* FunctionExpression */, declFlags, parentDecl); + this.functionExpressionName = expressionName; + } + PullFunctionExpressionDecl.prototype.getFunctionExpressionName = function () { + return this.functionExpressionName; + }; + return PullFunctionExpressionDecl; + })(NormalPullDecl); + TypeScript.PullFunctionExpressionDecl = PullFunctionExpressionDecl; + + var PullSynthesizedDecl = (function (_super) { + __extends(PullSynthesizedDecl, _super); + function PullSynthesizedDecl(declName, displayName, kind, declFlags, parentDecl, semanticInfoChain) { + _super.call(this, declName, displayName, kind, declFlags, parentDecl, false); + this.semanticInfoChain = semanticInfoChain; + } + PullSynthesizedDecl.prototype.isSynthesized = function () { + return true; + }; + + PullSynthesizedDecl.prototype.fileName = function () { + return this._rootDecl ? this._rootDecl.fileName() : ""; + }; + return PullSynthesizedDecl; + })(NormalPullDecl); + TypeScript.PullSynthesizedDecl = PullSynthesizedDecl; + + var PullDeclGroup = (function () { + function PullDeclGroup(name) { + this.name = name; + this._decls = []; + } + PullDeclGroup.prototype.addDecl = function (decl) { + if (decl.name === this.name) { + this._decls[this._decls.length] = decl; + } + }; + + PullDeclGroup.prototype.getDecls = function () { + return this._decls; + }; + return PullDeclGroup; + })(); + TypeScript.PullDeclGroup = PullDeclGroup; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.pullSymbolID = 0; + TypeScript.sentinelEmptyArray = []; + + var PullSymbol = (function () { + function PullSymbol(name, declKind) { + this.pullSymbolID = ++TypeScript.pullSymbolID; + this._container = null; + this.type = null; + this._declarations = null; + this.isResolved = false; + this.isOptional = false; + this.inResolution = false; + this.isSynthesized = false; + this.isVarArg = false; + this.rootSymbol = null; + this._enclosingSignature = null; + this._docComments = null; + this.isPrinting = false; + this.name = name; + this.kind = declKind; + } + PullSymbol.prototype.isAny = function () { + return false; + }; + + PullSymbol.prototype.isType = function () { + return (this.kind & 58728795 /* SomeType */) !== 0; + }; + + PullSymbol.prototype.isTypeReference = function () { + return false; + }; + + PullSymbol.prototype.isSignature = function () { + return (this.kind & 7340032 /* SomeSignature */) !== 0; + }; + + PullSymbol.prototype.isArrayNamedTypeReference = function () { + return false; + }; + + PullSymbol.prototype.isPrimitive = function () { + return this.kind === 2 /* Primitive */; + }; + + PullSymbol.prototype.isAccessor = function () { + return false; + }; + + PullSymbol.prototype.isError = function () { + return false; + }; + + PullSymbol.prototype.isInterface = function () { + return this.kind === 16 /* Interface */; + }; + + PullSymbol.prototype.isMethod = function () { + return this.kind === 65536 /* Method */; + }; + + PullSymbol.prototype.isProperty = function () { + return this.kind === 4096 /* Property */; + }; + + PullSymbol.prototype.isAlias = function () { + return false; + }; + + PullSymbol.prototype.isContainer = function () { + return false; + }; + + PullSymbol.prototype.findAliasedTypeSymbols = function (scopeSymbol, skipScopeSymbolAliasesLookIn, lookIntoOnlyExportedAlias, aliasSymbols, visitedScopeDeclarations) { + if (typeof aliasSymbols === "undefined") { aliasSymbols = []; } + if (typeof visitedScopeDeclarations === "undefined") { visitedScopeDeclarations = []; } + var scopeDeclarations = scopeSymbol.getDeclarations(); + var scopeSymbolAliasesToLookIn = []; + + for (var i = 0; i < scopeDeclarations.length; i++) { + var scopeDecl = scopeDeclarations[i]; + if (!TypeScript.ArrayUtilities.contains(visitedScopeDeclarations, scopeDecl)) { + visitedScopeDeclarations.push(scopeDecl); + + var childDecls = scopeDecl.getChildDecls(); + for (var j = 0; j < childDecls.length; j++) { + var childDecl = childDecls[j]; + if (childDecl.kind === 128 /* TypeAlias */ && (!lookIntoOnlyExportedAlias || (childDecl.flags & 1 /* Exported */))) { + var symbol = childDecl.getSymbol(); + + if (PullContainerSymbol.usedAsSymbol(symbol, this) || (this.rootSymbol && PullContainerSymbol.usedAsSymbol(symbol, this.rootSymbol))) { + aliasSymbols.push(symbol); + return aliasSymbols; + } + + if (!skipScopeSymbolAliasesLookIn && PullSymbol._isExternalModuleReferenceAlias(symbol) && (!symbol.assignedContainer().hasExportAssignment() || (symbol.assignedContainer().getExportAssignedContainerSymbol() && symbol.assignedContainer().getExportAssignedContainerSymbol().kind === 32 /* DynamicModule */))) { + scopeSymbolAliasesToLookIn.push(symbol); + } + } + } + } + } + + for (var i = 0; i < scopeSymbolAliasesToLookIn.length; i++) { + var scopeSymbolAlias = scopeSymbolAliasesToLookIn[i]; + + aliasSymbols.push(scopeSymbolAlias); + var result = this.findAliasedTypeSymbols(scopeSymbolAlias.assignedContainer().hasExportAssignment() ? scopeSymbolAlias.assignedContainer().getExportAssignedContainerSymbol() : scopeSymbolAlias.assignedContainer(), false, true, aliasSymbols, visitedScopeDeclarations); + if (result) { + return result; + } + + aliasSymbols.pop(); + } + + return null; + }; + + PullSymbol.prototype.getExternalAliasedSymbols = function (scopeSymbol) { + if (!scopeSymbol) { + return null; + } + + var scopePath = scopeSymbol.pathToRoot(); + if (scopePath.length && scopePath[scopePath.length - 1].kind === 32 /* DynamicModule */) { + var symbols = this.findAliasedTypeSymbols(scopePath[scopePath.length - 1]); + return symbols; + } + + return null; + }; + + PullSymbol._isExternalModuleReferenceAlias = function (aliasSymbol) { + if (aliasSymbol) { + if (aliasSymbol.assignedValue()) { + return false; + } + + if (aliasSymbol.assignedType() && aliasSymbol.assignedType() !== aliasSymbol.assignedContainer()) { + return false; + } + + if (aliasSymbol.assignedContainer() && aliasSymbol.assignedContainer().kind !== 32 /* DynamicModule */) { + return false; + } + + return true; + } + + return false; + }; + + PullSymbol.prototype.getExportedInternalAliasSymbol = function (scopeSymbol) { + if (scopeSymbol) { + if (this.kind !== 128 /* TypeAlias */) { + var scopePath = scopeSymbol.pathToRoot(); + for (var i = 0; i < scopePath.length; i++) { + var internalAliases = this.findAliasedTypeSymbols(scopeSymbol, true, true); + if (internalAliases) { + TypeScript.Debug.assert(internalAliases.length === 1); + return internalAliases[0]; + } + } + } + } + + return null; + }; + + PullSymbol.prototype.getAliasSymbolName = function (scopeSymbol, aliasNameGetter, aliasPartsNameGetter, skipInternalAlias) { + if (!skipInternalAlias) { + var internalAlias = this.getExportedInternalAliasSymbol(scopeSymbol); + if (internalAlias) { + return aliasNameGetter(internalAlias); + } + } + + var externalAliases = this.getExternalAliasedSymbols(scopeSymbol); + + if (externalAliases && externalAliases[0] != this && PullSymbol._isExternalModuleReferenceAlias(externalAliases[externalAliases.length - 1])) { + var aliasFullName = aliasNameGetter(externalAliases[0]); + if (!aliasFullName) { + return null; + } + for (var i = 1, symbolsLen = externalAliases.length; i < symbolsLen; i++) { + aliasFullName = aliasFullName + "." + aliasPartsNameGetter(externalAliases[i]); + } + return aliasFullName; + } + + return null; + }; + + PullSymbol.prototype._getResolver = function () { + TypeScript.Debug.assert(this._declarations && this._declarations.length > 0); + return this._declarations[0].semanticInfoChain.getResolver(); + }; + + PullSymbol.prototype._resolveDeclaredSymbol = function () { + return this._getResolver().resolveDeclaredSymbol(this); + }; + + PullSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + var aliasName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getName(scopeSymbol, useConstraintInName); + }, function (symbol) { + return symbol.getName(); + }); + return aliasName || this.name; + }; + + PullSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { + var aliasDisplayName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getDisplayName(scopeSymbol, useConstraintInName); + }, function (symbol) { + return symbol.getDisplayName(); + }, skipInternalAliasName); + if (aliasDisplayName) { + return aliasDisplayName; + } + + var decls = this.getDeclarations(); + var name = decls.length && decls[0].getDisplayName(); + + return (name && name.length) ? name : this.name; + }; + + PullSymbol.prototype.getIsSpecialized = function () { + return false; + }; + + PullSymbol.prototype.getRootSymbol = function () { + if (!this.rootSymbol) { + return this; + } + return this.rootSymbol; + }; + PullSymbol.prototype.setRootSymbol = function (symbol) { + this.rootSymbol = symbol; + }; + + PullSymbol.prototype.setIsSynthesized = function (value) { + if (typeof value === "undefined") { value = true; } + TypeScript.Debug.assert(this.rootSymbol == null); + this.isSynthesized = value; + }; + + PullSymbol.prototype.getIsSynthesized = function () { + if (this.rootSymbol) { + return this.rootSymbol.getIsSynthesized(); + } + return this.isSynthesized; + }; + + PullSymbol.prototype.setEnclosingSignature = function (signature) { + this._enclosingSignature = signature; + }; + + PullSymbol.prototype.getEnclosingSignature = function () { + return this._enclosingSignature; + }; + + PullSymbol.prototype.addDeclaration = function (decl) { + TypeScript.Debug.assert(!!decl); + + if (this.rootSymbol) { + return; + } + + if (!this._declarations) { + this._declarations = [decl]; + } else { + this._declarations[this._declarations.length] = decl; + } + }; + + PullSymbol.prototype.getDeclarations = function () { + if (this.rootSymbol) { + return this.rootSymbol.getDeclarations(); + } + + if (!this._declarations) { + this._declarations = []; + } + + return this._declarations; + }; + + PullSymbol.prototype.hasDeclaration = function (decl) { + if (!this._declarations) { + return false; + } + + return TypeScript.ArrayUtilities.any(this._declarations, function (eachDecl) { + return eachDecl === decl; + }); + }; + + PullSymbol.prototype.setContainer = function (containerSymbol) { + if (this.rootSymbol) { + return; + } + + this._container = containerSymbol; + }; + + PullSymbol.prototype.getContainer = function () { + if (this.rootSymbol) { + return this.rootSymbol.getContainer(); + } + + return this._container; + }; + + PullSymbol.prototype.setResolved = function () { + this.isResolved = true; + this.inResolution = false; + }; + + PullSymbol.prototype.startResolving = function () { + this.inResolution = true; + }; + + PullSymbol.prototype.setUnresolved = function () { + this.isResolved = false; + this.inResolution = false; + }; + + PullSymbol.prototype.anyDeclHasFlag = function (flag) { + var declarations = this.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + if (TypeScript.hasFlag(declarations[i].flags, flag)) { + return true; + } + } + return false; + }; + + PullSymbol.prototype.allDeclsHaveFlag = function (flag) { + var declarations = this.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + if (!TypeScript.hasFlag(declarations[i].flags, flag)) { + return false; + } + } + return true; + }; + + PullSymbol.prototype.pathToRoot = function () { + var path = []; + var node = this; + while (node) { + if (node.isType()) { + var associatedContainerSymbol = node.getAssociatedContainerType(); + if (associatedContainerSymbol) { + node = associatedContainerSymbol; + } + } + path[path.length] = node; + var nodeKind = node.kind; + if (nodeKind === 2048 /* Parameter */) { + break; + } else { + node = node.getContainer(); + } + } + return path; + }; + + PullSymbol.unqualifiedNameReferencesDifferentSymbolInScope = function (symbol, scopePath, endScopePathIndex) { + var declPath = scopePath[0].getDeclarations()[0].getParentPath(); + for (var i = 0, declIndex = declPath.length - 1; i <= endScopePathIndex; i++, declIndex--) { + if (scopePath[i].isContainer()) { + var scopeContainer = scopePath[i]; + if (symbol.isContainer()) { + var memberSymbol = scopeContainer.findContainedNonMemberContainer(symbol.name, 164 /* SomeContainer */); + if (memberSymbol && memberSymbol != symbol && memberSymbol.getDeclarations()[0].getParentDecl() == declPath[declIndex]) { + return true; + } + + var memberSymbol = scopeContainer.findNestedContainer(symbol.name, 164 /* SomeContainer */); + if (memberSymbol && memberSymbol != symbol) { + return true; + } + } else if (symbol.isType()) { + var memberSymbol = scopeContainer.findContainedNonMemberType(symbol.name, 58728795 /* SomeType */); + var symbolRootType = TypeScript.PullHelpers.getRootType(symbol); + if (memberSymbol && TypeScript.PullHelpers.getRootType(memberSymbol) != symbolRootType && memberSymbol.getDeclarations()[0].getParentDecl() == declPath[declIndex]) { + return true; + } + + var memberSymbol = scopeContainer.findNestedType(symbol.name, 58728795 /* SomeType */); + if (memberSymbol && TypeScript.PullHelpers.getRootType(memberSymbol) != symbolRootType) { + return true; + } + } + } + } + + return false; + }; + + PullSymbol.prototype.findQualifyingSymbolPathInScopeSymbol = function (scopeSymbol) { + var thisPath = this.pathToRoot(); + if (thisPath.length === 1) { + return thisPath; + } + + var scopeSymbolPath; + if (scopeSymbol) { + scopeSymbolPath = scopeSymbol.pathToRoot(); + } else { + return thisPath; + } + + var thisCommonAncestorIndex = TypeScript.ArrayUtilities.indexOf(thisPath, function (thisNode) { + return TypeScript.ArrayUtilities.contains(scopeSymbolPath, thisNode); + }); + if (thisCommonAncestorIndex > 0) { + var thisCommonAncestor = thisPath[thisCommonAncestorIndex]; + var scopeCommonAncestorIndex = TypeScript.ArrayUtilities.indexOf(scopeSymbolPath, function (scopeNode) { + return scopeNode === thisCommonAncestor; + }); + TypeScript.Debug.assert(thisPath.length - thisCommonAncestorIndex === scopeSymbolPath.length - scopeCommonAncestorIndex); + + for (; thisCommonAncestorIndex < thisPath.length; thisCommonAncestorIndex++, scopeCommonAncestorIndex++) { + if (!PullSymbol.unqualifiedNameReferencesDifferentSymbolInScope(thisPath[thisCommonAncestorIndex - 1], scopeSymbolPath, scopeCommonAncestorIndex)) { + break; + } + } + } + + if (thisCommonAncestorIndex >= 0 && thisCommonAncestorIndex < thisPath.length) { + return thisPath.slice(0, thisCommonAncestorIndex); + } else { + return thisPath; + } + }; + + PullSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + var str = this.getNameAndTypeName(scopeSymbol); + return str; + }; + + PullSymbol.prototype.getNamePartForFullName = function () { + return this.getDisplayName(null, true); + }; + + PullSymbol.prototype.fullName = function (scopeSymbol) { + var _this = this; + var path = this.pathToRoot(); + var fullName = ""; + + var aliasFullName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.fullName(scopeSymbol); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }); + if (aliasFullName) { + return aliasFullName; + } + + for (var i = 1; i < path.length; i++) { + var aliasFullName = path[i].getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol === _this ? null : symbol.fullName(scopeSymbol); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }); + if (aliasFullName) { + fullName = aliasFullName + "." + fullName; + break; + } + + var scopedName = path[i].getNamePartForFullName(); + if (path[i].kind === 32 /* DynamicModule */ && !TypeScript.isQuoted(scopedName)) { + break; + } + + if (scopedName === "") { + break; + } + + fullName = scopedName + "." + fullName; + } + + fullName = fullName + this.getNamePartForFullName(); + return fullName; + }; + + PullSymbol.prototype.getScopedName = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName) { + var path = this.findQualifyingSymbolPathInScopeSymbol(scopeSymbol); + var fullName = ""; + + var aliasFullName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getScopedName(scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }, skipInternalAliasName); + if (aliasFullName) { + return aliasFullName; + } + + for (var i = 1; i < path.length; i++) { + var kind = path[i].kind; + if (kind === 4 /* Container */ || kind === 32 /* DynamicModule */) { + var aliasFullName = path[i].getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getScopedName(scopeSymbol, skipTypeParametersInName, false, skipInternalAliasName); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }, skipInternalAliasName); + if (aliasFullName) { + fullName = aliasFullName + "." + fullName; + break; + } + + if (kind === 4 /* Container */) { + fullName = path[i].getDisplayName() + "." + fullName; + } else { + var displayName = path[i].getDisplayName(); + if (TypeScript.isQuoted(displayName)) { + fullName = displayName + "." + fullName; + } + break; + } + } else { + break; + } + } + fullName = fullName + this.getDisplayName(scopeSymbol, useConstraintInName, skipInternalAliasName); + return fullName; + }; + + PullSymbol.prototype.getScopedNameEx = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName) { + var name = this.getScopedName(scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName); + return TypeScript.MemberName.create(name); + }; + + PullSymbol.prototype.getTypeName = function (scopeSymbol, getPrettyTypeName) { + var memberName = this.getTypeNameEx(scopeSymbol, getPrettyTypeName); + return memberName.toString(); + }; + + PullSymbol.prototype.getTypeNameEx = function (scopeSymbol, getPrettyTypeName) { + var type = this.type; + if (type) { + var memberName = getPrettyTypeName ? this.getTypeNameForFunctionSignature("", scopeSymbol, getPrettyTypeName) : null; + if (!memberName) { + memberName = type.getScopedNameEx(scopeSymbol, false, true, getPrettyTypeName); + } + + return memberName; + } + return TypeScript.MemberName.create(""); + }; + + PullSymbol.prototype.getTypeNameForFunctionSignature = function (prefix, scopeSymbol, getPrettyTypeName) { + var type = this.type; + if (type && !type.isNamedTypeSymbol() && this.kind !== 4096 /* Property */ && this.kind !== 512 /* Variable */ && this.kind !== 2048 /* Parameter */) { + var signatures = type.getCallSignatures(); + if (signatures.length === 1 || (getPrettyTypeName && signatures.length)) { + var typeName = new TypeScript.MemberNameArray(); + var signatureName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, prefix, false, false, scopeSymbol, getPrettyTypeName); + typeName.addAll(signatureName); + return typeName; + } + } + + return null; + }; + + PullSymbol.prototype.getNameAndTypeName = function (scopeSymbol) { + var nameAndTypeName = this.getNameAndTypeNameEx(scopeSymbol); + return nameAndTypeName.toString(); + }; + + PullSymbol.prototype.getNameAndTypeNameEx = function (scopeSymbol) { + var type = this.type; + var nameStr = this.getDisplayName(scopeSymbol); + if (type) { + nameStr = nameStr + (this.isOptional ? "?" : ""); + var memberName = this.getTypeNameForFunctionSignature(nameStr, scopeSymbol); + if (!memberName) { + var typeNameEx = type.getScopedNameEx(scopeSymbol); + memberName = TypeScript.MemberName.create(typeNameEx, nameStr + ": ", ""); + } + return memberName; + } + return TypeScript.MemberName.create(nameStr); + }; + + PullSymbol.getTypeParameterString = function (typars, scopeSymbol, useContraintInName) { + return PullSymbol.getTypeParameterStringEx(typars, scopeSymbol, undefined, useContraintInName).toString(); + }; + + PullSymbol.getTypeParameterStringEx = function (typeParameters, scopeSymbol, getTypeParamMarkerInfo, useContraintInName) { + var builder = new TypeScript.MemberNameArray(); + builder.prefix = ""; + + if (typeParameters && typeParameters.length) { + builder.add(TypeScript.MemberName.create("<")); + + for (var i = 0; i < typeParameters.length; i++) { + if (i) { + builder.add(TypeScript.MemberName.create(", ")); + } + + if (getTypeParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + + builder.add(typeParameters[i].getScopedNameEx(scopeSymbol, false, useContraintInName)); + + if (getTypeParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + } + + builder.add(TypeScript.MemberName.create(">")); + } + + return builder; + }; + + PullSymbol.getIsExternallyVisible = function (symbol, fromIsExternallyVisibleSymbol, inIsExternallyVisibleSymbols) { + if (inIsExternallyVisibleSymbols) { + for (var i = 0; i < inIsExternallyVisibleSymbols.length; i++) { + if (inIsExternallyVisibleSymbols[i] === symbol) { + return true; + } + } + } else { + inIsExternallyVisibleSymbols = []; + } + + if (fromIsExternallyVisibleSymbol === symbol) { + return true; + } + + inIsExternallyVisibleSymbols.push(fromIsExternallyVisibleSymbol); + + var result = symbol.isExternallyVisible(inIsExternallyVisibleSymbols); + + TypeScript.Debug.assert(TypeScript.ArrayUtilities.last(inIsExternallyVisibleSymbols) === fromIsExternallyVisibleSymbol); + inIsExternallyVisibleSymbols.pop(); + + return result; + }; + + PullSymbol.prototype.isExternallyVisible = function (inIsExternallyVisibleSymbols) { + var kind = this.kind; + if (kind === 2 /* Primitive */) { + return true; + } + + if (this.rootSymbol) { + return PullSymbol.getIsExternallyVisible(this.rootSymbol, this, inIsExternallyVisibleSymbols); + } + + if (this.isType()) { + var associatedContainerSymbol = this.getAssociatedContainerType(); + if (associatedContainerSymbol) { + return PullSymbol.getIsExternallyVisible(associatedContainerSymbol, this, inIsExternallyVisibleSymbols); + } + } + + if (this.anyDeclHasFlag(2 /* Private */)) { + return false; + } + + var container = this.getContainer(); + if (container === null) { + var decls = this.getDeclarations(); + if (decls.length) { + var parentDecl = decls[0].getParentDecl(); + if (parentDecl) { + var parentSymbol = parentDecl.getSymbol(); + if (!parentSymbol || parentDecl.kind === 1 /* Script */) { + return true; + } + + return PullSymbol.getIsExternallyVisible(parentSymbol, this, inIsExternallyVisibleSymbols); + } + } + + return true; + } + + if (container.kind === 32 /* DynamicModule */ || (container.getAssociatedContainerType() && container.getAssociatedContainerType().kind === 32 /* DynamicModule */)) { + var containerSymbol = container.kind === 32 /* DynamicModule */ ? container : container.getAssociatedContainerType(); + if (PullContainerSymbol.usedAsSymbol(containerSymbol, this)) { + return true; + } + } + + if (!this.anyDeclHasFlag(1 /* Exported */) && kind !== 4096 /* Property */ && kind !== 65536 /* Method */) { + return false; + } + + return PullSymbol.getIsExternallyVisible(container, this, inIsExternallyVisibleSymbols); + }; + + PullSymbol.prototype.getDocCommentsOfDecl = function (decl) { + var ast = decl.ast(); + + if (ast) { + var enclosingModuleDeclaration = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(ast); + if (TypeScript.ASTHelpers.isLastNameOfModule(enclosingModuleDeclaration, ast)) { + return TypeScript.ASTHelpers.docComments(enclosingModuleDeclaration); + } + + if (ast.kind() !== 130 /* ModuleDeclaration */ || decl.kind !== 512 /* Variable */) { + return TypeScript.ASTHelpers.docComments(ast); + } + } + + return []; + }; + + PullSymbol.prototype.getDocCommentArray = function (symbol) { + var docComments = []; + if (!symbol) { + return docComments; + } + + var isParameter = symbol.kind === 2048 /* Parameter */; + var decls = symbol.getDeclarations(); + for (var i = 0; i < decls.length; i++) { + if (isParameter && decls[i].kind === 4096 /* Property */) { + continue; + } + docComments = docComments.concat(this.getDocCommentsOfDecl(decls[i])); + } + return docComments; + }; + + PullSymbol.getDefaultConstructorSymbolForDocComments = function (classSymbol) { + if (classSymbol.getHasDefaultConstructor()) { + var extendedTypes = classSymbol.getExtendedTypes(); + if (extendedTypes.length) { + return PullSymbol.getDefaultConstructorSymbolForDocComments(extendedTypes[0]); + } + } + + return classSymbol.type.getConstructSignatures()[0]; + }; + + PullSymbol.prototype.getDocCommentText = function (comments) { + var docCommentText = new Array(); + for (var c = 0; c < comments.length; c++) { + var commentText = this.getDocCommentTextValue(comments[c]); + if (commentText !== "") { + docCommentText.push(commentText); + } + } + return docCommentText.join("\n"); + }; + + PullSymbol.prototype.getDocCommentTextValue = function (comment) { + return this.cleanJSDocComment(comment.fullText()); + }; + + PullSymbol.prototype.docComments = function (useConstructorAsClass) { + var decls = this.getDeclarations(); + if (useConstructorAsClass && decls.length && decls[0].kind === 32768 /* ConstructorMethod */) { + var classDecl = decls[0].getParentDecl(); + return this.getDocCommentText(this.getDocCommentsOfDecl(classDecl)); + } + + if (this._docComments === null) { + var docComments = ""; + if (!useConstructorAsClass && this.kind === 2097152 /* ConstructSignature */ && decls.length && decls[0].kind === 8 /* Class */) { + var classSymbol = this.returnType; + var extendedTypes = classSymbol.getExtendedTypes(); + if (extendedTypes.length) { + docComments = extendedTypes[0].getConstructorMethod().docComments(); + } else { + docComments = ""; + } + } else if (this.kind === 2048 /* Parameter */) { + var parameterComments = []; + + var funcContainer = this.getEnclosingSignature(); + var funcDocComments = this.getDocCommentArray(funcContainer); + var paramComment = this.getParameterDocCommentText(this.getDisplayName(), funcDocComments); + if (paramComment != "") { + parameterComments.push(paramComment); + } + + var paramSelfComment = this.getDocCommentText(this.getDocCommentArray(this)); + if (paramSelfComment != "") { + parameterComments.push(paramSelfComment); + } + docComments = parameterComments.join("\n"); + } else { + var getSymbolComments = true; + if (this.kind === 16777216 /* FunctionType */) { + var functionSymbol = this.getFunctionSymbol(); + + if (functionSymbol) { + docComments = functionSymbol._docComments || ""; + getSymbolComments = false; + } else { + var declarationList = this.getDeclarations(); + if (declarationList.length > 0) { + docComments = declarationList[0].getSymbol()._docComments || ""; + getSymbolComments = false; + } + } + } + if (getSymbolComments) { + docComments = this.getDocCommentText(this.getDocCommentArray(this)); + if (docComments === "") { + if (this.kind === 1048576 /* CallSignature */) { + var callTypeSymbol = this.functionType; + if (callTypeSymbol && callTypeSymbol.getCallSignatures().length === 1) { + docComments = callTypeSymbol.docComments(); + } + } + } + } + } + + this._docComments = docComments; + } + + return this._docComments; + }; + + PullSymbol.prototype.getParameterDocCommentText = function (param, fncDocComments) { + if (fncDocComments.length === 0 || fncDocComments[0].kind() !== 6 /* MultiLineCommentTrivia */) { + return ""; + } + + for (var i = 0; i < fncDocComments.length; i++) { + var commentContents = fncDocComments[i].fullText(); + for (var j = commentContents.indexOf("@param", 0); 0 <= j; j = commentContents.indexOf("@param", j)) { + j += 6; + if (!this.isSpaceChar(commentContents, j)) { + continue; + } + + j = this.consumeLeadingSpace(commentContents, j); + if (j === -1) { + break; + } + + if (commentContents.charCodeAt(j) === 123 /* openBrace */) { + j++; + + var charCode = 0; + for (var curlies = 1; j < commentContents.length; j++) { + charCode = commentContents.charCodeAt(j); + + if (charCode === 123 /* openBrace */) { + curlies++; + continue; + } + + if (charCode === 125 /* closeBrace */) { + curlies--; + if (curlies === 0) { + break; + } else { + continue; + } + } + + if (charCode === 64 /* at */) { + break; + } + } + + if (j === commentContents.length) { + break; + } + + if (charCode === 64 /* at */) { + continue; + } + + j = this.consumeLeadingSpace(commentContents, j + 1); + if (j === -1) { + break; + } + } + + if (param !== commentContents.substr(j, param.length) || !this.isSpaceChar(commentContents, j + param.length)) { + continue; + } + + j = this.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 = this.consumeLeadingSpace(commentContents, paramLineIndex); + if (startSpaceRemovalIndex !== j && commentContents.charAt(startSpaceRemovalIndex) === "*") { + paramSpacesToRemove = j - startSpaceRemovalIndex - 1; + } + + return this.cleanJSDocComment(paramHelpString, paramSpacesToRemove); + } + } + + return ""; + }; + + PullSymbol.prototype.cleanJSDocComment = function (content, spacesToRemove) { + var docCommentLines = new Array(); + 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 = this.cleanDocCommentLine(line, true, spacesToRemove); + if (!cleanLinePos) { + continue; + } + + var docCommentText = ""; + var prevPos = cleanLinePos.start; + for (var i = line.indexOf("@", cleanLinePos.start); 0 <= i && i < cleanLinePos.end; i = line.indexOf("@", i + 1)) { + var wasInParamtag = inParamTag; + + if (line.indexOf("param", i + 1) === i + 1 && this.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.end); + } + + var newCleanPos = this.cleanDocCommentLine(docCommentText, false); + if (newCleanPos) { + if (spacesToRemove === undefined) { + spacesToRemove = cleanLinePos.jsDocSpacesRemoved; + } + docCommentLines.push(docCommentText); + } + } + + return docCommentLines.join("\n"); + }; + + PullSymbol.prototype.consumeLeadingSpace = function (line, startIndex, maxSpacesToRemove) { + var endIndex = line.length; + if (maxSpacesToRemove !== undefined) { + endIndex = TypeScript.MathPrototype.min(startIndex + maxSpacesToRemove, endIndex); + } + + for (; startIndex < endIndex; startIndex++) { + var charCode = line.charCodeAt(startIndex); + if (charCode !== 32 /* space */ && charCode !== 9 /* tab */) { + return startIndex; + } + } + + if (endIndex !== line.length) { + return endIndex; + } + + return -1; + }; + + PullSymbol.prototype.isSpaceChar = function (line, index) { + var length = line.length; + if (index < length) { + var charCode = line.charCodeAt(index); + + return charCode === 32 /* space */ || charCode === 9 /* tab */; + } + + return index === length; + }; + + PullSymbol.prototype.cleanDocCommentLine = function (line, jsDocStyleComment, jsDocLineSpaceToRemove) { + var nonSpaceIndex = this.consumeLeadingSpace(line, 0); + if (nonSpaceIndex !== -1) { + var jsDocSpacesRemoved = nonSpaceIndex; + if (jsDocStyleComment && line.charAt(nonSpaceIndex) === '*') { + var startIndex = nonSpaceIndex + 1; + nonSpaceIndex = this.consumeLeadingSpace(line, startIndex, jsDocLineSpaceToRemove); + + if (nonSpaceIndex !== -1) { + jsDocSpacesRemoved = nonSpaceIndex - startIndex; + } else { + return null; + } + } + + return { + start: nonSpaceIndex, + end: line.charAt(line.length - 1) === "\r" ? line.length - 1 : line.length, + jsDocSpacesRemoved: jsDocSpacesRemoved + }; + } + + return null; + }; + return PullSymbol; + })(); + TypeScript.PullSymbol = PullSymbol; + + + + var PullSignatureSymbol = (function (_super) { + __extends(PullSignatureSymbol, _super); + function PullSignatureSymbol(kind, _isDefinition) { + if (typeof _isDefinition === "undefined") { _isDefinition = false; } + _super.call(this, "", kind); + this._isDefinition = _isDefinition; + this._memberTypeParameterNameCache = null; + this._stringConstantOverload = undefined; + this.parameters = TypeScript.sentinelEmptyArray; + this._typeParameters = null; + this.returnType = null; + this.functionType = null; + this.hasOptionalParam = false; + this.nonOptionalParamCount = 0; + this.hasVarArgs = false; + this._allowedToReferenceTypeParameters = null; + this._instantiationCache = null; + this.hasBeenChecked = false; + this.inWrapCheck = false; + this.inWrapInfiniteExpandingReferenceCheck = false; + } + PullSignatureSymbol.prototype.isDefinition = function () { + return this._isDefinition; + }; + + PullSignatureSymbol.prototype.isGeneric = function () { + var typeParameters = this.getTypeParameters(); + return !!typeParameters && typeParameters.length !== 0; + }; + + PullSignatureSymbol.prototype.addParameter = function (parameter, isOptional) { + if (typeof isOptional === "undefined") { isOptional = false; } + if (this.parameters === TypeScript.sentinelEmptyArray) { + this.parameters = []; + } + + this.parameters[this.parameters.length] = parameter; + this.hasOptionalParam = isOptional; + + if (!parameter.getEnclosingSignature()) { + parameter.setEnclosingSignature(this); + } + + if (!isOptional) { + this.nonOptionalParamCount++; + } + }; + + PullSignatureSymbol.prototype.addTypeParameter = function (typeParameter) { + if (!this._typeParameters) { + this._typeParameters = []; + } + + if (!this._memberTypeParameterNameCache) { + this._memberTypeParameterNameCache = TypeScript.createIntrinsicsObject(); + } + + this._typeParameters[this._typeParameters.length] = typeParameter; + + this._memberTypeParameterNameCache[typeParameter.getName()] = typeParameter; + }; + + PullSignatureSymbol.prototype.addTypeParametersFromReturnType = function () { + var typeParameters = this.returnType.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + this.addTypeParameter(typeParameters[i]); + } + }; + + PullSignatureSymbol.prototype.getTypeParameters = function () { + if (!this._typeParameters) { + this._typeParameters = []; + } + + return this._typeParameters; + }; + + PullSignatureSymbol.prototype.findTypeParameter = function (name) { + var memberSymbol; + + if (!this._memberTypeParameterNameCache) { + this._memberTypeParameterNameCache = TypeScript.createIntrinsicsObject(); + + for (var i = 0; i < this.getTypeParameters().length; i++) { + this._memberTypeParameterNameCache[this._typeParameters[i].getName()] = this._typeParameters[i]; + } + } + + memberSymbol = this._memberTypeParameterNameCache[name]; + + return memberSymbol; + }; + + PullSignatureSymbol.prototype.getTypeParameterArgumentMap = function () { + return null; + }; + + PullSignatureSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._allowedToReferenceTypeParameters) { + this._allowedToReferenceTypeParameters = TypeScript.PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl(this.getDeclarations()[0]); + } + + return this._allowedToReferenceTypeParameters; + }; + + PullSignatureSymbol.prototype.addSpecialization = function (specializedVersionOfThisSignature, typeArgumentMap) { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._instantiationCache) { + this._instantiationCache = TypeScript.createIntrinsicsObject(); + } + + this._instantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)] = specializedVersionOfThisSignature; + }; + + PullSignatureSymbol.prototype.getSpecialization = function (typeArgumentMap) { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._instantiationCache) { + return null; + } + + var result = this._instantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)]; + return result || null; + }; + + PullSignatureSymbol.prototype.isStringConstantOverloadSignature = function () { + if (this._stringConstantOverload === undefined) { + var params = this.parameters; + this._stringConstantOverload = false; + for (var i = 0; i < params.length; i++) { + var paramType = params[i].type; + if (paramType && paramType.isPrimitive() && paramType.isStringConstant()) { + this._stringConstantOverload = true; + } + } + } + + return this._stringConstantOverload; + }; + + PullSignatureSymbol.prototype.getParameterTypeAtIndex = function (iParam) { + if (iParam < this.parameters.length - 1 || (iParam < this.parameters.length && !this.hasVarArgs)) { + return this.parameters[iParam].type; + } else if (this.hasVarArgs) { + var paramType = this.parameters[this.parameters.length - 1].type; + if (paramType.isArrayNamedTypeReference()) { + paramType = paramType.getElementType(); + } + return paramType; + } + + return null; + }; + + PullSignatureSymbol.getSignatureTypeMemberName = function (candidateSignature, signatures, scopeSymbol) { + var allMemberNames = new TypeScript.MemberNameArray(); + var signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, "", false, false, scopeSymbol, true, candidateSignature); + allMemberNames.addAll(signatureMemberName); + return allMemberNames; + }; + + PullSignatureSymbol.getSignaturesTypeNameEx = function (signatures, prefix, shortform, brackets, scopeSymbol, getPrettyTypeName, candidateSignature) { + var result = []; + if (!signatures) { + return result; + } + + var len = signatures.length; + if (!getPrettyTypeName && len > 1) { + shortform = false; + } + + var foundDefinition = false; + if (candidateSignature && candidateSignature.isDefinition() && len > 1) { + candidateSignature = null; + } + + for (var i = 0; i < len; i++) { + if (len > 1 && signatures[i].isDefinition()) { + foundDefinition = true; + continue; + } + + var signature = signatures[i]; + if (getPrettyTypeName && candidateSignature) { + signature = candidateSignature; + } + + result.push(signature.getSignatureTypeNameEx(prefix, shortform, brackets, scopeSymbol)); + if (getPrettyTypeName) { + break; + } + } + + if (getPrettyTypeName && result.length && len > 1) { + var lastMemberName = result[result.length - 1]; + for (var i = i + 1; i < len; i++) { + if (signatures[i].isDefinition()) { + foundDefinition = true; + break; + } + } + var overloadString = TypeScript.getLocalizedText(TypeScript.DiagnosticCode._0_overload_s, [foundDefinition ? len - 2 : len - 1]); + lastMemberName.add(TypeScript.MemberName.create(overloadString)); + } + + return result; + }; + + PullSignatureSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + var s = this.getSignatureTypeNameEx(this.getScopedNameEx().toString(), false, false, scopeSymbol, undefined, useConstraintInName).toString(); + return s; + }; + + PullSignatureSymbol.prototype.getSignatureTypeNameEx = function (prefix, shortform, brackets, scopeSymbol, getParamMarkerInfo, getTypeParamMarkerInfo) { + var typeParamterBuilder = new TypeScript.MemberNameArray(); + + typeParamterBuilder.add(PullSymbol.getTypeParameterStringEx(this.getTypeParameters(), scopeSymbol, getTypeParamMarkerInfo, true)); + + if (brackets) { + typeParamterBuilder.add(TypeScript.MemberName.create("[")); + } else { + typeParamterBuilder.add(TypeScript.MemberName.create("(")); + } + + var builder = new TypeScript.MemberNameArray(); + builder.prefix = prefix; + + if (getTypeParamMarkerInfo) { + builder.prefix = prefix; + builder.addAll(typeParamterBuilder.entries); + } else { + builder.prefix = prefix + typeParamterBuilder.toString(); + } + + var params = this.parameters; + var paramLen = params.length; + for (var i = 0; i < paramLen; i++) { + var paramType = params[i].type; + var typeString = paramType ? ": " : ""; + var paramIsVarArg = params[i].isVarArg; + var varArgPrefix = paramIsVarArg ? "..." : ""; + var optionalString = (!paramIsVarArg && params[i].isOptional) ? "?" : ""; + if (getParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + builder.add(TypeScript.MemberName.create(varArgPrefix + params[i].getScopedNameEx(scopeSymbol).toString() + optionalString + typeString)); + if (paramType) { + builder.add(paramType.getScopedNameEx(scopeSymbol)); + } + if (getParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + if (i < paramLen - 1) { + builder.add(TypeScript.MemberName.create(", ")); + } + } + + 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) { + builder.add(this.returnType.getScopedNameEx(scopeSymbol)); + } else { + builder.add(TypeScript.MemberName.create("any")); + } + + return builder; + }; + + PullSignatureSymbol.prototype.forAllParameterTypes = function (length, predicate) { + if (this.parameters.length < length && !this.hasVarArgs) { + length = this.parameters.length; + } + + for (var i = 0; i < length; i++) { + var paramType = this.getParameterTypeAtIndex(i); + if (!predicate(paramType, i)) { + return false; + } + } + + return true; + }; + + PullSignatureSymbol.prototype.forAllCorrespondingParameterTypesInThisAndOtherSignature = function (otherSignature, predicate) { + var length; + if (this.hasVarArgs) { + length = otherSignature.hasVarArgs ? Math.max(this.parameters.length, otherSignature.parameters.length) : otherSignature.parameters.length; + } else { + length = otherSignature.hasVarArgs ? this.parameters.length : Math.min(this.parameters.length, otherSignature.parameters.length); + } + + for (var i = 0; i < length; i++) { + var thisParamType = this.getParameterTypeAtIndex(i); + var otherParamType = otherSignature.getParameterTypeAtIndex(i); + if (!predicate(thisParamType, otherParamType, i)) { + return false; + } + } + + return true; + }; + + PullSignatureSymbol.prototype.wrapsSomeTypeParameter = function (typeParameterArgumentMap) { + return this.getWrappingTypeParameterID(typeParameterArgumentMap) !== 0; + }; + + PullSignatureSymbol.prototype.getWrappingTypeParameterID = function (typeParameterArgumentMap) { + var signature = this; + if (signature.inWrapCheck) { + return 0; + } + + this._wrapsTypeParameterCache = this._wrapsTypeParameterCache || new TypeScript.WrapsTypeParameterCache(); + + var wrappingTypeParameterID = this._wrapsTypeParameterCache.getWrapsTypeParameter(typeParameterArgumentMap); + if (wrappingTypeParameterID === undefined) { + wrappingTypeParameterID = this.getWrappingTypeParameterIDWorker(typeParameterArgumentMap); + this._wrapsTypeParameterCache.setWrapsTypeParameter(typeParameterArgumentMap, wrappingTypeParameterID); + } + + return wrappingTypeParameterID; + }; + + PullSignatureSymbol.prototype.getWrappingTypeParameterIDWorker = function (typeParameterArgumentMap) { + var signature = this; + signature.inWrapCheck = true; + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(signature); + var wrappingTypeParameterID = signature.returnType ? signature.returnType.getWrappingTypeParameterID(typeParameterArgumentMap) : 0; + + var parameters = signature.parameters; + for (var i = 0; !wrappingTypeParameterID && i < parameters.length; i++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(parameters[i]); + wrappingTypeParameterID = parameters[i].type.getWrappingTypeParameterID(typeParameterArgumentMap); + } + + signature.inWrapCheck = false; + + return wrappingTypeParameterID; + }; + + PullSignatureSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference = function (enclosingType, knownWrapMap) { + var wrapsIntoInfinitelyExpandingTypeReference = knownWrapMap.valueAt(this.pullSymbolID, enclosingType.pullSymbolID); + if (wrapsIntoInfinitelyExpandingTypeReference != undefined) { + return wrapsIntoInfinitelyExpandingTypeReference; + } + + if (this.inWrapInfiniteExpandingReferenceCheck) { + return false; + } + + this.inWrapInfiniteExpandingReferenceCheck = true; + wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker(enclosingType, knownWrapMap); + knownWrapMap.setValueAt(this.pullSymbolID, enclosingType.pullSymbolID, wrapsIntoInfinitelyExpandingTypeReference); + this.inWrapInfiniteExpandingReferenceCheck = false; + + return wrapsIntoInfinitelyExpandingTypeReference; + }; + + PullSignatureSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker = function (enclosingType, knownWrapMap) { + if (this.returnType && this.returnType._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; + } + + var parameters = this.parameters; + + for (var i = 0; i < parameters.length; i++) { + if (parameters[i].type && parameters[i].type._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; + } + } + + return false; + }; + return PullSignatureSymbol; + })(PullSymbol); + TypeScript.PullSignatureSymbol = PullSignatureSymbol; + + var PullTypeSymbol = (function (_super) { + __extends(PullTypeSymbol, _super); + function PullTypeSymbol(name, kind) { + _super.call(this, name, kind); + this._members = TypeScript.sentinelEmptyArray; + this._enclosedMemberTypes = null; + this._enclosedMemberContainers = null; + this._typeParameters = null; + this._allowedToReferenceTypeParameters = null; + this._specializedVersionsOfThisType = null; + this._arrayVersionOfThisType = null; + this._implementedTypes = null; + this._extendedTypes = null; + this._typesThatExplicitlyImplementThisType = null; + this._typesThatExtendThisType = null; + this._callSignatures = null; + this._allCallSignatures = null; + this._constructSignatures = null; + this._allConstructSignatures = null; + this._indexSignatures = null; + this._allIndexSignatures = null; + this._allIndexSignaturesOfAugmentedType = null; + this._memberNameCache = null; + this._enclosedTypeNameCache = null; + this._enclosedContainerCache = null; + this._typeParameterNameCache = null; + this._containedNonMemberNameCache = null; + this._containedNonMemberTypeNameCache = null; + this._containedNonMemberContainerCache = null; + this._simpleInstantiationCache = null; + this._complexInstantiationCache = null; + this._hasGenericSignature = false; + this._hasGenericMember = false; + this._hasBaseTypeConflict = false; + this._knownBaseTypeCount = 0; + this._associatedContainerTypeSymbol = null; + this._constructorMethod = null; + this._hasDefaultConstructor = false; + this._functionSymbol = null; + this._inMemberTypeNameEx = false; + this.inSymbolPrivacyCheck = false; + this.inWrapCheck = false; + this.inWrapInfiniteExpandingReferenceCheck = false; + this.typeReference = null; + this._widenedType = null; + this._isArrayNamedTypeReference = undefined; + this.type = this; + } + PullTypeSymbol.prototype.isArrayNamedTypeReference = function () { + if (this._isArrayNamedTypeReference === undefined) { + this._isArrayNamedTypeReference = this.computeIsArrayNamedTypeReference(); + } + + return this._isArrayNamedTypeReference; + }; + + PullTypeSymbol.prototype.computeIsArrayNamedTypeReference = function () { + var typeArgs = this.getTypeArguments(); + if (typeArgs && this.getTypeArguments().length === 1 && this.name === "Array") { + var declaration = this.getDeclarations()[0]; + + if (declaration && declaration.getParentDecl() && declaration.getParentDecl().getParentDecl() === null) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.isType = function () { + return true; + }; + PullTypeSymbol.prototype.isClass = function () { + return this.kind === 8 /* Class */ || (this._constructorMethod !== null); + }; + PullTypeSymbol.prototype.isFunction = function () { + return (this.kind & (33554432 /* ConstructorType */ | 16777216 /* FunctionType */)) !== 0; + }; + PullTypeSymbol.prototype.isConstructor = function () { + return this.kind === 33554432 /* ConstructorType */ || (this._associatedContainerTypeSymbol && this._associatedContainerTypeSymbol.isClass()); + }; + PullTypeSymbol.prototype.isTypeParameter = function () { + return false; + }; + PullTypeSymbol.prototype.isTypeVariable = function () { + return false; + }; + PullTypeSymbol.prototype.isError = function () { + return false; + }; + PullTypeSymbol.prototype.isEnum = function () { + return this.kind === 64 /* Enum */; + }; + + PullTypeSymbol.prototype.getTypeParameterArgumentMap = function () { + return null; + }; + + PullTypeSymbol.prototype.isObject = function () { + return TypeScript.hasFlag(this.kind, 8 /* Class */ | 33554432 /* ConstructorType */ | 64 /* Enum */ | 16777216 /* FunctionType */ | 16 /* Interface */ | 8388608 /* ObjectType */ | 256 /* ObjectLiteral */); + }; + + PullTypeSymbol.prototype.isFunctionType = function () { + return this.getCallSignatures().length > 0 || this.getConstructSignatures().length > 0; + }; + + PullTypeSymbol.prototype.getKnownBaseTypeCount = function () { + return this._knownBaseTypeCount; + }; + PullTypeSymbol.prototype.resetKnownBaseTypeCount = function () { + this._knownBaseTypeCount = 0; + }; + PullTypeSymbol.prototype.incrementKnownBaseCount = function () { + this._knownBaseTypeCount++; + }; + + PullTypeSymbol.prototype.setHasBaseTypeConflict = function () { + this._hasBaseTypeConflict = true; + }; + PullTypeSymbol.prototype.hasBaseTypeConflict = function () { + return this._hasBaseTypeConflict; + }; + + PullTypeSymbol.prototype.hasMembers = function () { + if (this._members !== TypeScript.sentinelEmptyArray) { + return true; + } + + var parents = this.getExtendedTypes(); + + for (var i = 0; i < parents.length; i++) { + if (parents[i].hasMembers()) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.setHasGenericSignature = function () { + this._hasGenericSignature = true; + }; + PullTypeSymbol.prototype.getHasGenericSignature = function () { + return this._hasGenericSignature; + }; + + PullTypeSymbol.prototype.setHasGenericMember = function () { + this._hasGenericMember = true; + }; + PullTypeSymbol.prototype.getHasGenericMember = function () { + return this._hasGenericMember; + }; + + PullTypeSymbol.prototype.setAssociatedContainerType = function (type) { + this._associatedContainerTypeSymbol = type; + }; + + PullTypeSymbol.prototype.getAssociatedContainerType = function () { + return this._associatedContainerTypeSymbol; + }; + + PullTypeSymbol.prototype.getArrayType = function () { + return this._arrayVersionOfThisType; + }; + + PullTypeSymbol.prototype.getElementType = function () { + return null; + }; + + PullTypeSymbol.prototype.setArrayType = function (arrayType) { + this._arrayVersionOfThisType = arrayType; + }; + + PullTypeSymbol.prototype.getFunctionSymbol = function () { + return this._functionSymbol; + }; + + PullTypeSymbol.prototype.setFunctionSymbol = function (symbol) { + if (symbol) { + this._functionSymbol = symbol; + } + }; + + PullTypeSymbol.prototype.findContainedNonMember = function (name) { + if (!this._containedNonMemberNameCache) { + return null; + } + + return this._containedNonMemberNameCache[name]; + }; + + PullTypeSymbol.prototype.findContainedNonMemberType = function (typeName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + if (!this._containedNonMemberTypeNameCache) { + return null; + } + + var nonMemberSymbol = this._containedNonMemberTypeNameCache[typeName]; + + if (nonMemberSymbol && kind !== 0 /* None */) { + nonMemberSymbol = TypeScript.hasFlag(nonMemberSymbol.kind, kind) ? nonMemberSymbol : null; + } + + return nonMemberSymbol; + }; + + PullTypeSymbol.prototype.findContainedNonMemberContainer = function (containerName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + if (!this._containedNonMemberContainerCache) { + return null; + } + + var nonMemberSymbol = this._containedNonMemberContainerCache[containerName]; + + if (nonMemberSymbol && kind !== 0 /* None */) { + nonMemberSymbol = TypeScript.hasFlag(nonMemberSymbol.kind, kind) ? nonMemberSymbol : null; + } + + return nonMemberSymbol; + }; + + PullTypeSymbol.prototype.addMember = function (memberSymbol) { + if (!memberSymbol) { + return; + } + + memberSymbol.setContainer(this); + + if (!this._memberNameCache) { + this._memberNameCache = TypeScript.createIntrinsicsObject(); + } + + if (this._members === TypeScript.sentinelEmptyArray) { + this._members = []; + } + + this._members.push(memberSymbol); + this._memberNameCache[memberSymbol.name] = memberSymbol; + }; + + PullTypeSymbol.prototype.addEnclosedMemberType = function (enclosedType) { + if (!enclosedType) { + return; + } + + enclosedType.setContainer(this); + + if (!this._enclosedTypeNameCache) { + this._enclosedTypeNameCache = TypeScript.createIntrinsicsObject(); + } + + if (!this._enclosedMemberTypes) { + this._enclosedMemberTypes = []; + } + + this._enclosedMemberTypes[this._enclosedMemberTypes.length] = enclosedType; + this._enclosedTypeNameCache[enclosedType.name] = enclosedType; + }; + + PullTypeSymbol.prototype.addEnclosedMemberContainer = function (enclosedContainer) { + if (!enclosedContainer) { + return; + } + + enclosedContainer.setContainer(this); + + if (!this._enclosedContainerCache) { + this._enclosedContainerCache = TypeScript.createIntrinsicsObject(); + } + + if (!this._enclosedMemberContainers) { + this._enclosedMemberContainers = []; + } + + this._enclosedMemberContainers[this._enclosedMemberContainers.length] = enclosedContainer; + this._enclosedContainerCache[enclosedContainer.name] = enclosedContainer; + }; + + PullTypeSymbol.prototype.addEnclosedNonMember = function (enclosedNonMember) { + if (!enclosedNonMember) { + return; + } + + enclosedNonMember.setContainer(this); + + if (!this._containedNonMemberNameCache) { + this._containedNonMemberNameCache = TypeScript.createIntrinsicsObject(); + } + + this._containedNonMemberNameCache[enclosedNonMember.name] = enclosedNonMember; + }; + + PullTypeSymbol.prototype.addEnclosedNonMemberType = function (enclosedNonMemberType) { + if (!enclosedNonMemberType) { + return; + } + + enclosedNonMemberType.setContainer(this); + + if (!this._containedNonMemberTypeNameCache) { + this._containedNonMemberTypeNameCache = TypeScript.createIntrinsicsObject(); + } + + this._containedNonMemberTypeNameCache[enclosedNonMemberType.name] = enclosedNonMemberType; + }; + + PullTypeSymbol.prototype.addEnclosedNonMemberContainer = function (enclosedNonMemberContainer) { + if (!enclosedNonMemberContainer) { + return; + } + + enclosedNonMemberContainer.setContainer(this); + + if (!this._containedNonMemberContainerCache) { + this._containedNonMemberContainerCache = TypeScript.createIntrinsicsObject(); + } + + this._containedNonMemberContainerCache[enclosedNonMemberContainer.name] = enclosedNonMemberContainer; + }; + + PullTypeSymbol.prototype.addTypeParameter = function (typeParameter) { + if (!typeParameter) { + return; + } + + if (!typeParameter.getContainer()) { + typeParameter.setContainer(this); + } + + if (!this._typeParameterNameCache) { + this._typeParameterNameCache = TypeScript.createIntrinsicsObject(); + } + + if (!this._typeParameters) { + this._typeParameters = []; + } + + this._typeParameters[this._typeParameters.length] = typeParameter; + this._typeParameterNameCache[typeParameter.getName()] = typeParameter; + }; + + PullTypeSymbol.prototype.getMembers = function () { + return this._members; + }; + + PullTypeSymbol.prototype.setHasDefaultConstructor = function (hasOne) { + if (typeof hasOne === "undefined") { hasOne = true; } + this._hasDefaultConstructor = hasOne; + }; + + PullTypeSymbol.prototype.getHasDefaultConstructor = function () { + return this._hasDefaultConstructor; + }; + + PullTypeSymbol.prototype.getConstructorMethod = function () { + return this._constructorMethod; + }; + + PullTypeSymbol.prototype.setConstructorMethod = function (constructorMethod) { + this._constructorMethod = constructorMethod; + }; + + PullTypeSymbol.prototype.getTypeParameters = function () { + if (!this._typeParameters) { + return TypeScript.sentinelEmptyArray; + } + + return this._typeParameters; + }; + + PullTypeSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + if (!!(this.kind && 8216 /* SomeInstantiatableType */) && this.isNamedTypeSymbol() && !this.isTypeParameter()) { + return this.getTypeParameters(); + } + + if (!this._allowedToReferenceTypeParameters) { + this._allowedToReferenceTypeParameters = TypeScript.PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl(this.getDeclarations()[0]); + } + + return this._allowedToReferenceTypeParameters; + }; + + PullTypeSymbol.prototype.isGeneric = function () { + return (this._typeParameters && this._typeParameters.length > 0) || this._hasGenericSignature || this._hasGenericMember || this.isArrayNamedTypeReference(); + }; + + PullTypeSymbol.prototype.canUseSimpleInstantiationCache = function (typeArgumentMap) { + if (this.isTypeParameter()) { + return true; + } + + var typeParameters = this.getTypeParameters(); + return typeArgumentMap && this.isNamedTypeSymbol() && typeParameters.length === 1 && typeArgumentMap[typeParameters[0].pullSymbolID].kind !== 8388608 /* ObjectType */; + }; + + PullTypeSymbol.prototype.getSimpleInstantiationCacheId = function (typeArgumentMap) { + if (this.isTypeParameter()) { + return typeArgumentMap[0].pullSymbolID; + } + + return typeArgumentMap[this.getTypeParameters()[0].pullSymbolID].pullSymbolID; + }; + + PullTypeSymbol.prototype.addSpecialization = function (specializedVersionOfThisType, typeArgumentMap) { + if (this.canUseSimpleInstantiationCache(typeArgumentMap)) { + if (!this._simpleInstantiationCache) { + this._simpleInstantiationCache = []; + } + + this._simpleInstantiationCache[this.getSimpleInstantiationCacheId(typeArgumentMap)] = specializedVersionOfThisType; + } else { + if (!this._complexInstantiationCache) { + this._complexInstantiationCache = TypeScript.createIntrinsicsObject(); + } + + this._complexInstantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)] = specializedVersionOfThisType; + } + + if (!this._specializedVersionsOfThisType) { + this._specializedVersionsOfThisType = []; + } + + this._specializedVersionsOfThisType.push(specializedVersionOfThisType); + }; + + PullTypeSymbol.prototype.getSpecialization = function (typeArgumentMap) { + if (this.canUseSimpleInstantiationCache(typeArgumentMap)) { + if (!this._simpleInstantiationCache) { + return null; + } + + var result = this._simpleInstantiationCache[this.getSimpleInstantiationCacheId(typeArgumentMap)]; + return result || null; + } else { + if (!this._complexInstantiationCache) { + return null; + } + + if (this.getAllowedToReferenceTypeParameters().length == 0) { + return this; + } + + var result = this._complexInstantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)]; + return result || null; + } + }; + + PullTypeSymbol.prototype.getKnownSpecializations = function () { + if (!this._specializedVersionsOfThisType) { + return TypeScript.sentinelEmptyArray; + } + + return this._specializedVersionsOfThisType; + }; + + PullTypeSymbol.prototype.getTypeArguments = function () { + return null; + }; + + PullTypeSymbol.prototype.getTypeArgumentsOrTypeParameters = function () { + return this.getTypeParameters(); + }; + + PullTypeSymbol.prototype.addCallOrConstructSignaturePrerequisiteBase = function (signature) { + if (signature.isGeneric()) { + this._hasGenericSignature = true; + } + + signature.functionType = this; + }; + + PullTypeSymbol.prototype.addCallSignaturePrerequisite = function (callSignature) { + if (!this._callSignatures) { + this._callSignatures = []; + } + + this.addCallOrConstructSignaturePrerequisiteBase(callSignature); + }; + + PullTypeSymbol.prototype.appendCallSignature = function (callSignature) { + this.addCallSignaturePrerequisite(callSignature); + this._callSignatures.push(callSignature); + }; + + PullTypeSymbol.prototype.insertCallSignatureAtIndex = function (callSignature, index) { + this.addCallSignaturePrerequisite(callSignature); + TypeScript.Debug.assert(index <= this._callSignatures.length); + if (index === this._callSignatures.length) { + this._callSignatures.push(callSignature); + } else { + this._callSignatures.splice(index, 0, callSignature); + } + }; + + PullTypeSymbol.prototype.addConstructSignaturePrerequisite = function (constructSignature) { + if (!this._constructSignatures) { + this._constructSignatures = []; + } + + this.addCallOrConstructSignaturePrerequisiteBase(constructSignature); + }; + + PullTypeSymbol.prototype.appendConstructSignature = function (constructSignature) { + this.addConstructSignaturePrerequisite(constructSignature); + this._constructSignatures.push(constructSignature); + }; + + PullTypeSymbol.prototype.insertConstructSignatureAtIndex = function (constructSignature, index) { + this.addConstructSignaturePrerequisite(constructSignature); + TypeScript.Debug.assert(index <= this._constructSignatures.length); + if (index === this._constructSignatures.length) { + this._constructSignatures.push(constructSignature); + } else { + this._constructSignatures.splice(index, 0, constructSignature); + } + }; + + PullTypeSymbol.prototype.addIndexSignature = function (indexSignature) { + if (!this._indexSignatures) { + this._indexSignatures = []; + } + + this._indexSignatures[this._indexSignatures.length] = indexSignature; + + if (indexSignature.isGeneric()) { + this._hasGenericSignature = true; + } + + indexSignature.functionType = this; + }; + + PullTypeSymbol.prototype.hasOwnCallSignatures = function () { + return this._callSignatures !== null; + }; + + PullTypeSymbol.prototype.getOwnCallSignatures = function () { + return this._callSignatures || TypeScript.sentinelEmptyArray; + }; + + PullTypeSymbol.prototype.getCallSignatures = function () { + if (this._allCallSignatures) { + return this._allCallSignatures; + } + + var signatures = []; + + if (this._callSignatures) { + signatures = signatures.concat(this._callSignatures); + } + + if (this._extendedTypes && this.kind === 16 /* Interface */) { + for (var i = 0; i < this._extendedTypes.length; i++) { + if (this._extendedTypes[i].hasBase(this)) { + continue; + } + + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._callSignatures, this._extendedTypes[i].getCallSignatures(), signatures); + } + } + + this._allCallSignatures = signatures; + + return signatures; + }; + + PullTypeSymbol.prototype.hasOwnConstructSignatures = function () { + return this._constructSignatures !== null; + }; + + PullTypeSymbol.prototype.getOwnDeclaredConstructSignatures = function () { + return this._constructSignatures || TypeScript.sentinelEmptyArray; + }; + + PullTypeSymbol.prototype.getConstructSignatures = function () { + if (this._allConstructSignatures) { + return this._allConstructSignatures; + } + + var signatures = []; + + if (this._constructSignatures) { + signatures = signatures.concat(this._constructSignatures); + } else if (this.isConstructor()) { + if (this._extendedTypes && this._extendedTypes.length > 0) { + signatures = this.getBaseClassConstructSignatures(this._extendedTypes[0]); + } else { + signatures = [this.getDefaultClassConstructSignature()]; + } + } + + if (this._extendedTypes && this.kind === 16 /* Interface */) { + for (var i = 0; i < this._extendedTypes.length; i++) { + if (this._extendedTypes[i].hasBase(this)) { + continue; + } + + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._constructSignatures, this._extendedTypes[i].getConstructSignatures(), signatures); + } + } + + this._allConstructSignatures = signatures; + + return signatures; + }; + + PullTypeSymbol.prototype.hasOwnIndexSignatures = function () { + return this._indexSignatures !== null; + }; + + PullTypeSymbol.prototype.getOwnIndexSignatures = function () { + return this._indexSignatures || TypeScript.sentinelEmptyArray; + }; + + PullTypeSymbol.prototype.getIndexSignatures = function () { + if (this._allIndexSignatures) { + return this._allIndexSignatures; + } + + var signatures = []; + + if (this._indexSignatures) { + signatures = signatures.concat(this._indexSignatures); + } + + if (this._extendedTypes) { + for (var i = 0; i < this._extendedTypes.length; i++) { + if (this._extendedTypes[i].hasBase(this)) { + continue; + } + + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._indexSignatures, this._extendedTypes[i].getIndexSignatures(), signatures); + } + } + + this._allIndexSignatures = signatures; + + return signatures; + }; + + PullTypeSymbol.prototype.getIndexSignaturesOfAugmentedType = function (resolver, globalFunctionInterface, globalObjectInterface) { + if (!this._allIndexSignaturesOfAugmentedType) { + var initialIndexSignatures = this.getIndexSignatures(); + var shouldAddFunctionSignatures = false; + var shouldAddObjectSignatures = false; + + if (globalFunctionInterface && this.isFunctionType() && this !== globalFunctionInterface) { + var functionIndexSignatures = globalFunctionInterface.getIndexSignatures(); + if (functionIndexSignatures.length) { + shouldAddFunctionSignatures = true; + } + } + + if (globalObjectInterface && this !== globalObjectInterface) { + var objectIndexSignatures = globalObjectInterface.getIndexSignatures(); + if (objectIndexSignatures.length) { + shouldAddObjectSignatures = true; + } + } + + if (shouldAddFunctionSignatures || shouldAddObjectSignatures) { + this._allIndexSignaturesOfAugmentedType = initialIndexSignatures.slice(0); + if (shouldAddFunctionSignatures) { + resolver._addUnhiddenSignaturesFromBaseType(initialIndexSignatures, functionIndexSignatures, this._allIndexSignaturesOfAugmentedType); + } + if (shouldAddObjectSignatures) { + if (shouldAddFunctionSignatures) { + initialIndexSignatures = initialIndexSignatures.concat(functionIndexSignatures); + } + resolver._addUnhiddenSignaturesFromBaseType(initialIndexSignatures, objectIndexSignatures, this._allIndexSignaturesOfAugmentedType); + } + } else { + this._allIndexSignaturesOfAugmentedType = initialIndexSignatures; + } + } + + return this._allIndexSignaturesOfAugmentedType; + }; + + PullTypeSymbol.prototype.getBaseClassConstructSignatures = function (baseType) { + TypeScript.Debug.assert(this.isConstructor() && baseType.isConstructor()); + var instanceTypeSymbol = this.getAssociatedContainerType(); + TypeScript.Debug.assert(instanceTypeSymbol.getDeclarations().length === 1); + if (baseType.hasBase(this)) { + return null; + } + + var baseConstructSignatures = baseType.getConstructSignatures(); + var signatures = []; + for (var i = 0; i < baseConstructSignatures.length; i++) { + var baseSignature = baseConstructSignatures[i]; + + baseSignature._resolveDeclaredSymbol(); + var currentSignature = new PullSignatureSymbol(2097152 /* ConstructSignature */, baseSignature.isDefinition()); + currentSignature.returnType = instanceTypeSymbol; + currentSignature.addTypeParametersFromReturnType(); + for (var j = 0; j < baseSignature.parameters.length; j++) { + currentSignature.addParameter(baseSignature.parameters[j], baseSignature.parameters[j].isOptional); + } + if (baseSignature.parameters.length > 0) { + currentSignature.hasVarArgs = baseSignature.parameters[baseSignature.parameters.length - 1].isVarArg; + } + + currentSignature.addDeclaration(instanceTypeSymbol.getDeclarations()[0]); + this.addCallOrConstructSignaturePrerequisiteBase(currentSignature); + signatures.push(currentSignature); + } + + return signatures; + }; + + PullTypeSymbol.prototype.getDefaultClassConstructSignature = function () { + TypeScript.Debug.assert(this.isConstructor()); + var instanceTypeSymbol = this.getAssociatedContainerType(); + TypeScript.Debug.assert(instanceTypeSymbol.getDeclarations().length == 1); + var signature = new PullSignatureSymbol(2097152 /* ConstructSignature */, true); + signature.returnType = instanceTypeSymbol; + signature.addTypeParametersFromReturnType(); + signature.addDeclaration(instanceTypeSymbol.getDeclarations()[0]); + this.addCallOrConstructSignaturePrerequisiteBase(signature); + + return signature; + }; + + PullTypeSymbol.prototype.addImplementedType = function (implementedType) { + if (!implementedType) { + return; + } + + if (!this._implementedTypes) { + this._implementedTypes = []; + } + + this._implementedTypes[this._implementedTypes.length] = implementedType; + + implementedType.addTypeThatExplicitlyImplementsThisType(this); + }; + + PullTypeSymbol.prototype.getImplementedTypes = function () { + if (!this._implementedTypes) { + return TypeScript.sentinelEmptyArray; + } + + return this._implementedTypes; + }; + + PullTypeSymbol.prototype.addExtendedType = function (extendedType) { + if (!extendedType) { + return; + } + + if (!this._extendedTypes) { + this._extendedTypes = []; + } + + this._extendedTypes[this._extendedTypes.length] = extendedType; + + extendedType.addTypeThatExtendsThisType(this); + }; + + PullTypeSymbol.prototype.getExtendedTypes = function () { + if (!this._extendedTypes) { + return TypeScript.sentinelEmptyArray; + } + + return this._extendedTypes; + }; + + PullTypeSymbol.prototype.addTypeThatExtendsThisType = function (type) { + if (!type) { + return; + } + + if (!this._typesThatExtendThisType) { + this._typesThatExtendThisType = []; + } + + this._typesThatExtendThisType[this._typesThatExtendThisType.length] = type; + }; + + PullTypeSymbol.prototype.getTypesThatExtendThisType = function () { + if (!this._typesThatExtendThisType) { + this._typesThatExtendThisType = []; + } + + return this._typesThatExtendThisType; + }; + + PullTypeSymbol.prototype.addTypeThatExplicitlyImplementsThisType = function (type) { + if (!type) { + return; + } + + if (!this._typesThatExplicitlyImplementThisType) { + this._typesThatExplicitlyImplementThisType = []; + } + + this._typesThatExplicitlyImplementThisType[this._typesThatExplicitlyImplementThisType.length] = type; + }; + + PullTypeSymbol.prototype.getTypesThatExplicitlyImplementThisType = function () { + if (!this._typesThatExplicitlyImplementThisType) { + this._typesThatExplicitlyImplementThisType = []; + } + + return this._typesThatExplicitlyImplementThisType; + }; + + PullTypeSymbol.prototype.hasBase = function (potentialBase, visited) { + if (typeof visited === "undefined") { visited = []; } + if (this === potentialBase || this.getRootSymbol() === potentialBase || this === potentialBase.getRootSymbol()) { + return true; + } + + if (TypeScript.ArrayUtilities.contains(visited, this)) { + return true; + } + + visited.push(this); + + var extendedTypes = this.getExtendedTypes(); + + for (var i = 0; i < extendedTypes.length; i++) { + if (extendedTypes[i].hasBase(potentialBase, visited)) { + return true; + } + } + + var implementedTypes = this.getImplementedTypes(); + + for (var i = 0; i < implementedTypes.length; i++) { + if (implementedTypes[i].hasBase(potentialBase, visited)) { + return true; + } + } + + visited.pop(); + + return false; + }; + + PullTypeSymbol.prototype.isValidBaseKind = function (baseType, isExtendedType) { + if (baseType.isError()) { + return false; + } + + var thisIsClass = this.isClass(); + if (isExtendedType) { + if (thisIsClass) { + return baseType.kind === 8 /* Class */; + } + } else { + if (!thisIsClass) { + return false; + } + } + + return !!(baseType.kind & (16 /* Interface */ | 8 /* Class */)); + }; + + PullTypeSymbol.prototype.findMember = function (name, lookInParent) { + var memberSymbol = null; + + if (this._memberNameCache) { + memberSymbol = this._memberNameCache[name]; + } + + if (memberSymbol || !lookInParent) { + return memberSymbol; + } + + if (this._extendedTypes) { + for (var i = 0; i < this._extendedTypes.length; i++) { + memberSymbol = this._extendedTypes[i].findMember(name, lookInParent); + + if (memberSymbol) { + return memberSymbol; + } + } + } + + return null; + }; + + PullTypeSymbol.prototype.findNestedType = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + var memberSymbol; + + if (!this._enclosedTypeNameCache) { + return null; + } + + memberSymbol = this._enclosedTypeNameCache[name]; + + if (memberSymbol && kind !== 0 /* None */) { + memberSymbol = TypeScript.hasFlag(memberSymbol.kind, kind) ? memberSymbol : null; + } + + return memberSymbol; + }; + + PullTypeSymbol.prototype.findNestedContainer = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + var memberSymbol; + + if (!this._enclosedContainerCache) { + return null; + } + + memberSymbol = this._enclosedContainerCache[name]; + + if (memberSymbol && kind !== 0 /* None */) { + memberSymbol = TypeScript.hasFlag(memberSymbol.kind, kind) ? memberSymbol : null; + } + + return memberSymbol; + }; + + PullTypeSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisiblity) { + var allMembers = []; + + if (this._members !== TypeScript.sentinelEmptyArray) { + for (var i = 0, n = this._members.length; i < n; i++) { + var member = this._members[i]; + if ((member.kind & searchDeclKind) && (memberVisiblity !== 2 /* externallyVisible */ || !member.anyDeclHasFlag(2 /* Private */))) { + allMembers[allMembers.length] = member; + } + } + } + + if (this._extendedTypes) { + var extenedMembersVisibility = memberVisiblity !== 0 /* all */ ? 2 /* externallyVisible */ : 0 /* all */; + + for (var i = 0, n = this._extendedTypes.length; i < n; i++) { + var extendedMembers = this._extendedTypes[i].getAllMembers(searchDeclKind, extenedMembersVisibility); + + for (var j = 0, m = extendedMembers.length; j < m; j++) { + var extendedMember = extendedMembers[j]; + if (!(this._memberNameCache && this._memberNameCache[extendedMember.name])) { + allMembers[allMembers.length] = extendedMember; + } + } + } + } + + if (this.isContainer()) { + if (this._enclosedMemberTypes) { + for (var i = 0; i < this._enclosedMemberTypes.length; i++) { + allMembers[allMembers.length] = this._enclosedMemberTypes[i]; + } + } + if (this._enclosedMemberContainers) { + for (var i = 0; i < this._enclosedMemberContainers.length; i++) { + allMembers[allMembers.length] = this._enclosedMemberContainers[i]; + } + } + } + + return allMembers; + }; + + PullTypeSymbol.prototype.findTypeParameter = function (name) { + if (!this._typeParameterNameCache) { + return null; + } + + return this._typeParameterNameCache[name]; + }; + + PullTypeSymbol.prototype.setResolved = function () { + _super.prototype.setResolved.call(this); + }; + + PullTypeSymbol.prototype.getNamePartForFullName = function () { + var name = _super.prototype.getNamePartForFullName.call(this); + + var typars = this.getTypeArgumentsOrTypeParameters(); + var typarString = PullSymbol.getTypeParameterString(typars, this, true); + return name + typarString; + }; + + PullTypeSymbol.prototype.getScopedName = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName) { + return this.getScopedNameEx(scopeSymbol, skipTypeParametersInName, useConstraintInName, false, false, skipInternalAliasName).toString(); + }; + + PullTypeSymbol.prototype.isNamedTypeSymbol = function () { + var kind = this.kind; + if (kind === 2 /* Primitive */ || kind === 8 /* Class */ || kind === 4 /* Container */ || kind === 32 /* DynamicModule */ || kind === 128 /* TypeAlias */ || kind === 64 /* Enum */ || kind === 8192 /* TypeParameter */ || ((kind === 16 /* Interface */ || kind === 8388608 /* ObjectType */) && this.name !== "")) { + return true; + } + + return false; + }; + + PullTypeSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + var s = this.getScopedNameEx(scopeSymbol, false, useConstraintInName).toString(); + return s; + }; + + PullTypeSymbol.prototype.getScopedNameEx = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName, shouldAllowArrayType) { + if (typeof shouldAllowArrayType === "undefined") { shouldAllowArrayType = true; } + if (this.isArrayNamedTypeReference() && shouldAllowArrayType) { + var elementType = this.getElementType(); + var elementMemberName = elementType ? (elementType.isArrayNamedTypeReference() || elementType.isNamedTypeSymbol() ? elementType.getScopedNameEx(scopeSymbol, false, false, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName) : elementType.getMemberTypeNameEx(false, scopeSymbol, getPrettyTypeName)) : TypeScript.MemberName.create("any"); + return TypeScript.MemberName.create(elementMemberName, "", "[]"); + } + + if (!this.isNamedTypeSymbol()) { + return this.getMemberTypeNameEx(true, scopeSymbol, getPrettyTypeName); + } + + if (skipTypeParametersInName) { + return TypeScript.MemberName.create(_super.prototype.getScopedName.call(this, scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName)); + } else { + var builder = new TypeScript.MemberNameArray(); + builder.prefix = _super.prototype.getScopedName.call(this, scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName); + + var typars = this.getTypeArgumentsOrTypeParameters(); + builder.add(PullSymbol.getTypeParameterStringEx(typars, scopeSymbol, getTypeParamMarkerInfo, useConstraintInName)); + + return builder; + } + }; + + PullTypeSymbol.prototype.hasOnlyOverloadCallSignatures = function () { + var members = this.getMembers(); + var callSignatures = this.getCallSignatures(); + var constructSignatures = this.getConstructSignatures(); + return members.length === 0 && constructSignatures.length === 0 && callSignatures.length > 1; + }; + + PullTypeSymbol.prototype.getTypeOfSymbol = function () { + var associatedContainerType = this.getAssociatedContainerType(); + if (associatedContainerType && associatedContainerType.isNamedTypeSymbol()) { + return associatedContainerType; + } + + var functionSymbol = this.getFunctionSymbol(); + if (functionSymbol && functionSymbol.kind === 16384 /* Function */ && !TypeScript.PullHelpers.isSymbolLocal(functionSymbol)) { + return TypeScript.PullHelpers.isExportedSymbolInClodule(functionSymbol) ? null : functionSymbol; + } + + return null; + }; + + PullTypeSymbol.prototype.getMemberTypeNameEx = function (topLevel, scopeSymbol, getPrettyTypeName) { + var members = this.getMembers(); + var callSignatures = this.getCallSignatures(); + var constructSignatures = this.getConstructSignatures(); + var indexSignatures = this.getIndexSignatures(); + + var typeOfSymbol = this.getTypeOfSymbol(); + if (typeOfSymbol) { + var nameForTypeOf = typeOfSymbol.getScopedNameEx(scopeSymbol, true); + return TypeScript.MemberName.create(nameForTypeOf, "typeof ", ""); + } + + if (members.length > 0 || callSignatures.length > 0 || constructSignatures.length > 0 || indexSignatures.length > 0) { + if (this._inMemberTypeNameEx) { + return TypeScript.MemberName.create("any"); + } + + this._inMemberTypeNameEx = true; + + var allMemberNames = new TypeScript.MemberNameArray(); + var curlies = !topLevel || indexSignatures.length !== 0; + var delim = "; "; + for (var i = 0; i < members.length; i++) { + if (members[i].kind === 65536 /* Method */ && members[i].type.hasOnlyOverloadCallSignatures()) { + var methodCallSignatures = members[i].type.getCallSignatures(); + var nameStr = members[i].getDisplayName(scopeSymbol) + (members[i].isOptional ? "?" : ""); + ; + var methodMemberNames = PullSignatureSymbol.getSignaturesTypeNameEx(methodCallSignatures, nameStr, false, false, scopeSymbol); + allMemberNames.addAll(methodMemberNames); + } else { + var memberTypeName = members[i].getNameAndTypeNameEx(scopeSymbol); + if (memberTypeName.isArray() && memberTypeName.delim === delim) { + allMemberNames.addAll(memberTypeName.entries); + } else { + allMemberNames.add(memberTypeName); + } + } + curlies = true; + } + + var getPrettyFunctionOverload = getPrettyTypeName && !curlies && this.hasOnlyOverloadCallSignatures(); + + var signatureCount = callSignatures.length + constructSignatures.length + indexSignatures.length; + var useShortFormSignature = !curlies && (signatureCount === 1); + var signatureMemberName; + + if (callSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(callSignatures, "", useShortFormSignature, false, scopeSymbol, getPrettyFunctionOverload); + allMemberNames.addAll(signatureMemberName); + } + + if (constructSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(constructSignatures, "new", useShortFormSignature, false, scopeSymbol); + allMemberNames.addAll(signatureMemberName); + } + + if (indexSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(indexSignatures, "", useShortFormSignature, true, scopeSymbol); + allMemberNames.addAll(signatureMemberName); + } + + if ((curlies) || (!getPrettyFunctionOverload && (signatureCount > 1) && topLevel)) { + allMemberNames.prefix = "{ "; + allMemberNames.suffix = "}"; + allMemberNames.delim = delim; + } else if (allMemberNames.entries.length > 1) { + allMemberNames.delim = delim; + } + + this._inMemberTypeNameEx = false; + + return allMemberNames; + } + + return TypeScript.MemberName.create("{}"); + }; + + PullTypeSymbol.prototype.getGenerativeTypeClassification = function (enclosingType) { + return 2 /* Closed */; + }; + + PullTypeSymbol.prototype.wrapsSomeTypeParameter = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + return this.getWrappingTypeParameterID(typeParameterArgumentMap, skipTypeArgumentCheck) != 0; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterID = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + var type = this; + + if (type.isTypeParameter()) { + if (typeParameterArgumentMap[type.pullSymbolID] || typeParameterArgumentMap[type.getRootSymbol().pullSymbolID]) { + return type.pullSymbolID; + } + + var constraint = type.getConstraint(); + var wrappingTypeParameterID = constraint ? constraint.getWrappingTypeParameterID(typeParameterArgumentMap) : 0; + return wrappingTypeParameterID; + } + + if (type.inWrapCheck) { + return 0; + } + + this._wrapsTypeParameterCache = this._wrapsTypeParameterCache || new TypeScript.WrapsTypeParameterCache(); + var wrappingTypeParameterID = this._wrapsTypeParameterCache.getWrapsTypeParameter(typeParameterArgumentMap); + if (wrappingTypeParameterID === undefined) { + wrappingTypeParameterID = this.getWrappingTypeParameterIDWorker(typeParameterArgumentMap, skipTypeArgumentCheck); + + this._wrapsTypeParameterCache.setWrapsTypeParameter(typeParameterArgumentMap, wrappingTypeParameterID); + } + return wrappingTypeParameterID; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterIDFromSignatures = function (signatures, typeParameterArgumentMap) { + for (var i = 0; i < signatures.length; i++) { + var wrappingTypeParameterID = signatures[i].getWrappingTypeParameterID(typeParameterArgumentMap); + if (wrappingTypeParameterID !== 0) { + return wrappingTypeParameterID; + } + } + + return 0; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterIDWorker = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + var type = this; + var wrappingTypeParameterID = 0; + + if (!skipTypeArgumentCheck) { + type.inWrapCheck = true; + + var typeArguments = type.getTypeArguments(); + + if (type.isGeneric() && !typeArguments) { + typeArguments = type.getTypeParameters(); + } + + if (typeArguments) { + for (var i = 0; !wrappingTypeParameterID && i < typeArguments.length; i++) { + wrappingTypeParameterID = typeArguments[i].getWrappingTypeParameterID(typeParameterArgumentMap); + } + } + } + + if (skipTypeArgumentCheck || !(type.kind & 8216 /* SomeInstantiatableType */) || !type.name) { + var members = type.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + for (var i = 0; !wrappingTypeParameterID && i < members.length; i++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(members[i]); + wrappingTypeParameterID = members[i].type.getWrappingTypeParameterID(typeParameterArgumentMap); + } + + wrappingTypeParameterID = wrappingTypeParameterID || this.getWrappingTypeParameterIDFromSignatures(type.getCallSignatures(), typeParameterArgumentMap) || this.getWrappingTypeParameterIDFromSignatures(type.getConstructSignatures(), typeParameterArgumentMap) || this.getWrappingTypeParameterIDFromSignatures(type.getIndexSignatures(), typeParameterArgumentMap); + } + + if (!skipTypeArgumentCheck) { + type.inWrapCheck = false; + } + + return wrappingTypeParameterID; + }; + + PullTypeSymbol.prototype.wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference = function (enclosingType) { + TypeScript.Debug.assert(this.isNamedTypeSymbol()); + TypeScript.Debug.assert(TypeScript.PullHelpers.getRootType(enclosingType) == enclosingType); + var knownWrapMap = TypeScript.BitMatrix.getBitMatrix(true); + var wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap); + knownWrapMap.release(); + return wrapsIntoInfinitelyExpandingTypeReference; + }; + + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse = function (enclosingType, knownWrapMap) { + var wrapsIntoInfinitelyExpandingTypeReference = knownWrapMap.valueAt(this.pullSymbolID, enclosingType.pullSymbolID); + if (wrapsIntoInfinitelyExpandingTypeReference != undefined) { + return wrapsIntoInfinitelyExpandingTypeReference; + } + + if (this.inWrapInfiniteExpandingReferenceCheck) { + return false; + } + + this.inWrapInfiniteExpandingReferenceCheck = true; + wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker(enclosingType, knownWrapMap); + knownWrapMap.setValueAt(this.pullSymbolID, enclosingType.pullSymbolID, wrapsIntoInfinitelyExpandingTypeReference); + this.inWrapInfiniteExpandingReferenceCheck = false; + + return wrapsIntoInfinitelyExpandingTypeReference; + }; + + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker = function (enclosingType, knownWrapMap) { + var thisRootType = TypeScript.PullHelpers.getRootType(this); + + if (thisRootType != enclosingType) { + var thisIsNamedType = this.isNamedTypeSymbol(); + + if (thisIsNamedType) { + if (thisRootType.inWrapInfiniteExpandingReferenceCheck) { + return false; + } + + thisRootType.inWrapInfiniteExpandingReferenceCheck = true; + } + + var wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceStructure(enclosingType, knownWrapMap); + + if (thisIsNamedType) { + thisRootType.inWrapInfiniteExpandingReferenceCheck = false; + } + + return wrapsIntoInfinitelyExpandingTypeReference; + } + + var enclosingTypeParameters = enclosingType.getTypeParameters(); + var typeArguments = this.getTypeArguments(); + for (var i = 0; i < typeArguments.length; i++) { + if (TypeScript.ArrayUtilities.contains(enclosingTypeParameters, typeArguments[i])) { + continue; + } + + if (typeArguments[i].wrapsSomeTypeParameter(this.getTypeParameterArgumentMap())) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceStructure = function (enclosingType, knownWrapMap) { + var members = this.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + for (var i = 0; i < members.length; i++) { + if (members[i].type && members[i].type._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; + } + } + + var sigs = this.getCallSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + sigs = this.getConstructSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + sigs = this.getIndexSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.widenedType = function (resolver, ast, context) { + if (!this._widenedType) { + this._widenedType = resolver.widenType(this, ast, context); + } + return this._widenedType; + }; + return PullTypeSymbol; + })(PullSymbol); + TypeScript.PullTypeSymbol = PullTypeSymbol; + + var PullPrimitiveTypeSymbol = (function (_super) { + __extends(PullPrimitiveTypeSymbol, _super); + function PullPrimitiveTypeSymbol(name) { + _super.call(this, name, 2 /* Primitive */); + + this.isResolved = true; + } + PullPrimitiveTypeSymbol.prototype.isAny = function () { + return !this.isStringConstant() && this.name === "any"; + }; + + PullPrimitiveTypeSymbol.prototype.isNull = function () { + return !this.isStringConstant() && this.name === "null"; + }; + + PullPrimitiveTypeSymbol.prototype.isUndefined = function () { + return !this.isStringConstant() && this.name === "undefined"; + }; + + PullPrimitiveTypeSymbol.prototype.isStringConstant = function () { + return false; + }; + + PullPrimitiveTypeSymbol.prototype.setUnresolved = function () { + }; + + PullPrimitiveTypeSymbol.prototype.getDisplayName = function () { + if (this.isNull() || this.isUndefined()) { + return "any"; + } else { + return _super.prototype.getDisplayName.call(this); + } + }; + return PullPrimitiveTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullPrimitiveTypeSymbol = PullPrimitiveTypeSymbol; + + var PullStringConstantTypeSymbol = (function (_super) { + __extends(PullStringConstantTypeSymbol, _super); + function PullStringConstantTypeSymbol(name) { + _super.call(this, name); + } + PullStringConstantTypeSymbol.prototype.isStringConstant = function () { + return true; + }; + return PullStringConstantTypeSymbol; + })(PullPrimitiveTypeSymbol); + TypeScript.PullStringConstantTypeSymbol = PullStringConstantTypeSymbol; + + var PullErrorTypeSymbol = (function (_super) { + __extends(PullErrorTypeSymbol, _super); + function PullErrorTypeSymbol(_anyType, name) { + _super.call(this, name); + this._anyType = _anyType; + + TypeScript.Debug.assert(this._anyType); + this.isResolved = true; + } + PullErrorTypeSymbol.prototype.isError = function () { + return true; + }; + + PullErrorTypeSymbol.prototype._getResolver = function () { + return this._anyType._getResolver(); + }; + + PullErrorTypeSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + return this._anyType.getName(scopeSymbol, useConstraintInName); + }; + + PullErrorTypeSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { + return this._anyType.getName(scopeSymbol, useConstraintInName); + }; + + PullErrorTypeSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + return this._anyType.getName(scopeSymbol, useConstraintInName); + }; + return PullErrorTypeSymbol; + })(PullPrimitiveTypeSymbol); + TypeScript.PullErrorTypeSymbol = PullErrorTypeSymbol; + + var PullContainerSymbol = (function (_super) { + __extends(PullContainerSymbol, _super); + function PullContainerSymbol(name, kind) { + _super.call(this, name, kind); + this.instanceSymbol = null; + this.assignedValue = null; + this.assignedType = null; + this.assignedContainer = null; + } + PullContainerSymbol.prototype.isContainer = function () { + return true; + }; + + PullContainerSymbol.prototype.setInstanceSymbol = function (symbol) { + this.instanceSymbol = symbol; + }; + + PullContainerSymbol.prototype.getInstanceSymbol = function () { + return this.instanceSymbol; + }; + + PullContainerSymbol.prototype.setExportAssignedValueSymbol = function (symbol) { + this.assignedValue = symbol; + }; + + PullContainerSymbol.prototype.getExportAssignedValueSymbol = function () { + return this.assignedValue; + }; + + PullContainerSymbol.prototype.setExportAssignedTypeSymbol = function (type) { + this.assignedType = type; + }; + + PullContainerSymbol.prototype.getExportAssignedTypeSymbol = function () { + return this.assignedType; + }; + + PullContainerSymbol.prototype.setExportAssignedContainerSymbol = function (container) { + this.assignedContainer = container; + }; + + PullContainerSymbol.prototype.getExportAssignedContainerSymbol = function () { + return this.assignedContainer; + }; + + PullContainerSymbol.prototype.hasExportAssignment = function () { + return !!this.assignedValue || !!this.assignedType || !!this.assignedContainer; + }; + + PullContainerSymbol.usedAsSymbol = function (containerSymbol, symbol) { + if (!containerSymbol || !containerSymbol.isContainer()) { + return false; + } + + if (!containerSymbol.isAlias() && containerSymbol.type === symbol) { + return true; + } + + var moduleSymbol = containerSymbol; + var valueExportSymbol = moduleSymbol.getExportAssignedValueSymbol(); + var typeExportSymbol = moduleSymbol.getExportAssignedTypeSymbol(); + var containerExportSymbol = moduleSymbol.getExportAssignedContainerSymbol(); + if (valueExportSymbol || typeExportSymbol || containerExportSymbol) { + if (valueExportSymbol === symbol || typeExportSymbol == symbol || containerExportSymbol == symbol) { + return true; + } + + if (containerExportSymbol != containerSymbol) { + return PullContainerSymbol.usedAsSymbol(containerExportSymbol, symbol); + } + } + + return false; + }; + + PullContainerSymbol.prototype.getInstanceType = function () { + return this.instanceSymbol ? this.instanceSymbol.type : null; + }; + return PullContainerSymbol; + })(PullTypeSymbol); + TypeScript.PullContainerSymbol = PullContainerSymbol; + + var PullTypeAliasSymbol = (function (_super) { + __extends(PullTypeAliasSymbol, _super); + function PullTypeAliasSymbol(name) { + _super.call(this, name, 128 /* TypeAlias */); + this._assignedValue = null; + this._assignedType = null; + this._assignedContainer = null; + this._isUsedAsValue = false; + this._typeUsedExternally = false; + this._isUsedInExportAlias = false; + this.retrievingExportAssignment = false; + this.linkedAliasSymbols = null; + } + PullTypeAliasSymbol.prototype.isUsedInExportedAlias = function () { + this._resolveDeclaredSymbol(); + return this._isUsedInExportAlias; + }; + + PullTypeAliasSymbol.prototype.typeUsedExternally = function () { + this._resolveDeclaredSymbol(); + return this._typeUsedExternally; + }; + + PullTypeAliasSymbol.prototype.isUsedAsValue = function () { + this._resolveDeclaredSymbol(); + return this._isUsedAsValue; + }; + + PullTypeAliasSymbol.prototype.setTypeUsedExternally = function () { + this._typeUsedExternally = true; + }; + + PullTypeAliasSymbol.prototype.setIsUsedInExportedAlias = function () { + this._isUsedInExportAlias = true; + if (this.linkedAliasSymbols) { + this.linkedAliasSymbols.forEach(function (s) { + return s.setIsUsedInExportedAlias(); + }); + } + }; + + PullTypeAliasSymbol.prototype.addLinkedAliasSymbol = function (contingentValueSymbol) { + if (!this.linkedAliasSymbols) { + this.linkedAliasSymbols = [contingentValueSymbol]; + } else { + this.linkedAliasSymbols.push(contingentValueSymbol); + } + }; + + PullTypeAliasSymbol.prototype.setIsUsedAsValue = function () { + this._isUsedAsValue = true; + if (this.linkedAliasSymbols) { + this.linkedAliasSymbols.forEach(function (s) { + return s.setIsUsedAsValue(); + }); + } + }; + + PullTypeAliasSymbol.prototype.assignedValue = function () { + this._resolveDeclaredSymbol(); + return this._assignedValue; + }; + + PullTypeAliasSymbol.prototype.assignedType = function () { + this._resolveDeclaredSymbol(); + return this._assignedType; + }; + + PullTypeAliasSymbol.prototype.assignedContainer = function () { + this._resolveDeclaredSymbol(); + return this._assignedContainer; + }; + + PullTypeAliasSymbol.prototype.isAlias = function () { + return true; + }; + PullTypeAliasSymbol.prototype.isContainer = function () { + return true; + }; + + PullTypeAliasSymbol.prototype.setAssignedValueSymbol = function (symbol) { + this._assignedValue = symbol; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedValueSymbol = function () { + if (this._assignedValue) { + return this._assignedValue; + } + + if (this.retrievingExportAssignment) { + return null; + } + + if (this._assignedContainer) { + if (this._assignedContainer.hasExportAssignment()) { + this.retrievingExportAssignment = true; + var sym = this._assignedContainer.getExportAssignedValueSymbol(); + this.retrievingExportAssignment = false; + return sym; + } + + return this._assignedContainer.getInstanceSymbol(); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.setAssignedTypeSymbol = function (type) { + this._assignedType = type; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedTypeSymbol = function () { + if (this.retrievingExportAssignment) { + return null; + } + + if (this._assignedType) { + if (this._assignedType.isAlias()) { + this.retrievingExportAssignment = true; + var sym = this._assignedType.getExportAssignedTypeSymbol(); + this.retrievingExportAssignment = false; + } else if (this._assignedType !== this._assignedContainer) { + return this._assignedType; + } + } + + if (this._assignedContainer) { + this.retrievingExportAssignment = true; + var sym = this._assignedContainer.getExportAssignedTypeSymbol(); + this.retrievingExportAssignment = false; + if (sym) { + return sym; + } + } + + return this._assignedContainer; + }; + + PullTypeAliasSymbol.prototype.setAssignedContainerSymbol = function (container) { + this._assignedContainer = container; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedContainerSymbol = function () { + if (this.retrievingExportAssignment) { + return null; + } + + if (this._assignedContainer) { + this.retrievingExportAssignment = true; + var sym = this._assignedContainer.getExportAssignedContainerSymbol(); + this.retrievingExportAssignment = false; + if (sym) { + return sym; + } + } + + return this._assignedContainer; + }; + + PullTypeAliasSymbol.prototype.getMembers = function () { + if (this._assignedType) { + return this._assignedType.getMembers(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.getCallSignatures = function () { + if (this._assignedType) { + return this._assignedType.getCallSignatures(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.getConstructSignatures = function () { + if (this._assignedType) { + return this._assignedType.getConstructSignatures(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.getIndexSignatures = function () { + if (this._assignedType) { + return this._assignedType.getIndexSignatures(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.findMember = function (name) { + if (this._assignedType) { + return this._assignedType.findMember(name, true); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.findNestedType = function (name) { + if (this._assignedType) { + return this._assignedType.findNestedType(name); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.findNestedContainer = function (name) { + if (this._assignedType) { + return this._assignedType.findNestedContainer(name); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisibility) { + if (this._assignedType) { + return this._assignedType.getAllMembers(searchDeclKind, memberVisibility); + } + + return TypeScript.sentinelEmptyArray; + }; + return PullTypeAliasSymbol; + })(PullTypeSymbol); + TypeScript.PullTypeAliasSymbol = PullTypeAliasSymbol; + + var PullTypeParameterSymbol = (function (_super) { + __extends(PullTypeParameterSymbol, _super); + function PullTypeParameterSymbol(name) { + _super.call(this, name, 8192 /* TypeParameter */); + this._constraint = null; + } + PullTypeParameterSymbol.prototype.isTypeParameter = function () { + return true; + }; + + PullTypeParameterSymbol.prototype.setConstraint = function (constraintType) { + this._constraint = constraintType; + }; + + PullTypeParameterSymbol.prototype.getConstraint = function () { + return this._constraint; + }; + + PullTypeParameterSymbol.prototype.getBaseConstraint = function (semanticInfoChain) { + var preBaseConstraint = this.getConstraintRecursively({}); + TypeScript.Debug.assert(preBaseConstraint === null || !preBaseConstraint.isTypeParameter()); + return preBaseConstraint || semanticInfoChain.emptyTypeSymbol; + }; + + PullTypeParameterSymbol.prototype.getConstraintRecursively = function (visitedTypeParameters) { + var constraint = this.getConstraint(); + + if (constraint) { + if (constraint.isTypeParameter()) { + var constraintAsTypeParameter = constraint; + if (!visitedTypeParameters[constraintAsTypeParameter.pullSymbolID]) { + visitedTypeParameters[constraintAsTypeParameter.pullSymbolID] = constraintAsTypeParameter; + return constraintAsTypeParameter.getConstraintRecursively(visitedTypeParameters); + } + } else { + return constraint; + } + } + + return null; + }; + + PullTypeParameterSymbol.prototype.getDefaultConstraint = function (semanticInfoChain) { + return this._constraint || semanticInfoChain.emptyTypeSymbol; + }; + + PullTypeParameterSymbol.prototype.getCallSignatures = function () { + if (this._constraint) { + return this._constraint.getCallSignatures(); + } + + return _super.prototype.getCallSignatures.call(this); + }; + + PullTypeParameterSymbol.prototype.getConstructSignatures = function () { + if (this._constraint) { + return this._constraint.getConstructSignatures(); + } + + return _super.prototype.getConstructSignatures.call(this); + }; + + PullTypeParameterSymbol.prototype.getIndexSignatures = function () { + if (this._constraint) { + return this._constraint.getIndexSignatures(); + } + + return _super.prototype.getIndexSignatures.call(this); + }; + + PullTypeParameterSymbol.prototype.isGeneric = function () { + return true; + }; + + PullTypeParameterSymbol.prototype.fullName = function (scopeSymbol) { + var name = this.getDisplayName(scopeSymbol); + var container = this.getContainer(); + if (container) { + var containerName = container.fullName(scopeSymbol); + name = name + " in " + containerName; + } + + return name; + }; + + PullTypeParameterSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + var name = _super.prototype.getName.call(this, scopeSymbol); + + if (this.isPrinting) { + return name; + } + + this.isPrinting = true; + + if (useConstraintInName && this._constraint) { + name += " extends " + this._constraint.toString(scopeSymbol); + } + + this.isPrinting = false; + + return name; + }; + + PullTypeParameterSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { + var name = _super.prototype.getDisplayName.call(this, scopeSymbol, useConstraintInName, skipInternalAliasName); + + if (this.isPrinting) { + return name; + } + + this.isPrinting = true; + + if (useConstraintInName && this._constraint) { + name += " extends " + this._constraint.toString(scopeSymbol); + } + + this.isPrinting = false; + + return name; + }; + + PullTypeParameterSymbol.prototype.isExternallyVisible = function (inIsExternallyVisibleSymbols) { + return true; + }; + return PullTypeParameterSymbol; + })(PullTypeSymbol); + TypeScript.PullTypeParameterSymbol = PullTypeParameterSymbol; + + var PullAccessorSymbol = (function (_super) { + __extends(PullAccessorSymbol, _super); + function PullAccessorSymbol(name) { + _super.call(this, name, 4096 /* Property */); + this._getterSymbol = null; + this._setterSymbol = null; + } + PullAccessorSymbol.prototype.isAccessor = function () { + return true; + }; + + PullAccessorSymbol.prototype.setSetter = function (setter) { + if (!setter) { + return; + } + + this._setterSymbol = setter; + }; + + PullAccessorSymbol.prototype.getSetter = function () { + return this._setterSymbol; + }; + + PullAccessorSymbol.prototype.setGetter = function (getter) { + if (!getter) { + return; + } + + this._getterSymbol = getter; + }; + + PullAccessorSymbol.prototype.getGetter = function () { + return this._getterSymbol; + }; + return PullAccessorSymbol; + })(PullSymbol); + TypeScript.PullAccessorSymbol = PullAccessorSymbol; + + function getIDForTypeSubstitutions(instantiatingTypeOrSignature, typeArgumentMap) { + var substitution = ""; + var members = null; + + var allowedToReferenceTypeParameters = instantiatingTypeOrSignature.getAllowedToReferenceTypeParameters(); + for (var i = 0; i < allowedToReferenceTypeParameters.length; i++) { + var typeParameter = allowedToReferenceTypeParameters[i]; + var typeParameterID = typeParameter.pullSymbolID; + var typeArg = typeArgumentMap[typeParameterID]; + if (!typeArg) { + typeArg = typeParameter; + } + substitution += typeParameterID + ":" + getIDForTypeSubstitutionsOfType(typeArg); + } + + return substitution; + } + TypeScript.getIDForTypeSubstitutions = getIDForTypeSubstitutions; + + function getIDForTypeSubstitutionsOfType(type) { + var structure; + if (type.isError()) { + structure = "E" + getIDForTypeSubstitutionsOfType(type._anyType); + } else if (!type.isNamedTypeSymbol()) { + structure = getIDForTypeSubstitutionsFromObjectType(type); + } + + if (!structure) { + structure = type.pullSymbolID + "#"; + } + + return structure; + } + + function getIDForTypeSubstitutionsFromObjectType(type) { + if (type.isResolved) { + var getIDForTypeSubStitutionWalker = new GetIDForTypeSubStitutionWalker(); + TypeScript.PullHelpers.walkPullTypeSymbolStructure(type, getIDForTypeSubStitutionWalker); + } + + return null; + } + + var GetIDForTypeSubStitutionWalker = (function () { + function GetIDForTypeSubStitutionWalker() { + this.structure = ""; + } + GetIDForTypeSubStitutionWalker.prototype.memberSymbolWalk = function (memberSymbol) { + this.structure += memberSymbol.name + "@" + getIDForTypeSubstitutionsOfType(memberSymbol.type); + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.callSignatureWalk = function (signatureSymbol) { + this.structure += "("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.constructSignatureWalk = function (signatureSymbol) { + this.structure += "new("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.indexSignatureWalk = function (signatureSymbol) { + this.structure += "[]("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.signatureParameterWalk = function (parameterSymbol) { + this.structure += parameterSymbol.name + "@" + getIDForTypeSubstitutionsOfType(parameterSymbol.type); + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.signatureReturnTypeWalk = function (returnType) { + this.structure += ")" + getIDForTypeSubstitutionsOfType(returnType); + return true; + }; + return GetIDForTypeSubStitutionWalker; + })(); + + (function (GetAllMembersVisiblity) { + GetAllMembersVisiblity[GetAllMembersVisiblity["all"] = 0] = "all"; + + GetAllMembersVisiblity[GetAllMembersVisiblity["internallyVisible"] = 1] = "internallyVisible"; + + GetAllMembersVisiblity[GetAllMembersVisiblity["externallyVisible"] = 2] = "externallyVisible"; + })(TypeScript.GetAllMembersVisiblity || (TypeScript.GetAllMembersVisiblity = {})); + var GetAllMembersVisiblity = TypeScript.GetAllMembersVisiblity; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var EnclosingTypeWalkerState = (function () { + function EnclosingTypeWalkerState() { + } + EnclosingTypeWalkerState.getDefaultEnclosingTypeWalkerState = function () { + var defaultEnclosingTypeWalkerState = new EnclosingTypeWalkerState(); + defaultEnclosingTypeWalkerState._hasSetEnclosingType = false; + return defaultEnclosingTypeWalkerState; + }; + + EnclosingTypeWalkerState.getNonGenericEnclosingTypeWalkerState = function () { + var defaultEnclosingTypeWalkerState = new EnclosingTypeWalkerState(); + defaultEnclosingTypeWalkerState._hasSetEnclosingType = true; + return defaultEnclosingTypeWalkerState; + }; + + EnclosingTypeWalkerState.getGenericEnclosingTypeWalkerState = function (genericEnclosingType) { + var defaultEnclosingTypeWalkerState = new EnclosingTypeWalkerState(); + defaultEnclosingTypeWalkerState._hasSetEnclosingType = true; + defaultEnclosingTypeWalkerState._currentSymbols = [TypeScript.PullHelpers.getRootType(genericEnclosingType)]; + return defaultEnclosingTypeWalkerState; + }; + return EnclosingTypeWalkerState; + })(); + TypeScript.EnclosingTypeWalkerState = EnclosingTypeWalkerState; + + var PullTypeEnclosingTypeWalker = (function () { + function PullTypeEnclosingTypeWalker() { + this.setDefaultTypeWalkerState(); + } + PullTypeEnclosingTypeWalker.prototype.setDefaultTypeWalkerState = function () { + this.enclosingTypeWalkerState = PullTypeEnclosingTypeWalker._defaultEnclosingTypeWalkerState; + }; + + PullTypeEnclosingTypeWalker.prototype.setNonGenericEnclosingTypeWalkerState = function () { + this.enclosingTypeWalkerState = PullTypeEnclosingTypeWalker._nonGenericEnclosingTypeWalkerState; + }; + + PullTypeEnclosingTypeWalker.prototype.canSymbolOrDeclBeUsedAsEnclosingTypeHelper = function (name, kind) { + return name && (kind === 8 /* Class */ || kind === 16 /* Interface */); + }; + + PullTypeEnclosingTypeWalker.prototype.canDeclBeUsedAsEnclosingType = function (decl) { + return this.canSymbolOrDeclBeUsedAsEnclosingTypeHelper(decl.name, decl.kind); + }; + + PullTypeEnclosingTypeWalker.prototype.canSymbolBeUsedAsEnclosingType = function (symbol) { + return this.canSymbolOrDeclBeUsedAsEnclosingTypeHelper(symbol.name, symbol.kind); + }; + + PullTypeEnclosingTypeWalker.prototype.getEnclosingType = function () { + var currentSymbols = this.enclosingTypeWalkerState._currentSymbols; + if (currentSymbols) { + TypeScript.Debug.assert(currentSymbols.length > 0); + return currentSymbols[0]; + } + + return null; + }; + + PullTypeEnclosingTypeWalker.prototype._canWalkStructure = function () { + var enclosingType = this.getEnclosingType(); + TypeScript.Debug.assert(!enclosingType || enclosingType.isGeneric()); + return !!enclosingType; + }; + + PullTypeEnclosingTypeWalker.prototype._getCurrentSymbol = function () { + var currentSymbols = this.enclosingTypeWalkerState._currentSymbols; + if (currentSymbols && currentSymbols.length) { + return currentSymbols[currentSymbols.length - 1]; + } + + return null; + }; + + PullTypeEnclosingTypeWalker.prototype.getGenerativeClassification = function () { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + if (!currentType) { + return 0 /* Unknown */; + } + + var variableNeededToFixNodeJitterBug = this.getEnclosingType(); + + return currentType.getGenerativeTypeClassification(variableNeededToFixNodeJitterBug); + } + + return 2 /* Closed */; + }; + + PullTypeEnclosingTypeWalker.prototype._pushSymbol = function (symbol) { + return this.enclosingTypeWalkerState._currentSymbols.push(symbol); + }; + + PullTypeEnclosingTypeWalker.prototype._popSymbol = function () { + return this.enclosingTypeWalkerState._currentSymbols.pop(); + }; + + PullTypeEnclosingTypeWalker.prototype.setSymbolAsEnclosingType = function (type) { + if (type.isGeneric()) { + this.enclosingTypeWalkerState = EnclosingTypeWalkerState.getGenericEnclosingTypeWalkerState(type); + } else { + this.setNonGenericEnclosingTypeWalkerState(); + } + }; + + PullTypeEnclosingTypeWalker.prototype._setEnclosingTypeOfParentDecl = function (decl, setSignature) { + var parentDecl = decl.getParentDecl(); + + if (parentDecl && !(parentDecl.kind & (164 /* SomeContainer */ | 1 /* Script */))) { + if (this.canDeclBeUsedAsEnclosingType(parentDecl)) { + this.setSymbolAsEnclosingType(parentDecl.getSymbol()); + } else { + this._setEnclosingTypeOfParentDecl(parentDecl, true); + } + + if (this._canWalkStructure()) { + var symbol = decl.getSymbol(); + if (symbol) { + if (!symbol.isType() && !symbol.isSignature()) { + symbol = symbol.type; + } + + this._pushSymbol(symbol); + } + + if (setSignature) { + var signature = decl.getSignatureSymbol(); + if (signature) { + this._pushSymbol(signature); + } + } + } + } + }; + + PullTypeEnclosingTypeWalker.prototype.setEnclosingTypeForSymbol = function (symbol) { + var currentEnclosingTypeWalkerState = this.enclosingTypeWalkerState; + if (this.canSymbolBeUsedAsEnclosingType(symbol)) { + this.setSymbolAsEnclosingType(symbol); + } else { + this.setDefaultTypeWalkerState(); + + var decls = symbol.getDeclarations(); + for (var i = 0; i < decls.length; i++) { + var decl = decls[i]; + this._setEnclosingTypeOfParentDecl(decl, symbol.isSignature()); + + if (this.enclosingTypeWalkerState._hasSetEnclosingType) { + break; + } + } + + if (!this.enclosingTypeWalkerState._hasSetEnclosingType) { + this.setNonGenericEnclosingTypeWalkerState(); + } + } + return currentEnclosingTypeWalkerState; + }; + + PullTypeEnclosingTypeWalker.prototype.startWalkingType = function (symbol) { + var currentState = this.enclosingTypeWalkerState; + + var setEnclosingTypeForSymbol = !this.enclosingTypeWalkerState._hasSetEnclosingType || this.canSymbolBeUsedAsEnclosingType(symbol); + if (setEnclosingTypeForSymbol) { + this.setEnclosingTypeForSymbol(symbol); + } + return currentState; + }; + + PullTypeEnclosingTypeWalker.prototype.endWalkingType = function (stateWhenStartedWalkingTypes) { + this.enclosingTypeWalkerState = stateWhenStartedWalkingTypes; + }; + + PullTypeEnclosingTypeWalker.prototype.walkMemberType = function (memberName, resolver) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + var memberSymbol = currentType ? resolver._getNamedPropertySymbolOfAugmentedType(memberName, currentType) : null; + this._pushSymbol(memberSymbol ? memberSymbol.type : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkMemberType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkSignature = function (kind, index) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + var signatures; + if (currentType) { + if (kind == 1048576 /* CallSignature */) { + signatures = currentType.getCallSignatures(); + } else if (kind == 2097152 /* ConstructSignature */) { + signatures = currentType.getConstructSignatures(); + } else { + signatures = currentType.getIndexSignatures(); + } + } + + this._pushSymbol(signatures ? signatures[index] : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkSignature = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkTypeArgument = function (index) { + if (this._canWalkStructure()) { + var typeArgument = null; + var currentType = this._getCurrentSymbol(); + if (currentType) { + var typeArguments = currentType.getTypeArguments(); + typeArgument = typeArguments ? typeArguments[index] : null; + } + this._pushSymbol(typeArgument); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkTypeArgument = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkTypeParameterConstraint = function (index) { + if (this._canWalkStructure()) { + var typeParameters; + var currentSymbol = this._getCurrentSymbol(); + if (currentSymbol) { + if (currentSymbol.isSignature()) { + typeParameters = currentSymbol.getTypeParameters(); + } else { + TypeScript.Debug.assert(currentSymbol.isType()); + typeParameters = currentSymbol.getTypeParameters(); + } + } + this._pushSymbol(typeParameters ? typeParameters[index].getConstraint() : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkTypeParameterConstraint = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkReturnType = function () { + if (this._canWalkStructure()) { + var currentSignature = this._getCurrentSymbol(); + this._pushSymbol(currentSignature ? currentSignature.returnType : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkReturnType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkParameterType = function (iParam) { + if (this._canWalkStructure()) { + var currentSignature = this._getCurrentSymbol(); + this._pushSymbol(currentSignature ? currentSignature.getParameterTypeAtIndex(iParam) : null); + } + }; + PullTypeEnclosingTypeWalker.prototype.postWalkParameterType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.getBothKindOfIndexSignatures = function (resolver, context, includeAugmentedType) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + if (currentType) { + return resolver._getBothKindsOfIndexSignatures(currentType, context, includeAugmentedType); + } + } + return null; + }; + + PullTypeEnclosingTypeWalker.prototype.walkIndexSignatureReturnType = function (indexSigInfo, useStringIndexSignature, onlySignature) { + if (this._canWalkStructure()) { + var indexSig = indexSigInfo ? (useStringIndexSignature ? indexSigInfo.stringSignature : indexSigInfo.numericSignature) : null; + this._pushSymbol(indexSig); + if (!onlySignature) { + this._pushSymbol(indexSig ? indexSig.returnType : null); + } + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkIndexSignatureReturnType = function (onlySignature) { + if (this._canWalkStructure()) { + if (!onlySignature) { + this._popSymbol(); + } + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.resetEnclosingTypeWalkerState = function () { + var currentState = this.enclosingTypeWalkerState; + this.setDefaultTypeWalkerState(); + return currentState; + }; + + PullTypeEnclosingTypeWalker.prototype.setEnclosingTypeWalkerState = function (enclosingTypeWalkerState) { + if (enclosingTypeWalkerState) { + this.enclosingTypeWalkerState = enclosingTypeWalkerState; + } else { + this.setDefaultTypeWalkerState(); + } + }; + PullTypeEnclosingTypeWalker._defaultEnclosingTypeWalkerState = EnclosingTypeWalkerState.getDefaultEnclosingTypeWalkerState(); + + PullTypeEnclosingTypeWalker._nonGenericEnclosingTypeWalkerState = EnclosingTypeWalkerState.getNonGenericEnclosingTypeWalkerState(); + return PullTypeEnclosingTypeWalker; + })(); + TypeScript.PullTypeEnclosingTypeWalker = PullTypeEnclosingTypeWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CandidateInferenceInfo = (function () { + function CandidateInferenceInfo() { + this.typeParameter = null; + this._inferredTypeAfterFixing = null; + this.inferenceCandidates = []; + } + CandidateInferenceInfo.prototype.addCandidate = function (candidate) { + if (!this._inferredTypeAfterFixing) { + this.inferenceCandidates[this.inferenceCandidates.length] = candidate; + } + }; + + CandidateInferenceInfo.prototype.isFixed = function () { + return !!this._inferredTypeAfterFixing; + }; + + CandidateInferenceInfo.prototype.fixTypeParameter = function (resolver, context) { + var _this = this; + if (!this._inferredTypeAfterFixing) { + var collection = { + getLength: function () { + return _this.inferenceCandidates.length; + }, + getTypeAtIndex: function (index) { + return _this.inferenceCandidates[index].type; + } + }; + + var bestCommonType = resolver.findBestCommonType(collection, context, new TypeScript.TypeComparisonInfo()); + this._inferredTypeAfterFixing = bestCommonType.widenedType(resolver, null, context); + } + }; + return CandidateInferenceInfo; + })(); + TypeScript.CandidateInferenceInfo = CandidateInferenceInfo; + + var TypeArgumentInferenceContext = (function () { + function TypeArgumentInferenceContext(resolver, context, signatureBeingInferred) { + this.resolver = resolver; + this.context = context; + this.signatureBeingInferred = signatureBeingInferred; + this.inferenceCache = TypeScript.BitMatrix.getBitMatrix(false); + this.candidateCache = []; + var typeParameters = signatureBeingInferred.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + this.addInferenceRoot(typeParameters[i]); + } + } + TypeArgumentInferenceContext.prototype.alreadyRelatingTypes = function (objectType, parameterType) { + if (this.inferenceCache.valueAt(objectType.pullSymbolID, parameterType.pullSymbolID)) { + return true; + } else { + this.inferenceCache.setValueAt(objectType.pullSymbolID, parameterType.pullSymbolID, true); + return false; + } + }; + + TypeArgumentInferenceContext.prototype.resetRelationshipCache = function () { + this.inferenceCache.release(); + this.inferenceCache = TypeScript.BitMatrix.getBitMatrix(false); + }; + + TypeArgumentInferenceContext.prototype.addInferenceRoot = function (param) { + var info = this.candidateCache[param.pullSymbolID]; + + if (!info) { + info = new CandidateInferenceInfo(); + info.typeParameter = param; + this.candidateCache[param.pullSymbolID] = info; + } + }; + + TypeArgumentInferenceContext.prototype.getInferenceInfo = function (param) { + return this.candidateCache[param.pullSymbolID]; + }; + + TypeArgumentInferenceContext.prototype.addCandidateForInference = function (param, candidate) { + var info = this.getInferenceInfo(param); + + if (info && candidate && info.inferenceCandidates.indexOf(candidate) < 0) { + info.addCandidate(candidate); + } + }; + + TypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + throw TypeScript.Errors.abstract(); + }; + + TypeArgumentInferenceContext.prototype.fixTypeParameter = function (typeParameter) { + var candidateInfo = this.candidateCache[typeParameter.pullSymbolID]; + if (candidateInfo) { + candidateInfo.fixTypeParameter(this.resolver, this.context); + } + }; + + TypeArgumentInferenceContext.prototype._finalizeInferredTypeArguments = function () { + var results = []; + var typeParameters = this.signatureBeingInferred.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + var info = this.candidateCache[typeParameters[i].pullSymbolID]; + + info.fixTypeParameter(this.resolver, this.context); + + for (var i = 0; i < results.length; i++) { + if (results[i].type === info.typeParameter) { + results[i].type = info._inferredTypeAfterFixing; + } + } + + results.push(info._inferredTypeAfterFixing); + } + + return results; + }; + + TypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + throw TypeScript.Errors.abstract(); + }; + return TypeArgumentInferenceContext; + })(); + TypeScript.TypeArgumentInferenceContext = TypeArgumentInferenceContext; + + var InvocationTypeArgumentInferenceContext = (function (_super) { + __extends(InvocationTypeArgumentInferenceContext, _super); + function InvocationTypeArgumentInferenceContext(resolver, context, signatureBeingInferred, argumentASTs) { + _super.call(this, resolver, context, signatureBeingInferred); + this.argumentASTs = argumentASTs; + } + InvocationTypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + return true; + }; + + InvocationTypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + var _this = this; + this.signatureBeingInferred.forAllParameterTypes(this.argumentASTs.nonSeparatorCount(), function (parameterType, argumentIndex) { + var argumentAST = _this.argumentASTs.nonSeparatorAt(argumentIndex); + + _this.context.pushInferentialType(parameterType, _this); + var argumentType = _this.resolver.resolveAST(argumentAST, true, _this.context).type; + _this.resolver.relateTypeToTypeParametersWithNewEnclosingTypes(argumentType, parameterType, _this, _this.context); + _this.context.popAnyContextualType(); + + return true; + }); + + return this._finalizeInferredTypeArguments(); + }; + return InvocationTypeArgumentInferenceContext; + })(TypeArgumentInferenceContext); + TypeScript.InvocationTypeArgumentInferenceContext = InvocationTypeArgumentInferenceContext; + + var ContextualSignatureInstantiationTypeArgumentInferenceContext = (function (_super) { + __extends(ContextualSignatureInstantiationTypeArgumentInferenceContext, _super); + function ContextualSignatureInstantiationTypeArgumentInferenceContext(resolver, context, signatureBeingInferred, contextualSignature, shouldFixContextualSignatureParameterTypes) { + _super.call(this, resolver, context, signatureBeingInferred); + this.contextualSignature = contextualSignature; + this.shouldFixContextualSignatureParameterTypes = shouldFixContextualSignatureParameterTypes; + } + ContextualSignatureInstantiationTypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + return false; + }; + + ContextualSignatureInstantiationTypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + var _this = this; + var relateTypesCallback = function (parameterTypeBeingInferred, contextualParameterType) { + if (_this.shouldFixContextualSignatureParameterTypes) { + contextualParameterType = _this.context.fixAllTypeParametersReferencedByType(contextualParameterType, _this.resolver, _this); + } + _this.resolver.relateTypeToTypeParametersWithNewEnclosingTypes(contextualParameterType, parameterTypeBeingInferred, _this, _this.context); + + return true; + }; + + this.signatureBeingInferred.forAllCorrespondingParameterTypesInThisAndOtherSignature(this.contextualSignature, relateTypesCallback); + + return this._finalizeInferredTypeArguments(); + }; + return ContextualSignatureInstantiationTypeArgumentInferenceContext; + })(TypeArgumentInferenceContext); + TypeScript.ContextualSignatureInstantiationTypeArgumentInferenceContext = ContextualSignatureInstantiationTypeArgumentInferenceContext; + + var PullContextualTypeContext = (function () { + function PullContextualTypeContext(contextualType, provisional, isInferentiallyTyping, typeArgumentInferenceContext) { + this.contextualType = contextualType; + this.provisional = provisional; + this.isInferentiallyTyping = isInferentiallyTyping; + this.typeArgumentInferenceContext = typeArgumentInferenceContext; + this.provisionallyTypedSymbols = []; + this.hasProvisionalErrors = false; + this.astSymbolMap = []; + } + PullContextualTypeContext.prototype.recordProvisionallyTypedSymbol = function (symbol) { + this.provisionallyTypedSymbols[this.provisionallyTypedSymbols.length] = symbol; + }; + + PullContextualTypeContext.prototype.invalidateProvisionallyTypedSymbols = function () { + for (var i = 0; i < this.provisionallyTypedSymbols.length; i++) { + this.provisionallyTypedSymbols[i].setUnresolved(); + } + }; + + PullContextualTypeContext.prototype.setSymbolForAST = function (ast, symbol) { + this.astSymbolMap[ast.syntaxID()] = symbol; + }; + + PullContextualTypeContext.prototype.getSymbolForAST = function (ast) { + return this.astSymbolMap[ast.syntaxID()]; + }; + return PullContextualTypeContext; + })(); + TypeScript.PullContextualTypeContext = PullContextualTypeContext; + + var PullTypeResolutionContext = (function () { + function PullTypeResolutionContext(resolver, inTypeCheck, fileName) { + if (typeof inTypeCheck === "undefined") { inTypeCheck = false; } + if (typeof fileName === "undefined") { fileName = null; } + this.resolver = resolver; + this.inTypeCheck = inTypeCheck; + this.fileName = fileName; + this.contextStack = []; + this.typeCheckedNodes = null; + this.enclosingTypeWalker1 = null; + this.enclosingTypeWalker2 = null; + this.inBaseTypeResolution = false; + if (inTypeCheck) { + TypeScript.Debug.assert(fileName, "A file name must be provided if you are typechecking"); + this.typeCheckedNodes = TypeScript.BitVector.getBitVector(false); + } + } + PullTypeResolutionContext.prototype.setTypeChecked = function (ast) { + if (!this.inProvisionalResolution()) { + this.typeCheckedNodes.setValueAt(ast.syntaxID(), true); + } + }; + + PullTypeResolutionContext.prototype.canTypeCheckAST = function (ast) { + return this.typeCheck() && !this.typeCheckedNodes.valueAt(ast.syntaxID()) && this.fileName === ast.fileName(); + }; + + PullTypeResolutionContext.prototype._pushAnyContextualType = function (type, provisional, isInferentiallyTyping, argContext) { + this.contextStack.push(new PullContextualTypeContext(type, provisional, isInferentiallyTyping, argContext)); + }; + + PullTypeResolutionContext.prototype.pushNewContextualType = function (type) { + this._pushAnyContextualType(type, this.inProvisionalResolution(), false, null); + }; + + PullTypeResolutionContext.prototype.propagateContextualType = function (type) { + this._pushAnyContextualType(type, this.inProvisionalResolution(), this.isInferentiallyTyping(), this.getCurrentTypeArgumentInferenceContext()); + }; + + PullTypeResolutionContext.prototype.pushInferentialType = function (type, typeArgumentInferenceContext) { + this._pushAnyContextualType(type, true, true, typeArgumentInferenceContext); + }; + + PullTypeResolutionContext.prototype.pushProvisionalType = function (type) { + this._pushAnyContextualType(type, true, false, null); + }; + + PullTypeResolutionContext.prototype.popAnyContextualType = function () { + var tc = this.contextStack.pop(); + + tc.invalidateProvisionallyTypedSymbols(); + + if (tc.hasProvisionalErrors && this.inProvisionalResolution()) { + this.contextStack[this.contextStack.length - 1].hasProvisionalErrors = true; + } + + return tc; + }; + + PullTypeResolutionContext.prototype.hasProvisionalErrors = function () { + return this.contextStack.length ? this.contextStack[this.contextStack.length - 1].hasProvisionalErrors : false; + }; + + PullTypeResolutionContext.prototype.getContextualType = function () { + var context = !this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]; + + if (context) { + var type = context.contextualType; + + if (!type) { + return null; + } + + return type; + } + + return null; + }; + + PullTypeResolutionContext.prototype.fixAllTypeParametersReferencedByType = function (type, resolver, argContext) { + var argContext = this.getCurrentTypeArgumentInferenceContext(); + if (type.wrapsSomeTypeParameter(argContext.candidateCache)) { + var typeParameterArgumentMap = []; + + for (var n in argContext.candidateCache) { + var typeParameter = argContext.candidateCache[n] && argContext.candidateCache[n].typeParameter; + if (typeParameter) { + var dummyMap = []; + dummyMap[typeParameter.pullSymbolID] = typeParameter; + if (type.wrapsSomeTypeParameter(dummyMap)) { + argContext.fixTypeParameter(typeParameter); + TypeScript.Debug.assert(argContext.candidateCache[n]._inferredTypeAfterFixing); + typeParameterArgumentMap[typeParameter.pullSymbolID] = argContext.candidateCache[n]._inferredTypeAfterFixing; + } + } + } + + return resolver.instantiateType(type, typeParameterArgumentMap); + } + + return type; + }; + + PullTypeResolutionContext.prototype.getCurrentTypeArgumentInferenceContext = function () { + return this.contextStack.length ? this.contextStack[this.contextStack.length - 1].typeArgumentInferenceContext : null; + }; + + PullTypeResolutionContext.prototype.isInferentiallyTyping = function () { + return this.contextStack.length > 0 && this.contextStack[this.contextStack.length - 1].isInferentiallyTyping; + }; + + PullTypeResolutionContext.prototype.inProvisionalResolution = function () { + return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); + }; + + PullTypeResolutionContext.prototype.isInBaseTypeResolution = function () { + return this.inBaseTypeResolution; + }; + + PullTypeResolutionContext.prototype.startBaseTypeResolution = function () { + var wasInBaseTypeResoltion = this.inBaseTypeResolution; + this.inBaseTypeResolution = true; + return wasInBaseTypeResoltion; + }; + + PullTypeResolutionContext.prototype.doneBaseTypeResolution = function (wasInBaseTypeResolution) { + this.inBaseTypeResolution = wasInBaseTypeResolution; + }; + + PullTypeResolutionContext.prototype.setTypeInContext = function (symbol, type) { + if (symbol.type && symbol.type.isError() && !type.isError()) { + return; + } + symbol.type = type; + + if (this.contextStack.length && this.inProvisionalResolution()) { + this.contextStack[this.contextStack.length - 1].recordProvisionallyTypedSymbol(symbol); + } + }; + + PullTypeResolutionContext.prototype.postDiagnostic = function (diagnostic) { + if (diagnostic) { + if (this.inProvisionalResolution()) { + (this.contextStack[this.contextStack.length - 1]).hasProvisionalErrors = true; + } else if (this.inTypeCheck && this.resolver) { + this.resolver.semanticInfoChain.addDiagnostic(diagnostic); + } + } + }; + + PullTypeResolutionContext.prototype.typeCheck = function () { + return this.inTypeCheck && !this.inProvisionalResolution(); + }; + + PullTypeResolutionContext.prototype.setSymbolForAST = function (ast, symbol) { + this.contextStack[this.contextStack.length - 1].setSymbolForAST(ast, symbol); + }; + + PullTypeResolutionContext.prototype.getSymbolForAST = function (ast) { + for (var i = this.contextStack.length - 1; i >= 0; i--) { + var typeContext = this.contextStack[i]; + if (!typeContext.provisional) { + break; + } + + var symbol = typeContext.getSymbolForAST(ast); + if (symbol) { + return symbol; + } + } + + return null; + }; + + PullTypeResolutionContext.prototype.startWalkingTypes = function (symbol1, symbol2) { + if (!this.enclosingTypeWalker1) { + this.enclosingTypeWalker1 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var stateWhenStartedWalkingTypes1 = this.enclosingTypeWalker1.startWalkingType(symbol1); + if (!this.enclosingTypeWalker2) { + this.enclosingTypeWalker2 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var stateWhenStartedWalkingTypes2 = this.enclosingTypeWalker2.startWalkingType(symbol2); + return { + stateWhenStartedWalkingTypes1: stateWhenStartedWalkingTypes1, + stateWhenStartedWalkingTypes2: stateWhenStartedWalkingTypes2 + }; + }; + + PullTypeResolutionContext.prototype.endWalkingTypes = function (statesWhenStartedWalkingTypes) { + this.enclosingTypeWalker1.endWalkingType(statesWhenStartedWalkingTypes.stateWhenStartedWalkingTypes1); + this.enclosingTypeWalker2.endWalkingType(statesWhenStartedWalkingTypes.stateWhenStartedWalkingTypes2); + }; + + PullTypeResolutionContext.prototype.setEnclosingTypeForSymbols = function (symbol1, symbol2) { + if (!this.enclosingTypeWalker1) { + this.enclosingTypeWalker1 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var enclosingTypeWalkerState1 = this.enclosingTypeWalker1.setEnclosingTypeForSymbol(symbol1); + if (!this.enclosingTypeWalker2) { + this.enclosingTypeWalker2 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var enclosingTypeWalkerState2 = this.enclosingTypeWalker2.setEnclosingTypeForSymbol(symbol2); + return { + enclosingTypeWalkerState1: enclosingTypeWalkerState1, + enclosingTypeWalkerState2: enclosingTypeWalkerState2 + }; + }; + + PullTypeResolutionContext.prototype.walkMemberTypes = function (memberName) { + this.enclosingTypeWalker1.walkMemberType(memberName, this.resolver); + this.enclosingTypeWalker2.walkMemberType(memberName, this.resolver); + }; + + PullTypeResolutionContext.prototype.postWalkMemberTypes = function () { + this.enclosingTypeWalker1.postWalkMemberType(); + this.enclosingTypeWalker2.postWalkMemberType(); + }; + + PullTypeResolutionContext.prototype.walkSignatures = function (kind, index, index2) { + this.enclosingTypeWalker1.walkSignature(kind, index); + this.enclosingTypeWalker2.walkSignature(kind, index2 == undefined ? index : index2); + }; + + PullTypeResolutionContext.prototype.postWalkSignatures = function () { + this.enclosingTypeWalker1.postWalkSignature(); + this.enclosingTypeWalker2.postWalkSignature(); + }; + + PullTypeResolutionContext.prototype.walkTypeParameterConstraints = function (index) { + this.enclosingTypeWalker1.walkTypeParameterConstraint(index); + this.enclosingTypeWalker2.walkTypeParameterConstraint(index); + }; + + PullTypeResolutionContext.prototype.postWalkTypeParameterConstraints = function () { + this.enclosingTypeWalker1.postWalkTypeParameterConstraint(); + this.enclosingTypeWalker2.postWalkTypeParameterConstraint(); + }; + + PullTypeResolutionContext.prototype.walkTypeArgument = function (index) { + this.enclosingTypeWalker1.walkTypeArgument(index); + this.enclosingTypeWalker2.walkTypeArgument(index); + }; + + PullTypeResolutionContext.prototype.postWalkTypeArgument = function () { + this.enclosingTypeWalker1.postWalkTypeArgument(); + this.enclosingTypeWalker2.postWalkTypeArgument(); + }; + + PullTypeResolutionContext.prototype.walkReturnTypes = function () { + this.enclosingTypeWalker1.walkReturnType(); + this.enclosingTypeWalker2.walkReturnType(); + }; + + PullTypeResolutionContext.prototype.postWalkReturnTypes = function () { + this.enclosingTypeWalker1.postWalkReturnType(); + this.enclosingTypeWalker2.postWalkReturnType(); + }; + + PullTypeResolutionContext.prototype.walkParameterTypes = function (iParam) { + this.enclosingTypeWalker1.walkParameterType(iParam); + this.enclosingTypeWalker2.walkParameterType(iParam); + }; + + PullTypeResolutionContext.prototype.postWalkParameterTypes = function () { + this.enclosingTypeWalker1.postWalkParameterType(); + this.enclosingTypeWalker2.postWalkParameterType(); + }; + + PullTypeResolutionContext.prototype.getBothKindOfIndexSignatures = function (includeAugmentedType1, includeAugmentedType2) { + var indexSigs1 = this.enclosingTypeWalker1.getBothKindOfIndexSignatures(this.resolver, this, includeAugmentedType1); + var indexSigs2 = this.enclosingTypeWalker2.getBothKindOfIndexSignatures(this.resolver, this, includeAugmentedType2); + return { indexSigs1: indexSigs1, indexSigs2: indexSigs2 }; + }; + + PullTypeResolutionContext.prototype.walkIndexSignatureReturnTypes = function (indexSigs, useStringIndexSignature1, useStringIndexSignature2, onlySignature) { + this.enclosingTypeWalker1.walkIndexSignatureReturnType(indexSigs.indexSigs1, useStringIndexSignature1, onlySignature); + this.enclosingTypeWalker2.walkIndexSignatureReturnType(indexSigs.indexSigs2, useStringIndexSignature2, onlySignature); + }; + + PullTypeResolutionContext.prototype.postWalkIndexSignatureReturnTypes = function (onlySignature) { + this.enclosingTypeWalker1.postWalkIndexSignatureReturnType(onlySignature); + this.enclosingTypeWalker2.postWalkIndexSignatureReturnType(onlySignature); + }; + + PullTypeResolutionContext.prototype.swapEnclosingTypeWalkers = function () { + var tempEnclosingWalker1 = this.enclosingTypeWalker1; + this.enclosingTypeWalker1 = this.enclosingTypeWalker2; + this.enclosingTypeWalker2 = tempEnclosingWalker1; + }; + + PullTypeResolutionContext.prototype.oneOfClassificationsIsInfinitelyExpanding = function () { + var generativeClassification1 = this.enclosingTypeWalker1.getGenerativeClassification(); + if (generativeClassification1 === 3 /* InfinitelyExpanding */) { + return true; + } + var generativeClassification2 = this.enclosingTypeWalker2.getGenerativeClassification(); + if (generativeClassification2 === 3 /* InfinitelyExpanding */) { + return true; + } + + return false; + }; + + PullTypeResolutionContext.prototype.resetEnclosingTypeWalkerStates = function () { + var enclosingTypeWalkerState1 = this.enclosingTypeWalker1 ? this.enclosingTypeWalker1.resetEnclosingTypeWalkerState() : null; + var enclosingTypeWalkerState2 = this.enclosingTypeWalker2 ? this.enclosingTypeWalker2.resetEnclosingTypeWalkerState() : null; + return { + enclosingTypeWalkerState1: enclosingTypeWalkerState1, + enclosingTypeWalkerState2: enclosingTypeWalkerState2 + }; + }; + + PullTypeResolutionContext.prototype.setEnclosingTypeWalkerStates = function (enclosingTypeWalkerStates) { + TypeScript.Debug.assert(this.enclosingTypeWalker1 || !enclosingTypeWalkerStates.enclosingTypeWalkerState1); + if (this.enclosingTypeWalker1) { + this.enclosingTypeWalker1.setEnclosingTypeWalkerState(enclosingTypeWalkerStates.enclosingTypeWalkerState1); + } + TypeScript.Debug.assert(this.enclosingTypeWalker2 || !enclosingTypeWalkerStates.enclosingTypeWalkerState2); + if (this.enclosingTypeWalker2) { + this.enclosingTypeWalker2.setEnclosingTypeWalkerState(enclosingTypeWalkerStates.enclosingTypeWalkerState2); + } + }; + return PullTypeResolutionContext; + })(); + TypeScript.PullTypeResolutionContext = PullTypeResolutionContext; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var OverloadApplicabilityStatus; + (function (OverloadApplicabilityStatus) { + OverloadApplicabilityStatus[OverloadApplicabilityStatus["NotAssignable"] = 0] = "NotAssignable"; + OverloadApplicabilityStatus[OverloadApplicabilityStatus["AssignableButWithProvisionalErrors"] = 1] = "AssignableButWithProvisionalErrors"; + OverloadApplicabilityStatus[OverloadApplicabilityStatus["AssignableWithNoProvisionalErrors"] = 2] = "AssignableWithNoProvisionalErrors"; + OverloadApplicabilityStatus[OverloadApplicabilityStatus["Subtype"] = 3] = "Subtype"; + })(OverloadApplicabilityStatus || (OverloadApplicabilityStatus = {})); + + var PullAdditionalCallResolutionData = (function () { + function PullAdditionalCallResolutionData() { + this.targetSymbol = null; + this.resolvedSignatures = null; + this.candidateSignature = null; + this.actualParametersContextTypeSymbols = null; + this.diagnosticsFromOverloadResolution = []; + } + return PullAdditionalCallResolutionData; + })(); + TypeScript.PullAdditionalCallResolutionData = PullAdditionalCallResolutionData; + + var PullAdditionalObjectLiteralResolutionData = (function () { + function PullAdditionalObjectLiteralResolutionData() { + this.membersContextTypeSymbols = null; + } + return PullAdditionalObjectLiteralResolutionData; + })(); + TypeScript.PullAdditionalObjectLiteralResolutionData = PullAdditionalObjectLiteralResolutionData; + + var MemberWithBaseOrigin = (function () { + function MemberWithBaseOrigin(memberSymbol, baseOrigin) { + this.memberSymbol = memberSymbol; + this.baseOrigin = baseOrigin; + } + return MemberWithBaseOrigin; + })(); + + var SignatureWithBaseOrigin = (function () { + function SignatureWithBaseOrigin(signature, baseOrigin) { + this.signature = signature; + this.baseOrigin = baseOrigin; + } + return SignatureWithBaseOrigin; + })(); + + var InheritedIndexSignatureInfo = (function () { + function InheritedIndexSignatureInfo() { + } + return InheritedIndexSignatureInfo; + })(); + + var CompilerReservedName; + (function (CompilerReservedName) { + CompilerReservedName[CompilerReservedName["_this"] = 1] = "_this"; + CompilerReservedName[CompilerReservedName["_super"] = 2] = "_super"; + CompilerReservedName[CompilerReservedName["arguments"] = 3] = "arguments"; + CompilerReservedName[CompilerReservedName["_i"] = 4] = "_i"; + CompilerReservedName[CompilerReservedName["require"] = 5] = "require"; + CompilerReservedName[CompilerReservedName["exports"] = 6] = "exports"; + })(CompilerReservedName || (CompilerReservedName = {})); + + function getCompilerReservedName(name) { + var nameText = name.valueText(); + return CompilerReservedName[nameText]; + } + + var PullTypeResolver = (function () { + function PullTypeResolver(compilationSettings, semanticInfoChain) { + this.compilationSettings = compilationSettings; + this.semanticInfoChain = semanticInfoChain; + this._cachedArrayInterfaceType = null; + this._cachedNumberInterfaceType = null; + this._cachedStringInterfaceType = null; + this._cachedBooleanInterfaceType = null; + this._cachedObjectInterfaceType = null; + this._cachedFunctionInterfaceType = null; + this._cachedIArgumentsInterfaceType = null; + this._cachedRegExpInterfaceType = null; + this._cachedAnyTypeArgs = null; + this.typeCheckCallBacks = []; + this.postTypeCheckWorkitems = []; + this._cachedFunctionArgumentsSymbol = null; + this.assignableCache = TypeScript.BitMatrix.getBitMatrix(true); + this.subtypeCache = TypeScript.BitMatrix.getBitMatrix(true); + this.identicalCache = TypeScript.BitMatrix.getBitMatrix(true); + this.inResolvingOtherDeclsWalker = new TypeScript.PullHelpers.OtherPullDeclsWalker(); + } + PullTypeResolver.prototype.cachedArrayInterfaceType = function () { + if (!this._cachedArrayInterfaceType) { + this._cachedArrayInterfaceType = this.getSymbolFromDeclPath("Array", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (!this._cachedArrayInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedArrayInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedArrayInterfaceType; + }; + + PullTypeResolver.prototype.getArrayNamedType = function () { + return this.cachedArrayInterfaceType(); + }; + + PullTypeResolver.prototype.cachedNumberInterfaceType = function () { + if (!this._cachedNumberInterfaceType) { + this._cachedNumberInterfaceType = this.getSymbolFromDeclPath("Number", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedNumberInterfaceType && !this._cachedNumberInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedNumberInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedNumberInterfaceType; + }; + + PullTypeResolver.prototype.cachedStringInterfaceType = function () { + if (!this._cachedStringInterfaceType) { + this._cachedStringInterfaceType = this.getSymbolFromDeclPath("String", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedStringInterfaceType && !this._cachedStringInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedStringInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedStringInterfaceType; + }; + + PullTypeResolver.prototype.cachedBooleanInterfaceType = function () { + if (!this._cachedBooleanInterfaceType) { + this._cachedBooleanInterfaceType = this.getSymbolFromDeclPath("Boolean", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedBooleanInterfaceType && !this._cachedBooleanInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedBooleanInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedBooleanInterfaceType; + }; + + PullTypeResolver.prototype.cachedObjectInterfaceType = function () { + if (!this._cachedObjectInterfaceType) { + this._cachedObjectInterfaceType = this.getSymbolFromDeclPath("Object", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (!this._cachedObjectInterfaceType) { + this._cachedObjectInterfaceType = this.semanticInfoChain.anyTypeSymbol; + } + + if (!this._cachedObjectInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedObjectInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedObjectInterfaceType; + }; + + PullTypeResolver.prototype.cachedFunctionInterfaceType = function () { + if (!this._cachedFunctionInterfaceType) { + this._cachedFunctionInterfaceType = this.getSymbolFromDeclPath("Function", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedFunctionInterfaceType && !this._cachedFunctionInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedFunctionInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedFunctionInterfaceType; + }; + + PullTypeResolver.prototype.cachedIArgumentsInterfaceType = function () { + if (!this._cachedIArgumentsInterfaceType) { + this._cachedIArgumentsInterfaceType = this.getSymbolFromDeclPath("IArguments", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedIArgumentsInterfaceType && !this._cachedIArgumentsInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedIArgumentsInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedIArgumentsInterfaceType; + }; + + PullTypeResolver.prototype.cachedRegExpInterfaceType = function () { + if (!this._cachedRegExpInterfaceType) { + this._cachedRegExpInterfaceType = this.getSymbolFromDeclPath("RegExp", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedRegExpInterfaceType && !this._cachedRegExpInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedRegExpInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedRegExpInterfaceType; + }; + + PullTypeResolver.prototype.cachedFunctionArgumentsSymbol = function () { + if (!this._cachedFunctionArgumentsSymbol) { + this._cachedFunctionArgumentsSymbol = new TypeScript.PullSymbol("arguments", 512 /* Variable */); + this._cachedFunctionArgumentsSymbol.type = this.cachedIArgumentsInterfaceType() || this.semanticInfoChain.anyTypeSymbol; + this._cachedFunctionArgumentsSymbol.setResolved(); + + var functionArgumentsDecl = new TypeScript.PullSynthesizedDecl("arguments", "arguments", 2048 /* Parameter */, 0 /* None */, null, this.semanticInfoChain); + functionArgumentsDecl.setSymbol(this._cachedFunctionArgumentsSymbol); + this._cachedFunctionArgumentsSymbol.addDeclaration(functionArgumentsDecl); + } + + return this._cachedFunctionArgumentsSymbol; + }; + + PullTypeResolver.prototype.getApparentType = function (type) { + if (type.isTypeParameter()) { + var baseConstraint = type.getBaseConstraint(this.semanticInfoChain); + if (baseConstraint === this.semanticInfoChain.anyTypeSymbol) { + return this.semanticInfoChain.emptyTypeSymbol; + } else { + type = baseConstraint; + } + } + if (type.isPrimitive()) { + if (type === this.semanticInfoChain.numberTypeSymbol) { + return this.cachedNumberInterfaceType(); + } + if (type === this.semanticInfoChain.booleanTypeSymbol) { + return this.cachedBooleanInterfaceType(); + } + if (type === this.semanticInfoChain.stringTypeSymbol) { + return this.cachedStringInterfaceType(); + } + return type; + } + if (type.isEnum()) { + return this.cachedNumberInterfaceType(); + } + return type; + }; + + PullTypeResolver.prototype.setTypeChecked = function (ast, context) { + context.setTypeChecked(ast); + }; + + PullTypeResolver.prototype.canTypeCheckAST = function (ast, context) { + return context.canTypeCheckAST(ast); + }; + + PullTypeResolver.prototype.setSymbolForAST = function (ast, symbol, context) { + if (context && context.inProvisionalResolution()) { + context.setSymbolForAST(ast, symbol); + } else { + this.semanticInfoChain.setSymbolForAST(ast, symbol); + } + }; + + PullTypeResolver.prototype.getSymbolForAST = function (ast, context) { + var symbol = this.semanticInfoChain.getSymbolForAST(ast); + + if (!symbol) { + if (context && context.inProvisionalResolution()) { + symbol = context.getSymbolForAST(ast); + } + } + + return symbol; + }; + + PullTypeResolver.prototype.getASTForDecl = function (decl) { + return this.semanticInfoChain.getASTForDecl(decl); + }; + + PullTypeResolver.prototype.getNewErrorTypeSymbol = function (name) { + if (typeof name === "undefined") { name = null; } + return new TypeScript.PullErrorTypeSymbol(this.semanticInfoChain.anyTypeSymbol, name); + }; + + PullTypeResolver.prototype.getEnclosingDecl = function (decl) { + var declPath = decl.getParentPath(); + + if (declPath.length > 1 && declPath[declPath.length - 1] === decl) { + return declPath[declPath.length - 2]; + } else { + return declPath[declPath.length - 1]; + } + }; + + PullTypeResolver.prototype.getExportedMemberSymbol = function (symbol, parent) { + if (!(symbol.kind & (65536 /* Method */ | 4096 /* Property */))) { + var isContainer = (parent.kind & (4 /* Container */ | 32 /* DynamicModule */)) !== 0; + var containerType = !isContainer ? parent.getAssociatedContainerType() : parent; + + if (isContainer && containerType) { + if (symbol.anyDeclHasFlag(1 /* Exported */)) { + return symbol; + } + + return null; + } + } + + return symbol; + }; + + PullTypeResolver.prototype._getNamedPropertySymbolOfAugmentedType = function (symbolName, parent) { + var memberSymbol = this.getNamedPropertySymbol(symbolName, 68147712 /* SomeValue */, parent); + if (memberSymbol) { + return memberSymbol; + } + + if (this.cachedFunctionInterfaceType() && parent.isFunctionType()) { + memberSymbol = this.cachedFunctionInterfaceType().findMember(symbolName, true); + if (memberSymbol) { + return memberSymbol; + } + } + + if (this.cachedObjectInterfaceType()) { + return this.cachedObjectInterfaceType().findMember(symbolName, true); + } + + return null; + }; + + PullTypeResolver.prototype.getNamedPropertySymbol = function (symbolName, declSearchKind, parent) { + var member = null; + + if (declSearchKind & 68147712 /* SomeValue */) { + member = parent.findMember(symbolName, true); + } else if (declSearchKind & 58728795 /* SomeType */) { + member = parent.findNestedType(symbolName); + } else if (declSearchKind & 164 /* SomeContainer */) { + member = parent.findNestedContainer(symbolName); + } + + if (member) { + return this.getExportedMemberSymbol(member, parent); + } + + var containerType = parent.getAssociatedContainerType(); + + if (containerType) { + if (containerType.isClass()) { + return null; + } + + parent = containerType; + + if (declSearchKind & 68147712 /* SomeValue */) { + member = parent.findMember(symbolName, true); + } else if (declSearchKind & 58728795 /* SomeType */) { + member = parent.findNestedType(symbolName); + } else if (declSearchKind & 164 /* SomeContainer */) { + member = parent.findNestedContainer(symbolName); + } + + if (member) { + return this.getExportedMemberSymbol(member, parent); + } + } + + if (parent.kind & 164 /* SomeContainer */) { + var typeDeclarations = parent.getDeclarations(); + var childDecls = null; + + for (var j = 0; j < typeDeclarations.length; j++) { + childDecls = typeDeclarations[j].searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + member = childDecls[0].getSymbol(); + + if (!member) { + member = childDecls[0].getSignatureSymbol(); + } + return this.getExportedMemberSymbol(member, parent); + } + + if ((declSearchKind & 58728795 /* SomeType */) !== 0 || (declSearchKind & 68147712 /* SomeValue */) !== 0) { + childDecls = typeDeclarations[j].searchChildDecls(symbolName, 128 /* TypeAlias */); + if (childDecls.length && childDecls[0].kind === 128 /* TypeAlias */) { + var aliasSymbol = this.getExportedMemberSymbol(childDecls[0].getSymbol(), parent); + if (aliasSymbol) { + if ((declSearchKind & 58728795 /* SomeType */) !== 0) { + var typeSymbol = aliasSymbol.getExportAssignedTypeSymbol(); + if (typeSymbol) { + return typeSymbol; + } + } else { + var valueSymbol = aliasSymbol.getExportAssignedValueSymbol(); + if (valueSymbol) { + aliasSymbol.setIsUsedAsValue(); + return valueSymbol; + } + } + + return aliasSymbol; + } + } + } + } + } + }; + + PullTypeResolver.prototype.getSymbolFromDeclPath = function (symbolName, declPath, declSearchKind) { + var _this = this; + var symbol = null; + + var decl = null; + var childDecls; + var declSymbol = null; + var declMembers; + var pathDeclKind; + var valDecl = null; + var kind; + var instanceSymbol = null; + var instanceType = null; + var childSymbol = null; + + var allowedContainerDeclKind = 4 /* Container */ | 32 /* DynamicModule */; + if (TypeScript.hasFlag(declSearchKind, 67108864 /* EnumMember */)) { + allowedContainerDeclKind |= 64 /* Enum */; + } + + var isAcceptableAlias = function (symbol) { + if (symbol.isAlias()) { + _this.resolveDeclaredSymbol(symbol); + if (TypeScript.hasFlag(declSearchKind, 164 /* SomeContainer */)) { + if (symbol.assignedContainer() || symbol.getExportAssignedContainerSymbol()) { + return true; + } + } else if (TypeScript.hasFlag(declSearchKind, 58728795 /* SomeType */)) { + var type = symbol.getExportAssignedTypeSymbol(); + if (type && type.kind !== 32 /* DynamicModule */) { + return true; + } + + var type = symbol.assignedType(); + if (type && type.kind !== 32 /* DynamicModule */) { + return true; + } + } else if (TypeScript.hasFlag(declSearchKind, 68147712 /* SomeValue */ & ~67108864 /* EnumMember */)) { + if (symbol.assignedType() && symbol.assignedType().isError()) { + return true; + } else if (symbol.assignedValue() || symbol.getExportAssignedValueSymbol()) { + return true; + } else { + var assignedType = symbol.assignedType(); + if (assignedType && assignedType.isContainer() && assignedType.getInstanceType()) { + return true; + } + + var decls = symbol.getDeclarations(); + var ast = decls[0].ast(); + return ast.moduleReference.kind() === 245 /* ExternalModuleReference */; + } + } + } + + return false; + }; + + var tryFindAlias = function (decl) { + var childDecls = decl.searchChildDecls(symbolName, 128 /* TypeAlias */); + + if (childDecls.length) { + var sym = childDecls[0].getSymbol(); + if (isAcceptableAlias(sym)) { + return sym; + } + } + return null; + }; + + for (var i = declPath.length - 1; i >= 0; i--) { + decl = declPath[i]; + pathDeclKind = decl.kind; + + if (decl.flags & 2097152 /* DeclaredInAWithBlock */) { + return this.semanticInfoChain.anyTypeSymbol; + } + + if (pathDeclKind & allowedContainerDeclKind) { + childDecls = decl.searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + return childDecls[0].getSymbol(); + } + + var alias = tryFindAlias(decl); + if (alias) { + return alias; + } + + if (declSearchKind & 68147712 /* SomeValue */) { + instanceSymbol = decl.getSymbol().getInstanceSymbol(); + + if (instanceSymbol) { + instanceType = instanceSymbol.type; + + childSymbol = this.getNamedPropertySymbol(symbolName, declSearchKind, instanceType); + + if (childSymbol && (childSymbol.kind & declSearchKind) && !childSymbol.anyDeclHasFlag(16 /* Static */)) { + return childSymbol; + } + } + + valDecl = decl.getValueDecl(); + + if (valDecl) { + decl = valDecl; + } + } + + declSymbol = decl.getSymbol().type; + + var childSymbol = this.getNamedPropertySymbol(symbolName, declSearchKind, declSymbol); + + if (childSymbol && (childSymbol.kind & declSearchKind) && !childSymbol.anyDeclHasFlag(16 /* Static */)) { + return childSymbol; + } + } else if ((declSearchKind & (58728795 /* SomeType */ | 164 /* SomeContainer */)) || !(pathDeclKind & 8 /* Class */)) { + var candidateSymbol = null; + + if (pathDeclKind === 131072 /* FunctionExpression */ && symbolName === decl.getFunctionExpressionName()) { + candidateSymbol = decl.getSymbol(); + } + + childDecls = decl.searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + if (decl.kind & 1032192 /* SomeFunction */) { + decl.ensureSymbolIsBound(); + } + return childDecls[0].getSymbol(); + } + + if (candidateSymbol) { + return candidateSymbol; + } + + var alias = tryFindAlias(decl); + if (alias) { + return alias; + } + } + } + + symbol = this.semanticInfoChain.findSymbol([symbolName], declSearchKind); + if (symbol) { + return symbol; + } + + if (!TypeScript.hasFlag(declSearchKind, 128 /* TypeAlias */)) { + symbol = this.semanticInfoChain.findSymbol([symbolName], 128 /* TypeAlias */); + if (symbol && isAcceptableAlias(symbol)) { + return symbol; + } + } + + return null; + }; + + PullTypeResolver.prototype.getVisibleDeclsFromDeclPath = function (declPath, declSearchKind) { + var result = []; + var decl = null; + var childDecls; + var pathDeclKind; + + for (var i = declPath.length - 1; i >= 0; i--) { + decl = declPath[i]; + pathDeclKind = decl.kind; + + var declKind = decl.kind; + + if (declKind !== 8 /* Class */ && declKind !== 16 /* Interface */) { + this.addFilteredDecls(decl.getChildDecls(), declSearchKind, result); + } + + switch (declKind) { + case 4 /* Container */: + case 32 /* DynamicModule */: + var otherDecls = this.semanticInfoChain.findDeclsFromPath(declPath.slice(0, i + 1), 164 /* SomeContainer */); + for (var j = 0, m = otherDecls.length; j < m; j++) { + var otherDecl = otherDecls[j]; + if (otherDecl === decl) { + continue; + } + + var otherDeclChildren = otherDecl.getChildDecls(); + for (var k = 0, s = otherDeclChildren.length; k < s; k++) { + var otherDeclChild = otherDeclChildren[k]; + if ((otherDeclChild.flags & 1 /* Exported */) && (otherDeclChild.kind & declSearchKind)) { + result.push(otherDeclChild); + } + } + } + + break; + + case 8 /* Class */: + case 16 /* Interface */: + var parameters = decl.getTypeParameters(); + if (parameters && parameters.length) { + this.addFilteredDecls(parameters, declSearchKind, result); + } + + break; + + case 131072 /* FunctionExpression */: + var functionExpressionName = decl.getFunctionExpressionName(); + if (functionExpressionName) { + result.push(decl); + } + + case 16384 /* Function */: + case 32768 /* ConstructorMethod */: + case 65536 /* Method */: + var parameters = decl.getTypeParameters(); + if (parameters && parameters.length) { + this.addFilteredDecls(parameters, declSearchKind, result); + } + + break; + } + } + + var topLevelDecls = this.semanticInfoChain.topLevelDecls(); + for (var i = 0, n = topLevelDecls.length; i < n; i++) { + var topLevelDecl = topLevelDecls[i]; + if (declPath.length > 0 && topLevelDecl.fileName() === declPath[0].fileName()) { + continue; + } + + if (!topLevelDecl.isExternalModule()) { + this.addFilteredDecls(topLevelDecl.getChildDecls(), declSearchKind, result); + } + } + + return result; + }; + + PullTypeResolver.prototype.addFilteredDecls = function (decls, declSearchKind, result) { + if (decls.length) { + for (var i = 0, n = decls.length; i < n; i++) { + var decl = decls[i]; + if (decl.kind & declSearchKind) { + result.push(decl); + } + } + } + }; + + PullTypeResolver.prototype.getVisibleDecls = function (enclosingDecl) { + var declPath = enclosingDecl.getParentPath(); + + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + + return this.getVisibleDeclsFromDeclPath(declPath, declSearchKind); + }; + + PullTypeResolver.prototype.getVisibleContextSymbols = function (enclosingDecl, context) { + var contextualTypeSymbol = context.getContextualType(); + if (!contextualTypeSymbol || this.isAnyOrEquivalent(contextualTypeSymbol)) { + return null; + } + + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + var members = contextualTypeSymbol.getAllMembers(declSearchKind, 2 /* externallyVisible */); + + for (var i = 0; i < members.length; i++) { + members[i].setUnresolved(); + } + + return members; + }; + + PullTypeResolver.prototype.getVisibleMembersFromExpression = function (expression, enclosingDecl, context) { + var lhs = this.resolveAST(expression, false, context); + + if (isTypesOnlyLocation(expression) && (lhs.kind === 8 /* Class */ || lhs.kind === 16 /* Interface */ || lhs.kind === 64 /* Enum */)) { + return null; + } + + var lhsType = lhs.type; + if (!lhsType) { + return null; + } + + this.resolveDeclaredSymbol(lhsType, context); + + if (lhsType.isContainer() && lhsType.isAlias()) { + lhsType = lhsType.getExportAssignedTypeSymbol(); + } + + if (this.isAnyOrEquivalent(lhsType)) { + return null; + } + + var memberVisibilty = 2 /* externallyVisible */; + var containerSymbol = lhsType; + if (containerSymbol.kind === 33554432 /* ConstructorType */) { + containerSymbol = containerSymbol.getConstructSignatures()[0].returnType; + } + + if (containerSymbol && containerSymbol.isClass()) { + var declPath = enclosingDecl.getParentPath(); + if (declPath && declPath.length) { + var declarations = containerSymbol.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + var declaration = declarations[i]; + if (TypeScript.ArrayUtilities.contains(declPath, declaration)) { + memberVisibilty = 1 /* internallyVisible */; + break; + } + } + } + } + + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + + var members = []; + + if (lhsType.isContainer()) { + var exportedAssignedContainerSymbol = lhsType.getExportAssignedContainerSymbol(); + if (exportedAssignedContainerSymbol) { + lhsType = exportedAssignedContainerSymbol; + } + } + + lhsType = this.getApparentType(lhsType); + + if (!lhsType.isResolved) { + var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, context); + + if (potentiallySpecializedType !== lhsType) { + if (!lhs.isType()) { + context.setTypeInContext(lhs, potentiallySpecializedType); + } + + lhsType = potentiallySpecializedType; + } + } + + members = lhsType.getAllMembers(declSearchKind, memberVisibilty); + + if (lhsType.isContainer()) { + var associatedInstance = lhsType.getInstanceSymbol(); + if (associatedInstance) { + var instanceType = associatedInstance.type; + this.resolveDeclaredSymbol(instanceType, context); + var instanceMembers = instanceType.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(instanceMembers); + } + + var exportedContainer = lhsType.getExportAssignedContainerSymbol(); + if (exportedContainer) { + var exportedContainerMembers = exportedContainer.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(exportedContainerMembers); + } + } else if (!lhsType.isConstructor() && !lhsType.isEnum()) { + var associatedContainerSymbol = lhsType.getAssociatedContainerType(); + if (associatedContainerSymbol) { + var containerType = associatedContainerSymbol.type; + this.resolveDeclaredSymbol(containerType, context); + var containerMembers = containerType.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(containerMembers); + } + } + + if (lhsType.isFunctionType() && this.cachedFunctionInterfaceType()) { + members = members.concat(this.cachedFunctionInterfaceType().getAllMembers(declSearchKind, 2 /* externallyVisible */)); + } + + return members; + }; + + PullTypeResolver.prototype.isAnyOrEquivalent = function (type) { + return (type === this.semanticInfoChain.anyTypeSymbol) || type.isError(); + }; + + PullTypeResolver.prototype.resolveExternalModuleReference = function (idText, currentFileName) { + var originalIdText = idText; + var symbol = null; + + if (TypeScript.isRelative(originalIdText)) { + var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); + symbol = this.semanticInfoChain.findExternalModule(path + idText); + } else { + idText = originalIdText; + + symbol = this.semanticInfoChain.findAmbientExternalModuleInGlobalContext(TypeScript.quoteStr(originalIdText)); + + if (!symbol) { + var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); + + while (symbol === null && path != "") { + symbol = this.semanticInfoChain.findExternalModule(path + idText); + if (symbol === null) { + if (path === '/') { + path = ''; + } else { + path = TypeScript.normalizePath(path + ".."); + path = path && path != '/' ? path + '/' : path; + } + } + } + } + } + + return symbol; + }; + + PullTypeResolver.prototype.resolveDeclaredSymbol = function (symbol, context) { + if (!symbol || symbol.isResolved || symbol.isTypeReference()) { + return symbol; + } + + if (!context) { + context = new TypeScript.PullTypeResolutionContext(this); + } + + return this.resolveDeclaredSymbolWorker(symbol, context); + }; + + PullTypeResolver.prototype.resolveDeclaredSymbolWorker = function (symbol, context) { + if (!symbol || symbol.isResolved) { + return symbol; + } + + if (symbol.inResolution) { + if (!symbol.type && !symbol.isType()) { + symbol.type = this.semanticInfoChain.anyTypeSymbol; + } + + return symbol; + } + + var decls = symbol.getDeclarations(); + + for (var i = 0; i < decls.length; i++) { + var decl = decls[i]; + + var ast = this.semanticInfoChain.getASTForDecl(decl); + + if (!ast || (ast.kind() === 139 /* GetAccessor */ && ast.parent.parent.kind() === 215 /* ObjectLiteralExpression */) || (ast.kind() === 140 /* SetAccessor */ && ast.parent.parent.kind() === 215 /* ObjectLiteralExpression */)) { + return symbol; + } + + if (ast.parent && ast.parent.kind() === 236 /* CatchClause */ && ast.parent.identifier === ast) { + return symbol; + } + + if (ast.parent && ast.parent.kind() === 219 /* SimpleArrowFunctionExpression */ && ast.parent.identifier === ast) { + return symbol; + } + + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(ast); + var resolvedSymbol; + if (enclosingModule) { + resolvedSymbol = this.resolveSingleModuleDeclaration(enclosingModule, ast, context); + } else if (ast.kind() === 120 /* SourceUnit */ && decl.kind === 32 /* DynamicModule */) { + resolvedSymbol = this.resolveModuleSymbol(decl.getSymbol(), context, null, null, ast); + } else { + TypeScript.Debug.assert(ast.kind() !== 11 /* IdentifierName */ && ast.kind() !== 212 /* MemberAccessExpression */); + resolvedSymbol = this.resolveAST(ast, false, context); + } + + if (decl.kind === 2048 /* Parameter */ && !symbol.isResolved && !symbol.type && resolvedSymbol && symbol.anyDeclHasFlag(8388608 /* PropertyParameter */ | 67108864 /* ConstructorParameter */)) { + symbol.type = resolvedSymbol.type; + symbol.setResolved(); + } + } + + if (!symbol.isResolved) { + TypeScript.Debug.assert(!symbol.inResolution); + + symbol.setResolved(); + } + + return symbol; + }; + + PullTypeResolver.prototype.resolveOtherDecl = function (otherDecl, context) { + var astForOtherDecl = this.getASTForDecl(otherDecl); + var moduleDecl = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(astForOtherDecl); + if (moduleDecl) { + this.resolveSingleModuleDeclaration(moduleDecl, astForOtherDecl, context); + } else { + this.resolveAST(astForOtherDecl, false, context); + } + }; + + PullTypeResolver.prototype.resolveOtherDeclarations = function (astName, context) { + var _this = this; + var resolvedDecl = this.semanticInfoChain.getDeclForAST(astName); + var symbol = resolvedDecl.getSymbol(); + + var allDecls = symbol.getDeclarations(); + this.inResolvingOtherDeclsWalker.walkOtherPullDecls(resolvedDecl, symbol.getDeclarations(), function (otherDecl) { + return _this.resolveOtherDecl(otherDecl, context); + }); + }; + + PullTypeResolver.prototype.resolveSourceUnit = function (sourceUnit, context) { + var enclosingDecl = this.getEnclosingDeclForAST(sourceUnit); + var moduleSymbol = enclosingDecl.getSymbol(); + this.ensureAllSymbolsAreBound(moduleSymbol); + + this.resolveFirstExportAssignmentStatement(sourceUnit.moduleElements, context); + this.resolveAST(sourceUnit.moduleElements, false, context); + + if (this.canTypeCheckAST(sourceUnit, context)) { + this.typeCheckSourceUnit(sourceUnit, context); + } + + return moduleSymbol; + }; + + PullTypeResolver.prototype.typeCheckSourceUnit = function (sourceUnit, context) { + var _this = this; + this.setTypeChecked(sourceUnit, context); + + this.resolveAST(sourceUnit.moduleElements, false, context); + + this.typeCheckCallBacks.push(function (context) { + return _this.verifyUniquenessOfImportNamesInSourceUnit(sourceUnit); + }); + }; + + PullTypeResolver.prototype.verifyUniquenessOfImportNamesInSourceUnit = function (sourceUnit) { + var _this = this; + var enclosingDecl = this.semanticInfoChain.getDeclForAST(sourceUnit); + + var doesImportNameExistInOtherFiles = function (name) { + var importSymbol = _this.semanticInfoChain.findTopLevelSymbol(name, 128 /* TypeAlias */, null); + return importSymbol && importSymbol.isAlias(); + }; + + this.checkUniquenessOfImportNames([enclosingDecl], doesImportNameExistInOtherFiles); + }; + + PullTypeResolver.prototype.resolveEnumDeclaration = function (ast, context) { + var containerDecl = this.semanticInfoChain.getDeclForAST(ast); + var containerSymbol = containerDecl.getSymbol(); + + if (containerSymbol.isResolved || containerSymbol.inResolution) { + return containerSymbol; + } + + containerSymbol.inResolution = true; + + var containerDecls = containerSymbol.getDeclarations(); + + for (var i = 0; i < containerDecls.length; i++) { + var childDecls = containerDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + + containerSymbol.setResolved(); + + this.resolveOtherDeclarations(ast, context); + + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckEnumDeclaration(ast, context); + } + + return containerSymbol; + }; + + PullTypeResolver.prototype.typeCheckEnumDeclaration = function (ast, context) { + var _this = this; + this.setTypeChecked(ast, context); + + this.resolveAST(ast.enumElements, false, context); + var containerDecl = this.semanticInfoChain.getDeclForAST(ast); + this.validateVariableDeclarationGroups(containerDecl, context); + + this.typeCheckCallBacks.push(function (context) { + return _this.checkInitializersInEnumDeclarations(containerDecl, context); + }); + + if (!TypeScript.ASTHelpers.enumIsElided(ast)) { + this.checkNameForCompilerGeneratedDeclarationCollision(ast, true, ast.identifier, context); + } + }; + + PullTypeResolver.prototype.postTypeCheckEnumDeclaration = function (ast, context) { + this.checkThisCaptureVariableCollides(ast, true, context); + }; + + PullTypeResolver.prototype.checkInitializersInEnumDeclarations = function (decl, context) { + var symbol = decl.getSymbol(); + + var declarations = symbol.getDeclarations(); + if (decl !== declarations[0]) { + return; + } + + var seenEnumDeclWithNoFirstMember = false; + for (var i = 0; i < declarations.length; ++i) { + var currentDecl = declarations[i]; + + var ast = currentDecl.ast(); + if (ast.enumElements.nonSeparatorCount() === 0) { + continue; + } + + var firstVariable = ast.enumElements.nonSeparatorAt(0); + if (!firstVariable.equalsValueClause) { + if (!seenEnumDeclWithNoFirstMember) { + seenEnumDeclWithNoFirstMember = true; + } else { + this.semanticInfoChain.addDiagnosticFromAST(firstVariable, TypeScript.DiagnosticCode.In_enums_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_the_first_enum_element); + } + } + } + }; + + PullTypeResolver.prototype.resolveModuleDeclaration = function (ast, context) { + var result; + + if (ast.stringLiteral) { + result = this.resolveSingleModuleDeclaration(ast, ast.stringLiteral, context); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(ast.name); + for (var i = 0, n = moduleNames.length; i < n; i++) { + result = this.resolveSingleModuleDeclaration(ast, moduleNames[i], context); + } + } + + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckModuleDeclaration(ast, context); + } + + return result; + }; + + PullTypeResolver.prototype.ensureAllSymbolsAreBound = function (containerSymbol) { + if (containerSymbol) { + var containerDecls = containerSymbol.getDeclarations(); + + for (var i = 0; i < containerDecls.length; i++) { + var childDecls = containerDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + } + }; + + PullTypeResolver.prototype.resolveModuleSymbol = function (containerSymbol, context, moduleDeclAST, moduleDeclNameAST, sourceUnitAST) { + if (containerSymbol.isResolved || containerSymbol.inResolution) { + return containerSymbol; + } + + containerSymbol.inResolution = true; + this.ensureAllSymbolsAreBound(containerSymbol); + + var instanceSymbol = containerSymbol.getInstanceSymbol(); + + if (instanceSymbol) { + this.resolveDeclaredSymbol(instanceSymbol, context); + } + + var isLastName = TypeScript.ASTHelpers.isLastNameOfModule(moduleDeclAST, moduleDeclNameAST); + if (isLastName) { + this.resolveFirstExportAssignmentStatement(moduleDeclAST.moduleElements, context); + } else if (sourceUnitAST) { + this.resolveFirstExportAssignmentStatement(sourceUnitAST.moduleElements, context); + } + + containerSymbol.setResolved(); + + if (moduleDeclNameAST) { + this.resolveOtherDeclarations(moduleDeclNameAST, context); + } + + return containerSymbol; + }; + + PullTypeResolver.prototype.resolveFirstExportAssignmentStatement = function (moduleElements, context) { + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var moduleElement = moduleElements.childAt(i); + if (moduleElement.kind() === 134 /* ExportAssignment */) { + this.resolveExportAssignmentStatement(moduleElement, context); + return; + } + } + }; + + PullTypeResolver.prototype.resolveSingleModuleDeclaration = function (ast, astName, context) { + var containerDecl = this.semanticInfoChain.getDeclForAST(astName); + var containerSymbol = containerDecl.getSymbol(); + + return this.resolveModuleSymbol(containerSymbol, context, ast, astName, null); + }; + + PullTypeResolver.prototype.typeCheckModuleDeclaration = function (ast, context) { + if (ast.stringLiteral) { + this.typeCheckSingleModuleDeclaration(ast, ast.stringLiteral, context); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(ast.name); + for (var i = 0, n = moduleNames.length; i < n; i++) { + this.typeCheckSingleModuleDeclaration(ast, moduleNames[i], context); + } + } + }; + + PullTypeResolver.prototype.typeCheckSingleModuleDeclaration = function (ast, astName, context) { + var _this = this; + this.setTypeChecked(ast, context); + + if (TypeScript.ASTHelpers.isLastNameOfModule(ast, astName)) { + this.resolveAST(ast.moduleElements, false, context); + } + + var containerDecl = this.semanticInfoChain.getDeclForAST(astName); + this.validateVariableDeclarationGroups(containerDecl, context); + + if (ast.stringLiteral) { + if (TypeScript.isRelative(ast.stringLiteral.valueText())) { + this.semanticInfoChain.addDiagnosticFromAST(ast.stringLiteral, TypeScript.DiagnosticCode.Ambient_external_module_declaration_cannot_specify_relative_module_name); + } + } + + if (!TypeScript.ASTHelpers.moduleIsElided(ast) && !ast.stringLiteral) { + this.checkNameForCompilerGeneratedDeclarationCollision(astName, true, astName, context); + } + + this.typeCheckCallBacks.push(function (context) { + return _this.verifyUniquenessOfImportNamesInModule(containerDecl); + }); + }; + + PullTypeResolver.prototype.verifyUniquenessOfImportNamesInModule = function (decl) { + var symbol = decl.getSymbol(); + if (!symbol) { + return; + } + + var decls = symbol.getDeclarations(); + + if (decls[0] !== decl) { + return; + } + + this.checkUniquenessOfImportNames(decls); + }; + + PullTypeResolver.prototype.checkUniquenessOfImportNames = function (decls, doesNameExistOutside) { + var _this = this; + var importDeclarationNames; + + for (var i = 0; i < decls.length; ++i) { + var childDecls = decls[i].getChildDecls(); + for (var j = 0; j < childDecls.length; ++j) { + var childDecl = childDecls[j]; + if (childDecl.kind === 128 /* TypeAlias */) { + importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); + importDeclarationNames[childDecl.name] = true; + } + } + } + + if (!importDeclarationNames && !doesNameExistOutside) { + return; + } + + for (var i = 0; i < decls.length; ++i) { + this.scanVariableDeclarationGroups(decls[i], function (firstDeclInGroup) { + var nameConflict = importDeclarationNames && importDeclarationNames[firstDeclInGroup.name]; + if (!nameConflict) { + nameConflict = doesNameExistOutside && doesNameExistOutside(firstDeclInGroup.name); + if (nameConflict) { + importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); + importDeclarationNames[firstDeclInGroup.name] = true; + } + } + + if (nameConflict) { + _this.semanticInfoChain.addDiagnosticFromAST(firstDeclInGroup.ast(), TypeScript.DiagnosticCode.Variable_declaration_cannot_have_the_same_name_as_an_import_declaration); + } + }); + } + }; + + PullTypeResolver.prototype.scanVariableDeclarationGroups = function (enclosingDecl, firstDeclHandler, subsequentDeclHandler) { + var declGroups = enclosingDecl.getVariableDeclGroups(); + + for (var i = 0; i < declGroups.length; i++) { + var firstSymbol = null; + var enclosingDeclForFirstSymbol = null; + + if (enclosingDecl.kind === 1 /* Script */ && declGroups[i].length) { + var name = declGroups[i][0].name; + var candidateSymbol = this.semanticInfoChain.findTopLevelSymbol(name, 512 /* Variable */, enclosingDecl); + if (candidateSymbol) { + if (!candidateSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */)) { + if (!candidateSymbol.isResolved) { + this.resolveDeclaredSymbol(candidateSymbol); + } + firstSymbol = candidateSymbol; + } + } + } + + for (var j = 0; j < declGroups[i].length; j++) { + var decl = declGroups[i][j]; + + var name = decl.name; + + var symbol = decl.getSymbol(); + + if (j === 0) { + firstDeclHandler(decl); + if (!subsequentDeclHandler) { + break; + } + + if (!firstSymbol || !firstSymbol.type) { + firstSymbol = symbol; + continue; + } + } + + subsequentDeclHandler(decl, firstSymbol); + } + } + }; + + PullTypeResolver.prototype.postTypeCheckModuleDeclaration = function (ast, context) { + this.checkThisCaptureVariableCollides(ast, true, context); + }; + + PullTypeResolver.prototype.isTypeRefWithoutTypeArgs = function (term) { + if (term.kind() === 11 /* IdentifierName */) { + return true; + } else if (term.kind() === 121 /* QualifiedName */) { + var binex = term; + + if (binex.right.kind() === 11 /* IdentifierName */) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.createInstantiatedType = function (type, typeArguments) { + if (!type.isGeneric()) { + return type; + } + + var typeParameters = type.getTypeArgumentsOrTypeParameters(); + + var typeParameterArgumentMap = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameterArgumentMap[typeParameters[i].pullSymbolID] = typeArguments[i] || new TypeScript.PullErrorTypeSymbol(this.semanticInfoChain.anyTypeSymbol, typeParameters[i].name); + } + + return TypeScript.PullInstantiatedTypeReferenceSymbol.create(this, type, typeParameterArgumentMap); + }; + + PullTypeResolver.prototype.resolveReferenceTypeDeclaration = function (classOrInterface, name, heritageClauses, context) { + var _this = this; + var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var enclosingDecl = this.getEnclosingDecl(typeDecl); + var typeDeclSymbol = typeDecl.getSymbol(); + var typeDeclIsClass = classOrInterface.kind() === 131 /* ClassDeclaration */; + var hasVisited = this.getSymbolForAST(classOrInterface, context) !== null; + + if ((typeDeclSymbol.isResolved && hasVisited) || (typeDeclSymbol.inResolution && !context.isInBaseTypeResolution())) { + return typeDeclSymbol; + } + + var wasResolving = typeDeclSymbol.inResolution; + typeDeclSymbol.startResolving(); + + var typeRefDecls = typeDeclSymbol.getDeclarations(); + + for (var i = 0; i < typeRefDecls.length; i++) { + var childDecls = typeRefDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + + if (!typeDeclSymbol.isResolved) { + var typeDeclTypeParameters = typeDeclSymbol.getTypeParameters(); + for (var i = 0; i < typeDeclTypeParameters.length; i++) { + this.resolveDeclaredSymbol(typeDeclTypeParameters[i], context); + } + } + + var wasInBaseTypeResolution = context.startBaseTypeResolution(); + + if (!typeDeclIsClass && !hasVisited) { + typeDeclSymbol.resetKnownBaseTypeCount(); + } + + var extendsClause = TypeScript.ASTHelpers.getExtendsHeritageClause(heritageClauses); + if (extendsClause) { + for (var i = typeDeclSymbol.getKnownBaseTypeCount(); i < extendsClause.typeNames.nonSeparatorCount(); i = typeDeclSymbol.getKnownBaseTypeCount()) { + typeDeclSymbol.incrementKnownBaseCount(); + var parentType = this.resolveTypeReference(extendsClause.typeNames.nonSeparatorAt(i), context); + + if (typeDeclSymbol.isValidBaseKind(parentType, true)) { + this.setSymbolForAST(extendsClause.typeNames.nonSeparatorAt(i), parentType, null); + + if (!typeDeclSymbol.hasBase(parentType) && !parentType.hasBase(typeDeclSymbol)) { + typeDeclSymbol.addExtendedType(parentType); + + var specializations = typeDeclSymbol.getKnownSpecializations(); + + for (var j = 0; j < specializations.length; j++) { + specializations[j].addExtendedType(parentType); + } + } + } else if (parentType && !this.getSymbolForAST(extendsClause.typeNames.nonSeparatorAt(i), context)) { + this.setSymbolForAST(extendsClause.typeNames.nonSeparatorAt(i), parentType, null); + } + } + } + + var implementsClause = TypeScript.ASTHelpers.getImplementsHeritageClause(heritageClauses); + if (implementsClause && typeDeclIsClass) { + var extendsCount = extendsClause ? extendsClause.typeNames.nonSeparatorCount() : 0; + for (var i = typeDeclSymbol.getKnownBaseTypeCount(); ((i - extendsCount) >= 0) && ((i - extendsCount) < implementsClause.typeNames.nonSeparatorCount()); i = typeDeclSymbol.getKnownBaseTypeCount()) { + typeDeclSymbol.incrementKnownBaseCount(); + var implementedTypeAST = implementsClause.typeNames.nonSeparatorAt(i - extendsCount); + var implementedType = this.resolveTypeReference(implementedTypeAST, context); + + if (typeDeclSymbol.isValidBaseKind(implementedType, false)) { + this.setSymbolForAST(implementsClause.typeNames.nonSeparatorAt(i - extendsCount), implementedType, null); + + if (!typeDeclSymbol.hasBase(implementedType) && !implementedType.hasBase(typeDeclSymbol)) { + typeDeclSymbol.addImplementedType(implementedType); + } + } else if (implementedType && !this.getSymbolForAST(implementsClause.typeNames.nonSeparatorAt(i - extendsCount), context)) { + this.setSymbolForAST(implementsClause.typeNames.nonSeparatorAt(i - extendsCount), implementedType, null); + } + } + } + + context.doneBaseTypeResolution(wasInBaseTypeResolution); + + if (wasInBaseTypeResolution) { + typeDeclSymbol.inResolution = false; + + this.typeCheckCallBacks.push(function (context) { + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + _this.resolveClassDeclaration(classOrInterface, context); + } else { + _this.resolveInterfaceDeclaration(classOrInterface, context); + } + }); + + return typeDeclSymbol; + } + + this.setSymbolForAST(name, typeDeclSymbol, context); + this.setSymbolForAST(classOrInterface, typeDeclSymbol, context); + + typeDeclSymbol.setResolved(); + + return typeDeclSymbol; + }; + + PullTypeResolver.prototype.resolveClassDeclaration = function (classDeclAST, context) { + var classDecl = this.semanticInfoChain.getDeclForAST(classDeclAST); + var classDeclSymbol = classDecl.getSymbol(); + + if (!classDeclSymbol.isResolved) { + this.resolveReferenceTypeDeclaration(classDeclAST, classDeclAST.identifier, classDeclAST.heritageClauses, context); + + var constructorMethod = classDeclSymbol.getConstructorMethod(); + var extendedTypes = classDeclSymbol.getExtendedTypes(); + var parentType = extendedTypes.length ? extendedTypes[0] : null; + + if (constructorMethod) { + if (parentType) { + var parentConstructorSymbol = parentType.getConstructorMethod(); + + if (parentConstructorSymbol) { + var parentConstructorTypeSymbol = parentConstructorSymbol.type; + var constructorTypeSymbol = constructorMethod.type; + if (!constructorTypeSymbol.hasBase(parentConstructorTypeSymbol)) { + constructorTypeSymbol.addExtendedType(parentConstructorTypeSymbol); + } + } + } + + if (!classDeclSymbol.isResolved) { + return classDeclSymbol; + } + } + + this.resolveOtherDeclarations(classDeclAST, context); + } + + if (this.canTypeCheckAST(classDeclAST, context)) { + this.typeCheckClassDeclaration(classDeclAST, context); + } + + return classDeclSymbol; + }; + + PullTypeResolver.prototype.typeCheckTypeParametersOfTypeDeclaration = function (classOrInterface, context) { + var _this = this; + var typeParametersList = classOrInterface.kind() == 131 /* ClassDeclaration */ ? classOrInterface.typeParameterList : classOrInterface.typeParameterList; + + if (typeParametersList) { + var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var typeDeclSymbol = typeDecl.getSymbol(); + + for (var i = 0; i < typeParametersList.typeParameters.nonSeparatorCount(); i++) { + var typeParameterAST = typeParametersList.typeParameters.nonSeparatorAt(i); + this.resolveTypeParameterDeclaration(typeParameterAST, context); + + var typeParameterDecl = this.semanticInfoChain.getDeclForAST(typeParameterAST); + var typeParameterSymbol = typeParameterDecl.getSymbol(); + + this.checkSymbolPrivacy(typeDeclSymbol, typeParameterSymbol, function (symbol) { + return _this.typeParameterOfTypeDeclarationPrivacyErrorReporter(classOrInterface, typeParameterAST, typeParameterSymbol, symbol, context); + }); + } + } + }; + + PullTypeResolver.prototype.typeCheckClassDeclaration = function (classDeclAST, context) { + this.setTypeChecked(classDeclAST, context); + + var classDecl = this.semanticInfoChain.getDeclForAST(classDeclAST); + var classDeclSymbol = classDecl.getSymbol(); + + this.checkNameForCompilerGeneratedDeclarationCollision(classDeclAST, true, classDeclAST.identifier, context); + this.resolveAST(classDeclAST.classElements, false, context); + + this.typeCheckTypeParametersOfTypeDeclaration(classDeclAST, context); + this.typeCheckBases(classDeclAST, classDeclAST.identifier, classDeclAST.heritageClauses, classDeclSymbol, this.getEnclosingDecl(classDecl), context); + + if (!classDeclSymbol.hasBaseTypeConflict()) { + this.typeCheckMembersAgainstIndexer(classDeclSymbol, classDecl, context); + } + + this.checkTypeForDuplicateIndexSignatures(classDeclSymbol); + }; + + PullTypeResolver.prototype.postTypeCheckClassDeclaration = function (classDeclAST, context) { + this.checkThisCaptureVariableCollides(classDeclAST, true, context); + }; + + PullTypeResolver.prototype.resolveTypeSymbolSignatures = function (typeSymbol, context) { + var callSignatures = typeSymbol.getCallSignatures(); + for (var i = 0; i < callSignatures.length; i++) { + this.resolveDeclaredSymbol(callSignatures[i], context); + } + + var constructSignatures = typeSymbol.getConstructSignatures(); + for (var i = 0; i < constructSignatures.length; i++) { + this.resolveDeclaredSymbol(constructSignatures[i], context); + } + + var indexSignatures = typeSymbol.getIndexSignatures(); + for (var i = 0; i < indexSignatures.length; i++) { + this.resolveDeclaredSymbol(indexSignatures[i], context); + } + }; + + PullTypeResolver.prototype.resolveInterfaceDeclaration = function (interfaceDeclAST, context) { + this.resolveReferenceTypeDeclaration(interfaceDeclAST, interfaceDeclAST.identifier, interfaceDeclAST.heritageClauses, context); + + var interfaceDecl = this.semanticInfoChain.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + this.resolveTypeSymbolSignatures(interfaceDeclSymbol, context); + + if (interfaceDeclSymbol.isResolved) { + this.resolveOtherDeclarations(interfaceDeclAST, context); + + if (this.canTypeCheckAST(interfaceDeclAST, context)) { + this.typeCheckInterfaceDeclaration(interfaceDeclAST, context); + } + } + + return interfaceDeclSymbol; + }; + + PullTypeResolver.prototype.typeCheckInterfaceDeclaration = function (interfaceDeclAST, context) { + this.setTypeChecked(interfaceDeclAST, context); + + var interfaceDecl = this.semanticInfoChain.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + this.resolveAST(interfaceDeclAST.body.typeMembers, false, context); + + this.typeCheckTypeParametersOfTypeDeclaration(interfaceDeclAST, context); + this.typeCheckBases(interfaceDeclAST, interfaceDeclAST.identifier, interfaceDeclAST.heritageClauses, interfaceDeclSymbol, this.getEnclosingDecl(interfaceDecl), context); + + if (!interfaceDeclSymbol.hasBaseTypeConflict()) { + this.typeCheckMembersAgainstIndexer(interfaceDeclSymbol, interfaceDecl, context); + } + + var allInterfaceDecls = interfaceDeclSymbol.getDeclarations(); + if (interfaceDecl === allInterfaceDecls[allInterfaceDecls.length - 1]) { + this.checkTypeForDuplicateIndexSignatures(interfaceDeclSymbol); + } + + if (!this.checkInterfaceDeclForIdenticalTypeParameters(interfaceDeclAST, context)) { + this.semanticInfoChain.addDiagnosticFromAST(interfaceDeclAST.identifier, TypeScript.DiagnosticCode.All_declarations_of_an_interface_must_have_identical_type_parameters); + } + }; + + PullTypeResolver.prototype.checkInterfaceDeclForIdenticalTypeParameters = function (interfaceDeclAST, context) { + var interfaceDecl = this.semanticInfoChain.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + if (!interfaceDeclSymbol.isGeneric()) { + return true; + } + + var firstInterfaceDecl = interfaceDeclSymbol.getDeclarations()[0]; + if (firstInterfaceDecl == interfaceDecl) { + return true; + } + + var typeParameters = interfaceDecl.getTypeParameters(); + var firstInterfaceDeclTypeParameters = firstInterfaceDecl.getTypeParameters(); + + if (typeParameters.length != firstInterfaceDeclTypeParameters.length) { + return false; + } + + for (var i = 0; i < typeParameters.length; i++) { + var typeParameter = typeParameters[i]; + var firstInterfaceDeclTypeParameter = firstInterfaceDeclTypeParameters[i]; + + if (typeParameter.name != firstInterfaceDeclTypeParameter.name) { + return false; + } + + var typeParameterSymbol = typeParameter.getSymbol(); + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter); + var firstInterfaceDeclTypeParameterAST = this.semanticInfoChain.getASTForDecl(firstInterfaceDeclTypeParameter); + + if (!!typeParameterAST.constraint != !!firstInterfaceDeclTypeParameterAST.constraint) { + return false; + } + + if (typeParameterAST.constraint) { + var typeParameterConstraint = this.resolveAST(typeParameterAST.constraint, false, context); + if (!this.typesAreIdenticalWithNewEnclosingTypes(typeParameterConstraint, typeParameterSymbol.getConstraint(), context)) { + return false; + } + } + } + + return true; + }; + + PullTypeResolver.prototype.checkTypeForDuplicateIndexSignatures = function (enclosingTypeSymbol) { + var indexSignatures = enclosingTypeSymbol.getOwnIndexSignatures(); + var firstStringIndexer = null; + var firstNumberIndexer = null; + for (var i = 0; i < indexSignatures.length; i++) { + var currentIndexer = indexSignatures[i]; + var currentParameterType = currentIndexer.parameters[0].type; + TypeScript.Debug.assert(currentParameterType); + if (currentParameterType === this.semanticInfoChain.stringTypeSymbol) { + if (firstStringIndexer) { + this.semanticInfoChain.addDiagnosticFromAST(currentIndexer.getDeclarations()[0].ast(), TypeScript.DiagnosticCode.Duplicate_string_index_signature, null, [this.semanticInfoChain.locationFromAST(firstStringIndexer.getDeclarations()[0].ast())]); + return; + } else { + firstStringIndexer = currentIndexer; + } + } else if (currentParameterType === this.semanticInfoChain.numberTypeSymbol) { + if (firstNumberIndexer) { + this.semanticInfoChain.addDiagnosticFromAST(currentIndexer.getDeclarations()[0].ast(), TypeScript.DiagnosticCode.Duplicate_number_index_signature, null, [this.semanticInfoChain.locationFromAST(firstNumberIndexer.getDeclarations()[0].ast())]); + return; + } else { + firstNumberIndexer = currentIndexer; + } + } + } + }; + + PullTypeResolver.prototype.filterSymbol = function (symbol, kind, enclosingDecl, context) { + if (symbol) { + if (symbol.kind & kind) { + return symbol; + } + + if (symbol.isAlias()) { + this.resolveDeclaredSymbol(symbol, context); + + var alias = symbol; + if (kind & 164 /* SomeContainer */) { + return alias.getExportAssignedContainerSymbol(); + } else if (kind & 58728795 /* SomeType */) { + return alias.getExportAssignedTypeSymbol(); + } else if (kind & 68147712 /* SomeValue */) { + return alias.getExportAssignedValueSymbol(); + } + } + } + return null; + }; + + PullTypeResolver.prototype.getMemberSymbolOfKind = function (symbolName, kind, pullTypeSymbol, enclosingDecl, context) { + var memberSymbol = this.getNamedPropertySymbol(symbolName, kind, pullTypeSymbol); + + return { + symbol: this.filterSymbol(memberSymbol, kind, enclosingDecl, context), + aliasSymbol: memberSymbol && memberSymbol.isAlias() ? memberSymbol : null + }; + }; + + PullTypeResolver.prototype.resolveIdentifierOfInternalModuleReference = function (importDecl, identifier, moduleSymbol, enclosingDecl, context) { + var rhsName = identifier.valueText(); + if (rhsName.length === 0) { + return null; + } + + var moduleTypeSymbol = moduleSymbol.type; + var memberSymbol = this.getMemberSymbolOfKind(rhsName, 164 /* SomeContainer */, moduleTypeSymbol, enclosingDecl, context); + var containerSymbol = memberSymbol.symbol; + var valueSymbol = null; + var typeSymbol = null; + var aliasSymbol = null; + + var acceptableAlias = true; + + if (containerSymbol) { + acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) !== 0; + aliasSymbol = memberSymbol.aliasSymbol; + } + + if (!acceptableAlias && containerSymbol && containerSymbol.kind === 128 /* TypeAlias */) { + this.resolveDeclaredSymbol(containerSymbol, context); + var aliasedAssignedValue = containerSymbol.getExportAssignedValueSymbol(); + var aliasedAssignedType = containerSymbol.getExportAssignedTypeSymbol(); + var aliasedAssignedContainer = containerSymbol.getExportAssignedContainerSymbol(); + + if (aliasedAssignedValue || aliasedAssignedType || aliasedAssignedContainer) { + aliasSymbol = containerSymbol; + valueSymbol = aliasedAssignedValue; + typeSymbol = aliasedAssignedType; + containerSymbol = aliasedAssignedContainer; + acceptableAlias = true; + } + } + + if (!acceptableAlias) { + this.semanticInfoChain.addDiagnosticFromAST(identifier, TypeScript.DiagnosticCode.Import_declaration_referencing_identifier_from_internal_module_can_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules); + return null; + } + + if (!valueSymbol) { + if (moduleTypeSymbol.getInstanceSymbol()) { + memberSymbol = this.getMemberSymbolOfKind(rhsName, 68147712 /* SomeValue */, moduleTypeSymbol.getInstanceSymbol().type, enclosingDecl, context); + valueSymbol = memberSymbol.symbol; + if (valueSymbol && memberSymbol.aliasSymbol) { + aliasSymbol = memberSymbol.aliasSymbol; + } + } + } + + if (!typeSymbol) { + memberSymbol = this.getMemberSymbolOfKind(rhsName, 58728795 /* SomeType */, moduleTypeSymbol, enclosingDecl, context); + typeSymbol = memberSymbol.symbol; + if (typeSymbol && memberSymbol.aliasSymbol) { + aliasSymbol = memberSymbol.aliasSymbol; + } + } + + if (!valueSymbol && !typeSymbol && !containerSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(identifier, TypeScript.DiagnosticCode.Could_not_find_symbol_0_in_module_1, [rhsName, moduleSymbol.toString()]); + return null; + } + + if (!typeSymbol && containerSymbol) { + typeSymbol = containerSymbol; + } + + return { + valueSymbol: valueSymbol, + typeSymbol: typeSymbol, + containerSymbol: containerSymbol, + aliasSymbol: aliasSymbol + }; + }; + + PullTypeResolver.prototype.resolveModuleReference = function (importDecl, moduleNameExpr, enclosingDecl, context, declPath) { + TypeScript.Debug.assert(moduleNameExpr.kind() === 121 /* QualifiedName */ || moduleNameExpr.kind() === 11 /* IdentifierName */ || moduleNameExpr.kind() === 14 /* StringLiteral */, "resolving module reference should always be either name or member reference"); + + var moduleSymbol = null; + var moduleName; + + if (moduleNameExpr.kind() === 121 /* QualifiedName */) { + var dottedNameAST = moduleNameExpr; + var moduleContainer = this.resolveModuleReference(importDecl, dottedNameAST.left, enclosingDecl, context, declPath); + if (moduleContainer) { + moduleName = dottedNameAST.right.valueText(); + + moduleSymbol = this.getMemberSymbolOfKind(moduleName, 4 /* Container */, moduleContainer.type, enclosingDecl, context).symbol; + if (!moduleSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(dottedNameAST.right, TypeScript.DiagnosticCode.Could_not_find_module_0_in_module_1, [moduleName, moduleContainer.toString()]); + } + } + } else { + var valueText = moduleNameExpr.kind() === 11 /* IdentifierName */ ? moduleNameExpr.valueText() : moduleNameExpr.valueText(); + var text = moduleNameExpr.kind() === 11 /* IdentifierName */ ? moduleNameExpr.text() : moduleNameExpr.text(); + + if (text.length > 0) { + var resolvedModuleNameSymbol = this.getSymbolFromDeclPath(valueText, declPath, 4 /* Container */); + moduleSymbol = this.filterSymbol(resolvedModuleNameSymbol, 4 /* Container */, enclosingDecl, context); + if (moduleSymbol) { + this.semanticInfoChain.setSymbolForAST(moduleNameExpr, moduleSymbol); + if (resolvedModuleNameSymbol.isAlias()) { + this.semanticInfoChain.setAliasSymbolForAST(moduleNameExpr, resolvedModuleNameSymbol); + var importDeclSymbol = importDecl.getSymbol(); + importDeclSymbol.addLinkedAliasSymbol(resolvedModuleNameSymbol); + } + } else { + this.semanticInfoChain.addDiagnosticFromAST(moduleNameExpr, TypeScript.DiagnosticCode.Unable_to_resolve_module_reference_0, [valueText]); + } + } + } + + return moduleSymbol; + }; + + PullTypeResolver.prototype.resolveInternalModuleReference = function (importStatementAST, context) { + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var enclosingDecl = this.getEnclosingDecl(importDecl); + + var moduleReference = importStatementAST.moduleReference; + + var aliasExpr = moduleReference.kind() === 245 /* ExternalModuleReference */ ? moduleReference.stringLiteral : moduleReference.moduleName; + + var declPath = enclosingDecl.getParentPath(); + var aliasedType = null; + var importDeclSymbol = importDecl.getSymbol(); + + if (aliasExpr.kind() === 11 /* IdentifierName */ || aliasExpr.kind() === 14 /* StringLiteral */) { + var moduleSymbol = this.resolveModuleReference(importDecl, aliasExpr, enclosingDecl, context, declPath); + if (moduleSymbol) { + aliasedType = moduleSymbol.type; + this.semanticInfoChain.setAliasSymbolForAST(moduleReference, this.semanticInfoChain.getAliasSymbolForAST(aliasExpr)); + if (aliasedType.anyDeclHasFlag(32768 /* InitializedModule */)) { + var moduleName = aliasExpr.kind() === 11 /* IdentifierName */ ? aliasExpr.valueText() : aliasExpr.valueText(); + var valueSymbol = this.getSymbolFromDeclPath(moduleName, declPath, 68147712 /* SomeValue */); + var instanceSymbol = aliasedType.getInstanceSymbol(); + + if (valueSymbol && (instanceSymbol != valueSymbol || valueSymbol.type === aliasedType)) { + var text = aliasExpr.kind() === 11 /* IdentifierName */ ? aliasExpr.text() : aliasExpr.text(); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(aliasExpr, TypeScript.DiagnosticCode.Internal_module_reference_0_in_import_declaration_does_not_reference_module_instance_for_1, [text, moduleSymbol.type.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + } else { + importDeclSymbol.setAssignedValueSymbol(valueSymbol); + } + } + } else { + aliasedType = this.getNewErrorTypeSymbol(); + } + } else if (aliasExpr.kind() === 121 /* QualifiedName */) { + var dottedNameAST = aliasExpr; + var moduleSymbol = this.resolveModuleReference(importDecl, dottedNameAST.left, enclosingDecl, context, declPath); + if (moduleSymbol) { + var identifierResolution = this.resolveIdentifierOfInternalModuleReference(importDecl, dottedNameAST.right, moduleSymbol, enclosingDecl, context); + if (identifierResolution) { + importDeclSymbol.setAssignedValueSymbol(identifierResolution.valueSymbol); + importDeclSymbol.setAssignedTypeSymbol(identifierResolution.typeSymbol); + importDeclSymbol.setAssignedContainerSymbol(identifierResolution.containerSymbol); + this.semanticInfoChain.setAliasSymbolForAST(moduleReference, identifierResolution.aliasSymbol); + return null; + } + } + } + + if (!aliasedType) { + importDeclSymbol.setAssignedTypeSymbol(this.getNewErrorTypeSymbol()); + } + + return aliasedType; + }; + + PullTypeResolver.prototype.resolveImportDeclaration = function (importStatementAST, context) { + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var enclosingDecl = this.getEnclosingDecl(importDecl); + var importDeclSymbol = importDecl.getSymbol(); + + var aliasedType = null; + + if (importDeclSymbol.isResolved) { + return importDeclSymbol; + } + + importDeclSymbol.startResolving(); + + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + var modPath = importStatementAST.moduleReference.stringLiteral.valueText(); + var declPath = enclosingDecl.getParentPath(); + + aliasedType = this.resolveExternalModuleReference(modPath, importDecl.fileName()); + + if (!aliasedType) { + var path = importStatementAST.moduleReference.stringLiteral.text(); + this.semanticInfoChain.addDiagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Unable_to_resolve_external_module_0, [path]); + aliasedType = this.getNewErrorTypeSymbol(); + } + } else { + aliasedType = this.resolveInternalModuleReference(importStatementAST, context); + } + + if (aliasedType) { + if (!aliasedType.isContainer()) { + this.semanticInfoChain.addDiagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Module_cannot_be_aliased_to_a_non_module_type); + if (!aliasedType.isError()) { + aliasedType = this.getNewErrorTypeSymbol(); + } + } + + if (aliasedType.isContainer()) { + importDeclSymbol.setAssignedContainerSymbol(aliasedType); + } + importDeclSymbol.setAssignedTypeSymbol(aliasedType); + + this.setSymbolForAST(importStatementAST.moduleReference, aliasedType, null); + } + + importDeclSymbol.setResolved(); + + this.resolveDeclaredSymbol(importDeclSymbol.assignedValue(), context); + this.resolveDeclaredSymbol(importDeclSymbol.assignedType(), context); + this.resolveDeclaredSymbol(importDeclSymbol.assignedContainer(), context); + + if (aliasedType && importDeclSymbol.anyDeclHasFlag(1 /* Exported */)) { + importDeclSymbol.setIsUsedInExportedAlias(); + + if (aliasedType.isContainer() && aliasedType.getExportAssignedValueSymbol()) { + importDeclSymbol.setIsUsedAsValue(); + } + } + + if (this.canTypeCheckAST(importStatementAST, context)) { + this.typeCheckImportDeclaration(importStatementAST, context); + } + + return importDeclSymbol; + }; + + PullTypeResolver.prototype.typeCheckImportDeclaration = function (importStatementAST, context) { + var _this = this; + this.setTypeChecked(importStatementAST, context); + + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var enclosingDecl = this.getEnclosingDecl(importDecl); + var importDeclSymbol = importDecl.getSymbol(); + + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + if (this.compilationSettings.noResolve()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Import_declaration_cannot_refer_to_external_module_reference_when_noResolve_option_is_set, null)); + } + + var modPath = importStatementAST.moduleReference.stringLiteral.valueText(); + if (enclosingDecl.kind === 32 /* DynamicModule */) { + var ast = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(this.getASTForDecl(enclosingDecl)); + if (ast && ast.kind() === 130 /* ModuleDeclaration */) { + if (TypeScript.isRelative(modPath)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name)); + } + } + } + } + + var checkPrivacy; + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + var containerSymbol = importDeclSymbol.getExportAssignedContainerSymbol(); + var container = containerSymbol ? containerSymbol.getContainer() : null; + if (container && container.kind === 32 /* DynamicModule */) { + checkPrivacy = true; + } + } else { + checkPrivacy = true; + } + + if (checkPrivacy) { + var typeSymbol = importDeclSymbol.getExportAssignedTypeSymbol(); + var containerSymbol = importDeclSymbol.getExportAssignedContainerSymbol(); + var valueSymbol = importDeclSymbol.getExportAssignedValueSymbol(); + + this.checkSymbolPrivacy(importDeclSymbol, containerSymbol, function (symbol) { + var messageCode = TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_container_that_is_or_is_using_inaccessible_module_1; + var messageArguments = [importDeclSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null), symbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null, false, false, true)]; + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(importStatementAST, messageCode, messageArguments)); + }); + + if (typeSymbol !== containerSymbol) { + this.checkSymbolPrivacy(importDeclSymbol, typeSymbol, function (symbol) { + var messageCode = symbol.isContainer() && !symbol.isEnum() ? TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_type_that_is_using_inaccessible_module_1 : TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_type_that_has_or_is_using_private_type_1; + + var messageArguments = [importDeclSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null), symbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null, false, false, true)]; + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(importStatementAST, messageCode, messageArguments)); + }); + } + + if (valueSymbol) { + this.checkSymbolPrivacy(importDeclSymbol, valueSymbol.type, function (symbol) { + var messageCode = symbol.isContainer() && !symbol.isEnum() ? TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_value_with_type_that_is_using_inaccessible_module_1 : TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_value_with_type_that_has_or_is_using_private_type_1; + var messageArguments = [importDeclSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null), symbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null, false, false, true)]; + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(importStatementAST, messageCode, messageArguments)); + }); + } + } + + this.checkNameForCompilerGeneratedDeclarationCollision(importStatementAST, true, importStatementAST.identifier, context); + }; + + PullTypeResolver.prototype.postTypeCheckImportDeclaration = function (importStatementAST, context) { + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var importSymbol = importDecl.getSymbol(); + + var isUsedAsValue = importSymbol.isUsedAsValue(); + var hasAssignedValue = importStatementAST.moduleReference.kind() !== 245 /* ExternalModuleReference */ && importSymbol.getExportAssignedValueSymbol() !== null; + + if (isUsedAsValue || hasAssignedValue) { + this.checkThisCaptureVariableCollides(importStatementAST, true, context); + } + }; + + PullTypeResolver.prototype.resolveExportAssignmentStatement = function (exportAssignmentAST, context) { + var id = exportAssignmentAST.identifier.valueText(); + if (id.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var valueSymbol = null; + var typeSymbol = null; + var containerSymbol = null; + + var enclosingDecl = this.getEnclosingDeclForAST(exportAssignmentAST); + var parentSymbol = enclosingDecl.getSymbol(); + + if (!parentSymbol.isType() && parentSymbol.isContainer()) { + this.semanticInfoChain.addDiagnosticFromAST(exportAssignmentAST, TypeScript.DiagnosticCode.Export_assignments_may_only_be_used_at_the_top_level_of_external_modules); + return this.semanticInfoChain.anyTypeSymbol; + } + + var declPath = enclosingDecl !== null ? [enclosingDecl] : []; + + containerSymbol = this.getSymbolFromDeclPath(id, declPath, 164 /* SomeContainer */); + + var acceptableAlias = true; + + if (containerSymbol) { + acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) !== 0; + } + + if (!acceptableAlias && containerSymbol && containerSymbol.kind === 128 /* TypeAlias */) { + this.resolveDeclaredSymbol(containerSymbol, context); + + var aliasSymbol = containerSymbol; + var aliasedAssignedValue = aliasSymbol.getExportAssignedValueSymbol(); + var aliasedAssignedType = aliasSymbol.getExportAssignedTypeSymbol(); + var aliasedAssignedContainer = aliasSymbol.getExportAssignedContainerSymbol(); + + if (aliasedAssignedValue || aliasedAssignedType || aliasedAssignedContainer) { + valueSymbol = aliasedAssignedValue; + typeSymbol = aliasedAssignedType; + containerSymbol = aliasedAssignedContainer; + aliasSymbol.setTypeUsedExternally(); + if (valueSymbol) { + aliasSymbol.setIsUsedAsValue(); + } + acceptableAlias = true; + } + } + + if (!acceptableAlias) { + this.semanticInfoChain.addDiagnosticFromAST(exportAssignmentAST, TypeScript.DiagnosticCode.Export_assignments_may_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules); + return this.semanticInfoChain.voidTypeSymbol; + } + + if (!valueSymbol) { + valueSymbol = this.getSymbolFromDeclPath(id, declPath, 68147712 /* SomeValue */); + } + if (!typeSymbol) { + typeSymbol = this.getSymbolFromDeclPath(id, declPath, 58728795 /* SomeType */); + } + + if (!valueSymbol && !typeSymbol && !containerSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(exportAssignmentAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [id])); + return this.semanticInfoChain.voidTypeSymbol; + } + + if (valueSymbol) { + parentSymbol.setExportAssignedValueSymbol(valueSymbol); + } + if (typeSymbol) { + parentSymbol.setExportAssignedTypeSymbol(typeSymbol); + } + if (containerSymbol) { + parentSymbol.setExportAssignedContainerSymbol(containerSymbol); + } + + this.resolveDeclaredSymbol(valueSymbol, context); + this.resolveDeclaredSymbol(typeSymbol, context); + this.resolveDeclaredSymbol(containerSymbol, context); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveAnyFunctionTypeSignature = function (funcDeclAST, typeParameters, parameterList, returnTypeAnnotation, context) { + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + TypeScript.Debug.assert(functionDecl); + + var funcDeclSymbol = functionDecl.getSymbol(); + + var signature = funcDeclSymbol.kind === 33554432 /* ConstructorType */ ? funcDeclSymbol.getConstructSignatures()[0] : funcDeclSymbol.getCallSignatures()[0]; + + if (returnTypeAnnotation) { + signature.returnType = this.resolveTypeReference(returnTypeAnnotation, context); + } + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + if (parameterList) { + for (var i = 0; i < parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveFunctionTypeSignatureParameter(parameterList.parameters.nonSeparatorAt(i), signature, functionDecl, context); + } + } + + funcDeclSymbol.setResolved(); + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.setTypeChecked(funcDeclAST, context); + this.typeCheckFunctionOverloads(funcDeclAST, context); + } + + return funcDeclSymbol; + }; + + PullTypeResolver.prototype.resolveFunctionTypeSignatureParameter = function (argDeclAST, signature, enclosingDecl, context) { + var paramDecl = this.semanticInfoChain.getDeclForAST(argDeclAST); + var paramSymbol = paramDecl.getSymbol(); + + if (argDeclAST.typeAnnotation) { + var typeRef = this.resolveTypeReference(TypeScript.ASTHelpers.getType(argDeclAST), context); + + if (paramSymbol.isVarArg && !typeRef.isArrayNamedTypeReference()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); + typeRef = this.getNewErrorTypeSymbol(); + } + + context.setTypeInContext(paramSymbol, typeRef); + } else { + if (paramSymbol.isVarArg) { + if (this.cachedArrayInterfaceType()) { + context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [this.semanticInfoChain.anyTypeSymbol])); + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_function_type_implicitly_has_an_any_type, [argDeclAST.identifier.text()])); + } + } + + if (TypeScript.hasFlag(paramDecl.flags, 128 /* Optional */) && argDeclAST.equalsValueClause && isTypesOnlyLocation(argDeclAST)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Default_arguments_are_only_allowed_in_implementation)); + } + + paramSymbol.setResolved(); + }; + + PullTypeResolver.prototype.resolveFunctionExpressionParameter = function (argDeclAST, id, typeExpr, equalsValueClause, contextParam, enclosingDecl, context) { + var paramDecl = this.semanticInfoChain.getDeclForAST(argDeclAST); + var paramSymbol = paramDecl.getSymbol(); + var contextualType = contextParam && contextParam.type; + var isImplicitAny = false; + + if (typeExpr) { + var typeRef = this.resolveTypeReference(typeExpr, context); + + if (paramSymbol.isVarArg && !typeRef.isArrayNamedTypeReference()) { + var diagnostic = context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); + typeRef = this.getNewErrorTypeSymbol(); + } + + contextualType = typeRef || contextualType; + } + if (contextualType) { + if (context.isInferentiallyTyping()) { + contextualType = context.fixAllTypeParametersReferencedByType(contextualType, this); + } + context.setTypeInContext(paramSymbol, contextualType); + } else if (paramSymbol.isVarArg) { + if (this.cachedArrayInterfaceType()) { + context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [this.semanticInfoChain.anyTypeSymbol])); + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + isImplicitAny = true; + } + + var canTypeCheckAST = this.canTypeCheckAST(argDeclAST, context); + if (equalsValueClause && (canTypeCheckAST || !contextualType)) { + if (contextualType) { + context.propagateContextualType(contextualType); + } + + var initExprSymbol = this.resolveAST(equalsValueClause, contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + } + + if (!initExprSymbol || !initExprSymbol.type) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Unable_to_resolve_type_of_0, [id.text()])); + + if (!contextualType) { + context.setTypeInContext(paramSymbol, this.getNewErrorTypeSymbol(paramSymbol.name)); + } + } else { + var initTypeSymbol = this.getInstanceTypeForAssignment(argDeclAST, initExprSymbol.type, context); + if (!contextualType) { + context.setTypeInContext(paramSymbol, initTypeSymbol.widenedType(this, equalsValueClause, context)); + isImplicitAny = initTypeSymbol !== paramSymbol.type; + } else { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(initTypeSymbol, contextualType, argDeclAST, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(argDeclAST); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [initTypeSymbol.toString(enclosingSymbol), contextualType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [initTypeSymbol.toString(enclosingSymbol), contextualType.toString(enclosingSymbol)])); + } + } + } + } + } + + if (!contextualType && !paramSymbol.isVarArg && !initTypeSymbol) { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + isImplicitAny = true; + } + + if (isImplicitAny && this.compilationSettings.noImplicitAny()) { + var functionExpressionName = paramDecl.getParentDecl().getFunctionExpressionName(); + if (functionExpressionName) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [id.text(), functionExpressionName])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_lambda_function_implicitly_has_an_any_type, [id.text()])); + } + } + + if (canTypeCheckAST) { + this.checkNameForCompilerGeneratedDeclarationCollision(argDeclAST, true, id, context); + } + + paramSymbol.setResolved(); + }; + + PullTypeResolver.prototype.checkNameForCompilerGeneratedDeclarationCollision = function (astWithName, isDeclaration, name, context) { + var compilerReservedName = getCompilerReservedName(name); + switch (compilerReservedName) { + case 1 /* _this */: + this.postTypeCheckWorkitems.push(astWithName); + return; + + case 2 /* _super */: + this.checkSuperCaptureVariableCollides(astWithName, isDeclaration, context); + return; + + case 3 /* arguments */: + this.checkArgumentsCollides(astWithName, context); + return; + + case 4 /* _i */: + this.checkIndexOfRestArgumentInitializationCollides(astWithName, isDeclaration, context); + return; + + case 5 /* require */: + case 6 /* exports */: + if (isDeclaration) { + this.checkExternalModuleRequireExportsCollides(astWithName, name, context); + } + return; + } + }; + + PullTypeResolver.prototype.hasRestParameterCodeGen = function (someFunctionDecl) { + var enclosingAST = this.getASTForDecl(someFunctionDecl); + var nodeType = enclosingAST.kind(); + + if (nodeType === 129 /* FunctionDeclaration */) { + var functionDeclaration = enclosingAST; + return !TypeScript.hasFlag(someFunctionDecl.kind === 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && functionDeclaration.block && TypeScript.lastParameterIsRest(functionDeclaration.callSignature.parameterList); + } else if (nodeType === 135 /* MemberFunctionDeclaration */) { + var memberFunction = enclosingAST; + return !TypeScript.hasFlag(someFunctionDecl.kind === 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && memberFunction.block && TypeScript.lastParameterIsRest(memberFunction.callSignature.parameterList); + } else if (nodeType === 137 /* ConstructorDeclaration */) { + var constructorDeclaration = enclosingAST; + return !TypeScript.hasFlag(someFunctionDecl.getParentDecl().flags, 8 /* Ambient */) && constructorDeclaration.block && TypeScript.lastParameterIsRest(constructorDeclaration.callSignature.parameterList); + } else if (nodeType === 218 /* ParenthesizedArrowFunctionExpression */) { + var arrowFunctionExpression = enclosingAST; + return TypeScript.lastParameterIsRest(arrowFunctionExpression.callSignature.parameterList); + } else if (nodeType === 222 /* FunctionExpression */) { + var functionExpression = enclosingAST; + return TypeScript.lastParameterIsRest(functionExpression.callSignature.parameterList); + } + + return false; + }; + + PullTypeResolver.prototype.checkArgumentsCollides = function (ast, context) { + if (ast.kind() === 242 /* Parameter */) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + if (TypeScript.hasFlag(enclosingDecl.kind, 1032192 /* SomeFunction */)) { + if (this.hasRestParameterCodeGen(enclosingDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters)); + } + } + } + }; + + PullTypeResolver.prototype.checkIndexOfRestArgumentInitializationCollides = function (ast, isDeclaration, context) { + if (!isDeclaration || ast.kind() === 242 /* Parameter */) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + var declPath = isDeclaration ? [enclosingDecl] : (enclosingDecl ? enclosingDecl.getParentPath() : []); + var resolvedSymbol = null; + var resolvedSymbolContainer; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + if (!isDeclaration) { + if (!resolvedSymbol) { + resolvedSymbol = this.resolveNameExpression(ast, context); + if (resolvedSymbol.isError()) { + return; + } + + resolvedSymbolContainer = resolvedSymbol.getContainer(); + } + + if (resolvedSymbolContainer && TypeScript.ArrayUtilities.contains(resolvedSymbolContainer.getDeclarations(), decl)) { + break; + } + } + + if (TypeScript.hasFlag(decl.kind, 1032192 /* SomeFunction */)) { + if (this.hasRestParameterCodeGen(decl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, isDeclaration ? TypeScript.DiagnosticCode.Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter : TypeScript.DiagnosticCode.Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter)); + } + } + } + } + }; + + PullTypeResolver.prototype.checkExternalModuleRequireExportsCollides = function (ast, name, context) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(name); + if (enclosingModule) { + enclosingDecl = this.getEnclosingDeclForAST(enclosingModule); + } + + if (enclosingDecl && enclosingDecl.kind === 32 /* DynamicModule */) { + var decl = this.semanticInfoChain.getDeclForAST(ast); + + if (!TypeScript.hasFlag(decl.flags, 8 /* Ambient */)) { + var nameText = name.valueText(); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module, [nameText, nameText])); + } + } + }; + + PullTypeResolver.prototype.resolveObjectTypeTypeReference = function (objectType, context) { + var interfaceDecl = this.semanticInfoChain.getDeclForAST(objectType); + TypeScript.Debug.assert(interfaceDecl); + + var interfaceSymbol = interfaceDecl.getSymbol(); + TypeScript.Debug.assert(interfaceSymbol); + + if (objectType.typeMembers) { + var memberDecl = null; + var memberSymbol = null; + var memberType = null; + var typeMembers = objectType.typeMembers; + + for (var i = 0; i < typeMembers.nonSeparatorCount(); i++) { + memberDecl = this.semanticInfoChain.getDeclForAST(typeMembers.nonSeparatorAt(i)); + memberSymbol = (memberDecl.kind & 7340032 /* SomeSignature */) ? memberDecl.getSignatureSymbol() : memberDecl.getSymbol(); + + this.resolveAST(typeMembers.nonSeparatorAt(i), false, context); + + memberType = memberSymbol.type; + + if ((memberType && memberType.isGeneric()) || (memberSymbol.isSignature() && memberSymbol.isGeneric())) { + interfaceSymbol.setHasGenericMember(); + } + } + } + + interfaceSymbol.setResolved(); + + if (this.canTypeCheckAST(objectType, context)) { + this.typeCheckObjectTypeTypeReference(objectType, context); + } + + return interfaceSymbol; + }; + + PullTypeResolver.prototype.typeCheckObjectTypeTypeReference = function (objectType, context) { + this.setTypeChecked(objectType, context); + var objectTypeDecl = this.semanticInfoChain.getDeclForAST(objectType); + var objectTypeSymbol = objectTypeDecl.getSymbol(); + + this.typeCheckMembersAgainstIndexer(objectTypeSymbol, objectTypeDecl, context); + this.checkTypeForDuplicateIndexSignatures(objectTypeSymbol); + }; + + PullTypeResolver.prototype.resolveTypeAnnotation = function (typeAnnotation, context) { + return this.resolveTypeReference(typeAnnotation.type, context); + }; + + PullTypeResolver.prototype.resolveTypeReference = function (typeRef, context) { + if (typeRef === null) { + return null; + } + + TypeScript.Debug.assert(typeRef.kind() !== 244 /* TypeAnnotation */); + + var aliasType = null; + var type = this.computeTypeReferenceSymbol(typeRef, context); + + if (type.kind === 4 /* Container */) { + var container = type; + var instanceSymbol = container.getInstanceSymbol(); + + if (instanceSymbol && (instanceSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */) || instanceSymbol.kind === 32768 /* ConstructorMethod */)) { + type = instanceSymbol.type.getAssociatedContainerType(); + } + } + + if (type && type.isAlias()) { + aliasType = type; + type = aliasType.getExportAssignedTypeSymbol(); + } + + if (type && !type.isGeneric()) { + if (aliasType) { + this.semanticInfoChain.setAliasSymbolForAST(typeRef, aliasType); + } + } + + if (type && !type.isError()) { + if ((type.kind & 58728795 /* SomeType */) === 0) { + if (type.kind & 164 /* SomeContainer */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeRef, TypeScript.DiagnosticCode.Type_reference_cannot_refer_to_container_0, [aliasType ? aliasType.toString() : type.toString()])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeRef, TypeScript.DiagnosticCode.Type_reference_must_refer_to_type)); + } + } + } + + if (this.canTypeCheckAST(typeRef, context)) { + this.setTypeChecked(typeRef, context); + } + + return type; + }; + + PullTypeResolver.prototype.getArrayType = function (elementType) { + var arraySymbol = elementType.getArrayType(); + + if (!arraySymbol) { + arraySymbol = this.createInstantiatedType(this.cachedArrayInterfaceType(), [elementType]); + + if (!arraySymbol) { + arraySymbol = this.semanticInfoChain.anyTypeSymbol; + } + + elementType.setArrayType(arraySymbol); + } + + return arraySymbol; + }; + + PullTypeResolver.prototype.computeTypeReferenceSymbol = function (term, context) { + switch (term.kind()) { + case 60 /* AnyKeyword */: + return this.semanticInfoChain.anyTypeSymbol; + case 61 /* BooleanKeyword */: + return this.semanticInfoChain.booleanTypeSymbol; + case 67 /* NumberKeyword */: + return this.semanticInfoChain.numberTypeSymbol; + case 69 /* StringKeyword */: + return this.semanticInfoChain.stringTypeSymbol; + case 41 /* VoidKeyword */: + return this.semanticInfoChain.voidTypeSymbol; + } + + var typeDeclSymbol = null; + + if (term.kind() === 11 /* IdentifierName */) { + typeDeclSymbol = this.resolveTypeNameExpression(term, context); + } else if (term.kind() === 123 /* FunctionType */) { + var functionType = term; + typeDeclSymbol = this.resolveAnyFunctionTypeSignature(functionType, functionType.typeParameterList, functionType.parameterList, functionType.type, context); + } else if (term.kind() === 125 /* ConstructorType */) { + var constructorType = term; + typeDeclSymbol = this.resolveAnyFunctionTypeSignature(constructorType, constructorType.typeParameterList, constructorType.parameterList, constructorType.type, context); + } else if (term.kind() === 122 /* ObjectType */) { + typeDeclSymbol = this.resolveObjectTypeTypeReference(term, context); + } else if (term.kind() === 126 /* GenericType */) { + typeDeclSymbol = this.resolveGenericTypeReference(term, context); + } else if (term.kind() === 121 /* QualifiedName */) { + typeDeclSymbol = this.resolveQualifiedName(term, context); + } else if (term.kind() === 14 /* StringLiteral */) { + var stringConstantAST = term; + var enclosingDecl = this.getEnclosingDeclForAST(term); + typeDeclSymbol = new TypeScript.PullStringConstantTypeSymbol(stringConstantAST.text()); + var decl = new TypeScript.PullSynthesizedDecl(stringConstantAST.text(), stringConstantAST.text(), typeDeclSymbol.kind, null, enclosingDecl, enclosingDecl.semanticInfoChain); + typeDeclSymbol.addDeclaration(decl); + } else if (term.kind() === 127 /* TypeQuery */) { + var typeQuery = term; + + var typeQueryTerm = typeQuery.name; + + var valueSymbol = this.resolveAST(typeQueryTerm, false, context); + + if (valueSymbol && valueSymbol.isAlias()) { + if (valueSymbol.assignedValue()) { + valueSymbol = valueSymbol.assignedValue(); + } else { + var containerSymbol = valueSymbol.getExportAssignedContainerSymbol(); + valueSymbol = (containerSymbol && containerSymbol.isContainer() && !containerSymbol.isEnum()) ? containerSymbol.getInstanceSymbol() : null; + } + } + + if (valueSymbol) { + typeDeclSymbol = valueSymbol.type.widenedType(this, typeQueryTerm, context); + } else { + typeDeclSymbol = this.getNewErrorTypeSymbol(); + } + } else if (term.kind() === 124 /* ArrayType */) { + var arrayType = term; + var underlying = this.resolveTypeReference(arrayType.type, context); + typeDeclSymbol = this.getArrayType(underlying); + } else { + throw TypeScript.Errors.invalidOperation("unknown type"); + } + + if (!typeDeclSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(term, TypeScript.DiagnosticCode.Unable_to_resolve_type)); + return this.getNewErrorTypeSymbol(); + } + + if (typeDeclSymbol.isError()) { + return typeDeclSymbol; + } + + if (this.genericTypeIsUsedWithoutRequiredTypeArguments(typeDeclSymbol, term, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(term, TypeScript.DiagnosticCode.Generic_type_references_must_include_all_type_arguments)); + typeDeclSymbol = this.instantiateTypeToAny(typeDeclSymbol, context); + } + + return typeDeclSymbol; + }; + + PullTypeResolver.prototype.genericTypeIsUsedWithoutRequiredTypeArguments = function (typeSymbol, term, context) { + if (!typeSymbol) { + return false; + } + + if (typeSymbol.isAlias()) { + return this.genericTypeIsUsedWithoutRequiredTypeArguments(typeSymbol.getExportAssignedTypeSymbol(), term, context); + } + + return typeSymbol.isNamedTypeSymbol() && typeSymbol.isGeneric() && !typeSymbol.isTypeParameter() && (typeSymbol.isResolved || typeSymbol.inResolution) && !typeSymbol.getIsSpecialized() && typeSymbol.getTypeParameters().length && typeSymbol.getTypeArguments() === null && this.isTypeRefWithoutTypeArgs(term); + }; + + PullTypeResolver.prototype.resolveMemberVariableDeclaration = function (varDecl, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.ASTHelpers.getType(varDecl.variableDeclarator), varDecl.variableDeclarator.equalsValueClause, context); + }; + + PullTypeResolver.prototype.resolvePropertySignature = function (varDecl, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), null, context); + }; + + PullTypeResolver.prototype.resolveVariableDeclarator = function (varDecl, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.equalsValueClause, context); + }; + + PullTypeResolver.prototype.resolveParameterList = function (list, context) { + return this.resolveSeparatedList(list.parameters, context); + }; + + PullTypeResolver.prototype.resolveParameter = function (parameter, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.ASTHelpers.getType(parameter), parameter.equalsValueClause, context); + }; + + PullTypeResolver.prototype.getEnumTypeSymbol = function (enumElement, context) { + var enumDeclaration = enumElement.parent.parent; + var decl = this.semanticInfoChain.getDeclForAST(enumDeclaration); + var symbol = decl.getSymbol(); + this.resolveDeclaredSymbol(symbol, context); + + return symbol; + }; + + PullTypeResolver.prototype.resolveEnumElement = function (enumElement, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(enumElement, TypeScript.sentinelEmptyArray, enumElement.propertyName, null, enumElement.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckEnumElement = function (enumElement, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(enumElement, TypeScript.sentinelEmptyArray, enumElement.propertyName, null, enumElement.equalsValueClause, context); + }; + + PullTypeResolver.prototype.resolveEqualsValueClause = function (clause, isContextuallyTyped, context) { + if (this.canTypeCheckAST(clause, context)) { + this.setTypeChecked(clause, context); + } + + return this.resolveAST(clause.value, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveVariableDeclaratorOrParameterOrEnumElement = function (varDeclOrParameter, modifiers, name, typeExpr, init, context) { + var hasTypeExpr = typeExpr !== null || varDeclOrParameter.kind() === 243 /* EnumElement */; + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + + if (enclosingDecl && decl.kind === 2048 /* Parameter */) { + enclosingDecl.ensureSymbolIsBound(); + } + + var declSymbol = decl.getSymbol(); + var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; + + if (declSymbol.isResolved) { + var declType = declSymbol.type; + var valDecl = decl.getValueDecl(); + + if (valDecl) { + var valSymbol = valDecl.getSymbol(); + + if (valSymbol && !valSymbol.isResolved) { + valSymbol.type = declType; + valSymbol.setResolved(); + } + } + } else { + if (declSymbol.inResolution) { + declSymbol.type = this.semanticInfoChain.anyTypeSymbol; + declSymbol.setResolved(); + return declSymbol; + } + + if (!declSymbol.type || !declSymbol.type.isError()) { + declSymbol.startResolving(); + + var typeExprSymbol = this.resolveAndTypeCheckVariableDeclarationTypeExpr(varDeclOrParameter, name, typeExpr, context); + + if (!hasTypeExpr) { + this.resolveAndTypeCheckVariableDeclaratorOrParameterInitExpr(varDeclOrParameter, name, typeExpr, init, context, typeExprSymbol); + } + + if (!(hasTypeExpr || init)) { + var defaultType = this.semanticInfoChain.anyTypeSymbol; + + if (declSymbol.isVarArg && this.cachedArrayInterfaceType()) { + defaultType = this.createInstantiatedType(this.cachedArrayInterfaceType(), [defaultType]); + } + + context.setTypeInContext(declSymbol, defaultType); + + if (declParameterSymbol) { + declParameterSymbol.type = defaultType; + } + } + declSymbol.setResolved(); + + if (declParameterSymbol) { + declParameterSymbol.setResolved(); + } + } + } + + if (this.canTypeCheckAST(varDeclOrParameter, context)) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDeclOrParameter, modifiers, name, typeExpr, init, context); + } + + return declSymbol; + }; + + PullTypeResolver.prototype.resolveAndTypeCheckVariableDeclarationTypeExpr = function (varDeclOrParameter, name, typeExpr, context) { + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + var declSymbol = decl.getSymbol(); + var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; + + if (varDeclOrParameter.kind() === 243 /* EnumElement */) { + var result = this.getEnumTypeSymbol(varDeclOrParameter, context); + declSymbol.type = result; + return result; + } + + if (!typeExpr) { + return null; + } + + var wrapperDecl = this.getEnclosingDecl(decl); + wrapperDecl = wrapperDecl || enclosingDecl; + + var typeExprSymbol = this.resolveTypeReference(typeExpr, context); + + if (!typeExprSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Unable_to_resolve_type_of_0, [name.text()])); + declSymbol.type = this.getNewErrorTypeSymbol(); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } else if (typeExprSymbol.isError()) { + context.setTypeInContext(declSymbol, typeExprSymbol); + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, typeExprSymbol); + } + } else { + if (typeExprSymbol === this.semanticInfoChain.anyTypeSymbol) { + decl.setFlag(16777216 /* IsAnnotatedWithAny */); + } + + if (typeExprSymbol.isContainer()) { + var exportedTypeSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + + if (exportedTypeSymbol) { + typeExprSymbol = exportedTypeSymbol; + } else { + typeExprSymbol = typeExprSymbol.type; + + if (typeExprSymbol.isAlias()) { + typeExprSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + } + + if (typeExprSymbol && typeExprSymbol.isContainer() && !typeExprSymbol.isEnum()) { + var instanceSymbol = typeExprSymbol.getInstanceSymbol(); + + if (!instanceSymbol || !TypeScript.PullHelpers.symbolIsEnum(instanceSymbol)) { + typeExprSymbol = this.getNewErrorTypeSymbol(); + } else { + typeExprSymbol = instanceSymbol.type; + } + } + } + } else if (declSymbol.isVarArg && !(typeExprSymbol.isArrayNamedTypeReference() || typeExprSymbol === this.cachedArrayInterfaceType())) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); + typeExprSymbol = this.getNewErrorTypeSymbol(); + } + + context.setTypeInContext(declSymbol, typeExprSymbol); + + if (declParameterSymbol) { + declParameterSymbol.type = typeExprSymbol; + } + + if (typeExprSymbol.kind === 16777216 /* FunctionType */ && !typeExprSymbol.getFunctionSymbol()) { + typeExprSymbol.setFunctionSymbol(declSymbol); + } + } + + return typeExprSymbol; + }; + + PullTypeResolver.prototype.resolveAndTypeCheckVariableDeclaratorOrParameterInitExpr = function (varDeclOrParameter, name, typeExpr, init, context, typeExprSymbol) { + if (!init) { + return null; + } + + var hasTypeExpr = typeExpr !== null || varDeclOrParameter.kind() === 243 /* EnumElement */; + if (typeExprSymbol) { + context.pushNewContextualType(typeExprSymbol); + } + + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + var declSymbol = decl.getSymbol(); + var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; + + var wrapperDecl = this.getEnclosingDecl(decl); + wrapperDecl = wrapperDecl || enclosingDecl; + + var initExprSymbol = this.resolveAST(init, typeExprSymbol !== null, context); + + if (typeExprSymbol) { + context.popAnyContextualType(); + } + + if (!initExprSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Unable_to_resolve_type_of_0, [name.text()])); + + if (!hasTypeExpr) { + context.setTypeInContext(declSymbol, this.getNewErrorTypeSymbol()); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } + } else { + var initTypeSymbol = initExprSymbol.type; + + if (!hasTypeExpr) { + var widenedInitTypeSymbol = initTypeSymbol.widenedType(this, init.value, context); + context.setTypeInContext(declSymbol, widenedInitTypeSymbol); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, widenedInitTypeSymbol); + } + + if (this.compilationSettings.noImplicitAny()) { + if ((widenedInitTypeSymbol !== initTypeSymbol) && (widenedInitTypeSymbol === this.semanticInfoChain.anyTypeSymbol)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Variable_0_implicitly_has_an_any_type, [name.text()])); + } + } + + return widenedInitTypeSymbol; + } + } + + return initTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckPropertySignature = function (varDecl, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckMemberVariableDeclaration = function (varDecl, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.variableDeclarator.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckVariableDeclarator = function (varDecl, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckParameter = function (parameter, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.ASTHelpers.getType(parameter), parameter.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckVariableDeclaratorOrParameterOrEnumElement = function (varDeclOrParameter, modifiers, name, typeExpr, init, context) { + var _this = this; + this.setTypeChecked(varDeclOrParameter, context); + + var hasTypeExpr = typeExpr !== null || varDeclOrParameter.kind() === 243 /* EnumElement */; + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + var declSymbol = decl.getSymbol(); + + var typeExprSymbol = this.resolveAndTypeCheckVariableDeclarationTypeExpr(varDeclOrParameter, name, typeExpr, context); + + var initTypeSymbol = this.resolveAndTypeCheckVariableDeclaratorOrParameterInitExpr(varDeclOrParameter, name, typeExpr, init, context, typeExprSymbol); + + if (hasTypeExpr || init) { + if (typeExprSymbol && typeExprSymbol.isAlias()) { + typeExprSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + } + + if (typeExprSymbol && typeExprSymbol.kind === 32 /* DynamicModule */) { + var exportedTypeSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + + if (exportedTypeSymbol) { + typeExprSymbol = exportedTypeSymbol; + } else { + var instanceTypeSymbol = typeExprSymbol.getInstanceType(); + + if (!instanceTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Tried_to_set_variable_type_to_uninitialized_module_type_0, [typeExprSymbol.toString()])); + typeExprSymbol = null; + } else { + typeExprSymbol = instanceTypeSymbol; + } + } + } + + initTypeSymbol = this.getInstanceTypeForAssignment(varDeclOrParameter, initTypeSymbol, context); + + if (initTypeSymbol && typeExprSymbol) { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(initTypeSymbol, typeExprSymbol, varDeclOrParameter, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(varDeclOrParameter); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [initTypeSymbol.toString(enclosingSymbol), typeExprSymbol.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [initTypeSymbol.toString(enclosingSymbol), typeExprSymbol.toString(enclosingSymbol)])); + } + } + } + } else if (varDeclOrParameter.kind() !== 243 /* EnumElement */ && this.compilationSettings.noImplicitAny() && !this.isForInVariableDeclarator(varDeclOrParameter)) { + var wrapperDecl = this.getEnclosingDecl(decl); + wrapperDecl = wrapperDecl || enclosingDecl; + + var needReportError = function (containerDecl, selfDecl) { + if (!TypeScript.hasFlag(containerDecl.flags, 8 /* Ambient */)) { + return true; + } + + return selfDecl && !TypeScript.hasFlag(selfDecl.flags, 2 /* Private */); + }; + + if ((wrapperDecl.kind === 16384 /* Function */ || wrapperDecl.kind === 32768 /* ConstructorMethod */ || wrapperDecl.kind === 2097152 /* ConstructSignature */)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [name.text(), enclosingDecl.name])); + } else if (wrapperDecl.kind === 65536 /* Method */) { + var parentDecl = wrapperDecl.getParentDecl(); + + if (needReportError(parentDecl, wrapperDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [name.text(), enclosingDecl.name])); + } + } else if (decl.kind === 4096 /* Property */ && !declSymbol.getContainer().isNamedTypeSymbol()) { + if (needReportError(wrapperDecl, decl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Member_0_of_object_type_implicitly_has_an_any_type, [name.text()])); + } + } else if (wrapperDecl.kind !== 268435456 /* CatchBlock */) { + if (needReportError(wrapperDecl) || !TypeScript.hasModifier(modifiers, 2 /* Private */)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Variable_0_implicitly_has_an_any_type, [name.text()])); + } + } + } + + if (init && varDeclOrParameter.kind() === 242 /* Parameter */) { + var containerSignature = enclosingDecl.getSignatureSymbol(); + if (containerSignature && !containerSignature.isDefinition()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Default_arguments_are_only_allowed_in_implementation)); + } + } + if (declSymbol.kind !== 2048 /* Parameter */ && (declSymbol.kind !== 4096 /* Property */ || declSymbol.getContainer().isNamedTypeSymbol())) { + this.checkSymbolPrivacy(declSymbol, declSymbol.type, function (symbol) { + return _this.variablePrivacyErrorReporter(varDeclOrParameter, declSymbol, symbol, context); + }); + } + + if ((declSymbol.kind !== 4096 /* Property */ && declSymbol.kind !== 67108864 /* EnumMember */) || declSymbol.anyDeclHasFlag(8388608 /* PropertyParameter */)) { + this.checkNameForCompilerGeneratedDeclarationCollision(varDeclOrParameter, true, name, context); + } + }; + + PullTypeResolver.prototype.isForInVariableDeclarator = function (ast) { + return ast.kind() === 225 /* VariableDeclarator */ && ast.parent && ast.parent.parent && ast.parent.parent.parent && ast.parent.kind() === 2 /* SeparatedList */ && ast.parent.parent.kind() === 224 /* VariableDeclaration */ && ast.parent.parent.parent.kind() === 155 /* ForInStatement */ && ast.parent.parent.parent.variableDeclaration === ast.parent.parent; + }; + + PullTypeResolver.prototype.checkSuperCaptureVariableCollides = function (superAST, isDeclaration, context) { + var enclosingDecl = this.getEnclosingDeclForAST(superAST); + + var classSymbol = this.getContextualClassSymbolForEnclosingDecl(superAST, enclosingDecl); + + if (classSymbol && !classSymbol.anyDeclHasFlag(8 /* Ambient */)) { + if (superAST.kind() === 242 /* Parameter */) { + var enclosingAST = this.getASTForDecl(enclosingDecl); + if (enclosingAST.kind() !== 218 /* ParenthesizedArrowFunctionExpression */ && enclosingAST.kind() !== 219 /* SimpleArrowFunctionExpression */) { + var block = enclosingDecl.kind === 65536 /* Method */ ? enclosingAST.block : enclosingAST.block; + if (!block) { + return; + } + } + } + + this.resolveDeclaredSymbol(classSymbol, context); + + var parents = classSymbol.getExtendedTypes(); + if (parents.length) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(superAST, isDeclaration ? TypeScript.DiagnosticCode.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference : TypeScript.DiagnosticCode.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference)); + } + } + }; + + PullTypeResolver.prototype.checkThisCaptureVariableCollides = function (_thisAST, isDeclaration, context) { + if (isDeclaration) { + var decl = this.semanticInfoChain.getDeclForAST(_thisAST); + if (TypeScript.hasFlag(decl.flags, 8 /* Ambient */)) { + return; + } + } + + var enclosingDecl = this.getEnclosingDeclForAST(_thisAST); + + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(_thisAST); + if (enclosingModule) { + enclosingDecl = this.getEnclosingDeclForAST(enclosingModule); + } + + var declPath = enclosingDecl.getParentPath(); + + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.kind; + if (declKind === 131072 /* FunctionExpression */ && TypeScript.hasFlag(decl.flags, 8192 /* ArrowFunction */)) { + continue; + } + + if (declKind === 16384 /* Function */ || declKind === 65536 /* Method */ || declKind === 32768 /* ConstructorMethod */ || declKind === 262144 /* GetAccessor */ || declKind === 524288 /* SetAccessor */ || declKind === 131072 /* FunctionExpression */ || declKind === 8 /* Class */ || declKind === 4 /* Container */ || declKind === 32 /* DynamicModule */ || declKind === 1 /* Script */) { + if (TypeScript.hasFlag(decl.flags, 262144 /* MustCaptureThis */)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(_thisAST, isDeclaration ? TypeScript.DiagnosticCode.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference : TypeScript.DiagnosticCode.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference)); + } + break; + } + } + }; + + PullTypeResolver.prototype.postTypeCheckVariableDeclaratorOrParameter = function (varDeclOrParameter, context) { + this.checkThisCaptureVariableCollides(varDeclOrParameter, true, context); + }; + + PullTypeResolver.prototype.resolveTypeParameterDeclaration = function (typeParameterAST, context) { + var typeParameterDecl = this.semanticInfoChain.getDeclForAST(typeParameterAST); + var typeParameterSymbol = typeParameterDecl.getSymbol(); + + this.resolveFirstTypeParameterDeclaration(typeParameterSymbol, context); + + if (typeParameterSymbol.isResolved && this.canTypeCheckAST(typeParameterAST, context)) { + this.typeCheckTypeParameterDeclaration(typeParameterAST, context); + } + + return typeParameterSymbol; + }; + + PullTypeResolver.prototype.resolveFirstTypeParameterDeclaration = function (typeParameterSymbol, context) { + var typeParameterDecl = typeParameterSymbol.getDeclarations()[0]; + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecl); + + if (typeParameterSymbol.isResolved || typeParameterSymbol.inResolution) { + return; + } + + typeParameterSymbol.startResolving(); + + if (typeParameterAST.constraint) { + var constraintTypeSymbol = this.resolveTypeReference(typeParameterAST.constraint.type, context); + + if (constraintTypeSymbol) { + typeParameterSymbol.setConstraint(constraintTypeSymbol); + } + } + + typeParameterSymbol.setResolved(); + }; + + PullTypeResolver.prototype.typeCheckTypeParameterDeclaration = function (typeParameterAST, context) { + this.setTypeChecked(typeParameterAST, context); + + var constraint = this.resolveAST(typeParameterAST.constraint, false, context); + + if (constraint) { + var typeParametersAST = typeParameterAST.parent; + var typeParameters = []; + for (var i = 0; i < typeParametersAST.nonSeparatorCount(); i++) { + var currentTypeParameterAST = typeParametersAST.nonSeparatorAt(i); + var currentTypeParameterDecl = this.semanticInfoChain.getDeclForAST(currentTypeParameterAST); + var currentTypeParameter = this.semanticInfoChain.getSymbolForDecl(currentTypeParameterDecl); + typeParameters[currentTypeParameter.pullSymbolID] = currentTypeParameter; + } + + if (constraint.wrapsSomeTypeParameter(typeParameters)) { + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); + } + } + }; + + PullTypeResolver.prototype.resolveConstraint = function (constraint, context) { + if (this.canTypeCheckAST(constraint, context)) { + this.setTypeChecked(constraint, context); + } + + return this.resolveTypeReference(constraint.type, context); + }; + + PullTypeResolver.prototype.resolveFunctionBodyReturnTypes = function (funcDeclAST, block, bodyExpression, signature, useContextualType, enclosingDecl, context) { + var _this = this; + var returnStatementsExpressions = []; + + var enclosingDeclStack = [enclosingDecl]; + + var preFindReturnExpressionTypes = function (ast, walker) { + var go = true; + + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 215 /* ObjectLiteralExpression */: + go = false; + break; + + case 150 /* ReturnStatement */: + var returnStatement = ast; + enclosingDecl.setFlag(4194304 /* HasReturnStatement */); + returnStatementsExpressions.push({ expression: returnStatement.expression, enclosingDecl: enclosingDeclStack[enclosingDeclStack.length - 1] }); + go = false; + break; + + case 236 /* CatchClause */: + case 163 /* WithStatement */: + enclosingDeclStack[enclosingDeclStack.length] = _this.semanticInfoChain.getDeclForAST(ast); + break; + + default: + break; + } + + walker.options.goChildren = go; + + return ast; + }; + + var postFindReturnExpressionEnclosingDecls = function (ast, walker) { + switch (ast.kind()) { + case 236 /* CatchClause */: + case 163 /* WithStatement */: + enclosingDeclStack.length--; + break; + default: + break; + } + + walker.options.goChildren = true; + + return ast; + }; + + if (block) { + TypeScript.getAstWalkerFactory().walk(block, preFindReturnExpressionTypes, postFindReturnExpressionEnclosingDecls); + } else { + returnStatementsExpressions.push({ expression: bodyExpression, enclosingDecl: enclosingDecl }); + enclosingDecl.setFlag(4194304 /* HasReturnStatement */); + } + + if (!returnStatementsExpressions.length) { + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + } else { + var returnExpressionSymbols = []; + var returnExpressions = []; + + for (var i = 0; i < returnStatementsExpressions.length; i++) { + var returnExpression = returnStatementsExpressions[i].expression; + if (returnExpression) { + var returnType = this.resolveAST(returnExpression, useContextualType, context).type; + + if (returnType.isError()) { + signature.returnType = returnType; + return; + } else { + if (returnExpression.parent.kind() === 150 /* ReturnStatement */) { + this.setSymbolForAST(returnExpression.parent, returnType, context); + } + } + + returnExpressionSymbols.push(returnType); + returnExpressions.push(returnExpression); + } + } + + if (!returnExpressionSymbols.length) { + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + } else { + var collection = { + getLength: function () { + return returnExpressionSymbols.length; + }, + getTypeAtIndex: function (index) { + return returnExpressionSymbols[index].type; + } + }; + + var bestCommonReturnType = this.findBestCommonType(collection, context, new TypeComparisonInfo()); + var returnType = bestCommonReturnType; + var returnExpression = returnExpressions[returnExpressionSymbols.indexOf(returnType)]; + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var functionSymbol = functionDecl.getSymbol(); + + if (returnType) { + var previousReturnType = returnType; + var newReturnType = returnType.widenedType(this, returnExpression, context); + signature.returnType = newReturnType; + + if (!TypeScript.ArrayUtilities.contains(returnExpressionSymbols, bestCommonReturnType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Could_not_find_the_best_common_type_of_types_of_all_return_statement_expressions)); + } + + if (this.compilationSettings.noImplicitAny()) { + if (previousReturnType !== newReturnType && newReturnType === this.semanticInfoChain.anyTypeSymbol) { + var functionName = enclosingDecl.name; + if (functionName === "") { + functionName = enclosingDecl.getFunctionExpressionName(); + } + + if (functionName != "") { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type, [functionName])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + } + } + + if (!functionSymbol.type && functionSymbol.isAccessor()) { + functionSymbol.type = signature.returnType; + } + } + } + }; + + PullTypeResolver.prototype.typeCheckConstructorDeclaration = function (funcDeclAST, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + for (var i = 0; i < funcDeclAST.callSignature.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveAST(funcDeclAST.callSignature.parameterList.parameters.nonSeparatorAt(i), false, context); + } + + this.resolveAST(funcDeclAST.block, false, context); + + if (funcDecl.getSignatureSymbol() && funcDecl.getSignatureSymbol().isDefinition() && this.enclosingClassIsDerived(funcDecl.getParentDecl())) { + if (!this.constructorHasSuperCall(funcDeclAST)) { + context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), "constructor".length, TypeScript.DiagnosticCode.Constructors_for_derived_classes_must_contain_a_super_call)); + } else if (this.superCallMustBeFirstStatementInConstructor(funcDecl)) { + var firstStatement = this.getFirstStatementOfBlockOrNull(funcDeclAST.block); + if (!firstStatement || !this.isSuperInvocationExpressionStatement(firstStatement)) { + context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), "constructor".length, TypeScript.DiagnosticCode.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties)); + } + } + } + + this.validateVariableDeclarationGroups(funcDecl, context); + + this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.callSignature.parameterList), null, funcDeclAST.block, context); + + this.typeCheckCallBacks.push(function (context) { + _this.typeCheckFunctionOverloads(funcDeclAST, context); + }); + }; + + PullTypeResolver.prototype.constructorHasSuperCall = function (constructorDecl) { + var _this = this; + if (constructorDecl.block) { + var foundSuperCall = false; + var pre = function (ast, walker) { + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 215 /* ObjectLiteralExpression */: + walker.options.goChildren = false; + default: + if (_this.isSuperInvocationExpression(ast)) { + foundSuperCall = true; + walker.options.stopWalking = true; + } + } + }; + + TypeScript.getAstWalkerFactory().walk(constructorDecl.block, pre); + return foundSuperCall; + } + + return false; + }; + + PullTypeResolver.prototype.typeCheckFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + this.typeCheckAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), funcDecl.callSignature.typeAnnotation, funcDecl.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckCallSignature = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckConstructSignature = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckMethodSignature = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, false, funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckMemberFunctionDeclaration = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + }; + + PullTypeResolver.prototype.containsSingleThrowStatement = function (block) { + return block !== null && block.statements.childCount() === 1 && block.statements.childAt(0).kind() === 157 /* ThrowStatement */; + }; + + PullTypeResolver.prototype.typeCheckAnyFunctionDeclaration = function (funcDeclAST, isStatic, name, typeParameters, parameters, returnTypeAnnotation, block, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + this.resolveAST(parameters, false, context); + + this.resolveAST(block, false, context); + var enclosingDecl = this.getEnclosingDecl(funcDecl); + + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); + this.validateVariableDeclarationGroups(funcDecl, context); + + this.checkFunctionTypePrivacy(funcDeclAST, isStatic, typeParameters, TypeScript.ASTHelpers.parametersFromParameterList(parameters), returnTypeAnnotation, block, context); + + this.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement(funcDecl, returnTypeAnnotation, funcDecl.getSignatureSymbol().returnType, block, context); + + if (funcDecl.kind === 16384 /* Function */) { + this.checkNameForCompilerGeneratedDeclarationCollision(funcDeclAST, true, name, context); + } + + this.typeCheckCallBacks.push(function (context) { + _this.typeCheckFunctionOverloads(funcDeclAST, context); + }); + }; + + PullTypeResolver.prototype.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement = function (functionDecl, returnTypeAnnotation, returnTypeSymbol, block, context) { + var hasReturn = TypeScript.hasFlag(functionDecl.flags, 4194304 /* HasReturnStatement */); + + if (block !== null && returnTypeAnnotation !== null && !hasReturn) { + var isVoidOrAny = this.isAnyOrEquivalent(returnTypeSymbol) || returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol; + + if (!isVoidOrAny && !this.containsSingleThrowStatement(block)) { + var funcName = functionDecl.getDisplayName() || TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Function_declared_a_non_void_return_type_but_has_no_return_expression)); + } + } + }; + + PullTypeResolver.prototype.typeCheckIndexSignature = function (funcDeclAST, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + this.resolveAST(funcDeclAST.parameter, false, context); + + var enclosingDecl = this.getEnclosingDecl(funcDecl); + + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); + this.validateVariableDeclarationGroups(funcDecl, context); + + this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.ASTHelpers.parametersFromParameter(funcDeclAST.parameter), TypeScript.ASTHelpers.getType(funcDeclAST), null, context); + + var signature = funcDecl.getSignatureSymbol(); + + this.typeCheckCallBacks.push(function (context) { + var parentSymbol = funcDecl.getSignatureSymbol().getContainer(); + var allIndexSignatures = _this.getBothKindsOfIndexSignaturesExcludingAugmentedType(parentSymbol, context); + var stringIndexSignature = allIndexSignatures.stringSignature; + var numberIndexSignature = allIndexSignatures.numericSignature; + var isNumericIndexer = numberIndexSignature === signature; + + if (numberIndexSignature && stringIndexSignature && (isNumericIndexer || stringIndexSignature.getDeclarations()[0].getParentDecl() !== numberIndexSignature.getDeclarations()[0].getParentDecl())) { + var comparisonInfo = new TypeComparisonInfo(); + + if (!_this.sourceIsAssignableToTarget(numberIndexSignature.returnType, stringIndexSignature.returnType, funcDeclAST, context, comparisonInfo)) { + var enclosingSymbol = _this.getEnclosingSymbolForAST(funcDeclAST); + if (comparisonInfo.message) { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1_NL_2, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol)])); + } + } + } + + var allMembers = parentSymbol.type.getAllMembers(536869887 /* All */, 0 /* all */); + for (var i = 0; i < allMembers.length; i++) { + var member = allMembers[i]; + var name = member.name; + if (name || (member.kind === 4096 /* Property */ && name === "")) { + if (!allMembers[i].isResolved) { + _this.resolveDeclaredSymbol(allMembers[i], context); + } + + if (parentSymbol !== allMembers[i].getContainer()) { + var isMemberNumeric = TypeScript.PullHelpers.isNameNumeric(name); + var indexerKindMatchesMemberNameKind = isNumericIndexer === isMemberNumeric; + var onlyStringIndexerIsPresent = !numberIndexSignature; + + if (indexerKindMatchesMemberNameKind || onlyStringIndexerIsPresent) { + var comparisonInfo = new TypeComparisonInfo(); + if (!_this.sourceIsAssignableToTarget(allMembers[i].type, signature.returnType, funcDeclAST, context, comparisonInfo, false)) { + _this.reportErrorThatMemberIsNotSubtypeOfIndexer(allMembers[i], signature, funcDeclAST, context, comparisonInfo); + } + } + } + } + } + }); + }; + + PullTypeResolver.prototype.postTypeCheckFunctionDeclaration = function (funcDeclAST, context) { + this.checkThisCaptureVariableCollides(funcDeclAST, true, context); + }; + + PullTypeResolver.prototype.resolveReturnTypeAnnotationOfFunctionDeclaration = function (funcDeclAST, returnTypeAnnotation, context) { + var returnTypeSymbol = null; + + if (returnTypeAnnotation) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + returnTypeSymbol = this.resolveTypeReference(returnTypeAnnotation, context); + + if (!returnTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); + } else { + var isConstructor = funcDeclAST.kind() === 137 /* ConstructorDeclaration */ || funcDeclAST.kind() === 143 /* ConstructSignature */; + if (isConstructor && returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Constructors_cannot_have_a_return_type_of_void)); + } + } + } + + return returnTypeSymbol; + }; + + PullTypeResolver.prototype.resolveMemberFunctionDeclaration = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + }; + + PullTypeResolver.prototype.resolveCallSignature = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.resolveConstructSignature = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.resolveMethodSignature = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, false, funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.resolveAnyFunctionDeclaration = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + }; + + PullTypeResolver.prototype.resolveFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveSimpleArrowFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcDecl, null, TypeScript.ASTHelpers.parametersFromIdentifier(funcDecl.identifier), null, funcDecl.block, funcDecl.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveParenthesizedArrowFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, funcDecl.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.getEnclosingClassDeclaration = function (ast) { + while (ast) { + if (ast.kind() === 131 /* ClassDeclaration */) { + return ast; + } + + ast = ast.parent; + } + + return null; + }; + + PullTypeResolver.prototype.resolveConstructorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcSymbol = funcDecl.getSymbol(); + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckConstructorDeclaration(funcDeclAST, context); + } + return funcSymbol; + } + + if (!signature.inResolution) { + var classAST = this.getEnclosingClassDeclaration(funcDeclAST); + + if (classAST) { + var classDecl = this.semanticInfoChain.getDeclForAST(classAST); + var classSymbol = classDecl.getSymbol(); + + if (!classSymbol.isResolved && !classSymbol.inResolution) { + this.resolveDeclaredSymbol(classSymbol, context); + } + } + } + + var functionTypeSymbol = funcSymbol && funcSymbol.type; + + if (signature.inResolution) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + return funcSymbol; + } + + if (funcSymbol) { + funcSymbol.startResolving(); + } + signature.startResolving(); + + var prevInTypeCheck = context.inTypeCheck; + + context.inTypeCheck = false; + + for (var i = 0; i < funcDeclAST.callSignature.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(funcDeclAST.callSignature.parameterList.parameters.nonSeparatorAt(i), context); + } + + context.inTypeCheck = prevInTypeCheck; + + if (signature.isGeneric()) { + if (funcSymbol) { + funcSymbol.type.setHasGenericSignature(); + } + } + + if (!hadError) { + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + } + } + + if (funcSymbol) { + this.resolveOtherDeclarations(funcDeclAST, context); + } + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckConstructorDeclaration(funcDeclAST, context); + } + + return funcSymbol; + }; + + PullTypeResolver.prototype.resolveIndexMemberDeclaration = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + } + + return this.resolveIndexSignature(ast.indexSignature, context); + }; + + PullTypeResolver.prototype.resolveIndexSignature = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcSymbol = funcDecl.getSymbol(); + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckIndexSignature(funcDeclAST, context); + } + return funcSymbol; + } + + var functionTypeSymbol = funcSymbol && funcSymbol.type; + + if (signature.inResolution) { + if (funcDeclAST.typeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(TypeScript.ASTHelpers.getType(funcDeclAST), context); + if (!returnTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(TypeScript.ASTHelpers.getType(funcDeclAST), TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + } + + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + return funcSymbol; + } + + if (funcSymbol) { + funcSymbol.startResolving(); + } + signature.startResolving(); + + if (funcDeclAST.parameter) { + var prevInTypeCheck = context.inTypeCheck; + + context.inTypeCheck = false; + this.resolveParameter(funcDeclAST.parameter, context); + context.inTypeCheck = prevInTypeCheck; + } + + if (funcDeclAST.typeAnnotation) { + returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); + + if (!returnTypeSymbol) { + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + } + + if (!hadError) { + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + } + } + + if (funcSymbol) { + this.resolveOtherDeclarations(funcDeclAST, context); + } + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckIndexSignature(funcDeclAST, context); + } + + return funcSymbol; + }; + + PullTypeResolver.prototype.resolveFunctionDeclaration = function (funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcSymbol = funcDecl.getSymbol(); + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + var isConstructor = funcDeclAST.kind() === 143 /* ConstructSignature */; + + if (signature) { + if (signature.isResolved) { + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckAnyFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); + } + return funcSymbol; + } + + if (isConstructor && !signature.inResolution) { + var classAST = this.getEnclosingClassDeclaration(funcDeclAST); + + if (classAST) { + var classDecl = this.semanticInfoChain.getDeclForAST(classAST); + var classSymbol = classDecl.getSymbol(); + + if (!classSymbol.isResolved && !classSymbol.inResolution) { + this.resolveDeclaredSymbol(classSymbol, context); + } + } + } + + var functionTypeSymbol = funcSymbol && funcSymbol.type; + + if (signature.inResolution) { + if (returnTypeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(returnTypeAnnotation, context); + if (!returnTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + + if (isConstructor && returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Constructors_cannot_have_a_return_type_of_void)); + } + } + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + } + + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + return funcSymbol; + } + + if (funcSymbol) { + funcSymbol.startResolving(); + } + signature.startResolving(); + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + if (parameterList) { + var prevInTypeCheck = context.inTypeCheck; + + context.inTypeCheck = false; + + for (var i = 0; i < parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(parameterList.parameters.nonSeparatorAt(i), context); + } + + context.inTypeCheck = prevInTypeCheck; + } + + if (returnTypeAnnotation) { + returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); + + if (!returnTypeSymbol) { + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else if (funcDecl.kind !== 2097152 /* ConstructSignature */) { + if (TypeScript.hasFlag(funcDecl.flags, 2048 /* Signature */)) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + var parentDeclFlags = 0 /* None */; + if (TypeScript.hasFlag(funcDecl.kind, 65536 /* Method */) || TypeScript.hasFlag(funcDecl.kind, 32768 /* ConstructorMethod */)) { + var parentDecl = funcDecl.getParentDecl(); + parentDeclFlags = parentDecl.flags; + } + + if (this.compilationSettings.noImplicitAny() && (!TypeScript.hasFlag(parentDeclFlags, 8 /* Ambient */) || (TypeScript.hasFlag(parentDeclFlags, 8 /* Ambient */) && !TypeScript.hasFlag(funcDecl.flags, 2 /* Private */)))) { + var funcDeclASTName = name; + if (funcDeclASTName) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type, [funcDeclASTName.text()])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Lambda_Function_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + } else { + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, null, signature, false, funcDecl, context); + } + } else if (funcDecl.kind === 2097152 /* ConstructSignature */) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Constructor_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + + if (!hadError) { + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + } + } + + if (funcSymbol) { + this.resolveOtherDeclarations(funcDeclAST, context); + } + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckAnyFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); + } + + return funcSymbol; + }; + + PullTypeResolver.prototype.resolveGetterReturnTypeAnnotation = function (getterFunctionDeclarationAst, enclosingDecl, context) { + if (getterFunctionDeclarationAst && getterFunctionDeclarationAst.typeAnnotation) { + return this.resolveTypeReference(TypeScript.ASTHelpers.getType(getterFunctionDeclarationAst), context); + } + + return null; + }; + + PullTypeResolver.prototype.resolveSetterArgumentTypeAnnotation = function (setterFunctionDeclarationAst, enclosingDecl, context) { + if (setterFunctionDeclarationAst && setterFunctionDeclarationAst.parameterList && setterFunctionDeclarationAst.parameterList.parameters.nonSeparatorCount() > 0) { + var parameter = setterFunctionDeclarationAst.parameterList.parameters.nonSeparatorAt(0); + return this.resolveTypeReference(TypeScript.ASTHelpers.getType(parameter), context); + } + + return null; + }; + + PullTypeResolver.prototype.resolveAccessorDeclaration = function (funcDeclAst, context) { + var functionDeclaration = this.semanticInfoChain.getDeclForAST(funcDeclAst); + var accessorSymbol = functionDeclaration.getSymbol(); + + if (accessorSymbol.inResolution) { + accessorSymbol.type = this.semanticInfoChain.anyTypeSymbol; + accessorSymbol.setResolved(); + + return accessorSymbol; + } + + if (accessorSymbol.isResolved) { + if (!accessorSymbol.type) { + accessorSymbol.type = this.semanticInfoChain.anyTypeSymbol; + } + } else { + var getterSymbol = accessorSymbol.getGetter(); + var getterFunctionDeclarationAst = getterSymbol ? getterSymbol.getDeclarations()[0].ast() : null; + var hasGetter = getterSymbol !== null; + + var setterSymbol = accessorSymbol.getSetter(); + var setterFunctionDeclarationAst = setterSymbol ? setterSymbol.getDeclarations()[0].ast() : null; + var hasSetter = setterSymbol !== null; + + var getterAnnotatedType = this.resolveGetterReturnTypeAnnotation(getterFunctionDeclarationAst, functionDeclaration, context); + var getterHasTypeAnnotation = getterAnnotatedType !== null; + + var setterAnnotatedType = this.resolveSetterArgumentTypeAnnotation(setterFunctionDeclarationAst, functionDeclaration, context); + var setterHasTypeAnnotation = setterAnnotatedType !== null; + + accessorSymbol.startResolving(); + + if (hasGetter) { + getterSymbol = this.resolveGetAccessorDeclaration(getterFunctionDeclarationAst, getterFunctionDeclarationAst.parameterList, TypeScript.ASTHelpers.getType(getterFunctionDeclarationAst), getterFunctionDeclarationAst.block, setterAnnotatedType, context); + } + + if (hasSetter) { + setterSymbol = this.resolveSetAccessorDeclaration(setterFunctionDeclarationAst, setterFunctionDeclarationAst.parameterList, context); + } + + if (hasGetter && hasSetter) { + var setterSig = setterSymbol.type.getCallSignatures()[0]; + var setterParameters = setterSig.parameters; + var setterHasParameters = setterParameters.length > 0; + var getterSig = getterSymbol.type.getCallSignatures()[0]; + + var setterSuppliedTypeSymbol = setterHasParameters ? setterParameters[0].type : null; + var getterSuppliedTypeSymbol = getterSig.returnType; + + if (setterHasTypeAnnotation && !getterHasTypeAnnotation) { + getterSuppliedTypeSymbol = setterSuppliedTypeSymbol; + getterSig.returnType = setterSuppliedTypeSymbol; + } else if ((getterHasTypeAnnotation && !setterHasTypeAnnotation) || (!getterHasTypeAnnotation && !setterHasTypeAnnotation)) { + setterSuppliedTypeSymbol = getterSuppliedTypeSymbol; + + if (setterHasParameters) { + setterParameters[0].type = getterSuppliedTypeSymbol; + } + } + + if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol, context)) { + accessorSymbol.type = this.getNewErrorTypeSymbol(); + } else { + accessorSymbol.type = getterSuppliedTypeSymbol; + } + } else if (hasSetter) { + var setterSig = setterSymbol.type.getCallSignatures()[0]; + var setterParameters = setterSig.parameters; + var setterHasParameters = setterParameters.length > 0; + + accessorSymbol.type = setterHasParameters ? setterParameters[0].type : this.semanticInfoChain.anyTypeSymbol; + } else { + var getterSig = getterSymbol.type.getCallSignatures()[0]; + accessorSymbol.type = getterSig.returnType; + } + + accessorSymbol.setResolved(); + } + + if (this.canTypeCheckAST(funcDeclAst, context)) { + this.typeCheckAccessorDeclaration(funcDeclAst, context); + } + + return accessorSymbol; + }; + + PullTypeResolver.prototype.typeCheckAccessorDeclaration = function (funcDeclAst, context) { + this.setTypeChecked(funcDeclAst, context); + var functionDeclaration = this.semanticInfoChain.getDeclForAST(funcDeclAst); + var accessorSymbol = functionDeclaration.getSymbol(); + var getterSymbol = accessorSymbol.getGetter(); + var setterSymbol = accessorSymbol.getSetter(); + + var isGetter = funcDeclAst.kind() === 139 /* GetAccessor */; + if (isGetter) { + var getterFunctionDeclarationAst = funcDeclAst; + context.pushNewContextualType(getterSymbol.type); + this.typeCheckGetAccessorDeclaration(getterFunctionDeclarationAst, context); + context.popAnyContextualType(); + } else { + var setterFunctionDeclarationAst = funcDeclAst; + this.typeCheckSetAccessorDeclaration(setterFunctionDeclarationAst, context); + } + }; + + PullTypeResolver.prototype.resolveGetAccessorDeclaration = function (funcDeclAST, parameters, returnTypeAnnotation, block, setterAnnotatedType, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + var getterSymbol = accessorSymbol.getGetter(); + var getterTypeSymbol = getterSymbol.type; + + var signature = getterTypeSymbol.getCallSignatures()[0]; + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + return getterSymbol; + } + + if (signature.inResolution) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + signature.setResolved(); + + return getterSymbol; + } + + signature.startResolving(); + + if (returnTypeAnnotation) { + var returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); + + if (!returnTypeSymbol) { + signature.returnType = this.getNewErrorTypeSymbol(); + + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else { + if (!setterAnnotatedType) { + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, null, signature, false, funcDecl, context); + } else { + signature.returnType = setterAnnotatedType; + } + } + + if (!hadError) { + signature.setResolved(); + } + } + + return getterSymbol; + }; + + PullTypeResolver.prototype.checkIfGetterAndSetterTypeMatch = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + var getter = accessorSymbol.getGetter(); + var setter = accessorSymbol.getSetter(); + + if (getter && setter) { + var getterAST = getter.getDeclarations()[0].ast(); + var setterAST = setter.getDeclarations()[0].ast(); + + if (getterAST.typeAnnotation && PullTypeResolver.hasSetAccessorParameterTypeAnnotation(setterAST)) { + var setterSig = setter.type.getCallSignatures()[0]; + var setterParameters = setterSig.parameters; + + var getter = accessorSymbol.getGetter(); + var getterSig = getter.type.getCallSignatures()[0]; + + var setterSuppliedTypeSymbol = setterParameters[0].type; + var getterSuppliedTypeSymbol = getterSig.returnType; + + if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.get_and_set_accessor_must_have_the_same_type)); + } + } + } + }; + + PullTypeResolver.prototype.typeCheckGetAccessorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); + + this.resolveAST(funcDeclAST.block, false, context); + + this.validateVariableDeclarationGroups(funcDecl, context); + + var enclosingDecl = this.getEnclosingDecl(funcDecl); + + var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) !== 0; + var funcNameAST = funcDeclAST.propertyName; + + if (!hasReturn && !this.containsSingleThrowStatement(funcDeclAST.block)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getters_must_return_a_value)); + } + + var setter = accessorSymbol.getSetter(); + if (setter) { + var setterDecl = setter.getDeclarations()[0]; + var setterIsPrivate = TypeScript.hasFlag(setterDecl.flags, 2 /* Private */); + var getterIsPrivate = TypeScript.hasModifier(funcDeclAST.modifiers, 2 /* Private */); + + if (getterIsPrivate !== setterIsPrivate) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getter_and_setter_accessors_do_not_agree_in_visibility)); + } + + this.checkIfGetterAndSetterTypeMatch(funcDeclAST, context); + } + + this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), TypeScript.ASTHelpers.getType(funcDeclAST), funcDeclAST.block, context); + }; + + PullTypeResolver.hasSetAccessorParameterTypeAnnotation = function (setAccessor) { + return setAccessor.parameterList && setAccessor.parameterList.parameters.nonSeparatorCount() > 0 && setAccessor.parameterList.parameters.nonSeparatorAt(0).typeAnnotation !== null; + }; + + PullTypeResolver.prototype.resolveSetAccessorDeclaration = function (funcDeclAST, parameterList, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + var setterSymbol = accessorSymbol.getSetter(); + var setterTypeSymbol = setterSymbol.type; + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + return setterSymbol; + } + + if (signature.inResolution) { + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + signature.setResolved(); + return setterSymbol; + } + + signature.startResolving(); + + if (parameterList) { + for (var i = 0; i < parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(parameterList.parameters.nonSeparatorAt(i), context); + } + } + + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + + if (!hadError) { + signature.setResolved(); + } + } + + return setterSymbol; + }; + + PullTypeResolver.prototype.typeCheckSetAccessorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + if (funcDeclAST.parameterList) { + for (var i = 0; i < funcDeclAST.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(funcDeclAST.parameterList.parameters.nonSeparatorAt(i), context); + } + } + + this.resolveAST(funcDeclAST.block, false, context); + + this.validateVariableDeclarationGroups(funcDecl, context); + + var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) !== 0; + + var getter = accessorSymbol.getGetter(); + + var funcNameAST = funcDeclAST.propertyName; + + if (getter) { + var getterDecl = getter.getDeclarations()[0]; + var getterIsPrivate = TypeScript.hasFlag(getterDecl.flags, 2 /* Private */); + var setterIsPrivate = TypeScript.hasModifier(funcDeclAST.modifiers, 2 /* Private */); + + if (getterIsPrivate !== setterIsPrivate) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getter_and_setter_accessors_do_not_agree_in_visibility)); + } + + this.checkIfGetterAndSetterTypeMatch(funcDeclAST, context); + } else { + if (this.compilationSettings.noImplicitAny()) { + var setterFunctionDeclarationAst = funcDeclAST; + if (!PullTypeResolver.hasSetAccessorParameterTypeAnnotation(setterFunctionDeclarationAst) && accessorSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type, [setterFunctionDeclarationAst.propertyName.text()])); + } + } + } + + this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), null, funcDeclAST.block, context); + }; + + PullTypeResolver.prototype.resolveList = function (list, context) { + if (this.canTypeCheckAST(list, context)) { + this.setTypeChecked(list, context); + + for (var i = 0, n = list.childCount(); i < n; i++) { + this.resolveAST(list.childAt(i), false, context); + } + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveSeparatedList = function (list, context) { + if (this.canTypeCheckAST(list, context)) { + this.setTypeChecked(list, context); + + for (var i = 0, n = list.nonSeparatorCount(); i < n; i++) { + this.resolveAST(list.nonSeparatorAt(i), false, context); + } + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveVoidExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.undefinedTypeSymbol; + }; + + PullTypeResolver.prototype.resolveLogicalOperation = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckLogicalOperation(ast, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckLogicalOperation = function (binex, context) { + this.setTypeChecked(binex, context); + + var leftType = this.resolveAST(binex.left, false, context).type; + var rightType = this.resolveAST(binex.right, false, context).type; + + var comparisonInfo = new TypeComparisonInfo(); + if (!this.sourceIsAssignableToTarget(leftType, rightType, binex, context, comparisonInfo) && !this.sourceIsAssignableToTarget(rightType, leftType, binex, context, comparisonInfo)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(binex); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binex, TypeScript.DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2, [ + TypeScript.SyntaxFacts.getText(TypeScript.SyntaxFacts.getOperatorTokenFromBinaryExpression(binex.kind())), + leftType.toString(enclosingSymbol), rightType.toString(enclosingSymbol)])); + } + }; + + PullTypeResolver.prototype.resolveLogicalNotExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.operand, false, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.resolveUnaryArithmeticOperation = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckUnaryArithmeticOperation(ast, context); + } + + return this.semanticInfoChain.numberTypeSymbol; + }; + + PullTypeResolver.prototype.resolvePostfixUnaryExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckPostfixUnaryExpression(ast, context); + } + + return this.semanticInfoChain.numberTypeSymbol; + }; + + PullTypeResolver.prototype.isAnyOrNumberOrEnum = function (type) { + return this.isAnyOrEquivalent(type) || type === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(type); + }; + + PullTypeResolver.prototype.typeCheckUnaryArithmeticOperation = function (unaryExpression, context) { + this.setTypeChecked(unaryExpression, context); + + var nodeType = unaryExpression.kind(); + var expression = this.resolveAST(unaryExpression.operand, false, context); + + if (nodeType === 164 /* PlusExpression */ || nodeType == 165 /* NegateExpression */ || nodeType == 166 /* BitwiseNotExpression */) { + return; + } + + TypeScript.Debug.assert(nodeType === 168 /* PreIncrementExpression */ || nodeType === 169 /* PreDecrementExpression */); + + var operandType = expression.type; + if (!this.isAnyOrNumberOrEnum(operandType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type_any_number_or_an_enum_type)); + } + + if (!this.isReference(unaryExpression.operand, expression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer)); + } + }; + + PullTypeResolver.prototype.typeCheckPostfixUnaryExpression = function (unaryExpression, context) { + this.setTypeChecked(unaryExpression, context); + + var nodeType = unaryExpression.kind(); + var expression = this.resolveAST(unaryExpression.operand, false, context); + + TypeScript.Debug.assert(nodeType === 210 /* PostIncrementExpression */ || nodeType === 211 /* PostDecrementExpression */); + + var operandType = expression.type; + if (!this.isAnyOrNumberOrEnum(operandType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type_any_number_or_an_enum_type)); + } + + if (!this.isReference(unaryExpression.operand, expression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer)); + } + }; + + PullTypeResolver.prototype.resolveBinaryArithmeticExpression = function (binaryExpression, context) { + if (this.canTypeCheckAST(binaryExpression, context)) { + this.typeCheckBinaryArithmeticExpression(binaryExpression, context); + } + + return this.semanticInfoChain.numberTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckBinaryArithmeticExpression = function (binaryExpression, context) { + this.setTypeChecked(binaryExpression, context); + + var lhsSymbol = this.resolveAST(binaryExpression.left, false, context); + + var lhsType = lhsSymbol.type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + if (lhsType === this.semanticInfoChain.nullTypeSymbol || lhsType === this.semanticInfoChain.undefinedTypeSymbol) { + lhsType = rhsType; + } + + if (rhsType === this.semanticInfoChain.nullTypeSymbol || rhsType === this.semanticInfoChain.undefinedTypeSymbol) { + rhsType = lhsType; + } + + var lhsIsFit = this.isAnyOrNumberOrEnum(lhsType); + var rhsIsFit = this.isAnyOrNumberOrEnum(rhsType); + + if (!rhsIsFit) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type)); + } + + if (!lhsIsFit) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type)); + } + + if (lhsIsFit && rhsIsFit) { + switch (binaryExpression.kind()) { + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + if (!this.isReference(binaryExpression.left, lhsSymbol)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_left_hand_side_of_assignment_expression)); + } + + this.checkAssignability(binaryExpression.left, rhsType, lhsType, context); + } + } + }; + + PullTypeResolver.prototype.resolveTypeOfExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.stringTypeSymbol; + }; + + PullTypeResolver.prototype.resolveThrowStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveDeleteExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.resolveInstanceOfExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckInstanceOfExpression(ast, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckInstanceOfExpression = function (binaryExpression, context) { + this.setTypeChecked(binaryExpression, context); + + var lhsType = this.resolveAST(binaryExpression.left, false, context).type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + var enclosingSymbol = this.getEnclosingSymbolForAST(binaryExpression); + var isValidLHS = this.isAnyOrEquivalent(lhsType) || lhsType.isObject() || lhsType.isTypeParameter(); + var isValidRHS = this.isAnyOrEquivalent(rhsType) || this.typeIsAssignableToFunction(rhsType, binaryExpression, context); + + if (!isValidLHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter)); + } + + if (!isValidRHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type)); + } + }; + + PullTypeResolver.prototype.resolveCommaExpression = function (commaExpression, context) { + if (this.canTypeCheckAST(commaExpression, context)) { + this.setTypeChecked(commaExpression, context); + + this.resolveAST(commaExpression.left, false, context); + } + + return this.resolveAST(commaExpression.right, false, context).type; + }; + + PullTypeResolver.prototype.resolveInExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckInExpression(ast, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckInExpression = function (binaryExpression, context) { + this.setTypeChecked(binaryExpression, context); + + var lhsType = this.resolveAST(binaryExpression.left, false, context).type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + var isValidLHS = this.isAnyOrEquivalent(lhsType.type) || lhsType.type === this.semanticInfoChain.stringTypeSymbol || lhsType.type === this.semanticInfoChain.numberTypeSymbol; + + var isValidRHS = this.isAnyOrEquivalent(rhsType) || rhsType.isObject() || rhsType.isTypeParameter(); + + if (!isValidLHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number)); + } + + if (!isValidRHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter)); + } + }; + + PullTypeResolver.prototype.resolveForStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.variableDeclaration, false, context); + this.resolveAST(ast.initializer, false, context); + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.incrementor, false, context); + this.resolveAST(ast.statement, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveForInStatement = function (forInStatement, context) { + if (this.canTypeCheckAST(forInStatement, context)) { + this.typeCheckForInStatement(forInStatement, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckForInStatement = function (forInStatement, context) { + this.setTypeChecked(forInStatement, context); + + if (forInStatement.variableDeclaration) { + var declaration = forInStatement.variableDeclaration; + + if (declaration.declarators.nonSeparatorCount() === 1) { + var varDecl = declaration.declarators.nonSeparatorAt(0); + + if (varDecl.typeAnnotation) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(declaration, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_cannot_use_a_type_annotation)); + } + } + } else { + var varSym = this.resolveAST(forInStatement.left, false, context); + var isStringOrNumber = varSym.type === this.semanticInfoChain.stringTypeSymbol || this.isAnyOrEquivalent(varSym.type); + + if (!isStringOrNumber) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(forInStatement.left, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_must_be_of_types_string_or_any)); + } + } + + var rhsType = this.resolveAST(forInStatement.expression, false, context).type; + var isValidRHS = rhsType && (this.isAnyOrEquivalent(rhsType) || rhsType.isObject() || rhsType.isTypeParameter()); + + if (!isValidRHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(forInStatement.expression, TypeScript.DiagnosticCode.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter)); + } + + this.resolveAST(forInStatement.statement, false, context); + }; + + PullTypeResolver.prototype.resolveWhileStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckWhileStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckWhileStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.resolveDoStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckDoStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckDoStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.resolveIfStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckIfStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckIfStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.statement, false, context); + this.resolveAST(ast.elseClause, false, context); + }; + + PullTypeResolver.prototype.resolveElseClause = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckElseClause(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckElseClause = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.resolveBlock = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.statements, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveVariableStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.declaration, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveVariableDeclarationList = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.declarators, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveWithStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckWithStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckWithStatement = function (ast, context) { + this.setTypeChecked(ast, context); + var withStatement = ast; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(withStatement.condition, TypeScript.DiagnosticCode.All_symbols_within_a_with_block_will_be_resolved_to_any)); + }; + + PullTypeResolver.prototype.resolveTryStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckTryStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckTryStatement = function (ast, context) { + this.setTypeChecked(ast, context); + var tryStatement = ast; + + this.resolveAST(tryStatement.block, false, context); + this.resolveAST(tryStatement.catchClause, false, context); + this.resolveAST(tryStatement.finallyClause, false, context); + }; + + PullTypeResolver.prototype.resolveCatchClause = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckCatchClause(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckCatchClause = function (ast, context) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.block, false, context); + + var catchDecl = this.semanticInfoChain.getDeclForAST(ast); + this.validateVariableDeclarationGroups(catchDecl, context); + }; + + PullTypeResolver.prototype.resolveFinallyClause = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckFinallyClause(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckFinallyClause = function (ast, context) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.block, false, context); + }; + + PullTypeResolver.prototype.getEnclosingFunctionDeclaration = function (ast) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + + while (enclosingDecl) { + if (enclosingDecl.kind & 1032192 /* SomeFunction */) { + return enclosingDecl; + } + + enclosingDecl = enclosingDecl.getParentDecl(); + } + + return null; + }; + + PullTypeResolver.prototype.resolveReturnExpression = function (expression, enclosingFunction, context) { + if (enclosingFunction) { + enclosingFunction.setFlag(4194304 /* HasReturnStatement */); + } + + var isContextuallyTyped = false; + + if (enclosingFunction) { + var enclosingDeclAST = this.getASTForDecl(enclosingFunction); + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); + if (typeAnnotation) { + var returnTypeAnnotationSymbol = this.resolveTypeReference(typeAnnotation, context); + if (returnTypeAnnotationSymbol) { + isContextuallyTyped = true; + context.pushNewContextualType(returnTypeAnnotationSymbol); + } + } else { + var currentContextualType = context.getContextualType(); + if (currentContextualType && currentContextualType.isFunction()) { + var contextualSignatures = currentContextualType.kind == 33554432 /* ConstructorType */ ? currentContextualType.getConstructSignatures() : currentContextualType.getCallSignatures(); + var currentContextualTypeSignatureSymbol = contextualSignatures[0]; + + var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.returnType; + if (currentContextualTypeReturnTypeSymbol) { + isContextuallyTyped = true; + context.propagateContextualType(currentContextualTypeReturnTypeSymbol); + } + } + } + } + + var result = this.resolveAST(expression, isContextuallyTyped, context).type; + if (isContextuallyTyped) { + context.popAnyContextualType(); + } + + return result; + }; + + PullTypeResolver.prototype.typeCheckReturnExpression = function (expression, expressionType, enclosingFunction, context) { + if (enclosingFunction && enclosingFunction.kind === 32768 /* ConstructorMethod */) { + var classDecl = enclosingFunction.getParentDecl(); + if (classDecl) { + var classSymbol = classDecl.getSymbol(); + this.resolveDeclaredSymbol(classSymbol, context); + + var comparisonInfo = new TypeComparisonInfo(); + var isAssignable = this.sourceIsAssignableToTarget(expressionType, classSymbol.type, expression, context, comparisonInfo); + if (!isAssignable) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class)); + } + } + } + + if (enclosingFunction && enclosingFunction.kind === 524288 /* SetAccessor */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Setters_cannot_return_a_value)); + } + + if (enclosingFunction) { + var enclosingDeclAST = this.getASTForDecl(enclosingFunction); + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); + if (typeAnnotation || enclosingFunction.kind === 262144 /* GetAccessor */) { + var signatureSymbol = enclosingFunction.getSignatureSymbol(); + var sigReturnType = signatureSymbol.returnType; + + if (expressionType && sigReturnType) { + var comparisonInfo = new TypeComparisonInfo(); + var upperBound = null; + + this.resolveDeclaredSymbol(expressionType, context); + this.resolveDeclaredSymbol(sigReturnType, context); + + var isAssignable = this.sourceIsAssignableToTarget(expressionType, sigReturnType, expression, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(expression); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [expressionType.toString(enclosingSymbol), sigReturnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [expressionType.toString(enclosingSymbol), sigReturnType.toString(enclosingSymbol)])); + } + } + } + } + } + }; + + PullTypeResolver.prototype.resolveReturnStatement = function (returnAST, context) { + var enclosingFunction = this.getEnclosingFunctionDeclaration(returnAST); + if (enclosingFunction) { + enclosingFunction.setFlag(4194304 /* HasReturnStatement */); + } + + var returnType = this.getSymbolForAST(returnAST, context); + var canTypeCheckAST = this.canTypeCheckAST(returnAST, context); + if (!returnType || canTypeCheckAST) { + var returnExpr = returnAST.expression; + + var resolvedReturnType = returnExpr === null ? this.semanticInfoChain.voidTypeSymbol : this.resolveReturnExpression(returnExpr, enclosingFunction, context); + + if (!returnType) { + returnType = resolvedReturnType; + this.setSymbolForAST(returnAST, resolvedReturnType, context); + } + + if (returnExpr && canTypeCheckAST) { + this.setTypeChecked(returnExpr, context); + this.typeCheckReturnExpression(returnExpr, resolvedReturnType, enclosingFunction, context); + } + } + + return returnType; + }; + + PullTypeResolver.prototype.resolveSwitchStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckSwitchStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckSwitchStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + var expressionType = this.resolveAST(ast.expression, false, context).type; + + for (var i = 0, n = ast.switchClauses.childCount(); i < n; i++) { + var switchClause = ast.switchClauses.childAt(i); + if (switchClause.kind() === 233 /* CaseSwitchClause */) { + var caseSwitchClause = switchClause; + + var caseClauseExpressionType = this.resolveAST(caseSwitchClause.expression, false, context).type; + this.resolveAST(caseSwitchClause.statements, false, context); + + var comparisonInfo = new TypeComparisonInfo(); + if (!this.sourceIsAssignableToTarget(expressionType, caseClauseExpressionType, caseSwitchClause.expression, context, comparisonInfo) && !this.sourceIsAssignableToTarget(caseClauseExpressionType, expressionType, caseSwitchClause.expression, context, comparisonInfo)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(caseSwitchClause.expression); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(caseSwitchClause.expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [caseClauseExpressionType.toString(enclosingSymbol), expressionType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(caseSwitchClause.expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [caseClauseExpressionType.toString(enclosingSymbol), expressionType.toString(enclosingSymbol)])); + } + } + } else { + var defaultSwitchClause = switchClause; + this.resolveAST(defaultSwitchClause.statements, false, context); + } + } + }; + + PullTypeResolver.prototype.resolveLabeledStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckLabeledStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckLabeledStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + var labelIdentifier = ast.identifier.valueText(); + + var breakableLabels = this.getEnclosingLabels(ast, true, false); + + var matchingLabel = TypeScript.ArrayUtilities.firstOrDefault(breakableLabels, function (s) { + return s.identifier.valueText() === labelIdentifier; + }); + if (matchingLabel) { + context.postDiagnostic(this.semanticInfoChain.duplicateIdentifierDiagnosticFromAST(ast.identifier, labelIdentifier, matchingLabel)); + } + + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.labelIsOnContinuableConstruct = function (statement) { + switch (statement.kind()) { + case 160 /* LabeledStatement */: + return this.labelIsOnContinuableConstruct(statement.statement); + + case 158 /* WhileStatement */: + case 154 /* ForStatement */: + case 155 /* ForInStatement */: + case 161 /* DoStatement */: + return true; + + default: + return false; + } + }; + + PullTypeResolver.prototype.resolveContinueStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckContinueStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.isIterationStatement = function (ast) { + switch (ast.kind()) { + case 154 /* ForStatement */: + case 155 /* ForInStatement */: + case 158 /* WhileStatement */: + case 161 /* DoStatement */: + return true; + } + + return false; + }; + + PullTypeResolver.prototype.isAnyFunctionExpressionOrDeclaration = function (ast) { + switch (ast.kind()) { + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 129 /* FunctionDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 241 /* FunctionPropertyAssignment */: + case 137 /* ConstructorDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + return true; + } + + return false; + }; + + PullTypeResolver.prototype.inSwitchStatement = function (ast) { + while (ast) { + if (ast.kind() === 151 /* SwitchStatement */) { + return true; + } + + if (this.isAnyFunctionExpressionOrDeclaration(ast)) { + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inIterationStatement = function (ast, crossFunctions) { + while (ast) { + if (this.isIterationStatement(ast)) { + return true; + } + + if (!crossFunctions && this.isAnyFunctionExpressionOrDeclaration(ast)) { + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.getEnclosingLabels = function (ast, breakable, crossFunctions) { + var result = []; + + ast = ast.parent; + while (ast) { + if (ast.kind() === 160 /* LabeledStatement */) { + var labeledStatement = ast; + if (breakable) { + result.push(labeledStatement); + } else { + if (this.labelIsOnContinuableConstruct(labeledStatement.statement)) { + result.push(labeledStatement); + } + } + } + + if (!crossFunctions && this.isAnyFunctionExpressionOrDeclaration(ast)) { + break; + } + + ast = ast.parent; + } + + return result; + }; + + PullTypeResolver.prototype.typeCheckContinueStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + if (!this.inIterationStatement(ast, false)) { + if (this.inIterationStatement(ast, true)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.continue_statement_can_only_be_used_within_an_enclosing_iteration_statement)); + } + } else if (ast.identifier) { + var continuableLabels = this.getEnclosingLabels(ast, false, false); + + if (!TypeScript.ArrayUtilities.any(continuableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + var continuableLabels = this.getEnclosingLabels(ast, false, true); + + if (TypeScript.ArrayUtilities.any(continuableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_not_found)); + } + } + } + }; + + PullTypeResolver.prototype.resolveBreakStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckBreakStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckBreakStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + if (ast.identifier) { + var breakableLabels = this.getEnclosingLabels(ast, true, false); + + if (!TypeScript.ArrayUtilities.any(breakableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + var breakableLabels = this.getEnclosingLabels(ast, true, true); + if (TypeScript.ArrayUtilities.any(breakableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_not_found)); + } + } + } else if (!this.inIterationStatement(ast, false) && !this.inSwitchStatement(ast)) { + if (this.inIterationStatement(ast, true)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement)); + } + } + }; + + PullTypeResolver.prototype.resolveAST = function (ast, isContextuallyTyped, context) { + if (!ast) { + return; + } + + var symbol = this.getSymbolForAST(ast, context); + if (symbol && symbol.isResolved) { + this.typeCheckAST(ast, isContextuallyTyped, context); + return symbol; + } + + if (ast.isExpression() && !isTypesOnlyLocation(ast)) { + return this.resolveExpressionAST(ast, isContextuallyTyped, context); + } + + var nodeType = ast.kind(); + + switch (nodeType) { + case 124 /* ArrayType */: + case 126 /* GenericType */: + case 122 /* ObjectType */: + case 127 /* TypeQuery */: + case 125 /* ConstructorType */: + case 123 /* FunctionType */: + return this.resolveTypeReference(ast, context); + + case 1 /* List */: + return this.resolveList(ast, context); + + case 2 /* SeparatedList */: + return this.resolveSeparatedList(ast, context); + + case 120 /* SourceUnit */: + return this.resolveSourceUnit(ast, context); + + case 132 /* EnumDeclaration */: + return this.resolveEnumDeclaration(ast, context); + + case 130 /* ModuleDeclaration */: + return this.resolveModuleDeclaration(ast, context); + + case 128 /* InterfaceDeclaration */: + return this.resolveInterfaceDeclaration(ast, context); + + case 131 /* ClassDeclaration */: + return this.resolveClassDeclaration(ast, context); + + case 224 /* VariableDeclaration */: + return this.resolveVariableDeclarationList(ast, context); + + case 136 /* MemberVariableDeclaration */: + return this.resolveMemberVariableDeclaration(ast, context); + + case 225 /* VariableDeclarator */: + return this.resolveVariableDeclarator(ast, context); + + case 141 /* PropertySignature */: + return this.resolvePropertySignature(ast, context); + + case 227 /* ParameterList */: + return this.resolveParameterList(ast, context); + + case 242 /* Parameter */: + return this.resolveParameter(ast, context); + + case 243 /* EnumElement */: + return this.resolveEnumElement(ast, context); + + case 232 /* EqualsValueClause */: + return this.resolveEqualsValueClause(ast, isContextuallyTyped, context); + + case 238 /* TypeParameter */: + return this.resolveTypeParameterDeclaration(ast, context); + + case 239 /* Constraint */: + return this.resolveConstraint(ast, context); + + case 133 /* ImportDeclaration */: + return this.resolveImportDeclaration(ast, context); + + case 240 /* SimplePropertyAssignment */: + return this.resolveSimplePropertyAssignment(ast, isContextuallyTyped, context); + + case 241 /* FunctionPropertyAssignment */: + return this.resolveFunctionPropertyAssignment(ast, isContextuallyTyped, context); + + case 11 /* IdentifierName */: + TypeScript.Debug.assert(isTypesOnlyLocation(ast)); + return this.resolveTypeNameExpression(ast, context); + + case 121 /* QualifiedName */: + return this.resolveQualifiedName(ast, context); + + case 137 /* ConstructorDeclaration */: + return this.resolveConstructorDeclaration(ast, context); + + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + return this.resolveAccessorDeclaration(ast, context); + + case 138 /* IndexMemberDeclaration */: + return this.resolveIndexMemberDeclaration(ast, context); + + case 144 /* IndexSignature */: + return this.resolveIndexSignature(ast, context); + + case 135 /* MemberFunctionDeclaration */: + return this.resolveMemberFunctionDeclaration(ast, context); + + case 142 /* CallSignature */: + return this.resolveCallSignature(ast, context); + + case 143 /* ConstructSignature */: + return this.resolveConstructSignature(ast, context); + + case 145 /* MethodSignature */: + return this.resolveMethodSignature(ast, context); + + case 129 /* FunctionDeclaration */: + return this.resolveAnyFunctionDeclaration(ast, context); + + case 244 /* TypeAnnotation */: + return this.resolveTypeAnnotation(ast, context); + + case 134 /* ExportAssignment */: + return this.resolveExportAssignmentStatement(ast, context); + + case 157 /* ThrowStatement */: + return this.resolveThrowStatement(ast, context); + + case 149 /* ExpressionStatement */: + return this.resolveExpressionStatement(ast, context); + + case 154 /* ForStatement */: + return this.resolveForStatement(ast, context); + + case 155 /* ForInStatement */: + return this.resolveForInStatement(ast, context); + + case 158 /* WhileStatement */: + return this.resolveWhileStatement(ast, context); + + case 161 /* DoStatement */: + return this.resolveDoStatement(ast, context); + + case 147 /* IfStatement */: + return this.resolveIfStatement(ast, context); + + case 235 /* ElseClause */: + return this.resolveElseClause(ast, context); + + case 146 /* Block */: + return this.resolveBlock(ast, context); + + case 148 /* VariableStatement */: + return this.resolveVariableStatement(ast, context); + + case 163 /* WithStatement */: + return this.resolveWithStatement(ast, context); + + case 159 /* TryStatement */: + return this.resolveTryStatement(ast, context); + + case 236 /* CatchClause */: + return this.resolveCatchClause(ast, context); + + case 237 /* FinallyClause */: + return this.resolveFinallyClause(ast, context); + + case 150 /* ReturnStatement */: + return this.resolveReturnStatement(ast, context); + + case 151 /* SwitchStatement */: + return this.resolveSwitchStatement(ast, context); + + case 153 /* ContinueStatement */: + return this.resolveContinueStatement(ast, context); + + case 152 /* BreakStatement */: + return this.resolveBreakStatement(ast, context); + + case 160 /* LabeledStatement */: + return this.resolveLabeledStatement(ast, context); + } + + return this.semanticInfoChain.anyTypeSymbol; + }; + + PullTypeResolver.prototype.resolveExpressionAST = function (ast, isContextuallyOrInferentiallyTyped, context) { + var expressionSymbol = this.resolveExpressionWorker(ast, isContextuallyOrInferentiallyTyped, context); + + if (isContextuallyOrInferentiallyTyped && context.isInferentiallyTyping()) { + return this.alterPotentialGenericFunctionTypeToInstantiatedFunctionTypeForTypeArgumentInference(expressionSymbol, context); + } else { + return expressionSymbol; + } + }; + + PullTypeResolver.prototype.resolveExpressionWorker = function (ast, isContextuallyTyped, context) { + switch (ast.kind()) { + case 215 /* ObjectLiteralExpression */: + return this.resolveObjectLiteralExpression(ast, isContextuallyTyped, context); + + case 11 /* IdentifierName */: + return this.resolveNameExpression(ast, context); + + case 212 /* MemberAccessExpression */: + return this.resolveMemberAccessExpression(ast, context); + + case 222 /* FunctionExpression */: + return this.resolveFunctionExpression(ast, isContextuallyTyped, context); + + case 219 /* SimpleArrowFunctionExpression */: + return this.resolveSimpleArrowFunctionExpression(ast, isContextuallyTyped, context); + + case 218 /* ParenthesizedArrowFunctionExpression */: + return this.resolveParenthesizedArrowFunctionExpression(ast, isContextuallyTyped, context); + + case 214 /* ArrayLiteralExpression */: + return this.resolveArrayLiteralExpression(ast, isContextuallyTyped, context); + + case 35 /* ThisKeyword */: + return this.resolveThisExpression(ast, context); + + case 50 /* SuperKeyword */: + return this.resolveSuperExpression(ast, context); + + case 213 /* InvocationExpression */: + return this.resolveInvocationExpression(ast, context); + + case 216 /* ObjectCreationExpression */: + return this.resolveObjectCreationExpression(ast, context); + + case 220 /* CastExpression */: + return this.resolveCastExpression(ast, context); + + case 13 /* NumericLiteral */: + return this.semanticInfoChain.numberTypeSymbol; + + case 14 /* StringLiteral */: + return this.semanticInfoChain.stringTypeSymbol; + + case 32 /* NullKeyword */: + return this.semanticInfoChain.nullTypeSymbol; + + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return this.semanticInfoChain.booleanTypeSymbol; + + case 172 /* VoidExpression */: + return this.resolveVoidExpression(ast, context); + + case 174 /* AssignmentExpression */: + return this.resolveAssignmentExpression(ast, context); + + case 167 /* LogicalNotExpression */: + return this.resolveLogicalNotExpression(ast, context); + + case 193 /* NotEqualsWithTypeConversionExpression */: + case 192 /* EqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + case 196 /* LessThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 197 /* GreaterThanExpression */: + return this.resolveLogicalOperation(ast, context); + + case 208 /* AddExpression */: + case 175 /* AddAssignmentExpression */: + return this.resolveBinaryAdditionOperation(ast, context); + + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + case 166 /* BitwiseNotExpression */: + case 168 /* PreIncrementExpression */: + case 169 /* PreDecrementExpression */: + return this.resolveUnaryArithmeticOperation(ast, context); + + case 210 /* PostIncrementExpression */: + case 211 /* PostDecrementExpression */: + return this.resolvePostfixUnaryExpression(ast, context); + + case 209 /* SubtractExpression */: + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + case 189 /* BitwiseOrExpression */: + case 191 /* BitwiseAndExpression */: + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + case 190 /* BitwiseExclusiveOrExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + return this.resolveBinaryArithmeticExpression(ast, context); + + case 221 /* ElementAccessExpression */: + return this.resolveElementAccessExpression(ast, context); + + case 187 /* LogicalOrExpression */: + return this.resolveLogicalOrExpression(ast, isContextuallyTyped, context); + + case 188 /* LogicalAndExpression */: + return this.resolveLogicalAndExpression(ast, context); + + case 171 /* TypeOfExpression */: + return this.resolveTypeOfExpression(ast, context); + + case 170 /* DeleteExpression */: + return this.resolveDeleteExpression(ast, context); + + case 186 /* ConditionalExpression */: + return this.resolveConditionalExpression(ast, isContextuallyTyped, context); + + case 12 /* RegularExpressionLiteral */: + return this.resolveRegularExpressionLiteral(); + + case 217 /* ParenthesizedExpression */: + return this.resolveParenthesizedExpression(ast, context); + + case 200 /* InstanceOfExpression */: + return this.resolveInstanceOfExpression(ast, context); + + case 173 /* CommaExpression */: + return this.resolveCommaExpression(ast, context); + + case 201 /* InExpression */: + return this.resolveInExpression(ast, context); + + case 223 /* OmittedExpression */: + return this.semanticInfoChain.undefinedTypeSymbol; + } + + TypeScript.Debug.fail("resolveExpressionASTWorker: Missing expression kind: " + TypeScript.SyntaxKind[ast.kind()]); + }; + + PullTypeResolver.prototype.typeCheckAST = function (ast, isContextuallyTyped, context) { + if (!this.canTypeCheckAST(ast, context)) { + return; + } + + var nodeType = ast.kind(); + switch (nodeType) { + case 120 /* SourceUnit */: + this.typeCheckSourceUnit(ast, context); + return; + + case 132 /* EnumDeclaration */: + this.typeCheckEnumDeclaration(ast, context); + return; + + case 130 /* ModuleDeclaration */: + this.typeCheckModuleDeclaration(ast, context); + return; + + case 128 /* InterfaceDeclaration */: + this.typeCheckInterfaceDeclaration(ast, context); + return; + + case 131 /* ClassDeclaration */: + this.typeCheckClassDeclaration(ast, context); + return; + + case 243 /* EnumElement */: + this.typeCheckEnumElement(ast, context); + return; + + case 136 /* MemberVariableDeclaration */: + this.typeCheckMemberVariableDeclaration(ast, context); + return; + + case 225 /* VariableDeclarator */: + this.typeCheckVariableDeclarator(ast, context); + return; + + case 141 /* PropertySignature */: + this.typeCheckPropertySignature(ast, context); + return; + + case 242 /* Parameter */: + this.typeCheckParameter(ast, context); + return; + + case 133 /* ImportDeclaration */: + this.typeCheckImportDeclaration(ast, context); + return; + + case 215 /* ObjectLiteralExpression */: + this.resolveObjectLiteralExpression(ast, isContextuallyTyped, context); + return; + + case 241 /* FunctionPropertyAssignment */: + this.typeCheckFunctionPropertyAssignment(ast, isContextuallyTyped, context); + return; + + case 11 /* IdentifierName */: + if (isTypesOnlyLocation(ast)) { + this.resolveTypeNameExpression(ast, context); + } else { + this.resolveNameExpression(ast, context); + } + return; + + case 212 /* MemberAccessExpression */: + this.resolveMemberAccessExpression(ast, context); + return; + + case 121 /* QualifiedName */: + this.resolveQualifiedName(ast, context); + return; + + case 222 /* FunctionExpression */: + this.typeCheckFunctionExpression(ast, isContextuallyTyped, context); + return; + + case 137 /* ConstructorDeclaration */: + this.typeCheckConstructorDeclaration(ast, context); + return; + + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + this.typeCheckAccessorDeclaration(ast, context); + return; + + case 135 /* MemberFunctionDeclaration */: + this.typeCheckMemberFunctionDeclaration(ast, context); + return; + + case 145 /* MethodSignature */: + this.typeCheckMethodSignature(ast, context); + return; + + case 144 /* IndexSignature */: + this.typeCheckIndexSignature(ast, context); + break; + + case 142 /* CallSignature */: + this.typeCheckCallSignature(ast, context); + return; + + case 143 /* ConstructSignature */: + this.typeCheckConstructSignature(ast, context); + return; + + case 129 /* FunctionDeclaration */: { + var funcDecl = ast; + this.typeCheckAnyFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + return; + } + + case 219 /* SimpleArrowFunctionExpression */: + this.typeCheckSimpleArrowFunctionExpression(ast, isContextuallyTyped, context); + return; + + case 218 /* ParenthesizedArrowFunctionExpression */: + this.typeCheckParenthesizedArrowFunctionExpression(ast, isContextuallyTyped, context); + return; + + case 214 /* ArrayLiteralExpression */: + this.resolveArrayLiteralExpression(ast, isContextuallyTyped, context); + return; + + case 213 /* InvocationExpression */: + this.typeCheckInvocationExpression(ast, context); + return; + + case 216 /* ObjectCreationExpression */: + this.typeCheckObjectCreationExpression(ast, context); + return; + + case 150 /* ReturnStatement */: + this.resolveReturnStatement(ast, context); + return; + + default: + TypeScript.Debug.assert(false, "Failure nodeType: " + TypeScript.SyntaxKind[ast.kind()] + ". Implement typeCheck when symbol is set for the ast as part of resolution."); + } + }; + + PullTypeResolver.prototype.processPostTypeCheckWorkItems = function (context) { + while (this.postTypeCheckWorkitems.length) { + var ast = this.postTypeCheckWorkitems.pop(); + this.postTypeCheck(ast, context); + } + }; + + PullTypeResolver.prototype.postTypeCheck = function (ast, context) { + var nodeType = ast.kind(); + + switch (nodeType) { + case 242 /* Parameter */: + case 225 /* VariableDeclarator */: + this.postTypeCheckVariableDeclaratorOrParameter(ast, context); + return; + + case 131 /* ClassDeclaration */: + this.postTypeCheckClassDeclaration(ast, context); + return; + + case 129 /* FunctionDeclaration */: + this.postTypeCheckFunctionDeclaration(ast, context); + return; + + case 130 /* ModuleDeclaration */: + this.postTypeCheckModuleDeclaration(ast, context); + return; + + case 132 /* EnumDeclaration */: + this.postTypeCheckEnumDeclaration(ast, context); + return; + + case 133 /* ImportDeclaration */: + this.postTypeCheckImportDeclaration(ast, context); + return; + + case 11 /* IdentifierName */: + this.postTypeCheckNameExpression(ast, context); + return; + + default: + TypeScript.Debug.assert(false, "Implement postTypeCheck clause to handle the postTypeCheck work, nodeType: " + TypeScript.SyntaxKind[ast.kind()]); + } + }; + + PullTypeResolver.prototype.resolveRegularExpressionLiteral = function () { + if (this.cachedRegExpInterfaceType()) { + return this.cachedRegExpInterfaceType(); + } else { + return this.semanticInfoChain.anyTypeSymbol; + } + }; + + PullTypeResolver.prototype.postTypeCheckNameExpression = function (nameAST, context) { + this.checkThisCaptureVariableCollides(nameAST, false, context); + }; + + PullTypeResolver.prototype.typeCheckNameExpression = function (nameAST, context) { + this.setTypeChecked(nameAST, context); + this.checkNameForCompilerGeneratedDeclarationCollision(nameAST, false, nameAST, context); + }; + + PullTypeResolver.prototype.resolveNameExpression = function (nameAST, context) { + var nameSymbol = this.getSymbolForAST(nameAST, context); + var foundCached = nameSymbol !== null; + + if (!foundCached || this.canTypeCheckAST(nameAST, context)) { + if (this.canTypeCheckAST(nameAST, context)) { + this.typeCheckNameExpression(nameAST, context); + } + nameSymbol = this.computeNameExpression(nameAST, context); + } + + this.resolveDeclaredSymbol(nameSymbol, context); + + if (nameSymbol && (nameSymbol.type !== this.semanticInfoChain.anyTypeSymbol || nameSymbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { + this.setSymbolForAST(nameAST, nameSymbol, context); + } + + return nameSymbol; + }; + + PullTypeResolver.prototype.isInEnumDecl = function (decl) { + if (decl.kind & 64 /* Enum */) { + return true; + } + + var declPath = decl.getParentPath(); + + var disallowedKinds = 164 /* SomeContainer */ | 58728795 /* SomeType */; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + + if (decl.kind & 64 /* Enum */) { + return true; + } + + if (decl.kind & disallowedKinds) { + return false; + } + } + return false; + }; + + PullTypeResolver.prototype.getSomeInnermostFunctionScopeDecl = function (declPath) { + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + if (decl.kind & 1032192 /* SomeFunction */) { + return decl; + } + } + + return null; + }; + + PullTypeResolver.prototype.isFromFunctionScope = function (nameSymbol, functionScopeDecl) { + var _this = this; + return TypeScript.ArrayUtilities.any(nameSymbol.getDeclarations(), function (nameSymbolDecl) { + return _this.getSomeInnermostFunctionScopeDecl(nameSymbolDecl.getParentPath()) === functionScopeDecl; + }); + }; + + PullTypeResolver.prototype.findConstructorDeclOfEnclosingType = function (decl) { + var current = decl; + while (current) { + if (TypeScript.hasFlag(current.kind, 4096 /* Property */)) { + var parentDecl = current.getParentDecl(); + if (TypeScript.hasFlag(parentDecl.kind, 8 /* Class */)) { + return TypeScript.ArrayUtilities.lastOrDefault(parentDecl.getChildDecls(), function (decl) { + return TypeScript.hasFlag(decl.kind, 32768 /* ConstructorMethod */); + }); + } + } + + if (TypeScript.hasFlag(current.kind, 164 /* SomeContainer */)) { + return null; + } + + current = current.getParentDecl(); + } + return null; + }; + + PullTypeResolver.prototype.checkNameAsPartOfInitializerExpressionForInstanceMemberVariable = function (nameAST, nameSymbol, context) { + var id = nameAST.valueText(); + if (id.length === 0) { + return false; + } + + var memberVariableDeclarationAST = TypeScript.ASTHelpers.getEnclosingMemberVariableDeclaration(nameAST); + if (memberVariableDeclarationAST) { + var memberVariableDecl = this.semanticInfoChain.getDeclForAST(memberVariableDeclarationAST); + if (!TypeScript.hasFlag(memberVariableDecl.flags, 16 /* Static */)) { + var constructorDecl = this.findConstructorDeclOfEnclosingType(memberVariableDecl); + + if (constructorDecl) { + var childDecls = constructorDecl.searchChildDecls(id, 68147712 /* SomeValue */); + if (childDecls.length) { + if (TypeScript.PullHelpers.isSymbolDeclaredInScopeChain(nameSymbol, constructorDecl.getSymbol().getContainer())) { + var memberVariableSymbol = memberVariableDecl.getSymbol(); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, [memberVariableSymbol.getScopedName(constructorDecl.getSymbol()), nameAST.text()])); + return true; + } + } + } + } + } + return false; + }; + + PullTypeResolver.prototype.computeNameExpression = function (nameAST, context) { + var id = nameAST.valueText(); + if (id.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var nameSymbol = null; + var enclosingDecl = this.getEnclosingDeclForAST(nameAST); + + if (TypeScript.hasFlag(enclosingDecl.flags, 8388608 /* PropertyParameter */)) { + var valueDecl = enclosingDecl.getValueDecl(); + if (valueDecl && TypeScript.hasFlag(valueDecl.kind, 2048 /* Parameter */)) { + enclosingDecl = valueDecl; + } + } + + var isDeclarationASTOrDeclarationNameAST = TypeScript.ASTHelpers.isDeclarationASTOrDeclarationNameAST(nameAST); + if (isDeclarationASTOrDeclarationNameAST) { + nameSymbol = this.semanticInfoChain.getDeclForAST(nameAST.parent).getSymbol(); + } + + var declPath = enclosingDecl.getParentPath(); + + if (!nameSymbol) { + var searchKind = 68147712 /* SomeValue */; + + if (!this.isInEnumDecl(enclosingDecl)) { + searchKind = searchKind & ~(67108864 /* EnumMember */); + } + + var nameSymbol = this.getSymbolFromDeclPath(id, declPath, searchKind); + } + + if (id === "arguments") { + var functionScopeDecl = this.getSomeInnermostFunctionScopeDecl(declPath); + if (functionScopeDecl) { + if (!nameSymbol || !this.isFromFunctionScope(nameSymbol, functionScopeDecl)) { + nameSymbol = this.cachedFunctionArgumentsSymbol(); + this.resolveDeclaredSymbol(this.cachedIArgumentsInterfaceType(), context); + } + } + } + + var aliasSymbol = null; + if (nameSymbol && nameSymbol.isAlias() && !isDeclarationASTOrDeclarationNameAST) { + aliasSymbol = nameSymbol; + if (!this.inTypeQuery(nameAST)) { + aliasSymbol.setIsUsedAsValue(); + } + + this.resolveDeclaredSymbol(nameSymbol, context); + + this.resolveDeclaredSymbol(aliasSymbol.assignedValue(), context); + this.resolveDeclaredSymbol(aliasSymbol.assignedContainer(), context); + + nameSymbol = aliasSymbol.getExportAssignedValueSymbol(); + if (!nameSymbol) { + aliasSymbol = null; + } + } + + if (!nameSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [nameAST.text()])); + return this.getNewErrorTypeSymbol(id); + } else if (this.checkNameAsPartOfInitializerExpressionForInstanceMemberVariable(nameAST, nameSymbol, context)) { + return this.getNewErrorTypeSymbol(id); + } + + var nameDeclaration = nameSymbol.getDeclarations()[0]; + var nameParentDecl = nameDeclaration.getParentDecl(); + if (nameParentDecl && (nameParentDecl.kind & 1032192 /* SomeFunction */) && (nameParentDecl.flags & 33554432 /* HasDefaultArgs */)) { + var enclosingFunctionAST = this.semanticInfoChain.getASTForDecl(nameParentDecl); + var currentParameterIndex = this.getCurrentParameterIndexForFunction(nameAST, enclosingFunctionAST); + + var parameterList = TypeScript.ASTHelpers.getParameterList(enclosingFunctionAST); + + if (currentParameterIndex >= 0) { + var matchingParameter; + if (parameterList) { + for (var i = 0; i <= currentParameterIndex; i++) { + var candidateParameter = parameterList.parameters.nonSeparatorAt(i); + if (candidateParameter && candidateParameter.identifier.valueText() === id) { + matchingParameter = candidateParameter; + break; + } + } + } + + if (!matchingParameter) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, [parameterList.parameters.nonSeparatorAt(currentParameterIndex).identifier.text(), nameAST.text()])); + return this.getNewErrorTypeSymbol(id); + } else if (matchingParameter === TypeScript.ASTHelpers.getEnclosingParameterForInitializer(nameAST)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Parameter_0_cannot_be_referenced_in_its_initializer, [parameterList.parameters.nonSeparatorAt(currentParameterIndex).identifier.text()])); + return this.getNewErrorTypeSymbol(id); + } + } + } + + if (aliasSymbol) { + this.semanticInfoChain.setAliasSymbolForAST(nameAST, aliasSymbol); + } + + return nameSymbol; + }; + + PullTypeResolver.prototype.getCurrentParameterIndexForFunction = function (parameter, funcDecl) { + var parameterList = TypeScript.ASTHelpers.getParameterList(funcDecl); + if (parameterList) { + while (parameter && parameter.parent) { + if (parameter.parent.parent === parameterList) { + return parameterList.parameters.nonSeparatorIndexOf(parameter); + } + + parameter = parameter.parent; + } + } + + return -1; + }; + + PullTypeResolver.prototype.resolveMemberAccessExpression = function (dottedNameAST, context) { + return this.resolveDottedNameExpression(dottedNameAST, dottedNameAST.expression, dottedNameAST.name, context); + }; + + PullTypeResolver.prototype.resolveDottedNameExpression = function (dottedNameAST, expression, name, context) { + var symbol = this.getSymbolForAST(dottedNameAST, context); + var foundCached = symbol !== null; + + if (!foundCached || this.canTypeCheckAST(dottedNameAST, context)) { + var canTypeCheckDottedNameAST = this.canTypeCheckAST(dottedNameAST, context); + if (canTypeCheckDottedNameAST) { + this.setTypeChecked(dottedNameAST, context); + } + + symbol = this.computeDottedNameExpression(expression, name, context, canTypeCheckDottedNameAST); + } + + this.resolveDeclaredSymbol(symbol, context); + + if (symbol && (symbol.type !== this.semanticInfoChain.anyTypeSymbol || symbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { + this.setSymbolForAST(dottedNameAST, symbol, context); + this.setSymbolForAST(name, symbol, context); + } + + return symbol; + }; + + PullTypeResolver.prototype.computeDottedNameExpression = function (expression, name, context, checkSuperPrivateAndStaticAccess) { + var rhsName = name.valueText(); + if (rhsName.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var lhs = this.resolveAST(expression, false, context); + return this.computeDottedNameExpressionFromLHS(lhs, expression, name, context, checkSuperPrivateAndStaticAccess); + }; + + PullTypeResolver.prototype.computeDottedNameExpressionFromLHS = function (lhs, expression, name, context, checkSuperPrivateAndStaticAccess) { + var rhsName = name.valueText(); + if (rhsName.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var lhsType = lhs.type; + + if (lhs.isAlias()) { + var lhsAlias = lhs; + if (!this.inTypeQuery(expression)) { + lhsAlias.setIsUsedAsValue(); + } + lhsType = lhsAlias.getExportAssignedTypeSymbol(); + } + + if (lhsType.isAlias()) { + lhsType = lhsType.getExportAssignedTypeSymbol(); + } + + if (!lhsType) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.Could_not_find_enclosing_symbol_for_dotted_name_0, [name.text()])); + return this.getNewErrorTypeSymbol(); + } + + if (!lhsType.isResolved) { + var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, context); + + if (potentiallySpecializedType !== lhsType) { + if (!lhs.isType()) { + context.setTypeInContext(lhs, potentiallySpecializedType); + } + + lhsType = potentiallySpecializedType; + } + } + + if (lhsType.isContainer() && !lhsType.isAlias() && !lhsType.isEnum()) { + var instanceSymbol = lhsType.getInstanceSymbol(); + + if (instanceSymbol) { + lhsType = instanceSymbol.type; + } + } + + var originalLhsTypeForErrorReporting = lhsType; + + lhsType = this.getApparentType(lhsType).widenedType(this, expression, context); + + if (this.isAnyOrEquivalent(lhsType)) { + return lhsType; + } + + var nameSymbol = this._getNamedPropertySymbolOfAugmentedType(rhsName, lhsType); + + if (!nameSymbol) { + if (lhsType.kind === 32 /* DynamicModule */) { + var container = lhsType; + var associatedInstance = container.getInstanceSymbol(); + + if (associatedInstance) { + var instanceType = associatedInstance.type; + + nameSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, instanceType); + } + } else { + var associatedType = lhsType.getAssociatedContainerType(); + + if (associatedType && !associatedType.isClass()) { + nameSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, associatedType); + } + } + + if (!nameSymbol) { + var enclosingDecl = this.getEnclosingDeclForAST(expression); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.The_property_0_does_not_exist_on_value_of_type_1, [name.text(), originalLhsTypeForErrorReporting.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + return this.getNewErrorTypeSymbol(rhsName); + } + } + + if (checkSuperPrivateAndStaticAccess) { + this.checkForSuperMemberAccess(expression, name, nameSymbol, context) || this.checkForPrivateMemberAccess(name, lhsType, nameSymbol, context); + } + + return nameSymbol; + }; + + PullTypeResolver.prototype.resolveTypeNameExpression = function (nameAST, context) { + var typeNameSymbol = this.getSymbolForAST(nameAST, context); + + if (!typeNameSymbol || !typeNameSymbol.isType() || this.canTypeCheckAST(nameAST, context)) { + if (this.canTypeCheckAST(nameAST, context)) { + this.setTypeChecked(nameAST, context); + } + typeNameSymbol = this.computeTypeNameExpression(nameAST, context); + this.setSymbolForAST(nameAST, typeNameSymbol, context); + } + + this.resolveDeclaredSymbol(typeNameSymbol, context); + + return typeNameSymbol; + }; + + PullTypeResolver.prototype.computeTypeNameExpression = function (nameAST, context) { + var id = nameAST.valueText(); + if (id.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var enclosingDecl = this.getEnclosingDeclForAST(nameAST); + + var declPath = enclosingDecl.getParentPath(); + + var onLeftOfDot = this.isLeftSideOfQualifiedName(nameAST); + + var kindToCheckFirst = onLeftOfDot ? 164 /* SomeContainer */ : 58728795 /* SomeType */; + var kindToCheckSecond = onLeftOfDot ? 58728795 /* SomeType */ : 164 /* SomeContainer */; + + var typeNameSymbol = this.getSymbolFromDeclPath(id, declPath, kindToCheckFirst); + + if (!typeNameSymbol) { + typeNameSymbol = this.getSymbolFromDeclPath(id, declPath, kindToCheckSecond); + } + + if (!typeNameSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [nameAST.text()])); + return this.getNewErrorTypeSymbol(id); + } + + var typeNameSymbolAlias = null; + if (typeNameSymbol.isAlias()) { + typeNameSymbolAlias = typeNameSymbol; + this.resolveDeclaredSymbol(typeNameSymbol, context); + + var aliasedType = typeNameSymbolAlias.getExportAssignedTypeSymbol(); + + this.resolveDeclaredSymbol(aliasedType, context); + } + + if (typeNameSymbol.isTypeParameter()) { + if (this.isInStaticMemberContext(enclosingDecl)) { + var parentDecl = typeNameSymbol.getDeclarations()[0].getParentDecl(); + + if (parentDecl.kind === 8 /* Class */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Static_members_cannot_reference_class_type_parameters)); + return this.getNewErrorTypeSymbol(); + } + } + } + + if (!typeNameSymbol.isGeneric() && (typeNameSymbol.isClass() || typeNameSymbol.isInterface())) { + typeNameSymbol = TypeScript.PullTypeReferenceSymbol.createTypeReference(typeNameSymbol); + } + + return typeNameSymbol; + }; + + PullTypeResolver.prototype.isInStaticMemberContext = function (decl) { + while (decl) { + if (TypeScript.hasFlag(decl.kind, 1032192 /* SomeFunction */ | 4096 /* Property */) && TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + return true; + } + + if (TypeScript.hasFlag(decl.kind, 164 /* SomeContainer */)) { + return false; + } + + decl = decl.getParentDecl(); + } + + return false; + }; + + PullTypeResolver.prototype.isLeftSideOfQualifiedName = function (ast) { + return ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.left === ast; + }; + + PullTypeResolver.prototype.resolveGenericTypeReference = function (genericTypeAST, context) { + var _this = this; + var genericTypeSymbol = this.resolveAST(genericTypeAST.name, false, context).type; + + if (genericTypeSymbol.isError()) { + return genericTypeSymbol; + } + + if (!genericTypeSymbol.inResolution && !genericTypeSymbol.isResolved) { + this.resolveDeclaredSymbol(genericTypeSymbol, context); + } + + if (genericTypeSymbol.isAlias()) { + if (this.inClassExtendsHeritageClause(genericTypeAST) && !this.inTypeArgumentList(genericTypeAST)) { + genericTypeSymbol.setIsUsedAsValue(); + } + genericTypeSymbol = genericTypeSymbol.getExportAssignedTypeSymbol(); + } + + var typeParameters = genericTypeSymbol.getTypeParameters(); + if (typeParameters.length === 0) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Type_0_does_not_have_type_parameters, [genericTypeSymbol.toString()])); + return this.getNewErrorTypeSymbol(); + } + + var typeArgs = []; + + if (genericTypeAST.typeArgumentList && genericTypeAST.typeArgumentList.typeArguments.nonSeparatorCount()) { + for (var i = 0; i < genericTypeAST.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { + typeArgs[i] = this.resolveTypeReference(genericTypeAST.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + + if (typeArgs[i].isError()) { + typeArgs[i] = this.semanticInfoChain.anyTypeSymbol; + } + } + } + + if (typeArgs.length && typeArgs.length !== typeParameters.length) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Generic_type_0_requires_1_type_argument_s, [genericTypeSymbol.toString(), genericTypeSymbol.getTypeParameters().length])); + return this.getNewErrorTypeSymbol(); + } + + if (!genericTypeSymbol.isResolved) { + var typeDecls = genericTypeSymbol.getDeclarations(); + var childDecls = null; + + for (var i = 0; i < typeDecls.length; i++) { + childDecls = typeDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + } + + var specializedSymbol = this.createInstantiatedType(genericTypeSymbol, typeArgs); + + var upperBound = null; + + typeParameters = specializedSymbol.getTypeParameters(); + + var typeConstraintSubstitutionMap = []; + + var instantiatedSubstitutionMap = specializedSymbol.getTypeParameterArgumentMap(); + + for (var i = 0; i < typeParameters.length; i++) { + typeConstraintSubstitutionMap[typeParameters[i].pullSymbolID] = typeParameters[i]; + } + + for (var id in instantiatedSubstitutionMap) { + typeConstraintSubstitutionMap[id] = instantiatedSubstitutionMap[id]; + } + + for (var iArg = 0; (iArg < typeArgs.length) && (iArg < typeParameters.length); iArg++) { + var typeArg = typeArgs[iArg]; + var typeParameter = typeParameters[iArg]; + var typeConstraint = typeParameter.getConstraint(); + + typeConstraintSubstitutionMap[typeParameter.pullSymbolID] = typeArg; + + if (typeConstraint) { + if (typeConstraint.isTypeParameter()) { + for (var j = 0; j < typeParameters.length && j < typeArgs.length; j++) { + if (typeParameters[j] === typeConstraint) { + typeConstraint = typeArgs[j]; + } + } + } else if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeConstraintSubstitutionMap); + } + + if (typeArg.isTypeParameter()) { + upperBound = typeArg.getConstraint(); + + if (upperBound) { + typeArg = upperBound; + } + } + + if (typeArg.inResolution || (typeArg.isTypeReference() && typeArg.referencedTypeSymbol.inResolution)) { + return specializedSymbol; + } + + if (context.canTypeCheckAST(genericTypeAST)) { + this.typeCheckCallBacks.push(function (context) { + if (!_this.sourceIsAssignableToTarget(typeArg, typeConstraint, genericTypeAST, context)) { + var enclosingSymbol = _this.getEnclosingSymbolForAST(genericTypeAST); + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [typeArg.toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameter.toString(enclosingSymbol, true)])); + } + }); + } + } + } + + return specializedSymbol; + }; + + PullTypeResolver.prototype.resolveQualifiedName = function (dottedNameAST, context) { + if (this.inTypeQuery(dottedNameAST)) { + return this.resolveDottedNameExpression(dottedNameAST, dottedNameAST.left, dottedNameAST.right, context).type; + } + + var symbol = this.getSymbolForAST(dottedNameAST, context); + if (!symbol || this.canTypeCheckAST(dottedNameAST, context)) { + var canTypeCheck = this.canTypeCheckAST(dottedNameAST, context); + if (canTypeCheck) { + this.setTypeChecked(dottedNameAST, context); + } + + symbol = this.computeQualifiedName(dottedNameAST, context); + this.setSymbolForAST(dottedNameAST, symbol, context); + } + + this.resolveDeclaredSymbol(symbol, context); + + return symbol; + }; + + PullTypeResolver.prototype.isLastNameOfModuleNameModuleReference = function (ast) { + return ast.kind() === 11 /* IdentifierName */ && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast && ast.parent.parent && ast.parent.parent.kind() === 246 /* ModuleNameModuleReference */; + }; + + PullTypeResolver.prototype.computeQualifiedName = function (dottedNameAST, context) { + var rhsName = dottedNameAST.right.valueText(); + if (rhsName.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var enclosingDecl = this.getEnclosingDeclForAST(dottedNameAST); + var lhs = this.resolveAST(dottedNameAST.left, false, context); + + var lhsType = lhs.isAlias() ? lhs.getExportAssignedContainerSymbol() : lhs.type; + + if (this.inClassExtendsHeritageClause(dottedNameAST) && !this.inTypeArgumentList(dottedNameAST)) { + if (lhs.isAlias()) { + lhs.setIsUsedAsValue(); + } + } + + if (!lhsType) { + return this.getNewErrorTypeSymbol(); + } + + if (this.isAnyOrEquivalent(lhsType)) { + return lhsType; + } + + var onLeftOfDot = this.isLeftSideOfQualifiedName(dottedNameAST); + var isNameOfModule = dottedNameAST.parent.kind() === 130 /* ModuleDeclaration */ && dottedNameAST.parent.name === dottedNameAST; + + var memberKind = (onLeftOfDot || isNameOfModule) ? 164 /* SomeContainer */ : 58728795 /* SomeType */; + + var childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, lhsType); + + if (!childTypeSymbol && !isNameOfModule && this.isLastNameOfModuleNameModuleReference(dottedNameAST.right)) { + childTypeSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, lhsType); + } + + if (!childTypeSymbol && lhsType.isContainer()) { + var exportedContainer = lhsType.getExportAssignedContainerSymbol(); + + if (exportedContainer) { + childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, exportedContainer); + } + } + + if (!childTypeSymbol && enclosingDecl) { + var parentDecl = enclosingDecl; + + while (parentDecl) { + if (parentDecl.kind & 164 /* SomeContainer */) { + break; + } + + parentDecl = parentDecl.getParentDecl(); + } + + if (parentDecl) { + var enclosingSymbolType = parentDecl.getSymbol().type; + + if (enclosingSymbolType === lhsType) { + childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, lhsType); + } + } + } + + if (!childTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(dottedNameAST.right, TypeScript.DiagnosticCode.The_property_0_does_not_exist_on_value_of_type_1, [dottedNameAST.right.text(), lhsType.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + return this.getNewErrorTypeSymbol(rhsName); + } + + return childTypeSymbol; + }; + + PullTypeResolver.prototype.shouldContextuallyTypeAnyFunctionExpression = function (functionExpressionAST, typeParameters, parameters, returnTypeAnnotation, context) { + if (typeParameters && typeParameters.typeParameters.nonSeparatorCount() > 0) { + return false; + } + + if (returnTypeAnnotation) { + return false; + } + + if (parameters) { + for (var i = 0, n = parameters.length; i < n; i++) { + if (parameters.typeAt(i)) { + return false; + } + } + } + + var contextualFunctionTypeSymbol = context.getContextualType(); + + if (contextualFunctionTypeSymbol) { + this.resolveDeclaredSymbol(contextualFunctionTypeSymbol, context); + var callSignatures = contextualFunctionTypeSymbol.getCallSignatures(); + var exactlyOneCallSignature = callSignatures && callSignatures.length === 1; + if (!exactlyOneCallSignature) { + return false; + } + + var callSignatureIsGeneric = callSignatures[0].getTypeParameters().length > 0; + return !callSignatureIsGeneric; + } + + return false; + }; + + PullTypeResolver.prototype.resolveAnyFunctionExpression = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context) { + var funcDeclSymbol = null; + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + TypeScript.Debug.assert(functionDecl); + + if (functionDecl && functionDecl.hasSymbol()) { + funcDeclSymbol = functionDecl.getSymbol(); + if (funcDeclSymbol.isResolved || funcDeclSymbol.inResolution) { + return funcDeclSymbol; + } + } + + funcDeclSymbol = functionDecl.getSymbol(); + TypeScript.Debug.assert(funcDeclSymbol); + + var funcDeclType = funcDeclSymbol.type; + var signature = funcDeclType.getCallSignatures()[0]; + funcDeclSymbol.startResolving(); + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + var assigningFunctionSignature = null; + if (isContextuallyTyped && this.shouldContextuallyTypeAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, context)) { + assigningFunctionSignature = context.getContextualType().getCallSignatures()[0]; + } + + this.resolveAnyFunctionExpressionParameters(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context); + + if (returnTypeAnnotation) { + signature.returnType = this.resolveTypeReference(returnTypeAnnotation, context); + } else { + if (assigningFunctionSignature) { + var returnType = assigningFunctionSignature.returnType; + + if (returnType) { + context.propagateContextualType(returnType); + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, bodyExpression, signature, true, functionDecl, context); + context.popAnyContextualType(); + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + + if (this.compilationSettings.noImplicitAny()) { + var functionExpressionName = functionDecl.getFunctionExpressionName(); + + if (functionExpressionName != "") { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type, [functionExpressionName])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + } + } else { + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, bodyExpression, signature, false, functionDecl, context); + } + } + + context.setTypeInContext(funcDeclSymbol, funcDeclType); + funcDeclSymbol.setResolved(); + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context); + } + + return funcDeclSymbol; + }; + + PullTypeResolver.prototype.resolveAnyFunctionExpressionParameters = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context) { + if (!parameters) { + return; + } + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var contextParams = []; + + var assigningFunctionSignature = null; + if (isContextuallyTyped && this.shouldContextuallyTypeAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, context)) { + assigningFunctionSignature = context.getContextualType().getCallSignatures()[0]; + } + + if (assigningFunctionSignature) { + contextParams = assigningFunctionSignature.parameters; + } + + var contextualParametersCount = contextParams.length; + for (var i = 0, n = parameters.length; i < n; i++) { + var actualParameterIsVarArgParameter = (i === (n - 1)) && parameters.lastParameterIsRest(); + var correspondingContextualParameter = null; + var contextualParameterType = null; + + if (i < contextualParametersCount) { + correspondingContextualParameter = contextParams[i]; + } else if (contextualParametersCount && contextParams[contextualParametersCount - 1].isVarArg) { + correspondingContextualParameter = contextParams[contextualParametersCount - 1]; + } + + if (correspondingContextualParameter) { + if (correspondingContextualParameter.isVarArg === actualParameterIsVarArgParameter) { + contextualParameterType = correspondingContextualParameter.type; + } else if (correspondingContextualParameter.isVarArg) { + contextualParameterType = correspondingContextualParameter.type.getElementType(); + } + } + + this.resolveFunctionExpressionParameter(parameters.astAt(i), parameters.identifierAt(i), parameters.typeAt(i), parameters.initializerAt(i), contextualParameterType, functionDecl, context); + } + }; + + PullTypeResolver.prototype.typeCheckSimpleArrowFunctionExpression = function (arrowFunction, isContextuallyTyped, context) { + return this.typeCheckAnyFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromIdentifier(arrowFunction.identifier), null, arrowFunction.block, arrowFunction.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckParenthesizedArrowFunctionExpression = function (arrowFunction, isContextuallyTyped, context) { + return this.typeCheckAnyFunctionExpression(arrowFunction, arrowFunction.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), TypeScript.ASTHelpers.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckAnyFunctionExpression = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcDeclSymbol = functionDecl.getSymbol(); + var funcDeclType = funcDeclSymbol.type; + var signature = funcDeclType.getCallSignatures()[0]; + var returnTypeSymbol = signature.returnType; + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + this.resolveAnyFunctionExpressionParameters(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context); + + context.pushNewContextualType(null); + if (block) { + this.resolveAST(block, false, context); + } else { + var bodyExpressionType = this.resolveReturnExpression(bodyExpression, functionDecl, context); + this.typeCheckReturnExpression(bodyExpression, bodyExpressionType, functionDecl, context); + } + + context.popAnyContextualType(); + + this.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement(functionDecl, returnTypeAnnotation, returnTypeSymbol, block, context); + + this.validateVariableDeclarationGroups(functionDecl, context); + + this.typeCheckCallBacks.push(function (context) { + _this.typeCheckFunctionOverloads(funcDeclAST, context); + }); + }; + + PullTypeResolver.prototype.resolveThisExpression = function (thisExpression, context) { + var enclosingDecl = this.getEnclosingDeclForAST(thisExpression); + var thisTypeSymbol = this.getContextualClassSymbolForEnclosingDecl(thisExpression, enclosingDecl) || this.semanticInfoChain.anyTypeSymbol; + + if (this.canTypeCheckAST(thisExpression, context)) { + this.typeCheckThisExpression(thisExpression, context, enclosingDecl); + } + + return thisTypeSymbol; + }; + + PullTypeResolver.prototype.inTypeArgumentList = function (ast) { + var previous = null; + var current = ast; + + while (current) { + switch (current.kind()) { + case 126 /* GenericType */: + var genericType = current; + if (genericType.typeArgumentList === previous) { + return true; + } + break; + + case 226 /* ArgumentList */: + var argumentList = current; + return argumentList.typeArgumentList === previous; + } + + previous = current; + current = current.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inClassExtendsHeritageClause = function (ast) { + while (ast) { + switch (ast.kind()) { + case 230 /* ExtendsHeritageClause */: + var heritageClause = ast; + + return heritageClause.parent.parent.kind() === 131 /* ClassDeclaration */; + + case 137 /* ConstructorDeclaration */: + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inTypeQuery = function (ast) { + while (ast) { + switch (ast.kind()) { + case 127 /* TypeQuery */: + return true; + case 129 /* FunctionDeclaration */: + case 213 /* InvocationExpression */: + case 137 /* ConstructorDeclaration */: + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inArgumentListOfSuperInvocation = function (ast) { + var previous = null; + var current = ast; + while (current) { + switch (current.kind()) { + case 213 /* InvocationExpression */: + var invocationExpression = current; + if (previous === invocationExpression.argumentList && invocationExpression.expression.kind() === 50 /* SuperKeyword */) { + return true; + } + break; + + case 137 /* ConstructorDeclaration */: + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + previous = current; + current = current.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inConstructorParameterList = function (ast) { + var previous = null; + var current = ast; + while (current) { + switch (current.kind()) { + case 142 /* CallSignature */: + var callSignature = current; + if (previous === callSignature.parameterList && callSignature.parent.kind() === 137 /* ConstructorDeclaration */) { + return true; + } + + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + previous = current; + current = current.parent; + } + + return false; + }; + PullTypeResolver.prototype.isFunctionAccessorOrNonArrowFunctionExpression = function (decl) { + if (decl.kind === 262144 /* GetAccessor */ || decl.kind === 524288 /* SetAccessor */) { + return true; + } + + return this.isFunctionOrNonArrowFunctionExpression(decl); + }; + + PullTypeResolver.prototype.isFunctionOrNonArrowFunctionExpression = function (decl) { + if (decl.kind === 16384 /* Function */) { + return true; + } else if (decl.kind === 131072 /* FunctionExpression */ && !TypeScript.hasFlag(decl.flags, 8192 /* ArrowFunction */)) { + return true; + } + + return false; + }; + + PullTypeResolver.prototype.typeCheckThisExpression = function (thisExpression, context, enclosingDecl) { + this.checkForThisCaptureInArrowFunction(thisExpression); + + if (this.inConstructorParameterList(thisExpression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_constructor_arguments)); + return; + } + + for (var currentDecl = enclosingDecl; currentDecl !== null; currentDecl = currentDecl.getParentDecl()) { + if (this.isFunctionAccessorOrNonArrowFunctionExpression(currentDecl)) { + return; + } else if (currentDecl.kind === 4 /* Container */ || currentDecl.kind === 32 /* DynamicModule */) { + if (currentDecl.getParentDecl() === null) { + return; + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_within_module_bodies)); + return; + } + } else if (currentDecl.kind === 64 /* Enum */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_current_location)); + return; + } else if (currentDecl.kind === 32768 /* ConstructorMethod */) { + if (this.inArgumentListOfSuperInvocation(thisExpression) && this.superCallMustBeFirstStatementInConstructor(currentDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_current_location)); + } + + return; + } else if (currentDecl.kind === 8 /* Class */) { + if (this.inStaticMemberVariableDeclaration(thisExpression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_static_initializers_in_a_class_body)); + } + + return; + } + } + }; + + PullTypeResolver.prototype.getContextualClassSymbolForEnclosingDecl = function (ast, enclosingDecl) { + var declPath = enclosingDecl.getParentPath(); + + if (declPath.length) { + var isStaticContext = false; + + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.kind; + var declFlags = decl.flags; + + if (declFlags & 16 /* Static */) { + isStaticContext = true; + } else if (declKind === 131072 /* FunctionExpression */ && !TypeScript.hasFlag(declFlags, 8192 /* ArrowFunction */)) { + return null; + } else if (declKind === 16384 /* Function */) { + return null; + } else if (declKind === 8 /* Class */) { + if (this.inStaticMemberVariableDeclaration(ast)) { + return this.getNewErrorTypeSymbol(); + } else { + var classSymbol = decl.getSymbol(); + if (isStaticContext) { + var constructorSymbol = classSymbol.getConstructorMethod(); + return constructorSymbol.type; + } else { + return classSymbol; + } + } + } + } + } + + return null; + }; + + PullTypeResolver.prototype.inStaticMemberVariableDeclaration = function (ast) { + while (ast) { + if (ast.kind() === 136 /* MemberVariableDeclaration */ && TypeScript.hasModifier(ast.modifiers, 16 /* Static */)) { + return true; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.resolveSuperExpression = function (ast, context) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + var superType = this.semanticInfoChain.anyTypeSymbol; + + var classSymbol = this.getContextualClassSymbolForEnclosingDecl(ast, enclosingDecl); + + if (classSymbol) { + this.resolveDeclaredSymbol(classSymbol, context); + + var parents = classSymbol.getExtendedTypes(); + + if (parents.length) { + superType = parents[0]; + } + } + + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckSuperExpression(ast, context, enclosingDecl); + } + + return superType; + }; + + PullTypeResolver.prototype.typeCheckSuperExpression = function (ast, context, enclosingDecl) { + this.setTypeChecked(ast, context); + + this.checkForThisCaptureInArrowFunction(ast); + + var isSuperCall = ast.parent.kind() === 213 /* InvocationExpression */; + var isSuperPropertyAccess = ast.parent.kind() === 212 /* MemberAccessExpression */; + TypeScript.Debug.assert(isSuperCall || isSuperPropertyAccess); + + if (isSuperPropertyAccess) { + for (var currentDecl = enclosingDecl; currentDecl !== null; currentDecl = currentDecl.getParentDecl()) { + if (this.isFunctionOrNonArrowFunctionExpression(currentDecl)) { + break; + } else if (currentDecl.kind === 8 /* Class */) { + if (!this.enclosingClassIsDerived(currentDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_non_derived_classes)); + return; + } else if (this.inConstructorParameterList(ast)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_constructor_arguments)); + return; + } else if (this.inStaticMemberVariableDeclaration(ast)) { + break; + } + + return; + } + } + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class)); + return; + } else { + if (enclosingDecl.kind === 32768 /* ConstructorMethod */) { + var classDecl = enclosingDecl.getParentDecl(); + + if (!this.enclosingClassIsDerived(classDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_non_derived_classes)); + return; + } else if (this.inConstructorParameterList(ast)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_constructor_arguments)); + return; + } + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors)); + } + } + }; + + PullTypeResolver.prototype.resolveSimplePropertyAssignment = function (propertyAssignment, isContextuallyTyped, context) { + return this.resolveAST(propertyAssignment.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveFunctionPropertyAssignment = function (funcProp, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcProp), funcProp.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckFunctionPropertyAssignment = function (funcProp, isContextuallyTyped, context) { + this.typeCheckAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcProp), funcProp.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveObjectLiteralExpression = function (expressionAST, isContextuallyTyped, context, additionalResults) { + var symbol = this.getSymbolForAST(expressionAST, context); + var hasResolvedSymbol = symbol && symbol.isResolved; + + if (!hasResolvedSymbol || additionalResults || this.canTypeCheckAST(expressionAST, context)) { + if (this.canTypeCheckAST(expressionAST, context)) { + this.setTypeChecked(expressionAST, context); + } + symbol = this.computeObjectLiteralExpression(expressionAST, isContextuallyTyped, context, additionalResults); + this.setSymbolForAST(expressionAST, symbol, context); + } + + return symbol; + }; + + PullTypeResolver.prototype.bindObjectLiteralMembers = function (objectLiteralDeclaration, objectLiteralTypeSymbol, objectLiteralMembers, isUsingExistingSymbol, pullTypeContext) { + var boundMemberSymbols = []; + var memberSymbol; + for (var i = 0, len = objectLiteralMembers.nonSeparatorCount(); i < len; i++) { + var propertyAssignment = objectLiteralMembers.nonSeparatorAt(i); + + var id = this.getPropertyAssignmentName(propertyAssignment); + var assignmentText = getPropertyAssignmentNameTextFromIdentifier(id); + + var isAccessor = propertyAssignment.kind() === 139 /* GetAccessor */ || propertyAssignment.kind() === 140 /* SetAccessor */; + var decl = this.semanticInfoChain.getDeclForAST(propertyAssignment); + TypeScript.Debug.assert(decl); + + if (propertyAssignment.kind() === 240 /* SimplePropertyAssignment */) { + if (!isUsingExistingSymbol) { + memberSymbol = new TypeScript.PullSymbol(assignmentText.memberName, 4096 /* Property */); + memberSymbol.addDeclaration(decl); + decl.setSymbol(memberSymbol); + } else { + memberSymbol = decl.getSymbol(); + } + } else if (propertyAssignment.kind() === 241 /* FunctionPropertyAssignment */) { + memberSymbol = decl.getSymbol(); + } else { + TypeScript.Debug.assert(isAccessor); + memberSymbol = decl.getSymbol(); + } + + if (!isUsingExistingSymbol && !isAccessor) { + var existingMember = objectLiteralTypeSymbol.findMember(memberSymbol.name, true); + if (existingMember) { + pullTypeContext.postDiagnostic(this.semanticInfoChain.duplicateIdentifierDiagnosticFromAST(propertyAssignment, assignmentText.actualText, existingMember.getDeclarations()[0].ast())); + } + + objectLiteralTypeSymbol.addMember(memberSymbol); + } + + boundMemberSymbols.push(memberSymbol); + } + + return boundMemberSymbols; + }; + + PullTypeResolver.prototype.resolveObjectLiteralMembers = function (objectLiteralDeclaration, objectLiteralTypeSymbol, objectLiteralContextualType, objectLiteralMembers, stringIndexerSignature, numericIndexerSignature, allMemberTypes, allNumericMemberTypes, boundMemberSymbols, isUsingExistingSymbol, pullTypeContext, additionalResults) { + for (var i = 0, len = objectLiteralMembers.nonSeparatorCount(); i < len; i++) { + var propertyAssignment = objectLiteralMembers.nonSeparatorAt(i); + + var acceptedContextualType = false; + var assigningSymbol = null; + + var id = this.getPropertyAssignmentName(propertyAssignment); + var memberSymbol = boundMemberSymbols[i]; + var contextualMemberType = null; + + if (objectLiteralContextualType) { + assigningSymbol = this.getNamedPropertySymbol(memberSymbol.name, 68147712 /* SomeValue */, objectLiteralContextualType); + + if (!assigningSymbol) { + if (numericIndexerSignature && TypeScript.PullHelpers.isNameNumeric(memberSymbol.name)) { + assigningSymbol = numericIndexerSignature; + } else if (stringIndexerSignature) { + assigningSymbol = stringIndexerSignature; + } + } + + if (assigningSymbol) { + this.resolveDeclaredSymbol(assigningSymbol, pullTypeContext); + + contextualMemberType = assigningSymbol.kind === 4194304 /* IndexSignature */ ? assigningSymbol.returnType : assigningSymbol.type; + pullTypeContext.propagateContextualType(contextualMemberType); + + acceptedContextualType = true; + + if (additionalResults) { + additionalResults.membersContextTypeSymbols[i] = contextualMemberType; + } + } + } + + var memberSymbolType = this.resolveAST(propertyAssignment, contextualMemberType !== null, pullTypeContext).type; + + if (memberSymbolType) { + if (memberSymbolType.isGeneric()) { + objectLiteralTypeSymbol.setHasGenericMember(); + } + + if (stringIndexerSignature) { + allMemberTypes.push(memberSymbolType); + } + if (numericIndexerSignature && TypeScript.PullHelpers.isNameNumeric(memberSymbol.name)) { + allNumericMemberTypes.push(memberSymbolType); + } + } + + if (acceptedContextualType) { + pullTypeContext.popAnyContextualType(); + } + + var isAccessor = propertyAssignment.kind() === 140 /* SetAccessor */ || propertyAssignment.kind() === 139 /* GetAccessor */; + if (!memberSymbol.isResolved) { + if (isAccessor) { + this.setSymbolForAST(id, memberSymbolType, pullTypeContext); + } else { + pullTypeContext.setTypeInContext(memberSymbol, memberSymbolType); + memberSymbol.setResolved(); + + this.setSymbolForAST(id, memberSymbol, pullTypeContext); + } + } + } + }; + + PullTypeResolver.prototype.computeObjectLiteralExpression = function (objectLitAST, isContextuallyTyped, context, additionalResults) { + var objectLitDecl = this.semanticInfoChain.getDeclForAST(objectLitAST); + TypeScript.Debug.assert(objectLitDecl); + + var typeSymbol = this.getSymbolForAST(objectLitAST, context); + var isUsingExistingSymbol = !!typeSymbol; + + if (!typeSymbol) { + typeSymbol = new TypeScript.PullTypeSymbol("", 256 /* ObjectLiteral */); + typeSymbol.addDeclaration(objectLitDecl); + this.setSymbolForAST(objectLitAST, typeSymbol, context); + objectLitDecl.setSymbol(typeSymbol); + } + + var propertyAssignments = objectLitAST.propertyAssignments; + var contextualType = null; + + if (isContextuallyTyped) { + contextualType = context.getContextualType(); + this.resolveDeclaredSymbol(contextualType, context); + } + + var stringIndexerSignature = null; + var numericIndexerSignature = null; + var allMemberTypes = null; + var allNumericMemberTypes = null; + + if (contextualType) { + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(contextualType, context); + + stringIndexerSignature = indexSignatures.stringSignature; + numericIndexerSignature = indexSignatures.numericSignature; + + var inInferentialTyping = context.isInferentiallyTyping(); + if (stringIndexerSignature) { + allMemberTypes = inInferentialTyping ? [] : [stringIndexerSignature.returnType]; + } + + if (numericIndexerSignature) { + allNumericMemberTypes = inInferentialTyping ? [] : [numericIndexerSignature.returnType]; + } + } + + if (propertyAssignments) { + if (additionalResults) { + additionalResults.membersContextTypeSymbols = []; + } + + var boundMemberSymbols = this.bindObjectLiteralMembers(objectLitDecl, typeSymbol, propertyAssignments, isUsingExistingSymbol, context); + + this.resolveObjectLiteralMembers(objectLitDecl, typeSymbol, contextualType, propertyAssignments, stringIndexerSignature, numericIndexerSignature, allMemberTypes, allNumericMemberTypes, boundMemberSymbols, isUsingExistingSymbol, context, additionalResults); + + if (!isUsingExistingSymbol) { + this.stampObjectLiteralWithIndexSignature(typeSymbol, allMemberTypes, stringIndexerSignature, context); + this.stampObjectLiteralWithIndexSignature(typeSymbol, allNumericMemberTypes, numericIndexerSignature, context); + } + } + + typeSymbol.setResolved(); + return typeSymbol; + }; + + PullTypeResolver.prototype.getPropertyAssignmentName = function (propertyAssignment) { + if (propertyAssignment.kind() === 240 /* SimplePropertyAssignment */) { + return propertyAssignment.propertyName; + } else if (propertyAssignment.kind() === 241 /* FunctionPropertyAssignment */) { + return propertyAssignment.propertyName; + } else if (propertyAssignment.kind() === 139 /* GetAccessor */) { + return propertyAssignment.propertyName; + } else if (propertyAssignment.kind() === 140 /* SetAccessor */) { + return propertyAssignment.propertyName; + } else { + TypeScript.Debug.assert(false); + } + }; + + PullTypeResolver.prototype.stampObjectLiteralWithIndexSignature = function (objectLiteralSymbol, indexerTypeCandidates, contextualIndexSignature, context) { + if (contextualIndexSignature) { + var typeCollection = { + getLength: function () { + return indexerTypeCandidates.length; + }, + getTypeAtIndex: function (index) { + return indexerTypeCandidates[index]; + } + }; + var decl = objectLiteralSymbol.getDeclarations()[0]; + var indexerReturnType = this.findBestCommonType(typeCollection, context).widenedType(this, null, context); + if (indexerReturnType === contextualIndexSignature.returnType) { + objectLiteralSymbol.addIndexSignature(contextualIndexSignature); + } else { + this.semanticInfoChain.addSyntheticIndexSignature(decl, objectLiteralSymbol, this.getASTForDecl(decl), contextualIndexSignature.parameters[0].name, contextualIndexSignature.parameters[0].type, indexerReturnType); + } + } + }; + + PullTypeResolver.prototype.resolveArrayLiteralExpression = function (arrayLit, isContextuallyTyped, context) { + var symbol = this.getSymbolForAST(arrayLit, context); + if (!symbol || this.canTypeCheckAST(arrayLit, context)) { + if (this.canTypeCheckAST(arrayLit, context)) { + this.setTypeChecked(arrayLit, context); + } + symbol = this.computeArrayLiteralExpressionSymbol(arrayLit, isContextuallyTyped, context); + this.setSymbolForAST(arrayLit, symbol, context); + } + + return symbol; + }; + + PullTypeResolver.prototype.computeArrayLiteralExpressionSymbol = function (arrayLit, isContextuallyTyped, context) { + var elements = arrayLit.expressions; + var elementType = null; + var elementTypes = []; + var comparisonInfo = new TypeComparisonInfo(); + var contextualElementType = null; + comparisonInfo.onlyCaptureFirstError = true; + + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + + this.resolveDeclaredSymbol(contextualType, context); + + if (contextualType) { + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(contextualType, context); + if (indexSignatures.numericSignature) { + contextualElementType = indexSignatures.numericSignature.returnType; + } + } + } + + if (elements) { + if (contextualElementType) { + context.propagateContextualType(contextualElementType); + } + + for (var i = 0, n = elements.nonSeparatorCount(); i < n; i++) { + elementTypes.push(this.resolveAST(elements.nonSeparatorAt(i), contextualElementType !== null, context).type); + } + + if (contextualElementType) { + context.popAnyContextualType(); + } + } + + if (elementTypes.length) { + elementType = elementTypes[0]; + } + var collection; + + if (contextualElementType && !context.isInferentiallyTyping()) { + if (!elementType) { + elementType = contextualElementType; + } + + collection = { + getLength: function () { + return elements.nonSeparatorCount() + 1; + }, + getTypeAtIndex: function (index) { + return index === 0 ? contextualElementType : elementTypes[index - 1]; + } + }; + } else { + collection = { + getLength: function () { + return elements.nonSeparatorCount(); + }, + getTypeAtIndex: function (index) { + return elementTypes[index]; + } + }; + } + + elementType = elementType ? this.findBestCommonType(collection, context, comparisonInfo) : elementType; + + if (!elementType) { + elementType = this.semanticInfoChain.undefinedTypeSymbol; + } + + return this.getArrayType(elementType); + }; + + PullTypeResolver.prototype.resolveElementAccessExpression = function (callEx, context) { + var symbolAndDiagnostic = this.computeElementAccessExpressionSymbolAndDiagnostic(callEx, context); + + if (this.canTypeCheckAST(callEx, context)) { + this.typeCheckElementAccessExpression(callEx, context, symbolAndDiagnostic); + } + + return symbolAndDiagnostic.symbol; + }; + + PullTypeResolver.prototype.typeCheckElementAccessExpression = function (callEx, context, symbolAndDiagnostic) { + this.setTypeChecked(callEx, context); + context.postDiagnostic(symbolAndDiagnostic.diagnostic); + }; + + PullTypeResolver.prototype.computeElementAccessExpressionSymbolAndDiagnostic = function (callEx, context) { + var targetSymbol = this.resolveAST(callEx.expression, false, context); + var indexType = this.resolveAST(callEx.argumentExpression, false, context).type; + + var targetTypeSymbol = targetSymbol.type; + + targetTypeSymbol = this.getApparentType(targetTypeSymbol); + + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + return { symbol: targetTypeSymbol }; + } + + var elementType = targetTypeSymbol.getElementType(); + + var isNumberIndex = indexType === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(indexType); + + if (elementType && isNumberIndex) { + return { symbol: elementType }; + } + + if (callEx.argumentExpression.kind() === 14 /* StringLiteral */ || callEx.argumentExpression.kind() === 13 /* NumericLiteral */) { + var memberName = callEx.argumentExpression.kind() === 14 /* StringLiteral */ ? TypeScript.stripStartAndEndQuotes(callEx.argumentExpression.text()) : callEx.argumentExpression.valueText(); + + var member = this._getNamedPropertySymbolOfAugmentedType(memberName, targetTypeSymbol); + + if (member) { + this.resolveDeclaredSymbol(member, context); + + return { symbol: member.type }; + } + } + + var signatures = this.getBothKindsOfIndexSignaturesIncludingAugmentedType(targetTypeSymbol, context); + + var stringSignature = signatures.stringSignature; + var numberSignature = signatures.numericSignature; + + if (numberSignature && (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol)) { + return { symbol: numberSignature.returnType || this.semanticInfoChain.anyTypeSymbol }; + } else if (stringSignature && (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol)) { + return { symbol: stringSignature.returnType || this.semanticInfoChain.anyTypeSymbol }; + } else if (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol) { + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(callEx.argumentExpression, TypeScript.DiagnosticCode.Index_signature_of_object_type_implicitly_has_an_any_type)); + } + return { symbol: this.semanticInfoChain.anyTypeSymbol }; + } else { + return { + symbol: this.getNewErrorTypeSymbol(), + diagnostic: this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.Value_of_type_0_is_not_indexable_by_type_1, [targetTypeSymbol.toString(), indexType.toString()]) + }; + } + }; + + PullTypeResolver.prototype.getBothKindsOfIndexSignaturesIncludingAugmentedType = function (enclosingType, context) { + return this._getBothKindsOfIndexSignatures(enclosingType, context, true); + }; + + PullTypeResolver.prototype.getBothKindsOfIndexSignaturesExcludingAugmentedType = function (enclosingType, context) { + return this._getBothKindsOfIndexSignatures(enclosingType, context, false); + }; + + PullTypeResolver.prototype._getBothKindsOfIndexSignatures = function (enclosingType, context, includeAugmentedType) { + var signatures = includeAugmentedType ? enclosingType.getIndexSignaturesOfAugmentedType(this, this.cachedFunctionInterfaceType(), this.cachedObjectInterfaceType()) : enclosingType.getIndexSignatures(); + + var stringSignature = null; + var numberSignature = null; + var signature = null; + var paramSymbols; + var paramType; + + for (var i = 0; i < signatures.length; i++) { + if (stringSignature && numberSignature) { + break; + } + + signature = signatures[i]; + if (!signature.isResolved) { + this.resolveDeclaredSymbol(signature, context); + } + + paramSymbols = signature.parameters; + + if (paramSymbols.length) { + paramType = paramSymbols[0].type; + + if (!stringSignature && paramType === this.semanticInfoChain.stringTypeSymbol) { + stringSignature = signature; + continue; + } else if (!numberSignature && paramType === this.semanticInfoChain.numberTypeSymbol) { + numberSignature = signature; + continue; + } + } + } + + return { + numericSignature: numberSignature, + stringSignature: stringSignature + }; + }; + + PullTypeResolver.prototype._addUnhiddenSignaturesFromBaseType = function (derivedTypeSignatures, baseTypeSignatures, signaturesBeingAggregated) { + var _this = this; + if (!derivedTypeSignatures) { + signaturesBeingAggregated.push.apply(signaturesBeingAggregated, baseTypeSignatures); + return; + } + + var context = new TypeScript.PullTypeResolutionContext(this); + for (var i = 0; i < baseTypeSignatures.length; i++) { + var baseSignature = baseTypeSignatures[i]; + + var signatureIsHidden = TypeScript.ArrayUtilities.any(derivedTypeSignatures, function (sig) { + return _this.signaturesAreIdenticalWithNewEnclosingTypes(baseSignature, sig, context, false); + }); + + if (!signatureIsHidden) { + signaturesBeingAggregated.push(baseSignature); + } + } + }; + + PullTypeResolver.prototype.resolveBinaryAdditionOperation = function (binaryExpression, context) { + var lhsExpression = this.resolveAST(binaryExpression.left, false, context); + var lhsType = lhsExpression.type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + if (TypeScript.PullHelpers.symbolIsEnum(lhsType)) { + lhsType = this.semanticInfoChain.numberTypeSymbol; + } + + if (TypeScript.PullHelpers.symbolIsEnum(rhsType)) { + rhsType = this.semanticInfoChain.numberTypeSymbol; + } + + var isLhsTypeNullOrUndefined = lhsType === this.semanticInfoChain.nullTypeSymbol || lhsType === this.semanticInfoChain.undefinedTypeSymbol; + var isRhsTypeNullOrUndefined = rhsType === this.semanticInfoChain.nullTypeSymbol || rhsType === this.semanticInfoChain.undefinedTypeSymbol; + + if (isLhsTypeNullOrUndefined) { + if (isRhsTypeNullOrUndefined) { + lhsType = rhsType = this.semanticInfoChain.anyTypeSymbol; + } else { + lhsType = rhsType; + } + } else if (isRhsTypeNullOrUndefined) { + rhsType = lhsType; + } + + var exprType = null; + + if (lhsType === this.semanticInfoChain.stringTypeSymbol || rhsType === this.semanticInfoChain.stringTypeSymbol) { + exprType = this.semanticInfoChain.stringTypeSymbol; + } else if (this.isAnyOrEquivalent(lhsType) || this.isAnyOrEquivalent(rhsType)) { + exprType = this.semanticInfoChain.anyTypeSymbol; + } else if (rhsType === this.semanticInfoChain.numberTypeSymbol && lhsType === this.semanticInfoChain.numberTypeSymbol) { + exprType = this.semanticInfoChain.numberTypeSymbol; + } + + if (this.canTypeCheckAST(binaryExpression, context)) { + this.setTypeChecked(binaryExpression, context); + + if (exprType) { + if (binaryExpression.kind() === 175 /* AddAssignmentExpression */) { + if (!this.isReference(binaryExpression.left, lhsExpression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_left_hand_side_of_assignment_expression)); + } + + this.checkAssignability(binaryExpression.left, exprType, lhsType, context); + } + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_expression_types_not_known_to_support_the_addition_operator)); + } + } + + if (!exprType) { + exprType = this.semanticInfoChain.anyTypeSymbol; + } + + return exprType; + }; + + PullTypeResolver.prototype.bestCommonTypeOfTwoTypes = function (type1, type2, context) { + return this.findBestCommonType({ + getLength: function () { + return 2; + }, + getTypeAtIndex: function (index) { + switch (index) { + case 0: + return type1; + case 1: + return type2; + } + } + }, context); + }; + + PullTypeResolver.prototype.bestCommonTypeOfThreeTypes = function (type1, type2, type3, context) { + return this.findBestCommonType({ + getLength: function () { + return 3; + }, + getTypeAtIndex: function (index) { + switch (index) { + case 0: + return type1; + case 1: + return type2; + case 2: + return type3; + } + } + }, context); + }; + + PullTypeResolver.prototype.resolveLogicalOrExpression = function (binex, isContextuallyTyped, context) { + if (this.canTypeCheckAST(binex, context)) { + this.setTypeChecked(binex, context); + } + + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + var leftType = this.resolveAST(binex.left, isContextuallyTyped, context).type; + var rightType = this.resolveAST(binex.right, isContextuallyTyped, context).type; + + return context.isInferentiallyTyping() ? this.bestCommonTypeOfTwoTypes(leftType, rightType, context) : this.bestCommonTypeOfThreeTypes(contextualType, leftType, rightType, context); + } else { + var leftType = this.resolveAST(binex.left, false, context).type; + + context.pushNewContextualType(leftType); + var rightType = this.resolveAST(binex.right, true, context).type; + context.popAnyContextualType(); + + return this.bestCommonTypeOfTwoTypes(leftType, rightType, context); + } + }; + + PullTypeResolver.prototype.resolveLogicalAndExpression = function (binex, context) { + if (this.canTypeCheckAST(binex, context)) { + this.setTypeChecked(binex, context); + + this.resolveAST(binex.left, false, context); + } + + return this.resolveAST(binex.right, false, context).type; + }; + + PullTypeResolver.prototype.computeTypeOfConditionalExpression = function (leftType, rightType, isContextuallyTyped, context) { + if (isContextuallyTyped && !context.isInferentiallyTyping()) { + var contextualType = context.getContextualType(); + return this.bestCommonTypeOfThreeTypes(contextualType, leftType, rightType, context); + } else { + return this.bestCommonTypeOfTwoTypes(leftType, rightType, context); + } + }; + + PullTypeResolver.prototype.resolveConditionalExpression = function (trinex, isContextuallyTyped, context) { + var leftType = this.resolveAST(trinex.whenTrue, isContextuallyTyped, context).type; + var rightType = this.resolveAST(trinex.whenFalse, isContextuallyTyped, context).type; + + var expressionType = this.computeTypeOfConditionalExpression(leftType, rightType, isContextuallyTyped, context); + + var conditionalTypesAreValid = this.conditionExpressionTypesAreValid(leftType, rightType, expressionType, isContextuallyTyped, context); + + if (this.canTypeCheckAST(trinex, context)) { + this.setTypeChecked(trinex, context); + this.resolveAST(trinex.condition, false, context); + + if (!this.conditionExpressionTypesAreValid(leftType, rightType, expressionType, isContextuallyTyped, context)) { + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(trinex, TypeScript.DiagnosticCode.Type_of_conditional_0_must_be_identical_to_1_2_or_3, [expressionType.toString(), leftType.toString(), rightType.toString(), contextualType.toString()])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(trinex, TypeScript.DiagnosticCode.Type_of_conditional_0_must_be_identical_to_1_or_2, [expressionType.toString(), leftType.toString(), rightType.toString()])); + } + } + } + + if (!conditionalTypesAreValid) { + return this.getNewErrorTypeSymbol(); + } + + return expressionType; + }; + + PullTypeResolver.prototype.conditionExpressionTypesAreValid = function (leftType, rightType, expressionType, isContextuallyTyped, context) { + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + if (this.typesAreIdentical(expressionType, leftType, context) || this.typesAreIdentical(expressionType, rightType, context) || this.typesAreIdentical(expressionType, contextualType, context)) { + return true; + } + } else { + if (this.typesAreIdentical(expressionType, leftType, context) || this.typesAreIdentical(expressionType, rightType, context)) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.resolveParenthesizedExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + } + + return this.resolveAST(ast.expression, false, context); + }; + + PullTypeResolver.prototype.resolveExpressionStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveInvocationExpression = function (callEx, context, additionalResults) { + var symbol = this.getSymbolForAST(callEx, context); + + if (!symbol || !symbol.isResolved) { + if (!additionalResults) { + additionalResults = new PullAdditionalCallResolutionData(); + } + symbol = this.computeInvocationExpressionSymbol(callEx, context, additionalResults); + if (this.canTypeCheckAST(callEx, context)) { + this.setTypeChecked(callEx, context); + } + if (symbol !== this.semanticInfoChain.anyTypeSymbol) { + this.setSymbolForAST(callEx, symbol, context); + } + this.semanticInfoChain.setCallResolutionDataForAST(callEx, additionalResults); + } else { + if (this.canTypeCheckAST(callEx, context)) { + this.typeCheckInvocationExpression(callEx, context); + } + + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + if (additionalResults && (callResolutionData !== additionalResults)) { + additionalResults.actualParametersContextTypeSymbols = callResolutionData.actualParametersContextTypeSymbols; + additionalResults.candidateSignature = callResolutionData.candidateSignature; + additionalResults.resolvedSignatures = callResolutionData.resolvedSignatures; + additionalResults.targetSymbol = callResolutionData.targetSymbol; + } + } + + return symbol; + }; + + PullTypeResolver.prototype.typeCheckInvocationExpression = function (callEx, context) { + this.setTypeChecked(callEx, context); + var targetSymbol = this.resolveAST(callEx.expression, false, context); + + if (callEx.argumentList.arguments) { + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + + var len = callEx.argumentList.arguments.nonSeparatorCount(); + for (var i = 0; i < len; i++) { + var contextualType = callResolutionData.actualParametersContextTypeSymbols ? callResolutionData.actualParametersContextTypeSymbols[i] : null; + if (contextualType) { + context.pushNewContextualType(contextualType); + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + for (var i = 0; i < callResolutionData.diagnosticsFromOverloadResolution.length; i++) { + context.postDiagnostic(callResolutionData.diagnosticsFromOverloadResolution[i]); + } + }; + + PullTypeResolver.prototype.computeInvocationExpressionSymbol = function (callEx, context, additionalResults) { + var targetSymbol = this.resolveAST(callEx.expression, false, context); + var targetAST = this.getCallTargetErrorSpanAST(callEx); + + var targetTypeSymbol = targetSymbol.type; + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + this.resolveAST(callEx.argumentList.arguments, false, context); + + if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { + if (targetTypeSymbol === this.semanticInfoChain.anyTypeSymbol) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Untyped_function_calls_may_not_accept_type_arguments), additionalResults, context); + return this.getNewErrorTypeSymbol(); + } + } + + return this.semanticInfoChain.anyTypeSymbol; + } + + var isSuperCall = false; + + if (callEx.expression.kind() === 50 /* SuperKeyword */) { + isSuperCall = true; + + if (targetTypeSymbol.isClass()) { + targetSymbol = targetTypeSymbol.getConstructorMethod(); + this.resolveDeclaredSymbol(targetSymbol, context); + targetTypeSymbol = targetSymbol.type; + } else { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Calls_to_super_are_only_valid_inside_a_class), additionalResults, context); + this.resolveAST(callEx.argumentList.arguments, false, context); + + return this.getNewErrorTypeSymbol(); + } + } + + var signatures = isSuperCall ? targetTypeSymbol.getConstructSignatures() : targetTypeSymbol.getCallSignatures(); + + if (!signatures.length && (targetTypeSymbol.kind === 33554432 /* ConstructorType */)) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, [targetTypeSymbol.toString()]), additionalResults, context); + } + + var explicitTypeArgs = null; + var couldNotFindGenericOverload = false; + var couldNotAssignToConstraint; + var constraintDiagnostic = null; + var typeArgumentCountDiagnostic = null; + var diagnostics = []; + + if (callEx.argumentList.typeArgumentList) { + explicitTypeArgs = []; + + if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { + for (var i = 0; i < callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { + explicitTypeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + } + } + } + + var triedToInferTypeArgs = false; + + var resolvedSignatures = []; + var inferredOrExplicitTypeArgs; + var specializedSignature; + var typeParameters; + var typeConstraint = null; + var beforeResolutionSignatures = signatures; + var targetTypeReplacementMap = targetTypeSymbol.getTypeParameterArgumentMap(); + + for (var i = 0; i < signatures.length; i++) { + typeParameters = signatures[i].getTypeParameters(); + couldNotAssignToConstraint = false; + + if (signatures[i].isGeneric() && typeParameters.length) { + if (isSuperCall && targetTypeSymbol.isGeneric() && !callEx.argumentList.typeArgumentList) { + explicitTypeArgs = signatures[i].returnType.getTypeArguments(); + } + + if (explicitTypeArgs) { + if (explicitTypeArgs.length === typeParameters.length) { + inferredOrExplicitTypeArgs = explicitTypeArgs; + } else { + typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, explicitTypeArgs.length]); + continue; + } + } else { + TypeScript.Debug.assert(callEx.argumentList); + var typeArgumentInferenceContext = new TypeScript.InvocationTypeArgumentInferenceContext(this, context, signatures[i], callEx.argumentList.arguments); + inferredOrExplicitTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); + triedToInferTypeArgs = true; + } + + TypeScript.Debug.assert(inferredOrExplicitTypeArgs && inferredOrExplicitTypeArgs.length == typeParameters.length); + + var mutableTypeReplacementMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(targetTypeReplacementMap ? targetTypeReplacementMap : []); + TypeScript.PullInstantiationHelpers.updateMutableTypeParameterArgumentMap(typeParameters, inferredOrExplicitTypeArgs, mutableTypeReplacementMap); + var typeReplacementMap = mutableTypeReplacementMap.typeParameterArgumentMap; + + if (explicitTypeArgs) { + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); + } + + if (!this.sourceIsAssignableToTarget(inferredOrExplicitTypeArgs[j], typeConstraint, targetAST, context, null, true)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); + constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredOrExplicitTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); + couldNotAssignToConstraint = true; + } + + if (couldNotAssignToConstraint) { + break; + } + } + } + } + + if (couldNotAssignToConstraint) { + continue; + } + + specializedSignature = this.instantiateSignature(signatures[i], typeReplacementMap); + + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; + } + } else { + if (!(callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount())) { + resolvedSignatures[resolvedSignatures.length] = signatures[i]; + } + } + } + + if (signatures.length && !resolvedSignatures.length) { + couldNotFindGenericOverload = true; + } + + signatures = resolvedSignatures; + + var errorCondition = null; + if (!signatures.length) { + additionalResults.targetSymbol = targetSymbol; + additionalResults.resolvedSignatures = beforeResolutionSignatures; + additionalResults.candidateSignature = beforeResolutionSignatures && beforeResolutionSignatures.length ? beforeResolutionSignatures[0] : null; + + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + + this.resolveAST(callEx.argumentList.arguments, false, context); + + if (!couldNotFindGenericOverload) { + if (this.cachedFunctionInterfaceType() && this.sourceIsAssignableToTarget(targetTypeSymbol, this.cachedFunctionInterfaceType(), targetAST, context)) { + if (callEx.argumentList.typeArgumentList) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Non_generic_functions_may_not_accept_type_arguments), additionalResults, context); + } + return this.semanticInfoChain.anyTypeSymbol; + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature), additionalResults, context); + } else if (constraintDiagnostic) { + this.postOverloadResolutionDiagnostics(constraintDiagnostic, additionalResults, context); + } else if (typeArgumentCountDiagnostic) { + this.postOverloadResolutionDiagnostics(typeArgumentCountDiagnostic, additionalResults, context); + } else { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.Could_not_select_overload_for_call_expression), additionalResults, context); + } + + return this.getNewErrorTypeSymbol(); + } + + var signature = this.resolveOverloads(callEx, signatures, callEx.argumentList.typeArgumentList !== null, context, diagnostics); + var useBeforeResolutionSignatures = signature == null; + + if (!signature) { + for (var i = 0; i < diagnostics.length; i++) { + this.postOverloadResolutionDiagnostics(diagnostics[i], additionalResults, context); + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Could_not_select_overload_for_call_expression), additionalResults, context); + + errorCondition = this.getNewErrorTypeSymbol(); + + if (!signatures.length) { + return errorCondition; + } + + signature = signatures[0]; + } + + var rootSignature = signature.getRootSymbol(); + if (!rootSignature.isGeneric() && callEx.argumentList.typeArgumentList) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Non_generic_functions_may_not_accept_type_arguments), additionalResults, context); + } else if (rootSignature.isGeneric() && callEx.argumentList.typeArgumentList && rootSignature.getTypeParameters() && (callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount() !== rootSignature.getTypeParameters().length)) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [rootSignature.getTypeParameters().length, callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()]), additionalResults, context); + } + + var returnType = isSuperCall ? this.semanticInfoChain.voidTypeSymbol : signature.returnType; + + var actualParametersContextTypeSymbols = []; + if (callEx.argumentList.arguments) { + var len = callEx.argumentList.arguments.nonSeparatorCount(); + var params = signature.parameters; + var contextualType = null; + var signatureDecl = signature.getDeclarations()[0]; + + for (var i = 0; i < len; i++) { + if (params.length) { + if (i < params.length - 1 || (i < params.length && !signature.hasVarArgs)) { + this.resolveDeclaredSymbol(params[i], context); + contextualType = params[i].type; + } else if (signature.hasVarArgs) { + contextualType = params[params.length - 1].type; + if (contextualType.isArrayNamedTypeReference()) { + contextualType = contextualType.getElementType(); + } + } + } + + if (contextualType) { + context.pushNewContextualType(contextualType); + actualParametersContextTypeSymbols[i] = contextualType; + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + additionalResults.targetSymbol = targetSymbol; + if (useBeforeResolutionSignatures && beforeResolutionSignatures) { + additionalResults.resolvedSignatures = beforeResolutionSignatures; + additionalResults.candidateSignature = beforeResolutionSignatures[0]; + } else { + additionalResults.resolvedSignatures = signatures; + additionalResults.candidateSignature = signature; + } + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + + if (errorCondition) { + return errorCondition; + } + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return returnType; + }; + + PullTypeResolver.prototype.resolveObjectCreationExpression = function (callEx, context, additionalResults) { + var symbol = this.getSymbolForAST(callEx, context); + + if (!symbol || !symbol.isResolved) { + if (!additionalResults) { + additionalResults = new PullAdditionalCallResolutionData(); + } + symbol = this.computeObjectCreationExpressionSymbol(callEx, context, additionalResults); + if (this.canTypeCheckAST(callEx, context)) { + this.setTypeChecked(callEx, context); + } + this.setSymbolForAST(callEx, symbol, context); + this.semanticInfoChain.setCallResolutionDataForAST(callEx, additionalResults); + } else { + if (this.canTypeCheckAST(callEx, context)) { + this.typeCheckObjectCreationExpression(callEx, context); + } + + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + if (additionalResults && (callResolutionData !== additionalResults)) { + additionalResults.actualParametersContextTypeSymbols = callResolutionData.actualParametersContextTypeSymbols; + additionalResults.candidateSignature = callResolutionData.candidateSignature; + additionalResults.resolvedSignatures = callResolutionData.resolvedSignatures; + additionalResults.targetSymbol = callResolutionData.targetSymbol; + } + } + + return symbol; + }; + + PullTypeResolver.prototype.typeCheckObjectCreationExpression = function (callEx, context) { + this.setTypeChecked(callEx, context); + this.resolveAST(callEx.expression, false, context); + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + if (callEx.argumentList) { + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + var len = callEx.argumentList.arguments.nonSeparatorCount(); + + for (var i = 0; i < len; i++) { + var contextualType = callResolutionData.actualParametersContextTypeSymbols ? callResolutionData.actualParametersContextTypeSymbols[i] : null; + if (contextualType) { + context.pushNewContextualType(contextualType); + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + for (var i = 0; i < callResolutionData.diagnosticsFromOverloadResolution.length; i++) { + context.postDiagnostic(callResolutionData.diagnosticsFromOverloadResolution[i]); + } + }; + + PullTypeResolver.prototype.postOverloadResolutionDiagnostics = function (diagnostic, additionalResults, context) { + if (!context.inProvisionalResolution()) { + additionalResults.diagnosticsFromOverloadResolution.push(diagnostic); + } + context.postDiagnostic(diagnostic); + }; + + PullTypeResolver.prototype.computeObjectCreationExpressionSymbol = function (callEx, context, additionalResults) { + var _this = this; + var returnType = null; + + var targetSymbol = this.resolveAST(callEx.expression, false, context); + var targetTypeSymbol = targetSymbol.isType() ? targetSymbol : targetSymbol.type; + + var targetAST = this.getCallTargetErrorSpanAST(callEx); + + var constructSignatures = targetTypeSymbol.getConstructSignatures(); + + var explicitTypeArgs = null; + var usedCallSignaturesInstead = false; + var couldNotAssignToConstraint; + var constraintDiagnostic = null; + var typeArgumentCountDiagnostic = null; + var diagnostics = []; + + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + if (callEx.argumentList) { + this.resolveAST(callEx.argumentList.arguments, false, context); + } + + return targetTypeSymbol; + } + + if (!constructSignatures.length) { + constructSignatures = targetTypeSymbol.getCallSignatures(); + usedCallSignaturesInstead = true; + + if (this.compilationSettings.noImplicitAny()) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.new_expression_which_lacks_a_constructor_signature_implicitly_has_an_any_type), additionalResults, context); + } + } + + if (constructSignatures.length) { + if (callEx.argumentList && callEx.argumentList.typeArgumentList) { + explicitTypeArgs = []; + + if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { + for (var i = 0; i < callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { + explicitTypeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + } + } + } + + if (targetTypeSymbol.isGeneric()) { + var resolvedSignatures = []; + var inferredOrExplicitTypeArgs; + var specializedSignature; + var typeParameters; + var typeConstraint = null; + var triedToInferTypeArgs; + var targetTypeReplacementMap = targetTypeSymbol.getTypeParameterArgumentMap(); + + for (var i = 0; i < constructSignatures.length; i++) { + couldNotAssignToConstraint = false; + + if (constructSignatures[i].isGeneric()) { + typeParameters = constructSignatures[i].getTypeParameters(); + + if (explicitTypeArgs) { + if (explicitTypeArgs.length === typeParameters.length) { + inferredOrExplicitTypeArgs = explicitTypeArgs; + } else { + typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, explicitTypeArgs.length]); + continue; + } + } else if (callEx.argumentList) { + var typeArgumentInferenceContext = new TypeScript.InvocationTypeArgumentInferenceContext(this, context, constructSignatures[i], callEx.argumentList.arguments); + inferredOrExplicitTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); + triedToInferTypeArgs = true; + } else { + inferredOrExplicitTypeArgs = TypeScript.ArrayUtilities.select(typeParameters, function (typeParameter) { + return typeParameter.getDefaultConstraint(_this.semanticInfoChain); + }); + } + + TypeScript.Debug.assert(inferredOrExplicitTypeArgs && inferredOrExplicitTypeArgs.length == typeParameters.length); + + var mutableTypeReplacementMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(targetTypeReplacementMap ? targetTypeReplacementMap : []); + TypeScript.PullInstantiationHelpers.updateMutableTypeParameterArgumentMap(typeParameters, inferredOrExplicitTypeArgs, mutableTypeReplacementMap); + var typeReplacementMap = mutableTypeReplacementMap.typeParameterArgumentMap; + + if (explicitTypeArgs) { + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); + } + + if (!this.sourceIsAssignableToTarget(inferredOrExplicitTypeArgs[j], typeConstraint, targetAST, context, null, true)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); + constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredOrExplicitTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); + couldNotAssignToConstraint = true; + } + + if (couldNotAssignToConstraint) { + break; + } + } + } + } + + if (couldNotAssignToConstraint) { + continue; + } + + specializedSignature = this.instantiateSignature(constructSignatures[i], typeReplacementMap); + + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; + } + } else { + if (!(callEx.argumentList && callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount())) { + resolvedSignatures[resolvedSignatures.length] = constructSignatures[i]; + } + } + } + + constructSignatures = resolvedSignatures; + } + + var signature = this.resolveOverloads(callEx, constructSignatures, callEx.argumentList && callEx.argumentList.typeArgumentList !== null, context, diagnostics); + + additionalResults.targetSymbol = targetSymbol; + additionalResults.resolvedSignatures = constructSignatures; + additionalResults.candidateSignature = signature; + additionalResults.actualParametersContextTypeSymbols = []; + + if (!constructSignatures.length) { + if (constraintDiagnostic) { + this.postOverloadResolutionDiagnostics(constraintDiagnostic, additionalResults, context); + } else if (typeArgumentCountDiagnostic) { + this.postOverloadResolutionDiagnostics(typeArgumentCountDiagnostic, additionalResults, context); + } + + return this.getNewErrorTypeSymbol(); + } + + var errorCondition = null; + + if (!signature) { + for (var i = 0; i < diagnostics.length; i++) { + this.postOverloadResolutionDiagnostics(diagnostics[i], additionalResults, context); + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Could_not_select_overload_for_new_expression), additionalResults, context); + + errorCondition = this.getNewErrorTypeSymbol(); + + if (!constructSignatures.length) { + return errorCondition; + } + + signature = constructSignatures[0]; + } + + returnType = signature.returnType; + + if (returnType && !signature.isGeneric() && returnType.isGeneric() && !returnType.getIsSpecialized()) { + if (explicitTypeArgs && explicitTypeArgs.length) { + returnType = this.createInstantiatedType(returnType, explicitTypeArgs); + } else { + returnType = this.instantiateTypeToAny(returnType, context); + } + } + + if (usedCallSignaturesInstead) { + if (returnType !== this.semanticInfoChain.voidTypeSymbol) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Call_signatures_used_in_a_new_expression_must_have_a_void_return_type), additionalResults, context); + + return this.getNewErrorTypeSymbol(); + } else { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + } + + if (!returnType) { + returnType = signature.returnType; + + if (!returnType) { + returnType = targetTypeSymbol; + } + } + + var actualParametersContextTypeSymbols = []; + if (callEx.argumentList && callEx.argumentList.arguments) { + var len = callEx.argumentList.arguments.nonSeparatorCount(); + var params = signature.parameters; + var contextualType = null; + var signatureDecl = signature.getDeclarations()[0]; + + for (var i = 0; i < len; i++) { + if (params.length) { + if (i < params.length - 1 || (i < params.length && !signature.hasVarArgs)) { + this.resolveDeclaredSymbol(params[i], context); + contextualType = params[i].type; + } else if (signature.hasVarArgs) { + contextualType = params[params.length - 1].type; + if (contextualType.isArrayNamedTypeReference()) { + contextualType = contextualType.getElementType(); + } + } + } + + if (contextualType) { + context.pushNewContextualType(contextualType); + actualParametersContextTypeSymbols[i] = contextualType; + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + additionalResults.targetSymbol = targetSymbol; + additionalResults.resolvedSignatures = constructSignatures; + additionalResults.candidateSignature = signature; + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + + if (errorCondition) { + return errorCondition; + } + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return returnType; + } else if (callEx.argumentList) { + this.resolveAST(callEx.argumentList.arguments, false, context); + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Invalid_new_expression), additionalResults, context); + + return this.getNewErrorTypeSymbol(); + }; + + PullTypeResolver.prototype.instantiateSignatureInContext = function (signatureAToInstantiate, contextualSignatureB, context, shouldFixContextualSignatureParameterTypes) { + var typeReplacementMap = []; + var inferredTypeArgs; + var specializedSignature; + var typeParameters = signatureAToInstantiate.getTypeParameters(); + var typeConstraint = null; + + var typeArgumentInferenceContext = new TypeScript.ContextualSignatureInstantiationTypeArgumentInferenceContext(this, context, signatureAToInstantiate, contextualSignatureB, shouldFixContextualSignatureParameterTypes); + inferredTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); + + var functionTypeA = signatureAToInstantiate.functionType; + var functionTypeB = contextualSignatureB.functionType; + var enclosingTypeParameterMap; + + if (functionTypeA) { + enclosingTypeParameterMap = functionTypeA.getTypeParameterArgumentMap(); + + for (var id in enclosingTypeParameterMap) { + typeReplacementMap[id] = enclosingTypeParameterMap[id]; + } + } + + if (functionTypeB) { + enclosingTypeParameterMap = functionTypeB.getTypeParameterArgumentMap(); + + for (var id in enclosingTypeParameterMap) { + typeReplacementMap[id] = enclosingTypeParameterMap[id]; + } + } + + TypeScript.PullInstantiationHelpers.updateTypeParameterArgumentMap(typeParameters, inferredTypeArgs, typeReplacementMap); + + return this.instantiateSignature(signatureAToInstantiate, typeReplacementMap); + }; + + PullTypeResolver.prototype.resolveCastExpression = function (assertionExpression, context) { + var typeAssertionType = this.resolveTypeReference(assertionExpression.type, context).type; + + if (this.canTypeCheckAST(assertionExpression, context)) { + this.typeCheckCastExpression(assertionExpression, context, typeAssertionType); + } + + return typeAssertionType; + }; + + PullTypeResolver.prototype.typeCheckCastExpression = function (assertionExpression, context, typeAssertionType) { + this.setTypeChecked(assertionExpression, context); + + context.pushNewContextualType(typeAssertionType); + var exprType = this.resolveAST(assertionExpression.expression, true, context).type; + context.popAnyContextualType(); + + this.resolveDeclaredSymbol(typeAssertionType, context); + this.resolveDeclaredSymbol(exprType, context); + + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(exprType, typeAssertionType, assertionExpression, context, comparisonInfo); + + if (!isAssignable) { + var widenedExprType = exprType.widenedType(this, assertionExpression.expression, context); + isAssignable = this.sourceIsAssignableToTarget(typeAssertionType, widenedExprType, assertionExpression, context, comparisonInfo); + } + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(assertionExpression); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(assertionExpression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [exprType.toString(enclosingSymbol), typeAssertionType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(assertionExpression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [exprType.toString(enclosingSymbol), typeAssertionType.toString(enclosingSymbol)])); + } + } + }; + + PullTypeResolver.prototype.resolveAssignmentExpression = function (binaryExpression, context) { + var leftExpr = this.resolveAST(binaryExpression.left, false, context); + var leftType = leftExpr.type; + + context.pushNewContextualType(leftType); + var rightType = this.resolveAST(binaryExpression.right, true, context).type; + context.popAnyContextualType(); + + rightType = this.getInstanceTypeForAssignment(binaryExpression.left, rightType, context); + + if (this.canTypeCheckAST(binaryExpression, context)) { + this.setTypeChecked(binaryExpression, context); + + if (!this.isReference(binaryExpression.left, leftExpr)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_left_hand_side_of_assignment_expression)); + } else { + this.checkAssignability(binaryExpression.left, rightType, leftExpr.type, context); + } + } + + return rightType; + }; + + PullTypeResolver.prototype.getInstanceTypeForAssignment = function (lhs, type, context) { + var typeToReturn = type; + if (typeToReturn && typeToReturn.isAlias()) { + typeToReturn = typeToReturn.getExportAssignedTypeSymbol(); + } + + if (typeToReturn && typeToReturn.isContainer() && !typeToReturn.isEnum()) { + var instanceTypeSymbol = typeToReturn.getInstanceType(); + + if (!instanceTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(lhs, TypeScript.DiagnosticCode.Tried_to_set_variable_type_to_uninitialized_module_type_0, [type.toString()])); + typeToReturn = null; + } else { + typeToReturn = instanceTypeSymbol; + } + } + + return typeToReturn; + }; + + PullTypeResolver.prototype.widenType = function (type, ast, context) { + if (type === this.semanticInfoChain.undefinedTypeSymbol || type === this.semanticInfoChain.nullTypeSymbol || type.isError()) { + return this.semanticInfoChain.anyTypeSymbol; + } + + if (type.isArrayNamedTypeReference()) { + return this.widenArrayType(type, ast, context); + } else if (type.kind === 256 /* ObjectLiteral */) { + return this.widenObjectLiteralType(type, ast, context); + } + + return type; + }; + + PullTypeResolver.prototype.widenArrayType = function (type, ast, context) { + var elementType = type.getElementType().widenedType(this, ast, context); + + if (this.compilationSettings.noImplicitAny() && ast) { + if (elementType === this.semanticInfoChain.anyTypeSymbol && type.getElementType() !== this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Array_Literal_implicitly_has_an_any_type_from_widening)); + } + } + + return this.getArrayType(elementType); + }; + + PullTypeResolver.prototype.widenObjectLiteralType = function (type, ast, context) { + if (!this.needsToWidenObjectLiteralType(type, ast, context)) { + return type; + } + + TypeScript.Debug.assert(type.name === ""); + var newObjectTypeSymbol = new TypeScript.PullTypeSymbol(type.name, type.kind); + var declsOfObjectType = type.getDeclarations(); + TypeScript.Debug.assert(declsOfObjectType.length === 1); + newObjectTypeSymbol.addDeclaration(declsOfObjectType[0]); + var members = type.getMembers(); + + for (var i = 0; i < members.length; i++) { + var memberType = members[i].type; + + var widenedMemberType = members[i].type.widenedType(this, ast, context); + var newMember = new TypeScript.PullSymbol(members[i].name, members[i].kind); + + var declsOfMember = members[i].getDeclarations(); + + newMember.addDeclaration(declsOfMember[0]); + newMember.type = widenedMemberType; + newObjectTypeSymbol.addMember(newMember); + newMember.setResolved(); + + if (this.compilationSettings.noImplicitAny() && ast && widenedMemberType === this.semanticInfoChain.anyTypeSymbol && memberType !== this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Object_literal_s_property_0_implicitly_has_an_any_type_from_widening, [members[i].name])); + } + } + + var indexers = type.getIndexSignatures(); + for (var i = 0; i < indexers.length; i++) { + var newIndexer = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + var parameter = indexers[i].parameters[0]; + var newParameter = new TypeScript.PullSymbol(parameter.name, parameter.kind); + newParameter.type = parameter.type; + newIndexer.addParameter(newParameter); + newIndexer.returnType = indexers[i].returnType; + newObjectTypeSymbol.addIndexSignature(newIndexer); + } + + return newObjectTypeSymbol; + }; + + PullTypeResolver.prototype.needsToWidenObjectLiteralType = function (type, ast, context) { + var members = type.getMembers(); + for (var i = 0; i < members.length; i++) { + var memberType = members[i].type; + if (memberType !== memberType.widenedType(this, ast, context)) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.findBestCommonType = function (collection, context, comparisonInfo) { + var len = collection.getLength(); + + for (var i = 0; i < len; i++) { + var candidateType = collection.getTypeAtIndex(i); + if (this.typeIsBestCommonTypeCandidate(candidateType, collection, context)) { + return candidateType; + } + } + + return this.semanticInfoChain.emptyTypeSymbol; + }; + + PullTypeResolver.prototype.typeIsBestCommonTypeCandidate = function (candidateType, collection, context) { + for (var i = 0; i < collection.getLength(); i++) { + var otherType = collection.getTypeAtIndex(i); + if (candidateType === otherType) { + continue; + } + + if (!this.sourceIsSubtypeOfTarget(otherType, candidateType, null, context)) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.typesAreIdenticalInEnclosingTypes = function (t1, t2, context) { + t1 = this.getSymbolForRelationshipCheck(t1); + t2 = this.getSymbolForRelationshipCheck(t2); + + if (t1 === t2) { + return true; + } + + if (t1 && t2) { + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + return this.infinitelyExpandingTypesAreIdentical(t1, t2, context); + } + } + + return this.typesAreIdentical(t1, t2, context); + }; + + PullTypeResolver.prototype.typesAreIdenticalWithNewEnclosingTypes = function (t1, t2, context) { + var enclosingTypeWalkerStates = context.resetEnclosingTypeWalkerStates(); + var areTypesIdentical = this.typesAreIdentical(t1, t2, context); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areTypesIdentical; + }; + + PullTypeResolver.prototype.typesAreIdentical = function (t1, t2, context) { + t1 = this.getSymbolForRelationshipCheck(t1); + t2 = this.getSymbolForRelationshipCheck(t2); + + if (t1 === t2) { + return true; + } + + if (!t1 || !t2) { + return false; + } + + if (TypeScript.hasFlag(t1.kind, 64 /* Enum */) || TypeScript.hasFlag(t2.kind, 64 /* Enum */)) { + return false; + } + + if (t1.isPrimitive() && t1.isStringConstant() && t2.isPrimitive() && t2.isStringConstant()) { + return TypeScript.stripStartAndEndQuotes(t1.name) === TypeScript.stripStartAndEndQuotes(t2.name); + } + + if (t1.isPrimitive() || t2.isPrimitive()) { + return false; + } + + if (t1.isError() && t2.isError()) { + return true; + } + + var isIdentical = this.identicalCache.valueAt(t1.pullSymbolID, t2.pullSymbolID); + if (isIdentical != undefined) { + return isIdentical; + } + + if (t1.isTypeParameter() !== t2.isTypeParameter()) { + return false; + } else if (t1.isTypeParameter()) { + var t1ParentDeclaration = t1.getDeclarations()[0].getParentDecl(); + var t2ParentDeclaration = t2.getDeclarations()[0].getParentDecl(); + + if (t1ParentDeclaration === t2ParentDeclaration) { + return this.symbolsShareDeclaration(t1, t2); + } else { + return false; + } + } + + if (t1.isPrimitive() !== t2.isPrimitive()) { + return false; + } + + this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, true); + var statesWhenStartedWalkingTypes = context.startWalkingTypes(t1, t2); + isIdentical = this.typesAreIdenticalWorker(t1, t2, context); + context.endWalkingTypes(statesWhenStartedWalkingTypes); + this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, isIdentical); + + return isIdentical; + }; + + PullTypeResolver.prototype.typesAreIdenticalWorker = function (t1, t2, context) { + if (t1.getIsSpecialized() && t2.getIsSpecialized()) { + if (TypeScript.PullHelpers.getRootType(t1) === TypeScript.PullHelpers.getRootType(t2) && TypeScript.PullHelpers.getRootType(t1).isNamedTypeSymbol()) { + var t1TypeArguments = t1.getTypeArguments(); + var t2TypeArguments = t2.getTypeArguments(); + + if (t1TypeArguments && t2TypeArguments) { + for (var i = 0; i < t1TypeArguments.length; i++) { + if (!this.typesAreIdenticalWithNewEnclosingTypes(t1TypeArguments[i], t2TypeArguments[i], context)) { + return false; + } + } + } + + return true; + } + } + + if (t1.hasMembers() && t2.hasMembers()) { + var t1Members = t1.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + var t2Members = t2.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + + if (t1Members.length !== t2Members.length) { + return false; + } + + var t1MemberSymbol = null; + var t2MemberSymbol = null; + + var t1MemberType = null; + var t2MemberType = null; + + for (var iMember = 0; iMember < t1Members.length; iMember++) { + t1MemberSymbol = t1Members[iMember]; + t2MemberSymbol = this.getNamedPropertySymbol(t1MemberSymbol.name, 68147712 /* SomeValue */, t2); + + if (!this.propertiesAreIdentical(t1MemberSymbol, t2MemberSymbol, context)) { + return false; + } + } + } else if (t1.hasMembers() || t2.hasMembers()) { + return false; + } + + var t1CallSigs = t1.getCallSignatures(); + var t2CallSigs = t2.getCallSignatures(); + + var t1ConstructSigs = t1.getConstructSignatures(); + var t2ConstructSigs = t2.getConstructSignatures(); + + var t1IndexSigs = t1.getIndexSignatures(); + var t2IndexSigs = t2.getIndexSignatures(); + + if (!this.signatureGroupsAreIdentical(t1CallSigs, t2CallSigs, context)) { + return false; + } + + if (!this.signatureGroupsAreIdentical(t1ConstructSigs, t2ConstructSigs, context)) { + return false; + } + + if (!this.signatureGroupsAreIdentical(t1IndexSigs, t2IndexSigs, context)) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.propertiesAreIdentical = function (propertySymbol1, propertySymbol2, context) { + if (!propertySymbol2 || (propertySymbol1.isOptional !== propertySymbol2.isOptional)) { + return false; + } + + var t1MemberSymbolIsPrivate = propertySymbol1.anyDeclHasFlag(2 /* Private */); + var t2MemberSymbolIsPrivate = propertySymbol2.anyDeclHasFlag(2 /* Private */); + + if (t1MemberSymbolIsPrivate !== t2MemberSymbolIsPrivate) { + return false; + } else if (t2MemberSymbolIsPrivate && t1MemberSymbolIsPrivate) { + var t1MemberSymbolDecl = propertySymbol1.getDeclarations()[0]; + var sourceDecl = propertySymbol2.getDeclarations()[0]; + if (t1MemberSymbolDecl !== sourceDecl) { + return false; + } + } + + var t1MemberType = propertySymbol1.type; + var t2MemberType = propertySymbol2.type; + + context.walkMemberTypes(propertySymbol1.name); + var areMemberTypesIdentical = this.typesAreIdenticalInEnclosingTypes(t1MemberType, t2MemberType, context); + context.postWalkMemberTypes(); + return areMemberTypesIdentical; + }; + + PullTypeResolver.prototype.propertiesAreIdenticalWithNewEnclosingTypes = function (type1, type2, property1, property2, context) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(type1, type2); + var arePropertiesIdentical = this.propertiesAreIdentical(property1, property2, context); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return arePropertiesIdentical; + }; + + PullTypeResolver.prototype.signatureGroupsAreIdentical = function (sg1, sg2, context) { + if (sg1 === sg2) { + return true; + } + + if (!sg1 || !sg2) { + return false; + } + + if (sg1.length !== sg2.length) { + return false; + } + + for (var i = 0; i < sg1.length; i++) { + context.walkSignatures(sg1[i].kind, i); + var areSignaturesIdentical = this.signaturesAreIdentical(sg1[i], sg2[i], context, true); + context.postWalkSignatures(); + if (!areSignaturesIdentical) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.typeParametersAreIdentical = function (tp1, tp2, context) { + var typeParamsAreIdentical = this.typeParametersAreIdenticalWorker(tp1, tp2, context); + + this.setTypeParameterIdentity(tp1, tp2, undefined); + + return typeParamsAreIdentical; + }; + + PullTypeResolver.prototype.typeParametersAreIdenticalWorker = function (tp1, tp2, context) { + if (!!(tp1 && tp1.length) !== !!(tp2 && tp2.length)) { + return false; + } + + if (tp1 && tp2 && (tp1.length !== tp2.length)) { + return false; + } + + if (tp1 && tp2) { + for (var i = 0; i < tp1.length; i++) { + context.walkTypeParameterConstraints(i); + var areConstraintsIdentical = this.typesAreIdentical(tp1[i].getConstraint(), tp2[i].getConstraint(), context); + context.postWalkTypeParameterConstraints(); + if (!areConstraintsIdentical) { + return false; + } + } + } + + return true; + }; + + PullTypeResolver.prototype.setTypeParameterIdentity = function (tp1, tp2, val) { + if (tp1 && tp2 && tp1.length === tp2.length) { + for (var i = 0; i < tp1.length; i++) { + this.identicalCache.setValueAt(tp1[i].pullSymbolID, tp2[i].pullSymbolID, val); + } + } + }; + + PullTypeResolver.prototype.signaturesAreIdenticalWithNewEnclosingTypes = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(s1, s2); + var areSignaturesIdentical = this.signaturesAreIdentical(s1, s2, context, includingReturnType); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSignaturesIdentical; + }; + + PullTypeResolver.prototype.signaturesAreIdentical = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + if (s1 === s2) { + return true; + } + + var signaturesIdentical = this.identicalCache.valueAt(s1.pullSymbolID, s2.pullSymbolID); + if (signaturesIdentical || (signaturesIdentical != undefined && includingReturnType)) { + return signaturesIdentical; + } + + var oldValue = signaturesIdentical; + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, true); + + signaturesIdentical = this.signaturesAreIdenticalWorker(s1, s2, context, includingReturnType); + + if (includingReturnType) { + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, signaturesIdentical); + } else { + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, oldValue); + } + + return signaturesIdentical; + }; + + PullTypeResolver.prototype.signaturesAreIdenticalWorker = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + if (s1.hasVarArgs !== s2.hasVarArgs) { + return false; + } + + if (s1.nonOptionalParamCount !== s2.nonOptionalParamCount) { + return false; + } + + if (s1.parameters.length !== s2.parameters.length) { + return false; + } + + var s1TypeParameters = s1.getTypeParameters(); + var s2TypeParameters = s2.getTypeParameters(); + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, true); + + var typeParametersParametersAndReturnTypesAreIdentical = this.signatureTypeParametersParametersAndReturnTypesAreIdentical(s1, s2, context, includingReturnType); + + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, undefined); + return typeParametersParametersAndReturnTypesAreIdentical; + }; + + PullTypeResolver.prototype.signatureTypeParametersParametersAndReturnTypesAreIdentical = function (s1, s2, context, includingReturnType) { + if (!this.typeParametersAreIdenticalWorker(s1.getTypeParameters(), s2.getTypeParameters(), context)) { + return false; + } + + if (includingReturnType) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s1); + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s2); + context.walkReturnTypes(); + var areReturnTypesIdentical = this.typesAreIdenticalInEnclosingTypes(s1.returnType, s2.returnType, context); + context.postWalkReturnTypes(); + if (!areReturnTypesIdentical) { + return false; + } + } + + var s1Params = s1.parameters; + var s2Params = s2.parameters; + + for (var iParam = 0; iParam < s1Params.length; iParam++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s1Params[iParam]); + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s2Params[iParam]); + context.walkParameterTypes(iParam); + var areParameterTypesIdentical = this.typesAreIdenticalInEnclosingTypes(s1Params[iParam].type, s2Params[iParam].type, context); + context.postWalkParameterTypes(); + + if (!areParameterTypesIdentical) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.signatureReturnTypesAreIdentical = function (s1, s2, context) { + var s1TypeParameters = s1.getTypeParameters(); + var s2TypeParameters = s2.getTypeParameters(); + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, true); + + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(s1, s2); + context.walkReturnTypes(); + var returnTypeIsIdentical = this.typesAreIdenticalInEnclosingTypes(s1.returnType, s2.returnType, context); + + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, undefined); + + return returnTypeIsIdentical; + }; + + PullTypeResolver.prototype.symbolsShareDeclaration = function (symbol1, symbol2) { + var decls1 = symbol1.getDeclarations(); + var decls2 = symbol2.getDeclarations(); + + if (decls1.length && decls2.length) { + return decls1[0] === decls2[0]; + } + + return false; + }; + + PullTypeResolver.prototype.sourceIsSubtypeOfTarget = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.sourceMembersAreAssignableToTargetMembers = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceMembersAreAssignableToTargetMembers = this.sourceMembersAreRelatableToTargetMembers(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceMembersAreAssignableToTargetMembers; + }; + + PullTypeResolver.prototype.sourcePropertyIsAssignableToTargetProperty = function (source, target, sourceProp, targetProp, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var isSourcePropertyIsAssignableToTargetProperty = this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return isSourcePropertyIsAssignableToTargetProperty; + }; + + PullTypeResolver.prototype.sourceCallSignaturesAreAssignableToTargetCallSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceCallSignaturesAssignableToTargetCallSignatures = this.sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceCallSignaturesAssignableToTargetCallSignatures; + }; + + PullTypeResolver.prototype.sourceConstructSignaturesAreAssignableToTargetConstructSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceConstructSignaturesAssignableToTargetConstructSignatures = this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceConstructSignaturesAssignableToTargetConstructSignatures; + }; + + PullTypeResolver.prototype.sourceIndexSignaturesAreAssignableToTargetIndexSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceIndexSignaturesAssignableToTargetIndexSignatures = this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceIndexSignaturesAssignableToTargetIndexSignatures; + }; + + PullTypeResolver.prototype.typeIsAssignableToFunction = function (source, ast, context) { + if (source.isFunctionType()) { + return true; + } + + return this.cachedFunctionInterfaceType() && this.sourceIsAssignableToTarget(source, this.cachedFunctionInterfaceType(), ast, context); + }; + + PullTypeResolver.prototype.signatureIsAssignableToTarget = function (s1, s2, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(s1, s2); + var isSignatureIsAssignableToTarget = this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return isSignatureIsAssignableToTarget; + }; + + PullTypeResolver.prototype.sourceIsAssignableToTarget = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + return this.sourceIsRelatableToTarget(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.sourceIsAssignableToTargetWithNewEnclosingTypes = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + return this.sourceIsRelatableToTargetWithNewEnclosingTypes(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.getSymbolForRelationshipCheck = function (symbol) { + if (symbol && symbol.isTypeReference()) { + return symbol.getReferencedTypeSymbol(); + } + + return symbol; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetInEnclosingTypes = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + source = this.getSymbolForRelationshipCheck(source); + target = this.getSymbolForRelationshipCheck(target); + + if (source === target) { + return true; + } + + if (source && target) { + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + return this.infinitelyExpandingSourceTypeIsRelatableToTargetType(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + } + } + + return this.sourceIsRelatableToTarget(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetWithNewEnclosingTypes = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.resetEnclosingTypeWalkerStates(); + var isSourceRelatable = this.sourceIsRelatableToTarget(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return isSourceRelatable; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetInCache = function (source, target, comparisonCache, comparisonInfo) { + var isRelatable = comparisonCache.valueAt(source.pullSymbolID, target.pullSymbolID); + + if (isRelatable) { + return { isRelatable: isRelatable }; + } + + if (isRelatable != undefined && !comparisonInfo) { + return { isRelatable: isRelatable }; + } + + return null; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + source = this.getSymbolForRelationshipCheck(source); + target = this.getSymbolForRelationshipCheck(target); + + if (source === target) { + return true; + } + + if (!(source && target)) { + return true; + } + + var sourceApparentType = this.getApparentType(source); + + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(source, target, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; + } + + if (source === this.semanticInfoChain.stringTypeSymbol && target.isPrimitive() && target.isStringConstant()) { + return comparisonInfo && comparisonInfo.stringConstantVal && (comparisonInfo.stringConstantVal.kind() === 14 /* StringLiteral */) && (TypeScript.stripStartAndEndQuotes(comparisonInfo.stringConstantVal.text()) === TypeScript.stripStartAndEndQuotes(target.name)); + } + + if (assignableTo) { + if (this.isAnyOrEquivalent(source) || this.isAnyOrEquivalent(target)) { + return true; + } + } else { + if (this.isAnyOrEquivalent(target)) { + return true; + } + } + + if (target === this.semanticInfoChain.stringTypeSymbol && source.isPrimitive() && source.isStringConstant()) { + return true; + } + + if (source.isPrimitive() && source.isStringConstant() && target.isPrimitive() && target.isStringConstant()) { + return TypeScript.stripStartAndEndQuotes(source.name) === TypeScript.stripStartAndEndQuotes(target.name); + } + + if (source === this.semanticInfoChain.undefinedTypeSymbol) { + return true; + } + + if ((source === this.semanticInfoChain.nullTypeSymbol) && (target !== this.semanticInfoChain.undefinedTypeSymbol && target != this.semanticInfoChain.voidTypeSymbol)) { + return true; + } + + if (target === this.semanticInfoChain.voidTypeSymbol) { + if (source === this.semanticInfoChain.undefinedTypeSymbol || source == this.semanticInfoChain.nullTypeSymbol) { + return true; + } + + return false; + } else if (source === this.semanticInfoChain.voidTypeSymbol) { + if (target === this.semanticInfoChain.anyTypeSymbol) { + return true; + } + + return false; + } + + if (target === this.semanticInfoChain.numberTypeSymbol && TypeScript.PullHelpers.symbolIsEnum(source)) { + return true; + } + + if (source === this.semanticInfoChain.numberTypeSymbol && TypeScript.PullHelpers.symbolIsEnum(target)) { + return assignableTo; + } + + if (TypeScript.PullHelpers.symbolIsEnum(target) && TypeScript.PullHelpers.symbolIsEnum(source)) { + return this.symbolsShareDeclaration(target, source); + } + + if ((source.kind & 64 /* Enum */) || (target.kind & 64 /* Enum */)) { + return false; + } + + if (source.getIsSpecialized() && target.getIsSpecialized()) { + if (TypeScript.PullHelpers.getRootType(source) === TypeScript.PullHelpers.getRootType(target) && TypeScript.PullHelpers.getRootType(source).isNamedTypeSymbol()) { + var sourceTypeArguments = source.getTypeArguments(); + var targetTypeArguments = target.getTypeArguments(); + + if (sourceTypeArguments && targetTypeArguments) { + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, true); + + for (var i = 0; i < sourceTypeArguments.length; i++) { + if (!this.sourceIsRelatableToTargetWithNewEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, null, isComparingInstantiatedSignatures)) { + break; + } + } + + if (i === sourceTypeArguments.length) { + return true; + } else { + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, undefined); + } + } + } + } + + if (target.isTypeParameter()) { + if (source.isTypeParameter()) { + if (!source.getConstraint()) { + return this.typesAreIdentical(target, source, context); + } else { + return this.isSourceTypeParameterConstrainedToTargetTypeParameter(source, target); + } + } else { + if (isComparingInstantiatedSignatures) { + target = target.getBaseConstraint(this.semanticInfoChain); + } else { + return this.typesAreIdentical(target, sourceApparentType, context); + } + } + } + + if (sourceApparentType.isPrimitive() || target.isPrimitive()) { + return false; + } + + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, true); + + var symbolsWhenStartedWalkingTypes = context.startWalkingTypes(sourceApparentType, target); + var isRelatable = this.sourceIsRelatableToTargetWorker(sourceApparentType, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.endWalkingTypes(symbolsWhenStartedWalkingTypes); + + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.isSourceTypeParameterConstrainedToTargetTypeParameter = function (source, target) { + var current = source; + while (current && current.isTypeParameter()) { + if (current === target) { + return true; + } + + current = current.getConstraint(); + } + return false; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetWorker = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + if (target.hasMembers() && !this.sourceMembersAreRelatableToTargetMembers(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.sourceMembersAreRelatableToTargetMembers = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetProps = target.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + + for (var itargetProp = 0; itargetProp < targetProps.length; itargetProp++) { + var targetProp = targetProps[itargetProp]; + + var sourceProp = this._getNamedPropertySymbolOfAugmentedType(targetProp.name, source); + + this.resolveDeclaredSymbol(targetProp, context); + + var targetPropType = targetProp.type; + + if (!sourceProp) { + if (!(targetProp.isOptional)) { + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_is_missing_property_1_from_type_2, [source.toString(enclosingSymbol), targetProp.getScopedNameEx().toString(), target.toString(enclosingSymbol)])); + } + return false; + } + continue; + } + + if (!this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.infinitelyExpandingSourceTypeIsRelatableToTargetType = function (sourceType, targetType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var widenedTargetType = targetType.widenedType(this, null, context); + var widenedSourceType = sourceType.widenedType(this, null, context); + + if ((widenedSourceType !== this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType !== this.semanticInfoChain.anyTypeSymbol)) { + var sourceTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(sourceType); + var targetTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(targetType); + + if (sourceTypeNamedTypeReference !== targetTypeNamedTypeReference) { + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_do_not_refer_to_same_named_type, [sourceType.getScopedNameEx(enclosingSymbol).toString(), targetType.toString(enclosingSymbol)])); + } + return false; + } + + var sourceTypeArguments = sourceType.getTypeArguments(); + var targetTypeArguments = targetType.getTypeArguments(); + + if (!sourceTypeArguments && !targetTypeArguments) { + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, true); + return true; + } + + if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length !== targetTypeArguments.length) { + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)])); + } + return false; + } + + var comparisonInfoTypeArgumentsCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoTypeArgumentsCheck = new TypeComparisonInfo(comparisonInfo); + } + var isRelatable = true; + for (var i = 0; i < sourceTypeArguments.length && isRelatable; i++) { + context.walkTypeArgument(i); + + if (!this.sourceIsRelatableToTargetInEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, comparisonInfoTypeArgumentsCheck, isComparingInstantiatedSignatures)) { + isRelatable = false; + if (comparisonInfo) { + var message; + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + + if (comparisonInfoTypeArgumentsCheck && comparisonInfoTypeArgumentsCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol), comparisonInfoTypeArgumentsCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)]); + } + comparisonInfo.addMessage(message); + } + } + + context.postWalkTypeArgument(); + } + } + + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.infinitelyExpandingTypesAreIdentical = function (sourceType, targetType, context) { + var widenedTargetType = targetType.widenedType(this, null, null); + var widenedSourceType = sourceType.widenedType(this, null, null); + + if ((widenedSourceType !== this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType !== this.semanticInfoChain.anyTypeSymbol)) { + var sourceTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(sourceType); + var targetTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(targetType); + if (sourceTypeNamedTypeReference !== targetTypeNamedTypeReference) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + return false; + } + + var sourceTypeArguments = sourceType.getTypeArguments(); + var targetTypeArguments = targetType.getTypeArguments(); + + if (!sourceTypeArguments && !targetTypeArguments) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, true); + return true; + } + + if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length !== targetTypeArguments.length) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + return false; + } + + for (var i = 0; i < sourceTypeArguments.length; i++) { + context.walkTypeArgument(i); + var areIdentical = this.typesAreIdenticalInEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], context); + context.postWalkTypeArgument(); + + if (!areIdentical) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + return false; + } + } + } + + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, true); + return true; + }; + + PullTypeResolver.prototype.sourcePropertyIsRelatableToTargetProperty = function (source, target, sourceProp, targetProp, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var _this = this; + var sourceAndTargetAreConstructors = source.isConstructor() && target.isConstructor(); + + var getNames = function (takeTypesFromPropertyContainers) { + var enclosingSymbol = _this.getEnclosingSymbolForAST(ast); + var sourceType = takeTypesFromPropertyContainers ? sourceProp.getContainer() : source; + var targetType = takeTypesFromPropertyContainers ? targetProp.getContainer() : target; + if (sourceAndTargetAreConstructors) { + sourceType = sourceType.getAssociatedContainerType(); + targetType = targetType.getAssociatedContainerType(); + } + return { + propertyName: targetProp.getScopedNameEx().toString(), + sourceTypeName: sourceType.toString(enclosingSymbol), + targetTypeName: targetType.toString(enclosingSymbol) + }; + }; + + var targetPropIsPrivate = targetProp.anyDeclHasFlag(2 /* Private */); + var sourcePropIsPrivate = sourceProp.anyDeclHasFlag(2 /* Private */); + + if (targetPropIsPrivate !== sourcePropIsPrivate) { + if (comparisonInfo) { + var names = getNames(true); + var code; + if (targetPropIsPrivate) { + code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Static_property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2 : TypeScript.DiagnosticCode.Property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2; + } else { + code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Static_property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2 : TypeScript.DiagnosticCode.Property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2; + } + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName])); + comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; + } + return false; + } else if (sourcePropIsPrivate && targetPropIsPrivate) { + var targetDecl = targetProp.getDeclarations()[0]; + var sourceDecl = sourceProp.getDeclarations()[0]; + + if (targetDecl !== sourceDecl) { + if (comparisonInfo) { + var names = getNames(true); + + comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_0_and_1_define_static_property_2_as_private : TypeScript.DiagnosticCode.Types_0_and_1_define_property_2_as_private; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(code, [names.sourceTypeName, names.targetTypeName, names.propertyName])); + } + + return false; + } + } + + if (sourceProp.isOptional && !targetProp.isOptional) { + if (comparisonInfo) { + var names = getNames(true); + comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2, [names.propertyName, names.sourceTypeName, names.targetTypeName])); + } + return false; + } + + this.resolveDeclaredSymbol(sourceProp, context); + + var sourcePropType = sourceProp.type; + var targetPropType = targetProp.type; + + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(sourcePropType, targetPropType, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; + } + + var comparisonInfoPropertyTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoPropertyTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + context.walkMemberTypes(targetProp.name); + var isSourcePropertyRelatableToTargetProperty = this.sourceIsRelatableToTargetInEnclosingTypes(sourcePropType, targetPropType, assignableTo, comparisonCache, ast, context, comparisonInfoPropertyTypeCheck, isComparingInstantiatedSignatures); + context.postWalkMemberTypes(); + + if (!isSourcePropertyRelatableToTargetProperty && comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.flags |= 32 /* IncompatiblePropertyTypes */; + var message; + var names = getNames(false); + if (comparisonInfoPropertyTypeCheck && comparisonInfoPropertyTypeCheck.message) { + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3 : TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3; + message = TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName, comparisonInfoPropertyTypeCheck.message]); + } else { + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible : TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible; + message = TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName]); + } + comparisonInfo.addMessage(message); + } + + return isSourcePropertyRelatableToTargetProperty; + }; + + PullTypeResolver.prototype.sourceCallSignaturesAreRelatableToTargetCallSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetCallSigs = target.getCallSignatures(); + + if (targetCallSigs.length) { + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + var sourceCallSigs = source.getCallSignatures(); + if (!this.signatureGroupIsRelatableToTarget(source, target, sourceCallSigs, targetCallSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { + if (comparisonInfo) { + var message; + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + if (sourceCallSigs.length && targetCallSigs.length) { + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signatures_of_types_0_and_1_are_incompatible_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signatures_of_types_0_and_1_are_incompatible, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)]); + } + } else { + var hasSig = targetCallSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + var lacksSig = !targetCallSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_requires_a_call_signature_but_type_1_lacks_one, [hasSig, lacksSig]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.sourceConstructSignaturesAreRelatableToTargetConstructSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetConstructSigs = target.getConstructSignatures(); + if (targetConstructSigs.length) { + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + var sourceConstructSigs = source.getConstructSignatures(); + if (!this.signatureGroupIsRelatableToTarget(source, target, sourceConstructSigs, targetConstructSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + var message; + if (sourceConstructSigs.length && targetConstructSigs.length) { + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Construct_signatures_of_types_0_and_1_are_incompatible_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Construct_signatures_of_types_0_and_1_are_incompatible, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)]); + } + } else { + var hasSig = targetConstructSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + var lacksSig = !targetConstructSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_requires_a_construct_signature_but_type_1_lacks_one, [hasSig, lacksSig]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.sourceIndexSignaturesAreRelatableToTargetIndexSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetIndexSigs = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(target, context); + var targetStringSig = targetIndexSigs.stringSignature; + var targetNumberSig = targetIndexSigs.numericSignature; + + if (targetStringSig || targetNumberSig) { + var sourceIndexSigs = this.getBothKindsOfIndexSignaturesIncludingAugmentedType(source, context); + var enclosingTypeIndexSigs = context.getBothKindOfIndexSignatures(true, false); + var sourceStringSig = sourceIndexSigs.stringSignature; + var sourceNumberSig = sourceIndexSigs.numericSignature; + + var comparable = true; + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + if (targetStringSig) { + if (sourceStringSig) { + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, true, true); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceStringSig.returnType, targetStringSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); + } else { + comparable = false; + } + } + + if (comparable && targetNumberSig) { + if (sourceNumberSig) { + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, false, false); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceNumberSig.returnType, targetNumberSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); + } else if (sourceStringSig) { + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, true, false); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceStringSig.returnType, targetNumberSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); + } else { + comparable = false; + } + } + + if (!comparable) { + if (comparisonInfo) { + var message; + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Index_signatures_of_types_0_and_1_are_incompatible_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Index_signatures_of_types_0_and_1_are_incompatible, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.signatureGroupIsRelatableToTarget = function (source, target, sourceSG, targetSG, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + if (sourceSG === targetSG) { + return true; + } + + if (!(sourceSG.length && targetSG.length)) { + return false; + } + + var foundMatch = false; + + var targetExcludeDefinition = targetSG.length > 1; + var sourceExcludeDefinition = sourceSG.length > 1; + var sigsCompared = 0; + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo, true); + comparisonInfoSignatuesTypeCheck.message = comparisonInfo.message; + } + for (var iMSig = 0; iMSig < targetSG.length; iMSig++) { + var mSig = targetSG[iMSig]; + + if (mSig.isStringConstantOverloadSignature() || (targetExcludeDefinition && mSig.isDefinition())) { + continue; + } + + for (var iNSig = 0; iNSig < sourceSG.length; iNSig++) { + var nSig = sourceSG[iNSig]; + + if (nSig.isStringConstantOverloadSignature() || (sourceExcludeDefinition && nSig.isDefinition())) { + continue; + } + + context.walkSignatures(nSig.kind, iNSig, iMSig); + var isSignatureRelatableToTarget = this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, ast, context, sigsCompared == 0 ? comparisonInfoSignatuesTypeCheck : null, isComparingInstantiatedSignatures); + context.postWalkSignatures(); + + sigsCompared++; + + if (isSignatureRelatableToTarget) { + foundMatch = true; + break; + } + } + + if (foundMatch) { + foundMatch = false; + continue; + } + + if (comparisonInfo && sigsCompared == 1) { + comparisonInfo.message = comparisonInfoSignatuesTypeCheck.message; + } + + return false; + } + + return true; + }; + + PullTypeResolver.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(sourceSig, targetSig, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; + } + + comparisonCache.setValueAt(sourceSig.pullSymbolID, targetSig.pullSymbolID, true); + var isRelatable = this.signatureIsRelatableToTargetWorker(sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + comparisonCache.setValueAt(sourceSig.pullSymbolID, targetSig.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.signatureIsRelatableToTargetWorker = function (sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var _this = this; + var sourceParameters = sourceSig.parameters; + var targetParameters = targetSig.parameters; + + if (!sourceParameters || !targetParameters) { + return false; + } + + var targetNonOptionalParamCount = targetSig.nonOptionalParamCount; + var sourceNonOptionalParamCount = sourceSig.nonOptionalParamCount; + + if (!targetSig.hasVarArgs && sourceNonOptionalParamCount > targetParameters.length) { + if (comparisonInfo) { + comparisonInfo.flags |= 3 /* SourceSignatureHasTooManyParameters */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signature_expects_0_or_fewer_parameters, [targetParameters.length])); + } + return false; + } + + if (this.signaturesAreIdentical(sourceSig, targetSig, context)) { + return true; + } + + if (targetSig.isGeneric()) { + targetSig = this.instantiateSignatureToAny(targetSig); + } + + if (sourceSig.isGeneric()) { + sourceSig = this.instantiateSignatureToAny(sourceSig); + } + + var sourceReturnType = sourceSig.returnType; + var targetReturnType = targetSig.returnType; + + if (targetReturnType !== this.semanticInfoChain.voidTypeSymbol) { + context.walkReturnTypes(); + var returnTypesAreRelatable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceReturnType, targetReturnType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.postWalkReturnTypes(); + if (!returnTypesAreRelatable) { + if (comparisonInfo) { + comparisonInfo.flags |= 16 /* IncompatibleReturnTypes */; + } + + return false; + } + } + + return targetSig.forAllCorrespondingParameterTypesInThisAndOtherSignature(sourceSig, function (targetParamType, sourceParamType, iParam) { + context.walkParameterTypes(iParam); + var areParametersRelatable = _this.sourceIsRelatableToTargetInEnclosingTypes(sourceParamType, targetParamType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + if (!areParametersRelatable) { + context.swapEnclosingTypeWalkers(); + areParametersRelatable = _this.sourceIsRelatableToTargetInEnclosingTypes(targetParamType, sourceParamType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.swapEnclosingTypeWalkers(); + } + context.postWalkParameterTypes(); + + if (!areParametersRelatable) { + if (comparisonInfo) { + comparisonInfo.flags |= 64 /* IncompatibleParameterTypes */; + } + } + + return areParametersRelatable; + }); + }; + + PullTypeResolver.prototype.resolveOverloads = function (application, group, haveTypeArgumentsAtCallSite, context, diagnostics) { + var _this = this; + var hasOverloads = group.length > 1; + var comparisonInfo = new TypeComparisonInfo(); + var args = application.argumentList ? application.argumentList.arguments : null; + + var initialCandidates = TypeScript.ArrayUtilities.where(group, function (signature) { + if (hasOverloads && signature.isDefinition()) { + return false; + } + + var rootSignature = signature.getRootSymbol(); + if (haveTypeArgumentsAtCallSite && !rootSignature.isGeneric()) { + return false; + } + + return _this.overloadHasCorrectArity(signature, args); + }); + + var firstAssignableButNotSupertypeSignature = null; + var firstAssignableWithProvisionalErrorsSignature = null; + + for (var i = 0; i < initialCandidates.length; i++) { + var applicability = this.overloadIsApplicable(initialCandidates[i], args, context, comparisonInfo); + if (applicability === 3 /* Subtype */) { + return initialCandidates[i]; + } else if (applicability === 2 /* AssignableWithNoProvisionalErrors */ && !firstAssignableButNotSupertypeSignature) { + firstAssignableButNotSupertypeSignature = initialCandidates[i]; + } else if (applicability === 1 /* AssignableButWithProvisionalErrors */ && !firstAssignableWithProvisionalErrorsSignature) { + firstAssignableWithProvisionalErrorsSignature = initialCandidates[i]; + } + } + + if (firstAssignableButNotSupertypeSignature || firstAssignableWithProvisionalErrorsSignature) { + return firstAssignableButNotSupertypeSignature || firstAssignableWithProvisionalErrorsSignature; + } else { + var target = this.getCallTargetErrorSpanAST(application); + if (comparisonInfo.message) { + diagnostics.push(this.semanticInfoChain.diagnosticFromAST(target, TypeScript.DiagnosticCode.Supplied_parameters_do_not_match_any_signature_of_call_target_NL_0, [comparisonInfo.message])); + } else { + diagnostics.push(this.semanticInfoChain.diagnosticFromAST(target, TypeScript.DiagnosticCode.Supplied_parameters_do_not_match_any_signature_of_call_target, null)); + } + } + + return null; + }; + + PullTypeResolver.prototype.getCallTargetErrorSpanAST = function (callEx) { + return (callEx.expression.kind() === 212 /* MemberAccessExpression */) ? callEx.expression.name : callEx.expression; + }; + + PullTypeResolver.prototype.overloadHasCorrectArity = function (signature, args) { + if (args == null) { + return signature.nonOptionalParamCount === 0; + } + + var numberOfArgs = (args.nonSeparatorCount() && args.nonSeparatorCount() === args.separatorCount()) ? args.separatorCount() + 1 : args.nonSeparatorCount(); + if (numberOfArgs < signature.nonOptionalParamCount) { + return false; + } + if (!signature.hasVarArgs && numberOfArgs > signature.parameters.length) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.overloadIsApplicable = function (signature, args, context, comparisonInfo) { + if (args === null) { + return 3 /* Subtype */; + } + + var isInVarArg = false; + var parameters = signature.parameters; + var paramType = null; + + var overloadApplicability = 3 /* Subtype */; + + for (var i = 0; i < args.nonSeparatorCount(); i++) { + if (!isInVarArg) { + this.resolveDeclaredSymbol(parameters[i], context); + + if (parameters[i].isVarArg) { + paramType = parameters[i].type.getElementType() || this.getNewErrorTypeSymbol(parameters[i].type.getName()); + isInVarArg = true; + } else { + paramType = parameters[i].type; + } + } + + var statusOfCurrentArgument = this.overloadIsApplicableForArgument(paramType, args.nonSeparatorAt(i), i, context, comparisonInfo); + + if (statusOfCurrentArgument === 0 /* NotAssignable */) { + return 0 /* NotAssignable */; + } else if (statusOfCurrentArgument === 1 /* AssignableButWithProvisionalErrors */) { + overloadApplicability = 1 /* AssignableButWithProvisionalErrors */; + } else if (overloadApplicability !== 1 /* AssignableButWithProvisionalErrors */ && statusOfCurrentArgument === 2 /* AssignableWithNoProvisionalErrors */) { + overloadApplicability = 2 /* AssignableWithNoProvisionalErrors */; + } + } + + return overloadApplicability; + }; + + PullTypeResolver.prototype.overloadIsApplicableForArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + if (paramType.isAny()) { + return 3 /* Subtype */; + } else if (paramType.isError()) { + return 1 /* AssignableButWithProvisionalErrors */; + } else if (arg.kind() === 219 /* SimpleArrowFunctionExpression */) { + var simpleArrowFunction = arg; + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, null, TypeScript.ASTHelpers.parametersFromIdentifier(simpleArrowFunction.identifier), null, simpleArrowFunction.block, simpleArrowFunction.expression, argIndex, context, comparisonInfo); + } else if (arg.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { + var arrowFunction = arg; + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, arrowFunction.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), TypeScript.ASTHelpers.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, argIndex, context, comparisonInfo); + } else if (arg.kind() === 222 /* FunctionExpression */) { + var functionExpression = arg; + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, functionExpression.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(functionExpression.callSignature.parameterList), TypeScript.ASTHelpers.getType(functionExpression), functionExpression.block, null, argIndex, context, comparisonInfo); + } else if (arg.kind() === 215 /* ObjectLiteralExpression */) { + return this.overloadIsApplicableForObjectLiteralArgument(paramType, arg, argIndex, context, comparisonInfo); + } else if (arg.kind() === 214 /* ArrayLiteralExpression */) { + return this.overloadIsApplicableForArrayLiteralArgument(paramType, arg, argIndex, context, comparisonInfo); + } else { + return this.overloadIsApplicableForOtherArgument(paramType, arg, argIndex, context, comparisonInfo); + } + }; + + PullTypeResolver.prototype.overloadIsApplicableForAnyFunctionExpressionArgument = function (paramType, arg, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, argIndex, context, comparisonInfo) { + if (this.cachedFunctionInterfaceType() && paramType === this.cachedFunctionInterfaceType()) { + return 2 /* AssignableWithNoProvisionalErrors */; + } + + context.pushProvisionalType(paramType); + + var argSym = this.resolveAnyFunctionExpression(arg, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, true, context); + + var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + + context.popAnyContextualType(); + + return applicabilityStatus; + }; + + PullTypeResolver.prototype.overloadIsApplicableForObjectLiteralArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + if (this.cachedObjectInterfaceType() && paramType === this.cachedObjectInterfaceType()) { + return 2 /* AssignableWithNoProvisionalErrors */; + } + + context.pushProvisionalType(paramType); + var argSym = this.resolveObjectLiteralExpression(arg, true, context); + + var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + + context.popAnyContextualType(); + + return applicabilityStatus; + }; + + PullTypeResolver.prototype.overloadIsApplicableForArrayLiteralArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + if (paramType === this.cachedArrayInterfaceType()) { + return 2 /* AssignableWithNoProvisionalErrors */; + } + + context.pushProvisionalType(paramType); + var argSym = this.resolveArrayLiteralExpression(arg, true, context); + + var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + + context.popAnyContextualType(); + + return applicabilityStatus; + }; + + PullTypeResolver.prototype.overloadIsApplicableForOtherArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + var argSym = this.resolveAST(arg, false, context); + + if (argSym.type.isAlias()) { + var aliasSym = argSym.type; + argSym = aliasSym.getExportAssignedTypeSymbol(); + } + + comparisonInfo.stringConstantVal = arg; + return this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + }; + + PullTypeResolver.prototype.overloadIsApplicableForArgumentHelper = function (paramType, argSym, argumentIndex, comparisonInfo, arg, context) { + var tempComparisonInfo = new TypeComparisonInfo(); + tempComparisonInfo.stringConstantVal = comparisonInfo.stringConstantVal; + if (!context.hasProvisionalErrors() && this.sourceIsSubtypeOfTarget(argSym.type, paramType, arg, context, tempComparisonInfo)) { + return 3 /* Subtype */; + } + + if (this.sourceIsAssignableToTarget(argSym.type, paramType, arg, context, comparisonInfo.message ? tempComparisonInfo : comparisonInfo)) { + return context.hasProvisionalErrors() ? 1 /* AssignableButWithProvisionalErrors */ : 2 /* AssignableWithNoProvisionalErrors */; + } + + if (!comparisonInfo.message) { + var enclosingSymbol = this.getEnclosingSymbolForAST(arg); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Could_not_apply_type_0_to_argument_1_which_is_of_type_2, [paramType.toString(enclosingSymbol), (argumentIndex + 1), argSym.getTypeName(enclosingSymbol)])); + } + + return 0 /* NotAssignable */; + }; + + PullTypeResolver.prototype.inferArgumentTypesForSignature = function (argContext, comparisonInfo, context) { + var inferenceResultTypes = argContext.inferTypeArguments(); + var typeParameters = argContext.signatureBeingInferred.getTypeParameters(); + TypeScript.Debug.assert(typeParameters.length == inferenceResultTypes.length); + + var typeReplacementMapForConstraints = null; + for (var i = 0; i < inferenceResultTypes.length; i++) { + if (typeParameters[i].getConstraint()) { + typeReplacementMapForConstraints = typeReplacementMapForConstraints || TypeScript.PullInstantiationHelpers.createTypeParameterArgumentMap(typeParameters, inferenceResultTypes); + var associatedConstraint = this.instantiateType(typeParameters[i].getConstraint(), typeReplacementMapForConstraints); + if (!this.sourceIsAssignableToTargetWithNewEnclosingTypes(inferenceResultTypes[i], associatedConstraint, null, context, null, false)) { + inferenceResultTypes[i] = associatedConstraint; + } + } + } + + if (argContext.isInvocationInferenceContext()) { + var invocationContext = argContext; + if (!this.typeParametersAreInScopeAtArgumentList(typeParameters, invocationContext.argumentASTs)) { + for (var i = 0; i < inferenceResultTypes.length; i++) { + if (inferenceResultTypes[i].wrapsSomeTypeParameter(argContext.candidateCache)) { + inferenceResultTypes[i] = this.semanticInfoChain.anyTypeSymbol; + } + } + } + } + + return inferenceResultTypes; + }; + + PullTypeResolver.prototype.typeParametersAreInScopeAtArgumentList = function (typeParameters, args) { + var enclosingDecl = this.getEnclosingDeclForAST(args); + var typeParameterParentDecl = typeParameters[0].getDeclarations()[0].getParentDecl(); + return enclosingDecl.getParentPath().indexOf(typeParameterParentDecl) > -1; + }; + + PullTypeResolver.prototype.relateTypeToTypeParametersInEnclosingType = function (expressionType, parameterType, argContext, context) { + if (expressionType && parameterType) { + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + this.relateInifinitelyExpandingTypeToTypeParameters(expressionType, parameterType, argContext, context); + return; + } + } + this.relateTypeToTypeParameters(expressionType, parameterType, argContext, context); + }; + + PullTypeResolver.prototype.relateTypeToTypeParametersWithNewEnclosingTypes = function (expressionType, parameterType, argContext, context) { + var enclosingTypeWalkerStates = context.resetEnclosingTypeWalkerStates(); + this.relateTypeToTypeParameters(expressionType, parameterType, argContext, context); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + }; + + PullTypeResolver.prototype.relateTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { + if (!expressionType || !parameterType) { + return; + } + + if (expressionType.isError()) { + expressionType = this.semanticInfoChain.anyTypeSymbol; + } + + if (parameterType.isTypeParameter()) { + var typeParameter = parameterType; + argContext.addCandidateForInference(typeParameter, expressionType); + return; + } + + if (parameterType.isNamedTypeSymbol() && !parameterType.isGeneric() && !parameterType.getTypeArguments()) { + return; + } + + if (TypeScript.PullInstantiationHelpers.twoTypesAreInstantiationsOfSameNamedGenericType(expressionType, parameterType)) { + this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, argContext, context); + } else { + var symbolsWhenStartedWalkingTypes = context.startWalkingTypes(expressionType, parameterType); + this.relateObjectTypeToTypeParameters(expressionType, parameterType, argContext, context); + context.endWalkingTypes(symbolsWhenStartedWalkingTypes); + } + }; + + PullTypeResolver.prototype.relateTypeArgumentsOfTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { + var parameterSideTypeArguments = parameterType.getTypeArguments(); + var argumentSideTypeArguments = expressionType.getTypeArguments(); + + TypeScript.Debug.assert(parameterSideTypeArguments && argumentSideTypeArguments && parameterSideTypeArguments.length === argumentSideTypeArguments.length); + for (var i = 0; i < parameterSideTypeArguments.length; i++) { + this.relateTypeToTypeParametersWithNewEnclosingTypes(argumentSideTypeArguments[i], parameterSideTypeArguments[i], argContext, context); + } + }; + + PullTypeResolver.prototype.relateInifinitelyExpandingTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { + if (!expressionType || !parameterType) { + return; + } + + var expressionTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(expressionType); + var parameterTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(parameterType); + if (expressionTypeNamedTypeReference !== parameterTypeNamedTypeReference) { + return; + } + + var expressionTypeTypeArguments = expressionType.getTypeArguments(); + var parameterTypeArguments = parameterType.getTypeArguments(); + + if (expressionTypeTypeArguments && parameterTypeArguments && expressionTypeTypeArguments.length === parameterTypeArguments.length) { + for (var i = 0; i < expressionTypeTypeArguments.length; i++) { + this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, argContext, context); + } + } + }; + + PullTypeResolver.prototype.relateFunctionSignatureToTypeParameters = function (expressionSignature, parameterSignature, argContext, context) { + var _this = this; + var expressionReturnType = expressionSignature.returnType; + var parameterReturnType = parameterSignature.returnType; + + parameterSignature.forAllCorrespondingParameterTypesInThisAndOtherSignature(expressionSignature, function (parameterSignatureParameterType, expressionSignatureParameterType, i) { + context.walkParameterTypes(i); + _this.relateTypeToTypeParametersInEnclosingType(expressionSignatureParameterType, parameterSignatureParameterType, argContext, context); + context.postWalkParameterTypes(); + return true; + }); + + context.walkReturnTypes(); + this.relateTypeToTypeParametersInEnclosingType(expressionReturnType, parameterReturnType, argContext, context); + context.postWalkReturnTypes(); + }; + + PullTypeResolver.prototype.relateObjectTypeToTypeParameters = function (objectType, parameterType, argContext, context) { + var parameterTypeMembers = parameterType.getMembers(); + var parameterSignatures; + + var objectMember; + var objectSignatures; + + if (argContext.alreadyRelatingTypes(objectType, parameterType)) { + return; + } + + for (var i = 0; i < parameterTypeMembers.length; i++) { + objectMember = this.getNamedPropertySymbol(parameterTypeMembers[i].name, 68147712 /* SomeValue */, objectType); + if (objectMember) { + this.resolveDeclaredSymbol(objectMember); + this.resolveDeclaredSymbol(parameterTypeMembers[i]); + context.walkMemberTypes(parameterTypeMembers[i].name); + this.relateTypeToTypeParametersInEnclosingType(objectMember.type, parameterTypeMembers[i].type, argContext, context); + context.postWalkMemberTypes(); + } + } + + this.relateSignatureGroupToTypeParameters(objectType.getCallSignatures(), parameterType.getCallSignatures(), 1048576 /* CallSignature */, argContext, context); + + this.relateSignatureGroupToTypeParameters(objectType.getConstructSignatures(), parameterType.getConstructSignatures(), 2097152 /* ConstructSignature */, argContext, context); + + var parameterIndexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(parameterType, context); + var objectIndexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(objectType, context); + var indexSigInfo = context.getBothKindOfIndexSignatures(false, false); + + if (parameterIndexSignatures.stringSignature && objectIndexSignatures.stringSignature) { + context.walkIndexSignatureReturnTypes(indexSigInfo, true, true, true); + this.relateFunctionSignatureToTypeParameters(objectIndexSignatures.stringSignature, parameterIndexSignatures.stringSignature, argContext, context); + context.postWalkIndexSignatureReturnTypes(true); + } + if (parameterIndexSignatures.numericSignature && objectIndexSignatures.numericSignature) { + context.walkIndexSignatureReturnTypes(indexSigInfo, false, false, true); + this.relateFunctionSignatureToTypeParameters(objectIndexSignatures.numericSignature, parameterIndexSignatures.numericSignature, argContext, context); + context.postWalkIndexSignatureReturnTypes(true); + } + }; + + PullTypeResolver.prototype.relateSignatureGroupToTypeParameters = function (argumentSignatures, parameterSignatures, signatureKind, argContext, context) { + for (var i = 0; i < parameterSignatures.length; i++) { + var paramSignature = parameterSignatures[i]; + if (argumentSignatures.length > 0 && paramSignature.isGeneric()) { + paramSignature = this.instantiateSignatureToAny(paramSignature); + } + for (var j = 0; j < argumentSignatures.length; j++) { + var argumentSignature = argumentSignatures[j]; + if (argumentSignature.nonOptionalParamCount > paramSignature.nonOptionalParamCount) { + continue; + } + + if (argumentSignature.isGeneric()) { + argumentSignature = this.instantiateSignatureToAny(argumentSignature); + } + + context.walkSignatures(signatureKind, j, i); + this.relateFunctionSignatureToTypeParameters(argumentSignature, paramSignature, argContext, context); + context.postWalkSignatures(); + } + } + }; + + PullTypeResolver.prototype.alterPotentialGenericFunctionTypeToInstantiatedFunctionTypeForTypeArgumentInference = function (expressionSymbol, context) { + var inferentialType = context.getContextualType(); + TypeScript.Debug.assert(inferentialType); + var expressionType = expressionSymbol.type; + if (this.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers(expressionType, true) && this.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers(inferentialType, false)) { + var genericExpressionSignature = expressionType.getCallSignatures()[0]; + var contextualSignature = inferentialType.getCallSignatures()[0]; + + var instantiatedSignature = this.instantiateSignatureInContext(genericExpressionSignature, contextualSignature, context, true); + if (instantiatedSignature === null) { + return expressionSymbol; + } + + var newType = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + newType.appendCallSignature(instantiatedSignature); + return newType; + } + + return expressionSymbol; + }; + + PullTypeResolver.prototype.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers = function (type, callSignatureShouldBeGeneric) { + TypeScript.Debug.assert(type); + if (type.getCallSignatures().length !== 1) { + return false; + } + + var callSignatureIsGeneric = type.getCallSignatures()[0].isGeneric(); + if (callSignatureIsGeneric !== callSignatureShouldBeGeneric) { + return false; + } + + var typeHasOtherMembers = type.getConstructSignatures().length || type.getIndexSignatures().length || type.getAllMembers(68147712 /* SomeValue */, 0 /* all */).length; + if (typeHasOtherMembers) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.instantiateTypeToAny = function (typeToSpecialize, context) { + var typeParameters = typeToSpecialize.getTypeParameters(); + + if (!typeParameters.length) { + return typeToSpecialize; + } + + var typeArguments = null; + + if (!this._cachedAnyTypeArgs) { + this._cachedAnyTypeArgs = [ + [this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol] + ]; + } + + if (typeParameters.length < this._cachedAnyTypeArgs.length) { + typeArguments = this._cachedAnyTypeArgs[typeParameters.length - 1]; + } else { + typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArguments[typeArguments.length] = this.semanticInfoChain.anyTypeSymbol; + } + } + + var type = this.createInstantiatedType(typeToSpecialize, typeArguments); + + return type; + }; + + PullTypeResolver.prototype.instantiateSignatureToAny = function (signature) { + var typeParameters = signature.getTypeParameters(); + if (!this._cachedAnyTypeArgs) { + this._cachedAnyTypeArgs = [ + [this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol] + ]; + } + + if (typeParameters.length < this._cachedAnyTypeArgs.length) { + var typeArguments = this._cachedAnyTypeArgs[typeParameters.length - 1]; + } else { + var typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArguments[typeArguments.length] = this.semanticInfoChain.anyTypeSymbol; + } + } + + var typeParameterArgumentMap = TypeScript.PullInstantiationHelpers.createTypeParameterArgumentMap(typeParameters, typeArguments); + return this.instantiateSignature(signature, typeParameterArgumentMap); + }; + + PullTypeResolver.typeCheck = function (compilationSettings, semanticInfoChain, document) { + var sourceUnit = document.sourceUnit(); + + var resolver = semanticInfoChain.getResolver(); + var context = new TypeScript.PullTypeResolutionContext(resolver, true, sourceUnit.fileName()); + + if (resolver.canTypeCheckAST(sourceUnit, context)) { + resolver.resolveAST(sourceUnit, false, context); + resolver.validateVariableDeclarationGroups(semanticInfoChain.getDeclForAST(sourceUnit), context); + + while (resolver.typeCheckCallBacks.length) { + var callBack = resolver.typeCheckCallBacks.pop(); + callBack(context); + } + + resolver.processPostTypeCheckWorkItems(context); + } + }; + + PullTypeResolver.prototype.validateVariableDeclarationGroups = function (enclosingDecl, context) { + var _this = this; + this.scanVariableDeclarationGroups(enclosingDecl, function (_) { + }, function (subsequentDecl, firstSymbol) { + if (TypeScript.hasFlag(subsequentDecl.kind, 2048 /* Parameter */) || TypeScript.hasFlag(subsequentDecl.flags, 8388608 /* PropertyParameter */)) { + return; + } + + var boundDeclAST = _this.semanticInfoChain.getASTForDecl(subsequentDecl); + + var symbol = subsequentDecl.getSymbol(); + var symbolType = symbol.type; + var firstSymbolType = firstSymbol.type; + + if (symbolType && firstSymbolType && symbolType !== firstSymbolType && !_this.typesAreIdentical(symbolType, firstSymbolType, context)) { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(boundDeclAST, TypeScript.DiagnosticCode.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, [symbol.getScopedName(), firstSymbolType.toString(firstSymbol), symbolType.toString(symbol)])); + } + }); + }; + + PullTypeResolver.prototype.typeCheckFunctionOverloads = function (funcDecl, context, signature, allSignatures) { + if (!signature) { + var functionSignatureInfo = TypeScript.PullHelpers.getSignatureForFuncDecl(this.semanticInfoChain.getDeclForAST(funcDecl)); + signature = functionSignatureInfo.signature; + allSignatures = functionSignatureInfo.allSignatures; + } + var functionDeclaration = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSymbol = functionDeclaration.getSymbol(); + + var definitionSignature = null; + for (var i = allSignatures.length - 1; i >= 0; i--) { + if (allSignatures[i].isDefinition()) { + definitionSignature = allSignatures[i]; + break; + } + } + + if (!signature.isDefinition()) { + var signatureParentDecl = signature.getDeclarations()[0].getParentDecl(); + for (var i = 0; i < allSignatures.length; i++) { + if (allSignatures[i] === signature) { + break; + } + + var allSignaturesParentDecl = allSignatures[i].getDeclarations()[0].getParentDecl(); + if (allSignaturesParentDecl !== signatureParentDecl) { + continue; + } + + if (this.signaturesAreIdenticalWithNewEnclosingTypes(allSignatures[i], signature, context, false)) { + if (!this.signatureReturnTypesAreIdentical(allSignatures[i], signature, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overloads_cannot_differ_only_by_return_type)); + } else if (funcDecl.kind() === 137 /* ConstructorDeclaration */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_constructor_overload_signature)); + } else if (functionDeclaration.kind === 2097152 /* ConstructSignature */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_overload_construct_signature)); + } else if (functionDeclaration.kind === 1048576 /* CallSignature */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_overload_call_signature)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_overload_signature_for_0, [funcSymbol.getScopedNameEx().toString()])); + } + + break; + } + } + } + + var isConstantOverloadSignature = signature.isStringConstantOverloadSignature(); + if (isConstantOverloadSignature) { + if (signature.isDefinition()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overload_signature_implementation_cannot_use_specialized_type)); + } else { + var foundSubtypeSignature = false; + for (var i = 0; i < allSignatures.length; i++) { + if (allSignatures[i].isDefinition() || allSignatures[i] === signature) { + continue; + } + + if (!allSignatures[i].isResolved) { + this.resolveDeclaredSymbol(allSignatures[i], context); + } + + if (allSignatures[i].isStringConstantOverloadSignature()) { + continue; + } + + if (this.signatureIsAssignableToTarget(signature, allSignatures[i], null, context)) { + foundSubtypeSignature = true; + break; + } + } + + if (!foundSubtypeSignature) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature)); + } + } + } else if (definitionSignature && definitionSignature !== signature) { + var comparisonInfo = new TypeComparisonInfo(); + + if (!definitionSignature.isResolved) { + this.resolveDeclaredSymbol(definitionSignature, context); + } + + if (!this.signatureIsAssignableToTarget(definitionSignature, signature, funcDecl, context, comparisonInfo)) { + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overload_signature_is_not_compatible_with_function_definition_NL_0, [comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overload_signature_is_not_compatible_with_function_definition)); + } + } + } + + var signatureForVisibilityCheck = definitionSignature; + if (!definitionSignature) { + if (allSignatures[0] === signature) { + return; + } + signatureForVisibilityCheck = allSignatures[0]; + } + + if (funcDecl.kind() !== 137 /* ConstructorDeclaration */ && functionDeclaration.kind !== 2097152 /* ConstructSignature */ && signatureForVisibilityCheck && signature !== signatureForVisibilityCheck) { + var errorCode; + + if (signatureForVisibilityCheck.anyDeclHasFlag(2 /* Private */) !== signature.anyDeclHasFlag(2 /* Private */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_public_or_private; + } else if (signatureForVisibilityCheck.anyDeclHasFlag(1 /* Exported */) !== signature.anyDeclHasFlag(1 /* Exported */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_exported_or_not_exported; + } else if (signatureForVisibilityCheck.anyDeclHasFlag(8 /* Ambient */) !== signature.anyDeclHasFlag(8 /* Ambient */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_ambient_or_non_ambient; + } else if (signatureForVisibilityCheck.anyDeclHasFlag(128 /* Optional */) !== signature.anyDeclHasFlag(128 /* Optional */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_optional_or_required; + } + + if (errorCode) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, errorCode)); + } + } + }; + + PullTypeResolver.prototype.checkSymbolPrivacy = function (declSymbol, symbol, privacyErrorReporter) { + if (!symbol || symbol.kind === 2 /* Primitive */) { + return; + } + + if (symbol.isType()) { + var typeSymbol = symbol; + var isNamedType = typeSymbol.isNamedTypeSymbol(); + + if (typeSymbol.isArrayNamedTypeReference()) { + this.checkSymbolPrivacy(declSymbol, typeSymbol.getElementType(), privacyErrorReporter); + return; + } + + if (!isNamedType) { + var typeOfSymbol = typeSymbol.getTypeOfSymbol(); + if (typeOfSymbol) { + this.checkSymbolPrivacy(declSymbol, typeOfSymbol, privacyErrorReporter); + return; + } + } + + if (typeSymbol.inSymbolPrivacyCheck) { + return; + } + + typeSymbol.inSymbolPrivacyCheck = true; + + var typars = typeSymbol.getTypeArgumentsOrTypeParameters(); + if (typars) { + for (var i = 0; i < typars.length; i++) { + this.checkSymbolPrivacy(declSymbol, typars[i], privacyErrorReporter); + } + } + + if (!isNamedType) { + var members = typeSymbol.getMembers(); + for (var i = 0; i < members.length; i++) { + this.checkSymbolPrivacy(declSymbol, members[i].type, privacyErrorReporter); + } + + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getCallSignatures(), privacyErrorReporter); + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getConstructSignatures(), privacyErrorReporter); + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getIndexSignatures(), privacyErrorReporter); + } else if (typeSymbol.kind === 8192 /* TypeParameter */) { + this.checkSymbolPrivacy(declSymbol, typeSymbol.getConstraint(), privacyErrorReporter); + } + + typeSymbol.inSymbolPrivacyCheck = false; + + if (!isNamedType) { + return; + } + } + + if (declSymbol.isExternallyVisible()) { + var symbolIsVisible = symbol.isExternallyVisible(); + + if (symbolIsVisible && symbol.kind !== 8192 /* TypeParameter */) { + var symbolPath = symbol.pathToRoot(); + var declSymbolPath = declSymbol.pathToRoot(); + + if (symbolPath[symbolPath.length - 1].kind === 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1].kind === 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1] !== symbolPath[symbolPath.length - 1]) { + symbolIsVisible = false; + var declSymbolScope = declSymbolPath[declSymbolPath.length - 1]; + for (var i = symbolPath.length - 1; i >= 0; i--) { + var aliasSymbols = symbolPath[i].getExternalAliasedSymbols(declSymbolScope); + if (aliasSymbols) { + symbolIsVisible = true; + aliasSymbols[0].setTypeUsedExternally(); + break; + } + } + symbol = symbolPath[symbolPath.length - 1]; + } + } else if (symbol.kind === 128 /* TypeAlias */) { + var aliasSymbol = symbol; + symbolIsVisible = true; + aliasSymbol.setTypeUsedExternally(); + } + + if (!symbolIsVisible) { + privacyErrorReporter(symbol); + } + } + }; + + PullTypeResolver.prototype.checkTypePrivacyOfSignatures = function (declSymbol, signatures, privacyErrorReporter) { + for (var i = 0; i < signatures.length; i++) { + var signature = signatures[i]; + if (signatures.length > 1 && signature.isDefinition()) { + continue; + } + + var typeParams = signature.getTypeParameters(); + for (var j = 0; j < typeParams.length; j++) { + this.checkSymbolPrivacy(declSymbol, typeParams[j], privacyErrorReporter); + } + + var params = signature.parameters; + for (var j = 0; j < params.length; j++) { + var paramType = params[j].type; + this.checkSymbolPrivacy(declSymbol, paramType, privacyErrorReporter); + } + + var returnType = signature.returnType; + this.checkSymbolPrivacy(declSymbol, returnType, privacyErrorReporter); + } + }; + + PullTypeResolver.prototype.typeParameterOfTypeDeclarationPrivacyErrorReporter = function (classOrInterface, typeParameterAST, typeParameter, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + var messageCode; + + var typeParameters = classOrInterface.kind() === 131 /* ClassDeclaration */ ? classOrInterface.typeParameterList : classOrInterface.typeParameterList; + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_interface_is_using_inaccessible_module_1; + } + } else { + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_interface_has_or_is_using_private_type_1; + } + } + + var messageArguments = [typeParameter.getScopedName(enclosingSymbol, false, true), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeParameterAST, messageCode, messageArguments)); + }; + + PullTypeResolver.prototype.baseListPrivacyErrorReporter = function (classOrInterface, declSymbol, baseAst, isExtendedType, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + var messageCode; + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + if (isExtendedType) { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_extends_class_from_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_implements_interface_from_inaccessible_module_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_interface_0_extends_interface_from_inaccessible_module_1; + } + } else { + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + if (isExtendedType) { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_extends_private_class_1; + } else { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_implements_private_interface_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_interface_0_extends_private_interface_1; + } + } + + var messageArguments = [declSymbol.getScopedName(enclosingSymbol), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseAst, messageCode, messageArguments)); + }; + + PullTypeResolver.prototype.variablePrivacyErrorReporter = function (declAST, declSymbol, symbol, context) { + var typeSymbol = symbol; + var enclosingDecl = this.getEnclosingDecl(declSymbol.getDeclarations()[0]); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + + var isProperty = declSymbol.kind === 4096 /* Property */; + var isPropertyOfClass = false; + var declParent = declSymbol.getContainer(); + if (declParent && (declParent.kind === 8 /* Class */ || declParent.kind === 32768 /* ConstructorMethod */)) { + isPropertyOfClass = true; + } + + var messageCode; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (declSymbol.anyDeclHasFlag(16 /* Static */)) { + messageCode = TypeScript.DiagnosticCode.Public_static_property_0_of_exported_class_is_using_inaccessible_module_1; + } else if (isProperty) { + if (isPropertyOfClass) { + messageCode = TypeScript.DiagnosticCode.Public_property_0_of_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Property_0_of_exported_interface_is_using_inaccessible_module_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_variable_0_is_using_inaccessible_module_1; + } + } else { + if (declSymbol.anyDeclHasFlag(16 /* Static */)) { + messageCode = TypeScript.DiagnosticCode.Public_static_property_0_of_exported_class_has_or_is_using_private_type_1; + } else if (isProperty) { + if (isPropertyOfClass) { + messageCode = TypeScript.DiagnosticCode.Public_property_0_of_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.Property_0_of_exported_interface_has_or_is_using_private_type_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_variable_0_has_or_is_using_private_type_1; + } + } + + var messageArguments = [declSymbol.getScopedName(enclosingSymbol), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(declAST, messageCode, messageArguments)); + }; + + PullTypeResolver.prototype.checkFunctionTypePrivacy = function (funcDeclAST, isStatic, typeParameters, parameters, returnTypeAnnotation, block, context) { + var _this = this; + if (funcDeclAST.kind() === 222 /* FunctionExpression */ || funcDeclAST.kind() === 241 /* FunctionPropertyAssignment */ || (funcDeclAST.kind() === 139 /* GetAccessor */ && funcDeclAST.parent.parent.kind() === 215 /* ObjectLiteralExpression */) || (funcDeclAST.kind() === 140 /* SetAccessor */ && funcDeclAST.parent.parent.kind() === 215 /* ObjectLiteralExpression */)) { + return; + } + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var functionSymbol = functionDecl.getSymbol(); + ; + var functionSignature; + + var isGetter = funcDeclAST.kind() === 139 /* GetAccessor */; + var isSetter = funcDeclAST.kind() === 140 /* SetAccessor */; + var isIndexSignature = functionDecl.kind === 4194304 /* IndexSignature */; + + if (isGetter || isSetter) { + var accessorSymbol = functionSymbol; + functionSignature = (isGetter ? accessorSymbol.getGetter() : accessorSymbol.getSetter()).type.getCallSignatures()[0]; + } else { + if (!functionSymbol) { + var parentDecl = functionDecl.getParentDecl(); + functionSymbol = parentDecl.getSymbol(); + if (functionSymbol && functionSymbol.isType() && !functionSymbol.isNamedTypeSymbol()) { + return; + } + } else if (functionSymbol.kind === 65536 /* Method */ && !isStatic && !functionSymbol.getContainer().isNamedTypeSymbol()) { + return; + } + functionSignature = functionDecl.getSignatureSymbol(); + } + + if (typeParameters && !isGetter && !isSetter && !isIndexSignature && funcDeclAST.kind() !== 137 /* ConstructorDeclaration */) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + var typeParameterAST = typeParameters.typeParameters.nonSeparatorAt(i); + var typeParameter = this.resolveTypeParameterDeclaration(typeParameterAST, context); + this.checkSymbolPrivacy(functionSymbol, typeParameter, function (symbol) { + return _this.functionTypeArgumentArgumentTypePrivacyErrorReporter(funcDeclAST, isStatic, typeParameterAST, typeParameter, symbol, context); + }); + } + } + + if (!isGetter && !isIndexSignature) { + var funcParams = functionSignature.parameters; + for (var i = 0; i < funcParams.length; i++) { + this.checkSymbolPrivacy(functionSymbol, funcParams[i].type, function (symbol) { + return _this.functionArgumentTypePrivacyErrorReporter(funcDeclAST, isStatic, parameters, i, funcParams[i], symbol, context); + }); + } + } + + if (!isSetter) { + this.checkSymbolPrivacy(functionSymbol, functionSignature.returnType, function (symbol) { + return _this.functionReturnTypePrivacyErrorReporter(funcDeclAST, isStatic, returnTypeAnnotation, block, functionSignature.returnType, symbol, context); + }); + } + }; + + PullTypeResolver.prototype.functionTypeArgumentArgumentTypePrivacyErrorReporter = function (declAST, isStatic, typeParameterAST, typeParameter, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(declAST); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + + var isMethod = decl.kind === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.kind === 8 /* Class */ || isStatic)) { + isMethodOfClass = true; + } + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + var messageCode; + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_function_is_using_inaccessible_module_1; + } + } else { + if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_function_has_or_is_using_private_type_1; + } + } + + if (messageCode) { + var messageArgs = [typeParameter.getScopedName(enclosingSymbol, false, true), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeParameterAST, messageCode, messageArgs)); + } + }; + + PullTypeResolver.prototype.functionArgumentTypePrivacyErrorReporter = function (declAST, isStatic, parameters, argIndex, paramSymbol, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(declAST); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + + var isGetter = declAST.kind() === 139 /* GetAccessor */; + var isSetter = declAST.kind() === 140 /* SetAccessor */; + var isMethod = decl.kind === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.kind === 8 /* Class */ || isStatic)) { + isMethodOfClass = true; + } + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + var messageCode; + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (declAST.kind() === 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_from_exported_class_is_using_inaccessible_module_1; + } else if (isSetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_property_setter_from_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_property_setter_from_exported_class_is_using_inaccessible_module_1; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1; + } + } else if (!isGetter) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_exported_function_is_using_inaccessible_module_1; + } + } else { + if (declAST.kind() === 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_type_1; + } else if (isSetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_type_1; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1; + } + } else if (!isGetter && decl.kind !== 4194304 /* IndexSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_exported_function_has_or_is_using_private_type_1; + } + } + + if (messageCode) { + var parameter = parameters.astAt(argIndex); + + var messageArgs = [paramSymbol.getScopedName(enclosingSymbol), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(parameter, messageCode, messageArgs)); + } + }; + + PullTypeResolver.prototype.functionReturnTypePrivacyErrorReporter = function (declAST, isStatic, returnTypeAnnotation, block, funcReturnType, symbol, context) { + var _this = this; + var decl = this.semanticInfoChain.getDeclForAST(declAST); + var enclosingDecl = this.getEnclosingDecl(decl); + + var isGetter = declAST.kind() === 139 /* GetAccessor */; + var isSetter = declAST.kind() === 140 /* SetAccessor */; + var isMethod = decl.kind === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.kind === 8 /* Class */ || isStatic)) { + isMethodOfClass = true; + } + + var messageCode = null; + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (isGetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module_0; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_0; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module_0; + } else if (decl.kind === 4194304 /* IndexSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module_0; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module_0; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_method_from_exported_class_is_using_inaccessible_module_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_method_from_exported_interface_is_using_inaccessible_module_0; + } + } else if (!isSetter && declAST.kind() !== 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_exported_function_is_using_inaccessible_module_0; + } + } else { + if (isGetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type_0; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_0; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type_0; + } else if (decl.kind === 4194304 /* IndexSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type_0; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type_0; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_method_from_exported_class_has_or_is_using_private_type_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_method_from_exported_interface_has_or_is_using_private_type_0; + } + } else if (!isSetter && declAST.kind() !== 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_exported_function_has_or_is_using_private_type_0; + } + } + + if (messageCode) { + var messageArguments = [typeSymbolName]; + var reportOnFuncDecl = false; + + if (returnTypeAnnotation) { + var returnExpressionSymbol = this.resolveTypeReference(returnTypeAnnotation, context); + + if (TypeScript.PullHelpers.typeSymbolsAreIdentical(returnExpressionSymbol, funcReturnType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, messageCode, messageArguments)); + } + } + + if (block) { + var reportErrorOnReturnExpressions = function (ast, walker) { + var go = true; + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + go = false; + break; + + case 150 /* ReturnStatement */: + var returnStatement = ast; + var returnExpressionSymbol = _this.resolveAST(returnStatement.expression, false, context).type; + + if (TypeScript.PullHelpers.typeSymbolsAreIdentical(returnExpressionSymbol, funcReturnType)) { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(returnStatement, messageCode, messageArguments)); + } else { + reportOnFuncDecl = true; + } + go = false; + break; + + default: + break; + } + + walker.options.goChildren = go; + return ast; + }; + + TypeScript.getAstWalkerFactory().walk(block, reportErrorOnReturnExpressions); + } + + if (reportOnFuncDecl) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(declAST, messageCode, messageArguments)); + } + } + }; + + PullTypeResolver.prototype.enclosingClassIsDerived = function (classDecl) { + TypeScript.Debug.assert(classDecl.kind === 8 /* Class */); + + var classSymbol = classDecl.getSymbol(); + return classSymbol.getExtendedTypes().length > 0; + }; + + PullTypeResolver.prototype.isSuperInvocationExpression = function (ast) { + if (ast.kind() === 213 /* InvocationExpression */) { + var invocationExpression = ast; + if (invocationExpression.expression.kind() === 50 /* SuperKeyword */) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.isSuperInvocationExpressionStatement = function (node) { + if (node && node.kind() === 149 /* ExpressionStatement */) { + var expressionStatement = node; + if (this.isSuperInvocationExpression(expressionStatement.expression)) { + return true; + } + } + return false; + }; + + PullTypeResolver.prototype.getFirstStatementOfBlockOrNull = function (block) { + if (block && block.statements && block.statements.childCount() > 0) { + return block.statements.childAt(0); + } + + return null; + }; + + PullTypeResolver.prototype.superCallMustBeFirstStatementInConstructor = function (constructorDecl) { + TypeScript.Debug.assert(constructorDecl.kind === 32768 /* ConstructorMethod */); + + if (constructorDecl) { + var enclosingClass = constructorDecl.getParentDecl(); + + var classSymbol = enclosingClass.getSymbol(); + if (classSymbol.getExtendedTypes().length === 0) { + return false; + } + + var classMembers = classSymbol.getMembers(); + for (var i = 0, n1 = classMembers.length; i < n1; i++) { + var member = classMembers[i]; + + if (member.kind === 4096 /* Property */) { + var declarations = member.getDeclarations(); + for (var j = 0, n2 = declarations.length; j < n2; j++) { + var declaration = declarations[j]; + var ast = this.semanticInfoChain.getASTForDecl(declaration); + if (ast.kind() === 242 /* Parameter */) { + return true; + } + + if (ast.kind() === 136 /* MemberVariableDeclaration */) { + var variableDeclarator = ast; + if (variableDeclarator.variableDeclarator.equalsValueClause) { + return true; + } + } + } + } + } + } + + return false; + }; + + PullTypeResolver.prototype.checkForThisCaptureInArrowFunction = function (expression) { + var enclosingDecl = this.getEnclosingDeclForAST(expression); + + var declPath = enclosingDecl.getParentPath(); + + if (declPath.length) { + var inArrowFunction = false; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.kind; + var declFlags = decl.flags; + + if (declKind === 131072 /* FunctionExpression */ && TypeScript.hasFlag(declFlags, 8192 /* ArrowFunction */)) { + inArrowFunction = true; + continue; + } + + if (inArrowFunction) { + if (declKind === 16384 /* Function */ || declKind === 65536 /* Method */ || declKind === 32768 /* ConstructorMethod */ || declKind === 262144 /* GetAccessor */ || declKind === 524288 /* SetAccessor */ || declKind === 131072 /* FunctionExpression */ || declKind === 8 /* Class */ || declKind === 4 /* Container */ || declKind === 32 /* DynamicModule */ || declKind === 1 /* Script */) { + decl.setFlags(decl.flags | 262144 /* MustCaptureThis */); + + if (declKind === 8 /* Class */) { + var constructorSymbol = decl.getSymbol().getConstructorMethod(); + var constructorDecls = constructorSymbol.getDeclarations(); + for (var i = 0; i < constructorDecls.length; i++) { + constructorDecls[i].flags = constructorDecls[i].flags | 262144 /* MustCaptureThis */; + } + } + break; + } + } else if (declKind === 16384 /* Function */ || declKind === 131072 /* FunctionExpression */) { + break; + } + } + } + }; + + PullTypeResolver.prototype.typeCheckMembersAgainstIndexer = function (containerType, containerTypeDecl, context) { + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(containerType, context); + var stringSignature = indexSignatures.stringSignature; + var numberSignature = indexSignatures.numericSignature; + + if (stringSignature || numberSignature) { + var members = containerTypeDecl.getChildDecls(); + for (var i = 0; i < members.length; i++) { + var member = members[i]; + if ((member.name || (member.kind === 4096 /* Property */ && member.name === "")) && member.kind !== 32768 /* ConstructorMethod */ && !TypeScript.hasFlag(member.flags, 16 /* Static */)) { + var memberSymbol = member.getSymbol(); + var relevantSignature = this.determineRelevantIndexerForMember(memberSymbol, numberSignature, stringSignature); + if (relevantSignature) { + var comparisonInfo = new TypeComparisonInfo(); + if (!this.sourceIsAssignableToTarget(memberSymbol.type, relevantSignature.returnType, member.ast(), context, comparisonInfo)) { + this.reportErrorThatMemberIsNotSubtypeOfIndexer(memberSymbol, relevantSignature, member.ast(), context, comparisonInfo); + } + } + } + } + } + }; + + PullTypeResolver.prototype.determineRelevantIndexerForMember = function (member, numberIndexSignature, stringIndexSignature) { + if (numberIndexSignature && TypeScript.PullHelpers.isNameNumeric(member.name)) { + return numberIndexSignature; + } else if (stringIndexSignature) { + return stringIndexSignature; + } + + return null; + }; + + PullTypeResolver.prototype.reportErrorThatMemberIsNotSubtypeOfIndexer = function (member, indexSignature, astForError, context, comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(astForError); + if (indexSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol) { + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); + } + } else { + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_assignable_to_string_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_assignable_to_string_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); + } + } + }; + + PullTypeResolver.prototype.typeCheckIfTypeMemberPropertyOkToOverride = function (typeSymbol, extendedType, typeMember, extendedTypeMember, enclosingDecl, comparisonInfo) { + if (!typeSymbol.isClass()) { + return true; + } + + var typeMemberKind = typeMember.kind; + var extendedMemberKind = extendedTypeMember.kind; + + if (typeMemberKind === extendedMemberKind) { + return true; + } + + var errorCode; + if (typeMemberKind === 4096 /* Property */) { + if (typeMember.isAccessor()) { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } else { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + } else if (typeMemberKind === 65536 /* Method */) { + if (extendedTypeMember.isAccessor()) { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } else { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + + var message = TypeScript.getDiagnosticMessage(errorCode, [typeSymbol.toString(), typeMember.getScopedNameEx().toString(), extendedType.toString()]); + comparisonInfo.addMessage(message); + return false; + }; + + PullTypeResolver.prototype.typeCheckIfTypeExtendsType = function (classOrInterface, name, typeSymbol, extendedType, enclosingDecl, context) { + var typeMembers = typeSymbol.getMembers(); + + var comparisonInfo = new TypeComparisonInfo(); + var foundError = false; + var foundError1 = false; + var foundError2 = false; + + for (var i = 0; i < typeMembers.length; i++) { + var propName = typeMembers[i].name; + var extendedTypeProp = extendedType.findMember(propName, true); + if (extendedTypeProp) { + this.resolveDeclaredSymbol(extendedTypeProp, context); + foundError1 = !this.typeCheckIfTypeMemberPropertyOkToOverride(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, enclosingDecl, comparisonInfo); + + if (!foundError1) { + foundError2 = !this.sourcePropertyIsAssignableToTargetProperty(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, classOrInterface, context, comparisonInfo); + } + + if (foundError1 || foundError2) { + foundError = true; + break; + } + } + } + + if (!foundError && typeSymbol.hasOwnCallSignatures()) { + foundError = !this.sourceCallSignaturesAreAssignableToTargetCallSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + } + + if (!foundError && typeSymbol.hasOwnConstructSignatures()) { + foundError = !this.sourceConstructSignaturesAreAssignableToTargetConstructSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + } + + if (!foundError && typeSymbol.hasOwnIndexSignatures()) { + foundError = !this.sourceIndexSignaturesAreAssignableToTargetIndexSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + } + + if (!foundError && typeSymbol.isClass()) { + var typeConstructorType = typeSymbol.getConstructorMethod().type; + var typeConstructorTypeMembers = typeConstructorType.getMembers(); + if (typeConstructorTypeMembers.length) { + var extendedConstructorType = extendedType.getConstructorMethod().type; + var comparisonInfoForPropTypeCheck = new TypeComparisonInfo(comparisonInfo); + + for (var i = 0; i < typeConstructorTypeMembers.length; i++) { + var propName = typeConstructorTypeMembers[i].name; + var extendedConstructorTypeProp = extendedConstructorType.findMember(propName, true); + if (extendedConstructorTypeProp) { + if (!extendedConstructorTypeProp.isResolved) { + this.resolveDeclaredSymbol(extendedConstructorTypeProp, context); + } + + if (!this.sourcePropertyIsAssignableToTargetProperty(typeConstructorType, extendedConstructorType, typeConstructorTypeMembers[i], extendedConstructorTypeProp, classOrInterface, context, comparisonInfo)) { + foundError = true; + break; + } + } + } + } + } + + if (foundError) { + var errorCode; + if (typeSymbol.isClass()) { + errorCode = TypeScript.DiagnosticCode.Class_0_cannot_extend_class_1_NL_2; + } else { + if (extendedType.isClass()) { + errorCode = TypeScript.DiagnosticCode.Interface_0_cannot_extend_class_1_NL_2; + } else { + errorCode = TypeScript.DiagnosticCode.Interface_0_cannot_extend_interface_1_NL_2; + } + } + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, errorCode, [typeSymbol.getScopedName(), extendedType.getScopedName(), comparisonInfo.message])); + } + }; + + PullTypeResolver.prototype.typeCheckIfClassImplementsType = function (classDecl, classSymbol, implementedType, enclosingDecl, context) { + var comparisonInfo = new TypeComparisonInfo(); + var foundError = !this.sourceMembersAreAssignableToTargetMembers(classSymbol, implementedType, classDecl, context, comparisonInfo); + if (!foundError) { + foundError = !this.sourceCallSignaturesAreAssignableToTargetCallSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + if (!foundError) { + foundError = !this.sourceConstructSignaturesAreAssignableToTargetConstructSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + if (!foundError) { + foundError = !this.sourceIndexSignaturesAreAssignableToTargetIndexSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + } + } + } + + if (foundError) { + var enclosingSymbol = this.getEnclosingSymbolForAST(classDecl); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(classDecl.identifier, TypeScript.DiagnosticCode.Class_0_declares_interface_1_but_does_not_implement_it_NL_2, [classSymbol.getScopedName(enclosingSymbol), implementedType.getScopedName(enclosingSymbol), comparisonInfo.message])); + } + }; + + PullTypeResolver.prototype.computeValueSymbolFromAST = function (valueDeclAST, context) { + var prevInTypeCheck = context.inTypeCheck; + context.inTypeCheck = false; + + var typeSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(valueDeclAST); + + if (valueDeclAST.kind() == 11 /* IdentifierName */) { + var valueSymbol = this.computeNameExpression(valueDeclAST, context); + } else { + TypeScript.Debug.assert(valueDeclAST.kind() == 121 /* QualifiedName */); + var qualifiedName = valueDeclAST; + + var lhs = this.computeValueSymbolFromAST(qualifiedName.left, context); + var valueSymbol = this.computeDottedNameExpressionFromLHS(lhs.symbol, qualifiedName.left, qualifiedName.right, context, false); + } + var valueSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(valueDeclAST); + + this.semanticInfoChain.setAliasSymbolForAST(valueDeclAST, typeSymbolAlias); + context.inTypeCheck = prevInTypeCheck; + + return { symbol: valueSymbol, alias: valueSymbolAlias }; + }; + + PullTypeResolver.prototype.hasClassTypeSymbolConflictAsValue = function (baseDeclAST, typeSymbol, enclosingDecl, context) { + var typeSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(baseDeclAST); + + var valueDeclAST = baseDeclAST.kind() == 126 /* GenericType */ ? baseDeclAST.name : baseDeclAST; + var valueSymbolInfo = this.computeValueSymbolFromAST(valueDeclAST, context); + var valueSymbol = valueSymbolInfo.symbol; + var valueSymbolAlias = valueSymbolInfo.alias; + + if (typeSymbolAlias && valueSymbolAlias) { + return typeSymbolAlias !== valueSymbolAlias; + } + + if (!valueSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */)) { + return true; + } + + var associatedContainerType = valueSymbol.type ? valueSymbol.type.getAssociatedContainerType() : null; + + if (associatedContainerType) { + return associatedContainerType !== typeSymbol.getRootSymbol(); + } + + return true; + }; + + PullTypeResolver.prototype.typeCheckBase = function (classOrInterface, name, typeSymbol, baseDeclAST, isExtendedType, enclosingDecl, context) { + var _this = this; + var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); + + var baseType = this.resolveTypeReference(baseDeclAST, context).type; + + if (!baseType) { + return; + } + + var typeDeclIsClass = typeSymbol.isClass(); + + if (!typeSymbol.isValidBaseKind(baseType, isExtendedType)) { + if (!baseType.isError()) { + if (isExtendedType) { + if (typeDeclIsClass) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.A_class_may_only_extend_another_class)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.An_interface_may_only_extend_another_class_or_interface)); + } + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.A_class_may_only_implement_another_class_or_interface)); + } + } + return; + } else if (typeDeclIsClass && isExtendedType) { + if (this.hasClassTypeSymbolConflictAsValue(baseDeclAST, baseType, enclosingDecl, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_1, [TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(baseDeclAST.kind() == 126 /* GenericType */ ? baseDeclAST.name : baseDeclAST), baseType.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + } + } + + if (baseType.hasBase(typeSymbol)) { + typeSymbol.setHasBaseTypeConflict(); + baseType.setHasBaseTypeConflict(); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, typeDeclIsClass ? TypeScript.DiagnosticCode.Class_0_is_recursively_referenced_as_a_base_type_of_itself : TypeScript.DiagnosticCode.Interface_0_is_recursively_referenced_as_a_base_type_of_itself, [typeSymbol.getScopedName()])); + return; + } + + if (isExtendedType) { + this.typeCheckCallBacks.push(function (context) { + return _this.typeCheckIfTypeExtendsType(classOrInterface, name, typeSymbol, baseType, enclosingDecl, context); + }); + } else { + TypeScript.Debug.assert(classOrInterface.kind() === 131 /* ClassDeclaration */); + + this.typeCheckCallBacks.push(function (context) { + return _this.typeCheckIfClassImplementsType(classOrInterface, typeSymbol, baseType, enclosingDecl, context); + }); + } + + this.checkSymbolPrivacy(typeSymbol, baseType, function (errorSymbol) { + return _this.baseListPrivacyErrorReporter(classOrInterface, typeSymbol, baseDeclAST, isExtendedType, errorSymbol, context); + }); + }; + + PullTypeResolver.prototype.typeCheckBases = function (classOrInterface, name, heritageClauses, typeSymbol, enclosingDecl, context) { + var _this = this; + var extendsClause = TypeScript.ASTHelpers.getExtendsHeritageClause(heritageClauses); + var implementsClause = TypeScript.ASTHelpers.getImplementsHeritageClause(heritageClauses); + if (!extendsClause && !implementsClause) { + return; + } + + if (extendsClause) { + for (var i = 0; i < extendsClause.typeNames.nonSeparatorCount(); i++) { + this.typeCheckBase(classOrInterface, name, typeSymbol, extendsClause.typeNames.nonSeparatorAt(i), true, enclosingDecl, context); + } + } + + if (typeSymbol.isClass()) { + if (implementsClause) { + for (var i = 0; i < implementsClause.typeNames.nonSeparatorCount(); i++) { + this.typeCheckBase(classOrInterface, name, typeSymbol, implementsClause.typeNames.nonSeparatorAt(i), false, enclosingDecl, context); + } + } + } else if (extendsClause && !typeSymbol.hasBaseTypeConflict() && typeSymbol.getExtendedTypes().length > 1) { + var firstInterfaceASTWithExtendsClause = TypeScript.ArrayUtilities.firstOrDefault(typeSymbol.getDeclarations(), function (decl) { + return decl.ast().heritageClauses !== null; + }).ast(); + if (classOrInterface === firstInterfaceASTWithExtendsClause) { + this.typeCheckCallBacks.push(function (context) { + _this.checkTypeCompatibilityBetweenBases(classOrInterface.identifier, typeSymbol, context); + }); + } + } + }; + + PullTypeResolver.prototype.checkTypeCompatibilityBetweenBases = function (name, typeSymbol, context) { + var derivedIndexSignatures = typeSymbol.getOwnIndexSignatures(); + + var inheritedMembersMap = TypeScript.createIntrinsicsObject(); + var inheritedIndexSignatures = new InheritedIndexSignatureInfo(); + + var typeHasOwnNumberIndexer = false; + var typeHasOwnStringIndexer = false; + + if (typeSymbol.hasOwnIndexSignatures()) { + var ownIndexSignatures = typeSymbol.getOwnIndexSignatures(); + for (var i = 0; i < ownIndexSignatures.length; i++) { + if (ownIndexSignatures[i].parameters[0].type === this.semanticInfoChain.numberTypeSymbol) { + typeHasOwnNumberIndexer = true; + } else { + typeHasOwnStringIndexer = true; + } + } + } + var baseTypes = typeSymbol.getExtendedTypes(); + for (var i = 0; i < baseTypes.length; i++) { + if (this.checkNamedPropertyIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedMembersMap, context) || this.checkIndexSignatureIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedIndexSignatures, typeHasOwnNumberIndexer, typeHasOwnStringIndexer, context)) { + return; + } + } + + if (this.checkThatInheritedNumberSignatureIsSubtypeOfInheritedStringSignature(name, typeSymbol, inheritedIndexSignatures, context)) { + return; + } + + this.checkInheritedMembersAgainstInheritedIndexSignatures(name, typeSymbol, inheritedIndexSignatures, inheritedMembersMap, context); + }; + + PullTypeResolver.prototype.checkNamedPropertyIdentityBetweenBases = function (interfaceName, interfaceSymbol, baseTypeSymbol, inheritedMembersMap, context) { + var baseMembers = baseTypeSymbol.getAllMembers(4096 /* Property */ | 65536 /* Method */, 0 /* all */); + for (var i = 0; i < baseMembers.length; i++) { + var member = baseMembers[i]; + var memberName = member.name; + + if (interfaceSymbol.findMember(memberName, false)) { + continue; + } + + this.resolveDeclaredSymbol(member, context); + + if (inheritedMembersMap[memberName]) { + var prevMember = inheritedMembersMap[memberName]; + if (prevMember.baseOrigin !== baseTypeSymbol && !this.propertiesAreIdenticalWithNewEnclosingTypes(baseTypeSymbol, prevMember.baseOrigin, member, prevMember.memberSymbol, context)) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Named_properties_0_of_types_1_and_2_are_not_identical, [memberName, prevMember.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), prevMember.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); + return true; + } + } else { + inheritedMembersMap[memberName] = new MemberWithBaseOrigin(member, baseTypeSymbol); + } + } + + return false; + }; + + PullTypeResolver.prototype.checkIndexSignatureIdentityBetweenBases = function (interfaceName, interfaceSymbol, baseTypeSymbol, allInheritedSignatures, derivedTypeHasOwnNumberSignature, derivedTypeHasOwnStringSignature, context) { + if (derivedTypeHasOwnNumberSignature && derivedTypeHasOwnStringSignature) { + return false; + } + + var indexSignaturesFromThisBaseType = baseTypeSymbol.getIndexSignatures(); + for (var i = 0; i < indexSignaturesFromThisBaseType.length; i++) { + var currentInheritedSignature = indexSignaturesFromThisBaseType[i]; + + var parameterTypeIsString = currentInheritedSignature.parameters[0].type === this.semanticInfoChain.stringTypeSymbol; + var parameterTypeIsNumber = currentInheritedSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol; + + if (parameterTypeIsString && derivedTypeHasOwnStringSignature || parameterTypeIsNumber && derivedTypeHasOwnNumberSignature) { + continue; + } + + if (parameterTypeIsString) { + if (allInheritedSignatures.stringSignatureWithBaseOrigin) { + if (allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.stringSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType, context)) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_string_indexer_of_types_0_and_1_are_not_identical, [allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); + return true; + } + } else { + allInheritedSignatures.stringSignatureWithBaseOrigin = new SignatureWithBaseOrigin(currentInheritedSignature, baseTypeSymbol); + } + } else if (parameterTypeIsNumber) { + if (allInheritedSignatures.numberSignatureWithBaseOrigin) { + if (allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.numberSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType, context)) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_number_indexer_of_types_0_and_1_are_not_identical, [allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); + return true; + } + } else { + allInheritedSignatures.numberSignatureWithBaseOrigin = new SignatureWithBaseOrigin(currentInheritedSignature, baseTypeSymbol); + } + } + } + + return false; + }; + + PullTypeResolver.prototype.checkInheritedMembersAgainstInheritedIndexSignatures = function (interfaceName, interfaceSymbol, inheritedIndexSignatures, inheritedMembers, context) { + if (!inheritedIndexSignatures.stringSignatureWithBaseOrigin && !inheritedIndexSignatures.numberSignatureWithBaseOrigin) { + return false; + } + + var comparisonInfo = new TypeComparisonInfo(); + var stringSignature = inheritedIndexSignatures.stringSignatureWithBaseOrigin && inheritedIndexSignatures.stringSignatureWithBaseOrigin.signature; + var numberSignature = inheritedIndexSignatures.numberSignatureWithBaseOrigin && inheritedIndexSignatures.numberSignatureWithBaseOrigin.signature; + for (var memberName in inheritedMembers) { + var memberWithBaseOrigin = inheritedMembers[memberName]; + if (!memberWithBaseOrigin) { + continue; + } + + var relevantSignature = this.determineRelevantIndexerForMember(memberWithBaseOrigin.memberSymbol, numberSignature, stringSignature); + if (!relevantSignature) { + continue; + } + + var relevantSignatureIsNumberSignature = relevantSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol; + var signatureBaseOrigin = relevantSignatureIsNumberSignature ? inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin : inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin; + + if (signatureBaseOrigin === memberWithBaseOrigin.baseOrigin) { + continue; + } + + var memberIsSubtype = this.sourceIsAssignableToTarget(memberWithBaseOrigin.memberSymbol.type, relevantSignature.returnType, interfaceName, context, comparisonInfo); + + if (!memberIsSubtype) { + var enclosingSymbol = this.getEnclosingSymbolForAST(interfaceName); + if (relevantSignatureIsNumberSignature) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_assignable_to_number_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(enclosingSymbol), memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); + } else { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_assignable_to_string_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(enclosingSymbol), memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); + } + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.checkThatInheritedNumberSignatureIsSubtypeOfInheritedStringSignature = function (interfaceName, interfaceSymbol, inheritedIndexSignatures, context) { + if (inheritedIndexSignatures.numberSignatureWithBaseOrigin && inheritedIndexSignatures.stringSignatureWithBaseOrigin) { + if (inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin === inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin) { + return false; + } + + var comparisonInfo = new TypeComparisonInfo(); + var signatureIsSubtype = this.sourceIsAssignableToTarget(inheritedIndexSignatures.numberSignatureWithBaseOrigin.signature.returnType, inheritedIndexSignatures.stringSignatureWithBaseOrigin.signature.returnType, interfaceName, context, comparisonInfo); + + if (!signatureIsSubtype) { + var enclosingSymbol = this.getEnclosingSymbolForAST(interfaceName); + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_number_indexer_in_type_0_is_not_assignable_to_string_indexer_type_in_type_1_NL_2, [ + inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), + inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [ + interfaceSymbol.getDisplayName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), + inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.checkAssignability = function (ast, source, target, context) { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(source, target, ast, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)])); + } + } + }; + + PullTypeResolver.prototype.isReference = function (ast, astSymbol) { + if (ast.kind() === 217 /* ParenthesizedExpression */) { + return this.isReference(ast.expression, astSymbol); + } + + if (ast.kind() !== 11 /* IdentifierName */ && ast.kind() !== 212 /* MemberAccessExpression */ && ast.kind() !== 221 /* ElementAccessExpression */) { + return false; + } + + if (ast.kind() === 11 /* IdentifierName */) { + if (astSymbol.kind === 512 /* Variable */ && astSymbol.anyDeclHasFlag(4096 /* Enum */)) { + return false; + } + + if (astSymbol.kind === 512 /* Variable */ && astSymbol.anyDeclHasFlag(102400 /* SomeInitializedModule */)) { + return false; + } + + if (astSymbol.kind === 32768 /* ConstructorMethod */ || astSymbol.kind === 16384 /* Function */) { + return false; + } + } + + if (ast.kind() === 212 /* MemberAccessExpression */ && astSymbol.kind === 67108864 /* EnumMember */) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.checkForSuperMemberAccess = function (expression, name, resolvedName, context) { + if (resolvedName) { + if (expression.kind() === 50 /* SuperKeyword */ && !resolvedName.isError() && resolvedName.kind !== 65536 /* Method */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword)); + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.getEnclosingDeclForAST = function (ast) { + return this.semanticInfoChain.getEnclosingDecl(ast); + }; + + PullTypeResolver.prototype.getEnclosingSymbolForAST = function (ast) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + return enclosingDecl ? enclosingDecl.getSymbol() : null; + }; + + PullTypeResolver.prototype.checkForPrivateMemberAccess = function (name, expressionType, resolvedName, context) { + if (resolvedName) { + if (resolvedName.anyDeclHasFlag(2 /* Private */)) { + var memberContainer = resolvedName.getContainer(); + if (memberContainer && memberContainer.kind === 33554432 /* ConstructorType */) { + memberContainer = memberContainer.getAssociatedContainerType(); + } + + if (memberContainer && memberContainer.isClass()) { + var memberClass = memberContainer.getDeclarations()[0].ast(); + TypeScript.Debug.assert(memberClass); + + var containingClass = this.getEnclosingClassDeclaration(name); + + if (!containingClass || containingClass !== memberClass) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode._0_1_is_inaccessible, [memberContainer.toString(null, false), name.text()])); + return true; + } + } + } + } + + return false; + }; + + PullTypeResolver.prototype.instantiateType = function (type, typeParameterArgumentMap) { + if (type.isPrimitive()) { + return type; + } + + if (type.isError()) { + return type; + } + + if (typeParameterArgumentMap[type.pullSymbolID]) { + return typeParameterArgumentMap[type.pullSymbolID]; + } + + type._resolveDeclaredSymbol(); + if (type.isTypeParameter()) { + return this.instantiateTypeParameter(type, typeParameterArgumentMap); + } + + if (type.wrapsSomeTypeParameter(typeParameterArgumentMap)) { + return TypeScript.PullInstantiatedTypeReferenceSymbol.create(this, type, typeParameterArgumentMap); + } + + return type; + }; + + PullTypeResolver.prototype.instantiateTypeParameter = function (typeParameter, typeParameterArgumentMap) { + var constraint = typeParameter.getConstraint(); + if (!constraint) { + return typeParameter; + } + + var instantiatedConstraint = this.instantiateType(constraint, typeParameterArgumentMap); + + if (instantiatedConstraint == constraint) { + return typeParameter; + } + + var rootTypeParameter = typeParameter.getRootSymbol(); + var instantiation = rootTypeParameter.getSpecialization([instantiatedConstraint]); + if (instantiation) { + return instantiation; + } + + instantiation = new TypeScript.PullInstantiatedTypeParameterSymbol(rootTypeParameter, instantiatedConstraint); + return instantiation; + }; + + PullTypeResolver.prototype.instantiateSignature = function (signature, typeParameterArgumentMap) { + if (!signature.wrapsSomeTypeParameter(typeParameterArgumentMap)) { + return signature; + } + + var rootSignature = signature.getRootSymbol(); + var mutableTypeParameterMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(typeParameterArgumentMap); + TypeScript.PullInstantiationHelpers.instantiateTypeArgument(this, signature, mutableTypeParameterMap); + + var instantiatedSignature = rootSignature.getSpecialization(mutableTypeParameterMap.typeParameterArgumentMap); + if (instantiatedSignature) { + return instantiatedSignature; + } + + TypeScript.PullInstantiationHelpers.cleanUpTypeArgumentMap(signature, mutableTypeParameterMap); + typeParameterArgumentMap = mutableTypeParameterMap.typeParameterArgumentMap; + + instantiatedSignature = new TypeScript.PullInstantiatedSignatureSymbol(rootSignature, typeParameterArgumentMap); + + instantiatedSignature.returnType = this.instantiateType((rootSignature.returnType || this.semanticInfoChain.anyTypeSymbol), typeParameterArgumentMap); + instantiatedSignature.functionType = this.instantiateType(rootSignature.functionType, typeParameterArgumentMap); + + var parameters = rootSignature.parameters; + var parameter = null; + + if (parameters) { + for (var j = 0; j < parameters.length; j++) { + parameter = new TypeScript.PullSymbol(parameters[j].name, 2048 /* Parameter */); + parameter.setRootSymbol(parameters[j]); + + if (parameters[j].isOptional) { + parameter.isOptional = true; + } + if (parameters[j].isVarArg) { + parameter.isVarArg = true; + instantiatedSignature.hasVarArgs = true; + } + instantiatedSignature.addParameter(parameter, parameter.isOptional); + + parameter.type = this.instantiateType(parameters[j].type, typeParameterArgumentMap); + } + } + + return instantiatedSignature; + }; + PullTypeResolver.globalTypeCheckPhase = 0; + return PullTypeResolver; + })(); + TypeScript.PullTypeResolver = PullTypeResolver; + + var TypeComparisonInfo = (function () { + function TypeComparisonInfo(sourceComparisonInfo, useSameIndent) { + this.onlyCaptureFirstError = false; + this.flags = 0 /* SuccessfulComparison */; + this.message = ""; + this.stringConstantVal = null; + this.indent = 1; + if (sourceComparisonInfo) { + this.flags = sourceComparisonInfo.flags; + this.onlyCaptureFirstError = sourceComparisonInfo.onlyCaptureFirstError; + this.stringConstantVal = sourceComparisonInfo.stringConstantVal; + this.indent = sourceComparisonInfo.indent; + if (!useSameIndent) { + this.indent++; + } + } + } + TypeComparisonInfo.prototype.indentString = function () { + var result = ""; + + for (var i = 0; i < this.indent; i++) { + result += "\t"; + } + + return result; + }; + + TypeComparisonInfo.prototype.addMessage = function (message) { + if (!this.onlyCaptureFirstError && this.message) { + this.message = this.message + TypeScript.newLine() + this.indentString() + message; + } else { + this.message = this.indentString() + message; + } + }; + return TypeComparisonInfo; + })(); + TypeScript.TypeComparisonInfo = TypeComparisonInfo; + + function getPropertyAssignmentNameTextFromIdentifier(identifier) { + if (identifier.kind() === 11 /* IdentifierName */) { + return { actualText: identifier.text(), memberName: identifier.valueText() }; + } else if (identifier.kind() === 14 /* StringLiteral */) { + return { actualText: identifier.text(), memberName: identifier.valueText() }; + } else if (identifier.kind() === 13 /* NumericLiteral */) { + return { actualText: identifier.text(), memberName: identifier.valueText() }; + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + TypeScript.getPropertyAssignmentNameTextFromIdentifier = getPropertyAssignmentNameTextFromIdentifier; + + function isTypesOnlyLocation(ast) { + while (ast && ast.parent) { + switch (ast.parent.kind()) { + case 244 /* TypeAnnotation */: + return true; + case 127 /* TypeQuery */: + return false; + case 125 /* ConstructorType */: + var constructorType = ast.parent; + if (constructorType.type === ast) { + return true; + } + break; + case 123 /* FunctionType */: + var functionType = ast.parent; + if (functionType.type === ast) { + return true; + } + break; + case 239 /* Constraint */: + var constraint = ast.parent; + if (constraint.type === ast) { + return true; + } + break; + case 220 /* CastExpression */: + var castExpression = ast.parent; + return castExpression.type === ast; + case 230 /* ExtendsHeritageClause */: + case 231 /* ImplementsHeritageClause */: + return true; + case 228 /* TypeArgumentList */: + return true; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + case 129 /* FunctionDeclaration */: + case 145 /* MethodSignature */: + case 212 /* MemberAccessExpression */: + case 242 /* Parameter */: + return false; + } + + ast = ast.parent; + } + + return false; + } + TypeScript.isTypesOnlyLocation = isTypesOnlyLocation; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.declCacheHit = 0; + TypeScript.declCacheMiss = 0; + TypeScript.symbolCacheHit = 0; + TypeScript.symbolCacheMiss = 0; + + var sentinalEmptyArray = []; + + var SemanticInfoChain = (function () { + function SemanticInfoChain(compiler, logger) { + this.compiler = compiler; + this.logger = logger; + this.documents = []; + this.fileNameToDocument = TypeScript.createIntrinsicsObject(); + this.anyTypeDecl = null; + this.booleanTypeDecl = null; + this.numberTypeDecl = null; + this.stringTypeDecl = null; + this.nullTypeDecl = null; + this.undefinedTypeDecl = null; + this.voidTypeDecl = null; + this.undefinedValueDecl = null; + this.anyTypeSymbol = null; + this.booleanTypeSymbol = null; + this.numberTypeSymbol = null; + this.stringTypeSymbol = null; + this.nullTypeSymbol = null; + this.undefinedTypeSymbol = null; + this.voidTypeSymbol = null; + this.undefinedValueSymbol = null; + this.emptyTypeSymbol = null; + this.astSymbolMap = []; + this.astAliasSymbolMap = []; + this.astCallResolutionDataMap = []; + this.declSymbolMap = []; + this.declSignatureSymbolMap = []; + this.declCache = null; + this.symbolCache = null; + this.fileNameToDiagnostics = null; + this._binder = null; + this._resolver = null; + this._topLevelDecls = null; + this._fileNames = null; + var globalDecl = new TypeScript.RootPullDecl("", "", 0 /* Global */, 0 /* None */, this, false); + this.documents[0] = new TypeScript.Document(this.compiler, this, "", [], null, 0 /* None */, 0, false, null, globalDecl); + + this.anyTypeDecl = new TypeScript.NormalPullDecl("any", "any", 2 /* Primitive */, 0 /* None */, globalDecl); + this.booleanTypeDecl = new TypeScript.NormalPullDecl("boolean", "boolean", 2 /* Primitive */, 0 /* None */, globalDecl); + this.numberTypeDecl = new TypeScript.NormalPullDecl("number", "number", 2 /* Primitive */, 0 /* None */, globalDecl); + this.stringTypeDecl = new TypeScript.NormalPullDecl("string", "string", 2 /* Primitive */, 0 /* None */, globalDecl); + this.voidTypeDecl = new TypeScript.NormalPullDecl("void", "void", 2 /* Primitive */, 0 /* None */, globalDecl); + + this.nullTypeDecl = new TypeScript.RootPullDecl("null", "", 2 /* Primitive */, 0 /* None */, this, false); + this.undefinedTypeDecl = new TypeScript.RootPullDecl("undefined", "", 2 /* Primitive */, 0 /* None */, this, false); + this.undefinedValueDecl = new TypeScript.NormalPullDecl("undefined", "undefined", 512 /* Variable */, 8 /* Ambient */, globalDecl); + + this.invalidate(); + } + SemanticInfoChain.prototype.getDocument = function (fileName) { + var document = this.fileNameToDocument[fileName]; + return document || null; + }; + + SemanticInfoChain.prototype.lineMap = function (fileName) { + return this.getDocument(fileName).lineMap(); + }; + + SemanticInfoChain.prototype.fileNames = function () { + if (this._fileNames === null) { + this._fileNames = this.documents.slice(1).map(function (s) { + return s.fileName; + }); + } + + return this._fileNames; + }; + + SemanticInfoChain.prototype.bindPrimitiveSymbol = function (decl, newSymbol) { + newSymbol.addDeclaration(decl); + decl.setSymbol(newSymbol); + newSymbol.setResolved(); + + return newSymbol; + }; + + SemanticInfoChain.prototype.addPrimitiveTypeSymbol = function (decl) { + var newSymbol = new TypeScript.PullPrimitiveTypeSymbol(decl.name); + return this.bindPrimitiveSymbol(decl, newSymbol); + }; + + SemanticInfoChain.prototype.addPrimitiveValueSymbol = function (decl, type) { + var newSymbol = new TypeScript.PullSymbol(decl.name, 512 /* Variable */); + newSymbol.type = type; + return this.bindPrimitiveSymbol(decl, newSymbol); + }; + + SemanticInfoChain.prototype.resetGlobalSymbols = function () { + this.anyTypeSymbol = this.addPrimitiveTypeSymbol(this.anyTypeDecl); + this.booleanTypeSymbol = this.addPrimitiveTypeSymbol(this.booleanTypeDecl); + this.numberTypeSymbol = this.addPrimitiveTypeSymbol(this.numberTypeDecl); + this.stringTypeSymbol = this.addPrimitiveTypeSymbol(this.stringTypeDecl); + this.voidTypeSymbol = this.addPrimitiveTypeSymbol(this.voidTypeDecl); + this.nullTypeSymbol = this.addPrimitiveTypeSymbol(this.nullTypeDecl); + this.undefinedTypeSymbol = this.addPrimitiveTypeSymbol(this.undefinedTypeDecl); + this.undefinedValueSymbol = this.addPrimitiveValueSymbol(this.undefinedValueDecl, this.undefinedTypeSymbol); + + var emptyTypeDecl = new TypeScript.PullSynthesizedDecl("{}", "{}", 8388608 /* ObjectType */, 0 /* None */, null, this); + var emptyTypeSymbol = new TypeScript.PullTypeSymbol("{}", 8388608 /* ObjectType */); + emptyTypeDecl.setSymbol(emptyTypeSymbol); + emptyTypeSymbol.addDeclaration(emptyTypeDecl); + emptyTypeSymbol.setResolved(); + this.emptyTypeSymbol = emptyTypeSymbol; + }; + + SemanticInfoChain.prototype.addDocument = function (document) { + var fileName = document.fileName; + + var existingIndex = TypeScript.ArrayUtilities.indexOf(this.documents, function (u) { + return u.fileName === fileName; + }); + if (existingIndex < 0) { + this.documents.push(document); + } else { + this.documents[existingIndex] = document; + } + + this.fileNameToDocument[fileName] = document; + + this.invalidate(); + }; + + SemanticInfoChain.prototype.removeDocument = function (fileName) { + TypeScript.Debug.assert(fileName !== "", "Can't remove the semantic info for the global decl."); + var index = TypeScript.ArrayUtilities.indexOf(this.documents, function (u) { + return u.fileName === fileName; + }); + if (index > 0) { + this.fileNameToDocument[fileName] = undefined; + this.documents.splice(index, 1); + this.invalidate(); + } + }; + + SemanticInfoChain.prototype.getDeclPathCacheID = function (declPath, declKind) { + var cacheID = ""; + + for (var i = 0; i < declPath.length; i++) { + cacheID += "#" + declPath[i]; + } + + return cacheID + "#" + declKind.toString(); + }; + + SemanticInfoChain.prototype.findTopLevelSymbol = function (name, kind, doNotGoPastThisDecl) { + var cacheID = this.getDeclPathCacheID([name], kind); + + var symbol = this.symbolCache[cacheID]; + + if (!symbol) { + for (var i = 0, n = this.documents.length; i < n; i++) { + var topLevelDecl = this.documents[i].topLevelDecl(); + + var symbol = this.findTopLevelSymbolInDecl(topLevelDecl, name, kind, doNotGoPastThisDecl); + if (symbol) { + break; + } + + if (doNotGoPastThisDecl && topLevelDecl.name === doNotGoPastThisDecl.fileName()) { + return null; + } + } + + if (symbol) { + this.symbolCache[cacheID] = symbol; + } + } + + return symbol; + }; + + SemanticInfoChain.prototype.findTopLevelSymbolInDecl = function (topLevelDecl, name, kind, doNotGoPastThisDecl) { + var doNotGoPastThisPosition = doNotGoPastThisDecl && doNotGoPastThisDecl.fileName() === topLevelDecl.fileName() ? doNotGoPastThisDecl.ast().start() : -1; + + var foundDecls = topLevelDecl.searchChildDecls(name, kind); + + for (var j = 0; j < foundDecls.length; j++) { + var foundDecl = foundDecls[j]; + + if (doNotGoPastThisPosition !== -1 && foundDecl.ast() && foundDecl.ast().start() > doNotGoPastThisPosition) { + break; + } + + var symbol = foundDecls[j].getSymbol(); + if (symbol) { + return symbol; + } + } + + return null; + }; + + SemanticInfoChain.prototype.findExternalModule = function (id) { + id = TypeScript.normalizePath(id); + + var tsFile = id + ".ts"; + var tsCacheID = this.getDeclPathCacheID([tsFile], 32 /* DynamicModule */); + symbol = this.symbolCache[tsCacheID]; + if (symbol != undefined) { + return symbol; + } + + var dtsFile = id + ".d.ts"; + var dtsCacheID = this.getDeclPathCacheID([dtsFile], 32 /* DynamicModule */); + var symbol = this.symbolCache[dtsCacheID]; + if (symbol) { + return symbol; + } + + var dtsSymbol; + for (var i = 0; i < this.documents.length; i++) { + var document = this.documents[i]; + var topLevelDecl = document.topLevelDecl(); + + if (topLevelDecl.isExternalModule()) { + var isTsFile = document.fileName === tsFile; + if (isTsFile || document.fileName === dtsFile) { + var dynamicModuleDecl = topLevelDecl.getChildDecls()[0]; + symbol = dynamicModuleDecl.getSymbol(); + + if (isTsFile) { + this.symbolCache[tsCacheID] = symbol; + + return symbol; + } else { + dtsSymbol = symbol; + } + } + } + } + + if (dtsSymbol) { + this.symbolCache[dtsCacheID] = symbol; + return dtsSymbol; + } + + this.symbolCache[dtsCacheID] = null; + this.symbolCache[tsCacheID] = null; + + return null; + }; + + SemanticInfoChain.prototype.findAmbientExternalModuleInGlobalContext = function (id) { + var cacheID = this.getDeclPathCacheID([id], 32 /* DynamicModule */); + + var symbol = this.symbolCache[cacheID]; + if (symbol == undefined) { + symbol = null; + for (var i = 0; i < this.documents.length; i++) { + var document = this.documents[i]; + var topLevelDecl = document.topLevelDecl(); + + if (!topLevelDecl.isExternalModule()) { + var dynamicModules = topLevelDecl.searchChildDecls(id, 32 /* DynamicModule */); + if (dynamicModules.length) { + symbol = dynamicModules[0].getSymbol(); + break; + } + } + } + + this.symbolCache[cacheID] = symbol; + } + + return symbol; + }; + + SemanticInfoChain.prototype.findDecls = function (declPath, declKind) { + var cacheID = this.getDeclPathCacheID(declPath, declKind); + + if (declPath.length) { + var cachedDecls = this.declCache[cacheID]; + + if (cachedDecls && cachedDecls.length) { + TypeScript.declCacheHit++; + return cachedDecls; + } + } + + TypeScript.declCacheMiss++; + + var declsToSearch = this.topLevelDecls(); + + var decls = TypeScript.sentinelEmptyArray; + var path; + var foundDecls = TypeScript.sentinelEmptyArray; + + for (var i = 0; i < declPath.length; i++) { + path = declPath[i]; + decls = TypeScript.sentinelEmptyArray; + + var kind = (i === declPath.length - 1) ? declKind : 164 /* SomeContainer */; + for (var j = 0; j < declsToSearch.length; j++) { + foundDecls = declsToSearch[j].searchChildDecls(path, kind); + + for (var k = 0; k < foundDecls.length; k++) { + if (decls === TypeScript.sentinelEmptyArray) { + decls = []; + } + decls[decls.length] = foundDecls[k]; + } + } + + declsToSearch = decls; + + if (!declsToSearch) { + break; + } + } + + if (decls.length) { + this.declCache[cacheID] = decls; + } + + return decls; + }; + + SemanticInfoChain.prototype.findDeclsFromPath = function (declPath, declKind) { + var declString = []; + + for (var i = 0, n = declPath.length; i < n; i++) { + if (declPath[i].kind & 1 /* Script */) { + continue; + } + + declString.push(declPath[i].name); + } + + return this.findDecls(declString, declKind); + }; + + SemanticInfoChain.prototype.findSymbol = function (declPath, declType) { + var cacheID = this.getDeclPathCacheID(declPath, declType); + + if (declPath.length) { + var cachedSymbol = this.symbolCache[cacheID]; + + if (cachedSymbol) { + TypeScript.symbolCacheHit++; + return cachedSymbol; + } + } + + TypeScript.symbolCacheMiss++; + + var decls = this.findDecls(declPath, declType); + var symbol = null; + + if (decls.length) { + var decl = decls[0]; + if (TypeScript.hasFlag(decl.kind, 164 /* SomeContainer */)) { + var valueDecl = decl.getValueDecl(); + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + } + symbol = decl.getSymbol(); + + if (symbol) { + for (var i = 1; i < decls.length; i++) { + decls[i].ensureSymbolIsBound(); + } + + this.symbolCache[cacheID] = symbol; + } + } + + return symbol; + }; + + SemanticInfoChain.prototype.cacheGlobalSymbol = function (symbol, kind) { + var cacheID1 = this.getDeclPathCacheID([symbol.name], kind); + var cacheID2 = this.getDeclPathCacheID([symbol.name], symbol.kind); + + if (!this.symbolCache[cacheID1]) { + this.symbolCache[cacheID1] = symbol; + } + + if (!this.symbolCache[cacheID2]) { + this.symbolCache[cacheID2] = symbol; + } + }; + + SemanticInfoChain.prototype.invalidate = function (oldSettings, newSettings) { + if (typeof oldSettings === "undefined") { oldSettings = null; } + if (typeof newSettings === "undefined") { newSettings = null; } + TypeScript.PullTypeResolver.globalTypeCheckPhase++; + + var cleanStart = new Date().getTime(); + + this.astSymbolMap.length = 0; + this.astAliasSymbolMap.length = 0; + this.astCallResolutionDataMap.length = 0; + + this.declCache = TypeScript.createIntrinsicsObject(); + this.symbolCache = TypeScript.createIntrinsicsObject(); + this.fileNameToDiagnostics = TypeScript.createIntrinsicsObject(); + this._binder = null; + this._resolver = null; + this._topLevelDecls = null; + this._fileNames = null; + + this.declSymbolMap.length = 0; + this.declSignatureSymbolMap.length = 0; + + if (oldSettings && newSettings) { + if (this.settingsChangeAffectsSyntax(oldSettings, newSettings)) { + for (var i = 1, n = this.documents.length; i < n; i++) { + this.documents[i].invalidate(); + } + } + } + + TypeScript.pullSymbolID = 0; + + this.resetGlobalSymbols(); + + var cleanEnd = new Date().getTime(); + }; + + SemanticInfoChain.prototype.settingsChangeAffectsSyntax = function (before, after) { + return before.allowAutomaticSemicolonInsertion() !== after.allowAutomaticSemicolonInsertion() || before.codeGenTarget() !== after.codeGenTarget() || before.propagateEnumConstants() !== after.propagateEnumConstants(); + }; + + SemanticInfoChain.prototype.setSymbolForAST = function (ast, symbol) { + this.astSymbolMap[ast.syntaxID()] = symbol; + }; + + SemanticInfoChain.prototype.getSymbolForAST = function (ast) { + return this.astSymbolMap[ast.syntaxID()] || null; + }; + + SemanticInfoChain.prototype.setAliasSymbolForAST = function (ast, symbol) { + this.astAliasSymbolMap[ast.syntaxID()] = symbol; + }; + + SemanticInfoChain.prototype.getAliasSymbolForAST = function (ast) { + return this.astAliasSymbolMap[ast.syntaxID()]; + }; + + SemanticInfoChain.prototype.getCallResolutionDataForAST = function (ast) { + return this.astCallResolutionDataMap[ast.syntaxID()]; + }; + + SemanticInfoChain.prototype.setCallResolutionDataForAST = function (ast, callResolutionData) { + if (callResolutionData) { + this.astCallResolutionDataMap[ast.syntaxID()] = callResolutionData; + } + }; + + SemanticInfoChain.prototype.setSymbolForDecl = function (decl, symbol) { + this.declSymbolMap[decl.declID] = symbol; + }; + + SemanticInfoChain.prototype.getSymbolForDecl = function (decl) { + return this.declSymbolMap[decl.declID]; + }; + + SemanticInfoChain.prototype.setSignatureSymbolForDecl = function (decl, signatureSymbol) { + this.declSignatureSymbolMap[decl.declID] = signatureSymbol; + }; + + SemanticInfoChain.prototype.getSignatureSymbolForDecl = function (decl) { + return this.declSignatureSymbolMap[decl.declID]; + }; + + SemanticInfoChain.prototype.addDiagnostic = function (diagnostic) { + var fileName = diagnostic.fileName(); + var diagnostics = this.fileNameToDiagnostics[fileName]; + if (!diagnostics) { + diagnostics = []; + this.fileNameToDiagnostics[fileName] = diagnostics; + } + + diagnostics.push(diagnostic); + }; + + SemanticInfoChain.prototype.getDiagnostics = function (fileName) { + var diagnostics = this.fileNameToDiagnostics[fileName]; + return diagnostics || []; + }; + + SemanticInfoChain.prototype.getBinder = function () { + if (!this._binder) { + this._binder = new TypeScript.PullSymbolBinder(this); + } + + return this._binder; + }; + + SemanticInfoChain.prototype.getResolver = function () { + if (!this._resolver) { + this._resolver = new TypeScript.PullTypeResolver(this.compiler.compilationSettings(), this); + } + + return this._resolver; + }; + + SemanticInfoChain.prototype.addSyntheticIndexSignature = function (containingDecl, containingSymbol, ast, indexParamName, indexParamType, returnType) { + var indexSignature = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + var indexParameterSymbol = new TypeScript.PullSymbol(indexParamName, 2048 /* Parameter */); + indexParameterSymbol.type = indexParamType; + indexSignature.addParameter(indexParameterSymbol); + indexSignature.returnType = returnType; + indexSignature.setResolved(); + indexParameterSymbol.setResolved(); + + containingSymbol.addIndexSignature(indexSignature); + + var indexSigDecl = new TypeScript.PullSynthesizedDecl("", "", 4194304 /* IndexSignature */, 2048 /* Signature */, containingDecl, containingDecl.semanticInfoChain); + var indexParamDecl = new TypeScript.PullSynthesizedDecl(indexParamName, indexParamName, 2048 /* Parameter */, 0 /* None */, indexSigDecl, containingDecl.semanticInfoChain); + indexSigDecl.setSignatureSymbol(indexSignature); + indexParamDecl.setSymbol(indexParameterSymbol); + indexSignature.addDeclaration(indexSigDecl); + indexParameterSymbol.addDeclaration(indexParamDecl); + }; + + SemanticInfoChain.prototype.getDeclForAST = function (ast) { + var document = this.getDocument(ast.fileName()); + + if (document) { + return document._getDeclForAST(ast); + } + + return null; + }; + + SemanticInfoChain.prototype.getEnclosingDecl = function (ast) { + return this.getDocument(ast.fileName()).getEnclosingDecl(ast); + }; + + SemanticInfoChain.prototype.setDeclForAST = function (ast, decl) { + this.getDocument(decl.fileName())._setDeclForAST(ast, decl); + }; + + SemanticInfoChain.prototype.getASTForDecl = function (decl) { + var document = this.getDocument(decl.fileName()); + if (document) { + return document._getASTForDecl(decl); + } + + return null; + }; + + SemanticInfoChain.prototype.setASTForDecl = function (decl, ast) { + this.getDocument(decl.fileName())._setASTForDecl(decl, ast); + }; + + SemanticInfoChain.prototype.topLevelDecl = function (fileName) { + var document = this.getDocument(fileName); + if (document) { + return document.topLevelDecl(); + } + + return null; + }; + + SemanticInfoChain.prototype.topLevelDecls = function () { + if (!this._topLevelDecls) { + this._topLevelDecls = TypeScript.ArrayUtilities.select(this.documents, function (u) { + return u.topLevelDecl(); + }); + } + + return this._topLevelDecls; + }; + + SemanticInfoChain.prototype.addDiagnosticFromAST = function (ast, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + this.addDiagnostic(this.diagnosticFromAST(ast, diagnosticKey, _arguments, additionalLocations)); + }; + + SemanticInfoChain.prototype.diagnosticFromAST = function (ast, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + return new TypeScript.Diagnostic(ast.fileName(), this.lineMap(ast.fileName()), ast.start(), ast.width(), diagnosticKey, _arguments, additionalLocations); + }; + + SemanticInfoChain.prototype.locationFromAST = function (ast) { + return new TypeScript.Location(ast.fileName(), this.lineMap(ast.fileName()), ast.start(), ast.width()); + }; + + SemanticInfoChain.prototype.duplicateIdentifierDiagnosticFromAST = function (ast, identifier, additionalLocationAST) { + return this.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_0, [identifier], additionalLocationAST ? [this.locationFromAST(additionalLocationAST)] : null); + }; + + SemanticInfoChain.prototype.addDuplicateIdentifierDiagnosticFromAST = function (ast, identifier, additionalLocationAST) { + this.addDiagnostic(this.duplicateIdentifierDiagnosticFromAST(ast, identifier, additionalLocationAST)); + }; + return SemanticInfoChain; + })(); + TypeScript.SemanticInfoChain = SemanticInfoChain; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DeclCollectionContext = (function () { + function DeclCollectionContext(document, semanticInfoChain, propagateEnumConstants) { + this.document = document; + this.semanticInfoChain = semanticInfoChain; + this.propagateEnumConstants = propagateEnumConstants; + this.isDeclareFile = false; + this.parentChain = []; + } + DeclCollectionContext.prototype.getParent = function () { + return this.parentChain ? this.parentChain[this.parentChain.length - 1] : null; + }; + + DeclCollectionContext.prototype.pushParent = function (parentDecl) { + if (parentDecl) { + this.parentChain[this.parentChain.length] = parentDecl; + } + }; + + DeclCollectionContext.prototype.popParent = function () { + this.parentChain.length--; + }; + return DeclCollectionContext; + })(); + + function moduleElementsHasExportAssignment(moduleElements) { + return moduleElements.any(function (m) { + return m.kind() === 134 /* ExportAssignment */; + }); + } + + function containingModuleHasExportAssignment(ast) { + ast = ast.parent; + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + var moduleDecl = ast; + return moduleElementsHasExportAssignment(moduleDecl.moduleElements); + } else if (ast.kind() === 120 /* SourceUnit */) { + var sourceUnit = ast; + return moduleElementsHasExportAssignment(sourceUnit.moduleElements); + } + + ast = ast.parent; + } + + return false; + } + + function isParsingAmbientModule(ast, context) { + ast = ast.parent; + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + if (TypeScript.hasModifier(ast.modifiers, 8 /* Ambient */)) { + return true; + } + } + + ast = ast.parent; + } + + return false; + } + + function preCollectImportDecls(ast, context) { + var importDecl = ast; + var declFlags = 0 /* None */; + + var parent = context.getParent(); + + if (TypeScript.hasModifier(importDecl.modifiers, 1 /* Exported */) && !containingModuleHasExportAssignment(ast)) { + declFlags |= 1 /* Exported */; + } + + var decl = new TypeScript.NormalPullDecl(importDecl.identifier.valueText(), importDecl.identifier.text(), 128 /* TypeAlias */, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + } + + function preCollectScriptDecls(sourceUnit, context) { + var fileName = sourceUnit.fileName(); + + var isExternalModule = context.document.isExternalModule(); + + var decl = new TypeScript.RootPullDecl(fileName, fileName, 1 /* Script */, 0 /* None */, context.semanticInfoChain, isExternalModule); + context.semanticInfoChain.setDeclForAST(sourceUnit, decl); + context.semanticInfoChain.setASTForDecl(decl, sourceUnit); + + context.isDeclareFile = context.document.isDeclareFile(); + + context.pushParent(decl); + + if (isExternalModule) { + var declFlags = 1 /* Exported */; + if (TypeScript.isDTSFile(fileName)) { + declFlags |= 8 /* Ambient */; + } + + var moduleContainsExecutableCode = containsExecutableCode(sourceUnit.moduleElements); + var kind = 32 /* DynamicModule */; + var valueText = TypeScript.quoteStr(fileName); + + var decl = new TypeScript.NormalPullDecl(valueText, fileName, kind, declFlags, context.getParent()); + + context.semanticInfoChain.setASTForDecl(decl, sourceUnit); + + context.semanticInfoChain.setDeclForAST(sourceUnit, decl); + + if (!moduleElementsHasExportAssignment(sourceUnit.moduleElements) || moduleContainsExecutableCode) { + createModuleVariableDecl(decl, sourceUnit, context); + } + + context.pushParent(decl); + } + } + + function preCollectEnumDecls(enumDecl, context) { + var declFlags = 0 /* None */; + var enumName = enumDecl.identifier.valueText(); + + if ((TypeScript.hasModifier(enumDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(enumDecl, context)) && !containingModuleHasExportAssignment(enumDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(enumDecl.modifiers, 8 /* Ambient */) || isParsingAmbientModule(enumDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + declFlags |= 4096 /* Enum */; + var kind = 64 /* Enum */; + + var enumDeclaration = new TypeScript.NormalPullDecl(enumName, enumDecl.identifier.text(), kind, declFlags, context.getParent()); + context.semanticInfoChain.setDeclForAST(enumDecl, enumDeclaration); + context.semanticInfoChain.setASTForDecl(enumDeclaration, enumDecl); + + var valueDecl = new TypeScript.NormalPullDecl(enumDeclaration.name, enumDeclaration.getDisplayName(), 512 /* Variable */, enumDeclaration.flags, context.getParent()); + enumDeclaration.setValueDecl(valueDecl); + context.semanticInfoChain.setASTForDecl(valueDecl, enumDecl); + + context.pushParent(enumDeclaration); + } + + function createEnumElementDecls(propertyDecl, context) { + var parent = context.getParent(); + + var decl = new TypeScript.PullEnumElementDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), parent); + context.semanticInfoChain.setDeclForAST(propertyDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyDecl); + } + + function preCollectModuleDecls(moduleDecl, context) { + var declFlags = 0 /* None */; + + var moduleContainsExecutableCode = containsExecutableCode(moduleDecl.moduleElements); + + var isDynamic = moduleDecl.stringLiteral !== null; + + if ((TypeScript.hasModifier(moduleDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(moduleDecl, context)) && !containingModuleHasExportAssignment(moduleDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(moduleDecl.modifiers, 8 /* Ambient */) || isParsingAmbientModule(moduleDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + var kind = isDynamic ? 32 /* DynamicModule */ : 4 /* Container */; + + if (moduleDecl.stringLiteral) { + var valueText = TypeScript.quoteStr(moduleDecl.stringLiteral.valueText()); + var text = moduleDecl.stringLiteral.text(); + + var decl = new TypeScript.NormalPullDecl(valueText, text, kind, declFlags, context.getParent()); + + context.semanticInfoChain.setDeclForAST(moduleDecl, decl); + context.semanticInfoChain.setDeclForAST(moduleDecl.stringLiteral, decl); + context.semanticInfoChain.setASTForDecl(decl, moduleDecl.stringLiteral); + + if (!moduleElementsHasExportAssignment(moduleDecl.moduleElements) || moduleContainsExecutableCode) { + createModuleVariableDecl(decl, moduleDecl.stringLiteral, context); + } + + context.pushParent(decl); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDecl.name); + for (var i = 0, n = moduleNames.length; i < n; i++) { + var moduleName = moduleNames[i]; + + var specificFlags = declFlags; + if (i > 0) { + specificFlags |= 1 /* Exported */; + } + + var decl = new TypeScript.NormalPullDecl(moduleName.valueText(), moduleName.text(), kind, specificFlags, context.getParent()); + + context.semanticInfoChain.setDeclForAST(moduleDecl, decl); + context.semanticInfoChain.setDeclForAST(moduleName, decl); + context.semanticInfoChain.setASTForDecl(decl, moduleName); + + if (moduleContainsExecutableCode) { + createModuleVariableDecl(decl, moduleName, context); + } + + context.pushParent(decl); + } + } + } + + function createModuleVariableDecl(decl, moduleNameAST, context) { + decl.setFlags(decl.flags | getInitializationFlag(decl)); + + var valueDecl = new TypeScript.NormalPullDecl(decl.name, decl.getDisplayName(), 512 /* Variable */, decl.flags, context.getParent()); + decl.setValueDecl(valueDecl); + context.semanticInfoChain.setASTForDecl(valueDecl, moduleNameAST); + } + + function containsExecutableCode(members) { + for (var i = 0, n = members.childCount(); i < n; i++) { + var member = members.childAt(i); + + if (member.kind() === 130 /* ModuleDeclaration */) { + var moduleDecl = member; + + if (containsExecutableCode(moduleDecl.moduleElements)) { + return true; + } + } else if (member.kind() === 133 /* ImportDeclaration */) { + if (TypeScript.hasModifier(member.modifiers, 1 /* Exported */)) { + return true; + } + } else if (member.kind() !== 128 /* InterfaceDeclaration */ && member.kind() !== 134 /* ExportAssignment */) { + return true; + } + } + + return false; + } + + function preCollectClassDecls(classDecl, context) { + var declFlags = 0 /* None */; + + if ((TypeScript.hasModifier(classDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(classDecl, context)) && !containingModuleHasExportAssignment(classDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(classDecl.modifiers, 8 /* Ambient */) || isParsingAmbientModule(classDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), 8 /* Class */, declFlags, parent); + + var constructorDecl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), 512 /* Variable */, declFlags | 16384 /* ClassConstructorVariable */, parent); + + decl.setValueDecl(constructorDecl); + + context.semanticInfoChain.setDeclForAST(classDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, classDecl); + context.semanticInfoChain.setASTForDecl(constructorDecl, classDecl); + + context.pushParent(decl); + } + + function preCollectObjectTypeDecls(objectType, context) { + if (objectType.parent.kind() === 128 /* InterfaceDeclaration */) { + return; + } + + var declFlags = 0 /* None */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", 8388608 /* ObjectType */, declFlags, parent); + context.semanticInfoChain.setDeclForAST(objectType, decl); + context.semanticInfoChain.setASTForDecl(decl, objectType); + + context.pushParent(decl); + } + + function preCollectInterfaceDecls(interfaceDecl, context) { + var declFlags = 0 /* None */; + + if ((TypeScript.hasModifier(interfaceDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(interfaceDecl, context)) && !containingModuleHasExportAssignment(interfaceDecl)) { + declFlags |= 1 /* Exported */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(interfaceDecl.identifier.valueText(), interfaceDecl.identifier.text(), 16 /* Interface */, declFlags, parent); + context.semanticInfoChain.setDeclForAST(interfaceDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, interfaceDecl); + + context.pushParent(decl); + } + + function preCollectParameterDecl(argDecl, context) { + var declFlags = 0 /* None */; + + if (TypeScript.hasModifier(argDecl.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (argDecl.questionToken !== null || argDecl.equalsValueClause !== null || argDecl.dotDotDotToken !== null) { + declFlags |= 128 /* Optional */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 2048 /* Parameter */, declFlags, parent); + + if (argDecl.equalsValueClause) { + parent.flags |= 33554432 /* HasDefaultArgs */; + } + + if (parent.kind === 32768 /* ConstructorMethod */) { + decl.setFlag(67108864 /* ConstructorParameter */); + } + + var isPublicOrPrivate = TypeScript.hasModifier(argDecl.modifiers, 4 /* Public */ | 2 /* Private */); + var isInConstructor = parent.kind === 32768 /* ConstructorMethod */; + if (isPublicOrPrivate && isInConstructor) { + var parentsParent = context.parentChain[context.parentChain.length - 2]; + + var propDeclFlags = declFlags & ~128 /* Optional */; + var propDecl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 4096 /* Property */, propDeclFlags, parentsParent); + propDecl.setValueDecl(decl); + decl.setFlag(8388608 /* PropertyParameter */); + propDecl.setFlag(8388608 /* PropertyParameter */); + + if (parent.kind === 32768 /* ConstructorMethod */) { + propDecl.setFlag(67108864 /* ConstructorParameter */); + } + + context.semanticInfoChain.setASTForDecl(decl, argDecl); + context.semanticInfoChain.setASTForDecl(propDecl, argDecl); + context.semanticInfoChain.setDeclForAST(argDecl, propDecl); + } else { + context.semanticInfoChain.setASTForDecl(decl, argDecl); + context.semanticInfoChain.setDeclForAST(argDecl, decl); + } + + parent.addVariableDeclToGroup(decl); + } + + function preCollectTypeParameterDecl(typeParameterDecl, context) { + var declFlags = 0 /* None */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(typeParameterDecl.identifier.valueText(), typeParameterDecl.identifier.text(), 8192 /* TypeParameter */, declFlags, parent); + context.semanticInfoChain.setASTForDecl(decl, typeParameterDecl); + context.semanticInfoChain.setDeclForAST(typeParameterDecl, decl); + } + + function createPropertySignature(propertyDecl, context) { + var declFlags = 4 /* Public */; + var parent = context.getParent(); + var declType = 4096 /* Property */; + + if (propertyDecl.questionToken !== null) { + declFlags |= 128 /* Optional */; + } + + var decl = new TypeScript.NormalPullDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(propertyDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyDecl); + } + + function createMemberVariableDeclaration(memberDecl, context) { + var declFlags = 0 /* None */; + var declType = 4096 /* Property */; + + if (TypeScript.hasModifier(memberDecl.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (TypeScript.hasModifier(memberDecl.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(memberDecl.variableDeclarator.propertyName.valueText(), memberDecl.variableDeclarator.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(memberDecl, decl); + context.semanticInfoChain.setDeclForAST(memberDecl.variableDeclarator, decl); + context.semanticInfoChain.setASTForDecl(decl, memberDecl); + } + + function createVariableDeclaration(varDecl, context) { + var declFlags = 0 /* None */; + var declType = 512 /* Variable */; + + var modifiers = TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl); + if ((TypeScript.hasModifier(modifiers, 1 /* Exported */) || isParsingAmbientModule(varDecl, context)) && !containingModuleHasExportAssignment(varDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(modifiers, 8 /* Ambient */) || isParsingAmbientModule(varDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(varDecl.propertyName.valueText(), varDecl.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(varDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, varDecl); + + if (parent) { + parent.addVariableDeclToGroup(decl); + } + } + + function preCollectVarDecls(ast, context) { + if (ast.parent.kind() === 136 /* MemberVariableDeclaration */) { + return; + } + + var varDecl = ast; + createVariableDeclaration(varDecl, context); + } + + function createFunctionTypeDeclaration(functionTypeDeclAST, context) { + var declFlags = 2048 /* Signature */; + var declType = 16777216 /* FunctionType */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(functionTypeDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, functionTypeDeclAST); + + context.pushParent(decl); + } + + function createConstructorTypeDeclaration(constructorTypeDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 33554432 /* ConstructorType */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(constructorTypeDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, constructorTypeDeclAST); + + context.pushParent(decl); + } + + function createFunctionDeclaration(funcDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 16384 /* Function */; + + if ((TypeScript.hasModifier(funcDeclAST.modifiers, 1 /* Exported */) || isParsingAmbientModule(funcDeclAST, context)) && !containingModuleHasExportAssignment(funcDeclAST)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(funcDeclAST.modifiers, 8 /* Ambient */) || isParsingAmbientModule(funcDeclAST, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + if (!funcDeclAST.block) { + declFlags |= 2048 /* Signature */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(funcDeclAST.identifier.valueText(), funcDeclAST.identifier.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(funcDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, funcDeclAST); + + context.pushParent(decl); + } + + function createAnyFunctionExpressionDeclaration(functionExpressionDeclAST, id, context, displayName) { + if (typeof displayName === "undefined") { displayName = null; } + var declFlags = 0 /* None */; + + if (functionExpressionDeclAST.kind() === 219 /* SimpleArrowFunctionExpression */ || functionExpressionDeclAST.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { + declFlags |= 8192 /* ArrowFunction */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var name = id ? id.text() : ""; + var displayNameText = displayName ? displayName.text() : ""; + var decl = new TypeScript.PullFunctionExpressionDecl(name, declFlags, parent, displayNameText); + context.semanticInfoChain.setDeclForAST(functionExpressionDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, functionExpressionDeclAST); + + context.pushParent(decl); + + if (functionExpressionDeclAST.kind() === 219 /* SimpleArrowFunctionExpression */) { + var simpleArrow = functionExpressionDeclAST; + var declFlags = 4 /* Public */; + + var parent = context.getParent(); + + if (TypeScript.hasFlag(parent.flags, 2097152 /* DeclaredInAWithBlock */)) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(simpleArrow.identifier.valueText(), simpleArrow.identifier.text(), 2048 /* Parameter */, declFlags, parent); + + context.semanticInfoChain.setASTForDecl(decl, simpleArrow.identifier); + context.semanticInfoChain.setDeclForAST(simpleArrow.identifier, decl); + + parent.addVariableDeclToGroup(decl); + } + } + + function createMemberFunctionDeclaration(funcDecl, context) { + var declFlags = 0 /* None */; + var declType = 65536 /* Method */; + + if (TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasModifier(funcDecl.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (!funcDecl.block) { + declFlags |= 2048 /* Signature */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(funcDecl.propertyName.valueText(), funcDecl.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(funcDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, funcDecl); + + context.pushParent(decl); + } + + function createIndexSignatureDeclaration(indexSignatureDeclAST, context) { + var declFlags = 2048 /* Signature */; + var declType = 4194304 /* IndexSignature */; + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(indexSignatureDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, indexSignatureDeclAST); + + context.pushParent(decl); + } + + function createCallSignatureDeclaration(callSignature, context) { + var isChildOfObjectType = callSignature.parent && callSignature.parent.parent && callSignature.parent.kind() === 2 /* SeparatedList */ && callSignature.parent.parent.kind() === 122 /* ObjectType */; + + if (!isChildOfObjectType) { + return; + } + + var declFlags = 2048 /* Signature */; + var declType = 1048576 /* CallSignature */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(callSignature, decl); + context.semanticInfoChain.setASTForDecl(decl, callSignature); + + context.pushParent(decl); + } + + function createMethodSignatureDeclaration(method, context) { + var declFlags = 0 /* None */; + var declType = 65536 /* Method */; + + declFlags |= 4 /* Public */; + declFlags |= 2048 /* Signature */; + + if (method.questionToken !== null) { + declFlags |= 128 /* Optional */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(method.propertyName.valueText(), method.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(method, decl); + context.semanticInfoChain.setASTForDecl(decl, method); + + context.pushParent(decl); + } + + function createConstructSignatureDeclaration(constructSignatureDeclAST, context) { + var declFlags = 2048 /* Signature */; + var declType = 2097152 /* ConstructSignature */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(constructSignatureDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, constructSignatureDeclAST); + + context.pushParent(decl); + } + + function createClassConstructorDeclaration(constructorDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 32768 /* ConstructorMethod */; + + if (!constructorDeclAST.block) { + declFlags |= 2048 /* Signature */; + } + + var parent = context.getParent(); + + if (parent) { + var parentFlags = parent.flags; + + if (parentFlags & 1 /* Exported */) { + declFlags |= 1 /* Exported */; + } + } + + var decl = new TypeScript.NormalPullDecl(parent.name, parent.getDisplayName(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(constructorDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, constructorDeclAST); + + context.pushParent(decl); + } + + function createGetAccessorDeclaration(getAccessorDeclAST, context) { + var declFlags = 4 /* Public */; + var declType = 262144 /* GetAccessor */; + + if (TypeScript.hasModifier(getAccessorDeclAST.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasModifier(getAccessorDeclAST.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(getAccessorDeclAST.propertyName.valueText(), getAccessorDeclAST.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(getAccessorDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, getAccessorDeclAST); + + context.pushParent(decl); + } + + function createFunctionExpressionDeclaration(expression, context) { + createAnyFunctionExpressionDeclaration(expression, expression.identifier, context); + } + + function createSetAccessorDeclaration(setAccessorDeclAST, context) { + var declFlags = 4 /* Public */; + var declType = 524288 /* SetAccessor */; + + if (TypeScript.hasModifier(setAccessorDeclAST.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasModifier(setAccessorDeclAST.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(setAccessorDeclAST.propertyName.valueText(), setAccessorDeclAST.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(setAccessorDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, setAccessorDeclAST); + + context.pushParent(decl); + } + + function preCollectCatchDecls(ast, context) { + var declFlags = 0 /* None */; + var declType = 268435456 /* CatchBlock */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + + context.pushParent(decl); + + var declFlags = 0 /* None */; + var declType = 1024 /* CatchVariable */; + + var parent = context.getParent(); + + if (TypeScript.hasFlag(parent.flags, 2097152 /* DeclaredInAWithBlock */)) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(ast.identifier.valueText(), ast.identifier.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast.identifier, decl); + context.semanticInfoChain.setASTForDecl(decl, ast.identifier); + + if (parent) { + parent.addVariableDeclToGroup(decl); + } + } + + function preCollectWithDecls(ast, context) { + var declFlags = 0 /* None */; + var declType = 134217728 /* WithBlock */; + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + + context.pushParent(decl); + } + + function preCollectObjectLiteralDecls(ast, context) { + var decl = new TypeScript.NormalPullDecl("", "", 256 /* ObjectLiteral */, 0 /* None */, context.getParent()); + + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + + context.pushParent(decl); + } + + function preCollectSimplePropertyAssignmentDecls(propertyAssignment, context) { + var assignmentText = TypeScript.getPropertyAssignmentNameTextFromIdentifier(propertyAssignment.propertyName); + var span = TypeScript.TextSpan.fromBounds(propertyAssignment.start(), propertyAssignment.end()); + + var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent()); + + context.semanticInfoChain.setDeclForAST(propertyAssignment, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyAssignment); + } + + function preCollectFunctionPropertyAssignmentDecls(propertyAssignment, context) { + var assignmentText = TypeScript.getPropertyAssignmentNameTextFromIdentifier(propertyAssignment.propertyName); + + var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent()); + + context.semanticInfoChain.setDeclForAST(propertyAssignment, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyAssignment); + + createAnyFunctionExpressionDeclaration(propertyAssignment, propertyAssignment.propertyName, context, propertyAssignment.propertyName); + } + + function preCollectDecls(ast, context) { + switch (ast.kind()) { + case 120 /* SourceUnit */: + preCollectScriptDecls(ast, context); + break; + case 132 /* EnumDeclaration */: + preCollectEnumDecls(ast, context); + break; + case 243 /* EnumElement */: + createEnumElementDecls(ast, context); + break; + case 130 /* ModuleDeclaration */: + preCollectModuleDecls(ast, context); + break; + case 131 /* ClassDeclaration */: + preCollectClassDecls(ast, context); + break; + case 128 /* InterfaceDeclaration */: + preCollectInterfaceDecls(ast, context); + break; + case 122 /* ObjectType */: + preCollectObjectTypeDecls(ast, context); + break; + case 242 /* Parameter */: + preCollectParameterDecl(ast, context); + break; + case 136 /* MemberVariableDeclaration */: + createMemberVariableDeclaration(ast, context); + break; + case 141 /* PropertySignature */: + createPropertySignature(ast, context); + break; + case 225 /* VariableDeclarator */: + preCollectVarDecls(ast, context); + break; + case 137 /* ConstructorDeclaration */: + createClassConstructorDeclaration(ast, context); + break; + case 139 /* GetAccessor */: + createGetAccessorDeclaration(ast, context); + break; + case 140 /* SetAccessor */: + createSetAccessorDeclaration(ast, context); + break; + case 222 /* FunctionExpression */: + createFunctionExpressionDeclaration(ast, context); + break; + case 135 /* MemberFunctionDeclaration */: + createMemberFunctionDeclaration(ast, context); + break; + case 144 /* IndexSignature */: + createIndexSignatureDeclaration(ast, context); + break; + case 123 /* FunctionType */: + createFunctionTypeDeclaration(ast, context); + break; + case 125 /* ConstructorType */: + createConstructorTypeDeclaration(ast, context); + break; + case 142 /* CallSignature */: + createCallSignatureDeclaration(ast, context); + break; + case 143 /* ConstructSignature */: + createConstructSignatureDeclaration(ast, context); + break; + case 145 /* MethodSignature */: + createMethodSignatureDeclaration(ast, context); + break; + case 129 /* FunctionDeclaration */: + createFunctionDeclaration(ast, context); + break; + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + createAnyFunctionExpressionDeclaration(ast, null, context); + break; + case 133 /* ImportDeclaration */: + preCollectImportDecls(ast, context); + break; + case 238 /* TypeParameter */: + preCollectTypeParameterDecl(ast, context); + break; + case 236 /* CatchClause */: + preCollectCatchDecls(ast, context); + break; + case 163 /* WithStatement */: + preCollectWithDecls(ast, context); + break; + case 215 /* ObjectLiteralExpression */: + preCollectObjectLiteralDecls(ast, context); + break; + case 240 /* SimplePropertyAssignment */: + preCollectSimplePropertyAssignmentDecls(ast, context); + break; + case 241 /* FunctionPropertyAssignment */: + preCollectFunctionPropertyAssignmentDecls(ast, context); + break; + } + } + + function isContainer(decl) { + return decl.kind === 4 /* Container */ || decl.kind === 32 /* DynamicModule */ || decl.kind === 64 /* Enum */; + } + + function getInitializationFlag(decl) { + if (decl.kind & 4 /* Container */) { + return 32768 /* InitializedModule */; + } else if (decl.kind & 32 /* DynamicModule */) { + return 65536 /* InitializedDynamicModule */; + } + + return 0 /* None */; + } + + function hasInitializationFlag(decl) { + var kind = decl.kind; + + if (kind & 4 /* Container */) { + return (decl.flags & 32768 /* InitializedModule */) !== 0; + } else if (kind & 32 /* DynamicModule */) { + return (decl.flags & 65536 /* InitializedDynamicModule */) !== 0; + } + + return false; + } + + function postCollectDecls(ast, context) { + var currentDecl = context.getParent(); + + if (ast.kind() === 11 /* IdentifierName */ || ast.kind() === 14 /* StringLiteral */) { + if (currentDecl.kind === 4 /* Container */ || currentDecl.kind === 32 /* DynamicModule */) { + return; + } + } + + if (ast.kind() === 130 /* ModuleDeclaration */) { + var moduleDeclaration = ast; + if (moduleDeclaration.stringLiteral) { + TypeScript.Debug.assert(currentDecl.ast() === moduleDeclaration.stringLiteral); + context.popParent(); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDeclaration.name); + for (var i = moduleNames.length - 1; i >= 0; i--) { + var moduleName = moduleNames[i]; + TypeScript.Debug.assert(currentDecl.ast() === moduleName); + context.popParent(); + currentDecl = context.getParent(); + } + } + } + + if (ast.kind() === 132 /* EnumDeclaration */) { + computeEnumElementConstantValues(ast, currentDecl, context); + } + + while (currentDecl.getParentDecl() && currentDecl.ast() === ast) { + context.popParent(); + currentDecl = context.getParent(); + } + } + + function computeEnumElementConstantValues(ast, enumDecl, context) { + TypeScript.Debug.assert(enumDecl.kind === 64 /* Enum */); + + var isAmbientEnum = TypeScript.hasFlag(enumDecl.flags, 8 /* Ambient */); + var inConstantSection = !isAmbientEnum; + var currentConstantValue = 0; + var enumMemberDecls = enumDecl.getChildDecls(); + + for (var i = 0, n = ast.enumElements.nonSeparatorCount(); i < n; i++) { + var enumElement = ast.enumElements.nonSeparatorAt(i); + var enumElementDecl = TypeScript.ArrayUtilities.first(enumMemberDecls, function (d) { + return context.semanticInfoChain.getASTForDecl(d) === enumElement; + }); + + TypeScript.Debug.assert(enumElementDecl.kind === 67108864 /* EnumMember */); + + if (enumElement.equalsValueClause === null) { + if (inConstantSection) { + enumElementDecl.constantValue = currentConstantValue; + currentConstantValue++; + } + } else { + enumElementDecl.constantValue = computeEnumElementConstantValue(enumElement.equalsValueClause.value, enumMemberDecls, context); + if (enumElementDecl.constantValue !== null && !isAmbientEnum) { + inConstantSection = true; + currentConstantValue = enumElementDecl.constantValue + 1; + } else { + inConstantSection = false; + } + } + + TypeScript.Debug.assert(enumElementDecl.constantValue !== undefined); + } + } + + function computeEnumElementConstantValue(expression, enumMemberDecls, context) { + TypeScript.Debug.assert(expression); + + if (TypeScript.ASTHelpers.isIntegerLiteralAST(expression)) { + var token; + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + token = expression.operand; + break; + default: + token = expression; + } + + var value = token.value(); + return value && expression.kind() === 165 /* NegateExpression */ ? -value : value; + } else if (context.propagateEnumConstants) { + switch (expression.kind()) { + case 11 /* IdentifierName */: + var name = expression; + var matchingEnumElement = TypeScript.ArrayUtilities.firstOrDefault(enumMemberDecls, function (d) { + return d.name === name.valueText(); + }); + + return matchingEnumElement ? matchingEnumElement.constantValue : null; + + case 202 /* LeftShiftExpression */: + var binaryExpression = expression; + var left = computeEnumElementConstantValue(binaryExpression.left, enumMemberDecls, context); + var right = computeEnumElementConstantValue(binaryExpression.right, enumMemberDecls, context); + if (left === null || right === null) { + return null; + } + + return left << right; + + case 189 /* BitwiseOrExpression */: + var binaryExpression = expression; + var left = computeEnumElementConstantValue(binaryExpression.left, enumMemberDecls, context); + var right = computeEnumElementConstantValue(binaryExpression.right, enumMemberDecls, context); + if (left === null || right === null) { + return null; + } + + return left | right; + } + + return null; + } else { + return null; + } + } + + (function (DeclarationCreator) { + function create(document, semanticInfoChain, compilationSettings) { + var declCollectionContext = new DeclCollectionContext(document, semanticInfoChain, compilationSettings.propagateEnumConstants()); + + TypeScript.getAstWalkerFactory().simpleWalk(document.sourceUnit(), preCollectDecls, postCollectDecls, declCollectionContext); + + return declCollectionContext.getParent(); + } + DeclarationCreator.create = create; + })(TypeScript.DeclarationCreator || (TypeScript.DeclarationCreator = {})); + var DeclarationCreator = TypeScript.DeclarationCreator; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PullSymbolBinder = (function () { + function PullSymbolBinder(semanticInfoChain) { + this.semanticInfoChain = semanticInfoChain; + this.declsBeingBound = []; + this.inBindingOtherDeclsWalker = new TypeScript.PullHelpers.OtherPullDeclsWalker(); + } + PullSymbolBinder.prototype.getParent = function (decl, returnInstanceType) { + if (typeof returnInstanceType === "undefined") { returnInstanceType = false; } + var parentDecl = decl.getParentDecl(); + + if (parentDecl.kind === 1 /* Script */) { + return null; + } + + var parent = parentDecl.getSymbol(); + + if (!parent && parentDecl && !parentDecl.hasBeenBound()) { + this.bindDeclToPullSymbol(parentDecl); + } + + parent = parentDecl.getSymbol(); + if (parent) { + var parentDeclKind = parentDecl.kind; + if (parentDeclKind === 262144 /* GetAccessor */) { + parent = parent.getGetter(); + } else if (parentDeclKind === 524288 /* SetAccessor */) { + parent = parent.getSetter(); + } + } + + if (parent) { + if (returnInstanceType && parent.isType() && parent.isContainer()) { + var instanceSymbol = parent.getInstanceSymbol(); + + if (instanceSymbol) { + return instanceSymbol.type; + } + } + + return parent.type; + } + + return null; + }; + + PullSymbolBinder.prototype.findDeclsInContext = function (startingDecl, declKind, searchGlobally) { + if (!searchGlobally) { + var parentDecl = startingDecl.getParentDecl(); + return parentDecl.searchChildDecls(startingDecl.name, declKind); + } + + var contextSymbolPath = startingDecl.getParentPath(); + + if (contextSymbolPath.length) { + var copyOfContextSymbolPath = []; + + for (var i = 0; i < contextSymbolPath.length; i++) { + if (contextSymbolPath[i].kind & 1 /* Script */) { + continue; + } + copyOfContextSymbolPath[copyOfContextSymbolPath.length] = contextSymbolPath[i].name; + } + + return this.semanticInfoChain.findDecls(copyOfContextSymbolPath, declKind); + } + }; + + PullSymbolBinder.prototype.getExistingSymbol = function (decl, searchKind, parent) { + var lookingForValue = (searchKind & 68147712 /* SomeValue */) !== 0; + var lookingForType = (searchKind & 58728795 /* SomeType */) !== 0; + var lookingForContainer = (searchKind & 164 /* SomeContainer */) !== 0; + var name = decl.name; + if (parent) { + var isExported = (decl.flags & 1 /* Exported */) !== 0; + + var prevSymbol = null; + if (lookingForValue) { + prevSymbol = parent.findContainedNonMember(name); + } else if (lookingForType) { + prevSymbol = parent.findContainedNonMemberType(name, searchKind); + } else if (lookingForContainer) { + prevSymbol = parent.findContainedNonMemberContainer(name, searchKind); + } + var prevIsExported = !prevSymbol; + if (!prevSymbol) { + if (lookingForValue) { + prevSymbol = parent.findMember(name, false); + } else if (lookingForType) { + prevSymbol = parent.findNestedType(name, searchKind); + } else if (lookingForContainer) { + prevSymbol = parent.findNestedContainer(name, searchKind); + } + } + + if (isExported && prevIsExported) { + return prevSymbol; + } + if (prevSymbol) { + var prevDecls = prevSymbol.getDeclarations(); + var lastPrevDecl = prevDecls[prevDecls.length - 1]; + var parentDecl = decl.getParentDecl(); + var prevParentDecl = lastPrevDecl && lastPrevDecl.getParentDecl(); + if (parentDecl !== prevParentDecl) { + return null; + } + + return prevSymbol; + } + } else { + var parentDecl = decl.getParentDecl(); + if (parentDecl && parentDecl.kind === 1 /* Script */) { + return this.semanticInfoChain.findTopLevelSymbol(name, searchKind, decl); + } else { + var prevDecls = parentDecl && parentDecl.searchChildDecls(name, searchKind); + return prevDecls[0] && prevDecls[0].getSymbol(); + } + } + + return null; + }; + + PullSymbolBinder.prototype.checkThatExportsMatch = function (decl, prevSymbol, reportError) { + if (typeof reportError === "undefined") { reportError = true; } + var isExported = (decl.flags & 1 /* Exported */) !== 0; + var prevDecls = prevSymbol.getDeclarations(); + var prevIsExported = (prevDecls[prevDecls.length - 1].flags & 1 /* Exported */) !== 0; + if ((isExported !== prevIsExported) && !prevSymbol.isSignature() && (decl.kind & 7340032 /* SomeSignature */) === 0) { + if (reportError) { + var ast = this.semanticInfoChain.getASTForDecl(decl); + this.semanticInfoChain.addDiagnosticFromAST(ast, TypeScript.DiagnosticCode.All_declarations_of_merged_declaration_0_must_be_exported_or_not_exported, [decl.getDisplayName()]); + } + return false; + } + + return true; + }; + + PullSymbolBinder.prototype.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList = function (signature, currentSignatures) { + var signatureDecl = signature.getDeclarations()[0]; + TypeScript.Debug.assert(signatureDecl); + var enclosingDecl = signatureDecl.getParentDecl(); + var indexToInsert = TypeScript.ArrayUtilities.indexOf(currentSignatures, function (someSignature) { + return someSignature.getDeclarations()[0].getParentDecl() !== enclosingDecl; + }); + return indexToInsert < 0 ? currentSignatures.length : indexToInsert; + }; + + PullSymbolBinder.prototype.bindEnumDeclarationToPullSymbol = function (enumContainerDecl) { + var enumName = enumContainerDecl.name; + + var enumContainerSymbol = null; + var enumInstanceSymbol = null; + var moduleInstanceTypeSymbol = null; + + var enumInstanceDecl = enumContainerDecl.getValueDecl(); + + var enumDeclKind = enumContainerDecl.kind; + + var parent = this.getParent(enumContainerDecl); + var parentInstanceSymbol = this.getParent(enumContainerDecl, true); + var parentDecl = enumContainerDecl.getParentDecl(); + var enumAST = this.semanticInfoChain.getASTForDecl(enumContainerDecl); + + var isExported = enumContainerDecl.flags & 1 /* Exported */; + + var createdNewSymbol = false; + + enumContainerSymbol = this.getExistingSymbol(enumContainerDecl, 64 /* Enum */, parent); + + if (enumContainerSymbol) { + if (enumContainerSymbol.kind !== enumDeclKind) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(enumAST.identifier, enumContainerDecl.getDisplayName(), enumContainerSymbol.getDeclarations()[0].ast()); + enumContainerSymbol = null; + } else if (!this.checkThatExportsMatch(enumContainerDecl, enumContainerSymbol)) { + enumContainerSymbol = null; + } + } + + if (enumContainerSymbol) { + enumInstanceSymbol = enumContainerSymbol.getInstanceSymbol(); + } else { + enumContainerSymbol = new TypeScript.PullContainerSymbol(enumName, enumDeclKind); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(enumContainerSymbol, 64 /* Enum */); + } + } + + enumContainerSymbol.addDeclaration(enumContainerDecl); + enumContainerDecl.setSymbol(enumContainerSymbol); + + this.semanticInfoChain.setSymbolForAST(enumAST.identifier, enumContainerSymbol); + this.semanticInfoChain.setSymbolForAST(enumAST, enumContainerSymbol); + + if (!enumInstanceSymbol) { + var variableSymbol = null; + if (parentInstanceSymbol) { + if (isExported) { + variableSymbol = parentInstanceSymbol.findMember(enumName, false); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findContainedNonMember(enumName); + } + } else { + variableSymbol = parentInstanceSymbol.findContainedNonMember(enumName); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findMember(enumName, false); + } + } + + if (variableSymbol) { + var declarations = variableSymbol.getDeclarations(); + + if (declarations.length) { + var variableSymbolParentDecl = declarations[0].getParentDecl(); + + if (parentDecl !== variableSymbolParentDecl) { + variableSymbol = null; + } + } + } + } else if (!(enumContainerDecl.flags & 1 /* Exported */)) { + var siblingDecls = parentDecl.getChildDecls(); + var augmentedDecl = null; + + for (var i = 0; i < siblingDecls.length; i++) { + if (siblingDecls[i] === enumContainerDecl) { + break; + } + + if ((siblingDecls[i].name === enumName) && (siblingDecls[i].kind & 68147712 /* SomeValue */)) { + augmentedDecl = siblingDecls[i]; + break; + } + } + + if (augmentedDecl) { + variableSymbol = augmentedDecl.getSymbol(); + + if (variableSymbol) { + if (variableSymbol.isContainer()) { + variableSymbol = variableSymbol.getInstanceSymbol(); + } else if (variableSymbol && variableSymbol.isType()) { + variableSymbol = variableSymbol.getConstructorMethod(); + } + } + } + } + + if (variableSymbol) { + enumInstanceSymbol = variableSymbol; + moduleInstanceTypeSymbol = variableSymbol.type; + } else { + enumInstanceSymbol = new TypeScript.PullSymbol(enumName, 512 /* Variable */); + } + + enumContainerSymbol.setInstanceSymbol(enumInstanceSymbol); + + if (!moduleInstanceTypeSymbol) { + moduleInstanceTypeSymbol = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + enumInstanceSymbol.type = moduleInstanceTypeSymbol; + } + + moduleInstanceTypeSymbol.addDeclaration(enumContainerDecl); + + if (!moduleInstanceTypeSymbol.getAssociatedContainerType()) { + moduleInstanceTypeSymbol.setAssociatedContainerType(enumContainerSymbol); + } + } + + if (createdNewSymbol && parent) { + if (enumContainerDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberType(enumContainerSymbol); + } else { + parent.addEnclosedNonMemberType(enumContainerSymbol); + } + } + + if (createdNewSymbol) { + this.bindEnumIndexerDeclsToPullSymbols(enumContainerSymbol); + } + var valueDecl = enumContainerDecl.getValueDecl(); + + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + }; + + PullSymbolBinder.prototype.bindEnumIndexerDeclsToPullSymbols = function (enumContainerSymbol) { + var enumContainerInstanceTypeSymbol = enumContainerSymbol.getInstanceSymbol().type; + + var syntheticIndexerParameterSymbol = new TypeScript.PullSymbol("x", 2048 /* Parameter */); + syntheticIndexerParameterSymbol.type = this.semanticInfoChain.numberTypeSymbol; + syntheticIndexerParameterSymbol.setResolved(); + syntheticIndexerParameterSymbol.setIsSynthesized(); + + var syntheticIndexerSignatureSymbol = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + syntheticIndexerSignatureSymbol.addParameter(syntheticIndexerParameterSymbol); + syntheticIndexerSignatureSymbol.returnType = this.semanticInfoChain.stringTypeSymbol; + syntheticIndexerSignatureSymbol.setResolved(); + syntheticIndexerSignatureSymbol.setIsSynthesized(); + + enumContainerInstanceTypeSymbol.addIndexSignature(syntheticIndexerSignatureSymbol); + }; + + PullSymbolBinder.prototype.findExistingVariableSymbolForModuleValueDecl = function (decl) { + var isExported = TypeScript.hasFlag(decl.flags, 1 /* Exported */); + var modName = decl.name; + var parentInstanceSymbol = this.getParent(decl, true); + var parentDecl = decl.getParentDecl(); + + var variableSymbol = null; + + if (parentInstanceSymbol) { + if (isExported) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); + } + } else { + variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + } + } + + if (variableSymbol) { + var declarations = variableSymbol.getDeclarations(); + + if (declarations.length) { + var variableSymbolParentDecl = declarations[0].getParentDecl(); + var isExportedOrHasTheSameParent = isExported || (parentDecl === variableSymbolParentDecl); + + var canReuseVariableSymbol = isExportedOrHasTheSameParent && this.checkThatExportsMatch(decl, variableSymbol, false); + + if (!canReuseVariableSymbol) { + variableSymbol = null; + } + } + } + } else if (!isExported) { + var siblingDecls = parentDecl.getChildDecls(); + + for (var i = 0; i < siblingDecls.length; i++) { + var sibling = siblingDecls[i]; + + var siblingIsSomeValue = TypeScript.hasFlag(sibling.kind, 68147712 /* SomeValue */); + var siblingIsFunctionOrHasImplictVarFlag = TypeScript.hasFlag(sibling.kind, 1032192 /* SomeFunction */) || TypeScript.hasFlag(sibling.flags, 118784 /* ImplicitVariable */); + + var isSiblingAnAugmentableVariable = sibling !== decl && sibling !== decl.getValueDecl() && sibling.name === modName && siblingIsSomeValue && siblingIsFunctionOrHasImplictVarFlag; + + if (isSiblingAnAugmentableVariable) { + if (sibling.hasSymbol()) { + variableSymbol = sibling.getSymbol(); + if (variableSymbol.isContainer()) { + variableSymbol = variableSymbol.getInstanceSymbol(); + } else if (variableSymbol && variableSymbol.isType()) { + variableSymbol = variableSymbol.getConstructorMethod(); + } + + break; + } + } + } + } + return variableSymbol; + }; + + PullSymbolBinder.prototype.bindModuleDeclarationToPullSymbol = function (moduleContainerDecl) { + var modName = moduleContainerDecl.name; + + var moduleContainerTypeSymbol = null; + var moduleKind = moduleContainerDecl.kind; + + var parent = this.getParent(moduleContainerDecl); + var parentInstanceSymbol = this.getParent(moduleContainerDecl, true); + var parentDecl = moduleContainerDecl.getParentDecl(); + var moduleNameAST = this.semanticInfoChain.getASTForDecl(moduleContainerDecl); + var moduleDeclAST = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(moduleNameAST); + if (!moduleDeclAST) { + TypeScript.Debug.assert(moduleKind === 32 /* DynamicModule */); + TypeScript.Debug.assert(moduleNameAST.kind() === 120 /* SourceUnit */); + + moduleDeclAST = moduleNameAST; + } + + var isExported = TypeScript.hasFlag(moduleContainerDecl.flags, 1 /* Exported */); + var searchKind = 164 /* SomeContainer */; + var isInitializedModule = (moduleContainerDecl.flags & 102400 /* SomeInitializedModule */) !== 0; + + if (parent && moduleKind === 32 /* DynamicModule */) { + this.semanticInfoChain.addDiagnosticFromAST(moduleNameAST, TypeScript.DiagnosticCode.Ambient_external_module_declaration_must_be_defined_in_global_context, null); + } + + var createdNewSymbol = false; + + moduleContainerTypeSymbol = this.getExistingSymbol(moduleContainerDecl, searchKind, parent); + + if (moduleContainerTypeSymbol) { + if (moduleContainerTypeSymbol.kind !== moduleKind) { + if (isInitializedModule) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(moduleNameAST, moduleContainerDecl.getDisplayName(), moduleContainerTypeSymbol.getDeclarations()[0].ast()); + } + + moduleContainerTypeSymbol = null; + } else if (moduleKind === 32 /* DynamicModule */) { + this.semanticInfoChain.addDiagnosticFromAST(moduleNameAST, TypeScript.DiagnosticCode.Ambient_external_module_declaration_cannot_be_reopened); + } else if (!this.checkThatExportsMatch(moduleContainerDecl, moduleContainerTypeSymbol)) { + moduleContainerTypeSymbol = null; + } + } + + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = new TypeScript.PullContainerSymbol(modName, moduleKind); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(moduleContainerTypeSymbol, searchKind); + } + } + + moduleContainerTypeSymbol.addDeclaration(moduleContainerDecl); + moduleContainerDecl.setSymbol(moduleContainerTypeSymbol); + + this.semanticInfoChain.setSymbolForAST(moduleNameAST, moduleContainerTypeSymbol); + this.semanticInfoChain.setSymbolForAST(moduleDeclAST, moduleContainerTypeSymbol); + + var currentModuleValueDecl = moduleContainerDecl.getValueDecl(); + + var moduleDeclarations = moduleContainerTypeSymbol.getDeclarations(); + + if (createdNewSymbol) { + if (parent) { + if (moduleContainerDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberContainer(moduleContainerTypeSymbol); + } else { + parent.addEnclosedNonMemberContainer(moduleContainerTypeSymbol); + } + } + } + + if (currentModuleValueDecl) { + currentModuleValueDecl.ensureSymbolIsBound(); + + var instanceSymbol = null; + var instanceTypeSymbol = null; + if (currentModuleValueDecl.hasSymbol()) { + instanceSymbol = currentModuleValueDecl.getSymbol(); + } else { + instanceSymbol = new TypeScript.PullSymbol(modName, 512 /* Variable */); + currentModuleValueDecl.setSymbol(instanceSymbol); + if (!instanceSymbol.hasDeclaration(currentModuleValueDecl)) { + instanceSymbol.addDeclaration(currentModuleValueDecl); + } + } + + if (!instanceSymbol.type) { + instanceSymbol.type = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + } + + moduleContainerTypeSymbol.setInstanceSymbol(instanceSymbol); + + if (!instanceSymbol.type.getAssociatedContainerType()) { + instanceSymbol.type.setAssociatedContainerType(moduleContainerTypeSymbol); + } + } + }; + + PullSymbolBinder.prototype.bindImportDeclaration = function (importDeclaration) { + var declFlags = importDeclaration.flags; + var declKind = importDeclaration.kind; + var importDeclAST = this.semanticInfoChain.getASTForDecl(importDeclaration); + + var isExported = false; + var importSymbol = null; + var declName = importDeclaration.name; + var parentHadSymbol = false; + var parent = this.getParent(importDeclaration); + + importSymbol = this.getExistingSymbol(importDeclaration, 164 /* SomeContainer */, parent); + + if (importSymbol) { + parentHadSymbol = true; + } + + if (importSymbol) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(importDeclAST, importDeclaration.getDisplayName(), importSymbol.getDeclarations()[0].ast()); + importSymbol = null; + } + + if (!importSymbol) { + importSymbol = new TypeScript.PullTypeAliasSymbol(declName); + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(importSymbol, 164 /* SomeContainer */); + } + } + + importSymbol.addDeclaration(importDeclaration); + importDeclaration.setSymbol(importSymbol); + + this.semanticInfoChain.setSymbolForAST(importDeclAST, importSymbol); + + if (parent && !parentHadSymbol) { + if (declFlags & 1 /* Exported */) { + parent.addEnclosedMemberContainer(importSymbol); + } else { + parent.addEnclosedNonMemberContainer(importSymbol); + } + } + }; + + PullSymbolBinder.prototype.ensurePriorDeclarationsAreBound = function (container, currentDecl) { + if (!container) { + return; + } + + var parentDecls = container.getDeclarations(); + for (var i = 0; i < parentDecls.length; ++i) { + var parentDecl = parentDecls[i]; + var childDecls = parentDecl.getChildDecls(); + for (var j = 0; j < childDecls.length; ++j) { + var childDecl = childDecls[j]; + if (childDecl === currentDecl) { + return; + } + + if (childDecl.name === currentDecl.name) { + childDecl.ensureSymbolIsBound(); + } + } + } + }; + + PullSymbolBinder.prototype.bindClassDeclarationToPullSymbol = function (classDecl) { + var className = classDecl.name; + var classSymbol = null; + + var constructorSymbol = null; + var constructorTypeSymbol = null; + + var classAST = this.semanticInfoChain.getASTForDecl(classDecl); + + var parent = this.getParent(classDecl); + + this.ensurePriorDeclarationsAreBound(parent, classDecl); + + var parentDecl = classDecl.getParentDecl(); + var isExported = classDecl.flags & 1 /* Exported */; + var isGeneric = false; + + classSymbol = this.getExistingSymbol(classDecl, 58728795 /* SomeType */, parent); + + if (classSymbol && classSymbol.kind === 16 /* Interface */) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(classAST.identifier, classDecl.getDisplayName(), classSymbol.getDeclarations()[0].ast()); + classSymbol = null; + } + + classSymbol = new TypeScript.PullTypeSymbol(className, 8 /* Class */); + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(classSymbol, 8 /* Class */); + } + + classSymbol.addDeclaration(classDecl); + + classDecl.setSymbol(classSymbol); + + this.semanticInfoChain.setSymbolForAST(classAST.identifier, classSymbol); + this.semanticInfoChain.setSymbolForAST(classAST, classSymbol); + + if (parent) { + if (classDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberType(classSymbol); + } else { + parent.addEnclosedNonMemberType(classSymbol); + } + } + + var typeParameterDecls = classDecl.getTypeParameters(); + + for (var i = 0; i < typeParameterDecls.length; i++) { + var typeParameterSymbol = classSymbol.findTypeParameter(typeParameterDecls[i].name); + + if (typeParameterSymbol) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterSymbol.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameterSymbol.getName()]); + } + + typeParameterSymbol = new TypeScript.PullTypeParameterSymbol(typeParameterDecls[i].name); + + classSymbol.addTypeParameter(typeParameterSymbol); + typeParameterSymbol.addDeclaration(typeParameterDecls[i]); + typeParameterDecls[i].setSymbol(typeParameterSymbol); + } + + constructorSymbol = classSymbol.getConstructorMethod(); + constructorTypeSymbol = constructorSymbol ? constructorSymbol.type : null; + + if (!constructorSymbol) { + var siblingValueDecls = null; + if (parentDecl) { + siblingValueDecls = parentDecl.searchChildDecls(className, 68147712 /* SomeValue */); + + if (siblingValueDecls && siblingValueDecls[0] && siblingValueDecls[0].hasSymbol()) { + constructorSymbol = siblingValueDecls[0].getSymbol(); + } + } + + if (constructorSymbol) { + constructorTypeSymbol = constructorSymbol.type; + } else { + constructorSymbol = new TypeScript.PullSymbol(className, 32768 /* ConstructorMethod */); + constructorTypeSymbol = new TypeScript.PullTypeSymbol("", 33554432 /* ConstructorType */); + constructorSymbol.setIsSynthesized(); + constructorSymbol.type = constructorTypeSymbol; + } + + classSymbol.setConstructorMethod(constructorSymbol); + classSymbol.setHasDefaultConstructor(); + } + + if (constructorSymbol.getIsSynthesized()) { + constructorSymbol.addDeclaration(classDecl.getValueDecl()); + constructorTypeSymbol.addDeclaration(classDecl); + } else { + classSymbol.setHasDefaultConstructor(false); + } + + constructorTypeSymbol.setAssociatedContainerType(classSymbol); + + var valueDecl = classDecl.getValueDecl(); + + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + + this.bindStaticPrototypePropertyOfClass(classAST, classSymbol, constructorTypeSymbol); + }; + + PullSymbolBinder.prototype.bindInterfaceDeclarationToPullSymbol = function (interfaceDecl) { + var interfaceName = interfaceDecl.name; + var interfaceSymbol = null; + + var interfaceAST = this.semanticInfoChain.getASTForDecl(interfaceDecl); + var createdNewSymbol = false; + var parent = this.getParent(interfaceDecl); + + var acceptableSharedKind = 16 /* Interface */; + + interfaceSymbol = this.getExistingSymbol(interfaceDecl, 58728795 /* SomeType */, parent); + + if (interfaceSymbol) { + if (!(interfaceSymbol.kind & acceptableSharedKind)) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(interfaceAST.identifier, interfaceDecl.getDisplayName(), interfaceSymbol.getDeclarations()[0].ast()); + interfaceSymbol = null; + } else if (!this.checkThatExportsMatch(interfaceDecl, interfaceSymbol)) { + interfaceSymbol = null; + } + } + + if (!interfaceSymbol) { + interfaceSymbol = new TypeScript.PullTypeSymbol(interfaceName, 16 /* Interface */); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(interfaceSymbol, acceptableSharedKind); + } + } + + interfaceSymbol.addDeclaration(interfaceDecl); + interfaceDecl.setSymbol(interfaceSymbol); + + if (createdNewSymbol) { + if (parent) { + if (interfaceDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberType(interfaceSymbol); + } else { + parent.addEnclosedNonMemberType(interfaceSymbol); + } + } + } + + var typeParameters = interfaceDecl.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = interfaceSymbol.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + interfaceSymbol.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + for (var j = 0; j < typeParameterDecls.length; j++) { + var typeParameterDeclParent = typeParameterDecls[j].getParentDecl(); + + if (typeParameterDeclParent && typeParameterDeclParent === interfaceDecl) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + + break; + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + }; + + PullSymbolBinder.prototype.bindObjectTypeDeclarationToPullSymbol = function (objectDecl) { + var objectSymbolAST = this.semanticInfoChain.getASTForDecl(objectDecl); + + var objectSymbol = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + + objectSymbol.addDeclaration(objectDecl); + objectDecl.setSymbol(objectSymbol); + + this.semanticInfoChain.setSymbolForAST(objectSymbolAST, objectSymbol); + + var childDecls = objectDecl.getChildDecls(); + + for (var i = 0; i < childDecls.length; i++) { + this.bindDeclToPullSymbol(childDecls[i]); + } + }; + + PullSymbolBinder.prototype.bindConstructorTypeDeclarationToPullSymbol = function (constructorTypeDeclaration) { + var declKind = constructorTypeDeclaration.kind; + var declFlags = constructorTypeDeclaration.flags; + var constructorTypeAST = this.semanticInfoChain.getASTForDecl(constructorTypeDeclaration); + + var constructorTypeSymbol = new TypeScript.PullTypeSymbol("", 33554432 /* ConstructorType */); + + constructorTypeDeclaration.setSymbol(constructorTypeSymbol); + constructorTypeSymbol.addDeclaration(constructorTypeDeclaration); + this.semanticInfoChain.setSymbolForAST(constructorTypeAST, constructorTypeSymbol); + + var signature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + + var funcDecl = this.semanticInfoChain.getASTForDecl(constructorTypeDeclaration); + if (TypeScript.lastParameterIsRest(funcDecl.parameterList)) { + signature.hasVarArgs = true; + } + + signature.addDeclaration(constructorTypeDeclaration); + constructorTypeDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList), constructorTypeSymbol, signature); + + var typeParameters = constructorTypeDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = constructorTypeSymbol.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.name]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + constructorTypeSymbol.appendConstructSignature(signature); + }; + + PullSymbolBinder.prototype.bindVariableDeclarationToPullSymbol = function (variableDeclaration) { + var declFlags = variableDeclaration.flags; + var declKind = variableDeclaration.kind; + var varDeclAST = this.semanticInfoChain.getASTForDecl(variableDeclaration); + var nameAST = varDeclAST.kind() === 131 /* ClassDeclaration */ ? varDeclAST.identifier : varDeclAST.kind() === 225 /* VariableDeclarator */ ? varDeclAST.propertyName : varDeclAST.kind() === 132 /* EnumDeclaration */ ? varDeclAST.identifier : varDeclAST; + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var variableSymbol = null; + + var declName = variableDeclaration.name; + + var parentHadSymbol = false; + + var parent = this.getParent(variableDeclaration, true); + + var parentDecl = variableDeclaration.getParentDecl(); + + var isImplicit = (declFlags & 118784 /* ImplicitVariable */) !== 0; + var isModuleValue = (declFlags & (32768 /* InitializedModule */)) !== 0; + var isEnumValue = (declFlags & 4096 /* Enum */) !== 0; + var isClassConstructorVariable = (declFlags & 16384 /* ClassConstructorVariable */) !== 0; + variableSymbol = this.getExistingSymbol(variableDeclaration, 68147712 /* SomeValue */, parent); + + if (!variableSymbol && isModuleValue) { + variableSymbol = this.findExistingVariableSymbolForModuleValueDecl(variableDeclaration.getContainerDecl()); + } + + if (variableSymbol && !variableSymbol.isType()) { + parentHadSymbol = true; + } + + var decl; + var decls; + var ast; + var members; + + if (variableSymbol) { + var prevKind = variableSymbol.kind; + var prevIsEnum = variableSymbol.anyDeclHasFlag(4096 /* Enum */); + var prevIsClassConstructorVariable = variableSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */); + var prevIsModuleValue = variableSymbol.allDeclsHaveFlag(32768 /* InitializedModule */); + var prevIsImplicit = variableSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */); + var prevIsFunction = TypeScript.ArrayUtilities.any(variableSymbol.getDeclarations(), function (decl) { + return decl.kind === 16384 /* Function */; + }); + var prevIsAmbient = variableSymbol.allDeclsHaveFlag(8 /* Ambient */); + var isAmbientOrPrevIsAmbient = prevIsAmbient || (variableDeclaration.flags & 8 /* Ambient */) !== 0; + var prevDecl = variableSymbol.getDeclarations()[0]; + var prevParentDecl = prevDecl.getParentDecl(); + var bothAreGlobal = parentDecl && (parentDecl.kind === 1 /* Script */) && (prevParentDecl.kind === 1 /* Script */); + var shareParent = bothAreGlobal || prevDecl.getParentDecl() === variableDeclaration.getParentDecl(); + var prevIsParam = shareParent && prevKind === 2048 /* Parameter */ && declKind == 512 /* Variable */; + + var acceptableRedeclaration = prevIsParam || (isImplicit && ((!isEnumValue && !isClassConstructorVariable && prevIsFunction) || ((isModuleValue || isEnumValue) && (prevIsModuleValue || prevIsEnum)) || (isClassConstructorVariable && prevIsModuleValue && isAmbientOrPrevIsAmbient) || (isModuleValue && prevIsClassConstructorVariable))); + + if (acceptableRedeclaration && (prevIsClassConstructorVariable || prevIsFunction) && !isAmbientOrPrevIsAmbient) { + if (prevDecl.fileName() !== variableDeclaration.fileName()) { + this.semanticInfoChain.addDiagnostic(TypeScript.PullHelpers.diagnosticFromDecl(variableDeclaration, TypeScript.DiagnosticCode.Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2, [declName, declName, prevDecl.fileName()])); + variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); + } + } + + if (!acceptableRedeclaration || prevIsParam) { + if (!prevIsParam && (isImplicit || prevIsImplicit || TypeScript.hasFlag(prevKind, 1032192 /* SomeFunction */)) || !shareParent) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(nameAST, variableDeclaration.getDisplayName(), variableSymbol.getDeclarations()[0].ast()); + variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); + } else { + this.checkThatExportsMatch(variableDeclaration, variableSymbol); + variableSymbol = null; + parentHadSymbol = false; + } + } + + if (variableSymbol && !(variableSymbol.type && variableSymbol.type.isError()) && !this.checkThatExportsMatch(variableDeclaration, variableSymbol, !(isModuleValue && prevIsModuleValue))) { + variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); + } + } + + if ((declFlags & 118784 /* ImplicitVariable */) === 0) { + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + if (!parent && parentDecl.kind === 1 /* Script */) { + this.semanticInfoChain.cacheGlobalSymbol(variableSymbol, declKind); + } + } + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + this.semanticInfoChain.setSymbolForAST(nameAST, variableSymbol); + this.semanticInfoChain.setSymbolForAST(varDeclAST, variableSymbol); + } else if (!parentHadSymbol) { + if (isClassConstructorVariable) { + var classTypeSymbol = variableSymbol; + + if (parent) { + members = parent.getMembers(); + + for (var i = 0; i < members.length; i++) { + if ((members[i].name === declName) && (members[i].kind === 8 /* Class */)) { + classTypeSymbol = members[i]; + break; + } + } + } + + if (!classTypeSymbol) { + var containerDecl = variableDeclaration.getContainerDecl(); + classTypeSymbol = containerDecl.getSymbol(); + if (!classTypeSymbol) { + classTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 58728795 /* SomeType */, variableDeclaration); + } + } + + if (classTypeSymbol && (classTypeSymbol.kind !== 8 /* Class */)) { + classTypeSymbol = null; + } + + if (classTypeSymbol && classTypeSymbol.isClass()) { + variableSymbol = classTypeSymbol.getConstructorMethod(); + variableDeclaration.setSymbol(variableSymbol); + + decls = classTypeSymbol.getDeclarations(); + + if (decls.length) { + decl = decls[decls.length - 1]; + ast = this.semanticInfoChain.getASTForDecl(decl); + } + } else { + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + } + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + variableSymbol.type = this.semanticInfoChain.anyTypeSymbol; + } + } else if (declFlags & 102400 /* SomeInitializedModule */) { + var moduleContainerTypeSymbol = null; + var moduleParent = this.getParent(variableDeclaration); + + if (moduleParent) { + members = moduleParent.getMembers(); + + for (var i = 0; i < members.length; i++) { + if ((members[i].name === declName) && (members[i].isContainer())) { + moduleContainerTypeSymbol = members[i]; + break; + } + } + } + + if (!moduleContainerTypeSymbol) { + var containerDecl = variableDeclaration.getContainerDecl(); + moduleContainerTypeSymbol = containerDecl.getSymbol(); + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 164 /* SomeContainer */, variableDeclaration); + + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 64 /* Enum */, variableDeclaration); + } + } + } + + if (moduleContainerTypeSymbol && (!moduleContainerTypeSymbol.isContainer())) { + moduleContainerTypeSymbol = null; + } + + if (moduleContainerTypeSymbol) { + variableSymbol = moduleContainerTypeSymbol.getInstanceSymbol(); + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + variableSymbol.type = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + } + + if (!variableSymbol.hasDeclaration(variableDeclaration)) { + variableSymbol.addDeclaration(variableDeclaration); + } + variableDeclaration.setSymbol(variableSymbol); + } else { + TypeScript.Debug.assert(false, "Attempted to bind invalid implicit variable symbol"); + } + } + } else { + if (!variableSymbol.hasDeclaration(variableDeclaration)) { + variableSymbol.addDeclaration(variableDeclaration); + } + variableDeclaration.setSymbol(variableSymbol); + } + + var containerDecl = variableDeclaration.getContainerDecl(); + if (variableSymbol && variableSymbol.type && containerDecl && !variableSymbol.type.hasDeclaration(containerDecl)) { + variableSymbol.type.addDeclaration(containerDecl); + } + + if (parent && !parentHadSymbol) { + if (declFlags & 1 /* Exported */) { + parent.addMember(variableSymbol); + } else { + parent.addEnclosedNonMember(variableSymbol); + } + } + }; + + PullSymbolBinder.prototype.bindCatchVariableToPullSymbol = function (variableDeclaration) { + var declFlags = variableDeclaration.flags; + var declKind = variableDeclaration.kind; + var identifier = this.semanticInfoChain.getASTForDecl(variableDeclaration); + + var declName = variableDeclaration.name; + + var variableSymbol = new TypeScript.PullSymbol(declName, declKind); + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + variableSymbol.type = this.semanticInfoChain.anyTypeSymbol; + + this.semanticInfoChain.setSymbolForAST(identifier, variableSymbol); + }; + + PullSymbolBinder.prototype.bindEnumMemberDeclarationToPullSymbol = function (propertyDeclaration) { + var declFlags = propertyDeclaration.flags; + var declKind = propertyDeclaration.kind; + var propDeclAST = this.semanticInfoChain.getASTForDecl(propertyDeclaration); + + var declName = propertyDeclaration.name; + + var parentHadSymbol = false; + + var parent = this.getParent(propertyDeclaration, true); + + var propertySymbol = parent.findMember(declName, false); + + if (propertySymbol) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(propDeclAST.propertyName, propertyDeclaration.getDisplayName(), propertySymbol.getDeclarations()[0].ast()); + } + + if (propertySymbol) { + parentHadSymbol = true; + } + + if (!parentHadSymbol) { + propertySymbol = new TypeScript.PullSymbol(declName, declKind); + } + + propertySymbol.addDeclaration(propertyDeclaration); + propertyDeclaration.setSymbol(propertySymbol); + + this.semanticInfoChain.setSymbolForAST(propDeclAST.propertyName, propertySymbol); + this.semanticInfoChain.setSymbolForAST(propDeclAST, propertySymbol); + + if (parent && !parentHadSymbol) { + parent.addMember(propertySymbol); + } + }; + + PullSymbolBinder.prototype.bindPropertyDeclarationToPullSymbol = function (propertyDeclaration) { + var declFlags = propertyDeclaration.flags; + var declKind = propertyDeclaration.kind; + + var ast = this.semanticInfoChain.getASTForDecl(propertyDeclaration); + var astName = ast.kind() === 136 /* MemberVariableDeclaration */ ? ast.variableDeclarator.propertyName : ast.kind() === 141 /* PropertySignature */ ? ast.propertyName : ast.kind() === 242 /* Parameter */ ? ast.identifier : ast.propertyName; + + var isStatic = false; + var isOptional = false; + + var propertySymbol = null; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + if (TypeScript.hasFlag(declFlags, 128 /* Optional */)) { + isOptional = true; + } + + var declName = propertyDeclaration.name; + + var parentHadSymbol = false; + + var parent = this.getParent(propertyDeclaration, true); + + if (parent.isClass() && isStatic) { + parent = parent.getConstructorMethod().type; + } + + propertySymbol = parent.findMember(declName, false); + + if (propertySymbol) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(astName, propertyDeclaration.getDisplayName(), propertySymbol.getDeclarations()[0].ast()); + } + + if (propertySymbol) { + parentHadSymbol = true; + } + + var classTypeSymbol; + + if (!parentHadSymbol) { + propertySymbol = new TypeScript.PullSymbol(declName, declKind); + } + + propertySymbol.addDeclaration(propertyDeclaration); + propertyDeclaration.setSymbol(propertySymbol); + + this.semanticInfoChain.setSymbolForAST(astName, propertySymbol); + this.semanticInfoChain.setSymbolForAST(ast, propertySymbol); + + if (isOptional) { + propertySymbol.isOptional = true; + } + + if (parent && !parentHadSymbol) { + parent.addMember(propertySymbol); + } + }; + + PullSymbolBinder.prototype.bindParameterSymbols = function (functionDeclaration, parameterList, funcType, signatureSymbol) { + var parameters = []; + var params = TypeScript.createIntrinsicsObject(); + var funcDecl = this.semanticInfoChain.getDeclForAST(functionDeclaration); + + if (parameterList) { + for (var i = 0, n = parameterList.length; i < n; i++) { + var argDecl = parameterList.astAt(i); + var id = parameterList.identifierAt(i); + var decl = this.semanticInfoChain.getDeclForAST(argDecl); + var isProperty = TypeScript.hasFlag(decl.flags, 8388608 /* PropertyParameter */); + var parameterSymbol = new TypeScript.PullSymbol(id.valueText(), 2048 /* Parameter */); + + if ((i === (n - 1)) && parameterList.lastParameterIsRest()) { + parameterSymbol.isVarArg = true; + } + + if (params[id.valueText()]) { + this.semanticInfoChain.addDiagnosticFromAST(argDecl, TypeScript.DiagnosticCode.Duplicate_identifier_0, [id.text()]); + } else { + params[id.valueText()] = true; + } + + if (decl) { + var isParameterOptional = false; + + if (isProperty) { + decl.ensureSymbolIsBound(); + var valDecl = decl.getValueDecl(); + + if (valDecl) { + isParameterOptional = TypeScript.hasFlag(valDecl.flags, 128 /* Optional */); + + valDecl.setSymbol(parameterSymbol); + parameterSymbol.addDeclaration(valDecl); + } + } else { + isParameterOptional = TypeScript.hasFlag(decl.flags, 128 /* Optional */); + + parameterSymbol.addDeclaration(decl); + decl.setSymbol(parameterSymbol); + } + + parameterSymbol.isOptional = isParameterOptional; + } + + signatureSymbol.addParameter(parameterSymbol, parameterSymbol.isOptional); + + if (signatureSymbol.isDefinition()) { + funcType.addEnclosedNonMember(parameterSymbol); + } + } + } + }; + + PullSymbolBinder.prototype.bindFunctionDeclarationToPullSymbol = function (functionDeclaration) { + var declKind = functionDeclaration.kind; + var declFlags = functionDeclaration.flags; + var funcDeclAST = this.semanticInfoChain.getASTForDecl(functionDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = functionDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(functionDeclaration, true); + + var parentDecl = functionDeclaration.getParentDecl(); + var parentHadSymbol = false; + + var functionSymbol = null; + var functionTypeSymbol = null; + + functionSymbol = this.getExistingSymbol(functionDeclaration, 68147712 /* SomeValue */, parent); + + if (functionSymbol) { + var acceptableRedeclaration; + + if (functionSymbol.kind === 16384 /* Function */) { + acceptableRedeclaration = isSignature || functionSymbol.allDeclsHaveFlag(2048 /* Signature */); + } else { + var isCurrentDeclAmbient = TypeScript.hasFlag(functionDeclaration.flags, 8 /* Ambient */); + acceptableRedeclaration = TypeScript.ArrayUtilities.all(functionSymbol.getDeclarations(), function (decl) { + var isInitializedModuleOrAmbientDecl = TypeScript.hasFlag(decl.flags, 32768 /* InitializedModule */) && (isCurrentDeclAmbient || TypeScript.hasFlag(decl.flags, 8 /* Ambient */)); + var isSignature = TypeScript.hasFlag(decl.flags, 2048 /* Signature */); + return isInitializedModuleOrAmbientDecl || isSignature; + }); + } + + if (!acceptableRedeclaration) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.identifier, functionDeclaration.getDisplayName(), functionSymbol.getDeclarations()[0].ast()); + functionSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(funcName); + } + } + + if (functionSymbol) { + functionTypeSymbol = functionSymbol.type; + parentHadSymbol = true; + } + + if (!functionSymbol) { + functionSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + } + + if (!functionTypeSymbol) { + functionTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + functionSymbol.type = functionTypeSymbol; + functionTypeSymbol.setFunctionSymbol(functionSymbol); + } + + functionDeclaration.setSymbol(functionSymbol); + functionSymbol.addDeclaration(functionDeclaration); + functionTypeSymbol.addDeclaration(functionDeclaration); + + this.semanticInfoChain.setSymbolForAST(funcDeclAST.identifier, functionSymbol); + this.semanticInfoChain.setSymbolForAST(funcDeclAST, functionSymbol); + + if (parent && !parentHadSymbol) { + if (isExported) { + parent.addMember(functionSymbol); + } else { + parent.addEnclosedNonMember(functionSymbol); + } + } + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + signature.addDeclaration(functionDeclaration); + functionDeclaration.setSignatureSymbol(signature); + + if (TypeScript.lastParameterIsRest(funcDeclAST.callSignature.parameterList)) { + signature.hasVarArgs = true; + } + + var funcDecl = this.semanticInfoChain.getASTForDecl(functionDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), functionTypeSymbol, signature); + + var typeParameters = functionDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.name]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + functionTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindFunctionExpressionToPullSymbol = function (functionExpressionDeclaration) { + var declKind = functionExpressionDeclaration.kind; + var declFlags = functionExpressionDeclaration.flags; + var ast = this.semanticInfoChain.getASTForDecl(functionExpressionDeclaration); + + var parameters = ast.kind() === 219 /* SimpleArrowFunctionExpression */ ? TypeScript.ASTHelpers.parametersFromIdentifier(ast.identifier) : TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(ast)); + var funcExpAST = ast; + + var functionName = declKind === 131072 /* FunctionExpression */ ? functionExpressionDeclaration.getFunctionExpressionName() : functionExpressionDeclaration.name; + var functionSymbol = new TypeScript.PullSymbol(functionName, declKind); + var functionTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + functionTypeSymbol.setFunctionSymbol(functionSymbol); + + functionSymbol.type = functionTypeSymbol; + + functionExpressionDeclaration.setSymbol(functionSymbol); + functionSymbol.addDeclaration(functionExpressionDeclaration); + functionTypeSymbol.addDeclaration(functionExpressionDeclaration); + + var name = funcExpAST.kind() === 222 /* FunctionExpression */ ? funcExpAST.identifier : funcExpAST.kind() === 241 /* FunctionPropertyAssignment */ ? funcExpAST.propertyName : null; + if (name) { + this.semanticInfoChain.setSymbolForAST(name, functionSymbol); + } + + this.semanticInfoChain.setSymbolForAST(funcExpAST, functionSymbol); + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, true); + + if (parameters.lastParameterIsRest()) { + signature.hasVarArgs = true; + } + + var typeParameters = functionExpressionDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(functionExpressionDeclaration); + functionExpressionDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcExpAST, parameters, functionTypeSymbol, signature); + + functionTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindFunctionTypeDeclarationToPullSymbol = function (functionTypeDeclaration) { + var declKind = functionTypeDeclaration.kind; + var declFlags = functionTypeDeclaration.flags; + var funcTypeAST = this.semanticInfoChain.getASTForDecl(functionTypeDeclaration); + + var functionTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + + functionTypeDeclaration.setSymbol(functionTypeSymbol); + functionTypeSymbol.addDeclaration(functionTypeDeclaration); + this.semanticInfoChain.setSymbolForAST(funcTypeAST, functionTypeSymbol); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + if (TypeScript.lastParameterIsRest(funcTypeAST.parameterList)) { + signature.hasVarArgs = true; + } + + var typeParameters = functionTypeDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.name]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(functionTypeDeclaration); + functionTypeDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcTypeAST, TypeScript.ASTHelpers.parametersFromParameterList(funcTypeAST.parameterList), functionTypeSymbol, signature); + + functionTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindMethodDeclarationToPullSymbol = function (methodDeclaration) { + var declKind = methodDeclaration.kind; + var declFlags = methodDeclaration.flags; + var methodAST = this.semanticInfoChain.getASTForDecl(methodDeclaration); + + var isPrivate = (declFlags & 2 /* Private */) !== 0; + var isStatic = (declFlags & 16 /* Static */) !== 0; + var isOptional = (declFlags & 128 /* Optional */) !== 0; + + var methodName = methodDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(methodDeclaration, true); + var parentHadSymbol = false; + + var methodSymbol = null; + var methodTypeSymbol = null; + + if (parent.isClass() && isStatic) { + parent = parent.getConstructorMethod().type; + } + + methodSymbol = parent.findMember(methodName, false); + + if (methodSymbol && (methodSymbol.kind !== 65536 /* Method */ || (!isSignature && !methodSymbol.allDeclsHaveFlag(2048 /* Signature */)))) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(methodAST, methodDeclaration.getDisplayName(), methodSymbol.getDeclarations()[0].ast()); + methodSymbol = null; + } + + if (methodSymbol) { + methodTypeSymbol = methodSymbol.type; + parentHadSymbol = true; + } + + if (!methodSymbol) { + methodSymbol = new TypeScript.PullSymbol(methodName, 65536 /* Method */); + } + + if (!methodTypeSymbol) { + methodTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + methodSymbol.type = methodTypeSymbol; + methodTypeSymbol.setFunctionSymbol(methodSymbol); + } + + methodDeclaration.setSymbol(methodSymbol); + methodSymbol.addDeclaration(methodDeclaration); + methodTypeSymbol.addDeclaration(methodDeclaration); + + var nameAST = methodAST.kind() === 135 /* MemberFunctionDeclaration */ ? methodAST.propertyName : methodAST.propertyName; + + TypeScript.Debug.assert(nameAST); + + this.semanticInfoChain.setSymbolForAST(nameAST, methodSymbol); + this.semanticInfoChain.setSymbolForAST(methodAST, methodSymbol); + + if (isOptional) { + methodSymbol.isOptional = true; + } + + if (!parentHadSymbol) { + parent.addMember(methodSymbol); + } + + var sigKind = 1048576 /* CallSignature */; + + var signature = new TypeScript.PullSignatureSymbol(sigKind, !isSignature); + + var parameterList = TypeScript.ASTHelpers.getParameterList(methodAST); + if (TypeScript.lastParameterIsRest(parameterList)) { + signature.hasVarArgs = true; + } + + var typeParameters = methodDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterName; + var typeParameterAST; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameterName = typeParameters[i].name; + typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameters[i]); + + typeParameter = signature.findTypeParameter(typeParameterName); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameterName); + signature.addTypeParameter(typeParameter); + } else { + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(methodDeclaration); + methodDeclaration.setSignatureSymbol(signature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(methodDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(funcDecl)), methodTypeSymbol, signature); + + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(signature, methodTypeSymbol.getOwnCallSignatures()); + methodTypeSymbol.insertCallSignatureAtIndex(signature, signatureIndex); + }; + + PullSymbolBinder.prototype.bindStaticPrototypePropertyOfClass = function (classAST, classTypeSymbol, constructorTypeSymbol) { + var prototypeStr = "prototype"; + + var prototypeSymbol = constructorTypeSymbol.findMember(prototypeStr, false); + if (prototypeSymbol && !prototypeSymbol.getIsSynthesized()) { + this.semanticInfoChain.addDiagnostic(TypeScript.PullHelpers.diagnosticFromDecl(prototypeSymbol.getDeclarations()[0], TypeScript.DiagnosticCode.Duplicate_identifier_0, [prototypeSymbol.getDisplayName()])); + } + + if (!prototypeSymbol || !prototypeSymbol.getIsSynthesized()) { + var prototypeDecl = new TypeScript.PullSynthesizedDecl(prototypeStr, prototypeStr, 4096 /* Property */, 4 /* Public */ | 16 /* Static */, constructorTypeSymbol.getDeclarations()[0], this.semanticInfoChain); + + prototypeSymbol = new TypeScript.PullSymbol(prototypeStr, 4096 /* Property */); + prototypeSymbol.setIsSynthesized(); + prototypeSymbol.addDeclaration(prototypeDecl); + prototypeSymbol.type = classTypeSymbol; + constructorTypeSymbol.addMember(prototypeSymbol); + + if (prototypeSymbol.type && prototypeSymbol.type.isGeneric()) { + var resolver = this.semanticInfoChain.getResolver(); + prototypeSymbol.type = resolver.instantiateTypeToAny(prototypeSymbol.type, new TypeScript.PullTypeResolutionContext(resolver)); + } + prototypeSymbol.setResolved(); + } + }; + + PullSymbolBinder.prototype.bindConstructorDeclarationToPullSymbol = function (constructorDeclaration) { + var declKind = constructorDeclaration.kind; + var declFlags = constructorDeclaration.flags; + var constructorAST = this.semanticInfoChain.getASTForDecl(constructorDeclaration); + + var constructorName = constructorDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(constructorDeclaration, true); + + var parentHadSymbol = false; + + var constructorSymbol = parent.getConstructorMethod(); + var constructorTypeSymbol = null; + + if (constructorSymbol && (constructorSymbol.kind !== 32768 /* ConstructorMethod */ || (!isSignature && constructorSymbol.type && constructorSymbol.type.hasOwnConstructSignatures()))) { + var hasDefinitionSignature = false; + var constructorSigs = constructorSymbol.type.getOwnDeclaredConstructSignatures(); + + for (var i = 0; i < constructorSigs.length; i++) { + if (!constructorSigs[i].anyDeclHasFlag(2048 /* Signature */)) { + hasDefinitionSignature = true; + break; + } + } + + if (hasDefinitionSignature) { + this.semanticInfoChain.addDiagnosticFromAST(constructorAST, TypeScript.DiagnosticCode.Multiple_constructor_implementations_are_not_allowed); + + constructorSymbol = null; + } + } + + if (constructorSymbol) { + constructorTypeSymbol = constructorSymbol.type; + } else { + constructorSymbol = new TypeScript.PullSymbol(constructorName, 32768 /* ConstructorMethod */); + constructorTypeSymbol = new TypeScript.PullTypeSymbol("", 33554432 /* ConstructorType */); + } + + parent.setConstructorMethod(constructorSymbol); + constructorSymbol.type = constructorTypeSymbol; + + constructorDeclaration.setSymbol(constructorSymbol); + constructorSymbol.addDeclaration(constructorDeclaration); + constructorTypeSymbol.addDeclaration(constructorDeclaration); + constructorSymbol.setIsSynthesized(false); + this.semanticInfoChain.setSymbolForAST(constructorAST, constructorSymbol); + + var constructSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */, !isSignature); + constructSignature.returnType = parent; + constructSignature.addTypeParametersFromReturnType(); + + constructSignature.addDeclaration(constructorDeclaration); + constructorDeclaration.setSignatureSymbol(constructSignature); + + this.bindParameterSymbols(constructorAST, TypeScript.ASTHelpers.parametersFromParameterList(constructorAST.callSignature.parameterList), constructorTypeSymbol, constructSignature); + + if (TypeScript.lastParameterIsRest(constructorAST.callSignature.parameterList)) { + constructSignature.hasVarArgs = true; + } + + constructorTypeSymbol.appendConstructSignature(constructSignature); + }; + + PullSymbolBinder.prototype.bindConstructSignatureDeclarationToPullSymbol = function (constructSignatureDeclaration) { + var parent = this.getParent(constructSignatureDeclaration, true); + var constructorAST = this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration); + + var constructSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + + if (TypeScript.lastParameterIsRest(constructorAST.callSignature.parameterList)) { + constructSignature.hasVarArgs = true; + } + + var typeParameters = constructSignatureDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = constructSignature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + constructSignature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + constructSignature.addDeclaration(constructSignatureDeclaration); + constructSignatureDeclaration.setSignatureSymbol(constructSignature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(funcDecl)), null, constructSignature); + + this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration), constructSignature); + + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(constructSignature, parent.getOwnDeclaredConstructSignatures()); + parent.insertConstructSignatureAtIndex(constructSignature, signatureIndex); + }; + + PullSymbolBinder.prototype.bindCallSignatureDeclarationToPullSymbol = function (callSignatureDeclaration) { + var parent = this.getParent(callSignatureDeclaration, true); + var callSignatureAST = this.semanticInfoChain.getASTForDecl(callSignatureDeclaration); + + var callSignature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */); + + if (TypeScript.lastParameterIsRest(callSignatureAST.parameterList)) { + callSignature.hasVarArgs = true; + } + + var typeParameters = callSignatureDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = callSignature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + callSignature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + callSignature.addDeclaration(callSignatureDeclaration); + callSignatureDeclaration.setSignatureSymbol(callSignature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(callSignatureDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList), null, callSignature); + + this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(callSignatureDeclaration), callSignature); + + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(callSignature, parent.getOwnCallSignatures()); + parent.insertCallSignatureAtIndex(callSignature, signatureIndex); + }; + + PullSymbolBinder.prototype.bindIndexSignatureDeclarationToPullSymbol = function (indexSignatureDeclaration) { + var indexSignature = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + + indexSignature.addDeclaration(indexSignatureDeclaration); + indexSignatureDeclaration.setSignatureSymbol(indexSignature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(indexSignatureDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameter(funcDecl.parameter), null, indexSignature); + + this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(indexSignatureDeclaration), indexSignature); + + var parent = this.getParent(indexSignatureDeclaration); + parent.addIndexSignature(indexSignature); + indexSignature.setContainer(parent); + }; + + PullSymbolBinder.prototype.bindGetAccessorDeclarationToPullSymbol = function (getAccessorDeclaration) { + var declKind = getAccessorDeclaration.kind; + var declFlags = getAccessorDeclaration.flags; + var funcDeclAST = this.semanticInfoChain.getASTForDecl(getAccessorDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = getAccessorDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var isStatic = false; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + var parent = this.getParent(getAccessorDeclaration, true); + var parentHadSymbol = false; + + var accessorSymbol = null; + var getterSymbol = null; + var getterTypeSymbol = null; + + if (isStatic) { + parent = parent.getConstructorMethod().type; + } + + accessorSymbol = parent.findMember(funcName, false); + + if (accessorSymbol) { + if (!accessorSymbol.isAccessor()) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.propertyName, getAccessorDeclaration.getDisplayName(), accessorSymbol.getDeclarations()[0].ast()); + accessorSymbol = null; + } else { + getterSymbol = accessorSymbol.getGetter(); + + if (getterSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Getter_0_already_declared, [getAccessorDeclaration.getDisplayName()]); + accessorSymbol = null; + getterSymbol = null; + } + } + } + + if (accessorSymbol) { + parentHadSymbol = true; + } + + if (accessorSymbol && getterSymbol) { + getterTypeSymbol = getterSymbol.type; + } + + if (!accessorSymbol) { + accessorSymbol = new TypeScript.PullAccessorSymbol(funcName); + } + + if (!getterSymbol) { + getterSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + getterTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + getterTypeSymbol.setFunctionSymbol(getterSymbol); + + getterSymbol.type = getterTypeSymbol; + + accessorSymbol.setGetter(getterSymbol); + } + + getAccessorDeclaration.setSymbol(accessorSymbol); + accessorSymbol.addDeclaration(getAccessorDeclaration); + getterSymbol.addDeclaration(getAccessorDeclaration); + + var nameAST = funcDeclAST.propertyName; + this.semanticInfoChain.setSymbolForAST(nameAST, accessorSymbol); + this.semanticInfoChain.setSymbolForAST(funcDeclAST, getterSymbol); + + if (!parentHadSymbol) { + parent.addMember(accessorSymbol); + } + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + signature.addDeclaration(getAccessorDeclaration); + getAccessorDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcDeclAST, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), getterTypeSymbol, signature); + + getterTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindSetAccessorDeclarationToPullSymbol = function (setAccessorDeclaration) { + var declKind = setAccessorDeclaration.kind; + var declFlags = setAccessorDeclaration.flags; + var funcDeclAST = this.semanticInfoChain.getASTForDecl(setAccessorDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = setAccessorDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var isStatic = false; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + var parent = this.getParent(setAccessorDeclaration, true); + var parentHadSymbol = false; + + var accessorSymbol = null; + var setterSymbol = null; + var setterTypeSymbol = null; + + if (isStatic) { + parent = parent.getConstructorMethod().type; + } + + accessorSymbol = parent.findMember(funcName, false); + + if (accessorSymbol) { + if (!accessorSymbol.isAccessor()) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.propertyName, setAccessorDeclaration.getDisplayName(), accessorSymbol.getDeclarations()[0].ast()); + accessorSymbol = null; + } else { + setterSymbol = accessorSymbol.getSetter(); + + if (setterSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Setter_0_already_declared, [setAccessorDeclaration.getDisplayName()]); + accessorSymbol = null; + setterSymbol = null; + } + } + } + + if (accessorSymbol) { + parentHadSymbol = true; + + if (setterSymbol) { + setterTypeSymbol = setterSymbol.type; + } + } + + if (!accessorSymbol) { + accessorSymbol = new TypeScript.PullAccessorSymbol(funcName); + } + + if (!setterSymbol) { + setterSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + setterTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + setterTypeSymbol.setFunctionSymbol(setterSymbol); + + setterSymbol.type = setterTypeSymbol; + + accessorSymbol.setSetter(setterSymbol); + } + + setAccessorDeclaration.setSymbol(accessorSymbol); + accessorSymbol.addDeclaration(setAccessorDeclaration); + setterSymbol.addDeclaration(setAccessorDeclaration); + + var nameAST = funcDeclAST.propertyName; + this.semanticInfoChain.setSymbolForAST(nameAST, accessorSymbol); + this.semanticInfoChain.setSymbolForAST(funcDeclAST, setterSymbol); + + if (!parentHadSymbol) { + parent.addMember(accessorSymbol); + } + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + signature.addDeclaration(setAccessorDeclaration); + setAccessorDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcDeclAST, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), setterTypeSymbol, signature); + + setterTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.getDeclsToBind = function (decl) { + var decls; + switch (decl.kind) { + case 64 /* Enum */: + case 32 /* DynamicModule */: + case 4 /* Container */: + case 16 /* Interface */: + decls = this.findDeclsInContext(decl, decl.kind, true); + break; + + case 512 /* Variable */: + case 16384 /* Function */: + case 65536 /* Method */: + case 32768 /* ConstructorMethod */: + decls = this.findDeclsInContext(decl, decl.kind, false); + break; + + default: + decls = [decl]; + } + TypeScript.Debug.assert(decls && decls.length > 0); + TypeScript.Debug.assert(TypeScript.ArrayUtilities.contains(decls, decl)); + return decls; + }; + + PullSymbolBinder.prototype.shouldBindDeclaration = function (decl) { + return !decl.hasBeenBound() && this.declsBeingBound.indexOf(decl.declID) < 0; + }; + + PullSymbolBinder.prototype.bindDeclToPullSymbol = function (decl) { + if (this.shouldBindDeclaration(decl)) { + this.bindAllDeclsToPullSymbol(decl); + } + }; + + PullSymbolBinder.prototype.bindAllDeclsToPullSymbol = function (askedDecl) { + var allDecls = this.getDeclsToBind(askedDecl); + for (var i = 0; i < allDecls.length; i++) { + var decl = allDecls[i]; + + if (this.shouldBindDeclaration(decl)) { + this.bindSingleDeclToPullSymbol(decl); + } + } + }; + + PullSymbolBinder.prototype.bindSingleDeclToPullSymbol = function (decl) { + this.declsBeingBound.push(decl.declID); + + switch (decl.kind) { + case 1 /* Script */: + var childDecls = decl.getChildDecls(); + for (var i = 0; i < childDecls.length; i++) { + this.bindDeclToPullSymbol(childDecls[i]); + } + break; + + case 64 /* Enum */: + this.bindEnumDeclarationToPullSymbol(decl); + break; + + case 32 /* DynamicModule */: + case 4 /* Container */: + this.bindModuleDeclarationToPullSymbol(decl); + break; + + case 16 /* Interface */: + this.bindInterfaceDeclarationToPullSymbol(decl); + break; + + case 8 /* Class */: + this.bindClassDeclarationToPullSymbol(decl); + break; + + case 16384 /* Function */: + this.bindFunctionDeclarationToPullSymbol(decl); + break; + + case 512 /* Variable */: + this.bindVariableDeclarationToPullSymbol(decl); + break; + + case 1024 /* CatchVariable */: + this.bindCatchVariableToPullSymbol(decl); + break; + + case 67108864 /* EnumMember */: + this.bindEnumMemberDeclarationToPullSymbol(decl); + break; + + case 4096 /* Property */: + this.bindPropertyDeclarationToPullSymbol(decl); + break; + + case 65536 /* Method */: + this.bindMethodDeclarationToPullSymbol(decl); + break; + + case 32768 /* ConstructorMethod */: + this.bindConstructorDeclarationToPullSymbol(decl); + break; + + case 1048576 /* CallSignature */: + this.bindCallSignatureDeclarationToPullSymbol(decl); + break; + + case 2097152 /* ConstructSignature */: + this.bindConstructSignatureDeclarationToPullSymbol(decl); + break; + + case 4194304 /* IndexSignature */: + this.bindIndexSignatureDeclarationToPullSymbol(decl); + break; + + case 262144 /* GetAccessor */: + this.bindGetAccessorDeclarationToPullSymbol(decl); + break; + + case 524288 /* SetAccessor */: + this.bindSetAccessorDeclarationToPullSymbol(decl); + break; + + case 8388608 /* ObjectType */: + this.bindObjectTypeDeclarationToPullSymbol(decl); + break; + + case 16777216 /* FunctionType */: + this.bindFunctionTypeDeclarationToPullSymbol(decl); + break; + + case 33554432 /* ConstructorType */: + this.bindConstructorTypeDeclarationToPullSymbol(decl); + break; + + case 131072 /* FunctionExpression */: + this.bindFunctionExpressionToPullSymbol(decl); + break; + + case 128 /* TypeAlias */: + this.bindImportDeclaration(decl); + break; + + case 2048 /* Parameter */: + case 8192 /* TypeParameter */: + decl.getParentDecl().getSymbol(); + break; + + case 268435456 /* CatchBlock */: + case 134217728 /* WithBlock */: + break; + + default: + TypeScript.CompilerDiagnostics.assert(false, "Unrecognized type declaration"); + } + + TypeScript.Debug.assert(TypeScript.ArrayUtilities.last(this.declsBeingBound) === decl.declID); + this.declsBeingBound.pop(); + }; + return PullSymbolBinder; + })(); + TypeScript.PullSymbolBinder = PullSymbolBinder; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (PullHelpers) { + function diagnosticFromDecl(decl, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + var ast = decl.ast(); + return decl.semanticInfoChain.diagnosticFromAST(ast, diagnosticKey, _arguments, additionalLocations); + } + PullHelpers.diagnosticFromDecl = diagnosticFromDecl; + + function resolveDeclaredSymbolToUseType(symbol) { + if (symbol.isSignature()) { + if (!symbol.returnType) { + symbol._resolveDeclaredSymbol(); + } + } else if (!symbol.type) { + symbol._resolveDeclaredSymbol(); + } + } + PullHelpers.resolveDeclaredSymbolToUseType = resolveDeclaredSymbolToUseType; + + function getSignatureForFuncDecl(functionDecl) { + var funcDecl = functionDecl.ast(); + var funcSymbol = functionDecl.getSymbol(); + + if (!funcSymbol) { + funcSymbol = functionDecl.getSignatureSymbol(); + } + + var functionSignature = null; + var typeSymbolWithAllSignatures = null; + if (funcSymbol.isSignature()) { + functionSignature = funcSymbol; + var parent = functionDecl.getParentDecl(); + typeSymbolWithAllSignatures = parent.getSymbol().type; + } else { + functionSignature = functionDecl.getSignatureSymbol(); + typeSymbolWithAllSignatures = funcSymbol.type; + } + var signatures; + + if (funcDecl.kind() === 137 /* ConstructorDeclaration */ || functionDecl.kind === 2097152 /* ConstructSignature */) { + signatures = typeSymbolWithAllSignatures.getConstructSignatures(); + } else if (functionDecl.kind === 4194304 /* IndexSignature */) { + signatures = typeSymbolWithAllSignatures.getIndexSignatures(); + } else { + signatures = typeSymbolWithAllSignatures.getCallSignatures(); + } + + return { + signature: functionSignature, + allSignatures: signatures + }; + } + PullHelpers.getSignatureForFuncDecl = getSignatureForFuncDecl; + + function getAccessorSymbol(getterOrSetter, semanticInfoChain) { + var functionDecl = semanticInfoChain.getDeclForAST(getterOrSetter); + var getterOrSetterSymbol = functionDecl.getSymbol(); + + return getterOrSetterSymbol; + } + PullHelpers.getAccessorSymbol = getAccessorSymbol; + + function getGetterAndSetterFunction(funcDecl, semanticInfoChain) { + var accessorSymbol = PullHelpers.getAccessorSymbol(funcDecl, semanticInfoChain); + var result = { + getter: null, + setter: null + }; + var getter = accessorSymbol.getGetter(); + if (getter) { + var getterDecl = getter.getDeclarations()[0]; + result.getter = semanticInfoChain.getASTForDecl(getterDecl); + } + var setter = accessorSymbol.getSetter(); + if (setter) { + var setterDecl = setter.getDeclarations()[0]; + result.setter = semanticInfoChain.getASTForDecl(setterDecl); + } + + return result; + } + PullHelpers.getGetterAndSetterFunction = getGetterAndSetterFunction; + + function symbolIsEnum(source) { + return source && (source.kind & (64 /* Enum */ | 67108864 /* EnumMember */)) !== 0; + } + PullHelpers.symbolIsEnum = symbolIsEnum; + + function symbolIsModule(symbol) { + return symbol && (symbol.kind === 4 /* Container */ || isOneDeclarationOfKind(symbol, 4 /* Container */)); + } + PullHelpers.symbolIsModule = symbolIsModule; + + function isOneDeclarationOfKind(symbol, kind) { + var decls = symbol.getDeclarations(); + for (var i = 0; i < decls.length; i++) { + if (decls[i].kind === kind) { + return true; + } + } + + return false; + } + + function isNameNumeric(name) { + return isFinite(+name); + } + PullHelpers.isNameNumeric = isNameNumeric; + + function typeSymbolsAreIdentical(a, b) { + if (a.isTypeReference() && !a.getIsSpecialized()) { + a = a.referencedTypeSymbol; + } + + if (b.isTypeReference() && !b.getIsSpecialized()) { + b = b.referencedTypeSymbol; + } + + return a === b; + } + PullHelpers.typeSymbolsAreIdentical = typeSymbolsAreIdentical; + + function getRootType(type) { + var rootType = type.getRootSymbol(); + + while (true) { + if (type === rootType) { + return type; + } + + type = rootType; + rootType = type.getRootSymbol(); + } + } + PullHelpers.getRootType = getRootType; + + function isSymbolLocal(symbol) { + var container = symbol.getContainer(); + if (container) { + var containerKind = container.kind; + if (containerKind & (1032192 /* SomeFunction */ | 16777216 /* FunctionType */)) { + return true; + } + + if (containerKind === 33554432 /* ConstructorType */ && !symbol.anyDeclHasFlag(16 /* Static */ | 1 /* Exported */)) { + return true; + } + } + + return false; + } + PullHelpers.isSymbolLocal = isSymbolLocal; + + function isExportedSymbolInClodule(symbol) { + var container = symbol.getContainer(); + return container && container.kind === 33554432 /* ConstructorType */ && symbolIsModule(container) && symbol.anyDeclHasFlag(1 /* Exported */); + } + PullHelpers.isExportedSymbolInClodule = isExportedSymbolInClodule; + + function isSymbolDeclaredInScopeChain(symbol, scopeSymbol) { + TypeScript.Debug.assert(symbol); + var symbolDeclarationScope = symbol.getContainer(); + + while (scopeSymbol) { + if (scopeSymbol === symbolDeclarationScope) { + return true; + } + + scopeSymbol = scopeSymbol.getContainer(); + } + + if (scopeSymbol === null && symbolDeclarationScope === null) { + return true; + } + + return false; + } + PullHelpers.isSymbolDeclaredInScopeChain = isSymbolDeclaredInScopeChain; + + + + function walkSignatureSymbol(signatureSymbol, walker) { + var continueWalk = true; + var parameters = signatureSymbol.parameters; + if (parameters) { + for (var i = 0; continueWalk && i < parameters.length; i++) { + continueWalk = walker.signatureParameterWalk(parameters[i]); + } + } + + if (continueWalk) { + continueWalk = walker.signatureReturnTypeWalk(signatureSymbol.returnType); + } + + return continueWalk; + } + + function walkPullTypeSymbolStructure(typeSymbol, walker) { + var continueWalk = true; + + var members = typeSymbol.getMembers(); + for (var i = 0; continueWalk && i < members.length; i++) { + continueWalk = walker.memberSymbolWalk(members[i]); + } + + if (continueWalk) { + var callSigantures = typeSymbol.getCallSignatures(); + for (var i = 0; continueWalk && i < callSigantures.length; i++) { + continueWalk = walker.callSignatureWalk(callSigantures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(callSigantures[i], walker); + } + } + } + + if (continueWalk) { + var constructSignatures = typeSymbol.getConstructSignatures(); + for (var i = 0; continueWalk && i < constructSignatures.length; i++) { + continueWalk = walker.constructSignatureWalk(constructSignatures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(constructSignatures[i], walker); + } + } + } + + if (continueWalk) { + var indexSignatures = typeSymbol.getIndexSignatures(); + for (var i = 0; continueWalk && i < indexSignatures.length; i++) { + continueWalk = walker.indexSignatureWalk(indexSignatures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(indexSignatures[i], walker); + } + } + } + } + PullHelpers.walkPullTypeSymbolStructure = walkPullTypeSymbolStructure; + + var OtherPullDeclsWalker = (function () { + function OtherPullDeclsWalker() { + this.currentlyWalkingOtherDecls = []; + } + OtherPullDeclsWalker.prototype.walkOtherPullDecls = function (currentDecl, otherDecls, callBack) { + if (otherDecls) { + var isAlreadyWalkingOtherDecl = TypeScript.ArrayUtilities.any(this.currentlyWalkingOtherDecls, function (inWalkingOtherDecl) { + return TypeScript.ArrayUtilities.contains(otherDecls, inWalkingOtherDecl); + }); + + if (!isAlreadyWalkingOtherDecl) { + this.currentlyWalkingOtherDecls.push(currentDecl); + for (var i = 0; i < otherDecls.length; i++) { + if (otherDecls[i] !== currentDecl) { + callBack(otherDecls[i]); + } + } + var currentlyWalkingOtherDeclsDecl = this.currentlyWalkingOtherDecls.pop(); + TypeScript.Debug.assert(currentlyWalkingOtherDeclsDecl == currentDecl); + } + } + }; + return OtherPullDeclsWalker; + })(); + PullHelpers.OtherPullDeclsWalker = OtherPullDeclsWalker; + })(TypeScript.PullHelpers || (TypeScript.PullHelpers = {})); + var PullHelpers = TypeScript.PullHelpers; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var WrapsTypeParameterCache = (function () { + function WrapsTypeParameterCache() { + this._wrapsTypeParameterCache = TypeScript.BitVector.getBitVector(true); + } + WrapsTypeParameterCache.prototype.getWrapsTypeParameter = function (typeParameterArgumentMap) { + var mapHasTypeParameterNotCached = false; + for (var typeParameterID in typeParameterArgumentMap) { + if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + var cachedValue = this._wrapsTypeParameterCache.valueAt(typeParameterID); + if (cachedValue) { + return typeParameterID; + } + mapHasTypeParameterNotCached = mapHasTypeParameterNotCached || cachedValue === undefined; + } + } + + if (!mapHasTypeParameterNotCached) { + return 0; + } + + return undefined; + }; + + WrapsTypeParameterCache.prototype.setWrapsTypeParameter = function (typeParameterArgumentMap, wrappingTypeParameterID) { + if (wrappingTypeParameterID) { + this._wrapsTypeParameterCache.setValueAt(wrappingTypeParameterID, true); + } else { + for (var typeParameterID in typeParameterArgumentMap) { + if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + this._wrapsTypeParameterCache.setValueAt(typeParameterID, false); + } + } + } + }; + return WrapsTypeParameterCache; + })(); + TypeScript.WrapsTypeParameterCache = WrapsTypeParameterCache; + + (function (PullInstantiationHelpers) { + var MutableTypeArgumentMap = (function () { + function MutableTypeArgumentMap(typeParameterArgumentMap) { + this.typeParameterArgumentMap = typeParameterArgumentMap; + this.createdDuplicateTypeArgumentMap = false; + } + MutableTypeArgumentMap.prototype.ensureTypeArgumentCopy = function () { + if (!this.createdDuplicateTypeArgumentMap) { + var passedInTypeArgumentMap = this.typeParameterArgumentMap; + this.typeParameterArgumentMap = []; + for (var typeParameterID in passedInTypeArgumentMap) { + if (passedInTypeArgumentMap.hasOwnProperty(typeParameterID)) { + this.typeParameterArgumentMap[typeParameterID] = passedInTypeArgumentMap[typeParameterID]; + } + } + this.createdDuplicateTypeArgumentMap = true; + } + }; + return MutableTypeArgumentMap; + })(); + PullInstantiationHelpers.MutableTypeArgumentMap = MutableTypeArgumentMap; + + function instantiateTypeArgument(resolver, symbol, mutableTypeParameterMap) { + if (symbol.getIsSpecialized()) { + var rootTypeArgumentMap = symbol.getTypeParameterArgumentMap(); + var newTypeArgumentMap = []; + var allowedTypeParameters = symbol.getAllowedToReferenceTypeParameters(); + for (var i = 0; i < allowedTypeParameters.length; i++) { + var typeParameterID = allowedTypeParameters[i].pullSymbolID; + var typeArg = rootTypeArgumentMap[typeParameterID]; + if (typeArg) { + newTypeArgumentMap[typeParameterID] = resolver.instantiateType(typeArg, mutableTypeParameterMap.typeParameterArgumentMap); + } + } + + for (var i = 0; i < allowedTypeParameters.length; i++) { + var typeParameterID = allowedTypeParameters[i].pullSymbolID; + if (newTypeArgumentMap[typeParameterID] && mutableTypeParameterMap.typeParameterArgumentMap[typeParameterID] != newTypeArgumentMap[typeParameterID]) { + mutableTypeParameterMap.ensureTypeArgumentCopy(); + mutableTypeParameterMap.typeParameterArgumentMap[typeParameterID] = newTypeArgumentMap[typeParameterID]; + } + } + } + } + PullInstantiationHelpers.instantiateTypeArgument = instantiateTypeArgument; + + function cleanUpTypeArgumentMap(symbol, mutableTypeArgumentMap) { + var allowedToReferenceTypeParameters = symbol.getAllowedToReferenceTypeParameters(); + for (var typeParameterID in mutableTypeArgumentMap.typeParameterArgumentMap) { + if (mutableTypeArgumentMap.typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + if (!TypeScript.ArrayUtilities.any(allowedToReferenceTypeParameters, function (typeParameter) { + return typeParameter.pullSymbolID == typeParameterID; + })) { + mutableTypeArgumentMap.ensureTypeArgumentCopy(); + delete mutableTypeArgumentMap.typeParameterArgumentMap[typeParameterID]; + } + } + } + } + PullInstantiationHelpers.cleanUpTypeArgumentMap = cleanUpTypeArgumentMap; + + function getAllowedToReferenceTypeParametersFromDecl(decl) { + var allowedToReferenceTypeParameters = []; + + var allowedToUseDeclTypeParameters = false; + var getTypeParametersFromParentDecl = false; + + switch (decl.kind) { + case 65536 /* Method */: + if (TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + allowedToUseDeclTypeParameters = true; + break; + } + + case 16777216 /* FunctionType */: + case 33554432 /* ConstructorType */: + case 2097152 /* ConstructSignature */: + case 1048576 /* CallSignature */: + case 131072 /* FunctionExpression */: + case 16384 /* Function */: + allowedToUseDeclTypeParameters = true; + getTypeParametersFromParentDecl = true; + break; + + case 4096 /* Property */: + if (TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + break; + } + + case 2048 /* Parameter */: + case 262144 /* GetAccessor */: + case 524288 /* SetAccessor */: + case 32768 /* ConstructorMethod */: + case 4194304 /* IndexSignature */: + case 8388608 /* ObjectType */: + case 256 /* ObjectLiteral */: + case 8192 /* TypeParameter */: + getTypeParametersFromParentDecl = true; + break; + + case 8 /* Class */: + case 16 /* Interface */: + allowedToUseDeclTypeParameters = true; + break; + } + + if (getTypeParametersFromParentDecl) { + allowedToReferenceTypeParameters = allowedToReferenceTypeParameters.concat(getAllowedToReferenceTypeParametersFromDecl(decl.getParentDecl())); + } + + if (allowedToUseDeclTypeParameters) { + var typeParameterDecls = decl.getTypeParameters(); + for (var i = 0; i < typeParameterDecls.length; i++) { + allowedToReferenceTypeParameters.push(typeParameterDecls[i].getSymbol()); + } + } + + return allowedToReferenceTypeParameters; + } + PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl = getAllowedToReferenceTypeParametersFromDecl; + + function createTypeParameterArgumentMap(typeParameters, typeArguments) { + return updateTypeParameterArgumentMap(typeParameters, typeArguments, {}); + } + PullInstantiationHelpers.createTypeParameterArgumentMap = createTypeParameterArgumentMap; + + function updateTypeParameterArgumentMap(typeParameters, typeArguments, typeParameterArgumentMap) { + for (var i = 0; i < typeParameters.length; i++) { + typeParameterArgumentMap[typeParameters[i].getRootSymbol().pullSymbolID] = typeArguments[i]; + } + return typeParameterArgumentMap; + } + PullInstantiationHelpers.updateTypeParameterArgumentMap = updateTypeParameterArgumentMap; + + function updateMutableTypeParameterArgumentMap(typeParameters, typeArguments, mutableMap) { + for (var i = 0; i < typeParameters.length; i++) { + var typeParameterId = typeParameters[i].getRootSymbol().pullSymbolID; + if (mutableMap.typeParameterArgumentMap[typeParameterId] !== typeArguments[i]) { + mutableMap.ensureTypeArgumentCopy(); + mutableMap.typeParameterArgumentMap[typeParameterId] = typeArguments[i]; + } + } + } + PullInstantiationHelpers.updateMutableTypeParameterArgumentMap = updateMutableTypeParameterArgumentMap; + + function twoTypesAreInstantiationsOfSameNamedGenericType(type1, type2) { + var type1IsGeneric = type1.isGeneric() && type1.getTypeArguments() !== null; + var type2IsGeneric = type2.isGeneric() && type2.getTypeArguments() !== null; + + if (type1IsGeneric && type2IsGeneric) { + var type1Root = TypeScript.PullHelpers.getRootType(type1); + var type2Root = TypeScript.PullHelpers.getRootType(type2); + return type1Root === type2Root; + } + + return false; + } + PullInstantiationHelpers.twoTypesAreInstantiationsOfSameNamedGenericType = twoTypesAreInstantiationsOfSameNamedGenericType; + })(TypeScript.PullInstantiationHelpers || (TypeScript.PullInstantiationHelpers = {})); + var PullInstantiationHelpers = TypeScript.PullInstantiationHelpers; +})(TypeScript || (TypeScript = {})); +if (Error) + Error.stackTraceLimit = 1000; + +var TypeScript; +(function (TypeScript) { + TypeScript.fileResolutionTime = 0; + TypeScript.fileResolutionIOTime = 0; + TypeScript.fileResolutionScanImportsTime = 0; + TypeScript.fileResolutionImportFileSearchTime = 0; + TypeScript.fileResolutionGetDefaultLibraryTime = 0; + TypeScript.sourceCharactersCompiled = 0; + TypeScript.syntaxTreeParseTime = 0; + TypeScript.syntaxDiagnosticsTime = 0; + TypeScript.astTranslationTime = 0; + TypeScript.typeCheckTime = 0; + + TypeScript.compilerResolvePathTime = 0; + TypeScript.compilerDirectoryNameTime = 0; + TypeScript.compilerDirectoryExistsTime = 0; + TypeScript.compilerFileExistsTime = 0; + + TypeScript.emitTime = 0; + TypeScript.emitWriteFileTime = 0; + + TypeScript.declarationEmitTime = 0; + TypeScript.declarationEmitIsExternallyVisibleTime = 0; + TypeScript.declarationEmitTypeSignatureTime = 0; + TypeScript.declarationEmitGetBoundDeclTypeTime = 0; + TypeScript.declarationEmitIsOverloadedCallSignatureTime = 0; + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime = 0; + TypeScript.declarationEmitGetBaseTypeTime = 0; + TypeScript.declarationEmitGetAccessorFunctionTime = 0; + TypeScript.declarationEmitGetTypeParameterSymbolTime = 0; + TypeScript.declarationEmitGetImportDeclarationSymbolTime = 0; + + TypeScript.ioHostResolvePathTime = 0; + TypeScript.ioHostDirectoryNameTime = 0; + TypeScript.ioHostCreateDirectoryStructureTime = 0; + TypeScript.ioHostWriteFileTime = 0; + + (function (EmitOutputResult) { + EmitOutputResult[EmitOutputResult["Succeeded"] = 0] = "Succeeded"; + EmitOutputResult[EmitOutputResult["FailedBecauseOfSyntaxErrors"] = 1] = "FailedBecauseOfSyntaxErrors"; + EmitOutputResult[EmitOutputResult["FailedBecauseOfCompilerOptionsErrors"] = 2] = "FailedBecauseOfCompilerOptionsErrors"; + EmitOutputResult[EmitOutputResult["FailedToGenerateDeclarationsBecauseOfSemanticErrors"] = 3] = "FailedToGenerateDeclarationsBecauseOfSemanticErrors"; + })(TypeScript.EmitOutputResult || (TypeScript.EmitOutputResult = {})); + var EmitOutputResult = TypeScript.EmitOutputResult; + + var EmitOutput = (function () { + function EmitOutput(emitOutputResult) { + if (typeof emitOutputResult === "undefined") { emitOutputResult = 0 /* Succeeded */; } + this.outputFiles = []; + this.emitOutputResult = emitOutputResult; + } + return EmitOutput; + })(); + TypeScript.EmitOutput = EmitOutput; + + (function (OutputFileType) { + OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; + OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; + OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; + })(TypeScript.OutputFileType || (TypeScript.OutputFileType = {})); + var OutputFileType = TypeScript.OutputFileType; + + var OutputFile = (function () { + function OutputFile(name, writeByteOrderMark, text, fileType, sourceMapEntries) { + if (typeof sourceMapEntries === "undefined") { sourceMapEntries = []; } + this.name = name; + this.writeByteOrderMark = writeByteOrderMark; + this.text = text; + this.fileType = fileType; + this.sourceMapEntries = sourceMapEntries; + } + return OutputFile; + })(); + TypeScript.OutputFile = OutputFile; + + var CompileResult = (function () { + function CompileResult() { + this.diagnostics = []; + this.outputFiles = []; + } + CompileResult.fromDiagnostics = function (diagnostics) { + var result = new CompileResult(); + result.diagnostics = diagnostics; + return result; + }; + + CompileResult.fromOutputFiles = function (outputFiles) { + var result = new CompileResult(); + result.outputFiles = outputFiles; + return result; + }; + return CompileResult; + })(); + TypeScript.CompileResult = CompileResult; + + var TypeScriptCompiler = (function () { + function TypeScriptCompiler(logger, _settings) { + if (typeof logger === "undefined") { logger = new TypeScript.NullLogger(); } + if (typeof _settings === "undefined") { _settings = TypeScript.ImmutableCompilationSettings.defaultSettings(); } + this.logger = logger; + this._settings = _settings; + this.semanticInfoChain = null; + this.semanticInfoChain = new TypeScript.SemanticInfoChain(this, logger); + } + TypeScriptCompiler.prototype.compilationSettings = function () { + return this._settings; + }; + + TypeScriptCompiler.prototype.setCompilationSettings = function (newSettings) { + var oldSettings = this._settings; + this._settings = newSettings; + + if (!compareDataObjects(oldSettings, newSettings)) { + this.semanticInfoChain.invalidate(oldSettings, newSettings); + } + }; + + TypeScriptCompiler.prototype.getDocument = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + return this.semanticInfoChain.getDocument(fileName); + }; + + TypeScriptCompiler.prototype.cleanupSemanticCache = function () { + this.semanticInfoChain.invalidate(); + }; + + TypeScriptCompiler.prototype.addFile = function (fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles) { + if (typeof referencedFiles === "undefined") { referencedFiles = []; } + fileName = TypeScript.switchToForwardSlashes(fileName); + + TypeScript.sourceCharactersCompiled += scriptSnapshot.getLength(); + + var document = TypeScript.Document.create(this, this.semanticInfoChain, fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles); + + this.semanticInfoChain.addDocument(document); + }; + + TypeScriptCompiler.prototype.updateFile = function (fileName, scriptSnapshot, version, isOpen, textChangeRange) { + fileName = TypeScript.switchToForwardSlashes(fileName); + + var document = this.getDocument(fileName); + var updatedDocument = document.update(scriptSnapshot, version, isOpen, textChangeRange); + + this.semanticInfoChain.addDocument(updatedDocument); + }; + + TypeScriptCompiler.prototype.removeFile = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + this.semanticInfoChain.removeDocument(fileName); + }; + + TypeScriptCompiler.prototype.mapOutputFileName = function (document, emitOptions, extensionChanger) { + if (document.emitToOwnOutputFile()) { + var updatedFileName = document.fileName; + if (emitOptions.outputDirectory() !== "") { + updatedFileName = document.fileName.replace(emitOptions.commonDirectoryPath(), ""); + updatedFileName = emitOptions.outputDirectory() + updatedFileName; + } + return extensionChanger(updatedFileName, false); + } else { + return extensionChanger(emitOptions.sharedOutputFile(), true); + } + }; + + TypeScriptCompiler.prototype.writeByteOrderMarkForDocument = function (document) { + var printReason = false; + + if (document.emitToOwnOutputFile()) { + var result = document.byteOrderMark !== 0 /* None */; + if (printReason) { + TypeScript.Environment.standardOut.WriteLine("Emitting byte order mark because of: " + document.fileName); + } + return result; + } else { + var fileNames = this.fileNames(); + + var result = false; + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = this.getDocument(fileNames[i]); + + if (document.isExternalModule()) { + continue; + } + + if (document.byteOrderMark !== 0 /* None */) { + if (printReason) { + TypeScript.Environment.standardOut.WriteLine("Emitting byte order mark because of: " + document.fileName); + result = true; + } else { + return true; + } + } + } + + return result; + } + }; + + TypeScriptCompiler.mapToDTSFileName = function (fileName, wholeFileNameReplaced) { + return TypeScript.getDeclareFilePath(fileName); + }; + + TypeScriptCompiler.prototype._shouldEmit = function (document) { + return !document.isDeclareFile(); + }; + + TypeScriptCompiler.prototype._shouldEmitDeclarations = function (document) { + if (!this.compilationSettings().generateDeclarationFiles()) { + return false; + } + + return this._shouldEmit(document); + }; + + TypeScriptCompiler.prototype.emitDocumentDeclarationsWorker = function (document, emitOptions, declarationEmitter) { + var sourceUnit = document.sourceUnit(); + TypeScript.Debug.assert(this._shouldEmitDeclarations(document)); + + if (declarationEmitter) { + declarationEmitter.document = document; + } else { + var declareFileName = this.mapOutputFileName(document, emitOptions, TypeScriptCompiler.mapToDTSFileName); + declarationEmitter = new TypeScript.DeclarationEmitter(declareFileName, document, this, emitOptions, this.semanticInfoChain); + } + + declarationEmitter.emitDeclarations(sourceUnit); + return declarationEmitter; + }; + + TypeScriptCompiler.prototype._emitDocumentDeclarations = function (document, emitOptions, onSingleFileEmitComplete, sharedEmitter) { + if (this._shouldEmitDeclarations(document)) { + if (document.emitToOwnOutputFile()) { + var singleEmitter = this.emitDocumentDeclarationsWorker(document, emitOptions); + if (singleEmitter) { + onSingleFileEmitComplete(singleEmitter.getOutputFile()); + } + } else { + sharedEmitter = this.emitDocumentDeclarationsWorker(document, emitOptions, sharedEmitter); + } + } + + return sharedEmitter; + }; + + TypeScriptCompiler.prototype.emitAllDeclarations = function (resolvePath) { + var start = new Date().getTime(); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var sharedEmitter = null; + var fileNames = this.fileNames(); + + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + + var document = this.getDocument(fileNames[i]); + + sharedEmitter = this._emitDocumentDeclarations(document, emitOptions, function (file) { + return emitOutput.outputFiles.push(file); + }, sharedEmitter); + } + + if (sharedEmitter) { + emitOutput.outputFiles.push(sharedEmitter.getOutputFile()); + } + + TypeScript.declarationEmitTime += new Date().getTime() - start; + + return emitOutput; + }; + + TypeScriptCompiler.prototype.emitDeclarations = function (fileName, resolvePath) { + fileName = TypeScript.switchToForwardSlashes(fileName); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var document = this.getDocument(fileName); + + if (document.emitToOwnOutputFile()) { + this._emitDocumentDeclarations(document, emitOptions, function (file) { + return emitOutput.outputFiles.push(file); + }, null); + return emitOutput; + } else { + return this.emitAllDeclarations(resolvePath); + } + }; + + TypeScriptCompiler.prototype.canEmitDeclarations = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + var document = this.getDocument(fileName); + return this._shouldEmitDeclarations(document); + }; + + TypeScriptCompiler.mapToFileNameExtension = function (extension, fileName, wholeFileNameReplaced) { + if (wholeFileNameReplaced) { + return fileName; + } else { + var splitFname = fileName.split("."); + splitFname.pop(); + return splitFname.join(".") + extension; + } + }; + + TypeScriptCompiler.mapToJSFileName = function (fileName, wholeFileNameReplaced) { + return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced); + }; + + TypeScriptCompiler.prototype.emitDocumentWorker = function (document, emitOptions, emitter) { + var sourceUnit = document.sourceUnit(); + TypeScript.Debug.assert(this._shouldEmit(document)); + + var typeScriptFileName = document.fileName; + if (!emitter) { + var javaScriptFileName = this.mapOutputFileName(document, emitOptions, TypeScriptCompiler.mapToJSFileName); + var outFile = new TypeScript.TextWriter(javaScriptFileName, this.writeByteOrderMarkForDocument(document), 0 /* JavaScript */); + + emitter = new TypeScript.Emitter(javaScriptFileName, outFile, emitOptions, this.semanticInfoChain); + + if (this.compilationSettings().mapSourceFiles()) { + var sourceMapFile = new TypeScript.TextWriter(javaScriptFileName + TypeScript.SourceMapper.MapFileExtension, false, 1 /* SourceMap */); + emitter.createSourceMapper(document, javaScriptFileName, outFile, sourceMapFile, emitOptions.resolvePath); + } + } else if (this.compilationSettings().mapSourceFiles()) { + emitter.setSourceMapperNewSourceFile(document); + } + + emitter.setDocument(document); + emitter.emitJavascript(sourceUnit, false); + + return emitter; + }; + + TypeScriptCompiler.prototype._emitDocument = function (document, emitOptions, onSingleFileEmitComplete, sharedEmitter) { + if (this._shouldEmit(document)) { + if (document.emitToOwnOutputFile()) { + var singleEmitter = this.emitDocumentWorker(document, emitOptions); + if (singleEmitter) { + onSingleFileEmitComplete(singleEmitter.getOutputFiles()); + } + } else { + sharedEmitter = this.emitDocumentWorker(document, emitOptions, sharedEmitter); + } + } + + return sharedEmitter; + }; + + TypeScriptCompiler.prototype.emitAll = function (resolvePath) { + var start = new Date().getTime(); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var fileNames = this.fileNames(); + var sharedEmitter = null; + + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + + var document = this.getDocument(fileName); + + sharedEmitter = this._emitDocument(document, emitOptions, function (files) { + return emitOutput.outputFiles.push.apply(emitOutput.outputFiles, files); + }, sharedEmitter); + } + + if (sharedEmitter) { + emitOutput.outputFiles.push.apply(emitOutput.outputFiles, sharedEmitter.getOutputFiles()); + } + + TypeScript.emitTime += new Date().getTime() - start; + return emitOutput; + }; + + TypeScriptCompiler.prototype.emit = function (fileName, resolvePath) { + fileName = TypeScript.switchToForwardSlashes(fileName); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var document = this.getDocument(fileName); + + if (document.emitToOwnOutputFile()) { + this._emitDocument(document, emitOptions, function (files) { + return emitOutput.outputFiles.push.apply(emitOutput.outputFiles, files); + }, null); + return emitOutput; + } else { + return this.emitAll(resolvePath); + } + }; + + TypeScriptCompiler.prototype.compile = function (resolvePath, continueOnDiagnostics) { + if (typeof continueOnDiagnostics === "undefined") { continueOnDiagnostics = false; } + return new CompilerIterator(this, resolvePath, continueOnDiagnostics); + }; + + TypeScriptCompiler.prototype.getSyntacticDiagnostics = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + return this.getDocument(fileName).diagnostics(); + }; + + TypeScriptCompiler.prototype.getSyntaxTree = function (fileName) { + return this.getDocument(fileName).syntaxTree(); + }; + + TypeScriptCompiler.prototype.getSourceUnit = function (fileName) { + return this.getDocument(fileName).sourceUnit(); + }; + + TypeScriptCompiler.prototype.getSemanticDiagnostics = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + + var document = this.getDocument(fileName); + + var startTime = (new Date()).getTime(); + TypeScript.PullTypeResolver.typeCheck(this.compilationSettings(), this.semanticInfoChain, document); + var endTime = (new Date()).getTime(); + + TypeScript.typeCheckTime += endTime - startTime; + + var errors = this.semanticInfoChain.getDiagnostics(fileName); + + errors = TypeScript.ArrayUtilities.distinct(errors, TypeScript.Diagnostic.equals); + errors.sort(function (d1, d2) { + if (d1.fileName() < d2.fileName()) { + return -1; + } else if (d1.fileName() > d2.fileName()) { + return 1; + } + + if (d1.start() < d2.start()) { + return -1; + } else if (d1.start() > d2.start()) { + return 1; + } + + var code1 = TypeScript.diagnosticInformationMap[d1.diagnosticKey()].code; + var code2 = TypeScript.diagnosticInformationMap[d2.diagnosticKey()].code; + if (code1 < code2) { + return -1; + } else if (code1 > code2) { + return 1; + } + + return 0; + }); + + return errors; + }; + + TypeScriptCompiler.prototype.getCompilerOptionsDiagnostics = function (resolvePath) { + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + var emitDiagnostic = emitOptions.diagnostic(); + if (emitDiagnostic) { + return [emitDiagnostic]; + } + return TypeScript.sentinelEmptyArray; + }; + + TypeScriptCompiler.prototype.resolveAllFiles = function () { + var fileNames = this.fileNames(); + for (var i = 0, n = fileNames.length; i < n; i++) { + this.getSemanticDiagnostics(fileNames[i]); + } + }; + + TypeScriptCompiler.prototype.getSymbolOfDeclaration = function (decl) { + if (!decl) { + return null; + } + + var resolver = this.semanticInfoChain.getResolver(); + var ast = this.semanticInfoChain.getASTForDecl(decl); + if (!ast) { + return null; + } + + var enclosingDecl = resolver.getEnclosingDecl(decl); + if (ast.kind() === 139 /* GetAccessor */ || ast.kind() === 140 /* SetAccessor */) { + return this.getSymbolOfDeclaration(enclosingDecl); + } + + return resolver.resolveAST(ast, false, new TypeScript.PullTypeResolutionContext(resolver)); + }; + + TypeScriptCompiler.prototype.extractResolutionContextFromAST = function (resolver, ast, document, propagateContextualTypes) { + var scriptName = document.fileName; + + var enclosingDecl = null; + var enclosingDeclAST = null; + var inContextuallyTypedAssignment = false; + var inWithBlock = false; + + var resolutionContext = new TypeScript.PullTypeResolutionContext(resolver); + + if (!ast) { + return null; + } + + var path = this.getASTPath(ast); + + for (var i = 0, n = path.length; i < n; i++) { + var current = path[i]; + + switch (current.kind()) { + case 222 /* FunctionExpression */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + if (propagateContextualTypes) { + resolver.resolveAST(current, true, resolutionContext); + } + break; + + case 136 /* MemberVariableDeclaration */: + var memberVariable = current; + inContextuallyTypedAssignment = memberVariable.variableDeclarator.typeAnnotation !== null; + + this.extractResolutionContextForVariable(inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, memberVariable, memberVariable.variableDeclarator.equalsValueClause); + break; + + case 225 /* VariableDeclarator */: + var variableDeclarator = current; + inContextuallyTypedAssignment = variableDeclarator.typeAnnotation !== null; + + this.extractResolutionContextForVariable(inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, variableDeclarator, variableDeclarator.equalsValueClause); + break; + + case 213 /* InvocationExpression */: + case 216 /* ObjectCreationExpression */: + if (propagateContextualTypes) { + var isNew = current.kind() === 216 /* ObjectCreationExpression */; + var callExpression = current; + var contextualType = null; + + if ((i + 2 < n) && callExpression.argumentList === path[i + 1] && callExpression.argumentList.arguments === path[i + 2]) { + var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); + if (isNew) { + resolver.resolveObjectCreationExpression(callExpression, resolutionContext, callResolutionResults); + } else { + resolver.resolveInvocationExpression(callExpression, resolutionContext, callResolutionResults); + } + + if (callResolutionResults.actualParametersContextTypeSymbols) { + var argExpression = path[i + 3]; + if (argExpression) { + for (var j = 0, m = callExpression.argumentList.arguments.nonSeparatorCount(); j < m; j++) { + if (callExpression.argumentList.arguments.nonSeparatorAt(j) === argExpression) { + var callContextualType = callResolutionResults.actualParametersContextTypeSymbols[j]; + if (callContextualType) { + contextualType = callContextualType; + break; + } + } + } + } + } + } else { + if (isNew) { + resolver.resolveObjectCreationExpression(callExpression, resolutionContext); + } else { + resolver.resolveInvocationExpression(callExpression, resolutionContext); + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 214 /* ArrayLiteralExpression */: + if (propagateContextualTypes) { + var contextualType = null; + var currentContextualType = resolutionContext.getContextualType(); + if (currentContextualType && currentContextualType.isArrayNamedTypeReference()) { + contextualType = currentContextualType.getElementType(); + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 215 /* ObjectLiteralExpression */: + if (propagateContextualTypes) { + var objectLiteralExpression = current; + var objectLiteralResolutionContext = new TypeScript.PullAdditionalObjectLiteralResolutionData(); + resolver.resolveObjectLiteralExpression(objectLiteralExpression, inContextuallyTypedAssignment, resolutionContext, objectLiteralResolutionContext); + + var memeberAST = (path[i + 1] && path[i + 1].kind() === 2 /* SeparatedList */) ? path[i + 2] : path[i + 1]; + if (memeberAST) { + var contextualType = null; + var memberDecls = objectLiteralExpression.propertyAssignments; + if (memberDecls && objectLiteralResolutionContext.membersContextTypeSymbols) { + for (var j = 0, m = memberDecls.nonSeparatorCount(); j < m; j++) { + if (memberDecls.nonSeparatorAt(j) === memeberAST) { + var memberContextualType = objectLiteralResolutionContext.membersContextTypeSymbols[j]; + if (memberContextualType) { + contextualType = memberContextualType; + break; + } + } + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + } + + break; + + case 174 /* AssignmentExpression */: + if (propagateContextualTypes) { + var assignmentExpression = current; + var contextualType = null; + + if (path[i + 1] && path[i + 1] === assignmentExpression.right) { + var leftType = resolver.resolveAST(assignmentExpression.left, inContextuallyTypedAssignment, resolutionContext).type; + if (leftType) { + inContextuallyTypedAssignment = true; + contextualType = leftType; + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 220 /* CastExpression */: + var castExpression = current; + if (!(i + 1 < n && path[i + 1] === castExpression.type)) { + if (propagateContextualTypes) { + var contextualType = null; + var typeSymbol = resolver.resolveAST(castExpression, inContextuallyTypedAssignment, resolutionContext).type; + + if (typeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = typeSymbol; + } + + resolutionContext.pushNewContextualType(contextualType); + } + } + + break; + + case 150 /* ReturnStatement */: + if (propagateContextualTypes) { + var returnStatement = current; + var contextualType = null; + + if (enclosingDecl && (enclosingDecl.kind & 1032192 /* SomeFunction */)) { + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); + if (typeAnnotation) { + var returnTypeSymbol = resolver.resolveTypeReference(typeAnnotation, resolutionContext); + if (returnTypeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = returnTypeSymbol; + } + } else { + var currentContextualType = resolutionContext.getContextualType(); + if (currentContextualType && currentContextualType.isFunction()) { + var contextualSignatures = currentContextualType.kind == 33554432 /* ConstructorType */ ? currentContextualType.getConstructSignatures() : currentContextualType.getCallSignatures(); + var currentContextualTypeSignatureSymbol = contextualSignatures[0]; + var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.returnType; + if (currentContextualTypeReturnTypeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = currentContextualTypeReturnTypeSymbol; + } + } + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 122 /* ObjectType */: + if (propagateContextualTypes && TypeScript.isTypesOnlyLocation(current)) { + resolver.resolveAST(current, false, resolutionContext); + } + + break; + + case 163 /* WithStatement */: + inWithBlock = true; + break; + + case 146 /* Block */: + inContextuallyTypedAssignment = false; + break; + } + + var decl = this.semanticInfoChain.getDeclForAST(current); + if (decl) { + enclosingDecl = decl; + enclosingDeclAST = current; + } + } + + if (ast && ast.parent && ast.kind() === 11 /* IdentifierName */) { + if (ast.parent.kind() === 212 /* MemberAccessExpression */) { + if (ast.parent.name === ast) { + ast = ast.parent; + } + } else if (ast.parent.kind() === 121 /* QualifiedName */) { + if (ast.parent.right === ast) { + ast = ast.parent; + } + } + } + + return { + ast: ast, + enclosingDecl: enclosingDecl, + resolutionContext: resolutionContext, + inContextuallyTypedAssignment: inContextuallyTypedAssignment, + inWithBlock: inWithBlock + }; + }; + + TypeScriptCompiler.prototype.extractResolutionContextForVariable = function (inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, assigningAST, init) { + if (inContextuallyTypedAssignment) { + if (propagateContextualTypes) { + resolver.resolveAST(assigningAST, false, resolutionContext); + var varSymbol = this.semanticInfoChain.getSymbolForAST(assigningAST); + + var contextualType = null; + if (varSymbol && inContextuallyTypedAssignment) { + contextualType = varSymbol.type; + } + + resolutionContext.pushNewContextualType(contextualType); + + if (init) { + resolver.resolveAST(init, inContextuallyTypedAssignment, resolutionContext); + } + } + } + }; + + TypeScriptCompiler.prototype.getASTPath = function (ast) { + var result = []; + + while (ast) { + result.unshift(ast); + ast = ast.parent; + } + + return result; + }; + + TypeScriptCompiler.prototype.pullGetSymbolInformationFromAST = function (ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + ast = context.ast; + var symbol = resolver.resolveAST(ast, context.inContextuallyTypedAssignment, context.resolutionContext); + + if (!symbol) { + TypeScript.Debug.assert(ast.kind() === 120 /* SourceUnit */, "No symbol was found for ast and ast was not source unit. Ast Kind: " + TypeScript.SyntaxKind[ast.kind()]); + return null; + } + + if (symbol.isTypeReference()) { + symbol = symbol.getReferencedTypeSymbol(); + } + + var aliasSymbol = this.semanticInfoChain.getAliasSymbolForAST(ast); + + return { + symbol: symbol, + aliasSymbol: aliasSymbol, + ast: ast, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetCallInformationFromAST = function (ast, document) { + if (ast.kind() !== 213 /* InvocationExpression */ && ast.kind() !== 216 /* ObjectCreationExpression */) { + return null; + } + + var isNew = ast.kind() === 216 /* ObjectCreationExpression */; + + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); + + if (isNew) { + resolver.resolveObjectCreationExpression(ast, context.resolutionContext, callResolutionResults); + } else { + resolver.resolveInvocationExpression(ast, context.resolutionContext, callResolutionResults); + } + + return { + targetSymbol: callResolutionResults.targetSymbol, + resolvedSignatures: callResolutionResults.resolvedSignatures, + candidateSignature: callResolutionResults.candidateSignature, + ast: ast, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl), + isConstructorCall: isNew + }; + }; + + TypeScriptCompiler.prototype.pullGetVisibleMemberSymbolsFromAST = function (ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var symbols = resolver.getVisibleMembersFromExpression(ast, context.enclosingDecl, context.resolutionContext); + if (!symbols) { + return null; + } + + return { + symbols: symbols, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetVisibleDeclsFromAST = function (ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, false); + if (!context || context.inWithBlock) { + return null; + } + + return resolver.getVisibleDecls(context.enclosingDecl); + }; + + TypeScriptCompiler.prototype.pullGetContextualMembersFromAST = function (ast, document) { + if (ast.kind() !== 215 /* ObjectLiteralExpression */) { + return null; + } + + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var members = resolver.getVisibleContextSymbols(context.enclosingDecl, context.resolutionContext); + + return { + symbols: members, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetDeclInformation = function (decl, ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var astForDecl = decl.ast(); + if (!astForDecl) { + return null; + } + + var astForDeclContext = this.extractResolutionContextFromAST(resolver, astForDecl, this.getDocument(astForDecl.fileName()), true); + if (!astForDeclContext) { + return null; + } + + var symbol = decl.getSymbol(); + resolver.resolveDeclaredSymbol(symbol, context.resolutionContext); + symbol.setUnresolved(); + + return { + symbol: symbol, + aliasSymbol: null, + ast: ast, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.topLevelDeclaration = function (fileName) { + return this.semanticInfoChain.topLevelDecl(fileName); + }; + + TypeScriptCompiler.prototype.getDeclForAST = function (ast) { + return this.semanticInfoChain.getDeclForAST(ast); + }; + + TypeScriptCompiler.prototype.fileNames = function () { + return this.semanticInfoChain.fileNames(); + }; + + TypeScriptCompiler.prototype.topLevelDecl = function (fileName) { + return this.semanticInfoChain.topLevelDecl(fileName); + }; + + TypeScriptCompiler.getLocationText = function (location, resolvePath) { + return resolvePath(location.fileName()) + "(" + (location.line() + 1) + "," + (location.character() + 1) + ")"; + }; + + TypeScriptCompiler.getFullDiagnosticText = function (diagnostic, resolvePath) { + var result = ""; + if (diagnostic.fileName()) { + result += this.getLocationText(diagnostic, resolvePath) + ": "; + } + + result += diagnostic.message(); + + var additionalLocations = diagnostic.additionalLocations(); + if (additionalLocations.length > 0) { + result += " " + TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Additional_locations, null) + TypeScript.Environment.newLine; + + for (var i = 0, n = additionalLocations.length; i < n; i++) { + result += "\t" + this.getLocationText(additionalLocations[i], resolvePath) + TypeScript.Environment.newLine; + } + } else { + result += TypeScript.Environment.newLine; + } + + return result; + }; + return TypeScriptCompiler; + })(); + TypeScript.TypeScriptCompiler = TypeScriptCompiler; + + var CompilerPhase; + (function (CompilerPhase) { + CompilerPhase[CompilerPhase["Syntax"] = 0] = "Syntax"; + CompilerPhase[CompilerPhase["Semantics"] = 1] = "Semantics"; + CompilerPhase[CompilerPhase["EmitOptionsValidation"] = 2] = "EmitOptionsValidation"; + CompilerPhase[CompilerPhase["Emit"] = 3] = "Emit"; + CompilerPhase[CompilerPhase["DeclarationEmit"] = 4] = "DeclarationEmit"; + })(CompilerPhase || (CompilerPhase = {})); + + var CompilerIterator = (function () { + function CompilerIterator(compiler, resolvePath, continueOnDiagnostics, startingPhase) { + if (typeof startingPhase === "undefined") { startingPhase = 0 /* Syntax */; } + this.compiler = compiler; + this.resolvePath = resolvePath; + this.continueOnDiagnostics = continueOnDiagnostics; + this.index = -1; + this.fileNames = null; + this._current = null; + this._emitOptions = null; + this._sharedEmitter = null; + this._sharedDeclarationEmitter = null; + this.hadSyntacticDiagnostics = false; + this.hadSemanticDiagnostics = false; + this.hadEmitDiagnostics = false; + this.fileNames = compiler.fileNames(); + this.compilerPhase = startingPhase; + } + CompilerIterator.prototype.current = function () { + return this._current; + }; + + CompilerIterator.prototype.moveNext = function () { + this._current = null; + + while (this.moveNextInternal()) { + if (this._current) { + return true; + } + } + + return false; + }; + + CompilerIterator.prototype.moveNextInternal = function () { + this.index++; + + while (this.shouldMoveToNextPhase()) { + this.index = 0; + this.compilerPhase++; + } + + if (this.compilerPhase > 4 /* DeclarationEmit */) { + return false; + } + + switch (this.compilerPhase) { + case 0 /* Syntax */: + return this.moveNextSyntaxPhase(); + case 1 /* Semantics */: + return this.moveNextSemanticsPhase(); + case 2 /* EmitOptionsValidation */: + return this.moveNextEmitOptionsValidationPhase(); + case 3 /* Emit */: + return this.moveNextEmitPhase(); + case 4 /* DeclarationEmit */: + return this.moveNextDeclarationEmitPhase(); + } + }; + + CompilerIterator.prototype.shouldMoveToNextPhase = function () { + switch (this.compilerPhase) { + case 2 /* EmitOptionsValidation */: + return this.index === 1; + + case 0 /* Syntax */: + case 1 /* Semantics */: + return this.index === this.fileNames.length; + + case 3 /* Emit */: + case 4 /* DeclarationEmit */: + return this.index === (this.fileNames.length + 1); + } + + return false; + }; + + CompilerIterator.prototype.moveNextSyntaxPhase = function () { + TypeScript.Debug.assert(this.index >= 0 && this.index < this.fileNames.length); + var fileName = this.fileNames[this.index]; + + var diagnostics = this.compiler.getSyntacticDiagnostics(fileName); + if (diagnostics.length) { + if (!this.continueOnDiagnostics) { + this.hadSyntacticDiagnostics = true; + } + + this._current = CompileResult.fromDiagnostics(diagnostics); + } + + return true; + }; + + CompilerIterator.prototype.moveNextSemanticsPhase = function () { + if (this.hadSyntacticDiagnostics) { + return false; + } + + TypeScript.Debug.assert(this.index >= 0 && this.index < this.fileNames.length); + var fileName = this.fileNames[this.index]; + var diagnostics = this.compiler.getSemanticDiagnostics(fileName); + if (diagnostics.length) { + if (!this.continueOnDiagnostics) { + this.hadSemanticDiagnostics = true; + } + + this._current = CompileResult.fromDiagnostics(diagnostics); + } + + return true; + }; + + CompilerIterator.prototype.moveNextEmitOptionsValidationPhase = function () { + TypeScript.Debug.assert(!this.hadSyntacticDiagnostics); + + if (!this._emitOptions) { + this._emitOptions = new TypeScript.EmitOptions(this.compiler, this.resolvePath); + } + + if (this._emitOptions.diagnostic()) { + if (!this.continueOnDiagnostics) { + this.hadEmitDiagnostics = true; + } + + this._current = CompileResult.fromDiagnostics([this._emitOptions.diagnostic()]); + } + + return true; + }; + + CompilerIterator.prototype.moveNextEmitPhase = function () { + var _this = this; + TypeScript.Debug.assert(!this.hadSyntacticDiagnostics); + TypeScript.Debug.assert(this._emitOptions); + + if (this.hadEmitDiagnostics) { + return false; + } + + TypeScript.Debug.assert(this.index >= 0 && this.index <= this.fileNames.length); + if (this.index < this.fileNames.length) { + var fileName = this.fileNames[this.index]; + var document = this.compiler.getDocument(fileName); + + this._sharedEmitter = this.compiler._emitDocument(document, this._emitOptions, function (outputFiles) { + _this._current = CompileResult.fromOutputFiles(outputFiles); + }, this._sharedEmitter); + return true; + } + + if (this.index === this.fileNames.length && this._sharedEmitter) { + this._current = CompileResult.fromOutputFiles(this._sharedEmitter.getOutputFiles()); + } + + return true; + }; + + CompilerIterator.prototype.moveNextDeclarationEmitPhase = function () { + var _this = this; + TypeScript.Debug.assert(!this.hadSyntacticDiagnostics); + TypeScript.Debug.assert(!this.hadEmitDiagnostics); + if (this.hadSemanticDiagnostics) { + return false; + } + + if (!this.compiler.compilationSettings().generateDeclarationFiles()) { + return false; + } + + TypeScript.Debug.assert(this.index >= 0 && this.index <= this.fileNames.length); + if (this.index < this.fileNames.length) { + var fileName = this.fileNames[this.index]; + var document = this.compiler.getDocument(fileName); + + this._sharedDeclarationEmitter = this.compiler._emitDocumentDeclarations(document, this._emitOptions, function (file) { + _this._current = CompileResult.fromOutputFiles([file]); + }, this._sharedDeclarationEmitter); + return true; + } + + if (this.index === this.fileNames.length && this._sharedDeclarationEmitter) { + this._current = CompileResult.fromOutputFiles([this._sharedDeclarationEmitter.getOutputFile()]); + } + + return true; + }; + return CompilerIterator; + })(); + + function compareDataObjects(dst, src) { + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) + return false; + } else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) + return false; + } + } + return true; + } + TypeScript.compareDataObjects = compareDataObjects; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (GenerativeTypeClassification) { + GenerativeTypeClassification[GenerativeTypeClassification["Unknown"] = 0] = "Unknown"; + GenerativeTypeClassification[GenerativeTypeClassification["Open"] = 1] = "Open"; + GenerativeTypeClassification[GenerativeTypeClassification["Closed"] = 2] = "Closed"; + GenerativeTypeClassification[GenerativeTypeClassification["InfinitelyExpanding"] = 3] = "InfinitelyExpanding"; + })(TypeScript.GenerativeTypeClassification || (TypeScript.GenerativeTypeClassification = {})); + var GenerativeTypeClassification = TypeScript.GenerativeTypeClassification; + + var PullTypeReferenceSymbol = (function (_super) { + __extends(PullTypeReferenceSymbol, _super); + function PullTypeReferenceSymbol(referencedTypeSymbol) { + _super.call(this, referencedTypeSymbol.name, referencedTypeSymbol.kind); + this.referencedTypeSymbol = referencedTypeSymbol; + this.isResolved = true; + + TypeScript.Debug.assert(referencedTypeSymbol !== null, "Type root symbol may not be null"); + + this.setRootSymbol(referencedTypeSymbol); + + this.typeReference = this; + } + PullTypeReferenceSymbol.createTypeReference = function (type) { + if (type.isTypeReference()) { + return type; + } + + var typeReference = type.typeReference; + + if (!typeReference) { + typeReference = new PullTypeReferenceSymbol(type); + type.typeReference = typeReference; + } + + return typeReference; + }; + + PullTypeReferenceSymbol.prototype.isTypeReference = function () { + return true; + }; + + PullTypeReferenceSymbol.prototype.setResolved = function () { + }; + + PullTypeReferenceSymbol.prototype.setUnresolved = function () { + }; + PullTypeReferenceSymbol.prototype.invalidate = function () { + }; + + PullTypeReferenceSymbol.prototype.ensureReferencedTypeIsResolved = function () { + this._getResolver().resolveDeclaredSymbol(this.referencedTypeSymbol); + }; + + PullTypeReferenceSymbol.prototype.getReferencedTypeSymbol = function () { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol; + }; + + PullTypeReferenceSymbol.prototype._getResolver = function () { + return this.referencedTypeSymbol._getResolver(); + }; + + PullTypeReferenceSymbol.prototype.hasMembers = function () { + return this.referencedTypeSymbol.hasMembers(); + }; + + PullTypeReferenceSymbol.prototype.setAssociatedContainerType = function (type) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": setAssociatedContainerType"); + }; + + PullTypeReferenceSymbol.prototype.getAssociatedContainerType = function () { + return this.referencedTypeSymbol.getAssociatedContainerType(); + }; + + PullTypeReferenceSymbol.prototype.getFunctionSymbol = function () { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.getFunctionSymbol(); + }; + PullTypeReferenceSymbol.prototype.setFunctionSymbol = function (symbol) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": setFunctionSymbol"); + }; + + PullTypeReferenceSymbol.prototype.addContainedNonMember = function (nonMember) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addContainedNonMember"); + }; + PullTypeReferenceSymbol.prototype.findContainedNonMemberContainer = function (containerName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.findContainedNonMemberContainer(containerName, kind); + }; + + PullTypeReferenceSymbol.prototype.addMember = function (memberSymbol) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addMember"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedMemberType = function (enclosedType) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedMemberType"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedMemberContainer = function (enclosedContainer) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedMemberContainer"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedNonMember = function (enclosedNonMember) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedNonMember"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedNonMemberType = function (enclosedNonMemberType) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedNonMemberType"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedNonMemberContainer = function (enclosedNonMemberContainer) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedNonMemberContainer"); + }; + PullTypeReferenceSymbol.prototype.addTypeParameter = function (typeParameter) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addTypeParameter"); + }; + PullTypeReferenceSymbol.prototype.addConstructorTypeParameter = function (typeParameter) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addConstructorTypeParameter"); + }; + + PullTypeReferenceSymbol.prototype.findContainedNonMember = function (name) { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findContainedNonMember(name); + }; + + PullTypeReferenceSymbol.prototype.findContainedNonMemberType = function (typeName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findContainedNonMemberType(typeName, kind); + }; + + PullTypeReferenceSymbol.prototype.getMembers = function () { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.getMembers(); + }; + + PullTypeReferenceSymbol.prototype.setHasDefaultConstructor = function (hasOne) { + if (typeof hasOne === "undefined") { hasOne = true; } + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ":setHasDefaultConstructor"); + }; + PullTypeReferenceSymbol.prototype.getHasDefaultConstructor = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getHasDefaultConstructor(); + }; + PullTypeReferenceSymbol.prototype.getConstructorMethod = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getConstructorMethod(); + }; + PullTypeReferenceSymbol.prototype.setConstructorMethod = function (constructorMethod) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": setConstructorMethod"); + }; + PullTypeReferenceSymbol.prototype.getTypeParameters = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypeParameters(); + }; + + PullTypeReferenceSymbol.prototype.isGeneric = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.isGeneric(); + }; + + PullTypeReferenceSymbol.prototype.addSpecialization = function (specializedVersionOfThisType, substitutingTypes) { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.addSpecialization(specializedVersionOfThisType, substitutingTypes); + }; + PullTypeReferenceSymbol.prototype.getSpecialization = function (substitutingTypes) { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getSpecialization(substitutingTypes); + }; + PullTypeReferenceSymbol.prototype.getKnownSpecializations = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getKnownSpecializations(); + }; + PullTypeReferenceSymbol.prototype.getTypeArguments = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypeArguments(); + }; + PullTypeReferenceSymbol.prototype.getTypeArgumentsOrTypeParameters = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypeArgumentsOrTypeParameters(); + }; + + PullTypeReferenceSymbol.prototype.appendCallSignature = function (callSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": appendCallSignature"); + }; + PullTypeReferenceSymbol.prototype.insertCallSignatureAtIndex = function (callSignature, index) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": insertCallSignatureAtIndex"); + }; + PullTypeReferenceSymbol.prototype.appendConstructSignature = function (callSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": appendConstructSignature"); + }; + PullTypeReferenceSymbol.prototype.insertConstructSignatureAtIndex = function (callSignature, index) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": insertConstructSignatureAtIndex"); + }; + PullTypeReferenceSymbol.prototype.addIndexSignature = function (indexSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addIndexSignature"); + }; + + PullTypeReferenceSymbol.prototype.hasOwnCallSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.hasOwnCallSignatures(); + }; + PullTypeReferenceSymbol.prototype.getCallSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getCallSignatures(); + }; + PullTypeReferenceSymbol.prototype.hasOwnConstructSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.hasOwnConstructSignatures(); + }; + PullTypeReferenceSymbol.prototype.getConstructSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getConstructSignatures(); + }; + PullTypeReferenceSymbol.prototype.hasOwnIndexSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.hasOwnIndexSignatures(); + }; + PullTypeReferenceSymbol.prototype.getIndexSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getIndexSignatures(); + }; + + PullTypeReferenceSymbol.prototype.addImplementedType = function (implementedType) { + this.referencedTypeSymbol.addImplementedType(implementedType); + }; + PullTypeReferenceSymbol.prototype.getImplementedTypes = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getImplementedTypes(); + }; + PullTypeReferenceSymbol.prototype.addExtendedType = function (extendedType) { + this.referencedTypeSymbol.addExtendedType(extendedType); + }; + PullTypeReferenceSymbol.prototype.getExtendedTypes = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getExtendedTypes(); + }; + PullTypeReferenceSymbol.prototype.addTypeThatExtendsThisType = function (type) { + this.referencedTypeSymbol.addTypeThatExtendsThisType(type); + }; + PullTypeReferenceSymbol.prototype.getTypesThatExtendThisType = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypesThatExtendThisType(); + }; + PullTypeReferenceSymbol.prototype.addTypeThatExplicitlyImplementsThisType = function (type) { + this.referencedTypeSymbol.addTypeThatExplicitlyImplementsThisType(type); + }; + PullTypeReferenceSymbol.prototype.getTypesThatExplicitlyImplementThisType = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypesThatExplicitlyImplementThisType(); + }; + + PullTypeReferenceSymbol.prototype.isValidBaseKind = function (baseType, isExtendedType) { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.isValidBaseKind(baseType, isExtendedType); + }; + + PullTypeReferenceSymbol.prototype.findMember = function (name, lookInParent) { + if (typeof lookInParent === "undefined") { lookInParent = true; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findMember(name, lookInParent); + }; + PullTypeReferenceSymbol.prototype.findNestedType = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findNestedType(name, kind); + }; + PullTypeReferenceSymbol.prototype.findNestedContainer = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findNestedContainer(name, kind); + }; + PullTypeReferenceSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisiblity) { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.getAllMembers(searchDeclKind, memberVisiblity); + }; + + PullTypeReferenceSymbol.prototype.findTypeParameter = function (name) { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findTypeParameter(name); + }; + + PullTypeReferenceSymbol.prototype.hasOnlyOverloadCallSignatures = function () { + return this.referencedTypeSymbol.hasOnlyOverloadCallSignatures(); + }; + return PullTypeReferenceSymbol; + })(TypeScript.PullTypeSymbol); + TypeScript.PullTypeReferenceSymbol = PullTypeReferenceSymbol; + + TypeScript.nSpecializationsCreated = 0; + TypeScript.nSpecializedSignaturesCreated = 0; + TypeScript.nSpecializedTypeParameterCreated = 0; + + var PullInstantiatedTypeReferenceSymbol = (function (_super) { + __extends(PullInstantiatedTypeReferenceSymbol, _super); + function PullInstantiatedTypeReferenceSymbol(referencedTypeSymbol, _typeParameterArgumentMap, isInstanceReferenceType) { + _super.call(this, referencedTypeSymbol); + this.referencedTypeSymbol = referencedTypeSymbol; + this._typeParameterArgumentMap = _typeParameterArgumentMap; + this.isInstanceReferenceType = isInstanceReferenceType; + this._instantiatedMembers = null; + this._allInstantiatedMemberNameCache = null; + this._instantiatedMemberNameCache = TypeScript.createIntrinsicsObject(); + this._instantiatedCallSignatures = null; + this._instantiatedConstructSignatures = null; + this._instantiatedIndexSignatures = null; + this._typeArgumentReferences = undefined; + this._instantiatedConstructorMethod = null; + this._instantiatedAssociatedContainerType = null; + this._isArray = undefined; + this._generativeTypeClassification = []; + + TypeScript.nSpecializationsCreated++; + } + PullInstantiatedTypeReferenceSymbol.prototype.getIsSpecialized = function () { + return !this.isInstanceReferenceType; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getGenerativeTypeClassification = function (enclosingType) { + if (!this.isNamedTypeSymbol()) { + return 0 /* Unknown */; + } + + var generativeTypeClassification = this._generativeTypeClassification[enclosingType.pullSymbolID] || 0 /* Unknown */; + if (generativeTypeClassification === 0 /* Unknown */) { + var typeParameters = enclosingType.getTypeParameters(); + var enclosingTypeParameterMap = []; + for (var i = 0; i < typeParameters.length; i++) { + enclosingTypeParameterMap[typeParameters[i].pullSymbolID] = typeParameters[i]; + } + + var typeArguments = this.getTypeArguments(); + for (var i = 0; i < typeArguments.length; i++) { + if (typeArguments[i].wrapsSomeTypeParameter(enclosingTypeParameterMap, true)) { + generativeTypeClassification = 1 /* Open */; + break; + } + } + + if (generativeTypeClassification === 1 /* Open */) { + if (this.wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType)) { + generativeTypeClassification = 3 /* InfinitelyExpanding */; + } + } else { + generativeTypeClassification = 2 /* Closed */; + } + + this._generativeTypeClassification[enclosingType.pullSymbolID] = generativeTypeClassification; + } + + return generativeTypeClassification; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.isArrayNamedTypeReference = function () { + if (this._isArray === undefined) { + this._isArray = this.getRootSymbol().isArrayNamedTypeReference() || (this.getRootSymbol() === this._getResolver().getArrayNamedType()); + } + return this._isArray; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getElementType = function () { + if (!this.isArrayNamedTypeReference()) { + return null; + } + + var typeArguments = this.getTypeArguments(); + return typeArguments ? typeArguments[0] : null; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getReferencedTypeSymbol = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.getIsSpecialized()) { + return this; + } + + return this.referencedTypeSymbol; + }; + + PullInstantiatedTypeReferenceSymbol.create = function (resolver, type, typeParameterArgumentMap) { + TypeScript.Debug.assert(resolver); + + var mutableTypeParameterMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(typeParameterArgumentMap); + + TypeScript.PullInstantiationHelpers.instantiateTypeArgument(resolver, type, mutableTypeParameterMap); + + var rootType = type.getRootSymbol(); + var instantiation = rootType.getSpecialization(mutableTypeParameterMap.typeParameterArgumentMap); + if (instantiation) { + return instantiation; + } + + TypeScript.PullInstantiationHelpers.cleanUpTypeArgumentMap(type, mutableTypeParameterMap); + typeParameterArgumentMap = mutableTypeParameterMap.typeParameterArgumentMap; + + var isInstanceReferenceType = (type.kind & 8216 /* SomeInstantiatableType */) != 0; + var resolvedTypeParameterArgumentMap = typeParameterArgumentMap; + if (isInstanceReferenceType) { + var typeParameters = rootType.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + if (!TypeScript.PullHelpers.typeSymbolsAreIdentical(typeParameters[i], typeParameterArgumentMap[typeParameters[i].pullSymbolID])) { + isInstanceReferenceType = false; + break; + } + } + + if (isInstanceReferenceType) { + typeParameterArgumentMap = []; + } + } + + instantiation = new PullInstantiatedTypeReferenceSymbol(rootType, typeParameterArgumentMap, isInstanceReferenceType); + + rootType.addSpecialization(instantiation, resolvedTypeParameterArgumentMap); + + return instantiation; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.isGeneric = function () { + return this.getRootSymbol().isGeneric(); + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getTypeParameterArgumentMap = function () { + return this._typeParameterArgumentMap; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getTypeArguments = function () { + if (this.isInstanceReferenceType) { + return this.getTypeParameters(); + } + + if (this._typeArgumentReferences === undefined) { + var typeParameters = this.referencedTypeSymbol.getTypeParameters(); + + if (typeParameters.length) { + var typeArgument = null; + var typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArgument = this._typeParameterArgumentMap[typeParameters[i].pullSymbolID]; + + if (!typeArgument) { + TypeScript.Debug.fail("type argument count mismatch"); + } + + if (typeArgument) { + typeArguments[typeArguments.length] = typeArgument; + } + } + + this._typeArgumentReferences = typeArguments; + } else { + this._typeArgumentReferences = null; + } + } + + return this._typeArgumentReferences; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getTypeArgumentsOrTypeParameters = function () { + return this.getTypeArguments(); + }; + + PullInstantiatedTypeReferenceSymbol.prototype.populateInstantiatedMemberFromReferencedMember = function (referencedMember) { + var instantiatedMember; + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(referencedMember); + + if (!referencedMember.type.wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + instantiatedMember = referencedMember; + } else { + instantiatedMember = new TypeScript.PullSymbol(referencedMember.name, referencedMember.kind); + instantiatedMember.setRootSymbol(referencedMember); + instantiatedMember.type = this._getResolver().instantiateType(referencedMember.type, this._typeParameterArgumentMap); + instantiatedMember.isOptional = referencedMember.isOptional; + } + this._instantiatedMemberNameCache[instantiatedMember.name] = instantiatedMember; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getMembers = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getMembers(); + } + + if (!this._instantiatedMembers) { + var referencedMembers = this.referencedTypeSymbol.getMembers(); + var referencedMember = null; + var instantiatedMember = null; + + this._instantiatedMembers = []; + + for (var i = 0; i < referencedMembers.length; i++) { + referencedMember = referencedMembers[i]; + + this._getResolver().resolveDeclaredSymbol(referencedMember); + + if (!this._instantiatedMemberNameCache[referencedMember.name]) { + this.populateInstantiatedMemberFromReferencedMember(referencedMember); + } + + this._instantiatedMembers[this._instantiatedMembers.length] = this._instantiatedMemberNameCache[referencedMember.name]; + } + } + + return this._instantiatedMembers; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.findMember = function (name, lookInParent) { + if (typeof lookInParent === "undefined") { lookInParent = true; } + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.findMember(name, lookInParent); + } + + var memberSymbol = this._instantiatedMemberNameCache[name]; + + if (!memberSymbol) { + var referencedMemberSymbol = this.referencedTypeSymbol.findMember(name, lookInParent); + + if (referencedMemberSymbol) { + this.populateInstantiatedMemberFromReferencedMember(referencedMemberSymbol); + memberSymbol = this._instantiatedMemberNameCache[name]; + } else { + memberSymbol = null; + } + } + + return memberSymbol; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisiblity) { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getAllMembers(searchDeclKind, memberVisiblity); + } + + var requestedMembers = []; + var allReferencedMembers = this.referencedTypeSymbol.getAllMembers(searchDeclKind, memberVisiblity); + + if (!this._allInstantiatedMemberNameCache) { + this._allInstantiatedMemberNameCache = TypeScript.createIntrinsicsObject(); + + var members = this.getMembers(); + + for (var i = 0; i < members.length; i++) { + this._allInstantiatedMemberNameCache[members[i].name] = members[i]; + } + } + + var referencedMember = null; + var requestedMember = null; + + for (var i = 0; i < allReferencedMembers.length; i++) { + referencedMember = allReferencedMembers[i]; + + this._getResolver().resolveDeclaredSymbol(referencedMember); + + if (this._allInstantiatedMemberNameCache[referencedMember.name]) { + requestedMembers[requestedMembers.length] = this._allInstantiatedMemberNameCache[referencedMember.name]; + } else { + if (!referencedMember.type.wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._allInstantiatedMemberNameCache[referencedMember.name] = referencedMember; + requestedMembers[requestedMembers.length] = referencedMember; + } else { + requestedMember = new TypeScript.PullSymbol(referencedMember.name, referencedMember.kind); + requestedMember.setRootSymbol(referencedMember); + + requestedMember.type = this._getResolver().instantiateType(referencedMember.type, this._typeParameterArgumentMap); + requestedMember.isOptional = referencedMember.isOptional; + + this._allInstantiatedMemberNameCache[requestedMember.name] = requestedMember; + requestedMembers[requestedMembers.length] = requestedMember; + } + } + } + + return requestedMembers; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getConstructorMethod = function () { + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getConstructorMethod(); + } + + if (!this._instantiatedConstructorMethod) { + var referencedConstructorMethod = this.referencedTypeSymbol.getConstructorMethod(); + this._instantiatedConstructorMethod = new TypeScript.PullSymbol(referencedConstructorMethod.name, referencedConstructorMethod.kind); + this._instantiatedConstructorMethod.setRootSymbol(referencedConstructorMethod); + this._instantiatedConstructorMethod.setResolved(); + + this._instantiatedConstructorMethod.type = PullInstantiatedTypeReferenceSymbol.create(this._getResolver(), referencedConstructorMethod.type, this._typeParameterArgumentMap); + } + + return this._instantiatedConstructorMethod; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getAssociatedContainerType = function () { + if (!this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getAssociatedContainerType(); + } + + if (!this._instantiatedAssociatedContainerType) { + var referencedAssociatedContainerType = this.referencedTypeSymbol.getAssociatedContainerType(); + + if (referencedAssociatedContainerType) { + this._instantiatedAssociatedContainerType = PullInstantiatedTypeReferenceSymbol.create(this._getResolver(), referencedAssociatedContainerType, this._typeParameterArgumentMap); + } + } + + return this._instantiatedAssociatedContainerType; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getCallSignatures = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getCallSignatures(); + } + + if (this._instantiatedCallSignatures) { + return this._instantiatedCallSignatures; + } + + var referencedCallSignatures = this.referencedTypeSymbol.getCallSignatures(); + this._instantiatedCallSignatures = []; + + for (var i = 0; i < referencedCallSignatures.length; i++) { + this._getResolver().resolveDeclaredSymbol(referencedCallSignatures[i]); + + if (!referencedCallSignatures[i].wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._instantiatedCallSignatures[this._instantiatedCallSignatures.length] = referencedCallSignatures[i]; + } else { + this._instantiatedCallSignatures[this._instantiatedCallSignatures.length] = this._getResolver().instantiateSignature(referencedCallSignatures[i], this._typeParameterArgumentMap); + this._instantiatedCallSignatures[this._instantiatedCallSignatures.length - 1].functionType = this; + } + } + + return this._instantiatedCallSignatures; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getConstructSignatures = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getConstructSignatures(); + } + + if (this._instantiatedConstructSignatures) { + return this._instantiatedConstructSignatures; + } + + var referencedConstructSignatures = this.referencedTypeSymbol.getConstructSignatures(); + this._instantiatedConstructSignatures = []; + + for (var i = 0; i < referencedConstructSignatures.length; i++) { + this._getResolver().resolveDeclaredSymbol(referencedConstructSignatures[i]); + + if (!referencedConstructSignatures[i].wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._instantiatedConstructSignatures[this._instantiatedConstructSignatures.length] = referencedConstructSignatures[i]; + } else { + this._instantiatedConstructSignatures[this._instantiatedConstructSignatures.length] = this._getResolver().instantiateSignature(referencedConstructSignatures[i], this._typeParameterArgumentMap); + this._instantiatedConstructSignatures[this._instantiatedConstructSignatures.length - 1].functionType = this; + } + } + + return this._instantiatedConstructSignatures; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getIndexSignatures = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getIndexSignatures(); + } + + if (this._instantiatedIndexSignatures) { + return this._instantiatedIndexSignatures; + } + + var referencedIndexSignatures = this.referencedTypeSymbol.getIndexSignatures(); + this._instantiatedIndexSignatures = []; + + for (var i = 0; i < referencedIndexSignatures.length; i++) { + this._getResolver().resolveDeclaredSymbol(referencedIndexSignatures[i]); + + if (!referencedIndexSignatures[i].wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._instantiatedIndexSignatures[this._instantiatedIndexSignatures.length] = referencedIndexSignatures[i]; + } else { + this._instantiatedIndexSignatures[this._instantiatedIndexSignatures.length] = this._getResolver().instantiateSignature(referencedIndexSignatures[i], this._typeParameterArgumentMap); + this._instantiatedIndexSignatures[this._instantiatedIndexSignatures.length - 1].functionType = this; + } + } + + return this._instantiatedIndexSignatures; + }; + return PullInstantiatedTypeReferenceSymbol; + })(PullTypeReferenceSymbol); + TypeScript.PullInstantiatedTypeReferenceSymbol = PullInstantiatedTypeReferenceSymbol; + + var PullInstantiatedSignatureSymbol = (function (_super) { + __extends(PullInstantiatedSignatureSymbol, _super); + function PullInstantiatedSignatureSymbol(rootSignature, _typeParameterArgumentMap) { + _super.call(this, rootSignature.kind, rootSignature.isDefinition()); + this._typeParameterArgumentMap = _typeParameterArgumentMap; + this.setRootSymbol(rootSignature); + TypeScript.nSpecializedSignaturesCreated++; + + rootSignature.addSpecialization(this, _typeParameterArgumentMap); + } + PullInstantiatedSignatureSymbol.prototype.getTypeParameterArgumentMap = function () { + return this._typeParameterArgumentMap; + }; + + PullInstantiatedSignatureSymbol.prototype.getIsSpecialized = function () { + return true; + }; + + PullInstantiatedSignatureSymbol.prototype._getResolver = function () { + return this.getRootSymbol()._getResolver(); + }; + + PullInstantiatedSignatureSymbol.prototype.getTypeParameters = function () { + var _this = this; + if (!this._typeParameters) { + var rootSymbol = this.getRootSymbol(); + var typeParameters = rootSymbol.getTypeParameters(); + var hasInstantiatedTypeParametersOfThisSignature = TypeScript.ArrayUtilities.all(typeParameters, function (typeParameter) { + return _this._typeParameterArgumentMap[typeParameter.pullSymbolID] !== undefined; + }); + + if (!hasInstantiatedTypeParametersOfThisSignature && typeParameters.length) { + this._typeParameters = []; + for (var i = 0; i < typeParameters.length; i++) { + this._typeParameters[this._typeParameters.length] = this._getResolver().instantiateTypeParameter(typeParameters[i], this._typeParameterArgumentMap); + } + } else { + this._typeParameters = TypeScript.sentinelEmptyArray; + } + } + + return this._typeParameters; + }; + + PullInstantiatedSignatureSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + var rootSymbol = this.getRootSymbol(); + return rootSymbol.getAllowedToReferenceTypeParameters(); + }; + return PullInstantiatedSignatureSymbol; + })(TypeScript.PullSignatureSymbol); + TypeScript.PullInstantiatedSignatureSymbol = PullInstantiatedSignatureSymbol; + + var PullInstantiatedTypeParameterSymbol = (function (_super) { + __extends(PullInstantiatedTypeParameterSymbol, _super); + function PullInstantiatedTypeParameterSymbol(rootTypeParameter, constraintType) { + _super.call(this, rootTypeParameter.name); + TypeScript.nSpecializedTypeParameterCreated++; + + this.setRootSymbol(rootTypeParameter); + this.setConstraint(constraintType); + + rootTypeParameter.addSpecialization(this, [constraintType]); + } + PullInstantiatedTypeParameterSymbol.prototype._getResolver = function () { + return this.getRootSymbol()._getResolver(); + }; + return PullInstantiatedTypeParameterSymbol; + })(TypeScript.PullTypeParameterSymbol); + TypeScript.PullInstantiatedTypeParameterSymbol = PullInstantiatedTypeParameterSymbol; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTreeToAstVisitor = (function () { + function SyntaxTreeToAstVisitor(fileName, lineMap, compilationSettings) { + this.fileName = fileName; + this.lineMap = lineMap; + this.compilationSettings = compilationSettings; + this.position = 0; + this.previousTokenTrailingComments = null; + } + SyntaxTreeToAstVisitor.visit = function (syntaxTree, fileName, compilationSettings, incrementalAST) { + var visitor = incrementalAST ? new SyntaxTreeToIncrementalAstVisitor(fileName, syntaxTree.lineMap(), compilationSettings) : new SyntaxTreeToAstVisitor(fileName, syntaxTree.lineMap(), compilationSettings); + return syntaxTree.sourceUnit().accept(visitor); + }; + + SyntaxTreeToAstVisitor.prototype.movePast = function (element) { + if (element !== null) { + this.position += element.fullWidth(); + } + }; + + SyntaxTreeToAstVisitor.prototype.moveTo = function (element1, element2) { + if (element2 !== null) { + this.position += TypeScript.Syntax.childOffset(element1, element2); + } + }; + + SyntaxTreeToAstVisitor.prototype.setCommentsAndSpan = function (ast, fullStart, node) { + var firstToken = node.firstToken(); + var lastToken = node.lastToken(); + + this.setSpan(ast, fullStart, node, firstToken, lastToken); + ast.setPreComments(this.convertTokenLeadingComments(firstToken, fullStart)); + ast.setPostComments(this.convertNodeTrailingComments(node, lastToken, fullStart)); + }; + + SyntaxTreeToAstVisitor.prototype.createTokenSpan = function (fullStart, element) { + if (element === null) { + return null; + } + + if (element.fullWidth() === 0) { + return new TypeScript.ASTSpan(-1, -1); + } + + var leadingTriviaWidth = element.leadingTriviaWidth(); + var trailingTriviaWidth = element.trailingTriviaWidth(); + + var start = fullStart + leadingTriviaWidth; + var end = fullStart + element.fullWidth() - trailingTriviaWidth; + + return new TypeScript.ASTSpan(start, end); + }; + + SyntaxTreeToAstVisitor.prototype.setSpan = function (span, fullStart, element, firstToken, lastToken) { + if (typeof firstToken === "undefined") { firstToken = element.firstToken(); } + if (typeof lastToken === "undefined") { lastToken = element.lastToken(); } + var leadingTriviaWidth = firstToken ? firstToken.leadingTriviaWidth() : 0; + var trailingTriviaWidth = lastToken ? lastToken.trailingTriviaWidth() : 0; + + var desiredMinChar = fullStart + leadingTriviaWidth; + var desiredLimChar = fullStart + element.fullWidth() - trailingTriviaWidth; + + this.setSpanExplicit(span, desiredMinChar, desiredLimChar); + + span._trailingTriviaWidth = trailingTriviaWidth; + }; + + SyntaxTreeToAstVisitor.prototype.setSpanExplicit = function (span, start, end) { + span._start = start; + span._end = end; + }; + + SyntaxTreeToAstVisitor.prototype.visitSyntaxList = function (node) { + var start = this.position; + var array = new Array(node.childCount()); + + for (var i = 0, n = node.childCount(); i < n; i++) { + array[i] = node.childAt(i).accept(this); + } + + var result = new TypeScript.ISyntaxList2(this.fileName, array); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSeparatedSyntaxList = function (list) { + var start = this.position; + var array = new Array(list.nonSeparatorCount()); + + for (var i = 0, n = list.childCount(); i < n; i++) { + if (i % 2 === 0) { + array[i / 2] = list.childAt(i).accept(this); + this.previousTokenTrailingComments = null; + } else { + var separatorToken = list.childAt(i); + this.previousTokenTrailingComments = this.convertTokenTrailingComments(separatorToken, this.position + separatorToken.leadingTriviaWidth() + separatorToken.width()); + this.movePast(separatorToken); + } + } + + var result = new TypeScript.ISeparatedSyntaxList2(this.fileName, array, list.separatorCount()); + this.setSpan(result, start, list); + + result.setPostComments(this.previousTokenTrailingComments); + this.previousTokenTrailingComments = null; + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.convertComment = function (trivia, commentStartPosition, hasTrailingNewLine) { + var comment = new TypeScript.Comment(trivia, hasTrailingNewLine, commentStartPosition, commentStartPosition + trivia.fullWidth()); + + return comment; + }; + + SyntaxTreeToAstVisitor.prototype.convertComments = function (triviaList, commentStartPosition) { + var result = []; + + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + if (trivia.isComment()) { + var hasTrailingNewLine = ((i + 1) < n) && triviaList.syntaxTriviaAt(i + 1).isNewLine(); + result.push(this.convertComment(trivia, commentStartPosition, hasTrailingNewLine)); + } + + commentStartPosition += trivia.fullWidth(); + } + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.mergeComments = function (comments1, comments2) { + if (comments1 === null) { + return comments2; + } + + if (comments2 === null) { + return comments1; + } + + return comments1.concat(comments2); + }; + + SyntaxTreeToAstVisitor.prototype.convertTokenLeadingComments = function (token, commentStartPosition) { + if (token === null) { + return null; + } + + var preComments = token.hasLeadingComment() ? this.convertComments(token.leadingTrivia(), commentStartPosition) : null; + + var previousTokenTrailingComments = this.previousTokenTrailingComments; + this.previousTokenTrailingComments = null; + + return this.mergeComments(previousTokenTrailingComments, preComments); + }; + + SyntaxTreeToAstVisitor.prototype.convertTokenTrailingComments = function (token, commentStartPosition) { + if (token === null || !token.hasTrailingComment() || token.hasTrailingNewLine()) { + return null; + } + + return this.convertComments(token.trailingTrivia(), commentStartPosition); + }; + + SyntaxTreeToAstVisitor.prototype.convertNodeTrailingComments = function (node, lastToken, nodeStart) { + if (lastToken === null || !lastToken.hasTrailingComment() || lastToken.hasTrailingNewLine()) { + return null; + } + + return this.convertComments(lastToken.trailingTrivia(), nodeStart + node.fullWidth() - lastToken.trailingTriviaWidth()); + }; + + SyntaxTreeToAstVisitor.prototype.visitIdentifier = function (token) { + return this.visitToken(token); + }; + + SyntaxTreeToAstVisitor.prototype.visitToken = function (token) { + var fullStart = this.position; + + var result = this.visitTokenWorker(token); + + this.movePast(token); + + var start = fullStart + token.leadingTriviaWidth(); + this.setSpanExplicit(result, start, start + token.width()); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTokenWorker = function (token) { + switch (token.tokenKind) { + case 60 /* AnyKeyword */: + return new TypeScript.BuiltInType(60 /* AnyKeyword */, token.text(), token.valueText()); + case 61 /* BooleanKeyword */: + return new TypeScript.BuiltInType(61 /* BooleanKeyword */, token.text(), token.valueText()); + case 67 /* NumberKeyword */: + return new TypeScript.BuiltInType(67 /* NumberKeyword */, token.text(), token.valueText()); + case 69 /* StringKeyword */: + return new TypeScript.BuiltInType(69 /* StringKeyword */, token.text(), token.valueText()); + case 41 /* VoidKeyword */: + return new TypeScript.BuiltInType(41 /* VoidKeyword */, token.text(), token.valueText()); + case 35 /* ThisKeyword */: + return new TypeScript.ThisExpression(token.text(), token.valueText()); + case 50 /* SuperKeyword */: + return new TypeScript.SuperExpression(token.text(), token.valueText()); + case 37 /* TrueKeyword */: + return new TypeScript.LiteralExpression(37 /* TrueKeyword */, token.text(), token.valueText()); + case 24 /* FalseKeyword */: + return new TypeScript.LiteralExpression(24 /* FalseKeyword */, token.text(), token.valueText()); + case 32 /* NullKeyword */: + return new TypeScript.LiteralExpression(32 /* NullKeyword */, token.text(), token.valueText()); + case 14 /* StringLiteral */: + return new TypeScript.StringLiteral(token.text(), token.valueText()); + case 12 /* RegularExpressionLiteral */: + return new TypeScript.RegularExpressionLiteral(token.text(), token.valueText()); + case 13 /* NumericLiteral */: + var fullStart = this.position; + var preComments = this.convertTokenLeadingComments(token, fullStart); + + var result = new TypeScript.NumericLiteral(token.value(), token.text(), token.valueText()); + + result.setPreComments(preComments); + return result; + case 11 /* IdentifierName */: + return new TypeScript.Identifier(token.text()); + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SyntaxTreeToAstVisitor.prototype.visitSourceUnit = function (node) { + var start = this.position; + TypeScript.Debug.assert(start === 0); + + var bod = this.visitSyntaxList(node.moduleElements); + var comments = this.convertTokenLeadingComments(node.endOfFileToken, TypeScript.Syntax.childOffset(node, node.endOfFileToken)); + var result = new TypeScript.SourceUnit(bod, comments, this.fileName); + this.setSpanExplicit(result, start, start + node.fullWidth()); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitExternalModuleReference = function (node) { + var start = this.position; + + this.moveTo(node, node.stringLiteral); + var stringLiteral = node.stringLiteral.accept(this); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ExternalModuleReference(stringLiteral); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitModuleNameModuleReference = function (node) { + var start = this.position; + var moduleName = node.moduleName.accept(this); + + var result = new TypeScript.ModuleNameModuleReference(moduleName); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitClassDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var heritageClauses = node.heritageClauses ? this.visitSyntaxList(node.heritageClauses) : null; + + this.movePast(node.openBraceToken); + var members = this.visitSyntaxList(node.classElements); + + var closeBraceToken = this.createTokenSpan(this.position, node.closeBraceToken); + this.movePast(node.closeBraceToken); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.ClassDeclaration(modifiers, name, typeParameters, heritageClauses, members, closeBraceToken); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitModifiers = function (modifiers) { + var result = null; + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 47 /* ExportKeyword */)) { + result = result || []; + result.push(1 /* Exported */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 63 /* DeclareKeyword */)) { + result = result || []; + result.push(8 /* Ambient */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 58 /* StaticKeyword */)) { + result = result || []; + result.push(16 /* Static */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 57 /* PublicKeyword */)) { + result = result || []; + result.push(4 /* Public */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 55 /* PrivateKeyword */)) { + result = result || []; + result.push(2 /* Private */); + } + + return result || TypeScript.sentinelEmptyArray; + }; + + SyntaxTreeToAstVisitor.prototype.visitInterfaceDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var heritageClauses = node.heritageClauses ? this.visitSyntaxList(node.heritageClauses) : null; + + var body = this.visitObjectType(node.body); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.InterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, body); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitHeritageClause = function (node) { + var start = this.position; + + this.movePast(node.extendsOrImplementsKeyword); + var typeNames = this.visitSeparatedSyntaxList(node.typeNames); + + var result = new TypeScript.HeritageClause(node.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */ ? 230 /* ExtendsHeritageClause */ : 231 /* ImplementsHeritageClause */, typeNames); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitModuleDeclaration = function (node) { + var start = this.position; + + var modifiers = this.visitModifiers(node.modifiers); + + this.moveTo(node, node.moduleKeyword); + this.movePast(node.moduleKeyword); + + var moduleName = node.name ? node.name.accept(this) : null; + var stringLiteral = node.stringLiteral ? node.stringLiteral.accept(this) : null; + + this.movePast(node.openBraceToken); + + var moduleElements = this.visitSyntaxList(node.moduleElements); + + var closeBraceToken = this.createTokenSpan(this.position, node.closeBraceToken); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.ModuleDeclaration(modifiers, moduleName, stringLiteral, moduleElements, closeBraceToken); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + + var callSignature = this.visitCallSignature(node.callSignature); + var block = node.block ? this.visitBlock(node.block) : null; + + this.movePast(node.semicolonToken); + + var result = new TypeScript.FunctionDeclaration(this.visitModifiers(node.modifiers), name, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEnumDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var identifier = this.visitIdentifier(node.identifier); + + this.movePast(node.openBraceToken); + + var enumElements = this.visitSeparatedSyntaxList(node.enumElements); + + this.movePast(node.closeBraceToken); + + var result = new TypeScript.EnumDeclaration(this.visitModifiers(node.modifiers), identifier, enumElements); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEnumElement = function (node) { + var start = this.position; + + var memberName = this.visitToken(node.propertyName); + + var value = node.equalsValueClause !== null ? this.visitEqualsValueClause(node.equalsValueClause) : null; + + var result = new TypeScript.EnumElement(memberName, value); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitImportDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + this.movePast(node.equalsToken); + var alias = node.moduleReference.accept(this); + this.movePast(node.semicolonToken); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.ImportDeclaration(modifiers, name, alias); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitExportAssignment = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + this.movePast(node.semicolonToken); + + var result = new TypeScript.ExportAssignment(name); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.variableDeclaration); + + var declaration = node.variableDeclaration.accept(this); + this.movePast(node.semicolonToken); + + var modifiers = this.visitModifiers(node.modifiers); + + var result = new TypeScript.VariableStatement(modifiers, declaration); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.variableDeclarators); + var variableDecls = this.visitSeparatedSyntaxList(node.variableDeclarators); + + var result = new TypeScript.VariableDeclaration(variableDecls); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableDeclarator = function (node) { + var start = this.position; + var propertyName = this.visitToken(node.propertyName); + var typeExpr = this.visitTypeAnnotation(node.typeAnnotation); + var init = node.equalsValueClause ? this.visitEqualsValueClause(node.equalsValueClause) : null; + + var result = new TypeScript.VariableDeclarator(propertyName, typeExpr, init); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEqualsValueClause = function (node) { + var start = this.position; + var afterEqualsComments = this.convertTokenTrailingComments(node.equalsToken, this.position + node.equalsToken.leadingTriviaWidth() + node.equalsToken.width()); + + this.movePast(node.equalsToken); + var value = node.value.accept(this); + value.setPreComments(this.mergeComments(afterEqualsComments, value.preComments())); + + var result = new TypeScript.EqualsValueClause(value); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPrefixUnaryExpression = function (node) { + var start = this.position; + + this.movePast(node.operatorToken); + var operand = node.operand.accept(this); + + var result = new TypeScript.PrefixUnaryExpression(node.kind(), operand); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArrayLiteralExpression = function (node) { + var start = this.position; + var openStart = this.position + node.openBracketToken.leadingTriviaWidth(); + this.movePast(node.openBracketToken); + + var expressions = this.visitSeparatedSyntaxList(node.expressions); + + var closeStart = this.position + node.closeBracketToken.leadingTriviaWidth(); + this.movePast(node.closeBracketToken); + + var result = new TypeScript.ArrayLiteralExpression(expressions); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitOmittedExpression = function (node) { + var start = this.position; + + var result = new TypeScript.OmittedExpression(); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParenthesizedExpression = function (node) { + var start = this.position; + + var openParenToken = node.openParenToken; + var openParenTrailingComments = this.convertTokenTrailingComments(openParenToken, start + openParenToken.leadingTriviaWidth() + openParenToken.width()); + + this.movePast(openParenToken); + + var expr = node.expression.accept(this); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ParenthesizedExpression(openParenTrailingComments, expr); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + var start = this.position; + + var identifier = node.identifier.accept(this); + this.movePast(node.equalsGreaterThanToken); + + var block = node.block ? this.visitBlock(node.block) : null; + var expression = node.expression ? node.expression.accept(this) : null; + + var result = new TypeScript.SimpleArrowFunctionExpression(identifier, block, expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + var start = this.position; + + var callSignature = this.visitCallSignature(node.callSignature); + this.movePast(node.equalsGreaterThanToken); + + var block = node.block ? this.visitBlock(node.block) : null; + var expression = node.expression ? node.expression.accept(this) : null; + + var result = new TypeScript.ParenthesizedArrowFunctionExpression(callSignature, block, expression); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitType = function (type) { + return type ? type.accept(this) : null; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeQuery = function (node) { + var start = this.position; + this.movePast(node.typeOfKeyword); + var name = node.name.accept(this); + + var result = new TypeScript.TypeQuery(name); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitQualifiedName = function (node) { + var start = this.position; + var left = this.visitType(node.left); + this.movePast(node.dotToken); + var right = this.visitIdentifier(node.right); + + var result = new TypeScript.QualifiedName(left, right); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeArgumentList = function (node) { + if (node === null) { + return null; + } + + var start = this.position; + this.movePast(node.lessThanToken); + var typeArguments = this.visitSeparatedSyntaxList(node.typeArguments); + this.movePast(node.greaterThanToken); + + var result = new TypeScript.TypeArgumentList(typeArguments); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructorType = function (node) { + var start = this.position; + + this.movePast(node.newKeyword); + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var parameters = this.visitParameterList(node.parameterList); + this.movePast(node.equalsGreaterThanToken); + var returnType = this.visitType(node.type); + + var result = new TypeScript.ConstructorType(typeParameters, parameters, returnType); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionType = function (node) { + var start = this.position; + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var parameters = this.visitParameterList(node.parameterList); + this.movePast(node.equalsGreaterThanToken); + var returnType = this.visitType(node.type); + + var result = new TypeScript.FunctionType(typeParameters, parameters, returnType); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectType = function (node) { + var start = this.position; + + this.movePast(node.openBraceToken); + var typeMembers = this.visitSeparatedSyntaxList(node.typeMembers); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.ObjectType(typeMembers); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArrayType = function (node) { + var start = this.position; + + var underlying = this.visitType(node.type); + this.movePast(node.openBracketToken); + this.movePast(node.closeBracketToken); + + var result = new TypeScript.ArrayType(underlying); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitGenericType = function (node) { + var start = this.position; + + var underlying = this.visitType(node.name); + var typeArguments = this.visitTypeArgumentList(node.typeArgumentList); + + var result = new TypeScript.GenericType(underlying, typeArguments); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeAnnotation = function (node) { + if (!node) { + return null; + } + + var start = this.position; + this.movePast(node.colonToken); + var type = this.visitType(node.type); + + var result = new TypeScript.TypeAnnotation(type); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitBlock = function (node) { + if (!node) { + return null; + } + + var start = this.position; + + this.movePast(node.openBraceToken); + var statements = this.visitSyntaxList(node.statements); + var closeBracePosition = this.position; + + var closeBraceLeadingComments = this.convertTokenLeadingComments(node.closeBraceToken, this.position); + var closeBraceToken = this.createTokenSpan(this.position, node.closeBraceToken); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.Block(statements, closeBraceLeadingComments, closeBraceToken); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParameter = function (node) { + var start = this.position; + + var dotDotDotToken = this.createTokenSpan(this.position, node.dotDotDotToken); + + this.moveTo(node, node.identifier); + var identifier = this.visitIdentifier(node.identifier); + + var questionToken = this.createTokenSpan(this.position, node.questionToken); + this.movePast(node.questionToken); + var typeExpr = this.visitTypeAnnotation(node.typeAnnotation); + var init = node.equalsValueClause ? node.equalsValueClause.accept(this) : null; + + var modifiers = this.visitModifiers(node.modifiers); + + var result = new TypeScript.Parameter(dotDotDotToken, modifiers, identifier, questionToken, typeExpr, init); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberAccessExpression = function (node) { + var start = this.position; + + var expression = node.expression.accept(this); + this.movePast(node.dotToken); + var name = this.visitIdentifier(node.name); + + var result = new TypeScript.MemberAccessExpression(expression, name); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPostfixUnaryExpression = function (node) { + var start = this.position; + + var operand = node.operand.accept(this); + this.movePast(node.operatorToken); + + var result = new TypeScript.PostfixUnaryExpression(node.kind() === 210 /* PostIncrementExpression */ ? 210 /* PostIncrementExpression */ : 211 /* PostDecrementExpression */, operand); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitElementAccessExpression = function (node) { + var start = this.position; + + var expression = node.expression.accept(this); + this.movePast(node.openBracketToken); + var argumentExpression = node.argumentExpression.accept(this); + this.movePast(node.closeBracketToken); + + var result = new TypeScript.ElementAccessExpression(expression, argumentExpression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitInvocationExpression = function (node) { + var start = this.position; + + var expression = node.expression.accept(this); + var argumentList = this.visitArgumentList(node.argumentList); + + var result = new TypeScript.InvocationExpression(expression, argumentList); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArgumentList = function (node) { + if (node === null) { + return null; + } + + var start = this.position; + + var typeArguments = this.visitTypeArgumentList(node.typeArgumentList); + + this.movePast(node.openParenToken); + + var _arguments = this.visitSeparatedSyntaxList(node.arguments); + + if (node.arguments.fullWidth() === 0 && node.closeParenToken.fullWidth() === 0) { + var openParenTokenEnd = start + node.openParenToken.leadingTriviaWidth() + node.openParenToken.width(); + this.setSpanExplicit(_arguments, openParenTokenEnd, openParenTokenEnd + node.openParenToken.trailingTriviaWidth()); + } + + var closeParenToken = this.createTokenSpan(this.position, node.closeParenToken); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ArgumentList(typeArguments, _arguments, closeParenToken); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitBinaryExpression = function (node) { + var start = this.position; + + var left = node.left.accept(this); + this.movePast(node.operatorToken); + var right = node.right.accept(this); + + var result = new TypeScript.BinaryExpression(node.kind(), left, right); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConditionalExpression = function (node) { + var start = this.position; + + var condition = node.condition.accept(this); + this.movePast(node.questionToken); + var whenTrue = node.whenTrue.accept(this); + this.movePast(node.colonToken); + var whenFalse = node.whenFalse.accept(this); + + var result = new TypeScript.ConditionalExpression(condition, whenTrue, whenFalse); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructSignature = function (node) { + var start = this.position; + + this.movePast(node.newKeyword); + var callSignature = this.visitCallSignature(node.callSignature); + + var result = new TypeScript.ConstructSignature(callSignature); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMethodSignature = function (node) { + var start = this.position; + + var name = this.visitToken(node.propertyName); + + var questionToken = this.createTokenSpan(this.position, node.questionToken); + this.movePast(node.questionToken); + + var callSignature = this.visitCallSignature(node.callSignature); + + var result = new TypeScript.MethodSignature(name, questionToken, callSignature); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitIndexSignature = function (node) { + var start = this.position; + + this.movePast(node.openBracketToken); + + var parameter = node.parameter.accept(this); + + this.movePast(node.closeBracketToken); + var returnType = this.visitTypeAnnotation(node.typeAnnotation); + + var result = new TypeScript.IndexSignature(parameter, returnType); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPropertySignature = function (node) { + var start = this.position; + + var name = this.visitToken(node.propertyName); + + var questionToken = this.createTokenSpan(this.position, node.questionToken); + this.movePast(node.questionToken); + var typeExpr = this.visitTypeAnnotation(node.typeAnnotation); + + var result = new TypeScript.PropertySignature(name, questionToken, typeExpr); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParameterList = function (node) { + if (!node) { + return null; + } + + var start = this.position; + + var openParenToken = node.openParenToken; + + this.previousTokenTrailingComments = this.convertTokenTrailingComments(openParenToken, start + openParenToken.leadingTriviaWidth() + openParenToken.width()); + var openParenTrailingComments = null; + if (node.parameters.childCount() === 0) { + openParenTrailingComments = this.previousTokenTrailingComments; + this.previousTokenTrailingComments = null; + } + + this.movePast(node.openParenToken); + var parameters = this.visitSeparatedSyntaxList(node.parameters); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ParameterList(openParenTrailingComments, parameters); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCallSignature = function (node) { + var start = this.position; + + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var parameters = this.visitParameterList(node.parameterList); + var returnType = this.visitTypeAnnotation(node.typeAnnotation); + + var result = new TypeScript.CallSignature(typeParameters, parameters, returnType); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeParameterList = function (node) { + if (!node) { + return null; + } + + var start = this.position; + this.movePast(node.lessThanToken); + var typeParameters = this.visitSeparatedSyntaxList(node.typeParameters); + this.movePast(node.greaterThanToken); + + var result = new TypeScript.TypeParameterList(typeParameters); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeParameter = function (node) { + var start = this.position; + + var identifier = this.visitIdentifier(node.identifier); + var constraint = node.constraint ? node.constraint.accept(this) : null; + + var result = new TypeScript.TypeParameter(identifier, constraint); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstraint = function (node) { + var start = this.position; + this.movePast(node.extendsKeyword); + var type = this.visitType(node.type); + + var result = new TypeScript.Constraint(type); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitIfStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var thenBod = node.statement.accept(this); + var elseBod = node.elseClause ? node.elseClause.accept(this) : null; + + var result = new TypeScript.IfStatement(condition, thenBod, elseBod); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitElseClause = function (node) { + var start = this.position; + + this.movePast(node.elseKeyword); + var statement = node.statement.accept(this); + + var result = new TypeScript.ElseClause(statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitExpressionStatement = function (node) { + var start = this.position; + + var preComments = this.convertTokenLeadingComments(node.firstToken(), start); + var expression = node.expression.accept(this); + + var semicolonPosition = this.position; + + var postComments = this.convertComments(node.semicolonToken.trailingTrivia(), this.position + node.semicolonToken.leadingTriviaWidth() + node.semicolonToken.width()); + this.movePast(node.semicolonToken); + + var result = new TypeScript.ExpressionStatement(expression); + this.setSpan(result, start, node); + + result.setPreComments(preComments); + result.setPostComments(postComments); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructorDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.callSignature); + var callSignature = this.visitCallSignature(node.callSignature); + + var block = node.block ? node.block.accept(this) : null; + + this.movePast(node.semicolonToken); + + var result = new TypeScript.ConstructorDeclaration(callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitIndexMemberDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.indexSignature); + var indexSignature = node.indexSignature.accept(this); + + this.movePast(node.semicolonToken); + + var result = new TypeScript.IndexMemberDeclaration(indexSignature); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.propertyName); + var name = this.visitToken(node.propertyName); + + var callSignature = this.visitCallSignature(node.callSignature); + var block = node.block ? this.visitBlock(node.block) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.MemberFunctionDeclaration(this.visitModifiers(node.modifiers), name, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitGetAccessor = function (node) { + var start = this.position; + + this.moveTo(node, node.propertyName); + var name = this.visitToken(node.propertyName); + var parameters = this.visitParameterList(node.parameterList); + var returnType = this.visitTypeAnnotation(node.typeAnnotation); + + var block = node.block ? node.block.accept(this) : null; + var result = new TypeScript.GetAccessor(this.visitModifiers(node.modifiers), name, parameters, returnType, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSetAccessor = function (node) { + var start = this.position; + + this.moveTo(node, node.propertyName); + var name = this.visitToken(node.propertyName); + var parameters = this.visitParameterList(node.parameterList); + var block = node.block ? node.block.accept(this) : null; + var result = new TypeScript.SetAccessor(this.visitModifiers(node.modifiers), name, parameters, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberVariableDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.variableDeclarator); + var variableDeclarator = node.variableDeclarator.accept(this); + this.movePast(node.semicolonToken); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.MemberVariableDeclaration(modifiers, variableDeclarator); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitThrowStatement = function (node) { + var start = this.position; + + this.movePast(node.throwKeyword); + var expression = node.expression.accept(this); + this.movePast(node.semicolonToken); + + var result = new TypeScript.ThrowStatement(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitReturnStatement = function (node) { + var start = this.position; + + this.movePast(node.returnKeyword); + var expression = node.expression ? node.expression.accept(this) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.ReturnStatement(expression); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectCreationExpression = function (node) { + var start = this.position; + + this.movePast(node.newKeyword); + var expression = node.expression.accept(this); + var argumentList = this.visitArgumentList(node.argumentList); + + var result = new TypeScript.ObjectCreationExpression(expression, argumentList); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSwitchStatement = function (node) { + var start = this.position; + + this.movePast(node.switchKeyword); + this.movePast(node.openParenToken); + var expression = node.expression.accept(this); + + var closeParenToken = this.createTokenSpan(this.position, node.closeParenToken); + this.movePast(node.closeParenToken); + this.movePast(node.openBraceToken); + var switchClauses = this.visitSyntaxList(node.switchClauses); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.SwitchStatement(expression, closeParenToken, switchClauses); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCaseSwitchClause = function (node) { + var start = this.position; + + this.movePast(node.caseKeyword); + var expression = node.expression.accept(this); + this.movePast(node.colonToken); + var statements = this.visitSyntaxList(node.statements); + + var result = new TypeScript.CaseSwitchClause(expression, statements); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDefaultSwitchClause = function (node) { + var start = this.position; + + this.movePast(node.defaultKeyword); + this.movePast(node.colonToken); + var statements = this.visitSyntaxList(node.statements); + + var result = new TypeScript.DefaultSwitchClause(statements); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitBreakStatement = function (node) { + var start = this.position; + + this.movePast(node.breakKeyword); + var identifier = node.identifier ? node.identifier.accept(this) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.BreakStatement(identifier); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitContinueStatement = function (node) { + var start = this.position; + + this.movePast(node.continueKeyword); + var identifier = node.identifier ? node.identifier.accept(this) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.ContinueStatement(identifier); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitForStatement = function (node) { + var start = this.position; + + this.movePast(node.forKeyword); + this.movePast(node.openParenToken); + var variableDeclaration = node.variableDeclaration ? node.variableDeclaration.accept(this) : null; + var initializer = node.initializer ? node.initializer.accept(this) : null; + + this.movePast(node.firstSemicolonToken); + var cond = node.condition ? node.condition.accept(this) : null; + this.movePast(node.secondSemicolonToken); + var incr = node.incrementor ? node.incrementor.accept(this) : null; + this.movePast(node.closeParenToken); + var body = node.statement.accept(this); + + var result = new TypeScript.ForStatement(variableDeclaration, initializer, cond, incr, body); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitForInStatement = function (node) { + var start = this.position; + + this.movePast(node.forKeyword); + this.movePast(node.openParenToken); + var variableDeclaration = node.variableDeclaration ? node.variableDeclaration.accept(this) : null; + var left = node.left ? node.left.accept(this) : null; + + this.movePast(node.inKeyword); + var expression = node.expression.accept(this); + this.movePast(node.closeParenToken); + var body = node.statement.accept(this); + + var result = new TypeScript.ForInStatement(variableDeclaration, left, expression, body); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitWhileStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var statement = node.statement.accept(this); + + var result = new TypeScript.WhileStatement(condition, statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitWithStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var statement = node.statement.accept(this); + + var result = new TypeScript.WithStatement(condition, statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCastExpression = function (node) { + var start = this.position; + + this.movePast(node.lessThanToken); + var castTerm = this.visitType(node.type); + this.movePast(node.greaterThanToken); + var expression = node.expression.accept(this); + + var result = new TypeScript.CastExpression(castTerm, expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectLiteralExpression = function (node) { + var start = this.position; + + var openStart = this.position + node.openBraceToken.leadingTriviaWidth(); + this.movePast(node.openBraceToken); + + var propertyAssignments = this.visitSeparatedSyntaxList(node.propertyAssignments); + + var closeStart = this.position + node.closeBraceToken.leadingTriviaWidth(); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.ObjectLiteralExpression(propertyAssignments); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSimplePropertyAssignment = function (node) { + var start = this.position; + + var preComments = this.convertTokenLeadingComments(node.firstToken(), start); + var postComments = this.convertNodeTrailingComments(node, node.lastToken(), start); + + var propertyName = node.propertyName.accept(this); + + var afterColonComments = this.convertTokenTrailingComments(node.colonToken, this.position + node.colonToken.leadingTriviaWidth() + node.colonToken.width()); + + this.movePast(node.colonToken); + var expression = node.expression.accept(this); + expression.setPreComments(this.mergeComments(afterColonComments, expression.preComments())); + + var result = new TypeScript.SimplePropertyAssignment(propertyName, expression); + this.setSpan(result, start, node); + + result.setPreComments(preComments); + result.setPostComments(postComments); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + var start = this.position; + + var propertyName = node.propertyName.accept(this); + var callSignature = this.visitCallSignature(node.callSignature); + var block = this.visitBlock(node.block); + + var result = new TypeScript.FunctionPropertyAssignment(propertyName, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionExpression = function (node) { + var start = this.position; + + this.movePast(node.functionKeyword); + var name = node.identifier === null ? null : this.visitIdentifier(node.identifier); + + var callSignature = this.visitCallSignature(node.callSignature); + var block = node.block ? node.block.accept(this) : null; + + var result = new TypeScript.FunctionExpression(name, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEmptyStatement = function (node) { + var start = this.position; + + this.movePast(node.semicolonToken); + + var result = new TypeScript.EmptyStatement(); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTryStatement = function (node) { + var start = this.position; + + this.movePast(node.tryKeyword); + var tryBody = node.block.accept(this); + + var catchClause = null; + if (node.catchClause !== null) { + catchClause = node.catchClause.accept(this); + } + + var finallyBody = null; + if (node.finallyClause !== null) { + finallyBody = node.finallyClause.accept(this); + } + + var result = new TypeScript.TryStatement(tryBody, catchClause, finallyBody); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCatchClause = function (node) { + var start = this.position; + + this.movePast(node.catchKeyword); + this.movePast(node.openParenToken); + var identifier = this.visitIdentifier(node.identifier); + var typeAnnotation = this.visitTypeAnnotation(node.typeAnnotation); + this.movePast(node.closeParenToken); + var block = node.block.accept(this); + + var result = new TypeScript.CatchClause(identifier, typeAnnotation, block); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFinallyClause = function (node) { + var start = this.position; + this.movePast(node.finallyKeyword); + var block = node.block.accept(this); + + var result = new TypeScript.FinallyClause(block); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitLabeledStatement = function (node) { + var start = this.position; + + var identifier = this.visitIdentifier(node.identifier); + this.movePast(node.colonToken); + var statement = node.statement.accept(this); + + var result = new TypeScript.LabeledStatement(identifier, statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDoStatement = function (node) { + var start = this.position; + + this.movePast(node.doKeyword); + var statement = node.statement.accept(this); + var whileKeyword = this.createTokenSpan(this.position, node.whileKeyword); + + this.movePast(node.whileKeyword); + this.movePast(node.openParenToken); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + this.movePast(node.semicolonToken); + + var result = new TypeScript.DoStatement(statement, whileKeyword, condition); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeOfExpression = function (node) { + var start = this.position; + + this.movePast(node.typeOfKeyword); + var expression = node.expression.accept(this); + + var result = new TypeScript.TypeOfExpression(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDeleteExpression = function (node) { + var start = this.position; + + this.movePast(node.deleteKeyword); + var expression = node.expression.accept(this); + + var result = new TypeScript.DeleteExpression(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVoidExpression = function (node) { + var start = this.position; + + this.movePast(node.voidKeyword); + var expression = node.expression.accept(this); + + var result = new TypeScript.VoidExpression(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDebuggerStatement = function (node) { + var start = this.position; + + this.movePast(node.debuggerKeyword); + this.movePast(node.semicolonToken); + + var result = new TypeScript.DebuggerStatement(); + this.setSpan(result, start, node); + + return result; + }; + return SyntaxTreeToAstVisitor; + })(); + TypeScript.SyntaxTreeToAstVisitor = SyntaxTreeToAstVisitor; + + function applyDelta(ast, delta) { + if (ast) { + if (ast._start !== -1) { + ast._start += delta; + } + + if (ast._end !== -1) { + ast._end += delta; + } + } + } + + function applyDeltaToComments(comments, delta) { + if (comments && comments.length > 0) { + for (var i = 0; i < comments.length; i++) { + var comment = comments[i]; + applyDelta(comment, delta); + } + } + } + + var SyntaxTreeToIncrementalAstVisitor = (function (_super) { + __extends(SyntaxTreeToIncrementalAstVisitor, _super); + function SyntaxTreeToIncrementalAstVisitor() { + _super.apply(this, arguments); + } + SyntaxTreeToIncrementalAstVisitor.prototype.applyDelta = function (ast, delta) { + if (delta === 0) { + return; + } + + var pre = function (cur) { + applyDelta(cur, delta); + applyDeltaToComments(cur.preComments(), delta); + applyDeltaToComments(cur.postComments(), delta); + + switch (cur.kind()) { + case 146 /* Block */: + applyDelta(cur.closeBraceToken, delta); + break; + + case 226 /* ArgumentList */: + applyDelta(cur.closeParenToken, delta); + break; + + case 130 /* ModuleDeclaration */: + applyDelta(cur.endingToken, delta); + break; + + case 131 /* ClassDeclaration */: + applyDelta(cur.closeBraceToken, delta); + break; + + case 161 /* DoStatement */: + applyDelta(cur.whileKeyword, delta); + break; + + case 151 /* SwitchStatement */: + applyDelta(cur.closeParenToken, delta); + break; + } + }; + + TypeScript.getAstWalkerFactory().simpleWalk(ast, pre); + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.setSpanExplicit = function (span, start, end) { + if (span._start !== -1) { + var delta = start - span._start; + this.applyDelta(span, delta); + + span._end = end; + } else { + _super.prototype.setSpanExplicit.call(this, span, start, end); + } + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.getAndMovePastAST = function (element) { + if (this.previousTokenTrailingComments !== null) { + return null; + } + + var result = element._ast; + if (!result) { + return null; + } + + var start = this.position; + this.movePast(element); + this.setSpan(result, start, element); + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.setAST = function (element, ast) { + element._ast = ast; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSyntaxList = function (list) { + var result = this.getAndMovePastAST(list); + if (!result) { + result = _super.prototype.visitSyntaxList.call(this, list); + + if (list.childCount() > 0) { + this.setAST(list, result); + } + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSeparatedSyntaxList = function (list) { + var result = this.getAndMovePastAST(list); + if (!result) { + result = _super.prototype.visitSeparatedSyntaxList.call(this, list); + + if (list.childCount() > 0) { + this.setAST(list, result); + } + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitToken = function (token) { + var result = this.getAndMovePastAST(token); + + if (!result) { + result = _super.prototype.visitToken.call(this, token); + this.setAST(token, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitClassDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitClassDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitInterfaceDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitInterfaceDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitHeritageClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitHeritageClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitModuleDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitModuleDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitImportDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitImportDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitExportAssignment = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitExportAssignment.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitPrefixUnaryExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitPrefixUnaryExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitArrayLiteralExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitArrayLiteralExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitOmittedExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitOmittedExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitParenthesizedExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitParenthesizedExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSimpleArrowFunctionExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitParenthesizedArrowFunctionExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitQualifiedName = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + var result = _super.prototype.visitQualifiedName.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConstructorType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConstructorType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitObjectType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitObjectType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitArrayType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitArrayType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitGenericType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitGenericType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitBlock = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitBlock.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitParameter = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitParameter.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMemberAccessExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMemberAccessExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitPostfixUnaryExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitPostfixUnaryExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitElementAccessExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitElementAccessExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitInvocationExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitInvocationExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitBinaryExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitBinaryExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConditionalExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConditionalExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConstructSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConstructSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMethodSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMethodSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitIndexSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitIndexSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitPropertySignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitPropertySignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCallSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCallSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitTypeParameter = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitTypeParameter.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitIfStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitIfStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitExpressionStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitExpressionStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConstructorDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConstructorDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMemberFunctionDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitGetAccessor = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitGetAccessor.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSetAccessor = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSetAccessor.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMemberVariableDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMemberVariableDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitThrowStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitThrowStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitReturnStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitReturnStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitObjectCreationExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitObjectCreationExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSwitchStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSwitchStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCaseSwitchClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCaseSwitchClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDefaultSwitchClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDefaultSwitchClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitBreakStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitBreakStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitContinueStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitContinueStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitForStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitForStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitForInStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitForInStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitWhileStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitWhileStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitWithStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitWithStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCastExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCastExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitObjectLiteralExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitObjectLiteralExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSimplePropertyAssignment = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSimplePropertyAssignment.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionPropertyAssignment.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitEmptyStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitEmptyStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitTryStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitTryStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCatchClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCatchClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitLabeledStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitLabeledStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDoStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDoStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitTypeOfExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitTypeOfExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDeleteExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDeleteExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitVoidExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitVoidExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDebuggerStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDebuggerStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + return SyntaxTreeToIncrementalAstVisitor; + })(SyntaxTreeToAstVisitor); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ASTSpan = (function () { + function ASTSpan(_start, _end) { + this._start = _start; + this._end = _end; + } + ASTSpan.prototype.start = function () { + return this._start; + }; + + ASTSpan.prototype.end = function () { + return this._end; + }; + return ASTSpan; + })(); + TypeScript.ASTSpan = ASTSpan; + + var astID = 0; + + function structuralEqualsNotIncludingPosition(ast1, ast2) { + return structuralEquals(ast1, ast2, false); + } + TypeScript.structuralEqualsNotIncludingPosition = structuralEqualsNotIncludingPosition; + + function structuralEqualsIncludingPosition(ast1, ast2) { + return structuralEquals(ast1, ast2, true); + } + TypeScript.structuralEqualsIncludingPosition = structuralEqualsIncludingPosition; + + function commentStructuralEqualsNotIncludingPosition(ast1, ast2) { + return commentStructuralEquals(ast1, ast2, false); + } + + function commentStructuralEqualsIncludingPosition(ast1, ast2) { + return commentStructuralEquals(ast1, ast2, true); + } + + function structuralEquals(ast1, ast2, includingPosition) { + if (ast1 === ast2) { + return true; + } + + return ast1 !== null && ast2 !== null && ast1.kind() === ast2.kind() && ast1.structuralEquals(ast2, includingPosition); + } + + function commentStructuralEquals(ast1, ast2, includingPosition) { + if (ast1 === ast2) { + return true; + } + + return ast1 !== null && ast2 !== null && ast1.structuralEquals(ast2, includingPosition); + } + + function astArrayStructuralEquals(array1, array2, includingPosition) { + return TypeScript.ArrayUtilities.sequenceEquals(array1, array2, includingPosition ? structuralEqualsIncludingPosition : structuralEqualsNotIncludingPosition); + } + + function commentArrayStructuralEquals(array1, array2, includingPosition) { + return TypeScript.ArrayUtilities.sequenceEquals(array1, array2, includingPosition ? commentStructuralEqualsIncludingPosition : commentStructuralEqualsNotIncludingPosition); + } + + var AST = (function () { + function AST() { + this.parent = null; + this._start = -1; + this._end = -1; + this._trailingTriviaWidth = 0; + this._astID = astID++; + this._preComments = null; + this._postComments = null; + } + AST.prototype.syntaxID = function () { + return this._astID; + }; + + AST.prototype.start = function () { + return this._start; + }; + + AST.prototype.end = function () { + return this._end; + }; + + AST.prototype.trailingTriviaWidth = function () { + return this._trailingTriviaWidth; + }; + + AST.prototype.fileName = function () { + return this.parent.fileName(); + }; + + AST.prototype.kind = function () { + throw TypeScript.Errors.abstract(); + }; + + AST.prototype.preComments = function () { + return this._preComments; + }; + + AST.prototype.postComments = function () { + return this._postComments; + }; + + AST.prototype.setPreComments = function (comments) { + if (comments && comments.length) { + this._preComments = comments; + } else if (this._preComments) { + this._preComments = null; + } + }; + + AST.prototype.setPostComments = function (comments) { + if (comments && comments.length) { + this._postComments = comments; + } else if (this._postComments) { + this._postComments = null; + } + }; + + AST.prototype.width = function () { + return this.end() - this.start(); + }; + + AST.prototype.structuralEquals = function (ast, includingPosition) { + if (includingPosition) { + if (this.start() !== ast.start() || this.end() !== ast.end()) { + return false; + } + } + + return commentArrayStructuralEquals(this.preComments(), ast.preComments(), includingPosition) && commentArrayStructuralEquals(this.postComments(), ast.postComments(), includingPosition); + }; + + AST.prototype.isExpression = function () { + return false; + }; + return AST; + })(); + TypeScript.AST = AST; + + var ISyntaxList2 = (function (_super) { + __extends(ISyntaxList2, _super); + function ISyntaxList2(_fileName, members) { + _super.call(this); + this._fileName = _fileName; + this.members = members; + + for (var i = 0, n = members.length; i < n; i++) { + members[i].parent = this; + } + } + ISyntaxList2.prototype.childCount = function () { + return this.members.length; + }; + + ISyntaxList2.prototype.childAt = function (index) { + return this.members[index]; + }; + + ISyntaxList2.prototype.fileName = function () { + return this._fileName; + }; + + ISyntaxList2.prototype.kind = function () { + return 1 /* List */; + }; + + ISyntaxList2.prototype.firstOrDefault = function (func) { + return TypeScript.ArrayUtilities.firstOrDefault(this.members, func); + }; + + ISyntaxList2.prototype.lastOrDefault = function (func) { + return TypeScript.ArrayUtilities.lastOrDefault(this.members, func); + }; + + ISyntaxList2.prototype.any = function (func) { + return TypeScript.ArrayUtilities.any(this.members, func); + }; + + ISyntaxList2.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && astArrayStructuralEquals(this.members, ast.members, includingPosition); + }; + return ISyntaxList2; + })(AST); + TypeScript.ISyntaxList2 = ISyntaxList2; + + var ISeparatedSyntaxList2 = (function (_super) { + __extends(ISeparatedSyntaxList2, _super); + function ISeparatedSyntaxList2(_fileName, members, _separatorCount) { + _super.call(this); + this._fileName = _fileName; + this.members = members; + this._separatorCount = _separatorCount; + + for (var i = 0, n = members.length; i < n; i++) { + members[i].parent = this; + } + } + ISeparatedSyntaxList2.prototype.nonSeparatorCount = function () { + return this.members.length; + }; + + ISeparatedSyntaxList2.prototype.separatorCount = function () { + return this._separatorCount; + }; + + ISeparatedSyntaxList2.prototype.nonSeparatorAt = function (index) { + return this.members[index]; + }; + + ISeparatedSyntaxList2.prototype.nonSeparatorIndexOf = function (ast) { + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + if (this.nonSeparatorAt(i) === ast) { + return i; + } + } + + return -1; + }; + + ISeparatedSyntaxList2.prototype.fileName = function () { + return this._fileName; + }; + + ISeparatedSyntaxList2.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + ISeparatedSyntaxList2.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && astArrayStructuralEquals(this.members, ast.members, includingPosition); + }; + return ISeparatedSyntaxList2; + })(AST); + TypeScript.ISeparatedSyntaxList2 = ISeparatedSyntaxList2; + + var SourceUnit = (function (_super) { + __extends(SourceUnit, _super); + function SourceUnit(moduleElements, endOfFileTokenLeadingComments, _fileName) { + _super.call(this); + this.moduleElements = moduleElements; + this.endOfFileTokenLeadingComments = endOfFileTokenLeadingComments; + this._fileName = _fileName; + moduleElements && (moduleElements.parent = this); + } + SourceUnit.prototype.fileName = function () { + return this._fileName; + }; + + SourceUnit.prototype.kind = function () { + return 120 /* SourceUnit */; + }; + + SourceUnit.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.moduleElements, ast.moduleElements, includingPosition); + }; + return SourceUnit; + })(AST); + TypeScript.SourceUnit = SourceUnit; + + var Identifier = (function (_super) { + __extends(Identifier, _super); + function Identifier(_text) { + _super.call(this); + this._text = _text; + this._valueText = null; + } + Identifier.prototype.text = function () { + return this._text; + }; + Identifier.prototype.valueText = function () { + if (!this._valueText) { + var text = this._text; + if (text === "__proto__") { + this._valueText = "#__proto__"; + } else { + this._valueText = TypeScript.Syntax.massageEscapes(text); + } + } + + return this._valueText; + }; + + Identifier.prototype.kind = function () { + return 11 /* IdentifierName */; + }; + + Identifier.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._text === ast._text; + }; + + Identifier.prototype.isExpression = function () { + return true; + }; + return Identifier; + })(AST); + TypeScript.Identifier = Identifier; + + var LiteralExpression = (function (_super) { + __extends(LiteralExpression, _super); + function LiteralExpression(_nodeType, _text, _valueText) { + _super.call(this); + this._nodeType = _nodeType; + this._text = _text; + this._valueText = _valueText; + } + LiteralExpression.prototype.text = function () { + return this._text; + }; + + LiteralExpression.prototype.valueText = function () { + return this._valueText; + }; + + LiteralExpression.prototype.kind = function () { + return this._nodeType; + }; + + LiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + LiteralExpression.prototype.isExpression = function () { + return true; + }; + return LiteralExpression; + })(AST); + TypeScript.LiteralExpression = LiteralExpression; + + var ThisExpression = (function (_super) { + __extends(ThisExpression, _super); + function ThisExpression(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + } + ThisExpression.prototype.text = function () { + return this._text; + }; + + ThisExpression.prototype.valueText = function () { + return this._valueText; + }; + + ThisExpression.prototype.kind = function () { + return 35 /* ThisKeyword */; + }; + + ThisExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + ThisExpression.prototype.isExpression = function () { + return true; + }; + return ThisExpression; + })(AST); + TypeScript.ThisExpression = ThisExpression; + + var SuperExpression = (function (_super) { + __extends(SuperExpression, _super); + function SuperExpression(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + } + SuperExpression.prototype.text = function () { + return this._text; + }; + + SuperExpression.prototype.valueText = function () { + return this._valueText; + }; + + SuperExpression.prototype.kind = function () { + return 50 /* SuperKeyword */; + }; + + SuperExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + SuperExpression.prototype.isExpression = function () { + return true; + }; + return SuperExpression; + })(AST); + TypeScript.SuperExpression = SuperExpression; + + var NumericLiteral = (function (_super) { + __extends(NumericLiteral, _super); + function NumericLiteral(_value, _text, _valueText) { + _super.call(this); + this._value = _value; + this._text = _text; + this._valueText = _valueText; + } + NumericLiteral.prototype.text = function () { + return this._text; + }; + NumericLiteral.prototype.valueText = function () { + return this._valueText; + }; + NumericLiteral.prototype.value = function () { + return this._value; + }; + + NumericLiteral.prototype.kind = function () { + return 13 /* NumericLiteral */; + }; + + NumericLiteral.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && (this._value === ast._value || (isNaN(this._value) && isNaN(ast._value))) && this._text === ast._text; + }; + + NumericLiteral.prototype.isExpression = function () { + return true; + }; + return NumericLiteral; + })(AST); + TypeScript.NumericLiteral = NumericLiteral; + + var RegularExpressionLiteral = (function (_super) { + __extends(RegularExpressionLiteral, _super); + function RegularExpressionLiteral(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + } + RegularExpressionLiteral.prototype.text = function () { + return this._text; + }; + + RegularExpressionLiteral.prototype.valueText = function () { + return this._valueText; + }; + + RegularExpressionLiteral.prototype.kind = function () { + return 12 /* RegularExpressionLiteral */; + }; + + RegularExpressionLiteral.prototype.isExpression = function () { + return true; + }; + return RegularExpressionLiteral; + })(AST); + TypeScript.RegularExpressionLiteral = RegularExpressionLiteral; + + var StringLiteral = (function (_super) { + __extends(StringLiteral, _super); + function StringLiteral(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + this._valueText = _valueText === "__proto__" ? "#__proto__" : _valueText; + } + StringLiteral.prototype.text = function () { + return this._text; + }; + StringLiteral.prototype.valueText = function () { + return this._valueText; + }; + + StringLiteral.prototype.kind = function () { + return 14 /* StringLiteral */; + }; + + StringLiteral.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._text === ast._text; + }; + + StringLiteral.prototype.isExpression = function () { + return true; + }; + return StringLiteral; + })(AST); + TypeScript.StringLiteral = StringLiteral; + + var TypeAnnotation = (function (_super) { + __extends(TypeAnnotation, _super); + function TypeAnnotation(type) { + _super.call(this); + this.type = type; + type && (type.parent = this); + } + TypeAnnotation.prototype.kind = function () { + return 244 /* TypeAnnotation */; + }; + return TypeAnnotation; + })(AST); + TypeScript.TypeAnnotation = TypeAnnotation; + + var BuiltInType = (function (_super) { + __extends(BuiltInType, _super); + function BuiltInType(_nodeType, _text, _valueText) { + _super.call(this); + this._nodeType = _nodeType; + this._text = _text; + this._valueText = _valueText; + } + BuiltInType.prototype.text = function () { + return this._text; + }; + + BuiltInType.prototype.valueText = function () { + return this._valueText; + }; + + BuiltInType.prototype.kind = function () { + return this._nodeType; + }; + return BuiltInType; + })(AST); + TypeScript.BuiltInType = BuiltInType; + + var ExternalModuleReference = (function (_super) { + __extends(ExternalModuleReference, _super); + function ExternalModuleReference(stringLiteral) { + _super.call(this); + this.stringLiteral = stringLiteral; + stringLiteral && (stringLiteral.parent = this); + } + ExternalModuleReference.prototype.kind = function () { + return 245 /* ExternalModuleReference */; + }; + return ExternalModuleReference; + })(AST); + TypeScript.ExternalModuleReference = ExternalModuleReference; + + var ModuleNameModuleReference = (function (_super) { + __extends(ModuleNameModuleReference, _super); + function ModuleNameModuleReference(moduleName) { + _super.call(this); + this.moduleName = moduleName; + moduleName && (moduleName.parent = this); + } + ModuleNameModuleReference.prototype.kind = function () { + return 246 /* ModuleNameModuleReference */; + }; + return ModuleNameModuleReference; + })(AST); + TypeScript.ModuleNameModuleReference = ModuleNameModuleReference; + + var ImportDeclaration = (function (_super) { + __extends(ImportDeclaration, _super); + function ImportDeclaration(modifiers, identifier, moduleReference) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.moduleReference = moduleReference; + identifier && (identifier.parent = this); + moduleReference && (moduleReference.parent = this); + } + ImportDeclaration.prototype.kind = function () { + return 133 /* ImportDeclaration */; + }; + + ImportDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.moduleReference, ast.moduleReference, includingPosition); + }; + return ImportDeclaration; + })(AST); + TypeScript.ImportDeclaration = ImportDeclaration; + + var ExportAssignment = (function (_super) { + __extends(ExportAssignment, _super); + function ExportAssignment(identifier) { + _super.call(this); + this.identifier = identifier; + identifier && (identifier.parent = this); + } + ExportAssignment.prototype.kind = function () { + return 134 /* ExportAssignment */; + }; + + ExportAssignment.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition); + }; + return ExportAssignment; + })(AST); + TypeScript.ExportAssignment = ExportAssignment; + + var TypeParameterList = (function (_super) { + __extends(TypeParameterList, _super); + function TypeParameterList(typeParameters) { + _super.call(this); + this.typeParameters = typeParameters; + typeParameters && (typeParameters.parent = this); + } + TypeParameterList.prototype.kind = function () { + return 229 /* TypeParameterList */; + }; + return TypeParameterList; + })(AST); + TypeScript.TypeParameterList = TypeParameterList; + + var ClassDeclaration = (function (_super) { + __extends(ClassDeclaration, _super); + function ClassDeclaration(modifiers, identifier, typeParameterList, heritageClauses, classElements, closeBraceToken) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.classElements = classElements; + this.closeBraceToken = closeBraceToken; + identifier && (identifier.parent = this); + typeParameterList && (typeParameterList.parent = this); + heritageClauses && (heritageClauses.parent = this); + classElements && (classElements.parent = this); + } + ClassDeclaration.prototype.kind = function () { + return 131 /* ClassDeclaration */; + }; + + ClassDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.classElements, ast.classElements, includingPosition) && structuralEquals(this.typeParameterList, ast.typeParameterList, includingPosition) && structuralEquals(this.heritageClauses, ast.heritageClauses, includingPosition); + }; + return ClassDeclaration; + })(AST); + TypeScript.ClassDeclaration = ClassDeclaration; + + var InterfaceDeclaration = (function (_super) { + __extends(InterfaceDeclaration, _super); + function InterfaceDeclaration(modifiers, identifier, typeParameterList, heritageClauses, body) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.body = body; + identifier && (identifier.parent = this); + typeParameterList && (typeParameterList.parent = this); + body && (body.parent = this); + heritageClauses && (heritageClauses.parent = this); + } + InterfaceDeclaration.prototype.kind = function () { + return 128 /* InterfaceDeclaration */; + }; + + InterfaceDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.body, ast.body, includingPosition) && structuralEquals(this.typeParameterList, ast.typeParameterList, includingPosition) && structuralEquals(this.heritageClauses, ast.heritageClauses, includingPosition); + }; + return InterfaceDeclaration; + })(AST); + TypeScript.InterfaceDeclaration = InterfaceDeclaration; + + var HeritageClause = (function (_super) { + __extends(HeritageClause, _super); + function HeritageClause(_nodeType, typeNames) { + _super.call(this); + this._nodeType = _nodeType; + this.typeNames = typeNames; + typeNames && (typeNames.parent = this); + } + HeritageClause.prototype.kind = function () { + return this._nodeType; + }; + + HeritageClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.typeNames, ast.typeNames, includingPosition); + }; + return HeritageClause; + })(AST); + TypeScript.HeritageClause = HeritageClause; + + var ModuleDeclaration = (function (_super) { + __extends(ModuleDeclaration, _super); + function ModuleDeclaration(modifiers, name, stringLiteral, moduleElements, endingToken) { + _super.call(this); + this.modifiers = modifiers; + this.name = name; + this.stringLiteral = stringLiteral; + this.moduleElements = moduleElements; + this.endingToken = endingToken; + name && (name.parent = this); + stringLiteral && (stringLiteral.parent = this); + moduleElements && (moduleElements.parent = this); + } + ModuleDeclaration.prototype.kind = function () { + return 130 /* ModuleDeclaration */; + }; + + ModuleDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.moduleElements, ast.moduleElements, includingPosition); + }; + return ModuleDeclaration; + })(AST); + TypeScript.ModuleDeclaration = ModuleDeclaration; + + var FunctionDeclaration = (function (_super) { + __extends(FunctionDeclaration, _super); + function FunctionDeclaration(modifiers, identifier, callSignature, block) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + identifier && (identifier.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + FunctionDeclaration.prototype.kind = function () { + return 129 /* FunctionDeclaration */; + }; + + FunctionDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.block, ast.block, includingPosition) && structuralEquals(this.callSignature, ast.callSignature, includingPosition); + }; + return FunctionDeclaration; + })(AST); + TypeScript.FunctionDeclaration = FunctionDeclaration; + + var VariableStatement = (function (_super) { + __extends(VariableStatement, _super); + function VariableStatement(modifiers, declaration) { + _super.call(this); + this.modifiers = modifiers; + this.declaration = declaration; + declaration && (declaration.parent = this); + } + VariableStatement.prototype.kind = function () { + return 148 /* VariableStatement */; + }; + + VariableStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.declaration, ast.declaration, includingPosition); + }; + return VariableStatement; + })(AST); + TypeScript.VariableStatement = VariableStatement; + + var VariableDeclaration = (function (_super) { + __extends(VariableDeclaration, _super); + function VariableDeclaration(declarators) { + _super.call(this); + this.declarators = declarators; + declarators && (declarators.parent = this); + } + VariableDeclaration.prototype.kind = function () { + return 224 /* VariableDeclaration */; + }; + + VariableDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.declarators, ast.declarators, includingPosition); + }; + return VariableDeclaration; + })(AST); + TypeScript.VariableDeclaration = VariableDeclaration; + + var VariableDeclarator = (function (_super) { + __extends(VariableDeclarator, _super); + function VariableDeclarator(propertyName, typeAnnotation, equalsValueClause) { + _super.call(this); + this.propertyName = propertyName; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + propertyName && (propertyName.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + equalsValueClause && (equalsValueClause.parent = this); + } + VariableDeclarator.prototype.kind = function () { + return 225 /* VariableDeclarator */; + }; + return VariableDeclarator; + })(AST); + TypeScript.VariableDeclarator = VariableDeclarator; + + var EqualsValueClause = (function (_super) { + __extends(EqualsValueClause, _super); + function EqualsValueClause(value) { + _super.call(this); + this.value = value; + value && (value.parent = this); + } + EqualsValueClause.prototype.kind = function () { + return 232 /* EqualsValueClause */; + }; + return EqualsValueClause; + })(AST); + TypeScript.EqualsValueClause = EqualsValueClause; + + var PrefixUnaryExpression = (function (_super) { + __extends(PrefixUnaryExpression, _super); + function PrefixUnaryExpression(_nodeType, operand) { + _super.call(this); + this._nodeType = _nodeType; + this.operand = operand; + operand && (operand.parent = this); + } + PrefixUnaryExpression.prototype.kind = function () { + return this._nodeType; + }; + + PrefixUnaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand, ast.operand, includingPosition); + }; + + PrefixUnaryExpression.prototype.isExpression = function () { + return true; + }; + return PrefixUnaryExpression; + })(AST); + TypeScript.PrefixUnaryExpression = PrefixUnaryExpression; + + var ArrayLiteralExpression = (function (_super) { + __extends(ArrayLiteralExpression, _super); + function ArrayLiteralExpression(expressions) { + _super.call(this); + this.expressions = expressions; + expressions && (expressions.parent = this); + } + ArrayLiteralExpression.prototype.kind = function () { + return 214 /* ArrayLiteralExpression */; + }; + + ArrayLiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expressions, ast.expressions, includingPosition); + }; + + ArrayLiteralExpression.prototype.isExpression = function () { + return true; + }; + return ArrayLiteralExpression; + })(AST); + TypeScript.ArrayLiteralExpression = ArrayLiteralExpression; + + var OmittedExpression = (function (_super) { + __extends(OmittedExpression, _super); + function OmittedExpression() { + _super.apply(this, arguments); + } + OmittedExpression.prototype.kind = function () { + return 223 /* OmittedExpression */; + }; + + OmittedExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + OmittedExpression.prototype.isExpression = function () { + return true; + }; + return OmittedExpression; + })(AST); + TypeScript.OmittedExpression = OmittedExpression; + + var ParenthesizedExpression = (function (_super) { + __extends(ParenthesizedExpression, _super); + function ParenthesizedExpression(openParenTrailingComments, expression) { + _super.call(this); + this.openParenTrailingComments = openParenTrailingComments; + this.expression = expression; + expression && (expression.parent = this); + } + ParenthesizedExpression.prototype.kind = function () { + return 217 /* ParenthesizedExpression */; + }; + + ParenthesizedExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + ParenthesizedExpression.prototype.isExpression = function () { + return true; + }; + return ParenthesizedExpression; + })(AST); + TypeScript.ParenthesizedExpression = ParenthesizedExpression; + + var SimpleArrowFunctionExpression = (function (_super) { + __extends(SimpleArrowFunctionExpression, _super); + function SimpleArrowFunctionExpression(identifier, block, expression) { + _super.call(this); + this.identifier = identifier; + this.block = block; + this.expression = expression; + identifier && (identifier.parent = this); + block && (block.parent = this); + expression && (expression.parent = this); + } + SimpleArrowFunctionExpression.prototype.kind = function () { + return 219 /* SimpleArrowFunctionExpression */; + }; + + SimpleArrowFunctionExpression.prototype.isExpression = function () { + return true; + }; + return SimpleArrowFunctionExpression; + })(AST); + TypeScript.SimpleArrowFunctionExpression = SimpleArrowFunctionExpression; + + var ParenthesizedArrowFunctionExpression = (function (_super) { + __extends(ParenthesizedArrowFunctionExpression, _super); + function ParenthesizedArrowFunctionExpression(callSignature, block, expression) { + _super.call(this); + this.callSignature = callSignature; + this.block = block; + this.expression = expression; + callSignature && (callSignature.parent = this); + block && (block.parent = this); + expression && (expression.parent = this); + } + ParenthesizedArrowFunctionExpression.prototype.kind = function () { + return 218 /* ParenthesizedArrowFunctionExpression */; + }; + + ParenthesizedArrowFunctionExpression.prototype.isExpression = function () { + return true; + }; + return ParenthesizedArrowFunctionExpression; + })(AST); + TypeScript.ParenthesizedArrowFunctionExpression = ParenthesizedArrowFunctionExpression; + + var QualifiedName = (function (_super) { + __extends(QualifiedName, _super); + function QualifiedName(left, right) { + _super.call(this); + this.left = left; + this.right = right; + left && (left.parent = this); + right && (right.parent = this); + } + QualifiedName.prototype.kind = function () { + return 121 /* QualifiedName */; + }; + + QualifiedName.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.left, ast.left, includingPosition) && structuralEquals(this.right, ast.right, includingPosition); + }; + return QualifiedName; + })(AST); + TypeScript.QualifiedName = QualifiedName; + + var ParameterList = (function (_super) { + __extends(ParameterList, _super); + function ParameterList(openParenTrailingComments, parameters) { + _super.call(this); + this.openParenTrailingComments = openParenTrailingComments; + this.parameters = parameters; + parameters && (parameters.parent = this); + } + ParameterList.prototype.kind = function () { + return 227 /* ParameterList */; + }; + return ParameterList; + })(AST); + TypeScript.ParameterList = ParameterList; + + var ConstructorType = (function (_super) { + __extends(ConstructorType, _super); + function ConstructorType(typeParameterList, parameterList, type) { + _super.call(this); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.type = type; + typeParameterList && (typeParameterList.parent = this); + parameterList && (parameterList.parent = this); + type && (type.parent = this); + } + ConstructorType.prototype.kind = function () { + return 125 /* ConstructorType */; + }; + return ConstructorType; + })(AST); + TypeScript.ConstructorType = ConstructorType; + + var FunctionType = (function (_super) { + __extends(FunctionType, _super); + function FunctionType(typeParameterList, parameterList, type) { + _super.call(this); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.type = type; + typeParameterList && (typeParameterList.parent = this); + parameterList && (parameterList.parent = this); + type && (type.parent = this); + } + FunctionType.prototype.kind = function () { + return 123 /* FunctionType */; + }; + return FunctionType; + })(AST); + TypeScript.FunctionType = FunctionType; + + var ObjectType = (function (_super) { + __extends(ObjectType, _super); + function ObjectType(typeMembers) { + _super.call(this); + this.typeMembers = typeMembers; + typeMembers && (typeMembers.parent = this); + } + ObjectType.prototype.kind = function () { + return 122 /* ObjectType */; + }; + + ObjectType.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.typeMembers, ast.typeMembers, includingPosition); + }; + return ObjectType; + })(AST); + TypeScript.ObjectType = ObjectType; + + var ArrayType = (function (_super) { + __extends(ArrayType, _super); + function ArrayType(type) { + _super.call(this); + this.type = type; + type && (type.parent = this); + } + ArrayType.prototype.kind = function () { + return 124 /* ArrayType */; + }; + + ArrayType.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.type, ast.type, includingPosition); + }; + return ArrayType; + })(AST); + TypeScript.ArrayType = ArrayType; + + var TypeArgumentList = (function (_super) { + __extends(TypeArgumentList, _super); + function TypeArgumentList(typeArguments) { + _super.call(this); + this.typeArguments = typeArguments; + typeArguments && (typeArguments.parent = this); + } + TypeArgumentList.prototype.kind = function () { + return 228 /* TypeArgumentList */; + }; + return TypeArgumentList; + })(AST); + TypeScript.TypeArgumentList = TypeArgumentList; + + var GenericType = (function (_super) { + __extends(GenericType, _super); + function GenericType(name, typeArgumentList) { + _super.call(this); + this.name = name; + this.typeArgumentList = typeArgumentList; + name && (name.parent = this); + typeArgumentList && (typeArgumentList.parent = this); + } + GenericType.prototype.kind = function () { + return 126 /* GenericType */; + }; + + GenericType.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.typeArgumentList, ast.typeArgumentList, includingPosition); + }; + return GenericType; + })(AST); + TypeScript.GenericType = GenericType; + + var TypeQuery = (function (_super) { + __extends(TypeQuery, _super); + function TypeQuery(name) { + _super.call(this); + this.name = name; + name && (name.parent = this); + } + TypeQuery.prototype.kind = function () { + return 127 /* TypeQuery */; + }; + + TypeQuery.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition); + }; + return TypeQuery; + })(AST); + TypeScript.TypeQuery = TypeQuery; + + var Block = (function (_super) { + __extends(Block, _super); + function Block(statements, closeBraceLeadingComments, closeBraceToken) { + _super.call(this); + this.statements = statements; + this.closeBraceLeadingComments = closeBraceLeadingComments; + this.closeBraceToken = closeBraceToken; + statements && (statements.parent = this); + } + Block.prototype.kind = function () { + return 146 /* Block */; + }; + + Block.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statements, ast.statements, includingPosition); + }; + return Block; + })(AST); + TypeScript.Block = Block; + + var Parameter = (function (_super) { + __extends(Parameter, _super); + function Parameter(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + _super.call(this); + this.dotDotDotToken = dotDotDotToken; + this.modifiers = modifiers; + this.identifier = identifier; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + identifier && (identifier.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + equalsValueClause && (equalsValueClause.parent = this); + } + Parameter.prototype.kind = function () { + return 242 /* Parameter */; + }; + return Parameter; + })(AST); + TypeScript.Parameter = Parameter; + + var MemberAccessExpression = (function (_super) { + __extends(MemberAccessExpression, _super); + function MemberAccessExpression(expression, name) { + _super.call(this); + this.expression = expression; + this.name = name; + expression && (expression.parent = this); + name && (name.parent = this); + } + MemberAccessExpression.prototype.kind = function () { + return 212 /* MemberAccessExpression */; + }; + + MemberAccessExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.name, ast.name, includingPosition); + }; + + MemberAccessExpression.prototype.isExpression = function () { + return true; + }; + return MemberAccessExpression; + })(AST); + TypeScript.MemberAccessExpression = MemberAccessExpression; + + var PostfixUnaryExpression = (function (_super) { + __extends(PostfixUnaryExpression, _super); + function PostfixUnaryExpression(_nodeType, operand) { + _super.call(this); + this._nodeType = _nodeType; + this.operand = operand; + operand && (operand.parent = this); + } + PostfixUnaryExpression.prototype.kind = function () { + return this._nodeType; + }; + + PostfixUnaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand, ast.operand, includingPosition); + }; + + PostfixUnaryExpression.prototype.isExpression = function () { + return true; + }; + return PostfixUnaryExpression; + })(AST); + TypeScript.PostfixUnaryExpression = PostfixUnaryExpression; + + var ElementAccessExpression = (function (_super) { + __extends(ElementAccessExpression, _super); + function ElementAccessExpression(expression, argumentExpression) { + _super.call(this); + this.expression = expression; + this.argumentExpression = argumentExpression; + expression && (expression.parent = this); + argumentExpression && (argumentExpression.parent = this); + } + ElementAccessExpression.prototype.kind = function () { + return 221 /* ElementAccessExpression */; + }; + + ElementAccessExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentExpression, ast.argumentExpression, includingPosition); + }; + + ElementAccessExpression.prototype.isExpression = function () { + return true; + }; + return ElementAccessExpression; + })(AST); + TypeScript.ElementAccessExpression = ElementAccessExpression; + + var InvocationExpression = (function (_super) { + __extends(InvocationExpression, _super); + function InvocationExpression(expression, argumentList) { + _super.call(this); + this.expression = expression; + this.argumentList = argumentList; + expression && (expression.parent = this); + argumentList && (argumentList.parent = this); + } + InvocationExpression.prototype.kind = function () { + return 213 /* InvocationExpression */; + }; + + InvocationExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentList, ast.argumentList, includingPosition); + }; + + InvocationExpression.prototype.isExpression = function () { + return true; + }; + return InvocationExpression; + })(AST); + TypeScript.InvocationExpression = InvocationExpression; + + var ArgumentList = (function (_super) { + __extends(ArgumentList, _super); + function ArgumentList(typeArgumentList, _arguments, closeParenToken) { + _super.call(this); + this.typeArgumentList = typeArgumentList; + this.closeParenToken = closeParenToken; + this.arguments = _arguments; + + typeArgumentList && (typeArgumentList.parent = this); + _arguments && (_arguments.parent = this); + } + ArgumentList.prototype.kind = function () { + return 226 /* ArgumentList */; + }; + return ArgumentList; + })(AST); + TypeScript.ArgumentList = ArgumentList; + + var BinaryExpression = (function (_super) { + __extends(BinaryExpression, _super); + function BinaryExpression(_nodeType, left, right) { + _super.call(this); + this._nodeType = _nodeType; + this.left = left; + this.right = right; + left && (left.parent = this); + right && (right.parent = this); + } + BinaryExpression.prototype.kind = function () { + return this._nodeType; + }; + + BinaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.left, ast.left, includingPosition) && structuralEquals(this.right, ast.right, includingPosition); + }; + + BinaryExpression.prototype.isExpression = function () { + return true; + }; + return BinaryExpression; + })(AST); + TypeScript.BinaryExpression = BinaryExpression; + + var ConditionalExpression = (function (_super) { + __extends(ConditionalExpression, _super); + function ConditionalExpression(condition, whenTrue, whenFalse) { + _super.call(this); + this.condition = condition; + this.whenTrue = whenTrue; + this.whenFalse = whenFalse; + condition && (condition.parent = this); + whenTrue && (whenTrue.parent = this); + whenFalse && (whenFalse.parent = this); + } + ConditionalExpression.prototype.kind = function () { + return 186 /* ConditionalExpression */; + }; + + ConditionalExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.whenTrue, ast.whenTrue, includingPosition) && structuralEquals(this.whenFalse, ast.whenFalse, includingPosition); + }; + + ConditionalExpression.prototype.isExpression = function () { + return true; + }; + return ConditionalExpression; + })(AST); + TypeScript.ConditionalExpression = ConditionalExpression; + + var ConstructSignature = (function (_super) { + __extends(ConstructSignature, _super); + function ConstructSignature(callSignature) { + _super.call(this); + this.callSignature = callSignature; + callSignature && (callSignature.parent = this); + } + ConstructSignature.prototype.kind = function () { + return 143 /* ConstructSignature */; + }; + return ConstructSignature; + })(AST); + TypeScript.ConstructSignature = ConstructSignature; + + var MethodSignature = (function (_super) { + __extends(MethodSignature, _super); + function MethodSignature(propertyName, questionToken, callSignature) { + _super.call(this); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.callSignature = callSignature; + propertyName && (propertyName.parent = this); + callSignature && (callSignature.parent = this); + } + MethodSignature.prototype.kind = function () { + return 145 /* MethodSignature */; + }; + return MethodSignature; + })(AST); + TypeScript.MethodSignature = MethodSignature; + + var IndexSignature = (function (_super) { + __extends(IndexSignature, _super); + function IndexSignature(parameter, typeAnnotation) { + _super.call(this); + this.parameter = parameter; + this.typeAnnotation = typeAnnotation; + parameter && (parameter.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + } + IndexSignature.prototype.kind = function () { + return 144 /* IndexSignature */; + }; + return IndexSignature; + })(AST); + TypeScript.IndexSignature = IndexSignature; + + var PropertySignature = (function (_super) { + __extends(PropertySignature, _super); + function PropertySignature(propertyName, questionToken, typeAnnotation) { + _super.call(this); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + propertyName && (propertyName.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + } + PropertySignature.prototype.kind = function () { + return 141 /* PropertySignature */; + }; + return PropertySignature; + })(AST); + TypeScript.PropertySignature = PropertySignature; + + var CallSignature = (function (_super) { + __extends(CallSignature, _super); + function CallSignature(typeParameterList, parameterList, typeAnnotation) { + _super.call(this); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + typeParameterList && (typeParameterList.parent = this); + parameterList && (parameterList.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + } + CallSignature.prototype.kind = function () { + return 142 /* CallSignature */; + }; + return CallSignature; + })(AST); + TypeScript.CallSignature = CallSignature; + + var TypeParameter = (function (_super) { + __extends(TypeParameter, _super); + function TypeParameter(identifier, constraint) { + _super.call(this); + this.identifier = identifier; + this.constraint = constraint; + identifier && (identifier.parent = this); + constraint && (constraint.parent = this); + } + TypeParameter.prototype.kind = function () { + return 238 /* TypeParameter */; + }; + + TypeParameter.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.constraint, ast.constraint, includingPosition); + }; + return TypeParameter; + })(AST); + TypeScript.TypeParameter = TypeParameter; + + var Constraint = (function (_super) { + __extends(Constraint, _super); + function Constraint(type) { + _super.call(this); + this.type = type; + type && (type.parent = this); + } + Constraint.prototype.kind = function () { + return 239 /* Constraint */; + }; + return Constraint; + })(AST); + TypeScript.Constraint = Constraint; + + var ElseClause = (function (_super) { + __extends(ElseClause, _super); + function ElseClause(statement) { + _super.call(this); + this.statement = statement; + statement && (statement.parent = this); + } + ElseClause.prototype.kind = function () { + return 235 /* ElseClause */; + }; + + ElseClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return ElseClause; + })(AST); + TypeScript.ElseClause = ElseClause; + + var IfStatement = (function (_super) { + __extends(IfStatement, _super); + function IfStatement(condition, statement, elseClause) { + _super.call(this); + this.condition = condition; + this.statement = statement; + this.elseClause = elseClause; + condition && (condition.parent = this); + statement && (statement.parent = this); + elseClause && (elseClause.parent = this); + } + IfStatement.prototype.kind = function () { + return 147 /* IfStatement */; + }; + + IfStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition) && structuralEquals(this.elseClause, ast.elseClause, includingPosition); + }; + return IfStatement; + })(AST); + TypeScript.IfStatement = IfStatement; + + var ExpressionStatement = (function (_super) { + __extends(ExpressionStatement, _super); + function ExpressionStatement(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + ExpressionStatement.prototype.kind = function () { + return 149 /* ExpressionStatement */; + }; + + ExpressionStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ExpressionStatement; + })(AST); + TypeScript.ExpressionStatement = ExpressionStatement; + + var ConstructorDeclaration = (function (_super) { + __extends(ConstructorDeclaration, _super); + function ConstructorDeclaration(callSignature, block) { + _super.call(this); + this.callSignature = callSignature; + this.block = block; + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + ConstructorDeclaration.prototype.kind = function () { + return 137 /* ConstructorDeclaration */; + }; + return ConstructorDeclaration; + })(AST); + TypeScript.ConstructorDeclaration = ConstructorDeclaration; + + var MemberFunctionDeclaration = (function (_super) { + __extends(MemberFunctionDeclaration, _super); + function MemberFunctionDeclaration(modifiers, propertyName, callSignature, block) { + _super.call(this); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + propertyName && (propertyName.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + MemberFunctionDeclaration.prototype.kind = function () { + return 135 /* MemberFunctionDeclaration */; + }; + return MemberFunctionDeclaration; + })(AST); + TypeScript.MemberFunctionDeclaration = MemberFunctionDeclaration; + + var GetAccessor = (function (_super) { + __extends(GetAccessor, _super); + function GetAccessor(modifiers, propertyName, parameterList, typeAnnotation, block) { + _super.call(this); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + this.block = block; + propertyName && (propertyName.parent = this); + parameterList && (parameterList.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + block && (block.parent = this); + } + GetAccessor.prototype.kind = function () { + return 139 /* GetAccessor */; + }; + return GetAccessor; + })(AST); + TypeScript.GetAccessor = GetAccessor; + + var SetAccessor = (function (_super) { + __extends(SetAccessor, _super); + function SetAccessor(modifiers, propertyName, parameterList, block) { + _super.call(this); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.block = block; + propertyName && (propertyName.parent = this); + parameterList && (parameterList.parent = this); + block && (block.parent = this); + } + SetAccessor.prototype.kind = function () { + return 140 /* SetAccessor */; + }; + return SetAccessor; + })(AST); + TypeScript.SetAccessor = SetAccessor; + + var MemberVariableDeclaration = (function (_super) { + __extends(MemberVariableDeclaration, _super); + function MemberVariableDeclaration(modifiers, variableDeclarator) { + _super.call(this); + this.modifiers = modifiers; + this.variableDeclarator = variableDeclarator; + variableDeclarator && (variableDeclarator.parent = this); + } + MemberVariableDeclaration.prototype.kind = function () { + return 136 /* MemberVariableDeclaration */; + }; + return MemberVariableDeclaration; + })(AST); + TypeScript.MemberVariableDeclaration = MemberVariableDeclaration; + + var IndexMemberDeclaration = (function (_super) { + __extends(IndexMemberDeclaration, _super); + function IndexMemberDeclaration(indexSignature) { + _super.call(this); + this.indexSignature = indexSignature; + indexSignature && (indexSignature.parent = this); + } + IndexMemberDeclaration.prototype.kind = function () { + return 138 /* IndexMemberDeclaration */; + }; + return IndexMemberDeclaration; + })(AST); + TypeScript.IndexMemberDeclaration = IndexMemberDeclaration; + + var ThrowStatement = (function (_super) { + __extends(ThrowStatement, _super); + function ThrowStatement(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + ThrowStatement.prototype.kind = function () { + return 157 /* ThrowStatement */; + }; + + ThrowStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ThrowStatement; + })(AST); + TypeScript.ThrowStatement = ThrowStatement; + + var ReturnStatement = (function (_super) { + __extends(ReturnStatement, _super); + function ReturnStatement(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + ReturnStatement.prototype.kind = function () { + return 150 /* ReturnStatement */; + }; + + ReturnStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ReturnStatement; + })(AST); + TypeScript.ReturnStatement = ReturnStatement; + + var ObjectCreationExpression = (function (_super) { + __extends(ObjectCreationExpression, _super); + function ObjectCreationExpression(expression, argumentList) { + _super.call(this); + this.expression = expression; + this.argumentList = argumentList; + expression && (expression.parent = this); + argumentList && (argumentList.parent = this); + } + ObjectCreationExpression.prototype.kind = function () { + return 216 /* ObjectCreationExpression */; + }; + + ObjectCreationExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentList, ast.argumentList, includingPosition); + }; + + ObjectCreationExpression.prototype.isExpression = function () { + return true; + }; + return ObjectCreationExpression; + })(AST); + TypeScript.ObjectCreationExpression = ObjectCreationExpression; + + var SwitchStatement = (function (_super) { + __extends(SwitchStatement, _super); + function SwitchStatement(expression, closeParenToken, switchClauses) { + _super.call(this); + this.expression = expression; + this.closeParenToken = closeParenToken; + this.switchClauses = switchClauses; + expression && (expression.parent = this); + switchClauses && (switchClauses.parent = this); + } + SwitchStatement.prototype.kind = function () { + return 151 /* SwitchStatement */; + }; + + SwitchStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.switchClauses, ast.switchClauses, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return SwitchStatement; + })(AST); + TypeScript.SwitchStatement = SwitchStatement; + + var CaseSwitchClause = (function (_super) { + __extends(CaseSwitchClause, _super); + function CaseSwitchClause(expression, statements) { + _super.call(this); + this.expression = expression; + this.statements = statements; + expression && (expression.parent = this); + statements && (statements.parent = this); + } + CaseSwitchClause.prototype.kind = function () { + return 233 /* CaseSwitchClause */; + }; + + CaseSwitchClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.statements, ast.statements, includingPosition); + }; + return CaseSwitchClause; + })(AST); + TypeScript.CaseSwitchClause = CaseSwitchClause; + + var DefaultSwitchClause = (function (_super) { + __extends(DefaultSwitchClause, _super); + function DefaultSwitchClause(statements) { + _super.call(this); + this.statements = statements; + statements && (statements.parent = this); + } + DefaultSwitchClause.prototype.kind = function () { + return 234 /* DefaultSwitchClause */; + }; + + DefaultSwitchClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statements, ast.statements, includingPosition); + }; + return DefaultSwitchClause; + })(AST); + TypeScript.DefaultSwitchClause = DefaultSwitchClause; + + var BreakStatement = (function (_super) { + __extends(BreakStatement, _super); + function BreakStatement(identifier) { + _super.call(this); + this.identifier = identifier; + } + BreakStatement.prototype.kind = function () { + return 152 /* BreakStatement */; + }; + + BreakStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return BreakStatement; + })(AST); + TypeScript.BreakStatement = BreakStatement; + + var ContinueStatement = (function (_super) { + __extends(ContinueStatement, _super); + function ContinueStatement(identifier) { + _super.call(this); + this.identifier = identifier; + } + ContinueStatement.prototype.kind = function () { + return 153 /* ContinueStatement */; + }; + + ContinueStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return ContinueStatement; + })(AST); + TypeScript.ContinueStatement = ContinueStatement; + + var ForStatement = (function (_super) { + __extends(ForStatement, _super); + function ForStatement(variableDeclaration, initializer, condition, incrementor, statement) { + _super.call(this); + this.variableDeclaration = variableDeclaration; + this.initializer = initializer; + this.condition = condition; + this.incrementor = incrementor; + this.statement = statement; + variableDeclaration && (variableDeclaration.parent = this); + initializer && (initializer.parent = this); + condition && (condition.parent = this); + incrementor && (incrementor.parent = this); + statement && (statement.parent = this); + } + ForStatement.prototype.kind = function () { + return 154 /* ForStatement */; + }; + + ForStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.initializer, ast.initializer, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.incrementor, ast.incrementor, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return ForStatement; + })(AST); + TypeScript.ForStatement = ForStatement; + + var ForInStatement = (function (_super) { + __extends(ForInStatement, _super); + function ForInStatement(variableDeclaration, left, expression, statement) { + _super.call(this); + this.variableDeclaration = variableDeclaration; + this.left = left; + this.expression = expression; + this.statement = statement; + variableDeclaration && (variableDeclaration.parent = this); + left && (left.parent = this); + expression && (expression.parent = this); + statement && (statement.parent = this); + } + ForInStatement.prototype.kind = function () { + return 155 /* ForInStatement */; + }; + + ForInStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.variableDeclaration, ast.variableDeclaration, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return ForInStatement; + })(AST); + TypeScript.ForInStatement = ForInStatement; + + var WhileStatement = (function (_super) { + __extends(WhileStatement, _super); + function WhileStatement(condition, statement) { + _super.call(this); + this.condition = condition; + this.statement = statement; + condition && (condition.parent = this); + statement && (statement.parent = this); + } + WhileStatement.prototype.kind = function () { + return 158 /* WhileStatement */; + }; + + WhileStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return WhileStatement; + })(AST); + TypeScript.WhileStatement = WhileStatement; + + var WithStatement = (function (_super) { + __extends(WithStatement, _super); + function WithStatement(condition, statement) { + _super.call(this); + this.condition = condition; + this.statement = statement; + condition && (condition.parent = this); + statement && (statement.parent = this); + } + WithStatement.prototype.kind = function () { + return 163 /* WithStatement */; + }; + + WithStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return WithStatement; + })(AST); + TypeScript.WithStatement = WithStatement; + + var EnumDeclaration = (function (_super) { + __extends(EnumDeclaration, _super); + function EnumDeclaration(modifiers, identifier, enumElements) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.enumElements = enumElements; + identifier && (identifier.parent = this); + enumElements && (enumElements.parent = this); + } + EnumDeclaration.prototype.kind = function () { + return 132 /* EnumDeclaration */; + }; + return EnumDeclaration; + })(AST); + TypeScript.EnumDeclaration = EnumDeclaration; + + var EnumElement = (function (_super) { + __extends(EnumElement, _super); + function EnumElement(propertyName, equalsValueClause) { + _super.call(this); + this.propertyName = propertyName; + this.equalsValueClause = equalsValueClause; + propertyName && (propertyName.parent = this); + equalsValueClause && (equalsValueClause.parent = this); + } + EnumElement.prototype.kind = function () { + return 243 /* EnumElement */; + }; + return EnumElement; + })(AST); + TypeScript.EnumElement = EnumElement; + + var CastExpression = (function (_super) { + __extends(CastExpression, _super); + function CastExpression(type, expression) { + _super.call(this); + this.type = type; + this.expression = expression; + type && (type.parent = this); + expression && (expression.parent = this); + } + CastExpression.prototype.kind = function () { + return 220 /* CastExpression */; + }; + + CastExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.type, ast.type, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + CastExpression.prototype.isExpression = function () { + return true; + }; + return CastExpression; + })(AST); + TypeScript.CastExpression = CastExpression; + + var ObjectLiteralExpression = (function (_super) { + __extends(ObjectLiteralExpression, _super); + function ObjectLiteralExpression(propertyAssignments) { + _super.call(this); + this.propertyAssignments = propertyAssignments; + propertyAssignments && (propertyAssignments.parent = this); + } + ObjectLiteralExpression.prototype.kind = function () { + return 215 /* ObjectLiteralExpression */; + }; + + ObjectLiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.propertyAssignments, ast.propertyAssignments, includingPosition); + }; + + ObjectLiteralExpression.prototype.isExpression = function () { + return true; + }; + return ObjectLiteralExpression; + })(AST); + TypeScript.ObjectLiteralExpression = ObjectLiteralExpression; + + var SimplePropertyAssignment = (function (_super) { + __extends(SimplePropertyAssignment, _super); + function SimplePropertyAssignment(propertyName, expression) { + _super.call(this); + this.propertyName = propertyName; + this.expression = expression; + propertyName && (propertyName.parent = this); + expression && (expression.parent = this); + } + SimplePropertyAssignment.prototype.kind = function () { + return 240 /* SimplePropertyAssignment */; + }; + return SimplePropertyAssignment; + })(AST); + TypeScript.SimplePropertyAssignment = SimplePropertyAssignment; + + var FunctionPropertyAssignment = (function (_super) { + __extends(FunctionPropertyAssignment, _super); + function FunctionPropertyAssignment(propertyName, callSignature, block) { + _super.call(this); + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + propertyName && (propertyName.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + FunctionPropertyAssignment.prototype.kind = function () { + return 241 /* FunctionPropertyAssignment */; + }; + return FunctionPropertyAssignment; + })(AST); + TypeScript.FunctionPropertyAssignment = FunctionPropertyAssignment; + + var FunctionExpression = (function (_super) { + __extends(FunctionExpression, _super); + function FunctionExpression(identifier, callSignature, block) { + _super.call(this); + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + identifier && (identifier.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + FunctionExpression.prototype.kind = function () { + return 222 /* FunctionExpression */; + }; + + FunctionExpression.prototype.isExpression = function () { + return true; + }; + return FunctionExpression; + })(AST); + TypeScript.FunctionExpression = FunctionExpression; + + var EmptyStatement = (function (_super) { + __extends(EmptyStatement, _super); + function EmptyStatement() { + _super.apply(this, arguments); + } + EmptyStatement.prototype.kind = function () { + return 156 /* EmptyStatement */; + }; + + EmptyStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return EmptyStatement; + })(AST); + TypeScript.EmptyStatement = EmptyStatement; + + var TryStatement = (function (_super) { + __extends(TryStatement, _super); + function TryStatement(block, catchClause, finallyClause) { + _super.call(this); + this.block = block; + this.catchClause = catchClause; + this.finallyClause = finallyClause; + block && (block.parent = this); + catchClause && (catchClause.parent = this); + finallyClause && (finallyClause.parent = this); + } + TryStatement.prototype.kind = function () { + return 159 /* TryStatement */; + }; + + TryStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.block, ast.block, includingPosition) && structuralEquals(this.catchClause, ast.catchClause, includingPosition) && structuralEquals(this.finallyClause, ast.finallyClause, includingPosition); + }; + return TryStatement; + })(AST); + TypeScript.TryStatement = TryStatement; + + var CatchClause = (function (_super) { + __extends(CatchClause, _super); + function CatchClause(identifier, typeAnnotation, block) { + _super.call(this); + this.identifier = identifier; + this.typeAnnotation = typeAnnotation; + this.block = block; + identifier && (identifier.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + block && (block.parent = this); + } + CatchClause.prototype.kind = function () { + return 236 /* CatchClause */; + }; + + CatchClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.typeAnnotation, ast.typeAnnotation, includingPosition) && structuralEquals(this.block, ast.block, includingPosition); + }; + return CatchClause; + })(AST); + TypeScript.CatchClause = CatchClause; + + var FinallyClause = (function (_super) { + __extends(FinallyClause, _super); + function FinallyClause(block) { + _super.call(this); + this.block = block; + block && (block.parent = this); + } + FinallyClause.prototype.kind = function () { + return 237 /* FinallyClause */; + }; + + FinallyClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.block, ast.block, includingPosition); + }; + return FinallyClause; + })(AST); + TypeScript.FinallyClause = FinallyClause; + + var LabeledStatement = (function (_super) { + __extends(LabeledStatement, _super); + function LabeledStatement(identifier, statement) { + _super.call(this); + this.identifier = identifier; + this.statement = statement; + identifier && (identifier.parent = this); + statement && (statement.parent = this); + } + LabeledStatement.prototype.kind = function () { + return 160 /* LabeledStatement */; + }; + + LabeledStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return LabeledStatement; + })(AST); + TypeScript.LabeledStatement = LabeledStatement; + + var DoStatement = (function (_super) { + __extends(DoStatement, _super); + function DoStatement(statement, whileKeyword, condition) { + _super.call(this); + this.statement = statement; + this.whileKeyword = whileKeyword; + this.condition = condition; + statement && (statement.parent = this); + condition && (condition.parent = this); + } + DoStatement.prototype.kind = function () { + return 161 /* DoStatement */; + }; + + DoStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition); + }; + return DoStatement; + })(AST); + TypeScript.DoStatement = DoStatement; + + var TypeOfExpression = (function (_super) { + __extends(TypeOfExpression, _super); + function TypeOfExpression(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + TypeOfExpression.prototype.kind = function () { + return 171 /* TypeOfExpression */; + }; + + TypeOfExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + TypeOfExpression.prototype.isExpression = function () { + return true; + }; + return TypeOfExpression; + })(AST); + TypeScript.TypeOfExpression = TypeOfExpression; + + var DeleteExpression = (function (_super) { + __extends(DeleteExpression, _super); + function DeleteExpression(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + DeleteExpression.prototype.kind = function () { + return 170 /* DeleteExpression */; + }; + + DeleteExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + DeleteExpression.prototype.isExpression = function () { + return true; + }; + return DeleteExpression; + })(AST); + TypeScript.DeleteExpression = DeleteExpression; + + var VoidExpression = (function (_super) { + __extends(VoidExpression, _super); + function VoidExpression(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + VoidExpression.prototype.kind = function () { + return 172 /* VoidExpression */; + }; + + VoidExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + VoidExpression.prototype.isExpression = function () { + return true; + }; + return VoidExpression; + })(AST); + TypeScript.VoidExpression = VoidExpression; + + var DebuggerStatement = (function (_super) { + __extends(DebuggerStatement, _super); + function DebuggerStatement() { + _super.apply(this, arguments); + } + DebuggerStatement.prototype.kind = function () { + return 162 /* DebuggerStatement */; + }; + return DebuggerStatement; + })(AST); + TypeScript.DebuggerStatement = DebuggerStatement; + + var Comment = (function () { + function Comment(_trivia, endsLine, _start, _end) { + this._trivia = _trivia; + this.endsLine = endsLine; + this._start = _start; + this._end = _end; + } + Comment.prototype.start = function () { + return this._start; + }; + + Comment.prototype.end = function () { + return this._end; + }; + + Comment.prototype.fullText = function () { + return this._trivia.fullText(); + }; + + Comment.prototype.kind = function () { + return this._trivia.kind(); + }; + + Comment.prototype.structuralEquals = function (ast, includingPosition) { + if (includingPosition) { + if (this.start() !== ast.start() || this.end() !== ast.end()) { + return false; + } + } + + return this._trivia.fullText() === ast._trivia.fullText() && this.endsLine === ast.endsLine; + }; + return Comment; + })(); + TypeScript.Comment = Comment; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (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 writeFileAndFolderStructure(ioHost, fileName, contents, writeByteOrderMark) { + var start = new Date().getTime(); + var path = ioHost.resolvePath(fileName); + TypeScript.ioHostResolvePathTime += new Date().getTime() - start; + + var start = new Date().getTime(); + var dirName = ioHost.dirName(path); + TypeScript.ioHostDirectoryNameTime += new Date().getTime() - start; + + var start = new Date().getTime(); + createDirectoryStructure(ioHost, dirName); + TypeScript.ioHostCreateDirectoryStructureTime += new Date().getTime() - start; + + var start = new Date().getTime(); + ioHost.writeFile(path, contents, writeByteOrderMark); + TypeScript.ioHostWriteFileTime += new Date().getTime() - start; + } + IOUtils.writeFileAndFolderStructure = writeFileAndFolderStructure; + + function throwIOError(message, error) { + var errorMessage = message; + if (error && error.message) { + errorMessage += (" " + error.message); + } + throw new Error(errorMessage); + } + IOUtils.throwIOError = throwIOError; + + function combine(prefix, suffix) { + return prefix + "/" + suffix; + } + IOUtils.combine = combine; + + 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; + })(TypeScript.IOUtils || (TypeScript.IOUtils = {})); + var IOUtils = TypeScript.IOUtils; + + TypeScript.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 { + appendFile: function (path, content) { + var txtFile = fso.OpenTextFile(path, 8, true); + txtFile.Write(content); + txtFile.Close(); + }, + readFile: function (path, codepage) { + return TypeScript.Environment.readFile(path, codepage); + }, + writeFile: function (path, contents, writeByteOrderMark) { + TypeScript.Environment.writeFile(path, contents, writeByteOrderMark); + }, + 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)) { + return { fileInformation: this.readFile(path), path: path }; + } 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(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Could_not_delete_file_0, [path]), e); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + createDirectory: function (path) { + try { + if (!this.directoryExists(path)) { + fso.CreateFolder(path); + } + } catch (e) { + IOUtils.throwIOError(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Could_not_create_directory_0, [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(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Error_while_executing_file_0, [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 { + appendFile: function (path, content) { + _fs.appendFileSync(path, content); + }, + readFile: function (file, codepage) { + return TypeScript.Environment.readFile(file, codepage); + }, + writeFile: function (path, contents, writeByteOrderMark) { + TypeScript.Environment.writeFile(path, contents, writeByteOrderMark); + }, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + IOUtils.throwIOError(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Could_not_delete_file_0, [path]), e); + } + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + dir: function dir(path, spec, options) { + options = options || {}; + + function filesInFolder(folder) { + var paths = []; + + try { + 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]); + } + } + } catch (err) { + } + + return paths; + } + + return filesInFolder(path); + }, + createDirectory: function (path) { + try { + if (!this.directoryExists(path)) { + _fs.mkdirSync(path); + } + } catch (e) { + IOUtils.throwIOError(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Could_not_create_directory_0, [path]), e); + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); + }, + resolvePath: function (path) { + return _path.resolve(path); + }, + dirName: function (path) { + var dirPath = _path.dirname(path); + + if (dirPath === path) { + dirPath = null; + } + + return dirPath; + }, + findFile: function (rootPath, partialFilePath) { + var path = rootPath + "/" + partialFilePath; + + while (true) { + if (_fs.existsSync(path)) { + return { fileInformation: this.readFile(path), path: path }; + } 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: function (code) { + var stderrFlushed = process.stderr.write(''); + var stdoutFlushed = process.stdout.write(''); + process.stderr.on('drain', function () { + stderrFlushed = true; + if (stdoutFlushed) { + process.exit(code); + } + }); + process.stdout.on('drain', function () { + stdoutFlushed = true; + if (stderrFlushed) { + process.exit(code); + } + }); + setTimeout(function () { + process.exit(code); + }, 5); + } + }; + } + ; + + if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") + return getWindowsScriptHostIO(); + else if (typeof module !== 'undefined' && module.exports) + return getNodeIO(); + else + return null; + })(); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var OptionsParser = (function () { + function OptionsParser(host, version) { + this.host = host; + this.version = version; + this.DEFAULT_SHORT_FLAG = "-"; + this.DEFAULT_LONG_FLAG = "--"; + this.printedVersion = false; + this.unnamed = []; + this.options = []; + } + OptionsParser.prototype.findOption = function (arg) { + var upperCaseArg = arg && arg.toUpperCase(); + + for (var i = 0; i < this.options.length; i++) { + var current = this.options[i]; + + if (upperCaseArg === (current.short && current.short.toUpperCase()) || upperCaseArg === (current.name && current.name.toUpperCase())) { + return current; + } + } + + return null; + }; + + OptionsParser.prototype.printUsage = function () { + this.printVersion(); + + var optionsWord = TypeScript.getLocalizedText(TypeScript.DiagnosticCode.options, null); + var fileWord = TypeScript.getLocalizedText(TypeScript.DiagnosticCode.file1, null); + var tscSyntax = "tsc [" + optionsWord + "] [" + fileWord + " ..]"; + var syntaxHelp = TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Syntax_0, [tscSyntax]); + this.host.printLine(syntaxHelp); + this.host.printLine(""); + this.host.printLine(TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Examples, null) + " tsc hello.ts"); + this.host.printLine(" tsc --out foo.js foo.ts"); + this.host.printLine(" tsc @args.txt"); + this.host.printLine(""); + this.host.printLine(TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Options, null)); + + var output = []; + var maxLength = 0; + var i = 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 (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 ? (" " + TypeScript.getLocalizedText(option.type, null)) : ""; + + if (option.short) { + usageString += this.DEFAULT_SHORT_FLAG + option.short + type + ", "; + } + + usageString += this.DEFAULT_LONG_FLAG + option.name + type; + + output.push([usageString, TypeScript.getLocalizedText(option.usage.locCode, option.usage.args)]); + + if (usageString.length > maxLength) { + maxLength = usageString.length; + } + } + + var fileDescription = TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Insert_command_line_options_and_files_from_a_file, null); + output.push([" @<" + fileWord + ">", fileDescription]); + + for (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.printVersion = function () { + if (!this.printedVersion) { + this.host.printLine(TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Version_0, [this.version])); + this.printedVersion = true; + } + }; + + 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], null).contents); + } else { + var arg = match[2]; + var option = this.findOption(arg); + + if (option === null) { + this.host.printLine(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Unknown_option_0, [arg])); + this.host.printLine(TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Use_the_0_flag_to_see_options, ["--help"])); + } else { + if (!option.flag) { + value = consume(); + if (value === undefined) { + this.host.printLine(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Option_0_specified_without_1, [arg, TypeScript.getLocalizedText(option.type, null)])); + this.host.printLine(TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Use_the_0_flag_to_see_options, ["--help"])); + continue; + } + } + + option.set(value); + } + } + } else { + this.unnamed.push(current); + } + } + }; + return OptionsParser; + })(); + TypeScript.OptionsParser = OptionsParser; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceFile = (function () { + function SourceFile(scriptSnapshot, byteOrderMark) { + this.scriptSnapshot = scriptSnapshot; + this.byteOrderMark = byteOrderMark; + } + return SourceFile; + })(); + + var DiagnosticsLogger = (function () { + function DiagnosticsLogger(ioHost) { + this.ioHost = ioHost; + } + DiagnosticsLogger.prototype.information = function () { + return false; + }; + DiagnosticsLogger.prototype.debug = function () { + return false; + }; + DiagnosticsLogger.prototype.warning = function () { + return false; + }; + DiagnosticsLogger.prototype.error = function () { + return false; + }; + DiagnosticsLogger.prototype.fatal = function () { + return false; + }; + DiagnosticsLogger.prototype.log = function (s) { + this.ioHost.stdout.WriteLine(s); + }; + return DiagnosticsLogger; + })(); + + var FileLogger = (function () { + function FileLogger(ioHost) { + this.ioHost = ioHost; + var file = "tsc." + Date.now() + ".log"; + + this.fileName = this.ioHost.resolvePath(file); + } + FileLogger.prototype.information = function () { + return false; + }; + FileLogger.prototype.debug = function () { + return false; + }; + FileLogger.prototype.warning = function () { + return false; + }; + FileLogger.prototype.error = function () { + return false; + }; + FileLogger.prototype.fatal = function () { + return false; + }; + FileLogger.prototype.log = function (s) { + this.ioHost.appendFile(this.fileName, s + '\r\n'); + }; + return FileLogger; + })(); + + var BatchCompiler = (function () { + function BatchCompiler(ioHost) { + this.ioHost = ioHost; + this.compilerVersion = "1.0.2.1"; + this.inputFiles = []; + this.resolvedFiles = []; + this.fileNameToSourceFile = new TypeScript.StringHashTable(); + this.hasErrors = false; + this.logger = null; + this.fileExistsCache = TypeScript.createIntrinsicsObject(); + this.resolvePathCache = TypeScript.createIntrinsicsObject(); + } + BatchCompiler.prototype.batchCompile = function () { + var _this = this; + var start = new Date().getTime(); + + TypeScript.CompilerDiagnostics.diagnosticWriter = { Alert: function (s) { + _this.ioHost.printLine(s); + } }; + + if (this.parseOptions()) { + if (this.compilationSettings.createFileLog()) { + this.logger = new FileLogger(this.ioHost); + } else if (this.compilationSettings.gatherDiagnostics()) { + this.logger = new DiagnosticsLogger(this.ioHost); + } else { + this.logger = new TypeScript.NullLogger(); + } + + if (this.compilationSettings.watch()) { + this.watchFiles(); + return; + } + + this.resolve(); + + this.compile(); + + if (this.compilationSettings.createFileLog()) { + this.logger.log("Compilation settings:"); + this.logger.log(" propagateEnumConstants " + this.compilationSettings.propagateEnumConstants()); + this.logger.log(" removeComments " + this.compilationSettings.removeComments()); + this.logger.log(" watch " + this.compilationSettings.watch()); + this.logger.log(" noResolve " + this.compilationSettings.noResolve()); + this.logger.log(" noImplicitAny " + this.compilationSettings.noImplicitAny()); + this.logger.log(" nolib " + this.compilationSettings.noLib()); + this.logger.log(" target " + this.compilationSettings.codeGenTarget()); + this.logger.log(" module " + this.compilationSettings.moduleGenTarget()); + this.logger.log(" out " + this.compilationSettings.outFileOption()); + this.logger.log(" outDir " + this.compilationSettings.outDirOption()); + this.logger.log(" sourcemap " + this.compilationSettings.mapSourceFiles()); + this.logger.log(" mapRoot " + this.compilationSettings.mapRoot()); + this.logger.log(" sourceroot " + this.compilationSettings.sourceRoot()); + this.logger.log(" declaration " + this.compilationSettings.generateDeclarationFiles()); + this.logger.log(" useCaseSensitiveFileResolution " + this.compilationSettings.useCaseSensitiveFileResolution()); + this.logger.log(" diagnostics " + this.compilationSettings.gatherDiagnostics()); + this.logger.log(" codepage " + this.compilationSettings.codepage()); + + this.logger.log(""); + + this.logger.log("Input files:"); + this.inputFiles.forEach(function (file) { + _this.logger.log(" " + file); + }); + + this.logger.log(""); + + this.logger.log("Resolved Files:"); + this.resolvedFiles.forEach(function (file) { + file.importedFiles.forEach(function (file) { + _this.logger.log(" " + file); + }); + file.referencedFiles.forEach(function (file) { + _this.logger.log(" " + file); + }); + }); + } + + if (this.compilationSettings.gatherDiagnostics()) { + this.logger.log(""); + this.logger.log("File resolution time: " + TypeScript.fileResolutionTime); + this.logger.log(" file read: " + TypeScript.fileResolutionIOTime); + this.logger.log(" scan imports: " + TypeScript.fileResolutionScanImportsTime); + this.logger.log(" import search: " + TypeScript.fileResolutionImportFileSearchTime); + this.logger.log(" get lib.d.ts: " + TypeScript.fileResolutionGetDefaultLibraryTime); + + this.logger.log("SyntaxTree parse time: " + TypeScript.syntaxTreeParseTime); + this.logger.log("Syntax Diagnostics time: " + TypeScript.syntaxDiagnosticsTime); + this.logger.log("AST translation time: " + TypeScript.astTranslationTime); + this.logger.log(""); + this.logger.log("Type check time: " + TypeScript.typeCheckTime); + this.logger.log(""); + this.logger.log("Emit time: " + TypeScript.emitTime); + this.logger.log("Declaration emit time: " + TypeScript.declarationEmitTime); + + this.logger.log("Total number of symbols created: " + TypeScript.pullSymbolID); + this.logger.log("Specialized types created: " + TypeScript.nSpecializationsCreated); + this.logger.log("Specialized signatures created: " + TypeScript.nSpecializedSignaturesCreated); + + this.logger.log(" IsExternallyVisibleTime: " + TypeScript.declarationEmitIsExternallyVisibleTime); + this.logger.log(" TypeSignatureTime: " + TypeScript.declarationEmitTypeSignatureTime); + this.logger.log(" GetBoundDeclTypeTime: " + TypeScript.declarationEmitGetBoundDeclTypeTime); + this.logger.log(" IsOverloadedCallSignatureTime: " + TypeScript.declarationEmitIsOverloadedCallSignatureTime); + this.logger.log(" FunctionDeclarationGetSymbolTime: " + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime); + this.logger.log(" GetBaseTypeTime: " + TypeScript.declarationEmitGetBaseTypeTime); + this.logger.log(" GetAccessorFunctionTime: " + TypeScript.declarationEmitGetAccessorFunctionTime); + this.logger.log(" GetTypeParameterSymbolTime: " + TypeScript.declarationEmitGetTypeParameterSymbolTime); + this.logger.log(" GetImportDeclarationSymbolTime: " + TypeScript.declarationEmitGetImportDeclarationSymbolTime); + + this.logger.log("Emit write file time: " + TypeScript.emitWriteFileTime); + + this.logger.log("Compiler resolve path time: " + TypeScript.compilerResolvePathTime); + this.logger.log("Compiler directory name time: " + TypeScript.compilerDirectoryNameTime); + this.logger.log("Compiler directory exists time: " + TypeScript.compilerDirectoryExistsTime); + this.logger.log("Compiler file exists time: " + TypeScript.compilerFileExistsTime); + + this.logger.log("IO host resolve path time: " + TypeScript.ioHostResolvePathTime); + this.logger.log("IO host directory name time: " + TypeScript.ioHostDirectoryNameTime); + this.logger.log("IO host create directory structure time: " + TypeScript.ioHostCreateDirectoryStructureTime); + this.logger.log("IO host write file time: " + TypeScript.ioHostWriteFileTime); + + this.logger.log("Node make directory time: " + TypeScript.nodeMakeDirectoryTime); + this.logger.log("Node writeFileSync time: " + TypeScript.nodeWriteFileSyncTime); + this.logger.log("Node createBuffer time: " + TypeScript.nodeCreateBufferTime); + } + } + + this.ioHost.quit(this.hasErrors ? 1 : 0); + }; + + BatchCompiler.prototype.resolve = function () { + var _this = this; + var includeDefaultLibrary = !this.compilationSettings.noLib(); + var resolvedFiles = []; + + var start = new Date().getTime(); + + if (!this.compilationSettings.noResolve()) { + var resolutionResults = TypeScript.ReferenceResolver.resolve(this.inputFiles, this, this.compilationSettings.useCaseSensitiveFileResolution()); + resolvedFiles = resolutionResults.resolvedFiles; + + includeDefaultLibrary = !this.compilationSettings.noLib() && !resolutionResults.seenNoDefaultLibTag; + + resolutionResults.diagnostics.forEach(function (d) { + return _this.addDiagnostic(d); + }); + } else { + for (var i = 0, n = this.inputFiles.length; i < n; i++) { + var inputFile = this.inputFiles[i]; + var referencedFiles = []; + var importedFiles = []; + + if (this.compilationSettings.generateDeclarationFiles()) { + var references = TypeScript.getReferencedFiles(inputFile, this.getScriptSnapshot(inputFile)); + for (var j = 0; j < references.length; j++) { + referencedFiles.push(references[j].path); + } + + inputFile = this.resolvePath(inputFile); + } + + resolvedFiles.push({ + path: inputFile, + referencedFiles: referencedFiles, + importedFiles: importedFiles + }); + } + } + + var defaultLibStart = new Date().getTime(); + if (includeDefaultLibrary) { + var libraryResolvedFile = { + path: this.getDefaultLibraryFilePath(), + referencedFiles: [], + importedFiles: [] + }; + + resolvedFiles = [libraryResolvedFile].concat(resolvedFiles); + } + TypeScript.fileResolutionGetDefaultLibraryTime += new Date().getTime() - defaultLibStart; + + this.resolvedFiles = resolvedFiles; + + TypeScript.fileResolutionTime = new Date().getTime() - start; + }; + + BatchCompiler.prototype.compile = function () { + var _this = this; + var compiler = new TypeScript.TypeScriptCompiler(this.logger, this.compilationSettings); + + this.resolvedFiles.forEach(function (resolvedFile) { + var sourceFile = _this.getSourceFile(resolvedFile.path); + compiler.addFile(resolvedFile.path, sourceFile.scriptSnapshot, sourceFile.byteOrderMark, 0, false, resolvedFile.referencedFiles); + }); + + for (var it = compiler.compile(function (path) { + return _this.resolvePath(path); + }); it.moveNext();) { + var result = it.current(); + + result.diagnostics.forEach(function (d) { + return _this.addDiagnostic(d); + }); + if (!this.tryWriteOutputFiles(result.outputFiles)) { + return; + } + } + }; + + BatchCompiler.prototype.parseOptions = function () { + var _this = this; + var opts = new TypeScript.OptionsParser(this.ioHost, this.compilerVersion); + + var mutableSettings = new TypeScript.CompilationSettings(); + opts.option('out', { + usage: { + locCode: TypeScript.DiagnosticCode.Concatenate_and_emit_output_to_single_file, + args: null + }, + type: TypeScript.DiagnosticCode.file2, + set: function (str) { + mutableSettings.outFileOption = str; + } + }); + + opts.option('outDir', { + usage: { + locCode: TypeScript.DiagnosticCode.Redirect_output_structure_to_the_directory, + args: null + }, + type: TypeScript.DiagnosticCode.DIRECTORY, + set: function (str) { + mutableSettings.outDirOption = str; + } + }); + + opts.flag('sourcemap', { + usage: { + locCode: TypeScript.DiagnosticCode.Generates_corresponding_0_file, + args: ['.map'] + }, + set: function () { + mutableSettings.mapSourceFiles = true; + } + }); + + opts.option('mapRoot', { + usage: { + locCode: TypeScript.DiagnosticCode.Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, + args: null + }, + type: TypeScript.DiagnosticCode.LOCATION, + set: function (str) { + mutableSettings.mapRoot = str; + } + }); + + opts.option('sourceRoot', { + usage: { + locCode: TypeScript.DiagnosticCode.Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, + args: null + }, + type: TypeScript.DiagnosticCode.LOCATION, + set: function (str) { + mutableSettings.sourceRoot = str; + } + }); + + opts.flag('declaration', { + usage: { + locCode: TypeScript.DiagnosticCode.Generates_corresponding_0_file, + args: ['.d.ts'] + }, + set: function () { + mutableSettings.generateDeclarationFiles = true; + } + }, 'd'); + + if (this.ioHost.watchFile) { + opts.flag('watch', { + usage: { + locCode: TypeScript.DiagnosticCode.Watch_input_files, + args: null + }, + set: function () { + mutableSettings.watch = true; + } + }, 'w'); + } + + opts.flag('propagateEnumConstants', { + experimental: true, + set: function () { + mutableSettings.propagateEnumConstants = true; + } + }); + + opts.flag('removeComments', { + usage: { + locCode: TypeScript.DiagnosticCode.Do_not_emit_comments_to_output, + args: null + }, + set: function () { + mutableSettings.removeComments = true; + } + }); + + opts.flag('noResolve', { + experimental: true, + usage: { + locCode: TypeScript.DiagnosticCode.Skip_resolution_and_preprocessing, + args: null + }, + set: function () { + mutableSettings.noResolve = true; + } + }); + + opts.flag('noLib', { + experimental: true, + set: function () { + mutableSettings.noLib = true; + } + }); + + opts.flag('diagnostics', { + experimental: true, + set: function () { + mutableSettings.gatherDiagnostics = true; + } + }); + + opts.flag('logFile', { + experimental: true, + set: function () { + mutableSettings.createFileLog = true; + } + }); + + opts.option('target', { + usage: { + locCode: TypeScript.DiagnosticCode.Specify_ECMAScript_target_version_0_default_or_1, + args: ['ES3', 'ES5'] + }, + type: TypeScript.DiagnosticCode.VERSION, + set: function (type) { + type = type.toLowerCase(); + + if (type === 'es3') { + mutableSettings.codeGenTarget = 0 /* EcmaScript3 */; + } else if (type === 'es5') { + mutableSettings.codeGenTarget = 1 /* EcmaScript5 */; + } else { + _this.addDiagnostic(new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.ECMAScript_target_version_0_not_supported_Specify_a_valid_target_version_1_default_or_2, [type, "ES3", "ES5"])); + } + } + }, 't'); + + opts.option('module', { + usage: { + locCode: TypeScript.DiagnosticCode.Specify_module_code_generation_0_or_1, + args: ['commonjs', 'amd'] + }, + type: TypeScript.DiagnosticCode.KIND, + set: function (type) { + type = type.toLowerCase(); + + if (type === 'commonjs') { + mutableSettings.moduleGenTarget = 1 /* Synchronous */; + } else if (type === 'amd') { + mutableSettings.moduleGenTarget = 2 /* Asynchronous */; + } else { + _this.addDiagnostic(new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Module_code_generation_0_not_supported, [type])); + } + } + }, 'm'); + + var needsHelp = false; + opts.flag('help', { + usage: { + locCode: TypeScript.DiagnosticCode.Print_this_message, + args: null + }, + set: function () { + needsHelp = true; + } + }, 'h'); + + opts.flag('useCaseSensitiveFileResolution', { + experimental: true, + set: function () { + mutableSettings.useCaseSensitiveFileResolution = true; + } + }); + var shouldPrintVersionOnly = false; + opts.flag('version', { + usage: { + locCode: TypeScript.DiagnosticCode.Print_the_compiler_s_version_0, + args: [this.compilerVersion] + }, + set: function () { + shouldPrintVersionOnly = true; + } + }, 'v'); + + var locale = null; + opts.option('locale', { + experimental: true, + usage: { + locCode: TypeScript.DiagnosticCode.Specify_locale_for_errors_and_messages_For_example_0_or_1, + args: ['en', 'ja-jp'] + }, + type: TypeScript.DiagnosticCode.STRING, + set: function (value) { + locale = value; + } + }); + + opts.flag('noImplicitAny', { + usage: { + locCode: TypeScript.DiagnosticCode.Warn_on_expressions_and_declarations_with_an_implied_any_type, + args: null + }, + set: function () { + mutableSettings.noImplicitAny = true; + } + }); + + if (TypeScript.Environment.supportsCodePage()) { + opts.option('codepage', { + usage: { + locCode: TypeScript.DiagnosticCode.Specify_the_codepage_to_use_when_opening_source_files, + args: null + }, + type: TypeScript.DiagnosticCode.NUMBER, + set: function (arg) { + mutableSettings.codepage = parseInt(arg, 10); + } + }); + } + + opts.parse(this.ioHost.arguments); + + this.compilationSettings = TypeScript.ImmutableCompilationSettings.fromCompilationSettings(mutableSettings); + + if (locale) { + if (!this.setLocale(locale)) { + return false; + } + } + + this.inputFiles.push.apply(this.inputFiles, opts.unnamed); + + if (shouldPrintVersionOnly) { + opts.printVersion(); + return false; + } else if (this.inputFiles.length === 0 || needsHelp) { + opts.printUsage(); + return false; + } + + return !this.hasErrors; + }; + + BatchCompiler.prototype.setLocale = function (locale) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + this.addDiagnostic(new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, ['en', 'ja-jp'])); + return false; + } + + var language = matchResult[1]; + var territory = matchResult[3]; + + if (!this.setLanguageAndTerritory(language, territory) && !this.setLanguageAndTerritory(language, null)) { + this.addDiagnostic(new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Unsupported_locale_0, [locale])); + return false; + } + + return true; + }; + + BatchCompiler.prototype.setLanguageAndTerritory = function (language, territory) { + var compilerFilePath = this.ioHost.getExecutingFilePath(); + var containingDirectoryPath = this.ioHost.dirName(compilerFilePath); + + var filePath = TypeScript.IOUtils.combine(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + + filePath = this.resolvePath(TypeScript.IOUtils.combine(filePath, "diagnosticMessages.generated.json")); + + if (!this.fileExists(filePath)) { + return false; + } + + var fileContents = this.ioHost.readFile(filePath, this.compilationSettings.codepage()); + TypeScript.LocalizedDiagnosticMessages = JSON.parse(fileContents.contents); + return true; + }; + + BatchCompiler.prototype.watchFiles = function () { + var _this = this; + if (!this.ioHost.watchFile) { + this.addDiagnostic(new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Current_host_does_not_support_0_option, ['-w[atch]'])); + return; + } + + var lastResolvedFileSet = []; + var watchers = {}; + var firstTime = true; + + 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.hasErrors = false; + + _this.fileNameToSourceFile = new TypeScript.StringHashTable(); + + _this.resolve(); + + var oldFiles = lastResolvedFileSet; + var newFiles = _this.resolvedFiles.map(function (resolvedFile) { + return resolvedFile.path; + }).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 (k = j; k < newFiles.length; k++) { + addWatcher(newFiles[k]); + } + + lastResolvedFileSet = newFiles; + + if (!firstTime) { + var fileNames = ""; + for (var k = 0; k < lastResolvedFileSet.length; k++) { + fileNames += TypeScript.Environment.newLine + " " + lastResolvedFileSet[k]; + } + _this.ioHost.printLine(TypeScript.getLocalizedText(TypeScript.DiagnosticCode.NL_Recompiling_0, [fileNames])); + } else { + firstTime = false; + } + + _this.compile(); + }; + + this.ioHost.stderr = this.ioHost.stdout; + + onWatchedFileChange(); + }; + + BatchCompiler.prototype.getSourceFile = function (fileName) { + var sourceFile = this.fileNameToSourceFile.lookup(fileName); + if (!sourceFile) { + var fileInformation; + + try { + fileInformation = this.ioHost.readFile(fileName, this.compilationSettings.codepage()); + } catch (e) { + this.addDiagnostic(new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Cannot_read_file_0_1, [fileName, e.message])); + fileInformation = new TypeScript.FileInformation("", 0 /* None */); + } + + var snapshot = TypeScript.ScriptSnapshot.fromString(fileInformation.contents); + var sourceFile = new SourceFile(snapshot, fileInformation.byteOrderMark); + this.fileNameToSourceFile.add(fileName, sourceFile); + } + + return sourceFile; + }; + + BatchCompiler.prototype.getDefaultLibraryFilePath = function () { + var compilerFilePath = this.ioHost.getExecutingFilePath(); + var containingDirectoryPath = this.ioHost.dirName(compilerFilePath); + var libraryFilePath = this.resolvePath(TypeScript.IOUtils.combine(containingDirectoryPath, "lib.d.ts")); + + return libraryFilePath; + }; + + BatchCompiler.prototype.getScriptSnapshot = function (fileName) { + return this.getSourceFile(fileName).scriptSnapshot; + }; + + BatchCompiler.prototype.resolveRelativePath = function (path, directory) { + var start = new Date().getTime(); + + var unQuotedPath = TypeScript.stripStartAndEndQuotes(path); + var normalizedPath; + + if (TypeScript.isRooted(unQuotedPath) || !directory) { + normalizedPath = unQuotedPath; + } else { + normalizedPath = TypeScript.IOUtils.combine(directory, unQuotedPath); + } + + normalizedPath = this.resolvePath(normalizedPath); + + normalizedPath = TypeScript.switchToForwardSlashes(normalizedPath); + + return normalizedPath; + }; + + BatchCompiler.prototype.fileExists = function (path) { + var exists = this.fileExistsCache[path]; + if (exists === undefined) { + var start = new Date().getTime(); + exists = this.ioHost.fileExists(path); + this.fileExistsCache[path] = exists; + TypeScript.compilerFileExistsTime += new Date().getTime() - start; + } + + return exists; + }; + + BatchCompiler.prototype.getParentDirectory = function (path) { + var start = new Date().getTime(); + var result = this.ioHost.dirName(path); + TypeScript.compilerDirectoryNameTime += new Date().getTime() - start; + + return result; + }; + + BatchCompiler.prototype.addDiagnostic = function (diagnostic) { + var _this = this; + var diagnosticInfo = diagnostic.info(); + if (diagnosticInfo.category === 1 /* Error */) { + this.hasErrors = true; + } + + this.ioHost.stderr.Write(TypeScript.TypeScriptCompiler.getFullDiagnosticText(diagnostic, function (path) { + return _this.resolvePath(path); + })); + }; + + BatchCompiler.prototype.tryWriteOutputFiles = function (outputFiles) { + for (var i = 0, n = outputFiles.length; i < n; i++) { + var outputFile = outputFiles[i]; + + try { + this.writeFile(outputFile.name, outputFile.text, outputFile.writeByteOrderMark); + } catch (e) { + this.addDiagnostic(new TypeScript.Diagnostic(outputFile.name, null, 0, 0, TypeScript.DiagnosticCode.Emit_Error_0, [e.message])); + return false; + } + } + + return true; + }; + + BatchCompiler.prototype.writeFile = function (fileName, contents, writeByteOrderMark) { + var start = new Date().getTime(); + TypeScript.IOUtils.writeFileAndFolderStructure(this.ioHost, fileName, contents, writeByteOrderMark); + TypeScript.emitWriteFileTime += new Date().getTime() - start; + }; + + BatchCompiler.prototype.directoryExists = function (path) { + var start = new Date().getTime(); + var result = this.ioHost.directoryExists(path); + TypeScript.compilerDirectoryExistsTime += new Date().getTime() - start; + return result; + }; + + BatchCompiler.prototype.resolvePath = function (path) { + var cachedValue = this.resolvePathCache[path]; + if (!cachedValue) { + var start = new Date().getTime(); + cachedValue = this.ioHost.resolvePath(path); + this.resolvePathCache[path] = cachedValue; + TypeScript.compilerResolvePathTime += new Date().getTime() - start; + } + + return cachedValue; + }; + return BatchCompiler; + })(); + TypeScript.BatchCompiler = BatchCompiler; + + var batch = new TypeScript.BatchCompiler(TypeScript.IO); + batch.batchCompile(); +})(TypeScript || (TypeScript = {})); diff --git a/_infrastructure/tests/typescript/1.0.2.1-225bad/typescript.js b/_infrastructure/tests/typescript/1.0.2.1-225bad/typescript.js new file mode 100644 index 0000000000..bc994ab347 --- /dev/null +++ b/_infrastructure/tests/typescript/1.0.2.1-225bad/typescript.js @@ -0,0 +1,61516 @@ +/*! ***************************************************************************** +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) { + TypeScript.DiagnosticCode = { + error_TS_0_1: "error TS{0}: {1}", + warning_TS_0_1: "warning TS{0}: {1}", + Unrecognized_escape_sequence: "Unrecognized escape sequence.", + Unexpected_character_0: "Unexpected character {0}.", + Missing_close_quote_character: "Missing close quote character.", + Identifier_expected: "Identifier expected.", + _0_keyword_expected: "'{0}' keyword expected.", + _0_expected: "'{0}' expected.", + Identifier_expected_0_is_a_keyword: "Identifier expected; '{0}' is a keyword.", + Automatic_semicolon_insertion_not_allowed: "Automatic semicolon insertion not allowed.", + Unexpected_token_0_expected: "Unexpected token; '{0}' expected.", + Trailing_separator_not_allowed: "Trailing separator not allowed.", + AsteriskSlash_expected: "'*/' expected.", + public_or_private_modifier_must_precede_static: "'public' or 'private' modifier must precede 'static'.", + Unexpected_token: "Unexpected token.", + Catch_clause_parameter_cannot_have_a_type_annotation: "Catch clause parameter cannot have a type annotation.", + Rest_parameter_must_be_last_in_list: "Rest parameter must be last in list.", + Parameter_cannot_have_question_mark_and_initializer: "Parameter cannot have question mark and initializer.", + Required_parameter_cannot_follow_optional_parameter: "Required parameter cannot follow optional parameter.", + Index_signatures_cannot_have_rest_parameters: "Index signatures cannot have rest parameters.", + Index_signature_parameter_cannot_have_accessibility_modifiers: "Index signature parameter cannot have accessibility modifiers.", + Index_signature_parameter_cannot_have_a_question_mark: "Index signature parameter cannot have a question mark.", + Index_signature_parameter_cannot_have_an_initializer: "Index signature parameter cannot have an initializer.", + Index_signature_must_have_a_type_annotation: "Index signature must have a type annotation.", + Index_signature_parameter_must_have_a_type_annotation: "Index signature parameter must have a type annotation.", + Index_signature_parameter_type_must_be_string_or_number: "Index signature parameter type must be 'string' or 'number'.", + extends_clause_already_seen: "'extends' clause already seen.", + extends_clause_must_precede_implements_clause: "'extends' clause must precede 'implements' clause.", + Classes_can_only_extend_a_single_class: "Classes can only extend a single class.", + implements_clause_already_seen: "'implements' clause already seen.", + Accessibility_modifier_already_seen: "Accessibility modifier already seen.", + _0_modifier_must_precede_1_modifier: "'{0}' modifier must precede '{1}' modifier.", + _0_modifier_already_seen: "'{0}' modifier already seen.", + _0_modifier_cannot_appear_on_a_class_element: "'{0}' modifier cannot appear on a class element.", + Interface_declaration_cannot_have_implements_clause: "Interface declaration cannot have 'implements' clause.", + super_invocation_cannot_have_type_arguments: "'super' invocation cannot have type arguments.", + Only_ambient_modules_can_use_quoted_names: "Only ambient modules can use quoted names.", + Statements_are_not_allowed_in_ambient_contexts: "Statements are not allowed in ambient contexts.", + Implementations_are_not_allowed_in_ambient_contexts: "Implementations are not allowed in ambient contexts.", + declare_modifier_not_allowed_for_code_already_in_an_ambient_context: "'declare' modifier not allowed for code already in an ambient context.", + Initializers_are_not_allowed_in_ambient_contexts: "Initializers are not allowed in ambient contexts.", + Parameter_property_declarations_can_only_be_used_in_a_non_ambient_constructor_declaration: "Parameter property declarations can only be used in a non-ambient constructor declaration.", + Function_implementation_expected: "Function implementation expected.", + Constructor_implementation_expected: "Constructor implementation expected.", + Function_overload_name_must_be_0: "Function overload name must be '{0}'.", + _0_modifier_cannot_appear_on_a_module_element: "'{0}' modifier cannot appear on a module element.", + declare_modifier_cannot_appear_on_an_interface_declaration: "'declare' modifier cannot appear on an interface declaration.", + declare_modifier_required_for_top_level_element: "'declare' modifier required for top level element.", + Rest_parameter_cannot_be_optional: "Rest parameter cannot be optional.", + Rest_parameter_cannot_have_an_initializer: "Rest parameter cannot have an initializer.", + set_accessor_must_have_one_and_only_one_parameter: "'set' accessor must have one and only one parameter.", + set_accessor_parameter_cannot_be_optional: "'set' accessor parameter cannot be optional.", + set_accessor_parameter_cannot_have_an_initializer: "'set' accessor parameter cannot have an initializer.", + set_accessor_cannot_have_rest_parameter: "'set' accessor cannot have rest parameter.", + get_accessor_cannot_have_parameters: "'get' accessor cannot have parameters.", + Modifiers_cannot_appear_here: "Modifiers cannot appear here.", + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: "Accessors are only available when targeting ECMAScript 5 and higher.", + Class_name_cannot_be_0: "Class name cannot be '{0}'.", + Interface_name_cannot_be_0: "Interface name cannot be '{0}'.", + Enum_name_cannot_be_0: "Enum name cannot be '{0}'.", + Module_name_cannot_be_0: "Module name cannot be '{0}'.", + Enum_member_must_have_initializer: "Enum member must have initializer.", + Export_assignment_cannot_be_used_in_internal_modules: "Export assignment cannot be used in internal modules.", + Export_assignment_not_allowed_in_module_with_exported_element: "Export assignment not allowed in module with exported element.", + Module_cannot_have_multiple_export_assignments: "Module cannot have multiple export assignments.", + Ambient_enum_elements_can_only_have_integer_literal_initializers: "Ambient enum elements can only have integer literal initializers.", + module_class_interface_enum_import_or_statement: "module, class, interface, enum, import or statement", + constructor_function_accessor_or_variable: "constructor, function, accessor or variable", + statement: "statement", + case_or_default_clause: "case or default clause", + identifier: "identifier", + call_construct_index_property_or_function_signature: "call, construct, index, property or function signature", + expression: "expression", + type_name: "type name", + property_or_accessor: "property or accessor", + parameter: "parameter", + type: "type", + type_parameter: "type parameter", + declare_modifier_not_allowed_on_import_declaration: "'declare' modifier not allowed on import declaration.", + Function_overload_must_be_static: "Function overload must be static.", + Function_overload_must_not_be_static: "Function overload must not be static.", + Parameter_property_declarations_cannot_be_used_in_a_constructor_overload: "Parameter property declarations cannot be used in a constructor overload.", + Invalid_reference_directive_syntax: "Invalid 'reference' directive syntax.", + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: "Octal literals are not available when targeting ECMAScript 5 and higher.", + Accessors_are_not_allowed_in_ambient_contexts: "Accessors are not allowed in ambient contexts.", + _0_modifier_cannot_appear_on_a_constructor_declaration: "'{0}' modifier cannot appear on a constructor declaration.", + _0_modifier_cannot_appear_on_a_parameter: "'{0}' modifier cannot appear on a parameter.", + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: "Only a single variable declaration is allowed in a 'for...in' statement.", + Type_parameters_cannot_appear_on_a_constructor_declaration: "Type parameters cannot appear on a constructor declaration.", + Type_annotation_cannot_appear_on_a_constructor_declaration: "Type annotation cannot appear on a constructor declaration.", + Duplicate_identifier_0: "Duplicate identifier '{0}'.", + The_name_0_does_not_exist_in_the_current_scope: "The name '{0}' does not exist in the current scope.", + The_name_0_does_not_refer_to_a_value: "The name '{0}' does not refer to a value.", + super_can_only_be_used_inside_a_class_instance_method: "'super' can only be used inside a class instance method.", + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_property_or_indexer: "The left-hand side of an assignment expression must be a variable, property or indexer.", + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: "Value of type '{0}' is not callable. Did you mean to include 'new'?", + Value_of_type_0_is_not_callable: "Value of type '{0}' is not callable.", + Value_of_type_0_is_not_newable: "Value of type '{0}' is not newable.", + Value_of_type_0_is_not_indexable_by_type_1: "Value of type '{0}' is not indexable by type '{1}'.", + Operator_0_cannot_be_applied_to_types_1_and_2: "Operator '{0}' cannot be applied to types '{1}' and '{2}'.", + Operator_0_cannot_be_applied_to_types_1_and_2_3: "Operator '{0}' cannot be applied to types '{1}' and '{2}': {3}", + Cannot_convert_0_to_1: "Cannot convert '{0}' to '{1}'.", + Cannot_convert_0_to_1_NL_2: "Cannot convert '{0}' to '{1}':{NL}{2}", + Expected_var_class_interface_or_module: "Expected var, class, interface, or module.", + Operator_0_cannot_be_applied_to_type_1: "Operator '{0}' cannot be applied to type '{1}'.", + Getter_0_already_declared: "Getter '{0}' already declared.", + Setter_0_already_declared: "Setter '{0}' already declared.", + Exported_class_0_extends_private_class_1: "Exported class '{0}' extends private class '{1}'.", + Exported_class_0_implements_private_interface_1: "Exported class '{0}' implements private interface '{1}'.", + Exported_interface_0_extends_private_interface_1: "Exported interface '{0}' extends private interface '{1}'.", + Exported_class_0_extends_class_from_inaccessible_module_1: "Exported class '{0}' extends class from inaccessible module {1}.", + Exported_class_0_implements_interface_from_inaccessible_module_1: "Exported class '{0}' implements interface from inaccessible module {1}.", + Exported_interface_0_extends_interface_from_inaccessible_module_1: "Exported interface '{0}' extends interface from inaccessible module {1}.", + Public_static_property_0_of_exported_class_has_or_is_using_private_type_1: "Public static property '{0}' of exported class has or is using private type '{1}'.", + Public_property_0_of_exported_class_has_or_is_using_private_type_1: "Public property '{0}' of exported class has or is using private type '{1}'.", + Property_0_of_exported_interface_has_or_is_using_private_type_1: "Property '{0}' of exported interface has or is using private type '{1}'.", + Exported_variable_0_has_or_is_using_private_type_1: "Exported variable '{0}' has or is using private type '{1}'.", + Public_static_property_0_of_exported_class_is_using_inaccessible_module_1: "Public static property '{0}' of exported class is using inaccessible module {1}.", + Public_property_0_of_exported_class_is_using_inaccessible_module_1: "Public property '{0}' of exported class is using inaccessible module {1}.", + Property_0_of_exported_interface_is_using_inaccessible_module_1: "Property '{0}' of exported interface is using inaccessible module {1}.", + Exported_variable_0_is_using_inaccessible_module_1: "Exported variable '{0}' is using inaccessible module {1}.", + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of constructor from exported class has or is using private type '{1}'.", + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public static property setter from exported class has or is using private type '{1}'.", + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public property setter from exported class has or is using private type '{1}'.", + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.", + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of call signature from exported interface has or is using private type '{1}'.", + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public static method from exported class has or is using private type '{1}'.", + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1: "Parameter '{0}' of public method from exported class has or is using private type '{1}'.", + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1: "Parameter '{0}' of method from exported interface has or is using private type '{1}'.", + Parameter_0_of_exported_function_has_or_is_using_private_type_1: "Parameter '{0}' of exported function has or is using private type '{1}'.", + Parameter_0_of_constructor_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of constructor from exported class is using inaccessible module {1}.", + Parameter_0_of_public_static_property_setter_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public static property setter from exported class is using inaccessible module {1}.", + Parameter_0_of_public_property_setter_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public property setter from exported class is using inaccessible module {1}.", + Parameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.", + Parameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of call signature from exported interface is using inaccessible module {1}", + Parameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public static method from exported class is using inaccessible module {1}.", + Parameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1: "Parameter '{0}' of public method from exported class is using inaccessible module {1}.", + Parameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1: "Parameter '{0}' of method from exported interface is using inaccessible module {1}.", + Parameter_0_of_exported_function_is_using_inaccessible_module_1: "Parameter '{0}' of exported function is using inaccessible module {1}.", + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type_0: "Return type of public static property getter from exported class has or is using private type '{0}'.", + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type_0: "Return type of public property getter from exported class has or is using private type '{0}'.", + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of constructor signature from exported interface has or is using private type '{0}'.", + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of call signature from exported interface has or is using private type '{0}'.", + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type_0: "Return type of index signature from exported interface has or is using private type '{0}'.", + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type_0: "Return type of public static method from exported class has or is using private type '{0}'.", + Return_type_of_public_method_from_exported_class_has_or_is_using_private_type_0: "Return type of public method from exported class has or is using private type '{0}'.", + Return_type_of_method_from_exported_interface_has_or_is_using_private_type_0: "Return type of method from exported interface has or is using private type '{0}'.", + Return_type_of_exported_function_has_or_is_using_private_type_0: "Return type of exported function has or is using private type '{0}'.", + Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module_0: "Return type of public static property getter from exported class is using inaccessible module {0}.", + Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module_0: "Return type of public property getter from exported class is using inaccessible module {0}.", + Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of constructor signature from exported interface is using inaccessible module {0}.", + Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of call signature from exported interface is using inaccessible module {0}.", + Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module_0: "Return type of index signature from exported interface is using inaccessible module {0}.", + Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module_0: "Return type of public static method from exported class is using inaccessible module {0}.", + Return_type_of_public_method_from_exported_class_is_using_inaccessible_module_0: "Return type of public method from exported class is using inaccessible module {0}.", + Return_type_of_method_from_exported_interface_is_using_inaccessible_module_0: "Return type of method from exported interface is using inaccessible module {0}.", + Return_type_of_exported_function_is_using_inaccessible_module_0: "Return type of exported function is using inaccessible module {0}.", + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: "'new T[]' cannot be used to create an array. Use 'new Array()' instead.", + A_parameter_list_must_follow_a_generic_type_argument_list_expected: "A parameter list must follow a generic type argument list. '(' expected.", + Multiple_constructor_implementations_are_not_allowed: "Multiple constructor implementations are not allowed.", + Unable_to_resolve_external_module_0: "Unable to resolve external module '{0}'.", + Module_cannot_be_aliased_to_a_non_module_type: "Module cannot be aliased to a non-module type.", + A_class_may_only_extend_another_class: "A class may only extend another class.", + A_class_may_only_implement_another_class_or_interface: "A class may only implement another class or interface.", + An_interface_may_only_extend_another_class_or_interface: "An interface may only extend another class or interface.", + Unable_to_resolve_type: "Unable to resolve type.", + Unable_to_resolve_type_of_0: "Unable to resolve type of '{0}'.", + Unable_to_resolve_type_parameter_constraint: "Unable to resolve type parameter constraint.", + Type_parameter_constraint_cannot_be_a_primitive_type: "Type parameter constraint cannot be a primitive type.", + Supplied_parameters_do_not_match_any_signature_of_call_target: "Supplied parameters do not match any signature of call target.", + Supplied_parameters_do_not_match_any_signature_of_call_target_NL_0: "Supplied parameters do not match any signature of call target:{NL}{0}", + Invalid_new_expression: "Invalid 'new' expression.", + Call_signatures_used_in_a_new_expression_must_have_a_void_return_type: "Call signatures used in a 'new' expression must have a 'void' return type.", + Could_not_select_overload_for_new_expression: "Could not select overload for 'new' expression.", + Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2: "Type '{0}' does not satisfy the constraint '{1}' for type parameter '{2}'.", + Could_not_select_overload_for_call_expression: "Could not select overload for 'call' expression.", + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: "Cannot invoke an expression whose type lacks a call signature.", + Calls_to_super_are_only_valid_inside_a_class: "Calls to 'super' are only valid inside a class.", + Generic_type_0_requires_1_type_argument_s: "Generic type '{0}' requires {1} type argument(s).", + Type_of_array_literal_cannot_be_determined_Best_common_type_could_not_be_found_for_array_elements: "Type of array literal cannot be determined. Best common type could not be found for array elements.", + Could_not_find_enclosing_symbol_for_dotted_name_0: "Could not find enclosing symbol for dotted name '{0}'.", + The_property_0_does_not_exist_on_value_of_type_1: "The property '{0}' does not exist on value of type '{1}'.", + Could_not_find_symbol_0: "Could not find symbol '{0}'.", + get_and_set_accessor_must_have_the_same_type: "'get' and 'set' accessor must have the same type.", + this_cannot_be_referenced_in_current_location: "'this' cannot be referenced in current location.", + Static_members_cannot_reference_class_type_parameters: "Static members cannot reference class type parameters.", + Class_0_is_recursively_referenced_as_a_base_type_of_itself: "Class '{0}' is recursively referenced as a base type of itself.", + Interface_0_is_recursively_referenced_as_a_base_type_of_itself: "Interface '{0}' is recursively referenced as a base type of itself.", + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class.", + super_cannot_be_referenced_in_non_derived_classes: "'super' cannot be referenced in non-derived classes.", + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.", + Constructors_for_derived_classes_must_contain_a_super_call: "Constructors for derived classes must contain a 'super' call.", + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: "Super calls are not permitted outside constructors or in nested functions inside constructors.", + _0_1_is_inaccessible: "'{0}.{1}' is inaccessible.", + this_cannot_be_referenced_within_module_bodies: "'this' cannot be referenced within module bodies.", + Invalid_expression_types_not_known_to_support_the_addition_operator: "Invalid '+' expression - types not known to support the addition operator.", + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.", + The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type_any_number_or_an_enum_type: "The type of a unary arithmetic operation operand must be of type 'any', 'number' or an enum type.", + Variable_declarations_of_a_for_statement_cannot_use_a_type_annotation: "Variable declarations of a 'for' statement cannot use a type annotation.", + Variable_declarations_of_a_for_statement_must_be_of_types_string_or_any: "Variable declarations of a 'for' statement must be of types 'string' or 'any'.", + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter.", + The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number: "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'.", + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.", + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.", + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.", + Setters_cannot_return_a_value: "Setters cannot return a value.", + Tried_to_query_type_of_uninitialized_module_0: "Tried to query type of uninitialized module '{0}'.", + Tried_to_set_variable_type_to_uninitialized_module_type_0: "Tried to set variable type to uninitialized module type '{0}'.", + Type_0_does_not_have_type_parameters: "Type '{0}' does not have type parameters.", + Getters_must_return_a_value: "Getters must return a value.", + Getter_and_setter_accessors_do_not_agree_in_visibility: "Getter and setter accessors do not agree in visibility.", + Invalid_left_hand_side_of_assignment_expression: "Invalid left-hand side of assignment expression.", + Function_declared_a_non_void_return_type_but_has_no_return_expression: "Function declared a non-void return type, but has no return expression.", + Cannot_resolve_return_type_reference: "Cannot resolve return type reference.", + Constructors_cannot_have_a_return_type_of_void: "Constructors cannot have a return type of 'void'.", + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'.", + All_symbols_within_a_with_block_will_be_resolved_to_any: "All symbols within a with block will be resolved to 'any'.", + Import_declarations_in_an_internal_module_cannot_reference_an_external_module: "Import declarations in an internal module cannot reference an external module.", + Class_0_declares_interface_1_but_does_not_implement_it_NL_2: "Class {0} declares interface {1} but does not implement it:{NL}{2}", + Class_0_declares_class_1_as_an_interface_but_does_not_implement_it_NL_2: "Class {0} declares class {1} as an interface but does not implement it:{NL}{2}", + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: "The operand of an increment or decrement operator must be a variable, property or indexer.", + this_cannot_be_referenced_in_static_initializers_in_a_class_body: "'this' cannot be referenced in static initializers in a class body.", + Class_0_cannot_extend_class_1_NL_2: "Class '{0}' cannot extend class '{1}':{NL}{2}", + Interface_0_cannot_extend_class_1_NL_2: "Interface '{0}' cannot extend class '{1}':{NL}{2}", + Interface_0_cannot_extend_interface_1_NL_2: "Interface '{0}' cannot extend interface '{1}':{NL}{2}", + Duplicate_overload_signature_for_0: "Duplicate overload signature for '{0}'.", + Duplicate_constructor_overload_signature: "Duplicate constructor overload signature.", + Duplicate_overload_call_signature: "Duplicate overload call signature.", + Duplicate_overload_construct_signature: "Duplicate overload construct signature.", + Overload_signature_is_not_compatible_with_function_definition: "Overload signature is not compatible with function definition.", + Overload_signature_is_not_compatible_with_function_definition_NL_0: "Overload signature is not compatible with function definition:{NL}{0}", + Overload_signatures_must_all_be_public_or_private: "Overload signatures must all be public or private.", + Overload_signatures_must_all_be_exported_or_not_exported: "Overload signatures must all be exported or not exported.", + Overload_signatures_must_all_be_ambient_or_non_ambient: "Overload signatures must all be ambient or non-ambient.", + Overload_signatures_must_all_be_optional_or_required: "Overload signatures must all be optional or required.", + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: "Specialized overload signature is not assignable to any non-specialized signature.", + this_cannot_be_referenced_in_constructor_arguments: "'this' cannot be referenced in constructor arguments.", + Instance_member_cannot_be_accessed_off_a_class: "Instance member cannot be accessed off a class.", + Untyped_function_calls_may_not_accept_type_arguments: "Untyped function calls may not accept type arguments.", + Non_generic_functions_may_not_accept_type_arguments: "Non-generic functions may not accept type arguments.", + A_generic_type_may_not_reference_itself_with_a_wrapped_form_of_its_own_type_parameters: "A generic type may not reference itself with a wrapped form of its own type parameters.", + Rest_parameters_must_be_array_types: "Rest parameters must be array types.", + Overload_signature_implementation_cannot_use_specialized_type: "Overload signature implementation cannot use specialized type.", + Export_assignments_may_only_be_used_at_the_top_level_of_external_modules: "Export assignments may only be used at the top-level of external modules.", + Export_assignments_may_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: "Export assignments may only be made with variables, functions, classes, interfaces, enums and internal modules.", + Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword: "Only public methods of the base class are accessible via the 'super' keyword.", + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1: "Numeric indexer type '{0}' must be assignable to string indexer type '{1}'.", + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1_NL_2: "Numeric indexer type '{0}' must be assignable to string indexer type '{1}':{NL}{2}", + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0: "All numerically named properties must be assignable to numeric indexer type '{0}'.", + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0_NL_1: "All numerically named properties must be assignable to numeric indexer type '{0}':{NL}{1}", + All_named_properties_must_be_assignable_to_string_indexer_type_0: "All named properties must be assignable to string indexer type '{0}'.", + All_named_properties_must_be_assignable_to_string_indexer_type_0_NL_1: "All named properties must be assignable to string indexer type '{0}':{NL}{1}", + Generic_type_references_must_include_all_type_arguments: "Generic type references must include all type arguments.", + Default_arguments_are_only_allowed_in_implementation: "Default arguments are only allowed in implementation.", + Overloads_cannot_differ_only_by_return_type: "Overloads cannot differ only by return type.", + Function_expression_declared_a_non_void_return_type_but_has_no_return_expression: "Function expression declared a non-void return type, but has no return expression.", + Import_declaration_referencing_identifier_from_internal_module_can_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: "Import declaration referencing identifier from internal module can only be made with variables, functions, classes, interfaces, enums and internal modules.", + Could_not_find_symbol_0_in_module_1: "Could not find symbol '{0}' in module '{1}'.", + Unable_to_resolve_module_reference_0: "Unable to resolve module reference '{0}'.", + Could_not_find_module_0_in_module_1: "Could not find module '{0}' in module '{1}'.", + Exported_import_declaration_0_is_assigned_value_with_type_that_has_or_is_using_private_type_1: "Exported import declaration '{0}' is assigned value with type that has or is using private type '{1}'.", + Exported_import_declaration_0_is_assigned_value_with_type_that_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned value with type that is using inaccessible module '{1}'.", + Exported_import_declaration_0_is_assigned_type_that_has_or_is_using_private_type_1: "Exported import declaration '{0}' is assigned type that has or is using private type '{1}'.", + Exported_import_declaration_0_is_assigned_type_that_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned type that is using inaccessible module '{1}'.", + Exported_import_declaration_0_is_assigned_container_that_is_or_is_using_inaccessible_module_1: "Exported import declaration '{0}' is assigned container that is or is using inaccessible module '{1}'.", + Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_1: "Type name '{0}' in extends clause does not reference constructor function for '{1}'.", + Internal_module_reference_0_in_import_declaration_does_not_reference_module_instance_for_1: "Internal module reference '{0}' in import declaration does not reference module instance for '{1}'.", + Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2: "Module '{0}' cannot merge with previous declaration of '{1}' in a different file '{2}'.", + Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':{NL}{3}", + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it.", + Ambient_external_module_declaration_cannot_be_reopened: "Ambient external module declaration cannot be reopened.", + All_declarations_of_merged_declaration_0_must_be_exported_or_not_exported: "All declarations of merged declaration '{0}' must be exported or not exported.", + super_cannot_be_referenced_in_constructor_arguments: "'super' cannot be referenced in constructor arguments.", + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: "Return type of constructor signature must be assignable to the instance type of the class.", + Ambient_external_module_declaration_must_be_defined_in_global_context: "Ambient external module declaration must be defined in global context.", + Ambient_external_module_declaration_cannot_specify_relative_module_name: "Ambient external module declaration cannot specify relative module name.", + Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name: "Import declaration in an ambient external module declaration cannot reference external module through relative external module name.", + Could_not_find_the_best_common_type_of_types_of_all_return_statement_expressions: "Could not find the best common type of types of all return statement expressions.", + Import_declaration_cannot_refer_to_external_module_reference_when_noResolve_option_is_set: "Import declaration cannot refer to external module reference when --noResolve option is set.", + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference.", + continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: "'continue' statement can only be used within an enclosing iteration statement.", + break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: "'break' statement can only be used within an enclosing iteration or switch statement.", + Jump_target_not_found: "Jump target not found.", + Jump_target_cannot_cross_function_boundary: "Jump target cannot cross function boundary.", + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference.", + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference.", + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: "Expression resolves to '_super' that compiler uses to capture base class reference.", + TypeParameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of call signature from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of public static method from exported class has or is using private type '{1}'.", + TypeParameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of public method from exported class has or is using private type '{1}'.", + TypeParameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of method from exported interface has or is using private type '{1}'.", + TypeParameter_0_of_exported_function_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported function has or is using private type '{1}'.", + TypeParameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.", + TypeParameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of call signature from exported interface is using inaccessible module {1}", + TypeParameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of public static method from exported class is using inaccessible module {1}.", + TypeParameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of public method from exported class is using inaccessible module {1}.", + TypeParameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of method from exported interface is using inaccessible module {1}.", + TypeParameter_0_of_exported_function_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported function is using inaccessible module {1}.", + TypeParameter_0_of_exported_class_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported class has or is using private type '{1}'.", + TypeParameter_0_of_exported_interface_has_or_is_using_private_type_1: "TypeParameter '{0}' of exported interface has or is using private type '{1}'.", + TypeParameter_0_of_exported_class_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported class is using inaccessible module {1}.", + TypeParameter_0_of_exported_interface_is_using_inaccessible_module_1: "TypeParameter '{0}' of exported interface is using inaccessible module {1}.", + Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter: "Duplicate identifier '_i'. Compiler uses '_i' to initialize rest parameter.", + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters.", + Type_of_conditional_0_must_be_identical_to_1_or_2: "Type of conditional '{0}' must be identical to '{1}' or '{2}'.", + Type_of_conditional_0_must_be_identical_to_1_2_or_3: "Type of conditional '{0}' must be identical to '{1}', '{2}' or '{3}'.", + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of an external module.", + Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.", + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.", + Parameter_0_cannot_be_referenced_in_its_initializer: "Parameter '{0}' cannot be referenced in its initializer.", + Duplicate_string_index_signature: "Duplicate string index signature.", + Duplicate_number_index_signature: "Duplicate number index signature.", + All_declarations_of_an_interface_must_have_identical_type_parameters: "All declarations of an interface must have identical type parameters.", + Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter: "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter.", + Type_0_is_missing_property_1_from_type_2: "Type '{0}' is missing property '{1}' from type '{2}'.", + Types_of_property_0_of_types_1_and_2_are_incompatible: "Types of property '{0}' of types '{1}' and '{2}' are incompatible.", + Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3: "Types of property '{0}' of types '{1}' and '{2}' are incompatible:{NL}{3}", + Property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2: "Property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.", + Property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2: "Property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.", + Types_0_and_1_define_property_2_as_private: "Types '{0}' and '{1}' define property '{2}' as private.", + Call_signatures_of_types_0_and_1_are_incompatible: "Call signatures of types '{0}' and '{1}' are incompatible.", + Call_signatures_of_types_0_and_1_are_incompatible_NL_2: "Call signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Type_0_requires_a_call_signature_but_type_1_lacks_one: "Type '{0}' requires a call signature, but type '{1}' lacks one.", + Construct_signatures_of_types_0_and_1_are_incompatible: "Construct signatures of types '{0}' and '{1}' are incompatible.", + Construct_signatures_of_types_0_and_1_are_incompatible_NL_2: "Construct signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Type_0_requires_a_construct_signature_but_type_1_lacks_one: "Type '{0}' requires a construct signature, but type '{1}' lacks one.", + Index_signatures_of_types_0_and_1_are_incompatible: "Index signatures of types '{0}' and '{1}' are incompatible.", + Index_signatures_of_types_0_and_1_are_incompatible_NL_2: "Index signatures of types '{0}' and '{1}' are incompatible:{NL}{2}", + Call_signature_expects_0_or_fewer_parameters: "Call signature expects {0} or fewer parameters.", + Could_not_apply_type_0_to_argument_1_which_is_of_type_2: "Could not apply type '{0}' to argument {1} which is of type '{2}'.", + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function.", + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.", + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor.", + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.", + Types_of_static_property_0_of_class_1_and_class_2_are_incompatible: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible.", + Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3: "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible:{NL}{3}", + Type_reference_cannot_refer_to_container_0: "Type reference cannot refer to container '{0}'.", + Type_reference_must_refer_to_type: "Type reference must refer to type.", + In_enums_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_the_first_enum_element: "In enums with multiple declarations only one declaration can omit an initializer for the first enum element.", + _0_overload_s: " (+ {0} overload(s))", + Variable_declaration_cannot_have_the_same_name_as_an_import_declaration: "Variable declaration cannot have the same name as an import declaration.", + Signature_expected_0_type_arguments_got_1_instead: "Signature expected {0} type arguments, got {1} instead.", + Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2: "Property '{0}' defined as optional in type '{1}', but is required in type '{2}'.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_do_not_refer_to_same_named_type: "Types '{0}' and '{1}' originating in infinitely expanding type reference do not refer to same named type.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments: "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments.", + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2: "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments:{NL}{2}", + Named_properties_0_of_types_1_and_2_are_not_identical: "Named properties '{0}' of types '{1}' and '{2}' are not identical.", + Types_of_string_indexer_of_types_0_and_1_are_not_identical: "Types of string indexer of types '{0}' and '{1}' are not identical.", + Types_of_number_indexer_of_types_0_and_1_are_not_identical: "Types of number indexer of types '{0}' and '{1}' are not identical.", + Type_of_number_indexer_in_type_0_is_not_assignable_to_string_indexer_type_in_type_1_NL_2: "Type of number indexer in type '{0}' is not assignable to string indexer type in type '{1}'.{NL}{2}", + Type_of_property_0_in_type_1_is_not_assignable_to_string_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not assignable to string indexer type in type '{2}'.{NL}{3}", + Type_of_property_0_in_type_1_is_not_assignable_to_number_indexer_type_in_type_2_NL_3: "Type of property '{0}' in type '{1}' is not assignable to number indexer type in type '{2}'.{NL}{3}", + Static_property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2: "Static property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.", + Static_property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2: "Static property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.", + Types_0_and_1_define_static_property_2_as_private: "Types '{0}' and '{1}' define static property '{2}' as private.", + Current_host_does_not_support_0_option: "Current host does not support '{0}' option.", + ECMAScript_target_version_0_not_supported_Specify_a_valid_target_version_1_default_or_2: "ECMAScript target version '{0}' not supported. Specify a valid target version: '{1}' (default), or '{2}'", + Module_code_generation_0_not_supported: "Module code generation '{0}' not supported.", + Could_not_find_file_0: "Could not find file: '{0}'.", + A_file_cannot_have_a_reference_to_itself: "A file cannot have a reference to itself.", + Cannot_resolve_referenced_file_0: "Cannot resolve referenced file: '{0}'.", + Cannot_find_the_common_subdirectory_path_for_the_input_files: "Cannot find the common subdirectory path for the input files.", + Emit_Error_0: "Emit Error: {0}.", + Cannot_read_file_0_1: "Cannot read file '{0}': {1}", + Unsupported_file_encoding: "Unsupported file encoding.", + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: "Locale must be of the form or -. For example '{0}' or '{1}'.", + Unsupported_locale_0: "Unsupported locale: '{0}'.", + Execution_Failed_NL: "Execution Failed.{NL}", + Invalid_call_to_up: "Invalid call to 'up'", + Invalid_call_to_down: "Invalid call to 'down'", + Base64_value_0_finished_with_a_continuation_bit: "Base64 value '{0}' finished with a continuation bit.", + Unknown_option_0: "Unknown option '{0}'", + Expected_0_arguments_to_message_got_1_instead: "Expected {0} arguments to message, got {1} instead.", + Expected_the_message_0_to_have_1_arguments_but_it_had_2: "Expected the message '{0}' to have {1} arguments, but it had {2}", + Could_not_delete_file_0: "Could not delete file '{0}'", + Could_not_create_directory_0: "Could not create directory '{0}'", + Error_while_executing_file_0: "Error while executing file '{0}': ", + Cannot_compile_external_modules_unless_the_module_flag_is_provided: "Cannot compile external modules unless the '--module' flag is provided.", + Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: "Option mapRoot cannot be specified without specifying sourcemap option.", + Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: "Option sourceRoot cannot be specified without specifying sourcemap option.", + Options_mapRoot_and_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: "Options mapRoot and sourceRoot cannot be specified without specifying sourcemap option.", + Option_0_specified_without_1: "Option '{0}' specified without '{1}'", + codepage_option_not_supported_on_current_platform: "'codepage' option not supported on current platform.", + Concatenate_and_emit_output_to_single_file: "Concatenate and emit output to single file.", + Generates_corresponding_0_file: "Generates corresponding {0} file.", + Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: "Specifies the location where debugger should locate map files instead of generated locations.", + Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: "Specifies the location where debugger should locate TypeScript files instead of source locations.", + Watch_input_files: "Watch input files.", + Redirect_output_structure_to_the_directory: "Redirect output structure to the directory.", + Do_not_emit_comments_to_output: "Do not emit comments to output.", + Skip_resolution_and_preprocessing: "Skip resolution and preprocessing.", + Specify_ECMAScript_target_version_0_default_or_1: "Specify ECMAScript target version: '{0}' (default), or '{1}'", + Specify_module_code_generation_0_or_1: "Specify module code generation: '{0}' or '{1}'", + Print_this_message: "Print this message.", + Print_the_compiler_s_version_0: "Print the compiler's version: {0}", + Allow_use_of_deprecated_0_keyword_when_referencing_an_external_module: "Allow use of deprecated '{0}' keyword when referencing an external module.", + Specify_locale_for_errors_and_messages_For_example_0_or_1: "Specify locale for errors and messages. For example '{0}' or '{1}'", + Syntax_0: "Syntax: {0}", + options: "options", + file1: "file", + Examples: "Examples:", + Options: "Options:", + Insert_command_line_options_and_files_from_a_file: "Insert command line options and files from a file.", + Version_0: "Version {0}", + Use_the_0_flag_to_see_options: "Use the '{0}' flag to see options.", + NL_Recompiling_0: "{NL}Recompiling ({0}):", + STRING: "STRING", + KIND: "KIND", + file2: "FILE", + VERSION: "VERSION", + LOCATION: "LOCATION", + DIRECTORY: "DIRECTORY", + NUMBER: "NUMBER", + Specify_the_codepage_to_use_when_opening_source_files: "Specify the codepage to use when opening source files.", + Additional_locations: "Additional locations:", + This_version_of_the_Javascript_runtime_does_not_support_the_0_function: "This version of the Javascript runtime does not support the '{0}' function.", + Unknown_rule: "Unknown rule.", + Invalid_line_number_0: "Invalid line number ({0})", + Warn_on_expressions_and_declarations_with_an_implied_any_type: "Warn on expressions and declarations with an implied 'any' type.", + Variable_0_implicitly_has_an_any_type: "Variable '{0}' implicitly has an 'any' type.", + Parameter_0_of_1_implicitly_has_an_any_type: "Parameter '{0}' of '{1}' implicitly has an 'any' type.", + Parameter_0_of_function_type_implicitly_has_an_any_type: "Parameter '{0}' of function type implicitly has an 'any' type.", + Member_0_of_object_type_implicitly_has_an_any_type: "Member '{0}' of object type implicitly has an 'any' type.", + new_expression_which_lacks_a_constructor_signature_implicitly_has_an_any_type: "'new' expression, which lacks a constructor signature, implicitly has an 'any' type.", + _0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "'{0}', which lacks return-type annotation, implicitly has an 'any' return type.", + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Function expression, which lacks return-type annotation, implicitly has an 'any' return type.", + Parameter_0_of_lambda_function_implicitly_has_an_any_type: "Parameter '{0}' of lambda function implicitly has an 'any' type.", + Constructor_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Constructor signature, which lacks return-type annotation, implicitly has an 'any' return type.", + Lambda_Function_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: "Lambda Function, which lacks return-type annotation, implicitly has an 'any' return type.", + Array_Literal_implicitly_has_an_any_type_from_widening: "Array Literal implicitly has an 'any' type from widening.", + _0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type: "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type.", + Index_signature_of_object_type_implicitly_has_an_any_type: "Index signature of object type implicitly has an 'any' type.", + Object_literal_s_property_0_implicitly_has_an_any_type_from_widening: "Object literal's property '{0}' implicitly has an 'any' type from widening." + }; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ArrayUtilities = (function () { + function ArrayUtilities() { + } + ArrayUtilities.isArray = function (value) { + return Object.prototype.toString.apply(value, []) === '[object Array]'; + }; + + ArrayUtilities.sequenceEquals = function (array1, array2, equals) { + if (array1 === array2) { + return true; + } + + if (array1 === null || array2 === null) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0, n = array1.length; i < n; i++) { + if (!equals(array1[i], array2[i])) { + return false; + } + } + + return true; + }; + + ArrayUtilities.contains = function (array, value) { + for (var i = 0; i < array.length; i++) { + if (array[i] === value) { + return true; + } + } + + return false; + }; + + ArrayUtilities.groupBy = function (array, func) { + var result = {}; + + for (var i = 0, n = array.length; i < n; i++) { + var v = array[i]; + var k = func(v); + + var list = result[k] || []; + list.push(v); + result[k] = list; + } + + return result; + }; + + ArrayUtilities.distinct = function (array, equalsFn) { + var result = []; + + for (var i = 0, n = array.length; i < n; i++) { + var current = array[i]; + for (var j = 0; j < result.length; j++) { + if (equalsFn(result[j], current)) { + break; + } + } + + if (j === result.length) { + result.push(current); + } + } + + return result; + }; + + ArrayUtilities.min = function (array, func) { + var min = func(array[0]); + + for (var i = 1; i < array.length; i++) { + var next = func(array[i]); + if (next < min) { + min = next; + } + } + + return min; + }; + + ArrayUtilities.max = function (array, func) { + var max = func(array[0]); + + for (var i = 1; i < array.length; i++) { + var next = func(array[i]); + if (next > max) { + max = next; + } + } + + return max; + }; + + ArrayUtilities.last = function (array) { + if (array.length === 0) { + throw TypeScript.Errors.argumentOutOfRange('array'); + } + + return array[array.length - 1]; + }; + + ArrayUtilities.lastOrDefault = function (array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var v = array[i]; + if (predicate(v, i)) { + return v; + } + } + + return null; + }; + + ArrayUtilities.firstOrDefault = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + var value = array[i]; + if (func(value, i)) { + return value; + } + } + + return null; + }; + + ArrayUtilities.first = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + var value = array[i]; + if (!func || func(value, i)) { + return value; + } + } + + throw TypeScript.Errors.invalidOperation(); + }; + + ArrayUtilities.sum = function (array, func) { + var result = 0; + + for (var i = 0, n = array.length; i < n; i++) { + result += func(array[i]); + } + + return result; + }; + + ArrayUtilities.select = function (values, func) { + var result = new Array(values.length); + + for (var i = 0; i < values.length; i++) { + result[i] = func(values[i]); + } + + return result; + }; + + ArrayUtilities.where = function (values, func) { + var result = new Array(); + + for (var i = 0; i < values.length; i++) { + if (func(values[i])) { + result.push(values[i]); + } + } + + return result; + }; + + ArrayUtilities.any = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + if (func(array[i])) { + return true; + } + } + + return false; + }; + + ArrayUtilities.all = function (array, func) { + for (var i = 0, n = array.length; i < n; i++) { + if (!func(array[i])) { + return false; + } + } + + return true; + }; + + ArrayUtilities.binarySearch = function (array, value) { + var low = 0; + var high = array.length - 1; + + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midValue = array[middle]; + + if (midValue === value) { + return middle; + } else if (midValue > value) { + high = middle - 1; + } else { + low = middle + 1; + } + } + + return ~low; + }; + + ArrayUtilities.createArray = function (length, defaultValue) { + var result = new Array(length); + for (var i = 0; i < length; i++) { + result[i] = defaultValue; + } + + return result; + }; + + ArrayUtilities.grow = function (array, length, defaultValue) { + var count = length - array.length; + for (var i = 0; i < count; i++) { + array.push(defaultValue); + } + }; + + ArrayUtilities.copy = function (sourceArray, sourceIndex, destinationArray, destinationIndex, length) { + for (var i = 0; i < length; i++) { + destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i]; + } + }; + + ArrayUtilities.indexOf = function (array, predicate) { + for (var i = 0, n = array.length; i < n; i++) { + if (predicate(array[i])) { + return i; + } + } + + return -1; + }; + return ArrayUtilities; + })(); + TypeScript.ArrayUtilities = ArrayUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (BitVector) { + var pool = []; + var Constants; + (function (Constants) { + Constants[Constants["MaxBitsPerEncodedNumber"] = 30] = "MaxBitsPerEncodedNumber"; + Constants[Constants["BitsPerEncodedBiStateValue"] = 1] = "BitsPerEncodedBiStateValue"; + + Constants[Constants["BitsPerEncodedTriStateValue"] = 2] = "BitsPerEncodedTriStateValue"; + + Constants[Constants["BiStateEncodedTrue"] = 1] = "BiStateEncodedTrue"; + Constants[Constants["BiStateClearBitsMask"] = 1] = "BiStateClearBitsMask"; + + Constants[Constants["TriStateEncodedFalse"] = 1] = "TriStateEncodedFalse"; + Constants[Constants["TriStateEncodedTrue"] = 2] = "TriStateEncodedTrue"; + Constants[Constants["TriStateClearBitsMask"] = 3] = "TriStateClearBitsMask"; + })(Constants || (Constants = {})); + + var BitVectorImpl = (function () { + function BitVectorImpl(allowUndefinedValues) { + this.allowUndefinedValues = allowUndefinedValues; + this.isReleased = false; + this.bits = []; + } + BitVectorImpl.prototype.computeTriStateArrayIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 2 /* BitsPerEncodedTriStateValue */; + + return (index / encodedValuesPerNumber) >>> 0; + }; + + BitVectorImpl.prototype.computeBiStateArrayIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 1 /* BitsPerEncodedBiStateValue */; + + return (index / encodedValuesPerNumber) >>> 0; + }; + + BitVectorImpl.prototype.computeTriStateEncodedValueIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 2 /* BitsPerEncodedTriStateValue */; + + return (index % encodedValuesPerNumber) * 2 /* BitsPerEncodedTriStateValue */; + }; + + BitVectorImpl.prototype.computeBiStateEncodedValueIndex = function (index) { + var encodedValuesPerNumber = 30 /* MaxBitsPerEncodedNumber */ / 1 /* BitsPerEncodedBiStateValue */; + + return (index % encodedValuesPerNumber) * 1 /* BitsPerEncodedBiStateValue */; + }; + + BitVectorImpl.prototype.valueAt = function (index) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + if (this.allowUndefinedValues) { + var arrayIndex = this.computeTriStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + return undefined; + } + + var bitIndex = this.computeTriStateEncodedValueIndex(index); + if (encoded & (2 /* TriStateEncodedTrue */ << bitIndex)) { + return true; + } else if (encoded & (1 /* TriStateEncodedFalse */ << bitIndex)) { + return false; + } else { + return undefined; + } + } else { + var arrayIndex = this.computeBiStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + return false; + } + + var bitIndex = this.computeBiStateEncodedValueIndex(index); + if (encoded & (1 /* BiStateEncodedTrue */ << bitIndex)) { + return true; + } else { + return false; + } + } + }; + + BitVectorImpl.prototype.setValueAt = function (index, value) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + if (this.allowUndefinedValues) { + TypeScript.Debug.assert(value === true || value === false || value === undefined, "value must only be true, false or undefined."); + + var arrayIndex = this.computeTriStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + if (value === undefined) { + return; + } + + encoded = 0; + } + + var bitIndex = this.computeTriStateEncodedValueIndex(index); + + var clearMask = ~(3 /* TriStateClearBitsMask */ << bitIndex); + encoded = encoded & clearMask; + + if (value === true) { + encoded = encoded | (2 /* TriStateEncodedTrue */ << bitIndex); + } else if (value === false) { + encoded = encoded | (1 /* TriStateEncodedFalse */ << bitIndex); + } + + this.bits[arrayIndex] = encoded; + } else { + TypeScript.Debug.assert(value === true || value === false, "value must only be true or false."); + + var arrayIndex = this.computeBiStateArrayIndex(index); + var encoded = this.bits[arrayIndex]; + if (encoded === undefined) { + if (value === false) { + return; + } + + encoded = 0; + } + + var bitIndex = this.computeBiStateEncodedValueIndex(index); + + encoded = encoded & ~(1 /* BiStateClearBitsMask */ << bitIndex); + + if (value) { + encoded = encoded | (1 /* BiStateEncodedTrue */ << bitIndex); + } + + this.bits[arrayIndex] = encoded; + } + }; + + BitVectorImpl.prototype.release = function () { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + this.isReleased = true; + this.bits.length = 0; + pool.push(this); + }; + return BitVectorImpl; + })(); + + function getBitVector(allowUndefinedValues) { + if (pool.length === 0) { + return new BitVectorImpl(allowUndefinedValues); + } + + var vector = pool.pop(); + vector.isReleased = false; + vector.allowUndefinedValues = allowUndefinedValues; + + return vector; + } + BitVector.getBitVector = getBitVector; + })(TypeScript.BitVector || (TypeScript.BitVector = {})); + var BitVector = TypeScript.BitVector; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (BitMatrix) { + var pool = []; + + var BitMatrixImpl = (function () { + function BitMatrixImpl(allowUndefinedValues) { + this.allowUndefinedValues = allowUndefinedValues; + this.isReleased = false; + this.vectors = []; + } + BitMatrixImpl.prototype.valueAt = function (x, y) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + var vector = this.vectors[x]; + if (!vector) { + return this.allowUndefinedValues ? undefined : false; + } + + return vector.valueAt(y); + }; + + BitMatrixImpl.prototype.setValueAt = function (x, y, value) { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + var vector = this.vectors[x]; + if (!vector) { + if (value === undefined) { + return; + } + + vector = TypeScript.BitVector.getBitVector(this.allowUndefinedValues); + this.vectors[x] = vector; + } + + vector.setValueAt(y, value); + }; + + BitMatrixImpl.prototype.release = function () { + TypeScript.Debug.assert(!this.isReleased, "Should not use a released bitvector"); + this.isReleased = true; + + for (var name in this.vectors) { + if (this.vectors.hasOwnProperty(name)) { + var vector = this.vectors[name]; + vector.release(); + } + } + + this.vectors.length = 0; + pool.push(this); + }; + return BitMatrixImpl; + })(); + + function getBitMatrix(allowUndefinedValues) { + if (pool.length === 0) { + return new BitMatrixImpl(allowUndefinedValues); + } + + var matrix = pool.pop(); + matrix.isReleased = false; + matrix.allowUndefinedValues = allowUndefinedValues; + + return matrix; + } + BitMatrix.getBitMatrix = getBitMatrix; + })(TypeScript.BitMatrix || (TypeScript.BitMatrix = {})); + var BitMatrix = TypeScript.BitMatrix; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Constants) { + Constants[Constants["Max31BitInteger"] = 1073741823] = "Max31BitInteger"; + Constants[Constants["Min31BitInteger"] = -1073741824] = "Min31BitInteger"; + })(TypeScript.Constants || (TypeScript.Constants = {})); + var Constants = TypeScript.Constants; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(TypeScript.AssertionLevel || (TypeScript.AssertionLevel = {})); + var AssertionLevel = TypeScript.AssertionLevel; + + var Debug = (function () { + function Debug() { + } + Debug.shouldAssert = function (level) { + return this.currentAssertionLevel >= level; + }; + + Debug.assert = function (expression, message, verboseDebugInfo) { + if (typeof message === "undefined") { message = ""; } + if (typeof verboseDebugInfo === "undefined") { verboseDebugInfo = null; } + if (!expression) { + var verboseDebugString = ""; + if (verboseDebugInfo) { + verboseDebugString = "\r\nVerbose Debug Information:" + verboseDebugInfo(); + } + + throw new Error("Debug Failure. False expression: " + message + verboseDebugString); + } + }; + + Debug.fail = function (message) { + Debug.assert(false, message); + }; + Debug.currentAssertionLevel = 0 /* None */; + return Debug; + })(); + TypeScript.Debug = Debug; +})(TypeScript || (TypeScript = {})); +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var TypeScript; +(function (TypeScript) { + TypeScript.LocalizedDiagnosticMessages = null; + + var Location = (function () { + function Location(fileName, lineMap, start, length) { + this._fileName = fileName; + this._lineMap = lineMap; + this._start = start; + this._length = length; + } + Location.prototype.fileName = function () { + return this._fileName; + }; + + Location.prototype.lineMap = function () { + return this._lineMap; + }; + + Location.prototype.line = function () { + return this._lineMap ? this._lineMap.getLineNumberFromPosition(this.start()) : 0; + }; + + Location.prototype.character = function () { + return this._lineMap ? this._lineMap.getLineAndCharacterFromPosition(this.start()).character() : 0; + }; + + Location.prototype.start = function () { + return this._start; + }; + + Location.prototype.length = function () { + return this._length; + }; + + Location.equals = function (location1, location2) { + return location1._fileName === location2._fileName && location1._start === location2._start && location1._length === location2._length; + }; + return Location; + })(); + TypeScript.Location = Location; + + var Diagnostic = (function (_super) { + __extends(Diagnostic, _super); + function Diagnostic(fileName, lineMap, start, length, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + _super.call(this, fileName, lineMap, start, length); + this._diagnosticKey = diagnosticKey; + this._arguments = (_arguments && _arguments.length > 0) ? _arguments : null; + this._additionalLocations = (additionalLocations && additionalLocations.length > 0) ? additionalLocations : null; + } + Diagnostic.prototype.toJSON = function (key) { + var result = {}; + result.start = this.start(); + result.length = this.length(); + + result.diagnosticCode = this._diagnosticKey; + + var _arguments = this.arguments(); + if (_arguments && _arguments.length > 0) { + result.arguments = _arguments; + } + + return result; + }; + + Diagnostic.prototype.diagnosticKey = function () { + return this._diagnosticKey; + }; + + Diagnostic.prototype.arguments = function () { + return this._arguments; + }; + + Diagnostic.prototype.text = function () { + return TypeScript.getLocalizedText(this._diagnosticKey, this._arguments); + }; + + Diagnostic.prototype.message = function () { + return TypeScript.getDiagnosticMessage(this._diagnosticKey, this._arguments); + }; + + Diagnostic.prototype.additionalLocations = function () { + return this._additionalLocations || []; + }; + + Diagnostic.equals = function (diagnostic1, diagnostic2) { + return Location.equals(diagnostic1, diagnostic2) && diagnostic1._diagnosticKey === diagnostic2._diagnosticKey && TypeScript.ArrayUtilities.sequenceEquals(diagnostic1._arguments, diagnostic2._arguments, function (v1, v2) { + return v1 === v2; + }); + }; + + Diagnostic.prototype.info = function () { + return getDiagnosticInfoFromKey(this.diagnosticKey()); + }; + return Diagnostic; + })(Location); + TypeScript.Diagnostic = Diagnostic; + + function newLine() { + return TypeScript.Environment ? TypeScript.Environment.newLine : "\r\n"; + } + TypeScript.newLine = newLine; + + function getLargestIndex(diagnostic) { + var largest = -1; + var regex = /\{(\d+)\}/g; + + var match; + while (match = regex.exec(diagnostic)) { + var val = parseInt(match[1]); + if (!isNaN(val) && val > largest) { + largest = val; + } + } + + return largest; + } + + function getDiagnosticInfoFromKey(diagnosticKey) { + var result = TypeScript.diagnosticInformationMap[diagnosticKey]; + TypeScript.Debug.assert(result); + return result; + } + + function getLocalizedText(diagnosticKey, args) { + if (TypeScript.LocalizedDiagnosticMessages) { + } + + var diagnosticMessageText = TypeScript.LocalizedDiagnosticMessages ? TypeScript.LocalizedDiagnosticMessages[diagnosticKey] : diagnosticKey; + TypeScript.Debug.assert(diagnosticMessageText !== undefined && diagnosticMessageText !== null); + + var actualCount = args ? args.length : 0; + + var expectedCount = 1 + getLargestIndex(diagnosticKey); + + if (expectedCount !== actualCount) { + throw new Error(getLocalizedText(TypeScript.DiagnosticCode.Expected_0_arguments_to_message_got_1_instead, [expectedCount, actualCount])); + } + + var valueCount = 1 + getLargestIndex(diagnosticMessageText); + if (valueCount !== expectedCount) { + throw new Error(getLocalizedText(TypeScript.DiagnosticCode.Expected_the_message_0_to_have_1_arguments_but_it_had_2, [diagnosticMessageText, expectedCount, valueCount])); + } + + diagnosticMessageText = diagnosticMessageText.replace(/{(\d+)}/g, function (match, num) { + return typeof args[num] !== 'undefined' ? args[num] : match; + }); + + diagnosticMessageText = diagnosticMessageText.replace(/{(NL)}/g, function (match) { + return TypeScript.newLine(); + }); + + return diagnosticMessageText; + } + TypeScript.getLocalizedText = getLocalizedText; + + function getDiagnosticMessage(diagnosticKey, args) { + var diagnostic = getDiagnosticInfoFromKey(diagnosticKey); + var diagnosticMessageText = getLocalizedText(diagnosticKey, args); + + var message; + if (diagnostic.category === 1 /* Error */) { + message = getLocalizedText(TypeScript.DiagnosticCode.error_TS_0_1, [diagnostic.code, diagnosticMessageText]); + } else if (diagnostic.category === 0 /* Warning */) { + message = getLocalizedText(TypeScript.DiagnosticCode.warning_TS_0_1, [diagnostic.code, diagnosticMessageText]); + } else { + message = diagnosticMessageText; + } + + return message; + } + TypeScript.getDiagnosticMessage = getDiagnosticMessage; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Errors = (function () { + function Errors() { + } + Errors.argument = function (argument, message) { + return new Error("Invalid argument: " + argument + ". " + message); + }; + + Errors.argumentOutOfRange = function (argument) { + return new Error("Argument out of range: " + argument); + }; + + Errors.argumentNull = function (argument) { + return new Error("Argument null: " + argument); + }; + + Errors.abstract = function () { + return new Error("Operation not implemented properly by subclass."); + }; + + Errors.notYetImplemented = function () { + return new Error("Not yet implemented."); + }; + + Errors.invalidOperation = function (message) { + return new Error("Invalid operation: " + message); + }; + return Errors; + })(); + TypeScript.Errors = Errors; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Hash = (function () { + function Hash() { + } + Hash.computeFnv1aCharArrayHashCode = function (text, start, len) { + var hashCode = Hash.FNV_BASE; + var end = start + len; + + for (var i = start; i < end; i++) { + hashCode = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(hashCode ^ text[i], Hash.FNV_PRIME); + } + + return hashCode; + }; + + Hash.computeSimple31BitCharArrayHashCode = function (key, start, len) { + var hash = 0; + + for (var i = 0; i < len; i++) { + var ch = key[start + i]; + + hash = ((((hash << 5) - hash) | 0) + ch) | 0; + } + + return hash & 0x7FFFFFFF; + }; + + Hash.computeSimple31BitStringHashCode = function (key) { + var hash = 0; + + var start = 0; + var len = key.length; + + for (var i = 0; i < len; i++) { + var ch = key.charCodeAt(start + i); + + hash = ((((hash << 5) - hash) | 0) + ch) | 0; + } + + return hash & 0x7FFFFFFF; + }; + + Hash.computeMurmur2StringHashCode = function (key, seed) { + var m = 0x5bd1e995; + var r = 24; + + var numberOfCharsLeft = key.length; + var h = Math.abs(seed ^ numberOfCharsLeft); + + var index = 0; + while (numberOfCharsLeft >= 2) { + var c1 = key.charCodeAt(index); + var c2 = key.charCodeAt(index + 1); + + var k = Math.abs(c1 | (c2 << 16)); + + k = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(k, m); + k ^= k >> r; + k = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(k, m); + + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + h ^= k; + + index += 2; + numberOfCharsLeft -= 2; + } + + if (numberOfCharsLeft === 1) { + h ^= key.charCodeAt(index); + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + } + + h ^= h >> 13; + h = TypeScript.IntegerUtilities.integerMultiplyLow32Bits(h, m); + h ^= h >> 15; + + return h; + }; + + Hash.getPrime = function (min) { + for (var i = 0; i < Hash.primes.length; i++) { + var num = Hash.primes[i]; + if (num >= min) { + return num; + } + } + + throw TypeScript.Errors.notYetImplemented(); + }; + + Hash.expandPrime = function (oldSize) { + var num = oldSize << 1; + if (num > 2146435069 && 2146435069 > oldSize) { + return 2146435069; + } + return Hash.getPrime(num); + }; + + Hash.combine = function (value, currentHash) { + return (((currentHash << 5) + currentHash) + value) & 0x7FFFFFFF; + }; + Hash.FNV_BASE = 2166136261; + Hash.FNV_PRIME = 16777619; + + Hash.primes = [ + 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, + 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, + 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, + 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, + 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, + 4166287, 4999559, 5999471, 7199369]; + return Hash; + })(); + TypeScript.Hash = Hash; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Collections) { + Collections.DefaultHashTableCapacity = 1024; + + var HashTableEntry = (function () { + function HashTableEntry(Key, Value, HashCode, Next) { + this.Key = Key; + this.Value = Value; + this.HashCode = HashCode; + this.Next = Next; + } + return HashTableEntry; + })(); + + var HashTable = (function () { + function HashTable(capacity, hash) { + this.hash = hash; + this.count = 0; + var size = TypeScript.Hash.getPrime(capacity); + this.entries = TypeScript.ArrayUtilities.createArray(size, null); + } + HashTable.prototype.set = function (key, value) { + this.addOrSet(key, value, false); + }; + + HashTable.prototype.add = function (key, value) { + this.addOrSet(key, value, true); + }; + + HashTable.prototype.containsKey = function (key) { + var hashCode = this.computeHashCode(key); + var entry = this.findEntry(key, hashCode); + return entry !== null; + }; + + HashTable.prototype.get = function (key) { + var hashCode = this.computeHashCode(key); + var entry = this.findEntry(key, hashCode); + + return entry === null ? null : entry.Value; + }; + + HashTable.prototype.computeHashCode = function (key) { + var hashCode = this.hash === null ? key.hashCode : this.hash(key); + + hashCode = hashCode & 0x7FFFFFFF; + TypeScript.Debug.assert(hashCode >= 0); + + return hashCode; + }; + + HashTable.prototype.addOrSet = function (key, value, throwOnExistingEntry) { + var hashCode = this.computeHashCode(key); + + var entry = this.findEntry(key, hashCode); + if (entry !== null) { + if (throwOnExistingEntry) { + throw TypeScript.Errors.argument('key', "Key was already in table."); + } + + entry.Key = key; + entry.Value = value; + return; + } + + return this.addEntry(key, value, hashCode); + }; + + HashTable.prototype.findEntry = function (key, hashCode) { + for (var e = this.entries[hashCode % this.entries.length]; e !== null; e = e.Next) { + if (e.HashCode === hashCode && key === e.Key) { + return e; + } + } + + return null; + }; + + HashTable.prototype.addEntry = function (key, value, hashCode) { + var index = hashCode % this.entries.length; + + var e = new HashTableEntry(key, value, hashCode, this.entries[index]); + + this.entries[index] = e; + + if (this.count >= (this.entries.length / 2)) { + this.grow(); + } + + this.count++; + return e.Key; + }; + + HashTable.prototype.grow = function () { + var newSize = TypeScript.Hash.expandPrime(this.entries.length); + + var oldEntries = this.entries; + var newEntries = TypeScript.ArrayUtilities.createArray(newSize, null); + + this.entries = newEntries; + + for (var i = 0; i < oldEntries.length; i++) { + var e = oldEntries[i]; + + while (e !== null) { + var newIndex = e.HashCode % newSize; + var tmp = e.Next; + e.Next = newEntries[newIndex]; + newEntries[newIndex] = e; + e = tmp; + } + } + }; + return HashTable; + })(); + Collections.HashTable = HashTable; + + function createHashTable(capacity, hash) { + if (typeof capacity === "undefined") { capacity = Collections.DefaultHashTableCapacity; } + if (typeof hash === "undefined") { hash = null; } + return new HashTable(capacity, hash); + } + Collections.createHashTable = createHashTable; + + var currentHashCode = 1; + function identityHashCode(value) { + if (value.__hash === undefined) { + value.__hash = currentHashCode; + currentHashCode++; + } + + return value.__hash; + } + Collections.identityHashCode = identityHashCode; + })(TypeScript.Collections || (TypeScript.Collections = {})); + var Collections = TypeScript.Collections; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + TypeScript.nodeMakeDirectoryTime = 0; + TypeScript.nodeCreateBufferTime = 0; + TypeScript.nodeWriteFileSyncTime = 0; + + (function (ByteOrderMark) { + ByteOrderMark[ByteOrderMark["None"] = 0] = "None"; + ByteOrderMark[ByteOrderMark["Utf8"] = 1] = "Utf8"; + ByteOrderMark[ByteOrderMark["Utf16BigEndian"] = 2] = "Utf16BigEndian"; + ByteOrderMark[ByteOrderMark["Utf16LittleEndian"] = 3] = "Utf16LittleEndian"; + })(TypeScript.ByteOrderMark || (TypeScript.ByteOrderMark = {})); + var ByteOrderMark = TypeScript.ByteOrderMark; + + var FileInformation = (function () { + function FileInformation(contents, byteOrderMark) { + this.contents = contents; + this.byteOrderMark = byteOrderMark; + } + return FileInformation; + })(); + TypeScript.FileInformation = FileInformation; + + TypeScript.Environment = (function () { + function getWindowsScriptHostEnvironment() { + try { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + } catch (e) { + return null; + } + + 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 { + newLine: "\r\n", + currentDirectory: function () { + return WScript.CreateObject("WScript.Shell").CurrentDirectory; + }, + supportsCodePage: function () { + return WScript.ReadFile; + }, + readFile: function (path, codepage) { + try { + if (codepage !== null && this.supportsCodePage()) { + try { + var contents = WScript.ReadFile(path, codepage); + return new FileInformation(contents, 0 /* None */); + } catch (e) { + } + } + + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; + + streamObj.Charset = 'x-ansi'; + + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); + + streamObj.Position = 0; + + var byteOrderMark = 0 /* None */; + + if (bomChar.charCodeAt(0) === 0xFE && bomChar.charCodeAt(1) === 0xFF) { + streamObj.Charset = 'unicode'; + byteOrderMark = 2 /* Utf16BigEndian */; + } else if (bomChar.charCodeAt(0) === 0xFF && bomChar.charCodeAt(1) === 0xFE) { + streamObj.Charset = 'unicode'; + byteOrderMark = 3 /* Utf16LittleEndian */; + } else if (bomChar.charCodeAt(0) === 0xEF && bomChar.charCodeAt(1) === 0xBB) { + streamObj.Charset = 'utf-8'; + byteOrderMark = 1 /* Utf8 */; + } else { + streamObj.Charset = 'utf-8'; + } + + var contents = streamObj.ReadText(-1); + streamObj.Close(); + releaseStreamObject(streamObj); + return new FileInformation(contents, byteOrderMark); + } catch (err) { + var message; + if (err.number === -2147024809) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Unsupported_file_encoding, null); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Cannot_read_file_0_1, [path, err.message]); + } + + throw new Error(message); + } + }, + writeFile: function (path, contents, writeByteOrderMark) { + var textStream = getStreamObject(); + textStream.Charset = 'utf-8'; + textStream.Open(); + textStream.WriteText(contents, 0); + + if (!writeByteOrderMark) { + textStream.Position = 3; + } else { + textStream.Position = 0; + } + + var fileStream = getStreamObject(); + fileStream.Type = 1; + fileStream.Open(); + + textStream.CopyTo(fileStream); + + fileStream.Flush(); + fileStream.SaveToFile(path, 2); + fileStream.Close(); + + textStream.Flush(); + textStream.Close(); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + deleteFile: function (path) { + if (fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + listFiles: 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); + }, + arguments: args, + standardOut: WScript.StdOut + }; + } + ; + + function getNodeEnvironment() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + var _os = require('os'); + + return { + newLine: _os.EOL, + currentDirectory: function () { + return process.cwd(); + }, + supportsCodePage: function () { + return false; + }, + readFile: function (file, codepage) { + if (codepage !== null) { + throw new Error(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.codepage_option_not_supported_on_current_platform, null)); + } + + 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 new FileInformation(buffer.toString("ucs2", 2), 2 /* Utf16BigEndian */); + } + break; + case 0xFF: + if (buffer[1] === 0xFE) { + return new FileInformation(buffer.toString("ucs2", 2), 3 /* Utf16LittleEndian */); + } + break; + case 0xEF: + if (buffer[1] === 0xBB) { + return new FileInformation(buffer.toString("utf8", 3), 1 /* Utf8 */); + } + } + + return new FileInformation(buffer.toString("utf8", 0), 0 /* None */); + }, + writeFile: function (path, contents, writeByteOrderMark) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if (stats.isFile()) { + throw "\"" + path + "\" exists but isn't a directory."; + } else if (stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 509); + } + } + var start = new Date().getTime(); + mkdirRecursiveSync(_path.dirname(path)); + TypeScript.nodeMakeDirectoryTime += new Date().getTime() - start; + + if (writeByteOrderMark) { + contents = '\uFEFF' + contents; + } + + var start = new Date().getTime(); + + var chunkLength = 4 * 1024; + var fileDescriptor = _fs.openSync(path, "w"); + try { + for (var index = 0; index < contents.length; index += chunkLength) { + var bufferStart = new Date().getTime(); + var buffer = new Buffer(contents.substr(index, chunkLength), "utf8"); + TypeScript.nodeCreateBufferTime += new Date().getTime() - bufferStart; + + _fs.writeSync(fileDescriptor, buffer, 0, buffer.length, null); + } + } finally { + _fs.closeSync(fileDescriptor); + } + + TypeScript.nodeWriteFileSyncTime += new Date().getTime() - start; + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); + }, + listFiles: 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); + }, + arguments: process.argv.slice(2), + standardOut: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + } + }; + } + ; + + if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { + return getWindowsScriptHostEnvironment(); + } else if (typeof module !== 'undefined' && module.exports) { + return getNodeEnvironment(); + } else { + return null; + } + })(); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (IntegerUtilities) { + function integerDivide(numerator, denominator) { + return (numerator / denominator) >> 0; + } + IntegerUtilities.integerDivide = integerDivide; + + function integerMultiplyLow32Bits(n1, n2) { + var n1Low16 = n1 & 0x0000ffff; + var n1High16 = n1 >>> 16; + + var n2Low16 = n2 & 0x0000ffff; + var n2High16 = n2 >>> 16; + + var resultLow32 = (((n1 & 0xffff0000) * n2) >>> 0) + (((n1 & 0x0000ffff) * n2) >>> 0) >>> 0; + return resultLow32; + } + IntegerUtilities.integerMultiplyLow32Bits = integerMultiplyLow32Bits; + + function integerMultiplyHigh32Bits(n1, n2) { + var n1Low16 = n1 & 0x0000ffff; + var n1High16 = n1 >>> 16; + + var n2Low16 = n2 & 0x0000ffff; + var n2High16 = n2 >>> 16; + + var resultHigh32 = n1High16 * n2High16 + ((((n1Low16 * n2Low16) >>> 17) + n1Low16 * n2High16) >>> 15); + return resultHigh32; + } + IntegerUtilities.integerMultiplyHigh32Bits = integerMultiplyHigh32Bits; + + function isInteger(text) { + return /^[0-9]+$/.test(text); + } + IntegerUtilities.isInteger = isInteger; + + function isHexInteger(text) { + return /^0(x|X)[0-9a-fA-F]+$/.test(text); + } + IntegerUtilities.isHexInteger = isHexInteger; + })(TypeScript.IntegerUtilities || (TypeScript.IntegerUtilities = {})); + var IntegerUtilities = TypeScript.IntegerUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var LineMap = (function () { + function LineMap(_computeLineStarts, length) { + this._computeLineStarts = _computeLineStarts; + this.length = length; + this._lineStarts = null; + } + LineMap.prototype.toJSON = function (key) { + return { lineStarts: this.lineStarts(), length: this.length }; + }; + + LineMap.prototype.equals = function (other) { + return this.length === other.length && TypeScript.ArrayUtilities.sequenceEquals(this.lineStarts(), other.lineStarts(), function (v1, v2) { + return v1 === v2; + }); + }; + + LineMap.prototype.lineStarts = function () { + if (this._lineStarts === null) { + this._lineStarts = this._computeLineStarts(); + } + + return this._lineStarts; + }; + + LineMap.prototype.lineCount = function () { + return this.lineStarts().length; + }; + + LineMap.prototype.getPosition = function (line, character) { + return this.lineStarts()[line] + character; + }; + + LineMap.prototype.getLineNumberFromPosition = function (position) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + if (position === this.length) { + return this.lineCount() - 1; + } + + var lineNumber = TypeScript.ArrayUtilities.binarySearch(this.lineStarts(), position); + if (lineNumber < 0) { + lineNumber = (~lineNumber) - 1; + } + + return lineNumber; + }; + + LineMap.prototype.getLineStartPosition = function (lineNumber) { + return this.lineStarts()[lineNumber]; + }; + + LineMap.prototype.fillLineAndCharacterFromPosition = function (position, lineAndCharacter) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + lineAndCharacter.line = lineNumber; + lineAndCharacter.character = position - this.lineStarts()[lineNumber]; + }; + + LineMap.prototype.getLineAndCharacterFromPosition = function (position) { + if (position < 0 || position > this.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + + return new TypeScript.LineAndCharacter(lineNumber, position - this.lineStarts()[lineNumber]); + }; + LineMap.empty = new LineMap(function () { + return [0]; + }, 0); + return LineMap; + })(); + TypeScript.LineMap = LineMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var LineAndCharacter = (function () { + function LineAndCharacter(line, character) { + this._line = 0; + this._character = 0; + if (line < 0) { + throw TypeScript.Errors.argumentOutOfRange("line"); + } + + if (character < 0) { + throw TypeScript.Errors.argumentOutOfRange("character"); + } + + this._line = line; + this._character = character; + } + LineAndCharacter.prototype.line = function () { + return this._line; + }; + + LineAndCharacter.prototype.character = function () { + return this._character; + }; + return LineAndCharacter; + })(); + TypeScript.LineAndCharacter = LineAndCharacter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var MathPrototype = (function () { + function MathPrototype() { + } + MathPrototype.max = function (a, b) { + return a >= b ? a : b; + }; + + MathPrototype.min = function (a, b) { + return a <= b ? a : b; + }; + return MathPrototype; + })(); + TypeScript.MathPrototype = MathPrototype; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Collections) { + Collections.DefaultStringTableCapacity = 256; + + var StringTableEntry = (function () { + function StringTableEntry(Text, HashCode, Next) { + this.Text = Text; + this.HashCode = HashCode; + this.Next = Next; + } + return StringTableEntry; + })(); + + var StringTable = (function () { + function StringTable(capacity) { + this.count = 0; + var size = TypeScript.Hash.getPrime(capacity); + this.entries = TypeScript.ArrayUtilities.createArray(size, null); + } + StringTable.prototype.addCharArray = function (key, start, len) { + var hashCode = TypeScript.Hash.computeSimple31BitCharArrayHashCode(key, start, len) & 0x7FFFFFFF; + + var entry = this.findCharArrayEntry(key, start, len, hashCode); + if (entry !== null) { + return entry.Text; + } + + var slice = key.slice(start, start + len); + return this.addEntry(TypeScript.StringUtilities.fromCharCodeArray(slice), hashCode); + }; + + StringTable.prototype.findCharArrayEntry = function (key, start, len, hashCode) { + for (var e = this.entries[hashCode % this.entries.length]; e !== null; e = e.Next) { + if (e.HashCode === hashCode && StringTable.textCharArrayEquals(e.Text, key, start, len)) { + return e; + } + } + + return null; + }; + + StringTable.prototype.addEntry = function (text, hashCode) { + var index = hashCode % this.entries.length; + + var e = new StringTableEntry(text, hashCode, this.entries[index]); + + this.entries[index] = e; + + if (this.count === this.entries.length) { + this.grow(); + } + + this.count++; + return e.Text; + }; + + StringTable.prototype.grow = function () { + var newSize = TypeScript.Hash.expandPrime(this.entries.length); + + var oldEntries = this.entries; + var newEntries = TypeScript.ArrayUtilities.createArray(newSize, null); + + this.entries = newEntries; + + for (var i = 0; i < oldEntries.length; i++) { + var e = oldEntries[i]; + while (e !== null) { + var newIndex = e.HashCode % newSize; + var tmp = e.Next; + e.Next = newEntries[newIndex]; + newEntries[newIndex] = e; + e = tmp; + } + } + }; + + StringTable.textCharArrayEquals = function (text, array, start, length) { + if (text.length !== length) { + return false; + } + + var s = start; + for (var i = 0; i < length; i++) { + if (text.charCodeAt(i) !== array[s]) { + return false; + } + + s++; + } + + return true; + }; + return StringTable; + })(); + Collections.StringTable = StringTable; + + Collections.DefaultStringTable = new StringTable(Collections.DefaultStringTableCapacity); + })(TypeScript.Collections || (TypeScript.Collections = {})); + var Collections = TypeScript.Collections; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var StringUtilities = (function () { + function StringUtilities() { + } + StringUtilities.isString = function (value) { + return Object.prototype.toString.apply(value, []) === '[object String]'; + }; + + StringUtilities.fromCharCodeArray = function (array) { + return String.fromCharCode.apply(null, array); + }; + + StringUtilities.endsWith = function (string, value) { + return string.substring(string.length - value.length, string.length) === value; + }; + + StringUtilities.startsWith = function (string, value) { + return string.substr(0, value.length) === value; + }; + + StringUtilities.copyTo = function (source, sourceIndex, destination, destinationIndex, count) { + for (var i = 0; i < count; i++) { + destination[destinationIndex + i] = source.charCodeAt(sourceIndex + i); + } + }; + + StringUtilities.repeat = function (value, count) { + return Array(count + 1).join(value); + }; + + StringUtilities.stringEquals = function (val1, val2) { + return val1 === val2; + }; + return StringUtilities; + })(); + TypeScript.StringUtilities = StringUtilities; +})(TypeScript || (TypeScript = {})); +var global = Function("return this").call(null); + +var TypeScript; +(function (TypeScript) { + var Clock; + (function (Clock) { + Clock.now; + Clock.resolution; + + if (typeof WScript !== "undefined" && typeof global['WScript'].InitializeProjection !== "undefined") { + global['WScript'].InitializeProjection(); + + Clock.now = function () { + return TestUtilities.QueryPerformanceCounter(); + }; + + Clock.resolution = TestUtilities.QueryPerformanceFrequency(); + } else { + Clock.now = function () { + return Date.now(); + }; + + Clock.resolution = 1000; + } + })(Clock || (Clock = {})); + + var Timer = (function () { + function Timer() { + this.time = 0; + } + Timer.prototype.start = function () { + this.time = 0; + this.startTime = Clock.now(); + }; + + Timer.prototype.end = function () { + this.time = (Clock.now() - this.startTime); + }; + return Timer; + })(); + TypeScript.Timer = Timer; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + DiagnosticCategory[DiagnosticCategory["NoPrefix"] = 3] = "NoPrefix"; + })(TypeScript.DiagnosticCategory || (TypeScript.DiagnosticCategory = {})); + var DiagnosticCategory = TypeScript.DiagnosticCategory; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.diagnosticInformationMap = { + "error TS{0}: {1}": { + "code": 0, + "category": 3 /* NoPrefix */ + }, + "warning TS{0}: {1}": { + "code": 1, + "category": 3 /* NoPrefix */ + }, + "Unrecognized escape sequence.": { + "code": 1000, + "category": 1 /* Error */ + }, + "Unexpected character {0}.": { + "code": 1001, + "category": 1 /* Error */ + }, + "Missing close quote character.": { + "code": 1002, + "category": 1 /* Error */ + }, + "Identifier expected.": { + "code": 1003, + "category": 1 /* Error */ + }, + "'{0}' keyword expected.": { + "code": 1004, + "category": 1 /* Error */ + }, + "'{0}' expected.": { + "code": 1005, + "category": 1 /* Error */ + }, + "Identifier expected; '{0}' is a keyword.": { + "code": 1006, + "category": 1 /* Error */ + }, + "Automatic semicolon insertion not allowed.": { + "code": 1007, + "category": 1 /* Error */ + }, + "Unexpected token; '{0}' expected.": { + "code": 1008, + "category": 1 /* Error */ + }, + "Trailing separator not allowed.": { + "code": 1009, + "category": 1 /* Error */ + }, + "'*/' expected.": { + "code": 1010, + "category": 1 /* Error */ + }, + "'public' or 'private' modifier must precede 'static'.": { + "code": 1011, + "category": 1 /* Error */ + }, + "Unexpected token.": { + "code": 1012, + "category": 1 /* Error */ + }, + "Catch clause parameter cannot have a type annotation.": { + "code": 1013, + "category": 1 /* Error */ + }, + "Rest parameter must be last in list.": { + "code": 1014, + "category": 1 /* Error */ + }, + "Parameter cannot have question mark and initializer.": { + "code": 1015, + "category": 1 /* Error */ + }, + "Required parameter cannot follow optional parameter.": { + "code": 1016, + "category": 1 /* Error */ + }, + "Index signatures cannot have rest parameters.": { + "code": 1017, + "category": 1 /* Error */ + }, + "Index signature parameter cannot have accessibility modifiers.": { + "code": 1018, + "category": 1 /* Error */ + }, + "Index signature parameter cannot have a question mark.": { + "code": 1019, + "category": 1 /* Error */ + }, + "Index signature parameter cannot have an initializer.": { + "code": 1020, + "category": 1 /* Error */ + }, + "Index signature must have a type annotation.": { + "code": 1021, + "category": 1 /* Error */ + }, + "Index signature parameter must have a type annotation.": { + "code": 1022, + "category": 1 /* Error */ + }, + "Index signature parameter type must be 'string' or 'number'.": { + "code": 1023, + "category": 1 /* Error */ + }, + "'extends' clause already seen.": { + "code": 1024, + "category": 1 /* Error */ + }, + "'extends' clause must precede 'implements' clause.": { + "code": 1025, + "category": 1 /* Error */ + }, + "Classes can only extend a single class.": { + "code": 1026, + "category": 1 /* Error */ + }, + "'implements' clause already seen.": { + "code": 1027, + "category": 1 /* Error */ + }, + "Accessibility modifier already seen.": { + "code": 1028, + "category": 1 /* Error */ + }, + "'{0}' modifier must precede '{1}' modifier.": { + "code": 1029, + "category": 1 /* Error */ + }, + "'{0}' modifier already seen.": { + "code": 1030, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a class element.": { + "code": 1031, + "category": 1 /* Error */ + }, + "Interface declaration cannot have 'implements' clause.": { + "code": 1032, + "category": 1 /* Error */ + }, + "'super' invocation cannot have type arguments.": { + "code": 1034, + "category": 1 /* Error */ + }, + "Only ambient modules can use quoted names.": { + "code": 1035, + "category": 1 /* Error */ + }, + "Statements are not allowed in ambient contexts.": { + "code": 1036, + "category": 1 /* Error */ + }, + "Implementations are not allowed in ambient contexts.": { + "code": 1037, + "category": 1 /* Error */ + }, + "'declare' modifier not allowed for code already in an ambient context.": { + "code": 1038, + "category": 1 /* Error */ + }, + "Initializers are not allowed in ambient contexts.": { + "code": 1039, + "category": 1 /* Error */ + }, + "Parameter property declarations can only be used in a non-ambient constructor declaration.": { + "code": 1040, + "category": 1 /* Error */ + }, + "Function implementation expected.": { + "code": 1041, + "category": 1 /* Error */ + }, + "Constructor implementation expected.": { + "code": 1042, + "category": 1 /* Error */ + }, + "Function overload name must be '{0}'.": { + "code": 1043, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a module element.": { + "code": 1044, + "category": 1 /* Error */ + }, + "'declare' modifier cannot appear on an interface declaration.": { + "code": 1045, + "category": 1 /* Error */ + }, + "'declare' modifier required for top level element.": { + "code": 1046, + "category": 1 /* Error */ + }, + "Rest parameter cannot be optional.": { + "code": 1047, + "category": 1 /* Error */ + }, + "Rest parameter cannot have an initializer.": { + "code": 1048, + "category": 1 /* Error */ + }, + "'set' accessor must have one and only one parameter.": { + "code": 1049, + "category": 1 /* Error */ + }, + "'set' accessor parameter cannot be optional.": { + "code": 1051, + "category": 1 /* Error */ + }, + "'set' accessor parameter cannot have an initializer.": { + "code": 1052, + "category": 1 /* Error */ + }, + "'set' accessor cannot have rest parameter.": { + "code": 1053, + "category": 1 /* Error */ + }, + "'get' accessor cannot have parameters.": { + "code": 1054, + "category": 1 /* Error */ + }, + "Modifiers cannot appear here.": { + "code": 1055, + "category": 1 /* Error */ + }, + "Accessors are only available when targeting ECMAScript 5 and higher.": { + "code": 1056, + "category": 1 /* Error */ + }, + "Class name cannot be '{0}'.": { + "code": 1057, + "category": 1 /* Error */ + }, + "Interface name cannot be '{0}'.": { + "code": 1058, + "category": 1 /* Error */ + }, + "Enum name cannot be '{0}'.": { + "code": 1059, + "category": 1 /* Error */ + }, + "Module name cannot be '{0}'.": { + "code": 1060, + "category": 1 /* Error */ + }, + "Enum member must have initializer.": { + "code": 1061, + "category": 1 /* Error */ + }, + "Export assignment cannot be used in internal modules.": { + "code": 1063, + "category": 1 /* Error */ + }, + "Export assignment not allowed in module with exported element.": { + "code": 1064, + "category": 1 /* Error */ + }, + "Module cannot have multiple export assignments.": { + "code": 1065, + "category": 1 /* Error */ + }, + "Ambient enum elements can only have integer literal initializers.": { + "code": 1066, + "category": 1 /* Error */ + }, + "module, class, interface, enum, import or statement": { + "code": 1067, + "category": 3 /* NoPrefix */ + }, + "constructor, function, accessor or variable": { + "code": 1068, + "category": 3 /* NoPrefix */ + }, + "statement": { + "code": 1069, + "category": 3 /* NoPrefix */ + }, + "case or default clause": { + "code": 1070, + "category": 3 /* NoPrefix */ + }, + "identifier": { + "code": 1071, + "category": 3 /* NoPrefix */ + }, + "call, construct, index, property or function signature": { + "code": 1072, + "category": 3 /* NoPrefix */ + }, + "expression": { + "code": 1073, + "category": 3 /* NoPrefix */ + }, + "type name": { + "code": 1074, + "category": 3 /* NoPrefix */ + }, + "property or accessor": { + "code": 1075, + "category": 3 /* NoPrefix */ + }, + "parameter": { + "code": 1076, + "category": 3 /* NoPrefix */ + }, + "type": { + "code": 1077, + "category": 3 /* NoPrefix */ + }, + "type parameter": { + "code": 1078, + "category": 3 /* NoPrefix */ + }, + "'declare' modifier not allowed on import declaration.": { + "code": 1079, + "category": 1 /* Error */ + }, + "Function overload must be static.": { + "code": 1080, + "category": 1 /* Error */ + }, + "Function overload must not be static.": { + "code": 1081, + "category": 1 /* Error */ + }, + "Parameter property declarations cannot be used in a constructor overload.": { + "code": 1083, + "category": 1 /* Error */ + }, + "Invalid 'reference' directive syntax.": { + "code": 1084, + "category": 1 /* Error */ + }, + "Octal literals are not available when targeting ECMAScript 5 and higher.": { + "code": 1085, + "category": 1 /* Error */ + }, + "Accessors are not allowed in ambient contexts.": { + "code": 1086, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a constructor declaration.": { + "code": 1089, + "category": 1 /* Error */ + }, + "'{0}' modifier cannot appear on a parameter.": { + "code": 1090, + "category": 1 /* Error */ + }, + "Only a single variable declaration is allowed in a 'for...in' statement.": { + "code": 1091, + "category": 1 /* Error */ + }, + "Type parameters cannot appear on a constructor declaration.": { + "code": 1091, + "category": 1 /* Error */ + }, + "Type annotation cannot appear on a constructor declaration.": { + "code": 1092, + "category": 1 /* Error */ + }, + "Duplicate identifier '{0}'.": { + "code": 2000, + "category": 1 /* Error */ + }, + "The name '{0}' does not exist in the current scope.": { + "code": 2001, + "category": 1 /* Error */ + }, + "The name '{0}' does not refer to a value.": { + "code": 2002, + "category": 1 /* Error */ + }, + "'super' can only be used inside a class instance method.": { + "code": 2003, + "category": 1 /* Error */ + }, + "The left-hand side of an assignment expression must be a variable, property or indexer.": { + "code": 2004, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not callable. Did you mean to include 'new'?": { + "code": 2161, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not callable.": { + "code": 2006, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not newable.": { + "code": 2007, + "category": 1 /* Error */ + }, + "Value of type '{0}' is not indexable by type '{1}'.": { + "code": 2008, + "category": 1 /* Error */ + }, + "Operator '{0}' cannot be applied to types '{1}' and '{2}'.": { + "code": 2009, + "category": 1 /* Error */ + }, + "Operator '{0}' cannot be applied to types '{1}' and '{2}': {3}": { + "code": 2010, + "category": 1 /* Error */ + }, + "Cannot convert '{0}' to '{1}'.": { + "code": 2011, + "category": 1 /* Error */ + }, + "Cannot convert '{0}' to '{1}':{NL}{2}": { + "code": 2012, + "category": 1 /* Error */ + }, + "Expected var, class, interface, or module.": { + "code": 2013, + "category": 1 /* Error */ + }, + "Operator '{0}' cannot be applied to type '{1}'.": { + "code": 2014, + "category": 1 /* Error */ + }, + "Getter '{0}' already declared.": { + "code": 2015, + "category": 1 /* Error */ + }, + "Setter '{0}' already declared.": { + "code": 2016, + "category": 1 /* Error */ + }, + "Exported class '{0}' extends private class '{1}'.": { + "code": 2018, + "category": 1 /* Error */ + }, + "Exported class '{0}' implements private interface '{1}'.": { + "code": 2019, + "category": 1 /* Error */ + }, + "Exported interface '{0}' extends private interface '{1}'.": { + "code": 2020, + "category": 1 /* Error */ + }, + "Exported class '{0}' extends class from inaccessible module {1}.": { + "code": 2021, + "category": 1 /* Error */ + }, + "Exported class '{0}' implements interface from inaccessible module {1}.": { + "code": 2022, + "category": 1 /* Error */ + }, + "Exported interface '{0}' extends interface from inaccessible module {1}.": { + "code": 2023, + "category": 1 /* Error */ + }, + "Public static property '{0}' of exported class has or is using private type '{1}'.": { + "code": 2024, + "category": 1 /* Error */ + }, + "Public property '{0}' of exported class has or is using private type '{1}'.": { + "code": 2025, + "category": 1 /* Error */ + }, + "Property '{0}' of exported interface has or is using private type '{1}'.": { + "code": 2026, + "category": 1 /* Error */ + }, + "Exported variable '{0}' has or is using private type '{1}'.": { + "code": 2027, + "category": 1 /* Error */ + }, + "Public static property '{0}' of exported class is using inaccessible module {1}.": { + "code": 2028, + "category": 1 /* Error */ + }, + "Public property '{0}' of exported class is using inaccessible module {1}.": { + "code": 2029, + "category": 1 /* Error */ + }, + "Property '{0}' of exported interface is using inaccessible module {1}.": { + "code": 2030, + "category": 1 /* Error */ + }, + "Exported variable '{0}' is using inaccessible module {1}.": { + "code": 2031, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor from exported class has or is using private type '{1}'.": { + "code": 2032, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static property setter from exported class has or is using private type '{1}'.": { + "code": 2033, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public property setter from exported class has or is using private type '{1}'.": { + "code": 2034, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.": { + "code": 2035, + "category": 1 /* Error */ + }, + "Parameter '{0}' of call signature from exported interface has or is using private type '{1}'.": { + "code": 2036, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static method from exported class has or is using private type '{1}'.": { + "code": 2037, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public method from exported class has or is using private type '{1}'.": { + "code": 2038, + "category": 1 /* Error */ + }, + "Parameter '{0}' of method from exported interface has or is using private type '{1}'.": { + "code": 2039, + "category": 1 /* Error */ + }, + "Parameter '{0}' of exported function has or is using private type '{1}'.": { + "code": 2040, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor from exported class is using inaccessible module {1}.": { + "code": 2041, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static property setter from exported class is using inaccessible module {1}.": { + "code": 2042, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public property setter from exported class is using inaccessible module {1}.": { + "code": 2043, + "category": 1 /* Error */ + }, + "Parameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.": { + "code": 2044, + "category": 1 /* Error */ + }, + "Parameter '{0}' of call signature from exported interface is using inaccessible module {1}": { + "code": 2045, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public static method from exported class is using inaccessible module {1}.": { + "code": 2046, + "category": 1 /* Error */ + }, + "Parameter '{0}' of public method from exported class is using inaccessible module {1}.": { + "code": 2047, + "category": 1 /* Error */ + }, + "Parameter '{0}' of method from exported interface is using inaccessible module {1}.": { + "code": 2048, + "category": 1 /* Error */ + }, + "Parameter '{0}' of exported function is using inaccessible module {1}.": { + "code": 2049, + "category": 1 /* Error */ + }, + "Return type of public static property getter from exported class has or is using private type '{0}'.": { + "code": 2050, + "category": 1 /* Error */ + }, + "Return type of public property getter from exported class has or is using private type '{0}'.": { + "code": 2051, + "category": 1 /* Error */ + }, + "Return type of constructor signature from exported interface has or is using private type '{0}'.": { + "code": 2052, + "category": 1 /* Error */ + }, + "Return type of call signature from exported interface has or is using private type '{0}'.": { + "code": 2053, + "category": 1 /* Error */ + }, + "Return type of index signature from exported interface has or is using private type '{0}'.": { + "code": 2054, + "category": 1 /* Error */ + }, + "Return type of public static method from exported class has or is using private type '{0}'.": { + "code": 2055, + "category": 1 /* Error */ + }, + "Return type of public method from exported class has or is using private type '{0}'.": { + "code": 2056, + "category": 1 /* Error */ + }, + "Return type of method from exported interface has or is using private type '{0}'.": { + "code": 2057, + "category": 1 /* Error */ + }, + "Return type of exported function has or is using private type '{0}'.": { + "code": 2058, + "category": 1 /* Error */ + }, + "Return type of public static property getter from exported class is using inaccessible module {0}.": { + "code": 2059, + "category": 1 /* Error */ + }, + "Return type of public property getter from exported class is using inaccessible module {0}.": { + "code": 2060, + "category": 1 /* Error */ + }, + "Return type of constructor signature from exported interface is using inaccessible module {0}.": { + "code": 2061, + "category": 1 /* Error */ + }, + "Return type of call signature from exported interface is using inaccessible module {0}.": { + "code": 2062, + "category": 1 /* Error */ + }, + "Return type of index signature from exported interface is using inaccessible module {0}.": { + "code": 2063, + "category": 1 /* Error */ + }, + "Return type of public static method from exported class is using inaccessible module {0}.": { + "code": 2064, + "category": 1 /* Error */ + }, + "Return type of public method from exported class is using inaccessible module {0}.": { + "code": 2065, + "category": 1 /* Error */ + }, + "Return type of method from exported interface is using inaccessible module {0}.": { + "code": 2066, + "category": 1 /* Error */ + }, + "Return type of exported function is using inaccessible module {0}.": { + "code": 2067, + "category": 1 /* Error */ + }, + "'new T[]' cannot be used to create an array. Use 'new Array()' instead.": { + "code": 2068, + "category": 1 /* Error */ + }, + "A parameter list must follow a generic type argument list. '(' expected.": { + "code": 2069, + "category": 1 /* Error */ + }, + "Multiple constructor implementations are not allowed.": { + "code": 2070, + "category": 1 /* Error */ + }, + "Unable to resolve external module '{0}'.": { + "code": 2071, + "category": 1 /* Error */ + }, + "Module cannot be aliased to a non-module type.": { + "code": 2072, + "category": 1 /* Error */ + }, + "A class may only extend another class.": { + "code": 2073, + "category": 1 /* Error */ + }, + "A class may only implement another class or interface.": { + "code": 2074, + "category": 1 /* Error */ + }, + "An interface may only extend another class or interface.": { + "code": 2075, + "category": 1 /* Error */ + }, + "Unable to resolve type.": { + "code": 2077, + "category": 1 /* Error */ + }, + "Unable to resolve type of '{0}'.": { + "code": 2078, + "category": 1 /* Error */ + }, + "Unable to resolve type parameter constraint.": { + "code": 2079, + "category": 1 /* Error */ + }, + "Type parameter constraint cannot be a primitive type.": { + "code": 2080, + "category": 1 /* Error */ + }, + "Supplied parameters do not match any signature of call target.": { + "code": 2081, + "category": 1 /* Error */ + }, + "Supplied parameters do not match any signature of call target:{NL}{0}": { + "code": 2082, + "category": 1 /* Error */ + }, + "Invalid 'new' expression.": { + "code": 2083, + "category": 1 /* Error */ + }, + "Call signatures used in a 'new' expression must have a 'void' return type.": { + "code": 2084, + "category": 1 /* Error */ + }, + "Could not select overload for 'new' expression.": { + "code": 2085, + "category": 1 /* Error */ + }, + "Type '{0}' does not satisfy the constraint '{1}' for type parameter '{2}'.": { + "code": 2086, + "category": 1 /* Error */ + }, + "Could not select overload for 'call' expression.": { + "code": 2087, + "category": 1 /* Error */ + }, + "Cannot invoke an expression whose type lacks a call signature.": { + "code": 2088, + "category": 1 /* Error */ + }, + "Calls to 'super' are only valid inside a class.": { + "code": 2089, + "category": 1 /* Error */ + }, + "Generic type '{0}' requires {1} type argument(s).": { + "code": 2090, + "category": 1 /* Error */ + }, + "Type of array literal cannot be determined. Best common type could not be found for array elements.": { + "code": 2092, + "category": 1 /* Error */ + }, + "Could not find enclosing symbol for dotted name '{0}'.": { + "code": 2093, + "category": 1 /* Error */ + }, + "The property '{0}' does not exist on value of type '{1}'.": { + "code": 2094, + "category": 1 /* Error */ + }, + "Could not find symbol '{0}'.": { + "code": 2095, + "category": 1 /* Error */ + }, + "'get' and 'set' accessor must have the same type.": { + "code": 2096, + "category": 1 /* Error */ + }, + "'this' cannot be referenced in current location.": { + "code": 2097, + "category": 1 /* Error */ + }, + "Static members cannot reference class type parameters.": { + "code": 2099, + "category": 1 /* Error */ + }, + "Class '{0}' is recursively referenced as a base type of itself.": { + "code": 2100, + "category": 1 /* Error */ + }, + "Interface '{0}' is recursively referenced as a base type of itself.": { + "code": 2101, + "category": 1 /* Error */ + }, + "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class.": { + "code": 2102, + "category": 1 /* Error */ + }, + "'super' cannot be referenced in non-derived classes.": { + "code": 2103, + "category": 1 /* Error */ + }, + "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.": { + "code": 2104, + "category": 1 /* Error */ + }, + "Constructors for derived classes must contain a 'super' call.": { + "code": 2105, + "category": 1 /* Error */ + }, + "Super calls are not permitted outside constructors or in nested functions inside constructors.": { + "code": 2106, + "category": 1 /* Error */ + }, + "'{0}.{1}' is inaccessible.": { + "code": 2107, + "category": 1 /* Error */ + }, + "'this' cannot be referenced within module bodies.": { + "code": 2108, + "category": 1 /* Error */ + }, + "Invalid '+' expression - types not known to support the addition operator.": { + "code": 2111, + "category": 1 /* Error */ + }, + "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.": { + "code": 2112, + "category": 1 /* Error */ + }, + "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.": { + "code": 2113, + "category": 1 /* Error */ + }, + "The type of a unary arithmetic operation operand must be of type 'any', 'number' or an enum type.": { + "code": 2114, + "category": 1 /* Error */ + }, + "Variable declarations of a 'for' statement cannot use a type annotation.": { + "code": 2115, + "category": 1 /* Error */ + }, + "Variable declarations of a 'for' statement must be of types 'string' or 'any'.": { + "code": 2116, + "category": 1 /* Error */ + }, + "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter.": { + "code": 2117, + "category": 1 /* Error */ + }, + "The left-hand side of an 'in' expression must be of types 'any', 'string' or 'number'.": { + "code": 2118, + "category": 1 /* Error */ + }, + "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.": { + "code": 2119, + "category": 1 /* Error */ + }, + "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.": { + "code": 2120, + "category": 1 /* Error */ + }, + "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.": { + "code": 2121, + "category": 1 /* Error */ + }, + "Setters cannot return a value.": { + "code": 2122, + "category": 1 /* Error */ + }, + "Tried to query type of uninitialized module '{0}'.": { + "code": 2123, + "category": 1 /* Error */ + }, + "Tried to set variable type to uninitialized module type '{0}'.": { + "code": 2124, + "category": 1 /* Error */ + }, + "Type '{0}' does not have type parameters.": { + "code": 2125, + "category": 1 /* Error */ + }, + "Getters must return a value.": { + "code": 2126, + "category": 1 /* Error */ + }, + "Getter and setter accessors do not agree in visibility.": { + "code": 2127, + "category": 1 /* Error */ + }, + "Invalid left-hand side of assignment expression.": { + "code": 2130, + "category": 1 /* Error */ + }, + "Function declared a non-void return type, but has no return expression.": { + "code": 2131, + "category": 1 /* Error */ + }, + "Cannot resolve return type reference.": { + "code": 2132, + "category": 1 /* Error */ + }, + "Constructors cannot have a return type of 'void'.": { + "code": 2133, + "category": 1 /* Error */ + }, + "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'.": { + "code": 2134, + "category": 1 /* Error */ + }, + "All symbols within a with block will be resolved to 'any'.": { + "code": 2135, + "category": 1 /* Error */ + }, + "Import declarations in an internal module cannot reference an external module.": { + "code": 2136, + "category": 1 /* Error */ + }, + "Class {0} declares interface {1} but does not implement it:{NL}{2}": { + "code": 2137, + "category": 1 /* Error */ + }, + "Class {0} declares class {1} as an interface but does not implement it:{NL}{2}": { + "code": 2138, + "category": 1 /* Error */ + }, + "The operand of an increment or decrement operator must be a variable, property or indexer.": { + "code": 2139, + "category": 1 /* Error */ + }, + "'this' cannot be referenced in static initializers in a class body.": { + "code": 2140, + "category": 1 /* Error */ + }, + "Class '{0}' cannot extend class '{1}':{NL}{2}": { + "code": 2141, + "category": 1 /* Error */ + }, + "Interface '{0}' cannot extend class '{1}':{NL}{2}": { + "code": 2142, + "category": 1 /* Error */ + }, + "Interface '{0}' cannot extend interface '{1}':{NL}{2}": { + "code": 2143, + "category": 1 /* Error */ + }, + "Duplicate overload signature for '{0}'.": { + "code": 2144, + "category": 1 /* Error */ + }, + "Duplicate constructor overload signature.": { + "code": 2145, + "category": 1 /* Error */ + }, + "Duplicate overload call signature.": { + "code": 2146, + "category": 1 /* Error */ + }, + "Duplicate overload construct signature.": { + "code": 2147, + "category": 1 /* Error */ + }, + "Overload signature is not compatible with function definition.": { + "code": 2148, + "category": 1 /* Error */ + }, + "Overload signature is not compatible with function definition:{NL}{0}": { + "code": 2149, + "category": 1 /* Error */ + }, + "Overload signatures must all be public or private.": { + "code": 2150, + "category": 1 /* Error */ + }, + "Overload signatures must all be exported or not exported.": { + "code": 2151, + "category": 1 /* Error */ + }, + "Overload signatures must all be ambient or non-ambient.": { + "code": 2152, + "category": 1 /* Error */ + }, + "Overload signatures must all be optional or required.": { + "code": 2153, + "category": 1 /* Error */ + }, + "Specialized overload signature is not assignable to any non-specialized signature.": { + "code": 2154, + "category": 1 /* Error */ + }, + "'this' cannot be referenced in constructor arguments.": { + "code": 2155, + "category": 1 /* Error */ + }, + "Instance member cannot be accessed off a class.": { + "code": 2157, + "category": 1 /* Error */ + }, + "Untyped function calls may not accept type arguments.": { + "code": 2158, + "category": 1 /* Error */ + }, + "Non-generic functions may not accept type arguments.": { + "code": 2159, + "category": 1 /* Error */ + }, + "A generic type may not reference itself with a wrapped form of its own type parameters.": { + "code": 2160, + "category": 1 /* Error */ + }, + "Rest parameters must be array types.": { + "code": 2162, + "category": 1 /* Error */ + }, + "Overload signature implementation cannot use specialized type.": { + "code": 2163, + "category": 1 /* Error */ + }, + "Export assignments may only be used at the top-level of external modules.": { + "code": 2164, + "category": 1 /* Error */ + }, + "Export assignments may only be made with variables, functions, classes, interfaces, enums and internal modules.": { + "code": 2165, + "category": 1 /* Error */ + }, + "Only public methods of the base class are accessible via the 'super' keyword.": { + "code": 2166, + "category": 1 /* Error */ + }, + "Numeric indexer type '{0}' must be assignable to string indexer type '{1}'.": { + "code": 2167, + "category": 1 /* Error */ + }, + "Numeric indexer type '{0}' must be assignable to string indexer type '{1}':{NL}{2}": { + "code": 2168, + "category": 1 /* Error */ + }, + "All numerically named properties must be assignable to numeric indexer type '{0}'.": { + "code": 2169, + "category": 1 /* Error */ + }, + "All numerically named properties must be assignable to numeric indexer type '{0}':{NL}{1}": { + "code": 2170, + "category": 1 /* Error */ + }, + "All named properties must be assignable to string indexer type '{0}'.": { + "code": 2171, + "category": 1 /* Error */ + }, + "All named properties must be assignable to string indexer type '{0}':{NL}{1}": { + "code": 2172, + "category": 1 /* Error */ + }, + "Generic type references must include all type arguments.": { + "code": 2173, + "category": 1 /* Error */ + }, + "Default arguments are only allowed in implementation.": { + "code": 2174, + "category": 1 /* Error */ + }, + "Overloads cannot differ only by return type.": { + "code": 2175, + "category": 1 /* Error */ + }, + "Function expression declared a non-void return type, but has no return expression.": { + "code": 2176, + "category": 1 /* Error */ + }, + "Import declaration referencing identifier from internal module can only be made with variables, functions, classes, interfaces, enums and internal modules.": { + "code": 2177, + "category": 1 /* Error */ + }, + "Could not find symbol '{0}' in module '{1}'.": { + "code": 2178, + "category": 1 /* Error */ + }, + "Unable to resolve module reference '{0}'.": { + "code": 2179, + "category": 1 /* Error */ + }, + "Could not find module '{0}' in module '{1}'.": { + "code": 2180, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned value with type that has or is using private type '{1}'.": { + "code": 2181, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned value with type that is using inaccessible module '{1}'.": { + "code": 2182, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned type that has or is using private type '{1}'.": { + "code": 2183, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned type that is using inaccessible module '{1}'.": { + "code": 2184, + "category": 1 /* Error */ + }, + "Exported import declaration '{0}' is assigned container that is or is using inaccessible module '{1}'.": { + "code": 2185, + "category": 1 /* Error */ + }, + "Type name '{0}' in extends clause does not reference constructor function for '{1}'.": { + "code": 2186, + "category": 1 /* Error */ + }, + "Internal module reference '{0}' in import declaration does not reference module instance for '{1}'.": { + "code": 2187, + "category": 1 /* Error */ + }, + "Module '{0}' cannot merge with previous declaration of '{1}' in a different file '{2}'.": { + "code": 2188, + "category": 1 /* Error */ + }, + "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}':{NL}{3}": { + "code": 2189, + "category": 1 /* Error */ + }, + "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it.": { + "code": 2190, + "category": 1 /* Error */ + }, + "Ambient external module declaration cannot be reopened.": { + "code": 2191, + "category": 1 /* Error */ + }, + "All declarations of merged declaration '{0}' must be exported or not exported.": { + "code": 2192, + "category": 1 /* Error */ + }, + "'super' cannot be referenced in constructor arguments.": { + "code": 2193, + "category": 1 /* Error */ + }, + "Return type of constructor signature must be assignable to the instance type of the class.": { + "code": 2194, + "category": 1 /* Error */ + }, + "Ambient external module declaration must be defined in global context.": { + "code": 2195, + "category": 1 /* Error */ + }, + "Ambient external module declaration cannot specify relative module name.": { + "code": 2196, + "category": 1 /* Error */ + }, + "Import declaration in an ambient external module declaration cannot reference external module through relative external module name.": { + "code": 2197, + "category": 1 /* Error */ + }, + "Could not find the best common type of types of all return statement expressions.": { + "code": 2198, + "category": 1 /* Error */ + }, + "Import declaration cannot refer to external module reference when --noResolve option is set.": { + "code": 2199, + "category": 1 /* Error */ + }, + "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference.": { + "code": 2200, + "category": 1 /* Error */ + }, + "'continue' statement can only be used within an enclosing iteration statement.": { + "code": 2201, + "category": 1 /* Error */ + }, + "'break' statement can only be used within an enclosing iteration or switch statement.": { + "code": 2202, + "category": 1 /* Error */ + }, + "Jump target not found.": { + "code": 2203, + "category": 1 /* Error */ + }, + "Jump target cannot cross function boundary.": { + "code": 2204, + "category": 1 /* Error */ + }, + "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference.": { + "code": 2205, + "category": 1 /* Error */ + }, + "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference.": { + "code": 2206, + "category": 1 /* Error */ + }, + "Expression resolves to '_super' that compiler uses to capture base class reference.": { + "code": 2207, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of constructor signature from exported interface has or is using private type '{1}'.": { + "code": 2208, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of call signature from exported interface has or is using private type '{1}'.": { + "code": 2209, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public static method from exported class has or is using private type '{1}'.": { + "code": 2210, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public method from exported class has or is using private type '{1}'.": { + "code": 2211, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of method from exported interface has or is using private type '{1}'.": { + "code": 2212, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported function has or is using private type '{1}'.": { + "code": 2213, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of constructor signature from exported interface is using inaccessible module {1}.": { + "code": 2214, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of call signature from exported interface is using inaccessible module {1}": { + "code": 2215, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public static method from exported class is using inaccessible module {1}.": { + "code": 2216, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of public method from exported class is using inaccessible module {1}.": { + "code": 2217, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of method from exported interface is using inaccessible module {1}.": { + "code": 2218, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported function is using inaccessible module {1}.": { + "code": 2219, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported class has or is using private type '{1}'.": { + "code": 2220, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported interface has or is using private type '{1}'.": { + "code": 2221, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported class is using inaccessible module {1}.": { + "code": 2222, + "category": 1 /* Error */ + }, + "TypeParameter '{0}' of exported interface is using inaccessible module {1}.": { + "code": 2223, + "category": 1 /* Error */ + }, + "Duplicate identifier '_i'. Compiler uses '_i' to initialize rest parameter.": { + "code": 2224, + "category": 1 /* Error */ + }, + "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters.": { + "code": 2225, + "category": 1 /* Error */ + }, + "Type of conditional '{0}' must be identical to '{1}' or '{2}'.": { + "code": 2226, + "category": 1 /* Error */ + }, + "Type of conditional '{0}' must be identical to '{1}', '{2}' or '{3}'.": { + "code": 2227, + "category": 1 /* Error */ + }, + "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of an external module.": { + "code": 2228, + "category": 1 /* Error */ + }, + "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.": { + "code": 2229, + "category": 1 /* Error */ + }, + "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.": { + "code": 2230, + "category": 1 /* Error */ + }, + "Parameter '{0}' cannot be referenced in its initializer.": { + "code": 2231, + "category": 1 /* Error */ + }, + "Duplicate string index signature.": { + "code": 2232, + "category": 1 /* Error */ + }, + "Duplicate number index signature.": { + "code": 2233, + "category": 1 /* Error */ + }, + "All declarations of an interface must have identical type parameters.": { + "code": 2234, + "category": 1 /* Error */ + }, + "Expression resolves to variable declaration '_i' that compiler uses to initialize rest parameter.": { + "code": 2235, + "category": 1 /* Error */ + }, + "Type '{0}' is missing property '{1}' from type '{2}'.": { + "code": 4000, + "category": 3 /* NoPrefix */ + }, + "Types of property '{0}' of types '{1}' and '{2}' are incompatible.": { + "code": 4001, + "category": 3 /* NoPrefix */ + }, + "Types of property '{0}' of types '{1}' and '{2}' are incompatible:{NL}{3}": { + "code": 4002, + "category": 3 /* NoPrefix */ + }, + "Property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.": { + "code": 4003, + "category": 3 /* NoPrefix */ + }, + "Property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.": { + "code": 4004, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' define property '{2}' as private.": { + "code": 4005, + "category": 3 /* NoPrefix */ + }, + "Call signatures of types '{0}' and '{1}' are incompatible.": { + "code": 4006, + "category": 3 /* NoPrefix */ + }, + "Call signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { + "code": 4007, + "category": 3 /* NoPrefix */ + }, + "Type '{0}' requires a call signature, but type '{1}' lacks one.": { + "code": 4008, + "category": 3 /* NoPrefix */ + }, + "Construct signatures of types '{0}' and '{1}' are incompatible.": { + "code": 4009, + "category": 3 /* NoPrefix */ + }, + "Construct signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { + "code": 4010, + "category": 3 /* NoPrefix */ + }, + "Type '{0}' requires a construct signature, but type '{1}' lacks one.": { + "code": 4011, + "category": 3 /* NoPrefix */ + }, + "Index signatures of types '{0}' and '{1}' are incompatible.": { + "code": 4012, + "category": 3 /* NoPrefix */ + }, + "Index signatures of types '{0}' and '{1}' are incompatible:{NL}{2}": { + "code": 4013, + "category": 3 /* NoPrefix */ + }, + "Call signature expects {0} or fewer parameters.": { + "code": 4014, + "category": 3 /* NoPrefix */ + }, + "Could not apply type '{0}' to argument {1} which is of type '{2}'.": { + "code": 4015, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function.": { + "code": 4016, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.": { + "code": 4017, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor.": { + "code": 4018, + "category": 3 /* NoPrefix */ + }, + "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.": { + "code": 4019, + "category": 3 /* NoPrefix */ + }, + "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible.": { + "code": 4020, + "category": 3 /* NoPrefix */ + }, + "Types of static property '{0}' of class '{1}' and class '{2}' are incompatible:{NL}{3}": { + "code": 4021, + "category": 3 /* NoPrefix */ + }, + "Type reference cannot refer to container '{0}'.": { + "code": 4022, + "category": 1 /* Error */ + }, + "Type reference must refer to type.": { + "code": 4023, + "category": 1 /* Error */ + }, + "In enums with multiple declarations only one declaration can omit an initializer for the first enum element.": { + "code": 4024, + "category": 1 /* Error */ + }, + " (+ {0} overload(s))": { + "code": 4025, + "category": 2 /* Message */ + }, + "Variable declaration cannot have the same name as an import declaration.": { + "code": 4026, + "category": 1 /* Error */ + }, + "Signature expected {0} type arguments, got {1} instead.": { + "code": 4027, + "category": 1 /* Error */ + }, + "Property '{0}' defined as optional in type '{1}', but is required in type '{2}'.": { + "code": 4028, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference do not refer to same named type.": { + "code": 4029, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments.": { + "code": 4030, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' originating in infinitely expanding type reference have incompatible type arguments:{NL}{2}": { + "code": 4031, + "category": 3 /* NoPrefix */ + }, + "Named properties '{0}' of types '{1}' and '{2}' are not identical.": { + "code": 4032, + "category": 3 /* NoPrefix */ + }, + "Types of string indexer of types '{0}' and '{1}' are not identical.": { + "code": 4033, + "category": 3 /* NoPrefix */ + }, + "Types of number indexer of types '{0}' and '{1}' are not identical.": { + "code": 4034, + "category": 3 /* NoPrefix */ + }, + "Type of number indexer in type '{0}' is not assignable to string indexer type in type '{1}'.{NL}{2}": { + "code": 4035, + "category": 3 /* NoPrefix */ + }, + "Type of property '{0}' in type '{1}' is not assignable to string indexer type in type '{2}'.{NL}{3}": { + "code": 4036, + "category": 3 /* NoPrefix */ + }, + "Type of property '{0}' in type '{1}' is not assignable to number indexer type in type '{2}'.{NL}{3}": { + "code": 4037, + "category": 3 /* NoPrefix */ + }, + "Static property '{0}' defined as private in type '{1}' is defined as public in type '{2}'.": { + "code": 4038, + "category": 3 /* NoPrefix */ + }, + "Static property '{0}' defined as public in type '{1}' is defined as private in type '{2}'.": { + "code": 4039, + "category": 3 /* NoPrefix */ + }, + "Types '{0}' and '{1}' define static property '{2}' as private.": { + "code": 4040, + "category": 3 /* NoPrefix */ + }, + "Current host does not support '{0}' option.": { + "code": 5001, + "category": 1 /* Error */ + }, + "ECMAScript target version '{0}' not supported. Specify a valid target version: '{1}' (default), or '{2}'": { + "code": 5002, + "category": 1 /* Error */ + }, + "Module code generation '{0}' not supported.": { + "code": 5003, + "category": 1 /* Error */ + }, + "Could not find file: '{0}'.": { + "code": 5004, + "category": 1 /* Error */ + }, + "A file cannot have a reference to itself.": { + "code": 5006, + "category": 1 /* Error */ + }, + "Cannot resolve referenced file: '{0}'.": { + "code": 5007, + "category": 1 /* Error */ + }, + "Cannot find the common subdirectory path for the input files.": { + "code": 5009, + "category": 1 /* Error */ + }, + "Emit Error: {0}.": { + "code": 5011, + "category": 1 /* Error */ + }, + "Cannot read file '{0}': {1}": { + "code": 5012, + "category": 1 /* Error */ + }, + "Unsupported file encoding.": { + "code": 5013, + "category": 3 /* NoPrefix */ + }, + "Locale must be of the form or -. For example '{0}' or '{1}'.": { + "code": 5014, + "category": 1 /* Error */ + }, + "Unsupported locale: '{0}'.": { + "code": 5015, + "category": 1 /* Error */ + }, + "Execution Failed.{NL}": { + "code": 5016, + "category": 1 /* Error */ + }, + "Invalid call to 'up'": { + "code": 5019, + "category": 1 /* Error */ + }, + "Invalid call to 'down'": { + "code": 5020, + "category": 1 /* Error */ + }, + "Base64 value '{0}' finished with a continuation bit.": { + "code": 5021, + "category": 1 /* Error */ + }, + "Unknown option '{0}'": { + "code": 5023, + "category": 1 /* Error */ + }, + "Expected {0} arguments to message, got {1} instead.": { + "code": 5024, + "category": 1 /* Error */ + }, + "Expected the message '{0}' to have {1} arguments, but it had {2}": { + "code": 5025, + "category": 1 /* Error */ + }, + "Could not delete file '{0}'": { + "code": 5034, + "category": 1 /* Error */ + }, + "Could not create directory '{0}'": { + "code": 5035, + "category": 1 /* Error */ + }, + "Error while executing file '{0}': ": { + "code": 5036, + "category": 1 /* Error */ + }, + "Cannot compile external modules unless the '--module' flag is provided.": { + "code": 5037, + "category": 1 /* Error */ + }, + "Option mapRoot cannot be specified without specifying sourcemap option.": { + "code": 5038, + "category": 1 /* Error */ + }, + "Option sourceRoot cannot be specified without specifying sourcemap option.": { + "code": 5039, + "category": 1 /* Error */ + }, + "Options mapRoot and sourceRoot cannot be specified without specifying sourcemap option.": { + "code": 5040, + "category": 1 /* Error */ + }, + "Option '{0}' specified without '{1}'": { + "code": 5041, + "category": 1 /* Error */ + }, + "'codepage' option not supported on current platform.": { + "code": 5042, + "category": 1 /* Error */ + }, + "Concatenate and emit output to single file.": { + "code": 6001, + "category": 2 /* Message */ + }, + "Generates corresponding {0} file.": { + "code": 6002, + "category": 2 /* Message */ + }, + "Specifies the location where debugger should locate map files instead of generated locations.": { + "code": 6003, + "category": 2 /* Message */ + }, + "Specifies the location where debugger should locate TypeScript files instead of source locations.": { + "code": 6004, + "category": 2 /* Message */ + }, + "Watch input files.": { + "code": 6005, + "category": 2 /* Message */ + }, + "Redirect output structure to the directory.": { + "code": 6006, + "category": 2 /* Message */ + }, + "Do not emit comments to output.": { + "code": 6009, + "category": 2 /* Message */ + }, + "Skip resolution and preprocessing.": { + "code": 6010, + "category": 2 /* Message */ + }, + "Specify ECMAScript target version: '{0}' (default), or '{1}'": { + "code": 6015, + "category": 2 /* Message */ + }, + "Specify module code generation: '{0}' or '{1}'": { + "code": 6016, + "category": 2 /* Message */ + }, + "Print this message.": { + "code": 6017, + "category": 2 /* Message */ + }, + "Print the compiler's version: {0}": { + "code": 6019, + "category": 2 /* Message */ + }, + "Allow use of deprecated '{0}' keyword when referencing an external module.": { + "code": 6021, + "category": 2 /* Message */ + }, + "Specify locale for errors and messages. For example '{0}' or '{1}'": { + "code": 6022, + "category": 2 /* Message */ + }, + "Syntax: {0}": { + "code": 6023, + "category": 2 /* Message */ + }, + "options": { + "code": 6024, + "category": 2 /* Message */ + }, + "file1": { + "code": 6025, + "category": 2 /* Message */ + }, + "Examples:": { + "code": 6026, + "category": 2 /* Message */ + }, + "Options:": { + "code": 6027, + "category": 2 /* Message */ + }, + "Insert command line options and files from a file.": { + "code": 6030, + "category": 2 /* Message */ + }, + "Version {0}": { + "code": 6029, + "category": 2 /* Message */ + }, + "Use the '{0}' flag to see options.": { + "code": 6031, + "category": 2 /* Message */ + }, + "{NL}Recompiling ({0}):": { + "code": 6032, + "category": 2 /* Message */ + }, + "STRING": { + "code": 6033, + "category": 2 /* Message */ + }, + "KIND": { + "code": 6034, + "category": 2 /* Message */ + }, + "file2": { + "code": 6035, + "category": 2 /* Message */ + }, + "VERSION": { + "code": 6036, + "category": 2 /* Message */ + }, + "LOCATION": { + "code": 6037, + "category": 2 /* Message */ + }, + "DIRECTORY": { + "code": 6038, + "category": 2 /* Message */ + }, + "NUMBER": { + "code": 6039, + "category": 2 /* Message */ + }, + "Specify the codepage to use when opening source files.": { + "code": 6040, + "category": 2 /* Message */ + }, + "Additional locations:": { + "code": 6041, + "category": 2 /* Message */ + }, + "This version of the Javascript runtime does not support the '{0}' function.": { + "code": 7000, + "category": 1 /* Error */ + }, + "Unknown rule.": { + "code": 7002, + "category": 1 /* Error */ + }, + "Invalid line number ({0})": { + "code": 7003, + "category": 1 /* Error */ + }, + "Warn on expressions and declarations with an implied 'any' type.": { + "code": 7004, + "category": 2 /* Message */ + }, + "Variable '{0}' implicitly has an 'any' type.": { + "code": 7005, + "category": 1 /* Error */ + }, + "Parameter '{0}' of '{1}' implicitly has an 'any' type.": { + "code": 7006, + "category": 1 /* Error */ + }, + "Parameter '{0}' of function type implicitly has an 'any' type.": { + "code": 7007, + "category": 1 /* Error */ + }, + "Member '{0}' of object type implicitly has an 'any' type.": { + "code": 7008, + "category": 1 /* Error */ + }, + "'new' expression, which lacks a constructor signature, implicitly has an 'any' type.": { + "code": 7009, + "category": 1 /* Error */ + }, + "'{0}', which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7010, + "category": 1 /* Error */ + }, + "Function expression, which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7011, + "category": 1 /* Error */ + }, + "Parameter '{0}' of lambda function implicitly has an 'any' type.": { + "code": 7012, + "category": 1 /* Error */ + }, + "Constructor signature, which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7013, + "category": 1 /* Error */ + }, + "Lambda Function, which lacks return-type annotation, implicitly has an 'any' return type.": { + "code": 7014, + "category": 1 /* Error */ + }, + "Array Literal implicitly has an 'any' type from widening.": { + "code": 7015, + "category": 1 /* Error */ + }, + "'{0}', which lacks 'get' accessor and parameter type annotation on 'set' accessor, implicitly has an 'any' type.": { + "code": 7016, + "category": 1 /* Error */ + }, + "Index signature of object type implicitly has an 'any' type.": { + "code": 7017, + "category": 1 /* Error */ + }, + "Object literal's property '{0}' implicitly has an 'any' type from widening.": { + "code": 7018, + "category": 1 /* Error */ + } + }; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 0x2028] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 0x2029] = "paragraphSeparator"; + + CharacterCodes[CharacterCodes["nextLine"] = 0x0085] = "nextLine"; + + CharacterCodes[CharacterCodes["space"] = 0x0020] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 0x00A0] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 0x2000] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 0x2001] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 0x2002] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 0x2003] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 0x2004] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 0x2005] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 0x2006] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 0x2007] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 0x2008] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 0x2009] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 0x200A] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 0x200B] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 0x202F] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 0x3000] = "ideographicSpace"; + + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 0xFEFF] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(TypeScript.CharacterCodes || (TypeScript.CharacterCodes = {})); + var CharacterCodes = TypeScript.CharacterCodes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + + + (function (ScriptSnapshot) { + var StringScriptSnapshot = (function () { + function StringScriptSnapshot(text) { + this.text = text; + this._lineStartPositions = null; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + + StringScriptSnapshot.prototype.getLineStartPositions = function () { + if (!this._lineStartPositions) { + this._lineStartPositions = TypeScript.TextUtilities.parseLineStarts(this.text); + } + + return this._lineStartPositions; + }; + + StringScriptSnapshot.prototype.getTextChangeRangeSinceVersion = function (scriptVersion) { + throw TypeScript.Errors.notYetImplemented(); + }; + return StringScriptSnapshot; + })(); + + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(TypeScript.ScriptSnapshot || (TypeScript.ScriptSnapshot = {})); + var ScriptSnapshot = TypeScript.ScriptSnapshot; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (LineMap1) { + function fromSimpleText(text) { + return new TypeScript.LineMap(function () { + return TypeScript.TextUtilities.parseLineStarts({ charCodeAt: function (index) { + return text.charCodeAt(index); + }, length: text.length() }); + }, text.length()); + } + LineMap1.fromSimpleText = fromSimpleText; + + function fromScriptSnapshot(scriptSnapshot) { + return new TypeScript.LineMap(function () { + return scriptSnapshot.getLineStartPositions(); + }, scriptSnapshot.getLength()); + } + LineMap1.fromScriptSnapshot = fromScriptSnapshot; + + function fromString(text) { + return new TypeScript.LineMap(function () { + return TypeScript.TextUtilities.parseLineStarts(text); + }, text.length); + } + LineMap1.fromString = fromString; + })(TypeScript.LineMap1 || (TypeScript.LineMap1 = {})); + var LineMap1 = TypeScript.LineMap1; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TextFactory) { + function getStartAndLengthOfLineBreakEndingAt(text, index, info) { + var c = text.charCodeAt(index); + if (c === 10 /* lineFeed */) { + if (index > 0 && text.charCodeAt(index - 1) === 13 /* carriageReturn */) { + info.startPosition = index - 1; + info.length = 2; + } else { + info.startPosition = index; + info.length = 1; + } + } else if (TypeScript.TextUtilities.isAnyLineBreakCharacter(c)) { + info.startPosition = index; + info.length = 1; + } else { + info.startPosition = index + 1; + info.length = 0; + } + } + + var LinebreakInfo = (function () { + function LinebreakInfo(startPosition, length) { + this.startPosition = startPosition; + this.length = length; + } + return LinebreakInfo; + })(); + + var TextLine = (function () { + function TextLine(text, body, lineBreakLength, lineNumber) { + this._text = null; + this._textSpan = null; + if (text === null) { + throw TypeScript.Errors.argumentNull('text'); + } + TypeScript.Debug.assert(lineBreakLength >= 0); + TypeScript.Debug.assert(lineNumber >= 0); + this._text = text; + this._textSpan = body; + this._lineBreakLength = lineBreakLength; + this._lineNumber = lineNumber; + } + TextLine.prototype.start = function () { + return this._textSpan.start(); + }; + + TextLine.prototype.end = function () { + return this._textSpan.end(); + }; + + TextLine.prototype.endIncludingLineBreak = function () { + return this.end() + this._lineBreakLength; + }; + + TextLine.prototype.extent = function () { + return this._textSpan; + }; + + TextLine.prototype.extentIncludingLineBreak = function () { + return TypeScript.TextSpan.fromBounds(this.start(), this.endIncludingLineBreak()); + }; + + TextLine.prototype.toString = function () { + return this._text.toString(this._textSpan); + }; + + TextLine.prototype.lineNumber = function () { + return this._lineNumber; + }; + return TextLine; + })(); + + var TextBase = (function () { + function TextBase() { + this.linebreakInfo = new LinebreakInfo(0, 0); + this.lastLineFoundForPosition = null; + } + TextBase.prototype.length = function () { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.charCodeAt = function (position) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.checkSubSpan = function (span) { + if (span.start() < 0 || span.start() > this.length() || span.end() > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("span"); + } + }; + + TextBase.prototype.toString = function (span) { + if (typeof span === "undefined") { span = null; } + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SubText(this, span); + }; + + TextBase.prototype.substr = function (start, length, intern) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.lineCount = function () { + return this._lineStarts().length; + }; + + TextBase.prototype.lines = function () { + var lines = []; + + var length = this.lineCount(); + for (var i = 0; i < length; ++i) { + lines[i] = this.getLineFromLineNumber(i); + } + + return lines; + }; + + TextBase.prototype.lineMap = function () { + var _this = this; + return new TypeScript.LineMap(function () { + return _this._lineStarts(); + }, this.length()); + }; + + TextBase.prototype._lineStarts = function () { + throw TypeScript.Errors.abstract(); + }; + + TextBase.prototype.getLineFromLineNumber = function (lineNumber) { + var lineStarts = this._lineStarts(); + + if (lineNumber < 0 || lineNumber >= lineStarts.length) { + throw TypeScript.Errors.argumentOutOfRange("lineNumber"); + } + + var first = lineStarts[lineNumber]; + if (lineNumber === lineStarts.length - 1) { + return new TextLine(this, new TypeScript.TextSpan(first, this.length() - first), 0, lineNumber); + } else { + getStartAndLengthOfLineBreakEndingAt(this, lineStarts[lineNumber + 1] - 1, this.linebreakInfo); + return new TextLine(this, new TypeScript.TextSpan(first, this.linebreakInfo.startPosition - first), this.linebreakInfo.length, lineNumber); + } + }; + + TextBase.prototype.getLineFromPosition = function (position) { + var lastFound = this.lastLineFoundForPosition; + if (lastFound !== null && lastFound.start() <= position && lastFound.endIncludingLineBreak() > position) { + return lastFound; + } + + var lineNumber = this.getLineNumberFromPosition(position); + + var result = this.getLineFromLineNumber(lineNumber); + this.lastLineFoundForPosition = result; + return result; + }; + + TextBase.prototype.getLineNumberFromPosition = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + if (position === this.length()) { + return this.lineCount() - 1; + } + + var lineNumber = TypeScript.ArrayUtilities.binarySearch(this._lineStarts(), position); + if (lineNumber < 0) { + lineNumber = (~lineNumber) - 1; + } + + return lineNumber; + }; + + TextBase.prototype.getLinePosition = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var lineNumber = this.getLineNumberFromPosition(position); + + return new TypeScript.LineAndCharacter(lineNumber, position - this._lineStarts()[lineNumber]); + }; + return TextBase; + })(); + + var SubText = (function (_super) { + __extends(SubText, _super); + function SubText(text, span) { + _super.call(this); + this._lazyLineStarts = null; + + if (text === null) { + throw TypeScript.Errors.argumentNull("text"); + } + + if (span.start() < 0 || span.start() >= text.length() || span.end() < 0 || span.end() > text.length()) { + throw TypeScript.Errors.argument("span"); + } + + this.text = text; + this.span = span; + } + SubText.prototype.length = function () { + return this.span.length(); + }; + + SubText.prototype.charCodeAt = function (position) { + if (position < 0 || position > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + return this.text.charCodeAt(this.span.start() + position); + }; + + SubText.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SubText(this.text, this.getCompositeSpan(span.start(), span.length())); + }; + + SubText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var span = this.getCompositeSpan(sourceIndex, count); + this.text.copyTo(span.start(), destination, destinationIndex, span.length()); + }; + + SubText.prototype.substr = function (start, length, intern) { + var startInOriginalText = this.span.start() + start; + return this.text.substr(startInOriginalText, length, intern); + }; + + SubText.prototype.getCompositeSpan = function (start, length) { + var compositeStart = TypeScript.MathPrototype.min(this.text.length(), this.span.start() + start); + var compositeEnd = TypeScript.MathPrototype.min(this.text.length(), compositeStart + length); + return new TypeScript.TextSpan(compositeStart, compositeEnd - compositeStart); + }; + + SubText.prototype._lineStarts = function () { + var _this = this; + if (!this._lazyLineStarts) { + this._lazyLineStarts = TypeScript.TextUtilities.parseLineStarts({ charCodeAt: function (index) { + return _this.charCodeAt(index); + }, length: this.length() }); + } + + return this._lazyLineStarts; + }; + return SubText; + })(TextBase); + + var StringText = (function (_super) { + __extends(StringText, _super); + function StringText(data) { + _super.call(this); + this.source = null; + this._lazyLineStarts = null; + + if (data === null) { + throw TypeScript.Errors.argumentNull("data"); + } + + this.source = data; + } + StringText.prototype.length = function () { + return this.source.length; + }; + + StringText.prototype.charCodeAt = function (position) { + if (position < 0 || position >= this.source.length) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + return this.source.charCodeAt(position); + }; + + StringText.prototype.substr = function (start, length, intern) { + return this.source.substr(start, length); + }; + + StringText.prototype.toString = function (span) { + if (typeof span === "undefined") { span = null; } + if (span === null) { + span = new TypeScript.TextSpan(0, this.length()); + } + + this.checkSubSpan(span); + + if (span.start() === 0 && span.length() === this.length()) { + return this.source; + } + + return this.source.substr(span.start(), span.length()); + }; + + StringText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + TypeScript.StringUtilities.copyTo(this.source, sourceIndex, destination, destinationIndex, count); + }; + + StringText.prototype._lineStarts = function () { + if (this._lazyLineStarts === null) { + this._lazyLineStarts = TypeScript.TextUtilities.parseLineStarts(this.source); + } + + return this._lazyLineStarts; + }; + return StringText; + })(TextBase); + + function createText(value) { + return new StringText(value); + } + TextFactory.createText = createText; + })(TypeScript.TextFactory || (TypeScript.TextFactory = {})); + var TextFactory = TypeScript.TextFactory; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (SimpleText) { + var SimpleSubText = (function () { + function SimpleSubText(text, span) { + this.text = null; + this.span = null; + if (text === null) { + throw TypeScript.Errors.argumentNull("text"); + } + + if (span.start() < 0 || span.start() >= text.length() || span.end() < 0 || span.end() > text.length()) { + throw TypeScript.Errors.argument("span"); + } + + this.text = text; + this.span = span; + } + SimpleSubText.prototype.checkSubSpan = function (span) { + if (span.start() < 0 || span.start() > this.length() || span.end() > this.length()) { + throw TypeScript.Errors.argumentOutOfRange("span"); + } + }; + + SimpleSubText.prototype.checkSubPosition = function (position) { + if (position < 0 || position >= this.length()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + }; + + SimpleSubText.prototype.length = function () { + return this.span.length(); + }; + + SimpleSubText.prototype.subText = function (span) { + this.checkSubSpan(span); + + return new SimpleSubText(this.text, this.getCompositeSpan(span.start(), span.length())); + }; + + SimpleSubText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var span = this.getCompositeSpan(sourceIndex, count); + this.text.copyTo(span.start(), destination, destinationIndex, span.length()); + }; + + SimpleSubText.prototype.substr = function (start, length, intern) { + var span = this.getCompositeSpan(start, length); + return this.text.substr(span.start(), span.length(), intern); + }; + + SimpleSubText.prototype.getCompositeSpan = function (start, length) { + var compositeStart = TypeScript.MathPrototype.min(this.text.length(), this.span.start() + start); + var compositeEnd = TypeScript.MathPrototype.min(this.text.length(), compositeStart + length); + return new TypeScript.TextSpan(compositeStart, compositeEnd - compositeStart); + }; + + SimpleSubText.prototype.charCodeAt = function (index) { + this.checkSubPosition(index); + return this.text.charCodeAt(this.span.start() + index); + }; + + SimpleSubText.prototype.lineMap = function () { + return TypeScript.LineMap1.fromSimpleText(this); + }; + return SimpleSubText; + })(); + + var SimpleStringText = (function () { + function SimpleStringText(value) { + this.value = value; + this._lineMap = null; + } + SimpleStringText.prototype.length = function () { + return this.value.length; + }; + + SimpleStringText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + TypeScript.StringUtilities.copyTo(this.value, sourceIndex, destination, destinationIndex, count); + }; + + SimpleStringText.prototype.substr = function (start, length, intern) { + if (intern) { + var array = length <= SimpleStringText.charArray.length ? SimpleStringText.charArray : TypeScript.ArrayUtilities.createArray(length, 0); + this.copyTo(start, array, 0, length); + return TypeScript.Collections.DefaultStringTable.addCharArray(array, 0, length); + } + + return this.value.substr(start, length); + }; + + SimpleStringText.prototype.subText = function (span) { + return new SimpleSubText(this, span); + }; + + SimpleStringText.prototype.charCodeAt = function (index) { + return this.value.charCodeAt(index); + }; + + SimpleStringText.prototype.lineMap = function () { + if (!this._lineMap) { + this._lineMap = TypeScript.LineMap1.fromString(this.value); + } + + return this._lineMap; + }; + SimpleStringText.charArray = TypeScript.ArrayUtilities.createArray(1024, 0); + return SimpleStringText; + })(); + + var SimpleScriptSnapshotText = (function () { + function SimpleScriptSnapshotText(scriptSnapshot) { + this.scriptSnapshot = scriptSnapshot; + } + SimpleScriptSnapshotText.prototype.charCodeAt = function (index) { + return this.scriptSnapshot.getText(index, index + 1).charCodeAt(0); + }; + + SimpleScriptSnapshotText.prototype.length = function () { + return this.scriptSnapshot.getLength(); + }; + + SimpleScriptSnapshotText.prototype.copyTo = function (sourceIndex, destination, destinationIndex, count) { + var text = this.scriptSnapshot.getText(sourceIndex, sourceIndex + count); + TypeScript.StringUtilities.copyTo(text, 0, destination, destinationIndex, count); + }; + + SimpleScriptSnapshotText.prototype.substr = function (start, length, intern) { + return this.scriptSnapshot.getText(start, start + length); + }; + + SimpleScriptSnapshotText.prototype.subText = function (span) { + return new SimpleSubText(this, span); + }; + + SimpleScriptSnapshotText.prototype.lineMap = function () { + var _this = this; + return new TypeScript.LineMap(function () { + return _this.scriptSnapshot.getLineStartPositions(); + }, this.length()); + }; + return SimpleScriptSnapshotText; + })(); + + function fromString(value) { + return new SimpleStringText(value); + } + SimpleText.fromString = fromString; + + function fromScriptSnapshot(scriptSnapshot) { + return new SimpleScriptSnapshotText(scriptSnapshot); + } + SimpleText.fromScriptSnapshot = fromScriptSnapshot; + })(TypeScript.SimpleText || (TypeScript.SimpleText = {})); + var SimpleText = TypeScript.SimpleText; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TextUtilities) { + function parseLineStarts(text) { + var length = text.length; + + if (0 === length) { + var result = new Array(); + result.push(0); + return result; + } + + var position = 0; + var index = 0; + var arrayBuilder = new Array(); + var lineNumber = 0; + + while (index < length) { + var c = text.charCodeAt(index); + var lineBreakLength; + + if (c > 13 /* carriageReturn */ && c <= 127) { + index++; + continue; + } else if (c === 13 /* carriageReturn */ && index + 1 < length && text.charCodeAt(index + 1) === 10 /* lineFeed */) { + lineBreakLength = 2; + } else if (c === 10 /* lineFeed */) { + lineBreakLength = 1; + } else { + lineBreakLength = TextUtilities.getLengthOfLineBreak(text, index); + } + + if (0 === lineBreakLength) { + index++; + } else { + arrayBuilder.push(position); + index += lineBreakLength; + position = index; + lineNumber++; + } + } + + arrayBuilder.push(position); + + return arrayBuilder; + } + TextUtilities.parseLineStarts = parseLineStarts; + + function getLengthOfLineBreakSlow(text, index, c) { + if (c === 13 /* carriageReturn */) { + var next = index + 1; + return (next < text.length) && 10 /* lineFeed */ === text.charCodeAt(next) ? 2 : 1; + } else if (isAnyLineBreakCharacter(c)) { + return 1; + } else { + return 0; + } + } + TextUtilities.getLengthOfLineBreakSlow = getLengthOfLineBreakSlow; + + function getLengthOfLineBreak(text, index) { + var c = text.charCodeAt(index); + + if (c > 13 /* carriageReturn */ && c <= 127) { + return 0; + } + + return getLengthOfLineBreakSlow(text, index, c); + } + TextUtilities.getLengthOfLineBreak = getLengthOfLineBreak; + + function isAnyLineBreakCharacter(c) { + return c === 10 /* lineFeed */ || c === 13 /* carriageReturn */ || c === 133 /* nextLine */ || c === 8232 /* lineSeparator */ || c === 8233 /* paragraphSeparator */; + } + TextUtilities.isAnyLineBreakCharacter = isAnyLineBreakCharacter; + })(TypeScript.TextUtilities || (TypeScript.TextUtilities = {})); + var TextUtilities = TypeScript.TextUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextSpan = (function () { + function TextSpan(start, length) { + if (start < 0) { + TypeScript.Errors.argument("start"); + } + + if (length < 0) { + TypeScript.Errors.argument("length"); + } + + this._start = start; + this._length = length; + } + TextSpan.prototype.start = function () { + return this._start; + }; + + TextSpan.prototype.length = function () { + return this._length; + }; + + TextSpan.prototype.end = function () { + return this._start + this._length; + }; + + TextSpan.prototype.isEmpty = function () { + return this._length === 0; + }; + + TextSpan.prototype.containsPosition = function (position) { + return position >= this._start && position < this.end(); + }; + + TextSpan.prototype.containsTextSpan = function (span) { + return span._start >= this._start && span.end() <= this.end(); + }; + + TextSpan.prototype.overlapsWith = function (span) { + var overlapStart = TypeScript.MathPrototype.max(this._start, span._start); + var overlapEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + return overlapStart < overlapEnd; + }; + + TextSpan.prototype.overlap = function (span) { + var overlapStart = TypeScript.MathPrototype.max(this._start, span._start); + var overlapEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + if (overlapStart < overlapEnd) { + return TextSpan.fromBounds(overlapStart, overlapEnd); + } + + return null; + }; + + TextSpan.prototype.intersectsWithTextSpan = function (span) { + return span._start <= this.end() && span.end() >= this._start; + }; + + TextSpan.prototype.intersectsWith = function (start, length) { + var end = start + length; + return start <= this.end() && end >= this._start; + }; + + TextSpan.prototype.intersectsWithPosition = function (position) { + return position <= this.end() && position >= this._start; + }; + + TextSpan.prototype.intersection = function (span) { + var intersectStart = TypeScript.MathPrototype.max(this._start, span._start); + var intersectEnd = TypeScript.MathPrototype.min(this.end(), span.end()); + + if (intersectStart <= intersectEnd) { + return TextSpan.fromBounds(intersectStart, intersectEnd); + } + + return null; + }; + + TextSpan.fromBounds = function (start, end) { + TypeScript.Debug.assert(start >= 0); + TypeScript.Debug.assert(end - start >= 0); + return new TextSpan(start, end - start); + }; + return TextSpan; + })(); + TypeScript.TextSpan = TextSpan; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextChangeRange = (function () { + function TextChangeRange(span, newLength) { + if (newLength < 0) { + throw TypeScript.Errors.argumentOutOfRange("newLength"); + } + + this._span = span; + this._newLength = newLength; + } + TextChangeRange.prototype.span = function () { + return this._span; + }; + + TextChangeRange.prototype.newLength = function () { + return this._newLength; + }; + + TextChangeRange.prototype.newSpan = function () { + return new TypeScript.TextSpan(this.span().start(), this.newLength()); + }; + + TextChangeRange.prototype.isUnchanged = function () { + return this.span().isEmpty() && this.newLength() === 0; + }; + + TextChangeRange.collapseChangesFromSingleVersion = function (changes) { + var diff = 0; + var start = 1073741823 /* Max31BitInteger */; + var end = 0; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + diff += change.newLength() - change.span().length(); + + if (change.span().start() < start) { + start = change.span().start(); + } + + if (change.span().end() > end) { + end = change.span().end(); + } + } + + if (start > end) { + return null; + } + + var combined = TypeScript.TextSpan.fromBounds(start, end); + var newLen = combined.length() + diff; + + return new TextChangeRange(combined, newLen); + }; + + TextChangeRange.collapseChangesAcrossMultipleVersions = function (changes) { + if (changes.length === 0) { + return TextChangeRange.unchanged; + } + + if (changes.length === 1) { + return changes[0]; + } + + var change0 = changes[0]; + + var oldStartN = change0.span().start(); + var oldEndN = change0.span().end(); + var newEndN = oldStartN + change0.newLength(); + + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + + var oldStart2 = nextChange.span().start(); + var oldEnd2 = nextChange.span().end(); + var newEnd2 = oldStart2 + nextChange.newLength(); + + oldStartN = TypeScript.MathPrototype.min(oldStart1, oldStart2); + oldEndN = TypeScript.MathPrototype.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = TypeScript.MathPrototype.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + + return new TextChangeRange(TypeScript.TextSpan.fromBounds(oldStartN, oldEndN), newEndN - oldStartN); + }; + TextChangeRange.unchanged = new TextChangeRange(new TypeScript.TextSpan(0, 0), 0); + return TextChangeRange; + })(); + TypeScript.TextChangeRange = TextChangeRange; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CharacterInfo = (function () { + function CharacterInfo() { + } + CharacterInfo.isDecimalDigit = function (c) { + return c >= 48 /* _0 */ && c <= 57 /* _9 */; + }; + CharacterInfo.isOctalDigit = function (c) { + return c >= 48 /* _0 */ && c <= 55 /* _7 */; + }; + + CharacterInfo.isHexDigit = function (c) { + return CharacterInfo.isDecimalDigit(c) || (c >= 65 /* A */ && c <= 70 /* F */) || (c >= 97 /* a */ && c <= 102 /* f */); + }; + + CharacterInfo.hexValue = function (c) { + return CharacterInfo.isDecimalDigit(c) ? (c - 48 /* _0 */) : (c >= 65 /* A */ && c <= 70 /* F */) ? c - 65 /* A */ + 10 : c - 97 /* a */ + 10; + }; + + CharacterInfo.isWhitespace = function (ch) { + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + return true; + } + + return false; + }; + + CharacterInfo.isLineTerminator = function (ch) { + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + return true; + } + + return false; + }; + return CharacterInfo; + })(); + TypeScript.CharacterInfo = CharacterInfo; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxConstants) { + SyntaxConstants[SyntaxConstants["TriviaNewLineMask"] = 0x00000001] = "TriviaNewLineMask"; + SyntaxConstants[SyntaxConstants["TriviaCommentMask"] = 0x00000002] = "TriviaCommentMask"; + SyntaxConstants[SyntaxConstants["TriviaFullWidthShift"] = 2] = "TriviaFullWidthShift"; + + SyntaxConstants[SyntaxConstants["NodeDataComputed"] = 0x00000001] = "NodeDataComputed"; + SyntaxConstants[SyntaxConstants["NodeIncrementallyUnusableMask"] = 0x00000002] = "NodeIncrementallyUnusableMask"; + SyntaxConstants[SyntaxConstants["NodeParsedInStrictModeMask"] = 0x00000004] = "NodeParsedInStrictModeMask"; + SyntaxConstants[SyntaxConstants["NodeFullWidthShift"] = 3] = "NodeFullWidthShift"; + + SyntaxConstants[SyntaxConstants["IsVariableWidthKeyword"] = 1 << 31] = "IsVariableWidthKeyword"; + })(TypeScript.SyntaxConstants || (TypeScript.SyntaxConstants = {})); + var SyntaxConstants = TypeScript.SyntaxConstants; +})(TypeScript || (TypeScript = {})); +var FormattingOptions = (function () { + function FormattingOptions(useTabs, spacesPerTab, indentSpaces, newLineCharacter) { + this.useTabs = useTabs; + this.spacesPerTab = spacesPerTab; + this.indentSpaces = indentSpaces; + this.newLineCharacter = newLineCharacter; + } + FormattingOptions.defaultOptions = new FormattingOptions(false, 4, 4, "\r\n"); + return FormattingOptions; +})(); +var TypeScript; +(function (TypeScript) { + (function (Indentation) { + function columnForEndOfToken(token, syntaxInformationMap, options) { + return columnForStartOfToken(token, syntaxInformationMap, options) + token.width(); + } + Indentation.columnForEndOfToken = columnForEndOfToken; + + function columnForStartOfToken(token, syntaxInformationMap, options) { + var firstTokenInLine = syntaxInformationMap.firstTokenInLineContainingToken(token); + var leadingTextInReverse = []; + + var current = token; + while (current !== firstTokenInLine) { + current = syntaxInformationMap.previousToken(current); + + if (current === firstTokenInLine) { + leadingTextInReverse.push(current.trailingTrivia().fullText()); + leadingTextInReverse.push(current.text()); + } else { + leadingTextInReverse.push(current.fullText()); + } + } + + collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse); + + return columnForLeadingTextInReverse(leadingTextInReverse, options); + } + Indentation.columnForStartOfToken = columnForStartOfToken; + + function columnForStartOfFirstTokenInLineContainingToken(token, syntaxInformationMap, options) { + var firstTokenInLine = syntaxInformationMap.firstTokenInLineContainingToken(token); + var leadingTextInReverse = []; + + collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse); + + return columnForLeadingTextInReverse(leadingTextInReverse, options); + } + Indentation.columnForStartOfFirstTokenInLineContainingToken = columnForStartOfFirstTokenInLineContainingToken; + + function collectLeadingTriviaTextToStartOfLine(firstTokenInLine, leadingTextInReverse) { + var leadingTrivia = firstTokenInLine.leadingTrivia(); + + for (var i = leadingTrivia.count() - 1; i >= 0; i--) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.kind() === 5 /* NewLineTrivia */) { + break; + } + + if (trivia.kind() === 6 /* MultiLineCommentTrivia */) { + var lineSegments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + leadingTextInReverse.push(TypeScript.ArrayUtilities.last(lineSegments)); + + if (lineSegments.length > 0) { + break; + } + } + + leadingTextInReverse.push(trivia.fullText()); + } + } + + function columnForLeadingTextInReverse(leadingTextInReverse, options) { + var column = 0; + + for (var i = leadingTextInReverse.length - 1; i >= 0; i--) { + var text = leadingTextInReverse[i]; + column = columnForPositionInStringWorker(text, text.length, column, options); + } + + return column; + } + + function columnForPositionInString(input, position, options) { + return columnForPositionInStringWorker(input, position, 0, options); + } + Indentation.columnForPositionInString = columnForPositionInString; + + function columnForPositionInStringWorker(input, position, startColumn, options) { + var column = startColumn; + var spacesPerTab = options.spacesPerTab; + + for (var j = 0; j < position; j++) { + var ch = input.charCodeAt(j); + + if (ch === 9 /* tab */) { + column += spacesPerTab - column % spacesPerTab; + } else { + column++; + } + } + + return column; + } + + function indentationString(column, options) { + var numberOfTabs = 0; + var numberOfSpaces = TypeScript.MathPrototype.max(0, column); + + if (options.useTabs) { + numberOfTabs = Math.floor(column / options.spacesPerTab); + numberOfSpaces -= numberOfTabs * options.spacesPerTab; + } + + return TypeScript.StringUtilities.repeat('\t', numberOfTabs) + TypeScript.StringUtilities.repeat(' ', numberOfSpaces); + } + Indentation.indentationString = indentationString; + + function indentationTrivia(column, options) { + return TypeScript.Syntax.whitespace(this.indentationString(column, options)); + } + Indentation.indentationTrivia = indentationTrivia; + + function firstNonWhitespacePosition(value) { + for (var i = 0; i < value.length; i++) { + var ch = value.charCodeAt(i); + if (!TypeScript.CharacterInfo.isWhitespace(ch)) { + return i; + } + } + + return value.length; + } + Indentation.firstNonWhitespacePosition = firstNonWhitespacePosition; + })(TypeScript.Indentation || (TypeScript.Indentation = {})); + var Indentation = TypeScript.Indentation; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (LanguageVersion) { + LanguageVersion[LanguageVersion["EcmaScript3"] = 0] = "EcmaScript3"; + LanguageVersion[LanguageVersion["EcmaScript5"] = 1] = "EcmaScript5"; + })(TypeScript.LanguageVersion || (TypeScript.LanguageVersion = {})); + var LanguageVersion = TypeScript.LanguageVersion; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ParseOptions = (function () { + function ParseOptions(languageVersion, allowAutomaticSemicolonInsertion) { + this._languageVersion = languageVersion; + this._allowAutomaticSemicolonInsertion = allowAutomaticSemicolonInsertion; + } + ParseOptions.prototype.toJSON = function (key) { + return { allowAutomaticSemicolonInsertion: this._allowAutomaticSemicolonInsertion }; + }; + + ParseOptions.prototype.languageVersion = function () { + return this._languageVersion; + }; + + ParseOptions.prototype.allowAutomaticSemicolonInsertion = function () { + return this._allowAutomaticSemicolonInsertion; + }; + return ParseOptions; + })(); + TypeScript.ParseOptions = ParseOptions; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PositionedElement = (function () { + function PositionedElement(parent, element, fullStart) { + this._parent = parent; + this._element = element; + this._fullStart = fullStart; + } + PositionedElement.create = function (parent, element, fullStart) { + if (element === null) { + return null; + } + + if (element.isNode()) { + return new PositionedNode(parent, element, fullStart); + } else if (element.isToken()) { + return new PositionedToken(parent, element, fullStart); + } else if (element.isList()) { + return new PositionedList(parent, element, fullStart); + } else if (element.isSeparatedList()) { + return new PositionedSeparatedList(parent, element, fullStart); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + PositionedElement.prototype.parent = function () { + return this._parent; + }; + + PositionedElement.prototype.parentElement = function () { + return this._parent && this._parent._element; + }; + + PositionedElement.prototype.element = function () { + return this._element; + }; + + PositionedElement.prototype.kind = function () { + return this.element().kind(); + }; + + PositionedElement.prototype.childIndex = function (child) { + return TypeScript.Syntax.childIndex(this.element(), child); + }; + + PositionedElement.prototype.childCount = function () { + return this.element().childCount(); + }; + + PositionedElement.prototype.childAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + return PositionedElement.create(this, this.element().childAt(index), this.fullStart() + offset); + }; + + PositionedElement.prototype.childStart = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return this.fullStart() + offset + child.leadingTriviaWidth(); + }; + + PositionedElement.prototype.childEnd = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return this.fullStart() + offset + child.leadingTriviaWidth() + child.width(); + }; + + PositionedElement.prototype.childStartAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + var child = this.element().childAt(index); + return this.fullStart() + offset + child.leadingTriviaWidth(); + }; + + PositionedElement.prototype.childEndAt = function (index) { + var offset = TypeScript.Syntax.childOffsetAt(this.element(), index); + var child = this.element().childAt(index); + return this.fullStart() + offset + child.leadingTriviaWidth() + child.width(); + }; + + PositionedElement.prototype.getPositionedChild = function (child) { + var offset = TypeScript.Syntax.childOffset(this.element(), child); + return PositionedElement.create(this, child, this.fullStart() + offset); + }; + + PositionedElement.prototype.fullStart = function () { + return this._fullStart; + }; + + PositionedElement.prototype.fullEnd = function () { + return this.fullStart() + this.element().fullWidth(); + }; + + PositionedElement.prototype.fullWidth = function () { + return this.element().fullWidth(); + }; + + PositionedElement.prototype.start = function () { + return this.fullStart() + this.element().leadingTriviaWidth(); + }; + + PositionedElement.prototype.end = function () { + return this.fullStart() + this.element().leadingTriviaWidth() + this.element().width(); + }; + + PositionedElement.prototype.root = function () { + var current = this; + while (current.parent() !== null) { + current = current.parent(); + } + + return current; + }; + + PositionedElement.prototype.containingNode = function () { + var current = this.parent(); + + while (current !== null && !current.element().isNode()) { + current = current.parent(); + } + + return current; + }; + return PositionedElement; + })(); + TypeScript.PositionedElement = PositionedElement; + + var PositionedNodeOrToken = (function (_super) { + __extends(PositionedNodeOrToken, _super); + function PositionedNodeOrToken(parent, nodeOrToken, fullStart) { + _super.call(this, parent, nodeOrToken, fullStart); + } + PositionedNodeOrToken.prototype.nodeOrToken = function () { + return this.element(); + }; + return PositionedNodeOrToken; + })(PositionedElement); + TypeScript.PositionedNodeOrToken = PositionedNodeOrToken; + + var PositionedNode = (function (_super) { + __extends(PositionedNode, _super); + function PositionedNode(parent, node, fullStart) { + _super.call(this, parent, node, fullStart); + } + PositionedNode.prototype.node = function () { + return this.element(); + }; + return PositionedNode; + })(PositionedNodeOrToken); + TypeScript.PositionedNode = PositionedNode; + + var PositionedToken = (function (_super) { + __extends(PositionedToken, _super); + function PositionedToken(parent, token, fullStart) { + _super.call(this, parent, token, fullStart); + } + PositionedToken.prototype.token = function () { + return this.element(); + }; + + PositionedToken.prototype.previousToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var triviaList = this.token().leadingTrivia(); + if (includeSkippedTokens && triviaList && triviaList.hasSkippedToken()) { + var currentTriviaEndPosition = this.start(); + for (var i = triviaList.count() - 1; i >= 0; i--) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isSkippedToken()) { + return new PositionedSkippedToken(this, trivia.skippedToken(), currentTriviaEndPosition - trivia.fullWidth()); + } + + currentTriviaEndPosition -= trivia.fullWidth(); + } + } + + var start = this.fullStart(); + if (start === 0) { + return null; + } + + return this.root().node().findToken(start - 1, includeSkippedTokens); + }; + + PositionedToken.prototype.nextToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + if (this.token().tokenKind === 10 /* EndOfFileToken */) { + return null; + } + + var triviaList = this.token().trailingTrivia(); + if (includeSkippedTokens && triviaList && triviaList.hasSkippedToken()) { + var fullStart = this.end(); + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (trivia.isSkippedToken()) { + return new PositionedSkippedToken(this, trivia.skippedToken(), fullStart); + } + + fullStart += trivia.fullWidth(); + } + } + + return this.root().node().findToken(this.fullEnd(), includeSkippedTokens); + }; + return PositionedToken; + })(PositionedNodeOrToken); + TypeScript.PositionedToken = PositionedToken; + + var PositionedList = (function (_super) { + __extends(PositionedList, _super); + function PositionedList(parent, list, fullStart) { + _super.call(this, parent, list, fullStart); + } + PositionedList.prototype.list = function () { + return this.element(); + }; + return PositionedList; + })(PositionedElement); + TypeScript.PositionedList = PositionedList; + + var PositionedSeparatedList = (function (_super) { + __extends(PositionedSeparatedList, _super); + function PositionedSeparatedList(parent, list, fullStart) { + _super.call(this, parent, list, fullStart); + } + PositionedSeparatedList.prototype.list = function () { + return this.element(); + }; + return PositionedSeparatedList; + })(PositionedElement); + TypeScript.PositionedSeparatedList = PositionedSeparatedList; + + var PositionedSkippedToken = (function (_super) { + __extends(PositionedSkippedToken, _super); + function PositionedSkippedToken(parentToken, token, fullStart) { + _super.call(this, parentToken.parent(), token, fullStart); + this._parentToken = parentToken; + } + PositionedSkippedToken.prototype.parentToken = function () { + return this._parentToken; + }; + + PositionedSkippedToken.prototype.previousToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var start = this.fullStart(); + + if (includeSkippedTokens) { + var previousToken; + + if (start >= this.parentToken().end()) { + previousToken = TypeScript.Syntax.findSkippedTokenInTrailingTriviaList(this.parentToken(), start - 1); + + if (previousToken) { + return previousToken; + } + + return this.parentToken(); + } else { + previousToken = TypeScript.Syntax.findSkippedTokenInLeadingTriviaList(this.parentToken(), start - 1); + + if (previousToken) { + return previousToken; + } + } + } + + var start = this.parentToken().fullStart(); + if (start === 0) { + return null; + } + + return this.root().node().findToken(start - 1, includeSkippedTokens); + }; + + PositionedSkippedToken.prototype.nextToken = function (includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + if (this.token().tokenKind === 10 /* EndOfFileToken */) { + return null; + } + + if (includeSkippedTokens) { + var end = this.end(); + var nextToken; + + if (end <= this.parentToken().start()) { + nextToken = TypeScript.Syntax.findSkippedTokenInLeadingTriviaList(this.parentToken(), end); + + if (nextToken) { + return nextToken; + } + + return this.parentToken(); + } else { + nextToken = TypeScript.Syntax.findSkippedTokenInTrailingTriviaList(this.parentToken(), end); + + if (nextToken) { + return nextToken; + } + } + } + + return this.root().node().findToken(this.parentToken().fullEnd(), includeSkippedTokens); + }; + return PositionedSkippedToken; + })(PositionedToken); + TypeScript.PositionedSkippedToken = PositionedSkippedToken; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["None"] = 0] = "None"; + SyntaxKind[SyntaxKind["List"] = 1] = "List"; + SyntaxKind[SyntaxKind["SeparatedList"] = 2] = "SeparatedList"; + SyntaxKind[SyntaxKind["TriviaList"] = 3] = "TriviaList"; + + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 4] = "WhitespaceTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 5] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 6] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 7] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["SkippedTokenTrivia"] = 8] = "SkippedTokenTrivia"; + + SyntaxKind[SyntaxKind["ErrorToken"] = 9] = "ErrorToken"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 10] = "EndOfFileToken"; + + SyntaxKind[SyntaxKind["IdentifierName"] = 11] = "IdentifierName"; + + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 13] = "NumericLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 14] = "StringLiteral"; + + SyntaxKind[SyntaxKind["BreakKeyword"] = 15] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 16] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 17] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 18] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 19] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 20] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 21] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 22] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 23] = "ElseKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 24] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 25] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 26] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 27] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 28] = "IfKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 29] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 30] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 31] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 32] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 33] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 34] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 35] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 36] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 37] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 38] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 39] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 40] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 41] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 42] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 43] = "WithKeyword"; + + SyntaxKind[SyntaxKind["ClassKeyword"] = 44] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 45] = "ConstKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 46] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 47] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 48] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 49] = "ImportKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 50] = "SuperKeyword"; + + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 51] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 52] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 53] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 54] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 55] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 56] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 57] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 58] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 59] = "YieldKeyword"; + + SyntaxKind[SyntaxKind["AnyKeyword"] = 60] = "AnyKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 61] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 62] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 63] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 64] = "GetKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 65] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 66] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 67] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 68] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 69] = "StringKeyword"; + + SyntaxKind[SyntaxKind["OpenBraceToken"] = 70] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 71] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 72] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 73] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 74] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 75] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 76] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 77] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 78] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 79] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 80] = "LessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 81] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 82] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 83] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 84] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 85] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 86] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 87] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 88] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 89] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 90] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 91] = "AsteriskToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 92] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 93] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 94] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 95] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 96] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 97] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 98] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 99] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 100] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 101] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 102] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 103] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 104] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 105] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 106] = "ColonToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 107] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 108] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 109] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 110] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 111] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 112] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 113] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 114] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 115] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 116] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 117] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 118] = "SlashToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 119] = "SlashEqualsToken"; + + SyntaxKind[SyntaxKind["SourceUnit"] = 120] = "SourceUnit"; + + SyntaxKind[SyntaxKind["QualifiedName"] = 121] = "QualifiedName"; + + SyntaxKind[SyntaxKind["ObjectType"] = 122] = "ObjectType"; + SyntaxKind[SyntaxKind["FunctionType"] = 123] = "FunctionType"; + SyntaxKind[SyntaxKind["ArrayType"] = 124] = "ArrayType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 125] = "ConstructorType"; + SyntaxKind[SyntaxKind["GenericType"] = 126] = "GenericType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 127] = "TypeQuery"; + + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 128] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 129] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 130] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 131] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 132] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 133] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 134] = "ExportAssignment"; + + SyntaxKind[SyntaxKind["MemberFunctionDeclaration"] = 135] = "MemberFunctionDeclaration"; + SyntaxKind[SyntaxKind["MemberVariableDeclaration"] = 136] = "MemberVariableDeclaration"; + SyntaxKind[SyntaxKind["ConstructorDeclaration"] = 137] = "ConstructorDeclaration"; + SyntaxKind[SyntaxKind["IndexMemberDeclaration"] = 138] = "IndexMemberDeclaration"; + + SyntaxKind[SyntaxKind["GetAccessor"] = 139] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 140] = "SetAccessor"; + + SyntaxKind[SyntaxKind["PropertySignature"] = 141] = "PropertySignature"; + SyntaxKind[SyntaxKind["CallSignature"] = 142] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 143] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 144] = "IndexSignature"; + SyntaxKind[SyntaxKind["MethodSignature"] = 145] = "MethodSignature"; + + SyntaxKind[SyntaxKind["Block"] = 146] = "Block"; + SyntaxKind[SyntaxKind["IfStatement"] = 147] = "IfStatement"; + SyntaxKind[SyntaxKind["VariableStatement"] = 148] = "VariableStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 149] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 150] = "ReturnStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 151] = "SwitchStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 152] = "BreakStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 153] = "ContinueStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 154] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 155] = "ForInStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 156] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 157] = "ThrowStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 158] = "WhileStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 159] = "TryStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 160] = "LabeledStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 161] = "DoStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 162] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 163] = "WithStatement"; + + SyntaxKind[SyntaxKind["PlusExpression"] = 164] = "PlusExpression"; + SyntaxKind[SyntaxKind["NegateExpression"] = 165] = "NegateExpression"; + SyntaxKind[SyntaxKind["BitwiseNotExpression"] = 166] = "BitwiseNotExpression"; + SyntaxKind[SyntaxKind["LogicalNotExpression"] = 167] = "LogicalNotExpression"; + SyntaxKind[SyntaxKind["PreIncrementExpression"] = 168] = "PreIncrementExpression"; + SyntaxKind[SyntaxKind["PreDecrementExpression"] = 169] = "PreDecrementExpression"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 170] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 171] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 172] = "VoidExpression"; + SyntaxKind[SyntaxKind["CommaExpression"] = 173] = "CommaExpression"; + SyntaxKind[SyntaxKind["AssignmentExpression"] = 174] = "AssignmentExpression"; + SyntaxKind[SyntaxKind["AddAssignmentExpression"] = 175] = "AddAssignmentExpression"; + SyntaxKind[SyntaxKind["SubtractAssignmentExpression"] = 176] = "SubtractAssignmentExpression"; + SyntaxKind[SyntaxKind["MultiplyAssignmentExpression"] = 177] = "MultiplyAssignmentExpression"; + SyntaxKind[SyntaxKind["DivideAssignmentExpression"] = 178] = "DivideAssignmentExpression"; + SyntaxKind[SyntaxKind["ModuloAssignmentExpression"] = 179] = "ModuloAssignmentExpression"; + SyntaxKind[SyntaxKind["AndAssignmentExpression"] = 180] = "AndAssignmentExpression"; + SyntaxKind[SyntaxKind["ExclusiveOrAssignmentExpression"] = 181] = "ExclusiveOrAssignmentExpression"; + SyntaxKind[SyntaxKind["OrAssignmentExpression"] = 182] = "OrAssignmentExpression"; + SyntaxKind[SyntaxKind["LeftShiftAssignmentExpression"] = 183] = "LeftShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["SignedRightShiftAssignmentExpression"] = 184] = "SignedRightShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["UnsignedRightShiftAssignmentExpression"] = 185] = "UnsignedRightShiftAssignmentExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 186] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["LogicalOrExpression"] = 187] = "LogicalOrExpression"; + SyntaxKind[SyntaxKind["LogicalAndExpression"] = 188] = "LogicalAndExpression"; + SyntaxKind[SyntaxKind["BitwiseOrExpression"] = 189] = "BitwiseOrExpression"; + SyntaxKind[SyntaxKind["BitwiseExclusiveOrExpression"] = 190] = "BitwiseExclusiveOrExpression"; + SyntaxKind[SyntaxKind["BitwiseAndExpression"] = 191] = "BitwiseAndExpression"; + SyntaxKind[SyntaxKind["EqualsWithTypeConversionExpression"] = 192] = "EqualsWithTypeConversionExpression"; + SyntaxKind[SyntaxKind["NotEqualsWithTypeConversionExpression"] = 193] = "NotEqualsWithTypeConversionExpression"; + SyntaxKind[SyntaxKind["EqualsExpression"] = 194] = "EqualsExpression"; + SyntaxKind[SyntaxKind["NotEqualsExpression"] = 195] = "NotEqualsExpression"; + SyntaxKind[SyntaxKind["LessThanExpression"] = 196] = "LessThanExpression"; + SyntaxKind[SyntaxKind["GreaterThanExpression"] = 197] = "GreaterThanExpression"; + SyntaxKind[SyntaxKind["LessThanOrEqualExpression"] = 198] = "LessThanOrEqualExpression"; + SyntaxKind[SyntaxKind["GreaterThanOrEqualExpression"] = 199] = "GreaterThanOrEqualExpression"; + SyntaxKind[SyntaxKind["InstanceOfExpression"] = 200] = "InstanceOfExpression"; + SyntaxKind[SyntaxKind["InExpression"] = 201] = "InExpression"; + SyntaxKind[SyntaxKind["LeftShiftExpression"] = 202] = "LeftShiftExpression"; + SyntaxKind[SyntaxKind["SignedRightShiftExpression"] = 203] = "SignedRightShiftExpression"; + SyntaxKind[SyntaxKind["UnsignedRightShiftExpression"] = 204] = "UnsignedRightShiftExpression"; + SyntaxKind[SyntaxKind["MultiplyExpression"] = 205] = "MultiplyExpression"; + SyntaxKind[SyntaxKind["DivideExpression"] = 206] = "DivideExpression"; + SyntaxKind[SyntaxKind["ModuloExpression"] = 207] = "ModuloExpression"; + SyntaxKind[SyntaxKind["AddExpression"] = 208] = "AddExpression"; + SyntaxKind[SyntaxKind["SubtractExpression"] = 209] = "SubtractExpression"; + SyntaxKind[SyntaxKind["PostIncrementExpression"] = 210] = "PostIncrementExpression"; + SyntaxKind[SyntaxKind["PostDecrementExpression"] = 211] = "PostDecrementExpression"; + SyntaxKind[SyntaxKind["MemberAccessExpression"] = 212] = "MemberAccessExpression"; + SyntaxKind[SyntaxKind["InvocationExpression"] = 213] = "InvocationExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 214] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 215] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectCreationExpression"] = 216] = "ObjectCreationExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 217] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["ParenthesizedArrowFunctionExpression"] = 218] = "ParenthesizedArrowFunctionExpression"; + SyntaxKind[SyntaxKind["SimpleArrowFunctionExpression"] = 219] = "SimpleArrowFunctionExpression"; + SyntaxKind[SyntaxKind["CastExpression"] = 220] = "CastExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 221] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 222] = "FunctionExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 223] = "OmittedExpression"; + + SyntaxKind[SyntaxKind["VariableDeclaration"] = 224] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarator"] = 225] = "VariableDeclarator"; + + SyntaxKind[SyntaxKind["ArgumentList"] = 226] = "ArgumentList"; + SyntaxKind[SyntaxKind["ParameterList"] = 227] = "ParameterList"; + SyntaxKind[SyntaxKind["TypeArgumentList"] = 228] = "TypeArgumentList"; + SyntaxKind[SyntaxKind["TypeParameterList"] = 229] = "TypeParameterList"; + + SyntaxKind[SyntaxKind["ExtendsHeritageClause"] = 230] = "ExtendsHeritageClause"; + SyntaxKind[SyntaxKind["ImplementsHeritageClause"] = 231] = "ImplementsHeritageClause"; + SyntaxKind[SyntaxKind["EqualsValueClause"] = 232] = "EqualsValueClause"; + SyntaxKind[SyntaxKind["CaseSwitchClause"] = 233] = "CaseSwitchClause"; + SyntaxKind[SyntaxKind["DefaultSwitchClause"] = 234] = "DefaultSwitchClause"; + SyntaxKind[SyntaxKind["ElseClause"] = 235] = "ElseClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 236] = "CatchClause"; + SyntaxKind[SyntaxKind["FinallyClause"] = 237] = "FinallyClause"; + + SyntaxKind[SyntaxKind["TypeParameter"] = 238] = "TypeParameter"; + SyntaxKind[SyntaxKind["Constraint"] = 239] = "Constraint"; + + SyntaxKind[SyntaxKind["SimplePropertyAssignment"] = 240] = "SimplePropertyAssignment"; + + SyntaxKind[SyntaxKind["FunctionPropertyAssignment"] = 241] = "FunctionPropertyAssignment"; + + SyntaxKind[SyntaxKind["Parameter"] = 242] = "Parameter"; + SyntaxKind[SyntaxKind["EnumElement"] = 243] = "EnumElement"; + SyntaxKind[SyntaxKind["TypeAnnotation"] = 244] = "TypeAnnotation"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 245] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ModuleNameModuleReference"] = 246] = "ModuleNameModuleReference"; + SyntaxKind[SyntaxKind["Last"] = SyntaxKind.ModuleNameModuleReference] = "Last"; + + SyntaxKind[SyntaxKind["FirstStandardKeyword"] = SyntaxKind.BreakKeyword] = "FirstStandardKeyword"; + SyntaxKind[SyntaxKind["LastStandardKeyword"] = SyntaxKind.WithKeyword] = "LastStandardKeyword"; + + SyntaxKind[SyntaxKind["FirstFutureReservedKeyword"] = SyntaxKind.ClassKeyword] = "FirstFutureReservedKeyword"; + SyntaxKind[SyntaxKind["LastFutureReservedKeyword"] = SyntaxKind.SuperKeyword] = "LastFutureReservedKeyword"; + + SyntaxKind[SyntaxKind["FirstFutureReservedStrictKeyword"] = SyntaxKind.ImplementsKeyword] = "FirstFutureReservedStrictKeyword"; + SyntaxKind[SyntaxKind["LastFutureReservedStrictKeyword"] = SyntaxKind.YieldKeyword] = "LastFutureReservedStrictKeyword"; + + SyntaxKind[SyntaxKind["FirstTypeScriptKeyword"] = SyntaxKind.AnyKeyword] = "FirstTypeScriptKeyword"; + SyntaxKind[SyntaxKind["LastTypeScriptKeyword"] = SyntaxKind.StringKeyword] = "LastTypeScriptKeyword"; + + SyntaxKind[SyntaxKind["FirstKeyword"] = SyntaxKind.FirstStandardKeyword] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = SyntaxKind.LastTypeScriptKeyword] = "LastKeyword"; + + SyntaxKind[SyntaxKind["FirstToken"] = SyntaxKind.ErrorToken] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = SyntaxKind.SlashEqualsToken] = "LastToken"; + + SyntaxKind[SyntaxKind["FirstPunctuation"] = SyntaxKind.OpenBraceToken] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = SyntaxKind.SlashEqualsToken] = "LastPunctuation"; + + SyntaxKind[SyntaxKind["FirstFixedWidth"] = SyntaxKind.FirstKeyword] = "FirstFixedWidth"; + SyntaxKind[SyntaxKind["LastFixedWidth"] = SyntaxKind.LastPunctuation] = "LastFixedWidth"; + + SyntaxKind[SyntaxKind["FirstTrivia"] = SyntaxKind.WhitespaceTrivia] = "FirstTrivia"; + SyntaxKind[SyntaxKind["LastTrivia"] = SyntaxKind.SkippedTokenTrivia] = "LastTrivia"; + })(TypeScript.SyntaxKind || (TypeScript.SyntaxKind = {})); + var SyntaxKind = TypeScript.SyntaxKind; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxFacts) { + var textToKeywordKind = { + "any": 60 /* AnyKeyword */, + "boolean": 61 /* BooleanKeyword */, + "break": 15 /* BreakKeyword */, + "case": 16 /* CaseKeyword */, + "catch": 17 /* CatchKeyword */, + "class": 44 /* ClassKeyword */, + "continue": 18 /* ContinueKeyword */, + "const": 45 /* ConstKeyword */, + "constructor": 62 /* ConstructorKeyword */, + "debugger": 19 /* DebuggerKeyword */, + "declare": 63 /* DeclareKeyword */, + "default": 20 /* DefaultKeyword */, + "delete": 21 /* DeleteKeyword */, + "do": 22 /* DoKeyword */, + "else": 23 /* ElseKeyword */, + "enum": 46 /* EnumKeyword */, + "export": 47 /* ExportKeyword */, + "extends": 48 /* ExtendsKeyword */, + "false": 24 /* FalseKeyword */, + "finally": 25 /* FinallyKeyword */, + "for": 26 /* ForKeyword */, + "function": 27 /* FunctionKeyword */, + "get": 64 /* GetKeyword */, + "if": 28 /* IfKeyword */, + "implements": 51 /* ImplementsKeyword */, + "import": 49 /* ImportKeyword */, + "in": 29 /* InKeyword */, + "instanceof": 30 /* InstanceOfKeyword */, + "interface": 52 /* InterfaceKeyword */, + "let": 53 /* LetKeyword */, + "module": 65 /* ModuleKeyword */, + "new": 31 /* NewKeyword */, + "null": 32 /* NullKeyword */, + "number": 67 /* NumberKeyword */, + "package": 54 /* PackageKeyword */, + "private": 55 /* PrivateKeyword */, + "protected": 56 /* ProtectedKeyword */, + "public": 57 /* PublicKeyword */, + "require": 66 /* RequireKeyword */, + "return": 33 /* ReturnKeyword */, + "set": 68 /* SetKeyword */, + "static": 58 /* StaticKeyword */, + "string": 69 /* StringKeyword */, + "super": 50 /* SuperKeyword */, + "switch": 34 /* SwitchKeyword */, + "this": 35 /* ThisKeyword */, + "throw": 36 /* ThrowKeyword */, + "true": 37 /* TrueKeyword */, + "try": 38 /* TryKeyword */, + "typeof": 39 /* TypeOfKeyword */, + "var": 40 /* VarKeyword */, + "void": 41 /* VoidKeyword */, + "while": 42 /* WhileKeyword */, + "with": 43 /* WithKeyword */, + "yield": 59 /* YieldKeyword */, + "{": 70 /* OpenBraceToken */, + "}": 71 /* CloseBraceToken */, + "(": 72 /* OpenParenToken */, + ")": 73 /* CloseParenToken */, + "[": 74 /* OpenBracketToken */, + "]": 75 /* CloseBracketToken */, + ".": 76 /* DotToken */, + "...": 77 /* DotDotDotToken */, + ";": 78 /* SemicolonToken */, + ",": 79 /* CommaToken */, + "<": 80 /* LessThanToken */, + ">": 81 /* GreaterThanToken */, + "<=": 82 /* LessThanEqualsToken */, + ">=": 83 /* GreaterThanEqualsToken */, + "==": 84 /* EqualsEqualsToken */, + "=>": 85 /* EqualsGreaterThanToken */, + "!=": 86 /* ExclamationEqualsToken */, + "===": 87 /* EqualsEqualsEqualsToken */, + "!==": 88 /* ExclamationEqualsEqualsToken */, + "+": 89 /* PlusToken */, + "-": 90 /* MinusToken */, + "*": 91 /* AsteriskToken */, + "%": 92 /* PercentToken */, + "++": 93 /* PlusPlusToken */, + "--": 94 /* MinusMinusToken */, + "<<": 95 /* LessThanLessThanToken */, + ">>": 96 /* GreaterThanGreaterThanToken */, + ">>>": 97 /* GreaterThanGreaterThanGreaterThanToken */, + "&": 98 /* AmpersandToken */, + "|": 99 /* BarToken */, + "^": 100 /* CaretToken */, + "!": 101 /* ExclamationToken */, + "~": 102 /* TildeToken */, + "&&": 103 /* AmpersandAmpersandToken */, + "||": 104 /* BarBarToken */, + "?": 105 /* QuestionToken */, + ":": 106 /* ColonToken */, + "=": 107 /* EqualsToken */, + "+=": 108 /* PlusEqualsToken */, + "-=": 109 /* MinusEqualsToken */, + "*=": 110 /* AsteriskEqualsToken */, + "%=": 111 /* PercentEqualsToken */, + "<<=": 112 /* LessThanLessThanEqualsToken */, + ">>=": 113 /* GreaterThanGreaterThanEqualsToken */, + ">>>=": 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */, + "&=": 115 /* AmpersandEqualsToken */, + "|=": 116 /* BarEqualsToken */, + "^=": 117 /* CaretEqualsToken */, + "/": 118 /* SlashToken */, + "/=": 119 /* SlashEqualsToken */ + }; + + var kindToText = new Array(); + + for (var name in textToKeywordKind) { + if (textToKeywordKind.hasOwnProperty(name)) { + kindToText[textToKeywordKind[name]] = name; + } + } + + kindToText[62 /* ConstructorKeyword */] = "constructor"; + + function getTokenKind(text) { + if (textToKeywordKind.hasOwnProperty(text)) { + return textToKeywordKind[text]; + } + + return 0 /* None */; + } + SyntaxFacts.getTokenKind = getTokenKind; + + function getText(kind) { + var result = kindToText[kind]; + return result !== undefined ? result : null; + } + SyntaxFacts.getText = getText; + + function isTokenKind(kind) { + return kind >= 9 /* FirstToken */ && kind <= 119 /* LastToken */; + } + SyntaxFacts.isTokenKind = isTokenKind; + + function isAnyKeyword(kind) { + return kind >= 15 /* FirstKeyword */ && kind <= 69 /* LastKeyword */; + } + SyntaxFacts.isAnyKeyword = isAnyKeyword; + + function isStandardKeyword(kind) { + return kind >= 15 /* FirstStandardKeyword */ && kind <= 43 /* LastStandardKeyword */; + } + SyntaxFacts.isStandardKeyword = isStandardKeyword; + + function isFutureReservedKeyword(kind) { + return kind >= 44 /* FirstFutureReservedKeyword */ && kind <= 50 /* LastFutureReservedKeyword */; + } + SyntaxFacts.isFutureReservedKeyword = isFutureReservedKeyword; + + function isFutureReservedStrictKeyword(kind) { + return kind >= 51 /* FirstFutureReservedStrictKeyword */ && kind <= 59 /* LastFutureReservedStrictKeyword */; + } + SyntaxFacts.isFutureReservedStrictKeyword = isFutureReservedStrictKeyword; + + function isAnyPunctuation(kind) { + return kind >= 70 /* FirstPunctuation */ && kind <= 119 /* LastPunctuation */; + } + SyntaxFacts.isAnyPunctuation = isAnyPunctuation; + + function isPrefixUnaryExpressionOperatorToken(tokenKind) { + return getPrefixUnaryExpressionFromOperatorToken(tokenKind) !== 0 /* None */; + } + SyntaxFacts.isPrefixUnaryExpressionOperatorToken = isPrefixUnaryExpressionOperatorToken; + + function isBinaryExpressionOperatorToken(tokenKind) { + return getBinaryExpressionFromOperatorToken(tokenKind) !== 0 /* None */; + } + SyntaxFacts.isBinaryExpressionOperatorToken = isBinaryExpressionOperatorToken; + + function getPrefixUnaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 89 /* PlusToken */: + return 164 /* PlusExpression */; + case 90 /* MinusToken */: + return 165 /* NegateExpression */; + case 102 /* TildeToken */: + return 166 /* BitwiseNotExpression */; + case 101 /* ExclamationToken */: + return 167 /* LogicalNotExpression */; + case 93 /* PlusPlusToken */: + return 168 /* PreIncrementExpression */; + case 94 /* MinusMinusToken */: + return 169 /* PreDecrementExpression */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getPrefixUnaryExpressionFromOperatorToken = getPrefixUnaryExpressionFromOperatorToken; + + function getPostfixUnaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 93 /* PlusPlusToken */: + return 210 /* PostIncrementExpression */; + case 94 /* MinusMinusToken */: + return 211 /* PostDecrementExpression */; + default: + return 0 /* None */; + } + } + SyntaxFacts.getPostfixUnaryExpressionFromOperatorToken = getPostfixUnaryExpressionFromOperatorToken; + + function getBinaryExpressionFromOperatorToken(tokenKind) { + switch (tokenKind) { + case 91 /* AsteriskToken */: + return 205 /* MultiplyExpression */; + + case 118 /* SlashToken */: + return 206 /* DivideExpression */; + + case 92 /* PercentToken */: + return 207 /* ModuloExpression */; + + case 89 /* PlusToken */: + return 208 /* AddExpression */; + + case 90 /* MinusToken */: + return 209 /* SubtractExpression */; + + case 95 /* LessThanLessThanToken */: + return 202 /* LeftShiftExpression */; + + case 96 /* GreaterThanGreaterThanToken */: + return 203 /* SignedRightShiftExpression */; + + case 97 /* GreaterThanGreaterThanGreaterThanToken */: + return 204 /* UnsignedRightShiftExpression */; + + case 80 /* LessThanToken */: + return 196 /* LessThanExpression */; + + case 81 /* GreaterThanToken */: + return 197 /* GreaterThanExpression */; + + case 82 /* LessThanEqualsToken */: + return 198 /* LessThanOrEqualExpression */; + + case 83 /* GreaterThanEqualsToken */: + return 199 /* GreaterThanOrEqualExpression */; + + case 30 /* InstanceOfKeyword */: + return 200 /* InstanceOfExpression */; + + case 29 /* InKeyword */: + return 201 /* InExpression */; + + case 84 /* EqualsEqualsToken */: + return 192 /* EqualsWithTypeConversionExpression */; + + case 86 /* ExclamationEqualsToken */: + return 193 /* NotEqualsWithTypeConversionExpression */; + + case 87 /* EqualsEqualsEqualsToken */: + return 194 /* EqualsExpression */; + + case 88 /* ExclamationEqualsEqualsToken */: + return 195 /* NotEqualsExpression */; + + case 98 /* AmpersandToken */: + return 191 /* BitwiseAndExpression */; + + case 100 /* CaretToken */: + return 190 /* BitwiseExclusiveOrExpression */; + + case 99 /* BarToken */: + return 189 /* BitwiseOrExpression */; + + case 103 /* AmpersandAmpersandToken */: + return 188 /* LogicalAndExpression */; + + case 104 /* BarBarToken */: + return 187 /* LogicalOrExpression */; + + case 116 /* BarEqualsToken */: + return 182 /* OrAssignmentExpression */; + + case 115 /* AmpersandEqualsToken */: + return 180 /* AndAssignmentExpression */; + + case 117 /* CaretEqualsToken */: + return 181 /* ExclusiveOrAssignmentExpression */; + + case 112 /* LessThanLessThanEqualsToken */: + return 183 /* LeftShiftAssignmentExpression */; + + case 113 /* GreaterThanGreaterThanEqualsToken */: + return 184 /* SignedRightShiftAssignmentExpression */; + + case 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + return 185 /* UnsignedRightShiftAssignmentExpression */; + + case 108 /* PlusEqualsToken */: + return 175 /* AddAssignmentExpression */; + + case 109 /* MinusEqualsToken */: + return 176 /* SubtractAssignmentExpression */; + + case 110 /* AsteriskEqualsToken */: + return 177 /* MultiplyAssignmentExpression */; + + case 119 /* SlashEqualsToken */: + return 178 /* DivideAssignmentExpression */; + + case 111 /* PercentEqualsToken */: + return 179 /* ModuloAssignmentExpression */; + + case 107 /* EqualsToken */: + return 174 /* AssignmentExpression */; + + case 79 /* CommaToken */: + return 173 /* CommaExpression */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getBinaryExpressionFromOperatorToken = getBinaryExpressionFromOperatorToken; + + function getOperatorTokenFromBinaryExpression(tokenKind) { + switch (tokenKind) { + case 205 /* MultiplyExpression */: + return 91 /* AsteriskToken */; + + case 206 /* DivideExpression */: + return 118 /* SlashToken */; + + case 207 /* ModuloExpression */: + return 92 /* PercentToken */; + + case 208 /* AddExpression */: + return 89 /* PlusToken */; + + case 209 /* SubtractExpression */: + return 90 /* MinusToken */; + + case 202 /* LeftShiftExpression */: + return 95 /* LessThanLessThanToken */; + + case 203 /* SignedRightShiftExpression */: + return 96 /* GreaterThanGreaterThanToken */; + + case 204 /* UnsignedRightShiftExpression */: + return 97 /* GreaterThanGreaterThanGreaterThanToken */; + + case 196 /* LessThanExpression */: + return 80 /* LessThanToken */; + + case 197 /* GreaterThanExpression */: + return 81 /* GreaterThanToken */; + + case 198 /* LessThanOrEqualExpression */: + return 82 /* LessThanEqualsToken */; + + case 199 /* GreaterThanOrEqualExpression */: + return 83 /* GreaterThanEqualsToken */; + + case 200 /* InstanceOfExpression */: + return 30 /* InstanceOfKeyword */; + + case 201 /* InExpression */: + return 29 /* InKeyword */; + + case 192 /* EqualsWithTypeConversionExpression */: + return 84 /* EqualsEqualsToken */; + + case 193 /* NotEqualsWithTypeConversionExpression */: + return 86 /* ExclamationEqualsToken */; + + case 194 /* EqualsExpression */: + return 87 /* EqualsEqualsEqualsToken */; + + case 195 /* NotEqualsExpression */: + return 88 /* ExclamationEqualsEqualsToken */; + + case 191 /* BitwiseAndExpression */: + return 98 /* AmpersandToken */; + + case 190 /* BitwiseExclusiveOrExpression */: + return 100 /* CaretToken */; + + case 189 /* BitwiseOrExpression */: + return 99 /* BarToken */; + + case 188 /* LogicalAndExpression */: + return 103 /* AmpersandAmpersandToken */; + + case 187 /* LogicalOrExpression */: + return 104 /* BarBarToken */; + + case 182 /* OrAssignmentExpression */: + return 116 /* BarEqualsToken */; + + case 180 /* AndAssignmentExpression */: + return 115 /* AmpersandEqualsToken */; + + case 181 /* ExclusiveOrAssignmentExpression */: + return 117 /* CaretEqualsToken */; + + case 183 /* LeftShiftAssignmentExpression */: + return 112 /* LessThanLessThanEqualsToken */; + + case 184 /* SignedRightShiftAssignmentExpression */: + return 113 /* GreaterThanGreaterThanEqualsToken */; + + case 185 /* UnsignedRightShiftAssignmentExpression */: + return 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + + case 175 /* AddAssignmentExpression */: + return 108 /* PlusEqualsToken */; + + case 176 /* SubtractAssignmentExpression */: + return 109 /* MinusEqualsToken */; + + case 177 /* MultiplyAssignmentExpression */: + return 110 /* AsteriskEqualsToken */; + + case 178 /* DivideAssignmentExpression */: + return 119 /* SlashEqualsToken */; + + case 179 /* ModuloAssignmentExpression */: + return 111 /* PercentEqualsToken */; + + case 174 /* AssignmentExpression */: + return 107 /* EqualsToken */; + + case 173 /* CommaExpression */: + return 79 /* CommaToken */; + + default: + return 0 /* None */; + } + } + SyntaxFacts.getOperatorTokenFromBinaryExpression = getOperatorTokenFromBinaryExpression; + + function isAnyDivideToken(kind) { + switch (kind) { + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + return true; + default: + return false; + } + } + SyntaxFacts.isAnyDivideToken = isAnyDivideToken; + + function isAnyDivideOrRegularExpressionToken(kind) { + switch (kind) { + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + case 12 /* RegularExpressionLiteral */: + return true; + default: + return false; + } + } + SyntaxFacts.isAnyDivideOrRegularExpressionToken = isAnyDivideOrRegularExpressionToken; + })(TypeScript.SyntaxFacts || (TypeScript.SyntaxFacts = {})); + var SyntaxFacts = TypeScript.SyntaxFacts; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var isKeywordStartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + var isIdentifierStartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + var isIdentifierPartCharacter = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + var isNumericLiteralStart = TypeScript.ArrayUtilities.createArray(127 /* maxAsciiCharacter */, false); + + for (var character = 0; character < 127 /* maxAsciiCharacter */; character++) { + if (character >= 97 /* a */ && character <= 122 /* z */) { + isIdentifierStartCharacter[character] = true; + isIdentifierPartCharacter[character] = true; + } else if ((character >= 65 /* A */ && character <= 90 /* Z */) || character === 95 /* _ */ || character === 36 /* $ */) { + isIdentifierStartCharacter[character] = true; + isIdentifierPartCharacter[character] = true; + } else if (character >= 48 /* _0 */ && character <= 57 /* _9 */) { + isIdentifierPartCharacter[character] = true; + isNumericLiteralStart[character] = true; + } + } + + isNumericLiteralStart[46 /* dot */] = true; + + for (var keywordKind = 15 /* FirstKeyword */; keywordKind <= 69 /* LastKeyword */; keywordKind++) { + var keyword = TypeScript.SyntaxFacts.getText(keywordKind); + isKeywordStartCharacter[keyword.charCodeAt(0)] = true; + } + + var Scanner = (function () { + function Scanner(fileName, text, languageVersion, window) { + if (typeof window === "undefined") { window = TypeScript.ArrayUtilities.createArray(2048, 0); } + this.slidingWindow = new TypeScript.SlidingWindow(this, window, 0, text.length()); + this.fileName = fileName; + this.text = text; + this._languageVersion = languageVersion; + } + Scanner.prototype.languageVersion = function () { + return this._languageVersion; + }; + + Scanner.prototype.fetchMoreItems = function (argument, sourceIndex, window, destinationIndex, spaceAvailable) { + var charactersRemaining = this.text.length() - sourceIndex; + var amountToRead = TypeScript.MathPrototype.min(charactersRemaining, spaceAvailable); + this.text.copyTo(sourceIndex, window, destinationIndex, amountToRead); + return amountToRead; + }; + + Scanner.prototype.currentCharCode = function () { + return this.slidingWindow.currentItem(null); + }; + + Scanner.prototype.absoluteIndex = function () { + return this.slidingWindow.absoluteIndex(); + }; + + Scanner.prototype.setAbsoluteIndex = function (index) { + this.slidingWindow.setAbsoluteIndex(index); + }; + + Scanner.prototype.scan = function (diagnostics, allowRegularExpression) { + var diagnosticsLength = diagnostics.length; + var fullStart = this.slidingWindow.absoluteIndex(); + var leadingTriviaInfo = this.scanTriviaInfo(diagnostics, false); + + var start = this.slidingWindow.absoluteIndex(); + var kindAndFlags = this.scanSyntaxToken(diagnostics, allowRegularExpression); + var end = this.slidingWindow.absoluteIndex(); + + var trailingTriviaInfo = this.scanTriviaInfo(diagnostics, true); + var fullEnd = this.slidingWindow.absoluteIndex(); + + var isVariableWidthKeyword = (kindAndFlags & -2147483648 /* IsVariableWidthKeyword */) !== 0; + var kind = kindAndFlags & ~-2147483648 /* IsVariableWidthKeyword */; + + var token = this.createToken(fullStart, leadingTriviaInfo, start, kind, end, fullEnd, trailingTriviaInfo, isVariableWidthKeyword); + + return diagnosticsLength !== diagnostics.length ? TypeScript.Syntax.realizeToken(token) : token; + }; + + Scanner.prototype.createToken = function (fullStart, leadingTriviaInfo, start, kind, end, fullEnd, trailingTriviaInfo, isVariableWidthKeyword) { + if (!isVariableWidthKeyword && kind >= 15 /* FirstFixedWidth */) { + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.FixedWidthTokenWithNoTrivia(kind); + } else { + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo); + } else { + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + return new TypeScript.Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo); + } + } else { + var width = end - start; + + var fullText = this.text.substr(fullStart, fullEnd - fullStart, false); + + if (leadingTriviaInfo === 0) { + if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.VariableWidthTokenWithNoTrivia(fullText, kind); + } else { + return new TypeScript.Syntax.VariableWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo); + } + } else if (trailingTriviaInfo === 0) { + return new TypeScript.Syntax.VariableWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo); + } else { + return new TypeScript.Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo); + } + } + }; + + Scanner.scanTrivia = function (text, start, length, isTrailing) { + var scanner = new Scanner(null, text.subText(new TypeScript.TextSpan(start, length)), 1 /* EcmaScript5 */, Scanner.triviaWindow); + return scanner.scanTrivia(text, start, isTrailing); + }; + + Scanner.prototype.scanTrivia = function (underlyingText, underlyingTextStart, isTrailing) { + var trivia = new Array(); + + while (true) { + if (!this.slidingWindow.isAtEndOfSource()) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + trivia.push(this.scanWhitespaceTrivia(underlyingText, underlyingTextStart)); + continue; + + case 47 /* slash */: + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 47 /* slash */) { + trivia.push(this.scanSingleLineCommentTrivia(underlyingText, underlyingTextStart)); + continue; + } + + if (ch2 === 42 /* asterisk */) { + trivia.push(this.scanMultiLineCommentTrivia(underlyingText, underlyingTextStart)); + continue; + } + + throw TypeScript.Errors.invalidOperation(); + + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + trivia.push(this.scanLineTerminatorSequenceTrivia(ch)); + + if (!isTrailing) { + continue; + } + + break; + + default: + throw TypeScript.Errors.invalidOperation(); + } + } + + return TypeScript.Syntax.triviaList(trivia); + } + }; + + Scanner.prototype.scanTriviaInfo = function (diagnostics, isTrailing) { + var width = 0; + var hasCommentOrNewLine = 0; + + while (true) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + this.slidingWindow.moveToNextItem(); + width++; + continue; + + case 47 /* slash */: + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 47 /* slash */) { + hasCommentOrNewLine |= 2 /* TriviaCommentMask */; + width += this.scanSingleLineCommentTriviaLength(); + continue; + } + + if (ch2 === 42 /* asterisk */) { + hasCommentOrNewLine |= 2 /* TriviaCommentMask */; + width += this.scanMultiLineCommentTriviaLength(diagnostics); + continue; + } + + break; + + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + hasCommentOrNewLine |= 1 /* TriviaNewLineMask */; + width += this.scanLineTerminatorSequenceLength(ch); + + if (!isTrailing) { + continue; + } + + break; + } + + return (width << 2 /* TriviaFullWidthShift */) | hasCommentOrNewLine; + } + }; + + Scanner.prototype.isNewLineCharacter = function (ch) { + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + return true; + default: + return false; + } + }; + + Scanner.prototype.scanWhitespaceTrivia = function (underlyingText, underlyingTextStart) { + var absoluteStartIndex = this.absoluteIndex(); + + var width = 0; + while (true) { + var ch = this.currentCharCode(); + + switch (ch) { + case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 12288 /* ideographicSpace */: + + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 65279 /* byteOrderMark */: + this.slidingWindow.moveToNextItem(); + width++; + continue; + } + + break; + } + + return TypeScript.Syntax.deferredTrivia(4 /* WhitespaceTrivia */, underlyingText, underlyingTextStart + absoluteStartIndex, width); + }; + + Scanner.prototype.scanSingleLineCommentTrivia = function (underlyingText, underlyingTextStart) { + var absoluteStartIndex = this.slidingWindow.absoluteIndex(); + var width = this.scanSingleLineCommentTriviaLength(); + + return TypeScript.Syntax.deferredTrivia(7 /* SingleLineCommentTrivia */, underlyingText, underlyingTextStart + absoluteStartIndex, width); + }; + + Scanner.prototype.scanSingleLineCommentTriviaLength = function () { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + var width = 2; + while (true) { + if (this.slidingWindow.isAtEndOfSource() || this.isNewLineCharacter(this.currentCharCode())) { + return width; + } + + this.slidingWindow.moveToNextItem(); + width++; + } + }; + + Scanner.prototype.scanMultiLineCommentTrivia = function (underlyingText, underlyingTextStart) { + var absoluteStartIndex = this.absoluteIndex(); + var width = this.scanMultiLineCommentTriviaLength(null); + + return TypeScript.Syntax.deferredTrivia(6 /* MultiLineCommentTrivia */, underlyingText, underlyingTextStart + absoluteStartIndex, width); + }; + + Scanner.prototype.scanMultiLineCommentTriviaLength = function (diagnostics) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + var width = 2; + while (true) { + if (this.slidingWindow.isAtEndOfSource()) { + if (diagnostics !== null) { + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), this.slidingWindow.absoluteIndex(), 0, TypeScript.DiagnosticCode.AsteriskSlash_expected, null)); + } + + return width; + } + + var ch = this.currentCharCode(); + if (ch === 42 /* asterisk */ && this.slidingWindow.peekItemN(1) === 47 /* slash */) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + width += 2; + return width; + } + + this.slidingWindow.moveToNextItem(); + width++; + } + }; + + Scanner.prototype.scanLineTerminatorSequenceTrivia = function (ch) { + var absoluteStartIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + var width = this.scanLineTerminatorSequenceLength(ch); + + var text = this.substring(absoluteStartIndex, absoluteStartIndex + width, false); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(absoluteStartIndex); + + return TypeScript.Syntax.trivia(5 /* NewLineTrivia */, text); + }; + + Scanner.prototype.scanLineTerminatorSequenceLength = function (ch) { + this.slidingWindow.moveToNextItem(); + + if (ch === 13 /* carriageReturn */ && this.currentCharCode() === 10 /* lineFeed */) { + this.slidingWindow.moveToNextItem(); + return 2; + } else { + return 1; + } + }; + + Scanner.prototype.scanSyntaxToken = function (diagnostics, allowRegularExpression) { + if (this.slidingWindow.isAtEndOfSource()) { + return 10 /* EndOfFileToken */; + } + + var character = this.currentCharCode(); + + switch (character) { + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + return this.scanStringLiteral(diagnostics); + + case 47 /* slash */: + return this.scanSlashToken(allowRegularExpression); + + case 46 /* dot */: + return this.scanDotToken(diagnostics); + + case 45 /* minus */: + return this.scanMinusToken(); + + case 33 /* exclamation */: + return this.scanExclamationToken(); + + case 61 /* equals */: + return this.scanEqualsToken(); + + case 124 /* bar */: + return this.scanBarToken(); + + case 42 /* asterisk */: + return this.scanAsteriskToken(); + + case 43 /* plus */: + return this.scanPlusToken(); + + case 37 /* percent */: + return this.scanPercentToken(); + + case 38 /* ampersand */: + return this.scanAmpersandToken(); + + case 94 /* caret */: + return this.scanCaretToken(); + + case 60 /* lessThan */: + return this.scanLessThanToken(); + + case 62 /* greaterThan */: + return this.advanceAndSetTokenKind(81 /* GreaterThanToken */); + + case 44 /* comma */: + return this.advanceAndSetTokenKind(79 /* CommaToken */); + + case 58 /* colon */: + return this.advanceAndSetTokenKind(106 /* ColonToken */); + + case 59 /* semicolon */: + return this.advanceAndSetTokenKind(78 /* SemicolonToken */); + + case 126 /* tilde */: + return this.advanceAndSetTokenKind(102 /* TildeToken */); + + case 40 /* openParen */: + return this.advanceAndSetTokenKind(72 /* OpenParenToken */); + + case 41 /* closeParen */: + return this.advanceAndSetTokenKind(73 /* CloseParenToken */); + + case 123 /* openBrace */: + return this.advanceAndSetTokenKind(70 /* OpenBraceToken */); + + case 125 /* closeBrace */: + return this.advanceAndSetTokenKind(71 /* CloseBraceToken */); + + case 91 /* openBracket */: + return this.advanceAndSetTokenKind(74 /* OpenBracketToken */); + + case 93 /* closeBracket */: + return this.advanceAndSetTokenKind(75 /* CloseBracketToken */); + + case 63 /* question */: + return this.advanceAndSetTokenKind(105 /* QuestionToken */); + } + + if (isNumericLiteralStart[character]) { + return this.scanNumericLiteral(diagnostics); + } + + if (isIdentifierStartCharacter[character]) { + var result = this.tryFastScanIdentifierOrKeyword(character); + if (result !== 0 /* None */) { + return result; + } + } + + if (this.isIdentifierStart(this.peekCharOrUnicodeEscape())) { + return this.slowScanIdentifierOrKeyword(diagnostics); + } + + return this.scanDefaultCharacter(character, diagnostics); + }; + + Scanner.prototype.isIdentifierStart = function (interpretedChar) { + if (isIdentifierStartCharacter[interpretedChar]) { + return true; + } + + return interpretedChar > 127 /* maxAsciiCharacter */ && TypeScript.Unicode.isIdentifierStart(interpretedChar, this._languageVersion); + }; + + Scanner.prototype.isIdentifierPart = function (interpretedChar) { + if (isIdentifierPartCharacter[interpretedChar]) { + return true; + } + + return interpretedChar > 127 /* maxAsciiCharacter */ && TypeScript.Unicode.isIdentifierPart(interpretedChar, this._languageVersion); + }; + + Scanner.prototype.tryFastScanIdentifierOrKeyword = function (firstCharacter) { + var slidingWindow = this.slidingWindow; + var window = slidingWindow.window; + + var startIndex = slidingWindow.currentRelativeItemIndex; + var endIndex = slidingWindow.windowCount; + var currentIndex = startIndex; + var character = 0; + + while (currentIndex < endIndex) { + character = window[currentIndex]; + if (!isIdentifierPartCharacter[character]) { + break; + } + + currentIndex++; + } + + if (currentIndex === endIndex) { + return 0 /* None */; + } else if (character === 92 /* backslash */ || character > 127 /* maxAsciiCharacter */) { + return 0 /* None */; + } else { + var kind; + var identifierLength = currentIndex - startIndex; + if (isKeywordStartCharacter[firstCharacter]) { + kind = TypeScript.ScannerUtilities.identifierKind(window, startIndex, identifierLength); + } else { + kind = 11 /* IdentifierName */; + } + + slidingWindow.setAbsoluteIndex(slidingWindow.absoluteIndex() + identifierLength); + + return kind; + } + }; + + Scanner.prototype.slowScanIdentifierOrKeyword = function (diagnostics) { + var startIndex = this.slidingWindow.absoluteIndex(); + var sawUnicodeEscape = false; + + do { + var unicodeEscape = this.scanCharOrUnicodeEscape(diagnostics); + sawUnicodeEscape = sawUnicodeEscape || unicodeEscape; + } while(this.isIdentifierPart(this.peekCharOrUnicodeEscape())); + + var length = this.slidingWindow.absoluteIndex() - startIndex; + var text = this.text.substr(startIndex, length, false); + var valueText = TypeScript.Syntax.massageEscapes(text); + + var keywordKind = TypeScript.SyntaxFacts.getTokenKind(valueText); + if (keywordKind >= 15 /* FirstKeyword */ && keywordKind <= 69 /* LastKeyword */) { + if (sawUnicodeEscape) { + return keywordKind | -2147483648 /* IsVariableWidthKeyword */; + } else { + return keywordKind; + } + } + + return 11 /* IdentifierName */; + }; + + Scanner.prototype.scanNumericLiteral = function (diagnostics) { + if (this.isHexNumericLiteral()) { + this.scanHexNumericLiteral(); + } else if (this.isOctalNumericLiteral()) { + this.scanOctalNumericLiteral(diagnostics); + } else { + this.scanDecimalNumericLiteral(); + } + + return 13 /* NumericLiteral */; + }; + + Scanner.prototype.isOctalNumericLiteral = function () { + return this.currentCharCode() === 48 /* _0 */ && TypeScript.CharacterInfo.isOctalDigit(this.slidingWindow.peekItemN(1)); + }; + + Scanner.prototype.scanOctalNumericLiteral = function (diagnostics) { + var position = this.absoluteIndex(); + + while (TypeScript.CharacterInfo.isOctalDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + + if (this.languageVersion() >= 1 /* EcmaScript5 */) { + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), position, this.absoluteIndex() - position, TypeScript.DiagnosticCode.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher, null)); + } + }; + + Scanner.prototype.scanDecimalDigits = function () { + while (TypeScript.CharacterInfo.isDecimalDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + }; + + Scanner.prototype.scanDecimalNumericLiteral = function () { + this.scanDecimalDigits(); + + if (this.currentCharCode() === 46 /* dot */) { + this.slidingWindow.moveToNextItem(); + } + + this.scanDecimalDigits(); + + var ch = this.currentCharCode(); + if (ch === 101 /* e */ || ch === 69 /* E */) { + var nextChar1 = this.slidingWindow.peekItemN(1); + + if (TypeScript.CharacterInfo.isDecimalDigit(nextChar1)) { + this.slidingWindow.moveToNextItem(); + this.scanDecimalDigits(); + } else if (nextChar1 === 45 /* minus */ || nextChar1 === 43 /* plus */) { + var nextChar2 = this.slidingWindow.peekItemN(2); + if (TypeScript.CharacterInfo.isDecimalDigit(nextChar2)) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + this.scanDecimalDigits(); + } + } + } + }; + + Scanner.prototype.scanHexNumericLiteral = function () { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + + while (TypeScript.CharacterInfo.isHexDigit(this.currentCharCode())) { + this.slidingWindow.moveToNextItem(); + } + }; + + Scanner.prototype.isHexNumericLiteral = function () { + if (this.currentCharCode() === 48 /* _0 */) { + var ch = this.slidingWindow.peekItemN(1); + + if (ch === 120 /* x */ || ch === 88 /* X */) { + ch = this.slidingWindow.peekItemN(2); + + return TypeScript.CharacterInfo.isHexDigit(ch); + } + } + + return false; + }; + + Scanner.prototype.advanceAndSetTokenKind = function (kind) { + this.slidingWindow.moveToNextItem(); + return kind; + }; + + Scanner.prototype.scanLessThanToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 82 /* LessThanEqualsToken */; + } else if (this.currentCharCode() === 60 /* lessThan */) { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 112 /* LessThanLessThanEqualsToken */; + } else { + return 95 /* LessThanLessThanToken */; + } + } else { + return 80 /* LessThanToken */; + } + }; + + Scanner.prototype.scanBarToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 116 /* BarEqualsToken */; + } else if (this.currentCharCode() === 124 /* bar */) { + this.slidingWindow.moveToNextItem(); + return 104 /* BarBarToken */; + } else { + return 99 /* BarToken */; + } + }; + + Scanner.prototype.scanCaretToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 117 /* CaretEqualsToken */; + } else { + return 100 /* CaretToken */; + } + }; + + Scanner.prototype.scanAmpersandToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 115 /* AmpersandEqualsToken */; + } else if (this.currentCharCode() === 38 /* ampersand */) { + this.slidingWindow.moveToNextItem(); + return 103 /* AmpersandAmpersandToken */; + } else { + return 98 /* AmpersandToken */; + } + }; + + Scanner.prototype.scanPercentToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 111 /* PercentEqualsToken */; + } else { + return 92 /* PercentToken */; + } + }; + + Scanner.prototype.scanMinusToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 109 /* MinusEqualsToken */; + } else if (character === 45 /* minus */) { + this.slidingWindow.moveToNextItem(); + return 94 /* MinusMinusToken */; + } else { + return 90 /* MinusToken */; + } + }; + + Scanner.prototype.scanPlusToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 108 /* PlusEqualsToken */; + } else if (character === 43 /* plus */) { + this.slidingWindow.moveToNextItem(); + return 93 /* PlusPlusToken */; + } else { + return 89 /* PlusToken */; + } + }; + + Scanner.prototype.scanAsteriskToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 110 /* AsteriskEqualsToken */; + } else { + return 91 /* AsteriskToken */; + } + }; + + Scanner.prototype.scanEqualsToken = function () { + this.slidingWindow.moveToNextItem(); + var character = this.currentCharCode(); + if (character === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + return 87 /* EqualsEqualsEqualsToken */; + } else { + return 84 /* EqualsEqualsToken */; + } + } else if (character === 62 /* greaterThan */) { + this.slidingWindow.moveToNextItem(); + return 85 /* EqualsGreaterThanToken */; + } else { + return 107 /* EqualsToken */; + } + }; + + Scanner.prototype.isDotPrefixedNumericLiteral = function () { + if (this.currentCharCode() === 46 /* dot */) { + var ch = this.slidingWindow.peekItemN(1); + return TypeScript.CharacterInfo.isDecimalDigit(ch); + } + + return false; + }; + + Scanner.prototype.scanDotToken = function (diagnostics) { + if (this.isDotPrefixedNumericLiteral()) { + return this.scanNumericLiteral(diagnostics); + } + + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 46 /* dot */ && this.slidingWindow.peekItemN(1) === 46 /* dot */) { + this.slidingWindow.moveToNextItem(); + this.slidingWindow.moveToNextItem(); + return 77 /* DotDotDotToken */; + } else { + return 76 /* DotToken */; + } + }; + + Scanner.prototype.scanSlashToken = function (allowRegularExpression) { + if (allowRegularExpression) { + var result = this.tryScanRegularExpressionToken(); + if (result !== 0 /* None */) { + return result; + } + } + + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + return 119 /* SlashEqualsToken */; + } else { + return 118 /* SlashToken */; + } + }; + + Scanner.prototype.tryScanRegularExpressionToken = function () { + var startIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + this.slidingWindow.moveToNextItem(); + + var inEscape = false; + var inCharacterClass = false; + while (true) { + var ch = this.currentCharCode(); + + if (this.isNewLineCharacter(ch) || this.slidingWindow.isAtEndOfSource()) { + this.slidingWindow.rewindToPinnedIndex(startIndex); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + return 0 /* None */; + } + + this.slidingWindow.moveToNextItem(); + if (inEscape) { + inEscape = false; + continue; + } + + switch (ch) { + case 92 /* backslash */: + inEscape = true; + continue; + + case 91 /* openBracket */: + inCharacterClass = true; + continue; + + case 93 /* closeBracket */: + inCharacterClass = false; + continue; + + case 47 /* slash */: + if (inCharacterClass) { + continue; + } + + break; + + default: + continue; + } + + break; + } + + while (isIdentifierPartCharacter[this.currentCharCode()]) { + this.slidingWindow.moveToNextItem(); + } + + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + return 12 /* RegularExpressionLiteral */; + }; + + Scanner.prototype.scanExclamationToken = function () { + this.slidingWindow.moveToNextItem(); + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + if (this.currentCharCode() === 61 /* equals */) { + this.slidingWindow.moveToNextItem(); + + return 88 /* ExclamationEqualsEqualsToken */; + } else { + return 86 /* ExclamationEqualsToken */; + } + } else { + return 101 /* ExclamationToken */; + } + }; + + Scanner.prototype.scanDefaultCharacter = function (character, diagnostics) { + var position = this.slidingWindow.absoluteIndex(); + this.slidingWindow.moveToNextItem(); + + var text = String.fromCharCode(character); + var messageText = this.getErrorMessageText(text); + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), position, 1, TypeScript.DiagnosticCode.Unexpected_character_0, [messageText])); + + return 9 /* ErrorToken */; + }; + + Scanner.prototype.getErrorMessageText = function (text) { + if (text === "\\") { + return '"\\"'; + } + + return JSON.stringify(text); + }; + + Scanner.prototype.skipEscapeSequence = function (diagnostics) { + var rewindPoint = this.slidingWindow.getAndPinAbsoluteIndex(); + + this.slidingWindow.moveToNextItem(); + + var ch = this.currentCharCode(); + this.slidingWindow.moveToNextItem(); + switch (ch) { + case 120 /* x */: + case 117 /* u */: + this.slidingWindow.rewindToPinnedIndex(rewindPoint); + var value = this.scanUnicodeOrHexEscape(diagnostics); + break; + + case 13 /* carriageReturn */: + if (this.currentCharCode() === 10 /* lineFeed */) { + this.slidingWindow.moveToNextItem(); + } + break; + + default: + break; + } + + this.slidingWindow.releaseAndUnpinAbsoluteIndex(rewindPoint); + }; + + Scanner.prototype.scanStringLiteral = function (diagnostics) { + var quoteCharacter = this.currentCharCode(); + + this.slidingWindow.moveToNextItem(); + + while (true) { + var ch = this.currentCharCode(); + if (ch === 92 /* backslash */) { + this.skipEscapeSequence(diagnostics); + } else if (ch === quoteCharacter) { + this.slidingWindow.moveToNextItem(); + break; + } else if (this.isNewLineCharacter(ch) || this.slidingWindow.isAtEndOfSource()) { + diagnostics.push(new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), TypeScript.MathPrototype.min(this.slidingWindow.absoluteIndex(), this.text.length()), 1, TypeScript.DiagnosticCode.Missing_close_quote_character, null)); + break; + } else { + this.slidingWindow.moveToNextItem(); + } + } + + return 14 /* StringLiteral */; + }; + + Scanner.prototype.isUnicodeEscape = function (character) { + if (character === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 117 /* u */) { + return true; + } + } + + return false; + }; + + Scanner.prototype.peekCharOrUnicodeEscape = function () { + var character = this.currentCharCode(); + if (this.isUnicodeEscape(character)) { + return this.peekUnicodeOrHexEscape(); + } else { + return character; + } + }; + + Scanner.prototype.peekUnicodeOrHexEscape = function () { + var startIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + var ch = this.scanUnicodeOrHexEscape(null); + + this.slidingWindow.rewindToPinnedIndex(startIndex); + this.slidingWindow.releaseAndUnpinAbsoluteIndex(startIndex); + + return ch; + }; + + Scanner.prototype.scanCharOrUnicodeEscape = function (errors) { + var ch = this.currentCharCode(); + if (ch === 92 /* backslash */) { + var ch2 = this.slidingWindow.peekItemN(1); + if (ch2 === 117 /* u */) { + this.scanUnicodeOrHexEscape(errors); + return true; + } + } + + this.slidingWindow.moveToNextItem(); + return false; + }; + + Scanner.prototype.scanUnicodeOrHexEscape = function (errors) { + var start = this.slidingWindow.absoluteIndex(); + var character = this.currentCharCode(); + + this.slidingWindow.moveToNextItem(); + + character = this.currentCharCode(); + + var intChar = 0; + this.slidingWindow.moveToNextItem(); + + var count = character === 117 /* u */ ? 4 : 2; + + for (var i = 0; i < count; i++) { + var ch2 = this.currentCharCode(); + if (!TypeScript.CharacterInfo.isHexDigit(ch2)) { + if (errors !== null) { + var end = this.slidingWindow.absoluteIndex(); + var info = this.createIllegalEscapeDiagnostic(start, end); + errors.push(info); + } + + break; + } + + intChar = (intChar << 4) + TypeScript.CharacterInfo.hexValue(ch2); + this.slidingWindow.moveToNextItem(); + } + + return intChar; + }; + + Scanner.prototype.substring = function (start, end, intern) { + var length = end - start; + var offset = start - this.slidingWindow.windowAbsoluteStartIndex; + + if (intern) { + return TypeScript.Collections.DefaultStringTable.addCharArray(this.slidingWindow.window, offset, length); + } else { + return TypeScript.StringUtilities.fromCharCodeArray(this.slidingWindow.window.slice(offset, offset + length)); + } + }; + + Scanner.prototype.createIllegalEscapeDiagnostic = function (start, end) { + return new TypeScript.Diagnostic(this.fileName, this.text.lineMap(), start, end - start, TypeScript.DiagnosticCode.Unrecognized_escape_sequence, null); + }; + + Scanner.isValidIdentifier = function (text, languageVersion) { + var scanner = new Scanner(null, text, languageVersion, Scanner.triviaWindow); + var errors = new Array(); + var token = scanner.scan(errors, false); + + return errors.length === 0 && TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token) && token.width() === text.length(); + }; + Scanner.triviaWindow = TypeScript.ArrayUtilities.createArray(2048, 0); + return Scanner; + })(); + TypeScript.Scanner = Scanner; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScannerUtilities = (function () { + function ScannerUtilities() { + } + ScannerUtilities.identifierKind = function (array, startIndex, length) { + switch (length) { + case 2: + switch (array[startIndex]) { + case 100 /* d */: + return (array[startIndex + 1] === 111 /* o */) ? 22 /* DoKeyword */ : 11 /* IdentifierName */; + case 105 /* i */: + switch (array[startIndex + 1]) { + case 102 /* f */: + return 28 /* IfKeyword */; + case 110 /* n */: + return 29 /* InKeyword */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 3: + switch (array[startIndex]) { + case 102 /* f */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 114 /* r */) ? 26 /* ForKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 119 /* w */) ? 31 /* NewKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 121 /* y */) ? 38 /* TryKeyword */ : 11 /* IdentifierName */; + case 118 /* v */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 114 /* r */) ? 40 /* VarKeyword */ : 11 /* IdentifierName */; + case 108 /* l */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 53 /* LetKeyword */ : 11 /* IdentifierName */; + case 97 /* a */: + return (array[startIndex + 1] === 110 /* n */ && array[startIndex + 2] === 121 /* y */) ? 60 /* AnyKeyword */ : 11 /* IdentifierName */; + case 103 /* g */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 64 /* GetKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */) ? 68 /* SetKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 4: + switch (array[startIndex]) { + case 99 /* c */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 101 /* e */) ? 16 /* CaseKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + switch (array[startIndex + 1]) { + case 108 /* l */: + return (array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 101 /* e */) ? 23 /* ElseKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 2] === 117 /* u */ && array[startIndex + 3] === 109 /* m */) ? 46 /* EnumKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 110 /* n */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 108 /* l */) ? 32 /* NullKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + switch (array[startIndex + 1]) { + case 104 /* h */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 115 /* s */) ? 35 /* ThisKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 2] === 117 /* u */ && array[startIndex + 3] === 101 /* e */) ? 37 /* TrueKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 118 /* v */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 100 /* d */) ? 41 /* VoidKeyword */ : 11 /* IdentifierName */; + case 119 /* w */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 104 /* h */) ? 43 /* WithKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 5: + switch (array[startIndex]) { + case 98 /* b */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 101 /* e */ && array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 107 /* k */) ? 15 /* BreakKeyword */ : 11 /* IdentifierName */; + case 99 /* c */: + switch (array[startIndex + 1]) { + case 97 /* a */: + return (array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 99 /* c */ && array[startIndex + 4] === 104 /* h */) ? 17 /* CatchKeyword */ : 11 /* IdentifierName */; + case 108 /* l */: + return (array[startIndex + 2] === 97 /* a */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 115 /* s */) ? 44 /* ClassKeyword */ : 11 /* IdentifierName */; + case 111 /* o */: + return (array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 116 /* t */) ? 45 /* ConstKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 102 /* f */: + return (array[startIndex + 1] === 97 /* a */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 101 /* e */) ? 24 /* FalseKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + return (array[startIndex + 1] === 104 /* h */ && array[startIndex + 2] === 114 /* r */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 119 /* w */) ? 36 /* ThrowKeyword */ : 11 /* IdentifierName */; + case 119 /* w */: + return (array[startIndex + 1] === 104 /* h */ && array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */) ? 42 /* WhileKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 114 /* r */) ? 50 /* SuperKeyword */ : 11 /* IdentifierName */; + case 121 /* y */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 101 /* e */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 100 /* d */) ? 59 /* YieldKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 6: + switch (array[startIndex]) { + case 100 /* d */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 108 /* l */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 101 /* e */) ? 21 /* DeleteKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 110 /* n */) ? 33 /* ReturnKeyword */ : 11 /* IdentifierName */; + case 115 /* s */: + switch (array[startIndex + 1]) { + case 119 /* w */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 99 /* c */ && array[startIndex + 5] === 104 /* h */) ? 34 /* SwitchKeyword */ : 11 /* IdentifierName */; + case 116 /* t */: + switch (array[startIndex + 2]) { + case 97 /* a */: + return (array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 99 /* c */) ? 58 /* StaticKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 3] === 105 /* i */ && array[startIndex + 4] === 110 /* n */ && array[startIndex + 5] === 103 /* g */) ? 69 /* StringKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 116 /* t */: + return (array[startIndex + 1] === 121 /* y */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 111 /* o */ && array[startIndex + 5] === 102 /* f */) ? 39 /* TypeOfKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + return (array[startIndex + 1] === 120 /* x */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 116 /* t */) ? 47 /* ExportKeyword */ : 11 /* IdentifierName */; + case 105 /* i */: + return (array[startIndex + 1] === 109 /* m */ && array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 111 /* o */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 116 /* t */) ? 49 /* ImportKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 98 /* b */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 99 /* c */) ? 57 /* PublicKeyword */ : 11 /* IdentifierName */; + case 109 /* m */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 100 /* d */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 108 /* l */ && array[startIndex + 5] === 101 /* e */) ? 65 /* ModuleKeyword */ : 11 /* IdentifierName */; + case 110 /* n */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 109 /* m */ && array[startIndex + 3] === 98 /* b */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 114 /* r */) ? 67 /* NumberKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 7: + switch (array[startIndex]) { + case 100 /* d */: + switch (array[startIndex + 1]) { + case 101 /* e */: + switch (array[startIndex + 2]) { + case 102 /* f */: + return (array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 117 /* u */ && array[startIndex + 5] === 108 /* l */ && array[startIndex + 6] === 116 /* t */) ? 20 /* DefaultKeyword */ : 11 /* IdentifierName */; + case 99 /* c */: + return (array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 101 /* e */) ? 63 /* DeclareKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 102 /* f */: + return (array[startIndex + 1] === 105 /* i */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 97 /* a */ && array[startIndex + 4] === 108 /* l */ && array[startIndex + 5] === 108 /* l */ && array[startIndex + 6] === 121 /* y */) ? 25 /* FinallyKeyword */ : 11 /* IdentifierName */; + case 101 /* e */: + return (array[startIndex + 1] === 120 /* x */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 110 /* n */ && array[startIndex + 5] === 100 /* d */ && array[startIndex + 6] === 115 /* s */) ? 48 /* ExtendsKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + switch (array[startIndex + 1]) { + case 97 /* a */: + return (array[startIndex + 2] === 99 /* c */ && array[startIndex + 3] === 107 /* k */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 103 /* g */ && array[startIndex + 6] === 101 /* e */) ? 54 /* PackageKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 2] === 105 /* i */ && array[startIndex + 3] === 118 /* v */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 116 /* t */ && array[startIndex + 6] === 101 /* e */) ? 55 /* PrivateKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 98 /* b */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 111 /* o */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 97 /* a */ && array[startIndex + 6] === 110 /* n */) ? 61 /* BooleanKeyword */ : 11 /* IdentifierName */; + case 114 /* r */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 113 /* q */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 101 /* e */) ? 66 /* RequireKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 8: + switch (array[startIndex]) { + case 99 /* c */: + return (array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 105 /* i */ && array[startIndex + 5] === 110 /* n */ && array[startIndex + 6] === 117 /* u */ && array[startIndex + 7] === 101 /* e */) ? 18 /* ContinueKeyword */ : 11 /* IdentifierName */; + case 100 /* d */: + return (array[startIndex + 1] === 101 /* e */ && array[startIndex + 2] === 98 /* b */ && array[startIndex + 3] === 117 /* u */ && array[startIndex + 4] === 103 /* g */ && array[startIndex + 5] === 103 /* g */ && array[startIndex + 6] === 101 /* e */ && array[startIndex + 7] === 114 /* r */) ? 19 /* DebuggerKeyword */ : 11 /* IdentifierName */; + case 102 /* f */: + return (array[startIndex + 1] === 117 /* u */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 99 /* c */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 105 /* i */ && array[startIndex + 6] === 111 /* o */ && array[startIndex + 7] === 110 /* n */) ? 27 /* FunctionKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 9: + switch (array[startIndex]) { + case 105 /* i */: + return (array[startIndex + 1] === 110 /* n */ && array[startIndex + 2] === 116 /* t */ && array[startIndex + 3] === 101 /* e */ && array[startIndex + 4] === 114 /* r */ && array[startIndex + 5] === 102 /* f */ && array[startIndex + 6] === 97 /* a */ && array[startIndex + 7] === 99 /* c */ && array[startIndex + 8] === 101 /* e */) ? 52 /* InterfaceKeyword */ : 11 /* IdentifierName */; + case 112 /* p */: + return (array[startIndex + 1] === 114 /* r */ && array[startIndex + 2] === 111 /* o */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 99 /* c */ && array[startIndex + 6] === 116 /* t */ && array[startIndex + 7] === 101 /* e */ && array[startIndex + 8] === 100 /* d */) ? 56 /* ProtectedKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + case 10: + switch (array[startIndex]) { + case 105 /* i */: + switch (array[startIndex + 1]) { + case 110 /* n */: + return (array[startIndex + 2] === 115 /* s */ && array[startIndex + 3] === 116 /* t */ && array[startIndex + 4] === 97 /* a */ && array[startIndex + 5] === 110 /* n */ && array[startIndex + 6] === 99 /* c */ && array[startIndex + 7] === 101 /* e */ && array[startIndex + 8] === 111 /* o */ && array[startIndex + 9] === 102 /* f */) ? 30 /* InstanceOfKeyword */ : 11 /* IdentifierName */; + case 109 /* m */: + return (array[startIndex + 2] === 112 /* p */ && array[startIndex + 3] === 108 /* l */ && array[startIndex + 4] === 101 /* e */ && array[startIndex + 5] === 109 /* m */ && array[startIndex + 6] === 101 /* e */ && array[startIndex + 7] === 110 /* n */ && array[startIndex + 8] === 116 /* t */ && array[startIndex + 9] === 115 /* s */) ? 51 /* ImplementsKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + + default: + return 11 /* IdentifierName */; + } + + case 11: + return (array[startIndex] === 99 /* c */ && array[startIndex + 1] === 111 /* o */ && array[startIndex + 2] === 110 /* n */ && array[startIndex + 3] === 115 /* s */ && array[startIndex + 4] === 116 /* t */ && array[startIndex + 5] === 114 /* r */ && array[startIndex + 6] === 117 /* u */ && array[startIndex + 7] === 99 /* c */ && array[startIndex + 8] === 116 /* t */ && array[startIndex + 9] === 111 /* o */ && array[startIndex + 10] === 114 /* r */) ? 62 /* ConstructorKeyword */ : 11 /* IdentifierName */; + default: + return 11 /* IdentifierName */; + } + }; + return ScannerUtilities; + })(); + TypeScript.ScannerUtilities = ScannerUtilities; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var EmptySeparatedSyntaxList = (function () { + function EmptySeparatedSyntaxList() { + } + EmptySeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + EmptySeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isList = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + + EmptySeparatedSyntaxList.prototype.toJSON = function (key) { + return []; + }; + + EmptySeparatedSyntaxList.prototype.childCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.separatorCount = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.toArray = function () { + return []; + }; + + EmptySeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + return []; + }; + + EmptySeparatedSyntaxList.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.separatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySeparatedSyntaxList.prototype.collectTextElements = function (elements) { + }; + + EmptySeparatedSyntaxList.prototype.firstToken = function () { + return null; + }; + + EmptySeparatedSyntaxList.prototype.lastToken = function () { + return null; + }; + + EmptySeparatedSyntaxList.prototype.fullWidth = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.fullText = function () { + return ""; + }; + + EmptySeparatedSyntaxList.prototype.width = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return false; + }; + + EmptySeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + throw TypeScript.Errors.invalidOperation(); + }; + + EmptySeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + }; + + EmptySeparatedSyntaxList.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySeparatedSyntaxList.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return 0; + }; + + EmptySeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return 0; + }; + return EmptySeparatedSyntaxList; + })(); + + Syntax.emptySeparatedList = new EmptySeparatedSyntaxList(); + + var SingletonSeparatedSyntaxList = (function () { + function SingletonSeparatedSyntaxList(item) { + this.item = item; + } + SingletonSeparatedSyntaxList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + SingletonSeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isList = function () { + return false; + }; + SingletonSeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + + SingletonSeparatedSyntaxList.prototype.childCount = function () { + return 1; + }; + SingletonSeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return 1; + }; + SingletonSeparatedSyntaxList.prototype.separatorCount = function () { + return 0; + }; + + SingletonSeparatedSyntaxList.prototype.toArray = function () { + return [this.item]; + }; + SingletonSeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + return [this.item]; + }; + + SingletonSeparatedSyntaxList.prototype.childAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSeparatedSyntaxList.prototype.separatorAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + SingletonSeparatedSyntaxList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSeparatedSyntaxList.prototype.firstToken = function () { + return this.item.firstToken(); + }; + + SingletonSeparatedSyntaxList.prototype.lastToken = function () { + return this.item.lastToken(); + }; + + SingletonSeparatedSyntaxList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.width = function () { + return this.item.width(); + }; + + SingletonSeparatedSyntaxList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSeparatedSyntaxList.prototype.leadingTrivia = function () { + return this.item.leadingTrivia(); + }; + + SingletonSeparatedSyntaxList.prototype.trailingTrivia = function () { + return this.item.trailingTrivia(); + }; + + SingletonSeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return this.item.leadingTriviaWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return this.item.trailingTriviaWidth(); + }; + + SingletonSeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + return this.item.isTypeScriptSpecific(); + }; + + SingletonSeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return this.item.isIncrementallyUnusable(); + }; + + SingletonSeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + return this.item.findTokenInternal(new TypeScript.PositionedSeparatedList(parent, this, fullStart), position, fullStart); + }; + + SingletonSeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + array.splice(index, 0, this.item); + }; + return SingletonSeparatedSyntaxList; + })(); + + var NormalSeparatedSyntaxList = (function () { + function NormalSeparatedSyntaxList(elements) { + this._data = 0; + this.elements = elements; + } + NormalSeparatedSyntaxList.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + NormalSeparatedSyntaxList.prototype.isToken = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isNode = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isList = function () { + return false; + }; + NormalSeparatedSyntaxList.prototype.isSeparatedList = function () { + return true; + }; + NormalSeparatedSyntaxList.prototype.toJSON = function (key) { + return this.elements; + }; + + NormalSeparatedSyntaxList.prototype.childCount = function () { + return this.elements.length; + }; + NormalSeparatedSyntaxList.prototype.nonSeparatorCount = function () { + return TypeScript.IntegerUtilities.integerDivide(this.elements.length + 1, 2); + }; + NormalSeparatedSyntaxList.prototype.separatorCount = function () { + return TypeScript.IntegerUtilities.integerDivide(this.elements.length, 2); + }; + + NormalSeparatedSyntaxList.prototype.toArray = function () { + return this.elements.slice(0); + }; + + NormalSeparatedSyntaxList.prototype.toNonSeparatorArray = function () { + var result = []; + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + result.push(this.nonSeparatorAt(i)); + } + + return result; + }; + + NormalSeparatedSyntaxList.prototype.childAt = function (index) { + if (index < 0 || index >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[index]; + }; + + NormalSeparatedSyntaxList.prototype.nonSeparatorAt = function (index) { + var value = index * 2; + if (value < 0 || value >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[value]; + }; + + NormalSeparatedSyntaxList.prototype.separatorAt = function (index) { + var value = index * 2 + 1; + if (value < 0 || value >= this.elements.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.elements[value]; + }; + + NormalSeparatedSyntaxList.prototype.firstToken = function () { + var token; + for (var i = 0, n = this.elements.length; i < n; i++) { + if (i % 2 === 0) { + var nodeOrToken = this.elements[i]; + token = nodeOrToken.firstToken(); + if (token !== null) { + return token; + } + } else { + token = this.elements[i]; + if (token.width() > 0) { + return token; + } + } + } + + return null; + }; + + NormalSeparatedSyntaxList.prototype.lastToken = function () { + var token; + for (var i = this.elements.length - 1; i >= 0; i--) { + if (i % 2 === 0) { + var nodeOrToken = this.elements[i]; + token = nodeOrToken.lastToken(); + if (token !== null) { + return token; + } + } else { + token = this.elements[i]; + if (token.width() > 0) { + return token; + } + } + } + + return null; + }; + + NormalSeparatedSyntaxList.prototype.fullText = function () { + var elements = []; + this.collectTextElements(elements); + return elements.join(""); + }; + + NormalSeparatedSyntaxList.prototype.isTypeScriptSpecific = function () { + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + if (this.nonSeparatorAt(i).isTypeScriptSpecific()) { + return true; + } + } + + return false; + }; + + NormalSeparatedSyntaxList.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + NormalSeparatedSyntaxList.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + NormalSeparatedSyntaxList.prototype.width = function () { + var fullWidth = this.fullWidth(); + return fullWidth - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.leadingTrivia = function () { + return this.firstToken().leadingTrivia(); + }; + + NormalSeparatedSyntaxList.prototype.trailingTrivia = function () { + return this.lastToken().trailingTrivia(); + }; + + NormalSeparatedSyntaxList.prototype.leadingTriviaWidth = function () { + return this.firstToken().leadingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.trailingTriviaWidth = function () { + return this.lastToken().trailingTriviaWidth(); + }; + + NormalSeparatedSyntaxList.prototype.computeData = function () { + var fullWidth = 0; + var isIncrementallyUnusable = false; + + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + + var childWidth = element.fullWidth(); + fullWidth += childWidth; + + isIncrementallyUnusable = isIncrementallyUnusable || element.isIncrementallyUnusable(); + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + NormalSeparatedSyntaxList.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data = this.computeData(); + } + + return this._data; + }; + + NormalSeparatedSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedSeparatedList(parent, this, fullStart); + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + + var childWidth = element.fullWidth(); + if (position < childWidth) { + return element.findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + NormalSeparatedSyntaxList.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.elements.length; i < n; i++) { + var element = this.elements[i]; + element.collectTextElements(elements); + } + }; + + NormalSeparatedSyntaxList.prototype.insertChildrenInto = function (array, index) { + if (index === 0) { + array.unshift.apply(array, this.elements); + } else { + array.splice.apply(array, [index, 0].concat(this.elements)); + } + }; + return NormalSeparatedSyntaxList; + })(); + + function separatedList(nodes) { + return separatedListAndValidate(nodes, false); + } + Syntax.separatedList = separatedList; + + function separatedListAndValidate(nodes, validate) { + if (nodes === undefined || nodes === null || nodes.length === 0) { + return Syntax.emptySeparatedList; + } + + if (validate) { + for (var i = 0; i < nodes.length; i++) { + var item = nodes[i]; + + if (i % 2 === 1) { + } + } + } + + if (nodes.length === 1) { + return new SingletonSeparatedSyntaxList(nodes[0]); + } + + return new NormalSeparatedSyntaxList(nodes); + } + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SlidingWindow = (function () { + function SlidingWindow(source, window, defaultValue, sourceLength) { + if (typeof sourceLength === "undefined") { sourceLength = -1; } + this.source = source; + this.window = window; + this.defaultValue = defaultValue; + this.sourceLength = sourceLength; + this.windowCount = 0; + this.windowAbsoluteStartIndex = 0; + this.currentRelativeItemIndex = 0; + this._pinCount = 0; + this.firstPinnedAbsoluteIndex = -1; + } + SlidingWindow.prototype.windowAbsoluteEndIndex = function () { + return this.windowAbsoluteStartIndex + this.windowCount; + }; + + SlidingWindow.prototype.addMoreItemsToWindow = function (argument) { + if (this.sourceLength >= 0 && this.absoluteIndex() >= this.sourceLength) { + return false; + } + + if (this.windowCount >= this.window.length) { + this.tryShiftOrGrowWindow(); + } + + var spaceAvailable = this.window.length - this.windowCount; + var amountFetched = this.source.fetchMoreItems(argument, this.windowAbsoluteEndIndex(), this.window, this.windowCount, spaceAvailable); + + this.windowCount += amountFetched; + return amountFetched > 0; + }; + + SlidingWindow.prototype.tryShiftOrGrowWindow = function () { + var currentIndexIsPastWindowHalfwayPoint = this.currentRelativeItemIndex > (this.window.length >>> 1); + + var isAllowedToShift = this.firstPinnedAbsoluteIndex === -1 || this.firstPinnedAbsoluteIndex > this.windowAbsoluteStartIndex; + + if (currentIndexIsPastWindowHalfwayPoint && isAllowedToShift) { + var shiftStartIndex = this.firstPinnedAbsoluteIndex === -1 ? this.currentRelativeItemIndex : this.firstPinnedAbsoluteIndex - this.windowAbsoluteStartIndex; + + var shiftCount = this.windowCount - shiftStartIndex; + + if (shiftCount > 0) { + TypeScript.ArrayUtilities.copy(this.window, shiftStartIndex, this.window, 0, shiftCount); + } + + this.windowAbsoluteStartIndex += shiftStartIndex; + + this.windowCount -= shiftStartIndex; + + this.currentRelativeItemIndex -= shiftStartIndex; + } else { + TypeScript.ArrayUtilities.grow(this.window, this.window.length * 2, this.defaultValue); + } + }; + + SlidingWindow.prototype.absoluteIndex = function () { + return this.windowAbsoluteStartIndex + this.currentRelativeItemIndex; + }; + + SlidingWindow.prototype.isAtEndOfSource = function () { + return this.absoluteIndex() >= this.sourceLength; + }; + + SlidingWindow.prototype.getAndPinAbsoluteIndex = function () { + var absoluteIndex = this.absoluteIndex(); + var pinCount = this._pinCount++; + if (pinCount === 0) { + this.firstPinnedAbsoluteIndex = absoluteIndex; + } + + return absoluteIndex; + }; + + SlidingWindow.prototype.releaseAndUnpinAbsoluteIndex = function (absoluteIndex) { + this._pinCount--; + if (this._pinCount === 0) { + this.firstPinnedAbsoluteIndex = -1; + } + }; + + SlidingWindow.prototype.rewindToPinnedIndex = function (absoluteIndex) { + var relativeIndex = absoluteIndex - this.windowAbsoluteStartIndex; + + this.currentRelativeItemIndex = relativeIndex; + }; + + SlidingWindow.prototype.currentItem = function (argument) { + if (this.currentRelativeItemIndex >= this.windowCount) { + if (!this.addMoreItemsToWindow(argument)) { + return this.defaultValue; + } + } + + return this.window[this.currentRelativeItemIndex]; + }; + + SlidingWindow.prototype.peekItemN = function (n) { + while (this.currentRelativeItemIndex + n >= this.windowCount) { + if (!this.addMoreItemsToWindow(null)) { + return this.defaultValue; + } + } + + return this.window[this.currentRelativeItemIndex + n]; + }; + + SlidingWindow.prototype.moveToNextItem = function () { + this.currentRelativeItemIndex++; + }; + + SlidingWindow.prototype.disgardAllItemsFromCurrentIndexOnwards = function () { + this.windowCount = this.currentRelativeItemIndex; + }; + + SlidingWindow.prototype.setAbsoluteIndex = function (absoluteIndex) { + if (this.absoluteIndex() === absoluteIndex) { + return; + } + + if (this._pinCount > 0) { + } + + if (absoluteIndex >= this.windowAbsoluteStartIndex && absoluteIndex < this.windowAbsoluteEndIndex()) { + this.currentRelativeItemIndex = (absoluteIndex - this.windowAbsoluteStartIndex); + } else { + this.windowAbsoluteStartIndex = absoluteIndex; + + this.windowCount = 0; + + this.currentRelativeItemIndex = 0; + } + }; + + SlidingWindow.prototype.pinCount = function () { + return this._pinCount; + }; + return SlidingWindow; + })(); + TypeScript.SlidingWindow = SlidingWindow; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + function emptySourceUnit() { + return Syntax.normalModeFactory.sourceUnit(Syntax.emptyList, Syntax.token(10 /* EndOfFileToken */, { text: "" })); + } + Syntax.emptySourceUnit = emptySourceUnit; + + function getStandaloneExpression(positionedToken) { + var token = positionedToken.token(); + if (positionedToken !== null && positionedToken.kind() === 11 /* IdentifierName */) { + var parentPositionedNode = positionedToken.containingNode(); + var parentNode = parentPositionedNode.node(); + + if (parentNode.kind() === 121 /* QualifiedName */ && parentNode.right === token) { + return parentPositionedNode; + } else if (parentNode.kind() === 212 /* MemberAccessExpression */ && parentNode.name === token) { + return parentPositionedNode; + } + } + + return positionedToken; + } + Syntax.getStandaloneExpression = getStandaloneExpression; + + function isInModuleOrTypeContext(positionedToken) { + if (positionedToken !== null) { + var positionedNodeOrToken = Syntax.getStandaloneExpression(positionedToken); + var parent = positionedNodeOrToken.containingNode(); + + if (parent !== null) { + switch (parent.kind()) { + case 246 /* ModuleNameModuleReference */: + return true; + case 121 /* QualifiedName */: + return true; + default: + return isInTypeOnlyContext(positionedToken); + } + } + } + + return false; + } + Syntax.isInModuleOrTypeContext = isInModuleOrTypeContext; + + function isInTypeOnlyContext(positionedToken) { + var positionedNodeOrToken = Syntax.getStandaloneExpression(positionedToken); + var positionedParent = positionedNodeOrToken.containingNode(); + + var parent = positionedParent.node(); + var nodeOrToken = positionedNodeOrToken.nodeOrToken(); + + if (parent !== null) { + switch (parent.kind()) { + case 124 /* ArrayType */: + return parent.type === nodeOrToken; + case 220 /* CastExpression */: + return parent.type === nodeOrToken; + case 244 /* TypeAnnotation */: + case 230 /* ExtendsHeritageClause */: + case 231 /* ImplementsHeritageClause */: + case 228 /* TypeArgumentList */: + return true; + } + } + + return false; + } + Syntax.isInTypeOnlyContext = isInTypeOnlyContext; + + function childOffset(parent, child) { + var offset = 0; + for (var i = 0, n = parent.childCount(); i < n; i++) { + var current = parent.childAt(i); + if (current === child) { + return offset; + } + + if (current !== null) { + offset += current.fullWidth(); + } + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.childOffset = childOffset; + + function childOffsetAt(parent, index) { + var offset = 0; + for (var i = 0; i < index; i++) { + var current = parent.childAt(i); + if (current !== null) { + offset += current.fullWidth(); + } + } + + return offset; + } + Syntax.childOffsetAt = childOffsetAt; + + function childIndex(parent, child) { + for (var i = 0, n = parent.childCount(); i < n; i++) { + var current = parent.childAt(i); + if (current === child) { + return i; + } + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.childIndex = childIndex; + + function nodeStructuralEquals(node1, node2) { + if (node1 === null) { + return node2 === null; + } + + return node1.structuralEquals(node2); + } + Syntax.nodeStructuralEquals = nodeStructuralEquals; + + function nodeOrTokenStructuralEquals(node1, node2) { + if (node1 === node2) { + return true; + } + + if (node1 === null || node2 === null) { + return false; + } + + if (node1.isToken()) { + return node2.isToken() ? tokenStructuralEquals(node1, node2) : false; + } + + return node2.isNode() ? nodeStructuralEquals(node1, node2) : false; + } + Syntax.nodeOrTokenStructuralEquals = nodeOrTokenStructuralEquals; + + function tokenStructuralEquals(token1, token2) { + if (token1 === token2) { + return true; + } + + if (token1 === null || token2 === null) { + return false; + } + + return token1.kind() === token2.kind() && token1.width() === token2.width() && token1.fullWidth() === token2.fullWidth() && token1.text() === token2.text() && Syntax.triviaListStructuralEquals(token1.leadingTrivia(), token2.leadingTrivia()) && Syntax.triviaListStructuralEquals(token1.trailingTrivia(), token2.trailingTrivia()); + } + Syntax.tokenStructuralEquals = tokenStructuralEquals; + + function triviaListStructuralEquals(triviaList1, triviaList2) { + if (triviaList1.count() !== triviaList2.count()) { + return false; + } + + for (var i = 0, n = triviaList1.count(); i < n; i++) { + if (!Syntax.triviaStructuralEquals(triviaList1.syntaxTriviaAt(i), triviaList2.syntaxTriviaAt(i))) { + return false; + } + } + + return true; + } + Syntax.triviaListStructuralEquals = triviaListStructuralEquals; + + function triviaStructuralEquals(trivia1, trivia2) { + return trivia1.kind() === trivia2.kind() && trivia1.fullWidth() === trivia2.fullWidth() && trivia1.fullText() === trivia2.fullText(); + } + Syntax.triviaStructuralEquals = triviaStructuralEquals; + + function listStructuralEquals(list1, list2) { + if (list1.childCount() !== list2.childCount()) { + return false; + } + + for (var i = 0, n = list1.childCount(); i < n; i++) { + var child1 = list1.childAt(i); + var child2 = list2.childAt(i); + + if (!Syntax.nodeOrTokenStructuralEquals(child1, child2)) { + return false; + } + } + + return true; + } + Syntax.listStructuralEquals = listStructuralEquals; + + function separatedListStructuralEquals(list1, list2) { + if (list1.childCount() !== list2.childCount()) { + return false; + } + + for (var i = 0, n = list1.childCount(); i < n; i++) { + var element1 = list1.childAt(i); + var element2 = list2.childAt(i); + if (!Syntax.nodeOrTokenStructuralEquals(element1, element2)) { + return false; + } + } + + return true; + } + Syntax.separatedListStructuralEquals = separatedListStructuralEquals; + + function elementStructuralEquals(element1, element2) { + if (element1 === element2) { + return true; + } + + if (element1 === null || element2 === null) { + return false; + } + + if (element2.kind() !== element2.kind()) { + return false; + } + + if (element1.isToken()) { + return tokenStructuralEquals(element1, element2); + } else if (element1.isNode()) { + return nodeStructuralEquals(element1, element2); + } else if (element1.isList()) { + return listStructuralEquals(element1, element2); + } else if (element1.isSeparatedList()) { + return separatedListStructuralEquals(element1, element2); + } + + throw TypeScript.Errors.invalidOperation(); + } + Syntax.elementStructuralEquals = elementStructuralEquals; + + function identifierName(text, info) { + if (typeof info === "undefined") { info = null; } + return Syntax.identifier(text); + } + Syntax.identifierName = identifierName; + + function trueExpression() { + return Syntax.token(37 /* TrueKeyword */); + } + Syntax.trueExpression = trueExpression; + + function falseExpression() { + return Syntax.token(24 /* FalseKeyword */); + } + Syntax.falseExpression = falseExpression; + + function numericLiteralExpression(text) { + return Syntax.token(13 /* NumericLiteral */, { text: text }); + } + Syntax.numericLiteralExpression = numericLiteralExpression; + + function stringLiteralExpression(text) { + return Syntax.token(14 /* StringLiteral */, { text: text }); + } + Syntax.stringLiteralExpression = stringLiteralExpression; + + function isSuperInvocationExpression(node) { + return node.kind() === 213 /* InvocationExpression */ && node.expression.kind() === 50 /* SuperKeyword */; + } + Syntax.isSuperInvocationExpression = isSuperInvocationExpression; + + function isSuperInvocationExpressionStatement(node) { + return node.kind() === 149 /* ExpressionStatement */ && isSuperInvocationExpression(node.expression); + } + Syntax.isSuperInvocationExpressionStatement = isSuperInvocationExpressionStatement; + + function isSuperMemberAccessExpression(node) { + return node.kind() === 212 /* MemberAccessExpression */ && node.expression.kind() === 50 /* SuperKeyword */; + } + Syntax.isSuperMemberAccessExpression = isSuperMemberAccessExpression; + + function isSuperMemberAccessInvocationExpression(node) { + return node.kind() === 213 /* InvocationExpression */ && isSuperMemberAccessExpression(node.expression); + } + Syntax.isSuperMemberAccessInvocationExpression = isSuperMemberAccessInvocationExpression; + + function assignmentExpression(left, token, right) { + return Syntax.normalModeFactory.binaryExpression(174 /* AssignmentExpression */, left, token, right); + } + Syntax.assignmentExpression = assignmentExpression; + + function nodeHasSkippedOrMissingTokens(node) { + for (var i = 0; i < node.childCount(); i++) { + var child = node.childAt(i); + if (child !== null && child.isToken()) { + var token = child; + + if (token.hasSkippedToken() || (token.width() === 0 && token.kind() !== 10 /* EndOfFileToken */)) { + return true; + } + } + } + return false; + } + Syntax.nodeHasSkippedOrMissingTokens = nodeHasSkippedOrMissingTokens; + + function isUnterminatedStringLiteral(token) { + if (token && token.kind() === 14 /* StringLiteral */) { + var text = token.text(); + return text.length < 2 || text.charCodeAt(text.length - 1) !== text.charCodeAt(0); + } + + return false; + } + Syntax.isUnterminatedStringLiteral = isUnterminatedStringLiteral; + + function isUnterminatedMultilineCommentTrivia(trivia) { + if (trivia && trivia.kind() === 6 /* MultiLineCommentTrivia */) { + var text = trivia.fullText(); + return text.length < 4 || text.substring(text.length - 2) !== "*/"; + } + return false; + } + Syntax.isUnterminatedMultilineCommentTrivia = isUnterminatedMultilineCommentTrivia; + + function isEntirelyInsideCommentTrivia(trivia, fullStart, position) { + if (trivia && trivia.isComment() && position > fullStart) { + var end = fullStart + trivia.fullWidth(); + if (position < end) { + return true; + } else if (position === end) { + return trivia.kind() === 7 /* SingleLineCommentTrivia */ || isUnterminatedMultilineCommentTrivia(trivia); + } + } + + return false; + } + Syntax.isEntirelyInsideCommentTrivia = isEntirelyInsideCommentTrivia; + + function isEntirelyInsideComment(sourceUnit, position) { + var positionedToken = sourceUnit.findToken(position); + var fullStart = positionedToken.fullStart(); + var triviaList = null; + var lastTriviaBeforeToken = null; + + if (positionedToken.kind() === 10 /* EndOfFileToken */) { + if (positionedToken.token().hasLeadingTrivia()) { + triviaList = positionedToken.token().leadingTrivia(); + } else { + positionedToken = positionedToken.previousToken(); + if (positionedToken) { + if (positionedToken && positionedToken.token().hasTrailingTrivia()) { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + } + } + } else { + if (position <= (fullStart + positionedToken.token().leadingTriviaWidth())) { + triviaList = positionedToken.token().leadingTrivia(); + } else if (position >= (fullStart + positionedToken.token().width())) { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + } + + if (triviaList) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + if (position <= fullStart) { + break; + } else if (position <= fullStart + trivia.fullWidth() && trivia.isComment()) { + lastTriviaBeforeToken = trivia; + break; + } + + fullStart += trivia.fullWidth(); + } + } + + return lastTriviaBeforeToken && isEntirelyInsideCommentTrivia(lastTriviaBeforeToken, fullStart, position); + } + Syntax.isEntirelyInsideComment = isEntirelyInsideComment; + + function isEntirelyInStringOrRegularExpressionLiteral(sourceUnit, position) { + var positionedToken = sourceUnit.findToken(position); + + if (positionedToken) { + if (positionedToken.kind() === 10 /* EndOfFileToken */) { + positionedToken = positionedToken.previousToken(); + return positionedToken && positionedToken.token().trailingTriviaWidth() === 0 && isUnterminatedStringLiteral(positionedToken.token()); + } else if (position > positionedToken.start()) { + return (position < positionedToken.end() && (positionedToken.kind() === 14 /* StringLiteral */ || positionedToken.kind() === 12 /* RegularExpressionLiteral */)) || (position <= positionedToken.end() && isUnterminatedStringLiteral(positionedToken.token())); + } + } + + return false; + } + Syntax.isEntirelyInStringOrRegularExpressionLiteral = isEntirelyInStringOrRegularExpressionLiteral; + + function findSkippedTokenInTriviaList(positionedToken, position, lookInLeadingTriviaList) { + var triviaList = null; + var fullStart; + + if (lookInLeadingTriviaList) { + triviaList = positionedToken.token().leadingTrivia(); + fullStart = positionedToken.fullStart(); + } else { + triviaList = positionedToken.token().trailingTrivia(); + fullStart = positionedToken.end(); + } + + if (triviaList && triviaList.hasSkippedToken()) { + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + var triviaWidth = trivia.fullWidth(); + + if (trivia.isSkippedToken() && position >= fullStart && position <= fullStart + triviaWidth) { + return new TypeScript.PositionedSkippedToken(positionedToken, trivia.skippedToken(), fullStart); + } + + fullStart += triviaWidth; + } + } + + return null; + } + + function findSkippedTokenOnLeftInTriviaList(positionedToken, position, lookInLeadingTriviaList) { + var triviaList = null; + var fullEnd; + + if (lookInLeadingTriviaList) { + triviaList = positionedToken.token().leadingTrivia(); + fullEnd = positionedToken.fullStart() + triviaList.fullWidth(); + } else { + triviaList = positionedToken.token().trailingTrivia(); + fullEnd = positionedToken.fullEnd(); + } + + if (triviaList && triviaList.hasSkippedToken()) { + for (var i = triviaList.count() - 1; i >= 0; i--) { + var trivia = triviaList.syntaxTriviaAt(i); + var triviaWidth = trivia.fullWidth(); + + if (trivia.isSkippedToken() && position >= fullEnd) { + return new TypeScript.PositionedSkippedToken(positionedToken, trivia.skippedToken(), fullEnd - triviaWidth); + } + + fullEnd -= triviaWidth; + } + } + + return null; + } + + function findSkippedTokenInLeadingTriviaList(positionedToken, position) { + return findSkippedTokenInTriviaList(positionedToken, position, true); + } + Syntax.findSkippedTokenInLeadingTriviaList = findSkippedTokenInLeadingTriviaList; + + function findSkippedTokenInTrailingTriviaList(positionedToken, position) { + return findSkippedTokenInTriviaList(positionedToken, position, false); + } + Syntax.findSkippedTokenInTrailingTriviaList = findSkippedTokenInTrailingTriviaList; + + function findSkippedTokenInPositionedToken(positionedToken, position) { + var positionInLeadingTriviaList = (position < positionedToken.start()); + return findSkippedTokenInTriviaList(positionedToken, position, positionInLeadingTriviaList); + } + Syntax.findSkippedTokenInPositionedToken = findSkippedTokenInPositionedToken; + + function findSkippedTokenOnLeft(positionedToken, position) { + var positionInLeadingTriviaList = (position < positionedToken.start()); + return findSkippedTokenOnLeftInTriviaList(positionedToken, position, positionInLeadingTriviaList); + } + Syntax.findSkippedTokenOnLeft = findSkippedTokenOnLeft; + + function getAncestorOfKind(positionedToken, kind) { + while (positionedToken && positionedToken.parent()) { + if (positionedToken.parent().kind() === kind) { + return positionedToken.parent(); + } + + positionedToken = positionedToken.parent(); + } + + return null; + } + Syntax.getAncestorOfKind = getAncestorOfKind; + + function hasAncestorOfKind(positionedToken, kind) { + return Syntax.getAncestorOfKind(positionedToken, kind) !== null; + } + Syntax.hasAncestorOfKind = hasAncestorOfKind; + + function isIntegerLiteral(expression) { + if (expression) { + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + expression = expression.operand; + return expression.isToken() && TypeScript.IntegerUtilities.isInteger(expression.text()); + + case 13 /* NumericLiteral */: + var text = expression.text(); + return TypeScript.IntegerUtilities.isInteger(text) || TypeScript.IntegerUtilities.isHexInteger(text); + } + } + + return false; + } + Syntax.isIntegerLiteral = isIntegerLiteral; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var NormalModeFactory = (function () { + function NormalModeFactory() { + } + NormalModeFactory.prototype.sourceUnit = function (moduleElements, endOfFileToken) { + return new TypeScript.SourceUnitSyntax(moduleElements, endOfFileToken, false); + }; + NormalModeFactory.prototype.externalModuleReference = function (requireKeyword, openParenToken, stringLiteral, closeParenToken) { + return new TypeScript.ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, false); + }; + NormalModeFactory.prototype.moduleNameModuleReference = function (moduleName) { + return new TypeScript.ModuleNameModuleReferenceSyntax(moduleName, false); + }; + NormalModeFactory.prototype.importDeclaration = function (modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new TypeScript.ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, false); + }; + NormalModeFactory.prototype.exportAssignment = function (exportKeyword, equalsToken, identifier, semicolonToken) { + return new TypeScript.ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.classDeclaration = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + return new TypeScript.ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.interfaceDeclaration = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + return new TypeScript.InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, false); + }; + NormalModeFactory.prototype.heritageClause = function (kind, extendsOrImplementsKeyword, typeNames) { + return new TypeScript.HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, false); + }; + NormalModeFactory.prototype.moduleDeclaration = function (modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + return new TypeScript.ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.functionDeclaration = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + return new TypeScript.FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.variableStatement = function (modifiers, variableDeclaration, semicolonToken) { + return new TypeScript.VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, false); + }; + NormalModeFactory.prototype.variableDeclaration = function (varKeyword, variableDeclarators) { + return new TypeScript.VariableDeclarationSyntax(varKeyword, variableDeclarators, false); + }; + NormalModeFactory.prototype.variableDeclarator = function (propertyName, typeAnnotation, equalsValueClause) { + return new TypeScript.VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, false); + }; + NormalModeFactory.prototype.equalsValueClause = function (equalsToken, value) { + return new TypeScript.EqualsValueClauseSyntax(equalsToken, value, false); + }; + NormalModeFactory.prototype.prefixUnaryExpression = function (kind, operatorToken, operand) { + return new TypeScript.PrefixUnaryExpressionSyntax(kind, operatorToken, operand, false); + }; + NormalModeFactory.prototype.arrayLiteralExpression = function (openBracketToken, expressions, closeBracketToken) { + return new TypeScript.ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, false); + }; + NormalModeFactory.prototype.omittedExpression = function () { + return new TypeScript.OmittedExpressionSyntax(false); + }; + NormalModeFactory.prototype.parenthesizedExpression = function (openParenToken, expression, closeParenToken) { + return new TypeScript.ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, false); + }; + NormalModeFactory.prototype.simpleArrowFunctionExpression = function (identifier, equalsGreaterThanToken, block, expression) { + return new TypeScript.SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, false); + }; + NormalModeFactory.prototype.parenthesizedArrowFunctionExpression = function (callSignature, equalsGreaterThanToken, block, expression) { + return new TypeScript.ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, false); + }; + NormalModeFactory.prototype.qualifiedName = function (left, dotToken, right) { + return new TypeScript.QualifiedNameSyntax(left, dotToken, right, false); + }; + NormalModeFactory.prototype.typeArgumentList = function (lessThanToken, typeArguments, greaterThanToken) { + return new TypeScript.TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, false); + }; + NormalModeFactory.prototype.constructorType = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, false); + }; + NormalModeFactory.prototype.functionType = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, false); + }; + NormalModeFactory.prototype.objectType = function (openBraceToken, typeMembers, closeBraceToken) { + return new TypeScript.ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, false); + }; + NormalModeFactory.prototype.arrayType = function (type, openBracketToken, closeBracketToken) { + return new TypeScript.ArrayTypeSyntax(type, openBracketToken, closeBracketToken, false); + }; + NormalModeFactory.prototype.genericType = function (name, typeArgumentList) { + return new TypeScript.GenericTypeSyntax(name, typeArgumentList, false); + }; + NormalModeFactory.prototype.typeQuery = function (typeOfKeyword, name) { + return new TypeScript.TypeQuerySyntax(typeOfKeyword, name, false); + }; + NormalModeFactory.prototype.typeAnnotation = function (colonToken, type) { + return new TypeScript.TypeAnnotationSyntax(colonToken, type, false); + }; + NormalModeFactory.prototype.block = function (openBraceToken, statements, closeBraceToken) { + return new TypeScript.BlockSyntax(openBraceToken, statements, closeBraceToken, false); + }; + NormalModeFactory.prototype.parameter = function (dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + return new TypeScript.ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, false); + }; + NormalModeFactory.prototype.memberAccessExpression = function (expression, dotToken, name) { + return new TypeScript.MemberAccessExpressionSyntax(expression, dotToken, name, false); + }; + NormalModeFactory.prototype.postfixUnaryExpression = function (kind, operand, operatorToken) { + return new TypeScript.PostfixUnaryExpressionSyntax(kind, operand, operatorToken, false); + }; + NormalModeFactory.prototype.elementAccessExpression = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + return new TypeScript.ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, false); + }; + NormalModeFactory.prototype.invocationExpression = function (expression, argumentList) { + return new TypeScript.InvocationExpressionSyntax(expression, argumentList, false); + }; + NormalModeFactory.prototype.argumentList = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + return new TypeScript.ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, false); + }; + NormalModeFactory.prototype.binaryExpression = function (kind, left, operatorToken, right) { + return new TypeScript.BinaryExpressionSyntax(kind, left, operatorToken, right, false); + }; + NormalModeFactory.prototype.conditionalExpression = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + return new TypeScript.ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, false); + }; + NormalModeFactory.prototype.constructSignature = function (newKeyword, callSignature) { + return new TypeScript.ConstructSignatureSyntax(newKeyword, callSignature, false); + }; + NormalModeFactory.prototype.methodSignature = function (propertyName, questionToken, callSignature) { + return new TypeScript.MethodSignatureSyntax(propertyName, questionToken, callSignature, false); + }; + NormalModeFactory.prototype.indexSignature = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + return new TypeScript.IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, false); + }; + NormalModeFactory.prototype.propertySignature = function (propertyName, questionToken, typeAnnotation) { + return new TypeScript.PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, false); + }; + NormalModeFactory.prototype.callSignature = function (typeParameterList, parameterList, typeAnnotation) { + return new TypeScript.CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, false); + }; + NormalModeFactory.prototype.parameterList = function (openParenToken, parameters, closeParenToken) { + return new TypeScript.ParameterListSyntax(openParenToken, parameters, closeParenToken, false); + }; + NormalModeFactory.prototype.typeParameterList = function (lessThanToken, typeParameters, greaterThanToken) { + return new TypeScript.TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, false); + }; + NormalModeFactory.prototype.typeParameter = function (identifier, constraint) { + return new TypeScript.TypeParameterSyntax(identifier, constraint, false); + }; + NormalModeFactory.prototype.constraint = function (extendsKeyword, type) { + return new TypeScript.ConstraintSyntax(extendsKeyword, type, false); + }; + NormalModeFactory.prototype.elseClause = function (elseKeyword, statement) { + return new TypeScript.ElseClauseSyntax(elseKeyword, statement, false); + }; + NormalModeFactory.prototype.ifStatement = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + return new TypeScript.IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, false); + }; + NormalModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { + return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, false); + }; + NormalModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { + return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, false); + }; + NormalModeFactory.prototype.getAccessor = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + return new TypeScript.GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, false); + }; + NormalModeFactory.prototype.setAccessor = function (modifiers, setKeyword, propertyName, parameterList, block) { + return new TypeScript.SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, false); + }; + NormalModeFactory.prototype.memberVariableDeclaration = function (modifiers, variableDeclarator, semicolonToken) { + return new TypeScript.MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, false); + }; + NormalModeFactory.prototype.indexMemberDeclaration = function (modifiers, indexSignature, semicolonToken) { + return new TypeScript.IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, false); + }; + NormalModeFactory.prototype.throwStatement = function (throwKeyword, expression, semicolonToken) { + return new TypeScript.ThrowStatementSyntax(throwKeyword, expression, semicolonToken, false); + }; + NormalModeFactory.prototype.returnStatement = function (returnKeyword, expression, semicolonToken) { + return new TypeScript.ReturnStatementSyntax(returnKeyword, expression, semicolonToken, false); + }; + NormalModeFactory.prototype.objectCreationExpression = function (newKeyword, expression, argumentList) { + return new TypeScript.ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, false); + }; + NormalModeFactory.prototype.switchStatement = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + return new TypeScript.SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, false); + }; + NormalModeFactory.prototype.caseSwitchClause = function (caseKeyword, expression, colonToken, statements) { + return new TypeScript.CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, false); + }; + NormalModeFactory.prototype.defaultSwitchClause = function (defaultKeyword, colonToken, statements) { + return new TypeScript.DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, false); + }; + NormalModeFactory.prototype.breakStatement = function (breakKeyword, identifier, semicolonToken) { + return new TypeScript.BreakStatementSyntax(breakKeyword, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.continueStatement = function (continueKeyword, identifier, semicolonToken) { + return new TypeScript.ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, false); + }; + NormalModeFactory.prototype.forStatement = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + return new TypeScript.ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.forInStatement = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + return new TypeScript.ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.whileStatement = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.withStatement = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, false); + }; + NormalModeFactory.prototype.enumDeclaration = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + return new TypeScript.EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, false); + }; + NormalModeFactory.prototype.enumElement = function (propertyName, equalsValueClause) { + return new TypeScript.EnumElementSyntax(propertyName, equalsValueClause, false); + }; + NormalModeFactory.prototype.castExpression = function (lessThanToken, type, greaterThanToken, expression) { + return new TypeScript.CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, false); + }; + NormalModeFactory.prototype.objectLiteralExpression = function (openBraceToken, propertyAssignments, closeBraceToken) { + return new TypeScript.ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, false); + }; + NormalModeFactory.prototype.simplePropertyAssignment = function (propertyName, colonToken, expression) { + return new TypeScript.SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, false); + }; + NormalModeFactory.prototype.functionPropertyAssignment = function (propertyName, callSignature, block) { + return new TypeScript.FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, false); + }; + NormalModeFactory.prototype.functionExpression = function (functionKeyword, identifier, callSignature, block) { + return new TypeScript.FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, false); + }; + NormalModeFactory.prototype.emptyStatement = function (semicolonToken) { + return new TypeScript.EmptyStatementSyntax(semicolonToken, false); + }; + NormalModeFactory.prototype.tryStatement = function (tryKeyword, block, catchClause, finallyClause) { + return new TypeScript.TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, false); + }; + NormalModeFactory.prototype.catchClause = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + return new TypeScript.CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, false); + }; + NormalModeFactory.prototype.finallyClause = function (finallyKeyword, block) { + return new TypeScript.FinallyClauseSyntax(finallyKeyword, block, false); + }; + NormalModeFactory.prototype.labeledStatement = function (identifier, colonToken, statement) { + return new TypeScript.LabeledStatementSyntax(identifier, colonToken, statement, false); + }; + NormalModeFactory.prototype.doStatement = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + return new TypeScript.DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, false); + }; + NormalModeFactory.prototype.typeOfExpression = function (typeOfKeyword, expression) { + return new TypeScript.TypeOfExpressionSyntax(typeOfKeyword, expression, false); + }; + NormalModeFactory.prototype.deleteExpression = function (deleteKeyword, expression) { + return new TypeScript.DeleteExpressionSyntax(deleteKeyword, expression, false); + }; + NormalModeFactory.prototype.voidExpression = function (voidKeyword, expression) { + return new TypeScript.VoidExpressionSyntax(voidKeyword, expression, false); + }; + NormalModeFactory.prototype.debuggerStatement = function (debuggerKeyword, semicolonToken) { + return new TypeScript.DebuggerStatementSyntax(debuggerKeyword, semicolonToken, false); + }; + return NormalModeFactory; + })(); + Syntax.NormalModeFactory = NormalModeFactory; + + var StrictModeFactory = (function () { + function StrictModeFactory() { + } + StrictModeFactory.prototype.sourceUnit = function (moduleElements, endOfFileToken) { + return new TypeScript.SourceUnitSyntax(moduleElements, endOfFileToken, true); + }; + StrictModeFactory.prototype.externalModuleReference = function (requireKeyword, openParenToken, stringLiteral, closeParenToken) { + return new TypeScript.ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, true); + }; + StrictModeFactory.prototype.moduleNameModuleReference = function (moduleName) { + return new TypeScript.ModuleNameModuleReferenceSyntax(moduleName, true); + }; + StrictModeFactory.prototype.importDeclaration = function (modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new TypeScript.ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, true); + }; + StrictModeFactory.prototype.exportAssignment = function (exportKeyword, equalsToken, identifier, semicolonToken) { + return new TypeScript.ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.classDeclaration = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + return new TypeScript.ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.interfaceDeclaration = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + return new TypeScript.InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, true); + }; + StrictModeFactory.prototype.heritageClause = function (kind, extendsOrImplementsKeyword, typeNames) { + return new TypeScript.HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, true); + }; + StrictModeFactory.prototype.moduleDeclaration = function (modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + return new TypeScript.ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.functionDeclaration = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + return new TypeScript.FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.variableStatement = function (modifiers, variableDeclaration, semicolonToken) { + return new TypeScript.VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, true); + }; + StrictModeFactory.prototype.variableDeclaration = function (varKeyword, variableDeclarators) { + return new TypeScript.VariableDeclarationSyntax(varKeyword, variableDeclarators, true); + }; + StrictModeFactory.prototype.variableDeclarator = function (propertyName, typeAnnotation, equalsValueClause) { + return new TypeScript.VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, true); + }; + StrictModeFactory.prototype.equalsValueClause = function (equalsToken, value) { + return new TypeScript.EqualsValueClauseSyntax(equalsToken, value, true); + }; + StrictModeFactory.prototype.prefixUnaryExpression = function (kind, operatorToken, operand) { + return new TypeScript.PrefixUnaryExpressionSyntax(kind, operatorToken, operand, true); + }; + StrictModeFactory.prototype.arrayLiteralExpression = function (openBracketToken, expressions, closeBracketToken) { + return new TypeScript.ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, true); + }; + StrictModeFactory.prototype.omittedExpression = function () { + return new TypeScript.OmittedExpressionSyntax(true); + }; + StrictModeFactory.prototype.parenthesizedExpression = function (openParenToken, expression, closeParenToken) { + return new TypeScript.ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, true); + }; + StrictModeFactory.prototype.simpleArrowFunctionExpression = function (identifier, equalsGreaterThanToken, block, expression) { + return new TypeScript.SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, true); + }; + StrictModeFactory.prototype.parenthesizedArrowFunctionExpression = function (callSignature, equalsGreaterThanToken, block, expression) { + return new TypeScript.ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, true); + }; + StrictModeFactory.prototype.qualifiedName = function (left, dotToken, right) { + return new TypeScript.QualifiedNameSyntax(left, dotToken, right, true); + }; + StrictModeFactory.prototype.typeArgumentList = function (lessThanToken, typeArguments, greaterThanToken) { + return new TypeScript.TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, true); + }; + StrictModeFactory.prototype.constructorType = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, true); + }; + StrictModeFactory.prototype.functionType = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + return new TypeScript.FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, true); + }; + StrictModeFactory.prototype.objectType = function (openBraceToken, typeMembers, closeBraceToken) { + return new TypeScript.ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, true); + }; + StrictModeFactory.prototype.arrayType = function (type, openBracketToken, closeBracketToken) { + return new TypeScript.ArrayTypeSyntax(type, openBracketToken, closeBracketToken, true); + }; + StrictModeFactory.prototype.genericType = function (name, typeArgumentList) { + return new TypeScript.GenericTypeSyntax(name, typeArgumentList, true); + }; + StrictModeFactory.prototype.typeQuery = function (typeOfKeyword, name) { + return new TypeScript.TypeQuerySyntax(typeOfKeyword, name, true); + }; + StrictModeFactory.prototype.typeAnnotation = function (colonToken, type) { + return new TypeScript.TypeAnnotationSyntax(colonToken, type, true); + }; + StrictModeFactory.prototype.block = function (openBraceToken, statements, closeBraceToken) { + return new TypeScript.BlockSyntax(openBraceToken, statements, closeBraceToken, true); + }; + StrictModeFactory.prototype.parameter = function (dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + return new TypeScript.ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, true); + }; + StrictModeFactory.prototype.memberAccessExpression = function (expression, dotToken, name) { + return new TypeScript.MemberAccessExpressionSyntax(expression, dotToken, name, true); + }; + StrictModeFactory.prototype.postfixUnaryExpression = function (kind, operand, operatorToken) { + return new TypeScript.PostfixUnaryExpressionSyntax(kind, operand, operatorToken, true); + }; + StrictModeFactory.prototype.elementAccessExpression = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + return new TypeScript.ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, true); + }; + StrictModeFactory.prototype.invocationExpression = function (expression, argumentList) { + return new TypeScript.InvocationExpressionSyntax(expression, argumentList, true); + }; + StrictModeFactory.prototype.argumentList = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + return new TypeScript.ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, true); + }; + StrictModeFactory.prototype.binaryExpression = function (kind, left, operatorToken, right) { + return new TypeScript.BinaryExpressionSyntax(kind, left, operatorToken, right, true); + }; + StrictModeFactory.prototype.conditionalExpression = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + return new TypeScript.ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, true); + }; + StrictModeFactory.prototype.constructSignature = function (newKeyword, callSignature) { + return new TypeScript.ConstructSignatureSyntax(newKeyword, callSignature, true); + }; + StrictModeFactory.prototype.methodSignature = function (propertyName, questionToken, callSignature) { + return new TypeScript.MethodSignatureSyntax(propertyName, questionToken, callSignature, true); + }; + StrictModeFactory.prototype.indexSignature = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + return new TypeScript.IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, true); + }; + StrictModeFactory.prototype.propertySignature = function (propertyName, questionToken, typeAnnotation) { + return new TypeScript.PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, true); + }; + StrictModeFactory.prototype.callSignature = function (typeParameterList, parameterList, typeAnnotation) { + return new TypeScript.CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, true); + }; + StrictModeFactory.prototype.parameterList = function (openParenToken, parameters, closeParenToken) { + return new TypeScript.ParameterListSyntax(openParenToken, parameters, closeParenToken, true); + }; + StrictModeFactory.prototype.typeParameterList = function (lessThanToken, typeParameters, greaterThanToken) { + return new TypeScript.TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, true); + }; + StrictModeFactory.prototype.typeParameter = function (identifier, constraint) { + return new TypeScript.TypeParameterSyntax(identifier, constraint, true); + }; + StrictModeFactory.prototype.constraint = function (extendsKeyword, type) { + return new TypeScript.ConstraintSyntax(extendsKeyword, type, true); + }; + StrictModeFactory.prototype.elseClause = function (elseKeyword, statement) { + return new TypeScript.ElseClauseSyntax(elseKeyword, statement, true); + }; + StrictModeFactory.prototype.ifStatement = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + return new TypeScript.IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, true); + }; + StrictModeFactory.prototype.expressionStatement = function (expression, semicolonToken) { + return new TypeScript.ExpressionStatementSyntax(expression, semicolonToken, true); + }; + StrictModeFactory.prototype.constructorDeclaration = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + return new TypeScript.ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.memberFunctionDeclaration = function (modifiers, propertyName, callSignature, block, semicolonToken) { + return new TypeScript.MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, true); + }; + StrictModeFactory.prototype.getAccessor = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + return new TypeScript.GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, true); + }; + StrictModeFactory.prototype.setAccessor = function (modifiers, setKeyword, propertyName, parameterList, block) { + return new TypeScript.SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, true); + }; + StrictModeFactory.prototype.memberVariableDeclaration = function (modifiers, variableDeclarator, semicolonToken) { + return new TypeScript.MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, true); + }; + StrictModeFactory.prototype.indexMemberDeclaration = function (modifiers, indexSignature, semicolonToken) { + return new TypeScript.IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, true); + }; + StrictModeFactory.prototype.throwStatement = function (throwKeyword, expression, semicolonToken) { + return new TypeScript.ThrowStatementSyntax(throwKeyword, expression, semicolonToken, true); + }; + StrictModeFactory.prototype.returnStatement = function (returnKeyword, expression, semicolonToken) { + return new TypeScript.ReturnStatementSyntax(returnKeyword, expression, semicolonToken, true); + }; + StrictModeFactory.prototype.objectCreationExpression = function (newKeyword, expression, argumentList) { + return new TypeScript.ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, true); + }; + StrictModeFactory.prototype.switchStatement = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + return new TypeScript.SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, true); + }; + StrictModeFactory.prototype.caseSwitchClause = function (caseKeyword, expression, colonToken, statements) { + return new TypeScript.CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, true); + }; + StrictModeFactory.prototype.defaultSwitchClause = function (defaultKeyword, colonToken, statements) { + return new TypeScript.DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, true); + }; + StrictModeFactory.prototype.breakStatement = function (breakKeyword, identifier, semicolonToken) { + return new TypeScript.BreakStatementSyntax(breakKeyword, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.continueStatement = function (continueKeyword, identifier, semicolonToken) { + return new TypeScript.ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, true); + }; + StrictModeFactory.prototype.forStatement = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + return new TypeScript.ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.forInStatement = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + return new TypeScript.ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.whileStatement = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.withStatement = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + return new TypeScript.WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, true); + }; + StrictModeFactory.prototype.enumDeclaration = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + return new TypeScript.EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, true); + }; + StrictModeFactory.prototype.enumElement = function (propertyName, equalsValueClause) { + return new TypeScript.EnumElementSyntax(propertyName, equalsValueClause, true); + }; + StrictModeFactory.prototype.castExpression = function (lessThanToken, type, greaterThanToken, expression) { + return new TypeScript.CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, true); + }; + StrictModeFactory.prototype.objectLiteralExpression = function (openBraceToken, propertyAssignments, closeBraceToken) { + return new TypeScript.ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, true); + }; + StrictModeFactory.prototype.simplePropertyAssignment = function (propertyName, colonToken, expression) { + return new TypeScript.SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, true); + }; + StrictModeFactory.prototype.functionPropertyAssignment = function (propertyName, callSignature, block) { + return new TypeScript.FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, true); + }; + StrictModeFactory.prototype.functionExpression = function (functionKeyword, identifier, callSignature, block) { + return new TypeScript.FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, true); + }; + StrictModeFactory.prototype.emptyStatement = function (semicolonToken) { + return new TypeScript.EmptyStatementSyntax(semicolonToken, true); + }; + StrictModeFactory.prototype.tryStatement = function (tryKeyword, block, catchClause, finallyClause) { + return new TypeScript.TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, true); + }; + StrictModeFactory.prototype.catchClause = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + return new TypeScript.CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, true); + }; + StrictModeFactory.prototype.finallyClause = function (finallyKeyword, block) { + return new TypeScript.FinallyClauseSyntax(finallyKeyword, block, true); + }; + StrictModeFactory.prototype.labeledStatement = function (identifier, colonToken, statement) { + return new TypeScript.LabeledStatementSyntax(identifier, colonToken, statement, true); + }; + StrictModeFactory.prototype.doStatement = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + return new TypeScript.DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, true); + }; + StrictModeFactory.prototype.typeOfExpression = function (typeOfKeyword, expression) { + return new TypeScript.TypeOfExpressionSyntax(typeOfKeyword, expression, true); + }; + StrictModeFactory.prototype.deleteExpression = function (deleteKeyword, expression) { + return new TypeScript.DeleteExpressionSyntax(deleteKeyword, expression, true); + }; + StrictModeFactory.prototype.voidExpression = function (voidKeyword, expression) { + return new TypeScript.VoidExpressionSyntax(voidKeyword, expression, true); + }; + StrictModeFactory.prototype.debuggerStatement = function (debuggerKeyword, semicolonToken) { + return new TypeScript.DebuggerStatementSyntax(debuggerKeyword, semicolonToken, true); + }; + return StrictModeFactory; + })(); + Syntax.StrictModeFactory = StrictModeFactory; + + Syntax.normalModeFactory = new NormalModeFactory(); + Syntax.strictModeFactory = new StrictModeFactory(); + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (SyntaxFacts) { + function isDirectivePrologueElement(node) { + if (node.kind() === 149 /* ExpressionStatement */) { + var expressionStatement = node; + var expression = expressionStatement.expression; + + if (expression.kind() === 14 /* StringLiteral */) { + return true; + } + } + + return false; + } + SyntaxFacts.isDirectivePrologueElement = isDirectivePrologueElement; + + function isUseStrictDirective(node) { + var expressionStatement = node; + var stringLiteral = expressionStatement.expression; + + var text = stringLiteral.text(); + return text === '"use strict"' || text === "'use strict'"; + } + SyntaxFacts.isUseStrictDirective = isUseStrictDirective; + + function isIdentifierNameOrAnyKeyword(token) { + var tokenKind = token.tokenKind; + return tokenKind === 11 /* IdentifierName */ || SyntaxFacts.isAnyKeyword(tokenKind); + } + SyntaxFacts.isIdentifierNameOrAnyKeyword = isIdentifierNameOrAnyKeyword; + })(TypeScript.SyntaxFacts || (TypeScript.SyntaxFacts = {})); + var SyntaxFacts = TypeScript.SyntaxFacts; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var EmptySyntaxList = (function () { + function EmptySyntaxList() { + } + EmptySyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + EmptySyntaxList.prototype.isNode = function () { + return false; + }; + EmptySyntaxList.prototype.isToken = function () { + return false; + }; + EmptySyntaxList.prototype.isList = function () { + return true; + }; + EmptySyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + EmptySyntaxList.prototype.toJSON = function (key) { + return []; + }; + + EmptySyntaxList.prototype.childCount = function () { + return 0; + }; + + EmptySyntaxList.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptySyntaxList.prototype.toArray = function () { + return []; + }; + + EmptySyntaxList.prototype.collectTextElements = function (elements) { + }; + + EmptySyntaxList.prototype.firstToken = function () { + return null; + }; + + EmptySyntaxList.prototype.lastToken = function () { + return null; + }; + + EmptySyntaxList.prototype.fullWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.width = function () { + return 0; + }; + + EmptySyntaxList.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySyntaxList.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + EmptySyntaxList.prototype.leadingTriviaWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.trailingTriviaWidth = function () { + return 0; + }; + + EmptySyntaxList.prototype.fullText = function () { + return ""; + }; + + EmptySyntaxList.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptySyntaxList.prototype.isIncrementallyUnusable = function () { + return false; + }; + + EmptySyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + throw TypeScript.Errors.invalidOperation(); + }; + + EmptySyntaxList.prototype.insertChildrenInto = function (array, index) { + }; + return EmptySyntaxList; + })(); + Syntax.EmptySyntaxList = EmptySyntaxList; + + Syntax.emptyList = new EmptySyntaxList(); + + var SingletonSyntaxList = (function () { + function SingletonSyntaxList(item) { + this.item = item; + } + SingletonSyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + SingletonSyntaxList.prototype.isToken = function () { + return false; + }; + SingletonSyntaxList.prototype.isNode = function () { + return false; + }; + SingletonSyntaxList.prototype.isList = function () { + return true; + }; + SingletonSyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + SingletonSyntaxList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSyntaxList.prototype.childCount = function () { + return 1; + }; + + SingletonSyntaxList.prototype.childAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSyntaxList.prototype.toArray = function () { + return [this.item]; + }; + + SingletonSyntaxList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSyntaxList.prototype.firstToken = function () { + return this.item.firstToken(); + }; + + SingletonSyntaxList.prototype.lastToken = function () { + return this.item.lastToken(); + }; + + SingletonSyntaxList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSyntaxList.prototype.width = function () { + return this.item.width(); + }; + + SingletonSyntaxList.prototype.leadingTrivia = function () { + return this.item.leadingTrivia(); + }; + + SingletonSyntaxList.prototype.trailingTrivia = function () { + return this.item.trailingTrivia(); + }; + + SingletonSyntaxList.prototype.leadingTriviaWidth = function () { + return this.item.leadingTriviaWidth(); + }; + + SingletonSyntaxList.prototype.trailingTriviaWidth = function () { + return this.item.trailingTriviaWidth(); + }; + + SingletonSyntaxList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSyntaxList.prototype.isTypeScriptSpecific = function () { + return this.item.isTypeScriptSpecific(); + }; + + SingletonSyntaxList.prototype.isIncrementallyUnusable = function () { + return this.item.isIncrementallyUnusable(); + }; + + SingletonSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + return this.item.findTokenInternal(new TypeScript.PositionedList(parent, this, fullStart), position, fullStart); + }; + + SingletonSyntaxList.prototype.insertChildrenInto = function (array, index) { + array.splice(index, 0, this.item); + }; + return SingletonSyntaxList; + })(); + + var NormalSyntaxList = (function () { + function NormalSyntaxList(nodeOrTokens) { + this._data = 0; + this.nodeOrTokens = nodeOrTokens; + } + NormalSyntaxList.prototype.kind = function () { + return 1 /* List */; + }; + + NormalSyntaxList.prototype.isNode = function () { + return false; + }; + NormalSyntaxList.prototype.isToken = function () { + return false; + }; + NormalSyntaxList.prototype.isList = function () { + return true; + }; + NormalSyntaxList.prototype.isSeparatedList = function () { + return false; + }; + + NormalSyntaxList.prototype.toJSON = function (key) { + return this.nodeOrTokens; + }; + + NormalSyntaxList.prototype.childCount = function () { + return this.nodeOrTokens.length; + }; + + NormalSyntaxList.prototype.childAt = function (index) { + if (index < 0 || index >= this.nodeOrTokens.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.nodeOrTokens[index]; + }; + + NormalSyntaxList.prototype.toArray = function () { + return this.nodeOrTokens.slice(0); + }; + + NormalSyntaxList.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var element = this.nodeOrTokens[i]; + element.collectTextElements(elements); + } + }; + + NormalSyntaxList.prototype.firstToken = function () { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var token = this.nodeOrTokens[i].firstToken(); + if (token !== null) { + return token; + } + } + + return null; + }; + + NormalSyntaxList.prototype.lastToken = function () { + for (var i = this.nodeOrTokens.length - 1; i >= 0; i--) { + var token = this.nodeOrTokens[i].lastToken(); + if (token !== null) { + return token; + } + } + + return null; + }; + + NormalSyntaxList.prototype.fullText = function () { + var elements = new Array(); + this.collectTextElements(elements); + return elements.join(""); + }; + + NormalSyntaxList.prototype.isTypeScriptSpecific = function () { + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + if (this.nodeOrTokens[i].isTypeScriptSpecific()) { + return true; + } + } + + return false; + }; + + NormalSyntaxList.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + NormalSyntaxList.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + NormalSyntaxList.prototype.width = function () { + var fullWidth = this.fullWidth(); + return fullWidth - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + NormalSyntaxList.prototype.leadingTrivia = function () { + return this.firstToken().leadingTrivia(); + }; + + NormalSyntaxList.prototype.trailingTrivia = function () { + return this.lastToken().trailingTrivia(); + }; + + NormalSyntaxList.prototype.leadingTriviaWidth = function () { + return this.firstToken().leadingTriviaWidth(); + }; + + NormalSyntaxList.prototype.trailingTriviaWidth = function () { + return this.lastToken().trailingTriviaWidth(); + }; + + NormalSyntaxList.prototype.computeData = function () { + var fullWidth = 0; + var isIncrementallyUnusable = false; + + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var node = this.nodeOrTokens[i]; + fullWidth += node.fullWidth(); + isIncrementallyUnusable = isIncrementallyUnusable || node.isIncrementallyUnusable(); + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + NormalSyntaxList.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data = this.computeData(); + } + + return this._data; + }; + + NormalSyntaxList.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedList(parent, this, fullStart); + for (var i = 0, n = this.nodeOrTokens.length; i < n; i++) { + var nodeOrToken = this.nodeOrTokens[i]; + + var childWidth = nodeOrToken.fullWidth(); + if (position < childWidth) { + return nodeOrToken.findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + NormalSyntaxList.prototype.insertChildrenInto = function (array, index) { + if (index === 0) { + array.unshift.apply(array, this.nodeOrTokens); + } else { + array.splice.apply(array, [index, 0].concat(this.nodeOrTokens)); + } + }; + return NormalSyntaxList; + })(); + + function list(nodes) { + if (nodes === undefined || nodes === null || nodes.length === 0) { + return Syntax.emptyList; + } + + if (nodes.length === 1) { + var item = nodes[0]; + return new SingletonSyntaxList(item); + } + + return new NormalSyntaxList(nodes); + } + Syntax.list = list; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxNode = (function () { + function SyntaxNode(parsedInStrictMode) { + this._data = parsedInStrictMode ? 4 /* NodeParsedInStrictModeMask */ : 0; + } + SyntaxNode.prototype.isNode = function () { + return true; + }; + SyntaxNode.prototype.isToken = function () { + return false; + }; + SyntaxNode.prototype.isList = function () { + return false; + }; + SyntaxNode.prototype.isSeparatedList = function () { + return false; + }; + + SyntaxNode.prototype.kind = function () { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.childCount = function () { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.childAt = function (slot) { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.firstToken = function () { + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + if (element.fullWidth() > 0 || element.kind() === 10 /* EndOfFileToken */) { + return element.firstToken(); + } + } + } + + return null; + }; + + SyntaxNode.prototype.lastToken = function () { + for (var i = this.childCount() - 1; i >= 0; i--) { + var element = this.childAt(i); + + if (element !== null) { + if (element.fullWidth() > 0 || element.kind() === 10 /* EndOfFileToken */) { + return element.lastToken(); + } + } + } + + return null; + }; + + SyntaxNode.prototype.insertChildrenInto = function (array, index) { + for (var i = this.childCount() - 1; i >= 0; i--) { + var element = this.childAt(i); + + if (element !== null) { + if (element.isNode() || element.isToken()) { + array.splice(index, 0, element); + } else if (element.isList()) { + element.insertChildrenInto(array, index); + } else if (element.isSeparatedList()) { + element.insertChildrenInto(array, index); + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + } + }; + + SyntaxNode.prototype.leadingTrivia = function () { + var firstToken = this.firstToken(); + return firstToken ? firstToken.leadingTrivia() : TypeScript.Syntax.emptyTriviaList; + }; + + SyntaxNode.prototype.trailingTrivia = function () { + var lastToken = this.lastToken(); + return lastToken ? lastToken.trailingTrivia() : TypeScript.Syntax.emptyTriviaList; + }; + + SyntaxNode.prototype.toJSON = function (key) { + var result = { + kind: TypeScript.SyntaxKind[this.kind()], + fullWidth: this.fullWidth() + }; + + if (this.isIncrementallyUnusable()) { + result.isIncrementallyUnusable = true; + } + + if (this.parsedInStrictMode()) { + result.parsedInStrictMode = true; + } + + var thisAsIndexable = this; + for (var i = 0, n = this.childCount(); i < n; i++) { + var value = this.childAt(i); + + if (value) { + for (var name in this) { + if (value === thisAsIndexable[name]) { + result[name] = value; + break; + } + } + } + } + + return result; + }; + + SyntaxNode.prototype.accept = function (visitor) { + throw TypeScript.Errors.abstract(); + }; + + SyntaxNode.prototype.fullText = function () { + var elements = []; + this.collectTextElements(elements); + return elements.join(""); + }; + + SyntaxNode.prototype.collectTextElements = function (elements) { + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + element.collectTextElements(elements); + } + } + }; + + SyntaxNode.prototype.replaceToken = function (token1, token2) { + if (token1 === token2) { + return this; + } + + return this.accept(new TypeScript.SyntaxTokenReplacer(token1, token2)); + }; + + SyntaxNode.prototype.withLeadingTrivia = function (trivia) { + return this.replaceToken(this.firstToken(), this.firstToken().withLeadingTrivia(trivia)); + }; + + SyntaxNode.prototype.withTrailingTrivia = function (trivia) { + return this.replaceToken(this.lastToken(), this.lastToken().withTrailingTrivia(trivia)); + }; + + SyntaxNode.prototype.hasLeadingTrivia = function () { + return this.lastToken().hasLeadingTrivia(); + }; + + SyntaxNode.prototype.hasTrailingTrivia = function () { + return this.lastToken().hasTrailingTrivia(); + }; + + SyntaxNode.prototype.isTypeScriptSpecific = function () { + return false; + }; + + SyntaxNode.prototype.isIncrementallyUnusable = function () { + return (this.data() & 2 /* NodeIncrementallyUnusableMask */) !== 0; + }; + + SyntaxNode.prototype.parsedInStrictMode = function () { + return (this.data() & 4 /* NodeParsedInStrictModeMask */) !== 0; + }; + + SyntaxNode.prototype.fullWidth = function () { + return this.data() >>> 3 /* NodeFullWidthShift */; + }; + + SyntaxNode.prototype.computeData = function () { + var slotCount = this.childCount(); + + var fullWidth = 0; + var childWidth = 0; + + var isIncrementallyUnusable = ((this._data & 2 /* NodeIncrementallyUnusableMask */) !== 0) || slotCount === 0; + + for (var i = 0, n = slotCount; i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + childWidth = element.fullWidth(); + fullWidth += childWidth; + + if (!isIncrementallyUnusable) { + isIncrementallyUnusable = element.isIncrementallyUnusable(); + } + } + } + + return (fullWidth << 3 /* NodeFullWidthShift */) | (isIncrementallyUnusable ? 2 /* NodeIncrementallyUnusableMask */ : 0) | 1 /* NodeDataComputed */; + }; + + SyntaxNode.prototype.data = function () { + if ((this._data & 1 /* NodeDataComputed */) === 0) { + this._data |= this.computeData(); + } + + return this._data; + }; + + SyntaxNode.prototype.findToken = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var endOfFileToken = this.tryGetEndOfFileAt(position); + if (endOfFileToken !== null) { + return endOfFileToken; + } + + if (position < 0 || position >= this.fullWidth()) { + throw TypeScript.Errors.argumentOutOfRange("position"); + } + + var positionedToken = this.findTokenInternal(null, position, 0); + + if (includeSkippedTokens) { + return TypeScript.Syntax.findSkippedTokenInPositionedToken(positionedToken, position) || positionedToken; + } + + return positionedToken; + }; + + SyntaxNode.prototype.tryGetEndOfFileAt = function (position) { + if (this.kind() === 120 /* SourceUnit */ && position === this.fullWidth()) { + var sourceUnit = this; + return new TypeScript.PositionedToken(new TypeScript.PositionedNode(null, sourceUnit, 0), sourceUnit.endOfFileToken, sourceUnit.moduleElements.fullWidth()); + } + + return null; + }; + + SyntaxNode.prototype.findTokenInternal = function (parent, position, fullStart) { + parent = new TypeScript.PositionedNode(parent, this, fullStart); + for (var i = 0, n = this.childCount(); i < n; i++) { + var element = this.childAt(i); + + if (element !== null) { + var childWidth = element.fullWidth(); + + if (position < childWidth) { + return element.findTokenInternal(parent, position, fullStart); + } + + position -= childWidth; + fullStart += childWidth; + } + } + + throw TypeScript.Errors.invalidOperation(); + }; + + SyntaxNode.prototype.findTokenOnLeft = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var positionedToken = this.findToken(position, false); + var start = positionedToken.start(); + + if (includeSkippedTokens) { + positionedToken = TypeScript.Syntax.findSkippedTokenOnLeft(positionedToken, position) || positionedToken; + } + + if (position > start) { + return positionedToken; + } + + if (positionedToken.fullStart() === 0) { + return null; + } + + return positionedToken.previousToken(includeSkippedTokens); + }; + + SyntaxNode.prototype.findCompleteTokenOnLeft = function (position, includeSkippedTokens) { + if (typeof includeSkippedTokens === "undefined") { includeSkippedTokens = false; } + var positionedToken = this.findToken(position, false); + + if (includeSkippedTokens) { + positionedToken = TypeScript.Syntax.findSkippedTokenOnLeft(positionedToken, position) || positionedToken; + } + + if (positionedToken.token().width() > 0 && position >= positionedToken.end()) { + return positionedToken; + } + + return positionedToken.previousToken(includeSkippedTokens); + }; + + SyntaxNode.prototype.isModuleElement = function () { + return false; + }; + + SyntaxNode.prototype.isClassElement = function () { + return false; + }; + + SyntaxNode.prototype.isTypeMember = function () { + return false; + }; + + SyntaxNode.prototype.isStatement = function () { + return false; + }; + + SyntaxNode.prototype.isExpression = function () { + return false; + }; + + SyntaxNode.prototype.isSwitchClause = function () { + return false; + }; + + SyntaxNode.prototype.structuralEquals = function (node) { + if (this === node) { + return true; + } + if (node === null) { + return false; + } + if (this.kind() !== node.kind()) { + return false; + } + + for (var i = 0, n = this.childCount(); i < n; i++) { + var element1 = this.childAt(i); + var element2 = node.childAt(i); + + if (!TypeScript.Syntax.elementStructuralEquals(element1, element2)) { + return false; + } + } + + return true; + }; + + SyntaxNode.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + SyntaxNode.prototype.leadingTriviaWidth = function () { + var firstToken = this.firstToken(); + return firstToken === null ? 0 : firstToken.leadingTriviaWidth(); + }; + + SyntaxNode.prototype.trailingTriviaWidth = function () { + var lastToken = this.lastToken(); + return lastToken === null ? 0 : lastToken.trailingTriviaWidth(); + }; + return SyntaxNode; + })(); + TypeScript.SyntaxNode = SyntaxNode; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceUnitSyntax = (function (_super) { + __extends(SourceUnitSyntax, _super); + function SourceUnitSyntax(moduleElements, endOfFileToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.moduleElements = moduleElements; + this.endOfFileToken = endOfFileToken; + } + SourceUnitSyntax.prototype.accept = function (visitor) { + return visitor.visitSourceUnit(this); + }; + + SourceUnitSyntax.prototype.kind = function () { + return 120 /* SourceUnit */; + }; + + SourceUnitSyntax.prototype.childCount = function () { + return 2; + }; + + SourceUnitSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.moduleElements; + case 1: + return this.endOfFileToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SourceUnitSyntax.prototype.update = function (moduleElements, endOfFileToken) { + if (this.moduleElements === moduleElements && this.endOfFileToken === endOfFileToken) { + return this; + } + + return new SourceUnitSyntax(moduleElements, endOfFileToken, this.parsedInStrictMode()); + }; + + SourceUnitSyntax.create = function (endOfFileToken) { + return new SourceUnitSyntax(TypeScript.Syntax.emptyList, endOfFileToken, false); + }; + + SourceUnitSyntax.create1 = function (endOfFileToken) { + return new SourceUnitSyntax(TypeScript.Syntax.emptyList, endOfFileToken, false); + }; + + SourceUnitSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SourceUnitSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SourceUnitSyntax.prototype.withModuleElements = function (moduleElements) { + return this.update(moduleElements, this.endOfFileToken); + }; + + SourceUnitSyntax.prototype.withModuleElement = function (moduleElement) { + return this.withModuleElements(TypeScript.Syntax.list([moduleElement])); + }; + + SourceUnitSyntax.prototype.withEndOfFileToken = function (endOfFileToken) { + return this.update(this.moduleElements, endOfFileToken); + }; + + SourceUnitSyntax.prototype.isTypeScriptSpecific = function () { + if (this.moduleElements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SourceUnitSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SourceUnitSyntax = SourceUnitSyntax; + + var ExternalModuleReferenceSyntax = (function (_super) { + __extends(ExternalModuleReferenceSyntax, _super); + function ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.requireKeyword = requireKeyword; + this.openParenToken = openParenToken; + this.stringLiteral = stringLiteral; + this.closeParenToken = closeParenToken; + } + ExternalModuleReferenceSyntax.prototype.accept = function (visitor) { + return visitor.visitExternalModuleReference(this); + }; + + ExternalModuleReferenceSyntax.prototype.kind = function () { + return 245 /* ExternalModuleReference */; + }; + + ExternalModuleReferenceSyntax.prototype.childCount = function () { + return 4; + }; + + ExternalModuleReferenceSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.requireKeyword; + case 1: + return this.openParenToken; + case 2: + return this.stringLiteral; + case 3: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExternalModuleReferenceSyntax.prototype.isModuleReference = function () { + return true; + }; + + ExternalModuleReferenceSyntax.prototype.update = function (requireKeyword, openParenToken, stringLiteral, closeParenToken) { + if (this.requireKeyword === requireKeyword && this.openParenToken === openParenToken && this.stringLiteral === stringLiteral && this.closeParenToken === closeParenToken) { + return this; + } + + return new ExternalModuleReferenceSyntax(requireKeyword, openParenToken, stringLiteral, closeParenToken, this.parsedInStrictMode()); + }; + + ExternalModuleReferenceSyntax.create1 = function (stringLiteral) { + return new ExternalModuleReferenceSyntax(TypeScript.Syntax.token(66 /* RequireKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), stringLiteral, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ExternalModuleReferenceSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExternalModuleReferenceSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExternalModuleReferenceSyntax.prototype.withRequireKeyword = function (requireKeyword) { + return this.update(requireKeyword, this.openParenToken, this.stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.requireKeyword, openParenToken, this.stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withStringLiteral = function (stringLiteral) { + return this.update(this.requireKeyword, this.openParenToken, stringLiteral, this.closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.requireKeyword, this.openParenToken, this.stringLiteral, closeParenToken); + }; + + ExternalModuleReferenceSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ExternalModuleReferenceSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExternalModuleReferenceSyntax = ExternalModuleReferenceSyntax; + + var ModuleNameModuleReferenceSyntax = (function (_super) { + __extends(ModuleNameModuleReferenceSyntax, _super); + function ModuleNameModuleReferenceSyntax(moduleName, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.moduleName = moduleName; + } + ModuleNameModuleReferenceSyntax.prototype.accept = function (visitor) { + return visitor.visitModuleNameModuleReference(this); + }; + + ModuleNameModuleReferenceSyntax.prototype.kind = function () { + return 246 /* ModuleNameModuleReference */; + }; + + ModuleNameModuleReferenceSyntax.prototype.childCount = function () { + return 1; + }; + + ModuleNameModuleReferenceSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.moduleName; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ModuleNameModuleReferenceSyntax.prototype.isModuleReference = function () { + return true; + }; + + ModuleNameModuleReferenceSyntax.prototype.update = function (moduleName) { + if (this.moduleName === moduleName) { + return this; + } + + return new ModuleNameModuleReferenceSyntax(moduleName, this.parsedInStrictMode()); + }; + + ModuleNameModuleReferenceSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ModuleNameModuleReferenceSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ModuleNameModuleReferenceSyntax.prototype.withModuleName = function (moduleName) { + return this.update(moduleName); + }; + + ModuleNameModuleReferenceSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ModuleNameModuleReferenceSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ModuleNameModuleReferenceSyntax = ModuleNameModuleReferenceSyntax; + + var ImportDeclarationSyntax = (function (_super) { + __extends(ImportDeclarationSyntax, _super); + function ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.importKeyword = importKeyword; + this.identifier = identifier; + this.equalsToken = equalsToken; + this.moduleReference = moduleReference; + this.semicolonToken = semicolonToken; + } + ImportDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitImportDeclaration(this); + }; + + ImportDeclarationSyntax.prototype.kind = function () { + return 133 /* ImportDeclaration */; + }; + + ImportDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + ImportDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.importKeyword; + case 2: + return this.identifier; + case 3: + return this.equalsToken; + case 4: + return this.moduleReference; + case 5: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ImportDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ImportDeclarationSyntax.prototype.update = function (modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + if (this.modifiers === modifiers && this.importKeyword === importKeyword && this.identifier === identifier && this.equalsToken === equalsToken && this.moduleReference === moduleReference && this.semicolonToken === semicolonToken) { + return this; + } + + return new ImportDeclarationSyntax(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, this.parsedInStrictMode()); + }; + + ImportDeclarationSyntax.create = function (importKeyword, identifier, equalsToken, moduleReference, semicolonToken) { + return new ImportDeclarationSyntax(TypeScript.Syntax.emptyList, importKeyword, identifier, equalsToken, moduleReference, semicolonToken, false); + }; + + ImportDeclarationSyntax.create1 = function (identifier, moduleReference) { + return new ImportDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(49 /* ImportKeyword */), identifier, TypeScript.Syntax.token(107 /* EqualsToken */), moduleReference, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ImportDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ImportDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ImportDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.importKeyword, this.identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ImportDeclarationSyntax.prototype.withImportKeyword = function (importKeyword) { + return this.update(this.modifiers, importKeyword, this.identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.importKeyword, identifier, this.equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(this.modifiers, this.importKeyword, this.identifier, equalsToken, this.moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withModuleReference = function (moduleReference) { + return this.update(this.modifiers, this.importKeyword, this.identifier, this.equalsToken, moduleReference, this.semicolonToken); + }; + + ImportDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.importKeyword, this.identifier, this.equalsToken, this.moduleReference, semicolonToken); + }; + + ImportDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ImportDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ImportDeclarationSyntax = ImportDeclarationSyntax; + + var ExportAssignmentSyntax = (function (_super) { + __extends(ExportAssignmentSyntax, _super); + function ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.exportKeyword = exportKeyword; + this.equalsToken = equalsToken; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + ExportAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitExportAssignment(this); + }; + + ExportAssignmentSyntax.prototype.kind = function () { + return 134 /* ExportAssignment */; + }; + + ExportAssignmentSyntax.prototype.childCount = function () { + return 4; + }; + + ExportAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.exportKeyword; + case 1: + return this.equalsToken; + case 2: + return this.identifier; + case 3: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExportAssignmentSyntax.prototype.isModuleElement = function () { + return true; + }; + + ExportAssignmentSyntax.prototype.update = function (exportKeyword, equalsToken, identifier, semicolonToken) { + if (this.exportKeyword === exportKeyword && this.equalsToken === equalsToken && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new ExportAssignmentSyntax(exportKeyword, equalsToken, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + ExportAssignmentSyntax.create1 = function (identifier) { + return new ExportAssignmentSyntax(TypeScript.Syntax.token(47 /* ExportKeyword */), TypeScript.Syntax.token(107 /* EqualsToken */), identifier, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ExportAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExportAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExportAssignmentSyntax.prototype.withExportKeyword = function (exportKeyword) { + return this.update(exportKeyword, this.equalsToken, this.identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(this.exportKeyword, equalsToken, this.identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.exportKeyword, this.equalsToken, identifier, this.semicolonToken); + }; + + ExportAssignmentSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.exportKeyword, this.equalsToken, this.identifier, semicolonToken); + }; + + ExportAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ExportAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExportAssignmentSyntax = ExportAssignmentSyntax; + + var ClassDeclarationSyntax = (function (_super) { + __extends(ClassDeclarationSyntax, _super); + function ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.classKeyword = classKeyword; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.openBraceToken = openBraceToken; + this.classElements = classElements; + this.closeBraceToken = closeBraceToken; + } + ClassDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitClassDeclaration(this); + }; + + ClassDeclarationSyntax.prototype.kind = function () { + return 131 /* ClassDeclaration */; + }; + + ClassDeclarationSyntax.prototype.childCount = function () { + return 8; + }; + + ClassDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.classKeyword; + case 2: + return this.identifier; + case 3: + return this.typeParameterList; + case 4: + return this.heritageClauses; + case 5: + return this.openBraceToken; + case 6: + return this.classElements; + case 7: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ClassDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ClassDeclarationSyntax.prototype.update = function (modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken) { + if (this.modifiers === modifiers && this.classKeyword === classKeyword && this.identifier === identifier && this.typeParameterList === typeParameterList && this.heritageClauses === heritageClauses && this.openBraceToken === openBraceToken && this.classElements === classElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ClassDeclarationSyntax(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken, this.parsedInStrictMode()); + }; + + ClassDeclarationSyntax.create = function (classKeyword, identifier, openBraceToken, closeBraceToken) { + return new ClassDeclarationSyntax(TypeScript.Syntax.emptyList, classKeyword, identifier, null, TypeScript.Syntax.emptyList, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + ClassDeclarationSyntax.create1 = function (identifier) { + return new ClassDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(44 /* ClassKeyword */), identifier, null, TypeScript.Syntax.emptyList, TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ClassDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ClassDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ClassDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ClassDeclarationSyntax.prototype.withClassKeyword = function (classKeyword) { + return this.update(this.modifiers, classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.classKeyword, identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.modifiers, this.classKeyword, this.identifier, typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withHeritageClauses = function (heritageClauses) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, heritageClauses, this.openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withHeritageClause = function (heritageClause) { + return this.withHeritageClauses(TypeScript.Syntax.list([heritageClause])); + }; + + ClassDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, openBraceToken, this.classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withClassElements = function (classElements) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, classElements, this.closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.withClassElement = function (classElement) { + return this.withClassElements(TypeScript.Syntax.list([classElement])); + }; + + ClassDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.classKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.openBraceToken, this.classElements, closeBraceToken); + }; + + ClassDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ClassDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ClassDeclarationSyntax = ClassDeclarationSyntax; + + var InterfaceDeclarationSyntax = (function (_super) { + __extends(InterfaceDeclarationSyntax, _super); + function InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.interfaceKeyword = interfaceKeyword; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.body = body; + } + InterfaceDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitInterfaceDeclaration(this); + }; + + InterfaceDeclarationSyntax.prototype.kind = function () { + return 128 /* InterfaceDeclaration */; + }; + + InterfaceDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + InterfaceDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.interfaceKeyword; + case 2: + return this.identifier; + case 3: + return this.typeParameterList; + case 4: + return this.heritageClauses; + case 5: + return this.body; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + InterfaceDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + InterfaceDeclarationSyntax.prototype.update = function (modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body) { + if (this.modifiers === modifiers && this.interfaceKeyword === interfaceKeyword && this.identifier === identifier && this.typeParameterList === typeParameterList && this.heritageClauses === heritageClauses && this.body === body) { + return this; + } + + return new InterfaceDeclarationSyntax(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, body, this.parsedInStrictMode()); + }; + + InterfaceDeclarationSyntax.create = function (interfaceKeyword, identifier, body) { + return new InterfaceDeclarationSyntax(TypeScript.Syntax.emptyList, interfaceKeyword, identifier, null, TypeScript.Syntax.emptyList, body, false); + }; + + InterfaceDeclarationSyntax.create1 = function (identifier) { + return new InterfaceDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(52 /* InterfaceKeyword */), identifier, null, TypeScript.Syntax.emptyList, ObjectTypeSyntax.create1(), false); + }; + + InterfaceDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + InterfaceDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + InterfaceDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + InterfaceDeclarationSyntax.prototype.withInterfaceKeyword = function (interfaceKeyword) { + return this.update(this.modifiers, interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.interfaceKeyword, identifier, this.typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, typeParameterList, this.heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withHeritageClauses = function (heritageClauses) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, heritageClauses, this.body); + }; + + InterfaceDeclarationSyntax.prototype.withHeritageClause = function (heritageClause) { + return this.withHeritageClauses(TypeScript.Syntax.list([heritageClause])); + }; + + InterfaceDeclarationSyntax.prototype.withBody = function (body) { + return this.update(this.modifiers, this.interfaceKeyword, this.identifier, this.typeParameterList, this.heritageClauses, body); + }; + + InterfaceDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return InterfaceDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.InterfaceDeclarationSyntax = InterfaceDeclarationSyntax; + + var HeritageClauseSyntax = (function (_super) { + __extends(HeritageClauseSyntax, _super); + function HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.extendsOrImplementsKeyword = extendsOrImplementsKeyword; + this.typeNames = typeNames; + + this._kind = kind; + } + HeritageClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitHeritageClause(this); + }; + + HeritageClauseSyntax.prototype.childCount = function () { + return 2; + }; + + HeritageClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.extendsOrImplementsKeyword; + case 1: + return this.typeNames; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + HeritageClauseSyntax.prototype.kind = function () { + return this._kind; + }; + + HeritageClauseSyntax.prototype.update = function (kind, extendsOrImplementsKeyword, typeNames) { + if (this._kind === kind && this.extendsOrImplementsKeyword === extendsOrImplementsKeyword && this.typeNames === typeNames) { + return this; + } + + return new HeritageClauseSyntax(kind, extendsOrImplementsKeyword, typeNames, this.parsedInStrictMode()); + }; + + HeritageClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + HeritageClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + HeritageClauseSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.extendsOrImplementsKeyword, this.typeNames); + }; + + HeritageClauseSyntax.prototype.withExtendsOrImplementsKeyword = function (extendsOrImplementsKeyword) { + return this.update(this._kind, extendsOrImplementsKeyword, this.typeNames); + }; + + HeritageClauseSyntax.prototype.withTypeNames = function (typeNames) { + return this.update(this._kind, this.extendsOrImplementsKeyword, typeNames); + }; + + HeritageClauseSyntax.prototype.withTypeName = function (typeName) { + return this.withTypeNames(TypeScript.Syntax.separatedList([typeName])); + }; + + HeritageClauseSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return HeritageClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.HeritageClauseSyntax = HeritageClauseSyntax; + + var ModuleDeclarationSyntax = (function (_super) { + __extends(ModuleDeclarationSyntax, _super); + function ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.moduleKeyword = moduleKeyword; + this.name = name; + this.stringLiteral = stringLiteral; + this.openBraceToken = openBraceToken; + this.moduleElements = moduleElements; + this.closeBraceToken = closeBraceToken; + } + ModuleDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitModuleDeclaration(this); + }; + + ModuleDeclarationSyntax.prototype.kind = function () { + return 130 /* ModuleDeclaration */; + }; + + ModuleDeclarationSyntax.prototype.childCount = function () { + return 7; + }; + + ModuleDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.moduleKeyword; + case 2: + return this.name; + case 3: + return this.stringLiteral; + case 4: + return this.openBraceToken; + case 5: + return this.moduleElements; + case 6: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ModuleDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + ModuleDeclarationSyntax.prototype.update = function (modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken) { + if (this.modifiers === modifiers && this.moduleKeyword === moduleKeyword && this.name === name && this.stringLiteral === stringLiteral && this.openBraceToken === openBraceToken && this.moduleElements === moduleElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ModuleDeclarationSyntax(modifiers, moduleKeyword, name, stringLiteral, openBraceToken, moduleElements, closeBraceToken, this.parsedInStrictMode()); + }; + + ModuleDeclarationSyntax.create = function (moduleKeyword, openBraceToken, closeBraceToken) { + return new ModuleDeclarationSyntax(TypeScript.Syntax.emptyList, moduleKeyword, null, null, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + ModuleDeclarationSyntax.create1 = function () { + return new ModuleDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(65 /* ModuleKeyword */), null, null, TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ModuleDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ModuleDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ModuleDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ModuleDeclarationSyntax.prototype.withModuleKeyword = function (moduleKeyword) { + return this.update(this.modifiers, moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withName = function (name) { + return this.update(this.modifiers, this.moduleKeyword, name, this.stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withStringLiteral = function (stringLiteral) { + return this.update(this.modifiers, this.moduleKeyword, this.name, stringLiteral, this.openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.moduleKeyword, this.name, this.stringLiteral, openBraceToken, this.moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModuleElements = function (moduleElements) { + return this.update(this.modifiers, this.moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, moduleElements, this.closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.withModuleElement = function (moduleElement) { + return this.withModuleElements(TypeScript.Syntax.list([moduleElement])); + }; + + ModuleDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.moduleKeyword, this.name, this.stringLiteral, this.openBraceToken, this.moduleElements, closeBraceToken); + }; + + ModuleDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ModuleDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ModuleDeclarationSyntax = ModuleDeclarationSyntax; + + var FunctionDeclarationSyntax = (function (_super) { + __extends(FunctionDeclarationSyntax, _super); + function FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.functionKeyword = functionKeyword; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + FunctionDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionDeclaration(this); + }; + + FunctionDeclarationSyntax.prototype.kind = function () { + return 129 /* FunctionDeclaration */; + }; + + FunctionDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + FunctionDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.functionKeyword; + case 2: + return this.identifier; + case 3: + return this.callSignature; + case 4: + return this.block; + case 5: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionDeclarationSyntax.prototype.isStatement = function () { + return true; + }; + + FunctionDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + FunctionDeclarationSyntax.prototype.update = function (modifiers, functionKeyword, identifier, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.functionKeyword === functionKeyword && this.identifier === identifier && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new FunctionDeclarationSyntax(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + FunctionDeclarationSyntax.create = function (functionKeyword, identifier, callSignature) { + return new FunctionDeclarationSyntax(TypeScript.Syntax.emptyList, functionKeyword, identifier, callSignature, null, null, false); + }; + + FunctionDeclarationSyntax.create1 = function (identifier) { + return new FunctionDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(27 /* FunctionKeyword */), identifier, CallSignatureSyntax.create1(), null, null, false); + }; + + FunctionDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.functionKeyword, this.identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + FunctionDeclarationSyntax.prototype.withFunctionKeyword = function (functionKeyword) { + return this.update(this.modifiers, functionKeyword, this.identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.functionKeyword, identifier, this.callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, callSignature, this.block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, this.callSignature, block, this.semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.functionKeyword, this.identifier, this.callSignature, this.block, semicolonToken); + }; + + FunctionDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.childCount() > 0) { + return true; + } + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block !== null && this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionDeclarationSyntax = FunctionDeclarationSyntax; + + var VariableStatementSyntax = (function (_super) { + __extends(VariableStatementSyntax, _super); + function VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.variableDeclaration = variableDeclaration; + this.semicolonToken = semicolonToken; + } + VariableStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableStatement(this); + }; + + VariableStatementSyntax.prototype.kind = function () { + return 148 /* VariableStatement */; + }; + + VariableStatementSyntax.prototype.childCount = function () { + return 3; + }; + + VariableStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.variableDeclaration; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableStatementSyntax.prototype.isStatement = function () { + return true; + }; + + VariableStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + VariableStatementSyntax.prototype.update = function (modifiers, variableDeclaration, semicolonToken) { + if (this.modifiers === modifiers && this.variableDeclaration === variableDeclaration && this.semicolonToken === semicolonToken) { + return this; + } + + return new VariableStatementSyntax(modifiers, variableDeclaration, semicolonToken, this.parsedInStrictMode()); + }; + + VariableStatementSyntax.create = function (variableDeclaration, semicolonToken) { + return new VariableStatementSyntax(TypeScript.Syntax.emptyList, variableDeclaration, semicolonToken, false); + }; + + VariableStatementSyntax.create1 = function (variableDeclaration) { + return new VariableStatementSyntax(TypeScript.Syntax.emptyList, variableDeclaration, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + VariableStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableStatementSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.variableDeclaration, this.semicolonToken); + }; + + VariableStatementSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + VariableStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.modifiers, variableDeclaration, this.semicolonToken); + }; + + VariableStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.variableDeclaration, semicolonToken); + }; + + VariableStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.childCount() > 0) { + return true; + } + if (this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableStatementSyntax = VariableStatementSyntax; + + var VariableDeclarationSyntax = (function (_super) { + __extends(VariableDeclarationSyntax, _super); + function VariableDeclarationSyntax(varKeyword, variableDeclarators, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.varKeyword = varKeyword; + this.variableDeclarators = variableDeclarators; + } + VariableDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableDeclaration(this); + }; + + VariableDeclarationSyntax.prototype.kind = function () { + return 224 /* VariableDeclaration */; + }; + + VariableDeclarationSyntax.prototype.childCount = function () { + return 2; + }; + + VariableDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.varKeyword; + case 1: + return this.variableDeclarators; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableDeclarationSyntax.prototype.update = function (varKeyword, variableDeclarators) { + if (this.varKeyword === varKeyword && this.variableDeclarators === variableDeclarators) { + return this; + } + + return new VariableDeclarationSyntax(varKeyword, variableDeclarators, this.parsedInStrictMode()); + }; + + VariableDeclarationSyntax.create1 = function (variableDeclarators) { + return new VariableDeclarationSyntax(TypeScript.Syntax.token(40 /* VarKeyword */), variableDeclarators, false); + }; + + VariableDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableDeclarationSyntax.prototype.withVarKeyword = function (varKeyword) { + return this.update(varKeyword, this.variableDeclarators); + }; + + VariableDeclarationSyntax.prototype.withVariableDeclarators = function (variableDeclarators) { + return this.update(this.varKeyword, variableDeclarators); + }; + + VariableDeclarationSyntax.prototype.withVariableDeclarator = function (variableDeclarator) { + return this.withVariableDeclarators(TypeScript.Syntax.separatedList([variableDeclarator])); + }; + + VariableDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclarators.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableDeclarationSyntax = VariableDeclarationSyntax; + + var VariableDeclaratorSyntax = (function (_super) { + __extends(VariableDeclaratorSyntax, _super); + function VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + } + VariableDeclaratorSyntax.prototype.accept = function (visitor) { + return visitor.visitVariableDeclarator(this); + }; + + VariableDeclaratorSyntax.prototype.kind = function () { + return 225 /* VariableDeclarator */; + }; + + VariableDeclaratorSyntax.prototype.childCount = function () { + return 3; + }; + + VariableDeclaratorSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.typeAnnotation; + case 2: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VariableDeclaratorSyntax.prototype.update = function (propertyName, typeAnnotation, equalsValueClause) { + if (this.propertyName === propertyName && this.typeAnnotation === typeAnnotation && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new VariableDeclaratorSyntax(propertyName, typeAnnotation, equalsValueClause, this.parsedInStrictMode()); + }; + + VariableDeclaratorSyntax.create = function (propertyName) { + return new VariableDeclaratorSyntax(propertyName, null, null, false); + }; + + VariableDeclaratorSyntax.create1 = function (propertyName) { + return new VariableDeclaratorSyntax(propertyName, null, null, false); + }; + + VariableDeclaratorSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VariableDeclaratorSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VariableDeclaratorSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.typeAnnotation, this.equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.propertyName, typeAnnotation, this.equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.propertyName, this.typeAnnotation, equalsValueClause); + }; + + VariableDeclaratorSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeAnnotation !== null) { + return true; + } + if (this.equalsValueClause !== null && this.equalsValueClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VariableDeclaratorSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VariableDeclaratorSyntax = VariableDeclaratorSyntax; + + var EqualsValueClauseSyntax = (function (_super) { + __extends(EqualsValueClauseSyntax, _super); + function EqualsValueClauseSyntax(equalsToken, value, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.equalsToken = equalsToken; + this.value = value; + } + EqualsValueClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitEqualsValueClause(this); + }; + + EqualsValueClauseSyntax.prototype.kind = function () { + return 232 /* EqualsValueClause */; + }; + + EqualsValueClauseSyntax.prototype.childCount = function () { + return 2; + }; + + EqualsValueClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.equalsToken; + case 1: + return this.value; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EqualsValueClauseSyntax.prototype.update = function (equalsToken, value) { + if (this.equalsToken === equalsToken && this.value === value) { + return this; + } + + return new EqualsValueClauseSyntax(equalsToken, value, this.parsedInStrictMode()); + }; + + EqualsValueClauseSyntax.create1 = function (value) { + return new EqualsValueClauseSyntax(TypeScript.Syntax.token(107 /* EqualsToken */), value, false); + }; + + EqualsValueClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EqualsValueClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EqualsValueClauseSyntax.prototype.withEqualsToken = function (equalsToken) { + return this.update(equalsToken, this.value); + }; + + EqualsValueClauseSyntax.prototype.withValue = function (value) { + return this.update(this.equalsToken, value); + }; + + EqualsValueClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.value.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return EqualsValueClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EqualsValueClauseSyntax = EqualsValueClauseSyntax; + + var PrefixUnaryExpressionSyntax = (function (_super) { + __extends(PrefixUnaryExpressionSyntax, _super); + function PrefixUnaryExpressionSyntax(kind, operatorToken, operand, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.operatorToken = operatorToken; + this.operand = operand; + + this._kind = kind; + } + PrefixUnaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitPrefixUnaryExpression(this); + }; + + PrefixUnaryExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + PrefixUnaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.operatorToken; + case 1: + return this.operand; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PrefixUnaryExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + PrefixUnaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + PrefixUnaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + PrefixUnaryExpressionSyntax.prototype.update = function (kind, operatorToken, operand) { + if (this._kind === kind && this.operatorToken === operatorToken && this.operand === operand) { + return this; + } + + return new PrefixUnaryExpressionSyntax(kind, operatorToken, operand, this.parsedInStrictMode()); + }; + + PrefixUnaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PrefixUnaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PrefixUnaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.operatorToken, this.operand); + }; + + PrefixUnaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, operatorToken, this.operand); + }; + + PrefixUnaryExpressionSyntax.prototype.withOperand = function (operand) { + return this.update(this._kind, this.operatorToken, operand); + }; + + PrefixUnaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.operand.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return PrefixUnaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PrefixUnaryExpressionSyntax = PrefixUnaryExpressionSyntax; + + var ArrayLiteralExpressionSyntax = (function (_super) { + __extends(ArrayLiteralExpressionSyntax, _super); + function ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBracketToken = openBracketToken; + this.expressions = expressions; + this.closeBracketToken = closeBracketToken; + } + ArrayLiteralExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitArrayLiteralExpression(this); + }; + + ArrayLiteralExpressionSyntax.prototype.kind = function () { + return 214 /* ArrayLiteralExpression */; + }; + + ArrayLiteralExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ArrayLiteralExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBracketToken; + case 1: + return this.expressions; + case 2: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArrayLiteralExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ArrayLiteralExpressionSyntax.prototype.update = function (openBracketToken, expressions, closeBracketToken) { + if (this.openBracketToken === openBracketToken && this.expressions === expressions && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ArrayLiteralExpressionSyntax(openBracketToken, expressions, closeBracketToken, this.parsedInStrictMode()); + }; + + ArrayLiteralExpressionSyntax.create = function (openBracketToken, closeBracketToken) { + return new ArrayLiteralExpressionSyntax(openBracketToken, TypeScript.Syntax.emptySeparatedList, closeBracketToken, false); + }; + + ArrayLiteralExpressionSyntax.create1 = function () { + return new ArrayLiteralExpressionSyntax(TypeScript.Syntax.token(74 /* OpenBracketToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(75 /* CloseBracketToken */), false); + }; + + ArrayLiteralExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArrayLiteralExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArrayLiteralExpressionSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(openBracketToken, this.expressions, this.closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.withExpressions = function (expressions) { + return this.update(this.openBracketToken, expressions, this.closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.withExpression = function (expression) { + return this.withExpressions(TypeScript.Syntax.separatedList([expression])); + }; + + ArrayLiteralExpressionSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.openBracketToken, this.expressions, closeBracketToken); + }; + + ArrayLiteralExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expressions.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ArrayLiteralExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArrayLiteralExpressionSyntax = ArrayLiteralExpressionSyntax; + + var OmittedExpressionSyntax = (function (_super) { + __extends(OmittedExpressionSyntax, _super); + function OmittedExpressionSyntax(parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + } + OmittedExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitOmittedExpression(this); + }; + + OmittedExpressionSyntax.prototype.kind = function () { + return 223 /* OmittedExpression */; + }; + + OmittedExpressionSyntax.prototype.childCount = function () { + return 0; + }; + + OmittedExpressionSyntax.prototype.childAt = function (slot) { + throw TypeScript.Errors.invalidOperation(); + }; + + OmittedExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + OmittedExpressionSyntax.prototype.update = function () { + return this; + }; + + OmittedExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + OmittedExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + OmittedExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return OmittedExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.OmittedExpressionSyntax = OmittedExpressionSyntax; + + var ParenthesizedExpressionSyntax = (function (_super) { + __extends(ParenthesizedExpressionSyntax, _super); + function ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openParenToken = openParenToken; + this.expression = expression; + this.closeParenToken = closeParenToken; + } + ParenthesizedExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitParenthesizedExpression(this); + }; + + ParenthesizedExpressionSyntax.prototype.kind = function () { + return 217 /* ParenthesizedExpression */; + }; + + ParenthesizedExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ParenthesizedExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openParenToken; + case 1: + return this.expression; + case 2: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParenthesizedExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ParenthesizedExpressionSyntax.prototype.update = function (openParenToken, expression, closeParenToken) { + if (this.openParenToken === openParenToken && this.expression === expression && this.closeParenToken === closeParenToken) { + return this; + } + + return new ParenthesizedExpressionSyntax(openParenToken, expression, closeParenToken, this.parsedInStrictMode()); + }; + + ParenthesizedExpressionSyntax.create1 = function (expression) { + return new ParenthesizedExpressionSyntax(TypeScript.Syntax.token(72 /* OpenParenToken */), expression, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ParenthesizedExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParenthesizedExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParenthesizedExpressionSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(openParenToken, this.expression, this.closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.openParenToken, expression, this.closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.openParenToken, this.expression, closeParenToken); + }; + + ParenthesizedExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ParenthesizedExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParenthesizedExpressionSyntax = ParenthesizedExpressionSyntax; + + var SimpleArrowFunctionExpressionSyntax = (function (_super) { + __extends(SimpleArrowFunctionExpressionSyntax, _super); + function SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.block = block; + this.expression = expression; + } + SimpleArrowFunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitSimpleArrowFunctionExpression(this); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.kind = function () { + return 219 /* SimpleArrowFunctionExpression */; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.equalsGreaterThanToken; + case 2: + return this.block; + case 3: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isArrowFunctionExpression = function () { + return true; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + SimpleArrowFunctionExpressionSyntax.prototype.update = function (identifier, equalsGreaterThanToken, block, expression) { + if (this.identifier === identifier && this.equalsGreaterThanToken === equalsGreaterThanToken && this.block === block && this.expression === expression) { + return this; + } + + return new SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, block, expression, this.parsedInStrictMode()); + }; + + SimpleArrowFunctionExpressionSyntax.create = function (identifier, equalsGreaterThanToken) { + return new SimpleArrowFunctionExpressionSyntax(identifier, equalsGreaterThanToken, null, null, false); + }; + + SimpleArrowFunctionExpressionSyntax.create1 = function (identifier) { + return new SimpleArrowFunctionExpressionSyntax(identifier, TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), null, null, false); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.equalsGreaterThanToken, this.block, this.expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.identifier, equalsGreaterThanToken, this.block, this.expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withBlock = function (block) { + return this.update(this.identifier, this.equalsGreaterThanToken, block, this.expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.identifier, this.equalsGreaterThanToken, this.block, expression); + }; + + SimpleArrowFunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return SimpleArrowFunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SimpleArrowFunctionExpressionSyntax = SimpleArrowFunctionExpressionSyntax; + + var ParenthesizedArrowFunctionExpressionSyntax = (function (_super) { + __extends(ParenthesizedArrowFunctionExpressionSyntax, _super); + function ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.callSignature = callSignature; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.block = block; + this.expression = expression; + } + ParenthesizedArrowFunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitParenthesizedArrowFunctionExpression(this); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.kind = function () { + return 218 /* ParenthesizedArrowFunctionExpression */; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.callSignature; + case 1: + return this.equalsGreaterThanToken; + case 2: + return this.block; + case 3: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isArrowFunctionExpression = function () { + return true; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.update = function (callSignature, equalsGreaterThanToken, block, expression) { + if (this.callSignature === callSignature && this.equalsGreaterThanToken === equalsGreaterThanToken && this.block === block && this.expression === expression) { + return this; + } + + return new ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, block, expression, this.parsedInStrictMode()); + }; + + ParenthesizedArrowFunctionExpressionSyntax.create = function (callSignature, equalsGreaterThanToken) { + return new ParenthesizedArrowFunctionExpressionSyntax(callSignature, equalsGreaterThanToken, null, null, false); + }; + + ParenthesizedArrowFunctionExpressionSyntax.create1 = function () { + return new ParenthesizedArrowFunctionExpressionSyntax(CallSignatureSyntax.create1(), TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), null, null, false); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(callSignature, this.equalsGreaterThanToken, this.block, this.expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.callSignature, equalsGreaterThanToken, this.block, this.expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withBlock = function (block) { + return this.update(this.callSignature, this.equalsGreaterThanToken, block, this.expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.callSignature, this.equalsGreaterThanToken, this.block, expression); + }; + + ParenthesizedArrowFunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ParenthesizedArrowFunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParenthesizedArrowFunctionExpressionSyntax = ParenthesizedArrowFunctionExpressionSyntax; + + var QualifiedNameSyntax = (function (_super) { + __extends(QualifiedNameSyntax, _super); + function QualifiedNameSyntax(left, dotToken, right, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.left = left; + this.dotToken = dotToken; + this.right = right; + } + QualifiedNameSyntax.prototype.accept = function (visitor) { + return visitor.visitQualifiedName(this); + }; + + QualifiedNameSyntax.prototype.kind = function () { + return 121 /* QualifiedName */; + }; + + QualifiedNameSyntax.prototype.childCount = function () { + return 3; + }; + + QualifiedNameSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.left; + case 1: + return this.dotToken; + case 2: + return this.right; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + QualifiedNameSyntax.prototype.isName = function () { + return true; + }; + + QualifiedNameSyntax.prototype.isType = function () { + return true; + }; + + QualifiedNameSyntax.prototype.update = function (left, dotToken, right) { + if (this.left === left && this.dotToken === dotToken && this.right === right) { + return this; + } + + return new QualifiedNameSyntax(left, dotToken, right, this.parsedInStrictMode()); + }; + + QualifiedNameSyntax.create1 = function (left, right) { + return new QualifiedNameSyntax(left, TypeScript.Syntax.token(76 /* DotToken */), right, false); + }; + + QualifiedNameSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + QualifiedNameSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + QualifiedNameSyntax.prototype.withLeft = function (left) { + return this.update(left, this.dotToken, this.right); + }; + + QualifiedNameSyntax.prototype.withDotToken = function (dotToken) { + return this.update(this.left, dotToken, this.right); + }; + + QualifiedNameSyntax.prototype.withRight = function (right) { + return this.update(this.left, this.dotToken, right); + }; + + QualifiedNameSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return QualifiedNameSyntax; + })(TypeScript.SyntaxNode); + TypeScript.QualifiedNameSyntax = QualifiedNameSyntax; + + var TypeArgumentListSyntax = (function (_super) { + __extends(TypeArgumentListSyntax, _super); + function TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.typeArguments = typeArguments; + this.greaterThanToken = greaterThanToken; + } + TypeArgumentListSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeArgumentList(this); + }; + + TypeArgumentListSyntax.prototype.kind = function () { + return 228 /* TypeArgumentList */; + }; + + TypeArgumentListSyntax.prototype.childCount = function () { + return 3; + }; + + TypeArgumentListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.typeArguments; + case 2: + return this.greaterThanToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeArgumentListSyntax.prototype.update = function (lessThanToken, typeArguments, greaterThanToken) { + if (this.lessThanToken === lessThanToken && this.typeArguments === typeArguments && this.greaterThanToken === greaterThanToken) { + return this; + } + + return new TypeArgumentListSyntax(lessThanToken, typeArguments, greaterThanToken, this.parsedInStrictMode()); + }; + + TypeArgumentListSyntax.create = function (lessThanToken, greaterThanToken) { + return new TypeArgumentListSyntax(lessThanToken, TypeScript.Syntax.emptySeparatedList, greaterThanToken, false); + }; + + TypeArgumentListSyntax.create1 = function () { + return new TypeArgumentListSyntax(TypeScript.Syntax.token(80 /* LessThanToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(81 /* GreaterThanToken */), false); + }; + + TypeArgumentListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeArgumentListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeArgumentListSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.typeArguments, this.greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.withTypeArguments = function (typeArguments) { + return this.update(this.lessThanToken, typeArguments, this.greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.withTypeArgument = function (typeArgument) { + return this.withTypeArguments(TypeScript.Syntax.separatedList([typeArgument])); + }; + + TypeArgumentListSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.typeArguments, greaterThanToken); + }; + + TypeArgumentListSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeArgumentListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeArgumentListSyntax = TypeArgumentListSyntax; + + var ConstructorTypeSyntax = (function (_super) { + __extends(ConstructorTypeSyntax, _super); + function ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.type = type; + } + ConstructorTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructorType(this); + }; + + ConstructorTypeSyntax.prototype.kind = function () { + return 125 /* ConstructorType */; + }; + + ConstructorTypeSyntax.prototype.childCount = function () { + return 5; + }; + + ConstructorTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.typeParameterList; + case 2: + return this.parameterList; + case 3: + return this.equalsGreaterThanToken; + case 4: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructorTypeSyntax.prototype.isType = function () { + return true; + }; + + ConstructorTypeSyntax.prototype.update = function (newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type) { + if (this.newKeyword === newKeyword && this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.equalsGreaterThanToken === equalsGreaterThanToken && this.type === type) { + return this; + } + + return new ConstructorTypeSyntax(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type, this.parsedInStrictMode()); + }; + + ConstructorTypeSyntax.create = function (newKeyword, parameterList, equalsGreaterThanToken, type) { + return new ConstructorTypeSyntax(newKeyword, null, parameterList, equalsGreaterThanToken, type, false); + }; + + ConstructorTypeSyntax.create1 = function (type) { + return new ConstructorTypeSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), null, ParameterListSyntax.create1(), TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), type, false); + }; + + ConstructorTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructorTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructorTypeSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(this.newKeyword, typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.newKeyword, this.typeParameterList, parameterList, this.equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.newKeyword, this.typeParameterList, this.parameterList, equalsGreaterThanToken, this.type); + }; + + ConstructorTypeSyntax.prototype.withType = function (type) { + return this.update(this.newKeyword, this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, type); + }; + + ConstructorTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructorTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructorTypeSyntax = ConstructorTypeSyntax; + + var FunctionTypeSyntax = (function (_super) { + __extends(FunctionTypeSyntax, _super); + function FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.equalsGreaterThanToken = equalsGreaterThanToken; + this.type = type; + } + FunctionTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionType(this); + }; + + FunctionTypeSyntax.prototype.kind = function () { + return 123 /* FunctionType */; + }; + + FunctionTypeSyntax.prototype.childCount = function () { + return 4; + }; + + FunctionTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeParameterList; + case 1: + return this.parameterList; + case 2: + return this.equalsGreaterThanToken; + case 3: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionTypeSyntax.prototype.isType = function () { + return true; + }; + + FunctionTypeSyntax.prototype.update = function (typeParameterList, parameterList, equalsGreaterThanToken, type) { + if (this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.equalsGreaterThanToken === equalsGreaterThanToken && this.type === type) { + return this; + } + + return new FunctionTypeSyntax(typeParameterList, parameterList, equalsGreaterThanToken, type, this.parsedInStrictMode()); + }; + + FunctionTypeSyntax.create = function (parameterList, equalsGreaterThanToken, type) { + return new FunctionTypeSyntax(null, parameterList, equalsGreaterThanToken, type, false); + }; + + FunctionTypeSyntax.create1 = function (type) { + return new FunctionTypeSyntax(null, ParameterListSyntax.create1(), TypeScript.Syntax.token(85 /* EqualsGreaterThanToken */), type, false); + }; + + FunctionTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionTypeSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(typeParameterList, this.parameterList, this.equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.typeParameterList, parameterList, this.equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withEqualsGreaterThanToken = function (equalsGreaterThanToken) { + return this.update(this.typeParameterList, this.parameterList, equalsGreaterThanToken, this.type); + }; + + FunctionTypeSyntax.prototype.withType = function (type) { + return this.update(this.typeParameterList, this.parameterList, this.equalsGreaterThanToken, type); + }; + + FunctionTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return FunctionTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionTypeSyntax = FunctionTypeSyntax; + + var ObjectTypeSyntax = (function (_super) { + __extends(ObjectTypeSyntax, _super); + function ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.typeMembers = typeMembers; + this.closeBraceToken = closeBraceToken; + } + ObjectTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectType(this); + }; + + ObjectTypeSyntax.prototype.kind = function () { + return 122 /* ObjectType */; + }; + + ObjectTypeSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.typeMembers; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectTypeSyntax.prototype.isType = function () { + return true; + }; + + ObjectTypeSyntax.prototype.update = function (openBraceToken, typeMembers, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.typeMembers === typeMembers && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ObjectTypeSyntax(openBraceToken, typeMembers, closeBraceToken, this.parsedInStrictMode()); + }; + + ObjectTypeSyntax.create = function (openBraceToken, closeBraceToken) { + return new ObjectTypeSyntax(openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + ObjectTypeSyntax.create1 = function () { + return new ObjectTypeSyntax(TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ObjectTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectTypeSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.typeMembers, this.closeBraceToken); + }; + + ObjectTypeSyntax.prototype.withTypeMembers = function (typeMembers) { + return this.update(this.openBraceToken, typeMembers, this.closeBraceToken); + }; + + ObjectTypeSyntax.prototype.withTypeMember = function (typeMember) { + return this.withTypeMembers(TypeScript.Syntax.separatedList([typeMember])); + }; + + ObjectTypeSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.typeMembers, closeBraceToken); + }; + + ObjectTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ObjectTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectTypeSyntax = ObjectTypeSyntax; + + var ArrayTypeSyntax = (function (_super) { + __extends(ArrayTypeSyntax, _super); + function ArrayTypeSyntax(type, openBracketToken, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.type = type; + this.openBracketToken = openBracketToken; + this.closeBracketToken = closeBracketToken; + } + ArrayTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitArrayType(this); + }; + + ArrayTypeSyntax.prototype.kind = function () { + return 124 /* ArrayType */; + }; + + ArrayTypeSyntax.prototype.childCount = function () { + return 3; + }; + + ArrayTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.type; + case 1: + return this.openBracketToken; + case 2: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArrayTypeSyntax.prototype.isType = function () { + return true; + }; + + ArrayTypeSyntax.prototype.update = function (type, openBracketToken, closeBracketToken) { + if (this.type === type && this.openBracketToken === openBracketToken && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ArrayTypeSyntax(type, openBracketToken, closeBracketToken, this.parsedInStrictMode()); + }; + + ArrayTypeSyntax.create1 = function (type) { + return new ArrayTypeSyntax(type, TypeScript.Syntax.token(74 /* OpenBracketToken */), TypeScript.Syntax.token(75 /* CloseBracketToken */), false); + }; + + ArrayTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArrayTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArrayTypeSyntax.prototype.withType = function (type) { + return this.update(type, this.openBracketToken, this.closeBracketToken); + }; + + ArrayTypeSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(this.type, openBracketToken, this.closeBracketToken); + }; + + ArrayTypeSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.type, this.openBracketToken, closeBracketToken); + }; + + ArrayTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ArrayTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArrayTypeSyntax = ArrayTypeSyntax; + + var GenericTypeSyntax = (function (_super) { + __extends(GenericTypeSyntax, _super); + function GenericTypeSyntax(name, typeArgumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.name = name; + this.typeArgumentList = typeArgumentList; + } + GenericTypeSyntax.prototype.accept = function (visitor) { + return visitor.visitGenericType(this); + }; + + GenericTypeSyntax.prototype.kind = function () { + return 126 /* GenericType */; + }; + + GenericTypeSyntax.prototype.childCount = function () { + return 2; + }; + + GenericTypeSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.name; + case 1: + return this.typeArgumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + GenericTypeSyntax.prototype.isType = function () { + return true; + }; + + GenericTypeSyntax.prototype.update = function (name, typeArgumentList) { + if (this.name === name && this.typeArgumentList === typeArgumentList) { + return this; + } + + return new GenericTypeSyntax(name, typeArgumentList, this.parsedInStrictMode()); + }; + + GenericTypeSyntax.create1 = function (name) { + return new GenericTypeSyntax(name, TypeArgumentListSyntax.create1(), false); + }; + + GenericTypeSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + GenericTypeSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + GenericTypeSyntax.prototype.withName = function (name) { + return this.update(name, this.typeArgumentList); + }; + + GenericTypeSyntax.prototype.withTypeArgumentList = function (typeArgumentList) { + return this.update(this.name, typeArgumentList); + }; + + GenericTypeSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return GenericTypeSyntax; + })(TypeScript.SyntaxNode); + TypeScript.GenericTypeSyntax = GenericTypeSyntax; + + var TypeQuerySyntax = (function (_super) { + __extends(TypeQuerySyntax, _super); + function TypeQuerySyntax(typeOfKeyword, name, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeOfKeyword = typeOfKeyword; + this.name = name; + } + TypeQuerySyntax.prototype.accept = function (visitor) { + return visitor.visitTypeQuery(this); + }; + + TypeQuerySyntax.prototype.kind = function () { + return 127 /* TypeQuery */; + }; + + TypeQuerySyntax.prototype.childCount = function () { + return 2; + }; + + TypeQuerySyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeOfKeyword; + case 1: + return this.name; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeQuerySyntax.prototype.isType = function () { + return true; + }; + + TypeQuerySyntax.prototype.update = function (typeOfKeyword, name) { + if (this.typeOfKeyword === typeOfKeyword && this.name === name) { + return this; + } + + return new TypeQuerySyntax(typeOfKeyword, name, this.parsedInStrictMode()); + }; + + TypeQuerySyntax.create1 = function (name) { + return new TypeQuerySyntax(TypeScript.Syntax.token(39 /* TypeOfKeyword */), name, false); + }; + + TypeQuerySyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeQuerySyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeQuerySyntax.prototype.withTypeOfKeyword = function (typeOfKeyword) { + return this.update(typeOfKeyword, this.name); + }; + + TypeQuerySyntax.prototype.withName = function (name) { + return this.update(this.typeOfKeyword, name); + }; + + TypeQuerySyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeQuerySyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeQuerySyntax = TypeQuerySyntax; + + var TypeAnnotationSyntax = (function (_super) { + __extends(TypeAnnotationSyntax, _super); + function TypeAnnotationSyntax(colonToken, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.colonToken = colonToken; + this.type = type; + } + TypeAnnotationSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeAnnotation(this); + }; + + TypeAnnotationSyntax.prototype.kind = function () { + return 244 /* TypeAnnotation */; + }; + + TypeAnnotationSyntax.prototype.childCount = function () { + return 2; + }; + + TypeAnnotationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.colonToken; + case 1: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeAnnotationSyntax.prototype.update = function (colonToken, type) { + if (this.colonToken === colonToken && this.type === type) { + return this; + } + + return new TypeAnnotationSyntax(colonToken, type, this.parsedInStrictMode()); + }; + + TypeAnnotationSyntax.create1 = function (type) { + return new TypeAnnotationSyntax(TypeScript.Syntax.token(106 /* ColonToken */), type, false); + }; + + TypeAnnotationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeAnnotationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeAnnotationSyntax.prototype.withColonToken = function (colonToken) { + return this.update(colonToken, this.type); + }; + + TypeAnnotationSyntax.prototype.withType = function (type) { + return this.update(this.colonToken, type); + }; + + TypeAnnotationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeAnnotationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeAnnotationSyntax = TypeAnnotationSyntax; + + var BlockSyntax = (function (_super) { + __extends(BlockSyntax, _super); + function BlockSyntax(openBraceToken, statements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.statements = statements; + this.closeBraceToken = closeBraceToken; + } + BlockSyntax.prototype.accept = function (visitor) { + return visitor.visitBlock(this); + }; + + BlockSyntax.prototype.kind = function () { + return 146 /* Block */; + }; + + BlockSyntax.prototype.childCount = function () { + return 3; + }; + + BlockSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.statements; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BlockSyntax.prototype.isStatement = function () { + return true; + }; + + BlockSyntax.prototype.isModuleElement = function () { + return true; + }; + + BlockSyntax.prototype.update = function (openBraceToken, statements, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.statements === statements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new BlockSyntax(openBraceToken, statements, closeBraceToken, this.parsedInStrictMode()); + }; + + BlockSyntax.create = function (openBraceToken, closeBraceToken) { + return new BlockSyntax(openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + BlockSyntax.create1 = function () { + return new BlockSyntax(TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + BlockSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BlockSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BlockSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.statements, this.closeBraceToken); + }; + + BlockSyntax.prototype.withStatements = function (statements) { + return this.update(this.openBraceToken, statements, this.closeBraceToken); + }; + + BlockSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + BlockSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.statements, closeBraceToken); + }; + + BlockSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return BlockSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BlockSyntax = BlockSyntax; + + var ParameterSyntax = (function (_super) { + __extends(ParameterSyntax, _super); + function ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.dotDotDotToken = dotDotDotToken; + this.modifiers = modifiers; + this.identifier = identifier; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + } + ParameterSyntax.prototype.accept = function (visitor) { + return visitor.visitParameter(this); + }; + + ParameterSyntax.prototype.kind = function () { + return 242 /* Parameter */; + }; + + ParameterSyntax.prototype.childCount = function () { + return 6; + }; + + ParameterSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.dotDotDotToken; + case 1: + return this.modifiers; + case 2: + return this.identifier; + case 3: + return this.questionToken; + case 4: + return this.typeAnnotation; + case 5: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParameterSyntax.prototype.update = function (dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + if (this.dotDotDotToken === dotDotDotToken && this.modifiers === modifiers && this.identifier === identifier && this.questionToken === questionToken && this.typeAnnotation === typeAnnotation && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new ParameterSyntax(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause, this.parsedInStrictMode()); + }; + + ParameterSyntax.create = function (identifier) { + return new ParameterSyntax(null, TypeScript.Syntax.emptyList, identifier, null, null, null, false); + }; + + ParameterSyntax.create1 = function (identifier) { + return new ParameterSyntax(null, TypeScript.Syntax.emptyList, identifier, null, null, null, false); + }; + + ParameterSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParameterSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParameterSyntax.prototype.withDotDotDotToken = function (dotDotDotToken) { + return this.update(dotDotDotToken, this.modifiers, this.identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withModifiers = function (modifiers) { + return this.update(this.dotDotDotToken, modifiers, this.identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ParameterSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.dotDotDotToken, this.modifiers, identifier, this.questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.dotDotDotToken, this.modifiers, this.identifier, questionToken, this.typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.dotDotDotToken, this.modifiers, this.identifier, this.questionToken, typeAnnotation, this.equalsValueClause); + }; + + ParameterSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.dotDotDotToken, this.modifiers, this.identifier, this.questionToken, this.typeAnnotation, equalsValueClause); + }; + + ParameterSyntax.prototype.isTypeScriptSpecific = function () { + if (this.dotDotDotToken !== null) { + return true; + } + if (this.modifiers.isTypeScriptSpecific()) { + return true; + } + if (this.questionToken !== null) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + if (this.equalsValueClause !== null) { + return true; + } + return false; + }; + return ParameterSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParameterSyntax = ParameterSyntax; + + var MemberAccessExpressionSyntax = (function (_super) { + __extends(MemberAccessExpressionSyntax, _super); + function MemberAccessExpressionSyntax(expression, dotToken, name, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.dotToken = dotToken; + this.name = name; + } + MemberAccessExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberAccessExpression(this); + }; + + MemberAccessExpressionSyntax.prototype.kind = function () { + return 212 /* MemberAccessExpression */; + }; + + MemberAccessExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + MemberAccessExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.dotToken; + case 2: + return this.name; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberAccessExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + MemberAccessExpressionSyntax.prototype.update = function (expression, dotToken, name) { + if (this.expression === expression && this.dotToken === dotToken && this.name === name) { + return this; + } + + return new MemberAccessExpressionSyntax(expression, dotToken, name, this.parsedInStrictMode()); + }; + + MemberAccessExpressionSyntax.create1 = function (expression, name) { + return new MemberAccessExpressionSyntax(expression, TypeScript.Syntax.token(76 /* DotToken */), name, false); + }; + + MemberAccessExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberAccessExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberAccessExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.dotToken, this.name); + }; + + MemberAccessExpressionSyntax.prototype.withDotToken = function (dotToken) { + return this.update(this.expression, dotToken, this.name); + }; + + MemberAccessExpressionSyntax.prototype.withName = function (name) { + return this.update(this.expression, this.dotToken, name); + }; + + MemberAccessExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return MemberAccessExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberAccessExpressionSyntax = MemberAccessExpressionSyntax; + + var PostfixUnaryExpressionSyntax = (function (_super) { + __extends(PostfixUnaryExpressionSyntax, _super); + function PostfixUnaryExpressionSyntax(kind, operand, operatorToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.operand = operand; + this.operatorToken = operatorToken; + + this._kind = kind; + } + PostfixUnaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitPostfixUnaryExpression(this); + }; + + PostfixUnaryExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + PostfixUnaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.operand; + case 1: + return this.operatorToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PostfixUnaryExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + PostfixUnaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + PostfixUnaryExpressionSyntax.prototype.update = function (kind, operand, operatorToken) { + if (this._kind === kind && this.operand === operand && this.operatorToken === operatorToken) { + return this; + } + + return new PostfixUnaryExpressionSyntax(kind, operand, operatorToken, this.parsedInStrictMode()); + }; + + PostfixUnaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PostfixUnaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PostfixUnaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.operand, this.operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.withOperand = function (operand) { + return this.update(this._kind, operand, this.operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, this.operand, operatorToken); + }; + + PostfixUnaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.operand.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return PostfixUnaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PostfixUnaryExpressionSyntax = PostfixUnaryExpressionSyntax; + + var ElementAccessExpressionSyntax = (function (_super) { + __extends(ElementAccessExpressionSyntax, _super); + function ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.openBracketToken = openBracketToken; + this.argumentExpression = argumentExpression; + this.closeBracketToken = closeBracketToken; + } + ElementAccessExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitElementAccessExpression(this); + }; + + ElementAccessExpressionSyntax.prototype.kind = function () { + return 221 /* ElementAccessExpression */; + }; + + ElementAccessExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + ElementAccessExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.openBracketToken; + case 2: + return this.argumentExpression; + case 3: + return this.closeBracketToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ElementAccessExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ElementAccessExpressionSyntax.prototype.update = function (expression, openBracketToken, argumentExpression, closeBracketToken) { + if (this.expression === expression && this.openBracketToken === openBracketToken && this.argumentExpression === argumentExpression && this.closeBracketToken === closeBracketToken) { + return this; + } + + return new ElementAccessExpressionSyntax(expression, openBracketToken, argumentExpression, closeBracketToken, this.parsedInStrictMode()); + }; + + ElementAccessExpressionSyntax.create1 = function (expression, argumentExpression) { + return new ElementAccessExpressionSyntax(expression, TypeScript.Syntax.token(74 /* OpenBracketToken */), argumentExpression, TypeScript.Syntax.token(75 /* CloseBracketToken */), false); + }; + + ElementAccessExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ElementAccessExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ElementAccessExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.openBracketToken, this.argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(this.expression, openBracketToken, this.argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withArgumentExpression = function (argumentExpression) { + return this.update(this.expression, this.openBracketToken, argumentExpression, this.closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.expression, this.openBracketToken, this.argumentExpression, closeBracketToken); + }; + + ElementAccessExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentExpression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ElementAccessExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ElementAccessExpressionSyntax = ElementAccessExpressionSyntax; + + var InvocationExpressionSyntax = (function (_super) { + __extends(InvocationExpressionSyntax, _super); + function InvocationExpressionSyntax(expression, argumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.argumentList = argumentList; + } + InvocationExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitInvocationExpression(this); + }; + + InvocationExpressionSyntax.prototype.kind = function () { + return 213 /* InvocationExpression */; + }; + + InvocationExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + InvocationExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.argumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + InvocationExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + InvocationExpressionSyntax.prototype.update = function (expression, argumentList) { + if (this.expression === expression && this.argumentList === argumentList) { + return this; + } + + return new InvocationExpressionSyntax(expression, argumentList, this.parsedInStrictMode()); + }; + + InvocationExpressionSyntax.create1 = function (expression) { + return new InvocationExpressionSyntax(expression, ArgumentListSyntax.create1(), false); + }; + + InvocationExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + InvocationExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + InvocationExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.argumentList); + }; + + InvocationExpressionSyntax.prototype.withArgumentList = function (argumentList) { + return this.update(this.expression, argumentList); + }; + + InvocationExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentList.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return InvocationExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.InvocationExpressionSyntax = InvocationExpressionSyntax; + + var ArgumentListSyntax = (function (_super) { + __extends(ArgumentListSyntax, _super); + function ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeArgumentList = typeArgumentList; + this.openParenToken = openParenToken; + this.closeParenToken = closeParenToken; + + this.arguments = _arguments; + } + ArgumentListSyntax.prototype.accept = function (visitor) { + return visitor.visitArgumentList(this); + }; + + ArgumentListSyntax.prototype.kind = function () { + return 226 /* ArgumentList */; + }; + + ArgumentListSyntax.prototype.childCount = function () { + return 4; + }; + + ArgumentListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeArgumentList; + case 1: + return this.openParenToken; + case 2: + return this.arguments; + case 3: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ArgumentListSyntax.prototype.update = function (typeArgumentList, openParenToken, _arguments, closeParenToken) { + if (this.typeArgumentList === typeArgumentList && this.openParenToken === openParenToken && this.arguments === _arguments && this.closeParenToken === closeParenToken) { + return this; + } + + return new ArgumentListSyntax(typeArgumentList, openParenToken, _arguments, closeParenToken, this.parsedInStrictMode()); + }; + + ArgumentListSyntax.create = function (openParenToken, closeParenToken) { + return new ArgumentListSyntax(null, openParenToken, TypeScript.Syntax.emptySeparatedList, closeParenToken, false); + }; + + ArgumentListSyntax.create1 = function () { + return new ArgumentListSyntax(null, TypeScript.Syntax.token(72 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ArgumentListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ArgumentListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ArgumentListSyntax.prototype.withTypeArgumentList = function (typeArgumentList) { + return this.update(typeArgumentList, this.openParenToken, this.arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.typeArgumentList, openParenToken, this.arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withArguments = function (_arguments) { + return this.update(this.typeArgumentList, this.openParenToken, _arguments, this.closeParenToken); + }; + + ArgumentListSyntax.prototype.withArgument = function (_argument) { + return this.withArguments(TypeScript.Syntax.separatedList([_argument])); + }; + + ArgumentListSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.typeArgumentList, this.openParenToken, this.arguments, closeParenToken); + }; + + ArgumentListSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeArgumentList !== null && this.typeArgumentList.isTypeScriptSpecific()) { + return true; + } + if (this.arguments.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ArgumentListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ArgumentListSyntax = ArgumentListSyntax; + + var BinaryExpressionSyntax = (function (_super) { + __extends(BinaryExpressionSyntax, _super); + function BinaryExpressionSyntax(kind, left, operatorToken, right, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.left = left; + this.operatorToken = operatorToken; + this.right = right; + + this._kind = kind; + } + BinaryExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitBinaryExpression(this); + }; + + BinaryExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + BinaryExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.left; + case 1: + return this.operatorToken; + case 2: + return this.right; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BinaryExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + BinaryExpressionSyntax.prototype.kind = function () { + return this._kind; + }; + + BinaryExpressionSyntax.prototype.update = function (kind, left, operatorToken, right) { + if (this._kind === kind && this.left === left && this.operatorToken === operatorToken && this.right === right) { + return this; + } + + return new BinaryExpressionSyntax(kind, left, operatorToken, right, this.parsedInStrictMode()); + }; + + BinaryExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BinaryExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BinaryExpressionSyntax.prototype.withKind = function (kind) { + return this.update(kind, this.left, this.operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withLeft = function (left) { + return this.update(this._kind, left, this.operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withOperatorToken = function (operatorToken) { + return this.update(this._kind, this.left, operatorToken, this.right); + }; + + BinaryExpressionSyntax.prototype.withRight = function (right) { + return this.update(this._kind, this.left, this.operatorToken, right); + }; + + BinaryExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.left.isTypeScriptSpecific()) { + return true; + } + if (this.right.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return BinaryExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BinaryExpressionSyntax = BinaryExpressionSyntax; + + var ConditionalExpressionSyntax = (function (_super) { + __extends(ConditionalExpressionSyntax, _super); + function ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.condition = condition; + this.questionToken = questionToken; + this.whenTrue = whenTrue; + this.colonToken = colonToken; + this.whenFalse = whenFalse; + } + ConditionalExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitConditionalExpression(this); + }; + + ConditionalExpressionSyntax.prototype.kind = function () { + return 186 /* ConditionalExpression */; + }; + + ConditionalExpressionSyntax.prototype.childCount = function () { + return 5; + }; + + ConditionalExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.condition; + case 1: + return this.questionToken; + case 2: + return this.whenTrue; + case 3: + return this.colonToken; + case 4: + return this.whenFalse; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConditionalExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ConditionalExpressionSyntax.prototype.update = function (condition, questionToken, whenTrue, colonToken, whenFalse) { + if (this.condition === condition && this.questionToken === questionToken && this.whenTrue === whenTrue && this.colonToken === colonToken && this.whenFalse === whenFalse) { + return this; + } + + return new ConditionalExpressionSyntax(condition, questionToken, whenTrue, colonToken, whenFalse, this.parsedInStrictMode()); + }; + + ConditionalExpressionSyntax.create1 = function (condition, whenTrue, whenFalse) { + return new ConditionalExpressionSyntax(condition, TypeScript.Syntax.token(105 /* QuestionToken */), whenTrue, TypeScript.Syntax.token(106 /* ColonToken */), whenFalse, false); + }; + + ConditionalExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConditionalExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConditionalExpressionSyntax.prototype.withCondition = function (condition) { + return this.update(condition, this.questionToken, this.whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.condition, questionToken, this.whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withWhenTrue = function (whenTrue) { + return this.update(this.condition, this.questionToken, whenTrue, this.colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.condition, this.questionToken, this.whenTrue, colonToken, this.whenFalse); + }; + + ConditionalExpressionSyntax.prototype.withWhenFalse = function (whenFalse) { + return this.update(this.condition, this.questionToken, this.whenTrue, this.colonToken, whenFalse); + }; + + ConditionalExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.whenTrue.isTypeScriptSpecific()) { + return true; + } + if (this.whenFalse.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ConditionalExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConditionalExpressionSyntax = ConditionalExpressionSyntax; + + var ConstructSignatureSyntax = (function (_super) { + __extends(ConstructSignatureSyntax, _super); + function ConstructSignatureSyntax(newKeyword, callSignature, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.callSignature = callSignature; + } + ConstructSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructSignature(this); + }; + + ConstructSignatureSyntax.prototype.kind = function () { + return 143 /* ConstructSignature */; + }; + + ConstructSignatureSyntax.prototype.childCount = function () { + return 2; + }; + + ConstructSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.callSignature; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + ConstructSignatureSyntax.prototype.update = function (newKeyword, callSignature) { + if (this.newKeyword === newKeyword && this.callSignature === callSignature) { + return this; + } + + return new ConstructSignatureSyntax(newKeyword, callSignature, this.parsedInStrictMode()); + }; + + ConstructSignatureSyntax.create1 = function () { + return new ConstructSignatureSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), CallSignatureSyntax.create1(), false); + }; + + ConstructSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructSignatureSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.callSignature); + }; + + ConstructSignatureSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.newKeyword, callSignature); + }; + + ConstructSignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructSignatureSyntax = ConstructSignatureSyntax; + + var MethodSignatureSyntax = (function (_super) { + __extends(MethodSignatureSyntax, _super); + function MethodSignatureSyntax(propertyName, questionToken, callSignature, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.callSignature = callSignature; + } + MethodSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitMethodSignature(this); + }; + + MethodSignatureSyntax.prototype.kind = function () { + return 145 /* MethodSignature */; + }; + + MethodSignatureSyntax.prototype.childCount = function () { + return 3; + }; + + MethodSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.questionToken; + case 2: + return this.callSignature; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MethodSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + MethodSignatureSyntax.prototype.update = function (propertyName, questionToken, callSignature) { + if (this.propertyName === propertyName && this.questionToken === questionToken && this.callSignature === callSignature) { + return this; + } + + return new MethodSignatureSyntax(propertyName, questionToken, callSignature, this.parsedInStrictMode()); + }; + + MethodSignatureSyntax.create = function (propertyName, callSignature) { + return new MethodSignatureSyntax(propertyName, null, callSignature, false); + }; + + MethodSignatureSyntax.create1 = function (propertyName) { + return new MethodSignatureSyntax(propertyName, null, CallSignatureSyntax.create1(), false); + }; + + MethodSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MethodSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MethodSignatureSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.questionToken, this.callSignature); + }; + + MethodSignatureSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.propertyName, questionToken, this.callSignature); + }; + + MethodSignatureSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.propertyName, this.questionToken, callSignature); + }; + + MethodSignatureSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return MethodSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MethodSignatureSyntax = MethodSignatureSyntax; + + var IndexSignatureSyntax = (function (_super) { + __extends(IndexSignatureSyntax, _super); + function IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBracketToken = openBracketToken; + this.parameter = parameter; + this.closeBracketToken = closeBracketToken; + this.typeAnnotation = typeAnnotation; + } + IndexSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitIndexSignature(this); + }; + + IndexSignatureSyntax.prototype.kind = function () { + return 144 /* IndexSignature */; + }; + + IndexSignatureSyntax.prototype.childCount = function () { + return 4; + }; + + IndexSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBracketToken; + case 1: + return this.parameter; + case 2: + return this.closeBracketToken; + case 3: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IndexSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + IndexSignatureSyntax.prototype.update = function (openBracketToken, parameter, closeBracketToken, typeAnnotation) { + if (this.openBracketToken === openBracketToken && this.parameter === parameter && this.closeBracketToken === closeBracketToken && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, typeAnnotation, this.parsedInStrictMode()); + }; + + IndexSignatureSyntax.create = function (openBracketToken, parameter, closeBracketToken) { + return new IndexSignatureSyntax(openBracketToken, parameter, closeBracketToken, null, false); + }; + + IndexSignatureSyntax.create1 = function (parameter) { + return new IndexSignatureSyntax(TypeScript.Syntax.token(74 /* OpenBracketToken */), parameter, TypeScript.Syntax.token(75 /* CloseBracketToken */), null, false); + }; + + IndexSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IndexSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IndexSignatureSyntax.prototype.withOpenBracketToken = function (openBracketToken) { + return this.update(openBracketToken, this.parameter, this.closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withParameter = function (parameter) { + return this.update(this.openBracketToken, parameter, this.closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withCloseBracketToken = function (closeBracketToken) { + return this.update(this.openBracketToken, this.parameter, closeBracketToken, this.typeAnnotation); + }; + + IndexSignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.openBracketToken, this.parameter, this.closeBracketToken, typeAnnotation); + }; + + IndexSignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return IndexSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IndexSignatureSyntax = IndexSignatureSyntax; + + var PropertySignatureSyntax = (function (_super) { + __extends(PropertySignatureSyntax, _super); + function PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + } + PropertySignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitPropertySignature(this); + }; + + PropertySignatureSyntax.prototype.kind = function () { + return 141 /* PropertySignature */; + }; + + PropertySignatureSyntax.prototype.childCount = function () { + return 3; + }; + + PropertySignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.questionToken; + case 2: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + PropertySignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + PropertySignatureSyntax.prototype.update = function (propertyName, questionToken, typeAnnotation) { + if (this.propertyName === propertyName && this.questionToken === questionToken && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new PropertySignatureSyntax(propertyName, questionToken, typeAnnotation, this.parsedInStrictMode()); + }; + + PropertySignatureSyntax.create = function (propertyName) { + return new PropertySignatureSyntax(propertyName, null, null, false); + }; + + PropertySignatureSyntax.create1 = function (propertyName) { + return new PropertySignatureSyntax(propertyName, null, null, false); + }; + + PropertySignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + PropertySignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + PropertySignatureSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.questionToken, this.typeAnnotation); + }; + + PropertySignatureSyntax.prototype.withQuestionToken = function (questionToken) { + return this.update(this.propertyName, questionToken, this.typeAnnotation); + }; + + PropertySignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.propertyName, this.questionToken, typeAnnotation); + }; + + PropertySignatureSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return PropertySignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.PropertySignatureSyntax = PropertySignatureSyntax; + + var CallSignatureSyntax = (function (_super) { + __extends(CallSignatureSyntax, _super); + function CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + } + CallSignatureSyntax.prototype.accept = function (visitor) { + return visitor.visitCallSignature(this); + }; + + CallSignatureSyntax.prototype.kind = function () { + return 142 /* CallSignature */; + }; + + CallSignatureSyntax.prototype.childCount = function () { + return 3; + }; + + CallSignatureSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeParameterList; + case 1: + return this.parameterList; + case 2: + return this.typeAnnotation; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CallSignatureSyntax.prototype.isTypeMember = function () { + return true; + }; + + CallSignatureSyntax.prototype.update = function (typeParameterList, parameterList, typeAnnotation) { + if (this.typeParameterList === typeParameterList && this.parameterList === parameterList && this.typeAnnotation === typeAnnotation) { + return this; + } + + return new CallSignatureSyntax(typeParameterList, parameterList, typeAnnotation, this.parsedInStrictMode()); + }; + + CallSignatureSyntax.create = function (parameterList) { + return new CallSignatureSyntax(null, parameterList, null, false); + }; + + CallSignatureSyntax.create1 = function () { + return new CallSignatureSyntax(null, ParameterListSyntax.create1(), null, false); + }; + + CallSignatureSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CallSignatureSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CallSignatureSyntax.prototype.withTypeParameterList = function (typeParameterList) { + return this.update(typeParameterList, this.parameterList, this.typeAnnotation); + }; + + CallSignatureSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.typeParameterList, parameterList, this.typeAnnotation); + }; + + CallSignatureSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.typeParameterList, this.parameterList, typeAnnotation); + }; + + CallSignatureSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeParameterList !== null) { + return true; + } + if (this.parameterList.isTypeScriptSpecific()) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + return false; + }; + return CallSignatureSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CallSignatureSyntax = CallSignatureSyntax; + + var ParameterListSyntax = (function (_super) { + __extends(ParameterListSyntax, _super); + function ParameterListSyntax(openParenToken, parameters, closeParenToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openParenToken = openParenToken; + this.parameters = parameters; + this.closeParenToken = closeParenToken; + } + ParameterListSyntax.prototype.accept = function (visitor) { + return visitor.visitParameterList(this); + }; + + ParameterListSyntax.prototype.kind = function () { + return 227 /* ParameterList */; + }; + + ParameterListSyntax.prototype.childCount = function () { + return 3; + }; + + ParameterListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openParenToken; + case 1: + return this.parameters; + case 2: + return this.closeParenToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParameterListSyntax.prototype.update = function (openParenToken, parameters, closeParenToken) { + if (this.openParenToken === openParenToken && this.parameters === parameters && this.closeParenToken === closeParenToken) { + return this; + } + + return new ParameterListSyntax(openParenToken, parameters, closeParenToken, this.parsedInStrictMode()); + }; + + ParameterListSyntax.create = function (openParenToken, closeParenToken) { + return new ParameterListSyntax(openParenToken, TypeScript.Syntax.emptySeparatedList, closeParenToken, false); + }; + + ParameterListSyntax.create1 = function () { + return new ParameterListSyntax(TypeScript.Syntax.token(72 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(73 /* CloseParenToken */), false); + }; + + ParameterListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ParameterListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ParameterListSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(openParenToken, this.parameters, this.closeParenToken); + }; + + ParameterListSyntax.prototype.withParameters = function (parameters) { + return this.update(this.openParenToken, parameters, this.closeParenToken); + }; + + ParameterListSyntax.prototype.withParameter = function (parameter) { + return this.withParameters(TypeScript.Syntax.separatedList([parameter])); + }; + + ParameterListSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.openParenToken, this.parameters, closeParenToken); + }; + + ParameterListSyntax.prototype.isTypeScriptSpecific = function () { + if (this.parameters.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ParameterListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ParameterListSyntax = ParameterListSyntax; + + var TypeParameterListSyntax = (function (_super) { + __extends(TypeParameterListSyntax, _super); + function TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.typeParameters = typeParameters; + this.greaterThanToken = greaterThanToken; + } + TypeParameterListSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeParameterList(this); + }; + + TypeParameterListSyntax.prototype.kind = function () { + return 229 /* TypeParameterList */; + }; + + TypeParameterListSyntax.prototype.childCount = function () { + return 3; + }; + + TypeParameterListSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.typeParameters; + case 2: + return this.greaterThanToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeParameterListSyntax.prototype.update = function (lessThanToken, typeParameters, greaterThanToken) { + if (this.lessThanToken === lessThanToken && this.typeParameters === typeParameters && this.greaterThanToken === greaterThanToken) { + return this; + } + + return new TypeParameterListSyntax(lessThanToken, typeParameters, greaterThanToken, this.parsedInStrictMode()); + }; + + TypeParameterListSyntax.create = function (lessThanToken, greaterThanToken) { + return new TypeParameterListSyntax(lessThanToken, TypeScript.Syntax.emptySeparatedList, greaterThanToken, false); + }; + + TypeParameterListSyntax.create1 = function () { + return new TypeParameterListSyntax(TypeScript.Syntax.token(80 /* LessThanToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(81 /* GreaterThanToken */), false); + }; + + TypeParameterListSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeParameterListSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeParameterListSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.typeParameters, this.greaterThanToken); + }; + + TypeParameterListSyntax.prototype.withTypeParameters = function (typeParameters) { + return this.update(this.lessThanToken, typeParameters, this.greaterThanToken); + }; + + TypeParameterListSyntax.prototype.withTypeParameter = function (typeParameter) { + return this.withTypeParameters(TypeScript.Syntax.separatedList([typeParameter])); + }; + + TypeParameterListSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.typeParameters, greaterThanToken); + }; + + TypeParameterListSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeParameterListSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeParameterListSyntax = TypeParameterListSyntax; + + var TypeParameterSyntax = (function (_super) { + __extends(TypeParameterSyntax, _super); + function TypeParameterSyntax(identifier, constraint, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.constraint = constraint; + } + TypeParameterSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeParameter(this); + }; + + TypeParameterSyntax.prototype.kind = function () { + return 238 /* TypeParameter */; + }; + + TypeParameterSyntax.prototype.childCount = function () { + return 2; + }; + + TypeParameterSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.constraint; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeParameterSyntax.prototype.update = function (identifier, constraint) { + if (this.identifier === identifier && this.constraint === constraint) { + return this; + } + + return new TypeParameterSyntax(identifier, constraint, this.parsedInStrictMode()); + }; + + TypeParameterSyntax.create = function (identifier) { + return new TypeParameterSyntax(identifier, null, false); + }; + + TypeParameterSyntax.create1 = function (identifier) { + return new TypeParameterSyntax(identifier, null, false); + }; + + TypeParameterSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeParameterSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeParameterSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.constraint); + }; + + TypeParameterSyntax.prototype.withConstraint = function (constraint) { + return this.update(this.identifier, constraint); + }; + + TypeParameterSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return TypeParameterSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeParameterSyntax = TypeParameterSyntax; + + var ConstraintSyntax = (function (_super) { + __extends(ConstraintSyntax, _super); + function ConstraintSyntax(extendsKeyword, type, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.extendsKeyword = extendsKeyword; + this.type = type; + } + ConstraintSyntax.prototype.accept = function (visitor) { + return visitor.visitConstraint(this); + }; + + ConstraintSyntax.prototype.kind = function () { + return 239 /* Constraint */; + }; + + ConstraintSyntax.prototype.childCount = function () { + return 2; + }; + + ConstraintSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.extendsKeyword; + case 1: + return this.type; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstraintSyntax.prototype.update = function (extendsKeyword, type) { + if (this.extendsKeyword === extendsKeyword && this.type === type) { + return this; + } + + return new ConstraintSyntax(extendsKeyword, type, this.parsedInStrictMode()); + }; + + ConstraintSyntax.create1 = function (type) { + return new ConstraintSyntax(TypeScript.Syntax.token(48 /* ExtendsKeyword */), type, false); + }; + + ConstraintSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstraintSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstraintSyntax.prototype.withExtendsKeyword = function (extendsKeyword) { + return this.update(extendsKeyword, this.type); + }; + + ConstraintSyntax.prototype.withType = function (type) { + return this.update(this.extendsKeyword, type); + }; + + ConstraintSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstraintSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstraintSyntax = ConstraintSyntax; + + var ElseClauseSyntax = (function (_super) { + __extends(ElseClauseSyntax, _super); + function ElseClauseSyntax(elseKeyword, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.elseKeyword = elseKeyword; + this.statement = statement; + } + ElseClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitElseClause(this); + }; + + ElseClauseSyntax.prototype.kind = function () { + return 235 /* ElseClause */; + }; + + ElseClauseSyntax.prototype.childCount = function () { + return 2; + }; + + ElseClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.elseKeyword; + case 1: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ElseClauseSyntax.prototype.update = function (elseKeyword, statement) { + if (this.elseKeyword === elseKeyword && this.statement === statement) { + return this; + } + + return new ElseClauseSyntax(elseKeyword, statement, this.parsedInStrictMode()); + }; + + ElseClauseSyntax.create1 = function (statement) { + return new ElseClauseSyntax(TypeScript.Syntax.token(23 /* ElseKeyword */), statement, false); + }; + + ElseClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ElseClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ElseClauseSyntax.prototype.withElseKeyword = function (elseKeyword) { + return this.update(elseKeyword, this.statement); + }; + + ElseClauseSyntax.prototype.withStatement = function (statement) { + return this.update(this.elseKeyword, statement); + }; + + ElseClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ElseClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ElseClauseSyntax = ElseClauseSyntax; + + var IfStatementSyntax = (function (_super) { + __extends(IfStatementSyntax, _super); + function IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.ifKeyword = ifKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + this.elseClause = elseClause; + } + IfStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitIfStatement(this); + }; + + IfStatementSyntax.prototype.kind = function () { + return 147 /* IfStatement */; + }; + + IfStatementSyntax.prototype.childCount = function () { + return 6; + }; + + IfStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.ifKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + case 5: + return this.elseClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IfStatementSyntax.prototype.isStatement = function () { + return true; + }; + + IfStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + IfStatementSyntax.prototype.update = function (ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause) { + if (this.ifKeyword === ifKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement && this.elseClause === elseClause) { + return this; + } + + return new IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause, this.parsedInStrictMode()); + }; + + IfStatementSyntax.create = function (ifKeyword, openParenToken, condition, closeParenToken, statement) { + return new IfStatementSyntax(ifKeyword, openParenToken, condition, closeParenToken, statement, null, false); + }; + + IfStatementSyntax.create1 = function (condition, statement) { + return new IfStatementSyntax(TypeScript.Syntax.token(28 /* IfKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, null, false); + }; + + IfStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IfStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IfStatementSyntax.prototype.withIfKeyword = function (ifKeyword) { + return this.update(ifKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.ifKeyword, openParenToken, this.condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.ifKeyword, this.openParenToken, condition, this.closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, closeParenToken, this.statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, this.closeParenToken, statement, this.elseClause); + }; + + IfStatementSyntax.prototype.withElseClause = function (elseClause) { + return this.update(this.ifKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement, elseClause); + }; + + IfStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + if (this.elseClause !== null && this.elseClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return IfStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IfStatementSyntax = IfStatementSyntax; + + var ExpressionStatementSyntax = (function (_super) { + __extends(ExpressionStatementSyntax, _super); + function ExpressionStatementSyntax(expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ExpressionStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitExpressionStatement(this); + }; + + ExpressionStatementSyntax.prototype.kind = function () { + return 149 /* ExpressionStatement */; + }; + + ExpressionStatementSyntax.prototype.childCount = function () { + return 2; + }; + + ExpressionStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.expression; + case 1: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ExpressionStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ExpressionStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ExpressionStatementSyntax.prototype.update = function (expression, semicolonToken) { + if (this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ExpressionStatementSyntax(expression, semicolonToken, this.parsedInStrictMode()); + }; + + ExpressionStatementSyntax.create1 = function (expression) { + return new ExpressionStatementSyntax(expression, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ExpressionStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ExpressionStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ExpressionStatementSyntax.prototype.withExpression = function (expression) { + return this.update(expression, this.semicolonToken); + }; + + ExpressionStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.expression, semicolonToken); + }; + + ExpressionStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ExpressionStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ExpressionStatementSyntax = ExpressionStatementSyntax; + + var ConstructorDeclarationSyntax = (function (_super) { + __extends(ConstructorDeclarationSyntax, _super); + function ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.constructorKeyword = constructorKeyword; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + ConstructorDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitConstructorDeclaration(this); + }; + + ConstructorDeclarationSyntax.prototype.kind = function () { + return 137 /* ConstructorDeclaration */; + }; + + ConstructorDeclarationSyntax.prototype.childCount = function () { + return 5; + }; + + ConstructorDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.constructorKeyword; + case 2: + return this.callSignature; + case 3: + return this.block; + case 4: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ConstructorDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + ConstructorDeclarationSyntax.prototype.update = function (modifiers, constructorKeyword, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.constructorKeyword === constructorKeyword && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new ConstructorDeclarationSyntax(modifiers, constructorKeyword, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + ConstructorDeclarationSyntax.create = function (constructorKeyword, callSignature) { + return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, constructorKeyword, callSignature, null, null, false); + }; + + ConstructorDeclarationSyntax.create1 = function () { + return new ConstructorDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(62 /* ConstructorKeyword */), CallSignatureSyntax.create1(), null, null, false); + }; + + ConstructorDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ConstructorDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ConstructorDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.constructorKeyword, this.callSignature, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + ConstructorDeclarationSyntax.prototype.withConstructorKeyword = function (constructorKeyword) { + return this.update(this.modifiers, constructorKeyword, this.callSignature, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.constructorKeyword, callSignature, this.block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.constructorKeyword, this.callSignature, block, this.semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.constructorKeyword, this.callSignature, this.block, semicolonToken); + }; + + ConstructorDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return ConstructorDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ConstructorDeclarationSyntax = ConstructorDeclarationSyntax; + + var MemberFunctionDeclarationSyntax = (function (_super) { + __extends(MemberFunctionDeclarationSyntax, _super); + function MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + this.semicolonToken = semicolonToken; + } + MemberFunctionDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberFunctionDeclaration(this); + }; + + MemberFunctionDeclarationSyntax.prototype.kind = function () { + return 135 /* MemberFunctionDeclaration */; + }; + + MemberFunctionDeclarationSyntax.prototype.childCount = function () { + return 5; + }; + + MemberFunctionDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.propertyName; + case 2: + return this.callSignature; + case 3: + return this.block; + case 4: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberFunctionDeclarationSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + MemberFunctionDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + MemberFunctionDeclarationSyntax.prototype.update = function (modifiers, propertyName, callSignature, block, semicolonToken) { + if (this.modifiers === modifiers && this.propertyName === propertyName && this.callSignature === callSignature && this.block === block && this.semicolonToken === semicolonToken) { + return this; + } + + return new MemberFunctionDeclarationSyntax(modifiers, propertyName, callSignature, block, semicolonToken, this.parsedInStrictMode()); + }; + + MemberFunctionDeclarationSyntax.create = function (propertyName, callSignature) { + return new MemberFunctionDeclarationSyntax(TypeScript.Syntax.emptyList, propertyName, callSignature, null, null, false); + }; + + MemberFunctionDeclarationSyntax.create1 = function (propertyName) { + return new MemberFunctionDeclarationSyntax(TypeScript.Syntax.emptyList, propertyName, CallSignatureSyntax.create1(), null, null, false); + }; + + MemberFunctionDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberFunctionDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberFunctionDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.propertyName, this.callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + MemberFunctionDeclarationSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, propertyName, this.callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.modifiers, this.propertyName, callSignature, this.block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.propertyName, this.callSignature, block, this.semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.propertyName, this.callSignature, this.block, semicolonToken); + }; + + MemberFunctionDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return MemberFunctionDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberFunctionDeclarationSyntax = MemberFunctionDeclarationSyntax; + + var GetAccessorSyntax = (function (_super) { + __extends(GetAccessorSyntax, _super); + function GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.getKeyword = getKeyword; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + this.block = block; + } + GetAccessorSyntax.prototype.accept = function (visitor) { + return visitor.visitGetAccessor(this); + }; + + GetAccessorSyntax.prototype.kind = function () { + return 139 /* GetAccessor */; + }; + + GetAccessorSyntax.prototype.childCount = function () { + return 6; + }; + + GetAccessorSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.getKeyword; + case 2: + return this.propertyName; + case 3: + return this.parameterList; + case 4: + return this.typeAnnotation; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + GetAccessorSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + GetAccessorSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + GetAccessorSyntax.prototype.isClassElement = function () { + return true; + }; + + GetAccessorSyntax.prototype.update = function (modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block) { + if (this.modifiers === modifiers && this.getKeyword === getKeyword && this.propertyName === propertyName && this.parameterList === parameterList && this.typeAnnotation === typeAnnotation && this.block === block) { + return this; + } + + return new GetAccessorSyntax(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block, this.parsedInStrictMode()); + }; + + GetAccessorSyntax.create = function (getKeyword, propertyName, parameterList, block) { + return new GetAccessorSyntax(TypeScript.Syntax.emptyList, getKeyword, propertyName, parameterList, null, block, false); + }; + + GetAccessorSyntax.create1 = function (propertyName) { + return new GetAccessorSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(64 /* GetKeyword */), propertyName, ParameterListSyntax.create1(), null, BlockSyntax.create1(), false); + }; + + GetAccessorSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + GetAccessorSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + GetAccessorSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + GetAccessorSyntax.prototype.withGetKeyword = function (getKeyword) { + return this.update(this.modifiers, getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, this.getKeyword, propertyName, this.parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, parameterList, this.typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, this.parameterList, typeAnnotation, this.block); + }; + + GetAccessorSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.getKeyword, this.propertyName, this.parameterList, this.typeAnnotation, block); + }; + + GetAccessorSyntax.prototype.isTypeScriptSpecific = function () { + if (this.modifiers.childCount() > 0) { + return true; + } + if (this.parameterList.isTypeScriptSpecific()) { + return true; + } + if (this.typeAnnotation !== null) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return GetAccessorSyntax; + })(TypeScript.SyntaxNode); + TypeScript.GetAccessorSyntax = GetAccessorSyntax; + + var SetAccessorSyntax = (function (_super) { + __extends(SetAccessorSyntax, _super); + function SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.setKeyword = setKeyword; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.block = block; + } + SetAccessorSyntax.prototype.accept = function (visitor) { + return visitor.visitSetAccessor(this); + }; + + SetAccessorSyntax.prototype.kind = function () { + return 140 /* SetAccessor */; + }; + + SetAccessorSyntax.prototype.childCount = function () { + return 5; + }; + + SetAccessorSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.setKeyword; + case 2: + return this.propertyName; + case 3: + return this.parameterList; + case 4: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SetAccessorSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + SetAccessorSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + SetAccessorSyntax.prototype.isClassElement = function () { + return true; + }; + + SetAccessorSyntax.prototype.update = function (modifiers, setKeyword, propertyName, parameterList, block) { + if (this.modifiers === modifiers && this.setKeyword === setKeyword && this.propertyName === propertyName && this.parameterList === parameterList && this.block === block) { + return this; + } + + return new SetAccessorSyntax(modifiers, setKeyword, propertyName, parameterList, block, this.parsedInStrictMode()); + }; + + SetAccessorSyntax.create = function (setKeyword, propertyName, parameterList, block) { + return new SetAccessorSyntax(TypeScript.Syntax.emptyList, setKeyword, propertyName, parameterList, block, false); + }; + + SetAccessorSyntax.create1 = function (propertyName) { + return new SetAccessorSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(68 /* SetKeyword */), propertyName, ParameterListSyntax.create1(), BlockSyntax.create1(), false); + }; + + SetAccessorSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SetAccessorSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SetAccessorSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.setKeyword, this.propertyName, this.parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + SetAccessorSyntax.prototype.withSetKeyword = function (setKeyword) { + return this.update(this.modifiers, setKeyword, this.propertyName, this.parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(this.modifiers, this.setKeyword, propertyName, this.parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withParameterList = function (parameterList) { + return this.update(this.modifiers, this.setKeyword, this.propertyName, parameterList, this.block); + }; + + SetAccessorSyntax.prototype.withBlock = function (block) { + return this.update(this.modifiers, this.setKeyword, this.propertyName, this.parameterList, block); + }; + + SetAccessorSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return SetAccessorSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SetAccessorSyntax = SetAccessorSyntax; + + var MemberVariableDeclarationSyntax = (function (_super) { + __extends(MemberVariableDeclarationSyntax, _super); + function MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.variableDeclarator = variableDeclarator; + this.semicolonToken = semicolonToken; + } + MemberVariableDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitMemberVariableDeclaration(this); + }; + + MemberVariableDeclarationSyntax.prototype.kind = function () { + return 136 /* MemberVariableDeclaration */; + }; + + MemberVariableDeclarationSyntax.prototype.childCount = function () { + return 3; + }; + + MemberVariableDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.variableDeclarator; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + MemberVariableDeclarationSyntax.prototype.isMemberDeclaration = function () { + return true; + }; + + MemberVariableDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + MemberVariableDeclarationSyntax.prototype.update = function (modifiers, variableDeclarator, semicolonToken) { + if (this.modifiers === modifiers && this.variableDeclarator === variableDeclarator && this.semicolonToken === semicolonToken) { + return this; + } + + return new MemberVariableDeclarationSyntax(modifiers, variableDeclarator, semicolonToken, this.parsedInStrictMode()); + }; + + MemberVariableDeclarationSyntax.create = function (variableDeclarator, semicolonToken) { + return new MemberVariableDeclarationSyntax(TypeScript.Syntax.emptyList, variableDeclarator, semicolonToken, false); + }; + + MemberVariableDeclarationSyntax.create1 = function (variableDeclarator) { + return new MemberVariableDeclarationSyntax(TypeScript.Syntax.emptyList, variableDeclarator, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + MemberVariableDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + MemberVariableDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + MemberVariableDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.variableDeclarator, this.semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + MemberVariableDeclarationSyntax.prototype.withVariableDeclarator = function (variableDeclarator) { + return this.update(this.modifiers, variableDeclarator, this.semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.variableDeclarator, semicolonToken); + }; + + MemberVariableDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return MemberVariableDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.MemberVariableDeclarationSyntax = MemberVariableDeclarationSyntax; + + var IndexMemberDeclarationSyntax = (function (_super) { + __extends(IndexMemberDeclarationSyntax, _super); + function IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.indexSignature = indexSignature; + this.semicolonToken = semicolonToken; + } + IndexMemberDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitIndexMemberDeclaration(this); + }; + + IndexMemberDeclarationSyntax.prototype.kind = function () { + return 138 /* IndexMemberDeclaration */; + }; + + IndexMemberDeclarationSyntax.prototype.childCount = function () { + return 3; + }; + + IndexMemberDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.indexSignature; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + IndexMemberDeclarationSyntax.prototype.isClassElement = function () { + return true; + }; + + IndexMemberDeclarationSyntax.prototype.update = function (modifiers, indexSignature, semicolonToken) { + if (this.modifiers === modifiers && this.indexSignature === indexSignature && this.semicolonToken === semicolonToken) { + return this; + } + + return new IndexMemberDeclarationSyntax(modifiers, indexSignature, semicolonToken, this.parsedInStrictMode()); + }; + + IndexMemberDeclarationSyntax.create = function (indexSignature, semicolonToken) { + return new IndexMemberDeclarationSyntax(TypeScript.Syntax.emptyList, indexSignature, semicolonToken, false); + }; + + IndexMemberDeclarationSyntax.create1 = function (indexSignature) { + return new IndexMemberDeclarationSyntax(TypeScript.Syntax.emptyList, indexSignature, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + IndexMemberDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + IndexMemberDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + IndexMemberDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.indexSignature, this.semicolonToken); + }; + + IndexMemberDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + IndexMemberDeclarationSyntax.prototype.withIndexSignature = function (indexSignature) { + return this.update(this.modifiers, indexSignature, this.semicolonToken); + }; + + IndexMemberDeclarationSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.modifiers, this.indexSignature, semicolonToken); + }; + + IndexMemberDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return IndexMemberDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.IndexMemberDeclarationSyntax = IndexMemberDeclarationSyntax; + + var ThrowStatementSyntax = (function (_super) { + __extends(ThrowStatementSyntax, _super); + function ThrowStatementSyntax(throwKeyword, expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.throwKeyword = throwKeyword; + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ThrowStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitThrowStatement(this); + }; + + ThrowStatementSyntax.prototype.kind = function () { + return 157 /* ThrowStatement */; + }; + + ThrowStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ThrowStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.throwKeyword; + case 1: + return this.expression; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ThrowStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ThrowStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ThrowStatementSyntax.prototype.update = function (throwKeyword, expression, semicolonToken) { + if (this.throwKeyword === throwKeyword && this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ThrowStatementSyntax(throwKeyword, expression, semicolonToken, this.parsedInStrictMode()); + }; + + ThrowStatementSyntax.create1 = function (expression) { + return new ThrowStatementSyntax(TypeScript.Syntax.token(36 /* ThrowKeyword */), expression, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ThrowStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ThrowStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ThrowStatementSyntax.prototype.withThrowKeyword = function (throwKeyword) { + return this.update(throwKeyword, this.expression, this.semicolonToken); + }; + + ThrowStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.throwKeyword, expression, this.semicolonToken); + }; + + ThrowStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.throwKeyword, this.expression, semicolonToken); + }; + + ThrowStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ThrowStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ThrowStatementSyntax = ThrowStatementSyntax; + + var ReturnStatementSyntax = (function (_super) { + __extends(ReturnStatementSyntax, _super); + function ReturnStatementSyntax(returnKeyword, expression, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.returnKeyword = returnKeyword; + this.expression = expression; + this.semicolonToken = semicolonToken; + } + ReturnStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitReturnStatement(this); + }; + + ReturnStatementSyntax.prototype.kind = function () { + return 150 /* ReturnStatement */; + }; + + ReturnStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ReturnStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.returnKeyword; + case 1: + return this.expression; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ReturnStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ReturnStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ReturnStatementSyntax.prototype.update = function (returnKeyword, expression, semicolonToken) { + if (this.returnKeyword === returnKeyword && this.expression === expression && this.semicolonToken === semicolonToken) { + return this; + } + + return new ReturnStatementSyntax(returnKeyword, expression, semicolonToken, this.parsedInStrictMode()); + }; + + ReturnStatementSyntax.create = function (returnKeyword, semicolonToken) { + return new ReturnStatementSyntax(returnKeyword, null, semicolonToken, false); + }; + + ReturnStatementSyntax.create1 = function () { + return new ReturnStatementSyntax(TypeScript.Syntax.token(33 /* ReturnKeyword */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ReturnStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ReturnStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ReturnStatementSyntax.prototype.withReturnKeyword = function (returnKeyword) { + return this.update(returnKeyword, this.expression, this.semicolonToken); + }; + + ReturnStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.returnKeyword, expression, this.semicolonToken); + }; + + ReturnStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.returnKeyword, this.expression, semicolonToken); + }; + + ReturnStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression !== null && this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ReturnStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ReturnStatementSyntax = ReturnStatementSyntax; + + var ObjectCreationExpressionSyntax = (function (_super) { + __extends(ObjectCreationExpressionSyntax, _super); + function ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.newKeyword = newKeyword; + this.expression = expression; + this.argumentList = argumentList; + } + ObjectCreationExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectCreationExpression(this); + }; + + ObjectCreationExpressionSyntax.prototype.kind = function () { + return 216 /* ObjectCreationExpression */; + }; + + ObjectCreationExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectCreationExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.newKeyword; + case 1: + return this.expression; + case 2: + return this.argumentList; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectCreationExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ObjectCreationExpressionSyntax.prototype.update = function (newKeyword, expression, argumentList) { + if (this.newKeyword === newKeyword && this.expression === expression && this.argumentList === argumentList) { + return this; + } + + return new ObjectCreationExpressionSyntax(newKeyword, expression, argumentList, this.parsedInStrictMode()); + }; + + ObjectCreationExpressionSyntax.create = function (newKeyword, expression) { + return new ObjectCreationExpressionSyntax(newKeyword, expression, null, false); + }; + + ObjectCreationExpressionSyntax.create1 = function (expression) { + return new ObjectCreationExpressionSyntax(TypeScript.Syntax.token(31 /* NewKeyword */), expression, null, false); + }; + + ObjectCreationExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectCreationExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectCreationExpressionSyntax.prototype.withNewKeyword = function (newKeyword) { + return this.update(newKeyword, this.expression, this.argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.newKeyword, expression, this.argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.withArgumentList = function (argumentList) { + return this.update(this.newKeyword, this.expression, argumentList); + }; + + ObjectCreationExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.argumentList !== null && this.argumentList.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ObjectCreationExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectCreationExpressionSyntax = ObjectCreationExpressionSyntax; + + var SwitchStatementSyntax = (function (_super) { + __extends(SwitchStatementSyntax, _super); + function SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.switchKeyword = switchKeyword; + this.openParenToken = openParenToken; + this.expression = expression; + this.closeParenToken = closeParenToken; + this.openBraceToken = openBraceToken; + this.switchClauses = switchClauses; + this.closeBraceToken = closeBraceToken; + } + SwitchStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitSwitchStatement(this); + }; + + SwitchStatementSyntax.prototype.kind = function () { + return 151 /* SwitchStatement */; + }; + + SwitchStatementSyntax.prototype.childCount = function () { + return 7; + }; + + SwitchStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.switchKeyword; + case 1: + return this.openParenToken; + case 2: + return this.expression; + case 3: + return this.closeParenToken; + case 4: + return this.openBraceToken; + case 5: + return this.switchClauses; + case 6: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SwitchStatementSyntax.prototype.isStatement = function () { + return true; + }; + + SwitchStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + SwitchStatementSyntax.prototype.update = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken) { + if (this.switchKeyword === switchKeyword && this.openParenToken === openParenToken && this.expression === expression && this.closeParenToken === closeParenToken && this.openBraceToken === openBraceToken && this.switchClauses === switchClauses && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken, this.parsedInStrictMode()); + }; + + SwitchStatementSyntax.create = function (switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, closeBraceToken) { + return new SwitchStatementSyntax(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, TypeScript.Syntax.emptyList, closeBraceToken, false); + }; + + SwitchStatementSyntax.create1 = function (expression) { + return new SwitchStatementSyntax(TypeScript.Syntax.token(34 /* SwitchKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), expression, TypeScript.Syntax.token(73 /* CloseParenToken */), TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptyList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + SwitchStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SwitchStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SwitchStatementSyntax.prototype.withSwitchKeyword = function (switchKeyword) { + return this.update(switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.switchKeyword, openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.switchKeyword, this.openParenToken, expression, this.closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, closeParenToken, this.openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, openBraceToken, this.switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withSwitchClauses = function (switchClauses) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, switchClauses, this.closeBraceToken); + }; + + SwitchStatementSyntax.prototype.withSwitchClause = function (switchClause) { + return this.withSwitchClauses(TypeScript.Syntax.list([switchClause])); + }; + + SwitchStatementSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.switchKeyword, this.openParenToken, this.expression, this.closeParenToken, this.openBraceToken, this.switchClauses, closeBraceToken); + }; + + SwitchStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.switchClauses.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SwitchStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SwitchStatementSyntax = SwitchStatementSyntax; + + var CaseSwitchClauseSyntax = (function (_super) { + __extends(CaseSwitchClauseSyntax, _super); + function CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.caseKeyword = caseKeyword; + this.expression = expression; + this.colonToken = colonToken; + this.statements = statements; + } + CaseSwitchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitCaseSwitchClause(this); + }; + + CaseSwitchClauseSyntax.prototype.kind = function () { + return 233 /* CaseSwitchClause */; + }; + + CaseSwitchClauseSyntax.prototype.childCount = function () { + return 4; + }; + + CaseSwitchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.caseKeyword; + case 1: + return this.expression; + case 2: + return this.colonToken; + case 3: + return this.statements; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CaseSwitchClauseSyntax.prototype.isSwitchClause = function () { + return true; + }; + + CaseSwitchClauseSyntax.prototype.update = function (caseKeyword, expression, colonToken, statements) { + if (this.caseKeyword === caseKeyword && this.expression === expression && this.colonToken === colonToken && this.statements === statements) { + return this; + } + + return new CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, statements, this.parsedInStrictMode()); + }; + + CaseSwitchClauseSyntax.create = function (caseKeyword, expression, colonToken) { + return new CaseSwitchClauseSyntax(caseKeyword, expression, colonToken, TypeScript.Syntax.emptyList, false); + }; + + CaseSwitchClauseSyntax.create1 = function (expression) { + return new CaseSwitchClauseSyntax(TypeScript.Syntax.token(16 /* CaseKeyword */), expression, TypeScript.Syntax.token(106 /* ColonToken */), TypeScript.Syntax.emptyList, false); + }; + + CaseSwitchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CaseSwitchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CaseSwitchClauseSyntax.prototype.withCaseKeyword = function (caseKeyword) { + return this.update(caseKeyword, this.expression, this.colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withExpression = function (expression) { + return this.update(this.caseKeyword, expression, this.colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.caseKeyword, this.expression, colonToken, this.statements); + }; + + CaseSwitchClauseSyntax.prototype.withStatements = function (statements) { + return this.update(this.caseKeyword, this.expression, this.colonToken, statements); + }; + + CaseSwitchClauseSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + CaseSwitchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return CaseSwitchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CaseSwitchClauseSyntax = CaseSwitchClauseSyntax; + + var DefaultSwitchClauseSyntax = (function (_super) { + __extends(DefaultSwitchClauseSyntax, _super); + function DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.defaultKeyword = defaultKeyword; + this.colonToken = colonToken; + this.statements = statements; + } + DefaultSwitchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitDefaultSwitchClause(this); + }; + + DefaultSwitchClauseSyntax.prototype.kind = function () { + return 234 /* DefaultSwitchClause */; + }; + + DefaultSwitchClauseSyntax.prototype.childCount = function () { + return 3; + }; + + DefaultSwitchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.defaultKeyword; + case 1: + return this.colonToken; + case 2: + return this.statements; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DefaultSwitchClauseSyntax.prototype.isSwitchClause = function () { + return true; + }; + + DefaultSwitchClauseSyntax.prototype.update = function (defaultKeyword, colonToken, statements) { + if (this.defaultKeyword === defaultKeyword && this.colonToken === colonToken && this.statements === statements) { + return this; + } + + return new DefaultSwitchClauseSyntax(defaultKeyword, colonToken, statements, this.parsedInStrictMode()); + }; + + DefaultSwitchClauseSyntax.create = function (defaultKeyword, colonToken) { + return new DefaultSwitchClauseSyntax(defaultKeyword, colonToken, TypeScript.Syntax.emptyList, false); + }; + + DefaultSwitchClauseSyntax.create1 = function () { + return new DefaultSwitchClauseSyntax(TypeScript.Syntax.token(20 /* DefaultKeyword */), TypeScript.Syntax.token(106 /* ColonToken */), TypeScript.Syntax.emptyList, false); + }; + + DefaultSwitchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DefaultSwitchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DefaultSwitchClauseSyntax.prototype.withDefaultKeyword = function (defaultKeyword) { + return this.update(defaultKeyword, this.colonToken, this.statements); + }; + + DefaultSwitchClauseSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.defaultKeyword, colonToken, this.statements); + }; + + DefaultSwitchClauseSyntax.prototype.withStatements = function (statements) { + return this.update(this.defaultKeyword, this.colonToken, statements); + }; + + DefaultSwitchClauseSyntax.prototype.withStatement = function (statement) { + return this.withStatements(TypeScript.Syntax.list([statement])); + }; + + DefaultSwitchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statements.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DefaultSwitchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DefaultSwitchClauseSyntax = DefaultSwitchClauseSyntax; + + var BreakStatementSyntax = (function (_super) { + __extends(BreakStatementSyntax, _super); + function BreakStatementSyntax(breakKeyword, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.breakKeyword = breakKeyword; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + BreakStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitBreakStatement(this); + }; + + BreakStatementSyntax.prototype.kind = function () { + return 152 /* BreakStatement */; + }; + + BreakStatementSyntax.prototype.childCount = function () { + return 3; + }; + + BreakStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.breakKeyword; + case 1: + return this.identifier; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + BreakStatementSyntax.prototype.isStatement = function () { + return true; + }; + + BreakStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + BreakStatementSyntax.prototype.update = function (breakKeyword, identifier, semicolonToken) { + if (this.breakKeyword === breakKeyword && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new BreakStatementSyntax(breakKeyword, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + BreakStatementSyntax.create = function (breakKeyword, semicolonToken) { + return new BreakStatementSyntax(breakKeyword, null, semicolonToken, false); + }; + + BreakStatementSyntax.create1 = function () { + return new BreakStatementSyntax(TypeScript.Syntax.token(15 /* BreakKeyword */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + BreakStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + BreakStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + BreakStatementSyntax.prototype.withBreakKeyword = function (breakKeyword) { + return this.update(breakKeyword, this.identifier, this.semicolonToken); + }; + + BreakStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.breakKeyword, identifier, this.semicolonToken); + }; + + BreakStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.breakKeyword, this.identifier, semicolonToken); + }; + + BreakStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return BreakStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.BreakStatementSyntax = BreakStatementSyntax; + + var ContinueStatementSyntax = (function (_super) { + __extends(ContinueStatementSyntax, _super); + function ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.continueKeyword = continueKeyword; + this.identifier = identifier; + this.semicolonToken = semicolonToken; + } + ContinueStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitContinueStatement(this); + }; + + ContinueStatementSyntax.prototype.kind = function () { + return 153 /* ContinueStatement */; + }; + + ContinueStatementSyntax.prototype.childCount = function () { + return 3; + }; + + ContinueStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.continueKeyword; + case 1: + return this.identifier; + case 2: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ContinueStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ContinueStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ContinueStatementSyntax.prototype.update = function (continueKeyword, identifier, semicolonToken) { + if (this.continueKeyword === continueKeyword && this.identifier === identifier && this.semicolonToken === semicolonToken) { + return this; + } + + return new ContinueStatementSyntax(continueKeyword, identifier, semicolonToken, this.parsedInStrictMode()); + }; + + ContinueStatementSyntax.create = function (continueKeyword, semicolonToken) { + return new ContinueStatementSyntax(continueKeyword, null, semicolonToken, false); + }; + + ContinueStatementSyntax.create1 = function () { + return new ContinueStatementSyntax(TypeScript.Syntax.token(18 /* ContinueKeyword */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + ContinueStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ContinueStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ContinueStatementSyntax.prototype.withContinueKeyword = function (continueKeyword) { + return this.update(continueKeyword, this.identifier, this.semicolonToken); + }; + + ContinueStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.continueKeyword, identifier, this.semicolonToken); + }; + + ContinueStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.continueKeyword, this.identifier, semicolonToken); + }; + + ContinueStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return ContinueStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ContinueStatementSyntax = ContinueStatementSyntax; + + var ForStatementSyntax = (function (_super) { + __extends(ForStatementSyntax, _super); + function ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.forKeyword = forKeyword; + this.openParenToken = openParenToken; + this.variableDeclaration = variableDeclaration; + this.initializer = initializer; + this.firstSemicolonToken = firstSemicolonToken; + this.condition = condition; + this.secondSemicolonToken = secondSemicolonToken; + this.incrementor = incrementor; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + ForStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitForStatement(this); + }; + + ForStatementSyntax.prototype.kind = function () { + return 154 /* ForStatement */; + }; + + ForStatementSyntax.prototype.childCount = function () { + return 10; + }; + + ForStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.forKeyword; + case 1: + return this.openParenToken; + case 2: + return this.variableDeclaration; + case 3: + return this.initializer; + case 4: + return this.firstSemicolonToken; + case 5: + return this.condition; + case 6: + return this.secondSemicolonToken; + case 7: + return this.incrementor; + case 8: + return this.closeParenToken; + case 9: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ForStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + ForStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ForStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ForStatementSyntax.prototype.update = function (forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement) { + if (this.forKeyword === forKeyword && this.openParenToken === openParenToken && this.variableDeclaration === variableDeclaration && this.initializer === initializer && this.firstSemicolonToken === firstSemicolonToken && this.condition === condition && this.secondSemicolonToken === secondSemicolonToken && this.incrementor === incrementor && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new ForStatementSyntax(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement, this.parsedInStrictMode()); + }; + + ForStatementSyntax.create = function (forKeyword, openParenToken, firstSemicolonToken, secondSemicolonToken, closeParenToken, statement) { + return new ForStatementSyntax(forKeyword, openParenToken, null, null, firstSemicolonToken, null, secondSemicolonToken, null, closeParenToken, statement, false); + }; + + ForStatementSyntax.create1 = function (statement) { + return new ForStatementSyntax(TypeScript.Syntax.token(26 /* ForKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), null, null, TypeScript.Syntax.token(78 /* SemicolonToken */), null, TypeScript.Syntax.token(78 /* SemicolonToken */), null, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + ForStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ForStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ForStatementSyntax.prototype.withForKeyword = function (forKeyword) { + return this.update(forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.forKeyword, openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.forKeyword, this.openParenToken, variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withInitializer = function (initializer) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withFirstSemicolonToken = function (firstSemicolonToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withSecondSemicolonToken = function (secondSemicolonToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, secondSemicolonToken, this.incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withIncrementor = function (incrementor) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, incrementor, this.closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, closeParenToken, this.statement); + }; + + ForStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.initializer, this.firstSemicolonToken, this.condition, this.secondSemicolonToken, this.incrementor, this.closeParenToken, statement); + }; + + ForStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclaration !== null && this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + if (this.initializer !== null && this.initializer.isTypeScriptSpecific()) { + return true; + } + if (this.condition !== null && this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.incrementor !== null && this.incrementor.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ForStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ForStatementSyntax = ForStatementSyntax; + + var ForInStatementSyntax = (function (_super) { + __extends(ForInStatementSyntax, _super); + function ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.forKeyword = forKeyword; + this.openParenToken = openParenToken; + this.variableDeclaration = variableDeclaration; + this.left = left; + this.inKeyword = inKeyword; + this.expression = expression; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + ForInStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitForInStatement(this); + }; + + ForInStatementSyntax.prototype.kind = function () { + return 155 /* ForInStatement */; + }; + + ForInStatementSyntax.prototype.childCount = function () { + return 8; + }; + + ForInStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.forKeyword; + case 1: + return this.openParenToken; + case 2: + return this.variableDeclaration; + case 3: + return this.left; + case 4: + return this.inKeyword; + case 5: + return this.expression; + case 6: + return this.closeParenToken; + case 7: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ForInStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + ForInStatementSyntax.prototype.isStatement = function () { + return true; + }; + + ForInStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + ForInStatementSyntax.prototype.update = function (forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement) { + if (this.forKeyword === forKeyword && this.openParenToken === openParenToken && this.variableDeclaration === variableDeclaration && this.left === left && this.inKeyword === inKeyword && this.expression === expression && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new ForInStatementSyntax(forKeyword, openParenToken, variableDeclaration, left, inKeyword, expression, closeParenToken, statement, this.parsedInStrictMode()); + }; + + ForInStatementSyntax.create = function (forKeyword, openParenToken, inKeyword, expression, closeParenToken, statement) { + return new ForInStatementSyntax(forKeyword, openParenToken, null, null, inKeyword, expression, closeParenToken, statement, false); + }; + + ForInStatementSyntax.create1 = function (expression, statement) { + return new ForInStatementSyntax(TypeScript.Syntax.token(26 /* ForKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), null, null, TypeScript.Syntax.token(29 /* InKeyword */), expression, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + ForInStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ForInStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ForInStatementSyntax.prototype.withForKeyword = function (forKeyword) { + return this.update(forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.forKeyword, openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withVariableDeclaration = function (variableDeclaration) { + return this.update(this.forKeyword, this.openParenToken, variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withLeft = function (left) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, left, this.inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withInKeyword = function (inKeyword) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, inKeyword, this.expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withExpression = function (expression) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, expression, this.closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, closeParenToken, this.statement); + }; + + ForInStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.forKeyword, this.openParenToken, this.variableDeclaration, this.left, this.inKeyword, this.expression, this.closeParenToken, statement); + }; + + ForInStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.variableDeclaration !== null && this.variableDeclaration.isTypeScriptSpecific()) { + return true; + } + if (this.left !== null && this.left.isTypeScriptSpecific()) { + return true; + } + if (this.expression.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ForInStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ForInStatementSyntax = ForInStatementSyntax; + + var WhileStatementSyntax = (function (_super) { + __extends(WhileStatementSyntax, _super); + function WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.whileKeyword = whileKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + WhileStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitWhileStatement(this); + }; + + WhileStatementSyntax.prototype.kind = function () { + return 158 /* WhileStatement */; + }; + + WhileStatementSyntax.prototype.childCount = function () { + return 5; + }; + + WhileStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.whileKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + WhileStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + WhileStatementSyntax.prototype.isStatement = function () { + return true; + }; + + WhileStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + WhileStatementSyntax.prototype.update = function (whileKeyword, openParenToken, condition, closeParenToken, statement) { + if (this.whileKeyword === whileKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new WhileStatementSyntax(whileKeyword, openParenToken, condition, closeParenToken, statement, this.parsedInStrictMode()); + }; + + WhileStatementSyntax.create1 = function (condition, statement) { + return new WhileStatementSyntax(TypeScript.Syntax.token(42 /* WhileKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + WhileStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + WhileStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + WhileStatementSyntax.prototype.withWhileKeyword = function (whileKeyword) { + return this.update(whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.whileKeyword, openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.whileKeyword, this.openParenToken, condition, this.closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.whileKeyword, this.openParenToken, this.condition, closeParenToken, this.statement); + }; + + WhileStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, statement); + }; + + WhileStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return WhileStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.WhileStatementSyntax = WhileStatementSyntax; + + var WithStatementSyntax = (function (_super) { + __extends(WithStatementSyntax, _super); + function WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.withKeyword = withKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.statement = statement; + } + WithStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitWithStatement(this); + }; + + WithStatementSyntax.prototype.kind = function () { + return 163 /* WithStatement */; + }; + + WithStatementSyntax.prototype.childCount = function () { + return 5; + }; + + WithStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.withKeyword; + case 1: + return this.openParenToken; + case 2: + return this.condition; + case 3: + return this.closeParenToken; + case 4: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + WithStatementSyntax.prototype.isStatement = function () { + return true; + }; + + WithStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + WithStatementSyntax.prototype.update = function (withKeyword, openParenToken, condition, closeParenToken, statement) { + if (this.withKeyword === withKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.statement === statement) { + return this; + } + + return new WithStatementSyntax(withKeyword, openParenToken, condition, closeParenToken, statement, this.parsedInStrictMode()); + }; + + WithStatementSyntax.create1 = function (condition, statement) { + return new WithStatementSyntax(TypeScript.Syntax.token(43 /* WithKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), statement, false); + }; + + WithStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + WithStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + WithStatementSyntax.prototype.withWithKeyword = function (withKeyword) { + return this.update(withKeyword, this.openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.withKeyword, openParenToken, this.condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.withKeyword, this.openParenToken, condition, this.closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.withKeyword, this.openParenToken, this.condition, closeParenToken, this.statement); + }; + + WithStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.withKeyword, this.openParenToken, this.condition, this.closeParenToken, statement); + }; + + WithStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.condition.isTypeScriptSpecific()) { + return true; + } + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return WithStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.WithStatementSyntax = WithStatementSyntax; + + var EnumDeclarationSyntax = (function (_super) { + __extends(EnumDeclarationSyntax, _super); + function EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.modifiers = modifiers; + this.enumKeyword = enumKeyword; + this.identifier = identifier; + this.openBraceToken = openBraceToken; + this.enumElements = enumElements; + this.closeBraceToken = closeBraceToken; + } + EnumDeclarationSyntax.prototype.accept = function (visitor) { + return visitor.visitEnumDeclaration(this); + }; + + EnumDeclarationSyntax.prototype.kind = function () { + return 132 /* EnumDeclaration */; + }; + + EnumDeclarationSyntax.prototype.childCount = function () { + return 6; + }; + + EnumDeclarationSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.modifiers; + case 1: + return this.enumKeyword; + case 2: + return this.identifier; + case 3: + return this.openBraceToken; + case 4: + return this.enumElements; + case 5: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EnumDeclarationSyntax.prototype.isModuleElement = function () { + return true; + }; + + EnumDeclarationSyntax.prototype.update = function (modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken) { + if (this.modifiers === modifiers && this.enumKeyword === enumKeyword && this.identifier === identifier && this.openBraceToken === openBraceToken && this.enumElements === enumElements && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new EnumDeclarationSyntax(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken, this.parsedInStrictMode()); + }; + + EnumDeclarationSyntax.create = function (enumKeyword, identifier, openBraceToken, closeBraceToken) { + return new EnumDeclarationSyntax(TypeScript.Syntax.emptyList, enumKeyword, identifier, openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + EnumDeclarationSyntax.create1 = function (identifier) { + return new EnumDeclarationSyntax(TypeScript.Syntax.emptyList, TypeScript.Syntax.token(46 /* EnumKeyword */), identifier, TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + EnumDeclarationSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EnumDeclarationSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EnumDeclarationSyntax.prototype.withModifiers = function (modifiers) { + return this.update(modifiers, this.enumKeyword, this.identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withModifier = function (modifier) { + return this.withModifiers(TypeScript.Syntax.list([modifier])); + }; + + EnumDeclarationSyntax.prototype.withEnumKeyword = function (enumKeyword) { + return this.update(this.modifiers, enumKeyword, this.identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.modifiers, this.enumKeyword, identifier, this.openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, openBraceToken, this.enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withEnumElements = function (enumElements) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, this.openBraceToken, enumElements, this.closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.withEnumElement = function (enumElement) { + return this.withEnumElements(TypeScript.Syntax.separatedList([enumElement])); + }; + + EnumDeclarationSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.modifiers, this.enumKeyword, this.identifier, this.openBraceToken, this.enumElements, closeBraceToken); + }; + + EnumDeclarationSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return EnumDeclarationSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EnumDeclarationSyntax = EnumDeclarationSyntax; + + var EnumElementSyntax = (function (_super) { + __extends(EnumElementSyntax, _super); + function EnumElementSyntax(propertyName, equalsValueClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.equalsValueClause = equalsValueClause; + } + EnumElementSyntax.prototype.accept = function (visitor) { + return visitor.visitEnumElement(this); + }; + + EnumElementSyntax.prototype.kind = function () { + return 243 /* EnumElement */; + }; + + EnumElementSyntax.prototype.childCount = function () { + return 2; + }; + + EnumElementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.equalsValueClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EnumElementSyntax.prototype.update = function (propertyName, equalsValueClause) { + if (this.propertyName === propertyName && this.equalsValueClause === equalsValueClause) { + return this; + } + + return new EnumElementSyntax(propertyName, equalsValueClause, this.parsedInStrictMode()); + }; + + EnumElementSyntax.create = function (propertyName) { + return new EnumElementSyntax(propertyName, null, false); + }; + + EnumElementSyntax.create1 = function (propertyName) { + return new EnumElementSyntax(propertyName, null, false); + }; + + EnumElementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EnumElementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EnumElementSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.equalsValueClause); + }; + + EnumElementSyntax.prototype.withEqualsValueClause = function (equalsValueClause) { + return this.update(this.propertyName, equalsValueClause); + }; + + EnumElementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.equalsValueClause !== null && this.equalsValueClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return EnumElementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EnumElementSyntax = EnumElementSyntax; + + var CastExpressionSyntax = (function (_super) { + __extends(CastExpressionSyntax, _super); + function CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.lessThanToken = lessThanToken; + this.type = type; + this.greaterThanToken = greaterThanToken; + this.expression = expression; + } + CastExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitCastExpression(this); + }; + + CastExpressionSyntax.prototype.kind = function () { + return 220 /* CastExpression */; + }; + + CastExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + CastExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.lessThanToken; + case 1: + return this.type; + case 2: + return this.greaterThanToken; + case 3: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CastExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + CastExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + CastExpressionSyntax.prototype.update = function (lessThanToken, type, greaterThanToken, expression) { + if (this.lessThanToken === lessThanToken && this.type === type && this.greaterThanToken === greaterThanToken && this.expression === expression) { + return this; + } + + return new CastExpressionSyntax(lessThanToken, type, greaterThanToken, expression, this.parsedInStrictMode()); + }; + + CastExpressionSyntax.create1 = function (type, expression) { + return new CastExpressionSyntax(TypeScript.Syntax.token(80 /* LessThanToken */), type, TypeScript.Syntax.token(81 /* GreaterThanToken */), expression, false); + }; + + CastExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CastExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CastExpressionSyntax.prototype.withLessThanToken = function (lessThanToken) { + return this.update(lessThanToken, this.type, this.greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withType = function (type) { + return this.update(this.lessThanToken, type, this.greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withGreaterThanToken = function (greaterThanToken) { + return this.update(this.lessThanToken, this.type, greaterThanToken, this.expression); + }; + + CastExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.lessThanToken, this.type, this.greaterThanToken, expression); + }; + + CastExpressionSyntax.prototype.isTypeScriptSpecific = function () { + return true; + }; + return CastExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CastExpressionSyntax = CastExpressionSyntax; + + var ObjectLiteralExpressionSyntax = (function (_super) { + __extends(ObjectLiteralExpressionSyntax, _super); + function ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.openBraceToken = openBraceToken; + this.propertyAssignments = propertyAssignments; + this.closeBraceToken = closeBraceToken; + } + ObjectLiteralExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitObjectLiteralExpression(this); + }; + + ObjectLiteralExpressionSyntax.prototype.kind = function () { + return 215 /* ObjectLiteralExpression */; + }; + + ObjectLiteralExpressionSyntax.prototype.childCount = function () { + return 3; + }; + + ObjectLiteralExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.openBraceToken; + case 1: + return this.propertyAssignments; + case 2: + return this.closeBraceToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ObjectLiteralExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + ObjectLiteralExpressionSyntax.prototype.update = function (openBraceToken, propertyAssignments, closeBraceToken) { + if (this.openBraceToken === openBraceToken && this.propertyAssignments === propertyAssignments && this.closeBraceToken === closeBraceToken) { + return this; + } + + return new ObjectLiteralExpressionSyntax(openBraceToken, propertyAssignments, closeBraceToken, this.parsedInStrictMode()); + }; + + ObjectLiteralExpressionSyntax.create = function (openBraceToken, closeBraceToken) { + return new ObjectLiteralExpressionSyntax(openBraceToken, TypeScript.Syntax.emptySeparatedList, closeBraceToken, false); + }; + + ObjectLiteralExpressionSyntax.create1 = function () { + return new ObjectLiteralExpressionSyntax(TypeScript.Syntax.token(70 /* OpenBraceToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.token(71 /* CloseBraceToken */), false); + }; + + ObjectLiteralExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + ObjectLiteralExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + ObjectLiteralExpressionSyntax.prototype.withOpenBraceToken = function (openBraceToken) { + return this.update(openBraceToken, this.propertyAssignments, this.closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.withPropertyAssignments = function (propertyAssignments) { + return this.update(this.openBraceToken, propertyAssignments, this.closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.withPropertyAssignment = function (propertyAssignment) { + return this.withPropertyAssignments(TypeScript.Syntax.separatedList([propertyAssignment])); + }; + + ObjectLiteralExpressionSyntax.prototype.withCloseBraceToken = function (closeBraceToken) { + return this.update(this.openBraceToken, this.propertyAssignments, closeBraceToken); + }; + + ObjectLiteralExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.propertyAssignments.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return ObjectLiteralExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.ObjectLiteralExpressionSyntax = ObjectLiteralExpressionSyntax; + + var SimplePropertyAssignmentSyntax = (function (_super) { + __extends(SimplePropertyAssignmentSyntax, _super); + function SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.colonToken = colonToken; + this.expression = expression; + } + SimplePropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitSimplePropertyAssignment(this); + }; + + SimplePropertyAssignmentSyntax.prototype.kind = function () { + return 240 /* SimplePropertyAssignment */; + }; + + SimplePropertyAssignmentSyntax.prototype.childCount = function () { + return 3; + }; + + SimplePropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.colonToken; + case 2: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SimplePropertyAssignmentSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + SimplePropertyAssignmentSyntax.prototype.update = function (propertyName, colonToken, expression) { + if (this.propertyName === propertyName && this.colonToken === colonToken && this.expression === expression) { + return this; + } + + return new SimplePropertyAssignmentSyntax(propertyName, colonToken, expression, this.parsedInStrictMode()); + }; + + SimplePropertyAssignmentSyntax.create1 = function (propertyName, expression) { + return new SimplePropertyAssignmentSyntax(propertyName, TypeScript.Syntax.token(106 /* ColonToken */), expression, false); + }; + + SimplePropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + SimplePropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + SimplePropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.colonToken, this.expression); + }; + + SimplePropertyAssignmentSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.propertyName, colonToken, this.expression); + }; + + SimplePropertyAssignmentSyntax.prototype.withExpression = function (expression) { + return this.update(this.propertyName, this.colonToken, expression); + }; + + SimplePropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return SimplePropertyAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.SimplePropertyAssignmentSyntax = SimplePropertyAssignmentSyntax; + + var FunctionPropertyAssignmentSyntax = (function (_super) { + __extends(FunctionPropertyAssignmentSyntax, _super); + function FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + } + FunctionPropertyAssignmentSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionPropertyAssignment(this); + }; + + FunctionPropertyAssignmentSyntax.prototype.kind = function () { + return 241 /* FunctionPropertyAssignment */; + }; + + FunctionPropertyAssignmentSyntax.prototype.childCount = function () { + return 3; + }; + + FunctionPropertyAssignmentSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.propertyName; + case 1: + return this.callSignature; + case 2: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionPropertyAssignmentSyntax.prototype.isPropertyAssignment = function () { + return true; + }; + + FunctionPropertyAssignmentSyntax.prototype.update = function (propertyName, callSignature, block) { + if (this.propertyName === propertyName && this.callSignature === callSignature && this.block === block) { + return this; + } + + return new FunctionPropertyAssignmentSyntax(propertyName, callSignature, block, this.parsedInStrictMode()); + }; + + FunctionPropertyAssignmentSyntax.create1 = function (propertyName) { + return new FunctionPropertyAssignmentSyntax(propertyName, CallSignatureSyntax.create1(), BlockSyntax.create1(), false); + }; + + FunctionPropertyAssignmentSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionPropertyAssignmentSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionPropertyAssignmentSyntax.prototype.withPropertyName = function (propertyName) { + return this.update(propertyName, this.callSignature, this.block); + }; + + FunctionPropertyAssignmentSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.propertyName, callSignature, this.block); + }; + + FunctionPropertyAssignmentSyntax.prototype.withBlock = function (block) { + return this.update(this.propertyName, this.callSignature, block); + }; + + FunctionPropertyAssignmentSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionPropertyAssignmentSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionPropertyAssignmentSyntax = FunctionPropertyAssignmentSyntax; + + var FunctionExpressionSyntax = (function (_super) { + __extends(FunctionExpressionSyntax, _super); + function FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.functionKeyword = functionKeyword; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + } + FunctionExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitFunctionExpression(this); + }; + + FunctionExpressionSyntax.prototype.kind = function () { + return 222 /* FunctionExpression */; + }; + + FunctionExpressionSyntax.prototype.childCount = function () { + return 4; + }; + + FunctionExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.functionKeyword; + case 1: + return this.identifier; + case 2: + return this.callSignature; + case 3: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FunctionExpressionSyntax.prototype.isPrimaryExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isMemberExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isPostfixExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + FunctionExpressionSyntax.prototype.update = function (functionKeyword, identifier, callSignature, block) { + if (this.functionKeyword === functionKeyword && this.identifier === identifier && this.callSignature === callSignature && this.block === block) { + return this; + } + + return new FunctionExpressionSyntax(functionKeyword, identifier, callSignature, block, this.parsedInStrictMode()); + }; + + FunctionExpressionSyntax.create = function (functionKeyword, callSignature, block) { + return new FunctionExpressionSyntax(functionKeyword, null, callSignature, block, false); + }; + + FunctionExpressionSyntax.create1 = function () { + return new FunctionExpressionSyntax(TypeScript.Syntax.token(27 /* FunctionKeyword */), null, CallSignatureSyntax.create1(), BlockSyntax.create1(), false); + }; + + FunctionExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FunctionExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FunctionExpressionSyntax.prototype.withFunctionKeyword = function (functionKeyword) { + return this.update(functionKeyword, this.identifier, this.callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.functionKeyword, identifier, this.callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withCallSignature = function (callSignature) { + return this.update(this.functionKeyword, this.identifier, callSignature, this.block); + }; + + FunctionExpressionSyntax.prototype.withBlock = function (block) { + return this.update(this.functionKeyword, this.identifier, this.callSignature, block); + }; + + FunctionExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.callSignature.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FunctionExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FunctionExpressionSyntax = FunctionExpressionSyntax; + + var EmptyStatementSyntax = (function (_super) { + __extends(EmptyStatementSyntax, _super); + function EmptyStatementSyntax(semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.semicolonToken = semicolonToken; + } + EmptyStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitEmptyStatement(this); + }; + + EmptyStatementSyntax.prototype.kind = function () { + return 156 /* EmptyStatement */; + }; + + EmptyStatementSyntax.prototype.childCount = function () { + return 1; + }; + + EmptyStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + EmptyStatementSyntax.prototype.isStatement = function () { + return true; + }; + + EmptyStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + EmptyStatementSyntax.prototype.update = function (semicolonToken) { + if (this.semicolonToken === semicolonToken) { + return this; + } + + return new EmptyStatementSyntax(semicolonToken, this.parsedInStrictMode()); + }; + + EmptyStatementSyntax.create1 = function () { + return new EmptyStatementSyntax(TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + EmptyStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + EmptyStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + EmptyStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(semicolonToken); + }; + + EmptyStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return EmptyStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.EmptyStatementSyntax = EmptyStatementSyntax; + + var TryStatementSyntax = (function (_super) { + __extends(TryStatementSyntax, _super); + function TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.tryKeyword = tryKeyword; + this.block = block; + this.catchClause = catchClause; + this.finallyClause = finallyClause; + } + TryStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitTryStatement(this); + }; + + TryStatementSyntax.prototype.kind = function () { + return 159 /* TryStatement */; + }; + + TryStatementSyntax.prototype.childCount = function () { + return 4; + }; + + TryStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.tryKeyword; + case 1: + return this.block; + case 2: + return this.catchClause; + case 3: + return this.finallyClause; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TryStatementSyntax.prototype.isStatement = function () { + return true; + }; + + TryStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + TryStatementSyntax.prototype.update = function (tryKeyword, block, catchClause, finallyClause) { + if (this.tryKeyword === tryKeyword && this.block === block && this.catchClause === catchClause && this.finallyClause === finallyClause) { + return this; + } + + return new TryStatementSyntax(tryKeyword, block, catchClause, finallyClause, this.parsedInStrictMode()); + }; + + TryStatementSyntax.create = function (tryKeyword, block) { + return new TryStatementSyntax(tryKeyword, block, null, null, false); + }; + + TryStatementSyntax.create1 = function () { + return new TryStatementSyntax(TypeScript.Syntax.token(38 /* TryKeyword */), BlockSyntax.create1(), null, null, false); + }; + + TryStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TryStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TryStatementSyntax.prototype.withTryKeyword = function (tryKeyword) { + return this.update(tryKeyword, this.block, this.catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withBlock = function (block) { + return this.update(this.tryKeyword, block, this.catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withCatchClause = function (catchClause) { + return this.update(this.tryKeyword, this.block, catchClause, this.finallyClause); + }; + + TryStatementSyntax.prototype.withFinallyClause = function (finallyClause) { + return this.update(this.tryKeyword, this.block, this.catchClause, finallyClause); + }; + + TryStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.block.isTypeScriptSpecific()) { + return true; + } + if (this.catchClause !== null && this.catchClause.isTypeScriptSpecific()) { + return true; + } + if (this.finallyClause !== null && this.finallyClause.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return TryStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TryStatementSyntax = TryStatementSyntax; + + var CatchClauseSyntax = (function (_super) { + __extends(CatchClauseSyntax, _super); + function CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.catchKeyword = catchKeyword; + this.openParenToken = openParenToken; + this.identifier = identifier; + this.typeAnnotation = typeAnnotation; + this.closeParenToken = closeParenToken; + this.block = block; + } + CatchClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitCatchClause(this); + }; + + CatchClauseSyntax.prototype.kind = function () { + return 236 /* CatchClause */; + }; + + CatchClauseSyntax.prototype.childCount = function () { + return 6; + }; + + CatchClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.catchKeyword; + case 1: + return this.openParenToken; + case 2: + return this.identifier; + case 3: + return this.typeAnnotation; + case 4: + return this.closeParenToken; + case 5: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + CatchClauseSyntax.prototype.update = function (catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block) { + if (this.catchKeyword === catchKeyword && this.openParenToken === openParenToken && this.identifier === identifier && this.typeAnnotation === typeAnnotation && this.closeParenToken === closeParenToken && this.block === block) { + return this; + } + + return new CatchClauseSyntax(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block, this.parsedInStrictMode()); + }; + + CatchClauseSyntax.create = function (catchKeyword, openParenToken, identifier, closeParenToken, block) { + return new CatchClauseSyntax(catchKeyword, openParenToken, identifier, null, closeParenToken, block, false); + }; + + CatchClauseSyntax.create1 = function (identifier) { + return new CatchClauseSyntax(TypeScript.Syntax.token(17 /* CatchKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), identifier, null, TypeScript.Syntax.token(73 /* CloseParenToken */), BlockSyntax.create1(), false); + }; + + CatchClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + CatchClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + CatchClauseSyntax.prototype.withCatchKeyword = function (catchKeyword) { + return this.update(catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.catchKeyword, openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withIdentifier = function (identifier) { + return this.update(this.catchKeyword, this.openParenToken, identifier, this.typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withTypeAnnotation = function (typeAnnotation) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, typeAnnotation, this.closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, closeParenToken, this.block); + }; + + CatchClauseSyntax.prototype.withBlock = function (block) { + return this.update(this.catchKeyword, this.openParenToken, this.identifier, this.typeAnnotation, this.closeParenToken, block); + }; + + CatchClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.typeAnnotation !== null && this.typeAnnotation.isTypeScriptSpecific()) { + return true; + } + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return CatchClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.CatchClauseSyntax = CatchClauseSyntax; + + var FinallyClauseSyntax = (function (_super) { + __extends(FinallyClauseSyntax, _super); + function FinallyClauseSyntax(finallyKeyword, block, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.finallyKeyword = finallyKeyword; + this.block = block; + } + FinallyClauseSyntax.prototype.accept = function (visitor) { + return visitor.visitFinallyClause(this); + }; + + FinallyClauseSyntax.prototype.kind = function () { + return 237 /* FinallyClause */; + }; + + FinallyClauseSyntax.prototype.childCount = function () { + return 2; + }; + + FinallyClauseSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.finallyKeyword; + case 1: + return this.block; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + FinallyClauseSyntax.prototype.update = function (finallyKeyword, block) { + if (this.finallyKeyword === finallyKeyword && this.block === block) { + return this; + } + + return new FinallyClauseSyntax(finallyKeyword, block, this.parsedInStrictMode()); + }; + + FinallyClauseSyntax.create1 = function () { + return new FinallyClauseSyntax(TypeScript.Syntax.token(25 /* FinallyKeyword */), BlockSyntax.create1(), false); + }; + + FinallyClauseSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + FinallyClauseSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + FinallyClauseSyntax.prototype.withFinallyKeyword = function (finallyKeyword) { + return this.update(finallyKeyword, this.block); + }; + + FinallyClauseSyntax.prototype.withBlock = function (block) { + return this.update(this.finallyKeyword, block); + }; + + FinallyClauseSyntax.prototype.isTypeScriptSpecific = function () { + if (this.block.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return FinallyClauseSyntax; + })(TypeScript.SyntaxNode); + TypeScript.FinallyClauseSyntax = FinallyClauseSyntax; + + var LabeledStatementSyntax = (function (_super) { + __extends(LabeledStatementSyntax, _super); + function LabeledStatementSyntax(identifier, colonToken, statement, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.identifier = identifier; + this.colonToken = colonToken; + this.statement = statement; + } + LabeledStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitLabeledStatement(this); + }; + + LabeledStatementSyntax.prototype.kind = function () { + return 160 /* LabeledStatement */; + }; + + LabeledStatementSyntax.prototype.childCount = function () { + return 3; + }; + + LabeledStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.identifier; + case 1: + return this.colonToken; + case 2: + return this.statement; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + LabeledStatementSyntax.prototype.isStatement = function () { + return true; + }; + + LabeledStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + LabeledStatementSyntax.prototype.update = function (identifier, colonToken, statement) { + if (this.identifier === identifier && this.colonToken === colonToken && this.statement === statement) { + return this; + } + + return new LabeledStatementSyntax(identifier, colonToken, statement, this.parsedInStrictMode()); + }; + + LabeledStatementSyntax.create1 = function (identifier, statement) { + return new LabeledStatementSyntax(identifier, TypeScript.Syntax.token(106 /* ColonToken */), statement, false); + }; + + LabeledStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + LabeledStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + LabeledStatementSyntax.prototype.withIdentifier = function (identifier) { + return this.update(identifier, this.colonToken, this.statement); + }; + + LabeledStatementSyntax.prototype.withColonToken = function (colonToken) { + return this.update(this.identifier, colonToken, this.statement); + }; + + LabeledStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.identifier, this.colonToken, statement); + }; + + LabeledStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return LabeledStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.LabeledStatementSyntax = LabeledStatementSyntax; + + var DoStatementSyntax = (function (_super) { + __extends(DoStatementSyntax, _super); + function DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.doKeyword = doKeyword; + this.statement = statement; + this.whileKeyword = whileKeyword; + this.openParenToken = openParenToken; + this.condition = condition; + this.closeParenToken = closeParenToken; + this.semicolonToken = semicolonToken; + } + DoStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitDoStatement(this); + }; + + DoStatementSyntax.prototype.kind = function () { + return 161 /* DoStatement */; + }; + + DoStatementSyntax.prototype.childCount = function () { + return 7; + }; + + DoStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.doKeyword; + case 1: + return this.statement; + case 2: + return this.whileKeyword; + case 3: + return this.openParenToken; + case 4: + return this.condition; + case 5: + return this.closeParenToken; + case 6: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DoStatementSyntax.prototype.isIterationStatement = function () { + return true; + }; + + DoStatementSyntax.prototype.isStatement = function () { + return true; + }; + + DoStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + DoStatementSyntax.prototype.update = function (doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken) { + if (this.doKeyword === doKeyword && this.statement === statement && this.whileKeyword === whileKeyword && this.openParenToken === openParenToken && this.condition === condition && this.closeParenToken === closeParenToken && this.semicolonToken === semicolonToken) { + return this; + } + + return new DoStatementSyntax(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken, this.parsedInStrictMode()); + }; + + DoStatementSyntax.create1 = function (statement, condition) { + return new DoStatementSyntax(TypeScript.Syntax.token(22 /* DoKeyword */), statement, TypeScript.Syntax.token(42 /* WhileKeyword */), TypeScript.Syntax.token(72 /* OpenParenToken */), condition, TypeScript.Syntax.token(73 /* CloseParenToken */), TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + DoStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DoStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DoStatementSyntax.prototype.withDoKeyword = function (doKeyword) { + return this.update(doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withStatement = function (statement) { + return this.update(this.doKeyword, statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withWhileKeyword = function (whileKeyword) { + return this.update(this.doKeyword, this.statement, whileKeyword, this.openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withOpenParenToken = function (openParenToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, openParenToken, this.condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withCondition = function (condition) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, condition, this.closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withCloseParenToken = function (closeParenToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, closeParenToken, this.semicolonToken); + }; + + DoStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.doKeyword, this.statement, this.whileKeyword, this.openParenToken, this.condition, this.closeParenToken, semicolonToken); + }; + + DoStatementSyntax.prototype.isTypeScriptSpecific = function () { + if (this.statement.isTypeScriptSpecific()) { + return true; + } + if (this.condition.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DoStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DoStatementSyntax = DoStatementSyntax; + + var TypeOfExpressionSyntax = (function (_super) { + __extends(TypeOfExpressionSyntax, _super); + function TypeOfExpressionSyntax(typeOfKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.typeOfKeyword = typeOfKeyword; + this.expression = expression; + } + TypeOfExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitTypeOfExpression(this); + }; + + TypeOfExpressionSyntax.prototype.kind = function () { + return 171 /* TypeOfExpression */; + }; + + TypeOfExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + TypeOfExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.typeOfKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + TypeOfExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + TypeOfExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + TypeOfExpressionSyntax.prototype.update = function (typeOfKeyword, expression) { + if (this.typeOfKeyword === typeOfKeyword && this.expression === expression) { + return this; + } + + return new TypeOfExpressionSyntax(typeOfKeyword, expression, this.parsedInStrictMode()); + }; + + TypeOfExpressionSyntax.create1 = function (expression) { + return new TypeOfExpressionSyntax(TypeScript.Syntax.token(39 /* TypeOfKeyword */), expression, false); + }; + + TypeOfExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + TypeOfExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + TypeOfExpressionSyntax.prototype.withTypeOfKeyword = function (typeOfKeyword) { + return this.update(typeOfKeyword, this.expression); + }; + + TypeOfExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.typeOfKeyword, expression); + }; + + TypeOfExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return TypeOfExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.TypeOfExpressionSyntax = TypeOfExpressionSyntax; + + var DeleteExpressionSyntax = (function (_super) { + __extends(DeleteExpressionSyntax, _super); + function DeleteExpressionSyntax(deleteKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.deleteKeyword = deleteKeyword; + this.expression = expression; + } + DeleteExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitDeleteExpression(this); + }; + + DeleteExpressionSyntax.prototype.kind = function () { + return 170 /* DeleteExpression */; + }; + + DeleteExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + DeleteExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.deleteKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DeleteExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + DeleteExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + DeleteExpressionSyntax.prototype.update = function (deleteKeyword, expression) { + if (this.deleteKeyword === deleteKeyword && this.expression === expression) { + return this; + } + + return new DeleteExpressionSyntax(deleteKeyword, expression, this.parsedInStrictMode()); + }; + + DeleteExpressionSyntax.create1 = function (expression) { + return new DeleteExpressionSyntax(TypeScript.Syntax.token(21 /* DeleteKeyword */), expression, false); + }; + + DeleteExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DeleteExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DeleteExpressionSyntax.prototype.withDeleteKeyword = function (deleteKeyword) { + return this.update(deleteKeyword, this.expression); + }; + + DeleteExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.deleteKeyword, expression); + }; + + DeleteExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return DeleteExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DeleteExpressionSyntax = DeleteExpressionSyntax; + + var VoidExpressionSyntax = (function (_super) { + __extends(VoidExpressionSyntax, _super); + function VoidExpressionSyntax(voidKeyword, expression, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.voidKeyword = voidKeyword; + this.expression = expression; + } + VoidExpressionSyntax.prototype.accept = function (visitor) { + return visitor.visitVoidExpression(this); + }; + + VoidExpressionSyntax.prototype.kind = function () { + return 172 /* VoidExpression */; + }; + + VoidExpressionSyntax.prototype.childCount = function () { + return 2; + }; + + VoidExpressionSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.voidKeyword; + case 1: + return this.expression; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + VoidExpressionSyntax.prototype.isUnaryExpression = function () { + return true; + }; + + VoidExpressionSyntax.prototype.isExpression = function () { + return true; + }; + + VoidExpressionSyntax.prototype.update = function (voidKeyword, expression) { + if (this.voidKeyword === voidKeyword && this.expression === expression) { + return this; + } + + return new VoidExpressionSyntax(voidKeyword, expression, this.parsedInStrictMode()); + }; + + VoidExpressionSyntax.create1 = function (expression) { + return new VoidExpressionSyntax(TypeScript.Syntax.token(41 /* VoidKeyword */), expression, false); + }; + + VoidExpressionSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + VoidExpressionSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + VoidExpressionSyntax.prototype.withVoidKeyword = function (voidKeyword) { + return this.update(voidKeyword, this.expression); + }; + + VoidExpressionSyntax.prototype.withExpression = function (expression) { + return this.update(this.voidKeyword, expression); + }; + + VoidExpressionSyntax.prototype.isTypeScriptSpecific = function () { + if (this.expression.isTypeScriptSpecific()) { + return true; + } + return false; + }; + return VoidExpressionSyntax; + })(TypeScript.SyntaxNode); + TypeScript.VoidExpressionSyntax = VoidExpressionSyntax; + + var DebuggerStatementSyntax = (function (_super) { + __extends(DebuggerStatementSyntax, _super); + function DebuggerStatementSyntax(debuggerKeyword, semicolonToken, parsedInStrictMode) { + _super.call(this, parsedInStrictMode); + this.debuggerKeyword = debuggerKeyword; + this.semicolonToken = semicolonToken; + } + DebuggerStatementSyntax.prototype.accept = function (visitor) { + return visitor.visitDebuggerStatement(this); + }; + + DebuggerStatementSyntax.prototype.kind = function () { + return 162 /* DebuggerStatement */; + }; + + DebuggerStatementSyntax.prototype.childCount = function () { + return 2; + }; + + DebuggerStatementSyntax.prototype.childAt = function (slot) { + switch (slot) { + case 0: + return this.debuggerKeyword; + case 1: + return this.semicolonToken; + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + DebuggerStatementSyntax.prototype.isStatement = function () { + return true; + }; + + DebuggerStatementSyntax.prototype.isModuleElement = function () { + return true; + }; + + DebuggerStatementSyntax.prototype.update = function (debuggerKeyword, semicolonToken) { + if (this.debuggerKeyword === debuggerKeyword && this.semicolonToken === semicolonToken) { + return this; + } + + return new DebuggerStatementSyntax(debuggerKeyword, semicolonToken, this.parsedInStrictMode()); + }; + + DebuggerStatementSyntax.create1 = function () { + return new DebuggerStatementSyntax(TypeScript.Syntax.token(19 /* DebuggerKeyword */), TypeScript.Syntax.token(78 /* SemicolonToken */), false); + }; + + DebuggerStatementSyntax.prototype.withLeadingTrivia = function (trivia) { + return _super.prototype.withLeadingTrivia.call(this, trivia); + }; + + DebuggerStatementSyntax.prototype.withTrailingTrivia = function (trivia) { + return _super.prototype.withTrailingTrivia.call(this, trivia); + }; + + DebuggerStatementSyntax.prototype.withDebuggerKeyword = function (debuggerKeyword) { + return this.update(debuggerKeyword, this.semicolonToken); + }; + + DebuggerStatementSyntax.prototype.withSemicolonToken = function (semicolonToken) { + return this.update(this.debuggerKeyword, semicolonToken); + }; + + DebuggerStatementSyntax.prototype.isTypeScriptSpecific = function () { + return false; + }; + return DebuggerStatementSyntax; + })(TypeScript.SyntaxNode); + TypeScript.DebuggerStatementSyntax = DebuggerStatementSyntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxRewriter = (function () { + function SyntaxRewriter() { + } + SyntaxRewriter.prototype.visitToken = function (token) { + return token; + }; + + SyntaxRewriter.prototype.visitNode = function (node) { + return node.accept(this); + }; + + SyntaxRewriter.prototype.visitNodeOrToken = function (node) { + return node.isToken() ? this.visitToken(node) : this.visitNode(node); + }; + + SyntaxRewriter.prototype.visitList = function (list) { + var newItems = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + var newItem = this.visitNodeOrToken(item); + + if (item !== newItem && newItems === null) { + newItems = []; + for (var j = 0; j < i; j++) { + newItems.push(list.childAt(j)); + } + } + + if (newItems) { + newItems.push(newItem); + } + } + + return newItems === null ? list : TypeScript.Syntax.list(newItems); + }; + + SyntaxRewriter.prototype.visitSeparatedList = function (list) { + var newItems = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + var newItem = item.isToken() ? this.visitToken(item) : this.visitNode(item); + + if (item !== newItem && newItems === null) { + newItems = []; + for (var j = 0; j < i; j++) { + newItems.push(list.childAt(j)); + } + } + + if (newItems) { + newItems.push(newItem); + } + } + + return newItems === null ? list : TypeScript.Syntax.separatedList(newItems); + }; + + SyntaxRewriter.prototype.visitSourceUnit = function (node) { + return node.update(this.visitList(node.moduleElements), this.visitToken(node.endOfFileToken)); + }; + + SyntaxRewriter.prototype.visitExternalModuleReference = function (node) { + return node.update(this.visitToken(node.requireKeyword), this.visitToken(node.openParenToken), this.visitToken(node.stringLiteral), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitModuleNameModuleReference = function (node) { + return node.update(this.visitNodeOrToken(node.moduleName)); + }; + + SyntaxRewriter.prototype.visitImportDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.importKeyword), this.visitToken(node.identifier), this.visitToken(node.equalsToken), this.visitNodeOrToken(node.moduleReference), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitExportAssignment = function (node) { + return node.update(this.visitToken(node.exportKeyword), this.visitToken(node.equalsToken), this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitClassDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.classKeyword), this.visitToken(node.identifier), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitList(node.heritageClauses), this.visitToken(node.openBraceToken), this.visitList(node.classElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitInterfaceDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.interfaceKeyword), this.visitToken(node.identifier), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitList(node.heritageClauses), this.visitNode(node.body)); + }; + + SyntaxRewriter.prototype.visitHeritageClause = function (node) { + return node.update(node.kind(), this.visitToken(node.extendsOrImplementsKeyword), this.visitSeparatedList(node.typeNames)); + }; + + SyntaxRewriter.prototype.visitModuleDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.moduleKeyword), node.name === null ? null : this.visitNodeOrToken(node.name), node.stringLiteral === null ? null : this.visitToken(node.stringLiteral), this.visitToken(node.openBraceToken), this.visitList(node.moduleElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitFunctionDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.functionKeyword), this.visitToken(node.identifier), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitVariableStatement = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.variableDeclaration), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitVariableDeclaration = function (node) { + return node.update(this.visitToken(node.varKeyword), this.visitSeparatedList(node.variableDeclarators)); + }; + + SyntaxRewriter.prototype.visitVariableDeclarator = function (node) { + return node.update(this.visitToken(node.propertyName), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitEqualsValueClause = function (node) { + return node.update(this.visitToken(node.equalsToken), this.visitNodeOrToken(node.value)); + }; + + SyntaxRewriter.prototype.visitPrefixUnaryExpression = function (node) { + return node.update(node.kind(), this.visitToken(node.operatorToken), this.visitNodeOrToken(node.operand)); + }; + + SyntaxRewriter.prototype.visitArrayLiteralExpression = function (node) { + return node.update(this.visitToken(node.openBracketToken), this.visitSeparatedList(node.expressions), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitOmittedExpression = function (node) { + return node; + }; + + SyntaxRewriter.prototype.visitParenthesizedExpression = function (node) { + return node.update(this.visitToken(node.openParenToken), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitSimpleArrowFunctionExpression = function (node) { + return node.update(this.visitToken(node.identifier), this.visitToken(node.equalsGreaterThanToken), node.block === null ? null : this.visitNode(node.block), node.expression === null ? null : this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + return node.update(this.visitNode(node.callSignature), this.visitToken(node.equalsGreaterThanToken), node.block === null ? null : this.visitNode(node.block), node.expression === null ? null : this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitQualifiedName = function (node) { + return node.update(this.visitNodeOrToken(node.left), this.visitToken(node.dotToken), this.visitToken(node.right)); + }; + + SyntaxRewriter.prototype.visitTypeArgumentList = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitSeparatedList(node.typeArguments), this.visitToken(node.greaterThanToken)); + }; + + SyntaxRewriter.prototype.visitConstructorType = function (node) { + return node.update(this.visitToken(node.newKeyword), node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitFunctionType = function (node) { + return node.update(node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), this.visitToken(node.equalsGreaterThanToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitObjectType = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitSeparatedList(node.typeMembers), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitArrayType = function (node) { + return node.update(this.visitNodeOrToken(node.type), this.visitToken(node.openBracketToken), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitGenericType = function (node) { + return node.update(this.visitNodeOrToken(node.name), this.visitNode(node.typeArgumentList)); + }; + + SyntaxRewriter.prototype.visitTypeQuery = function (node) { + return node.update(this.visitToken(node.typeOfKeyword), this.visitNodeOrToken(node.name)); + }; + + SyntaxRewriter.prototype.visitTypeAnnotation = function (node) { + return node.update(this.visitToken(node.colonToken), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitBlock = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitList(node.statements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitParameter = function (node) { + return node.update(node.dotDotDotToken === null ? null : this.visitToken(node.dotDotDotToken), this.visitList(node.modifiers), this.visitToken(node.identifier), node.questionToken === null ? null : this.visitToken(node.questionToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitMemberAccessExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.dotToken), this.visitToken(node.name)); + }; + + SyntaxRewriter.prototype.visitPostfixUnaryExpression = function (node) { + return node.update(node.kind(), this.visitNodeOrToken(node.operand), this.visitToken(node.operatorToken)); + }; + + SyntaxRewriter.prototype.visitElementAccessExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.openBracketToken), this.visitNodeOrToken(node.argumentExpression), this.visitToken(node.closeBracketToken)); + }; + + SyntaxRewriter.prototype.visitInvocationExpression = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitNode(node.argumentList)); + }; + + SyntaxRewriter.prototype.visitArgumentList = function (node) { + return node.update(node.typeArgumentList === null ? null : this.visitNode(node.typeArgumentList), this.visitToken(node.openParenToken), this.visitSeparatedList(node.arguments), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitBinaryExpression = function (node) { + return node.update(node.kind(), this.visitNodeOrToken(node.left), this.visitToken(node.operatorToken), this.visitNodeOrToken(node.right)); + }; + + SyntaxRewriter.prototype.visitConditionalExpression = function (node) { + return node.update(this.visitNodeOrToken(node.condition), this.visitToken(node.questionToken), this.visitNodeOrToken(node.whenTrue), this.visitToken(node.colonToken), this.visitNodeOrToken(node.whenFalse)); + }; + + SyntaxRewriter.prototype.visitConstructSignature = function (node) { + return node.update(this.visitToken(node.newKeyword), this.visitNode(node.callSignature)); + }; + + SyntaxRewriter.prototype.visitMethodSignature = function (node) { + return node.update(this.visitToken(node.propertyName), node.questionToken === null ? null : this.visitToken(node.questionToken), this.visitNode(node.callSignature)); + }; + + SyntaxRewriter.prototype.visitIndexSignature = function (node) { + return node.update(this.visitToken(node.openBracketToken), this.visitNode(node.parameter), this.visitToken(node.closeBracketToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitPropertySignature = function (node) { + return node.update(this.visitToken(node.propertyName), node.questionToken === null ? null : this.visitToken(node.questionToken), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitCallSignature = function (node) { + return node.update(node.typeParameterList === null ? null : this.visitNode(node.typeParameterList), this.visitNode(node.parameterList), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation)); + }; + + SyntaxRewriter.prototype.visitParameterList = function (node) { + return node.update(this.visitToken(node.openParenToken), this.visitSeparatedList(node.parameters), this.visitToken(node.closeParenToken)); + }; + + SyntaxRewriter.prototype.visitTypeParameterList = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitSeparatedList(node.typeParameters), this.visitToken(node.greaterThanToken)); + }; + + SyntaxRewriter.prototype.visitTypeParameter = function (node) { + return node.update(this.visitToken(node.identifier), node.constraint === null ? null : this.visitNode(node.constraint)); + }; + + SyntaxRewriter.prototype.visitConstraint = function (node) { + return node.update(this.visitToken(node.extendsKeyword), this.visitNodeOrToken(node.type)); + }; + + SyntaxRewriter.prototype.visitElseClause = function (node) { + return node.update(this.visitToken(node.elseKeyword), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitIfStatement = function (node) { + return node.update(this.visitToken(node.ifKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement), node.elseClause === null ? null : this.visitNode(node.elseClause)); + }; + + SyntaxRewriter.prototype.visitExpressionStatement = function (node) { + return node.update(this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitConstructorDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.constructorKeyword), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitMemberFunctionDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.propertyName), this.visitNode(node.callSignature), node.block === null ? null : this.visitNode(node.block), node.semicolonToken === null ? null : this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitGetAccessor = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.getKeyword), this.visitToken(node.propertyName), this.visitNode(node.parameterList), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitSetAccessor = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.setKeyword), this.visitToken(node.propertyName), this.visitNode(node.parameterList), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitMemberVariableDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.variableDeclarator), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitIndexMemberDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitNode(node.indexSignature), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitThrowStatement = function (node) { + return node.update(this.visitToken(node.throwKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitReturnStatement = function (node) { + return node.update(this.visitToken(node.returnKeyword), node.expression === null ? null : this.visitNodeOrToken(node.expression), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitObjectCreationExpression = function (node) { + return node.update(this.visitToken(node.newKeyword), this.visitNodeOrToken(node.expression), node.argumentList === null ? null : this.visitNode(node.argumentList)); + }; + + SyntaxRewriter.prototype.visitSwitchStatement = function (node) { + return node.update(this.visitToken(node.switchKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken), this.visitToken(node.openBraceToken), this.visitList(node.switchClauses), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitCaseSwitchClause = function (node) { + return node.update(this.visitToken(node.caseKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.colonToken), this.visitList(node.statements)); + }; + + SyntaxRewriter.prototype.visitDefaultSwitchClause = function (node) { + return node.update(this.visitToken(node.defaultKeyword), this.visitToken(node.colonToken), this.visitList(node.statements)); + }; + + SyntaxRewriter.prototype.visitBreakStatement = function (node) { + return node.update(this.visitToken(node.breakKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitContinueStatement = function (node) { + return node.update(this.visitToken(node.continueKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitForStatement = function (node) { + return node.update(this.visitToken(node.forKeyword), this.visitToken(node.openParenToken), node.variableDeclaration === null ? null : this.visitNode(node.variableDeclaration), node.initializer === null ? null : this.visitNodeOrToken(node.initializer), this.visitToken(node.firstSemicolonToken), node.condition === null ? null : this.visitNodeOrToken(node.condition), this.visitToken(node.secondSemicolonToken), node.incrementor === null ? null : this.visitNodeOrToken(node.incrementor), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitForInStatement = function (node) { + return node.update(this.visitToken(node.forKeyword), this.visitToken(node.openParenToken), node.variableDeclaration === null ? null : this.visitNode(node.variableDeclaration), node.left === null ? null : this.visitNodeOrToken(node.left), this.visitToken(node.inKeyword), this.visitNodeOrToken(node.expression), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitWhileStatement = function (node) { + return node.update(this.visitToken(node.whileKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitWithStatement = function (node) { + return node.update(this.visitToken(node.withKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitEnumDeclaration = function (node) { + return node.update(this.visitList(node.modifiers), this.visitToken(node.enumKeyword), this.visitToken(node.identifier), this.visitToken(node.openBraceToken), this.visitSeparatedList(node.enumElements), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitEnumElement = function (node) { + return node.update(this.visitToken(node.propertyName), node.equalsValueClause === null ? null : this.visitNode(node.equalsValueClause)); + }; + + SyntaxRewriter.prototype.visitCastExpression = function (node) { + return node.update(this.visitToken(node.lessThanToken), this.visitNodeOrToken(node.type), this.visitToken(node.greaterThanToken), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitObjectLiteralExpression = function (node) { + return node.update(this.visitToken(node.openBraceToken), this.visitSeparatedList(node.propertyAssignments), this.visitToken(node.closeBraceToken)); + }; + + SyntaxRewriter.prototype.visitSimplePropertyAssignment = function (node) { + return node.update(this.visitToken(node.propertyName), this.visitToken(node.colonToken), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitFunctionPropertyAssignment = function (node) { + return node.update(this.visitToken(node.propertyName), this.visitNode(node.callSignature), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitFunctionExpression = function (node) { + return node.update(this.visitToken(node.functionKeyword), node.identifier === null ? null : this.visitToken(node.identifier), this.visitNode(node.callSignature), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitEmptyStatement = function (node) { + return node.update(this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitTryStatement = function (node) { + return node.update(this.visitToken(node.tryKeyword), this.visitNode(node.block), node.catchClause === null ? null : this.visitNode(node.catchClause), node.finallyClause === null ? null : this.visitNode(node.finallyClause)); + }; + + SyntaxRewriter.prototype.visitCatchClause = function (node) { + return node.update(this.visitToken(node.catchKeyword), this.visitToken(node.openParenToken), this.visitToken(node.identifier), node.typeAnnotation === null ? null : this.visitNode(node.typeAnnotation), this.visitToken(node.closeParenToken), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitFinallyClause = function (node) { + return node.update(this.visitToken(node.finallyKeyword), this.visitNode(node.block)); + }; + + SyntaxRewriter.prototype.visitLabeledStatement = function (node) { + return node.update(this.visitToken(node.identifier), this.visitToken(node.colonToken), this.visitNodeOrToken(node.statement)); + }; + + SyntaxRewriter.prototype.visitDoStatement = function (node) { + return node.update(this.visitToken(node.doKeyword), this.visitNodeOrToken(node.statement), this.visitToken(node.whileKeyword), this.visitToken(node.openParenToken), this.visitNodeOrToken(node.condition), this.visitToken(node.closeParenToken), this.visitToken(node.semicolonToken)); + }; + + SyntaxRewriter.prototype.visitTypeOfExpression = function (node) { + return node.update(this.visitToken(node.typeOfKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitDeleteExpression = function (node) { + return node.update(this.visitToken(node.deleteKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitVoidExpression = function (node) { + return node.update(this.visitToken(node.voidKeyword), this.visitNodeOrToken(node.expression)); + }; + + SyntaxRewriter.prototype.visitDebuggerStatement = function (node) { + return node.update(this.visitToken(node.debuggerKeyword), this.visitToken(node.semicolonToken)); + }; + return SyntaxRewriter; + })(); + TypeScript.SyntaxRewriter = SyntaxRewriter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxDedenter = (function (_super) { + __extends(SyntaxDedenter, _super); + function SyntaxDedenter(dedentFirstToken, dedentationAmount, minimumIndent, options) { + _super.call(this); + this.dedentationAmount = dedentationAmount; + this.minimumIndent = minimumIndent; + this.options = options; + this.lastTriviaWasNewLine = dedentFirstToken; + } + SyntaxDedenter.prototype.abort = function () { + this.lastTriviaWasNewLine = false; + this.dedentationAmount = 0; + }; + + SyntaxDedenter.prototype.isAborted = function () { + return this.dedentationAmount === 0; + }; + + SyntaxDedenter.prototype.visitToken = function (token) { + if (token.width() === 0) { + return token; + } + + var result = token; + if (this.lastTriviaWasNewLine) { + result = token.withLeadingTrivia(this.dedentTriviaList(token.leadingTrivia())); + } + + if (this.isAborted()) { + return token; + } + + this.lastTriviaWasNewLine = token.hasTrailingNewLine(); + return result; + }; + + SyntaxDedenter.prototype.dedentTriviaList = function (triviaList) { + var result = []; + var dedentNextWhitespace = true; + + for (var i = 0, n = triviaList.count(); i < n && !this.isAborted(); i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + var dedentThisTrivia = dedentNextWhitespace; + dedentNextWhitespace = false; + + if (dedentThisTrivia) { + if (trivia.kind() === 4 /* WhitespaceTrivia */) { + var hasFollowingNewLine = (i < triviaList.count() - 1) && triviaList.syntaxTriviaAt(i + 1).kind() === 5 /* NewLineTrivia */; + result.push(this.dedentWhitespace(trivia, hasFollowingNewLine)); + continue; + } else if (trivia.kind() !== 5 /* NewLineTrivia */) { + this.abort(); + break; + } + } + + if (trivia.kind() === 6 /* MultiLineCommentTrivia */) { + result.push(this.dedentMultiLineComment(trivia)); + continue; + } + + result.push(trivia); + if (trivia.kind() === 5 /* NewLineTrivia */) { + dedentNextWhitespace = true; + } + } + + if (dedentNextWhitespace) { + this.abort(); + } + + if (this.isAborted()) { + return triviaList; + } + + return TypeScript.Syntax.triviaList(result); + }; + + SyntaxDedenter.prototype.dedentSegment = function (segment, hasFollowingNewLineTrivia) { + var firstNonWhitespacePosition = TypeScript.Indentation.firstNonWhitespacePosition(segment); + + if (firstNonWhitespacePosition === segment.length) { + if (hasFollowingNewLineTrivia) { + return ""; + } + } else if (TypeScript.CharacterInfo.isLineTerminator(segment.charCodeAt(firstNonWhitespacePosition))) { + return segment.substring(firstNonWhitespacePosition); + } + + var firstNonWhitespaceColumn = TypeScript.Indentation.columnForPositionInString(segment, firstNonWhitespacePosition, this.options); + + var newFirstNonWhitespaceColumn = TypeScript.MathPrototype.min(firstNonWhitespaceColumn, TypeScript.MathPrototype.max(firstNonWhitespaceColumn - this.dedentationAmount, this.minimumIndent)); + + if (newFirstNonWhitespaceColumn === firstNonWhitespaceColumn) { + this.abort(); + return segment; + } + + this.dedentationAmount = firstNonWhitespaceColumn - newFirstNonWhitespaceColumn; + TypeScript.Debug.assert(this.dedentationAmount >= 0); + + var indentationString = TypeScript.Indentation.indentationString(newFirstNonWhitespaceColumn, this.options); + + return indentationString + segment.substring(firstNonWhitespacePosition); + }; + + SyntaxDedenter.prototype.dedentWhitespace = function (trivia, hasFollowingNewLineTrivia) { + var newIndentation = this.dedentSegment(trivia.fullText(), hasFollowingNewLineTrivia); + return TypeScript.Syntax.whitespace(newIndentation); + }; + + SyntaxDedenter.prototype.dedentMultiLineComment = function (trivia) { + var segments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + if (segments.length === 1) { + return trivia; + } + + for (var i = 1; i < segments.length; i++) { + var segment = segments[i]; + segments[i] = this.dedentSegment(segment, false); + } + + var result = segments.join(""); + + return TypeScript.Syntax.multiLineComment(result); + }; + + SyntaxDedenter.dedentNode = function (node, dedentFirstToken, dedentAmount, minimumIndent, options) { + var dedenter = new SyntaxDedenter(dedentFirstToken, dedentAmount, minimumIndent, options); + var result = node.accept(dedenter); + + if (dedenter.isAborted()) { + return node; + } + + return result; + }; + return SyntaxDedenter; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxDedenter = SyntaxDedenter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxIndenter = (function (_super) { + __extends(SyntaxIndenter, _super); + function SyntaxIndenter(indentFirstToken, indentationAmount, options) { + _super.call(this); + this.indentationAmount = indentationAmount; + this.options = options; + this.lastTriviaWasNewLine = indentFirstToken; + this.indentationTrivia = TypeScript.Indentation.indentationTrivia(this.indentationAmount, this.options); + } + SyntaxIndenter.prototype.visitToken = function (token) { + if (token.width() === 0) { + return token; + } + + var result = token; + if (this.lastTriviaWasNewLine) { + result = token.withLeadingTrivia(this.indentTriviaList(token.leadingTrivia())); + } + + this.lastTriviaWasNewLine = token.hasTrailingNewLine(); + return result; + }; + + SyntaxIndenter.prototype.indentTriviaList = function (triviaList) { + var result = []; + + var indentNextTrivia = true; + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + var indentThisTrivia = indentNextTrivia; + indentNextTrivia = false; + + switch (trivia.kind()) { + case 6 /* MultiLineCommentTrivia */: + this.indentMultiLineComment(trivia, indentThisTrivia, result); + continue; + + case 7 /* SingleLineCommentTrivia */: + case 8 /* SkippedTokenTrivia */: + this.indentSingleLineOrSkippedText(trivia, indentThisTrivia, result); + continue; + + case 4 /* WhitespaceTrivia */: + this.indentWhitespace(trivia, indentThisTrivia, result); + continue; + + case 5 /* NewLineTrivia */: + result.push(trivia); + indentNextTrivia = true; + continue; + + default: + throw TypeScript.Errors.invalidOperation(); + } + } + + if (indentNextTrivia) { + result.push(this.indentationTrivia); + } + + return TypeScript.Syntax.triviaList(result); + }; + + SyntaxIndenter.prototype.indentSegment = function (segment) { + var firstNonWhitespacePosition = TypeScript.Indentation.firstNonWhitespacePosition(segment); + + if (firstNonWhitespacePosition < segment.length && TypeScript.CharacterInfo.isLineTerminator(segment.charCodeAt(firstNonWhitespacePosition))) { + return segment; + } + + var firstNonWhitespaceColumn = TypeScript.Indentation.columnForPositionInString(segment, firstNonWhitespacePosition, this.options); + + var newFirstNonWhitespaceColumn = firstNonWhitespaceColumn + this.indentationAmount; + + var indentationString = TypeScript.Indentation.indentationString(newFirstNonWhitespaceColumn, this.options); + + return indentationString + segment.substring(firstNonWhitespacePosition); + }; + + SyntaxIndenter.prototype.indentWhitespace = function (trivia, indentThisTrivia, result) { + if (!indentThisTrivia) { + result.push(trivia); + return; + } + + var newIndentation = this.indentSegment(trivia.fullText()); + result.push(TypeScript.Syntax.whitespace(newIndentation)); + }; + + SyntaxIndenter.prototype.indentSingleLineOrSkippedText = function (trivia, indentThisTrivia, result) { + if (indentThisTrivia) { + result.push(this.indentationTrivia); + } + + result.push(trivia); + }; + + SyntaxIndenter.prototype.indentMultiLineComment = function (trivia, indentThisTrivia, result) { + if (indentThisTrivia) { + result.push(this.indentationTrivia); + } + + var segments = TypeScript.Syntax.splitMultiLineCommentTriviaIntoMultipleLines(trivia); + + for (var i = 1; i < segments.length; i++) { + segments[i] = this.indentSegment(segments[i]); + } + + var newText = segments.join(""); + result.push(TypeScript.Syntax.multiLineComment(newText)); + }; + + SyntaxIndenter.indentNode = function (node, indentFirstToken, indentAmount, options) { + var indenter = new SyntaxIndenter(indentFirstToken, indentAmount, options); + return node.accept(indenter); + }; + + SyntaxIndenter.indentNodes = function (nodes, indentFirstToken, indentAmount, options) { + var indenter = new SyntaxIndenter(indentFirstToken, indentAmount, options); + var result = TypeScript.ArrayUtilities.select(nodes, function (n) { + return n.accept(indenter); + }); + + return result; + }; + return SyntaxIndenter; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxIndenter = SyntaxIndenter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var VariableWidthTokenWithNoTrivia = (function () { + function VariableWidthTokenWithNoTrivia(fullText, kind) { + this._fullText = fullText; + this.tokenKind = kind; + } + VariableWidthTokenWithNoTrivia.prototype.clone = function () { + return new VariableWidthTokenWithNoTrivia(this._fullText, this.tokenKind); + }; + + VariableWidthTokenWithNoTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithNoTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithNoTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithNoTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithNoTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithNoTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithNoTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithNoTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithNoTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithNoTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingComment = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingComment = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithNoTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithNoTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithNoTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithNoTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithNoTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithNoTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithNoTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithNoTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithNoTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithNoTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithNoTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithNoTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithNoTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithNoTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithNoTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithNoTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithNoTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithNoTrivia; + })(); + Syntax.VariableWidthTokenWithNoTrivia = VariableWidthTokenWithNoTrivia; + + var VariableWidthTokenWithLeadingTrivia = (function () { + function VariableWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + } + VariableWidthTokenWithLeadingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithLeadingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithLeadingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithLeadingTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithLeadingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingComment = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithLeadingTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithLeadingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithLeadingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithLeadingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithLeadingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithLeadingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithLeadingTrivia; + })(); + Syntax.VariableWidthTokenWithLeadingTrivia = VariableWidthTokenWithLeadingTrivia; + + var VariableWidthTokenWithTrailingTrivia = (function () { + function VariableWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._trailingTriviaInfo = trailingTriviaInfo; + } + VariableWidthTokenWithTrailingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithTrailingTrivia(this._fullText, this.tokenKind, this._trailingTriviaInfo); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithTrailingTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingComment = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + VariableWidthTokenWithTrailingTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithTrailingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithTrailingTrivia; + })(); + Syntax.VariableWidthTokenWithTrailingTrivia = VariableWidthTokenWithTrailingTrivia; + + var VariableWidthTokenWithLeadingAndTrailingTrivia = (function () { + function VariableWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + this._trailingTriviaInfo = trailingTriviaInfo; + } + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { + return new VariableWidthTokenWithLeadingAndTrailingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isToken = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isList = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.childCount = function () { + return 0; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { + return this.fullWidth() - this.leadingTriviaWidth() - this.trailingTriviaWidth(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { + return this.fullText().substr(this.leadingTriviaWidth(), this.width()); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { + if (this._value === undefined) { + this._value = Syntax.value(this); + } + + return this._value; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.valueText = function () { + if (this._valueText === undefined) { + this._valueText = Syntax.valueText(this); + } + + return this._valueText; + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.firstToken = function () { + return this; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.lastToken = function () { + return this; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + VariableWidthTokenWithLeadingAndTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return VariableWidthTokenWithLeadingAndTrailingTrivia; + })(); + Syntax.VariableWidthTokenWithLeadingAndTrailingTrivia = VariableWidthTokenWithLeadingAndTrailingTrivia; + + var FixedWidthTokenWithNoTrivia = (function () { + function FixedWidthTokenWithNoTrivia(kind) { + this.tokenKind = kind; + } + FixedWidthTokenWithNoTrivia.prototype.clone = function () { + return new FixedWidthTokenWithNoTrivia(this.tokenKind); + }; + + FixedWidthTokenWithNoTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithNoTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithNoTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithNoTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithNoTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithNoTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithNoTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithNoTrivia.prototype.fullText = function () { + return this.text(); + }; + + FixedWidthTokenWithNoTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithNoTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingComment = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithNoTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingComment = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithNoTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithNoTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithNoTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithNoTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithNoTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithNoTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithNoTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithNoTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithNoTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithNoTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithNoTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithNoTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithNoTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithNoTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithNoTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithNoTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithNoTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithNoTrivia; + })(); + Syntax.FixedWidthTokenWithNoTrivia = FixedWidthTokenWithNoTrivia; + + var FixedWidthTokenWithLeadingTrivia = (function () { + function FixedWidthTokenWithLeadingTrivia(fullText, kind, leadingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + } + FixedWidthTokenWithLeadingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithLeadingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithLeadingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithLeadingTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithLeadingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingTrivia = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingComment = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingNewLine = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.trailingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithLeadingTrivia.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithLeadingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithLeadingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithLeadingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithLeadingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithLeadingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithLeadingTrivia; + })(); + Syntax.FixedWidthTokenWithLeadingTrivia = FixedWidthTokenWithLeadingTrivia; + + var FixedWidthTokenWithTrailingTrivia = (function () { + function FixedWidthTokenWithTrailingTrivia(fullText, kind, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._trailingTriviaInfo = trailingTriviaInfo; + } + FixedWidthTokenWithTrailingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithTrailingTrivia(this._fullText, this.tokenKind, this._trailingTriviaInfo); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithTrailingTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingTrivia = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingComment = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingNewLine = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.leadingTriviaWidth = function () { + return 0; + }; + FixedWidthTokenWithTrailingTrivia.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithTrailingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithTrailingTrivia; + })(); + Syntax.FixedWidthTokenWithTrailingTrivia = FixedWidthTokenWithTrailingTrivia; + + var FixedWidthTokenWithLeadingAndTrailingTrivia = (function () { + function FixedWidthTokenWithLeadingAndTrailingTrivia(fullText, kind, leadingTriviaInfo, trailingTriviaInfo) { + this._fullText = fullText; + this.tokenKind = kind; + this._leadingTriviaInfo = leadingTriviaInfo; + this._trailingTriviaInfo = trailingTriviaInfo; + } + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.clone = function () { + return new FixedWidthTokenWithLeadingAndTrailingTrivia(this._fullText, this.tokenKind, this._leadingTriviaInfo, this._trailingTriviaInfo); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isNode = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isToken = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isList = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isSeparatedList = function () { + return false; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.kind = function () { + return this.tokenKind; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.childCount = function () { + return 0; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange('index'); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.width = function () { + return this.text().length; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.text = function () { + return TypeScript.SyntaxFacts.getText(this.tokenKind); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.fullText = function () { + return this._fullText; + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.value = function () { + return Syntax.value(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.valueText = function () { + return Syntax.valueText(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingComment = function () { + return hasTriviaComment(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingNewLine = function () { + return hasTriviaNewLine(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasLeadingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTriviaWidth = function () { + return getTriviaWidth(this._leadingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.leadingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), 0, getTriviaWidth(this._leadingTriviaInfo), false); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingTrivia = function () { + return true; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingComment = function () { + return hasTriviaComment(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingNewLine = function () { + return hasTriviaNewLine(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasTrailingSkippedText = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTriviaWidth = function () { + return getTriviaWidth(this._trailingTriviaInfo); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.trailingTrivia = function () { + return TypeScript.Scanner.scanTrivia(TypeScript.SimpleText.fromString(this._fullText), this.leadingTriviaWidth() + this.width(), getTriviaWidth(this._trailingTriviaInfo), true); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.hasSkippedToken = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.toJSON = function (key) { + return Syntax.tokenToJSON(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.firstToken = function () { + return this; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.lastToken = function () { + return this; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isTypeScriptSpecific = function () { + return false; + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isIncrementallyUnusable = function () { + return this.fullWidth() === 0 || TypeScript.SyntaxFacts.isAnyDivideOrRegularExpressionToken(this.tokenKind); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.realize = function () { + return Syntax.realizeToken(this); + }; + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.collectTextElements = function (elements) { + collectTokenTextElements(this, elements); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isExpression = function () { + return Syntax.isExpression(this); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + FixedWidthTokenWithLeadingAndTrailingTrivia.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return FixedWidthTokenWithLeadingAndTrailingTrivia; + })(); + Syntax.FixedWidthTokenWithLeadingAndTrailingTrivia = FixedWidthTokenWithLeadingAndTrailingTrivia; + + function collectTokenTextElements(token, elements) { + token.leadingTrivia().collectTextElements(elements); + elements.push(token.text()); + token.trailingTrivia().collectTextElements(elements); + } + + function getTriviaWidth(value) { + return value >>> 2 /* TriviaFullWidthShift */; + } + + function hasTriviaComment(value) { + return (value & 2 /* TriviaCommentMask */) !== 0; + } + + function hasTriviaNewLine(value) { + return (value & 1 /* TriviaNewLineMask */) !== 0; + } + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + function isExpression(token) { + switch (token.tokenKind) { + case 11 /* IdentifierName */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NumericLiteral */: + case 14 /* StringLiteral */: + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 50 /* SuperKeyword */: + return true; + } + + return false; + } + Syntax.isExpression = isExpression; + + function realizeToken(token) { + return new RealizedToken(token.tokenKind, token.leadingTrivia(), token.text(), token.value(), token.valueText(), token.trailingTrivia()); + } + Syntax.realizeToken = realizeToken; + + function convertToIdentifierName(token) { + TypeScript.Debug.assert(TypeScript.SyntaxFacts.isAnyKeyword(token.tokenKind)); + return new RealizedToken(11 /* IdentifierName */, token.leadingTrivia(), token.text(), token.text(), token.text(), token.trailingTrivia()); + } + Syntax.convertToIdentifierName = convertToIdentifierName; + + function tokenToJSON(token) { + var result = {}; + + for (var name in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind[name] === token.kind()) { + result.kind = name; + break; + } + } + + result.width = token.width(); + if (token.fullWidth() !== token.width()) { + result.fullWidth = token.fullWidth(); + } + + result.text = token.text(); + + var value = token.value(); + if (value !== null) { + result.value = value; + result.valueText = token.valueText(); + } + + if (token.hasLeadingTrivia()) { + result.hasLeadingTrivia = true; + } + + if (token.hasLeadingComment()) { + result.hasLeadingComment = true; + } + + if (token.hasLeadingNewLine()) { + result.hasLeadingNewLine = true; + } + + if (token.hasLeadingSkippedText()) { + result.hasLeadingSkippedText = true; + } + + if (token.hasTrailingTrivia()) { + result.hasTrailingTrivia = true; + } + + if (token.hasTrailingComment()) { + result.hasTrailingComment = true; + } + + if (token.hasTrailingNewLine()) { + result.hasTrailingNewLine = true; + } + + if (token.hasTrailingSkippedText()) { + result.hasTrailingSkippedText = true; + } + + var trivia = token.leadingTrivia(); + if (trivia.count() > 0) { + result.leadingTrivia = trivia; + } + + trivia = token.trailingTrivia(); + if (trivia.count() > 0) { + result.trailingTrivia = trivia; + } + + return result; + } + Syntax.tokenToJSON = tokenToJSON; + + function value(token) { + return value1(token.tokenKind, token.text()); + } + Syntax.value = value; + + function hexValue(text, start, length) { + var intChar = 0; + for (var i = 0; i < length; i++) { + var ch2 = text.charCodeAt(start + i); + if (!TypeScript.CharacterInfo.isHexDigit(ch2)) { + break; + } + + intChar = (intChar << 4) + TypeScript.CharacterInfo.hexValue(ch2); + } + + return intChar; + } + + var characterArray = []; + + function convertEscapes(text) { + characterArray.length = 0; + var result = ""; + + for (var i = 0, n = text.length; i < n; i++) { + var ch = text.charCodeAt(i); + + if (ch === 92 /* backslash */) { + i++; + if (i < n) { + ch = text.charCodeAt(i); + switch (ch) { + case 48 /* _0 */: + characterArray.push(0 /* nullCharacter */); + continue; + + case 98 /* b */: + characterArray.push(8 /* backspace */); + continue; + + case 102 /* f */: + characterArray.push(12 /* formFeed */); + continue; + + case 110 /* n */: + characterArray.push(10 /* lineFeed */); + continue; + + case 114 /* r */: + characterArray.push(13 /* carriageReturn */); + continue; + + case 116 /* t */: + characterArray.push(9 /* tab */); + continue; + + case 118 /* v */: + characterArray.push(11 /* verticalTab */); + continue; + + case 120 /* x */: + characterArray.push(hexValue(text, i + 1, 2)); + i += 2; + continue; + + case 117 /* u */: + characterArray.push(hexValue(text, i + 1, 4)); + i += 4; + continue; + + case 13 /* carriageReturn */: + var nextIndex = i + 1; + if (nextIndex < text.length && text.charCodeAt(nextIndex) === 10 /* lineFeed */) { + i++; + } + continue; + + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + continue; + + default: + } + } + } + + characterArray.push(ch); + + if (i && !(i % 1024)) { + result = result.concat(String.fromCharCode.apply(null, characterArray)); + characterArray.length = 0; + } + } + + if (characterArray.length) { + result = result.concat(String.fromCharCode.apply(null, characterArray)); + } + + return result; + } + + function massageEscapes(text) { + return text.indexOf("\\") >= 0 ? convertEscapes(text) : text; + } + Syntax.massageEscapes = massageEscapes; + + function value1(kind, text) { + if (kind === 11 /* IdentifierName */) { + return massageEscapes(text); + } + + switch (kind) { + case 37 /* TrueKeyword */: + return true; + case 24 /* FalseKeyword */: + return false; + case 32 /* NullKeyword */: + return null; + } + + if (TypeScript.SyntaxFacts.isAnyKeyword(kind) || TypeScript.SyntaxFacts.isAnyPunctuation(kind)) { + return TypeScript.SyntaxFacts.getText(kind); + } + + if (kind === 13 /* NumericLiteral */) { + return TypeScript.IntegerUtilities.isHexInteger(text) ? parseInt(text, 16) : parseFloat(text); + } else if (kind === 14 /* StringLiteral */) { + if (text.length > 1 && text.charCodeAt(text.length - 1) === text.charCodeAt(0)) { + return massageEscapes(text.substr(1, text.length - 2)); + } else { + return massageEscapes(text.substr(1)); + } + } else if (kind === 12 /* RegularExpressionLiteral */) { + return regularExpressionValue(text); + } else if (kind === 10 /* EndOfFileToken */ || kind === 9 /* ErrorToken */) { + return null; + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + + function regularExpressionValue(text) { + try { + var lastSlash = text.lastIndexOf("/"); + var body = text.substring(1, lastSlash); + var flags = text.substring(lastSlash + 1); + return new RegExp(body, flags); + } catch (e) { + return null; + } + } + + function valueText1(kind, text) { + var value = value1(kind, text); + return value === null ? "" : value.toString(); + } + + function valueText(token) { + var value = token.value(); + return value === null ? "" : value.toString(); + } + Syntax.valueText = valueText; + + var EmptyToken = (function () { + function EmptyToken(kind) { + this.tokenKind = kind; + } + EmptyToken.prototype.clone = function () { + return new EmptyToken(this.tokenKind); + }; + + EmptyToken.prototype.kind = function () { + return this.tokenKind; + }; + + EmptyToken.prototype.isToken = function () { + return true; + }; + EmptyToken.prototype.isNode = function () { + return false; + }; + EmptyToken.prototype.isList = function () { + return false; + }; + EmptyToken.prototype.isSeparatedList = function () { + return false; + }; + + EmptyToken.prototype.childCount = function () { + return 0; + }; + + EmptyToken.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + EmptyToken.prototype.toJSON = function (key) { + return tokenToJSON(this); + }; + EmptyToken.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + + EmptyToken.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + EmptyToken.prototype.firstToken = function () { + return this; + }; + EmptyToken.prototype.lastToken = function () { + return this; + }; + EmptyToken.prototype.isTypeScriptSpecific = function () { + return false; + }; + + EmptyToken.prototype.isIncrementallyUnusable = function () { + return true; + }; + + EmptyToken.prototype.fullWidth = function () { + return 0; + }; + EmptyToken.prototype.width = function () { + return 0; + }; + EmptyToken.prototype.text = function () { + return ""; + }; + EmptyToken.prototype.fullText = function () { + return ""; + }; + EmptyToken.prototype.value = function () { + return null; + }; + EmptyToken.prototype.valueText = function () { + return ""; + }; + + EmptyToken.prototype.hasLeadingTrivia = function () { + return false; + }; + EmptyToken.prototype.hasLeadingComment = function () { + return false; + }; + EmptyToken.prototype.hasLeadingNewLine = function () { + return false; + }; + EmptyToken.prototype.hasLeadingSkippedText = function () { + return false; + }; + EmptyToken.prototype.leadingTriviaWidth = function () { + return 0; + }; + EmptyToken.prototype.hasTrailingTrivia = function () { + return false; + }; + EmptyToken.prototype.hasTrailingComment = function () { + return false; + }; + EmptyToken.prototype.hasTrailingNewLine = function () { + return false; + }; + EmptyToken.prototype.hasTrailingSkippedText = function () { + return false; + }; + EmptyToken.prototype.hasSkippedToken = function () { + return false; + }; + + EmptyToken.prototype.trailingTriviaWidth = function () { + return 0; + }; + EmptyToken.prototype.leadingTrivia = function () { + return Syntax.emptyTriviaList; + }; + EmptyToken.prototype.trailingTrivia = function () { + return Syntax.emptyTriviaList; + }; + EmptyToken.prototype.realize = function () { + return realizeToken(this); + }; + EmptyToken.prototype.collectTextElements = function (elements) { + }; + + EmptyToken.prototype.withLeadingTrivia = function (leadingTrivia) { + return this.realize().withLeadingTrivia(leadingTrivia); + }; + + EmptyToken.prototype.withTrailingTrivia = function (trailingTrivia) { + return this.realize().withTrailingTrivia(trailingTrivia); + }; + + EmptyToken.prototype.isExpression = function () { + return isExpression(this); + }; + + EmptyToken.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + EmptyToken.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + EmptyToken.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + EmptyToken.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return EmptyToken; + })(); + + function emptyToken(kind) { + return new EmptyToken(kind); + } + Syntax.emptyToken = emptyToken; + + var RealizedToken = (function () { + function RealizedToken(tokenKind, leadingTrivia, text, value, valueText, trailingTrivia) { + this.tokenKind = tokenKind; + this._leadingTrivia = leadingTrivia; + this._text = text; + this._value = value; + this._valueText = valueText; + this._trailingTrivia = trailingTrivia; + } + RealizedToken.prototype.clone = function () { + return new RealizedToken(this.tokenKind, this._leadingTrivia, this._text, this._value, this._valueText, this._trailingTrivia); + }; + + RealizedToken.prototype.kind = function () { + return this.tokenKind; + }; + RealizedToken.prototype.toJSON = function (key) { + return tokenToJSON(this); + }; + RealizedToken.prototype.firstToken = function () { + return this; + }; + RealizedToken.prototype.lastToken = function () { + return this; + }; + RealizedToken.prototype.isTypeScriptSpecific = function () { + return false; + }; + + RealizedToken.prototype.isIncrementallyUnusable = function () { + return true; + }; + + RealizedToken.prototype.accept = function (visitor) { + return visitor.visitToken(this); + }; + + RealizedToken.prototype.childCount = function () { + return 0; + }; + + RealizedToken.prototype.childAt = function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }; + + RealizedToken.prototype.isToken = function () { + return true; + }; + RealizedToken.prototype.isNode = function () { + return false; + }; + RealizedToken.prototype.isList = function () { + return false; + }; + RealizedToken.prototype.isSeparatedList = function () { + return false; + }; + RealizedToken.prototype.isTrivia = function () { + return false; + }; + RealizedToken.prototype.isTriviaList = function () { + return false; + }; + + RealizedToken.prototype.fullWidth = function () { + return this._leadingTrivia.fullWidth() + this.width() + this._trailingTrivia.fullWidth(); + }; + RealizedToken.prototype.width = function () { + return this.text().length; + }; + + RealizedToken.prototype.text = function () { + return this._text; + }; + RealizedToken.prototype.fullText = function () { + return this._leadingTrivia.fullText() + this.text() + this._trailingTrivia.fullText(); + }; + + RealizedToken.prototype.value = function () { + return this._value; + }; + RealizedToken.prototype.valueText = function () { + return this._valueText; + }; + + RealizedToken.prototype.hasLeadingTrivia = function () { + return this._leadingTrivia.count() > 0; + }; + RealizedToken.prototype.hasLeadingComment = function () { + return this._leadingTrivia.hasComment(); + }; + RealizedToken.prototype.hasLeadingNewLine = function () { + return this._leadingTrivia.hasNewLine(); + }; + RealizedToken.prototype.hasLeadingSkippedText = function () { + return this._leadingTrivia.hasSkippedToken(); + }; + RealizedToken.prototype.leadingTriviaWidth = function () { + return this._leadingTrivia.fullWidth(); + }; + + RealizedToken.prototype.hasTrailingTrivia = function () { + return this._trailingTrivia.count() > 0; + }; + RealizedToken.prototype.hasTrailingComment = function () { + return this._trailingTrivia.hasComment(); + }; + RealizedToken.prototype.hasTrailingNewLine = function () { + return this._trailingTrivia.hasNewLine(); + }; + RealizedToken.prototype.hasTrailingSkippedText = function () { + return this._trailingTrivia.hasSkippedToken(); + }; + RealizedToken.prototype.trailingTriviaWidth = function () { + return this._trailingTrivia.fullWidth(); + }; + + RealizedToken.prototype.hasSkippedToken = function () { + return this.hasLeadingSkippedText() || this.hasTrailingSkippedText(); + }; + + RealizedToken.prototype.leadingTrivia = function () { + return this._leadingTrivia; + }; + RealizedToken.prototype.trailingTrivia = function () { + return this._trailingTrivia; + }; + + RealizedToken.prototype.findTokenInternal = function (parent, position, fullStart) { + return new TypeScript.PositionedToken(parent, this, fullStart); + }; + + RealizedToken.prototype.collectTextElements = function (elements) { + this.leadingTrivia().collectTextElements(elements); + elements.push(this.text()); + this.trailingTrivia().collectTextElements(elements); + }; + + RealizedToken.prototype.withLeadingTrivia = function (leadingTrivia) { + return new RealizedToken(this.tokenKind, leadingTrivia, this._text, this._value, this._valueText, this._trailingTrivia); + }; + + RealizedToken.prototype.withTrailingTrivia = function (trailingTrivia) { + return new RealizedToken(this.tokenKind, this._leadingTrivia, this._text, this._value, this._valueText, trailingTrivia); + }; + + RealizedToken.prototype.isExpression = function () { + return isExpression(this); + }; + + RealizedToken.prototype.isPrimaryExpression = function () { + return this.isExpression(); + }; + + RealizedToken.prototype.isMemberExpression = function () { + return this.isExpression(); + }; + + RealizedToken.prototype.isPostfixExpression = function () { + return this.isExpression(); + }; + + RealizedToken.prototype.isUnaryExpression = function () { + return this.isExpression(); + }; + return RealizedToken; + })(); + + function token(kind, info) { + if (typeof info === "undefined") { info = null; } + var text = (info !== null && info.text !== undefined) ? info.text : TypeScript.SyntaxFacts.getText(kind); + + return new RealizedToken(kind, Syntax.triviaList(info === null ? null : info.leadingTrivia), text, value1(kind, text), valueText1(kind, text), Syntax.triviaList(info === null ? null : info.trailingTrivia)); + } + Syntax.token = token; + + function identifier(text, info) { + if (typeof info === "undefined") { info = null; } + info = info || {}; + info.text = text; + return token(11 /* IdentifierName */, info); + } + Syntax.identifier = identifier; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTokenReplacer = (function (_super) { + __extends(SyntaxTokenReplacer, _super); + function SyntaxTokenReplacer(token1, token2) { + _super.call(this); + this.token1 = token1; + this.token2 = token2; + } + SyntaxTokenReplacer.prototype.visitToken = function (token) { + if (token === this.token1) { + var result = this.token2; + this.token1 = null; + this.token2 = null; + + return result; + } + + return token; + }; + + SyntaxTokenReplacer.prototype.visitNode = function (node) { + if (this.token1 === null) { + return node; + } + + return _super.prototype.visitNode.call(this, node); + }; + + SyntaxTokenReplacer.prototype.visitList = function (list) { + if (this.token1 === null) { + return list; + } + + return _super.prototype.visitList.call(this, list); + }; + + SyntaxTokenReplacer.prototype.visitSeparatedList = function (list) { + if (this.token1 === null) { + return list; + } + + return _super.prototype.visitSeparatedList.call(this, list); + }; + return SyntaxTokenReplacer; + })(TypeScript.SyntaxRewriter); + TypeScript.SyntaxTokenReplacer = SyntaxTokenReplacer; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + var AbstractTrivia = (function () { + function AbstractTrivia(_kind) { + this._kind = _kind; + } + AbstractTrivia.prototype.fullWidth = function () { + throw TypeScript.Errors.abstract(); + }; + + AbstractTrivia.prototype.fullText = function () { + throw TypeScript.Errors.abstract(); + }; + + AbstractTrivia.prototype.skippedToken = function () { + throw TypeScript.Errors.abstract(); + }; + + AbstractTrivia.prototype.toJSON = function (key) { + var result = {}; + + for (var name in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind[name] === this._kind) { + result.kind = name; + break; + } + } + + if (this.isSkippedToken()) { + result.skippedToken = this.skippedToken(); + } else { + result.text = this.fullText(); + } + return result; + }; + + AbstractTrivia.prototype.kind = function () { + return this._kind; + }; + + AbstractTrivia.prototype.isWhitespace = function () { + return this.kind() === 4 /* WhitespaceTrivia */; + }; + + AbstractTrivia.prototype.isComment = function () { + return this.kind() === 7 /* SingleLineCommentTrivia */ || this.kind() === 6 /* MultiLineCommentTrivia */; + }; + + AbstractTrivia.prototype.isNewLine = function () { + return this.kind() === 5 /* NewLineTrivia */; + }; + + AbstractTrivia.prototype.isSkippedToken = function () { + return this.kind() === 8 /* SkippedTokenTrivia */; + }; + + AbstractTrivia.prototype.collectTextElements = function (elements) { + elements.push(this.fullText()); + }; + return AbstractTrivia; + })(); + + var NormalTrivia = (function (_super) { + __extends(NormalTrivia, _super); + function NormalTrivia(kind, _text) { + _super.call(this, kind); + this._text = _text; + } + NormalTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + + NormalTrivia.prototype.fullText = function () { + return this._text; + }; + + NormalTrivia.prototype.skippedToken = function () { + throw TypeScript.Errors.invalidOperation(); + }; + return NormalTrivia; + })(AbstractTrivia); + + var SkippedTokenTrivia = (function (_super) { + __extends(SkippedTokenTrivia, _super); + function SkippedTokenTrivia(_skippedToken) { + _super.call(this, 8 /* SkippedTokenTrivia */); + this._skippedToken = _skippedToken; + } + SkippedTokenTrivia.prototype.fullWidth = function () { + return this.fullText().length; + }; + + SkippedTokenTrivia.prototype.fullText = function () { + return this.skippedToken().fullText(); + }; + + SkippedTokenTrivia.prototype.skippedToken = function () { + return this._skippedToken; + }; + return SkippedTokenTrivia; + })(AbstractTrivia); + + var DeferredTrivia = (function (_super) { + __extends(DeferredTrivia, _super); + function DeferredTrivia(kind, _text, _fullStart, _fullWidth) { + _super.call(this, kind); + this._text = _text; + this._fullStart = _fullStart; + this._fullWidth = _fullWidth; + this._fullText = null; + } + DeferredTrivia.prototype.fullWidth = function () { + return this._fullWidth; + }; + + DeferredTrivia.prototype.fullText = function () { + if (!this._fullText) { + this._fullText = this._text.substr(this._fullStart, this._fullWidth, false); + this._text = null; + } + + return this._fullText; + }; + + DeferredTrivia.prototype.skippedToken = function () { + throw TypeScript.Errors.invalidOperation(); + }; + return DeferredTrivia; + })(AbstractTrivia); + + function deferredTrivia(kind, text, fullStart, fullWidth) { + return new DeferredTrivia(kind, text, fullStart, fullWidth); + } + Syntax.deferredTrivia = deferredTrivia; + + function trivia(kind, text) { + return new NormalTrivia(kind, text); + } + Syntax.trivia = trivia; + + function skippedTokenTrivia(token) { + TypeScript.Debug.assert(!token.hasLeadingTrivia()); + TypeScript.Debug.assert(!token.hasTrailingTrivia()); + TypeScript.Debug.assert(token.fullWidth() > 0); + return new SkippedTokenTrivia(token); + } + Syntax.skippedTokenTrivia = skippedTokenTrivia; + + function spaces(count) { + return trivia(4 /* WhitespaceTrivia */, TypeScript.StringUtilities.repeat(" ", count)); + } + Syntax.spaces = spaces; + + function whitespace(text) { + return trivia(4 /* WhitespaceTrivia */, text); + } + Syntax.whitespace = whitespace; + + function multiLineComment(text) { + return trivia(6 /* MultiLineCommentTrivia */, text); + } + Syntax.multiLineComment = multiLineComment; + + function singleLineComment(text) { + return trivia(7 /* SingleLineCommentTrivia */, text); + } + Syntax.singleLineComment = singleLineComment; + + Syntax.spaceTrivia = spaces(1); + Syntax.lineFeedTrivia = trivia(5 /* NewLineTrivia */, "\n"); + Syntax.carriageReturnTrivia = trivia(5 /* NewLineTrivia */, "\r"); + Syntax.carriageReturnLineFeedTrivia = trivia(5 /* NewLineTrivia */, "\r\n"); + + function splitMultiLineCommentTriviaIntoMultipleLines(trivia) { + var result = []; + + var triviaText = trivia.fullText(); + var currentIndex = 0; + + for (var i = 0; i < triviaText.length; i++) { + var ch = triviaText.charCodeAt(i); + + var isCarriageReturnLineFeed = false; + switch (ch) { + case 13 /* carriageReturn */: + if (i < triviaText.length - 1 && triviaText.charCodeAt(i + 1) === 10 /* lineFeed */) { + i++; + } + + case 10 /* lineFeed */: + case 8233 /* paragraphSeparator */: + case 8232 /* lineSeparator */: + result.push(triviaText.substring(currentIndex, i + 1)); + + currentIndex = i + 1; + continue; + } + } + + result.push(triviaText.substring(currentIndex)); + return result; + } + Syntax.splitMultiLineCommentTriviaIntoMultipleLines = splitMultiLineCommentTriviaIntoMultipleLines; + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (Syntax) { + Syntax.emptyTriviaList = { + kind: function () { + return 3 /* TriviaList */; + }, + count: function () { + return 0; + }, + syntaxTriviaAt: function (index) { + throw TypeScript.Errors.argumentOutOfRange("index"); + }, + last: function () { + throw TypeScript.Errors.argumentOutOfRange("index"); + }, + fullWidth: function () { + return 0; + }, + fullText: function () { + return ""; + }, + hasComment: function () { + return false; + }, + hasNewLine: function () { + return false; + }, + hasSkippedToken: function () { + return false; + }, + toJSON: function (key) { + return []; + }, + collectTextElements: function (elements) { + }, + toArray: function () { + return []; + }, + concat: function (trivia) { + return trivia; + } + }; + + function concatTrivia(list1, list2) { + if (list1.count() === 0) { + return list2; + } + + if (list2.count() === 0) { + return list1; + } + + var trivia = list1.toArray(); + trivia.push.apply(trivia, list2.toArray()); + + return triviaList(trivia); + } + + function isComment(trivia) { + return trivia.kind() === 6 /* MultiLineCommentTrivia */ || trivia.kind() === 7 /* SingleLineCommentTrivia */; + } + + var SingletonSyntaxTriviaList = (function () { + function SingletonSyntaxTriviaList(item) { + this.item = item; + } + SingletonSyntaxTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + + SingletonSyntaxTriviaList.prototype.count = function () { + return 1; + }; + + SingletonSyntaxTriviaList.prototype.syntaxTriviaAt = function (index) { + if (index !== 0) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.item; + }; + + SingletonSyntaxTriviaList.prototype.last = function () { + return this.item; + }; + + SingletonSyntaxTriviaList.prototype.fullWidth = function () { + return this.item.fullWidth(); + }; + + SingletonSyntaxTriviaList.prototype.fullText = function () { + return this.item.fullText(); + }; + + SingletonSyntaxTriviaList.prototype.hasComment = function () { + return isComment(this.item); + }; + + SingletonSyntaxTriviaList.prototype.hasNewLine = function () { + return this.item.kind() === 5 /* NewLineTrivia */; + }; + + SingletonSyntaxTriviaList.prototype.hasSkippedToken = function () { + return this.item.kind() === 8 /* SkippedTokenTrivia */; + }; + + SingletonSyntaxTriviaList.prototype.toJSON = function (key) { + return [this.item]; + }; + + SingletonSyntaxTriviaList.prototype.collectTextElements = function (elements) { + this.item.collectTextElements(elements); + }; + + SingletonSyntaxTriviaList.prototype.toArray = function () { + return [this.item]; + }; + + SingletonSyntaxTriviaList.prototype.concat = function (trivia) { + return concatTrivia(this, trivia); + }; + return SingletonSyntaxTriviaList; + })(); + + var NormalSyntaxTriviaList = (function () { + function NormalSyntaxTriviaList(trivia) { + this.trivia = trivia; + } + NormalSyntaxTriviaList.prototype.kind = function () { + return 3 /* TriviaList */; + }; + + NormalSyntaxTriviaList.prototype.count = function () { + return this.trivia.length; + }; + + NormalSyntaxTriviaList.prototype.syntaxTriviaAt = function (index) { + if (index < 0 || index >= this.trivia.length) { + throw TypeScript.Errors.argumentOutOfRange("index"); + } + + return this.trivia[index]; + }; + + NormalSyntaxTriviaList.prototype.last = function () { + return this.trivia[this.trivia.length - 1]; + }; + + NormalSyntaxTriviaList.prototype.fullWidth = function () { + return TypeScript.ArrayUtilities.sum(this.trivia, function (t) { + return t.fullWidth(); + }); + }; + + NormalSyntaxTriviaList.prototype.fullText = function () { + var result = ""; + + for (var i = 0, n = this.trivia.length; i < n; i++) { + result += this.trivia[i].fullText(); + } + + return result; + }; + + NormalSyntaxTriviaList.prototype.hasComment = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (isComment(this.trivia[i])) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.hasNewLine = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (this.trivia[i].kind() === 5 /* NewLineTrivia */) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.hasSkippedToken = function () { + for (var i = 0; i < this.trivia.length; i++) { + if (this.trivia[i].kind() === 8 /* SkippedTokenTrivia */) { + return true; + } + } + + return false; + }; + + NormalSyntaxTriviaList.prototype.toJSON = function (key) { + return this.trivia; + }; + + NormalSyntaxTriviaList.prototype.collectTextElements = function (elements) { + for (var i = 0; i < this.trivia.length; i++) { + this.trivia[i].collectTextElements(elements); + } + }; + + NormalSyntaxTriviaList.prototype.toArray = function () { + return this.trivia.slice(0); + }; + + NormalSyntaxTriviaList.prototype.concat = function (trivia) { + return concatTrivia(this, trivia); + }; + return NormalSyntaxTriviaList; + })(); + + function triviaList(trivia) { + if (trivia === undefined || trivia === null || trivia.length === 0) { + return Syntax.emptyTriviaList; + } + + if (trivia.length === 1) { + return new SingletonSyntaxTriviaList(trivia[0]); + } + + return new NormalSyntaxTriviaList(trivia); + } + Syntax.triviaList = triviaList; + + Syntax.spaceTriviaList = triviaList([Syntax.spaceTrivia]); + })(TypeScript.Syntax || (TypeScript.Syntax = {})); + var Syntax = TypeScript.Syntax; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxUtilities = (function () { + function SyntaxUtilities() { + } + SyntaxUtilities.isAngleBracket = function (positionedElement) { + var element = positionedElement.element(); + var parent = positionedElement.parentElement(); + if (parent !== null && (element.kind() === 80 /* LessThanToken */ || element.kind() === 81 /* GreaterThanToken */)) { + switch (parent.kind()) { + case 228 /* TypeArgumentList */: + case 229 /* TypeParameterList */: + case 220 /* CastExpression */: + return true; + } + } + + return false; + }; + + SyntaxUtilities.getToken = function (list, kind) { + for (var i = 0, n = list.childCount(); i < n; i++) { + var token = list.childAt(i); + if (token.tokenKind === kind) { + return token; + } + } + + return null; + }; + + SyntaxUtilities.containsToken = function (list, kind) { + return SyntaxUtilities.getToken(list, kind) !== null; + }; + + SyntaxUtilities.hasExportKeyword = function (moduleElement) { + return SyntaxUtilities.getExportKeyword(moduleElement) !== null; + }; + + SyntaxUtilities.getExportKeyword = function (moduleElement) { + switch (moduleElement.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 148 /* VariableStatement */: + case 132 /* EnumDeclaration */: + case 128 /* InterfaceDeclaration */: + case 133 /* ImportDeclaration */: + return SyntaxUtilities.getToken(moduleElement.modifiers, 47 /* ExportKeyword */); + default: + return null; + } + }; + + SyntaxUtilities.isAmbientDeclarationSyntax = function (positionNode) { + if (!positionNode) { + return false; + } + + var node = positionNode.node(); + switch (node.kind()) { + case 130 /* ModuleDeclaration */: + case 131 /* ClassDeclaration */: + case 129 /* FunctionDeclaration */: + case 148 /* VariableStatement */: + case 132 /* EnumDeclaration */: + if (SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */)) { + return true; + } + + case 133 /* ImportDeclaration */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 136 /* MemberVariableDeclaration */: + if (node.isClassElement() || node.isModuleElement()) { + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode()); + } + + case 243 /* EnumElement */: + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode().containingNode()); + + default: + return SyntaxUtilities.isAmbientDeclarationSyntax(positionNode.containingNode()); + } + }; + return SyntaxUtilities; + })(); + TypeScript.SyntaxUtilities = SyntaxUtilities; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxVisitor = (function () { + function SyntaxVisitor() { + } + SyntaxVisitor.prototype.defaultVisit = function (node) { + return null; + }; + + SyntaxVisitor.prototype.visitToken = function (token) { + return this.defaultVisit(token); + }; + + SyntaxVisitor.prototype.visitSourceUnit = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExternalModuleReference = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitModuleNameModuleReference = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitImportDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExportAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitClassDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitInterfaceDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitHeritageClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitModuleDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVariableDeclarator = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEqualsValueClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPrefixUnaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArrayLiteralExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitOmittedExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParenthesizedExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitQualifiedName = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeArgumentList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructorType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArrayType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitGenericType = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeQuery = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeAnnotation = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBlock = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParameter = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberAccessExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPostfixUnaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitElementAccessExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitInvocationExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitArgumentList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBinaryExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConditionalExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMethodSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIndexSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitPropertySignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCallSignature = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitParameterList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeParameterList = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeParameter = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstraint = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitElseClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIfStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitExpressionStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitConstructorDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitGetAccessor = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSetAccessor = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitMemberVariableDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitIndexMemberDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitThrowStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitReturnStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectCreationExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSwitchStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCaseSwitchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDefaultSwitchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitBreakStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitContinueStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitForStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitForInStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitWhileStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitWithStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEnumDeclaration = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEnumElement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCastExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitObjectLiteralExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitSimplePropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFunctionExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitEmptyStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTryStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitCatchClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitFinallyClause = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitLabeledStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDoStatement = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitTypeOfExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDeleteExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitVoidExpression = function (node) { + return this.defaultVisit(node); + }; + + SyntaxVisitor.prototype.visitDebuggerStatement = function (node) { + return this.defaultVisit(node); + }; + return SyntaxVisitor; + })(); + TypeScript.SyntaxVisitor = SyntaxVisitor; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxWalker = (function () { + function SyntaxWalker() { + } + SyntaxWalker.prototype.visitToken = function (token) { + }; + + SyntaxWalker.prototype.visitNode = function (node) { + node.accept(this); + }; + + SyntaxWalker.prototype.visitNodeOrToken = function (nodeOrToken) { + if (nodeOrToken.isToken()) { + this.visitToken(nodeOrToken); + } else { + this.visitNode(nodeOrToken); + } + }; + + SyntaxWalker.prototype.visitOptionalToken = function (token) { + if (token === null) { + return; + } + + this.visitToken(token); + }; + + SyntaxWalker.prototype.visitOptionalNode = function (node) { + if (node === null) { + return; + } + + this.visitNode(node); + }; + + SyntaxWalker.prototype.visitOptionalNodeOrToken = function (nodeOrToken) { + if (nodeOrToken === null) { + return; + } + + this.visitNodeOrToken(nodeOrToken); + }; + + SyntaxWalker.prototype.visitList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + this.visitNodeOrToken(list.childAt(i)); + } + }; + + SyntaxWalker.prototype.visitSeparatedList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + var item = list.childAt(i); + this.visitNodeOrToken(item); + } + }; + + SyntaxWalker.prototype.visitSourceUnit = function (node) { + this.visitList(node.moduleElements); + this.visitToken(node.endOfFileToken); + }; + + SyntaxWalker.prototype.visitExternalModuleReference = function (node) { + this.visitToken(node.requireKeyword); + this.visitToken(node.openParenToken); + this.visitToken(node.stringLiteral); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitModuleNameModuleReference = function (node) { + this.visitNodeOrToken(node.moduleName); + }; + + SyntaxWalker.prototype.visitImportDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.importKeyword); + this.visitToken(node.identifier); + this.visitToken(node.equalsToken); + this.visitNodeOrToken(node.moduleReference); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitExportAssignment = function (node) { + this.visitToken(node.exportKeyword); + this.visitToken(node.equalsToken); + this.visitToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitClassDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.classKeyword); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeParameterList); + this.visitList(node.heritageClauses); + this.visitToken(node.openBraceToken); + this.visitList(node.classElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitInterfaceDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.interfaceKeyword); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeParameterList); + this.visitList(node.heritageClauses); + this.visitNode(node.body); + }; + + SyntaxWalker.prototype.visitHeritageClause = function (node) { + this.visitToken(node.extendsOrImplementsKeyword); + this.visitSeparatedList(node.typeNames); + }; + + SyntaxWalker.prototype.visitModuleDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.moduleKeyword); + this.visitOptionalNodeOrToken(node.name); + this.visitOptionalToken(node.stringLiteral); + this.visitToken(node.openBraceToken); + this.visitList(node.moduleElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitFunctionDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.functionKeyword); + this.visitToken(node.identifier); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitVariableStatement = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.variableDeclaration); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitVariableDeclaration = function (node) { + this.visitToken(node.varKeyword); + this.visitSeparatedList(node.variableDeclarators); + }; + + SyntaxWalker.prototype.visitVariableDeclarator = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalNode(node.typeAnnotation); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitEqualsValueClause = function (node) { + this.visitToken(node.equalsToken); + this.visitNodeOrToken(node.value); + }; + + SyntaxWalker.prototype.visitPrefixUnaryExpression = function (node) { + this.visitToken(node.operatorToken); + this.visitNodeOrToken(node.operand); + }; + + SyntaxWalker.prototype.visitArrayLiteralExpression = function (node) { + this.visitToken(node.openBracketToken); + this.visitSeparatedList(node.expressions); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitOmittedExpression = function (node) { + }; + + SyntaxWalker.prototype.visitParenthesizedExpression = function (node) { + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitSimpleArrowFunctionExpression = function (node) { + this.visitToken(node.identifier); + this.visitToken(node.equalsGreaterThanToken); + this.visitOptionalNode(node.block); + this.visitOptionalNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + this.visitNode(node.callSignature); + this.visitToken(node.equalsGreaterThanToken); + this.visitOptionalNode(node.block); + this.visitOptionalNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitQualifiedName = function (node) { + this.visitNodeOrToken(node.left); + this.visitToken(node.dotToken); + this.visitToken(node.right); + }; + + SyntaxWalker.prototype.visitTypeArgumentList = function (node) { + this.visitToken(node.lessThanToken); + this.visitSeparatedList(node.typeArguments); + this.visitToken(node.greaterThanToken); + }; + + SyntaxWalker.prototype.visitConstructorType = function (node) { + this.visitToken(node.newKeyword); + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitFunctionType = function (node) { + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitToken(node.equalsGreaterThanToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitObjectType = function (node) { + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.typeMembers); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitArrayType = function (node) { + this.visitNodeOrToken(node.type); + this.visitToken(node.openBracketToken); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitGenericType = function (node) { + this.visitNodeOrToken(node.name); + this.visitNode(node.typeArgumentList); + }; + + SyntaxWalker.prototype.visitTypeQuery = function (node) { + this.visitToken(node.typeOfKeyword); + this.visitNodeOrToken(node.name); + }; + + SyntaxWalker.prototype.visitTypeAnnotation = function (node) { + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitBlock = function (node) { + this.visitToken(node.openBraceToken); + this.visitList(node.statements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitParameter = function (node) { + this.visitOptionalToken(node.dotDotDotToken); + this.visitList(node.modifiers); + this.visitToken(node.identifier); + this.visitOptionalToken(node.questionToken); + this.visitOptionalNode(node.typeAnnotation); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitMemberAccessExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.dotToken); + this.visitToken(node.name); + }; + + SyntaxWalker.prototype.visitPostfixUnaryExpression = function (node) { + this.visitNodeOrToken(node.operand); + this.visitToken(node.operatorToken); + }; + + SyntaxWalker.prototype.visitElementAccessExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.openBracketToken); + this.visitNodeOrToken(node.argumentExpression); + this.visitToken(node.closeBracketToken); + }; + + SyntaxWalker.prototype.visitInvocationExpression = function (node) { + this.visitNodeOrToken(node.expression); + this.visitNode(node.argumentList); + }; + + SyntaxWalker.prototype.visitArgumentList = function (node) { + this.visitOptionalNode(node.typeArgumentList); + this.visitToken(node.openParenToken); + this.visitSeparatedList(node.arguments); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitBinaryExpression = function (node) { + this.visitNodeOrToken(node.left); + this.visitToken(node.operatorToken); + this.visitNodeOrToken(node.right); + }; + + SyntaxWalker.prototype.visitConditionalExpression = function (node) { + this.visitNodeOrToken(node.condition); + this.visitToken(node.questionToken); + this.visitNodeOrToken(node.whenTrue); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.whenFalse); + }; + + SyntaxWalker.prototype.visitConstructSignature = function (node) { + this.visitToken(node.newKeyword); + this.visitNode(node.callSignature); + }; + + SyntaxWalker.prototype.visitMethodSignature = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalToken(node.questionToken); + this.visitNode(node.callSignature); + }; + + SyntaxWalker.prototype.visitIndexSignature = function (node) { + this.visitToken(node.openBracketToken); + this.visitNode(node.parameter); + this.visitToken(node.closeBracketToken); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitPropertySignature = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalToken(node.questionToken); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitCallSignature = function (node) { + this.visitOptionalNode(node.typeParameterList); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.typeAnnotation); + }; + + SyntaxWalker.prototype.visitParameterList = function (node) { + this.visitToken(node.openParenToken); + this.visitSeparatedList(node.parameters); + this.visitToken(node.closeParenToken); + }; + + SyntaxWalker.prototype.visitTypeParameterList = function (node) { + this.visitToken(node.lessThanToken); + this.visitSeparatedList(node.typeParameters); + this.visitToken(node.greaterThanToken); + }; + + SyntaxWalker.prototype.visitTypeParameter = function (node) { + this.visitToken(node.identifier); + this.visitOptionalNode(node.constraint); + }; + + SyntaxWalker.prototype.visitConstraint = function (node) { + this.visitToken(node.extendsKeyword); + this.visitNodeOrToken(node.type); + }; + + SyntaxWalker.prototype.visitElseClause = function (node) { + this.visitToken(node.elseKeyword); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitIfStatement = function (node) { + this.visitToken(node.ifKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + this.visitOptionalNode(node.elseClause); + }; + + SyntaxWalker.prototype.visitExpressionStatement = function (node) { + this.visitNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitConstructorDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.constructorKeyword); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitMemberFunctionDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitOptionalNode(node.block); + this.visitOptionalToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitGetAccessor = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.getKeyword); + this.visitToken(node.propertyName); + this.visitNode(node.parameterList); + this.visitOptionalNode(node.typeAnnotation); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitSetAccessor = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.setKeyword); + this.visitToken(node.propertyName); + this.visitNode(node.parameterList); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitMemberVariableDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.variableDeclarator); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitIndexMemberDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitNode(node.indexSignature); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitThrowStatement = function (node) { + this.visitToken(node.throwKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitReturnStatement = function (node) { + this.visitToken(node.returnKeyword); + this.visitOptionalNodeOrToken(node.expression); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitObjectCreationExpression = function (node) { + this.visitToken(node.newKeyword); + this.visitNodeOrToken(node.expression); + this.visitOptionalNode(node.argumentList); + }; + + SyntaxWalker.prototype.visitSwitchStatement = function (node) { + this.visitToken(node.switchKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + this.visitToken(node.openBraceToken); + this.visitList(node.switchClauses); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitCaseSwitchClause = function (node) { + this.visitToken(node.caseKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.colonToken); + this.visitList(node.statements); + }; + + SyntaxWalker.prototype.visitDefaultSwitchClause = function (node) { + this.visitToken(node.defaultKeyword); + this.visitToken(node.colonToken); + this.visitList(node.statements); + }; + + SyntaxWalker.prototype.visitBreakStatement = function (node) { + this.visitToken(node.breakKeyword); + this.visitOptionalToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitContinueStatement = function (node) { + this.visitToken(node.continueKeyword); + this.visitOptionalToken(node.identifier); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitForStatement = function (node) { + this.visitToken(node.forKeyword); + this.visitToken(node.openParenToken); + this.visitOptionalNode(node.variableDeclaration); + this.visitOptionalNodeOrToken(node.initializer); + this.visitToken(node.firstSemicolonToken); + this.visitOptionalNodeOrToken(node.condition); + this.visitToken(node.secondSemicolonToken); + this.visitOptionalNodeOrToken(node.incrementor); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitForInStatement = function (node) { + this.visitToken(node.forKeyword); + this.visitToken(node.openParenToken); + this.visitOptionalNode(node.variableDeclaration); + this.visitOptionalNodeOrToken(node.left); + this.visitToken(node.inKeyword); + this.visitNodeOrToken(node.expression); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitWhileStatement = function (node) { + this.visitToken(node.whileKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitWithStatement = function (node) { + this.visitToken(node.withKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitEnumDeclaration = function (node) { + this.visitList(node.modifiers); + this.visitToken(node.enumKeyword); + this.visitToken(node.identifier); + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.enumElements); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitEnumElement = function (node) { + this.visitToken(node.propertyName); + this.visitOptionalNode(node.equalsValueClause); + }; + + SyntaxWalker.prototype.visitCastExpression = function (node) { + this.visitToken(node.lessThanToken); + this.visitNodeOrToken(node.type); + this.visitToken(node.greaterThanToken); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitObjectLiteralExpression = function (node) { + this.visitToken(node.openBraceToken); + this.visitSeparatedList(node.propertyAssignments); + this.visitToken(node.closeBraceToken); + }; + + SyntaxWalker.prototype.visitSimplePropertyAssignment = function (node) { + this.visitToken(node.propertyName); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitFunctionPropertyAssignment = function (node) { + this.visitToken(node.propertyName); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitFunctionExpression = function (node) { + this.visitToken(node.functionKeyword); + this.visitOptionalToken(node.identifier); + this.visitNode(node.callSignature); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitEmptyStatement = function (node) { + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitTryStatement = function (node) { + this.visitToken(node.tryKeyword); + this.visitNode(node.block); + this.visitOptionalNode(node.catchClause); + this.visitOptionalNode(node.finallyClause); + }; + + SyntaxWalker.prototype.visitCatchClause = function (node) { + this.visitToken(node.catchKeyword); + this.visitToken(node.openParenToken); + this.visitToken(node.identifier); + this.visitOptionalNode(node.typeAnnotation); + this.visitToken(node.closeParenToken); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitFinallyClause = function (node) { + this.visitToken(node.finallyKeyword); + this.visitNode(node.block); + }; + + SyntaxWalker.prototype.visitLabeledStatement = function (node) { + this.visitToken(node.identifier); + this.visitToken(node.colonToken); + this.visitNodeOrToken(node.statement); + }; + + SyntaxWalker.prototype.visitDoStatement = function (node) { + this.visitToken(node.doKeyword); + this.visitNodeOrToken(node.statement); + this.visitToken(node.whileKeyword); + this.visitToken(node.openParenToken); + this.visitNodeOrToken(node.condition); + this.visitToken(node.closeParenToken); + this.visitToken(node.semicolonToken); + }; + + SyntaxWalker.prototype.visitTypeOfExpression = function (node) { + this.visitToken(node.typeOfKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitDeleteExpression = function (node) { + this.visitToken(node.deleteKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitVoidExpression = function (node) { + this.visitToken(node.voidKeyword); + this.visitNodeOrToken(node.expression); + }; + + SyntaxWalker.prototype.visitDebuggerStatement = function (node) { + this.visitToken(node.debuggerKeyword); + this.visitToken(node.semicolonToken); + }; + return SyntaxWalker; + })(); + TypeScript.SyntaxWalker = SyntaxWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PositionTrackingWalker = (function (_super) { + __extends(PositionTrackingWalker, _super); + function PositionTrackingWalker() { + _super.apply(this, arguments); + this._position = 0; + } + PositionTrackingWalker.prototype.visitToken = function (token) { + this._position += token.fullWidth(); + }; + + PositionTrackingWalker.prototype.position = function () { + return this._position; + }; + + PositionTrackingWalker.prototype.skip = function (element) { + this._position += element.fullWidth(); + }; + return PositionTrackingWalker; + })(TypeScript.SyntaxWalker); + TypeScript.PositionTrackingWalker = PositionTrackingWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxInformationMap = (function (_super) { + __extends(SyntaxInformationMap, _super); + function SyntaxInformationMap(trackParents, trackPreviousToken) { + _super.call(this); + this.trackParents = trackParents; + this.trackPreviousToken = trackPreviousToken; + this.tokenToInformation = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this.elementToPosition = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this._previousToken = null; + this._previousTokenInformation = null; + this._currentPosition = 0; + this._elementToParent = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + this._parentStack = []; + this._parentStack.push(null); + } + SyntaxInformationMap.create = function (node, trackParents, trackPreviousToken) { + var map = new SyntaxInformationMap(trackParents, trackPreviousToken); + map.visitNode(node); + return map; + }; + + SyntaxInformationMap.prototype.visitNode = function (node) { + this.trackParents && this._elementToParent.add(node, TypeScript.ArrayUtilities.last(this._parentStack)); + this.elementToPosition.add(node, this._currentPosition); + + this.trackParents && this._parentStack.push(node); + _super.prototype.visitNode.call(this, node); + this.trackParents && this._parentStack.pop(); + }; + + SyntaxInformationMap.prototype.visitToken = function (token) { + this.trackParents && this._elementToParent.add(token, TypeScript.ArrayUtilities.last(this._parentStack)); + + if (this.trackPreviousToken) { + var tokenInformation = { + previousToken: this._previousToken, + nextToken: null + }; + + if (this._previousTokenInformation !== null) { + this._previousTokenInformation.nextToken = token; + } + + this._previousToken = token; + this._previousTokenInformation = tokenInformation; + + this.tokenToInformation.add(token, tokenInformation); + } + + this.elementToPosition.add(token, this._currentPosition); + this._currentPosition += token.fullWidth(); + }; + + SyntaxInformationMap.prototype.parent = function (element) { + return this._elementToParent.get(element); + }; + + SyntaxInformationMap.prototype.fullStart = function (element) { + return this.elementToPosition.get(element); + }; + + SyntaxInformationMap.prototype.start = function (element) { + return this.fullStart(element) + element.leadingTriviaWidth(); + }; + + SyntaxInformationMap.prototype.end = function (element) { + return this.start(element) + element.width(); + }; + + SyntaxInformationMap.prototype.previousToken = function (token) { + return this.tokenInformation(token).previousToken; + }; + + SyntaxInformationMap.prototype.tokenInformation = function (token) { + return this.tokenToInformation.get(token); + }; + + SyntaxInformationMap.prototype.firstTokenInLineContainingToken = function (token) { + var current = token; + while (true) { + var information = this.tokenInformation(current); + if (this.isFirstTokenInLineWorker(information)) { + break; + } + + current = information.previousToken; + } + + return current; + }; + + SyntaxInformationMap.prototype.isFirstTokenInLine = function (token) { + var information = this.tokenInformation(token); + return this.isFirstTokenInLineWorker(information); + }; + + SyntaxInformationMap.prototype.isFirstTokenInLineWorker = function (information) { + return information.previousToken === null || information.previousToken.hasTrailingNewLine(); + }; + return SyntaxInformationMap; + })(TypeScript.SyntaxWalker); + TypeScript.SyntaxInformationMap = SyntaxInformationMap; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxNodeInvariantsChecker = (function (_super) { + __extends(SyntaxNodeInvariantsChecker, _super); + function SyntaxNodeInvariantsChecker() { + _super.apply(this, arguments); + this.tokenTable = TypeScript.Collections.createHashTable(TypeScript.Collections.DefaultHashTableCapacity, TypeScript.Collections.identityHashCode); + } + SyntaxNodeInvariantsChecker.checkInvariants = function (node) { + node.accept(new SyntaxNodeInvariantsChecker()); + }; + + SyntaxNodeInvariantsChecker.prototype.visitToken = function (token) { + this.tokenTable.add(token, token); + }; + return SyntaxNodeInvariantsChecker; + })(TypeScript.SyntaxWalker); + TypeScript.SyntaxNodeInvariantsChecker = SyntaxNodeInvariantsChecker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DepthLimitedWalker = (function (_super) { + __extends(DepthLimitedWalker, _super); + function DepthLimitedWalker(maximumDepth) { + _super.call(this); + this._depth = 0; + this._maximumDepth = 0; + this._maximumDepth = maximumDepth; + } + DepthLimitedWalker.prototype.visitNode = function (node) { + if (this._depth < this._maximumDepth) { + this._depth++; + _super.prototype.visitNode.call(this, node); + this._depth--; + } else { + this.skip(node); + } + }; + return DepthLimitedWalker; + })(TypeScript.PositionTrackingWalker); + TypeScript.DepthLimitedWalker = DepthLimitedWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Parser) { + + + var ExpressionPrecedence; + (function (ExpressionPrecedence) { + ExpressionPrecedence[ExpressionPrecedence["CommaExpressionPrecedence"] = 1] = "CommaExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["AssignmentExpressionPrecedence"] = 2] = "AssignmentExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["ConditionalExpressionPrecedence"] = 3] = "ConditionalExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["ArrowFunctionPrecedence"] = 4] = "ArrowFunctionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["LogicalOrExpressionPrecedence"] = 5] = "LogicalOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["LogicalAndExpressionPrecedence"] = 6] = "LogicalAndExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseOrExpressionPrecedence"] = 7] = "BitwiseOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseExclusiveOrExpressionPrecedence"] = 8] = "BitwiseExclusiveOrExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["BitwiseAndExpressionPrecedence"] = 9] = "BitwiseAndExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["EqualityExpressionPrecedence"] = 10] = "EqualityExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["RelationalExpressionPrecedence"] = 11] = "RelationalExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["ShiftExpressionPrecdence"] = 12] = "ShiftExpressionPrecdence"; + ExpressionPrecedence[ExpressionPrecedence["AdditiveExpressionPrecedence"] = 13] = "AdditiveExpressionPrecedence"; + ExpressionPrecedence[ExpressionPrecedence["MultiplicativeExpressionPrecedence"] = 14] = "MultiplicativeExpressionPrecedence"; + + ExpressionPrecedence[ExpressionPrecedence["UnaryExpressionPrecedence"] = 15] = "UnaryExpressionPrecedence"; + })(ExpressionPrecedence || (ExpressionPrecedence = {})); + + var ListParsingState; + (function (ListParsingState) { + ListParsingState[ListParsingState["SourceUnit_ModuleElements"] = 1 << 0] = "SourceUnit_ModuleElements"; + ListParsingState[ListParsingState["ClassDeclaration_ClassElements"] = 1 << 1] = "ClassDeclaration_ClassElements"; + ListParsingState[ListParsingState["ModuleDeclaration_ModuleElements"] = 1 << 2] = "ModuleDeclaration_ModuleElements"; + ListParsingState[ListParsingState["SwitchStatement_SwitchClauses"] = 1 << 3] = "SwitchStatement_SwitchClauses"; + ListParsingState[ListParsingState["SwitchClause_Statements"] = 1 << 4] = "SwitchClause_Statements"; + ListParsingState[ListParsingState["Block_Statements"] = 1 << 5] = "Block_Statements"; + ListParsingState[ListParsingState["TryBlock_Statements"] = 1 << 6] = "TryBlock_Statements"; + ListParsingState[ListParsingState["CatchBlock_Statements"] = 1 << 7] = "CatchBlock_Statements"; + ListParsingState[ListParsingState["EnumDeclaration_EnumElements"] = 1 << 8] = "EnumDeclaration_EnumElements"; + ListParsingState[ListParsingState["ObjectType_TypeMembers"] = 1 << 9] = "ObjectType_TypeMembers"; + ListParsingState[ListParsingState["ClassOrInterfaceDeclaration_HeritageClauses"] = 1 << 10] = "ClassOrInterfaceDeclaration_HeritageClauses"; + ListParsingState[ListParsingState["HeritageClause_TypeNameList"] = 1 << 11] = "HeritageClause_TypeNameList"; + ListParsingState[ListParsingState["VariableDeclaration_VariableDeclarators_AllowIn"] = 1 << 12] = "VariableDeclaration_VariableDeclarators_AllowIn"; + ListParsingState[ListParsingState["VariableDeclaration_VariableDeclarators_DisallowIn"] = 1 << 13] = "VariableDeclaration_VariableDeclarators_DisallowIn"; + ListParsingState[ListParsingState["ArgumentList_AssignmentExpressions"] = 1 << 14] = "ArgumentList_AssignmentExpressions"; + ListParsingState[ListParsingState["ObjectLiteralExpression_PropertyAssignments"] = 1 << 15] = "ObjectLiteralExpression_PropertyAssignments"; + ListParsingState[ListParsingState["ArrayLiteralExpression_AssignmentExpressions"] = 1 << 16] = "ArrayLiteralExpression_AssignmentExpressions"; + ListParsingState[ListParsingState["ParameterList_Parameters"] = 1 << 17] = "ParameterList_Parameters"; + ListParsingState[ListParsingState["TypeArgumentList_Types"] = 1 << 18] = "TypeArgumentList_Types"; + ListParsingState[ListParsingState["TypeParameterList_TypeParameters"] = 1 << 19] = "TypeParameterList_TypeParameters"; + + ListParsingState[ListParsingState["FirstListParsingState"] = ListParsingState.SourceUnit_ModuleElements] = "FirstListParsingState"; + ListParsingState[ListParsingState["LastListParsingState"] = ListParsingState.TypeParameterList_TypeParameters] = "LastListParsingState"; + })(ListParsingState || (ListParsingState = {})); + + var SyntaxCursor = (function () { + function SyntaxCursor(sourceUnit) { + this._elements = []; + this._index = 0; + this._pinCount = 0; + sourceUnit.insertChildrenInto(this._elements, 0); + } + SyntaxCursor.prototype.isFinished = function () { + return this._index === this._elements.length; + }; + + SyntaxCursor.prototype.currentElement = function () { + if (this.isFinished()) { + return null; + } + + return this._elements[this._index]; + }; + + SyntaxCursor.prototype.currentNode = function () { + var element = this.currentElement(); + return element !== null && element.isNode() ? element : null; + }; + + SyntaxCursor.prototype.moveToFirstChild = function () { + if (this.isFinished()) { + return; + } + + var element = this._elements[this._index]; + if (element.isToken()) { + return; + } + + var node = element; + + this._elements.splice(this._index, 1); + + node.insertChildrenInto(this._elements, this._index); + }; + + SyntaxCursor.prototype.moveToNextSibling = function () { + if (this.isFinished()) { + return; + } + + if (this._pinCount > 0) { + this._index++; + return; + } + + this._elements.shift(); + }; + + SyntaxCursor.prototype.getAndPinCursorIndex = function () { + this._pinCount++; + return this._index; + }; + + SyntaxCursor.prototype.releaseAndUnpinCursorIndex = function (index) { + this._pinCount--; + if (this._pinCount === 0) { + } + }; + + SyntaxCursor.prototype.rewindToPinnedCursorIndex = function (index) { + this._index = index; + }; + + SyntaxCursor.prototype.pinCount = function () { + return this._pinCount; + }; + + SyntaxCursor.prototype.moveToFirstToken = function () { + var element; + + while (!this.isFinished()) { + element = this.currentElement(); + if (element.isNode()) { + this.moveToFirstChild(); + continue; + } + + return; + } + }; + + SyntaxCursor.prototype.currentToken = function () { + this.moveToFirstToken(); + if (this.isFinished()) { + return null; + } + + var element = this.currentElement(); + + return element; + }; + + SyntaxCursor.prototype.peekToken = function (n) { + this.moveToFirstToken(); + var pin = this.getAndPinCursorIndex(); + + for (var i = 0; i < n; i++) { + this.moveToNextSibling(); + this.moveToFirstToken(); + } + + var result = this.currentToken(); + this.rewindToPinnedCursorIndex(pin); + this.releaseAndUnpinCursorIndex(pin); + + return result; + }; + return SyntaxCursor; + })(); + + + + var NormalParserSource = (function () { + function NormalParserSource(fileName, text, languageVersion) { + this._previousToken = null; + this._absolutePosition = 0; + this._tokenDiagnostics = []; + this.rewindPointPool = []; + this.rewindPointPoolCount = 0; + this.slidingWindow = new TypeScript.SlidingWindow(this, TypeScript.ArrayUtilities.createArray(32, null), null); + this.scanner = new TypeScript.Scanner(fileName, text, languageVersion); + } + NormalParserSource.prototype.currentNode = function () { + return null; + }; + + NormalParserSource.prototype.moveToNextNode = function () { + throw TypeScript.Errors.invalidOperation(); + }; + + NormalParserSource.prototype.absolutePosition = function () { + return this._absolutePosition; + }; + + NormalParserSource.prototype.previousToken = function () { + return this._previousToken; + }; + + NormalParserSource.prototype.tokenDiagnostics = function () { + return this._tokenDiagnostics; + }; + + NormalParserSource.prototype.getOrCreateRewindPoint = function () { + if (this.rewindPointPoolCount === 0) { + return {}; + } + + this.rewindPointPoolCount--; + var result = this.rewindPointPool[this.rewindPointPoolCount]; + this.rewindPointPool[this.rewindPointPoolCount] = null; + return result; + }; + + NormalParserSource.prototype.getRewindPoint = function () { + var slidingWindowIndex = this.slidingWindow.getAndPinAbsoluteIndex(); + + var rewindPoint = this.getOrCreateRewindPoint(); + + rewindPoint.slidingWindowIndex = slidingWindowIndex; + rewindPoint.previousToken = this._previousToken; + rewindPoint.absolutePosition = this._absolutePosition; + + rewindPoint.pinCount = this.slidingWindow.pinCount(); + + return rewindPoint; + }; + + NormalParserSource.prototype.isPinned = function () { + return this.slidingWindow.pinCount() > 0; + }; + + NormalParserSource.prototype.rewind = function (rewindPoint) { + this.slidingWindow.rewindToPinnedIndex(rewindPoint.slidingWindowIndex); + + this._previousToken = rewindPoint.previousToken; + this._absolutePosition = rewindPoint.absolutePosition; + }; + + NormalParserSource.prototype.releaseRewindPoint = function (rewindPoint) { + this.slidingWindow.releaseAndUnpinAbsoluteIndex(rewindPoint.absoluteIndex); + + this.rewindPointPool[this.rewindPointPoolCount] = rewindPoint; + this.rewindPointPoolCount++; + }; + + NormalParserSource.prototype.fetchMoreItems = function (allowRegularExpression, sourceIndex, window, destinationIndex, spaceAvailable) { + window[destinationIndex] = this.scanner.scan(this._tokenDiagnostics, allowRegularExpression); + return 1; + }; + + NormalParserSource.prototype.peekToken = function (n) { + return this.slidingWindow.peekItemN(n); + }; + + NormalParserSource.prototype.moveToNextToken = function () { + var currentToken = this.currentToken(); + this._absolutePosition += currentToken.fullWidth(); + this._previousToken = currentToken; + + this.slidingWindow.moveToNextItem(); + }; + + NormalParserSource.prototype.currentToken = function () { + return this.slidingWindow.currentItem(false); + }; + + NormalParserSource.prototype.removeDiagnosticsOnOrAfterPosition = function (position) { + var tokenDiagnosticsLength = this._tokenDiagnostics.length; + while (tokenDiagnosticsLength > 0) { + var diagnostic = this._tokenDiagnostics[tokenDiagnosticsLength - 1]; + if (diagnostic.start() >= position) { + tokenDiagnosticsLength--; + } else { + break; + } + } + + this._tokenDiagnostics.length = tokenDiagnosticsLength; + }; + + NormalParserSource.prototype.resetToPosition = function (absolutePosition, previousToken) { + this._absolutePosition = absolutePosition; + this._previousToken = previousToken; + + this.removeDiagnosticsOnOrAfterPosition(absolutePosition); + + this.slidingWindow.disgardAllItemsFromCurrentIndexOnwards(); + + this.scanner.setAbsoluteIndex(absolutePosition); + }; + + NormalParserSource.prototype.currentTokenAllowingRegularExpression = function () { + this.resetToPosition(this._absolutePosition, this._previousToken); + + var token = this.slidingWindow.currentItem(true); + + return token; + }; + return NormalParserSource; + })(); + + var IncrementalParserSource = (function () { + function IncrementalParserSource(oldSyntaxTree, textChangeRange, newText) { + this._changeDelta = 0; + var oldSourceUnit = oldSyntaxTree.sourceUnit(); + this._oldSourceUnitCursor = new SyntaxCursor(oldSourceUnit); + + this._changeRange = IncrementalParserSource.extendToAffectedRange(textChangeRange, oldSourceUnit); + + if (TypeScript.Debug.shouldAssert(2 /* Aggressive */)) { + TypeScript.Debug.assert((oldSourceUnit.fullWidth() - this._changeRange.span().length() + this._changeRange.newLength()) === newText.length()); + } + + this._normalParserSource = new NormalParserSource(oldSyntaxTree.fileName(), newText, oldSyntaxTree.parseOptions().languageVersion()); + } + IncrementalParserSource.extendToAffectedRange = function (changeRange, sourceUnit) { + var maxLookahead = 1; + + var start = changeRange.span().start(); + + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var token = sourceUnit.findToken(start); + + var position = token.fullStart(); + + start = TypeScript.MathPrototype.max(0, position - 1); + } + + var finalSpan = TypeScript.TextSpan.fromBounds(start, changeRange.span().end()); + var finalLength = changeRange.newLength() + (changeRange.span().start() - start); + + return new TypeScript.TextChangeRange(finalSpan, finalLength); + }; + + IncrementalParserSource.prototype.absolutePosition = function () { + return this._normalParserSource.absolutePosition(); + }; + + IncrementalParserSource.prototype.previousToken = function () { + return this._normalParserSource.previousToken(); + }; + + IncrementalParserSource.prototype.tokenDiagnostics = function () { + return this._normalParserSource.tokenDiagnostics(); + }; + + IncrementalParserSource.prototype.getRewindPoint = function () { + var rewindPoint = this._normalParserSource.getRewindPoint(); + var oldSourceUnitCursorIndex = this._oldSourceUnitCursor.getAndPinCursorIndex(); + + rewindPoint.changeDelta = this._changeDelta; + rewindPoint.changeRange = this._changeRange; + rewindPoint.oldSourceUnitCursorIndex = oldSourceUnitCursorIndex; + + return rewindPoint; + }; + + IncrementalParserSource.prototype.rewind = function (rewindPoint) { + this._changeRange = rewindPoint.changeRange; + this._changeDelta = rewindPoint.changeDelta; + this._oldSourceUnitCursor.rewindToPinnedCursorIndex(rewindPoint.oldSourceUnitCursorIndex); + + this._normalParserSource.rewind(rewindPoint); + }; + + IncrementalParserSource.prototype.releaseRewindPoint = function (rewindPoint) { + this._oldSourceUnitCursor.releaseAndUnpinCursorIndex(rewindPoint.oldSourceUnitCursorIndex); + this._normalParserSource.releaseRewindPoint(rewindPoint); + }; + + IncrementalParserSource.prototype.canReadFromOldSourceUnit = function () { + if (this._normalParserSource.isPinned()) { + return false; + } + + if (this._changeRange !== null && this._changeRange.newSpan().intersectsWithPosition(this.absolutePosition())) { + return false; + } + + this.syncCursorToNewTextIfBehind(); + + return this._changeDelta === 0 && !this._oldSourceUnitCursor.isFinished(); + }; + + IncrementalParserSource.prototype.currentNode = function () { + if (this.canReadFromOldSourceUnit()) { + return this.tryGetNodeFromOldSourceUnit(); + } + + return null; + }; + + IncrementalParserSource.prototype.currentToken = function () { + if (this.canReadFromOldSourceUnit()) { + var token = this.tryGetTokenFromOldSourceUnit(); + if (token !== null) { + return token; + } + } + + return this._normalParserSource.currentToken(); + }; + + IncrementalParserSource.prototype.currentTokenAllowingRegularExpression = function () { + return this._normalParserSource.currentTokenAllowingRegularExpression(); + }; + + IncrementalParserSource.prototype.syncCursorToNewTextIfBehind = function () { + while (true) { + if (this._oldSourceUnitCursor.isFinished()) { + break; + } + + if (this._changeDelta >= 0) { + break; + } + + var currentElement = this._oldSourceUnitCursor.currentElement(); + + if (currentElement.isNode() && (currentElement.fullWidth() > Math.abs(this._changeDelta))) { + this._oldSourceUnitCursor.moveToFirstChild(); + } else { + this._oldSourceUnitCursor.moveToNextSibling(); + + this._changeDelta += currentElement.fullWidth(); + } + } + }; + + IncrementalParserSource.prototype.intersectsWithChangeRangeSpanInOriginalText = function (start, length) { + return this._changeRange !== null && this._changeRange.span().intersectsWith(start, length); + }; + + IncrementalParserSource.prototype.tryGetNodeFromOldSourceUnit = function () { + while (true) { + var node = this._oldSourceUnitCursor.currentNode(); + if (node === null) { + return null; + } + + if (!this.intersectsWithChangeRangeSpanInOriginalText(this.absolutePosition(), node.fullWidth())) { + if (!node.isIncrementallyUnusable()) { + return node; + } + } + + this._oldSourceUnitCursor.moveToFirstChild(); + } + }; + + IncrementalParserSource.prototype.canReuseTokenFromOldSourceUnit = function (position, token) { + if (token !== null) { + if (!this.intersectsWithChangeRangeSpanInOriginalText(position, token.fullWidth())) { + if (!token.isIncrementallyUnusable()) { + return true; + } + } + } + + return false; + }; + + IncrementalParserSource.prototype.tryGetTokenFromOldSourceUnit = function () { + var token = this._oldSourceUnitCursor.currentToken(); + + return this.canReuseTokenFromOldSourceUnit(this.absolutePosition(), token) ? token : null; + }; + + IncrementalParserSource.prototype.peekToken = function (n) { + if (this.canReadFromOldSourceUnit()) { + var token = this.tryPeekTokenFromOldSourceUnit(n); + if (token !== null) { + return token; + } + } + + return this._normalParserSource.peekToken(n); + }; + + IncrementalParserSource.prototype.tryPeekTokenFromOldSourceUnit = function (n) { + var currentPosition = this.absolutePosition(); + for (var i = 0; i < n; i++) { + var interimToken = this._oldSourceUnitCursor.peekToken(i); + if (!this.canReuseTokenFromOldSourceUnit(currentPosition, interimToken)) { + return null; + } + + currentPosition += interimToken.fullWidth(); + } + + var token = this._oldSourceUnitCursor.peekToken(n); + return this.canReuseTokenFromOldSourceUnit(currentPosition, token) ? token : null; + }; + + IncrementalParserSource.prototype.moveToNextNode = function () { + var currentElement = this._oldSourceUnitCursor.currentElement(); + var currentNode = this._oldSourceUnitCursor.currentNode(); + + this._oldSourceUnitCursor.moveToNextSibling(); + + var absolutePosition = this.absolutePosition() + currentNode.fullWidth(); + var previousToken = currentNode.lastToken(); + this._normalParserSource.resetToPosition(absolutePosition, previousToken); + + if (this._changeRange !== null) { + } + }; + + IncrementalParserSource.prototype.moveToNextToken = function () { + var currentToken = this.currentToken(); + + if (this._oldSourceUnitCursor.currentToken() === currentToken) { + this._oldSourceUnitCursor.moveToNextSibling(); + + var absolutePosition = this.absolutePosition() + currentToken.fullWidth(); + var previousToken = currentToken; + this._normalParserSource.resetToPosition(absolutePosition, previousToken); + + if (this._changeRange !== null) { + } + } else { + this._changeDelta -= currentToken.fullWidth(); + + this._normalParserSource.moveToNextToken(); + + if (this._changeRange !== null) { + var changeRangeSpanInNewText = this._changeRange.newSpan(); + if (this.absolutePosition() >= changeRangeSpanInNewText.end()) { + this._changeDelta += this._changeRange.newLength() - this._changeRange.span().length(); + this._changeRange = null; + } + } + } + }; + return IncrementalParserSource; + })(); + + var ParserImpl = (function () { + function ParserImpl(fileName, lineMap, source, parseOptions, newText_forDebuggingPurposesOnly) { + this.newText_forDebuggingPurposesOnly = newText_forDebuggingPurposesOnly; + this.listParsingState = 0; + this.isInStrictMode = false; + this.diagnostics = []; + this.factory = TypeScript.Syntax.normalModeFactory; + this.mergeTokensStorage = []; + this.arrayPool = []; + this.fileName = fileName; + this.lineMap = lineMap; + this.source = source; + this.parseOptions = parseOptions; + } + ParserImpl.prototype.getRewindPoint = function () { + var rewindPoint = this.source.getRewindPoint(); + + rewindPoint.diagnosticsCount = this.diagnostics.length; + + rewindPoint.isInStrictMode = this.isInStrictMode; + rewindPoint.listParsingState = this.listParsingState; + + return rewindPoint; + }; + + ParserImpl.prototype.rewind = function (rewindPoint) { + this.source.rewind(rewindPoint); + + this.diagnostics.length = rewindPoint.diagnosticsCount; + }; + + ParserImpl.prototype.releaseRewindPoint = function (rewindPoint) { + this.source.releaseRewindPoint(rewindPoint); + }; + + ParserImpl.prototype.currentTokenStart = function () { + return this.source.absolutePosition() + this.currentToken().leadingTriviaWidth(); + }; + + ParserImpl.prototype.previousTokenStart = function () { + if (this.previousToken() === null) { + return 0; + } + + return this.source.absolutePosition() - this.previousToken().fullWidth() + this.previousToken().leadingTriviaWidth(); + }; + + ParserImpl.prototype.previousTokenEnd = function () { + if (this.previousToken() === null) { + return 0; + } + + return this.previousTokenStart() + this.previousToken().width(); + }; + + ParserImpl.prototype.currentNode = function () { + var node = this.source.currentNode(); + + if (node === null || node.parsedInStrictMode() !== this.isInStrictMode) { + return null; + } + + return node; + }; + + ParserImpl.prototype.currentToken = function () { + return this.source.currentToken(); + }; + + ParserImpl.prototype.currentTokenAllowingRegularExpression = function () { + return this.source.currentTokenAllowingRegularExpression(); + }; + + ParserImpl.prototype.peekToken = function (n) { + return this.source.peekToken(n); + }; + + ParserImpl.prototype.eatAnyToken = function () { + var token = this.currentToken(); + this.moveToNextToken(); + return token; + }; + + ParserImpl.prototype.moveToNextToken = function () { + this.source.moveToNextToken(); + }; + + ParserImpl.prototype.previousToken = function () { + return this.source.previousToken(); + }; + + ParserImpl.prototype.eatNode = function () { + var node = this.source.currentNode(); + this.source.moveToNextNode(); + return node; + }; + + ParserImpl.prototype.eatToken = function (kind) { + var token = this.currentToken(); + if (token.tokenKind === kind) { + this.moveToNextToken(); + return token; + } + + return this.createMissingToken(kind, token); + }; + + ParserImpl.prototype.tryEatToken = function (kind) { + if (this.currentToken().tokenKind === kind) { + return this.eatToken(kind); + } + + return null; + }; + + ParserImpl.prototype.eatKeyword = function (kind) { + var token = this.currentToken(); + if (token.tokenKind === kind) { + this.moveToNextToken(); + return token; + } + + return this.createMissingToken(kind, token); + }; + + ParserImpl.prototype.isIdentifier = function (token) { + var tokenKind = token.tokenKind; + + if (tokenKind === 11 /* IdentifierName */) { + return true; + } + + if (tokenKind >= 51 /* FirstFutureReservedStrictKeyword */) { + if (tokenKind <= 59 /* LastFutureReservedStrictKeyword */) { + return !this.isInStrictMode; + } + + return tokenKind <= 69 /* LastTypeScriptKeyword */; + } + + return false; + }; + + ParserImpl.prototype.eatIdentifierNameToken = function () { + var token = this.currentToken(); + + if (token.tokenKind === 11 /* IdentifierName */) { + this.moveToNextToken(); + return token; + } + + if (TypeScript.SyntaxFacts.isAnyKeyword(token.tokenKind)) { + this.moveToNextToken(); + return TypeScript.Syntax.convertToIdentifierName(token); + } + + return this.createMissingToken(11 /* IdentifierName */, token); + }; + + ParserImpl.prototype.eatIdentifierToken = function () { + var token = this.currentToken(); + if (this.isIdentifier(token)) { + this.moveToNextToken(); + + if (token.tokenKind === 11 /* IdentifierName */) { + return token; + } + + return TypeScript.Syntax.convertToIdentifierName(token); + } + + return this.createMissingToken(11 /* IdentifierName */, token); + }; + + ParserImpl.prototype.canEatAutomaticSemicolon = function (allowWithoutNewLine) { + var token = this.currentToken(); + + if (token.tokenKind === 10 /* EndOfFileToken */) { + return true; + } + + if (token.tokenKind === 71 /* CloseBraceToken */) { + return true; + } + + if (allowWithoutNewLine) { + return true; + } + + if (this.previousToken() !== null && this.previousToken().hasTrailingNewLine()) { + return true; + } + + return false; + }; + + ParserImpl.prototype.canEatExplicitOrAutomaticSemicolon = function (allowWithoutNewline) { + var token = this.currentToken(); + + if (token.tokenKind === 78 /* SemicolonToken */) { + return true; + } + + return this.canEatAutomaticSemicolon(allowWithoutNewline); + }; + + ParserImpl.prototype.eatExplicitOrAutomaticSemicolon = function (allowWithoutNewline) { + var token = this.currentToken(); + + if (token.tokenKind === 78 /* SemicolonToken */) { + return this.eatToken(78 /* SemicolonToken */); + } + + if (this.canEatAutomaticSemicolon(allowWithoutNewline)) { + var semicolonToken = TypeScript.Syntax.emptyToken(78 /* SemicolonToken */); + + if (!this.parseOptions.allowAutomaticSemicolonInsertion()) { + this.addDiagnostic(new TypeScript.Diagnostic(this.fileName, this.lineMap, this.previousTokenEnd(), 0, TypeScript.DiagnosticCode.Automatic_semicolon_insertion_not_allowed, null)); + } + + return semicolonToken; + } + + return this.eatToken(78 /* SemicolonToken */); + }; + + ParserImpl.prototype.isKeyword = function (kind) { + if (kind >= 15 /* FirstKeyword */) { + if (kind <= 50 /* LastFutureReservedKeyword */) { + return true; + } + + if (this.isInStrictMode) { + return kind <= 59 /* LastFutureReservedStrictKeyword */; + } + } + + return false; + }; + + ParserImpl.prototype.createMissingToken = function (expectedKind, actual) { + var diagnostic = this.getExpectedTokenDiagnostic(expectedKind, actual); + this.addDiagnostic(diagnostic); + + return TypeScript.Syntax.emptyToken(expectedKind); + }; + + ParserImpl.prototype.getExpectedTokenDiagnostic = function (expectedKind, actual) { + var token = this.currentToken(); + + if (TypeScript.SyntaxFacts.isAnyKeyword(expectedKind) || TypeScript.SyntaxFacts.isAnyPunctuation(expectedKind)) { + return new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode._0_expected, [TypeScript.SyntaxFacts.getText(expectedKind)]); + } else { + if (actual !== null && TypeScript.SyntaxFacts.isAnyKeyword(actual.tokenKind)) { + return new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode.Identifier_expected_0_is_a_keyword, [TypeScript.SyntaxFacts.getText(actual.tokenKind)]); + } else { + return new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode.Identifier_expected, null); + } + } + }; + + ParserImpl.getPrecedence = function (expressionKind) { + switch (expressionKind) { + case 173 /* CommaExpression */: + return 1 /* CommaExpressionPrecedence */; + + case 174 /* AssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + return 2 /* AssignmentExpressionPrecedence */; + + case 186 /* ConditionalExpression */: + return 3 /* ConditionalExpressionPrecedence */; + + case 187 /* LogicalOrExpression */: + return 5 /* LogicalOrExpressionPrecedence */; + + case 188 /* LogicalAndExpression */: + return 6 /* LogicalAndExpressionPrecedence */; + + case 189 /* BitwiseOrExpression */: + return 7 /* BitwiseOrExpressionPrecedence */; + + case 190 /* BitwiseExclusiveOrExpression */: + return 8 /* BitwiseExclusiveOrExpressionPrecedence */; + + case 191 /* BitwiseAndExpression */: + return 9 /* BitwiseAndExpressionPrecedence */; + + case 192 /* EqualsWithTypeConversionExpression */: + case 193 /* NotEqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + return 10 /* EqualityExpressionPrecedence */; + + case 196 /* LessThanExpression */: + case 197 /* GreaterThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 200 /* InstanceOfExpression */: + case 201 /* InExpression */: + return 11 /* RelationalExpressionPrecedence */; + + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + return 12 /* ShiftExpressionPrecdence */; + + case 208 /* AddExpression */: + case 209 /* SubtractExpression */: + return 13 /* AdditiveExpressionPrecedence */; + + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + return 14 /* MultiplicativeExpressionPrecedence */; + + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + case 166 /* BitwiseNotExpression */: + case 167 /* LogicalNotExpression */: + case 170 /* DeleteExpression */: + case 171 /* TypeOfExpression */: + case 172 /* VoidExpression */: + case 168 /* PreIncrementExpression */: + case 169 /* PreDecrementExpression */: + return 15 /* UnaryExpressionPrecedence */; + } + + throw TypeScript.Errors.invalidOperation(); + }; + + ParserImpl.prototype.addSkippedTokenAfterNodeOrToken = function (nodeOrToken, skippedToken) { + if (nodeOrToken.isToken()) { + return this.addSkippedTokenAfterToken(nodeOrToken, skippedToken); + } else if (nodeOrToken.isNode()) { + return this.addSkippedTokenAfterNode(nodeOrToken, skippedToken); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.addSkippedTokenAfterNode = function (node, skippedToken) { + var oldToken = node.lastToken(); + var newToken = this.addSkippedTokenAfterToken(oldToken, skippedToken); + + return node.replaceToken(oldToken, newToken); + }; + + ParserImpl.prototype.addSkippedTokensBeforeNode = function (node, skippedTokens) { + if (skippedTokens.length > 0) { + var oldToken = node.firstToken(); + var newToken = this.addSkippedTokensBeforeToken(oldToken, skippedTokens); + + return node.replaceToken(oldToken, newToken); + } + + return node; + }; + + ParserImpl.prototype.addSkippedTokensBeforeToken = function (token, skippedTokens) { + var leadingTrivia = []; + for (var i = 0, n = skippedTokens.length; i < n; i++) { + this.addSkippedTokenToTriviaArray(leadingTrivia, skippedTokens[i]); + } + + this.addTriviaTo(token.leadingTrivia(), leadingTrivia); + + this.returnArray(skippedTokens); + return token.withLeadingTrivia(TypeScript.Syntax.triviaList(leadingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokensAfterToken = function (token, skippedTokens) { + if (skippedTokens.length === 0) { + this.returnArray(skippedTokens); + return token; + } + + var trailingTrivia = token.trailingTrivia().toArray(); + + for (var i = 0, n = skippedTokens.length; i < n; i++) { + this.addSkippedTokenToTriviaArray(trailingTrivia, skippedTokens[i]); + } + + this.returnArray(skippedTokens); + return token.withTrailingTrivia(TypeScript.Syntax.triviaList(trailingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokenAfterToken = function (token, skippedToken) { + var trailingTrivia = token.trailingTrivia().toArray(); + this.addSkippedTokenToTriviaArray(trailingTrivia, skippedToken); + + return token.withTrailingTrivia(TypeScript.Syntax.triviaList(trailingTrivia)); + }; + + ParserImpl.prototype.addSkippedTokenToTriviaArray = function (array, skippedToken) { + this.addTriviaTo(skippedToken.leadingTrivia(), array); + + var trimmedToken = skippedToken.withLeadingTrivia(TypeScript.Syntax.emptyTriviaList).withTrailingTrivia(TypeScript.Syntax.emptyTriviaList); + array.push(TypeScript.Syntax.skippedTokenTrivia(trimmedToken)); + + this.addTriviaTo(skippedToken.trailingTrivia(), array); + }; + + ParserImpl.prototype.addTriviaTo = function (list, array) { + for (var i = 0, n = list.count(); i < n; i++) { + array.push(list.syntaxTriviaAt(i)); + } + }; + + ParserImpl.prototype.parseSyntaxTree = function (isDeclaration) { + var sourceUnit = this.parseSourceUnit(); + + var allDiagnostics = this.source.tokenDiagnostics().concat(this.diagnostics); + allDiagnostics.sort(function (a, b) { + return a.start() - b.start(); + }); + + return new TypeScript.SyntaxTree(sourceUnit, isDeclaration, allDiagnostics, this.fileName, this.lineMap, this.parseOptions); + }; + + ParserImpl.prototype.setStrictMode = function (isInStrictMode) { + this.isInStrictMode = isInStrictMode; + this.factory = isInStrictMode ? TypeScript.Syntax.strictModeFactory : TypeScript.Syntax.normalModeFactory; + }; + + ParserImpl.prototype.parseSourceUnit = function () { + var savedIsInStrictMode = this.isInStrictMode; + + var result = this.parseSyntaxList(1 /* SourceUnit_ModuleElements */, ParserImpl.updateStrictModeState); + var moduleElements = result.list; + + this.setStrictMode(savedIsInStrictMode); + + var sourceUnit = this.factory.sourceUnit(moduleElements, this.currentToken()); + sourceUnit = this.addSkippedTokensBeforeNode(sourceUnit, result.skippedTokens); + + if (TypeScript.Debug.shouldAssert(2 /* Aggressive */)) { + TypeScript.Debug.assert(sourceUnit.fullWidth() === this.newText_forDebuggingPurposesOnly.length()); + + if (TypeScript.Debug.shouldAssert(3 /* VeryAggressive */)) { + TypeScript.Debug.assert(sourceUnit.fullText() === this.newText_forDebuggingPurposesOnly.substr(0, this.newText_forDebuggingPurposesOnly.length(), false)); + } + } + + return sourceUnit; + }; + + ParserImpl.updateStrictModeState = function (parser, items) { + if (!parser.isInStrictMode) { + for (var i = 0; i < items.length; i++) { + var item = items[i]; + if (!TypeScript.SyntaxFacts.isDirectivePrologueElement(item)) { + return; + } + } + + parser.setStrictMode(TypeScript.SyntaxFacts.isUseStrictDirective(items[items.length - 1])); + } + }; + + ParserImpl.prototype.isModuleElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isModuleElement()) { + return true; + } + + var modifierCount = this.modifierCount(); + return this.isImportDeclaration(modifierCount) || this.isExportAssignment() || this.isModuleDeclaration(modifierCount) || this.isInterfaceDeclaration(modifierCount) || this.isClassDeclaration(modifierCount) || this.isEnumDeclaration(modifierCount) || this.isStatement(inErrorRecovery); + }; + + ParserImpl.prototype.parseModuleElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isModuleElement()) { + return this.eatNode(); + } + + var modifierCount = this.modifierCount(); + if (this.isImportDeclaration(modifierCount)) { + return this.parseImportDeclaration(); + } else if (this.isExportAssignment()) { + return this.parseExportAssignment(); + } else if (this.isModuleDeclaration(modifierCount)) { + return this.parseModuleDeclaration(); + } else if (this.isInterfaceDeclaration(modifierCount)) { + return this.parseInterfaceDeclaration(); + } else if (this.isClassDeclaration(modifierCount)) { + return this.parseClassDeclaration(); + } else if (this.isEnumDeclaration(modifierCount)) { + return this.parseEnumDeclaration(); + } else if (this.isStatement(inErrorRecovery)) { + return this.parseStatement(inErrorRecovery); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isImportDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 49 /* ImportKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 49 /* ImportKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseImportDeclaration = function () { + var modifiers = this.parseModifiers(); + var importKeyword = this.eatKeyword(49 /* ImportKeyword */); + var identifier = this.eatIdentifierToken(); + var equalsToken = this.eatToken(107 /* EqualsToken */); + var moduleReference = this.parseModuleReference(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.importDeclaration(modifiers, importKeyword, identifier, equalsToken, moduleReference, semicolonToken); + }; + + ParserImpl.prototype.isExportAssignment = function () { + return this.currentToken().tokenKind === 47 /* ExportKeyword */ && this.peekToken(1).tokenKind === 107 /* EqualsToken */; + }; + + ParserImpl.prototype.parseExportAssignment = function () { + var exportKeyword = this.eatKeyword(47 /* ExportKeyword */); + var equalsToken = this.eatToken(107 /* EqualsToken */); + var identifier = this.eatIdentifierToken(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.exportAssignment(exportKeyword, equalsToken, identifier, semicolonToken); + }; + + ParserImpl.prototype.parseModuleReference = function () { + if (this.isExternalModuleReference()) { + return this.parseExternalModuleReference(); + } else { + return this.parseModuleNameModuleReference(); + } + }; + + ParserImpl.prototype.isExternalModuleReference = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 66 /* RequireKeyword */) { + return this.peekToken(1).tokenKind === 72 /* OpenParenToken */; + } + + return false; + }; + + ParserImpl.prototype.parseExternalModuleReference = function () { + var requireKeyword = this.eatKeyword(66 /* RequireKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var stringLiteral = this.eatToken(14 /* StringLiteral */); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + return this.factory.externalModuleReference(requireKeyword, openParenToken, stringLiteral, closeParenToken); + }; + + ParserImpl.prototype.parseModuleNameModuleReference = function () { + var name = this.parseName(); + return this.factory.moduleNameModuleReference(name); + }; + + ParserImpl.prototype.parseIdentifierName = function () { + var identifierName = this.eatIdentifierNameToken(); + return identifierName; + }; + + ParserImpl.prototype.tryParseTypeArgumentList = function (inExpression) { + if (this.currentToken().kind() !== 80 /* LessThanToken */) { + return null; + } + + var lessThanToken; + var greaterThanToken; + var result; + var typeArguments; + + if (!inExpression) { + lessThanToken = this.eatToken(80 /* LessThanToken */); + + result = this.parseSeparatedSyntaxList(262144 /* TypeArgumentList_Types */); + typeArguments = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + + return this.factory.typeArgumentList(lessThanToken, typeArguments, greaterThanToken); + } + + var rewindPoint = this.getRewindPoint(); + + lessThanToken = this.eatToken(80 /* LessThanToken */); + + result = this.parseSeparatedSyntaxList(262144 /* TypeArgumentList_Types */); + typeArguments = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + + if (greaterThanToken.fullWidth() === 0 || !this.canFollowTypeArgumentListInExpression(this.currentToken().kind())) { + this.rewind(rewindPoint); + + this.releaseRewindPoint(rewindPoint); + return null; + } else { + this.releaseRewindPoint(rewindPoint); + var typeArgumentList = this.factory.typeArgumentList(lessThanToken, typeArguments, greaterThanToken); + + return typeArgumentList; + } + }; + + ParserImpl.prototype.canFollowTypeArgumentListInExpression = function (kind) { + switch (kind) { + case 72 /* OpenParenToken */: + case 76 /* DotToken */: + + case 73 /* CloseParenToken */: + case 75 /* CloseBracketToken */: + case 106 /* ColonToken */: + case 78 /* SemicolonToken */: + case 79 /* CommaToken */: + case 105 /* QuestionToken */: + case 84 /* EqualsEqualsToken */: + case 87 /* EqualsEqualsEqualsToken */: + case 86 /* ExclamationEqualsToken */: + case 88 /* ExclamationEqualsEqualsToken */: + case 103 /* AmpersandAmpersandToken */: + case 104 /* BarBarToken */: + case 100 /* CaretToken */: + case 98 /* AmpersandToken */: + case 99 /* BarToken */: + case 71 /* CloseBraceToken */: + case 10 /* EndOfFileToken */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.parseName = function () { + var shouldContinue = this.isIdentifier(this.currentToken()); + var current = this.eatIdentifierToken(); + + while (shouldContinue && this.currentToken().tokenKind === 76 /* DotToken */) { + var dotToken = this.eatToken(76 /* DotToken */); + + var currentToken = this.currentToken(); + var identifierName; + + if (TypeScript.SyntaxFacts.isAnyKeyword(currentToken.tokenKind) && this.previousToken().hasTrailingNewLine() && !currentToken.hasTrailingNewLine() && TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(this.peekToken(1))) { + identifierName = this.createMissingToken(11 /* IdentifierName */, currentToken); + } else { + identifierName = this.eatIdentifierNameToken(); + } + + current = this.factory.qualifiedName(current, dotToken, identifierName); + + shouldContinue = identifierName.fullWidth() > 0; + } + + return current; + }; + + ParserImpl.prototype.isEnumDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 46 /* EnumKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 46 /* EnumKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseEnumDeclaration = function () { + var modifiers = this.parseModifiers(); + var enumKeyword = this.eatKeyword(46 /* EnumKeyword */); + var identifier = this.eatIdentifierToken(); + + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + var enumElements = TypeScript.Syntax.emptySeparatedList; + + if (openBraceToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(256 /* EnumDeclaration_EnumElements */); + enumElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.enumDeclaration(modifiers, enumKeyword, identifier, openBraceToken, enumElements, closeBraceToken); + }; + + ParserImpl.prototype.isEnumElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().kind() === 243 /* EnumElement */) { + return true; + } + + return this.isPropertyName(this.currentToken(), inErrorRecovery); + }; + + ParserImpl.prototype.parseEnumElement = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 243 /* EnumElement */) { + return this.eatNode(); + } + + var propertyName = this.eatPropertyName(); + var equalsValueClause = null; + if (this.isEqualsValueClause(false)) { + equalsValueClause = this.parseEqualsValueClause(true); + } + + return this.factory.enumElement(propertyName, equalsValueClause); + }; + + ParserImpl.isModifier = function (token) { + switch (token.tokenKind) { + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + case 47 /* ExportKeyword */: + case 63 /* DeclareKeyword */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.modifierCount = function () { + var modifierCount = 0; + while (true) { + if (ParserImpl.isModifier(this.peekToken(modifierCount))) { + modifierCount++; + continue; + } + + break; + } + + return modifierCount; + }; + + ParserImpl.prototype.parseModifiers = function () { + var tokens = this.getArray(); + + while (true) { + if (ParserImpl.isModifier(this.currentToken())) { + tokens.push(this.eatAnyToken()); + continue; + } + + break; + } + + var result = TypeScript.Syntax.list(tokens); + + this.returnZeroOrOneLengthArray(tokens); + + return result; + }; + + ParserImpl.prototype.isClassDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 44 /* ClassKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 44 /* ClassKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseHeritageClauses = function () { + var heritageClauses = TypeScript.Syntax.emptyList; + + if (this.isHeritageClause()) { + var result = this.parseSyntaxList(1024 /* ClassOrInterfaceDeclaration_HeritageClauses */); + heritageClauses = result.list; + TypeScript.Debug.assert(result.skippedTokens.length === 0); + } + + return heritageClauses; + }; + + ParserImpl.prototype.parseClassDeclaration = function () { + var modifiers = this.parseModifiers(); + + var classKeyword = this.eatKeyword(44 /* ClassKeyword */); + var identifier = this.eatIdentifierToken(); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var heritageClauses = this.parseHeritageClauses(); + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + var classElements = TypeScript.Syntax.emptyList; + + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(2 /* ClassDeclaration_ClassElements */); + + classElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + return this.factory.classDeclaration(modifiers, classKeyword, identifier, typeParameterList, heritageClauses, openBraceToken, classElements, closeBraceToken); + }; + + ParserImpl.isPublicOrPrivateKeyword = function (token) { + return token.tokenKind === 57 /* PublicKeyword */ || token.tokenKind === 55 /* PrivateKeyword */; + }; + + ParserImpl.prototype.isAccessor = function (inErrorRecovery) { + var index = this.modifierCount(); + + if (this.peekToken(index).tokenKind !== 64 /* GetKeyword */ && this.peekToken(index).tokenKind !== 68 /* SetKeyword */) { + return false; + } + + index++; + return this.isPropertyName(this.peekToken(index), inErrorRecovery); + }; + + ParserImpl.prototype.parseAccessor = function (checkForStrictMode) { + var modifiers = this.parseModifiers(); + + if (this.currentToken().tokenKind === 64 /* GetKeyword */) { + return this.parseGetMemberAccessorDeclaration(modifiers, checkForStrictMode); + } else if (this.currentToken().tokenKind === 68 /* SetKeyword */) { + return this.parseSetMemberAccessorDeclaration(modifiers, checkForStrictMode); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseGetMemberAccessorDeclaration = function (modifiers, checkForStrictMode) { + var getKeyword = this.eatKeyword(64 /* GetKeyword */); + var propertyName = this.eatPropertyName(); + var parameterList = this.parseParameterList(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + var block = this.parseBlock(false, checkForStrictMode); + + return this.factory.getAccessor(modifiers, getKeyword, propertyName, parameterList, typeAnnotation, block); + }; + + ParserImpl.prototype.parseSetMemberAccessorDeclaration = function (modifiers, checkForStrictMode) { + var setKeyword = this.eatKeyword(68 /* SetKeyword */); + var propertyName = this.eatPropertyName(); + var parameterList = this.parseParameterList(); + var block = this.parseBlock(false, checkForStrictMode); + + return this.factory.setAccessor(modifiers, setKeyword, propertyName, parameterList, block); + }; + + ParserImpl.prototype.isClassElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isClassElement()) { + return true; + } + + return this.isConstructorDeclaration() || this.isMemberFunctionDeclaration(inErrorRecovery) || this.isAccessor(inErrorRecovery) || this.isMemberVariableDeclaration(inErrorRecovery) || this.isIndexMemberDeclaration(); + }; + + ParserImpl.prototype.parseClassElement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isClassElement()) { + return this.eatNode(); + } + + if (this.isConstructorDeclaration()) { + return this.parseConstructorDeclaration(); + } else if (this.isMemberFunctionDeclaration(inErrorRecovery)) { + return this.parseMemberFunctionDeclaration(); + } else if (this.isAccessor(inErrorRecovery)) { + return this.parseAccessor(false); + } else if (this.isMemberVariableDeclaration(inErrorRecovery)) { + return this.parseMemberVariableDeclaration(); + } else if (this.isIndexMemberDeclaration()) { + return this.parseIndexMemberDeclaration(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isConstructorDeclaration = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 62 /* ConstructorKeyword */; + }; + + ParserImpl.prototype.parseConstructorDeclaration = function () { + var modifiers = this.parseModifiers(); + var constructorKeyword = this.eatKeyword(62 /* ConstructorKeyword */); + var callSignature = this.parseCallSignature(false); + + var semicolonToken = null; + var block = null; + + if (this.isBlock()) { + block = this.parseBlock(false, true); + } else { + semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.constructorDeclaration(modifiers, constructorKeyword, callSignature, block, semicolonToken); + }; + + ParserImpl.prototype.isMemberFunctionDeclaration = function (inErrorRecovery) { + var index = 0; + + while (true) { + var token = this.peekToken(index); + if (this.isPropertyName(token, inErrorRecovery) && this.isCallSignature(index + 1)) { + return true; + } + + if (ParserImpl.isModifier(token)) { + index++; + continue; + } + + return false; + } + }; + + ParserImpl.prototype.parseMemberFunctionDeclaration = function () { + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (this.isPropertyName(currentToken, false) && this.isCallSignature(1)) { + break; + } + + TypeScript.Debug.assert(ParserImpl.isModifier(currentToken)); + modifierArray.push(this.eatAnyToken()); + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var propertyName = this.eatPropertyName(); + var callSignature = this.parseCallSignature(false); + + var parseBlockEvenWithNoOpenBrace = false; + var newCallSignature = this.tryAddUnexpectedEqualsGreaterThanToken(callSignature); + if (newCallSignature !== callSignature) { + parseBlockEvenWithNoOpenBrace = true; + callSignature = newCallSignature; + } + + var block = null; + var semicolon = null; + + if (parseBlockEvenWithNoOpenBrace || this.isBlock()) { + block = this.parseBlock(parseBlockEvenWithNoOpenBrace, true); + } else { + semicolon = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.memberFunctionDeclaration(modifiers, propertyName, callSignature, block, semicolon); + }; + + ParserImpl.prototype.isDefinitelyMemberVariablePropertyName = function (index) { + if (TypeScript.SyntaxFacts.isAnyKeyword(this.peekToken(index).tokenKind)) { + switch (this.peekToken(index + 1).tokenKind) { + case 78 /* SemicolonToken */: + case 107 /* EqualsToken */: + case 106 /* ColonToken */: + case 71 /* CloseBraceToken */: + case 10 /* EndOfFileToken */: + return true; + default: + return false; + } + } else { + return true; + } + }; + + ParserImpl.prototype.isMemberVariableDeclaration = function (inErrorRecovery) { + var index = 0; + + while (true) { + var token = this.peekToken(index); + if (this.isPropertyName(token, inErrorRecovery) && this.isDefinitelyMemberVariablePropertyName(index)) { + return true; + } + + if (ParserImpl.isModifier(this.peekToken(index))) { + index++; + continue; + } + + return false; + } + }; + + ParserImpl.prototype.parseMemberVariableDeclaration = function () { + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (this.isPropertyName(currentToken, false) && this.isDefinitelyMemberVariablePropertyName(0)) { + break; + } + + TypeScript.Debug.assert(ParserImpl.isModifier(currentToken)); + modifierArray.push(this.eatAnyToken()); + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var variableDeclarator = this.parseVariableDeclarator(true, true); + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.memberVariableDeclaration(modifiers, variableDeclarator, semicolon); + }; + + ParserImpl.prototype.isIndexMemberDeclaration = function () { + var index = this.modifierCount(); + return this.isIndexSignature(index); + }; + + ParserImpl.prototype.parseIndexMemberDeclaration = function () { + var modifiers = this.parseModifiers(); + var indexSignature = this.parseIndexSignature(); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.indexMemberDeclaration(modifiers, indexSignature, semicolonToken); + }; + + ParserImpl.prototype.tryAddUnexpectedEqualsGreaterThanToken = function (callSignature) { + var token0 = this.currentToken(); + + var hasEqualsGreaterThanToken = token0.tokenKind === 85 /* EqualsGreaterThanToken */; + if (hasEqualsGreaterThanToken) { + if (callSignature.lastToken()) { + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token0.width(), TypeScript.DiagnosticCode.Unexpected_token_0_expected, [TypeScript.SyntaxFacts.getText(70 /* OpenBraceToken */)]); + this.addDiagnostic(diagnostic); + + var token = this.eatAnyToken(); + return this.addSkippedTokenAfterNode(callSignature, token0); + } + } + + return callSignature; + }; + + ParserImpl.prototype.isFunctionDeclaration = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 27 /* FunctionKeyword */; + }; + + ParserImpl.prototype.parseFunctionDeclaration = function () { + var modifiers = this.parseModifiers(); + var functionKeyword = this.eatKeyword(27 /* FunctionKeyword */); + var identifier = this.eatIdentifierToken(); + var callSignature = this.parseCallSignature(false); + + var parseBlockEvenWithNoOpenBrace = false; + var newCallSignature = this.tryAddUnexpectedEqualsGreaterThanToken(callSignature); + if (newCallSignature !== callSignature) { + parseBlockEvenWithNoOpenBrace = true; + callSignature = newCallSignature; + } + + var semicolonToken = null; + var block = null; + + if (parseBlockEvenWithNoOpenBrace || this.isBlock()) { + block = this.parseBlock(parseBlockEvenWithNoOpenBrace, true); + } else { + semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + } + + return this.factory.functionDeclaration(modifiers, functionKeyword, identifier, callSignature, block, semicolonToken); + }; + + ParserImpl.prototype.isModuleDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 65 /* ModuleKeyword */) { + return true; + } + + if (this.currentToken().tokenKind === 65 /* ModuleKeyword */) { + var token1 = this.peekToken(1); + return this.isIdentifier(token1) || token1.tokenKind === 14 /* StringLiteral */; + } + + return false; + }; + + ParserImpl.prototype.parseModuleDeclaration = function () { + var modifiers = this.parseModifiers(); + var moduleKeyword = this.eatKeyword(65 /* ModuleKeyword */); + + var moduleName = null; + var stringLiteral = null; + + if (this.currentToken().tokenKind === 14 /* StringLiteral */) { + stringLiteral = this.eatToken(14 /* StringLiteral */); + } else { + moduleName = this.parseName(); + } + + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var moduleElements = TypeScript.Syntax.emptyList; + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(4 /* ModuleDeclaration_ModuleElements */); + moduleElements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.moduleDeclaration(modifiers, moduleKeyword, moduleName, stringLiteral, openBraceToken, moduleElements, closeBraceToken); + }; + + ParserImpl.prototype.isInterfaceDeclaration = function (modifierCount) { + if (modifierCount > 0 && this.peekToken(modifierCount).tokenKind === 52 /* InterfaceKeyword */) { + return true; + } + + return this.currentToken().tokenKind === 52 /* InterfaceKeyword */ && this.isIdentifier(this.peekToken(1)); + }; + + ParserImpl.prototype.parseInterfaceDeclaration = function () { + var modifiers = this.parseModifiers(); + var interfaceKeyword = this.eatKeyword(52 /* InterfaceKeyword */); + var identifier = this.eatIdentifierToken(); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var heritageClauses = this.parseHeritageClauses(); + + var objectType = this.parseObjectType(); + return this.factory.interfaceDeclaration(modifiers, interfaceKeyword, identifier, typeParameterList, heritageClauses, objectType); + }; + + ParserImpl.prototype.parseObjectType = function () { + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var typeMembers = TypeScript.Syntax.emptySeparatedList; + if (openBraceToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(512 /* ObjectType_TypeMembers */); + typeMembers = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + return this.factory.objectType(openBraceToken, typeMembers, closeBraceToken); + }; + + ParserImpl.prototype.isTypeMember = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isTypeMember()) { + return true; + } + + return this.isCallSignature(0) || this.isConstructSignature() || this.isIndexSignature(0) || this.isMethodSignature(inErrorRecovery) || this.isPropertySignature(inErrorRecovery); + }; + + ParserImpl.prototype.parseTypeMember = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isTypeMember()) { + return this.eatNode(); + } + + if (this.isCallSignature(0)) { + return this.parseCallSignature(false); + } else if (this.isConstructSignature()) { + return this.parseConstructSignature(); + } else if (this.isIndexSignature(0)) { + return this.parseIndexSignature(); + } else if (this.isMethodSignature(inErrorRecovery)) { + return this.parseMethodSignature(); + } else if (this.isPropertySignature(inErrorRecovery)) { + return this.parsePropertySignature(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseConstructSignature = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + var callSignature = this.parseCallSignature(false); + + return this.factory.constructSignature(newKeyword, callSignature); + }; + + ParserImpl.prototype.parseIndexSignature = function () { + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + var parameter = this.parseParameter(); + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.indexSignature(openBracketToken, parameter, closeBracketToken, typeAnnotation); + }; + + ParserImpl.prototype.parseMethodSignature = function () { + var propertyName = this.eatPropertyName(); + var questionToken = this.tryEatToken(105 /* QuestionToken */); + var callSignature = this.parseCallSignature(false); + + return this.factory.methodSignature(propertyName, questionToken, callSignature); + }; + + ParserImpl.prototype.parsePropertySignature = function () { + var propertyName = this.eatPropertyName(); + var questionToken = this.tryEatToken(105 /* QuestionToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.propertySignature(propertyName, questionToken, typeAnnotation); + }; + + ParserImpl.prototype.isCallSignature = function (tokenIndex) { + var tokenKind = this.peekToken(tokenIndex).tokenKind; + return tokenKind === 72 /* OpenParenToken */ || tokenKind === 80 /* LessThanToken */; + }; + + ParserImpl.prototype.isConstructSignature = function () { + if (this.currentToken().tokenKind !== 31 /* NewKeyword */) { + return false; + } + + var token1 = this.peekToken(1); + return token1.tokenKind === 80 /* LessThanToken */ || token1.tokenKind === 72 /* OpenParenToken */; + }; + + ParserImpl.prototype.isIndexSignature = function (tokenIndex) { + return this.peekToken(tokenIndex).tokenKind === 74 /* OpenBracketToken */; + }; + + ParserImpl.prototype.isMethodSignature = function (inErrorRecovery) { + if (this.isPropertyName(this.currentToken(), inErrorRecovery)) { + if (this.isCallSignature(1)) { + return true; + } + + if (this.peekToken(1).tokenKind === 105 /* QuestionToken */ && this.isCallSignature(2)) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.isPropertySignature = function (inErrorRecovery) { + var currentToken = this.currentToken(); + + if (ParserImpl.isModifier(currentToken) && !currentToken.hasTrailingNewLine() && this.isPropertyName(this.peekToken(1), inErrorRecovery)) { + return false; + } + + return this.isPropertyName(currentToken, inErrorRecovery); + }; + + ParserImpl.prototype.isHeritageClause = function () { + var token0 = this.currentToken(); + return token0.tokenKind === 48 /* ExtendsKeyword */ || token0.tokenKind === 51 /* ImplementsKeyword */; + }; + + ParserImpl.prototype.isNotHeritageClauseTypeName = function () { + if (this.currentToken().tokenKind === 51 /* ImplementsKeyword */ || this.currentToken().tokenKind === 48 /* ExtendsKeyword */) { + return this.isIdentifier(this.peekToken(1)); + } + + return false; + }; + + ParserImpl.prototype.isHeritageClauseTypeName = function () { + if (this.isIdentifier(this.currentToken())) { + return !this.isNotHeritageClauseTypeName(); + } + + return false; + }; + + ParserImpl.prototype.parseHeritageClause = function () { + var extendsOrImplementsKeyword = this.eatAnyToken(); + TypeScript.Debug.assert(extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */ || extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + + var result = this.parseSeparatedSyntaxList(2048 /* HeritageClause_TypeNameList */); + var typeNames = result.list; + extendsOrImplementsKeyword = this.addSkippedTokensAfterToken(extendsOrImplementsKeyword, result.skippedTokens); + + return this.factory.heritageClause(extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */ ? 230 /* ExtendsHeritageClause */ : 231 /* ImplementsHeritageClause */, extendsOrImplementsKeyword, typeNames); + }; + + ParserImpl.prototype.isStatement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isStatement()) { + return true; + } + + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + switch (currentTokenKind) { + case 57 /* PublicKeyword */: + case 55 /* PrivateKeyword */: + case 58 /* StaticKeyword */: + var token1 = this.peekToken(1); + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token1)) { + return false; + } + + break; + + case 28 /* IfKeyword */: + case 70 /* OpenBraceToken */: + case 33 /* ReturnKeyword */: + case 34 /* SwitchKeyword */: + case 36 /* ThrowKeyword */: + case 15 /* BreakKeyword */: + case 18 /* ContinueKeyword */: + case 26 /* ForKeyword */: + case 42 /* WhileKeyword */: + case 43 /* WithKeyword */: + case 22 /* DoKeyword */: + case 38 /* TryKeyword */: + case 19 /* DebuggerKeyword */: + return true; + } + + if (this.isInterfaceDeclaration(0) || this.isClassDeclaration(0) || this.isEnumDeclaration(0) || this.isModuleDeclaration(0)) { + return false; + } + + return this.isLabeledStatement(currentToken) || this.isVariableStatement() || this.isFunctionDeclaration() || this.isEmptyStatement(currentToken, inErrorRecovery) || this.isExpressionStatement(currentToken); + }; + + ParserImpl.prototype.parseStatement = function (inErrorRecovery) { + if (this.currentNode() !== null && this.currentNode().isStatement()) { + return this.eatNode(); + } + + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + + switch (currentTokenKind) { + case 28 /* IfKeyword */: + return this.parseIfStatement(); + case 70 /* OpenBraceToken */: + return this.parseBlock(false, false); + case 33 /* ReturnKeyword */: + return this.parseReturnStatement(); + case 34 /* SwitchKeyword */: + return this.parseSwitchStatement(); + case 36 /* ThrowKeyword */: + return this.parseThrowStatement(); + case 15 /* BreakKeyword */: + return this.parseBreakStatement(); + case 18 /* ContinueKeyword */: + return this.parseContinueStatement(); + case 26 /* ForKeyword */: + return this.parseForOrForInStatement(); + case 42 /* WhileKeyword */: + return this.parseWhileStatement(); + case 43 /* WithKeyword */: + return this.parseWithStatement(); + case 22 /* DoKeyword */: + return this.parseDoStatement(); + case 38 /* TryKeyword */: + return this.parseTryStatement(); + case 19 /* DebuggerKeyword */: + return this.parseDebuggerStatement(); + } + + if (this.isVariableStatement()) { + return this.parseVariableStatement(); + } else if (this.isLabeledStatement(currentToken)) { + return this.parseLabeledStatement(); + } else if (this.isFunctionDeclaration()) { + return this.parseFunctionDeclaration(); + } else if (this.isEmptyStatement(currentToken, inErrorRecovery)) { + return this.parseEmptyStatement(); + } else { + return this.parseExpressionStatement(); + } + }; + + ParserImpl.prototype.parseDebuggerStatement = function () { + var debuggerKeyword = this.eatKeyword(19 /* DebuggerKeyword */); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.debuggerStatement(debuggerKeyword, semicolonToken); + }; + + ParserImpl.prototype.parseDoStatement = function () { + var doKeyword = this.eatKeyword(22 /* DoKeyword */); + var statement = this.parseStatement(false); + var whileKeyword = this.eatKeyword(42 /* WhileKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(true); + + return this.factory.doStatement(doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); + }; + + ParserImpl.prototype.isLabeledStatement = function (currentToken) { + return this.isIdentifier(currentToken) && this.peekToken(1).tokenKind === 106 /* ColonToken */; + }; + + ParserImpl.prototype.parseLabeledStatement = function () { + var identifier = this.eatIdentifierToken(); + var colonToken = this.eatToken(106 /* ColonToken */); + var statement = this.parseStatement(false); + + return this.factory.labeledStatement(identifier, colonToken, statement); + }; + + ParserImpl.prototype.parseTryStatement = function () { + var tryKeyword = this.eatKeyword(38 /* TryKeyword */); + + var savedListParsingState = this.listParsingState; + this.listParsingState |= 64 /* TryBlock_Statements */; + var block = this.parseBlock(false, false); + this.listParsingState = savedListParsingState; + + var catchClause = null; + if (this.isCatchClause()) { + catchClause = this.parseCatchClause(); + } + + var finallyClause = null; + if (catchClause === null || this.isFinallyClause()) { + finallyClause = this.parseFinallyClause(); + } + + return this.factory.tryStatement(tryKeyword, block, catchClause, finallyClause); + }; + + ParserImpl.prototype.isCatchClause = function () { + return this.currentToken().tokenKind === 17 /* CatchKeyword */; + }; + + ParserImpl.prototype.parseCatchClause = function () { + var catchKeyword = this.eatKeyword(17 /* CatchKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var identifier = this.eatIdentifierToken(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + var savedListParsingState = this.listParsingState; + this.listParsingState |= 128 /* CatchBlock_Statements */; + var block = this.parseBlock(false, false); + this.listParsingState = savedListParsingState; + + return this.factory.catchClause(catchKeyword, openParenToken, identifier, typeAnnotation, closeParenToken, block); + }; + + ParserImpl.prototype.isFinallyClause = function () { + return this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.parseFinallyClause = function () { + var finallyKeyword = this.eatKeyword(25 /* FinallyKeyword */); + var block = this.parseBlock(false, false); + + return this.factory.finallyClause(finallyKeyword, block); + }; + + ParserImpl.prototype.parseWithStatement = function () { + var withKeyword = this.eatKeyword(43 /* WithKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.withStatement(withKeyword, openParenToken, condition, closeParenToken, statement); + }; + + ParserImpl.prototype.parseWhileStatement = function () { + var whileKeyword = this.eatKeyword(42 /* WhileKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.whileStatement(whileKeyword, openParenToken, condition, closeParenToken, statement); + }; + + ParserImpl.prototype.isEmptyStatement = function (currentToken, inErrorRecovery) { + if (inErrorRecovery) { + return false; + } + + return currentToken.tokenKind === 78 /* SemicolonToken */; + }; + + ParserImpl.prototype.parseEmptyStatement = function () { + var semicolonToken = this.eatToken(78 /* SemicolonToken */); + return this.factory.emptyStatement(semicolonToken); + }; + + ParserImpl.prototype.parseForOrForInStatement = function () { + var forKeyword = this.eatKeyword(26 /* ForKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + + var currentToken = this.currentToken(); + if (currentToken.tokenKind === 40 /* VarKeyword */) { + return this.parseForOrForInStatementWithVariableDeclaration(forKeyword, openParenToken); + } else if (currentToken.tokenKind === 78 /* SemicolonToken */) { + return this.parseForStatementWithNoVariableDeclarationOrInitializer(forKeyword, openParenToken); + } else { + return this.parseForOrForInStatementWithInitializer(forKeyword, openParenToken); + } + }; + + ParserImpl.prototype.parseForOrForInStatementWithVariableDeclaration = function (forKeyword, openParenToken) { + var variableDeclaration = this.parseVariableDeclaration(false); + + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return this.parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null); + } + + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, variableDeclaration, null); + }; + + ParserImpl.prototype.parseForInStatementWithVariableDeclarationOrInitializer = function (forKeyword, openParenToken, variableDeclaration, initializer) { + var inKeyword = this.eatKeyword(29 /* InKeyword */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.forInStatement(forKeyword, openParenToken, variableDeclaration, initializer, inKeyword, expression, closeParenToken, statement); + }; + + ParserImpl.prototype.parseForOrForInStatementWithInitializer = function (forKeyword, openParenToken) { + var initializer = this.parseExpression(false); + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return this.parseForInStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + } else { + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, initializer); + } + }; + + ParserImpl.prototype.parseForStatementWithNoVariableDeclarationOrInitializer = function (forKeyword, openParenToken) { + return this.parseForStatementWithVariableDeclarationOrInitializer(forKeyword, openParenToken, null, null); + }; + + ParserImpl.prototype.parseForStatementWithVariableDeclarationOrInitializer = function (forKeyword, openParenToken, variableDeclaration, initializer) { + var firstSemicolonToken = this.eatToken(78 /* SemicolonToken */); + + var condition = null; + if (this.currentToken().tokenKind !== 78 /* SemicolonToken */ && this.currentToken().tokenKind !== 73 /* CloseParenToken */ && this.currentToken().tokenKind !== 10 /* EndOfFileToken */) { + condition = this.parseExpression(true); + } + + var secondSemicolonToken = this.eatToken(78 /* SemicolonToken */); + + var incrementor = null; + if (this.currentToken().tokenKind !== 73 /* CloseParenToken */ && this.currentToken().tokenKind !== 10 /* EndOfFileToken */) { + incrementor = this.parseExpression(true); + } + + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + return this.factory.forStatement(forKeyword, openParenToken, variableDeclaration, initializer, firstSemicolonToken, condition, secondSemicolonToken, incrementor, closeParenToken, statement); + }; + + ParserImpl.prototype.parseBreakStatement = function () { + var breakKeyword = this.eatKeyword(15 /* BreakKeyword */); + + var identifier = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + } + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + return this.factory.breakStatement(breakKeyword, identifier, semicolon); + }; + + ParserImpl.prototype.parseContinueStatement = function () { + var continueKeyword = this.eatKeyword(18 /* ContinueKeyword */); + + var identifier = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + } + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + return this.factory.continueStatement(continueKeyword, identifier, semicolon); + }; + + ParserImpl.prototype.parseSwitchStatement = function () { + var switchKeyword = this.eatKeyword(34 /* SwitchKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var switchClauses = TypeScript.Syntax.emptyList; + if (openBraceToken.width() > 0) { + var result = this.parseSyntaxList(8 /* SwitchStatement_SwitchClauses */); + switchClauses = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + return this.factory.switchStatement(switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, switchClauses, closeBraceToken); + }; + + ParserImpl.prototype.isCaseSwitchClause = function () { + return this.currentToken().tokenKind === 16 /* CaseKeyword */; + }; + + ParserImpl.prototype.isDefaultSwitchClause = function () { + return this.currentToken().tokenKind === 20 /* DefaultKeyword */; + }; + + ParserImpl.prototype.isSwitchClause = function () { + if (this.currentNode() !== null && this.currentNode().isSwitchClause()) { + return true; + } + + return this.isCaseSwitchClause() || this.isDefaultSwitchClause(); + }; + + ParserImpl.prototype.parseSwitchClause = function () { + if (this.currentNode() !== null && this.currentNode().isSwitchClause()) { + return this.eatNode(); + } + + if (this.isCaseSwitchClause()) { + return this.parseCaseSwitchClause(); + } else if (this.isDefaultSwitchClause()) { + return this.parseDefaultSwitchClause(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseCaseSwitchClause = function () { + var caseKeyword = this.eatKeyword(16 /* CaseKeyword */); + var expression = this.parseExpression(true); + var colonToken = this.eatToken(106 /* ColonToken */); + var statements = TypeScript.Syntax.emptyList; + + if (colonToken.fullWidth() > 0) { + var result = this.parseSyntaxList(16 /* SwitchClause_Statements */); + statements = result.list; + colonToken = this.addSkippedTokensAfterToken(colonToken, result.skippedTokens); + } + + return this.factory.caseSwitchClause(caseKeyword, expression, colonToken, statements); + }; + + ParserImpl.prototype.parseDefaultSwitchClause = function () { + var defaultKeyword = this.eatKeyword(20 /* DefaultKeyword */); + var colonToken = this.eatToken(106 /* ColonToken */); + var statements = TypeScript.Syntax.emptyList; + + if (colonToken.fullWidth() > 0) { + var result = this.parseSyntaxList(16 /* SwitchClause_Statements */); + statements = result.list; + colonToken = this.addSkippedTokensAfterToken(colonToken, result.skippedTokens); + } + + return this.factory.defaultSwitchClause(defaultKeyword, colonToken, statements); + }; + + ParserImpl.prototype.parseThrowStatement = function () { + var throwKeyword = this.eatKeyword(36 /* ThrowKeyword */); + + var expression = null; + if (this.canEatExplicitOrAutomaticSemicolon(false)) { + var token = this.createMissingToken(11 /* IdentifierName */, null); + expression = token; + } else { + expression = this.parseExpression(true); + } + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.throwStatement(throwKeyword, expression, semicolonToken); + }; + + ParserImpl.prototype.parseReturnStatement = function () { + var returnKeyword = this.eatKeyword(33 /* ReturnKeyword */); + + var expression = null; + if (!this.canEatExplicitOrAutomaticSemicolon(false)) { + expression = this.parseExpression(true); + } + + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.returnStatement(returnKeyword, expression, semicolonToken); + }; + + ParserImpl.prototype.isExpressionStatement = function (currentToken) { + var kind = currentToken.tokenKind; + if (kind === 70 /* OpenBraceToken */ || kind === 27 /* FunctionKeyword */) { + return false; + } + + return this.isExpression(currentToken); + }; + + ParserImpl.prototype.isAssignmentOrOmittedExpression = function () { + var currentToken = this.currentToken(); + if (currentToken.tokenKind === 79 /* CommaToken */) { + return true; + } + + return this.isExpression(currentToken); + }; + + ParserImpl.prototype.parseAssignmentOrOmittedExpression = function () { + if (this.currentToken().tokenKind === 79 /* CommaToken */) { + return this.factory.omittedExpression(); + } + + return this.parseAssignmentExpression(true); + }; + + ParserImpl.prototype.isExpression = function (currentToken) { + switch (currentToken.tokenKind) { + case 13 /* NumericLiteral */: + case 14 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + + case 74 /* OpenBracketToken */: + + case 72 /* OpenParenToken */: + + case 80 /* LessThanToken */: + + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + case 89 /* PlusToken */: + case 90 /* MinusToken */: + case 102 /* TildeToken */: + case 101 /* ExclamationToken */: + + case 70 /* OpenBraceToken */: + + case 85 /* EqualsGreaterThanToken */: + + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + + case 50 /* SuperKeyword */: + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + + case 31 /* NewKeyword */: + + case 21 /* DeleteKeyword */: + case 41 /* VoidKeyword */: + case 39 /* TypeOfKeyword */: + + case 27 /* FunctionKeyword */: + return true; + } + + return this.isIdentifier(currentToken); + }; + + ParserImpl.prototype.parseExpressionStatement = function () { + var expression = this.parseExpression(true); + + var semicolon = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.expressionStatement(expression, semicolon); + }; + + ParserImpl.prototype.parseIfStatement = function () { + var ifKeyword = this.eatKeyword(28 /* IfKeyword */); + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var condition = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + var statement = this.parseStatement(false); + + var elseClause = null; + if (this.isElseClause()) { + elseClause = this.parseElseClause(); + } + + return this.factory.ifStatement(ifKeyword, openParenToken, condition, closeParenToken, statement, elseClause); + }; + + ParserImpl.prototype.isElseClause = function () { + return this.currentToken().tokenKind === 23 /* ElseKeyword */; + }; + + ParserImpl.prototype.parseElseClause = function () { + var elseKeyword = this.eatKeyword(23 /* ElseKeyword */); + var statement = this.parseStatement(false); + + return this.factory.elseClause(elseKeyword, statement); + }; + + ParserImpl.prototype.isVariableStatement = function () { + var index = this.modifierCount(); + return this.peekToken(index).tokenKind === 40 /* VarKeyword */; + }; + + ParserImpl.prototype.parseVariableStatement = function () { + var modifiers = this.parseModifiers(); + var variableDeclaration = this.parseVariableDeclaration(true); + var semicolonToken = this.eatExplicitOrAutomaticSemicolon(false); + + return this.factory.variableStatement(modifiers, variableDeclaration, semicolonToken); + }; + + ParserImpl.prototype.parseVariableDeclaration = function (allowIn) { + var varKeyword = this.eatKeyword(40 /* VarKeyword */); + + var listParsingState = allowIn ? 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */ : 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */; + + var result = this.parseSeparatedSyntaxList(listParsingState); + var variableDeclarators = result.list; + varKeyword = this.addSkippedTokensAfterToken(varKeyword, result.skippedTokens); + + return this.factory.variableDeclaration(varKeyword, variableDeclarators); + }; + + ParserImpl.prototype.isVariableDeclarator = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 225 /* VariableDeclarator */) { + return true; + } + + return this.isIdentifier(this.currentToken()); + }; + + ParserImpl.prototype.canReuseVariableDeclaratorNode = function (node) { + if (node === null || node.kind() !== 225 /* VariableDeclarator */) { + return false; + } + + var variableDeclarator = node; + return variableDeclarator.equalsValueClause === null; + }; + + ParserImpl.prototype.parseVariableDeclarator = function (allowIn, allowPropertyName) { + if (this.canReuseVariableDeclaratorNode(this.currentNode())) { + return this.eatNode(); + } + + var propertyName = allowPropertyName ? this.eatPropertyName() : this.eatIdentifierToken(); + var equalsValueClause = null; + var typeAnnotation = null; + + if (propertyName.width() > 0) { + typeAnnotation = this.parseOptionalTypeAnnotation(false); + + if (this.isEqualsValueClause(false)) { + equalsValueClause = this.parseEqualsValueClause(allowIn); + } + } + + return this.factory.variableDeclarator(propertyName, typeAnnotation, equalsValueClause); + }; + + ParserImpl.prototype.isColonValueClause = function () { + return this.currentToken().tokenKind === 106 /* ColonToken */; + }; + + ParserImpl.prototype.isEqualsValueClause = function (inParameter) { + var token0 = this.currentToken(); + if (token0.tokenKind === 107 /* EqualsToken */) { + return true; + } + + if (!this.previousToken().hasTrailingNewLine()) { + if (token0.tokenKind === 85 /* EqualsGreaterThanToken */) { + return false; + } + + if (token0.tokenKind === 70 /* OpenBraceToken */ && inParameter) { + return false; + } + + return this.isExpression(token0); + } + + return false; + }; + + ParserImpl.prototype.parseEqualsValueClause = function (allowIn) { + var equalsToken = this.eatToken(107 /* EqualsToken */); + var value = this.parseAssignmentExpression(allowIn); + + return this.factory.equalsValueClause(equalsToken, value); + }; + + ParserImpl.prototype.parseExpression = function (allowIn) { + return this.parseSubExpression(0, allowIn); + }; + + ParserImpl.prototype.parseAssignmentExpression = function (allowIn) { + return this.parseSubExpression(2 /* AssignmentExpressionPrecedence */, allowIn); + }; + + ParserImpl.prototype.parseUnaryExpressionOrLower = function () { + var currentTokenKind = this.currentToken().tokenKind; + if (TypeScript.SyntaxFacts.isPrefixUnaryExpressionOperatorToken(currentTokenKind)) { + var operatorKind = TypeScript.SyntaxFacts.getPrefixUnaryExpressionFromOperatorToken(currentTokenKind); + + var operatorToken = this.eatAnyToken(); + + var operand = this.parseUnaryExpressionOrLower(); + return this.factory.prefixUnaryExpression(operatorKind, operatorToken, operand); + } else if (currentTokenKind === 39 /* TypeOfKeyword */) { + return this.parseTypeOfExpression(); + } else if (currentTokenKind === 41 /* VoidKeyword */) { + return this.parseVoidExpression(); + } else if (currentTokenKind === 21 /* DeleteKeyword */) { + return this.parseDeleteExpression(); + } else if (currentTokenKind === 80 /* LessThanToken */) { + return this.parseCastExpression(); + } else { + return this.parsePostfixExpressionOrLower(); + } + }; + + ParserImpl.prototype.parseSubExpression = function (precedence, allowIn) { + if (precedence <= 2 /* AssignmentExpressionPrecedence */) { + if (this.isSimpleArrowFunctionExpression()) { + return this.parseSimpleArrowFunctionExpression(); + } + + var parethesizedArrowFunction = this.tryParseParenthesizedArrowFunctionExpression(); + if (parethesizedArrowFunction !== null) { + return parethesizedArrowFunction; + } + } + + var leftOperand = this.parseUnaryExpressionOrLower(); + return this.parseBinaryOrConditionalExpressions(precedence, allowIn, leftOperand); + }; + + ParserImpl.prototype.parseBinaryOrConditionalExpressions = function (precedence, allowIn, leftOperand) { + while (true) { + var token0 = this.currentToken(); + var token0Kind = token0.tokenKind; + + if (TypeScript.SyntaxFacts.isBinaryExpressionOperatorToken(token0Kind)) { + if (token0Kind === 29 /* InKeyword */ && !allowIn) { + break; + } + + var mergedToken = this.tryMergeBinaryExpressionTokens(); + var tokenKind = mergedToken === null ? token0Kind : mergedToken.syntaxKind; + + var binaryExpressionKind = TypeScript.SyntaxFacts.getBinaryExpressionFromOperatorToken(tokenKind); + var newPrecedence = ParserImpl.getPrecedence(binaryExpressionKind); + + if (newPrecedence < precedence) { + break; + } + + if (newPrecedence === precedence && !this.isRightAssociative(binaryExpressionKind)) { + break; + } + + var operatorToken = mergedToken === null ? token0 : TypeScript.Syntax.token(mergedToken.syntaxKind).withLeadingTrivia(token0.leadingTrivia()).withTrailingTrivia(this.peekToken(mergedToken.tokenCount - 1).trailingTrivia()); + + var skipCount = mergedToken === null ? 1 : mergedToken.tokenCount; + for (var i = 0; i < skipCount; i++) { + this.eatAnyToken(); + } + + leftOperand = this.factory.binaryExpression(binaryExpressionKind, leftOperand, operatorToken, this.parseSubExpression(newPrecedence, allowIn)); + continue; + } + + if (token0Kind === 105 /* QuestionToken */ && precedence <= 3 /* ConditionalExpressionPrecedence */) { + var questionToken = this.eatToken(105 /* QuestionToken */); + + var whenTrueExpression = this.parseAssignmentExpression(allowIn); + var colon = this.eatToken(106 /* ColonToken */); + + var whenFalseExpression = this.parseAssignmentExpression(allowIn); + leftOperand = this.factory.conditionalExpression(leftOperand, questionToken, whenTrueExpression, colon, whenFalseExpression); + continue; + } + + break; + } + + return leftOperand; + }; + + ParserImpl.prototype.tryMergeBinaryExpressionTokens = function () { + var token0 = this.currentToken(); + + if (token0.tokenKind === 81 /* GreaterThanToken */ && !token0.hasTrailingTrivia()) { + var storage = this.mergeTokensStorage; + storage[0] = 0 /* None */; + storage[1] = 0 /* None */; + storage[2] = 0 /* None */; + + for (var i = 0; i < storage.length; i++) { + var nextToken = this.peekToken(i + 1); + + if (!nextToken.hasLeadingTrivia()) { + storage[i] = nextToken.tokenKind; + } + + if (nextToken.hasTrailingTrivia()) { + break; + } + } + + if (storage[0] === 81 /* GreaterThanToken */) { + if (storage[1] === 81 /* GreaterThanToken */) { + if (storage[2] === 107 /* EqualsToken */) { + return { tokenCount: 4, syntaxKind: 114 /* GreaterThanGreaterThanGreaterThanEqualsToken */ }; + } else { + return { tokenCount: 3, syntaxKind: 97 /* GreaterThanGreaterThanGreaterThanToken */ }; + } + } else if (storage[1] === 107 /* EqualsToken */) { + return { tokenCount: 3, syntaxKind: 113 /* GreaterThanGreaterThanEqualsToken */ }; + } else { + return { tokenCount: 2, syntaxKind: 96 /* GreaterThanGreaterThanToken */ }; + } + } else if (storage[0] === 107 /* EqualsToken */) { + return { tokenCount: 2, syntaxKind: 83 /* GreaterThanEqualsToken */ }; + } + } + + return null; + }; + + ParserImpl.prototype.isRightAssociative = function (expressionKind) { + switch (expressionKind) { + case 174 /* AssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + return true; + default: + return false; + } + }; + + ParserImpl.prototype.parseMemberExpressionOrLower = function (inObjectCreation) { + if (this.currentToken().tokenKind === 31 /* NewKeyword */) { + return this.parseObjectCreationExpression(); + } + + var expression = this.parsePrimaryExpression(); + if (expression === null) { + return this.eatIdentifierToken(); + } + + return this.parseMemberExpressionRest(expression, false, inObjectCreation); + }; + + ParserImpl.prototype.parseCallExpressionOrLower = function () { + var expression; + if (this.currentToken().tokenKind === 50 /* SuperKeyword */) { + expression = this.eatKeyword(50 /* SuperKeyword */); + + var currentTokenKind = this.currentToken().tokenKind; + if (currentTokenKind !== 72 /* OpenParenToken */ && currentTokenKind !== 76 /* DotToken */) { + expression = this.factory.memberAccessExpression(expression, this.eatToken(76 /* DotToken */), this.eatIdentifierNameToken()); + } + } else { + expression = this.parseMemberExpressionOrLower(false); + } + + return this.parseMemberExpressionRest(expression, true, false); + }; + + ParserImpl.prototype.parseMemberExpressionRest = function (expression, allowArguments, inObjectCreation) { + while (true) { + var currentTokenKind = this.currentToken().tokenKind; + + switch (currentTokenKind) { + case 72 /* OpenParenToken */: + if (!allowArguments) { + return expression; + } + + expression = this.factory.invocationExpression(expression, this.parseArgumentList(null)); + continue; + + case 80 /* LessThanToken */: + if (!allowArguments) { + return expression; + } + + var argumentList = this.tryParseArgumentList(); + if (argumentList !== null) { + expression = this.factory.invocationExpression(expression, argumentList); + continue; + } + + break; + + case 74 /* OpenBracketToken */: + expression = this.parseElementAccessExpression(expression, inObjectCreation); + continue; + + case 76 /* DotToken */: + expression = this.factory.memberAccessExpression(expression, this.eatToken(76 /* DotToken */), this.eatIdentifierNameToken()); + continue; + } + + return expression; + } + }; + + ParserImpl.prototype.parseLeftHandSideExpressionOrLower = function () { + if (this.currentToken().tokenKind === 31 /* NewKeyword */) { + return this.parseObjectCreationExpression(); + } else { + return this.parseCallExpressionOrLower(); + } + }; + + ParserImpl.prototype.parsePostfixExpressionOrLower = function () { + var expression = this.parseLeftHandSideExpressionOrLower(); + if (expression === null) { + return this.eatIdentifierToken(); + } + + var currentTokenKind = this.currentToken().tokenKind; + + switch (currentTokenKind) { + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + if (this.previousToken() !== null && this.previousToken().hasTrailingNewLine()) { + break; + } + + return this.factory.postfixUnaryExpression(TypeScript.SyntaxFacts.getPostfixUnaryExpressionFromOperatorToken(currentTokenKind), expression, this.eatAnyToken()); + } + + return expression; + }; + + ParserImpl.prototype.tryParseGenericArgumentList = function () { + var rewindPoint = this.getRewindPoint(); + + var typeArgumentList = this.tryParseTypeArgumentList(true); + var token0 = this.currentToken(); + + var isOpenParen = token0.tokenKind === 72 /* OpenParenToken */; + var isDot = token0.tokenKind === 76 /* DotToken */; + var isOpenParenOrDot = isOpenParen || isDot; + + var argumentList = null; + if (typeArgumentList === null || !isOpenParenOrDot) { + this.rewind(rewindPoint); + this.releaseRewindPoint(rewindPoint); + return null; + } else { + this.releaseRewindPoint(rewindPoint); + + if (isDot) { + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token0.width(), TypeScript.DiagnosticCode.A_parameter_list_must_follow_a_generic_type_argument_list_expected, null); + this.addDiagnostic(diagnostic); + + return this.factory.argumentList(typeArgumentList, TypeScript.Syntax.emptyToken(72 /* OpenParenToken */), TypeScript.Syntax.emptySeparatedList, TypeScript.Syntax.emptyToken(73 /* CloseParenToken */)); + } else { + return this.parseArgumentList(typeArgumentList); + } + } + }; + + ParserImpl.prototype.tryParseArgumentList = function () { + if (this.currentToken().tokenKind === 80 /* LessThanToken */) { + return this.tryParseGenericArgumentList(); + } + + if (this.currentToken().tokenKind === 72 /* OpenParenToken */) { + return this.parseArgumentList(null); + } + + return null; + }; + + ParserImpl.prototype.parseArgumentList = function (typeArgumentList) { + var openParenToken = this.eatToken(72 /* OpenParenToken */); + + var _arguments = TypeScript.Syntax.emptySeparatedList; + + if (openParenToken.fullWidth() > 0) { + var result = this.parseSeparatedSyntaxList(16384 /* ArgumentList_AssignmentExpressions */); + _arguments = result.list; + openParenToken = this.addSkippedTokensAfterToken(openParenToken, result.skippedTokens); + } + + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + return this.factory.argumentList(typeArgumentList, openParenToken, _arguments, closeParenToken); + }; + + ParserImpl.prototype.parseElementAccessExpression = function (expression, inObjectCreation) { + var start = this.currentTokenStart(); + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + var argumentExpression; + + if (this.currentToken().tokenKind === 75 /* CloseBracketToken */ && inObjectCreation) { + var end = this.currentTokenStart() + this.currentToken().width(); + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, start, end - start, TypeScript.DiagnosticCode.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead, null); + this.addDiagnostic(diagnostic); + + argumentExpression = TypeScript.Syntax.emptyToken(11 /* IdentifierName */); + } else { + argumentExpression = this.parseExpression(true); + } + + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + + return this.factory.elementAccessExpression(expression, openBracketToken, argumentExpression, closeBracketToken); + }; + + ParserImpl.prototype.parsePrimaryExpression = function () { + var currentToken = this.currentToken(); + + if (this.isIdentifier(currentToken)) { + return this.eatIdentifierToken(); + } + + var currentTokenKind = currentToken.tokenKind; + switch (currentTokenKind) { + case 35 /* ThisKeyword */: + return this.parseThisExpression(); + + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return this.parseLiteralExpression(); + + case 32 /* NullKeyword */: + return this.parseLiteralExpression(); + + case 27 /* FunctionKeyword */: + return this.parseFunctionExpression(); + + case 13 /* NumericLiteral */: + return this.parseLiteralExpression(); + + case 12 /* RegularExpressionLiteral */: + return this.parseLiteralExpression(); + + case 14 /* StringLiteral */: + return this.parseLiteralExpression(); + + case 74 /* OpenBracketToken */: + return this.parseArrayLiteralExpression(); + + case 70 /* OpenBraceToken */: + return this.parseObjectLiteralExpression(); + + case 72 /* OpenParenToken */: + return this.parseParenthesizedExpression(); + + case 118 /* SlashToken */: + case 119 /* SlashEqualsToken */: + var result = this.tryReparseDivideAsRegularExpression(); + if (result !== null) { + return result; + } + break; + } + + return null; + }; + + ParserImpl.prototype.tryReparseDivideAsRegularExpression = function () { + var currentToken = this.currentToken(); + + if (this.previousToken() !== null) { + var previousTokenKind = this.previousToken().tokenKind; + switch (previousTokenKind) { + case 11 /* IdentifierName */: + return null; + + case 35 /* ThisKeyword */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return null; + + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + case 12 /* RegularExpressionLiteral */: + case 93 /* PlusPlusToken */: + case 94 /* MinusMinusToken */: + case 75 /* CloseBracketToken */: + return null; + } + } + + currentToken = this.currentTokenAllowingRegularExpression(); + + if (currentToken.tokenKind === 118 /* SlashToken */ || currentToken.tokenKind === 119 /* SlashEqualsToken */) { + return null; + } else if (currentToken.tokenKind === 12 /* RegularExpressionLiteral */) { + return this.parseLiteralExpression(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.parseTypeOfExpression = function () { + var typeOfKeyword = this.eatKeyword(39 /* TypeOfKeyword */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.typeOfExpression(typeOfKeyword, expression); + }; + + ParserImpl.prototype.parseDeleteExpression = function () { + var deleteKeyword = this.eatKeyword(21 /* DeleteKeyword */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.deleteExpression(deleteKeyword, expression); + }; + + ParserImpl.prototype.parseVoidExpression = function () { + var voidKeyword = this.eatKeyword(41 /* VoidKeyword */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.voidExpression(voidKeyword, expression); + }; + + ParserImpl.prototype.parseFunctionExpression = function () { + var functionKeyword = this.eatKeyword(27 /* FunctionKeyword */); + var identifier = null; + + if (this.isIdentifier(this.currentToken())) { + identifier = this.eatIdentifierToken(); + } + + var callSignature = this.parseCallSignature(false); + var block = this.parseBlock(false, true); + + return this.factory.functionExpression(functionKeyword, identifier, callSignature, block); + }; + + ParserImpl.prototype.parseObjectCreationExpression = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + + var expression = this.parseObjectCreationExpressionOrLower(true); + var argumentList = this.tryParseArgumentList(); + + var result = this.factory.objectCreationExpression(newKeyword, expression, argumentList); + return this.parseMemberExpressionRest(result, true, false); + }; + + ParserImpl.prototype.parseObjectCreationExpressionOrLower = function (inObjectCreation) { + if (this.currentToken().tokenKind === 31 /* NewKeyword */) { + return this.parseObjectCreationExpression(); + } else { + return this.parseMemberExpressionOrLower(inObjectCreation); + } + }; + + ParserImpl.prototype.parseCastExpression = function () { + var lessThanToken = this.eatToken(80 /* LessThanToken */); + var type = this.parseType(); + var greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + var expression = this.parseUnaryExpressionOrLower(); + + return this.factory.castExpression(lessThanToken, type, greaterThanToken, expression); + }; + + ParserImpl.prototype.parseParenthesizedExpression = function () { + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var expression = this.parseExpression(true); + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + + return this.factory.parenthesizedExpression(openParenToken, expression, closeParenToken); + }; + + ParserImpl.prototype.tryParseParenthesizedArrowFunctionExpression = function () { + var tokenKind = this.currentToken().tokenKind; + if (tokenKind !== 72 /* OpenParenToken */ && tokenKind !== 80 /* LessThanToken */) { + return null; + } + + if (this.isDefinitelyArrowFunctionExpression()) { + return this.parseParenthesizedArrowFunctionExpression(false); + } + + if (!this.isPossiblyArrowFunctionExpression()) { + return null; + } + + var rewindPoint = this.getRewindPoint(); + + var arrowFunction = this.parseParenthesizedArrowFunctionExpression(true); + if (arrowFunction === null) { + this.rewind(rewindPoint); + } + + this.releaseRewindPoint(rewindPoint); + return arrowFunction; + }; + + ParserImpl.prototype.parseParenthesizedArrowFunctionExpression = function (requireArrow) { + var currentToken = this.currentToken(); + + var callSignature = this.parseCallSignature(true); + + if (requireArrow && this.currentToken().tokenKind !== 85 /* EqualsGreaterThanToken */) { + return null; + } + + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + + var block = this.tryParseArrowFunctionBlock(); + var expression = null; + if (block === null) { + expression = this.parseAssignmentExpression(true); + } + + return this.factory.parenthesizedArrowFunctionExpression(callSignature, equalsGreaterThanToken, block, expression); + }; + + ParserImpl.prototype.tryParseArrowFunctionBlock = function () { + if (this.isBlock()) { + return this.parseBlock(false, false); + } else { + if (this.isStatement(false) && !this.isExpressionStatement(this.currentToken()) && !this.isFunctionDeclaration()) { + return this.parseBlock(true, false); + } else { + return null; + } + } + }; + + ParserImpl.prototype.isSimpleArrowFunctionExpression = function () { + if (this.currentToken().tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + + return this.isIdentifier(this.currentToken()) && this.peekToken(1).tokenKind === 85 /* EqualsGreaterThanToken */; + }; + + ParserImpl.prototype.parseSimpleArrowFunctionExpression = function () { + var identifier = this.eatIdentifierToken(); + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + + var block = this.tryParseArrowFunctionBlock(); + var expression = null; + if (block === null) { + expression = this.parseAssignmentExpression(true); + } + + return this.factory.simpleArrowFunctionExpression(identifier, equalsGreaterThanToken, block, expression); + }; + + ParserImpl.prototype.isBlock = function () { + return this.currentToken().tokenKind === 70 /* OpenBraceToken */; + }; + + ParserImpl.prototype.isDefinitelyArrowFunctionExpression = function () { + var token0 = this.currentToken(); + if (token0.tokenKind !== 72 /* OpenParenToken */) { + return false; + } + + var token1 = this.peekToken(1); + var token2; + + if (token1.tokenKind === 73 /* CloseParenToken */) { + token2 = this.peekToken(2); + return token2.tokenKind === 106 /* ColonToken */ || token2.tokenKind === 85 /* EqualsGreaterThanToken */ || token2.tokenKind === 70 /* OpenBraceToken */; + } + + if (token1.tokenKind === 77 /* DotDotDotToken */) { + return true; + } + + token2 = this.peekToken(2); + if (token1.tokenKind === 57 /* PublicKeyword */ || token1.tokenKind === 55 /* PrivateKeyword */) { + if (this.isIdentifier(token2)) { + return true; + } + } + + if (!this.isIdentifier(token1)) { + return false; + } + + if (token2.tokenKind === 106 /* ColonToken */) { + return true; + } + + var token3 = this.peekToken(3); + if (token2.tokenKind === 105 /* QuestionToken */) { + if (token3.tokenKind === 106 /* ColonToken */ || token3.tokenKind === 73 /* CloseParenToken */ || token3.tokenKind === 79 /* CommaToken */) { + return true; + } + } + + if (token2.tokenKind === 73 /* CloseParenToken */) { + if (token3.tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.isPossiblyArrowFunctionExpression = function () { + var token0 = this.currentToken(); + if (token0.tokenKind !== 72 /* OpenParenToken */) { + return true; + } + + var token1 = this.peekToken(1); + + if (!this.isIdentifier(token1)) { + return false; + } + + var token2 = this.peekToken(2); + if (token2.tokenKind === 107 /* EqualsToken */) { + return true; + } + + if (token2.tokenKind === 79 /* CommaToken */) { + return true; + } + + if (token2.tokenKind === 73 /* CloseParenToken */) { + var token3 = this.peekToken(3); + if (token3.tokenKind === 106 /* ColonToken */) { + return true; + } + } + + return false; + }; + + ParserImpl.prototype.parseObjectLiteralExpression = function () { + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var result = this.parseSeparatedSyntaxList(32768 /* ObjectLiteralExpression_PropertyAssignments */); + var propertyAssignments = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.objectLiteralExpression(openBraceToken, propertyAssignments, closeBraceToken); + }; + + ParserImpl.prototype.parsePropertyAssignment = function (inErrorRecovery) { + if (this.isAccessor(inErrorRecovery)) { + return this.parseAccessor(true); + } else if (this.isFunctionPropertyAssignment(inErrorRecovery)) { + return this.parseFunctionPropertyAssignment(); + } else if (this.isSimplePropertyAssignment(inErrorRecovery)) { + return this.parseSimplePropertyAssignment(); + } else { + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isPropertyAssignment = function (inErrorRecovery) { + return this.isAccessor(inErrorRecovery) || this.isFunctionPropertyAssignment(inErrorRecovery) || this.isSimplePropertyAssignment(inErrorRecovery); + }; + + ParserImpl.prototype.eatPropertyName = function () { + return TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(this.currentToken()) ? this.eatIdentifierNameToken() : this.eatAnyToken(); + }; + + ParserImpl.prototype.isFunctionPropertyAssignment = function (inErrorRecovery) { + return this.isPropertyName(this.currentToken(), inErrorRecovery) && this.isCallSignature(1); + }; + + ParserImpl.prototype.parseFunctionPropertyAssignment = function () { + var propertyName = this.eatPropertyName(); + var callSignature = this.parseCallSignature(false); + var block = this.parseBlock(false, true); + + return this.factory.functionPropertyAssignment(propertyName, callSignature, block); + }; + + ParserImpl.prototype.isSimplePropertyAssignment = function (inErrorRecovery) { + return this.isPropertyName(this.currentToken(), inErrorRecovery); + }; + + ParserImpl.prototype.parseSimplePropertyAssignment = function () { + var propertyName = this.eatPropertyName(); + var colonToken = this.eatToken(106 /* ColonToken */); + var expression = this.parseAssignmentExpression(true); + + return this.factory.simplePropertyAssignment(propertyName, colonToken, expression); + }; + + ParserImpl.prototype.isPropertyName = function (token, inErrorRecovery) { + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) { + if (inErrorRecovery) { + return this.isIdentifier(token); + } else { + return true; + } + } + + switch (token.tokenKind) { + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + return true; + + default: + return false; + } + }; + + ParserImpl.prototype.parseArrayLiteralExpression = function () { + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + + var result = this.parseSeparatedSyntaxList(65536 /* ArrayLiteralExpression_AssignmentExpressions */); + var expressions = result.list; + openBracketToken = this.addSkippedTokensAfterToken(openBracketToken, result.skippedTokens); + + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + + return this.factory.arrayLiteralExpression(openBracketToken, expressions, closeBracketToken); + }; + + ParserImpl.prototype.parseLiteralExpression = function () { + return this.eatAnyToken(); + }; + + ParserImpl.prototype.parseThisExpression = function () { + return this.eatKeyword(35 /* ThisKeyword */); + }; + + ParserImpl.prototype.parseBlock = function (parseBlockEvenWithNoOpenBrace, checkForStrictMode) { + var openBraceToken = this.eatToken(70 /* OpenBraceToken */); + + var statements = TypeScript.Syntax.emptyList; + + if (parseBlockEvenWithNoOpenBrace || openBraceToken.width() > 0) { + var savedIsInStrictMode = this.isInStrictMode; + + var processItems = checkForStrictMode ? ParserImpl.updateStrictModeState : null; + var result = this.parseSyntaxList(32 /* Block_Statements */, processItems); + statements = result.list; + openBraceToken = this.addSkippedTokensAfterToken(openBraceToken, result.skippedTokens); + + this.setStrictMode(savedIsInStrictMode); + } + + var closeBraceToken = this.eatToken(71 /* CloseBraceToken */); + + return this.factory.block(openBraceToken, statements, closeBraceToken); + }; + + ParserImpl.prototype.parseCallSignature = function (requireCompleteTypeParameterList) { + var typeParameterList = this.parseOptionalTypeParameterList(requireCompleteTypeParameterList); + var parameterList = this.parseParameterList(); + var typeAnnotation = this.parseOptionalTypeAnnotation(false); + + return this.factory.callSignature(typeParameterList, parameterList, typeAnnotation); + }; + + ParserImpl.prototype.parseOptionalTypeParameterList = function (requireCompleteTypeParameterList) { + if (this.currentToken().tokenKind !== 80 /* LessThanToken */) { + return null; + } + + var rewindPoint = this.getRewindPoint(); + + var lessThanToken = this.eatToken(80 /* LessThanToken */); + + var result = this.parseSeparatedSyntaxList(524288 /* TypeParameterList_TypeParameters */); + var typeParameters = result.list; + lessThanToken = this.addSkippedTokensAfterToken(lessThanToken, result.skippedTokens); + + var greaterThanToken = this.eatToken(81 /* GreaterThanToken */); + + if (requireCompleteTypeParameterList && greaterThanToken.fullWidth() === 0) { + this.rewind(rewindPoint); + this.releaseRewindPoint(rewindPoint); + return null; + } else { + this.releaseRewindPoint(rewindPoint); + var typeParameterList = this.factory.typeParameterList(lessThanToken, typeParameters, greaterThanToken); + + return typeParameterList; + } + }; + + ParserImpl.prototype.isTypeParameter = function () { + return this.isIdentifier(this.currentToken()); + }; + + ParserImpl.prototype.parseTypeParameter = function () { + var identifier = this.eatIdentifierToken(); + var constraint = this.parseOptionalConstraint(); + + return this.factory.typeParameter(identifier, constraint); + }; + + ParserImpl.prototype.parseOptionalConstraint = function () { + if (this.currentToken().kind() !== 48 /* ExtendsKeyword */) { + return null; + } + + var extendsKeyword = this.eatKeyword(48 /* ExtendsKeyword */); + var type = this.parseType(); + + return this.factory.constraint(extendsKeyword, type); + }; + + ParserImpl.prototype.parseParameterList = function () { + var openParenToken = this.eatToken(72 /* OpenParenToken */); + var parameters = TypeScript.Syntax.emptySeparatedList; + + if (openParenToken.width() > 0) { + var result = this.parseSeparatedSyntaxList(131072 /* ParameterList_Parameters */); + parameters = result.list; + openParenToken = this.addSkippedTokensAfterToken(openParenToken, result.skippedTokens); + } + + var closeParenToken = this.eatToken(73 /* CloseParenToken */); + return this.factory.parameterList(openParenToken, parameters, closeParenToken); + }; + + ParserImpl.prototype.isTypeAnnotation = function () { + return this.currentToken().tokenKind === 106 /* ColonToken */; + }; + + ParserImpl.prototype.parseOptionalTypeAnnotation = function (allowStringLiteral) { + return this.isTypeAnnotation() ? this.parseTypeAnnotation(allowStringLiteral) : null; + }; + + ParserImpl.prototype.parseTypeAnnotation = function (allowStringLiteral) { + var colonToken = this.eatToken(106 /* ColonToken */); + var type = allowStringLiteral && this.currentToken().tokenKind === 14 /* StringLiteral */ ? this.eatToken(14 /* StringLiteral */) : this.parseType(); + + return this.factory.typeAnnotation(colonToken, type); + }; + + ParserImpl.prototype.isType = function () { + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + + switch (currentTokenKind) { + case 39 /* TypeOfKeyword */: + + case 60 /* AnyKeyword */: + case 67 /* NumberKeyword */: + case 61 /* BooleanKeyword */: + case 69 /* StringKeyword */: + case 41 /* VoidKeyword */: + + case 70 /* OpenBraceToken */: + + case 72 /* OpenParenToken */: + case 80 /* LessThanToken */: + + case 31 /* NewKeyword */: + return true; + } + + return this.isIdentifier(currentToken); + }; + + ParserImpl.prototype.parseType = function () { + var currentToken = this.currentToken(); + var currentTokenKind = currentToken.tokenKind; + + var type = this.parseNonArrayType(currentToken); + + while (this.currentToken().tokenKind === 74 /* OpenBracketToken */) { + var openBracketToken = this.eatToken(74 /* OpenBracketToken */); + var closeBracketToken = this.eatToken(75 /* CloseBracketToken */); + + type = this.factory.arrayType(type, openBracketToken, closeBracketToken); + } + + return type; + }; + + ParserImpl.prototype.isTypeQuery = function () { + return this.currentToken().tokenKind === 39 /* TypeOfKeyword */; + }; + + ParserImpl.prototype.parseTypeQuery = function () { + var typeOfKeyword = this.eatToken(39 /* TypeOfKeyword */); + var name = this.parseName(); + + return this.factory.typeQuery(typeOfKeyword, name); + }; + + ParserImpl.prototype.parseNonArrayType = function (currentToken) { + var currentTokenKind = currentToken.tokenKind; + switch (currentTokenKind) { + case 60 /* AnyKeyword */: + case 67 /* NumberKeyword */: + case 61 /* BooleanKeyword */: + case 69 /* StringKeyword */: + case 41 /* VoidKeyword */: + return this.eatAnyToken(); + + case 70 /* OpenBraceToken */: + return this.parseObjectType(); + + case 72 /* OpenParenToken */: + case 80 /* LessThanToken */: + return this.parseFunctionType(); + + case 31 /* NewKeyword */: + return this.parseConstructorType(); + + case 39 /* TypeOfKeyword */: + return this.parseTypeQuery(); + } + + return this.parseNameOrGenericType(); + }; + + ParserImpl.prototype.parseNameOrGenericType = function () { + var name = this.parseName(); + var typeArgumentList = this.tryParseTypeArgumentList(false); + + return typeArgumentList === null ? name : this.factory.genericType(name, typeArgumentList); + }; + + ParserImpl.prototype.parseFunctionType = function () { + var typeParameterList = this.parseOptionalTypeParameterList(false); + var parameterList = this.parseParameterList(); + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + var returnType = this.parseType(); + + return this.factory.functionType(typeParameterList, parameterList, equalsGreaterThanToken, returnType); + }; + + ParserImpl.prototype.parseConstructorType = function () { + var newKeyword = this.eatKeyword(31 /* NewKeyword */); + var typeParameterList = this.parseOptionalTypeParameterList(false); + var parameterList = this.parseParameterList(); + var equalsGreaterThanToken = this.eatToken(85 /* EqualsGreaterThanToken */); + var type = this.parseType(); + + return this.factory.constructorType(newKeyword, typeParameterList, parameterList, equalsGreaterThanToken, type); + }; + + ParserImpl.prototype.isParameter = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 242 /* Parameter */) { + return true; + } + + var token = this.currentToken(); + var tokenKind = token.tokenKind; + if (tokenKind === 77 /* DotDotDotToken */) { + return true; + } + + if (ParserImpl.isModifier(token) && !this.isModifierUsedAsParameterIdentifier(token)) { + return true; + } + + return this.isIdentifier(token); + }; + + ParserImpl.prototype.isModifierUsedAsParameterIdentifier = function (token) { + if (this.isIdentifier(token)) { + var nextTokenKind = this.peekToken(1).tokenKind; + switch (nextTokenKind) { + case 73 /* CloseParenToken */: + case 106 /* ColonToken */: + case 107 /* EqualsToken */: + case 79 /* CommaToken */: + case 105 /* QuestionToken */: + return true; + } + } + + return false; + }; + + ParserImpl.prototype.parseParameter = function () { + if (this.currentNode() !== null && this.currentNode().kind() === 242 /* Parameter */) { + return this.eatNode(); + } + + var dotDotDotToken = this.tryEatToken(77 /* DotDotDotToken */); + + var modifierArray = this.getArray(); + + while (true) { + var currentToken = this.currentToken(); + if (ParserImpl.isModifier(currentToken) && !this.isModifierUsedAsParameterIdentifier(currentToken)) { + modifierArray.push(this.eatAnyToken()); + continue; + } + + break; + } + + var modifiers = TypeScript.Syntax.list(modifierArray); + this.returnZeroOrOneLengthArray(modifierArray); + + var identifier = this.eatIdentifierToken(); + var questionToken = this.tryEatToken(105 /* QuestionToken */); + var typeAnnotation = this.parseOptionalTypeAnnotation(true); + + var equalsValueClause = null; + if (this.isEqualsValueClause(true)) { + equalsValueClause = this.parseEqualsValueClause(true); + } + + return this.factory.parameter(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause); + }; + + ParserImpl.prototype.parseSyntaxList = function (currentListType, processItems) { + if (typeof processItems === "undefined") { processItems = null; } + var savedListParsingState = this.listParsingState; + this.listParsingState |= currentListType; + + var result = this.parseSyntaxListWorker(currentListType, processItems); + + this.listParsingState = savedListParsingState; + + return result; + }; + + ParserImpl.prototype.parseSeparatedSyntaxList = function (currentListType) { + var savedListParsingState = this.listParsingState; + this.listParsingState |= currentListType; + + var result = this.parseSeparatedSyntaxListWorker(currentListType); + + this.listParsingState = savedListParsingState; + + return result; + }; + + ParserImpl.prototype.abortParsingListOrMoveToNextToken = function (currentListType, items, skippedTokens) { + this.reportUnexpectedTokenDiagnostic(currentListType); + + for (var state = 524288 /* LastListParsingState */; state >= 1 /* FirstListParsingState */; state >>= 1) { + if ((this.listParsingState & state) !== 0) { + if (this.isExpectedListTerminator(state) || this.isExpectedListItem(state, true)) { + return true; + } + } + } + + var skippedToken = this.currentToken(); + + this.moveToNextToken(); + + this.addSkippedTokenToList(items, skippedTokens, skippedToken); + + return false; + }; + + ParserImpl.prototype.addSkippedTokenToList = function (items, skippedTokens, skippedToken) { + for (var i = items.length - 1; i >= 0; i--) { + var item = items[i]; + var lastToken = item.lastToken(); + if (lastToken.fullWidth() > 0) { + items[i] = this.addSkippedTokenAfterNodeOrToken(item, skippedToken); + return; + } + } + + skippedTokens.push(skippedToken); + }; + + ParserImpl.prototype.tryParseExpectedListItem = function (currentListType, inErrorRecovery, items, processItems) { + if (this.isExpectedListItem(currentListType, inErrorRecovery)) { + var item = this.parseExpectedListItem(currentListType, inErrorRecovery); + + items.push(item); + + if (processItems !== null) { + processItems(this, items); + } + } + }; + + ParserImpl.prototype.listIsTerminated = function (currentListType) { + return this.isExpectedListTerminator(currentListType) || this.currentToken().tokenKind === 10 /* EndOfFileToken */; + }; + + ParserImpl.prototype.getArray = function () { + if (this.arrayPool.length > 0) { + return this.arrayPool.pop(); + } + + return []; + }; + + ParserImpl.prototype.returnZeroOrOneLengthArray = function (array) { + if (array.length <= 1) { + this.returnArray(array); + } + }; + + ParserImpl.prototype.returnArray = function (array) { + array.length = 0; + this.arrayPool.push(array); + }; + + ParserImpl.prototype.parseSyntaxListWorker = function (currentListType, processItems) { + var items = this.getArray(); + var skippedTokens = this.getArray(); + + while (true) { + var oldItemsCount = items.length; + this.tryParseExpectedListItem(currentListType, false, items, processItems); + + var newItemsCount = items.length; + if (newItemsCount === oldItemsCount) { + if (this.listIsTerminated(currentListType)) { + break; + } + + var abort = this.abortParsingListOrMoveToNextToken(currentListType, items, skippedTokens); + if (abort) { + break; + } + } + } + + var result = TypeScript.Syntax.list(items); + + this.returnZeroOrOneLengthArray(items); + + return { skippedTokens: skippedTokens, list: result }; + }; + + ParserImpl.prototype.parseSeparatedSyntaxListWorker = function (currentListType) { + var items = this.getArray(); + var skippedTokens = this.getArray(); + TypeScript.Debug.assert(items.length === 0); + TypeScript.Debug.assert(skippedTokens.length === 0); + TypeScript.Debug.assert(skippedTokens !== items); + + var separatorKind = this.separatorKind(currentListType); + var allowAutomaticSemicolonInsertion = separatorKind === 78 /* SemicolonToken */; + + var inErrorRecovery = false; + var listWasTerminated = false; + while (true) { + var oldItemsCount = items.length; + + this.tryParseExpectedListItem(currentListType, inErrorRecovery, items, null); + + var newItemsCount = items.length; + if (newItemsCount === oldItemsCount) { + if (this.listIsTerminated(currentListType)) { + listWasTerminated = true; + break; + } + + var abort = this.abortParsingListOrMoveToNextToken(currentListType, items, skippedTokens); + if (abort) { + break; + } else { + inErrorRecovery = true; + continue; + } + } + + inErrorRecovery = false; + + var currentToken = this.currentToken(); + if (currentToken.tokenKind === separatorKind || currentToken.tokenKind === 79 /* CommaToken */) { + items.push(this.eatAnyToken()); + continue; + } + + if (this.listIsTerminated(currentListType)) { + listWasTerminated = true; + break; + } + + if (allowAutomaticSemicolonInsertion && this.canEatAutomaticSemicolon(false)) { + items.push(this.eatExplicitOrAutomaticSemicolon(false)); + + continue; + } + + items.push(this.eatToken(separatorKind)); + + inErrorRecovery = true; + } + + var result = TypeScript.Syntax.separatedList(items); + + this.returnZeroOrOneLengthArray(items); + + return { skippedTokens: skippedTokens, list: result }; + }; + + ParserImpl.prototype.separatorKind = function (currentListType) { + switch (currentListType) { + case 2048 /* HeritageClause_TypeNameList */: + case 16384 /* ArgumentList_AssignmentExpressions */: + case 256 /* EnumDeclaration_EnumElements */: + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + case 131072 /* ParameterList_Parameters */: + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + case 262144 /* TypeArgumentList_Types */: + case 524288 /* TypeParameterList_TypeParameters */: + return 79 /* CommaToken */; + + case 512 /* ObjectType_TypeMembers */: + return 78 /* SemicolonToken */; + + case 1 /* SourceUnit_ModuleElements */: + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + case 2 /* ClassDeclaration_ClassElements */: + case 4 /* ModuleDeclaration_ModuleElements */: + case 8 /* SwitchStatement_SwitchClauses */: + case 16 /* SwitchClause_Statements */: + case 32 /* Block_Statements */: + default: + throw TypeScript.Errors.notYetImplemented(); + } + }; + + ParserImpl.prototype.reportUnexpectedTokenDiagnostic = function (listType) { + var token = this.currentToken(); + + var diagnostic = new TypeScript.Diagnostic(this.fileName, this.lineMap, this.currentTokenStart(), token.width(), TypeScript.DiagnosticCode.Unexpected_token_0_expected, [this.getExpectedListElementType(listType)]); + this.addDiagnostic(diagnostic); + }; + + ParserImpl.prototype.addDiagnostic = function (diagnostic) { + if (this.diagnostics.length > 0 && this.diagnostics[this.diagnostics.length - 1].start() === diagnostic.start()) { + return; + } + + this.diagnostics.push(diagnostic); + }; + + ParserImpl.prototype.isExpectedListTerminator = function (currentListType) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.isExpectedSourceUnit_ModuleElementsTerminator(); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.isExpectedClassDeclaration_ClassElementsTerminator(); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.isExpectedModuleDeclaration_ModuleElementsTerminator(); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.isExpectedSwitchStatement_SwitchClausesTerminator(); + + case 16 /* SwitchClause_Statements */: + return this.isExpectedSwitchClause_StatementsTerminator(); + + case 32 /* Block_Statements */: + return this.isExpectedBlock_StatementsTerminator(); + + case 64 /* TryBlock_Statements */: + return this.isExpectedTryBlock_StatementsTerminator(); + + case 128 /* CatchBlock_Statements */: + return this.isExpectedCatchBlock_StatementsTerminator(); + + case 256 /* EnumDeclaration_EnumElements */: + return this.isExpectedEnumDeclaration_EnumElementsTerminator(); + + case 512 /* ObjectType_TypeMembers */: + return this.isExpectedObjectType_TypeMembersTerminator(); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.isExpectedArgumentList_AssignmentExpressionsTerminator(); + + case 2048 /* HeritageClause_TypeNameList */: + return this.isExpectedHeritageClause_TypeNameListTerminator(); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return this.isExpectedVariableDeclaration_VariableDeclarators_AllowInTerminator(); + + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.isExpectedVariableDeclaration_VariableDeclarators_DisallowInTerminator(); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.isExpectedObjectLiteralExpression_PropertyAssignmentsTerminator(); + + case 131072 /* ParameterList_Parameters */: + return this.isExpectedParameterList_ParametersTerminator(); + + case 262144 /* TypeArgumentList_Types */: + return this.isExpectedTypeArgumentList_TypesTerminator(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.isExpectedTypeParameterList_TypeParametersTerminator(); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.isExpectedLiteralExpression_AssignmentExpressionsTerminator(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isExpectedSourceUnit_ModuleElementsTerminator = function () { + return this.currentToken().tokenKind === 10 /* EndOfFileToken */; + }; + + ParserImpl.prototype.isExpectedEnumDeclaration_EnumElementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedModuleDeclaration_ModuleElementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedObjectType_TypeMembersTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedObjectLiteralExpression_PropertyAssignmentsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedLiteralExpression_AssignmentExpressionsTerminator = function () { + return this.currentToken().tokenKind === 75 /* CloseBracketToken */; + }; + + ParserImpl.prototype.isExpectedTypeArgumentList_TypesTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 81 /* GreaterThanToken */) { + return true; + } + + if (this.canFollowTypeArgumentListInExpression(token.tokenKind)) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedTypeParameterList_TypeParametersTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 81 /* GreaterThanToken */) { + return true; + } + + if (token.tokenKind === 72 /* OpenParenToken */ || token.tokenKind === 70 /* OpenBraceToken */ || token.tokenKind === 48 /* ExtendsKeyword */ || token.tokenKind === 51 /* ImplementsKeyword */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedParameterList_ParametersTerminator = function () { + var token = this.currentToken(); + if (token.tokenKind === 73 /* CloseParenToken */) { + return true; + } + + if (token.tokenKind === 70 /* OpenBraceToken */) { + return true; + } + + if (token.tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedVariableDeclaration_VariableDeclarators_DisallowInTerminator = function () { + if (this.currentToken().tokenKind === 78 /* SemicolonToken */ || this.currentToken().tokenKind === 73 /* CloseParenToken */) { + return true; + } + + if (this.currentToken().tokenKind === 29 /* InKeyword */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedVariableDeclaration_VariableDeclarators_AllowInTerminator = function () { + if (this.previousToken().tokenKind === 79 /* CommaToken */) { + return false; + } + + if (this.currentToken().tokenKind === 85 /* EqualsGreaterThanToken */) { + return true; + } + + return this.canEatExplicitOrAutomaticSemicolon(false); + }; + + ParserImpl.prototype.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 70 /* OpenBraceToken */ || token0.tokenKind === 71 /* CloseBraceToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedHeritageClause_TypeNameListTerminator = function () { + var token0 = this.currentToken(); + if (token0.tokenKind === 48 /* ExtendsKeyword */ || token0.tokenKind === 51 /* ImplementsKeyword */) { + return true; + } + + if (this.isExpectedClassOrInterfaceDeclaration_HeritageClausesTerminator()) { + return true; + } + + return false; + }; + + ParserImpl.prototype.isExpectedArgumentList_AssignmentExpressionsTerminator = function () { + var token0 = this.currentToken(); + return token0.tokenKind === 73 /* CloseParenToken */ || token0.tokenKind === 78 /* SemicolonToken */; + }; + + ParserImpl.prototype.isExpectedClassDeclaration_ClassElementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedSwitchStatement_SwitchClausesTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedSwitchClause_StatementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */ || this.isSwitchClause(); + }; + + ParserImpl.prototype.isExpectedBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 71 /* CloseBraceToken */; + }; + + ParserImpl.prototype.isExpectedTryBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 17 /* CatchKeyword */ || this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.isExpectedCatchBlock_StatementsTerminator = function () { + return this.currentToken().tokenKind === 25 /* FinallyKeyword */; + }; + + ParserImpl.prototype.isExpectedListItem = function (currentListType, inErrorRecovery) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.isModuleElement(inErrorRecovery); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.isHeritageClause(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.isClassElement(inErrorRecovery); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.isModuleElement(inErrorRecovery); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.isSwitchClause(); + + case 16 /* SwitchClause_Statements */: + return this.isStatement(inErrorRecovery); + + case 32 /* Block_Statements */: + return this.isStatement(inErrorRecovery); + + case 64 /* TryBlock_Statements */: + case 128 /* CatchBlock_Statements */: + return false; + + case 256 /* EnumDeclaration_EnumElements */: + return this.isEnumElement(inErrorRecovery); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.isVariableDeclarator(); + + case 512 /* ObjectType_TypeMembers */: + return this.isTypeMember(inErrorRecovery); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.isExpectedArgumentList_AssignmentExpression(); + + case 2048 /* HeritageClause_TypeNameList */: + return this.isHeritageClauseTypeName(); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.isPropertyAssignment(inErrorRecovery); + + case 131072 /* ParameterList_Parameters */: + return this.isParameter(); + + case 262144 /* TypeArgumentList_Types */: + return this.isType(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.isTypeParameter(); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.isAssignmentOrOmittedExpression(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.isExpectedArgumentList_AssignmentExpression = function () { + var currentToken = this.currentToken(); + if (this.isExpression(currentToken)) { + return true; + } + + if (currentToken.tokenKind === 79 /* CommaToken */) { + return true; + } + + return false; + }; + + ParserImpl.prototype.parseExpectedListItem = function (currentListType, inErrorRecovery) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return this.parseModuleElement(inErrorRecovery); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return this.parseHeritageClause(); + + case 2 /* ClassDeclaration_ClassElements */: + return this.parseClassElement(inErrorRecovery); + + case 4 /* ModuleDeclaration_ModuleElements */: + return this.parseModuleElement(inErrorRecovery); + + case 8 /* SwitchStatement_SwitchClauses */: + return this.parseSwitchClause(); + + case 16 /* SwitchClause_Statements */: + return this.parseStatement(inErrorRecovery); + + case 32 /* Block_Statements */: + return this.parseStatement(inErrorRecovery); + + case 256 /* EnumDeclaration_EnumElements */: + return this.parseEnumElement(); + + case 512 /* ObjectType_TypeMembers */: + return this.parseTypeMember(inErrorRecovery); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return this.parseAssignmentExpression(true); + + case 2048 /* HeritageClause_TypeNameList */: + return this.parseNameOrGenericType(); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + return this.parseVariableDeclarator(true, false); + + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return this.parseVariableDeclarator(false, false); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return this.parsePropertyAssignment(inErrorRecovery); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return this.parseAssignmentOrOmittedExpression(); + + case 131072 /* ParameterList_Parameters */: + return this.parseParameter(); + + case 262144 /* TypeArgumentList_Types */: + return this.parseType(); + + case 524288 /* TypeParameterList_TypeParameters */: + return this.parseTypeParameter(); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + ParserImpl.prototype.getExpectedListElementType = function (currentListType) { + switch (currentListType) { + case 1 /* SourceUnit_ModuleElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.module_class_interface_enum_import_or_statement, null); + + case 1024 /* ClassOrInterfaceDeclaration_HeritageClauses */: + return '{'; + + case 2 /* ClassDeclaration_ClassElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.constructor_function_accessor_or_variable, null); + + case 4 /* ModuleDeclaration_ModuleElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.module_class_interface_enum_import_or_statement, null); + + case 8 /* SwitchStatement_SwitchClauses */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.case_or_default_clause, null); + + case 16 /* SwitchClause_Statements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.statement, null); + + case 32 /* Block_Statements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.statement, null); + + case 4096 /* VariableDeclaration_VariableDeclarators_AllowIn */: + case 8192 /* VariableDeclaration_VariableDeclarators_DisallowIn */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null); + + case 256 /* EnumDeclaration_EnumElements */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null); + + case 512 /* ObjectType_TypeMembers */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.call_construct_index_property_or_function_signature, null); + + case 16384 /* ArgumentList_AssignmentExpressions */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + + case 2048 /* HeritageClause_TypeNameList */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_name, null); + + case 32768 /* ObjectLiteralExpression_PropertyAssignments */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.property_or_accessor, null); + + case 131072 /* ParameterList_Parameters */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.parameter, null); + + case 262144 /* TypeArgumentList_Types */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type, null); + + case 524288 /* TypeParameterList_TypeParameters */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_parameter, null); + + case 65536 /* ArrayLiteralExpression_AssignmentExpressions */: + return TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + return ParserImpl; + })(); + + function parse(fileName, text, isDeclaration, options) { + var source = new NormalParserSource(fileName, text, options.languageVersion()); + + return new ParserImpl(fileName, text.lineMap(), source, options, text).parseSyntaxTree(isDeclaration); + } + Parser.parse = parse; + + function incrementalParse(oldSyntaxTree, textChangeRange, newText) { + if (textChangeRange.isUnchanged()) { + return oldSyntaxTree; + } + + var source = new IncrementalParserSource(oldSyntaxTree, textChangeRange, newText); + + return new ParserImpl(oldSyntaxTree.fileName(), newText.lineMap(), source, oldSyntaxTree.parseOptions(), newText).parseSyntaxTree(oldSyntaxTree.isDeclaration()); + } + Parser.incrementalParse = incrementalParse; + })(TypeScript.Parser || (TypeScript.Parser = {})); + var Parser = TypeScript.Parser; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTree = (function () { + function SyntaxTree(sourceUnit, isDeclaration, diagnostics, fileName, lineMap, parseOtions) { + this._allDiagnostics = null; + this._sourceUnit = sourceUnit; + this._isDeclaration = isDeclaration; + this._parserDiagnostics = diagnostics; + this._fileName = fileName; + this._lineMap = lineMap; + this._parseOptions = parseOtions; + } + SyntaxTree.prototype.toJSON = function (key) { + var result = {}; + + result.isDeclaration = this._isDeclaration; + result.languageVersion = TypeScript.LanguageVersion[this._parseOptions.languageVersion()]; + result.parseOptions = this._parseOptions; + + if (this.diagnostics().length > 0) { + result.diagnostics = this.diagnostics(); + } + + result.sourceUnit = this._sourceUnit; + result.lineMap = this._lineMap; + + return result; + }; + + SyntaxTree.prototype.sourceUnit = function () { + return this._sourceUnit; + }; + + SyntaxTree.prototype.isDeclaration = function () { + return this._isDeclaration; + }; + + SyntaxTree.prototype.computeDiagnostics = function () { + if (this._parserDiagnostics.length > 0) { + return this._parserDiagnostics; + } + + var diagnostics = []; + this.sourceUnit().accept(new GrammarCheckerWalker(this, diagnostics)); + + return diagnostics; + }; + + SyntaxTree.prototype.diagnostics = function () { + if (this._allDiagnostics === null) { + this._allDiagnostics = this.computeDiagnostics(); + } + + return this._allDiagnostics; + }; + + SyntaxTree.prototype.fileName = function () { + return this._fileName; + }; + + SyntaxTree.prototype.lineMap = function () { + return this._lineMap; + }; + + SyntaxTree.prototype.parseOptions = function () { + return this._parseOptions; + }; + + SyntaxTree.prototype.structuralEquals = function (tree) { + return TypeScript.ArrayUtilities.sequenceEquals(this.diagnostics(), tree.diagnostics(), TypeScript.Diagnostic.equals) && this.sourceUnit().structuralEquals(tree.sourceUnit()); + }; + return SyntaxTree; + })(); + TypeScript.SyntaxTree = SyntaxTree; + + var GrammarCheckerWalker = (function (_super) { + __extends(GrammarCheckerWalker, _super); + function GrammarCheckerWalker(syntaxTree, diagnostics) { + _super.call(this); + this.syntaxTree = syntaxTree; + this.diagnostics = diagnostics; + this.inAmbientDeclaration = false; + this.inBlock = false; + this.inObjectLiteralExpression = false; + this.currentConstructor = null; + } + GrammarCheckerWalker.prototype.childFullStart = function (parent, child) { + return this.position() + TypeScript.Syntax.childOffset(parent, child); + }; + + GrammarCheckerWalker.prototype.childStart = function (parent, child) { + return this.childFullStart(parent, child) + child.leadingTriviaWidth(); + }; + + GrammarCheckerWalker.prototype.pushDiagnostic = function (start, length, diagnosticKey, args) { + if (typeof args === "undefined") { args = null; } + this.diagnostics.push(new TypeScript.Diagnostic(this.syntaxTree.fileName(), this.syntaxTree.lineMap(), start, length, diagnosticKey, args)); + }; + + GrammarCheckerWalker.prototype.pushDiagnostic1 = function (elementFullStart, element, diagnosticKey, args) { + if (typeof args === "undefined") { args = null; } + this.diagnostics.push(new TypeScript.Diagnostic(this.syntaxTree.fileName(), this.syntaxTree.lineMap(), elementFullStart + element.leadingTriviaWidth(), element.width(), diagnosticKey, args)); + }; + + GrammarCheckerWalker.prototype.visitCatchClause = function (node) { + if (node.typeAnnotation) { + this.pushDiagnostic(this.childStart(node, node.typeAnnotation), node.typeAnnotation.width(), TypeScript.DiagnosticCode.Catch_clause_parameter_cannot_have_a_type_annotation); + } + + _super.prototype.visitCatchClause.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkParameterListOrder = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameters); + + var seenOptionalParameter = false; + var parameterCount = node.parameters.nonSeparatorCount(); + + for (var i = 0, n = node.parameters.childCount(); i < n; i++) { + var nodeOrToken = node.parameters.childAt(i); + if (i % 2 === 0) { + var parameterIndex = i / 2; + var parameter = node.parameters.childAt(i); + + if (parameter.dotDotDotToken) { + if (parameterIndex !== (parameterCount - 1)) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Rest_parameter_must_be_last_in_list); + return true; + } + + if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Rest_parameter_cannot_be_optional); + return true; + } + + if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Rest_parameter_cannot_have_an_initializer); + return true; + } + } else if (parameter.questionToken || parameter.equalsValueClause) { + seenOptionalParameter = true; + + if (parameter.questionToken && parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Parameter_cannot_have_question_mark_and_initializer); + return true; + } + } else { + if (seenOptionalParameter) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Required_parameter_cannot_follow_optional_parameter); + return true; + } + } + } + + parameterFullStart += nodeOrToken.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkParameterListAcessibilityModifiers = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameters); + + for (var i = 0, n = node.parameters.childCount(); i < n; i++) { + var nodeOrToken = node.parameters.childAt(i); + if (i % 2 === 0) { + var parameter = node.parameters.childAt(i); + + if (this.checkParameterAccessibilityModifiers(node, parameter, parameterFullStart)) { + return true; + } + } + + parameterFullStart += nodeOrToken.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkParameterAccessibilityModifiers = function (parameterList, parameter, parameterFullStart) { + if (parameter.modifiers.childCount() > 0) { + var modifiers = parameter.modifiers; + var modifierFullStart = parameterFullStart + TypeScript.Syntax.childOffset(parameter, modifiers); + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + + if (this.checkParameterAccessibilityModifier(parameterList, modifier, modifierFullStart, i)) { + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkParameterAccessibilityModifier = function (parameterList, modifier, modifierFullStart, modifierIndex) { + if (modifier.tokenKind !== 57 /* PublicKeyword */ && modifier.tokenKind !== 55 /* PrivateKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_parameter, [modifier.text()]); + return true; + } else { + if (modifierIndex > 0) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return true; + } + + if (!this.inAmbientDeclaration && this.currentConstructor && !this.currentConstructor.block && this.currentConstructor.callSignature.parameterList === parameterList) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_cannot_be_used_in_a_constructor_overload); + return true; + } else if (this.inAmbientDeclaration || this.currentConstructor === null || this.currentConstructor.callSignature.parameterList !== parameterList) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Parameter_property_declarations_can_only_be_used_in_a_non_ambient_constructor_declaration); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForTrailingSeparator = function (parent, list) { + if (list.childCount() === 0 || list.childCount() % 2 === 1) { + return false; + } + + var currentElementFullStart = this.childFullStart(parent, list); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var child = list.childAt(i); + if (i === n - 1) { + this.pushDiagnostic1(currentElementFullStart, child, TypeScript.DiagnosticCode.Trailing_separator_not_allowed); + } + + currentElementFullStart += child.fullWidth(); + } + + return true; + }; + + GrammarCheckerWalker.prototype.checkForAtLeastOneElement = function (parent, list, expected) { + if (list.childCount() > 0) { + return false; + } + + var listFullStart = this.childFullStart(parent, list); + var tokenAtStart = this.syntaxTree.sourceUnit().findToken(listFullStart); + + this.pushDiagnostic1(listFullStart, tokenAtStart.token(), TypeScript.DiagnosticCode.Unexpected_token_0_expected, [expected]); + + return true; + }; + + GrammarCheckerWalker.prototype.visitParameterList = function (node) { + if (this.checkParameterListAcessibilityModifiers(node) || this.checkParameterListOrder(node) || this.checkForTrailingSeparator(node, node.parameters)) { + this.skip(node); + return; + } + + _super.prototype.visitParameterList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitHeritageClause = function (node) { + if (this.checkForTrailingSeparator(node, node.typeNames) || this.checkForAtLeastOneElement(node, node.typeNames, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.type_name, null))) { + this.skip(node); + return; + } + + _super.prototype.visitHeritageClause.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitArgumentList = function (node) { + if (this.checkForTrailingSeparator(node, node.arguments)) { + this.skip(node); + return; + } + + _super.prototype.visitArgumentList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitVariableDeclaration = function (node) { + if (this.checkForTrailingSeparator(node, node.variableDeclarators) || this.checkForAtLeastOneElement(node, node.variableDeclarators, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null))) { + this.skip(node); + return; + } + + _super.prototype.visitVariableDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTypeArgumentList = function (node) { + if (this.checkForTrailingSeparator(node, node.typeArguments) || this.checkForAtLeastOneElement(node, node.typeArguments, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null))) { + this.skip(node); + return; + } + + _super.prototype.visitTypeArgumentList.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTypeParameterList = function (node) { + if (this.checkForTrailingSeparator(node, node.typeParameters) || this.checkForAtLeastOneElement(node, node.typeParameters, TypeScript.getLocalizedText(TypeScript.DiagnosticCode.identifier, null))) { + this.skip(node); + return; + } + + _super.prototype.visitTypeParameterList.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkIndexSignatureParameter = function (node) { + var parameterFullStart = this.childFullStart(node, node.parameter); + var parameter = node.parameter; + + if (parameter.dotDotDotToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signatures_cannot_have_rest_parameters); + return true; + } else if (parameter.modifiers.childCount() > 0) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_accessibility_modifiers); + return true; + } else if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_a_question_mark); + return true; + } else if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_cannot_have_an_initializer); + return true; + } else if (!parameter.typeAnnotation) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_must_have_a_type_annotation); + return true; + } else if (parameter.typeAnnotation.type.kind() !== 69 /* StringKeyword */ && parameter.typeAnnotation.type.kind() !== 67 /* NumberKeyword */) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.Index_signature_parameter_type_must_be_string_or_number); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitIndexSignature = function (node) { + if (this.checkIndexSignatureParameter(node)) { + this.skip(node); + return; + } + + if (!node.typeAnnotation) { + this.pushDiagnostic1(this.position(), node, TypeScript.DiagnosticCode.Index_signature_must_have_a_type_annotation); + this.skip(node); + return; + } + + _super.prototype.visitIndexSignature.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkClassDeclarationHeritageClauses = function (node) { + var heritageClauseFullStart = this.childFullStart(node, node.heritageClauses); + + var seenExtendsClause = false; + var seenImplementsClause = false; + + for (var i = 0, n = node.heritageClauses.childCount(); i < n; i++) { + TypeScript.Debug.assert(i <= 2); + var heritageClause = node.heritageClauses.childAt(i); + + if (heritageClause.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */) { + if (seenExtendsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.extends_clause_already_seen); + return true; + } + + if (seenImplementsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.extends_clause_must_precede_implements_clause); + return true; + } + + if (heritageClause.typeNames.nonSeparatorCount() > 1) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.Classes_can_only_extend_a_single_class); + return true; + } + + seenExtendsClause = true; + } else { + TypeScript.Debug.assert(heritageClause.extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + if (seenImplementsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.implements_clause_already_seen); + return true; + } + + seenImplementsClause = true; + } + + heritageClauseFullStart += heritageClause.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedDeclareModifier = function (modifiers) { + if (this.inAmbientDeclaration) { + var declareToken = TypeScript.SyntaxUtilities.getToken(modifiers, 63 /* DeclareKeyword */); + + if (declareToken) { + this.pushDiagnostic1(this.childFullStart(modifiers, declareToken), declareToken, TypeScript.DiagnosticCode.declare_modifier_not_allowed_for_code_already_in_an_ambient_context); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForRequiredDeclareModifier = function (moduleElement, typeKeyword, modifiers) { + if (!this.inAmbientDeclaration && this.syntaxTree.isDeclaration()) { + if (!TypeScript.SyntaxUtilities.containsToken(modifiers, 63 /* DeclareKeyword */)) { + this.pushDiagnostic1(this.childFullStart(moduleElement, typeKeyword), typeKeyword.firstToken(), TypeScript.DiagnosticCode.declare_modifier_required_for_top_level_element); + return true; + } + } + }; + + GrammarCheckerWalker.prototype.checkFunctionOverloads = function (node, moduleElements) { + if (!this.inAmbientDeclaration && !this.syntaxTree.isDeclaration()) { + var moduleElementFullStart = this.childFullStart(node, moduleElements); + + var inFunctionOverloadChain = false; + var functionOverloadChainName = null; + + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var moduleElement = moduleElements.childAt(i); + var lastElement = i === (n - 1); + + if (inFunctionOverloadChain) { + if (moduleElement.kind() !== 129 /* FunctionDeclaration */) { + this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + + var functionDeclaration = moduleElement; + if (functionDeclaration.identifier.valueText() !== functionOverloadChainName) { + var identifierFullStart = moduleElementFullStart + TypeScript.Syntax.childOffset(moduleElement, functionDeclaration.identifier); + this.pushDiagnostic1(identifierFullStart, functionDeclaration.identifier, TypeScript.DiagnosticCode.Function_overload_name_must_be_0, [functionOverloadChainName]); + return true; + } + } + + if (moduleElement.kind() === 129 /* FunctionDeclaration */) { + functionDeclaration = moduleElement; + if (!TypeScript.SyntaxUtilities.containsToken(functionDeclaration.modifiers, 63 /* DeclareKeyword */)) { + inFunctionOverloadChain = functionDeclaration.block === null; + functionOverloadChainName = functionDeclaration.identifier.valueText(); + + if (inFunctionOverloadChain) { + if (lastElement) { + this.pushDiagnostic1(moduleElementFullStart, moduleElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } else { + var nextElement = moduleElements.childAt(i + 1); + if (nextElement.kind() === 129 /* FunctionDeclaration */) { + var nextFunction = nextElement; + + if (nextFunction.identifier.valueText() !== functionOverloadChainName && nextFunction.block === null) { + var identifierFullStart = moduleElementFullStart + TypeScript.Syntax.childOffset(moduleElement, functionDeclaration.identifier); + this.pushDiagnostic1(identifierFullStart, functionDeclaration.identifier, TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + } + } + } + } else { + inFunctionOverloadChain = false; + functionOverloadChainName = ""; + } + } + + moduleElementFullStart += moduleElement.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkClassOverloads = function (node) { + if (!this.inAmbientDeclaration && !TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */)) { + var classElementFullStart = this.childFullStart(node, node.classElements); + + var inFunctionOverloadChain = false; + var inConstructorOverloadChain = false; + + var functionOverloadChainName = null; + var isInStaticOverloadChain = null; + var memberFunctionDeclaration = null; + + for (var i = 0, n = node.classElements.childCount(); i < n; i++) { + var classElement = node.classElements.childAt(i); + var lastElement = i === (n - 1); + var isStaticOverload = null; + + if (inFunctionOverloadChain) { + if (classElement.kind() !== 135 /* MemberFunctionDeclaration */) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + + memberFunctionDeclaration = classElement; + if (memberFunctionDeclaration.propertyName.valueText() !== functionOverloadChainName) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, TypeScript.DiagnosticCode.Function_overload_name_must_be_0, [functionOverloadChainName]); + return true; + } + + isStaticOverload = TypeScript.SyntaxUtilities.containsToken(memberFunctionDeclaration.modifiers, 58 /* StaticKeyword */); + if (isStaticOverload !== isInStaticOverloadChain) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + var diagnostic = isInStaticOverloadChain ? TypeScript.DiagnosticCode.Function_overload_must_be_static : TypeScript.DiagnosticCode.Function_overload_must_not_be_static; + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, diagnostic, null); + return true; + } + } else if (inConstructorOverloadChain) { + if (classElement.kind() !== 137 /* ConstructorDeclaration */) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Constructor_implementation_expected); + return true; + } + } + + if (classElement.kind() === 135 /* MemberFunctionDeclaration */) { + memberFunctionDeclaration = classElement; + + inFunctionOverloadChain = memberFunctionDeclaration.block === null; + functionOverloadChainName = memberFunctionDeclaration.propertyName.valueText(); + isInStaticOverloadChain = TypeScript.SyntaxUtilities.containsToken(memberFunctionDeclaration.modifiers, 58 /* StaticKeyword */); + + if (inFunctionOverloadChain) { + if (lastElement) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } else { + var nextElement = node.classElements.childAt(i + 1); + if (nextElement.kind() === 135 /* MemberFunctionDeclaration */) { + var nextMemberFunction = nextElement; + + if (nextMemberFunction.propertyName.valueText() !== functionOverloadChainName && nextMemberFunction.block === null) { + var propertyNameFullStart = classElementFullStart + TypeScript.Syntax.childOffset(classElement, memberFunctionDeclaration.propertyName); + this.pushDiagnostic1(propertyNameFullStart, memberFunctionDeclaration.propertyName, TypeScript.DiagnosticCode.Function_implementation_expected); + return true; + } + } + } + } + } else if (classElement.kind() === 137 /* ConstructorDeclaration */) { + var constructorDeclaration = classElement; + + inConstructorOverloadChain = constructorDeclaration.block === null; + if (lastElement && inConstructorOverloadChain) { + this.pushDiagnostic1(classElementFullStart, classElement.firstToken(), TypeScript.DiagnosticCode.Constructor_implementation_expected); + return true; + } + } + + classElementFullStart += classElement.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForReservedName = function (parent, name, diagnosticKey) { + var nameFullStart = this.childFullStart(parent, name); + var token; + var tokenFullStart; + + var current = name; + while (current !== null) { + if (current.kind() === 121 /* QualifiedName */) { + var qualifiedName = current; + token = qualifiedName.right; + tokenFullStart = nameFullStart + this.childFullStart(qualifiedName, token); + current = qualifiedName.left; + } else { + TypeScript.Debug.assert(current.kind() === 11 /* IdentifierName */); + token = current; + tokenFullStart = nameFullStart; + current = null; + } + + switch (token.valueText()) { + case "any": + case "number": + case "boolean": + case "string": + case "void": + this.pushDiagnostic(tokenFullStart + token.leadingTriviaWidth(), token.width(), diagnosticKey, [token.valueText()]); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitClassDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, TypeScript.DiagnosticCode.Class_name_cannot_be_0) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.classKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkClassDeclarationHeritageClauses(node) || this.checkClassOverloads(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitClassDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkInterfaceDeclarationHeritageClauses = function (node) { + var heritageClauseFullStart = this.childFullStart(node, node.heritageClauses); + + var seenExtendsClause = false; + + for (var i = 0, n = node.heritageClauses.childCount(); i < n; i++) { + TypeScript.Debug.assert(i <= 1); + var heritageClause = node.heritageClauses.childAt(i); + + if (heritageClause.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */) { + if (seenExtendsClause) { + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.extends_clause_already_seen); + return true; + } + + seenExtendsClause = true; + } else { + TypeScript.Debug.assert(heritageClause.extendsOrImplementsKeyword.tokenKind === 51 /* ImplementsKeyword */); + this.pushDiagnostic1(heritageClauseFullStart, heritageClause, TypeScript.DiagnosticCode.Interface_declaration_cannot_have_implements_clause); + return true; + } + + heritageClauseFullStart += heritageClause.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkInterfaceModifiers = function (modifiers) { + var modifierFullStart = this.position(); + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + if (modifier.tokenKind === 63 /* DeclareKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.declare_modifier_cannot_appear_on_an_interface_declaration); + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitInterfaceDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, TypeScript.DiagnosticCode.Interface_name_cannot_be_0) || this.checkInterfaceModifiers(node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkInterfaceDeclarationHeritageClauses(node)) { + this.skip(node); + return; + } + + _super.prototype.visitInterfaceDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkClassElementModifiers = function (list) { + var modifierFullStart = this.position(); + + var seenAccessibilityModifier = false; + var seenStaticModifier = false; + + for (var i = 0, n = list.childCount(); i < n; i++) { + var modifier = list.childAt(i); + if (modifier.tokenKind === 57 /* PublicKeyword */ || modifier.tokenKind === 55 /* PrivateKeyword */) { + if (seenAccessibilityModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return true; + } + + if (seenStaticModifier) { + var previousToken = list.childAt(i - 1); + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_must_precede_1_modifier, [modifier.text(), previousToken.text()]); + return true; + } + + seenAccessibilityModifier = true; + } else if (modifier.tokenKind === 58 /* StaticKeyword */) { + if (seenStaticModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_already_seen, [modifier.text()]); + return true; + } + + seenStaticModifier = true; + } else { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_class_element, [modifier.text()]); + return true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitMemberVariableDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitMemberVariableDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitMemberFunctionDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitMemberFunctionDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkGetAccessorParameter = function (node, getKeyword, parameterList) { + var getKeywordFullStart = this.childFullStart(node, getKeyword); + if (parameterList.parameters.childCount() !== 0) { + this.pushDiagnostic1(getKeywordFullStart, getKeyword, TypeScript.DiagnosticCode.get_accessor_cannot_have_parameters); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitIndexMemberDeclaration = function (node) { + if (this.checkIndexMemberModifiers(node)) { + this.skip(node); + return; + } + + _super.prototype.visitIndexMemberDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkIndexMemberModifiers = function (node) { + if (node.modifiers.childCount() > 0) { + var modifierFullStart = this.childFullStart(node, node.modifiers); + this.pushDiagnostic1(modifierFullStart, node.modifiers.childAt(0), TypeScript.DiagnosticCode.Modifiers_cannot_appear_here); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkEcmaScriptVersionIsAtLeast = function (parent, node, languageVersion, diagnosticKey) { + if (this.syntaxTree.parseOptions().languageVersion() < languageVersion) { + var nodeFullStart = this.childFullStart(parent, node); + this.pushDiagnostic1(nodeFullStart, node, diagnosticKey); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitObjectLiteralExpression = function (node) { + var savedInObjectLiteralExpression = this.inObjectLiteralExpression; + this.inObjectLiteralExpression = true; + _super.prototype.visitObjectLiteralExpression.call(this, node); + this.inObjectLiteralExpression = savedInObjectLiteralExpression; + }; + + GrammarCheckerWalker.prototype.visitGetAccessor = function (node) { + if (this.checkForAccessorDeclarationInAmbientContext(node) || this.checkEcmaScriptVersionIsAtLeast(node, node.getKeyword, 1 /* EcmaScript5 */, TypeScript.DiagnosticCode.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkClassElementModifiers(node.modifiers) || this.checkGetAccessorParameter(node, node.getKeyword, node.parameterList)) { + this.skip(node); + return; + } + + _super.prototype.visitGetAccessor.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkForAccessorDeclarationInAmbientContext = function (accessor) { + if (this.inAmbientDeclaration) { + this.pushDiagnostic1(this.position(), accessor, TypeScript.DiagnosticCode.Accessors_are_not_allowed_in_ambient_contexts, null); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkSetAccessorParameter = function (node, setKeyword, parameterList) { + var setKeywordFullStart = this.childFullStart(node, setKeyword); + if (parameterList.parameters.childCount() !== 1) { + this.pushDiagnostic1(setKeywordFullStart, setKeyword, TypeScript.DiagnosticCode.set_accessor_must_have_one_and_only_one_parameter); + return true; + } + + var parameterListFullStart = this.childFullStart(node, parameterList); + var parameterFullStart = parameterListFullStart + TypeScript.Syntax.childOffset(parameterList, parameterList.openParenToken); + var parameter = parameterList.parameters.childAt(0); + + if (parameter.questionToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.set_accessor_parameter_cannot_be_optional); + return true; + } + + if (parameter.equalsValueClause) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.set_accessor_parameter_cannot_have_an_initializer); + return true; + } + + if (parameter.dotDotDotToken) { + this.pushDiagnostic1(parameterFullStart, parameter, TypeScript.DiagnosticCode.set_accessor_cannot_have_rest_parameter); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitSetAccessor = function (node) { + if (this.checkForAccessorDeclarationInAmbientContext(node) || this.checkEcmaScriptVersionIsAtLeast(node, node.setKeyword, 1 /* EcmaScript5 */, TypeScript.DiagnosticCode.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkClassElementModifiers(node.modifiers) || this.checkSetAccessorParameter(node, node.setKeyword, node.parameterList)) { + this.skip(node); + return; + } + + _super.prototype.visitSetAccessor.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitEnumDeclaration = function (node) { + if (this.checkForReservedName(node, node.identifier, TypeScript.DiagnosticCode.Enum_name_cannot_be_0) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.enumKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers), this.checkEnumElements(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitEnumDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkEnumElements = function (node) { + var enumElementFullStart = this.childFullStart(node, node.enumElements); + + var previousValueWasComputed = false; + for (var i = 0, n = node.enumElements.childCount(); i < n; i++) { + var child = node.enumElements.childAt(i); + + if (i % 2 === 0) { + var enumElement = child; + + if (!enumElement.equalsValueClause && previousValueWasComputed) { + this.pushDiagnostic1(enumElementFullStart, enumElement, TypeScript.DiagnosticCode.Enum_member_must_have_initializer, null); + return true; + } + + if (enumElement.equalsValueClause) { + var value = enumElement.equalsValueClause.value; + previousValueWasComputed = !TypeScript.Syntax.isIntegerLiteral(value); + } + } + + enumElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitEnumElement = function (node) { + if (this.inAmbientDeclaration && node.equalsValueClause) { + var expression = node.equalsValueClause.value; + if (!TypeScript.Syntax.isIntegerLiteral(expression)) { + this.pushDiagnostic1(this.childFullStart(node, node.equalsValueClause), node.equalsValueClause.firstToken(), TypeScript.DiagnosticCode.Ambient_enum_elements_can_only_have_integer_literal_initializers); + this.skip(node); + return; + } + } + + _super.prototype.visitEnumElement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitInvocationExpression = function (node) { + if (node.expression.kind() === 50 /* SuperKeyword */ && node.argumentList.typeArgumentList !== null) { + this.pushDiagnostic1(this.position(), node, TypeScript.DiagnosticCode.super_invocation_cannot_have_type_arguments); + } + + _super.prototype.visitInvocationExpression.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkModuleElementModifiers = function (modifiers) { + var modifierFullStart = this.position(); + var seenExportModifier = false; + var seenDeclareModifier = false; + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var modifier = modifiers.childAt(i); + if (modifier.tokenKind === 57 /* PublicKeyword */ || modifier.tokenKind === 55 /* PrivateKeyword */ || modifier.tokenKind === 58 /* StaticKeyword */) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_module_element, [modifier.text()]); + return true; + } + + if (modifier.tokenKind === 63 /* DeclareKeyword */) { + if (seenDeclareModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode.Accessibility_modifier_already_seen); + return; + } + + seenDeclareModifier = true; + } else if (modifier.tokenKind === 47 /* ExportKeyword */) { + if (seenExportModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_already_seen, [modifier.text()]); + return; + } + + if (seenDeclareModifier) { + this.pushDiagnostic1(modifierFullStart, modifier, TypeScript.DiagnosticCode._0_modifier_must_precede_1_modifier, [TypeScript.SyntaxFacts.getText(47 /* ExportKeyword */), TypeScript.SyntaxFacts.getText(63 /* DeclareKeyword */)]); + return; + } + + seenExportModifier = true; + } + + modifierFullStart += modifier.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedImportDeclaration = function (node) { + var currentElementFullStart = this.childFullStart(node, node.moduleElements); + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var child = node.moduleElements.childAt(i); + if (child.kind() === 133 /* ImportDeclaration */) { + var importDeclaration = child; + if (importDeclaration.moduleReference.kind() === 245 /* ExternalModuleReference */) { + if (node.stringLiteral === null) { + this.pushDiagnostic1(currentElementFullStart, importDeclaration, TypeScript.DiagnosticCode.Import_declarations_in_an_internal_module_cannot_reference_an_external_module, null); + } + } + } + + currentElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedDeclareModifierOnImportDeclaration = function (modifiers) { + var declareToken = TypeScript.SyntaxUtilities.getToken(modifiers, 63 /* DeclareKeyword */); + + if (declareToken) { + this.pushDiagnostic1(this.childFullStart(modifiers, declareToken), declareToken, TypeScript.DiagnosticCode.declare_modifier_not_allowed_on_import_declaration); + return true; + } + }; + + GrammarCheckerWalker.prototype.visitImportDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifierOnImportDeclaration(node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + _super.prototype.visitImportDeclaration.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitModuleDeclaration = function (node) { + if (this.checkForReservedName(node, node.name, TypeScript.DiagnosticCode.Module_name_cannot_be_0) || this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForRequiredDeclareModifier(node, node.moduleKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers) || this.checkForDisallowedImportDeclaration(node) || this.checkForDisallowedExports(node, node.moduleElements) || this.checkForMultipleExportAssignments(node, node.moduleElements)) { + this.skip(node); + return; + } + + if (!TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */) && this.checkFunctionOverloads(node, node.moduleElements)) { + this.skip(node); + return; + } + + if (node.stringLiteral) { + if (!this.inAmbientDeclaration && !TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */)) { + var stringLiteralFullStart = this.childFullStart(node, node.stringLiteral); + this.pushDiagnostic1(stringLiteralFullStart, node.stringLiteral, TypeScript.DiagnosticCode.Only_ambient_modules_can_use_quoted_names); + this.skip(node); + return; + } + } + + if (!node.stringLiteral && this.checkForDisallowedExportAssignment(node)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitModuleDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedExports = function (node, moduleElements) { + var seenExportedElement = false; + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + + if (TypeScript.SyntaxUtilities.hasExportKeyword(child)) { + seenExportedElement = true; + break; + } + } + + var moduleElementFullStart = this.childFullStart(node, moduleElements); + if (seenExportedElement) { + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + + if (child.kind() === 134 /* ExportAssignment */) { + this.pushDiagnostic1(moduleElementFullStart, child, TypeScript.DiagnosticCode.Export_assignment_not_allowed_in_module_with_exported_element); + return true; + } + + moduleElementFullStart += child.fullWidth(); + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkForMultipleExportAssignments = function (node, moduleElements) { + var moduleElementFullStart = this.childFullStart(node, moduleElements); + var seenExportAssignment = false; + var errorFound = false; + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var child = moduleElements.childAt(i); + if (child.kind() === 134 /* ExportAssignment */) { + if (seenExportAssignment) { + this.pushDiagnostic1(moduleElementFullStart, child, TypeScript.DiagnosticCode.Module_cannot_have_multiple_export_assignments); + errorFound = true; + } + seenExportAssignment = true; + } + + moduleElementFullStart += child.fullWidth(); + } + + return errorFound; + }; + + GrammarCheckerWalker.prototype.checkForDisallowedExportAssignment = function (node) { + var moduleElementFullStart = this.childFullStart(node, node.moduleElements); + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var child = node.moduleElements.childAt(i); + + if (child.kind() === 134 /* ExportAssignment */) { + this.pushDiagnostic1(moduleElementFullStart, child, TypeScript.DiagnosticCode.Export_assignment_cannot_be_used_in_internal_modules); + + return true; + } + + moduleElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitBlock = function (node) { + if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) { + this.pushDiagnostic1(this.position(), node.firstToken(), TypeScript.DiagnosticCode.Implementations_are_not_allowed_in_ambient_contexts); + this.skip(node); + return; + } + + if (this.checkFunctionOverloads(node, node.statements)) { + this.skip(node); + return; + } + + var savedInBlock = this.inBlock; + this.inBlock = true; + _super.prototype.visitBlock.call(this, node); + this.inBlock = savedInBlock; + }; + + GrammarCheckerWalker.prototype.checkForStatementInAmbientContxt = function (node) { + if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) { + this.pushDiagnostic1(this.position(), node.firstToken(), TypeScript.DiagnosticCode.Statements_are_not_allowed_in_ambient_contexts); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitBreakStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitBreakStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitContinueStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitContinueStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitDebuggerStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitDebuggerStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitDoStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitDoStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitEmptyStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitEmptyStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitExpressionStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitExpressionStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitForInStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node) || this.checkForInStatementVariableDeclaration(node)) { + this.skip(node); + return; + } + + _super.prototype.visitForInStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkForInStatementVariableDeclaration = function (node) { + if (node.variableDeclaration && node.variableDeclaration.variableDeclarators.nonSeparatorCount() > 1) { + var variableDeclarationFullStart = this.childFullStart(node, node.variableDeclaration); + + this.pushDiagnostic1(variableDeclarationFullStart, node.variableDeclaration, TypeScript.DiagnosticCode.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitForStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitForStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitIfStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitIfStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitLabeledStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitLabeledStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitReturnStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitReturnStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitSwitchStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitSwitchStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitThrowStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitThrowStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitTryStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitTryStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitWhileStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitWhileStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitWithStatement = function (node) { + if (this.checkForStatementInAmbientContxt(node)) { + this.skip(node); + return; + } + + _super.prototype.visitWithStatement.call(this, node); + }; + + GrammarCheckerWalker.prototype.checkForDisallowedModifiers = function (parent, modifiers) { + if (this.inBlock || this.inObjectLiteralExpression) { + if (modifiers.childCount() > 0) { + var modifierFullStart = this.childFullStart(parent, modifiers); + this.pushDiagnostic1(modifierFullStart, modifiers.childAt(0), TypeScript.DiagnosticCode.Modifiers_cannot_appear_here); + return true; + } + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitFunctionDeclaration = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkForRequiredDeclareModifier(node, node.functionKeyword, node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitFunctionDeclaration.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitVariableStatement = function (node) { + if (this.checkForDisallowedDeclareModifier(node.modifiers) || this.checkForDisallowedModifiers(node, node.modifiers) || this.checkForRequiredDeclareModifier(node, node.variableDeclaration, node.modifiers) || this.checkModuleElementModifiers(node.modifiers)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = this.inAmbientDeclaration || this.syntaxTree.isDeclaration() || TypeScript.SyntaxUtilities.containsToken(node.modifiers, 63 /* DeclareKeyword */); + _super.prototype.visitVariableStatement.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.checkListSeparators = function (parent, list, kind) { + var currentElementFullStart = this.childFullStart(parent, list); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var child = list.childAt(i); + if (i % 2 === 1 && child.kind() !== kind) { + this.pushDiagnostic1(currentElementFullStart, child, TypeScript.DiagnosticCode._0_expected, [TypeScript.SyntaxFacts.getText(kind)]); + } + + currentElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitObjectType = function (node) { + if (this.checkListSeparators(node, node.typeMembers, 78 /* SemicolonToken */)) { + this.skip(node); + return; + } + + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitObjectType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitArrayType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitArrayType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitFunctionType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitFunctionType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitConstructorType = function (node) { + var savedInAmbientDeclaration = this.inAmbientDeclaration; + this.inAmbientDeclaration = true; + _super.prototype.visitConstructorType.call(this, node); + this.inAmbientDeclaration = savedInAmbientDeclaration; + }; + + GrammarCheckerWalker.prototype.visitVariableDeclarator = function (node) { + if (this.inAmbientDeclaration && node.equalsValueClause) { + this.pushDiagnostic1(this.childFullStart(node, node.equalsValueClause), node.equalsValueClause.firstToken(), TypeScript.DiagnosticCode.Initializers_are_not_allowed_in_ambient_contexts); + this.skip(node); + return; + } + + _super.prototype.visitVariableDeclarator.call(this, node); + }; + + GrammarCheckerWalker.prototype.visitConstructorDeclaration = function (node) { + if (this.checkClassElementModifiers(node.modifiers) || this.checkConstructorModifiers(node.modifiers) || this.checkConstructorTypeParameterList(node) || this.checkConstructorTypeAnnotation(node)) { + this.skip(node); + return; + } + + var savedCurrentConstructor = this.currentConstructor; + this.currentConstructor = node; + _super.prototype.visitConstructorDeclaration.call(this, node); + this.currentConstructor = savedCurrentConstructor; + }; + + GrammarCheckerWalker.prototype.checkConstructorModifiers = function (modifiers) { + var currentElementFullStart = this.position(); + + for (var i = 0, n = modifiers.childCount(); i < n; i++) { + var child = modifiers.childAt(i); + if (child.kind() !== 57 /* PublicKeyword */) { + this.pushDiagnostic1(currentElementFullStart, child, TypeScript.DiagnosticCode._0_modifier_cannot_appear_on_a_constructor_declaration, [TypeScript.SyntaxFacts.getText(child.kind())]); + return true; + } + + currentElementFullStart += child.fullWidth(); + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkConstructorTypeParameterList = function (node) { + var currentElementFullStart = this.position(); + + if (node.callSignature.typeParameterList) { + var callSignatureFullStart = this.childFullStart(node, node.callSignature); + var typeParameterListFullStart = callSignatureFullStart + TypeScript.Syntax.childOffset(node.callSignature, node.callSignature.typeAnnotation); + this.pushDiagnostic1(callSignatureFullStart, node.callSignature.typeParameterList, TypeScript.DiagnosticCode.Type_parameters_cannot_appear_on_a_constructor_declaration); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.checkConstructorTypeAnnotation = function (node) { + var currentElementFullStart = this.position(); + + if (node.callSignature.typeAnnotation) { + var callSignatureFullStart = this.childFullStart(node, node.callSignature); + var typeAnnotationFullStart = callSignatureFullStart + TypeScript.Syntax.childOffset(node.callSignature, node.callSignature.typeAnnotation); + this.pushDiagnostic1(typeAnnotationFullStart, node.callSignature.typeAnnotation, TypeScript.DiagnosticCode.Type_annotation_cannot_appear_on_a_constructor_declaration); + return true; + } + + return false; + }; + + GrammarCheckerWalker.prototype.visitSourceUnit = function (node) { + if (this.checkFunctionOverloads(node, node.moduleElements) || this.checkForDisallowedExports(node, node.moduleElements) || this.checkForMultipleExportAssignments(node, node.moduleElements)) { + this.skip(node); + return; + } + + _super.prototype.visitSourceUnit.call(this, node); + }; + return GrammarCheckerWalker; + })(TypeScript.PositionTrackingWalker); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Unicode = (function () { + function Unicode() { + } + Unicode.lookupInUnicodeMap = function (code, map) { + if (code < map[0]) { + return false; + } + + 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; + }; + + Unicode.isIdentifierStart = function (code, languageVersion) { + if (languageVersion === 0 /* EcmaScript3 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES3IdentifierStart); + } else if (languageVersion === 1 /* EcmaScript5 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES5IdentifierStart); + } else { + throw TypeScript.Errors.argumentOutOfRange("languageVersion"); + } + }; + + Unicode.isIdentifierPart = function (code, languageVersion) { + if (languageVersion === 0 /* EcmaScript3 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES3IdentifierPart); + } else if (languageVersion === 1 /* EcmaScript5 */) { + return Unicode.lookupInUnicodeMap(code, Unicode.unicodeES5IdentifierPart); + } else { + throw TypeScript.Errors.argumentOutOfRange("languageVersion"); + } + }; + Unicode.unicodeES3IdentifierStart = [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]; + Unicode.unicodeES3IdentifierPart = [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, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 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, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 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, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 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, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + + Unicode.unicodeES5IdentifierStart = [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]; + Unicode.unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 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, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 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, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 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, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 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, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; + return Unicode; + })(); + TypeScript.Unicode = Unicode; +})(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; + + function timeFunction(logger, funcDescription, func) { + var start = (new Date()).getTime(); + var result = func(); + var end = (new Date()).getTime(); + if (logger.information()) { + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + } + return result; + } + TypeScript.timeFunction = timeFunction; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Document = (function () { + function Document(_compiler, _semanticInfoChain, fileName, referencedFiles, _scriptSnapshot, byteOrderMark, version, isOpen, _syntaxTree, _topLevelDecl) { + this._compiler = _compiler; + this._semanticInfoChain = _semanticInfoChain; + this.fileName = fileName; + this.referencedFiles = referencedFiles; + this._scriptSnapshot = _scriptSnapshot; + this.byteOrderMark = byteOrderMark; + this.version = version; + this.isOpen = isOpen; + this._syntaxTree = _syntaxTree; + this._topLevelDecl = _topLevelDecl; + this._diagnostics = null; + this._bloomFilter = null; + this._sourceUnit = null; + this._lineMap = null; + this._declASTMap = []; + this._astDeclMap = []; + this._amdDependencies = undefined; + this._externalModuleIndicatorSpan = undefined; + } + Document.prototype.invalidate = function () { + this._declASTMap.length = 0; + this._astDeclMap.length = 0; + this._topLevelDecl = null; + + this._syntaxTree = null; + this._sourceUnit = null; + this._diagnostics = null; + this._bloomFilter = null; + }; + + Document.prototype.isDeclareFile = function () { + return TypeScript.isDTSFile(this.fileName); + }; + + Document.prototype.cacheSyntaxTreeInfo = function (syntaxTree) { + var start = new Date().getTime(); + this._diagnostics = syntaxTree.diagnostics(); + TypeScript.syntaxDiagnosticsTime += new Date().getTime() - start; + + this._lineMap = syntaxTree.lineMap(); + + var sourceUnit = syntaxTree.sourceUnit(); + var leadingTrivia = sourceUnit.leadingTrivia(); + + this._externalModuleIndicatorSpan = this.getImplicitImportSpan(leadingTrivia) || this.getTopLevelImportOrExportSpan(sourceUnit); + + var amdDependencies = []; + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + if (trivia.isComment()) { + var amdDependency = this.getAmdDependency(trivia.fullText()); + if (amdDependency) { + amdDependencies.push(amdDependency); + } + } + } + + this._amdDependencies = amdDependencies; + }; + + Document.prototype.getAmdDependency = function (comment) { + var amdDependencyRegEx = /^\/\/\/\s*/gim; + var match = implicitImportRegEx.exec(trivia.fullText()); + + if (match) { + return new TypeScript.TextSpan(position, trivia.fullWidth()); + } + + return null; + }; + + Document.prototype.getTopLevelImportOrExportSpan = function (node) { + var firstToken; + var position = 0; + + for (var i = 0, n = node.moduleElements.childCount(); i < n; i++) { + var moduleElement = node.moduleElements.childAt(i); + + firstToken = moduleElement.firstToken(); + if (firstToken !== null && firstToken.tokenKind === 47 /* ExportKeyword */) { + return new TypeScript.TextSpan(position + firstToken.leadingTriviaWidth(), firstToken.width()); + } + + if (moduleElement.kind() === 133 /* ImportDeclaration */) { + var importDecl = moduleElement; + if (importDecl.moduleReference.kind() === 245 /* ExternalModuleReference */) { + return new TypeScript.TextSpan(position + importDecl.leadingTriviaWidth(), importDecl.width()); + } + } + + position += moduleElement.fullWidth(); + } + + return null; + ; + }; + + Document.prototype.sourceUnit = function () { + if (!this._sourceUnit) { + var start = new Date().getTime(); + var syntaxTree = this.syntaxTree(); + this._sourceUnit = TypeScript.SyntaxTreeToAstVisitor.visit(syntaxTree, this.fileName, this._compiler.compilationSettings(), this.isOpen); + TypeScript.astTranslationTime += new Date().getTime() - start; + + if (!this.isOpen) { + this._syntaxTree = null; + } + } + + return this._sourceUnit; + }; + + Document.prototype.diagnostics = function () { + if (this._diagnostics === null) { + this.syntaxTree(); + TypeScript.Debug.assert(this._diagnostics); + } + + return this._diagnostics; + }; + + Document.prototype.lineMap = function () { + if (this._lineMap === null) { + this.syntaxTree(); + TypeScript.Debug.assert(this._lineMap); + } + + return this._lineMap; + }; + + Document.prototype.isExternalModule = function () { + return this.externalModuleIndicatorSpan() !== null; + }; + + Document.prototype.externalModuleIndicatorSpan = function () { + if (this._externalModuleIndicatorSpan === undefined) { + this.syntaxTree(); + TypeScript.Debug.assert(this._externalModuleIndicatorSpan !== undefined); + } + + return this._externalModuleIndicatorSpan; + }; + + Document.prototype.amdDependencies = function () { + if (this._amdDependencies === undefined) { + this.syntaxTree(); + TypeScript.Debug.assert(this._amdDependencies !== undefined); + } + + return this._amdDependencies; + }; + + Document.prototype.syntaxTree = function () { + var result = this._syntaxTree; + if (!result) { + var start = new Date().getTime(); + + result = TypeScript.Parser.parse(this.fileName, TypeScript.SimpleText.fromScriptSnapshot(this._scriptSnapshot), TypeScript.isDTSFile(this.fileName), TypeScript.getParseOptions(this._compiler.compilationSettings())); + + TypeScript.syntaxTreeParseTime += new Date().getTime() - start; + + if (this.isOpen || !this._sourceUnit) { + this._syntaxTree = result; + } + } + + this.cacheSyntaxTreeInfo(result); + return result; + }; + + Document.prototype.bloomFilter = function () { + if (!this._bloomFilter) { + var identifiers = TypeScript.createIntrinsicsObject(); + var pre = function (cur) { + if (TypeScript.ASTHelpers.isValidAstNode(cur)) { + if (cur.kind() === 11 /* IdentifierName */) { + var nodeText = cur.valueText(); + + identifiers[nodeText] = true; + } + } + }; + + TypeScript.getAstWalkerFactory().simpleWalk(this.sourceUnit(), pre, null, identifiers); + + var identifierCount = 0; + for (var name in identifiers) { + if (identifiers[name]) { + identifierCount++; + } + } + + this._bloomFilter = new TypeScript.BloomFilter(identifierCount); + this._bloomFilter.addKeys(identifiers); + } + return this._bloomFilter; + }; + + Document.prototype.emitToOwnOutputFile = function () { + return !this._compiler.compilationSettings().outFileOption() || this.isExternalModule(); + }; + + Document.prototype.update = function (scriptSnapshot, version, isOpen, textChangeRange) { + var oldSyntaxTree = this._syntaxTree; + + if (textChangeRange !== null && TypeScript.Debug.shouldAssert(1 /* Normal */)) { + var oldText = this._scriptSnapshot; + var newText = scriptSnapshot; + + TypeScript.Debug.assert((oldText.getLength() - textChangeRange.span().length() + textChangeRange.newLength()) === newText.getLength()); + + if (TypeScript.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldTextPrefix = oldText.getText(0, textChangeRange.span().start()); + var newTextPrefix = newText.getText(0, textChangeRange.span().start()); + TypeScript.Debug.assert(oldTextPrefix === newTextPrefix); + + var oldTextSuffix = oldText.getText(textChangeRange.span().end(), oldText.getLength()); + var newTextSuffix = newText.getText(textChangeRange.newSpan().end(), newText.getLength()); + TypeScript.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + + var text = TypeScript.SimpleText.fromScriptSnapshot(scriptSnapshot); + + var newSyntaxTree = textChangeRange === null || oldSyntaxTree === null ? TypeScript.Parser.parse(this.fileName, text, TypeScript.isDTSFile(this.fileName), TypeScript.getParseOptions(this._compiler.compilationSettings())) : TypeScript.Parser.incrementalParse(oldSyntaxTree, textChangeRange, text); + + return new Document(this._compiler, this._semanticInfoChain, this.fileName, this.referencedFiles, scriptSnapshot, this.byteOrderMark, version, isOpen, newSyntaxTree, null); + }; + + Document.create = function (compiler, semanticInfoChain, fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles) { + return new Document(compiler, semanticInfoChain, fileName, referencedFiles, scriptSnapshot, byteOrderMark, version, isOpen, null, null); + }; + + Document.prototype.topLevelDecl = function () { + if (this._topLevelDecl === null) { + this._topLevelDecl = TypeScript.DeclarationCreator.create(this, this._semanticInfoChain, this._compiler.compilationSettings()); + } + + return this._topLevelDecl; + }; + + Document.prototype._getDeclForAST = function (ast) { + this.topLevelDecl(); + return this._astDeclMap[ast.syntaxID()]; + }; + + Document.prototype.getEnclosingDecl = function (ast) { + if (ast.kind() === 120 /* SourceUnit */) { + return this._getDeclForAST(ast); + } + + ast = ast.parent; + var decl = null; + while (ast) { + decl = this._getDeclForAST(ast); + + if (decl) { + break; + } + + ast = ast.parent; + } + + return decl._getEnclosingDeclFromParentDecl(); + }; + + Document.prototype._setDeclForAST = function (ast, decl) { + TypeScript.Debug.assert(decl.fileName() === this.fileName); + this._astDeclMap[ast.syntaxID()] = decl; + }; + + Document.prototype._getASTForDecl = function (decl) { + return this._declASTMap[decl.declID]; + }; + + Document.prototype._setASTForDecl = function (decl, ast) { + TypeScript.Debug.assert(decl.fileName() === this.fileName); + this._declASTMap[decl.declID] = ast; + }; + return Document; + })(); + TypeScript.Document = Document; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function hasFlag(val, flag) { + return (val & flag) !== 0; + } + TypeScript.hasFlag = hasFlag; + + (function (TypeRelationshipFlags) { + TypeRelationshipFlags[TypeRelationshipFlags["SuccessfulComparison"] = 0] = "SuccessfulComparison"; + TypeRelationshipFlags[TypeRelationshipFlags["RequiredPropertyIsMissing"] = 1 << 1] = "RequiredPropertyIsMissing"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleSignatures"] = 1 << 2] = "IncompatibleSignatures"; + TypeRelationshipFlags[TypeRelationshipFlags["SourceSignatureHasTooManyParameters"] = 3] = "SourceSignatureHasTooManyParameters"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleReturnTypes"] = 1 << 4] = "IncompatibleReturnTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatiblePropertyTypes"] = 1 << 5] = "IncompatiblePropertyTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleParameterTypes"] = 1 << 6] = "IncompatibleParameterTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["InconsistantPropertyAccesibility"] = 1 << 7] = "InconsistantPropertyAccesibility"; + })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); + var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; + + (function (ModuleGenTarget) { + ModuleGenTarget[ModuleGenTarget["Unspecified"] = 0] = "Unspecified"; + ModuleGenTarget[ModuleGenTarget["Synchronous"] = 1] = "Synchronous"; + ModuleGenTarget[ModuleGenTarget["Asynchronous"] = 2] = "Asynchronous"; + })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); + var ModuleGenTarget = TypeScript.ModuleGenTarget; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var proto = "__proto__"; + + 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; + + this[proto] = null; + this[proto] = undefined; + } + return BlockIntrinsics; + })(); + + function createIntrinsicsObject() { + return new BlockIntrinsics(); + } + TypeScript.createIntrinsicsObject = createIntrinsicsObject; + + var StringHashTable = (function () { + function StringHashTable() { + this.itemCount = 0; + this.table = createIntrinsicsObject(); + } + StringHashTable.prototype.getAllKeys = function () { + var result = []; + + for (var k in this.table) { + if (this.table[k] !== undefined) { + result.push(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]; + return data === undefined ? null : data; + }; + + StringHashTable.prototype.remove = function (key) { + if (this.table[key] !== undefined) { + this.table[key] = undefined; + this.itemCount--; + } + }; + return StringHashTable; + })(); + TypeScript.StringHashTable = StringHashTable; + + var IdentiferNameHashTable = (function (_super) { + __extends(IdentiferNameHashTable, _super); + function IdentiferNameHashTable() { + _super.apply(this, arguments); + } + IdentiferNameHashTable.prototype.getAllKeys = function () { + var result = []; + + _super.prototype.map.call(this, function (k, v, c) { + if (v !== undefined) { + result.push(k.substring(1)); + } + }, null); + + return result; + }; + + IdentiferNameHashTable.prototype.add = function (key, data) { + return _super.prototype.add.call(this, "#" + key, data); + }; + + IdentiferNameHashTable.prototype.addOrUpdate = function (key, data) { + return _super.prototype.addOrUpdate.call(this, "#" + key, data); + }; + + IdentiferNameHashTable.prototype.map = function (fn, context) { + return _super.prototype.map.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.every = function (fn, context) { + return _super.prototype.every.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.some = function (fn, context) { + return _super.prototype.some.call(this, function (k, v, c) { + return fn(k.substring(1), v, c); + }, context); + }; + + IdentiferNameHashTable.prototype.lookup = function (key) { + return _super.prototype.lookup.call(this, "#" + key); + }; + return IdentiferNameHashTable; + })(StringHashTable); + TypeScript.IdentiferNameHashTable = IdentiferNameHashTable; +})(TypeScript || (TypeScript = {})); + +var TypeScript; +(function (TypeScript) { + (function (ASTHelpers) { + function scriptIsElided(sourceUnit) { + return TypeScript.isDTSFile(sourceUnit.fileName()) || moduleMembersAreElided(sourceUnit.moduleElements); + } + ASTHelpers.scriptIsElided = scriptIsElided; + + function moduleIsElided(declaration) { + return TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) || moduleMembersAreElided(declaration.moduleElements); + } + ASTHelpers.moduleIsElided = moduleIsElided; + + function moduleMembersAreElided(members) { + for (var i = 0, n = members.childCount(); i < n; i++) { + var member = members.childAt(i); + + if (member.kind() === 130 /* ModuleDeclaration */) { + if (!moduleIsElided(member)) { + return false; + } + } else if (member.kind() !== 128 /* InterfaceDeclaration */) { + return false; + } + } + + return true; + } + + function enumIsElided(declaration) { + if (TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */)) { + return true; + } + + return false; + } + ASTHelpers.enumIsElided = enumIsElided; + + function isValidAstNode(ast) { + if (!ast) + return false; + + if (ast.start() === -1 || ast.end() === -1) + return false; + + return true; + } + ASTHelpers.isValidAstNode = isValidAstNode; + + function getAstAtPosition(script, pos, useTrailingTriviaAsLimChar, forceInclusive) { + if (typeof useTrailingTriviaAsLimChar === "undefined") { useTrailingTriviaAsLimChar = true; } + if (typeof forceInclusive === "undefined") { forceInclusive = false; } + var top = null; + + var pre = function (cur, walker) { + if (isValidAstNode(cur)) { + var isInvalid1 = cur.kind() === 149 /* ExpressionStatement */ && cur.width() === 0; + + if (isInvalid1) { + walker.options.goChildren = false; + } else { + var inclusive = forceInclusive || cur.kind() === 11 /* IdentifierName */ || cur.kind() === 212 /* MemberAccessExpression */ || cur.kind() === 121 /* QualifiedName */ || cur.kind() === 224 /* VariableDeclaration */ || cur.kind() === 225 /* VariableDeclarator */ || cur.kind() === 213 /* InvocationExpression */ || pos === script.end() + script.trailingTriviaWidth(); + + var minChar = cur.start(); + var limChar = cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0) + (inclusive ? 1 : 0); + if (pos >= minChar && pos < limChar) { + if ((cur.kind() !== 1 /* List */ && cur.kind() !== 2 /* SeparatedList */) || cur.end() > cur.start()) { + if (top === null) { + top = cur; + } else if (cur.start() >= top.start() && (cur.end() + (useTrailingTriviaAsLimChar ? cur.trailingTriviaWidth() : 0)) <= (top.end() + (useTrailingTriviaAsLimChar ? top.trailingTriviaWidth() : 0))) { + if (top.width() !== 0 || cur.width() !== 0) { + top = cur; + } + } + } + } + + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + }; + + TypeScript.getAstWalkerFactory().walk(script, pre); + return top; + } + ASTHelpers.getAstAtPosition = getAstAtPosition; + + function getExtendsHeritageClause(clauses) { + if (!clauses) { + return null; + } + + return clauses.firstOrDefault(function (c) { + return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 230 /* ExtendsHeritageClause */; + }); + } + ASTHelpers.getExtendsHeritageClause = getExtendsHeritageClause; + + function getImplementsHeritageClause(clauses) { + if (!clauses) { + return null; + } + + return clauses.firstOrDefault(function (c) { + return c.typeNames.nonSeparatorCount() > 0 && c.kind() === 231 /* ImplementsHeritageClause */; + }); + } + ASTHelpers.getImplementsHeritageClause = getImplementsHeritageClause; + + function isCallExpression(ast) { + return (ast && ast.kind() === 213 /* InvocationExpression */) || (ast && ast.kind() === 216 /* ObjectCreationExpression */); + } + ASTHelpers.isCallExpression = isCallExpression; + + function isCallExpressionTarget(ast) { + if (!ast) { + return false; + } + + var current = ast; + + while (current && current.parent) { + if (current.parent.kind() === 212 /* MemberAccessExpression */ && current.parent.name === current) { + current = current.parent; + continue; + } + + break; + } + + if (current && current.parent) { + if (current.parent.kind() === 213 /* InvocationExpression */ || current.parent.kind() === 216 /* ObjectCreationExpression */) { + return current === current.parent.expression; + } + } + + return false; + } + ASTHelpers.isCallExpressionTarget = isCallExpressionTarget; + + function isNameOfSomeDeclaration(ast) { + if (ast === null || ast.parent === null) { + return false; + } + if (ast.kind() !== 11 /* IdentifierName */) { + return false; + } + + switch (ast.parent.kind()) { + case 131 /* ClassDeclaration */: + return ast.parent.identifier === ast; + case 128 /* InterfaceDeclaration */: + return ast.parent.identifier === ast; + case 132 /* EnumDeclaration */: + return ast.parent.identifier === ast; + case 130 /* ModuleDeclaration */: + return ast.parent.name === ast || ast.parent.stringLiteral === ast; + case 225 /* VariableDeclarator */: + return ast.parent.propertyName === ast; + case 129 /* FunctionDeclaration */: + return ast.parent.identifier === ast; + case 135 /* MemberFunctionDeclaration */: + return ast.parent.propertyName === ast; + case 242 /* Parameter */: + return ast.parent.identifier === ast; + case 238 /* TypeParameter */: + return ast.parent.identifier === ast; + case 240 /* SimplePropertyAssignment */: + return ast.parent.propertyName === ast; + case 241 /* FunctionPropertyAssignment */: + return ast.parent.propertyName === ast; + case 243 /* EnumElement */: + return ast.parent.propertyName === ast; + case 133 /* ImportDeclaration */: + return ast.parent.identifier === ast; + } + + return false; + } + + function isDeclarationASTOrDeclarationNameAST(ast) { + return isNameOfSomeDeclaration(ast) || isDeclarationAST(ast); + } + ASTHelpers.isDeclarationASTOrDeclarationNameAST = isDeclarationASTOrDeclarationNameAST; + + function getEnclosingParameterForInitializer(ast) { + var current = ast; + while (current) { + switch (current.kind()) { + case 232 /* EqualsValueClause */: + if (current.parent && current.parent.kind() === 242 /* Parameter */) { + return current.parent; + } + break; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + return null; + } + + current = current.parent; + } + return null; + } + ASTHelpers.getEnclosingParameterForInitializer = getEnclosingParameterForInitializer; + + function getEnclosingMemberVariableDeclaration(ast) { + var current = ast; + + while (current) { + switch (current.kind()) { + case 136 /* MemberVariableDeclaration */: + return current; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + return null; + } + current = current.parent; + } + + return null; + } + ASTHelpers.getEnclosingMemberVariableDeclaration = getEnclosingMemberVariableDeclaration; + + function isNameOfFunction(ast) { + return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 129 /* FunctionDeclaration */ && ast.parent.identifier === ast; + } + ASTHelpers.isNameOfFunction = isNameOfFunction; + + function isNameOfMemberFunction(ast) { + return ast && ast.parent && ast.kind() === 11 /* IdentifierName */ && ast.parent.kind() === 135 /* MemberFunctionDeclaration */ && ast.parent.propertyName === ast; + } + ASTHelpers.isNameOfMemberFunction = isNameOfMemberFunction; + + function isNameOfMemberAccessExpression(ast) { + if (ast && ast.parent && ast.parent.kind() === 212 /* MemberAccessExpression */ && ast.parent.name === ast) { + return true; + } + + return false; + } + ASTHelpers.isNameOfMemberAccessExpression = isNameOfMemberAccessExpression; + + function isRightSideOfQualifiedName(ast) { + if (ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast) { + return true; + } + + return false; + } + ASTHelpers.isRightSideOfQualifiedName = isRightSideOfQualifiedName; + + function parentIsModuleDeclaration(ast) { + return ast.parent && ast.parent.kind() === 130 /* ModuleDeclaration */; + } + ASTHelpers.parentIsModuleDeclaration = parentIsModuleDeclaration; + + function parametersFromIdentifier(id) { + return { + length: 1, + lastParameterIsRest: function () { + return false; + }, + ast: id, + astAt: function (index) { + return id; + }, + identifierAt: function (index) { + return id; + }, + typeAt: function (index) { + return null; + }, + initializerAt: function (index) { + return null; + }, + isOptionalAt: function (index) { + return false; + } + }; + } + ASTHelpers.parametersFromIdentifier = parametersFromIdentifier; + + function parametersFromParameter(parameter) { + return { + length: 1, + lastParameterIsRest: function () { + return parameter.dotDotDotToken !== null; + }, + ast: parameter, + astAt: function (index) { + return parameter; + }, + identifierAt: function (index) { + return parameter.identifier; + }, + typeAt: function (index) { + return getType(parameter); + }, + initializerAt: function (index) { + return parameter.equalsValueClause; + }, + isOptionalAt: function (index) { + return parameterIsOptional(parameter); + } + }; + } + ASTHelpers.parametersFromParameter = parametersFromParameter; + + function parameterIsOptional(parameter) { + return parameter.questionToken !== null || parameter.equalsValueClause !== null; + } + + function parametersFromParameterList(list) { + return { + length: list.parameters.nonSeparatorCount(), + lastParameterIsRest: function () { + return TypeScript.lastParameterIsRest(list); + }, + ast: list.parameters, + astAt: function (index) { + return list.parameters.nonSeparatorAt(index); + }, + identifierAt: function (index) { + return list.parameters.nonSeparatorAt(index).identifier; + }, + typeAt: function (index) { + return getType(list.parameters.nonSeparatorAt(index)); + }, + initializerAt: function (index) { + return list.parameters.nonSeparatorAt(index).equalsValueClause; + }, + isOptionalAt: function (index) { + return parameterIsOptional(list.parameters.nonSeparatorAt(index)); + } + }; + } + ASTHelpers.parametersFromParameterList = parametersFromParameterList; + + function isDeclarationAST(ast) { + switch (ast.kind()) { + case 225 /* VariableDeclarator */: + return getVariableStatement(ast) !== null; + + case 133 /* ImportDeclaration */: + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 242 /* Parameter */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 144 /* IndexSignature */: + case 129 /* FunctionDeclaration */: + case 130 /* ModuleDeclaration */: + case 124 /* ArrayType */: + case 122 /* ObjectType */: + case 238 /* TypeParameter */: + case 137 /* ConstructorDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + case 136 /* MemberVariableDeclaration */: + case 138 /* IndexMemberDeclaration */: + case 132 /* EnumDeclaration */: + case 243 /* EnumElement */: + case 240 /* SimplePropertyAssignment */: + case 241 /* FunctionPropertyAssignment */: + case 222 /* FunctionExpression */: + case 142 /* CallSignature */: + case 143 /* ConstructSignature */: + case 145 /* MethodSignature */: + case 141 /* PropertySignature */: + return true; + default: + return false; + } + } + ASTHelpers.isDeclarationAST = isDeclarationAST; + + function docComments(ast) { + if (isDeclarationAST(ast)) { + var preComments = ast.kind() === 225 /* VariableDeclarator */ ? getVariableStatement(ast).preComments() : ast.preComments(); + + if (preComments && preComments.length > 0) { + var preCommentsLength = preComments.length; + var docComments = new Array(); + for (var i = preCommentsLength - 1; i >= 0; i--) { + if (isDocComment(preComments[i])) { + docComments.push(preComments[i]); + continue; + } + + break; + } + + return docComments.reverse(); + } + } + + return TypeScript.sentinelEmptyArray; + } + ASTHelpers.docComments = docComments; + + function isDocComment(comment) { + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + var fullText = comment.fullText(); + return fullText.charAt(2) === "*" && fullText.charAt(3) !== "/"; + } + + return false; + } + + function getParameterList(ast) { + if (ast) { + switch (ast.kind()) { + case 137 /* ConstructorDeclaration */: + return getParameterList(ast.callSignature); + case 129 /* FunctionDeclaration */: + return getParameterList(ast.callSignature); + case 218 /* ParenthesizedArrowFunctionExpression */: + return getParameterList(ast.callSignature); + case 143 /* ConstructSignature */: + return getParameterList(ast.callSignature); + case 135 /* MemberFunctionDeclaration */: + return getParameterList(ast.callSignature); + case 241 /* FunctionPropertyAssignment */: + return getParameterList(ast.callSignature); + case 222 /* FunctionExpression */: + return getParameterList(ast.callSignature); + case 145 /* MethodSignature */: + return getParameterList(ast.callSignature); + case 125 /* ConstructorType */: + return ast.parameterList; + case 123 /* FunctionType */: + return ast.parameterList; + case 142 /* CallSignature */: + return ast.parameterList; + case 139 /* GetAccessor */: + return ast.parameterList; + case 140 /* SetAccessor */: + return ast.parameterList; + } + } + + return null; + } + ASTHelpers.getParameterList = getParameterList; + + function getType(ast) { + if (ast) { + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + return getType(ast.callSignature); + case 218 /* ParenthesizedArrowFunctionExpression */: + return getType(ast.callSignature); + case 143 /* ConstructSignature */: + return getType(ast.callSignature); + case 135 /* MemberFunctionDeclaration */: + return getType(ast.callSignature); + case 241 /* FunctionPropertyAssignment */: + return getType(ast.callSignature); + case 222 /* FunctionExpression */: + return getType(ast.callSignature); + case 145 /* MethodSignature */: + return getType(ast.callSignature); + case 142 /* CallSignature */: + return getType(ast.typeAnnotation); + case 144 /* IndexSignature */: + return getType(ast.typeAnnotation); + case 141 /* PropertySignature */: + return getType(ast.typeAnnotation); + case 139 /* GetAccessor */: + return getType(ast.typeAnnotation); + case 242 /* Parameter */: + return getType(ast.typeAnnotation); + case 136 /* MemberVariableDeclaration */: + return getType(ast.variableDeclarator); + case 225 /* VariableDeclarator */: + return getType(ast.typeAnnotation); + case 236 /* CatchClause */: + return getType(ast.typeAnnotation); + case 125 /* ConstructorType */: + return ast.type; + case 123 /* FunctionType */: + return ast.type; + case 244 /* TypeAnnotation */: + return ast.type; + } + } + + return null; + } + ASTHelpers.getType = getType; + + function getVariableStatement(variableDeclarator) { + if (variableDeclarator && variableDeclarator.parent && variableDeclarator.parent.parent && variableDeclarator.parent.parent.parent && variableDeclarator.parent.kind() === 2 /* SeparatedList */ && variableDeclarator.parent.parent.kind() === 224 /* VariableDeclaration */ && variableDeclarator.parent.parent.parent.kind() === 148 /* VariableStatement */) { + return variableDeclarator.parent.parent.parent; + } + + return null; + } + + function getVariableDeclaratorModifiers(variableDeclarator) { + var variableStatement = getVariableStatement(variableDeclarator); + return variableStatement ? variableStatement.modifiers : TypeScript.sentinelEmptyArray; + } + ASTHelpers.getVariableDeclaratorModifiers = getVariableDeclaratorModifiers; + + function isIntegerLiteralAST(expression) { + if (expression) { + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + expression = expression.operand; + return expression.kind() === 13 /* NumericLiteral */ && TypeScript.IntegerUtilities.isInteger(expression.text()); + + case 13 /* NumericLiteral */: + var text = expression.text(); + return TypeScript.IntegerUtilities.isInteger(text) || TypeScript.IntegerUtilities.isHexInteger(text); + } + } + + return false; + } + ASTHelpers.isIntegerLiteralAST = isIntegerLiteralAST; + + function getEnclosingModuleDeclaration(ast) { + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + return ast; + } + + ast = ast.parent; + } + + return null; + } + ASTHelpers.getEnclosingModuleDeclaration = getEnclosingModuleDeclaration; + + function isEntireNameOfModuleDeclaration(nameAST) { + return parentIsModuleDeclaration(nameAST) && nameAST.parent.name === nameAST; + } + + function getModuleDeclarationFromNameAST(ast) { + if (ast) { + switch (ast.kind()) { + case 14 /* StringLiteral */: + if (parentIsModuleDeclaration(ast) && ast.parent.stringLiteral === ast) { + return ast.parent; + } + return null; + + case 11 /* IdentifierName */: + case 121 /* QualifiedName */: + if (isEntireNameOfModuleDeclaration(ast)) { + return ast.parent; + } + break; + + default: + return null; + } + + for (ast = ast.parent; ast && ast.kind() === 121 /* QualifiedName */; ast = ast.parent) { + if (isEntireNameOfModuleDeclaration(ast)) { + return ast.parent; + } + } + } + + return null; + } + ASTHelpers.getModuleDeclarationFromNameAST = getModuleDeclarationFromNameAST; + + function isLastNameOfModule(ast, astName) { + if (ast) { + if (ast.stringLiteral) { + return astName === ast.stringLiteral; + } else if (ast.name.kind() === 121 /* QualifiedName */) { + return astName === ast.name.right; + } else { + return astName === ast.name; + } + } + + return false; + } + ASTHelpers.isLastNameOfModule = isLastNameOfModule; + + function getNameOfIdenfierOrQualifiedName(name) { + if (name.kind() === 11 /* IdentifierName */) { + return name.text(); + } else { + TypeScript.Debug.assert(name.kind() == 121 /* QualifiedName */); + var dotExpr = name; + return getNameOfIdenfierOrQualifiedName(dotExpr.left) + "." + getNameOfIdenfierOrQualifiedName(dotExpr.right); + } + } + ASTHelpers.getNameOfIdenfierOrQualifiedName = getNameOfIdenfierOrQualifiedName; + + function getModuleNames(name, result) { + result = result || []; + + if (name.kind() === 121 /* QualifiedName */) { + getModuleNames(name.left, result); + result.push(name.right); + } else { + result.push(name); + } + + return result; + } + ASTHelpers.getModuleNames = getModuleNames; + })(TypeScript.ASTHelpers || (TypeScript.ASTHelpers = {})); + var ASTHelpers = TypeScript.ASTHelpers; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function walkListChildren(preAst, walker) { + for (var i = 0, n = preAst.childCount(); i < n; i++) { + walker.walk(preAst.childAt(i)); + } + } + + function walkThrowStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkPrefixUnaryExpressionChildren(preAst, walker) { + walker.walk(preAst.operand); + } + + function walkPostfixUnaryExpressionChildren(preAst, walker) { + walker.walk(preAst.operand); + } + + function walkDeleteExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkTypeArgumentListChildren(preAst, walker) { + walker.walk(preAst.typeArguments); + } + + function walkTypeOfExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkVoidExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkArgumentListChildren(preAst, walker) { + walker.walk(preAst.typeArgumentList); + walker.walk(preAst.arguments); + } + + function walkArrayLiteralExpressionChildren(preAst, walker) { + walker.walk(preAst.expressions); + } + + function walkSimplePropertyAssignmentChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.expression); + } + + function walkFunctionPropertyAssignmentChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkGetAccessorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.parameterList); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.block); + } + + function walkSeparatedListChildren(preAst, walker) { + for (var i = 0, n = preAst.nonSeparatorCount(); i < n; i++) { + walker.walk(preAst.nonSeparatorAt(i)); + } + } + + function walkSetAccessorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.parameterList); + walker.walk(preAst.block); + } + + function walkObjectLiteralExpressionChildren(preAst, walker) { + walker.walk(preAst.propertyAssignments); + } + + function walkCastExpressionChildren(preAst, walker) { + walker.walk(preAst.type); + walker.walk(preAst.expression); + } + + function walkParenthesizedExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkElementAccessExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentExpression); + } + + function walkMemberAccessExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.name); + } + + function walkQualifiedNameChildren(preAst, walker) { + walker.walk(preAst.left); + walker.walk(preAst.right); + } + + function walkBinaryExpressionChildren(preAst, walker) { + walker.walk(preAst.left); + walker.walk(preAst.right); + } + + function walkEqualsValueClauseChildren(preAst, walker) { + walker.walk(preAst.value); + } + + function walkTypeParameterChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.constraint); + } + + function walkTypeParameterListChildren(preAst, walker) { + walker.walk(preAst.typeParameters); + } + + function walkGenericTypeChildren(preAst, walker) { + walker.walk(preAst.name); + walker.walk(preAst.typeArgumentList); + } + + function walkTypeAnnotationChildren(preAst, walker) { + walker.walk(preAst.type); + } + + function walkTypeQueryChildren(preAst, walker) { + walker.walk(preAst.name); + } + + function walkInvocationExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentList); + } + + function walkObjectCreationExpressionChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.argumentList); + } + + function walkTrinaryExpressionChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.whenTrue); + walker.walk(preAst.whenFalse); + } + + function walkFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkFunctionTypeChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.type); + } + + function walkParenthesizedArrowFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + walker.walk(preAst.expression); + } + + function walkSimpleArrowFunctionExpressionChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.block); + walker.walk(preAst.expression); + } + + function walkMemberFunctionDeclarationChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkFuncDeclChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkIndexMemberDeclarationChildren(preAst, walker) { + walker.walk(preAst.indexSignature); + } + + function walkIndexSignatureChildren(preAst, walker) { + walker.walk(preAst.parameter); + walker.walk(preAst.typeAnnotation); + } + + function walkCallSignatureChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.typeAnnotation); + } + + function walkConstraintChildren(preAst, walker) { + walker.walk(preAst.type); + } + + function walkConstructorDeclarationChildren(preAst, walker) { + walker.walk(preAst.callSignature); + walker.walk(preAst.block); + } + + function walkConstructorTypeChildren(preAst, walker) { + walker.walk(preAst.typeParameterList); + walker.walk(preAst.parameterList); + walker.walk(preAst.type); + } + + function walkConstructSignatureChildren(preAst, walker) { + walker.walk(preAst.callSignature); + } + + function walkParameterChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.equalsValueClause); + } + + function walkParameterListChildren(preAst, walker) { + walker.walk(preAst.parameters); + } + + function walkPropertySignatureChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.typeAnnotation); + } + + function walkVariableDeclaratorChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.equalsValueClause); + } + + function walkMemberVariableDeclarationChildren(preAst, walker) { + walker.walk(preAst.variableDeclarator); + } + + function walkMethodSignatureChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.callSignature); + } + + function walkReturnStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkForStatementChildren(preAst, walker) { + walker.walk(preAst.variableDeclaration); + walker.walk(preAst.initializer); + walker.walk(preAst.condition); + walker.walk(preAst.incrementor); + walker.walk(preAst.statement); + } + + function walkForInStatementChildren(preAst, walker) { + walker.walk(preAst.variableDeclaration); + walker.walk(preAst.left); + walker.walk(preAst.expression); + walker.walk(preAst.statement); + } + + function walkIfStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + walker.walk(preAst.elseClause); + } + + function walkElseClauseChildren(preAst, walker) { + walker.walk(preAst.statement); + } + + function walkWhileStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + + function walkDoStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + + function walkBlockChildren(preAst, walker) { + walker.walk(preAst.statements); + } + + function walkVariableDeclarationChildren(preAst, walker) { + walker.walk(preAst.declarators); + } + + function walkCaseSwitchClauseChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.statements); + } + + function walkDefaultSwitchClauseChildren(preAst, walker) { + walker.walk(preAst.statements); + } + + function walkSwitchStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + walker.walk(preAst.switchClauses); + } + + function walkTryStatementChildren(preAst, walker) { + walker.walk(preAst.block); + walker.walk(preAst.catchClause); + walker.walk(preAst.finallyClause); + } + + function walkCatchClauseChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeAnnotation); + walker.walk(preAst.block); + } + + function walkExternalModuleReferenceChildren(preAst, walker) { + walker.walk(preAst.stringLiteral); + } + + function walkFinallyClauseChildren(preAst, walker) { + walker.walk(preAst.block); + } + + function walkClassDeclChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeParameterList); + walker.walk(preAst.heritageClauses); + walker.walk(preAst.classElements); + } + + function walkScriptChildren(preAst, walker) { + walker.walk(preAst.moduleElements); + } + + function walkHeritageClauseChildren(preAst, walker) { + walker.walk(preAst.typeNames); + } + + function walkInterfaceDeclerationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.typeParameterList); + walker.walk(preAst.heritageClauses); + walker.walk(preAst.body); + } + + function walkObjectTypeChildren(preAst, walker) { + walker.walk(preAst.typeMembers); + } + + function walkArrayTypeChildren(preAst, walker) { + walker.walk(preAst.type); + } + + function walkModuleDeclarationChildren(preAst, walker) { + walker.walk(preAst.name); + walker.walk(preAst.stringLiteral); + walker.walk(preAst.moduleElements); + } + + function walkModuleNameModuleReferenceChildren(preAst, walker) { + walker.walk(preAst.moduleName); + } + + function walkEnumDeclarationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.enumElements); + } + + function walkEnumElementChildren(preAst, walker) { + walker.walk(preAst.propertyName); + walker.walk(preAst.equalsValueClause); + } + + function walkImportDeclarationChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.moduleReference); + } + + function walkExportAssignmentChildren(preAst, walker) { + walker.walk(preAst.identifier); + } + + function walkWithStatementChildren(preAst, walker) { + walker.walk(preAst.condition); + walker.walk(preAst.statement); + } + + function walkExpressionStatementChildren(preAst, walker) { + walker.walk(preAst.expression); + } + + function walkLabeledStatementChildren(preAst, walker) { + walker.walk(preAst.identifier); + walker.walk(preAst.statement); + } + + function walkVariableStatementChildren(preAst, walker) { + walker.walk(preAst.declaration); + } + + var childrenWalkers = new Array(246 /* Last */ + 1); + + for (var i = 9 /* FirstToken */, n = 119 /* LastToken */; i <= n; i++) { + childrenWalkers[i] = null; + } + for (var i = 4 /* FirstTrivia */, n = 8 /* LastTrivia */; i <= n; i++) { + childrenWalkers[i] = null; + } + + childrenWalkers[175 /* AddAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[208 /* AddExpression */] = walkBinaryExpressionChildren; + childrenWalkers[180 /* AndAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[60 /* AnyKeyword */] = null; + childrenWalkers[226 /* ArgumentList */] = walkArgumentListChildren; + childrenWalkers[214 /* ArrayLiteralExpression */] = walkArrayLiteralExpressionChildren; + childrenWalkers[124 /* ArrayType */] = walkArrayTypeChildren; + childrenWalkers[219 /* SimpleArrowFunctionExpression */] = walkSimpleArrowFunctionExpressionChildren; + childrenWalkers[218 /* ParenthesizedArrowFunctionExpression */] = walkParenthesizedArrowFunctionExpressionChildren; + childrenWalkers[174 /* AssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[191 /* BitwiseAndExpression */] = walkBinaryExpressionChildren; + childrenWalkers[190 /* BitwiseExclusiveOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[166 /* BitwiseNotExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[189 /* BitwiseOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[146 /* Block */] = walkBlockChildren; + childrenWalkers[61 /* BooleanKeyword */] = null; + childrenWalkers[152 /* BreakStatement */] = null; + childrenWalkers[142 /* CallSignature */] = walkCallSignatureChildren; + childrenWalkers[233 /* CaseSwitchClause */] = walkCaseSwitchClauseChildren; + childrenWalkers[220 /* CastExpression */] = walkCastExpressionChildren; + childrenWalkers[236 /* CatchClause */] = walkCatchClauseChildren; + childrenWalkers[131 /* ClassDeclaration */] = walkClassDeclChildren; + childrenWalkers[173 /* CommaExpression */] = walkBinaryExpressionChildren; + childrenWalkers[186 /* ConditionalExpression */] = walkTrinaryExpressionChildren; + childrenWalkers[239 /* Constraint */] = walkConstraintChildren; + childrenWalkers[137 /* ConstructorDeclaration */] = walkConstructorDeclarationChildren; + childrenWalkers[143 /* ConstructSignature */] = walkConstructSignatureChildren; + childrenWalkers[153 /* ContinueStatement */] = null; + childrenWalkers[125 /* ConstructorType */] = walkConstructorTypeChildren; + childrenWalkers[162 /* DebuggerStatement */] = null; + childrenWalkers[234 /* DefaultSwitchClause */] = walkDefaultSwitchClauseChildren; + childrenWalkers[170 /* DeleteExpression */] = walkDeleteExpressionChildren; + childrenWalkers[178 /* DivideAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[206 /* DivideExpression */] = walkBinaryExpressionChildren; + childrenWalkers[161 /* DoStatement */] = walkDoStatementChildren; + childrenWalkers[221 /* ElementAccessExpression */] = walkElementAccessExpressionChildren; + childrenWalkers[235 /* ElseClause */] = walkElseClauseChildren; + childrenWalkers[156 /* EmptyStatement */] = null; + childrenWalkers[132 /* EnumDeclaration */] = walkEnumDeclarationChildren; + childrenWalkers[243 /* EnumElement */] = walkEnumElementChildren; + childrenWalkers[194 /* EqualsExpression */] = walkBinaryExpressionChildren; + childrenWalkers[232 /* EqualsValueClause */] = walkEqualsValueClauseChildren; + childrenWalkers[192 /* EqualsWithTypeConversionExpression */] = walkBinaryExpressionChildren; + childrenWalkers[181 /* ExclusiveOrAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[134 /* ExportAssignment */] = walkExportAssignmentChildren; + childrenWalkers[149 /* ExpressionStatement */] = walkExpressionStatementChildren; + childrenWalkers[230 /* ExtendsHeritageClause */] = walkHeritageClauseChildren; + childrenWalkers[245 /* ExternalModuleReference */] = walkExternalModuleReferenceChildren; + childrenWalkers[24 /* FalseKeyword */] = null; + childrenWalkers[237 /* FinallyClause */] = walkFinallyClauseChildren; + childrenWalkers[155 /* ForInStatement */] = walkForInStatementChildren; + childrenWalkers[154 /* ForStatement */] = walkForStatementChildren; + childrenWalkers[129 /* FunctionDeclaration */] = walkFuncDeclChildren; + childrenWalkers[222 /* FunctionExpression */] = walkFunctionExpressionChildren; + childrenWalkers[241 /* FunctionPropertyAssignment */] = walkFunctionPropertyAssignmentChildren; + childrenWalkers[123 /* FunctionType */] = walkFunctionTypeChildren; + childrenWalkers[126 /* GenericType */] = walkGenericTypeChildren; + childrenWalkers[139 /* GetAccessor */] = walkGetAccessorChildren; + childrenWalkers[197 /* GreaterThanExpression */] = walkBinaryExpressionChildren; + childrenWalkers[199 /* GreaterThanOrEqualExpression */] = walkBinaryExpressionChildren; + childrenWalkers[147 /* IfStatement */] = walkIfStatementChildren; + childrenWalkers[231 /* ImplementsHeritageClause */] = walkHeritageClauseChildren; + childrenWalkers[133 /* ImportDeclaration */] = walkImportDeclarationChildren; + childrenWalkers[138 /* IndexMemberDeclaration */] = walkIndexMemberDeclarationChildren; + childrenWalkers[144 /* IndexSignature */] = walkIndexSignatureChildren; + childrenWalkers[201 /* InExpression */] = walkBinaryExpressionChildren; + childrenWalkers[200 /* InstanceOfExpression */] = walkBinaryExpressionChildren; + childrenWalkers[128 /* InterfaceDeclaration */] = walkInterfaceDeclerationChildren; + childrenWalkers[213 /* InvocationExpression */] = walkInvocationExpressionChildren; + childrenWalkers[160 /* LabeledStatement */] = walkLabeledStatementChildren; + childrenWalkers[183 /* LeftShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[202 /* LeftShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[196 /* LessThanExpression */] = walkBinaryExpressionChildren; + childrenWalkers[198 /* LessThanOrEqualExpression */] = walkBinaryExpressionChildren; + childrenWalkers[1 /* List */] = walkListChildren; + childrenWalkers[188 /* LogicalAndExpression */] = walkBinaryExpressionChildren; + childrenWalkers[167 /* LogicalNotExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[187 /* LogicalOrExpression */] = walkBinaryExpressionChildren; + childrenWalkers[212 /* MemberAccessExpression */] = walkMemberAccessExpressionChildren; + childrenWalkers[135 /* MemberFunctionDeclaration */] = walkMemberFunctionDeclarationChildren; + childrenWalkers[136 /* MemberVariableDeclaration */] = walkMemberVariableDeclarationChildren; + childrenWalkers[145 /* MethodSignature */] = walkMethodSignatureChildren; + childrenWalkers[130 /* ModuleDeclaration */] = walkModuleDeclarationChildren; + childrenWalkers[246 /* ModuleNameModuleReference */] = walkModuleNameModuleReferenceChildren; + childrenWalkers[179 /* ModuloAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[207 /* ModuloExpression */] = walkBinaryExpressionChildren; + childrenWalkers[177 /* MultiplyAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[205 /* MultiplyExpression */] = walkBinaryExpressionChildren; + childrenWalkers[11 /* IdentifierName */] = null; + childrenWalkers[165 /* NegateExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[0 /* None */] = null; + childrenWalkers[195 /* NotEqualsExpression */] = walkBinaryExpressionChildren; + childrenWalkers[193 /* NotEqualsWithTypeConversionExpression */] = walkBinaryExpressionChildren; + childrenWalkers[32 /* NullKeyword */] = null; + childrenWalkers[67 /* NumberKeyword */] = null; + childrenWalkers[13 /* NumericLiteral */] = null; + childrenWalkers[216 /* ObjectCreationExpression */] = walkObjectCreationExpressionChildren; + childrenWalkers[215 /* ObjectLiteralExpression */] = walkObjectLiteralExpressionChildren; + childrenWalkers[122 /* ObjectType */] = walkObjectTypeChildren; + childrenWalkers[223 /* OmittedExpression */] = null; + childrenWalkers[182 /* OrAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[242 /* Parameter */] = walkParameterChildren; + childrenWalkers[227 /* ParameterList */] = walkParameterListChildren; + childrenWalkers[217 /* ParenthesizedExpression */] = walkParenthesizedExpressionChildren; + childrenWalkers[164 /* PlusExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[211 /* PostDecrementExpression */] = walkPostfixUnaryExpressionChildren; + childrenWalkers[210 /* PostIncrementExpression */] = walkPostfixUnaryExpressionChildren; + childrenWalkers[169 /* PreDecrementExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[168 /* PreIncrementExpression */] = walkPrefixUnaryExpressionChildren; + childrenWalkers[141 /* PropertySignature */] = walkPropertySignatureChildren; + childrenWalkers[121 /* QualifiedName */] = walkQualifiedNameChildren; + childrenWalkers[12 /* RegularExpressionLiteral */] = null; + childrenWalkers[150 /* ReturnStatement */] = walkReturnStatementChildren; + childrenWalkers[120 /* SourceUnit */] = walkScriptChildren; + childrenWalkers[2 /* SeparatedList */] = walkSeparatedListChildren; + childrenWalkers[140 /* SetAccessor */] = walkSetAccessorChildren; + childrenWalkers[184 /* SignedRightShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[203 /* SignedRightShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[240 /* SimplePropertyAssignment */] = walkSimplePropertyAssignmentChildren; + childrenWalkers[14 /* StringLiteral */] = null; + childrenWalkers[69 /* StringKeyword */] = null; + childrenWalkers[176 /* SubtractAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[209 /* SubtractExpression */] = walkBinaryExpressionChildren; + childrenWalkers[50 /* SuperKeyword */] = null; + childrenWalkers[151 /* SwitchStatement */] = walkSwitchStatementChildren; + childrenWalkers[35 /* ThisKeyword */] = null; + childrenWalkers[157 /* ThrowStatement */] = walkThrowStatementChildren; + childrenWalkers[3 /* TriviaList */] = null; + childrenWalkers[37 /* TrueKeyword */] = null; + childrenWalkers[159 /* TryStatement */] = walkTryStatementChildren; + childrenWalkers[244 /* TypeAnnotation */] = walkTypeAnnotationChildren; + childrenWalkers[228 /* TypeArgumentList */] = walkTypeArgumentListChildren; + childrenWalkers[171 /* TypeOfExpression */] = walkTypeOfExpressionChildren; + childrenWalkers[238 /* TypeParameter */] = walkTypeParameterChildren; + childrenWalkers[229 /* TypeParameterList */] = walkTypeParameterListChildren; + childrenWalkers[127 /* TypeQuery */] = walkTypeQueryChildren; + childrenWalkers[185 /* UnsignedRightShiftAssignmentExpression */] = walkBinaryExpressionChildren; + childrenWalkers[204 /* UnsignedRightShiftExpression */] = walkBinaryExpressionChildren; + childrenWalkers[224 /* VariableDeclaration */] = walkVariableDeclarationChildren; + childrenWalkers[225 /* VariableDeclarator */] = walkVariableDeclaratorChildren; + childrenWalkers[148 /* VariableStatement */] = walkVariableStatementChildren; + childrenWalkers[172 /* VoidExpression */] = walkVoidExpressionChildren; + childrenWalkers[41 /* VoidKeyword */] = null; + childrenWalkers[158 /* WhileStatement */] = walkWhileStatementChildren; + childrenWalkers[163 /* WithStatement */] = walkWithStatementChildren; + + for (var e in TypeScript.SyntaxKind) { + if (TypeScript.SyntaxKind.hasOwnProperty(e) && TypeScript.StringUtilities.isString(TypeScript.SyntaxKind[e])) { + TypeScript.Debug.assert(childrenWalkers[e] !== undefined, "Fix initWalkers: " + TypeScript.SyntaxKind[e]); + } + } + + var AstWalkOptions = (function () { + function AstWalkOptions() { + this.goChildren = true; + this.stopWalking = false; + } + return AstWalkOptions; + })(); + TypeScript.AstWalkOptions = AstWalkOptions; + + var SimplePreAstWalker = (function () { + function SimplePreAstWalker(pre, state) { + this.pre = pre; + this.state = state; + this.options = new AstWalkOptions(); + } + SimplePreAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + + this.pre(ast, this.state); + + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + }; + return SimplePreAstWalker; + })(); + + var SimplePrePostAstWalker = (function () { + function SimplePrePostAstWalker(pre, post, state) { + this.pre = pre; + this.post = post; + this.state = state; + this.options = new AstWalkOptions(); + } + SimplePrePostAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + + this.pre(ast, this.state); + + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + + this.post(ast, this.state); + }; + return SimplePrePostAstWalker; + })(); + + var NormalAstWalker = (function () { + function NormalAstWalker(pre, post, state) { + this.pre = pre; + this.post = post; + this.state = state; + this.options = new AstWalkOptions(); + } + NormalAstWalker.prototype.walk = function (ast) { + if (!ast) { + return; + } + + if (this.options.stopWalking) { + return; + } + + this.pre(ast, this); + + if (this.options.stopWalking) { + return; + } + + if (this.options.goChildren) { + var walker = childrenWalkers[ast.kind()]; + if (walker) { + walker(ast, this); + } + } else { + this.options.goChildren = true; + } + + if (this.post) { + this.post(ast, this); + } + }; + return NormalAstWalker; + })(); + + var AstWalkerFactory = (function () { + function AstWalkerFactory() { + } + AstWalkerFactory.prototype.walk = function (ast, pre, post, state) { + new NormalAstWalker(pre, post, state).walk(ast); + }; + + AstWalkerFactory.prototype.simpleWalk = function (ast, pre, post, state) { + if (post) { + new SimplePrePostAstWalker(pre, post, state).walk(ast); + } else { + new SimplePreAstWalker(pre, state).walk(ast); + } + }; + return AstWalkerFactory; + })(); + TypeScript.AstWalkerFactory = AstWalkerFactory; + + var globalAstWalkerFactory = new AstWalkerFactory(); + + function getAstWalkerFactory() { + return globalAstWalkerFactory; + } + TypeScript.getAstWalkerFactory = getAstWalkerFactory; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Base64Format = (function () { + function Base64Format() { + } + Base64Format.encode = function (inValue) { + if (inValue < 64) { + return Base64Format.encodedValues.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + }; + + Base64Format.decodeChar = function (inChar) { + if (inChar.length === 1) { + return Base64Format.encodedValues.indexOf(inChar); + } else { + throw TypeError('"' + inChar + '" must have length 1'); + } + }; + Base64Format.encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + return Base64Format; + })(); + + var Base64VLQFormat = (function () { + function Base64VLQFormat() { + } + Base64VLQFormat.encode = function (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 (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(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Base64_value_0_finished_with_a_continuation_bit, [inString])); + }; + return Base64VLQFormat; + })(); + TypeScript.Base64VLQFormat = Base64VLQFormat; +})(TypeScript || (TypeScript = {})); +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 SourceMapEntry = (function () { + function SourceMapEntry(emittedFile, emittedLine, emittedColumn, sourceFile, sourceLine, sourceColumn, sourceName) { + this.emittedFile = emittedFile; + this.emittedLine = emittedLine; + this.emittedColumn = emittedColumn; + this.sourceFile = sourceFile; + this.sourceLine = sourceLine; + this.sourceColumn = sourceColumn; + this.sourceName = sourceName; + TypeScript.Debug.assert(isFinite(emittedLine)); + TypeScript.Debug.assert(isFinite(emittedColumn)); + TypeScript.Debug.assert(isFinite(sourceColumn)); + TypeScript.Debug.assert(isFinite(sourceLine)); + } + return SourceMapEntry; + })(); + TypeScript.SourceMapEntry = SourceMapEntry; + + var SourceMapper = (function () { + function SourceMapper(jsFile, sourceMapOut, document, jsFilePath, emitOptions, resolvePath) { + this.jsFile = jsFile; + this.sourceMapOut = sourceMapOut; + this.names = []; + this.mappingLevel = []; + this.tsFilePaths = []; + this.allSourceMappings = []; + this.sourceMapEntries = []; + this.setSourceMapOptions(document, jsFilePath, emitOptions, resolvePath); + this.setNewSourceFile(document, emitOptions); + } + SourceMapper.prototype.getOutputFile = function () { + var result = this.sourceMapOut.getOutputFile(); + result.sourceMapEntries = this.sourceMapEntries; + + return result; + }; + + SourceMapper.prototype.increaseMappingLevel = function (ast) { + this.mappingLevel.push(ast); + }; + + SourceMapper.prototype.decreaseMappingLevel = function (ast) { + TypeScript.Debug.assert(this.mappingLevel.length > 0, "Mapping level should never be less than 0. This suggests a missing start call."); + var expectedAst = this.mappingLevel.pop(); + var expectedAstInfo = expectedAst.kind ? TypeScript.SyntaxKind[expectedAst.kind()] : [expectedAst.start(), expectedAst.end()]; + var astInfo = ast.kind ? TypeScript.SyntaxKind[ast.kind()] : [ast.start(), ast.end()]; + TypeScript.Debug.assert(ast === expectedAst, "Provided ast is not the expected AST, Expected: " + expectedAstInfo + " Given: " + astInfo); + }; + + SourceMapper.prototype.setNewSourceFile = function (document, emitOptions) { + var sourceMappings = []; + this.allSourceMappings.push(sourceMappings); + this.currentMappings = [sourceMappings]; + this.currentNameIndex = []; + + this.setNewSourceFilePath(document, emitOptions); + }; + + SourceMapper.prototype.setSourceMapOptions = function (document, jsFilePath, emitOptions, resolvePath) { + var prettyJsFileName = TypeScript.getPrettyName(jsFilePath, false, true); + var prettyMapFileName = prettyJsFileName + SourceMapper.MapFileExtension; + this.jsFileName = prettyJsFileName; + + if (emitOptions.sourceMapRootDirectory()) { + this.sourceMapDirectory = emitOptions.sourceMapRootDirectory(); + if (document.emitToOwnOutputFile()) { + this.sourceMapDirectory = this.sourceMapDirectory + TypeScript.switchToForwardSlashes(TypeScript.getRootFilePath((document.fileName)).replace(emitOptions.commonDirectoryPath(), "")); + } + + if (TypeScript.isRelative(this.sourceMapDirectory)) { + this.sourceMapDirectory = emitOptions.commonDirectoryPath() + this.sourceMapDirectory; + this.sourceMapDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(resolvePath(this.sourceMapDirectory))); + this.sourceMapPath = TypeScript.getRelativePathToFixedPath(TypeScript.getRootFilePath(jsFilePath), this.sourceMapDirectory + prettyMapFileName); + } else { + this.sourceMapPath = this.sourceMapDirectory + prettyMapFileName; + } + } else { + this.sourceMapPath = prettyMapFileName; + this.sourceMapDirectory = TypeScript.getRootFilePath(jsFilePath); + } + this.sourceRoot = emitOptions.sourceRootDirectory(); + }; + + SourceMapper.prototype.setNewSourceFilePath = function (document, emitOptions) { + var tsFilePath = TypeScript.switchToForwardSlashes(document.fileName); + if (emitOptions.sourceRootDirectory()) { + tsFilePath = TypeScript.getRelativePathToFixedPath(emitOptions.commonDirectoryPath(), tsFilePath); + } else { + tsFilePath = TypeScript.getRelativePathToFixedPath(this.sourceMapDirectory, tsFilePath); + } + this.tsFilePaths.push(tsFilePath); + }; + + SourceMapper.prototype.emitSourceMapping = function () { + var _this = this; + TypeScript.Debug.assert(this.mappingLevel.length === 0, "Mapping level is not 0. This suggest a missing end call. Value: " + this.mappingLevel.map(function (item) { + return ['Node of type', TypeScript.SyntaxKind[item.kind()], 'at', item.start(), 'to', item.end()].join(' '); + }).join(', ')); + + this.jsFile.WriteLine("//# sourceMappingURL=" + this.sourceMapPath); + + var mappingsString = ""; + + var prevEmittedColumn = 0; + var prevEmittedLine = 0; + var prevSourceColumn = 0; + var prevSourceLine = 0; + var prevSourceIndex = 0; + var prevNameIndex = 0; + var emitComma = false; + + var recordedPosition = null; + for (var sourceIndex = 0; sourceIndex < this.tsFilePaths.length; sourceIndex++) { + 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 + ","; + } + + _this.sourceMapEntries.push(new SourceMapEntry(_this.jsFileName, mappedPosition.emittedLine + 1, mappedPosition.emittedColumn + 1, _this.tsFilePaths[sourceIndex], mappedPosition.sourceLine, mappedPosition.sourceColumn + 1, nameIndex >= 0 ? _this.names[nameIndex] : undefined)); + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.emittedColumn - prevEmittedColumn); + prevEmittedColumn = mappedPosition.emittedColumn; + + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(sourceIndex - prevSourceIndex); + prevSourceIndex = sourceIndex; + + 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(nameIndex - prevNameIndex); + prevNameIndex = 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(this.allSourceMappings[sourceIndex]); + } + + this.sourceMapOut.Write(JSON.stringify({ + version: 3, + file: this.jsFileName, + sourceRoot: this.sourceRoot, + sources: this.tsFilePaths, + names: this.names, + mappings: mappingsString + })); + + this.sourceMapOut.Close(); + }; + SourceMapper.MapFileExtension = ".map"; + return SourceMapper; + })(); + TypeScript.SourceMapper = SourceMapper; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (EmitContainer) { + EmitContainer[EmitContainer["Prog"] = 0] = "Prog"; + EmitContainer[EmitContainer["Module"] = 1] = "Module"; + EmitContainer[EmitContainer["DynamicModule"] = 2] = "DynamicModule"; + EmitContainer[EmitContainer["Class"] = 3] = "Class"; + EmitContainer[EmitContainer["Constructor"] = 4] = "Constructor"; + EmitContainer[EmitContainer["Function"] = 5] = "Function"; + EmitContainer[EmitContainer["Args"] = 6] = "Args"; + EmitContainer[EmitContainer["Interface"] = 7] = "Interface"; + })(TypeScript.EmitContainer || (TypeScript.EmitContainer = {})); + var EmitContainer = TypeScript.EmitContainer; + + var EmitState = (function () { + function EmitState() { + this.column = 0; + this.line = 0; + this.container = 0 /* Prog */; + } + return EmitState; + })(); + TypeScript.EmitState = EmitState; + + var EmitOptions = (function () { + function EmitOptions(compiler, resolvePath) { + this.resolvePath = resolvePath; + this._diagnostic = null; + this._settings = null; + this._commonDirectoryPath = ""; + this._sharedOutputFile = ""; + this._sourceRootDirectory = ""; + this._sourceMapRootDirectory = ""; + this._outputDirectory = ""; + var settings = compiler.compilationSettings(); + this._settings = settings; + + if (settings.moduleGenTarget() === 0 /* Unspecified */) { + var fileNames = compiler.fileNames(); + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = compiler.getDocument(fileNames[i]); + if (!document.isDeclareFile() && document.isExternalModule()) { + var errorSpan = document.externalModuleIndicatorSpan(); + this._diagnostic = new TypeScript.Diagnostic(document.fileName, document.lineMap(), errorSpan.start(), errorSpan.length(), TypeScript.DiagnosticCode.Cannot_compile_external_modules_unless_the_module_flag_is_provided); + + return; + } + } + } + + if (!settings.mapSourceFiles()) { + if (settings.mapRoot()) { + if (settings.sourceRoot()) { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Options_mapRoot_and_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option, null); + return; + } else { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option, null); + return; + } + } else if (settings.sourceRoot()) { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option, null); + return; + } + } + + this._sourceMapRootDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(settings.mapRoot())); + this._sourceRootDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(settings.sourceRoot())); + + if (settings.outFileOption() || settings.outDirOption() || settings.mapRoot() || settings.sourceRoot()) { + if (settings.outFileOption()) { + this._sharedOutputFile = TypeScript.switchToForwardSlashes(resolvePath(settings.outFileOption())); + } + + if (settings.outDirOption()) { + this._outputDirectory = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(resolvePath(settings.outDirOption()))); + } + + if (this._outputDirectory || this._sourceMapRootDirectory || this.sourceRootDirectory) { + this.determineCommonDirectoryPath(compiler); + } + } + } + EmitOptions.prototype.diagnostic = function () { + return this._diagnostic; + }; + + EmitOptions.prototype.commonDirectoryPath = function () { + return this._commonDirectoryPath; + }; + EmitOptions.prototype.sharedOutputFile = function () { + return this._sharedOutputFile; + }; + EmitOptions.prototype.sourceRootDirectory = function () { + return this._sourceRootDirectory; + }; + EmitOptions.prototype.sourceMapRootDirectory = function () { + return this._sourceMapRootDirectory; + }; + EmitOptions.prototype.outputDirectory = function () { + return this._outputDirectory; + }; + + EmitOptions.prototype.compilationSettings = function () { + return this._settings; + }; + + EmitOptions.prototype.determineCommonDirectoryPath = function (compiler) { + var commonComponents = []; + var commonComponentsLength = -1; + + var fileNames = compiler.fileNames(); + for (var i = 0, len = fileNames.length; i < len; i++) { + var fileName = fileNames[i]; + var document = compiler.getDocument(fileNames[i]); + var sourceUnit = document.sourceUnit(); + + if (!document.isDeclareFile()) { + 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) { + var isDynamicModuleCompilation = TypeScript.ArrayUtilities.any(fileNames, function (fileName) { + document = compiler.getDocument(fileName); + return !document.isDeclareFile() && document.isExternalModule(); + }); + + if (this._outputDirectory || this._sourceRootDirectory || (this._sourceMapRootDirectory && (!this._sharedOutputFile || isDynamicModuleCompilation))) { + this._diagnostic = new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Cannot_find_the_common_subdirectory_path_for_the_input_files, null); + return; + } + + return; + } + + break; + } + } + + if (!updatedPath && fileComponents.length < commonComponentsLength) { + commonComponentsLength = fileComponents.length; + } + } + } + } + + this._commonDirectoryPath = commonComponents.slice(0, commonComponentsLength).join("/") + "/"; + }; + return EmitOptions; + })(); + TypeScript.EmitOptions = EmitOptions; + + var Indenter = (function () { + function Indenter() { + this.indentAmt = 0; + } + 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; + }; + Indenter.indentStep = 4; + Indenter.indentStepString = " "; + Indenter.indentStrings = []; + return Indenter; + })(); + TypeScript.Indenter = Indenter; + + function lastParameterIsRest(parameterList) { + var parameters = parameterList.parameters; + return parameters.nonSeparatorCount() > 0 && parameters.nonSeparatorAt(parameters.nonSeparatorCount() - 1).dotDotDotToken !== null; + } + TypeScript.lastParameterIsRest = lastParameterIsRest; + + var Emitter = (function () { + function Emitter(emittingFileName, outfile, emitOptions, semanticInfoChain) { + this.emittingFileName = emittingFileName; + this.outfile = outfile; + this.emitOptions = emitOptions; + this.semanticInfoChain = semanticInfoChain; + this.globalThisCapturePrologueEmitted = false; + this.extendsPrologueEmitted = false; + this.thisClassNode = null; + this.inArrowFunction = false; + this.moduleName = ""; + this.emitState = new EmitState(); + this.indenter = new Indenter(); + this.sourceMapper = null; + this.captureThisStmtString = "var _this = this;"; + this.declStack = []; + this.exportAssignment = null; + this.inWithBlock = false; + this.document = null; + this.detachedCommentsElement = null; + } + Emitter.prototype.pushDecl = function (decl) { + if (decl) { + this.declStack[this.declStack.length] = decl; + } + }; + + Emitter.prototype.popDecl = function (decl) { + if (decl) { + this.declStack.length--; + } + }; + + Emitter.prototype.getEnclosingDecl = function () { + var declStackLen = this.declStack.length; + var enclosingDecl = declStackLen > 0 ? this.declStack[declStackLen - 1] : null; + return enclosingDecl; + }; + + Emitter.prototype.setExportAssignment = function (exportAssignment) { + this.exportAssignment = exportAssignment; + }; + + Emitter.prototype.getExportAssignment = function () { + return this.exportAssignment; + }; + + Emitter.prototype.setDocument = function (document) { + this.document = document; + }; + + Emitter.prototype.shouldEmitImportDeclaration = function (importDeclAST) { + var isExternalModuleReference = importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */; + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); + var isExported = TypeScript.hasFlag(importDecl.flags, 1 /* Exported */); + var isAmdCodeGen = this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */; + + if (isExternalModuleReference && !isExported && isAmdCodeGen) { + return false; + } + + var importSymbol = importDecl.getSymbol(); + if (importSymbol.isUsedAsValue()) { + return true; + } + + if (importDeclAST.moduleReference.kind() !== 245 /* ExternalModuleReference */) { + var canBeUsedExternally = isExported || importSymbol.typeUsedExternally() || importSymbol.isUsedInExportedAlias(); + if (!canBeUsedExternally && !this.document.isExternalModule()) { + canBeUsedExternally = TypeScript.hasFlag(importDecl.getParentDecl().kind, 1 /* Script */ | 32 /* DynamicModule */); + } + + if (canBeUsedExternally) { + if (importSymbol.getExportAssignedValueSymbol()) { + return true; + } + + var containerSymbol = importSymbol.getExportAssignedContainerSymbol(); + if (containerSymbol && containerSymbol.getInstanceSymbol()) { + return true; + } + } + } + + return false; + }; + + Emitter.prototype.emitImportDeclaration = function (importDeclAST) { + var isExternalModuleReference = importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */; + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); + var isExported = TypeScript.hasFlag(importDecl.flags, 1 /* Exported */); + var isAmdCodeGen = this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */; + + this.emitComments(importDeclAST, true); + + var importSymbol = importDecl.getSymbol(); + + var parentSymbol = importSymbol.getContainer(); + var parentKind = parentSymbol ? parentSymbol.kind : 0 /* None */; + var associatedParentSymbol = parentSymbol ? parentSymbol.getAssociatedContainerType() : null; + var associatedParentSymbolKind = associatedParentSymbol ? associatedParentSymbol.kind : 0 /* None */; + + var needsPropertyAssignment = false; + var usePropertyAssignmentInsteadOfVarDecl = false; + var moduleNamePrefix; + + if (isExported && (parentKind === 4 /* Container */ || parentKind === 32 /* DynamicModule */ || associatedParentSymbolKind === 4 /* Container */ || associatedParentSymbolKind === 32 /* DynamicModule */)) { + if (importSymbol.getExportAssignedTypeSymbol() || importSymbol.getExportAssignedContainerSymbol()) { + needsPropertyAssignment = true; + } else { + var valueSymbol = importSymbol.getExportAssignedValueSymbol(); + if (valueSymbol && (valueSymbol.kind === 65536 /* Method */ || valueSymbol.kind === 16384 /* Function */)) { + needsPropertyAssignment = true; + } else { + usePropertyAssignmentInsteadOfVarDecl = true; + } + } + + if (this.emitState.container === 2 /* DynamicModule */) { + moduleNamePrefix = "exports."; + } else { + moduleNamePrefix = this.moduleName + "."; + } + } + + if (isAmdCodeGen && isExternalModuleReference) { + needsPropertyAssignment = true; + } else { + this.recordSourceMappingStart(importDeclAST); + if (usePropertyAssignmentInsteadOfVarDecl) { + this.writeToOutput(moduleNamePrefix); + } else { + this.writeToOutput("var "); + } + this.writeToOutput(importDeclAST.identifier.text() + " = "); + var aliasAST = importDeclAST.moduleReference; + + if (isExternalModuleReference) { + this.writeToOutput("require(" + aliasAST.stringLiteral.text() + ")"); + } else { + this.emitJavascript(aliasAST.moduleName, false); + } + + this.recordSourceMappingEnd(importDeclAST); + this.writeToOutput(";"); + + if (needsPropertyAssignment) { + this.writeLineToOutput(""); + this.emitIndent(); + } + } + + if (needsPropertyAssignment) { + this.writeToOutputWithSourceMapRecord(moduleNamePrefix + importDeclAST.identifier.text() + " = " + importDeclAST.identifier.text(), importDeclAST); + this.writeToOutput(";"); + } + this.emitComments(importDeclAST, false); + }; + + Emitter.prototype.createSourceMapper = function (document, jsFileName, jsFile, sourceMapOut, resolvePath) { + this.sourceMapper = new TypeScript.SourceMapper(jsFile, sourceMapOut, document, jsFileName, this.emitOptions, resolvePath); + }; + + Emitter.prototype.setSourceMapperNewSourceFile = function (document) { + this.sourceMapper.setNewSourceFile(document, this.emitOptions); + }; + + Emitter.prototype.updateLineAndColumn = function (s) { + var lineNumbers = TypeScript.TextUtilities.parseLineStarts(s); + if (lineNumbers.length > 1) { + this.emitState.line += lineNumbers.length - 1; + this.emitState.column = s.length - lineNumbers[lineNumbers.length - 1]; + } else { + this.emitState.column += s.length; + } + }; + + Emitter.prototype.writeToOutputWithSourceMapRecord = function (s, astSpan) { + this.recordSourceMappingStart(astSpan); + this.writeToOutput(s); + this.recordSourceMappingEnd(astSpan); + }; + + Emitter.prototype.writeToOutput = function (s) { + this.outfile.Write(s); + this.updateLineAndColumn(s); + }; + + Emitter.prototype.writeLineToOutput = function (s, force) { + if (typeof force === "undefined") { force = false; } + if (!force && s === "" && this.emitState.column === 0) { + return; + } + + this.outfile.WriteLine(s); + this.updateLineAndColumn(s); + this.emitState.column = 0; + this.emitState.line++; + }; + + Emitter.prototype.writeCaptureThisStatement = function (ast) { + this.emitIndent(); + this.writeToOutputWithSourceMapRecord(this.captureThisStmtString, ast); + this.writeLineToOutput(""); + }; + + Emitter.prototype.setContainer = function (c) { + var temp = this.emitState.container; + this.emitState.container = c; + return temp; + }; + + Emitter.prototype.getIndentString = function () { + return this.indenter.getIndent(); + }; + + Emitter.prototype.emitIndent = function () { + this.writeToOutput(this.getIndentString()); + }; + + Emitter.prototype.emitComment = function (comment, trailing, first) { + if (this.emitOptions.compilationSettings().removeComments()) { + return; + } + + var text = getTrimmedTextLines(comment); + var emitColumn = this.emitState.column; + + if (emitColumn === 0) { + this.emitIndent(); + } else if (trailing && first) { + this.writeToOutput(" "); + } + + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + 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(""); + } else { + this.recordSourceMappingEnd(comment); + this.writeToOutput(" "); + return; + } + } else { + this.recordSourceMappingStart(comment); + this.writeToOutput(text[0]); + this.recordSourceMappingEnd(comment); + this.writeLineToOutput(""); + } + + if (!trailing && emitColumn !== 0) { + this.emitIndent(); + } + }; + + Emitter.prototype.emitComments = function (ast, pre, onlyPinnedOrTripleSlashComments) { + var _this = this; + if (typeof onlyPinnedOrTripleSlashComments === "undefined") { onlyPinnedOrTripleSlashComments = false; } + if (ast && ast.kind() !== 146 /* Block */) { + if (ast.parent.kind() === 219 /* SimpleArrowFunctionExpression */ || ast.parent.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { + return; + } + } + + if (pre) { + var preComments = ast.preComments(); + + if (preComments && ast === this.detachedCommentsElement) { + var detachedComments = this.getDetachedComments(ast); + preComments = preComments.slice(detachedComments.length); + this.detachedCommentsElement = null; + } + + if (preComments && onlyPinnedOrTripleSlashComments) { + preComments = TypeScript.ArrayUtilities.where(preComments, function (c) { + return _this.isPinnedOrTripleSlash(c); + }); + } + + this.emitCommentsArray(preComments, false); + } else { + this.emitCommentsArray(ast.postComments(), true); + } + }; + + Emitter.prototype.isPinnedOrTripleSlash = function (comment) { + var fullText = comment.fullText(); + if (fullText.match(TypeScript.tripleSlashReferenceRegExp)) { + return true; + } else { + return fullText.indexOf("/*!") === 0; + } + }; + + Emitter.prototype.emitCommentsArray = function (comments, trailing) { + if (!this.emitOptions.compilationSettings().removeComments() && comments) { + for (var i = 0, n = comments.length; i < n; i++) { + this.emitComment(comments[i], trailing, i === 0); + } + } + }; + + Emitter.prototype.emitObjectLiteralExpression = function (objectLiteral) { + this.recordSourceMappingStart(objectLiteral); + + this.writeToOutput("{"); + this.emitCommaSeparatedList(objectLiteral, objectLiteral.propertyAssignments, " ", true); + this.writeToOutput("}"); + + this.recordSourceMappingEnd(objectLiteral); + }; + + Emitter.prototype.emitArrayLiteralExpression = function (arrayLiteral) { + this.recordSourceMappingStart(arrayLiteral); + + this.writeToOutput("["); + this.emitCommaSeparatedList(arrayLiteral, arrayLiteral.expressions, "", true); + this.writeToOutput("]"); + + this.recordSourceMappingEnd(arrayLiteral); + }; + + Emitter.prototype.emitObjectCreationExpression = function (objectCreationExpression) { + this.recordSourceMappingStart(objectCreationExpression); + this.writeToOutput("new "); + var target = objectCreationExpression.expression; + + this.emit(target); + if (objectCreationExpression.argumentList) { + this.recordSourceMappingStart(objectCreationExpression.argumentList); + this.writeToOutput("("); + this.emitCommaSeparatedList(objectCreationExpression.argumentList, objectCreationExpression.argumentList.arguments, "", false); + this.writeToOutputWithSourceMapRecord(")", objectCreationExpression.argumentList.closeParenToken); + this.recordSourceMappingEnd(objectCreationExpression.argumentList); + } + + this.recordSourceMappingEnd(objectCreationExpression); + }; + + Emitter.prototype.getConstantDecl = function (dotExpr) { + var pullSymbol = this.semanticInfoChain.getSymbolForAST(dotExpr); + if (pullSymbol && pullSymbol.kind === 67108864 /* EnumMember */) { + var pullDecls = pullSymbol.getDeclarations(); + if (pullDecls.length === 1) { + var pullDecl = pullDecls[0]; + if (pullDecl.kind === 67108864 /* EnumMember */) { + return pullDecl; + } + } + } + + return null; + }; + + Emitter.prototype.tryEmitConstant = function (dotExpr) { + var propertyName = dotExpr.name; + var boundDecl = this.getConstantDecl(dotExpr); + if (boundDecl) { + var value = boundDecl.constantValue; + if (value !== null) { + this.recordSourceMappingStart(dotExpr); + this.writeToOutput(value.toString()); + var comment = " /* "; + comment += propertyName.text(); + comment += " */"; + this.writeToOutput(comment); + this.recordSourceMappingEnd(dotExpr); + return true; + } + } + + return false; + }; + + Emitter.prototype.emitInvocationExpression = function (callNode) { + this.recordSourceMappingStart(callNode); + var target = callNode.expression; + var args = callNode.argumentList.arguments; + + if (target.kind() === 212 /* MemberAccessExpression */ && target.expression.kind() === 50 /* SuperKeyword */) { + this.emit(target); + this.writeToOutput(".call"); + this.recordSourceMappingStart(args); + this.writeToOutput("("); + this.emitThis(); + if (args && args.nonSeparatorCount() > 0) { + this.writeToOutput(", "); + this.emitCommaSeparatedList(callNode.argumentList, args, "", false); + } + } else { + if (callNode.expression.kind() === 50 /* SuperKeyword */ && this.emitState.container === 4 /* Constructor */) { + this.writeToOutput("_super.call"); + } else { + this.emitJavascript(target, false); + } + this.recordSourceMappingStart(args); + this.writeToOutput("("); + if (callNode.expression.kind() === 50 /* SuperKeyword */ && this.emitState.container === 4 /* Constructor */) { + this.writeToOutput("this"); + if (args && args.nonSeparatorCount() > 0) { + this.writeToOutput(", "); + } + } + this.emitCommaSeparatedList(callNode.argumentList, args, "", false); + } + + this.writeToOutputWithSourceMapRecord(")", callNode.argumentList.closeParenToken); + this.recordSourceMappingEnd(args); + this.recordSourceMappingEnd(callNode); + }; + + Emitter.prototype.emitParameterList = function (list) { + this.writeToOutput("("); + this.emitCommentsArray(list.openParenTrailingComments, true); + this.emitFunctionParameters(TypeScript.ASTHelpers.parametersFromParameterList(list)); + this.writeToOutput(")"); + }; + + Emitter.prototype.emitFunctionParameters = function (parameters) { + var argsLen = 0; + + if (parameters) { + this.emitComments(parameters.ast, true); + + var tempContainer = this.setContainer(6 /* Args */); + argsLen = parameters.length; + var printLen = argsLen; + if (parameters.lastParameterIsRest()) { + printLen--; + } + for (var i = 0; i < printLen; i++) { + var arg = parameters.astAt(i); + this.emit(arg); + + if (i < (printLen - 1)) { + this.writeToOutput(", "); + } + } + this.setContainer(tempContainer); + + this.emitComments(parameters.ast, false); + } + }; + + Emitter.prototype.emitFunctionBodyStatements = function (name, funcDecl, parameterList, block, bodyExpression) { + this.writeLineToOutput(" {"); + if (name) { + this.recordSourceMappingNameStart(name); + } + + this.indenter.increaseIndent(); + + if (block) { + this.emitDetachedComments(block.statements); + } + + if (this.shouldCaptureThis(funcDecl)) { + this.writeCaptureThisStatement(funcDecl); + } + + if (parameterList) { + this.emitDefaultValueAssignments(parameterList); + this.emitRestParameterInitializer(parameterList); + } + + if (block) { + this.emitList(block.statements); + this.emitCommentsArray(block.closeBraceLeadingComments, false); + } else { + this.emitIndent(); + this.emitCommentsArray(bodyExpression.preComments(), false); + this.writeToOutput("return "); + this.emit(bodyExpression); + this.writeLineToOutput(";"); + this.emitCommentsArray(bodyExpression.postComments(), true); + } + + this.indenter.decreaseIndent(); + this.emitIndent(); + + if (block) { + this.writeToOutputWithSourceMapRecord("}", block.closeBraceToken); + } else { + this.writeToOutputWithSourceMapRecord("}", bodyExpression); + } + + if (name) { + this.recordSourceMappingNameEnd(); + } + }; + + Emitter.prototype.emitDefaultValueAssignments = function (parameters) { + var n = parameters.length; + if (parameters.lastParameterIsRest()) { + n--; + } + + for (var i = 0; i < n; i++) { + var arg = parameters.astAt(i); + var id = parameters.identifierAt(i); + var equalsValueClause = parameters.initializerAt(i); + if (equalsValueClause) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.writeToOutput("if (typeof " + id.text() + " === \"undefined\") { "); + this.writeToOutputWithSourceMapRecord(id.text(), id); + this.emitJavascript(equalsValueClause, false); + this.writeLineToOutput("; }"); + this.recordSourceMappingEnd(arg); + } + } + }; + + Emitter.prototype.emitRestParameterInitializer = function (parameters) { + if (parameters.lastParameterIsRest()) { + var n = parameters.length; + var lastArg = parameters.astAt(n - 1); + var id = parameters.identifierAt(n - 1); + this.emitIndent(); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var "); + this.writeToOutputWithSourceMapRecord(id.text(), id); + this.writeLineToOutput(" = [];"); + this.recordSourceMappingEnd(lastArg); + this.emitIndent(); + this.writeToOutput("for ("); + this.writeToOutputWithSourceMapRecord("var _i = 0;", lastArg); + this.writeToOutput(" "); + this.writeToOutputWithSourceMapRecord("_i < (arguments.length - " + (n - 1) + ")", lastArg); + this.writeToOutput("; "); + this.writeToOutputWithSourceMapRecord("_i++", lastArg); + this.writeLineToOutput(") {"); + this.indenter.increaseIndent(); + this.emitIndent(); + + this.writeToOutputWithSourceMapRecord(id.text() + "[_i] = arguments[_i + " + (n - 1) + "];", lastArg); + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + } + }; + + Emitter.prototype.getImportDecls = function (fileName) { + var topLevelDecl = this.semanticInfoChain.topLevelDecl(this.document.fileName); + var result = []; + + var dynamicModuleDecl = topLevelDecl.getChildDecls()[0]; + var queue = dynamicModuleDecl.getChildDecls(); + + for (var i = 0, n = queue.length; i < n; i++) { + var decl = queue[i]; + + if (decl.kind & 128 /* TypeAlias */) { + var importStatementAST = this.semanticInfoChain.getASTForDecl(decl); + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + var symbol = decl.getSymbol(); + var typeSymbol = symbol && symbol.type; + if (typeSymbol && typeSymbol !== this.semanticInfoChain.anyTypeSymbol && !typeSymbol.isError()) { + result.push(decl); + } + } + } + } + + return result; + }; + + Emitter.prototype.getModuleImportAndDependencyList = function (sourceUnit) { + var importList = ""; + var dependencyList = ""; + + var importDecls = this.getImportDecls(this.document.fileName); + + if (importDecls.length) { + for (var i = 0; i < importDecls.length; i++) { + var importStatementDecl = importDecls[i]; + var importStatementSymbol = importStatementDecl.getSymbol(); + var importStatementAST = this.semanticInfoChain.getASTForDecl(importStatementDecl); + + if (importStatementSymbol.isUsedAsValue()) { + if (i <= importDecls.length - 1) { + dependencyList += ", "; + importList += ", "; + } + + importList += importStatementDecl.name; + dependencyList += importStatementAST.moduleReference.stringLiteral.text(); + } + } + } + + var amdDependencies = this.document.amdDependencies(); + for (var i = 0; i < amdDependencies.length; i++) { + dependencyList += ", \"" + amdDependencies[i] + "\""; + } + + return { + importList: importList, + dependencyList: dependencyList + }; + }; + + Emitter.prototype.shouldCaptureThis = function (ast) { + if (ast.kind() === 120 /* SourceUnit */) { + var scriptDecl = this.semanticInfoChain.topLevelDecl(this.document.fileName); + return TypeScript.hasFlag(scriptDecl.flags, 262144 /* MustCaptureThis */); + } + + var decl = this.semanticInfoChain.getDeclForAST(ast); + if (decl) { + return TypeScript.hasFlag(decl.flags, 262144 /* MustCaptureThis */); + } + + return false; + }; + + Emitter.prototype.emitEnum = function (moduleDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(moduleDecl); + this.pushDecl(pullDecl); + + var svModuleName = this.moduleName; + this.moduleName = moduleDecl.identifier.text(); + + var temp = this.setContainer(1 /* Module */); + var isExported = TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */); + + if (!isExported) { + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("var "); + this.recordSourceMappingStart(moduleDecl.identifier); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.identifier); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(moduleDecl); + this.emitIndent(); + } + + this.writeToOutput("("); + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("function ("); + this.writeToOutputWithSourceMapRecord(this.moduleName, moduleDecl.identifier); + this.writeLineToOutput(") {"); + + this.recordSourceMappingNameStart(this.moduleName); + + this.indenter.increaseIndent(); + + if (this.shouldCaptureThis(moduleDecl)) { + this.writeCaptureThisStatement(moduleDecl); + } + + this.emitSeparatedList(moduleDecl.enumElements); + this.indenter.decreaseIndent(); + this.emitIndent(); + + var parentIsDynamic = temp === 2 /* DynamicModule */; + if (temp === 0 /* Prog */ && isExported) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); + } else if (isExported || temp === 0 /* Prog */) { + var dotMod = svModuleName !== "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); + } else if (!isExported && temp !== 0 /* Prog */) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); + } else { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.writeToOutput(")();"); + } + + this.recordSourceMappingEnd(moduleDecl); + if (temp !== 0 /* Prog */ && isExported) { + this.recordSourceMappingStart(moduleDecl); + if (parentIsDynamic) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); + } else { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); + } + this.recordSourceMappingEnd(moduleDecl); + } + + this.setContainer(temp); + this.moduleName = svModuleName; + + this.popDecl(pullDecl); + }; + + Emitter.prototype.getModuleDeclToVerifyChildNameCollision = function (moduleDecl, changeNameIfAnyDeclarationInContext) { + if (TypeScript.ArrayUtilities.contains(this.declStack, moduleDecl)) { + return moduleDecl; + } else if (changeNameIfAnyDeclarationInContext) { + var symbol = moduleDecl.getSymbol(); + if (symbol) { + var otherDecls = symbol.getDeclarations(); + for (var i = 0; i < otherDecls.length; i++) { + if (TypeScript.ArrayUtilities.contains(this.declStack, otherDecls[i])) { + return otherDecls[i]; + } + } + } + } + + return null; + }; + + Emitter.prototype.hasChildNameCollision = function (moduleName, parentDecl) { + var _this = this; + var childDecls = parentDecl.getChildDecls(); + return TypeScript.ArrayUtilities.any(childDecls, function (childDecl) { + var childAST = _this.semanticInfoChain.getASTForDecl(childDecl); + + if (childDecl.kind != 67108864 /* EnumMember */ && _this.shouldEmit(childAST)) { + if (childDecl.name === moduleName) { + if (parentDecl.kind != 8 /* Class */) { + return true; + } + + if (!(childDecl.kind == 65536 /* Method */ || childDecl.kind == 4096 /* Property */ || childDecl.kind == 524288 /* SetAccessor */ || childDecl.kind == 262144 /* GetAccessor */)) { + return true; + } + } + + if (_this.hasChildNameCollision(moduleName, childDecl)) { + return true; + } + } + return false; + }); + }; + + Emitter.prototype.getModuleName = function (moduleDecl, changeNameIfAnyDeclarationInContext) { + var moduleName = moduleDecl.name; + var moduleDisplayName = moduleDecl.getDisplayName(); + + moduleDecl = this.getModuleDeclToVerifyChildNameCollision(moduleDecl, changeNameIfAnyDeclarationInContext); + if (moduleDecl && moduleDecl.kind != 64 /* Enum */) { + while (this.hasChildNameCollision(moduleName, moduleDecl)) { + moduleName = "_" + moduleName; + moduleDisplayName = "_" + moduleDisplayName; + } + } + + return moduleDisplayName; + }; + + Emitter.prototype.emitModuleDeclarationWorker = function (moduleDecl) { + if (moduleDecl.stringLiteral) { + this.emitSingleModuleDeclaration(moduleDecl, moduleDecl.stringLiteral); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDecl.name); + this.emitSingleModuleDeclaration(moduleDecl, moduleNames[0]); + } + }; + + Emitter.prototype.emitSingleModuleDeclaration = function (moduleDecl, moduleName) { + var isLastName = TypeScript.ASTHelpers.isLastNameOfModule(moduleDecl, moduleName); + + if (isLastName) { + this.emitComments(moduleDecl, true); + } + + var pullDecl = this.semanticInfoChain.getDeclForAST(moduleName); + this.pushDecl(pullDecl); + + var svModuleName = this.moduleName; + + if (moduleDecl.stringLiteral) { + this.moduleName = moduleDecl.stringLiteral.valueText(); + if (TypeScript.isTSFile(this.moduleName)) { + this.moduleName = this.moduleName.substring(0, this.moduleName.length - ".ts".length); + } + } else { + this.moduleName = moduleName.text(); + } + + var temp = this.setContainer(1 /* Module */); + var isExported = TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */); + + if (!isExported) { + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("var "); + this.recordSourceMappingStart(moduleName); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleName); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(moduleDecl); + this.emitIndent(); + } + + this.writeToOutput("("); + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("function ("); + + this.moduleName = this.getModuleName(pullDecl); + this.writeToOutputWithSourceMapRecord(this.moduleName, moduleName); + this.writeLineToOutput(") {"); + + this.recordSourceMappingNameStart(moduleName.text()); + + this.indenter.increaseIndent(); + + if (this.shouldCaptureThis(moduleDecl)) { + this.writeCaptureThisStatement(moduleDecl); + } + + if (moduleName === moduleDecl.stringLiteral) { + this.emitList(moduleDecl.moduleElements); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDecl.name); + var nameIndex = moduleNames.indexOf(moduleName); + TypeScript.Debug.assert(nameIndex >= 0); + + if (isLastName) { + this.emitList(moduleDecl.moduleElements); + } else { + this.emitIndent(); + this.emitSingleModuleDeclaration(moduleDecl, moduleNames[nameIndex + 1]); + this.writeLineToOutput(""); + } + } + + this.moduleName = moduleName.text(); + this.indenter.decreaseIndent(); + this.emitIndent(); + + var parentIsDynamic = temp === 2 /* DynamicModule */; + this.recordSourceMappingStart(moduleDecl.endingToken); + if (temp === 0 /* Prog */ && isExported) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); + } else if (isExported || temp === 0 /* Prog */) { + var dotMod = svModuleName !== "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); + } else if (!isExported && temp !== 0 /* Prog */) { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); + } else { + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")();"); + } + + this.recordSourceMappingEnd(moduleDecl); + if (temp !== 0 /* Prog */ && isExported) { + this.recordSourceMappingStart(moduleDecl); + if (parentIsDynamic) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); + } else { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); + } + this.recordSourceMappingEnd(moduleDecl); + } + + this.setContainer(temp); + this.moduleName = svModuleName; + + this.popDecl(pullDecl); + + if (isLastName) { + this.emitComments(moduleDecl, false); + } + }; + + Emitter.prototype.emitEnumElement = function (varDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(varDecl); + TypeScript.Debug.assert(pullDecl && pullDecl.kind === 67108864 /* EnumMember */); + + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + var name = varDecl.propertyName.text(); + var quoted = TypeScript.isQuoted(name); + this.writeToOutput(this.moduleName); + this.writeToOutput('['); + this.writeToOutput(this.moduleName); + this.writeToOutput('['); + this.writeToOutput(quoted ? name : '"' + name + '"'); + this.writeToOutput(']'); + + if (varDecl.equalsValueClause) { + this.emit(varDecl.equalsValueClause); + } else if (pullDecl.constantValue !== null) { + this.writeToOutput(' = '); + this.writeToOutput(pullDecl.constantValue.toString()); + } else { + this.writeToOutput(' = null'); + } + + this.writeToOutput('] = '); + this.writeToOutput(quoted ? name : '"' + name + '"'); + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + this.writeToOutput(';'); + }; + + Emitter.prototype.emitElementAccessExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.emit(expression.expression); + this.writeToOutput("["); + this.emit(expression.argumentExpression); + this.writeToOutput("]"); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitSimpleArrowFunctionExpression = function (arrowFunction) { + this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromIdentifier(arrowFunction.identifier), arrowFunction.block, arrowFunction.expression); + }; + + Emitter.prototype.emitParenthesizedArrowFunctionExpression = function (arrowFunction) { + this.emitAnyArrowFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), arrowFunction.block, arrowFunction.expression); + }; + + Emitter.prototype.emitAnyArrowFunctionExpression = function (arrowFunction, funcName, parameters, block, expression) { + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = true; + + var temp = this.setContainer(5 /* Function */); + + this.recordSourceMappingStart(arrowFunction); + + var pullDecl = this.semanticInfoChain.getDeclForAST(arrowFunction); + this.pushDecl(pullDecl); + + this.emitComments(arrowFunction, true); + + this.recordSourceMappingStart(arrowFunction); + this.writeToOutput("function "); + this.writeToOutput("("); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(funcName, arrowFunction, parameters, block, expression); + + this.recordSourceMappingEnd(arrowFunction); + + this.recordSourceMappingEnd(arrowFunction); + + this.emitComments(arrowFunction, false); + + this.popDecl(pullDecl); + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + }; + + Emitter.prototype.emitConstructor = function (funcDecl) { + if (!funcDecl.block) { + return; + } + var temp = this.setContainer(4 /* Constructor */); + + this.recordSourceMappingStart(funcDecl); + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.emitComments(funcDecl, true); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + this.writeToOutput(this.thisClassNode.identifier.text()); + this.writeToOutput("("); + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionParameters(parameters); + this.writeLineToOutput(") {"); + + this.recordSourceMappingNameStart("constructor"); + this.indenter.increaseIndent(); + + this.emitDefaultValueAssignments(parameters); + this.emitRestParameterInitializer(parameters); + + if (this.shouldCaptureThis(funcDecl)) { + this.writeCaptureThisStatement(funcDecl); + } + + this.emitConstructorStatements(funcDecl); + this.emitCommentsArray(funcDecl.block.closeBraceLeadingComments, false); + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("}", funcDecl.block.closeBraceToken); + + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.popDecl(pullDecl); + this.setContainer(temp); + }; + + Emitter.prototype.emitGetAccessor = function (accessor) { + this.recordSourceMappingStart(accessor); + this.writeToOutput("get "); + + var temp = this.setContainer(5 /* Function */); + + this.recordSourceMappingStart(accessor); + + var pullDecl = this.semanticInfoChain.getDeclForAST(accessor); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(accessor); + + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(accessor, this.semanticInfoChain); + var container = accessorSymbol.getContainer(); + var containerKind = container.kind; + + this.recordSourceMappingNameStart(accessor.propertyName.text()); + this.writeToOutput(accessor.propertyName.text()); + this.writeToOutput("("); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(null, accessor, TypeScript.ASTHelpers.parametersFromParameterList(accessor.parameterList), accessor.block, null); + + this.recordSourceMappingEnd(accessor); + + this.recordSourceMappingEnd(accessor); + + this.popDecl(pullDecl); + this.setContainer(temp); + this.recordSourceMappingEnd(accessor); + }; + + Emitter.prototype.emitSetAccessor = function (accessor) { + this.recordSourceMappingStart(accessor); + this.writeToOutput("set "); + + var temp = this.setContainer(5 /* Function */); + + this.recordSourceMappingStart(accessor); + + var pullDecl = this.semanticInfoChain.getDeclForAST(accessor); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(accessor); + + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(accessor, this.semanticInfoChain); + var container = accessorSymbol.getContainer(); + var containerKind = container.kind; + + this.recordSourceMappingNameStart(accessor.propertyName.text()); + this.writeToOutput(accessor.propertyName.text()); + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(accessor.parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(null, accessor, parameters, accessor.block, null); + + this.recordSourceMappingEnd(accessor); + + this.recordSourceMappingEnd(accessor); + + this.popDecl(pullDecl); + this.setContainer(temp); + this.recordSourceMappingEnd(accessor); + }; + + Emitter.prototype.emitFunctionExpression = function (funcDecl) { + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = false; + + var temp = this.setContainer(5 /* Function */); + + var funcName = funcDecl.identifier ? funcDecl.identifier.text() : null; + + this.recordSourceMappingStart(funcDecl); + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + if (funcDecl.identifier) { + this.recordSourceMappingStart(funcDecl.identifier); + this.writeToOutput(funcDecl.identifier.text()); + this.recordSourceMappingEnd(funcDecl.identifier); + } + + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(funcName, funcDecl, parameters, funcDecl.block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.popDecl(pullDecl); + + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + }; + + Emitter.prototype.emitFunction = function (funcDecl) { + if (funcDecl.block === null) { + return; + } + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = false; + + var temp = this.setContainer(5 /* Function */); + + var funcName = funcDecl.identifier.text(); + + this.recordSourceMappingStart(funcDecl); + + var printName = funcDecl.identifier !== null; + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.emitComments(funcDecl, true); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + if (printName) { + var id = funcDecl.identifier.text(); + if (id) { + if (funcDecl.identifier) { + this.recordSourceMappingStart(funcDecl.identifier); + } + this.writeToOutput(id); + if (funcDecl.identifier) { + this.recordSourceMappingEnd(funcDecl.identifier); + } + } + } + + this.emitParameterList(funcDecl.callSignature.parameterList); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionBodyStatements(funcDecl.identifier.text(), funcDecl, parameters, funcDecl.block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.popDecl(pullDecl); + + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + + if (funcDecl.block) { + var pullFunctionDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + if ((this.emitState.container === 1 /* Module */ || this.emitState.container === 2 /* DynamicModule */) && pullFunctionDecl && TypeScript.hasFlag(pullFunctionDecl.flags, 1 /* Exported */)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = this.emitState.container === 1 /* Module */ ? this.moduleName : "exports"; + this.recordSourceMappingStart(funcDecl); + this.writeToOutput(modName + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + }; + + Emitter.prototype.emitAmbientVarDecl = function (varDecl) { + this.recordSourceMappingStart(this.currentVariableDeclaration); + if (varDecl.equalsValueClause) { + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + this.writeToOutputWithSourceMapRecord(varDecl.propertyName.text(), varDecl.propertyName); + this.emitJavascript(varDecl.equalsValueClause, false); + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + } + }; + + Emitter.prototype.emitVarDeclVar = function () { + if (this.currentVariableDeclaration) { + this.writeToOutput("var "); + } + }; + + Emitter.prototype.emitVariableDeclaration = function (declaration) { + var varDecl = declaration.declarators.nonSeparatorAt(0); + + var symbol = this.semanticInfoChain.getSymbolForAST(varDecl); + + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentKind = parentSymbol ? parentSymbol.kind : 0 /* None */; + + this.emitComments(declaration, true); + + var pullVarDecl = this.semanticInfoChain.getDeclForAST(varDecl); + var isAmbientWithoutInit = pullVarDecl && TypeScript.hasFlag(pullVarDecl.flags, 8 /* Ambient */) && varDecl.equalsValueClause === null; + if (!isAmbientWithoutInit) { + var prevVariableDeclaration = this.currentVariableDeclaration; + this.currentVariableDeclaration = declaration; + + for (var i = 0, n = declaration.declarators.nonSeparatorCount(); i < n; i++) { + var declarator = declaration.declarators.nonSeparatorAt(i); + + if (i > 0) { + this.writeToOutput(", "); + } + + this.emit(declarator); + } + this.currentVariableDeclaration = prevVariableDeclaration; + + this.recordSourceMappingEnd(declaration); + } + + this.emitComments(declaration, false); + }; + + Emitter.prototype.emitMemberVariableDeclaration = function (varDecl) { + TypeScript.Debug.assert(!TypeScript.hasModifier(varDecl.modifiers, 16 /* Static */) && varDecl.variableDeclarator.equalsValueClause); + + var pullDecl = this.semanticInfoChain.getDeclForAST(varDecl); + this.pushDecl(pullDecl); + + this.emitComments(varDecl, true); + this.recordSourceMappingStart(varDecl); + + var varDeclName = varDecl.variableDeclarator.propertyName.text(); + var quotedOrNumber = TypeScript.isQuoted(varDeclName) || varDecl.variableDeclarator.propertyName.kind() !== 11 /* IdentifierName */; + + var symbol = this.semanticInfoChain.getSymbolForAST(varDecl); + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentDecl = pullDecl && pullDecl.getParentDecl(); + + if (quotedOrNumber) { + this.writeToOutput("this["); + } else { + this.writeToOutput("this."); + } + + this.writeToOutputWithSourceMapRecord(varDecl.variableDeclarator.propertyName.text(), varDecl.variableDeclarator.propertyName); + + if (quotedOrNumber) { + this.writeToOutput("]"); + } + + if (varDecl.variableDeclarator.equalsValueClause) { + var prevVariableDeclaration = this.currentVariableDeclaration; + this.emit(varDecl.variableDeclarator.equalsValueClause); + this.currentVariableDeclaration = prevVariableDeclaration; + } + + if (this.emitState.container !== 6 /* Args */) { + this.writeToOutput(";"); + } + + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitVariableDeclarator = function (varDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(varDecl); + this.pushDecl(pullDecl); + if (pullDecl && (pullDecl.flags & 8 /* Ambient */) === 8 /* Ambient */) { + this.emitAmbientVarDecl(varDecl); + } else { + this.emitComments(varDecl, true); + this.recordSourceMappingStart(this.currentVariableDeclaration); + this.recordSourceMappingStart(varDecl); + + var varDeclName = varDecl.propertyName.text(); + + var symbol = this.semanticInfoChain.getSymbolForAST(varDecl); + var parentSymbol = symbol ? symbol.getContainer() : null; + var parentDecl = pullDecl && pullDecl.getParentDecl(); + var parentIsModule = parentDecl && (parentDecl.flags & 102400 /* SomeInitializedModule */); + + if (parentIsModule) { + if (!TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */)) { + this.emitVarDeclVar(); + } else { + if (this.emitState.container === 2 /* DynamicModule */) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(this.moduleName + "."); + } + } + } else { + this.emitVarDeclVar(); + } + + this.writeToOutputWithSourceMapRecord(varDecl.propertyName.text(), varDecl.propertyName); + + if (varDecl.equalsValueClause) { + var prevVariableDeclaration = this.currentVariableDeclaration; + this.emit(varDecl.equalsValueClause); + this.currentVariableDeclaration = prevVariableDeclaration; + } + + this.recordSourceMappingEnd(varDecl); + this.emitComments(varDecl, false); + } + this.currentVariableDeclaration = undefined; + this.popDecl(pullDecl); + }; + + Emitter.prototype.symbolIsUsedInItsEnclosingContainer = function (symbol, dynamic) { + if (typeof dynamic === "undefined") { dynamic = false; } + var symDecls = symbol.getDeclarations(); + + if (symDecls.length) { + var enclosingDecl = this.getEnclosingDecl(); + if (enclosingDecl) { + var parentDecl = symDecls[0].getParentDecl(); + if (parentDecl) { + var symbolDeclarationEnclosingContainer = parentDecl; + var enclosingContainer = enclosingDecl; + + while (symbolDeclarationEnclosingContainer) { + if (symbolDeclarationEnclosingContainer.kind === (dynamic ? 32 /* DynamicModule */ : 4 /* Container */)) { + break; + } + symbolDeclarationEnclosingContainer = symbolDeclarationEnclosingContainer.getParentDecl(); + } + + if (symbolDeclarationEnclosingContainer) { + while (enclosingContainer) { + if (enclosingContainer.kind === (dynamic ? 32 /* DynamicModule */ : 4 /* Container */)) { + break; + } + + enclosingContainer = enclosingContainer.getParentDecl(); + } + } + + if (symbolDeclarationEnclosingContainer && enclosingContainer) { + var same = symbolDeclarationEnclosingContainer === enclosingContainer; + + if (!same && symbol.anyDeclHasFlag(32768 /* InitializedModule */)) { + same = symbolDeclarationEnclosingContainer === enclosingContainer.getParentDecl(); + } + + return same; + } + } + } + } + + return false; + }; + + Emitter.prototype.shouldQualifySymbolNameWithParentName = function (symbol) { + var enclosingContextDeclPath = this.declStack; + var symbolDeclarations = symbol.getDeclarations(); + for (var i = 0; i < symbolDeclarations.length; i++) { + var currentDecl = symbolDeclarations[i]; + var declParent = currentDecl.getParentDecl(); + + if (currentDecl.kind === 67108864 /* EnumMember */) { + return true; + } + + if (!TypeScript.hasFlag(currentDecl.flags, 1 /* Exported */)) { + return false; + } + + if (currentDecl.kind === 512 /* Variable */ && !TypeScript.hasFlag(currentDecl.flags, 118784 /* ImplicitVariable */)) { + return true; + } + + if (TypeScript.ArrayUtilities.contains(this.declStack, declParent)) { + return false; + } + } + + return true; + }; + + Emitter.prototype.getSymbolForEmit = function (ast) { + var pullSymbol = this.semanticInfoChain.getSymbolForAST(ast); + var pullSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(ast); + if (pullSymbol && pullSymbolAlias) { + var symbolToCompare = TypeScript.isTypesOnlyLocation(ast) ? pullSymbolAlias.getExportAssignedTypeSymbol() : pullSymbolAlias.getExportAssignedValueSymbol(); + + if (pullSymbol === symbolToCompare) { + pullSymbol = pullSymbolAlias; + pullSymbolAlias = null; + } + } + return { symbol: pullSymbol, aliasSymbol: pullSymbolAlias }; + }; + + Emitter.prototype.emitName = function (name, addThis) { + this.emitComments(name, true); + this.recordSourceMappingStart(name); + if (name.text().length > 0) { + var symbolForEmit = this.getSymbolForEmit(name); + var pullSymbol = symbolForEmit.symbol; + if (!pullSymbol) { + pullSymbol = this.semanticInfoChain.anyTypeSymbol; + } + var pullSymbolAlias = symbolForEmit.aliasSymbol; + var pullSymbolKind = pullSymbol.kind; + var isLocalAlias = pullSymbolAlias && (pullSymbolAlias.getDeclarations()[0].getParentDecl() === this.getEnclosingDecl()); + if (addThis && (this.emitState.container !== 6 /* Args */) && pullSymbol) { + var pullSymbolContainer = pullSymbol.getContainer(); + + if (pullSymbolContainer) { + var pullSymbolContainerKind = pullSymbolContainer.kind; + + if (TypeScript.PullHelpers.symbolIsModule(pullSymbolContainer) || pullSymbolContainerKind === 64 /* Enum */ || pullSymbolContainer.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */)) { + var needToEmitParentName = this.shouldQualifySymbolNameWithParentName(pullSymbol); + if (needToEmitParentName) { + var parentDecl = pullSymbol.getDeclarations()[0].getParentDecl(); + TypeScript.Debug.assert(parentDecl && !parentDecl.isRootDecl()); + this.writeToOutput(this.getModuleName(parentDecl, true) + "."); + } + } else if (pullSymbolContainerKind === 32 /* DynamicModule */ || pullSymbolContainer.anyDeclHasFlag(65536 /* InitializedDynamicModule */)) { + if (pullSymbolKind === 4096 /* Property */) { + this.writeToOutput("exports."); + } else if (pullSymbol.anyDeclHasFlag(1 /* Exported */) && !isLocalAlias && !pullSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */) && pullSymbol.kind !== 32768 /* ConstructorMethod */ && pullSymbol.kind !== 8 /* Class */ && pullSymbol.kind !== 64 /* Enum */) { + this.writeToOutput("exports."); + } + } + } + } + + this.writeToOutput(name.text()); + } + + this.recordSourceMappingEnd(name); + this.emitComments(name, false); + }; + + Emitter.prototype.recordSourceMappingNameStart = function (name) { + if (this.sourceMapper) { + var nameIndex = -1; + if (name) { + if (this.sourceMapper.currentNameIndex.length > 0) { + var parentNameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; + if (parentNameIndex !== -1) { + name = this.sourceMapper.names[parentNameIndex] + "." + name; + } + } + + var nameIndex = this.sourceMapper.names.length - 1; + for (nameIndex; nameIndex >= 0; nameIndex--) { + if (this.sourceMapper.names[nameIndex] === name) { + break; + } + } + + if (nameIndex === -1) { + nameIndex = this.sourceMapper.names.length; + this.sourceMapper.names.push(name); + } + } + this.sourceMapper.currentNameIndex.push(nameIndex); + } + }; + + Emitter.prototype.recordSourceMappingNameEnd = function () { + if (this.sourceMapper) { + this.sourceMapper.currentNameIndex.pop(); + } + }; + + Emitter.prototype.recordSourceMappingStart = function (ast) { + if (this.sourceMapper && TypeScript.ASTHelpers.isValidAstNode(ast)) { + var lineCol = { line: -1, character: -1 }; + var sourceMapping = new TypeScript.SourceMapping(); + sourceMapping.start.emittedColumn = this.emitState.column; + sourceMapping.start.emittedLine = this.emitState.line; + + var lineMap = this.document.lineMap(); + lineMap.fillLineAndCharacterFromPosition(ast.start(), lineCol); + sourceMapping.start.sourceColumn = lineCol.character; + sourceMapping.start.sourceLine = lineCol.line + 1; + lineMap.fillLineAndCharacterFromPosition(ast.end(), lineCol); + sourceMapping.end.sourceColumn = lineCol.character; + sourceMapping.end.sourceLine = lineCol.line + 1; + + TypeScript.Debug.assert(!isNaN(sourceMapping.start.emittedColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.start.emittedLine)); + TypeScript.Debug.assert(!isNaN(sourceMapping.start.sourceColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.start.sourceLine)); + TypeScript.Debug.assert(!isNaN(sourceMapping.end.sourceColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.end.sourceLine)); + + 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); + this.sourceMapper.increaseMappingLevel(ast); + } + }; + + Emitter.prototype.recordSourceMappingEnd = function (ast) { + if (this.sourceMapper && TypeScript.ASTHelpers.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; + + TypeScript.Debug.assert(!isNaN(sourceMapping.end.emittedColumn)); + TypeScript.Debug.assert(!isNaN(sourceMapping.end.emittedLine)); + + this.sourceMapper.decreaseMappingLevel(ast); + } + }; + + Emitter.prototype.getOutputFiles = function () { + var result = []; + if (this.sourceMapper !== null) { + this.sourceMapper.emitSourceMapping(); + result.push(this.sourceMapper.getOutputFile()); + } + + result.push(this.outfile.getOutputFile()); + return result; + }; + + Emitter.prototype.emitParameterPropertyAndMemberVariableAssignments = function () { + var constructorDecl = getLastConstructor(this.thisClassNode); + + if (constructorDecl) { + for (var i = 0, n = constructorDecl.callSignature.parameterList.parameters.nonSeparatorCount(); i < n; i++) { + var parameter = constructorDecl.callSignature.parameterList.parameters.nonSeparatorAt(i); + var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter); + if (TypeScript.hasFlag(parameterDecl.flags, 8388608 /* PropertyParameter */)) { + this.emitIndent(); + this.recordSourceMappingStart(parameter); + this.writeToOutputWithSourceMapRecord("this." + parameter.identifier.text(), parameter.identifier); + this.writeToOutput(" = "); + this.writeToOutputWithSourceMapRecord(parameter.identifier.text(), parameter.identifier); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(parameter); + } + } + } + + for (var i = 0, n = this.thisClassNode.classElements.childCount(); i < n; i++) { + if (this.thisClassNode.classElements.childAt(i).kind() === 136 /* MemberVariableDeclaration */) { + var varDecl = this.thisClassNode.classElements.childAt(i); + if (!TypeScript.hasModifier(varDecl.modifiers, 16 /* Static */) && varDecl.variableDeclarator.equalsValueClause) { + this.emitIndent(); + this.emitMemberVariableDeclaration(varDecl); + this.writeLineToOutput(""); + } + } + } + }; + + Emitter.prototype.isOnSameLine = function (pos1, pos2) { + var lineMap = this.document.lineMap(); + return lineMap.getLineNumberFromPosition(pos1) === lineMap.getLineNumberFromPosition(pos2); + }; + + Emitter.prototype.emitCommaSeparatedList = function (parent, list, buffer, preserveNewLines) { + if (list === null || list.nonSeparatorCount() === 0) { + return; + } + + var startLine = preserveNewLines && !this.isOnSameLine(parent.end(), list.nonSeparatorAt(0).end()); + + if (preserveNewLines) { + this.indenter.increaseIndent(); + } + + if (startLine) { + this.writeLineToOutput(""); + } else { + this.writeToOutput(buffer); + } + + for (var i = 0, n = list.nonSeparatorCount(); i < n; i++) { + var emitNode = list.nonSeparatorAt(i); + + this.emitJavascript(emitNode, startLine); + + if (i < (n - 1)) { + startLine = preserveNewLines && !this.isOnSameLine(emitNode.end(), list.nonSeparatorAt(i + 1).start()); + if (startLine) { + this.writeLineToOutput(","); + } else { + this.writeToOutput(", "); + } + } + } + + if (preserveNewLines) { + this.indenter.decreaseIndent(); + } + + if (preserveNewLines && !this.isOnSameLine(parent.end(), list.nonSeparatorAt(list.nonSeparatorCount() - 1).end())) { + this.writeLineToOutput(""); + this.emitIndent(); + } else { + this.writeToOutput(buffer); + } + }; + + Emitter.prototype.emitList = function (list, useNewLineSeparator, startInclusive, endExclusive) { + if (typeof useNewLineSeparator === "undefined") { useNewLineSeparator = true; } + if (typeof startInclusive === "undefined") { startInclusive = 0; } + if (typeof endExclusive === "undefined") { endExclusive = list.childCount(); } + if (list === null) { + return; + } + + this.emitComments(list, true); + var lastEmittedNode = null; + + for (var i = startInclusive; i < endExclusive; i++) { + var node = list.childAt(i); + + if (this.shouldEmit(node)) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + if (useNewLineSeparator) { + this.writeLineToOutput(""); + } + + lastEmittedNode = node; + } + } + + this.emitComments(list, false); + }; + + Emitter.prototype.emitSeparatedList = function (list, useNewLineSeparator, startInclusive, endExclusive) { + if (typeof useNewLineSeparator === "undefined") { useNewLineSeparator = true; } + if (typeof startInclusive === "undefined") { startInclusive = 0; } + if (typeof endExclusive === "undefined") { endExclusive = list.nonSeparatorCount(); } + if (list === null) { + return; + } + + this.emitComments(list, true); + var lastEmittedNode = null; + + for (var i = startInclusive; i < endExclusive; i++) { + var node = list.nonSeparatorAt(i); + + if (this.shouldEmit(node)) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + if (useNewLineSeparator) { + this.writeLineToOutput(""); + } + + lastEmittedNode = node; + } + } + + this.emitComments(list, false); + }; + + Emitter.prototype.isDirectivePrologueElement = function (node) { + if (node.kind() === 149 /* ExpressionStatement */) { + var exprStatement = node; + return exprStatement.expression.kind() === 14 /* StringLiteral */; + } + + return false; + }; + + Emitter.prototype.emitSpaceBetweenConstructs = function (node1, node2) { + if (node1 === null || node2 === null) { + return; + } + + if (node1.start() === -1 || node1.end() === -1 || node2.start() === -1 || node2.end() === -1) { + return; + } + + var lineMap = this.document.lineMap(); + var node1EndLine = lineMap.getLineNumberFromPosition(node1.end()); + var node2StartLine = lineMap.getLineNumberFromPosition(node2.start()); + + if ((node2StartLine - node1EndLine) > 1) { + this.writeLineToOutput("", true); + } + }; + + Emitter.prototype.getDetachedComments = function (element) { + var preComments = element.preComments(); + if (preComments) { + var lineMap = this.document.lineMap(); + + var detachedComments = []; + var lastComment = null; + + for (var i = 0, n = preComments.length; i < n; i++) { + var comment = preComments[i]; + + if (lastComment) { + var lastCommentLine = lineMap.getLineNumberFromPosition(lastComment.end()); + var commentLine = lineMap.getLineNumberFromPosition(comment.start()); + + if (commentLine >= lastCommentLine + 2) { + return detachedComments; + } + } + + detachedComments.push(comment); + lastComment = comment; + } + + var lastCommentLine = lineMap.getLineNumberFromPosition(TypeScript.ArrayUtilities.last(detachedComments).end()); + var astLine = lineMap.getLineNumberFromPosition(element.start()); + if (astLine >= lastCommentLine + 2) { + return detachedComments; + } + } + + return []; + }; + + Emitter.prototype.emitPossibleCopyrightHeaders = function (script) { + this.emitDetachedComments(script.moduleElements); + }; + + Emitter.prototype.emitDetachedComments = function (list) { + if (list.childCount() > 0) { + var firstElement = list.childAt(0); + + this.detachedCommentsElement = firstElement; + this.emitCommentsArray(this.getDetachedComments(this.detachedCommentsElement), false); + } + }; + + Emitter.prototype.emitScriptElements = function (sourceUnit) { + var list = sourceUnit.moduleElements; + + this.emitPossibleCopyrightHeaders(sourceUnit); + + for (var i = 0, n = list.childCount(); i < n; i++) { + var node = list.childAt(i); + + if (!this.isDirectivePrologueElement(node)) { + break; + } + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + } + + this.emitPrologue(sourceUnit); + + var isExternalModule = this.document.isExternalModule(); + var isNonElidedExternalModule = isExternalModule && !TypeScript.ASTHelpers.scriptIsElided(sourceUnit); + if (isNonElidedExternalModule) { + this.recordSourceMappingStart(sourceUnit); + + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + var dependencyList = "[\"require\", \"exports\""; + var importList = "require, exports"; + + var importAndDependencyList = this.getModuleImportAndDependencyList(sourceUnit); + importList += importAndDependencyList.importList; + dependencyList += importAndDependencyList.dependencyList + "]"; + + this.writeLineToOutput("define(" + dependencyList + "," + " function(" + importList + ") {"); + } + } + + if (isExternalModule) { + var temp = this.setContainer(2 /* DynamicModule */); + + var svModuleName = this.moduleName; + this.moduleName = sourceUnit.fileName(); + if (TypeScript.isTSFile(this.moduleName)) { + this.moduleName = this.moduleName.substring(0, this.moduleName.length - ".ts".length); + } + + this.setExportAssignment(null); + + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + this.indenter.increaseIndent(); + } + + var externalModule = this.semanticInfoChain.getDeclForAST(this.document.sourceUnit()); + + if (TypeScript.hasFlag(externalModule.flags, 262144 /* MustCaptureThis */)) { + this.writeCaptureThisStatement(sourceUnit); + } + + this.pushDecl(externalModule); + } + + this.emitList(list, true, i, n); + + if (isExternalModule) { + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + this.indenter.decreaseIndent(); + } + + if (isNonElidedExternalModule) { + var exportAssignment = this.getExportAssignment(); + var exportAssignmentIdentifierText = exportAssignment ? exportAssignment.identifier.text() : null; + var exportAssignmentValueSymbol = externalModule.getSymbol().getExportAssignedValueSymbol(); + + if (this.emitOptions.compilationSettings().moduleGenTarget() === 2 /* Asynchronous */) { + if (exportAssignmentIdentifierText && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { + this.indenter.increaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("return " + exportAssignmentIdentifierText, exportAssignment); + this.writeLineToOutput(";"); + this.indenter.decreaseIndent(); + } + this.writeToOutput("});"); + } else if (exportAssignmentIdentifierText && exportAssignmentValueSymbol && !(exportAssignmentValueSymbol.kind & 58720272 /* SomeTypeReference */)) { + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("module.exports = " + exportAssignmentIdentifierText, exportAssignment); + this.writeToOutput(";"); + } + + this.recordSourceMappingEnd(sourceUnit); + this.writeLineToOutput(""); + } + + this.setContainer(temp); + this.moduleName = svModuleName; + this.popDecl(externalModule); + } + }; + + Emitter.prototype.emitConstructorStatements = function (funcDecl) { + var list = funcDecl.block.statements; + + if (list === null) { + return; + } + + this.emitComments(list, true); + + var emitPropertyAssignmentsAfterSuperCall = TypeScript.ASTHelpers.getExtendsHeritageClause(this.thisClassNode.heritageClauses) !== null; + var propertyAssignmentIndex = emitPropertyAssignmentsAfterSuperCall ? 1 : 0; + var lastEmittedNode = null; + + for (var i = 0, n = list.childCount(); i < n; i++) { + if (i === propertyAssignmentIndex) { + this.emitParameterPropertyAndMemberVariableAssignments(); + } + + var node = list.childAt(i); + + if (this.shouldEmit(node)) { + this.emitSpaceBetweenConstructs(lastEmittedNode, node); + + this.emitJavascript(node, true); + this.writeLineToOutput(""); + + lastEmittedNode = node; + } + } + + if (i === propertyAssignmentIndex) { + this.emitParameterPropertyAndMemberVariableAssignments(); + } + + this.emitComments(list, false); + }; + + Emitter.prototype.emitJavascript = function (ast, startLine) { + if (ast === null) { + return; + } + + if (startLine && this.indenter.indentAmt > 0) { + this.emitIndent(); + } + + this.emit(ast); + }; + + Emitter.prototype.emitAccessorMemberDeclaration = function (funcDecl, name, className, isProto) { + if (funcDecl.kind() !== 139 /* GetAccessor */) { + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain); + if (accessorSymbol.getGetter()) { + return; + } + } + + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + + this.writeToOutput("Object.defineProperty(" + className); + if (isProto) { + this.writeToOutput(".prototype, "); + } else { + this.writeToOutput(", "); + } + + var functionName = name.text(); + if (TypeScript.isQuoted(functionName)) { + this.writeToOutput(functionName); + } else { + this.writeToOutput('"' + functionName + '"'); + } + + this.writeLineToOutput(", {"); + + this.indenter.increaseIndent(); + + var accessors = TypeScript.PullHelpers.getGetterAndSetterFunction(funcDecl, this.semanticInfoChain); + if (accessors.getter) { + this.emitIndent(); + this.recordSourceMappingStart(accessors.getter); + this.emitComments(accessors.getter, true); + this.writeToOutput("get: "); + this.emitAccessorBody(accessors.getter, accessors.getter.parameterList, accessors.getter.block); + this.writeLineToOutput(","); + } + + if (accessors.setter) { + this.emitIndent(); + this.recordSourceMappingStart(accessors.setter); + this.emitComments(accessors.setter, true); + this.writeToOutput("set: "); + this.emitAccessorBody(accessors.setter, accessors.setter.parameterList, accessors.setter.block); + this.writeLineToOutput(","); + } + + this.emitIndent(); + this.writeLineToOutput("enumerable: true,"); + this.emitIndent(); + this.writeLineToOutput("configurable: true"); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("});"); + this.recordSourceMappingEnd(funcDecl); + }; + + Emitter.prototype.emitAccessorBody = function (funcDecl, parameterList, block) { + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(null, funcDecl, parameters, block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.recordSourceMappingEnd(funcDecl); + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitClass = function (classDecl) { + var pullDecl = this.semanticInfoChain.getDeclForAST(classDecl); + this.pushDecl(pullDecl); + + var svClassNode = this.thisClassNode; + this.thisClassNode = classDecl; + var className = classDecl.identifier.text(); + this.emitComments(classDecl, true); + var temp = this.setContainer(3 /* Class */); + + this.recordSourceMappingStart(classDecl); + this.writeToOutput("var " + className); + + var hasBaseClass = TypeScript.ASTHelpers.getExtendsHeritageClause(classDecl.heritageClauses) !== null; + var baseTypeReference = null; + var varDecl = null; + + if (hasBaseClass) { + this.writeLineToOutput(" = (function (_super) {"); + } else { + this.writeLineToOutput(" = (function () {"); + } + + this.recordSourceMappingNameStart(className); + this.indenter.increaseIndent(); + + if (hasBaseClass) { + baseTypeReference = TypeScript.ASTHelpers.getExtendsHeritageClause(classDecl.heritageClauses).typeNames.nonSeparatorAt(0); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("__extends(" + className + ", _super)", baseTypeReference); + this.writeLineToOutput(";"); + } + + this.emitIndent(); + + var constrDecl = getLastConstructor(classDecl); + + if (constrDecl) { + this.emit(constrDecl); + this.writeLineToOutput(""); + } else { + this.recordSourceMappingStart(classDecl); + + this.indenter.increaseIndent(); + this.writeLineToOutput("function " + classDecl.identifier.text() + "() {"); + this.recordSourceMappingNameStart("constructor"); + if (hasBaseClass) { + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("_super.apply(this, arguments)", baseTypeReference); + this.writeLineToOutput(";"); + } + + if (this.shouldCaptureThis(classDecl)) { + this.writeCaptureThisStatement(classDecl); + } + + this.emitParameterPropertyAndMemberVariableAssignments(); + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("}", classDecl.closeBraceToken); + this.writeLineToOutput(""); + + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl); + } + + this.emitClassMembers(classDecl); + + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("return " + className + ";", classDecl.closeBraceToken); + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutputWithSourceMapRecord("}", classDecl.closeBraceToken); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingStart(classDecl); + this.writeToOutput(")("); + if (hasBaseClass) { + this.emitJavascript(baseTypeReference, false); + } + this.writeToOutput(");"); + this.recordSourceMappingEnd(classDecl); + + if ((temp === 1 /* Module */ || temp === 2 /* DynamicModule */) && TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = temp === 1 /* Module */ ? this.moduleName : "exports"; + this.writeToOutputWithSourceMapRecord(modName + "." + className + " = " + className + ";", classDecl); + } + + this.recordSourceMappingEnd(classDecl); + this.emitComments(classDecl, false); + this.setContainer(temp); + this.thisClassNode = svClassNode; + + this.popDecl(pullDecl); + }; + + Emitter.prototype.emitClassMembers = function (classDecl) { + var lastEmittedMember = null; + + for (var i = 0, n = classDecl.classElements.childCount(); i < n; i++) { + var memberDecl = classDecl.classElements.childAt(i); + + if (memberDecl.kind() === 139 /* GetAccessor */) { + this.emitSpaceBetweenConstructs(lastEmittedMember, memberDecl); + var getter = memberDecl; + this.emitAccessorMemberDeclaration(getter, getter.propertyName, classDecl.identifier.text(), !TypeScript.hasModifier(getter.modifiers, 16 /* Static */)); + lastEmittedMember = memberDecl; + } else if (memberDecl.kind() === 140 /* SetAccessor */) { + this.emitSpaceBetweenConstructs(lastEmittedMember, memberDecl); + var setter = memberDecl; + this.emitAccessorMemberDeclaration(setter, setter.propertyName, classDecl.identifier.text(), !TypeScript.hasModifier(setter.modifiers, 16 /* Static */)); + lastEmittedMember = memberDecl; + } else if (memberDecl.kind() === 135 /* MemberFunctionDeclaration */) { + var memberFunction = memberDecl; + + if (memberFunction.block) { + this.emitSpaceBetweenConstructs(lastEmittedMember, memberDecl); + + this.emitClassMemberFunctionDeclaration(classDecl, memberFunction); + lastEmittedMember = memberDecl; + } + } + } + + for (var i = 0, n = classDecl.classElements.childCount(); i < n; i++) { + var memberDecl = classDecl.classElements.childAt(i); + + if (memberDecl.kind() === 136 /* MemberVariableDeclaration */) { + var varDecl = memberDecl; + + if (TypeScript.hasModifier(varDecl.modifiers, 16 /* Static */) && varDecl.variableDeclarator.equalsValueClause) { + this.emitSpaceBetweenConstructs(lastEmittedMember, varDecl); + + this.emitIndent(); + this.recordSourceMappingStart(varDecl); + + var varDeclName = varDecl.variableDeclarator.propertyName.text(); + if (TypeScript.isQuoted(varDeclName) || varDecl.variableDeclarator.propertyName.kind() !== 11 /* IdentifierName */) { + this.writeToOutput(classDecl.identifier.text() + "[" + varDeclName + "]"); + } else { + this.writeToOutput(classDecl.identifier.text() + "." + varDeclName); + } + + this.emit(varDecl.variableDeclarator.equalsValueClause); + + this.recordSourceMappingEnd(varDecl); + this.writeLineToOutput(";"); + + lastEmittedMember = varDecl; + } + } + } + }; + + Emitter.prototype.emitClassMemberFunctionDeclaration = function (classDecl, funcDecl) { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.emitComments(funcDecl, true); + var functionName = funcDecl.propertyName.text(); + + this.writeToOutput(classDecl.identifier.text()); + + if (!TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */)) { + this.writeToOutput(".prototype"); + } + + if (TypeScript.isQuoted(functionName) || funcDecl.propertyName.kind() !== 11 /* IdentifierName */) { + this.writeToOutput("[" + functionName + "] = "); + } else { + this.writeToOutput("." + functionName + " = "); + } + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcDecl); + this.writeToOutput("function "); + + this.emitParameterList(funcDecl.callSignature.parameterList); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList); + this.emitFunctionBodyStatements(funcDecl.propertyName.text(), funcDecl, parameters, funcDecl.block, null); + + this.recordSourceMappingEnd(funcDecl); + + this.emitComments(funcDecl, false); + + this.recordSourceMappingEnd(funcDecl); + this.popDecl(pullDecl); + + this.writeLineToOutput(";"); + }; + + Emitter.prototype.requiresExtendsBlock = function (moduleElements) { + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var moduleElement = moduleElements.childAt(i); + + if (moduleElement.kind() === 130 /* ModuleDeclaration */) { + var moduleAST = moduleElement; + + if (!TypeScript.hasModifier(moduleAST.modifiers, 8 /* Ambient */) && this.requiresExtendsBlock(moduleAST.moduleElements)) { + return true; + } + } else if (moduleElement.kind() === 131 /* ClassDeclaration */) { + var classDeclaration = moduleElement; + + if (!TypeScript.hasModifier(classDeclaration.modifiers, 8 /* Ambient */) && TypeScript.ASTHelpers.getExtendsHeritageClause(classDeclaration.heritageClauses) !== null) { + return true; + } + } + } + + return false; + }; + + Emitter.prototype.emitPrologue = function (sourceUnit) { + if (!this.extendsPrologueEmitted) { + if (this.requiresExtendsBlock(sourceUnit.moduleElements)) { + this.extendsPrologueEmitted = true; + this.writeLineToOutput("var __extends = this.__extends || function (d, b) {"); + this.writeLineToOutput(" for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];"); + this.writeLineToOutput(" function __() { this.constructor = d; }"); + this.writeLineToOutput(" __.prototype = b.prototype;"); + this.writeLineToOutput(" d.prototype = new __();"); + this.writeLineToOutput("};"); + } + } + + if (!this.globalThisCapturePrologueEmitted) { + if (this.shouldCaptureThis(sourceUnit)) { + this.globalThisCapturePrologueEmitted = true; + this.writeLineToOutput(this.captureThisStmtString); + } + } + }; + + Emitter.prototype.emitThis = function () { + if (!this.inWithBlock && this.inArrowFunction) { + this.writeToOutput("_this"); + } else { + this.writeToOutput("this"); + } + }; + + Emitter.prototype.emitBlockOrStatement = function (node) { + if (node.kind() === 146 /* Block */) { + this.emit(node); + } else { + this.writeLineToOutput(""); + this.indenter.increaseIndent(); + this.emitJavascript(node, true); + this.indenter.decreaseIndent(); + } + }; + + Emitter.prototype.emitLiteralExpression = function (expression) { + switch (expression.kind()) { + case 32 /* NullKeyword */: + this.writeToOutputWithSourceMapRecord("null", expression); + break; + case 24 /* FalseKeyword */: + this.writeToOutputWithSourceMapRecord("false", expression); + break; + case 37 /* TrueKeyword */: + this.writeToOutputWithSourceMapRecord("true", expression); + break; + default: + throw TypeScript.Errors.abstract(); + } + }; + + Emitter.prototype.emitThisExpression = function (expression) { + if (!this.inWithBlock && this.inArrowFunction) { + this.writeToOutputWithSourceMapRecord("_this", expression); + } else { + this.writeToOutputWithSourceMapRecord("this", expression); + } + }; + + Emitter.prototype.emitSuperExpression = function (expression) { + this.writeToOutputWithSourceMapRecord("_super.prototype", expression); + }; + + Emitter.prototype.emitParenthesizedExpression = function (parenthesizedExpression) { + var omitParentheses = false; + + if (parenthesizedExpression.expression.kind() === 220 /* CastExpression */ && parenthesizedExpression.openParenTrailingComments === null) { + var castedExpression = parenthesizedExpression.expression.expression; + + while (castedExpression.kind() == 220 /* CastExpression */) { + castedExpression = castedExpression.expression; + } + + switch (castedExpression.kind()) { + case 217 /* ParenthesizedExpression */: + case 11 /* IdentifierName */: + case 32 /* NullKeyword */: + case 35 /* ThisKeyword */: + case 14 /* StringLiteral */: + case 13 /* NumericLiteral */: + case 12 /* RegularExpressionLiteral */: + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + case 214 /* ArrayLiteralExpression */: + case 215 /* ObjectLiteralExpression */: + case 212 /* MemberAccessExpression */: + case 221 /* ElementAccessExpression */: + omitParentheses = true; + break; + + case 213 /* InvocationExpression */: + if (parenthesizedExpression.parent.kind() !== 216 /* ObjectCreationExpression */) { + omitParentheses = true; + } + + break; + } + } + + if (omitParentheses) { + this.emit(parenthesizedExpression.expression); + } else { + this.recordSourceMappingStart(parenthesizedExpression); + this.writeToOutput("("); + this.emitCommentsArray(parenthesizedExpression.openParenTrailingComments, false); + this.emit(parenthesizedExpression.expression); + this.writeToOutput(")"); + this.recordSourceMappingEnd(parenthesizedExpression); + } + }; + + Emitter.prototype.emitCastExpression = function (expression) { + this.emit(expression.expression); + }; + + Emitter.prototype.emitPrefixUnaryExpression = function (expression) { + var nodeType = expression.kind(); + + this.recordSourceMappingStart(expression); + switch (nodeType) { + case 167 /* LogicalNotExpression */: + this.writeToOutput("!"); + this.emit(expression.operand); + break; + case 166 /* BitwiseNotExpression */: + this.writeToOutput("~"); + this.emit(expression.operand); + break; + case 165 /* NegateExpression */: + this.writeToOutput("-"); + if (expression.operand.kind() === 165 /* NegateExpression */ || expression.operand.kind() === 169 /* PreDecrementExpression */) { + this.writeToOutput(" "); + } + this.emit(expression.operand); + break; + case 164 /* PlusExpression */: + this.writeToOutput("+"); + if (expression.operand.kind() === 164 /* PlusExpression */ || expression.operand.kind() === 168 /* PreIncrementExpression */) { + this.writeToOutput(" "); + } + this.emit(expression.operand); + break; + case 168 /* PreIncrementExpression */: + this.writeToOutput("++"); + this.emit(expression.operand); + break; + case 169 /* PreDecrementExpression */: + this.writeToOutput("--"); + this.emit(expression.operand); + break; + default: + throw TypeScript.Errors.abstract(); + } + + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitPostfixUnaryExpression = function (expression) { + var nodeType = expression.kind(); + + this.recordSourceMappingStart(expression); + switch (nodeType) { + case 210 /* PostIncrementExpression */: + this.emit(expression.operand); + this.writeToOutput("++"); + break; + case 211 /* PostDecrementExpression */: + this.emit(expression.operand); + this.writeToOutput("--"); + break; + default: + throw TypeScript.Errors.abstract(); + } + + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitTypeOfExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.writeToOutput("typeof "); + this.emit(expression.expression); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitDeleteExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.writeToOutput("delete "); + this.emit(expression.expression); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitVoidExpression = function (expression) { + this.recordSourceMappingStart(expression); + this.writeToOutput("void "); + this.emit(expression.expression); + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.canEmitDottedNameMemberAccessExpression = function (expression) { + var memberExpressionNodeType = expression.expression.kind(); + + if (memberExpressionNodeType === 11 /* IdentifierName */ || memberExpressionNodeType == 212 /* MemberAccessExpression */) { + var memberAccessSymbol = this.getSymbolForEmit(expression).symbol; + var memberAccessExpressionSymbol = this.getSymbolForEmit(expression.expression).symbol; + if (memberAccessSymbol && memberAccessExpressionSymbol && !this.semanticInfoChain.getAliasSymbolForAST(expression.expression) && (TypeScript.PullHelpers.symbolIsModule(memberAccessExpressionSymbol) || memberAccessExpressionSymbol.kind === 64 /* Enum */ || memberAccessExpressionSymbol.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */))) { + var memberAccessSymbolKind = memberAccessSymbol.kind; + if (memberAccessSymbolKind === 4096 /* Property */ || memberAccessSymbolKind === 67108864 /* EnumMember */ || (memberAccessSymbol.anyDeclHasFlag(1 /* Exported */) && memberAccessSymbolKind === 512 /* Variable */ && !memberAccessSymbol.anyDeclHasFlag(32768 /* InitializedModule */ | 4096 /* Enum */)) || ((memberAccessSymbol.anyDeclHasFlag(1 /* Exported */) && !this.symbolIsUsedInItsEnclosingContainer(memberAccessSymbol)))) { + if (memberExpressionNodeType === 212 /* MemberAccessExpression */) { + return this.canEmitDottedNameMemberAccessExpression(expression.expression); + } + + return true; + } + } + } + + return false; + }; + + Emitter.prototype.emitDottedNameMemberAccessExpression = function (expression) { + this.recordSourceMappingStart(expression); + if (expression.expression.kind() === 212 /* MemberAccessExpression */) { + this.emitDottedNameMemberAccessExpressionRecurse(expression.expression); + } else { + this.emitName(expression.expression, true); + } + + this.writeToOutput("."); + this.emitName(expression.name, false); + + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitDottedNameMemberAccessExpressionRecurse = function (expression) { + this.emitComments(expression, true); + this.emitDottedNameMemberAccessExpression(expression); + this.emitComments(expression, false); + }; + + Emitter.prototype.emitMemberAccessExpression = function (expression) { + if (!this.tryEmitConstant(expression)) { + if (this.canEmitDottedNameMemberAccessExpression(expression)) { + this.emitDottedNameMemberAccessExpression(expression); + } else { + this.recordSourceMappingStart(expression); + this.emit(expression.expression); + this.writeToOutput("."); + this.emitName(expression.name, false); + this.recordSourceMappingEnd(expression); + } + } + }; + + Emitter.prototype.emitQualifiedName = function (name) { + this.recordSourceMappingStart(name); + + this.emit(name.left); + this.writeToOutput("."); + this.emitName(name.right, false); + + this.recordSourceMappingEnd(name); + }; + + Emitter.prototype.emitBinaryExpression = function (expression) { + this.recordSourceMappingStart(expression); + switch (expression.kind()) { + case 173 /* CommaExpression */: + this.emit(expression.left); + this.writeToOutput(", "); + this.emit(expression.right); + break; + default: { + this.emit(expression.left); + var binOp = TypeScript.SyntaxFacts.getText(TypeScript.SyntaxFacts.getOperatorTokenFromBinaryExpression(expression.kind())); + if (binOp === "instanceof") { + this.writeToOutput(" instanceof "); + } else if (binOp === "in") { + this.writeToOutput(" in "); + } else { + this.writeToOutput(" " + binOp + " "); + } + this.emit(expression.right); + } + } + this.recordSourceMappingEnd(expression); + }; + + Emitter.prototype.emitSimplePropertyAssignment = function (property) { + this.recordSourceMappingStart(property); + this.emit(property.propertyName); + this.writeToOutput(": "); + this.emit(property.expression); + this.recordSourceMappingEnd(property); + }; + + Emitter.prototype.emitFunctionPropertyAssignment = function (funcProp) { + this.recordSourceMappingStart(funcProp); + + this.emit(funcProp.propertyName); + this.writeToOutput(": "); + + var pullFunctionDecl = this.semanticInfoChain.getDeclForAST(funcProp); + + var savedInArrowFunction = this.inArrowFunction; + this.inArrowFunction = false; + + var temp = this.setContainer(5 /* Function */); + var funcName = funcProp.propertyName; + + var pullDecl = this.semanticInfoChain.getDeclForAST(funcProp); + this.pushDecl(pullDecl); + + this.recordSourceMappingStart(funcProp); + this.writeToOutput("function "); + + this.writeToOutput("("); + + var parameters = TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList); + this.emitFunctionParameters(parameters); + this.writeToOutput(")"); + + this.emitFunctionBodyStatements(funcProp.propertyName.text(), funcProp, parameters, funcProp.block, null); + + this.recordSourceMappingEnd(funcProp); + + this.recordSourceMappingEnd(funcProp); + + this.emitComments(funcProp, false); + + this.popDecl(pullDecl); + + this.setContainer(temp); + this.inArrowFunction = savedInArrowFunction; + }; + + Emitter.prototype.emitConditionalExpression = function (expression) { + this.emit(expression.condition); + this.writeToOutput(" ? "); + this.emit(expression.whenTrue); + this.writeToOutput(" : "); + this.emit(expression.whenFalse); + }; + + Emitter.prototype.emitThrowStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("throw "); + this.emit(statement.expression); + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitExpressionStatement = function (statement) { + var isArrowExpression = statement.expression.kind() === 219 /* SimpleArrowFunctionExpression */ || statement.expression.kind() === 218 /* ParenthesizedArrowFunctionExpression */; + + this.recordSourceMappingStart(statement); + if (isArrowExpression) { + this.writeToOutput("("); + } + + this.emit(statement.expression); + + if (isArrowExpression) { + this.writeToOutput(")"); + } + + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitLabeledStatement = function (statement) { + this.writeToOutputWithSourceMapRecord(statement.identifier.text(), statement.identifier); + this.writeLineToOutput(":"); + this.emitJavascript(statement.statement, true); + }; + + Emitter.prototype.emitBlock = function (block) { + this.recordSourceMappingStart(block); + this.writeLineToOutput(" {"); + this.indenter.increaseIndent(); + if (block.statements) { + this.emitList(block.statements); + } + this.emitCommentsArray(block.closeBraceLeadingComments, false); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + this.recordSourceMappingEnd(block); + }; + + Emitter.prototype.emitBreakStatement = function (jump) { + this.recordSourceMappingStart(jump); + this.writeToOutput("break"); + + if (jump.identifier) { + this.writeToOutput(" " + jump.identifier.text()); + } + + this.recordSourceMappingEnd(jump); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitContinueStatement = function (jump) { + this.recordSourceMappingStart(jump); + this.writeToOutput("continue"); + + if (jump.identifier) { + this.writeToOutput(" " + jump.identifier.text()); + } + + this.recordSourceMappingEnd(jump); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitWhileStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("while ("); + this.emit(statement.condition); + this.writeToOutput(")"); + this.emitBlockOrStatement(statement.statement); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitDoStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("do"); + this.emitBlockOrStatement(statement.statement); + this.writeToOutputWithSourceMapRecord(" while", statement.whileKeyword); + this.writeToOutput('('); + this.emit(statement.condition); + this.writeToOutput(")"); + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitIfStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("if ("); + this.emit(statement.condition); + this.writeToOutput(")"); + + this.emitBlockOrStatement(statement.statement); + + if (statement.elseClause) { + if (statement.statement.kind() !== 146 /* Block */) { + this.writeLineToOutput(""); + this.emitIndent(); + } else { + this.writeToOutput(" "); + } + + this.emit(statement.elseClause); + } + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitElseClause = function (elseClause) { + if (elseClause.statement.kind() === 147 /* IfStatement */) { + this.writeToOutput("else "); + this.emit(elseClause.statement); + } else { + this.writeToOutput("else"); + this.emitBlockOrStatement(elseClause.statement); + } + }; + + Emitter.prototype.emitReturnStatement = function (statement) { + this.recordSourceMappingStart(statement); + if (statement.expression) { + this.writeToOutput("return "); + this.emit(statement.expression); + } else { + this.writeToOutput("return"); + } + this.recordSourceMappingEnd(statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitForInStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("for ("); + if (statement.left) { + this.emit(statement.left); + } else { + this.emit(statement.variableDeclaration); + } + this.writeToOutput(" in "); + this.emit(statement.expression); + this.writeToOutput(")"); + this.emitBlockOrStatement(statement.statement); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitForStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("for ("); + if (statement.variableDeclaration) { + this.emit(statement.variableDeclaration); + } else if (statement.initializer) { + this.emit(statement.initializer); + } + + this.writeToOutput("; "); + this.emitJavascript(statement.condition, false); + this.writeToOutput(";"); + if (statement.incrementor) { + this.writeToOutput(" "); + this.emitJavascript(statement.incrementor, false); + } + this.writeToOutput(")"); + this.emitBlockOrStatement(statement.statement); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitWithStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("with ("); + if (statement.condition) { + this.emit(statement.condition); + } + + this.writeToOutput(")"); + var prevInWithBlock = this.inWithBlock; + this.inWithBlock = true; + this.emitBlockOrStatement(statement.statement); + this.inWithBlock = prevInWithBlock; + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitSwitchStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("switch ("); + this.emit(statement.expression); + this.recordSourceMappingStart(statement.closeParenToken); + this.writeToOutput(")"); + this.recordSourceMappingEnd(statement.closeParenToken); + this.writeLineToOutput(" {"); + this.indenter.increaseIndent(); + this.emitList(statement.switchClauses, false); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitCaseSwitchClause = function (clause) { + this.recordSourceMappingStart(clause); + this.writeToOutput("case "); + this.emit(clause.expression); + this.writeToOutput(":"); + + this.emitSwitchClauseBody(clause.statements); + this.recordSourceMappingEnd(clause); + }; + + Emitter.prototype.emitSwitchClauseBody = function (body) { + if (body.childCount() === 1 && body.childAt(0).kind() === 146 /* Block */) { + this.emit(body.childAt(0)); + this.writeLineToOutput(""); + } else { + this.writeLineToOutput(""); + this.indenter.increaseIndent(); + this.emit(body); + this.indenter.decreaseIndent(); + } + }; + + Emitter.prototype.emitDefaultSwitchClause = function (clause) { + this.recordSourceMappingStart(clause); + this.writeToOutput("default:"); + + this.emitSwitchClauseBody(clause.statements); + this.recordSourceMappingEnd(clause); + }; + + Emitter.prototype.emitTryStatement = function (statement) { + this.recordSourceMappingStart(statement); + this.writeToOutput("try "); + this.emit(statement.block); + this.emitJavascript(statement.catchClause, false); + + if (statement.finallyClause) { + this.emit(statement.finallyClause); + } + this.recordSourceMappingEnd(statement); + }; + + Emitter.prototype.emitCatchClause = function (clause) { + this.writeToOutput(" "); + this.recordSourceMappingStart(clause); + this.writeToOutput("catch ("); + this.emit(clause.identifier); + this.writeToOutput(")"); + this.emit(clause.block); + this.recordSourceMappingEnd(clause); + }; + + Emitter.prototype.emitFinallyClause = function (clause) { + this.writeToOutput(" finally"); + this.emit(clause.block); + }; + + Emitter.prototype.emitDebuggerStatement = function (statement) { + this.writeToOutputWithSourceMapRecord("debugger", statement); + this.writeToOutput(";"); + }; + + Emitter.prototype.emitNumericLiteral = function (literal) { + this.writeToOutputWithSourceMapRecord(literal.text(), literal); + }; + + Emitter.prototype.emitRegularExpressionLiteral = function (literal) { + this.writeToOutputWithSourceMapRecord(literal.text(), literal); + }; + + Emitter.prototype.emitStringLiteral = function (literal) { + this.writeToOutputWithSourceMapRecord(literal.text(), literal); + }; + + Emitter.prototype.emitEqualsValueClause = function (clause) { + this.writeToOutput(" = "); + this.emit(clause.value); + }; + + Emitter.prototype.emitParameter = function (parameter) { + this.writeToOutputWithSourceMapRecord(parameter.identifier.text(), parameter); + }; + + Emitter.prototype.emitConstructorDeclaration = function (declaration) { + if (declaration.block) { + this.emitConstructor(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitFunctionDeclaration = function (declaration) { + return declaration.preComments() !== null || (!TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) && declaration.block !== null); + }; + + Emitter.prototype.emitFunctionDeclaration = function (declaration) { + if (!TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */) && declaration.block !== null) { + this.emitFunction(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.emitSourceUnit = function (sourceUnit) { + if (!this.document.isDeclareFile()) { + var pullDecl = this.semanticInfoChain.getDeclForAST(sourceUnit); + this.pushDecl(pullDecl); + this.emitScriptElements(sourceUnit); + this.popDecl(pullDecl); + + this.emitCommentsArray(sourceUnit.endOfFileTokenLeadingComments, false); + } + }; + + Emitter.prototype.shouldEmitEnumDeclaration = function (declaration) { + return declaration.preComments() !== null || !TypeScript.ASTHelpers.enumIsElided(declaration); + }; + + Emitter.prototype.emitEnumDeclaration = function (declaration) { + if (!TypeScript.ASTHelpers.enumIsElided(declaration)) { + this.emitComments(declaration, true); + this.emitEnum(declaration); + this.emitComments(declaration, false); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitModuleDeclaration = function (declaration) { + return declaration.preComments() !== null || !TypeScript.ASTHelpers.moduleIsElided(declaration); + }; + + Emitter.prototype.emitModuleDeclaration = function (declaration) { + if (!TypeScript.ASTHelpers.moduleIsElided(declaration)) { + this.emitModuleDeclarationWorker(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitClassDeclaration = function (declaration) { + return declaration.preComments() !== null || !TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */); + }; + + Emitter.prototype.emitClassDeclaration = function (declaration) { + if (!TypeScript.hasModifier(declaration.modifiers, 8 /* Ambient */)) { + this.emitClass(declaration); + } else { + this.emitComments(declaration, true, true); + } + }; + + Emitter.prototype.shouldEmitInterfaceDeclaration = function (declaration) { + return declaration.preComments() !== null; + }; + + Emitter.prototype.emitInterfaceDeclaration = function (declaration) { + this.emitComments(declaration, true, true); + }; + + Emitter.prototype.firstVariableDeclarator = function (statement) { + return statement.declaration.declarators.nonSeparatorAt(0); + }; + + Emitter.prototype.isNotAmbientOrHasInitializer = function (variableStatement) { + return !TypeScript.hasModifier(variableStatement.modifiers, 8 /* Ambient */) || this.firstVariableDeclarator(variableStatement).equalsValueClause !== null; + }; + + Emitter.prototype.shouldEmitVariableStatement = function (statement) { + return statement.preComments() !== null || this.isNotAmbientOrHasInitializer(statement); + }; + + Emitter.prototype.emitVariableStatement = function (statement) { + if (this.isNotAmbientOrHasInitializer(statement)) { + this.emitComments(statement, true); + this.emit(statement.declaration); + this.writeToOutput(";"); + this.emitComments(statement, false); + } else { + this.emitComments(statement, true, true); + } + }; + + Emitter.prototype.emitGenericType = function (type) { + this.emit(type.name); + }; + + Emitter.prototype.shouldEmit = function (ast) { + if (!ast) { + return false; + } + + switch (ast.kind()) { + case 133 /* ImportDeclaration */: + return this.shouldEmitImportDeclaration(ast); + case 131 /* ClassDeclaration */: + return this.shouldEmitClassDeclaration(ast); + case 128 /* InterfaceDeclaration */: + return this.shouldEmitInterfaceDeclaration(ast); + case 129 /* FunctionDeclaration */: + return this.shouldEmitFunctionDeclaration(ast); + case 130 /* ModuleDeclaration */: + return this.shouldEmitModuleDeclaration(ast); + case 148 /* VariableStatement */: + return this.shouldEmitVariableStatement(ast); + case 223 /* OmittedExpression */: + return false; + case 132 /* EnumDeclaration */: + return this.shouldEmitEnumDeclaration(ast); + } + + return true; + }; + + Emitter.prototype.emit = function (ast) { + if (!ast) { + return; + } + + switch (ast.kind()) { + case 2 /* SeparatedList */: + return this.emitSeparatedList(ast); + case 1 /* List */: + return this.emitList(ast); + case 120 /* SourceUnit */: + return this.emitSourceUnit(ast); + case 133 /* ImportDeclaration */: + return this.emitImportDeclaration(ast); + case 134 /* ExportAssignment */: + return this.setExportAssignment(ast); + case 131 /* ClassDeclaration */: + return this.emitClassDeclaration(ast); + case 128 /* InterfaceDeclaration */: + return this.emitInterfaceDeclaration(ast); + case 11 /* IdentifierName */: + return this.emitName(ast, true); + case 225 /* VariableDeclarator */: + return this.emitVariableDeclarator(ast); + case 219 /* SimpleArrowFunctionExpression */: + return this.emitSimpleArrowFunctionExpression(ast); + case 218 /* ParenthesizedArrowFunctionExpression */: + return this.emitParenthesizedArrowFunctionExpression(ast); + case 129 /* FunctionDeclaration */: + return this.emitFunctionDeclaration(ast); + case 130 /* ModuleDeclaration */: + return this.emitModuleDeclaration(ast); + case 224 /* VariableDeclaration */: + return this.emitVariableDeclaration(ast); + case 126 /* GenericType */: + return this.emitGenericType(ast); + case 137 /* ConstructorDeclaration */: + return this.emitConstructorDeclaration(ast); + case 132 /* EnumDeclaration */: + return this.emitEnumDeclaration(ast); + case 243 /* EnumElement */: + return this.emitEnumElement(ast); + case 222 /* FunctionExpression */: + return this.emitFunctionExpression(ast); + case 148 /* VariableStatement */: + return this.emitVariableStatement(ast); + } + + this.emitComments(ast, true); + this.emitWorker(ast); + this.emitComments(ast, false); + }; + + Emitter.prototype.emitWorker = function (ast) { + if (!ast) { + return; + } + + switch (ast.kind()) { + case 13 /* NumericLiteral */: + return this.emitNumericLiteral(ast); + case 12 /* RegularExpressionLiteral */: + return this.emitRegularExpressionLiteral(ast); + case 14 /* StringLiteral */: + return this.emitStringLiteral(ast); + case 24 /* FalseKeyword */: + case 32 /* NullKeyword */: + case 37 /* TrueKeyword */: + return this.emitLiteralExpression(ast); + case 35 /* ThisKeyword */: + return this.emitThisExpression(ast); + case 50 /* SuperKeyword */: + return this.emitSuperExpression(ast); + case 217 /* ParenthesizedExpression */: + return this.emitParenthesizedExpression(ast); + case 214 /* ArrayLiteralExpression */: + return this.emitArrayLiteralExpression(ast); + case 211 /* PostDecrementExpression */: + case 210 /* PostIncrementExpression */: + return this.emitPostfixUnaryExpression(ast); + case 167 /* LogicalNotExpression */: + case 166 /* BitwiseNotExpression */: + case 165 /* NegateExpression */: + case 164 /* PlusExpression */: + case 168 /* PreIncrementExpression */: + case 169 /* PreDecrementExpression */: + return this.emitPrefixUnaryExpression(ast); + case 213 /* InvocationExpression */: + return this.emitInvocationExpression(ast); + case 221 /* ElementAccessExpression */: + return this.emitElementAccessExpression(ast); + case 212 /* MemberAccessExpression */: + return this.emitMemberAccessExpression(ast); + case 121 /* QualifiedName */: + return this.emitQualifiedName(ast); + case 173 /* CommaExpression */: + case 174 /* AssignmentExpression */: + case 175 /* AddAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 187 /* LogicalOrExpression */: + case 188 /* LogicalAndExpression */: + case 189 /* BitwiseOrExpression */: + case 190 /* BitwiseExclusiveOrExpression */: + case 191 /* BitwiseAndExpression */: + case 192 /* EqualsWithTypeConversionExpression */: + case 193 /* NotEqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + case 196 /* LessThanExpression */: + case 197 /* GreaterThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 200 /* InstanceOfExpression */: + case 201 /* InExpression */: + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + case 208 /* AddExpression */: + case 209 /* SubtractExpression */: + return this.emitBinaryExpression(ast); + case 186 /* ConditionalExpression */: + return this.emitConditionalExpression(ast); + case 232 /* EqualsValueClause */: + return this.emitEqualsValueClause(ast); + case 242 /* Parameter */: + return this.emitParameter(ast); + case 146 /* Block */: + return this.emitBlock(ast); + case 235 /* ElseClause */: + return this.emitElseClause(ast); + case 147 /* IfStatement */: + return this.emitIfStatement(ast); + case 149 /* ExpressionStatement */: + return this.emitExpressionStatement(ast); + case 139 /* GetAccessor */: + return this.emitGetAccessor(ast); + case 140 /* SetAccessor */: + return this.emitSetAccessor(ast); + case 157 /* ThrowStatement */: + return this.emitThrowStatement(ast); + case 150 /* ReturnStatement */: + return this.emitReturnStatement(ast); + case 216 /* ObjectCreationExpression */: + return this.emitObjectCreationExpression(ast); + case 151 /* SwitchStatement */: + return this.emitSwitchStatement(ast); + case 233 /* CaseSwitchClause */: + return this.emitCaseSwitchClause(ast); + case 234 /* DefaultSwitchClause */: + return this.emitDefaultSwitchClause(ast); + case 152 /* BreakStatement */: + return this.emitBreakStatement(ast); + case 153 /* ContinueStatement */: + return this.emitContinueStatement(ast); + case 154 /* ForStatement */: + return this.emitForStatement(ast); + case 155 /* ForInStatement */: + return this.emitForInStatement(ast); + case 158 /* WhileStatement */: + return this.emitWhileStatement(ast); + case 163 /* WithStatement */: + return this.emitWithStatement(ast); + case 220 /* CastExpression */: + return this.emitCastExpression(ast); + case 215 /* ObjectLiteralExpression */: + return this.emitObjectLiteralExpression(ast); + case 240 /* SimplePropertyAssignment */: + return this.emitSimplePropertyAssignment(ast); + case 241 /* FunctionPropertyAssignment */: + return this.emitFunctionPropertyAssignment(ast); + case 156 /* EmptyStatement */: + return this.writeToOutputWithSourceMapRecord(";", ast); + case 159 /* TryStatement */: + return this.emitTryStatement(ast); + case 236 /* CatchClause */: + return this.emitCatchClause(ast); + case 237 /* FinallyClause */: + return this.emitFinallyClause(ast); + case 160 /* LabeledStatement */: + return this.emitLabeledStatement(ast); + case 161 /* DoStatement */: + return this.emitDoStatement(ast); + case 171 /* TypeOfExpression */: + return this.emitTypeOfExpression(ast); + case 170 /* DeleteExpression */: + return this.emitDeleteExpression(ast); + case 172 /* VoidExpression */: + return this.emitVoidExpression(ast); + case 162 /* DebuggerStatement */: + return this.emitDebuggerStatement(ast); + } + }; + return Emitter; + })(); + TypeScript.Emitter = Emitter; + + function getLastConstructor(classDecl) { + return classDecl.classElements.lastOrDefault(function (e) { + return e.kind() === 137 /* ConstructorDeclaration */; + }); + } + TypeScript.getLastConstructor = getLastConstructor; + + function getTrimmedTextLines(comment) { + if (comment.kind() === 6 /* MultiLineCommentTrivia */) { + return comment.fullText().split("\n").map(function (s) { + return s.trim(); + }); + } else { + return [comment.fullText().trim()]; + } + } + TypeScript.getTrimmedTextLines = getTrimmedTextLines; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var MemberName = (function () { + function MemberName() { + this.prefix = ""; + this.suffix = ""; + } + MemberName.prototype.isString = function () { + return false; + }; + MemberName.prototype.isArray = function () { + return false; + }; + MemberName.prototype.isMarker = function () { + return !this.isString() && !this.isArray(); + }; + + MemberName.prototype.toString = function () { + return MemberName.memberNameToString(this); + }; + + MemberName.memberNameToString = function (memberName, markerInfo, markerBaseLength) { + if (typeof markerBaseLength === "undefined") { markerBaseLength = 0; } + var result = memberName.prefix; + + if (memberName.isString()) { + result += memberName.text; + } else if (memberName.isArray()) { + var ar = memberName; + for (var index = 0; index < ar.entries.length; index++) { + if (ar.entries[index].isMarker()) { + if (markerInfo) { + markerInfo.push(markerBaseLength + result.length); + } + continue; + } + + result += MemberName.memberNameToString(ar.entries[index], markerInfo, markerBaseLength + result.length); + result += ar.delim; + } + } + + result += memberName.suffix; + return result; + }; + + MemberName.create = function (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.call(this); + 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; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function stripStartAndEndQuotes(str) { + var firstCharCode = str && str.charCodeAt(0); + if (str && str.length >= 2 && firstCharCode === str.charCodeAt(str.length - 1) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { + return str.substring(1, str.length - 1); + } + + return str; + } + TypeScript.stripStartAndEndQuotes = stripStartAndEndQuotes; + + function isSingleQuoted(str) { + return str && str.length >= 2 && str.charCodeAt(0) === str.charCodeAt(str.length - 1) && str.charCodeAt(0) === 39 /* singleQuote */; + } + TypeScript.isSingleQuoted = isSingleQuoted; + + function isDoubleQuoted(str) { + return str && str.length >= 2 && str.charCodeAt(0) === str.charCodeAt(str.length - 1) && str.charCodeAt(0) === 34 /* doubleQuote */; + } + TypeScript.isDoubleQuoted = isDoubleQuoted; + + function isQuoted(str) { + return isDoubleQuoted(str) || isSingleQuoted(str); + } + TypeScript.isQuoted = isQuoted; + + function quoteStr(str) { + return "\"" + str + "\""; + } + TypeScript.quoteStr = quoteStr; + + var switchToForwardSlashesRegEx = /\\/g; + function switchToForwardSlashes(path) { + return path.replace(switchToForwardSlashesRegEx, "/"); + } + TypeScript.switchToForwardSlashes = switchToForwardSlashes; + + function trimModName(modName) { + 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 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 isTSFile(fname) { + return isFileOfExtension(fname, ".ts"); + } + TypeScript.isTSFile = isTSFile; + + 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(stripStartAndEndQuotes(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, isAbsoultePathURL) { + if (typeof isAbsoultePathURL === "undefined") { isAbsoultePathURL = true; } + 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("/"); + } + + if (isAbsoultePathURL && absoluteModPath.indexOf("://") === -1) { + absoluteModPath = "file:///" + absoluteModPath; + } + + return absoluteModPath; + } + TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; + + function changePathToDTS(modPath) { + return trimModName(stripStartAndEndQuotes(modPath)) + ".d.ts"; + } + TypeScript.changePathToDTS = changePathToDTS; + + function isRelative(path) { + return path.length > 0 && path.charAt(0) === "."; + } + TypeScript.isRelative = isRelative; + function isRooted(path) { + return path.length > 0 && (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 convertToDirectoryPath(dirPath) { + if (dirPath && dirPath.charAt(dirPath.length - 1) !== "/") { + dirPath += "/"; + } + + return dirPath; + } + TypeScript.convertToDirectoryPath = convertToDirectoryPath; + + var normalizePathRegEx = /^\\\\[^\\]/; + function normalizePath(path) { + if (normalizePathRegEx.test(path)) { + path = "file:" + path; + } + var parts = this.getPathComponents(switchToForwardSlashes(path)); + var normalizedParts = []; + + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + if (part === ".") { + continue; + } + + if (normalizedParts.length > 0 && TypeScript.ArrayUtilities.last(normalizedParts) !== ".." && part === "..") { + normalizedParts.pop(); + continue; + } + + normalizedParts.push(part); + } + + return normalizedParts.join("/"); + } + TypeScript.normalizePath = normalizePath; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + + + function isNoDefaultLibMatch(comment) { + var isNoDefaultLibRegex = /^(\/\/\/\s*/gim; + return isNoDefaultLibRegex.exec(comment); + } + + TypeScript.tripleSlashReferenceRegExp = /^(\/\/\/\s*/; + + function getFileReferenceFromReferencePath(fileName, lineMap, position, comment, diagnostics) { + var simpleReferenceRegEx = /^\/\/\/\s*= 7 && fullReference[6] === "true"; + if (isResident) { + TypeScript.CompilerDiagnostics.debugPrint(path + " is resident"); + } + return { + line: 0, + character: 0, + position: 0, + length: 0, + path: TypeScript.switchToForwardSlashes(adjustedPath), + isResident: isResident + }; + } + } + } + + return null; + } + + var scannerWindow = TypeScript.ArrayUtilities.createArray(2048, 0); + var scannerDiagnostics = []; + + function processImports(lineMap, scanner, token, importedFiles) { + var position = 0; + var lineChar = { line: -1, character: -1 }; + + var start = new Date().getTime(); + + while (token.tokenKind !== 10 /* EndOfFileToken */) { + if (token.tokenKind === 49 /* ImportKeyword */) { + var importStart = position + token.leadingTriviaWidth(); + token = scanner.scan(scannerDiagnostics, false); + + if (TypeScript.SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 107 /* EqualsToken */) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 65 /* ModuleKeyword */ || token.tokenKind === 66 /* RequireKeyword */) { + token = scanner.scan(scannerDiagnostics, false); + + if (token.tokenKind === 72 /* OpenParenToken */) { + var afterOpenParenPosition = scanner.absoluteIndex(); + token = scanner.scan(scannerDiagnostics, false); + + lineMap.fillLineAndCharacterFromPosition(importStart, lineChar); + + if (token.tokenKind === 14 /* StringLiteral */) { + var ref = { + line: lineChar.line, + character: lineChar.character, + position: afterOpenParenPosition + token.leadingTriviaWidth(), + length: token.width(), + path: TypeScript.stripStartAndEndQuotes(TypeScript.switchToForwardSlashes(token.text())), + isResident: false + }; + importedFiles.push(ref); + } + } + } + } + } + } + + position = scanner.absoluteIndex(); + token = scanner.scan(scannerDiagnostics, false); + } + + var totalTime = new Date().getTime() - start; + TypeScript.fileResolutionScanImportsTime += totalTime; + } + + function processTripleSlashDirectives(fileName, lineMap, firstToken) { + var leadingTrivia = firstToken.leadingTrivia(); + + var position = 0; + var lineChar = { line: -1, character: -1 }; + var noDefaultLib = false; + var diagnostics = []; + var referencedFiles = []; + + for (var i = 0, n = leadingTrivia.count(); i < n; i++) { + var trivia = leadingTrivia.syntaxTriviaAt(i); + + if (trivia.kind() === 7 /* SingleLineCommentTrivia */) { + var triviaText = trivia.fullText(); + var referencedCode = getFileReferenceFromReferencePath(fileName, lineMap, position, triviaText, diagnostics); + + if (referencedCode) { + lineMap.fillLineAndCharacterFromPosition(position, lineChar); + referencedCode.position = position; + referencedCode.length = trivia.fullWidth(); + referencedCode.line = lineChar.line; + referencedCode.character = lineChar.character; + + referencedFiles.push(referencedCode); + } + + var isNoDefaultLib = isNoDefaultLibMatch(triviaText); + if (isNoDefaultLib) { + noDefaultLib = isNoDefaultLib[3] === "true"; + } + } + + position += trivia.fullWidth(); + } + + return { noDefaultLib: noDefaultLib, diagnostics: diagnostics, referencedFiles: referencedFiles }; + } + + function preProcessFile(fileName, sourceText, readImportFiles) { + if (typeof readImportFiles === "undefined") { readImportFiles = true; } + var text = TypeScript.SimpleText.fromScriptSnapshot(sourceText); + var scanner = new TypeScript.Scanner(fileName, text, 1 /* EcmaScript5 */, scannerWindow); + + var firstToken = scanner.scan(scannerDiagnostics, false); + + var importedFiles = []; + if (readImportFiles) { + processImports(text.lineMap(), scanner, firstToken, importedFiles); + } + + var properties = processTripleSlashDirectives(fileName, text.lineMap(), firstToken); + + scannerDiagnostics.length = 0; + return { referencedFiles: properties.referencedFiles, importedFiles: importedFiles, isLibFile: properties.noDefaultLib, diagnostics: properties.diagnostics }; + } + TypeScript.preProcessFile = preProcessFile; + + function getParseOptions(settings) { + return new TypeScript.ParseOptions(settings.codeGenTarget(), settings.allowAutomaticSemicolonInsertion()); + } + TypeScript.getParseOptions = getParseOptions; + + function getReferencedFiles(fileName, sourceText) { + return preProcessFile(fileName, sourceText, false).referencedFiles; + } + TypeScript.getReferencedFiles = getReferencedFiles; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ReferenceResolutionResult = (function () { + function ReferenceResolutionResult() { + this.resolvedFiles = []; + this.diagnostics = []; + this.seenNoDefaultLibTag = false; + } + return ReferenceResolutionResult; + })(); + TypeScript.ReferenceResolutionResult = ReferenceResolutionResult; + + var ReferenceLocation = (function () { + function ReferenceLocation(filePath, lineMap, position, length, isImported) { + this.filePath = filePath; + this.lineMap = lineMap; + this.position = position; + this.length = length; + this.isImported = isImported; + } + return ReferenceLocation; + })(); + + var ReferenceResolver = (function () { + function ReferenceResolver(inputFileNames, host, useCaseSensitiveFileResolution) { + this.useCaseSensitiveFileResolution = useCaseSensitiveFileResolution; + this.inputFileNames = inputFileNames; + this.host = host; + this.visited = {}; + } + ReferenceResolver.resolve = function (inputFileNames, host, useCaseSensitiveFileResolution) { + var resolver = new ReferenceResolver(inputFileNames, host, useCaseSensitiveFileResolution); + return resolver.resolveInputFiles(); + }; + + ReferenceResolver.prototype.resolveInputFiles = function () { + var _this = this; + var result = new ReferenceResolutionResult(); + + if (!this.inputFileNames || this.inputFileNames.length <= 0) { + return result; + } + + var referenceLocation = new ReferenceLocation(null, null, 0, 0, false); + this.inputFileNames.forEach(function (fileName) { + return _this.resolveIncludedFile(fileName, referenceLocation, result); + }); + + return result; + }; + + ReferenceResolver.prototype.resolveIncludedFile = function (path, referenceLocation, resolutionResult) { + var normalizedPath = this.getNormalizedFilePath(path, referenceLocation.filePath); + + if (this.isSameFile(normalizedPath, referenceLocation.filePath)) { + if (!referenceLocation.isImported) { + resolutionResult.diagnostics.push(new TypeScript.Diagnostic(referenceLocation.filePath, referenceLocation.lineMap, referenceLocation.position, referenceLocation.length, TypeScript.DiagnosticCode.A_file_cannot_have_a_reference_to_itself, null)); + } + + return normalizedPath; + } + + if (!TypeScript.isTSFile(normalizedPath) && !TypeScript.isDTSFile(normalizedPath)) { + var dtsFile = normalizedPath + ".d.ts"; + var tsFile = normalizedPath + ".ts"; + + if (this.host.fileExists(tsFile)) { + normalizedPath = tsFile; + } else { + normalizedPath = dtsFile; + } + } + + if (!this.host.fileExists(normalizedPath)) { + if (!referenceLocation.isImported) { + resolutionResult.diagnostics.push(new TypeScript.Diagnostic(referenceLocation.filePath, referenceLocation.lineMap, referenceLocation.position, referenceLocation.length, TypeScript.DiagnosticCode.Cannot_resolve_referenced_file_0, [path])); + } + + return normalizedPath; + } + + return this.resolveFile(normalizedPath, resolutionResult); + }; + + ReferenceResolver.prototype.resolveImportedFile = function (path, referenceLocation, resolutionResult) { + var isRelativePath = TypeScript.isRelative(path); + var isRootedPath = isRelativePath ? false : TypeScript.isRooted(path); + + if (isRelativePath || isRootedPath) { + return this.resolveIncludedFile(path, referenceLocation, resolutionResult); + } else { + var parentDirectory = this.host.getParentDirectory(referenceLocation.filePath); + var searchFilePath = null; + var dtsFileName = path + ".d.ts"; + var tsFilePath = path + ".ts"; + + var start = new Date().getTime(); + + do { + currentFilePath = this.host.resolveRelativePath(tsFilePath, parentDirectory); + if (this.host.fileExists(currentFilePath)) { + searchFilePath = currentFilePath; + break; + } + + var currentFilePath = this.host.resolveRelativePath(dtsFileName, parentDirectory); + if (this.host.fileExists(currentFilePath)) { + searchFilePath = currentFilePath; + break; + } + + parentDirectory = this.host.getParentDirectory(parentDirectory); + } while(parentDirectory); + + TypeScript.fileResolutionImportFileSearchTime += new Date().getTime() - start; + + if (!searchFilePath) { + return path; + } + + return this.resolveFile(searchFilePath, resolutionResult); + } + }; + + ReferenceResolver.prototype.resolveFile = function (normalizedPath, resolutionResult) { + var _this = this; + var visitedPath = this.isVisited(normalizedPath); + if (!visitedPath) { + this.recordVisitedFile(normalizedPath); + + var start = new Date().getTime(); + var scriptSnapshot = this.host.getScriptSnapshot(normalizedPath); + var totalTime = new Date().getTime() - start; + TypeScript.fileResolutionIOTime += totalTime; + + var lineMap = TypeScript.LineMap1.fromScriptSnapshot(scriptSnapshot); + var preprocessedFileInformation = TypeScript.preProcessFile(normalizedPath, scriptSnapshot); + resolutionResult.diagnostics.push.apply(resolutionResult.diagnostics, preprocessedFileInformation.diagnostics); + + if (preprocessedFileInformation.isLibFile) { + resolutionResult.seenNoDefaultLibTag = true; + } + + var normalizedReferencePaths = []; + preprocessedFileInformation.referencedFiles.forEach(function (fileReference) { + var currentReferenceLocation = new ReferenceLocation(normalizedPath, lineMap, fileReference.position, fileReference.length, false); + var normalizedReferencePath = _this.resolveIncludedFile(fileReference.path, currentReferenceLocation, resolutionResult); + normalizedReferencePaths.push(normalizedReferencePath); + }); + + var normalizedImportPaths = []; + for (var i = 0; i < preprocessedFileInformation.importedFiles.length; i++) { + var fileImport = preprocessedFileInformation.importedFiles[i]; + var currentReferenceLocation = new ReferenceLocation(normalizedPath, lineMap, fileImport.position, fileImport.length, true); + var normalizedImportPath = this.resolveImportedFile(fileImport.path, currentReferenceLocation, resolutionResult); + normalizedImportPaths.push(normalizedImportPath); + } + + resolutionResult.resolvedFiles.push({ + path: normalizedPath, + referencedFiles: normalizedReferencePaths, + importedFiles: normalizedImportPaths + }); + } else { + normalizedPath = visitedPath; + } + + return normalizedPath; + }; + + ReferenceResolver.prototype.getNormalizedFilePath = function (path, parentFilePath) { + var parentFileDirectory = parentFilePath ? this.host.getParentDirectory(parentFilePath) : ""; + var normalizedPath = this.host.resolveRelativePath(path, parentFileDirectory); + return normalizedPath; + }; + + ReferenceResolver.prototype.getUniqueFileId = function (filePath) { + return this.useCaseSensitiveFileResolution ? filePath : filePath.toLocaleUpperCase(); + }; + + ReferenceResolver.prototype.recordVisitedFile = function (filePath) { + this.visited[this.getUniqueFileId(filePath)] = filePath; + }; + + ReferenceResolver.prototype.isVisited = function (filePath) { + return this.visited[this.getUniqueFileId(filePath)]; + }; + + ReferenceResolver.prototype.isSameFile = function (filePath1, filePath2) { + if (!filePath1 || !filePath2) { + return false; + } + + if (this.useCaseSensitiveFileResolution) { + return filePath1 === filePath2; + } else { + return filePath1.toLocaleUpperCase() === filePath2.toLocaleUpperCase(); + } + }; + return ReferenceResolver; + })(); + TypeScript.ReferenceResolver = ReferenceResolver; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TextWriter = (function () { + function TextWriter(name, writeByteOrderMark, outputFileType) { + this.name = name; + this.writeByteOrderMark = writeByteOrderMark; + this.outputFileType = outputFileType; + this.contents = ""; + this.onNewLine = true; + } + TextWriter.prototype.Write = function (s) { + this.contents += s; + this.onNewLine = false; + }; + + TextWriter.prototype.WriteLine = function (s) { + this.contents += s; + this.contents += TypeScript.newLine(); + this.onNewLine = true; + }; + + TextWriter.prototype.Close = function () { + }; + + TextWriter.prototype.getOutputFile = function () { + return new TypeScript.OutputFile(this.name, this.writeByteOrderMark, this.contents, this.outputFileType); + }; + return TextWriter; + })(); + TypeScript.TextWriter = TextWriter; + + var DeclarationEmitter = (function () { + function DeclarationEmitter(emittingFileName, document, compiler, emitOptions, semanticInfoChain) { + this.emittingFileName = emittingFileName; + this.document = document; + this.compiler = compiler; + this.emitOptions = emitOptions; + this.semanticInfoChain = semanticInfoChain; + this.declFile = null; + this.indenter = new TypeScript.Indenter(); + this.emittedReferencePaths = false; + this.declFile = new TextWriter(emittingFileName, this.document.byteOrderMark !== 0 /* None */, 2 /* Declaration */); + } + DeclarationEmitter.prototype.getOutputFile = function () { + return this.declFile.getOutputFile(); + }; + + DeclarationEmitter.prototype.emitDeclarations = function (sourceUnit) { + this.emitDeclarationsForSourceUnit(sourceUnit); + }; + + DeclarationEmitter.prototype.emitDeclarationsForList = function (list) { + for (var i = 0, n = list.childCount(); i < n; i++) { + this.emitDeclarationsForAST(list.childAt(i)); + } + }; + + DeclarationEmitter.prototype.emitSeparatedList = function (list) { + for (var i = 0, n = list.nonSeparatorCount(); i < n; i++) { + this.emitDeclarationsForAST(list.nonSeparatorAt(i)); + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForAST = function (ast) { + switch (ast.kind()) { + case 148 /* VariableStatement */: + return this.emitDeclarationsForVariableStatement(ast); + case 141 /* PropertySignature */: + return this.emitPropertySignature(ast); + case 225 /* VariableDeclarator */: + return this.emitVariableDeclarator(ast, true, true); + case 136 /* MemberVariableDeclaration */: + return this.emitDeclarationsForMemberVariableDeclaration(ast); + case 137 /* ConstructorDeclaration */: + return this.emitDeclarationsForConstructorDeclaration(ast); + case 139 /* GetAccessor */: + return this.emitDeclarationsForGetAccessor(ast); + case 140 /* SetAccessor */: + return this.emitDeclarationsForSetAccessor(ast); + case 138 /* IndexMemberDeclaration */: + return this.emitIndexMemberDeclaration(ast); + case 144 /* IndexSignature */: + return this.emitIndexSignature(ast); + case 142 /* CallSignature */: + return this.emitCallSignature(ast); + case 143 /* ConstructSignature */: + return this.emitConstructSignature(ast); + case 145 /* MethodSignature */: + return this.emitMethodSignature(ast); + case 129 /* FunctionDeclaration */: + return this.emitDeclarationsForFunctionDeclaration(ast); + case 135 /* MemberFunctionDeclaration */: + return this.emitMemberFunctionDeclaration(ast); + case 131 /* ClassDeclaration */: + return this.emitDeclarationsForClassDeclaration(ast); + case 128 /* InterfaceDeclaration */: + return this.emitDeclarationsForInterfaceDeclaration(ast); + case 133 /* ImportDeclaration */: + return this.emitDeclarationsForImportDeclaration(ast); + case 130 /* ModuleDeclaration */: + return this.emitDeclarationsForModuleDeclaration(ast); + case 132 /* EnumDeclaration */: + return this.emitDeclarationsForEnumDeclaration(ast); + case 134 /* ExportAssignment */: + return this.emitDeclarationsForExportAssignment(ast); + } + }; + + DeclarationEmitter.prototype.getIndentString = function (declIndent) { + if (typeof declIndent === "undefined") { declIndent = false; } + return this.indenter.getIndent(); + }; + + DeclarationEmitter.prototype.emitIndent = function () { + this.declFile.Write(this.getIndentString()); + }; + + DeclarationEmitter.prototype.canEmitDeclarations = function (declAST) { + var container = DeclarationEmitter.getEnclosingContainer(declAST); + if (container.kind() === 130 /* ModuleDeclaration */ || container.kind() === 120 /* SourceUnit */) { + var pullDecl = this.semanticInfoChain.getDeclForAST(declAST); + if (!TypeScript.hasFlag(pullDecl.flags, 1 /* Exported */)) { + var start = new Date().getTime(); + var declSymbol = this.semanticInfoChain.getSymbolForAST(declAST); + var result = declSymbol && declSymbol.isExternallyVisible(); + TypeScript.declarationEmitIsExternallyVisibleTime += new Date().getTime() - start; + + return result; + } + } + + return true; + }; + + DeclarationEmitter.prototype.getDeclFlagsString = function (pullDecl, typeString) { + var result = this.getIndentString(); + var pullFlags = pullDecl.flags; + + if (TypeScript.hasFlag(pullFlags, 16 /* Static */)) { + if (TypeScript.hasFlag(pullFlags, 2 /* Private */)) { + result += "private "; + } + result += "static "; + } else { + if (TypeScript.hasFlag(pullFlags, 2 /* Private */)) { + result += "private "; + } else if (TypeScript.hasFlag(pullFlags, 4 /* Public */)) { + result += "public "; + } else { + var emitDeclare = !TypeScript.hasFlag(pullFlags, 1 /* Exported */); + + var declAST = this.semanticInfoChain.getASTForDecl(pullDecl); + var container = DeclarationEmitter.getEnclosingContainer(declAST); + + var isExternalModule = container.kind() === 120 /* SourceUnit */ && this.document.isExternalModule(); + + if (isExternalModule && TypeScript.hasFlag(pullFlags, 1 /* Exported */)) { + result += "export "; + emitDeclare = true; + } + + if (isExternalModule || container.kind() === 120 /* SourceUnit */) { + if (emitDeclare && typeString !== "interface" && typeString !== "import") { + result += "declare "; + } + } + + result += typeString + " "; + } + } + + return result; + }; + + DeclarationEmitter.prototype.emitDeclFlags = function (declarationAST, typeString) { + this.declFile.Write(this.getDeclFlagsString(this.semanticInfoChain.getDeclForAST(declarationAST), typeString)); + }; + + 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 if (memberName.isArray()) { + 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 (ast, type) { + var declarationContainerAst = DeclarationEmitter.getEnclosingContainer(ast); + + var start = new Date().getTime(); + var declarationContainerDecl = this.semanticInfoChain.getDeclForAST(declarationContainerAst); + + var declarationPullSymbol = declarationContainerDecl.getSymbol(); + TypeScript.declarationEmitTypeSignatureTime += new Date().getTime() - start; + + var isNotAGenericType = ast.kind() !== 126 /* GenericType */; + + var typeNameMembers = type.getScopedNameEx(declarationPullSymbol, false, false, false, false, false, isNotAGenericType); + this.emitTypeNamesMember(typeNameMembers); + }; + + DeclarationEmitter.prototype.emitComment = function (comment) { + var text = TypeScript.getTrimmedTextLines(comment); + if (this.declFile.onNewLine) { + this.emitIndent(); + } else if (comment.kind() !== 6 /* MultiLineCommentTrivia */) { + 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.kind() !== 6 /* MultiLineCommentTrivia */) { + this.declFile.WriteLine(""); + } else { + this.declFile.Write(" "); + } + }; + + DeclarationEmitter.prototype.emitDeclarationComments = function (astOrSymbol, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + if (this.emitOptions.compilationSettings().removeComments()) { + return; + } + + var declComments = astOrSymbol.docComments ? astOrSymbol.docComments() : TypeScript.ASTHelpers.docComments(astOrSymbol); + this.writeDeclarationComments(declComments, endLine); + }; + + DeclarationEmitter.prototype.writeDeclarationComments = function (declComments, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + 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.emitTypeOfVariableDeclaratorOrParameter = function (boundDecl) { + var start = new Date().getTime(); + var decl = this.semanticInfoChain.getDeclForAST(boundDecl); + var pullSymbol = decl.getSymbol(); + TypeScript.declarationEmitGetBoundDeclTypeTime += new Date().getTime() - start; + + var type = pullSymbol.type; + TypeScript.Debug.assert(type); + + this.declFile.Write(": "); + this.emitTypeSignature(boundDecl, type); + }; + + DeclarationEmitter.prototype.emitPropertySignature = function (varDecl) { + this.emitDeclarationComments(varDecl); + this.emitIndent(); + this.declFile.Write(varDecl.propertyName.text()); + if (varDecl.questionToken) { + this.declFile.Write("?"); + } + + this.emitTypeOfVariableDeclaratorOrParameter(varDecl); + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitVariableDeclarator = function (varDecl, isFirstVarInList, isLastVarInList) { + if (this.canEmitDeclarations(varDecl)) { + this.emitDeclarationComments(varDecl); + + if (isFirstVarInList) { + this.emitDeclFlags(varDecl, "var"); + } + + this.declFile.Write(varDecl.propertyName.text()); + + if (!TypeScript.hasModifier(TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), 2 /* Private */)) { + this.emitTypeOfVariableDeclaratorOrParameter(varDecl); + } + + if (isLastVarInList) { + this.declFile.WriteLine(";"); + } else { + this.declFile.Write(", "); + } + } + }; + + DeclarationEmitter.prototype.emitClassElementModifiers = function (modifiers) { + if (TypeScript.hasModifier(modifiers, 16 /* Static */)) { + if (TypeScript.hasModifier(modifiers, 2 /* Private */)) { + this.declFile.Write("private "); + } + this.declFile.Write("static "); + } else { + if (TypeScript.hasModifier(modifiers, 2 /* Private */)) { + this.declFile.Write("private "); + } else { + this.declFile.Write("public "); + } + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForMemberVariableDeclaration = function (varDecl) { + if (this.canEmitDeclarations(varDecl)) { + this.emitDeclarationComments(varDecl); + + this.declFile.Write(this.getIndentString()); + this.emitClassElementModifiers(varDecl.modifiers); + ; + + this.declFile.Write(varDecl.variableDeclarator.propertyName.text()); + + if (!TypeScript.hasModifier(varDecl.modifiers, 2 /* Private */)) { + this.emitTypeOfVariableDeclaratorOrParameter(varDecl); + } + + this.declFile.WriteLine(";"); + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForVariableStatement = function (variableStatement) { + this.emitDeclarationsForVariableDeclaration(variableStatement.declaration); + }; + + DeclarationEmitter.prototype.emitDeclarationsForVariableDeclaration = function (variableDeclaration) { + var varListCount = variableDeclaration.declarators.nonSeparatorCount(); + for (var i = 0; i < varListCount; i++) { + this.emitVariableDeclarator(variableDeclaration.declarators.nonSeparatorAt(i), i === 0, i === varListCount - 1); + } + }; + + DeclarationEmitter.prototype.emitArgDecl = function (argDecl, id, isOptional, isPrivate) { + this.indenter.increaseIndent(); + + this.emitDeclarationComments(argDecl, false); + this.declFile.Write(id.text()); + if (isOptional) { + this.declFile.Write("?"); + } + + this.indenter.decreaseIndent(); + + if (!isPrivate) { + this.emitTypeOfVariableDeclaratorOrParameter(argDecl); + } + }; + + DeclarationEmitter.prototype.isOverloadedCallSignature = function (funcDecl) { + var start = new Date().getTime(); + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSymbol = functionDecl.getSymbol(); + TypeScript.declarationEmitIsOverloadedCallSignatureTime += new Date().getTime() - start; + + var funcTypeSymbol = funcSymbol.type; + var signatures = funcTypeSymbol.getCallSignatures(); + var result = signatures && signatures.length > 1; + + return result; + }; + + DeclarationEmitter.prototype.emitDeclarationsForConstructorDeclaration = function (funcDecl) { + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + var funcTypeSymbol = funcSymbol.type; + if (funcDecl.block) { + var constructSignatures = funcTypeSymbol.getConstructSignatures(); + if (constructSignatures && constructSignatures.length > 1) { + return; + } + } + + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write("constructor"); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitParameterList = function (isPrivate, parameterList) { + this.declFile.Write("("); + this.emitParameters(isPrivate, TypeScript.ASTHelpers.parametersFromParameterList(parameterList)); + this.declFile.Write(")"); + }; + + DeclarationEmitter.prototype.emitParameters = function (isPrivate, parameterList) { + var hasLastParameterRestParameter = parameterList.lastParameterIsRest(); + var argsLen = parameterList.length; + if (hasLastParameterRestParameter) { + argsLen--; + } + + for (var i = 0; i < argsLen; i++) { + this.emitArgDecl(parameterList.astAt(i), parameterList.identifierAt(i), parameterList.isOptionalAt(i), isPrivate); + if (i < (argsLen - 1)) { + this.declFile.Write(", "); + } + } + + if (hasLastParameterRestParameter) { + if (parameterList.length > 1) { + this.declFile.Write(", ..."); + } else { + this.declFile.Write("..."); + } + + var index = parameterList.length - 1; + this.emitArgDecl(parameterList.astAt(index), parameterList.identifierAt(index), parameterList.isOptionalAt(index), isPrivate); + } + }; + + DeclarationEmitter.prototype.emitMemberFunctionDeclaration = function (funcDecl) { + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + var funcTypeSymbol = funcSymbol.type; + if (funcDecl.block) { + var constructSignatures = funcTypeSymbol.getConstructSignatures(); + if (constructSignatures && constructSignatures.length > 1) { + return; + } else if (this.isOverloadedCallSignature(funcDecl)) { + return; + } + } else if (TypeScript.hasModifier(funcDecl.modifiers, 2 /* Private */) && this.isOverloadedCallSignature(funcDecl)) { + var callSignatures = funcTypeSymbol.getCallSignatures(); + TypeScript.Debug.assert(callSignatures && callSignatures.length > 1); + var firstSignature = callSignatures[0].isDefinition() ? callSignatures[1] : callSignatures[0]; + var firstSignatureDecl = firstSignature.getDeclarations()[0]; + var firstFuncDecl = this.semanticInfoChain.getASTForDecl(firstSignatureDecl); + if (firstFuncDecl !== funcDecl) { + return; + } + } + + if (!this.canEmitDeclarations(funcDecl)) { + return; + } + + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitDeclarationComments(funcDecl); + + this.emitDeclFlags(funcDecl, "function"); + var id = funcDecl.propertyName.text(); + this.declFile.Write(id); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + var isPrivate = TypeScript.hasModifier(funcDecl.modifiers, 2 /* Private */); + + this.emitParameterList(isPrivate, funcDecl.callSignature.parameterList); + + if (!isPrivate) { + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + this.emitTypeSignature(funcDecl, returnType); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitCallSignature = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + this.emitDeclarationComments(funcDecl); + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.typeParameterList, funcSignature); + + this.emitIndent(); + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitConstructSignature = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write("new"); + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitMethodSignature = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write(funcDecl.propertyName.text()); + if (funcDecl.questionToken) { + this.declFile.Write("? "); + } + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForFunctionDeclaration = function (funcDecl) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + + var start = new Date().getTime(); + var funcSymbol = this.semanticInfoChain.getSymbolForAST(funcDecl); + + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime += new Date().getTime() - start; + + if (funcDecl.block) { + var funcTypeSymbol = funcSymbol.type; + var constructSignatures = funcTypeSymbol.getConstructSignatures(); + if (constructSignatures && constructSignatures.length > 1) { + return; + } else if (this.isOverloadedCallSignature(funcDecl)) { + return; + } + } + + if (!this.canEmitDeclarations(funcDecl)) { + return; + } + + this.emitDeclarationComments(funcDecl); + + var id = funcDecl.identifier.text(); + this.emitDeclFlags(funcDecl, "function"); + if (id !== "" || !funcDecl.identifier || funcDecl.identifier.text().length > 0) { + this.declFile.Write(id); + } else if (funcPullDecl.kind === 2097152 /* ConstructSignature */) { + this.declFile.Write("new"); + } + + var funcSignature = funcPullDecl.getSignatureSymbol(); + this.emitTypeParameters(funcDecl.callSignature.typeParameterList, funcSignature); + + this.declFile.Write("("); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList)); + this.declFile.Write(")"); + + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + if (returnType) { + this.emitTypeSignature(funcDecl, returnType); + } else { + this.declFile.Write("any"); + } + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitIndexMemberDeclaration = function (funcDecl) { + this.emitDeclarationsForAST(funcDecl.indexSignature); + }; + + DeclarationEmitter.prototype.emitIndexSignature = function (funcDecl) { + if (!this.canEmitDeclarations(funcDecl)) { + return; + } + + this.emitDeclarationComments(funcDecl); + + this.emitIndent(); + this.declFile.Write("["); + this.emitParameters(false, TypeScript.ASTHelpers.parametersFromParameter(funcDecl.parameter)); + this.declFile.Write("]"); + + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSignature = funcPullDecl.getSignatureSymbol(); + var returnType = funcSignature.returnType; + this.declFile.Write(": "); + this.emitTypeSignature(funcDecl, returnType); + + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitBaseList = function (bases, useExtendsList) { + if (bases && (bases.nonSeparatorCount() > 0)) { + var qual = useExtendsList ? "extends" : "implements"; + this.declFile.Write(" " + qual + " "); + var basesLen = bases.nonSeparatorCount(); + for (var i = 0; i < basesLen; i++) { + if (i > 0) { + this.declFile.Write(", "); + } + var base = bases.nonSeparatorAt(i); + var baseType = this.semanticInfoChain.getSymbolForAST(base); + this.emitTypeSignature(base, baseType); + } + } + }; + + DeclarationEmitter.prototype.emitAccessorDeclarationComments = function (funcDecl) { + if (this.emitOptions.compilationSettings().removeComments()) { + return; + } + + var start = new Date().getTime(); + var accessors = TypeScript.PullHelpers.getGetterAndSetterFunction(funcDecl, this.semanticInfoChain); + TypeScript.declarationEmitGetAccessorFunctionTime += new Date().getTime(); + + var comments = []; + if (accessors.getter) { + comments = comments.concat(TypeScript.ASTHelpers.docComments(accessors.getter)); + } + if (accessors.setter) { + comments = comments.concat(TypeScript.ASTHelpers.docComments(accessors.setter)); + } + + this.writeDeclarationComments(comments); + }; + + DeclarationEmitter.prototype.emitDeclarationsForGetAccessor = function (funcDecl) { + this.emitMemberAccessorDeclaration(funcDecl, funcDecl.modifiers, funcDecl.propertyName); + }; + + DeclarationEmitter.prototype.emitDeclarationsForSetAccessor = function (funcDecl) { + this.emitMemberAccessorDeclaration(funcDecl, funcDecl.modifiers, funcDecl.propertyName); + }; + + DeclarationEmitter.prototype.emitMemberAccessorDeclaration = function (funcDecl, modifiers, name) { + var start = new Date().getTime(); + var accessorSymbol = TypeScript.PullHelpers.getAccessorSymbol(funcDecl, this.semanticInfoChain); + TypeScript.declarationEmitGetAccessorFunctionTime += new Date().getTime(); + + if (funcDecl.kind() === 140 /* SetAccessor */ && accessorSymbol.getGetter()) { + return; + } + + var isPrivate = TypeScript.hasModifier(modifiers, 2 /* Private */); + this.emitAccessorDeclarationComments(funcDecl); + this.declFile.Write(this.getIndentString()); + this.emitClassElementModifiers(modifiers); + this.declFile.Write(name.text()); + if (!isPrivate) { + this.declFile.Write(" : "); + var type = accessorSymbol.type; + this.emitTypeSignature(funcDecl, type); + } + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { + var argsLen = funcDecl.callSignature.parameterList.parameters.nonSeparatorCount(); + if (TypeScript.lastParameterIsRest(funcDecl.callSignature.parameterList)) { + argsLen--; + } + + for (var i = 0; i < argsLen; i++) { + var parameter = funcDecl.callSignature.parameterList.parameters.nonSeparatorAt(i); + var parameterDecl = this.semanticInfoChain.getDeclForAST(parameter); + if (TypeScript.hasFlag(parameterDecl.flags, 8388608 /* PropertyParameter */)) { + var funcPullDecl = this.semanticInfoChain.getDeclForAST(funcDecl); + this.emitDeclarationComments(parameter); + this.declFile.Write(this.getIndentString()); + this.emitClassElementModifiers(parameter.modifiers); + this.declFile.Write(parameter.identifier.text()); + + if (!TypeScript.hasModifier(parameter.modifiers, 2 /* Private */)) { + this.emitTypeOfVariableDeclaratorOrParameter(parameter); + } + this.declFile.WriteLine(";"); + } + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForClassDeclaration = function (classDecl) { + if (!this.canEmitDeclarations(classDecl)) { + return; + } + + var className = classDecl.identifier.text(); + this.emitDeclarationComments(classDecl); + var classPullDecl = this.semanticInfoChain.getDeclForAST(classDecl); + this.emitDeclFlags(classDecl, "class"); + this.declFile.Write(className); + + this.emitTypeParameters(classDecl.typeParameterList); + this.emitHeritageClauses(classDecl.heritageClauses); + this.declFile.WriteLine(" {"); + + this.indenter.increaseIndent(); + var constructorDecl = TypeScript.getLastConstructor(classDecl); + if (constructorDecl) { + this.emitClassMembersFromConstructorDefinition(constructorDecl); + } + + this.emitDeclarationsForList(classDecl.classElements); + + this.indenter.decreaseIndent(); + + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitHeritageClauses = function (clauses) { + if (clauses) { + for (var i = 0, n = clauses.childCount(); i < n; i++) { + this.emitHeritageClause(clauses.childAt(i)); + } + } + }; + + DeclarationEmitter.prototype.emitHeritageClause = function (clause) { + this.emitBaseList(clause.typeNames, clause.kind() === 230 /* ExtendsHeritageClause */); + }; + + DeclarationEmitter.getEnclosingContainer = function (ast) { + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(ast); + ast = enclosingModule || ast; + + ast = ast.parent; + while (ast) { + if (ast.kind() === 131 /* ClassDeclaration */ || ast.kind() === 128 /* InterfaceDeclaration */ || ast.kind() === 130 /* ModuleDeclaration */ || ast.kind() === 120 /* SourceUnit */) { + return ast; + } + + ast = ast.parent; + } + + return null; + }; + + DeclarationEmitter.prototype.emitTypeParameters = function (typeParams, funcSignature) { + if (!typeParams || !typeParams.typeParameters.nonSeparatorCount()) { + return; + } + + this.declFile.Write("<"); + var containerAst = DeclarationEmitter.getEnclosingContainer(typeParams); + + var start = new Date().getTime(); + var containerDecl = this.semanticInfoChain.getDeclForAST(containerAst); + var containerSymbol = containerDecl.getSymbol(); + TypeScript.declarationEmitGetTypeParameterSymbolTime += new Date().getTime() - start; + + var typars; + if (funcSignature) { + typars = funcSignature.getTypeParameters(); + } else { + typars = containerSymbol.getTypeArgumentsOrTypeParameters(); + } + + for (var i = 0; i < typars.length; i++) { + if (i) { + this.declFile.Write(", "); + } + + var memberName = typars[i].getScopedNameEx(containerSymbol, false, true); + this.emitTypeNamesMember(memberName); + } + + this.declFile.Write(">"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForInterfaceDeclaration = function (interfaceDecl) { + if (!this.canEmitDeclarations(interfaceDecl)) { + return; + } + + var interfaceName = interfaceDecl.identifier.text(); + this.emitDeclarationComments(interfaceDecl); + var interfacePullDecl = this.semanticInfoChain.getDeclForAST(interfaceDecl); + this.emitDeclFlags(interfaceDecl, "interface"); + this.declFile.Write(interfaceName); + + this.emitTypeParameters(interfaceDecl.typeParameterList); + this.emitHeritageClauses(interfaceDecl.heritageClauses); + this.declFile.WriteLine(" {"); + + this.indenter.increaseIndent(); + + this.emitSeparatedList(interfaceDecl.body.typeMembers); + + this.indenter.decreaseIndent(); + + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForImportDeclaration = function (importDeclAST) { + var importDecl = this.semanticInfoChain.getDeclForAST(importDeclAST); + var importSymbol = importDecl.getSymbol(); + var isExportedImportDecl = TypeScript.hasModifier(importDeclAST.modifiers, 1 /* Exported */); + + if (isExportedImportDecl || importSymbol.typeUsedExternally() || TypeScript.PullContainerSymbol.usedAsSymbol(importSymbol.getContainer(), importSymbol)) { + this.emitDeclarationComments(importDeclAST); + this.emitIndent(); + if (isExportedImportDecl) { + this.declFile.Write("export "); + } + this.declFile.Write("import "); + this.declFile.Write(importDeclAST.identifier.text() + " = "); + if (importDeclAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + this.declFile.WriteLine("require(" + importDeclAST.moduleReference.stringLiteral.text() + ");"); + } else { + this.declFile.WriteLine(TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(importDeclAST.moduleReference.moduleName) + ";"); + } + } + }; + + DeclarationEmitter.prototype.emitDeclarationsForEnumDeclaration = function (moduleDecl) { + if (!this.canEmitDeclarations(moduleDecl)) { + return; + } + + this.emitDeclarationComments(moduleDecl); + var modulePullDecl = this.semanticInfoChain.getDeclForAST(moduleDecl); + this.emitDeclFlags(moduleDecl, "enum"); + this.declFile.WriteLine(moduleDecl.identifier.text() + " {"); + + this.indenter.increaseIndent(); + var membersLen = moduleDecl.enumElements.nonSeparatorCount(); + for (var j = 0; j < membersLen; j++) { + var memberDecl = moduleDecl.enumElements.nonSeparatorAt(j); + var enumElement = memberDecl; + var enumElementDecl = this.semanticInfoChain.getDeclForAST(enumElement); + this.emitDeclarationComments(enumElement); + this.emitIndent(); + this.declFile.Write(enumElement.propertyName.text()); + if (enumElementDecl.constantValue !== null) { + this.declFile.Write(" = " + enumElementDecl.constantValue); + } + this.declFile.WriteLine(","); + } + this.indenter.decreaseIndent(); + + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForModuleDeclaration = function (moduleDecl) { + var name = moduleDecl.stringLiteral || TypeScript.ArrayUtilities.first(TypeScript.ASTHelpers.getModuleNames(moduleDecl.name)); + if (!this.canEmitDeclarations(name)) { + return; + } + + this.emitDeclarationComments(moduleDecl); + this.emitDeclFlags(name, "module"); + + if (moduleDecl.stringLiteral) { + this.declFile.Write(moduleDecl.stringLiteral.text()); + } else { + this.declFile.Write(TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(moduleDecl.name)); + } + + this.declFile.WriteLine(" {"); + this.indenter.increaseIndent(); + + this.emitDeclarationsForList(moduleDecl.moduleElements); + + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.WriteLine("}"); + }; + + DeclarationEmitter.prototype.emitDeclarationsForExportAssignment = function (ast) { + this.emitIndent(); + this.declFile.Write("export = "); + this.declFile.Write(ast.identifier.text()); + this.declFile.WriteLine(";"); + }; + + DeclarationEmitter.prototype.resolveScriptReference = function (document, reference) { + if (!this.emitOptions.compilationSettings().noResolve() || TypeScript.isRooted(reference)) { + return reference; + } + + var documentDir = TypeScript.convertToDirectoryPath(TypeScript.switchToForwardSlashes(TypeScript.getRootFilePath(document.fileName))); + var resolvedReferencePath = this.emitOptions.resolvePath(documentDir + reference); + return resolvedReferencePath; + }; + + DeclarationEmitter.prototype.emitReferencePaths = function (sourceUnit) { + if (this.emittedReferencePaths) { + return; + } + + var documents = []; + if (this.document.emitToOwnOutputFile()) { + var scriptReferences = this.document.referencedFiles; + var addedGlobalDocument = false; + for (var j = 0; j < scriptReferences.length; j++) { + var currentReference = this.resolveScriptReference(this.document, scriptReferences[j]); + var document = this.compiler.getDocument(currentReference); + + if (document && (document.emitToOwnOutputFile() || document.isDeclareFile() || !addedGlobalDocument)) { + documents = documents.concat(document); + + if (!document.isDeclareFile() && document.isExternalModule()) { + addedGlobalDocument = true; + } + } + } + } else { + var fileNames = this.compiler.fileNames(); + for (var i = 0; i < fileNames.length; i++) { + var doc = this.compiler.getDocument(fileNames[i]); + if (!doc.isDeclareFile() && !doc.isExternalModule()) { + var scriptReferences = doc.referencedFiles; + for (var j = 0; j < scriptReferences.length; j++) { + var currentReference = this.resolveScriptReference(doc, scriptReferences[j]); + var document = this.compiler.getDocument(currentReference); + + if (document && (document.isDeclareFile() || document.isExternalModule())) { + for (var k = 0; k < documents.length; k++) { + if (documents[k] === document) { + break; + } + } + + if (k === documents.length) { + documents = documents.concat(document); + } + } + } + } + } + } + + var emittingFilePath = documents.length ? TypeScript.getRootFilePath(this.emittingFileName) : null; + for (var i = 0; i < documents.length; i++) { + var document = documents[i]; + var declFileName; + if (document.isDeclareFile()) { + declFileName = document.fileName; + } else { + declFileName = this.compiler.mapOutputFileName(document, this.emitOptions, TypeScript.TypeScriptCompiler.mapToDTSFileName); + } + + declFileName = TypeScript.getRelativePathToFixedPath(emittingFilePath, declFileName, false); + this.declFile.WriteLine('/// '); + } + + this.emittedReferencePaths = true; + }; + + DeclarationEmitter.prototype.emitDeclarationsForSourceUnit = function (sourceUnit) { + this.emitReferencePaths(sourceUnit); + this.emitDeclarationsForList(sourceUnit.moduleElements); + }; + return DeclarationEmitter; + })(); + TypeScript.DeclarationEmitter = DeclarationEmitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var BloomFilter = (function () { + function BloomFilter(expectedCount) { + var m = Math.max(1, BloomFilter.computeM(expectedCount)); + var k = Math.max(1, BloomFilter.computeK(expectedCount)); + ; + + var sizeInEvenBytes = (m + 7) & ~7; + + this.bitArray = []; + for (var i = 0, len = sizeInEvenBytes; i < len; i++) { + this.bitArray[i] = false; + } + this.hashFunctionCount = k; + } + BloomFilter.computeM = function (expectedCount) { + var p = BloomFilter.falsePositiveProbability; + var n = expectedCount; + + var numerator = n * Math.log(p); + var denominator = Math.log(1.0 / Math.pow(2.0, Math.log(2.0))); + return Math.ceil(numerator / denominator); + }; + + BloomFilter.computeK = function (expectedCount) { + var n = expectedCount; + var m = BloomFilter.computeM(expectedCount); + + var temp = Math.log(2.0) * m / n; + return Math.round(temp); + }; + + BloomFilter.prototype.computeHash = function (key, seed) { + return TypeScript.Hash.computeMurmur2StringHashCode(key, seed); + }; + + BloomFilter.prototype.addKeys = function (keys) { + for (var name in keys) { + if (keys[name]) { + this.add(name); + } + } + }; + + BloomFilter.prototype.add = function (value) { + for (var i = 0; i < this.hashFunctionCount; i++) { + var hash = this.computeHash(value, i); + hash = hash % this.bitArray.length; + this.bitArray[Math.abs(hash)] = true; + } + }; + + BloomFilter.prototype.probablyContains = function (value) { + for (var i = 0; i < this.hashFunctionCount; i++) { + var hash = this.computeHash(value, i); + hash = hash % this.bitArray.length; + if (!this.bitArray[Math.abs(hash)]) { + return false; + } + } + + return true; + }; + + BloomFilter.prototype.isEquivalent = function (filter) { + return BloomFilter.isEquivalent(this.bitArray, filter.bitArray) && this.hashFunctionCount === filter.hashFunctionCount; + }; + + BloomFilter.isEquivalent = function (array1, array2) { + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; i++) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; + }; + BloomFilter.falsePositiveProbability = 0.0001; + return BloomFilter; + })(); + TypeScript.BloomFilter = BloomFilter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var IdentifierWalker = (function (_super) { + __extends(IdentifierWalker, _super); + function IdentifierWalker(list) { + _super.call(this); + this.list = list; + } + IdentifierWalker.prototype.visitToken = function (token) { + this.list[token.text()] = true; + }; + return IdentifierWalker; + })(TypeScript.SyntaxWalker); + TypeScript.IdentifierWalker = IdentifierWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CompilationSettings = (function () { + function CompilationSettings() { + this.propagateEnumConstants = false; + this.removeComments = false; + this.watch = false; + this.noResolve = false; + this.allowAutomaticSemicolonInsertion = true; + this.noImplicitAny = false; + this.noLib = false; + this.codeGenTarget = 0 /* EcmaScript3 */; + this.moduleGenTarget = 0 /* Unspecified */; + this.outFileOption = ""; + this.outDirOption = ""; + this.mapSourceFiles = false; + this.mapRoot = ""; + this.sourceRoot = ""; + this.generateDeclarationFiles = false; + this.useCaseSensitiveFileResolution = false; + this.gatherDiagnostics = false; + this.codepage = null; + this.createFileLog = false; + } + return CompilationSettings; + })(); + TypeScript.CompilationSettings = CompilationSettings; + + var ImmutableCompilationSettings = (function () { + function ImmutableCompilationSettings(propagateEnumConstants, removeComments, watch, noResolve, allowAutomaticSemicolonInsertion, noImplicitAny, noLib, codeGenTarget, moduleGenTarget, outFileOption, outDirOption, mapSourceFiles, mapRoot, sourceRoot, generateDeclarationFiles, useCaseSensitiveFileResolution, gatherDiagnostics, codepage, createFileLog) { + this._propagateEnumConstants = propagateEnumConstants; + this._removeComments = removeComments; + this._watch = watch; + this._noResolve = noResolve; + this._allowAutomaticSemicolonInsertion = allowAutomaticSemicolonInsertion; + this._noImplicitAny = noImplicitAny; + this._noLib = noLib; + this._codeGenTarget = codeGenTarget; + this._moduleGenTarget = moduleGenTarget; + this._outFileOption = outFileOption; + this._outDirOption = outDirOption; + this._mapSourceFiles = mapSourceFiles; + this._mapRoot = mapRoot; + this._sourceRoot = sourceRoot; + this._generateDeclarationFiles = generateDeclarationFiles; + this._useCaseSensitiveFileResolution = useCaseSensitiveFileResolution; + this._gatherDiagnostics = gatherDiagnostics; + this._codepage = codepage; + this._createFileLog = createFileLog; + } + ImmutableCompilationSettings.prototype.propagateEnumConstants = function () { + return this._propagateEnumConstants; + }; + ImmutableCompilationSettings.prototype.removeComments = function () { + return this._removeComments; + }; + ImmutableCompilationSettings.prototype.watch = function () { + return this._watch; + }; + ImmutableCompilationSettings.prototype.noResolve = function () { + return this._noResolve; + }; + ImmutableCompilationSettings.prototype.allowAutomaticSemicolonInsertion = function () { + return this._allowAutomaticSemicolonInsertion; + }; + ImmutableCompilationSettings.prototype.noImplicitAny = function () { + return this._noImplicitAny; + }; + ImmutableCompilationSettings.prototype.noLib = function () { + return this._noLib; + }; + ImmutableCompilationSettings.prototype.codeGenTarget = function () { + return this._codeGenTarget; + }; + ImmutableCompilationSettings.prototype.moduleGenTarget = function () { + return this._moduleGenTarget; + }; + ImmutableCompilationSettings.prototype.outFileOption = function () { + return this._outFileOption; + }; + ImmutableCompilationSettings.prototype.outDirOption = function () { + return this._outDirOption; + }; + ImmutableCompilationSettings.prototype.mapSourceFiles = function () { + return this._mapSourceFiles; + }; + ImmutableCompilationSettings.prototype.mapRoot = function () { + return this._mapRoot; + }; + ImmutableCompilationSettings.prototype.sourceRoot = function () { + return this._sourceRoot; + }; + ImmutableCompilationSettings.prototype.generateDeclarationFiles = function () { + return this._generateDeclarationFiles; + }; + ImmutableCompilationSettings.prototype.useCaseSensitiveFileResolution = function () { + return this._useCaseSensitiveFileResolution; + }; + ImmutableCompilationSettings.prototype.gatherDiagnostics = function () { + return this._gatherDiagnostics; + }; + ImmutableCompilationSettings.prototype.codepage = function () { + return this._codepage; + }; + ImmutableCompilationSettings.prototype.createFileLog = function () { + return this._createFileLog; + }; + + ImmutableCompilationSettings.defaultSettings = function () { + if (!ImmutableCompilationSettings._defaultSettings) { + ImmutableCompilationSettings._defaultSettings = ImmutableCompilationSettings.fromCompilationSettings(new CompilationSettings()); + } + + return ImmutableCompilationSettings._defaultSettings; + }; + + ImmutableCompilationSettings.fromCompilationSettings = function (settings) { + return new ImmutableCompilationSettings(settings.propagateEnumConstants, settings.removeComments, settings.watch, settings.noResolve, settings.allowAutomaticSemicolonInsertion, settings.noImplicitAny, settings.noLib, settings.codeGenTarget, settings.moduleGenTarget, settings.outFileOption, settings.outDirOption, settings.mapSourceFiles, settings.mapRoot, settings.sourceRoot, settings.generateDeclarationFiles, settings.useCaseSensitiveFileResolution, settings.gatherDiagnostics, settings.codepage, settings.createFileLog); + }; + + ImmutableCompilationSettings.prototype.toCompilationSettings = function () { + var result = new CompilationSettings(); + + var thisAsIndexable = this; + var resultAsIndexable = result; + for (var name in this) { + if (this.hasOwnProperty(name) && TypeScript.StringUtilities.startsWith(name, "_")) { + resultAsIndexable[name.substr(1)] = thisAsIndexable[name]; + } + } + + return result; + }; + return ImmutableCompilationSettings; + })(); + TypeScript.ImmutableCompilationSettings = ImmutableCompilationSettings; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (PullElementFlags) { + PullElementFlags[PullElementFlags["None"] = 0] = "None"; + PullElementFlags[PullElementFlags["Exported"] = 1] = "Exported"; + PullElementFlags[PullElementFlags["Private"] = 1 << 1] = "Private"; + PullElementFlags[PullElementFlags["Public"] = 1 << 2] = "Public"; + PullElementFlags[PullElementFlags["Ambient"] = 1 << 3] = "Ambient"; + PullElementFlags[PullElementFlags["Static"] = 1 << 4] = "Static"; + PullElementFlags[PullElementFlags["Optional"] = 1 << 7] = "Optional"; + PullElementFlags[PullElementFlags["Signature"] = 1 << 11] = "Signature"; + PullElementFlags[PullElementFlags["Enum"] = 1 << 12] = "Enum"; + PullElementFlags[PullElementFlags["ArrowFunction"] = 1 << 13] = "ArrowFunction"; + + PullElementFlags[PullElementFlags["ClassConstructorVariable"] = 1 << 14] = "ClassConstructorVariable"; + PullElementFlags[PullElementFlags["InitializedModule"] = 1 << 15] = "InitializedModule"; + PullElementFlags[PullElementFlags["InitializedDynamicModule"] = 1 << 16] = "InitializedDynamicModule"; + + PullElementFlags[PullElementFlags["MustCaptureThis"] = 1 << 18] = "MustCaptureThis"; + + PullElementFlags[PullElementFlags["DeclaredInAWithBlock"] = 1 << 21] = "DeclaredInAWithBlock"; + + PullElementFlags[PullElementFlags["HasReturnStatement"] = 1 << 22] = "HasReturnStatement"; + + PullElementFlags[PullElementFlags["PropertyParameter"] = 1 << 23] = "PropertyParameter"; + + PullElementFlags[PullElementFlags["IsAnnotatedWithAny"] = 1 << 24] = "IsAnnotatedWithAny"; + + PullElementFlags[PullElementFlags["HasDefaultArgs"] = 1 << 25] = "HasDefaultArgs"; + + PullElementFlags[PullElementFlags["ConstructorParameter"] = 1 << 26] = "ConstructorParameter"; + + PullElementFlags[PullElementFlags["ImplicitVariable"] = PullElementFlags.ClassConstructorVariable | PullElementFlags.InitializedModule | PullElementFlags.InitializedDynamicModule | PullElementFlags.Enum] = "ImplicitVariable"; + PullElementFlags[PullElementFlags["SomeInitializedModule"] = PullElementFlags.InitializedModule | PullElementFlags.InitializedDynamicModule | PullElementFlags.Enum] = "SomeInitializedModule"; + })(TypeScript.PullElementFlags || (TypeScript.PullElementFlags = {})); + var PullElementFlags = TypeScript.PullElementFlags; + + function hasModifier(modifiers, flag) { + for (var i = 0, n = modifiers.length; i < n; i++) { + if (TypeScript.hasFlag(modifiers[i], flag)) { + return true; + } + } + + return false; + } + TypeScript.hasModifier = hasModifier; + + (function (PullElementKind) { + PullElementKind[PullElementKind["None"] = 0] = "None"; + PullElementKind[PullElementKind["Global"] = 0] = "Global"; + + PullElementKind[PullElementKind["Script"] = 1 << 0] = "Script"; + PullElementKind[PullElementKind["Primitive"] = 1 << 1] = "Primitive"; + + PullElementKind[PullElementKind["Container"] = 1 << 2] = "Container"; + PullElementKind[PullElementKind["Class"] = 1 << 3] = "Class"; + PullElementKind[PullElementKind["Interface"] = 1 << 4] = "Interface"; + PullElementKind[PullElementKind["DynamicModule"] = 1 << 5] = "DynamicModule"; + PullElementKind[PullElementKind["Enum"] = 1 << 6] = "Enum"; + PullElementKind[PullElementKind["TypeAlias"] = 1 << 7] = "TypeAlias"; + PullElementKind[PullElementKind["ObjectLiteral"] = 1 << 8] = "ObjectLiteral"; + + PullElementKind[PullElementKind["Variable"] = 1 << 9] = "Variable"; + PullElementKind[PullElementKind["CatchVariable"] = 1 << 10] = "CatchVariable"; + PullElementKind[PullElementKind["Parameter"] = 1 << 11] = "Parameter"; + PullElementKind[PullElementKind["Property"] = 1 << 12] = "Property"; + PullElementKind[PullElementKind["TypeParameter"] = 1 << 13] = "TypeParameter"; + + PullElementKind[PullElementKind["Function"] = 1 << 14] = "Function"; + PullElementKind[PullElementKind["ConstructorMethod"] = 1 << 15] = "ConstructorMethod"; + PullElementKind[PullElementKind["Method"] = 1 << 16] = "Method"; + PullElementKind[PullElementKind["FunctionExpression"] = 1 << 17] = "FunctionExpression"; + + PullElementKind[PullElementKind["GetAccessor"] = 1 << 18] = "GetAccessor"; + PullElementKind[PullElementKind["SetAccessor"] = 1 << 19] = "SetAccessor"; + + PullElementKind[PullElementKind["CallSignature"] = 1 << 20] = "CallSignature"; + PullElementKind[PullElementKind["ConstructSignature"] = 1 << 21] = "ConstructSignature"; + PullElementKind[PullElementKind["IndexSignature"] = 1 << 22] = "IndexSignature"; + + PullElementKind[PullElementKind["ObjectType"] = 1 << 23] = "ObjectType"; + PullElementKind[PullElementKind["FunctionType"] = 1 << 24] = "FunctionType"; + PullElementKind[PullElementKind["ConstructorType"] = 1 << 25] = "ConstructorType"; + + PullElementKind[PullElementKind["EnumMember"] = 1 << 26] = "EnumMember"; + + PullElementKind[PullElementKind["WithBlock"] = 1 << 27] = "WithBlock"; + PullElementKind[PullElementKind["CatchBlock"] = 1 << 28] = "CatchBlock"; + + PullElementKind[PullElementKind["All"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Container | PullElementKind.Class | PullElementKind.Interface | PullElementKind.DynamicModule | PullElementKind.Enum | PullElementKind.TypeAlias | PullElementKind.ObjectLiteral | PullElementKind.Variable | PullElementKind.Parameter | PullElementKind.Property | PullElementKind.TypeParameter | PullElementKind.Function | PullElementKind.ConstructorMethod | PullElementKind.Method | PullElementKind.FunctionExpression | PullElementKind.GetAccessor | PullElementKind.SetAccessor | PullElementKind.CallSignature | PullElementKind.ConstructSignature | PullElementKind.IndexSignature | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.EnumMember | PullElementKind.WithBlock | PullElementKind.CatchBlock] = "All"; + + PullElementKind[PullElementKind["SomeFunction"] = PullElementKind.Function | PullElementKind.ConstructorMethod | PullElementKind.Method | PullElementKind.FunctionExpression | PullElementKind.GetAccessor | PullElementKind.SetAccessor] = "SomeFunction"; + + PullElementKind[PullElementKind["SomeValue"] = PullElementKind.Variable | PullElementKind.Parameter | PullElementKind.Property | PullElementKind.EnumMember | PullElementKind.SomeFunction] = "SomeValue"; + + PullElementKind[PullElementKind["SomeType"] = PullElementKind.Script | PullElementKind.Global | PullElementKind.Primitive | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.ObjectLiteral | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType | PullElementKind.TypeParameter] = "SomeType"; + + PullElementKind[PullElementKind["AcceptableAlias"] = PullElementKind.Variable | PullElementKind.SomeFunction | PullElementKind.Class | PullElementKind.Interface | PullElementKind.Enum | PullElementKind.Container | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType] = "AcceptableAlias"; + + PullElementKind[PullElementKind["SomeContainer"] = PullElementKind.Container | PullElementKind.DynamicModule | PullElementKind.TypeAlias] = "SomeContainer"; + + PullElementKind[PullElementKind["SomeSignature"] = PullElementKind.CallSignature | PullElementKind.ConstructSignature | PullElementKind.IndexSignature] = "SomeSignature"; + + PullElementKind[PullElementKind["SomeTypeReference"] = PullElementKind.Interface | PullElementKind.ObjectType | PullElementKind.FunctionType | PullElementKind.ConstructorType] = "SomeTypeReference"; + + PullElementKind[PullElementKind["SomeInstantiatableType"] = PullElementKind.Class | PullElementKind.Interface | PullElementKind.TypeParameter] = "SomeInstantiatableType"; + })(TypeScript.PullElementKind || (TypeScript.PullElementKind = {})); + var PullElementKind = TypeScript.PullElementKind; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var pullDeclID = 0; + var sentinelEmptyPullDeclArray = []; + + var PullDecl = (function () { + function PullDecl(declName, displayName, kind, declFlags, semanticInfoChain) { + this.declID = pullDeclID++; + this.flags = 0 /* None */; + this.declGroups = null; + this.childDecls = null; + this.typeParameters = null; + this.synthesizedValDecl = null; + this.containerDecl = null; + this.childDeclTypeCache = null; + this.childDeclValueCache = null; + this.childDeclNamespaceCache = null; + this.childDeclTypeParameterCache = null; + this.name = declName; + this.kind = kind; + this.flags = declFlags; + this.semanticInfoChain = semanticInfoChain; + + if (displayName !== this.name) { + this.declDisplayName = displayName; + } + } + PullDecl.prototype.fileName = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.getParentPath = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.getParentDecl = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.isExternalModule = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype.getEnclosingDecl = function () { + throw TypeScript.Errors.abstract(); + }; + + PullDecl.prototype._getEnclosingDeclFromParentDecl = function () { + var decl = this; + while (decl) { + switch (decl.kind) { + default: + return decl; + case 512 /* Variable */: + case 8192 /* TypeParameter */: + case 2048 /* Parameter */: + case 128 /* TypeAlias */: + case 67108864 /* EnumMember */: + } + + decl = decl.getParentDecl(); + } + + TypeScript.Debug.fail(); + }; + + PullDecl.prototype.getDisplayName = function () { + return this.declDisplayName === undefined ? this.name : this.declDisplayName; + }; + + PullDecl.prototype.setSymbol = function (symbol) { + this.semanticInfoChain.setSymbolForDecl(this, symbol); + }; + + PullDecl.prototype.ensureSymbolIsBound = function () { + if (!this.hasBeenBound() && this.kind !== 1 /* Script */) { + var binder = this.semanticInfoChain.getBinder(); + binder.bindDeclToPullSymbol(this); + } + }; + + PullDecl.prototype.getSymbol = function () { + if (this.kind === 1 /* Script */) { + return null; + } + + this.ensureSymbolIsBound(); + + return this.semanticInfoChain.getSymbolForDecl(this); + }; + + PullDecl.prototype.hasSymbol = function () { + var symbol = this.semanticInfoChain.getSymbolForDecl(this); + return !!symbol; + }; + + PullDecl.prototype.setSignatureSymbol = function (signatureSymbol) { + this.semanticInfoChain.setSignatureSymbolForDecl(this, signatureSymbol); + }; + + PullDecl.prototype.getSignatureSymbol = function () { + this.ensureSymbolIsBound(); + return this.semanticInfoChain.getSignatureSymbolForDecl(this); + }; + + PullDecl.prototype.hasSignatureSymbol = function () { + var signatureSymbol = this.semanticInfoChain.getSignatureSymbolForDecl(this); + return !!signatureSymbol; + }; + + PullDecl.prototype.setFlags = function (flags) { + this.flags = flags; + }; + + PullDecl.prototype.setFlag = function (flags) { + this.flags |= flags; + }; + + PullDecl.prototype.setValueDecl = function (valDecl) { + this.synthesizedValDecl = valDecl; + valDecl.containerDecl = this; + }; + + PullDecl.prototype.getValueDecl = function () { + return this.synthesizedValDecl; + }; + + PullDecl.prototype.getContainerDecl = function () { + return this.containerDecl; + }; + + PullDecl.prototype.getChildDeclCache = function (declKind) { + if (declKind === 8192 /* TypeParameter */) { + if (!this.childDeclTypeParameterCache) { + this.childDeclTypeParameterCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclTypeParameterCache; + } else if (TypeScript.hasFlag(declKind, 164 /* SomeContainer */)) { + if (!this.childDeclNamespaceCache) { + this.childDeclNamespaceCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclNamespaceCache; + } else if (TypeScript.hasFlag(declKind, 58728795 /* SomeType */)) { + if (!this.childDeclTypeCache) { + this.childDeclTypeCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclTypeCache; + } else { + if (!this.childDeclValueCache) { + this.childDeclValueCache = TypeScript.createIntrinsicsObject(); + } + + return this.childDeclValueCache; + } + }; + + PullDecl.prototype.addChildDecl = function (childDecl) { + if (childDecl.kind === 8192 /* TypeParameter */) { + if (!this.typeParameters) { + this.typeParameters = []; + } + this.typeParameters[this.typeParameters.length] = childDecl; + } else { + if (!this.childDecls) { + this.childDecls = []; + } + this.childDecls[this.childDecls.length] = childDecl; + } + + var declName = childDecl.name; + + if (!(childDecl.kind & 7340032 /* SomeSignature */)) { + var cache = this.getChildDeclCache(childDecl.kind); + var childrenOfName = cache[declName]; + if (!childrenOfName) { + childrenOfName = []; + } + + childrenOfName.push(childDecl); + cache[declName] = childrenOfName; + } + }; + + PullDecl.prototype.searchChildDecls = function (declName, searchKind) { + var cacheVal = null; + + if (searchKind & 58728795 /* SomeType */) { + cacheVal = this.childDeclTypeCache ? this.childDeclTypeCache[declName] : null; + } else if (searchKind & 164 /* SomeContainer */) { + cacheVal = this.childDeclNamespaceCache ? this.childDeclNamespaceCache[declName] : null; + } else { + cacheVal = this.childDeclValueCache ? this.childDeclValueCache[declName] : null; + } + + if (cacheVal) { + return cacheVal; + } else { + if (searchKind & 58728795 /* SomeType */) { + cacheVal = this.childDeclTypeParameterCache ? this.childDeclTypeParameterCache[declName] : null; + + if (cacheVal) { + return cacheVal; + } + } + + return sentinelEmptyPullDeclArray; + } + }; + + PullDecl.prototype.getChildDecls = function () { + return this.childDecls || sentinelEmptyPullDeclArray; + }; + + PullDecl.prototype.getTypeParameters = function () { + return this.typeParameters || sentinelEmptyPullDeclArray; + }; + + PullDecl.prototype.addVariableDeclToGroup = function (decl) { + if (!this.declGroups) { + this.declGroups = TypeScript.createIntrinsicsObject(); + } + + var declGroup = this.declGroups[decl.name]; + if (declGroup) { + declGroup.addDecl(decl); + } else { + declGroup = new PullDeclGroup(decl.name); + declGroup.addDecl(decl); + this.declGroups[decl.name] = declGroup; + } + }; + + PullDecl.prototype.getVariableDeclGroups = function () { + var declGroups = null; + + if (this.declGroups) { + for (var declName in this.declGroups) { + if (this.declGroups[declName]) { + if (declGroups === null) { + declGroups = []; + } + + declGroups.push(this.declGroups[declName].getDecls()); + } + } + } + + return declGroups || sentinelEmptyPullDeclArray; + }; + + PullDecl.prototype.hasBeenBound = function () { + return this.hasSymbol() || this.hasSignatureSymbol(); + }; + + PullDecl.prototype.isSynthesized = function () { + return false; + }; + + PullDecl.prototype.ast = function () { + return this.semanticInfoChain.getASTForDecl(this); + }; + + PullDecl.prototype.isRootDecl = function () { + throw TypeScript.Errors.abstract(); + }; + return PullDecl; + })(); + TypeScript.PullDecl = PullDecl; + + var RootPullDecl = (function (_super) { + __extends(RootPullDecl, _super); + function RootPullDecl(name, fileName, kind, declFlags, semanticInfoChain, isExternalModule) { + _super.call(this, name, name, kind, declFlags, semanticInfoChain); + this.semanticInfoChain = semanticInfoChain; + this._isExternalModule = isExternalModule; + this._fileName = fileName; + } + RootPullDecl.prototype.fileName = function () { + return this._fileName; + }; + + RootPullDecl.prototype.getParentPath = function () { + return [this]; + }; + + RootPullDecl.prototype.getParentDecl = function () { + return null; + }; + + RootPullDecl.prototype.isExternalModule = function () { + return this._isExternalModule; + }; + + RootPullDecl.prototype.getEnclosingDecl = function () { + return this; + }; + + RootPullDecl.prototype.isRootDecl = function () { + return true; + }; + return RootPullDecl; + })(PullDecl); + TypeScript.RootPullDecl = RootPullDecl; + + var NormalPullDecl = (function (_super) { + __extends(NormalPullDecl, _super); + function NormalPullDecl(declName, displayName, kind, declFlags, parentDecl, addToParent) { + if (typeof addToParent === "undefined") { addToParent = true; } + _super.call(this, declName, displayName, kind, declFlags, parentDecl ? parentDecl.semanticInfoChain : null); + this.parentDecl = null; + this.parentPath = null; + + this.parentDecl = parentDecl; + if (addToParent) { + parentDecl.addChildDecl(this); + } + + if (this.parentDecl) { + if (this.parentDecl.isRootDecl()) { + this._rootDecl = this.parentDecl; + } else { + this._rootDecl = this.parentDecl._rootDecl; + } + } else { + TypeScript.Debug.assert(this.isSynthesized()); + this._rootDecl = null; + } + } + NormalPullDecl.prototype.fileName = function () { + return this._rootDecl.fileName(); + }; + + NormalPullDecl.prototype.getParentDecl = function () { + return this.parentDecl; + }; + + NormalPullDecl.prototype.getParentPath = function () { + if (!this.parentPath) { + var path = [this]; + var parentDecl = this.parentDecl; + + while (parentDecl) { + if (parentDecl && path[path.length - 1] !== parentDecl && !(parentDecl.kind & (256 /* ObjectLiteral */ | 8388608 /* ObjectType */))) { + path.unshift(parentDecl); + } + + parentDecl = parentDecl.getParentDecl(); + } + + this.parentPath = path; + } + + return this.parentPath; + }; + + NormalPullDecl.prototype.isExternalModule = function () { + return false; + }; + + NormalPullDecl.prototype.getEnclosingDecl = function () { + return this.parentDecl && this.parentDecl._getEnclosingDeclFromParentDecl(); + }; + + NormalPullDecl.prototype.isRootDecl = function () { + return false; + }; + return NormalPullDecl; + })(PullDecl); + TypeScript.NormalPullDecl = NormalPullDecl; + + var PullEnumElementDecl = (function (_super) { + __extends(PullEnumElementDecl, _super); + function PullEnumElementDecl(declName, displayName, parentDecl) { + _super.call(this, declName, displayName, 67108864 /* EnumMember */, 4 /* Public */, parentDecl); + this.constantValue = null; + } + return PullEnumElementDecl; + })(NormalPullDecl); + TypeScript.PullEnumElementDecl = PullEnumElementDecl; + + var PullFunctionExpressionDecl = (function (_super) { + __extends(PullFunctionExpressionDecl, _super); + function PullFunctionExpressionDecl(expressionName, declFlags, parentDecl, displayName) { + if (typeof displayName === "undefined") { displayName = ""; } + _super.call(this, "", displayName, 131072 /* FunctionExpression */, declFlags, parentDecl); + this.functionExpressionName = expressionName; + } + PullFunctionExpressionDecl.prototype.getFunctionExpressionName = function () { + return this.functionExpressionName; + }; + return PullFunctionExpressionDecl; + })(NormalPullDecl); + TypeScript.PullFunctionExpressionDecl = PullFunctionExpressionDecl; + + var PullSynthesizedDecl = (function (_super) { + __extends(PullSynthesizedDecl, _super); + function PullSynthesizedDecl(declName, displayName, kind, declFlags, parentDecl, semanticInfoChain) { + _super.call(this, declName, displayName, kind, declFlags, parentDecl, false); + this.semanticInfoChain = semanticInfoChain; + } + PullSynthesizedDecl.prototype.isSynthesized = function () { + return true; + }; + + PullSynthesizedDecl.prototype.fileName = function () { + return this._rootDecl ? this._rootDecl.fileName() : ""; + }; + return PullSynthesizedDecl; + })(NormalPullDecl); + TypeScript.PullSynthesizedDecl = PullSynthesizedDecl; + + var PullDeclGroup = (function () { + function PullDeclGroup(name) { + this.name = name; + this._decls = []; + } + PullDeclGroup.prototype.addDecl = function (decl) { + if (decl.name === this.name) { + this._decls[this._decls.length] = decl; + } + }; + + PullDeclGroup.prototype.getDecls = function () { + return this._decls; + }; + return PullDeclGroup; + })(); + TypeScript.PullDeclGroup = PullDeclGroup; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.pullSymbolID = 0; + TypeScript.sentinelEmptyArray = []; + + var PullSymbol = (function () { + function PullSymbol(name, declKind) { + this.pullSymbolID = ++TypeScript.pullSymbolID; + this._container = null; + this.type = null; + this._declarations = null; + this.isResolved = false; + this.isOptional = false; + this.inResolution = false; + this.isSynthesized = false; + this.isVarArg = false; + this.rootSymbol = null; + this._enclosingSignature = null; + this._docComments = null; + this.isPrinting = false; + this.name = name; + this.kind = declKind; + } + PullSymbol.prototype.isAny = function () { + return false; + }; + + PullSymbol.prototype.isType = function () { + return (this.kind & 58728795 /* SomeType */) !== 0; + }; + + PullSymbol.prototype.isTypeReference = function () { + return false; + }; + + PullSymbol.prototype.isSignature = function () { + return (this.kind & 7340032 /* SomeSignature */) !== 0; + }; + + PullSymbol.prototype.isArrayNamedTypeReference = function () { + return false; + }; + + PullSymbol.prototype.isPrimitive = function () { + return this.kind === 2 /* Primitive */; + }; + + PullSymbol.prototype.isAccessor = function () { + return false; + }; + + PullSymbol.prototype.isError = function () { + return false; + }; + + PullSymbol.prototype.isInterface = function () { + return this.kind === 16 /* Interface */; + }; + + PullSymbol.prototype.isMethod = function () { + return this.kind === 65536 /* Method */; + }; + + PullSymbol.prototype.isProperty = function () { + return this.kind === 4096 /* Property */; + }; + + PullSymbol.prototype.isAlias = function () { + return false; + }; + + PullSymbol.prototype.isContainer = function () { + return false; + }; + + PullSymbol.prototype.findAliasedTypeSymbols = function (scopeSymbol, skipScopeSymbolAliasesLookIn, lookIntoOnlyExportedAlias, aliasSymbols, visitedScopeDeclarations) { + if (typeof aliasSymbols === "undefined") { aliasSymbols = []; } + if (typeof visitedScopeDeclarations === "undefined") { visitedScopeDeclarations = []; } + var scopeDeclarations = scopeSymbol.getDeclarations(); + var scopeSymbolAliasesToLookIn = []; + + for (var i = 0; i < scopeDeclarations.length; i++) { + var scopeDecl = scopeDeclarations[i]; + if (!TypeScript.ArrayUtilities.contains(visitedScopeDeclarations, scopeDecl)) { + visitedScopeDeclarations.push(scopeDecl); + + var childDecls = scopeDecl.getChildDecls(); + for (var j = 0; j < childDecls.length; j++) { + var childDecl = childDecls[j]; + if (childDecl.kind === 128 /* TypeAlias */ && (!lookIntoOnlyExportedAlias || (childDecl.flags & 1 /* Exported */))) { + var symbol = childDecl.getSymbol(); + + if (PullContainerSymbol.usedAsSymbol(symbol, this) || (this.rootSymbol && PullContainerSymbol.usedAsSymbol(symbol, this.rootSymbol))) { + aliasSymbols.push(symbol); + return aliasSymbols; + } + + if (!skipScopeSymbolAliasesLookIn && PullSymbol._isExternalModuleReferenceAlias(symbol) && (!symbol.assignedContainer().hasExportAssignment() || (symbol.assignedContainer().getExportAssignedContainerSymbol() && symbol.assignedContainer().getExportAssignedContainerSymbol().kind === 32 /* DynamicModule */))) { + scopeSymbolAliasesToLookIn.push(symbol); + } + } + } + } + } + + for (var i = 0; i < scopeSymbolAliasesToLookIn.length; i++) { + var scopeSymbolAlias = scopeSymbolAliasesToLookIn[i]; + + aliasSymbols.push(scopeSymbolAlias); + var result = this.findAliasedTypeSymbols(scopeSymbolAlias.assignedContainer().hasExportAssignment() ? scopeSymbolAlias.assignedContainer().getExportAssignedContainerSymbol() : scopeSymbolAlias.assignedContainer(), false, true, aliasSymbols, visitedScopeDeclarations); + if (result) { + return result; + } + + aliasSymbols.pop(); + } + + return null; + }; + + PullSymbol.prototype.getExternalAliasedSymbols = function (scopeSymbol) { + if (!scopeSymbol) { + return null; + } + + var scopePath = scopeSymbol.pathToRoot(); + if (scopePath.length && scopePath[scopePath.length - 1].kind === 32 /* DynamicModule */) { + var symbols = this.findAliasedTypeSymbols(scopePath[scopePath.length - 1]); + return symbols; + } + + return null; + }; + + PullSymbol._isExternalModuleReferenceAlias = function (aliasSymbol) { + if (aliasSymbol) { + if (aliasSymbol.assignedValue()) { + return false; + } + + if (aliasSymbol.assignedType() && aliasSymbol.assignedType() !== aliasSymbol.assignedContainer()) { + return false; + } + + if (aliasSymbol.assignedContainer() && aliasSymbol.assignedContainer().kind !== 32 /* DynamicModule */) { + return false; + } + + return true; + } + + return false; + }; + + PullSymbol.prototype.getExportedInternalAliasSymbol = function (scopeSymbol) { + if (scopeSymbol) { + if (this.kind !== 128 /* TypeAlias */) { + var scopePath = scopeSymbol.pathToRoot(); + for (var i = 0; i < scopePath.length; i++) { + var internalAliases = this.findAliasedTypeSymbols(scopeSymbol, true, true); + if (internalAliases) { + TypeScript.Debug.assert(internalAliases.length === 1); + return internalAliases[0]; + } + } + } + } + + return null; + }; + + PullSymbol.prototype.getAliasSymbolName = function (scopeSymbol, aliasNameGetter, aliasPartsNameGetter, skipInternalAlias) { + if (!skipInternalAlias) { + var internalAlias = this.getExportedInternalAliasSymbol(scopeSymbol); + if (internalAlias) { + return aliasNameGetter(internalAlias); + } + } + + var externalAliases = this.getExternalAliasedSymbols(scopeSymbol); + + if (externalAliases && externalAliases[0] != this && PullSymbol._isExternalModuleReferenceAlias(externalAliases[externalAliases.length - 1])) { + var aliasFullName = aliasNameGetter(externalAliases[0]); + if (!aliasFullName) { + return null; + } + for (var i = 1, symbolsLen = externalAliases.length; i < symbolsLen; i++) { + aliasFullName = aliasFullName + "." + aliasPartsNameGetter(externalAliases[i]); + } + return aliasFullName; + } + + return null; + }; + + PullSymbol.prototype._getResolver = function () { + TypeScript.Debug.assert(this._declarations && this._declarations.length > 0); + return this._declarations[0].semanticInfoChain.getResolver(); + }; + + PullSymbol.prototype._resolveDeclaredSymbol = function () { + return this._getResolver().resolveDeclaredSymbol(this); + }; + + PullSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + var aliasName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getName(scopeSymbol, useConstraintInName); + }, function (symbol) { + return symbol.getName(); + }); + return aliasName || this.name; + }; + + PullSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { + var aliasDisplayName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getDisplayName(scopeSymbol, useConstraintInName); + }, function (symbol) { + return symbol.getDisplayName(); + }, skipInternalAliasName); + if (aliasDisplayName) { + return aliasDisplayName; + } + + var decls = this.getDeclarations(); + var name = decls.length && decls[0].getDisplayName(); + + return (name && name.length) ? name : this.name; + }; + + PullSymbol.prototype.getIsSpecialized = function () { + return false; + }; + + PullSymbol.prototype.getRootSymbol = function () { + if (!this.rootSymbol) { + return this; + } + return this.rootSymbol; + }; + PullSymbol.prototype.setRootSymbol = function (symbol) { + this.rootSymbol = symbol; + }; + + PullSymbol.prototype.setIsSynthesized = function (value) { + if (typeof value === "undefined") { value = true; } + TypeScript.Debug.assert(this.rootSymbol == null); + this.isSynthesized = value; + }; + + PullSymbol.prototype.getIsSynthesized = function () { + if (this.rootSymbol) { + return this.rootSymbol.getIsSynthesized(); + } + return this.isSynthesized; + }; + + PullSymbol.prototype.setEnclosingSignature = function (signature) { + this._enclosingSignature = signature; + }; + + PullSymbol.prototype.getEnclosingSignature = function () { + return this._enclosingSignature; + }; + + PullSymbol.prototype.addDeclaration = function (decl) { + TypeScript.Debug.assert(!!decl); + + if (this.rootSymbol) { + return; + } + + if (!this._declarations) { + this._declarations = [decl]; + } else { + this._declarations[this._declarations.length] = decl; + } + }; + + PullSymbol.prototype.getDeclarations = function () { + if (this.rootSymbol) { + return this.rootSymbol.getDeclarations(); + } + + if (!this._declarations) { + this._declarations = []; + } + + return this._declarations; + }; + + PullSymbol.prototype.hasDeclaration = function (decl) { + if (!this._declarations) { + return false; + } + + return TypeScript.ArrayUtilities.any(this._declarations, function (eachDecl) { + return eachDecl === decl; + }); + }; + + PullSymbol.prototype.setContainer = function (containerSymbol) { + if (this.rootSymbol) { + return; + } + + this._container = containerSymbol; + }; + + PullSymbol.prototype.getContainer = function () { + if (this.rootSymbol) { + return this.rootSymbol.getContainer(); + } + + return this._container; + }; + + PullSymbol.prototype.setResolved = function () { + this.isResolved = true; + this.inResolution = false; + }; + + PullSymbol.prototype.startResolving = function () { + this.inResolution = true; + }; + + PullSymbol.prototype.setUnresolved = function () { + this.isResolved = false; + this.inResolution = false; + }; + + PullSymbol.prototype.anyDeclHasFlag = function (flag) { + var declarations = this.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + if (TypeScript.hasFlag(declarations[i].flags, flag)) { + return true; + } + } + return false; + }; + + PullSymbol.prototype.allDeclsHaveFlag = function (flag) { + var declarations = this.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + if (!TypeScript.hasFlag(declarations[i].flags, flag)) { + return false; + } + } + return true; + }; + + PullSymbol.prototype.pathToRoot = function () { + var path = []; + var node = this; + while (node) { + if (node.isType()) { + var associatedContainerSymbol = node.getAssociatedContainerType(); + if (associatedContainerSymbol) { + node = associatedContainerSymbol; + } + } + path[path.length] = node; + var nodeKind = node.kind; + if (nodeKind === 2048 /* Parameter */) { + break; + } else { + node = node.getContainer(); + } + } + return path; + }; + + PullSymbol.unqualifiedNameReferencesDifferentSymbolInScope = function (symbol, scopePath, endScopePathIndex) { + var declPath = scopePath[0].getDeclarations()[0].getParentPath(); + for (var i = 0, declIndex = declPath.length - 1; i <= endScopePathIndex; i++, declIndex--) { + if (scopePath[i].isContainer()) { + var scopeContainer = scopePath[i]; + if (symbol.isContainer()) { + var memberSymbol = scopeContainer.findContainedNonMemberContainer(symbol.name, 164 /* SomeContainer */); + if (memberSymbol && memberSymbol != symbol && memberSymbol.getDeclarations()[0].getParentDecl() == declPath[declIndex]) { + return true; + } + + var memberSymbol = scopeContainer.findNestedContainer(symbol.name, 164 /* SomeContainer */); + if (memberSymbol && memberSymbol != symbol) { + return true; + } + } else if (symbol.isType()) { + var memberSymbol = scopeContainer.findContainedNonMemberType(symbol.name, 58728795 /* SomeType */); + var symbolRootType = TypeScript.PullHelpers.getRootType(symbol); + if (memberSymbol && TypeScript.PullHelpers.getRootType(memberSymbol) != symbolRootType && memberSymbol.getDeclarations()[0].getParentDecl() == declPath[declIndex]) { + return true; + } + + var memberSymbol = scopeContainer.findNestedType(symbol.name, 58728795 /* SomeType */); + if (memberSymbol && TypeScript.PullHelpers.getRootType(memberSymbol) != symbolRootType) { + return true; + } + } + } + } + + return false; + }; + + PullSymbol.prototype.findQualifyingSymbolPathInScopeSymbol = function (scopeSymbol) { + var thisPath = this.pathToRoot(); + if (thisPath.length === 1) { + return thisPath; + } + + var scopeSymbolPath; + if (scopeSymbol) { + scopeSymbolPath = scopeSymbol.pathToRoot(); + } else { + return thisPath; + } + + var thisCommonAncestorIndex = TypeScript.ArrayUtilities.indexOf(thisPath, function (thisNode) { + return TypeScript.ArrayUtilities.contains(scopeSymbolPath, thisNode); + }); + if (thisCommonAncestorIndex > 0) { + var thisCommonAncestor = thisPath[thisCommonAncestorIndex]; + var scopeCommonAncestorIndex = TypeScript.ArrayUtilities.indexOf(scopeSymbolPath, function (scopeNode) { + return scopeNode === thisCommonAncestor; + }); + TypeScript.Debug.assert(thisPath.length - thisCommonAncestorIndex === scopeSymbolPath.length - scopeCommonAncestorIndex); + + for (; thisCommonAncestorIndex < thisPath.length; thisCommonAncestorIndex++, scopeCommonAncestorIndex++) { + if (!PullSymbol.unqualifiedNameReferencesDifferentSymbolInScope(thisPath[thisCommonAncestorIndex - 1], scopeSymbolPath, scopeCommonAncestorIndex)) { + break; + } + } + } + + if (thisCommonAncestorIndex >= 0 && thisCommonAncestorIndex < thisPath.length) { + return thisPath.slice(0, thisCommonAncestorIndex); + } else { + return thisPath; + } + }; + + PullSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + var str = this.getNameAndTypeName(scopeSymbol); + return str; + }; + + PullSymbol.prototype.getNamePartForFullName = function () { + return this.getDisplayName(null, true); + }; + + PullSymbol.prototype.fullName = function (scopeSymbol) { + var _this = this; + var path = this.pathToRoot(); + var fullName = ""; + + var aliasFullName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.fullName(scopeSymbol); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }); + if (aliasFullName) { + return aliasFullName; + } + + for (var i = 1; i < path.length; i++) { + var aliasFullName = path[i].getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol === _this ? null : symbol.fullName(scopeSymbol); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }); + if (aliasFullName) { + fullName = aliasFullName + "." + fullName; + break; + } + + var scopedName = path[i].getNamePartForFullName(); + if (path[i].kind === 32 /* DynamicModule */ && !TypeScript.isQuoted(scopedName)) { + break; + } + + if (scopedName === "") { + break; + } + + fullName = scopedName + "." + fullName; + } + + fullName = fullName + this.getNamePartForFullName(); + return fullName; + }; + + PullSymbol.prototype.getScopedName = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName) { + var path = this.findQualifyingSymbolPathInScopeSymbol(scopeSymbol); + var fullName = ""; + + var aliasFullName = this.getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getScopedName(scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }, skipInternalAliasName); + if (aliasFullName) { + return aliasFullName; + } + + for (var i = 1; i < path.length; i++) { + var kind = path[i].kind; + if (kind === 4 /* Container */ || kind === 32 /* DynamicModule */) { + var aliasFullName = path[i].getAliasSymbolName(scopeSymbol, function (symbol) { + return symbol.getScopedName(scopeSymbol, skipTypeParametersInName, false, skipInternalAliasName); + }, function (symbol) { + return symbol.getNamePartForFullName(); + }, skipInternalAliasName); + if (aliasFullName) { + fullName = aliasFullName + "." + fullName; + break; + } + + if (kind === 4 /* Container */) { + fullName = path[i].getDisplayName() + "." + fullName; + } else { + var displayName = path[i].getDisplayName(); + if (TypeScript.isQuoted(displayName)) { + fullName = displayName + "." + fullName; + } + break; + } + } else { + break; + } + } + fullName = fullName + this.getDisplayName(scopeSymbol, useConstraintInName, skipInternalAliasName); + return fullName; + }; + + PullSymbol.prototype.getScopedNameEx = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName) { + var name = this.getScopedName(scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName); + return TypeScript.MemberName.create(name); + }; + + PullSymbol.prototype.getTypeName = function (scopeSymbol, getPrettyTypeName) { + var memberName = this.getTypeNameEx(scopeSymbol, getPrettyTypeName); + return memberName.toString(); + }; + + PullSymbol.prototype.getTypeNameEx = function (scopeSymbol, getPrettyTypeName) { + var type = this.type; + if (type) { + var memberName = getPrettyTypeName ? this.getTypeNameForFunctionSignature("", scopeSymbol, getPrettyTypeName) : null; + if (!memberName) { + memberName = type.getScopedNameEx(scopeSymbol, false, true, getPrettyTypeName); + } + + return memberName; + } + return TypeScript.MemberName.create(""); + }; + + PullSymbol.prototype.getTypeNameForFunctionSignature = function (prefix, scopeSymbol, getPrettyTypeName) { + var type = this.type; + if (type && !type.isNamedTypeSymbol() && this.kind !== 4096 /* Property */ && this.kind !== 512 /* Variable */ && this.kind !== 2048 /* Parameter */) { + var signatures = type.getCallSignatures(); + if (signatures.length === 1 || (getPrettyTypeName && signatures.length)) { + var typeName = new TypeScript.MemberNameArray(); + var signatureName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, prefix, false, false, scopeSymbol, getPrettyTypeName); + typeName.addAll(signatureName); + return typeName; + } + } + + return null; + }; + + PullSymbol.prototype.getNameAndTypeName = function (scopeSymbol) { + var nameAndTypeName = this.getNameAndTypeNameEx(scopeSymbol); + return nameAndTypeName.toString(); + }; + + PullSymbol.prototype.getNameAndTypeNameEx = function (scopeSymbol) { + var type = this.type; + var nameStr = this.getDisplayName(scopeSymbol); + if (type) { + nameStr = nameStr + (this.isOptional ? "?" : ""); + var memberName = this.getTypeNameForFunctionSignature(nameStr, scopeSymbol); + if (!memberName) { + var typeNameEx = type.getScopedNameEx(scopeSymbol); + memberName = TypeScript.MemberName.create(typeNameEx, nameStr + ": ", ""); + } + return memberName; + } + return TypeScript.MemberName.create(nameStr); + }; + + PullSymbol.getTypeParameterString = function (typars, scopeSymbol, useContraintInName) { + return PullSymbol.getTypeParameterStringEx(typars, scopeSymbol, undefined, useContraintInName).toString(); + }; + + PullSymbol.getTypeParameterStringEx = function (typeParameters, scopeSymbol, getTypeParamMarkerInfo, useContraintInName) { + var builder = new TypeScript.MemberNameArray(); + builder.prefix = ""; + + if (typeParameters && typeParameters.length) { + builder.add(TypeScript.MemberName.create("<")); + + for (var i = 0; i < typeParameters.length; i++) { + if (i) { + builder.add(TypeScript.MemberName.create(", ")); + } + + if (getTypeParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + + builder.add(typeParameters[i].getScopedNameEx(scopeSymbol, false, useContraintInName)); + + if (getTypeParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + } + + builder.add(TypeScript.MemberName.create(">")); + } + + return builder; + }; + + PullSymbol.getIsExternallyVisible = function (symbol, fromIsExternallyVisibleSymbol, inIsExternallyVisibleSymbols) { + if (inIsExternallyVisibleSymbols) { + for (var i = 0; i < inIsExternallyVisibleSymbols.length; i++) { + if (inIsExternallyVisibleSymbols[i] === symbol) { + return true; + } + } + } else { + inIsExternallyVisibleSymbols = []; + } + + if (fromIsExternallyVisibleSymbol === symbol) { + return true; + } + + inIsExternallyVisibleSymbols.push(fromIsExternallyVisibleSymbol); + + var result = symbol.isExternallyVisible(inIsExternallyVisibleSymbols); + + TypeScript.Debug.assert(TypeScript.ArrayUtilities.last(inIsExternallyVisibleSymbols) === fromIsExternallyVisibleSymbol); + inIsExternallyVisibleSymbols.pop(); + + return result; + }; + + PullSymbol.prototype.isExternallyVisible = function (inIsExternallyVisibleSymbols) { + var kind = this.kind; + if (kind === 2 /* Primitive */) { + return true; + } + + if (this.rootSymbol) { + return PullSymbol.getIsExternallyVisible(this.rootSymbol, this, inIsExternallyVisibleSymbols); + } + + if (this.isType()) { + var associatedContainerSymbol = this.getAssociatedContainerType(); + if (associatedContainerSymbol) { + return PullSymbol.getIsExternallyVisible(associatedContainerSymbol, this, inIsExternallyVisibleSymbols); + } + } + + if (this.anyDeclHasFlag(2 /* Private */)) { + return false; + } + + var container = this.getContainer(); + if (container === null) { + var decls = this.getDeclarations(); + if (decls.length) { + var parentDecl = decls[0].getParentDecl(); + if (parentDecl) { + var parentSymbol = parentDecl.getSymbol(); + if (!parentSymbol || parentDecl.kind === 1 /* Script */) { + return true; + } + + return PullSymbol.getIsExternallyVisible(parentSymbol, this, inIsExternallyVisibleSymbols); + } + } + + return true; + } + + if (container.kind === 32 /* DynamicModule */ || (container.getAssociatedContainerType() && container.getAssociatedContainerType().kind === 32 /* DynamicModule */)) { + var containerSymbol = container.kind === 32 /* DynamicModule */ ? container : container.getAssociatedContainerType(); + if (PullContainerSymbol.usedAsSymbol(containerSymbol, this)) { + return true; + } + } + + if (!this.anyDeclHasFlag(1 /* Exported */) && kind !== 4096 /* Property */ && kind !== 65536 /* Method */) { + return false; + } + + return PullSymbol.getIsExternallyVisible(container, this, inIsExternallyVisibleSymbols); + }; + + PullSymbol.prototype.getDocCommentsOfDecl = function (decl) { + var ast = decl.ast(); + + if (ast) { + var enclosingModuleDeclaration = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(ast); + if (TypeScript.ASTHelpers.isLastNameOfModule(enclosingModuleDeclaration, ast)) { + return TypeScript.ASTHelpers.docComments(enclosingModuleDeclaration); + } + + if (ast.kind() !== 130 /* ModuleDeclaration */ || decl.kind !== 512 /* Variable */) { + return TypeScript.ASTHelpers.docComments(ast); + } + } + + return []; + }; + + PullSymbol.prototype.getDocCommentArray = function (symbol) { + var docComments = []; + if (!symbol) { + return docComments; + } + + var isParameter = symbol.kind === 2048 /* Parameter */; + var decls = symbol.getDeclarations(); + for (var i = 0; i < decls.length; i++) { + if (isParameter && decls[i].kind === 4096 /* Property */) { + continue; + } + docComments = docComments.concat(this.getDocCommentsOfDecl(decls[i])); + } + return docComments; + }; + + PullSymbol.getDefaultConstructorSymbolForDocComments = function (classSymbol) { + if (classSymbol.getHasDefaultConstructor()) { + var extendedTypes = classSymbol.getExtendedTypes(); + if (extendedTypes.length) { + return PullSymbol.getDefaultConstructorSymbolForDocComments(extendedTypes[0]); + } + } + + return classSymbol.type.getConstructSignatures()[0]; + }; + + PullSymbol.prototype.getDocCommentText = function (comments) { + var docCommentText = new Array(); + for (var c = 0; c < comments.length; c++) { + var commentText = this.getDocCommentTextValue(comments[c]); + if (commentText !== "") { + docCommentText.push(commentText); + } + } + return docCommentText.join("\n"); + }; + + PullSymbol.prototype.getDocCommentTextValue = function (comment) { + return this.cleanJSDocComment(comment.fullText()); + }; + + PullSymbol.prototype.docComments = function (useConstructorAsClass) { + var decls = this.getDeclarations(); + if (useConstructorAsClass && decls.length && decls[0].kind === 32768 /* ConstructorMethod */) { + var classDecl = decls[0].getParentDecl(); + return this.getDocCommentText(this.getDocCommentsOfDecl(classDecl)); + } + + if (this._docComments === null) { + var docComments = ""; + if (!useConstructorAsClass && this.kind === 2097152 /* ConstructSignature */ && decls.length && decls[0].kind === 8 /* Class */) { + var classSymbol = this.returnType; + var extendedTypes = classSymbol.getExtendedTypes(); + if (extendedTypes.length) { + docComments = extendedTypes[0].getConstructorMethod().docComments(); + } else { + docComments = ""; + } + } else if (this.kind === 2048 /* Parameter */) { + var parameterComments = []; + + var funcContainer = this.getEnclosingSignature(); + var funcDocComments = this.getDocCommentArray(funcContainer); + var paramComment = this.getParameterDocCommentText(this.getDisplayName(), funcDocComments); + if (paramComment != "") { + parameterComments.push(paramComment); + } + + var paramSelfComment = this.getDocCommentText(this.getDocCommentArray(this)); + if (paramSelfComment != "") { + parameterComments.push(paramSelfComment); + } + docComments = parameterComments.join("\n"); + } else { + var getSymbolComments = true; + if (this.kind === 16777216 /* FunctionType */) { + var functionSymbol = this.getFunctionSymbol(); + + if (functionSymbol) { + docComments = functionSymbol._docComments || ""; + getSymbolComments = false; + } else { + var declarationList = this.getDeclarations(); + if (declarationList.length > 0) { + docComments = declarationList[0].getSymbol()._docComments || ""; + getSymbolComments = false; + } + } + } + if (getSymbolComments) { + docComments = this.getDocCommentText(this.getDocCommentArray(this)); + if (docComments === "") { + if (this.kind === 1048576 /* CallSignature */) { + var callTypeSymbol = this.functionType; + if (callTypeSymbol && callTypeSymbol.getCallSignatures().length === 1) { + docComments = callTypeSymbol.docComments(); + } + } + } + } + } + + this._docComments = docComments; + } + + return this._docComments; + }; + + PullSymbol.prototype.getParameterDocCommentText = function (param, fncDocComments) { + if (fncDocComments.length === 0 || fncDocComments[0].kind() !== 6 /* MultiLineCommentTrivia */) { + return ""; + } + + for (var i = 0; i < fncDocComments.length; i++) { + var commentContents = fncDocComments[i].fullText(); + for (var j = commentContents.indexOf("@param", 0); 0 <= j; j = commentContents.indexOf("@param", j)) { + j += 6; + if (!this.isSpaceChar(commentContents, j)) { + continue; + } + + j = this.consumeLeadingSpace(commentContents, j); + if (j === -1) { + break; + } + + if (commentContents.charCodeAt(j) === 123 /* openBrace */) { + j++; + + var charCode = 0; + for (var curlies = 1; j < commentContents.length; j++) { + charCode = commentContents.charCodeAt(j); + + if (charCode === 123 /* openBrace */) { + curlies++; + continue; + } + + if (charCode === 125 /* closeBrace */) { + curlies--; + if (curlies === 0) { + break; + } else { + continue; + } + } + + if (charCode === 64 /* at */) { + break; + } + } + + if (j === commentContents.length) { + break; + } + + if (charCode === 64 /* at */) { + continue; + } + + j = this.consumeLeadingSpace(commentContents, j + 1); + if (j === -1) { + break; + } + } + + if (param !== commentContents.substr(j, param.length) || !this.isSpaceChar(commentContents, j + param.length)) { + continue; + } + + j = this.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 = this.consumeLeadingSpace(commentContents, paramLineIndex); + if (startSpaceRemovalIndex !== j && commentContents.charAt(startSpaceRemovalIndex) === "*") { + paramSpacesToRemove = j - startSpaceRemovalIndex - 1; + } + + return this.cleanJSDocComment(paramHelpString, paramSpacesToRemove); + } + } + + return ""; + }; + + PullSymbol.prototype.cleanJSDocComment = function (content, spacesToRemove) { + var docCommentLines = new Array(); + 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 = this.cleanDocCommentLine(line, true, spacesToRemove); + if (!cleanLinePos) { + continue; + } + + var docCommentText = ""; + var prevPos = cleanLinePos.start; + for (var i = line.indexOf("@", cleanLinePos.start); 0 <= i && i < cleanLinePos.end; i = line.indexOf("@", i + 1)) { + var wasInParamtag = inParamTag; + + if (line.indexOf("param", i + 1) === i + 1 && this.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.end); + } + + var newCleanPos = this.cleanDocCommentLine(docCommentText, false); + if (newCleanPos) { + if (spacesToRemove === undefined) { + spacesToRemove = cleanLinePos.jsDocSpacesRemoved; + } + docCommentLines.push(docCommentText); + } + } + + return docCommentLines.join("\n"); + }; + + PullSymbol.prototype.consumeLeadingSpace = function (line, startIndex, maxSpacesToRemove) { + var endIndex = line.length; + if (maxSpacesToRemove !== undefined) { + endIndex = TypeScript.MathPrototype.min(startIndex + maxSpacesToRemove, endIndex); + } + + for (; startIndex < endIndex; startIndex++) { + var charCode = line.charCodeAt(startIndex); + if (charCode !== 32 /* space */ && charCode !== 9 /* tab */) { + return startIndex; + } + } + + if (endIndex !== line.length) { + return endIndex; + } + + return -1; + }; + + PullSymbol.prototype.isSpaceChar = function (line, index) { + var length = line.length; + if (index < length) { + var charCode = line.charCodeAt(index); + + return charCode === 32 /* space */ || charCode === 9 /* tab */; + } + + return index === length; + }; + + PullSymbol.prototype.cleanDocCommentLine = function (line, jsDocStyleComment, jsDocLineSpaceToRemove) { + var nonSpaceIndex = this.consumeLeadingSpace(line, 0); + if (nonSpaceIndex !== -1) { + var jsDocSpacesRemoved = nonSpaceIndex; + if (jsDocStyleComment && line.charAt(nonSpaceIndex) === '*') { + var startIndex = nonSpaceIndex + 1; + nonSpaceIndex = this.consumeLeadingSpace(line, startIndex, jsDocLineSpaceToRemove); + + if (nonSpaceIndex !== -1) { + jsDocSpacesRemoved = nonSpaceIndex - startIndex; + } else { + return null; + } + } + + return { + start: nonSpaceIndex, + end: line.charAt(line.length - 1) === "\r" ? line.length - 1 : line.length, + jsDocSpacesRemoved: jsDocSpacesRemoved + }; + } + + return null; + }; + return PullSymbol; + })(); + TypeScript.PullSymbol = PullSymbol; + + + + var PullSignatureSymbol = (function (_super) { + __extends(PullSignatureSymbol, _super); + function PullSignatureSymbol(kind, _isDefinition) { + if (typeof _isDefinition === "undefined") { _isDefinition = false; } + _super.call(this, "", kind); + this._isDefinition = _isDefinition; + this._memberTypeParameterNameCache = null; + this._stringConstantOverload = undefined; + this.parameters = TypeScript.sentinelEmptyArray; + this._typeParameters = null; + this.returnType = null; + this.functionType = null; + this.hasOptionalParam = false; + this.nonOptionalParamCount = 0; + this.hasVarArgs = false; + this._allowedToReferenceTypeParameters = null; + this._instantiationCache = null; + this.hasBeenChecked = false; + this.inWrapCheck = false; + this.inWrapInfiniteExpandingReferenceCheck = false; + } + PullSignatureSymbol.prototype.isDefinition = function () { + return this._isDefinition; + }; + + PullSignatureSymbol.prototype.isGeneric = function () { + var typeParameters = this.getTypeParameters(); + return !!typeParameters && typeParameters.length !== 0; + }; + + PullSignatureSymbol.prototype.addParameter = function (parameter, isOptional) { + if (typeof isOptional === "undefined") { isOptional = false; } + if (this.parameters === TypeScript.sentinelEmptyArray) { + this.parameters = []; + } + + this.parameters[this.parameters.length] = parameter; + this.hasOptionalParam = isOptional; + + if (!parameter.getEnclosingSignature()) { + parameter.setEnclosingSignature(this); + } + + if (!isOptional) { + this.nonOptionalParamCount++; + } + }; + + PullSignatureSymbol.prototype.addTypeParameter = function (typeParameter) { + if (!this._typeParameters) { + this._typeParameters = []; + } + + if (!this._memberTypeParameterNameCache) { + this._memberTypeParameterNameCache = TypeScript.createIntrinsicsObject(); + } + + this._typeParameters[this._typeParameters.length] = typeParameter; + + this._memberTypeParameterNameCache[typeParameter.getName()] = typeParameter; + }; + + PullSignatureSymbol.prototype.addTypeParametersFromReturnType = function () { + var typeParameters = this.returnType.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + this.addTypeParameter(typeParameters[i]); + } + }; + + PullSignatureSymbol.prototype.getTypeParameters = function () { + if (!this._typeParameters) { + this._typeParameters = []; + } + + return this._typeParameters; + }; + + PullSignatureSymbol.prototype.findTypeParameter = function (name) { + var memberSymbol; + + if (!this._memberTypeParameterNameCache) { + this._memberTypeParameterNameCache = TypeScript.createIntrinsicsObject(); + + for (var i = 0; i < this.getTypeParameters().length; i++) { + this._memberTypeParameterNameCache[this._typeParameters[i].getName()] = this._typeParameters[i]; + } + } + + memberSymbol = this._memberTypeParameterNameCache[name]; + + return memberSymbol; + }; + + PullSignatureSymbol.prototype.getTypeParameterArgumentMap = function () { + return null; + }; + + PullSignatureSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._allowedToReferenceTypeParameters) { + this._allowedToReferenceTypeParameters = TypeScript.PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl(this.getDeclarations()[0]); + } + + return this._allowedToReferenceTypeParameters; + }; + + PullSignatureSymbol.prototype.addSpecialization = function (specializedVersionOfThisSignature, typeArgumentMap) { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._instantiationCache) { + this._instantiationCache = TypeScript.createIntrinsicsObject(); + } + + this._instantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)] = specializedVersionOfThisSignature; + }; + + PullSignatureSymbol.prototype.getSpecialization = function (typeArgumentMap) { + TypeScript.Debug.assert(this.getRootSymbol() == this); + if (!this._instantiationCache) { + return null; + } + + var result = this._instantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)]; + return result || null; + }; + + PullSignatureSymbol.prototype.isStringConstantOverloadSignature = function () { + if (this._stringConstantOverload === undefined) { + var params = this.parameters; + this._stringConstantOverload = false; + for (var i = 0; i < params.length; i++) { + var paramType = params[i].type; + if (paramType && paramType.isPrimitive() && paramType.isStringConstant()) { + this._stringConstantOverload = true; + } + } + } + + return this._stringConstantOverload; + }; + + PullSignatureSymbol.prototype.getParameterTypeAtIndex = function (iParam) { + if (iParam < this.parameters.length - 1 || (iParam < this.parameters.length && !this.hasVarArgs)) { + return this.parameters[iParam].type; + } else if (this.hasVarArgs) { + var paramType = this.parameters[this.parameters.length - 1].type; + if (paramType.isArrayNamedTypeReference()) { + paramType = paramType.getElementType(); + } + return paramType; + } + + return null; + }; + + PullSignatureSymbol.getSignatureTypeMemberName = function (candidateSignature, signatures, scopeSymbol) { + var allMemberNames = new TypeScript.MemberNameArray(); + var signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(signatures, "", false, false, scopeSymbol, true, candidateSignature); + allMemberNames.addAll(signatureMemberName); + return allMemberNames; + }; + + PullSignatureSymbol.getSignaturesTypeNameEx = function (signatures, prefix, shortform, brackets, scopeSymbol, getPrettyTypeName, candidateSignature) { + var result = []; + if (!signatures) { + return result; + } + + var len = signatures.length; + if (!getPrettyTypeName && len > 1) { + shortform = false; + } + + var foundDefinition = false; + if (candidateSignature && candidateSignature.isDefinition() && len > 1) { + candidateSignature = null; + } + + for (var i = 0; i < len; i++) { + if (len > 1 && signatures[i].isDefinition()) { + foundDefinition = true; + continue; + } + + var signature = signatures[i]; + if (getPrettyTypeName && candidateSignature) { + signature = candidateSignature; + } + + result.push(signature.getSignatureTypeNameEx(prefix, shortform, brackets, scopeSymbol)); + if (getPrettyTypeName) { + break; + } + } + + if (getPrettyTypeName && result.length && len > 1) { + var lastMemberName = result[result.length - 1]; + for (var i = i + 1; i < len; i++) { + if (signatures[i].isDefinition()) { + foundDefinition = true; + break; + } + } + var overloadString = TypeScript.getLocalizedText(TypeScript.DiagnosticCode._0_overload_s, [foundDefinition ? len - 2 : len - 1]); + lastMemberName.add(TypeScript.MemberName.create(overloadString)); + } + + return result; + }; + + PullSignatureSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + var s = this.getSignatureTypeNameEx(this.getScopedNameEx().toString(), false, false, scopeSymbol, undefined, useConstraintInName).toString(); + return s; + }; + + PullSignatureSymbol.prototype.getSignatureTypeNameEx = function (prefix, shortform, brackets, scopeSymbol, getParamMarkerInfo, getTypeParamMarkerInfo) { + var typeParamterBuilder = new TypeScript.MemberNameArray(); + + typeParamterBuilder.add(PullSymbol.getTypeParameterStringEx(this.getTypeParameters(), scopeSymbol, getTypeParamMarkerInfo, true)); + + if (brackets) { + typeParamterBuilder.add(TypeScript.MemberName.create("[")); + } else { + typeParamterBuilder.add(TypeScript.MemberName.create("(")); + } + + var builder = new TypeScript.MemberNameArray(); + builder.prefix = prefix; + + if (getTypeParamMarkerInfo) { + builder.prefix = prefix; + builder.addAll(typeParamterBuilder.entries); + } else { + builder.prefix = prefix + typeParamterBuilder.toString(); + } + + var params = this.parameters; + var paramLen = params.length; + for (var i = 0; i < paramLen; i++) { + var paramType = params[i].type; + var typeString = paramType ? ": " : ""; + var paramIsVarArg = params[i].isVarArg; + var varArgPrefix = paramIsVarArg ? "..." : ""; + var optionalString = (!paramIsVarArg && params[i].isOptional) ? "?" : ""; + if (getParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + builder.add(TypeScript.MemberName.create(varArgPrefix + params[i].getScopedNameEx(scopeSymbol).toString() + optionalString + typeString)); + if (paramType) { + builder.add(paramType.getScopedNameEx(scopeSymbol)); + } + if (getParamMarkerInfo) { + builder.add(new TypeScript.MemberName()); + } + if (i < paramLen - 1) { + builder.add(TypeScript.MemberName.create(", ")); + } + } + + 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) { + builder.add(this.returnType.getScopedNameEx(scopeSymbol)); + } else { + builder.add(TypeScript.MemberName.create("any")); + } + + return builder; + }; + + PullSignatureSymbol.prototype.forAllParameterTypes = function (length, predicate) { + if (this.parameters.length < length && !this.hasVarArgs) { + length = this.parameters.length; + } + + for (var i = 0; i < length; i++) { + var paramType = this.getParameterTypeAtIndex(i); + if (!predicate(paramType, i)) { + return false; + } + } + + return true; + }; + + PullSignatureSymbol.prototype.forAllCorrespondingParameterTypesInThisAndOtherSignature = function (otherSignature, predicate) { + var length; + if (this.hasVarArgs) { + length = otherSignature.hasVarArgs ? Math.max(this.parameters.length, otherSignature.parameters.length) : otherSignature.parameters.length; + } else { + length = otherSignature.hasVarArgs ? this.parameters.length : Math.min(this.parameters.length, otherSignature.parameters.length); + } + + for (var i = 0; i < length; i++) { + var thisParamType = this.getParameterTypeAtIndex(i); + var otherParamType = otherSignature.getParameterTypeAtIndex(i); + if (!predicate(thisParamType, otherParamType, i)) { + return false; + } + } + + return true; + }; + + PullSignatureSymbol.prototype.wrapsSomeTypeParameter = function (typeParameterArgumentMap) { + return this.getWrappingTypeParameterID(typeParameterArgumentMap) !== 0; + }; + + PullSignatureSymbol.prototype.getWrappingTypeParameterID = function (typeParameterArgumentMap) { + var signature = this; + if (signature.inWrapCheck) { + return 0; + } + + this._wrapsTypeParameterCache = this._wrapsTypeParameterCache || new TypeScript.WrapsTypeParameterCache(); + + var wrappingTypeParameterID = this._wrapsTypeParameterCache.getWrapsTypeParameter(typeParameterArgumentMap); + if (wrappingTypeParameterID === undefined) { + wrappingTypeParameterID = this.getWrappingTypeParameterIDWorker(typeParameterArgumentMap); + this._wrapsTypeParameterCache.setWrapsTypeParameter(typeParameterArgumentMap, wrappingTypeParameterID); + } + + return wrappingTypeParameterID; + }; + + PullSignatureSymbol.prototype.getWrappingTypeParameterIDWorker = function (typeParameterArgumentMap) { + var signature = this; + signature.inWrapCheck = true; + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(signature); + var wrappingTypeParameterID = signature.returnType ? signature.returnType.getWrappingTypeParameterID(typeParameterArgumentMap) : 0; + + var parameters = signature.parameters; + for (var i = 0; !wrappingTypeParameterID && i < parameters.length; i++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(parameters[i]); + wrappingTypeParameterID = parameters[i].type.getWrappingTypeParameterID(typeParameterArgumentMap); + } + + signature.inWrapCheck = false; + + return wrappingTypeParameterID; + }; + + PullSignatureSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference = function (enclosingType, knownWrapMap) { + var wrapsIntoInfinitelyExpandingTypeReference = knownWrapMap.valueAt(this.pullSymbolID, enclosingType.pullSymbolID); + if (wrapsIntoInfinitelyExpandingTypeReference != undefined) { + return wrapsIntoInfinitelyExpandingTypeReference; + } + + if (this.inWrapInfiniteExpandingReferenceCheck) { + return false; + } + + this.inWrapInfiniteExpandingReferenceCheck = true; + wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker(enclosingType, knownWrapMap); + knownWrapMap.setValueAt(this.pullSymbolID, enclosingType.pullSymbolID, wrapsIntoInfinitelyExpandingTypeReference); + this.inWrapInfiniteExpandingReferenceCheck = false; + + return wrapsIntoInfinitelyExpandingTypeReference; + }; + + PullSignatureSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker = function (enclosingType, knownWrapMap) { + if (this.returnType && this.returnType._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; + } + + var parameters = this.parameters; + + for (var i = 0; i < parameters.length; i++) { + if (parameters[i].type && parameters[i].type._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; + } + } + + return false; + }; + return PullSignatureSymbol; + })(PullSymbol); + TypeScript.PullSignatureSymbol = PullSignatureSymbol; + + var PullTypeSymbol = (function (_super) { + __extends(PullTypeSymbol, _super); + function PullTypeSymbol(name, kind) { + _super.call(this, name, kind); + this._members = TypeScript.sentinelEmptyArray; + this._enclosedMemberTypes = null; + this._enclosedMemberContainers = null; + this._typeParameters = null; + this._allowedToReferenceTypeParameters = null; + this._specializedVersionsOfThisType = null; + this._arrayVersionOfThisType = null; + this._implementedTypes = null; + this._extendedTypes = null; + this._typesThatExplicitlyImplementThisType = null; + this._typesThatExtendThisType = null; + this._callSignatures = null; + this._allCallSignatures = null; + this._constructSignatures = null; + this._allConstructSignatures = null; + this._indexSignatures = null; + this._allIndexSignatures = null; + this._allIndexSignaturesOfAugmentedType = null; + this._memberNameCache = null; + this._enclosedTypeNameCache = null; + this._enclosedContainerCache = null; + this._typeParameterNameCache = null; + this._containedNonMemberNameCache = null; + this._containedNonMemberTypeNameCache = null; + this._containedNonMemberContainerCache = null; + this._simpleInstantiationCache = null; + this._complexInstantiationCache = null; + this._hasGenericSignature = false; + this._hasGenericMember = false; + this._hasBaseTypeConflict = false; + this._knownBaseTypeCount = 0; + this._associatedContainerTypeSymbol = null; + this._constructorMethod = null; + this._hasDefaultConstructor = false; + this._functionSymbol = null; + this._inMemberTypeNameEx = false; + this.inSymbolPrivacyCheck = false; + this.inWrapCheck = false; + this.inWrapInfiniteExpandingReferenceCheck = false; + this.typeReference = null; + this._widenedType = null; + this._isArrayNamedTypeReference = undefined; + this.type = this; + } + PullTypeSymbol.prototype.isArrayNamedTypeReference = function () { + if (this._isArrayNamedTypeReference === undefined) { + this._isArrayNamedTypeReference = this.computeIsArrayNamedTypeReference(); + } + + return this._isArrayNamedTypeReference; + }; + + PullTypeSymbol.prototype.computeIsArrayNamedTypeReference = function () { + var typeArgs = this.getTypeArguments(); + if (typeArgs && this.getTypeArguments().length === 1 && this.name === "Array") { + var declaration = this.getDeclarations()[0]; + + if (declaration && declaration.getParentDecl() && declaration.getParentDecl().getParentDecl() === null) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.isType = function () { + return true; + }; + PullTypeSymbol.prototype.isClass = function () { + return this.kind === 8 /* Class */ || (this._constructorMethod !== null); + }; + PullTypeSymbol.prototype.isFunction = function () { + return (this.kind & (33554432 /* ConstructorType */ | 16777216 /* FunctionType */)) !== 0; + }; + PullTypeSymbol.prototype.isConstructor = function () { + return this.kind === 33554432 /* ConstructorType */ || (this._associatedContainerTypeSymbol && this._associatedContainerTypeSymbol.isClass()); + }; + PullTypeSymbol.prototype.isTypeParameter = function () { + return false; + }; + PullTypeSymbol.prototype.isTypeVariable = function () { + return false; + }; + PullTypeSymbol.prototype.isError = function () { + return false; + }; + PullTypeSymbol.prototype.isEnum = function () { + return this.kind === 64 /* Enum */; + }; + + PullTypeSymbol.prototype.getTypeParameterArgumentMap = function () { + return null; + }; + + PullTypeSymbol.prototype.isObject = function () { + return TypeScript.hasFlag(this.kind, 8 /* Class */ | 33554432 /* ConstructorType */ | 64 /* Enum */ | 16777216 /* FunctionType */ | 16 /* Interface */ | 8388608 /* ObjectType */ | 256 /* ObjectLiteral */); + }; + + PullTypeSymbol.prototype.isFunctionType = function () { + return this.getCallSignatures().length > 0 || this.getConstructSignatures().length > 0; + }; + + PullTypeSymbol.prototype.getKnownBaseTypeCount = function () { + return this._knownBaseTypeCount; + }; + PullTypeSymbol.prototype.resetKnownBaseTypeCount = function () { + this._knownBaseTypeCount = 0; + }; + PullTypeSymbol.prototype.incrementKnownBaseCount = function () { + this._knownBaseTypeCount++; + }; + + PullTypeSymbol.prototype.setHasBaseTypeConflict = function () { + this._hasBaseTypeConflict = true; + }; + PullTypeSymbol.prototype.hasBaseTypeConflict = function () { + return this._hasBaseTypeConflict; + }; + + PullTypeSymbol.prototype.hasMembers = function () { + if (this._members !== TypeScript.sentinelEmptyArray) { + return true; + } + + var parents = this.getExtendedTypes(); + + for (var i = 0; i < parents.length; i++) { + if (parents[i].hasMembers()) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.setHasGenericSignature = function () { + this._hasGenericSignature = true; + }; + PullTypeSymbol.prototype.getHasGenericSignature = function () { + return this._hasGenericSignature; + }; + + PullTypeSymbol.prototype.setHasGenericMember = function () { + this._hasGenericMember = true; + }; + PullTypeSymbol.prototype.getHasGenericMember = function () { + return this._hasGenericMember; + }; + + PullTypeSymbol.prototype.setAssociatedContainerType = function (type) { + this._associatedContainerTypeSymbol = type; + }; + + PullTypeSymbol.prototype.getAssociatedContainerType = function () { + return this._associatedContainerTypeSymbol; + }; + + PullTypeSymbol.prototype.getArrayType = function () { + return this._arrayVersionOfThisType; + }; + + PullTypeSymbol.prototype.getElementType = function () { + return null; + }; + + PullTypeSymbol.prototype.setArrayType = function (arrayType) { + this._arrayVersionOfThisType = arrayType; + }; + + PullTypeSymbol.prototype.getFunctionSymbol = function () { + return this._functionSymbol; + }; + + PullTypeSymbol.prototype.setFunctionSymbol = function (symbol) { + if (symbol) { + this._functionSymbol = symbol; + } + }; + + PullTypeSymbol.prototype.findContainedNonMember = function (name) { + if (!this._containedNonMemberNameCache) { + return null; + } + + return this._containedNonMemberNameCache[name]; + }; + + PullTypeSymbol.prototype.findContainedNonMemberType = function (typeName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + if (!this._containedNonMemberTypeNameCache) { + return null; + } + + var nonMemberSymbol = this._containedNonMemberTypeNameCache[typeName]; + + if (nonMemberSymbol && kind !== 0 /* None */) { + nonMemberSymbol = TypeScript.hasFlag(nonMemberSymbol.kind, kind) ? nonMemberSymbol : null; + } + + return nonMemberSymbol; + }; + + PullTypeSymbol.prototype.findContainedNonMemberContainer = function (containerName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + if (!this._containedNonMemberContainerCache) { + return null; + } + + var nonMemberSymbol = this._containedNonMemberContainerCache[containerName]; + + if (nonMemberSymbol && kind !== 0 /* None */) { + nonMemberSymbol = TypeScript.hasFlag(nonMemberSymbol.kind, kind) ? nonMemberSymbol : null; + } + + return nonMemberSymbol; + }; + + PullTypeSymbol.prototype.addMember = function (memberSymbol) { + if (!memberSymbol) { + return; + } + + memberSymbol.setContainer(this); + + if (!this._memberNameCache) { + this._memberNameCache = TypeScript.createIntrinsicsObject(); + } + + if (this._members === TypeScript.sentinelEmptyArray) { + this._members = []; + } + + this._members.push(memberSymbol); + this._memberNameCache[memberSymbol.name] = memberSymbol; + }; + + PullTypeSymbol.prototype.addEnclosedMemberType = function (enclosedType) { + if (!enclosedType) { + return; + } + + enclosedType.setContainer(this); + + if (!this._enclosedTypeNameCache) { + this._enclosedTypeNameCache = TypeScript.createIntrinsicsObject(); + } + + if (!this._enclosedMemberTypes) { + this._enclosedMemberTypes = []; + } + + this._enclosedMemberTypes[this._enclosedMemberTypes.length] = enclosedType; + this._enclosedTypeNameCache[enclosedType.name] = enclosedType; + }; + + PullTypeSymbol.prototype.addEnclosedMemberContainer = function (enclosedContainer) { + if (!enclosedContainer) { + return; + } + + enclosedContainer.setContainer(this); + + if (!this._enclosedContainerCache) { + this._enclosedContainerCache = TypeScript.createIntrinsicsObject(); + } + + if (!this._enclosedMemberContainers) { + this._enclosedMemberContainers = []; + } + + this._enclosedMemberContainers[this._enclosedMemberContainers.length] = enclosedContainer; + this._enclosedContainerCache[enclosedContainer.name] = enclosedContainer; + }; + + PullTypeSymbol.prototype.addEnclosedNonMember = function (enclosedNonMember) { + if (!enclosedNonMember) { + return; + } + + enclosedNonMember.setContainer(this); + + if (!this._containedNonMemberNameCache) { + this._containedNonMemberNameCache = TypeScript.createIntrinsicsObject(); + } + + this._containedNonMemberNameCache[enclosedNonMember.name] = enclosedNonMember; + }; + + PullTypeSymbol.prototype.addEnclosedNonMemberType = function (enclosedNonMemberType) { + if (!enclosedNonMemberType) { + return; + } + + enclosedNonMemberType.setContainer(this); + + if (!this._containedNonMemberTypeNameCache) { + this._containedNonMemberTypeNameCache = TypeScript.createIntrinsicsObject(); + } + + this._containedNonMemberTypeNameCache[enclosedNonMemberType.name] = enclosedNonMemberType; + }; + + PullTypeSymbol.prototype.addEnclosedNonMemberContainer = function (enclosedNonMemberContainer) { + if (!enclosedNonMemberContainer) { + return; + } + + enclosedNonMemberContainer.setContainer(this); + + if (!this._containedNonMemberContainerCache) { + this._containedNonMemberContainerCache = TypeScript.createIntrinsicsObject(); + } + + this._containedNonMemberContainerCache[enclosedNonMemberContainer.name] = enclosedNonMemberContainer; + }; + + PullTypeSymbol.prototype.addTypeParameter = function (typeParameter) { + if (!typeParameter) { + return; + } + + if (!typeParameter.getContainer()) { + typeParameter.setContainer(this); + } + + if (!this._typeParameterNameCache) { + this._typeParameterNameCache = TypeScript.createIntrinsicsObject(); + } + + if (!this._typeParameters) { + this._typeParameters = []; + } + + this._typeParameters[this._typeParameters.length] = typeParameter; + this._typeParameterNameCache[typeParameter.getName()] = typeParameter; + }; + + PullTypeSymbol.prototype.getMembers = function () { + return this._members; + }; + + PullTypeSymbol.prototype.setHasDefaultConstructor = function (hasOne) { + if (typeof hasOne === "undefined") { hasOne = true; } + this._hasDefaultConstructor = hasOne; + }; + + PullTypeSymbol.prototype.getHasDefaultConstructor = function () { + return this._hasDefaultConstructor; + }; + + PullTypeSymbol.prototype.getConstructorMethod = function () { + return this._constructorMethod; + }; + + PullTypeSymbol.prototype.setConstructorMethod = function (constructorMethod) { + this._constructorMethod = constructorMethod; + }; + + PullTypeSymbol.prototype.getTypeParameters = function () { + if (!this._typeParameters) { + return TypeScript.sentinelEmptyArray; + } + + return this._typeParameters; + }; + + PullTypeSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + if (!!(this.kind && 8216 /* SomeInstantiatableType */) && this.isNamedTypeSymbol() && !this.isTypeParameter()) { + return this.getTypeParameters(); + } + + if (!this._allowedToReferenceTypeParameters) { + this._allowedToReferenceTypeParameters = TypeScript.PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl(this.getDeclarations()[0]); + } + + return this._allowedToReferenceTypeParameters; + }; + + PullTypeSymbol.prototype.isGeneric = function () { + return (this._typeParameters && this._typeParameters.length > 0) || this._hasGenericSignature || this._hasGenericMember || this.isArrayNamedTypeReference(); + }; + + PullTypeSymbol.prototype.canUseSimpleInstantiationCache = function (typeArgumentMap) { + if (this.isTypeParameter()) { + return true; + } + + var typeParameters = this.getTypeParameters(); + return typeArgumentMap && this.isNamedTypeSymbol() && typeParameters.length === 1 && typeArgumentMap[typeParameters[0].pullSymbolID].kind !== 8388608 /* ObjectType */; + }; + + PullTypeSymbol.prototype.getSimpleInstantiationCacheId = function (typeArgumentMap) { + if (this.isTypeParameter()) { + return typeArgumentMap[0].pullSymbolID; + } + + return typeArgumentMap[this.getTypeParameters()[0].pullSymbolID].pullSymbolID; + }; + + PullTypeSymbol.prototype.addSpecialization = function (specializedVersionOfThisType, typeArgumentMap) { + if (this.canUseSimpleInstantiationCache(typeArgumentMap)) { + if (!this._simpleInstantiationCache) { + this._simpleInstantiationCache = []; + } + + this._simpleInstantiationCache[this.getSimpleInstantiationCacheId(typeArgumentMap)] = specializedVersionOfThisType; + } else { + if (!this._complexInstantiationCache) { + this._complexInstantiationCache = TypeScript.createIntrinsicsObject(); + } + + this._complexInstantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)] = specializedVersionOfThisType; + } + + if (!this._specializedVersionsOfThisType) { + this._specializedVersionsOfThisType = []; + } + + this._specializedVersionsOfThisType.push(specializedVersionOfThisType); + }; + + PullTypeSymbol.prototype.getSpecialization = function (typeArgumentMap) { + if (this.canUseSimpleInstantiationCache(typeArgumentMap)) { + if (!this._simpleInstantiationCache) { + return null; + } + + var result = this._simpleInstantiationCache[this.getSimpleInstantiationCacheId(typeArgumentMap)]; + return result || null; + } else { + if (!this._complexInstantiationCache) { + return null; + } + + if (this.getAllowedToReferenceTypeParameters().length == 0) { + return this; + } + + var result = this._complexInstantiationCache[getIDForTypeSubstitutions(this, typeArgumentMap)]; + return result || null; + } + }; + + PullTypeSymbol.prototype.getKnownSpecializations = function () { + if (!this._specializedVersionsOfThisType) { + return TypeScript.sentinelEmptyArray; + } + + return this._specializedVersionsOfThisType; + }; + + PullTypeSymbol.prototype.getTypeArguments = function () { + return null; + }; + + PullTypeSymbol.prototype.getTypeArgumentsOrTypeParameters = function () { + return this.getTypeParameters(); + }; + + PullTypeSymbol.prototype.addCallOrConstructSignaturePrerequisiteBase = function (signature) { + if (signature.isGeneric()) { + this._hasGenericSignature = true; + } + + signature.functionType = this; + }; + + PullTypeSymbol.prototype.addCallSignaturePrerequisite = function (callSignature) { + if (!this._callSignatures) { + this._callSignatures = []; + } + + this.addCallOrConstructSignaturePrerequisiteBase(callSignature); + }; + + PullTypeSymbol.prototype.appendCallSignature = function (callSignature) { + this.addCallSignaturePrerequisite(callSignature); + this._callSignatures.push(callSignature); + }; + + PullTypeSymbol.prototype.insertCallSignatureAtIndex = function (callSignature, index) { + this.addCallSignaturePrerequisite(callSignature); + TypeScript.Debug.assert(index <= this._callSignatures.length); + if (index === this._callSignatures.length) { + this._callSignatures.push(callSignature); + } else { + this._callSignatures.splice(index, 0, callSignature); + } + }; + + PullTypeSymbol.prototype.addConstructSignaturePrerequisite = function (constructSignature) { + if (!this._constructSignatures) { + this._constructSignatures = []; + } + + this.addCallOrConstructSignaturePrerequisiteBase(constructSignature); + }; + + PullTypeSymbol.prototype.appendConstructSignature = function (constructSignature) { + this.addConstructSignaturePrerequisite(constructSignature); + this._constructSignatures.push(constructSignature); + }; + + PullTypeSymbol.prototype.insertConstructSignatureAtIndex = function (constructSignature, index) { + this.addConstructSignaturePrerequisite(constructSignature); + TypeScript.Debug.assert(index <= this._constructSignatures.length); + if (index === this._constructSignatures.length) { + this._constructSignatures.push(constructSignature); + } else { + this._constructSignatures.splice(index, 0, constructSignature); + } + }; + + PullTypeSymbol.prototype.addIndexSignature = function (indexSignature) { + if (!this._indexSignatures) { + this._indexSignatures = []; + } + + this._indexSignatures[this._indexSignatures.length] = indexSignature; + + if (indexSignature.isGeneric()) { + this._hasGenericSignature = true; + } + + indexSignature.functionType = this; + }; + + PullTypeSymbol.prototype.hasOwnCallSignatures = function () { + return this._callSignatures !== null; + }; + + PullTypeSymbol.prototype.getOwnCallSignatures = function () { + return this._callSignatures || TypeScript.sentinelEmptyArray; + }; + + PullTypeSymbol.prototype.getCallSignatures = function () { + if (this._allCallSignatures) { + return this._allCallSignatures; + } + + var signatures = []; + + if (this._callSignatures) { + signatures = signatures.concat(this._callSignatures); + } + + if (this._extendedTypes && this.kind === 16 /* Interface */) { + for (var i = 0; i < this._extendedTypes.length; i++) { + if (this._extendedTypes[i].hasBase(this)) { + continue; + } + + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._callSignatures, this._extendedTypes[i].getCallSignatures(), signatures); + } + } + + this._allCallSignatures = signatures; + + return signatures; + }; + + PullTypeSymbol.prototype.hasOwnConstructSignatures = function () { + return this._constructSignatures !== null; + }; + + PullTypeSymbol.prototype.getOwnDeclaredConstructSignatures = function () { + return this._constructSignatures || TypeScript.sentinelEmptyArray; + }; + + PullTypeSymbol.prototype.getConstructSignatures = function () { + if (this._allConstructSignatures) { + return this._allConstructSignatures; + } + + var signatures = []; + + if (this._constructSignatures) { + signatures = signatures.concat(this._constructSignatures); + } else if (this.isConstructor()) { + if (this._extendedTypes && this._extendedTypes.length > 0) { + signatures = this.getBaseClassConstructSignatures(this._extendedTypes[0]); + } else { + signatures = [this.getDefaultClassConstructSignature()]; + } + } + + if (this._extendedTypes && this.kind === 16 /* Interface */) { + for (var i = 0; i < this._extendedTypes.length; i++) { + if (this._extendedTypes[i].hasBase(this)) { + continue; + } + + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._constructSignatures, this._extendedTypes[i].getConstructSignatures(), signatures); + } + } + + this._allConstructSignatures = signatures; + + return signatures; + }; + + PullTypeSymbol.prototype.hasOwnIndexSignatures = function () { + return this._indexSignatures !== null; + }; + + PullTypeSymbol.prototype.getOwnIndexSignatures = function () { + return this._indexSignatures || TypeScript.sentinelEmptyArray; + }; + + PullTypeSymbol.prototype.getIndexSignatures = function () { + if (this._allIndexSignatures) { + return this._allIndexSignatures; + } + + var signatures = []; + + if (this._indexSignatures) { + signatures = signatures.concat(this._indexSignatures); + } + + if (this._extendedTypes) { + for (var i = 0; i < this._extendedTypes.length; i++) { + if (this._extendedTypes[i].hasBase(this)) { + continue; + } + + this._getResolver()._addUnhiddenSignaturesFromBaseType(this._indexSignatures, this._extendedTypes[i].getIndexSignatures(), signatures); + } + } + + this._allIndexSignatures = signatures; + + return signatures; + }; + + PullTypeSymbol.prototype.getIndexSignaturesOfAugmentedType = function (resolver, globalFunctionInterface, globalObjectInterface) { + if (!this._allIndexSignaturesOfAugmentedType) { + var initialIndexSignatures = this.getIndexSignatures(); + var shouldAddFunctionSignatures = false; + var shouldAddObjectSignatures = false; + + if (globalFunctionInterface && this.isFunctionType() && this !== globalFunctionInterface) { + var functionIndexSignatures = globalFunctionInterface.getIndexSignatures(); + if (functionIndexSignatures.length) { + shouldAddFunctionSignatures = true; + } + } + + if (globalObjectInterface && this !== globalObjectInterface) { + var objectIndexSignatures = globalObjectInterface.getIndexSignatures(); + if (objectIndexSignatures.length) { + shouldAddObjectSignatures = true; + } + } + + if (shouldAddFunctionSignatures || shouldAddObjectSignatures) { + this._allIndexSignaturesOfAugmentedType = initialIndexSignatures.slice(0); + if (shouldAddFunctionSignatures) { + resolver._addUnhiddenSignaturesFromBaseType(initialIndexSignatures, functionIndexSignatures, this._allIndexSignaturesOfAugmentedType); + } + if (shouldAddObjectSignatures) { + if (shouldAddFunctionSignatures) { + initialIndexSignatures = initialIndexSignatures.concat(functionIndexSignatures); + } + resolver._addUnhiddenSignaturesFromBaseType(initialIndexSignatures, objectIndexSignatures, this._allIndexSignaturesOfAugmentedType); + } + } else { + this._allIndexSignaturesOfAugmentedType = initialIndexSignatures; + } + } + + return this._allIndexSignaturesOfAugmentedType; + }; + + PullTypeSymbol.prototype.getBaseClassConstructSignatures = function (baseType) { + TypeScript.Debug.assert(this.isConstructor() && baseType.isConstructor()); + var instanceTypeSymbol = this.getAssociatedContainerType(); + TypeScript.Debug.assert(instanceTypeSymbol.getDeclarations().length === 1); + if (baseType.hasBase(this)) { + return null; + } + + var baseConstructSignatures = baseType.getConstructSignatures(); + var signatures = []; + for (var i = 0; i < baseConstructSignatures.length; i++) { + var baseSignature = baseConstructSignatures[i]; + + baseSignature._resolveDeclaredSymbol(); + var currentSignature = new PullSignatureSymbol(2097152 /* ConstructSignature */, baseSignature.isDefinition()); + currentSignature.returnType = instanceTypeSymbol; + currentSignature.addTypeParametersFromReturnType(); + for (var j = 0; j < baseSignature.parameters.length; j++) { + currentSignature.addParameter(baseSignature.parameters[j], baseSignature.parameters[j].isOptional); + } + if (baseSignature.parameters.length > 0) { + currentSignature.hasVarArgs = baseSignature.parameters[baseSignature.parameters.length - 1].isVarArg; + } + + currentSignature.addDeclaration(instanceTypeSymbol.getDeclarations()[0]); + this.addCallOrConstructSignaturePrerequisiteBase(currentSignature); + signatures.push(currentSignature); + } + + return signatures; + }; + + PullTypeSymbol.prototype.getDefaultClassConstructSignature = function () { + TypeScript.Debug.assert(this.isConstructor()); + var instanceTypeSymbol = this.getAssociatedContainerType(); + TypeScript.Debug.assert(instanceTypeSymbol.getDeclarations().length == 1); + var signature = new PullSignatureSymbol(2097152 /* ConstructSignature */, true); + signature.returnType = instanceTypeSymbol; + signature.addTypeParametersFromReturnType(); + signature.addDeclaration(instanceTypeSymbol.getDeclarations()[0]); + this.addCallOrConstructSignaturePrerequisiteBase(signature); + + return signature; + }; + + PullTypeSymbol.prototype.addImplementedType = function (implementedType) { + if (!implementedType) { + return; + } + + if (!this._implementedTypes) { + this._implementedTypes = []; + } + + this._implementedTypes[this._implementedTypes.length] = implementedType; + + implementedType.addTypeThatExplicitlyImplementsThisType(this); + }; + + PullTypeSymbol.prototype.getImplementedTypes = function () { + if (!this._implementedTypes) { + return TypeScript.sentinelEmptyArray; + } + + return this._implementedTypes; + }; + + PullTypeSymbol.prototype.addExtendedType = function (extendedType) { + if (!extendedType) { + return; + } + + if (!this._extendedTypes) { + this._extendedTypes = []; + } + + this._extendedTypes[this._extendedTypes.length] = extendedType; + + extendedType.addTypeThatExtendsThisType(this); + }; + + PullTypeSymbol.prototype.getExtendedTypes = function () { + if (!this._extendedTypes) { + return TypeScript.sentinelEmptyArray; + } + + return this._extendedTypes; + }; + + PullTypeSymbol.prototype.addTypeThatExtendsThisType = function (type) { + if (!type) { + return; + } + + if (!this._typesThatExtendThisType) { + this._typesThatExtendThisType = []; + } + + this._typesThatExtendThisType[this._typesThatExtendThisType.length] = type; + }; + + PullTypeSymbol.prototype.getTypesThatExtendThisType = function () { + if (!this._typesThatExtendThisType) { + this._typesThatExtendThisType = []; + } + + return this._typesThatExtendThisType; + }; + + PullTypeSymbol.prototype.addTypeThatExplicitlyImplementsThisType = function (type) { + if (!type) { + return; + } + + if (!this._typesThatExplicitlyImplementThisType) { + this._typesThatExplicitlyImplementThisType = []; + } + + this._typesThatExplicitlyImplementThisType[this._typesThatExplicitlyImplementThisType.length] = type; + }; + + PullTypeSymbol.prototype.getTypesThatExplicitlyImplementThisType = function () { + if (!this._typesThatExplicitlyImplementThisType) { + this._typesThatExplicitlyImplementThisType = []; + } + + return this._typesThatExplicitlyImplementThisType; + }; + + PullTypeSymbol.prototype.hasBase = function (potentialBase, visited) { + if (typeof visited === "undefined") { visited = []; } + if (this === potentialBase || this.getRootSymbol() === potentialBase || this === potentialBase.getRootSymbol()) { + return true; + } + + if (TypeScript.ArrayUtilities.contains(visited, this)) { + return true; + } + + visited.push(this); + + var extendedTypes = this.getExtendedTypes(); + + for (var i = 0; i < extendedTypes.length; i++) { + if (extendedTypes[i].hasBase(potentialBase, visited)) { + return true; + } + } + + var implementedTypes = this.getImplementedTypes(); + + for (var i = 0; i < implementedTypes.length; i++) { + if (implementedTypes[i].hasBase(potentialBase, visited)) { + return true; + } + } + + visited.pop(); + + return false; + }; + + PullTypeSymbol.prototype.isValidBaseKind = function (baseType, isExtendedType) { + if (baseType.isError()) { + return false; + } + + var thisIsClass = this.isClass(); + if (isExtendedType) { + if (thisIsClass) { + return baseType.kind === 8 /* Class */; + } + } else { + if (!thisIsClass) { + return false; + } + } + + return !!(baseType.kind & (16 /* Interface */ | 8 /* Class */)); + }; + + PullTypeSymbol.prototype.findMember = function (name, lookInParent) { + var memberSymbol = null; + + if (this._memberNameCache) { + memberSymbol = this._memberNameCache[name]; + } + + if (memberSymbol || !lookInParent) { + return memberSymbol; + } + + if (this._extendedTypes) { + for (var i = 0; i < this._extendedTypes.length; i++) { + memberSymbol = this._extendedTypes[i].findMember(name, lookInParent); + + if (memberSymbol) { + return memberSymbol; + } + } + } + + return null; + }; + + PullTypeSymbol.prototype.findNestedType = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + var memberSymbol; + + if (!this._enclosedTypeNameCache) { + return null; + } + + memberSymbol = this._enclosedTypeNameCache[name]; + + if (memberSymbol && kind !== 0 /* None */) { + memberSymbol = TypeScript.hasFlag(memberSymbol.kind, kind) ? memberSymbol : null; + } + + return memberSymbol; + }; + + PullTypeSymbol.prototype.findNestedContainer = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + var memberSymbol; + + if (!this._enclosedContainerCache) { + return null; + } + + memberSymbol = this._enclosedContainerCache[name]; + + if (memberSymbol && kind !== 0 /* None */) { + memberSymbol = TypeScript.hasFlag(memberSymbol.kind, kind) ? memberSymbol : null; + } + + return memberSymbol; + }; + + PullTypeSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisiblity) { + var allMembers = []; + + if (this._members !== TypeScript.sentinelEmptyArray) { + for (var i = 0, n = this._members.length; i < n; i++) { + var member = this._members[i]; + if ((member.kind & searchDeclKind) && (memberVisiblity !== 2 /* externallyVisible */ || !member.anyDeclHasFlag(2 /* Private */))) { + allMembers[allMembers.length] = member; + } + } + } + + if (this._extendedTypes) { + var extenedMembersVisibility = memberVisiblity !== 0 /* all */ ? 2 /* externallyVisible */ : 0 /* all */; + + for (var i = 0, n = this._extendedTypes.length; i < n; i++) { + var extendedMembers = this._extendedTypes[i].getAllMembers(searchDeclKind, extenedMembersVisibility); + + for (var j = 0, m = extendedMembers.length; j < m; j++) { + var extendedMember = extendedMembers[j]; + if (!(this._memberNameCache && this._memberNameCache[extendedMember.name])) { + allMembers[allMembers.length] = extendedMember; + } + } + } + } + + if (this.isContainer()) { + if (this._enclosedMemberTypes) { + for (var i = 0; i < this._enclosedMemberTypes.length; i++) { + allMembers[allMembers.length] = this._enclosedMemberTypes[i]; + } + } + if (this._enclosedMemberContainers) { + for (var i = 0; i < this._enclosedMemberContainers.length; i++) { + allMembers[allMembers.length] = this._enclosedMemberContainers[i]; + } + } + } + + return allMembers; + }; + + PullTypeSymbol.prototype.findTypeParameter = function (name) { + if (!this._typeParameterNameCache) { + return null; + } + + return this._typeParameterNameCache[name]; + }; + + PullTypeSymbol.prototype.setResolved = function () { + _super.prototype.setResolved.call(this); + }; + + PullTypeSymbol.prototype.getNamePartForFullName = function () { + var name = _super.prototype.getNamePartForFullName.call(this); + + var typars = this.getTypeArgumentsOrTypeParameters(); + var typarString = PullSymbol.getTypeParameterString(typars, this, true); + return name + typarString; + }; + + PullTypeSymbol.prototype.getScopedName = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName) { + return this.getScopedNameEx(scopeSymbol, skipTypeParametersInName, useConstraintInName, false, false, skipInternalAliasName).toString(); + }; + + PullTypeSymbol.prototype.isNamedTypeSymbol = function () { + var kind = this.kind; + if (kind === 2 /* Primitive */ || kind === 8 /* Class */ || kind === 4 /* Container */ || kind === 32 /* DynamicModule */ || kind === 128 /* TypeAlias */ || kind === 64 /* Enum */ || kind === 8192 /* TypeParameter */ || ((kind === 16 /* Interface */ || kind === 8388608 /* ObjectType */) && this.name !== "")) { + return true; + } + + return false; + }; + + PullTypeSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + var s = this.getScopedNameEx(scopeSymbol, false, useConstraintInName).toString(); + return s; + }; + + PullTypeSymbol.prototype.getScopedNameEx = function (scopeSymbol, skipTypeParametersInName, useConstraintInName, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName, shouldAllowArrayType) { + if (typeof shouldAllowArrayType === "undefined") { shouldAllowArrayType = true; } + if (this.isArrayNamedTypeReference() && shouldAllowArrayType) { + var elementType = this.getElementType(); + var elementMemberName = elementType ? (elementType.isArrayNamedTypeReference() || elementType.isNamedTypeSymbol() ? elementType.getScopedNameEx(scopeSymbol, false, false, getPrettyTypeName, getTypeParamMarkerInfo, skipInternalAliasName) : elementType.getMemberTypeNameEx(false, scopeSymbol, getPrettyTypeName)) : TypeScript.MemberName.create("any"); + return TypeScript.MemberName.create(elementMemberName, "", "[]"); + } + + if (!this.isNamedTypeSymbol()) { + return this.getMemberTypeNameEx(true, scopeSymbol, getPrettyTypeName); + } + + if (skipTypeParametersInName) { + return TypeScript.MemberName.create(_super.prototype.getScopedName.call(this, scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName)); + } else { + var builder = new TypeScript.MemberNameArray(); + builder.prefix = _super.prototype.getScopedName.call(this, scopeSymbol, skipTypeParametersInName, useConstraintInName, skipInternalAliasName); + + var typars = this.getTypeArgumentsOrTypeParameters(); + builder.add(PullSymbol.getTypeParameterStringEx(typars, scopeSymbol, getTypeParamMarkerInfo, useConstraintInName)); + + return builder; + } + }; + + PullTypeSymbol.prototype.hasOnlyOverloadCallSignatures = function () { + var members = this.getMembers(); + var callSignatures = this.getCallSignatures(); + var constructSignatures = this.getConstructSignatures(); + return members.length === 0 && constructSignatures.length === 0 && callSignatures.length > 1; + }; + + PullTypeSymbol.prototype.getTypeOfSymbol = function () { + var associatedContainerType = this.getAssociatedContainerType(); + if (associatedContainerType && associatedContainerType.isNamedTypeSymbol()) { + return associatedContainerType; + } + + var functionSymbol = this.getFunctionSymbol(); + if (functionSymbol && functionSymbol.kind === 16384 /* Function */ && !TypeScript.PullHelpers.isSymbolLocal(functionSymbol)) { + return TypeScript.PullHelpers.isExportedSymbolInClodule(functionSymbol) ? null : functionSymbol; + } + + return null; + }; + + PullTypeSymbol.prototype.getMemberTypeNameEx = function (topLevel, scopeSymbol, getPrettyTypeName) { + var members = this.getMembers(); + var callSignatures = this.getCallSignatures(); + var constructSignatures = this.getConstructSignatures(); + var indexSignatures = this.getIndexSignatures(); + + var typeOfSymbol = this.getTypeOfSymbol(); + if (typeOfSymbol) { + var nameForTypeOf = typeOfSymbol.getScopedNameEx(scopeSymbol, true); + return TypeScript.MemberName.create(nameForTypeOf, "typeof ", ""); + } + + if (members.length > 0 || callSignatures.length > 0 || constructSignatures.length > 0 || indexSignatures.length > 0) { + if (this._inMemberTypeNameEx) { + return TypeScript.MemberName.create("any"); + } + + this._inMemberTypeNameEx = true; + + var allMemberNames = new TypeScript.MemberNameArray(); + var curlies = !topLevel || indexSignatures.length !== 0; + var delim = "; "; + for (var i = 0; i < members.length; i++) { + if (members[i].kind === 65536 /* Method */ && members[i].type.hasOnlyOverloadCallSignatures()) { + var methodCallSignatures = members[i].type.getCallSignatures(); + var nameStr = members[i].getDisplayName(scopeSymbol) + (members[i].isOptional ? "?" : ""); + ; + var methodMemberNames = PullSignatureSymbol.getSignaturesTypeNameEx(methodCallSignatures, nameStr, false, false, scopeSymbol); + allMemberNames.addAll(methodMemberNames); + } else { + var memberTypeName = members[i].getNameAndTypeNameEx(scopeSymbol); + if (memberTypeName.isArray() && memberTypeName.delim === delim) { + allMemberNames.addAll(memberTypeName.entries); + } else { + allMemberNames.add(memberTypeName); + } + } + curlies = true; + } + + var getPrettyFunctionOverload = getPrettyTypeName && !curlies && this.hasOnlyOverloadCallSignatures(); + + var signatureCount = callSignatures.length + constructSignatures.length + indexSignatures.length; + var useShortFormSignature = !curlies && (signatureCount === 1); + var signatureMemberName; + + if (callSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(callSignatures, "", useShortFormSignature, false, scopeSymbol, getPrettyFunctionOverload); + allMemberNames.addAll(signatureMemberName); + } + + if (constructSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(constructSignatures, "new", useShortFormSignature, false, scopeSymbol); + allMemberNames.addAll(signatureMemberName); + } + + if (indexSignatures.length > 0) { + signatureMemberName = PullSignatureSymbol.getSignaturesTypeNameEx(indexSignatures, "", useShortFormSignature, true, scopeSymbol); + allMemberNames.addAll(signatureMemberName); + } + + if ((curlies) || (!getPrettyFunctionOverload && (signatureCount > 1) && topLevel)) { + allMemberNames.prefix = "{ "; + allMemberNames.suffix = "}"; + allMemberNames.delim = delim; + } else if (allMemberNames.entries.length > 1) { + allMemberNames.delim = delim; + } + + this._inMemberTypeNameEx = false; + + return allMemberNames; + } + + return TypeScript.MemberName.create("{}"); + }; + + PullTypeSymbol.prototype.getGenerativeTypeClassification = function (enclosingType) { + return 2 /* Closed */; + }; + + PullTypeSymbol.prototype.wrapsSomeTypeParameter = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + return this.getWrappingTypeParameterID(typeParameterArgumentMap, skipTypeArgumentCheck) != 0; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterID = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + var type = this; + + if (type.isTypeParameter()) { + if (typeParameterArgumentMap[type.pullSymbolID] || typeParameterArgumentMap[type.getRootSymbol().pullSymbolID]) { + return type.pullSymbolID; + } + + var constraint = type.getConstraint(); + var wrappingTypeParameterID = constraint ? constraint.getWrappingTypeParameterID(typeParameterArgumentMap) : 0; + return wrappingTypeParameterID; + } + + if (type.inWrapCheck) { + return 0; + } + + this._wrapsTypeParameterCache = this._wrapsTypeParameterCache || new TypeScript.WrapsTypeParameterCache(); + var wrappingTypeParameterID = this._wrapsTypeParameterCache.getWrapsTypeParameter(typeParameterArgumentMap); + if (wrappingTypeParameterID === undefined) { + wrappingTypeParameterID = this.getWrappingTypeParameterIDWorker(typeParameterArgumentMap, skipTypeArgumentCheck); + + this._wrapsTypeParameterCache.setWrapsTypeParameter(typeParameterArgumentMap, wrappingTypeParameterID); + } + return wrappingTypeParameterID; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterIDFromSignatures = function (signatures, typeParameterArgumentMap) { + for (var i = 0; i < signatures.length; i++) { + var wrappingTypeParameterID = signatures[i].getWrappingTypeParameterID(typeParameterArgumentMap); + if (wrappingTypeParameterID !== 0) { + return wrappingTypeParameterID; + } + } + + return 0; + }; + + PullTypeSymbol.prototype.getWrappingTypeParameterIDWorker = function (typeParameterArgumentMap, skipTypeArgumentCheck) { + var type = this; + var wrappingTypeParameterID = 0; + + if (!skipTypeArgumentCheck) { + type.inWrapCheck = true; + + var typeArguments = type.getTypeArguments(); + + if (type.isGeneric() && !typeArguments) { + typeArguments = type.getTypeParameters(); + } + + if (typeArguments) { + for (var i = 0; !wrappingTypeParameterID && i < typeArguments.length; i++) { + wrappingTypeParameterID = typeArguments[i].getWrappingTypeParameterID(typeParameterArgumentMap); + } + } + } + + if (skipTypeArgumentCheck || !(type.kind & 8216 /* SomeInstantiatableType */) || !type.name) { + var members = type.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + for (var i = 0; !wrappingTypeParameterID && i < members.length; i++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(members[i]); + wrappingTypeParameterID = members[i].type.getWrappingTypeParameterID(typeParameterArgumentMap); + } + + wrappingTypeParameterID = wrappingTypeParameterID || this.getWrappingTypeParameterIDFromSignatures(type.getCallSignatures(), typeParameterArgumentMap) || this.getWrappingTypeParameterIDFromSignatures(type.getConstructSignatures(), typeParameterArgumentMap) || this.getWrappingTypeParameterIDFromSignatures(type.getIndexSignatures(), typeParameterArgumentMap); + } + + if (!skipTypeArgumentCheck) { + type.inWrapCheck = false; + } + + return wrappingTypeParameterID; + }; + + PullTypeSymbol.prototype.wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference = function (enclosingType) { + TypeScript.Debug.assert(this.isNamedTypeSymbol()); + TypeScript.Debug.assert(TypeScript.PullHelpers.getRootType(enclosingType) == enclosingType); + var knownWrapMap = TypeScript.BitMatrix.getBitMatrix(true); + var wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap); + knownWrapMap.release(); + return wrapsIntoInfinitelyExpandingTypeReference; + }; + + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse = function (enclosingType, knownWrapMap) { + var wrapsIntoInfinitelyExpandingTypeReference = knownWrapMap.valueAt(this.pullSymbolID, enclosingType.pullSymbolID); + if (wrapsIntoInfinitelyExpandingTypeReference != undefined) { + return wrapsIntoInfinitelyExpandingTypeReference; + } + + if (this.inWrapInfiniteExpandingReferenceCheck) { + return false; + } + + this.inWrapInfiniteExpandingReferenceCheck = true; + wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker(enclosingType, knownWrapMap); + knownWrapMap.setValueAt(this.pullSymbolID, enclosingType.pullSymbolID, wrapsIntoInfinitelyExpandingTypeReference); + this.inWrapInfiniteExpandingReferenceCheck = false; + + return wrapsIntoInfinitelyExpandingTypeReference; + }; + + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker = function (enclosingType, knownWrapMap) { + var thisRootType = TypeScript.PullHelpers.getRootType(this); + + if (thisRootType != enclosingType) { + var thisIsNamedType = this.isNamedTypeSymbol(); + + if (thisIsNamedType) { + if (thisRootType.inWrapInfiniteExpandingReferenceCheck) { + return false; + } + + thisRootType.inWrapInfiniteExpandingReferenceCheck = true; + } + + var wrapsIntoInfinitelyExpandingTypeReference = this._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceStructure(enclosingType, knownWrapMap); + + if (thisIsNamedType) { + thisRootType.inWrapInfiniteExpandingReferenceCheck = false; + } + + return wrapsIntoInfinitelyExpandingTypeReference; + } + + var enclosingTypeParameters = enclosingType.getTypeParameters(); + var typeArguments = this.getTypeArguments(); + for (var i = 0; i < typeArguments.length; i++) { + if (TypeScript.ArrayUtilities.contains(enclosingTypeParameters, typeArguments[i])) { + continue; + } + + if (typeArguments[i].wrapsSomeTypeParameter(this.getTypeParameterArgumentMap())) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceStructure = function (enclosingType, knownWrapMap) { + var members = this.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + for (var i = 0; i < members.length; i++) { + if (members[i].type && members[i].type._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType, knownWrapMap)) { + return true; + } + } + + var sigs = this.getCallSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + sigs = this.getConstructSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + sigs = this.getIndexSignatures(); + for (var i = 0; i < sigs.length; i++) { + if (sigs[i]._wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType, knownWrapMap)) { + return true; + } + } + + return false; + }; + + PullTypeSymbol.prototype.widenedType = function (resolver, ast, context) { + if (!this._widenedType) { + this._widenedType = resolver.widenType(this, ast, context); + } + return this._widenedType; + }; + return PullTypeSymbol; + })(PullSymbol); + TypeScript.PullTypeSymbol = PullTypeSymbol; + + var PullPrimitiveTypeSymbol = (function (_super) { + __extends(PullPrimitiveTypeSymbol, _super); + function PullPrimitiveTypeSymbol(name) { + _super.call(this, name, 2 /* Primitive */); + + this.isResolved = true; + } + PullPrimitiveTypeSymbol.prototype.isAny = function () { + return !this.isStringConstant() && this.name === "any"; + }; + + PullPrimitiveTypeSymbol.prototype.isNull = function () { + return !this.isStringConstant() && this.name === "null"; + }; + + PullPrimitiveTypeSymbol.prototype.isUndefined = function () { + return !this.isStringConstant() && this.name === "undefined"; + }; + + PullPrimitiveTypeSymbol.prototype.isStringConstant = function () { + return false; + }; + + PullPrimitiveTypeSymbol.prototype.setUnresolved = function () { + }; + + PullPrimitiveTypeSymbol.prototype.getDisplayName = function () { + if (this.isNull() || this.isUndefined()) { + return "any"; + } else { + return _super.prototype.getDisplayName.call(this); + } + }; + return PullPrimitiveTypeSymbol; + })(PullTypeSymbol); + TypeScript.PullPrimitiveTypeSymbol = PullPrimitiveTypeSymbol; + + var PullStringConstantTypeSymbol = (function (_super) { + __extends(PullStringConstantTypeSymbol, _super); + function PullStringConstantTypeSymbol(name) { + _super.call(this, name); + } + PullStringConstantTypeSymbol.prototype.isStringConstant = function () { + return true; + }; + return PullStringConstantTypeSymbol; + })(PullPrimitiveTypeSymbol); + TypeScript.PullStringConstantTypeSymbol = PullStringConstantTypeSymbol; + + var PullErrorTypeSymbol = (function (_super) { + __extends(PullErrorTypeSymbol, _super); + function PullErrorTypeSymbol(_anyType, name) { + _super.call(this, name); + this._anyType = _anyType; + + TypeScript.Debug.assert(this._anyType); + this.isResolved = true; + } + PullErrorTypeSymbol.prototype.isError = function () { + return true; + }; + + PullErrorTypeSymbol.prototype._getResolver = function () { + return this._anyType._getResolver(); + }; + + PullErrorTypeSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + return this._anyType.getName(scopeSymbol, useConstraintInName); + }; + + PullErrorTypeSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { + return this._anyType.getName(scopeSymbol, useConstraintInName); + }; + + PullErrorTypeSymbol.prototype.toString = function (scopeSymbol, useConstraintInName) { + return this._anyType.getName(scopeSymbol, useConstraintInName); + }; + return PullErrorTypeSymbol; + })(PullPrimitiveTypeSymbol); + TypeScript.PullErrorTypeSymbol = PullErrorTypeSymbol; + + var PullContainerSymbol = (function (_super) { + __extends(PullContainerSymbol, _super); + function PullContainerSymbol(name, kind) { + _super.call(this, name, kind); + this.instanceSymbol = null; + this.assignedValue = null; + this.assignedType = null; + this.assignedContainer = null; + } + PullContainerSymbol.prototype.isContainer = function () { + return true; + }; + + PullContainerSymbol.prototype.setInstanceSymbol = function (symbol) { + this.instanceSymbol = symbol; + }; + + PullContainerSymbol.prototype.getInstanceSymbol = function () { + return this.instanceSymbol; + }; + + PullContainerSymbol.prototype.setExportAssignedValueSymbol = function (symbol) { + this.assignedValue = symbol; + }; + + PullContainerSymbol.prototype.getExportAssignedValueSymbol = function () { + return this.assignedValue; + }; + + PullContainerSymbol.prototype.setExportAssignedTypeSymbol = function (type) { + this.assignedType = type; + }; + + PullContainerSymbol.prototype.getExportAssignedTypeSymbol = function () { + return this.assignedType; + }; + + PullContainerSymbol.prototype.setExportAssignedContainerSymbol = function (container) { + this.assignedContainer = container; + }; + + PullContainerSymbol.prototype.getExportAssignedContainerSymbol = function () { + return this.assignedContainer; + }; + + PullContainerSymbol.prototype.hasExportAssignment = function () { + return !!this.assignedValue || !!this.assignedType || !!this.assignedContainer; + }; + + PullContainerSymbol.usedAsSymbol = function (containerSymbol, symbol) { + if (!containerSymbol || !containerSymbol.isContainer()) { + return false; + } + + if (!containerSymbol.isAlias() && containerSymbol.type === symbol) { + return true; + } + + var moduleSymbol = containerSymbol; + var valueExportSymbol = moduleSymbol.getExportAssignedValueSymbol(); + var typeExportSymbol = moduleSymbol.getExportAssignedTypeSymbol(); + var containerExportSymbol = moduleSymbol.getExportAssignedContainerSymbol(); + if (valueExportSymbol || typeExportSymbol || containerExportSymbol) { + if (valueExportSymbol === symbol || typeExportSymbol == symbol || containerExportSymbol == symbol) { + return true; + } + + if (containerExportSymbol != containerSymbol) { + return PullContainerSymbol.usedAsSymbol(containerExportSymbol, symbol); + } + } + + return false; + }; + + PullContainerSymbol.prototype.getInstanceType = function () { + return this.instanceSymbol ? this.instanceSymbol.type : null; + }; + return PullContainerSymbol; + })(PullTypeSymbol); + TypeScript.PullContainerSymbol = PullContainerSymbol; + + var PullTypeAliasSymbol = (function (_super) { + __extends(PullTypeAliasSymbol, _super); + function PullTypeAliasSymbol(name) { + _super.call(this, name, 128 /* TypeAlias */); + this._assignedValue = null; + this._assignedType = null; + this._assignedContainer = null; + this._isUsedAsValue = false; + this._typeUsedExternally = false; + this._isUsedInExportAlias = false; + this.retrievingExportAssignment = false; + this.linkedAliasSymbols = null; + } + PullTypeAliasSymbol.prototype.isUsedInExportedAlias = function () { + this._resolveDeclaredSymbol(); + return this._isUsedInExportAlias; + }; + + PullTypeAliasSymbol.prototype.typeUsedExternally = function () { + this._resolveDeclaredSymbol(); + return this._typeUsedExternally; + }; + + PullTypeAliasSymbol.prototype.isUsedAsValue = function () { + this._resolveDeclaredSymbol(); + return this._isUsedAsValue; + }; + + PullTypeAliasSymbol.prototype.setTypeUsedExternally = function () { + this._typeUsedExternally = true; + }; + + PullTypeAliasSymbol.prototype.setIsUsedInExportedAlias = function () { + this._isUsedInExportAlias = true; + if (this.linkedAliasSymbols) { + this.linkedAliasSymbols.forEach(function (s) { + return s.setIsUsedInExportedAlias(); + }); + } + }; + + PullTypeAliasSymbol.prototype.addLinkedAliasSymbol = function (contingentValueSymbol) { + if (!this.linkedAliasSymbols) { + this.linkedAliasSymbols = [contingentValueSymbol]; + } else { + this.linkedAliasSymbols.push(contingentValueSymbol); + } + }; + + PullTypeAliasSymbol.prototype.setIsUsedAsValue = function () { + this._isUsedAsValue = true; + if (this.linkedAliasSymbols) { + this.linkedAliasSymbols.forEach(function (s) { + return s.setIsUsedAsValue(); + }); + } + }; + + PullTypeAliasSymbol.prototype.assignedValue = function () { + this._resolveDeclaredSymbol(); + return this._assignedValue; + }; + + PullTypeAliasSymbol.prototype.assignedType = function () { + this._resolveDeclaredSymbol(); + return this._assignedType; + }; + + PullTypeAliasSymbol.prototype.assignedContainer = function () { + this._resolveDeclaredSymbol(); + return this._assignedContainer; + }; + + PullTypeAliasSymbol.prototype.isAlias = function () { + return true; + }; + PullTypeAliasSymbol.prototype.isContainer = function () { + return true; + }; + + PullTypeAliasSymbol.prototype.setAssignedValueSymbol = function (symbol) { + this._assignedValue = symbol; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedValueSymbol = function () { + if (this._assignedValue) { + return this._assignedValue; + } + + if (this.retrievingExportAssignment) { + return null; + } + + if (this._assignedContainer) { + if (this._assignedContainer.hasExportAssignment()) { + this.retrievingExportAssignment = true; + var sym = this._assignedContainer.getExportAssignedValueSymbol(); + this.retrievingExportAssignment = false; + return sym; + } + + return this._assignedContainer.getInstanceSymbol(); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.setAssignedTypeSymbol = function (type) { + this._assignedType = type; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedTypeSymbol = function () { + if (this.retrievingExportAssignment) { + return null; + } + + if (this._assignedType) { + if (this._assignedType.isAlias()) { + this.retrievingExportAssignment = true; + var sym = this._assignedType.getExportAssignedTypeSymbol(); + this.retrievingExportAssignment = false; + } else if (this._assignedType !== this._assignedContainer) { + return this._assignedType; + } + } + + if (this._assignedContainer) { + this.retrievingExportAssignment = true; + var sym = this._assignedContainer.getExportAssignedTypeSymbol(); + this.retrievingExportAssignment = false; + if (sym) { + return sym; + } + } + + return this._assignedContainer; + }; + + PullTypeAliasSymbol.prototype.setAssignedContainerSymbol = function (container) { + this._assignedContainer = container; + }; + + PullTypeAliasSymbol.prototype.getExportAssignedContainerSymbol = function () { + if (this.retrievingExportAssignment) { + return null; + } + + if (this._assignedContainer) { + this.retrievingExportAssignment = true; + var sym = this._assignedContainer.getExportAssignedContainerSymbol(); + this.retrievingExportAssignment = false; + if (sym) { + return sym; + } + } + + return this._assignedContainer; + }; + + PullTypeAliasSymbol.prototype.getMembers = function () { + if (this._assignedType) { + return this._assignedType.getMembers(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.getCallSignatures = function () { + if (this._assignedType) { + return this._assignedType.getCallSignatures(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.getConstructSignatures = function () { + if (this._assignedType) { + return this._assignedType.getConstructSignatures(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.getIndexSignatures = function () { + if (this._assignedType) { + return this._assignedType.getIndexSignatures(); + } + + return TypeScript.sentinelEmptyArray; + }; + + PullTypeAliasSymbol.prototype.findMember = function (name) { + if (this._assignedType) { + return this._assignedType.findMember(name, true); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.findNestedType = function (name) { + if (this._assignedType) { + return this._assignedType.findNestedType(name); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.findNestedContainer = function (name) { + if (this._assignedType) { + return this._assignedType.findNestedContainer(name); + } + + return null; + }; + + PullTypeAliasSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisibility) { + if (this._assignedType) { + return this._assignedType.getAllMembers(searchDeclKind, memberVisibility); + } + + return TypeScript.sentinelEmptyArray; + }; + return PullTypeAliasSymbol; + })(PullTypeSymbol); + TypeScript.PullTypeAliasSymbol = PullTypeAliasSymbol; + + var PullTypeParameterSymbol = (function (_super) { + __extends(PullTypeParameterSymbol, _super); + function PullTypeParameterSymbol(name) { + _super.call(this, name, 8192 /* TypeParameter */); + this._constraint = null; + } + PullTypeParameterSymbol.prototype.isTypeParameter = function () { + return true; + }; + + PullTypeParameterSymbol.prototype.setConstraint = function (constraintType) { + this._constraint = constraintType; + }; + + PullTypeParameterSymbol.prototype.getConstraint = function () { + return this._constraint; + }; + + PullTypeParameterSymbol.prototype.getBaseConstraint = function (semanticInfoChain) { + var preBaseConstraint = this.getConstraintRecursively({}); + TypeScript.Debug.assert(preBaseConstraint === null || !preBaseConstraint.isTypeParameter()); + return preBaseConstraint || semanticInfoChain.emptyTypeSymbol; + }; + + PullTypeParameterSymbol.prototype.getConstraintRecursively = function (visitedTypeParameters) { + var constraint = this.getConstraint(); + + if (constraint) { + if (constraint.isTypeParameter()) { + var constraintAsTypeParameter = constraint; + if (!visitedTypeParameters[constraintAsTypeParameter.pullSymbolID]) { + visitedTypeParameters[constraintAsTypeParameter.pullSymbolID] = constraintAsTypeParameter; + return constraintAsTypeParameter.getConstraintRecursively(visitedTypeParameters); + } + } else { + return constraint; + } + } + + return null; + }; + + PullTypeParameterSymbol.prototype.getDefaultConstraint = function (semanticInfoChain) { + return this._constraint || semanticInfoChain.emptyTypeSymbol; + }; + + PullTypeParameterSymbol.prototype.getCallSignatures = function () { + if (this._constraint) { + return this._constraint.getCallSignatures(); + } + + return _super.prototype.getCallSignatures.call(this); + }; + + PullTypeParameterSymbol.prototype.getConstructSignatures = function () { + if (this._constraint) { + return this._constraint.getConstructSignatures(); + } + + return _super.prototype.getConstructSignatures.call(this); + }; + + PullTypeParameterSymbol.prototype.getIndexSignatures = function () { + if (this._constraint) { + return this._constraint.getIndexSignatures(); + } + + return _super.prototype.getIndexSignatures.call(this); + }; + + PullTypeParameterSymbol.prototype.isGeneric = function () { + return true; + }; + + PullTypeParameterSymbol.prototype.fullName = function (scopeSymbol) { + var name = this.getDisplayName(scopeSymbol); + var container = this.getContainer(); + if (container) { + var containerName = container.fullName(scopeSymbol); + name = name + " in " + containerName; + } + + return name; + }; + + PullTypeParameterSymbol.prototype.getName = function (scopeSymbol, useConstraintInName) { + var name = _super.prototype.getName.call(this, scopeSymbol); + + if (this.isPrinting) { + return name; + } + + this.isPrinting = true; + + if (useConstraintInName && this._constraint) { + name += " extends " + this._constraint.toString(scopeSymbol); + } + + this.isPrinting = false; + + return name; + }; + + PullTypeParameterSymbol.prototype.getDisplayName = function (scopeSymbol, useConstraintInName, skipInternalAliasName) { + var name = _super.prototype.getDisplayName.call(this, scopeSymbol, useConstraintInName, skipInternalAliasName); + + if (this.isPrinting) { + return name; + } + + this.isPrinting = true; + + if (useConstraintInName && this._constraint) { + name += " extends " + this._constraint.toString(scopeSymbol); + } + + this.isPrinting = false; + + return name; + }; + + PullTypeParameterSymbol.prototype.isExternallyVisible = function (inIsExternallyVisibleSymbols) { + return true; + }; + return PullTypeParameterSymbol; + })(PullTypeSymbol); + TypeScript.PullTypeParameterSymbol = PullTypeParameterSymbol; + + var PullAccessorSymbol = (function (_super) { + __extends(PullAccessorSymbol, _super); + function PullAccessorSymbol(name) { + _super.call(this, name, 4096 /* Property */); + this._getterSymbol = null; + this._setterSymbol = null; + } + PullAccessorSymbol.prototype.isAccessor = function () { + return true; + }; + + PullAccessorSymbol.prototype.setSetter = function (setter) { + if (!setter) { + return; + } + + this._setterSymbol = setter; + }; + + PullAccessorSymbol.prototype.getSetter = function () { + return this._setterSymbol; + }; + + PullAccessorSymbol.prototype.setGetter = function (getter) { + if (!getter) { + return; + } + + this._getterSymbol = getter; + }; + + PullAccessorSymbol.prototype.getGetter = function () { + return this._getterSymbol; + }; + return PullAccessorSymbol; + })(PullSymbol); + TypeScript.PullAccessorSymbol = PullAccessorSymbol; + + function getIDForTypeSubstitutions(instantiatingTypeOrSignature, typeArgumentMap) { + var substitution = ""; + var members = null; + + var allowedToReferenceTypeParameters = instantiatingTypeOrSignature.getAllowedToReferenceTypeParameters(); + for (var i = 0; i < allowedToReferenceTypeParameters.length; i++) { + var typeParameter = allowedToReferenceTypeParameters[i]; + var typeParameterID = typeParameter.pullSymbolID; + var typeArg = typeArgumentMap[typeParameterID]; + if (!typeArg) { + typeArg = typeParameter; + } + substitution += typeParameterID + ":" + getIDForTypeSubstitutionsOfType(typeArg); + } + + return substitution; + } + TypeScript.getIDForTypeSubstitutions = getIDForTypeSubstitutions; + + function getIDForTypeSubstitutionsOfType(type) { + var structure; + if (type.isError()) { + structure = "E" + getIDForTypeSubstitutionsOfType(type._anyType); + } else if (!type.isNamedTypeSymbol()) { + structure = getIDForTypeSubstitutionsFromObjectType(type); + } + + if (!structure) { + structure = type.pullSymbolID + "#"; + } + + return structure; + } + + function getIDForTypeSubstitutionsFromObjectType(type) { + if (type.isResolved) { + var getIDForTypeSubStitutionWalker = new GetIDForTypeSubStitutionWalker(); + TypeScript.PullHelpers.walkPullTypeSymbolStructure(type, getIDForTypeSubStitutionWalker); + } + + return null; + } + + var GetIDForTypeSubStitutionWalker = (function () { + function GetIDForTypeSubStitutionWalker() { + this.structure = ""; + } + GetIDForTypeSubStitutionWalker.prototype.memberSymbolWalk = function (memberSymbol) { + this.structure += memberSymbol.name + "@" + getIDForTypeSubstitutionsOfType(memberSymbol.type); + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.callSignatureWalk = function (signatureSymbol) { + this.structure += "("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.constructSignatureWalk = function (signatureSymbol) { + this.structure += "new("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.indexSignatureWalk = function (signatureSymbol) { + this.structure += "[]("; + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.signatureParameterWalk = function (parameterSymbol) { + this.structure += parameterSymbol.name + "@" + getIDForTypeSubstitutionsOfType(parameterSymbol.type); + return true; + }; + GetIDForTypeSubStitutionWalker.prototype.signatureReturnTypeWalk = function (returnType) { + this.structure += ")" + getIDForTypeSubstitutionsOfType(returnType); + return true; + }; + return GetIDForTypeSubStitutionWalker; + })(); + + (function (GetAllMembersVisiblity) { + GetAllMembersVisiblity[GetAllMembersVisiblity["all"] = 0] = "all"; + + GetAllMembersVisiblity[GetAllMembersVisiblity["internallyVisible"] = 1] = "internallyVisible"; + + GetAllMembersVisiblity[GetAllMembersVisiblity["externallyVisible"] = 2] = "externallyVisible"; + })(TypeScript.GetAllMembersVisiblity || (TypeScript.GetAllMembersVisiblity = {})); + var GetAllMembersVisiblity = TypeScript.GetAllMembersVisiblity; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var EnclosingTypeWalkerState = (function () { + function EnclosingTypeWalkerState() { + } + EnclosingTypeWalkerState.getDefaultEnclosingTypeWalkerState = function () { + var defaultEnclosingTypeWalkerState = new EnclosingTypeWalkerState(); + defaultEnclosingTypeWalkerState._hasSetEnclosingType = false; + return defaultEnclosingTypeWalkerState; + }; + + EnclosingTypeWalkerState.getNonGenericEnclosingTypeWalkerState = function () { + var defaultEnclosingTypeWalkerState = new EnclosingTypeWalkerState(); + defaultEnclosingTypeWalkerState._hasSetEnclosingType = true; + return defaultEnclosingTypeWalkerState; + }; + + EnclosingTypeWalkerState.getGenericEnclosingTypeWalkerState = function (genericEnclosingType) { + var defaultEnclosingTypeWalkerState = new EnclosingTypeWalkerState(); + defaultEnclosingTypeWalkerState._hasSetEnclosingType = true; + defaultEnclosingTypeWalkerState._currentSymbols = [TypeScript.PullHelpers.getRootType(genericEnclosingType)]; + return defaultEnclosingTypeWalkerState; + }; + return EnclosingTypeWalkerState; + })(); + TypeScript.EnclosingTypeWalkerState = EnclosingTypeWalkerState; + + var PullTypeEnclosingTypeWalker = (function () { + function PullTypeEnclosingTypeWalker() { + this.setDefaultTypeWalkerState(); + } + PullTypeEnclosingTypeWalker.prototype.setDefaultTypeWalkerState = function () { + this.enclosingTypeWalkerState = PullTypeEnclosingTypeWalker._defaultEnclosingTypeWalkerState; + }; + + PullTypeEnclosingTypeWalker.prototype.setNonGenericEnclosingTypeWalkerState = function () { + this.enclosingTypeWalkerState = PullTypeEnclosingTypeWalker._nonGenericEnclosingTypeWalkerState; + }; + + PullTypeEnclosingTypeWalker.prototype.canSymbolOrDeclBeUsedAsEnclosingTypeHelper = function (name, kind) { + return name && (kind === 8 /* Class */ || kind === 16 /* Interface */); + }; + + PullTypeEnclosingTypeWalker.prototype.canDeclBeUsedAsEnclosingType = function (decl) { + return this.canSymbolOrDeclBeUsedAsEnclosingTypeHelper(decl.name, decl.kind); + }; + + PullTypeEnclosingTypeWalker.prototype.canSymbolBeUsedAsEnclosingType = function (symbol) { + return this.canSymbolOrDeclBeUsedAsEnclosingTypeHelper(symbol.name, symbol.kind); + }; + + PullTypeEnclosingTypeWalker.prototype.getEnclosingType = function () { + var currentSymbols = this.enclosingTypeWalkerState._currentSymbols; + if (currentSymbols) { + TypeScript.Debug.assert(currentSymbols.length > 0); + return currentSymbols[0]; + } + + return null; + }; + + PullTypeEnclosingTypeWalker.prototype._canWalkStructure = function () { + var enclosingType = this.getEnclosingType(); + TypeScript.Debug.assert(!enclosingType || enclosingType.isGeneric()); + return !!enclosingType; + }; + + PullTypeEnclosingTypeWalker.prototype._getCurrentSymbol = function () { + var currentSymbols = this.enclosingTypeWalkerState._currentSymbols; + if (currentSymbols && currentSymbols.length) { + return currentSymbols[currentSymbols.length - 1]; + } + + return null; + }; + + PullTypeEnclosingTypeWalker.prototype.getGenerativeClassification = function () { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + if (!currentType) { + return 0 /* Unknown */; + } + + var variableNeededToFixNodeJitterBug = this.getEnclosingType(); + + return currentType.getGenerativeTypeClassification(variableNeededToFixNodeJitterBug); + } + + return 2 /* Closed */; + }; + + PullTypeEnclosingTypeWalker.prototype._pushSymbol = function (symbol) { + return this.enclosingTypeWalkerState._currentSymbols.push(symbol); + }; + + PullTypeEnclosingTypeWalker.prototype._popSymbol = function () { + return this.enclosingTypeWalkerState._currentSymbols.pop(); + }; + + PullTypeEnclosingTypeWalker.prototype.setSymbolAsEnclosingType = function (type) { + if (type.isGeneric()) { + this.enclosingTypeWalkerState = EnclosingTypeWalkerState.getGenericEnclosingTypeWalkerState(type); + } else { + this.setNonGenericEnclosingTypeWalkerState(); + } + }; + + PullTypeEnclosingTypeWalker.prototype._setEnclosingTypeOfParentDecl = function (decl, setSignature) { + var parentDecl = decl.getParentDecl(); + + if (parentDecl && !(parentDecl.kind & (164 /* SomeContainer */ | 1 /* Script */))) { + if (this.canDeclBeUsedAsEnclosingType(parentDecl)) { + this.setSymbolAsEnclosingType(parentDecl.getSymbol()); + } else { + this._setEnclosingTypeOfParentDecl(parentDecl, true); + } + + if (this._canWalkStructure()) { + var symbol = decl.getSymbol(); + if (symbol) { + if (!symbol.isType() && !symbol.isSignature()) { + symbol = symbol.type; + } + + this._pushSymbol(symbol); + } + + if (setSignature) { + var signature = decl.getSignatureSymbol(); + if (signature) { + this._pushSymbol(signature); + } + } + } + } + }; + + PullTypeEnclosingTypeWalker.prototype.setEnclosingTypeForSymbol = function (symbol) { + var currentEnclosingTypeWalkerState = this.enclosingTypeWalkerState; + if (this.canSymbolBeUsedAsEnclosingType(symbol)) { + this.setSymbolAsEnclosingType(symbol); + } else { + this.setDefaultTypeWalkerState(); + + var decls = symbol.getDeclarations(); + for (var i = 0; i < decls.length; i++) { + var decl = decls[i]; + this._setEnclosingTypeOfParentDecl(decl, symbol.isSignature()); + + if (this.enclosingTypeWalkerState._hasSetEnclosingType) { + break; + } + } + + if (!this.enclosingTypeWalkerState._hasSetEnclosingType) { + this.setNonGenericEnclosingTypeWalkerState(); + } + } + return currentEnclosingTypeWalkerState; + }; + + PullTypeEnclosingTypeWalker.prototype.startWalkingType = function (symbol) { + var currentState = this.enclosingTypeWalkerState; + + var setEnclosingTypeForSymbol = !this.enclosingTypeWalkerState._hasSetEnclosingType || this.canSymbolBeUsedAsEnclosingType(symbol); + if (setEnclosingTypeForSymbol) { + this.setEnclosingTypeForSymbol(symbol); + } + return currentState; + }; + + PullTypeEnclosingTypeWalker.prototype.endWalkingType = function (stateWhenStartedWalkingTypes) { + this.enclosingTypeWalkerState = stateWhenStartedWalkingTypes; + }; + + PullTypeEnclosingTypeWalker.prototype.walkMemberType = function (memberName, resolver) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + var memberSymbol = currentType ? resolver._getNamedPropertySymbolOfAugmentedType(memberName, currentType) : null; + this._pushSymbol(memberSymbol ? memberSymbol.type : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkMemberType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkSignature = function (kind, index) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + var signatures; + if (currentType) { + if (kind == 1048576 /* CallSignature */) { + signatures = currentType.getCallSignatures(); + } else if (kind == 2097152 /* ConstructSignature */) { + signatures = currentType.getConstructSignatures(); + } else { + signatures = currentType.getIndexSignatures(); + } + } + + this._pushSymbol(signatures ? signatures[index] : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkSignature = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkTypeArgument = function (index) { + if (this._canWalkStructure()) { + var typeArgument = null; + var currentType = this._getCurrentSymbol(); + if (currentType) { + var typeArguments = currentType.getTypeArguments(); + typeArgument = typeArguments ? typeArguments[index] : null; + } + this._pushSymbol(typeArgument); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkTypeArgument = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkTypeParameterConstraint = function (index) { + if (this._canWalkStructure()) { + var typeParameters; + var currentSymbol = this._getCurrentSymbol(); + if (currentSymbol) { + if (currentSymbol.isSignature()) { + typeParameters = currentSymbol.getTypeParameters(); + } else { + TypeScript.Debug.assert(currentSymbol.isType()); + typeParameters = currentSymbol.getTypeParameters(); + } + } + this._pushSymbol(typeParameters ? typeParameters[index].getConstraint() : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkTypeParameterConstraint = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkReturnType = function () { + if (this._canWalkStructure()) { + var currentSignature = this._getCurrentSymbol(); + this._pushSymbol(currentSignature ? currentSignature.returnType : null); + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkReturnType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.walkParameterType = function (iParam) { + if (this._canWalkStructure()) { + var currentSignature = this._getCurrentSymbol(); + this._pushSymbol(currentSignature ? currentSignature.getParameterTypeAtIndex(iParam) : null); + } + }; + PullTypeEnclosingTypeWalker.prototype.postWalkParameterType = function () { + if (this._canWalkStructure()) { + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.getBothKindOfIndexSignatures = function (resolver, context, includeAugmentedType) { + if (this._canWalkStructure()) { + var currentType = this._getCurrentSymbol(); + if (currentType) { + return resolver._getBothKindsOfIndexSignatures(currentType, context, includeAugmentedType); + } + } + return null; + }; + + PullTypeEnclosingTypeWalker.prototype.walkIndexSignatureReturnType = function (indexSigInfo, useStringIndexSignature, onlySignature) { + if (this._canWalkStructure()) { + var indexSig = indexSigInfo ? (useStringIndexSignature ? indexSigInfo.stringSignature : indexSigInfo.numericSignature) : null; + this._pushSymbol(indexSig); + if (!onlySignature) { + this._pushSymbol(indexSig ? indexSig.returnType : null); + } + } + }; + + PullTypeEnclosingTypeWalker.prototype.postWalkIndexSignatureReturnType = function (onlySignature) { + if (this._canWalkStructure()) { + if (!onlySignature) { + this._popSymbol(); + } + this._popSymbol(); + } + }; + + PullTypeEnclosingTypeWalker.prototype.resetEnclosingTypeWalkerState = function () { + var currentState = this.enclosingTypeWalkerState; + this.setDefaultTypeWalkerState(); + return currentState; + }; + + PullTypeEnclosingTypeWalker.prototype.setEnclosingTypeWalkerState = function (enclosingTypeWalkerState) { + if (enclosingTypeWalkerState) { + this.enclosingTypeWalkerState = enclosingTypeWalkerState; + } else { + this.setDefaultTypeWalkerState(); + } + }; + PullTypeEnclosingTypeWalker._defaultEnclosingTypeWalkerState = EnclosingTypeWalkerState.getDefaultEnclosingTypeWalkerState(); + + PullTypeEnclosingTypeWalker._nonGenericEnclosingTypeWalkerState = EnclosingTypeWalkerState.getNonGenericEnclosingTypeWalkerState(); + return PullTypeEnclosingTypeWalker; + })(); + TypeScript.PullTypeEnclosingTypeWalker = PullTypeEnclosingTypeWalker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var CandidateInferenceInfo = (function () { + function CandidateInferenceInfo() { + this.typeParameter = null; + this._inferredTypeAfterFixing = null; + this.inferenceCandidates = []; + } + CandidateInferenceInfo.prototype.addCandidate = function (candidate) { + if (!this._inferredTypeAfterFixing) { + this.inferenceCandidates[this.inferenceCandidates.length] = candidate; + } + }; + + CandidateInferenceInfo.prototype.isFixed = function () { + return !!this._inferredTypeAfterFixing; + }; + + CandidateInferenceInfo.prototype.fixTypeParameter = function (resolver, context) { + var _this = this; + if (!this._inferredTypeAfterFixing) { + var collection = { + getLength: function () { + return _this.inferenceCandidates.length; + }, + getTypeAtIndex: function (index) { + return _this.inferenceCandidates[index].type; + } + }; + + var bestCommonType = resolver.findBestCommonType(collection, context, new TypeScript.TypeComparisonInfo()); + this._inferredTypeAfterFixing = bestCommonType.widenedType(resolver, null, context); + } + }; + return CandidateInferenceInfo; + })(); + TypeScript.CandidateInferenceInfo = CandidateInferenceInfo; + + var TypeArgumentInferenceContext = (function () { + function TypeArgumentInferenceContext(resolver, context, signatureBeingInferred) { + this.resolver = resolver; + this.context = context; + this.signatureBeingInferred = signatureBeingInferred; + this.inferenceCache = TypeScript.BitMatrix.getBitMatrix(false); + this.candidateCache = []; + var typeParameters = signatureBeingInferred.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + this.addInferenceRoot(typeParameters[i]); + } + } + TypeArgumentInferenceContext.prototype.alreadyRelatingTypes = function (objectType, parameterType) { + if (this.inferenceCache.valueAt(objectType.pullSymbolID, parameterType.pullSymbolID)) { + return true; + } else { + this.inferenceCache.setValueAt(objectType.pullSymbolID, parameterType.pullSymbolID, true); + return false; + } + }; + + TypeArgumentInferenceContext.prototype.resetRelationshipCache = function () { + this.inferenceCache.release(); + this.inferenceCache = TypeScript.BitMatrix.getBitMatrix(false); + }; + + TypeArgumentInferenceContext.prototype.addInferenceRoot = function (param) { + var info = this.candidateCache[param.pullSymbolID]; + + if (!info) { + info = new CandidateInferenceInfo(); + info.typeParameter = param; + this.candidateCache[param.pullSymbolID] = info; + } + }; + + TypeArgumentInferenceContext.prototype.getInferenceInfo = function (param) { + return this.candidateCache[param.pullSymbolID]; + }; + + TypeArgumentInferenceContext.prototype.addCandidateForInference = function (param, candidate) { + var info = this.getInferenceInfo(param); + + if (info && candidate && info.inferenceCandidates.indexOf(candidate) < 0) { + info.addCandidate(candidate); + } + }; + + TypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + throw TypeScript.Errors.abstract(); + }; + + TypeArgumentInferenceContext.prototype.fixTypeParameter = function (typeParameter) { + var candidateInfo = this.candidateCache[typeParameter.pullSymbolID]; + if (candidateInfo) { + candidateInfo.fixTypeParameter(this.resolver, this.context); + } + }; + + TypeArgumentInferenceContext.prototype._finalizeInferredTypeArguments = function () { + var results = []; + var typeParameters = this.signatureBeingInferred.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + var info = this.candidateCache[typeParameters[i].pullSymbolID]; + + info.fixTypeParameter(this.resolver, this.context); + + for (var i = 0; i < results.length; i++) { + if (results[i].type === info.typeParameter) { + results[i].type = info._inferredTypeAfterFixing; + } + } + + results.push(info._inferredTypeAfterFixing); + } + + return results; + }; + + TypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + throw TypeScript.Errors.abstract(); + }; + return TypeArgumentInferenceContext; + })(); + TypeScript.TypeArgumentInferenceContext = TypeArgumentInferenceContext; + + var InvocationTypeArgumentInferenceContext = (function (_super) { + __extends(InvocationTypeArgumentInferenceContext, _super); + function InvocationTypeArgumentInferenceContext(resolver, context, signatureBeingInferred, argumentASTs) { + _super.call(this, resolver, context, signatureBeingInferred); + this.argumentASTs = argumentASTs; + } + InvocationTypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + return true; + }; + + InvocationTypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + var _this = this; + this.signatureBeingInferred.forAllParameterTypes(this.argumentASTs.nonSeparatorCount(), function (parameterType, argumentIndex) { + var argumentAST = _this.argumentASTs.nonSeparatorAt(argumentIndex); + + _this.context.pushInferentialType(parameterType, _this); + var argumentType = _this.resolver.resolveAST(argumentAST, true, _this.context).type; + _this.resolver.relateTypeToTypeParametersWithNewEnclosingTypes(argumentType, parameterType, _this, _this.context); + _this.context.popAnyContextualType(); + + return true; + }); + + return this._finalizeInferredTypeArguments(); + }; + return InvocationTypeArgumentInferenceContext; + })(TypeArgumentInferenceContext); + TypeScript.InvocationTypeArgumentInferenceContext = InvocationTypeArgumentInferenceContext; + + var ContextualSignatureInstantiationTypeArgumentInferenceContext = (function (_super) { + __extends(ContextualSignatureInstantiationTypeArgumentInferenceContext, _super); + function ContextualSignatureInstantiationTypeArgumentInferenceContext(resolver, context, signatureBeingInferred, contextualSignature, shouldFixContextualSignatureParameterTypes) { + _super.call(this, resolver, context, signatureBeingInferred); + this.contextualSignature = contextualSignature; + this.shouldFixContextualSignatureParameterTypes = shouldFixContextualSignatureParameterTypes; + } + ContextualSignatureInstantiationTypeArgumentInferenceContext.prototype.isInvocationInferenceContext = function () { + return false; + }; + + ContextualSignatureInstantiationTypeArgumentInferenceContext.prototype.inferTypeArguments = function () { + var _this = this; + var relateTypesCallback = function (parameterTypeBeingInferred, contextualParameterType) { + if (_this.shouldFixContextualSignatureParameterTypes) { + contextualParameterType = _this.context.fixAllTypeParametersReferencedByType(contextualParameterType, _this.resolver, _this); + } + _this.resolver.relateTypeToTypeParametersWithNewEnclosingTypes(contextualParameterType, parameterTypeBeingInferred, _this, _this.context); + + return true; + }; + + this.signatureBeingInferred.forAllCorrespondingParameterTypesInThisAndOtherSignature(this.contextualSignature, relateTypesCallback); + + return this._finalizeInferredTypeArguments(); + }; + return ContextualSignatureInstantiationTypeArgumentInferenceContext; + })(TypeArgumentInferenceContext); + TypeScript.ContextualSignatureInstantiationTypeArgumentInferenceContext = ContextualSignatureInstantiationTypeArgumentInferenceContext; + + var PullContextualTypeContext = (function () { + function PullContextualTypeContext(contextualType, provisional, isInferentiallyTyping, typeArgumentInferenceContext) { + this.contextualType = contextualType; + this.provisional = provisional; + this.isInferentiallyTyping = isInferentiallyTyping; + this.typeArgumentInferenceContext = typeArgumentInferenceContext; + this.provisionallyTypedSymbols = []; + this.hasProvisionalErrors = false; + this.astSymbolMap = []; + } + PullContextualTypeContext.prototype.recordProvisionallyTypedSymbol = function (symbol) { + this.provisionallyTypedSymbols[this.provisionallyTypedSymbols.length] = symbol; + }; + + PullContextualTypeContext.prototype.invalidateProvisionallyTypedSymbols = function () { + for (var i = 0; i < this.provisionallyTypedSymbols.length; i++) { + this.provisionallyTypedSymbols[i].setUnresolved(); + } + }; + + PullContextualTypeContext.prototype.setSymbolForAST = function (ast, symbol) { + this.astSymbolMap[ast.syntaxID()] = symbol; + }; + + PullContextualTypeContext.prototype.getSymbolForAST = function (ast) { + return this.astSymbolMap[ast.syntaxID()]; + }; + return PullContextualTypeContext; + })(); + TypeScript.PullContextualTypeContext = PullContextualTypeContext; + + var PullTypeResolutionContext = (function () { + function PullTypeResolutionContext(resolver, inTypeCheck, fileName) { + if (typeof inTypeCheck === "undefined") { inTypeCheck = false; } + if (typeof fileName === "undefined") { fileName = null; } + this.resolver = resolver; + this.inTypeCheck = inTypeCheck; + this.fileName = fileName; + this.contextStack = []; + this.typeCheckedNodes = null; + this.enclosingTypeWalker1 = null; + this.enclosingTypeWalker2 = null; + this.inBaseTypeResolution = false; + if (inTypeCheck) { + TypeScript.Debug.assert(fileName, "A file name must be provided if you are typechecking"); + this.typeCheckedNodes = TypeScript.BitVector.getBitVector(false); + } + } + PullTypeResolutionContext.prototype.setTypeChecked = function (ast) { + if (!this.inProvisionalResolution()) { + this.typeCheckedNodes.setValueAt(ast.syntaxID(), true); + } + }; + + PullTypeResolutionContext.prototype.canTypeCheckAST = function (ast) { + return this.typeCheck() && !this.typeCheckedNodes.valueAt(ast.syntaxID()) && this.fileName === ast.fileName(); + }; + + PullTypeResolutionContext.prototype._pushAnyContextualType = function (type, provisional, isInferentiallyTyping, argContext) { + this.contextStack.push(new PullContextualTypeContext(type, provisional, isInferentiallyTyping, argContext)); + }; + + PullTypeResolutionContext.prototype.pushNewContextualType = function (type) { + this._pushAnyContextualType(type, this.inProvisionalResolution(), false, null); + }; + + PullTypeResolutionContext.prototype.propagateContextualType = function (type) { + this._pushAnyContextualType(type, this.inProvisionalResolution(), this.isInferentiallyTyping(), this.getCurrentTypeArgumentInferenceContext()); + }; + + PullTypeResolutionContext.prototype.pushInferentialType = function (type, typeArgumentInferenceContext) { + this._pushAnyContextualType(type, true, true, typeArgumentInferenceContext); + }; + + PullTypeResolutionContext.prototype.pushProvisionalType = function (type) { + this._pushAnyContextualType(type, true, false, null); + }; + + PullTypeResolutionContext.prototype.popAnyContextualType = function () { + var tc = this.contextStack.pop(); + + tc.invalidateProvisionallyTypedSymbols(); + + if (tc.hasProvisionalErrors && this.inProvisionalResolution()) { + this.contextStack[this.contextStack.length - 1].hasProvisionalErrors = true; + } + + return tc; + }; + + PullTypeResolutionContext.prototype.hasProvisionalErrors = function () { + return this.contextStack.length ? this.contextStack[this.contextStack.length - 1].hasProvisionalErrors : false; + }; + + PullTypeResolutionContext.prototype.getContextualType = function () { + var context = !this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]; + + if (context) { + var type = context.contextualType; + + if (!type) { + return null; + } + + return type; + } + + return null; + }; + + PullTypeResolutionContext.prototype.fixAllTypeParametersReferencedByType = function (type, resolver, argContext) { + var argContext = this.getCurrentTypeArgumentInferenceContext(); + if (type.wrapsSomeTypeParameter(argContext.candidateCache)) { + var typeParameterArgumentMap = []; + + for (var n in argContext.candidateCache) { + var typeParameter = argContext.candidateCache[n] && argContext.candidateCache[n].typeParameter; + if (typeParameter) { + var dummyMap = []; + dummyMap[typeParameter.pullSymbolID] = typeParameter; + if (type.wrapsSomeTypeParameter(dummyMap)) { + argContext.fixTypeParameter(typeParameter); + TypeScript.Debug.assert(argContext.candidateCache[n]._inferredTypeAfterFixing); + typeParameterArgumentMap[typeParameter.pullSymbolID] = argContext.candidateCache[n]._inferredTypeAfterFixing; + } + } + } + + return resolver.instantiateType(type, typeParameterArgumentMap); + } + + return type; + }; + + PullTypeResolutionContext.prototype.getCurrentTypeArgumentInferenceContext = function () { + return this.contextStack.length ? this.contextStack[this.contextStack.length - 1].typeArgumentInferenceContext : null; + }; + + PullTypeResolutionContext.prototype.isInferentiallyTyping = function () { + return this.contextStack.length > 0 && this.contextStack[this.contextStack.length - 1].isInferentiallyTyping; + }; + + PullTypeResolutionContext.prototype.inProvisionalResolution = function () { + return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); + }; + + PullTypeResolutionContext.prototype.isInBaseTypeResolution = function () { + return this.inBaseTypeResolution; + }; + + PullTypeResolutionContext.prototype.startBaseTypeResolution = function () { + var wasInBaseTypeResoltion = this.inBaseTypeResolution; + this.inBaseTypeResolution = true; + return wasInBaseTypeResoltion; + }; + + PullTypeResolutionContext.prototype.doneBaseTypeResolution = function (wasInBaseTypeResolution) { + this.inBaseTypeResolution = wasInBaseTypeResolution; + }; + + PullTypeResolutionContext.prototype.setTypeInContext = function (symbol, type) { + if (symbol.type && symbol.type.isError() && !type.isError()) { + return; + } + symbol.type = type; + + if (this.contextStack.length && this.inProvisionalResolution()) { + this.contextStack[this.contextStack.length - 1].recordProvisionallyTypedSymbol(symbol); + } + }; + + PullTypeResolutionContext.prototype.postDiagnostic = function (diagnostic) { + if (diagnostic) { + if (this.inProvisionalResolution()) { + (this.contextStack[this.contextStack.length - 1]).hasProvisionalErrors = true; + } else if (this.inTypeCheck && this.resolver) { + this.resolver.semanticInfoChain.addDiagnostic(diagnostic); + } + } + }; + + PullTypeResolutionContext.prototype.typeCheck = function () { + return this.inTypeCheck && !this.inProvisionalResolution(); + }; + + PullTypeResolutionContext.prototype.setSymbolForAST = function (ast, symbol) { + this.contextStack[this.contextStack.length - 1].setSymbolForAST(ast, symbol); + }; + + PullTypeResolutionContext.prototype.getSymbolForAST = function (ast) { + for (var i = this.contextStack.length - 1; i >= 0; i--) { + var typeContext = this.contextStack[i]; + if (!typeContext.provisional) { + break; + } + + var symbol = typeContext.getSymbolForAST(ast); + if (symbol) { + return symbol; + } + } + + return null; + }; + + PullTypeResolutionContext.prototype.startWalkingTypes = function (symbol1, symbol2) { + if (!this.enclosingTypeWalker1) { + this.enclosingTypeWalker1 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var stateWhenStartedWalkingTypes1 = this.enclosingTypeWalker1.startWalkingType(symbol1); + if (!this.enclosingTypeWalker2) { + this.enclosingTypeWalker2 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var stateWhenStartedWalkingTypes2 = this.enclosingTypeWalker2.startWalkingType(symbol2); + return { + stateWhenStartedWalkingTypes1: stateWhenStartedWalkingTypes1, + stateWhenStartedWalkingTypes2: stateWhenStartedWalkingTypes2 + }; + }; + + PullTypeResolutionContext.prototype.endWalkingTypes = function (statesWhenStartedWalkingTypes) { + this.enclosingTypeWalker1.endWalkingType(statesWhenStartedWalkingTypes.stateWhenStartedWalkingTypes1); + this.enclosingTypeWalker2.endWalkingType(statesWhenStartedWalkingTypes.stateWhenStartedWalkingTypes2); + }; + + PullTypeResolutionContext.prototype.setEnclosingTypeForSymbols = function (symbol1, symbol2) { + if (!this.enclosingTypeWalker1) { + this.enclosingTypeWalker1 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var enclosingTypeWalkerState1 = this.enclosingTypeWalker1.setEnclosingTypeForSymbol(symbol1); + if (!this.enclosingTypeWalker2) { + this.enclosingTypeWalker2 = new TypeScript.PullTypeEnclosingTypeWalker(); + } + var enclosingTypeWalkerState2 = this.enclosingTypeWalker2.setEnclosingTypeForSymbol(symbol2); + return { + enclosingTypeWalkerState1: enclosingTypeWalkerState1, + enclosingTypeWalkerState2: enclosingTypeWalkerState2 + }; + }; + + PullTypeResolutionContext.prototype.walkMemberTypes = function (memberName) { + this.enclosingTypeWalker1.walkMemberType(memberName, this.resolver); + this.enclosingTypeWalker2.walkMemberType(memberName, this.resolver); + }; + + PullTypeResolutionContext.prototype.postWalkMemberTypes = function () { + this.enclosingTypeWalker1.postWalkMemberType(); + this.enclosingTypeWalker2.postWalkMemberType(); + }; + + PullTypeResolutionContext.prototype.walkSignatures = function (kind, index, index2) { + this.enclosingTypeWalker1.walkSignature(kind, index); + this.enclosingTypeWalker2.walkSignature(kind, index2 == undefined ? index : index2); + }; + + PullTypeResolutionContext.prototype.postWalkSignatures = function () { + this.enclosingTypeWalker1.postWalkSignature(); + this.enclosingTypeWalker2.postWalkSignature(); + }; + + PullTypeResolutionContext.prototype.walkTypeParameterConstraints = function (index) { + this.enclosingTypeWalker1.walkTypeParameterConstraint(index); + this.enclosingTypeWalker2.walkTypeParameterConstraint(index); + }; + + PullTypeResolutionContext.prototype.postWalkTypeParameterConstraints = function () { + this.enclosingTypeWalker1.postWalkTypeParameterConstraint(); + this.enclosingTypeWalker2.postWalkTypeParameterConstraint(); + }; + + PullTypeResolutionContext.prototype.walkTypeArgument = function (index) { + this.enclosingTypeWalker1.walkTypeArgument(index); + this.enclosingTypeWalker2.walkTypeArgument(index); + }; + + PullTypeResolutionContext.prototype.postWalkTypeArgument = function () { + this.enclosingTypeWalker1.postWalkTypeArgument(); + this.enclosingTypeWalker2.postWalkTypeArgument(); + }; + + PullTypeResolutionContext.prototype.walkReturnTypes = function () { + this.enclosingTypeWalker1.walkReturnType(); + this.enclosingTypeWalker2.walkReturnType(); + }; + + PullTypeResolutionContext.prototype.postWalkReturnTypes = function () { + this.enclosingTypeWalker1.postWalkReturnType(); + this.enclosingTypeWalker2.postWalkReturnType(); + }; + + PullTypeResolutionContext.prototype.walkParameterTypes = function (iParam) { + this.enclosingTypeWalker1.walkParameterType(iParam); + this.enclosingTypeWalker2.walkParameterType(iParam); + }; + + PullTypeResolutionContext.prototype.postWalkParameterTypes = function () { + this.enclosingTypeWalker1.postWalkParameterType(); + this.enclosingTypeWalker2.postWalkParameterType(); + }; + + PullTypeResolutionContext.prototype.getBothKindOfIndexSignatures = function (includeAugmentedType1, includeAugmentedType2) { + var indexSigs1 = this.enclosingTypeWalker1.getBothKindOfIndexSignatures(this.resolver, this, includeAugmentedType1); + var indexSigs2 = this.enclosingTypeWalker2.getBothKindOfIndexSignatures(this.resolver, this, includeAugmentedType2); + return { indexSigs1: indexSigs1, indexSigs2: indexSigs2 }; + }; + + PullTypeResolutionContext.prototype.walkIndexSignatureReturnTypes = function (indexSigs, useStringIndexSignature1, useStringIndexSignature2, onlySignature) { + this.enclosingTypeWalker1.walkIndexSignatureReturnType(indexSigs.indexSigs1, useStringIndexSignature1, onlySignature); + this.enclosingTypeWalker2.walkIndexSignatureReturnType(indexSigs.indexSigs2, useStringIndexSignature2, onlySignature); + }; + + PullTypeResolutionContext.prototype.postWalkIndexSignatureReturnTypes = function (onlySignature) { + this.enclosingTypeWalker1.postWalkIndexSignatureReturnType(onlySignature); + this.enclosingTypeWalker2.postWalkIndexSignatureReturnType(onlySignature); + }; + + PullTypeResolutionContext.prototype.swapEnclosingTypeWalkers = function () { + var tempEnclosingWalker1 = this.enclosingTypeWalker1; + this.enclosingTypeWalker1 = this.enclosingTypeWalker2; + this.enclosingTypeWalker2 = tempEnclosingWalker1; + }; + + PullTypeResolutionContext.prototype.oneOfClassificationsIsInfinitelyExpanding = function () { + var generativeClassification1 = this.enclosingTypeWalker1.getGenerativeClassification(); + if (generativeClassification1 === 3 /* InfinitelyExpanding */) { + return true; + } + var generativeClassification2 = this.enclosingTypeWalker2.getGenerativeClassification(); + if (generativeClassification2 === 3 /* InfinitelyExpanding */) { + return true; + } + + return false; + }; + + PullTypeResolutionContext.prototype.resetEnclosingTypeWalkerStates = function () { + var enclosingTypeWalkerState1 = this.enclosingTypeWalker1 ? this.enclosingTypeWalker1.resetEnclosingTypeWalkerState() : null; + var enclosingTypeWalkerState2 = this.enclosingTypeWalker2 ? this.enclosingTypeWalker2.resetEnclosingTypeWalkerState() : null; + return { + enclosingTypeWalkerState1: enclosingTypeWalkerState1, + enclosingTypeWalkerState2: enclosingTypeWalkerState2 + }; + }; + + PullTypeResolutionContext.prototype.setEnclosingTypeWalkerStates = function (enclosingTypeWalkerStates) { + TypeScript.Debug.assert(this.enclosingTypeWalker1 || !enclosingTypeWalkerStates.enclosingTypeWalkerState1); + if (this.enclosingTypeWalker1) { + this.enclosingTypeWalker1.setEnclosingTypeWalkerState(enclosingTypeWalkerStates.enclosingTypeWalkerState1); + } + TypeScript.Debug.assert(this.enclosingTypeWalker2 || !enclosingTypeWalkerStates.enclosingTypeWalkerState2); + if (this.enclosingTypeWalker2) { + this.enclosingTypeWalker2.setEnclosingTypeWalkerState(enclosingTypeWalkerStates.enclosingTypeWalkerState2); + } + }; + return PullTypeResolutionContext; + })(); + TypeScript.PullTypeResolutionContext = PullTypeResolutionContext; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var OverloadApplicabilityStatus; + (function (OverloadApplicabilityStatus) { + OverloadApplicabilityStatus[OverloadApplicabilityStatus["NotAssignable"] = 0] = "NotAssignable"; + OverloadApplicabilityStatus[OverloadApplicabilityStatus["AssignableButWithProvisionalErrors"] = 1] = "AssignableButWithProvisionalErrors"; + OverloadApplicabilityStatus[OverloadApplicabilityStatus["AssignableWithNoProvisionalErrors"] = 2] = "AssignableWithNoProvisionalErrors"; + OverloadApplicabilityStatus[OverloadApplicabilityStatus["Subtype"] = 3] = "Subtype"; + })(OverloadApplicabilityStatus || (OverloadApplicabilityStatus = {})); + + var PullAdditionalCallResolutionData = (function () { + function PullAdditionalCallResolutionData() { + this.targetSymbol = null; + this.resolvedSignatures = null; + this.candidateSignature = null; + this.actualParametersContextTypeSymbols = null; + this.diagnosticsFromOverloadResolution = []; + } + return PullAdditionalCallResolutionData; + })(); + TypeScript.PullAdditionalCallResolutionData = PullAdditionalCallResolutionData; + + var PullAdditionalObjectLiteralResolutionData = (function () { + function PullAdditionalObjectLiteralResolutionData() { + this.membersContextTypeSymbols = null; + } + return PullAdditionalObjectLiteralResolutionData; + })(); + TypeScript.PullAdditionalObjectLiteralResolutionData = PullAdditionalObjectLiteralResolutionData; + + var MemberWithBaseOrigin = (function () { + function MemberWithBaseOrigin(memberSymbol, baseOrigin) { + this.memberSymbol = memberSymbol; + this.baseOrigin = baseOrigin; + } + return MemberWithBaseOrigin; + })(); + + var SignatureWithBaseOrigin = (function () { + function SignatureWithBaseOrigin(signature, baseOrigin) { + this.signature = signature; + this.baseOrigin = baseOrigin; + } + return SignatureWithBaseOrigin; + })(); + + var InheritedIndexSignatureInfo = (function () { + function InheritedIndexSignatureInfo() { + } + return InheritedIndexSignatureInfo; + })(); + + var CompilerReservedName; + (function (CompilerReservedName) { + CompilerReservedName[CompilerReservedName["_this"] = 1] = "_this"; + CompilerReservedName[CompilerReservedName["_super"] = 2] = "_super"; + CompilerReservedName[CompilerReservedName["arguments"] = 3] = "arguments"; + CompilerReservedName[CompilerReservedName["_i"] = 4] = "_i"; + CompilerReservedName[CompilerReservedName["require"] = 5] = "require"; + CompilerReservedName[CompilerReservedName["exports"] = 6] = "exports"; + })(CompilerReservedName || (CompilerReservedName = {})); + + function getCompilerReservedName(name) { + var nameText = name.valueText(); + return CompilerReservedName[nameText]; + } + + var PullTypeResolver = (function () { + function PullTypeResolver(compilationSettings, semanticInfoChain) { + this.compilationSettings = compilationSettings; + this.semanticInfoChain = semanticInfoChain; + this._cachedArrayInterfaceType = null; + this._cachedNumberInterfaceType = null; + this._cachedStringInterfaceType = null; + this._cachedBooleanInterfaceType = null; + this._cachedObjectInterfaceType = null; + this._cachedFunctionInterfaceType = null; + this._cachedIArgumentsInterfaceType = null; + this._cachedRegExpInterfaceType = null; + this._cachedAnyTypeArgs = null; + this.typeCheckCallBacks = []; + this.postTypeCheckWorkitems = []; + this._cachedFunctionArgumentsSymbol = null; + this.assignableCache = TypeScript.BitMatrix.getBitMatrix(true); + this.subtypeCache = TypeScript.BitMatrix.getBitMatrix(true); + this.identicalCache = TypeScript.BitMatrix.getBitMatrix(true); + this.inResolvingOtherDeclsWalker = new TypeScript.PullHelpers.OtherPullDeclsWalker(); + } + PullTypeResolver.prototype.cachedArrayInterfaceType = function () { + if (!this._cachedArrayInterfaceType) { + this._cachedArrayInterfaceType = this.getSymbolFromDeclPath("Array", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (!this._cachedArrayInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedArrayInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedArrayInterfaceType; + }; + + PullTypeResolver.prototype.getArrayNamedType = function () { + return this.cachedArrayInterfaceType(); + }; + + PullTypeResolver.prototype.cachedNumberInterfaceType = function () { + if (!this._cachedNumberInterfaceType) { + this._cachedNumberInterfaceType = this.getSymbolFromDeclPath("Number", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedNumberInterfaceType && !this._cachedNumberInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedNumberInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedNumberInterfaceType; + }; + + PullTypeResolver.prototype.cachedStringInterfaceType = function () { + if (!this._cachedStringInterfaceType) { + this._cachedStringInterfaceType = this.getSymbolFromDeclPath("String", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedStringInterfaceType && !this._cachedStringInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedStringInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedStringInterfaceType; + }; + + PullTypeResolver.prototype.cachedBooleanInterfaceType = function () { + if (!this._cachedBooleanInterfaceType) { + this._cachedBooleanInterfaceType = this.getSymbolFromDeclPath("Boolean", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedBooleanInterfaceType && !this._cachedBooleanInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedBooleanInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedBooleanInterfaceType; + }; + + PullTypeResolver.prototype.cachedObjectInterfaceType = function () { + if (!this._cachedObjectInterfaceType) { + this._cachedObjectInterfaceType = this.getSymbolFromDeclPath("Object", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (!this._cachedObjectInterfaceType) { + this._cachedObjectInterfaceType = this.semanticInfoChain.anyTypeSymbol; + } + + if (!this._cachedObjectInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedObjectInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedObjectInterfaceType; + }; + + PullTypeResolver.prototype.cachedFunctionInterfaceType = function () { + if (!this._cachedFunctionInterfaceType) { + this._cachedFunctionInterfaceType = this.getSymbolFromDeclPath("Function", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedFunctionInterfaceType && !this._cachedFunctionInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedFunctionInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedFunctionInterfaceType; + }; + + PullTypeResolver.prototype.cachedIArgumentsInterfaceType = function () { + if (!this._cachedIArgumentsInterfaceType) { + this._cachedIArgumentsInterfaceType = this.getSymbolFromDeclPath("IArguments", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedIArgumentsInterfaceType && !this._cachedIArgumentsInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedIArgumentsInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedIArgumentsInterfaceType; + }; + + PullTypeResolver.prototype.cachedRegExpInterfaceType = function () { + if (!this._cachedRegExpInterfaceType) { + this._cachedRegExpInterfaceType = this.getSymbolFromDeclPath("RegExp", [], 16 /* Interface */) || this.semanticInfoChain.emptyTypeSymbol; + } + + if (this._cachedRegExpInterfaceType && !this._cachedRegExpInterfaceType.isResolved) { + this.resolveDeclaredSymbol(this._cachedRegExpInterfaceType, new TypeScript.PullTypeResolutionContext(this)); + } + + return this._cachedRegExpInterfaceType; + }; + + PullTypeResolver.prototype.cachedFunctionArgumentsSymbol = function () { + if (!this._cachedFunctionArgumentsSymbol) { + this._cachedFunctionArgumentsSymbol = new TypeScript.PullSymbol("arguments", 512 /* Variable */); + this._cachedFunctionArgumentsSymbol.type = this.cachedIArgumentsInterfaceType() || this.semanticInfoChain.anyTypeSymbol; + this._cachedFunctionArgumentsSymbol.setResolved(); + + var functionArgumentsDecl = new TypeScript.PullSynthesizedDecl("arguments", "arguments", 2048 /* Parameter */, 0 /* None */, null, this.semanticInfoChain); + functionArgumentsDecl.setSymbol(this._cachedFunctionArgumentsSymbol); + this._cachedFunctionArgumentsSymbol.addDeclaration(functionArgumentsDecl); + } + + return this._cachedFunctionArgumentsSymbol; + }; + + PullTypeResolver.prototype.getApparentType = function (type) { + if (type.isTypeParameter()) { + var baseConstraint = type.getBaseConstraint(this.semanticInfoChain); + if (baseConstraint === this.semanticInfoChain.anyTypeSymbol) { + return this.semanticInfoChain.emptyTypeSymbol; + } else { + type = baseConstraint; + } + } + if (type.isPrimitive()) { + if (type === this.semanticInfoChain.numberTypeSymbol) { + return this.cachedNumberInterfaceType(); + } + if (type === this.semanticInfoChain.booleanTypeSymbol) { + return this.cachedBooleanInterfaceType(); + } + if (type === this.semanticInfoChain.stringTypeSymbol) { + return this.cachedStringInterfaceType(); + } + return type; + } + if (type.isEnum()) { + return this.cachedNumberInterfaceType(); + } + return type; + }; + + PullTypeResolver.prototype.setTypeChecked = function (ast, context) { + context.setTypeChecked(ast); + }; + + PullTypeResolver.prototype.canTypeCheckAST = function (ast, context) { + return context.canTypeCheckAST(ast); + }; + + PullTypeResolver.prototype.setSymbolForAST = function (ast, symbol, context) { + if (context && context.inProvisionalResolution()) { + context.setSymbolForAST(ast, symbol); + } else { + this.semanticInfoChain.setSymbolForAST(ast, symbol); + } + }; + + PullTypeResolver.prototype.getSymbolForAST = function (ast, context) { + var symbol = this.semanticInfoChain.getSymbolForAST(ast); + + if (!symbol) { + if (context && context.inProvisionalResolution()) { + symbol = context.getSymbolForAST(ast); + } + } + + return symbol; + }; + + PullTypeResolver.prototype.getASTForDecl = function (decl) { + return this.semanticInfoChain.getASTForDecl(decl); + }; + + PullTypeResolver.prototype.getNewErrorTypeSymbol = function (name) { + if (typeof name === "undefined") { name = null; } + return new TypeScript.PullErrorTypeSymbol(this.semanticInfoChain.anyTypeSymbol, name); + }; + + PullTypeResolver.prototype.getEnclosingDecl = function (decl) { + var declPath = decl.getParentPath(); + + if (declPath.length > 1 && declPath[declPath.length - 1] === decl) { + return declPath[declPath.length - 2]; + } else { + return declPath[declPath.length - 1]; + } + }; + + PullTypeResolver.prototype.getExportedMemberSymbol = function (symbol, parent) { + if (!(symbol.kind & (65536 /* Method */ | 4096 /* Property */))) { + var isContainer = (parent.kind & (4 /* Container */ | 32 /* DynamicModule */)) !== 0; + var containerType = !isContainer ? parent.getAssociatedContainerType() : parent; + + if (isContainer && containerType) { + if (symbol.anyDeclHasFlag(1 /* Exported */)) { + return symbol; + } + + return null; + } + } + + return symbol; + }; + + PullTypeResolver.prototype._getNamedPropertySymbolOfAugmentedType = function (symbolName, parent) { + var memberSymbol = this.getNamedPropertySymbol(symbolName, 68147712 /* SomeValue */, parent); + if (memberSymbol) { + return memberSymbol; + } + + if (this.cachedFunctionInterfaceType() && parent.isFunctionType()) { + memberSymbol = this.cachedFunctionInterfaceType().findMember(symbolName, true); + if (memberSymbol) { + return memberSymbol; + } + } + + if (this.cachedObjectInterfaceType()) { + return this.cachedObjectInterfaceType().findMember(symbolName, true); + } + + return null; + }; + + PullTypeResolver.prototype.getNamedPropertySymbol = function (symbolName, declSearchKind, parent) { + var member = null; + + if (declSearchKind & 68147712 /* SomeValue */) { + member = parent.findMember(symbolName, true); + } else if (declSearchKind & 58728795 /* SomeType */) { + member = parent.findNestedType(symbolName); + } else if (declSearchKind & 164 /* SomeContainer */) { + member = parent.findNestedContainer(symbolName); + } + + if (member) { + return this.getExportedMemberSymbol(member, parent); + } + + var containerType = parent.getAssociatedContainerType(); + + if (containerType) { + if (containerType.isClass()) { + return null; + } + + parent = containerType; + + if (declSearchKind & 68147712 /* SomeValue */) { + member = parent.findMember(symbolName, true); + } else if (declSearchKind & 58728795 /* SomeType */) { + member = parent.findNestedType(symbolName); + } else if (declSearchKind & 164 /* SomeContainer */) { + member = parent.findNestedContainer(symbolName); + } + + if (member) { + return this.getExportedMemberSymbol(member, parent); + } + } + + if (parent.kind & 164 /* SomeContainer */) { + var typeDeclarations = parent.getDeclarations(); + var childDecls = null; + + for (var j = 0; j < typeDeclarations.length; j++) { + childDecls = typeDeclarations[j].searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + member = childDecls[0].getSymbol(); + + if (!member) { + member = childDecls[0].getSignatureSymbol(); + } + return this.getExportedMemberSymbol(member, parent); + } + + if ((declSearchKind & 58728795 /* SomeType */) !== 0 || (declSearchKind & 68147712 /* SomeValue */) !== 0) { + childDecls = typeDeclarations[j].searchChildDecls(symbolName, 128 /* TypeAlias */); + if (childDecls.length && childDecls[0].kind === 128 /* TypeAlias */) { + var aliasSymbol = this.getExportedMemberSymbol(childDecls[0].getSymbol(), parent); + if (aliasSymbol) { + if ((declSearchKind & 58728795 /* SomeType */) !== 0) { + var typeSymbol = aliasSymbol.getExportAssignedTypeSymbol(); + if (typeSymbol) { + return typeSymbol; + } + } else { + var valueSymbol = aliasSymbol.getExportAssignedValueSymbol(); + if (valueSymbol) { + aliasSymbol.setIsUsedAsValue(); + return valueSymbol; + } + } + + return aliasSymbol; + } + } + } + } + } + }; + + PullTypeResolver.prototype.getSymbolFromDeclPath = function (symbolName, declPath, declSearchKind) { + var _this = this; + var symbol = null; + + var decl = null; + var childDecls; + var declSymbol = null; + var declMembers; + var pathDeclKind; + var valDecl = null; + var kind; + var instanceSymbol = null; + var instanceType = null; + var childSymbol = null; + + var allowedContainerDeclKind = 4 /* Container */ | 32 /* DynamicModule */; + if (TypeScript.hasFlag(declSearchKind, 67108864 /* EnumMember */)) { + allowedContainerDeclKind |= 64 /* Enum */; + } + + var isAcceptableAlias = function (symbol) { + if (symbol.isAlias()) { + _this.resolveDeclaredSymbol(symbol); + if (TypeScript.hasFlag(declSearchKind, 164 /* SomeContainer */)) { + if (symbol.assignedContainer() || symbol.getExportAssignedContainerSymbol()) { + return true; + } + } else if (TypeScript.hasFlag(declSearchKind, 58728795 /* SomeType */)) { + var type = symbol.getExportAssignedTypeSymbol(); + if (type && type.kind !== 32 /* DynamicModule */) { + return true; + } + + var type = symbol.assignedType(); + if (type && type.kind !== 32 /* DynamicModule */) { + return true; + } + } else if (TypeScript.hasFlag(declSearchKind, 68147712 /* SomeValue */ & ~67108864 /* EnumMember */)) { + if (symbol.assignedType() && symbol.assignedType().isError()) { + return true; + } else if (symbol.assignedValue() || symbol.getExportAssignedValueSymbol()) { + return true; + } else { + var assignedType = symbol.assignedType(); + if (assignedType && assignedType.isContainer() && assignedType.getInstanceType()) { + return true; + } + + var decls = symbol.getDeclarations(); + var ast = decls[0].ast(); + return ast.moduleReference.kind() === 245 /* ExternalModuleReference */; + } + } + } + + return false; + }; + + var tryFindAlias = function (decl) { + var childDecls = decl.searchChildDecls(symbolName, 128 /* TypeAlias */); + + if (childDecls.length) { + var sym = childDecls[0].getSymbol(); + if (isAcceptableAlias(sym)) { + return sym; + } + } + return null; + }; + + for (var i = declPath.length - 1; i >= 0; i--) { + decl = declPath[i]; + pathDeclKind = decl.kind; + + if (decl.flags & 2097152 /* DeclaredInAWithBlock */) { + return this.semanticInfoChain.anyTypeSymbol; + } + + if (pathDeclKind & allowedContainerDeclKind) { + childDecls = decl.searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + return childDecls[0].getSymbol(); + } + + var alias = tryFindAlias(decl); + if (alias) { + return alias; + } + + if (declSearchKind & 68147712 /* SomeValue */) { + instanceSymbol = decl.getSymbol().getInstanceSymbol(); + + if (instanceSymbol) { + instanceType = instanceSymbol.type; + + childSymbol = this.getNamedPropertySymbol(symbolName, declSearchKind, instanceType); + + if (childSymbol && (childSymbol.kind & declSearchKind) && !childSymbol.anyDeclHasFlag(16 /* Static */)) { + return childSymbol; + } + } + + valDecl = decl.getValueDecl(); + + if (valDecl) { + decl = valDecl; + } + } + + declSymbol = decl.getSymbol().type; + + var childSymbol = this.getNamedPropertySymbol(symbolName, declSearchKind, declSymbol); + + if (childSymbol && (childSymbol.kind & declSearchKind) && !childSymbol.anyDeclHasFlag(16 /* Static */)) { + return childSymbol; + } + } else if ((declSearchKind & (58728795 /* SomeType */ | 164 /* SomeContainer */)) || !(pathDeclKind & 8 /* Class */)) { + var candidateSymbol = null; + + if (pathDeclKind === 131072 /* FunctionExpression */ && symbolName === decl.getFunctionExpressionName()) { + candidateSymbol = decl.getSymbol(); + } + + childDecls = decl.searchChildDecls(symbolName, declSearchKind); + + if (childDecls.length) { + if (decl.kind & 1032192 /* SomeFunction */) { + decl.ensureSymbolIsBound(); + } + return childDecls[0].getSymbol(); + } + + if (candidateSymbol) { + return candidateSymbol; + } + + var alias = tryFindAlias(decl); + if (alias) { + return alias; + } + } + } + + symbol = this.semanticInfoChain.findSymbol([symbolName], declSearchKind); + if (symbol) { + return symbol; + } + + if (!TypeScript.hasFlag(declSearchKind, 128 /* TypeAlias */)) { + symbol = this.semanticInfoChain.findSymbol([symbolName], 128 /* TypeAlias */); + if (symbol && isAcceptableAlias(symbol)) { + return symbol; + } + } + + return null; + }; + + PullTypeResolver.prototype.getVisibleDeclsFromDeclPath = function (declPath, declSearchKind) { + var result = []; + var decl = null; + var childDecls; + var pathDeclKind; + + for (var i = declPath.length - 1; i >= 0; i--) { + decl = declPath[i]; + pathDeclKind = decl.kind; + + var declKind = decl.kind; + + if (declKind !== 8 /* Class */ && declKind !== 16 /* Interface */) { + this.addFilteredDecls(decl.getChildDecls(), declSearchKind, result); + } + + switch (declKind) { + case 4 /* Container */: + case 32 /* DynamicModule */: + var otherDecls = this.semanticInfoChain.findDeclsFromPath(declPath.slice(0, i + 1), 164 /* SomeContainer */); + for (var j = 0, m = otherDecls.length; j < m; j++) { + var otherDecl = otherDecls[j]; + if (otherDecl === decl) { + continue; + } + + var otherDeclChildren = otherDecl.getChildDecls(); + for (var k = 0, s = otherDeclChildren.length; k < s; k++) { + var otherDeclChild = otherDeclChildren[k]; + if ((otherDeclChild.flags & 1 /* Exported */) && (otherDeclChild.kind & declSearchKind)) { + result.push(otherDeclChild); + } + } + } + + break; + + case 8 /* Class */: + case 16 /* Interface */: + var parameters = decl.getTypeParameters(); + if (parameters && parameters.length) { + this.addFilteredDecls(parameters, declSearchKind, result); + } + + break; + + case 131072 /* FunctionExpression */: + var functionExpressionName = decl.getFunctionExpressionName(); + if (functionExpressionName) { + result.push(decl); + } + + case 16384 /* Function */: + case 32768 /* ConstructorMethod */: + case 65536 /* Method */: + var parameters = decl.getTypeParameters(); + if (parameters && parameters.length) { + this.addFilteredDecls(parameters, declSearchKind, result); + } + + break; + } + } + + var topLevelDecls = this.semanticInfoChain.topLevelDecls(); + for (var i = 0, n = topLevelDecls.length; i < n; i++) { + var topLevelDecl = topLevelDecls[i]; + if (declPath.length > 0 && topLevelDecl.fileName() === declPath[0].fileName()) { + continue; + } + + if (!topLevelDecl.isExternalModule()) { + this.addFilteredDecls(topLevelDecl.getChildDecls(), declSearchKind, result); + } + } + + return result; + }; + + PullTypeResolver.prototype.addFilteredDecls = function (decls, declSearchKind, result) { + if (decls.length) { + for (var i = 0, n = decls.length; i < n; i++) { + var decl = decls[i]; + if (decl.kind & declSearchKind) { + result.push(decl); + } + } + } + }; + + PullTypeResolver.prototype.getVisibleDecls = function (enclosingDecl) { + var declPath = enclosingDecl.getParentPath(); + + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + + return this.getVisibleDeclsFromDeclPath(declPath, declSearchKind); + }; + + PullTypeResolver.prototype.getVisibleContextSymbols = function (enclosingDecl, context) { + var contextualTypeSymbol = context.getContextualType(); + if (!contextualTypeSymbol || this.isAnyOrEquivalent(contextualTypeSymbol)) { + return null; + } + + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + var members = contextualTypeSymbol.getAllMembers(declSearchKind, 2 /* externallyVisible */); + + for (var i = 0; i < members.length; i++) { + members[i].setUnresolved(); + } + + return members; + }; + + PullTypeResolver.prototype.getVisibleMembersFromExpression = function (expression, enclosingDecl, context) { + var lhs = this.resolveAST(expression, false, context); + + if (isTypesOnlyLocation(expression) && (lhs.kind === 8 /* Class */ || lhs.kind === 16 /* Interface */ || lhs.kind === 64 /* Enum */)) { + return null; + } + + var lhsType = lhs.type; + if (!lhsType) { + return null; + } + + this.resolveDeclaredSymbol(lhsType, context); + + if (lhsType.isContainer() && lhsType.isAlias()) { + lhsType = lhsType.getExportAssignedTypeSymbol(); + } + + if (this.isAnyOrEquivalent(lhsType)) { + return null; + } + + var memberVisibilty = 2 /* externallyVisible */; + var containerSymbol = lhsType; + if (containerSymbol.kind === 33554432 /* ConstructorType */) { + containerSymbol = containerSymbol.getConstructSignatures()[0].returnType; + } + + if (containerSymbol && containerSymbol.isClass()) { + var declPath = enclosingDecl.getParentPath(); + if (declPath && declPath.length) { + var declarations = containerSymbol.getDeclarations(); + for (var i = 0, n = declarations.length; i < n; i++) { + var declaration = declarations[i]; + if (TypeScript.ArrayUtilities.contains(declPath, declaration)) { + memberVisibilty = 1 /* internallyVisible */; + break; + } + } + } + } + + var declSearchKind = 58728795 /* SomeType */ | 164 /* SomeContainer */ | 68147712 /* SomeValue */; + + var members = []; + + if (lhsType.isContainer()) { + var exportedAssignedContainerSymbol = lhsType.getExportAssignedContainerSymbol(); + if (exportedAssignedContainerSymbol) { + lhsType = exportedAssignedContainerSymbol; + } + } + + lhsType = this.getApparentType(lhsType); + + if (!lhsType.isResolved) { + var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, context); + + if (potentiallySpecializedType !== lhsType) { + if (!lhs.isType()) { + context.setTypeInContext(lhs, potentiallySpecializedType); + } + + lhsType = potentiallySpecializedType; + } + } + + members = lhsType.getAllMembers(declSearchKind, memberVisibilty); + + if (lhsType.isContainer()) { + var associatedInstance = lhsType.getInstanceSymbol(); + if (associatedInstance) { + var instanceType = associatedInstance.type; + this.resolveDeclaredSymbol(instanceType, context); + var instanceMembers = instanceType.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(instanceMembers); + } + + var exportedContainer = lhsType.getExportAssignedContainerSymbol(); + if (exportedContainer) { + var exportedContainerMembers = exportedContainer.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(exportedContainerMembers); + } + } else if (!lhsType.isConstructor() && !lhsType.isEnum()) { + var associatedContainerSymbol = lhsType.getAssociatedContainerType(); + if (associatedContainerSymbol) { + var containerType = associatedContainerSymbol.type; + this.resolveDeclaredSymbol(containerType, context); + var containerMembers = containerType.getAllMembers(declSearchKind, memberVisibilty); + members = members.concat(containerMembers); + } + } + + if (lhsType.isFunctionType() && this.cachedFunctionInterfaceType()) { + members = members.concat(this.cachedFunctionInterfaceType().getAllMembers(declSearchKind, 2 /* externallyVisible */)); + } + + return members; + }; + + PullTypeResolver.prototype.isAnyOrEquivalent = function (type) { + return (type === this.semanticInfoChain.anyTypeSymbol) || type.isError(); + }; + + PullTypeResolver.prototype.resolveExternalModuleReference = function (idText, currentFileName) { + var originalIdText = idText; + var symbol = null; + + if (TypeScript.isRelative(originalIdText)) { + var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); + symbol = this.semanticInfoChain.findExternalModule(path + idText); + } else { + idText = originalIdText; + + symbol = this.semanticInfoChain.findAmbientExternalModuleInGlobalContext(TypeScript.quoteStr(originalIdText)); + + if (!symbol) { + var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); + + while (symbol === null && path != "") { + symbol = this.semanticInfoChain.findExternalModule(path + idText); + if (symbol === null) { + if (path === '/') { + path = ''; + } else { + path = TypeScript.normalizePath(path + ".."); + path = path && path != '/' ? path + '/' : path; + } + } + } + } + } + + return symbol; + }; + + PullTypeResolver.prototype.resolveDeclaredSymbol = function (symbol, context) { + if (!symbol || symbol.isResolved || symbol.isTypeReference()) { + return symbol; + } + + if (!context) { + context = new TypeScript.PullTypeResolutionContext(this); + } + + return this.resolveDeclaredSymbolWorker(symbol, context); + }; + + PullTypeResolver.prototype.resolveDeclaredSymbolWorker = function (symbol, context) { + if (!symbol || symbol.isResolved) { + return symbol; + } + + if (symbol.inResolution) { + if (!symbol.type && !symbol.isType()) { + symbol.type = this.semanticInfoChain.anyTypeSymbol; + } + + return symbol; + } + + var decls = symbol.getDeclarations(); + + for (var i = 0; i < decls.length; i++) { + var decl = decls[i]; + + var ast = this.semanticInfoChain.getASTForDecl(decl); + + if (!ast || (ast.kind() === 139 /* GetAccessor */ && ast.parent.parent.kind() === 215 /* ObjectLiteralExpression */) || (ast.kind() === 140 /* SetAccessor */ && ast.parent.parent.kind() === 215 /* ObjectLiteralExpression */)) { + return symbol; + } + + if (ast.parent && ast.parent.kind() === 236 /* CatchClause */ && ast.parent.identifier === ast) { + return symbol; + } + + if (ast.parent && ast.parent.kind() === 219 /* SimpleArrowFunctionExpression */ && ast.parent.identifier === ast) { + return symbol; + } + + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(ast); + var resolvedSymbol; + if (enclosingModule) { + resolvedSymbol = this.resolveSingleModuleDeclaration(enclosingModule, ast, context); + } else if (ast.kind() === 120 /* SourceUnit */ && decl.kind === 32 /* DynamicModule */) { + resolvedSymbol = this.resolveModuleSymbol(decl.getSymbol(), context, null, null, ast); + } else { + TypeScript.Debug.assert(ast.kind() !== 11 /* IdentifierName */ && ast.kind() !== 212 /* MemberAccessExpression */); + resolvedSymbol = this.resolveAST(ast, false, context); + } + + if (decl.kind === 2048 /* Parameter */ && !symbol.isResolved && !symbol.type && resolvedSymbol && symbol.anyDeclHasFlag(8388608 /* PropertyParameter */ | 67108864 /* ConstructorParameter */)) { + symbol.type = resolvedSymbol.type; + symbol.setResolved(); + } + } + + if (!symbol.isResolved) { + TypeScript.Debug.assert(!symbol.inResolution); + + symbol.setResolved(); + } + + return symbol; + }; + + PullTypeResolver.prototype.resolveOtherDecl = function (otherDecl, context) { + var astForOtherDecl = this.getASTForDecl(otherDecl); + var moduleDecl = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(astForOtherDecl); + if (moduleDecl) { + this.resolveSingleModuleDeclaration(moduleDecl, astForOtherDecl, context); + } else { + this.resolveAST(astForOtherDecl, false, context); + } + }; + + PullTypeResolver.prototype.resolveOtherDeclarations = function (astName, context) { + var _this = this; + var resolvedDecl = this.semanticInfoChain.getDeclForAST(astName); + var symbol = resolvedDecl.getSymbol(); + + var allDecls = symbol.getDeclarations(); + this.inResolvingOtherDeclsWalker.walkOtherPullDecls(resolvedDecl, symbol.getDeclarations(), function (otherDecl) { + return _this.resolveOtherDecl(otherDecl, context); + }); + }; + + PullTypeResolver.prototype.resolveSourceUnit = function (sourceUnit, context) { + var enclosingDecl = this.getEnclosingDeclForAST(sourceUnit); + var moduleSymbol = enclosingDecl.getSymbol(); + this.ensureAllSymbolsAreBound(moduleSymbol); + + this.resolveFirstExportAssignmentStatement(sourceUnit.moduleElements, context); + this.resolveAST(sourceUnit.moduleElements, false, context); + + if (this.canTypeCheckAST(sourceUnit, context)) { + this.typeCheckSourceUnit(sourceUnit, context); + } + + return moduleSymbol; + }; + + PullTypeResolver.prototype.typeCheckSourceUnit = function (sourceUnit, context) { + var _this = this; + this.setTypeChecked(sourceUnit, context); + + this.resolveAST(sourceUnit.moduleElements, false, context); + + this.typeCheckCallBacks.push(function (context) { + return _this.verifyUniquenessOfImportNamesInSourceUnit(sourceUnit); + }); + }; + + PullTypeResolver.prototype.verifyUniquenessOfImportNamesInSourceUnit = function (sourceUnit) { + var _this = this; + var enclosingDecl = this.semanticInfoChain.getDeclForAST(sourceUnit); + + var doesImportNameExistInOtherFiles = function (name) { + var importSymbol = _this.semanticInfoChain.findTopLevelSymbol(name, 128 /* TypeAlias */, null); + return importSymbol && importSymbol.isAlias(); + }; + + this.checkUniquenessOfImportNames([enclosingDecl], doesImportNameExistInOtherFiles); + }; + + PullTypeResolver.prototype.resolveEnumDeclaration = function (ast, context) { + var containerDecl = this.semanticInfoChain.getDeclForAST(ast); + var containerSymbol = containerDecl.getSymbol(); + + if (containerSymbol.isResolved || containerSymbol.inResolution) { + return containerSymbol; + } + + containerSymbol.inResolution = true; + + var containerDecls = containerSymbol.getDeclarations(); + + for (var i = 0; i < containerDecls.length; i++) { + var childDecls = containerDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + + containerSymbol.setResolved(); + + this.resolveOtherDeclarations(ast, context); + + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckEnumDeclaration(ast, context); + } + + return containerSymbol; + }; + + PullTypeResolver.prototype.typeCheckEnumDeclaration = function (ast, context) { + var _this = this; + this.setTypeChecked(ast, context); + + this.resolveAST(ast.enumElements, false, context); + var containerDecl = this.semanticInfoChain.getDeclForAST(ast); + this.validateVariableDeclarationGroups(containerDecl, context); + + this.typeCheckCallBacks.push(function (context) { + return _this.checkInitializersInEnumDeclarations(containerDecl, context); + }); + + if (!TypeScript.ASTHelpers.enumIsElided(ast)) { + this.checkNameForCompilerGeneratedDeclarationCollision(ast, true, ast.identifier, context); + } + }; + + PullTypeResolver.prototype.postTypeCheckEnumDeclaration = function (ast, context) { + this.checkThisCaptureVariableCollides(ast, true, context); + }; + + PullTypeResolver.prototype.checkInitializersInEnumDeclarations = function (decl, context) { + var symbol = decl.getSymbol(); + + var declarations = symbol.getDeclarations(); + if (decl !== declarations[0]) { + return; + } + + var seenEnumDeclWithNoFirstMember = false; + for (var i = 0; i < declarations.length; ++i) { + var currentDecl = declarations[i]; + + var ast = currentDecl.ast(); + if (ast.enumElements.nonSeparatorCount() === 0) { + continue; + } + + var firstVariable = ast.enumElements.nonSeparatorAt(0); + if (!firstVariable.equalsValueClause) { + if (!seenEnumDeclWithNoFirstMember) { + seenEnumDeclWithNoFirstMember = true; + } else { + this.semanticInfoChain.addDiagnosticFromAST(firstVariable, TypeScript.DiagnosticCode.In_enums_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_the_first_enum_element); + } + } + } + }; + + PullTypeResolver.prototype.resolveModuleDeclaration = function (ast, context) { + var result; + + if (ast.stringLiteral) { + result = this.resolveSingleModuleDeclaration(ast, ast.stringLiteral, context); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(ast.name); + for (var i = 0, n = moduleNames.length; i < n; i++) { + result = this.resolveSingleModuleDeclaration(ast, moduleNames[i], context); + } + } + + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckModuleDeclaration(ast, context); + } + + return result; + }; + + PullTypeResolver.prototype.ensureAllSymbolsAreBound = function (containerSymbol) { + if (containerSymbol) { + var containerDecls = containerSymbol.getDeclarations(); + + for (var i = 0; i < containerDecls.length; i++) { + var childDecls = containerDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + } + }; + + PullTypeResolver.prototype.resolveModuleSymbol = function (containerSymbol, context, moduleDeclAST, moduleDeclNameAST, sourceUnitAST) { + if (containerSymbol.isResolved || containerSymbol.inResolution) { + return containerSymbol; + } + + containerSymbol.inResolution = true; + this.ensureAllSymbolsAreBound(containerSymbol); + + var instanceSymbol = containerSymbol.getInstanceSymbol(); + + if (instanceSymbol) { + this.resolveDeclaredSymbol(instanceSymbol, context); + } + + var isLastName = TypeScript.ASTHelpers.isLastNameOfModule(moduleDeclAST, moduleDeclNameAST); + if (isLastName) { + this.resolveFirstExportAssignmentStatement(moduleDeclAST.moduleElements, context); + } else if (sourceUnitAST) { + this.resolveFirstExportAssignmentStatement(sourceUnitAST.moduleElements, context); + } + + containerSymbol.setResolved(); + + if (moduleDeclNameAST) { + this.resolveOtherDeclarations(moduleDeclNameAST, context); + } + + return containerSymbol; + }; + + PullTypeResolver.prototype.resolveFirstExportAssignmentStatement = function (moduleElements, context) { + for (var i = 0, n = moduleElements.childCount(); i < n; i++) { + var moduleElement = moduleElements.childAt(i); + if (moduleElement.kind() === 134 /* ExportAssignment */) { + this.resolveExportAssignmentStatement(moduleElement, context); + return; + } + } + }; + + PullTypeResolver.prototype.resolveSingleModuleDeclaration = function (ast, astName, context) { + var containerDecl = this.semanticInfoChain.getDeclForAST(astName); + var containerSymbol = containerDecl.getSymbol(); + + return this.resolveModuleSymbol(containerSymbol, context, ast, astName, null); + }; + + PullTypeResolver.prototype.typeCheckModuleDeclaration = function (ast, context) { + if (ast.stringLiteral) { + this.typeCheckSingleModuleDeclaration(ast, ast.stringLiteral, context); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(ast.name); + for (var i = 0, n = moduleNames.length; i < n; i++) { + this.typeCheckSingleModuleDeclaration(ast, moduleNames[i], context); + } + } + }; + + PullTypeResolver.prototype.typeCheckSingleModuleDeclaration = function (ast, astName, context) { + var _this = this; + this.setTypeChecked(ast, context); + + if (TypeScript.ASTHelpers.isLastNameOfModule(ast, astName)) { + this.resolveAST(ast.moduleElements, false, context); + } + + var containerDecl = this.semanticInfoChain.getDeclForAST(astName); + this.validateVariableDeclarationGroups(containerDecl, context); + + if (ast.stringLiteral) { + if (TypeScript.isRelative(ast.stringLiteral.valueText())) { + this.semanticInfoChain.addDiagnosticFromAST(ast.stringLiteral, TypeScript.DiagnosticCode.Ambient_external_module_declaration_cannot_specify_relative_module_name); + } + } + + if (!TypeScript.ASTHelpers.moduleIsElided(ast) && !ast.stringLiteral) { + this.checkNameForCompilerGeneratedDeclarationCollision(astName, true, astName, context); + } + + this.typeCheckCallBacks.push(function (context) { + return _this.verifyUniquenessOfImportNamesInModule(containerDecl); + }); + }; + + PullTypeResolver.prototype.verifyUniquenessOfImportNamesInModule = function (decl) { + var symbol = decl.getSymbol(); + if (!symbol) { + return; + } + + var decls = symbol.getDeclarations(); + + if (decls[0] !== decl) { + return; + } + + this.checkUniquenessOfImportNames(decls); + }; + + PullTypeResolver.prototype.checkUniquenessOfImportNames = function (decls, doesNameExistOutside) { + var _this = this; + var importDeclarationNames; + + for (var i = 0; i < decls.length; ++i) { + var childDecls = decls[i].getChildDecls(); + for (var j = 0; j < childDecls.length; ++j) { + var childDecl = childDecls[j]; + if (childDecl.kind === 128 /* TypeAlias */) { + importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); + importDeclarationNames[childDecl.name] = true; + } + } + } + + if (!importDeclarationNames && !doesNameExistOutside) { + return; + } + + for (var i = 0; i < decls.length; ++i) { + this.scanVariableDeclarationGroups(decls[i], function (firstDeclInGroup) { + var nameConflict = importDeclarationNames && importDeclarationNames[firstDeclInGroup.name]; + if (!nameConflict) { + nameConflict = doesNameExistOutside && doesNameExistOutside(firstDeclInGroup.name); + if (nameConflict) { + importDeclarationNames = importDeclarationNames || TypeScript.createIntrinsicsObject(); + importDeclarationNames[firstDeclInGroup.name] = true; + } + } + + if (nameConflict) { + _this.semanticInfoChain.addDiagnosticFromAST(firstDeclInGroup.ast(), TypeScript.DiagnosticCode.Variable_declaration_cannot_have_the_same_name_as_an_import_declaration); + } + }); + } + }; + + PullTypeResolver.prototype.scanVariableDeclarationGroups = function (enclosingDecl, firstDeclHandler, subsequentDeclHandler) { + var declGroups = enclosingDecl.getVariableDeclGroups(); + + for (var i = 0; i < declGroups.length; i++) { + var firstSymbol = null; + var enclosingDeclForFirstSymbol = null; + + if (enclosingDecl.kind === 1 /* Script */ && declGroups[i].length) { + var name = declGroups[i][0].name; + var candidateSymbol = this.semanticInfoChain.findTopLevelSymbol(name, 512 /* Variable */, enclosingDecl); + if (candidateSymbol) { + if (!candidateSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */)) { + if (!candidateSymbol.isResolved) { + this.resolveDeclaredSymbol(candidateSymbol); + } + firstSymbol = candidateSymbol; + } + } + } + + for (var j = 0; j < declGroups[i].length; j++) { + var decl = declGroups[i][j]; + + var name = decl.name; + + var symbol = decl.getSymbol(); + + if (j === 0) { + firstDeclHandler(decl); + if (!subsequentDeclHandler) { + break; + } + + if (!firstSymbol || !firstSymbol.type) { + firstSymbol = symbol; + continue; + } + } + + subsequentDeclHandler(decl, firstSymbol); + } + } + }; + + PullTypeResolver.prototype.postTypeCheckModuleDeclaration = function (ast, context) { + this.checkThisCaptureVariableCollides(ast, true, context); + }; + + PullTypeResolver.prototype.isTypeRefWithoutTypeArgs = function (term) { + if (term.kind() === 11 /* IdentifierName */) { + return true; + } else if (term.kind() === 121 /* QualifiedName */) { + var binex = term; + + if (binex.right.kind() === 11 /* IdentifierName */) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.createInstantiatedType = function (type, typeArguments) { + if (!type.isGeneric()) { + return type; + } + + var typeParameters = type.getTypeArgumentsOrTypeParameters(); + + var typeParameterArgumentMap = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameterArgumentMap[typeParameters[i].pullSymbolID] = typeArguments[i] || new TypeScript.PullErrorTypeSymbol(this.semanticInfoChain.anyTypeSymbol, typeParameters[i].name); + } + + return TypeScript.PullInstantiatedTypeReferenceSymbol.create(this, type, typeParameterArgumentMap); + }; + + PullTypeResolver.prototype.resolveReferenceTypeDeclaration = function (classOrInterface, name, heritageClauses, context) { + var _this = this; + var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var enclosingDecl = this.getEnclosingDecl(typeDecl); + var typeDeclSymbol = typeDecl.getSymbol(); + var typeDeclIsClass = classOrInterface.kind() === 131 /* ClassDeclaration */; + var hasVisited = this.getSymbolForAST(classOrInterface, context) !== null; + + if ((typeDeclSymbol.isResolved && hasVisited) || (typeDeclSymbol.inResolution && !context.isInBaseTypeResolution())) { + return typeDeclSymbol; + } + + var wasResolving = typeDeclSymbol.inResolution; + typeDeclSymbol.startResolving(); + + var typeRefDecls = typeDeclSymbol.getDeclarations(); + + for (var i = 0; i < typeRefDecls.length; i++) { + var childDecls = typeRefDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + + if (!typeDeclSymbol.isResolved) { + var typeDeclTypeParameters = typeDeclSymbol.getTypeParameters(); + for (var i = 0; i < typeDeclTypeParameters.length; i++) { + this.resolveDeclaredSymbol(typeDeclTypeParameters[i], context); + } + } + + var wasInBaseTypeResolution = context.startBaseTypeResolution(); + + if (!typeDeclIsClass && !hasVisited) { + typeDeclSymbol.resetKnownBaseTypeCount(); + } + + var extendsClause = TypeScript.ASTHelpers.getExtendsHeritageClause(heritageClauses); + if (extendsClause) { + for (var i = typeDeclSymbol.getKnownBaseTypeCount(); i < extendsClause.typeNames.nonSeparatorCount(); i = typeDeclSymbol.getKnownBaseTypeCount()) { + typeDeclSymbol.incrementKnownBaseCount(); + var parentType = this.resolveTypeReference(extendsClause.typeNames.nonSeparatorAt(i), context); + + if (typeDeclSymbol.isValidBaseKind(parentType, true)) { + this.setSymbolForAST(extendsClause.typeNames.nonSeparatorAt(i), parentType, null); + + if (!typeDeclSymbol.hasBase(parentType) && !parentType.hasBase(typeDeclSymbol)) { + typeDeclSymbol.addExtendedType(parentType); + + var specializations = typeDeclSymbol.getKnownSpecializations(); + + for (var j = 0; j < specializations.length; j++) { + specializations[j].addExtendedType(parentType); + } + } + } else if (parentType && !this.getSymbolForAST(extendsClause.typeNames.nonSeparatorAt(i), context)) { + this.setSymbolForAST(extendsClause.typeNames.nonSeparatorAt(i), parentType, null); + } + } + } + + var implementsClause = TypeScript.ASTHelpers.getImplementsHeritageClause(heritageClauses); + if (implementsClause && typeDeclIsClass) { + var extendsCount = extendsClause ? extendsClause.typeNames.nonSeparatorCount() : 0; + for (var i = typeDeclSymbol.getKnownBaseTypeCount(); ((i - extendsCount) >= 0) && ((i - extendsCount) < implementsClause.typeNames.nonSeparatorCount()); i = typeDeclSymbol.getKnownBaseTypeCount()) { + typeDeclSymbol.incrementKnownBaseCount(); + var implementedTypeAST = implementsClause.typeNames.nonSeparatorAt(i - extendsCount); + var implementedType = this.resolveTypeReference(implementedTypeAST, context); + + if (typeDeclSymbol.isValidBaseKind(implementedType, false)) { + this.setSymbolForAST(implementsClause.typeNames.nonSeparatorAt(i - extendsCount), implementedType, null); + + if (!typeDeclSymbol.hasBase(implementedType) && !implementedType.hasBase(typeDeclSymbol)) { + typeDeclSymbol.addImplementedType(implementedType); + } + } else if (implementedType && !this.getSymbolForAST(implementsClause.typeNames.nonSeparatorAt(i - extendsCount), context)) { + this.setSymbolForAST(implementsClause.typeNames.nonSeparatorAt(i - extendsCount), implementedType, null); + } + } + } + + context.doneBaseTypeResolution(wasInBaseTypeResolution); + + if (wasInBaseTypeResolution) { + typeDeclSymbol.inResolution = false; + + this.typeCheckCallBacks.push(function (context) { + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + _this.resolveClassDeclaration(classOrInterface, context); + } else { + _this.resolveInterfaceDeclaration(classOrInterface, context); + } + }); + + return typeDeclSymbol; + } + + this.setSymbolForAST(name, typeDeclSymbol, context); + this.setSymbolForAST(classOrInterface, typeDeclSymbol, context); + + typeDeclSymbol.setResolved(); + + return typeDeclSymbol; + }; + + PullTypeResolver.prototype.resolveClassDeclaration = function (classDeclAST, context) { + var classDecl = this.semanticInfoChain.getDeclForAST(classDeclAST); + var classDeclSymbol = classDecl.getSymbol(); + + if (!classDeclSymbol.isResolved) { + this.resolveReferenceTypeDeclaration(classDeclAST, classDeclAST.identifier, classDeclAST.heritageClauses, context); + + var constructorMethod = classDeclSymbol.getConstructorMethod(); + var extendedTypes = classDeclSymbol.getExtendedTypes(); + var parentType = extendedTypes.length ? extendedTypes[0] : null; + + if (constructorMethod) { + if (parentType) { + var parentConstructorSymbol = parentType.getConstructorMethod(); + + if (parentConstructorSymbol) { + var parentConstructorTypeSymbol = parentConstructorSymbol.type; + var constructorTypeSymbol = constructorMethod.type; + if (!constructorTypeSymbol.hasBase(parentConstructorTypeSymbol)) { + constructorTypeSymbol.addExtendedType(parentConstructorTypeSymbol); + } + } + } + + if (!classDeclSymbol.isResolved) { + return classDeclSymbol; + } + } + + this.resolveOtherDeclarations(classDeclAST, context); + } + + if (this.canTypeCheckAST(classDeclAST, context)) { + this.typeCheckClassDeclaration(classDeclAST, context); + } + + return classDeclSymbol; + }; + + PullTypeResolver.prototype.typeCheckTypeParametersOfTypeDeclaration = function (classOrInterface, context) { + var _this = this; + var typeParametersList = classOrInterface.kind() == 131 /* ClassDeclaration */ ? classOrInterface.typeParameterList : classOrInterface.typeParameterList; + + if (typeParametersList) { + var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var typeDeclSymbol = typeDecl.getSymbol(); + + for (var i = 0; i < typeParametersList.typeParameters.nonSeparatorCount(); i++) { + var typeParameterAST = typeParametersList.typeParameters.nonSeparatorAt(i); + this.resolveTypeParameterDeclaration(typeParameterAST, context); + + var typeParameterDecl = this.semanticInfoChain.getDeclForAST(typeParameterAST); + var typeParameterSymbol = typeParameterDecl.getSymbol(); + + this.checkSymbolPrivacy(typeDeclSymbol, typeParameterSymbol, function (symbol) { + return _this.typeParameterOfTypeDeclarationPrivacyErrorReporter(classOrInterface, typeParameterAST, typeParameterSymbol, symbol, context); + }); + } + } + }; + + PullTypeResolver.prototype.typeCheckClassDeclaration = function (classDeclAST, context) { + this.setTypeChecked(classDeclAST, context); + + var classDecl = this.semanticInfoChain.getDeclForAST(classDeclAST); + var classDeclSymbol = classDecl.getSymbol(); + + this.checkNameForCompilerGeneratedDeclarationCollision(classDeclAST, true, classDeclAST.identifier, context); + this.resolveAST(classDeclAST.classElements, false, context); + + this.typeCheckTypeParametersOfTypeDeclaration(classDeclAST, context); + this.typeCheckBases(classDeclAST, classDeclAST.identifier, classDeclAST.heritageClauses, classDeclSymbol, this.getEnclosingDecl(classDecl), context); + + if (!classDeclSymbol.hasBaseTypeConflict()) { + this.typeCheckMembersAgainstIndexer(classDeclSymbol, classDecl, context); + } + + this.checkTypeForDuplicateIndexSignatures(classDeclSymbol); + }; + + PullTypeResolver.prototype.postTypeCheckClassDeclaration = function (classDeclAST, context) { + this.checkThisCaptureVariableCollides(classDeclAST, true, context); + }; + + PullTypeResolver.prototype.resolveTypeSymbolSignatures = function (typeSymbol, context) { + var callSignatures = typeSymbol.getCallSignatures(); + for (var i = 0; i < callSignatures.length; i++) { + this.resolveDeclaredSymbol(callSignatures[i], context); + } + + var constructSignatures = typeSymbol.getConstructSignatures(); + for (var i = 0; i < constructSignatures.length; i++) { + this.resolveDeclaredSymbol(constructSignatures[i], context); + } + + var indexSignatures = typeSymbol.getIndexSignatures(); + for (var i = 0; i < indexSignatures.length; i++) { + this.resolveDeclaredSymbol(indexSignatures[i], context); + } + }; + + PullTypeResolver.prototype.resolveInterfaceDeclaration = function (interfaceDeclAST, context) { + this.resolveReferenceTypeDeclaration(interfaceDeclAST, interfaceDeclAST.identifier, interfaceDeclAST.heritageClauses, context); + + var interfaceDecl = this.semanticInfoChain.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + this.resolveTypeSymbolSignatures(interfaceDeclSymbol, context); + + if (interfaceDeclSymbol.isResolved) { + this.resolveOtherDeclarations(interfaceDeclAST, context); + + if (this.canTypeCheckAST(interfaceDeclAST, context)) { + this.typeCheckInterfaceDeclaration(interfaceDeclAST, context); + } + } + + return interfaceDeclSymbol; + }; + + PullTypeResolver.prototype.typeCheckInterfaceDeclaration = function (interfaceDeclAST, context) { + this.setTypeChecked(interfaceDeclAST, context); + + var interfaceDecl = this.semanticInfoChain.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + this.resolveAST(interfaceDeclAST.body.typeMembers, false, context); + + this.typeCheckTypeParametersOfTypeDeclaration(interfaceDeclAST, context); + this.typeCheckBases(interfaceDeclAST, interfaceDeclAST.identifier, interfaceDeclAST.heritageClauses, interfaceDeclSymbol, this.getEnclosingDecl(interfaceDecl), context); + + if (!interfaceDeclSymbol.hasBaseTypeConflict()) { + this.typeCheckMembersAgainstIndexer(interfaceDeclSymbol, interfaceDecl, context); + } + + var allInterfaceDecls = interfaceDeclSymbol.getDeclarations(); + if (interfaceDecl === allInterfaceDecls[allInterfaceDecls.length - 1]) { + this.checkTypeForDuplicateIndexSignatures(interfaceDeclSymbol); + } + + if (!this.checkInterfaceDeclForIdenticalTypeParameters(interfaceDeclAST, context)) { + this.semanticInfoChain.addDiagnosticFromAST(interfaceDeclAST.identifier, TypeScript.DiagnosticCode.All_declarations_of_an_interface_must_have_identical_type_parameters); + } + }; + + PullTypeResolver.prototype.checkInterfaceDeclForIdenticalTypeParameters = function (interfaceDeclAST, context) { + var interfaceDecl = this.semanticInfoChain.getDeclForAST(interfaceDeclAST); + var interfaceDeclSymbol = interfaceDecl.getSymbol(); + + if (!interfaceDeclSymbol.isGeneric()) { + return true; + } + + var firstInterfaceDecl = interfaceDeclSymbol.getDeclarations()[0]; + if (firstInterfaceDecl == interfaceDecl) { + return true; + } + + var typeParameters = interfaceDecl.getTypeParameters(); + var firstInterfaceDeclTypeParameters = firstInterfaceDecl.getTypeParameters(); + + if (typeParameters.length != firstInterfaceDeclTypeParameters.length) { + return false; + } + + for (var i = 0; i < typeParameters.length; i++) { + var typeParameter = typeParameters[i]; + var firstInterfaceDeclTypeParameter = firstInterfaceDeclTypeParameters[i]; + + if (typeParameter.name != firstInterfaceDeclTypeParameter.name) { + return false; + } + + var typeParameterSymbol = typeParameter.getSymbol(); + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter); + var firstInterfaceDeclTypeParameterAST = this.semanticInfoChain.getASTForDecl(firstInterfaceDeclTypeParameter); + + if (!!typeParameterAST.constraint != !!firstInterfaceDeclTypeParameterAST.constraint) { + return false; + } + + if (typeParameterAST.constraint) { + var typeParameterConstraint = this.resolveAST(typeParameterAST.constraint, false, context); + if (!this.typesAreIdenticalWithNewEnclosingTypes(typeParameterConstraint, typeParameterSymbol.getConstraint(), context)) { + return false; + } + } + } + + return true; + }; + + PullTypeResolver.prototype.checkTypeForDuplicateIndexSignatures = function (enclosingTypeSymbol) { + var indexSignatures = enclosingTypeSymbol.getOwnIndexSignatures(); + var firstStringIndexer = null; + var firstNumberIndexer = null; + for (var i = 0; i < indexSignatures.length; i++) { + var currentIndexer = indexSignatures[i]; + var currentParameterType = currentIndexer.parameters[0].type; + TypeScript.Debug.assert(currentParameterType); + if (currentParameterType === this.semanticInfoChain.stringTypeSymbol) { + if (firstStringIndexer) { + this.semanticInfoChain.addDiagnosticFromAST(currentIndexer.getDeclarations()[0].ast(), TypeScript.DiagnosticCode.Duplicate_string_index_signature, null, [this.semanticInfoChain.locationFromAST(firstStringIndexer.getDeclarations()[0].ast())]); + return; + } else { + firstStringIndexer = currentIndexer; + } + } else if (currentParameterType === this.semanticInfoChain.numberTypeSymbol) { + if (firstNumberIndexer) { + this.semanticInfoChain.addDiagnosticFromAST(currentIndexer.getDeclarations()[0].ast(), TypeScript.DiagnosticCode.Duplicate_number_index_signature, null, [this.semanticInfoChain.locationFromAST(firstNumberIndexer.getDeclarations()[0].ast())]); + return; + } else { + firstNumberIndexer = currentIndexer; + } + } + } + }; + + PullTypeResolver.prototype.filterSymbol = function (symbol, kind, enclosingDecl, context) { + if (symbol) { + if (symbol.kind & kind) { + return symbol; + } + + if (symbol.isAlias()) { + this.resolveDeclaredSymbol(symbol, context); + + var alias = symbol; + if (kind & 164 /* SomeContainer */) { + return alias.getExportAssignedContainerSymbol(); + } else if (kind & 58728795 /* SomeType */) { + return alias.getExportAssignedTypeSymbol(); + } else if (kind & 68147712 /* SomeValue */) { + return alias.getExportAssignedValueSymbol(); + } + } + } + return null; + }; + + PullTypeResolver.prototype.getMemberSymbolOfKind = function (symbolName, kind, pullTypeSymbol, enclosingDecl, context) { + var memberSymbol = this.getNamedPropertySymbol(symbolName, kind, pullTypeSymbol); + + return { + symbol: this.filterSymbol(memberSymbol, kind, enclosingDecl, context), + aliasSymbol: memberSymbol && memberSymbol.isAlias() ? memberSymbol : null + }; + }; + + PullTypeResolver.prototype.resolveIdentifierOfInternalModuleReference = function (importDecl, identifier, moduleSymbol, enclosingDecl, context) { + var rhsName = identifier.valueText(); + if (rhsName.length === 0) { + return null; + } + + var moduleTypeSymbol = moduleSymbol.type; + var memberSymbol = this.getMemberSymbolOfKind(rhsName, 164 /* SomeContainer */, moduleTypeSymbol, enclosingDecl, context); + var containerSymbol = memberSymbol.symbol; + var valueSymbol = null; + var typeSymbol = null; + var aliasSymbol = null; + + var acceptableAlias = true; + + if (containerSymbol) { + acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) !== 0; + aliasSymbol = memberSymbol.aliasSymbol; + } + + if (!acceptableAlias && containerSymbol && containerSymbol.kind === 128 /* TypeAlias */) { + this.resolveDeclaredSymbol(containerSymbol, context); + var aliasedAssignedValue = containerSymbol.getExportAssignedValueSymbol(); + var aliasedAssignedType = containerSymbol.getExportAssignedTypeSymbol(); + var aliasedAssignedContainer = containerSymbol.getExportAssignedContainerSymbol(); + + if (aliasedAssignedValue || aliasedAssignedType || aliasedAssignedContainer) { + aliasSymbol = containerSymbol; + valueSymbol = aliasedAssignedValue; + typeSymbol = aliasedAssignedType; + containerSymbol = aliasedAssignedContainer; + acceptableAlias = true; + } + } + + if (!acceptableAlias) { + this.semanticInfoChain.addDiagnosticFromAST(identifier, TypeScript.DiagnosticCode.Import_declaration_referencing_identifier_from_internal_module_can_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules); + return null; + } + + if (!valueSymbol) { + if (moduleTypeSymbol.getInstanceSymbol()) { + memberSymbol = this.getMemberSymbolOfKind(rhsName, 68147712 /* SomeValue */, moduleTypeSymbol.getInstanceSymbol().type, enclosingDecl, context); + valueSymbol = memberSymbol.symbol; + if (valueSymbol && memberSymbol.aliasSymbol) { + aliasSymbol = memberSymbol.aliasSymbol; + } + } + } + + if (!typeSymbol) { + memberSymbol = this.getMemberSymbolOfKind(rhsName, 58728795 /* SomeType */, moduleTypeSymbol, enclosingDecl, context); + typeSymbol = memberSymbol.symbol; + if (typeSymbol && memberSymbol.aliasSymbol) { + aliasSymbol = memberSymbol.aliasSymbol; + } + } + + if (!valueSymbol && !typeSymbol && !containerSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(identifier, TypeScript.DiagnosticCode.Could_not_find_symbol_0_in_module_1, [rhsName, moduleSymbol.toString()]); + return null; + } + + if (!typeSymbol && containerSymbol) { + typeSymbol = containerSymbol; + } + + return { + valueSymbol: valueSymbol, + typeSymbol: typeSymbol, + containerSymbol: containerSymbol, + aliasSymbol: aliasSymbol + }; + }; + + PullTypeResolver.prototype.resolveModuleReference = function (importDecl, moduleNameExpr, enclosingDecl, context, declPath) { + TypeScript.Debug.assert(moduleNameExpr.kind() === 121 /* QualifiedName */ || moduleNameExpr.kind() === 11 /* IdentifierName */ || moduleNameExpr.kind() === 14 /* StringLiteral */, "resolving module reference should always be either name or member reference"); + + var moduleSymbol = null; + var moduleName; + + if (moduleNameExpr.kind() === 121 /* QualifiedName */) { + var dottedNameAST = moduleNameExpr; + var moduleContainer = this.resolveModuleReference(importDecl, dottedNameAST.left, enclosingDecl, context, declPath); + if (moduleContainer) { + moduleName = dottedNameAST.right.valueText(); + + moduleSymbol = this.getMemberSymbolOfKind(moduleName, 4 /* Container */, moduleContainer.type, enclosingDecl, context).symbol; + if (!moduleSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(dottedNameAST.right, TypeScript.DiagnosticCode.Could_not_find_module_0_in_module_1, [moduleName, moduleContainer.toString()]); + } + } + } else { + var valueText = moduleNameExpr.kind() === 11 /* IdentifierName */ ? moduleNameExpr.valueText() : moduleNameExpr.valueText(); + var text = moduleNameExpr.kind() === 11 /* IdentifierName */ ? moduleNameExpr.text() : moduleNameExpr.text(); + + if (text.length > 0) { + var resolvedModuleNameSymbol = this.getSymbolFromDeclPath(valueText, declPath, 4 /* Container */); + moduleSymbol = this.filterSymbol(resolvedModuleNameSymbol, 4 /* Container */, enclosingDecl, context); + if (moduleSymbol) { + this.semanticInfoChain.setSymbolForAST(moduleNameExpr, moduleSymbol); + if (resolvedModuleNameSymbol.isAlias()) { + this.semanticInfoChain.setAliasSymbolForAST(moduleNameExpr, resolvedModuleNameSymbol); + var importDeclSymbol = importDecl.getSymbol(); + importDeclSymbol.addLinkedAliasSymbol(resolvedModuleNameSymbol); + } + } else { + this.semanticInfoChain.addDiagnosticFromAST(moduleNameExpr, TypeScript.DiagnosticCode.Unable_to_resolve_module_reference_0, [valueText]); + } + } + } + + return moduleSymbol; + }; + + PullTypeResolver.prototype.resolveInternalModuleReference = function (importStatementAST, context) { + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var enclosingDecl = this.getEnclosingDecl(importDecl); + + var moduleReference = importStatementAST.moduleReference; + + var aliasExpr = moduleReference.kind() === 245 /* ExternalModuleReference */ ? moduleReference.stringLiteral : moduleReference.moduleName; + + var declPath = enclosingDecl.getParentPath(); + var aliasedType = null; + var importDeclSymbol = importDecl.getSymbol(); + + if (aliasExpr.kind() === 11 /* IdentifierName */ || aliasExpr.kind() === 14 /* StringLiteral */) { + var moduleSymbol = this.resolveModuleReference(importDecl, aliasExpr, enclosingDecl, context, declPath); + if (moduleSymbol) { + aliasedType = moduleSymbol.type; + this.semanticInfoChain.setAliasSymbolForAST(moduleReference, this.semanticInfoChain.getAliasSymbolForAST(aliasExpr)); + if (aliasedType.anyDeclHasFlag(32768 /* InitializedModule */)) { + var moduleName = aliasExpr.kind() === 11 /* IdentifierName */ ? aliasExpr.valueText() : aliasExpr.valueText(); + var valueSymbol = this.getSymbolFromDeclPath(moduleName, declPath, 68147712 /* SomeValue */); + var instanceSymbol = aliasedType.getInstanceSymbol(); + + if (valueSymbol && (instanceSymbol != valueSymbol || valueSymbol.type === aliasedType)) { + var text = aliasExpr.kind() === 11 /* IdentifierName */ ? aliasExpr.text() : aliasExpr.text(); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(aliasExpr, TypeScript.DiagnosticCode.Internal_module_reference_0_in_import_declaration_does_not_reference_module_instance_for_1, [text, moduleSymbol.type.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + } else { + importDeclSymbol.setAssignedValueSymbol(valueSymbol); + } + } + } else { + aliasedType = this.getNewErrorTypeSymbol(); + } + } else if (aliasExpr.kind() === 121 /* QualifiedName */) { + var dottedNameAST = aliasExpr; + var moduleSymbol = this.resolveModuleReference(importDecl, dottedNameAST.left, enclosingDecl, context, declPath); + if (moduleSymbol) { + var identifierResolution = this.resolveIdentifierOfInternalModuleReference(importDecl, dottedNameAST.right, moduleSymbol, enclosingDecl, context); + if (identifierResolution) { + importDeclSymbol.setAssignedValueSymbol(identifierResolution.valueSymbol); + importDeclSymbol.setAssignedTypeSymbol(identifierResolution.typeSymbol); + importDeclSymbol.setAssignedContainerSymbol(identifierResolution.containerSymbol); + this.semanticInfoChain.setAliasSymbolForAST(moduleReference, identifierResolution.aliasSymbol); + return null; + } + } + } + + if (!aliasedType) { + importDeclSymbol.setAssignedTypeSymbol(this.getNewErrorTypeSymbol()); + } + + return aliasedType; + }; + + PullTypeResolver.prototype.resolveImportDeclaration = function (importStatementAST, context) { + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var enclosingDecl = this.getEnclosingDecl(importDecl); + var importDeclSymbol = importDecl.getSymbol(); + + var aliasedType = null; + + if (importDeclSymbol.isResolved) { + return importDeclSymbol; + } + + importDeclSymbol.startResolving(); + + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + var modPath = importStatementAST.moduleReference.stringLiteral.valueText(); + var declPath = enclosingDecl.getParentPath(); + + aliasedType = this.resolveExternalModuleReference(modPath, importDecl.fileName()); + + if (!aliasedType) { + var path = importStatementAST.moduleReference.stringLiteral.text(); + this.semanticInfoChain.addDiagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Unable_to_resolve_external_module_0, [path]); + aliasedType = this.getNewErrorTypeSymbol(); + } + } else { + aliasedType = this.resolveInternalModuleReference(importStatementAST, context); + } + + if (aliasedType) { + if (!aliasedType.isContainer()) { + this.semanticInfoChain.addDiagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Module_cannot_be_aliased_to_a_non_module_type); + if (!aliasedType.isError()) { + aliasedType = this.getNewErrorTypeSymbol(); + } + } + + if (aliasedType.isContainer()) { + importDeclSymbol.setAssignedContainerSymbol(aliasedType); + } + importDeclSymbol.setAssignedTypeSymbol(aliasedType); + + this.setSymbolForAST(importStatementAST.moduleReference, aliasedType, null); + } + + importDeclSymbol.setResolved(); + + this.resolveDeclaredSymbol(importDeclSymbol.assignedValue(), context); + this.resolveDeclaredSymbol(importDeclSymbol.assignedType(), context); + this.resolveDeclaredSymbol(importDeclSymbol.assignedContainer(), context); + + if (aliasedType && importDeclSymbol.anyDeclHasFlag(1 /* Exported */)) { + importDeclSymbol.setIsUsedInExportedAlias(); + + if (aliasedType.isContainer() && aliasedType.getExportAssignedValueSymbol()) { + importDeclSymbol.setIsUsedAsValue(); + } + } + + if (this.canTypeCheckAST(importStatementAST, context)) { + this.typeCheckImportDeclaration(importStatementAST, context); + } + + return importDeclSymbol; + }; + + PullTypeResolver.prototype.typeCheckImportDeclaration = function (importStatementAST, context) { + var _this = this; + this.setTypeChecked(importStatementAST, context); + + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var enclosingDecl = this.getEnclosingDecl(importDecl); + var importDeclSymbol = importDecl.getSymbol(); + + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + if (this.compilationSettings.noResolve()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Import_declaration_cannot_refer_to_external_module_reference_when_noResolve_option_is_set, null)); + } + + var modPath = importStatementAST.moduleReference.stringLiteral.valueText(); + if (enclosingDecl.kind === 32 /* DynamicModule */) { + var ast = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(this.getASTForDecl(enclosingDecl)); + if (ast && ast.kind() === 130 /* ModuleDeclaration */) { + if (TypeScript.isRelative(modPath)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(importStatementAST, TypeScript.DiagnosticCode.Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name)); + } + } + } + } + + var checkPrivacy; + if (importStatementAST.moduleReference.kind() === 245 /* ExternalModuleReference */) { + var containerSymbol = importDeclSymbol.getExportAssignedContainerSymbol(); + var container = containerSymbol ? containerSymbol.getContainer() : null; + if (container && container.kind === 32 /* DynamicModule */) { + checkPrivacy = true; + } + } else { + checkPrivacy = true; + } + + if (checkPrivacy) { + var typeSymbol = importDeclSymbol.getExportAssignedTypeSymbol(); + var containerSymbol = importDeclSymbol.getExportAssignedContainerSymbol(); + var valueSymbol = importDeclSymbol.getExportAssignedValueSymbol(); + + this.checkSymbolPrivacy(importDeclSymbol, containerSymbol, function (symbol) { + var messageCode = TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_container_that_is_or_is_using_inaccessible_module_1; + var messageArguments = [importDeclSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null), symbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null, false, false, true)]; + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(importStatementAST, messageCode, messageArguments)); + }); + + if (typeSymbol !== containerSymbol) { + this.checkSymbolPrivacy(importDeclSymbol, typeSymbol, function (symbol) { + var messageCode = symbol.isContainer() && !symbol.isEnum() ? TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_type_that_is_using_inaccessible_module_1 : TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_type_that_has_or_is_using_private_type_1; + + var messageArguments = [importDeclSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null), symbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null, false, false, true)]; + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(importStatementAST, messageCode, messageArguments)); + }); + } + + if (valueSymbol) { + this.checkSymbolPrivacy(importDeclSymbol, valueSymbol.type, function (symbol) { + var messageCode = symbol.isContainer() && !symbol.isEnum() ? TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_value_with_type_that_is_using_inaccessible_module_1 : TypeScript.DiagnosticCode.Exported_import_declaration_0_is_assigned_value_with_type_that_has_or_is_using_private_type_1; + var messageArguments = [importDeclSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null), symbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null, false, false, true)]; + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(importStatementAST, messageCode, messageArguments)); + }); + } + } + + this.checkNameForCompilerGeneratedDeclarationCollision(importStatementAST, true, importStatementAST.identifier, context); + }; + + PullTypeResolver.prototype.postTypeCheckImportDeclaration = function (importStatementAST, context) { + var importDecl = this.semanticInfoChain.getDeclForAST(importStatementAST); + var importSymbol = importDecl.getSymbol(); + + var isUsedAsValue = importSymbol.isUsedAsValue(); + var hasAssignedValue = importStatementAST.moduleReference.kind() !== 245 /* ExternalModuleReference */ && importSymbol.getExportAssignedValueSymbol() !== null; + + if (isUsedAsValue || hasAssignedValue) { + this.checkThisCaptureVariableCollides(importStatementAST, true, context); + } + }; + + PullTypeResolver.prototype.resolveExportAssignmentStatement = function (exportAssignmentAST, context) { + var id = exportAssignmentAST.identifier.valueText(); + if (id.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var valueSymbol = null; + var typeSymbol = null; + var containerSymbol = null; + + var enclosingDecl = this.getEnclosingDeclForAST(exportAssignmentAST); + var parentSymbol = enclosingDecl.getSymbol(); + + if (!parentSymbol.isType() && parentSymbol.isContainer()) { + this.semanticInfoChain.addDiagnosticFromAST(exportAssignmentAST, TypeScript.DiagnosticCode.Export_assignments_may_only_be_used_at_the_top_level_of_external_modules); + return this.semanticInfoChain.anyTypeSymbol; + } + + var declPath = enclosingDecl !== null ? [enclosingDecl] : []; + + containerSymbol = this.getSymbolFromDeclPath(id, declPath, 164 /* SomeContainer */); + + var acceptableAlias = true; + + if (containerSymbol) { + acceptableAlias = (containerSymbol.kind & 59753052 /* AcceptableAlias */) !== 0; + } + + if (!acceptableAlias && containerSymbol && containerSymbol.kind === 128 /* TypeAlias */) { + this.resolveDeclaredSymbol(containerSymbol, context); + + var aliasSymbol = containerSymbol; + var aliasedAssignedValue = aliasSymbol.getExportAssignedValueSymbol(); + var aliasedAssignedType = aliasSymbol.getExportAssignedTypeSymbol(); + var aliasedAssignedContainer = aliasSymbol.getExportAssignedContainerSymbol(); + + if (aliasedAssignedValue || aliasedAssignedType || aliasedAssignedContainer) { + valueSymbol = aliasedAssignedValue; + typeSymbol = aliasedAssignedType; + containerSymbol = aliasedAssignedContainer; + aliasSymbol.setTypeUsedExternally(); + if (valueSymbol) { + aliasSymbol.setIsUsedAsValue(); + } + acceptableAlias = true; + } + } + + if (!acceptableAlias) { + this.semanticInfoChain.addDiagnosticFromAST(exportAssignmentAST, TypeScript.DiagnosticCode.Export_assignments_may_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules); + return this.semanticInfoChain.voidTypeSymbol; + } + + if (!valueSymbol) { + valueSymbol = this.getSymbolFromDeclPath(id, declPath, 68147712 /* SomeValue */); + } + if (!typeSymbol) { + typeSymbol = this.getSymbolFromDeclPath(id, declPath, 58728795 /* SomeType */); + } + + if (!valueSymbol && !typeSymbol && !containerSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(exportAssignmentAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [id])); + return this.semanticInfoChain.voidTypeSymbol; + } + + if (valueSymbol) { + parentSymbol.setExportAssignedValueSymbol(valueSymbol); + } + if (typeSymbol) { + parentSymbol.setExportAssignedTypeSymbol(typeSymbol); + } + if (containerSymbol) { + parentSymbol.setExportAssignedContainerSymbol(containerSymbol); + } + + this.resolveDeclaredSymbol(valueSymbol, context); + this.resolveDeclaredSymbol(typeSymbol, context); + this.resolveDeclaredSymbol(containerSymbol, context); + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveAnyFunctionTypeSignature = function (funcDeclAST, typeParameters, parameterList, returnTypeAnnotation, context) { + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + TypeScript.Debug.assert(functionDecl); + + var funcDeclSymbol = functionDecl.getSymbol(); + + var signature = funcDeclSymbol.kind === 33554432 /* ConstructorType */ ? funcDeclSymbol.getConstructSignatures()[0] : funcDeclSymbol.getCallSignatures()[0]; + + if (returnTypeAnnotation) { + signature.returnType = this.resolveTypeReference(returnTypeAnnotation, context); + } + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + if (parameterList) { + for (var i = 0; i < parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveFunctionTypeSignatureParameter(parameterList.parameters.nonSeparatorAt(i), signature, functionDecl, context); + } + } + + funcDeclSymbol.setResolved(); + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.setTypeChecked(funcDeclAST, context); + this.typeCheckFunctionOverloads(funcDeclAST, context); + } + + return funcDeclSymbol; + }; + + PullTypeResolver.prototype.resolveFunctionTypeSignatureParameter = function (argDeclAST, signature, enclosingDecl, context) { + var paramDecl = this.semanticInfoChain.getDeclForAST(argDeclAST); + var paramSymbol = paramDecl.getSymbol(); + + if (argDeclAST.typeAnnotation) { + var typeRef = this.resolveTypeReference(TypeScript.ASTHelpers.getType(argDeclAST), context); + + if (paramSymbol.isVarArg && !typeRef.isArrayNamedTypeReference()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); + typeRef = this.getNewErrorTypeSymbol(); + } + + context.setTypeInContext(paramSymbol, typeRef); + } else { + if (paramSymbol.isVarArg) { + if (this.cachedArrayInterfaceType()) { + context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [this.semanticInfoChain.anyTypeSymbol])); + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_function_type_implicitly_has_an_any_type, [argDeclAST.identifier.text()])); + } + } + + if (TypeScript.hasFlag(paramDecl.flags, 128 /* Optional */) && argDeclAST.equalsValueClause && isTypesOnlyLocation(argDeclAST)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Default_arguments_are_only_allowed_in_implementation)); + } + + paramSymbol.setResolved(); + }; + + PullTypeResolver.prototype.resolveFunctionExpressionParameter = function (argDeclAST, id, typeExpr, equalsValueClause, contextParam, enclosingDecl, context) { + var paramDecl = this.semanticInfoChain.getDeclForAST(argDeclAST); + var paramSymbol = paramDecl.getSymbol(); + var contextualType = contextParam && contextParam.type; + var isImplicitAny = false; + + if (typeExpr) { + var typeRef = this.resolveTypeReference(typeExpr, context); + + if (paramSymbol.isVarArg && !typeRef.isArrayNamedTypeReference()) { + var diagnostic = context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); + typeRef = this.getNewErrorTypeSymbol(); + } + + contextualType = typeRef || contextualType; + } + if (contextualType) { + if (context.isInferentiallyTyping()) { + contextualType = context.fixAllTypeParametersReferencedByType(contextualType, this); + } + context.setTypeInContext(paramSymbol, contextualType); + } else if (paramSymbol.isVarArg) { + if (this.cachedArrayInterfaceType()) { + context.setTypeInContext(paramSymbol, this.createInstantiatedType(this.cachedArrayInterfaceType(), [this.semanticInfoChain.anyTypeSymbol])); + } else { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + } + isImplicitAny = true; + } + + var canTypeCheckAST = this.canTypeCheckAST(argDeclAST, context); + if (equalsValueClause && (canTypeCheckAST || !contextualType)) { + if (contextualType) { + context.propagateContextualType(contextualType); + } + + var initExprSymbol = this.resolveAST(equalsValueClause, contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + } + + if (!initExprSymbol || !initExprSymbol.type) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Unable_to_resolve_type_of_0, [id.text()])); + + if (!contextualType) { + context.setTypeInContext(paramSymbol, this.getNewErrorTypeSymbol(paramSymbol.name)); + } + } else { + var initTypeSymbol = this.getInstanceTypeForAssignment(argDeclAST, initExprSymbol.type, context); + if (!contextualType) { + context.setTypeInContext(paramSymbol, initTypeSymbol.widenedType(this, equalsValueClause, context)); + isImplicitAny = initTypeSymbol !== paramSymbol.type; + } else { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(initTypeSymbol, contextualType, argDeclAST, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(argDeclAST); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [initTypeSymbol.toString(enclosingSymbol), contextualType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [initTypeSymbol.toString(enclosingSymbol), contextualType.toString(enclosingSymbol)])); + } + } + } + } + } + + if (!contextualType && !paramSymbol.isVarArg && !initTypeSymbol) { + context.setTypeInContext(paramSymbol, this.semanticInfoChain.anyTypeSymbol); + isImplicitAny = true; + } + + if (isImplicitAny && this.compilationSettings.noImplicitAny()) { + var functionExpressionName = paramDecl.getParentDecl().getFunctionExpressionName(); + if (functionExpressionName) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [id.text(), functionExpressionName])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(argDeclAST, TypeScript.DiagnosticCode.Parameter_0_of_lambda_function_implicitly_has_an_any_type, [id.text()])); + } + } + + if (canTypeCheckAST) { + this.checkNameForCompilerGeneratedDeclarationCollision(argDeclAST, true, id, context); + } + + paramSymbol.setResolved(); + }; + + PullTypeResolver.prototype.checkNameForCompilerGeneratedDeclarationCollision = function (astWithName, isDeclaration, name, context) { + var compilerReservedName = getCompilerReservedName(name); + switch (compilerReservedName) { + case 1 /* _this */: + this.postTypeCheckWorkitems.push(astWithName); + return; + + case 2 /* _super */: + this.checkSuperCaptureVariableCollides(astWithName, isDeclaration, context); + return; + + case 3 /* arguments */: + this.checkArgumentsCollides(astWithName, context); + return; + + case 4 /* _i */: + this.checkIndexOfRestArgumentInitializationCollides(astWithName, isDeclaration, context); + return; + + case 5 /* require */: + case 6 /* exports */: + if (isDeclaration) { + this.checkExternalModuleRequireExportsCollides(astWithName, name, context); + } + return; + } + }; + + PullTypeResolver.prototype.hasRestParameterCodeGen = function (someFunctionDecl) { + var enclosingAST = this.getASTForDecl(someFunctionDecl); + var nodeType = enclosingAST.kind(); + + if (nodeType === 129 /* FunctionDeclaration */) { + var functionDeclaration = enclosingAST; + return !TypeScript.hasFlag(someFunctionDecl.kind === 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && functionDeclaration.block && TypeScript.lastParameterIsRest(functionDeclaration.callSignature.parameterList); + } else if (nodeType === 135 /* MemberFunctionDeclaration */) { + var memberFunction = enclosingAST; + return !TypeScript.hasFlag(someFunctionDecl.kind === 65536 /* Method */ ? someFunctionDecl.getParentDecl().flags : someFunctionDecl.flags, 8 /* Ambient */) && memberFunction.block && TypeScript.lastParameterIsRest(memberFunction.callSignature.parameterList); + } else if (nodeType === 137 /* ConstructorDeclaration */) { + var constructorDeclaration = enclosingAST; + return !TypeScript.hasFlag(someFunctionDecl.getParentDecl().flags, 8 /* Ambient */) && constructorDeclaration.block && TypeScript.lastParameterIsRest(constructorDeclaration.callSignature.parameterList); + } else if (nodeType === 218 /* ParenthesizedArrowFunctionExpression */) { + var arrowFunctionExpression = enclosingAST; + return TypeScript.lastParameterIsRest(arrowFunctionExpression.callSignature.parameterList); + } else if (nodeType === 222 /* FunctionExpression */) { + var functionExpression = enclosingAST; + return TypeScript.lastParameterIsRest(functionExpression.callSignature.parameterList); + } + + return false; + }; + + PullTypeResolver.prototype.checkArgumentsCollides = function (ast, context) { + if (ast.kind() === 242 /* Parameter */) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + if (TypeScript.hasFlag(enclosingDecl.kind, 1032192 /* SomeFunction */)) { + if (this.hasRestParameterCodeGen(enclosingDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters)); + } + } + } + }; + + PullTypeResolver.prototype.checkIndexOfRestArgumentInitializationCollides = function (ast, isDeclaration, context) { + if (!isDeclaration || ast.kind() === 242 /* Parameter */) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + var declPath = isDeclaration ? [enclosingDecl] : (enclosingDecl ? enclosingDecl.getParentPath() : []); + var resolvedSymbol = null; + var resolvedSymbolContainer; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + if (!isDeclaration) { + if (!resolvedSymbol) { + resolvedSymbol = this.resolveNameExpression(ast, context); + if (resolvedSymbol.isError()) { + return; + } + + resolvedSymbolContainer = resolvedSymbol.getContainer(); + } + + if (resolvedSymbolContainer && TypeScript.ArrayUtilities.contains(resolvedSymbolContainer.getDeclarations(), decl)) { + break; + } + } + + if (TypeScript.hasFlag(decl.kind, 1032192 /* SomeFunction */)) { + if (this.hasRestParameterCodeGen(decl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, isDeclaration ? TypeScript.DiagnosticCode.Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter : TypeScript.DiagnosticCode.Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter)); + } + } + } + } + }; + + PullTypeResolver.prototype.checkExternalModuleRequireExportsCollides = function (ast, name, context) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(name); + if (enclosingModule) { + enclosingDecl = this.getEnclosingDeclForAST(enclosingModule); + } + + if (enclosingDecl && enclosingDecl.kind === 32 /* DynamicModule */) { + var decl = this.semanticInfoChain.getDeclForAST(ast); + + if (!TypeScript.hasFlag(decl.flags, 8 /* Ambient */)) { + var nameText = name.valueText(); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module, [nameText, nameText])); + } + } + }; + + PullTypeResolver.prototype.resolveObjectTypeTypeReference = function (objectType, context) { + var interfaceDecl = this.semanticInfoChain.getDeclForAST(objectType); + TypeScript.Debug.assert(interfaceDecl); + + var interfaceSymbol = interfaceDecl.getSymbol(); + TypeScript.Debug.assert(interfaceSymbol); + + if (objectType.typeMembers) { + var memberDecl = null; + var memberSymbol = null; + var memberType = null; + var typeMembers = objectType.typeMembers; + + for (var i = 0; i < typeMembers.nonSeparatorCount(); i++) { + memberDecl = this.semanticInfoChain.getDeclForAST(typeMembers.nonSeparatorAt(i)); + memberSymbol = (memberDecl.kind & 7340032 /* SomeSignature */) ? memberDecl.getSignatureSymbol() : memberDecl.getSymbol(); + + this.resolveAST(typeMembers.nonSeparatorAt(i), false, context); + + memberType = memberSymbol.type; + + if ((memberType && memberType.isGeneric()) || (memberSymbol.isSignature() && memberSymbol.isGeneric())) { + interfaceSymbol.setHasGenericMember(); + } + } + } + + interfaceSymbol.setResolved(); + + if (this.canTypeCheckAST(objectType, context)) { + this.typeCheckObjectTypeTypeReference(objectType, context); + } + + return interfaceSymbol; + }; + + PullTypeResolver.prototype.typeCheckObjectTypeTypeReference = function (objectType, context) { + this.setTypeChecked(objectType, context); + var objectTypeDecl = this.semanticInfoChain.getDeclForAST(objectType); + var objectTypeSymbol = objectTypeDecl.getSymbol(); + + this.typeCheckMembersAgainstIndexer(objectTypeSymbol, objectTypeDecl, context); + this.checkTypeForDuplicateIndexSignatures(objectTypeSymbol); + }; + + PullTypeResolver.prototype.resolveTypeAnnotation = function (typeAnnotation, context) { + return this.resolveTypeReference(typeAnnotation.type, context); + }; + + PullTypeResolver.prototype.resolveTypeReference = function (typeRef, context) { + if (typeRef === null) { + return null; + } + + TypeScript.Debug.assert(typeRef.kind() !== 244 /* TypeAnnotation */); + + var aliasType = null; + var type = this.computeTypeReferenceSymbol(typeRef, context); + + if (type.kind === 4 /* Container */) { + var container = type; + var instanceSymbol = container.getInstanceSymbol(); + + if (instanceSymbol && (instanceSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */) || instanceSymbol.kind === 32768 /* ConstructorMethod */)) { + type = instanceSymbol.type.getAssociatedContainerType(); + } + } + + if (type && type.isAlias()) { + aliasType = type; + type = aliasType.getExportAssignedTypeSymbol(); + } + + if (type && !type.isGeneric()) { + if (aliasType) { + this.semanticInfoChain.setAliasSymbolForAST(typeRef, aliasType); + } + } + + if (type && !type.isError()) { + if ((type.kind & 58728795 /* SomeType */) === 0) { + if (type.kind & 164 /* SomeContainer */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeRef, TypeScript.DiagnosticCode.Type_reference_cannot_refer_to_container_0, [aliasType ? aliasType.toString() : type.toString()])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeRef, TypeScript.DiagnosticCode.Type_reference_must_refer_to_type)); + } + } + } + + if (this.canTypeCheckAST(typeRef, context)) { + this.setTypeChecked(typeRef, context); + } + + return type; + }; + + PullTypeResolver.prototype.getArrayType = function (elementType) { + var arraySymbol = elementType.getArrayType(); + + if (!arraySymbol) { + arraySymbol = this.createInstantiatedType(this.cachedArrayInterfaceType(), [elementType]); + + if (!arraySymbol) { + arraySymbol = this.semanticInfoChain.anyTypeSymbol; + } + + elementType.setArrayType(arraySymbol); + } + + return arraySymbol; + }; + + PullTypeResolver.prototype.computeTypeReferenceSymbol = function (term, context) { + switch (term.kind()) { + case 60 /* AnyKeyword */: + return this.semanticInfoChain.anyTypeSymbol; + case 61 /* BooleanKeyword */: + return this.semanticInfoChain.booleanTypeSymbol; + case 67 /* NumberKeyword */: + return this.semanticInfoChain.numberTypeSymbol; + case 69 /* StringKeyword */: + return this.semanticInfoChain.stringTypeSymbol; + case 41 /* VoidKeyword */: + return this.semanticInfoChain.voidTypeSymbol; + } + + var typeDeclSymbol = null; + + if (term.kind() === 11 /* IdentifierName */) { + typeDeclSymbol = this.resolveTypeNameExpression(term, context); + } else if (term.kind() === 123 /* FunctionType */) { + var functionType = term; + typeDeclSymbol = this.resolveAnyFunctionTypeSignature(functionType, functionType.typeParameterList, functionType.parameterList, functionType.type, context); + } else if (term.kind() === 125 /* ConstructorType */) { + var constructorType = term; + typeDeclSymbol = this.resolveAnyFunctionTypeSignature(constructorType, constructorType.typeParameterList, constructorType.parameterList, constructorType.type, context); + } else if (term.kind() === 122 /* ObjectType */) { + typeDeclSymbol = this.resolveObjectTypeTypeReference(term, context); + } else if (term.kind() === 126 /* GenericType */) { + typeDeclSymbol = this.resolveGenericTypeReference(term, context); + } else if (term.kind() === 121 /* QualifiedName */) { + typeDeclSymbol = this.resolveQualifiedName(term, context); + } else if (term.kind() === 14 /* StringLiteral */) { + var stringConstantAST = term; + var enclosingDecl = this.getEnclosingDeclForAST(term); + typeDeclSymbol = new TypeScript.PullStringConstantTypeSymbol(stringConstantAST.text()); + var decl = new TypeScript.PullSynthesizedDecl(stringConstantAST.text(), stringConstantAST.text(), typeDeclSymbol.kind, null, enclosingDecl, enclosingDecl.semanticInfoChain); + typeDeclSymbol.addDeclaration(decl); + } else if (term.kind() === 127 /* TypeQuery */) { + var typeQuery = term; + + var typeQueryTerm = typeQuery.name; + + var valueSymbol = this.resolveAST(typeQueryTerm, false, context); + + if (valueSymbol && valueSymbol.isAlias()) { + if (valueSymbol.assignedValue()) { + valueSymbol = valueSymbol.assignedValue(); + } else { + var containerSymbol = valueSymbol.getExportAssignedContainerSymbol(); + valueSymbol = (containerSymbol && containerSymbol.isContainer() && !containerSymbol.isEnum()) ? containerSymbol.getInstanceSymbol() : null; + } + } + + if (valueSymbol) { + typeDeclSymbol = valueSymbol.type.widenedType(this, typeQueryTerm, context); + } else { + typeDeclSymbol = this.getNewErrorTypeSymbol(); + } + } else if (term.kind() === 124 /* ArrayType */) { + var arrayType = term; + var underlying = this.resolveTypeReference(arrayType.type, context); + typeDeclSymbol = this.getArrayType(underlying); + } else { + throw TypeScript.Errors.invalidOperation("unknown type"); + } + + if (!typeDeclSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(term, TypeScript.DiagnosticCode.Unable_to_resolve_type)); + return this.getNewErrorTypeSymbol(); + } + + if (typeDeclSymbol.isError()) { + return typeDeclSymbol; + } + + if (this.genericTypeIsUsedWithoutRequiredTypeArguments(typeDeclSymbol, term, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(term, TypeScript.DiagnosticCode.Generic_type_references_must_include_all_type_arguments)); + typeDeclSymbol = this.instantiateTypeToAny(typeDeclSymbol, context); + } + + return typeDeclSymbol; + }; + + PullTypeResolver.prototype.genericTypeIsUsedWithoutRequiredTypeArguments = function (typeSymbol, term, context) { + if (!typeSymbol) { + return false; + } + + if (typeSymbol.isAlias()) { + return this.genericTypeIsUsedWithoutRequiredTypeArguments(typeSymbol.getExportAssignedTypeSymbol(), term, context); + } + + return typeSymbol.isNamedTypeSymbol() && typeSymbol.isGeneric() && !typeSymbol.isTypeParameter() && (typeSymbol.isResolved || typeSymbol.inResolution) && !typeSymbol.getIsSpecialized() && typeSymbol.getTypeParameters().length && typeSymbol.getTypeArguments() === null && this.isTypeRefWithoutTypeArgs(term); + }; + + PullTypeResolver.prototype.resolveMemberVariableDeclaration = function (varDecl, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.ASTHelpers.getType(varDecl.variableDeclarator), varDecl.variableDeclarator.equalsValueClause, context); + }; + + PullTypeResolver.prototype.resolvePropertySignature = function (varDecl, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), null, context); + }; + + PullTypeResolver.prototype.resolveVariableDeclarator = function (varDecl, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.equalsValueClause, context); + }; + + PullTypeResolver.prototype.resolveParameterList = function (list, context) { + return this.resolveSeparatedList(list.parameters, context); + }; + + PullTypeResolver.prototype.resolveParameter = function (parameter, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.ASTHelpers.getType(parameter), parameter.equalsValueClause, context); + }; + + PullTypeResolver.prototype.getEnumTypeSymbol = function (enumElement, context) { + var enumDeclaration = enumElement.parent.parent; + var decl = this.semanticInfoChain.getDeclForAST(enumDeclaration); + var symbol = decl.getSymbol(); + this.resolveDeclaredSymbol(symbol, context); + + return symbol; + }; + + PullTypeResolver.prototype.resolveEnumElement = function (enumElement, context) { + return this.resolveVariableDeclaratorOrParameterOrEnumElement(enumElement, TypeScript.sentinelEmptyArray, enumElement.propertyName, null, enumElement.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckEnumElement = function (enumElement, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(enumElement, TypeScript.sentinelEmptyArray, enumElement.propertyName, null, enumElement.equalsValueClause, context); + }; + + PullTypeResolver.prototype.resolveEqualsValueClause = function (clause, isContextuallyTyped, context) { + if (this.canTypeCheckAST(clause, context)) { + this.setTypeChecked(clause, context); + } + + return this.resolveAST(clause.value, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveVariableDeclaratorOrParameterOrEnumElement = function (varDeclOrParameter, modifiers, name, typeExpr, init, context) { + var hasTypeExpr = typeExpr !== null || varDeclOrParameter.kind() === 243 /* EnumElement */; + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + + if (enclosingDecl && decl.kind === 2048 /* Parameter */) { + enclosingDecl.ensureSymbolIsBound(); + } + + var declSymbol = decl.getSymbol(); + var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; + + if (declSymbol.isResolved) { + var declType = declSymbol.type; + var valDecl = decl.getValueDecl(); + + if (valDecl) { + var valSymbol = valDecl.getSymbol(); + + if (valSymbol && !valSymbol.isResolved) { + valSymbol.type = declType; + valSymbol.setResolved(); + } + } + } else { + if (declSymbol.inResolution) { + declSymbol.type = this.semanticInfoChain.anyTypeSymbol; + declSymbol.setResolved(); + return declSymbol; + } + + if (!declSymbol.type || !declSymbol.type.isError()) { + declSymbol.startResolving(); + + var typeExprSymbol = this.resolveAndTypeCheckVariableDeclarationTypeExpr(varDeclOrParameter, name, typeExpr, context); + + if (!hasTypeExpr) { + this.resolveAndTypeCheckVariableDeclaratorOrParameterInitExpr(varDeclOrParameter, name, typeExpr, init, context, typeExprSymbol); + } + + if (!(hasTypeExpr || init)) { + var defaultType = this.semanticInfoChain.anyTypeSymbol; + + if (declSymbol.isVarArg && this.cachedArrayInterfaceType()) { + defaultType = this.createInstantiatedType(this.cachedArrayInterfaceType(), [defaultType]); + } + + context.setTypeInContext(declSymbol, defaultType); + + if (declParameterSymbol) { + declParameterSymbol.type = defaultType; + } + } + declSymbol.setResolved(); + + if (declParameterSymbol) { + declParameterSymbol.setResolved(); + } + } + } + + if (this.canTypeCheckAST(varDeclOrParameter, context)) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDeclOrParameter, modifiers, name, typeExpr, init, context); + } + + return declSymbol; + }; + + PullTypeResolver.prototype.resolveAndTypeCheckVariableDeclarationTypeExpr = function (varDeclOrParameter, name, typeExpr, context) { + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + var declSymbol = decl.getSymbol(); + var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; + + if (varDeclOrParameter.kind() === 243 /* EnumElement */) { + var result = this.getEnumTypeSymbol(varDeclOrParameter, context); + declSymbol.type = result; + return result; + } + + if (!typeExpr) { + return null; + } + + var wrapperDecl = this.getEnclosingDecl(decl); + wrapperDecl = wrapperDecl || enclosingDecl; + + var typeExprSymbol = this.resolveTypeReference(typeExpr, context); + + if (!typeExprSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Unable_to_resolve_type_of_0, [name.text()])); + declSymbol.type = this.getNewErrorTypeSymbol(); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } else if (typeExprSymbol.isError()) { + context.setTypeInContext(declSymbol, typeExprSymbol); + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, typeExprSymbol); + } + } else { + if (typeExprSymbol === this.semanticInfoChain.anyTypeSymbol) { + decl.setFlag(16777216 /* IsAnnotatedWithAny */); + } + + if (typeExprSymbol.isContainer()) { + var exportedTypeSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + + if (exportedTypeSymbol) { + typeExprSymbol = exportedTypeSymbol; + } else { + typeExprSymbol = typeExprSymbol.type; + + if (typeExprSymbol.isAlias()) { + typeExprSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + } + + if (typeExprSymbol && typeExprSymbol.isContainer() && !typeExprSymbol.isEnum()) { + var instanceSymbol = typeExprSymbol.getInstanceSymbol(); + + if (!instanceSymbol || !TypeScript.PullHelpers.symbolIsEnum(instanceSymbol)) { + typeExprSymbol = this.getNewErrorTypeSymbol(); + } else { + typeExprSymbol = instanceSymbol.type; + } + } + } + } else if (declSymbol.isVarArg && !(typeExprSymbol.isArrayNamedTypeReference() || typeExprSymbol === this.cachedArrayInterfaceType())) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Rest_parameters_must_be_array_types)); + typeExprSymbol = this.getNewErrorTypeSymbol(); + } + + context.setTypeInContext(declSymbol, typeExprSymbol); + + if (declParameterSymbol) { + declParameterSymbol.type = typeExprSymbol; + } + + if (typeExprSymbol.kind === 16777216 /* FunctionType */ && !typeExprSymbol.getFunctionSymbol()) { + typeExprSymbol.setFunctionSymbol(declSymbol); + } + } + + return typeExprSymbol; + }; + + PullTypeResolver.prototype.resolveAndTypeCheckVariableDeclaratorOrParameterInitExpr = function (varDeclOrParameter, name, typeExpr, init, context, typeExprSymbol) { + if (!init) { + return null; + } + + var hasTypeExpr = typeExpr !== null || varDeclOrParameter.kind() === 243 /* EnumElement */; + if (typeExprSymbol) { + context.pushNewContextualType(typeExprSymbol); + } + + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + var declSymbol = decl.getSymbol(); + var declParameterSymbol = decl.getValueDecl() ? decl.getValueDecl().getSymbol() : null; + + var wrapperDecl = this.getEnclosingDecl(decl); + wrapperDecl = wrapperDecl || enclosingDecl; + + var initExprSymbol = this.resolveAST(init, typeExprSymbol !== null, context); + + if (typeExprSymbol) { + context.popAnyContextualType(); + } + + if (!initExprSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Unable_to_resolve_type_of_0, [name.text()])); + + if (!hasTypeExpr) { + context.setTypeInContext(declSymbol, this.getNewErrorTypeSymbol()); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, this.semanticInfoChain.anyTypeSymbol); + } + } + } else { + var initTypeSymbol = initExprSymbol.type; + + if (!hasTypeExpr) { + var widenedInitTypeSymbol = initTypeSymbol.widenedType(this, init.value, context); + context.setTypeInContext(declSymbol, widenedInitTypeSymbol); + + if (declParameterSymbol) { + context.setTypeInContext(declParameterSymbol, widenedInitTypeSymbol); + } + + if (this.compilationSettings.noImplicitAny()) { + if ((widenedInitTypeSymbol !== initTypeSymbol) && (widenedInitTypeSymbol === this.semanticInfoChain.anyTypeSymbol)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Variable_0_implicitly_has_an_any_type, [name.text()])); + } + } + + return widenedInitTypeSymbol; + } + } + + return initTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckPropertySignature = function (varDecl, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.sentinelEmptyArray, varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckMemberVariableDeclaration = function (varDecl, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, varDecl.modifiers, varDecl.variableDeclarator.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.variableDeclarator.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckVariableDeclarator = function (varDecl, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(varDecl, TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl), varDecl.propertyName, TypeScript.ASTHelpers.getType(varDecl), varDecl.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckParameter = function (parameter, context) { + this.typeCheckVariableDeclaratorOrParameterOrEnumElement(parameter, parameter.modifiers, parameter.identifier, TypeScript.ASTHelpers.getType(parameter), parameter.equalsValueClause, context); + }; + + PullTypeResolver.prototype.typeCheckVariableDeclaratorOrParameterOrEnumElement = function (varDeclOrParameter, modifiers, name, typeExpr, init, context) { + var _this = this; + this.setTypeChecked(varDeclOrParameter, context); + + var hasTypeExpr = typeExpr !== null || varDeclOrParameter.kind() === 243 /* EnumElement */; + var enclosingDecl = this.getEnclosingDeclForAST(varDeclOrParameter); + var decl = this.semanticInfoChain.getDeclForAST(varDeclOrParameter); + var declSymbol = decl.getSymbol(); + + var typeExprSymbol = this.resolveAndTypeCheckVariableDeclarationTypeExpr(varDeclOrParameter, name, typeExpr, context); + + var initTypeSymbol = this.resolveAndTypeCheckVariableDeclaratorOrParameterInitExpr(varDeclOrParameter, name, typeExpr, init, context, typeExprSymbol); + + if (hasTypeExpr || init) { + if (typeExprSymbol && typeExprSymbol.isAlias()) { + typeExprSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + } + + if (typeExprSymbol && typeExprSymbol.kind === 32 /* DynamicModule */) { + var exportedTypeSymbol = typeExprSymbol.getExportAssignedTypeSymbol(); + + if (exportedTypeSymbol) { + typeExprSymbol = exportedTypeSymbol; + } else { + var instanceTypeSymbol = typeExprSymbol.getInstanceType(); + + if (!instanceTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Tried_to_set_variable_type_to_uninitialized_module_type_0, [typeExprSymbol.toString()])); + typeExprSymbol = null; + } else { + typeExprSymbol = instanceTypeSymbol; + } + } + } + + initTypeSymbol = this.getInstanceTypeForAssignment(varDeclOrParameter, initTypeSymbol, context); + + if (initTypeSymbol && typeExprSymbol) { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(initTypeSymbol, typeExprSymbol, varDeclOrParameter, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(varDeclOrParameter); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [initTypeSymbol.toString(enclosingSymbol), typeExprSymbol.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [initTypeSymbol.toString(enclosingSymbol), typeExprSymbol.toString(enclosingSymbol)])); + } + } + } + } else if (varDeclOrParameter.kind() !== 243 /* EnumElement */ && this.compilationSettings.noImplicitAny() && !this.isForInVariableDeclarator(varDeclOrParameter)) { + var wrapperDecl = this.getEnclosingDecl(decl); + wrapperDecl = wrapperDecl || enclosingDecl; + + var needReportError = function (containerDecl, selfDecl) { + if (!TypeScript.hasFlag(containerDecl.flags, 8 /* Ambient */)) { + return true; + } + + return selfDecl && !TypeScript.hasFlag(selfDecl.flags, 2 /* Private */); + }; + + if ((wrapperDecl.kind === 16384 /* Function */ || wrapperDecl.kind === 32768 /* ConstructorMethod */ || wrapperDecl.kind === 2097152 /* ConstructSignature */)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [name.text(), enclosingDecl.name])); + } else if (wrapperDecl.kind === 65536 /* Method */) { + var parentDecl = wrapperDecl.getParentDecl(); + + if (needReportError(parentDecl, wrapperDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Parameter_0_of_1_implicitly_has_an_any_type, [name.text(), enclosingDecl.name])); + } + } else if (decl.kind === 4096 /* Property */ && !declSymbol.getContainer().isNamedTypeSymbol()) { + if (needReportError(wrapperDecl, decl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Member_0_of_object_type_implicitly_has_an_any_type, [name.text()])); + } + } else if (wrapperDecl.kind !== 268435456 /* CatchBlock */) { + if (needReportError(wrapperDecl) || !TypeScript.hasModifier(modifiers, 2 /* Private */)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Variable_0_implicitly_has_an_any_type, [name.text()])); + } + } + } + + if (init && varDeclOrParameter.kind() === 242 /* Parameter */) { + var containerSignature = enclosingDecl.getSignatureSymbol(); + if (containerSignature && !containerSignature.isDefinition()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(varDeclOrParameter, TypeScript.DiagnosticCode.Default_arguments_are_only_allowed_in_implementation)); + } + } + if (declSymbol.kind !== 2048 /* Parameter */ && (declSymbol.kind !== 4096 /* Property */ || declSymbol.getContainer().isNamedTypeSymbol())) { + this.checkSymbolPrivacy(declSymbol, declSymbol.type, function (symbol) { + return _this.variablePrivacyErrorReporter(varDeclOrParameter, declSymbol, symbol, context); + }); + } + + if ((declSymbol.kind !== 4096 /* Property */ && declSymbol.kind !== 67108864 /* EnumMember */) || declSymbol.anyDeclHasFlag(8388608 /* PropertyParameter */)) { + this.checkNameForCompilerGeneratedDeclarationCollision(varDeclOrParameter, true, name, context); + } + }; + + PullTypeResolver.prototype.isForInVariableDeclarator = function (ast) { + return ast.kind() === 225 /* VariableDeclarator */ && ast.parent && ast.parent.parent && ast.parent.parent.parent && ast.parent.kind() === 2 /* SeparatedList */ && ast.parent.parent.kind() === 224 /* VariableDeclaration */ && ast.parent.parent.parent.kind() === 155 /* ForInStatement */ && ast.parent.parent.parent.variableDeclaration === ast.parent.parent; + }; + + PullTypeResolver.prototype.checkSuperCaptureVariableCollides = function (superAST, isDeclaration, context) { + var enclosingDecl = this.getEnclosingDeclForAST(superAST); + + var classSymbol = this.getContextualClassSymbolForEnclosingDecl(superAST, enclosingDecl); + + if (classSymbol && !classSymbol.anyDeclHasFlag(8 /* Ambient */)) { + if (superAST.kind() === 242 /* Parameter */) { + var enclosingAST = this.getASTForDecl(enclosingDecl); + if (enclosingAST.kind() !== 218 /* ParenthesizedArrowFunctionExpression */ && enclosingAST.kind() !== 219 /* SimpleArrowFunctionExpression */) { + var block = enclosingDecl.kind === 65536 /* Method */ ? enclosingAST.block : enclosingAST.block; + if (!block) { + return; + } + } + } + + this.resolveDeclaredSymbol(classSymbol, context); + + var parents = classSymbol.getExtendedTypes(); + if (parents.length) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(superAST, isDeclaration ? TypeScript.DiagnosticCode.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference : TypeScript.DiagnosticCode.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference)); + } + } + }; + + PullTypeResolver.prototype.checkThisCaptureVariableCollides = function (_thisAST, isDeclaration, context) { + if (isDeclaration) { + var decl = this.semanticInfoChain.getDeclForAST(_thisAST); + if (TypeScript.hasFlag(decl.flags, 8 /* Ambient */)) { + return; + } + } + + var enclosingDecl = this.getEnclosingDeclForAST(_thisAST); + + var enclosingModule = TypeScript.ASTHelpers.getModuleDeclarationFromNameAST(_thisAST); + if (enclosingModule) { + enclosingDecl = this.getEnclosingDeclForAST(enclosingModule); + } + + var declPath = enclosingDecl.getParentPath(); + + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.kind; + if (declKind === 131072 /* FunctionExpression */ && TypeScript.hasFlag(decl.flags, 8192 /* ArrowFunction */)) { + continue; + } + + if (declKind === 16384 /* Function */ || declKind === 65536 /* Method */ || declKind === 32768 /* ConstructorMethod */ || declKind === 262144 /* GetAccessor */ || declKind === 524288 /* SetAccessor */ || declKind === 131072 /* FunctionExpression */ || declKind === 8 /* Class */ || declKind === 4 /* Container */ || declKind === 32 /* DynamicModule */ || declKind === 1 /* Script */) { + if (TypeScript.hasFlag(decl.flags, 262144 /* MustCaptureThis */)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(_thisAST, isDeclaration ? TypeScript.DiagnosticCode.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference : TypeScript.DiagnosticCode.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference)); + } + break; + } + } + }; + + PullTypeResolver.prototype.postTypeCheckVariableDeclaratorOrParameter = function (varDeclOrParameter, context) { + this.checkThisCaptureVariableCollides(varDeclOrParameter, true, context); + }; + + PullTypeResolver.prototype.resolveTypeParameterDeclaration = function (typeParameterAST, context) { + var typeParameterDecl = this.semanticInfoChain.getDeclForAST(typeParameterAST); + var typeParameterSymbol = typeParameterDecl.getSymbol(); + + this.resolveFirstTypeParameterDeclaration(typeParameterSymbol, context); + + if (typeParameterSymbol.isResolved && this.canTypeCheckAST(typeParameterAST, context)) { + this.typeCheckTypeParameterDeclaration(typeParameterAST, context); + } + + return typeParameterSymbol; + }; + + PullTypeResolver.prototype.resolveFirstTypeParameterDeclaration = function (typeParameterSymbol, context) { + var typeParameterDecl = typeParameterSymbol.getDeclarations()[0]; + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecl); + + if (typeParameterSymbol.isResolved || typeParameterSymbol.inResolution) { + return; + } + + typeParameterSymbol.startResolving(); + + if (typeParameterAST.constraint) { + var constraintTypeSymbol = this.resolveTypeReference(typeParameterAST.constraint.type, context); + + if (constraintTypeSymbol) { + typeParameterSymbol.setConstraint(constraintTypeSymbol); + } + } + + typeParameterSymbol.setResolved(); + }; + + PullTypeResolver.prototype.typeCheckTypeParameterDeclaration = function (typeParameterAST, context) { + this.setTypeChecked(typeParameterAST, context); + + var constraint = this.resolveAST(typeParameterAST.constraint, false, context); + + if (constraint) { + var typeParametersAST = typeParameterAST.parent; + var typeParameters = []; + for (var i = 0; i < typeParametersAST.nonSeparatorCount(); i++) { + var currentTypeParameterAST = typeParametersAST.nonSeparatorAt(i); + var currentTypeParameterDecl = this.semanticInfoChain.getDeclForAST(currentTypeParameterAST); + var currentTypeParameter = this.semanticInfoChain.getSymbolForDecl(currentTypeParameterDecl); + typeParameters[currentTypeParameter.pullSymbolID] = currentTypeParameter; + } + + if (constraint.wrapsSomeTypeParameter(typeParameters)) { + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); + } + } + }; + + PullTypeResolver.prototype.resolveConstraint = function (constraint, context) { + if (this.canTypeCheckAST(constraint, context)) { + this.setTypeChecked(constraint, context); + } + + return this.resolveTypeReference(constraint.type, context); + }; + + PullTypeResolver.prototype.resolveFunctionBodyReturnTypes = function (funcDeclAST, block, bodyExpression, signature, useContextualType, enclosingDecl, context) { + var _this = this; + var returnStatementsExpressions = []; + + var enclosingDeclStack = [enclosingDecl]; + + var preFindReturnExpressionTypes = function (ast, walker) { + var go = true; + + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 215 /* ObjectLiteralExpression */: + go = false; + break; + + case 150 /* ReturnStatement */: + var returnStatement = ast; + enclosingDecl.setFlag(4194304 /* HasReturnStatement */); + returnStatementsExpressions.push({ expression: returnStatement.expression, enclosingDecl: enclosingDeclStack[enclosingDeclStack.length - 1] }); + go = false; + break; + + case 236 /* CatchClause */: + case 163 /* WithStatement */: + enclosingDeclStack[enclosingDeclStack.length] = _this.semanticInfoChain.getDeclForAST(ast); + break; + + default: + break; + } + + walker.options.goChildren = go; + + return ast; + }; + + var postFindReturnExpressionEnclosingDecls = function (ast, walker) { + switch (ast.kind()) { + case 236 /* CatchClause */: + case 163 /* WithStatement */: + enclosingDeclStack.length--; + break; + default: + break; + } + + walker.options.goChildren = true; + + return ast; + }; + + if (block) { + TypeScript.getAstWalkerFactory().walk(block, preFindReturnExpressionTypes, postFindReturnExpressionEnclosingDecls); + } else { + returnStatementsExpressions.push({ expression: bodyExpression, enclosingDecl: enclosingDecl }); + enclosingDecl.setFlag(4194304 /* HasReturnStatement */); + } + + if (!returnStatementsExpressions.length) { + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + } else { + var returnExpressionSymbols = []; + var returnExpressions = []; + + for (var i = 0; i < returnStatementsExpressions.length; i++) { + var returnExpression = returnStatementsExpressions[i].expression; + if (returnExpression) { + var returnType = this.resolveAST(returnExpression, useContextualType, context).type; + + if (returnType.isError()) { + signature.returnType = returnType; + return; + } else { + if (returnExpression.parent.kind() === 150 /* ReturnStatement */) { + this.setSymbolForAST(returnExpression.parent, returnType, context); + } + } + + returnExpressionSymbols.push(returnType); + returnExpressions.push(returnExpression); + } + } + + if (!returnExpressionSymbols.length) { + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + } else { + var collection = { + getLength: function () { + return returnExpressionSymbols.length; + }, + getTypeAtIndex: function (index) { + return returnExpressionSymbols[index].type; + } + }; + + var bestCommonReturnType = this.findBestCommonType(collection, context, new TypeComparisonInfo()); + var returnType = bestCommonReturnType; + var returnExpression = returnExpressions[returnExpressionSymbols.indexOf(returnType)]; + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var functionSymbol = functionDecl.getSymbol(); + + if (returnType) { + var previousReturnType = returnType; + var newReturnType = returnType.widenedType(this, returnExpression, context); + signature.returnType = newReturnType; + + if (!TypeScript.ArrayUtilities.contains(returnExpressionSymbols, bestCommonReturnType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Could_not_find_the_best_common_type_of_types_of_all_return_statement_expressions)); + } + + if (this.compilationSettings.noImplicitAny()) { + if (previousReturnType !== newReturnType && newReturnType === this.semanticInfoChain.anyTypeSymbol) { + var functionName = enclosingDecl.name; + if (functionName === "") { + functionName = enclosingDecl.getFunctionExpressionName(); + } + + if (functionName != "") { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type, [functionName])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + } + } + + if (!functionSymbol.type && functionSymbol.isAccessor()) { + functionSymbol.type = signature.returnType; + } + } + } + }; + + PullTypeResolver.prototype.typeCheckConstructorDeclaration = function (funcDeclAST, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + for (var i = 0; i < funcDeclAST.callSignature.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveAST(funcDeclAST.callSignature.parameterList.parameters.nonSeparatorAt(i), false, context); + } + + this.resolveAST(funcDeclAST.block, false, context); + + if (funcDecl.getSignatureSymbol() && funcDecl.getSignatureSymbol().isDefinition() && this.enclosingClassIsDerived(funcDecl.getParentDecl())) { + if (!this.constructorHasSuperCall(funcDeclAST)) { + context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), "constructor".length, TypeScript.DiagnosticCode.Constructors_for_derived_classes_must_contain_a_super_call)); + } else if (this.superCallMustBeFirstStatementInConstructor(funcDecl)) { + var firstStatement = this.getFirstStatementOfBlockOrNull(funcDeclAST.block); + if (!firstStatement || !this.isSuperInvocationExpressionStatement(firstStatement)) { + context.postDiagnostic(new TypeScript.Diagnostic(funcDeclAST.fileName(), this.semanticInfoChain.lineMap(funcDeclAST.fileName()), funcDeclAST.start(), "constructor".length, TypeScript.DiagnosticCode.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties)); + } + } + } + + this.validateVariableDeclarationGroups(funcDecl, context); + + this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.callSignature.parameterList), null, funcDeclAST.block, context); + + this.typeCheckCallBacks.push(function (context) { + _this.typeCheckFunctionOverloads(funcDeclAST, context); + }); + }; + + PullTypeResolver.prototype.constructorHasSuperCall = function (constructorDecl) { + var _this = this; + if (constructorDecl.block) { + var foundSuperCall = false; + var pre = function (ast, walker) { + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 215 /* ObjectLiteralExpression */: + walker.options.goChildren = false; + default: + if (_this.isSuperInvocationExpression(ast)) { + foundSuperCall = true; + walker.options.stopWalking = true; + } + } + }; + + TypeScript.getAstWalkerFactory().walk(constructorDecl.block, pre); + return foundSuperCall; + } + + return false; + }; + + PullTypeResolver.prototype.typeCheckFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + this.typeCheckAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), funcDecl.callSignature.typeAnnotation, funcDecl.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckCallSignature = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckConstructSignature = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckMethodSignature = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, false, funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.typeCheckMemberFunctionDeclaration = function (funcDecl, context) { + this.typeCheckAnyFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + }; + + PullTypeResolver.prototype.containsSingleThrowStatement = function (block) { + return block !== null && block.statements.childCount() === 1 && block.statements.childAt(0).kind() === 157 /* ThrowStatement */; + }; + + PullTypeResolver.prototype.typeCheckAnyFunctionDeclaration = function (funcDeclAST, isStatic, name, typeParameters, parameters, returnTypeAnnotation, block, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + this.resolveAST(parameters, false, context); + + this.resolveAST(block, false, context); + var enclosingDecl = this.getEnclosingDecl(funcDecl); + + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); + this.validateVariableDeclarationGroups(funcDecl, context); + + this.checkFunctionTypePrivacy(funcDeclAST, isStatic, typeParameters, TypeScript.ASTHelpers.parametersFromParameterList(parameters), returnTypeAnnotation, block, context); + + this.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement(funcDecl, returnTypeAnnotation, funcDecl.getSignatureSymbol().returnType, block, context); + + if (funcDecl.kind === 16384 /* Function */) { + this.checkNameForCompilerGeneratedDeclarationCollision(funcDeclAST, true, name, context); + } + + this.typeCheckCallBacks.push(function (context) { + _this.typeCheckFunctionOverloads(funcDeclAST, context); + }); + }; + + PullTypeResolver.prototype.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement = function (functionDecl, returnTypeAnnotation, returnTypeSymbol, block, context) { + var hasReturn = TypeScript.hasFlag(functionDecl.flags, 4194304 /* HasReturnStatement */); + + if (block !== null && returnTypeAnnotation !== null && !hasReturn) { + var isVoidOrAny = this.isAnyOrEquivalent(returnTypeSymbol) || returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol; + + if (!isVoidOrAny && !this.containsSingleThrowStatement(block)) { + var funcName = functionDecl.getDisplayName() || TypeScript.getLocalizedText(TypeScript.DiagnosticCode.expression, null); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Function_declared_a_non_void_return_type_but_has_no_return_expression)); + } + } + }; + + PullTypeResolver.prototype.typeCheckIndexSignature = function (funcDeclAST, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + this.resolveAST(funcDeclAST.parameter, false, context); + + var enclosingDecl = this.getEnclosingDecl(funcDecl); + + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); + this.validateVariableDeclarationGroups(funcDecl, context); + + this.checkFunctionTypePrivacy(funcDeclAST, false, null, TypeScript.ASTHelpers.parametersFromParameter(funcDeclAST.parameter), TypeScript.ASTHelpers.getType(funcDeclAST), null, context); + + var signature = funcDecl.getSignatureSymbol(); + + this.typeCheckCallBacks.push(function (context) { + var parentSymbol = funcDecl.getSignatureSymbol().getContainer(); + var allIndexSignatures = _this.getBothKindsOfIndexSignaturesExcludingAugmentedType(parentSymbol, context); + var stringIndexSignature = allIndexSignatures.stringSignature; + var numberIndexSignature = allIndexSignatures.numericSignature; + var isNumericIndexer = numberIndexSignature === signature; + + if (numberIndexSignature && stringIndexSignature && (isNumericIndexer || stringIndexSignature.getDeclarations()[0].getParentDecl() !== numberIndexSignature.getDeclarations()[0].getParentDecl())) { + var comparisonInfo = new TypeComparisonInfo(); + + if (!_this.sourceIsAssignableToTarget(numberIndexSignature.returnType, stringIndexSignature.returnType, funcDeclAST, context, comparisonInfo)) { + var enclosingSymbol = _this.getEnclosingSymbolForAST(funcDeclAST); + if (comparisonInfo.message) { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1_NL_2, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1, [numberIndexSignature.returnType.toString(enclosingSymbol), stringIndexSignature.returnType.toString(enclosingSymbol)])); + } + } + } + + var allMembers = parentSymbol.type.getAllMembers(536869887 /* All */, 0 /* all */); + for (var i = 0; i < allMembers.length; i++) { + var member = allMembers[i]; + var name = member.name; + if (name || (member.kind === 4096 /* Property */ && name === "")) { + if (!allMembers[i].isResolved) { + _this.resolveDeclaredSymbol(allMembers[i], context); + } + + if (parentSymbol !== allMembers[i].getContainer()) { + var isMemberNumeric = TypeScript.PullHelpers.isNameNumeric(name); + var indexerKindMatchesMemberNameKind = isNumericIndexer === isMemberNumeric; + var onlyStringIndexerIsPresent = !numberIndexSignature; + + if (indexerKindMatchesMemberNameKind || onlyStringIndexerIsPresent) { + var comparisonInfo = new TypeComparisonInfo(); + if (!_this.sourceIsAssignableToTarget(allMembers[i].type, signature.returnType, funcDeclAST, context, comparisonInfo, false)) { + _this.reportErrorThatMemberIsNotSubtypeOfIndexer(allMembers[i], signature, funcDeclAST, context, comparisonInfo); + } + } + } + } + } + }); + }; + + PullTypeResolver.prototype.postTypeCheckFunctionDeclaration = function (funcDeclAST, context) { + this.checkThisCaptureVariableCollides(funcDeclAST, true, context); + }; + + PullTypeResolver.prototype.resolveReturnTypeAnnotationOfFunctionDeclaration = function (funcDeclAST, returnTypeAnnotation, context) { + var returnTypeSymbol = null; + + if (returnTypeAnnotation) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + returnTypeSymbol = this.resolveTypeReference(returnTypeAnnotation, context); + + if (!returnTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); + } else { + var isConstructor = funcDeclAST.kind() === 137 /* ConstructorDeclaration */ || funcDeclAST.kind() === 143 /* ConstructSignature */; + if (isConstructor && returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Constructors_cannot_have_a_return_type_of_void)); + } + } + } + + return returnTypeSymbol; + }; + + PullTypeResolver.prototype.resolveMemberFunctionDeclaration = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + }; + + PullTypeResolver.prototype.resolveCallSignature = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.typeParameterList, funcDecl.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.resolveConstructSignature = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, false, null, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.resolveMethodSignature = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, false, funcDecl.propertyName, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), null, context); + }; + + PullTypeResolver.prototype.resolveAnyFunctionDeclaration = function (funcDecl, context) { + return this.resolveFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + }; + + PullTypeResolver.prototype.resolveFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveSimpleArrowFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcDecl, null, TypeScript.ASTHelpers.parametersFromIdentifier(funcDecl.identifier), null, funcDecl.block, funcDecl.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveParenthesizedArrowFunctionExpression = function (funcDecl, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcDecl, funcDecl.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, funcDecl.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.getEnclosingClassDeclaration = function (ast) { + while (ast) { + if (ast.kind() === 131 /* ClassDeclaration */) { + return ast; + } + + ast = ast.parent; + } + + return null; + }; + + PullTypeResolver.prototype.resolveConstructorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcSymbol = funcDecl.getSymbol(); + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckConstructorDeclaration(funcDeclAST, context); + } + return funcSymbol; + } + + if (!signature.inResolution) { + var classAST = this.getEnclosingClassDeclaration(funcDeclAST); + + if (classAST) { + var classDecl = this.semanticInfoChain.getDeclForAST(classAST); + var classSymbol = classDecl.getSymbol(); + + if (!classSymbol.isResolved && !classSymbol.inResolution) { + this.resolveDeclaredSymbol(classSymbol, context); + } + } + } + + var functionTypeSymbol = funcSymbol && funcSymbol.type; + + if (signature.inResolution) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + return funcSymbol; + } + + if (funcSymbol) { + funcSymbol.startResolving(); + } + signature.startResolving(); + + var prevInTypeCheck = context.inTypeCheck; + + context.inTypeCheck = false; + + for (var i = 0; i < funcDeclAST.callSignature.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(funcDeclAST.callSignature.parameterList.parameters.nonSeparatorAt(i), context); + } + + context.inTypeCheck = prevInTypeCheck; + + if (signature.isGeneric()) { + if (funcSymbol) { + funcSymbol.type.setHasGenericSignature(); + } + } + + if (!hadError) { + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + } + } + + if (funcSymbol) { + this.resolveOtherDeclarations(funcDeclAST, context); + } + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckConstructorDeclaration(funcDeclAST, context); + } + + return funcSymbol; + }; + + PullTypeResolver.prototype.resolveIndexMemberDeclaration = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + } + + return this.resolveIndexSignature(ast.indexSignature, context); + }; + + PullTypeResolver.prototype.resolveIndexSignature = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcSymbol = funcDecl.getSymbol(); + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckIndexSignature(funcDeclAST, context); + } + return funcSymbol; + } + + var functionTypeSymbol = funcSymbol && funcSymbol.type; + + if (signature.inResolution) { + if (funcDeclAST.typeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(TypeScript.ASTHelpers.getType(funcDeclAST), context); + if (!returnTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(TypeScript.ASTHelpers.getType(funcDeclAST), TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + } + + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + return funcSymbol; + } + + if (funcSymbol) { + funcSymbol.startResolving(); + } + signature.startResolving(); + + if (funcDeclAST.parameter) { + var prevInTypeCheck = context.inTypeCheck; + + context.inTypeCheck = false; + this.resolveParameter(funcDeclAST.parameter, context); + context.inTypeCheck = prevInTypeCheck; + } + + if (funcDeclAST.typeAnnotation) { + returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); + + if (!returnTypeSymbol) { + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + } + + if (!hadError) { + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + } + } + + if (funcSymbol) { + this.resolveOtherDeclarations(funcDeclAST, context); + } + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckIndexSignature(funcDeclAST, context); + } + + return funcSymbol; + }; + + PullTypeResolver.prototype.resolveFunctionDeclaration = function (funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcSymbol = funcDecl.getSymbol(); + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + var isConstructor = funcDeclAST.kind() === 143 /* ConstructSignature */; + + if (signature) { + if (signature.isResolved) { + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckAnyFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); + } + return funcSymbol; + } + + if (isConstructor && !signature.inResolution) { + var classAST = this.getEnclosingClassDeclaration(funcDeclAST); + + if (classAST) { + var classDecl = this.semanticInfoChain.getDeclForAST(classAST); + var classSymbol = classDecl.getSymbol(); + + if (!classSymbol.isResolved && !classSymbol.inResolution) { + this.resolveDeclaredSymbol(classSymbol, context); + } + } + } + + var functionTypeSymbol = funcSymbol && funcSymbol.type; + + if (signature.inResolution) { + if (returnTypeAnnotation) { + var returnTypeSymbol = this.resolveTypeReference(returnTypeAnnotation, context); + if (!returnTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, TypeScript.DiagnosticCode.Cannot_resolve_return_type_reference)); + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + + if (isConstructor && returnTypeSymbol === this.semanticInfoChain.voidTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Constructors_cannot_have_a_return_type_of_void)); + } + } + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + } + + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + return funcSymbol; + } + + if (funcSymbol) { + funcSymbol.startResolving(); + } + signature.startResolving(); + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + if (parameterList) { + var prevInTypeCheck = context.inTypeCheck; + + context.inTypeCheck = false; + + for (var i = 0; i < parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(parameterList.parameters.nonSeparatorAt(i), context); + } + + context.inTypeCheck = prevInTypeCheck; + } + + if (returnTypeAnnotation) { + returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); + + if (!returnTypeSymbol) { + signature.returnType = this.getNewErrorTypeSymbol(); + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else if (funcDecl.kind !== 2097152 /* ConstructSignature */) { + if (TypeScript.hasFlag(funcDecl.flags, 2048 /* Signature */)) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + var parentDeclFlags = 0 /* None */; + if (TypeScript.hasFlag(funcDecl.kind, 65536 /* Method */) || TypeScript.hasFlag(funcDecl.kind, 32768 /* ConstructorMethod */)) { + var parentDecl = funcDecl.getParentDecl(); + parentDeclFlags = parentDecl.flags; + } + + if (this.compilationSettings.noImplicitAny() && (!TypeScript.hasFlag(parentDeclFlags, 8 /* Ambient */) || (TypeScript.hasFlag(parentDeclFlags, 8 /* Ambient */) && !TypeScript.hasFlag(funcDecl.flags, 2 /* Private */)))) { + var funcDeclASTName = name; + if (funcDeclASTName) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type, [funcDeclASTName.text()])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Lambda_Function_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + } else { + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, null, signature, false, funcDecl, context); + } + } else if (funcDecl.kind === 2097152 /* ConstructSignature */) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Constructor_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + + if (!hadError) { + if (funcSymbol) { + funcSymbol.setUnresolved(); + if (funcSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + funcSymbol.type = functionTypeSymbol; + } + } + signature.setResolved(); + } + } + + if (funcSymbol) { + this.resolveOtherDeclarations(funcDeclAST, context); + } + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckAnyFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); + } + + return funcSymbol; + }; + + PullTypeResolver.prototype.resolveGetterReturnTypeAnnotation = function (getterFunctionDeclarationAst, enclosingDecl, context) { + if (getterFunctionDeclarationAst && getterFunctionDeclarationAst.typeAnnotation) { + return this.resolveTypeReference(TypeScript.ASTHelpers.getType(getterFunctionDeclarationAst), context); + } + + return null; + }; + + PullTypeResolver.prototype.resolveSetterArgumentTypeAnnotation = function (setterFunctionDeclarationAst, enclosingDecl, context) { + if (setterFunctionDeclarationAst && setterFunctionDeclarationAst.parameterList && setterFunctionDeclarationAst.parameterList.parameters.nonSeparatorCount() > 0) { + var parameter = setterFunctionDeclarationAst.parameterList.parameters.nonSeparatorAt(0); + return this.resolveTypeReference(TypeScript.ASTHelpers.getType(parameter), context); + } + + return null; + }; + + PullTypeResolver.prototype.resolveAccessorDeclaration = function (funcDeclAst, context) { + var functionDeclaration = this.semanticInfoChain.getDeclForAST(funcDeclAst); + var accessorSymbol = functionDeclaration.getSymbol(); + + if (accessorSymbol.inResolution) { + accessorSymbol.type = this.semanticInfoChain.anyTypeSymbol; + accessorSymbol.setResolved(); + + return accessorSymbol; + } + + if (accessorSymbol.isResolved) { + if (!accessorSymbol.type) { + accessorSymbol.type = this.semanticInfoChain.anyTypeSymbol; + } + } else { + var getterSymbol = accessorSymbol.getGetter(); + var getterFunctionDeclarationAst = getterSymbol ? getterSymbol.getDeclarations()[0].ast() : null; + var hasGetter = getterSymbol !== null; + + var setterSymbol = accessorSymbol.getSetter(); + var setterFunctionDeclarationAst = setterSymbol ? setterSymbol.getDeclarations()[0].ast() : null; + var hasSetter = setterSymbol !== null; + + var getterAnnotatedType = this.resolveGetterReturnTypeAnnotation(getterFunctionDeclarationAst, functionDeclaration, context); + var getterHasTypeAnnotation = getterAnnotatedType !== null; + + var setterAnnotatedType = this.resolveSetterArgumentTypeAnnotation(setterFunctionDeclarationAst, functionDeclaration, context); + var setterHasTypeAnnotation = setterAnnotatedType !== null; + + accessorSymbol.startResolving(); + + if (hasGetter) { + getterSymbol = this.resolveGetAccessorDeclaration(getterFunctionDeclarationAst, getterFunctionDeclarationAst.parameterList, TypeScript.ASTHelpers.getType(getterFunctionDeclarationAst), getterFunctionDeclarationAst.block, setterAnnotatedType, context); + } + + if (hasSetter) { + setterSymbol = this.resolveSetAccessorDeclaration(setterFunctionDeclarationAst, setterFunctionDeclarationAst.parameterList, context); + } + + if (hasGetter && hasSetter) { + var setterSig = setterSymbol.type.getCallSignatures()[0]; + var setterParameters = setterSig.parameters; + var setterHasParameters = setterParameters.length > 0; + var getterSig = getterSymbol.type.getCallSignatures()[0]; + + var setterSuppliedTypeSymbol = setterHasParameters ? setterParameters[0].type : null; + var getterSuppliedTypeSymbol = getterSig.returnType; + + if (setterHasTypeAnnotation && !getterHasTypeAnnotation) { + getterSuppliedTypeSymbol = setterSuppliedTypeSymbol; + getterSig.returnType = setterSuppliedTypeSymbol; + } else if ((getterHasTypeAnnotation && !setterHasTypeAnnotation) || (!getterHasTypeAnnotation && !setterHasTypeAnnotation)) { + setterSuppliedTypeSymbol = getterSuppliedTypeSymbol; + + if (setterHasParameters) { + setterParameters[0].type = getterSuppliedTypeSymbol; + } + } + + if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol, context)) { + accessorSymbol.type = this.getNewErrorTypeSymbol(); + } else { + accessorSymbol.type = getterSuppliedTypeSymbol; + } + } else if (hasSetter) { + var setterSig = setterSymbol.type.getCallSignatures()[0]; + var setterParameters = setterSig.parameters; + var setterHasParameters = setterParameters.length > 0; + + accessorSymbol.type = setterHasParameters ? setterParameters[0].type : this.semanticInfoChain.anyTypeSymbol; + } else { + var getterSig = getterSymbol.type.getCallSignatures()[0]; + accessorSymbol.type = getterSig.returnType; + } + + accessorSymbol.setResolved(); + } + + if (this.canTypeCheckAST(funcDeclAst, context)) { + this.typeCheckAccessorDeclaration(funcDeclAst, context); + } + + return accessorSymbol; + }; + + PullTypeResolver.prototype.typeCheckAccessorDeclaration = function (funcDeclAst, context) { + this.setTypeChecked(funcDeclAst, context); + var functionDeclaration = this.semanticInfoChain.getDeclForAST(funcDeclAst); + var accessorSymbol = functionDeclaration.getSymbol(); + var getterSymbol = accessorSymbol.getGetter(); + var setterSymbol = accessorSymbol.getSetter(); + + var isGetter = funcDeclAst.kind() === 139 /* GetAccessor */; + if (isGetter) { + var getterFunctionDeclarationAst = funcDeclAst; + context.pushNewContextualType(getterSymbol.type); + this.typeCheckGetAccessorDeclaration(getterFunctionDeclarationAst, context); + context.popAnyContextualType(); + } else { + var setterFunctionDeclarationAst = funcDeclAst; + this.typeCheckSetAccessorDeclaration(setterFunctionDeclarationAst, context); + } + }; + + PullTypeResolver.prototype.resolveGetAccessorDeclaration = function (funcDeclAST, parameters, returnTypeAnnotation, block, setterAnnotatedType, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + var getterSymbol = accessorSymbol.getGetter(); + var getterTypeSymbol = getterSymbol.type; + + var signature = getterTypeSymbol.getCallSignatures()[0]; + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + return getterSymbol; + } + + if (signature.inResolution) { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + signature.setResolved(); + + return getterSymbol; + } + + signature.startResolving(); + + if (returnTypeAnnotation) { + var returnTypeSymbol = this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); + + if (!returnTypeSymbol) { + signature.returnType = this.getNewErrorTypeSymbol(); + + hadError = true; + } else { + signature.returnType = returnTypeSymbol; + } + } else { + if (!setterAnnotatedType) { + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, null, signature, false, funcDecl, context); + } else { + signature.returnType = setterAnnotatedType; + } + } + + if (!hadError) { + signature.setResolved(); + } + } + + return getterSymbol; + }; + + PullTypeResolver.prototype.checkIfGetterAndSetterTypeMatch = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + var getter = accessorSymbol.getGetter(); + var setter = accessorSymbol.getSetter(); + + if (getter && setter) { + var getterAST = getter.getDeclarations()[0].ast(); + var setterAST = setter.getDeclarations()[0].ast(); + + if (getterAST.typeAnnotation && PullTypeResolver.hasSetAccessorParameterTypeAnnotation(setterAST)) { + var setterSig = setter.type.getCallSignatures()[0]; + var setterParameters = setterSig.parameters; + + var getter = accessorSymbol.getGetter(); + var getterSig = getter.type.getCallSignatures()[0]; + + var setterSuppliedTypeSymbol = setterParameters[0].type; + var getterSuppliedTypeSymbol = getterSig.returnType; + + if (!this.typesAreIdentical(setterSuppliedTypeSymbol, getterSuppliedTypeSymbol, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.get_and_set_accessor_must_have_the_same_type)); + } + } + } + }; + + PullTypeResolver.prototype.typeCheckGetAccessorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + this.resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, TypeScript.ASTHelpers.getType(funcDeclAST), context); + + this.resolveAST(funcDeclAST.block, false, context); + + this.validateVariableDeclarationGroups(funcDecl, context); + + var enclosingDecl = this.getEnclosingDecl(funcDecl); + + var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) !== 0; + var funcNameAST = funcDeclAST.propertyName; + + if (!hasReturn && !this.containsSingleThrowStatement(funcDeclAST.block)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getters_must_return_a_value)); + } + + var setter = accessorSymbol.getSetter(); + if (setter) { + var setterDecl = setter.getDeclarations()[0]; + var setterIsPrivate = TypeScript.hasFlag(setterDecl.flags, 2 /* Private */); + var getterIsPrivate = TypeScript.hasModifier(funcDeclAST.modifiers, 2 /* Private */); + + if (getterIsPrivate !== setterIsPrivate) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getter_and_setter_accessors_do_not_agree_in_visibility)); + } + + this.checkIfGetterAndSetterTypeMatch(funcDeclAST, context); + } + + this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), TypeScript.ASTHelpers.getType(funcDeclAST), funcDeclAST.block, context); + }; + + PullTypeResolver.hasSetAccessorParameterTypeAnnotation = function (setAccessor) { + return setAccessor.parameterList && setAccessor.parameterList.parameters.nonSeparatorCount() > 0 && setAccessor.parameterList.parameters.nonSeparatorAt(0).typeAnnotation !== null; + }; + + PullTypeResolver.prototype.resolveSetAccessorDeclaration = function (funcDeclAST, parameterList, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + var setterSymbol = accessorSymbol.getSetter(); + var setterTypeSymbol = setterSymbol.type; + + var signature = funcDecl.getSignatureSymbol(); + + var hadError = false; + + if (signature) { + if (signature.isResolved) { + return setterSymbol; + } + + if (signature.inResolution) { + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + signature.setResolved(); + return setterSymbol; + } + + signature.startResolving(); + + if (parameterList) { + for (var i = 0; i < parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(parameterList.parameters.nonSeparatorAt(i), context); + } + } + + signature.returnType = this.semanticInfoChain.voidTypeSymbol; + + if (!hadError) { + signature.setResolved(); + } + } + + return setterSymbol; + }; + + PullTypeResolver.prototype.typeCheckSetAccessorDeclaration = function (funcDeclAST, context) { + var funcDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var accessorSymbol = funcDecl.getSymbol(); + + if (funcDeclAST.parameterList) { + for (var i = 0; i < funcDeclAST.parameterList.parameters.nonSeparatorCount(); i++) { + this.resolveParameter(funcDeclAST.parameterList.parameters.nonSeparatorAt(i), context); + } + } + + this.resolveAST(funcDeclAST.block, false, context); + + this.validateVariableDeclarationGroups(funcDecl, context); + + var hasReturn = (funcDecl.flags & (2048 /* Signature */ | 4194304 /* HasReturnStatement */)) !== 0; + + var getter = accessorSymbol.getGetter(); + + var funcNameAST = funcDeclAST.propertyName; + + if (getter) { + var getterDecl = getter.getDeclarations()[0]; + var getterIsPrivate = TypeScript.hasFlag(getterDecl.flags, 2 /* Private */); + var setterIsPrivate = TypeScript.hasModifier(funcDeclAST.modifiers, 2 /* Private */); + + if (getterIsPrivate !== setterIsPrivate) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcNameAST, TypeScript.DiagnosticCode.Getter_and_setter_accessors_do_not_agree_in_visibility)); + } + + this.checkIfGetterAndSetterTypeMatch(funcDeclAST, context); + } else { + if (this.compilationSettings.noImplicitAny()) { + var setterFunctionDeclarationAst = funcDeclAST; + if (!PullTypeResolver.hasSetAccessorParameterTypeAnnotation(setterFunctionDeclarationAst) && accessorSymbol.type === this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type, [setterFunctionDeclarationAst.propertyName.text()])); + } + } + } + + this.checkFunctionTypePrivacy(funcDeclAST, TypeScript.hasModifier(funcDeclAST.modifiers, 16 /* Static */), null, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), null, funcDeclAST.block, context); + }; + + PullTypeResolver.prototype.resolveList = function (list, context) { + if (this.canTypeCheckAST(list, context)) { + this.setTypeChecked(list, context); + + for (var i = 0, n = list.childCount(); i < n; i++) { + this.resolveAST(list.childAt(i), false, context); + } + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveSeparatedList = function (list, context) { + if (this.canTypeCheckAST(list, context)) { + this.setTypeChecked(list, context); + + for (var i = 0, n = list.nonSeparatorCount(); i < n; i++) { + this.resolveAST(list.nonSeparatorAt(i), false, context); + } + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveVoidExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.undefinedTypeSymbol; + }; + + PullTypeResolver.prototype.resolveLogicalOperation = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckLogicalOperation(ast, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckLogicalOperation = function (binex, context) { + this.setTypeChecked(binex, context); + + var leftType = this.resolveAST(binex.left, false, context).type; + var rightType = this.resolveAST(binex.right, false, context).type; + + var comparisonInfo = new TypeComparisonInfo(); + if (!this.sourceIsAssignableToTarget(leftType, rightType, binex, context, comparisonInfo) && !this.sourceIsAssignableToTarget(rightType, leftType, binex, context, comparisonInfo)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(binex); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binex, TypeScript.DiagnosticCode.Operator_0_cannot_be_applied_to_types_1_and_2, [ + TypeScript.SyntaxFacts.getText(TypeScript.SyntaxFacts.getOperatorTokenFromBinaryExpression(binex.kind())), + leftType.toString(enclosingSymbol), rightType.toString(enclosingSymbol)])); + } + }; + + PullTypeResolver.prototype.resolveLogicalNotExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.operand, false, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.resolveUnaryArithmeticOperation = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckUnaryArithmeticOperation(ast, context); + } + + return this.semanticInfoChain.numberTypeSymbol; + }; + + PullTypeResolver.prototype.resolvePostfixUnaryExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckPostfixUnaryExpression(ast, context); + } + + return this.semanticInfoChain.numberTypeSymbol; + }; + + PullTypeResolver.prototype.isAnyOrNumberOrEnum = function (type) { + return this.isAnyOrEquivalent(type) || type === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(type); + }; + + PullTypeResolver.prototype.typeCheckUnaryArithmeticOperation = function (unaryExpression, context) { + this.setTypeChecked(unaryExpression, context); + + var nodeType = unaryExpression.kind(); + var expression = this.resolveAST(unaryExpression.operand, false, context); + + if (nodeType === 164 /* PlusExpression */ || nodeType == 165 /* NegateExpression */ || nodeType == 166 /* BitwiseNotExpression */) { + return; + } + + TypeScript.Debug.assert(nodeType === 168 /* PreIncrementExpression */ || nodeType === 169 /* PreDecrementExpression */); + + var operandType = expression.type; + if (!this.isAnyOrNumberOrEnum(operandType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type_any_number_or_an_enum_type)); + } + + if (!this.isReference(unaryExpression.operand, expression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer)); + } + }; + + PullTypeResolver.prototype.typeCheckPostfixUnaryExpression = function (unaryExpression, context) { + this.setTypeChecked(unaryExpression, context); + + var nodeType = unaryExpression.kind(); + var expression = this.resolveAST(unaryExpression.operand, false, context); + + TypeScript.Debug.assert(nodeType === 210 /* PostIncrementExpression */ || nodeType === 211 /* PostDecrementExpression */); + + var operandType = expression.type; + if (!this.isAnyOrNumberOrEnum(operandType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type_any_number_or_an_enum_type)); + } + + if (!this.isReference(unaryExpression.operand, expression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(unaryExpression.operand, TypeScript.DiagnosticCode.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer)); + } + }; + + PullTypeResolver.prototype.resolveBinaryArithmeticExpression = function (binaryExpression, context) { + if (this.canTypeCheckAST(binaryExpression, context)) { + this.typeCheckBinaryArithmeticExpression(binaryExpression, context); + } + + return this.semanticInfoChain.numberTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckBinaryArithmeticExpression = function (binaryExpression, context) { + this.setTypeChecked(binaryExpression, context); + + var lhsSymbol = this.resolveAST(binaryExpression.left, false, context); + + var lhsType = lhsSymbol.type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + if (lhsType === this.semanticInfoChain.nullTypeSymbol || lhsType === this.semanticInfoChain.undefinedTypeSymbol) { + lhsType = rhsType; + } + + if (rhsType === this.semanticInfoChain.nullTypeSymbol || rhsType === this.semanticInfoChain.undefinedTypeSymbol) { + rhsType = lhsType; + } + + var lhsIsFit = this.isAnyOrNumberOrEnum(lhsType); + var rhsIsFit = this.isAnyOrNumberOrEnum(rhsType); + + if (!rhsIsFit) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type)); + } + + if (!lhsIsFit) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type)); + } + + if (lhsIsFit && rhsIsFit) { + switch (binaryExpression.kind()) { + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + if (!this.isReference(binaryExpression.left, lhsSymbol)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_left_hand_side_of_assignment_expression)); + } + + this.checkAssignability(binaryExpression.left, rhsType, lhsType, context); + } + } + }; + + PullTypeResolver.prototype.resolveTypeOfExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.stringTypeSymbol; + }; + + PullTypeResolver.prototype.resolveThrowStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveDeleteExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.resolveInstanceOfExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckInstanceOfExpression(ast, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckInstanceOfExpression = function (binaryExpression, context) { + this.setTypeChecked(binaryExpression, context); + + var lhsType = this.resolveAST(binaryExpression.left, false, context).type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + var enclosingSymbol = this.getEnclosingSymbolForAST(binaryExpression); + var isValidLHS = this.isAnyOrEquivalent(lhsType) || lhsType.isObject() || lhsType.isTypeParameter(); + var isValidRHS = this.isAnyOrEquivalent(rhsType) || this.typeIsAssignableToFunction(rhsType, binaryExpression, context); + + if (!isValidLHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter)); + } + + if (!isValidRHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type)); + } + }; + + PullTypeResolver.prototype.resolveCommaExpression = function (commaExpression, context) { + if (this.canTypeCheckAST(commaExpression, context)) { + this.setTypeChecked(commaExpression, context); + + this.resolveAST(commaExpression.left, false, context); + } + + return this.resolveAST(commaExpression.right, false, context).type; + }; + + PullTypeResolver.prototype.resolveInExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckInExpression(ast, context); + } + + return this.semanticInfoChain.booleanTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckInExpression = function (binaryExpression, context) { + this.setTypeChecked(binaryExpression, context); + + var lhsType = this.resolveAST(binaryExpression.left, false, context).type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + var isValidLHS = this.isAnyOrEquivalent(lhsType.type) || lhsType.type === this.semanticInfoChain.stringTypeSymbol || lhsType.type === this.semanticInfoChain.numberTypeSymbol; + + var isValidRHS = this.isAnyOrEquivalent(rhsType) || rhsType.isObject() || rhsType.isTypeParameter(); + + if (!isValidLHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number)); + } + + if (!isValidRHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.right, TypeScript.DiagnosticCode.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter)); + } + }; + + PullTypeResolver.prototype.resolveForStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.variableDeclaration, false, context); + this.resolveAST(ast.initializer, false, context); + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.incrementor, false, context); + this.resolveAST(ast.statement, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveForInStatement = function (forInStatement, context) { + if (this.canTypeCheckAST(forInStatement, context)) { + this.typeCheckForInStatement(forInStatement, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckForInStatement = function (forInStatement, context) { + this.setTypeChecked(forInStatement, context); + + if (forInStatement.variableDeclaration) { + var declaration = forInStatement.variableDeclaration; + + if (declaration.declarators.nonSeparatorCount() === 1) { + var varDecl = declaration.declarators.nonSeparatorAt(0); + + if (varDecl.typeAnnotation) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(declaration, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_cannot_use_a_type_annotation)); + } + } + } else { + var varSym = this.resolveAST(forInStatement.left, false, context); + var isStringOrNumber = varSym.type === this.semanticInfoChain.stringTypeSymbol || this.isAnyOrEquivalent(varSym.type); + + if (!isStringOrNumber) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(forInStatement.left, TypeScript.DiagnosticCode.Variable_declarations_of_a_for_statement_must_be_of_types_string_or_any)); + } + } + + var rhsType = this.resolveAST(forInStatement.expression, false, context).type; + var isValidRHS = rhsType && (this.isAnyOrEquivalent(rhsType) || rhsType.isObject() || rhsType.isTypeParameter()); + + if (!isValidRHS) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(forInStatement.expression, TypeScript.DiagnosticCode.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter)); + } + + this.resolveAST(forInStatement.statement, false, context); + }; + + PullTypeResolver.prototype.resolveWhileStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckWhileStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckWhileStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.resolveDoStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckDoStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckDoStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.resolveIfStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckIfStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckIfStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.condition, false, context); + this.resolveAST(ast.statement, false, context); + this.resolveAST(ast.elseClause, false, context); + }; + + PullTypeResolver.prototype.resolveElseClause = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckElseClause(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckElseClause = function (ast, context) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.resolveBlock = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.statements, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveVariableStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.declaration, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveVariableDeclarationList = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.declarators, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveWithStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckWithStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckWithStatement = function (ast, context) { + this.setTypeChecked(ast, context); + var withStatement = ast; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(withStatement.condition, TypeScript.DiagnosticCode.All_symbols_within_a_with_block_will_be_resolved_to_any)); + }; + + PullTypeResolver.prototype.resolveTryStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckTryStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckTryStatement = function (ast, context) { + this.setTypeChecked(ast, context); + var tryStatement = ast; + + this.resolveAST(tryStatement.block, false, context); + this.resolveAST(tryStatement.catchClause, false, context); + this.resolveAST(tryStatement.finallyClause, false, context); + }; + + PullTypeResolver.prototype.resolveCatchClause = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckCatchClause(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckCatchClause = function (ast, context) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.block, false, context); + + var catchDecl = this.semanticInfoChain.getDeclForAST(ast); + this.validateVariableDeclarationGroups(catchDecl, context); + }; + + PullTypeResolver.prototype.resolveFinallyClause = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckFinallyClause(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckFinallyClause = function (ast, context) { + this.setTypeChecked(ast, context); + this.resolveAST(ast.block, false, context); + }; + + PullTypeResolver.prototype.getEnclosingFunctionDeclaration = function (ast) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + + while (enclosingDecl) { + if (enclosingDecl.kind & 1032192 /* SomeFunction */) { + return enclosingDecl; + } + + enclosingDecl = enclosingDecl.getParentDecl(); + } + + return null; + }; + + PullTypeResolver.prototype.resolveReturnExpression = function (expression, enclosingFunction, context) { + if (enclosingFunction) { + enclosingFunction.setFlag(4194304 /* HasReturnStatement */); + } + + var isContextuallyTyped = false; + + if (enclosingFunction) { + var enclosingDeclAST = this.getASTForDecl(enclosingFunction); + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); + if (typeAnnotation) { + var returnTypeAnnotationSymbol = this.resolveTypeReference(typeAnnotation, context); + if (returnTypeAnnotationSymbol) { + isContextuallyTyped = true; + context.pushNewContextualType(returnTypeAnnotationSymbol); + } + } else { + var currentContextualType = context.getContextualType(); + if (currentContextualType && currentContextualType.isFunction()) { + var contextualSignatures = currentContextualType.kind == 33554432 /* ConstructorType */ ? currentContextualType.getConstructSignatures() : currentContextualType.getCallSignatures(); + var currentContextualTypeSignatureSymbol = contextualSignatures[0]; + + var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.returnType; + if (currentContextualTypeReturnTypeSymbol) { + isContextuallyTyped = true; + context.propagateContextualType(currentContextualTypeReturnTypeSymbol); + } + } + } + } + + var result = this.resolveAST(expression, isContextuallyTyped, context).type; + if (isContextuallyTyped) { + context.popAnyContextualType(); + } + + return result; + }; + + PullTypeResolver.prototype.typeCheckReturnExpression = function (expression, expressionType, enclosingFunction, context) { + if (enclosingFunction && enclosingFunction.kind === 32768 /* ConstructorMethod */) { + var classDecl = enclosingFunction.getParentDecl(); + if (classDecl) { + var classSymbol = classDecl.getSymbol(); + this.resolveDeclaredSymbol(classSymbol, context); + + var comparisonInfo = new TypeComparisonInfo(); + var isAssignable = this.sourceIsAssignableToTarget(expressionType, classSymbol.type, expression, context, comparisonInfo); + if (!isAssignable) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class)); + } + } + } + + if (enclosingFunction && enclosingFunction.kind === 524288 /* SetAccessor */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Setters_cannot_return_a_value)); + } + + if (enclosingFunction) { + var enclosingDeclAST = this.getASTForDecl(enclosingFunction); + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); + if (typeAnnotation || enclosingFunction.kind === 262144 /* GetAccessor */) { + var signatureSymbol = enclosingFunction.getSignatureSymbol(); + var sigReturnType = signatureSymbol.returnType; + + if (expressionType && sigReturnType) { + var comparisonInfo = new TypeComparisonInfo(); + var upperBound = null; + + this.resolveDeclaredSymbol(expressionType, context); + this.resolveDeclaredSymbol(sigReturnType, context); + + var isAssignable = this.sourceIsAssignableToTarget(expressionType, sigReturnType, expression, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(expression); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [expressionType.toString(enclosingSymbol), sigReturnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [expressionType.toString(enclosingSymbol), sigReturnType.toString(enclosingSymbol)])); + } + } + } + } + } + }; + + PullTypeResolver.prototype.resolveReturnStatement = function (returnAST, context) { + var enclosingFunction = this.getEnclosingFunctionDeclaration(returnAST); + if (enclosingFunction) { + enclosingFunction.setFlag(4194304 /* HasReturnStatement */); + } + + var returnType = this.getSymbolForAST(returnAST, context); + var canTypeCheckAST = this.canTypeCheckAST(returnAST, context); + if (!returnType || canTypeCheckAST) { + var returnExpr = returnAST.expression; + + var resolvedReturnType = returnExpr === null ? this.semanticInfoChain.voidTypeSymbol : this.resolveReturnExpression(returnExpr, enclosingFunction, context); + + if (!returnType) { + returnType = resolvedReturnType; + this.setSymbolForAST(returnAST, resolvedReturnType, context); + } + + if (returnExpr && canTypeCheckAST) { + this.setTypeChecked(returnExpr, context); + this.typeCheckReturnExpression(returnExpr, resolvedReturnType, enclosingFunction, context); + } + } + + return returnType; + }; + + PullTypeResolver.prototype.resolveSwitchStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckSwitchStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckSwitchStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + var expressionType = this.resolveAST(ast.expression, false, context).type; + + for (var i = 0, n = ast.switchClauses.childCount(); i < n; i++) { + var switchClause = ast.switchClauses.childAt(i); + if (switchClause.kind() === 233 /* CaseSwitchClause */) { + var caseSwitchClause = switchClause; + + var caseClauseExpressionType = this.resolveAST(caseSwitchClause.expression, false, context).type; + this.resolveAST(caseSwitchClause.statements, false, context); + + var comparisonInfo = new TypeComparisonInfo(); + if (!this.sourceIsAssignableToTarget(expressionType, caseClauseExpressionType, caseSwitchClause.expression, context, comparisonInfo) && !this.sourceIsAssignableToTarget(caseClauseExpressionType, expressionType, caseSwitchClause.expression, context, comparisonInfo)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(caseSwitchClause.expression); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(caseSwitchClause.expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [caseClauseExpressionType.toString(enclosingSymbol), expressionType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(caseSwitchClause.expression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [caseClauseExpressionType.toString(enclosingSymbol), expressionType.toString(enclosingSymbol)])); + } + } + } else { + var defaultSwitchClause = switchClause; + this.resolveAST(defaultSwitchClause.statements, false, context); + } + } + }; + + PullTypeResolver.prototype.resolveLabeledStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckLabeledStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckLabeledStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + var labelIdentifier = ast.identifier.valueText(); + + var breakableLabels = this.getEnclosingLabels(ast, true, false); + + var matchingLabel = TypeScript.ArrayUtilities.firstOrDefault(breakableLabels, function (s) { + return s.identifier.valueText() === labelIdentifier; + }); + if (matchingLabel) { + context.postDiagnostic(this.semanticInfoChain.duplicateIdentifierDiagnosticFromAST(ast.identifier, labelIdentifier, matchingLabel)); + } + + this.resolveAST(ast.statement, false, context); + }; + + PullTypeResolver.prototype.labelIsOnContinuableConstruct = function (statement) { + switch (statement.kind()) { + case 160 /* LabeledStatement */: + return this.labelIsOnContinuableConstruct(statement.statement); + + case 158 /* WhileStatement */: + case 154 /* ForStatement */: + case 155 /* ForInStatement */: + case 161 /* DoStatement */: + return true; + + default: + return false; + } + }; + + PullTypeResolver.prototype.resolveContinueStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckContinueStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.isIterationStatement = function (ast) { + switch (ast.kind()) { + case 154 /* ForStatement */: + case 155 /* ForInStatement */: + case 158 /* WhileStatement */: + case 161 /* DoStatement */: + return true; + } + + return false; + }; + + PullTypeResolver.prototype.isAnyFunctionExpressionOrDeclaration = function (ast) { + switch (ast.kind()) { + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + case 129 /* FunctionDeclaration */: + case 135 /* MemberFunctionDeclaration */: + case 241 /* FunctionPropertyAssignment */: + case 137 /* ConstructorDeclaration */: + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + return true; + } + + return false; + }; + + PullTypeResolver.prototype.inSwitchStatement = function (ast) { + while (ast) { + if (ast.kind() === 151 /* SwitchStatement */) { + return true; + } + + if (this.isAnyFunctionExpressionOrDeclaration(ast)) { + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inIterationStatement = function (ast, crossFunctions) { + while (ast) { + if (this.isIterationStatement(ast)) { + return true; + } + + if (!crossFunctions && this.isAnyFunctionExpressionOrDeclaration(ast)) { + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.getEnclosingLabels = function (ast, breakable, crossFunctions) { + var result = []; + + ast = ast.parent; + while (ast) { + if (ast.kind() === 160 /* LabeledStatement */) { + var labeledStatement = ast; + if (breakable) { + result.push(labeledStatement); + } else { + if (this.labelIsOnContinuableConstruct(labeledStatement.statement)) { + result.push(labeledStatement); + } + } + } + + if (!crossFunctions && this.isAnyFunctionExpressionOrDeclaration(ast)) { + break; + } + + ast = ast.parent; + } + + return result; + }; + + PullTypeResolver.prototype.typeCheckContinueStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + if (!this.inIterationStatement(ast, false)) { + if (this.inIterationStatement(ast, true)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.continue_statement_can_only_be_used_within_an_enclosing_iteration_statement)); + } + } else if (ast.identifier) { + var continuableLabels = this.getEnclosingLabels(ast, false, false); + + if (!TypeScript.ArrayUtilities.any(continuableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + var continuableLabels = this.getEnclosingLabels(ast, false, true); + + if (TypeScript.ArrayUtilities.any(continuableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_not_found)); + } + } + } + }; + + PullTypeResolver.prototype.resolveBreakStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckBreakStatement(ast, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.typeCheckBreakStatement = function (ast, context) { + this.setTypeChecked(ast, context); + + if (ast.identifier) { + var breakableLabels = this.getEnclosingLabels(ast, true, false); + + if (!TypeScript.ArrayUtilities.any(breakableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + var breakableLabels = this.getEnclosingLabels(ast, true, true); + if (TypeScript.ArrayUtilities.any(breakableLabels, function (s) { + return s.identifier.valueText() === ast.identifier.valueText(); + })) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_not_found)); + } + } + } else if (!this.inIterationStatement(ast, false) && !this.inSwitchStatement(ast)) { + if (this.inIterationStatement(ast, true)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Jump_target_cannot_cross_function_boundary)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement)); + } + } + }; + + PullTypeResolver.prototype.resolveAST = function (ast, isContextuallyTyped, context) { + if (!ast) { + return; + } + + var symbol = this.getSymbolForAST(ast, context); + if (symbol && symbol.isResolved) { + this.typeCheckAST(ast, isContextuallyTyped, context); + return symbol; + } + + if (ast.isExpression() && !isTypesOnlyLocation(ast)) { + return this.resolveExpressionAST(ast, isContextuallyTyped, context); + } + + var nodeType = ast.kind(); + + switch (nodeType) { + case 124 /* ArrayType */: + case 126 /* GenericType */: + case 122 /* ObjectType */: + case 127 /* TypeQuery */: + case 125 /* ConstructorType */: + case 123 /* FunctionType */: + return this.resolveTypeReference(ast, context); + + case 1 /* List */: + return this.resolveList(ast, context); + + case 2 /* SeparatedList */: + return this.resolveSeparatedList(ast, context); + + case 120 /* SourceUnit */: + return this.resolveSourceUnit(ast, context); + + case 132 /* EnumDeclaration */: + return this.resolveEnumDeclaration(ast, context); + + case 130 /* ModuleDeclaration */: + return this.resolveModuleDeclaration(ast, context); + + case 128 /* InterfaceDeclaration */: + return this.resolveInterfaceDeclaration(ast, context); + + case 131 /* ClassDeclaration */: + return this.resolveClassDeclaration(ast, context); + + case 224 /* VariableDeclaration */: + return this.resolveVariableDeclarationList(ast, context); + + case 136 /* MemberVariableDeclaration */: + return this.resolveMemberVariableDeclaration(ast, context); + + case 225 /* VariableDeclarator */: + return this.resolveVariableDeclarator(ast, context); + + case 141 /* PropertySignature */: + return this.resolvePropertySignature(ast, context); + + case 227 /* ParameterList */: + return this.resolveParameterList(ast, context); + + case 242 /* Parameter */: + return this.resolveParameter(ast, context); + + case 243 /* EnumElement */: + return this.resolveEnumElement(ast, context); + + case 232 /* EqualsValueClause */: + return this.resolveEqualsValueClause(ast, isContextuallyTyped, context); + + case 238 /* TypeParameter */: + return this.resolveTypeParameterDeclaration(ast, context); + + case 239 /* Constraint */: + return this.resolveConstraint(ast, context); + + case 133 /* ImportDeclaration */: + return this.resolveImportDeclaration(ast, context); + + case 240 /* SimplePropertyAssignment */: + return this.resolveSimplePropertyAssignment(ast, isContextuallyTyped, context); + + case 241 /* FunctionPropertyAssignment */: + return this.resolveFunctionPropertyAssignment(ast, isContextuallyTyped, context); + + case 11 /* IdentifierName */: + TypeScript.Debug.assert(isTypesOnlyLocation(ast)); + return this.resolveTypeNameExpression(ast, context); + + case 121 /* QualifiedName */: + return this.resolveQualifiedName(ast, context); + + case 137 /* ConstructorDeclaration */: + return this.resolveConstructorDeclaration(ast, context); + + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + return this.resolveAccessorDeclaration(ast, context); + + case 138 /* IndexMemberDeclaration */: + return this.resolveIndexMemberDeclaration(ast, context); + + case 144 /* IndexSignature */: + return this.resolveIndexSignature(ast, context); + + case 135 /* MemberFunctionDeclaration */: + return this.resolveMemberFunctionDeclaration(ast, context); + + case 142 /* CallSignature */: + return this.resolveCallSignature(ast, context); + + case 143 /* ConstructSignature */: + return this.resolveConstructSignature(ast, context); + + case 145 /* MethodSignature */: + return this.resolveMethodSignature(ast, context); + + case 129 /* FunctionDeclaration */: + return this.resolveAnyFunctionDeclaration(ast, context); + + case 244 /* TypeAnnotation */: + return this.resolveTypeAnnotation(ast, context); + + case 134 /* ExportAssignment */: + return this.resolveExportAssignmentStatement(ast, context); + + case 157 /* ThrowStatement */: + return this.resolveThrowStatement(ast, context); + + case 149 /* ExpressionStatement */: + return this.resolveExpressionStatement(ast, context); + + case 154 /* ForStatement */: + return this.resolveForStatement(ast, context); + + case 155 /* ForInStatement */: + return this.resolveForInStatement(ast, context); + + case 158 /* WhileStatement */: + return this.resolveWhileStatement(ast, context); + + case 161 /* DoStatement */: + return this.resolveDoStatement(ast, context); + + case 147 /* IfStatement */: + return this.resolveIfStatement(ast, context); + + case 235 /* ElseClause */: + return this.resolveElseClause(ast, context); + + case 146 /* Block */: + return this.resolveBlock(ast, context); + + case 148 /* VariableStatement */: + return this.resolveVariableStatement(ast, context); + + case 163 /* WithStatement */: + return this.resolveWithStatement(ast, context); + + case 159 /* TryStatement */: + return this.resolveTryStatement(ast, context); + + case 236 /* CatchClause */: + return this.resolveCatchClause(ast, context); + + case 237 /* FinallyClause */: + return this.resolveFinallyClause(ast, context); + + case 150 /* ReturnStatement */: + return this.resolveReturnStatement(ast, context); + + case 151 /* SwitchStatement */: + return this.resolveSwitchStatement(ast, context); + + case 153 /* ContinueStatement */: + return this.resolveContinueStatement(ast, context); + + case 152 /* BreakStatement */: + return this.resolveBreakStatement(ast, context); + + case 160 /* LabeledStatement */: + return this.resolveLabeledStatement(ast, context); + } + + return this.semanticInfoChain.anyTypeSymbol; + }; + + PullTypeResolver.prototype.resolveExpressionAST = function (ast, isContextuallyOrInferentiallyTyped, context) { + var expressionSymbol = this.resolveExpressionWorker(ast, isContextuallyOrInferentiallyTyped, context); + + if (isContextuallyOrInferentiallyTyped && context.isInferentiallyTyping()) { + return this.alterPotentialGenericFunctionTypeToInstantiatedFunctionTypeForTypeArgumentInference(expressionSymbol, context); + } else { + return expressionSymbol; + } + }; + + PullTypeResolver.prototype.resolveExpressionWorker = function (ast, isContextuallyTyped, context) { + switch (ast.kind()) { + case 215 /* ObjectLiteralExpression */: + return this.resolveObjectLiteralExpression(ast, isContextuallyTyped, context); + + case 11 /* IdentifierName */: + return this.resolveNameExpression(ast, context); + + case 212 /* MemberAccessExpression */: + return this.resolveMemberAccessExpression(ast, context); + + case 222 /* FunctionExpression */: + return this.resolveFunctionExpression(ast, isContextuallyTyped, context); + + case 219 /* SimpleArrowFunctionExpression */: + return this.resolveSimpleArrowFunctionExpression(ast, isContextuallyTyped, context); + + case 218 /* ParenthesizedArrowFunctionExpression */: + return this.resolveParenthesizedArrowFunctionExpression(ast, isContextuallyTyped, context); + + case 214 /* ArrayLiteralExpression */: + return this.resolveArrayLiteralExpression(ast, isContextuallyTyped, context); + + case 35 /* ThisKeyword */: + return this.resolveThisExpression(ast, context); + + case 50 /* SuperKeyword */: + return this.resolveSuperExpression(ast, context); + + case 213 /* InvocationExpression */: + return this.resolveInvocationExpression(ast, context); + + case 216 /* ObjectCreationExpression */: + return this.resolveObjectCreationExpression(ast, context); + + case 220 /* CastExpression */: + return this.resolveCastExpression(ast, context); + + case 13 /* NumericLiteral */: + return this.semanticInfoChain.numberTypeSymbol; + + case 14 /* StringLiteral */: + return this.semanticInfoChain.stringTypeSymbol; + + case 32 /* NullKeyword */: + return this.semanticInfoChain.nullTypeSymbol; + + case 37 /* TrueKeyword */: + case 24 /* FalseKeyword */: + return this.semanticInfoChain.booleanTypeSymbol; + + case 172 /* VoidExpression */: + return this.resolveVoidExpression(ast, context); + + case 174 /* AssignmentExpression */: + return this.resolveAssignmentExpression(ast, context); + + case 167 /* LogicalNotExpression */: + return this.resolveLogicalNotExpression(ast, context); + + case 193 /* NotEqualsWithTypeConversionExpression */: + case 192 /* EqualsWithTypeConversionExpression */: + case 194 /* EqualsExpression */: + case 195 /* NotEqualsExpression */: + case 196 /* LessThanExpression */: + case 198 /* LessThanOrEqualExpression */: + case 199 /* GreaterThanOrEqualExpression */: + case 197 /* GreaterThanExpression */: + return this.resolveLogicalOperation(ast, context); + + case 208 /* AddExpression */: + case 175 /* AddAssignmentExpression */: + return this.resolveBinaryAdditionOperation(ast, context); + + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + case 166 /* BitwiseNotExpression */: + case 168 /* PreIncrementExpression */: + case 169 /* PreDecrementExpression */: + return this.resolveUnaryArithmeticOperation(ast, context); + + case 210 /* PostIncrementExpression */: + case 211 /* PostDecrementExpression */: + return this.resolvePostfixUnaryExpression(ast, context); + + case 209 /* SubtractExpression */: + case 205 /* MultiplyExpression */: + case 206 /* DivideExpression */: + case 207 /* ModuloExpression */: + case 189 /* BitwiseOrExpression */: + case 191 /* BitwiseAndExpression */: + case 202 /* LeftShiftExpression */: + case 203 /* SignedRightShiftExpression */: + case 204 /* UnsignedRightShiftExpression */: + case 190 /* BitwiseExclusiveOrExpression */: + case 181 /* ExclusiveOrAssignmentExpression */: + case 183 /* LeftShiftAssignmentExpression */: + case 184 /* SignedRightShiftAssignmentExpression */: + case 185 /* UnsignedRightShiftAssignmentExpression */: + case 176 /* SubtractAssignmentExpression */: + case 177 /* MultiplyAssignmentExpression */: + case 178 /* DivideAssignmentExpression */: + case 179 /* ModuloAssignmentExpression */: + case 182 /* OrAssignmentExpression */: + case 180 /* AndAssignmentExpression */: + return this.resolveBinaryArithmeticExpression(ast, context); + + case 221 /* ElementAccessExpression */: + return this.resolveElementAccessExpression(ast, context); + + case 187 /* LogicalOrExpression */: + return this.resolveLogicalOrExpression(ast, isContextuallyTyped, context); + + case 188 /* LogicalAndExpression */: + return this.resolveLogicalAndExpression(ast, context); + + case 171 /* TypeOfExpression */: + return this.resolveTypeOfExpression(ast, context); + + case 170 /* DeleteExpression */: + return this.resolveDeleteExpression(ast, context); + + case 186 /* ConditionalExpression */: + return this.resolveConditionalExpression(ast, isContextuallyTyped, context); + + case 12 /* RegularExpressionLiteral */: + return this.resolveRegularExpressionLiteral(); + + case 217 /* ParenthesizedExpression */: + return this.resolveParenthesizedExpression(ast, context); + + case 200 /* InstanceOfExpression */: + return this.resolveInstanceOfExpression(ast, context); + + case 173 /* CommaExpression */: + return this.resolveCommaExpression(ast, context); + + case 201 /* InExpression */: + return this.resolveInExpression(ast, context); + + case 223 /* OmittedExpression */: + return this.semanticInfoChain.undefinedTypeSymbol; + } + + TypeScript.Debug.fail("resolveExpressionASTWorker: Missing expression kind: " + TypeScript.SyntaxKind[ast.kind()]); + }; + + PullTypeResolver.prototype.typeCheckAST = function (ast, isContextuallyTyped, context) { + if (!this.canTypeCheckAST(ast, context)) { + return; + } + + var nodeType = ast.kind(); + switch (nodeType) { + case 120 /* SourceUnit */: + this.typeCheckSourceUnit(ast, context); + return; + + case 132 /* EnumDeclaration */: + this.typeCheckEnumDeclaration(ast, context); + return; + + case 130 /* ModuleDeclaration */: + this.typeCheckModuleDeclaration(ast, context); + return; + + case 128 /* InterfaceDeclaration */: + this.typeCheckInterfaceDeclaration(ast, context); + return; + + case 131 /* ClassDeclaration */: + this.typeCheckClassDeclaration(ast, context); + return; + + case 243 /* EnumElement */: + this.typeCheckEnumElement(ast, context); + return; + + case 136 /* MemberVariableDeclaration */: + this.typeCheckMemberVariableDeclaration(ast, context); + return; + + case 225 /* VariableDeclarator */: + this.typeCheckVariableDeclarator(ast, context); + return; + + case 141 /* PropertySignature */: + this.typeCheckPropertySignature(ast, context); + return; + + case 242 /* Parameter */: + this.typeCheckParameter(ast, context); + return; + + case 133 /* ImportDeclaration */: + this.typeCheckImportDeclaration(ast, context); + return; + + case 215 /* ObjectLiteralExpression */: + this.resolveObjectLiteralExpression(ast, isContextuallyTyped, context); + return; + + case 241 /* FunctionPropertyAssignment */: + this.typeCheckFunctionPropertyAssignment(ast, isContextuallyTyped, context); + return; + + case 11 /* IdentifierName */: + if (isTypesOnlyLocation(ast)) { + this.resolveTypeNameExpression(ast, context); + } else { + this.resolveNameExpression(ast, context); + } + return; + + case 212 /* MemberAccessExpression */: + this.resolveMemberAccessExpression(ast, context); + return; + + case 121 /* QualifiedName */: + this.resolveQualifiedName(ast, context); + return; + + case 222 /* FunctionExpression */: + this.typeCheckFunctionExpression(ast, isContextuallyTyped, context); + return; + + case 137 /* ConstructorDeclaration */: + this.typeCheckConstructorDeclaration(ast, context); + return; + + case 139 /* GetAccessor */: + case 140 /* SetAccessor */: + this.typeCheckAccessorDeclaration(ast, context); + return; + + case 135 /* MemberFunctionDeclaration */: + this.typeCheckMemberFunctionDeclaration(ast, context); + return; + + case 145 /* MethodSignature */: + this.typeCheckMethodSignature(ast, context); + return; + + case 144 /* IndexSignature */: + this.typeCheckIndexSignature(ast, context); + break; + + case 142 /* CallSignature */: + this.typeCheckCallSignature(ast, context); + return; + + case 143 /* ConstructSignature */: + this.typeCheckConstructSignature(ast, context); + return; + + case 129 /* FunctionDeclaration */: { + var funcDecl = ast; + this.typeCheckAnyFunctionDeclaration(funcDecl, TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */), funcDecl.identifier, funcDecl.callSignature.typeParameterList, funcDecl.callSignature.parameterList, TypeScript.ASTHelpers.getType(funcDecl), funcDecl.block, context); + return; + } + + case 219 /* SimpleArrowFunctionExpression */: + this.typeCheckSimpleArrowFunctionExpression(ast, isContextuallyTyped, context); + return; + + case 218 /* ParenthesizedArrowFunctionExpression */: + this.typeCheckParenthesizedArrowFunctionExpression(ast, isContextuallyTyped, context); + return; + + case 214 /* ArrayLiteralExpression */: + this.resolveArrayLiteralExpression(ast, isContextuallyTyped, context); + return; + + case 213 /* InvocationExpression */: + this.typeCheckInvocationExpression(ast, context); + return; + + case 216 /* ObjectCreationExpression */: + this.typeCheckObjectCreationExpression(ast, context); + return; + + case 150 /* ReturnStatement */: + this.resolveReturnStatement(ast, context); + return; + + default: + TypeScript.Debug.assert(false, "Failure nodeType: " + TypeScript.SyntaxKind[ast.kind()] + ". Implement typeCheck when symbol is set for the ast as part of resolution."); + } + }; + + PullTypeResolver.prototype.processPostTypeCheckWorkItems = function (context) { + while (this.postTypeCheckWorkitems.length) { + var ast = this.postTypeCheckWorkitems.pop(); + this.postTypeCheck(ast, context); + } + }; + + PullTypeResolver.prototype.postTypeCheck = function (ast, context) { + var nodeType = ast.kind(); + + switch (nodeType) { + case 242 /* Parameter */: + case 225 /* VariableDeclarator */: + this.postTypeCheckVariableDeclaratorOrParameter(ast, context); + return; + + case 131 /* ClassDeclaration */: + this.postTypeCheckClassDeclaration(ast, context); + return; + + case 129 /* FunctionDeclaration */: + this.postTypeCheckFunctionDeclaration(ast, context); + return; + + case 130 /* ModuleDeclaration */: + this.postTypeCheckModuleDeclaration(ast, context); + return; + + case 132 /* EnumDeclaration */: + this.postTypeCheckEnumDeclaration(ast, context); + return; + + case 133 /* ImportDeclaration */: + this.postTypeCheckImportDeclaration(ast, context); + return; + + case 11 /* IdentifierName */: + this.postTypeCheckNameExpression(ast, context); + return; + + default: + TypeScript.Debug.assert(false, "Implement postTypeCheck clause to handle the postTypeCheck work, nodeType: " + TypeScript.SyntaxKind[ast.kind()]); + } + }; + + PullTypeResolver.prototype.resolveRegularExpressionLiteral = function () { + if (this.cachedRegExpInterfaceType()) { + return this.cachedRegExpInterfaceType(); + } else { + return this.semanticInfoChain.anyTypeSymbol; + } + }; + + PullTypeResolver.prototype.postTypeCheckNameExpression = function (nameAST, context) { + this.checkThisCaptureVariableCollides(nameAST, false, context); + }; + + PullTypeResolver.prototype.typeCheckNameExpression = function (nameAST, context) { + this.setTypeChecked(nameAST, context); + this.checkNameForCompilerGeneratedDeclarationCollision(nameAST, false, nameAST, context); + }; + + PullTypeResolver.prototype.resolveNameExpression = function (nameAST, context) { + var nameSymbol = this.getSymbolForAST(nameAST, context); + var foundCached = nameSymbol !== null; + + if (!foundCached || this.canTypeCheckAST(nameAST, context)) { + if (this.canTypeCheckAST(nameAST, context)) { + this.typeCheckNameExpression(nameAST, context); + } + nameSymbol = this.computeNameExpression(nameAST, context); + } + + this.resolveDeclaredSymbol(nameSymbol, context); + + if (nameSymbol && (nameSymbol.type !== this.semanticInfoChain.anyTypeSymbol || nameSymbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { + this.setSymbolForAST(nameAST, nameSymbol, context); + } + + return nameSymbol; + }; + + PullTypeResolver.prototype.isInEnumDecl = function (decl) { + if (decl.kind & 64 /* Enum */) { + return true; + } + + var declPath = decl.getParentPath(); + + var disallowedKinds = 164 /* SomeContainer */ | 58728795 /* SomeType */; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + + if (decl.kind & 64 /* Enum */) { + return true; + } + + if (decl.kind & disallowedKinds) { + return false; + } + } + return false; + }; + + PullTypeResolver.prototype.getSomeInnermostFunctionScopeDecl = function (declPath) { + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + if (decl.kind & 1032192 /* SomeFunction */) { + return decl; + } + } + + return null; + }; + + PullTypeResolver.prototype.isFromFunctionScope = function (nameSymbol, functionScopeDecl) { + var _this = this; + return TypeScript.ArrayUtilities.any(nameSymbol.getDeclarations(), function (nameSymbolDecl) { + return _this.getSomeInnermostFunctionScopeDecl(nameSymbolDecl.getParentPath()) === functionScopeDecl; + }); + }; + + PullTypeResolver.prototype.findConstructorDeclOfEnclosingType = function (decl) { + var current = decl; + while (current) { + if (TypeScript.hasFlag(current.kind, 4096 /* Property */)) { + var parentDecl = current.getParentDecl(); + if (TypeScript.hasFlag(parentDecl.kind, 8 /* Class */)) { + return TypeScript.ArrayUtilities.lastOrDefault(parentDecl.getChildDecls(), function (decl) { + return TypeScript.hasFlag(decl.kind, 32768 /* ConstructorMethod */); + }); + } + } + + if (TypeScript.hasFlag(current.kind, 164 /* SomeContainer */)) { + return null; + } + + current = current.getParentDecl(); + } + return null; + }; + + PullTypeResolver.prototype.checkNameAsPartOfInitializerExpressionForInstanceMemberVariable = function (nameAST, nameSymbol, context) { + var id = nameAST.valueText(); + if (id.length === 0) { + return false; + } + + var memberVariableDeclarationAST = TypeScript.ASTHelpers.getEnclosingMemberVariableDeclaration(nameAST); + if (memberVariableDeclarationAST) { + var memberVariableDecl = this.semanticInfoChain.getDeclForAST(memberVariableDeclarationAST); + if (!TypeScript.hasFlag(memberVariableDecl.flags, 16 /* Static */)) { + var constructorDecl = this.findConstructorDeclOfEnclosingType(memberVariableDecl); + + if (constructorDecl) { + var childDecls = constructorDecl.searchChildDecls(id, 68147712 /* SomeValue */); + if (childDecls.length) { + if (TypeScript.PullHelpers.isSymbolDeclaredInScopeChain(nameSymbol, constructorDecl.getSymbol().getContainer())) { + var memberVariableSymbol = memberVariableDecl.getSymbol(); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, [memberVariableSymbol.getScopedName(constructorDecl.getSymbol()), nameAST.text()])); + return true; + } + } + } + } + } + return false; + }; + + PullTypeResolver.prototype.computeNameExpression = function (nameAST, context) { + var id = nameAST.valueText(); + if (id.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var nameSymbol = null; + var enclosingDecl = this.getEnclosingDeclForAST(nameAST); + + if (TypeScript.hasFlag(enclosingDecl.flags, 8388608 /* PropertyParameter */)) { + var valueDecl = enclosingDecl.getValueDecl(); + if (valueDecl && TypeScript.hasFlag(valueDecl.kind, 2048 /* Parameter */)) { + enclosingDecl = valueDecl; + } + } + + var isDeclarationASTOrDeclarationNameAST = TypeScript.ASTHelpers.isDeclarationASTOrDeclarationNameAST(nameAST); + if (isDeclarationASTOrDeclarationNameAST) { + nameSymbol = this.semanticInfoChain.getDeclForAST(nameAST.parent).getSymbol(); + } + + var declPath = enclosingDecl.getParentPath(); + + if (!nameSymbol) { + var searchKind = 68147712 /* SomeValue */; + + if (!this.isInEnumDecl(enclosingDecl)) { + searchKind = searchKind & ~(67108864 /* EnumMember */); + } + + var nameSymbol = this.getSymbolFromDeclPath(id, declPath, searchKind); + } + + if (id === "arguments") { + var functionScopeDecl = this.getSomeInnermostFunctionScopeDecl(declPath); + if (functionScopeDecl) { + if (!nameSymbol || !this.isFromFunctionScope(nameSymbol, functionScopeDecl)) { + nameSymbol = this.cachedFunctionArgumentsSymbol(); + this.resolveDeclaredSymbol(this.cachedIArgumentsInterfaceType(), context); + } + } + } + + var aliasSymbol = null; + if (nameSymbol && nameSymbol.isAlias() && !isDeclarationASTOrDeclarationNameAST) { + aliasSymbol = nameSymbol; + if (!this.inTypeQuery(nameAST)) { + aliasSymbol.setIsUsedAsValue(); + } + + this.resolveDeclaredSymbol(nameSymbol, context); + + this.resolveDeclaredSymbol(aliasSymbol.assignedValue(), context); + this.resolveDeclaredSymbol(aliasSymbol.assignedContainer(), context); + + nameSymbol = aliasSymbol.getExportAssignedValueSymbol(); + if (!nameSymbol) { + aliasSymbol = null; + } + } + + if (!nameSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [nameAST.text()])); + return this.getNewErrorTypeSymbol(id); + } else if (this.checkNameAsPartOfInitializerExpressionForInstanceMemberVariable(nameAST, nameSymbol, context)) { + return this.getNewErrorTypeSymbol(id); + } + + var nameDeclaration = nameSymbol.getDeclarations()[0]; + var nameParentDecl = nameDeclaration.getParentDecl(); + if (nameParentDecl && (nameParentDecl.kind & 1032192 /* SomeFunction */) && (nameParentDecl.flags & 33554432 /* HasDefaultArgs */)) { + var enclosingFunctionAST = this.semanticInfoChain.getASTForDecl(nameParentDecl); + var currentParameterIndex = this.getCurrentParameterIndexForFunction(nameAST, enclosingFunctionAST); + + var parameterList = TypeScript.ASTHelpers.getParameterList(enclosingFunctionAST); + + if (currentParameterIndex >= 0) { + var matchingParameter; + if (parameterList) { + for (var i = 0; i <= currentParameterIndex; i++) { + var candidateParameter = parameterList.parameters.nonSeparatorAt(i); + if (candidateParameter && candidateParameter.identifier.valueText() === id) { + matchingParameter = candidateParameter; + break; + } + } + } + + if (!matchingParameter) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, [parameterList.parameters.nonSeparatorAt(currentParameterIndex).identifier.text(), nameAST.text()])); + return this.getNewErrorTypeSymbol(id); + } else if (matchingParameter === TypeScript.ASTHelpers.getEnclosingParameterForInitializer(nameAST)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Parameter_0_cannot_be_referenced_in_its_initializer, [parameterList.parameters.nonSeparatorAt(currentParameterIndex).identifier.text()])); + return this.getNewErrorTypeSymbol(id); + } + } + } + + if (aliasSymbol) { + this.semanticInfoChain.setAliasSymbolForAST(nameAST, aliasSymbol); + } + + return nameSymbol; + }; + + PullTypeResolver.prototype.getCurrentParameterIndexForFunction = function (parameter, funcDecl) { + var parameterList = TypeScript.ASTHelpers.getParameterList(funcDecl); + if (parameterList) { + while (parameter && parameter.parent) { + if (parameter.parent.parent === parameterList) { + return parameterList.parameters.nonSeparatorIndexOf(parameter); + } + + parameter = parameter.parent; + } + } + + return -1; + }; + + PullTypeResolver.prototype.resolveMemberAccessExpression = function (dottedNameAST, context) { + return this.resolveDottedNameExpression(dottedNameAST, dottedNameAST.expression, dottedNameAST.name, context); + }; + + PullTypeResolver.prototype.resolveDottedNameExpression = function (dottedNameAST, expression, name, context) { + var symbol = this.getSymbolForAST(dottedNameAST, context); + var foundCached = symbol !== null; + + if (!foundCached || this.canTypeCheckAST(dottedNameAST, context)) { + var canTypeCheckDottedNameAST = this.canTypeCheckAST(dottedNameAST, context); + if (canTypeCheckDottedNameAST) { + this.setTypeChecked(dottedNameAST, context); + } + + symbol = this.computeDottedNameExpression(expression, name, context, canTypeCheckDottedNameAST); + } + + this.resolveDeclaredSymbol(symbol, context); + + if (symbol && (symbol.type !== this.semanticInfoChain.anyTypeSymbol || symbol.anyDeclHasFlag(16777216 /* IsAnnotatedWithAny */ | 1 /* Exported */))) { + this.setSymbolForAST(dottedNameAST, symbol, context); + this.setSymbolForAST(name, symbol, context); + } + + return symbol; + }; + + PullTypeResolver.prototype.computeDottedNameExpression = function (expression, name, context, checkSuperPrivateAndStaticAccess) { + var rhsName = name.valueText(); + if (rhsName.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var lhs = this.resolveAST(expression, false, context); + return this.computeDottedNameExpressionFromLHS(lhs, expression, name, context, checkSuperPrivateAndStaticAccess); + }; + + PullTypeResolver.prototype.computeDottedNameExpressionFromLHS = function (lhs, expression, name, context, checkSuperPrivateAndStaticAccess) { + var rhsName = name.valueText(); + if (rhsName.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var lhsType = lhs.type; + + if (lhs.isAlias()) { + var lhsAlias = lhs; + if (!this.inTypeQuery(expression)) { + lhsAlias.setIsUsedAsValue(); + } + lhsType = lhsAlias.getExportAssignedTypeSymbol(); + } + + if (lhsType.isAlias()) { + lhsType = lhsType.getExportAssignedTypeSymbol(); + } + + if (!lhsType) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.Could_not_find_enclosing_symbol_for_dotted_name_0, [name.text()])); + return this.getNewErrorTypeSymbol(); + } + + if (!lhsType.isResolved) { + var potentiallySpecializedType = this.resolveDeclaredSymbol(lhsType, context); + + if (potentiallySpecializedType !== lhsType) { + if (!lhs.isType()) { + context.setTypeInContext(lhs, potentiallySpecializedType); + } + + lhsType = potentiallySpecializedType; + } + } + + if (lhsType.isContainer() && !lhsType.isAlias() && !lhsType.isEnum()) { + var instanceSymbol = lhsType.getInstanceSymbol(); + + if (instanceSymbol) { + lhsType = instanceSymbol.type; + } + } + + var originalLhsTypeForErrorReporting = lhsType; + + lhsType = this.getApparentType(lhsType).widenedType(this, expression, context); + + if (this.isAnyOrEquivalent(lhsType)) { + return lhsType; + } + + var nameSymbol = this._getNamedPropertySymbolOfAugmentedType(rhsName, lhsType); + + if (!nameSymbol) { + if (lhsType.kind === 32 /* DynamicModule */) { + var container = lhsType; + var associatedInstance = container.getInstanceSymbol(); + + if (associatedInstance) { + var instanceType = associatedInstance.type; + + nameSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, instanceType); + } + } else { + var associatedType = lhsType.getAssociatedContainerType(); + + if (associatedType && !associatedType.isClass()) { + nameSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, associatedType); + } + } + + if (!nameSymbol) { + var enclosingDecl = this.getEnclosingDeclForAST(expression); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.The_property_0_does_not_exist_on_value_of_type_1, [name.text(), originalLhsTypeForErrorReporting.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + return this.getNewErrorTypeSymbol(rhsName); + } + } + + if (checkSuperPrivateAndStaticAccess) { + this.checkForSuperMemberAccess(expression, name, nameSymbol, context) || this.checkForPrivateMemberAccess(name, lhsType, nameSymbol, context); + } + + return nameSymbol; + }; + + PullTypeResolver.prototype.resolveTypeNameExpression = function (nameAST, context) { + var typeNameSymbol = this.getSymbolForAST(nameAST, context); + + if (!typeNameSymbol || !typeNameSymbol.isType() || this.canTypeCheckAST(nameAST, context)) { + if (this.canTypeCheckAST(nameAST, context)) { + this.setTypeChecked(nameAST, context); + } + typeNameSymbol = this.computeTypeNameExpression(nameAST, context); + this.setSymbolForAST(nameAST, typeNameSymbol, context); + } + + this.resolveDeclaredSymbol(typeNameSymbol, context); + + return typeNameSymbol; + }; + + PullTypeResolver.prototype.computeTypeNameExpression = function (nameAST, context) { + var id = nameAST.valueText(); + if (id.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var enclosingDecl = this.getEnclosingDeclForAST(nameAST); + + var declPath = enclosingDecl.getParentPath(); + + var onLeftOfDot = this.isLeftSideOfQualifiedName(nameAST); + + var kindToCheckFirst = onLeftOfDot ? 164 /* SomeContainer */ : 58728795 /* SomeType */; + var kindToCheckSecond = onLeftOfDot ? 58728795 /* SomeType */ : 164 /* SomeContainer */; + + var typeNameSymbol = this.getSymbolFromDeclPath(id, declPath, kindToCheckFirst); + + if (!typeNameSymbol) { + typeNameSymbol = this.getSymbolFromDeclPath(id, declPath, kindToCheckSecond); + } + + if (!typeNameSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Could_not_find_symbol_0, [nameAST.text()])); + return this.getNewErrorTypeSymbol(id); + } + + var typeNameSymbolAlias = null; + if (typeNameSymbol.isAlias()) { + typeNameSymbolAlias = typeNameSymbol; + this.resolveDeclaredSymbol(typeNameSymbol, context); + + var aliasedType = typeNameSymbolAlias.getExportAssignedTypeSymbol(); + + this.resolveDeclaredSymbol(aliasedType, context); + } + + if (typeNameSymbol.isTypeParameter()) { + if (this.isInStaticMemberContext(enclosingDecl)) { + var parentDecl = typeNameSymbol.getDeclarations()[0].getParentDecl(); + + if (parentDecl.kind === 8 /* Class */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(nameAST, TypeScript.DiagnosticCode.Static_members_cannot_reference_class_type_parameters)); + return this.getNewErrorTypeSymbol(); + } + } + } + + if (!typeNameSymbol.isGeneric() && (typeNameSymbol.isClass() || typeNameSymbol.isInterface())) { + typeNameSymbol = TypeScript.PullTypeReferenceSymbol.createTypeReference(typeNameSymbol); + } + + return typeNameSymbol; + }; + + PullTypeResolver.prototype.isInStaticMemberContext = function (decl) { + while (decl) { + if (TypeScript.hasFlag(decl.kind, 1032192 /* SomeFunction */ | 4096 /* Property */) && TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + return true; + } + + if (TypeScript.hasFlag(decl.kind, 164 /* SomeContainer */)) { + return false; + } + + decl = decl.getParentDecl(); + } + + return false; + }; + + PullTypeResolver.prototype.isLeftSideOfQualifiedName = function (ast) { + return ast && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.left === ast; + }; + + PullTypeResolver.prototype.resolveGenericTypeReference = function (genericTypeAST, context) { + var _this = this; + var genericTypeSymbol = this.resolveAST(genericTypeAST.name, false, context).type; + + if (genericTypeSymbol.isError()) { + return genericTypeSymbol; + } + + if (!genericTypeSymbol.inResolution && !genericTypeSymbol.isResolved) { + this.resolveDeclaredSymbol(genericTypeSymbol, context); + } + + if (genericTypeSymbol.isAlias()) { + if (this.inClassExtendsHeritageClause(genericTypeAST) && !this.inTypeArgumentList(genericTypeAST)) { + genericTypeSymbol.setIsUsedAsValue(); + } + genericTypeSymbol = genericTypeSymbol.getExportAssignedTypeSymbol(); + } + + var typeParameters = genericTypeSymbol.getTypeParameters(); + if (typeParameters.length === 0) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Type_0_does_not_have_type_parameters, [genericTypeSymbol.toString()])); + return this.getNewErrorTypeSymbol(); + } + + var typeArgs = []; + + if (genericTypeAST.typeArgumentList && genericTypeAST.typeArgumentList.typeArguments.nonSeparatorCount()) { + for (var i = 0; i < genericTypeAST.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { + typeArgs[i] = this.resolveTypeReference(genericTypeAST.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + + if (typeArgs[i].isError()) { + typeArgs[i] = this.semanticInfoChain.anyTypeSymbol; + } + } + } + + if (typeArgs.length && typeArgs.length !== typeParameters.length) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Generic_type_0_requires_1_type_argument_s, [genericTypeSymbol.toString(), genericTypeSymbol.getTypeParameters().length])); + return this.getNewErrorTypeSymbol(); + } + + if (!genericTypeSymbol.isResolved) { + var typeDecls = genericTypeSymbol.getDeclarations(); + var childDecls = null; + + for (var i = 0; i < typeDecls.length; i++) { + childDecls = typeDecls[i].getChildDecls(); + + for (var j = 0; j < childDecls.length; j++) { + childDecls[j].ensureSymbolIsBound(); + } + } + } + + var specializedSymbol = this.createInstantiatedType(genericTypeSymbol, typeArgs); + + var upperBound = null; + + typeParameters = specializedSymbol.getTypeParameters(); + + var typeConstraintSubstitutionMap = []; + + var instantiatedSubstitutionMap = specializedSymbol.getTypeParameterArgumentMap(); + + for (var i = 0; i < typeParameters.length; i++) { + typeConstraintSubstitutionMap[typeParameters[i].pullSymbolID] = typeParameters[i]; + } + + for (var id in instantiatedSubstitutionMap) { + typeConstraintSubstitutionMap[id] = instantiatedSubstitutionMap[id]; + } + + for (var iArg = 0; (iArg < typeArgs.length) && (iArg < typeParameters.length); iArg++) { + var typeArg = typeArgs[iArg]; + var typeParameter = typeParameters[iArg]; + var typeConstraint = typeParameter.getConstraint(); + + typeConstraintSubstitutionMap[typeParameter.pullSymbolID] = typeArg; + + if (typeConstraint) { + if (typeConstraint.isTypeParameter()) { + for (var j = 0; j < typeParameters.length && j < typeArgs.length; j++) { + if (typeParameters[j] === typeConstraint) { + typeConstraint = typeArgs[j]; + } + } + } else if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeConstraintSubstitutionMap); + } + + if (typeArg.isTypeParameter()) { + upperBound = typeArg.getConstraint(); + + if (upperBound) { + typeArg = upperBound; + } + } + + if (typeArg.inResolution || (typeArg.isTypeReference() && typeArg.referencedTypeSymbol.inResolution)) { + return specializedSymbol; + } + + if (context.canTypeCheckAST(genericTypeAST)) { + this.typeCheckCallBacks.push(function (context) { + if (!_this.sourceIsAssignableToTarget(typeArg, typeConstraint, genericTypeAST, context)) { + var enclosingSymbol = _this.getEnclosingSymbolForAST(genericTypeAST); + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(genericTypeAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [typeArg.toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameter.toString(enclosingSymbol, true)])); + } + }); + } + } + } + + return specializedSymbol; + }; + + PullTypeResolver.prototype.resolveQualifiedName = function (dottedNameAST, context) { + if (this.inTypeQuery(dottedNameAST)) { + return this.resolveDottedNameExpression(dottedNameAST, dottedNameAST.left, dottedNameAST.right, context).type; + } + + var symbol = this.getSymbolForAST(dottedNameAST, context); + if (!symbol || this.canTypeCheckAST(dottedNameAST, context)) { + var canTypeCheck = this.canTypeCheckAST(dottedNameAST, context); + if (canTypeCheck) { + this.setTypeChecked(dottedNameAST, context); + } + + symbol = this.computeQualifiedName(dottedNameAST, context); + this.setSymbolForAST(dottedNameAST, symbol, context); + } + + this.resolveDeclaredSymbol(symbol, context); + + return symbol; + }; + + PullTypeResolver.prototype.isLastNameOfModuleNameModuleReference = function (ast) { + return ast.kind() === 11 /* IdentifierName */ && ast.parent && ast.parent.kind() === 121 /* QualifiedName */ && ast.parent.right === ast && ast.parent.parent && ast.parent.parent.kind() === 246 /* ModuleNameModuleReference */; + }; + + PullTypeResolver.prototype.computeQualifiedName = function (dottedNameAST, context) { + var rhsName = dottedNameAST.right.valueText(); + if (rhsName.length === 0) { + return this.semanticInfoChain.anyTypeSymbol; + } + + var enclosingDecl = this.getEnclosingDeclForAST(dottedNameAST); + var lhs = this.resolveAST(dottedNameAST.left, false, context); + + var lhsType = lhs.isAlias() ? lhs.getExportAssignedContainerSymbol() : lhs.type; + + if (this.inClassExtendsHeritageClause(dottedNameAST) && !this.inTypeArgumentList(dottedNameAST)) { + if (lhs.isAlias()) { + lhs.setIsUsedAsValue(); + } + } + + if (!lhsType) { + return this.getNewErrorTypeSymbol(); + } + + if (this.isAnyOrEquivalent(lhsType)) { + return lhsType; + } + + var onLeftOfDot = this.isLeftSideOfQualifiedName(dottedNameAST); + var isNameOfModule = dottedNameAST.parent.kind() === 130 /* ModuleDeclaration */ && dottedNameAST.parent.name === dottedNameAST; + + var memberKind = (onLeftOfDot || isNameOfModule) ? 164 /* SomeContainer */ : 58728795 /* SomeType */; + + var childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, lhsType); + + if (!childTypeSymbol && !isNameOfModule && this.isLastNameOfModuleNameModuleReference(dottedNameAST.right)) { + childTypeSymbol = this.getNamedPropertySymbol(rhsName, 68147712 /* SomeValue */, lhsType); + } + + if (!childTypeSymbol && lhsType.isContainer()) { + var exportedContainer = lhsType.getExportAssignedContainerSymbol(); + + if (exportedContainer) { + childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, exportedContainer); + } + } + + if (!childTypeSymbol && enclosingDecl) { + var parentDecl = enclosingDecl; + + while (parentDecl) { + if (parentDecl.kind & 164 /* SomeContainer */) { + break; + } + + parentDecl = parentDecl.getParentDecl(); + } + + if (parentDecl) { + var enclosingSymbolType = parentDecl.getSymbol().type; + + if (enclosingSymbolType === lhsType) { + childTypeSymbol = this.getNamedPropertySymbol(rhsName, memberKind, lhsType); + } + } + } + + if (!childTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(dottedNameAST.right, TypeScript.DiagnosticCode.The_property_0_does_not_exist_on_value_of_type_1, [dottedNameAST.right.text(), lhsType.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + return this.getNewErrorTypeSymbol(rhsName); + } + + return childTypeSymbol; + }; + + PullTypeResolver.prototype.shouldContextuallyTypeAnyFunctionExpression = function (functionExpressionAST, typeParameters, parameters, returnTypeAnnotation, context) { + if (typeParameters && typeParameters.typeParameters.nonSeparatorCount() > 0) { + return false; + } + + if (returnTypeAnnotation) { + return false; + } + + if (parameters) { + for (var i = 0, n = parameters.length; i < n; i++) { + if (parameters.typeAt(i)) { + return false; + } + } + } + + var contextualFunctionTypeSymbol = context.getContextualType(); + + if (contextualFunctionTypeSymbol) { + this.resolveDeclaredSymbol(contextualFunctionTypeSymbol, context); + var callSignatures = contextualFunctionTypeSymbol.getCallSignatures(); + var exactlyOneCallSignature = callSignatures && callSignatures.length === 1; + if (!exactlyOneCallSignature) { + return false; + } + + var callSignatureIsGeneric = callSignatures[0].getTypeParameters().length > 0; + return !callSignatureIsGeneric; + } + + return false; + }; + + PullTypeResolver.prototype.resolveAnyFunctionExpression = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context) { + var funcDeclSymbol = null; + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + TypeScript.Debug.assert(functionDecl); + + if (functionDecl && functionDecl.hasSymbol()) { + funcDeclSymbol = functionDecl.getSymbol(); + if (funcDeclSymbol.isResolved || funcDeclSymbol.inResolution) { + return funcDeclSymbol; + } + } + + funcDeclSymbol = functionDecl.getSymbol(); + TypeScript.Debug.assert(funcDeclSymbol); + + var funcDeclType = funcDeclSymbol.type; + var signature = funcDeclType.getCallSignatures()[0]; + funcDeclSymbol.startResolving(); + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + var assigningFunctionSignature = null; + if (isContextuallyTyped && this.shouldContextuallyTypeAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, context)) { + assigningFunctionSignature = context.getContextualType().getCallSignatures()[0]; + } + + this.resolveAnyFunctionExpressionParameters(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context); + + if (returnTypeAnnotation) { + signature.returnType = this.resolveTypeReference(returnTypeAnnotation, context); + } else { + if (assigningFunctionSignature) { + var returnType = assigningFunctionSignature.returnType; + + if (returnType) { + context.propagateContextualType(returnType); + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, bodyExpression, signature, true, functionDecl, context); + context.popAnyContextualType(); + } else { + signature.returnType = this.semanticInfoChain.anyTypeSymbol; + + if (this.compilationSettings.noImplicitAny()) { + var functionExpressionName = functionDecl.getFunctionExpressionName(); + + if (functionExpressionName != "") { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode._0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type, [functionExpressionName])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)); + } + } + } + } else { + this.resolveFunctionBodyReturnTypes(funcDeclAST, block, bodyExpression, signature, false, functionDecl, context); + } + } + + context.setTypeInContext(funcDeclSymbol, funcDeclType); + funcDeclSymbol.setResolved(); + + if (this.canTypeCheckAST(funcDeclAST, context)) { + this.typeCheckAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context); + } + + return funcDeclSymbol; + }; + + PullTypeResolver.prototype.resolveAnyFunctionExpressionParameters = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context) { + if (!parameters) { + return; + } + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var contextParams = []; + + var assigningFunctionSignature = null; + if (isContextuallyTyped && this.shouldContextuallyTypeAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, context)) { + assigningFunctionSignature = context.getContextualType().getCallSignatures()[0]; + } + + if (assigningFunctionSignature) { + contextParams = assigningFunctionSignature.parameters; + } + + var contextualParametersCount = contextParams.length; + for (var i = 0, n = parameters.length; i < n; i++) { + var actualParameterIsVarArgParameter = (i === (n - 1)) && parameters.lastParameterIsRest(); + var correspondingContextualParameter = null; + var contextualParameterType = null; + + if (i < contextualParametersCount) { + correspondingContextualParameter = contextParams[i]; + } else if (contextualParametersCount && contextParams[contextualParametersCount - 1].isVarArg) { + correspondingContextualParameter = contextParams[contextualParametersCount - 1]; + } + + if (correspondingContextualParameter) { + if (correspondingContextualParameter.isVarArg === actualParameterIsVarArgParameter) { + contextualParameterType = correspondingContextualParameter.type; + } else if (correspondingContextualParameter.isVarArg) { + contextualParameterType = correspondingContextualParameter.type.getElementType(); + } + } + + this.resolveFunctionExpressionParameter(parameters.astAt(i), parameters.identifierAt(i), parameters.typeAt(i), parameters.initializerAt(i), contextualParameterType, functionDecl, context); + } + }; + + PullTypeResolver.prototype.typeCheckSimpleArrowFunctionExpression = function (arrowFunction, isContextuallyTyped, context) { + return this.typeCheckAnyFunctionExpression(arrowFunction, null, TypeScript.ASTHelpers.parametersFromIdentifier(arrowFunction.identifier), null, arrowFunction.block, arrowFunction.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckParenthesizedArrowFunctionExpression = function (arrowFunction, isContextuallyTyped, context) { + return this.typeCheckAnyFunctionExpression(arrowFunction, arrowFunction.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), TypeScript.ASTHelpers.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckAnyFunctionExpression = function (funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context) { + var _this = this; + this.setTypeChecked(funcDeclAST, context); + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + + var funcDeclSymbol = functionDecl.getSymbol(); + var funcDeclType = funcDeclSymbol.type; + var signature = funcDeclType.getCallSignatures()[0]; + var returnTypeSymbol = signature.returnType; + + if (typeParameters) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + this.resolveTypeParameterDeclaration(typeParameters.typeParameters.nonSeparatorAt(i), context); + } + } + + this.resolveAnyFunctionExpressionParameters(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context); + + context.pushNewContextualType(null); + if (block) { + this.resolveAST(block, false, context); + } else { + var bodyExpressionType = this.resolveReturnExpression(bodyExpression, functionDecl, context); + this.typeCheckReturnExpression(bodyExpression, bodyExpressionType, functionDecl, context); + } + + context.popAnyContextualType(); + + this.checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement(functionDecl, returnTypeAnnotation, returnTypeSymbol, block, context); + + this.validateVariableDeclarationGroups(functionDecl, context); + + this.typeCheckCallBacks.push(function (context) { + _this.typeCheckFunctionOverloads(funcDeclAST, context); + }); + }; + + PullTypeResolver.prototype.resolveThisExpression = function (thisExpression, context) { + var enclosingDecl = this.getEnclosingDeclForAST(thisExpression); + var thisTypeSymbol = this.getContextualClassSymbolForEnclosingDecl(thisExpression, enclosingDecl) || this.semanticInfoChain.anyTypeSymbol; + + if (this.canTypeCheckAST(thisExpression, context)) { + this.typeCheckThisExpression(thisExpression, context, enclosingDecl); + } + + return thisTypeSymbol; + }; + + PullTypeResolver.prototype.inTypeArgumentList = function (ast) { + var previous = null; + var current = ast; + + while (current) { + switch (current.kind()) { + case 126 /* GenericType */: + var genericType = current; + if (genericType.typeArgumentList === previous) { + return true; + } + break; + + case 226 /* ArgumentList */: + var argumentList = current; + return argumentList.typeArgumentList === previous; + } + + previous = current; + current = current.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inClassExtendsHeritageClause = function (ast) { + while (ast) { + switch (ast.kind()) { + case 230 /* ExtendsHeritageClause */: + var heritageClause = ast; + + return heritageClause.parent.parent.kind() === 131 /* ClassDeclaration */; + + case 137 /* ConstructorDeclaration */: + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inTypeQuery = function (ast) { + while (ast) { + switch (ast.kind()) { + case 127 /* TypeQuery */: + return true; + case 129 /* FunctionDeclaration */: + case 213 /* InvocationExpression */: + case 137 /* ConstructorDeclaration */: + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inArgumentListOfSuperInvocation = function (ast) { + var previous = null; + var current = ast; + while (current) { + switch (current.kind()) { + case 213 /* InvocationExpression */: + var invocationExpression = current; + if (previous === invocationExpression.argumentList && invocationExpression.expression.kind() === 50 /* SuperKeyword */) { + return true; + } + break; + + case 137 /* ConstructorDeclaration */: + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + previous = current; + current = current.parent; + } + + return false; + }; + + PullTypeResolver.prototype.inConstructorParameterList = function (ast) { + var previous = null; + var current = ast; + while (current) { + switch (current.kind()) { + case 142 /* CallSignature */: + var callSignature = current; + if (previous === callSignature.parameterList && callSignature.parent.kind() === 137 /* ConstructorDeclaration */) { + return true; + } + + case 131 /* ClassDeclaration */: + case 130 /* ModuleDeclaration */: + return false; + } + + previous = current; + current = current.parent; + } + + return false; + }; + PullTypeResolver.prototype.isFunctionAccessorOrNonArrowFunctionExpression = function (decl) { + if (decl.kind === 262144 /* GetAccessor */ || decl.kind === 524288 /* SetAccessor */) { + return true; + } + + return this.isFunctionOrNonArrowFunctionExpression(decl); + }; + + PullTypeResolver.prototype.isFunctionOrNonArrowFunctionExpression = function (decl) { + if (decl.kind === 16384 /* Function */) { + return true; + } else if (decl.kind === 131072 /* FunctionExpression */ && !TypeScript.hasFlag(decl.flags, 8192 /* ArrowFunction */)) { + return true; + } + + return false; + }; + + PullTypeResolver.prototype.typeCheckThisExpression = function (thisExpression, context, enclosingDecl) { + this.checkForThisCaptureInArrowFunction(thisExpression); + + if (this.inConstructorParameterList(thisExpression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_constructor_arguments)); + return; + } + + for (var currentDecl = enclosingDecl; currentDecl !== null; currentDecl = currentDecl.getParentDecl()) { + if (this.isFunctionAccessorOrNonArrowFunctionExpression(currentDecl)) { + return; + } else if (currentDecl.kind === 4 /* Container */ || currentDecl.kind === 32 /* DynamicModule */) { + if (currentDecl.getParentDecl() === null) { + return; + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_within_module_bodies)); + return; + } + } else if (currentDecl.kind === 64 /* Enum */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_current_location)); + return; + } else if (currentDecl.kind === 32768 /* ConstructorMethod */) { + if (this.inArgumentListOfSuperInvocation(thisExpression) && this.superCallMustBeFirstStatementInConstructor(currentDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_current_location)); + } + + return; + } else if (currentDecl.kind === 8 /* Class */) { + if (this.inStaticMemberVariableDeclaration(thisExpression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(thisExpression, TypeScript.DiagnosticCode.this_cannot_be_referenced_in_static_initializers_in_a_class_body)); + } + + return; + } + } + }; + + PullTypeResolver.prototype.getContextualClassSymbolForEnclosingDecl = function (ast, enclosingDecl) { + var declPath = enclosingDecl.getParentPath(); + + if (declPath.length) { + var isStaticContext = false; + + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.kind; + var declFlags = decl.flags; + + if (declFlags & 16 /* Static */) { + isStaticContext = true; + } else if (declKind === 131072 /* FunctionExpression */ && !TypeScript.hasFlag(declFlags, 8192 /* ArrowFunction */)) { + return null; + } else if (declKind === 16384 /* Function */) { + return null; + } else if (declKind === 8 /* Class */) { + if (this.inStaticMemberVariableDeclaration(ast)) { + return this.getNewErrorTypeSymbol(); + } else { + var classSymbol = decl.getSymbol(); + if (isStaticContext) { + var constructorSymbol = classSymbol.getConstructorMethod(); + return constructorSymbol.type; + } else { + return classSymbol; + } + } + } + } + } + + return null; + }; + + PullTypeResolver.prototype.inStaticMemberVariableDeclaration = function (ast) { + while (ast) { + if (ast.kind() === 136 /* MemberVariableDeclaration */ && TypeScript.hasModifier(ast.modifiers, 16 /* Static */)) { + return true; + } + + ast = ast.parent; + } + + return false; + }; + + PullTypeResolver.prototype.resolveSuperExpression = function (ast, context) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + var superType = this.semanticInfoChain.anyTypeSymbol; + + var classSymbol = this.getContextualClassSymbolForEnclosingDecl(ast, enclosingDecl); + + if (classSymbol) { + this.resolveDeclaredSymbol(classSymbol, context); + + var parents = classSymbol.getExtendedTypes(); + + if (parents.length) { + superType = parents[0]; + } + } + + if (this.canTypeCheckAST(ast, context)) { + this.typeCheckSuperExpression(ast, context, enclosingDecl); + } + + return superType; + }; + + PullTypeResolver.prototype.typeCheckSuperExpression = function (ast, context, enclosingDecl) { + this.setTypeChecked(ast, context); + + this.checkForThisCaptureInArrowFunction(ast); + + var isSuperCall = ast.parent.kind() === 213 /* InvocationExpression */; + var isSuperPropertyAccess = ast.parent.kind() === 212 /* MemberAccessExpression */; + TypeScript.Debug.assert(isSuperCall || isSuperPropertyAccess); + + if (isSuperPropertyAccess) { + for (var currentDecl = enclosingDecl; currentDecl !== null; currentDecl = currentDecl.getParentDecl()) { + if (this.isFunctionOrNonArrowFunctionExpression(currentDecl)) { + break; + } else if (currentDecl.kind === 8 /* Class */) { + if (!this.enclosingClassIsDerived(currentDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_non_derived_classes)); + return; + } else if (this.inConstructorParameterList(ast)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_constructor_arguments)); + return; + } else if (this.inStaticMemberVariableDeclaration(ast)) { + break; + } + + return; + } + } + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class)); + return; + } else { + if (enclosingDecl.kind === 32768 /* ConstructorMethod */) { + var classDecl = enclosingDecl.getParentDecl(); + + if (!this.enclosingClassIsDerived(classDecl)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_non_derived_classes)); + return; + } else if (this.inConstructorParameterList(ast)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.super_cannot_be_referenced_in_constructor_arguments)); + return; + } + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors)); + } + } + }; + + PullTypeResolver.prototype.resolveSimplePropertyAssignment = function (propertyAssignment, isContextuallyTyped, context) { + return this.resolveAST(propertyAssignment.expression, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveFunctionPropertyAssignment = function (funcProp, isContextuallyTyped, context) { + return this.resolveAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcProp), funcProp.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.typeCheckFunctionPropertyAssignment = function (funcProp, isContextuallyTyped, context) { + this.typeCheckAnyFunctionExpression(funcProp, funcProp.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(funcProp.callSignature.parameterList), TypeScript.ASTHelpers.getType(funcProp), funcProp.block, null, isContextuallyTyped, context); + }; + + PullTypeResolver.prototype.resolveObjectLiteralExpression = function (expressionAST, isContextuallyTyped, context, additionalResults) { + var symbol = this.getSymbolForAST(expressionAST, context); + var hasResolvedSymbol = symbol && symbol.isResolved; + + if (!hasResolvedSymbol || additionalResults || this.canTypeCheckAST(expressionAST, context)) { + if (this.canTypeCheckAST(expressionAST, context)) { + this.setTypeChecked(expressionAST, context); + } + symbol = this.computeObjectLiteralExpression(expressionAST, isContextuallyTyped, context, additionalResults); + this.setSymbolForAST(expressionAST, symbol, context); + } + + return symbol; + }; + + PullTypeResolver.prototype.bindObjectLiteralMembers = function (objectLiteralDeclaration, objectLiteralTypeSymbol, objectLiteralMembers, isUsingExistingSymbol, pullTypeContext) { + var boundMemberSymbols = []; + var memberSymbol; + for (var i = 0, len = objectLiteralMembers.nonSeparatorCount(); i < len; i++) { + var propertyAssignment = objectLiteralMembers.nonSeparatorAt(i); + + var id = this.getPropertyAssignmentName(propertyAssignment); + var assignmentText = getPropertyAssignmentNameTextFromIdentifier(id); + + var isAccessor = propertyAssignment.kind() === 139 /* GetAccessor */ || propertyAssignment.kind() === 140 /* SetAccessor */; + var decl = this.semanticInfoChain.getDeclForAST(propertyAssignment); + TypeScript.Debug.assert(decl); + + if (propertyAssignment.kind() === 240 /* SimplePropertyAssignment */) { + if (!isUsingExistingSymbol) { + memberSymbol = new TypeScript.PullSymbol(assignmentText.memberName, 4096 /* Property */); + memberSymbol.addDeclaration(decl); + decl.setSymbol(memberSymbol); + } else { + memberSymbol = decl.getSymbol(); + } + } else if (propertyAssignment.kind() === 241 /* FunctionPropertyAssignment */) { + memberSymbol = decl.getSymbol(); + } else { + TypeScript.Debug.assert(isAccessor); + memberSymbol = decl.getSymbol(); + } + + if (!isUsingExistingSymbol && !isAccessor) { + var existingMember = objectLiteralTypeSymbol.findMember(memberSymbol.name, true); + if (existingMember) { + pullTypeContext.postDiagnostic(this.semanticInfoChain.duplicateIdentifierDiagnosticFromAST(propertyAssignment, assignmentText.actualText, existingMember.getDeclarations()[0].ast())); + } + + objectLiteralTypeSymbol.addMember(memberSymbol); + } + + boundMemberSymbols.push(memberSymbol); + } + + return boundMemberSymbols; + }; + + PullTypeResolver.prototype.resolveObjectLiteralMembers = function (objectLiteralDeclaration, objectLiteralTypeSymbol, objectLiteralContextualType, objectLiteralMembers, stringIndexerSignature, numericIndexerSignature, allMemberTypes, allNumericMemberTypes, boundMemberSymbols, isUsingExistingSymbol, pullTypeContext, additionalResults) { + for (var i = 0, len = objectLiteralMembers.nonSeparatorCount(); i < len; i++) { + var propertyAssignment = objectLiteralMembers.nonSeparatorAt(i); + + var acceptedContextualType = false; + var assigningSymbol = null; + + var id = this.getPropertyAssignmentName(propertyAssignment); + var memberSymbol = boundMemberSymbols[i]; + var contextualMemberType = null; + + if (objectLiteralContextualType) { + assigningSymbol = this.getNamedPropertySymbol(memberSymbol.name, 68147712 /* SomeValue */, objectLiteralContextualType); + + if (!assigningSymbol) { + if (numericIndexerSignature && TypeScript.PullHelpers.isNameNumeric(memberSymbol.name)) { + assigningSymbol = numericIndexerSignature; + } else if (stringIndexerSignature) { + assigningSymbol = stringIndexerSignature; + } + } + + if (assigningSymbol) { + this.resolveDeclaredSymbol(assigningSymbol, pullTypeContext); + + contextualMemberType = assigningSymbol.kind === 4194304 /* IndexSignature */ ? assigningSymbol.returnType : assigningSymbol.type; + pullTypeContext.propagateContextualType(contextualMemberType); + + acceptedContextualType = true; + + if (additionalResults) { + additionalResults.membersContextTypeSymbols[i] = contextualMemberType; + } + } + } + + var memberSymbolType = this.resolveAST(propertyAssignment, contextualMemberType !== null, pullTypeContext).type; + + if (memberSymbolType) { + if (memberSymbolType.isGeneric()) { + objectLiteralTypeSymbol.setHasGenericMember(); + } + + if (stringIndexerSignature) { + allMemberTypes.push(memberSymbolType); + } + if (numericIndexerSignature && TypeScript.PullHelpers.isNameNumeric(memberSymbol.name)) { + allNumericMemberTypes.push(memberSymbolType); + } + } + + if (acceptedContextualType) { + pullTypeContext.popAnyContextualType(); + } + + var isAccessor = propertyAssignment.kind() === 140 /* SetAccessor */ || propertyAssignment.kind() === 139 /* GetAccessor */; + if (!memberSymbol.isResolved) { + if (isAccessor) { + this.setSymbolForAST(id, memberSymbolType, pullTypeContext); + } else { + pullTypeContext.setTypeInContext(memberSymbol, memberSymbolType); + memberSymbol.setResolved(); + + this.setSymbolForAST(id, memberSymbol, pullTypeContext); + } + } + } + }; + + PullTypeResolver.prototype.computeObjectLiteralExpression = function (objectLitAST, isContextuallyTyped, context, additionalResults) { + var objectLitDecl = this.semanticInfoChain.getDeclForAST(objectLitAST); + TypeScript.Debug.assert(objectLitDecl); + + var typeSymbol = this.getSymbolForAST(objectLitAST, context); + var isUsingExistingSymbol = !!typeSymbol; + + if (!typeSymbol) { + typeSymbol = new TypeScript.PullTypeSymbol("", 256 /* ObjectLiteral */); + typeSymbol.addDeclaration(objectLitDecl); + this.setSymbolForAST(objectLitAST, typeSymbol, context); + objectLitDecl.setSymbol(typeSymbol); + } + + var propertyAssignments = objectLitAST.propertyAssignments; + var contextualType = null; + + if (isContextuallyTyped) { + contextualType = context.getContextualType(); + this.resolveDeclaredSymbol(contextualType, context); + } + + var stringIndexerSignature = null; + var numericIndexerSignature = null; + var allMemberTypes = null; + var allNumericMemberTypes = null; + + if (contextualType) { + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(contextualType, context); + + stringIndexerSignature = indexSignatures.stringSignature; + numericIndexerSignature = indexSignatures.numericSignature; + + var inInferentialTyping = context.isInferentiallyTyping(); + if (stringIndexerSignature) { + allMemberTypes = inInferentialTyping ? [] : [stringIndexerSignature.returnType]; + } + + if (numericIndexerSignature) { + allNumericMemberTypes = inInferentialTyping ? [] : [numericIndexerSignature.returnType]; + } + } + + if (propertyAssignments) { + if (additionalResults) { + additionalResults.membersContextTypeSymbols = []; + } + + var boundMemberSymbols = this.bindObjectLiteralMembers(objectLitDecl, typeSymbol, propertyAssignments, isUsingExistingSymbol, context); + + this.resolveObjectLiteralMembers(objectLitDecl, typeSymbol, contextualType, propertyAssignments, stringIndexerSignature, numericIndexerSignature, allMemberTypes, allNumericMemberTypes, boundMemberSymbols, isUsingExistingSymbol, context, additionalResults); + + if (!isUsingExistingSymbol) { + this.stampObjectLiteralWithIndexSignature(typeSymbol, allMemberTypes, stringIndexerSignature, context); + this.stampObjectLiteralWithIndexSignature(typeSymbol, allNumericMemberTypes, numericIndexerSignature, context); + } + } + + typeSymbol.setResolved(); + return typeSymbol; + }; + + PullTypeResolver.prototype.getPropertyAssignmentName = function (propertyAssignment) { + if (propertyAssignment.kind() === 240 /* SimplePropertyAssignment */) { + return propertyAssignment.propertyName; + } else if (propertyAssignment.kind() === 241 /* FunctionPropertyAssignment */) { + return propertyAssignment.propertyName; + } else if (propertyAssignment.kind() === 139 /* GetAccessor */) { + return propertyAssignment.propertyName; + } else if (propertyAssignment.kind() === 140 /* SetAccessor */) { + return propertyAssignment.propertyName; + } else { + TypeScript.Debug.assert(false); + } + }; + + PullTypeResolver.prototype.stampObjectLiteralWithIndexSignature = function (objectLiteralSymbol, indexerTypeCandidates, contextualIndexSignature, context) { + if (contextualIndexSignature) { + var typeCollection = { + getLength: function () { + return indexerTypeCandidates.length; + }, + getTypeAtIndex: function (index) { + return indexerTypeCandidates[index]; + } + }; + var decl = objectLiteralSymbol.getDeclarations()[0]; + var indexerReturnType = this.findBestCommonType(typeCollection, context).widenedType(this, null, context); + if (indexerReturnType === contextualIndexSignature.returnType) { + objectLiteralSymbol.addIndexSignature(contextualIndexSignature); + } else { + this.semanticInfoChain.addSyntheticIndexSignature(decl, objectLiteralSymbol, this.getASTForDecl(decl), contextualIndexSignature.parameters[0].name, contextualIndexSignature.parameters[0].type, indexerReturnType); + } + } + }; + + PullTypeResolver.prototype.resolveArrayLiteralExpression = function (arrayLit, isContextuallyTyped, context) { + var symbol = this.getSymbolForAST(arrayLit, context); + if (!symbol || this.canTypeCheckAST(arrayLit, context)) { + if (this.canTypeCheckAST(arrayLit, context)) { + this.setTypeChecked(arrayLit, context); + } + symbol = this.computeArrayLiteralExpressionSymbol(arrayLit, isContextuallyTyped, context); + this.setSymbolForAST(arrayLit, symbol, context); + } + + return symbol; + }; + + PullTypeResolver.prototype.computeArrayLiteralExpressionSymbol = function (arrayLit, isContextuallyTyped, context) { + var elements = arrayLit.expressions; + var elementType = null; + var elementTypes = []; + var comparisonInfo = new TypeComparisonInfo(); + var contextualElementType = null; + comparisonInfo.onlyCaptureFirstError = true; + + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + + this.resolveDeclaredSymbol(contextualType, context); + + if (contextualType) { + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(contextualType, context); + if (indexSignatures.numericSignature) { + contextualElementType = indexSignatures.numericSignature.returnType; + } + } + } + + if (elements) { + if (contextualElementType) { + context.propagateContextualType(contextualElementType); + } + + for (var i = 0, n = elements.nonSeparatorCount(); i < n; i++) { + elementTypes.push(this.resolveAST(elements.nonSeparatorAt(i), contextualElementType !== null, context).type); + } + + if (contextualElementType) { + context.popAnyContextualType(); + } + } + + if (elementTypes.length) { + elementType = elementTypes[0]; + } + var collection; + + if (contextualElementType && !context.isInferentiallyTyping()) { + if (!elementType) { + elementType = contextualElementType; + } + + collection = { + getLength: function () { + return elements.nonSeparatorCount() + 1; + }, + getTypeAtIndex: function (index) { + return index === 0 ? contextualElementType : elementTypes[index - 1]; + } + }; + } else { + collection = { + getLength: function () { + return elements.nonSeparatorCount(); + }, + getTypeAtIndex: function (index) { + return elementTypes[index]; + } + }; + } + + elementType = elementType ? this.findBestCommonType(collection, context, comparisonInfo) : elementType; + + if (!elementType) { + elementType = this.semanticInfoChain.undefinedTypeSymbol; + } + + return this.getArrayType(elementType); + }; + + PullTypeResolver.prototype.resolveElementAccessExpression = function (callEx, context) { + var symbolAndDiagnostic = this.computeElementAccessExpressionSymbolAndDiagnostic(callEx, context); + + if (this.canTypeCheckAST(callEx, context)) { + this.typeCheckElementAccessExpression(callEx, context, symbolAndDiagnostic); + } + + return symbolAndDiagnostic.symbol; + }; + + PullTypeResolver.prototype.typeCheckElementAccessExpression = function (callEx, context, symbolAndDiagnostic) { + this.setTypeChecked(callEx, context); + context.postDiagnostic(symbolAndDiagnostic.diagnostic); + }; + + PullTypeResolver.prototype.computeElementAccessExpressionSymbolAndDiagnostic = function (callEx, context) { + var targetSymbol = this.resolveAST(callEx.expression, false, context); + var indexType = this.resolveAST(callEx.argumentExpression, false, context).type; + + var targetTypeSymbol = targetSymbol.type; + + targetTypeSymbol = this.getApparentType(targetTypeSymbol); + + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + return { symbol: targetTypeSymbol }; + } + + var elementType = targetTypeSymbol.getElementType(); + + var isNumberIndex = indexType === this.semanticInfoChain.numberTypeSymbol || TypeScript.PullHelpers.symbolIsEnum(indexType); + + if (elementType && isNumberIndex) { + return { symbol: elementType }; + } + + if (callEx.argumentExpression.kind() === 14 /* StringLiteral */ || callEx.argumentExpression.kind() === 13 /* NumericLiteral */) { + var memberName = callEx.argumentExpression.kind() === 14 /* StringLiteral */ ? TypeScript.stripStartAndEndQuotes(callEx.argumentExpression.text()) : callEx.argumentExpression.valueText(); + + var member = this._getNamedPropertySymbolOfAugmentedType(memberName, targetTypeSymbol); + + if (member) { + this.resolveDeclaredSymbol(member, context); + + return { symbol: member.type }; + } + } + + var signatures = this.getBothKindsOfIndexSignaturesIncludingAugmentedType(targetTypeSymbol, context); + + var stringSignature = signatures.stringSignature; + var numberSignature = signatures.numericSignature; + + if (numberSignature && (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol)) { + return { symbol: numberSignature.returnType || this.semanticInfoChain.anyTypeSymbol }; + } else if (stringSignature && (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol)) { + return { symbol: stringSignature.returnType || this.semanticInfoChain.anyTypeSymbol }; + } else if (isNumberIndex || indexType === this.semanticInfoChain.anyTypeSymbol || indexType === this.semanticInfoChain.stringTypeSymbol) { + if (this.compilationSettings.noImplicitAny()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(callEx.argumentExpression, TypeScript.DiagnosticCode.Index_signature_of_object_type_implicitly_has_an_any_type)); + } + return { symbol: this.semanticInfoChain.anyTypeSymbol }; + } else { + return { + symbol: this.getNewErrorTypeSymbol(), + diagnostic: this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.Value_of_type_0_is_not_indexable_by_type_1, [targetTypeSymbol.toString(), indexType.toString()]) + }; + } + }; + + PullTypeResolver.prototype.getBothKindsOfIndexSignaturesIncludingAugmentedType = function (enclosingType, context) { + return this._getBothKindsOfIndexSignatures(enclosingType, context, true); + }; + + PullTypeResolver.prototype.getBothKindsOfIndexSignaturesExcludingAugmentedType = function (enclosingType, context) { + return this._getBothKindsOfIndexSignatures(enclosingType, context, false); + }; + + PullTypeResolver.prototype._getBothKindsOfIndexSignatures = function (enclosingType, context, includeAugmentedType) { + var signatures = includeAugmentedType ? enclosingType.getIndexSignaturesOfAugmentedType(this, this.cachedFunctionInterfaceType(), this.cachedObjectInterfaceType()) : enclosingType.getIndexSignatures(); + + var stringSignature = null; + var numberSignature = null; + var signature = null; + var paramSymbols; + var paramType; + + for (var i = 0; i < signatures.length; i++) { + if (stringSignature && numberSignature) { + break; + } + + signature = signatures[i]; + if (!signature.isResolved) { + this.resolveDeclaredSymbol(signature, context); + } + + paramSymbols = signature.parameters; + + if (paramSymbols.length) { + paramType = paramSymbols[0].type; + + if (!stringSignature && paramType === this.semanticInfoChain.stringTypeSymbol) { + stringSignature = signature; + continue; + } else if (!numberSignature && paramType === this.semanticInfoChain.numberTypeSymbol) { + numberSignature = signature; + continue; + } + } + } + + return { + numericSignature: numberSignature, + stringSignature: stringSignature + }; + }; + + PullTypeResolver.prototype._addUnhiddenSignaturesFromBaseType = function (derivedTypeSignatures, baseTypeSignatures, signaturesBeingAggregated) { + var _this = this; + if (!derivedTypeSignatures) { + signaturesBeingAggregated.push.apply(signaturesBeingAggregated, baseTypeSignatures); + return; + } + + var context = new TypeScript.PullTypeResolutionContext(this); + for (var i = 0; i < baseTypeSignatures.length; i++) { + var baseSignature = baseTypeSignatures[i]; + + var signatureIsHidden = TypeScript.ArrayUtilities.any(derivedTypeSignatures, function (sig) { + return _this.signaturesAreIdenticalWithNewEnclosingTypes(baseSignature, sig, context, false); + }); + + if (!signatureIsHidden) { + signaturesBeingAggregated.push(baseSignature); + } + } + }; + + PullTypeResolver.prototype.resolveBinaryAdditionOperation = function (binaryExpression, context) { + var lhsExpression = this.resolveAST(binaryExpression.left, false, context); + var lhsType = lhsExpression.type; + var rhsType = this.resolveAST(binaryExpression.right, false, context).type; + + if (TypeScript.PullHelpers.symbolIsEnum(lhsType)) { + lhsType = this.semanticInfoChain.numberTypeSymbol; + } + + if (TypeScript.PullHelpers.symbolIsEnum(rhsType)) { + rhsType = this.semanticInfoChain.numberTypeSymbol; + } + + var isLhsTypeNullOrUndefined = lhsType === this.semanticInfoChain.nullTypeSymbol || lhsType === this.semanticInfoChain.undefinedTypeSymbol; + var isRhsTypeNullOrUndefined = rhsType === this.semanticInfoChain.nullTypeSymbol || rhsType === this.semanticInfoChain.undefinedTypeSymbol; + + if (isLhsTypeNullOrUndefined) { + if (isRhsTypeNullOrUndefined) { + lhsType = rhsType = this.semanticInfoChain.anyTypeSymbol; + } else { + lhsType = rhsType; + } + } else if (isRhsTypeNullOrUndefined) { + rhsType = lhsType; + } + + var exprType = null; + + if (lhsType === this.semanticInfoChain.stringTypeSymbol || rhsType === this.semanticInfoChain.stringTypeSymbol) { + exprType = this.semanticInfoChain.stringTypeSymbol; + } else if (this.isAnyOrEquivalent(lhsType) || this.isAnyOrEquivalent(rhsType)) { + exprType = this.semanticInfoChain.anyTypeSymbol; + } else if (rhsType === this.semanticInfoChain.numberTypeSymbol && lhsType === this.semanticInfoChain.numberTypeSymbol) { + exprType = this.semanticInfoChain.numberTypeSymbol; + } + + if (this.canTypeCheckAST(binaryExpression, context)) { + this.setTypeChecked(binaryExpression, context); + + if (exprType) { + if (binaryExpression.kind() === 175 /* AddAssignmentExpression */) { + if (!this.isReference(binaryExpression.left, lhsExpression)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_left_hand_side_of_assignment_expression)); + } + + this.checkAssignability(binaryExpression.left, exprType, lhsType, context); + } + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_expression_types_not_known_to_support_the_addition_operator)); + } + } + + if (!exprType) { + exprType = this.semanticInfoChain.anyTypeSymbol; + } + + return exprType; + }; + + PullTypeResolver.prototype.bestCommonTypeOfTwoTypes = function (type1, type2, context) { + return this.findBestCommonType({ + getLength: function () { + return 2; + }, + getTypeAtIndex: function (index) { + switch (index) { + case 0: + return type1; + case 1: + return type2; + } + } + }, context); + }; + + PullTypeResolver.prototype.bestCommonTypeOfThreeTypes = function (type1, type2, type3, context) { + return this.findBestCommonType({ + getLength: function () { + return 3; + }, + getTypeAtIndex: function (index) { + switch (index) { + case 0: + return type1; + case 1: + return type2; + case 2: + return type3; + } + } + }, context); + }; + + PullTypeResolver.prototype.resolveLogicalOrExpression = function (binex, isContextuallyTyped, context) { + if (this.canTypeCheckAST(binex, context)) { + this.setTypeChecked(binex, context); + } + + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + var leftType = this.resolveAST(binex.left, isContextuallyTyped, context).type; + var rightType = this.resolveAST(binex.right, isContextuallyTyped, context).type; + + return context.isInferentiallyTyping() ? this.bestCommonTypeOfTwoTypes(leftType, rightType, context) : this.bestCommonTypeOfThreeTypes(contextualType, leftType, rightType, context); + } else { + var leftType = this.resolveAST(binex.left, false, context).type; + + context.pushNewContextualType(leftType); + var rightType = this.resolveAST(binex.right, true, context).type; + context.popAnyContextualType(); + + return this.bestCommonTypeOfTwoTypes(leftType, rightType, context); + } + }; + + PullTypeResolver.prototype.resolveLogicalAndExpression = function (binex, context) { + if (this.canTypeCheckAST(binex, context)) { + this.setTypeChecked(binex, context); + + this.resolveAST(binex.left, false, context); + } + + return this.resolveAST(binex.right, false, context).type; + }; + + PullTypeResolver.prototype.computeTypeOfConditionalExpression = function (leftType, rightType, isContextuallyTyped, context) { + if (isContextuallyTyped && !context.isInferentiallyTyping()) { + var contextualType = context.getContextualType(); + return this.bestCommonTypeOfThreeTypes(contextualType, leftType, rightType, context); + } else { + return this.bestCommonTypeOfTwoTypes(leftType, rightType, context); + } + }; + + PullTypeResolver.prototype.resolveConditionalExpression = function (trinex, isContextuallyTyped, context) { + var leftType = this.resolveAST(trinex.whenTrue, isContextuallyTyped, context).type; + var rightType = this.resolveAST(trinex.whenFalse, isContextuallyTyped, context).type; + + var expressionType = this.computeTypeOfConditionalExpression(leftType, rightType, isContextuallyTyped, context); + + var conditionalTypesAreValid = this.conditionExpressionTypesAreValid(leftType, rightType, expressionType, isContextuallyTyped, context); + + if (this.canTypeCheckAST(trinex, context)) { + this.setTypeChecked(trinex, context); + this.resolveAST(trinex.condition, false, context); + + if (!this.conditionExpressionTypesAreValid(leftType, rightType, expressionType, isContextuallyTyped, context)) { + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(trinex, TypeScript.DiagnosticCode.Type_of_conditional_0_must_be_identical_to_1_2_or_3, [expressionType.toString(), leftType.toString(), rightType.toString(), contextualType.toString()])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(trinex, TypeScript.DiagnosticCode.Type_of_conditional_0_must_be_identical_to_1_or_2, [expressionType.toString(), leftType.toString(), rightType.toString()])); + } + } + } + + if (!conditionalTypesAreValid) { + return this.getNewErrorTypeSymbol(); + } + + return expressionType; + }; + + PullTypeResolver.prototype.conditionExpressionTypesAreValid = function (leftType, rightType, expressionType, isContextuallyTyped, context) { + if (isContextuallyTyped) { + var contextualType = context.getContextualType(); + if (this.typesAreIdentical(expressionType, leftType, context) || this.typesAreIdentical(expressionType, rightType, context) || this.typesAreIdentical(expressionType, contextualType, context)) { + return true; + } + } else { + if (this.typesAreIdentical(expressionType, leftType, context) || this.typesAreIdentical(expressionType, rightType, context)) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.resolveParenthesizedExpression = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + } + + return this.resolveAST(ast.expression, false, context); + }; + + PullTypeResolver.prototype.resolveExpressionStatement = function (ast, context) { + if (this.canTypeCheckAST(ast, context)) { + this.setTypeChecked(ast, context); + + this.resolveAST(ast.expression, false, context); + } + + return this.semanticInfoChain.voidTypeSymbol; + }; + + PullTypeResolver.prototype.resolveInvocationExpression = function (callEx, context, additionalResults) { + var symbol = this.getSymbolForAST(callEx, context); + + if (!symbol || !symbol.isResolved) { + if (!additionalResults) { + additionalResults = new PullAdditionalCallResolutionData(); + } + symbol = this.computeInvocationExpressionSymbol(callEx, context, additionalResults); + if (this.canTypeCheckAST(callEx, context)) { + this.setTypeChecked(callEx, context); + } + if (symbol !== this.semanticInfoChain.anyTypeSymbol) { + this.setSymbolForAST(callEx, symbol, context); + } + this.semanticInfoChain.setCallResolutionDataForAST(callEx, additionalResults); + } else { + if (this.canTypeCheckAST(callEx, context)) { + this.typeCheckInvocationExpression(callEx, context); + } + + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + if (additionalResults && (callResolutionData !== additionalResults)) { + additionalResults.actualParametersContextTypeSymbols = callResolutionData.actualParametersContextTypeSymbols; + additionalResults.candidateSignature = callResolutionData.candidateSignature; + additionalResults.resolvedSignatures = callResolutionData.resolvedSignatures; + additionalResults.targetSymbol = callResolutionData.targetSymbol; + } + } + + return symbol; + }; + + PullTypeResolver.prototype.typeCheckInvocationExpression = function (callEx, context) { + this.setTypeChecked(callEx, context); + var targetSymbol = this.resolveAST(callEx.expression, false, context); + + if (callEx.argumentList.arguments) { + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + + var len = callEx.argumentList.arguments.nonSeparatorCount(); + for (var i = 0; i < len; i++) { + var contextualType = callResolutionData.actualParametersContextTypeSymbols ? callResolutionData.actualParametersContextTypeSymbols[i] : null; + if (contextualType) { + context.pushNewContextualType(contextualType); + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + for (var i = 0; i < callResolutionData.diagnosticsFromOverloadResolution.length; i++) { + context.postDiagnostic(callResolutionData.diagnosticsFromOverloadResolution[i]); + } + }; + + PullTypeResolver.prototype.computeInvocationExpressionSymbol = function (callEx, context, additionalResults) { + var targetSymbol = this.resolveAST(callEx.expression, false, context); + var targetAST = this.getCallTargetErrorSpanAST(callEx); + + var targetTypeSymbol = targetSymbol.type; + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + this.resolveAST(callEx.argumentList.arguments, false, context); + + if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { + if (targetTypeSymbol === this.semanticInfoChain.anyTypeSymbol) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Untyped_function_calls_may_not_accept_type_arguments), additionalResults, context); + return this.getNewErrorTypeSymbol(); + } + } + + return this.semanticInfoChain.anyTypeSymbol; + } + + var isSuperCall = false; + + if (callEx.expression.kind() === 50 /* SuperKeyword */) { + isSuperCall = true; + + if (targetTypeSymbol.isClass()) { + targetSymbol = targetTypeSymbol.getConstructorMethod(); + this.resolveDeclaredSymbol(targetSymbol, context); + targetTypeSymbol = targetSymbol.type; + } else { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Calls_to_super_are_only_valid_inside_a_class), additionalResults, context); + this.resolveAST(callEx.argumentList.arguments, false, context); + + return this.getNewErrorTypeSymbol(); + } + } + + var signatures = isSuperCall ? targetTypeSymbol.getConstructSignatures() : targetTypeSymbol.getCallSignatures(); + + if (!signatures.length && (targetTypeSymbol.kind === 33554432 /* ConstructorType */)) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, [targetTypeSymbol.toString()]), additionalResults, context); + } + + var explicitTypeArgs = null; + var couldNotFindGenericOverload = false; + var couldNotAssignToConstraint; + var constraintDiagnostic = null; + var typeArgumentCountDiagnostic = null; + var diagnostics = []; + + if (callEx.argumentList.typeArgumentList) { + explicitTypeArgs = []; + + if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { + for (var i = 0; i < callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { + explicitTypeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + } + } + } + + var triedToInferTypeArgs = false; + + var resolvedSignatures = []; + var inferredOrExplicitTypeArgs; + var specializedSignature; + var typeParameters; + var typeConstraint = null; + var beforeResolutionSignatures = signatures; + var targetTypeReplacementMap = targetTypeSymbol.getTypeParameterArgumentMap(); + + for (var i = 0; i < signatures.length; i++) { + typeParameters = signatures[i].getTypeParameters(); + couldNotAssignToConstraint = false; + + if (signatures[i].isGeneric() && typeParameters.length) { + if (isSuperCall && targetTypeSymbol.isGeneric() && !callEx.argumentList.typeArgumentList) { + explicitTypeArgs = signatures[i].returnType.getTypeArguments(); + } + + if (explicitTypeArgs) { + if (explicitTypeArgs.length === typeParameters.length) { + inferredOrExplicitTypeArgs = explicitTypeArgs; + } else { + typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, explicitTypeArgs.length]); + continue; + } + } else { + TypeScript.Debug.assert(callEx.argumentList); + var typeArgumentInferenceContext = new TypeScript.InvocationTypeArgumentInferenceContext(this, context, signatures[i], callEx.argumentList.arguments); + inferredOrExplicitTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); + triedToInferTypeArgs = true; + } + + TypeScript.Debug.assert(inferredOrExplicitTypeArgs && inferredOrExplicitTypeArgs.length == typeParameters.length); + + var mutableTypeReplacementMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(targetTypeReplacementMap ? targetTypeReplacementMap : []); + TypeScript.PullInstantiationHelpers.updateMutableTypeParameterArgumentMap(typeParameters, inferredOrExplicitTypeArgs, mutableTypeReplacementMap); + var typeReplacementMap = mutableTypeReplacementMap.typeParameterArgumentMap; + + if (explicitTypeArgs) { + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); + } + + if (!this.sourceIsAssignableToTarget(inferredOrExplicitTypeArgs[j], typeConstraint, targetAST, context, null, true)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); + constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredOrExplicitTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); + couldNotAssignToConstraint = true; + } + + if (couldNotAssignToConstraint) { + break; + } + } + } + } + + if (couldNotAssignToConstraint) { + continue; + } + + specializedSignature = this.instantiateSignature(signatures[i], typeReplacementMap); + + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; + } + } else { + if (!(callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount())) { + resolvedSignatures[resolvedSignatures.length] = signatures[i]; + } + } + } + + if (signatures.length && !resolvedSignatures.length) { + couldNotFindGenericOverload = true; + } + + signatures = resolvedSignatures; + + var errorCondition = null; + if (!signatures.length) { + additionalResults.targetSymbol = targetSymbol; + additionalResults.resolvedSignatures = beforeResolutionSignatures; + additionalResults.candidateSignature = beforeResolutionSignatures && beforeResolutionSignatures.length ? beforeResolutionSignatures[0] : null; + + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + + this.resolveAST(callEx.argumentList.arguments, false, context); + + if (!couldNotFindGenericOverload) { + if (this.cachedFunctionInterfaceType() && this.sourceIsAssignableToTarget(targetTypeSymbol, this.cachedFunctionInterfaceType(), targetAST, context)) { + if (callEx.argumentList.typeArgumentList) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Non_generic_functions_may_not_accept_type_arguments), additionalResults, context); + } + return this.semanticInfoChain.anyTypeSymbol; + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature), additionalResults, context); + } else if (constraintDiagnostic) { + this.postOverloadResolutionDiagnostics(constraintDiagnostic, additionalResults, context); + } else if (typeArgumentCountDiagnostic) { + this.postOverloadResolutionDiagnostics(typeArgumentCountDiagnostic, additionalResults, context); + } else { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.Could_not_select_overload_for_call_expression), additionalResults, context); + } + + return this.getNewErrorTypeSymbol(); + } + + var signature = this.resolveOverloads(callEx, signatures, callEx.argumentList.typeArgumentList !== null, context, diagnostics); + var useBeforeResolutionSignatures = signature == null; + + if (!signature) { + for (var i = 0; i < diagnostics.length; i++) { + this.postOverloadResolutionDiagnostics(diagnostics[i], additionalResults, context); + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Could_not_select_overload_for_call_expression), additionalResults, context); + + errorCondition = this.getNewErrorTypeSymbol(); + + if (!signatures.length) { + return errorCondition; + } + + signature = signatures[0]; + } + + var rootSignature = signature.getRootSymbol(); + if (!rootSignature.isGeneric() && callEx.argumentList.typeArgumentList) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Non_generic_functions_may_not_accept_type_arguments), additionalResults, context); + } else if (rootSignature.isGeneric() && callEx.argumentList.typeArgumentList && rootSignature.getTypeParameters() && (callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount() !== rootSignature.getTypeParameters().length)) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [rootSignature.getTypeParameters().length, callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()]), additionalResults, context); + } + + var returnType = isSuperCall ? this.semanticInfoChain.voidTypeSymbol : signature.returnType; + + var actualParametersContextTypeSymbols = []; + if (callEx.argumentList.arguments) { + var len = callEx.argumentList.arguments.nonSeparatorCount(); + var params = signature.parameters; + var contextualType = null; + var signatureDecl = signature.getDeclarations()[0]; + + for (var i = 0; i < len; i++) { + if (params.length) { + if (i < params.length - 1 || (i < params.length && !signature.hasVarArgs)) { + this.resolveDeclaredSymbol(params[i], context); + contextualType = params[i].type; + } else if (signature.hasVarArgs) { + contextualType = params[params.length - 1].type; + if (contextualType.isArrayNamedTypeReference()) { + contextualType = contextualType.getElementType(); + } + } + } + + if (contextualType) { + context.pushNewContextualType(contextualType); + actualParametersContextTypeSymbols[i] = contextualType; + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + additionalResults.targetSymbol = targetSymbol; + if (useBeforeResolutionSignatures && beforeResolutionSignatures) { + additionalResults.resolvedSignatures = beforeResolutionSignatures; + additionalResults.candidateSignature = beforeResolutionSignatures[0]; + } else { + additionalResults.resolvedSignatures = signatures; + additionalResults.candidateSignature = signature; + } + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + + if (errorCondition) { + return errorCondition; + } + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return returnType; + }; + + PullTypeResolver.prototype.resolveObjectCreationExpression = function (callEx, context, additionalResults) { + var symbol = this.getSymbolForAST(callEx, context); + + if (!symbol || !symbol.isResolved) { + if (!additionalResults) { + additionalResults = new PullAdditionalCallResolutionData(); + } + symbol = this.computeObjectCreationExpressionSymbol(callEx, context, additionalResults); + if (this.canTypeCheckAST(callEx, context)) { + this.setTypeChecked(callEx, context); + } + this.setSymbolForAST(callEx, symbol, context); + this.semanticInfoChain.setCallResolutionDataForAST(callEx, additionalResults); + } else { + if (this.canTypeCheckAST(callEx, context)) { + this.typeCheckObjectCreationExpression(callEx, context); + } + + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + if (additionalResults && (callResolutionData !== additionalResults)) { + additionalResults.actualParametersContextTypeSymbols = callResolutionData.actualParametersContextTypeSymbols; + additionalResults.candidateSignature = callResolutionData.candidateSignature; + additionalResults.resolvedSignatures = callResolutionData.resolvedSignatures; + additionalResults.targetSymbol = callResolutionData.targetSymbol; + } + } + + return symbol; + }; + + PullTypeResolver.prototype.typeCheckObjectCreationExpression = function (callEx, context) { + this.setTypeChecked(callEx, context); + this.resolveAST(callEx.expression, false, context); + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + if (callEx.argumentList) { + var callResolutionData = this.semanticInfoChain.getCallResolutionDataForAST(callEx); + var len = callEx.argumentList.arguments.nonSeparatorCount(); + + for (var i = 0; i < len; i++) { + var contextualType = callResolutionData.actualParametersContextTypeSymbols ? callResolutionData.actualParametersContextTypeSymbols[i] : null; + if (contextualType) { + context.pushNewContextualType(contextualType); + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + for (var i = 0; i < callResolutionData.diagnosticsFromOverloadResolution.length; i++) { + context.postDiagnostic(callResolutionData.diagnosticsFromOverloadResolution[i]); + } + }; + + PullTypeResolver.prototype.postOverloadResolutionDiagnostics = function (diagnostic, additionalResults, context) { + if (!context.inProvisionalResolution()) { + additionalResults.diagnosticsFromOverloadResolution.push(diagnostic); + } + context.postDiagnostic(diagnostic); + }; + + PullTypeResolver.prototype.computeObjectCreationExpressionSymbol = function (callEx, context, additionalResults) { + var _this = this; + var returnType = null; + + var targetSymbol = this.resolveAST(callEx.expression, false, context); + var targetTypeSymbol = targetSymbol.isType() ? targetSymbol : targetSymbol.type; + + var targetAST = this.getCallTargetErrorSpanAST(callEx); + + var constructSignatures = targetTypeSymbol.getConstructSignatures(); + + var explicitTypeArgs = null; + var usedCallSignaturesInstead = false; + var couldNotAssignToConstraint; + var constraintDiagnostic = null; + var typeArgumentCountDiagnostic = null; + var diagnostics = []; + + if (this.isAnyOrEquivalent(targetTypeSymbol)) { + if (callEx.argumentList) { + this.resolveAST(callEx.argumentList.arguments, false, context); + } + + return targetTypeSymbol; + } + + if (!constructSignatures.length) { + constructSignatures = targetTypeSymbol.getCallSignatures(); + usedCallSignaturesInstead = true; + + if (this.compilationSettings.noImplicitAny()) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(callEx, TypeScript.DiagnosticCode.new_expression_which_lacks_a_constructor_signature_implicitly_has_an_any_type), additionalResults, context); + } + } + + if (constructSignatures.length) { + if (callEx.argumentList && callEx.argumentList.typeArgumentList) { + explicitTypeArgs = []; + + if (callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount()) { + for (var i = 0; i < callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount(); i++) { + explicitTypeArgs[i] = this.resolveTypeReference(callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorAt(i), context); + } + } + } + + if (targetTypeSymbol.isGeneric()) { + var resolvedSignatures = []; + var inferredOrExplicitTypeArgs; + var specializedSignature; + var typeParameters; + var typeConstraint = null; + var triedToInferTypeArgs; + var targetTypeReplacementMap = targetTypeSymbol.getTypeParameterArgumentMap(); + + for (var i = 0; i < constructSignatures.length; i++) { + couldNotAssignToConstraint = false; + + if (constructSignatures[i].isGeneric()) { + typeParameters = constructSignatures[i].getTypeParameters(); + + if (explicitTypeArgs) { + if (explicitTypeArgs.length === typeParameters.length) { + inferredOrExplicitTypeArgs = explicitTypeArgs; + } else { + typeArgumentCountDiagnostic = typeArgumentCountDiagnostic || this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Signature_expected_0_type_arguments_got_1_instead, [typeParameters.length, explicitTypeArgs.length]); + continue; + } + } else if (callEx.argumentList) { + var typeArgumentInferenceContext = new TypeScript.InvocationTypeArgumentInferenceContext(this, context, constructSignatures[i], callEx.argumentList.arguments); + inferredOrExplicitTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); + triedToInferTypeArgs = true; + } else { + inferredOrExplicitTypeArgs = TypeScript.ArrayUtilities.select(typeParameters, function (typeParameter) { + return typeParameter.getDefaultConstraint(_this.semanticInfoChain); + }); + } + + TypeScript.Debug.assert(inferredOrExplicitTypeArgs && inferredOrExplicitTypeArgs.length == typeParameters.length); + + var mutableTypeReplacementMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(targetTypeReplacementMap ? targetTypeReplacementMap : []); + TypeScript.PullInstantiationHelpers.updateMutableTypeParameterArgumentMap(typeParameters, inferredOrExplicitTypeArgs, mutableTypeReplacementMap); + var typeReplacementMap = mutableTypeReplacementMap.typeParameterArgumentMap; + + if (explicitTypeArgs) { + for (var j = 0; j < typeParameters.length; j++) { + typeConstraint = typeParameters[j].getConstraint(); + + if (typeConstraint) { + if (typeConstraint.isGeneric()) { + typeConstraint = this.instantiateType(typeConstraint, typeReplacementMap); + } + + if (!this.sourceIsAssignableToTarget(inferredOrExplicitTypeArgs[j], typeConstraint, targetAST, context, null, true)) { + var enclosingSymbol = this.getEnclosingSymbolForAST(targetAST); + constraintDiagnostic = this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2, [inferredOrExplicitTypeArgs[j].toString(enclosingSymbol, true), typeConstraint.toString(enclosingSymbol, true), typeParameters[j].toString(enclosingSymbol, true)]); + couldNotAssignToConstraint = true; + } + + if (couldNotAssignToConstraint) { + break; + } + } + } + } + + if (couldNotAssignToConstraint) { + continue; + } + + specializedSignature = this.instantiateSignature(constructSignatures[i], typeReplacementMap); + + if (specializedSignature) { + resolvedSignatures[resolvedSignatures.length] = specializedSignature; + } + } else { + if (!(callEx.argumentList && callEx.argumentList.typeArgumentList && callEx.argumentList.typeArgumentList.typeArguments.nonSeparatorCount())) { + resolvedSignatures[resolvedSignatures.length] = constructSignatures[i]; + } + } + } + + constructSignatures = resolvedSignatures; + } + + var signature = this.resolveOverloads(callEx, constructSignatures, callEx.argumentList && callEx.argumentList.typeArgumentList !== null, context, diagnostics); + + additionalResults.targetSymbol = targetSymbol; + additionalResults.resolvedSignatures = constructSignatures; + additionalResults.candidateSignature = signature; + additionalResults.actualParametersContextTypeSymbols = []; + + if (!constructSignatures.length) { + if (constraintDiagnostic) { + this.postOverloadResolutionDiagnostics(constraintDiagnostic, additionalResults, context); + } else if (typeArgumentCountDiagnostic) { + this.postOverloadResolutionDiagnostics(typeArgumentCountDiagnostic, additionalResults, context); + } + + return this.getNewErrorTypeSymbol(); + } + + var errorCondition = null; + + if (!signature) { + for (var i = 0; i < diagnostics.length; i++) { + this.postOverloadResolutionDiagnostics(diagnostics[i], additionalResults, context); + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Could_not_select_overload_for_new_expression), additionalResults, context); + + errorCondition = this.getNewErrorTypeSymbol(); + + if (!constructSignatures.length) { + return errorCondition; + } + + signature = constructSignatures[0]; + } + + returnType = signature.returnType; + + if (returnType && !signature.isGeneric() && returnType.isGeneric() && !returnType.getIsSpecialized()) { + if (explicitTypeArgs && explicitTypeArgs.length) { + returnType = this.createInstantiatedType(returnType, explicitTypeArgs); + } else { + returnType = this.instantiateTypeToAny(returnType, context); + } + } + + if (usedCallSignaturesInstead) { + if (returnType !== this.semanticInfoChain.voidTypeSymbol) { + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Call_signatures_used_in_a_new_expression_must_have_a_void_return_type), additionalResults, context); + + return this.getNewErrorTypeSymbol(); + } else { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + } + + if (!returnType) { + returnType = signature.returnType; + + if (!returnType) { + returnType = targetTypeSymbol; + } + } + + var actualParametersContextTypeSymbols = []; + if (callEx.argumentList && callEx.argumentList.arguments) { + var len = callEx.argumentList.arguments.nonSeparatorCount(); + var params = signature.parameters; + var contextualType = null; + var signatureDecl = signature.getDeclarations()[0]; + + for (var i = 0; i < len; i++) { + if (params.length) { + if (i < params.length - 1 || (i < params.length && !signature.hasVarArgs)) { + this.resolveDeclaredSymbol(params[i], context); + contextualType = params[i].type; + } else if (signature.hasVarArgs) { + contextualType = params[params.length - 1].type; + if (contextualType.isArrayNamedTypeReference()) { + contextualType = contextualType.getElementType(); + } + } + } + + if (contextualType) { + context.pushNewContextualType(contextualType); + actualParametersContextTypeSymbols[i] = contextualType; + } + + this.resolveAST(callEx.argumentList.arguments.nonSeparatorAt(i), contextualType !== null, context); + + if (contextualType) { + context.popAnyContextualType(); + contextualType = null; + } + } + } + + additionalResults.targetSymbol = targetSymbol; + additionalResults.resolvedSignatures = constructSignatures; + additionalResults.candidateSignature = signature; + additionalResults.actualParametersContextTypeSymbols = actualParametersContextTypeSymbols; + + if (errorCondition) { + return errorCondition; + } + + if (!returnType) { + returnType = this.semanticInfoChain.anyTypeSymbol; + } + + return returnType; + } else if (callEx.argumentList) { + this.resolveAST(callEx.argumentList.arguments, false, context); + } + + this.postOverloadResolutionDiagnostics(this.semanticInfoChain.diagnosticFromAST(targetAST, TypeScript.DiagnosticCode.Invalid_new_expression), additionalResults, context); + + return this.getNewErrorTypeSymbol(); + }; + + PullTypeResolver.prototype.instantiateSignatureInContext = function (signatureAToInstantiate, contextualSignatureB, context, shouldFixContextualSignatureParameterTypes) { + var typeReplacementMap = []; + var inferredTypeArgs; + var specializedSignature; + var typeParameters = signatureAToInstantiate.getTypeParameters(); + var typeConstraint = null; + + var typeArgumentInferenceContext = new TypeScript.ContextualSignatureInstantiationTypeArgumentInferenceContext(this, context, signatureAToInstantiate, contextualSignatureB, shouldFixContextualSignatureParameterTypes); + inferredTypeArgs = this.inferArgumentTypesForSignature(typeArgumentInferenceContext, new TypeComparisonInfo(), context); + + var functionTypeA = signatureAToInstantiate.functionType; + var functionTypeB = contextualSignatureB.functionType; + var enclosingTypeParameterMap; + + if (functionTypeA) { + enclosingTypeParameterMap = functionTypeA.getTypeParameterArgumentMap(); + + for (var id in enclosingTypeParameterMap) { + typeReplacementMap[id] = enclosingTypeParameterMap[id]; + } + } + + if (functionTypeB) { + enclosingTypeParameterMap = functionTypeB.getTypeParameterArgumentMap(); + + for (var id in enclosingTypeParameterMap) { + typeReplacementMap[id] = enclosingTypeParameterMap[id]; + } + } + + TypeScript.PullInstantiationHelpers.updateTypeParameterArgumentMap(typeParameters, inferredTypeArgs, typeReplacementMap); + + return this.instantiateSignature(signatureAToInstantiate, typeReplacementMap); + }; + + PullTypeResolver.prototype.resolveCastExpression = function (assertionExpression, context) { + var typeAssertionType = this.resolveTypeReference(assertionExpression.type, context).type; + + if (this.canTypeCheckAST(assertionExpression, context)) { + this.typeCheckCastExpression(assertionExpression, context, typeAssertionType); + } + + return typeAssertionType; + }; + + PullTypeResolver.prototype.typeCheckCastExpression = function (assertionExpression, context, typeAssertionType) { + this.setTypeChecked(assertionExpression, context); + + context.pushNewContextualType(typeAssertionType); + var exprType = this.resolveAST(assertionExpression.expression, true, context).type; + context.popAnyContextualType(); + + this.resolveDeclaredSymbol(typeAssertionType, context); + this.resolveDeclaredSymbol(exprType, context); + + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(exprType, typeAssertionType, assertionExpression, context, comparisonInfo); + + if (!isAssignable) { + var widenedExprType = exprType.widenedType(this, assertionExpression.expression, context); + isAssignable = this.sourceIsAssignableToTarget(typeAssertionType, widenedExprType, assertionExpression, context, comparisonInfo); + } + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(assertionExpression); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(assertionExpression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [exprType.toString(enclosingSymbol), typeAssertionType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(assertionExpression, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [exprType.toString(enclosingSymbol), typeAssertionType.toString(enclosingSymbol)])); + } + } + }; + + PullTypeResolver.prototype.resolveAssignmentExpression = function (binaryExpression, context) { + var leftExpr = this.resolveAST(binaryExpression.left, false, context); + var leftType = leftExpr.type; + + context.pushNewContextualType(leftType); + var rightType = this.resolveAST(binaryExpression.right, true, context).type; + context.popAnyContextualType(); + + rightType = this.getInstanceTypeForAssignment(binaryExpression.left, rightType, context); + + if (this.canTypeCheckAST(binaryExpression, context)) { + this.setTypeChecked(binaryExpression, context); + + if (!this.isReference(binaryExpression.left, leftExpr)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(binaryExpression.left, TypeScript.DiagnosticCode.Invalid_left_hand_side_of_assignment_expression)); + } else { + this.checkAssignability(binaryExpression.left, rightType, leftExpr.type, context); + } + } + + return rightType; + }; + + PullTypeResolver.prototype.getInstanceTypeForAssignment = function (lhs, type, context) { + var typeToReturn = type; + if (typeToReturn && typeToReturn.isAlias()) { + typeToReturn = typeToReturn.getExportAssignedTypeSymbol(); + } + + if (typeToReturn && typeToReturn.isContainer() && !typeToReturn.isEnum()) { + var instanceTypeSymbol = typeToReturn.getInstanceType(); + + if (!instanceTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(lhs, TypeScript.DiagnosticCode.Tried_to_set_variable_type_to_uninitialized_module_type_0, [type.toString()])); + typeToReturn = null; + } else { + typeToReturn = instanceTypeSymbol; + } + } + + return typeToReturn; + }; + + PullTypeResolver.prototype.widenType = function (type, ast, context) { + if (type === this.semanticInfoChain.undefinedTypeSymbol || type === this.semanticInfoChain.nullTypeSymbol || type.isError()) { + return this.semanticInfoChain.anyTypeSymbol; + } + + if (type.isArrayNamedTypeReference()) { + return this.widenArrayType(type, ast, context); + } else if (type.kind === 256 /* ObjectLiteral */) { + return this.widenObjectLiteralType(type, ast, context); + } + + return type; + }; + + PullTypeResolver.prototype.widenArrayType = function (type, ast, context) { + var elementType = type.getElementType().widenedType(this, ast, context); + + if (this.compilationSettings.noImplicitAny() && ast) { + if (elementType === this.semanticInfoChain.anyTypeSymbol && type.getElementType() !== this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Array_Literal_implicitly_has_an_any_type_from_widening)); + } + } + + return this.getArrayType(elementType); + }; + + PullTypeResolver.prototype.widenObjectLiteralType = function (type, ast, context) { + if (!this.needsToWidenObjectLiteralType(type, ast, context)) { + return type; + } + + TypeScript.Debug.assert(type.name === ""); + var newObjectTypeSymbol = new TypeScript.PullTypeSymbol(type.name, type.kind); + var declsOfObjectType = type.getDeclarations(); + TypeScript.Debug.assert(declsOfObjectType.length === 1); + newObjectTypeSymbol.addDeclaration(declsOfObjectType[0]); + var members = type.getMembers(); + + for (var i = 0; i < members.length; i++) { + var memberType = members[i].type; + + var widenedMemberType = members[i].type.widenedType(this, ast, context); + var newMember = new TypeScript.PullSymbol(members[i].name, members[i].kind); + + var declsOfMember = members[i].getDeclarations(); + + newMember.addDeclaration(declsOfMember[0]); + newMember.type = widenedMemberType; + newObjectTypeSymbol.addMember(newMember); + newMember.setResolved(); + + if (this.compilationSettings.noImplicitAny() && ast && widenedMemberType === this.semanticInfoChain.anyTypeSymbol && memberType !== this.semanticInfoChain.anyTypeSymbol) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Object_literal_s_property_0_implicitly_has_an_any_type_from_widening, [members[i].name])); + } + } + + var indexers = type.getIndexSignatures(); + for (var i = 0; i < indexers.length; i++) { + var newIndexer = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + var parameter = indexers[i].parameters[0]; + var newParameter = new TypeScript.PullSymbol(parameter.name, parameter.kind); + newParameter.type = parameter.type; + newIndexer.addParameter(newParameter); + newIndexer.returnType = indexers[i].returnType; + newObjectTypeSymbol.addIndexSignature(newIndexer); + } + + return newObjectTypeSymbol; + }; + + PullTypeResolver.prototype.needsToWidenObjectLiteralType = function (type, ast, context) { + var members = type.getMembers(); + for (var i = 0; i < members.length; i++) { + var memberType = members[i].type; + if (memberType !== memberType.widenedType(this, ast, context)) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.findBestCommonType = function (collection, context, comparisonInfo) { + var len = collection.getLength(); + + for (var i = 0; i < len; i++) { + var candidateType = collection.getTypeAtIndex(i); + if (this.typeIsBestCommonTypeCandidate(candidateType, collection, context)) { + return candidateType; + } + } + + return this.semanticInfoChain.emptyTypeSymbol; + }; + + PullTypeResolver.prototype.typeIsBestCommonTypeCandidate = function (candidateType, collection, context) { + for (var i = 0; i < collection.getLength(); i++) { + var otherType = collection.getTypeAtIndex(i); + if (candidateType === otherType) { + continue; + } + + if (!this.sourceIsSubtypeOfTarget(otherType, candidateType, null, context)) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.typesAreIdenticalInEnclosingTypes = function (t1, t2, context) { + t1 = this.getSymbolForRelationshipCheck(t1); + t2 = this.getSymbolForRelationshipCheck(t2); + + if (t1 === t2) { + return true; + } + + if (t1 && t2) { + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + return this.infinitelyExpandingTypesAreIdentical(t1, t2, context); + } + } + + return this.typesAreIdentical(t1, t2, context); + }; + + PullTypeResolver.prototype.typesAreIdenticalWithNewEnclosingTypes = function (t1, t2, context) { + var enclosingTypeWalkerStates = context.resetEnclosingTypeWalkerStates(); + var areTypesIdentical = this.typesAreIdentical(t1, t2, context); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areTypesIdentical; + }; + + PullTypeResolver.prototype.typesAreIdentical = function (t1, t2, context) { + t1 = this.getSymbolForRelationshipCheck(t1); + t2 = this.getSymbolForRelationshipCheck(t2); + + if (t1 === t2) { + return true; + } + + if (!t1 || !t2) { + return false; + } + + if (TypeScript.hasFlag(t1.kind, 64 /* Enum */) || TypeScript.hasFlag(t2.kind, 64 /* Enum */)) { + return false; + } + + if (t1.isPrimitive() && t1.isStringConstant() && t2.isPrimitive() && t2.isStringConstant()) { + return TypeScript.stripStartAndEndQuotes(t1.name) === TypeScript.stripStartAndEndQuotes(t2.name); + } + + if (t1.isPrimitive() || t2.isPrimitive()) { + return false; + } + + if (t1.isError() && t2.isError()) { + return true; + } + + var isIdentical = this.identicalCache.valueAt(t1.pullSymbolID, t2.pullSymbolID); + if (isIdentical != undefined) { + return isIdentical; + } + + if (t1.isTypeParameter() !== t2.isTypeParameter()) { + return false; + } else if (t1.isTypeParameter()) { + var t1ParentDeclaration = t1.getDeclarations()[0].getParentDecl(); + var t2ParentDeclaration = t2.getDeclarations()[0].getParentDecl(); + + if (t1ParentDeclaration === t2ParentDeclaration) { + return this.symbolsShareDeclaration(t1, t2); + } else { + return false; + } + } + + if (t1.isPrimitive() !== t2.isPrimitive()) { + return false; + } + + this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, true); + var statesWhenStartedWalkingTypes = context.startWalkingTypes(t1, t2); + isIdentical = this.typesAreIdenticalWorker(t1, t2, context); + context.endWalkingTypes(statesWhenStartedWalkingTypes); + this.identicalCache.setValueAt(t1.pullSymbolID, t2.pullSymbolID, isIdentical); + + return isIdentical; + }; + + PullTypeResolver.prototype.typesAreIdenticalWorker = function (t1, t2, context) { + if (t1.getIsSpecialized() && t2.getIsSpecialized()) { + if (TypeScript.PullHelpers.getRootType(t1) === TypeScript.PullHelpers.getRootType(t2) && TypeScript.PullHelpers.getRootType(t1).isNamedTypeSymbol()) { + var t1TypeArguments = t1.getTypeArguments(); + var t2TypeArguments = t2.getTypeArguments(); + + if (t1TypeArguments && t2TypeArguments) { + for (var i = 0; i < t1TypeArguments.length; i++) { + if (!this.typesAreIdenticalWithNewEnclosingTypes(t1TypeArguments[i], t2TypeArguments[i], context)) { + return false; + } + } + } + + return true; + } + } + + if (t1.hasMembers() && t2.hasMembers()) { + var t1Members = t1.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + var t2Members = t2.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + + if (t1Members.length !== t2Members.length) { + return false; + } + + var t1MemberSymbol = null; + var t2MemberSymbol = null; + + var t1MemberType = null; + var t2MemberType = null; + + for (var iMember = 0; iMember < t1Members.length; iMember++) { + t1MemberSymbol = t1Members[iMember]; + t2MemberSymbol = this.getNamedPropertySymbol(t1MemberSymbol.name, 68147712 /* SomeValue */, t2); + + if (!this.propertiesAreIdentical(t1MemberSymbol, t2MemberSymbol, context)) { + return false; + } + } + } else if (t1.hasMembers() || t2.hasMembers()) { + return false; + } + + var t1CallSigs = t1.getCallSignatures(); + var t2CallSigs = t2.getCallSignatures(); + + var t1ConstructSigs = t1.getConstructSignatures(); + var t2ConstructSigs = t2.getConstructSignatures(); + + var t1IndexSigs = t1.getIndexSignatures(); + var t2IndexSigs = t2.getIndexSignatures(); + + if (!this.signatureGroupsAreIdentical(t1CallSigs, t2CallSigs, context)) { + return false; + } + + if (!this.signatureGroupsAreIdentical(t1ConstructSigs, t2ConstructSigs, context)) { + return false; + } + + if (!this.signatureGroupsAreIdentical(t1IndexSigs, t2IndexSigs, context)) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.propertiesAreIdentical = function (propertySymbol1, propertySymbol2, context) { + if (!propertySymbol2 || (propertySymbol1.isOptional !== propertySymbol2.isOptional)) { + return false; + } + + var t1MemberSymbolIsPrivate = propertySymbol1.anyDeclHasFlag(2 /* Private */); + var t2MemberSymbolIsPrivate = propertySymbol2.anyDeclHasFlag(2 /* Private */); + + if (t1MemberSymbolIsPrivate !== t2MemberSymbolIsPrivate) { + return false; + } else if (t2MemberSymbolIsPrivate && t1MemberSymbolIsPrivate) { + var t1MemberSymbolDecl = propertySymbol1.getDeclarations()[0]; + var sourceDecl = propertySymbol2.getDeclarations()[0]; + if (t1MemberSymbolDecl !== sourceDecl) { + return false; + } + } + + var t1MemberType = propertySymbol1.type; + var t2MemberType = propertySymbol2.type; + + context.walkMemberTypes(propertySymbol1.name); + var areMemberTypesIdentical = this.typesAreIdenticalInEnclosingTypes(t1MemberType, t2MemberType, context); + context.postWalkMemberTypes(); + return areMemberTypesIdentical; + }; + + PullTypeResolver.prototype.propertiesAreIdenticalWithNewEnclosingTypes = function (type1, type2, property1, property2, context) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(type1, type2); + var arePropertiesIdentical = this.propertiesAreIdentical(property1, property2, context); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return arePropertiesIdentical; + }; + + PullTypeResolver.prototype.signatureGroupsAreIdentical = function (sg1, sg2, context) { + if (sg1 === sg2) { + return true; + } + + if (!sg1 || !sg2) { + return false; + } + + if (sg1.length !== sg2.length) { + return false; + } + + for (var i = 0; i < sg1.length; i++) { + context.walkSignatures(sg1[i].kind, i); + var areSignaturesIdentical = this.signaturesAreIdentical(sg1[i], sg2[i], context, true); + context.postWalkSignatures(); + if (!areSignaturesIdentical) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.typeParametersAreIdentical = function (tp1, tp2, context) { + var typeParamsAreIdentical = this.typeParametersAreIdenticalWorker(tp1, tp2, context); + + this.setTypeParameterIdentity(tp1, tp2, undefined); + + return typeParamsAreIdentical; + }; + + PullTypeResolver.prototype.typeParametersAreIdenticalWorker = function (tp1, tp2, context) { + if (!!(tp1 && tp1.length) !== !!(tp2 && tp2.length)) { + return false; + } + + if (tp1 && tp2 && (tp1.length !== tp2.length)) { + return false; + } + + if (tp1 && tp2) { + for (var i = 0; i < tp1.length; i++) { + context.walkTypeParameterConstraints(i); + var areConstraintsIdentical = this.typesAreIdentical(tp1[i].getConstraint(), tp2[i].getConstraint(), context); + context.postWalkTypeParameterConstraints(); + if (!areConstraintsIdentical) { + return false; + } + } + } + + return true; + }; + + PullTypeResolver.prototype.setTypeParameterIdentity = function (tp1, tp2, val) { + if (tp1 && tp2 && tp1.length === tp2.length) { + for (var i = 0; i < tp1.length; i++) { + this.identicalCache.setValueAt(tp1[i].pullSymbolID, tp2[i].pullSymbolID, val); + } + } + }; + + PullTypeResolver.prototype.signaturesAreIdenticalWithNewEnclosingTypes = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(s1, s2); + var areSignaturesIdentical = this.signaturesAreIdentical(s1, s2, context, includingReturnType); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSignaturesIdentical; + }; + + PullTypeResolver.prototype.signaturesAreIdentical = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + if (s1 === s2) { + return true; + } + + var signaturesIdentical = this.identicalCache.valueAt(s1.pullSymbolID, s2.pullSymbolID); + if (signaturesIdentical || (signaturesIdentical != undefined && includingReturnType)) { + return signaturesIdentical; + } + + var oldValue = signaturesIdentical; + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, true); + + signaturesIdentical = this.signaturesAreIdenticalWorker(s1, s2, context, includingReturnType); + + if (includingReturnType) { + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, signaturesIdentical); + } else { + this.identicalCache.setValueAt(s1.pullSymbolID, s2.pullSymbolID, oldValue); + } + + return signaturesIdentical; + }; + + PullTypeResolver.prototype.signaturesAreIdenticalWorker = function (s1, s2, context, includingReturnType) { + if (typeof includingReturnType === "undefined") { includingReturnType = true; } + if (s1.hasVarArgs !== s2.hasVarArgs) { + return false; + } + + if (s1.nonOptionalParamCount !== s2.nonOptionalParamCount) { + return false; + } + + if (s1.parameters.length !== s2.parameters.length) { + return false; + } + + var s1TypeParameters = s1.getTypeParameters(); + var s2TypeParameters = s2.getTypeParameters(); + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, true); + + var typeParametersParametersAndReturnTypesAreIdentical = this.signatureTypeParametersParametersAndReturnTypesAreIdentical(s1, s2, context, includingReturnType); + + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, undefined); + return typeParametersParametersAndReturnTypesAreIdentical; + }; + + PullTypeResolver.prototype.signatureTypeParametersParametersAndReturnTypesAreIdentical = function (s1, s2, context, includingReturnType) { + if (!this.typeParametersAreIdenticalWorker(s1.getTypeParameters(), s2.getTypeParameters(), context)) { + return false; + } + + if (includingReturnType) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s1); + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s2); + context.walkReturnTypes(); + var areReturnTypesIdentical = this.typesAreIdenticalInEnclosingTypes(s1.returnType, s2.returnType, context); + context.postWalkReturnTypes(); + if (!areReturnTypesIdentical) { + return false; + } + } + + var s1Params = s1.parameters; + var s2Params = s2.parameters; + + for (var iParam = 0; iParam < s1Params.length; iParam++) { + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s1Params[iParam]); + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(s2Params[iParam]); + context.walkParameterTypes(iParam); + var areParameterTypesIdentical = this.typesAreIdenticalInEnclosingTypes(s1Params[iParam].type, s2Params[iParam].type, context); + context.postWalkParameterTypes(); + + if (!areParameterTypesIdentical) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.signatureReturnTypesAreIdentical = function (s1, s2, context) { + var s1TypeParameters = s1.getTypeParameters(); + var s2TypeParameters = s2.getTypeParameters(); + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, true); + + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(s1, s2); + context.walkReturnTypes(); + var returnTypeIsIdentical = this.typesAreIdenticalInEnclosingTypes(s1.returnType, s2.returnType, context); + + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + + this.setTypeParameterIdentity(s1TypeParameters, s2TypeParameters, undefined); + + return returnTypeIsIdentical; + }; + + PullTypeResolver.prototype.symbolsShareDeclaration = function (symbol1, symbol2) { + var decls1 = symbol1.getDeclarations(); + var decls2 = symbol2.getDeclarations(); + + if (decls1.length && decls2.length) { + return decls1[0] === decls2[0]; + } + + return false; + }; + + PullTypeResolver.prototype.sourceIsSubtypeOfTarget = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.sourceMembersAreAssignableToTargetMembers = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceMembersAreAssignableToTargetMembers = this.sourceMembersAreRelatableToTargetMembers(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceMembersAreAssignableToTargetMembers; + }; + + PullTypeResolver.prototype.sourcePropertyIsAssignableToTargetProperty = function (source, target, sourceProp, targetProp, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var isSourcePropertyIsAssignableToTargetProperty = this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return isSourcePropertyIsAssignableToTargetProperty; + }; + + PullTypeResolver.prototype.sourceCallSignaturesAreAssignableToTargetCallSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceCallSignaturesAssignableToTargetCallSignatures = this.sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceCallSignaturesAssignableToTargetCallSignatures; + }; + + PullTypeResolver.prototype.sourceConstructSignaturesAreAssignableToTargetConstructSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceConstructSignaturesAssignableToTargetConstructSignatures = this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceConstructSignaturesAssignableToTargetConstructSignatures; + }; + + PullTypeResolver.prototype.sourceIndexSignaturesAreAssignableToTargetIndexSignatures = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(source, target); + var areSourceIndexSignaturesAssignableToTargetIndexSignatures = this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return areSourceIndexSignaturesAssignableToTargetIndexSignatures; + }; + + PullTypeResolver.prototype.typeIsAssignableToFunction = function (source, ast, context) { + if (source.isFunctionType()) { + return true; + } + + return this.cachedFunctionInterfaceType() && this.sourceIsAssignableToTarget(source, this.cachedFunctionInterfaceType(), ast, context); + }; + + PullTypeResolver.prototype.signatureIsAssignableToTarget = function (s1, s2, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.setEnclosingTypeForSymbols(s1, s2); + var isSignatureIsAssignableToTarget = this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return isSignatureIsAssignableToTarget; + }; + + PullTypeResolver.prototype.sourceIsAssignableToTarget = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + return this.sourceIsRelatableToTarget(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.sourceIsAssignableToTargetWithNewEnclosingTypes = function (source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + return this.sourceIsRelatableToTargetWithNewEnclosingTypes(source, target, true, this.assignableCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.getSymbolForRelationshipCheck = function (symbol) { + if (symbol && symbol.isTypeReference()) { + return symbol.getReferencedTypeSymbol(); + } + + return symbol; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetInEnclosingTypes = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + source = this.getSymbolForRelationshipCheck(source); + target = this.getSymbolForRelationshipCheck(target); + + if (source === target) { + return true; + } + + if (source && target) { + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + return this.infinitelyExpandingSourceTypeIsRelatableToTargetType(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + } + } + + return this.sourceIsRelatableToTarget(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetWithNewEnclosingTypes = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var enclosingTypeWalkerStates = context.resetEnclosingTypeWalkerStates(); + var isSourceRelatable = this.sourceIsRelatableToTarget(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + return isSourceRelatable; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetInCache = function (source, target, comparisonCache, comparisonInfo) { + var isRelatable = comparisonCache.valueAt(source.pullSymbolID, target.pullSymbolID); + + if (isRelatable) { + return { isRelatable: isRelatable }; + } + + if (isRelatable != undefined && !comparisonInfo) { + return { isRelatable: isRelatable }; + } + + return null; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + source = this.getSymbolForRelationshipCheck(source); + target = this.getSymbolForRelationshipCheck(target); + + if (source === target) { + return true; + } + + if (!(source && target)) { + return true; + } + + var sourceApparentType = this.getApparentType(source); + + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(source, target, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; + } + + if (source === this.semanticInfoChain.stringTypeSymbol && target.isPrimitive() && target.isStringConstant()) { + return comparisonInfo && comparisonInfo.stringConstantVal && (comparisonInfo.stringConstantVal.kind() === 14 /* StringLiteral */) && (TypeScript.stripStartAndEndQuotes(comparisonInfo.stringConstantVal.text()) === TypeScript.stripStartAndEndQuotes(target.name)); + } + + if (assignableTo) { + if (this.isAnyOrEquivalent(source) || this.isAnyOrEquivalent(target)) { + return true; + } + } else { + if (this.isAnyOrEquivalent(target)) { + return true; + } + } + + if (target === this.semanticInfoChain.stringTypeSymbol && source.isPrimitive() && source.isStringConstant()) { + return true; + } + + if (source.isPrimitive() && source.isStringConstant() && target.isPrimitive() && target.isStringConstant()) { + return TypeScript.stripStartAndEndQuotes(source.name) === TypeScript.stripStartAndEndQuotes(target.name); + } + + if (source === this.semanticInfoChain.undefinedTypeSymbol) { + return true; + } + + if ((source === this.semanticInfoChain.nullTypeSymbol) && (target !== this.semanticInfoChain.undefinedTypeSymbol && target != this.semanticInfoChain.voidTypeSymbol)) { + return true; + } + + if (target === this.semanticInfoChain.voidTypeSymbol) { + if (source === this.semanticInfoChain.undefinedTypeSymbol || source == this.semanticInfoChain.nullTypeSymbol) { + return true; + } + + return false; + } else if (source === this.semanticInfoChain.voidTypeSymbol) { + if (target === this.semanticInfoChain.anyTypeSymbol) { + return true; + } + + return false; + } + + if (target === this.semanticInfoChain.numberTypeSymbol && TypeScript.PullHelpers.symbolIsEnum(source)) { + return true; + } + + if (source === this.semanticInfoChain.numberTypeSymbol && TypeScript.PullHelpers.symbolIsEnum(target)) { + return assignableTo; + } + + if (TypeScript.PullHelpers.symbolIsEnum(target) && TypeScript.PullHelpers.symbolIsEnum(source)) { + return this.symbolsShareDeclaration(target, source); + } + + if ((source.kind & 64 /* Enum */) || (target.kind & 64 /* Enum */)) { + return false; + } + + if (source.getIsSpecialized() && target.getIsSpecialized()) { + if (TypeScript.PullHelpers.getRootType(source) === TypeScript.PullHelpers.getRootType(target) && TypeScript.PullHelpers.getRootType(source).isNamedTypeSymbol()) { + var sourceTypeArguments = source.getTypeArguments(); + var targetTypeArguments = target.getTypeArguments(); + + if (sourceTypeArguments && targetTypeArguments) { + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, true); + + for (var i = 0; i < sourceTypeArguments.length; i++) { + if (!this.sourceIsRelatableToTargetWithNewEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, null, isComparingInstantiatedSignatures)) { + break; + } + } + + if (i === sourceTypeArguments.length) { + return true; + } else { + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, undefined); + } + } + } + } + + if (target.isTypeParameter()) { + if (source.isTypeParameter()) { + if (!source.getConstraint()) { + return this.typesAreIdentical(target, source, context); + } else { + return this.isSourceTypeParameterConstrainedToTargetTypeParameter(source, target); + } + } else { + if (isComparingInstantiatedSignatures) { + target = target.getBaseConstraint(this.semanticInfoChain); + } else { + return this.typesAreIdentical(target, sourceApparentType, context); + } + } + } + + if (sourceApparentType.isPrimitive() || target.isPrimitive()) { + return false; + } + + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, true); + + var symbolsWhenStartedWalkingTypes = context.startWalkingTypes(sourceApparentType, target); + var isRelatable = this.sourceIsRelatableToTargetWorker(sourceApparentType, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.endWalkingTypes(symbolsWhenStartedWalkingTypes); + + comparisonCache.setValueAt(source.pullSymbolID, target.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.isSourceTypeParameterConstrainedToTargetTypeParameter = function (source, target) { + var current = source; + while (current && current.isTypeParameter()) { + if (current === target) { + return true; + } + + current = current.getConstraint(); + } + return false; + }; + + PullTypeResolver.prototype.sourceIsRelatableToTargetWorker = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + if (target.hasMembers() && !this.sourceMembersAreRelatableToTargetMembers(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + if (!this.sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.sourceMembersAreRelatableToTargetMembers = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetProps = target.getAllMembers(68147712 /* SomeValue */, 0 /* all */); + + for (var itargetProp = 0; itargetProp < targetProps.length; itargetProp++) { + var targetProp = targetProps[itargetProp]; + + var sourceProp = this._getNamedPropertySymbolOfAugmentedType(targetProp.name, source); + + this.resolveDeclaredSymbol(targetProp, context); + + var targetPropType = targetProp.type; + + if (!sourceProp) { + if (!(targetProp.isOptional)) { + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_is_missing_property_1_from_type_2, [source.toString(enclosingSymbol), targetProp.getScopedNameEx().toString(), target.toString(enclosingSymbol)])); + } + return false; + } + continue; + } + + if (!this.sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures)) { + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.infinitelyExpandingSourceTypeIsRelatableToTargetType = function (sourceType, targetType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var widenedTargetType = targetType.widenedType(this, null, context); + var widenedSourceType = sourceType.widenedType(this, null, context); + + if ((widenedSourceType !== this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType !== this.semanticInfoChain.anyTypeSymbol)) { + var sourceTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(sourceType); + var targetTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(targetType); + + if (sourceTypeNamedTypeReference !== targetTypeNamedTypeReference) { + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_do_not_refer_to_same_named_type, [sourceType.getScopedNameEx(enclosingSymbol).toString(), targetType.toString(enclosingSymbol)])); + } + return false; + } + + var sourceTypeArguments = sourceType.getTypeArguments(); + var targetTypeArguments = targetType.getTypeArguments(); + + if (!sourceTypeArguments && !targetTypeArguments) { + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, true); + return true; + } + + if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length !== targetTypeArguments.length) { + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)])); + } + return false; + } + + var comparisonInfoTypeArgumentsCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoTypeArgumentsCheck = new TypeComparisonInfo(comparisonInfo); + } + var isRelatable = true; + for (var i = 0; i < sourceTypeArguments.length && isRelatable; i++) { + context.walkTypeArgument(i); + + if (!this.sourceIsRelatableToTargetInEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], assignableTo, comparisonCache, ast, context, comparisonInfoTypeArgumentsCheck, isComparingInstantiatedSignatures)) { + isRelatable = false; + if (comparisonInfo) { + var message; + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + + if (comparisonInfoTypeArgumentsCheck && comparisonInfoTypeArgumentsCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol), comparisonInfoTypeArgumentsCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments, [sourceType.toString(enclosingSymbol), targetType.toString(enclosingSymbol)]); + } + comparisonInfo.addMessage(message); + } + } + + context.postWalkTypeArgument(); + } + } + + comparisonCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.infinitelyExpandingTypesAreIdentical = function (sourceType, targetType, context) { + var widenedTargetType = targetType.widenedType(this, null, null); + var widenedSourceType = sourceType.widenedType(this, null, null); + + if ((widenedSourceType !== this.semanticInfoChain.anyTypeSymbol) && (widenedTargetType !== this.semanticInfoChain.anyTypeSymbol)) { + var sourceTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(sourceType); + var targetTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(targetType); + if (sourceTypeNamedTypeReference !== targetTypeNamedTypeReference) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + return false; + } + + var sourceTypeArguments = sourceType.getTypeArguments(); + var targetTypeArguments = targetType.getTypeArguments(); + + if (!sourceTypeArguments && !targetTypeArguments) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, true); + return true; + } + + if (!(sourceTypeArguments && targetTypeArguments) || sourceTypeArguments.length !== targetTypeArguments.length) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + return false; + } + + for (var i = 0; i < sourceTypeArguments.length; i++) { + context.walkTypeArgument(i); + var areIdentical = this.typesAreIdenticalInEnclosingTypes(sourceTypeArguments[i], targetTypeArguments[i], context); + context.postWalkTypeArgument(); + + if (!areIdentical) { + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, false); + return false; + } + } + } + + this.identicalCache.setValueAt(sourceType.pullSymbolID, targetType.pullSymbolID, true); + return true; + }; + + PullTypeResolver.prototype.sourcePropertyIsRelatableToTargetProperty = function (source, target, sourceProp, targetProp, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var _this = this; + var sourceAndTargetAreConstructors = source.isConstructor() && target.isConstructor(); + + var getNames = function (takeTypesFromPropertyContainers) { + var enclosingSymbol = _this.getEnclosingSymbolForAST(ast); + var sourceType = takeTypesFromPropertyContainers ? sourceProp.getContainer() : source; + var targetType = takeTypesFromPropertyContainers ? targetProp.getContainer() : target; + if (sourceAndTargetAreConstructors) { + sourceType = sourceType.getAssociatedContainerType(); + targetType = targetType.getAssociatedContainerType(); + } + return { + propertyName: targetProp.getScopedNameEx().toString(), + sourceTypeName: sourceType.toString(enclosingSymbol), + targetTypeName: targetType.toString(enclosingSymbol) + }; + }; + + var targetPropIsPrivate = targetProp.anyDeclHasFlag(2 /* Private */); + var sourcePropIsPrivate = sourceProp.anyDeclHasFlag(2 /* Private */); + + if (targetPropIsPrivate !== sourcePropIsPrivate) { + if (comparisonInfo) { + var names = getNames(true); + var code; + if (targetPropIsPrivate) { + code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Static_property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2 : TypeScript.DiagnosticCode.Property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2; + } else { + code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Static_property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2 : TypeScript.DiagnosticCode.Property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2; + } + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName])); + comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; + } + return false; + } else if (sourcePropIsPrivate && targetPropIsPrivate) { + var targetDecl = targetProp.getDeclarations()[0]; + var sourceDecl = sourceProp.getDeclarations()[0]; + + if (targetDecl !== sourceDecl) { + if (comparisonInfo) { + var names = getNames(true); + + comparisonInfo.flags |= 128 /* InconsistantPropertyAccesibility */; + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_0_and_1_define_static_property_2_as_private : TypeScript.DiagnosticCode.Types_0_and_1_define_property_2_as_private; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(code, [names.sourceTypeName, names.targetTypeName, names.propertyName])); + } + + return false; + } + } + + if (sourceProp.isOptional && !targetProp.isOptional) { + if (comparisonInfo) { + var names = getNames(true); + comparisonInfo.flags |= 2 /* RequiredPropertyIsMissing */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2, [names.propertyName, names.sourceTypeName, names.targetTypeName])); + } + return false; + } + + this.resolveDeclaredSymbol(sourceProp, context); + + var sourcePropType = sourceProp.type; + var targetPropType = targetProp.type; + + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(sourcePropType, targetPropType, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; + } + + var comparisonInfoPropertyTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoPropertyTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + context.walkMemberTypes(targetProp.name); + var isSourcePropertyRelatableToTargetProperty = this.sourceIsRelatableToTargetInEnclosingTypes(sourcePropType, targetPropType, assignableTo, comparisonCache, ast, context, comparisonInfoPropertyTypeCheck, isComparingInstantiatedSignatures); + context.postWalkMemberTypes(); + + if (!isSourcePropertyRelatableToTargetProperty && comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + comparisonInfo.flags |= 32 /* IncompatiblePropertyTypes */; + var message; + var names = getNames(false); + if (comparisonInfoPropertyTypeCheck && comparisonInfoPropertyTypeCheck.message) { + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3 : TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3; + message = TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName, comparisonInfoPropertyTypeCheck.message]); + } else { + var code = sourceAndTargetAreConstructors ? TypeScript.DiagnosticCode.Types_of_static_property_0_of_class_1_and_class_2_are_incompatible : TypeScript.DiagnosticCode.Types_of_property_0_of_types_1_and_2_are_incompatible; + message = TypeScript.getDiagnosticMessage(code, [names.propertyName, names.sourceTypeName, names.targetTypeName]); + } + comparisonInfo.addMessage(message); + } + + return isSourcePropertyRelatableToTargetProperty; + }; + + PullTypeResolver.prototype.sourceCallSignaturesAreRelatableToTargetCallSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetCallSigs = target.getCallSignatures(); + + if (targetCallSigs.length) { + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + var sourceCallSigs = source.getCallSignatures(); + if (!this.signatureGroupIsRelatableToTarget(source, target, sourceCallSigs, targetCallSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { + if (comparisonInfo) { + var message; + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + if (sourceCallSigs.length && targetCallSigs.length) { + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signatures_of_types_0_and_1_are_incompatible_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signatures_of_types_0_and_1_are_incompatible, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)]); + } + } else { + var hasSig = targetCallSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + var lacksSig = !targetCallSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_requires_a_call_signature_but_type_1_lacks_one, [hasSig, lacksSig]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.sourceConstructSignaturesAreRelatableToTargetConstructSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetConstructSigs = target.getConstructSignatures(); + if (targetConstructSigs.length) { + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + var sourceConstructSigs = source.getConstructSignatures(); + if (!this.signatureGroupIsRelatableToTarget(source, target, sourceConstructSigs, targetConstructSigs, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures)) { + if (comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + var message; + if (sourceConstructSigs.length && targetConstructSigs.length) { + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Construct_signatures_of_types_0_and_1_are_incompatible_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Construct_signatures_of_types_0_and_1_are_incompatible, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)]); + } + } else { + var hasSig = targetConstructSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + var lacksSig = !targetConstructSigs.length ? target.toString(enclosingSymbol) : source.toString(enclosingSymbol); + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_0_requires_a_construct_signature_but_type_1_lacks_one, [hasSig, lacksSig]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.sourceIndexSignaturesAreRelatableToTargetIndexSignatures = function (source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var targetIndexSigs = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(target, context); + var targetStringSig = targetIndexSigs.stringSignature; + var targetNumberSig = targetIndexSigs.numericSignature; + + if (targetStringSig || targetNumberSig) { + var sourceIndexSigs = this.getBothKindsOfIndexSignaturesIncludingAugmentedType(source, context); + var enclosingTypeIndexSigs = context.getBothKindOfIndexSignatures(true, false); + var sourceStringSig = sourceIndexSigs.stringSignature; + var sourceNumberSig = sourceIndexSigs.numericSignature; + + var comparable = true; + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo && !comparisonInfo.onlyCaptureFirstError) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo); + } + + if (targetStringSig) { + if (sourceStringSig) { + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, true, true); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceStringSig.returnType, targetStringSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); + } else { + comparable = false; + } + } + + if (comparable && targetNumberSig) { + if (sourceNumberSig) { + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, false, false); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceNumberSig.returnType, targetNumberSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); + } else if (sourceStringSig) { + context.walkIndexSignatureReturnTypes(enclosingTypeIndexSigs, true, false); + comparable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceStringSig.returnType, targetNumberSig.returnType, assignableTo, comparisonCache, ast, context, comparisonInfoSignatuesTypeCheck, isComparingInstantiatedSignatures); + context.postWalkIndexSignatureReturnTypes(); + } else { + comparable = false; + } + } + + if (!comparable) { + if (comparisonInfo) { + var message; + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + if (comparisonInfoSignatuesTypeCheck && comparisonInfoSignatuesTypeCheck.message) { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Index_signatures_of_types_0_and_1_are_incompatible_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfoSignatuesTypeCheck.message]); + } else { + message = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Index_signatures_of_types_0_and_1_are_incompatible, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)]); + } + comparisonInfo.flags |= 4 /* IncompatibleSignatures */; + comparisonInfo.addMessage(message); + } + return false; + } + } + + return true; + }; + + PullTypeResolver.prototype.signatureGroupIsRelatableToTarget = function (source, target, sourceSG, targetSG, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + if (sourceSG === targetSG) { + return true; + } + + if (!(sourceSG.length && targetSG.length)) { + return false; + } + + var foundMatch = false; + + var targetExcludeDefinition = targetSG.length > 1; + var sourceExcludeDefinition = sourceSG.length > 1; + var sigsCompared = 0; + var comparisonInfoSignatuesTypeCheck = null; + if (comparisonInfo) { + comparisonInfoSignatuesTypeCheck = new TypeComparisonInfo(comparisonInfo, true); + comparisonInfoSignatuesTypeCheck.message = comparisonInfo.message; + } + for (var iMSig = 0; iMSig < targetSG.length; iMSig++) { + var mSig = targetSG[iMSig]; + + if (mSig.isStringConstantOverloadSignature() || (targetExcludeDefinition && mSig.isDefinition())) { + continue; + } + + for (var iNSig = 0; iNSig < sourceSG.length; iNSig++) { + var nSig = sourceSG[iNSig]; + + if (nSig.isStringConstantOverloadSignature() || (sourceExcludeDefinition && nSig.isDefinition())) { + continue; + } + + context.walkSignatures(nSig.kind, iNSig, iMSig); + var isSignatureRelatableToTarget = this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, ast, context, sigsCompared == 0 ? comparisonInfoSignatuesTypeCheck : null, isComparingInstantiatedSignatures); + context.postWalkSignatures(); + + sigsCompared++; + + if (isSignatureRelatableToTarget) { + foundMatch = true; + break; + } + } + + if (foundMatch) { + foundMatch = false; + continue; + } + + if (comparisonInfo && sigsCompared == 1) { + comparisonInfo.message = comparisonInfoSignatuesTypeCheck.message; + } + + return false; + } + + return true; + }; + + PullTypeResolver.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var isRelatableInfo = this.sourceIsRelatableToTargetInCache(sourceSig, targetSig, comparisonCache, comparisonInfo); + if (isRelatableInfo) { + return isRelatableInfo.isRelatable; + } + + comparisonCache.setValueAt(sourceSig.pullSymbolID, targetSig.pullSymbolID, true); + var isRelatable = this.signatureIsRelatableToTargetWorker(sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + comparisonCache.setValueAt(sourceSig.pullSymbolID, targetSig.pullSymbolID, isRelatable); + return isRelatable; + }; + + PullTypeResolver.prototype.signatureIsRelatableToTargetWorker = function (sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures) { + var _this = this; + var sourceParameters = sourceSig.parameters; + var targetParameters = targetSig.parameters; + + if (!sourceParameters || !targetParameters) { + return false; + } + + var targetNonOptionalParamCount = targetSig.nonOptionalParamCount; + var sourceNonOptionalParamCount = sourceSig.nonOptionalParamCount; + + if (!targetSig.hasVarArgs && sourceNonOptionalParamCount > targetParameters.length) { + if (comparisonInfo) { + comparisonInfo.flags |= 3 /* SourceSignatureHasTooManyParameters */; + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Call_signature_expects_0_or_fewer_parameters, [targetParameters.length])); + } + return false; + } + + if (this.signaturesAreIdentical(sourceSig, targetSig, context)) { + return true; + } + + if (targetSig.isGeneric()) { + targetSig = this.instantiateSignatureToAny(targetSig); + } + + if (sourceSig.isGeneric()) { + sourceSig = this.instantiateSignatureToAny(sourceSig); + } + + var sourceReturnType = sourceSig.returnType; + var targetReturnType = targetSig.returnType; + + if (targetReturnType !== this.semanticInfoChain.voidTypeSymbol) { + context.walkReturnTypes(); + var returnTypesAreRelatable = this.sourceIsRelatableToTargetInEnclosingTypes(sourceReturnType, targetReturnType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.postWalkReturnTypes(); + if (!returnTypesAreRelatable) { + if (comparisonInfo) { + comparisonInfo.flags |= 16 /* IncompatibleReturnTypes */; + } + + return false; + } + } + + return targetSig.forAllCorrespondingParameterTypesInThisAndOtherSignature(sourceSig, function (targetParamType, sourceParamType, iParam) { + context.walkParameterTypes(iParam); + var areParametersRelatable = _this.sourceIsRelatableToTargetInEnclosingTypes(sourceParamType, targetParamType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + if (!areParametersRelatable) { + context.swapEnclosingTypeWalkers(); + areParametersRelatable = _this.sourceIsRelatableToTargetInEnclosingTypes(targetParamType, sourceParamType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + context.swapEnclosingTypeWalkers(); + } + context.postWalkParameterTypes(); + + if (!areParametersRelatable) { + if (comparisonInfo) { + comparisonInfo.flags |= 64 /* IncompatibleParameterTypes */; + } + } + + return areParametersRelatable; + }); + }; + + PullTypeResolver.prototype.resolveOverloads = function (application, group, haveTypeArgumentsAtCallSite, context, diagnostics) { + var _this = this; + var hasOverloads = group.length > 1; + var comparisonInfo = new TypeComparisonInfo(); + var args = application.argumentList ? application.argumentList.arguments : null; + + var initialCandidates = TypeScript.ArrayUtilities.where(group, function (signature) { + if (hasOverloads && signature.isDefinition()) { + return false; + } + + var rootSignature = signature.getRootSymbol(); + if (haveTypeArgumentsAtCallSite && !rootSignature.isGeneric()) { + return false; + } + + return _this.overloadHasCorrectArity(signature, args); + }); + + var firstAssignableButNotSupertypeSignature = null; + var firstAssignableWithProvisionalErrorsSignature = null; + + for (var i = 0; i < initialCandidates.length; i++) { + var applicability = this.overloadIsApplicable(initialCandidates[i], args, context, comparisonInfo); + if (applicability === 3 /* Subtype */) { + return initialCandidates[i]; + } else if (applicability === 2 /* AssignableWithNoProvisionalErrors */ && !firstAssignableButNotSupertypeSignature) { + firstAssignableButNotSupertypeSignature = initialCandidates[i]; + } else if (applicability === 1 /* AssignableButWithProvisionalErrors */ && !firstAssignableWithProvisionalErrorsSignature) { + firstAssignableWithProvisionalErrorsSignature = initialCandidates[i]; + } + } + + if (firstAssignableButNotSupertypeSignature || firstAssignableWithProvisionalErrorsSignature) { + return firstAssignableButNotSupertypeSignature || firstAssignableWithProvisionalErrorsSignature; + } else { + var target = this.getCallTargetErrorSpanAST(application); + if (comparisonInfo.message) { + diagnostics.push(this.semanticInfoChain.diagnosticFromAST(target, TypeScript.DiagnosticCode.Supplied_parameters_do_not_match_any_signature_of_call_target_NL_0, [comparisonInfo.message])); + } else { + diagnostics.push(this.semanticInfoChain.diagnosticFromAST(target, TypeScript.DiagnosticCode.Supplied_parameters_do_not_match_any_signature_of_call_target, null)); + } + } + + return null; + }; + + PullTypeResolver.prototype.getCallTargetErrorSpanAST = function (callEx) { + return (callEx.expression.kind() === 212 /* MemberAccessExpression */) ? callEx.expression.name : callEx.expression; + }; + + PullTypeResolver.prototype.overloadHasCorrectArity = function (signature, args) { + if (args == null) { + return signature.nonOptionalParamCount === 0; + } + + var numberOfArgs = (args.nonSeparatorCount() && args.nonSeparatorCount() === args.separatorCount()) ? args.separatorCount() + 1 : args.nonSeparatorCount(); + if (numberOfArgs < signature.nonOptionalParamCount) { + return false; + } + if (!signature.hasVarArgs && numberOfArgs > signature.parameters.length) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.overloadIsApplicable = function (signature, args, context, comparisonInfo) { + if (args === null) { + return 3 /* Subtype */; + } + + var isInVarArg = false; + var parameters = signature.parameters; + var paramType = null; + + var overloadApplicability = 3 /* Subtype */; + + for (var i = 0; i < args.nonSeparatorCount(); i++) { + if (!isInVarArg) { + this.resolveDeclaredSymbol(parameters[i], context); + + if (parameters[i].isVarArg) { + paramType = parameters[i].type.getElementType() || this.getNewErrorTypeSymbol(parameters[i].type.getName()); + isInVarArg = true; + } else { + paramType = parameters[i].type; + } + } + + var statusOfCurrentArgument = this.overloadIsApplicableForArgument(paramType, args.nonSeparatorAt(i), i, context, comparisonInfo); + + if (statusOfCurrentArgument === 0 /* NotAssignable */) { + return 0 /* NotAssignable */; + } else if (statusOfCurrentArgument === 1 /* AssignableButWithProvisionalErrors */) { + overloadApplicability = 1 /* AssignableButWithProvisionalErrors */; + } else if (overloadApplicability !== 1 /* AssignableButWithProvisionalErrors */ && statusOfCurrentArgument === 2 /* AssignableWithNoProvisionalErrors */) { + overloadApplicability = 2 /* AssignableWithNoProvisionalErrors */; + } + } + + return overloadApplicability; + }; + + PullTypeResolver.prototype.overloadIsApplicableForArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + if (paramType.isAny()) { + return 3 /* Subtype */; + } else if (paramType.isError()) { + return 1 /* AssignableButWithProvisionalErrors */; + } else if (arg.kind() === 219 /* SimpleArrowFunctionExpression */) { + var simpleArrowFunction = arg; + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, null, TypeScript.ASTHelpers.parametersFromIdentifier(simpleArrowFunction.identifier), null, simpleArrowFunction.block, simpleArrowFunction.expression, argIndex, context, comparisonInfo); + } else if (arg.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { + var arrowFunction = arg; + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, arrowFunction.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(arrowFunction.callSignature.parameterList), TypeScript.ASTHelpers.getType(arrowFunction), arrowFunction.block, arrowFunction.expression, argIndex, context, comparisonInfo); + } else if (arg.kind() === 222 /* FunctionExpression */) { + var functionExpression = arg; + return this.overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, functionExpression.callSignature.typeParameterList, TypeScript.ASTHelpers.parametersFromParameterList(functionExpression.callSignature.parameterList), TypeScript.ASTHelpers.getType(functionExpression), functionExpression.block, null, argIndex, context, comparisonInfo); + } else if (arg.kind() === 215 /* ObjectLiteralExpression */) { + return this.overloadIsApplicableForObjectLiteralArgument(paramType, arg, argIndex, context, comparisonInfo); + } else if (arg.kind() === 214 /* ArrayLiteralExpression */) { + return this.overloadIsApplicableForArrayLiteralArgument(paramType, arg, argIndex, context, comparisonInfo); + } else { + return this.overloadIsApplicableForOtherArgument(paramType, arg, argIndex, context, comparisonInfo); + } + }; + + PullTypeResolver.prototype.overloadIsApplicableForAnyFunctionExpressionArgument = function (paramType, arg, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, argIndex, context, comparisonInfo) { + if (this.cachedFunctionInterfaceType() && paramType === this.cachedFunctionInterfaceType()) { + return 2 /* AssignableWithNoProvisionalErrors */; + } + + context.pushProvisionalType(paramType); + + var argSym = this.resolveAnyFunctionExpression(arg, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, true, context); + + var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + + context.popAnyContextualType(); + + return applicabilityStatus; + }; + + PullTypeResolver.prototype.overloadIsApplicableForObjectLiteralArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + if (this.cachedObjectInterfaceType() && paramType === this.cachedObjectInterfaceType()) { + return 2 /* AssignableWithNoProvisionalErrors */; + } + + context.pushProvisionalType(paramType); + var argSym = this.resolveObjectLiteralExpression(arg, true, context); + + var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + + context.popAnyContextualType(); + + return applicabilityStatus; + }; + + PullTypeResolver.prototype.overloadIsApplicableForArrayLiteralArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + if (paramType === this.cachedArrayInterfaceType()) { + return 2 /* AssignableWithNoProvisionalErrors */; + } + + context.pushProvisionalType(paramType); + var argSym = this.resolveArrayLiteralExpression(arg, true, context); + + var applicabilityStatus = this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + + context.popAnyContextualType(); + + return applicabilityStatus; + }; + + PullTypeResolver.prototype.overloadIsApplicableForOtherArgument = function (paramType, arg, argIndex, context, comparisonInfo) { + var argSym = this.resolveAST(arg, false, context); + + if (argSym.type.isAlias()) { + var aliasSym = argSym.type; + argSym = aliasSym.getExportAssignedTypeSymbol(); + } + + comparisonInfo.stringConstantVal = arg; + return this.overloadIsApplicableForArgumentHelper(paramType, argSym.type, argIndex, comparisonInfo, arg, context); + }; + + PullTypeResolver.prototype.overloadIsApplicableForArgumentHelper = function (paramType, argSym, argumentIndex, comparisonInfo, arg, context) { + var tempComparisonInfo = new TypeComparisonInfo(); + tempComparisonInfo.stringConstantVal = comparisonInfo.stringConstantVal; + if (!context.hasProvisionalErrors() && this.sourceIsSubtypeOfTarget(argSym.type, paramType, arg, context, tempComparisonInfo)) { + return 3 /* Subtype */; + } + + if (this.sourceIsAssignableToTarget(argSym.type, paramType, arg, context, comparisonInfo.message ? tempComparisonInfo : comparisonInfo)) { + return context.hasProvisionalErrors() ? 1 /* AssignableButWithProvisionalErrors */ : 2 /* AssignableWithNoProvisionalErrors */; + } + + if (!comparisonInfo.message) { + var enclosingSymbol = this.getEnclosingSymbolForAST(arg); + comparisonInfo.addMessage(TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Could_not_apply_type_0_to_argument_1_which_is_of_type_2, [paramType.toString(enclosingSymbol), (argumentIndex + 1), argSym.getTypeName(enclosingSymbol)])); + } + + return 0 /* NotAssignable */; + }; + + PullTypeResolver.prototype.inferArgumentTypesForSignature = function (argContext, comparisonInfo, context) { + var inferenceResultTypes = argContext.inferTypeArguments(); + var typeParameters = argContext.signatureBeingInferred.getTypeParameters(); + TypeScript.Debug.assert(typeParameters.length == inferenceResultTypes.length); + + var typeReplacementMapForConstraints = null; + for (var i = 0; i < inferenceResultTypes.length; i++) { + if (typeParameters[i].getConstraint()) { + typeReplacementMapForConstraints = typeReplacementMapForConstraints || TypeScript.PullInstantiationHelpers.createTypeParameterArgumentMap(typeParameters, inferenceResultTypes); + var associatedConstraint = this.instantiateType(typeParameters[i].getConstraint(), typeReplacementMapForConstraints); + if (!this.sourceIsAssignableToTargetWithNewEnclosingTypes(inferenceResultTypes[i], associatedConstraint, null, context, null, false)) { + inferenceResultTypes[i] = associatedConstraint; + } + } + } + + if (argContext.isInvocationInferenceContext()) { + var invocationContext = argContext; + if (!this.typeParametersAreInScopeAtArgumentList(typeParameters, invocationContext.argumentASTs)) { + for (var i = 0; i < inferenceResultTypes.length; i++) { + if (inferenceResultTypes[i].wrapsSomeTypeParameter(argContext.candidateCache)) { + inferenceResultTypes[i] = this.semanticInfoChain.anyTypeSymbol; + } + } + } + } + + return inferenceResultTypes; + }; + + PullTypeResolver.prototype.typeParametersAreInScopeAtArgumentList = function (typeParameters, args) { + var enclosingDecl = this.getEnclosingDeclForAST(args); + var typeParameterParentDecl = typeParameters[0].getDeclarations()[0].getParentDecl(); + return enclosingDecl.getParentPath().indexOf(typeParameterParentDecl) > -1; + }; + + PullTypeResolver.prototype.relateTypeToTypeParametersInEnclosingType = function (expressionType, parameterType, argContext, context) { + if (expressionType && parameterType) { + if (context.oneOfClassificationsIsInfinitelyExpanding()) { + this.relateInifinitelyExpandingTypeToTypeParameters(expressionType, parameterType, argContext, context); + return; + } + } + this.relateTypeToTypeParameters(expressionType, parameterType, argContext, context); + }; + + PullTypeResolver.prototype.relateTypeToTypeParametersWithNewEnclosingTypes = function (expressionType, parameterType, argContext, context) { + var enclosingTypeWalkerStates = context.resetEnclosingTypeWalkerStates(); + this.relateTypeToTypeParameters(expressionType, parameterType, argContext, context); + context.setEnclosingTypeWalkerStates(enclosingTypeWalkerStates); + }; + + PullTypeResolver.prototype.relateTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { + if (!expressionType || !parameterType) { + return; + } + + if (expressionType.isError()) { + expressionType = this.semanticInfoChain.anyTypeSymbol; + } + + if (parameterType.isTypeParameter()) { + var typeParameter = parameterType; + argContext.addCandidateForInference(typeParameter, expressionType); + return; + } + + if (parameterType.isNamedTypeSymbol() && !parameterType.isGeneric() && !parameterType.getTypeArguments()) { + return; + } + + if (TypeScript.PullInstantiationHelpers.twoTypesAreInstantiationsOfSameNamedGenericType(expressionType, parameterType)) { + this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, argContext, context); + } else { + var symbolsWhenStartedWalkingTypes = context.startWalkingTypes(expressionType, parameterType); + this.relateObjectTypeToTypeParameters(expressionType, parameterType, argContext, context); + context.endWalkingTypes(symbolsWhenStartedWalkingTypes); + } + }; + + PullTypeResolver.prototype.relateTypeArgumentsOfTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { + var parameterSideTypeArguments = parameterType.getTypeArguments(); + var argumentSideTypeArguments = expressionType.getTypeArguments(); + + TypeScript.Debug.assert(parameterSideTypeArguments && argumentSideTypeArguments && parameterSideTypeArguments.length === argumentSideTypeArguments.length); + for (var i = 0; i < parameterSideTypeArguments.length; i++) { + this.relateTypeToTypeParametersWithNewEnclosingTypes(argumentSideTypeArguments[i], parameterSideTypeArguments[i], argContext, context); + } + }; + + PullTypeResolver.prototype.relateInifinitelyExpandingTypeToTypeParameters = function (expressionType, parameterType, argContext, context) { + if (!expressionType || !parameterType) { + return; + } + + var expressionTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(expressionType); + var parameterTypeNamedTypeReference = TypeScript.PullHelpers.getRootType(parameterType); + if (expressionTypeNamedTypeReference !== parameterTypeNamedTypeReference) { + return; + } + + var expressionTypeTypeArguments = expressionType.getTypeArguments(); + var parameterTypeArguments = parameterType.getTypeArguments(); + + if (expressionTypeTypeArguments && parameterTypeArguments && expressionTypeTypeArguments.length === parameterTypeArguments.length) { + for (var i = 0; i < expressionTypeTypeArguments.length; i++) { + this.relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, argContext, context); + } + } + }; + + PullTypeResolver.prototype.relateFunctionSignatureToTypeParameters = function (expressionSignature, parameterSignature, argContext, context) { + var _this = this; + var expressionReturnType = expressionSignature.returnType; + var parameterReturnType = parameterSignature.returnType; + + parameterSignature.forAllCorrespondingParameterTypesInThisAndOtherSignature(expressionSignature, function (parameterSignatureParameterType, expressionSignatureParameterType, i) { + context.walkParameterTypes(i); + _this.relateTypeToTypeParametersInEnclosingType(expressionSignatureParameterType, parameterSignatureParameterType, argContext, context); + context.postWalkParameterTypes(); + return true; + }); + + context.walkReturnTypes(); + this.relateTypeToTypeParametersInEnclosingType(expressionReturnType, parameterReturnType, argContext, context); + context.postWalkReturnTypes(); + }; + + PullTypeResolver.prototype.relateObjectTypeToTypeParameters = function (objectType, parameterType, argContext, context) { + var parameterTypeMembers = parameterType.getMembers(); + var parameterSignatures; + + var objectMember; + var objectSignatures; + + if (argContext.alreadyRelatingTypes(objectType, parameterType)) { + return; + } + + for (var i = 0; i < parameterTypeMembers.length; i++) { + objectMember = this.getNamedPropertySymbol(parameterTypeMembers[i].name, 68147712 /* SomeValue */, objectType); + if (objectMember) { + this.resolveDeclaredSymbol(objectMember); + this.resolveDeclaredSymbol(parameterTypeMembers[i]); + context.walkMemberTypes(parameterTypeMembers[i].name); + this.relateTypeToTypeParametersInEnclosingType(objectMember.type, parameterTypeMembers[i].type, argContext, context); + context.postWalkMemberTypes(); + } + } + + this.relateSignatureGroupToTypeParameters(objectType.getCallSignatures(), parameterType.getCallSignatures(), 1048576 /* CallSignature */, argContext, context); + + this.relateSignatureGroupToTypeParameters(objectType.getConstructSignatures(), parameterType.getConstructSignatures(), 2097152 /* ConstructSignature */, argContext, context); + + var parameterIndexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(parameterType, context); + var objectIndexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(objectType, context); + var indexSigInfo = context.getBothKindOfIndexSignatures(false, false); + + if (parameterIndexSignatures.stringSignature && objectIndexSignatures.stringSignature) { + context.walkIndexSignatureReturnTypes(indexSigInfo, true, true, true); + this.relateFunctionSignatureToTypeParameters(objectIndexSignatures.stringSignature, parameterIndexSignatures.stringSignature, argContext, context); + context.postWalkIndexSignatureReturnTypes(true); + } + if (parameterIndexSignatures.numericSignature && objectIndexSignatures.numericSignature) { + context.walkIndexSignatureReturnTypes(indexSigInfo, false, false, true); + this.relateFunctionSignatureToTypeParameters(objectIndexSignatures.numericSignature, parameterIndexSignatures.numericSignature, argContext, context); + context.postWalkIndexSignatureReturnTypes(true); + } + }; + + PullTypeResolver.prototype.relateSignatureGroupToTypeParameters = function (argumentSignatures, parameterSignatures, signatureKind, argContext, context) { + for (var i = 0; i < parameterSignatures.length; i++) { + var paramSignature = parameterSignatures[i]; + if (argumentSignatures.length > 0 && paramSignature.isGeneric()) { + paramSignature = this.instantiateSignatureToAny(paramSignature); + } + for (var j = 0; j < argumentSignatures.length; j++) { + var argumentSignature = argumentSignatures[j]; + if (argumentSignature.nonOptionalParamCount > paramSignature.nonOptionalParamCount) { + continue; + } + + if (argumentSignature.isGeneric()) { + argumentSignature = this.instantiateSignatureToAny(argumentSignature); + } + + context.walkSignatures(signatureKind, j, i); + this.relateFunctionSignatureToTypeParameters(argumentSignature, paramSignature, argContext, context); + context.postWalkSignatures(); + } + } + }; + + PullTypeResolver.prototype.alterPotentialGenericFunctionTypeToInstantiatedFunctionTypeForTypeArgumentInference = function (expressionSymbol, context) { + var inferentialType = context.getContextualType(); + TypeScript.Debug.assert(inferentialType); + var expressionType = expressionSymbol.type; + if (this.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers(expressionType, true) && this.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers(inferentialType, false)) { + var genericExpressionSignature = expressionType.getCallSignatures()[0]; + var contextualSignature = inferentialType.getCallSignatures()[0]; + + var instantiatedSignature = this.instantiateSignatureInContext(genericExpressionSignature, contextualSignature, context, true); + if (instantiatedSignature === null) { + return expressionSymbol; + } + + var newType = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + newType.appendCallSignature(instantiatedSignature); + return newType; + } + + return expressionSymbol; + }; + + PullTypeResolver.prototype.isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers = function (type, callSignatureShouldBeGeneric) { + TypeScript.Debug.assert(type); + if (type.getCallSignatures().length !== 1) { + return false; + } + + var callSignatureIsGeneric = type.getCallSignatures()[0].isGeneric(); + if (callSignatureIsGeneric !== callSignatureShouldBeGeneric) { + return false; + } + + var typeHasOtherMembers = type.getConstructSignatures().length || type.getIndexSignatures().length || type.getAllMembers(68147712 /* SomeValue */, 0 /* all */).length; + if (typeHasOtherMembers) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.instantiateTypeToAny = function (typeToSpecialize, context) { + var typeParameters = typeToSpecialize.getTypeParameters(); + + if (!typeParameters.length) { + return typeToSpecialize; + } + + var typeArguments = null; + + if (!this._cachedAnyTypeArgs) { + this._cachedAnyTypeArgs = [ + [this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol] + ]; + } + + if (typeParameters.length < this._cachedAnyTypeArgs.length) { + typeArguments = this._cachedAnyTypeArgs[typeParameters.length - 1]; + } else { + typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArguments[typeArguments.length] = this.semanticInfoChain.anyTypeSymbol; + } + } + + var type = this.createInstantiatedType(typeToSpecialize, typeArguments); + + return type; + }; + + PullTypeResolver.prototype.instantiateSignatureToAny = function (signature) { + var typeParameters = signature.getTypeParameters(); + if (!this._cachedAnyTypeArgs) { + this._cachedAnyTypeArgs = [ + [this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol], + [this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol, this.semanticInfoChain.anyTypeSymbol] + ]; + } + + if (typeParameters.length < this._cachedAnyTypeArgs.length) { + var typeArguments = this._cachedAnyTypeArgs[typeParameters.length - 1]; + } else { + var typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArguments[typeArguments.length] = this.semanticInfoChain.anyTypeSymbol; + } + } + + var typeParameterArgumentMap = TypeScript.PullInstantiationHelpers.createTypeParameterArgumentMap(typeParameters, typeArguments); + return this.instantiateSignature(signature, typeParameterArgumentMap); + }; + + PullTypeResolver.typeCheck = function (compilationSettings, semanticInfoChain, document) { + var sourceUnit = document.sourceUnit(); + + var resolver = semanticInfoChain.getResolver(); + var context = new TypeScript.PullTypeResolutionContext(resolver, true, sourceUnit.fileName()); + + if (resolver.canTypeCheckAST(sourceUnit, context)) { + resolver.resolveAST(sourceUnit, false, context); + resolver.validateVariableDeclarationGroups(semanticInfoChain.getDeclForAST(sourceUnit), context); + + while (resolver.typeCheckCallBacks.length) { + var callBack = resolver.typeCheckCallBacks.pop(); + callBack(context); + } + + resolver.processPostTypeCheckWorkItems(context); + } + }; + + PullTypeResolver.prototype.validateVariableDeclarationGroups = function (enclosingDecl, context) { + var _this = this; + this.scanVariableDeclarationGroups(enclosingDecl, function (_) { + }, function (subsequentDecl, firstSymbol) { + if (TypeScript.hasFlag(subsequentDecl.kind, 2048 /* Parameter */) || TypeScript.hasFlag(subsequentDecl.flags, 8388608 /* PropertyParameter */)) { + return; + } + + var boundDeclAST = _this.semanticInfoChain.getASTForDecl(subsequentDecl); + + var symbol = subsequentDecl.getSymbol(); + var symbolType = symbol.type; + var firstSymbolType = firstSymbol.type; + + if (symbolType && firstSymbolType && symbolType !== firstSymbolType && !_this.typesAreIdentical(symbolType, firstSymbolType, context)) { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(boundDeclAST, TypeScript.DiagnosticCode.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, [symbol.getScopedName(), firstSymbolType.toString(firstSymbol), symbolType.toString(symbol)])); + } + }); + }; + + PullTypeResolver.prototype.typeCheckFunctionOverloads = function (funcDecl, context, signature, allSignatures) { + if (!signature) { + var functionSignatureInfo = TypeScript.PullHelpers.getSignatureForFuncDecl(this.semanticInfoChain.getDeclForAST(funcDecl)); + signature = functionSignatureInfo.signature; + allSignatures = functionSignatureInfo.allSignatures; + } + var functionDeclaration = this.semanticInfoChain.getDeclForAST(funcDecl); + var funcSymbol = functionDeclaration.getSymbol(); + + var definitionSignature = null; + for (var i = allSignatures.length - 1; i >= 0; i--) { + if (allSignatures[i].isDefinition()) { + definitionSignature = allSignatures[i]; + break; + } + } + + if (!signature.isDefinition()) { + var signatureParentDecl = signature.getDeclarations()[0].getParentDecl(); + for (var i = 0; i < allSignatures.length; i++) { + if (allSignatures[i] === signature) { + break; + } + + var allSignaturesParentDecl = allSignatures[i].getDeclarations()[0].getParentDecl(); + if (allSignaturesParentDecl !== signatureParentDecl) { + continue; + } + + if (this.signaturesAreIdenticalWithNewEnclosingTypes(allSignatures[i], signature, context, false)) { + if (!this.signatureReturnTypesAreIdentical(allSignatures[i], signature, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overloads_cannot_differ_only_by_return_type)); + } else if (funcDecl.kind() === 137 /* ConstructorDeclaration */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_constructor_overload_signature)); + } else if (functionDeclaration.kind === 2097152 /* ConstructSignature */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_overload_construct_signature)); + } else if (functionDeclaration.kind === 1048576 /* CallSignature */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_overload_call_signature)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Duplicate_overload_signature_for_0, [funcSymbol.getScopedNameEx().toString()])); + } + + break; + } + } + } + + var isConstantOverloadSignature = signature.isStringConstantOverloadSignature(); + if (isConstantOverloadSignature) { + if (signature.isDefinition()) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overload_signature_implementation_cannot_use_specialized_type)); + } else { + var foundSubtypeSignature = false; + for (var i = 0; i < allSignatures.length; i++) { + if (allSignatures[i].isDefinition() || allSignatures[i] === signature) { + continue; + } + + if (!allSignatures[i].isResolved) { + this.resolveDeclaredSymbol(allSignatures[i], context); + } + + if (allSignatures[i].isStringConstantOverloadSignature()) { + continue; + } + + if (this.signatureIsAssignableToTarget(signature, allSignatures[i], null, context)) { + foundSubtypeSignature = true; + break; + } + } + + if (!foundSubtypeSignature) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature)); + } + } + } else if (definitionSignature && definitionSignature !== signature) { + var comparisonInfo = new TypeComparisonInfo(); + + if (!definitionSignature.isResolved) { + this.resolveDeclaredSymbol(definitionSignature, context); + } + + if (!this.signatureIsAssignableToTarget(definitionSignature, signature, funcDecl, context, comparisonInfo)) { + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overload_signature_is_not_compatible_with_function_definition_NL_0, [comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, TypeScript.DiagnosticCode.Overload_signature_is_not_compatible_with_function_definition)); + } + } + } + + var signatureForVisibilityCheck = definitionSignature; + if (!definitionSignature) { + if (allSignatures[0] === signature) { + return; + } + signatureForVisibilityCheck = allSignatures[0]; + } + + if (funcDecl.kind() !== 137 /* ConstructorDeclaration */ && functionDeclaration.kind !== 2097152 /* ConstructSignature */ && signatureForVisibilityCheck && signature !== signatureForVisibilityCheck) { + var errorCode; + + if (signatureForVisibilityCheck.anyDeclHasFlag(2 /* Private */) !== signature.anyDeclHasFlag(2 /* Private */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_public_or_private; + } else if (signatureForVisibilityCheck.anyDeclHasFlag(1 /* Exported */) !== signature.anyDeclHasFlag(1 /* Exported */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_exported_or_not_exported; + } else if (signatureForVisibilityCheck.anyDeclHasFlag(8 /* Ambient */) !== signature.anyDeclHasFlag(8 /* Ambient */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_ambient_or_non_ambient; + } else if (signatureForVisibilityCheck.anyDeclHasFlag(128 /* Optional */) !== signature.anyDeclHasFlag(128 /* Optional */)) { + errorCode = TypeScript.DiagnosticCode.Overload_signatures_must_all_be_optional_or_required; + } + + if (errorCode) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(funcDecl, errorCode)); + } + } + }; + + PullTypeResolver.prototype.checkSymbolPrivacy = function (declSymbol, symbol, privacyErrorReporter) { + if (!symbol || symbol.kind === 2 /* Primitive */) { + return; + } + + if (symbol.isType()) { + var typeSymbol = symbol; + var isNamedType = typeSymbol.isNamedTypeSymbol(); + + if (typeSymbol.isArrayNamedTypeReference()) { + this.checkSymbolPrivacy(declSymbol, typeSymbol.getElementType(), privacyErrorReporter); + return; + } + + if (!isNamedType) { + var typeOfSymbol = typeSymbol.getTypeOfSymbol(); + if (typeOfSymbol) { + this.checkSymbolPrivacy(declSymbol, typeOfSymbol, privacyErrorReporter); + return; + } + } + + if (typeSymbol.inSymbolPrivacyCheck) { + return; + } + + typeSymbol.inSymbolPrivacyCheck = true; + + var typars = typeSymbol.getTypeArgumentsOrTypeParameters(); + if (typars) { + for (var i = 0; i < typars.length; i++) { + this.checkSymbolPrivacy(declSymbol, typars[i], privacyErrorReporter); + } + } + + if (!isNamedType) { + var members = typeSymbol.getMembers(); + for (var i = 0; i < members.length; i++) { + this.checkSymbolPrivacy(declSymbol, members[i].type, privacyErrorReporter); + } + + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getCallSignatures(), privacyErrorReporter); + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getConstructSignatures(), privacyErrorReporter); + this.checkTypePrivacyOfSignatures(declSymbol, typeSymbol.getIndexSignatures(), privacyErrorReporter); + } else if (typeSymbol.kind === 8192 /* TypeParameter */) { + this.checkSymbolPrivacy(declSymbol, typeSymbol.getConstraint(), privacyErrorReporter); + } + + typeSymbol.inSymbolPrivacyCheck = false; + + if (!isNamedType) { + return; + } + } + + if (declSymbol.isExternallyVisible()) { + var symbolIsVisible = symbol.isExternallyVisible(); + + if (symbolIsVisible && symbol.kind !== 8192 /* TypeParameter */) { + var symbolPath = symbol.pathToRoot(); + var declSymbolPath = declSymbol.pathToRoot(); + + if (symbolPath[symbolPath.length - 1].kind === 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1].kind === 32 /* DynamicModule */ && declSymbolPath[declSymbolPath.length - 1] !== symbolPath[symbolPath.length - 1]) { + symbolIsVisible = false; + var declSymbolScope = declSymbolPath[declSymbolPath.length - 1]; + for (var i = symbolPath.length - 1; i >= 0; i--) { + var aliasSymbols = symbolPath[i].getExternalAliasedSymbols(declSymbolScope); + if (aliasSymbols) { + symbolIsVisible = true; + aliasSymbols[0].setTypeUsedExternally(); + break; + } + } + symbol = symbolPath[symbolPath.length - 1]; + } + } else if (symbol.kind === 128 /* TypeAlias */) { + var aliasSymbol = symbol; + symbolIsVisible = true; + aliasSymbol.setTypeUsedExternally(); + } + + if (!symbolIsVisible) { + privacyErrorReporter(symbol); + } + } + }; + + PullTypeResolver.prototype.checkTypePrivacyOfSignatures = function (declSymbol, signatures, privacyErrorReporter) { + for (var i = 0; i < signatures.length; i++) { + var signature = signatures[i]; + if (signatures.length > 1 && signature.isDefinition()) { + continue; + } + + var typeParams = signature.getTypeParameters(); + for (var j = 0; j < typeParams.length; j++) { + this.checkSymbolPrivacy(declSymbol, typeParams[j], privacyErrorReporter); + } + + var params = signature.parameters; + for (var j = 0; j < params.length; j++) { + var paramType = params[j].type; + this.checkSymbolPrivacy(declSymbol, paramType, privacyErrorReporter); + } + + var returnType = signature.returnType; + this.checkSymbolPrivacy(declSymbol, returnType, privacyErrorReporter); + } + }; + + PullTypeResolver.prototype.typeParameterOfTypeDeclarationPrivacyErrorReporter = function (classOrInterface, typeParameterAST, typeParameter, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + var messageCode; + + var typeParameters = classOrInterface.kind() === 131 /* ClassDeclaration */ ? classOrInterface.typeParameterList : classOrInterface.typeParameterList; + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_interface_is_using_inaccessible_module_1; + } + } else { + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_interface_has_or_is_using_private_type_1; + } + } + + var messageArguments = [typeParameter.getScopedName(enclosingSymbol, false, true), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeParameterAST, messageCode, messageArguments)); + }; + + PullTypeResolver.prototype.baseListPrivacyErrorReporter = function (classOrInterface, declSymbol, baseAst, isExtendedType, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(classOrInterface); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + var messageCode; + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + if (isExtendedType) { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_extends_class_from_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_implements_interface_from_inaccessible_module_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_interface_0_extends_interface_from_inaccessible_module_1; + } + } else { + if (classOrInterface.kind() === 131 /* ClassDeclaration */) { + if (isExtendedType) { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_extends_private_class_1; + } else { + messageCode = TypeScript.DiagnosticCode.Exported_class_0_implements_private_interface_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_interface_0_extends_private_interface_1; + } + } + + var messageArguments = [declSymbol.getScopedName(enclosingSymbol), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseAst, messageCode, messageArguments)); + }; + + PullTypeResolver.prototype.variablePrivacyErrorReporter = function (declAST, declSymbol, symbol, context) { + var typeSymbol = symbol; + var enclosingDecl = this.getEnclosingDecl(declSymbol.getDeclarations()[0]); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + + var isProperty = declSymbol.kind === 4096 /* Property */; + var isPropertyOfClass = false; + var declParent = declSymbol.getContainer(); + if (declParent && (declParent.kind === 8 /* Class */ || declParent.kind === 32768 /* ConstructorMethod */)) { + isPropertyOfClass = true; + } + + var messageCode; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (declSymbol.anyDeclHasFlag(16 /* Static */)) { + messageCode = TypeScript.DiagnosticCode.Public_static_property_0_of_exported_class_is_using_inaccessible_module_1; + } else if (isProperty) { + if (isPropertyOfClass) { + messageCode = TypeScript.DiagnosticCode.Public_property_0_of_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Property_0_of_exported_interface_is_using_inaccessible_module_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_variable_0_is_using_inaccessible_module_1; + } + } else { + if (declSymbol.anyDeclHasFlag(16 /* Static */)) { + messageCode = TypeScript.DiagnosticCode.Public_static_property_0_of_exported_class_has_or_is_using_private_type_1; + } else if (isProperty) { + if (isPropertyOfClass) { + messageCode = TypeScript.DiagnosticCode.Public_property_0_of_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.Property_0_of_exported_interface_has_or_is_using_private_type_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.Exported_variable_0_has_or_is_using_private_type_1; + } + } + + var messageArguments = [declSymbol.getScopedName(enclosingSymbol), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(declAST, messageCode, messageArguments)); + }; + + PullTypeResolver.prototype.checkFunctionTypePrivacy = function (funcDeclAST, isStatic, typeParameters, parameters, returnTypeAnnotation, block, context) { + var _this = this; + if (funcDeclAST.kind() === 222 /* FunctionExpression */ || funcDeclAST.kind() === 241 /* FunctionPropertyAssignment */ || (funcDeclAST.kind() === 139 /* GetAccessor */ && funcDeclAST.parent.parent.kind() === 215 /* ObjectLiteralExpression */) || (funcDeclAST.kind() === 140 /* SetAccessor */ && funcDeclAST.parent.parent.kind() === 215 /* ObjectLiteralExpression */)) { + return; + } + + var functionDecl = this.semanticInfoChain.getDeclForAST(funcDeclAST); + var functionSymbol = functionDecl.getSymbol(); + ; + var functionSignature; + + var isGetter = funcDeclAST.kind() === 139 /* GetAccessor */; + var isSetter = funcDeclAST.kind() === 140 /* SetAccessor */; + var isIndexSignature = functionDecl.kind === 4194304 /* IndexSignature */; + + if (isGetter || isSetter) { + var accessorSymbol = functionSymbol; + functionSignature = (isGetter ? accessorSymbol.getGetter() : accessorSymbol.getSetter()).type.getCallSignatures()[0]; + } else { + if (!functionSymbol) { + var parentDecl = functionDecl.getParentDecl(); + functionSymbol = parentDecl.getSymbol(); + if (functionSymbol && functionSymbol.isType() && !functionSymbol.isNamedTypeSymbol()) { + return; + } + } else if (functionSymbol.kind === 65536 /* Method */ && !isStatic && !functionSymbol.getContainer().isNamedTypeSymbol()) { + return; + } + functionSignature = functionDecl.getSignatureSymbol(); + } + + if (typeParameters && !isGetter && !isSetter && !isIndexSignature && funcDeclAST.kind() !== 137 /* ConstructorDeclaration */) { + for (var i = 0; i < typeParameters.typeParameters.nonSeparatorCount(); i++) { + var typeParameterAST = typeParameters.typeParameters.nonSeparatorAt(i); + var typeParameter = this.resolveTypeParameterDeclaration(typeParameterAST, context); + this.checkSymbolPrivacy(functionSymbol, typeParameter, function (symbol) { + return _this.functionTypeArgumentArgumentTypePrivacyErrorReporter(funcDeclAST, isStatic, typeParameterAST, typeParameter, symbol, context); + }); + } + } + + if (!isGetter && !isIndexSignature) { + var funcParams = functionSignature.parameters; + for (var i = 0; i < funcParams.length; i++) { + this.checkSymbolPrivacy(functionSymbol, funcParams[i].type, function (symbol) { + return _this.functionArgumentTypePrivacyErrorReporter(funcDeclAST, isStatic, parameters, i, funcParams[i], symbol, context); + }); + } + } + + if (!isSetter) { + this.checkSymbolPrivacy(functionSymbol, functionSignature.returnType, function (symbol) { + return _this.functionReturnTypePrivacyErrorReporter(funcDeclAST, isStatic, returnTypeAnnotation, block, functionSignature.returnType, symbol, context); + }); + } + }; + + PullTypeResolver.prototype.functionTypeArgumentArgumentTypePrivacyErrorReporter = function (declAST, isStatic, typeParameterAST, typeParameter, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(declAST); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + + var isMethod = decl.kind === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.kind === 8 /* Class */ || isStatic)) { + isMethodOfClass = true; + } + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + var messageCode; + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_function_is_using_inaccessible_module_1; + } + } else { + if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1; + } + } else { + messageCode = TypeScript.DiagnosticCode.TypeParameter_0_of_exported_function_has_or_is_using_private_type_1; + } + } + + if (messageCode) { + var messageArgs = [typeParameter.getScopedName(enclosingSymbol, false, true), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(typeParameterAST, messageCode, messageArgs)); + } + }; + + PullTypeResolver.prototype.functionArgumentTypePrivacyErrorReporter = function (declAST, isStatic, parameters, argIndex, paramSymbol, symbol, context) { + var decl = this.semanticInfoChain.getDeclForAST(declAST); + var enclosingDecl = this.getEnclosingDecl(decl); + var enclosingSymbol = enclosingDecl ? enclosingDecl.getSymbol() : null; + + var isGetter = declAST.kind() === 139 /* GetAccessor */; + var isSetter = declAST.kind() === 140 /* SetAccessor */; + var isMethod = decl.kind === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.kind === 8 /* Class */ || isStatic)) { + isMethodOfClass = true; + } + + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingSymbol); + var messageCode; + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (declAST.kind() === 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_from_exported_class_is_using_inaccessible_module_1; + } else if (isSetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_property_setter_from_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_property_setter_from_exported_class_is_using_inaccessible_module_1; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1; + } + } else if (!isGetter) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_exported_function_is_using_inaccessible_module_1; + } + } else { + if (declAST.kind() === 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_type_1; + } else if (isSetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_type_1; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1; + } else { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1; + } + } else if (!isGetter && decl.kind !== 4194304 /* IndexSignature */) { + messageCode = TypeScript.DiagnosticCode.Parameter_0_of_exported_function_has_or_is_using_private_type_1; + } + } + + if (messageCode) { + var parameter = parameters.astAt(argIndex); + + var messageArgs = [paramSymbol.getScopedName(enclosingSymbol), typeSymbolName]; + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(parameter, messageCode, messageArgs)); + } + }; + + PullTypeResolver.prototype.functionReturnTypePrivacyErrorReporter = function (declAST, isStatic, returnTypeAnnotation, block, funcReturnType, symbol, context) { + var _this = this; + var decl = this.semanticInfoChain.getDeclForAST(declAST); + var enclosingDecl = this.getEnclosingDecl(decl); + + var isGetter = declAST.kind() === 139 /* GetAccessor */; + var isSetter = declAST.kind() === 140 /* SetAccessor */; + var isMethod = decl.kind === 65536 /* Method */; + var isMethodOfClass = false; + var declParent = decl.getParentDecl(); + if (declParent && (declParent.kind === 8 /* Class */ || isStatic)) { + isMethodOfClass = true; + } + + var messageCode = null; + var typeSymbol = symbol; + var typeSymbolName = typeSymbol.getScopedName(enclosingDecl ? enclosingDecl.getSymbol() : null); + if (typeSymbol.isContainer() && !typeSymbol.isEnum()) { + if (!TypeScript.isQuoted(typeSymbolName)) { + typeSymbolName = "'" + typeSymbolName + "'"; + } + + if (isGetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module_0; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_0; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module_0; + } else if (decl.kind === 4194304 /* IndexSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module_0; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module_0; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_method_from_exported_class_is_using_inaccessible_module_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_method_from_exported_interface_is_using_inaccessible_module_0; + } + } else if (!isSetter && declAST.kind() !== 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_exported_function_is_using_inaccessible_module_0; + } + } else { + if (isGetter) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type_0; + } + } else if (decl.kind === 2097152 /* ConstructSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_0; + } else if (decl.kind === 1048576 /* CallSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type_0; + } else if (decl.kind === 4194304 /* IndexSignature */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type_0; + } else if (isMethod) { + if (isStatic) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type_0; + } else if (isMethodOfClass) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_public_method_from_exported_class_has_or_is_using_private_type_0; + } else { + messageCode = TypeScript.DiagnosticCode.Return_type_of_method_from_exported_interface_has_or_is_using_private_type_0; + } + } else if (!isSetter && declAST.kind() !== 137 /* ConstructorDeclaration */) { + messageCode = TypeScript.DiagnosticCode.Return_type_of_exported_function_has_or_is_using_private_type_0; + } + } + + if (messageCode) { + var messageArguments = [typeSymbolName]; + var reportOnFuncDecl = false; + + if (returnTypeAnnotation) { + var returnExpressionSymbol = this.resolveTypeReference(returnTypeAnnotation, context); + + if (TypeScript.PullHelpers.typeSymbolsAreIdentical(returnExpressionSymbol, funcReturnType)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(returnTypeAnnotation, messageCode, messageArguments)); + } + } + + if (block) { + var reportErrorOnReturnExpressions = function (ast, walker) { + var go = true; + switch (ast.kind()) { + case 129 /* FunctionDeclaration */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + case 222 /* FunctionExpression */: + go = false; + break; + + case 150 /* ReturnStatement */: + var returnStatement = ast; + var returnExpressionSymbol = _this.resolveAST(returnStatement.expression, false, context).type; + + if (TypeScript.PullHelpers.typeSymbolsAreIdentical(returnExpressionSymbol, funcReturnType)) { + context.postDiagnostic(_this.semanticInfoChain.diagnosticFromAST(returnStatement, messageCode, messageArguments)); + } else { + reportOnFuncDecl = true; + } + go = false; + break; + + default: + break; + } + + walker.options.goChildren = go; + return ast; + }; + + TypeScript.getAstWalkerFactory().walk(block, reportErrorOnReturnExpressions); + } + + if (reportOnFuncDecl) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(declAST, messageCode, messageArguments)); + } + } + }; + + PullTypeResolver.prototype.enclosingClassIsDerived = function (classDecl) { + TypeScript.Debug.assert(classDecl.kind === 8 /* Class */); + + var classSymbol = classDecl.getSymbol(); + return classSymbol.getExtendedTypes().length > 0; + }; + + PullTypeResolver.prototype.isSuperInvocationExpression = function (ast) { + if (ast.kind() === 213 /* InvocationExpression */) { + var invocationExpression = ast; + if (invocationExpression.expression.kind() === 50 /* SuperKeyword */) { + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.isSuperInvocationExpressionStatement = function (node) { + if (node && node.kind() === 149 /* ExpressionStatement */) { + var expressionStatement = node; + if (this.isSuperInvocationExpression(expressionStatement.expression)) { + return true; + } + } + return false; + }; + + PullTypeResolver.prototype.getFirstStatementOfBlockOrNull = function (block) { + if (block && block.statements && block.statements.childCount() > 0) { + return block.statements.childAt(0); + } + + return null; + }; + + PullTypeResolver.prototype.superCallMustBeFirstStatementInConstructor = function (constructorDecl) { + TypeScript.Debug.assert(constructorDecl.kind === 32768 /* ConstructorMethod */); + + if (constructorDecl) { + var enclosingClass = constructorDecl.getParentDecl(); + + var classSymbol = enclosingClass.getSymbol(); + if (classSymbol.getExtendedTypes().length === 0) { + return false; + } + + var classMembers = classSymbol.getMembers(); + for (var i = 0, n1 = classMembers.length; i < n1; i++) { + var member = classMembers[i]; + + if (member.kind === 4096 /* Property */) { + var declarations = member.getDeclarations(); + for (var j = 0, n2 = declarations.length; j < n2; j++) { + var declaration = declarations[j]; + var ast = this.semanticInfoChain.getASTForDecl(declaration); + if (ast.kind() === 242 /* Parameter */) { + return true; + } + + if (ast.kind() === 136 /* MemberVariableDeclaration */) { + var variableDeclarator = ast; + if (variableDeclarator.variableDeclarator.equalsValueClause) { + return true; + } + } + } + } + } + } + + return false; + }; + + PullTypeResolver.prototype.checkForThisCaptureInArrowFunction = function (expression) { + var enclosingDecl = this.getEnclosingDeclForAST(expression); + + var declPath = enclosingDecl.getParentPath(); + + if (declPath.length) { + var inArrowFunction = false; + for (var i = declPath.length - 1; i >= 0; i--) { + var decl = declPath[i]; + var declKind = decl.kind; + var declFlags = decl.flags; + + if (declKind === 131072 /* FunctionExpression */ && TypeScript.hasFlag(declFlags, 8192 /* ArrowFunction */)) { + inArrowFunction = true; + continue; + } + + if (inArrowFunction) { + if (declKind === 16384 /* Function */ || declKind === 65536 /* Method */ || declKind === 32768 /* ConstructorMethod */ || declKind === 262144 /* GetAccessor */ || declKind === 524288 /* SetAccessor */ || declKind === 131072 /* FunctionExpression */ || declKind === 8 /* Class */ || declKind === 4 /* Container */ || declKind === 32 /* DynamicModule */ || declKind === 1 /* Script */) { + decl.setFlags(decl.flags | 262144 /* MustCaptureThis */); + + if (declKind === 8 /* Class */) { + var constructorSymbol = decl.getSymbol().getConstructorMethod(); + var constructorDecls = constructorSymbol.getDeclarations(); + for (var i = 0; i < constructorDecls.length; i++) { + constructorDecls[i].flags = constructorDecls[i].flags | 262144 /* MustCaptureThis */; + } + } + break; + } + } else if (declKind === 16384 /* Function */ || declKind === 131072 /* FunctionExpression */) { + break; + } + } + } + }; + + PullTypeResolver.prototype.typeCheckMembersAgainstIndexer = function (containerType, containerTypeDecl, context) { + var indexSignatures = this.getBothKindsOfIndexSignaturesExcludingAugmentedType(containerType, context); + var stringSignature = indexSignatures.stringSignature; + var numberSignature = indexSignatures.numericSignature; + + if (stringSignature || numberSignature) { + var members = containerTypeDecl.getChildDecls(); + for (var i = 0; i < members.length; i++) { + var member = members[i]; + if ((member.name || (member.kind === 4096 /* Property */ && member.name === "")) && member.kind !== 32768 /* ConstructorMethod */ && !TypeScript.hasFlag(member.flags, 16 /* Static */)) { + var memberSymbol = member.getSymbol(); + var relevantSignature = this.determineRelevantIndexerForMember(memberSymbol, numberSignature, stringSignature); + if (relevantSignature) { + var comparisonInfo = new TypeComparisonInfo(); + if (!this.sourceIsAssignableToTarget(memberSymbol.type, relevantSignature.returnType, member.ast(), context, comparisonInfo)) { + this.reportErrorThatMemberIsNotSubtypeOfIndexer(memberSymbol, relevantSignature, member.ast(), context, comparisonInfo); + } + } + } + } + } + }; + + PullTypeResolver.prototype.determineRelevantIndexerForMember = function (member, numberIndexSignature, stringIndexSignature) { + if (numberIndexSignature && TypeScript.PullHelpers.isNameNumeric(member.name)) { + return numberIndexSignature; + } else if (stringIndexSignature) { + return stringIndexSignature; + } + + return null; + }; + + PullTypeResolver.prototype.reportErrorThatMemberIsNotSubtypeOfIndexer = function (member, indexSignature, astForError, context, comparisonInfo) { + var enclosingSymbol = this.getEnclosingSymbolForAST(astForError); + if (indexSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol) { + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); + } + } else { + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_assignable_to_string_indexer_type_0_NL_1, [indexSignature.returnType.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(astForError, TypeScript.DiagnosticCode.All_named_properties_must_be_assignable_to_string_indexer_type_0, [indexSignature.returnType.toString(enclosingSymbol)])); + } + } + }; + + PullTypeResolver.prototype.typeCheckIfTypeMemberPropertyOkToOverride = function (typeSymbol, extendedType, typeMember, extendedTypeMember, enclosingDecl, comparisonInfo) { + if (!typeSymbol.isClass()) { + return true; + } + + var typeMemberKind = typeMember.kind; + var extendedMemberKind = extendedTypeMember.kind; + + if (typeMemberKind === extendedMemberKind) { + return true; + } + + var errorCode; + if (typeMemberKind === 4096 /* Property */) { + if (typeMember.isAccessor()) { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } else { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + } else if (typeMemberKind === 65536 /* Method */) { + if (extendedTypeMember.isAccessor()) { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } else { + errorCode = TypeScript.DiagnosticCode.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + + var message = TypeScript.getDiagnosticMessage(errorCode, [typeSymbol.toString(), typeMember.getScopedNameEx().toString(), extendedType.toString()]); + comparisonInfo.addMessage(message); + return false; + }; + + PullTypeResolver.prototype.typeCheckIfTypeExtendsType = function (classOrInterface, name, typeSymbol, extendedType, enclosingDecl, context) { + var typeMembers = typeSymbol.getMembers(); + + var comparisonInfo = new TypeComparisonInfo(); + var foundError = false; + var foundError1 = false; + var foundError2 = false; + + for (var i = 0; i < typeMembers.length; i++) { + var propName = typeMembers[i].name; + var extendedTypeProp = extendedType.findMember(propName, true); + if (extendedTypeProp) { + this.resolveDeclaredSymbol(extendedTypeProp, context); + foundError1 = !this.typeCheckIfTypeMemberPropertyOkToOverride(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, enclosingDecl, comparisonInfo); + + if (!foundError1) { + foundError2 = !this.sourcePropertyIsAssignableToTargetProperty(typeSymbol, extendedType, typeMembers[i], extendedTypeProp, classOrInterface, context, comparisonInfo); + } + + if (foundError1 || foundError2) { + foundError = true; + break; + } + } + } + + if (!foundError && typeSymbol.hasOwnCallSignatures()) { + foundError = !this.sourceCallSignaturesAreAssignableToTargetCallSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + } + + if (!foundError && typeSymbol.hasOwnConstructSignatures()) { + foundError = !this.sourceConstructSignaturesAreAssignableToTargetConstructSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + } + + if (!foundError && typeSymbol.hasOwnIndexSignatures()) { + foundError = !this.sourceIndexSignaturesAreAssignableToTargetIndexSignatures(typeSymbol, extendedType, classOrInterface, context, comparisonInfo); + } + + if (!foundError && typeSymbol.isClass()) { + var typeConstructorType = typeSymbol.getConstructorMethod().type; + var typeConstructorTypeMembers = typeConstructorType.getMembers(); + if (typeConstructorTypeMembers.length) { + var extendedConstructorType = extendedType.getConstructorMethod().type; + var comparisonInfoForPropTypeCheck = new TypeComparisonInfo(comparisonInfo); + + for (var i = 0; i < typeConstructorTypeMembers.length; i++) { + var propName = typeConstructorTypeMembers[i].name; + var extendedConstructorTypeProp = extendedConstructorType.findMember(propName, true); + if (extendedConstructorTypeProp) { + if (!extendedConstructorTypeProp.isResolved) { + this.resolveDeclaredSymbol(extendedConstructorTypeProp, context); + } + + if (!this.sourcePropertyIsAssignableToTargetProperty(typeConstructorType, extendedConstructorType, typeConstructorTypeMembers[i], extendedConstructorTypeProp, classOrInterface, context, comparisonInfo)) { + foundError = true; + break; + } + } + } + } + } + + if (foundError) { + var errorCode; + if (typeSymbol.isClass()) { + errorCode = TypeScript.DiagnosticCode.Class_0_cannot_extend_class_1_NL_2; + } else { + if (extendedType.isClass()) { + errorCode = TypeScript.DiagnosticCode.Interface_0_cannot_extend_class_1_NL_2; + } else { + errorCode = TypeScript.DiagnosticCode.Interface_0_cannot_extend_interface_1_NL_2; + } + } + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, errorCode, [typeSymbol.getScopedName(), extendedType.getScopedName(), comparisonInfo.message])); + } + }; + + PullTypeResolver.prototype.typeCheckIfClassImplementsType = function (classDecl, classSymbol, implementedType, enclosingDecl, context) { + var comparisonInfo = new TypeComparisonInfo(); + var foundError = !this.sourceMembersAreAssignableToTargetMembers(classSymbol, implementedType, classDecl, context, comparisonInfo); + if (!foundError) { + foundError = !this.sourceCallSignaturesAreAssignableToTargetCallSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + if (!foundError) { + foundError = !this.sourceConstructSignaturesAreAssignableToTargetConstructSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + if (!foundError) { + foundError = !this.sourceIndexSignaturesAreAssignableToTargetIndexSignatures(classSymbol, implementedType, classDecl, context, comparisonInfo); + } + } + } + + if (foundError) { + var enclosingSymbol = this.getEnclosingSymbolForAST(classDecl); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(classDecl.identifier, TypeScript.DiagnosticCode.Class_0_declares_interface_1_but_does_not_implement_it_NL_2, [classSymbol.getScopedName(enclosingSymbol), implementedType.getScopedName(enclosingSymbol), comparisonInfo.message])); + } + }; + + PullTypeResolver.prototype.computeValueSymbolFromAST = function (valueDeclAST, context) { + var prevInTypeCheck = context.inTypeCheck; + context.inTypeCheck = false; + + var typeSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(valueDeclAST); + + if (valueDeclAST.kind() == 11 /* IdentifierName */) { + var valueSymbol = this.computeNameExpression(valueDeclAST, context); + } else { + TypeScript.Debug.assert(valueDeclAST.kind() == 121 /* QualifiedName */); + var qualifiedName = valueDeclAST; + + var lhs = this.computeValueSymbolFromAST(qualifiedName.left, context); + var valueSymbol = this.computeDottedNameExpressionFromLHS(lhs.symbol, qualifiedName.left, qualifiedName.right, context, false); + } + var valueSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(valueDeclAST); + + this.semanticInfoChain.setAliasSymbolForAST(valueDeclAST, typeSymbolAlias); + context.inTypeCheck = prevInTypeCheck; + + return { symbol: valueSymbol, alias: valueSymbolAlias }; + }; + + PullTypeResolver.prototype.hasClassTypeSymbolConflictAsValue = function (baseDeclAST, typeSymbol, enclosingDecl, context) { + var typeSymbolAlias = this.semanticInfoChain.getAliasSymbolForAST(baseDeclAST); + + var valueDeclAST = baseDeclAST.kind() == 126 /* GenericType */ ? baseDeclAST.name : baseDeclAST; + var valueSymbolInfo = this.computeValueSymbolFromAST(valueDeclAST, context); + var valueSymbol = valueSymbolInfo.symbol; + var valueSymbolAlias = valueSymbolInfo.alias; + + if (typeSymbolAlias && valueSymbolAlias) { + return typeSymbolAlias !== valueSymbolAlias; + } + + if (!valueSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */)) { + return true; + } + + var associatedContainerType = valueSymbol.type ? valueSymbol.type.getAssociatedContainerType() : null; + + if (associatedContainerType) { + return associatedContainerType !== typeSymbol.getRootSymbol(); + } + + return true; + }; + + PullTypeResolver.prototype.typeCheckBase = function (classOrInterface, name, typeSymbol, baseDeclAST, isExtendedType, enclosingDecl, context) { + var _this = this; + var typeDecl = this.semanticInfoChain.getDeclForAST(classOrInterface); + + var baseType = this.resolveTypeReference(baseDeclAST, context).type; + + if (!baseType) { + return; + } + + var typeDeclIsClass = typeSymbol.isClass(); + + if (!typeSymbol.isValidBaseKind(baseType, isExtendedType)) { + if (!baseType.isError()) { + if (isExtendedType) { + if (typeDeclIsClass) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.A_class_may_only_extend_another_class)); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.An_interface_may_only_extend_another_class_or_interface)); + } + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.A_class_may_only_implement_another_class_or_interface)); + } + } + return; + } else if (typeDeclIsClass && isExtendedType) { + if (this.hasClassTypeSymbolConflictAsValue(baseDeclAST, baseType, enclosingDecl, context)) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(baseDeclAST, TypeScript.DiagnosticCode.Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_1, [TypeScript.ASTHelpers.getNameOfIdenfierOrQualifiedName(baseDeclAST.kind() == 126 /* GenericType */ ? baseDeclAST.name : baseDeclAST), baseType.toString(enclosingDecl ? enclosingDecl.getSymbol() : null)])); + } + } + + if (baseType.hasBase(typeSymbol)) { + typeSymbol.setHasBaseTypeConflict(); + baseType.setHasBaseTypeConflict(); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, typeDeclIsClass ? TypeScript.DiagnosticCode.Class_0_is_recursively_referenced_as_a_base_type_of_itself : TypeScript.DiagnosticCode.Interface_0_is_recursively_referenced_as_a_base_type_of_itself, [typeSymbol.getScopedName()])); + return; + } + + if (isExtendedType) { + this.typeCheckCallBacks.push(function (context) { + return _this.typeCheckIfTypeExtendsType(classOrInterface, name, typeSymbol, baseType, enclosingDecl, context); + }); + } else { + TypeScript.Debug.assert(classOrInterface.kind() === 131 /* ClassDeclaration */); + + this.typeCheckCallBacks.push(function (context) { + return _this.typeCheckIfClassImplementsType(classOrInterface, typeSymbol, baseType, enclosingDecl, context); + }); + } + + this.checkSymbolPrivacy(typeSymbol, baseType, function (errorSymbol) { + return _this.baseListPrivacyErrorReporter(classOrInterface, typeSymbol, baseDeclAST, isExtendedType, errorSymbol, context); + }); + }; + + PullTypeResolver.prototype.typeCheckBases = function (classOrInterface, name, heritageClauses, typeSymbol, enclosingDecl, context) { + var _this = this; + var extendsClause = TypeScript.ASTHelpers.getExtendsHeritageClause(heritageClauses); + var implementsClause = TypeScript.ASTHelpers.getImplementsHeritageClause(heritageClauses); + if (!extendsClause && !implementsClause) { + return; + } + + if (extendsClause) { + for (var i = 0; i < extendsClause.typeNames.nonSeparatorCount(); i++) { + this.typeCheckBase(classOrInterface, name, typeSymbol, extendsClause.typeNames.nonSeparatorAt(i), true, enclosingDecl, context); + } + } + + if (typeSymbol.isClass()) { + if (implementsClause) { + for (var i = 0; i < implementsClause.typeNames.nonSeparatorCount(); i++) { + this.typeCheckBase(classOrInterface, name, typeSymbol, implementsClause.typeNames.nonSeparatorAt(i), false, enclosingDecl, context); + } + } + } else if (extendsClause && !typeSymbol.hasBaseTypeConflict() && typeSymbol.getExtendedTypes().length > 1) { + var firstInterfaceASTWithExtendsClause = TypeScript.ArrayUtilities.firstOrDefault(typeSymbol.getDeclarations(), function (decl) { + return decl.ast().heritageClauses !== null; + }).ast(); + if (classOrInterface === firstInterfaceASTWithExtendsClause) { + this.typeCheckCallBacks.push(function (context) { + _this.checkTypeCompatibilityBetweenBases(classOrInterface.identifier, typeSymbol, context); + }); + } + } + }; + + PullTypeResolver.prototype.checkTypeCompatibilityBetweenBases = function (name, typeSymbol, context) { + var derivedIndexSignatures = typeSymbol.getOwnIndexSignatures(); + + var inheritedMembersMap = TypeScript.createIntrinsicsObject(); + var inheritedIndexSignatures = new InheritedIndexSignatureInfo(); + + var typeHasOwnNumberIndexer = false; + var typeHasOwnStringIndexer = false; + + if (typeSymbol.hasOwnIndexSignatures()) { + var ownIndexSignatures = typeSymbol.getOwnIndexSignatures(); + for (var i = 0; i < ownIndexSignatures.length; i++) { + if (ownIndexSignatures[i].parameters[0].type === this.semanticInfoChain.numberTypeSymbol) { + typeHasOwnNumberIndexer = true; + } else { + typeHasOwnStringIndexer = true; + } + } + } + var baseTypes = typeSymbol.getExtendedTypes(); + for (var i = 0; i < baseTypes.length; i++) { + if (this.checkNamedPropertyIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedMembersMap, context) || this.checkIndexSignatureIdentityBetweenBases(name, typeSymbol, baseTypes[i], inheritedIndexSignatures, typeHasOwnNumberIndexer, typeHasOwnStringIndexer, context)) { + return; + } + } + + if (this.checkThatInheritedNumberSignatureIsSubtypeOfInheritedStringSignature(name, typeSymbol, inheritedIndexSignatures, context)) { + return; + } + + this.checkInheritedMembersAgainstInheritedIndexSignatures(name, typeSymbol, inheritedIndexSignatures, inheritedMembersMap, context); + }; + + PullTypeResolver.prototype.checkNamedPropertyIdentityBetweenBases = function (interfaceName, interfaceSymbol, baseTypeSymbol, inheritedMembersMap, context) { + var baseMembers = baseTypeSymbol.getAllMembers(4096 /* Property */ | 65536 /* Method */, 0 /* all */); + for (var i = 0; i < baseMembers.length; i++) { + var member = baseMembers[i]; + var memberName = member.name; + + if (interfaceSymbol.findMember(memberName, false)) { + continue; + } + + this.resolveDeclaredSymbol(member, context); + + if (inheritedMembersMap[memberName]) { + var prevMember = inheritedMembersMap[memberName]; + if (prevMember.baseOrigin !== baseTypeSymbol && !this.propertiesAreIdenticalWithNewEnclosingTypes(baseTypeSymbol, prevMember.baseOrigin, member, prevMember.memberSymbol, context)) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Named_properties_0_of_types_1_and_2_are_not_identical, [memberName, prevMember.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), prevMember.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); + return true; + } + } else { + inheritedMembersMap[memberName] = new MemberWithBaseOrigin(member, baseTypeSymbol); + } + } + + return false; + }; + + PullTypeResolver.prototype.checkIndexSignatureIdentityBetweenBases = function (interfaceName, interfaceSymbol, baseTypeSymbol, allInheritedSignatures, derivedTypeHasOwnNumberSignature, derivedTypeHasOwnStringSignature, context) { + if (derivedTypeHasOwnNumberSignature && derivedTypeHasOwnStringSignature) { + return false; + } + + var indexSignaturesFromThisBaseType = baseTypeSymbol.getIndexSignatures(); + for (var i = 0; i < indexSignaturesFromThisBaseType.length; i++) { + var currentInheritedSignature = indexSignaturesFromThisBaseType[i]; + + var parameterTypeIsString = currentInheritedSignature.parameters[0].type === this.semanticInfoChain.stringTypeSymbol; + var parameterTypeIsNumber = currentInheritedSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol; + + if (parameterTypeIsString && derivedTypeHasOwnStringSignature || parameterTypeIsNumber && derivedTypeHasOwnNumberSignature) { + continue; + } + + if (parameterTypeIsString) { + if (allInheritedSignatures.stringSignatureWithBaseOrigin) { + if (allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.stringSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType, context)) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_string_indexer_of_types_0_and_1_are_not_identical, [allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), allInheritedSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); + return true; + } + } else { + allInheritedSignatures.stringSignatureWithBaseOrigin = new SignatureWithBaseOrigin(currentInheritedSignature, baseTypeSymbol); + } + } else if (parameterTypeIsNumber) { + if (allInheritedSignatures.numberSignatureWithBaseOrigin) { + if (allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin !== baseTypeSymbol && !this.typesAreIdentical(allInheritedSignatures.numberSignatureWithBaseOrigin.signature.returnType, currentInheritedSignature.returnType, context)) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Types_of_number_indexer_of_types_0_and_1_are_not_identical, [allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName()]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(), allInheritedSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), baseTypeSymbol.getScopedName(), innerDiagnostic])); + return true; + } + } else { + allInheritedSignatures.numberSignatureWithBaseOrigin = new SignatureWithBaseOrigin(currentInheritedSignature, baseTypeSymbol); + } + } + } + + return false; + }; + + PullTypeResolver.prototype.checkInheritedMembersAgainstInheritedIndexSignatures = function (interfaceName, interfaceSymbol, inheritedIndexSignatures, inheritedMembers, context) { + if (!inheritedIndexSignatures.stringSignatureWithBaseOrigin && !inheritedIndexSignatures.numberSignatureWithBaseOrigin) { + return false; + } + + var comparisonInfo = new TypeComparisonInfo(); + var stringSignature = inheritedIndexSignatures.stringSignatureWithBaseOrigin && inheritedIndexSignatures.stringSignatureWithBaseOrigin.signature; + var numberSignature = inheritedIndexSignatures.numberSignatureWithBaseOrigin && inheritedIndexSignatures.numberSignatureWithBaseOrigin.signature; + for (var memberName in inheritedMembers) { + var memberWithBaseOrigin = inheritedMembers[memberName]; + if (!memberWithBaseOrigin) { + continue; + } + + var relevantSignature = this.determineRelevantIndexerForMember(memberWithBaseOrigin.memberSymbol, numberSignature, stringSignature); + if (!relevantSignature) { + continue; + } + + var relevantSignatureIsNumberSignature = relevantSignature.parameters[0].type === this.semanticInfoChain.numberTypeSymbol; + var signatureBaseOrigin = relevantSignatureIsNumberSignature ? inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin : inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin; + + if (signatureBaseOrigin === memberWithBaseOrigin.baseOrigin) { + continue; + } + + var memberIsSubtype = this.sourceIsAssignableToTarget(memberWithBaseOrigin.memberSymbol.type, relevantSignature.returnType, interfaceName, context, comparisonInfo); + + if (!memberIsSubtype) { + var enclosingSymbol = this.getEnclosingSymbolForAST(interfaceName); + if (relevantSignatureIsNumberSignature) { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_assignable_to_number_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(enclosingSymbol), memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); + } else { + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_property_0_in_type_1_is_not_assignable_to_string_indexer_type_in_type_2_NL_3, [memberName, memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [interfaceSymbol.getDisplayName(enclosingSymbol), memberWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); + } + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.checkThatInheritedNumberSignatureIsSubtypeOfInheritedStringSignature = function (interfaceName, interfaceSymbol, inheritedIndexSignatures, context) { + if (inheritedIndexSignatures.numberSignatureWithBaseOrigin && inheritedIndexSignatures.stringSignatureWithBaseOrigin) { + if (inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin === inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin) { + return false; + } + + var comparisonInfo = new TypeComparisonInfo(); + var signatureIsSubtype = this.sourceIsAssignableToTarget(inheritedIndexSignatures.numberSignatureWithBaseOrigin.signature.returnType, inheritedIndexSignatures.stringSignatureWithBaseOrigin.signature.returnType, interfaceName, context, comparisonInfo); + + if (!signatureIsSubtype) { + var enclosingSymbol = this.getEnclosingSymbolForAST(interfaceName); + var innerDiagnostic = TypeScript.getDiagnosticMessage(TypeScript.DiagnosticCode.Type_of_number_indexer_in_type_0_is_not_assignable_to_string_indexer_type_in_type_1_NL_2, [ + inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), + inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), comparisonInfo.message]); + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(interfaceName, TypeScript.DiagnosticCode.Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3, [ + interfaceSymbol.getDisplayName(enclosingSymbol), inheritedIndexSignatures.numberSignatureWithBaseOrigin.baseOrigin.getScopedName(), + inheritedIndexSignatures.stringSignatureWithBaseOrigin.baseOrigin.getScopedName(enclosingSymbol), innerDiagnostic])); + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.checkAssignability = function (ast, source, target, context) { + var comparisonInfo = new TypeComparisonInfo(); + + var isAssignable = this.sourceIsAssignableToTarget(source, target, ast, context, comparisonInfo); + + if (!isAssignable) { + var enclosingSymbol = this.getEnclosingSymbolForAST(ast); + if (comparisonInfo.message) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Cannot_convert_0_to_1_NL_2, [source.toString(enclosingSymbol), target.toString(enclosingSymbol), comparisonInfo.message])); + } else { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Cannot_convert_0_to_1, [source.toString(enclosingSymbol), target.toString(enclosingSymbol)])); + } + } + }; + + PullTypeResolver.prototype.isReference = function (ast, astSymbol) { + if (ast.kind() === 217 /* ParenthesizedExpression */) { + return this.isReference(ast.expression, astSymbol); + } + + if (ast.kind() !== 11 /* IdentifierName */ && ast.kind() !== 212 /* MemberAccessExpression */ && ast.kind() !== 221 /* ElementAccessExpression */) { + return false; + } + + if (ast.kind() === 11 /* IdentifierName */) { + if (astSymbol.kind === 512 /* Variable */ && astSymbol.anyDeclHasFlag(4096 /* Enum */)) { + return false; + } + + if (astSymbol.kind === 512 /* Variable */ && astSymbol.anyDeclHasFlag(102400 /* SomeInitializedModule */)) { + return false; + } + + if (astSymbol.kind === 32768 /* ConstructorMethod */ || astSymbol.kind === 16384 /* Function */) { + return false; + } + } + + if (ast.kind() === 212 /* MemberAccessExpression */ && astSymbol.kind === 67108864 /* EnumMember */) { + return false; + } + + return true; + }; + + PullTypeResolver.prototype.checkForSuperMemberAccess = function (expression, name, resolvedName, context) { + if (resolvedName) { + if (expression.kind() === 50 /* SuperKeyword */ && !resolvedName.isError() && resolvedName.kind !== 65536 /* Method */) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode.Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword)); + return true; + } + } + + return false; + }; + + PullTypeResolver.prototype.getEnclosingDeclForAST = function (ast) { + return this.semanticInfoChain.getEnclosingDecl(ast); + }; + + PullTypeResolver.prototype.getEnclosingSymbolForAST = function (ast) { + var enclosingDecl = this.getEnclosingDeclForAST(ast); + return enclosingDecl ? enclosingDecl.getSymbol() : null; + }; + + PullTypeResolver.prototype.checkForPrivateMemberAccess = function (name, expressionType, resolvedName, context) { + if (resolvedName) { + if (resolvedName.anyDeclHasFlag(2 /* Private */)) { + var memberContainer = resolvedName.getContainer(); + if (memberContainer && memberContainer.kind === 33554432 /* ConstructorType */) { + memberContainer = memberContainer.getAssociatedContainerType(); + } + + if (memberContainer && memberContainer.isClass()) { + var memberClass = memberContainer.getDeclarations()[0].ast(); + TypeScript.Debug.assert(memberClass); + + var containingClass = this.getEnclosingClassDeclaration(name); + + if (!containingClass || containingClass !== memberClass) { + context.postDiagnostic(this.semanticInfoChain.diagnosticFromAST(name, TypeScript.DiagnosticCode._0_1_is_inaccessible, [memberContainer.toString(null, false), name.text()])); + return true; + } + } + } + } + + return false; + }; + + PullTypeResolver.prototype.instantiateType = function (type, typeParameterArgumentMap) { + if (type.isPrimitive()) { + return type; + } + + if (type.isError()) { + return type; + } + + if (typeParameterArgumentMap[type.pullSymbolID]) { + return typeParameterArgumentMap[type.pullSymbolID]; + } + + type._resolveDeclaredSymbol(); + if (type.isTypeParameter()) { + return this.instantiateTypeParameter(type, typeParameterArgumentMap); + } + + if (type.wrapsSomeTypeParameter(typeParameterArgumentMap)) { + return TypeScript.PullInstantiatedTypeReferenceSymbol.create(this, type, typeParameterArgumentMap); + } + + return type; + }; + + PullTypeResolver.prototype.instantiateTypeParameter = function (typeParameter, typeParameterArgumentMap) { + var constraint = typeParameter.getConstraint(); + if (!constraint) { + return typeParameter; + } + + var instantiatedConstraint = this.instantiateType(constraint, typeParameterArgumentMap); + + if (instantiatedConstraint == constraint) { + return typeParameter; + } + + var rootTypeParameter = typeParameter.getRootSymbol(); + var instantiation = rootTypeParameter.getSpecialization([instantiatedConstraint]); + if (instantiation) { + return instantiation; + } + + instantiation = new TypeScript.PullInstantiatedTypeParameterSymbol(rootTypeParameter, instantiatedConstraint); + return instantiation; + }; + + PullTypeResolver.prototype.instantiateSignature = function (signature, typeParameterArgumentMap) { + if (!signature.wrapsSomeTypeParameter(typeParameterArgumentMap)) { + return signature; + } + + var rootSignature = signature.getRootSymbol(); + var mutableTypeParameterMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(typeParameterArgumentMap); + TypeScript.PullInstantiationHelpers.instantiateTypeArgument(this, signature, mutableTypeParameterMap); + + var instantiatedSignature = rootSignature.getSpecialization(mutableTypeParameterMap.typeParameterArgumentMap); + if (instantiatedSignature) { + return instantiatedSignature; + } + + TypeScript.PullInstantiationHelpers.cleanUpTypeArgumentMap(signature, mutableTypeParameterMap); + typeParameterArgumentMap = mutableTypeParameterMap.typeParameterArgumentMap; + + instantiatedSignature = new TypeScript.PullInstantiatedSignatureSymbol(rootSignature, typeParameterArgumentMap); + + instantiatedSignature.returnType = this.instantiateType((rootSignature.returnType || this.semanticInfoChain.anyTypeSymbol), typeParameterArgumentMap); + instantiatedSignature.functionType = this.instantiateType(rootSignature.functionType, typeParameterArgumentMap); + + var parameters = rootSignature.parameters; + var parameter = null; + + if (parameters) { + for (var j = 0; j < parameters.length; j++) { + parameter = new TypeScript.PullSymbol(parameters[j].name, 2048 /* Parameter */); + parameter.setRootSymbol(parameters[j]); + + if (parameters[j].isOptional) { + parameter.isOptional = true; + } + if (parameters[j].isVarArg) { + parameter.isVarArg = true; + instantiatedSignature.hasVarArgs = true; + } + instantiatedSignature.addParameter(parameter, parameter.isOptional); + + parameter.type = this.instantiateType(parameters[j].type, typeParameterArgumentMap); + } + } + + return instantiatedSignature; + }; + PullTypeResolver.globalTypeCheckPhase = 0; + return PullTypeResolver; + })(); + TypeScript.PullTypeResolver = PullTypeResolver; + + var TypeComparisonInfo = (function () { + function TypeComparisonInfo(sourceComparisonInfo, useSameIndent) { + this.onlyCaptureFirstError = false; + this.flags = 0 /* SuccessfulComparison */; + this.message = ""; + this.stringConstantVal = null; + this.indent = 1; + if (sourceComparisonInfo) { + this.flags = sourceComparisonInfo.flags; + this.onlyCaptureFirstError = sourceComparisonInfo.onlyCaptureFirstError; + this.stringConstantVal = sourceComparisonInfo.stringConstantVal; + this.indent = sourceComparisonInfo.indent; + if (!useSameIndent) { + this.indent++; + } + } + } + TypeComparisonInfo.prototype.indentString = function () { + var result = ""; + + for (var i = 0; i < this.indent; i++) { + result += "\t"; + } + + return result; + }; + + TypeComparisonInfo.prototype.addMessage = function (message) { + if (!this.onlyCaptureFirstError && this.message) { + this.message = this.message + TypeScript.newLine() + this.indentString() + message; + } else { + this.message = this.indentString() + message; + } + }; + return TypeComparisonInfo; + })(); + TypeScript.TypeComparisonInfo = TypeComparisonInfo; + + function getPropertyAssignmentNameTextFromIdentifier(identifier) { + if (identifier.kind() === 11 /* IdentifierName */) { + return { actualText: identifier.text(), memberName: identifier.valueText() }; + } else if (identifier.kind() === 14 /* StringLiteral */) { + return { actualText: identifier.text(), memberName: identifier.valueText() }; + } else if (identifier.kind() === 13 /* NumericLiteral */) { + return { actualText: identifier.text(), memberName: identifier.valueText() }; + } else { + throw TypeScript.Errors.invalidOperation(); + } + } + TypeScript.getPropertyAssignmentNameTextFromIdentifier = getPropertyAssignmentNameTextFromIdentifier; + + function isTypesOnlyLocation(ast) { + while (ast && ast.parent) { + switch (ast.parent.kind()) { + case 244 /* TypeAnnotation */: + return true; + case 127 /* TypeQuery */: + return false; + case 125 /* ConstructorType */: + var constructorType = ast.parent; + if (constructorType.type === ast) { + return true; + } + break; + case 123 /* FunctionType */: + var functionType = ast.parent; + if (functionType.type === ast) { + return true; + } + break; + case 239 /* Constraint */: + var constraint = ast.parent; + if (constraint.type === ast) { + return true; + } + break; + case 220 /* CastExpression */: + var castExpression = ast.parent; + return castExpression.type === ast; + case 230 /* ExtendsHeritageClause */: + case 231 /* ImplementsHeritageClause */: + return true; + case 228 /* TypeArgumentList */: + return true; + case 131 /* ClassDeclaration */: + case 128 /* InterfaceDeclaration */: + case 130 /* ModuleDeclaration */: + case 129 /* FunctionDeclaration */: + case 145 /* MethodSignature */: + case 212 /* MemberAccessExpression */: + case 242 /* Parameter */: + return false; + } + + ast = ast.parent; + } + + return false; + } + TypeScript.isTypesOnlyLocation = isTypesOnlyLocation; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.declCacheHit = 0; + TypeScript.declCacheMiss = 0; + TypeScript.symbolCacheHit = 0; + TypeScript.symbolCacheMiss = 0; + + var sentinalEmptyArray = []; + + var SemanticInfoChain = (function () { + function SemanticInfoChain(compiler, logger) { + this.compiler = compiler; + this.logger = logger; + this.documents = []; + this.fileNameToDocument = TypeScript.createIntrinsicsObject(); + this.anyTypeDecl = null; + this.booleanTypeDecl = null; + this.numberTypeDecl = null; + this.stringTypeDecl = null; + this.nullTypeDecl = null; + this.undefinedTypeDecl = null; + this.voidTypeDecl = null; + this.undefinedValueDecl = null; + this.anyTypeSymbol = null; + this.booleanTypeSymbol = null; + this.numberTypeSymbol = null; + this.stringTypeSymbol = null; + this.nullTypeSymbol = null; + this.undefinedTypeSymbol = null; + this.voidTypeSymbol = null; + this.undefinedValueSymbol = null; + this.emptyTypeSymbol = null; + this.astSymbolMap = []; + this.astAliasSymbolMap = []; + this.astCallResolutionDataMap = []; + this.declSymbolMap = []; + this.declSignatureSymbolMap = []; + this.declCache = null; + this.symbolCache = null; + this.fileNameToDiagnostics = null; + this._binder = null; + this._resolver = null; + this._topLevelDecls = null; + this._fileNames = null; + var globalDecl = new TypeScript.RootPullDecl("", "", 0 /* Global */, 0 /* None */, this, false); + this.documents[0] = new TypeScript.Document(this.compiler, this, "", [], null, 0 /* None */, 0, false, null, globalDecl); + + this.anyTypeDecl = new TypeScript.NormalPullDecl("any", "any", 2 /* Primitive */, 0 /* None */, globalDecl); + this.booleanTypeDecl = new TypeScript.NormalPullDecl("boolean", "boolean", 2 /* Primitive */, 0 /* None */, globalDecl); + this.numberTypeDecl = new TypeScript.NormalPullDecl("number", "number", 2 /* Primitive */, 0 /* None */, globalDecl); + this.stringTypeDecl = new TypeScript.NormalPullDecl("string", "string", 2 /* Primitive */, 0 /* None */, globalDecl); + this.voidTypeDecl = new TypeScript.NormalPullDecl("void", "void", 2 /* Primitive */, 0 /* None */, globalDecl); + + this.nullTypeDecl = new TypeScript.RootPullDecl("null", "", 2 /* Primitive */, 0 /* None */, this, false); + this.undefinedTypeDecl = new TypeScript.RootPullDecl("undefined", "", 2 /* Primitive */, 0 /* None */, this, false); + this.undefinedValueDecl = new TypeScript.NormalPullDecl("undefined", "undefined", 512 /* Variable */, 8 /* Ambient */, globalDecl); + + this.invalidate(); + } + SemanticInfoChain.prototype.getDocument = function (fileName) { + var document = this.fileNameToDocument[fileName]; + return document || null; + }; + + SemanticInfoChain.prototype.lineMap = function (fileName) { + return this.getDocument(fileName).lineMap(); + }; + + SemanticInfoChain.prototype.fileNames = function () { + if (this._fileNames === null) { + this._fileNames = this.documents.slice(1).map(function (s) { + return s.fileName; + }); + } + + return this._fileNames; + }; + + SemanticInfoChain.prototype.bindPrimitiveSymbol = function (decl, newSymbol) { + newSymbol.addDeclaration(decl); + decl.setSymbol(newSymbol); + newSymbol.setResolved(); + + return newSymbol; + }; + + SemanticInfoChain.prototype.addPrimitiveTypeSymbol = function (decl) { + var newSymbol = new TypeScript.PullPrimitiveTypeSymbol(decl.name); + return this.bindPrimitiveSymbol(decl, newSymbol); + }; + + SemanticInfoChain.prototype.addPrimitiveValueSymbol = function (decl, type) { + var newSymbol = new TypeScript.PullSymbol(decl.name, 512 /* Variable */); + newSymbol.type = type; + return this.bindPrimitiveSymbol(decl, newSymbol); + }; + + SemanticInfoChain.prototype.resetGlobalSymbols = function () { + this.anyTypeSymbol = this.addPrimitiveTypeSymbol(this.anyTypeDecl); + this.booleanTypeSymbol = this.addPrimitiveTypeSymbol(this.booleanTypeDecl); + this.numberTypeSymbol = this.addPrimitiveTypeSymbol(this.numberTypeDecl); + this.stringTypeSymbol = this.addPrimitiveTypeSymbol(this.stringTypeDecl); + this.voidTypeSymbol = this.addPrimitiveTypeSymbol(this.voidTypeDecl); + this.nullTypeSymbol = this.addPrimitiveTypeSymbol(this.nullTypeDecl); + this.undefinedTypeSymbol = this.addPrimitiveTypeSymbol(this.undefinedTypeDecl); + this.undefinedValueSymbol = this.addPrimitiveValueSymbol(this.undefinedValueDecl, this.undefinedTypeSymbol); + + var emptyTypeDecl = new TypeScript.PullSynthesizedDecl("{}", "{}", 8388608 /* ObjectType */, 0 /* None */, null, this); + var emptyTypeSymbol = new TypeScript.PullTypeSymbol("{}", 8388608 /* ObjectType */); + emptyTypeDecl.setSymbol(emptyTypeSymbol); + emptyTypeSymbol.addDeclaration(emptyTypeDecl); + emptyTypeSymbol.setResolved(); + this.emptyTypeSymbol = emptyTypeSymbol; + }; + + SemanticInfoChain.prototype.addDocument = function (document) { + var fileName = document.fileName; + + var existingIndex = TypeScript.ArrayUtilities.indexOf(this.documents, function (u) { + return u.fileName === fileName; + }); + if (existingIndex < 0) { + this.documents.push(document); + } else { + this.documents[existingIndex] = document; + } + + this.fileNameToDocument[fileName] = document; + + this.invalidate(); + }; + + SemanticInfoChain.prototype.removeDocument = function (fileName) { + TypeScript.Debug.assert(fileName !== "", "Can't remove the semantic info for the global decl."); + var index = TypeScript.ArrayUtilities.indexOf(this.documents, function (u) { + return u.fileName === fileName; + }); + if (index > 0) { + this.fileNameToDocument[fileName] = undefined; + this.documents.splice(index, 1); + this.invalidate(); + } + }; + + SemanticInfoChain.prototype.getDeclPathCacheID = function (declPath, declKind) { + var cacheID = ""; + + for (var i = 0; i < declPath.length; i++) { + cacheID += "#" + declPath[i]; + } + + return cacheID + "#" + declKind.toString(); + }; + + SemanticInfoChain.prototype.findTopLevelSymbol = function (name, kind, doNotGoPastThisDecl) { + var cacheID = this.getDeclPathCacheID([name], kind); + + var symbol = this.symbolCache[cacheID]; + + if (!symbol) { + for (var i = 0, n = this.documents.length; i < n; i++) { + var topLevelDecl = this.documents[i].topLevelDecl(); + + var symbol = this.findTopLevelSymbolInDecl(topLevelDecl, name, kind, doNotGoPastThisDecl); + if (symbol) { + break; + } + + if (doNotGoPastThisDecl && topLevelDecl.name === doNotGoPastThisDecl.fileName()) { + return null; + } + } + + if (symbol) { + this.symbolCache[cacheID] = symbol; + } + } + + return symbol; + }; + + SemanticInfoChain.prototype.findTopLevelSymbolInDecl = function (topLevelDecl, name, kind, doNotGoPastThisDecl) { + var doNotGoPastThisPosition = doNotGoPastThisDecl && doNotGoPastThisDecl.fileName() === topLevelDecl.fileName() ? doNotGoPastThisDecl.ast().start() : -1; + + var foundDecls = topLevelDecl.searchChildDecls(name, kind); + + for (var j = 0; j < foundDecls.length; j++) { + var foundDecl = foundDecls[j]; + + if (doNotGoPastThisPosition !== -1 && foundDecl.ast() && foundDecl.ast().start() > doNotGoPastThisPosition) { + break; + } + + var symbol = foundDecls[j].getSymbol(); + if (symbol) { + return symbol; + } + } + + return null; + }; + + SemanticInfoChain.prototype.findExternalModule = function (id) { + id = TypeScript.normalizePath(id); + + var tsFile = id + ".ts"; + var tsCacheID = this.getDeclPathCacheID([tsFile], 32 /* DynamicModule */); + symbol = this.symbolCache[tsCacheID]; + if (symbol != undefined) { + return symbol; + } + + var dtsFile = id + ".d.ts"; + var dtsCacheID = this.getDeclPathCacheID([dtsFile], 32 /* DynamicModule */); + var symbol = this.symbolCache[dtsCacheID]; + if (symbol) { + return symbol; + } + + var dtsSymbol; + for (var i = 0; i < this.documents.length; i++) { + var document = this.documents[i]; + var topLevelDecl = document.topLevelDecl(); + + if (topLevelDecl.isExternalModule()) { + var isTsFile = document.fileName === tsFile; + if (isTsFile || document.fileName === dtsFile) { + var dynamicModuleDecl = topLevelDecl.getChildDecls()[0]; + symbol = dynamicModuleDecl.getSymbol(); + + if (isTsFile) { + this.symbolCache[tsCacheID] = symbol; + + return symbol; + } else { + dtsSymbol = symbol; + } + } + } + } + + if (dtsSymbol) { + this.symbolCache[dtsCacheID] = symbol; + return dtsSymbol; + } + + this.symbolCache[dtsCacheID] = null; + this.symbolCache[tsCacheID] = null; + + return null; + }; + + SemanticInfoChain.prototype.findAmbientExternalModuleInGlobalContext = function (id) { + var cacheID = this.getDeclPathCacheID([id], 32 /* DynamicModule */); + + var symbol = this.symbolCache[cacheID]; + if (symbol == undefined) { + symbol = null; + for (var i = 0; i < this.documents.length; i++) { + var document = this.documents[i]; + var topLevelDecl = document.topLevelDecl(); + + if (!topLevelDecl.isExternalModule()) { + var dynamicModules = topLevelDecl.searchChildDecls(id, 32 /* DynamicModule */); + if (dynamicModules.length) { + symbol = dynamicModules[0].getSymbol(); + break; + } + } + } + + this.symbolCache[cacheID] = symbol; + } + + return symbol; + }; + + SemanticInfoChain.prototype.findDecls = function (declPath, declKind) { + var cacheID = this.getDeclPathCacheID(declPath, declKind); + + if (declPath.length) { + var cachedDecls = this.declCache[cacheID]; + + if (cachedDecls && cachedDecls.length) { + TypeScript.declCacheHit++; + return cachedDecls; + } + } + + TypeScript.declCacheMiss++; + + var declsToSearch = this.topLevelDecls(); + + var decls = TypeScript.sentinelEmptyArray; + var path; + var foundDecls = TypeScript.sentinelEmptyArray; + + for (var i = 0; i < declPath.length; i++) { + path = declPath[i]; + decls = TypeScript.sentinelEmptyArray; + + var kind = (i === declPath.length - 1) ? declKind : 164 /* SomeContainer */; + for (var j = 0; j < declsToSearch.length; j++) { + foundDecls = declsToSearch[j].searchChildDecls(path, kind); + + for (var k = 0; k < foundDecls.length; k++) { + if (decls === TypeScript.sentinelEmptyArray) { + decls = []; + } + decls[decls.length] = foundDecls[k]; + } + } + + declsToSearch = decls; + + if (!declsToSearch) { + break; + } + } + + if (decls.length) { + this.declCache[cacheID] = decls; + } + + return decls; + }; + + SemanticInfoChain.prototype.findDeclsFromPath = function (declPath, declKind) { + var declString = []; + + for (var i = 0, n = declPath.length; i < n; i++) { + if (declPath[i].kind & 1 /* Script */) { + continue; + } + + declString.push(declPath[i].name); + } + + return this.findDecls(declString, declKind); + }; + + SemanticInfoChain.prototype.findSymbol = function (declPath, declType) { + var cacheID = this.getDeclPathCacheID(declPath, declType); + + if (declPath.length) { + var cachedSymbol = this.symbolCache[cacheID]; + + if (cachedSymbol) { + TypeScript.symbolCacheHit++; + return cachedSymbol; + } + } + + TypeScript.symbolCacheMiss++; + + var decls = this.findDecls(declPath, declType); + var symbol = null; + + if (decls.length) { + var decl = decls[0]; + if (TypeScript.hasFlag(decl.kind, 164 /* SomeContainer */)) { + var valueDecl = decl.getValueDecl(); + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + } + symbol = decl.getSymbol(); + + if (symbol) { + for (var i = 1; i < decls.length; i++) { + decls[i].ensureSymbolIsBound(); + } + + this.symbolCache[cacheID] = symbol; + } + } + + return symbol; + }; + + SemanticInfoChain.prototype.cacheGlobalSymbol = function (symbol, kind) { + var cacheID1 = this.getDeclPathCacheID([symbol.name], kind); + var cacheID2 = this.getDeclPathCacheID([symbol.name], symbol.kind); + + if (!this.symbolCache[cacheID1]) { + this.symbolCache[cacheID1] = symbol; + } + + if (!this.symbolCache[cacheID2]) { + this.symbolCache[cacheID2] = symbol; + } + }; + + SemanticInfoChain.prototype.invalidate = function (oldSettings, newSettings) { + if (typeof oldSettings === "undefined") { oldSettings = null; } + if (typeof newSettings === "undefined") { newSettings = null; } + TypeScript.PullTypeResolver.globalTypeCheckPhase++; + + var cleanStart = new Date().getTime(); + + this.astSymbolMap.length = 0; + this.astAliasSymbolMap.length = 0; + this.astCallResolutionDataMap.length = 0; + + this.declCache = TypeScript.createIntrinsicsObject(); + this.symbolCache = TypeScript.createIntrinsicsObject(); + this.fileNameToDiagnostics = TypeScript.createIntrinsicsObject(); + this._binder = null; + this._resolver = null; + this._topLevelDecls = null; + this._fileNames = null; + + this.declSymbolMap.length = 0; + this.declSignatureSymbolMap.length = 0; + + if (oldSettings && newSettings) { + if (this.settingsChangeAffectsSyntax(oldSettings, newSettings)) { + for (var i = 1, n = this.documents.length; i < n; i++) { + this.documents[i].invalidate(); + } + } + } + + TypeScript.pullSymbolID = 0; + + this.resetGlobalSymbols(); + + var cleanEnd = new Date().getTime(); + }; + + SemanticInfoChain.prototype.settingsChangeAffectsSyntax = function (before, after) { + return before.allowAutomaticSemicolonInsertion() !== after.allowAutomaticSemicolonInsertion() || before.codeGenTarget() !== after.codeGenTarget() || before.propagateEnumConstants() !== after.propagateEnumConstants(); + }; + + SemanticInfoChain.prototype.setSymbolForAST = function (ast, symbol) { + this.astSymbolMap[ast.syntaxID()] = symbol; + }; + + SemanticInfoChain.prototype.getSymbolForAST = function (ast) { + return this.astSymbolMap[ast.syntaxID()] || null; + }; + + SemanticInfoChain.prototype.setAliasSymbolForAST = function (ast, symbol) { + this.astAliasSymbolMap[ast.syntaxID()] = symbol; + }; + + SemanticInfoChain.prototype.getAliasSymbolForAST = function (ast) { + return this.astAliasSymbolMap[ast.syntaxID()]; + }; + + SemanticInfoChain.prototype.getCallResolutionDataForAST = function (ast) { + return this.astCallResolutionDataMap[ast.syntaxID()]; + }; + + SemanticInfoChain.prototype.setCallResolutionDataForAST = function (ast, callResolutionData) { + if (callResolutionData) { + this.astCallResolutionDataMap[ast.syntaxID()] = callResolutionData; + } + }; + + SemanticInfoChain.prototype.setSymbolForDecl = function (decl, symbol) { + this.declSymbolMap[decl.declID] = symbol; + }; + + SemanticInfoChain.prototype.getSymbolForDecl = function (decl) { + return this.declSymbolMap[decl.declID]; + }; + + SemanticInfoChain.prototype.setSignatureSymbolForDecl = function (decl, signatureSymbol) { + this.declSignatureSymbolMap[decl.declID] = signatureSymbol; + }; + + SemanticInfoChain.prototype.getSignatureSymbolForDecl = function (decl) { + return this.declSignatureSymbolMap[decl.declID]; + }; + + SemanticInfoChain.prototype.addDiagnostic = function (diagnostic) { + var fileName = diagnostic.fileName(); + var diagnostics = this.fileNameToDiagnostics[fileName]; + if (!diagnostics) { + diagnostics = []; + this.fileNameToDiagnostics[fileName] = diagnostics; + } + + diagnostics.push(diagnostic); + }; + + SemanticInfoChain.prototype.getDiagnostics = function (fileName) { + var diagnostics = this.fileNameToDiagnostics[fileName]; + return diagnostics || []; + }; + + SemanticInfoChain.prototype.getBinder = function () { + if (!this._binder) { + this._binder = new TypeScript.PullSymbolBinder(this); + } + + return this._binder; + }; + + SemanticInfoChain.prototype.getResolver = function () { + if (!this._resolver) { + this._resolver = new TypeScript.PullTypeResolver(this.compiler.compilationSettings(), this); + } + + return this._resolver; + }; + + SemanticInfoChain.prototype.addSyntheticIndexSignature = function (containingDecl, containingSymbol, ast, indexParamName, indexParamType, returnType) { + var indexSignature = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + var indexParameterSymbol = new TypeScript.PullSymbol(indexParamName, 2048 /* Parameter */); + indexParameterSymbol.type = indexParamType; + indexSignature.addParameter(indexParameterSymbol); + indexSignature.returnType = returnType; + indexSignature.setResolved(); + indexParameterSymbol.setResolved(); + + containingSymbol.addIndexSignature(indexSignature); + + var indexSigDecl = new TypeScript.PullSynthesizedDecl("", "", 4194304 /* IndexSignature */, 2048 /* Signature */, containingDecl, containingDecl.semanticInfoChain); + var indexParamDecl = new TypeScript.PullSynthesizedDecl(indexParamName, indexParamName, 2048 /* Parameter */, 0 /* None */, indexSigDecl, containingDecl.semanticInfoChain); + indexSigDecl.setSignatureSymbol(indexSignature); + indexParamDecl.setSymbol(indexParameterSymbol); + indexSignature.addDeclaration(indexSigDecl); + indexParameterSymbol.addDeclaration(indexParamDecl); + }; + + SemanticInfoChain.prototype.getDeclForAST = function (ast) { + var document = this.getDocument(ast.fileName()); + + if (document) { + return document._getDeclForAST(ast); + } + + return null; + }; + + SemanticInfoChain.prototype.getEnclosingDecl = function (ast) { + return this.getDocument(ast.fileName()).getEnclosingDecl(ast); + }; + + SemanticInfoChain.prototype.setDeclForAST = function (ast, decl) { + this.getDocument(decl.fileName())._setDeclForAST(ast, decl); + }; + + SemanticInfoChain.prototype.getASTForDecl = function (decl) { + var document = this.getDocument(decl.fileName()); + if (document) { + return document._getASTForDecl(decl); + } + + return null; + }; + + SemanticInfoChain.prototype.setASTForDecl = function (decl, ast) { + this.getDocument(decl.fileName())._setASTForDecl(decl, ast); + }; + + SemanticInfoChain.prototype.topLevelDecl = function (fileName) { + var document = this.getDocument(fileName); + if (document) { + return document.topLevelDecl(); + } + + return null; + }; + + SemanticInfoChain.prototype.topLevelDecls = function () { + if (!this._topLevelDecls) { + this._topLevelDecls = TypeScript.ArrayUtilities.select(this.documents, function (u) { + return u.topLevelDecl(); + }); + } + + return this._topLevelDecls; + }; + + SemanticInfoChain.prototype.addDiagnosticFromAST = function (ast, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + this.addDiagnostic(this.diagnosticFromAST(ast, diagnosticKey, _arguments, additionalLocations)); + }; + + SemanticInfoChain.prototype.diagnosticFromAST = function (ast, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + return new TypeScript.Diagnostic(ast.fileName(), this.lineMap(ast.fileName()), ast.start(), ast.width(), diagnosticKey, _arguments, additionalLocations); + }; + + SemanticInfoChain.prototype.locationFromAST = function (ast) { + return new TypeScript.Location(ast.fileName(), this.lineMap(ast.fileName()), ast.start(), ast.width()); + }; + + SemanticInfoChain.prototype.duplicateIdentifierDiagnosticFromAST = function (ast, identifier, additionalLocationAST) { + return this.diagnosticFromAST(ast, TypeScript.DiagnosticCode.Duplicate_identifier_0, [identifier], additionalLocationAST ? [this.locationFromAST(additionalLocationAST)] : null); + }; + + SemanticInfoChain.prototype.addDuplicateIdentifierDiagnosticFromAST = function (ast, identifier, additionalLocationAST) { + this.addDiagnostic(this.duplicateIdentifierDiagnosticFromAST(ast, identifier, additionalLocationAST)); + }; + return SemanticInfoChain; + })(); + TypeScript.SemanticInfoChain = SemanticInfoChain; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DeclCollectionContext = (function () { + function DeclCollectionContext(document, semanticInfoChain, propagateEnumConstants) { + this.document = document; + this.semanticInfoChain = semanticInfoChain; + this.propagateEnumConstants = propagateEnumConstants; + this.isDeclareFile = false; + this.parentChain = []; + } + DeclCollectionContext.prototype.getParent = function () { + return this.parentChain ? this.parentChain[this.parentChain.length - 1] : null; + }; + + DeclCollectionContext.prototype.pushParent = function (parentDecl) { + if (parentDecl) { + this.parentChain[this.parentChain.length] = parentDecl; + } + }; + + DeclCollectionContext.prototype.popParent = function () { + this.parentChain.length--; + }; + return DeclCollectionContext; + })(); + + function moduleElementsHasExportAssignment(moduleElements) { + return moduleElements.any(function (m) { + return m.kind() === 134 /* ExportAssignment */; + }); + } + + function containingModuleHasExportAssignment(ast) { + ast = ast.parent; + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + var moduleDecl = ast; + return moduleElementsHasExportAssignment(moduleDecl.moduleElements); + } else if (ast.kind() === 120 /* SourceUnit */) { + var sourceUnit = ast; + return moduleElementsHasExportAssignment(sourceUnit.moduleElements); + } + + ast = ast.parent; + } + + return false; + } + + function isParsingAmbientModule(ast, context) { + ast = ast.parent; + while (ast) { + if (ast.kind() === 130 /* ModuleDeclaration */) { + if (TypeScript.hasModifier(ast.modifiers, 8 /* Ambient */)) { + return true; + } + } + + ast = ast.parent; + } + + return false; + } + + function preCollectImportDecls(ast, context) { + var importDecl = ast; + var declFlags = 0 /* None */; + + var parent = context.getParent(); + + if (TypeScript.hasModifier(importDecl.modifiers, 1 /* Exported */) && !containingModuleHasExportAssignment(ast)) { + declFlags |= 1 /* Exported */; + } + + var decl = new TypeScript.NormalPullDecl(importDecl.identifier.valueText(), importDecl.identifier.text(), 128 /* TypeAlias */, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + } + + function preCollectScriptDecls(sourceUnit, context) { + var fileName = sourceUnit.fileName(); + + var isExternalModule = context.document.isExternalModule(); + + var decl = new TypeScript.RootPullDecl(fileName, fileName, 1 /* Script */, 0 /* None */, context.semanticInfoChain, isExternalModule); + context.semanticInfoChain.setDeclForAST(sourceUnit, decl); + context.semanticInfoChain.setASTForDecl(decl, sourceUnit); + + context.isDeclareFile = context.document.isDeclareFile(); + + context.pushParent(decl); + + if (isExternalModule) { + var declFlags = 1 /* Exported */; + if (TypeScript.isDTSFile(fileName)) { + declFlags |= 8 /* Ambient */; + } + + var moduleContainsExecutableCode = containsExecutableCode(sourceUnit.moduleElements); + var kind = 32 /* DynamicModule */; + var valueText = TypeScript.quoteStr(fileName); + + var decl = new TypeScript.NormalPullDecl(valueText, fileName, kind, declFlags, context.getParent()); + + context.semanticInfoChain.setASTForDecl(decl, sourceUnit); + + context.semanticInfoChain.setDeclForAST(sourceUnit, decl); + + if (!moduleElementsHasExportAssignment(sourceUnit.moduleElements) || moduleContainsExecutableCode) { + createModuleVariableDecl(decl, sourceUnit, context); + } + + context.pushParent(decl); + } + } + + function preCollectEnumDecls(enumDecl, context) { + var declFlags = 0 /* None */; + var enumName = enumDecl.identifier.valueText(); + + if ((TypeScript.hasModifier(enumDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(enumDecl, context)) && !containingModuleHasExportAssignment(enumDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(enumDecl.modifiers, 8 /* Ambient */) || isParsingAmbientModule(enumDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + declFlags |= 4096 /* Enum */; + var kind = 64 /* Enum */; + + var enumDeclaration = new TypeScript.NormalPullDecl(enumName, enumDecl.identifier.text(), kind, declFlags, context.getParent()); + context.semanticInfoChain.setDeclForAST(enumDecl, enumDeclaration); + context.semanticInfoChain.setASTForDecl(enumDeclaration, enumDecl); + + var valueDecl = new TypeScript.NormalPullDecl(enumDeclaration.name, enumDeclaration.getDisplayName(), 512 /* Variable */, enumDeclaration.flags, context.getParent()); + enumDeclaration.setValueDecl(valueDecl); + context.semanticInfoChain.setASTForDecl(valueDecl, enumDecl); + + context.pushParent(enumDeclaration); + } + + function createEnumElementDecls(propertyDecl, context) { + var parent = context.getParent(); + + var decl = new TypeScript.PullEnumElementDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), parent); + context.semanticInfoChain.setDeclForAST(propertyDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyDecl); + } + + function preCollectModuleDecls(moduleDecl, context) { + var declFlags = 0 /* None */; + + var moduleContainsExecutableCode = containsExecutableCode(moduleDecl.moduleElements); + + var isDynamic = moduleDecl.stringLiteral !== null; + + if ((TypeScript.hasModifier(moduleDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(moduleDecl, context)) && !containingModuleHasExportAssignment(moduleDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(moduleDecl.modifiers, 8 /* Ambient */) || isParsingAmbientModule(moduleDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + var kind = isDynamic ? 32 /* DynamicModule */ : 4 /* Container */; + + if (moduleDecl.stringLiteral) { + var valueText = TypeScript.quoteStr(moduleDecl.stringLiteral.valueText()); + var text = moduleDecl.stringLiteral.text(); + + var decl = new TypeScript.NormalPullDecl(valueText, text, kind, declFlags, context.getParent()); + + context.semanticInfoChain.setDeclForAST(moduleDecl, decl); + context.semanticInfoChain.setDeclForAST(moduleDecl.stringLiteral, decl); + context.semanticInfoChain.setASTForDecl(decl, moduleDecl.stringLiteral); + + if (!moduleElementsHasExportAssignment(moduleDecl.moduleElements) || moduleContainsExecutableCode) { + createModuleVariableDecl(decl, moduleDecl.stringLiteral, context); + } + + context.pushParent(decl); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDecl.name); + for (var i = 0, n = moduleNames.length; i < n; i++) { + var moduleName = moduleNames[i]; + + var specificFlags = declFlags; + if (i > 0) { + specificFlags |= 1 /* Exported */; + } + + var decl = new TypeScript.NormalPullDecl(moduleName.valueText(), moduleName.text(), kind, specificFlags, context.getParent()); + + context.semanticInfoChain.setDeclForAST(moduleDecl, decl); + context.semanticInfoChain.setDeclForAST(moduleName, decl); + context.semanticInfoChain.setASTForDecl(decl, moduleName); + + if (moduleContainsExecutableCode) { + createModuleVariableDecl(decl, moduleName, context); + } + + context.pushParent(decl); + } + } + } + + function createModuleVariableDecl(decl, moduleNameAST, context) { + decl.setFlags(decl.flags | getInitializationFlag(decl)); + + var valueDecl = new TypeScript.NormalPullDecl(decl.name, decl.getDisplayName(), 512 /* Variable */, decl.flags, context.getParent()); + decl.setValueDecl(valueDecl); + context.semanticInfoChain.setASTForDecl(valueDecl, moduleNameAST); + } + + function containsExecutableCode(members) { + for (var i = 0, n = members.childCount(); i < n; i++) { + var member = members.childAt(i); + + if (member.kind() === 130 /* ModuleDeclaration */) { + var moduleDecl = member; + + if (containsExecutableCode(moduleDecl.moduleElements)) { + return true; + } + } else if (member.kind() === 133 /* ImportDeclaration */) { + if (TypeScript.hasModifier(member.modifiers, 1 /* Exported */)) { + return true; + } + } else if (member.kind() !== 128 /* InterfaceDeclaration */ && member.kind() !== 134 /* ExportAssignment */) { + return true; + } + } + + return false; + } + + function preCollectClassDecls(classDecl, context) { + var declFlags = 0 /* None */; + + if ((TypeScript.hasModifier(classDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(classDecl, context)) && !containingModuleHasExportAssignment(classDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(classDecl.modifiers, 8 /* Ambient */) || isParsingAmbientModule(classDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), 8 /* Class */, declFlags, parent); + + var constructorDecl = new TypeScript.NormalPullDecl(classDecl.identifier.valueText(), classDecl.identifier.text(), 512 /* Variable */, declFlags | 16384 /* ClassConstructorVariable */, parent); + + decl.setValueDecl(constructorDecl); + + context.semanticInfoChain.setDeclForAST(classDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, classDecl); + context.semanticInfoChain.setASTForDecl(constructorDecl, classDecl); + + context.pushParent(decl); + } + + function preCollectObjectTypeDecls(objectType, context) { + if (objectType.parent.kind() === 128 /* InterfaceDeclaration */) { + return; + } + + var declFlags = 0 /* None */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", 8388608 /* ObjectType */, declFlags, parent); + context.semanticInfoChain.setDeclForAST(objectType, decl); + context.semanticInfoChain.setASTForDecl(decl, objectType); + + context.pushParent(decl); + } + + function preCollectInterfaceDecls(interfaceDecl, context) { + var declFlags = 0 /* None */; + + if ((TypeScript.hasModifier(interfaceDecl.modifiers, 1 /* Exported */) || isParsingAmbientModule(interfaceDecl, context)) && !containingModuleHasExportAssignment(interfaceDecl)) { + declFlags |= 1 /* Exported */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(interfaceDecl.identifier.valueText(), interfaceDecl.identifier.text(), 16 /* Interface */, declFlags, parent); + context.semanticInfoChain.setDeclForAST(interfaceDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, interfaceDecl); + + context.pushParent(decl); + } + + function preCollectParameterDecl(argDecl, context) { + var declFlags = 0 /* None */; + + if (TypeScript.hasModifier(argDecl.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (argDecl.questionToken !== null || argDecl.equalsValueClause !== null || argDecl.dotDotDotToken !== null) { + declFlags |= 128 /* Optional */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 2048 /* Parameter */, declFlags, parent); + + if (argDecl.equalsValueClause) { + parent.flags |= 33554432 /* HasDefaultArgs */; + } + + if (parent.kind === 32768 /* ConstructorMethod */) { + decl.setFlag(67108864 /* ConstructorParameter */); + } + + var isPublicOrPrivate = TypeScript.hasModifier(argDecl.modifiers, 4 /* Public */ | 2 /* Private */); + var isInConstructor = parent.kind === 32768 /* ConstructorMethod */; + if (isPublicOrPrivate && isInConstructor) { + var parentsParent = context.parentChain[context.parentChain.length - 2]; + + var propDeclFlags = declFlags & ~128 /* Optional */; + var propDecl = new TypeScript.NormalPullDecl(argDecl.identifier.valueText(), argDecl.identifier.text(), 4096 /* Property */, propDeclFlags, parentsParent); + propDecl.setValueDecl(decl); + decl.setFlag(8388608 /* PropertyParameter */); + propDecl.setFlag(8388608 /* PropertyParameter */); + + if (parent.kind === 32768 /* ConstructorMethod */) { + propDecl.setFlag(67108864 /* ConstructorParameter */); + } + + context.semanticInfoChain.setASTForDecl(decl, argDecl); + context.semanticInfoChain.setASTForDecl(propDecl, argDecl); + context.semanticInfoChain.setDeclForAST(argDecl, propDecl); + } else { + context.semanticInfoChain.setASTForDecl(decl, argDecl); + context.semanticInfoChain.setDeclForAST(argDecl, decl); + } + + parent.addVariableDeclToGroup(decl); + } + + function preCollectTypeParameterDecl(typeParameterDecl, context) { + var declFlags = 0 /* None */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(typeParameterDecl.identifier.valueText(), typeParameterDecl.identifier.text(), 8192 /* TypeParameter */, declFlags, parent); + context.semanticInfoChain.setASTForDecl(decl, typeParameterDecl); + context.semanticInfoChain.setDeclForAST(typeParameterDecl, decl); + } + + function createPropertySignature(propertyDecl, context) { + var declFlags = 4 /* Public */; + var parent = context.getParent(); + var declType = 4096 /* Property */; + + if (propertyDecl.questionToken !== null) { + declFlags |= 128 /* Optional */; + } + + var decl = new TypeScript.NormalPullDecl(propertyDecl.propertyName.valueText(), propertyDecl.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(propertyDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyDecl); + } + + function createMemberVariableDeclaration(memberDecl, context) { + var declFlags = 0 /* None */; + var declType = 4096 /* Property */; + + if (TypeScript.hasModifier(memberDecl.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (TypeScript.hasModifier(memberDecl.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(memberDecl.variableDeclarator.propertyName.valueText(), memberDecl.variableDeclarator.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(memberDecl, decl); + context.semanticInfoChain.setDeclForAST(memberDecl.variableDeclarator, decl); + context.semanticInfoChain.setASTForDecl(decl, memberDecl); + } + + function createVariableDeclaration(varDecl, context) { + var declFlags = 0 /* None */; + var declType = 512 /* Variable */; + + var modifiers = TypeScript.ASTHelpers.getVariableDeclaratorModifiers(varDecl); + if ((TypeScript.hasModifier(modifiers, 1 /* Exported */) || isParsingAmbientModule(varDecl, context)) && !containingModuleHasExportAssignment(varDecl)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(modifiers, 8 /* Ambient */) || isParsingAmbientModule(varDecl, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(varDecl.propertyName.valueText(), varDecl.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(varDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, varDecl); + + if (parent) { + parent.addVariableDeclToGroup(decl); + } + } + + function preCollectVarDecls(ast, context) { + if (ast.parent.kind() === 136 /* MemberVariableDeclaration */) { + return; + } + + var varDecl = ast; + createVariableDeclaration(varDecl, context); + } + + function createFunctionTypeDeclaration(functionTypeDeclAST, context) { + var declFlags = 2048 /* Signature */; + var declType = 16777216 /* FunctionType */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(functionTypeDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, functionTypeDeclAST); + + context.pushParent(decl); + } + + function createConstructorTypeDeclaration(constructorTypeDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 33554432 /* ConstructorType */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(constructorTypeDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, constructorTypeDeclAST); + + context.pushParent(decl); + } + + function createFunctionDeclaration(funcDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 16384 /* Function */; + + if ((TypeScript.hasModifier(funcDeclAST.modifiers, 1 /* Exported */) || isParsingAmbientModule(funcDeclAST, context)) && !containingModuleHasExportAssignment(funcDeclAST)) { + declFlags |= 1 /* Exported */; + } + + if (TypeScript.hasModifier(funcDeclAST.modifiers, 8 /* Ambient */) || isParsingAmbientModule(funcDeclAST, context) || context.isDeclareFile) { + declFlags |= 8 /* Ambient */; + } + + if (!funcDeclAST.block) { + declFlags |= 2048 /* Signature */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(funcDeclAST.identifier.valueText(), funcDeclAST.identifier.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(funcDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, funcDeclAST); + + context.pushParent(decl); + } + + function createAnyFunctionExpressionDeclaration(functionExpressionDeclAST, id, context, displayName) { + if (typeof displayName === "undefined") { displayName = null; } + var declFlags = 0 /* None */; + + if (functionExpressionDeclAST.kind() === 219 /* SimpleArrowFunctionExpression */ || functionExpressionDeclAST.kind() === 218 /* ParenthesizedArrowFunctionExpression */) { + declFlags |= 8192 /* ArrowFunction */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var name = id ? id.text() : ""; + var displayNameText = displayName ? displayName.text() : ""; + var decl = new TypeScript.PullFunctionExpressionDecl(name, declFlags, parent, displayNameText); + context.semanticInfoChain.setDeclForAST(functionExpressionDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, functionExpressionDeclAST); + + context.pushParent(decl); + + if (functionExpressionDeclAST.kind() === 219 /* SimpleArrowFunctionExpression */) { + var simpleArrow = functionExpressionDeclAST; + var declFlags = 4 /* Public */; + + var parent = context.getParent(); + + if (TypeScript.hasFlag(parent.flags, 2097152 /* DeclaredInAWithBlock */)) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(simpleArrow.identifier.valueText(), simpleArrow.identifier.text(), 2048 /* Parameter */, declFlags, parent); + + context.semanticInfoChain.setASTForDecl(decl, simpleArrow.identifier); + context.semanticInfoChain.setDeclForAST(simpleArrow.identifier, decl); + + parent.addVariableDeclToGroup(decl); + } + } + + function createMemberFunctionDeclaration(funcDecl, context) { + var declFlags = 0 /* None */; + var declType = 65536 /* Method */; + + if (TypeScript.hasModifier(funcDecl.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasModifier(funcDecl.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + if (!funcDecl.block) { + declFlags |= 2048 /* Signature */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(funcDecl.propertyName.valueText(), funcDecl.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(funcDecl, decl); + context.semanticInfoChain.setASTForDecl(decl, funcDecl); + + context.pushParent(decl); + } + + function createIndexSignatureDeclaration(indexSignatureDeclAST, context) { + var declFlags = 2048 /* Signature */; + var declType = 4194304 /* IndexSignature */; + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(indexSignatureDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, indexSignatureDeclAST); + + context.pushParent(decl); + } + + function createCallSignatureDeclaration(callSignature, context) { + var isChildOfObjectType = callSignature.parent && callSignature.parent.parent && callSignature.parent.kind() === 2 /* SeparatedList */ && callSignature.parent.parent.kind() === 122 /* ObjectType */; + + if (!isChildOfObjectType) { + return; + } + + var declFlags = 2048 /* Signature */; + var declType = 1048576 /* CallSignature */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(callSignature, decl); + context.semanticInfoChain.setASTForDecl(decl, callSignature); + + context.pushParent(decl); + } + + function createMethodSignatureDeclaration(method, context) { + var declFlags = 0 /* None */; + var declType = 65536 /* Method */; + + declFlags |= 4 /* Public */; + declFlags |= 2048 /* Signature */; + + if (method.questionToken !== null) { + declFlags |= 128 /* Optional */; + } + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl(method.propertyName.valueText(), method.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(method, decl); + context.semanticInfoChain.setASTForDecl(decl, method); + + context.pushParent(decl); + } + + function createConstructSignatureDeclaration(constructSignatureDeclAST, context) { + var declFlags = 2048 /* Signature */; + var declType = 2097152 /* ConstructSignature */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(constructSignatureDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, constructSignatureDeclAST); + + context.pushParent(decl); + } + + function createClassConstructorDeclaration(constructorDeclAST, context) { + var declFlags = 0 /* None */; + var declType = 32768 /* ConstructorMethod */; + + if (!constructorDeclAST.block) { + declFlags |= 2048 /* Signature */; + } + + var parent = context.getParent(); + + if (parent) { + var parentFlags = parent.flags; + + if (parentFlags & 1 /* Exported */) { + declFlags |= 1 /* Exported */; + } + } + + var decl = new TypeScript.NormalPullDecl(parent.name, parent.getDisplayName(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(constructorDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, constructorDeclAST); + + context.pushParent(decl); + } + + function createGetAccessorDeclaration(getAccessorDeclAST, context) { + var declFlags = 4 /* Public */; + var declType = 262144 /* GetAccessor */; + + if (TypeScript.hasModifier(getAccessorDeclAST.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasModifier(getAccessorDeclAST.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(getAccessorDeclAST.propertyName.valueText(), getAccessorDeclAST.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(getAccessorDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, getAccessorDeclAST); + + context.pushParent(decl); + } + + function createFunctionExpressionDeclaration(expression, context) { + createAnyFunctionExpressionDeclaration(expression, expression.identifier, context); + } + + function createSetAccessorDeclaration(setAccessorDeclAST, context) { + var declFlags = 4 /* Public */; + var declType = 524288 /* SetAccessor */; + + if (TypeScript.hasModifier(setAccessorDeclAST.modifiers, 16 /* Static */)) { + declFlags |= 16 /* Static */; + } + + if (TypeScript.hasModifier(setAccessorDeclAST.modifiers, 2 /* Private */)) { + declFlags |= 2 /* Private */; + } else { + declFlags |= 4 /* Public */; + } + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(setAccessorDeclAST.propertyName.valueText(), setAccessorDeclAST.propertyName.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(setAccessorDeclAST, decl); + context.semanticInfoChain.setASTForDecl(decl, setAccessorDeclAST); + + context.pushParent(decl); + } + + function preCollectCatchDecls(ast, context) { + var declFlags = 0 /* None */; + var declType = 268435456 /* CatchBlock */; + + var parent = context.getParent(); + + if (parent && (parent.kind === 134217728 /* WithBlock */ || (parent.flags & 2097152 /* DeclaredInAWithBlock */))) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + + context.pushParent(decl); + + var declFlags = 0 /* None */; + var declType = 1024 /* CatchVariable */; + + var parent = context.getParent(); + + if (TypeScript.hasFlag(parent.flags, 2097152 /* DeclaredInAWithBlock */)) { + declFlags |= 2097152 /* DeclaredInAWithBlock */; + } + + var decl = new TypeScript.NormalPullDecl(ast.identifier.valueText(), ast.identifier.text(), declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast.identifier, decl); + context.semanticInfoChain.setASTForDecl(decl, ast.identifier); + + if (parent) { + parent.addVariableDeclToGroup(decl); + } + } + + function preCollectWithDecls(ast, context) { + var declFlags = 0 /* None */; + var declType = 134217728 /* WithBlock */; + + var parent = context.getParent(); + + var decl = new TypeScript.NormalPullDecl("", "", declType, declFlags, parent); + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + + context.pushParent(decl); + } + + function preCollectObjectLiteralDecls(ast, context) { + var decl = new TypeScript.NormalPullDecl("", "", 256 /* ObjectLiteral */, 0 /* None */, context.getParent()); + + context.semanticInfoChain.setDeclForAST(ast, decl); + context.semanticInfoChain.setASTForDecl(decl, ast); + + context.pushParent(decl); + } + + function preCollectSimplePropertyAssignmentDecls(propertyAssignment, context) { + var assignmentText = TypeScript.getPropertyAssignmentNameTextFromIdentifier(propertyAssignment.propertyName); + var span = TypeScript.TextSpan.fromBounds(propertyAssignment.start(), propertyAssignment.end()); + + var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent()); + + context.semanticInfoChain.setDeclForAST(propertyAssignment, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyAssignment); + } + + function preCollectFunctionPropertyAssignmentDecls(propertyAssignment, context) { + var assignmentText = TypeScript.getPropertyAssignmentNameTextFromIdentifier(propertyAssignment.propertyName); + + var decl = new TypeScript.NormalPullDecl(assignmentText.memberName, assignmentText.actualText, 4096 /* Property */, 4 /* Public */, context.getParent()); + + context.semanticInfoChain.setDeclForAST(propertyAssignment, decl); + context.semanticInfoChain.setASTForDecl(decl, propertyAssignment); + + createAnyFunctionExpressionDeclaration(propertyAssignment, propertyAssignment.propertyName, context, propertyAssignment.propertyName); + } + + function preCollectDecls(ast, context) { + switch (ast.kind()) { + case 120 /* SourceUnit */: + preCollectScriptDecls(ast, context); + break; + case 132 /* EnumDeclaration */: + preCollectEnumDecls(ast, context); + break; + case 243 /* EnumElement */: + createEnumElementDecls(ast, context); + break; + case 130 /* ModuleDeclaration */: + preCollectModuleDecls(ast, context); + break; + case 131 /* ClassDeclaration */: + preCollectClassDecls(ast, context); + break; + case 128 /* InterfaceDeclaration */: + preCollectInterfaceDecls(ast, context); + break; + case 122 /* ObjectType */: + preCollectObjectTypeDecls(ast, context); + break; + case 242 /* Parameter */: + preCollectParameterDecl(ast, context); + break; + case 136 /* MemberVariableDeclaration */: + createMemberVariableDeclaration(ast, context); + break; + case 141 /* PropertySignature */: + createPropertySignature(ast, context); + break; + case 225 /* VariableDeclarator */: + preCollectVarDecls(ast, context); + break; + case 137 /* ConstructorDeclaration */: + createClassConstructorDeclaration(ast, context); + break; + case 139 /* GetAccessor */: + createGetAccessorDeclaration(ast, context); + break; + case 140 /* SetAccessor */: + createSetAccessorDeclaration(ast, context); + break; + case 222 /* FunctionExpression */: + createFunctionExpressionDeclaration(ast, context); + break; + case 135 /* MemberFunctionDeclaration */: + createMemberFunctionDeclaration(ast, context); + break; + case 144 /* IndexSignature */: + createIndexSignatureDeclaration(ast, context); + break; + case 123 /* FunctionType */: + createFunctionTypeDeclaration(ast, context); + break; + case 125 /* ConstructorType */: + createConstructorTypeDeclaration(ast, context); + break; + case 142 /* CallSignature */: + createCallSignatureDeclaration(ast, context); + break; + case 143 /* ConstructSignature */: + createConstructSignatureDeclaration(ast, context); + break; + case 145 /* MethodSignature */: + createMethodSignatureDeclaration(ast, context); + break; + case 129 /* FunctionDeclaration */: + createFunctionDeclaration(ast, context); + break; + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + createAnyFunctionExpressionDeclaration(ast, null, context); + break; + case 133 /* ImportDeclaration */: + preCollectImportDecls(ast, context); + break; + case 238 /* TypeParameter */: + preCollectTypeParameterDecl(ast, context); + break; + case 236 /* CatchClause */: + preCollectCatchDecls(ast, context); + break; + case 163 /* WithStatement */: + preCollectWithDecls(ast, context); + break; + case 215 /* ObjectLiteralExpression */: + preCollectObjectLiteralDecls(ast, context); + break; + case 240 /* SimplePropertyAssignment */: + preCollectSimplePropertyAssignmentDecls(ast, context); + break; + case 241 /* FunctionPropertyAssignment */: + preCollectFunctionPropertyAssignmentDecls(ast, context); + break; + } + } + + function isContainer(decl) { + return decl.kind === 4 /* Container */ || decl.kind === 32 /* DynamicModule */ || decl.kind === 64 /* Enum */; + } + + function getInitializationFlag(decl) { + if (decl.kind & 4 /* Container */) { + return 32768 /* InitializedModule */; + } else if (decl.kind & 32 /* DynamicModule */) { + return 65536 /* InitializedDynamicModule */; + } + + return 0 /* None */; + } + + function hasInitializationFlag(decl) { + var kind = decl.kind; + + if (kind & 4 /* Container */) { + return (decl.flags & 32768 /* InitializedModule */) !== 0; + } else if (kind & 32 /* DynamicModule */) { + return (decl.flags & 65536 /* InitializedDynamicModule */) !== 0; + } + + return false; + } + + function postCollectDecls(ast, context) { + var currentDecl = context.getParent(); + + if (ast.kind() === 11 /* IdentifierName */ || ast.kind() === 14 /* StringLiteral */) { + if (currentDecl.kind === 4 /* Container */ || currentDecl.kind === 32 /* DynamicModule */) { + return; + } + } + + if (ast.kind() === 130 /* ModuleDeclaration */) { + var moduleDeclaration = ast; + if (moduleDeclaration.stringLiteral) { + TypeScript.Debug.assert(currentDecl.ast() === moduleDeclaration.stringLiteral); + context.popParent(); + } else { + var moduleNames = TypeScript.ASTHelpers.getModuleNames(moduleDeclaration.name); + for (var i = moduleNames.length - 1; i >= 0; i--) { + var moduleName = moduleNames[i]; + TypeScript.Debug.assert(currentDecl.ast() === moduleName); + context.popParent(); + currentDecl = context.getParent(); + } + } + } + + if (ast.kind() === 132 /* EnumDeclaration */) { + computeEnumElementConstantValues(ast, currentDecl, context); + } + + while (currentDecl.getParentDecl() && currentDecl.ast() === ast) { + context.popParent(); + currentDecl = context.getParent(); + } + } + + function computeEnumElementConstantValues(ast, enumDecl, context) { + TypeScript.Debug.assert(enumDecl.kind === 64 /* Enum */); + + var isAmbientEnum = TypeScript.hasFlag(enumDecl.flags, 8 /* Ambient */); + var inConstantSection = !isAmbientEnum; + var currentConstantValue = 0; + var enumMemberDecls = enumDecl.getChildDecls(); + + for (var i = 0, n = ast.enumElements.nonSeparatorCount(); i < n; i++) { + var enumElement = ast.enumElements.nonSeparatorAt(i); + var enumElementDecl = TypeScript.ArrayUtilities.first(enumMemberDecls, function (d) { + return context.semanticInfoChain.getASTForDecl(d) === enumElement; + }); + + TypeScript.Debug.assert(enumElementDecl.kind === 67108864 /* EnumMember */); + + if (enumElement.equalsValueClause === null) { + if (inConstantSection) { + enumElementDecl.constantValue = currentConstantValue; + currentConstantValue++; + } + } else { + enumElementDecl.constantValue = computeEnumElementConstantValue(enumElement.equalsValueClause.value, enumMemberDecls, context); + if (enumElementDecl.constantValue !== null && !isAmbientEnum) { + inConstantSection = true; + currentConstantValue = enumElementDecl.constantValue + 1; + } else { + inConstantSection = false; + } + } + + TypeScript.Debug.assert(enumElementDecl.constantValue !== undefined); + } + } + + function computeEnumElementConstantValue(expression, enumMemberDecls, context) { + TypeScript.Debug.assert(expression); + + if (TypeScript.ASTHelpers.isIntegerLiteralAST(expression)) { + var token; + switch (expression.kind()) { + case 164 /* PlusExpression */: + case 165 /* NegateExpression */: + token = expression.operand; + break; + default: + token = expression; + } + + var value = token.value(); + return value && expression.kind() === 165 /* NegateExpression */ ? -value : value; + } else if (context.propagateEnumConstants) { + switch (expression.kind()) { + case 11 /* IdentifierName */: + var name = expression; + var matchingEnumElement = TypeScript.ArrayUtilities.firstOrDefault(enumMemberDecls, function (d) { + return d.name === name.valueText(); + }); + + return matchingEnumElement ? matchingEnumElement.constantValue : null; + + case 202 /* LeftShiftExpression */: + var binaryExpression = expression; + var left = computeEnumElementConstantValue(binaryExpression.left, enumMemberDecls, context); + var right = computeEnumElementConstantValue(binaryExpression.right, enumMemberDecls, context); + if (left === null || right === null) { + return null; + } + + return left << right; + + case 189 /* BitwiseOrExpression */: + var binaryExpression = expression; + var left = computeEnumElementConstantValue(binaryExpression.left, enumMemberDecls, context); + var right = computeEnumElementConstantValue(binaryExpression.right, enumMemberDecls, context); + if (left === null || right === null) { + return null; + } + + return left | right; + } + + return null; + } else { + return null; + } + } + + (function (DeclarationCreator) { + function create(document, semanticInfoChain, compilationSettings) { + var declCollectionContext = new DeclCollectionContext(document, semanticInfoChain, compilationSettings.propagateEnumConstants()); + + TypeScript.getAstWalkerFactory().simpleWalk(document.sourceUnit(), preCollectDecls, postCollectDecls, declCollectionContext); + + return declCollectionContext.getParent(); + } + DeclarationCreator.create = create; + })(TypeScript.DeclarationCreator || (TypeScript.DeclarationCreator = {})); + var DeclarationCreator = TypeScript.DeclarationCreator; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PullSymbolBinder = (function () { + function PullSymbolBinder(semanticInfoChain) { + this.semanticInfoChain = semanticInfoChain; + this.declsBeingBound = []; + this.inBindingOtherDeclsWalker = new TypeScript.PullHelpers.OtherPullDeclsWalker(); + } + PullSymbolBinder.prototype.getParent = function (decl, returnInstanceType) { + if (typeof returnInstanceType === "undefined") { returnInstanceType = false; } + var parentDecl = decl.getParentDecl(); + + if (parentDecl.kind === 1 /* Script */) { + return null; + } + + var parent = parentDecl.getSymbol(); + + if (!parent && parentDecl && !parentDecl.hasBeenBound()) { + this.bindDeclToPullSymbol(parentDecl); + } + + parent = parentDecl.getSymbol(); + if (parent) { + var parentDeclKind = parentDecl.kind; + if (parentDeclKind === 262144 /* GetAccessor */) { + parent = parent.getGetter(); + } else if (parentDeclKind === 524288 /* SetAccessor */) { + parent = parent.getSetter(); + } + } + + if (parent) { + if (returnInstanceType && parent.isType() && parent.isContainer()) { + var instanceSymbol = parent.getInstanceSymbol(); + + if (instanceSymbol) { + return instanceSymbol.type; + } + } + + return parent.type; + } + + return null; + }; + + PullSymbolBinder.prototype.findDeclsInContext = function (startingDecl, declKind, searchGlobally) { + if (!searchGlobally) { + var parentDecl = startingDecl.getParentDecl(); + return parentDecl.searchChildDecls(startingDecl.name, declKind); + } + + var contextSymbolPath = startingDecl.getParentPath(); + + if (contextSymbolPath.length) { + var copyOfContextSymbolPath = []; + + for (var i = 0; i < contextSymbolPath.length; i++) { + if (contextSymbolPath[i].kind & 1 /* Script */) { + continue; + } + copyOfContextSymbolPath[copyOfContextSymbolPath.length] = contextSymbolPath[i].name; + } + + return this.semanticInfoChain.findDecls(copyOfContextSymbolPath, declKind); + } + }; + + PullSymbolBinder.prototype.getExistingSymbol = function (decl, searchKind, parent) { + var lookingForValue = (searchKind & 68147712 /* SomeValue */) !== 0; + var lookingForType = (searchKind & 58728795 /* SomeType */) !== 0; + var lookingForContainer = (searchKind & 164 /* SomeContainer */) !== 0; + var name = decl.name; + if (parent) { + var isExported = (decl.flags & 1 /* Exported */) !== 0; + + var prevSymbol = null; + if (lookingForValue) { + prevSymbol = parent.findContainedNonMember(name); + } else if (lookingForType) { + prevSymbol = parent.findContainedNonMemberType(name, searchKind); + } else if (lookingForContainer) { + prevSymbol = parent.findContainedNonMemberContainer(name, searchKind); + } + var prevIsExported = !prevSymbol; + if (!prevSymbol) { + if (lookingForValue) { + prevSymbol = parent.findMember(name, false); + } else if (lookingForType) { + prevSymbol = parent.findNestedType(name, searchKind); + } else if (lookingForContainer) { + prevSymbol = parent.findNestedContainer(name, searchKind); + } + } + + if (isExported && prevIsExported) { + return prevSymbol; + } + if (prevSymbol) { + var prevDecls = prevSymbol.getDeclarations(); + var lastPrevDecl = prevDecls[prevDecls.length - 1]; + var parentDecl = decl.getParentDecl(); + var prevParentDecl = lastPrevDecl && lastPrevDecl.getParentDecl(); + if (parentDecl !== prevParentDecl) { + return null; + } + + return prevSymbol; + } + } else { + var parentDecl = decl.getParentDecl(); + if (parentDecl && parentDecl.kind === 1 /* Script */) { + return this.semanticInfoChain.findTopLevelSymbol(name, searchKind, decl); + } else { + var prevDecls = parentDecl && parentDecl.searchChildDecls(name, searchKind); + return prevDecls[0] && prevDecls[0].getSymbol(); + } + } + + return null; + }; + + PullSymbolBinder.prototype.checkThatExportsMatch = function (decl, prevSymbol, reportError) { + if (typeof reportError === "undefined") { reportError = true; } + var isExported = (decl.flags & 1 /* Exported */) !== 0; + var prevDecls = prevSymbol.getDeclarations(); + var prevIsExported = (prevDecls[prevDecls.length - 1].flags & 1 /* Exported */) !== 0; + if ((isExported !== prevIsExported) && !prevSymbol.isSignature() && (decl.kind & 7340032 /* SomeSignature */) === 0) { + if (reportError) { + var ast = this.semanticInfoChain.getASTForDecl(decl); + this.semanticInfoChain.addDiagnosticFromAST(ast, TypeScript.DiagnosticCode.All_declarations_of_merged_declaration_0_must_be_exported_or_not_exported, [decl.getDisplayName()]); + } + return false; + } + + return true; + }; + + PullSymbolBinder.prototype.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList = function (signature, currentSignatures) { + var signatureDecl = signature.getDeclarations()[0]; + TypeScript.Debug.assert(signatureDecl); + var enclosingDecl = signatureDecl.getParentDecl(); + var indexToInsert = TypeScript.ArrayUtilities.indexOf(currentSignatures, function (someSignature) { + return someSignature.getDeclarations()[0].getParentDecl() !== enclosingDecl; + }); + return indexToInsert < 0 ? currentSignatures.length : indexToInsert; + }; + + PullSymbolBinder.prototype.bindEnumDeclarationToPullSymbol = function (enumContainerDecl) { + var enumName = enumContainerDecl.name; + + var enumContainerSymbol = null; + var enumInstanceSymbol = null; + var moduleInstanceTypeSymbol = null; + + var enumInstanceDecl = enumContainerDecl.getValueDecl(); + + var enumDeclKind = enumContainerDecl.kind; + + var parent = this.getParent(enumContainerDecl); + var parentInstanceSymbol = this.getParent(enumContainerDecl, true); + var parentDecl = enumContainerDecl.getParentDecl(); + var enumAST = this.semanticInfoChain.getASTForDecl(enumContainerDecl); + + var isExported = enumContainerDecl.flags & 1 /* Exported */; + + var createdNewSymbol = false; + + enumContainerSymbol = this.getExistingSymbol(enumContainerDecl, 64 /* Enum */, parent); + + if (enumContainerSymbol) { + if (enumContainerSymbol.kind !== enumDeclKind) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(enumAST.identifier, enumContainerDecl.getDisplayName(), enumContainerSymbol.getDeclarations()[0].ast()); + enumContainerSymbol = null; + } else if (!this.checkThatExportsMatch(enumContainerDecl, enumContainerSymbol)) { + enumContainerSymbol = null; + } + } + + if (enumContainerSymbol) { + enumInstanceSymbol = enumContainerSymbol.getInstanceSymbol(); + } else { + enumContainerSymbol = new TypeScript.PullContainerSymbol(enumName, enumDeclKind); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(enumContainerSymbol, 64 /* Enum */); + } + } + + enumContainerSymbol.addDeclaration(enumContainerDecl); + enumContainerDecl.setSymbol(enumContainerSymbol); + + this.semanticInfoChain.setSymbolForAST(enumAST.identifier, enumContainerSymbol); + this.semanticInfoChain.setSymbolForAST(enumAST, enumContainerSymbol); + + if (!enumInstanceSymbol) { + var variableSymbol = null; + if (parentInstanceSymbol) { + if (isExported) { + variableSymbol = parentInstanceSymbol.findMember(enumName, false); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findContainedNonMember(enumName); + } + } else { + variableSymbol = parentInstanceSymbol.findContainedNonMember(enumName); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findMember(enumName, false); + } + } + + if (variableSymbol) { + var declarations = variableSymbol.getDeclarations(); + + if (declarations.length) { + var variableSymbolParentDecl = declarations[0].getParentDecl(); + + if (parentDecl !== variableSymbolParentDecl) { + variableSymbol = null; + } + } + } + } else if (!(enumContainerDecl.flags & 1 /* Exported */)) { + var siblingDecls = parentDecl.getChildDecls(); + var augmentedDecl = null; + + for (var i = 0; i < siblingDecls.length; i++) { + if (siblingDecls[i] === enumContainerDecl) { + break; + } + + if ((siblingDecls[i].name === enumName) && (siblingDecls[i].kind & 68147712 /* SomeValue */)) { + augmentedDecl = siblingDecls[i]; + break; + } + } + + if (augmentedDecl) { + variableSymbol = augmentedDecl.getSymbol(); + + if (variableSymbol) { + if (variableSymbol.isContainer()) { + variableSymbol = variableSymbol.getInstanceSymbol(); + } else if (variableSymbol && variableSymbol.isType()) { + variableSymbol = variableSymbol.getConstructorMethod(); + } + } + } + } + + if (variableSymbol) { + enumInstanceSymbol = variableSymbol; + moduleInstanceTypeSymbol = variableSymbol.type; + } else { + enumInstanceSymbol = new TypeScript.PullSymbol(enumName, 512 /* Variable */); + } + + enumContainerSymbol.setInstanceSymbol(enumInstanceSymbol); + + if (!moduleInstanceTypeSymbol) { + moduleInstanceTypeSymbol = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + enumInstanceSymbol.type = moduleInstanceTypeSymbol; + } + + moduleInstanceTypeSymbol.addDeclaration(enumContainerDecl); + + if (!moduleInstanceTypeSymbol.getAssociatedContainerType()) { + moduleInstanceTypeSymbol.setAssociatedContainerType(enumContainerSymbol); + } + } + + if (createdNewSymbol && parent) { + if (enumContainerDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberType(enumContainerSymbol); + } else { + parent.addEnclosedNonMemberType(enumContainerSymbol); + } + } + + if (createdNewSymbol) { + this.bindEnumIndexerDeclsToPullSymbols(enumContainerSymbol); + } + var valueDecl = enumContainerDecl.getValueDecl(); + + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + }; + + PullSymbolBinder.prototype.bindEnumIndexerDeclsToPullSymbols = function (enumContainerSymbol) { + var enumContainerInstanceTypeSymbol = enumContainerSymbol.getInstanceSymbol().type; + + var syntheticIndexerParameterSymbol = new TypeScript.PullSymbol("x", 2048 /* Parameter */); + syntheticIndexerParameterSymbol.type = this.semanticInfoChain.numberTypeSymbol; + syntheticIndexerParameterSymbol.setResolved(); + syntheticIndexerParameterSymbol.setIsSynthesized(); + + var syntheticIndexerSignatureSymbol = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + syntheticIndexerSignatureSymbol.addParameter(syntheticIndexerParameterSymbol); + syntheticIndexerSignatureSymbol.returnType = this.semanticInfoChain.stringTypeSymbol; + syntheticIndexerSignatureSymbol.setResolved(); + syntheticIndexerSignatureSymbol.setIsSynthesized(); + + enumContainerInstanceTypeSymbol.addIndexSignature(syntheticIndexerSignatureSymbol); + }; + + PullSymbolBinder.prototype.findExistingVariableSymbolForModuleValueDecl = function (decl) { + var isExported = TypeScript.hasFlag(decl.flags, 1 /* Exported */); + var modName = decl.name; + var parentInstanceSymbol = this.getParent(decl, true); + var parentDecl = decl.getParentDecl(); + + var variableSymbol = null; + + if (parentInstanceSymbol) { + if (isExported) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); + } + } else { + variableSymbol = parentInstanceSymbol.findContainedNonMember(modName); + + if (!variableSymbol) { + variableSymbol = parentInstanceSymbol.findMember(modName, false); + } + } + + if (variableSymbol) { + var declarations = variableSymbol.getDeclarations(); + + if (declarations.length) { + var variableSymbolParentDecl = declarations[0].getParentDecl(); + var isExportedOrHasTheSameParent = isExported || (parentDecl === variableSymbolParentDecl); + + var canReuseVariableSymbol = isExportedOrHasTheSameParent && this.checkThatExportsMatch(decl, variableSymbol, false); + + if (!canReuseVariableSymbol) { + variableSymbol = null; + } + } + } + } else if (!isExported) { + var siblingDecls = parentDecl.getChildDecls(); + + for (var i = 0; i < siblingDecls.length; i++) { + var sibling = siblingDecls[i]; + + var siblingIsSomeValue = TypeScript.hasFlag(sibling.kind, 68147712 /* SomeValue */); + var siblingIsFunctionOrHasImplictVarFlag = TypeScript.hasFlag(sibling.kind, 1032192 /* SomeFunction */) || TypeScript.hasFlag(sibling.flags, 118784 /* ImplicitVariable */); + + var isSiblingAnAugmentableVariable = sibling !== decl && sibling !== decl.getValueDecl() && sibling.name === modName && siblingIsSomeValue && siblingIsFunctionOrHasImplictVarFlag; + + if (isSiblingAnAugmentableVariable) { + if (sibling.hasSymbol()) { + variableSymbol = sibling.getSymbol(); + if (variableSymbol.isContainer()) { + variableSymbol = variableSymbol.getInstanceSymbol(); + } else if (variableSymbol && variableSymbol.isType()) { + variableSymbol = variableSymbol.getConstructorMethod(); + } + + break; + } + } + } + } + return variableSymbol; + }; + + PullSymbolBinder.prototype.bindModuleDeclarationToPullSymbol = function (moduleContainerDecl) { + var modName = moduleContainerDecl.name; + + var moduleContainerTypeSymbol = null; + var moduleKind = moduleContainerDecl.kind; + + var parent = this.getParent(moduleContainerDecl); + var parentInstanceSymbol = this.getParent(moduleContainerDecl, true); + var parentDecl = moduleContainerDecl.getParentDecl(); + var moduleNameAST = this.semanticInfoChain.getASTForDecl(moduleContainerDecl); + var moduleDeclAST = TypeScript.ASTHelpers.getEnclosingModuleDeclaration(moduleNameAST); + if (!moduleDeclAST) { + TypeScript.Debug.assert(moduleKind === 32 /* DynamicModule */); + TypeScript.Debug.assert(moduleNameAST.kind() === 120 /* SourceUnit */); + + moduleDeclAST = moduleNameAST; + } + + var isExported = TypeScript.hasFlag(moduleContainerDecl.flags, 1 /* Exported */); + var searchKind = 164 /* SomeContainer */; + var isInitializedModule = (moduleContainerDecl.flags & 102400 /* SomeInitializedModule */) !== 0; + + if (parent && moduleKind === 32 /* DynamicModule */) { + this.semanticInfoChain.addDiagnosticFromAST(moduleNameAST, TypeScript.DiagnosticCode.Ambient_external_module_declaration_must_be_defined_in_global_context, null); + } + + var createdNewSymbol = false; + + moduleContainerTypeSymbol = this.getExistingSymbol(moduleContainerDecl, searchKind, parent); + + if (moduleContainerTypeSymbol) { + if (moduleContainerTypeSymbol.kind !== moduleKind) { + if (isInitializedModule) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(moduleNameAST, moduleContainerDecl.getDisplayName(), moduleContainerTypeSymbol.getDeclarations()[0].ast()); + } + + moduleContainerTypeSymbol = null; + } else if (moduleKind === 32 /* DynamicModule */) { + this.semanticInfoChain.addDiagnosticFromAST(moduleNameAST, TypeScript.DiagnosticCode.Ambient_external_module_declaration_cannot_be_reopened); + } else if (!this.checkThatExportsMatch(moduleContainerDecl, moduleContainerTypeSymbol)) { + moduleContainerTypeSymbol = null; + } + } + + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = new TypeScript.PullContainerSymbol(modName, moduleKind); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(moduleContainerTypeSymbol, searchKind); + } + } + + moduleContainerTypeSymbol.addDeclaration(moduleContainerDecl); + moduleContainerDecl.setSymbol(moduleContainerTypeSymbol); + + this.semanticInfoChain.setSymbolForAST(moduleNameAST, moduleContainerTypeSymbol); + this.semanticInfoChain.setSymbolForAST(moduleDeclAST, moduleContainerTypeSymbol); + + var currentModuleValueDecl = moduleContainerDecl.getValueDecl(); + + var moduleDeclarations = moduleContainerTypeSymbol.getDeclarations(); + + if (createdNewSymbol) { + if (parent) { + if (moduleContainerDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberContainer(moduleContainerTypeSymbol); + } else { + parent.addEnclosedNonMemberContainer(moduleContainerTypeSymbol); + } + } + } + + if (currentModuleValueDecl) { + currentModuleValueDecl.ensureSymbolIsBound(); + + var instanceSymbol = null; + var instanceTypeSymbol = null; + if (currentModuleValueDecl.hasSymbol()) { + instanceSymbol = currentModuleValueDecl.getSymbol(); + } else { + instanceSymbol = new TypeScript.PullSymbol(modName, 512 /* Variable */); + currentModuleValueDecl.setSymbol(instanceSymbol); + if (!instanceSymbol.hasDeclaration(currentModuleValueDecl)) { + instanceSymbol.addDeclaration(currentModuleValueDecl); + } + } + + if (!instanceSymbol.type) { + instanceSymbol.type = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + } + + moduleContainerTypeSymbol.setInstanceSymbol(instanceSymbol); + + if (!instanceSymbol.type.getAssociatedContainerType()) { + instanceSymbol.type.setAssociatedContainerType(moduleContainerTypeSymbol); + } + } + }; + + PullSymbolBinder.prototype.bindImportDeclaration = function (importDeclaration) { + var declFlags = importDeclaration.flags; + var declKind = importDeclaration.kind; + var importDeclAST = this.semanticInfoChain.getASTForDecl(importDeclaration); + + var isExported = false; + var importSymbol = null; + var declName = importDeclaration.name; + var parentHadSymbol = false; + var parent = this.getParent(importDeclaration); + + importSymbol = this.getExistingSymbol(importDeclaration, 164 /* SomeContainer */, parent); + + if (importSymbol) { + parentHadSymbol = true; + } + + if (importSymbol) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(importDeclAST, importDeclaration.getDisplayName(), importSymbol.getDeclarations()[0].ast()); + importSymbol = null; + } + + if (!importSymbol) { + importSymbol = new TypeScript.PullTypeAliasSymbol(declName); + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(importSymbol, 164 /* SomeContainer */); + } + } + + importSymbol.addDeclaration(importDeclaration); + importDeclaration.setSymbol(importSymbol); + + this.semanticInfoChain.setSymbolForAST(importDeclAST, importSymbol); + + if (parent && !parentHadSymbol) { + if (declFlags & 1 /* Exported */) { + parent.addEnclosedMemberContainer(importSymbol); + } else { + parent.addEnclosedNonMemberContainer(importSymbol); + } + } + }; + + PullSymbolBinder.prototype.ensurePriorDeclarationsAreBound = function (container, currentDecl) { + if (!container) { + return; + } + + var parentDecls = container.getDeclarations(); + for (var i = 0; i < parentDecls.length; ++i) { + var parentDecl = parentDecls[i]; + var childDecls = parentDecl.getChildDecls(); + for (var j = 0; j < childDecls.length; ++j) { + var childDecl = childDecls[j]; + if (childDecl === currentDecl) { + return; + } + + if (childDecl.name === currentDecl.name) { + childDecl.ensureSymbolIsBound(); + } + } + } + }; + + PullSymbolBinder.prototype.bindClassDeclarationToPullSymbol = function (classDecl) { + var className = classDecl.name; + var classSymbol = null; + + var constructorSymbol = null; + var constructorTypeSymbol = null; + + var classAST = this.semanticInfoChain.getASTForDecl(classDecl); + + var parent = this.getParent(classDecl); + + this.ensurePriorDeclarationsAreBound(parent, classDecl); + + var parentDecl = classDecl.getParentDecl(); + var isExported = classDecl.flags & 1 /* Exported */; + var isGeneric = false; + + classSymbol = this.getExistingSymbol(classDecl, 58728795 /* SomeType */, parent); + + if (classSymbol && classSymbol.kind === 16 /* Interface */) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(classAST.identifier, classDecl.getDisplayName(), classSymbol.getDeclarations()[0].ast()); + classSymbol = null; + } + + classSymbol = new TypeScript.PullTypeSymbol(className, 8 /* Class */); + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(classSymbol, 8 /* Class */); + } + + classSymbol.addDeclaration(classDecl); + + classDecl.setSymbol(classSymbol); + + this.semanticInfoChain.setSymbolForAST(classAST.identifier, classSymbol); + this.semanticInfoChain.setSymbolForAST(classAST, classSymbol); + + if (parent) { + if (classDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberType(classSymbol); + } else { + parent.addEnclosedNonMemberType(classSymbol); + } + } + + var typeParameterDecls = classDecl.getTypeParameters(); + + for (var i = 0; i < typeParameterDecls.length; i++) { + var typeParameterSymbol = classSymbol.findTypeParameter(typeParameterDecls[i].name); + + if (typeParameterSymbol) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterSymbol.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameterSymbol.getName()]); + } + + typeParameterSymbol = new TypeScript.PullTypeParameterSymbol(typeParameterDecls[i].name); + + classSymbol.addTypeParameter(typeParameterSymbol); + typeParameterSymbol.addDeclaration(typeParameterDecls[i]); + typeParameterDecls[i].setSymbol(typeParameterSymbol); + } + + constructorSymbol = classSymbol.getConstructorMethod(); + constructorTypeSymbol = constructorSymbol ? constructorSymbol.type : null; + + if (!constructorSymbol) { + var siblingValueDecls = null; + if (parentDecl) { + siblingValueDecls = parentDecl.searchChildDecls(className, 68147712 /* SomeValue */); + + if (siblingValueDecls && siblingValueDecls[0] && siblingValueDecls[0].hasSymbol()) { + constructorSymbol = siblingValueDecls[0].getSymbol(); + } + } + + if (constructorSymbol) { + constructorTypeSymbol = constructorSymbol.type; + } else { + constructorSymbol = new TypeScript.PullSymbol(className, 32768 /* ConstructorMethod */); + constructorTypeSymbol = new TypeScript.PullTypeSymbol("", 33554432 /* ConstructorType */); + constructorSymbol.setIsSynthesized(); + constructorSymbol.type = constructorTypeSymbol; + } + + classSymbol.setConstructorMethod(constructorSymbol); + classSymbol.setHasDefaultConstructor(); + } + + if (constructorSymbol.getIsSynthesized()) { + constructorSymbol.addDeclaration(classDecl.getValueDecl()); + constructorTypeSymbol.addDeclaration(classDecl); + } else { + classSymbol.setHasDefaultConstructor(false); + } + + constructorTypeSymbol.setAssociatedContainerType(classSymbol); + + var valueDecl = classDecl.getValueDecl(); + + if (valueDecl) { + valueDecl.ensureSymbolIsBound(); + } + + this.bindStaticPrototypePropertyOfClass(classAST, classSymbol, constructorTypeSymbol); + }; + + PullSymbolBinder.prototype.bindInterfaceDeclarationToPullSymbol = function (interfaceDecl) { + var interfaceName = interfaceDecl.name; + var interfaceSymbol = null; + + var interfaceAST = this.semanticInfoChain.getASTForDecl(interfaceDecl); + var createdNewSymbol = false; + var parent = this.getParent(interfaceDecl); + + var acceptableSharedKind = 16 /* Interface */; + + interfaceSymbol = this.getExistingSymbol(interfaceDecl, 58728795 /* SomeType */, parent); + + if (interfaceSymbol) { + if (!(interfaceSymbol.kind & acceptableSharedKind)) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(interfaceAST.identifier, interfaceDecl.getDisplayName(), interfaceSymbol.getDeclarations()[0].ast()); + interfaceSymbol = null; + } else if (!this.checkThatExportsMatch(interfaceDecl, interfaceSymbol)) { + interfaceSymbol = null; + } + } + + if (!interfaceSymbol) { + interfaceSymbol = new TypeScript.PullTypeSymbol(interfaceName, 16 /* Interface */); + createdNewSymbol = true; + + if (!parent) { + this.semanticInfoChain.cacheGlobalSymbol(interfaceSymbol, acceptableSharedKind); + } + } + + interfaceSymbol.addDeclaration(interfaceDecl); + interfaceDecl.setSymbol(interfaceSymbol); + + if (createdNewSymbol) { + if (parent) { + if (interfaceDecl.flags & 1 /* Exported */) { + parent.addEnclosedMemberType(interfaceSymbol); + } else { + parent.addEnclosedNonMemberType(interfaceSymbol); + } + } + } + + var typeParameters = interfaceDecl.getTypeParameters(); + var typeParameter; + var typeParameterDecls = null; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = interfaceSymbol.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + interfaceSymbol.addTypeParameter(typeParameter); + } else { + typeParameterDecls = typeParameter.getDeclarations(); + + for (var j = 0; j < typeParameterDecls.length; j++) { + var typeParameterDeclParent = typeParameterDecls[j].getParentDecl(); + + if (typeParameterDeclParent && typeParameterDeclParent === interfaceDecl) { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameterDecls[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + + break; + } + } + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + }; + + PullSymbolBinder.prototype.bindObjectTypeDeclarationToPullSymbol = function (objectDecl) { + var objectSymbolAST = this.semanticInfoChain.getASTForDecl(objectDecl); + + var objectSymbol = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + + objectSymbol.addDeclaration(objectDecl); + objectDecl.setSymbol(objectSymbol); + + this.semanticInfoChain.setSymbolForAST(objectSymbolAST, objectSymbol); + + var childDecls = objectDecl.getChildDecls(); + + for (var i = 0; i < childDecls.length; i++) { + this.bindDeclToPullSymbol(childDecls[i]); + } + }; + + PullSymbolBinder.prototype.bindConstructorTypeDeclarationToPullSymbol = function (constructorTypeDeclaration) { + var declKind = constructorTypeDeclaration.kind; + var declFlags = constructorTypeDeclaration.flags; + var constructorTypeAST = this.semanticInfoChain.getASTForDecl(constructorTypeDeclaration); + + var constructorTypeSymbol = new TypeScript.PullTypeSymbol("", 33554432 /* ConstructorType */); + + constructorTypeDeclaration.setSymbol(constructorTypeSymbol); + constructorTypeSymbol.addDeclaration(constructorTypeDeclaration); + this.semanticInfoChain.setSymbolForAST(constructorTypeAST, constructorTypeSymbol); + + var signature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + + var funcDecl = this.semanticInfoChain.getASTForDecl(constructorTypeDeclaration); + if (TypeScript.lastParameterIsRest(funcDecl.parameterList)) { + signature.hasVarArgs = true; + } + + signature.addDeclaration(constructorTypeDeclaration); + constructorTypeDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList), constructorTypeSymbol, signature); + + var typeParameters = constructorTypeDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = constructorTypeSymbol.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.name]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + constructorTypeSymbol.appendConstructSignature(signature); + }; + + PullSymbolBinder.prototype.bindVariableDeclarationToPullSymbol = function (variableDeclaration) { + var declFlags = variableDeclaration.flags; + var declKind = variableDeclaration.kind; + var varDeclAST = this.semanticInfoChain.getASTForDecl(variableDeclaration); + var nameAST = varDeclAST.kind() === 131 /* ClassDeclaration */ ? varDeclAST.identifier : varDeclAST.kind() === 225 /* VariableDeclarator */ ? varDeclAST.propertyName : varDeclAST.kind() === 132 /* EnumDeclaration */ ? varDeclAST.identifier : varDeclAST; + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var variableSymbol = null; + + var declName = variableDeclaration.name; + + var parentHadSymbol = false; + + var parent = this.getParent(variableDeclaration, true); + + var parentDecl = variableDeclaration.getParentDecl(); + + var isImplicit = (declFlags & 118784 /* ImplicitVariable */) !== 0; + var isModuleValue = (declFlags & (32768 /* InitializedModule */)) !== 0; + var isEnumValue = (declFlags & 4096 /* Enum */) !== 0; + var isClassConstructorVariable = (declFlags & 16384 /* ClassConstructorVariable */) !== 0; + variableSymbol = this.getExistingSymbol(variableDeclaration, 68147712 /* SomeValue */, parent); + + if (!variableSymbol && isModuleValue) { + variableSymbol = this.findExistingVariableSymbolForModuleValueDecl(variableDeclaration.getContainerDecl()); + } + + if (variableSymbol && !variableSymbol.isType()) { + parentHadSymbol = true; + } + + var decl; + var decls; + var ast; + var members; + + if (variableSymbol) { + var prevKind = variableSymbol.kind; + var prevIsEnum = variableSymbol.anyDeclHasFlag(4096 /* Enum */); + var prevIsClassConstructorVariable = variableSymbol.anyDeclHasFlag(16384 /* ClassConstructorVariable */); + var prevIsModuleValue = variableSymbol.allDeclsHaveFlag(32768 /* InitializedModule */); + var prevIsImplicit = variableSymbol.anyDeclHasFlag(118784 /* ImplicitVariable */); + var prevIsFunction = TypeScript.ArrayUtilities.any(variableSymbol.getDeclarations(), function (decl) { + return decl.kind === 16384 /* Function */; + }); + var prevIsAmbient = variableSymbol.allDeclsHaveFlag(8 /* Ambient */); + var isAmbientOrPrevIsAmbient = prevIsAmbient || (variableDeclaration.flags & 8 /* Ambient */) !== 0; + var prevDecl = variableSymbol.getDeclarations()[0]; + var prevParentDecl = prevDecl.getParentDecl(); + var bothAreGlobal = parentDecl && (parentDecl.kind === 1 /* Script */) && (prevParentDecl.kind === 1 /* Script */); + var shareParent = bothAreGlobal || prevDecl.getParentDecl() === variableDeclaration.getParentDecl(); + var prevIsParam = shareParent && prevKind === 2048 /* Parameter */ && declKind == 512 /* Variable */; + + var acceptableRedeclaration = prevIsParam || (isImplicit && ((!isEnumValue && !isClassConstructorVariable && prevIsFunction) || ((isModuleValue || isEnumValue) && (prevIsModuleValue || prevIsEnum)) || (isClassConstructorVariable && prevIsModuleValue && isAmbientOrPrevIsAmbient) || (isModuleValue && prevIsClassConstructorVariable))); + + if (acceptableRedeclaration && (prevIsClassConstructorVariable || prevIsFunction) && !isAmbientOrPrevIsAmbient) { + if (prevDecl.fileName() !== variableDeclaration.fileName()) { + this.semanticInfoChain.addDiagnostic(TypeScript.PullHelpers.diagnosticFromDecl(variableDeclaration, TypeScript.DiagnosticCode.Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2, [declName, declName, prevDecl.fileName()])); + variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); + } + } + + if (!acceptableRedeclaration || prevIsParam) { + if (!prevIsParam && (isImplicit || prevIsImplicit || TypeScript.hasFlag(prevKind, 1032192 /* SomeFunction */)) || !shareParent) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(nameAST, variableDeclaration.getDisplayName(), variableSymbol.getDeclarations()[0].ast()); + variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); + } else { + this.checkThatExportsMatch(variableDeclaration, variableSymbol); + variableSymbol = null; + parentHadSymbol = false; + } + } + + if (variableSymbol && !(variableSymbol.type && variableSymbol.type.isError()) && !this.checkThatExportsMatch(variableDeclaration, variableSymbol, !(isModuleValue && prevIsModuleValue))) { + variableSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(declName); + } + } + + if ((declFlags & 118784 /* ImplicitVariable */) === 0) { + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + if (!parent && parentDecl.kind === 1 /* Script */) { + this.semanticInfoChain.cacheGlobalSymbol(variableSymbol, declKind); + } + } + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + this.semanticInfoChain.setSymbolForAST(nameAST, variableSymbol); + this.semanticInfoChain.setSymbolForAST(varDeclAST, variableSymbol); + } else if (!parentHadSymbol) { + if (isClassConstructorVariable) { + var classTypeSymbol = variableSymbol; + + if (parent) { + members = parent.getMembers(); + + for (var i = 0; i < members.length; i++) { + if ((members[i].name === declName) && (members[i].kind === 8 /* Class */)) { + classTypeSymbol = members[i]; + break; + } + } + } + + if (!classTypeSymbol) { + var containerDecl = variableDeclaration.getContainerDecl(); + classTypeSymbol = containerDecl.getSymbol(); + if (!classTypeSymbol) { + classTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 58728795 /* SomeType */, variableDeclaration); + } + } + + if (classTypeSymbol && (classTypeSymbol.kind !== 8 /* Class */)) { + classTypeSymbol = null; + } + + if (classTypeSymbol && classTypeSymbol.isClass()) { + variableSymbol = classTypeSymbol.getConstructorMethod(); + variableDeclaration.setSymbol(variableSymbol); + + decls = classTypeSymbol.getDeclarations(); + + if (decls.length) { + decl = decls[decls.length - 1]; + ast = this.semanticInfoChain.getASTForDecl(decl); + } + } else { + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + } + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + variableSymbol.type = this.semanticInfoChain.anyTypeSymbol; + } + } else if (declFlags & 102400 /* SomeInitializedModule */) { + var moduleContainerTypeSymbol = null; + var moduleParent = this.getParent(variableDeclaration); + + if (moduleParent) { + members = moduleParent.getMembers(); + + for (var i = 0; i < members.length; i++) { + if ((members[i].name === declName) && (members[i].isContainer())) { + moduleContainerTypeSymbol = members[i]; + break; + } + } + } + + if (!moduleContainerTypeSymbol) { + var containerDecl = variableDeclaration.getContainerDecl(); + moduleContainerTypeSymbol = containerDecl.getSymbol(); + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 164 /* SomeContainer */, variableDeclaration); + + if (!moduleContainerTypeSymbol) { + moduleContainerTypeSymbol = this.semanticInfoChain.findTopLevelSymbol(declName, 64 /* Enum */, variableDeclaration); + } + } + } + + if (moduleContainerTypeSymbol && (!moduleContainerTypeSymbol.isContainer())) { + moduleContainerTypeSymbol = null; + } + + if (moduleContainerTypeSymbol) { + variableSymbol = moduleContainerTypeSymbol.getInstanceSymbol(); + if (!variableSymbol) { + variableSymbol = new TypeScript.PullSymbol(declName, declKind); + variableSymbol.type = new TypeScript.PullTypeSymbol("", 8388608 /* ObjectType */); + } + + if (!variableSymbol.hasDeclaration(variableDeclaration)) { + variableSymbol.addDeclaration(variableDeclaration); + } + variableDeclaration.setSymbol(variableSymbol); + } else { + TypeScript.Debug.assert(false, "Attempted to bind invalid implicit variable symbol"); + } + } + } else { + if (!variableSymbol.hasDeclaration(variableDeclaration)) { + variableSymbol.addDeclaration(variableDeclaration); + } + variableDeclaration.setSymbol(variableSymbol); + } + + var containerDecl = variableDeclaration.getContainerDecl(); + if (variableSymbol && variableSymbol.type && containerDecl && !variableSymbol.type.hasDeclaration(containerDecl)) { + variableSymbol.type.addDeclaration(containerDecl); + } + + if (parent && !parentHadSymbol) { + if (declFlags & 1 /* Exported */) { + parent.addMember(variableSymbol); + } else { + parent.addEnclosedNonMember(variableSymbol); + } + } + }; + + PullSymbolBinder.prototype.bindCatchVariableToPullSymbol = function (variableDeclaration) { + var declFlags = variableDeclaration.flags; + var declKind = variableDeclaration.kind; + var identifier = this.semanticInfoChain.getASTForDecl(variableDeclaration); + + var declName = variableDeclaration.name; + + var variableSymbol = new TypeScript.PullSymbol(declName, declKind); + + variableSymbol.addDeclaration(variableDeclaration); + variableDeclaration.setSymbol(variableSymbol); + + variableSymbol.type = this.semanticInfoChain.anyTypeSymbol; + + this.semanticInfoChain.setSymbolForAST(identifier, variableSymbol); + }; + + PullSymbolBinder.prototype.bindEnumMemberDeclarationToPullSymbol = function (propertyDeclaration) { + var declFlags = propertyDeclaration.flags; + var declKind = propertyDeclaration.kind; + var propDeclAST = this.semanticInfoChain.getASTForDecl(propertyDeclaration); + + var declName = propertyDeclaration.name; + + var parentHadSymbol = false; + + var parent = this.getParent(propertyDeclaration, true); + + var propertySymbol = parent.findMember(declName, false); + + if (propertySymbol) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(propDeclAST.propertyName, propertyDeclaration.getDisplayName(), propertySymbol.getDeclarations()[0].ast()); + } + + if (propertySymbol) { + parentHadSymbol = true; + } + + if (!parentHadSymbol) { + propertySymbol = new TypeScript.PullSymbol(declName, declKind); + } + + propertySymbol.addDeclaration(propertyDeclaration); + propertyDeclaration.setSymbol(propertySymbol); + + this.semanticInfoChain.setSymbolForAST(propDeclAST.propertyName, propertySymbol); + this.semanticInfoChain.setSymbolForAST(propDeclAST, propertySymbol); + + if (parent && !parentHadSymbol) { + parent.addMember(propertySymbol); + } + }; + + PullSymbolBinder.prototype.bindPropertyDeclarationToPullSymbol = function (propertyDeclaration) { + var declFlags = propertyDeclaration.flags; + var declKind = propertyDeclaration.kind; + + var ast = this.semanticInfoChain.getASTForDecl(propertyDeclaration); + var astName = ast.kind() === 136 /* MemberVariableDeclaration */ ? ast.variableDeclarator.propertyName : ast.kind() === 141 /* PropertySignature */ ? ast.propertyName : ast.kind() === 242 /* Parameter */ ? ast.identifier : ast.propertyName; + + var isStatic = false; + var isOptional = false; + + var propertySymbol = null; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + if (TypeScript.hasFlag(declFlags, 128 /* Optional */)) { + isOptional = true; + } + + var declName = propertyDeclaration.name; + + var parentHadSymbol = false; + + var parent = this.getParent(propertyDeclaration, true); + + if (parent.isClass() && isStatic) { + parent = parent.getConstructorMethod().type; + } + + propertySymbol = parent.findMember(declName, false); + + if (propertySymbol) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(astName, propertyDeclaration.getDisplayName(), propertySymbol.getDeclarations()[0].ast()); + } + + if (propertySymbol) { + parentHadSymbol = true; + } + + var classTypeSymbol; + + if (!parentHadSymbol) { + propertySymbol = new TypeScript.PullSymbol(declName, declKind); + } + + propertySymbol.addDeclaration(propertyDeclaration); + propertyDeclaration.setSymbol(propertySymbol); + + this.semanticInfoChain.setSymbolForAST(astName, propertySymbol); + this.semanticInfoChain.setSymbolForAST(ast, propertySymbol); + + if (isOptional) { + propertySymbol.isOptional = true; + } + + if (parent && !parentHadSymbol) { + parent.addMember(propertySymbol); + } + }; + + PullSymbolBinder.prototype.bindParameterSymbols = function (functionDeclaration, parameterList, funcType, signatureSymbol) { + var parameters = []; + var params = TypeScript.createIntrinsicsObject(); + var funcDecl = this.semanticInfoChain.getDeclForAST(functionDeclaration); + + if (parameterList) { + for (var i = 0, n = parameterList.length; i < n; i++) { + var argDecl = parameterList.astAt(i); + var id = parameterList.identifierAt(i); + var decl = this.semanticInfoChain.getDeclForAST(argDecl); + var isProperty = TypeScript.hasFlag(decl.flags, 8388608 /* PropertyParameter */); + var parameterSymbol = new TypeScript.PullSymbol(id.valueText(), 2048 /* Parameter */); + + if ((i === (n - 1)) && parameterList.lastParameterIsRest()) { + parameterSymbol.isVarArg = true; + } + + if (params[id.valueText()]) { + this.semanticInfoChain.addDiagnosticFromAST(argDecl, TypeScript.DiagnosticCode.Duplicate_identifier_0, [id.text()]); + } else { + params[id.valueText()] = true; + } + + if (decl) { + var isParameterOptional = false; + + if (isProperty) { + decl.ensureSymbolIsBound(); + var valDecl = decl.getValueDecl(); + + if (valDecl) { + isParameterOptional = TypeScript.hasFlag(valDecl.flags, 128 /* Optional */); + + valDecl.setSymbol(parameterSymbol); + parameterSymbol.addDeclaration(valDecl); + } + } else { + isParameterOptional = TypeScript.hasFlag(decl.flags, 128 /* Optional */); + + parameterSymbol.addDeclaration(decl); + decl.setSymbol(parameterSymbol); + } + + parameterSymbol.isOptional = isParameterOptional; + } + + signatureSymbol.addParameter(parameterSymbol, parameterSymbol.isOptional); + + if (signatureSymbol.isDefinition()) { + funcType.addEnclosedNonMember(parameterSymbol); + } + } + } + }; + + PullSymbolBinder.prototype.bindFunctionDeclarationToPullSymbol = function (functionDeclaration) { + var declKind = functionDeclaration.kind; + var declFlags = functionDeclaration.flags; + var funcDeclAST = this.semanticInfoChain.getASTForDecl(functionDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = functionDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(functionDeclaration, true); + + var parentDecl = functionDeclaration.getParentDecl(); + var parentHadSymbol = false; + + var functionSymbol = null; + var functionTypeSymbol = null; + + functionSymbol = this.getExistingSymbol(functionDeclaration, 68147712 /* SomeValue */, parent); + + if (functionSymbol) { + var acceptableRedeclaration; + + if (functionSymbol.kind === 16384 /* Function */) { + acceptableRedeclaration = isSignature || functionSymbol.allDeclsHaveFlag(2048 /* Signature */); + } else { + var isCurrentDeclAmbient = TypeScript.hasFlag(functionDeclaration.flags, 8 /* Ambient */); + acceptableRedeclaration = TypeScript.ArrayUtilities.all(functionSymbol.getDeclarations(), function (decl) { + var isInitializedModuleOrAmbientDecl = TypeScript.hasFlag(decl.flags, 32768 /* InitializedModule */) && (isCurrentDeclAmbient || TypeScript.hasFlag(decl.flags, 8 /* Ambient */)); + var isSignature = TypeScript.hasFlag(decl.flags, 2048 /* Signature */); + return isInitializedModuleOrAmbientDecl || isSignature; + }); + } + + if (!acceptableRedeclaration) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.identifier, functionDeclaration.getDisplayName(), functionSymbol.getDeclarations()[0].ast()); + functionSymbol.type = this.semanticInfoChain.getResolver().getNewErrorTypeSymbol(funcName); + } + } + + if (functionSymbol) { + functionTypeSymbol = functionSymbol.type; + parentHadSymbol = true; + } + + if (!functionSymbol) { + functionSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + } + + if (!functionTypeSymbol) { + functionTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + functionSymbol.type = functionTypeSymbol; + functionTypeSymbol.setFunctionSymbol(functionSymbol); + } + + functionDeclaration.setSymbol(functionSymbol); + functionSymbol.addDeclaration(functionDeclaration); + functionTypeSymbol.addDeclaration(functionDeclaration); + + this.semanticInfoChain.setSymbolForAST(funcDeclAST.identifier, functionSymbol); + this.semanticInfoChain.setSymbolForAST(funcDeclAST, functionSymbol); + + if (parent && !parentHadSymbol) { + if (isExported) { + parent.addMember(functionSymbol); + } else { + parent.addEnclosedNonMember(functionSymbol); + } + } + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + signature.addDeclaration(functionDeclaration); + functionDeclaration.setSignatureSymbol(signature); + + if (TypeScript.lastParameterIsRest(funcDeclAST.callSignature.parameterList)) { + signature.hasVarArgs = true; + } + + var funcDecl = this.semanticInfoChain.getASTForDecl(functionDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.callSignature.parameterList), functionTypeSymbol, signature); + + var typeParameters = functionDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.name]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + functionTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindFunctionExpressionToPullSymbol = function (functionExpressionDeclaration) { + var declKind = functionExpressionDeclaration.kind; + var declFlags = functionExpressionDeclaration.flags; + var ast = this.semanticInfoChain.getASTForDecl(functionExpressionDeclaration); + + var parameters = ast.kind() === 219 /* SimpleArrowFunctionExpression */ ? TypeScript.ASTHelpers.parametersFromIdentifier(ast.identifier) : TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(ast)); + var funcExpAST = ast; + + var functionName = declKind === 131072 /* FunctionExpression */ ? functionExpressionDeclaration.getFunctionExpressionName() : functionExpressionDeclaration.name; + var functionSymbol = new TypeScript.PullSymbol(functionName, declKind); + var functionTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + functionTypeSymbol.setFunctionSymbol(functionSymbol); + + functionSymbol.type = functionTypeSymbol; + + functionExpressionDeclaration.setSymbol(functionSymbol); + functionSymbol.addDeclaration(functionExpressionDeclaration); + functionTypeSymbol.addDeclaration(functionExpressionDeclaration); + + var name = funcExpAST.kind() === 222 /* FunctionExpression */ ? funcExpAST.identifier : funcExpAST.kind() === 241 /* FunctionPropertyAssignment */ ? funcExpAST.propertyName : null; + if (name) { + this.semanticInfoChain.setSymbolForAST(name, functionSymbol); + } + + this.semanticInfoChain.setSymbolForAST(funcExpAST, functionSymbol); + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, true); + + if (parameters.lastParameterIsRest()) { + signature.hasVarArgs = true; + } + + var typeParameters = functionExpressionDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(functionExpressionDeclaration); + functionExpressionDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcExpAST, parameters, functionTypeSymbol, signature); + + functionTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindFunctionTypeDeclarationToPullSymbol = function (functionTypeDeclaration) { + var declKind = functionTypeDeclaration.kind; + var declFlags = functionTypeDeclaration.flags; + var funcTypeAST = this.semanticInfoChain.getASTForDecl(functionTypeDeclaration); + + var functionTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + + functionTypeDeclaration.setSymbol(functionTypeSymbol); + functionTypeSymbol.addDeclaration(functionTypeDeclaration); + this.semanticInfoChain.setSymbolForAST(funcTypeAST, functionTypeSymbol); + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + if (TypeScript.lastParameterIsRest(funcTypeAST.parameterList)) { + signature.hasVarArgs = true; + } + + var typeParameters = functionTypeDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = signature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + signature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.name]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(functionTypeDeclaration); + functionTypeDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcTypeAST, TypeScript.ASTHelpers.parametersFromParameterList(funcTypeAST.parameterList), functionTypeSymbol, signature); + + functionTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindMethodDeclarationToPullSymbol = function (methodDeclaration) { + var declKind = methodDeclaration.kind; + var declFlags = methodDeclaration.flags; + var methodAST = this.semanticInfoChain.getASTForDecl(methodDeclaration); + + var isPrivate = (declFlags & 2 /* Private */) !== 0; + var isStatic = (declFlags & 16 /* Static */) !== 0; + var isOptional = (declFlags & 128 /* Optional */) !== 0; + + var methodName = methodDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(methodDeclaration, true); + var parentHadSymbol = false; + + var methodSymbol = null; + var methodTypeSymbol = null; + + if (parent.isClass() && isStatic) { + parent = parent.getConstructorMethod().type; + } + + methodSymbol = parent.findMember(methodName, false); + + if (methodSymbol && (methodSymbol.kind !== 65536 /* Method */ || (!isSignature && !methodSymbol.allDeclsHaveFlag(2048 /* Signature */)))) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(methodAST, methodDeclaration.getDisplayName(), methodSymbol.getDeclarations()[0].ast()); + methodSymbol = null; + } + + if (methodSymbol) { + methodTypeSymbol = methodSymbol.type; + parentHadSymbol = true; + } + + if (!methodSymbol) { + methodSymbol = new TypeScript.PullSymbol(methodName, 65536 /* Method */); + } + + if (!methodTypeSymbol) { + methodTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + methodSymbol.type = methodTypeSymbol; + methodTypeSymbol.setFunctionSymbol(methodSymbol); + } + + methodDeclaration.setSymbol(methodSymbol); + methodSymbol.addDeclaration(methodDeclaration); + methodTypeSymbol.addDeclaration(methodDeclaration); + + var nameAST = methodAST.kind() === 135 /* MemberFunctionDeclaration */ ? methodAST.propertyName : methodAST.propertyName; + + TypeScript.Debug.assert(nameAST); + + this.semanticInfoChain.setSymbolForAST(nameAST, methodSymbol); + this.semanticInfoChain.setSymbolForAST(methodAST, methodSymbol); + + if (isOptional) { + methodSymbol.isOptional = true; + } + + if (!parentHadSymbol) { + parent.addMember(methodSymbol); + } + + var sigKind = 1048576 /* CallSignature */; + + var signature = new TypeScript.PullSignatureSymbol(sigKind, !isSignature); + + var parameterList = TypeScript.ASTHelpers.getParameterList(methodAST); + if (TypeScript.lastParameterIsRest(parameterList)) { + signature.hasVarArgs = true; + } + + var typeParameters = methodDeclaration.getTypeParameters(); + var typeParameter; + var typeParameterName; + var typeParameterAST; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameterName = typeParameters[i].name; + typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameters[i]); + + typeParameter = signature.findTypeParameter(typeParameterName); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameterName); + signature.addTypeParameter(typeParameter); + } else { + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + signature.addDeclaration(methodDeclaration); + methodDeclaration.setSignatureSymbol(signature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(methodDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(funcDecl)), methodTypeSymbol, signature); + + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(signature, methodTypeSymbol.getOwnCallSignatures()); + methodTypeSymbol.insertCallSignatureAtIndex(signature, signatureIndex); + }; + + PullSymbolBinder.prototype.bindStaticPrototypePropertyOfClass = function (classAST, classTypeSymbol, constructorTypeSymbol) { + var prototypeStr = "prototype"; + + var prototypeSymbol = constructorTypeSymbol.findMember(prototypeStr, false); + if (prototypeSymbol && !prototypeSymbol.getIsSynthesized()) { + this.semanticInfoChain.addDiagnostic(TypeScript.PullHelpers.diagnosticFromDecl(prototypeSymbol.getDeclarations()[0], TypeScript.DiagnosticCode.Duplicate_identifier_0, [prototypeSymbol.getDisplayName()])); + } + + if (!prototypeSymbol || !prototypeSymbol.getIsSynthesized()) { + var prototypeDecl = new TypeScript.PullSynthesizedDecl(prototypeStr, prototypeStr, 4096 /* Property */, 4 /* Public */ | 16 /* Static */, constructorTypeSymbol.getDeclarations()[0], this.semanticInfoChain); + + prototypeSymbol = new TypeScript.PullSymbol(prototypeStr, 4096 /* Property */); + prototypeSymbol.setIsSynthesized(); + prototypeSymbol.addDeclaration(prototypeDecl); + prototypeSymbol.type = classTypeSymbol; + constructorTypeSymbol.addMember(prototypeSymbol); + + if (prototypeSymbol.type && prototypeSymbol.type.isGeneric()) { + var resolver = this.semanticInfoChain.getResolver(); + prototypeSymbol.type = resolver.instantiateTypeToAny(prototypeSymbol.type, new TypeScript.PullTypeResolutionContext(resolver)); + } + prototypeSymbol.setResolved(); + } + }; + + PullSymbolBinder.prototype.bindConstructorDeclarationToPullSymbol = function (constructorDeclaration) { + var declKind = constructorDeclaration.kind; + var declFlags = constructorDeclaration.flags; + var constructorAST = this.semanticInfoChain.getASTForDecl(constructorDeclaration); + + var constructorName = constructorDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + + var parent = this.getParent(constructorDeclaration, true); + + var parentHadSymbol = false; + + var constructorSymbol = parent.getConstructorMethod(); + var constructorTypeSymbol = null; + + if (constructorSymbol && (constructorSymbol.kind !== 32768 /* ConstructorMethod */ || (!isSignature && constructorSymbol.type && constructorSymbol.type.hasOwnConstructSignatures()))) { + var hasDefinitionSignature = false; + var constructorSigs = constructorSymbol.type.getOwnDeclaredConstructSignatures(); + + for (var i = 0; i < constructorSigs.length; i++) { + if (!constructorSigs[i].anyDeclHasFlag(2048 /* Signature */)) { + hasDefinitionSignature = true; + break; + } + } + + if (hasDefinitionSignature) { + this.semanticInfoChain.addDiagnosticFromAST(constructorAST, TypeScript.DiagnosticCode.Multiple_constructor_implementations_are_not_allowed); + + constructorSymbol = null; + } + } + + if (constructorSymbol) { + constructorTypeSymbol = constructorSymbol.type; + } else { + constructorSymbol = new TypeScript.PullSymbol(constructorName, 32768 /* ConstructorMethod */); + constructorTypeSymbol = new TypeScript.PullTypeSymbol("", 33554432 /* ConstructorType */); + } + + parent.setConstructorMethod(constructorSymbol); + constructorSymbol.type = constructorTypeSymbol; + + constructorDeclaration.setSymbol(constructorSymbol); + constructorSymbol.addDeclaration(constructorDeclaration); + constructorTypeSymbol.addDeclaration(constructorDeclaration); + constructorSymbol.setIsSynthesized(false); + this.semanticInfoChain.setSymbolForAST(constructorAST, constructorSymbol); + + var constructSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */, !isSignature); + constructSignature.returnType = parent; + constructSignature.addTypeParametersFromReturnType(); + + constructSignature.addDeclaration(constructorDeclaration); + constructorDeclaration.setSignatureSymbol(constructSignature); + + this.bindParameterSymbols(constructorAST, TypeScript.ASTHelpers.parametersFromParameterList(constructorAST.callSignature.parameterList), constructorTypeSymbol, constructSignature); + + if (TypeScript.lastParameterIsRest(constructorAST.callSignature.parameterList)) { + constructSignature.hasVarArgs = true; + } + + constructorTypeSymbol.appendConstructSignature(constructSignature); + }; + + PullSymbolBinder.prototype.bindConstructSignatureDeclarationToPullSymbol = function (constructSignatureDeclaration) { + var parent = this.getParent(constructSignatureDeclaration, true); + var constructorAST = this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration); + + var constructSignature = new TypeScript.PullSignatureSymbol(2097152 /* ConstructSignature */); + + if (TypeScript.lastParameterIsRest(constructorAST.callSignature.parameterList)) { + constructSignature.hasVarArgs = true; + } + + var typeParameters = constructSignatureDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = constructSignature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + constructSignature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + constructSignature.addDeclaration(constructSignatureDeclaration); + constructSignatureDeclaration.setSignatureSymbol(constructSignature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(TypeScript.ASTHelpers.getParameterList(funcDecl)), null, constructSignature); + + this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(constructSignatureDeclaration), constructSignature); + + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(constructSignature, parent.getOwnDeclaredConstructSignatures()); + parent.insertConstructSignatureAtIndex(constructSignature, signatureIndex); + }; + + PullSymbolBinder.prototype.bindCallSignatureDeclarationToPullSymbol = function (callSignatureDeclaration) { + var parent = this.getParent(callSignatureDeclaration, true); + var callSignatureAST = this.semanticInfoChain.getASTForDecl(callSignatureDeclaration); + + var callSignature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */); + + if (TypeScript.lastParameterIsRest(callSignatureAST.parameterList)) { + callSignature.hasVarArgs = true; + } + + var typeParameters = callSignatureDeclaration.getTypeParameters(); + var typeParameter; + + for (var i = 0; i < typeParameters.length; i++) { + typeParameter = callSignature.findTypeParameter(typeParameters[i].name); + + if (!typeParameter) { + typeParameter = new TypeScript.PullTypeParameterSymbol(typeParameters[i].name); + + callSignature.addTypeParameter(typeParameter); + } else { + var typeParameterAST = this.semanticInfoChain.getASTForDecl(typeParameter.getDeclarations()[0]); + this.semanticInfoChain.addDiagnosticFromAST(typeParameterAST, TypeScript.DiagnosticCode.Duplicate_identifier_0, [typeParameter.getName()]); + } + + typeParameter.addDeclaration(typeParameters[i]); + typeParameters[i].setSymbol(typeParameter); + } + + callSignature.addDeclaration(callSignatureDeclaration); + callSignatureDeclaration.setSignatureSymbol(callSignature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(callSignatureDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameterList(funcDecl.parameterList), null, callSignature); + + this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(callSignatureDeclaration), callSignature); + + var signatureIndex = this.getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(callSignature, parent.getOwnCallSignatures()); + parent.insertCallSignatureAtIndex(callSignature, signatureIndex); + }; + + PullSymbolBinder.prototype.bindIndexSignatureDeclarationToPullSymbol = function (indexSignatureDeclaration) { + var indexSignature = new TypeScript.PullSignatureSymbol(4194304 /* IndexSignature */); + + indexSignature.addDeclaration(indexSignatureDeclaration); + indexSignatureDeclaration.setSignatureSymbol(indexSignature); + + var funcDecl = this.semanticInfoChain.getASTForDecl(indexSignatureDeclaration); + this.bindParameterSymbols(funcDecl, TypeScript.ASTHelpers.parametersFromParameter(funcDecl.parameter), null, indexSignature); + + this.semanticInfoChain.setSymbolForAST(this.semanticInfoChain.getASTForDecl(indexSignatureDeclaration), indexSignature); + + var parent = this.getParent(indexSignatureDeclaration); + parent.addIndexSignature(indexSignature); + indexSignature.setContainer(parent); + }; + + PullSymbolBinder.prototype.bindGetAccessorDeclarationToPullSymbol = function (getAccessorDeclaration) { + var declKind = getAccessorDeclaration.kind; + var declFlags = getAccessorDeclaration.flags; + var funcDeclAST = this.semanticInfoChain.getASTForDecl(getAccessorDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = getAccessorDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var isStatic = false; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + var parent = this.getParent(getAccessorDeclaration, true); + var parentHadSymbol = false; + + var accessorSymbol = null; + var getterSymbol = null; + var getterTypeSymbol = null; + + if (isStatic) { + parent = parent.getConstructorMethod().type; + } + + accessorSymbol = parent.findMember(funcName, false); + + if (accessorSymbol) { + if (!accessorSymbol.isAccessor()) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.propertyName, getAccessorDeclaration.getDisplayName(), accessorSymbol.getDeclarations()[0].ast()); + accessorSymbol = null; + } else { + getterSymbol = accessorSymbol.getGetter(); + + if (getterSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Getter_0_already_declared, [getAccessorDeclaration.getDisplayName()]); + accessorSymbol = null; + getterSymbol = null; + } + } + } + + if (accessorSymbol) { + parentHadSymbol = true; + } + + if (accessorSymbol && getterSymbol) { + getterTypeSymbol = getterSymbol.type; + } + + if (!accessorSymbol) { + accessorSymbol = new TypeScript.PullAccessorSymbol(funcName); + } + + if (!getterSymbol) { + getterSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + getterTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + getterTypeSymbol.setFunctionSymbol(getterSymbol); + + getterSymbol.type = getterTypeSymbol; + + accessorSymbol.setGetter(getterSymbol); + } + + getAccessorDeclaration.setSymbol(accessorSymbol); + accessorSymbol.addDeclaration(getAccessorDeclaration); + getterSymbol.addDeclaration(getAccessorDeclaration); + + var nameAST = funcDeclAST.propertyName; + this.semanticInfoChain.setSymbolForAST(nameAST, accessorSymbol); + this.semanticInfoChain.setSymbolForAST(funcDeclAST, getterSymbol); + + if (!parentHadSymbol) { + parent.addMember(accessorSymbol); + } + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + signature.addDeclaration(getAccessorDeclaration); + getAccessorDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcDeclAST, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), getterTypeSymbol, signature); + + getterTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.bindSetAccessorDeclarationToPullSymbol = function (setAccessorDeclaration) { + var declKind = setAccessorDeclaration.kind; + var declFlags = setAccessorDeclaration.flags; + var funcDeclAST = this.semanticInfoChain.getASTForDecl(setAccessorDeclaration); + + var isExported = (declFlags & 1 /* Exported */) !== 0; + + var funcName = setAccessorDeclaration.name; + + var isSignature = (declFlags & 2048 /* Signature */) !== 0; + var isStatic = false; + + if (TypeScript.hasFlag(declFlags, 16 /* Static */)) { + isStatic = true; + } + + var parent = this.getParent(setAccessorDeclaration, true); + var parentHadSymbol = false; + + var accessorSymbol = null; + var setterSymbol = null; + var setterTypeSymbol = null; + + if (isStatic) { + parent = parent.getConstructorMethod().type; + } + + accessorSymbol = parent.findMember(funcName, false); + + if (accessorSymbol) { + if (!accessorSymbol.isAccessor()) { + this.semanticInfoChain.addDuplicateIdentifierDiagnosticFromAST(funcDeclAST.propertyName, setAccessorDeclaration.getDisplayName(), accessorSymbol.getDeclarations()[0].ast()); + accessorSymbol = null; + } else { + setterSymbol = accessorSymbol.getSetter(); + + if (setterSymbol) { + this.semanticInfoChain.addDiagnosticFromAST(funcDeclAST, TypeScript.DiagnosticCode.Setter_0_already_declared, [setAccessorDeclaration.getDisplayName()]); + accessorSymbol = null; + setterSymbol = null; + } + } + } + + if (accessorSymbol) { + parentHadSymbol = true; + + if (setterSymbol) { + setterTypeSymbol = setterSymbol.type; + } + } + + if (!accessorSymbol) { + accessorSymbol = new TypeScript.PullAccessorSymbol(funcName); + } + + if (!setterSymbol) { + setterSymbol = new TypeScript.PullSymbol(funcName, 16384 /* Function */); + setterTypeSymbol = new TypeScript.PullTypeSymbol("", 16777216 /* FunctionType */); + setterTypeSymbol.setFunctionSymbol(setterSymbol); + + setterSymbol.type = setterTypeSymbol; + + accessorSymbol.setSetter(setterSymbol); + } + + setAccessorDeclaration.setSymbol(accessorSymbol); + accessorSymbol.addDeclaration(setAccessorDeclaration); + setterSymbol.addDeclaration(setAccessorDeclaration); + + var nameAST = funcDeclAST.propertyName; + this.semanticInfoChain.setSymbolForAST(nameAST, accessorSymbol); + this.semanticInfoChain.setSymbolForAST(funcDeclAST, setterSymbol); + + if (!parentHadSymbol) { + parent.addMember(accessorSymbol); + } + + var signature = new TypeScript.PullSignatureSymbol(1048576 /* CallSignature */, !isSignature); + + signature.addDeclaration(setAccessorDeclaration); + setAccessorDeclaration.setSignatureSymbol(signature); + + this.bindParameterSymbols(funcDeclAST, TypeScript.ASTHelpers.parametersFromParameterList(funcDeclAST.parameterList), setterTypeSymbol, signature); + + setterTypeSymbol.appendCallSignature(signature); + }; + + PullSymbolBinder.prototype.getDeclsToBind = function (decl) { + var decls; + switch (decl.kind) { + case 64 /* Enum */: + case 32 /* DynamicModule */: + case 4 /* Container */: + case 16 /* Interface */: + decls = this.findDeclsInContext(decl, decl.kind, true); + break; + + case 512 /* Variable */: + case 16384 /* Function */: + case 65536 /* Method */: + case 32768 /* ConstructorMethod */: + decls = this.findDeclsInContext(decl, decl.kind, false); + break; + + default: + decls = [decl]; + } + TypeScript.Debug.assert(decls && decls.length > 0); + TypeScript.Debug.assert(TypeScript.ArrayUtilities.contains(decls, decl)); + return decls; + }; + + PullSymbolBinder.prototype.shouldBindDeclaration = function (decl) { + return !decl.hasBeenBound() && this.declsBeingBound.indexOf(decl.declID) < 0; + }; + + PullSymbolBinder.prototype.bindDeclToPullSymbol = function (decl) { + if (this.shouldBindDeclaration(decl)) { + this.bindAllDeclsToPullSymbol(decl); + } + }; + + PullSymbolBinder.prototype.bindAllDeclsToPullSymbol = function (askedDecl) { + var allDecls = this.getDeclsToBind(askedDecl); + for (var i = 0; i < allDecls.length; i++) { + var decl = allDecls[i]; + + if (this.shouldBindDeclaration(decl)) { + this.bindSingleDeclToPullSymbol(decl); + } + } + }; + + PullSymbolBinder.prototype.bindSingleDeclToPullSymbol = function (decl) { + this.declsBeingBound.push(decl.declID); + + switch (decl.kind) { + case 1 /* Script */: + var childDecls = decl.getChildDecls(); + for (var i = 0; i < childDecls.length; i++) { + this.bindDeclToPullSymbol(childDecls[i]); + } + break; + + case 64 /* Enum */: + this.bindEnumDeclarationToPullSymbol(decl); + break; + + case 32 /* DynamicModule */: + case 4 /* Container */: + this.bindModuleDeclarationToPullSymbol(decl); + break; + + case 16 /* Interface */: + this.bindInterfaceDeclarationToPullSymbol(decl); + break; + + case 8 /* Class */: + this.bindClassDeclarationToPullSymbol(decl); + break; + + case 16384 /* Function */: + this.bindFunctionDeclarationToPullSymbol(decl); + break; + + case 512 /* Variable */: + this.bindVariableDeclarationToPullSymbol(decl); + break; + + case 1024 /* CatchVariable */: + this.bindCatchVariableToPullSymbol(decl); + break; + + case 67108864 /* EnumMember */: + this.bindEnumMemberDeclarationToPullSymbol(decl); + break; + + case 4096 /* Property */: + this.bindPropertyDeclarationToPullSymbol(decl); + break; + + case 65536 /* Method */: + this.bindMethodDeclarationToPullSymbol(decl); + break; + + case 32768 /* ConstructorMethod */: + this.bindConstructorDeclarationToPullSymbol(decl); + break; + + case 1048576 /* CallSignature */: + this.bindCallSignatureDeclarationToPullSymbol(decl); + break; + + case 2097152 /* ConstructSignature */: + this.bindConstructSignatureDeclarationToPullSymbol(decl); + break; + + case 4194304 /* IndexSignature */: + this.bindIndexSignatureDeclarationToPullSymbol(decl); + break; + + case 262144 /* GetAccessor */: + this.bindGetAccessorDeclarationToPullSymbol(decl); + break; + + case 524288 /* SetAccessor */: + this.bindSetAccessorDeclarationToPullSymbol(decl); + break; + + case 8388608 /* ObjectType */: + this.bindObjectTypeDeclarationToPullSymbol(decl); + break; + + case 16777216 /* FunctionType */: + this.bindFunctionTypeDeclarationToPullSymbol(decl); + break; + + case 33554432 /* ConstructorType */: + this.bindConstructorTypeDeclarationToPullSymbol(decl); + break; + + case 131072 /* FunctionExpression */: + this.bindFunctionExpressionToPullSymbol(decl); + break; + + case 128 /* TypeAlias */: + this.bindImportDeclaration(decl); + break; + + case 2048 /* Parameter */: + case 8192 /* TypeParameter */: + decl.getParentDecl().getSymbol(); + break; + + case 268435456 /* CatchBlock */: + case 134217728 /* WithBlock */: + break; + + default: + TypeScript.CompilerDiagnostics.assert(false, "Unrecognized type declaration"); + } + + TypeScript.Debug.assert(TypeScript.ArrayUtilities.last(this.declsBeingBound) === decl.declID); + this.declsBeingBound.pop(); + }; + return PullSymbolBinder; + })(); + TypeScript.PullSymbolBinder = PullSymbolBinder; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (PullHelpers) { + function diagnosticFromDecl(decl, diagnosticKey, _arguments, additionalLocations) { + if (typeof _arguments === "undefined") { _arguments = null; } + if (typeof additionalLocations === "undefined") { additionalLocations = null; } + var ast = decl.ast(); + return decl.semanticInfoChain.diagnosticFromAST(ast, diagnosticKey, _arguments, additionalLocations); + } + PullHelpers.diagnosticFromDecl = diagnosticFromDecl; + + function resolveDeclaredSymbolToUseType(symbol) { + if (symbol.isSignature()) { + if (!symbol.returnType) { + symbol._resolveDeclaredSymbol(); + } + } else if (!symbol.type) { + symbol._resolveDeclaredSymbol(); + } + } + PullHelpers.resolveDeclaredSymbolToUseType = resolveDeclaredSymbolToUseType; + + function getSignatureForFuncDecl(functionDecl) { + var funcDecl = functionDecl.ast(); + var funcSymbol = functionDecl.getSymbol(); + + if (!funcSymbol) { + funcSymbol = functionDecl.getSignatureSymbol(); + } + + var functionSignature = null; + var typeSymbolWithAllSignatures = null; + if (funcSymbol.isSignature()) { + functionSignature = funcSymbol; + var parent = functionDecl.getParentDecl(); + typeSymbolWithAllSignatures = parent.getSymbol().type; + } else { + functionSignature = functionDecl.getSignatureSymbol(); + typeSymbolWithAllSignatures = funcSymbol.type; + } + var signatures; + + if (funcDecl.kind() === 137 /* ConstructorDeclaration */ || functionDecl.kind === 2097152 /* ConstructSignature */) { + signatures = typeSymbolWithAllSignatures.getConstructSignatures(); + } else if (functionDecl.kind === 4194304 /* IndexSignature */) { + signatures = typeSymbolWithAllSignatures.getIndexSignatures(); + } else { + signatures = typeSymbolWithAllSignatures.getCallSignatures(); + } + + return { + signature: functionSignature, + allSignatures: signatures + }; + } + PullHelpers.getSignatureForFuncDecl = getSignatureForFuncDecl; + + function getAccessorSymbol(getterOrSetter, semanticInfoChain) { + var functionDecl = semanticInfoChain.getDeclForAST(getterOrSetter); + var getterOrSetterSymbol = functionDecl.getSymbol(); + + return getterOrSetterSymbol; + } + PullHelpers.getAccessorSymbol = getAccessorSymbol; + + function getGetterAndSetterFunction(funcDecl, semanticInfoChain) { + var accessorSymbol = PullHelpers.getAccessorSymbol(funcDecl, semanticInfoChain); + var result = { + getter: null, + setter: null + }; + var getter = accessorSymbol.getGetter(); + if (getter) { + var getterDecl = getter.getDeclarations()[0]; + result.getter = semanticInfoChain.getASTForDecl(getterDecl); + } + var setter = accessorSymbol.getSetter(); + if (setter) { + var setterDecl = setter.getDeclarations()[0]; + result.setter = semanticInfoChain.getASTForDecl(setterDecl); + } + + return result; + } + PullHelpers.getGetterAndSetterFunction = getGetterAndSetterFunction; + + function symbolIsEnum(source) { + return source && (source.kind & (64 /* Enum */ | 67108864 /* EnumMember */)) !== 0; + } + PullHelpers.symbolIsEnum = symbolIsEnum; + + function symbolIsModule(symbol) { + return symbol && (symbol.kind === 4 /* Container */ || isOneDeclarationOfKind(symbol, 4 /* Container */)); + } + PullHelpers.symbolIsModule = symbolIsModule; + + function isOneDeclarationOfKind(symbol, kind) { + var decls = symbol.getDeclarations(); + for (var i = 0; i < decls.length; i++) { + if (decls[i].kind === kind) { + return true; + } + } + + return false; + } + + function isNameNumeric(name) { + return isFinite(+name); + } + PullHelpers.isNameNumeric = isNameNumeric; + + function typeSymbolsAreIdentical(a, b) { + if (a.isTypeReference() && !a.getIsSpecialized()) { + a = a.referencedTypeSymbol; + } + + if (b.isTypeReference() && !b.getIsSpecialized()) { + b = b.referencedTypeSymbol; + } + + return a === b; + } + PullHelpers.typeSymbolsAreIdentical = typeSymbolsAreIdentical; + + function getRootType(type) { + var rootType = type.getRootSymbol(); + + while (true) { + if (type === rootType) { + return type; + } + + type = rootType; + rootType = type.getRootSymbol(); + } + } + PullHelpers.getRootType = getRootType; + + function isSymbolLocal(symbol) { + var container = symbol.getContainer(); + if (container) { + var containerKind = container.kind; + if (containerKind & (1032192 /* SomeFunction */ | 16777216 /* FunctionType */)) { + return true; + } + + if (containerKind === 33554432 /* ConstructorType */ && !symbol.anyDeclHasFlag(16 /* Static */ | 1 /* Exported */)) { + return true; + } + } + + return false; + } + PullHelpers.isSymbolLocal = isSymbolLocal; + + function isExportedSymbolInClodule(symbol) { + var container = symbol.getContainer(); + return container && container.kind === 33554432 /* ConstructorType */ && symbolIsModule(container) && symbol.anyDeclHasFlag(1 /* Exported */); + } + PullHelpers.isExportedSymbolInClodule = isExportedSymbolInClodule; + + function isSymbolDeclaredInScopeChain(symbol, scopeSymbol) { + TypeScript.Debug.assert(symbol); + var symbolDeclarationScope = symbol.getContainer(); + + while (scopeSymbol) { + if (scopeSymbol === symbolDeclarationScope) { + return true; + } + + scopeSymbol = scopeSymbol.getContainer(); + } + + if (scopeSymbol === null && symbolDeclarationScope === null) { + return true; + } + + return false; + } + PullHelpers.isSymbolDeclaredInScopeChain = isSymbolDeclaredInScopeChain; + + + + function walkSignatureSymbol(signatureSymbol, walker) { + var continueWalk = true; + var parameters = signatureSymbol.parameters; + if (parameters) { + for (var i = 0; continueWalk && i < parameters.length; i++) { + continueWalk = walker.signatureParameterWalk(parameters[i]); + } + } + + if (continueWalk) { + continueWalk = walker.signatureReturnTypeWalk(signatureSymbol.returnType); + } + + return continueWalk; + } + + function walkPullTypeSymbolStructure(typeSymbol, walker) { + var continueWalk = true; + + var members = typeSymbol.getMembers(); + for (var i = 0; continueWalk && i < members.length; i++) { + continueWalk = walker.memberSymbolWalk(members[i]); + } + + if (continueWalk) { + var callSigantures = typeSymbol.getCallSignatures(); + for (var i = 0; continueWalk && i < callSigantures.length; i++) { + continueWalk = walker.callSignatureWalk(callSigantures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(callSigantures[i], walker); + } + } + } + + if (continueWalk) { + var constructSignatures = typeSymbol.getConstructSignatures(); + for (var i = 0; continueWalk && i < constructSignatures.length; i++) { + continueWalk = walker.constructSignatureWalk(constructSignatures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(constructSignatures[i], walker); + } + } + } + + if (continueWalk) { + var indexSignatures = typeSymbol.getIndexSignatures(); + for (var i = 0; continueWalk && i < indexSignatures.length; i++) { + continueWalk = walker.indexSignatureWalk(indexSignatures[i]); + if (continueWalk) { + continueWalk = walkSignatureSymbol(indexSignatures[i], walker); + } + } + } + } + PullHelpers.walkPullTypeSymbolStructure = walkPullTypeSymbolStructure; + + var OtherPullDeclsWalker = (function () { + function OtherPullDeclsWalker() { + this.currentlyWalkingOtherDecls = []; + } + OtherPullDeclsWalker.prototype.walkOtherPullDecls = function (currentDecl, otherDecls, callBack) { + if (otherDecls) { + var isAlreadyWalkingOtherDecl = TypeScript.ArrayUtilities.any(this.currentlyWalkingOtherDecls, function (inWalkingOtherDecl) { + return TypeScript.ArrayUtilities.contains(otherDecls, inWalkingOtherDecl); + }); + + if (!isAlreadyWalkingOtherDecl) { + this.currentlyWalkingOtherDecls.push(currentDecl); + for (var i = 0; i < otherDecls.length; i++) { + if (otherDecls[i] !== currentDecl) { + callBack(otherDecls[i]); + } + } + var currentlyWalkingOtherDeclsDecl = this.currentlyWalkingOtherDecls.pop(); + TypeScript.Debug.assert(currentlyWalkingOtherDeclsDecl == currentDecl); + } + } + }; + return OtherPullDeclsWalker; + })(); + PullHelpers.OtherPullDeclsWalker = OtherPullDeclsWalker; + })(TypeScript.PullHelpers || (TypeScript.PullHelpers = {})); + var PullHelpers = TypeScript.PullHelpers; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var WrapsTypeParameterCache = (function () { + function WrapsTypeParameterCache() { + this._wrapsTypeParameterCache = TypeScript.BitVector.getBitVector(true); + } + WrapsTypeParameterCache.prototype.getWrapsTypeParameter = function (typeParameterArgumentMap) { + var mapHasTypeParameterNotCached = false; + for (var typeParameterID in typeParameterArgumentMap) { + if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + var cachedValue = this._wrapsTypeParameterCache.valueAt(typeParameterID); + if (cachedValue) { + return typeParameterID; + } + mapHasTypeParameterNotCached = mapHasTypeParameterNotCached || cachedValue === undefined; + } + } + + if (!mapHasTypeParameterNotCached) { + return 0; + } + + return undefined; + }; + + WrapsTypeParameterCache.prototype.setWrapsTypeParameter = function (typeParameterArgumentMap, wrappingTypeParameterID) { + if (wrappingTypeParameterID) { + this._wrapsTypeParameterCache.setValueAt(wrappingTypeParameterID, true); + } else { + for (var typeParameterID in typeParameterArgumentMap) { + if (typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + this._wrapsTypeParameterCache.setValueAt(typeParameterID, false); + } + } + } + }; + return WrapsTypeParameterCache; + })(); + TypeScript.WrapsTypeParameterCache = WrapsTypeParameterCache; + + (function (PullInstantiationHelpers) { + var MutableTypeArgumentMap = (function () { + function MutableTypeArgumentMap(typeParameterArgumentMap) { + this.typeParameterArgumentMap = typeParameterArgumentMap; + this.createdDuplicateTypeArgumentMap = false; + } + MutableTypeArgumentMap.prototype.ensureTypeArgumentCopy = function () { + if (!this.createdDuplicateTypeArgumentMap) { + var passedInTypeArgumentMap = this.typeParameterArgumentMap; + this.typeParameterArgumentMap = []; + for (var typeParameterID in passedInTypeArgumentMap) { + if (passedInTypeArgumentMap.hasOwnProperty(typeParameterID)) { + this.typeParameterArgumentMap[typeParameterID] = passedInTypeArgumentMap[typeParameterID]; + } + } + this.createdDuplicateTypeArgumentMap = true; + } + }; + return MutableTypeArgumentMap; + })(); + PullInstantiationHelpers.MutableTypeArgumentMap = MutableTypeArgumentMap; + + function instantiateTypeArgument(resolver, symbol, mutableTypeParameterMap) { + if (symbol.getIsSpecialized()) { + var rootTypeArgumentMap = symbol.getTypeParameterArgumentMap(); + var newTypeArgumentMap = []; + var allowedTypeParameters = symbol.getAllowedToReferenceTypeParameters(); + for (var i = 0; i < allowedTypeParameters.length; i++) { + var typeParameterID = allowedTypeParameters[i].pullSymbolID; + var typeArg = rootTypeArgumentMap[typeParameterID]; + if (typeArg) { + newTypeArgumentMap[typeParameterID] = resolver.instantiateType(typeArg, mutableTypeParameterMap.typeParameterArgumentMap); + } + } + + for (var i = 0; i < allowedTypeParameters.length; i++) { + var typeParameterID = allowedTypeParameters[i].pullSymbolID; + if (newTypeArgumentMap[typeParameterID] && mutableTypeParameterMap.typeParameterArgumentMap[typeParameterID] != newTypeArgumentMap[typeParameterID]) { + mutableTypeParameterMap.ensureTypeArgumentCopy(); + mutableTypeParameterMap.typeParameterArgumentMap[typeParameterID] = newTypeArgumentMap[typeParameterID]; + } + } + } + } + PullInstantiationHelpers.instantiateTypeArgument = instantiateTypeArgument; + + function cleanUpTypeArgumentMap(symbol, mutableTypeArgumentMap) { + var allowedToReferenceTypeParameters = symbol.getAllowedToReferenceTypeParameters(); + for (var typeParameterID in mutableTypeArgumentMap.typeParameterArgumentMap) { + if (mutableTypeArgumentMap.typeParameterArgumentMap.hasOwnProperty(typeParameterID)) { + if (!TypeScript.ArrayUtilities.any(allowedToReferenceTypeParameters, function (typeParameter) { + return typeParameter.pullSymbolID == typeParameterID; + })) { + mutableTypeArgumentMap.ensureTypeArgumentCopy(); + delete mutableTypeArgumentMap.typeParameterArgumentMap[typeParameterID]; + } + } + } + } + PullInstantiationHelpers.cleanUpTypeArgumentMap = cleanUpTypeArgumentMap; + + function getAllowedToReferenceTypeParametersFromDecl(decl) { + var allowedToReferenceTypeParameters = []; + + var allowedToUseDeclTypeParameters = false; + var getTypeParametersFromParentDecl = false; + + switch (decl.kind) { + case 65536 /* Method */: + if (TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + allowedToUseDeclTypeParameters = true; + break; + } + + case 16777216 /* FunctionType */: + case 33554432 /* ConstructorType */: + case 2097152 /* ConstructSignature */: + case 1048576 /* CallSignature */: + case 131072 /* FunctionExpression */: + case 16384 /* Function */: + allowedToUseDeclTypeParameters = true; + getTypeParametersFromParentDecl = true; + break; + + case 4096 /* Property */: + if (TypeScript.hasFlag(decl.flags, 16 /* Static */)) { + break; + } + + case 2048 /* Parameter */: + case 262144 /* GetAccessor */: + case 524288 /* SetAccessor */: + case 32768 /* ConstructorMethod */: + case 4194304 /* IndexSignature */: + case 8388608 /* ObjectType */: + case 256 /* ObjectLiteral */: + case 8192 /* TypeParameter */: + getTypeParametersFromParentDecl = true; + break; + + case 8 /* Class */: + case 16 /* Interface */: + allowedToUseDeclTypeParameters = true; + break; + } + + if (getTypeParametersFromParentDecl) { + allowedToReferenceTypeParameters = allowedToReferenceTypeParameters.concat(getAllowedToReferenceTypeParametersFromDecl(decl.getParentDecl())); + } + + if (allowedToUseDeclTypeParameters) { + var typeParameterDecls = decl.getTypeParameters(); + for (var i = 0; i < typeParameterDecls.length; i++) { + allowedToReferenceTypeParameters.push(typeParameterDecls[i].getSymbol()); + } + } + + return allowedToReferenceTypeParameters; + } + PullInstantiationHelpers.getAllowedToReferenceTypeParametersFromDecl = getAllowedToReferenceTypeParametersFromDecl; + + function createTypeParameterArgumentMap(typeParameters, typeArguments) { + return updateTypeParameterArgumentMap(typeParameters, typeArguments, {}); + } + PullInstantiationHelpers.createTypeParameterArgumentMap = createTypeParameterArgumentMap; + + function updateTypeParameterArgumentMap(typeParameters, typeArguments, typeParameterArgumentMap) { + for (var i = 0; i < typeParameters.length; i++) { + typeParameterArgumentMap[typeParameters[i].getRootSymbol().pullSymbolID] = typeArguments[i]; + } + return typeParameterArgumentMap; + } + PullInstantiationHelpers.updateTypeParameterArgumentMap = updateTypeParameterArgumentMap; + + function updateMutableTypeParameterArgumentMap(typeParameters, typeArguments, mutableMap) { + for (var i = 0; i < typeParameters.length; i++) { + var typeParameterId = typeParameters[i].getRootSymbol().pullSymbolID; + if (mutableMap.typeParameterArgumentMap[typeParameterId] !== typeArguments[i]) { + mutableMap.ensureTypeArgumentCopy(); + mutableMap.typeParameterArgumentMap[typeParameterId] = typeArguments[i]; + } + } + } + PullInstantiationHelpers.updateMutableTypeParameterArgumentMap = updateMutableTypeParameterArgumentMap; + + function twoTypesAreInstantiationsOfSameNamedGenericType(type1, type2) { + var type1IsGeneric = type1.isGeneric() && type1.getTypeArguments() !== null; + var type2IsGeneric = type2.isGeneric() && type2.getTypeArguments() !== null; + + if (type1IsGeneric && type2IsGeneric) { + var type1Root = TypeScript.PullHelpers.getRootType(type1); + var type2Root = TypeScript.PullHelpers.getRootType(type2); + return type1Root === type2Root; + } + + return false; + } + PullInstantiationHelpers.twoTypesAreInstantiationsOfSameNamedGenericType = twoTypesAreInstantiationsOfSameNamedGenericType; + })(TypeScript.PullInstantiationHelpers || (TypeScript.PullInstantiationHelpers = {})); + var PullInstantiationHelpers = TypeScript.PullInstantiationHelpers; +})(TypeScript || (TypeScript = {})); +if (Error) + Error.stackTraceLimit = 1000; + +var TypeScript; +(function (TypeScript) { + TypeScript.fileResolutionTime = 0; + TypeScript.fileResolutionIOTime = 0; + TypeScript.fileResolutionScanImportsTime = 0; + TypeScript.fileResolutionImportFileSearchTime = 0; + TypeScript.fileResolutionGetDefaultLibraryTime = 0; + TypeScript.sourceCharactersCompiled = 0; + TypeScript.syntaxTreeParseTime = 0; + TypeScript.syntaxDiagnosticsTime = 0; + TypeScript.astTranslationTime = 0; + TypeScript.typeCheckTime = 0; + + TypeScript.compilerResolvePathTime = 0; + TypeScript.compilerDirectoryNameTime = 0; + TypeScript.compilerDirectoryExistsTime = 0; + TypeScript.compilerFileExistsTime = 0; + + TypeScript.emitTime = 0; + TypeScript.emitWriteFileTime = 0; + + TypeScript.declarationEmitTime = 0; + TypeScript.declarationEmitIsExternallyVisibleTime = 0; + TypeScript.declarationEmitTypeSignatureTime = 0; + TypeScript.declarationEmitGetBoundDeclTypeTime = 0; + TypeScript.declarationEmitIsOverloadedCallSignatureTime = 0; + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime = 0; + TypeScript.declarationEmitGetBaseTypeTime = 0; + TypeScript.declarationEmitGetAccessorFunctionTime = 0; + TypeScript.declarationEmitGetTypeParameterSymbolTime = 0; + TypeScript.declarationEmitGetImportDeclarationSymbolTime = 0; + + TypeScript.ioHostResolvePathTime = 0; + TypeScript.ioHostDirectoryNameTime = 0; + TypeScript.ioHostCreateDirectoryStructureTime = 0; + TypeScript.ioHostWriteFileTime = 0; + + (function (EmitOutputResult) { + EmitOutputResult[EmitOutputResult["Succeeded"] = 0] = "Succeeded"; + EmitOutputResult[EmitOutputResult["FailedBecauseOfSyntaxErrors"] = 1] = "FailedBecauseOfSyntaxErrors"; + EmitOutputResult[EmitOutputResult["FailedBecauseOfCompilerOptionsErrors"] = 2] = "FailedBecauseOfCompilerOptionsErrors"; + EmitOutputResult[EmitOutputResult["FailedToGenerateDeclarationsBecauseOfSemanticErrors"] = 3] = "FailedToGenerateDeclarationsBecauseOfSemanticErrors"; + })(TypeScript.EmitOutputResult || (TypeScript.EmitOutputResult = {})); + var EmitOutputResult = TypeScript.EmitOutputResult; + + var EmitOutput = (function () { + function EmitOutput(emitOutputResult) { + if (typeof emitOutputResult === "undefined") { emitOutputResult = 0 /* Succeeded */; } + this.outputFiles = []; + this.emitOutputResult = emitOutputResult; + } + return EmitOutput; + })(); + TypeScript.EmitOutput = EmitOutput; + + (function (OutputFileType) { + OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; + OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; + OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; + })(TypeScript.OutputFileType || (TypeScript.OutputFileType = {})); + var OutputFileType = TypeScript.OutputFileType; + + var OutputFile = (function () { + function OutputFile(name, writeByteOrderMark, text, fileType, sourceMapEntries) { + if (typeof sourceMapEntries === "undefined") { sourceMapEntries = []; } + this.name = name; + this.writeByteOrderMark = writeByteOrderMark; + this.text = text; + this.fileType = fileType; + this.sourceMapEntries = sourceMapEntries; + } + return OutputFile; + })(); + TypeScript.OutputFile = OutputFile; + + var CompileResult = (function () { + function CompileResult() { + this.diagnostics = []; + this.outputFiles = []; + } + CompileResult.fromDiagnostics = function (diagnostics) { + var result = new CompileResult(); + result.diagnostics = diagnostics; + return result; + }; + + CompileResult.fromOutputFiles = function (outputFiles) { + var result = new CompileResult(); + result.outputFiles = outputFiles; + return result; + }; + return CompileResult; + })(); + TypeScript.CompileResult = CompileResult; + + var TypeScriptCompiler = (function () { + function TypeScriptCompiler(logger, _settings) { + if (typeof logger === "undefined") { logger = new TypeScript.NullLogger(); } + if (typeof _settings === "undefined") { _settings = TypeScript.ImmutableCompilationSettings.defaultSettings(); } + this.logger = logger; + this._settings = _settings; + this.semanticInfoChain = null; + this.semanticInfoChain = new TypeScript.SemanticInfoChain(this, logger); + } + TypeScriptCompiler.prototype.compilationSettings = function () { + return this._settings; + }; + + TypeScriptCompiler.prototype.setCompilationSettings = function (newSettings) { + var oldSettings = this._settings; + this._settings = newSettings; + + if (!compareDataObjects(oldSettings, newSettings)) { + this.semanticInfoChain.invalidate(oldSettings, newSettings); + } + }; + + TypeScriptCompiler.prototype.getDocument = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + return this.semanticInfoChain.getDocument(fileName); + }; + + TypeScriptCompiler.prototype.cleanupSemanticCache = function () { + this.semanticInfoChain.invalidate(); + }; + + TypeScriptCompiler.prototype.addFile = function (fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles) { + if (typeof referencedFiles === "undefined") { referencedFiles = []; } + fileName = TypeScript.switchToForwardSlashes(fileName); + + TypeScript.sourceCharactersCompiled += scriptSnapshot.getLength(); + + var document = TypeScript.Document.create(this, this.semanticInfoChain, fileName, scriptSnapshot, byteOrderMark, version, isOpen, referencedFiles); + + this.semanticInfoChain.addDocument(document); + }; + + TypeScriptCompiler.prototype.updateFile = function (fileName, scriptSnapshot, version, isOpen, textChangeRange) { + fileName = TypeScript.switchToForwardSlashes(fileName); + + var document = this.getDocument(fileName); + var updatedDocument = document.update(scriptSnapshot, version, isOpen, textChangeRange); + + this.semanticInfoChain.addDocument(updatedDocument); + }; + + TypeScriptCompiler.prototype.removeFile = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + this.semanticInfoChain.removeDocument(fileName); + }; + + TypeScriptCompiler.prototype.mapOutputFileName = function (document, emitOptions, extensionChanger) { + if (document.emitToOwnOutputFile()) { + var updatedFileName = document.fileName; + if (emitOptions.outputDirectory() !== "") { + updatedFileName = document.fileName.replace(emitOptions.commonDirectoryPath(), ""); + updatedFileName = emitOptions.outputDirectory() + updatedFileName; + } + return extensionChanger(updatedFileName, false); + } else { + return extensionChanger(emitOptions.sharedOutputFile(), true); + } + }; + + TypeScriptCompiler.prototype.writeByteOrderMarkForDocument = function (document) { + var printReason = false; + + if (document.emitToOwnOutputFile()) { + var result = document.byteOrderMark !== 0 /* None */; + if (printReason) { + TypeScript.Environment.standardOut.WriteLine("Emitting byte order mark because of: " + document.fileName); + } + return result; + } else { + var fileNames = this.fileNames(); + + var result = false; + for (var i = 0, n = fileNames.length; i < n; i++) { + var document = this.getDocument(fileNames[i]); + + if (document.isExternalModule()) { + continue; + } + + if (document.byteOrderMark !== 0 /* None */) { + if (printReason) { + TypeScript.Environment.standardOut.WriteLine("Emitting byte order mark because of: " + document.fileName); + result = true; + } else { + return true; + } + } + } + + return result; + } + }; + + TypeScriptCompiler.mapToDTSFileName = function (fileName, wholeFileNameReplaced) { + return TypeScript.getDeclareFilePath(fileName); + }; + + TypeScriptCompiler.prototype._shouldEmit = function (document) { + return !document.isDeclareFile(); + }; + + TypeScriptCompiler.prototype._shouldEmitDeclarations = function (document) { + if (!this.compilationSettings().generateDeclarationFiles()) { + return false; + } + + return this._shouldEmit(document); + }; + + TypeScriptCompiler.prototype.emitDocumentDeclarationsWorker = function (document, emitOptions, declarationEmitter) { + var sourceUnit = document.sourceUnit(); + TypeScript.Debug.assert(this._shouldEmitDeclarations(document)); + + if (declarationEmitter) { + declarationEmitter.document = document; + } else { + var declareFileName = this.mapOutputFileName(document, emitOptions, TypeScriptCompiler.mapToDTSFileName); + declarationEmitter = new TypeScript.DeclarationEmitter(declareFileName, document, this, emitOptions, this.semanticInfoChain); + } + + declarationEmitter.emitDeclarations(sourceUnit); + return declarationEmitter; + }; + + TypeScriptCompiler.prototype._emitDocumentDeclarations = function (document, emitOptions, onSingleFileEmitComplete, sharedEmitter) { + if (this._shouldEmitDeclarations(document)) { + if (document.emitToOwnOutputFile()) { + var singleEmitter = this.emitDocumentDeclarationsWorker(document, emitOptions); + if (singleEmitter) { + onSingleFileEmitComplete(singleEmitter.getOutputFile()); + } + } else { + sharedEmitter = this.emitDocumentDeclarationsWorker(document, emitOptions, sharedEmitter); + } + } + + return sharedEmitter; + }; + + TypeScriptCompiler.prototype.emitAllDeclarations = function (resolvePath) { + var start = new Date().getTime(); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var sharedEmitter = null; + var fileNames = this.fileNames(); + + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + + var document = this.getDocument(fileNames[i]); + + sharedEmitter = this._emitDocumentDeclarations(document, emitOptions, function (file) { + return emitOutput.outputFiles.push(file); + }, sharedEmitter); + } + + if (sharedEmitter) { + emitOutput.outputFiles.push(sharedEmitter.getOutputFile()); + } + + TypeScript.declarationEmitTime += new Date().getTime() - start; + + return emitOutput; + }; + + TypeScriptCompiler.prototype.emitDeclarations = function (fileName, resolvePath) { + fileName = TypeScript.switchToForwardSlashes(fileName); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var document = this.getDocument(fileName); + + if (document.emitToOwnOutputFile()) { + this._emitDocumentDeclarations(document, emitOptions, function (file) { + return emitOutput.outputFiles.push(file); + }, null); + return emitOutput; + } else { + return this.emitAllDeclarations(resolvePath); + } + }; + + TypeScriptCompiler.prototype.canEmitDeclarations = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + var document = this.getDocument(fileName); + return this._shouldEmitDeclarations(document); + }; + + TypeScriptCompiler.mapToFileNameExtension = function (extension, fileName, wholeFileNameReplaced) { + if (wholeFileNameReplaced) { + return fileName; + } else { + var splitFname = fileName.split("."); + splitFname.pop(); + return splitFname.join(".") + extension; + } + }; + + TypeScriptCompiler.mapToJSFileName = function (fileName, wholeFileNameReplaced) { + return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced); + }; + + TypeScriptCompiler.prototype.emitDocumentWorker = function (document, emitOptions, emitter) { + var sourceUnit = document.sourceUnit(); + TypeScript.Debug.assert(this._shouldEmit(document)); + + var typeScriptFileName = document.fileName; + if (!emitter) { + var javaScriptFileName = this.mapOutputFileName(document, emitOptions, TypeScriptCompiler.mapToJSFileName); + var outFile = new TypeScript.TextWriter(javaScriptFileName, this.writeByteOrderMarkForDocument(document), 0 /* JavaScript */); + + emitter = new TypeScript.Emitter(javaScriptFileName, outFile, emitOptions, this.semanticInfoChain); + + if (this.compilationSettings().mapSourceFiles()) { + var sourceMapFile = new TypeScript.TextWriter(javaScriptFileName + TypeScript.SourceMapper.MapFileExtension, false, 1 /* SourceMap */); + emitter.createSourceMapper(document, javaScriptFileName, outFile, sourceMapFile, emitOptions.resolvePath); + } + } else if (this.compilationSettings().mapSourceFiles()) { + emitter.setSourceMapperNewSourceFile(document); + } + + emitter.setDocument(document); + emitter.emitJavascript(sourceUnit, false); + + return emitter; + }; + + TypeScriptCompiler.prototype._emitDocument = function (document, emitOptions, onSingleFileEmitComplete, sharedEmitter) { + if (this._shouldEmit(document)) { + if (document.emitToOwnOutputFile()) { + var singleEmitter = this.emitDocumentWorker(document, emitOptions); + if (singleEmitter) { + onSingleFileEmitComplete(singleEmitter.getOutputFiles()); + } + } else { + sharedEmitter = this.emitDocumentWorker(document, emitOptions, sharedEmitter); + } + } + + return sharedEmitter; + }; + + TypeScriptCompiler.prototype.emitAll = function (resolvePath) { + var start = new Date().getTime(); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var fileNames = this.fileNames(); + var sharedEmitter = null; + + for (var i = 0, n = fileNames.length; i < n; i++) { + var fileName = fileNames[i]; + + var document = this.getDocument(fileName); + + sharedEmitter = this._emitDocument(document, emitOptions, function (files) { + return emitOutput.outputFiles.push.apply(emitOutput.outputFiles, files); + }, sharedEmitter); + } + + if (sharedEmitter) { + emitOutput.outputFiles.push.apply(emitOutput.outputFiles, sharedEmitter.getOutputFiles()); + } + + TypeScript.emitTime += new Date().getTime() - start; + return emitOutput; + }; + + TypeScriptCompiler.prototype.emit = function (fileName, resolvePath) { + fileName = TypeScript.switchToForwardSlashes(fileName); + var emitOutput = new EmitOutput(); + + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + if (emitOptions.diagnostic()) { + emitOutput.emitOutputResult = 2 /* FailedBecauseOfCompilerOptionsErrors */; + return emitOutput; + } + + var document = this.getDocument(fileName); + + if (document.emitToOwnOutputFile()) { + this._emitDocument(document, emitOptions, function (files) { + return emitOutput.outputFiles.push.apply(emitOutput.outputFiles, files); + }, null); + return emitOutput; + } else { + return this.emitAll(resolvePath); + } + }; + + TypeScriptCompiler.prototype.compile = function (resolvePath, continueOnDiagnostics) { + if (typeof continueOnDiagnostics === "undefined") { continueOnDiagnostics = false; } + return new CompilerIterator(this, resolvePath, continueOnDiagnostics); + }; + + TypeScriptCompiler.prototype.getSyntacticDiagnostics = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + return this.getDocument(fileName).diagnostics(); + }; + + TypeScriptCompiler.prototype.getSyntaxTree = function (fileName) { + return this.getDocument(fileName).syntaxTree(); + }; + + TypeScriptCompiler.prototype.getSourceUnit = function (fileName) { + return this.getDocument(fileName).sourceUnit(); + }; + + TypeScriptCompiler.prototype.getSemanticDiagnostics = function (fileName) { + fileName = TypeScript.switchToForwardSlashes(fileName); + + var document = this.getDocument(fileName); + + var startTime = (new Date()).getTime(); + TypeScript.PullTypeResolver.typeCheck(this.compilationSettings(), this.semanticInfoChain, document); + var endTime = (new Date()).getTime(); + + TypeScript.typeCheckTime += endTime - startTime; + + var errors = this.semanticInfoChain.getDiagnostics(fileName); + + errors = TypeScript.ArrayUtilities.distinct(errors, TypeScript.Diagnostic.equals); + errors.sort(function (d1, d2) { + if (d1.fileName() < d2.fileName()) { + return -1; + } else if (d1.fileName() > d2.fileName()) { + return 1; + } + + if (d1.start() < d2.start()) { + return -1; + } else if (d1.start() > d2.start()) { + return 1; + } + + var code1 = TypeScript.diagnosticInformationMap[d1.diagnosticKey()].code; + var code2 = TypeScript.diagnosticInformationMap[d2.diagnosticKey()].code; + if (code1 < code2) { + return -1; + } else if (code1 > code2) { + return 1; + } + + return 0; + }); + + return errors; + }; + + TypeScriptCompiler.prototype.getCompilerOptionsDiagnostics = function (resolvePath) { + var emitOptions = new TypeScript.EmitOptions(this, resolvePath); + var emitDiagnostic = emitOptions.diagnostic(); + if (emitDiagnostic) { + return [emitDiagnostic]; + } + return TypeScript.sentinelEmptyArray; + }; + + TypeScriptCompiler.prototype.resolveAllFiles = function () { + var fileNames = this.fileNames(); + for (var i = 0, n = fileNames.length; i < n; i++) { + this.getSemanticDiagnostics(fileNames[i]); + } + }; + + TypeScriptCompiler.prototype.getSymbolOfDeclaration = function (decl) { + if (!decl) { + return null; + } + + var resolver = this.semanticInfoChain.getResolver(); + var ast = this.semanticInfoChain.getASTForDecl(decl); + if (!ast) { + return null; + } + + var enclosingDecl = resolver.getEnclosingDecl(decl); + if (ast.kind() === 139 /* GetAccessor */ || ast.kind() === 140 /* SetAccessor */) { + return this.getSymbolOfDeclaration(enclosingDecl); + } + + return resolver.resolveAST(ast, false, new TypeScript.PullTypeResolutionContext(resolver)); + }; + + TypeScriptCompiler.prototype.extractResolutionContextFromAST = function (resolver, ast, document, propagateContextualTypes) { + var scriptName = document.fileName; + + var enclosingDecl = null; + var enclosingDeclAST = null; + var inContextuallyTypedAssignment = false; + var inWithBlock = false; + + var resolutionContext = new TypeScript.PullTypeResolutionContext(resolver); + + if (!ast) { + return null; + } + + var path = this.getASTPath(ast); + + for (var i = 0, n = path.length; i < n; i++) { + var current = path[i]; + + switch (current.kind()) { + case 222 /* FunctionExpression */: + case 219 /* SimpleArrowFunctionExpression */: + case 218 /* ParenthesizedArrowFunctionExpression */: + if (propagateContextualTypes) { + resolver.resolveAST(current, true, resolutionContext); + } + break; + + case 136 /* MemberVariableDeclaration */: + var memberVariable = current; + inContextuallyTypedAssignment = memberVariable.variableDeclarator.typeAnnotation !== null; + + this.extractResolutionContextForVariable(inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, memberVariable, memberVariable.variableDeclarator.equalsValueClause); + break; + + case 225 /* VariableDeclarator */: + var variableDeclarator = current; + inContextuallyTypedAssignment = variableDeclarator.typeAnnotation !== null; + + this.extractResolutionContextForVariable(inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, variableDeclarator, variableDeclarator.equalsValueClause); + break; + + case 213 /* InvocationExpression */: + case 216 /* ObjectCreationExpression */: + if (propagateContextualTypes) { + var isNew = current.kind() === 216 /* ObjectCreationExpression */; + var callExpression = current; + var contextualType = null; + + if ((i + 2 < n) && callExpression.argumentList === path[i + 1] && callExpression.argumentList.arguments === path[i + 2]) { + var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); + if (isNew) { + resolver.resolveObjectCreationExpression(callExpression, resolutionContext, callResolutionResults); + } else { + resolver.resolveInvocationExpression(callExpression, resolutionContext, callResolutionResults); + } + + if (callResolutionResults.actualParametersContextTypeSymbols) { + var argExpression = path[i + 3]; + if (argExpression) { + for (var j = 0, m = callExpression.argumentList.arguments.nonSeparatorCount(); j < m; j++) { + if (callExpression.argumentList.arguments.nonSeparatorAt(j) === argExpression) { + var callContextualType = callResolutionResults.actualParametersContextTypeSymbols[j]; + if (callContextualType) { + contextualType = callContextualType; + break; + } + } + } + } + } + } else { + if (isNew) { + resolver.resolveObjectCreationExpression(callExpression, resolutionContext); + } else { + resolver.resolveInvocationExpression(callExpression, resolutionContext); + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 214 /* ArrayLiteralExpression */: + if (propagateContextualTypes) { + var contextualType = null; + var currentContextualType = resolutionContext.getContextualType(); + if (currentContextualType && currentContextualType.isArrayNamedTypeReference()) { + contextualType = currentContextualType.getElementType(); + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 215 /* ObjectLiteralExpression */: + if (propagateContextualTypes) { + var objectLiteralExpression = current; + var objectLiteralResolutionContext = new TypeScript.PullAdditionalObjectLiteralResolutionData(); + resolver.resolveObjectLiteralExpression(objectLiteralExpression, inContextuallyTypedAssignment, resolutionContext, objectLiteralResolutionContext); + + var memeberAST = (path[i + 1] && path[i + 1].kind() === 2 /* SeparatedList */) ? path[i + 2] : path[i + 1]; + if (memeberAST) { + var contextualType = null; + var memberDecls = objectLiteralExpression.propertyAssignments; + if (memberDecls && objectLiteralResolutionContext.membersContextTypeSymbols) { + for (var j = 0, m = memberDecls.nonSeparatorCount(); j < m; j++) { + if (memberDecls.nonSeparatorAt(j) === memeberAST) { + var memberContextualType = objectLiteralResolutionContext.membersContextTypeSymbols[j]; + if (memberContextualType) { + contextualType = memberContextualType; + break; + } + } + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + } + + break; + + case 174 /* AssignmentExpression */: + if (propagateContextualTypes) { + var assignmentExpression = current; + var contextualType = null; + + if (path[i + 1] && path[i + 1] === assignmentExpression.right) { + var leftType = resolver.resolveAST(assignmentExpression.left, inContextuallyTypedAssignment, resolutionContext).type; + if (leftType) { + inContextuallyTypedAssignment = true; + contextualType = leftType; + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 220 /* CastExpression */: + var castExpression = current; + if (!(i + 1 < n && path[i + 1] === castExpression.type)) { + if (propagateContextualTypes) { + var contextualType = null; + var typeSymbol = resolver.resolveAST(castExpression, inContextuallyTypedAssignment, resolutionContext).type; + + if (typeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = typeSymbol; + } + + resolutionContext.pushNewContextualType(contextualType); + } + } + + break; + + case 150 /* ReturnStatement */: + if (propagateContextualTypes) { + var returnStatement = current; + var contextualType = null; + + if (enclosingDecl && (enclosingDecl.kind & 1032192 /* SomeFunction */)) { + var typeAnnotation = TypeScript.ASTHelpers.getType(enclosingDeclAST); + if (typeAnnotation) { + var returnTypeSymbol = resolver.resolveTypeReference(typeAnnotation, resolutionContext); + if (returnTypeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = returnTypeSymbol; + } + } else { + var currentContextualType = resolutionContext.getContextualType(); + if (currentContextualType && currentContextualType.isFunction()) { + var contextualSignatures = currentContextualType.kind == 33554432 /* ConstructorType */ ? currentContextualType.getConstructSignatures() : currentContextualType.getCallSignatures(); + var currentContextualTypeSignatureSymbol = contextualSignatures[0]; + var currentContextualTypeReturnTypeSymbol = currentContextualTypeSignatureSymbol.returnType; + if (currentContextualTypeReturnTypeSymbol) { + inContextuallyTypedAssignment = true; + contextualType = currentContextualTypeReturnTypeSymbol; + } + } + } + } + + resolutionContext.pushNewContextualType(contextualType); + } + + break; + + case 122 /* ObjectType */: + if (propagateContextualTypes && TypeScript.isTypesOnlyLocation(current)) { + resolver.resolveAST(current, false, resolutionContext); + } + + break; + + case 163 /* WithStatement */: + inWithBlock = true; + break; + + case 146 /* Block */: + inContextuallyTypedAssignment = false; + break; + } + + var decl = this.semanticInfoChain.getDeclForAST(current); + if (decl) { + enclosingDecl = decl; + enclosingDeclAST = current; + } + } + + if (ast && ast.parent && ast.kind() === 11 /* IdentifierName */) { + if (ast.parent.kind() === 212 /* MemberAccessExpression */) { + if (ast.parent.name === ast) { + ast = ast.parent; + } + } else if (ast.parent.kind() === 121 /* QualifiedName */) { + if (ast.parent.right === ast) { + ast = ast.parent; + } + } + } + + return { + ast: ast, + enclosingDecl: enclosingDecl, + resolutionContext: resolutionContext, + inContextuallyTypedAssignment: inContextuallyTypedAssignment, + inWithBlock: inWithBlock + }; + }; + + TypeScriptCompiler.prototype.extractResolutionContextForVariable = function (inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, assigningAST, init) { + if (inContextuallyTypedAssignment) { + if (propagateContextualTypes) { + resolver.resolveAST(assigningAST, false, resolutionContext); + var varSymbol = this.semanticInfoChain.getSymbolForAST(assigningAST); + + var contextualType = null; + if (varSymbol && inContextuallyTypedAssignment) { + contextualType = varSymbol.type; + } + + resolutionContext.pushNewContextualType(contextualType); + + if (init) { + resolver.resolveAST(init, inContextuallyTypedAssignment, resolutionContext); + } + } + } + }; + + TypeScriptCompiler.prototype.getASTPath = function (ast) { + var result = []; + + while (ast) { + result.unshift(ast); + ast = ast.parent; + } + + return result; + }; + + TypeScriptCompiler.prototype.pullGetSymbolInformationFromAST = function (ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + ast = context.ast; + var symbol = resolver.resolveAST(ast, context.inContextuallyTypedAssignment, context.resolutionContext); + + if (!symbol) { + TypeScript.Debug.assert(ast.kind() === 120 /* SourceUnit */, "No symbol was found for ast and ast was not source unit. Ast Kind: " + TypeScript.SyntaxKind[ast.kind()]); + return null; + } + + if (symbol.isTypeReference()) { + symbol = symbol.getReferencedTypeSymbol(); + } + + var aliasSymbol = this.semanticInfoChain.getAliasSymbolForAST(ast); + + return { + symbol: symbol, + aliasSymbol: aliasSymbol, + ast: ast, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetCallInformationFromAST = function (ast, document) { + if (ast.kind() !== 213 /* InvocationExpression */ && ast.kind() !== 216 /* ObjectCreationExpression */) { + return null; + } + + var isNew = ast.kind() === 216 /* ObjectCreationExpression */; + + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var callResolutionResults = new TypeScript.PullAdditionalCallResolutionData(); + + if (isNew) { + resolver.resolveObjectCreationExpression(ast, context.resolutionContext, callResolutionResults); + } else { + resolver.resolveInvocationExpression(ast, context.resolutionContext, callResolutionResults); + } + + return { + targetSymbol: callResolutionResults.targetSymbol, + resolvedSignatures: callResolutionResults.resolvedSignatures, + candidateSignature: callResolutionResults.candidateSignature, + ast: ast, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl), + isConstructorCall: isNew + }; + }; + + TypeScriptCompiler.prototype.pullGetVisibleMemberSymbolsFromAST = function (ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var symbols = resolver.getVisibleMembersFromExpression(ast, context.enclosingDecl, context.resolutionContext); + if (!symbols) { + return null; + } + + return { + symbols: symbols, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetVisibleDeclsFromAST = function (ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, false); + if (!context || context.inWithBlock) { + return null; + } + + return resolver.getVisibleDecls(context.enclosingDecl); + }; + + TypeScriptCompiler.prototype.pullGetContextualMembersFromAST = function (ast, document) { + if (ast.kind() !== 215 /* ObjectLiteralExpression */) { + return null; + } + + var resolver = this.semanticInfoChain.getResolver(); + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var members = resolver.getVisibleContextSymbols(context.enclosingDecl, context.resolutionContext); + + return { + symbols: members, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.pullGetDeclInformation = function (decl, ast, document) { + var resolver = this.semanticInfoChain.getResolver(); + + var context = this.extractResolutionContextFromAST(resolver, ast, document, true); + if (!context || context.inWithBlock) { + return null; + } + + var astForDecl = decl.ast(); + if (!astForDecl) { + return null; + } + + var astForDeclContext = this.extractResolutionContextFromAST(resolver, astForDecl, this.getDocument(astForDecl.fileName()), true); + if (!astForDeclContext) { + return null; + } + + var symbol = decl.getSymbol(); + resolver.resolveDeclaredSymbol(symbol, context.resolutionContext); + symbol.setUnresolved(); + + return { + symbol: symbol, + aliasSymbol: null, + ast: ast, + enclosingScopeSymbol: this.getSymbolOfDeclaration(context.enclosingDecl) + }; + }; + + TypeScriptCompiler.prototype.topLevelDeclaration = function (fileName) { + return this.semanticInfoChain.topLevelDecl(fileName); + }; + + TypeScriptCompiler.prototype.getDeclForAST = function (ast) { + return this.semanticInfoChain.getDeclForAST(ast); + }; + + TypeScriptCompiler.prototype.fileNames = function () { + return this.semanticInfoChain.fileNames(); + }; + + TypeScriptCompiler.prototype.topLevelDecl = function (fileName) { + return this.semanticInfoChain.topLevelDecl(fileName); + }; + + TypeScriptCompiler.getLocationText = function (location, resolvePath) { + return resolvePath(location.fileName()) + "(" + (location.line() + 1) + "," + (location.character() + 1) + ")"; + }; + + TypeScriptCompiler.getFullDiagnosticText = function (diagnostic, resolvePath) { + var result = ""; + if (diagnostic.fileName()) { + result += this.getLocationText(diagnostic, resolvePath) + ": "; + } + + result += diagnostic.message(); + + var additionalLocations = diagnostic.additionalLocations(); + if (additionalLocations.length > 0) { + result += " " + TypeScript.getLocalizedText(TypeScript.DiagnosticCode.Additional_locations, null) + TypeScript.Environment.newLine; + + for (var i = 0, n = additionalLocations.length; i < n; i++) { + result += "\t" + this.getLocationText(additionalLocations[i], resolvePath) + TypeScript.Environment.newLine; + } + } else { + result += TypeScript.Environment.newLine; + } + + return result; + }; + return TypeScriptCompiler; + })(); + TypeScript.TypeScriptCompiler = TypeScriptCompiler; + + var CompilerPhase; + (function (CompilerPhase) { + CompilerPhase[CompilerPhase["Syntax"] = 0] = "Syntax"; + CompilerPhase[CompilerPhase["Semantics"] = 1] = "Semantics"; + CompilerPhase[CompilerPhase["EmitOptionsValidation"] = 2] = "EmitOptionsValidation"; + CompilerPhase[CompilerPhase["Emit"] = 3] = "Emit"; + CompilerPhase[CompilerPhase["DeclarationEmit"] = 4] = "DeclarationEmit"; + })(CompilerPhase || (CompilerPhase = {})); + + var CompilerIterator = (function () { + function CompilerIterator(compiler, resolvePath, continueOnDiagnostics, startingPhase) { + if (typeof startingPhase === "undefined") { startingPhase = 0 /* Syntax */; } + this.compiler = compiler; + this.resolvePath = resolvePath; + this.continueOnDiagnostics = continueOnDiagnostics; + this.index = -1; + this.fileNames = null; + this._current = null; + this._emitOptions = null; + this._sharedEmitter = null; + this._sharedDeclarationEmitter = null; + this.hadSyntacticDiagnostics = false; + this.hadSemanticDiagnostics = false; + this.hadEmitDiagnostics = false; + this.fileNames = compiler.fileNames(); + this.compilerPhase = startingPhase; + } + CompilerIterator.prototype.current = function () { + return this._current; + }; + + CompilerIterator.prototype.moveNext = function () { + this._current = null; + + while (this.moveNextInternal()) { + if (this._current) { + return true; + } + } + + return false; + }; + + CompilerIterator.prototype.moveNextInternal = function () { + this.index++; + + while (this.shouldMoveToNextPhase()) { + this.index = 0; + this.compilerPhase++; + } + + if (this.compilerPhase > 4 /* DeclarationEmit */) { + return false; + } + + switch (this.compilerPhase) { + case 0 /* Syntax */: + return this.moveNextSyntaxPhase(); + case 1 /* Semantics */: + return this.moveNextSemanticsPhase(); + case 2 /* EmitOptionsValidation */: + return this.moveNextEmitOptionsValidationPhase(); + case 3 /* Emit */: + return this.moveNextEmitPhase(); + case 4 /* DeclarationEmit */: + return this.moveNextDeclarationEmitPhase(); + } + }; + + CompilerIterator.prototype.shouldMoveToNextPhase = function () { + switch (this.compilerPhase) { + case 2 /* EmitOptionsValidation */: + return this.index === 1; + + case 0 /* Syntax */: + case 1 /* Semantics */: + return this.index === this.fileNames.length; + + case 3 /* Emit */: + case 4 /* DeclarationEmit */: + return this.index === (this.fileNames.length + 1); + } + + return false; + }; + + CompilerIterator.prototype.moveNextSyntaxPhase = function () { + TypeScript.Debug.assert(this.index >= 0 && this.index < this.fileNames.length); + var fileName = this.fileNames[this.index]; + + var diagnostics = this.compiler.getSyntacticDiagnostics(fileName); + if (diagnostics.length) { + if (!this.continueOnDiagnostics) { + this.hadSyntacticDiagnostics = true; + } + + this._current = CompileResult.fromDiagnostics(diagnostics); + } + + return true; + }; + + CompilerIterator.prototype.moveNextSemanticsPhase = function () { + if (this.hadSyntacticDiagnostics) { + return false; + } + + TypeScript.Debug.assert(this.index >= 0 && this.index < this.fileNames.length); + var fileName = this.fileNames[this.index]; + var diagnostics = this.compiler.getSemanticDiagnostics(fileName); + if (diagnostics.length) { + if (!this.continueOnDiagnostics) { + this.hadSemanticDiagnostics = true; + } + + this._current = CompileResult.fromDiagnostics(diagnostics); + } + + return true; + }; + + CompilerIterator.prototype.moveNextEmitOptionsValidationPhase = function () { + TypeScript.Debug.assert(!this.hadSyntacticDiagnostics); + + if (!this._emitOptions) { + this._emitOptions = new TypeScript.EmitOptions(this.compiler, this.resolvePath); + } + + if (this._emitOptions.diagnostic()) { + if (!this.continueOnDiagnostics) { + this.hadEmitDiagnostics = true; + } + + this._current = CompileResult.fromDiagnostics([this._emitOptions.diagnostic()]); + } + + return true; + }; + + CompilerIterator.prototype.moveNextEmitPhase = function () { + var _this = this; + TypeScript.Debug.assert(!this.hadSyntacticDiagnostics); + TypeScript.Debug.assert(this._emitOptions); + + if (this.hadEmitDiagnostics) { + return false; + } + + TypeScript.Debug.assert(this.index >= 0 && this.index <= this.fileNames.length); + if (this.index < this.fileNames.length) { + var fileName = this.fileNames[this.index]; + var document = this.compiler.getDocument(fileName); + + this._sharedEmitter = this.compiler._emitDocument(document, this._emitOptions, function (outputFiles) { + _this._current = CompileResult.fromOutputFiles(outputFiles); + }, this._sharedEmitter); + return true; + } + + if (this.index === this.fileNames.length && this._sharedEmitter) { + this._current = CompileResult.fromOutputFiles(this._sharedEmitter.getOutputFiles()); + } + + return true; + }; + + CompilerIterator.prototype.moveNextDeclarationEmitPhase = function () { + var _this = this; + TypeScript.Debug.assert(!this.hadSyntacticDiagnostics); + TypeScript.Debug.assert(!this.hadEmitDiagnostics); + if (this.hadSemanticDiagnostics) { + return false; + } + + if (!this.compiler.compilationSettings().generateDeclarationFiles()) { + return false; + } + + TypeScript.Debug.assert(this.index >= 0 && this.index <= this.fileNames.length); + if (this.index < this.fileNames.length) { + var fileName = this.fileNames[this.index]; + var document = this.compiler.getDocument(fileName); + + this._sharedDeclarationEmitter = this.compiler._emitDocumentDeclarations(document, this._emitOptions, function (file) { + _this._current = CompileResult.fromOutputFiles([file]); + }, this._sharedDeclarationEmitter); + return true; + } + + if (this.index === this.fileNames.length && this._sharedDeclarationEmitter) { + this._current = CompileResult.fromOutputFiles([this._sharedDeclarationEmitter.getOutputFile()]); + } + + return true; + }; + return CompilerIterator; + })(); + + function compareDataObjects(dst, src) { + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) + return false; + } else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) + return false; + } + } + return true; + } + TypeScript.compareDataObjects = compareDataObjects; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (GenerativeTypeClassification) { + GenerativeTypeClassification[GenerativeTypeClassification["Unknown"] = 0] = "Unknown"; + GenerativeTypeClassification[GenerativeTypeClassification["Open"] = 1] = "Open"; + GenerativeTypeClassification[GenerativeTypeClassification["Closed"] = 2] = "Closed"; + GenerativeTypeClassification[GenerativeTypeClassification["InfinitelyExpanding"] = 3] = "InfinitelyExpanding"; + })(TypeScript.GenerativeTypeClassification || (TypeScript.GenerativeTypeClassification = {})); + var GenerativeTypeClassification = TypeScript.GenerativeTypeClassification; + + var PullTypeReferenceSymbol = (function (_super) { + __extends(PullTypeReferenceSymbol, _super); + function PullTypeReferenceSymbol(referencedTypeSymbol) { + _super.call(this, referencedTypeSymbol.name, referencedTypeSymbol.kind); + this.referencedTypeSymbol = referencedTypeSymbol; + this.isResolved = true; + + TypeScript.Debug.assert(referencedTypeSymbol !== null, "Type root symbol may not be null"); + + this.setRootSymbol(referencedTypeSymbol); + + this.typeReference = this; + } + PullTypeReferenceSymbol.createTypeReference = function (type) { + if (type.isTypeReference()) { + return type; + } + + var typeReference = type.typeReference; + + if (!typeReference) { + typeReference = new PullTypeReferenceSymbol(type); + type.typeReference = typeReference; + } + + return typeReference; + }; + + PullTypeReferenceSymbol.prototype.isTypeReference = function () { + return true; + }; + + PullTypeReferenceSymbol.prototype.setResolved = function () { + }; + + PullTypeReferenceSymbol.prototype.setUnresolved = function () { + }; + PullTypeReferenceSymbol.prototype.invalidate = function () { + }; + + PullTypeReferenceSymbol.prototype.ensureReferencedTypeIsResolved = function () { + this._getResolver().resolveDeclaredSymbol(this.referencedTypeSymbol); + }; + + PullTypeReferenceSymbol.prototype.getReferencedTypeSymbol = function () { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol; + }; + + PullTypeReferenceSymbol.prototype._getResolver = function () { + return this.referencedTypeSymbol._getResolver(); + }; + + PullTypeReferenceSymbol.prototype.hasMembers = function () { + return this.referencedTypeSymbol.hasMembers(); + }; + + PullTypeReferenceSymbol.prototype.setAssociatedContainerType = function (type) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": setAssociatedContainerType"); + }; + + PullTypeReferenceSymbol.prototype.getAssociatedContainerType = function () { + return this.referencedTypeSymbol.getAssociatedContainerType(); + }; + + PullTypeReferenceSymbol.prototype.getFunctionSymbol = function () { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.getFunctionSymbol(); + }; + PullTypeReferenceSymbol.prototype.setFunctionSymbol = function (symbol) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": setFunctionSymbol"); + }; + + PullTypeReferenceSymbol.prototype.addContainedNonMember = function (nonMember) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addContainedNonMember"); + }; + PullTypeReferenceSymbol.prototype.findContainedNonMemberContainer = function (containerName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.findContainedNonMemberContainer(containerName, kind); + }; + + PullTypeReferenceSymbol.prototype.addMember = function (memberSymbol) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addMember"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedMemberType = function (enclosedType) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedMemberType"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedMemberContainer = function (enclosedContainer) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedMemberContainer"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedNonMember = function (enclosedNonMember) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedNonMember"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedNonMemberType = function (enclosedNonMemberType) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedNonMemberType"); + }; + PullTypeReferenceSymbol.prototype.addEnclosedNonMemberContainer = function (enclosedNonMemberContainer) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addEnclosedNonMemberContainer"); + }; + PullTypeReferenceSymbol.prototype.addTypeParameter = function (typeParameter) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addTypeParameter"); + }; + PullTypeReferenceSymbol.prototype.addConstructorTypeParameter = function (typeParameter) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addConstructorTypeParameter"); + }; + + PullTypeReferenceSymbol.prototype.findContainedNonMember = function (name) { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findContainedNonMember(name); + }; + + PullTypeReferenceSymbol.prototype.findContainedNonMemberType = function (typeName, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findContainedNonMemberType(typeName, kind); + }; + + PullTypeReferenceSymbol.prototype.getMembers = function () { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.getMembers(); + }; + + PullTypeReferenceSymbol.prototype.setHasDefaultConstructor = function (hasOne) { + if (typeof hasOne === "undefined") { hasOne = true; } + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ":setHasDefaultConstructor"); + }; + PullTypeReferenceSymbol.prototype.getHasDefaultConstructor = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getHasDefaultConstructor(); + }; + PullTypeReferenceSymbol.prototype.getConstructorMethod = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getConstructorMethod(); + }; + PullTypeReferenceSymbol.prototype.setConstructorMethod = function (constructorMethod) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": setConstructorMethod"); + }; + PullTypeReferenceSymbol.prototype.getTypeParameters = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypeParameters(); + }; + + PullTypeReferenceSymbol.prototype.isGeneric = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.isGeneric(); + }; + + PullTypeReferenceSymbol.prototype.addSpecialization = function (specializedVersionOfThisType, substitutingTypes) { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.addSpecialization(specializedVersionOfThisType, substitutingTypes); + }; + PullTypeReferenceSymbol.prototype.getSpecialization = function (substitutingTypes) { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getSpecialization(substitutingTypes); + }; + PullTypeReferenceSymbol.prototype.getKnownSpecializations = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getKnownSpecializations(); + }; + PullTypeReferenceSymbol.prototype.getTypeArguments = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypeArguments(); + }; + PullTypeReferenceSymbol.prototype.getTypeArgumentsOrTypeParameters = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypeArgumentsOrTypeParameters(); + }; + + PullTypeReferenceSymbol.prototype.appendCallSignature = function (callSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": appendCallSignature"); + }; + PullTypeReferenceSymbol.prototype.insertCallSignatureAtIndex = function (callSignature, index) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": insertCallSignatureAtIndex"); + }; + PullTypeReferenceSymbol.prototype.appendConstructSignature = function (callSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": appendConstructSignature"); + }; + PullTypeReferenceSymbol.prototype.insertConstructSignatureAtIndex = function (callSignature, index) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": insertConstructSignatureAtIndex"); + }; + PullTypeReferenceSymbol.prototype.addIndexSignature = function (indexSignature) { + TypeScript.Debug.fail("Reference symbol " + this.pullSymbolID + ": addIndexSignature"); + }; + + PullTypeReferenceSymbol.prototype.hasOwnCallSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.hasOwnCallSignatures(); + }; + PullTypeReferenceSymbol.prototype.getCallSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getCallSignatures(); + }; + PullTypeReferenceSymbol.prototype.hasOwnConstructSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.hasOwnConstructSignatures(); + }; + PullTypeReferenceSymbol.prototype.getConstructSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getConstructSignatures(); + }; + PullTypeReferenceSymbol.prototype.hasOwnIndexSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.hasOwnIndexSignatures(); + }; + PullTypeReferenceSymbol.prototype.getIndexSignatures = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getIndexSignatures(); + }; + + PullTypeReferenceSymbol.prototype.addImplementedType = function (implementedType) { + this.referencedTypeSymbol.addImplementedType(implementedType); + }; + PullTypeReferenceSymbol.prototype.getImplementedTypes = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getImplementedTypes(); + }; + PullTypeReferenceSymbol.prototype.addExtendedType = function (extendedType) { + this.referencedTypeSymbol.addExtendedType(extendedType); + }; + PullTypeReferenceSymbol.prototype.getExtendedTypes = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getExtendedTypes(); + }; + PullTypeReferenceSymbol.prototype.addTypeThatExtendsThisType = function (type) { + this.referencedTypeSymbol.addTypeThatExtendsThisType(type); + }; + PullTypeReferenceSymbol.prototype.getTypesThatExtendThisType = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypesThatExtendThisType(); + }; + PullTypeReferenceSymbol.prototype.addTypeThatExplicitlyImplementsThisType = function (type) { + this.referencedTypeSymbol.addTypeThatExplicitlyImplementsThisType(type); + }; + PullTypeReferenceSymbol.prototype.getTypesThatExplicitlyImplementThisType = function () { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.getTypesThatExplicitlyImplementThisType(); + }; + + PullTypeReferenceSymbol.prototype.isValidBaseKind = function (baseType, isExtendedType) { + this.ensureReferencedTypeIsResolved(); + return this.referencedTypeSymbol.isValidBaseKind(baseType, isExtendedType); + }; + + PullTypeReferenceSymbol.prototype.findMember = function (name, lookInParent) { + if (typeof lookInParent === "undefined") { lookInParent = true; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findMember(name, lookInParent); + }; + PullTypeReferenceSymbol.prototype.findNestedType = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findNestedType(name, kind); + }; + PullTypeReferenceSymbol.prototype.findNestedContainer = function (name, kind) { + if (typeof kind === "undefined") { kind = 0 /* None */; } + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findNestedContainer(name, kind); + }; + PullTypeReferenceSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisiblity) { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.getAllMembers(searchDeclKind, memberVisiblity); + }; + + PullTypeReferenceSymbol.prototype.findTypeParameter = function (name) { + this.ensureReferencedTypeIsResolved(); + + return this.referencedTypeSymbol.findTypeParameter(name); + }; + + PullTypeReferenceSymbol.prototype.hasOnlyOverloadCallSignatures = function () { + return this.referencedTypeSymbol.hasOnlyOverloadCallSignatures(); + }; + return PullTypeReferenceSymbol; + })(TypeScript.PullTypeSymbol); + TypeScript.PullTypeReferenceSymbol = PullTypeReferenceSymbol; + + TypeScript.nSpecializationsCreated = 0; + TypeScript.nSpecializedSignaturesCreated = 0; + TypeScript.nSpecializedTypeParameterCreated = 0; + + var PullInstantiatedTypeReferenceSymbol = (function (_super) { + __extends(PullInstantiatedTypeReferenceSymbol, _super); + function PullInstantiatedTypeReferenceSymbol(referencedTypeSymbol, _typeParameterArgumentMap, isInstanceReferenceType) { + _super.call(this, referencedTypeSymbol); + this.referencedTypeSymbol = referencedTypeSymbol; + this._typeParameterArgumentMap = _typeParameterArgumentMap; + this.isInstanceReferenceType = isInstanceReferenceType; + this._instantiatedMembers = null; + this._allInstantiatedMemberNameCache = null; + this._instantiatedMemberNameCache = TypeScript.createIntrinsicsObject(); + this._instantiatedCallSignatures = null; + this._instantiatedConstructSignatures = null; + this._instantiatedIndexSignatures = null; + this._typeArgumentReferences = undefined; + this._instantiatedConstructorMethod = null; + this._instantiatedAssociatedContainerType = null; + this._isArray = undefined; + this._generativeTypeClassification = []; + + TypeScript.nSpecializationsCreated++; + } + PullInstantiatedTypeReferenceSymbol.prototype.getIsSpecialized = function () { + return !this.isInstanceReferenceType; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getGenerativeTypeClassification = function (enclosingType) { + if (!this.isNamedTypeSymbol()) { + return 0 /* Unknown */; + } + + var generativeTypeClassification = this._generativeTypeClassification[enclosingType.pullSymbolID] || 0 /* Unknown */; + if (generativeTypeClassification === 0 /* Unknown */) { + var typeParameters = enclosingType.getTypeParameters(); + var enclosingTypeParameterMap = []; + for (var i = 0; i < typeParameters.length; i++) { + enclosingTypeParameterMap[typeParameters[i].pullSymbolID] = typeParameters[i]; + } + + var typeArguments = this.getTypeArguments(); + for (var i = 0; i < typeArguments.length; i++) { + if (typeArguments[i].wrapsSomeTypeParameter(enclosingTypeParameterMap, true)) { + generativeTypeClassification = 1 /* Open */; + break; + } + } + + if (generativeTypeClassification === 1 /* Open */) { + if (this.wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType)) { + generativeTypeClassification = 3 /* InfinitelyExpanding */; + } + } else { + generativeTypeClassification = 2 /* Closed */; + } + + this._generativeTypeClassification[enclosingType.pullSymbolID] = generativeTypeClassification; + } + + return generativeTypeClassification; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.isArrayNamedTypeReference = function () { + if (this._isArray === undefined) { + this._isArray = this.getRootSymbol().isArrayNamedTypeReference() || (this.getRootSymbol() === this._getResolver().getArrayNamedType()); + } + return this._isArray; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getElementType = function () { + if (!this.isArrayNamedTypeReference()) { + return null; + } + + var typeArguments = this.getTypeArguments(); + return typeArguments ? typeArguments[0] : null; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getReferencedTypeSymbol = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.getIsSpecialized()) { + return this; + } + + return this.referencedTypeSymbol; + }; + + PullInstantiatedTypeReferenceSymbol.create = function (resolver, type, typeParameterArgumentMap) { + TypeScript.Debug.assert(resolver); + + var mutableTypeParameterMap = new TypeScript.PullInstantiationHelpers.MutableTypeArgumentMap(typeParameterArgumentMap); + + TypeScript.PullInstantiationHelpers.instantiateTypeArgument(resolver, type, mutableTypeParameterMap); + + var rootType = type.getRootSymbol(); + var instantiation = rootType.getSpecialization(mutableTypeParameterMap.typeParameterArgumentMap); + if (instantiation) { + return instantiation; + } + + TypeScript.PullInstantiationHelpers.cleanUpTypeArgumentMap(type, mutableTypeParameterMap); + typeParameterArgumentMap = mutableTypeParameterMap.typeParameterArgumentMap; + + var isInstanceReferenceType = (type.kind & 8216 /* SomeInstantiatableType */) != 0; + var resolvedTypeParameterArgumentMap = typeParameterArgumentMap; + if (isInstanceReferenceType) { + var typeParameters = rootType.getTypeParameters(); + for (var i = 0; i < typeParameters.length; i++) { + if (!TypeScript.PullHelpers.typeSymbolsAreIdentical(typeParameters[i], typeParameterArgumentMap[typeParameters[i].pullSymbolID])) { + isInstanceReferenceType = false; + break; + } + } + + if (isInstanceReferenceType) { + typeParameterArgumentMap = []; + } + } + + instantiation = new PullInstantiatedTypeReferenceSymbol(rootType, typeParameterArgumentMap, isInstanceReferenceType); + + rootType.addSpecialization(instantiation, resolvedTypeParameterArgumentMap); + + return instantiation; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.isGeneric = function () { + return this.getRootSymbol().isGeneric(); + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getTypeParameterArgumentMap = function () { + return this._typeParameterArgumentMap; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getTypeArguments = function () { + if (this.isInstanceReferenceType) { + return this.getTypeParameters(); + } + + if (this._typeArgumentReferences === undefined) { + var typeParameters = this.referencedTypeSymbol.getTypeParameters(); + + if (typeParameters.length) { + var typeArgument = null; + var typeArguments = []; + + for (var i = 0; i < typeParameters.length; i++) { + typeArgument = this._typeParameterArgumentMap[typeParameters[i].pullSymbolID]; + + if (!typeArgument) { + TypeScript.Debug.fail("type argument count mismatch"); + } + + if (typeArgument) { + typeArguments[typeArguments.length] = typeArgument; + } + } + + this._typeArgumentReferences = typeArguments; + } else { + this._typeArgumentReferences = null; + } + } + + return this._typeArgumentReferences; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getTypeArgumentsOrTypeParameters = function () { + return this.getTypeArguments(); + }; + + PullInstantiatedTypeReferenceSymbol.prototype.populateInstantiatedMemberFromReferencedMember = function (referencedMember) { + var instantiatedMember; + TypeScript.PullHelpers.resolveDeclaredSymbolToUseType(referencedMember); + + if (!referencedMember.type.wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + instantiatedMember = referencedMember; + } else { + instantiatedMember = new TypeScript.PullSymbol(referencedMember.name, referencedMember.kind); + instantiatedMember.setRootSymbol(referencedMember); + instantiatedMember.type = this._getResolver().instantiateType(referencedMember.type, this._typeParameterArgumentMap); + instantiatedMember.isOptional = referencedMember.isOptional; + } + this._instantiatedMemberNameCache[instantiatedMember.name] = instantiatedMember; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getMembers = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getMembers(); + } + + if (!this._instantiatedMembers) { + var referencedMembers = this.referencedTypeSymbol.getMembers(); + var referencedMember = null; + var instantiatedMember = null; + + this._instantiatedMembers = []; + + for (var i = 0; i < referencedMembers.length; i++) { + referencedMember = referencedMembers[i]; + + this._getResolver().resolveDeclaredSymbol(referencedMember); + + if (!this._instantiatedMemberNameCache[referencedMember.name]) { + this.populateInstantiatedMemberFromReferencedMember(referencedMember); + } + + this._instantiatedMembers[this._instantiatedMembers.length] = this._instantiatedMemberNameCache[referencedMember.name]; + } + } + + return this._instantiatedMembers; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.findMember = function (name, lookInParent) { + if (typeof lookInParent === "undefined") { lookInParent = true; } + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.findMember(name, lookInParent); + } + + var memberSymbol = this._instantiatedMemberNameCache[name]; + + if (!memberSymbol) { + var referencedMemberSymbol = this.referencedTypeSymbol.findMember(name, lookInParent); + + if (referencedMemberSymbol) { + this.populateInstantiatedMemberFromReferencedMember(referencedMemberSymbol); + memberSymbol = this._instantiatedMemberNameCache[name]; + } else { + memberSymbol = null; + } + } + + return memberSymbol; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getAllMembers = function (searchDeclKind, memberVisiblity) { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getAllMembers(searchDeclKind, memberVisiblity); + } + + var requestedMembers = []; + var allReferencedMembers = this.referencedTypeSymbol.getAllMembers(searchDeclKind, memberVisiblity); + + if (!this._allInstantiatedMemberNameCache) { + this._allInstantiatedMemberNameCache = TypeScript.createIntrinsicsObject(); + + var members = this.getMembers(); + + for (var i = 0; i < members.length; i++) { + this._allInstantiatedMemberNameCache[members[i].name] = members[i]; + } + } + + var referencedMember = null; + var requestedMember = null; + + for (var i = 0; i < allReferencedMembers.length; i++) { + referencedMember = allReferencedMembers[i]; + + this._getResolver().resolveDeclaredSymbol(referencedMember); + + if (this._allInstantiatedMemberNameCache[referencedMember.name]) { + requestedMembers[requestedMembers.length] = this._allInstantiatedMemberNameCache[referencedMember.name]; + } else { + if (!referencedMember.type.wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._allInstantiatedMemberNameCache[referencedMember.name] = referencedMember; + requestedMembers[requestedMembers.length] = referencedMember; + } else { + requestedMember = new TypeScript.PullSymbol(referencedMember.name, referencedMember.kind); + requestedMember.setRootSymbol(referencedMember); + + requestedMember.type = this._getResolver().instantiateType(referencedMember.type, this._typeParameterArgumentMap); + requestedMember.isOptional = referencedMember.isOptional; + + this._allInstantiatedMemberNameCache[requestedMember.name] = requestedMember; + requestedMembers[requestedMembers.length] = requestedMember; + } + } + } + + return requestedMembers; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getConstructorMethod = function () { + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getConstructorMethod(); + } + + if (!this._instantiatedConstructorMethod) { + var referencedConstructorMethod = this.referencedTypeSymbol.getConstructorMethod(); + this._instantiatedConstructorMethod = new TypeScript.PullSymbol(referencedConstructorMethod.name, referencedConstructorMethod.kind); + this._instantiatedConstructorMethod.setRootSymbol(referencedConstructorMethod); + this._instantiatedConstructorMethod.setResolved(); + + this._instantiatedConstructorMethod.type = PullInstantiatedTypeReferenceSymbol.create(this._getResolver(), referencedConstructorMethod.type, this._typeParameterArgumentMap); + } + + return this._instantiatedConstructorMethod; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getAssociatedContainerType = function () { + if (!this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getAssociatedContainerType(); + } + + if (!this._instantiatedAssociatedContainerType) { + var referencedAssociatedContainerType = this.referencedTypeSymbol.getAssociatedContainerType(); + + if (referencedAssociatedContainerType) { + this._instantiatedAssociatedContainerType = PullInstantiatedTypeReferenceSymbol.create(this._getResolver(), referencedAssociatedContainerType, this._typeParameterArgumentMap); + } + } + + return this._instantiatedAssociatedContainerType; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getCallSignatures = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getCallSignatures(); + } + + if (this._instantiatedCallSignatures) { + return this._instantiatedCallSignatures; + } + + var referencedCallSignatures = this.referencedTypeSymbol.getCallSignatures(); + this._instantiatedCallSignatures = []; + + for (var i = 0; i < referencedCallSignatures.length; i++) { + this._getResolver().resolveDeclaredSymbol(referencedCallSignatures[i]); + + if (!referencedCallSignatures[i].wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._instantiatedCallSignatures[this._instantiatedCallSignatures.length] = referencedCallSignatures[i]; + } else { + this._instantiatedCallSignatures[this._instantiatedCallSignatures.length] = this._getResolver().instantiateSignature(referencedCallSignatures[i], this._typeParameterArgumentMap); + this._instantiatedCallSignatures[this._instantiatedCallSignatures.length - 1].functionType = this; + } + } + + return this._instantiatedCallSignatures; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getConstructSignatures = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getConstructSignatures(); + } + + if (this._instantiatedConstructSignatures) { + return this._instantiatedConstructSignatures; + } + + var referencedConstructSignatures = this.referencedTypeSymbol.getConstructSignatures(); + this._instantiatedConstructSignatures = []; + + for (var i = 0; i < referencedConstructSignatures.length; i++) { + this._getResolver().resolveDeclaredSymbol(referencedConstructSignatures[i]); + + if (!referencedConstructSignatures[i].wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._instantiatedConstructSignatures[this._instantiatedConstructSignatures.length] = referencedConstructSignatures[i]; + } else { + this._instantiatedConstructSignatures[this._instantiatedConstructSignatures.length] = this._getResolver().instantiateSignature(referencedConstructSignatures[i], this._typeParameterArgumentMap); + this._instantiatedConstructSignatures[this._instantiatedConstructSignatures.length - 1].functionType = this; + } + } + + return this._instantiatedConstructSignatures; + }; + + PullInstantiatedTypeReferenceSymbol.prototype.getIndexSignatures = function () { + this.ensureReferencedTypeIsResolved(); + + if (this.isInstanceReferenceType) { + return this.referencedTypeSymbol.getIndexSignatures(); + } + + if (this._instantiatedIndexSignatures) { + return this._instantiatedIndexSignatures; + } + + var referencedIndexSignatures = this.referencedTypeSymbol.getIndexSignatures(); + this._instantiatedIndexSignatures = []; + + for (var i = 0; i < referencedIndexSignatures.length; i++) { + this._getResolver().resolveDeclaredSymbol(referencedIndexSignatures[i]); + + if (!referencedIndexSignatures[i].wrapsSomeTypeParameter(this._typeParameterArgumentMap)) { + this._instantiatedIndexSignatures[this._instantiatedIndexSignatures.length] = referencedIndexSignatures[i]; + } else { + this._instantiatedIndexSignatures[this._instantiatedIndexSignatures.length] = this._getResolver().instantiateSignature(referencedIndexSignatures[i], this._typeParameterArgumentMap); + this._instantiatedIndexSignatures[this._instantiatedIndexSignatures.length - 1].functionType = this; + } + } + + return this._instantiatedIndexSignatures; + }; + return PullInstantiatedTypeReferenceSymbol; + })(PullTypeReferenceSymbol); + TypeScript.PullInstantiatedTypeReferenceSymbol = PullInstantiatedTypeReferenceSymbol; + + var PullInstantiatedSignatureSymbol = (function (_super) { + __extends(PullInstantiatedSignatureSymbol, _super); + function PullInstantiatedSignatureSymbol(rootSignature, _typeParameterArgumentMap) { + _super.call(this, rootSignature.kind, rootSignature.isDefinition()); + this._typeParameterArgumentMap = _typeParameterArgumentMap; + this.setRootSymbol(rootSignature); + TypeScript.nSpecializedSignaturesCreated++; + + rootSignature.addSpecialization(this, _typeParameterArgumentMap); + } + PullInstantiatedSignatureSymbol.prototype.getTypeParameterArgumentMap = function () { + return this._typeParameterArgumentMap; + }; + + PullInstantiatedSignatureSymbol.prototype.getIsSpecialized = function () { + return true; + }; + + PullInstantiatedSignatureSymbol.prototype._getResolver = function () { + return this.getRootSymbol()._getResolver(); + }; + + PullInstantiatedSignatureSymbol.prototype.getTypeParameters = function () { + var _this = this; + if (!this._typeParameters) { + var rootSymbol = this.getRootSymbol(); + var typeParameters = rootSymbol.getTypeParameters(); + var hasInstantiatedTypeParametersOfThisSignature = TypeScript.ArrayUtilities.all(typeParameters, function (typeParameter) { + return _this._typeParameterArgumentMap[typeParameter.pullSymbolID] !== undefined; + }); + + if (!hasInstantiatedTypeParametersOfThisSignature && typeParameters.length) { + this._typeParameters = []; + for (var i = 0; i < typeParameters.length; i++) { + this._typeParameters[this._typeParameters.length] = this._getResolver().instantiateTypeParameter(typeParameters[i], this._typeParameterArgumentMap); + } + } else { + this._typeParameters = TypeScript.sentinelEmptyArray; + } + } + + return this._typeParameters; + }; + + PullInstantiatedSignatureSymbol.prototype.getAllowedToReferenceTypeParameters = function () { + var rootSymbol = this.getRootSymbol(); + return rootSymbol.getAllowedToReferenceTypeParameters(); + }; + return PullInstantiatedSignatureSymbol; + })(TypeScript.PullSignatureSymbol); + TypeScript.PullInstantiatedSignatureSymbol = PullInstantiatedSignatureSymbol; + + var PullInstantiatedTypeParameterSymbol = (function (_super) { + __extends(PullInstantiatedTypeParameterSymbol, _super); + function PullInstantiatedTypeParameterSymbol(rootTypeParameter, constraintType) { + _super.call(this, rootTypeParameter.name); + TypeScript.nSpecializedTypeParameterCreated++; + + this.setRootSymbol(rootTypeParameter); + this.setConstraint(constraintType); + + rootTypeParameter.addSpecialization(this, [constraintType]); + } + PullInstantiatedTypeParameterSymbol.prototype._getResolver = function () { + return this.getRootSymbol()._getResolver(); + }; + return PullInstantiatedTypeParameterSymbol; + })(TypeScript.PullTypeParameterSymbol); + TypeScript.PullInstantiatedTypeParameterSymbol = PullInstantiatedTypeParameterSymbol; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SyntaxTreeToAstVisitor = (function () { + function SyntaxTreeToAstVisitor(fileName, lineMap, compilationSettings) { + this.fileName = fileName; + this.lineMap = lineMap; + this.compilationSettings = compilationSettings; + this.position = 0; + this.previousTokenTrailingComments = null; + } + SyntaxTreeToAstVisitor.visit = function (syntaxTree, fileName, compilationSettings, incrementalAST) { + var visitor = incrementalAST ? new SyntaxTreeToIncrementalAstVisitor(fileName, syntaxTree.lineMap(), compilationSettings) : new SyntaxTreeToAstVisitor(fileName, syntaxTree.lineMap(), compilationSettings); + return syntaxTree.sourceUnit().accept(visitor); + }; + + SyntaxTreeToAstVisitor.prototype.movePast = function (element) { + if (element !== null) { + this.position += element.fullWidth(); + } + }; + + SyntaxTreeToAstVisitor.prototype.moveTo = function (element1, element2) { + if (element2 !== null) { + this.position += TypeScript.Syntax.childOffset(element1, element2); + } + }; + + SyntaxTreeToAstVisitor.prototype.setCommentsAndSpan = function (ast, fullStart, node) { + var firstToken = node.firstToken(); + var lastToken = node.lastToken(); + + this.setSpan(ast, fullStart, node, firstToken, lastToken); + ast.setPreComments(this.convertTokenLeadingComments(firstToken, fullStart)); + ast.setPostComments(this.convertNodeTrailingComments(node, lastToken, fullStart)); + }; + + SyntaxTreeToAstVisitor.prototype.createTokenSpan = function (fullStart, element) { + if (element === null) { + return null; + } + + if (element.fullWidth() === 0) { + return new TypeScript.ASTSpan(-1, -1); + } + + var leadingTriviaWidth = element.leadingTriviaWidth(); + var trailingTriviaWidth = element.trailingTriviaWidth(); + + var start = fullStart + leadingTriviaWidth; + var end = fullStart + element.fullWidth() - trailingTriviaWidth; + + return new TypeScript.ASTSpan(start, end); + }; + + SyntaxTreeToAstVisitor.prototype.setSpan = function (span, fullStart, element, firstToken, lastToken) { + if (typeof firstToken === "undefined") { firstToken = element.firstToken(); } + if (typeof lastToken === "undefined") { lastToken = element.lastToken(); } + var leadingTriviaWidth = firstToken ? firstToken.leadingTriviaWidth() : 0; + var trailingTriviaWidth = lastToken ? lastToken.trailingTriviaWidth() : 0; + + var desiredMinChar = fullStart + leadingTriviaWidth; + var desiredLimChar = fullStart + element.fullWidth() - trailingTriviaWidth; + + this.setSpanExplicit(span, desiredMinChar, desiredLimChar); + + span._trailingTriviaWidth = trailingTriviaWidth; + }; + + SyntaxTreeToAstVisitor.prototype.setSpanExplicit = function (span, start, end) { + span._start = start; + span._end = end; + }; + + SyntaxTreeToAstVisitor.prototype.visitSyntaxList = function (node) { + var start = this.position; + var array = new Array(node.childCount()); + + for (var i = 0, n = node.childCount(); i < n; i++) { + array[i] = node.childAt(i).accept(this); + } + + var result = new TypeScript.ISyntaxList2(this.fileName, array); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSeparatedSyntaxList = function (list) { + var start = this.position; + var array = new Array(list.nonSeparatorCount()); + + for (var i = 0, n = list.childCount(); i < n; i++) { + if (i % 2 === 0) { + array[i / 2] = list.childAt(i).accept(this); + this.previousTokenTrailingComments = null; + } else { + var separatorToken = list.childAt(i); + this.previousTokenTrailingComments = this.convertTokenTrailingComments(separatorToken, this.position + separatorToken.leadingTriviaWidth() + separatorToken.width()); + this.movePast(separatorToken); + } + } + + var result = new TypeScript.ISeparatedSyntaxList2(this.fileName, array, list.separatorCount()); + this.setSpan(result, start, list); + + result.setPostComments(this.previousTokenTrailingComments); + this.previousTokenTrailingComments = null; + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.convertComment = function (trivia, commentStartPosition, hasTrailingNewLine) { + var comment = new TypeScript.Comment(trivia, hasTrailingNewLine, commentStartPosition, commentStartPosition + trivia.fullWidth()); + + return comment; + }; + + SyntaxTreeToAstVisitor.prototype.convertComments = function (triviaList, commentStartPosition) { + var result = []; + + for (var i = 0, n = triviaList.count(); i < n; i++) { + var trivia = triviaList.syntaxTriviaAt(i); + + if (trivia.isComment()) { + var hasTrailingNewLine = ((i + 1) < n) && triviaList.syntaxTriviaAt(i + 1).isNewLine(); + result.push(this.convertComment(trivia, commentStartPosition, hasTrailingNewLine)); + } + + commentStartPosition += trivia.fullWidth(); + } + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.mergeComments = function (comments1, comments2) { + if (comments1 === null) { + return comments2; + } + + if (comments2 === null) { + return comments1; + } + + return comments1.concat(comments2); + }; + + SyntaxTreeToAstVisitor.prototype.convertTokenLeadingComments = function (token, commentStartPosition) { + if (token === null) { + return null; + } + + var preComments = token.hasLeadingComment() ? this.convertComments(token.leadingTrivia(), commentStartPosition) : null; + + var previousTokenTrailingComments = this.previousTokenTrailingComments; + this.previousTokenTrailingComments = null; + + return this.mergeComments(previousTokenTrailingComments, preComments); + }; + + SyntaxTreeToAstVisitor.prototype.convertTokenTrailingComments = function (token, commentStartPosition) { + if (token === null || !token.hasTrailingComment() || token.hasTrailingNewLine()) { + return null; + } + + return this.convertComments(token.trailingTrivia(), commentStartPosition); + }; + + SyntaxTreeToAstVisitor.prototype.convertNodeTrailingComments = function (node, lastToken, nodeStart) { + if (lastToken === null || !lastToken.hasTrailingComment() || lastToken.hasTrailingNewLine()) { + return null; + } + + return this.convertComments(lastToken.trailingTrivia(), nodeStart + node.fullWidth() - lastToken.trailingTriviaWidth()); + }; + + SyntaxTreeToAstVisitor.prototype.visitIdentifier = function (token) { + return this.visitToken(token); + }; + + SyntaxTreeToAstVisitor.prototype.visitToken = function (token) { + var fullStart = this.position; + + var result = this.visitTokenWorker(token); + + this.movePast(token); + + var start = fullStart + token.leadingTriviaWidth(); + this.setSpanExplicit(result, start, start + token.width()); + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTokenWorker = function (token) { + switch (token.tokenKind) { + case 60 /* AnyKeyword */: + return new TypeScript.BuiltInType(60 /* AnyKeyword */, token.text(), token.valueText()); + case 61 /* BooleanKeyword */: + return new TypeScript.BuiltInType(61 /* BooleanKeyword */, token.text(), token.valueText()); + case 67 /* NumberKeyword */: + return new TypeScript.BuiltInType(67 /* NumberKeyword */, token.text(), token.valueText()); + case 69 /* StringKeyword */: + return new TypeScript.BuiltInType(69 /* StringKeyword */, token.text(), token.valueText()); + case 41 /* VoidKeyword */: + return new TypeScript.BuiltInType(41 /* VoidKeyword */, token.text(), token.valueText()); + case 35 /* ThisKeyword */: + return new TypeScript.ThisExpression(token.text(), token.valueText()); + case 50 /* SuperKeyword */: + return new TypeScript.SuperExpression(token.text(), token.valueText()); + case 37 /* TrueKeyword */: + return new TypeScript.LiteralExpression(37 /* TrueKeyword */, token.text(), token.valueText()); + case 24 /* FalseKeyword */: + return new TypeScript.LiteralExpression(24 /* FalseKeyword */, token.text(), token.valueText()); + case 32 /* NullKeyword */: + return new TypeScript.LiteralExpression(32 /* NullKeyword */, token.text(), token.valueText()); + case 14 /* StringLiteral */: + return new TypeScript.StringLiteral(token.text(), token.valueText()); + case 12 /* RegularExpressionLiteral */: + return new TypeScript.RegularExpressionLiteral(token.text(), token.valueText()); + case 13 /* NumericLiteral */: + var fullStart = this.position; + var preComments = this.convertTokenLeadingComments(token, fullStart); + + var result = new TypeScript.NumericLiteral(token.value(), token.text(), token.valueText()); + + result.setPreComments(preComments); + return result; + case 11 /* IdentifierName */: + return new TypeScript.Identifier(token.text()); + default: + throw TypeScript.Errors.invalidOperation(); + } + }; + + SyntaxTreeToAstVisitor.prototype.visitSourceUnit = function (node) { + var start = this.position; + TypeScript.Debug.assert(start === 0); + + var bod = this.visitSyntaxList(node.moduleElements); + var comments = this.convertTokenLeadingComments(node.endOfFileToken, TypeScript.Syntax.childOffset(node, node.endOfFileToken)); + var result = new TypeScript.SourceUnit(bod, comments, this.fileName); + this.setSpanExplicit(result, start, start + node.fullWidth()); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitExternalModuleReference = function (node) { + var start = this.position; + + this.moveTo(node, node.stringLiteral); + var stringLiteral = node.stringLiteral.accept(this); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ExternalModuleReference(stringLiteral); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitModuleNameModuleReference = function (node) { + var start = this.position; + var moduleName = node.moduleName.accept(this); + + var result = new TypeScript.ModuleNameModuleReference(moduleName); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitClassDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var heritageClauses = node.heritageClauses ? this.visitSyntaxList(node.heritageClauses) : null; + + this.movePast(node.openBraceToken); + var members = this.visitSyntaxList(node.classElements); + + var closeBraceToken = this.createTokenSpan(this.position, node.closeBraceToken); + this.movePast(node.closeBraceToken); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.ClassDeclaration(modifiers, name, typeParameters, heritageClauses, members, closeBraceToken); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitModifiers = function (modifiers) { + var result = null; + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 47 /* ExportKeyword */)) { + result = result || []; + result.push(1 /* Exported */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 63 /* DeclareKeyword */)) { + result = result || []; + result.push(8 /* Ambient */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 58 /* StaticKeyword */)) { + result = result || []; + result.push(16 /* Static */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 57 /* PublicKeyword */)) { + result = result || []; + result.push(4 /* Public */); + } + + if (TypeScript.SyntaxUtilities.containsToken(modifiers, 55 /* PrivateKeyword */)) { + result = result || []; + result.push(2 /* Private */); + } + + return result || TypeScript.sentinelEmptyArray; + }; + + SyntaxTreeToAstVisitor.prototype.visitInterfaceDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var heritageClauses = node.heritageClauses ? this.visitSyntaxList(node.heritageClauses) : null; + + var body = this.visitObjectType(node.body); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.InterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, body); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitHeritageClause = function (node) { + var start = this.position; + + this.movePast(node.extendsOrImplementsKeyword); + var typeNames = this.visitSeparatedSyntaxList(node.typeNames); + + var result = new TypeScript.HeritageClause(node.extendsOrImplementsKeyword.tokenKind === 48 /* ExtendsKeyword */ ? 230 /* ExtendsHeritageClause */ : 231 /* ImplementsHeritageClause */, typeNames); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitModuleDeclaration = function (node) { + var start = this.position; + + var modifiers = this.visitModifiers(node.modifiers); + + this.moveTo(node, node.moduleKeyword); + this.movePast(node.moduleKeyword); + + var moduleName = node.name ? node.name.accept(this) : null; + var stringLiteral = node.stringLiteral ? node.stringLiteral.accept(this) : null; + + this.movePast(node.openBraceToken); + + var moduleElements = this.visitSyntaxList(node.moduleElements); + + var closeBraceToken = this.createTokenSpan(this.position, node.closeBraceToken); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.ModuleDeclaration(modifiers, moduleName, stringLiteral, moduleElements, closeBraceToken); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + + var callSignature = this.visitCallSignature(node.callSignature); + var block = node.block ? this.visitBlock(node.block) : null; + + this.movePast(node.semicolonToken); + + var result = new TypeScript.FunctionDeclaration(this.visitModifiers(node.modifiers), name, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEnumDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var identifier = this.visitIdentifier(node.identifier); + + this.movePast(node.openBraceToken); + + var enumElements = this.visitSeparatedSyntaxList(node.enumElements); + + this.movePast(node.closeBraceToken); + + var result = new TypeScript.EnumDeclaration(this.visitModifiers(node.modifiers), identifier, enumElements); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEnumElement = function (node) { + var start = this.position; + + var memberName = this.visitToken(node.propertyName); + + var value = node.equalsValueClause !== null ? this.visitEqualsValueClause(node.equalsValueClause) : null; + + var result = new TypeScript.EnumElement(memberName, value); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitImportDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + this.movePast(node.equalsToken); + var alias = node.moduleReference.accept(this); + this.movePast(node.semicolonToken); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.ImportDeclaration(modifiers, name, alias); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitExportAssignment = function (node) { + var start = this.position; + + this.moveTo(node, node.identifier); + var name = this.visitIdentifier(node.identifier); + this.movePast(node.semicolonToken); + + var result = new TypeScript.ExportAssignment(name); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.variableDeclaration); + + var declaration = node.variableDeclaration.accept(this); + this.movePast(node.semicolonToken); + + var modifiers = this.visitModifiers(node.modifiers); + + var result = new TypeScript.VariableStatement(modifiers, declaration); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.variableDeclarators); + var variableDecls = this.visitSeparatedSyntaxList(node.variableDeclarators); + + var result = new TypeScript.VariableDeclaration(variableDecls); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVariableDeclarator = function (node) { + var start = this.position; + var propertyName = this.visitToken(node.propertyName); + var typeExpr = this.visitTypeAnnotation(node.typeAnnotation); + var init = node.equalsValueClause ? this.visitEqualsValueClause(node.equalsValueClause) : null; + + var result = new TypeScript.VariableDeclarator(propertyName, typeExpr, init); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEqualsValueClause = function (node) { + var start = this.position; + var afterEqualsComments = this.convertTokenTrailingComments(node.equalsToken, this.position + node.equalsToken.leadingTriviaWidth() + node.equalsToken.width()); + + this.movePast(node.equalsToken); + var value = node.value.accept(this); + value.setPreComments(this.mergeComments(afterEqualsComments, value.preComments())); + + var result = new TypeScript.EqualsValueClause(value); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPrefixUnaryExpression = function (node) { + var start = this.position; + + this.movePast(node.operatorToken); + var operand = node.operand.accept(this); + + var result = new TypeScript.PrefixUnaryExpression(node.kind(), operand); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArrayLiteralExpression = function (node) { + var start = this.position; + var openStart = this.position + node.openBracketToken.leadingTriviaWidth(); + this.movePast(node.openBracketToken); + + var expressions = this.visitSeparatedSyntaxList(node.expressions); + + var closeStart = this.position + node.closeBracketToken.leadingTriviaWidth(); + this.movePast(node.closeBracketToken); + + var result = new TypeScript.ArrayLiteralExpression(expressions); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitOmittedExpression = function (node) { + var start = this.position; + + var result = new TypeScript.OmittedExpression(); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParenthesizedExpression = function (node) { + var start = this.position; + + var openParenToken = node.openParenToken; + var openParenTrailingComments = this.convertTokenTrailingComments(openParenToken, start + openParenToken.leadingTriviaWidth() + openParenToken.width()); + + this.movePast(openParenToken); + + var expr = node.expression.accept(this); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ParenthesizedExpression(openParenTrailingComments, expr); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + var start = this.position; + + var identifier = node.identifier.accept(this); + this.movePast(node.equalsGreaterThanToken); + + var block = node.block ? this.visitBlock(node.block) : null; + var expression = node.expression ? node.expression.accept(this) : null; + + var result = new TypeScript.SimpleArrowFunctionExpression(identifier, block, expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + var start = this.position; + + var callSignature = this.visitCallSignature(node.callSignature); + this.movePast(node.equalsGreaterThanToken); + + var block = node.block ? this.visitBlock(node.block) : null; + var expression = node.expression ? node.expression.accept(this) : null; + + var result = new TypeScript.ParenthesizedArrowFunctionExpression(callSignature, block, expression); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitType = function (type) { + return type ? type.accept(this) : null; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeQuery = function (node) { + var start = this.position; + this.movePast(node.typeOfKeyword); + var name = node.name.accept(this); + + var result = new TypeScript.TypeQuery(name); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitQualifiedName = function (node) { + var start = this.position; + var left = this.visitType(node.left); + this.movePast(node.dotToken); + var right = this.visitIdentifier(node.right); + + var result = new TypeScript.QualifiedName(left, right); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeArgumentList = function (node) { + if (node === null) { + return null; + } + + var start = this.position; + this.movePast(node.lessThanToken); + var typeArguments = this.visitSeparatedSyntaxList(node.typeArguments); + this.movePast(node.greaterThanToken); + + var result = new TypeScript.TypeArgumentList(typeArguments); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructorType = function (node) { + var start = this.position; + + this.movePast(node.newKeyword); + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var parameters = this.visitParameterList(node.parameterList); + this.movePast(node.equalsGreaterThanToken); + var returnType = this.visitType(node.type); + + var result = new TypeScript.ConstructorType(typeParameters, parameters, returnType); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionType = function (node) { + var start = this.position; + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var parameters = this.visitParameterList(node.parameterList); + this.movePast(node.equalsGreaterThanToken); + var returnType = this.visitType(node.type); + + var result = new TypeScript.FunctionType(typeParameters, parameters, returnType); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectType = function (node) { + var start = this.position; + + this.movePast(node.openBraceToken); + var typeMembers = this.visitSeparatedSyntaxList(node.typeMembers); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.ObjectType(typeMembers); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArrayType = function (node) { + var start = this.position; + + var underlying = this.visitType(node.type); + this.movePast(node.openBracketToken); + this.movePast(node.closeBracketToken); + + var result = new TypeScript.ArrayType(underlying); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitGenericType = function (node) { + var start = this.position; + + var underlying = this.visitType(node.name); + var typeArguments = this.visitTypeArgumentList(node.typeArgumentList); + + var result = new TypeScript.GenericType(underlying, typeArguments); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeAnnotation = function (node) { + if (!node) { + return null; + } + + var start = this.position; + this.movePast(node.colonToken); + var type = this.visitType(node.type); + + var result = new TypeScript.TypeAnnotation(type); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitBlock = function (node) { + if (!node) { + return null; + } + + var start = this.position; + + this.movePast(node.openBraceToken); + var statements = this.visitSyntaxList(node.statements); + var closeBracePosition = this.position; + + var closeBraceLeadingComments = this.convertTokenLeadingComments(node.closeBraceToken, this.position); + var closeBraceToken = this.createTokenSpan(this.position, node.closeBraceToken); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.Block(statements, closeBraceLeadingComments, closeBraceToken); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParameter = function (node) { + var start = this.position; + + var dotDotDotToken = this.createTokenSpan(this.position, node.dotDotDotToken); + + this.moveTo(node, node.identifier); + var identifier = this.visitIdentifier(node.identifier); + + var questionToken = this.createTokenSpan(this.position, node.questionToken); + this.movePast(node.questionToken); + var typeExpr = this.visitTypeAnnotation(node.typeAnnotation); + var init = node.equalsValueClause ? node.equalsValueClause.accept(this) : null; + + var modifiers = this.visitModifiers(node.modifiers); + + var result = new TypeScript.Parameter(dotDotDotToken, modifiers, identifier, questionToken, typeExpr, init); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberAccessExpression = function (node) { + var start = this.position; + + var expression = node.expression.accept(this); + this.movePast(node.dotToken); + var name = this.visitIdentifier(node.name); + + var result = new TypeScript.MemberAccessExpression(expression, name); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPostfixUnaryExpression = function (node) { + var start = this.position; + + var operand = node.operand.accept(this); + this.movePast(node.operatorToken); + + var result = new TypeScript.PostfixUnaryExpression(node.kind() === 210 /* PostIncrementExpression */ ? 210 /* PostIncrementExpression */ : 211 /* PostDecrementExpression */, operand); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitElementAccessExpression = function (node) { + var start = this.position; + + var expression = node.expression.accept(this); + this.movePast(node.openBracketToken); + var argumentExpression = node.argumentExpression.accept(this); + this.movePast(node.closeBracketToken); + + var result = new TypeScript.ElementAccessExpression(expression, argumentExpression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitInvocationExpression = function (node) { + var start = this.position; + + var expression = node.expression.accept(this); + var argumentList = this.visitArgumentList(node.argumentList); + + var result = new TypeScript.InvocationExpression(expression, argumentList); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitArgumentList = function (node) { + if (node === null) { + return null; + } + + var start = this.position; + + var typeArguments = this.visitTypeArgumentList(node.typeArgumentList); + + this.movePast(node.openParenToken); + + var _arguments = this.visitSeparatedSyntaxList(node.arguments); + + if (node.arguments.fullWidth() === 0 && node.closeParenToken.fullWidth() === 0) { + var openParenTokenEnd = start + node.openParenToken.leadingTriviaWidth() + node.openParenToken.width(); + this.setSpanExplicit(_arguments, openParenTokenEnd, openParenTokenEnd + node.openParenToken.trailingTriviaWidth()); + } + + var closeParenToken = this.createTokenSpan(this.position, node.closeParenToken); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ArgumentList(typeArguments, _arguments, closeParenToken); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitBinaryExpression = function (node) { + var start = this.position; + + var left = node.left.accept(this); + this.movePast(node.operatorToken); + var right = node.right.accept(this); + + var result = new TypeScript.BinaryExpression(node.kind(), left, right); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConditionalExpression = function (node) { + var start = this.position; + + var condition = node.condition.accept(this); + this.movePast(node.questionToken); + var whenTrue = node.whenTrue.accept(this); + this.movePast(node.colonToken); + var whenFalse = node.whenFalse.accept(this); + + var result = new TypeScript.ConditionalExpression(condition, whenTrue, whenFalse); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructSignature = function (node) { + var start = this.position; + + this.movePast(node.newKeyword); + var callSignature = this.visitCallSignature(node.callSignature); + + var result = new TypeScript.ConstructSignature(callSignature); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMethodSignature = function (node) { + var start = this.position; + + var name = this.visitToken(node.propertyName); + + var questionToken = this.createTokenSpan(this.position, node.questionToken); + this.movePast(node.questionToken); + + var callSignature = this.visitCallSignature(node.callSignature); + + var result = new TypeScript.MethodSignature(name, questionToken, callSignature); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitIndexSignature = function (node) { + var start = this.position; + + this.movePast(node.openBracketToken); + + var parameter = node.parameter.accept(this); + + this.movePast(node.closeBracketToken); + var returnType = this.visitTypeAnnotation(node.typeAnnotation); + + var result = new TypeScript.IndexSignature(parameter, returnType); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitPropertySignature = function (node) { + var start = this.position; + + var name = this.visitToken(node.propertyName); + + var questionToken = this.createTokenSpan(this.position, node.questionToken); + this.movePast(node.questionToken); + var typeExpr = this.visitTypeAnnotation(node.typeAnnotation); + + var result = new TypeScript.PropertySignature(name, questionToken, typeExpr); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitParameterList = function (node) { + if (!node) { + return null; + } + + var start = this.position; + + var openParenToken = node.openParenToken; + + this.previousTokenTrailingComments = this.convertTokenTrailingComments(openParenToken, start + openParenToken.leadingTriviaWidth() + openParenToken.width()); + var openParenTrailingComments = null; + if (node.parameters.childCount() === 0) { + openParenTrailingComments = this.previousTokenTrailingComments; + this.previousTokenTrailingComments = null; + } + + this.movePast(node.openParenToken); + var parameters = this.visitSeparatedSyntaxList(node.parameters); + this.movePast(node.closeParenToken); + + var result = new TypeScript.ParameterList(openParenTrailingComments, parameters); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCallSignature = function (node) { + var start = this.position; + + var typeParameters = this.visitTypeParameterList(node.typeParameterList); + var parameters = this.visitParameterList(node.parameterList); + var returnType = this.visitTypeAnnotation(node.typeAnnotation); + + var result = new TypeScript.CallSignature(typeParameters, parameters, returnType); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeParameterList = function (node) { + if (!node) { + return null; + } + + var start = this.position; + this.movePast(node.lessThanToken); + var typeParameters = this.visitSeparatedSyntaxList(node.typeParameters); + this.movePast(node.greaterThanToken); + + var result = new TypeScript.TypeParameterList(typeParameters); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeParameter = function (node) { + var start = this.position; + + var identifier = this.visitIdentifier(node.identifier); + var constraint = node.constraint ? node.constraint.accept(this) : null; + + var result = new TypeScript.TypeParameter(identifier, constraint); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstraint = function (node) { + var start = this.position; + this.movePast(node.extendsKeyword); + var type = this.visitType(node.type); + + var result = new TypeScript.Constraint(type); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitIfStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var thenBod = node.statement.accept(this); + var elseBod = node.elseClause ? node.elseClause.accept(this) : null; + + var result = new TypeScript.IfStatement(condition, thenBod, elseBod); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitElseClause = function (node) { + var start = this.position; + + this.movePast(node.elseKeyword); + var statement = node.statement.accept(this); + + var result = new TypeScript.ElseClause(statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitExpressionStatement = function (node) { + var start = this.position; + + var preComments = this.convertTokenLeadingComments(node.firstToken(), start); + var expression = node.expression.accept(this); + + var semicolonPosition = this.position; + + var postComments = this.convertComments(node.semicolonToken.trailingTrivia(), this.position + node.semicolonToken.leadingTriviaWidth() + node.semicolonToken.width()); + this.movePast(node.semicolonToken); + + var result = new TypeScript.ExpressionStatement(expression); + this.setSpan(result, start, node); + + result.setPreComments(preComments); + result.setPostComments(postComments); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitConstructorDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.callSignature); + var callSignature = this.visitCallSignature(node.callSignature); + + var block = node.block ? node.block.accept(this) : null; + + this.movePast(node.semicolonToken); + + var result = new TypeScript.ConstructorDeclaration(callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitIndexMemberDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.indexSignature); + var indexSignature = node.indexSignature.accept(this); + + this.movePast(node.semicolonToken); + + var result = new TypeScript.IndexMemberDeclaration(indexSignature); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.propertyName); + var name = this.visitToken(node.propertyName); + + var callSignature = this.visitCallSignature(node.callSignature); + var block = node.block ? this.visitBlock(node.block) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.MemberFunctionDeclaration(this.visitModifiers(node.modifiers), name, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitGetAccessor = function (node) { + var start = this.position; + + this.moveTo(node, node.propertyName); + var name = this.visitToken(node.propertyName); + var parameters = this.visitParameterList(node.parameterList); + var returnType = this.visitTypeAnnotation(node.typeAnnotation); + + var block = node.block ? node.block.accept(this) : null; + var result = new TypeScript.GetAccessor(this.visitModifiers(node.modifiers), name, parameters, returnType, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSetAccessor = function (node) { + var start = this.position; + + this.moveTo(node, node.propertyName); + var name = this.visitToken(node.propertyName); + var parameters = this.visitParameterList(node.parameterList); + var block = node.block ? node.block.accept(this) : null; + var result = new TypeScript.SetAccessor(this.visitModifiers(node.modifiers), name, parameters, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitMemberVariableDeclaration = function (node) { + var start = this.position; + + this.moveTo(node, node.variableDeclarator); + var variableDeclarator = node.variableDeclarator.accept(this); + this.movePast(node.semicolonToken); + + var modifiers = this.visitModifiers(node.modifiers); + var result = new TypeScript.MemberVariableDeclaration(modifiers, variableDeclarator); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitThrowStatement = function (node) { + var start = this.position; + + this.movePast(node.throwKeyword); + var expression = node.expression.accept(this); + this.movePast(node.semicolonToken); + + var result = new TypeScript.ThrowStatement(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitReturnStatement = function (node) { + var start = this.position; + + this.movePast(node.returnKeyword); + var expression = node.expression ? node.expression.accept(this) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.ReturnStatement(expression); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectCreationExpression = function (node) { + var start = this.position; + + this.movePast(node.newKeyword); + var expression = node.expression.accept(this); + var argumentList = this.visitArgumentList(node.argumentList); + + var result = new TypeScript.ObjectCreationExpression(expression, argumentList); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSwitchStatement = function (node) { + var start = this.position; + + this.movePast(node.switchKeyword); + this.movePast(node.openParenToken); + var expression = node.expression.accept(this); + + var closeParenToken = this.createTokenSpan(this.position, node.closeParenToken); + this.movePast(node.closeParenToken); + this.movePast(node.openBraceToken); + var switchClauses = this.visitSyntaxList(node.switchClauses); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.SwitchStatement(expression, closeParenToken, switchClauses); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCaseSwitchClause = function (node) { + var start = this.position; + + this.movePast(node.caseKeyword); + var expression = node.expression.accept(this); + this.movePast(node.colonToken); + var statements = this.visitSyntaxList(node.statements); + + var result = new TypeScript.CaseSwitchClause(expression, statements); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDefaultSwitchClause = function (node) { + var start = this.position; + + this.movePast(node.defaultKeyword); + this.movePast(node.colonToken); + var statements = this.visitSyntaxList(node.statements); + + var result = new TypeScript.DefaultSwitchClause(statements); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitBreakStatement = function (node) { + var start = this.position; + + this.movePast(node.breakKeyword); + var identifier = node.identifier ? node.identifier.accept(this) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.BreakStatement(identifier); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitContinueStatement = function (node) { + var start = this.position; + + this.movePast(node.continueKeyword); + var identifier = node.identifier ? node.identifier.accept(this) : null; + this.movePast(node.semicolonToken); + + var result = new TypeScript.ContinueStatement(identifier); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitForStatement = function (node) { + var start = this.position; + + this.movePast(node.forKeyword); + this.movePast(node.openParenToken); + var variableDeclaration = node.variableDeclaration ? node.variableDeclaration.accept(this) : null; + var initializer = node.initializer ? node.initializer.accept(this) : null; + + this.movePast(node.firstSemicolonToken); + var cond = node.condition ? node.condition.accept(this) : null; + this.movePast(node.secondSemicolonToken); + var incr = node.incrementor ? node.incrementor.accept(this) : null; + this.movePast(node.closeParenToken); + var body = node.statement.accept(this); + + var result = new TypeScript.ForStatement(variableDeclaration, initializer, cond, incr, body); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitForInStatement = function (node) { + var start = this.position; + + this.movePast(node.forKeyword); + this.movePast(node.openParenToken); + var variableDeclaration = node.variableDeclaration ? node.variableDeclaration.accept(this) : null; + var left = node.left ? node.left.accept(this) : null; + + this.movePast(node.inKeyword); + var expression = node.expression.accept(this); + this.movePast(node.closeParenToken); + var body = node.statement.accept(this); + + var result = new TypeScript.ForInStatement(variableDeclaration, left, expression, body); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitWhileStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var statement = node.statement.accept(this); + + var result = new TypeScript.WhileStatement(condition, statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitWithStatement = function (node) { + var start = this.position; + + this.moveTo(node, node.condition); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + var statement = node.statement.accept(this); + + var result = new TypeScript.WithStatement(condition, statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCastExpression = function (node) { + var start = this.position; + + this.movePast(node.lessThanToken); + var castTerm = this.visitType(node.type); + this.movePast(node.greaterThanToken); + var expression = node.expression.accept(this); + + var result = new TypeScript.CastExpression(castTerm, expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitObjectLiteralExpression = function (node) { + var start = this.position; + + var openStart = this.position + node.openBraceToken.leadingTriviaWidth(); + this.movePast(node.openBraceToken); + + var propertyAssignments = this.visitSeparatedSyntaxList(node.propertyAssignments); + + var closeStart = this.position + node.closeBraceToken.leadingTriviaWidth(); + this.movePast(node.closeBraceToken); + + var result = new TypeScript.ObjectLiteralExpression(propertyAssignments); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitSimplePropertyAssignment = function (node) { + var start = this.position; + + var preComments = this.convertTokenLeadingComments(node.firstToken(), start); + var postComments = this.convertNodeTrailingComments(node, node.lastToken(), start); + + var propertyName = node.propertyName.accept(this); + + var afterColonComments = this.convertTokenTrailingComments(node.colonToken, this.position + node.colonToken.leadingTriviaWidth() + node.colonToken.width()); + + this.movePast(node.colonToken); + var expression = node.expression.accept(this); + expression.setPreComments(this.mergeComments(afterColonComments, expression.preComments())); + + var result = new TypeScript.SimplePropertyAssignment(propertyName, expression); + this.setSpan(result, start, node); + + result.setPreComments(preComments); + result.setPostComments(postComments); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + var start = this.position; + + var propertyName = node.propertyName.accept(this); + var callSignature = this.visitCallSignature(node.callSignature); + var block = this.visitBlock(node.block); + + var result = new TypeScript.FunctionPropertyAssignment(propertyName, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFunctionExpression = function (node) { + var start = this.position; + + this.movePast(node.functionKeyword); + var name = node.identifier === null ? null : this.visitIdentifier(node.identifier); + + var callSignature = this.visitCallSignature(node.callSignature); + var block = node.block ? node.block.accept(this) : null; + + var result = new TypeScript.FunctionExpression(name, callSignature, block); + this.setCommentsAndSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitEmptyStatement = function (node) { + var start = this.position; + + this.movePast(node.semicolonToken); + + var result = new TypeScript.EmptyStatement(); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTryStatement = function (node) { + var start = this.position; + + this.movePast(node.tryKeyword); + var tryBody = node.block.accept(this); + + var catchClause = null; + if (node.catchClause !== null) { + catchClause = node.catchClause.accept(this); + } + + var finallyBody = null; + if (node.finallyClause !== null) { + finallyBody = node.finallyClause.accept(this); + } + + var result = new TypeScript.TryStatement(tryBody, catchClause, finallyBody); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitCatchClause = function (node) { + var start = this.position; + + this.movePast(node.catchKeyword); + this.movePast(node.openParenToken); + var identifier = this.visitIdentifier(node.identifier); + var typeAnnotation = this.visitTypeAnnotation(node.typeAnnotation); + this.movePast(node.closeParenToken); + var block = node.block.accept(this); + + var result = new TypeScript.CatchClause(identifier, typeAnnotation, block); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitFinallyClause = function (node) { + var start = this.position; + this.movePast(node.finallyKeyword); + var block = node.block.accept(this); + + var result = new TypeScript.FinallyClause(block); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitLabeledStatement = function (node) { + var start = this.position; + + var identifier = this.visitIdentifier(node.identifier); + this.movePast(node.colonToken); + var statement = node.statement.accept(this); + + var result = new TypeScript.LabeledStatement(identifier, statement); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDoStatement = function (node) { + var start = this.position; + + this.movePast(node.doKeyword); + var statement = node.statement.accept(this); + var whileKeyword = this.createTokenSpan(this.position, node.whileKeyword); + + this.movePast(node.whileKeyword); + this.movePast(node.openParenToken); + var condition = node.condition.accept(this); + this.movePast(node.closeParenToken); + this.movePast(node.semicolonToken); + + var result = new TypeScript.DoStatement(statement, whileKeyword, condition); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitTypeOfExpression = function (node) { + var start = this.position; + + this.movePast(node.typeOfKeyword); + var expression = node.expression.accept(this); + + var result = new TypeScript.TypeOfExpression(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDeleteExpression = function (node) { + var start = this.position; + + this.movePast(node.deleteKeyword); + var expression = node.expression.accept(this); + + var result = new TypeScript.DeleteExpression(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitVoidExpression = function (node) { + var start = this.position; + + this.movePast(node.voidKeyword); + var expression = node.expression.accept(this); + + var result = new TypeScript.VoidExpression(expression); + this.setSpan(result, start, node); + + return result; + }; + + SyntaxTreeToAstVisitor.prototype.visitDebuggerStatement = function (node) { + var start = this.position; + + this.movePast(node.debuggerKeyword); + this.movePast(node.semicolonToken); + + var result = new TypeScript.DebuggerStatement(); + this.setSpan(result, start, node); + + return result; + }; + return SyntaxTreeToAstVisitor; + })(); + TypeScript.SyntaxTreeToAstVisitor = SyntaxTreeToAstVisitor; + + function applyDelta(ast, delta) { + if (ast) { + if (ast._start !== -1) { + ast._start += delta; + } + + if (ast._end !== -1) { + ast._end += delta; + } + } + } + + function applyDeltaToComments(comments, delta) { + if (comments && comments.length > 0) { + for (var i = 0; i < comments.length; i++) { + var comment = comments[i]; + applyDelta(comment, delta); + } + } + } + + var SyntaxTreeToIncrementalAstVisitor = (function (_super) { + __extends(SyntaxTreeToIncrementalAstVisitor, _super); + function SyntaxTreeToIncrementalAstVisitor() { + _super.apply(this, arguments); + } + SyntaxTreeToIncrementalAstVisitor.prototype.applyDelta = function (ast, delta) { + if (delta === 0) { + return; + } + + var pre = function (cur) { + applyDelta(cur, delta); + applyDeltaToComments(cur.preComments(), delta); + applyDeltaToComments(cur.postComments(), delta); + + switch (cur.kind()) { + case 146 /* Block */: + applyDelta(cur.closeBraceToken, delta); + break; + + case 226 /* ArgumentList */: + applyDelta(cur.closeParenToken, delta); + break; + + case 130 /* ModuleDeclaration */: + applyDelta(cur.endingToken, delta); + break; + + case 131 /* ClassDeclaration */: + applyDelta(cur.closeBraceToken, delta); + break; + + case 161 /* DoStatement */: + applyDelta(cur.whileKeyword, delta); + break; + + case 151 /* SwitchStatement */: + applyDelta(cur.closeParenToken, delta); + break; + } + }; + + TypeScript.getAstWalkerFactory().simpleWalk(ast, pre); + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.setSpanExplicit = function (span, start, end) { + if (span._start !== -1) { + var delta = start - span._start; + this.applyDelta(span, delta); + + span._end = end; + } else { + _super.prototype.setSpanExplicit.call(this, span, start, end); + } + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.getAndMovePastAST = function (element) { + if (this.previousTokenTrailingComments !== null) { + return null; + } + + var result = element._ast; + if (!result) { + return null; + } + + var start = this.position; + this.movePast(element); + this.setSpan(result, start, element); + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.setAST = function (element, ast) { + element._ast = ast; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSyntaxList = function (list) { + var result = this.getAndMovePastAST(list); + if (!result) { + result = _super.prototype.visitSyntaxList.call(this, list); + + if (list.childCount() > 0) { + this.setAST(list, result); + } + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSeparatedSyntaxList = function (list) { + var result = this.getAndMovePastAST(list); + if (!result) { + result = _super.prototype.visitSeparatedSyntaxList.call(this, list); + + if (list.childCount() > 0) { + this.setAST(list, result); + } + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitToken = function (token) { + var result = this.getAndMovePastAST(token); + + if (!result) { + result = _super.prototype.visitToken.call(this, token); + this.setAST(token, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitClassDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitClassDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitInterfaceDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitInterfaceDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitHeritageClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitHeritageClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitModuleDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitModuleDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitImportDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitImportDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitExportAssignment = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitExportAssignment.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitPrefixUnaryExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitPrefixUnaryExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitArrayLiteralExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitArrayLiteralExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitOmittedExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitOmittedExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitParenthesizedExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitParenthesizedExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSimpleArrowFunctionExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSimpleArrowFunctionExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitParenthesizedArrowFunctionExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitParenthesizedArrowFunctionExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitQualifiedName = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + var result = _super.prototype.visitQualifiedName.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConstructorType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConstructorType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitObjectType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitObjectType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitArrayType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitArrayType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitGenericType = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitGenericType.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitBlock = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitBlock.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitParameter = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitParameter.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMemberAccessExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMemberAccessExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitPostfixUnaryExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitPostfixUnaryExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitElementAccessExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitElementAccessExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitInvocationExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitInvocationExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitBinaryExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitBinaryExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConditionalExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConditionalExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConstructSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConstructSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMethodSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMethodSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitIndexSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitIndexSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitPropertySignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitPropertySignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCallSignature = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCallSignature.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitTypeParameter = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitTypeParameter.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitIfStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitIfStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitExpressionStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitExpressionStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitConstructorDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitConstructorDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMemberFunctionDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMemberFunctionDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitGetAccessor = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitGetAccessor.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSetAccessor = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSetAccessor.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitMemberVariableDeclaration = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitMemberVariableDeclaration.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitThrowStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitThrowStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitReturnStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitReturnStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitObjectCreationExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitObjectCreationExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSwitchStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSwitchStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCaseSwitchClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCaseSwitchClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDefaultSwitchClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDefaultSwitchClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitBreakStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitBreakStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitContinueStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitContinueStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitForStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitForStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitForInStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitForInStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitWhileStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitWhileStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitWithStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitWithStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCastExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCastExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitObjectLiteralExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitObjectLiteralExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitSimplePropertyAssignment = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitSimplePropertyAssignment.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionPropertyAssignment = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionPropertyAssignment.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitFunctionExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitFunctionExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitEmptyStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitEmptyStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitTryStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitTryStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitCatchClause = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitCatchClause.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitLabeledStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitLabeledStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDoStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDoStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitTypeOfExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitTypeOfExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDeleteExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDeleteExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitVoidExpression = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitVoidExpression.call(this, node); + this.setAST(node, result); + } + + return result; + }; + + SyntaxTreeToIncrementalAstVisitor.prototype.visitDebuggerStatement = function (node) { + var result = this.getAndMovePastAST(node); + if (!result) { + result = _super.prototype.visitDebuggerStatement.call(this, node); + this.setAST(node, result); + } + + return result; + }; + return SyntaxTreeToIncrementalAstVisitor; + })(SyntaxTreeToAstVisitor); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ASTSpan = (function () { + function ASTSpan(_start, _end) { + this._start = _start; + this._end = _end; + } + ASTSpan.prototype.start = function () { + return this._start; + }; + + ASTSpan.prototype.end = function () { + return this._end; + }; + return ASTSpan; + })(); + TypeScript.ASTSpan = ASTSpan; + + var astID = 0; + + function structuralEqualsNotIncludingPosition(ast1, ast2) { + return structuralEquals(ast1, ast2, false); + } + TypeScript.structuralEqualsNotIncludingPosition = structuralEqualsNotIncludingPosition; + + function structuralEqualsIncludingPosition(ast1, ast2) { + return structuralEquals(ast1, ast2, true); + } + TypeScript.structuralEqualsIncludingPosition = structuralEqualsIncludingPosition; + + function commentStructuralEqualsNotIncludingPosition(ast1, ast2) { + return commentStructuralEquals(ast1, ast2, false); + } + + function commentStructuralEqualsIncludingPosition(ast1, ast2) { + return commentStructuralEquals(ast1, ast2, true); + } + + function structuralEquals(ast1, ast2, includingPosition) { + if (ast1 === ast2) { + return true; + } + + return ast1 !== null && ast2 !== null && ast1.kind() === ast2.kind() && ast1.structuralEquals(ast2, includingPosition); + } + + function commentStructuralEquals(ast1, ast2, includingPosition) { + if (ast1 === ast2) { + return true; + } + + return ast1 !== null && ast2 !== null && ast1.structuralEquals(ast2, includingPosition); + } + + function astArrayStructuralEquals(array1, array2, includingPosition) { + return TypeScript.ArrayUtilities.sequenceEquals(array1, array2, includingPosition ? structuralEqualsIncludingPosition : structuralEqualsNotIncludingPosition); + } + + function commentArrayStructuralEquals(array1, array2, includingPosition) { + return TypeScript.ArrayUtilities.sequenceEquals(array1, array2, includingPosition ? commentStructuralEqualsIncludingPosition : commentStructuralEqualsNotIncludingPosition); + } + + var AST = (function () { + function AST() { + this.parent = null; + this._start = -1; + this._end = -1; + this._trailingTriviaWidth = 0; + this._astID = astID++; + this._preComments = null; + this._postComments = null; + } + AST.prototype.syntaxID = function () { + return this._astID; + }; + + AST.prototype.start = function () { + return this._start; + }; + + AST.prototype.end = function () { + return this._end; + }; + + AST.prototype.trailingTriviaWidth = function () { + return this._trailingTriviaWidth; + }; + + AST.prototype.fileName = function () { + return this.parent.fileName(); + }; + + AST.prototype.kind = function () { + throw TypeScript.Errors.abstract(); + }; + + AST.prototype.preComments = function () { + return this._preComments; + }; + + AST.prototype.postComments = function () { + return this._postComments; + }; + + AST.prototype.setPreComments = function (comments) { + if (comments && comments.length) { + this._preComments = comments; + } else if (this._preComments) { + this._preComments = null; + } + }; + + AST.prototype.setPostComments = function (comments) { + if (comments && comments.length) { + this._postComments = comments; + } else if (this._postComments) { + this._postComments = null; + } + }; + + AST.prototype.width = function () { + return this.end() - this.start(); + }; + + AST.prototype.structuralEquals = function (ast, includingPosition) { + if (includingPosition) { + if (this.start() !== ast.start() || this.end() !== ast.end()) { + return false; + } + } + + return commentArrayStructuralEquals(this.preComments(), ast.preComments(), includingPosition) && commentArrayStructuralEquals(this.postComments(), ast.postComments(), includingPosition); + }; + + AST.prototype.isExpression = function () { + return false; + }; + return AST; + })(); + TypeScript.AST = AST; + + var ISyntaxList2 = (function (_super) { + __extends(ISyntaxList2, _super); + function ISyntaxList2(_fileName, members) { + _super.call(this); + this._fileName = _fileName; + this.members = members; + + for (var i = 0, n = members.length; i < n; i++) { + members[i].parent = this; + } + } + ISyntaxList2.prototype.childCount = function () { + return this.members.length; + }; + + ISyntaxList2.prototype.childAt = function (index) { + return this.members[index]; + }; + + ISyntaxList2.prototype.fileName = function () { + return this._fileName; + }; + + ISyntaxList2.prototype.kind = function () { + return 1 /* List */; + }; + + ISyntaxList2.prototype.firstOrDefault = function (func) { + return TypeScript.ArrayUtilities.firstOrDefault(this.members, func); + }; + + ISyntaxList2.prototype.lastOrDefault = function (func) { + return TypeScript.ArrayUtilities.lastOrDefault(this.members, func); + }; + + ISyntaxList2.prototype.any = function (func) { + return TypeScript.ArrayUtilities.any(this.members, func); + }; + + ISyntaxList2.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && astArrayStructuralEquals(this.members, ast.members, includingPosition); + }; + return ISyntaxList2; + })(AST); + TypeScript.ISyntaxList2 = ISyntaxList2; + + var ISeparatedSyntaxList2 = (function (_super) { + __extends(ISeparatedSyntaxList2, _super); + function ISeparatedSyntaxList2(_fileName, members, _separatorCount) { + _super.call(this); + this._fileName = _fileName; + this.members = members; + this._separatorCount = _separatorCount; + + for (var i = 0, n = members.length; i < n; i++) { + members[i].parent = this; + } + } + ISeparatedSyntaxList2.prototype.nonSeparatorCount = function () { + return this.members.length; + }; + + ISeparatedSyntaxList2.prototype.separatorCount = function () { + return this._separatorCount; + }; + + ISeparatedSyntaxList2.prototype.nonSeparatorAt = function (index) { + return this.members[index]; + }; + + ISeparatedSyntaxList2.prototype.nonSeparatorIndexOf = function (ast) { + for (var i = 0, n = this.nonSeparatorCount(); i < n; i++) { + if (this.nonSeparatorAt(i) === ast) { + return i; + } + } + + return -1; + }; + + ISeparatedSyntaxList2.prototype.fileName = function () { + return this._fileName; + }; + + ISeparatedSyntaxList2.prototype.kind = function () { + return 2 /* SeparatedList */; + }; + + ISeparatedSyntaxList2.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && astArrayStructuralEquals(this.members, ast.members, includingPosition); + }; + return ISeparatedSyntaxList2; + })(AST); + TypeScript.ISeparatedSyntaxList2 = ISeparatedSyntaxList2; + + var SourceUnit = (function (_super) { + __extends(SourceUnit, _super); + function SourceUnit(moduleElements, endOfFileTokenLeadingComments, _fileName) { + _super.call(this); + this.moduleElements = moduleElements; + this.endOfFileTokenLeadingComments = endOfFileTokenLeadingComments; + this._fileName = _fileName; + moduleElements && (moduleElements.parent = this); + } + SourceUnit.prototype.fileName = function () { + return this._fileName; + }; + + SourceUnit.prototype.kind = function () { + return 120 /* SourceUnit */; + }; + + SourceUnit.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.moduleElements, ast.moduleElements, includingPosition); + }; + return SourceUnit; + })(AST); + TypeScript.SourceUnit = SourceUnit; + + var Identifier = (function (_super) { + __extends(Identifier, _super); + function Identifier(_text) { + _super.call(this); + this._text = _text; + this._valueText = null; + } + Identifier.prototype.text = function () { + return this._text; + }; + Identifier.prototype.valueText = function () { + if (!this._valueText) { + var text = this._text; + if (text === "__proto__") { + this._valueText = "#__proto__"; + } else { + this._valueText = TypeScript.Syntax.massageEscapes(text); + } + } + + return this._valueText; + }; + + Identifier.prototype.kind = function () { + return 11 /* IdentifierName */; + }; + + Identifier.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._text === ast._text; + }; + + Identifier.prototype.isExpression = function () { + return true; + }; + return Identifier; + })(AST); + TypeScript.Identifier = Identifier; + + var LiteralExpression = (function (_super) { + __extends(LiteralExpression, _super); + function LiteralExpression(_nodeType, _text, _valueText) { + _super.call(this); + this._nodeType = _nodeType; + this._text = _text; + this._valueText = _valueText; + } + LiteralExpression.prototype.text = function () { + return this._text; + }; + + LiteralExpression.prototype.valueText = function () { + return this._valueText; + }; + + LiteralExpression.prototype.kind = function () { + return this._nodeType; + }; + + LiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + LiteralExpression.prototype.isExpression = function () { + return true; + }; + return LiteralExpression; + })(AST); + TypeScript.LiteralExpression = LiteralExpression; + + var ThisExpression = (function (_super) { + __extends(ThisExpression, _super); + function ThisExpression(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + } + ThisExpression.prototype.text = function () { + return this._text; + }; + + ThisExpression.prototype.valueText = function () { + return this._valueText; + }; + + ThisExpression.prototype.kind = function () { + return 35 /* ThisKeyword */; + }; + + ThisExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + ThisExpression.prototype.isExpression = function () { + return true; + }; + return ThisExpression; + })(AST); + TypeScript.ThisExpression = ThisExpression; + + var SuperExpression = (function (_super) { + __extends(SuperExpression, _super); + function SuperExpression(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + } + SuperExpression.prototype.text = function () { + return this._text; + }; + + SuperExpression.prototype.valueText = function () { + return this._valueText; + }; + + SuperExpression.prototype.kind = function () { + return 50 /* SuperKeyword */; + }; + + SuperExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + SuperExpression.prototype.isExpression = function () { + return true; + }; + return SuperExpression; + })(AST); + TypeScript.SuperExpression = SuperExpression; + + var NumericLiteral = (function (_super) { + __extends(NumericLiteral, _super); + function NumericLiteral(_value, _text, _valueText) { + _super.call(this); + this._value = _value; + this._text = _text; + this._valueText = _valueText; + } + NumericLiteral.prototype.text = function () { + return this._text; + }; + NumericLiteral.prototype.valueText = function () { + return this._valueText; + }; + NumericLiteral.prototype.value = function () { + return this._value; + }; + + NumericLiteral.prototype.kind = function () { + return 13 /* NumericLiteral */; + }; + + NumericLiteral.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && (this._value === ast._value || (isNaN(this._value) && isNaN(ast._value))) && this._text === ast._text; + }; + + NumericLiteral.prototype.isExpression = function () { + return true; + }; + return NumericLiteral; + })(AST); + TypeScript.NumericLiteral = NumericLiteral; + + var RegularExpressionLiteral = (function (_super) { + __extends(RegularExpressionLiteral, _super); + function RegularExpressionLiteral(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + } + RegularExpressionLiteral.prototype.text = function () { + return this._text; + }; + + RegularExpressionLiteral.prototype.valueText = function () { + return this._valueText; + }; + + RegularExpressionLiteral.prototype.kind = function () { + return 12 /* RegularExpressionLiteral */; + }; + + RegularExpressionLiteral.prototype.isExpression = function () { + return true; + }; + return RegularExpressionLiteral; + })(AST); + TypeScript.RegularExpressionLiteral = RegularExpressionLiteral; + + var StringLiteral = (function (_super) { + __extends(StringLiteral, _super); + function StringLiteral(_text, _valueText) { + _super.call(this); + this._text = _text; + this._valueText = _valueText; + this._valueText = _valueText === "__proto__" ? "#__proto__" : _valueText; + } + StringLiteral.prototype.text = function () { + return this._text; + }; + StringLiteral.prototype.valueText = function () { + return this._valueText; + }; + + StringLiteral.prototype.kind = function () { + return 14 /* StringLiteral */; + }; + + StringLiteral.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && this._text === ast._text; + }; + + StringLiteral.prototype.isExpression = function () { + return true; + }; + return StringLiteral; + })(AST); + TypeScript.StringLiteral = StringLiteral; + + var TypeAnnotation = (function (_super) { + __extends(TypeAnnotation, _super); + function TypeAnnotation(type) { + _super.call(this); + this.type = type; + type && (type.parent = this); + } + TypeAnnotation.prototype.kind = function () { + return 244 /* TypeAnnotation */; + }; + return TypeAnnotation; + })(AST); + TypeScript.TypeAnnotation = TypeAnnotation; + + var BuiltInType = (function (_super) { + __extends(BuiltInType, _super); + function BuiltInType(_nodeType, _text, _valueText) { + _super.call(this); + this._nodeType = _nodeType; + this._text = _text; + this._valueText = _valueText; + } + BuiltInType.prototype.text = function () { + return this._text; + }; + + BuiltInType.prototype.valueText = function () { + return this._valueText; + }; + + BuiltInType.prototype.kind = function () { + return this._nodeType; + }; + return BuiltInType; + })(AST); + TypeScript.BuiltInType = BuiltInType; + + var ExternalModuleReference = (function (_super) { + __extends(ExternalModuleReference, _super); + function ExternalModuleReference(stringLiteral) { + _super.call(this); + this.stringLiteral = stringLiteral; + stringLiteral && (stringLiteral.parent = this); + } + ExternalModuleReference.prototype.kind = function () { + return 245 /* ExternalModuleReference */; + }; + return ExternalModuleReference; + })(AST); + TypeScript.ExternalModuleReference = ExternalModuleReference; + + var ModuleNameModuleReference = (function (_super) { + __extends(ModuleNameModuleReference, _super); + function ModuleNameModuleReference(moduleName) { + _super.call(this); + this.moduleName = moduleName; + moduleName && (moduleName.parent = this); + } + ModuleNameModuleReference.prototype.kind = function () { + return 246 /* ModuleNameModuleReference */; + }; + return ModuleNameModuleReference; + })(AST); + TypeScript.ModuleNameModuleReference = ModuleNameModuleReference; + + var ImportDeclaration = (function (_super) { + __extends(ImportDeclaration, _super); + function ImportDeclaration(modifiers, identifier, moduleReference) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.moduleReference = moduleReference; + identifier && (identifier.parent = this); + moduleReference && (moduleReference.parent = this); + } + ImportDeclaration.prototype.kind = function () { + return 133 /* ImportDeclaration */; + }; + + ImportDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.moduleReference, ast.moduleReference, includingPosition); + }; + return ImportDeclaration; + })(AST); + TypeScript.ImportDeclaration = ImportDeclaration; + + var ExportAssignment = (function (_super) { + __extends(ExportAssignment, _super); + function ExportAssignment(identifier) { + _super.call(this); + this.identifier = identifier; + identifier && (identifier.parent = this); + } + ExportAssignment.prototype.kind = function () { + return 134 /* ExportAssignment */; + }; + + ExportAssignment.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition); + }; + return ExportAssignment; + })(AST); + TypeScript.ExportAssignment = ExportAssignment; + + var TypeParameterList = (function (_super) { + __extends(TypeParameterList, _super); + function TypeParameterList(typeParameters) { + _super.call(this); + this.typeParameters = typeParameters; + typeParameters && (typeParameters.parent = this); + } + TypeParameterList.prototype.kind = function () { + return 229 /* TypeParameterList */; + }; + return TypeParameterList; + })(AST); + TypeScript.TypeParameterList = TypeParameterList; + + var ClassDeclaration = (function (_super) { + __extends(ClassDeclaration, _super); + function ClassDeclaration(modifiers, identifier, typeParameterList, heritageClauses, classElements, closeBraceToken) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.classElements = classElements; + this.closeBraceToken = closeBraceToken; + identifier && (identifier.parent = this); + typeParameterList && (typeParameterList.parent = this); + heritageClauses && (heritageClauses.parent = this); + classElements && (classElements.parent = this); + } + ClassDeclaration.prototype.kind = function () { + return 131 /* ClassDeclaration */; + }; + + ClassDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.classElements, ast.classElements, includingPosition) && structuralEquals(this.typeParameterList, ast.typeParameterList, includingPosition) && structuralEquals(this.heritageClauses, ast.heritageClauses, includingPosition); + }; + return ClassDeclaration; + })(AST); + TypeScript.ClassDeclaration = ClassDeclaration; + + var InterfaceDeclaration = (function (_super) { + __extends(InterfaceDeclaration, _super); + function InterfaceDeclaration(modifiers, identifier, typeParameterList, heritageClauses, body) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.typeParameterList = typeParameterList; + this.heritageClauses = heritageClauses; + this.body = body; + identifier && (identifier.parent = this); + typeParameterList && (typeParameterList.parent = this); + body && (body.parent = this); + heritageClauses && (heritageClauses.parent = this); + } + InterfaceDeclaration.prototype.kind = function () { + return 128 /* InterfaceDeclaration */; + }; + + InterfaceDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.body, ast.body, includingPosition) && structuralEquals(this.typeParameterList, ast.typeParameterList, includingPosition) && structuralEquals(this.heritageClauses, ast.heritageClauses, includingPosition); + }; + return InterfaceDeclaration; + })(AST); + TypeScript.InterfaceDeclaration = InterfaceDeclaration; + + var HeritageClause = (function (_super) { + __extends(HeritageClause, _super); + function HeritageClause(_nodeType, typeNames) { + _super.call(this); + this._nodeType = _nodeType; + this.typeNames = typeNames; + typeNames && (typeNames.parent = this); + } + HeritageClause.prototype.kind = function () { + return this._nodeType; + }; + + HeritageClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.typeNames, ast.typeNames, includingPosition); + }; + return HeritageClause; + })(AST); + TypeScript.HeritageClause = HeritageClause; + + var ModuleDeclaration = (function (_super) { + __extends(ModuleDeclaration, _super); + function ModuleDeclaration(modifiers, name, stringLiteral, moduleElements, endingToken) { + _super.call(this); + this.modifiers = modifiers; + this.name = name; + this.stringLiteral = stringLiteral; + this.moduleElements = moduleElements; + this.endingToken = endingToken; + name && (name.parent = this); + stringLiteral && (stringLiteral.parent = this); + moduleElements && (moduleElements.parent = this); + } + ModuleDeclaration.prototype.kind = function () { + return 130 /* ModuleDeclaration */; + }; + + ModuleDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.moduleElements, ast.moduleElements, includingPosition); + }; + return ModuleDeclaration; + })(AST); + TypeScript.ModuleDeclaration = ModuleDeclaration; + + var FunctionDeclaration = (function (_super) { + __extends(FunctionDeclaration, _super); + function FunctionDeclaration(modifiers, identifier, callSignature, block) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + identifier && (identifier.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + FunctionDeclaration.prototype.kind = function () { + return 129 /* FunctionDeclaration */; + }; + + FunctionDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.block, ast.block, includingPosition) && structuralEquals(this.callSignature, ast.callSignature, includingPosition); + }; + return FunctionDeclaration; + })(AST); + TypeScript.FunctionDeclaration = FunctionDeclaration; + + var VariableStatement = (function (_super) { + __extends(VariableStatement, _super); + function VariableStatement(modifiers, declaration) { + _super.call(this); + this.modifiers = modifiers; + this.declaration = declaration; + declaration && (declaration.parent = this); + } + VariableStatement.prototype.kind = function () { + return 148 /* VariableStatement */; + }; + + VariableStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.declaration, ast.declaration, includingPosition); + }; + return VariableStatement; + })(AST); + TypeScript.VariableStatement = VariableStatement; + + var VariableDeclaration = (function (_super) { + __extends(VariableDeclaration, _super); + function VariableDeclaration(declarators) { + _super.call(this); + this.declarators = declarators; + declarators && (declarators.parent = this); + } + VariableDeclaration.prototype.kind = function () { + return 224 /* VariableDeclaration */; + }; + + VariableDeclaration.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.declarators, ast.declarators, includingPosition); + }; + return VariableDeclaration; + })(AST); + TypeScript.VariableDeclaration = VariableDeclaration; + + var VariableDeclarator = (function (_super) { + __extends(VariableDeclarator, _super); + function VariableDeclarator(propertyName, typeAnnotation, equalsValueClause) { + _super.call(this); + this.propertyName = propertyName; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + propertyName && (propertyName.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + equalsValueClause && (equalsValueClause.parent = this); + } + VariableDeclarator.prototype.kind = function () { + return 225 /* VariableDeclarator */; + }; + return VariableDeclarator; + })(AST); + TypeScript.VariableDeclarator = VariableDeclarator; + + var EqualsValueClause = (function (_super) { + __extends(EqualsValueClause, _super); + function EqualsValueClause(value) { + _super.call(this); + this.value = value; + value && (value.parent = this); + } + EqualsValueClause.prototype.kind = function () { + return 232 /* EqualsValueClause */; + }; + return EqualsValueClause; + })(AST); + TypeScript.EqualsValueClause = EqualsValueClause; + + var PrefixUnaryExpression = (function (_super) { + __extends(PrefixUnaryExpression, _super); + function PrefixUnaryExpression(_nodeType, operand) { + _super.call(this); + this._nodeType = _nodeType; + this.operand = operand; + operand && (operand.parent = this); + } + PrefixUnaryExpression.prototype.kind = function () { + return this._nodeType; + }; + + PrefixUnaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand, ast.operand, includingPosition); + }; + + PrefixUnaryExpression.prototype.isExpression = function () { + return true; + }; + return PrefixUnaryExpression; + })(AST); + TypeScript.PrefixUnaryExpression = PrefixUnaryExpression; + + var ArrayLiteralExpression = (function (_super) { + __extends(ArrayLiteralExpression, _super); + function ArrayLiteralExpression(expressions) { + _super.call(this); + this.expressions = expressions; + expressions && (expressions.parent = this); + } + ArrayLiteralExpression.prototype.kind = function () { + return 214 /* ArrayLiteralExpression */; + }; + + ArrayLiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expressions, ast.expressions, includingPosition); + }; + + ArrayLiteralExpression.prototype.isExpression = function () { + return true; + }; + return ArrayLiteralExpression; + })(AST); + TypeScript.ArrayLiteralExpression = ArrayLiteralExpression; + + var OmittedExpression = (function (_super) { + __extends(OmittedExpression, _super); + function OmittedExpression() { + _super.apply(this, arguments); + } + OmittedExpression.prototype.kind = function () { + return 223 /* OmittedExpression */; + }; + + OmittedExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + + OmittedExpression.prototype.isExpression = function () { + return true; + }; + return OmittedExpression; + })(AST); + TypeScript.OmittedExpression = OmittedExpression; + + var ParenthesizedExpression = (function (_super) { + __extends(ParenthesizedExpression, _super); + function ParenthesizedExpression(openParenTrailingComments, expression) { + _super.call(this); + this.openParenTrailingComments = openParenTrailingComments; + this.expression = expression; + expression && (expression.parent = this); + } + ParenthesizedExpression.prototype.kind = function () { + return 217 /* ParenthesizedExpression */; + }; + + ParenthesizedExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + ParenthesizedExpression.prototype.isExpression = function () { + return true; + }; + return ParenthesizedExpression; + })(AST); + TypeScript.ParenthesizedExpression = ParenthesizedExpression; + + var SimpleArrowFunctionExpression = (function (_super) { + __extends(SimpleArrowFunctionExpression, _super); + function SimpleArrowFunctionExpression(identifier, block, expression) { + _super.call(this); + this.identifier = identifier; + this.block = block; + this.expression = expression; + identifier && (identifier.parent = this); + block && (block.parent = this); + expression && (expression.parent = this); + } + SimpleArrowFunctionExpression.prototype.kind = function () { + return 219 /* SimpleArrowFunctionExpression */; + }; + + SimpleArrowFunctionExpression.prototype.isExpression = function () { + return true; + }; + return SimpleArrowFunctionExpression; + })(AST); + TypeScript.SimpleArrowFunctionExpression = SimpleArrowFunctionExpression; + + var ParenthesizedArrowFunctionExpression = (function (_super) { + __extends(ParenthesizedArrowFunctionExpression, _super); + function ParenthesizedArrowFunctionExpression(callSignature, block, expression) { + _super.call(this); + this.callSignature = callSignature; + this.block = block; + this.expression = expression; + callSignature && (callSignature.parent = this); + block && (block.parent = this); + expression && (expression.parent = this); + } + ParenthesizedArrowFunctionExpression.prototype.kind = function () { + return 218 /* ParenthesizedArrowFunctionExpression */; + }; + + ParenthesizedArrowFunctionExpression.prototype.isExpression = function () { + return true; + }; + return ParenthesizedArrowFunctionExpression; + })(AST); + TypeScript.ParenthesizedArrowFunctionExpression = ParenthesizedArrowFunctionExpression; + + var QualifiedName = (function (_super) { + __extends(QualifiedName, _super); + function QualifiedName(left, right) { + _super.call(this); + this.left = left; + this.right = right; + left && (left.parent = this); + right && (right.parent = this); + } + QualifiedName.prototype.kind = function () { + return 121 /* QualifiedName */; + }; + + QualifiedName.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.left, ast.left, includingPosition) && structuralEquals(this.right, ast.right, includingPosition); + }; + return QualifiedName; + })(AST); + TypeScript.QualifiedName = QualifiedName; + + var ParameterList = (function (_super) { + __extends(ParameterList, _super); + function ParameterList(openParenTrailingComments, parameters) { + _super.call(this); + this.openParenTrailingComments = openParenTrailingComments; + this.parameters = parameters; + parameters && (parameters.parent = this); + } + ParameterList.prototype.kind = function () { + return 227 /* ParameterList */; + }; + return ParameterList; + })(AST); + TypeScript.ParameterList = ParameterList; + + var ConstructorType = (function (_super) { + __extends(ConstructorType, _super); + function ConstructorType(typeParameterList, parameterList, type) { + _super.call(this); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.type = type; + typeParameterList && (typeParameterList.parent = this); + parameterList && (parameterList.parent = this); + type && (type.parent = this); + } + ConstructorType.prototype.kind = function () { + return 125 /* ConstructorType */; + }; + return ConstructorType; + })(AST); + TypeScript.ConstructorType = ConstructorType; + + var FunctionType = (function (_super) { + __extends(FunctionType, _super); + function FunctionType(typeParameterList, parameterList, type) { + _super.call(this); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.type = type; + typeParameterList && (typeParameterList.parent = this); + parameterList && (parameterList.parent = this); + type && (type.parent = this); + } + FunctionType.prototype.kind = function () { + return 123 /* FunctionType */; + }; + return FunctionType; + })(AST); + TypeScript.FunctionType = FunctionType; + + var ObjectType = (function (_super) { + __extends(ObjectType, _super); + function ObjectType(typeMembers) { + _super.call(this); + this.typeMembers = typeMembers; + typeMembers && (typeMembers.parent = this); + } + ObjectType.prototype.kind = function () { + return 122 /* ObjectType */; + }; + + ObjectType.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.typeMembers, ast.typeMembers, includingPosition); + }; + return ObjectType; + })(AST); + TypeScript.ObjectType = ObjectType; + + var ArrayType = (function (_super) { + __extends(ArrayType, _super); + function ArrayType(type) { + _super.call(this); + this.type = type; + type && (type.parent = this); + } + ArrayType.prototype.kind = function () { + return 124 /* ArrayType */; + }; + + ArrayType.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.type, ast.type, includingPosition); + }; + return ArrayType; + })(AST); + TypeScript.ArrayType = ArrayType; + + var TypeArgumentList = (function (_super) { + __extends(TypeArgumentList, _super); + function TypeArgumentList(typeArguments) { + _super.call(this); + this.typeArguments = typeArguments; + typeArguments && (typeArguments.parent = this); + } + TypeArgumentList.prototype.kind = function () { + return 228 /* TypeArgumentList */; + }; + return TypeArgumentList; + })(AST); + TypeScript.TypeArgumentList = TypeArgumentList; + + var GenericType = (function (_super) { + __extends(GenericType, _super); + function GenericType(name, typeArgumentList) { + _super.call(this); + this.name = name; + this.typeArgumentList = typeArgumentList; + name && (name.parent = this); + typeArgumentList && (typeArgumentList.parent = this); + } + GenericType.prototype.kind = function () { + return 126 /* GenericType */; + }; + + GenericType.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition) && structuralEquals(this.typeArgumentList, ast.typeArgumentList, includingPosition); + }; + return GenericType; + })(AST); + TypeScript.GenericType = GenericType; + + var TypeQuery = (function (_super) { + __extends(TypeQuery, _super); + function TypeQuery(name) { + _super.call(this); + this.name = name; + name && (name.parent = this); + } + TypeQuery.prototype.kind = function () { + return 127 /* TypeQuery */; + }; + + TypeQuery.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.name, ast.name, includingPosition); + }; + return TypeQuery; + })(AST); + TypeScript.TypeQuery = TypeQuery; + + var Block = (function (_super) { + __extends(Block, _super); + function Block(statements, closeBraceLeadingComments, closeBraceToken) { + _super.call(this); + this.statements = statements; + this.closeBraceLeadingComments = closeBraceLeadingComments; + this.closeBraceToken = closeBraceToken; + statements && (statements.parent = this); + } + Block.prototype.kind = function () { + return 146 /* Block */; + }; + + Block.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statements, ast.statements, includingPosition); + }; + return Block; + })(AST); + TypeScript.Block = Block; + + var Parameter = (function (_super) { + __extends(Parameter, _super); + function Parameter(dotDotDotToken, modifiers, identifier, questionToken, typeAnnotation, equalsValueClause) { + _super.call(this); + this.dotDotDotToken = dotDotDotToken; + this.modifiers = modifiers; + this.identifier = identifier; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + this.equalsValueClause = equalsValueClause; + identifier && (identifier.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + equalsValueClause && (equalsValueClause.parent = this); + } + Parameter.prototype.kind = function () { + return 242 /* Parameter */; + }; + return Parameter; + })(AST); + TypeScript.Parameter = Parameter; + + var MemberAccessExpression = (function (_super) { + __extends(MemberAccessExpression, _super); + function MemberAccessExpression(expression, name) { + _super.call(this); + this.expression = expression; + this.name = name; + expression && (expression.parent = this); + name && (name.parent = this); + } + MemberAccessExpression.prototype.kind = function () { + return 212 /* MemberAccessExpression */; + }; + + MemberAccessExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.name, ast.name, includingPosition); + }; + + MemberAccessExpression.prototype.isExpression = function () { + return true; + }; + return MemberAccessExpression; + })(AST); + TypeScript.MemberAccessExpression = MemberAccessExpression; + + var PostfixUnaryExpression = (function (_super) { + __extends(PostfixUnaryExpression, _super); + function PostfixUnaryExpression(_nodeType, operand) { + _super.call(this); + this._nodeType = _nodeType; + this.operand = operand; + operand && (operand.parent = this); + } + PostfixUnaryExpression.prototype.kind = function () { + return this._nodeType; + }; + + PostfixUnaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.operand, ast.operand, includingPosition); + }; + + PostfixUnaryExpression.prototype.isExpression = function () { + return true; + }; + return PostfixUnaryExpression; + })(AST); + TypeScript.PostfixUnaryExpression = PostfixUnaryExpression; + + var ElementAccessExpression = (function (_super) { + __extends(ElementAccessExpression, _super); + function ElementAccessExpression(expression, argumentExpression) { + _super.call(this); + this.expression = expression; + this.argumentExpression = argumentExpression; + expression && (expression.parent = this); + argumentExpression && (argumentExpression.parent = this); + } + ElementAccessExpression.prototype.kind = function () { + return 221 /* ElementAccessExpression */; + }; + + ElementAccessExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentExpression, ast.argumentExpression, includingPosition); + }; + + ElementAccessExpression.prototype.isExpression = function () { + return true; + }; + return ElementAccessExpression; + })(AST); + TypeScript.ElementAccessExpression = ElementAccessExpression; + + var InvocationExpression = (function (_super) { + __extends(InvocationExpression, _super); + function InvocationExpression(expression, argumentList) { + _super.call(this); + this.expression = expression; + this.argumentList = argumentList; + expression && (expression.parent = this); + argumentList && (argumentList.parent = this); + } + InvocationExpression.prototype.kind = function () { + return 213 /* InvocationExpression */; + }; + + InvocationExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentList, ast.argumentList, includingPosition); + }; + + InvocationExpression.prototype.isExpression = function () { + return true; + }; + return InvocationExpression; + })(AST); + TypeScript.InvocationExpression = InvocationExpression; + + var ArgumentList = (function (_super) { + __extends(ArgumentList, _super); + function ArgumentList(typeArgumentList, _arguments, closeParenToken) { + _super.call(this); + this.typeArgumentList = typeArgumentList; + this.closeParenToken = closeParenToken; + this.arguments = _arguments; + + typeArgumentList && (typeArgumentList.parent = this); + _arguments && (_arguments.parent = this); + } + ArgumentList.prototype.kind = function () { + return 226 /* ArgumentList */; + }; + return ArgumentList; + })(AST); + TypeScript.ArgumentList = ArgumentList; + + var BinaryExpression = (function (_super) { + __extends(BinaryExpression, _super); + function BinaryExpression(_nodeType, left, right) { + _super.call(this); + this._nodeType = _nodeType; + this.left = left; + this.right = right; + left && (left.parent = this); + right && (right.parent = this); + } + BinaryExpression.prototype.kind = function () { + return this._nodeType; + }; + + BinaryExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.left, ast.left, includingPosition) && structuralEquals(this.right, ast.right, includingPosition); + }; + + BinaryExpression.prototype.isExpression = function () { + return true; + }; + return BinaryExpression; + })(AST); + TypeScript.BinaryExpression = BinaryExpression; + + var ConditionalExpression = (function (_super) { + __extends(ConditionalExpression, _super); + function ConditionalExpression(condition, whenTrue, whenFalse) { + _super.call(this); + this.condition = condition; + this.whenTrue = whenTrue; + this.whenFalse = whenFalse; + condition && (condition.parent = this); + whenTrue && (whenTrue.parent = this); + whenFalse && (whenFalse.parent = this); + } + ConditionalExpression.prototype.kind = function () { + return 186 /* ConditionalExpression */; + }; + + ConditionalExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.whenTrue, ast.whenTrue, includingPosition) && structuralEquals(this.whenFalse, ast.whenFalse, includingPosition); + }; + + ConditionalExpression.prototype.isExpression = function () { + return true; + }; + return ConditionalExpression; + })(AST); + TypeScript.ConditionalExpression = ConditionalExpression; + + var ConstructSignature = (function (_super) { + __extends(ConstructSignature, _super); + function ConstructSignature(callSignature) { + _super.call(this); + this.callSignature = callSignature; + callSignature && (callSignature.parent = this); + } + ConstructSignature.prototype.kind = function () { + return 143 /* ConstructSignature */; + }; + return ConstructSignature; + })(AST); + TypeScript.ConstructSignature = ConstructSignature; + + var MethodSignature = (function (_super) { + __extends(MethodSignature, _super); + function MethodSignature(propertyName, questionToken, callSignature) { + _super.call(this); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.callSignature = callSignature; + propertyName && (propertyName.parent = this); + callSignature && (callSignature.parent = this); + } + MethodSignature.prototype.kind = function () { + return 145 /* MethodSignature */; + }; + return MethodSignature; + })(AST); + TypeScript.MethodSignature = MethodSignature; + + var IndexSignature = (function (_super) { + __extends(IndexSignature, _super); + function IndexSignature(parameter, typeAnnotation) { + _super.call(this); + this.parameter = parameter; + this.typeAnnotation = typeAnnotation; + parameter && (parameter.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + } + IndexSignature.prototype.kind = function () { + return 144 /* IndexSignature */; + }; + return IndexSignature; + })(AST); + TypeScript.IndexSignature = IndexSignature; + + var PropertySignature = (function (_super) { + __extends(PropertySignature, _super); + function PropertySignature(propertyName, questionToken, typeAnnotation) { + _super.call(this); + this.propertyName = propertyName; + this.questionToken = questionToken; + this.typeAnnotation = typeAnnotation; + propertyName && (propertyName.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + } + PropertySignature.prototype.kind = function () { + return 141 /* PropertySignature */; + }; + return PropertySignature; + })(AST); + TypeScript.PropertySignature = PropertySignature; + + var CallSignature = (function (_super) { + __extends(CallSignature, _super); + function CallSignature(typeParameterList, parameterList, typeAnnotation) { + _super.call(this); + this.typeParameterList = typeParameterList; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + typeParameterList && (typeParameterList.parent = this); + parameterList && (parameterList.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + } + CallSignature.prototype.kind = function () { + return 142 /* CallSignature */; + }; + return CallSignature; + })(AST); + TypeScript.CallSignature = CallSignature; + + var TypeParameter = (function (_super) { + __extends(TypeParameter, _super); + function TypeParameter(identifier, constraint) { + _super.call(this); + this.identifier = identifier; + this.constraint = constraint; + identifier && (identifier.parent = this); + constraint && (constraint.parent = this); + } + TypeParameter.prototype.kind = function () { + return 238 /* TypeParameter */; + }; + + TypeParameter.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.constraint, ast.constraint, includingPosition); + }; + return TypeParameter; + })(AST); + TypeScript.TypeParameter = TypeParameter; + + var Constraint = (function (_super) { + __extends(Constraint, _super); + function Constraint(type) { + _super.call(this); + this.type = type; + type && (type.parent = this); + } + Constraint.prototype.kind = function () { + return 239 /* Constraint */; + }; + return Constraint; + })(AST); + TypeScript.Constraint = Constraint; + + var ElseClause = (function (_super) { + __extends(ElseClause, _super); + function ElseClause(statement) { + _super.call(this); + this.statement = statement; + statement && (statement.parent = this); + } + ElseClause.prototype.kind = function () { + return 235 /* ElseClause */; + }; + + ElseClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return ElseClause; + })(AST); + TypeScript.ElseClause = ElseClause; + + var IfStatement = (function (_super) { + __extends(IfStatement, _super); + function IfStatement(condition, statement, elseClause) { + _super.call(this); + this.condition = condition; + this.statement = statement; + this.elseClause = elseClause; + condition && (condition.parent = this); + statement && (statement.parent = this); + elseClause && (elseClause.parent = this); + } + IfStatement.prototype.kind = function () { + return 147 /* IfStatement */; + }; + + IfStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition) && structuralEquals(this.elseClause, ast.elseClause, includingPosition); + }; + return IfStatement; + })(AST); + TypeScript.IfStatement = IfStatement; + + var ExpressionStatement = (function (_super) { + __extends(ExpressionStatement, _super); + function ExpressionStatement(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + ExpressionStatement.prototype.kind = function () { + return 149 /* ExpressionStatement */; + }; + + ExpressionStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ExpressionStatement; + })(AST); + TypeScript.ExpressionStatement = ExpressionStatement; + + var ConstructorDeclaration = (function (_super) { + __extends(ConstructorDeclaration, _super); + function ConstructorDeclaration(callSignature, block) { + _super.call(this); + this.callSignature = callSignature; + this.block = block; + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + ConstructorDeclaration.prototype.kind = function () { + return 137 /* ConstructorDeclaration */; + }; + return ConstructorDeclaration; + })(AST); + TypeScript.ConstructorDeclaration = ConstructorDeclaration; + + var MemberFunctionDeclaration = (function (_super) { + __extends(MemberFunctionDeclaration, _super); + function MemberFunctionDeclaration(modifiers, propertyName, callSignature, block) { + _super.call(this); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + propertyName && (propertyName.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + MemberFunctionDeclaration.prototype.kind = function () { + return 135 /* MemberFunctionDeclaration */; + }; + return MemberFunctionDeclaration; + })(AST); + TypeScript.MemberFunctionDeclaration = MemberFunctionDeclaration; + + var GetAccessor = (function (_super) { + __extends(GetAccessor, _super); + function GetAccessor(modifiers, propertyName, parameterList, typeAnnotation, block) { + _super.call(this); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.typeAnnotation = typeAnnotation; + this.block = block; + propertyName && (propertyName.parent = this); + parameterList && (parameterList.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + block && (block.parent = this); + } + GetAccessor.prototype.kind = function () { + return 139 /* GetAccessor */; + }; + return GetAccessor; + })(AST); + TypeScript.GetAccessor = GetAccessor; + + var SetAccessor = (function (_super) { + __extends(SetAccessor, _super); + function SetAccessor(modifiers, propertyName, parameterList, block) { + _super.call(this); + this.modifiers = modifiers; + this.propertyName = propertyName; + this.parameterList = parameterList; + this.block = block; + propertyName && (propertyName.parent = this); + parameterList && (parameterList.parent = this); + block && (block.parent = this); + } + SetAccessor.prototype.kind = function () { + return 140 /* SetAccessor */; + }; + return SetAccessor; + })(AST); + TypeScript.SetAccessor = SetAccessor; + + var MemberVariableDeclaration = (function (_super) { + __extends(MemberVariableDeclaration, _super); + function MemberVariableDeclaration(modifiers, variableDeclarator) { + _super.call(this); + this.modifiers = modifiers; + this.variableDeclarator = variableDeclarator; + variableDeclarator && (variableDeclarator.parent = this); + } + MemberVariableDeclaration.prototype.kind = function () { + return 136 /* MemberVariableDeclaration */; + }; + return MemberVariableDeclaration; + })(AST); + TypeScript.MemberVariableDeclaration = MemberVariableDeclaration; + + var IndexMemberDeclaration = (function (_super) { + __extends(IndexMemberDeclaration, _super); + function IndexMemberDeclaration(indexSignature) { + _super.call(this); + this.indexSignature = indexSignature; + indexSignature && (indexSignature.parent = this); + } + IndexMemberDeclaration.prototype.kind = function () { + return 138 /* IndexMemberDeclaration */; + }; + return IndexMemberDeclaration; + })(AST); + TypeScript.IndexMemberDeclaration = IndexMemberDeclaration; + + var ThrowStatement = (function (_super) { + __extends(ThrowStatement, _super); + function ThrowStatement(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + ThrowStatement.prototype.kind = function () { + return 157 /* ThrowStatement */; + }; + + ThrowStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ThrowStatement; + })(AST); + TypeScript.ThrowStatement = ThrowStatement; + + var ReturnStatement = (function (_super) { + __extends(ReturnStatement, _super); + function ReturnStatement(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + ReturnStatement.prototype.kind = function () { + return 150 /* ReturnStatement */; + }; + + ReturnStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return ReturnStatement; + })(AST); + TypeScript.ReturnStatement = ReturnStatement; + + var ObjectCreationExpression = (function (_super) { + __extends(ObjectCreationExpression, _super); + function ObjectCreationExpression(expression, argumentList) { + _super.call(this); + this.expression = expression; + this.argumentList = argumentList; + expression && (expression.parent = this); + argumentList && (argumentList.parent = this); + } + ObjectCreationExpression.prototype.kind = function () { + return 216 /* ObjectCreationExpression */; + }; + + ObjectCreationExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.argumentList, ast.argumentList, includingPosition); + }; + + ObjectCreationExpression.prototype.isExpression = function () { + return true; + }; + return ObjectCreationExpression; + })(AST); + TypeScript.ObjectCreationExpression = ObjectCreationExpression; + + var SwitchStatement = (function (_super) { + __extends(SwitchStatement, _super); + function SwitchStatement(expression, closeParenToken, switchClauses) { + _super.call(this); + this.expression = expression; + this.closeParenToken = closeParenToken; + this.switchClauses = switchClauses; + expression && (expression.parent = this); + switchClauses && (switchClauses.parent = this); + } + SwitchStatement.prototype.kind = function () { + return 151 /* SwitchStatement */; + }; + + SwitchStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.switchClauses, ast.switchClauses, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + return SwitchStatement; + })(AST); + TypeScript.SwitchStatement = SwitchStatement; + + var CaseSwitchClause = (function (_super) { + __extends(CaseSwitchClause, _super); + function CaseSwitchClause(expression, statements) { + _super.call(this); + this.expression = expression; + this.statements = statements; + expression && (expression.parent = this); + statements && (statements.parent = this); + } + CaseSwitchClause.prototype.kind = function () { + return 233 /* CaseSwitchClause */; + }; + + CaseSwitchClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.statements, ast.statements, includingPosition); + }; + return CaseSwitchClause; + })(AST); + TypeScript.CaseSwitchClause = CaseSwitchClause; + + var DefaultSwitchClause = (function (_super) { + __extends(DefaultSwitchClause, _super); + function DefaultSwitchClause(statements) { + _super.call(this); + this.statements = statements; + statements && (statements.parent = this); + } + DefaultSwitchClause.prototype.kind = function () { + return 234 /* DefaultSwitchClause */; + }; + + DefaultSwitchClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statements, ast.statements, includingPosition); + }; + return DefaultSwitchClause; + })(AST); + TypeScript.DefaultSwitchClause = DefaultSwitchClause; + + var BreakStatement = (function (_super) { + __extends(BreakStatement, _super); + function BreakStatement(identifier) { + _super.call(this); + this.identifier = identifier; + } + BreakStatement.prototype.kind = function () { + return 152 /* BreakStatement */; + }; + + BreakStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return BreakStatement; + })(AST); + TypeScript.BreakStatement = BreakStatement; + + var ContinueStatement = (function (_super) { + __extends(ContinueStatement, _super); + function ContinueStatement(identifier) { + _super.call(this); + this.identifier = identifier; + } + ContinueStatement.prototype.kind = function () { + return 153 /* ContinueStatement */; + }; + + ContinueStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return ContinueStatement; + })(AST); + TypeScript.ContinueStatement = ContinueStatement; + + var ForStatement = (function (_super) { + __extends(ForStatement, _super); + function ForStatement(variableDeclaration, initializer, condition, incrementor, statement) { + _super.call(this); + this.variableDeclaration = variableDeclaration; + this.initializer = initializer; + this.condition = condition; + this.incrementor = incrementor; + this.statement = statement; + variableDeclaration && (variableDeclaration.parent = this); + initializer && (initializer.parent = this); + condition && (condition.parent = this); + incrementor && (incrementor.parent = this); + statement && (statement.parent = this); + } + ForStatement.prototype.kind = function () { + return 154 /* ForStatement */; + }; + + ForStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.initializer, ast.initializer, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.incrementor, ast.incrementor, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return ForStatement; + })(AST); + TypeScript.ForStatement = ForStatement; + + var ForInStatement = (function (_super) { + __extends(ForInStatement, _super); + function ForInStatement(variableDeclaration, left, expression, statement) { + _super.call(this); + this.variableDeclaration = variableDeclaration; + this.left = left; + this.expression = expression; + this.statement = statement; + variableDeclaration && (variableDeclaration.parent = this); + left && (left.parent = this); + expression && (expression.parent = this); + statement && (statement.parent = this); + } + ForInStatement.prototype.kind = function () { + return 155 /* ForInStatement */; + }; + + ForInStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.variableDeclaration, ast.variableDeclaration, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return ForInStatement; + })(AST); + TypeScript.ForInStatement = ForInStatement; + + var WhileStatement = (function (_super) { + __extends(WhileStatement, _super); + function WhileStatement(condition, statement) { + _super.call(this); + this.condition = condition; + this.statement = statement; + condition && (condition.parent = this); + statement && (statement.parent = this); + } + WhileStatement.prototype.kind = function () { + return 158 /* WhileStatement */; + }; + + WhileStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return WhileStatement; + })(AST); + TypeScript.WhileStatement = WhileStatement; + + var WithStatement = (function (_super) { + __extends(WithStatement, _super); + function WithStatement(condition, statement) { + _super.call(this); + this.condition = condition; + this.statement = statement; + condition && (condition.parent = this); + statement && (statement.parent = this); + } + WithStatement.prototype.kind = function () { + return 163 /* WithStatement */; + }; + + WithStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return WithStatement; + })(AST); + TypeScript.WithStatement = WithStatement; + + var EnumDeclaration = (function (_super) { + __extends(EnumDeclaration, _super); + function EnumDeclaration(modifiers, identifier, enumElements) { + _super.call(this); + this.modifiers = modifiers; + this.identifier = identifier; + this.enumElements = enumElements; + identifier && (identifier.parent = this); + enumElements && (enumElements.parent = this); + } + EnumDeclaration.prototype.kind = function () { + return 132 /* EnumDeclaration */; + }; + return EnumDeclaration; + })(AST); + TypeScript.EnumDeclaration = EnumDeclaration; + + var EnumElement = (function (_super) { + __extends(EnumElement, _super); + function EnumElement(propertyName, equalsValueClause) { + _super.call(this); + this.propertyName = propertyName; + this.equalsValueClause = equalsValueClause; + propertyName && (propertyName.parent = this); + equalsValueClause && (equalsValueClause.parent = this); + } + EnumElement.prototype.kind = function () { + return 243 /* EnumElement */; + }; + return EnumElement; + })(AST); + TypeScript.EnumElement = EnumElement; + + var CastExpression = (function (_super) { + __extends(CastExpression, _super); + function CastExpression(type, expression) { + _super.call(this); + this.type = type; + this.expression = expression; + type && (type.parent = this); + expression && (expression.parent = this); + } + CastExpression.prototype.kind = function () { + return 220 /* CastExpression */; + }; + + CastExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.type, ast.type, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + CastExpression.prototype.isExpression = function () { + return true; + }; + return CastExpression; + })(AST); + TypeScript.CastExpression = CastExpression; + + var ObjectLiteralExpression = (function (_super) { + __extends(ObjectLiteralExpression, _super); + function ObjectLiteralExpression(propertyAssignments) { + _super.call(this); + this.propertyAssignments = propertyAssignments; + propertyAssignments && (propertyAssignments.parent = this); + } + ObjectLiteralExpression.prototype.kind = function () { + return 215 /* ObjectLiteralExpression */; + }; + + ObjectLiteralExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.propertyAssignments, ast.propertyAssignments, includingPosition); + }; + + ObjectLiteralExpression.prototype.isExpression = function () { + return true; + }; + return ObjectLiteralExpression; + })(AST); + TypeScript.ObjectLiteralExpression = ObjectLiteralExpression; + + var SimplePropertyAssignment = (function (_super) { + __extends(SimplePropertyAssignment, _super); + function SimplePropertyAssignment(propertyName, expression) { + _super.call(this); + this.propertyName = propertyName; + this.expression = expression; + propertyName && (propertyName.parent = this); + expression && (expression.parent = this); + } + SimplePropertyAssignment.prototype.kind = function () { + return 240 /* SimplePropertyAssignment */; + }; + return SimplePropertyAssignment; + })(AST); + TypeScript.SimplePropertyAssignment = SimplePropertyAssignment; + + var FunctionPropertyAssignment = (function (_super) { + __extends(FunctionPropertyAssignment, _super); + function FunctionPropertyAssignment(propertyName, callSignature, block) { + _super.call(this); + this.propertyName = propertyName; + this.callSignature = callSignature; + this.block = block; + propertyName && (propertyName.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + FunctionPropertyAssignment.prototype.kind = function () { + return 241 /* FunctionPropertyAssignment */; + }; + return FunctionPropertyAssignment; + })(AST); + TypeScript.FunctionPropertyAssignment = FunctionPropertyAssignment; + + var FunctionExpression = (function (_super) { + __extends(FunctionExpression, _super); + function FunctionExpression(identifier, callSignature, block) { + _super.call(this); + this.identifier = identifier; + this.callSignature = callSignature; + this.block = block; + identifier && (identifier.parent = this); + callSignature && (callSignature.parent = this); + block && (block.parent = this); + } + FunctionExpression.prototype.kind = function () { + return 222 /* FunctionExpression */; + }; + + FunctionExpression.prototype.isExpression = function () { + return true; + }; + return FunctionExpression; + })(AST); + TypeScript.FunctionExpression = FunctionExpression; + + var EmptyStatement = (function (_super) { + __extends(EmptyStatement, _super); + function EmptyStatement() { + _super.apply(this, arguments); + } + EmptyStatement.prototype.kind = function () { + return 156 /* EmptyStatement */; + }; + + EmptyStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition); + }; + return EmptyStatement; + })(AST); + TypeScript.EmptyStatement = EmptyStatement; + + var TryStatement = (function (_super) { + __extends(TryStatement, _super); + function TryStatement(block, catchClause, finallyClause) { + _super.call(this); + this.block = block; + this.catchClause = catchClause; + this.finallyClause = finallyClause; + block && (block.parent = this); + catchClause && (catchClause.parent = this); + finallyClause && (finallyClause.parent = this); + } + TryStatement.prototype.kind = function () { + return 159 /* TryStatement */; + }; + + TryStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.block, ast.block, includingPosition) && structuralEquals(this.catchClause, ast.catchClause, includingPosition) && structuralEquals(this.finallyClause, ast.finallyClause, includingPosition); + }; + return TryStatement; + })(AST); + TypeScript.TryStatement = TryStatement; + + var CatchClause = (function (_super) { + __extends(CatchClause, _super); + function CatchClause(identifier, typeAnnotation, block) { + _super.call(this); + this.identifier = identifier; + this.typeAnnotation = typeAnnotation; + this.block = block; + identifier && (identifier.parent = this); + typeAnnotation && (typeAnnotation.parent = this); + block && (block.parent = this); + } + CatchClause.prototype.kind = function () { + return 236 /* CatchClause */; + }; + + CatchClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.typeAnnotation, ast.typeAnnotation, includingPosition) && structuralEquals(this.block, ast.block, includingPosition); + }; + return CatchClause; + })(AST); + TypeScript.CatchClause = CatchClause; + + var FinallyClause = (function (_super) { + __extends(FinallyClause, _super); + function FinallyClause(block) { + _super.call(this); + this.block = block; + block && (block.parent = this); + } + FinallyClause.prototype.kind = function () { + return 237 /* FinallyClause */; + }; + + FinallyClause.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.block, ast.block, includingPosition); + }; + return FinallyClause; + })(AST); + TypeScript.FinallyClause = FinallyClause; + + var LabeledStatement = (function (_super) { + __extends(LabeledStatement, _super); + function LabeledStatement(identifier, statement) { + _super.call(this); + this.identifier = identifier; + this.statement = statement; + identifier && (identifier.parent = this); + statement && (statement.parent = this); + } + LabeledStatement.prototype.kind = function () { + return 160 /* LabeledStatement */; + }; + + LabeledStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.identifier, ast.identifier, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition); + }; + return LabeledStatement; + })(AST); + TypeScript.LabeledStatement = LabeledStatement; + + var DoStatement = (function (_super) { + __extends(DoStatement, _super); + function DoStatement(statement, whileKeyword, condition) { + _super.call(this); + this.statement = statement; + this.whileKeyword = whileKeyword; + this.condition = condition; + statement && (statement.parent = this); + condition && (condition.parent = this); + } + DoStatement.prototype.kind = function () { + return 161 /* DoStatement */; + }; + + DoStatement.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.statement, ast.statement, includingPosition) && structuralEquals(this.condition, ast.condition, includingPosition); + }; + return DoStatement; + })(AST); + TypeScript.DoStatement = DoStatement; + + var TypeOfExpression = (function (_super) { + __extends(TypeOfExpression, _super); + function TypeOfExpression(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + TypeOfExpression.prototype.kind = function () { + return 171 /* TypeOfExpression */; + }; + + TypeOfExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + TypeOfExpression.prototype.isExpression = function () { + return true; + }; + return TypeOfExpression; + })(AST); + TypeScript.TypeOfExpression = TypeOfExpression; + + var DeleteExpression = (function (_super) { + __extends(DeleteExpression, _super); + function DeleteExpression(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + DeleteExpression.prototype.kind = function () { + return 170 /* DeleteExpression */; + }; + + DeleteExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + DeleteExpression.prototype.isExpression = function () { + return true; + }; + return DeleteExpression; + })(AST); + TypeScript.DeleteExpression = DeleteExpression; + + var VoidExpression = (function (_super) { + __extends(VoidExpression, _super); + function VoidExpression(expression) { + _super.call(this); + this.expression = expression; + expression && (expression.parent = this); + } + VoidExpression.prototype.kind = function () { + return 172 /* VoidExpression */; + }; + + VoidExpression.prototype.structuralEquals = function (ast, includingPosition) { + return _super.prototype.structuralEquals.call(this, ast, includingPosition) && structuralEquals(this.expression, ast.expression, includingPosition); + }; + + VoidExpression.prototype.isExpression = function () { + return true; + }; + return VoidExpression; + })(AST); + TypeScript.VoidExpression = VoidExpression; + + var DebuggerStatement = (function (_super) { + __extends(DebuggerStatement, _super); + function DebuggerStatement() { + _super.apply(this, arguments); + } + DebuggerStatement.prototype.kind = function () { + return 162 /* DebuggerStatement */; + }; + return DebuggerStatement; + })(AST); + TypeScript.DebuggerStatement = DebuggerStatement; + + var Comment = (function () { + function Comment(_trivia, endsLine, _start, _end) { + this._trivia = _trivia; + this.endsLine = endsLine; + this._start = _start; + this._end = _end; + } + Comment.prototype.start = function () { + return this._start; + }; + + Comment.prototype.end = function () { + return this._end; + }; + + Comment.prototype.fullText = function () { + return this._trivia.fullText(); + }; + + Comment.prototype.kind = function () { + return this._trivia.kind(); + }; + + Comment.prototype.structuralEquals = function (ast, includingPosition) { + if (includingPosition) { + if (this.start() !== ast.start() || this.end() !== ast.end()) { + return false; + } + } + + return this._trivia.fullText() === ast._trivia.fullText() && this.endsLine === ast.endsLine; + }; + return Comment; + })(); + TypeScript.Comment = Comment; +})(TypeScript || (TypeScript = {})); diff --git a/_infrastructure/tests/typings/bluebird/bluebird.d.ts b/_infrastructure/tests/typings/bluebird/bluebird.d.ts deleted file mode 100644 index 45db9d86a3..0000000000 --- a/_infrastructure/tests/typings/bluebird/bluebird.d.ts +++ /dev/null @@ -1,656 +0,0 @@ -// Type definitions for bluebird 1.0.0 -// Project: https://github.com/petkaantonov/bluebird -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -// ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts -// By: Campredon - -// Warning: recommended to use `tsc > v1.0.0` (critical bugs in generic code: -// - https://github.com/borisyankov/DefinitelyTyped/issues/1563 -// - https://github.com/borisyankov/DefinitelyTyped/tree/def/bluebird - -// Note: replicate changes to all overloads in both definition and test file -// Note: keep both static and instance members inline (so similar) - -// TODO fix remaining TODO annotations in both definition and test - -// TODO verify support to have no return statement in handlers to get a Promise (more overloads?) - -declare class Promise implements Promise.Thenable { - /** - * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. - */ - constructor(callback: (resolve: (thenable: Promise.Thenable) => void, reject: (error: any) => void) => void); - constructor(callback: (resolve: (result: R) => void, reject: (error: any) => void) => void); - - /** - * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. - */ - then(onFulfill: (value: R) => Promise.Thenable, onReject: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; - then(onFulfill: (value: R) => Promise.Thenable, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise; - then(onFulfill: (value: R) => U, onReject: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; - then(onFulfill?: (value: R) => U, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise; - - /** - * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. - * - * Alias `.caught();` for compatibility with earlier ECMAScript version. - */ - catch(onReject?: (error: any) => Promise.Thenable): Promise; - caught(onReject?: (error: any) => Promise.Thenable): Promise; - - catch(onReject?: (error: any) => U): Promise; - caught(onReject?: (error: any) => U): Promise; - - /** - * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. - * - * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. - * - * Alias `.caught();` for compatibility with earlier ECMAScript version. - */ - catch(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable): Promise; - caught(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable): Promise; - - catch(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise; - caught(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise; - - catch(ErrorClass: Function, onReject: (error: any) => Promise.Thenable): Promise; - caught(ErrorClass: Function, onReject: (error: any) => Promise.Thenable): Promise; - - catch(ErrorClass: Function, onReject: (error: any) => U): Promise; - caught(ErrorClass: Function, onReject: (error: any) => U): Promise; - - /** - * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. - */ - error(onReject: (reason: any) => Promise.Thenable): Promise; - error(onReject: (reason: any) => U): Promise; - - /** - * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. - * - * Alias `.lastly();` for compatibility with earlier ECMAScript version. - */ - finally(handler: (value: R) => Promise.Thenable): Promise; - finally(handler: (value: R) => R): Promise; - finally(handler: (value: R) => void): Promise; - - lastly(handler: (value: R) => Promise.Thenable): Promise; - lastly(handler: (value: R) => R): Promise; - - /** - * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. - */ - bind(thisArg: any): Promise; - - /** - * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. - */ - done(onFulfilled: (value: R) => Promise.Thenable, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; - done(onFulfilled: (value: R) => Promise.Thenable, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; - done(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; - done(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; - - /** - * Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise. - */ - progressed(handler: (note: any) => any): Promise; - - /** - * Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - delay(ms: number): Promise; - - /** - * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance. - * - * You may specify a custom error message with the `message` parameter. - */ - timeout(ms: number, message?: string): Promise; - - /** - * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. - * Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything. - */ - nodeify(callback: (err: any, value?: R) => void): Promise; - nodeify(...sink: any[]): void; - - /** - * Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise. - */ - cancellable(): Promise; - - /** - * Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending. - * - * That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason. - * - * In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`. - * - * Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable. - */ - // TODO what to do with this? - cancel(): Promise; - - /** - * Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors. - */ - fork(onFulfilled: (value: R) => Promise.Thenable, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; - fork(onFulfilled: (value: R) => Promise.Thenable, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; - fork(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; - fork(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; - - /** - * Create an uncancellable promise based on this promise. - */ - uncancellable(): Promise; - - /** - * See if this promise can be cancelled. - */ - isCancellable(): boolean; - - /** - * See if this `promise` has been fulfilled. - */ - isFulfilled(): boolean; - - /** - * See if this `promise` has been rejected. - */ - isRejected(): boolean; - - /** - * See if this `promise` is still defer. - */ - isPending(): boolean; - - /** - * See if this `promise` is resolved -> either fulfilled or rejected. - */ - isResolved(): boolean; - - /** - * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`. - */ - inspect(): Promise.Inspection; - - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName].call(obj, arg...); - * }); - * - */ - call(propertyName: string, ...args: any[]): Promise; - - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName]; - * }); - * - */ - // TODO find way to fix get() - // get(propertyName: string): Promise; - - /** - * Convenience method for: - * - * - * .then(function() { - * return value; - * }); - * - * - * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` - * - * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. - */ - return(value: U): Promise; - thenReturn(value: U): Promise; - return(): Promise; - thenReturn(): Promise; - - /** - * Convenience method for: - * - * - * .then(function() { - * throw reason; - * }); - * - * Same limitations apply as with `.return()`. - * - * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. - */ - throw(reason: Error): Promise; - thenThrow(reason: Error): Promise; - - /** - * Convert to String. - */ - toString(): string; - - /** - * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. - */ - toJSON(): Object; - - /** - * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. - */ - // TODO how to model instance.spread()? like Q? - spread(onFulfill: Function, onReject?: (reason: any) => Promise.Thenable): Promise; - spread(onFulfill: Function, onReject?: (reason: any) => U): Promise; - /* - // TODO or something like this? - spread(onFulfill: (...values: W[]) => Promise.Thenable, onReject?: (reason: any) => Promise.Thenable): Promise; - spread(onFulfill: (...values: W[]) => Promise.Thenable, onReject?: (reason: any) => U): Promise; - spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => Promise.Thenable): Promise; - spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise; - */ - /** - * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - all(): Promise; - - /** - * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO how to model instance.props()? - props(): Promise; - - /** - * Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - settle(): Promise[]>; - - /** - * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - any(): Promise; - - /** - * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - some(count: number): Promise; - - /** - * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - race(): Promise; - - /** - * Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - map(mapper: (item: Q, index: number, arrayLength: number) => Promise.Thenable): Promise; - map(mapper: (item: Q, index: number, arrayLength: number) => U): Promise; - - /** - * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U, initialValue?: U): Promise; - - /** - * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - filter(filterer: (item: U, index: number, arrayLength: number) => Promise.Thenable): Promise; - filter(filterer: (item: U, index: number, arrayLength: number) => boolean): Promise; -} - -declare module Promise { - - export interface Thenable { - then(onFulfilled: (value: R) => Thenable, onRejected: (error: any) => Thenable): Thenable; - then(onFulfilled: (value: R) => Thenable, onRejected?: (error: any) => U): Thenable; - then(onFulfilled: (value: R) => U, onRejected: (error: any) => Thenable): Thenable; - then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Thenable; - } - - export interface Resolver { - /** - * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. - */ - resolve(value: R): void; - - /** - * Reject the underlying promise with `reason` as the rejection reason. - */ - reject(reason: any): void; - - /** - * Progress the underlying promise with `value` as the progression value. - */ - progress(value: any): void; - - /** - * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. - * - * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. - */ - // TODO specify resolver callback - callback: Function; - } - - export interface Inspection { - /** - * See if the underlying promise was fulfilled at the creation time of this inspection object. - */ - isFulfilled(): boolean; - - /** - * See if the underlying promise was rejected at the creation time of this inspection object. - */ - isRejected(): boolean; - - /** - * See if the underlying promise was defer at the creation time of this inspection object. - */ - isPending(): boolean; - - /** - * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. - * - * throws `TypeError` - */ - value(): R; - - /** - * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. - * - * throws `TypeError` - */ - error(): any; - } - - /** - * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. - * - * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. - * - * Alias for `attempt();` for compatibility with earlier ECMAScript version. - */ - // TODO find way to enable try() without tsc borking - // see also: https://typescript.codeplex.com/workitem/2194 - /* - export function try(fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; - export function try(fn: () => R, args?: any[], ctx?: any): Promise; - */ - - export function attempt(fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; - export function attempt(fn: () => R, args?: any[], ctx?: any): Promise; - - /** - * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. - * This method is convenient when a function can sometimes return synchronously or throw synchronously. - */ - export function method(fn: Function): Function; - - /** - * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. - */ - export function resolve(value: Promise.Thenable): Promise; - export function resolve(value: R): Promise; - - /** - * Create a promise that is rejected with the given `reason`. - */ - export function reject(reason: any): Promise; - - /** - * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). - */ - export function defer(): Promise.Resolver; - - /** - * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. - */ - export function cast(value: Promise.Thenable): Promise; - export function cast(value: R): Promise; - - /** - * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. - */ - export function bind(thisArg: any): Promise; - - /** - * See if `value` is a trusted Promise. - */ - export function is(value: any): boolean; - - /** - * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. - */ - export function longStackTraces(): void; - - /** - * Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise. - */ - // TODO enable more overloads - export function delay(value: Promise.Thenable, ms: number): Promise; - export function delay(value: R, ms: number): Promise; - export function delay(ms: number): Promise; - - /** - * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. - * - * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. - * - * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. - */ - // TODO how to model promisify? - export function promisify(nodeFunction: Function, receiver?: any): Function; - - /** - * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. - * - * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. - */ - // TODO how to model promisifyAll? - export function promisifyAll(target: Object): Object; - - /** - * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. - */ - // TODO fix coroutine GeneratorFunction - export function coroutine(generatorFunction: Function): Function; - - /** - * Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. - */ - // TODO fix spawn GeneratorFunction - export function spawn(generatorFunction: Function): Promise; - - /** - * This is relevant to browser environments with no module loader. - * - * Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. - */ - export function noConflict(): typeof Promise; - - /** - * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. - * - * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. - */ - export function onPossiblyUnhandledRejection(handler: (reason: any) => any): void; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. - */ - // TODO enable more overloads - // promise of array with promises of value - export function all(values: Thenable[]>): Promise; - // promise of array with values - export function all(values: Thenable): Promise; - // array with promises of value - export function all(values: Thenable[]): Promise; - // array with values - export function all(values: R[]): Promise; - - /** - * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. - * - * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. - * - * *The original object is not modified.* - */ - // TODO verify this is correct - // trusted promise for object - export function props(object: Promise): Promise; - // object - export function props(object: Object): Promise; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array. - * - * *original: The array is not modified. The input array sparsity is retained in the resulting array.* - */ - // promise of array with promises of value - export function settle(values: Thenable[]>): Promise[]>; - // promise of array with values - export function settle(values: Thenable): Promise[]>; - // array with promises of value - export function settle(values: Thenable[]): Promise[]>; - // array with values - export function settle(values: R[]): Promise[]>; - - /** - * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. - */ - // promise of array with promises of value - export function any(values: Thenable[]>): Promise; - // promise of array with values - export function any(values: Thenable): Promise; - // array with promises of value - export function any(values: Thenable[]): Promise; - // array with values - export function any(values: R[]): Promise; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. - * - * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. - */ - // promise of array with promises of value - export function race(values: Thenable[]>): Promise; - // promise of array with values - export function race(values: Thenable): Promise; - // array with promises of value - export function race(values: Thenable[]): Promise; - // array with values - export function race(values: R[]): Promise; - - /** - * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. - * - * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. - * - * *The original array is not modified.* - */ - // promise of array with promises of value - export function some(values: Thenable[]>, count: number): Promise; - // promise of array with values - export function some(values: Thenable, count: number): Promise; - // array with promises of value - export function some(values: Thenable[], count: number): Promise; - // array with values - export function some(values: R[], count: number): Promise; - - /** - * Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments. - */ - // variadic array with promises of value - export function join(...values: Thenable[]): Promise; - // variadic array with values - export function join(...values: R[]): Promise; - - /** - * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. - * - * *The original array is not modified.* - */ - // promise of array with promises of value - export function map(values: Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => Thenable): Promise; - export function map(values: Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise; - - // promise of array with values - export function map(values: Thenable, mapper: (item: R, index: number, arrayLength: number) => Thenable): Promise; - export function map(values: Thenable, mapper: (item: R, index: number, arrayLength: number) => U): Promise; - - // array with promises of value - export function map(values: Thenable[], mapper: (item: R, index: number, arrayLength: number) => Thenable): Promise; - export function map(values: Thenable[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; - - // array with values - export function map(values: R[], mapper: (item: R, index: number, arrayLength: number) => Thenable): Promise; - export function map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; - - /** - * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. - * - * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* - */ - // promise of array with promises of value - export function reduce(values: Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable, initialValue?: U): Promise; - export function reduce(values: Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; - - // promise of array with values - export function reduce(values: Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable, initialValue?: U): Promise; - export function reduce(values: Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; - - // array with promises of value - export function reduce(values: Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable, initialValue?: U): Promise; - export function reduce(values: Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; - - // array with values - export function reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable, initialValue?: U): Promise; - export function reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; - - /** - * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. - * - * *The original array is not modified. - */ - // promise of array with promises of value - export function filter(values: Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => Thenable): Promise; - export function filter(values: Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; - - // promise of array with values - export function filter(values: Thenable, filterer: (item: R, index: number, arrayLength: number) => Thenable): Promise; - export function filter(values: Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; - - // array with promises of value - export function filter(values: Thenable[], filterer: (item: R, index: number, arrayLength: number) => Thenable): Promise; - export function filter(values: Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; - - // array with values - export function filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => Thenable): Promise; - export function filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; -} - -declare module 'bluebird' { -export = Promise; -} diff --git a/_infrastructure/tests/typings/lazy.js/lazy.js.d.ts b/_infrastructure/tests/typings/lazy.js/lazy.js.d.ts deleted file mode 100644 index b2909dfceb..0000000000 --- a/_infrastructure/tests/typings/lazy.js/lazy.js.d.ts +++ /dev/null @@ -1,252 +0,0 @@ -// Type definitions for Lazy.js 0.3.2 -// Project: https://github.com/dtao/lazy.js/ -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module LazyJS { - - interface LazyStatic { - - (value: T[]):ArrayLikeSequence; - (value: any[]):ArrayLikeSequence; - (value: Object):ObjectLikeSequence; - (value: Object):ObjectLikeSequence; - (value: string):StringLikeSequence; - - strict():LazyStatic; - - generate(generatorFn: GeneratorCallback, length?: number):GeneratedSequence; - - range(to: number):GeneratedSequence; - range(from: number, to: number, step?: number):GeneratedSequence; - - repeat(value: T, count?: number):GeneratedSequence; - - on(eventType: string):Sequence; - - readFile(path: string):StringLikeSequence; - makeHttpRequest(path: string):StringLikeSequence; - } - - interface ArrayLike { - length:number; - [index:number]:T; - } - - interface Callback { - ():void; - } - - interface ErrorCallback { - (error: any):void; - } - - interface ValueCallback { - (value: T):void; - } - - interface GetKeyCallback { - (value: T):string; - } - - interface TestCallback { - (value: T):boolean; - } - - interface MapCallback { - (value: T):U; - } - - interface MapStringCallback { - (value: string):string; - } - - interface NumberCallback { - (value: T):number; - } - - interface MemoCallback { - (memo: U, value: T):U; - } - - interface GeneratorCallback { - (index: number):T; - } - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - interface Iterator { - new (sequence: Sequence):Iterator; - current():T; - moveNext():boolean; - } - - interface GeneratedSequence extends Sequence { - new(generatorFn: GeneratorCallback, length: number):GeneratedSequence; - length():number; - } - - interface AsyncSequence extends SequenceBase { - each(callback: ValueCallback):AsyncHandle; - } - - interface AsyncHandle { - cancel():void; - onComplete(callback: Callback):void; - onError(callback: ErrorCallback):void; - } - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - module Sequence { - function define(methodName: string[], overrides: Object): Function; - } - - interface Sequence extends SequenceBase { - each(eachFn: ValueCallback):Sequence; - } - - interface SequenceBase extends SequenceBaser { - first():any; - first(count: number):Sequence; - indexOf(value: any, startIndex?: number):Sequence; - - last():any; - last(count: number):Sequence; - lastIndexOf(value: any):Sequence; - - reverse():Sequence; - } - - interface SequenceBaser { - // TODO improve define() (needs ugly overload) - async(interval: number):AsyncSequence; - chunk(size: number):Sequence; - compact():Sequence; - concat(var_args: T[]):Sequence; - consecutive(length: number):Sequence; - contains(value: T):boolean; - countBy(keyFn: GetKeyCallback): ObjectLikeSequence; - countBy(propertyName: string): ObjectLikeSequence; - dropWhile(predicateFn: TestCallback): Sequence; - every(predicateFn: TestCallback): boolean; - filter(predicateFn: TestCallback): Sequence; - find(predicateFn: TestCallback): Sequence; - findWhere(properties: Object): Sequence; - - flatten(): Sequence; - groupBy(keyFn: GetKeyCallback): ObjectLikeSequence; - initial(count?: number): Sequence; - intersection(var_args: T[]): Sequence; - invoke(methodName: string): Sequence; - isEmpty(): boolean; - join(delimiter?: string): string; - map(mapFn: MapCallback): Sequence; - - max(valueFn?: NumberCallback): T; - min(valueFn?: NumberCallback): T; - pluck(propertyName: string): Sequence; - reduce(aggregatorFn: MemoCallback, memo?: U): U; - reduceRight(aggregatorFn: MemoCallback, memo: U): U; - reject(predicateFn: TestCallback): Sequence; - rest(count?: number): Sequence; - shuffle(): Sequence; - some(predicateFn?: TestCallback): boolean; - sortBy(sortFn: NumberCallback): Sequence; - sortedIndex(value: T): Sequence; - sum(valueFn?: NumberCallback): Sequence; - takeWhile(predicateFn: TestCallback): Sequence; - union(var_args: T[]): Sequence; - uniq(): Sequence; - where(properties: Object): Sequence; - without(var_args: T[]): Sequence; - zip(var_args: T[]): Sequence; - - toArray(): T[]; - toObject(): Object; - } - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - module ArrayLikeSequence { - function define(methodName: string[], overrides: Object): Function; - } - - interface ArrayLikeSequence extends Sequence { - // define()X; - concat(): ArrayLikeSequence; - first(count?: number): ArrayLikeSequence; - get(index: number): T; - length(): number; - map(mapFn: MapCallback): ArrayLikeSequence; - pop(): ArrayLikeSequence; - rest(count?: number): ArrayLikeSequence; - reverse(): ArrayLikeSequence; - shift(): ArrayLikeSequence; - slice(begin: number, end?: number): ArrayLikeSequence; - } - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - module ObjectLikeSequence { - function define(methodName: string[], overrides: Object): Function; - } - - interface ObjectLikeSequence extends Sequence { - assign(other: Object): ObjectLikeSequence; - // throws error - //async(): X; - defaults(defaults: Object): ObjectLikeSequence; - functions(): Sequence; - get(property: string): ObjectLikeSequence; - invert(): ObjectLikeSequence; - keys(): Sequence; - omit(properties: string[]): ObjectLikeSequence; - pairs(): Sequence; - pick(properties: string[]): ObjectLikeSequence; - toArray(): T[]; - toObject(): Object; - values(): Sequence; - } - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - module StringLikeSequence { - function define(methodName: string[], overrides: Object): Function; - } - - interface StringLikeSequence extends SequenceBaser { - charAt(index: number): string; - charCodeAt(index: number): number; - contains(value: string): boolean; - endsWith(suffix: string): boolean; - - first(): string; - first(count: number): StringLikeSequence; - - indexOf(substring: string, startIndex?: number): number; - - last(): string; - last(count: number): StringLikeSequence; - - lastIndexOf(substring: string, startIndex?: number): number; - mapString(mapFn: MapStringCallback): StringLikeSequence; - match(pattern: RegExp): StringLikeSequence; - reverse(): StringLikeSequence; - - split(delimiter: string): StringLikeSequence; - split(delimiter: RegExp): StringLikeSequence; - - startsWith(prefix: string): boolean; - substring(start: number, stop?: number): StringLikeSequence; - toLowerCase(): StringLikeSequence; - toUpperCase(): StringLikeSequence; - } -} - -declare var Lazy: LazyJS.LazyStatic; - -declare module 'lazy.js' { -export = Lazy; -} - diff --git a/_infrastructure/tests/typings/node/node.d.ts b/_infrastructure/tests/typings/node/node.d.ts deleted file mode 100644 index dca0164b08..0000000000 --- a/_infrastructure/tests/typings/node/node.d.ts +++ /dev/null @@ -1,1258 +0,0 @@ -// Type definitions for Node.js v0.10.1 -// Project: http://nodejs.org/ -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/************************************************ -* * -* Node.js v0.10.1 API * -* * -************************************************/ - -/************************************************ -* * -* GLOBAL * -* * -************************************************/ -declare var process: NodeProcess; -declare var global: any; - -declare var __filename: string; -declare var __dirname: string; - -declare function setTimeout(callback: (...args: any[]) => void , ms: number , ...args: any[]): NodeTimer; -declare function clearTimeout(timeoutId: NodeTimer): void; -declare function setInterval(callback: (...args: any[]) => void , ms: number , ...args: any[]): NodeTimer; -declare function clearInterval(intervalId: NodeTimer): void; -declare function setImmediate(callback: (...args: any[]) => void , ...args: any[]): any; -declare function clearImmediate(immediateId: any): void; - -declare var require: { - (id: string): any; - resolve(id:string): string; - cache: any; - extensions: any; - main: any; -} - -declare var module: { - exports: any; - require(id: string): any; - id: string; - filename: string; - loaded: boolean; - parent: any; - children: any[]; -} - -// Same as module.exports -declare var exports: any; -declare var SlowBuffer: { - new (str: string, encoding?: string): NodeBuffer; - new (size: number): NodeBuffer; - new (array: any[]): NodeBuffer; - prototype: NodeBuffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: NodeBuffer[], totalLength?: number): NodeBuffer; -}; -declare var Buffer: { - new (str: string, encoding?: string): NodeBuffer; - new (size: number): NodeBuffer; - new (array: any[]): NodeBuffer; - prototype: NodeBuffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: NodeBuffer[], totalLength?: number): NodeBuffer; -} - -/************************************************ -* * -* INTERFACES * -* * -************************************************/ - -interface ErrnoException extends Error { - errno?: any; - code?: string; - path?: string; - syscall?: string; -} - -interface NodeEventEmitter { - addListener(event: string, listener: Function): NodeEventEmitter; - on(event: string, listener: Function): NodeEventEmitter; - once(event: string, listener: Function): NodeEventEmitter; - removeListener(event: string, listener: Function): NodeEventEmitter; - removeAllListeners(event?: string): NodeEventEmitter; - setMaxListeners(n: number): void; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; -} - -interface ReadableStream extends NodeEventEmitter { - readable: boolean; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: NodeBuffer): void; - wrap(oldStream: ReadableStream): ReadableStream; -} - -interface WritableStream extends NodeEventEmitter { - writable: boolean; - write(buffer: NodeBuffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: NodeBuffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; -} - -interface ReadWriteStream extends ReadableStream, WritableStream { } - -interface NodeProcess extends NodeEventEmitter { - stdout: WritableStream; - stderr: WritableStream; - stdin: ReadableStream; - argv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - env: any; - exit(code?: number): void; - getgid(): number; - setgid(id: number): void; - setgid(id: string): void; - getuid(): number; - setuid(id: number): void; - setuid(id: string): void; - version: string; - versions: { http_parser: string; node: string; v8: string; ares: string; uv: string; zlib: string; openssl: string; }; - config: { - target_defaults: { - cflags: any[]; - default_configuration: string; - defines: string[]; - include_dirs: string[]; - libraries: string[]; - }; - variables: { - clang: number; - host_arch: string; - node_install_npm: boolean; - node_install_waf: boolean; - node_prefix: string; - node_shared_openssl: boolean; - node_shared_v8: boolean; - node_shared_zlib: boolean; - node_use_dtrace: boolean; - node_use_etw: boolean; - node_use_openssl: boolean; - target_arch: string; - v8_no_strict_aliasing: number; - v8_use_snapshot: boolean; - visibility: string; - }; - }; - kill(pid: number, signal?: string): void; - pid: number; - title: string; - arch: string; - platform: string; - memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; }; - nextTick(callback: Function): void; - umask(mask?: number): number; - uptime(): number; - hrtime(time?:number[]): number[]; - - // Worker - send?(message: any, sendHandle?: any): void; -} - -// Buffer class -interface NodeBuffer { - [index: number]: number; - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - length: number; - copy(targetBuffer: NodeBuffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): NodeBuffer; - readUInt8(offset: number, noAsset?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - writeUInt8(value: number, offset: number, noAssert?: boolean): void; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): void; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): void; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): void; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): void; - writeInt8(value: number, offset: number, noAssert?: boolean): void; - writeInt16LE(value: number, offset: number, noAssert?: boolean): void; - writeInt16BE(value: number, offset: number, noAssert?: boolean): void; - writeInt32LE(value: number, offset: number, noAssert?: boolean): void; - writeInt32BE(value: number, offset: number, noAssert?: boolean): void; - writeFloatLE(value: number, offset: number, noAssert?: boolean): void; - writeFloatBE(value: number, offset: number, noAssert?: boolean): void; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): void; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): void; - fill(value: any, offset?: number, end?: number): void; -} - -interface NodeTimer { - ref() : void; - unref() : void; -} - -/************************************************ -* * -* MODULES * -* * -************************************************/ -declare module "querystring" { - export function stringify(obj: any, sep?: string, eq?: string): string; - export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; - export function escape(): any; - export function unescape(): any; -} - -declare module "events" { - export class EventEmitter implements NodeEventEmitter { - static listenerCount(emitter: EventEmitter, event: string): number; - - addListener(event: string, listener: Function): EventEmitter; - on(event: string, listener: Function): EventEmitter; - once(event: string, listener: Function): EventEmitter; - removeListener(event: string, listener: Function): EventEmitter; - removeAllListeners(event?: string): EventEmitter; - setMaxListeners(n: number): void; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - } -} - -declare module "http" { - import events = require("events"); - import net = require("net"); - import stream = require("stream"); - - export interface Server extends NodeEventEmitter { - listen(port: number, hostname?: string, backlog?: number, callback?: Function): void; - listen(path: string, callback?: Function): void; - listen(handle: any, listeningListener?: Function): void; - close(cb?: any): void; - maxHeadersCount: number; - } - export interface ServerRequest extends NodeEventEmitter, ReadableStream { - method: string; - url: string; - headers: any; - trailers: string; - httpVersion: string; - setEncoding(encoding?: string): void; - pause(): void; - resume(): void; - connection: net.NodeSocket; - } - export interface ServerResponse extends NodeEventEmitter, WritableStream { - // Extended base methods - write(buffer: NodeBuffer): boolean; - write(buffer: NodeBuffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; - statusCode: number; - setHeader(name: string, value: string): void; - sendDate: boolean; - getHeader(name: string): string; - removeHeader(name: string): void; - write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; - - // Extended base methods - end(): void; - end(buffer: NodeBuffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - export interface ClientRequest extends NodeEventEmitter, WritableStream { - // Extended base methods - write(buffer: NodeBuffer): boolean; - write(buffer: NodeBuffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - write(chunk: any, encoding?: string): void; - abort(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: Function): void; - setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - - // Extended base methods - end(): void; - end(buffer: NodeBuffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - export interface ClientResponse extends NodeEventEmitter, ReadableStream { - statusCode: number; - httpVersion: string; - headers: any; - trailers: any; - setEncoding(encoding?: string): void; - pause(): void; - resume(): void; - } - export interface Agent { maxSockets: number; sockets: any; requests: any; } - - export var STATUS_CODES: any; - export function createServer(requestListener?: (request: ServerRequest, response: ServerResponse) =>void ): Server; - export function createClient(port?: number, host?: string): any; - export function request(options: any, callback?: Function): ClientRequest; - export function get(options: any, callback?: Function): ClientRequest; - export var globalAgent: Agent; -} - -declare module "cluster" { - import child = require("child_process"); - import events = require("events"); - - export interface ClusterSettings { - exec?: string; - args?: string[]; - silent?: boolean; - } - - export class Worker extends events.EventEmitter { - id: string; - process: child.ChildProcess; - suicide: boolean; - send(message: any, sendHandle?: any): void; - kill(signal?: string): void; - destroy(signal?: string): void; - disconnect(): void; - } - - export var settings: ClusterSettings; - export var isMaster: boolean; - export var isWorker: boolean; - export function setupMaster(settings?: ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; - export var worker: Worker; - export var workers: Worker[]; - - // Event emitter - export function addListener(event: string, listener: Function): void; - export function on(event: string, listener: Function): any; - export function once(event: string, listener: Function): void; - export function removeListener(event: string, listener: Function): void; - export function removeAllListeners(event?: string): void; - export function setMaxListeners(n: number): void; - export function listeners(event: string): Function[]; - export function emit(event: string, ...args: any[]): boolean; -} - -declare module "zlib" { - import stream = require("stream"); - export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } - - export interface Gzip extends ReadWriteStream { } - export interface Gunzip extends ReadWriteStream { } - export interface Deflate extends ReadWriteStream { } - export interface Inflate extends ReadWriteStream { } - export interface DeflateRaw extends ReadWriteStream { } - export interface InflateRaw extends ReadWriteStream { } - export interface Unzip extends ReadWriteStream { } - - export function createGzip(options?: ZlibOptions): Gzip; - export function createGunzip(options?: ZlibOptions): Gunzip; - export function createDeflate(options?: ZlibOptions): Deflate; - export function createInflate(options?: ZlibOptions): Inflate; - export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; - export function createInflateRaw(options?: ZlibOptions): InflateRaw; - export function createUnzip(options?: ZlibOptions): Unzip; - - export function deflate(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function deflateRaw(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function gzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function gunzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function inflate(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function inflateRaw(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function unzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - - // Constants - export var Z_NO_FLUSH: number; - export var Z_PARTIAL_FLUSH: number; - export var Z_SYNC_FLUSH: number; - export var Z_FULL_FLUSH: number; - export var Z_FINISH: number; - export var Z_BLOCK: number; - export var Z_TREES: number; - export var Z_OK: number; - export var Z_STREAM_END: number; - export var Z_NEED_DICT: number; - export var Z_ERRNO: number; - export var Z_STREAM_ERROR: number; - export var Z_DATA_ERROR: number; - export var Z_MEM_ERROR: number; - export var Z_BUF_ERROR: number; - export var Z_VERSION_ERROR: number; - export var Z_NO_COMPRESSION: number; - export var Z_BEST_SPEED: number; - export var Z_BEST_COMPRESSION: number; - export var Z_DEFAULT_COMPRESSION: number; - export var Z_FILTERED: number; - export var Z_HUFFMAN_ONLY: number; - export var Z_RLE: number; - export var Z_FIXED: number; - export var Z_DEFAULT_STRATEGY: number; - export var Z_BINARY: number; - export var Z_TEXT: number; - export var Z_ASCII: number; - export var Z_UNKNOWN: number; - export var Z_DEFLATED: number; - export var Z_NULL: number; -} - -declare module "os" { - export function tmpDir(): string; - export function hostname(): string; - export function type(): string; - export function platform(): string; - export function arch(): string; - export function release(): string; - export function uptime(): number; - export function loadavg(): number[]; - export function totalmem(): number; - export function freemem(): number; - export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; - export function networkInterfaces(): any; - export var EOL: string; -} - -declare module "https" { - import tls = require("tls"); - import events = require("events"); - import http = require("http"); - - export interface ServerOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - crl?: any; - ciphers?: string; - honorCipherOrder?: boolean; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; - SNICallback?: (servername: string) => any; - } - - export interface RequestOptions { - host?: string; - hostname?: string; - port?: number; - path?: string; - method?: string; - headers?: any; - auth?: string; - agent?: any; - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; - rejectUnauthorized?: boolean; - } - - export interface NodeAgent { - maxSockets: number; - sockets: any; - requests: any; - } - export var Agent: { - new (options?: RequestOptions): NodeAgent; - }; - export interface Server extends tls.Server { } - export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: NodeEventEmitter) =>void ): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: NodeEventEmitter) =>void ): http.ClientRequest; - export var globalAgent: NodeAgent; -} - -declare module "punycode" { - export function decode(string: string): string; - export function encode(string: string): string; - export function toUnicode(domain: string): string; - export function toASCII(domain: string): string; - export var ucs2: ucs2; - interface ucs2 { - decode(string: string): string; - encode(codePoints: number[]): string; - } - export var version: any; -} - -declare module "repl" { - import stream = require("stream"); - import events = require("events"); - - export interface ReplOptions { - prompt?: string; - input?: ReadableStream; - output?: WritableStream; - terminal?: boolean; - eval?: Function; - useColors?: boolean; - useGlobal?: boolean; - ignoreUndefined?: boolean; - writer?: Function; - } - export function start(options: ReplOptions): NodeEventEmitter; -} - -declare module "readline" { - import events = require("events"); - import stream = require("stream"); - - export interface ReadLine extends NodeEventEmitter { - setPrompt(prompt: string, length: number): void; - prompt(preserveCursor?: boolean): void; - question(query: string, callback: Function): void; - pause(): void; - resume(): void; - close(): void; - write(data: any, key?: any): void; - } - export interface ReadLineOptions { - input: ReadableStream; - output: WritableStream; - completer?: Function; - terminal?: boolean; - } - export function createInterface(options: ReadLineOptions): ReadLine; -} - -declare module "vm" { - export interface Context { } - export interface Script { - runInThisContext(): void; - runInNewContext(sandbox?: Context): void; - } - export function runInThisContext(code: string, filename?: string): void; - export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; - export function runInContext(code: string, context: Context, filename?: string): void; - export function createContext(initSandbox?: Context): Context; - export function createScript(code: string, filename?: string): Script; -} - -declare module "child_process" { - import events = require("events"); - import stream = require("stream"); - - export interface ChildProcess extends NodeEventEmitter { - stdin: WritableStream; - stdout: ReadableStream; - stderr: ReadableStream; - pid: number; - kill(signal?: string): void; - send(message: any, sendHandle: any): void; - disconnect(): void; - } - - export function spawn(command: string, args?: string[], options?: { - cwd?: string; - stdio?: any; - custom?: any; - env?: any; - detached?: boolean; - }): ChildProcess; - export function exec(command: string, options: { - cwd?: string; - stdio?: any; - customFds?: any; - env?: any; - encoding?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - }, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; - export function exec(command: string, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; - export function execFile(file: string, args: string[], options: { - cwd?: string; - stdio?: any; - customFds?: any; - env?: any; - encoding?: string; - timeout?: number; - maxBuffer?: string; - killSignal?: string; - }, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; - export function fork(modulePath: string, args?: string[], options?: { - cwd?: string; - env?: any; - encoding?: string; - }): ChildProcess; -} - -declare module "url" { - export interface Url { - href: string; - protocol: string; - auth: string; - hostname: string; - port: string; - host: string; - pathname: string; - search: string; - query: string; - slashes: boolean; - } - - export interface UrlOptions { - protocol?: string; - auth?: string; - hostname?: string; - port?: string; - host?: string; - pathname?: string; - search?: string; - query?: any; - } - - export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; - export function format(url: UrlOptions): string; - export function resolve(from: string, to: string): string; -} - -declare module "dns" { - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; -} - -declare module "net" { - import stream = require("stream"); - - export interface NodeSocket extends ReadWriteStream { - // Extended base methods - write(buffer: NodeBuffer): boolean; - write(buffer: NodeBuffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - connect(port: number, host?: string, connectionListener?: Function): void; - connect(path: string, connectionListener?: Function): void; - bufferSize: number; - setEncoding(encoding?: string): void; - write(data: any, encoding?: string, callback?: Function): void; - destroy(): void; - pause(): void; - resume(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setKeepAlive(enable?: boolean, initialDelay?: number): void; - address(): { port: number; family: string; address: string; }; - remoteAddress: string; - remotePort: number; - bytesRead: number; - bytesWritten: number; - - // Extended base methods - end(): void; - end(buffer: NodeBuffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - - export var Socket: { - new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): NodeSocket; - }; - - export interface Server extends NodeSocket { - listen(port: number, host?: string, backlog?: number, listeningListener?: Function): void; - listen(path: string, listeningListener?: Function): void; - listen(handle: any, listeningListener?: Function): void; - close(callback?: Function): void; - address(): { port: number; family: string; address: string; }; - maxConnections: number; - connections: number; - } - export function createServer(connectionListener?: (socket: NodeSocket) =>void ): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: NodeSocket) =>void ): Server; - export function connect(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): NodeSocket; - export function connect(port: number, host?: string, connectionListener?: Function): NodeSocket; - export function connect(path: string, connectionListener?: Function): NodeSocket; - export function createConnection(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): NodeSocket; - export function createConnection(port: number, host?: string, connectionListener?: Function): NodeSocket; - export function createConnection(path: string, connectionListener?: Function): NodeSocket; - export function isIP(input: string): number; - export function isIPv4(input: string): boolean; - export function isIPv6(input: string): boolean; -} - -declare module "dgram" { - import events = require("events"); - - export function createSocket(type: string, callback?: Function): Socket; - - interface Socket extends NodeEventEmitter { - send(buf: NodeBuffer, offset: number, length: number, port: number, address: string, callback?: Function): void; - bind(port: number, address?: string): void; - close(): void; - address: { address: string; family: string; port: number; }; - setBroadcast(flag: boolean): void; - setMulticastTTL(ttl: number): void; - setMulticastLoopback(flag: boolean): void; - addMembership(multicastAddress: string, multicastInterface?: string): void; - dropMembership(multicastAddress: string, multicastInterface?: string): void; - } -} - -declare module "fs" { - import stream = require("stream"); - - interface Stats { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: number; - ino: number; - mode: number; - nlink: number; - uid: number; - gid: number; - rdev: number; - size: number; - blksize: number; - blocks: number; - atime: Date; - mtime: Date; - ctime: Date; - } - - interface FSWatcher extends NodeEventEmitter { - close(): void; - } - - export interface ReadStream extends ReadableStream { } - export interface WriteStream extends WritableStream { } - - export function rename(oldPath: string, newPath: string, callback?: (err?: ErrnoException) => void): void; - export function renameSync(oldPath: string, newPath: string): void; - export function truncate(path: string, callback?: (err?: ErrnoException) => void): void; - export function truncate(path: string, len: number, callback?: (err?: ErrnoException) => void): void; - export function truncateSync(path: string, len?: number): void; - export function ftruncate(fd: number, callback?: (err?: ErrnoException) => void): void; - export function ftruncate(fd: number, len: number, callback?: (err?: ErrnoException) => void): void; - export function ftruncateSync(fd: number, len?: number): void; - export function chown(path: string, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; - export function chownSync(path: string, uid: number, gid: number): void; - export function fchown(fd: number, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; - export function fchownSync(fd: number, uid: number, gid: number): void; - export function lchown(path: string, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; - export function lchownSync(path: string, uid: number, gid: number): void; - export function chmod(path: string, mode: number, callback?: (err?: ErrnoException) => void): void; - export function chmod(path: string, mode: string, callback?: (err?: ErrnoException) => void): void; - export function chmodSync(path: string, mode: number): void; - export function chmodSync(path: string, mode: string): void; - export function fchmod(fd: number, mode: number, callback?: (err?: ErrnoException) => void): void; - export function fchmod(fd: number, mode: string, callback?: (err?: ErrnoException) => void): void; - export function fchmodSync(fd: number, mode: number): void; - export function fchmodSync(fd: number, mode: string): void; - export function lchmod(path: string, mode: number, callback?: (err?: ErrnoException) => void): void; - export function lchmod(path: string, mode: string, callback?: (err?: ErrnoException) => void): void; - export function lchmodSync(path: string, mode: number): void; - export function lchmodSync(path: string, mode: string): void; - export function stat(path: string, callback?: (err: ErrnoException, stats: Stats) => any): void; - export function lstat(path: string, callback?: (err: ErrnoException, stats: Stats) => any): void; - export function fstat(fd: number, callback?: (err: ErrnoException, stats: Stats) => any): void; - export function statSync(path: string): Stats; - export function lstatSync(path: string): Stats; - export function fstatSync(fd: number): Stats; - export function link(srcpath: string, dstpath: string, callback?: (err?: ErrnoException) => void): void; - export function linkSync(srcpath: string, dstpath: string): void; - export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: ErrnoException) => void): void; - export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; - export function readlink(path: string, callback?: (err: ErrnoException, linkString: string) => any): void; - export function readlinkSync(path: string): string; - export function realpath(path: string, callback?: (err: ErrnoException, resolvedPath: string) => any): void; - export function realpath(path: string, cache: {[path: string]: string}, callback: (err: ErrnoException, resolvedPath: string) =>any): void; - export function realpathSync(path: string, cache?: {[path: string]: string}): void; - export function unlink(path: string, callback?: (err?: ErrnoException) => void): void; - export function unlinkSync(path: string): void; - export function rmdir(path: string, callback?: (err?: ErrnoException) => void): void; - export function rmdirSync(path: string): void; - export function mkdir(path: string, callback?: (err?: ErrnoException) => void): void; - export function mkdir(path: string, mode: number, callback?: (err?: ErrnoException) => void): void; - export function mkdir(path: string, mode: string, callback?: (err?: ErrnoException) => void): void; - export function mkdirSync(path: string, mode?: number): void; - export function mkdirSync(path: string, mode?: string): void; - export function readdir(path: string, callback?: (err: ErrnoException, files: string[]) => void): void; - export function readdirSync(path: string): string[]; - export function close(fd: number, callback?: (err?: ErrnoException) => void): void; - export function closeSync(fd: number): void; - export function open(path: string, flags: string, callback?: (err: ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: number, callback?: (err: ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: string, callback?: (err: ErrnoException, fd: number) => any): void; - export function openSync(path: string, flags: string, mode?: number): number; - export function openSync(path: string, flags: string, mode?: string): number; - export function utimes(path: string, atime: number, mtime: number, callback?: (err?: ErrnoException) => void): void; - export function utimesSync(path: string, atime: number, mtime: number): void; - export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: ErrnoException) => void): void; - export function futimesSync(fd: number, atime: number, mtime: number): void; - export function fsync(fd: number, callback?: (err?: ErrnoException) => void): void; - export function fsyncSync(fd: number): void; - export function write(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: ErrnoException, written: number, buffer: NodeBuffer) => void): void; - export function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; - export function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: ErrnoException, bytesRead: number, buffer: NodeBuffer) => void): void; - export function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; - export function readFile(filename: string, options: { encoding?: string; flag?: string; }, callback: (err: ErrnoException, data: any) => void): void; - export function readFile(filename: string, callback: (err: ErrnoException, data: NodeBuffer) => void ): void; - export function readFileSync(filename: string, options?: { flag?: string; }): NodeBuffer; - export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; - export function writeFile(filename: string, data: any, callback?: (err: ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: ErrnoException) => void): void; - export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; - export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: ErrnoException) => void): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: ErrnoException) => void): void; - export function appendFile(filename: string, data: any, callback?: (err: ErrnoException) => void): void; - export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; - export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; - export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; - export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; - export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; - export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; - export function exists(path: string, callback?: (exists: boolean) => void): void; - export function existsSync(path: string): boolean; - export function createReadStream(path: string, options?: { - flags?: string; - encoding?: string; - fd?: string; - mode?: number; - bufferSize?: number; - }): ReadStream; - export function createReadStream(path: string, options?: { - flags?: string; - encoding?: string; - fd?: string; - mode?: string; - bufferSize?: number; - }): ReadStream; - export function createWriteStream(path: string, options?: { - flags?: string; - encoding?: string; - string?: string; - }): WriteStream; -} - -declare module "path" { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; -} - -declare module "string_decoder" { - export interface NodeStringDecoder { - write(buffer: NodeBuffer): string; - detectIncompleteChar(buffer: NodeBuffer): number; - } - export var StringDecoder: { - new (encoding: string): NodeStringDecoder; - }; -} - -declare module "tls" { - import crypto = require("crypto"); - import net = require("net"); - import stream = require("stream"); - - var CLIENT_RENEG_LIMIT: number; - var CLIENT_RENEG_WINDOW: number; - - export interface TlsOptions { - pfx?: any; //string or buffer - key?: any; //string or buffer - passphrase?: string; - cert?: any; - ca?: any; //string or buffer - crl?: any; //string or string array - ciphers?: string; - honorCipherOrder?: any; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; //array or Buffer; - SNICallback?: (servername: string) => any; - } - - export interface ConnectionOptions { - host?: string; - port?: number; - socket?: net.NodeSocket; - pfx?: any; //string | Buffer - key?: any; //string | Buffer - passphrase?: string; - cert?: any; //string | Buffer - ca?: any; //Array of string | Buffer - rejectUnauthorized?: boolean; - NPNProtocols?: any; //Array of string | Buffer - servername?: string; - } - - export interface Server extends net.Server { - // Extended base methods - listen(port: number, host?: string, backlog?: number, listeningListener?: Function): void; - listen(path: string, listeningListener?: Function): void; - listen(handle: any, listeningListener?: Function): void; - - listen(port: number, host?: string, callback?: Function): void; - close(): void; - address(): { port: number; family: string; address: string; }; - addContext(hostName: string, credentials: { - key: string; - cert: string; - ca: string; - }): void; - maxConnections: number; - connections: number; - } - - export interface ClearTextStream extends ReadWriteStream { - authorized: boolean; - authorizationError: Error; - getPeerCertificate(): any; - getCipher: { - name: string; - version: string; - }; - address: { - port: number; - family: string; - address: string; - }; - remoteAddress: string; - remotePort: number; - } - - export interface SecurePair { - encrypted: any; - cleartext: any; - } - - export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; - export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; - export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; - export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; - export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; -} - -declare module "crypto" { - export interface CredentialDetails { - pfx: string; - key: string; - passphrase: string; - cert: string; - ca: any; //string | string array - crl: any; //string | string array - ciphers: string; - } - export interface Credentials { context?: any; } - export function createCredentials(details: CredentialDetails): Credentials; - export function createHash(algorithm: string): Hash; - export function createHmac(algorithm: string, key: string): Hmac; - interface Hash { - update(data: any, input_encoding?: string): Hash; - digest(encoding?: string): string; - } - interface Hmac { - update(data: any): void; - digest(encoding?: string): void; - } - export function createCipher(algorithm: string, password: any): Cipher; - export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; - interface Cipher { - update(data: any, input_encoding?: string, output_encoding?: string): string; - final(output_encoding?: string): string; - setAutoPadding(auto_padding: boolean): void; - createDecipher(algorithm: string, password: any): Decipher; - createDecipheriv(algorithm: string, key: any, iv: any): Decipher; - } - interface Decipher { - update(data: any, input_encoding?: string, output_encoding?: string): void; - final(output_encoding?: string): string; - setAutoPadding(auto_padding: boolean): void; - } - export function createSign(algorithm: string): Signer; - interface Signer { - update(data: any): void; - sign(private_key: string, output_format: string): string; - } - export function createVerify(algorith: string): Verify; - interface Verify { - update(data: any): void; - verify(object: string, signature: string, signature_format?: string): boolean; - } - export function createDiffieHellman(prime_length: number): DiffieHellman; - export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; - interface DiffieHellman { - generateKeys(encoding?: string): string; - computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; - getPrime(encoding?: string): string; - getGenerator(encoding: string): string; - getPublicKey(encoding?: string): string; - getPrivateKey(encoding?: string): string; - setPublicKey(public_key: string, encoding?: string): void; - setPrivateKey(public_key: string, encoding?: string): void; - } - export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: string) => any): void; - export function randomBytes(size: number): NodeBuffer; - export function randomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; - export function pseudoRandomBytes(size: number): NodeBuffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; -} - -declare module "stream" { - import events = require("events"); - - export interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - } - - export class Readable extends events.EventEmitter implements ReadableStream { - readable: boolean; - constructor(opts?: ReadableOptions); - _read(size: number): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: NodeBuffer): void; - wrap(oldStream: ReadableStream): ReadableStream; - push(chunk: any, encoding?: string): boolean; - } - - export interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - } - - export class Writable extends events.EventEmitter implements WritableStream { - writable: boolean; - constructor(opts?: WritableOptions); - _write(data: NodeBuffer, encoding: string, callback: Function): void; - _write(data: string, encoding: string, callback: Function): void; - write(buffer: NodeBuffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: NodeBuffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - export interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - } - - // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements ReadWriteStream { - writable: boolean; - constructor(opts?: DuplexOptions); - _write(data: NodeBuffer, encoding: string, callback: Function): void; - _write(data: string, encoding: string, callback: Function): void; - write(buffer: NodeBuffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: NodeBuffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - export interface TransformOptions extends ReadableOptions, WritableOptions {} - - // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends events.EventEmitter implements ReadWriteStream { - readable: boolean; - writable: boolean; - constructor(opts?: TransformOptions); - _transform(chunk: NodeBuffer, encoding: string, callback: Function): void; - _transform(chunk: string, encoding: string, callback: Function): void; - _flush(callback: Function): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: NodeBuffer): void; - wrap(oldStream: ReadableStream): ReadableStream; - push(chunk: any, encoding?: string): boolean; - write(buffer: NodeBuffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: NodeBuffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - export class PassThrough extends Transform {} -} - -declare module "util" { - export interface InspectOptions { - showHidden?: boolean; - depth?: number; - colors?: boolean; - customInspect?: boolean; - } - - export function format(format: any, ...param: any[]): string; - export function debug(string: string): void; - export function error(...param: any[]): void; - export function puts(...param: any[]): void; - export function print(...param: any[]): void; - export function log(string: string): void; - export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; - export function inspect(object: any, options: InspectOptions): string; - export function isArray(object: any): boolean; - export function isRegExp(object: any): boolean; - export function isDate(object: any): boolean; - export function isError(object: any): boolean; - export function inherits(constructor: any, superConstructor: any): void; -} - -declare module "assert" { - function internal (value: any, message?: string): void; - module internal { - export class AssertionError implements Error { - name: string; - message: string; - actual: any; - expected: any; - operator: string; - generatedMessage: boolean; - - constructor(options?: {message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function}); - } - - export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; - export function ok(value: any, message?: string): void; - export function equal(actual: any, expected: any, message?: string): void; - export function notEqual(actual: any, expected: any, message?: string): void; - export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; - export function strictEqual(actual: any, expected: any, message?: string): void; - export function notStrictEqual(actual: any, expected: any, message?: string): void; - export var throws: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - } - - export var doesNotThrow: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - } - - export function ifError(value: any): void; - } - - export = internal; -} - -declare module "tty" { - import net = require("net"); - - export function isatty(fd: number): boolean; - export interface ReadStream extends net.NodeSocket { - isRaw: boolean; - setRawMode(mode: boolean): void; - } - export interface WriteStream extends net.NodeSocket { - columns: number; - rows: number; - } -} - -declare module "domain" { - import events = require("events"); - - export class Domain extends events.EventEmitter { - run(fn: Function): void; - add(emitter: NodeEventEmitter): void; - remove(emitter: NodeEventEmitter): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; - - addListener(event: string, listener: Function): Domain; - on(event: string, listener: Function): Domain; - once(event: string, listener: Function): Domain; - removeListener(event: string, listener: Function): Domain; - removeAllListeners(event?: string): Domain; - } - - export function create(): Domain; -} diff --git a/_infrastructure/tests/typings/optimist/optimist.d.ts b/_infrastructure/tests/typings/optimist/optimist.d.ts deleted file mode 100644 index d79dcfaf0e..0000000000 --- a/_infrastructure/tests/typings/optimist/optimist.d.ts +++ /dev/null @@ -1,48 +0,0 @@ -// https://github.com/substack/node-optimist -// sourced from https://github.com/soywiz/typescript-node-definitions/blob/master/optimist.d.ts -// rehacked by @Bartvds - -declare module Optimist { - export interface Argv { - _: string[]; - } - export interface Optimist { - default(name: string, value: any): Optimist; - default(args: any): Optimist; - - boolean(name: string): Optimist; - boolean(names: string[]): Optimist; - - string(name: string): Optimist; - string(names: string[]): Optimist; - - wrap(columns): Optimist; - - help(): Optimist; - showHelp(fn?: Function): Optimist; - - usage(message: string): Optimist; - - demand(key: string): Optimist; - demand(key: number): Optimist; - demand(key: string[]): Optimist; - - alias(key: string, alias: string): Optimist; - - describe(key: string, desc: string): Optimist; - - options(key: string, opt: any): Optimist; - - check(fn: Function); - - parse(args: string[]): Optimist; - - argv: Argv; - } -} -interface Optimist extends Optimist.Optimist { - (args: string[]): Optimist.Optimist; -} -declare module 'optimist' { - export = Optimist; -} diff --git a/_infrastructure/tests/typings/tsd.d.ts b/_infrastructure/tests/typings/tsd.d.ts deleted file mode 100644 index 371833438e..0000000000 --- a/_infrastructure/tests/typings/tsd.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -/// -/// -/// -/// diff --git a/alertify/alertify-tests.ts b/alertify/alertify-tests.ts new file mode 100644 index 0000000000..9f6c0cd860 --- /dev/null +++ b/alertify/alertify-tests.ts @@ -0,0 +1,32 @@ +/// + +alertify.init(); + +alertify.alert("This is an alert"); +alertify.alert("This is an alert with a callback", () => { + alertify.success("Alert finished"); +}, "myCustomClass"); + + +alertify.confirm("This is a confirm request"); +alertify.confirm("This is a confirm request with a callback", () => { + alertify.success("Confirm finished"); +}, "myCustomClass"); + +var custom = alertify.extend("custom"); + +alertify.log("log message 1"); +alertify.log("log message 2", "success", 3000); + +alertify.prompt("prompt message 1"); +alertify.prompt("prompt message 2", () => { console.log("callback"); }, "ok", "myClass"); + +alertify.set({ delay: 1000 }); +alertify.set({ labels: { ok: "OK", cancel: "Cancel" }}); +alertify.set({ buttonFocus: "ok" }); +alertify.set({ buttonReverse: true }); + +alertify.success("This is a success message"); +alertify.error("This is an error message"); + +alertify.debug(); diff --git a/alertify/alertify.d.ts b/alertify/alertify.d.ts new file mode 100644 index 0000000000..79ff53ec38 --- /dev/null +++ b/alertify/alertify.d.ts @@ -0,0 +1,124 @@ +// Type definitions for alertify 0.3.11 +// Project: http://fabien-d.github.io/alertify.js/ +// Definitions by: John Jeffery +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var alertify: alertify.IAlertifyStatic; + +declare module alertify { + interface IAlertifyStatic { + /** + * Create an alert dialog box + * @param message The message passed from the callee + * @param fn Callback function + * @param cssClass Class(es) to append to dialog box + * @return alertify (ie this) + * @since 0.0.1 + */ + alert(message: string, fn?: Function, cssClass?: string): IAlertifyStatic; + + /** + * Create a confirm dialog box + * @param message The message passed from the callee + * @param fn Callback function + * @param cssClass Class(es) to append to dialog box + * @return alertify (ie this) + * @since 0.0.1 + */ + confirm(message: string, fn?: Function, cssClass?: string): IAlertifyStatic; + + /** + * Extend the log method to create custom methods + * @param type Custom method name + * @return function for logging + * @since 0.0.1 + */ + extend(type: string): (message: string, wait?: number) => IAlertifyStatic; + + /** + * Initialize Alertify and create the 2 main elements. + * Initialization will happen automatically on the first + * use of alert, confirm, prompt or log. + * @since 0.0.1 + */ + init(): void; + + /** + * Show a new log message box + * @param message The message passed from the callee + * @param type Optional type of log message + * @param wait Optional time (in ms) to wait before auto-hiding + * @return alertify (ie this) + * @since 0.0.1 + */ + log(message: string, type?: string, wait?: number): IAlertifyStatic; + + /** + * Create a prompt dialog box + * @param message The message passed from the callee + * @param fn Callback function + * @param placeholder Default value for prompt input + * @param cssClass Class(es) to append to dialog + * @return alertify (ie this) + * @since 0.0.1 + */ + prompt(message: string, fn?: Function, placeholder?: string, cssClass?: string): IAlertifyStatic; + + /** + * Shorthand for log messages + * @param message The message passed from the callee + * @return alertify (ie this) + * @since 0.0.1 + */ + success(message: string): IAlertifyStatic; + + /** + * Shorthand for log messages + * @param message The message passed from the callee + * @return alertify (ie this) + * @since 0.0.1 + */ + error(message: string): IAlertifyStatic; + + /** + * Used to set alertify properties + * @param Properties + * @since 0.2.11 + */ + set(args: IProperties): void; + + /** + * The labels used for dialog buttons + */ + labels: ILabels; + + /** + * Attaches alertify.error to window.onerror method + * @since 0.3.8 + */ + debug(): void; + } + + /** + * Properties for alertify.set function + */ + interface IProperties { + /** Default value for milliseconds display of log messages */ + delay?: number; + + /** Default values for display of labels */ + labels?: ILabels; + + /** Default button for focus */ + buttonFocus?: string; + + /** Should buttons be displayed in reverse order */ + buttonReverse?: boolean; + } + + /** Labels for altertify.set function */ + interface ILabels { + ok?: string; + cancel?: string; + } +} \ No newline at end of file diff --git a/amplifyjs/amplifyjs-tests.ts b/amplifyjs/amplifyjs-tests.ts index c26955348b..a104d4a7cc 100644 --- a/amplifyjs/amplifyjs-tests.ts +++ b/amplifyjs/amplifyjs-tests.ts @@ -176,8 +176,7 @@ amplify.request("twitter-mentions", { user: "amplifyjs" }); //Example: -amplify.request.decoders.appEnvelope = -function (data, status, xhr, success, error) { +var appEnvelopeDecoder: amplifyDecoder = function (data, status, xhr, success, error) { if (data.status === "success") { success(data.data); } else if (data.status === "fail" || data.status === "error") { @@ -187,6 +186,17 @@ function (data, status, xhr, success, error) { } }; +//a new decoder can be added to the amplifyDecoders interface +interface amplifyDecoders { + appEnvelope: amplifyDecoder; +} + +amplify.request.decoders.appEnvelope = appEnvelopeDecoder; + +//but you can also just add it via an index +amplify.request.decoders['appEnvelopeStr'] = appEnvelopeDecoder; + + amplify.request.define("decoderExample", "ajax", { url: "/myAjaxUrl", type: "POST", diff --git a/amplifyjs/amplifyjs.d.ts b/amplifyjs/amplifyjs.d.ts index c8de7260ae..364845f3c4 100644 --- a/amplifyjs/amplifyjs.d.ts +++ b/amplifyjs/amplifyjs.d.ts @@ -3,11 +3,33 @@ // Definitions by: Jonas Eriksson // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + interface amplifyRequestSettings { resourceId: string; data?: any; - success?: Function; - error?: Function; + success?: (...args: any[]) => void; + error?: (...args: any[]) => void; +} + +interface amplifyDecoder { + ( + data?: any, + status?: string, + xhr?: JQueryXHR, + success?: (...args: any[]) => void, + error?: (...args: any[]) => void + ): void +} + +interface amplifyDecoders { + [decoderName: string]: amplifyDecoder; + jsSend: amplifyDecoder; +} + +interface amplifyAjaxSettings extends JQueryAjaxSettings { + cache?: any; + decoder?: any /* string or amplifyDecoder */; } interface amplifyRequest { @@ -39,7 +61,7 @@ interface amplifyRequest { * cache: See the cache section for more details. * decoder: See the decoder section for more details. */ - define(resourceId: string, requestType: string, settings?: any): void; + define(resourceId: string, requestType: string, settings?: amplifyAjaxSettings): void; /*** * Define a custom request. @@ -50,9 +72,9 @@ interface amplifyRequest { * success: Callback to invoke on success. * error: Callback to invoke on error. */ - define(resourceId: string, resource: Function): void; - - decoders: any; + define(resourceId: string, resource: (settings: amplifyRequestSettings) => void): void; + + decoders: amplifyDecoders; cache: any; } diff --git a/angular-agility/angular-agility-tests.ts b/angular-agility/angular-agility-tests.ts new file mode 100644 index 0000000000..1e8eea478b --- /dev/null +++ b/angular-agility/angular-agility-tests.ts @@ -0,0 +1,78 @@ +/// +/// + +var validIconStrategy:aa.IValidIconStrategy = {}; +validIconStrategy.validIcon = ""; +validIconStrategy.invalidIcon = ""; +validIconStrategy.getContainer({}); + +var provider:aa.IFormExtensionsProvider = {}; +provider.defaultLabelStrategy = ""; +provider.defaultFieldGroupStrategy = ""; +provider.defaultValMsgPlacementStrategy = ""; +provider.validIconStrategy = validIconStrategy; +provider.defaultSpinnerClickStrategy = ""; +provider.defaultNotifyTarget = ""; +provider.defaultOnNavigateAwayStrategy = ""; +provider.validationMessages['testName'] = 'testMessages'; +provider.valMsgForTemplate = ""; +provider.confirmResetStrategy = ():boolean=>{ return false; }; +provider.globalSettings['testSetting'] = 'test'; +provider.labelStrategies['testLabelStratgey'] = (element:ng.IAugmentedJQueryStatic, labelText:string, isRequired:boolean):void=>{}; +provider.fieldGroupStrategies['testFieldGroupStratgey'] = (element:ng.IAugmentedJQueryStatic):void=>{}; +provider.valMsgPlacementStrategies['testValMsgPlacementStrategy'] = (formFieldElement:ng.IAugmentedJQueryStatic, formName:string, formFieldName:string):void=>{}; +provider.spinnerClickStrategies['testSpinnerClickStratgey'] = (element:ng.IAugmentedJQueryStatic):void=>{}; +provider.onNavigateAwayStrategies['testOnNavigateAwayStrategy'] = (rootFormScope:ng.IScope, rootForm:ng.IAugmentedJQueryStatic, $injector:ng.auto.IInjectorService)=>{}; + +var defaults:aa.INotifyDefaults = {}; +defaults.success = (message:string, options:any, notifier:any):any=>{}; +defaults.info = (message:string, options:any, notifier:any):any=>{}; +defaults.warning = (message:string, options:any, notifier:any):any=>{}; +defaults.danger = (message:string, options:any, notifier:any):any=>{}; +defaults.error = (message:string, options:any, notifier:any):any=>{}; + +var configWithoutTemplate:aa.INotifyConfig = { + name: "", + options: {}, + namedDefaults: {} +} + +var configWithTemplate:aa.INotifyConfig = { + name: "", + template: "", + templateName: "", + options: {}, + namedDefaults: {} +} + +var notifyOptionsWithoutCssClasses:aa.INotifyOptions = { + messageType: "", + allowHtml: true, + message: "" +} + +var notifyOptionsWithCssClasses:aa.INotifyOptions = { + cssClasses: "", + messageType: "", + allowHtml: true, + message: "" +} + +var notifyConfigProvider:aa.INotifyConfigProvider = {}; +notifyConfigProvider.notifyConfigs = {}; +notifyConfigProvider.defaultTargetContainerName = ""; +notifyConfigProvider.defaultNotifyConfig = ""; +notifyConfigProvider.addOrUpdateNotifyConfig("", configWithTemplate); +notifyConfigProvider.optionsTransformer(notifyOptionsWithCssClasses, {}); + +var fullExternalConfig:aa.IExternalFormValidationConfig = { + validations: "", + ignore: "", + globals: "", + resolve: "", + resolveFn: (modelValue:string):string=>{ return "" } +} + +var minimalExternalConfig:aa.IExternalFormValidationConfig = { + validations: "" +} diff --git a/angular-agility/angular-agility.d.ts b/angular-agility/angular-agility.d.ts new file mode 100644 index 0000000000..872971aedd --- /dev/null +++ b/angular-agility/angular-agility.d.ts @@ -0,0 +1,106 @@ +// Type definitions for AngularAgility +// Project: https://github.com/AngularAgility/AngularAgility +// Definitions by: Roland Zwaga +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module aa { + + export interface ILabelStrategies { + [strategyName: string]: (element:ng.IAugmentedJQueryStatic, labelText:string, isRequired:boolean)=>void; + } + + export interface IFieldGroupStrategies { + [strategyName: string]: (element:ng.IAugmentedJQueryStatic)=>void; + } + + export interface IValMsgPlacementStrategies { + [strategyName: string]: (formFieldElement:ng.IAugmentedJQueryStatic, formName:string, formFieldName:string)=>void; + } + + export interface IValidIconStrategy { + validIcon:string; + invalidIcon:string; + getContainer(element:ng.IAugmentedJQueryStatic):void; + } + + export interface ISpinnerClickStrategies { + [strategyName: string]: (element:ng.IAugmentedJQueryStatic)=>void; + } + + export interface IOnNavigateAwayStrategies { + [strategyName: string]: (rootFormScope:ng.IScope, rootForm:ng.IAugmentedJQueryStatic, $injector:ng.auto.IInjectorService)=>void; + } + + export interface IValidationMessages { + [validationKey: string]: string; + } + + export interface IGlobalSettings { + [settingName: string]: any; + } + + export interface IFormExtensionsProvider extends ng.IServiceProvider { + defaultLabelStrategy:string; + defaultFieldGroupStrategy:string; + defaultValMsgPlacementStrategy:string; + validIconStrategy:IValidIconStrategy; + defaultSpinnerClickStrategy:string; + defaultNotifyTarget:string; + defaultOnNavigateAwayStrategy:string; + validationMessages:IValidationMessages; + valMsgForTemplate:string; + confirmResetStrategy:()=>boolean; + globalSettings:IGlobalSettings; + + labelStrategies:ILabelStrategies; + fieldGroupStrategies:IFieldGroupStrategies; + valMsgPlacementStrategies:IValMsgPlacementStrategies; + spinnerClickStrategies:ISpinnerClickStrategies; + onNavigateAwayStrategies:IOnNavigateAwayStrategies; + } + + export interface INotifyPredicate { + (message:string, options:any, notifier:any):any; + } + + export interface INotifyDefaults { + success: INotifyPredicate; + info: INotifyPredicate; + warning: INotifyPredicate; + danger: INotifyPredicate; + error: INotifyPredicate; + } + + export interface INotifyConfig { + name:string; + template?:string; + templateName?:string; + options:INotifyOptions; + namedDefaults:INotifyDefaults; + } + + export interface INotifyOptions { + cssClasses?:string; + messageType:string; + allowHtml:boolean; + message:string; + } + + export interface INotifyConfigProvider extends ng.IServiceProvider { + notifyConfigs:any; + defaultTargetContainerName:string; + defaultNotifyConfig:string; + addOrUpdateNotifyConfig(name:string, opts:INotifyConfig):void; + optionsTransformer(options:INotifyOptions, $sce:ng.ISCEService):void; + } + + export interface IExternalFormValidationConfig { + validations:any; + ignore?:any; + globals?:any; + resolve?:any; + resolveFn?:(modelValue:string)=>string; + } +} \ No newline at end of file diff --git a/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts b/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts new file mode 100644 index 0000000000..21e9b2ce98 --- /dev/null +++ b/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts @@ -0,0 +1,35 @@ +/// + +var imageList:angular.bootstrap.lightbox.ILightboxImageInfo[] = []; +imageList.push({ + url: 'url1', + width: 100, + height: 100 +}); +imageList.push({ + url: 'url2', + width: 100, + height: 100, + thumbUrl: 'thumbUrl', + caption: 'caption' +}); + +var lightBox:angular.bootstrap.lightbox.ILightbox = {}; +lightBox.openModal(imageList, 0); + +var provider:angular.bootstrap.lightbox.ILightBoxProvider = {}; +provider.templateUrl = 'templateUrl'; +provider.calculateImageDimensionLimits = (dimensions:angular.bootstrap.lightbox.IImageDimensionParameter):angular.bootstrap.lightbox.IImageDimensionLimits=> { + return { + minWidth: 100, + minHeight: 100, + maxWidth: dimensions.windowWidth - 102, + maxHeight: dimensions.windowHeight - 136 + }; +}; +provider.calculateModalDimensions = (dimensions:angular.bootstrap.lightbox.IModalDimensionsParameter):angular.bootstrap.lightbox.IModalDimensions=> { + return { + width: Math.max(500, dimensions.imageDisplayWidth + 42), + height: Math.max(500, dimensions.imageDisplayHeight + 76) + }; + }; \ No newline at end of file diff --git a/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts b/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts new file mode 100644 index 0000000000..299967bdd1 --- /dev/null +++ b/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts @@ -0,0 +1,51 @@ +// Type definitions for angular-bootstrap-lightbox +// Project: https://github.com/compact/angular-bootstrap-lightbox +// Definitions by: Roland Zwaga +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module angular.bootstrap.lightbox { + + export interface ILightboxImageInfo { + url: string; + width: number; + height: number; + thumbUrl?: string; + caption?: string; + } + + export interface IImageDimensionLimits { + minWidth?: number; + minHeight?: number; + maxWidth?: number; + maxHeight?: number; + } + + export interface IImageDimensionParameter { + windowWidth:number; + windowHeight:number; + imageWidth:number; + imageHeight:number; + } + + export interface IModalDimensionsParameter { + windowWidth:number; + windowHeight:number; + imageDisplayWidth:number; + imageDisplayHeight:number; + } + + export interface IModalDimensions { + width:number; + height:number; + } + + export interface ILightbox { + openModal(images:ILightboxImageInfo[], index:number):void; + } + + export interface ILightBoxProvider { + templateUrl:string; + calculateImageDimensionLimits:(dimensions:IImageDimensionParameter)=>IImageDimensionLimits; + calculateModalDimensions:(dimensions:IModalDimensionsParameter)=>IModalDimensions; + } +} \ No newline at end of file diff --git a/angular-hotkeys/angular-hotkeys-tests.ts b/angular-hotkeys/angular-hotkeys-tests.ts new file mode 100644 index 0000000000..a065d4b21d --- /dev/null +++ b/angular-hotkeys/angular-hotkeys-tests.ts @@ -0,0 +1,25 @@ +/// +/// + +var scope: ng.IScope; +var hotkeyProvider: ng.hotkeys.HotkeysProvider; +var hotkeyObj: ng.hotkeys.Hotkey; + +hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} ); +hotkeyProvider.add(hotkeyObj); +hotkeyProvider.bindTo(scope); +hotkeyProvider.del("mod+s"); +hotkeyProvider.get("mod+s"); +hotkeyProvider.toggleCheatSheet(); + +hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description ,hotkeyObj.callback); + +hotkeyProvider.bindTo(scope) + .add(hotkeyObj) + .add(hotkeyObj) + .add({ + combo: 'w', + description: 'blah blah', + callback: function() {} + }); + diff --git a/angular-hotkeys/angular-hotkeys.d.ts b/angular-hotkeys/angular-hotkeys.d.ts new file mode 100644 index 0000000000..f209fbe089 --- /dev/null +++ b/angular-hotkeys/angular-hotkeys.d.ts @@ -0,0 +1,40 @@ +// Type definitions for angular-hotkeys +// Project: https://github.com/chieffancypants/angular-hotkeys +// Definitions by: Jason Zhao +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module ng.hotkeys { + + interface HotkeysProvider { + template: string; + includeCheatSheet: boolean; + cheatSheetHotkey: string; + cheatSheetDescription: string; + + add(combo: string, description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): void; + + add(hotkeyObj: ng.hotkeys.Hotkey): void; + + bindTo(scope : ng.IScope): ng.hotkeys.HotkeysProviderChained; + + del(combo: string): void; + + get(combo: string): ng.hotkeys.Hotkey; + + toggleCheatSheet(): void; + } + + interface HotkeysProviderChained { + add(combo: string, description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): HotkeysProviderChained; + + add(hotkeyObj: ng.hotkeys.Hotkey): HotkeysProviderChained; + } + + interface Hotkey { + combo: string; + description?: string; + callback: (event: Event, hotkey: ng.hotkeys.Hotkey) => void; + } +} diff --git a/angular-protractor/angular-protractor-tests.ts b/angular-protractor/angular-protractor-tests.ts index 2ed627af84..5ca9ecde46 100644 --- a/angular-protractor/angular-protractor-tests.ts +++ b/angular-protractor/angular-protractor-tests.ts @@ -153,21 +153,36 @@ function TestProtractor() { ptor.debugger(); + var webElement: protractor.WebElement = ptor.findElement(by.css('.class')); + var promise: webdriver.promise.Promise; + promise = ptor.findElements(by.css('.class')); + promise = ptor.isElementPresent(by.css('.class')); + promise = ptor.isElementPresent(webElement); + ptor.clearMockModules(); ptor.addMockModule('name', 'script'); ptor.addMockModule('name', function() {}); + ptor.removeMockModule('name'); ptor.waitForAngular(); var elementFinder: protractor.ElementFinder; + var elementArrayFinder: protractor.ElementArrayFinder; elementFinder = ptor.element(by.id('ABC')); elementFinder = ptor.$('.class'); - var elementArrayFinder: protractor.ElementArrayFinder = ptor.$$('.class'); - - var webElement: webdriver.WebElement = ptor.wrapWebElement(new webdriver.WebElement(driver, 'id')); + elementArrayFinder = ptor.$$('.class'); var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl(); + ptor.setLocation('webaddress.com'); + + promise = ptor.get('webaddress.com'); + promise = ptor.get('webdaddress.com', 45); + ptor.refresh(); + ptor.refresh(45); + var navigation: webdriver.WebDriverNavigation = ptor.navigate(); + ptor.pause(); + ptor.pause(8080); } function TestElement() { @@ -180,6 +195,7 @@ function TestElementFinder() { var promise: webdriver.promise.Promise; promise = elementFinder.click(); + promise = elementFinder.allowAnimations('string'); promise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); promise = elementFinder.getTagName(); promise = elementFinder.getCssValue('display'); @@ -195,19 +211,49 @@ function TestElementFinder() { promise = elementFinder.getOuterHtml(); promise = elementFinder.getInnerHtml(); promise = elementFinder.isElementPresent(by.id('id')); - promise = elementFinder.isElementPresent(by.js('function(a, b, c) {}'), 1, 2, 3); - promise = elementFinder.findElements(by.className('class')); - promise = elementFinder.findElements(by.js('function(a, b, c) {}'), 1, 2, 3); + promise = elementFinder.$('.class'); promise = elementFinder.$$('.class'); promise = elementFinder.evaluate('expression'); promise = elementFinder.isPresent(); var webElement: webdriver.WebElement; +} - webElement = elementFinder.$('.class'); - webElement = elementFinder.findElement(by.id('id')); - webElement = elementFinder.findElement(by.js('function(a, b, c) {}'), 1, 2, 3); - webElement = elementFinder.find(); +function TestElementArrayFinder() { + var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.id('id')); + var promise: webdriver.promise.Promise; + var elementFinder: protractor.ElementFinder; + + var driverElementArray: webdriver.WebElement[] = elementArrayFinder.getWebElements(); + elementFinder = elementArrayFinder.get(42); + elementFinder = elementArrayFinder.first(); + elementFinder = elementArrayFinder.last(); + promise = elementArrayFinder.count(); + promise = elementArrayFinder.asElementFinders_(); + elementArrayFinder.each(function(element: protractor.ElementFinder){ + // nothing + }); + elementArrayFinder.map(function(element: protractor.ElementFinder, index: number){ + // nothing + }); + elementArrayFinder.filter(function(element: protractor.ElementFinder, index: number){ + return element.getText().then((text: string) => { + return text === "foo"; + }); + }); + elementArrayFinder.reduce(function(accumulator: string, element: protractor.ElementFinder){ + return element.getText().then((text: string) => { + return accumulator + ',' + text; + }); + }, ''); + elementArrayFinder.reduce(function(accumulator: string, element: protractor.ElementFinder, index: number, array: protractor.ElementFinder[]){ + return element.getText().then((text: string) => { + return accumulator + ',' + text; + }); + }, ''); + elementArrayFinder.then(function(underlyingElementFinders: protractor.ElementFinder[]){ + //nothing + }); } // This function tests the angular specific locator strategies. @@ -216,27 +262,19 @@ function TestLocatorStrategies() { var webElement: webdriver.WebElement; // Protractor Specific Locators + protractor.By.addLocator('customLocator', 'script'); + protractor.By.addLocator('customLocator2', function(){ + // nothing + }); webElement = ptor.findElement(protractor.By.binding('binding')); - webElement = ptor.findElement(protractor.By.select('select')); - webElement = ptor.findElement(protractor.By.selectedOption('selectedOptions')); - webElement = ptor.findElement(protractor.By.input('input')); + webElement = ptor.findElement(protractor.By.exactBinding('exactBinding')); webElement = ptor.findElement(protractor.By.model('model')); - webElement = ptor.findElement(protractor.By.textarea('textarea')); webElement = ptor.findElement(protractor.By.repeater('repeater')); -} - -// This function tests the methods that were added to the base WebElement class -function TestWebElements() { - var ptor: protractor.Protractor = protractor.getInstance(); - - var webElement: protractor.WebElement; - var promise: webdriver.promise.Promise; - - webElement = ptor.findElement(by.id('id')).$('.class'); - promise = ptor.findElement(by.id('id')).$$('.class'); - promise = ptor.findElement(by.id('id')).evaluate('something'); - - webElement = webElement.findElement(by.id('id')).$('.class'); - promise = webElement.findElement(by.id('id')).$$('.class'); - promise = webElement.findElement(by.id('id')).evaluate('something'); + webElement = ptor.findElement(protractor.By.repeater('repeater').column(0)); + webElement = ptor.findElement(protractor.By.repeater('repeater').row(0)); + webElement = ptor.findElement(protractor.By.repeater('repeater').row(0).column(0)); + webElement = ptor.findElement(protractor.By.buttonText('buttonText')); + webElement = ptor.findElement(protractor.By.partialButtonText('partialButtonText')); + webElement = ptor.findElement(protractor.By.cssContainingText('cssSelector', 'search text')); + webElement = ptor.findElement(protractor.By.options('options')); } diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index a78fc42f36..2de49a0a45 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Protractor 0.17.0 +// Type definitions for Angular Protractor 1.0.0-rc4 // Project: https://github.com/angular/protractor // Definitions by: Bill Armstrong // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -25,71 +25,7 @@ declare module protractor { class CommandName extends webdriver.CommandName {} class Key extends webdriver.Key {} class UnhandledAlertError extends webdriver.UnhandledAlertError {} - - class WebElement extends webdriver.WebElement { - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElement - * @return {!protractor.WebElement} - */ - $(selector: string): protractor.WebElement; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElements - * @return {!webdriver.promise.Promise} A promise that will be resolved to an - * array of the located {@link webdriver.WebElement}s. - */ - $$(selector: string): webdriver.promise.Promise; - - /** - * Evalates the input as if it were on the scope of the current element. - * @param {string} expression - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * evaluated expression. The result will be resolved as in - * {@link webdriver.WebDriver.executeScript}. In summary - primitives will - * be resolved as is, functions will be converted to string, and elements - * will be returned as a WebElement. - */ - evaluate(expression: string): webdriver.promise.Promise; - - /** - * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will - * be returned by the driver. Unlike other commands, this error cannot be - * suppressed. In other words, scheduling a command to find an element doubles - * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. - *

- * The search criteria for find an element may either be a - * {@code webdriver.Locator} object, or a simple JSON object whose sole key - * is one of the accepted locator strategies, as defined by - * {@code webdriver.Locator.Strategy}. For example, the following two - * statements are equivalent: - *

-         * var e1 = element.findElement(By.id('foo'));
-         * var e2 = element.findElement({id:'foo'});
-         * 
- *

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locator: any, ...var_args: any[]): protractor.WebElement; - } + class WebElement extends webdriver.WebElement {} module command { class Command extends webdriver.Command {} @@ -273,13 +209,140 @@ declare module protractor { } //endregion - + /** + * Use as: element(locator) + * + * The ElementFinder can be treated as a WebElement for most purposes, in + * particular, you may perform actions (i.e. click, getText) on them as you + * would a WebElement. ElementFinders extend Promise, and once an action + * is performed on an ElementFinder, the latest result from the chain can be + * accessed using then. Unlike a WebElement, an ElementFinder will wait for + * angular to settle before performing finds or actions. + * + * ElementFinder can be used to build a chain of locators that is used to find + * an element. An ElementFinder does not actually attempt to find the element + * until an action is called, which means they can be set up in helper files + * before the page is available. + * + * @param {webdriver.Locator} locator An element locator. + * @return {ElementFinder} + */ interface Element { (locator: webdriver.Locator): ElementFinder; + + /** + * ElementArrayFinder is used for operations on an array of elements (as opposed + * to a single element). + * + * @param {webdriver.Locator} locator An element locator. + * @return {ElementArrayFinder} + */ all(locator: webdriver.Locator): ElementArrayFinder; } interface ElementFinder { + /** + * Use as: element(locator).element(locator) + * Calls to element may be chained to find elements within a parent. + * + * @param {webdriver.Locator} locator The locator that will be used to find descendents. + * + * @return {protractor.ElementFinder} The descendent element found by the locator + */ + element(locator: webdriver.Locator): protractor.ElementFinder; + + /** + * Use as: element(locator).all(locator) + * Calls to element may be chained to find an array of elements within a parent. + * + * @param {webdriver.Locator} locator The locator that will be used to find descendents. + * + * @return {protractor.ElementArrayFinder} The descendent elements found by the locator + */ + all(locator: webdriver.Locator): protractor.ElementArrayFinder; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElement + * @return {!protractor.WebElement} + */ + $(selector: string): protractor.WebElement; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElements + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): webdriver.promise.Promise; + + /** + * Use as: element(locator).isPresent() + * Determine whether the element is present on the page. + * + * @return {protractor.ElementFinder} Which resolves to whether the element is present on the page. + */ + isPresent(): webdriver.promise.Promise; + + /** + * Override for WebElement.prototype.isElementPresent so that protractor waits + * for Angular to settle before making the check. + * + * @see ElementFinder.isPresent + * @return {!webdriver.promise.Promise} which resolves to whether the element is present on the page. + */ + isElementPresent(locator: webdriver.Locator): webdriver.promise.Promise; + + /** + * Return this ElementFinder's locator. + * + * @return {webdriver.Locator} + */ + locator(): webdriver.Locator; + + /** + * Use as: element(locator).getWebElement() + * Returns the WebElement represented by this ElementFinder. + * Throws the WebDriver error if the element doesn't exist. + * If index is null, it makes sure that there is only one underlying WebElement + * described by the chain of locators and issues a warning otherwise. + * If index is not null, it retrieves the WebElement specified by the index.. + * @return {webdriver.WebElement} The WebElement represented by the ElementFinder. + */ + getWebElement(): webdriver.WebElement; + + /** + * Evalates the input as if it were on the scope of the current element. + * @param {string} expression + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * evaluated expression. The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): webdriver.promise.Promise; + + /** + * Determine if animation is allowed on the current element. + * @param {string} value + * + * @return {ElementFinder} which resolves to whether animation is allowed. + */ + allowAnimations(value: string): webdriver.promise.Promise; + + /** + * Access the underlying actionResult of ElementFinder. Implementation allows ElementFinder to be used as a webdriver.promise.Promise. + * @param {function(webdriver.promise.Promise)} fn Function which takes the value of the underlying actionResult. + * + * @return {webdriver.promise.Promise} Promise which contains the results of evaluating fn. + */ + then(fn: IThenFunction): webdriver.promise.Promise; + /** * Schedules a command to click on this element. * @return {!webdriver.promise.Promise} A promise that will be resolved when @@ -460,113 +523,163 @@ declare module protractor { getInnerHtml(): webdriver.promise.Promise; /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. - * - *

Note that JS locator searches cannot be restricted to a subtree of the - * DOM. All such searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether an element could be located on the page. + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol */ - isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Schedules a command to find all of the descendants of this element that match - * the given search criteria. - *

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the elements. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved with an - * array of located {@link webdriver.WebElement}s. - */ - findElements(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElement - * @return {!protractor.WebElement} - */ - $(selector: string): protractor.WebElement; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElements - * @return {!webdriver.promise.Promise} A promise that will be resolved to an - * array of the located {@link webdriver.WebElement}s. - */ - $$(selector: string): webdriver.promise.Promise; - - /** - * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will - * be returned by the driver. Unlike other commands, this error cannot be - * suppressed. In other words, scheduling a command to find an element doubles - * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. - *

- * The search criteria for find an element may either be a - * {@code webdriver.Locator} object, or a simple JSON object whose sole key - * is one of the accepted locator strategies, as defined by - * {@code webdriver.Locator.Strategy}. For example, the following two - * statements are equivalent: - *

-         * var e1 = element.findElement(By.id('foo'));
-         * var e2 = element.findElement({id:'foo'});
-         * 
- *

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locator: any, ...var_args: any[]): protractor.WebElement; - - /** - * Evalates the input as if it were on the scope of the current element. - * @param {string} expression - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * evaluated expression. The result will be resolved as in - * {@link webdriver.WebDriver.executeScript}. In summary - primitives will - * be resolved as is, functions will be converted to string, and elements - * will be returned as a WebElement. - */ - evaluate(expression: string): webdriver.promise.Promise; - - find(): protractor.WebElement; - - isPresent(): webdriver.promise.Promise; + toWireValue(): webdriver.promise.Promise; } - interface ElementArrayFinder{ + interface IThenFunction { + (promiseResult: any): any; + } + + + interface ElementArrayFinder { + /** + * Use as: element.all(locator).getWebElements() + * Returns the array of WebElements represented by this ElementArrayFinder. + * + * @return {Array.} Array of WebElements represented by this ElementArrayFinder + */ + getWebElements(): webdriver.WebElement[]; + + /** + * Use as: element.all(locator).get(index) + * Get an element found by the locator by index. The index starts at 0. This does not actually retrieve the underlying element. + * + * @param {number} index Element index. + * + * @return {protractor.ElementFinder} Finder representing element at the given index + */ + get(index: number): protractor.ElementFinder; + + + /** + * Use as: element.all(locator).first() + * Get the first matching element for the locator. This does not actually retrieve the underlying element. + * + * @return {Protractor.ElementFinder} Finder representing the first matching element + */ + first(): protractor.ElementFinder; + + /** + * Use as: element.all(locator).last() + * Get the last matching element for the locator. This does not actually retrieve the underlying element. + * + * @return {Protractor.ElementFinder} Finder representing the last matching element + */ + last(): protractor.ElementFinder; + + /** + * Use as: element.all(locator).getWebElements() + * Returns the array of WebElements represented by this ElementArrayFinder. + * + * @return {!webdriver.promise.Promise} The array of WebElements represented by this ElementArrayFinder + */ count(): webdriver.promise.Promise; - get(index: number): protractor.WebElement; - first(): protractor.WebElement; - last(): protractor.WebElement; - then(fn: (value: any) => any): webdriver.promise.Promise; + + /** + * Use as: element.all(locator).each(eachFunction) + * Calls the input function on each ElementFinder found by the locator. + * + * @param {function(ElementFinder)} fn Input function. + */ + each(fn: IEachFunction): void; + + /** + * Use as: element.all(locator).map(mapFunction) + * Apply a map function to each element found using the locator. The callback receives the ElementFinder as the first argument and the index as a second arg. + * + * @param {function(ElementFinder, number)} mapFn Map function that will be applied to each element. + * + * @return {!webdriver.promise.Promise} A promise that resolves to an array of values returned by the map function. + */ + map(mapFn: IMapFunction): webdriver.promise.Promise; + + /** + * Use as: element.all(locator).filter(filterFn) + * Apply a filter function to each element found using the locator. Returns promise of a new array with all elements that pass the filter function. The filter function receives the ElementFinder as the first argument and the index as a second arg. + * + * @param {function(ElementFinder, number): webdriver.promise.Promise} filterFn Filter function that will test if an element should be returned. filterFn should return a promise that resolves to a boolean. + * + * @return {!webdriver.promise.Promise} A promise that resolves to an array of ElementFinders that satisfy the filter function. + */ + filter(func: IFilterFunction): webdriver.promise.Promise; + + /** + * Use as: element.all(locator).reduce(reduceFn) + * Apply a reduce function against an accumulator and every element found using the locator (from left-to-right). + * The reduce function has to reduce every element into a single value (the accumulator). + * Returns promise of the accumulator. + * The reduce function receives the accumulator, current ElementFinder, the index, and the entire array of ElementFinders, respectively. + * + * @param {function(number, ElementFinder, number, Array.): webdriver.promise.Promise} reduceFn Reduce function that reduces every element into a single value. + * @param {*} initialValue Initial value of the accumulator. + * + * @return {!webdriver.promise.Promise} A promise that resolves to the final value of the accumulator. + */ + reduce(func: IReductionFunction, initialValue: any): webdriver.promise.Promise; + + /** + * Represents the ElementArrayFinder as an array of ElementFinders. + * + * @return {!webdriver.promise.Promise} Return a promise, which resolves to a list (array) + * of ElementFinders specified by the locator. + */ + asElementFinders_(): webdriver.promise.Promise; + + + /** + * Find the elements specified by the locator. The input function is passed + * to the resulting promise, which resolves to an array of ElementFinders. + * + * Use as: element.all(locator).then(thenFunction) + *

    + *
  • First
  • + *
  • Second
  • + *
  • Third
  • + *
+ * + * element.all(by.css('.items li')).then(function(arr) { + * expect(arr.length).toEqual(3); + * }); + * + * @param {function(Array.)} fn + * + * @type {webdriver.promise.Promise} a promise which will resolve to + * an array of ElementFinders matching the locator. + */ + then(fn: IElementArrayFinderThenFunction): webdriver.promise.Promise; + } + + interface IEachFunction { + (element: protractor.ElementFinder): void; + } + + interface IMapFunction { + (element: ElementFinder, index: number): any; + } + + interface IFilterFunction { + (element: ElementFinder, index: number): webdriver.promise.Promise; + } + + interface IReductionFunction { + (accumulator: any, element: protractor.ElementFinder, index?: number, array?: protractor.ElementFinder[]): webdriver.promise.Promise; + } + + interface IElementArrayFinderThenFunction { + (promiseResult: ElementFinder[]): any; + } + + class LocatorWithColumn extends webdriver.Locator { + column(index: number): webdriver.Locator; + } + + class RepeaterLocator extends LocatorWithColumn { + row(index: number): LocatorWithColumn; } interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy { @@ -587,65 +700,160 @@ declare module protractor { * Usage: * {{status}} * var status = element(by.binding('{{status}}')); + * + * @param {string} bindingDescriptor + * @return {webdriver.Locator} */ binding(bindingDescriptor: string): webdriver.Locator; /** - * Usage: - * - * element(by.select("user")); + * Find an element by exact binding. + * + * {{ person.name }} + * + * {{person_phone|uppercase}} + * + * expect(element(by.exactBinding('person.name')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person-email')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person')).isPresent()).toBe(false); + * expect(element(by.exactBinding('person_phone')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true); + * expect(element(by.exactBinding('phone')).isPresent()).toBe(false); + * + * @param {string} bindingDescriptor + * @return {webdriver.Locator} */ - select(model: string): webdriver.Locator; + exactBinding(bindingDescriptor: string): webdriver.Locator; /** + * + * Find an element by ng-model expression. + * * Usage: - * - * element(by.selectedOption("user")); - */ - selectedOption(model: string): webdriver.Locator; - - /** - * @DEPRECATED - use 'model' instead. - * Usage: - * - * element(by.input('user')); - */ - input(model: string): webdriver.Locator; - - /** - * Usage: - * - * element(by.model('user')); + * + * var input = element(by.model('person.name')); + * input.sendKeys('123'); + * expect(input.getAttribute('value')).toBe('Foo123'); + * + * @param {string} model ng-model expression. + * @return {webdriver.Locator} */ model(model: string): webdriver.Locator; /** + * Find a button by text. + * * Usage: - * - * element(by.textarea("user")); + * + * element(by.buttonText('Save')); + * + * @param {string} searchText + * @return {webdriver.Locator} */ - textarea(model: string): webdriver.Locator; + buttonText(searchText: string): webdriver.Locator; + /** + * Find a button by partial text. + * * Usage: - *
- * {{cat.name}} - * {{cat.age}} - *
+ * + * element(by.partialButtonText('Save')); + * + * @param {string} searchText + * @return {webdriver.Locator} + */ + partialButtonText(searchText: string): webdriver.Locator; + + /** + * Find elements inside an ng-repeat. + * + * Usage: + *
+ * {{cat.name}} + * {{cat.age}} + *
+ * + *
+ * {{$index}} + *
+ *
+ *

{{book.name}}

+ *

{{book.blurb}}

+ *
* * // Returns the DIV for the second cat. - * var secondCat = element(by.repeater("cat in pets").row(2)); + * var secondCat = element(by.repeater('cat in pets').row(1)); + * * // Returns the SPAN for the first cat's name. - * var firstCatName = element( - * by.repeater("cat in pets").row(1).column("{{cat.name}}")); + * var firstCatName = element(by.repeater('cat in pets'). + * row(0).column('{{cat.name}}')); + * * // Returns a promise that resolves to an array of WebElements from a column - * var ages = element( - * by.repeater("cat in pets").column("{{cat.age}}")); + * var ages = element.all( + * by.repeater('cat in pets').column('{{cat.age}}')); + * * // Returns a promise that resolves to an array of WebElements containing - * // all rows of the repeater. - * var rows = element(by.repeater("cat in pets")); + * // all top level elements repeated by the repeater. For 2 pets rows resolves + * // to an array of 2 elements. + * var rows = element.all(by.repeater('cat in pets')); + * + * // Returns a promise that resolves to an array of WebElements containing all + * // the elements with a binding to the book's name. + * var divs = element.all(by.repeater('book in library').column('book.name')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // the DIVs for the second book. + * var bookInfo = element.all(by.repeater('book in library').row(1)); + * + * // Returns the H4 for the first book's name. + * var firstBookName = element(by.repeater('book in library'). + * row(0).column('{{book.name}}')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // all top level elements repeated by the repeater. For 2 books divs + * // resolves to an array of 4 elements. + * var divs = element.all(by.repeater('book in library')); */ - repeater(repeatDescriptor: string): webdriver.Locator; + repeater(repeatDescriptor: string): RepeaterLocator; + + /** + * Find elements by CSS which contain a certain string. + * + * @view + *
    + *
  • Dog
  • + *
  • Cat
  • + *
+ * + * @example + * // Returns the DIV for the dog, but not cat. + * var dog = element(by.cssContainingText('.pet', 'Dog')); + * + * @param cssSelector {string} + * @param searchText {string} + * @return {webdriver.Locator} + */ + cssContainingText(cssSelector: string, searchText: string): webdriver.Locator; + + /** + * Find an element by ng-options expression. + * + * Usage: + * + * + * var allOptions = element.all(by.options('c for c in colors')); + * expect(allOptions.count()).toEqual(2); + * var firstOption = allOptions.first(); + * expect(firstOption.getText()).toEqual('red'); + * + * @param {string} optionsDescriptor ng-options expression. + * @return {webdriver.Locator} + */ + options(optionsDescriptor: string): webdriver.Locator; } var By: IProtractorLocatorStrategy; @@ -714,6 +922,43 @@ declare module protractor { //region Methods + /** + * Instruct webdriver to wait until Angular has finished rendering and has + * no outstanding $http calls before continuing. + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + waitForAngular(): webdriver.promise.Promise; + + /** + * Waits for Angular to finish rendering before searching for elements. + * @see webdriver.WebDriver.findElement + * + * @param {webdriver.Locator} locator The locator used to find the element. + * @return {!webdriver.WebElement} + */ + findElement(locator: webdriver.Locator): protractor.WebElement; + + /** + * Waits for Angular to finish rendering before searching for elements. + * @see webdriver.WebDriver.findElements + * + * @param {webdriver.Locator} locator The locator used to find the elements. + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + findElements(locator: webdriver.Locator): webdriver.promise.Promise; + + /** + * Tests if an element is present on the page. + * @see webdriver.WebDriver.isElementPresent + * @return {!webdriver.promise.Promise} A promise that will resolve to whether + * the element is present on the page. + */ + isElementPresent(locatorOrElement: webdriver.Locator): webdriver.promise.Promise; + isElementPresent(locatorOrElement: any): webdriver.promise.Promise; + /** * Helper function for finding elements. * @@ -735,40 +980,71 @@ declare module protractor { */ $$(cssLocator: string): ElementArrayFinder; - /** - * Instruct webdriver to wait until Angular has finished rendering and has - * no outstanding $http calls before continuing. - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * scripts return value. - */ - waitForAngular(): webdriver.promise.Promise; - - /** - * Wrap a webdriver.WebElement with protractor specific functionality. - * - * @param {webdriver.WebElement} element - * @return {protractor.WebElement} the wrapped web element. - */ - wrapWebElement(element: webdriver.WebElement): protractor.WebElement; - /** * Add a module to load before Angular whenever Protractor.get is called. * Modules will be registered after existing modules already on the page, * so any module registered here will override preexisting modules with the same * name. * - * @param {!string} name The name of the module to load or override. - * @param {!string|Function} script The JavaScript to load the module. + * @param {string} name The name of the module to load or override. + * @param {string|Function} script The JavaScript to load the module. + * @param {...*} varArgs Any additional arguments will be provided to + * the script and may be referenced using the `arguments` object. */ - addMockModule(name: string, script: string): void; - addMockModule(name: string, script: any): void; + addMockModule(name: string, script: string, ...varArgs: any[]): void; + addMockModule(name: string, script: any, ...varArgs: any[]): void; /** * Clear the list of registered mock modules. */ clearMockModules(): void; + /** + * Remove a registered mock module. + * @param {!string} name The name of the module to remove. + */ + removeMockModule(name: string): void; + + /** + * See webdriver.WebDriver.get + * + * Navigate to the given destination and loads mock modules before + * Angular. Assumes that the page being loaded uses Angular. + * If you need to access a page which does not have Angular on load, use + * the wrapped webdriver directly. + * + * @param {string} destination Destination URL. + * @param {number=} opt_timeout Number of seconds to wait for Angular to start. + */ + get(destination: string, opt_timeout?: number): webdriver.promise.Promise; + + /** + * See webdriver.WebDriver.refresh + * + * Makes a full reload of the current page and loads mock modules before + * Angular. Assumes that the page being loaded uses Angular. + * If you need to access a page which does not have Angular on load, use + * the wrapped webdriver directly. + * + * @param {number=} opt_timeout Number of seconds to wait for Angular to start. + */ + refresh(opt_timeout?: number): void; + + /** + * Mixin navigation methods back into the navigation object so that + * they are invoked as before, i.e. driver.navigate().refresh() + */ + navigate(): webdriver.WebDriverNavigation; + + /** + * Browse to another page using in-page navigation. + * + * @param {string} url In page URL using the same syntax as $location.url() + * @returns {!webdriver.promise.Promise} A promise that will resolve once + * page has been changed. + */ + setLocation(url: string): webdriver.promise.Promise; + /** * Returns the current absolute url from AngularJS. */ @@ -795,43 +1071,14 @@ declare module protractor { debugger(): void; /** - * Schedule a command to find an element on the page. If the element cannot be - * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned - * by the driver. Unlike other commands, this error cannot be suppressed. In - * other words, scheduling a command to find an element doubles as an assert - * that the element is present on the page. To test whether an element is - * present on the page, use {@code #isElementPresent} instead. + * Beta (unstable) pause function for debugging webdriver tests. Use + * browser.pause() in your test to enter the protractor debugger from that + * point in the control flow. + * Does not require changes to the command line (no need to add 'debug'). * - *

The search criteria for find an element may either be a - * {@code webdriver.Locator} object, or a simple JSON object whose sole key - * is one of the accepted locator strategies, as defined by - * {@code webdriver.Locator.Strategy}. For example, the following two statements - * are equivalent: - *

-         * var e1 = driver.findElement(By.id('foo'));
-         * var e2 = driver.findElement({id:'foo'});
-         * 
- * - *

When running in the browser, a WebDriver cannot manipulate DOM elements - * directly; it may do so only through a {@link webdriver.WebElement} reference. - * This function may be used to generate a WebElement from a DOM element. A - * reference to the DOM element will be stored in a known location and this - * driver will attempt to retrieve it through {@link #executeScript}. If the - * element cannot be found (eg, it belongs to a different document than the - * one this instance is currently focused on), a - * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. - * - * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The - * locator strategy to use when searching for the element, or the actual - * DOM element to be located by the server. - * @param {...} var_args Arguments to pass to {@code #executeScript} if using a - * JavaScript locator. Otherwise ignored. - * @return {!protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. + * @param {=number} opt_debugPort Optional port to use for the debugging process */ - findElement(locatorOrElement: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locatorOrElement: any, ...var_args: any[]): protractor.WebElement; + pause(opt_debugPort?: number): void; //endregion } @@ -859,9 +1106,19 @@ declare module protractor { } +interface cssSelectorHelper { + (cssLocator: string): protractor.ElementFinder; +} + +interface cssArraySelectorHelper { + (cssLocator: string): protractor.ElementArrayFinder; +} + declare var browser: protractor.Protractor; declare var by: protractor.IProtractorLocatorStrategy; declare var element: protractor.Element; +declare var $: cssSelectorHelper; +declare var $$: cssArraySelectorHelper; declare module 'protractor' { export = protractor; diff --git a/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts b/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts new file mode 100644 index 0000000000..dfd413d0e0 --- /dev/null +++ b/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts @@ -0,0 +1,244 @@ +/// + +function TestWebDriverExports() { + var abstractBuilder: protractor.AbstractBuilder = new protractor.AbstractBuilder(); + var baseAbstractBuilder: webdriver.AbstractBuilder = abstractBuilder; + + var button: protractor.Button = new protractor.Button(); + var baseButton: webdriver.Button = button; + + var key: string = protractor.Key.ADD; + var chord: string = protractor.Key.chord(protractor.Key.NUMPAD0, protractor.Key.NUMPAD1); + + var driver: protractor.WebDriver = new protractor.Builder(). + withCapabilities(protractor.Capabilities.chrome()). + build(); + var baseDriver: webdriver.WebDriver = driver; + + var action: protractor.ActionSequence = new protractor.ActionSequence(driver); + var baseAction: webdriver.ActionSequence = action; + + var alert: protractor.Alert = new protractor.Alert(driver, 'Message'); + var baseAlert: webdriver.Alert = alert; + + var unhandledAlertError: protractor.UnhandledAlertError = new protractor.UnhandledAlertError('Message', alert); + var baseUnhandledAlertError: webdriver.UnhandledAlertError = unhandledAlertError; + + var browser: string = protractor.Browser.ANDROID; + + var builder: protractor.Builder = new protractor.Builder(); + var baseBuilder: webdriver.Builder = builder; + + var capability: string = protractor.Capability.BROWSER_NAME; + + var capabilities: protractor.Capabilities = protractor.Capabilities.chrome(); + var baseCapabilities: webdriver.Capabilities = capabilities; + + var commandName: string = protractor.CommandName.CLICK_ELEMENT; + + var command: protractor.Command = new protractor.Command(protractor.CommandName.CLICK); + var baseCommand: webdriver.Command = command; + + var eventEmitter: protractor.EventEmitter = new protractor.EventEmitter(); + var baseEventEmitter: webdriver.EventEmitter = eventEmitter; + + var firefoxDomExecutor: protractor.FirefoxDomExecutor = new protractor.FirefoxDomExecutor(); + var baseFirefoxDomExecutor: webdriver.FirefoxDomExecutor = firefoxDomExecutor; + + var webElement: protractor.WebElement = new protractor.WebElement(driver, new protractor.promise.Promise()); + var baseWebElement: webdriver.WebElement = webElement; + + var locator: protractor.Locator = new protractor.Locator('id', 'ABC'); + var baseLocator: webdriver.Locator = locator; + + var session: protractor.Session = new protractor.Session('ABC', webdriver.Capabilities.android()); + var baseSession: webdriver.Session = session; + + locator = protractor.By.name('name'); + + // logging module + + var levelName: string = protractor.logging.LevelName.ALL; + var loggingType: string = protractor.logging.Type.CLIENT; + + var level: webdriver.logging.Level = protractor.logging.Level.ALL; + + var entry: protractor.logging.Entry = new protractor.logging.Entry(protractor.logging.Level.ALL, 'Message'); + var baseEntry: webdriver.logging.Entry = entry; + + level = protractor.logging.getLevel('DEBUG'); + + protractor.logging.Preferences = { a: 123 }; + + // promise module + + var promise: protractor.promise.Promise = new protractor.promise.Promise(); + var basePromise: webdriver.promise.Promise = promise; + + var deferred: protractor.promise.Deferred = new protractor.promise.Deferred(); + var baseDeferred: webdriver.promise.Deferred = deferred; + + var flow: protractor.promise.ControlFlow = new protractor.promise.ControlFlow(); + var baseFlow: webdriver.promise.ControlFlow = flow; + + protractor.promise.asap(promise, function(value: any){ return true; }); + protractor.promise.asap(promise, function(value: any){}, function(err: any) { return 'ABC'; }); + + promise = protractor.promise.checkedNodeCall(function(err: any, value: any) { return 123; }); + + flow = protractor.promise.controlFlow(); + + promise = protractor.promise.createFlow(function(newFlow: webdriver.promise.ControlFlow) { }); + + deferred = protractor.promise.defer(function() {}); + deferred = protractor.promise.defer(function(reason?: any) {}); + + promise = protractor.promise.delayed(123); + + promise = protractor.promise.fulfilled(); + promise = protractor.promise.fulfilled({a: 123}); + + promise = protractor.promise.fullyResolved({a: 123}); + + var isPromise: boolean = protractor.promise.isPromise('ABC'); + + promise = protractor.promise.rejected({a: 123}); + + protractor.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); + + promise = protractor.promise.when(promise, function(value: any) { return 123; }, function(err: Error) { return 123; }); + + // error module + + var errorCode: number = protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE; + var error: protractor.error.Error = new protractor.error.Error(protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE); + var baseError: webdriver.error.Error = error; + + // process module + + var isNative: boolean = protractor.process.isNative(); + var value: string; + + value = protractor.process.getEnv('name'); + value = protractor.process.getEnv('name', 'default'); + + protractor.process.setEnv('name', 'value'); + protractor.process.setEnv('name', 123); + +} + +function TestProtractor() { + var ptor: protractor.Protractor; + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + ptor = new protractor.Protractor(driver); + ptor = new protractor.Protractor(driver, 'baseUrl'); + ptor = new protractor.Protractor(driver, 'baseUrl', 'rootElement'); + ptor = protractor.getInstance(); + protractor.setInstance(ptor); + + ptor = protractor.wrapDriver(driver); + ptor = protractor.wrapDriver(driver, 'baseUrl'); + ptor = protractor.wrapDriver(driver, 'baseUrl', 'rootElement'); + + ptor = browser; + + driver = ptor.driver; + var baseUrl: string = ptor.baseUrl; + var rootEl: string = ptor.rootEl; + var ignoreSynchronization: boolean = ptor.ignoreSynchronization; + var params: any = ptor.params; + + ptor.debugger(); + + ptor.clearMockModules(); + ptor.addMockModule('name', 'script'); + ptor.addMockModule('name', function() {}); + ptor.waitForAngular(); + + var elementFinder: protractor.ElementFinder; + + elementFinder = ptor.element(by.id('ABC')); + elementFinder = ptor.$('.class'); + + var elementArrayFinder: protractor.ElementArrayFinder = ptor.$$('.class'); + + var webElement: webdriver.WebElement = ptor.wrapWebElement(new webdriver.WebElement(driver, 'id')); + + var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl(); +} + +function TestElement() { + var elementFinder: protractor.ElementFinder = element(by.id('id')); + var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.className('class')); +} + +function TestElementFinder() { + var elementFinder: protractor.ElementFinder = element(by.id('id')); + var promise: webdriver.promise.Promise; + + promise = elementFinder.click(); + promise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); + promise = elementFinder.getTagName(); + promise = elementFinder.getCssValue('display'); + promise = elementFinder.getAttribute('atribute'); + promise = elementFinder.getText(); + promise = elementFinder.getSize(); + promise = elementFinder.getLocation(); + promise = elementFinder.isEnabled(); + promise = elementFinder.isSelected(); + promise = elementFinder.submit(); + promise = elementFinder.clear(); + promise = elementFinder.isDisplayed(); + promise = elementFinder.getOuterHtml(); + promise = elementFinder.getInnerHtml(); + promise = elementFinder.isElementPresent(by.id('id')); + promise = elementFinder.isElementPresent(by.js('function(a, b, c) {}'), 1, 2, 3); + promise = elementFinder.findElements(by.className('class')); + promise = elementFinder.findElements(by.js('function(a, b, c) {}'), 1, 2, 3); + promise = elementFinder.$$('.class'); + promise = elementFinder.evaluate('expression'); + promise = elementFinder.isPresent(); + + var webElement: webdriver.WebElement; + + webElement = elementFinder.$('.class'); + webElement = elementFinder.findElement(by.id('id')); + webElement = elementFinder.findElement(by.js('function(a, b, c) {}'), 1, 2, 3); + webElement = elementFinder.find(); +} + +// This function tests the angular specific locator strategies. +function TestLocatorStrategies() { + var ptor: protractor.Protractor = protractor.getInstance(); + var webElement: webdriver.WebElement; + + // Protractor Specific Locators + webElement = ptor.findElement(protractor.By.binding('binding')); + webElement = ptor.findElement(protractor.By.select('select')); + webElement = ptor.findElement(protractor.By.selectedOption('selectedOptions')); + webElement = ptor.findElement(protractor.By.input('input')); + webElement = ptor.findElement(protractor.By.model('model')); + webElement = ptor.findElement(protractor.By.textarea('textarea')); + webElement = ptor.findElement(protractor.By.repeater('repeater')); + webElement = ptor.findElement(protractor.By.buttonText('buttonText')); + webElement = ptor.findElement(protractor.By.partialButtonText('partialButtonText')); +} + +// This function tests the methods that were added to the base WebElement class +function TestWebElements() { + var ptor: protractor.Protractor = protractor.getInstance(); + + var webElement: protractor.WebElement; + var promise: webdriver.promise.Promise; + + webElement = ptor.findElement(by.id('id')).$('.class'); + promise = ptor.findElement(by.id('id')).$$('.class'); + promise = ptor.findElement(by.id('id')).evaluate('something'); + + webElement = webElement.findElement(by.id('id')).$('.class'); + promise = webElement.findElement(by.id('id')).$$('.class'); + promise = webElement.findElement(by.id('id')).evaluate('something'); +} diff --git a/angular-protractor/legacy/angular-protractor-0.17.0.d.ts b/angular-protractor/legacy/angular-protractor-0.17.0.d.ts new file mode 100644 index 0000000000..38458b4933 --- /dev/null +++ b/angular-protractor/legacy/angular-protractor-0.17.0.d.ts @@ -0,0 +1,906 @@ +// Type definitions for Angular Protractor 0.17.0 +// Project: https://github.com/angular/protractor +// Definitions by: Bill Armstrong +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module protractor { + //region Wrapped webdriver Items + + class AbstractBuilder extends webdriver.AbstractBuilder {} + class ActionSequence extends webdriver.ActionSequence {} + class Alert extends webdriver.Alert {} + class Builder extends webdriver.Builder {} + class Button extends webdriver.Button {} + class Capabilities extends webdriver.Capabilities {} + class Command extends webdriver.Command {} + class EventEmitter extends webdriver.EventEmitter {} + class FirefoxDomExecutor extends webdriver.FirefoxDomExecutor {} + class Locator extends webdriver.Locator {} + class Session extends webdriver.Session {} + class WebDriver extends webdriver.WebDriver {} + class Browser extends webdriver.Browser {} + class Capability extends webdriver.Capability {} + class CommandName extends webdriver.CommandName {} + class Key extends webdriver.Key {} + class UnhandledAlertError extends webdriver.UnhandledAlertError {} + + class WebElement extends webdriver.WebElement { + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElement + * @return {!protractor.WebElement} + */ + $(selector: string): protractor.WebElement; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElements + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): webdriver.promise.Promise; + + /** + * Evalates the input as if it were on the scope of the current element. + * @param {string} expression + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * evaluated expression. The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): webdriver.promise.Promise; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + *

+ * The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two + * statements are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locator: any, ...var_args: any[]): protractor.WebElement; + } + + module command { + class Command extends webdriver.Command {} + class CommandName extends webdriver.CommandName {} + } + + module error { + class Error extends webdriver.error.Error {} + class ErrorCode extends webdriver.error.ErrorCode {} + } + + module events { + class EventEmitter extends webdriver.EventEmitter {} + } + + module logging { + var Preferences: any; + + class LevelName extends webdriver.logging.LevelName {} + class Type extends webdriver.logging.Type {} + class Level extends webdriver.logging.Level {} + class Entry extends webdriver.logging.Entry {} + + function getLevel(nameOrValue: string): webdriver.logging.Level; + function getLevel(nameOrValue: number): webdriver.logging.Level; + } + + module promise { + class Promise extends webdriver.promise.Promise {} + class Deferred extends webdriver.promise.Deferred {} + class ControlFlow extends webdriver.promise.ControlFlow {} + + /** + * @return {!webdriver.promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): webdriver.promise.ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: webdriver.promise.ControlFlow) => any): webdriver.promise.Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose "then" property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!webdriver.promise.Promise} The promise. + */ + function delayed(ms: number): webdriver.promise.Promise; + + /** + * Creates a new deferred object. + * @param {Function=} opt_canceller Function to call when cancelling the + * computation of this instance's value. + * @return {!webdriver.promise.Deferred} The new deferred object. + */ + function defer(opt_canceller?: any): webdriver.promise.Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. + */ + function fulfilled(opt_value?: any): webdriver.promise.Promise; + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!webdriver.promise.Promise} The rejected promise. + */ + function rejected(opt_reason?: any): webdriver.promise.Promise; + + /** + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. + * @param {!Function} fn The function to wrap. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: (error: any, value: any) => any): webdriver.promise.Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!webdriver.promise.Promise} A new promise. + */ + function when(value: any, opt_callback?: (value: any) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@code webdriver.promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: (value: any) => any, opt_errback?: (error: any) => any): void; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * webdriver.promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): webdriver.promise.Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: webdriver.promise.ControlFlow): void; + + } + + module process { + + /** + * Queries for a named environment variable. + * @param {string} name The name of the environment variable to look up. + * @param {string=} opt_default The default value if the named variable is not + * defined. + * @return {string} The queried environment variable. + */ + function getEnv(name: string, opt_default?: string): string; + + /** + * @return {boolean} Whether the current process is Node's native process + * object. + */ + function isNative(): boolean; + + /** + * Sets an environment value. If the new value is either null or undefined, the + * environment variable will be cleared. + * @param {string} name The value to set. + * @param {*} value The new value; will be coerced to a string. + */ + function setEnv(name: string, value: any): void; + + } + + //endregion + + interface Element { + (locator: webdriver.Locator): ElementFinder; + all(locator: webdriver.Locator): ElementArrayFinder; + } + + interface ElementFinder { + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

+ * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

    + *
  • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
  • + *
  • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
  • + *
  • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
  • + *
+ * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

+ * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

    + *
  • "class" + *
  • "readonly" + *
+ * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + *

Note that JS locator searches cannot be restricted to a subtree of the + * DOM. All such searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether an element could be located on the page. + */ + isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that match + * the given search criteria. + *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the elements. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved with an + * array of located {@link webdriver.WebElement}s. + */ + findElements(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElement + * @return {!protractor.WebElement} + */ + $(selector: string): protractor.WebElement; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElements + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): webdriver.promise.Promise; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + *

+ * The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two + * statements are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locator: any, ...var_args: any[]): protractor.WebElement; + + /** + * Evalates the input as if it were on the scope of the current element. + * @param {string} expression + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * evaluated expression. The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): webdriver.promise.Promise; + + /** + * Use as: element(locator).element(locator) + * Calls to element may be chained to find elements within a parent. + * + * @param {webdriver.Locator} The locator that will be used to find descendents. + * + * @return {protractor.ElementFinder} the descendent element found by the locator + */ + element(locator: webdriver.Locator): protractor.ElementFinder; + + /** + * Use as: element(locator).all(locator) + * Calls to element may be chained to find an array of elements within a parent. + * + * @param {webdriver.Locator} The locator that will be used to find descendents. + * + * @return {protractor.ElementArrayFinder} the descendent elements found by the locator + */ + all(locator: webdriver.Locator): protractor.ElementArrayFinder; + + find(): protractor.WebElement; + + isPresent(): webdriver.promise.Promise; + } + + interface ElementArrayFinder{ + count(): webdriver.promise.Promise; + get(index: number): protractor.WebElement; + first(): protractor.WebElement; + last(): protractor.WebElement; + then(fn: (value: any) => any): webdriver.promise.Promise; + } + + class LocatorWithColumn extends webdriver.Locator { + column(index: number): webdriver.Locator; + } + + class RepeaterLocator extends LocatorWithColumn { + row(index: number): LocatorWithColumn; + } + + interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy { + /** + * Add a locator to this instance of ProtractorBy. This locator can then be + * used with element(by.()). + * + * @param {string} name + * @param {function|string} script A script to be run in the context of + * the browser. This script will be passed an array of arguments + * that begins with the element scoping the search, and then + * contains any args passed into the locator. It should return + * an array of elements. + */ + addLocator(name: string, script: any): void; + + /** + * Usage: + * {{status}} + * var status = element(by.binding('{{status}}')); + */ + binding(bindingDescriptor: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.select("user")); + */ + select(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.selectedOption("user")); + */ + selectedOption(model: string): webdriver.Locator; + + /** + * @DEPRECATED - use 'model' instead. + * Usage: + * + * element(by.input('user')); + */ + input(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.model('user')); + */ + model(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.textarea("user")); + */ + textarea(model: string): webdriver.Locator; + + /** + * Usage: + *

+ * {{cat.name}} + * {{cat.age}} + *
+ * + * // Returns the DIV for the second cat. + * var secondCat = element(by.repeater("cat in pets").row(2)); + * // Returns the SPAN for the first cat's name. + * var firstCatName = element( + * by.repeater("cat in pets").row(1).column("{{cat.name}}")); + * // Returns a promise that resolves to an array of WebElements from a column + * var ages = element( + * by.repeater("cat in pets").column("{{cat.age}}")); + * // Returns a promise that resolves to an array of WebElements containing + * // all rows of the repeater. + * var rows = element(by.repeater("cat in pets")); + */ + repeater(repeatDescriptor: string): RepeaterLocator; + + buttonText(searchText: string): webdriver.Locator; + + partialButtonText(searchText: string): webdriver.Locator; + } + + var By: IProtractorLocatorStrategy; + + class Protractor extends webdriver.WebDriver { + + //region Constructors + + /** + * @param {webdriver.WebDriver} webdriver + * @param {string=} opt_baseUrl A base URL to run get requests against. + * @param {string=body} opt_rootElement Selector element that has an ng-app in + * scope. + * @constructor + */ + constructor(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string); + + //endregion + + //region Properties + + /** + * The wrapped webdriver instance. Use this to interact with pages that do + * not contain Angular (such as a log-in screen). + * + * @type {webdriver.WebDriver} + */ + driver: webdriver.WebDriver; + + /** + * All get methods will be resolved against this base URL. Relative URLs are = + * resolved the way anchor tags resolve. + * + * @type {string} + */ + baseUrl: string; + + /** + * The css selector for an element on which to find Angular. This is usually + * 'body' but if your ng-app is on a subsection of the page it may be + * a subelement. + * + * @type {string} + */ + rootEl: string; + + /** + * If true, Protractor will not attempt to synchronize with the page before + * performing actions. This can be harmful because Protractor will not wait + * until $timeouts and $http calls have been processed, which can cause + * tests to become flaky. This should be used only when necessary, such as + * when a page continuously polls an API using $timeout. + * + * @type {boolean} + */ + ignoreSynchronization: boolean; + + /** + * An object that holds custom test parameters. + * + * @type {Object} + */ + params: any; + + //endregion + + //region Methods + + /** + * Helper function for finding elements. + * + * @type {function(webdriver.Locator): ElementFinder} + */ + element(locator: webdriver.Locator): ElementFinder; + + /** + * Helper function for finding elements by css. + * + * @type {function(string): ElementFinder} + */ + $(cssLocator: string): ElementFinder; + + /** + * Helper function for finding arrays of elements by css. + * + * @type {function(string): ElementArrayFinder} + */ + $$(cssLocator: string): ElementArrayFinder; + + /** + * Instruct webdriver to wait until Angular has finished rendering and has + * no outstanding $http calls before continuing. + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + waitForAngular(): webdriver.promise.Promise; + + /** + * Wrap a webdriver.WebElement with protractor specific functionality. + * + * @param {webdriver.WebElement} element + * @return {protractor.WebElement} the wrapped web element. + */ + wrapWebElement(element: webdriver.WebElement): protractor.WebElement; + + /** + * Add a module to load before Angular whenever Protractor.get is called. + * Modules will be registered after existing modules already on the page, + * so any module registered here will override preexisting modules with the same + * name. + * + * @param {!string} name The name of the module to load or override. + * @param {!string|Function} script The JavaScript to load the module. + */ + addMockModule(name: string, script: string): void; + addMockModule(name: string, script: any): void; + + /** + * Clear the list of registered mock modules. + */ + clearMockModules(): void; + + /** + * Returns the current absolute url from AngularJS. + */ + getLocationAbsUrl(): webdriver.promise.Promise; + + /** + * Pauses the test and injects some helper functions into the browser, so that + * debugging may be done in the browser console. + * + * This should be used under node in debug mode, i.e. with + * protractor debug + * + * While in the debugger, commands can be scheduled through webdriver by + * entering the repl: + * debug> repl + * Press Ctrl + C to leave rdebug repl + * > ptor.findElement(protractor.By.input('user').sendKeys('Laura')); + * > ptor.debugger(); + * debug> c + * + * This will run the sendKeys command as the next task, then re-enter the + * debugger. + */ + debugger(): void; + + /** + * Schedule a command to find an element on the page. If the element cannot be + * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * by the driver. Unlike other commands, this error cannot be suppressed. In + * other words, scheduling a command to find an element doubles as an assert + * that the element is present on the page. To test whether an element is + * present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two statements + * are equivalent: + *

+         * var e1 = driver.findElement(By.id('foo'));
+         * var e2 = driver.findElement({id:'foo'});
+         * 
+ * + *

When running in the browser, a WebDriver cannot manipulate DOM elements + * directly; it may do so only through a {@link webdriver.WebElement} reference. + * This function may be used to generate a WebElement from a DOM element. A + * reference to the DOM element will be stored in a known location and this + * driver will attempt to retrieve it through {@link #executeScript}. If the + * element cannot be found (eg, it belongs to a different document than the + * one this instance is currently focused on), a + * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. + * + * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The + * locator strategy to use when searching for the element, or the actual + * DOM element to be located by the server. + * @param {...} var_args Arguments to pass to {@code #executeScript} if using a + * JavaScript locator. Otherwise ignored. + * @return {!protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locatorOrElement: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locatorOrElement: any, ...var_args: any[]): protractor.WebElement; + + //endregion + } + + /** + * Create a new instance of Protractor by wrapping a webdriver instance. + * + * @param {webdriver.WebDriver} webdriver The configured webdriver instance. + * @param {string=} opt_baseUrl A URL to prepend to relative gets. + * @return {Protractor} + */ + function wrapDriver(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string): Protractor; + + /** + * Set a singleton instance of protractor. + * @param {Protractor} ptor + */ + function setInstance(ptor: Protractor): void; + + /** + * Get the singleton instance. + * @return {Protractor} + */ + function getInstance(): Protractor; + +} + +interface cssSelectorHelper { + (cssLocator: string): protractor.ElementFinder; +} + +declare var browser: protractor.Protractor; +declare var by: protractor.IProtractorLocatorStrategy; +declare var element: protractor.Element; +declare var $: cssSelectorHelper; +declare var $$: cssSelectorHelper; + +declare module 'protractor' { + export = protractor; +} diff --git a/angular-translate/angular-translate-tests.ts b/angular-translate/angular-translate-tests.ts index bea7faa09d..559555418b 100644 --- a/angular-translate/angular-translate-tests.ts +++ b/angular-translate/angular-translate-tests.ts @@ -24,6 +24,6 @@ interface Scope extends ng.IScope { app.controller('Ctrl', ($scope: Scope, $translate: ng.translate.ITranslateService) => { $scope['changeLanguage'] = function (key: any) { - $translate.uses(key); + $translate.use(key); }; }); diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 106d0ae252..313ef86351 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -1,15 +1,26 @@ // Type definitions for Angular Translate (pascalprecht.translate module) // Project: https://github.com/PascalPrecht/angular-translate -// Definitions by: Michel Salib +// Definitions by: Michel Salib // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare module ng.translate { + + interface ITranslatePartialLoaderService { + addPart(name: string): ITranslatePartialLoaderService; + deletePart(name: string, removeData?: boolean): ITranslatePartialLoaderService; + isPartAvailable(name: string): boolean; + } + interface ITranslationTable { [key: string]: string; } + interface ILanguageKeyAlias { + [key: string]: string; + } + interface IStorage { get(name: string): string; set(name: string, value: string): void; @@ -22,22 +33,33 @@ declare module ng.translate { } interface ITranslateService { - (key: string, ...params: string[]): string; - fallbackLanguage(): string; + (key: string, ...params: string[]): ng.IPromise; + cloakClassName(): string; + cloakClassName(name: string): ITranslateProvider; + fallbackLanguage(langKey?: string): string; + fallbackLanguage(langKey?: string[]): string; + instant(translationId: string, interpolateParams?: any, interpolationId?: string): string; + instant(translationId: string[], interpolateParams?: any, interpolationId?: string): string; + isPostCompilingEnabled(): boolean; preferredLanguage(): string; proposedLanguage(): string; - refresh(lankKey: string): ng.IPromise; + refresh(langKey?: string): ng.IPromise; storage(): IStorage; storageKey(): string; - uses(): string; - uses(key: string): ng.IPromise; + use(): string; + use(key: string): ng.IPromise; + useFallbackLanguage(langKey?: string): void; } - interface ITranslateProvider extends ng.IServiceProvider { + interface ITranslateProvider extends ng.IServiceProvider { + translations(): ITranslationTable; translations(key: string, translationTable: ITranslationTable): ITranslateProvider; + cloakClassName(): string; + cloakClassName(name: string): ITranslateProvider; addInterpolation(factory: any): ITranslateProvider; useMessageFormatInterpolation(): ITranslateProvider; useInterpolation(factory: string): ITranslateProvider; + useSanitizeValueStrategy(value: string): ITranslateProvider; preferredLanguage(): string; preferredLanguage(language: string): ITranslateProvider; translationNotFoundIndicator(indicator: string): ITranslateProvider; @@ -48,8 +70,10 @@ declare module ng.translate { fallbackLanguage(): string; fallbackLanguage(language: string): ITranslateProvider; fallbackLanguage(languages: string[]): ITranslateProvider; - uses(): string; - uses(key: string): ITranslateProvider; + use(): string; + use(key: string): ITranslateProvider; + storageKey(): string; + storageKey(key: string): void; // JeroMiya - the library should probably return ITranslateProvider but it doesn't here useUrlLoader(url: string): ITranslateProvider; useStaticFilesLoader(options: ISTaticFilesLoaderOptions): ITranslateProvider; useLoader(loaderFactory: string, options: any): ITranslateProvider; @@ -60,5 +84,9 @@ declare module ng.translate { storagePrefix(prefix: string): ITranslateProvider; useMissingTranslationHandlerLog(): ITranslateProvider; useMissingTranslationHandler(factory: string): ITranslateProvider; + usePostCompiling(value: boolean): ITranslateProvider; + determinePreferredLanguage(fn?: () => void): ITranslateProvider; + registerAvailableLanguageKeys(): string[]; + registerAvailableLanguageKeys(languageKeys: string[], aliases?: ILanguageKeyAlias): ITranslateProvider; } } diff --git a/angular-ui/angular-ui-router-tests.ts b/angular-ui/angular-ui-router-tests.ts index 5a9c4ad6c3..971a47cd2e 100644 --- a/angular-ui/angular-ui-router-tests.ts +++ b/angular-ui/angular-ui-router-tests.ts @@ -13,6 +13,10 @@ myApp.config(( $urlMatcherFactory: ng.ui.IUrlMatcherFactory) => { var matcher: ng.ui.IUrlMatcher = $urlMatcherFactory.compile("/foo/:bar?param1"); + var obj: Object = matcher.exec('/user/bob', { x:'1', q:'hello' }); + var concat: ng.ui.IUrlMatcher = matcher.concat('/test'); + var str: string = matcher.format({ id:'bob', q:'yes' }); + var arr: string[] = matcher.parameters(); $urlRouterProvider .when('/test', '/list') @@ -71,3 +75,74 @@ myApp.config(( } }); }); + +interface IUrlLocatorTestService { + currentUser: any; +} + +// Service for determining who the currently logged on user is. +class UrlLocatorTestService implements IUrlLocatorTestService { + static $inject = ["$http", "$rootScope", "$urlRouter", "$state"]; + + constructor( + private $http: ng.IHttpService, + private $rootScope: ng.IRootScopeService, + private $urlRouter: ng.ui.IUrlRouterService, + private $state: ng.ui.IStateService + ) { + $rootScope.$on("$locationChangeSuccess", (event: ng.IAngularEvent) => this.onLocationChangeSuccess(event)); + } + + public currentUser: any; + + private onLocationChangeSuccess(event: ng.IAngularEvent) { + if (!this.currentUser) { + // If the current user is unknown, halt the state change and request current + // user details from the server + event.preventDefault(); + + // Note that we do not concern ourselves with what to do if this request fails, + // because if it fails, the web page will be redirected away to the login screen. + this.$http({ url: "/api/me", method: "GET" }).success((user: any) => { + this.currentUser = user; + + // sync the ui-state with the location in the browser, which effectively + // restarts the state change that was stopped previously + this.$urlRouter.sync(); + }); + } + } + + private stateServiceTest() { + this.$state.go("myState"); + this.$state.transitionTo("myState"); + if (this.$state.includes("myState") === true) { + // + } + if (this.$state.is("myState") === true) { + // + } + if (this.$state.href("myState") === "/myState") { + // + } + this.$state.get("myState"); + this.$state.get(); + this.$state.reload(); + } +} + +myApp.service("urlLocatorTest", UrlLocatorTestService); + +module UiViewScrollProviderTests { + var app = angular.module("uiViewScrollProviderTests", ["ui.router"]); + + app.config(['$uiViewScrollProvider', function($uiViewScrollProvider: ng.ui.IUiViewScrollProvider) { + // This prevents unwanted scrolling to the active nested state view. + // Use this when you have nested states, but you don't want the browser to scroll down the page + // to the nested state view. + // + // See https://github.com/angular-ui/ui-router/issues/848 + // And https://github.com/angular-ui/ui-router/releases/tag/0.2.8 + $uiViewScrollProvider.useAnchorScroll(); + }]); +} diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index 82bd14f383..081d35723b 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS 1.1.5+ (ui.router module) // Project: https://github.com/angular-ui/ui-router -// Definitions by: Michel Salib +// Definitions by: Michel Salib // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -33,13 +33,13 @@ declare module ng.ui { interface IUrlMatcher { concat(pattern: string): IUrlMatcher; exec(path: string, searchParams: {}): {}; + parameters(): string[]; + format(values: {}): string; } interface IUrlMatcherFactory { compile(pattern: string): IUrlMatcher; isMatcher(o: any): boolean; - parameters(): string[]; - format(values: {}): string; } interface IUrlRouterProvider extends IServiceProvider { @@ -86,9 +86,32 @@ declare module ng.ui { get(): IState[]; current: IState; params: IStateParamsService; + reload(): void; } interface IStateParamsService { [key: string]: any; } + + interface IUrlRouterService { + /* + * Triggers an update; the same update that happens when the address bar + * url changes, aka $locationChangeSuccess. + * + * This method is useful when you need to use preventDefault() on the + * $locationChangeSuccess event, perform some custom logic (route protection, + * auth, config, redirection, etc) and then finally proceed with the transition + * by calling $urlRouter.sync(). + * + */ + sync(): void; + } + + interface IUiViewScrollProvider { + /* + * Reverts back to using the core $anchorScroll service for scrolling + * based on the url anchor. + */ + useAnchorScroll(): void; + } } diff --git a/angularLocalStorage/angularLocalStorage-tests.ts b/angularLocalStorage/angularLocalStorage-tests.ts new file mode 100644 index 0000000000..7ae0d90669 --- /dev/null +++ b/angularLocalStorage/angularLocalStorage-tests.ts @@ -0,0 +1,27 @@ +/// +/// + +interface TestScope extends ng.IScope { + viewType: string; +} + +module ng.LocalStorageTests { + export class TestController { + constructor(private $scope: TestScope, private storage: ng.localStorage.ILocalStorageService) { + storage.bind($scope, 'varName'); + storage.bind($scope,'varName', { defaultValue: 'randomValue123', storeName: 'customStoreKey' }); + $scope.viewType = 'ANYTHING'; + storage.unbind($scope, 'viewType'); + + storage.set('key', 'value'); + storage.get('key'); + storage.remove('key'); + + storage.clearAll(); + } + } +} + +var app = angular.module('angularLocalStorageTests', ['angularLocalStorage']); +app.controller('testCtrl', ['$scope', 'storage', ($scope: TestScope, storage: ng.localStorage.ILocalStorageService) => new ng.LocalStorageTests.TestController($scope, storage)]); + diff --git a/angularLocalStorage/angularLocalStorage.d.ts b/angularLocalStorage/angularLocalStorage.d.ts new file mode 100644 index 0000000000..f83ae33060 --- /dev/null +++ b/angularLocalStorage/angularLocalStorage.d.ts @@ -0,0 +1,22 @@ +// Type definitions for AngularLocalStorage 0.1.7 +// Project: https://github.com/agrublev/angularLocalStorage +// Definitions by: Horiuchi_H +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module ng.localStorage { + interface ILocalStorageService { + set(key: string, value: any): any; + get(key: string): any; + remove(key: string): boolean; + clearAll(): void; + + bind($scope: ng.IScope, key: string, opts?: { + defaultValue?: any; + storeName?: string; + }): any; + unbind($scope: ng.IScope, key: string, storeName?: string): void; + } +} + diff --git a/angularjs/angular-animate.d.ts b/angularjs/angular-animate.d.ts index 696e6f8349..9503e36d75 100644 --- a/angularjs/angular-animate.d.ts +++ b/angularjs/angular-animate.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS 1.2+ (ngAnimate module) // Project: http://angularjs.org -// Definitions by: Michel Salib +// Definitions by: Michel Salib // Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/angularjs/angular-cookies.d.ts b/angularjs/angular-cookies.d.ts index 60eebbacb0..6222216750 100644 --- a/angularjs/angular-cookies.d.ts +++ b/angularjs/angular-cookies.d.ts @@ -1,4 +1,4 @@ -/// Type definitions for Angular JS 1.2 (ngCookies module) +// Type definitions for Angular JS 1.2 (ngCookies module) // Project: http://angularjs.org // Definitions by: Diego Vilar // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/angularjs/angular-mocks-tests.ts b/angularjs/angular-mocks-tests.ts index b43580f36c..e9cd216424 100644 --- a/angularjs/angular-mocks-tests.ts +++ b/angularjs/angular-mocks-tests.ts @@ -21,6 +21,15 @@ mock.inject( function () { return 2; } ); +mock.inject( + ['$rootScope', function ($rootScope: ng.IRootScopeService) { return 1; }]); + +// This overload is not documented on the website, but flows from +// how the injector works. +mock.inject( + ['$rootScope', function ($rootScope: ng.IRootScopeService) { return 1; }], + ['$rootScope', function ($rootScope: ng.IRootScopeService) { return 2; }]); + mock.module('module1', 'module2'); mock.module( function () { return 1; }, @@ -41,7 +50,7 @@ exceptionHandlerProvider.mode('log'); /////////////////////////////////////// -// IExceptionHandlerProvider +// ITimeoutService /////////////////////////////////////// var timeoutService: ng.ITimeoutService; @@ -51,6 +60,14 @@ timeoutService.flushNext(); timeoutService.flushNext(1234); timeoutService.verifyNoPendingTasks(); +//////////////////////////////////////// +// IIntervalService +//////////////////////////////////////// +var intervalService: ng.IIntervalService; +var intervalServiceTimeActuallyAdvanced: number; + +intervalServiceTimeActuallyAdvanced = intervalService.flush(); +intervalServiceTimeActuallyAdvanced = intervalService.flush(1234); /////////////////////////////////////// // ILogService, ILogCall diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index a607422dd4..2591c006e9 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -30,11 +30,10 @@ declare module ng { // see http://docs.angularjs.org/api/angular.mock.inject inject(...fns: Function[]): any; + inject(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works // see http://docs.angularjs.org/api/angular.mock.module - module(...modules: string[]): any; - module(...modules: Function[]): any; - module(modules: Object): any; + module(...modules: any[]): any; // see http://docs.angularjs.org/api/angular.mock.TzDate TzDate(offset: number, timestamp: number): Date; @@ -60,6 +59,15 @@ declare module ng { flushNext(expectedDelay?: number): void; verifyNoPendingTasks(): void; } + + /////////////////////////////////////////////////////////////////////////// + // IntervalService + // see http://docs.angularjs.org/api/ngMock.$interval + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + interface IIntervalService { + flush(millis?: number): number; + } /////////////////////////////////////////////////////////////////////////// // LogService diff --git a/angularjs/angular-resource-tests.ts b/angularjs/angular-resource-tests.ts index 2870b21ad8..c80cc662de 100644 --- a/angularjs/angular-resource-tests.ts +++ b/angularjs/angular-resource-tests.ts @@ -19,7 +19,7 @@ actionDescriptor.params = { key: 'value' }; /////////////////////////////////////// var resourceClass: IMyResourceClass; var resource: IMyResource; -var resourceArray: IMyResource[]; +var resourceArray: ng.resource.IResourceArray; resource = resourceClass.delete(); resource = resourceClass.delete({ key: 'value' }); @@ -29,6 +29,7 @@ resource = resourceClass.delete(function () { }, function () { }); resource = resourceClass.delete({ key: 'value' }, { key: 'value' }); resource = resourceClass.delete({ key: 'value' }, { key: 'value' }, function () { }); resource = resourceClass.delete({ key: 'value' }, { key: 'value' }, function () { }, function () { }); +resource.$promise.then(function(data: IMyResource) {}); resource = resourceClass.get(); resource = resourceClass.get({ key: 'value' }); @@ -47,6 +48,8 @@ resourceArray = resourceClass.query(function () { }, function () { }); resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }); resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }, function () { }); resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }, function () { }, function () { }); +resourceArray.push(resource); +resourceArray.$promise.then(function(data: ng.resource.IResourceArray) {}); resource = resourceClass.remove(); resource = resourceClass.remove({ key: 'value' }); @@ -66,6 +69,50 @@ resource = resourceClass.save({ key: 'value' }, { key: 'value' }); resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () { }); resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () { }, function () { }); +/////////////////////////////////////// +// IResource +/////////////////////////////////////// + +var promise : ng.IPromise; +var arrayPromise : ng.IPromise; + +promise = resource.$delete(); +promise = resource.$delete({ key: 'value' }); +promise = resource.$delete({ key: 'value' }, function () { }); +promise = resource.$delete(function () { }); +promise = resource.$delete(function () { }, function () { }); +promise = resource.$delete({ key: 'value' }, function () { }, function () { }); +promise.then(function(data: IMyResource) {}); + +promise = resource.$get(); +promise = resource.$get({ key: 'value' }); +promise = resource.$get({ key: 'value' }, function () { }); +promise = resource.$get(function () { }); +promise = resource.$get(function () { }, function () { }); +promise = resource.$get({ key: 'value' }, function () { }, function () { }); + +arrayPromise = resourceArray[0].$query(); +arrayPromise = resourceArray[0].$query({ key: 'value' }); +arrayPromise = resourceArray[0].$query({ key: 'value' }, function () { }); +arrayPromise = resourceArray[0].$query(function () { }); +arrayPromise = resourceArray[0].$query(function () { }, function () { }); +arrayPromise = resourceArray[0].$query({ key: 'value' }, function () { }, function () { }); +arrayPromise.then(function(data: ng.resource.IResourceArray) {}); + +promise = resource.$remove(); +promise = resource.$remove({ key: 'value' }); +promise = resource.$remove({ key: 'value' }, function () { }); +promise = resource.$remove(function () { }); +promise = resource.$remove(function () { }, function () { }); +promise = resource.$remove({ key: 'value' }, function () { }, function () { }); + +promise = resource.$save(); +promise = resource.$save({ key: 'value' }); +promise = resource.$save({ key: 'value' }, function () { }); +promise = resource.$save(function () { }); +promise = resource.$save(function () { }, function () { }); +promise = resource.$save({ key: 'value' }, function () { }, function () { }); + /////////////////////////////////////// // IResourceService /////////////////////////////////////// @@ -85,3 +132,7 @@ resourceClass = resourceServiceFactoryFunction(resourceService resourceServiceFactoryFunction = function (resourceService: ng.resource.IResourceService) { return resourceClass; }; mod = mod.factory('factory name', resourceServiceFactoryFunction); + +/////////////////////////////////////// +// IResource +/////////////////////////////////////// \ No newline at end of file diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index a0cd4ab85a..597a58e401 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS 1.2 (ngResource module) // Project: http://angularjs.org -// Definitions by: Diego Vilar +// Definitions by: Diego Vilar , Michael Jess // Definitions: https://github.com/daptiv/DefinitelyTyped /// @@ -50,67 +50,84 @@ declare module ng.resource { // PATCH (in other words, methods with body). Otherwise, it's going // to be considered as parameters to the request. // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L461-L465 + // + // Only those methods with an HTTP body do have 'data' as first parameter: + // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L463 + // More specifically, those methods are POST, PUT and PATCH: + // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L432 + // + // Also, static calls always return the IResource (or IResourceArray) retrieved + // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L549 interface IResourceClass { new(dataOrParams? : any) : T; get(): T; - get(dataOrParams: any): T; - get(dataOrParams: any, success: Function): T; + get(params: Object): T; get(success: Function, error?: Function): T; - get(params: any, data: any, success?: Function, error?: Function): T; + get(params: Object, success: Function, error?: Function): T; + get(params: Object, data: Object, success?: Function, error?: Function): T; + + query(): IResourceArray; + query(params: Object): IResourceArray; + query(success: Function, error?: Function): IResourceArray; + query(params: Object, success: Function, error?: Function): IResourceArray; + query(params: Object, data: Object, success?: Function, error?: Function): IResourceArray; + save(): T; - save(dataOrParams: any): T; - save(dataOrParams: any, success: Function): T; + save(data: Object): T; save(success: Function, error?: Function): T; - save(params: any, data: any, success?: Function, error?: Function): T; - query(): T[]; - query(dataOrParams: any): T[]; - query(dataOrParams: any, success: Function): T[]; - query(success: Function, error?: Function): T[]; - query(params: any, data: any, success?: Function, error?: Function): T[]; + save(data: Object, success: Function, error?: Function): T; + save(params: Object, data: Object, success?: Function, error?: Function): T; + remove(): T; - remove(dataOrParams: any): T; - remove(dataOrParams: any, success: Function): T; + remove(params: Object): T; remove(success: Function, error?: Function): T; - remove(params: any, data: any, success?: Function, error?: Function): T; + remove(params: Object, success: Function, error?: Function): T; + remove(params: Object, data: Object, success?: Function, error?: Function): T; + delete(): T; - delete(dataOrParams: any): T; - delete(dataOrParams: any, success: Function): T; + delete(params: Object): T; delete(success: Function, error?: Function): T; - delete(params: any, data: any, success?: Function, error?: Function): T; + delete(params: Object, success: Function, error?: Function): T; + delete(params: Object, data: Object, success?: Function, error?: Function): T; } + // Instance calls always return the the promise of the request which retrieved the object + // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L546 interface IResource { - $get(): T; - $get(dataOrParams: any): T; - $get(dataOrParams: any, success: Function): T; - $get(success: Function, error?: Function): T; - $get(params: any, data: any, success?: Function, error?: Function): T; - $save(): T; - $save(dataOrParams: any): T; - $save(dataOrParams: any, success: Function): T; - $save(success: Function, error?: Function): T; - $save(params: any, data: any, success?: Function, error?: Function): T; - $query(): T[]; - $query(dataOrParams: any): T[]; - $query(dataOrParams: any, success: Function): T[]; - $query(success: Function, error?: Function): T[]; - $query(params: any, data: any, success?: Function, error?: Function): T[]; - $remove(): T; - $remove(dataOrParams: any): T; - $remove(dataOrParams: any, success: Function): T; - $remove(success: Function, error?: Function): T; - $remove(params: any, data: any, success?: Function, error?: Function): T; - $delete(): T; - $delete(dataOrParams: any): T; - $delete(dataOrParams: any, success: Function): T; - $delete(success: Function, error?: Function): T; - $delete(params: any, data: any, success?: Function, error?: Function): T; - + $get(): ng.IPromise; + $get(params?: Object, success?: Function, error?: Function): ng.IPromise; + $get(success: Function, error?: Function): ng.IPromise; + + $query(): ng.IPromise>; + $query(params?: Object, success?: Function, error?: Function): ng.IPromise>; + $query(success: Function, error?: Function): ng.IPromise>; + + $save(): ng.IPromise; + $save(params?: Object, success?: Function, error?: Function): ng.IPromise; + $save(success: Function, error?: Function): ng.IPromise; + + $remove(): ng.IPromise; + $remove(params?: Object, success?: Function, error?: Function): ng.IPromise; + $remove(success: Function, error?: Function): ng.IPromise; + + $delete(): ng.IPromise; + $delete(params?: Object, success?: Function, error?: Function): ng.IPromise; + $delete(success: Function, error?: Function): ng.IPromise; + /** the promise of the original server interaction that created this instance. **/ $promise : ng.IPromise; $resolved : boolean; } + /** + * Really just a regular Array object with $promise and $resolve attached to it + */ + interface IResourceArray extends Array { + /** the promise of the original server interaction that created this collection. **/ + $promise : ng.IPromise>; + $resolved : boolean; + } + /** when creating a resource factory via IModule.factory */ interface IResourceServiceFactoryFunction { ($resource: ng.resource.IResourceService): IResourceClass; diff --git a/angularjs/angular-route-tests.ts b/angularjs/angular-route-tests.ts index 2ebe16a21e..3b35a97bbc 100644 --- a/angularjs/angular-route-tests.ts +++ b/angularjs/angular-route-tests.ts @@ -9,6 +9,9 @@ declare var $routeProvider: ng.route.IRouteProvider; $routeProvider .when('/projects/:projectId/dashboard',{ - controller: '' + controller: '', + templateUrl: '', + caseInsensitiveMatch: true, + reloadOnSearch: false }) .otherwise({redirectTo: '/'}); diff --git a/angularjs/angular-route.d.ts b/angularjs/angular-route.d.ts index 628d746df7..ba6d0aac98 100644 --- a/angularjs/angular-route.d.ts +++ b/angularjs/angular-route.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS 1.2 (ngRoute module) // Project: http://angularjs.org -// Definitions by: Jonathan Park +// Definitions by: Jonathan Park // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -15,7 +15,9 @@ declare module ng.route { // RouteParamsService // see http://docs.angularjs.org/api/ngRoute.$routeParams /////////////////////////////////////////////////////////////////////////// - interface IRouteParamsService {} + interface IRouteParamsService { + [key: string]: any; + } /////////////////////////////////////////////////////////////////////////// // RouteService @@ -30,17 +32,73 @@ declare module ng.route { // to a controller that was not initialized as a result of a route maching. current?: ICurrentRoute; } - - // see http://docs.angularjs.org/api/ngRoute.$routeProvider#when for options explanations + + + /** + * see http://docs.angularjs.org/api/ngRoute/provider/$routeProvider#when for API documentation + */ interface IRoute { + /** + * {(string|function()=} + * Controller fn that should be associated with newly created scope or the name of a registered controller if passed as a string. + */ controller?: any; - controllerAs?: any; + /** + * A controller alias name. If present the controller will be published to scope under the controllerAs name. + */ + controllerAs?: string; + /** + * Undocumented? + */ name?: string; + /** + * {string=|function()=} + * Html template as a string or a function that returns an html template as a string which should be used by ngView or ngInclude directives. This property takes precedence over templateUrl. + * + * If template is a function, it will be called with the following parameters: + * + * {Array.} - route parameters extracted from the current $location.path() by applying the current route + */ template?: string; + /** + * {string=|function()=} + * Path or function that returns a path to an html template that should be used by ngView. + * + * If templateUrl is a function, it will be called with the following parameters: + * + * {Array.} - route parameters extracted from the current $location.path() by applying the current route + */ templateUrl?: any; + /** + * {Object.=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. The map object is: + * + * - key - {string}: a name of a dependency to be injected into the controller. + * - factory - {string|function}: If string then it is an alias for a service. Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before its value is injected into the controller. Be aware that ngRoute.$routeParams will still refer to the previous route within these resolve functions. Use $route.current.params to access the new route parameters, instead. + */ resolve?: any; + /** + * {(string|function())=} + * Value to update $location path with and trigger route redirection. + * + * If redirectTo is a function, it will be called with the following parameters: + * + * - {Object.} - route parameters extracted from the current $location.path() by applying the current route templateUrl. + * - {string} - current $location.path() + * - {Object} - current $location.search() + * - The custom redirectTo function is expected to return a string which will be used to update $location.path() and $location.search(). + */ redirectTo?: any; + /** + * Reload route when only $location.search() or $location.hash() changes. + * + * This option defaults to true. If the option is set to false and url in the browser changes, then $routeUpdate event is broadcasted on the root scope. + */ reloadOnSearch?: boolean; + /** + * Match routes without being case sensitive + * + * This option defaults to false. If the option is set to true, then the particular route can be matched without being case sensitive + */ caseInsensitiveMatch?: boolean; } @@ -55,10 +113,24 @@ declare module ng.route { } interface IRouteProvider extends IServiceProvider { - otherwise(params: any): IRouteProvider; /** - * This is a description + * Sets route definition that will be used on route change when no other route definition is matched. + * + * @params Mapping information to be assigned to $route.current. + */ + otherwise(params: IRoute): IRouteProvider; + /** + * Adds a new route definition to the $route service. + * + * @param path Route path (matched against $location.path). If $location.path contains redundant trailing slash or is missing one, the route will still match and the $location.path will be updated to add or drop the trailing slash to exactly match the route definition. + * + * - path can contain named groups starting with a colon: e.g. :name. All characters up to the next slash are matched and stored in $routeParams under the given name when the route matches. + * - path can contain named groups starting with a colon and ending with a star: e.g.:name*. All characters are eagerly stored in $routeParams under the given name when the route matches. + * - path can contain optional named groups with a question mark: e.g.:name?. * + * For example, routes like /color/:color/largecode/:largecode*\/edit will match /color/brown/largecode/code/with/slashes/edit and extract: color: brown and largecode: code/with/slashes. + * + * @param route Mapping information to be assigned to $route.current on route match. */ when(path: string, route: IRoute): IRouteProvider; } diff --git a/angularjs/angular-scenario.d.ts b/angularjs/angular-scenario.d.ts index ec3efd9f93..ee71ffbea0 100644 --- a/angularjs/angular-scenario.d.ts +++ b/angularjs/angular-scenario.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular Scenario Testing // Project: http://angularjs.org -// Definitions by: RomanoLindano +// Definitions by: RomanoLindano // Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 8ab1efc72e..a1577856e4 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -7,27 +7,27 @@ * (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: { config: ng.IRequestConfig; deferred: ng.IDeferred; }[] = []; +class AuthService { + /** + * Holds all the requests which failed due to 401 response, + * so they can be re-requested in future, once login is completed. + */ + buffer: { config: ng.IRequestConfig; deferred: ng.IDeferred; }[] = []; - /** - * 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 - }); - } + /** + * Required by HTTP interceptor. + * Function is attached to provider to be invisible for regular users of this service. + */ + pushToBuffer = function(config: ng.IRequestConfig, deferred: ng.IDeferred) { + this.buffer.push({ + config: config, + deferred: deferred + }); + } - this.$get = ['$rootScope', '$injector', function ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { + $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'); @@ -36,20 +36,25 @@ angular.module('http-auth-interceptor', []) }); } function retryAll() { - for (var i = 0; i < buffer.length; ++i) { - retry(buffer[i].config, buffer[i].deferred); + for (var i = 0; i < this.buffer.length; ++i) { + retry(this.buffer[i].config, this.buffer[i].deferred); } - buffer = []; + this.buffer = []; } - return { + return { loginConfirmed: function () { $rootScope.$broadcast('event:auth-loginConfirmed'); retryAll(); } } - }] - }) + } + ]; +} + +angular.module('http-auth-interceptor', []) + + .provider('authService', AuthService) /** * $http interceptor. @@ -64,7 +69,7 @@ angular.module('http-auth-interceptor', []) function error(response: ng.IHttpPromiseCallbackArg) { if (response.status === 401) { - var deferred = $q.defer(); + var deferred = $q.defer(); authServiceProvider.pushToBuffer(response.config, deferred); $rootScope.$broadcast('event:auth-loginRequired'); return deferred.promise; @@ -95,15 +100,16 @@ module HttpAndRegularPromiseTests { theAnswer: number; letters: string[]; snack: string; + nothing?: string; } var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => { - $http.get("http://somewhere/some/resource") + $http.get("http://somewhere/some/resource") .success((data: ExpectedResponse) => { $scope.person = data; }); - $http.get("http://somewhere/some/resource") + $http.get("http://somewhere/some/resource") .then((response: ng.IHttpPromiseCallbackArg) => { // typing lost, so something like // var i: number = response.data @@ -111,7 +117,7 @@ module HttpAndRegularPromiseTests { $scope.person = response.data; }); - $http.get("http://somewhere/some/resource") + $http.get("http://somewhere/some/resource") .then((response: ng.IHttpPromiseCallbackArg) => { // typing lost, so something like // var i: number = response.data @@ -139,6 +145,12 @@ module HttpAndRegularPromiseTests { dPromise.then((snack: string) => { $scope.snack = snack; }); + + // $q.when may be called without arguments + var ePromise: ng.IPromise = $q.when(); + ePromise.then(() => { + $scope.nothing = "really nothing"; + }); } // Test that we can pass around a type-checked success/error Promise Callback @@ -148,7 +160,7 @@ module HttpAndRegularPromiseTests { var buildFooData: Function = () => 42; var doFoo: Function = (callback: ng.IHttpPromiseCallback) => { - $http.get('/foo', buildFooData()) + $http.get('/foo', buildFooData()) .success(callback); } @@ -176,7 +188,8 @@ mod.factory(My.Namespace); mod.filter('name', function ($scope: ng.IScope) { }) mod.filter('name', ['$scope', function ($scope: ng.IScope) { }]) mod.filter(My.Namespace); -mod.provider('name', function ($scope: ng.IScope) { }) +mod.provider('name', function ($scope: ng.IScope) { return { $get: () => { } } }) +mod.provider('name', TestProvider); mod.provider('name', ['$scope', function ($scope: ng.IScope) { }]) mod.provider(My.Namespace); mod.service('name', function ($scope: ng.IScope) { }) @@ -189,6 +202,13 @@ mod.value('name', 23); mod.value('name', "23"); mod.value(My.Namespace); +class TestProvider implements ng.IServiceProvider { + constructor(private $scope: ng.IScope) { + } + + $get() { + } +} // Promise signature tests var foo: ng.IPromise; @@ -220,9 +240,30 @@ foo.then((x) => { }); +var httpFoo: ng.IHttpPromise; +httpFoo.then((x) => { + // When returning a promise the generic type must be inferred. + var innerPromise : ng.IPromise; + return innerPromise; +}).then((x) => { + // must still be number. + x.toFixed(); +}); + + +function test_angular_forEach() { + var values: { [key: string]: string } = { name: 'misko', gender: 'male' }; + var log: string[] = []; + angular.forEach(values, function (value, key) { + this.push(key + ': ' + value); + }, log); + //expect(log).toEqual(['name: misko', 'gender: male']); +} + // angular.element() tests var element = angular.element("div.myApp"); var scope: ng.IScope = element.scope(); +var isolateScope: ng.IScope = element.isolateScope(); @@ -239,3 +280,253 @@ test_IAttributes({ }, $attr: {} }); + +// test from https://docs.angularjs.org/guide/directive +angular.module('docsSimpleDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + template: 'Name: {{customer.name}} Address: {{customer.address}}' + }; + }); + +angular.module('docsTemplateUrlDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsRestrictDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsScopeProblemExample', []) + .controller('NaomiController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .controller('IgorController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Igor', + address: '123 Somewhere' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsIsolateScopeDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.igor = { name: 'Igor', address: '123 Somewhere' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-iso.html' + }; + }); + +angular.module('docsIsolationExample', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-plus-vojta.html' + }; + }); + +angular.module('docsTimeDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.format = 'M/d/yy h:mm:ss a'; + }]) + .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any): ng.IDirective { + + return { + link: function(scope: any, element: any, attrs: any) { + var format: any, + timeoutId: any; + + function updateTime() { + element.text(dateFilter(new Date(), format)); + } + + scope.$watch(attrs.myCurrentTime, function (value: any) { + format = value; + updateTime(); + }); + + element.on('$destroy', function () { + $interval.cancel(timeoutId); + }); + + // start the UI update process; save the timeoutId for canceling + timeoutId = $interval(function () { + updateTime(); // update DOM + }, 1000); + } + }; + }]); + +angular.module('docsTransclusionDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + templateUrl: 'my-dialog.html' + }; + }); + +angular.module('docsTransclusionExample', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + templateUrl: 'my-dialog.html', + link: function (scope: any, element: any) { + scope.name = 'Jeff'; + } + }; + }); + +angular.module('docsIsoFnBindExample', []) + .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { + $scope.name = 'Tobias'; + $scope.hideDialog = function () { + $scope.dialogIsHidden = true; + $timeout(function () { + $scope.dialogIsHidden = false; + }, 2000); + }; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: { + 'close': '&onClose' + }, + templateUrl: 'my-dialog-close.html' + }; + }); + +angular.module('dragModule', []) + .directive('myDraggable', ['$document', function($document: any) { + return function(scope: any, element: any, attr: any) { + var startX = 0, startY = 0, x = 0, y = 0; + + element.css({ + position: 'relative', + border: '1px solid red', + backgroundColor: 'lightgrey', + cursor: 'pointer' + }); + + element.on('mousedown', function(event: any) { + // Prevent default dragging of selected content + event.preventDefault(); + startX = event.pageX - x; + startY = event.pageY - y; + $document.on('mousemove', mousemove); + $document.on('mouseup', mouseup); + }); + + function mousemove(event: any) { + y = event.pageY - startY; + x = event.pageX - startX; + element.css({ + top: y + 'px', + left: x + 'px' + }); + } + + function mouseup() { + $document.off('mousemove', mousemove); + $document.off('mouseup', mouseup); + } + }; + }]); + +angular.module('docsTabsExample', []) + .directive('myTabs', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + controller: function($scope: any) { + var panes: any = $scope.panes = []; + + $scope.select = function(pane: any) { + angular.forEach(panes, function(pane: any) { + pane.selected = false; + }); + pane.selected = true; + }; + + this.addPane = function(pane: any) { + if (panes.length === 0) { + $scope.select(pane); + } + panes.push(pane); + }; + }, + templateUrl: 'my-tabs.html' + }; + }) + .directive('myPane', function() { + return { + require: '^myTabs', + restrict: 'E', + transclude: true, + scope: { + title: '@' + }, + link: function(scope, element, attrs, tabsCtrl) { + tabsCtrl.addPane(scope); + }, + templateUrl: 'my-pane.html' + }; + }); diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index c5e45258d2..e447985fba 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -18,6 +18,15 @@ interface Function { /////////////////////////////////////////////////////////////////////////////// declare module ng { + // not directly implemented, but ensures that constructed class implements $get + interface IServiceProviderClass { + new(...args: any[]): IServiceProvider; + } + + interface IServiceProviderFactory { + (...args: any[]): IServiceProvider; + } + // All service providers extend this interface interface IServiceProvider { $get: any; @@ -37,7 +46,38 @@ declare module ng { element: IAugmentedJQueryStatic; equals(value1: any, value2: any): boolean; extend(destination: any, ...sources: any[]): any; + + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: T[], iterator: (value: T, key: number) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any; + fromJson(json: string): any; identity(arg?: any): any; injector(modules?: any[]): auto.IInjectorService; @@ -51,16 +91,21 @@ declare module ng { isString(value: any): boolean; isUndefined(value: any): boolean; lowercase(str: string): string; - /** construct your angular application - official docs: Interface for configuring angular modules. - see: http://docs.angularjs.org/api/angular.Module - */ + + /** + * The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism. + * + * When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved. + * + * @param name The name of the module to create or retrieve. + * @param requires The names of modules this module depends on. If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * @param configFn Optional configuration function for the module. + */ module( - /** name of your module you want to create */ name: string, - /** name of modules yours depends on */ requires?: string[], - configFunction?: any): IModule; + configFn?: Function): IModule; + noop(...args: any[]): void; toJson(obj: any, pretty?: boolean): string; uppercase(str: string): string; @@ -81,37 +126,90 @@ declare module ng { animation(name: string, animationFactory: Function): IModule; animation(name: string, inlineAnnotatedFunction: any[]): IModule; animation(object: Object): IModule; - /** configure existing services. - Use this method to register work which needs to be performed on module loading - */ + /** + * Use this method to register work which needs to be performed on module loading. + * + * @param configFn Execute this function on module load. Useful for service configuration. + */ config(configFn: Function): IModule; - /** configure existing services. - Use this method to register work which needs to be performed on module loading - */ + /** + * Use this method to register work which needs to be performed on module loading. + * + * @param inlineAnnotatedFunction Execute this function on module load. Useful for service configuration. + */ config(inlineAnnotatedFunction: any[]): IModule; + /** + * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. + * + * @param name The name of the constant. + * @param value The constant value. + */ constant(name: string, value: any): IModule; constant(object: Object): IModule; + /** + * The $controller service is used by Angular to create new controllers. + * + * This provider allows controller registration via the register method. + * + * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. + * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). + */ controller(name: string, controllerConstructor: Function): IModule; + /** + * The $controller service is used by Angular to create new controllers. + * + * This provider allows controller registration via the register method. + * + * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. + * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). + */ controller(name: string, inlineAnnotatedConstructor: any[]): IModule; controller(object : Object): IModule; - directive(name: string, directiveFactory: Function): IModule; + directive(name: string, directiveFactory: IDirectiveFactory): IModule; directive(name: string, inlineAnnotatedFunction: any[]): IModule; directive(object: Object): IModule; - factory(name: string, serviceFactoryFunction: Function): IModule; + /** + * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. + * + * @param name The name of the instance. + * @param $getFn The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). + */ + factory(name: string, $getFn: Function): IModule; + /** + * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. + * + * @param name The name of the instance. + * @param inlineAnnotatedFunction The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). + */ factory(name: string, inlineAnnotatedFunction: any[]): IModule; factory(object: Object): IModule; filter(name: string, filterFactoryFunction: Function): IModule; filter(name: string, inlineAnnotatedFunction: any[]): IModule; filter(object: Object): IModule; - provider(name: string, serviceProviderConstructor: Function): IModule; + provider(name: string, serviceProviderFactory: IServiceProviderFactory): IModule; + provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule; provider(name: string, inlineAnnotatedConstructor: any[]): IModule; - provider(name: string, providerObject: auto.IProvider): IModule; + provider(name: string, providerObject: IServiceProvider): IModule; provider(object: Object): IModule; + /** + * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. + */ run(initializationFunction: Function): IModule; + /** + * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. + */ run(inlineAnnotatedFunction: any[]): IModule; service(name: string, serviceConstructor: Function): IModule; service(name: string, inlineAnnotatedConstructor: any[]): IModule; service(object: Object): IModule; + /** + * Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service. + + Value services are similar to constant services, except that they cannot be injected into a module configuration function (see config) but they can be overridden by an Angular decorator. + * + * @param name The name of the instance. + * @param value The value. + */ value(name: string, value: any): IModule; value(object: Object): IModule; @@ -125,10 +223,10 @@ declare module ng { // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes /////////////////////////////////////////////////////////////////////////// interface IAttributes { - // this is necessary to be able to access the scoped attributes. it's not very elegant - // because you have to use attrs['foo'] instead of attrs.foo but I don't know of a better way - // this should really be limited to return string but it creates this problem: http://stackoverflow.com/q/17201854/165656 - [name: string]: any; + // this is necessary to be able to access the scoped attributes. it's not very elegant + // because you have to use attrs['foo'] instead of attrs.foo but I don't know of a better way + // this should really be limited to return string but it creates this problem: http://stackoverflow.com/q/17201854/165656 + [name: string]: any; // Adds the CSS class value specified by the classVal parameter to the // element. If animations are enabled then an animation will be triggered @@ -154,11 +252,17 @@ declare module ng { $attr: Object; } - /////////////////////////////////////////////////////////////////////////// - // FormController - // see http://docs.angularjs.org/api/ng.directive:form.FormController - /////////////////////////////////////////////////////////////////////////// + /** + * form.FormController - type in module ng + * see https://docs.angularjs.org/api/ng/type/form.FormController + */ interface IFormController { + + /** + * Indexer which should return ng.INgModelController for most properties but cannot because of "All named properties must be assignable to string indexer type" constraint - see https://github.com/Microsoft/TypeScript/issues/272 + */ + [name: string]: any; + $pristine: boolean; $dirty: boolean; $valid: boolean; @@ -166,6 +270,7 @@ declare module ng { $error: any; $addControl(control: ng.INgModelController): void; $removeControl(control: ng.INgModelController): void; + $setValidity(validationErrorKey: string, isValid: boolean, control: ng.INgModelController): void; $setDirty(): void; $setPristine(): void; } @@ -186,6 +291,7 @@ declare module ng { $parsers: IModelParser[]; $formatters: IModelFormatter[]; + $viewChangeListeners: IModelViewChangeListener[]; $error: any; $pristine: boolean; $dirty: boolean; @@ -201,6 +307,10 @@ declare module ng { (value: any): any; } + interface IModelViewChangeListener { + (): void; + } + /////////////////////////////////////////////////////////////////////////// // Scope // see http://docs.angularjs.org/api/ng.$rootScope.Scope @@ -236,8 +346,13 @@ declare module ng { $watchCollection(watchExpression: string, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; $watchCollection(watchExpression: (scope: IScope) => any, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + $watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + $watchGroup(watchExpressions: {(scope: IScope) : any}[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + $parent: IScope; + $root: IRootScopeService; + $id: string; // Hidden members @@ -260,13 +375,17 @@ declare module ng { // WindowService // see http://docs.angularjs.org/api/ng.$window /////////////////////////////////////////////////////////////////////////// - interface IWindowService extends Window {} + interface IWindowService extends Window { + [key: string]: any; + } /////////////////////////////////////////////////////////////////////////// // BrowserService // TODO undocumented, so we need to get it from the source code /////////////////////////////////////////////////////////////////////////// - interface IBrowserService {} + interface IBrowserService { + [key: string]: any; + } /////////////////////////////////////////////////////////////////////////// // TimeoutService @@ -351,6 +470,7 @@ declare module ng { /////////////////////////////////////////////////////////////////////////// // LogService // see http://docs.angularjs.org/api/ng.$log + // see http://docs.angularjs.org/api/ng.$logProvider /////////////////////////////////////////////////////////////////////////// interface ILogService { debug: ILogCall; @@ -360,6 +480,11 @@ declare module ng { warn: ILogCall; } + interface ILogProvider { + debugEnabled(enabled: boolean): ILogProvider; + debugEnabled(): boolean; + } + // We define this as separete interface so we can reopen it later for // the ngMock module. interface ILogCall { @@ -376,11 +501,11 @@ declare module ng { } interface IParseProvider { - logPromiseWarnings(): boolean; - logPromiseWarnings(value: boolean): IParseProvider; + logPromiseWarnings(): boolean; + logPromiseWarnings(value: boolean): IParseProvider; - unwrapPromises(): boolean; - unwrapPromises(value: boolean): IParseProvider; + unwrapPromises(): boolean; + unwrapPromises(value: boolean): IParseProvider; } interface ICompiledExpression { @@ -446,17 +571,58 @@ declare module ng { /////////////////////////////////////////////////////////////////////////// interface IRootElementService extends JQuery {} - /////////////////////////////////////////////////////////////////////////// - // QService - // see http://docs.angularjs.org/api/ng.$q - /////////////////////////////////////////////////////////////////////////// + /** + * $q - service in module ng + * A promise/deferred implementation inspired by Kris Kowal's Q. + * See http://docs.angularjs.org/api/ng/service/$q + */ interface IQService { + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * + * Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * + * @param promises An array or hash of promises. + */ all(promises: IPromise[]): IPromise; - all(promises: {[id: string]: IPromise;}): IPromise<{[id: string]: any}>; + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * + * Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * + * @param promises An array or hash of promises. + */ + all(promises: { [id: string]: IPromise; }): IPromise<{ [id: string]: any }>; + /** + * Creates a Deferred object which represents a task which will finish in the future. + */ defer(): IDeferred; + /** + * Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it. + * + * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject. + * + * @param reason Constant, message, exception or an object representing the rejection reason. + */ reject(reason?: any): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ when(value: IPromise): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ when(value: T): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ + when(): IPromise; } interface IPromise { @@ -538,6 +704,12 @@ declare module ng { // Undocumented, but it is there... directive(directivesMap: any): ICompileProvider; + + aHrefSanitizationWhitelist(): RegExp; + aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider; + + imgSrcSanitizationWhitelist(): RegExp; + imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider; } interface ICloneAttachFunction { @@ -574,44 +746,157 @@ declare module ng { register(name: string, dependencyAnnotatedConstructor: any[]): void; } - /////////////////////////////////////////////////////////////////////////// - // HttpService - // see http://docs.angularjs.org/api/ng.$http - /////////////////////////////////////////////////////////////////////////// + /** + * HttpService + * see http://docs.angularjs.org/api/ng/service/$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; + /** + * Object describing the request to be made and how it should be processed. + */ + (config: IRequestConfig): IHttpPromise; + + /** + * Shortcut method to perform GET request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + get(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform DELETE request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + delete(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform HEAD request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + head(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform JSONP request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + jsonp(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform POST request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param data Request content + * @param config Optional configuration object + */ + post(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform PUT request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param data Request content + * @param config Optional configuration object + */ + put(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Runtime equivalent of the $httpProvider.defaults property. Allows configuration of default headers, withCredentials as well as request and response transformations. + */ defaults: IRequestConfig; - // For debugging, BUT it is documented as public, so... + /** + * Array of config objects for currently pending requests. This is primarily meant to be used for debugging purposes. + */ 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; + /** + * Object describing the request to be made and how it should be processed. + * see http://docs.angularjs.org/api/ng/service/$http#usage + */ + interface IRequestShortcutConfig { + /** + * {Object.} + * Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified. + */ params?: any; - // XXX it has it's own structure... perhaps we should define it in the future + /** + * Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. + */ headers?: any; + /** + * Name of HTTP header to populate with the XSRF token. + */ + xsrfHeaderName?: string; + + /** + * Name of cookie containing the XSRF token. + */ + xsrfCookieName?: string; + + /** + * {boolean|Cache} + * If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching. + */ cache?: any; + + /** + * whether to to set the withCredentials flag on the XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5 for more information. + */ withCredentials?: boolean; - // These accept multiple types, so let's define them as any + /** + * {string|Object} + * Data to be sent as the request message data. + */ data?: any; + + /** + * {function(data, headersGetter)|Array.} + * Transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version. + */ transformRequest?: any; + + /** + * {function(data, headersGetter)|Array.} + * Transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version. + */ transformResponse?: any; - timeout?: any; // number | promise + + /** + * {number|Promise} + * Timeout in milliseconds, or promise that should abort the request when resolved. + */ + timeout?: any; + + /** + * See requestType. + */ + responseType?: string; + } + + /** + * Object describing the request to be made and how it should be processed. + * see http://docs.angularjs.org/api/ng/service/$http#usage + */ + interface IRequestConfig extends IRequestShortcutConfig { + /** + * HTTP method (e.g. 'GET', 'POST', etc) + */ + method: string; + /** + * Absolute or relative URL of the resource that is being requested. + */ + url: string; } interface IHttpPromiseCallback { @@ -623,13 +908,14 @@ declare module ng { status?: number; headers?: (headerName: string) => string; config?: IRequestConfig; + statusText?: string; } interface IHttpPromise extends IPromise { success(callback: IHttpPromiseCallback): IHttpPromise; - error(callback: IHttpPromiseCallback): IHttpPromise; - then(successCallback: (response: IHttpPromiseCallbackArg) => TResult, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; - then(successCallback: (response: IHttpPromiseCallbackArg) => IPromise, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; + error(callback: IHttpPromiseCallback): IHttpPromise; + then(successCallback: (response: IHttpPromiseCallbackArg) => IPromise, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; + then(successCallback: (response: IHttpPromiseCallbackArg) => TResult, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; } interface IHttpProvider extends IServiceProvider { @@ -686,26 +972,26 @@ declare module ng { // SCEService // see http://docs.angularjs.org/api/ng.$sce /////////////////////////////////////////////////////////////////////////// - interface ISCEService { - getTrusted(type: string, mayBeTrusted: any): any; - getTrustedCss(value: any): any; - getTrustedHtml(value: any): any; - getTrustedJs(value: any): any; - getTrustedResourceUrl(value: any): any; - getTrustedUrl(value: any): any; - parse(type: string, expression: string): (context: any, locals: any) => any; - parseAsCss(expression: string): (context: any, locals: any) => any; - parseAsHtml(expression: string): (context: any, locals: any) => any; - parseAsJs(expression: string): (context: any, locals: any) => any; - parseAsResourceUrl(expression: string): (context: any, locals: any) => any; - parseAsUrl(expression: string): (context: any, locals: any) => any; - trustAs(type: string, value: any): any; - trustAsHtml(value: any): any; - trustAsJs(value: any): any; - trustAsResourceUrl(value: any): any; - trustAsUrl(value: any): any; - isEnabled(): boolean; - } + interface ISCEService { + getTrusted(type: string, mayBeTrusted: any): any; + getTrustedCss(value: any): any; + getTrustedHtml(value: any): any; + getTrustedJs(value: any): any; + getTrustedResourceUrl(value: any): any; + getTrustedUrl(value: any): any; + parse(type: string, expression: string): (context: any, locals: any) => any; + parseAsCss(expression: string): (context: any, locals: any) => any; + parseAsHtml(expression: string): (context: any, locals: any) => any; + parseAsJs(expression: string): (context: any, locals: any) => any; + parseAsResourceUrl(expression: string): (context: any, locals: any) => any; + parseAsUrl(expression: string): (context: any, locals: any) => any; + trustAs(type: string, value: any): any; + trustAsHtml(value: any): any; + trustAsJs(value: any): any; + trustAsResourceUrl(value: any): any; + trustAsUrl(value: any): any; + isEnabled(): boolean; + } /////////////////////////////////////////////////////////////////////////// // SCEProvider @@ -741,6 +1027,11 @@ declare module ng { // and http://docs.angularjs.org/guide/directive /////////////////////////////////////////////////////////////////////////// + interface IDirectiveFactory { + (...args: any[]): IDirective; + } + + interface IDirective{ compile?: (templateElement: IAugmentedJQuery, @@ -796,6 +1087,7 @@ declare module ng { controller(name: string): any; injector(): any; scope(): IScope; + isolateScope(): IScope; inheritedData(key: string, value: any): JQuery; inheritedData(obj: { [key: string]: any; }): JQuery; @@ -818,9 +1110,6 @@ declare module ng { // AUTO module (angular.js) /////////////////////////////////////////////////////////////////////////// export module auto { - interface IProvider { - $get: any; - } /////////////////////////////////////////////////////////////////////// // InjectorService @@ -830,7 +1119,7 @@ declare module ng { annotate(fn: Function): string[]; annotate(inlineAnnotatedFunction: any[]): string[]; get(name: string): any; - has(name: string): boolean; + has(name: string): boolean; instantiate(typeConstructor: Function, locals?: any): any; invoke(inlineAnnotatedFunction: any[]): any; invoke(func: Function, context?: any, locals?: any): any; @@ -844,10 +1133,32 @@ declare module ng { // Documentation says it returns the registered instance, but actual // implementation does not return anything. // constant(name: string, value: any): any; + /** + * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. + * + * @param name The name of the constant. + * @param value The constant value. + */ constant(name: string, value: any): void; + /** + * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. + * + * @param name The name of the service to decorate. + * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: + * + * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. + */ decorator(name: string, decorator: Function): void; - decorator(name: string, decoratorInline: any[]): void; + /** + * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. + * + * @param name The name of the service to decorate. + * @param inlineAnnotatedFunction This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: + * + * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. + */ + decorator(name: string, inlineAnnotatedFunction: any[]): void; factory(name: string, serviceFactoryFunction: Function): ng.IServiceProvider; factory(name: string, inlineAnnotatedFunction: any[]): ng.IServiceProvider; provider(name: string, provider: ng.IServiceProvider): ng.IServiceProvider; diff --git a/angularjs/legacy/angular-1.0-tests.ts b/angularjs/legacy/angular-1.0-tests.ts index ff3c87f77f..dc4dbcee00 100644 --- a/angularjs/legacy/angular-1.0-tests.ts +++ b/angularjs/legacy/angular-1.0-tests.ts @@ -64,7 +64,7 @@ angular.module('http-auth-interceptor', []) function error(response: ng.IHttpPromiseCallbackArg) { if (response.status === 401) { - var deferred = $q.defer(); + var deferred = $q.defer(); authServiceProvider.pushToBuffer(response.config, deferred); $rootScope.$broadcast('event:auth-loginRequired'); return deferred.promise; diff --git a/ansicolors/ansicolors.d.ts b/ansicolors/ansicolors.d.ts new file mode 100644 index 0000000000..2f61b04352 --- /dev/null +++ b/ansicolors/ansicolors.d.ts @@ -0,0 +1,9 @@ +// Type definitions for ansicolors +// Project: https://github.com/thlorenz/ansicolors +// Definitions by: rogierschouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "ansicolors" { + var colors: {[index: string]: (s: string) => string;}; + export = colors; +} diff --git a/arbiter/Arbiter.d.ts b/arbiter/Arbiter.d.ts index cb35f9c584..b5bededed6 100644 --- a/arbiter/Arbiter.d.ts +++ b/arbiter/Arbiter.d.ts @@ -121,12 +121,12 @@ declare module ArbiterDef { /** * Unsubscribing simply sets a flag which prevents the subscriber from executing, in case you want to re-subscribe later. */ - unsubscribe(subscription_id: number); + unsubscribe(subscription_id: number): boolean; /** * After unsubscribing, you can later re-subscribe to begin receiving messages again. */ - resubscribe(subscription_id: number); + resubscribe(subscription_id: number): boolean; } } diff --git a/arbiter/Arbiter.d.ts.tscparams b/arbiter/Arbiter.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/arbiter/Arbiter.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/asciify/asciify.d.ts b/asciify/asciify.d.ts index 4dc47cd3a3..33f82019b1 100644 --- a/asciify/asciify.d.ts +++ b/asciify/asciify.d.ts @@ -1,6 +1,6 @@ // Type definitions for asciify 1.3.5 // Project: https://www.npmjs.org/package/asciify -// Definitions by: Alan Norbauer http://alan.norbauer.com +// Definitions by: Alan Norbauer // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -26,4 +26,4 @@ declare module "asciify" { } export = asciify -} \ No newline at end of file +} diff --git a/async/async-tests.ts b/async/async-tests.ts index ae92bbff98..9b0c8e7eeb 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -145,9 +145,8 @@ q.drain = function () { console.log('all items have been processed'); } -q.push({ name: 'foo' }, function (err) { - console.log('finished processing foo'); -}); +q.push({ name: 'foo' }); + q.push({ name: 'bar' }, function (err) { console.log('finished processing bar'); }); @@ -156,6 +155,64 @@ q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { console.log('finished processing bar'); }); +q.unshift({ name: 'foo' }); + +q.unshift({ name: 'bar' }, function (err) { + console.log('finished processing bar'); +}); + +q.unshift([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { + console.log('finished processing bar'); +}); + +var qLength : number = q.length(); +var qStarted : boolean = q.started; +var qPaused : boolean = q.paused; +var qProcessingCount : number = q.running(); +var qIsIdle : boolean = q.idle(); + +q.saturated = function() { + console.log('queue is saturated.'); +} + +q.empty = function() { + console.log('queue is empty.'); +} + +q.drain = function() { + console.log('queue was drained.'); +} + +q.pause(); +q.resume(); +q.kill(); + +// tests for strongly typed tasks +var q2 = async.queue(function (task: string, callback) { + console.log('Task: ' + task); + callback(); +}, 1); + +q2.push('task1'); + +q2.push('task2', function (error, results: string[]) { + console.log('Finished tasks: ' + results.join(', ')); +}); + +q2.push(['task3', 'task4', 'task5'], function (error, results: string[]) { + console.log('Finished tasks: ' + results.join(', ')); +}); + +q2.unshift('task1'); + +q2.unshift('task2', function (error, results: string[]) { + console.log('Finished tasks: ' + results.join(', ')); +}); + +q2.unshift(['task3', 'task4', 'task5'], function (error, results: string[]) { + console.log('Finished tasks: ' + results.join(', ')); +}); + var filename = ''; async.auto({ get_data: function (callback) { }, diff --git a/async/async.d.ts b/async/async.d.ts index b8666febfb..d1d5926299 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -3,8 +3,8 @@ // Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface AsyncMultipleResultsCallback { (err: string, results: T[]): any; } -interface AsyncSingleResultCallback { (err: string, result: T): void; } +interface AsyncMultipleResultsCallback { (err: Error, results: T[]): any; } +interface AsyncSingleResultCallback { (err: Error, result: T): void; } interface AsyncTimesCallback { (n: number, callback: AsyncMultipleResultsCallback): void; } interface AsyncIterator { (item: T, callback: AsyncSingleResultCallback): void; } @@ -15,10 +15,20 @@ interface AsyncWorker { (task: T, callback: Function): void; } interface AsyncQueue { length(): number; concurrency: number; + started: boolean; + paused: boolean; push(task: T, callback?: AsyncMultipleResultsCallback): void; - saturated: AsyncMultipleResultsCallback; - empty: AsyncMultipleResultsCallback; - drain: AsyncMultipleResultsCallback; + push(task: T[], callback?: AsyncMultipleResultsCallback): void; + unshift(task: T, callback?: AsyncMultipleResultsCallback): void; + unshift(task: T[], callback?: AsyncMultipleResultsCallback): void; + saturated: () => any; + empty: () => any; + drain: () => any; + running(): number; + idle(): boolean; + pause(): void; + resume(): void; + kill(): void; } interface Async { @@ -27,28 +37,28 @@ interface Async { forEach(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; forEachSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; forEachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; - map(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); - mapSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); - filter(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); - select(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); - filterSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); - selectSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); - reject(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); - rejectSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); - reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback); - inject(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback); - foldl(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback); - reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback); - foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback); - detect(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); - detectSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); - sortBy(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); - some(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); - any(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); - every(arr: T[], iterator: AsyncIterator, callback: (result: boolean) => any); - all(arr: T[], iterator: AsyncIterator, callback: (result: boolean) => any); - concat(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); - concatSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback); + map(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + mapSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + filter(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + select(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + filterSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + selectSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + reject(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + rejectSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback): any; + inject(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback): any; + foldl(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback): any; + reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback): any; + foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback): any; + detect(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + detectSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + sortBy(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + some(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + any(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + every(arr: T[], iterator: AsyncIterator, callback: (result: boolean) => any): any; + all(arr: T[], iterator: AsyncIterator, callback: (result: boolean) => any): any; + concat(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + concatSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; // Control Flow series(tasks: T[], callback?: AsyncMultipleResultsCallback): void; diff --git a/async/async.d.ts.tscparams b/async/async.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/async/async.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/async/asyncamd-tests.ts.tscparams b/async/asyncamd-tests.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/async/asyncamd-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/atmosphere/atmosphere-tests.ts b/atmosphere/atmosphere-tests.ts new file mode 100644 index 0000000000..44c2880a35 --- /dev/null +++ b/atmosphere/atmosphere-tests.ts @@ -0,0 +1,46 @@ +/// + +var socket = atmosphere; + +var request1:Atmosphere.Request = new atmosphere.AtmosphereRequest(); + +request1.url = document.location.toString() + 'chat'; +request1.contentType = "application/json"; +request1.transport = 'websocket'; +request1.fallbackTransport = 'long-polling'; + +var request2:Atmosphere.Request = { + url: 'http://localhost:8080/chat', + contentType: "application/json", + logLevel: 'debug', + transport: 'websocket', + fallbackTransport: 'long-polling' +}; + +request1.onError = function (response?:Atmosphere.Response) {}; +request1.onClose = function (response?:Atmosphere.Response) {}; +request1.onOpen = function (response?:Atmosphere.Response) {}; +request1.onMessage = function (response:Atmosphere.Response) {}; +request1.onReopen = function (request?:Atmosphere.Request, response?:Atmosphere.Response) {}; +request1.onReconnect = function (request?:Atmosphere.Request, response?:Atmosphere.Response) {}; +request1.onMessagePublished = function (response?:Atmosphere.Response) {}; +request1.onTransportFailure = function (reason?:string, response?:Atmosphere.Response) {}; +request1.onLocalMessage = function (request?:Atmosphere.Request) {}; +request1.onFailureToReconnect = function (request?:Atmosphere.Request, response?:Atmosphere.Response) {}; +request1.onClientTimeout = function (request?:Atmosphere.Request) {}; + +request1.subscribe = function (options:Atmosphere.Request) {}; +request1.execute = function () {}; +request1.close = function () {}; +request1.disconnect = function () {}; +request1.getUrl = function ():string { return "http://www.toedter.com" }; +request1.push = function (message:string, dispatchUrl?:string) {}; +request1.getUUID = function () {}; +request1.pushLocal = function (message:string) {}; + +var subSocket:Atmosphere.Request = socket.subscribe(request1); +var subSocket2:Atmosphere.Request = socket.subscribe('http://chat.com', function() {}, request2); +subSocket2.close(); + +subSocket.push("test"); +socket.unsubscribe(); \ No newline at end of file diff --git a/atmosphere/atmosphere.d.ts b/atmosphere/atmosphere.d.ts new file mode 100644 index 0000000000..59d743a4b9 --- /dev/null +++ b/atmosphere/atmosphere.d.ts @@ -0,0 +1,106 @@ +// Type definitions for Atmosphere v2.1.5 +// Project: https://github.com/Atmosphere/atmosphere-javascript +// Definitions by: Kai Toedter +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Atmosphere { + interface Atmosphere { + /** + * The atmosphere API is a little bit special here: the first parameter can either be + * a URL string or a Request object. If it is a URL string, then the additional parameters are expected. + */ + subscribe?: (requestOrUrl:any, callback?:Function, request?:Request) => Request; + unsubscribe?: () => void; + + AtmosphereRequest?: AtmosphereRequest; + } + + // needed to fit JavaScript "new atmosphere.AtmosphereRequest()" + // and compile with --noImplicitAny + interface AtmosphereRequest { + new(): Request; + } + + interface Request { + timeout?: number; + method?: string; + headers?: any; + contentType?: string; + callback?: Function; + url?: string; + data?: string; + suspend?: boolean; + maxRequest?: number; + reconnect?: boolean; + maxStreamingLength?: number; + lastIndex?: number; + logLevel?: string; + requestCount?: number; + fallbackMethod?: string; + fallbackTransport?: string; + transport?: string; + webSocketImpl?: any; + webSocketBinaryType?: any; + dispatchUrl?: string; + webSocketPathDelimiter?: string; + enableXDR?: boolean; + rewriteURL?: boolean; + attachHeadersAsQueryString?: boolean; + executeCallbackBeforeReconnect?: boolean; + readyState?: number; + lastTimestamp?: number; + withCredentials?: boolean; + trackMessageLength?: boolean; + messageDelimiter?: string; + connectTimeout?: number; + reconnectInterval?: number; + dropHeaders?: boolean; + uuid?: number; + async?: boolean; + shared?: boolean; + readResponsesHeaders?: boolean; + maxReconnectOnClose?: number; + enableProtocol?: boolean; + pollingInterval?: number; + + onError?: (response?:Response) => void; + onClose?: (response?:Response) => void; + onOpen?: (response?:Response) => void; + onMessage?: (response:Response) => void; + onReopen?: (request?:Request, response?:Response) => void; + onReconnect?: (request?:Request, response?:Response) => void; + onMessagePublished?: (response?:Response) => void; + onTransportFailure?: (reason?:string, response?:Response) => void; + onLocalMessage?: (request?:Request) => void; + onFailureToReconnect?: (request?:Request, response?:Response) => void; + onClientTimeout?: (request?:Request) => void; + + subscribe?: (options:Request) => void; + execute?: () => void; + close?: () => void; + disconnect?: () => void; + getUrl?: () => string; + push?: (message:string, dispatchUrl?:string) => void; + getUUID?: () => void; + pushLocal?: (message:string) => void; + } + + interface Response { + status?: number; + reasonPhrase?: string; + responseBody?: string; + messages?: string[]; + headers?: string[]; + state?: string; + transport?: string; + error?: string; + request?: Request; + partialMessage?: string; + errorHandled?: boolean; + closedByClientTimeout?: boolean; + } +} + +declare var atmosphere:Atmosphere.Atmosphere; + + diff --git a/atom/atom-tests.ts b/atom/atom-tests.ts index 505973c9af..29dde2d89e 100644 --- a/atom/atom-tests.ts +++ b/atom/atom-tests.ts @@ -11,7 +11,7 @@ var File = pathwatcher.File; class SampleView extends _atom.ScrollView { editorId:string; - file:pathwatcher.IFile; + file:PathWatcher.IFile; editor:AtomCore.IEditor; static deserialize(state:any):SampleView { diff --git a/atom/atom.d.ts b/atom/atom.d.ts index 14a8dbebae..00f55ef024 100644 --- a/atom/atom.d.ts +++ b/atom/atom.d.ts @@ -4,14 +4,18 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// +/// /// /// +/// +/// +/// // Policy: this definition file only declare element related to `atom`. // if js file include to another npm package (e.g. "space-pen", "mixto" and "emissary"). // you should create a separate file. -// NOTE Document? You should use DevTools hehe... +// API documentation : https://atom.io/docs/api/v0.106.0/api/docs/README.md.html interface Window { atom: AtomCore.IAtom; @@ -22,54 +26,475 @@ interface Window { declare module AtomCore { // https://atom.io/docs/v0.84.0/advanced/view-system - interface IWorkspaceView { - prependToBottom:any; - prependToTop:any; - prependToLeft:any; - prependToRight:any; - appendToBottom:any; - appendToTop:any; - appendToLeft:any; - appendToRight:any; + interface IWorkspaceViewStatic { + new ():IWorkspaceView; - command: Function; + version: number; + configDefaults:any; + content():any; + } + + interface IWorkspaceView extends View { + // Delegator.includeInto(WorkspaceView); + + // delegate to model property's property + fullScreen:boolean; + + // delegate to model property's method + open(uri:string, options:any):Q.Promise; + openSync(uri:string, options?:any):any; + saveActivePaneItem():any; + saveActivePaneItemAs():any; + saveAll():void; + destroyActivePaneItem():any; + destroyActivePane():any; + increaseFontSize():void; + decreaseFontSize():void; + + // own property & methods + initialize(model:IWorkspace):any; + initialize(view:View, args:any):void; // do not use + model:IWorkspace; + panes: IPaneContainerView; + getModel():IWorkspace; + installShellCommands():any; + handleFocus():any; + afterAttach(onDom?:any):any; + confirmClose():boolean; + updateTitle():any; + setTitle(title:string):any; + getEditorViews():any[]; // atom.EditorView + prependToTop(element:any):any; + appendToTop(element:any):any; + prependToBottom(element:any):any; + appendToBottom(element:any):any; + prependToLeft(element:any):any; + appendToLeft(element:any):any; + prependToRight(element:any):any; + appendToRight(element:any):any; + getActivePaneView():IPaneView; + getActiveView():View; + focusPreviousPaneView():any; + focusNextPaneView():any; + focusPaneViewAbove():any; + focusPaneViewBelow():any; + focusPaneViewOnLeft():any; + focusPaneViewOnRight():any; + eachPaneView(callback:(paneView:IPaneView)=>any):{ off():any; }; + getPaneViews():IPaneView[]; + eachEditorView(callback:(editorView:any /* EditorView */)=>any):{ off():any; }; + beforeRemove():any; + + command(eventName:string, handler:Function):any; + command(eventName:string, selector:Function, handler:Function):any; + command(eventName:string, options:any, handler:Function):any; + command(eventName:string, selector:Function, options:any, handler:Function):any; + + statusBar:StatusBar.IStatusBarView; } interface IPanes { // TBD } - interface TreeView { + interface IPaneView { // TBD } + interface IPaneContainerView { + // TBD + } + + interface ITreeView { + // TBD + } + + interface IGutterViewStatic { + new(): IGutterView; + content():any; + } + + interface IGutterView extends View { + firstScreenRow:any; + lastScreenRow:any; + initialize():void; + initialize(view:View, args:any):void; // do not use + afterAttach(onDom?:any):any; + beforeRemove():any; + handleMouseEvents(e:JQueryMouseEventObject):any; + getEditorView():any; /* EditorView */ + getEditor():IEditor; + getLineNumberElements():HTMLCollection; + getLineNumberElementsForClass(klass:string):NodeList; + getLineNumberElement(bufferRow:number):NodeList; + addClassToAllLines(klass:string):boolean; + removeClassFromAllLines(klass:string):boolean; + addClassToLine(bufferRow:number, klass:string):boolean; + removeClassFromLine(bufferRow:number, klass:string):boolean; + updateLineNumbers(changes:any[], startScreenRow?:number, endScreenRow?:number):any; + prependLineElements(lineElements:any):void; + appendLineElements(lineElements:any):void; + removeLineElements(numberOfElements:number):void; + buildLineElements(startScreenRow:any, endScreenRow:any):any; + buildLineElementsHtml(startScreenRow:any, endScreenRow:any):any; + updateFoldableClasses(changes:any[]):any; + removeLineHighlights():void; + addLineHighlight(row:number, emptySelection?:boolean):any; + highlightLines():boolean; + } + interface ICommandPanel { // TBD } - interface ITextBuffer { - // TBD + interface IDisplayBufferStatic { + new(_arg?:any):IDisplayBuffer; } - interface IDisplayBuffer { - buffer: ITextBuffer; - // TBD + interface IDisplayBuffer /* extends Theorist.Model */ { + // Serializable.includeInto(Editor); + + constructor:IDisplayBufferStatic; + + verticalScrollMargin:number; + horizontalScrollMargin:number; + + declaredPropertyValues:any; + tokenizedBuffer: ITokenizedBuffer; + buffer: TextBuffer.ITextBuffer; + charWidthsByScope:any; + markers:{ [index:number]:IDisplayBufferMarker; }; + foldsByMarkerId:any; + maxLineLength:number; + screenLines:ITokenizedLine[]; + rowMap:any; // return type are RowMap + longestScreenRow:number; + subscriptions:Emissary.ISubscription[]; + subscriptionsByObject:any; // return type are WeakMap + behaviors:any; + subscriptionCounts:any; + eventHandlersByEventName:any; + pendingChangeEvent:any; + + softWrap:boolean; + + serializeParams():{id:number; softWrap:boolean; editorWidthInChars: number; scrollTop: number; scrollLeft: number; tokenizedBuffer: any; }; + deserializeParams(params:any):any; + copy():IDisplayBuffer; + updateAllScreenLines():any; + emitChanged(eventProperties:any, refreshMarkers?:boolean):any; + updateWrappedScreenLines():any; + setVisible(visible:any):any; + getVerticalScrollMargin():number; + setVerticalScrollMargin(verticalScrollMargin:number):number; + getHorizontalScrollMargin():number; + setHorizontalScrollMargin(horizontalScrollMargin:number):number; + getHeight():any; + setHeight(height:any):any; + getWidth():any; + setWidth(newWidth:any):any; + getScrollTop():number; + setScrollTop(scrollTop:number):number; + getScrollBottom():number; + setScrollBottom(scrollBottom:number):number; + getScrollLeft():number; + setScrollLeft(scrollLeft:number):number; + getScrollRight():number; + setScrollRight(scrollRight:number):number; + getLineHeight():any; + setLineHeight(lineHeight:any):any; + getDefaultCharWidth():any; + setDefaultCharWidth(defaultCharWidth:any):any; + getScopedCharWidth(scopeNames:any, char:any):any; + getScopedCharWidths(scopeNames:any):any; + setScopedCharWidth(scopeNames:any, char:any, width:any):any; + setScopedCharWidths(scopeNames:any, charWidths:any):any; + clearScopedCharWidths():any; + getScrollHeight():number; + getScrollWidth():number; + getVisibleRowRange():number[]; + intersectsVisibleRowRange(startRow:any, endRow:any):any; + selectionIntersectsVisibleRowRange(selection:any):any; + scrollToScreenRange(screenRange:any):any; + scrollToScreenPosition(screenPosition:any):any; + scrollToBufferPosition(bufferPosition:any):any; + pixelRectForScreenRange(screenRange:TextBuffer.IRange):any; + getTabLength():number; + setTabLength(tabLength:number):any; + setSoftWrap(softWrap:boolean):boolean; + getSoftWrap():boolean; + setEditorWidthInChars(editorWidthInChars:number):any; + getEditorWidthInChars():number; + getSoftWrapColumn():number; + lineForRow(row:number):any; + linesForRows(startRow:number, endRow:number):any; + getLines():any[]; + indentLevelForLine(line:any):any; + bufferRowsForScreenRows(startScreenRow:any, endScreenRow:any):any; + createFold(startRow:number, endRow:number):IFold; + isFoldedAtBufferRow(bufferRow:number):boolean; + isFoldedAtScreenRow(screenRow:number):boolean; + destroyFoldWithId(id:number):any; + unfoldBufferRow(bufferRow:number):any[]; + largestFoldStartingAtBufferRow(bufferRow:number):any; + foldsStartingAtBufferRow(bufferRow:number):any; + largestFoldStartingAtScreenRow(screenRow:any):any; + largestFoldContainingBufferRow(bufferRow:any):any; + outermostFoldsInBufferRowRange(startRow:any, endRow:any):any[]; + foldsContainingBufferRow(bufferRow:any):any[]; + screenRowForBufferRow(bufferRow:number):number; + lastScreenRowForBufferRow(bufferRow:number):number; + bufferRowForScreenRow(screenRow:number):number; + + screenRangeForBufferRange(bufferRange:TextBuffer.IPoint[]):TextBuffer.IRange; + + screenRangeForBufferRange(bufferRange:TextBuffer.IRange):TextBuffer.IRange; + + screenRangeForBufferRange(bufferRange:{start: TextBuffer.IPoint; end: TextBuffer.IPoint}):TextBuffer.IRange; + screenRangeForBufferRange(bufferRange:{start: number[]; end: TextBuffer.IPoint}):TextBuffer.IRange; + screenRangeForBufferRange(bufferRange:{start: {row:number; col:number;}; end: TextBuffer.IPoint}):TextBuffer.IRange; + + screenRangeForBufferRange(bufferRange:{start: TextBuffer.IPoint; end: number[]}):TextBuffer.IRange; + screenRangeForBufferRange(bufferRange:{start: number[]; end: number[]}):TextBuffer.IRange; + screenRangeForBufferRange(bufferRange:{start: {row:number; col:number;}; end: number[]}):TextBuffer.IRange; + + screenRangeForBufferRange(bufferRange:{start: TextBuffer.IPoint; end: {row:number; col:number;}}):TextBuffer.IRange; + screenRangeForBufferRange(bufferRange:{start: number[]; end: {row:number; col:number;}}):TextBuffer.IRange; + screenRangeForBufferRange(bufferRange:{start: {row:number; col:number;}; end: {row:number; col:number;}}):TextBuffer.IRange; + + bufferRangeForScreenRange(screenRange:TextBuffer.IPoint[]):TextBuffer.IRange; + + bufferRangeForScreenRange(screenRange:TextBuffer.IRange):TextBuffer.IRange; + + bufferRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: TextBuffer.IPoint}):TextBuffer.IRange; + bufferRangeForScreenRange(screenRange:{start: number[]; end: TextBuffer.IPoint}):TextBuffer.IRange; + bufferRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: TextBuffer.IPoint}):TextBuffer.IRange; + + bufferRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: number[]}):TextBuffer.IRange; + bufferRangeForScreenRange(screenRange:{start: number[]; end: number[]}):TextBuffer.IRange; + bufferRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: number[]}):TextBuffer.IRange; + + bufferRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: {row:number; col:number;}}):TextBuffer.IRange; + bufferRangeForScreenRange(screenRange:{start: number[]; end: {row:number; col:number;}}):TextBuffer.IRange; + bufferRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: {row:number; col:number;}}):TextBuffer.IRange; + + pixelRangeForScreenRange(screenRange:TextBuffer.IPoint[], clip?:boolean):TextBuffer.IRange; + + pixelRangeForScreenRange(screenRange:TextBuffer.IRange, clip?:boolean):TextBuffer.IRange; + + pixelRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: TextBuffer.IPoint}, clip?:boolean):TextBuffer.IRange; + pixelRangeForScreenRange(screenRange:{start: number[]; end: TextBuffer.IPoint}, clip?:boolean):TextBuffer.IRange; + pixelRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: TextBuffer.IPoint}, clip?:boolean):TextBuffer.IRange; + + pixelRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: number[]}, clip?:boolean):TextBuffer.IRange; + pixelRangeForScreenRange(screenRange:{start: number[]; end: number[]}, clip?:boolean):TextBuffer.IRange; + pixelRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: number[]}, clip?:boolean):TextBuffer.IRange; + + pixelRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: {row:number; col:number;}}, clip?:boolean):TextBuffer.IRange; + pixelRangeForScreenRange(screenRange:{start: number[]; end: {row:number; col:number;}}, clip?:boolean):TextBuffer.IRange; + pixelRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: {row:number; col:number;}}, clip?:boolean):TextBuffer.IRange; + + pixelPositionForScreenPosition(screenPosition:TextBuffer.IPoint, clip?:boolean):TextBuffer.IPoint; + pixelPositionForScreenPosition(screenPosition:number[], clip?:boolean):TextBuffer.IPoint; + pixelPositionForScreenPosition(screenPosition:{row:number; col:number;}, clip?:boolean):TextBuffer.IPoint; + + screenPositionForPixelPosition(pixelPosition:any):TextBuffer.IPoint; + + pixelPositionForBufferPosition(bufferPosition:any):any; + getLineCount():number; + getLastRow():number; + getMaxLineLength():number; + screenPositionForBufferPosition(bufferPosition:any, options:any):any; + bufferPositionForScreenPosition(bufferPosition:any, options:any):any; + scopesForBufferPosition(bufferPosition:any):any; + bufferRangeForScopeAtPosition(selector:any, position:any):any; + tokenForBufferPosition(bufferPosition:any):any; + getGrammar():IGrammar; + setGrammar(grammar:IGrammar):any; + reloadGrammar():any; + clipScreenPosition(screenPosition:any, options:any):any; + findWrapColumn(line:any, softWrapColumn:any):any; + rangeForAllLines():TextBuffer.IRange; + getMarker(id:number):IDisplayBufferMarker; + getMarkers():IDisplayBufferMarker[]; + getMarkerCount():number; + markScreenRange(range:TextBuffer.IRange, ...args:any[]):IDisplayBufferMarker; + markBufferRange(range:TextBuffer.IRange, options?:any):IDisplayBufferMarker; + markScreenPosition(screenPosition:TextBuffer.IPoint, options?:any):IDisplayBufferMarker; + markBufferPosition(bufferPosition:TextBuffer.IPoint, options?:any):IDisplayBufferMarker; + destroyMarker(id:number):any; + findMarker(params?:any):IDisplayBufferMarker; + findMarkers(params?:any):IDisplayBufferMarker[]; + translateToBufferMarkerParams(params?:any):any; + findFoldMarker(attributes:any):IMarker; + findFoldMarkers(attributes:any):IMarker[]; + getFoldMarkerAttributes(attributes?:any):any; + pauseMarkerObservers():any; + resumeMarkerObservers():any; + refreshMarkerScreenPositions():any; + destroy():any; + logLines(start:number, end:number):any[]; + handleTokenizedBufferChange(tokenizedBufferChange:any):any; + updateScreenLines(startBufferRow:any, endBufferRow:any, bufferDelta?:number, options?:any):any; + buildScreenLines(startBufferRow:any, endBufferRow:any):any; + findMaxLineLength(startScreenRow:any, endScreenRow:any, newScreenLines:any):any; + handleBufferMarkersUpdated():any; + handleBufferMarkerCreated(marker:any):any; + createFoldForMarker(maker:any):IFold; + foldForMarker(marker:any):any; } - interface ICursor { - // TBD + interface ICursorStatic { + new (arg:{editor:IEditor; marker:IDisplayBufferMarker; id: number;}):ICursor; + } + + interface ICursor /* extends Theorist.Model */ { + screenPosition:any; + bufferPosition:any; + goalColumn:any; + visible:boolean; + needsAutoscroll:boolean; + + editor:IEditor; + marker:IDisplayBufferMarker; + id: number; + + destroy():any; + changePosition(options:any, fn:Function):any; + getPixelRect():any; + setScreenPosition(screenPosition:any, options?:any):any; + getScreenPosition():TextBuffer.IPoint; + getScreenRange():TextBuffer.IRange; + setBufferPosition(bufferPosition:any, options?:any):any; + getBufferPosition():TextBuffer.IPoint; + autoscroll():any; + updateVisibility():any; + setVisible(visible:boolean):any; + isVisible():boolean; + wordRegExp(arg?:any):any; + isLastCursor():boolean; + isSurroundedByWhitespace():boolean; + isBetweenWordAndNonWord():boolean; + isInsideWord():boolean; + clearAutoscroll():void; + clearSelection():void; + getScreenRow():number; + getScreenColumn():number; + getBufferRow():number; + getBufferColumn():number; + getCurrentBufferLine():string; + moveUp(rowCount:number, arg?:any):any; + moveDown(rowCount:number, arg?:any):any; + moveLeft(arg?:any):any; + moveRight(arg?:any):any; + moveToTop():any; + moveToBottom():void; + moveToBeginningOfScreenLine():void; + moveToBeginningOfLine():void; + moveToFirstCharacterOfLine():void; + moveToEndOfScreenLine():void; + moveToEndOfLine():void; + moveToBeginningOfWord():void; + moveToEndOfWord():void; + moveToBeginningOfNextWord():void; + moveToPreviousWordBoundary():void; + moveToNextWordBoundary():void; + getBeginningOfCurrentWordBufferPosition(options?:any):TextBuffer.IPoint; + getPreviousWordBoundaryBufferPosition(options?:any):TextBuffer.IPoint; + getMoveNextWordBoundaryBufferPosition(options?:any):TextBuffer.IPoint; + getEndOfCurrentWordBufferPosition(options?:any):TextBuffer.IPoint; + getBeginningOfNextWordBufferPosition(options?:any):TextBuffer.IPoint; + getCurrentWordBufferRange(options?:any):TextBuffer.IPoint; + getCurrentLineBufferRange(options?:any):TextBuffer.IPoint; + getCurrentParagraphBufferRange():any; + getCurrentWordPrefix():string; + isAtBeginningOfLine():boolean; + getIndentLevel():number; + isAtEndOfLine():boolean; + getScopes():string[]; + hasPrecedingCharactersOnLine():boolean; } interface ILanguageMode { // TBD } - interface ISelection { - // TBD - } + interface ISelection /* extends Theorist.Model */ { + cursor:ICursor; + marker:IDisplayBufferMarker; + editor:IEditor; + initialScreenRange:any; + wordwise:boolean; + needsAutoscroll:boolean; + retainSelection:boolean; + subscriptionCounts:any; - interface ISubscription { - // TBD + destroy():any; + finalize():any; + clearAutoscroll():any; + isEmpty():boolean; + isReversed():boolean; + isSingleScreenLine():boolean; + getScreenRange():TextBuffer.IRange; + setScreenRange(screenRange:any, options:any):any; + getBufferRange():TextBuffer.IRange; + setBufferRange(bufferRange:any, options:any):any; + getBufferRowRange():number[]; + autoscroll():void; + getText():string; + clear():boolean; + selectWord():TextBuffer.IRange; + expandOverWord():any; + selectLine(row?:any):TextBuffer.IRange; + expandOverLine():boolean; + selectToScreenPosition(position:any):any; + selectToBufferPosition(position:any):any; + selectRight():boolean; + selectLeft():boolean; + selectUp(rowCount?:any):boolean; + selectDown(rowCount?:any):boolean; + selectToTop():any; + selectToBottom():any; + selectAll():any; + selectToBeginningOfLine():any; + selectToFirstCharacterOfLine():any; + selectToEndOfLine():any; + selectToBeginningOfWord():any; + selectToEndOfWord():any; + selectToBeginningOfNextWord():any; + selectToPreviousWordBoundary():any; + selectToNextWordBoundary():any; + addSelectionBelow():any; + getGoalBufferRange():any; + addSelectionAbove():any[]; + insertText(text:string, options?:any):any; + normalizeIndents(text:string, indentBasis:number):any; + indent(_arg?:any):any; + indentSelectedRows():TextBuffer.IRange[]; + setIndentationForLine(line:string, indentLevel:number):any; + backspace():any; + backspaceToBeginningOfWord():any; + backspaceToBeginningOfLine():any; + delete():any; + deleteToEndOfWord():any; + deleteSelectedText():any; + deleteLine():any; + joinLines():any; + outdentSelectedRows():any[]; + autoIndentSelectedRows():any; + toggleLineComments():any; + cutToEndOfLine(maintainClipboard:any):any; + cut(maintainClipboard:any):any; + copy(maintainClipboard:any):any; + fold():any; + modifySelection(fn:()=>any):any; + plantTail():any; + intersectsBufferRange(bufferRange:any):any; + intersectsWith(otherSelection:any):any; + merge(otherSelection:any, options:any):any; + compare(otherSelection:any):any; + getRegionRects():any[]; + screenRangeChanged():any; } interface IEditor { @@ -79,7 +504,7 @@ declare module AtomCore { deserializing:boolean; callDisplayBufferCreatedHook:boolean; registerEditor:boolean; - buffer:ITextBuffer; + buffer:TextBuffer.ITextBuffer; languageMode: ILanguageMode; cursors:ICursor[]; selections: ISelection[]; @@ -95,7 +520,7 @@ declare module AtomCore { lastOpened: number; subscriptionCounts: any; subscriptionsByObject: any; /* WeakMap */ - subscriptions: ISubscription[]; + subscriptions: Emissary.ISubscription[]; serializeParams():{id:number; softTabs:boolean; scrollTop:number; scrollLeft:number; displayBuffer:any;}; deserializeParams(params:any):any; @@ -108,214 +533,214 @@ declare module AtomCore { getLongTitle():string; setVisible(visible:boolean):void; setScrollTop(scrollTop:any):void; - getScrollTop():any; + getScrollTop():number; setScrollLeft(scrollLeft:any):void; - getScrollLeft():any; + getScrollLeft():number; setEditorWidthInChars(editorWidthInChars:any):void; - getSoftWrapColumn():any; + getSoftWrapColumn():number; getSoftTabs():boolean; setSoftTabs(softTabs:boolean):void; - getSoftWrap():any; + getSoftWrap():boolean; setSoftWrap(softWrap:any):void; - getTabText():any; - getTabLength():any; + getTabText():string; + getTabLength():number; setTabLength(tabLength:any):void; clipBufferPosition(bufferPosition:any):void; clipBufferRange(range:any):void; indentationForBufferRow(bufferRow:any):void; setIndentationForBufferRow(bufferRow:any, newLevel:any, _arg:any):void; indentLevelForLine(line:any):number; - buildIndentString(number:any):any; + buildIndentString(number:any):string; save():void; saveAs(filePath:any):void; - getPath():any; - getText():any; + getPath():string; + getText():string; setText(text:any):void; getTextInRange(range:any):any; - getLineCount():any; - getBuffer():any; - getUri():any; - isBufferRowBlank(bufferRow:any):void; + getLineCount():number; + getBuffer():TextBuffer.ITextBuffer; + getUri():string; + isBufferRowBlank(bufferRow:any):boolean; isBufferRowCommented(bufferRow:any):void; nextNonBlankBufferRow(bufferRow:any):void; - getEofBufferPosition():any; - getLastBufferRow():any; - bufferRangeForBufferRow(row:any, options:any):any; - lineForBufferRow(row:any):any; - lineLengthForBufferRow(row:any):any; + getEofBufferPosition():TextBuffer.IPoint; + getLastBufferRow():number; + bufferRangeForBufferRow(row:any, options:any):TextBuffer.IRange; + lineForBufferRow(row:number):string; + lineLengthForBufferRow(row:number):number; scan():any; scanInBufferRange():any; backwardsScanInBufferRange():any; - isModified():any; - shouldPromptToSave():any; - screenPositionForBufferPosition(bufferPosition:any, options:any):any; - bufferPositionForScreenPosition(screenPosition:any, options:any):any; - screenRangeForBufferRange(bufferRange:any):any; - bufferRangeForScreenRange(screenRange:any):any; - clipScreenPosition(screenPosition:any, options:any):any; - lineForScreenRow(row:any):any; - linesForScreenRows(start:any, end:any):any; - getScreenLineCount():any; - getMaxScreenLineLength():any; - getLastScreenRow():any; - bufferRowsForScreenRows(startRow:any, endRow:any):any; - bufferRowForScreenRow(row:any):any; - scopesForBufferPosition(bufferPosition:any):any; - bufferRangeForScopeAtCursor(selector:any):any; - tokenForBufferPosition(bufferPosition:any):any; - getCursorScopes():any; - insertText(text:any, options:any):any; - insertNewline():any; - insertNewlineBelow():any; + isModified():boolean; + shouldPromptToSave():boolean; + screenPositionForBufferPosition(bufferPosition:any, options?:any):TextBuffer.IPoint; + bufferPositionForScreenPosition(screenPosition:any, options?:any):TextBuffer.IPoint; + screenRangeForBufferRange(bufferRange:any):TextBuffer.IRange; + bufferRangeForScreenRange(screenRange:any):TextBuffer.IRange; + clipScreenPosition(screenPosition:any, options:any):TextBuffer.IRange; + lineForScreenRow(row:any):ITokenizedLine; + linesForScreenRows(start?:any, end?:any):ITokenizedLine[]; + getScreenLineCount():number; + getMaxScreenLineLength():number; + getLastScreenRow():number; + bufferRowsForScreenRows(startRow:any, endRow:any):any[]; + bufferRowForScreenRow(row:any):number; + scopesForBufferPosition(bufferPosition:any):string[]; + bufferRangeForScopeAtCursor(selector:string):any; + tokenForBufferPosition(bufferPosition:any):IToken; + getCursorScopes():string[]; + insertText(text:string, options?:any):TextBuffer.IRange[]; + insertNewline():TextBuffer.IRange[]; + insertNewlineBelow():TextBuffer.IRange[]; insertNewlineAbove():any; indent(options?:any):any; - backspace():any; - backspaceToBeginningOfWord():any; - backspaceToBeginningOfLine():any; - delete():any; - deleteToEndOfWord():any; - deleteLine():any; - indentSelectedRows():any; - outdentSelectedRows():any; - toggleLineCommentsInSelection():any; - autoIndentSelectedRows():any; + backspace():any[]; + backspaceToBeginningOfWord():any[]; + backspaceToBeginningOfLine():any[]; + delete():any[]; + deleteToEndOfWord():any[]; + deleteLine():TextBuffer.IRange[]; + indentSelectedRows():TextBuffer.IRange[][]; + outdentSelectedRows():TextBuffer.IRange[][]; + toggleLineCommentsInSelection():TextBuffer.IRange[]; + autoIndentSelectedRows():TextBuffer.IRange[][]; normalizeTabsInBufferRange(bufferRange:any):any; - cutToEndOfLine():any; - cutSelectedText():any; - copySelectedText():any; - pasteText(options?:any):any; - undo():any; - redo():any; + cutToEndOfLine():boolean[]; + cutSelectedText():boolean[]; + copySelectedText():boolean[]; + pasteText(options?:any):TextBuffer.IRange[]; + undo():any[]; + redo():any[]; foldCurrentRow():any; - unfoldCurrentRow():any; - foldSelectedLines():any; - foldAll():any; - unfoldAll():any; + unfoldCurrentRow():any[]; + foldSelectedLines():any[]; + foldAll():any[]; + unfoldAll():any[]; foldAllAtIndentLevel(level:any):any; foldBufferRow(bufferRow:any):any; unfoldBufferRow(bufferRow:any):any; - isFoldableAtBufferRow(bufferRow:any):any; - createFold(startRow:any, endRow:any):any; + isFoldableAtBufferRow(bufferRow:any):boolean; + createFold(startRow:any, endRow:any):IFold; destroyFoldWithId(id:any):any; destroyFoldsIntersectingBufferRange(bufferRange:any):any; toggleFoldAtBufferRow(bufferRow:any):any; - isFoldedAtCursorRow():any; - isFoldedAtBufferRow(bufferRow:any):any; - isFoldedAtScreenRow(screenRow:any):any; - largestFoldContainingBufferRow(bufferRow:any):any; + isFoldedAtCursorRow():boolean; + isFoldedAtBufferRow(bufferRow:any):boolean; + isFoldedAtScreenRow(screenRow:any):boolean; + largestFoldContainingBufferRow(bufferRow:any):boolean; largestFoldStartingAtScreenRow(screenRow:any):any; - outermostFoldsInBufferRowRange(startRow:any, endRow:any):any; - moveLineUp():any; - moveLineDown():any; - duplicateLines():any; - duplicateLine():any; - mutateSelectedText(fn:Function):any; - replaceSelectedText(options:any, fn:Function):any; - getMarker(id:any):any; - getMarkers():any; - findMarkers(properties:any):any; - markScreenRange():any; - markBufferRange():any; - markScreenPosition():any; - markBufferPosition():any; - destroyMarker():any; - getMarkerCount():any; - hasMultipleCursors():any; - getCursors():any; - getCursor():any; - addCursorAtScreenPosition(screenPosition:any):any; - addCursorAtBufferPosition(bufferPosition:any):any; - addCursor(marker:any):any; - removeCursor(cursor:any):any; - addSelection(marker:any, options:any):any; - addSelectionForBufferRange(bufferRange:any, options:any):any; + outermostFoldsInBufferRowRange(startRow:any, endRow:any):any[]; + moveLineUp():ISelection[]; + moveLineDown():ISelection[]; + duplicateLines():any[][]; + duplicateLine():any[][]; + mutateSelectedText(fn:(selection:ISelection)=>any):any; + replaceSelectedText(options:any, fn:(selection:string)=>any):any; + getMarker(id:number):IDisplayBufferMarker; + getMarkers():IDisplayBufferMarker[]; + findMarkers(...args:any[]):IDisplayBufferMarker[]; + markScreenRange(...args:any[]):IDisplayBufferMarker; + markBufferRange(...args:any[]):IDisplayBufferMarker; + markScreenPosition(...args:any[]):IDisplayBufferMarker; + markBufferPosition(...args:any[]):IDisplayBufferMarker; + destroyMarker(...args:any[]):boolean; + getMarkerCount():number; + hasMultipleCursors():boolean; + getCursors():ICursor[]; + getCursor():ICursor; + addCursorAtScreenPosition(screenPosition:any):ICursor; + addCursorAtBufferPosition(bufferPosition:any):ICursor; + addCursor(marker:any):ICursor; + removeCursor(cursor:any):ICursor[]; + addSelection(marker:any, options:any):ISelection; + addSelectionForBufferRange(bufferRange:any, options:any):ISelection; setSelectedBufferRange(bufferRange:any, options:any):any; setSelectedBufferRanges(bufferRanges:any, options:any):any; - removeSelection(selection:any):any; - clearSelections():any; - consolidateSelections():any; - getSelections():any; - getSelection(index:any):any; - getLastSelection():any; - getSelectionsOrderedByBufferPosition():any; - getLastSelectionInBuffer():any; + removeSelection(selection:ISelection):any; + clearSelections():boolean; + consolidateSelections():boolean; + getSelections():ISelection[]; + getSelection(index?:number):ISelection; + getLastSelection():ISelection; + getSelectionsOrderedByBufferPosition():ISelection[]; + getLastSelectionInBuffer():ISelection; selectionIntersectsBufferRange(bufferRange:any):any; - setCursorScreenPosition(position:any, options:any):any; - getCursorScreenPosition():any; - getCursorScreenRow():any; - setCursorBufferPosition(position:any, options:any):any; - getCursorBufferPosition():any; - getSelectedScreenRange():any; - getSelectedBufferRange():any; - getSelectedBufferRanges():any; - getSelectedText():any; - getTextInBufferRange(range:any):any; - setTextInBufferRange(range:any, text:any):any; - getCurrentParagraphBufferRange():any; - getWordUnderCursor(options:any):any; - moveCursorUp(lineCount:any):any; - moveCursorDown(lineCount:any):any; - moveCursorLeft():any; - moveCursorRight():any; - moveCursorToTop():any; - moveCursorToBottom():any; - moveCursorToBeginningOfScreenLine():any; - moveCursorToBeginningOfLine():any; - moveCursorToFirstCharacterOfLine():any; - moveCursorToEndOfScreenLine():any; - moveCursorToEndOfLine():any; - moveCursorToBeginningOfWord():any; - moveCursorToEndOfWord():any; - moveCursorToBeginningOfNextWord():any; - moveCursorToPreviousWordBoundary():any; - moveCursorToNextWordBoundary():any; - moveCursors(fn:Function):any; - selectToScreenPosition(position:any):any; - selectRight():any; - selectLeft():any; - selectUp(rowCount:any):any; - selectDown(rowCount:any):any; - selectToTop():any; - selectAll():any; - selectToBottom():any; - selectToBeginningOfLine():any; - selectToFirstCharacterOfLine():any; - selectToEndOfLine():any; - selectToPreviousWordBoundary():any; - selectToNextWordBoundary():any; - selectLine():any; - addSelectionBelow():any; - addSelectionAbove():any; - splitSelectionsIntoLines():any; - transpose():any; - upperCase():any; - lowerCase():any; - joinLines():any; - selectToBeginningOfWord():any; - selectToEndOfWord():any; - selectToBeginningOfNextWord():any; - selectWord():any; + setCursorScreenPosition(position:TextBuffer.IPoint, options?:any):any; + getCursorScreenPosition():TextBuffer.IPoint; + getCursorScreenRow():number; + setCursorBufferPosition(position:any, options?:any):any; + getCursorBufferPosition():TextBuffer.IPoint; + getSelectedScreenRange():TextBuffer.IRange; + getSelectedBufferRange():TextBuffer.IRange; + getSelectedBufferRanges():TextBuffer.IRange[]; + getSelectedText():string; + getTextInBufferRange(range:TextBuffer.IRange):string; + setTextInBufferRange(range:TextBuffer.IRange, text:string):any; + getCurrentParagraphBufferRange():TextBuffer.IRange; + getWordUnderCursor(options?:any):string; + moveCursorUp(lineCount?:number):void; + moveCursorDown(lineCount?:number):void; + moveCursorLeft():void; + moveCursorRight():void; + moveCursorToTop():void; + moveCursorToBottom():void; + moveCursorToBeginningOfScreenLine():void; + moveCursorToBeginningOfLine():void; + moveCursorToFirstCharacterOfLine():void; + moveCursorToEndOfScreenLine():void; + moveCursorToEndOfLine():void; + moveCursorToBeginningOfWord():void; + moveCursorToEndOfWord():void; + moveCursorToBeginningOfNextWord():void; + moveCursorToPreviousWordBoundary():void; + moveCursorToNextWordBoundary():void; + moveCursors(fn:(cursor:ICursor)=>any):any; + selectToScreenPosition(position:TextBuffer.IPoint):any; + selectRight():ISelection[]; + selectLeft():ISelection[]; + selectUp(rowCount?:number):ISelection[]; + selectDown(rowCount?:number):ISelection[]; + selectToTop():ISelection[]; + selectAll():ISelection[]; + selectToBottom():ISelection[]; + selectToBeginningOfLine():ISelection[]; + selectToFirstCharacterOfLine():ISelection[]; + selectToEndOfLine():ISelection[]; + selectToPreviousWordBoundary():ISelection[]; + selectToNextWordBoundary():ISelection[]; + selectLine():ISelection[]; + addSelectionBelow():ISelection[]; + addSelectionAbove():ISelection[]; + splitSelectionsIntoLines():any[]; + transpose():TextBuffer.IRange[]; + upperCase():boolean[]; + lowerCase():boolean[]; + joinLines():any[]; + selectToBeginningOfWord():ISelection[]; + selectToEndOfWord():ISelection[]; + selectToBeginningOfNextWord():ISelection[]; + selectWord():ISelection[]; selectMarker(marker:any):any; - mergeCursors():any; + mergeCursors():number[]; expandSelectionsForward():any; - expandSelectionsBackward(fn:Function):any; - finalizeSelections():any; + expandSelectionsBackward(fn:(selection:ISelection)=>any):ISelection[]; + finalizeSelections():boolean[]; mergeIntersectingSelections():any; - preserveCursorPositionOnBufferReload():any; + preserveCursorPositionOnBufferReload():Emissary.ISubscription; getGrammar(): IGrammar; setGrammar(grammer:IGrammar):void; reloadGrammar():any; - shouldAutoIndent():any; + shouldAutoIndent():boolean; transact(fn:Function):any; - beginTransaction():any; + beginTransaction():ITransaction; commitTransaction():any; - abortTransaction():any; - inspect():any; - logScreenLines(start:any, end:any):any; - handleGrammarChange():any; + abortTransaction():any[]; + inspect():string; + logScreenLines(start:number, end:number):any[]; + handleGrammarChange():void; handleMarkerCreated(marker:any):any; - getSelectionMarkerAttributes():any; - joinLine():any; + getSelectionMarkerAttributes():{type: string; editorId: number; invalidate: string; }; + // joinLine():any; // deprecated } interface IGrammar { @@ -399,8 +824,46 @@ declare module AtomCore { height:number; } - interface IProject { - // TBD + interface IProjectStatic { + pathForRepositoryUrl(repoUrl:string):string; + + new (arg?:{path:any; buffers:any[];}):IProject; + } + + interface IProject /* extends Theorist.Model */ { + // Serializable.includeInto(Project); + + path:string; + rootDirectory:PathWatcher.IDirectory; + + serializeParams():any; + deserializeParams(params:any):any; + destroyed():any; + destroyRepo():any; + destroyUnretainedBuffers():any; + getRepo():IGit; + getPath():string; + setPath(projectPath:string):any; + getRootDirectory():PathWatcher.IDirectory; + resolve(uri:string):string; + relativize(fullPath:string):string; + contains(pathToCheck:string):boolean; + open(filePath:string, options?:any):Q.Promise; + openSync(filePath:string, options?:any):IEditor; + getBuffers():TextBuffer.ITextBuffer; + isPathModified(filePath:string):boolean; + findBufferForPath(filePath:string):TextBuffer.ITextBuffer; + bufferForPathSync(filePath:string):TextBuffer.ITextBuffer; + bufferForPath(filePath:string):Q.Promise; + bufferForId(id:any):TextBuffer.ITextBuffer; + buildBufferSync(absoluteFilePath:string):TextBuffer.ITextBuffer; + buildBuffer(absoluteFilePath:string):Q.Promise; + addBuffer(buffer:TextBuffer.ITextBuffer, options?:any):any; + addBufferAtIndex(buffer:TextBuffer.ITextBuffer, index:number, options?:any):any; + scan(regex:any, options:any, iterator:any):Q.Promise; + replace(regex:any, replacementText:any, filePaths:any, iterator:any):Q.Promise; + buildEditorForBuffer(buffer:any, editorOptions:any):IEditor; + eachBuffer(...args:any[]):any; } interface IWorkspaceStatic { @@ -478,6 +941,21 @@ declare module AtomCore { // TBD } + interface IPackage { + mainModulePath: string; + mainModule: any; + enable(): void; + disable(): void; + isTheme(): boolean; + getType(): string; + getStylesheetType(): string; + load(): IPackage; + reset(): void; + activate(): Q.Promise; + activateNow(): void; + // TBD + } + interface IPackageManager extends Emissary.IEmitter { packageDirPaths:string[]; loadedPackages:any; @@ -494,7 +972,7 @@ declare module AtomCore { activate():void; registerPackageActivator(activator:any, types:any):void; activatePackages(packages:any):void; - activatePackage(name:string):void; + activatePackage(name:string):Q.Promise; deactivatePackages():void; deactivatePackage(name:string):void; getActivePackages():any; @@ -547,7 +1025,14 @@ declare module AtomCore { interface IAtomStatic extends ISerializationStatic { version: number; loadSettings: IAtomSettings; + + /* Load or create the Atom environment in the given mode */ + loadOrCreate(mode:'editor'):IAtom; + /* Load or create the Atom environment in the given mode */ + loadOrCreate(mode:'spec'):IAtom; + /* Load or create the Atom environment in the given mode */ loadOrCreate(mode:string):IAtom; + loadState(mode:any):void; getStatePath(mode:any):string; getConfigDirPath():string; @@ -560,6 +1045,8 @@ declare module AtomCore { new(state:IAtomState):IAtom; } + // https://atom.io/docs/api/v0.106.0/api/classes/Atom.html + /* Global Atom class : instance members */ interface IAtom { constructor:IAtomStatic; @@ -670,19 +1157,94 @@ declare module AtomCore { interface IGit { } - interface IPointStatic { - new(row:any, column:any):IPoint; - } - - interface IPoint { + interface ITokenizedBuffer { // TBD } - interface IRangeStatic { - new(pointA:IPoint, pointB:IPoint):IRange; + interface ITokenizedLine { + // TBD } - interface IRange { + interface IToken { + // TBD + } + + interface IFoldStatic { + new (displayBuffer:IDisplayBuffer, marker:IMarker):IFold; + // TBD + } + + interface IFold { + id:number; + displayBuffer:IDisplayBuffer; + marker:IMarker; + + // TBD + } + + interface IDisplayBufferMarkerStatic { + new (_arg:{bufferMarker:IMarker; displayBuffer: IDisplayBuffer}):IDisplayBufferMarker; + } + + interface IDisplayBufferMarker extends Emissary.IEmitter, Emissary.ISubscriber { + constructor:IDisplayBufferMarkerStatic; + + id: number; + + bufferMarkerSubscription:any; + oldHeadBufferPosition:TextBuffer.IPoint; + oldHeadScreenPosition:TextBuffer.IPoint; + oldTailBufferPosition:TextBuffer.IPoint; + oldTailScreenPosition:TextBuffer.IPoint; + wasValid:boolean; + + bufferMarker: IMarker; + displayBuffer: IDisplayBuffer; + globalPauseCount:number; + globalQueuedEvents:any; + + subscriptions:Emissary.ISubscription[]; + subscriptionsByObject:any; // WeakMap + + copy(attributes?:any /* maybe IMarker */):IDisplayBufferMarker; + getScreenRange():TextBuffer.IRange; + setScreenRange(screenRange:any, options:any):any; + getBufferRange():TextBuffer.IRange; + setBufferRange(bufferRange:any, options:any):any; + getPixelRange():any; + getHeadScreenPosition():TextBuffer.IPoint; + setHeadScreenPosition(screenPosition:any, options:any):any; + getHeadBufferPosition():TextBuffer.IPoint; + setHeadBufferPosition(bufferPosition:any):any; + getTailScreenPosition():TextBuffer.IPoint; + setTailScreenPosition(screenPosition:any, options:any):any; + getTailBufferPosition():TextBuffer.IPoint; + setTailBufferPosition(bufferPosition:any):any; + plantTail():boolean; + clearTail():boolean; + hasTail():boolean; + isReversed():boolean; + isValid():boolean; + isDestroyed():boolean; + getAttributes():any; + setAttributes(attributes:any):any; + matchesAttributes(attributes:any):any; + destroy():any; + isEqual(other:IDisplayBufferMarker):boolean; + compare(other:IDisplayBufferMarker):boolean; + inspect():string; + destroyed():any; + notifyObservers(_arg:any):any; + } + + interface ITransaction { + // TBD + } + + interface IMarker extends Emissary.IEmitter { + // Serializable.includeInto(Editor); + // Delegator.includeInto(Editor); + // TBD } @@ -701,14 +1263,14 @@ declare module "atom" { import spacePen = require("space-pen"); var $:typeof spacePen.$; + var $$:typeof spacePen.$$; var $$$:typeof spacePen.$$$; var BufferedNodeProcess:AtomCore.IBufferedNodeProcessStatic; var BufferedProcess:AtomCore.IBufferedProcessStatic; - var EditorView:any; var Git:AtomCore.IGitStatic; - var Point:AtomCore.IPointStatic; - var Range:AtomCore.IRangeStatic; + var Point:TextBuffer.IPointStatic; + var Range:TextBuffer.IRangeStatic; class View extends spacePen.View implements Emissary.ISubscriber { // Subscriber.includeInto(spacePen.View); @@ -725,12 +1287,375 @@ declare module "atom" { unsubscribe(object?:any):any; } + class EditorView extends View { + static characterWidthCache:any; + static configDefaults:any; + static nextEditorId:number; + + static content(params:any):void; + + static classes(_arg?:{mini?:any}):string; + + vScrollMargin:number; + hScrollMargin:number; + lineHeight:any; + charWidth:any; + charHeight:any; + cursorViews:any[]; + selectionViews:any[]; + lineCache:any[]; + isFocused:any; + editor:AtomCore.IEditor; + attached:any; + lineOverdraw:number; + pendingChanges:any[]; + newCursors:any[]; + newSelections:any[]; + redrawOnReattach:any; + bottomPaddingInLines:number; + active:boolean; + + id:number; + + gutter:AtomCore.IGutterView; + overlayer:JQuery; + scrollView:JQuery; + renderedLines:JQuery; + underlayer:JQuery; + hiddenInput:JQuery; + verticalScrollbar:JQuery; + verticalScrollbarContent:JQuery; + + constructor(editor:AtomCore.IEditor); + + initialize(editorOrOptions:AtomCore.IEditor):void; // return type are same as editor method. + initialize(editorOrOptions?:{editor: AtomCore.IEditor; mini:any; placeholderText:any}):void; + + initialize(editorOrOptions:{}):void; // compatible for spacePen.View + + bindKeys():void; + + getEditor():AtomCore.IEditor; + + getText():string; + + setText(text:string):void; + + insertText(text:string, options?:any):TextBuffer.IRange[]; + + setHeightInLines(heightInLines:number):number; + + setWidthInChars(widthInChars:number):number; + + pageDown():void; + + pageUp():void; + + getPageRows():number; + + setShowInvisibles(showInvisibles:boolean):void; + + setInvisibles(invisibles:{ eol:string; space: string; tab: string; cr: string; }):void; + + setShowIndentGuide(showIndentGuide:boolean):void; + + setPlaceholderText(placeholderText:string):void; + + getPlaceholderText():string; + + checkoutHead():boolean; + + configure():Emissary.ISubscription; + + handleEvents():void; + + handleInputEvents():void; + + bringHiddenInputIntoView():JQuery; + + selectOnMousemoveUntilMouseup():any; + + afterAttach(onDom:any):any; + + edit(editor:AtomCore.IEditor):any; + + getModel():AtomCore.IEditor; + + setModel(editor:AtomCore.IEditor):any; + + showBufferConflictAlert(editor:AtomCore.IEditor):any; + + scrollTop(scrollTop:number, options?:any):any; + + scrollBottom(scrollBottom?:number):any; + + scrollLeft(scrollLeft?:number):number; + + scrollRight(scrollRight?:number):any; + + scrollToBottom():any; + + scrollToCursorPosition():any; + + scrollToBufferPosition(bufferPosition:any, options:any):any; + + scrollToScreenPosition(screenPosition:any, options:any):any; + + scrollToPixelPosition(pixelPosition:any, options:any):any; + + highlightFoldsContainingBufferRange(bufferRange:any):any; + + saveScrollPositionForEditor():any; + + toggleSoftTabs():any; + + toggleSoftWrap():any; + + calculateWidthInChars():number; + + calculateHeightInLines():number; + + getScrollbarWidth():number; + + setSoftWrap(softWrap:boolean):any; + + setFontSize(fontSize:number):any; + + getFontSize():number; + + setFontFamily(fontFamily?:string):any; + + getFontFamily():string; + + setLineHeight(lineHeight:number):any; + + redraw():any; + + splitLeft():any; + + splitRight():any; + + splitUp():any; + + splitDown():any; + + getPane():any; // return type are PaneView + + remove(selector:any, keepData:any):any; + + beforeRemove():any; + + getCursorView(index?:number):any; // return type are CursorView + + getCursorViews():any[]; // return type are CursorView[] + + addCursorView(cursor:any, options:any):any; // return type are CursorView + + removeCursorView(cursorView:any):any; + + getSelectionView(index?:number):any; // return type are SelectionView + + getSelectionViews():any[]; // return type are SelectionView[] + + addSelectionView(selection:any):any; + + removeSelectionView(selectionView:any):any; + + removeAllCursorAndSelectionViews():any[]; + + appendToLinesView(view:any):any; + + scrollVertically(pixelPosition:any, _arg:any):any; + + scrollHorizontally(pixelPosition:any):any; + + calculateDimensions():number; + + recalculateDimensions():any; + + updateLayerDimensions():any; + + isHidden():boolean; + + clearRenderedLines():void; + + resetDisplay():any; + + requestDisplayUpdate():any; + + updateDisplay(options?:any):any; + + updateCursorViews():any; + + shouldUpdateCursor(cursorView:any):any; + + updateSelectionViews():any[]; + + shouldUpdateSelection(selectionView:any):any; + + syncCursorAnimations():any[]; + + autoscroll(suppressAutoscroll?:any):any[]; + + updatePlaceholderText():any; + + updateRenderedLines(scrollViewWidth:any):any; + + computeSurroundingEmptyLineChanges(change:any):any; + + computeIntactRanges(renderFrom:any, renderTo:any):any; + + truncateIntactRanges(intactRanges:any, renderFrom:any, renderTo:any):any; + + clearDirtyRanges(intactRanges:any):any; + + clearLine(lineElement:any):any; + + fillDirtyRanges(intactRanges:any, renderFrom:any, renderTo:any):any; + + updatePaddingOfRenderedLines():any; + + getFirstVisibleScreenRow():number; + + getLastVisibleScreenRow():number; + + isScreenRowVisible():boolean; + + handleScreenLinesChange(change:any):any; + + buildLineElementForScreenRow(screenRow:any):any; + + buildLineElementsForScreenRows(startRow:any, endRow:any):any; + + htmlForScreenRows(startRow:any, endRow:any):any; + + htmlForScreenLine(screenLine:any, screenRow:any):any; + + buildIndentation(screenRow:any, editor:any):any; + + buildHtmlEndOfLineInvisibles(screenLine:any):any; + + getEndOfLineInvisibles(screenLine:any):any; + + lineElementForScreenRow(screenRow:any):any; + + toggleLineCommentsInSelection():any; + + pixelPositionForBufferPosition(position:any):any; + + pixelPositionForScreenPosition(position:any):any; + + positionLeftForLineAndColumn(lineElement:any, screenRow:any, screenColumn:any):any; + + measureToColumn(lineElement:any, tokenizedLine:any, screenColumn:any):any; + + getCharacterWidthCache(scopes:any, char:any):any; + + setCharacterWidthCache(scopes:any, char:any, val:any):any; + + clearCharacterWidthCache():any; + + pixelOffsetForScreenPosition(position:any):any; + + screenPositionFromMouseEvent(e:any):any; + + highlightCursorLine():any; + + copyPathToClipboard():any; + + buildLineHtml(_arg:any):any; + + updateScopeStack(line:any, scopeStack:any, desiredScopes:any):any; + + pushScope(line:any, scopeStack:any, scope:any):any; + + popScope(line:any, scopeStack:any):any; + + buildEmptyLineHtml(showIndentGuide:any, eolInvisibles:any, htmlEolInvisibles:any, indentation:any, editor:any, mini:any):any; + + replaceSelectedText(replaceFn:(str:string)=>string):any; + + consolidateSelections(e:any):any; + + logCursorScope():any; + + logScreenLines(start:any, end:any):any; + + logRenderedLines():any; + } + class ScrollView extends View { // TBD } - var SelectListView:any; + interface ISelectListItem { + /** e.g. application:about */ + eventName:string; + /** e.g. Application: About */ + eventDescription:string; + } + + class SelectListView extends View { + static content():any; + + maxItems:number; + scheduleTimeout:any; + inputThrottle:number; + cancelling:boolean; + items:any[]; + list:JQuery; + + previouslyFocusedElement:JQuery; + + initialize():any; + + schedulePopulateList():number; + + setItems(items:any[]):any; + + setError(message?:string):any; + + setLoading(message?:string):any; + + getFilterQuery():string; + + populateList():any; + + getEmptyMessage(itemCount?:any, filteredItemCount?:any):string; + + setMaxItems(maxItems:number):void; + + selectPreviousItemView():any; + + selectNextItemView():any; + + selectItemView(view:any):any; + + scrollToItemView(view:any):any; + + getSelectedItemView():any; + + getSelectedItem():any; + + confirmSelection():any; + + viewForItem(item:any):JQuery; // You must override this method! + confirmed(item:any):any; // You must override this method! + getFilterKey():any; + + focusFilterEditor():any; + + storeFocusedElement():any; + + restoreFocus():any; + + cancelled():any; + + cancel():any; + } + + var WorkspaceView:AtomCore.IWorkspaceViewStatic; + var Task:AtomCore.ITaskStatic; var Workspace:AtomCore.IWorkspaceStatic; - var WorkspaceView:any; // WorkspaceView extends View } diff --git a/atpl/atpl-tests.ts b/atpl/atpl-tests.ts new file mode 100644 index 0000000000..f1751d9015 --- /dev/null +++ b/atpl/atpl-tests.ts @@ -0,0 +1,25 @@ +/// + +import atpl = require('atpl'); + +var bool: boolean; +var str: string; +var err: Error; +var items: any; +var options: Object; +var callback: Function; + +atpl.compile(str, options); +atpl.__express(str, options, callback); + +atpl.registerExtension(items); +atpl.registerTags(items); +atpl.registerFunctions(items); +atpl.registerFilters(items); +atpl.registerTests(items); + +atpl.registerTags(null); +atpl.renderFile(str, str, options, bool, (e, res?) => { + err = err; + str = res; +}); diff --git a/atpl/atpl.d.ts b/atpl/atpl.d.ts new file mode 100644 index 0000000000..7eae246a80 --- /dev/null +++ b/atpl/atpl.d.ts @@ -0,0 +1,20 @@ +// Type definitions for atpl +// Project: https://github.com/soywiz/atpl.js +// Definitions by: Carlos Ballesteros Velasco +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/atpl.d.ts + +declare module "atpl" { + export function compile(templateString: string, options: any): (context:any) => string; + export function __express(filename: string, options: any, callback: Function): any; + + export function registerExtension(items: any): void; + export function registerTags(items: any): void; + export function registerFunctions(items: any): void; + export function registerFilters(items: any): void; + export function registerTests(items: any): void; + + export function renderFileSync(viewsPath: string, filename: string, parameters: any, cache: boolean ): string; + export function renderFile(viewsPath: string, filename: string, parameters: any, cache: boolean, done: (err: Error, result?: string) => void): void; +} diff --git a/auth0.widget/auth0.widget-tests.ts b/auth0.widget/auth0.widget-tests.ts new file mode 100644 index 0000000000..012e9b9769 --- /dev/null +++ b/auth0.widget/auth0.widget-tests.ts @@ -0,0 +1,18 @@ +/// +/// + +var widget: Auth0WidgetStatic = new Auth0Widget({ + domain: 'mine.auth0.com', + clientID: 'dsa7d77dsa7d7', + callbackURL: 'http://my-app.com/callback', + callbackOnLocationHash: true +}); + +widget.signin({ + connections: ['facebook', 'google-oauth2', 'twitter', 'Username-Password-Authentication'], + icon: 'https://contoso.com/logo-32.png', + showIcon: true +}, + () => { + // The Auth0 Widget is now loaded. + }); diff --git a/auth0.widget/auth0.widget.d.ts b/auth0.widget/auth0.widget.d.ts new file mode 100644 index 0000000000..d45c3a2121 --- /dev/null +++ b/auth0.widget/auth0.widget.d.ts @@ -0,0 +1,48 @@ +// Type definitions for Auth0Widget.js +// Project: http://auth0.com +// Definitions by: Robert McLaws +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + + +interface Auth0WidgetStatic { + new(params: Auth0Constructor): Auth0WidgetStatic; + + getClient(): Auth0Static; + getProfile(token: string, callback: Function): Auth0UserProfile; + parseHash(hash: string): Auth0DecodedHash; + reset(options: Auth0Options, callback?: Function): Auth0WidgetStatic; + signin(options: Auth0Options, widgetLoadedCallback?: Function, popupCallback?: Function): Auth0WidgetStatic; + signup(options: Auth0Options, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): Auth0WidgetStatic; + } + +interface Auth0Constructor extends Auth0ClientOptions { + assetsUrl?: string; + cdn?: string; + dict?: any; + } + +interface Auth0Options { + access_token?: string; + connections?: string[]; + container?: string; + enableReturnUserExperience?: boolean; + extraParameters?: any; + icon?: string; + protocol?: string; + request_id?: string; + scope?: string; + showIcon?: boolean; + showForgot?: boolean; + showSignup?: boolean; + state?: any; + userPwdConnectionName?: string; + username_style?: string; +} + +declare var Auth0Widget: Auth0WidgetStatic; + +declare module "Auth0Widget" { + export = Auth0Widget +} diff --git a/auth0/auth0-tests.ts b/auth0/auth0-tests.ts new file mode 100644 index 0000000000..9cd903b306 --- /dev/null +++ b/auth0/auth0-tests.ts @@ -0,0 +1,23 @@ +/// + +var auth0 = new Auth0({ + domain: 'mine.auth0.com', + clientID: 'dsa7d77dsa7d7', + callbackURL: 'http://my-app.com/callback', + callbackOnLocationHash: true +}); + +auth0.login({ + connection: 'google-oauth2', + popup: true, + popupOptions: { + width: 450, + height: 800 + } +}, (err, profile, idToken, accessToken, state) => { + if (err) { + alert("something went wrong: " + err.message); + return; + } + alert('hello ' + profile.name); + }); diff --git a/auth0/auth0.d.ts b/auth0/auth0.d.ts new file mode 100644 index 0000000000..5d3149ead4 --- /dev/null +++ b/auth0/auth0.d.ts @@ -0,0 +1,133 @@ +// Type definitions for Auth0.js +// Project: http://auth0.com +// Definitions by: Robert McLaws +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** Extensions to the browser Window object. */ +interface Window { + /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ + token: string; +} + +interface Location { + origin: string; +} + +/** This is the interface for the main Auth0 client. */ +interface Auth0Static { + + new(options: Auth0ClientOptions): Auth0Static; + changePassword(options: any, callback?: Function): void; + decodeJwt(jwt: string): any; + login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; + loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + logout(query: string): void; + getConnections(callback?: Function): void; + getDelegationToken(targetClientId: string, id_token: string, options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getProfile(id_token: string, callback?: Function): Auth0UserProfile; + getSSOData(withActiveDirectories: any, callback?: Function): void; + parseHash(hash: string): Auth0DecodedHash; + signup(options: Auth0SignupOptions, callback: Function): void; + validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; +} + +/** Represents constructor options for the Auth0 client. */ +interface Auth0ClientOptions { + clientID: string; + callbackURL: string; + callbackOnLoactionHash?: boolean; + domain: string; + forceJSONP?: boolean; +} + +/** Represents a normalized UserProfile. */ +interface Auth0UserProfile { + email: string; + family_name: string; + gender: string; + given_name: string; + locale: string; + name: string; + nickname: string; + picture: string; + user_id: string; + /** Represents one or more Identities that may be associated with the User. */ + identities: Auth0Identity[]; +} + +/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ +interface MicrosoftUserProfile extends Auth0UserProfile { + emails: string[]; +} + +/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ +interface Office365UserProfile extends Auth0UserProfile { + tenantid: string; + upn: string; +} + +/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ +interface AdfsUserProfile extends Auth0UserProfile { + issuer: string; +} + +/** Represents multiple identities assigned to a user. */ +interface Auth0Identity { + access_token: string; + connection: string; + isSocial: boolean; + provider: string; + user_id: string; +} + +interface Auth0DecodedHash { + access_token: string; + id_token: string; + profile: Auth0UserProfile; + state: any; +} + +interface Auth0PopupOptions { + width: number; + height: number; +} + +interface Auth0LoginOptions { + auto_login?: boolean; + connection?: string; + email?: string; + username?: string; + password?: string; + popup?: boolean; + popupOptions?: Auth0PopupOptions; +} + +interface Auth0SignupOptions extends Auth0LoginOptions { + auto_login: boolean; +} + +interface Auth0Error { + code: any; + details: any; + name: string; + message: string; + status: any; +} + +/** Represents the response from an API Token Delegation request. */ +interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + expires_in: string; + /** The JWT for delegated access. */ + id_token: string; + /** The type of token being returned. Possible values: "Bearer" */ + token_type: string; +} + +declare var Auth0: Auth0Static; + +declare module "Auth0" { + export = Auth0 +} diff --git a/aws-sdk/aws-sdk-tests.ts b/aws-sdk/aws-sdk-tests.ts new file mode 100644 index 0000000000..8a3464a6df --- /dev/null +++ b/aws-sdk/aws-sdk-tests.ts @@ -0,0 +1,13 @@ +/// + +import awsSdk = require('aws-sdk'); + +var str: string; + +var creds: awsSdk.Credentials; + +creds = new awsSdk.Credentials(str, str); +creds = new awsSdk.Credentials(str, str, str); +str = creds.accessKeyId; + +// more diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts new file mode 100644 index 0000000000..3ae6778b5d --- /dev/null +++ b/aws-sdk/aws-sdk.d.ts @@ -0,0 +1,909 @@ +// Type definitions for aws-sdk +// Project: https://github.com/aws/aws-sdk-js +// Definitions by: midknight41 +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/aws-sdk.d.ts + +/// + +declare module "aws-sdk" { + + export var config: ClientConfig; + + export function Config(json: any): void; + + export class Credentials { + constructor(accessKeyId: string, secretAccessKey: string, sessionToken?: string); + accessKeyId: string; + } + + export interface ClientConfig { + credentials: Credentials; + region: string; + } + + export class SQS { + constructor(options?: any); + public client: Sqs.Client; + } + + export class SES { + constructor(options?: any); + public client: Ses.Client; + } + + export class SNS { + constructor(options?: any); + public client: Sns.Client; + } + + export class SimpleWorkflow { + constructor(options?: any); + public client: Swf.Client; + } + + export class S3 { + constructor(options?: any); + public client: s3.Client; + } + + export module Sqs { + + export interface Client { + config: ClientConfig; + + sendMessage(params: SendMessageRequest, callback: (err: any, data: SendMessageResult) => void): void; + sendMessageBatch(params: SendMessageBatchRequest, callback: (err: any, data: SendMessageBatchResult) => void): void; + receiveMessage(params: ReceiveMessageRequest, callback: (err: any, data: ReceiveMessageResult) => void): void; + deleteMessage(params: DeleteMessageRequest, callback: (err: any, data: any) => void): void; + deleteMessageBatch(params: DeleteMessageBatchRequest, callback: (err: any, data: DeleteMessageBatchResult) => void): void; + createQueue(params: CreateQueueRequest, callback: (err: any, data: CreateQueueResult) => void): void; + deleteQueue(params: DeleteQueueRequest, callback: (err: any, data: any) => void): void; + } + + export interface SendMessageRequest { + QueueUrl?: string; + MessageBody?: string; + DelaySeconds?: number; + } + + export interface ReceiveMessageRequest { + QueueUrl?: string; + MaxNumberOfMessages?: number; + VisibilityTimeout?: number; + AttributeNames?: string[]; + } + + export interface DeleteMessageBatchRequest { + QueueUrl?: string; + Entries?: DeleteMessageBatchRequestEntry[]; + } + + export interface DeleteMessageBatchRequestEntry { + Id: string; + ReceiptHandle: string; + } + + export interface DeleteMessageRequest { + QueueUrl?: string; + ReceiptHandle?: string; + } + + export class Attribute { + Name: string; + Value: string; + } + + export interface SendMessageBatchRequest { + QueueUrl?: string; + Entries?: SendMessageBatchRequestEntry[]; + } + + export class SendMessageBatchRequestEntry { + Id: string; + MessageBody: string; + DelaySeconds: number; + } + + export interface CreateQueueRequest { + QueueName?: string; + DefaultVisibilityTimeout?: number; + DelaySeconds?: number; + Attributes?: Attribute[]; + } + + export interface DeleteQueueRequest { + QueueUrl?: string; + } + + export class SendMessageResult { + MessageId: string; + MD5OfMessageBody: string; + } + + export class ReceiveMessageResult { + Messages: Message[]; + } + + export class Message { + MessageId: string; + ReceiptHandle: string; + MD5OfBody: string; + Body: string; + Attributes: Attribute[]; + } + + export class DeleteMessageBatchResult { + Successful: DeleteMessageBatchResultEntry[]; + Failed: BatchResultErrorEntry[]; + } + + export class DeleteMessageBatchResultEntry { + Id: string; + } + + export class BatchResultErrorEntry { + Id: string; + Code: string; + Message: string; + SenderFault: string; + } + + export class SendMessageBatchResult { + Successful: SendMessageBatchResultEntry[]; + Failed: BatchResultErrorEntry[]; + } + + export class SendMessageBatchResultEntry { + Id: string; + MessageId: string; + MD5OfMessageBody: string; + } + + export class CreateQueueResult { + QueueUrl: string; + } + + } + + export module Ses { + + export interface Client { + config: ClientConfig; + + sendEmail(params: any, callback: (err: any, data: SendEmailResult) => void): void; + } + + export interface SendEmailRequest { + Source: string; + Destination: Destination; + Message: Message; + ReplyToAddresses: string[]; + ReturnPath: string; + } + + export class Destination { + ToAddresses: string[]; + CcAddresses: string[]; + BccAddresses: string[]; + } + + export class Message { + Subject: Content; + Body: Body; + } + + export class Content { + Data: string; + Charset: string; + } + + export class Body { + Text: Content; + Html: Content; + } + + export class SendEmailResult { + MessageId: string; + } + + } + + export module Swf { + + export class Client { + //constructor(options?: any); + public config: ClientConfig; + + countClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + countOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + countPendingActivityTasks(params: any, callback: (err: any, data: any) => void): void; + countPendingDecisionTasks(params: any, callback: (err: any, data: any) => void): void; + deprecateActivityType(params: any, callback: (err: any, data: any) => void): void; + deprecateDomain(params: any, callback: (err: any, data: any) => void): void; + deprecateWorkflowType(params: any, callback: (err: any, data: any) => void): void; + describeActivityType(params: any, callback: (err: any, data: any) => void): void; + describeDomain(params: any, callback: (err: any, data: any) => void): void; + describeWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + describeWorkflowType(params: any, callback: (err: any, data: any) => void): void; + getWorkflowExecutionHistory(params: any, callback: (err: any, data: any) => void): void; + listActivityTypes(params: any, callback: (err: any, data: any) => void): void; + listClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + listDomains(params: any, callback: (err: any, data: any) => void): void; + listOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + listWorkflowTypes(params: any, callback: (err: any, data: any) => void): void; + pollForActivityTask(params: any, callback: (err: any, data: ActivityTask) => void): void; + pollForDecisionTask(params: any, callback: (err: any, data: DecisionTask) => void): void; + recordActivityTaskHeartbeat(params: any, callback: (err: any, data: any) => void): void; + registerActivityType(params: any, callback: (err: any, data: any) => void): void; + registerDomain(params: any, callback: (err: any, data: any) => void): void; + registerWorkflowType(params: any, callback: (err: any, data: any) => void): void; + requestCancelWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + respondActivityTaskCanceled(params: RespondActivityTaskCanceledRequest, callback: (err: any, data: any) => void): void; + respondActivityTaskCompleted(params: RespondActivityTaskCompletedRequest, callback: (err: any, data: any) => void): void; + respondActivityTaskFailed(params: RespondActivityTaskFailedRequest, callback: (err: any, data: any) => void): void; + respondDecisionTaskCompleted(params: RespondDecisionTaskCompletedRequest, callback: (err: any, data: any) => void): void; + signalWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + startWorkflowExecution(params: any, callback: (err: any, data: StartWorkflowExecutionResult) => void): void; + terminateWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + } + + export interface PollForActivityTaskRequest { + domain?: string; + taskList?: TaskList; + identity?: string; + } + + export interface TaskList { + name?: string; + } + + export interface PollForDecisionTaskRequest { + domain?: string; + taskList?: TaskList; + identity?: string; + nextPageToken?: string; + maximumPageSize?: number; + reverseOrder?: Boolean; + } + + export interface StartWorkflowExecutionRequest { + domain?: string; + workflowId?: string; + workflowType?: WorkflowType; + taskList?: TaskList; + input?: string; + executionStartToCloseTimeout?: string; + tagList?: string[]; + taskStartToCloseTimeout?: string; + childPolicy?: string; + } + + export interface WorkflowType { + name?: string; + version?: string; + } + + export interface RespondDecisionTaskCompletedRequest { + taskToken?: string; + decisions?: Decision[]; + executionContext?: string; + } + + export interface Decision { + decisionType?: string; + scheduleActivityTaskDecisionAttributes?: ScheduleActivityTaskDecisionAttributes; + requestCancelActivityTaskDecisionAttributes?: RequestCancelActivityTaskDecisionAttributes; + completeWorkflowExecutionDecisionAttributes?: CompleteWorkflowExecutionDecisionAttributes; + failWorkflowExecutionDecisionAttributes?: FailWorkflowExecutionDecisionAttributes; + cancelWorkflowExecutionDecisionAttributes?: CancelWorkflowExecutionDecisionAttributes; + continueAsNewWorkflowExecutionDecisionAttributes?: ContinueAsNewWorkflowExecutionDecisionAttributes; + recordMarkerDecisionAttributes?: RecordMarkerDecisionAttributes; + startTimerDecisionAttributes?: StartTimerDecisionAttributes; + cancelTimerDecisionAttributes?: CancelTimerDecisionAttributes; + signalExternalWorkflowExecutionDecisionAttributes?: SignalExternalWorkflowExecutionDecisionAttributes; + requestCancelExternalWorkflowExecutionDecisionAttributes?: RequestCancelExternalWorkflowExecutionDecisionAttributes; + startChildWorkflowExecutionDecisionAttributes?: StartChildWorkflowExecutionDecisionAttributes; + } + + export interface ScheduleActivityTaskDecisionAttributes { + activityType?: ActivityType; + activityId?: string; + control?: string; + input?: string; + scheduleToCloseTimeout?: string; + taskList?: TaskList; + scheduleToStartTimeout?: string; + startToCloseTimeout?: string; + heartbeatTimeout?: string; + } + + export interface ActivityType { + name?: string; + version?: string; + } + + export interface RequestCancelActivityTaskDecisionAttributes { + activityId?: string; + } + + export interface CompleteWorkflowExecutionDecisionAttributes { + result?: string; + } + + export interface FailWorkflowExecutionDecisionAttributes { + reason?: string; + details?: string; + } + + export interface CancelWorkflowExecutionDecisionAttributes { + details?: string; + } + + export interface ContinueAsNewWorkflowExecutionDecisionAttributes { + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + workflowTypeVersion?: string; + } + + export interface RecordMarkerDecisionAttributes { + markerName?: string; + details?: string; + } + + export interface StartTimerDecisionAttributes { + timerId?: string; + control?: string; + startToFireTimeout?: string; + } + + export interface CancelTimerDecisionAttributes { + timerId?: string; + } + + export interface SignalExternalWorkflowExecutionDecisionAttributes { + workflowId?: string; + runId?: string; + signalName?: string; + input?: string; + control?: string; + } + + export interface RequestCancelExternalWorkflowExecutionDecisionAttributes { + workflowId?: string; + runId?: string; + control?: string; + } + + export interface StartChildWorkflowExecutionDecisionAttributes { + workflowType?: WorkflowType; + workflowId?: string; + control?: string; + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + } + + export interface RespondActivityTaskCompletedRequest { + taskToken?: string; + result?: string; + } + + export interface RespondActivityTaskFailedRequest { + taskToken?: string; + reason?: string; + details?: string; + } + + export interface RespondActivityTaskCanceledRequest { + taskToken?: string; + details?: string; + } + + export interface DecisionTask { + taskToken?: string; + startedEventId?: number; + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + events?: HistoryEvent[]; + nextPageToken?: string; + previousStartedEventId?: number; + } + + export interface WorkflowExecution { + workflowId?: string; + runId?: string; + } + + export interface HistoryEvent { + eventTimestamp?: any; + eventType?: string; + eventId?: number; + workflowExecutionStartedEventAttributes?: WorkflowExecutionStartedEventAttributes; + workflowExecutionCompletedEventAttributes?: WorkflowExecutionCompletedEventAttributes; + completeWorkflowExecutionFailedEventAttributes?: CompleteWorkflowExecutionFailedEventAttributes; + workflowExecutionFailedEventAttributes?: WorkflowExecutionFailedEventAttributes; + failWorkflowExecutionFailedEventAttributes?: FailWorkflowExecutionFailedEventAttributes; + workflowExecutionTimedOutEventAttributes?: WorkflowExecutionTimedOutEventAttributes; + workflowExecutionCanceledEventAttributes?: WorkflowExecutionCanceledEventAttributes; + cancelWorkflowExecutionFailedEventAttributes?: CancelWorkflowExecutionFailedEventAttributes; + workflowExecutionContinuedAsNewEventAttributes?: WorkflowExecutionContinuedAsNewEventAttributes; + continueAsNewWorkflowExecutionFailedEventAttributes?: ContinueAsNewWorkflowExecutionFailedEventAttributes; + workflowExecutionTerminatedEventAttributes?: WorkflowExecutionTerminatedEventAttributes; + workflowExecutionCancelRequestedEventAttributes?: WorkflowExecutionCancelRequestedEventAttributes; + decisionTaskScheduledEventAttributes?: DecisionTaskScheduledEventAttributes; + decisionTaskStartedEventAttributes?: DecisionTaskStartedEventAttributes; + decisionTaskCompletedEventAttributes?: DecisionTaskCompletedEventAttributes; + decisionTaskTimedOutEventAttributes?: DecisionTaskTimedOutEventAttributes; + activityTaskScheduledEventAttributes?: ActivityTaskScheduledEventAttributes; + activityTaskStartedEventAttributes?: ActivityTaskStartedEventAttributes; + activityTaskCompletedEventAttributes?: ActivityTaskCompletedEventAttributes; + activityTaskFailedEventAttributes?: ActivityTaskFailedEventAttributes; + activityTaskTimedOutEventAttributes?: ActivityTaskTimedOutEventAttributes; + activityTaskCanceledEventAttributes?: ActivityTaskCanceledEventAttributes; + activityTaskCancelRequestedEventAttributes?: ActivityTaskCancelRequestedEventAttributes; + workflowExecutionSignaledEventAttributes?: WorkflowExecutionSignaledEventAttributes; + markerRecordedEventAttributes?: MarkerRecordedEventAttributes; + timerStartedEventAttributes?: TimerStartedEventAttributes; + timerFiredEventAttributes?: TimerFiredEventAttributes; + timerCanceledEventAttributes?: TimerCanceledEventAttributes; + startChildWorkflowExecutionInitiatedEventAttributes?: StartChildWorkflowExecutionInitiatedEventAttributes; + childWorkflowExecutionStartedEventAttributes?: ChildWorkflowExecutionStartedEventAttributes; + childWorkflowExecutionCompletedEventAttributes?: ChildWorkflowExecutionCompletedEventAttributes; + childWorkflowExecutionFailedEventAttributes?: ChildWorkflowExecutionFailedEventAttributes; + childWorkflowExecutionTimedOutEventAttributes?: ChildWorkflowExecutionTimedOutEventAttributes; + childWorkflowExecutionCanceledEventAttributes?: ChildWorkflowExecutionCanceledEventAttributes; + childWorkflowExecutionTerminatedEventAttributes?: ChildWorkflowExecutionTerminatedEventAttributes; + signalExternalWorkflowExecutionInitiatedEventAttributes?: SignalExternalWorkflowExecutionInitiatedEventAttributes; + externalWorkflowExecutionSignaledEventAttributes?: ExternalWorkflowExecutionSignaledEventAttributes; + signalExternalWorkflowExecutionFailedEventAttributes?: SignalExternalWorkflowExecutionFailedEventAttributes; + externalWorkflowExecutionCancelRequestedEventAttributes?: ExternalWorkflowExecutionCancelRequestedEventAttributes; + requestCancelExternalWorkflowExecutionInitiatedEventAttributes?: RequestCancelExternalWorkflowExecutionInitiatedEventAttributes; + requestCancelExternalWorkflowExecutionFailedEventAttributes?: RequestCancelExternalWorkflowExecutionFailedEventAttributes; + scheduleActivityTaskFailedEventAttributes?: ScheduleActivityTaskFailedEventAttributes; + requestCancelActivityTaskFailedEventAttributes?: RequestCancelActivityTaskFailedEventAttributes; + startTimerFailedEventAttributes?: StartTimerFailedEventAttributes; + cancelTimerFailedEventAttributes?: CancelTimerFailedEventAttributes; + startChildWorkflowExecutionFailedEventAttributes?: StartChildWorkflowExecutionFailedEventAttributes; + } + + export interface WorkflowExecutionStartedEventAttributes { + input?: string; + executionStartToCloseTimeout?: string; + taskStartToCloseTimeout?: string; + childPolicy?: string; + taskList?: TaskList; + workflowType?: WorkflowType; + tagList?: string[]; + continuedExecutionRunId?: string; + parentWorkflowExecution?: WorkflowExecution; + parentInitiatedEventId?: number; + } + + export interface WorkflowExecutionCompletedEventAttributes { + result?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CompleteWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionFailedEventAttributes { + reason?: string; + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface FailWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionTimedOutEventAttributes { + timeoutType?: string; + childPolicy?: string; + } + + export interface WorkflowExecutionCanceledEventAttributes { + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CancelWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionContinuedAsNewEventAttributes { + input?: string; + decisionTaskCompletedEventId?: number; + newExecutionRunId?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + workflowType?: WorkflowType; + } + + export interface ContinueAsNewWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionTerminatedEventAttributes { + reason?: string; + details?: string; + childPolicy?: string; + cause?: string; + } + + export interface WorkflowExecutionCancelRequestedEventAttributes { + externalWorkflowExecution?: WorkflowExecution; + externalInitiatedEventId?: number; + cause?: string; + } + + export interface DecisionTaskScheduledEventAttributes { + taskList?: TaskList; + startToCloseTimeout?: string; + } + + export interface DecisionTaskStartedEventAttributes { + identity?: string; + scheduledEventId?: number; + } + + export interface DecisionTaskCompletedEventAttributes { + executionContext?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface DecisionTaskTimedOutEventAttributes { + timeoutType?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskScheduledEventAttributes { + activityType?: ActivityType; + activityId?: string; + input?: string; + control?: string; + scheduleToStartTimeout?: string; + scheduleToCloseTimeout?: string; + startToCloseTimeout?: string; + taskList?: TaskList; + decisionTaskCompletedEventId?: number; + heartbeatTimeout?: string; + } + + export interface ActivityTaskStartedEventAttributes { + identity?: string; + scheduledEventId?: number; + } + + export interface ActivityTaskCompletedEventAttributes { + result?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskFailedEventAttributes { + reason?: string; + details?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskTimedOutEventAttributes { + timeoutType?: string; + scheduledEventId?: number; + startedEventId?: number; + details?: string; + } + + export interface ActivityTaskCanceledEventAttributes { + details?: string; + scheduledEventId?: number; + startedEventId?: number; + latestCancelRequestedEventId?: number; + } + + export interface ActivityTaskCancelRequestedEventAttributes { + decisionTaskCompletedEventId?: number; + activityId?: string; + } + + export interface WorkflowExecutionSignaledEventAttributes { + signalName?: string; + input?: string; + externalWorkflowExecution?: WorkflowExecution; + externalInitiatedEventId?: number; + } + + export interface MarkerRecordedEventAttributes { + markerName?: string; + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface TimerStartedEventAttributes { + timerId?: string; + control?: string; + startToFireTimeout?: string; + decisionTaskCompletedEventId?: number; + } + + export interface TimerFiredEventAttributes { + timerId?: string; + startedEventId?: number; + } + + export interface TimerCanceledEventAttributes { + timerId?: string; + startedEventId?: number; + decisionTaskCompletedEventId?: number; + } + + export interface StartChildWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + workflowType?: WorkflowType; + control?: string; + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + decisionTaskCompletedEventId?: number; + childPolicy?: string; + taskStartToCloseTimeout?: string; + tagList?: string[]; + } + + export interface ChildWorkflowExecutionStartedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + initiatedEventId?: number; + } + + export interface ChildWorkflowExecutionCompletedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + result?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionFailedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + reason?: string; + details?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionTimedOutEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + timeoutType?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionCanceledEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + details?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionTerminatedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface SignalExternalWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + runId?: string; + signalName?: string; + input?: string; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ExternalWorkflowExecutionSignaledEventAttributes { + workflowExecution?: WorkflowExecution; + initiatedEventId?: number; + } + + export interface SignalExternalWorkflowExecutionFailedEventAttributes { + workflowId?: string; + runId?: string; + cause?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ExternalWorkflowExecutionCancelRequestedEventAttributes { + workflowExecution?: WorkflowExecution; + initiatedEventId?: number; + } + + export interface RequestCancelExternalWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + runId?: string; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface RequestCancelExternalWorkflowExecutionFailedEventAttributes { + workflowId?: string; + runId?: string; + cause?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ScheduleActivityTaskFailedEventAttributes { + activityType?: ActivityType; + activityId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface RequestCancelActivityTaskFailedEventAttributes { + activityId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface StartTimerFailedEventAttributes { + timerId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CancelTimerFailedEventAttributes { + timerId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface StartChildWorkflowExecutionFailedEventAttributes { + workflowType?: WorkflowType; + cause?: string; + workflowId?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ActivityTask { + taskToken?: string; + activityId?: string; + startedEventId?: number; + workflowExecution?: WorkflowExecution; + activityType?: ActivityType; + input?: string; + } + + export interface PollForActivityTaskResult { + activityTask?: ActivityTask; + } + + export interface PollForDecisionTaskResult { + decisionTask?: DecisionTask; + } + + export interface StartWorkflowExecutionResult { + run?: Run; + } + + export interface Run { + runId?: string; + } + + } + + export module Sns { + + export interface Client { + config: ClientConfig; + + publicTopic(params: PublishRequest, callback: (err: any, data: PublishResult) => void): void; + createTopic(params: CreateTopicRequest, callback: (err: any, data: CreateTopicResult) => void): void; + deleteTopic(params: DeleteTopicRequest, callback: (err: any, data: any) => void): void; + } + + export interface PublishRequest { + TopicArn?: string; + Message?: string; + MessageStructure?: string; + Subject?: string; + } + + export interface PublishResult { + MessageId?: string; + } + + export interface CreateTopicRequest { + Name?: string; + } + + export interface CreateTopicResult { + TopicArn?: string; + } + + export interface DeleteTopicRequest { + TopicArn?: string; + } + + } + + export module s3 { + + export interface Client { + config: ClientConfig; + + putObject(params: PutObjectRequest, callback: (err: any, data: any) => void): void; + getObject(params: GetObjectRequest, callback: (err: any, data: any) => void): void; + } + + export interface PutObjectRequest { + ACL?: string; + Body?: any; + Bucket: string; + CacheControl?: string; + ContentDisposition?: string; + ContentEncoding?: string; + ContentLanguage?: string; + ContentLength?: string; + ContentMD5?: string; + ContentType?: string; + Expires?: any; + GrantFullControl?: string; + GrantRead?: string; + GrantReadACP?: string; + GrantWriteACP?: string; + Key: string; + Metadata?: string[]; + ServerSideEncryption?: string; + StorageClass?: string; + WebsiteRedirectLocation?: string; + } + + export interface GetObjectRequest { + Bucket: string; + IfMatch?: string; + IfModifiedSince?: any; + IfNoneMatch?: string; + IfUnmodifiedSince?: any; + Key: string; + Range?: string; + ResponseCacheControl?: string; + ResponseContentDisposition?: string; + ResponseContentEncoding?: string; + ResponseContentLanguage?: string; + ResponseContentType?: string; + ResponseExpires?: any; + VersionId?: string; + } + + } +} diff --git a/azure-mobile-services-client/AzureMobileServicesClient.d.ts b/azure-mobile-services-client/AzureMobileServicesClient.d.ts index 3b2b8fc167..2aec111143 100644 --- a/azure-mobile-services-client/AzureMobileServicesClient.d.ts +++ b/azure-mobile-services-client/AzureMobileServicesClient.d.ts @@ -42,21 +42,21 @@ declare module Microsoft.WindowsAzure { 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; + insert(instance: any, paramsQS: Object, callback: (error: any, retInserted: any) => any): void; + insert(instance: any, paramsQS: Object): asyncPromise; + insert(instance: any): asyncPromise; - update(istance: any, paramsQS: Object, callback: (error: any, retUpdated: any) => any): void; - update(istance: any, paramsQS: Object): asyncPromise; - update(istance: any): asyncPromise; + update(instance: any, paramsQS: Object, callback: (error: any, retUpdated: any) => any): void; + update(instance: any, paramsQS: Object): asyncPromise; + update(instance: 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; + del(instance: any, paramsQS: Object, callback: (error?: any) => void ): void; + del(instance: any, paramsQS: Object): asyncPromise; + del(instance: any): asyncPromise; read(query: IQuery, paramsQS: Object, callback: (error: any, retValues: any) => any): void; diff --git a/backbone-relational/backbone-relational.d.ts b/backbone-relational/backbone-relational.d.ts index 56dd2e9e83..4f4aa45cc6 100644 --- a/backbone-relational/backbone-relational.d.ts +++ b/backbone-relational/backbone-relational.d.ts @@ -5,12 +5,15 @@ /// - /// declare module Backbone { - export class RelationalModel extends Model { - static extend(properties:any, classProperties?:any):any; // do not use, prefer TypeScript's extend functionality + class RelationalModel extends Model { + /** + * Do not use, prefer TypeScript's extend functionality. + **/ + //private static extend(properties:any, classProperties?:any):any; + relations:any; subModelTypes:any; subModelTypeAttribute:any; @@ -58,7 +61,7 @@ declare module Backbone { setRelated(related:Model):void; - setRelated(related:Collection):void; + setRelated(related:Collection):void; getReverseRelations(model:RelationalModel):Relation; @@ -78,15 +81,15 @@ declare module Backbone { setKeyContents(keyContents:number[]):void; - setKeyContents(keyContents:Collection):void; + setKeyContents(keyContents:Collection):void; onChange(model:Model, attr:any, options:any):void; - handleAddition(model:Model, coll:Collection, options:any):void; + handleAddition(model:Model, coll:Collection, options:any):void; - handleRemoval(model:Model, coll:Collection, options:any):void; + handleRemoval(model:Model, coll:Collection, options:any):void; - handleReset(coll:Collection, options:any):void; + handleReset(coll:Collection, options:any):void; tryAddRelated(model:Model, coll:any, options:any):void; @@ -135,9 +138,9 @@ declare module Backbone { processOrphanRelations():void; - retroFitRelation(relation:RelationalModel, create:boolean):Collection; + retroFitRelation(relation:RelationalModel, create:boolean):Collection; - getCollection(type:RelationalModel, create:boolean):Collection; + getCollection(type:RelationalModel, create:boolean):Collection; getObjectByName(name:string):any; @@ -158,7 +161,7 @@ declare module Backbone { update(model:RelationalModel):void; - unregister(model:RelationalModel, collection:Collection, options:any):void; + unregister(model:RelationalModel, collection:Collection, options:any):void; reset():void; diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts index c1292c1c25..506fd7bb68 100644 --- a/backbone/backbone-tests.ts +++ b/backbone/backbone-tests.ts @@ -4,7 +4,7 @@ function test_events() { var object = new Backbone.Events(); - object.on("alert", (msg) => alert("Triggered " + msg)); + object.on("alert", (eventName: string) => alert("Triggered " + eventName)); object.trigger("alert", "an event"); @@ -18,48 +18,74 @@ function test_events() { object.off(); } +class SettingDefaults extends Backbone.Model { + + // 'defaults' could be set in one of the following ways: + + defaults() { + return { + name: "Joe" + } + } + + constructor(attributes?: any, options?: any) { + this.defaults = { + name: "Joe" + } + // super has to come last + super(attributes, options); + } + + // or set it like this + initialize() { + this.defaults = { + name: "Joe" + } + + } + + // same patterns could be used for setting 'Router.routes' and 'View.events' +} + +class Sidebar extends Backbone.Model { + + promptColor() { + var cssColor = prompt("Please enter a CSS color:"); + this.set({ color: cssColor }); + } +} + +class Note extends Backbone.Model { + initialize() { } + author() { } + coordinates() { } + allowedToEdit(account: any) { + return true; + } +} + +class PrivateNote extends Note { + allowedToEdit(account: any) { + return account.owns(this); + } + + set(attributes: any, options?: any): Backbone.Model { + return Backbone.Model.prototype.set.call(this, attributes, options); + } +} + function test_models() { - var Sidebar = Backbone.Model.extend({ - promptColor: function () { - var cssColor = prompt("Please enter a CSS color:"); - this.set({ color: cssColor }); - } - }); - var sidebar = new Sidebar(); - sidebar.on('change:color', (model, color) => $('#sidebar').css({ background: color })); + sidebar.on('change:color', (model: {}, color: string) => $('#sidebar').css({ background: color })); sidebar.set({ color: 'white' }); sidebar.promptColor(); - //////// - - var Note = Backbone.Model.extend({ - initialize: () => { }, - author: () => { }, - coordinates: () => { }, - allowedToEdit: (account) => { - return true; - } - }); - - var PrivateNote = Note.extend({ - - allowedToEdit: function (account) { - return account.owns(this); - } - - }); - ////////// - var note = Backbone.Model.extend({ - set: function (attributes, options) { - Backbone.Model.prototype.set.call(this, attributes, options); - } - }); + var note = new PrivateNote(); - note.get("title") + note.get("title"); note.set({ title: "March 20", content: "In his eyes she eclipses..." }); @@ -69,7 +95,7 @@ function test_models() { class Employee extends Backbone.Model { reports: EmployeeCollection; - constructor (options? ) { + constructor(attributes?: any, options?: any) { super(options); this.reports = new EmployeeCollection(); this.reports.url = '../api/employees/' + this.id + '/reports'; @@ -80,31 +106,51 @@ class Employee extends Backbone.Model { } } -class EmployeeCollection extends Backbone.Collection { - findByName(key) { } +class EmployeeCollection extends Backbone.Collection { + findByName(key: any) { } } + +class Book extends Backbone.Model { + title: string; + author: string; + published: boolean; +} + +class Library extends Backbone.Collection { + // This model definition is here only to test type compatibility of the model, but it + // is not necessary in working code as it is automatically inferred through generics. + model: typeof Book; +} + +class Books extends Backbone.Collection { } + function test_collection() { - var Book: Backbone.Model; - var Library = Backbone.Collection.extend({ - model: Book - }); - var Books: Backbone.Collection; + var books = new Books(); - Books.each(function (book) { - }); + var book1: Book = new Book({ title: "Title 1", author: "Mike" }); + books.add(book1); - var titles = Books.map(function (book) { - return book.get("title"); - }); + // Objects can be added to collection by casting to model type. + // Compiler will check if object properties are valid for the cast. + // This gives better type checking than declaring an `any` overload. + books.add({ title: "Title 2", author: "Mikey" }); - var publishedBooks = Books.filter(function (book) { - return book.get("published") === true; - }); + var model: Book = book1.collection.first(); + if (model !== book1) { + throw new Error("Error"); + } - var alphabetical = Books.sortBy(function (book) { - return null; - }); + books.each(book => + book.get("title")); + + var titles = books.map(book => + book.get("title")); + + var publishedBooks = books.filter(book => + book.get("published") === true); + + var alphabetical = books.sortBy((book: Book): number => null); } ////////// @@ -121,26 +167,26 @@ module v1Changes { function test_listenTo() { var model = new Employee; - var view = new Backbone.View; + var view = new Backbone.View(); view.listenTo(model, 'invalid', () => { }); } function test_listenToOnce() { var model = new Employee; - var view = new Backbone.View; + var view = new Backbone.View(); view.listenToOnce(model, 'invalid', () => { }); } function test_stopListening() { var model = new Employee; - var view = new Backbone.View; + var view = new Backbone.View(); view.stopListening(model, 'invalid', () => { }); view.stopListening(model, 'invalid'); view.stopListening(model); } } - module modelandcollection { + module ModelAndCollection { function test_url() { Employee.prototype.url = () => '/employees'; EmployeeCollection.prototype.url = () => '/employees'; @@ -168,7 +214,7 @@ module v1Changes { } } - module model { + module Model { function test_validationError() { var model = new Employee; if (model.validationError) { @@ -195,17 +241,17 @@ module v1Changes { model.destroy({ wait: true, success: (m?, response?, options?) => { }, - error: (m?, jqxhr?: JQueryXHR, options?) => { } + error: (m?, jqxhr?, options?) => { } }); model.destroy({ success: (m?, response?, options?) => { }, - error: (m?, jqxhr?: JQueryXHR) => { } + error: (m?, jqxhr?) => { } }); model.destroy({ success: () => { }, - error: (m?, jqxhr?: JQueryXHR) => { } + error: (m?, jqxhr?) => { } }); } @@ -220,7 +266,7 @@ module v1Changes { wait: true, validate: false, success: (m?, response?, options?) => { }, - error: (m?, jqxhr?: JQueryXHR, options?) => { } + error: (m?, jqxhr?, options?) => { } }); model.save({ @@ -229,7 +275,7 @@ module v1Changes { }, { success: () => { }, - error: (m?, jqxhr?: JQueryXHR) => { } + error: (m?, jqxhr?) => { } }); } @@ -240,7 +286,7 @@ module v1Changes { } } - module collection { + module Collection { function test_fetch() { var collection = new EmployeeCollection; collection.fetch({ reset: true }); @@ -256,7 +302,7 @@ module v1Changes { } } - module router { + module Router { function test_navigate() { var router = new Backbone.Router; @@ -264,4 +310,4 @@ module v1Changes { router.navigate('/employees', true); } } -} \ No newline at end of file +} diff --git a/backbone/backbone-tests.ts.tscparams b/backbone/backbone-tests.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/backbone/backbone-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index d94e9172bf..3aeeb7d906 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -1,11 +1,10 @@ // Type definitions for Backbone 1.0.0 // Project: http://backbonejs.org/ -// Definitions by: Boris Yankov -// Definitions by: Natan Vivo +// Definitions by: Boris Yankov , Natan Vivo // Definitions: https://github.com/borisyankov/DefinitelyTyped - /// +/// declare module Backbone { @@ -67,7 +66,7 @@ declare module Backbone { } class Events { - on(eventName: any, callback?: Function, context?: any): any; + on(eventName: string, callback?: Function, context?: any): any; off(eventName?: string, callback?: Function, context?: any): any; trigger(eventName: string, ...args: any[]): any; bind(eventName: string, callback: Function, context?: any): any; @@ -86,17 +85,24 @@ declare module Backbone { sync(...arg: any[]): JQueryXHR; } - interface OptionalDefaults { - defaults?(): any; - } + class Model extends ModelBase { - class Model extends ModelBase implements OptionalDefaults { - - static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality + /** + * Do not use, prefer TypeScript's extend functionality. + **/ + private static extend(properties: any, classProperties?: any): any; attributes: any; changed: any[]; cid: string; + collection: Collection; + + /** + * Default attributes for the model. It can be an object hash or a method returning an object hash. + * For assigning an object hash, do it like this: this.defaults = { attribute: value, ... }; + * That works only if you set it in the constructor or the initialize method. + **/ + defaults(): any; id: any; idAttribute: string; validationError: any; @@ -107,8 +113,23 @@ declare module Backbone { fetch(options?: ModelFetchOptions): JQueryXHR; - get(attributeName: string): any; - set(attributeName: string, value: any, options?: ModelSetOptions): Model; + /** + * For strongly-typed access to attributes, use the `get` method only privately in public getter properties. + * @example + * get name(): string { + * return super.get("name"); + * } + **/ + /*private*/ get(attributeName: string): any; + + /** + * For strongly-typed assignment of attributes, use the `set` method only privately in public setter properties. + * @example + * set name(value: string) { + * super.set("name", value); + * } + **/ + /*private*/ set(attributeName: string, value: any, options?: ModelSetOptions): Model; set(obj: any, options?: ModelSetOptions): Model; change(): any; @@ -127,7 +148,7 @@ declare module Backbone { unset(attribute: string, options?: Silenceable): Model; validate(attributes: any, options?: any): any; - _validate(attrs: any, options: any): boolean; + private _validate(attrs: any, options: any): boolean; // mixins from underscore @@ -141,115 +162,129 @@ declare module Backbone { omit(...keys: string[]): any; } - class Collection extends ModelBase { + class Collection extends ModelBase { - static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality + /** + * Do not use, prefer TypeScript's extend functionality. + **/ + private static extend(properties: any, classProperties?: any): any; - model: any; - models: any; - collection: Model; + // TODO: this really has to be typeof TModel + //model: typeof TModel; + model: { new(): TModel; }; // workaround + models: TModel[]; length: number; - constructor(models?: any, options?: any); + constructor(models?: TModel[], options?: any); fetch(options?: CollectionFetchOptions): JQueryXHR; - comparator(element: Model): any; - comparator(compare: Model, to?: Model): any; + comparator(element: TModel): number; + comparator(compare: TModel, to?: TModel): number; - add(model: Model, options?: AddOptions): Collection; - add(model: any, options?: AddOptions): Collection; - add(models: Model[], options?: AddOptions): Collection; - add(models: any[], options?: AddOptions): Collection; - at(index: number): Model; - get(id: any): Model; - create(attributes: any, options?: ModelSaveOptions): Model; + add(model: TModel, options?: AddOptions): Collection; + add(models: TModel[], options?: AddOptions): Collection; + at(index: number): TModel; + /** + * Get a model from a collection, specified by an id, a cid, or by passing in a model. + **/ + get(id: number): TModel; + get(id: string): TModel; + get(id: Model): TModel; + create(attributes: any, options?: ModelSaveOptions): TModel; pluck(attribute: string): any[]; - push(model: Model, options?: AddOptions): Model; - pop(options?: Silenceable): Model; - remove(model: Model, options?: Silenceable): Model; - remove(models: Model[], options?: Silenceable): Model[]; - reset(models?: Model[], options?: Silenceable): Model[]; - reset(models?: any[], options?: Silenceable): Model[]; - set(models?: any[], options?: Silenceable): Model[]; - shift(options?: Silenceable): Model; - sort(options?: Silenceable): Collection; - unshift(model: Model, options?: AddOptions): Model; - where(properies: any): Model[]; - findWhere(properties: any): Model; + push(model: TModel, options?: AddOptions): TModel; + pop(options?: Silenceable): TModel; + remove(model: TModel, options?: Silenceable): TModel; + remove(models: TModel[], options?: Silenceable): TModel[]; + reset(models?: TModel[], options?: Silenceable): TModel[]; + set(models?: TModel[], options?: Silenceable): TModel[]; + shift(options?: Silenceable): TModel; + sort(options?: Silenceable): Collection; + unshift(model: TModel, options?: AddOptions): TModel; + where(properies: any): TModel[]; + findWhere(properties: any): TModel; - _prepareModel(attrs?: any, options?: any): any; - _removeReference(model: Model): void; - _onModelEvent(event: string, model: Model, collection: Collection, options: any): void; + private _prepareModel(attrs?: any, options?: any): any; + private _removeReference(model: TModel): void; + private _onModelEvent(event: string, model: TModel, collection: Collection, options: any): void; // mixins from underscore - all(iterator: (element: Model, index: number) => boolean, context?: any): boolean; - any(iterator: (element: Model, index: number) => boolean, context?: any): boolean; - collect(iterator: (element: Model, index: number, context?: any) => any[], context?: any): any[]; + all(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; + any(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; + collect(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[]; chain(): any; - compact(): Model[]; + compact(): TModel[]; contains(value: any): boolean; - countBy(iterator: (element: Model, index: number) => any): any[]; - countBy(attribute: string): any[]; + countBy(iterator: (element: TModel, index: number) => any): _.Dictionary; + countBy(attribute: string): _.Dictionary; detect(iterator: (item: any) => boolean, context?: any): any; // ??? - difference(...model: Model[]): Model[]; - drop(): Model; - drop(n: number): Model[]; - each(iterator: (element: Model, index: number, list?: any) => void , context?: any): any; - every(iterator: (element: Model, index: number) => boolean, context?: any): boolean; - filter(iterator: (element: Model, index: number) => boolean, context?: any): Model[]; - find(iterator: (element: Model, index: number) => boolean, context?: any): Model; - first(): Model; - first(n: number): Model[]; - flatten(shallow?: boolean): 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): any; + difference(...model: TModel[]): TModel[]; + drop(): TModel; + drop(n: number): TModel[]; + each(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any; + every(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; + filter(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[]; + find(iterator: (element: TModel, index: number) => boolean, context?: any): TModel; + first(): TModel; + first(n: number): TModel[]; + flatten(shallow?: boolean): TModel[]; + foldl(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; + forEach(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any; + groupBy(iterator: (element: TModel, index: number) => string, context?: any): _.Dictionary; + groupBy(attribute: string, context?: any): _.Dictionary; include(value: any): boolean; - indexOf(element: Model, isSorted?: boolean): 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[]; + indexOf(element: TModel, isSorted?: boolean): number; + initial(): TModel; + initial(n: number): TModel[]; + inject(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; + intersection(...model: TModel[]): TModel[]; isEmpty(object: any): boolean; invoke(methodName: string, arguments?: any[]): 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; + last(): TModel; + last(n: number): TModel[]; + lastIndexOf(element: TModel, fromIndex?: number): number; + map(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[]; + max(iterator?: (element: TModel, index: number) => any, context?: any): TModel; + min(iterator?: (element: TModel, index: number) => any, context?: any): TModel; object(...values: any[]): any[]; - reduce(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any; + reduce(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; select(iterator: any, context?: any): any[]; size(): number; shuffle(): any[]; - some(iterator: (element: Model, index: number) => boolean, context?: any): boolean; - 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; + some(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; + sortBy(iterator: (element: TModel, index: number) => number, context?: any): TModel[]; + sortBy(attribute: string, context?: any): TModel[]; + sortedIndex(element: TModel, iterator?: (element: TModel, index: number) => number): number; range(stop: number, step?: number): any; range(start: number, stop: number, step?: number): any; - reduceRight(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any[]; - reject(iterator: (element: Model, index: number) => boolean, context?: any): Model[]; - rest(): Model; - rest(n: number): Model[]; - tail(): Model; - tail(n: number): Model[]; + reduceRight(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any[]; + reject(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[]; + rest(): TModel; + rest(n: number): TModel[]; + tail(): TModel; + tail(n: number): TModel[]; toArray(): any[]; - union(...model: Model[]): Model[]; - uniq(isSorted?: boolean, iterator?: (element: Model, index: number) => boolean): Model[]; - without(...values: any[]): Model[]; - zip(...model: Model[]): Model[]; + union(...model: TModel[]): TModel[]; + uniq(isSorted?: boolean, iterator?: (element: TModel, index: number) => boolean): TModel[]; + without(...values: any[]): TModel[]; + zip(...model: TModel[]): TModel[]; } - interface OptionalRoutes { - routes?(): any; - } + class Router extends Events { - class Router extends Events implements OptionalRoutes { + /** + * Do not use, prefer TypeScript's extend functionality. + **/ + private static extend(properties: any, classProperties?: any): any; - static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality + /** + * Routes hash or a method returning the routes hash that maps URLs with parameters to methods on your Router. + * For assigning routes as object hash, do it like this: this.routes = { "route": callback, ... }; + * That works only if you set it in the constructor or the initialize method. + **/ + routes(): any; constructor(options?: RouterOptions); initialize(options?: RouterOptions): void; @@ -257,9 +292,9 @@ declare module Backbone { navigate(fragment: string, options?: NavigateOptions): Router; navigate(fragment: string, trigger?: boolean): Router; - _bindRoutes(): void; - _routeToRegExp(route: string): RegExp; - _extractParameters(route: RegExp, fragment: string): string[]; + private _bindRoutes(): void; + private _routeToRegExp(route: string): RegExp; + private _extractParameters(route: RegExp, fragment: string): string[]; } var history: History; @@ -279,14 +314,14 @@ declare module Backbone { loadUrl(fragmentOverride: string): boolean; navigate(fragment: string, options?: any): boolean; started: boolean; - options: any; - - _updateHash(location: Location, fragment: string, replace: boolean): void; + options: any; + + private _updateHash(location: Location, fragment: string, replace: boolean): void; } - interface ViewOptions { - model?: Backbone.Model; - collection?: Backbone.Collection; + interface ViewOptions { + model?: TModel; + collection?: Backbone.Collection; el?: any; id?: string; className?: string; @@ -294,35 +329,41 @@ declare module Backbone { attributes?: any[]; } - interface OptionalEvents { - events?(): any; - } + class View extends Events { - class View extends Events implements OptionalEvents { + /** + * Do not use, prefer TypeScript's extend functionality. + **/ + private static extend(properties: any, classProperties?: any): any; - static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality + constructor(options?: ViewOptions); - constructor(options?: ViewOptions); + /** + * Events hash or a method returning the events hash that maps events/selectors to methods on your View. + * For assigning events as object hash, do it like this: this.events = { "event:selector": callback, ... }; + * That works only if you set it in the constructor or the initialize method. + **/ + events(): any; $(selector: string): JQuery; - model: Model; - collection: Collection; - make(tagName: string, attrs?: any, opts?: any): View; - setElement(element: HTMLElement, delegate?: boolean): View; - setElement(element: JQuery, delegate?: boolean): View; + model: TModel; + collection: Collection; + //template: (json, options?) => string; + make(tagName: string, attrs?: any, opts?: any): View; + setElement(element: HTMLElement, delegate?: boolean): View; + setElement(element: JQuery, delegate?: boolean): View; id: string; cid: string; className: string; tagName: string; - options: any; el: any; $el: JQuery; - setElement(element: any): View; + setElement(element: any): View; attributes: any; $(selector: any): JQuery; - render(): View; - remove(): View; + render(): View; + remove(): View; make(tagName: any, attributes?: any, content?: any): any; delegateEvents(events?: any): any; undelegateEvents(): any; @@ -333,13 +374,11 @@ declare module Backbone { // SYNC function sync(method: string, model: Model, options?: JQueryAjaxSettings): any; function ajax(options?: JQueryAjaxSettings): JQueryXHR; - var emulateHTTP: boolean; - var emulateJSONBackbone: boolean; + var emulateHTTP: boolean; + var emulateJSON: boolean; // Utility function noConflict(): typeof Backbone; - function setDomLibrary(jQueryNew: any): any; - var $: JQueryStatic; } diff --git a/backgrid/backgrid-tests.ts b/backgrid/backgrid-tests.ts index 0c681a1d34..a29a4ae7e6 100644 --- a/backgrid/backgrid-tests.ts +++ b/backgrid/backgrid-tests.ts @@ -23,7 +23,7 @@ class TestModel extends Backbone.Model { } -class TestCollection extends Backbone.Collection { +class TestCollection extends Backbone.Collection { constructor(models?: any, options?: any) { this.model = TestModel; @@ -41,11 +41,11 @@ class TestCollection extends Backbone.Collection { } } -class TestView extends Backbone.View { +class TestView extends Backbone.View { gridView: Backgrid.Grid; testCollection: TestCollection; - constructor(viewOptions?: Backbone.ViewOptions) { + constructor(viewOptions?: Backbone.ViewOptions) { this.testCollection = new TestCollection(); this.gridView = new Backgrid.Grid({ columns: [new Backgrid.Column({name: "FirstName", cell: "string", label: "First Name"}), diff --git a/backgrid/backgrid.d.ts b/backgrid/backgrid.d.ts index 73cb12450e..fcae05d800 100644 --- a/backgrid/backgrid.d.ts +++ b/backgrid/backgrid.d.ts @@ -9,20 +9,20 @@ declare module Backgrid { interface GridOptions { columns: Column[]; - collection: Backbone.Collection; + collection: Backbone.Collection; header: Header; body: Body; row: Row; footer: Footer; } - class Header extends Backbone.View { + class Header extends Backbone.View { } - class Footer extends Backbone.View { + class Footer extends Backbone.View { } - class Row extends Backbone.View { + class Row extends Backbone.View { } class Command { @@ -50,19 +50,19 @@ declare module Backgrid { initialize(options?: any); } - class Body extends Backbone.View { + class Body extends Backbone.View { tagName: string; initialize(options?: any); - insertRow(model: Backbone.Model, collection: Backbone.Collection, options: any); + insertRow(model: Backbone.Model, collection: Backbone.Collection, options: any); moveToNextCell(model: Backbone.Model, cell: Column, command: Command); refresh(): Body; remove(): Body; - removeRow(model: Backbone.Model, collection: Backbone.Collection, options: any); + removeRow(model: Backbone.Model, collection: Backbone.Collection, options: any); render(): Body; } - class Grid extends Backbone.View { + class Grid extends Backbone.View { body: Backgrid.Body; className: string; footer: any; @@ -72,10 +72,10 @@ declare module Backgrid { initialize(options: any); getSelectedModels(): Backbone.Model[]; insertColumn(...options: any[]): Grid; - insertRow(model: Backbone.Model, collection: Backbone.Collection, options: any); + insertRow(model: Backbone.Model, collection: Backbone.Collection, options: any); remove():Grid; removeColumn(...options: any[]): Grid; - removeRow(model: Backbone.Model, collection: Backbone.Collection, options: any); + removeRow(model: Backbone.Model, collection: Backbone.Collection, options: any); render():Grid; } diff --git a/big-integer/big-integer-tests.ts b/big-integer/big-integer-tests.ts new file mode 100644 index 0000000000..3b9fb8745f --- /dev/null +++ b/big-integer/big-integer-tests.ts @@ -0,0 +1,114 @@ +/// + +// constructor tests +var noArgument = bigInt(), + numberArgument = bigInt( 93 ), + stringArgument = bigInt( "75643564363473453456342378564387956906736546456235345" ), + bigIntArgument = bigInt( noArgument ); + +// method tests +var x = bigInt(), + isBigInteger: BigInteger, + isNumber: number, + isBoolean: boolean, + isString: string, + isDivmod: { + quotient: BigInteger; + remainder: BigInteger; + }; + +isBigInteger = x.abs(); + +isBigInteger = x.add( 0 ); +isBigInteger = x.add( x ); +isBigInteger = x.add( "100" ); + +isBigInteger = x.compare( 0 ); +isBigInteger = x.compare( x ); +isBigInteger = x.compare( "100" ); + +isBigInteger = x.compareAbs( 0 ); +isBigInteger = x.compareAbs( x ); +isBigInteger = x.compareAbs( "100" ); + +isBigInteger = x.divide( 0 ); +isBigInteger = x.divide( x ); +isBigInteger = x.divide( "100" ); + +isDivmod = x.divmod( 0 ); +isDivmod = x.divmod( x ); +isDivmod = x.divmod( "100" ); + +isBoolean = x.equals( 0 ); +isBoolean = x.equals( x ); +isBoolean = x.equals( "100" ); + +isBoolean = x.greater( 0 ); +isBoolean = x.greater( x ); +isBoolean = x.greater( "100" ); + +isBoolean = x.greaterOrEquals( 0 ); +isBoolean = x.greaterOrEquals( x ); +isBoolean = x.greaterOrEquals( "100" ); + +isBoolean = x.isEven(); + +isBoolean = x.isNegative(); + +isBoolean = x.isOdd(); + +isBoolean = x.isPositive(); + +isBoolean = x.lesser( 0 ); +isBoolean = x.lesser( x ); +isBoolean = x.lesser( "100" ); + +isBoolean = x.lesserOrEquals( 0 ); +isBoolean = x.lesserOrEquals( x ); +isBoolean = x.lesserOrEquals( "100" ); + +isBigInteger = x.minus( 0 ); +isBigInteger = x.minus( x ); +isBigInteger = x.minus( "100" ); + +isBigInteger = x.mod( 0 ); +isBigInteger = x.mod( x ); +isBigInteger = x.mod( "100" ); + +isBigInteger = x.multiply( 0 ); +isBigInteger = x.multiply( x ); +isBigInteger = x.multiply( "100" ); + +isBigInteger = x.next(); + +isBoolean = x.notEquals( 0 ); +isBoolean = x.notEquals( x ); +isBoolean = x.notEquals( "100" ); + +isBigInteger = x.over( 0 ); +isBigInteger = x.over( x ); +isBigInteger = x.over( "100" ); + +isBigInteger = x.plus( 0 ); +isBigInteger = x.plus( x ); +isBigInteger = x.plus( "100" ); + +isBigInteger = x.pow( 0 ); +isBigInteger = x.pow( x ); +isBigInteger = x.pow( "100" ); + +isBigInteger = x.prev(); + +isBigInteger = x.subtract( 0 ); +isBigInteger = x.subtract( x ); +isBigInteger = x.subtract( "100" ); + +isBigInteger = x.times( 0 ); +isBigInteger = x.times( x ); +isBigInteger = x.times( "100" ); + +isNumber = x.toJSNumber(); + +isString = x.toString(); + +isNumber = x.valueOf(); \ No newline at end of file diff --git a/big-integer/big-integer.d.ts b/big-integer/big-integer.d.ts new file mode 100644 index 0000000000..dfadc49629 --- /dev/null +++ b/big-integer/big-integer.d.ts @@ -0,0 +1,202 @@ +// Type definitions for BigInteger.js +// Project: https://github.com/peterolson/BigInteger.js +// Definitions by: Ingo Bürk +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface BigInteger { + /** Returns the absolute value of a bigInt. */ + abs(): BigInteger; + + /** Performs addition */ + add( number: number ): BigInteger; + /** Performs addition */ + add( number: BigInteger ): BigInteger; + /** Performs addition */ + add( number: string ): BigInteger; + + /** Alias for the add method. */ + plus( number: number ): BigInteger; + /** Alias for the add method. */ + plus( number: BigInteger ): BigInteger; + /** Alias for the add method. */ + plus( number: string ): BigInteger; + + /** Alias for the subtract method. */ + minus( number: number ): BigInteger; + /** Alias for the subtract method. */ + minus( number: BigInteger ): BigInteger; + /** Alias for the subtract method. */ + minus( number: string ): BigInteger; + + /** Performs subtraction. */ + subtract( number: number ): BigInteger; + /** Performs subtraction. */ + subtract( number: BigInteger ): BigInteger; + /** Performs subtraction. */ + subtract( number: string ): BigInteger; + + /** Performs multiplication. */ + multiply( number: number ): BigInteger; + /** Performs multiplication. */ + multiply( number: BigInteger ): BigInteger; + /** Performs multiplication. */ + multiply( number: string ): BigInteger; + + /** Alias for the multiply method. */ + times( number: number ): BigInteger; + /** Alias for the multiply method. */ + times( number: BigInteger ): BigInteger; + /** Alias for the multiply method. */ + times( number: string ): BigInteger; + + /** Performs integer division, disregarding the remainder. */ + divide( number: number ): BigInteger; + /** Performs integer division, disregarding the remainder. */ + divide( number: BigInteger ): BigInteger; + /** Performs integer division, disregarding the remainder. */ + divide( number: string ): BigInteger; + + /** Alias for the divide method. */ + over( number: number ): BigInteger; + /** Alias for the divide method. */ + over( number: BigInteger ): BigInteger; + /** Alias for the divide method. */ + over( number: string ): BigInteger; + + /** Performs exponentiation. If the exponent is less than 0, pow returns 0. bigInt.zero.pow(0) returns 1. */ + pow( number: number ): BigInteger; + /** Performs exponentiation. If the exponent is less than 0, pow returns 0. bigInt.zero.pow(0) returns 1. */ + pow( number: BigInteger ): BigInteger; + /** Performs exponentiation. If the exponent is less than 0, pow returns 0. bigInt.zero.pow(0) returns 1. */ + pow( number: string ): BigInteger; + + /** Adds one to the number. */ + next(): BigInteger; + + /** Subtracts one from the number. */ + prev(): BigInteger; + + /** Performs division and returns the remainder, disregarding the quotient. The sign of the remainder will match the sign of the dividend. */ + mod( number: number ): BigInteger; + /** Performs division and returns the remainder, disregarding the quotient. The sign of the remainder will match the sign of the dividend. */ + mod( number: BigInteger ): BigInteger; + /** Performs division and returns the remainder, disregarding the quotient. The sign of the remainder will match the sign of the dividend. */ + mod( number: string ): BigInteger; + + /** Performs division and returns an object with two properties: quotient and remainder. The sign of the remainder will match the sign of the dividend. */ + divmod( number: number ): { quotient: BigInteger; remainder: BigInteger }; + /** Performs division and returns an object with two properties: quotient and remainder. The sign of the remainder will match the sign of the dividend. */ + divmod( number: BigInteger ): { quotient: BigInteger; remainder: BigInteger }; + /** Performs division and returns an object with two properties: quotient and remainder. The sign of the remainder will match the sign of the dividend. */ + divmod( number: string ): { quotient: BigInteger; remainder: BigInteger }; + + /** Checks if the first number is greater than the second. */ + greater( number: number ): boolean; + /** Checks if the first number is greater than the second. */ + greater( number: BigInteger ): boolean; + /** Checks if the first number is greater than the second. */ + greater( number: string ): boolean; + + /** Checks if the first number is greater than or equal to the second. */ + greaterOrEquals( number: number ): boolean; + /** Checks if the first number is greater than or equal to the second. */ + greaterOrEquals( number: BigInteger ): boolean; + /** Checks if the first number is greater than or equal to the second. */ + greaterOrEquals( number: string ): boolean; + + /** Checks if the first number is lesser than the second. */ + lesser( number: number ): boolean; + /** Checks if the first number is lesser than the second. */ + lesser( number: BigInteger ): boolean; + /** Checks if the first number is lesser than the second. */ + lesser( number: string ): boolean; + + /** Checks if the first number is less than or equal to the second. */ + lesserOrEquals( number: number ): boolean; + /** Checks if the first number is less than or equal to the second. */ + lesserOrEquals( number: BigInteger ): boolean; + /** Checks if the first number is less than or equal to the second. */ + lesserOrEquals( number: string ): boolean; + + /** Returns true if the number is even, false otherwise. */ + isEven(): boolean; + + /** Returns true if the number is odd, false otherwise. */ + isOdd(): boolean; + + /** Return true if the number is positive, false otherwise. Returns true for 0 and false for -0. */ + isPositive(): boolean; + + /** Returns true if the number is negative, false otherwise. Returns false for 0 and true for -0. */ + isNegative(): boolean; + + /** + * Performs a comparison between two numbers. If the numbers are equal, it returns 0. + * If the first number is greater, it returns 1. If the first number is lesser, it returns -1. + */ + compare( number: number ): BigInteger; + /** + * Performs a comparison between two numbers. If the numbers are equal, it returns 0. + * If the first number is greater, it returns 1. If the first number is lesser, it returns -1. + */ + compare( number: BigInteger ): BigInteger; + /** + * Performs a comparison between two numbers. If the numbers are equal, it returns 0. + * If the first number is greater, it returns 1. If the first number is lesser, it returns -1. + */ + compare( number: string ): BigInteger; + + /** Performs a comparison between the absolute value of two numbers. */ + compareAbs( number: number ): BigInteger; + /** Performs a comparison between the absolute value of two numbers. */ + compareAbs( number: BigInteger ): BigInteger; + /** Performs a comparison between the absolute value of two numbers. */ + compareAbs( number: string ): BigInteger; + + /** Checks if two numbers are equal. */ + equals( number: number ): boolean; + /** Checks if two numbers are equal. */ + equals( number: BigInteger ): boolean; + /** Checks if two numbers are equal. */ + equals( number: string ): boolean; + + /** Checks if two numbers are not equal. */ + notEquals( number: number ): boolean; + /** Checks if two numbers are not equal. */ + notEquals( number: BigInteger ): boolean; + /** Checks if two numbers are not equal. */ + notEquals( number: string ): boolean; + + /** Converts a bigInt into a native Javascript number. Loses precision for numbers outside the range. */ + toJSNumber(): number; + + /** Converts a bigInt to a string. */ + toString(): string; + + /** Converts a bigInt to a native Javascript number. This override allows you to use native arithmetic operators without explicit conversion. */ + valueOf(): number; +} + +interface BigIntegerStatic { + /** Equivalent to bigInt(1) */ + one: BigInteger; + /** Equivalent to bigInt(0) */ + zero: BigInteger; + /** Equivalent to bigInt(-1) */ + minusOne: BigInteger; + + /** Equivalent to bigInt(0) */ + (): BigInteger; + /** Parse a Javascript number into a bigInt */ + ( number: number ): BigInteger; + /** Parse a string into a bigInt */ + ( string: string ): BigInteger; + /** no-op */ + ( bigInt: BigInteger ): BigInteger; +} + +declare var bigInt: BigIntegerStatic; + +declare module "big-integer" { + export = bigInt; +} \ No newline at end of file diff --git a/big.js/big.js-tests.ts b/big.js/big.js-tests.ts new file mode 100644 index 0000000000..6de9ee7ccc --- /dev/null +++ b/big.js/big.js-tests.ts @@ -0,0 +1,233 @@ +// Type definitions for big.js +// Project: https://github.com/MikeMcl/big.js/ +// Definitions by: Steve Ognibene +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + +/* + + Tests include code from http://mikemcl.github.io/big.js/ + + Minor changes have been made such as adding variable definitions where required. + +*/ + +function constructorTests() { + var x = new Big(9) // '9' + var y = new Big(x) // '9' + var d = Big(435.345) // 'new' is optional + var e = Big('435.345') // 'new' is optional + var a = new Big('5032485723458348569331745.33434346346912144534543') + var b = new Big('4.321e+4') // '43210' + var c = new Big('-735.0918e-430') // '-7.350918e-428' +} + +function staticPropertiesTests() { + Big.DP = 40; + Big.RM = 3; + Big.RM = BigJsLibrary.RoundingMode.RoundAwayFromZero; +} + +function absTests() { + var x = new Big(-0.8); + x.abs(); // '0.8' +} + +function cmpTests() { + var x = new Big(6); + var y = new Big(5); + x.cmp(y); // 1 + y.cmp(x.minus(1)); // 0 +} + +function divTests() { + var x = new Big(355); + var y = new Big(113); + x.div(y); // '3.14159292035398230088' + Big.DP = 2; + x.div(y); // '3.14' + x.div(5); // '71' +} + +function eqTests() { + 0 === 1e-324; // true + var x = new Big(0); + x.eq('1e-324'); // false + Big(-0).eq(x); // true ( -0 === 0 ) +} + +function gtTests() { + 0.1 > 0.3 - 0.2; // true + var x = new Big(0.1); + x.gt(Big(0.3).minus(0.2)); // false + Big(0).gt(x); // false +} + +function gteTests() { + 0.3 - 0.2 >= 0.1; // false + var x = new Big(0.3).minus(0.2); + x.gte(0.1); // true + Big(1).gte(x); // true +} + +function ltTests() { + 0.3 - 0.2 < 0.1; // true + var x = new Big(0.3).minus(0.2); + x.lt(0.1); // false + Big(0).lt(x); // true +} + +function lteTests() { + 0.1 <= 0.3 - 0.2; // false + var x = new Big(0.1); + x.lte(Big(0.3).minus(0.2)); // true + Big(-1).lte(x); // true +} + +function minusTests() { + 0.3 - 0.1; // 0.19999999999999998 + var x = new Big(0.3); + x.minus(0.1); // '0.2' +} + +function modTests() { + 1 % 0.9 // 0.09999999999999998 + var x = Big(1); + x.mod(0.9) // '0.1' +} + +function plusTests() { + 0.1 + 0.2 // 0.30000000000000004 + var x = new Big(0.1) + var y = x.plus(0.2) // '0.3' + Big(0.7).plus(x).plus(y) // '1' +} + +function powTests() { + Math.pow(0.7, 2) // 0.48999999999999994 + var x = new Big(0.7) + x.pow(2) // '0.49' + Big.DP = 20 + Big(3).pow(-2) // '0.11111111111111111111' + + new Big(123.456).pow(1000).toString().length // 5099 + new Big(2).pow(1e+6) // Time taken (Node.js): 9 minutes 34 secs. +} + +function roundTests() { + var x = 123.45 + Math.round(x) // 123 + var y = new Big(x) + y.round() // '123' + y.round(2) // '123.45' + y.round(10) // '123.45' + y.round(1, 0) // '123.4' + y.round(1, 1) // '123.5' + y.round(1, 2) // '123.4' + y.round(1, 3) // '123.5' + y // '123.45' +} + +function sqrtTests() { + var x = new Big(16) + x.sqrt() // '4' + var y = new Big(3) + y.sqrt() // '1.73205080756887729353' +} + +function timesTests() { + 0.6 * 3 // 1.7999999999999998 + var x = new Big(0.6) + var y = x.times(3) // '1.8' + Big('7e+500').times(y) // '1.26e+501' +} + +function toExponentialTests() { + var x = 45.6 + var y = new Big(x) + x.toExponential() // '4.56e+1' + y.toExponential() // '4.56e+1' + x.toExponential(0) // '5e+1' + y.toExponential(0) // '5e+1' + x.toExponential(1) // '4.6e+1' + y.toExponential(1) // '4.6e+1' + x.toExponential(3) // '4.560e+1' + y.toExponential(3) // '4.560e+1' +} + +function toFixedTests() { + var x = 45.6 + var y = new Big(x) + x.toFixed() // '46' + y.toFixed() // '45.6' + y.toFixed(0) // '46' + x.toFixed(3) // '45.600' + y.toFixed(3) // '45.600' +} + +function toPrecisionTests() { + var x = 45.6 + var y = new Big(x) + x.toPrecision() // '45.6' + y.toPrecision() // '45.6' + x.toPrecision(1) // '5e+1' + y.toPrecision(1) // '5e+1' + x.toPrecision(5) // '45.600' + y.toPrecision(5) // '45.600' +} + +function toStringTests() { + var x = new Big('9.99e+20') + x.toString() // '999000000000000000000' + var y = new Big('1E21') + x.toString() // '1e+21' +} + +function valueOfTests() { + var x = new Big('177.7e+457') + x.valueOf() // '1.777e+459' +} + +function toJSONTests() { + var x = new Big('177.7e+457') + var y = new Big(235.4325) + var z = new Big('0.0098074') + var str = JSON.stringify([x, y, z]) + + var a = new Big('123').toJSON(); + + JSON.parse(str, function (k, v) { return k === '' ? v : new Big(v) }) // Returns an array of three Big numbers. +} + +function propertiesTest1() { + var x = new Big(0.123) // '0.123' + x.toExponential() // '1.23e-1' + x.c // '1,2,3' + x.e // -1 + x.s // 1 + + var y = new Number(-123.4567000e+2) // '-12345.67' + y.toExponential() // '-1.234567e+4' + var z = new Big('-123.4567000e+2') // '-12345.67' + z.toExponential() // '-1.234567e+4' + z.c // '1,2,3,4,5,6,7' + z.e // 4 + z.s // -1 +} + +function propertiesTest2() { + var x = new Big('1234.000') // '1234' + x.toExponential() // '1.234e+3' + x.c // '1,2,3,4' + x.e // 3 + + x.e = -5 + x // '0.00001234' +} + +function propertiesTest3() { + var y = new Big(-0) // '0' + y.c // '0' [0].toString() + y.e // 0 + y.s // -1 +} \ No newline at end of file diff --git a/big.js/big.js.d.ts b/big.js/big.js.d.ts new file mode 100644 index 0000000000..4f6278a80e --- /dev/null +++ b/big.js/big.js.d.ts @@ -0,0 +1,200 @@ +// Type definitions for big.js +// Project: https://github.com/MikeMcl/big.js/ +// Definitions by: Steve Ognibene +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module BigJsLibrary { + + export enum RoundingMode { + RoundTowardsZero = 0, + RoundTowardsNearestAwayFromZero = 1, + RoundTowardsNearestTowardsEven = 2, + RoundAwayFromZero = 3 + } + + interface BigJS extends BigJS_Constructors { + /** The maximum number of decimal places of the results of operations involving division. + It is relevant only to the div and sqrt methods, and the pow method when the exponent is negative. + @default 40 */ + DP: number; + + /** The rounding mode used in the above operations and by round, toExponential, toFixed and toPrecision. + Default is RoundTowardsNearestAwayFromZero + @default 1 */ + RM: RoundingMode; + } + + interface BigJS_Constructors { + /** A decimal value. */ + new (value: number): BigJS; + /** A decimal value. + String values may be in exponential, as well as normal (non-exponential) notation. There is no limit to the number of digits of a string value (other than that of Javascript's maximum array size), but the largest recommended exponent magnitude is 1e+6. Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid. + String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9. */ + new (value: string): BigJS; + /** A decimal value. */ + new (value: BigJS): BigJS; + /** A decimal value. */ + (value: number): BigJS; + /** A decimal value. + String values may be in exponential, as well as normal (non-exponential) notation. There is no limit to the number of digits of a string value (other than that of Javascript's maximum array size), but the largest recommended exponent magnitude is 1e+6. Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid. + String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9. */ + (value: string): BigJS; + /** A decimal value. */ + (value: BigJS): BigJS; + } + + /** BigJS instance methods */ + interface BigJS extends BigJS_Constructors { + /** Returns a Big number whose value is the absolute value, i.e. the magnitude, of this Big number. */ + abs(): BigJS; + + /** Compare + @returns {Number} + 1 = If the value of this Big number is greater than the value of n + -1 = If the value of this Big number is less than the value of n + 0 = If this Big number and n have the same value */ + cmp(n: number): number; + /** Compare + @returns {Number} + 1 = If the value of this Big number is greater than the value of n + -1 = If the value of this Big number is less than the value of n + 0 = If this Big number and n have the same value */ + cmp(n: string): number; + /** Compare + @returns {Number} + 1 = If the value of this Big number is greater than the value of n + -1 = If the value of this Big number is less than the value of n + 0 = If this Big number and n have the same value */ + cmp(n: BigJS): number; + + /** Returns a Big number whose value is the value of this Big number divided by n. */ + div(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number divided by n. */ + div(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number divided by n. */ + div(n: BigJS): BigJS; + + /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ + eq(n: number): boolean; + /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ + eq(n: string): boolean; + /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ + eq(n: BigJS): boolean; + + /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ + gt(n: number): boolean; + /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ + gt(n: string): boolean; + /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ + gt(n: BigJS): boolean; + + /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ + gte(n: number): boolean; + /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ + gte(n: string): boolean; + /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ + gte(n: BigJS): boolean; + + /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ + lt(n: number): boolean; + /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ + lt(n: string): boolean; + /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ + lt(n: BigJS): boolean; + + /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ + lte(n: number): boolean; + /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ + lte(n: string): boolean; + /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ + lte(n: BigJS): boolean; + + /** Returns a Big number whose value is the value of this Big number minus n. */ + minus(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number minus n. */ + minus(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number minus n. */ + minus(n: BigJS): BigJS; + + /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. + The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ + mod(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. + The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ + mod(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. + The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ + mod(n: BigJS): BigJS; + + /** Returns a Big number whose value is the value of this Big number plus n. */ + plus(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number plus n. */ + plus(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number plus n. */ + plus(n: BigJS): BigJS; + + /** Returns a Big number whose value is the value of this Big number raised to the power exp. + If exp is negative and the result has more fraction digits than is specified by Big.DP, it will be rounded to Big.DP decimal places using rounding mode Big.RM. + @param exp integer, -1e+6 to 1e+6 inclusive */ + pow(exp: number): BigJS; + + /** Returns a Big number whose value is the value of this Big number rounded to a whole number. */ + round(): BigJS; + /** Returns a Big number whose value is the value of this Big number rounded using rounding mode rm to a maximum of dp decimal places. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted or is null or undefined, the return value is n rounded to a whole number. */ + round(dp: number): BigJS; + /** Returns a Big number whose value is the value of this Big number rounded using rounding mode rm to a maximum of dp decimal places. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted or is null or undefined, the return value is n rounded to a whole number. + @param rm Rounding mode. If rm is omitted or is null or undefined, the current Big.RM setting is used. */ + round(dp: number, rm: RoundingMode): BigJS; + + /** Returns a Big number whose value is the square root of this Big number. */ + sqrt(): BigJS; + + /** Returns a Big number whose value is the value of this Big number times n. */ + times(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number times n. */ + times(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number times n. */ + times(n: BigJS): BigJS; + + /** Returns a string representing the value of this Big number in exponential notation to a fixed number of decimal places dp. */ + toExponential(): string; + /** Returns a string representing the value of this Big number in exponential notation to a fixed number of decimal places dp. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted, or is null or undefined, the number of digits after the decimal point defaults to the minimum number of digits necessary to represent the value exactly. */ + toExponential(dp: number): string; + + /** Returns a string representing the value of this Big number in normal notation to a fixed number of decimal places dp. */ + toFixed(): string; + /** Returns a string representing the value of this Big number in normal notation to a fixed number of decimal places dp. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted, or is null or undefined, then the return value is simply the value in normal notation. This is also unlike Number.prototype.toFixed, which returns the value to zero decimal places. */ + toFixed(dp: number): string; + + /** Returns a string representing the value of this Big number to the specified number of significant digits sd. */ + toPrecision(): string; + /** Returns a string representing the value of this Big number to the specified number of significant digits sd. + @param sd significant digits. If sd is omitted, or is null or undefined, then the return value is the same as .toString(). */ + toPrecision(sd: number /** number of significant digits (0 to 1e+6 inclusive) */): string; + + /** Returns a string representing the value of this Big number. */ + toString(): string; + + /** As toString. */ + valueOf(): string; + + /** As toString. */ + toJSON(): string; + + /** coefficient (significand) */ + c: number[]; + + /** exponent (Integer, -1e+6 to 1e+6 inclusive) */ + e: number; + + /** sign (-1 or 1) */ + s: number; + } +} + +declare var Big: BigJsLibrary.BigJS; \ No newline at end of file diff --git a/bl/bl-tests.ts b/bl/bl-tests.ts new file mode 100644 index 0000000000..b8435911de --- /dev/null +++ b/bl/bl-tests.ts @@ -0,0 +1,68 @@ +/// + +import BufferList = require('bl'); + +var bl: BufferList; +var buffer: Buffer; +var offset: number; +var num: number; +var str: string; +var noAssert: boolean; + +bl = new BufferList(); +bl = new BufferList((err:Error, buffer:Buffer) => { + +}); + +bl.append(buffer); +num = bl.get(num); + +buffer = bl.slice(num, num); +buffer = bl.slice(num); +buffer = bl.slice(); + +bl.copy(buffer, num, num, num); +bl.copy(buffer, num, num); +bl.copy(buffer, num); +bl.copy(buffer); + +bl = bl.duplicate(); + +bl.consume(); +bl.consume(num); + +str = bl.toString(str, num, num); +str = bl.toString(str, num); +str = bl.toString(str); +str = bl.toString(); + +num = bl.length; + +num = bl.readDoubleBE(offset, noAssert); +num = bl.readDoubleBE(offset); +num = bl.readDoubleLE(offset, noAssert); +num = bl.readDoubleLE(offset); +num = bl.readFloatBE(offset, noAssert); +num = bl.readFloatBE(offset); +num = bl.readFloatLE(offset, noAssert); +num = bl.readFloatLE(offset); +num = bl.readInt32BE(offset, noAssert); +num = bl.readInt32BE(offset); +num = bl.readInt32LE(offset, noAssert); +num = bl.readInt32LE(offset); +num = bl.readUInt32BE(offset, noAssert); +num = bl.readUInt32BE(offset); +num = bl.readUInt32LE(offset, noAssert); +num = bl.readUInt32LE(offset); +num = bl.readInt16BE(offset, noAssert); +num = bl.readInt16BE(offset); +num = bl.readInt16LE(offset, noAssert); +num = bl.readInt16LE(offset); +num = bl.readUInt16BE(offset, noAssert); +num = bl.readUInt16BE(offset); +num = bl.readUInt16LE(offset, noAssert); +num = bl.readUInt16LE(offset); +num = bl.readInt8(offset, noAssert); +num = bl.readInt8(offset); +num = bl.readUInt8(offset, noAssert); +num = bl.readUInt8(offset); diff --git a/bl/bl.d.ts b/bl/bl.d.ts new file mode 100644 index 0000000000..6e8c3b4a87 --- /dev/null +++ b/bl/bl.d.ts @@ -0,0 +1,40 @@ +// Type definitions for BufferList v0.8.0 +// Project: https://github.com/rvagg/bl +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'bl' { + import stream = require('stream'); + + class BufferList extends stream.Duplex { + new (callback?:(err:Error, buffer:Buffer) => void): void; + + append(buffer: Buffer):void; + get(index: number): number; + slice(start?: number, end?: number): Buffer; + copy(dest: Buffer, destStart?: number, srcStart?: number, srcEnd?: number): void; + duplicate(): BufferList; + consume(bytes?: number): void; + toString(encoding?: string, start?: number, end?: number): string; + length: number; + + readDoubleBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + } + + export = BufferList; +} diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts new file mode 100644 index 0000000000..994aa4e1b4 --- /dev/null +++ b/body-parser/body-parser.d.ts @@ -0,0 +1,138 @@ +// Type definitions for body-parser +// Project: http://expressjs.com +// Definitions by: Santi Albo , VILIC VANE , Jonathan Häberle +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "body-parser" { + import express = require('express'); + + /** + * bodyParser: use individual json/urlencoded middlewares + * @deprecated + */ + + function bodyParser(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * only parse objects and arrays. (default: true) + */ + strict?: boolean; + /** + * passed to JSON.parse(). + */ + receiver?: (key: string, value: any) => any; + /** + * parse extended syntax with the qs module. (default: true) + */ + extended?: boolean; + }): express.RequestHandler; + + module bodyParser { + export function json(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'json') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * only parse objects and arrays. (default: true) + */ + strict?: boolean; + /** + * passed to JSON.parse(). + */ + receiver?: (key: string, value: any) => any; + }): express.RequestHandler; + + export function raw(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'application/octet-stream') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + }): express.RequestHandler; + + export function text(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'text/plain') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * the default charset to parse as, if not specified in content-type. (default: 'utf-8') + */ + defaultCharset?: string; + }): express.RequestHandler; + + export function urlencoded(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'urlencoded') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * parse extended syntax with the qs module. (default: true) + */ + extended?: boolean; + }): express.RequestHandler; + } + + export = bodyParser; +} \ No newline at end of file diff --git a/bootstrap.datepicker/bootstrap.datepicker.d.ts b/bootstrap.datepicker/bootstrap.datepicker.d.ts index 41f2fcd253..da0ec1ab3d 100644 --- a/bootstrap.datepicker/bootstrap.datepicker.d.ts +++ b/bootstrap.datepicker/bootstrap.datepicker.d.ts @@ -5,6 +5,15 @@ /// +/** + * All options that take a “Date” can handle a Date object; a String + * formatted according to the given format; or a timedelta relative + * to today, eg “-1d”, “+6m +1y”, etc, where valid units are “d” (day), + * “w” (week), “m” (month), and “y” (year). + * + * See online docs for more info: + * http://bootstrap-datepicker.readthedocs.org/en/release/options.html + */ interface DatepickerOptions { format?: string; weekStart?: number; @@ -16,11 +25,21 @@ interface DatepickerOptions { todayHighlight?: boolean; keyboardNavigation?: boolean; language?: string; + beforeShowDay?: (date: any) => any; + calendarWeeks?: boolean; + clearBtn?: boolean; + daysOfWeekDisabled?: number[]; + forceParse?: boolean; + inputs?: any[]; + minViewMode?: any; + multidate?: any; + multidateSeparator?: string; + orientation?: string; } interface DatepickerEventObject extends JQueryEventObject { - date: Date; - format(format?: string): string; + date: Date; + format(format?: string): string; } interface JQuery { @@ -29,10 +48,10 @@ interface JQuery { datepicker(methodName: string, params: any): JQuery; datepicker(options: DatepickerOptions): JQuery; - off(events: "changeDate", selector?: string, handler?: (eventObject: DatepickerEventObject) => any): JQuery; - off(events: "changeDate", handler: (eventObject: DatepickerEventObject) => any): JQuery; + off(events: "changeDate", selector?: string, handler?: (eventObject: DatepickerEventObject) => any): JQuery; + off(events: "changeDate", handler: (eventObject: DatepickerEventObject) => any): JQuery; - on(events: "changeDate", selector: string, data: any, handler?: (eventObject: DatepickerEventObject) => any): JQuery; - on(events: "changeDate", selector: string, handler: (eventObject: DatepickerEventObject) => any): JQuery; - on(events: 'changeDate', handler: (eventObject: DatepickerEventObject) => any): JQuery; + on(events: "changeDate", selector: string, data: any, handler?: (eventObject: DatepickerEventObject) => any): JQuery; + on(events: "changeDate", selector: string, handler: (eventObject: DatepickerEventObject) => any): JQuery; + on(events: 'changeDate', handler: (eventObject: DatepickerEventObject) => any): JQuery; } diff --git a/bootstrap.v3.datetimepicker/boostrap.v3.datetimepicker-tests.ts b/bootstrap.v3.datetimepicker/boostrap.v3.datetimepicker-tests.ts new file mode 100644 index 0000000000..6abf38f946 --- /dev/null +++ b/bootstrap.v3.datetimepicker/boostrap.v3.datetimepicker-tests.ts @@ -0,0 +1,31 @@ +/// +/// + +function test_cases() { + $('#datetimepicker').datetimepicker(); + $('#datetimepicker').datetimepicker({ + pickDate: false + }); + $('#datetimepicker').datetimepicker({ + pickTime: false + }); + $('#datetimepicker').datetimepicker({ + minDate: '2012-12-31' + }); + + $('#datetimepicker').data("DateTimePicker").setMaxDate('2012-12-31'); + + var startDate = new Date(2012, 1, 20); + var endDate = new Date(2012, 1, 25); + $('#datetimepicker2') + .datetimepicker() + .on("dp.change", function (ev) { + if (ev.date.valueOf() > endDate.valueOf()) { + $('#alert').show().find('strong').text('The start date must be before the end date.'); + } else { + $('#alert').hide(); + startDate = ev.date; + $('#date-start-display').text($('#date-start').data('date')); + } + }); +} \ No newline at end of file diff --git a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker.d.ts b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker.d.ts new file mode 100644 index 0000000000..6f1147cc11 --- /dev/null +++ b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker.d.ts @@ -0,0 +1,100 @@ +// Type definitions for Bootstrap datetimepicker v3 +// Project: http://eonasdan.github.io/bootstrap-datetimepicker +// Definitions by: Jesica N. Fera +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** + * bootstrap-datetimepicker.js 3.0.0 Copyright (c) 2014 Jonathan Peterson + * Available via the MIT license. + * see: http://eonasdan.github.io/bootstrap-datetimepicker or https://github.com/Eonasdan/bootstrap-datetimepicker for details. + */ + +/// + +declare module BootstrapV3DatetimePicker { + interface DatetimepickerChangeEventObject extends JQueryEventObject { + date: any; + oldDate: any; + } + + interface DatetimepickerEventObject extends JQueryEventObject { + date: any; + } + + interface DatetimepickerIcons { + time?: string; + date?: string; + up?: string; + down?: string; + } + + interface DatetimepickerOptions { + pickDate?: boolean; + pickTime?: boolean; + useMinutes?: boolean; + useSeconds?: boolean; + useCurrent?: boolean; + minuteStepping?: number; + minDate?: any; + maxDate?: any; + showToday?: boolean; + collapse?: boolean; + language?: string; + defaultDate?: string; + disabledDates?: Array; + enabledDates?: Array; + icons?: DatetimepickerIcons; + useStrict?: boolean; + direction?: string; + sideBySide?: boolean; + daysOfWeekDisabled?: Array; + } + + interface Datetimepicker { + setDate(date: any): void; + setMinDate(date: any): void; + setMaxDate(date: any): void; + show(): void; + disable(): void; + enable(): void; + getDate(): void; + } + +} + + +interface JQuery { + + datetimepicker(): JQuery; + datetimepicker(options: BootstrapV3DatetimePicker.DatetimepickerOptions): JQuery; + + off(events: "dp.change", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; + off(events: "dp.change", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; + + on(events: "dp.change", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; + on(events: "dp.change", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; + on(events: 'dp.change', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; + + off(events: "dp.show", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + off(events: "dp.show", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + + on(events: "dp.show", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: "dp.show", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: 'dp.show', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + + off(events: "dp.hide", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + off(events: "dp.hide", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + + on(events: "dp.hide", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: "dp.hide", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: 'dp.hide', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + + off(events: "dp.error", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + off(events: "dp.error", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + + on(events: "dp.error", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: "dp.error", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: 'dp.error', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + + data(key: 'DateTimePicker'): BootstrapV3DatetimePicker.Datetimepicker; +} \ No newline at end of file diff --git a/breeze/breeze.d.ts b/breeze/breeze.d.ts index 3614e34461..fab5dd0772 100644 --- a/breeze/breeze.d.ts +++ b/breeze/breeze.d.ts @@ -382,7 +382,7 @@ declare module breeze { executeQuery(query: EntityQuery, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Q.Promise; executeQueryLocally(query: EntityQuery): Entity[]; - exportEntities(entities?: Entity[]): string; + exportEntities(entities?: Entity[], includeMetadata?: boolean): string; fetchEntityByKey(typeName: string, keyValue: any, checkLocalCacheFirst?: boolean): Q.Promise; fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: boolean): Q.Promise; fetchEntityByKey(entityKey: EntityKey, checkLocalCacheFirst?: boolean): Q.Promise; @@ -877,7 +877,7 @@ declare module breeze.config { var dataService: string; var functionRegistry: Object; export function getAdapter(interfaceName: string, adapterName: string): Object; - export function getAdapterInstance(interfaceName: string, adapterName: string): Object; + export function getAdapterInstance(interfaceName: string, adapterName?: string): Object; export function initializeAdapterInstance(interfaceName: string, adapterName: string, isDefault: boolean): void; export function initializeAdapterInstances(config: Object): void; var interfaceInitialized: Event; diff --git a/browser-harness/browser-harness.d.ts b/browser-harness/browser-harness.d.ts index 68dbf8be51..a960741649 100644 --- a/browser-harness/browser-harness.d.ts +++ b/browser-harness/browser-harness.d.ts @@ -6,27 +6,28 @@ /// declare module "browser-harness" { + import _events = require('events'); - interface HarnessEvents extends NodeEventEmitter { - once(event: string, listener: (driver: Driver) => void): NodeEventEmitter; - once(event: 'ready', listener: (driver: Driver) => void): NodeEventEmitter; + interface HarnessEvents extends _events.EventEmitter { + once(event: string, listener: (driver: Driver) => void): _events.EventEmitter; + once(event: 'ready', listener: (driver: Driver) => void): _events.EventEmitter; - on(event: string, listener: (driver: Driver) => void): NodeEventEmitter; - on(event: 'ready', listener: (driver: Driver) => void): NodeEventEmitter; + on(event: string, listener: (driver: Driver) => void): _events.EventEmitter; + on(event: 'ready', listener: (driver: Driver) => void): _events.EventEmitter; } - interface DriverEvents extends NodeEventEmitter { - once(event: string, listener: (text: string) => void): NodeEventEmitter; - once(event: 'console.log', listener: (text: string) => void): NodeEventEmitter; - once(event: 'console.warn', listener: (text: string) => void): NodeEventEmitter; - once(event: 'console.error', listener: (text: string) => void): NodeEventEmitter; - once(event: 'window.onerror', listener: (text: string) => void): NodeEventEmitter; + interface DriverEvents extends _events.EventEmitter { + once(event: string, listener: (text: string) => void): _events.EventEmitter; + once(event: 'console.log', listener: (text: string) => void): _events.EventEmitter; + once(event: 'console.warn', listener: (text: string) => void): _events.EventEmitter; + once(event: 'console.error', listener: (text: string) => void): _events.EventEmitter; + once(event: 'window.onerror', listener: (text: string) => void): _events.EventEmitter; - on(event: string, listener: (text: string) => void): NodeEventEmitter; - on(event: 'console.log', listener: (text: string) => void): NodeEventEmitter; - on(event: 'console.warn', listener: (text: string) => void): NodeEventEmitter; - on(event: 'console.error', listener: (text: string) => void): NodeEventEmitter; - on(event: 'window.onerror', listener: (text: string) => void): NodeEventEmitter; + on(event: string, listener: (text: string) => void): _events.EventEmitter; + on(event: 'console.log', listener: (text: string) => void): _events.EventEmitter; + on(event: 'console.warn', listener: (text: string) => void): _events.EventEmitter; + on(event: 'console.error', listener: (text: string) => void): _events.EventEmitter; + on(event: 'window.onerror', listener: (text: string) => void): _events.EventEmitter; } export interface Driver { diff --git a/browserify/browserify.d.ts b/browserify/browserify.d.ts index e725de98c8..02ac29bf28 100644 --- a/browserify/browserify.d.ts +++ b/browserify/browserify.d.ts @@ -5,7 +5,7 @@ /// -interface BrowserifyObject extends NodeEventEmitter { +interface BrowserifyObject extends NodeJS.EventEmitter { add(file: string): BrowserifyObject; require(file: string, opts?: { expose: string; @@ -16,12 +16,14 @@ interface BrowserifyObject extends NodeEventEmitter { debug?: boolean; standalone?: string; insertGlobalVars?: any; - }, cb?: (err: any, src: any) => void): ReadableStream; + }, cb?: (err: any, src: any) => void): NodeJS.ReadableStream; external(file: string): BrowserifyObject; ignore(file: string): BrowserifyObject; transform(tr: string): BrowserifyObject; transform(tr: Function): BrowserifyObject; + plugin(plugin: string, opts?: any): BrowserifyObject; + plugin(plugin: Function, opts?: any): BrowserifyObject; } declare module "browserify" { @@ -33,4 +35,4 @@ declare module "browserify" { }): BrowserifyObject; export = browserify; -} \ No newline at end of file +} diff --git a/bucks/bucks-test.ts b/bucks/bucks-test.ts new file mode 100644 index 0000000000..5ebbd882cf --- /dev/null +++ b/bucks/bucks-test.ts @@ -0,0 +1,222 @@ +/// + +function add_and_end() { + // + // new Bucks object + // + var b = new Bucks(); + + // + // Add and add several tasks. + // + b.add(function f1(err, res) { + + return 'a'; + + }).add(function f2(err, res, next) { + + // res => 'a' + return next(null, 3); + + }).add(function f3(err, res, next) { + + // res => 3 + return next(new Error('error after 3')); + + }).add(function f4(err, res, next) { + + // err => 'error after 3' + return next(null, "recover 4"); + + }).add(function f5(err, res) { + + // res => 'recover 4' + throw new Error('error in f5'); + + }).add(function f6(err, res) { + + // err => 'error in f5' + throw err; + + }).add(function f7(err, res) { + + // err => 'error in f5' + // ignore and return + return "recover 7"; + + }).add(function f8(err, res, next) { + + // res => 'recover 7'; + throw new Error('error in f8'); + + }).add(function f9(err, res, next) { + + // err => 'Error in f8' + // ignore error + return next(null, 'result of 9'); + + }).end(function last(err, results) { + + // all of results + // are obtained in #end + + // err => null + + // results => [ + // 'a', + // null, + // null, + // 'recover 4', + // null, + // null, + // 'recover 7', + // null, + // 'result of 9' + // ]; + }); +} + +function then() { + var b = new Bucks(); + b.then(function start() { + return 'start'; + }).then(function second(res, next) { + // res => 'start' + return next(null, 'second') + }).end(); +} + +function delay() { + var b = new Bucks(); + b.add(function (){ /** program */ }) + .delay(1 * 1000) // 1ms + .add(function() { /** program */}) + .end(); +} + +function error() { + var b = new Bucks(); + b.then(function start() { + throw new Error('error in start'); + return 'start'; + }).error(function onError(e, next) { + // e => 'error in start' + return next(); + }).end(); +} + +function final_errorback_in_end() { + // + // last error back + // + var b = new Bucks(); + b.empty( + // add empty task (#end with no task cause error) + ).end(function last(err, res) { + // error in last callback + throw new Error('error in end'); + }, function finalErrorback(err) { + // catch uncaught error in last callback + // err => 'error in end' + }); +} + +function uncaught_error() { + try { + var b = new Bucks(); + b.then(function () { + throw new Error('error'); + }).end(); + } catch(e) { + // e => 'error' + } +} + +function waterfall() { + var t1: Bucks.Task = function t1(err, res) { + return 't1'; + }; + var t2: Bucks.Task = function t2(err, res) { + return 't2'; + }; + + new Bucks().waterfall([t1, t2]).end(function finish(err, ress) { + // ress => ['t1', 't2'] + }); + + // same as + new Bucks().add(t1).add(t2).end(function finish(err, ress) { + // ress => ['t1', 't2'] + }); +} + +function parallel() { + var b = new Bucks(); + + b.parallel([ + function task1(err, res) { + return "task1"; + }, + function task2(err, res, next) { + return next(null, "task2"); + }, + function task3(err, res, next) { + return next(new Error('passed error in task3')); + }, + function task4(err, res, next) { + throw new Error('thrown error in task4'); + } + ]).add(function getResults(err, res, next) { + // res => { + // err: [ + // null, + // null, + // [Error: passed error in task3], + // [Error: thrown error in task4] + // ], + // res: [ + // 'task1', + // 'task2', + // null, + // null + // ] + // } + next(); + }).end(); +} + +function onError() { + var onError = function (e: Error, bucks: Bucks.Bucks) { + console.log("Custom onError"); + }; + + // Bucks.onError!! + Bucks.onError(onError); + var b0 = new Bucks(); + b0 + .add(function(err, next) { + throw new Error('b0'); + }) + .end() + ; +} + +function dispose() { + var b0 = new Bucks(); + + b0.dispose = function dispose () { + // delete b0.dummy; + } + + b0 + .add(function(err, next) { + // b0.dummy = "dummy"; + next(); + }) + .end(null, null) + ; +} + +function debug() { + Bucks.DEBUG = true; +} diff --git a/bucks/bucks.d.ts b/bucks/bucks.d.ts new file mode 100644 index 0000000000..cac3c71217 --- /dev/null +++ b/bucks/bucks.d.ts @@ -0,0 +1,113 @@ +// Type definitions for bucks.js 0.8.3 +// Project: https://github.com/CyberAgent/bucks.js +// Definitions by: Shunsuke Ohtani +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Bucks { + + interface BucksStatic { + + /** + * bucks.js version. + */ + VERSION: string; + + /** + * If set `true`, uncaught errors are logged. + */ + DEBUG: boolean; + + /** + * Running bucks objects. + */ + running: Bucks[]; + + /** + * Not yet called `end` bucks object. + */ + living: Bucks[]; + + /** + * Create bucks object. + */ + new(): Bucks; + + /** + * Catch all errors. + * @param onError Function called after catching error + */ + onError(onError: (err:Error, bucks:Bucks)=>any): void; + } + + interface Bucks { + + /** + * Add a task. + * @param task Function added async chain + */ + add(task: TaskWithNext): Bucks; + + /** + * Add a task called only in case of success. + * @param onSuccess Function called only in case of success + */ + then(onSuccess: (res:any, next?:Task)=>any): Bucks; + + /** + * Add a empty task. + */ + empty(): Bucks; + + /** + * Add a task called only in case of error. + * @param onError Function called only in case of error + */ + error(onError: (err:Error, next?:Task)=>any): Bucks; + + /** + * Add tasks in asynchronous way and join their results. + * @param tasks Functions called in asynchronous way and join their results + */ + parallel(tasks: TaskWithNext[]): Bucks; + + /** + * Add tasks in asynchronous way and join their results. + * @param tasks Functions added async chain + */ + waterfall(tasks: TaskWithNext[]): Bucks; + + /** + * Add delay execution. + * @param ms number millisecond for delaying + */ + delay(ms: number): Bucks; + + /** + * Called when destroy async chain. + */ + dispose(): void; + + /** + * Destroy this object and call last callback function. + * @param err If specify err and no callback, throw to execute failure callback + */ + destroy(err?: Error): Bucks; + + /** + * Complete creating async chain and start executing. + * @param callback Last callback function + * @param errback Handler for occurring error in last callback function + */ + end(callback?: Task, errback?: (err:Error)=>any): void; + } + + interface TaskWithNext { + (err?: Error, res?: any, next?: Task): any; + } + + interface Task { + (err?: Error, res?: any): any; + } +} + +declare var Bucks: Bucks.BucksStatic; diff --git a/buffer-equal/buffer-equal-tests.ts b/buffer-equal/buffer-equal-tests.ts index 743ed187ec..192051ab47 100644 --- a/buffer-equal/buffer-equal-tests.ts +++ b/buffer-equal/buffer-equal-tests.ts @@ -3,6 +3,6 @@ import bufferEqual = require('buffer-equal'); var bool: boolean; -var buf: NodeBuffer; +var buf: Buffer; bool = bufferEqual(buf, buf); diff --git a/buffer-equal/buffer-equal.d.ts b/buffer-equal/buffer-equal.d.ts index bc8b1ce28e..a3597c6847 100644 --- a/buffer-equal/buffer-equal.d.ts +++ b/buffer-equal/buffer-equal.d.ts @@ -1,11 +1,11 @@ // Type definitions for buffer-equal 1.0 0 -// Project: https://github.com/chaijs/assertion-error +// Project: https://github.com/substack/node-buffer-equal // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare module 'buffer-equal' { - function bufferEqual(actual:NodeBuffer, expected:NodeBuffer): boolean; + function bufferEqual(actual:Buffer, expected:Buffer): boolean; export = bufferEqual; } diff --git a/bufferstream/bufferstream-tests.ts b/bufferstream/bufferstream-tests.ts new file mode 100644 index 0000000000..fe1ea70aa9 --- /dev/null +++ b/bufferstream/bufferstream-tests.ts @@ -0,0 +1,14 @@ +/// + +import BufferStream = require('bufferstream') + +var stream = new BufferStream({encoding:'utf8', size:'flexible'}); +stream.enable(); +stream.disable(); +stream.split('//', ':'); +stream.on('split', (chunk: any, token: any) => { + console.log("got '%s' by '%s'", chunk.toString(), token.toString()) +}); +stream.write("buffer:stream//23"); +console.log(stream.toString()); + diff --git a/bufferstream/bufferstream.d.ts b/bufferstream/bufferstream.d.ts new file mode 100644 index 0000000000..5323103e27 --- /dev/null +++ b/bufferstream/bufferstream.d.ts @@ -0,0 +1,119 @@ +// Type definitions for bufferstream v0.6.2 +// Project: https://github.com/dodo/node-bufferstream +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'bufferstream' { + import stream = require('stream'); + + export = BufferStream; + + class BufferStream extends stream.Duplex { + constructor(options?: BufferStream.Opts); + + /* + different buffer behaviors can be triggered by size: + + none when output drains, bufferstream drains too + flexible buffers everthing that it gets and not piping out + TODO buffer has given size. buffers everthing until buffer is full. when buffer is full then the stream will drain + */ + setSize(size: string): void; // can be one of ['none', 'flexible', ] + setSize(size: number): void; // can be one of ['none', 'flexible', ] + /* + enables stream buffering default + */ + enable(): void; + /* + flushes buffer and disables stream buffering. BufferStream now pipes all data as long as the output accepting data. when the output is draining BufferStream will buffer all input temporary. + + token[s] buffer splitters (should be String or Buffer) + + disables given tokens. wont flush until no splitter tokens are left. + */ + disable(): void; + disable(token: string, ...tokens: string[]): void; + disable(tokens: string[]): void; // Array + disable(token: Buffer, ...tokens: Buffer[]): void; + disable(tokens: Buffer[]): void; // Array + /* + each time BufferStream finds a splitter token in the input data it will emit a split event. this also works for binary data. + + token[s] buffer splitters (should be String or Buffer) + */ + split(token: string, ...tokens: string[]): void; + split(tokens: string[]): void; // Array + split(token: Buffer, ...tokens: Buffer[]): void; + split(tokens: Buffer[]): void; // Array + /* + returns Buffer. + */ + getBuffer(): Buffer; + /* + returns Buffer. + */ + buffer: Buffer; + /* + shortcut for buffer.toString() + */ + toString(): string; + /* + shortcut for buffer.length + */ + length: number; + } + module BufferStream { + + export interface Opts { + /* + default encoding for writing strings + */ + encoding?: string; + /* + if true and the source is a child_process the stream will block the entire process (timeouts wont work anymore, but splitting and listening on data still works, because they work sync) + */ + blocking?: boolean; + /* + defines buffer level or sets buffer to given size (see ↓setSize for more) + */ + size?: any; + /* + immediately call disable + */ + disabled?: boolean; + /* + short form for: + split(token, function (chunk) {emit('data', chunk)}) + */ + // String or Buffer + split?: any; + } + export var fn: {warn: boolean}; + } +} + +declare module 'bufferstream/postbuffer' { + import http = require('http'); + import BufferStream = require('bufferstream'); + + class PostBuffer extends BufferStream { + /* + for if you want to get all the post data from a http server request and do some db reqeust before. + + http client buffer + */ + constructor(req: http.ServerRequest); + /* + set a callback to get all post data from a http server request + */ + onEnd(callback: (data: any) => void): void; + /* + pumps data into another stream to allow incoming streams given options will be passed to Stream.pipe + */ + pipe(stream: NodeJS.WritableStream, options?: BufferStream.Opts): NodeJS.ReadableStream; + } + + export = PostBuffer; +} diff --git a/camljs/camljs.d.ts b/camljs/camljs.d.ts index 7cfba8a40d..0127b3e1dc 100644 --- a/camljs/camljs.d.ts +++ b/camljs/camljs.d.ts @@ -102,6 +102,10 @@ declare module CamlBuilder { All(...conditions: IExpression[]): IExpression; /** Adds Or clauses to the query. Use for creating bracket-expressions in conjuction with CamlBuilder.Expression(). */ Any(...conditions: IExpression[]): IExpression; + /** Adds And clauses to the query. Use for creating bracket-expressions in conjuction with CamlBuilder.Expression(). */ + All(conditions: IExpression[]): IExpression; + /** Adds Or clauses to the query. Use for creating bracket-expressions in conjuction with CamlBuilder.Expression(). */ + Any(conditions: IExpression[]): IExpression; /** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is Text */ TextField(internalName: string): ITextFieldExpression; /** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is Boolean */ diff --git a/chai-datetime/chai-datetime-tests.ts b/chai-datetime/chai-datetime-tests.ts new file mode 100644 index 0000000000..8f8238b4ee --- /dev/null +++ b/chai-datetime/chai-datetime-tests.ts @@ -0,0 +1,47 @@ +/// +/// + +var expect = chai.expect; +var assert = chai.assert; + +function test_equalTime(){ + var date: Date = new Date(2014, 1, 1); + expect(date).to.be.equalTime(date); + date.should.be.equalTime(date); + assert.equalTime(date, date); +} + +function test_beforeTime(){ + var date: Date = new Date(2014, 1, 1); + expect(date).to.be.beforeTime(date); + date.should.be.beforeTime(date); + assert.beforeTime(date, date); +} + +function test_afterTime(){ + var date: Date = new Date(2014, 1, 1); + expect(date).to.be.afterTime(date); + date.should.be.afterTime(date); + assert.afterTime(date, date); +} + +function test_equalDate(){ + var date: Date = new Date(2014, 1, 1); + expect(date).to.equalDate(date); + date.should.equalDate(date); + assert.equalDate(date, date); +} + +function test_beforeDate(){ + var date: Date = new Date(2014, 1, 1); + expect(date).to.beforeDate(date); + date.should.beforeDate(date); + assert.beforeDate(date, date); +} + +function test_afterDate(){ + var date: Date = new Date(2014, 1, 1); + expect(date).to.afterDate(date); + date.should.afterDate(date); + assert.afterDate(date, date); +} diff --git a/chai-datetime/chai-datetime.d.ts b/chai-datetime/chai-datetime.d.ts new file mode 100644 index 0000000000..bce063443a --- /dev/null +++ b/chai-datetime/chai-datetime.d.ts @@ -0,0 +1,39 @@ +// Type definitions for chai-datetime +// Project: https://github.com/gaslight/chai-datetime.git +// Definitions by: Cliff Burger +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module chai { + + interface Expect { + afterDate(date: Date): boolean; + beforeDate(date: Date): boolean; + equalDate(date: Date): boolean; + + afterTime(date: Date): boolean; + beforeTime(date: Date): boolean; + equalTime(date: Date): boolean; + } + + interface Assert { + equalTime(val: Date, exp: Date, msg?: string): boolean; + notEqualTime(val: Date, exp: Date, msg?: string): boolean; + beforeTime(val: Date, exp: Date, msg?: string): boolean; + notBeforeTime(val: Date, exp: Date, msg?: string): boolean; + afterTime(val: Date, exp: Date, msg?: string): boolean; + notAfterTime(val: Date, exp: Date, msg?: string): boolean; + + equalDate(val: Date, exp: Date, msg?: string): boolean; + notEqualDate(val: Date, exp: Date, msg?: string): boolean; + beforeDate(val: Date, exp: Date, msg?: string): boolean; + notBeforeDate(val: Date, exp: Date, msg?: string): boolean; + afterDate(val: Date, exp: Date, msg?: string): boolean; + notAfterDate(val: Date, exp: Date, msg?: string): boolean; + } +} + +interface Date { + should: chai.Expect; +} diff --git a/chai-fuzzy/chai-fuzzy-assert.d.ts.tscparams b/chai-fuzzy/chai-fuzzy-assert.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/chai-fuzzy/chai-fuzzy-assert.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/chai-fuzzy/chai-fuzzy-assert.d.ts b/chai-fuzzy/chai-fuzzy.d.ts similarity index 91% rename from chai-fuzzy/chai-fuzzy-assert.d.ts rename to chai-fuzzy/chai-fuzzy.d.ts index f75f99d559..0cbb1741b9 100644 --- a/chai-fuzzy/chai-fuzzy-assert.d.ts +++ b/chai-fuzzy/chai-fuzzy.d.ts @@ -3,7 +3,7 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare module chai { interface Assert { @@ -14,4 +14,4 @@ declare module chai { jsonOf(act:any, exp:any, msg?:string); notJsonOf(act:any, exp:any, msg?:string); } -} \ No newline at end of file +} diff --git a/arbiter/Arbiter-tests.ts.tscparams b/chai-fuzzy/chai-fuzzy.d.ts.tscparams similarity index 100% rename from arbiter/Arbiter-tests.ts.tscparams rename to chai-fuzzy/chai-fuzzy.d.ts.tscparams diff --git a/chai-jquery/chai-jquery.d.ts b/chai-jquery/chai-jquery.d.ts index 52fd4f3f5f..826e665792 100644 --- a/chai-jquery/chai-jquery.d.ts +++ b/chai-jquery/chai-jquery.d.ts @@ -1,7 +1,7 @@ // Type definitions for chai-jquery 1.1.1 // Project: https://github.com/chaijs/chai-jquery // Definitions by: Kazi Manzur Rashid -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/chai-jquery/chai-jquery.d.ts.tscparams b/chai-jquery/chai-jquery.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/chai-jquery/chai-jquery.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/chai/chai-assert-tests.ts b/chai/chai-assert-tests.ts deleted file mode 100644 index 19429b4c92..0000000000 --- a/chai/chai-assert-tests.ts +++ /dev/null @@ -1,671 +0,0 @@ -/* - ---------- - test extracted from original test suite - chai original licence follows ---------- - -## License - -(The MIT License) - -Copyright (c) 2011-2013 Jake Luer - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -/// - -//stubs -declare module chai { - var AssertionError; - function expect(body):any; -} -//tdd -declare function suite(description, action):void; -declare function test(description, action):void; -declare function err(action, msg?):void; -interface FieldObj { - field: any; -} - -suite('assert', function () { - - test('assert', function () { - var foo = 'bar'; - assert(foo == 'bar', "expected foo to equal `bar`"); - - err(function () { - assert(foo == 'baz', "expected foo to equal `bar`"); - }, "expected foo to equal `bar`"); - }); - - test('fail', function () { - chai.expect(function () { - assert.fail(); - }).to.throw(chai.AssertionError); - }); - - test('isTrue', function () { - assert.isTrue(true); - - err(function () { - assert.isTrue(false); - }, "expected false to be true"); - - err(function () { - assert.isTrue(1); - }, "expected 1 to be true"); - - err(function () { - assert.isTrue('test'); - }, "expected 'test' to be true"); - }); - - test('ok', function () { - assert.ok(true); - assert.ok(1); - assert.ok('test'); - - err(function () { - assert.ok(false); - }, "expected false to be truthy"); - - err(function () { - assert.ok(0); - }, "expected 0 to be truthy"); - - err(function () { - assert.ok(''); - }, "expected '' to be truthy"); - }); - - test('isFalse', function () { - assert.isFalse(false); - - err(function () { - assert.isFalse(true); - }, "expected true to be false"); - - err(function () { - assert.isFalse(0); - }, "expected 0 to be false"); - }); - - test('equal', function () { - var foo; - assert.equal(foo, undefined); - }); - - test('typeof / notTypeOf', function () { - assert.typeOf('test', 'string'); - assert.typeOf(true, 'boolean'); - assert.typeOf(5, 'number'); - - err(function () { - assert.typeOf(5, 'string'); - }, "expected 5 to be a string"); - - }); - - test('notTypeOf', function () { - assert.notTypeOf('test', 'number'); - - err(function () { - assert.notTypeOf(5, 'number'); - }, "expected 5 not to be a number"); - }); - - test('instanceOf', function () { - function Foo() { - } - - assert.instanceOf(new Foo(), Foo); - - err(function () { - assert.instanceOf(5, Foo); - }, "expected 5 to be an instance of Foo"); - - function CrashyObject() { - }; - CrashyObject.prototype.inspect = function () { - throw new Error("Arg's inspect() called even though the test passed"); - }; - assert.instanceOf(new CrashyObject(), CrashyObject); - }); - - test('notInstanceOf', function () { - function Foo() { - } - - assert.notInstanceOf(new Foo(), String); - - err(function () { - assert.notInstanceOf(new Foo(), Foo); - }, "expected {} to not be an instance of Foo"); - }); - - test('isObject', function () { - function Foo() { - } - - assert.isObject({}); - assert.isObject(new Foo()); - - err(function () { - assert.isObject(true); - }, "expected true to be an object"); - - err(function () { - assert.isObject(Foo); - }, "expected [Function: Foo] to be an object"); - - err(function () { - assert.isObject('foo'); - }, "expected 'foo' to be an object"); - }); - - test('isNotObject', function () { - function Foo() { - } - - assert.isNotObject(5); - - err(function () { - assert.isNotObject({}); - }, "expected {} not to be an object"); - }); - - test('notEqual', function () { - assert.notEqual(3, 4); - - err(function () { - assert.notEqual(5, 5); - }, "expected 5 to not equal 5"); - }); - - test('strictEqual', function () { - assert.strictEqual('foo', 'foo'); - - err(function () { - assert.strictEqual('5', 5); - }, "expected \'5\' to equal 5"); - }); - - test('notStrictEqual', function () { - assert.notStrictEqual(5, '5'); - - err(function () { - assert.notStrictEqual(5, 5); - }, "expected 5 to not equal 5"); - }); - - test('deepEqual', function () { - assert.deepEqual({tea: 'chai'}, {tea: 'chai'}); - - err(function () { - assert.deepEqual({tea: 'chai'}, {tea: 'black'}); - }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); - - var obja = Object.create({ tea: 'chai' }) - , objb = Object.create({ tea: 'chai' }); - - assert.deepEqual(obja, objb); - - var obj1 = Object.create({tea: 'chai'}) - , obj2 = Object.create({tea: 'black'}); - - err(function () { - assert.deepEqual(obj1, obj2); - }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); - }); - - test('deepEqual (ordering)', function () { - var a = { a: 'b', c: 'd' } - , b = { c: 'd', a: 'b' }; - assert.deepEqual(a, b); - }); - - test('deepEqual (circular)', function () { - var circularObject:any = {} - , secondCircularObject:any = {}; - circularObject.field = circularObject; - secondCircularObject.field = secondCircularObject; - - assert.deepEqual(circularObject, secondCircularObject); - - err(function () { - secondCircularObject.field2 = secondCircularObject; - assert.deepEqual(circularObject, secondCircularObject); - }, "expected { field: [Circular] } to deeply equal { Object (field, field2) }"); - }); - - test('notDeepEqual', function () { - assert.notDeepEqual({tea: 'jasmine'}, {tea: 'chai'}); - err(function () { - assert.notDeepEqual({tea: 'chai'}, {tea: 'chai'}); - }, "expected { tea: \'chai\' } to not deeply equal { tea: \'chai\' }"); - }); - - test('notDeepEqual (circular)', function () { - var circularObject:any = {} - , secondCircularObject:any = { tea: 'jasmine' }; - circularObject.field = circularObject; - secondCircularObject.field = secondCircularObject; - - assert.notDeepEqual(circularObject, secondCircularObject); - - err(function () { - delete secondCircularObject.tea; - assert.notDeepEqual(circularObject, secondCircularObject); - }, "expected { field: [Circular] } to not deeply equal { field: [Circular] }"); - }); - - test('isNull', function () { - assert.isNull(null); - - err(function () { - assert.isNull(undefined); - }, "expected undefined to equal null"); - }); - - test('isNotNull', function () { - assert.isNotNull(undefined); - - err(function () { - assert.isNotNull(null); - }, "expected null to not equal null"); - }); - - test('isUndefined', function () { - assert.isUndefined(undefined); - - err(function () { - assert.isUndefined(null); - }, "expected null to equal undefined"); - }); - - test('isDefined', function () { - assert.isDefined(null); - - err(function () { - assert.isDefined(undefined); - }, "expected undefined to not equal undefined"); - }); - - test('isFunction', function () { - var func = function () { - }; - assert.isFunction(func); - - err(function () { - assert.isFunction({}); - }, "expected {} to be a function"); - }); - - test('isNotFunction', function () { - assert.isNotFunction(5); - - err(function () { - assert.isNotFunction(function () { - }); - }, "expected [Function] not to be a function"); - }); - - test('isArray', function () { - assert.isArray([]); - assert.isArray(new Array()); - - err(function () { - assert.isArray({}); - }, "expected {} to be an array"); - }); - - test('isNotArray', function () { - assert.isNotArray(3); - - err(function () { - assert.isNotArray([]); - }, "expected [] not to be an array"); - - err(function () { - assert.isNotArray(new Array()); - }, "expected [] not to be an array"); - }); - - test('isString', function () { - assert.isString('Foo'); - assert.isString(new String('foo')); - - err(function () { - assert.isString(1); - }, "expected 1 to be a string"); - }); - - test('isNotString', function () { - assert.isNotString(3); - assert.isNotString([ 'hello' ]); - - err(function () { - assert.isNotString('hello'); - }, "expected 'hello' not to be a string"); - }); - - test('isNumber', function () { - assert.isNumber(1); - assert.isNumber(Number('3')); - - err(function () { - assert.isNumber('1'); - }, "expected \'1\' to be a number"); - }); - - test('isNotNumber', function () { - assert.isNotNumber('hello'); - assert.isNotNumber([ 5 ]); - - err(function () { - assert.isNotNumber(4); - }, "expected 4 not to be a number"); - }); - - test('isBoolean', function () { - assert.isBoolean(true); - assert.isBoolean(false); - - err(function () { - assert.isBoolean('1'); - }, "expected \'1\' to be a boolean"); - }); - - test('isNotBoolean', function () { - assert.isNotBoolean('true'); - - err(function () { - assert.isNotBoolean(true); - }, "expected true not to be a boolean"); - - err(function () { - assert.isNotBoolean(false); - }, "expected false not to be a boolean"); - }); - - test('include', function () { - assert.include('foobar', 'bar'); - assert.include([ 1, 2, 3], 3); - - err(function () { - assert.include('foobar', 'baz'); - }, "expected \'foobar\' to contain \'baz\'"); - - err(function () { - assert.include(undefined, 'bar'); - }, "expected an array or string"); - }); - - test('notInclude', function () { - assert.notInclude('foobar', 'baz'); - assert.notInclude([ 1, 2, 3 ], 4); - - err(function () { - assert.notInclude('foobar', 'bar'); - }, "expected \'foobar\' to not contain \'bar\'"); - - err(function () { - assert.notInclude(undefined, 'bar'); - }, "expected an array or string"); - }); - - test('lengthOf', function () { - assert.lengthOf([1, 2, 3], 3); - assert.lengthOf('foobar', 6); - - err(function () { - assert.lengthOf('foobar', 5); - }, "expected 'foobar' to have a length of 5 but got 6"); - - err(function () { - assert.lengthOf(1, 5); - }, "expected 1 to have a property \'length\'"); - }); - - test('match', function () { - assert.match('foobar', /^foo/); - assert.notMatch('foobar', /^bar/); - - err(function () { - assert.match('foobar', /^bar/i); - }, "expected 'foobar' to match /^bar/i"); - - err(function () { - assert.notMatch('foobar', /^foo/i); - }, "expected 'foobar' not to match /^foo/i"); - }); - - test('property', function () { - var obj = { foo: { bar: 'baz' } }; - var simpleObj = { foo: 'bar' }; - assert.property(obj, 'foo'); - assert.deepProperty(obj, 'foo.bar'); - assert.notProperty(obj, 'baz'); - assert.notProperty(obj, 'foo.bar'); - assert.notDeepProperty(obj, 'foo.baz'); - assert.deepPropertyVal(obj, 'foo.bar', 'baz'); - assert.deepPropertyNotVal(obj, 'foo.bar', 'flow'); - - err(function () { - assert.property(obj, 'baz'); - }, "expected { foo: { bar: 'baz' } } to have a property 'baz'"); - - err(function () { - assert.deepProperty(obj, 'foo.baz'); - }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.baz'"); - - err(function () { - assert.notProperty(obj, 'foo'); - }, "expected { foo: { bar: 'baz' } } to not have property 'foo'"); - - err(function () { - assert.notDeepProperty(obj, 'foo.bar'); - }, "expected { foo: { bar: 'baz' } } to not have deep property 'foo.bar'"); - - err(function () { - assert.propertyVal(simpleObj, 'foo', 'ball'); - }, "expected { foo: 'bar' } to have a property 'foo' of 'ball', but got 'bar'"); - - err(function () { - assert.deepPropertyVal(obj, 'foo.bar', 'ball'); - }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.bar' of 'ball', but got 'baz'"); - - err(function () { - assert.propertyNotVal(simpleObj, 'foo', 'bar'); - }, "expected { foo: 'bar' } to not have a property 'foo' of 'bar'"); - - err(function () { - assert.deepPropertyNotVal(obj, 'foo.bar', 'baz'); - }, "expected { foo: { bar: 'baz' } } to not have a deep property 'foo.bar' of 'baz'"); - }); - - test('throws', function () { - assert.throws(function () { - throw new Error('foo'); - }); - assert.throws(function () { - throw new Error('bar'); - }, 'bar'); - assert.throws(function () { - throw new Error('bar'); - }, /bar/); - assert.throws(function () { - throw new Error('bar'); - }, Error); - assert.throws(function () { - throw new Error('bar'); - }, Error, 'bar'); - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, TypeError); - }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, 'bar'); - }, "expected [Function] to throw error including 'bar' but got 'foo'") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, Error, 'bar'); - }, "expected [Function] to throw error including 'bar' but got 'foo'") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, TypeError, 'bar'); - }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") - - err(function () { - assert.throws(function () { - }); - }, "expected [Function] to throw an error"); - - err(function () { - assert.throws(function () { - throw new Error('') - }, 'bar'); - }, "expected [Function] to throw error including 'bar' but got ''"); - - err(function () { - assert.throws(function () { - throw new Error('') - }, /bar/); - }, "expected [Function] to throw error matching /bar/ but got ''"); - }); - - test('doesNotThrow', function () { - assert.doesNotThrow(function () { - }); - assert.doesNotThrow(function () { - }, 'foo'); - - err(function () { - assert.doesNotThrow(function () { - throw new Error('foo'); - }); - }, 'expected [Function] to not throw an error but [Error: foo] was thrown'); - }); - - test('ifError', function () { - assert.ifError(false); - assert.ifError(null); - assert.ifError(undefined); - - err(function () { - assert.ifError('foo'); - }, "expected \'foo\' to be falsy"); - }); - - test('operator', function () { - assert.operator(1, '<', 2); - assert.operator(2, '>', 1); - assert.operator(1, '==', 1); - assert.operator(1, '<=', 1); - assert.operator(1, '>=', 1); - assert.operator(1, '!=', 2); - assert.operator(1, '!==', 2); - - err(function () { - assert.operator(1, '=', 2); - }, 'Invalid operator "="'); - - err(function () { - assert.operator(2, '<', 1); - }, "expected 2 to be < 1"); - - err(function () { - assert.operator(1, '>', 2); - }, "expected 1 to be > 2"); - - err(function () { - assert.operator(1, '==', 2); - }, "expected 1 to be == 2"); - - err(function () { - assert.operator(2, '<=', 1); - }, "expected 2 to be <= 1"); - - err(function () { - assert.operator(1, '>=', 2); - }, "expected 1 to be >= 2"); - - err(function () { - assert.operator(1, '!=', 1); - }, "expected 1 to be != 1"); - - err(function () { - assert.operator(1, '!==', '1'); - }, "expected 1 to be !== \'1\'"); - }); - - test('closeTo', function () { - assert.closeTo(1.5, 1.0, 0.5); - assert.closeTo(10, 20, 20); - assert.closeTo(-10, 20, 30); - - err(function () { - assert.closeTo(2, 1.0, 0.5); - }, "expected 2 to be close to 1 +/- 0.5"); - - err(function () { - assert.closeTo(-10, 20, 29); - }, "expected -10 to be close to 20 +/- 29"); - }); - - test('members', function () { - assert.includeMembers([1, 2, 3], [2, 3]); - assert.includeMembers([1, 2, 3], []); - assert.includeMembers([1, 2, 3], [3]); - - err(function () { - assert.includeMembers([5, 6], [7, 8]); - }, 'expected [ 5, 6 ] to be a superset of [ 7, 8 ]'); - - err(function () { - assert.includeMembers([5, 6], [5, 6, 0]); - }, 'expected [ 5, 6 ] to be a superset of [ 5, 6, 0 ]'); - }); - - test('memberEquals', function () { - assert.sameMembers([], []); - assert.sameMembers([1, 2, 3], [3, 2, 1]); - assert.sameMembers([4, 2], [4, 2]); - - err(function () { - assert.sameMembers([], [1, 2]); - }, 'expected [] to have the same members as [ 1, 2 ]'); - - err(function () { - assert.sameMembers([1, 54], [6, 1, 54]); - }, 'expected [ 1, 54 ] to have the same members as [ 6, 1, 54 ]'); - }); - -}); diff --git a/chai/chai-assert-tests.ts.tscparams b/chai/chai-assert-tests.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/chai/chai-assert-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/chai/chai-assert.d.ts b/chai/chai-assert.d.ts deleted file mode 100644 index b8845bc6b8..0000000000 --- a/chai/chai-assert.d.ts +++ /dev/null @@ -1,114 +0,0 @@ -// Type definitions for chai v1.7.0 assert style -// Project: http://chaijs.com/ -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module chai -{ - interface Assert - { - (express:any, msg?:string):void; - - fail(actual?:any, expected?:any, msg?:string, operator?:string):void; - - ok(val:any, msg?:string):void; - notOk(val:any, msg?:string):void; - - equal(act:any, exp:any, msg?:string):void; - notEqual(act:any, exp:any, msg?:string):void; - - strictEqual(act:any, exp:any, msg?:string):void; - notStrictEqual(act:any, exp:any, msg?:string):void; - - deepEqual(act:any, exp:any, msg?:string):void; - notDeepEqual(act:any, exp:any, msg?:string):void; - - isTrue(val:any, msg?:string):void; - isFalse(val:any, msg?:string):void; - - isNull(val:any, msg?:string):void; - isNotNull(val:any, msg?:string):void; - - isUndefined(val:any, msg?:string):void; - isDefined(val:any, msg?:string):void; - - isFunction(val:any, msg?:string):void; - isNotFunction(val:any, msg?:string):void; - - isObject(val:any, msg?:string):void; - isNotObject(val:any, msg?:string):void; - - isArray(val:any, msg?:string):void; - isNotArray(val:any, msg?:string):void; - - isString(val:any, msg?:string):void; - isNotString(val:any, msg?:string):void; - - isNumber(val:any, msg?:string):void; - isNotNumber(val:any, msg?:string):void; - - isBoolean(val:any, msg?:string):void; - isNotBoolean(val:any, msg?:string):void; - - typeOf(val:any, type:string, msg?:string):void; - notTypeOf(val:any, type:string, msg?:string):void; - - instanceOf(val:any, type:Function, msg?:string):void; - notInstanceOf(val:any, type:Function, msg?:string):void; - - include(exp:string, inc:any, msg?:string):void; - include(exp:any[], inc:any, msg?:string):void; - - notInclude(exp:string, inc:any, msg?:string):void; - notInclude(exp:any[], inc:any, msg?:string):void; - - match(exp:any, re:RegExp, msg?:string):void; - notMatch(exp:any, re:RegExp, msg?:string):void; - - property(obj:Object, prop:string, msg?:string):void; - notProperty(obj:Object, prop:string, msg?:string):void; - deepProperty(obj:Object, prop:string, msg?:string):void; - notDeepProperty(obj:Object, prop:string, msg?:string):void; - - propertyVal(obj:Object, prop:string, val:any, msg?:string):void; - propertyNotVal(obj:Object, prop:string, val:any, msg?:string):void; - - deepPropertyVal(obj:Object, prop:string, val:any, msg?:string):void; - deepPropertyNotVal(obj:Object, prop:string, val:any, msg?:string):void; - - lengthOf(exp:any, len:number, msg?:string):void; - - //alias frenzy - throw(fn:Function, msg?:string):void; - throw(fn:Function, regExp:RegExp):void; - throw(fn:Function, errType:Function, msg?:string):void; - throw(fn:Function, errType:Function, regExp:RegExp):void; - - throws(fn:Function, msg?:string):void; - throws(fn:Function, regExp:RegExp):void; - throws(fn:Function, errType:Function, msg?:string):void; - throws(fn:Function, errType:Function, regExp:RegExp):void; - - Throw(fn:Function, msg?:string):void; - Throw(fn:Function, regExp:RegExp):void; - Throw(fn:Function, errType:Function, msg?:string):void; - Throw(fn:Function, errType:Function, regExp:RegExp):void; - - doesNotThrow(fn:Function, msg?:string):void; - doesNotThrow(fn:Function, regExp:RegExp):void; - doesNotThrow(fn:Function, errType:Function, msg?:string):void; - doesNotThrow(fn:Function, errType:Function, regExp:RegExp):void; - - operator(val:any, operator:string, val2:any, msg?:string):void; - closeTo(act:number, exp:number, delta:number, msg?:string):void; - - sameMembers(set1:any[], set2:any[], msg?:string):void; - includeMembers(set1:any[], set2:any[], msg?:string):void; - - ifError(val:any, msg?:string):void; - } - //node module - var assert:Assert; -} -//browser global -declare var assert:chai.Assert; diff --git a/chai/chai-tests.ts b/chai/chai-tests.ts index b559c515da..98d75e8aef 100644 --- a/chai/chai-tests.ts +++ b/chai/chai-tests.ts @@ -1,6 +1,7 @@ /// var expect = chai.expect; +var assert = chai.assert; declare var err: Function; function chaiVersion() { @@ -767,3 +768,623 @@ function members() { expect([5, 4]).not.members([6, 3]); expect([5, 4]).not.members([5, 4, 2]); } + +//tdd +declare function suite(description: string, action: Function):void; +declare function test(description: string, action: Function):void; + +interface FieldObj { + field: any; +} +class Foo { + constructor() { + + } +} + +class CrashyObject { + inspect (): void { + throw new Error("Arg's inspect() called even though the test passed"); + } +} + +suite('assert', function () { + + test('assert', function () { + var foo = 'bar'; + assert(foo == 'bar', "expected foo to equal `bar`"); + + err(function () { + assert(foo == 'baz', "expected foo to equal `bar`"); + }, "expected foo to equal `bar`"); + }); + + test('isTrue', function () { + assert.isTrue(true); + + err(function () { + assert.isTrue(false); + }, "expected false to be true"); + + err(function () { + assert.isTrue(1); + }, "expected 1 to be true"); + + err(function () { + assert.isTrue('test'); + }, "expected 'test' to be true"); + }); + + test('ok', function () { + assert.ok(true); + assert.ok(1); + assert.ok('test'); + + err(function () { + assert.ok(false); + }, "expected false to be truthy"); + + err(function () { + assert.ok(0); + }, "expected 0 to be truthy"); + + err(function () { + assert.ok(''); + }, "expected '' to be truthy"); + }); + + test('isFalse', function () { + assert.isFalse(false); + + err(function () { + assert.isFalse(true); + }, "expected true to be false"); + + err(function () { + assert.isFalse(0); + }, "expected 0 to be false"); + }); + + test('equal', function () { + var foo: any; + assert.equal(foo, undefined); + }); + + test('typeof / notTypeOf', function () { + assert.typeOf('test', 'string'); + assert.typeOf(true, 'boolean'); + assert.typeOf(5, 'number'); + + err(function () { + assert.typeOf(5, 'string'); + }, "expected 5 to be a string"); + + }); + + test('notTypeOf', function () { + assert.notTypeOf('test', 'number'); + + err(function () { + assert.notTypeOf(5, 'number'); + }, "expected 5 not to be a number"); + }); + + test('instanceOf', function () { + assert.instanceOf(new Foo(), Foo); + + err(function () { + assert.instanceOf(5, Foo); + }, "expected 5 to be an instance of Foo"); + assert.instanceOf(new CrashyObject(), CrashyObject); + }); + + test('notInstanceOf', function () { + assert.notInstanceOf(new Foo(), String); + + err(function () { + assert.notInstanceOf(new Foo(), Foo); + }, "expected {} to not be an instance of Foo"); + }); + + test('isObject', function () { + assert.isObject({}); + assert.isObject(new Foo()); + + err(function () { + assert.isObject(true); + }, "expected true to be an object"); + + err(function () { + assert.isObject(Foo); + }, "expected [Function: Foo] to be an object"); + + err(function () { + assert.isObject('foo'); + }, "expected 'foo' to be an object"); + }); + + test('isNotObject', function () { + assert.isNotObject(5); + + err(function () { + assert.isNotObject({}); + }, "expected {} not to be an object"); + }); + + test('notEqual', function () { + assert.notEqual(3, 4); + + err(function () { + assert.notEqual(5, 5); + }, "expected 5 to not equal 5"); + }); + + test('strictEqual', function () { + assert.strictEqual('foo', 'foo'); + + err(function () { + assert.strictEqual('5', 5); + }, "expected \'5\' to equal 5"); + }); + + test('notStrictEqual', function () { + assert.notStrictEqual(5, '5'); + + err(function () { + assert.notStrictEqual(5, 5); + }, "expected 5 to not equal 5"); + }); + + test('deepEqual', function () { + assert.deepEqual({tea: 'chai'}, {tea: 'chai'}); + + err(function () { + assert.deepEqual({tea: 'chai'}, {tea: 'black'}); + }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); + + var obja = Object.create({ tea: 'chai' }) + , objb = Object.create({ tea: 'chai' }); + + assert.deepEqual(obja, objb); + + var obj1 = Object.create({tea: 'chai'}) + , obj2 = Object.create({tea: 'black'}); + + err(function () { + assert.deepEqual(obj1, obj2); + }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); + }); + + test('deepEqual (ordering)', function () { + var a = { a: 'b', c: 'd' } + , b = { c: 'd', a: 'b' }; + assert.deepEqual(a, b); + }); + + test('deepEqual (circular)', function () { + var circularObject:any = {} + , secondCircularObject:any = {}; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.deepEqual(circularObject, secondCircularObject); + + err(function () { + secondCircularObject.field2 = secondCircularObject; + assert.deepEqual(circularObject, secondCircularObject); + }, "expected { field: [Circular] } to deeply equal { Object (field, field2) }"); + }); + + test('notDeepEqual', function () { + assert.notDeepEqual({tea: 'jasmine'}, {tea: 'chai'}); + err(function () { + assert.notDeepEqual({tea: 'chai'}, {tea: 'chai'}); + }, "expected { tea: \'chai\' } to not deeply equal { tea: \'chai\' }"); + }); + + test('notDeepEqual (circular)', function () { + var circularObject:any = {} + , secondCircularObject:any = { tea: 'jasmine' }; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.notDeepEqual(circularObject, secondCircularObject); + + err(function () { + delete secondCircularObject.tea; + assert.notDeepEqual(circularObject, secondCircularObject); + }, "expected { field: [Circular] } to not deeply equal { field: [Circular] }"); + }); + + test('isNull', function () { + assert.isNull(null); + + err(function () { + assert.isNull(undefined); + }, "expected undefined to equal null"); + }); + + test('isNotNull', function () { + assert.isNotNull(undefined); + + err(function () { + assert.isNotNull(null); + }, "expected null to not equal null"); + }); + + test('isUndefined', function () { + assert.isUndefined(undefined); + + err(function () { + assert.isUndefined(null); + }, "expected null to equal undefined"); + }); + + test('isDefined', function () { + assert.isDefined(null); + + err(function () { + assert.isDefined(undefined); + }, "expected undefined to not equal undefined"); + }); + + test('isFunction', function () { + var func = function () { + }; + assert.isFunction(func); + + err(function () { + assert.isFunction({}); + }, "expected {} to be a function"); + }); + + test('isNotFunction', function () { + assert.isNotFunction(5); + + err(function () { + assert.isNotFunction(function () { + }); + }, "expected [Function] not to be a function"); + }); + + test('isArray', function () { + assert.isArray([]); + assert.isArray(new Array()); + + err(function () { + assert.isArray({}); + }, "expected {} to be an array"); + }); + + test('isNotArray', function () { + assert.isNotArray(3); + + err(function () { + assert.isNotArray([]); + }, "expected [] not to be an array"); + + err(function () { + assert.isNotArray(new Array()); + }, "expected [] not to be an array"); + }); + + test('isString', function () { + assert.isString('Foo'); + assert.isString(new String('foo')); + + err(function () { + assert.isString(1); + }, "expected 1 to be a string"); + }); + + test('isNotString', function () { + assert.isNotString(3); + assert.isNotString([ 'hello' ]); + + err(function () { + assert.isNotString('hello'); + }, "expected 'hello' not to be a string"); + }); + + test('isNumber', function () { + assert.isNumber(1); + assert.isNumber(Number('3')); + + err(function () { + assert.isNumber('1'); + }, "expected \'1\' to be a number"); + }); + + test('isNotNumber', function () { + assert.isNotNumber('hello'); + assert.isNotNumber([ 5 ]); + + err(function () { + assert.isNotNumber(4); + }, "expected 4 not to be a number"); + }); + + test('isBoolean', function () { + assert.isBoolean(true); + assert.isBoolean(false); + + err(function () { + assert.isBoolean('1'); + }, "expected \'1\' to be a boolean"); + }); + + test('isNotBoolean', function () { + assert.isNotBoolean('true'); + + err(function () { + assert.isNotBoolean(true); + }, "expected true not to be a boolean"); + + err(function () { + assert.isNotBoolean(false); + }, "expected false not to be a boolean"); + }); + + test('include', function () { + assert.include('foobar', 'bar'); + assert.include([ 1, 2, 3], 3); + + err(function () { + assert.include('foobar', 'baz'); + }, "expected \'foobar\' to contain \'baz\'"); + + err(function () { + assert.include(undefined, 'bar'); + }, "expected an array or string"); + }); + + test('notInclude', function () { + assert.notInclude('foobar', 'baz'); + assert.notInclude([ 1, 2, 3 ], 4); + + err(function () { + assert.notInclude('foobar', 'bar'); + }, "expected \'foobar\' to not contain \'bar\'"); + + err(function () { + assert.notInclude(undefined, 'bar'); + }, "expected an array or string"); + }); + + test('lengthOf', function () { + assert.lengthOf([1, 2, 3], 3); + assert.lengthOf('foobar', 6); + + err(function () { + assert.lengthOf('foobar', 5); + }, "expected 'foobar' to have a length of 5 but got 6"); + + err(function () { + assert.lengthOf(1, 5); + }, "expected 1 to have a property \'length\'"); + }); + + test('match', function () { + assert.match('foobar', /^foo/); + assert.notMatch('foobar', /^bar/); + + err(function () { + assert.match('foobar', /^bar/i); + }, "expected 'foobar' to match /^bar/i"); + + err(function () { + assert.notMatch('foobar', /^foo/i); + }, "expected 'foobar' not to match /^foo/i"); + }); + + test('property', function () { + var obj = { foo: { bar: 'baz' } }; + var simpleObj = { foo: 'bar' }; + assert.property(obj, 'foo'); + assert.deepProperty(obj, 'foo.bar'); + assert.notProperty(obj, 'baz'); + assert.notProperty(obj, 'foo.bar'); + assert.notDeepProperty(obj, 'foo.baz'); + assert.deepPropertyVal(obj, 'foo.bar', 'baz'); + assert.deepPropertyNotVal(obj, 'foo.bar', 'flow'); + + err(function () { + assert.property(obj, 'baz'); + }, "expected { foo: { bar: 'baz' } } to have a property 'baz'"); + + err(function () { + assert.deepProperty(obj, 'foo.baz'); + }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.baz'"); + + err(function () { + assert.notProperty(obj, 'foo'); + }, "expected { foo: { bar: 'baz' } } to not have property 'foo'"); + + err(function () { + assert.notDeepProperty(obj, 'foo.bar'); + }, "expected { foo: { bar: 'baz' } } to not have deep property 'foo.bar'"); + + err(function () { + assert.propertyVal(simpleObj, 'foo', 'ball'); + }, "expected { foo: 'bar' } to have a property 'foo' of 'ball', but got 'bar'"); + + err(function () { + assert.deepPropertyVal(obj, 'foo.bar', 'ball'); + }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.bar' of 'ball', but got 'baz'"); + + err(function () { + assert.propertyNotVal(simpleObj, 'foo', 'bar'); + }, "expected { foo: 'bar' } to not have a property 'foo' of 'bar'"); + + err(function () { + assert.deepPropertyNotVal(obj, 'foo.bar', 'baz'); + }, "expected { foo: { bar: 'baz' } } to not have a deep property 'foo.bar' of 'baz'"); + }); + + test('throws', function () { + assert.throws(function () { + throw new Error('foo'); + }); + assert.throws(function () { + throw new Error('bar'); + }, 'bar'); + assert.throws(function () { + throw new Error('bar'); + }, /bar/); + assert.throws(function () { + throw new Error('bar'); + }, Error); + assert.throws(function () { + throw new Error('bar'); + }, Error, 'bar'); + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, TypeError); + }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, 'bar'); + }, "expected [Function] to throw error including 'bar' but got 'foo'") + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, Error, 'bar'); + }, "expected [Function] to throw error including 'bar' but got 'foo'") + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, TypeError, 'bar'); + }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") + + err(function () { + assert.throws(function () { + }); + }, "expected [Function] to throw an error"); + + err(function () { + assert.throws(function () { + throw new Error('') + }, 'bar'); + }, "expected [Function] to throw error including 'bar' but got ''"); + + err(function () { + assert.throws(function () { + throw new Error('') + }, /bar/); + }, "expected [Function] to throw error matching /bar/ but got ''"); + }); + + test('doesNotThrow', function () { + assert.doesNotThrow(function () { + }); + assert.doesNotThrow(function () { + }, 'foo'); + + err(function () { + assert.doesNotThrow(function () { + throw new Error('foo'); + }); + }, 'expected [Function] to not throw an error but [Error: foo] was thrown'); + }); + + test('ifError', function () { + assert.ifError(false); + assert.ifError(null); + assert.ifError(undefined); + + err(function () { + assert.ifError('foo'); + }, "expected \'foo\' to be falsy"); + }); + + test('operator', function () { + assert.operator(1, '<', 2); + assert.operator(2, '>', 1); + assert.operator(1, '==', 1); + assert.operator(1, '<=', 1); + assert.operator(1, '>=', 1); + assert.operator(1, '!=', 2); + assert.operator(1, '!==', 2); + + err(function () { + assert.operator(1, '=', 2); + }, 'Invalid operator "="'); + + err(function () { + assert.operator(2, '<', 1); + }, "expected 2 to be < 1"); + + err(function () { + assert.operator(1, '>', 2); + }, "expected 1 to be > 2"); + + err(function () { + assert.operator(1, '==', 2); + }, "expected 1 to be == 2"); + + err(function () { + assert.operator(2, '<=', 1); + }, "expected 2 to be <= 1"); + + err(function () { + assert.operator(1, '>=', 2); + }, "expected 1 to be >= 2"); + + err(function () { + assert.operator(1, '!=', 1); + }, "expected 1 to be != 1"); + + err(function () { + assert.operator(1, '!==', '1'); + }, "expected 1 to be !== \'1\'"); + }); + + test('closeTo', function () { + assert.closeTo(1.5, 1.0, 0.5); + assert.closeTo(10, 20, 20); + assert.closeTo(-10, 20, 30); + + err(function () { + assert.closeTo(2, 1.0, 0.5); + }, "expected 2 to be close to 1 +/- 0.5"); + + err(function () { + assert.closeTo(-10, 20, 29); + }, "expected -10 to be close to 20 +/- 29"); + }); + + test('members', function () { + assert.includeMembers([1, 2, 3], [2, 3]); + assert.includeMembers([1, 2, 3], []); + assert.includeMembers([1, 2, 3], [3]); + + err(function () { + assert.includeMembers([5, 6], [7, 8]); + }, 'expected [ 5, 6 ] to be a superset of [ 7, 8 ]'); + + err(function () { + assert.includeMembers([5, 6], [5, 6, 0]); + }, 'expected [ 5, 6 ] to be a superset of [ 5, 6, 0 ]'); + }); + + test('memberEquals', function () { + assert.sameMembers([], []); + assert.sameMembers([1, 2, 3], [3, 2, 1]); + assert.sameMembers([4, 2], [4, 2]); + + err(function () { + assert.sameMembers([], [1, 2]); + }, 'expected [] to have the same members as [ 1, 2 ]'); + + err(function () { + assert.sameMembers([1, 54], [6, 1, 54]); + }, 'expected [ 1, 54 ] to have the same members as [ 6, 1, 54 ]'); + }); + +}); diff --git a/chai/chai.d.ts b/chai/chai.d.ts index 7318744012..fc767c639d 100644 --- a/chai/chai.d.ts +++ b/chai/chai.d.ts @@ -1,36 +1,49 @@ // Type definitions for chai 1.7.2 // Project: http://chaijs.com/ -// Definitions by: Jed Hunsaker -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped - +// Definitions by: Jed Hunsaker , Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped declare module chai { + export class AssertionError { + constructor(message: string, _props?: any, ssf?: Function); + name: string; + message: string; + showDiff: boolean; + stack: string; + } function expect(target: any, message?: string): Expect; + + export var assert: Assert; + export var config: Config; + + export interface Config { + includeStack: boolean; + } // Provides a way to extend the internals of Chai - function use(fn: (chai: any, utils: any) => void); + function use(fn: (chai: any, utils: any) => void): any; interface ExpectStatic { (target: any): Expect; } interface Assertions { - attr(name, value?); - css(name, value?); - data(name, value?); - class(className); - id(id); - html(html); - text(text); - value(value); - visible; - hidden; - selected; - checked; - disabled; - empty; - exist; + attr(name: string, value?: string): any; + css(name: string, value?: string): any; + data(name: string, value?: string): any; + class(className: string): any; + id(id: string): any; + html(html: string): any; + text(text: string): any; + value(value: string): any; + visible: any; + hidden: any; + selected: any; + checked: any; + disabled: any; + empty: any; + exist: any; } interface Expect extends LanguageChains, NumericComparison, TypeComparison, Assertions { @@ -162,4 +175,109 @@ declare module chai { (constructor: Function, expected?: string, message?: string): Expect; (constructor: Function, expected?: RegExp, message?: string): Expect; } + + export interface Assert { + (express: any, msg?: string):void; + + fail(actual?: any, expected?: any, msg?: string, operator?: string):void; + + ok(val: any, msg?: string):void; + notOk(val: any, msg?: string):void; + + equal(act: any, exp: any, msg?: string):void; + notEqual(act: any, exp: any, msg?: string):void; + + strictEqual(act: any, exp: any, msg?: string):void; + notStrictEqual(act: any, exp: any, msg?: string):void; + + deepEqual(act: any, exp: any, msg?: string):void; + notDeepEqual(act: any, exp: any, msg?: string):void; + + isTrue(val: any, msg?: string):void; + isFalse(val: any, msg?: string):void; + + isNull(val: any, msg?: string):void; + isNotNull(val: any, msg?: string):void; + + isUndefined(val: any, msg?: string):void; + isDefined(val: any, msg?: string):void; + + isFunction(val: any, msg?: string):void; + isNotFunction(val: any, msg?: string):void; + + isObject(val: any, msg?: string):void; + isNotObject(val: any, msg?: string):void; + + isArray(val: any, msg?: string):void; + isNotArray(val: any, msg?: string):void; + + isString(val: any, msg?: string):void; + isNotString(val: any, msg?: string):void; + + isNumber(val: any, msg?: string):void; + isNotNumber(val: any, msg?: string):void; + + isBoolean(val: any, msg?: string):void; + isNotBoolean(val: any, msg?: string):void; + + typeOf(val: any, type: string, msg?: string):void; + notTypeOf(val: any, type: string, msg?: string):void; + + instanceOf(val: any, type: Function, msg?: string):void; + notInstanceOf(val: any, type: Function, msg?: string):void; + + include(exp: string, inc: any, msg?: string):void; + include(exp: any[], inc: any, msg?: string):void; + + notInclude(exp: string, inc: any, msg?: string):void; + notInclude(exp: any[], inc: any, msg?: string):void; + + match(exp: any, re: RegExp, msg?: string):void; + notMatch(exp: any, re: RegExp, msg?: string):void; + + property(obj: Object, prop: string, msg?: string):void; + notProperty(obj: Object, prop: string, msg?: string):void; + deepProperty(obj: Object, prop: string, msg?: string):void; + notDeepProperty(obj: Object, prop: string, msg?: string):void; + + propertyVal(obj: Object, prop: string, val: any, msg?: string):void; + propertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; + + deepPropertyVal(obj: Object, prop: string, val: any, msg?: string):void; + deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; + + lengthOf(exp: any, len: number, msg?: string):void; + //alias frenzy + throw(fn: Function, msg?: string):void; + throw(fn: Function, regExp: RegExp):void; + throw(fn: Function, errType: Function, msg?: string):void; + throw(fn: Function, errType: Function, regExp: RegExp):void; + + throws(fn: Function, msg?: string):void; + throws(fn: Function, regExp: RegExp):void; + throws(fn: Function, errType: Function, msg?: string):void; + throws(fn: Function, errType: Function, regExp: RegExp):void; + + Throw(fn: Function, msg?: string):void; + Throw(fn: Function, regExp: RegExp):void; + Throw(fn: Function, errType: Function, msg?: string):void; + Throw(fn: Function, errType: Function, regExp: RegExp):void; + + doesNotThrow(fn: Function, msg?: string):void; + doesNotThrow(fn: Function, regExp: RegExp):void; + doesNotThrow(fn: Function, errType: Function, msg?: string):void; + doesNotThrow(fn: Function, errType: Function, regExp: RegExp):void; + + operator(val: any, operator: string, val2: any, msg?: string):void; + closeTo(act: number, exp: number, delta: number, msg?: string):void; + + sameMembers(set1: any[], set2: any[], msg?: string):void; + includeMembers(set1: any[], set2: any[], msg?: string):void; + + ifError(val: any, msg?: string):void; + } +} + +declare module "chai" { + export = chai; } diff --git a/chai/chai.d.ts.tscparams b/chai/chai.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/chai/chai.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/chalk/chalk-tests.ts b/chalk/chalk-tests.ts new file mode 100644 index 0000000000..208709e5b1 --- /dev/null +++ b/chalk/chalk-tests.ts @@ -0,0 +1,30 @@ +/// + +import chalk = require('chalk'); + +var str: string; +var bool: boolean; + +chalk.enabled = bool; +str = chalk.stripColor(str); + +bool = chalk.supportsColor; +bool = chalk.hasColor(str); + +// style a string +console.log( chalk.blue('Hello world!') ); + +// combine styled and normal strings +console.log( chalk.blue('Hello'), 'World' + chalk.red('!') ); + +// compose multiple styles using the chainable API +console.log( chalk.blue.bgRed.bold('Hello world!') ); + +// pass in multiple arguments +console.log( chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz') ); + +// nest styles +console.log( chalk.red('Hello', chalk.underline.bgBlue('world') + '!') ); + +// nest styles of the same type even (color, underline, background) +console.log( chalk.green('I am a green line ' + chalk.blue('with a blue substring') + ' that becomes green again!') ); diff --git a/chalk/chalk.d.ts b/chalk/chalk.d.ts new file mode 100644 index 0000000000..5cceb95145 --- /dev/null +++ b/chalk/chalk.d.ts @@ -0,0 +1,92 @@ +// Type definitions for chalk v0.4.0 +// Project: https://github.com/sindresorhus/chalk +// Definitions by: Diullei Gomes , Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Chalk { + export interface ChalkModule extends ChalkStyle { + enabled: boolean; + supportsColor: boolean; + styles: ChalkStyleMap; + + stripColor(value: string): any; + hasColor(str: string): boolean; + } + + export interface ChalkChain extends ChalkStyle { + (...text: string[]): ChalkChain; + } + + export interface ChalkStyleElement { + open: string; + close: string; + } + + export interface ChalkStyle { + // General + reset: ChalkChain; + bold: ChalkChain; + italic: ChalkChain; + underline: ChalkChain; + inverse: ChalkChain; + strikethrough: ChalkChain; + + // Text colors + black: ChalkChain; + red: ChalkChain; + green: ChalkChain; + yellow: ChalkChain; + blue: ChalkChain; + magenta: ChalkChain; + cyan: ChalkChain; + white: ChalkChain; + gray: ChalkChain; + + // Background colors + bgBlack: ChalkChain; + bgRed: ChalkChain; + bgGreen: ChalkChain; + bgYellow: ChalkChain; + bgBlue: ChalkChain; + bgMagenta: ChalkChain; + bgCyan: ChalkChain; + bgWhite: ChalkChain; + } + + export interface ChalkStyleMap { + // General + reset: ChalkStyleElement; + bold: ChalkStyleElement; + italic: ChalkStyleElement; + underline: ChalkStyleElement; + inverse: ChalkStyleElement; + strikethrough: ChalkStyleElement; + + // Text colors + black: ChalkStyleElement; + red: ChalkStyleElement; + green: ChalkStyleElement; + yellow: ChalkStyleElement; + blue: ChalkStyleElement; + magenta: ChalkStyleElement; + cyan: ChalkStyleElement; + white: ChalkStyleElement; + gray: ChalkStyleElement; + + // Background colors + bgBlack: ChalkStyleElement; + bgRed: ChalkStyleElement; + bgGreen: ChalkStyleElement; + bgYellow: ChalkStyleElement; + bgBlue: ChalkStyleElement; + bgMagenta: ChalkStyleElement; + bgCyan: ChalkStyleElement; + bgWhite: ChalkStyleElement; + } +} + +declare module "chalk" { + var ch: Chalk.ChalkModule; + export = ch; +} + diff --git a/cheerio/cheerio-tests.ts b/cheerio/cheerio-tests.ts index 71d54c5579..af671cd009 100644 --- a/cheerio/cheerio-tests.ts +++ b/cheerio/cheerio-tests.ts @@ -33,7 +33,7 @@ $el.children().map((index, element) => { }); $el.children().filter((index) => { - return $el.children().eq(index).find('t'); + return $el.children().eq(index).find('t').length >= 0; }); $el.filter('span').filter('li'); @@ -60,6 +60,6 @@ $el.text('some text'); $el.toArray(); $el.clone().find('a').parent(); -$el.root().find('a'); +$.root().find('a'); -$el.dom(); +$el.data(); diff --git a/cheerio/cheerio-tests.ts.tscparams b/cheerio/cheerio-tests.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/cheerio/cheerio-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index b0e09b778b..cd0be35934 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -1,81 +1,215 @@ -// Type definitions for Cheerio -// Project: https://github.com/MatthewMueller/cheerio -// Definitions by: Bret Little +// Type definitions for Cheerio v0.17.0 +// Project: https://github.com/cheeriojs/cheerio +// Definitions by: Bret Little , VILIC VANE , Wayne Maurer // Definitions: https://github.com/borisyankov/DefinitelyTyped - interface Cheerio { - - addClass(classNames: string): Cheerio; - hasClass(className: string): boolean; - removeClass(className?: any): Cheerio; + // Document References + // Cheerio https://github.com/cheeriojs/cheerio + // JQuery http://api.jquery.com - attr(attributeName: string, value: any): Cheerio; - attr(attributeName: string): string; - removeAttr(attributeName: any): Cheerio; + [index: number]: CheerioElement; + length: number; + + // Attributes + + attr(name: string): string; + attr(name: string, value: any): Cheerio; + + data(): any; + + val(): string; + val(value: string): Cheerio; + + removeAttr(name: string): Cheerio; + + hasClass(className: string): boolean; + addClass(classNames: string): Cheerio; + + removeClass(): Cheerio; + removeClass(className: string): Cheerio; + removeClass(func: (index: number, className: string) => string): Cheerio; + + toggleClass(className: string): Cheerio; + toggleClass(className: string, toggleSwitch: boolean): Cheerio; + toggleClass(toggleSwitch?: boolean): Cheerio; + toggleClass(func: (index: number, className: string, toggleSwitch: boolean) => string, toggleSwitch?: boolean): Cheerio; + + is(selector: string): boolean; + is(element: CheerioElement): boolean; + is(element: CheerioElement[]): boolean; + is(selection: Cheerio): boolean; + is(func: (index: number, element: CheerioElement) => boolean): boolean; + + // Traversing find(selector: string): Cheerio; - parent(): Cheerio; + parent(selector?: string): Cheerio; + parents(selector?: string): Cheerio; + parentsUntil(selector?: string, filter?: string): Cheerio; + parentsUntil(element: CheerioElement, filter?: string): Cheerio; + parentsUntil(element: Cheerio, filter?: string): Cheerio; - next(): Cheerio; - prev(): Cheerio; + closest(selector: string): Cheerio; - siblings(): Cheerio; + next(selector?: string): Cheerio; + nextAll(): Cheerio; - children(selector?: any): Cheerio; + nextUntil(selector?: string, filter?: string): Cheerio; + nextUntil(element: CheerioElement, filter?: string): Cheerio; + nextUntil(element: Cheerio, filter?: string): Cheerio; - each(func: (index: any, elem: any) => Cheerio); + prev(selector?: string): Cheerio; + prevAll(): Cheerio; - map(callback: (index: any, domElement: Element) =>any): Cheerio; + prevUntil(selector?: string, filter?: string): Cheerio; + prevUntil(element: CheerioElement, filter?: string): Cheerio; + prevUntil(element: Cheerio, filter?: string): Cheerio; + + slice(start: number, end?: number): Cheerio; + + siblings(selector?: string): Cheerio; + + children(selector?: string): Cheerio; + + each(func: (index: number, element: CheerioElement) => any): Cheerio; + map(func: (index: number, element: CheerioElement) => any): Cheerio; filter(selector: string): Cheerio; - filter(func: (index: any) =>any): Cheerio; + filter(selection: Cheerio): Cheerio; + filter(element: CheerioElement): Cheerio; + filter(elements: CheerioElement[]): Cheerio; + filter(func: (index: number) => boolean): 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; + get(): Document[]; + get(index: number): Document; + + end(): Cheerio; + + add(selectorOrHtml: string): Cheerio; + add(selector: string, context: Document): Cheerio; + add(element: CheerioElement): Cheerio; + add(elements: CheerioElement[]): Cheerio; + add(selection: Cheerio): Cheerio; + + // Manipulation + + append(content: string, ...contents: any[]): Cheerio; + append(content: Document, ...contents: any[]): Cheerio; + append(content: Document[], ...contents: any[]): Cheerio; + append(content: Cheerio, ...contents: any[]): Cheerio; + + prepend(content: string, ...contents: any[]): Cheerio; + prepend(content: Document, ...contents: any[]): Cheerio; + prepend(content: Document[], ...contents: any[]): Cheerio; + prepend(content: Cheerio, ...contents: any[]): Cheerio; + + after(content: string, ...contents: any[]): Cheerio; + after(content: Document, ...contents: any[]): Cheerio; + after(content: Document[], ...contents: any[]): Cheerio; + after(content: Cheerio, ...contents: any[]): Cheerio; + + before(content: string, ...contents: any[]): Cheerio; + before(content: Document, ...contents: any[]): Cheerio; + before(content: Document[], ...contents: any[]): Cheerio; + before(content: Cheerio, ...contents: any[]): Cheerio; + + remove(selector?: string): Cheerio; + replaceWith(content: string): Cheerio; + replaceWith(content: CheerioElement): Cheerio; + replaceWith(content: CheerioElement[]): Cheerio; + replaceWith(content: Cheerio): Cheerio; + empty(): Cheerio; - html(htmlString: string): Cheerio; html(): string; + html(html: string): Cheerio; - text(textString: string): Cheerio; text(): string; + text(text: string): Cheerio; - toArray(): any[]; + css(propertyName: string): string; + css(propertyNames: string[]): string[]; + css(propertyName: string, value: string): Cheerio; + css(propertyName: string, value: number): Cheerio; + css(propertyName: string, func: (index: number, value: string) => string): Cheerio; + css(propertyName: string, func: (index: number, value: string) => number): Cheerio; + css(properties: Object): Cheerio; - clone() : Cheerio; - root() : Cheerio; - dom(): any; + // Rendering - contains(container: Element, contained: Element): boolean; - isArray(obj: any): boolean; - inArray(value: any, array: any[], fromIndex?: number): number; - merge(first: any[], second: any[]): any[]; + // Miscellaneous + clone(): Cheerio; + // Not Documented + + toArray(): CheerioElement[]; } interface CheerioOptionsInterface { - ignoreWhitespace?: boolean; + // Document References + // Cheerio https://github.com/cheeriojs/cheerio + // HTMLParser2 https://github.com/fb55/htmlparser2/wiki/Parser-options + // DomHandler https://github.com/fb55/DomHandler + xmlMode?: boolean; + decodeEntities?: boolean; lowerCaseTags?: boolean; + lowerCaseAttributeNames?: boolean; + recognizeCDATA?: boolean; + recognizeSelfClosing?: boolean; + normalizeWhitespace?: boolean; } interface CheerioStatic { - (...selectors: any[]): Cheerio; - (): Cheerio; + // Document References + // Cheerio https://github.com/cheeriojs/cheerio + // JQuery http://api.jquery.com + + (selector: string): Cheerio; + (selector: string, context: string): Cheerio; + (selector: string, context: CheerioElement): Cheerio; + (selector: string, context: CheerioElement[]): Cheerio; + (selector: string, context: Cheerio): Cheerio; + (selector: string, context: string, root: string): Cheerio; + (selector: string, context: CheerioElement, root: string): Cheerio; + (selector: string, context: CheerioElement[], root: string): Cheerio; + (selector: string, context: Cheerio, root: string): Cheerio; + (selector: any): Cheerio; + + xml(): string; + root(): Cheerio; + contains(container: CheerioElement, contained: CheerioElement): boolean; + parseHTML(data: string, context?: Document, keepScripts?: boolean): Document[]; + + html(options?: CheerioOptionsInterface): string; + html(selector: string, options?: CheerioOptionsInterface): string; + html(element: Cheerio, options?: CheerioOptionsInterface): string; + html(element: CheerioElement, options?: CheerioOptionsInterface): string; +} + +interface CheerioElement { + // Document References + // Node Console + + type: string; + name: string; + attribs: Object; + children: CheerioElement[]; + next: CheerioElement; + prev: CheerioElement; + parent: CheerioElement; + root: CheerioElement; } declare module "cheerio" { - export function load (html : string, options?: CheerioOptionsInterface) : CheerioStatic; + export function load(html: string, options?: CheerioOptionsInterface): CheerioStatic; } diff --git a/cheerio/cheerio.d.ts.tscparams b/cheerio/cheerio.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/cheerio/cheerio.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/chrome/chrome-app-tests.ts b/chrome/chrome-app-tests.ts index 0ae0ae2af4..12dc7b97db 100644 --- a/chrome/chrome-app-tests.ts +++ b/chrome/chrome-app-tests.ts @@ -24,4 +24,253 @@ chrome.app.runtime.onLaunched.addListener(function (launchData: runtime.LaunchDa chrome.app.runtime.onRestarted.addListener(function () { return; }); // Get Current Window -var currentWindow: cwindow.AppWindow = chrome.app.window.current(); \ No newline at end of file +var currentWindow: cwindow.AppWindow = chrome.app.window.current(); + +// Sockets +// https://developer.chrome.com/apps/sockets_tcp +function test_socketsTcp(): void { + var socketId: number; + var properties: chrome.sockets.tcp.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.tcp.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.tcp.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.tcp.update(socketId, properties); + chrome.sockets.tcp.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.tcp.setPaused(socketId, true); + chrome.sockets.tcp.setPaused(socketId, true, () => { }); + + // setKeepAlive + chrome.sockets.tcp.setKeepAlive(socketId, true, (result: number) => { }); + chrome.sockets.tcp.setKeepAlive(socketId, true, 0, (result: number) => { }); + + // setNoDelay + chrome.sockets.tcp.setNoDelay(socketId, true, (result: number) => { }); + + // connect + chrome.sockets.tcp.connect(socketId, "192.168.0.1", 8080, (result: number) => { }); + + // disconnect + chrome.sockets.tcp.disconnect(socketId); + chrome.sockets.tcp.disconnect(socketId, () => { }); + + // send + chrome.sockets.tcp.send(socketId, buffer, (info: chrome.sockets.tcp.SendInfo) => { }); + + // close + chrome.sockets.tcp.close(socketId); + chrome.sockets.tcp.close(socketId, () => { }); + + // getInfo + chrome.sockets.tcp.getInfo(socketId, (info: chrome.sockets.tcp.SocketInfo) => { }); + + // getSockets + chrome.sockets.tcp.getSockets(socketId, (infos: chrome.sockets.tcp.SocketInfo[]) => { }); +} + +function test_socketsTcpEvents(): void { + chrome.sockets.tcp.onReceive.addListener((info: chrome.sockets.tcp.ReceiveEventArgs) => { }); + chrome.sockets.tcp.onReceiveError.addListener((info: chrome.sockets.tcp.ReceiveErrorEventArgs) => { }); +} + +function testSocketsTcpTypes(): void { + // SocketProperties + var properties: chrome.sockets.tcp.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: "test", + bufferSize: 1024 + }; + + // SocketInfo + var socketInfo: chrome.sockets.tcp.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true, + connected: false + }; + + socketInfo.name = "test"; + socketInfo.bufferSize = 1024; + socketInfo.localAddress = "192.168.0.2"; + socketInfo.localPort = 8000; + socketInfo.peerAddress = "192.168.0.3"; + socketInfo.peerPort = 1000; +} + +// https://developer.chrome.com/apps/sockets_udp +function test_socketsUdp(): void { + var socketId: number; + var properties: chrome.sockets.udp.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.udp.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.udp.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.udp.update(socketId, properties); + chrome.sockets.udp.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.udp.setPaused(socketId, true); + chrome.sockets.udp.setPaused(socketId, true, () => { }); + + // bind + chrome.sockets.udp.bind(socketId, "0.0.0.0", 8080, (result: number) => { }); + + // send + chrome.sockets.udp.send(socketId, buffer, "172.21.0.1", 10080, (info: chrome.sockets.udp.SendInfo) => { }); + + // close + chrome.sockets.udp.close(socketId); + chrome.sockets.udp.close(socketId, () => { }); + + // getInfo + chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.udp.SocketInfo) => { }); + + // getSockets + chrome.sockets.udp.getSockets((infos: chrome.sockets.udp.SocketInfo[]) => { }); + + // joinGroup + chrome.sockets.udp.joinGroup(socketId, "224.0.0.1", (result: number) => { }); + + // leaveGroup + chrome.sockets.udp.leaveGroup(socketId, "224.0.0.1", (result: number) => { }); + + // setMulticastTimeToLive + chrome.sockets.udp.setMulticastTimeToLive(socketId, 100, (result: number) => { }); + + // setMulticastLoopbackMode + chrome.sockets.udp.setMulticastLoopbackMode(socketId, true, (result: number) => { }); + + // getJoinedGroups + chrome.sockets.udp.getJoinedGroups(socketId, (groups: string[]) => { }); +} + +function test_socketsUdpEvents(): void { + chrome.sockets.udp.onReceive.addListener((info: chrome.sockets.udp.ReceiveEventArgs) => { }); + chrome.sockets.udp.onReceiveError.addListener((info: chrome.sockets.udp.ReceiveErrorEventArgs) => { }); +} + +function testSocketsUdpTypes(): void { + // SocketProperties + var properties: chrome.sockets.udp.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: "test", + bufferSize: 1024 + }; + + // SocketInfo + var socketInfo: chrome.sockets.udp.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true + }; + + socketInfo.name = "test"; + socketInfo.bufferSize = 1024; + socketInfo.localAddress = "192.168.0.2"; + socketInfo.localPort = 8000; +} + +// https://developer.chrome.com/apps/sockets_tcpServer +function test_socketsTcpServer(): void { + var socketId: number; + var properties: chrome.sockets.tcpServer.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.tcpServer.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.tcpServer.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.tcpServer.update(socketId, properties); + chrome.sockets.tcpServer.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.tcpServer.setPaused(socketId, true); + chrome.sockets.tcpServer.setPaused(socketId, true, () => { }); + + // listen + chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, (result: number) => { }); + chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, 128, (result: number) => { }); + + // disconnect + chrome.sockets.tcp.disconnect(socketId); + chrome.sockets.tcp.disconnect(socketId, () => { }); + + // close + chrome.sockets.udp.close(socketId); + chrome.sockets.udp.close(socketId, () => { }); + + // getInfo + chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.udp.SocketInfo) => { }); + + // getSockets + chrome.sockets.tcp.getSockets(socketId, (infos: chrome.sockets.tcp.SocketInfo[]) => { }); +} + +function test_socketsTcpServerEvents(): void { + chrome.sockets.tcpServer.onAccept.addListener((info: chrome.sockets.tcpServer.AcceptEventArgs) => { }); + chrome.sockets.tcpServer.onAcceptError.addListener((info: chrome.sockets.tcpServer.AcceptErrorEventArgs) => { }); +} + +function testSocketsTcpServerTypes(): void { + // SocketProperties + var properties: chrome.sockets.tcpServer.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: "test" + }; + + // SocketInfo + var socketInfo: chrome.sockets.tcpServer.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true + }; + + socketInfo.name = "test"; + socketInfo.localAddress = "192.168.0.2"; + socketInfo.localPort = 8000; +} diff --git a/chrome/chrome-app.d.ts b/chrome/chrome-app.d.ts index c8dd2e6d46..830b26e4fd 100644 --- a/chrome/chrome-app.d.ts +++ b/chrome/chrome-app.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Chrome packaged application development. +// Type definitions for Chrome packaged application development // Project: http://developer.chrome.com/apps/ -// Definitions by: Adam Lay +// Definitions by: Adam Lay , MIZUNE Pine // Definitions: https://github.com/borisyankov/DefinitelyTyped //////////////////// @@ -92,4 +92,190 @@ declare module chrome.app.window { var onMaximized: WindowEvent; var onMinimized: WindowEvent; var onRestored: WindowEvent; +} + + +//////////////////// +// Sockets +//////////////////// +declare module chrome.sockets.tcp { + interface CreateInfo { + socketId: number; + } + + interface SendInfo { + resultCode: number; + bytesSent?: number; + } + + interface Event { + addListener(callback: (info: T) => void): void; + } + + interface ReceiveEventArgs { + socketId: number; + data: ArrayBuffer; + } + + interface ReceiveErrorEventArgs { + socketId: number; + resultCode: number; + } + + interface SocketProperties { + persistent?: boolean; + name?: string; + bufferSize?: number; + } + + interface SocketInfo { + socketId: number; + persistent: boolean; + name?: string; + bufferSize?: number; + paused: boolean; + connected: boolean; + localAddress?: string; + localPort?: number; + peerAddress?: string; + peerPort?: number; + } + + export function create(callback: (createInfo: CreateInfo) => void): void; + export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + + export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + + export function setKeepAlive(socketId: number, + enable: boolean, callback: (result: number) => void): void; + export function setKeepAlive(socketId: number, + enable: boolean, delay: number, callback: (result: number) => void): void; + + export function setNoDelay(socketId: number, noDelay: boolean, callback: (result: number) => void): void; + export function connect(socketId: number, + peerAddress: string, peerPort: number, callback: (result: number) => void): void; + export function disconnect(socketId: number, callback?: () => void): void; + export function send(socketId: number, data: ArrayBuffer, callback: (sendInfo: SendInfo) => void): void; + export function close(socketId: number, callback?: () => void): void; + export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + export function getSockets(socketId: number, callback: (socketInfos: SocketInfo[]) => void): void; + + var onReceive: Event; + var onReceiveError: Event; +} + +declare module chrome.sockets.udp { + interface CreateInfo { + socketId: number; + } + + interface SendInfo { + resultCode: number; + bytesSent?: number; + } + + interface Event { + addListener(callback: (info: T) => void): void; + } + + interface ReceiveEventArgs { + socketId: number; + data: ArrayBuffer; + remoteAddress: string; + remotePort: number; + } + + interface ReceiveErrorEventArgs { + socketId: number; + resultCode: number; + } + + interface SocketProperties { + persistent?: boolean; + name?: string; + bufferSize?: number; + } + + interface SocketInfo { + socketId: number; + persistent: boolean; + name?: string; + bufferSize?: number; + paused: boolean; + localAddress?: string; + localPort?: number; + } + + export function create(callback: (createInfo: CreateInfo) => void): void; + export function create(properties: SocketProperties, + callback: (createInfo: CreateInfo) => void): void; + + export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + export function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; + export function send(socketId: number, data: ArrayBuffer, address: string, port: number, callback: (sendInfo: SendInfo) => void): void; + export function close(socketId: number, callback?: () => void): void; + export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; + export function joinGroup(socketId: number, address: string, callback: (result: number) => void): void; + export function leaveGroup(socketId: number, address: string, callback: (result: number) => void): void; + export function setMulticastTimeToLive(socketId: number, ttl: number, callback: (result: number) => void): void; + export function setMulticastLoopbackMode(socketId: number, enabled: boolean, callback: (result: number) => void): void; + export function getJoinedGroups(socketId: number, callback: (groups: string[]) => void): void; + + var onReceive: Event; + var onReceiveError: Event; +} + +declare module chrome.sockets.tcpServer { + interface CreateInfo { + socketId: number; + } + + interface Event { + addListener(callback: (info: T) => void): void; + } + + interface AcceptEventArgs { + socketId: number; + clientSocketId: number; + } + + interface AcceptErrorEventArgs { + socketId: number; + resultCode: number; + } + + interface SocketProperties { + persistent?: boolean; + name?: string; + } + + interface SocketInfo { + socketId: number; + persistent: boolean; + name?: string; + paused: boolean; + localAddress?: string; + localPort?: number; + } + + export function create(callback: (createInfo: CreateInfo) => void): void; + export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + + export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + + export function listen(socketId: number, address: string, + port: number, backlog: number, callback: (result: number) => void): void; + export function listen(socketId: number, address: string, + port: number, callback: (result: number) => void): void; + + export function disconnect(socketId: number, callback?: () => void): void; + export function close(socketId: number, callback?: () => void): void; + export function getInfo(socketId: number, callback: (socketInfos: SocketInfo[]) => void): void; + + var onAccept: Event; + var onAcceptError: Event; } \ No newline at end of file diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index 9d3b9451c0..23ee0d9166 100755 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Chrome extension development. +// Type definitions for Chrome extension development // Project: http://developer.chrome.com/extensions/ -// Definitions by: Matthew Kimber and otiai10 +// Definitions by: Matthew Kimber , otiai10 // Definitions: https://github.com/borisyankov/DefinitelyTyped //////////////////// @@ -843,8 +843,12 @@ declare module chrome.extension { type?: string; } + interface LastError { + message?: string; + } + var inIncognitoContext: boolean; - var lastError: Object; + var lastError: LastError; export function getBackgroundPage(): Window; export function getURL(path: string): string; @@ -1232,6 +1236,68 @@ declare module chrome.management { var onEnabled: ManagementEnabledEvent; } +//////////////////// +// Notifications +// https://developer.chrome.com/extensions/notifications +//////////////////// +declare module chrome.notifications { + interface ButtonOptions { + title: string; + iconUrl?: string; + } + + interface ItemOptions { + title: string; + message: string; + } + + interface NotificationOptions { + type?: string; + iconUrl?: string; + title?: string; + message?: string; + contextMessage?: string; + priority?: number; + eventTime?: number; + buttons?: Array; + items?: Array; + progress?: number; + isClickable?: boolean; + } + + interface OnClosed { + addListener(callback: (notificationId: string, byUser: boolean) => void): void; + } + + interface OnClicked { + addListener(callback: (notificationId: string) => void): void; + } + + interface OnButtonClicked { + addListener(callback: (notificationId: string, buttonIndex: number) => void): void; + } + + interface OnPermissionLevelChanged { + addListener(callback: (level: string) => void): void; + } + + interface OnShowSettings { + addListener(callback: Function): void; + } + + export var onClosed: OnClosed; + export var onClicked: OnClicked; + export var onButtonClicked: OnButtonClicked; + export var onPermissionLevelChanged: OnPermissionLevelChanged; + export var onShowSettings: OnShowSettings; + + export function create(notificationId: string, options: NotificationOptions, callback: (notificationId: string) => void): void; + export function update(notificationId: string, options: NotificationOptions, callback: (wasUpdated: boolean) => void): void; + export function clear(notificationId: string, callback: (wasCleared: boolean) => void): void; + export function getAll(callback: (notifications: any) => void): void; + export function getPermissionLevel(callback: (level: string) => void): void; +} + //////////////////// // Omnibox //////////////////// @@ -1425,9 +1491,13 @@ declare module chrome.proxy { // Runtime //////////////////// declare module chrome.runtime { - var lastError: Object; + var lastError: LastError; var id: string; + interface LastError { + message?: string; + } + interface ConnectInfo { name?: string; } @@ -1824,6 +1894,10 @@ declare module chrome.tabs { addListener(callback: (activeInfo: TabActiveInfo) => void): void; } + interface TabReplacedEvent extends chrome.events.Event { + addListener(callback: (addedTabId: number, removedTabId: number) => void): void; + } + export function executeScript(details: InjectDetails, callback?: (result: any[]) => void): void; export function executeScript(tabId: number, details: InjectDetails, callback?: (result: any[]) => void): void; export function get(tabId: number, callback: (tab: Tab) => void): void; @@ -1831,6 +1905,7 @@ declare module chrome.tabs { export function create(createProperties: CreateProperties, callback?: (tab: Tab) => void): void; export function move(tabId: number, moveProperties: MoveProperties, callback?: (tab: Tab) => void): void; export function move(tabIds: number[], moveProperties: MoveProperties, callback?: (tabs: Tab[]) => void): void; + export function update(updateProperties: UpdateProperties, callback?: (tab?: Tab) => void): void; export function update(tabId: number, updateProperties: UpdateProperties, callback?: (tab?: Tab) => void): void; export function remove(tabId: number, callback?: Function): void; export function remove(tabIds: number[], callback?: Function): void; @@ -1856,6 +1931,7 @@ declare module chrome.tabs { var onDetached: TabDetachedEvent; var onCreated: TabCreatedEvent; var onActivated: TabActivatedEvent; + var onReplaced: TabReplacedEvent; } //////////////////// diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index affee34583..af4b32046a 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -9,7 +9,7 @@ declare function CodeMirror(callback: (host: HTMLElement) => void , options?: Co declare module CodeMirror { export var Pass: any; - function fromTextArea(host: HTMLTextAreaElement, options?: EditorConfiguration): CodeMirror.Editor; + function fromTextArea(host: HTMLTextAreaElement, options?: EditorConfiguration): CodeMirror.EditorFromTextArea; var version: string; @@ -86,6 +86,11 @@ declare module CodeMirror { or the line the widget is on require the widget to be redrawn. */ function on(line: LineWidget, eventName: 'redraw', handler: () => void ): void; function off(line: LineWidget, eventName: 'redraw', handler: () => void ): void; + + /** Various CodeMirror-related objects emit events, which allow client code to react to various situations. + Handlers for such events can be registered with the on and off methods on the objects that the event fires on. + To fire your own events, use CodeMirror.signal(target, name, args...), where target is a non-DOM-node object. */ + function signal(target: any, name: string, ...args: any[]): void; interface Editor { @@ -369,6 +374,18 @@ declare module CodeMirror { on(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void; off(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void; } + + interface EditorFromTextArea extends Editor { + + /** Copy the content of the editor into the textarea. */ + save(): void; + + /** Remove the editor, and restore the original textarea (with the editor's current content). */ + toTextArea(): void; + + /** Returns the textarea that the instance was based on. */ + getTextArea(): HTMLTextAreaElement; + } class Doc { constructor (text: string, mode?: any, firstLineNumber?: number); diff --git a/colors/colors.d.ts b/colors/colors.d.ts index c87112d7c4..e6056b3540 100644 --- a/colors/colors.d.ts +++ b/colors/colors.d.ts @@ -3,6 +3,10 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped +declare module "colors" { + export function setTheme(theme:any):any; +} + interface String { bold:string; italic:string; diff --git a/compression/compression-tests.ts b/compression/compression-tests.ts new file mode 100644 index 0000000000..ecfcab4320 --- /dev/null +++ b/compression/compression-tests.ts @@ -0,0 +1,10 @@ +/// + +import express = require('express'); +import compress = require('compression'); + +var app = express(); +app.use(compress()); +app.use(compress({ + threshold: 512 +})); diff --git a/compression/compression.d.ts b/compression/compression.d.ts new file mode 100644 index 0000000000..00b2e0459a --- /dev/null +++ b/compression/compression.d.ts @@ -0,0 +1,20 @@ +// Type definitions for compression +// Project: https://github.com/expressjs/compression +// Definitions by: Santi Albo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "compression" { + import express = require('express'); + + module e { + interface CompressionOptions { + threshold?: number; + filter?: Function; + } + } + + function e(options?: e.CompressionOptions): express.RequestHandler; + export = e; +} \ No newline at end of file diff --git a/consolidate/consolidate-tests.ts b/consolidate/consolidate-tests.ts new file mode 100644 index 0000000000..bf4fea4496 --- /dev/null +++ b/consolidate/consolidate-tests.ts @@ -0,0 +1,27 @@ +/// + +import consolidate = require('consolidate'); + +var path: string = null; +var options: any = null; +var fn: any = null; + +consolidate.clearCache(); +consolidate.jade(path, options, fn); +consolidate.dust(path, options, fn); +consolidate.swig(path, options, fn); +consolidate.liquor(path, options, fn); +consolidate.ejs(path, options, fn); +consolidate.eco(path, options, fn); +consolidate.jazz(path, options, fn); +consolidate.jqtpl(path, options, fn); +consolidate.haml(path, options, fn); +consolidate.whiskers(path, options, fn); +//consolidate.'haml-coffee':Function; +consolidate.hogan(path, options, fn); +consolidate.handlebars(path, options, fn); +consolidate.underscore(path, options, fn); +consolidate.qejs(path, options, fn); +consolidate.walrus(path, options, fn); +consolidate.mustache(path, options, fn); +consolidate.dot(path, options, fn); diff --git a/consolidate/consolidate.d.ts b/consolidate/consolidate.d.ts new file mode 100644 index 0000000000..3bfe35bf04 --- /dev/null +++ b/consolidate/consolidate.d.ts @@ -0,0 +1,30 @@ +// Type definitions for consolidate +// Project: https://github.com/visionmedia/consolidate.js +// Definitions by: Carlos Ballesteros Velasco +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/consolidate.d.ts + +/// + +declare module "consolidate" { + export function clearCache(): void; + export var jade: (path: String, options: any, fn: any) => void; + export var dust: (path: String, options: any, fn: any) => void; + export var swig: (path: String, options: any, fn: any) => void; + export var liquor: (path: String, options: any, fn: any) => void; + export var ejs: (path: String, options: any, fn: any) => void; + export var eco: (path: String, options: any, fn: any) => void; + export var jazz: (path: String, options: any, fn: any) => void; + export var jqtpl: (path: String, options: any, fn: any) => void; + export var haml: (path: String, options: any, fn: any) => void; + export var whiskers: (path: String, options: any, fn: any) => void; + //export var 'haml-coffee':Function; + export var hogan: (path: String, options: any, fn: any) => void; + export var handlebars: (path: String, options: any, fn: any) => void; + export var underscore: (path: String, options: any, fn: any) => void; + export var qejs: (path: String, options: any, fn: any) => void; + export var walrus: (path: String, options: any, fn: any) => void; + export var mustache: (path: String, options: any, fn: any) => void; + export var dot: (path: String, options: any, fn: any) => void; +} diff --git a/cookie-parser/cookie-parser-tests.ts b/cookie-parser/cookie-parser-tests.ts new file mode 100644 index 0000000000..94e8a9fdb2 --- /dev/null +++ b/cookie-parser/cookie-parser-tests.ts @@ -0,0 +1,7 @@ +/// + +import express = require('express'); +import cookieParser = require('cookie-parser'); + +var app = express(); +app.use(cookieParser('optional secret string')); diff --git a/cookie-parser/cookie-parser.d.ts b/cookie-parser/cookie-parser.d.ts new file mode 100644 index 0000000000..a4897c5e7e --- /dev/null +++ b/cookie-parser/cookie-parser.d.ts @@ -0,0 +1,12 @@ +// Type definitions for cookie-parser +// Project: https://github.com/expressjs/cookie-parser +// Definitions by: Santi Albo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "cookie-parser" { + import express = require('express'); + function e(secret?: string, options?: any): express.RequestHandler; + export = e; +} \ No newline at end of file diff --git a/cordova-ionic/cordova-ionic-tests.ts b/cordova-ionic/cordova-ionic-tests.ts new file mode 100644 index 0000000000..69d1a3d829 --- /dev/null +++ b/cordova-ionic/cordova-ionic-tests.ts @@ -0,0 +1,10 @@ +/// +/// + +// Keyboard +cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); +cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false); +cordova.plugins.Keyboard.close(); +cordova.plugins.Keyboard.disableScroll(true); +cordova.plugins.Keyboard.disableScroll(false); +console.log(cordova.plugins.Keyboard.isVisible); diff --git a/cordova-ionic/cordova-ionic.d.ts b/cordova-ionic/cordova-ionic.d.ts new file mode 100644 index 0000000000..c9b1e635b3 --- /dev/null +++ b/cordova-ionic/cordova-ionic.d.ts @@ -0,0 +1,14 @@ +// Type definitions for Ionic Cordova plugins +// Project: https://github.com/driftyco +// Definitions by: Hendrik Maus +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface Cordova { + plugins:Plugins; +} + +interface Plugins { + Keyboard:Ionic.Keyboard; +} diff --git a/cordova-ionic/plugins/keyboard.d.ts b/cordova-ionic/plugins/keyboard.d.ts new file mode 100644 index 0000000000..4ff9e293d5 --- /dev/null +++ b/cordova-ionic/plugins/keyboard.d.ts @@ -0,0 +1,33 @@ +// Type definitions for Cordova Keyboard plugin +// Project: https://github.com/driftyco/ionic-plugins-keyboard +// Definitions by: Hendrik Maus +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Ionic { + interface Keyboard { + + /** + * Hide the keyboard accessory bar with the next, previous and done buttons. + * + * @param hide + */ + hideKeyboardAccessoryBar(hide:boolean): void; + + /** + * Close the keyboard if it is open. + */ + close(): void; + + /** + * Disable native scrolling, useful if you are using JavaScript to scroll + * + * @param disbale + */ + disableScroll(disbale:boolean): void; + + /** + * Whether or not the keyboard is currently visible. + */ + isVisible: boolean; + } +} diff --git a/cordova/cordova.d.ts b/cordova/cordova.d.ts index 95be388824..9377912b00 100644 --- a/cordova/cordova.d.ts +++ b/cordova/cordova.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Apache Cordova. +// Type definitions for Apache Cordova // Project: http://cordova.apache.org -// Definitions by: Microsoft Open Technologies, Inc. +// Definitions by: Microsoft Open Technologies Inc. // Definitions: https://github.com/borisyankov/DefinitelyTyped // // Copyright (c) Microsoft Open Technologies, Inc. @@ -57,4 +57,4 @@ interface UrlUtil { } /** Apache Cordova instance */ -declare var cordova: Cordova; \ No newline at end of file +declare var cordova: Cordova; diff --git a/cordova/plugins/Contacts.d.ts b/cordova/plugins/Contacts.d.ts index a6f7bc0868..f054c12d09 100644 --- a/cordova/plugins/Contacts.d.ts +++ b/cordova/plugins/Contacts.d.ts @@ -143,9 +143,9 @@ interface ContactName { /** The contact's middle name. */ middleName?: string; /** The contact's prefix (example Mr. or Dr.) */ - honorifixPrefix?: string; + honorificPrefix?: string; /** The contact's suffix (example Esq.). */ - honorifixSuffix?: string; + honorificSuffix?: string; } declare var ContactName: { @@ -154,8 +154,8 @@ declare var ContactName: { familyName?: string, givenName?: string, middleName?: string, - honorifixPrefix?: string, - honorifixSuffix?: string): ContactName + honorificPrefix?: string, + honorificSuffix?: string): ContactName }; /** @@ -171,19 +171,19 @@ declare var ContactName: { * contains a base64-encoded image string. */ interface ContactField { - /** Set to true if this ContactField contains the user's preferred value. */ - pref: boolean; /** A string that indicates what type of field this is, home for example. */ type: string; /** The value of the field, such as a phone number or email address. */ value: string; + /** Set to true if this ContactField contains the user's preferred value. */ + pref: boolean; } declare var ContactField: { /** Constructor for ContactField object */ new(type?: string, - pref?: boolean, - value?: string): ContactField + value?: string, + pref?: boolean): ContactField }; /** diff --git a/cordova/plugins/FileSystem.d.ts b/cordova/plugins/FileSystem.d.ts index 4aefa5ecfd..569f9a2096 100644 --- a/cordova/plugins/FileSystem.d.ts +++ b/cordova/plugins/FileSystem.d.ts @@ -25,17 +25,7 @@ interface Window { /** This interface represents a file system. */ interface FileSystem { - /** - * Constructor for FileSystem object - * @param name 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. - * @param root The root directory of the file system. - */ - new (name: string, root: DirectoryEntry) - /** - * 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. - */ + /* The name of the file system, unique across the list of exposed file systems. */ name: string; /** The root directory of the file system. */ root: DirectoryEntry; @@ -46,8 +36,6 @@ interface FileSystem { * each of which may be a File or DirectoryEntry. */ interface Entry { - /** Constructor for Entry object */ - new ( isFile: boolean, isDirectory: boolean, name: string, fullPath: string, fileSystem: FileSystem, nativeURL: string) ; /** Entry is a file. */ isFile: boolean; /** Entry is a directory. */ @@ -265,13 +253,13 @@ interface FileSaver extends EventTarget { */ 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. + * The byte offset at which the next write to the file will occur. This always less or equal than length. + * A newly-created FileWriter will 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. + * this will be the highest byte offset at which the user has written. */ length: number; /** @@ -287,7 +275,7 @@ interface FileWriter extends FileSaver { 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. + * will be discarded. If extending the file, the existing data will 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; diff --git a/cordova/plugins/Media.d.ts b/cordova/plugins/Media.d.ts index 3751152be1..21d1a17e38 100644 --- a/cordova/plugins/Media.d.ts +++ b/cordova/plugins/Media.d.ts @@ -27,19 +27,6 @@ declare var Media: { * W3C specification and may deprecate the current APIs. */ interface Media { - /** - * Constructor for Media object. - * @param src A URI containing the audio content. - * @param mediaSuccess The callback that executes after a Media object has completed - * the current play, record, or stop action. - * @param mediaError The callback that executes if an error occurs. - * @param mediaStatus The callback that executes to indicate status changes. - */ - new ( - src: string, - mediaSuccess: () => void, - mediaError?: (error: MediaError) => any, - mediaStatus?: (status: number) => void): Media; /** * Returns the current position within an audio file. Also updates the Media object's position parameter. * @param mediaSuccess The callback that is passed the current position in seconds. diff --git a/cordova/plugins/WebSQL.d.ts b/cordova/plugins/WebSQL.d.ts index 807dab42a7..8d28a69c8f 100644 --- a/cordova/plugins/WebSQL.d.ts +++ b/cordova/plugins/WebSQL.d.ts @@ -1,5 +1,5 @@ // Type definitions for Apache Cordova WebSQL plugin. -// Project: https://github.com/sgrebnov/cordova-plugin-websql +// Project: https://github.com/MSOpenTech/cordova-plugin-websql // Definitions by: Microsoft Open Technologies, Inc. // Definitions: https://github.com/borisyankov/DefinitelyTyped // @@ -43,7 +43,7 @@ interface Database { successCallback?: () => void): void; name: string; version: string; - displayname: string; + displayName: string; size: number; } diff --git a/cordovarduino/cordovarduino-tests.ts b/cordovarduino/cordovarduino-tests.ts new file mode 100644 index 0000000000..a4fd608789 --- /dev/null +++ b/cordovarduino/cordovarduino-tests.ts @@ -0,0 +1,38 @@ +/// + +serial.requestPermission(function success() {}, function error() {}); +serial.open({}, function success() {}, function error() {}); +serial.write('data_string', function success() {}, function error() {}); +serial.read(function success() {}, function error() {}); +serial.registerReadCallback( + function success(data:any) { + var view = new Uint8Array(data); + console.log(view); + }, + function error() { + new Error("Failed to register read callback"); + }); +serial.close(function success() {}, function error() {}); + +var errorCallback = function (message:string) { + alert('Error: ' + message); +}; + +serial.requestPermission( + function (successMessage:string) { + serial.open( + {baudRate: 9600}, + function (successMessage:string) { + serial.write( + '1', + function (successMessage:string) { + alert(successMessage); + }, + errorCallback + ); + }, + errorCallback + ); + }, + errorCallback +); diff --git a/cordovarduino/cordovarduino.d.ts b/cordovarduino/cordovarduino.d.ts new file mode 100644 index 0000000000..0fccff2ad9 --- /dev/null +++ b/cordovarduino/cordovarduino.d.ts @@ -0,0 +1,84 @@ +// Type definitions for Cordovarduino plugin +// Project: https://github.com/stereolux/cordovarduino +// Definitions by: Hendrik Maus +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Cordovardunio { + interface Serial { + /** + * Request permission to interact with the serial port. + * + * @param successCallback Function to call on success + * @param errorCallback Function to call on error + */ + requestPermission(successCallback:Function, errorCallback:Function): void; + + /** + * Open a connection. + * + * @param opts SerialOptions object + * @param successCallback Function to call on success + * @param errorCallback Function to call on error + */ + open(opts:SerialOptions, successCallback:Function, errorCallback:Function): void + + /** + * Write to the serial port. + * + * @param data String data to write to serial port + * @param successCallback Function to call on success + * @param errorCallback Function to call on error + */ + write(data:string, successCallback:Function, errorCallback:Function): void; + + /** + * Read from the serial port. + * + * @param successCallback Function to call on success + * @param errorCallback Function to call on error + */ + read(successCallback:Function, errorCallback:Function): void; + + /** + * Close connection. + * + * @param successCallback Function to call on success + * @param errorCallback Function to call on error + */ + close(successCallback:Function, errorCallback:Function): void; + + /** + * Register a callback for the driver reading incoming data from the serial device + * + * @param successCallback Function to call on success + * @param errorCallback Function to call on error + */ + registerReadCallback(successCallback:Function, errorCallback:Function): void; + } + + interface SerialOptions { + /** + * @defaultValue 9600 + */ + baudRate?: number; + + /** + * @defaultValue 8 + */ + dataBits?: number; + + /** + * @defaultValue 1 + */ + stopBits?: number; + + /** + * @defaultValue 0 + */ + parity?: number; + } +} + + +// Plugin will be surfaced as window.serial +declare var serial:Cordovardunio.Serial; diff --git a/couchbase/couchbase.d.ts b/couchbase/couchbase.d.ts index 2b0a720a93..3a8605b731 100644 --- a/couchbase/couchbase.d.ts +++ b/couchbase/couchbase.d.ts @@ -648,8 +648,8 @@ declare module 'couchbase' { append(key: string, fragment: string, callback: KeyCallback): void; append(key: string, fragment: string, options: AppendOptions, callback: KeyCallback): void; - append(key: string, fragment: NodeBuffer, callback: KeyCallback): void; - append(key: string, fragment: NodeBuffer, options: AppendOptions, callback: KeyCallback): void; + append(key: string, fragment: Buffer, callback: KeyCallback): void; + append(key: string, fragment: Buffer, options: AppendOptions, callback: KeyCallback): void; appendMulti(kv: { [key: string]: AppendMultiOptionsForValue }, options: AppendMultiOptions, callback: MultiCallback): void; decr(key: string, callback: KeyCallback): void; @@ -683,8 +683,8 @@ declare module 'couchbase' { prepend(key: string, fragment: string, callback: KeyCallback): void; prepend(key: string, fragment: string, options: PrependOptions, callback: KeyCallback): void; - prepend(key: string, fragment: NodeBuffer, callback: KeyCallback): void; - prepend(key: string, fragment: NodeBuffer, options: PrependOptions, callback: KeyCallback): void; + prepend(key: string, fragment: Buffer, callback: KeyCallback): void; + prepend(key: string, fragment: Buffer, options: PrependOptions, callback: KeyCallback): void; prependMulti(kv: { [key: string]: PrependMultiOptionsFoValue }, options: { [key: string]: PrependMultiOptions }, callback: MultiCallback): void; remove(key: string, callback: KeyCallback): void; diff --git a/createjs-lib/createjs-lib.d.ts b/createjs-lib/createjs-lib.d.ts index 048fde92df..a61679aa7a 100644 --- a/createjs-lib/createjs-lib.d.ts +++ b/createjs-lib/createjs-lib.d.ts @@ -1,5 +1,5 @@ -// Type definitions for EaselJS 0.7.1, TweenJS 0.5.1, SoundJS 0.5.2, PreloadJS 0.4.1 -// Project: http://www.createjs.com/#!/EaselJS +// Type definitions for CreateJS +// Project: http://www.createjs.com/ // Definitions by: Pedro Ferreira , Chris Smith , Satoru Kimura // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/createjs/createjs.d.ts b/createjs/createjs.d.ts index 7be29abbea..f064d07f61 100644 --- a/createjs/createjs.d.ts +++ b/createjs/createjs.d.ts @@ -1,5 +1,5 @@ -// Type definitions for EaselJS 0.7.1, TweenJS 0.5.1, SoundJS 0.5.2, PreloadJS 0.4.1 -// Project: http://www.createjs.com/#!/EaselJS +// Type definitions for CreateJS +// Project: http://www.createjs.com/ // Definitions by: Pedro Ferreira , Chris Smith , Satoru Kimura // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/crossroads/crossroads.d.ts b/crossroads/crossroads.d.ts index 76fad217ac..e86e3154df 100644 --- a/crossroads/crossroads.d.ts +++ b/crossroads/crossroads.d.ts @@ -1,7 +1,7 @@ // Type definitions for Crossroads.js // Project: http://millermedeiros.github.io/crossroads.js/ // Definitions by: Diullei Gomes -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/d3/d3-tests.ts b/d3/d3-tests.ts index aab65c06c0..1a2b5f1c58 100644 --- a/d3/d3-tests.ts +++ b/d3/d3-tests.ts @@ -2286,62 +2286,57 @@ function attrObjTest () { .attr({"xlink:href": function(d, i) { return d + "-" + i + ".png"; }}); } +// Test for setting styles as an object +// From https://github.com/mbostock/d3/blob/master/test/selection/style-test.js +function styleObjTest () { + d3.select('body') + .style({"background-color": "white", opacity: .42}); +} + +// Test for setting styles as an object +// From https://github.com/mbostock/d3/blob/master/test/selection/property-test.js +function propertyObjTest () { + d3.select('body') + .property({bgcolor: "purple", opacity: .41}); +} + + // Test for brushes -// This triggers a bug (shown below) in the 0.9.0 compiler, but works with -// 0.9.1 compiler. +function brushTest() { + var xScale = d3.scale.linear(), + yScale = d3.scale.linear(); -// Stack trace: -// /usr/local/share/npm/lib/node_modules/typescript/bin/tsc.js:38215 -// return (type === this.semanticInfoChain.anyTypeSymbol) || type.isError(); -// ^ -// TypeError: Cannot call method 'isError' of null -// at PullTypeResolver.isAnyOrEquivalent (/usr/local/share/npm/lib/node_modules/typescript/bin/tsc.js:38215:76) -// at PullTypeResolver.resolveNameExpression (/usr/local/share/npm/lib/node_modules/typescript/bin/tsc.js:39953:39) -// at PullTypeResolver.resolveAST (/usr/local/share/npm/lib/node_modules/typescript/bin/tsc.js:39758:37) -// at PullTypeResolver.computeIndexExpressionSymbol (/usr/local/share/npm/lib/node_modules/typescript/bin/tsc.js:40933:37) -// at PullTypeResolver.resolveIndexExpression (/usr/local/share/npm/lib/node_modules/typescript/bin/tsc.js:40925:45) -// at PullTypeResolver.resolveAST (/usr/local/share/npm/lib/node_modules/typescript/bin/tsc.js:39870:33) -// at PullTypeResolver.resolveOverloads (/usr/local/share/npm/lib/node_modules/typescript/bin/tsc.js:42917:43) -// at PullTypeResolver.computeCallExpressionSymbol (/usr/local/share/npm/lib/node_modules/typescript/bin/tsc.js:41373:34) -// at PullTypeResolver.resolveCallExpression (/usr/local/share/npm/lib/node_modules/typescript/bin/tsc.js:41175:29) -// at PullTypeChecker.typeCheckCallExpression (/usr/local/share/npm/lib/node_modules/typescript/bin/tsc.js:45111:58) -// at PullTypeChecker.typeCheckAST (/usr/local/share/npm/lib/node_modules/typescript/bin/tsc.js:43786:33) + var xMin = 0, xMax = 1, + yMin = 0, yMax = 1; -// function brushTest() { -// var xScale = d3.scale.linear(), -// yScale = d3.scale.linear(); -// -// var xMin = 0, xMax = 1, -// yMin = 0, yMax = 1; -// -// // Setting only x scale. -// var brush1 = d3.svg.brush() -// .x(xScale) -// .on('brush', function () { -// var extent = brush1.extent(); -// xMin = Math.max(extent[0], 0); -// xMax = Math.min(extent[1], 1); -// brush1.extent([xMin, xMax]); -// }); -// -// // Setting both the x and y scale -// var brush2 = d3.svg.brush() -// .x(xScale) -// .y(yScale) -// .on('brush', function () { -// var extent = brush2.extent(); -// var xExtent = extent[0], -// yExtent = extent[1]; -// -// xMin = Math.max(xExtent[0], 0); -// xMax = Math.min(xExtent[1], 1); -// -// yMin = Math.max(yExtent[0], 0); -// yMax = Math.min(yExtent[1], 1); -// -// brush1.extent([[xMin, xMax], [yMin, yMax]]); -// }); -// } + // Setting only x scale. + var brush1 = d3.svg.brush() + .x(xScale) + .on('brush', function () { + var extent = brush1.extent(); + xMin = Math.max(extent[0], 0); + xMax = Math.min(extent[1], 1); + brush1.extent([xMin, xMax]); + }); + + // Setting both the x and y scale + var brush2 = d3.svg.brush() + .x(xScale) + .y(yScale) + .on('brush', function () { + var extent = brush2.extent(); + var xExtent = extent[0], + yExtent = extent[1]; + + xMin = Math.max(xExtent[0], 0); + xMax = Math.min(xExtent[1], 1); + + yMin = Math.max(yExtent[0], 0); + yMax = Math.min(yExtent[1], 1); + + brush1.extent([[xMin, xMax], [yMin, yMax]]); + }); +} // Tests for area @@ -2592,4 +2587,42 @@ function extentTest() { d3.extent(["20", 3], (d) => { return d; }); d3.extent([3, "20"], (d) => { return d; }); d3.extent(["3", 20], (d) => { return d; }); +} + +// Tests for d3.time.format.multi +// Adopted from http://bl.ocks.org/mbostock/4149176 +function multiTest() { + var customTimeFormat = d3.time.format.multi([ + [".%L", function(d) { return d.getMilliseconds(); }], + [":%S", function(d) { return d.getSeconds(); }], + ["%I:%M", function(d) { return d.getMinutes(); }], + ["%I %p", function(d) { return d.getHours(); }], + ["%a %d", function(d) { return d.getDay() && d.getDate() != 1; }], + ["%b %d", function(d) { return d.getDate() != 1; }], + ["%B", function(d) { return d.getMonth(); }], + ["%Y", function() { return true; }] + ]); + + var margin = {top: 250, right: 40, bottom: 250, left: 40}, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var x = d3.time.scale() + .domain([new Date(2012, 0, 1), new Date(2013, 0, 1)]) + .range([0, width]); + + var xAxis = d3.svg.axis() + .scale(x) + .tickFormat(customTimeFormat); + + 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 + ")"); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); } \ No newline at end of file diff --git a/d3/d3.d.ts b/d3/d3.d.ts old mode 100644 new mode 100755 index 5f68f6f362..0354bc2645 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -42,14 +42,14 @@ declare module D3 { }; } - export interface Event { + export interface D3Event extends Event{ dx: number; dy: number; clientX: number; clientY: number; translate: number[]; scale: number; - sourceEvent: Event; + sourceEvent: D3Event; x: number; y: number; keyCode: number; @@ -65,7 +65,7 @@ declare module D3 { /** * Access the current user event for interaction */ - event: Event; + event: D3Event; /** * Compare two values for sorting. @@ -710,7 +710,7 @@ declare module D3 { (name: string): string; (name: string, value: any): Selection; (name: string, valueFunction: (data: any, index: number) => any): Selection; - (attrValueMap : any): Selection; + (attrValueMap : Object): Selection; }; classed: { @@ -723,12 +723,14 @@ declare module D3 { (name: string): string; (name: string, value: any, priority?: string): Selection; (name: string, valueFunction: (data: any, index: number) => any, priority?: string): Selection; + (styleValueMap : Object): Selection; }; property: { (name: string): void; (name: string, value: any): Selection; (name: string, valueFunction: (data: any, index: number) => any): Selection; + (propertyValueMap : Object): Selection; }; text: { @@ -747,10 +749,10 @@ declare module D3 { insert: (name: string, before: string) => Selection; remove: () => Selection; empty: () => boolean; - + data: { - (values: (data: any, index?: number) => any[], key?: (data: any, index?: number) => string): UpdateSelection; - (values: any[], key?: (data: any, index?: number) => string): UpdateSelection; + (values: (data: any, index?: number) => any[], key?: (data: any, index?: number) => any): UpdateSelection; + (values: any[], key?: (data: any, index?: number) => any): UpdateSelection; (): any[]; }; @@ -765,7 +767,7 @@ declare module D3 { //(filter: string): UpdateSelection; }; - call(callback: (selection: Selection) => void ): Selection; + call(callback: (selection: Selection, ...args: any[]) => void, ...args: any[]): Selection; each(eachFunction: (data: any, index: number) => any): Selection; on: { (type: string): (data: any, index: number) => any; @@ -809,7 +811,7 @@ declare module D3 { export interface EnterSelection { append: (name: string) => Selection; - insert: (name: string, before: string) => Selection; + insert: (name: string, before?: string) => Selection; select: (selector: string) => Selection; empty: () => boolean; node: () => Element; @@ -1001,9 +1003,29 @@ declare module D3 { fridays: Range; saturdays: Range; format: { - + /** + * Constructs a new local time formatter using the given specifier. + */ (specifier: string): TimeFormat; - utc: (specifier: string) => TimeFormat; + /** + * Returns a new multi-resolution time format given the specified array of predicated formats. + */ + multi: (formats: any[][]) => TimeFormat; + + utc: { + /** + * Constructs a new local time formatter using the given specifier. + */ + (specifier: string): TimeFormat; + /** + * Returns a new multi-resolution UTC time format given the specified array of predicated formats. + */ + multi: (formats: any[][]) => TimeFormat; + }; + + /** + * The full ISO 8601 UTC time format: "%Y-%m-%dT%H:%M:%S.%LZ". + */ iso: TimeFormat; }; @@ -1461,7 +1483,7 @@ declare module D3 { /** * decrease lightness by some exponential factor (gamma) */ - darker(k: number): Color; + darker(k?: number): Color; /** * convert the color to a string. */ @@ -1598,6 +1620,7 @@ declare module D3 { export interface Symbol { type: (string:string) => Symbol; size: (number:number) => Symbol; + (datum:any, index:number): string; } export interface Brush { @@ -2485,7 +2508,7 @@ declare module D3 { copy(): Scale; } - export interface QuantitiveScale extends Scale { + export interface QuantitativeScale extends Scale { /** * Get the range value corresponding to a given domain value. * @@ -2507,7 +2530,7 @@ declare module D3 { * * @param value The input domain */ - (values: any[]): QuantitiveScale; + (values: any[]): QuantitativeScale; /** * Get the scale's input domain. */ @@ -2522,7 +2545,7 @@ declare module D3 { * * @param value The output range. */ - (values: any[]): QuantitiveScale; + (values: any[]): QuantitativeScale; /** * Get the scale's output range. */ @@ -2533,26 +2556,26 @@ declare module D3 { * * @param value The output range. */ - rangeRound: (values: any[]) => QuantitiveScale; + rangeRound: (values: any[]) => QuantitativeScale; /** * get or set the scale's output interpolator. */ interpolate: { (): D3.Transition.Interpolate; - (factory: D3.Transition.Interpolate): QuantitiveScale; + (factory: D3.Transition.Interpolate): QuantitativeScale; }; /** * enable or disable clamping of the output range. * * @param clamp Enable or disable */ - clamp(clamp: boolean): QuantitiveScale; + clamp(clamp: boolean): QuantitativeScale; /** * extend the scale domain to nice round numbers. - * + * * @param count Optional number of ticks to exactly fit the domain */ - nice(count?: number): QuantitiveScale; + nice(count?: number): QuantitativeScale; /** * get representative values from the input domain. * @@ -2568,10 +2591,10 @@ declare module D3 { /** * create a new scale from an existing scale.. */ - copy(): QuantitiveScale; + copy(): QuantitativeScale; } - export interface LinearScale extends QuantitiveScale { + export interface LinearScale extends QuantitativeScale { /** * Get the range value corresponding to a given domain value. * @@ -2607,7 +2630,7 @@ declare module D3 { tickFormat(count: number): (n: number) => string; } - export interface SqrtScale extends QuantitiveScale { + export interface SqrtScale extends QuantitativeScale { /** * Get the range value corresponding to a given domain value. * @@ -2616,7 +2639,7 @@ declare module D3 { (value: number): number; } - export interface PowScale extends QuantitiveScale { + export interface PowScale extends QuantitativeScale { /** * Get the range value corresponding to a given domain value. * @@ -2625,7 +2648,7 @@ declare module D3 { (value: number): number; } - export interface LogScale extends QuantitiveScale { + export interface LogScale extends QuantitativeScale { /** * Get the range value corresponding to a given domain value. * @@ -2741,7 +2764,7 @@ declare module D3 { clamp(clamp: boolean): TimeScale; ticks: { (count: number): any[]; - (range: Range, count: number): any[]; + (range: D3.Time.Range, count: number): any[]; }; tickFormat(count: number): (n: number) => string; copy(): TimeScale; @@ -3394,7 +3417,7 @@ declare module D3 { * * @param constant The new constant value. */ - (constant: number): Voronoi; + (constant: number): Voronoi; } clipExtent: { /** diff --git a/d3/plugins/d3.superformula.d.ts.tscparams b/d3/plugins/d3.superformula.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/d3/plugins/d3.superformula.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/date.format.js/date.format-tests.ts b/date.format.js/date.format-tests.ts new file mode 100644 index 0000000000..d06e78cb7a --- /dev/null +++ b/date.format.js/date.format-tests.ts @@ -0,0 +1,10 @@ +/// + +// test dateFormat +var now : string = dateFormat(); +var nowFullDate : string = dateFormat( dateFormat.masks.fullDate ); + +// test format() (on the prototype of Date) +var then : Date = new Date( 2014, 1, 1 ); +var thenDefaultFormat : string = then.format(); +var thenCustomFormat : string = then.format('yyyy/m/d HH:MM'); diff --git a/date.format.js/date.format.d.ts b/date.format.js/date.format.d.ts new file mode 100644 index 0000000000..6e4ef4ea68 --- /dev/null +++ b/date.format.js/date.format.d.ts @@ -0,0 +1,244 @@ +// Type definitions for Date Format 1.2.3 +// Project: http://blog.stevenlevithan.com/archives/date-time-format +// Definitions by: Rob Stutton +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/***************************************************************************** + Portions 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. + ***************************************************************************** */ + +/** 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; + /** Returns a value as a string value appropriate to the host environment's current locale. */ + 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; + /** + * This is a convenience addition to the Date prototype + * Returns a formatted version of the date. + * The mask defaults to dateFormat.masks.default. + * @param {string=} mask + * @param {boolean=} utc + */ + format(mask?: string, utc?: boolean) : string; +} + +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 number between 0 and 11 (January to December). + * @param date The date as an number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. + * @param ms An number 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; +}; + +// Some common format strings +interface DateFormatMasks { + "default": string; + shortDate: string; + mediumDate: string; + longDate: string; + fullDate: string; + shortTime: string; + mediumTime: string; + longTime: string; + isoDate: string; + isoTime: string; + isoDateTime: string; + isoUtcDateTime: string; +} + +// Internationalization strings +interface DateFormatI18n { + dayNames: string[]; + monthNames: string[]; +} + +/** + * Accepts a date, a mask, or a date and a mask. + * Returns a formatted version of the given date. + * The date defaults to the current date/time. + * The mask defaults to dateFormat.masks.default. + * @param {Date=} date + * @param {string=} mask + * @param {boolean=} utc + */ +declare var dateFormat: { + (date?: any, mask?: string, utc?: boolean ): string; + masks : DateFormatMasks; + i18n : DateFormatI18n; +}; diff --git a/dcjs/dc.d.ts b/dcjs/dc.d.ts index 0391d2502f..2b06c34dda 100644 --- a/dcjs/dc.d.ts +++ b/dcjs/dc.d.ts @@ -1,7 +1,8 @@ // Type definitions for DCJS // Project: https://github.com/dc-js -// Definitions by: hans windhoff +// Definitions by: hans windhoff // Definitions: https://github.com/borisyankov/DefinitelyTyped + // this makes only sense together with d3 and crossfilter so you need the d3.d.ts and crossfilter.d.ts files /// @@ -195,4 +196,4 @@ export interface ILegendwidget { export function rowChart(cssSel: string): IRowchart; -} \ No newline at end of file +} diff --git a/deep-freeze/deep-freeze-tests.ts b/deep-freeze/deep-freeze-tests.ts new file mode 100644 index 0000000000..8369d30871 --- /dev/null +++ b/deep-freeze/deep-freeze-tests.ts @@ -0,0 +1,8 @@ +/// + +import df = require('deep-freeze'); + +class Foo { + foo: string; +} +var foo:Foo = df(new Foo()); diff --git a/deep-freeze/deep-freeze.d.ts b/deep-freeze/deep-freeze.d.ts new file mode 100644 index 0000000000..3d7ede8ad0 --- /dev/null +++ b/deep-freeze/deep-freeze.d.ts @@ -0,0 +1,9 @@ +// Type definitions for deep-freeze +// Project: https://github.com/substack/deep-freeze +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'deep-freeze' { + function df(obj: T): T; + export = df; +} diff --git a/dojo/README.md b/dojo/README.md new file mode 100644 index 0000000000..1fa593757d --- /dev/null +++ b/dojo/README.md @@ -0,0 +1,298 @@ +# Dojo Definitions Usage Notes + +## Overview +Anyone that has used Dojo for any length of time has probably discovered three things: +* Dojo is very powerful +* Dojo can be challenging to learn +* Dojo doesn't always play well with other + +Having said that, there are ways that Dojo can be coerced out of its shell to work with other JavaScript technologies. This README is intended to describe some techniques for getting the full power of Dojo to work in an environment where almost everything can take advantage of TypeScript. + +*Disclaimer*: Dojo is VERY big framework and, as such the type definitions are generated by a [tool](https://github.com/vansimke/DojoTypeDescriptionGenerator) from dojo's [API](dojotoolkit.org/api) docs. The generated files were then hand-polished to eliminate any import errors and clean up some obvious errors. This is all to say that the generated type definitions are not flawless and are not guaranteed to reflect the actual implementations. + +## Basic Usage +A normal dojo module might look something like this: + +```js + define(['dojo/request', 'dojo/request/xhr'], + function (request, xhr) { + ... + } + ); +``` + +When using the TypeScript, you can write the following: + +```ts + define(['dojo/request', 'dojo/request/xhr'], + function (request: dojo.request, + xhr: dojo.request.xhr) { + ... + } + ); + ``` + + Inside of the define variable, both `request` and `xhr` will work as the functions that come from Dojo, only they are strongly typed. + +## Advanced Usage + Dojo and TypeScript both use different and conflicting class semantics. This causes some issues when trying to create custom class modules that are strongly typed in other modules. The following technique is presented as **A** solution to the problem, but not necessarily the best one. Other ideas a welcomed! + + Using pure JavaScript, a class that has a base class and mixins can be defined in Dojo as follows: + + ```js + define(['dojo/_base/declare', 'dijit/_WidgetBase', 'dijit/_TemplatedMixin', 'dojo/request'], + function(dojoDeclare, _WidgetBase, _TemplatedMixin, request) { + var Foo = dojoDeclare([_WidgetBase, _TemplatedMixin], { + templateString: '
Hello TypeScript { + console.log(data); + }); + } + + } + } +``` + +This class is identical to the standard Dojo method, except that it is declared inside of a TypeScript module and it is declared using TypeScript instead of Dojo's `declare` method. Two problems arise however: +1. `Foo` has an error because it doesn't honor the interface declared by dijit._TemplatedMixin +2. `request` is undefined + +The first problem can be solved by adding the missing properties and methods, but this will only serve to clutter the code base over time. Instead, we are creating another base class that hides this requirement like so: + +```ts + module App { + export class Foo extends WidgetBaseWithTemplatedMixin { + constructor(public templateString= "
Hello TypeScript
", + public message= "") { + super(); + } + + sayMessage() { + alert(this.message); + } + + getServerInfo() { + request.get("http://dojoAndTypeScriptTogetherAtLast.html", (data: string) => { + console.log(data); + }); + } + + } + + export class WidgetBaseWithTemplatedMixin extends dijit._WidgetBase implements dijit._TemplatedMixin { + "attachScope": Object; + "searchContainerNode": boolean; + "templatePath": string; + "templateString": string; + buildRendering(): {} + destroyRendering(): {} + getCachedTemplate(templateString: String, alwaysUseString: boolean, doc: HTMLDocument): {} + + } + } +``` + +Now the base class meets TypeScript's requirements so it is happy. This class could easily be moved out to a general add-in file so that it can be created and forgotten since it is only here to make TypeScript happy. + +The second problem that we had as that `request` is undefined. This is going to take a bit more trickery as shown below: + +```ts + module App { + export class Foo extends WidgetBaseWithTemplatedMixin { + constructor(public templateString= "
Hello TypeScript
", + public message= "") { + super(); + } + + public request: dojo.request; + + sayMessage() { + alert(this.message); + } + + getServerInfo() { + this.request.get("http://dojoAndTypeScriptTogetherAtLast.html").then((data: string) => { + console.log(data); + }); + } + + } + + export class WidgetBaseWithTemplatedMixin extends dijit._WidgetBase implements dijit._TemplatedMixin { + public static getPrototype(deps: Object) { + if (deps) { + for (var i in deps) { + this.prototype[i] = deps[i]; + } + + return this.prototype; + } + } + + "attachScope": Object; + "searchContainerNode": boolean; + "templatePath": string; + "templateString": string; + buildRendering(): {} + destroyRendering(): {} + getCachedTemplate(templateString: String, alwaysUseString: boolean, doc: HTMLDocument): {} + + } + } + + + define(['dojo/_base/declare', 'dijit/_WidgetBase', 'dijit/_TemplatedMixin', 'dojo/request'], + function (dojoDeclare, _WidgetBase, _TemplatedMixin, request) { + var deps = { + request: request + }; + + var Foo = dojoDeclare([_WidgetBase, _TemplatedMixin], App.Foo.getPrototype(deps)); + + return Foo; + } + ); +``` + +Yes, I know - pretty crazy right. But, we're getting close... + +In the Dojo module, we are building an object that contains references to each of the dependencies. We are then passing that object into the static method `getPrototype` that we have added to the base class. This method takes an object literal and mixes it into the class's prototype. In this way, the module dependencies are made available to the TypeScript class via its prototype. The last thing we need to do is change the `getServerInfo()`'s call to `request` to be a `this.request` call since it is calling through its prototype instead of the ambient object that is used in Dojo. + +Okay, great. TypeScript is happy. Everything should be working right? Wrong. + +We have two more problems that are not apparent until the code is actually executed. They are both related to our usage of the `extends` keyword that we used to show that our `Foo` class extends from `dijit._WidgetBase`. + +The first problem is that, as stated previously, TypeScript has its own implementation of a class system in JavaScript. When one class extends another, TypeScript injects the following snippet into the module: + +```js + var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); + }; +``` + +This method is called in a closure that wraps the class definition and mixes the parent's prototype and owned properties into the child class. However, this won't work in our case, because our base class is `dijit._WidgetBase` which doesn't actually exist in the global namespace (where TypeScript expects it). This is because we are still using Dojo's class system (via `declare`). This is an important, and confusing, point. Our class is actually being constructed by Dojo using declare. However, we are working with the class as if it was created in the way the TypeScript expects. In short, this means that we don't actually need the `__extends` function to work, but something needs to be there so that the constructor function doesn't die. The solve is actually relatively easy: In the main HTML page, add this function before the tag that includes `dojo.js`: + +```js +var __extends = function (d, b) { + if (d && b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { + this.constructor = d; + } + + __.prototype = b.prototype; + d.prototype = new __(); + } +}; +``` + +All this does is check to see if `d` and `b` are defined before running. Since TypeScript won't override __extends, it will allow us to override the default implementation. + +Okay, only one more thing to deal with: the call to super. This issue is also related to TypeScript's method for handling inheritance. After calling `__extends`, the generated constructor function will call the parent's constructor function. Once again, we are hit by the fact that our base class (`dijit._WidgetBase`) doesn't actually exist where TypeScript is expecting it. The only way around this is to give TypeScript something to call. This simplest thing to do is to add a no-op function for TypeScript to call. In short add this: + +```js + var dijit = dijit || {}; + dijit._WidgetBase = function() {} +``` + +Into the page after Dojo bootstraps, but before our module loads. The simplest way to do this is to create a little module that does this and added it to the array of modules loaded in the `define()` call of the module. + +Okay, so things look pretty messy right now. There are several hacks and tricks that we have to play in order to allow TypeScript and Dojo to work together. The nice thing about most of this is that it can all be shoved into a single helper module and never thought of again. Here is an example of what that module would look like: + +```ts + "use strict"; + + define([], function () { }); + + var __extends = function (d, b) { + if (d && b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { + this.constructor = d; + } + + __.prototype = b.prototype; + d.prototype = new __(); + } + }; + + window['dojo'] = {}; + window['dijit'] = { + _WidgetBase: function () { + + } + }; + + module Base { + function getPrototype(type: Function, deps: Object): Object { + if (deps) { + for (var i in deps) { + type.prototype[i] = deps[i]; + } + + return this.prototype; + } + } + export class WidgetBaseWithTemplatedMixin extends dijit._WidgetBase implements dijit._TemplatedMixin { + public static getPrototype(deps: Object): Object { + return getPrototype(this, deps); + } + + "attachScope": Object; + "searchContainerNode": boolean; + "templatePath": string; + "templateString": string; + buildRendering() { } + destroyRendering() { } + getCachedTemplate(templateString: String, alwaysUseString: boolean, doc: HTMLDocument) { } + + } + } +``` + +This module can then be added to whenever we have another base class / mix-in combination (e.g. dijit/_WidgetBase, dijit/_TemplatedMixin, and dijit/_WidgetsInTemplateMixin). When done this way, the only regularly visible changes that we have to do is to compose the hash of dependencies and call the `getPrototype` as the last argument to `declare`. + +## Appendix + +Examples: +* https://github.com/craigstjean/typescript-dojo-sample + diff --git a/dojo/dijit.d.ts b/dojo/dijit.d.ts new file mode 100644 index 0000000000..f95d636c08 --- /dev/null +++ b/dojo/dijit.d.ts @@ -0,0 +1,104749 @@ +// Type definitions for Dojo v1.9 +// Project: http://dojotoolkit.org +// Definitions by: Michael Van Sickle +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module dijit { + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_BidiSupport.html + * + * Deprecated module for enabling textdir support in the dijit widgets. New code should just define + * has("dojo-bidi") to return true, rather than manually requiring this module. + * + */ + interface _BidiSupport{(): void} + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/BackgroundIframe.html + * + * For IE/FF z-index shenanigans. id attribute is required. + * new dijit.BackgroundIframe(node). + * + * Makes a background iframe as a child of node, that fills + * area (and position) of node + * + * @param node + */ + interface BackgroundIframe{(node: HTMLElement): void} + module BackgroundIframe { + /** + * destroy the iframe + * + */ + interface destroy{(): void} + /** + * Resize the iframe so it's the same size as node. + * Needed on IE6 and IE/quirks because height:100% doesn't work right. + * + * @param node + */ + interface resize{(node: any): void} + } + + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/hccss.html + * + * Test if computer is in high contrast mode, and sets dijit_a11y flag on if it is. + * Deprecated, use dojo/hccss instead. + * + */ + interface hccss{(): void} + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_AttachMixin.html + * + * Mixin for widgets to attach to dom nodes and setup events via + * convenient data-dojo-attach-point and data-dojo-attach-event DOM attributes. + * + * Superclass of _TemplatedMixin, and can also be used standalone when templates are pre-rendered on the + * server. + * + * Does not [yet] handle widgets like ContentPane with this.containerNode set. It should skip + * scanning for data-dojo-attach-point and data-dojo-attach-event inside this.containerNode, but it + * doesn't. + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified, replace srcNodeRef with my generated DOM tree. + */ + class _AttachMixin { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + /** + * Search descendants of this.containerNode for data-dojo-attach-point and data-dojo-attach-event. + * Should generally be left false (the default value) both for performance and to avoid failures when + * this.containerNode holds other _AttachMixin instances with their own attach points and events. + * + */ + "searchContainerNode": boolean; + /** + * Attach to DOM nodes marked with special attributes. + * + */ + buildRendering(): void; + /** + * + */ + destroyRendering(): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_Container.html + * + * Mixin for widgets that contain HTML and/or a set of widget children. + * + */ + class _Container { + constructor(); + /** + * Makes the given widget a child of this widget. + * Inserts specified child widget's dom node as a child of this widget's + * container node, and possibly does other processing (such as layout). + * + * @param widget + * @param insertIndex Optional + */ + addChild(widget: dijit._WidgetBase, insertIndex: number): void; + /** + * + */ + buildRendering(): void; + /** + * Gets the index of the child in this container or -1 if not found + * + * @param child + */ + getIndexOfChild(child: dijit._WidgetBase): any; + /** + * Returns true if widget has child widgets, i.e. if this.containerNode contains widgets. + * + */ + hasChildren(): boolean; + /** + * Removes the passed widget instance from this widget but does + * not destroy it. You can also pass in an integer indicating + * the index within the container to remove (ie, removeChild(5) removes the sixth widget). + * + * @param widget + */ + removeChild(widget: dijit._WidgetBase): void; + /** + * Removes the passed widget instance from this widget but does + * not destroy it. You can also pass in an integer indicating + * the index within the container to remove (ie, removeChild(5) removes the sixth widget). + * + * @param widget + */ + removeChild(widget: number): void; + + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_Contained.html + * + * Mixin for widgets that are children of a container widget + * + */ + class _Contained { + constructor(); + /** + * Returns the index of this widget within its container parent. + * It returns -1 if the parent does not exist, or if the parent + * is not a dijit/_Container + * + */ + getIndexInParent(): any; + /** + * Returns null if this is the last child of the parent, + * otherwise returns the next element sibling to the "right". + * + */ + getNextSibling(): any; + /** + * Returns null if this is the first child of the parent, + * otherwise returns the next element sibling to the "left". + * + */ + getPreviousSibling(): any; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_DialogMixin.html + * + * This provides functions useful to Dialog and TooltipDialog + * + */ + class _DialogMixin { + constructor(); + /** + * Callback when the user hits the submit button. + * Override this method to handle Dialog execution. + * After the user has pressed the submit button, the Dialog + * first calls onExecute() to notify the container to hide the + * dialog and restore focus to wherever it used to be. + * + * Then this method is called. + * + * @param formContents + */ + execute(formContents: Object): void; + /** + * Called when user has pressed the Dialog's cancel button, to notify container. + * Developer shouldn't override or connect to this method; + * it's a private communication device between the TooltipDialog + * and the thing that opened it (ex: dijit/form/DropDownButton) + * + */ + onCancel(): void; + /** + * Called when user has pressed the dialog's OK button, to notify container. + * Developer shouldn't override or connect to this method; + * it's a private communication device between the TooltipDialog + * and the thing that opened it (ex: dijit/form/DropDownButton) + * + */ + onExecute(): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_CssStateMixin.html + * + * Mixin for widgets to set CSS classes on the widget DOM nodes depending on hover/mouse press/focus + * state changes, and also higher-level state changes such becoming disabled or selected. + * By mixing this class into your widget, and setting the this.baseClass attribute, it will automatically + * maintain CSS classes on the widget root node (this.domNode) depending on hover, + * active, focus, etc. state. Ex: with a baseClass of dijitButton, it will apply the classes + * dijitButtonHovered and dijitButtonActive, as the user moves the mouse over the widget and clicks it. + * + * It also sets CSS like dijitButtonDisabled based on widget semantic state. + * + * By setting the cssStateNodes attribute, a widget can also track events on subnodes (like buttons + * within the widget). + * + */ + class _CssStateMixin { + constructor(); + /** + * True if mouse was pressed while over this widget, and hasn't been released yet + * + */ + "active": boolean; + /** + * Subclasses may define a cssStateNodes property that lists sub-nodes within the widget that + * need CSS classes applied on mouse hover/press and focus. + * + * Each entry in this optional hash is a an attach-point name (like "upArrowButton") mapped to a CSS class name + * (like "dijitUpArrowButton"). Example: + * + * { + * "upArrowButton": "dijitUpArrowButton", + * "downArrowButton": "dijitDownArrowButton" + * } + * The above will set the CSS class dijitUpArrowButton to the this.upArrowButton DOMNode when it + * + * is hovered, etc. + * + */ + "cssStateNodes": Object; + /** + * True if cursor is over this widget + * + */ + "hovering": boolean; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_FocusMixin.html + * + * Mixin to widget to provide _onFocus() and _onBlur() methods that + * fire when a widget or its descendants get/lose focus + * + */ + class _FocusMixin { + constructor(); + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_HasDropDown.html + * + * Mixin for widgets that need drop down ability. + * + */ + class _HasDropDown extends dijit._FocusMixin { + constructor(); + /** + * Set to true to make the drop down at least as wide as this + * widget. Set to false if the drop down should just be its + * default width. + * + */ + "autoWidth": boolean; + /** + * The widget to display as a popup. This widget must be + * defined before the startup function is called. + * + */ + "dropDown": Object; + /** + * This variable controls the position of the drop down. + * It's an array of strings with the following values: + * + * before: places drop down to the left of the target node/widget, or to the right in + * the case of RTL scripts like Hebrew and Arabic + * after: places drop down to the right of the target node/widget, or to the left in + * the case of RTL scripts like Hebrew and Arabic + * above: drop down goes above target node + * below: drop down goes below target node + * The list is positions is tried, in order, until a position is found where the drop down fits + * within the viewport. + * + */ + "dropDownPosition": Object; + /** + * Set to true to make the drop down exactly as wide as this + * widget. Overrides autoWidth. + * + */ + "forceWidth": boolean; + /** + * The max height for our dropdown. + * Any dropdown taller than this will have scrollbars. + * Set to 0 for no max height, or -1 to limit height to available space in viewport + * + */ + "maxHeight": number; + /** + * + */ + buildRendering(): void; + /** + * Closes the drop down on this widget + * + * @param focus If true, refocuses the button widget + */ + closeDropDown(focus: boolean): void; + /** + * + */ + destroy(): void; + /** + * Returns true if the dropdown exists and it's data is loaded. This can + * be overridden in order to force a call to loadDropDown(). + * + */ + isLoaded(): boolean; + /** + * Creates the drop down if it doesn't exist, loads the data + * if there's an href and it hasn't been loaded yet, and + * then opens the drop down. This is basically a callback when the + * user presses the down arrow button to open the drop down. + * + */ + loadAndOpenDropDown(): any; + /** + * Creates the drop down if it doesn't exist, loads the data + * if there's an href and it hasn't been loaded yet, and then calls + * the given callback. + * + * @param loadCallback + */ + loadDropDown(loadCallback: Function): void; + /** + * Opens the dropdown for this widget. To be called only when this.dropDown + * has been created and is ready to display (ie, it's data is loaded). + * + */ + openDropDown(): any; + /** + * set up nodes and connect our mouse and keyboard events + * + */ + postCreate(): void; + /** + * Callback when the user presses the down arrow button or presses + * the down arrow key to open/close the drop down. + * Toggle the drop-down widget; if it is up, close it, if not, open it + * + */ + toggleDropDown(): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_KeyNavMixin.html + * + * A mixin to allow arrow key and letter key navigation of child or descendant widgets. + * It can be used by dijit/_Container based widgets with a flat list of children, + * or more complex widgets like dijit/Tree. + * + * To use this mixin, the subclass must: + * + * - Implement _getNext(), _getFirst(), _getLast(), _onLeftArrow(), _onRightArrow() + * _onDownArrow(), _onUpArrow() methods to handle home/end/left/right/up/down keystrokes. + * Next and previous in this context refer to a linear ordering of the descendants used + * by letter key search. + * - Set all descendants' initial tabIndex to "-1"; both initial descendants and any + * descendants added later, by for example addChild() + * - Define childSelector to a function or string that identifies focusable descendant widgets + * Also, child widgets must implement a focus() method. + * + */ + class _KeyNavMixin extends dijit._FocusMixin { + constructor(); + /** + * Selector (passed to on.selector()) used to identify what to treat as a child widget. Used to monitor + * focus events and set this.focusedChild. Must be set by implementing class. If this is a string + * (ex: "> *") then the implementing class must require dojo/query. + * + */ + "childSelector": any; + /** + * The currently focused child widget, or null if there isn't one + * + */ + "focusedChild": Object; + /** + * If multiple characters are typed where each keystroke happens within + * multiCharSearchDuration of the previous keystroke, + * search for nodes matching all the keystrokes. + * + * For example, typing "ab" will search for entries starting with + * "ab" unless the delay between "a" and "b" is greater than multiCharSearchDuration. + * + */ + "multiCharSearchDuration": number; + /** + * Tab index of the container; same as HTML tabIndex attribute. + * Note then when user tabs into the container, focus is immediately + * moved to the first item in the container. + * + */ + "tabIndex": string; + /** + * Default focus() implementation: focus the first child. + * + */ + focus(): void; + /** + * Focus specified child widget. + * + * @param widget Reference to container's child widget + * @param last If true and if widget has multiple focusable nodes, focus thelast one instead of the first one + */ + focusChild(widget: dijit._WidgetBase, last: boolean): void; + /** + * Focus the first focusable child in the container. + * + */ + focusFirstChild(): void; + /** + * Focus the last focusable child in the container. + * + */ + focusLastChild(): void; + /** + * + */ + postCreate(): void; + /** + * When a key is pressed that matches a child item, + * this method is called so that a widget can take appropriate action is necessary. + * + * @param item + * @param evt + * @param searchString + * @param numMatches + */ + onKeyboardSearch(item: dijit._WidgetBase, evt: Event, searchString: String, numMatches: number): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_KeyNavContainer.html + * + * A _Container with keyboard navigation of its children. + * Provides normalized keyboard and focusing code for Container widgets. + * To use this mixin, call connectKeyNavHandlers() in postCreate(). + * Also, child widgets must implement a focus() method. + * + */ + class _KeyNavContainer extends dijit._FocusMixin implements dijit._KeyNavMixin, dijit._Container { + constructor(); + /** + * The currently focused child widget, or null if there isn't one + * + */ + "focusedChild": Object; + /** + * If multiple characters are typed where each keystroke happens within + * multiCharSearchDuration of the previous keystroke, + * search for nodes matching all the keystrokes. + * + * For example, typing "ab" will search for entries starting with + * "ab" unless the delay between "a" and "b" is greater than multiCharSearchDuration. + * + */ + "multiCharSearchDuration": number; + /** + * Tab index of the container; same as HTML tabIndex attribute. + * Note then when user tabs into the container, focus is immediately + * moved to the first item in the container. + * + */ + "tabIndex": string; + /** + * + * @param widget + * @param insertIndex Optional + */ + addChild(widget: dijit._WidgetBase, insertIndex: number): void; + /** + * + */ + buildRendering(): void; + /** + * + * @param node + */ + childSelector(node: HTMLElement): any; + /** + * Deprecated. You can call this in postCreate() to attach the keyboard handlers to the container, + * but the preferred method is to override _onLeftArrow() and _onRightArrow(), or + * _onUpArrow() and _onDownArrow(), to call focusPrev() and focusNext(). + * + * @param prevKeyCodes Key codes for navigating to the previous child. + * @param nextKeyCodes Key codes for navigating to the next child. + */ + connectKeyNavHandlers(prevKeyCodes: dojo.keys, nextKeyCodes: dojo.keys): void; + /** + * Default focus() implementation: focus the first child. + * + */ + focus(): void; + /** + * Focus specified child widget. + * + * @param widget Reference to container's child widget + * @param last If true and if widget has multiple focusable nodes, focus thelast one instead of the first one + */ + focusChild(widget: dijit._WidgetBase, last: boolean): void; + /** + * Focus the first focusable child in the container. + * + */ + focusFirstChild(): void; + /** + * Focus the last focusable child in the container. + * + */ + focusLastChild(): void; + /** + * Focus the next widget + * + */ + focusNext(): void; + /** + * Focus the last focusable node in the previous widget + * (ex: go to the ComboButton icon section rather than button section) + * + */ + focusPrev(): void; + /** + * Gets the index of the child in this container or -1 if not found + * + * @param child + */ + getIndexOfChild(child: dijit._WidgetBase): any; + /** + * Returns true if widget has child widgets, i.e. if this.containerNode contains widgets. + * + */ + hasChildren(): boolean; + /** + * + */ + postCreate(): void; + /** + * Removes the passed widget instance from this widget but does + * not destroy it. You can also pass in an integer indicating + * the index within the container to remove (ie, removeChild(5) removes the sixth widget). + * + * @param widget + */ + removeChild(widget: dijit._WidgetBase): void; + /** + * Removes the passed widget instance from this widget but does + * not destroy it. You can also pass in an integer indicating + * the index within the container to remove (ie, removeChild(5) removes the sixth widget). + * + * @param widget + */ + removeChild(widget: number): void; + /** + * + */ + startup(): void; + /** + * + */ + startupKeyNavChildren(): void; + /** + * When a key is pressed that matches a child item, + * this method is called so that a widget can take appropriate action is necessary. + * + * @param item + * @param evt + * @param searchString + * @param numMatches + */ + onKeyboardSearch(item: dijit._WidgetBase, evt: Event, searchString: String, numMatches: number): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_OnDijitClickMixin.html + * + * Deprecated. New code should access the dijit/a11yclick event directly, ex: + * + * this.own(on(node, a11yclick, function(){ ... })); + * Mixing in this class will make _WidgetBase.connect(node, "ondijitclick", ...) work. + * It also used to be necessary to make templates with ondijitclick work, but now you can just require + * dijit/a11yclick. + * + */ + class _OnDijitClickMixin { + constructor(); + /** + * Custom press, release, and click synthetic events + * which trigger on a left mouse click, touch, or space/enter keyup. + * + */ + "a11yclick": Object; + /** + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: any, method: any): any; + } + module _OnDijitClickMixin { + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_OnDijitClickMixin.a11yclick.html + * + * Custom press, release, and click synthetic events + * which trigger on a left mouse click, touch, or space/enter keyup. + * + */ + interface a11yclick { + /** + * Logical click operation for mouse, touch, or keyboard (space/enter key) + * + * @param node + * @param listener + */ + click(node: any, listener: any): void; + /** + * Mouse cursor or a finger is dragged over the given node. + * + * @param node + * @param listener + */ + move(node: any, listener: any): void; + /** + * Mousedown (left button), touchstart, or keydown (space or enter) corresponding to logical click operation. + * + * @param node + * @param listener + */ + press(node: any, listener: any): void; + /** + * Mouseup (left button), touchend, or keyup (space or enter) corresponding to logical click operation. + * + * @param node + * @param listener + */ + release(node: any, listener: any): void; + } + } + + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_PaletteMixin.html + * + * A keyboard accessible palette, for picking a color/emoticon/etc. + * A mixin for a grid showing various entities, so the user can pick a certain entity. + * + */ + class _PaletteMixin extends dijit._CssStateMixin { + constructor(); + /** + * True if mouse was pressed while over this widget, and hasn't been released yet + * + */ + "active": boolean; + /** + * CSS class applied to each cell in the palette + * + */ + "cellClass": string; + /** + * Subclasses may define a cssStateNodes property that lists sub-nodes within the widget that + * need CSS classes applied on mouse hover/press and focus. + * + * Each entry in this optional hash is a an attach-point name (like "upArrowButton") mapped to a CSS class name + * (like "dijitUpArrowButton"). Example: + * + * { + * "upArrowButton": "dijitUpArrowButton", + * "downArrowButton": "dijitDownArrowButton" + * } + * The above will set the CSS class dijitUpArrowButton to the this.upArrowButton DOMNode when it + * + * is hovered, etc. + * + */ + "cssStateNodes": Object; + /** + * Number of milliseconds before a held key or button becomes typematic + * + */ + "defaultTimeout": number; + /** + * Constructor for Object created for each cell of the palette. + * dyeClass should implement the dijit/_PaletteMixin.__Dye interface. + * + */ + "dyeClass": Object; + /** + * True if cursor is over this widget + * + */ + "hovering": boolean; + /** + * Widget tab index. + * + */ + "tabIndex": string; + /** + * Fraction of time used to change the typematic timer between events + * 1.0 means that each typematic event fires at defaultTimeout intervals + * Less than 1.0 means that each typematic event fires at an increasing faster rate + * + */ + "timeoutChangeRate": number; + /** + * Currently selected color/emoticon/etc. + * + */ + "value": string; + /** + * Focus this widget. Puts focus on the most recently focused cell. + * + */ + focus(): void; + /** + * + */ + postCreate(): void; + /** + * Callback when a cell is selected. + * + * @param value Value corresponding to cell. + */ + onChange(value: String): void; + } + module _PaletteMixin { + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_PaletteMixin.__Dye.html + * + * Interface for the JS Object associated with a palette cell (i.e. DOMNode) + * + * @param alias + * @param row + * @param col + */ + class __Dye { + constructor(alias: String, row: any, col: any); + /** + * Add cell DOMNode inner structure + * + * @param cell The surrounding cell + * @param blankGif URL for blank cell image + */ + fillCell(cell: HTMLElement, blankGif: String): void; + /** + * Return "value" of cell; meaning of "value" varies by subclass. + * For example color hex value, emoticon ascii value etc, entity hex value. + * + */ + getValue(): void; + } + } + + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_TemplatedMixin.html + * + * Mixin for widgets that are instantiated from a template + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified, replace srcNodeRef with my generated DOM tree. + */ + class _TemplatedMixin extends dijit._AttachMixin { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + /** + * + */ + "searchContainerNode": boolean; + /** + * Path to template (HTML file) for this widget relative to dojo.baseUrl. + * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead + * + */ + "templatePath": string; + /** + * A string that represents the widget template. + * Use in conjunction with dojo.cache() to load from a file. + * + */ + "templateString": string; + /** + * Construct the UI for this widget from a template, setting this.domNode. + * + */ + buildRendering(): void; + /** + * + */ + destroyRendering(): void; + /** + * Static method to get a template based on the templatePath or + * templateString key + * + * @param templateString The template + * @param alwaysUseString Don't cache the DOM tree for this template, even if it doesn't have any variables + * @param doc OptionalThe target document. Defaults to document global if unspecified. + */ + getCachedTemplate(templateString: String, alwaysUseString: boolean, doc: HTMLDocument): any; + } + module _TemplatedMixin { + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_TemplatedMixin._templateCache.html + * + * + */ + interface _templateCache { + } + } + + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_Templated.html + * + * Deprecated mixin for widgets that are instantiated from a template. + * Widgets should use _TemplatedMixin plus if necessary _WidgetsInTemplateMixin instead. + * + */ + class _Templated extends dijit._TemplatedMixin implements dijit._WidgetsInTemplateMixin { + constructor(); + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + /** + * Used to provide a context require to the dojo/parser in order to be + * able to use relative MIDs (e.g. ./Widget) in the widget's template. + * + */ + "contextRequire": Function; + /** + * + */ + "searchContainerNode": boolean; + /** + * Path to template (HTML file) for this widget relative to dojo.baseUrl. + * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead + * + */ + "templatePath": string; + /** + * A string that represents the widget template. + * Use in conjunction with dojo.cache() to load from a file. + * + */ + "templateString": string; + /** + * Should we parse the template to find widgets that might be + * declared in markup inside it? False by default. + * + */ + "widgetsInTemplate": boolean; + /** + * Construct the UI for this widget from a template, setting this.domNode. + * + */ + buildRendering(): void; + /** + * + */ + destroyRendering(): void; + /** + * + */ + startup(): void; + /** + * Static method to get a template based on the templatePath or + * templateString key + */ + getCachedTemplate(): any; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_MenuBase.html + * + * Abstract base class for Menu and MenuBar. + * Subclass should implement _onUpArrow(), _onDownArrow(), _onLeftArrow(), and _onRightArrow(). + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree + */ + class _MenuBase extends dijit._Widget implements dijit._TemplatedMixin, dijit._KeyNavContainer, dijit._CssStateMixin { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * This Menu has been clicked (mouse or via space/arrow key) or opened as a submenu, + * so mere mouseover will open submenus. Focusing a menu via TAB does NOT automatically make it active + * since TAB is a navigation operation and not a selection one. + * For Windows apps, pressing the ALT key focuses the menubar menus (similar to TAB navigation) but the + * menu is not active (ie no dropdown) until an item is clicked. + * + */ + "activated": boolean; + set(property:"activated", value: boolean): void; + get(property:"activated"): boolean; + watch(property:"activated", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * True if mouse was pressed while over this widget, and hasn't been released yet + * + */ + "active": boolean; + set(property:"active", value: boolean): void; + get(property:"active"): boolean; + watch(property:"active", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + set(property:"attachScope", value: Object): void; + get(property:"attachScope"): Object; + watch(property:"attachScope", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * A toggle to control whether or not a Menu gets focused when opened as a drop down from a MenuBar + * or DropDownButton/ComboButton. Note though that it always get focused when opened via the keyboard. + * + */ + "autoFocus": boolean; + set(property:"autoFocus", value: boolean): void; + get(property:"autoFocus"): boolean; + watch(property:"autoFocus", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Root CSS class of the widget (ex: dijitTextBox), used to construct CSS classes to indicate + * widget state. + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Subclasses may define a cssStateNodes property that lists sub-nodes within the widget that + * need CSS classes applied on mouse hover/press and focus. + * + * Each entry in this optional hash is a an attach-point name (like "upArrowButton") mapped to a CSS class name + * (like "dijitUpArrowButton"). Example: + * + * { + * "upArrowButton": "dijitUpArrowButton", + * "downArrowButton": "dijitDownArrowButton" + * } + * The above will set the CSS class dijitUpArrowButton to the this.upArrowButton DOMNode when it + * + * is hovered, etc. + * + */ + "cssStateNodes": Object; + set(property:"cssStateNodes", value: Object): void; + get(property:"cssStateNodes"): Object; + watch(property:"cssStateNodes", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * This widget or a widget it contains has focus, or is "active" because + * it was recently clicked. + * + */ + "focused": boolean; + set(property:"focused", value: boolean): void; + get(property:"focused"): boolean; + watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * The currently focused child widget, or null if there isn't one + * + */ + "focusedChild": Object; + set(property:"focusedChild", value: Object): void; + get(property:"focusedChild"): Object; + watch(property:"focusedChild", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * True if cursor is over this widget + * + */ + "hovering": boolean; + set(property:"hovering", value: boolean): void; + get(property:"hovering"): boolean; + watch(property:"hovering", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * If multiple characters are typed where each keystroke happens within + * multiCharSearchDuration of the previous keystroke, + * search for nodes matching all the keystrokes. + * + * For example, typing "ab" will search for entries starting with + * "ab" unless the delay between "a" and "b" is greater than multiCharSearchDuration. + * + */ + "multiCharSearchDuration": number; + set(property:"multiCharSearchDuration", value: number): void; + get(property:"multiCharSearchDuration"): number; + watch(property:"multiCharSearchDuration", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * pointer to menu that displayed me + * + */ + "parentMenu": Object; + set(property:"parentMenu", value: Object): void; + get(property:"parentMenu"): Object; + watch(property:"parentMenu", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * For a passive (unclicked) Menu, number of milliseconds before hovering (without clicking) will cause + * the popup to open. Default is Infinity, meaning you need to click the menu to open it. + * + */ + "passivePopupDelay": number; + set(property:"passivePopupDelay", value: number): void; + get(property:"passivePopupDelay"): number; + watch(property:"passivePopupDelay", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} + /** + * After a menu has been activated (by clicking on it etc.), number of milliseconds before hovering + * (without clicking) another MenuItem causes that MenuItem's popup to automatically open. + * + */ + "popupDelay": number; + set(property:"popupDelay", value: number): void; + get(property:"popupDelay"): number; + watch(property:"popupDelay", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} + /** + * + */ + "searchContainerNode": boolean; + set(property:"searchContainerNode", value: boolean): void; + get(property:"searchContainerNode"): boolean; + watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Currently selected (a.k.a. highlighted) MenuItem, or null if no MenuItem is selected. + * If a submenu is open, will be set to MenuItem that displayed the submenu. OTOH, if + * this Menu is in passive mode (i.e. hasn't been clicked yet), will be null, because + * "selected" is not merely "hovered". + * + */ + "selected": Object; + set(property:"selected", value: Object): void; + get(property:"selected"): Object; + watch(property:"selected", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": string; + set(property:"style", value: string): void; + get(property:"style"): string; + watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Tab index of the container; same as HTML tabIndex attribute. + * Note then when user tabs into the container, focus is immediately + * moved to the first item in the container. + * + */ + "tabIndex": string; + set(property:"tabIndex", value: string): void; + get(property:"tabIndex"): string; + watch(property:"tabIndex", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Path to template (HTML file) for this widget relative to dojo.baseUrl. + * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead + * + */ + "templatePath": string; + set(property:"templatePath", value: string): void; + get(property:"templatePath"): string; + watch(property:"templatePath", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * A string that represents the widget template. + * Use in conjunction with dojo.cache() to load from a file. + * + */ + "templateString": string; + set(property:"templateString", value: string): void; + get(property:"templateString"): string; + watch(property:"templateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + * @param widget + * @param insertIndex Optional + */ + addChild(widget: dijit._WidgetBase, insertIndex: number): void; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: String, value: Object): any; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: Object, value: Object): any; + /** + * Construct the UI for this widget, setting this.domNode. + * Most widgets will mixin dijit._TemplatedMixin, which implements this method. + * + */ + buildRendering(): void; + /** + * Selector (passed to on.selector()) used to identify MenuItem child widgets, but exclude inert children + * like MenuSeparator. If subclass overrides to a string (ex: "> *"), the subclass must require dojo/query. + * + * @param node + */ + childSelector(node: HTMLElement): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * Deprecated. You can call this in postCreate() to attach the keyboard handlers to the container, + * but the preferred method is to override _onLeftArrow() and _onRightArrow(), or + * _onUpArrow() and _onDownArrow(), to call focusPrev() and focusNext(). + * + * @param prevKeyCodes Key codes for navigating to the previous child. + * @param nextKeyCodes Key codes for navigating to the next child. + */ + connectKeyNavHandlers(prevKeyCodes: dojo.keys, nextKeyCodes: dojo.keys): void; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * Destroy this widget, but not its descendants. Descendants means widgets inside of + * this.containerNode. Will also destroy any resources (including widgets) registered via this.own(). + * + * This method will also destroy internal widgets such as those created from a template, + * assuming those widgets exist inside of this.domNode but outside of this.containerNode. + * + * For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not + * depend on the current ability to destroy a widget without destroying its descendants. Generally + * they should use destroyRecursive() for widgets with children. + * + * @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets + */ + destroy(preserveDom?: boolean): void; + /** + * Recursively destroy the children of this widget and their + * descendants. + * + * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy this widget and its descendants + * This is the generic "destructor" function that all widget users + * should call to cleanly discard with a widget. Once a widget is + * destroyed, it is removed from the manager object. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Default focus() implementation: focus the first child. + * + */ + focus(): void; + /** + * Focus specified child widget. + * + * @param widget Reference to container's child widget + * @param last If true and if widget has multiple focusable nodes, focus thelast one instead of the first one + */ + focusChild(widget: dijit._WidgetBase, last: boolean): void; + /** + * Focus the first focusable child in the container. + * + */ + focusFirstChild(): void; + /** + * Focus the last focusable child in the container. + * + */ + focusLastChild(): void; + /** + * Focus the next widget + * + */ + focusNext(): void; + /** + * Focus the last focusable node in the previous widget + * (ex: go to the ComboButton icon section rather than button section) + * + */ + focusPrev(): void; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode. + * This method should generally be avoided as it returns widgets declared in templates, which are + * supposed to be internal/hidden, but it's left here for back-compat reasons. + * + */ + getDescendants(): any[]; + /** + * Gets the index of the child in this container or -1 if not found + * + * @param child + */ + getIndexOfChild(child: dijit._WidgetBase): any; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Returns true if widget has child widgets, i.e. if this.containerNode contains widgets. + * + */ + hasChildren(): boolean; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * + * @param type protected + * @param func + */ + on(type: String, func: Function): any; + /** + * + * @param type protected + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * + */ + postCreate(): void; + /** + * Called after the parameters to the widget have been read-in, + * but before the widget template is instantiated. Especially + * useful to set properties that are referenced in the widget + * template. + * + */ + postMixInProperties(): void; + /** + * Removes the passed widget instance from this widget but does + * not destroy it. You can also pass in an integer indicating + * the index within the container to remove (ie, removeChild(5) removes the sixth widget). + * + * @param widget + */ + removeChild(widget: dijit._WidgetBase): void; + /** + * Removes the passed widget instance from this widget but does + * not destroy it. You can also pass in an integer indicating + * the index within the container to remove (ie, removeChild(5) removes the sixth widget). + * + * @param widget + */ + removeChild(widget: number): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Deprecated. Use set() instead. + * + * @param attr + * @param value + */ + setAttribute(attr: String, value: any): void; + /** + * Processing after the DOM fragment is added to the document + * Called after a widget and its children have been created and added to the page, + * and all related widgets have finished their create() cycle, up through postCreate(). + * + * Note that startup() may be called while the widget is still hidden, for example if the widget is + * inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer. + * For widgets that need to do layout, it's best to put that layout code inside resize(), and then + * extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible. + * + */ + startup(): void; + /** + * + */ + startupKeyNavChildren(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Static method to get a template based on the templatePath or + * templateString key + */ + getCachedTemplate(): any; + /** + * Called when the widget stops being "active" because + * focus moved to something outside of it, or the user + * clicked somewhere outside of it, or the widget was + * hidden. + * + */ + onBlur(): void; + /** + * Attach point for notification about when the user cancels the current menu + * This is an internal mechanism used for Menus to signal to their parent to + * close them. In general developers should not attach to or override this method. + * + * @param closeAll + */ + onCancel(closeAll: boolean): void; + /** + * Connect to this function to receive notifications of mouse click events. + * + * @param event mouse Event + */ + onClick(event: any): void; + /** + * Connect to this function to receive notifications of mouse double click events. + * + * @param event mouse Event + */ + onDblClick(event: any): void; + /** + * Attach point for notification about when a menu item has been executed. + * This is an internal mechanism used for Menus to signal to their parent to + * close them, because they are about to execute the onClick handler. In + * general developers should not attach to or override this method. + * + */ + onExecute(): void; + /** + * Called when the widget becomes "active" because + * it or a widget inside of it either has focus, or has recently + * been clicked. + * + */ + onFocus(): void; + /** + * Called when another widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate hide of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onHide(): void; + /** + * Called when cursor is over a MenuItem. + * + * @param item + */ + onItemHover(item: dijit.MenuItem): void; + /** + * Callback fires when mouse exits a MenuItem + * + * @param item + */ + onItemUnhover(item: dijit.MenuItem): void; + /** + * Attach point for notification about when a menu item has been searched for + * via the keyboard search mechanism. + * + * @param item + * @param evt + * @param searchString + * @param numMatches + */ + onKeyboardSearch(item: dijit.MenuItem, evt: Event, searchString: String, numMatches: number): void; + /** + * Connect to this function to receive notifications of keys being pressed down. + * + * @param event key Event + */ + onKeyDown(event: any): void; + /** + * Connect to this function to receive notifications of printable keys being typed. + * + * @param event key Event + */ + onKeyPress(event: any): void; + /** + * Connect to this function to receive notifications of keys being released. + * + * @param event key Event + */ + onKeyUp(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is pressed down. + * + * @param event mouse Event + */ + onMouseDown(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto this widget. + * + * @param event mouse Event + */ + onMouseEnter(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of this widget. + * + * @param event mouse Event + */ + onMouseLeave(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves over nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseMove(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOut(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOver(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is released. + * + * @param event mouse Event + */ + onMouseUp(event: any): void; + /** + * Called when this widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate display of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onShow(): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_WidgetsInTemplateMixin.html + * + * Mixin to supplement _TemplatedMixin when template contains widgets + * + */ + class _WidgetsInTemplateMixin { + constructor(); + /** + * Used to provide a context require to the dojo/parser in order to be + * able to use relative MIDs (e.g. ./Widget) in the widget's template. + * + */ + "contextRequire": Function; + /** + * Should we parse the template to find widgets that might be + * declared in markup inside it? (Remove for 2.0 and assume true) + * + */ + "widgetsInTemplate": boolean; + /** + * + */ + startup(): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_WidgetBase.html + * + * Future base class for all Dijit widgets. + * Future base class for all Dijit widgets. + * _Widget extends this class adding support for various features needed by desktop. + * + * Provides stubs for widget lifecycle methods for subclasses to extend, like postMixInProperties(), buildRendering(), + * postCreate(), startup(), and destroy(), and also public API methods like set(), get(), and watch(). + * + * Widgets can provide custom setters/getters for widget attributes, which are called automatically by set(name, value). + * For an attribute XXX, define methods _setXXXAttr() and/or _getXXXAttr(). + * + * _setXXXAttr can also be a string/hash/array mapping from a widget attribute XXX to the widget's DOMNodes: + * + * DOM node attribute + * _setFocusAttr: {node: "focusNode", type: "attribute"} + * _setFocusAttr: "focusNode" (shorthand) + * _setFocusAttr: "" (shorthand, maps to this.domNode) + * Maps this.focus to this.focusNode.focus, or (last example) this.domNode.focus + * + * DOM node innerHTML + * _setTitleAttr: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * _setTitleAttr: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * _setMyClassAttr: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value of _setXXXAttr is an array, then each element in the array matches one of the + * formats of the above list. + * + * If the custom setter is null, no action is performed other than saving the new value + * in the widget (in this). + * + * If no custom setter is defined for an attribute, then it will be copied + * to this.focusNode (if the widget defines a focusNode), or this.domNode otherwise. + * That's only done though for attributes that match DOMNode attributes (title, + * alt, aria-labelledby, etc.) + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree + */ + class _WidgetBase extends dojo.Stateful implements dijit.Destroyable { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Root CSS class of the widget (ex: dijitTextBox), used to construct CSS classes to indicate + * widget state. + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * This widget or a widget it contains has focus, or is "active" because + * it was recently clicked. + * + */ + "focused": boolean; + set(property:"focused", value: boolean): void; + get(property:"focused"): boolean; + watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": Object; + set(property:"style", value: Object): void; + get(property:"style"): Object; + watch(property:"style", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Construct the UI for this widget, setting this.domNode. + * Most widgets will mixin dijit._TemplatedMixin, which implements this method. + * + */ + buildRendering(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * Destroy this widget, but not its descendants. Descendants means widgets inside of + * this.containerNode. Will also destroy any resources (including widgets) registered via this.own(). + * + * This method will also destroy internal widgets such as those created from a template, + * assuming those widgets exist inside of this.domNode but outside of this.containerNode. + * + * For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not + * depend on the current ability to destroy a widget without destroying its descendants. Generally + * they should use destroyRecursive() for widgets with children. + * + * @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets + */ + destroy(preserveDom?: boolean): void; + /** + * Recursively destroy the children of this widget and their + * descendants. + * + * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy this widget and its descendants + * This is the generic "destructor" function that all widget users + * should call to cleanly discard with a widget. Once a widget is + * destroyed, it is removed from the manager object. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * + */ + isValid: any; + /** + * Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }). + * Call specified function when event type occurs, ex: myWidget.on("click", function(){ ... }). + * Note that the function is not run in any particular scope, so if (for example) you want it to run in the + * widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)). + * + * @param type Name of event (ex: "click") or extension event like touch.press. + * @param func + */ + on(type: String, func: Function): any; + /** + * Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }). + * Call specified function when event type occurs, ex: myWidget.on("click", function(){ ... }). + * Note that the function is not run in any particular scope, so if (for example) you want it to run in the + * widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)). + * + * @param type Name of event (ex: "click") or extension event like touch.press. + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * Processing after the DOM fragment is created + * Called after the DOM fragment has been created, but not necessarily + * added to the document. Do not include any operations which rely on + * node dimensions or placement. + * + */ + postCreate(): void; + /** + * Called after the parameters to the widget have been read-in, + * but before the widget template is instantiated. Especially + * useful to set properties that are referenced in the widget + * template. + * + */ + postMixInProperties(): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Processing after the DOM fragment is added to the document + * Called after a widget and its children have been created and added to the page, + * and all related widgets have finished their create() cycle, up through postCreate(). + * + * Note that startup() may be called while the widget is still hidden, for example if the widget is + * inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer. + * For widgets that need to do layout, it's best to put that layout code inside resize(), and then + * extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible. + * + */ + startup(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Called when the widget stops being "active" because + * focus moved to something outside of it, or the user + * clicked somewhere outside of it, or the widget was + * hidden. + * + */ + onBlur(): void; + /** + * Called when the widget becomes "active" because + * it or a widget inside of it either has focus, or has recently + * been clicked. + * + */ + onFocus(): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_Widget.html + * + * Old base class for widgets. New widgets should extend dijit/_WidgetBase instead + * Old Base class for Dijit widgets. + * + * Extends _WidgetBase, adding support for: + * + * declaratively/programatically specifying widget initialization parameters like + * onMouseMove="foo" that call foo when this.domNode gets a mousemove event + * ondijitclick: + * Support new data-dojo-attach-event="ondijitclick: ..." that is triggered by a mouse click or a SPACE/ENTER keypress + * focus related functions: + * In particular, the onFocus()/onBlur() callbacks. Driven internally by + * dijit/_base/focus.js. + * deprecated methods + * onShow(), onHide(), onClose() + * Also, by loading code in dijit/_base, turns on: + * + * browser sniffing (putting browser class like dj_ie on node) + * high contrast mode sniffing (add dijit_a11y class to if machine is in high contrast mode) + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree + */ + class _Widget extends dijit._WidgetBase implements dijit._OnDijitClickMixin, dijit._FocusMixin { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * Custom press, release, and click synthetic events + * which trigger on a left mouse click, touch, or space/enter keyup. + * + */ + "a11yclick": Object; + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Root CSS class of the widget (ex: dijitTextBox), used to construct CSS classes to indicate + * widget state. + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Defines a type of widget. + * + */ + "dndType": string; + set(property:"dndType", value: string): void; + get(property:"dndType"): string; + watch(property:"dndType", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * This widget or a widget it contains has focus, or is "active" because + * it was recently clicked. + * + */ + "focused": boolean; + set(property:"focused", value: boolean): void; + get(property:"focused"): boolean; + watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "observer": string; + set(property:"observer", value: string): void; + get(property:"observer"): string; + watch(property:"observer", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * A parameter needed by RadioGroupSlide only. An optional paramter to force + * the ContentPane to slide in from a set direction. Defaults + * to "random", or specify one of "top", "left", "right", "bottom" + * to slideFrom top, left, right, or bottom. + * + */ + "slideFrom": string; + set(property:"slideFrom", value: string): void; + get(property:"slideFrom"): string; + watch(property:"slideFrom", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": Object; + set(property:"style", value: Object): void; + get(property:"style"): Object; + watch(property:"style", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: String, value: Object): any; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: Object, value: Object): any; + /** + * Construct the UI for this widget, setting this.domNode. + * Most widgets will mixin dijit._TemplatedMixin, which implements this method. + * + */ + buildRendering(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * Destroy this widget, but not its descendants. Descendants means widgets inside of + * this.containerNode. Will also destroy any resources (including widgets) registered via this.own(). + * + * This method will also destroy internal widgets such as those created from a template, + * assuming those widgets exist inside of this.domNode but outside of this.containerNode. + * + * For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not + * depend on the current ability to destroy a widget without destroying its descendants. Generally + * they should use destroyRecursive() for widgets with children. + * + * @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets + */ + destroy(preserveDom?: boolean): void; + /** + * Recursively destroy the children of this widget and their + * descendants. + * + * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy this widget and its descendants + * This is the generic "destructor" function that all widget users + * should call to cleanly discard with a widget. Once a widget is + * destroyed, it is removed from the manager object. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode. + * This method should generally be avoided as it returns widgets declared in templates, which are + * supposed to be internal/hidden, but it's left here for back-compat reasons. + * + */ + getDescendants(): any[]; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * + * @param type protected + * @param func + */ + on(type: String, func: Function): any; + /** + * + * @param type protected + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * + */ + postCreate(): void; + /** + * Called after the parameters to the widget have been read-in, + * but before the widget template is instantiated. Especially + * useful to set properties that are referenced in the widget + * template. + * + */ + postMixInProperties(): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Deprecated. Use set() instead. + * + * @param attr + * @param value + */ + setAttribute(attr: String, value: any): void; + /** + * Processing after the DOM fragment is added to the document + * Called after a widget and its children have been created and added to the page, + * and all related widgets have finished their create() cycle, up through postCreate(). + * + * Note that startup() may be called while the widget is still hidden, for example if the widget is + * inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer. + * For widgets that need to do layout, it's best to put that layout code inside resize(), and then + * extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible. + * + */ + startup(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Called when the widget stops being "active" because + * focus moved to something outside of it, or the user + * clicked somewhere outside of it, or the widget was + * hidden. + * + */ + onBlur(): void; + /** + * Connect to this function to receive notifications of mouse click events. + * + * @param event mouse Event + */ + onClick(event: any): void; + /** + * Called when this widget is being displayed as a popup (ex: a Calendar popped + * up from a DateTextBox), and it is hidden. + * This is called from the dijit.popup code, and should not be called directly. + * + * Also used as a parameter for children of dijit/layout/StackContainer or subclasses. + * Callback if a user tries to close the child. Child will be closed if this function returns true. + * + */ + onClose(): boolean; + /** + * Connect to this function to receive notifications of mouse double click events. + * + * @param event mouse Event + */ + onDblClick(event: any): void; + /** + * Called when the widget becomes "active" because + * it or a widget inside of it either has focus, or has recently + * been clicked. + * + */ + onFocus(): void; + /** + * Called when another widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate hide of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onHide(): void; + /** + * Connect to this function to receive notifications of keys being pressed down. + * + * @param event key Event + */ + onKeyDown(event: any): void; + /** + * Connect to this function to receive notifications of printable keys being typed. + * + * @param event key Event + */ + onKeyPress(event: any): void; + /** + * Connect to this function to receive notifications of keys being released. + * + * @param event key Event + */ + onKeyUp(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is pressed down. + * + * @param event mouse Event + */ + onMouseDown(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto this widget. + * + * @param event mouse Event + */ + onMouseEnter(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of this widget. + * + * @param event mouse Event + */ + onMouseLeave(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves over nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseMove(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOut(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOver(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is released. + * + * @param event mouse Event + */ + onMouseUp(event: any): void; + /** + * Called when this widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate display of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onShow(): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_TimePicker.html + * + * A time picker dropdown, used by dijit/form/TimeTextBox. + * This widget is not available as a standalone widget due to lack of accessibility support. + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified, replace srcNodeRef with my generated DOM tree + */ + class _TimePicker extends dijit._WidgetBase implements dijit.form._ListMouseMixin { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * The root className to use for the various states of this widget + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * ISO-8601 string representing the amount by which + * every clickable element in the time picker increases. + * Set in local time, without a time zone. + * Example: T00:15:00 creates 15 minute increments + * Must divide dijit/_TimePicker.visibleIncrement evenly + * + */ + "clickableIncrement": string; + set(property:"clickableIncrement", value: string): void; + get(property:"clickableIncrement"): string; + watch(property:"clickableIncrement", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Specifies valid range of times (start time, end time) + * + */ + "constraints": Object; + set(property:"constraints", value: Object): void; + get(property:"constraints"): Object; + watch(property:"constraints", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * The string to filter by + * + */ + "filterString": string; + set(property:"filterString", value: string): void; + get(property:"filterString"): string; + watch(property:"filterString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This widget or a widget it contains has focus, or is "active" because + * it was recently clicked. + * + */ + "focused": boolean; + set(property:"focused", value: boolean): void; + get(property:"focused"): boolean; + watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * currently selected node + * + */ + "selected": HTMLElement; + set(property:"selected", value: HTMLElement): void; + get(property:"selected"): HTMLElement; + watch(property:"selected", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": string; + set(property:"style", value: string): void; + get(property:"style"): string; + watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Date to display. + * Defaults to current time and date. + * Can be a Date object or an ISO-8601 string. + * If you specify the GMT time zone (-01:00), + * the time will be converted to the local time in the local time zone. + * Otherwise, the time is considered to be in the local time zone. + * If you specify the date and isDate is true, the date is used. + * Example: if your local time zone is GMT -05:00, + * T10:00:00 becomes T10:00:00-05:00 (considered to be local time), + * T10:00:00-01:00 becomes T06:00:00-05:00 (4 hour difference), + * T10:00:00Z becomes T05:00:00-05:00 (5 hour difference between Zulu and local time) + * yyyy-mm-ddThh:mm:ss is the format to set the date and time + * Example: 2007-06-01T09:00:00 + * + */ + "value": string; + set(property:"value", value: string): void; + get(property:"value"): string; + watch(property:"value", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * ISO-8601 string representing the amount by which + * every element with a visible time in the time picker increases. + * Set in local time, without a time zone. + * Example: T01:00:00 creates text in every 1 hour increment + * + */ + "visibleIncrement": string; + set(property:"visibleIncrement", value: string): void; + get(property:"visibleIncrement"): string; + watch(property:"visibleIncrement", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + buildRendering(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * Destroy this widget, but not its descendants. Descendants means widgets inside of + * this.containerNode. Will also destroy any resources (including widgets) registered via this.own(). + * + * This method will also destroy internal widgets such as those created from a template, + * assuming those widgets exist inside of this.domNode but outside of this.containerNode. + * + * For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not + * depend on the current ability to destroy a widget without destroying its descendants. Generally + * they should use destroyRecursive() for widgets with children. + * + * @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets + */ + destroy(preserveDom?: boolean): void; + /** + * Recursively destroy the children of this widget and their + * descendants. + * + * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy this widget and its descendants + * This is the generic "destructor" function that all widget users + * should call to cleanly discard with a widget. Once a widget is + * destroyed, it is removed from the manager object. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Called from dijit/form/_DateTimeTextBox to pass a keypress event + * from the dijit/form/TimeTextBox to be handled in this widget + * + * @param e + */ + handleKey(e: Event): any; + /** + * May be overridden to disable certain dates in the TimePicker e.g. isDisabledDate=locale.isWeekend + * + * @param dateObject + * @param locale Optional + */ + isDisabledDate(dateObject: Date, locale: String): boolean; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }). + * Call specified function when event type occurs, ex: myWidget.on("click", function(){ ... }). + * Note that the function is not run in any particular scope, so if (for example) you want it to run in the + * widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)). + * + * @param type Name of event (ex: "click") or extension event like touch.press. + * @param func + */ + on(type: String, func: Function): any; + /** + * Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }). + * Call specified function when event type occurs, ex: myWidget.on("click", function(){ ... }). + * Note that the function is not run in any particular scope, so if (for example) you want it to run in the + * widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)). + * + * @param type Name of event (ex: "click") or extension event like touch.press. + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * Processing after the DOM fragment is created + * Called after the DOM fragment has been created, but not necessarily + * added to the document. Do not include any operations which rely on + * node dimensions or placement. + * + */ + postCreate(): void; + /** + * + */ + postMixInProperties(): void; + /** + * Select the first displayed item in the list. + * + */ + selectFirstNode(): void; + /** + * Select the last displayed item in the list + * + */ + selectLastNode(): void; + /** + * Select the item just below the current selection. + * If nothing selected, select first node. + * + */ + selectNextNode(): void; + /** + * Select the item just above the current selection. + * If nothing selected, select last node (if + * you select Previous and try to keep scrolling up the list). + * + */ + selectPreviousNode(): void; + /** + * Format a Date object as a string according a subset of the ISO-8601 standard + * When options.selector is omitted, output follows RFC3339 + * The local time zone is included as an offset from GMT, except when selector=='time' (time without a date) + * Does not check bounds. Only years between 100 and 9999 are supported. + * + * @param dateObject A Date object + * @param options OptionalAn object with the following properties:selector (String): "date" or "time" for partial formatting of the Date object.Both date and time will be formatted by default.zulu (Boolean): if true, UTC/GMT is used for a timezonemilliseconds (Boolean): if true, output milliseconds + */ + serialize(dateObject: Date, options: Object): any; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Deprecated. Used set('value') instead. + * + * @param value + */ + setValue(value: Date): void; + /** + * Processing after the DOM fragment is added to the document + * Called after a widget and its children have been created and added to the page, + * and all related widgets have finished their create() cycle, up through postCreate(). + * + * Note that startup() may be called while the widget is still hidden, for example if the widget is + * inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer. + * For widgets that need to do layout, it's best to put that layout code inside resize(), and then + * extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible. + * + */ + startup(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Called when the widget stops being "active" because + * focus moved to something outside of it, or the user + * clicked somewhere outside of it, or the widget was + * hidden. + * + */ + onBlur(): void; + /** + * Notification that a time was selected. It may be the same as the previous value. + * + * @param time + */ + onChange(time: Date): void; + /** + * + * @param node + */ + onClick(node: HTMLElement): void; + /** + * + * @param node + */ + onDeselect(node: HTMLElement): void; + /** + * Called when the widget becomes "active" because + * it or a widget inside of it either has focus, or has recently + * been clicked. + * + */ + onFocus(): void; + /** + * + * @param node + */ + onHover(node: HTMLElement): void; + /** + * + */ + onOpen(): void; + /** + * + * @param node + */ + onSelect(node: HTMLElement): void; + /** + * + * @param node + */ + onUnhover(node: HTMLElement): void; + } + module _TimePicker { + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/_TimePicker.__Constraints.html + * + * + */ + class __Constraints { + constructor(); + /** + * override strings for am in times + * + */ + "am": string; + /** + * See dijit/_TimePicker.clickableIncrement + * + */ + "clickableIncrement": string; + /** + * override pattern with this string + * + */ + "datePattern": string; + /** + * choice of long, short, medium or full (plus any custom additions). Defaults to 'short' + * + */ + "formatLength": string; + /** + * (format only) use 4 digit years whenever 2 digit years are called for + * + */ + "fullYear": boolean; + /** + * override the locale used to determine formatting rules + * + */ + "locale": string; + /** + * override strings for pm in times + * + */ + "pm": string; + /** + * choice of 'time','date' (default: date and time) + * + */ + "selector": string; + /** + * (parse only) strict parsing, off by default + * + */ + "strict": boolean; + /** + * override pattern with this string + * + */ + "timePattern": string; + } + } + + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/Destroyable.html + * + * Mixin to track handles and release them when instance is destroyed. + * Call this.own(...) on list of handles (returned from dojo/aspect, dojo/on, + * dojo/Stateful::watch, or any class (including widgets) with a destroyRecursive() or destroy() method. + * Then call destroy() later to destroy this instance and release the resources. + * + */ + class Destroyable { + constructor(); + /** + * Destroy this class, releasing any resources registered via own(). + * + * @param preserveDom + */ + destroy(preserveDom?: boolean): void; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/CalendarLite.html + * + * Lightweight version of Calendar widget aimed towards mobile use + * A simple GUI for choosing a date in the context of a monthly calendar. + * This widget can't be used in a form because it doesn't serialize the date to an + * field. For a form element, use dijit/form/DateTextBox instead. + * + * Note that the parser takes all dates attributes passed in the + * RFC 3339 format, e.g. 2005-06-30T08:05:00-07:00 + * so that they are serializable and locale-independent. + * + * Also note that this widget isn't keyboard accessible; use dijit.Calendar for that + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified, replace srcNodeRef with my generated DOM tree + */ + class CalendarLite extends dijit._WidgetBase implements dijit._TemplatedMixin { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + set(property:"attachScope", value: Object): void; + get(property:"attachScope"): Object; + watch(property:"attachScope", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Date object containing the currently focused date, or the date which would be focused + * if the calendar itself was focused. Also indicates which year and month to display, + * i.e. the current "page" the calendar is on. + * + */ + "currentFocus": Date; + set(property:"currentFocus", value: Date): void; + get(property:"currentFocus"): Date; + watch(property:"currentFocus", callback:{(property?:string, oldValue?:Date, newValue?: Date):void}) :{unwatch():void} + /** + * JavaScript namespace to find calendar routines. If unspecified, uses Gregorian calendar routines + * at dojo/date and dojo/date/locale. + * + */ + "datePackage": string; + set(property:"datePackage", value: string): void; + get(property:"datePackage"): string; + watch(property:"datePackage", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "dateTemplateString": string; + set(property:"dateTemplateString", value: string): void; + get(property:"dateTemplateString"): string; + watch(property:"dateTemplateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * How to represent the days of the week in the calendar header. See locale + * + */ + "dayWidth": string; + set(property:"dayWidth", value: string): void; + get(property:"dayWidth"): string; + watch(property:"dayWidth", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * + */ + "dowTemplateString": string; + set(property:"dowTemplateString", value: string): void; + get(property:"dowTemplateString"): string; + watch(property:"dowTemplateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * + */ + "searchContainerNode": boolean; + set(property:"searchContainerNode", value: boolean): void; + get(property:"searchContainerNode"): boolean; + watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": string; + set(property:"style", value: string): void; + get(property:"style"): string; + watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Order fields are traversed when user hits the tab key + * + */ + "tabIndex": string; + set(property:"tabIndex", value: string): void; + get(property:"tabIndex"): string; + watch(property:"tabIndex", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Path to template (HTML file) for this widget relative to dojo.baseUrl. + * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead + * + */ + "templatePath": string; + set(property:"templatePath", value: string): void; + get(property:"templatePath"): string; + watch(property:"templatePath", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "templateString": string; + set(property:"templateString", value: string): void; + get(property:"templateString"): string; + watch(property:"templateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * The currently selected Date, initially set to invalid date to indicate no selection. + * + */ + "value": Date; + set(property:"value", value: Date): void; + get(property:"value"): Date; + watch(property:"value", callback:{(property?:string, oldValue?:Date, newValue?: Date):void}) :{unwatch():void} + /** + * + */ + "weekTemplateString": string; + set(property:"weekTemplateString", value: string): void; + get(property:"weekTemplateString"): string; + watch(property:"weekTemplateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + buildRendering(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * Destroy this widget, but not its descendants. Descendants means widgets inside of + * this.containerNode. Will also destroy any resources (including widgets) registered via this.own(). + * + * This method will also destroy internal widgets such as those created from a template, + * assuming those widgets exist inside of this.domNode but outside of this.containerNode. + * + * For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not + * depend on the current ability to destroy a widget without destroying its descendants. Generally + * they should use destroyRecursive() for widgets with children. + * + * @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets + */ + destroy(preserveDom?: boolean): void; + /** + * Recursively destroy the children of this widget and their + * descendants. + * + * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy this widget and its descendants + * This is the generic "destructor" function that all widget users + * should call to cleanly discard with a widget. Once a widget is + * destroyed, it is removed from the manager object. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Focus the calendar by focusing one of the calendar cells + * + */ + focus(): void; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * May be overridden to return CSS classes to associate with the date entry for the given dateObject, + * for example to indicate a holiday in specified locale. + * + * @param dateObject + * @param locale Optional + */ + getClassForDate(dateObject: Date, locale: String): String; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Sets calendar's value to today's date + * + */ + goToToday(): void; + /** + * May be overridden to disable certain dates in the calendar e.g. isDisabledDate=dojo.date.locale.isWeekend + * + * @param dateObject + * @param locale Optional + */ + isDisabledDate(dateObject: Date, locale: String): boolean; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }). + * Call specified function when event type occurs, ex: myWidget.on("click", function(){ ... }). + * Note that the function is not run in any particular scope, so if (for example) you want it to run in the + * widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)). + * + * @param type Name of event (ex: "click") or extension event like touch.press. + * @param func + */ + on(type: String, func: Function): any; + /** + * Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }). + * Call specified function when event type occurs, ex: myWidget.on("click", function(){ ... }). + * Note that the function is not run in any particular scope, so if (for example) you want it to run in the + * widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)). + * + * @param type Name of event (ex: "click") or extension event like touch.press. + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * + */ + postCreate(): void; + /** + * Called after the parameters to the widget have been read-in, + * but before the widget template is instantiated. Especially + * useful to set properties that are referenced in the widget + * template. + * + */ + postMixInProperties(): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Processing after the DOM fragment is added to the document + * Called after a widget and its children have been created and added to the page, + * and all related widgets have finished their create() cycle, up through postCreate(). + * + * Note that startup() may be called while the widget is still hidden, for example if the widget is + * inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer. + * For widgets that need to do layout, it's best to put that layout code inside resize(), and then + * extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible. + * + */ + startup(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Static method to get a template based on the templatePath or + * templateString key + */ + getCachedTemplate(): any; + /** + * Called only when the selected date has changed + * + * @param date + */ + onChange(date: Date): void; + } + module CalendarLite { + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/CalendarLite._MonthWidget.html + * + * Displays name of current month padded to the width of the month + * w/the longest name, so that changing months doesn't change width. + * + * Create as: + * + * new Calendar._MonthWidget({ + * lang: ..., + * dateLocaleModule: ... + * }) + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree + */ + class _MonthWidget extends dijit._WidgetBase { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Root CSS class of the widget (ex: dijitTextBox), used to construct CSS classes to indicate + * widget state. + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": string; + set(property:"style", value: string): void; + get(property:"style"): string; + watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Construct the UI for this widget, setting this.domNode. + * Most widgets will mixin dijit._TemplatedMixin, which implements this method. + * + */ + buildRendering(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * Destroy this widget, but not its descendants. Descendants means widgets inside of + * this.containerNode. Will also destroy any resources (including widgets) registered via this.own(). + * + * This method will also destroy internal widgets such as those created from a template, + * assuming those widgets exist inside of this.domNode but outside of this.containerNode. + * + * For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not + * depend on the current ability to destroy a widget without destroying its descendants. Generally + * they should use destroyRecursive() for widgets with children. + * + * @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets + */ + destroy(preserveDom?: boolean): void; + /** + * Recursively destroy the children of this widget and their + * descendants. + * + * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy this widget and its descendants + * This is the generic "destructor" function that all widget users + * should call to cleanly discard with a widget. Once a widget is + * destroyed, it is removed from the manager object. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }). + * Call specified function when event type occurs, ex: myWidget.on("click", function(){ ... }). + * Note that the function is not run in any particular scope, so if (for example) you want it to run in the + * widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)). + * + * @param type Name of event (ex: "click") or extension event like touch.press. + * @param func + */ + on(type: String, func: Function): any; + /** + * Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }). + * Call specified function when event type occurs, ex: myWidget.on("click", function(){ ... }). + * Note that the function is not run in any particular scope, so if (for example) you want it to run in the + * widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)). + * + * @param type Name of event (ex: "click") or extension event like touch.press. + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * Processing after the DOM fragment is created + * Called after the DOM fragment has been created, but not necessarily + * added to the document. Do not include any operations which rely on + * node dimensions or placement. + * + */ + postCreate(): void; + /** + * Called after the parameters to the widget have been read-in, + * but before the widget template is instantiated. Especially + * useful to set properties that are referenced in the widget + * template. + * + */ + postMixInProperties(): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Processing after the DOM fragment is added to the document + * Called after a widget and its children have been created and added to the page, + * and all related widgets have finished their create() cycle, up through postCreate(). + * + * Note that startup() may be called while the widget is still hidden, for example if the widget is + * inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer. + * For widgets that need to do layout, it's best to put that layout code inside resize(), and then + * extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible. + * + */ + startup(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + } + } + + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/Declaration.html + * + * The Declaration widget allows a developer to declare new widget + * classes directly from a snippet of markup. + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree + */ + class Declaration extends dijit._Widget { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Root CSS class of the widget (ex: dijitTextBox), used to construct CSS classes to indicate + * widget state. + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * + */ + "defaults": Object; + set(property:"defaults", value: Object): void; + get(property:"defaults"): Object; + watch(property:"defaults", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * This widget or a widget it contains has focus, or is "active" because + * it was recently clicked. + * + */ + "focused": boolean; + set(property:"focused", value: boolean): void; + get(property:"focused"): boolean; + watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * List containing the prototype for this widget, and also any mixins, + * ex: ["dijit._Widget", "dijit._Container"] + * + */ + "mixins": Object; + set(property:"mixins", value: Object): void; + get(property:"mixins"): Object; + watch(property:"mixins", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": string; + set(property:"style", value: string): void; + get(property:"style"): string; + watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Name of class being declared, ex: "acme.myWidget" + * + */ + "widgetClass": string; + set(property:"widgetClass", value: string): void; + get(property:"widgetClass"): string; + watch(property:"widgetClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: String, value: Object): any; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: Object, value: Object): any; + /** + * + */ + buildRendering(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * Destroy this widget, but not its descendants. Descendants means widgets inside of + * this.containerNode. Will also destroy any resources (including widgets) registered via this.own(). + * + * This method will also destroy internal widgets such as those created from a template, + * assuming those widgets exist inside of this.domNode but outside of this.containerNode. + * + * For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not + * depend on the current ability to destroy a widget without destroying its descendants. Generally + * they should use destroyRecursive() for widgets with children. + * + * @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets + */ + destroy(preserveDom?: boolean): void; + /** + * Recursively destroy the children of this widget and their + * descendants. + * + * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy this widget and its descendants + * This is the generic "destructor" function that all widget users + * should call to cleanly discard with a widget. Once a widget is + * destroyed, it is removed from the manager object. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode. + * This method should generally be avoided as it returns widgets declared in templates, which are + * supposed to be internal/hidden, but it's left here for back-compat reasons. + * + */ + getDescendants(): any[]; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * + * @param type protected + * @param func + */ + on(type: String, func: Function): any; + /** + * + * @param type protected + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * + */ + postCreate(): void; + /** + * Called after the parameters to the widget have been read-in, + * but before the widget template is instantiated. Especially + * useful to set properties that are referenced in the widget + * template. + * + */ + postMixInProperties(): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Deprecated. Use set() instead. + * + * @param attr + * @param value + */ + setAttribute(attr: String, value: any): void; + /** + * Processing after the DOM fragment is added to the document + * Called after a widget and its children have been created and added to the page, + * and all related widgets have finished their create() cycle, up through postCreate(). + * + * Note that startup() may be called while the widget is still hidden, for example if the widget is + * inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer. + * For widgets that need to do layout, it's best to put that layout code inside resize(), and then + * extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible. + * + */ + startup(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Called when the widget stops being "active" because + * focus moved to something outside of it, or the user + * clicked somewhere outside of it, or the widget was + * hidden. + * + */ + onBlur(): void; + /** + * Connect to this function to receive notifications of mouse click events. + * + * @param event mouse Event + */ + onClick(event: any): void; + /** + * Called when this widget is being displayed as a popup (ex: a Calendar popped + * up from a DateTextBox), and it is hidden. + * This is called from the dijit.popup code, and should not be called directly. + * + * Also used as a parameter for children of dijit/layout/StackContainer or subclasses. + * Callback if a user tries to close the child. Child will be closed if this function returns true. + * + */ + onClose(): boolean; + /** + * Connect to this function to receive notifications of mouse double click events. + * + * @param event mouse Event + */ + onDblClick(event: any): void; + /** + * Called when the widget becomes "active" because + * it or a widget inside of it either has focus, or has recently + * been clicked. + * + */ + onFocus(): void; + /** + * Called when another widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate hide of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onHide(): void; + /** + * Connect to this function to receive notifications of keys being pressed down. + * + * @param event key Event + */ + onKeyDown(event: any): void; + /** + * Connect to this function to receive notifications of printable keys being typed. + * + * @param event key Event + */ + onKeyPress(event: any): void; + /** + * Connect to this function to receive notifications of keys being released. + * + * @param event key Event + */ + onKeyUp(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is pressed down. + * + * @param event mouse Event + */ + onMouseDown(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto this widget. + * + * @param event mouse Event + */ + onMouseEnter(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of this widget. + * + * @param event mouse Event + */ + onMouseLeave(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves over nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseMove(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOut(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOver(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is released. + * + * @param event mouse Event + */ + onMouseUp(event: any): void; + /** + * Called when this widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate display of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onShow(): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/Calendar.html + * + * A simple GUI for choosing a date in the context of a monthly calendar. + * See CalendarLite for general description. Calendar extends CalendarLite, adding: + * + * month drop down list + * keyboard navigation + * CSS classes for hover/mousepress on date, month, and year nodes + * support of deprecated methods (will be removed in 2.0) + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified, replace srcNodeRef with my generated DOM tree + */ + class Calendar extends dijit.CalendarLite implements dijit._Widget, dijit._CssStateMixin { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * Custom press, release, and click synthetic events + * which trigger on a left mouse click, touch, or space/enter keyup. + * + */ + "a11yclick": Object; + /** + * True if mouse was pressed while over this widget, and hasn't been released yet + * + */ + "active": boolean; + set(property:"active", value: boolean): void; + get(property:"active"): boolean; + watch(property:"active", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + set(property:"attachScope", value: Object): void; + get(property:"attachScope"): Object; + watch(property:"attachScope", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * + */ + "cssStateNodes": Object; + set(property:"cssStateNodes", value: Object): void; + get(property:"cssStateNodes"): Object; + watch(property:"cssStateNodes", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Date object containing the currently focused date, or the date which would be focused + * if the calendar itself was focused. Also indicates which year and month to display, + * i.e. the current "page" the calendar is on. + * + */ + "currentFocus": Date; + set(property:"currentFocus", value: Date): void; + get(property:"currentFocus"): Date; + watch(property:"currentFocus", callback:{(property?:string, oldValue?:Date, newValue?: Date):void}) :{unwatch():void} + /** + * JavaScript namespace to find calendar routines. If unspecified, uses Gregorian calendar routines + * at dojo/date and dojo/date/locale. + * + */ + "datePackage": string; + set(property:"datePackage", value: string): void; + get(property:"datePackage"): string; + watch(property:"datePackage", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "dateTemplateString": string; + set(property:"dateTemplateString", value: string): void; + get(property:"dateTemplateString"): string; + watch(property:"dateTemplateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * How to represent the days of the week in the calendar header. See locale + * + */ + "dayWidth": string; + set(property:"dayWidth", value: string): void; + get(property:"dayWidth"): string; + watch(property:"dayWidth", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * + */ + "dowTemplateString": string; + set(property:"dowTemplateString", value: string): void; + get(property:"dowTemplateString"): string; + watch(property:"dowTemplateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Defines a type of widget. + * + */ + "dndType": string; + set(property:"dndType", value: string): void; + get(property:"dndType"): string; + watch(property:"dndType", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This widget or a widget it contains has focus, or is "active" because + * it was recently clicked. + * + */ + "focused": boolean; + set(property:"focused", value: boolean): void; + get(property:"focused"): boolean; + watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * True if cursor is over this widget + * + */ + "hovering": boolean; + set(property:"hovering", value: boolean): void; + get(property:"hovering"): boolean; + watch(property:"hovering", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "observer": string; + set(property:"observer", value: string): void; + get(property:"observer"): string; + watch(property:"observer", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * + */ + "searchContainerNode": boolean; + set(property:"searchContainerNode", value: boolean): void; + get(property:"searchContainerNode"): boolean; + watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * A parameter needed by RadioGroupSlide only. An optional paramter to force + * the ContentPane to slide in from a set direction. Defaults + * to "random", or specify one of "top", "left", "right", "bottom" + * to slideFrom top, left, right, or bottom. + * + */ + "slideFrom": string; + set(property:"slideFrom", value: string): void; + get(property:"slideFrom"): string; + watch(property:"slideFrom", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": string; + set(property:"style", value: string): void; + get(property:"style"): string; + watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Order fields are traversed when user hits the tab key + * + */ + "tabIndex": string; + set(property:"tabIndex", value: string): void; + get(property:"tabIndex"): string; + watch(property:"tabIndex", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Path to template (HTML file) for this widget relative to dojo.baseUrl. + * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead + * + */ + "templatePath": string; + set(property:"templatePath", value: string): void; + get(property:"templatePath"): string; + watch(property:"templatePath", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "templateString": string; + set(property:"templateString", value: string): void; + get(property:"templateString"): string; + watch(property:"templateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * The currently selected Date, initially set to invalid date to indicate no selection. + * + */ + "value": Date; + set(property:"value", value: Date): void; + get(property:"value"): Date; + watch(property:"value", callback:{(property?:string, oldValue?:Date, newValue?: Date):void}) :{unwatch():void} + /** + * + */ + "weekTemplateString": string; + set(property:"weekTemplateString", value: string): void; + get(property:"weekTemplateString"): string; + watch(property:"weekTemplateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: String, value: Object): any; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: Object, value: Object): any; + /** + * + */ + buildRendering(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * Destroy this widget, but not its descendants. Descendants means widgets inside of + * this.containerNode. Will also destroy any resources (including widgets) registered via this.own(). + * + * This method will also destroy internal widgets such as those created from a template, + * assuming those widgets exist inside of this.domNode but outside of this.containerNode. + * + * For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not + * depend on the current ability to destroy a widget without destroying its descendants. Generally + * they should use destroyRecursive() for widgets with children. + * + * @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets + */ + destroy(preserveDom?: boolean): void; + /** + * Recursively destroy the children of this widget and their + * descendants. + * + * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy this widget and its descendants + * This is the generic "destructor" function that all widget users + * should call to cleanly discard with a widget. Once a widget is + * destroyed, it is removed from the manager object. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Focus the calendar by focusing one of the calendar cells + * + */ + focus(): void; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * May be overridden to return CSS classes to associate with the date entry for the given dateObject, + * for example to indicate a holiday in specified locale. + * + * @param dateObject + * @param locale Optional + */ + getClassForDate(dateObject: Date, locale: String): String; + /** + * Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode. + * This method should generally be avoided as it returns widgets declared in templates, which are + * supposed to be internal/hidden, but it's left here for back-compat reasons. + * + */ + getDescendants(): any[]; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Sets calendar's value to today's date + * + */ + goToToday(): void; + /** + * Provides keyboard navigation of calendar. + * Called from _onKeyDown() to handle keydown on a stand alone Calendar, + * and also from dijit/form/_DateTimeTextBox to pass a keydown event + * from the dijit/form/DateTextBox to be handled in this widget + * + * @param evt + */ + handleKey(evt: Event): any; + /** + * May be overridden to disable certain dates in the calendar e.g. isDisabledDate=dojo.date.locale.isWeekend + * + * @param dateObject + * @param locale Optional + */ + isDisabledDate(dateObject: Date, locale: String): boolean; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }). + * Call specified function when event type occurs, ex: myWidget.on("click", function(){ ... }). + * Note that the function is not run in any particular scope, so if (for example) you want it to run in the + * widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)). + * + * @param type Name of event (ex: "click") or extension event like touch.press. + * @param func + */ + on(type: String, func: Function): any; + /** + * Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }). + * Call specified function when event type occurs, ex: myWidget.on("click", function(){ ... }). + * Note that the function is not run in any particular scope, so if (for example) you want it to run in the + * widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)). + * + * @param type Name of event (ex: "click") or extension event like touch.press. + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * + */ + postCreate(): void; + /** + * Called after the parameters to the widget have been read-in, + * but before the widget template is instantiated. Especially + * useful to set properties that are referenced in the widget + * template. + * + */ + postMixInProperties(): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Deprecated. Use set() instead. + * + * @param attr + * @param value + */ + setAttribute(attr: String, value: any): void; + /** + * Deprecated. Use set('value', ...) instead. + * + * @param value + */ + setValue(value: Date): void; + /** + * Processing after the DOM fragment is added to the document + * Called after a widget and its children have been created and added to the page, + * and all related widgets have finished their create() cycle, up through postCreate(). + * + * Note that startup() may be called while the widget is still hidden, for example if the widget is + * inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer. + * For widgets that need to do layout, it's best to put that layout code inside resize(), and then + * extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible. + * + */ + startup(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Static method to get a template based on the templatePath or + * templateString key + */ + getCachedTemplate(): any; + /** + * Called when the widget stops being "active" because + * focus moved to something outside of it, or the user + * clicked somewhere outside of it, or the widget was + * hidden. + * + */ + onBlur(): void; + /** + * + * @param value + */ + onChange(value: any): void; + /** + * Connect to this function to receive notifications of mouse click events. + * + * @param event mouse Event + */ + onClick(event: any): void; + /** + * Called when this widget is being displayed as a popup (ex: a Calendar popped + * up from a DateTextBox), and it is hidden. + * This is called from the dijit.popup code, and should not be called directly. + * + * Also used as a parameter for children of dijit/layout/StackContainer or subclasses. + * Callback if a user tries to close the child. Child will be closed if this function returns true. + * + */ + onClose(): boolean; + /** + * Connect to this function to receive notifications of mouse double click events. + * + * @param event mouse Event + */ + onDblClick(event: any): void; + /** + * Called when the widget becomes "active" because + * it or a widget inside of it either has focus, or has recently + * been clicked. + * + */ + onFocus(): void; + /** + * Called when another widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate hide of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onHide(): void; + /** + * Connect to this function to receive notifications of keys being pressed down. + * + * @param event key Event + */ + onKeyDown(event: any): void; + /** + * Connect to this function to receive notifications of printable keys being typed. + * + * @param event key Event + */ + onKeyPress(event: any): void; + /** + * Connect to this function to receive notifications of keys being released. + * + * @param event key Event + */ + onKeyUp(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is pressed down. + * + * @param event mouse Event + */ + onMouseDown(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto this widget. + * + * @param event mouse Event + */ + onMouseEnter(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of this widget. + * + * @param event mouse Event + */ + onMouseLeave(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves over nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseMove(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOut(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOver(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is released. + * + * @param event mouse Event + */ + onMouseUp(event: any): void; + /** + * Called when this widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate display of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onShow(): void; + /** + * Deprecated. Notification that a date cell was selected. It may be the same as the previous value. + * Formerly used by dijit/form/_DateTimeTextBox (and thus dijit/form/DateTextBox) + * to get notification when the user has clicked a date. Now onExecute() (above) is used. + * + * @param date + */ + onValueSelected(date: Date): void; + } + module Calendar { + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/Calendar._MonthDropDown.html + * + * The list-of-months drop down from the MonthDropDownButton + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree + */ + class _MonthDropDown extends dijit._Widget implements dijit._TemplatedMixin { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + set(property:"attachScope", value: Object): void; + get(property:"attachScope"): Object; + watch(property:"attachScope", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Root CSS class of the widget (ex: dijitTextBox), used to construct CSS classes to indicate + * widget state. + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * This widget or a widget it contains has focus, or is "active" because + * it was recently clicked. + * + */ + "focused": boolean; + set(property:"focused", value: boolean): void; + get(property:"focused"): boolean; + watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * List of names of months, possibly w/some undefined entries for Hebrew leap months + * (ex: ["January", "February", undefined, "April", ...]) + * + */ + "months": Object; + set(property:"months", value: Object): void; + get(property:"months"): Object; + watch(property:"months", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * + */ + "searchContainerNode": boolean; + set(property:"searchContainerNode", value: boolean): void; + get(property:"searchContainerNode"): boolean; + watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": string; + set(property:"style", value: string): void; + get(property:"style"): string; + watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Path to template (HTML file) for this widget relative to dojo.baseUrl. + * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead + * + */ + "templatePath": string; + set(property:"templatePath", value: string): void; + get(property:"templatePath"): string; + watch(property:"templatePath", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "templateString": string; + set(property:"templateString", value: string): void; + get(property:"templateString"): string; + watch(property:"templateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: String, value: Object): any; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: Object, value: Object): any; + /** + * Construct the UI for this widget, setting this.domNode. + * Most widgets will mixin dijit._TemplatedMixin, which implements this method. + * + */ + buildRendering(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * Destroy this widget, but not its descendants. Descendants means widgets inside of + * this.containerNode. Will also destroy any resources (including widgets) registered via this.own(). + * + * This method will also destroy internal widgets such as those created from a template, + * assuming those widgets exist inside of this.domNode but outside of this.containerNode. + * + * For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not + * depend on the current ability to destroy a widget without destroying its descendants. Generally + * they should use destroyRecursive() for widgets with children. + * + * @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets + */ + destroy(preserveDom?: boolean): void; + /** + * Recursively destroy the children of this widget and their + * descendants. + * + * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy this widget and its descendants + * This is the generic "destructor" function that all widget users + * should call to cleanly discard with a widget. Once a widget is + * destroyed, it is removed from the manager object. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode. + * This method should generally be avoided as it returns widgets declared in templates, which are + * supposed to be internal/hidden, but it's left here for back-compat reasons. + * + */ + getDescendants(): any[]; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * + * @param type protected + * @param func + */ + on(type: String, func: Function): any; + /** + * + * @param type protected + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * + */ + postCreate(): void; + /** + * Called after the parameters to the widget have been read-in, + * but before the widget template is instantiated. Especially + * useful to set properties that are referenced in the widget + * template. + * + */ + postMixInProperties(): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Deprecated. Use set() instead. + * + * @param attr + * @param value + */ + setAttribute(attr: String, value: any): void; + /** + * Processing after the DOM fragment is added to the document + * Called after a widget and its children have been created and added to the page, + * and all related widgets have finished their create() cycle, up through postCreate(). + * + * Note that startup() may be called while the widget is still hidden, for example if the widget is + * inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer. + * For widgets that need to do layout, it's best to put that layout code inside resize(), and then + * extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible. + * + */ + startup(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Static method to get a template based on the templatePath or + * templateString key + */ + getCachedTemplate(): any; + /** + * Called when the widget stops being "active" because + * focus moved to something outside of it, or the user + * clicked somewhere outside of it, or the widget was + * hidden. + * + */ + onBlur(): void; + /** + * Callback when month is selected from drop down + * + * @param month + */ + onChange(month: number): void; + /** + * Connect to this function to receive notifications of mouse click events. + * + * @param event mouse Event + */ + onClick(event: any): void; + /** + * Called when this widget is being displayed as a popup (ex: a Calendar popped + * up from a DateTextBox), and it is hidden. + * This is called from the dijit.popup code, and should not be called directly. + * + * Also used as a parameter for children of dijit/layout/StackContainer or subclasses. + * Callback if a user tries to close the child. Child will be closed if this function returns true. + * + */ + onClose(): boolean; + /** + * Connect to this function to receive notifications of mouse double click events. + * + * @param event mouse Event + */ + onDblClick(event: any): void; + /** + * Called when the widget becomes "active" because + * it or a widget inside of it either has focus, or has recently + * been clicked. + * + */ + onFocus(): void; + /** + * Called when another widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate hide of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onHide(): void; + /** + * Connect to this function to receive notifications of keys being pressed down. + * + * @param event key Event + */ + onKeyDown(event: any): void; + /** + * Connect to this function to receive notifications of printable keys being typed. + * + * @param event key Event + */ + onKeyPress(event: any): void; + /** + * Connect to this function to receive notifications of keys being released. + * + * @param event key Event + */ + onKeyUp(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is pressed down. + * + * @param event mouse Event + */ + onMouseDown(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto this widget. + * + * @param event mouse Event + */ + onMouseEnter(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of this widget. + * + * @param event mouse Event + */ + onMouseLeave(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves over nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseMove(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOut(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOver(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is released. + * + * @param event mouse Event + */ + onMouseUp(event: any): void; + /** + * Called when this widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate display of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onShow(): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/Calendar._MonthDropDownButton.html + * + * DropDownButton for the current month. Displays name of current month + * and a list of month names in the drop down + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree + */ + class _MonthDropDownButton extends dijit.form.DropDownButton { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * True if mouse was pressed while over this widget, and hasn't been released yet + * + */ + "active": boolean; + set(property:"active", value: boolean): void; + get(property:"active"): boolean; + watch(property:"active", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Corresponds to the native HTML element's attribute. + * + */ + "alt": string; + set(property:"alt", value: string): void; + get(property:"alt"): string; + watch(property:"alt", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "aria-label": string; + set(property:"aria-label", value: string): void; + get(property:"aria-label"): string; + watch(property:"aria-label", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + set(property:"attachScope", value: Object): void; + get(property:"attachScope"): Object; + watch(property:"attachScope", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Set to true to make the drop down at least as wide as this + * widget. Set to false if the drop down should just be its + * default width. + * + */ + "autoWidth": boolean; + set(property:"autoWidth", value: boolean): void; + get(property:"autoWidth"): boolean; + watch(property:"autoWidth", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Subclasses may define a cssStateNodes property that lists sub-nodes within the widget that + * need CSS classes applied on mouse hover/press and focus. + * + * Each entry in this optional hash is a an attach-point name (like "upArrowButton") mapped to a CSS class name + * (like "dijitUpArrowButton"). Example: + * + * { + * "upArrowButton": "dijitUpArrowButton", + * "downArrowButton": "dijitDownArrowButton" + * } + * The above will set the CSS class dijitUpArrowButton to the this.upArrowButton DOMNode when it + * + * is hovered, etc. + * + */ + "cssStateNodes": Object; + set(property:"cssStateNodes", value: Object): void; + get(property:"cssStateNodes"): Object; + watch(property:"cssStateNodes", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Should this widget respond to user input? + * In markup, this is specified as "disabled='disabled'", or just "disabled". + * + */ + "disabled": boolean; + set(property:"disabled", value: boolean): void; + get(property:"disabled"): boolean; + watch(property:"disabled", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * The widget to display as a popup. This widget must be + * defined before the startup function is called. + * + */ + "dropDown": Object; + set(property:"dropDown", value: Object): void; + get(property:"dropDown"): Object; + watch(property:"dropDown", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * This variable controls the position of the drop down. + * It's an array of strings with the following values: + * + * before: places drop down to the left of the target node/widget, or to the right in + * the case of RTL scripts like Hebrew and Arabic + * after: places drop down to the right of the target node/widget, or to the left in + * the case of RTL scripts like Hebrew and Arabic + * above: drop down goes above target node + * below: drop down goes below target node + * The list is positions is tried, in order, until a position is found where the drop down fits + * within the viewport. + * + */ + "dropDownPosition": Object; + set(property:"dropDownPosition", value: Object): void; + get(property:"dropDownPosition"): Object; + watch(property:"dropDownPosition", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * This widget or a widget it contains has focus, or is "active" because + * it was recently clicked. + * + */ + "focused": boolean; + set(property:"focused", value: boolean): void; + get(property:"focused"): boolean; + watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Set to true to make the drop down exactly as wide as this + * widget. Overrides autoWidth. + * + */ + "forceWidth": boolean; + set(property:"forceWidth", value: boolean): void; + get(property:"forceWidth"): boolean; + watch(property:"forceWidth", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * True if cursor is over this widget + * + */ + "hovering": boolean; + set(property:"hovering", value: boolean): void; + get(property:"hovering"): boolean; + watch(property:"hovering", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Class to apply to DOMNode in button to make it display an icon + * + */ + "iconClass": string; + set(property:"iconClass", value: string): void; + get(property:"iconClass"): string; + watch(property:"iconClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Fires onChange for each value change or only on demand + * + */ + "intermediateChanges": boolean; + set(property:"intermediateChanges", value: boolean): void; + get(property:"intermediateChanges"): boolean; + watch(property:"intermediateChanges", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Content to display in button. + * + */ + "label": string; + set(property:"label", value: string): void; + get(property:"label"): string; + watch(property:"label", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * The max height for our dropdown. + * Any dropdown taller than this will have scrollbars. + * Set to 0 for no max height, or -1 to limit height to available space in viewport + * + */ + "maxHeight": number; + set(property:"maxHeight", value: number): void; + get(property:"maxHeight"): number; + watch(property:"maxHeight", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} + /** + * Name used when submitting form; same as "name" attribute or plain HTML elements + * + */ + "name": string; + set(property:"name", value: string): void; + get(property:"name"): string; + watch(property:"name", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * On focus, should this widget scroll into view? + * + */ + "scrollOnFocus": boolean; + set(property:"scrollOnFocus", value: boolean): void; + get(property:"scrollOnFocus"): boolean; + watch(property:"scrollOnFocus", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * + */ + "searchContainerNode": boolean; + set(property:"searchContainerNode", value: boolean): void; + get(property:"searchContainerNode"): boolean; + watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Set this to true to hide the label text and display only the icon. + * (If showLabel=false then iconClass must be specified.) + * Especially useful for toolbars. + * If showLabel=true, the label will become the title (a.k.a. tooltip/hint) of the icon. + * + * The exception case is for computers in high-contrast mode, where the label + * will still be displayed, since the icon doesn't appear. + * + */ + "showLabel": boolean; + set(property:"showLabel", value: boolean): void; + get(property:"showLabel"): boolean; + watch(property:"showLabel", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": string; + set(property:"style", value: string): void; + get(property:"style"): string; + watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Order fields are traversed when user hits the tab key + * + */ + "tabIndex": string; + set(property:"tabIndex", value: string): void; + get(property:"tabIndex"): string; + watch(property:"tabIndex", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Path to template (HTML file) for this widget relative to dojo.baseUrl. + * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead + * + */ + "templatePath": string; + set(property:"templatePath", value: string): void; + get(property:"templatePath"): string; + watch(property:"templatePath", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "templateString": string; + set(property:"templateString", value: string): void; + get(property:"templateString"): string; + watch(property:"templateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Corresponds to the native HTML element's attribute. + * + */ + "type": string; + set(property:"type", value: string): void; + get(property:"type"): string; + watch(property:"type", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Corresponds to the native HTML element's attribute. + * + */ + "value": string; + set(property:"value", value: string): void; + get(property:"value"): string; + watch(property:"value", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Makes the given widget a child of this widget. + * Inserts specified child widget's dom node as a child of this widget's + * container node, and possibly does other processing (such as layout). + * + * @param widget + * @param insertIndex Optional + */ + addChild(widget: dijit._WidgetBase, insertIndex: number): void; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: String, value: Object): any; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: Object, value: Object): any; + /** + * Construct the UI for this widget, setting this.domNode. + * Most widgets will mixin dijit._TemplatedMixin, which implements this method. + * + */ + buildRendering(): void; + /** + * Closes the drop down on this widget + * + * @param focus If true, refocuses the button widget + */ + closeDropDown(focus: boolean): void; + /** + * Compare 2 values (as returned by get('value') for this widget). + * + * @param val1 + * @param val2 + */ + compare(val1: any, val2: any): number; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * Destroy this widget, but not its descendants. Descendants means widgets inside of + * this.containerNode. Will also destroy any resources (including widgets) registered via this.own(). + * + * This method will also destroy internal widgets such as those created from a template, + * assuming those widgets exist inside of this.domNode but outside of this.containerNode. + * + * For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not + * depend on the current ability to destroy a widget without destroying its descendants. Generally + * they should use destroyRecursive() for widgets with children. + * + * @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets + */ + destroy(preserveDom?: boolean): void; + /** + * Recursively destroy the children of this widget and their + * descendants. + * + * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy this widget and its descendants + * This is the generic "destructor" function that all widget users + * should call to cleanly discard with a widget. Once a widget is + * destroyed, it is removed from the manager object. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Put focus on this widget + * + */ + focus(): void; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode. + * This method should generally be avoided as it returns widgets declared in templates, which are + * supposed to be internal/hidden, but it's left here for back-compat reasons. + * + */ + getDescendants(): any[]; + /** + * Gets the index of the child in this container or -1 if not found + * + * @param child + */ + getIndexOfChild(child: dijit._WidgetBase): any; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Deprecated. Use get('value') instead. + * + */ + getValue(): any; + /** + * Returns true if widget has child widgets, i.e. if this.containerNode contains widgets. + * + */ + hasChildren(): boolean; + /** + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * + */ + isLoaded(): boolean; + /** + * Creates the drop down if it doesn't exist, loads the data + * if there's an href and it hasn't been loaded yet, and + * then opens the drop down. This is basically a callback when the + * user presses the down arrow button to open the drop down. + * + */ + loadAndOpenDropDown(): any; + /** + * + * @param callback + */ + loadDropDown(callback: Function): void; + /** + * + * @param type protected + * @param func + */ + on(type: String, func: Function): any; + /** + * + * @param type protected + * @param func + */ + on(type: Function, func: Function): any; + /** + * Opens the dropdown for this widget. To be called only when this.dropDown + * has been created and is ready to display (ie, it's data is loaded). + * + */ + openDropDown(): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * + */ + postCreate(): void; + /** + * + */ + postMixInProperties(): void; + /** + * Removes the passed widget instance from this widget but does + * not destroy it. You can also pass in an integer indicating + * the index within the container to remove (ie, removeChild(5) removes the sixth widget). + * + * @param widget + */ + removeChild(widget: dijit._WidgetBase): void; + /** + * Removes the passed widget instance from this widget but does + * not destroy it. You can also pass in an integer indicating + * the index within the container to remove (ie, removeChild(5) removes the sixth widget). + * + * @param widget + */ + removeChild(widget: number): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Deprecated. Use set() instead. + * + * @param attr + * @param value + */ + setAttribute(attr: String, value: any): void; + /** + * Deprecated. Use set('disabled', ...) instead. + * + * @param disabled + */ + setDisabled(disabled: boolean): void; + /** + * Deprecated. Use set('label', ...) instead. + * + * @param content + */ + setLabel(content: String): void; + /** + * Deprecated. Use set('value', ...) instead. + * + * @param value + */ + setValue(value: String): void; + /** + * + */ + startup(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Callback when the user presses the down arrow button or presses + * the down arrow key to open/close the drop down. + * Toggle the drop-down widget; if it is up, close it, if not, open it + * + */ + toggleDropDown(): void; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Static method to get a template based on the templatePath or + * templateString key + */ + getCachedTemplate(): any; + /** + * Called when the widget stops being "active" because + * focus moved to something outside of it, or the user + * clicked somewhere outside of it, or the widget was + * hidden. + * + */ + onBlur(): void; + /** + * Callback when this widget's value is changed. + * + * @param newValue + */ + onChange(newValue: any): void; + /** + * Connect to this function to receive notifications of mouse click events. + * + * @param event mouse Event + */ + onClick(event: any): boolean; + /** + * Called when this widget is being displayed as a popup (ex: a Calendar popped + * up from a DateTextBox), and it is hidden. + * This is called from the dijit.popup code, and should not be called directly. + * + * Also used as a parameter for children of dijit/layout/StackContainer or subclasses. + * Callback if a user tries to close the child. Child will be closed if this function returns true. + * + */ + onClose(): boolean; + /** + * Connect to this function to receive notifications of mouse double click events. + * + * @param event mouse Event + */ + onDblClick(event: any): void; + /** + * Called when the widget becomes "active" because + * it or a widget inside of it either has focus, or has recently + * been clicked. + * + */ + onFocus(): void; + /** + * Called when another widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate hide of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onHide(): void; + /** + * Connect to this function to receive notifications of keys being pressed down. + * + * @param event key Event + */ + onKeyDown(event: any): void; + /** + * Connect to this function to receive notifications of printable keys being typed. + * + * @param event key Event + */ + onKeyPress(event: any): void; + /** + * Connect to this function to receive notifications of keys being released. + * + * @param event key Event + */ + onKeyUp(event: any): void; + /** + * + */ + onMonthSelect(): void; + /** + * Connect to this function to receive notifications of when the mouse button is pressed down. + * + * @param event mouse Event + */ + onMouseDown(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto this widget. + * + * @param event mouse Event + */ + onMouseEnter(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of this widget. + * + * @param event mouse Event + */ + onMouseLeave(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves over nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseMove(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOut(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOver(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is released. + * + * @param event mouse Event + */ + onMouseUp(event: any): void; + /** + * Called when this widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate display of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onShow(): void; + } + } + + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/CheckedMenuItem.html + * + * A checkbox-like menu item for toggling on and off + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree + */ + class CheckedMenuItem extends dijit.MenuItem { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * Text for the accelerator (shortcut) key combination, a control, alt, etc. modified keystroke meant to + * execute the menu item regardless of where the focus is on the page. + * + * Note that although Menu can display accelerator keys, there is no infrastructure to actually catch and + * execute those accelerators. + * + */ + "accelKey": string; + set(property:"accelKey", value: string): void; + get(property:"accelKey"): string; + watch(property:"accelKey", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * True if mouse was pressed while over this widget, and hasn't been released yet + * + */ + "active": boolean; + set(property:"active", value: boolean): void; + get(property:"active"): boolean; + watch(property:"active", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + set(property:"attachScope", value: Object): void; + get(property:"attachScope"): Object; + watch(property:"attachScope", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Our checked state + * + */ + "checked": boolean; + set(property:"checked", value: boolean): void; + get(property:"checked"): boolean; + watch(property:"checked", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Character (or string) used in place of checkbox icon when display in high contrast mode + * + */ + "checkedChar": string; + set(property:"checkedChar", value: string): void; + get(property:"checkedChar"): string; + watch(property:"checkedChar", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Subclasses may define a cssStateNodes property that lists sub-nodes within the widget that + * need CSS classes applied on mouse hover/press and focus. + * + * Each entry in this optional hash is a an attach-point name (like "upArrowButton") mapped to a CSS class name + * (like "dijitUpArrowButton"). Example: + * + * { + * "upArrowButton": "dijitUpArrowButton", + * "downArrowButton": "dijitDownArrowButton" + * } + * The above will set the CSS class dijitUpArrowButton to the this.upArrowButton DOMNode when it + * + * is hovered, etc. + * + */ + "cssStateNodes": Object; + set(property:"cssStateNodes", value: Object): void; + get(property:"cssStateNodes"): Object; + watch(property:"cssStateNodes", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * If true, the menu item is disabled. + * If false, the menu item is enabled. + * + */ + "disabled": boolean; + set(property:"disabled", value: boolean): void; + get(property:"disabled"): boolean; + watch(property:"disabled", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * This widget or a widget it contains has focus, or is "active" because + * it was recently clicked. + * + */ + "focused": boolean; + set(property:"focused", value: boolean): void; + get(property:"focused"): boolean; + watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * True if cursor is over this widget + * + */ + "hovering": boolean; + set(property:"hovering", value: boolean): void; + get(property:"hovering"): boolean; + watch(property:"hovering", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * + */ + "iconClass": string; + set(property:"iconClass", value: string): void; + get(property:"iconClass"): string; + watch(property:"iconClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Menu text as HTML + * + */ + "label": string; + set(property:"label", value: string): void; + get(property:"label"): string; + watch(property:"label", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * + */ + "role": string; + set(property:"role", value: string): void; + get(property:"role"): string; + watch(property:"role", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "searchContainerNode": boolean; + set(property:"searchContainerNode", value: boolean): void; + get(property:"searchContainerNode"): boolean; + watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Single character (underlined when the parent Menu is focused) used to navigate directly to this widget, + * also known as a mnemonic. + * This is denoted in the label by surrounding the single character with {}. + * For example, if label="{F}ile", then shortcutKey="F". + * + */ + "shortcutKey": string; + set(property:"shortcutKey", value: string): void; + get(property:"shortcutKey"): string; + watch(property:"shortcutKey", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": string; + set(property:"style", value: string): void; + get(property:"style"): string; + watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Path to template (HTML file) for this widget relative to dojo.baseUrl. + * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead + * + */ + "templatePath": string; + set(property:"templatePath", value: string): void; + get(property:"templatePath"): string; + watch(property:"templatePath", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "templateString": string; + set(property:"templateString", value: string): void; + get(property:"templateString"): string; + watch(property:"templateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: String, value: Object): any; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: Object, value: Object): any; + /** + * + */ + buildRendering(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * Destroy this widget, but not its descendants. Descendants means widgets inside of + * this.containerNode. Will also destroy any resources (including widgets) registered via this.own(). + * + * This method will also destroy internal widgets such as those created from a template, + * assuming those widgets exist inside of this.domNode but outside of this.containerNode. + * + * For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not + * depend on the current ability to destroy a widget without destroying its descendants. Generally + * they should use destroyRecursive() for widgets with children. + * + * @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets + */ + destroy(preserveDom?: boolean): void; + /** + * Recursively destroy the children of this widget and their + * descendants. + * + * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy this widget and its descendants + * This is the generic "destructor" function that all widget users + * should call to cleanly discard with a widget. Once a widget is + * destroyed, it is removed from the manager object. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Focus on this MenuItem + * + */ + focus(): void; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode. + * This method should generally be avoided as it returns widgets declared in templates, which are + * supposed to be internal/hidden, but it's left here for back-compat reasons. + * + */ + getDescendants(): any[]; + /** + * Returns the index of this widget within its container parent. + * It returns -1 if the parent does not exist, or if the parent + * is not a dijit/_Container + * + */ + getIndexInParent(): any; + /** + * Returns null if this is the last child of the parent, + * otherwise returns the next element sibling to the "right". + * + */ + getNextSibling(): any; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Returns null if this is the first child of the parent, + * otherwise returns the next element sibling to the "left". + * + */ + getPreviousSibling(): any; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * + * @param type protected + * @param func + */ + on(type: String, func: Function): any; + /** + * + * @param type protected + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * + */ + postCreate(): void; + /** + * Called after the parameters to the widget have been read-in, + * but before the widget template is instantiated. Especially + * useful to set properties that are referenced in the widget + * template. + * + */ + postMixInProperties(): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Deprecated. Use set() instead. + * + * @param attr + * @param value + */ + setAttribute(attr: String, value: any): void; + /** + * Deprecated. Use set('disabled', bool) instead. + * + * @param disabled + */ + setDisabled(disabled: boolean): void; + /** + * Deprecated. Use set('label', ...) instead. + * + * @param content + */ + setLabel(content: String): void; + /** + * Processing after the DOM fragment is added to the document + * Called after a widget and its children have been created and added to the page, + * and all related widgets have finished their create() cycle, up through postCreate(). + * + * Note that startup() may be called while the widget is still hidden, for example if the widget is + * inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer. + * For widgets that need to do layout, it's best to put that layout code inside resize(), and then + * extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible. + * + */ + startup(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Static method to get a template based on the templatePath or + * templateString key + */ + getCachedTemplate(): any; + /** + * Called when the widget stops being "active" because + * focus moved to something outside of it, or the user + * clicked somewhere outside of it, or the widget was + * hidden. + * + */ + onBlur(): void; + /** + * User defined function to handle check/uncheck events + * + * @param checked + */ + onChange(checked: boolean): void; + /** + * User defined function to handle clicks + * + */ + onClick(): void; + /** + * Called when this widget is being displayed as a popup (ex: a Calendar popped + * up from a DateTextBox), and it is hidden. + * This is called from the dijit.popup code, and should not be called directly. + * + * Also used as a parameter for children of dijit/layout/StackContainer or subclasses. + * Callback if a user tries to close the child. Child will be closed if this function returns true. + * + */ + onClose(): boolean; + /** + * Connect to this function to receive notifications of mouse double click events. + * + * @param event mouse Event + */ + onDblClick(event: any): void; + /** + * Called when the widget becomes "active" because + * it or a widget inside of it either has focus, or has recently + * been clicked. + * + */ + onFocus(): void; + /** + * Called when another widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate hide of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onHide(): void; + /** + * Connect to this function to receive notifications of keys being pressed down. + * + * @param event key Event + */ + onKeyDown(event: any): void; + /** + * Connect to this function to receive notifications of printable keys being typed. + * + * @param event key Event + */ + onKeyPress(event: any): void; + /** + * Connect to this function to receive notifications of keys being released. + * + * @param event key Event + */ + onKeyUp(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is pressed down. + * + * @param event mouse Event + */ + onMouseDown(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto this widget. + * + * @param event mouse Event + */ + onMouseEnter(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of this widget. + * + * @param event mouse Event + */ + onMouseLeave(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves over nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseMove(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOut(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOver(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is released. + * + * @param event mouse Event + */ + onMouseUp(event: any): void; + /** + * Called when this widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate display of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onShow(): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/DialogUnderlay.html + * + * A component used to block input behind a dijit/Dialog. + * + * Normally this class should not be instantiated directly, but rather shown and hidden via + * DialogUnderlay.show() and DialogUnderlay.hide(). And usually the module is not accessed directly + * at all, since the underlay is shown and hidden by Dialog.DialogLevelManager. + * + * The underlay itself can be styled based on and id: + * + * #myDialog_underlay { background-color:red; } + * In the case of dijit.Dialog, this id is based on the id of the Dialog, + * suffixed with _underlay. + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree + */ + class DialogUnderlay extends dijit._Widget implements dijit._TemplatedMixin { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + set(property:"attachScope", value: Object): void; + get(property:"attachScope"): Object; + watch(property:"attachScope", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Root CSS class of the widget (ex: dijitTextBox), used to construct CSS classes to indicate + * widget state. + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Id of the dialog.... DialogUnderlay's id is based on this id + * + */ + "dialogId": string; + set(property:"dialogId", value: string): void; + get(property:"dialogId"): string; + watch(property:"dialogId", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * This widget or a widget it contains has focus, or is "active" because + * it was recently clicked. + * + */ + "focused": boolean; + set(property:"focused", value: boolean): void; + get(property:"focused"): boolean; + watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * + */ + "searchContainerNode": boolean; + set(property:"searchContainerNode", value: boolean): void; + get(property:"searchContainerNode"): boolean; + watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": string; + set(property:"style", value: string): void; + get(property:"style"): string; + watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Path to template (HTML file) for this widget relative to dojo.baseUrl. + * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead + * + */ + "templatePath": string; + set(property:"templatePath", value: string): void; + get(property:"templatePath"): string; + watch(property:"templatePath", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "templateString": string; + set(property:"templateString", value: string): void; + get(property:"templateString"): string; + watch(property:"templateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: String, value: Object): any; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: Object, value: Object): any; + /** + * Construct the UI for this widget, setting this.domNode. + * Most widgets will mixin dijit._TemplatedMixin, which implements this method. + * + */ + buildRendering(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * + */ + destroy(): void; + /** + * Recursively destroy the children of this widget and their + * descendants. + * + * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy this widget and its descendants + * This is the generic "destructor" function that all widget users + * should call to cleanly discard with a widget. Once a widget is + * destroyed, it is removed from the manager object. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode. + * This method should generally be avoided as it returns widgets declared in templates, which are + * supposed to be internal/hidden, but it's left here for back-compat reasons. + * + */ + getDescendants(): any[]; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Hide the underlay. + * + */ + hide(): void; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * + * @param type protected + * @param func + */ + on(type: String, func: Function): any; + /** + * + * @param type protected + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * + */ + postCreate(): void; + /** + * Called after the parameters to the widget have been read-in, + * but before the widget template is instantiated. Especially + * useful to set properties that are referenced in the widget + * template. + * + */ + postMixInProperties(): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Deprecated. Use set() instead. + * + * @param attr + * @param value + */ + setAttribute(attr: String, value: any): void; + /** + * Show the dialog underlay + * + */ + show(): void; + /** + * Display the underlay with the given attributes set. If the underlay is already displayed, + * then adjust it's attributes as specified. + * + * @param attrs The parameters to create DialogUnderlay with. + * @param zIndex zIndex of the underlay + */ + show(attrs: Object, zIndex: number): void; + /** + * Processing after the DOM fragment is added to the document + * Called after a widget and its children have been created and added to the page, + * and all related widgets have finished their create() cycle, up through postCreate(). + * + * Note that startup() may be called while the widget is still hidden, for example if the widget is + * inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer. + * For widgets that need to do layout, it's best to put that layout code inside resize(), and then + * extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible. + * + */ + startup(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Static method to get a template based on the templatePath or + * templateString key + */ + getCachedTemplate(): any; + /** + * Called when the widget stops being "active" because + * focus moved to something outside of it, or the user + * clicked somewhere outside of it, or the widget was + * hidden. + * + */ + onBlur(): void; + /** + * Connect to this function to receive notifications of mouse click events. + * + * @param event mouse Event + */ + onClick(event: any): void; + /** + * Called when this widget is being displayed as a popup (ex: a Calendar popped + * up from a DateTextBox), and it is hidden. + * This is called from the dijit.popup code, and should not be called directly. + * + * Also used as a parameter for children of dijit/layout/StackContainer or subclasses. + * Callback if a user tries to close the child. Child will be closed if this function returns true. + * + */ + onClose(): boolean; + /** + * Connect to this function to receive notifications of mouse double click events. + * + * @param event mouse Event + */ + onDblClick(event: any): void; + /** + * Called when the widget becomes "active" because + * it or a widget inside of it either has focus, or has recently + * been clicked. + * + */ + onFocus(): void; + /** + * Called when another widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate hide of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onHide(): void; + /** + * Connect to this function to receive notifications of keys being pressed down. + * + * @param event key Event + */ + onKeyDown(event: any): void; + /** + * Connect to this function to receive notifications of printable keys being typed. + * + * @param event key Event + */ + onKeyPress(event: any): void; + /** + * Connect to this function to receive notifications of keys being released. + * + * @param event key Event + */ + onKeyUp(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is pressed down. + * + * @param event mouse Event + */ + onMouseDown(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto this widget. + * + * @param event mouse Event + */ + onMouseEnter(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of this widget. + * + * @param event mouse Event + */ + onMouseLeave(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves over nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseMove(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOut(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOver(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is released. + * + * @param event mouse Event + */ + onMouseUp(event: any): void; + /** + * Called when this widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate display of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onShow(): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/Dialog.html + * + * A modal dialog Widget. + * Pops up a modal dialog window, blocking access to the screen + * and also graying out the screen Dialog is extended from + * ContentPane so it supports all the same parameters (href, etc.). + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree + */ + class Dialog extends dijit.layout.ContentPane implements dijit._TemplatedMixin, dijit.form._FormMixin, dijit._DialogMixin, dijit._CssStateMixin { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * True if mouse was pressed while over this widget, and hasn't been released yet + * + */ + "active": boolean; + set(property:"active", value: boolean): void; + get(property:"active"): boolean; + watch(property:"active", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + set(property:"attachScope", value: Object): void; + get(property:"attachScope"): Object; + watch(property:"attachScope", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * A Toggle to modify the default focus behavior of a Dialog, which + * is to focus on the first dialog element after opening the dialog. + * False will disable autofocusing. Default: true + * + */ + "autofocus": boolean; + set(property:"autofocus", value: boolean): void; + get(property:"autofocus"): boolean; + watch(property:"autofocus", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Dialog show [x] icon to close itself, and ESC key will close the dialog. + * + */ + "closable": boolean; + set(property:"closable", value: boolean): void; + get(property:"closable"): boolean; + watch(property:"closable", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * The innerHTML of the ContentPane. + * Note that the initialization parameter / argument to set("content", ...) + * can be a String, DomNode, Nodelist, or _Widget. + * + */ + "content": string; + set(property:"content", value: string): void; + get(property:"content"): string; + watch(property:"content", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "cssStateNodes": Object; + set(property:"cssStateNodes", value: Object): void; + get(property:"cssStateNodes"): Object; + watch(property:"cssStateNodes", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + * false - don't adjust size of children + * true - if there is a single visible child widget, set it's size to however big the ContentPane is + * + */ + "doLayout": boolean; + set(property:"doLayout", value: boolean): void; + get(property:"doLayout"): boolean; + watch(property:"doLayout", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Toggles the movable aspect of the Dialog. If true, Dialog + * can be dragged by it's title. If false it will remain centered + * in the viewport. + * + */ + "draggable": boolean; + set(property:"draggable", value: boolean): void; + get(property:"draggable"): boolean; + watch(property:"draggable", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * The time in milliseconds it takes the dialog to fade in and out + * + */ + "duration": number; + set(property:"duration", value: number): void; + get(property:"duration"): number; + watch(property:"duration", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} + /** + * Message that shows if an error occurs + * + */ + "errorMessage": string; + set(property:"errorMessage", value: string): void; + get(property:"errorMessage"): string; + watch(property:"errorMessage", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Extract visible content from inside of .... . + * I.e., strip and (and it's contents) from the href + * + */ + "extractContent": boolean; + set(property:"extractContent", value: boolean): void; + get(property:"extractContent"): boolean; + watch(property:"extractContent", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * This widget or a widget it contains has focus, or is "active" because + * it was recently clicked. + * + */ + "focused": boolean; + set(property:"focused", value: boolean): void; + get(property:"focused"): boolean; + watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * True if cursor is over this widget + * + */ + "hovering": boolean; + set(property:"hovering", value: boolean): void; + get(property:"hovering"): boolean; + watch(property:"hovering", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * The href of the content that displays now. + * Set this at construction if you want to load data externally when the + * pane is shown. (Set preload=true to load it immediately.) + * Changing href after creation doesn't have any effect; Use set('href', ...); + * + */ + "href": string; + set(property:"href", value: string): void; + get(property:"href"): string; + watch(property:"href", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Parameters to pass to xhrGet() request, for example: + * + *
+ * + */ + "ioArgs": Object; + set(property:"ioArgs", value: Object): void; + get(property:"ioArgs"): Object; + watch(property:"ioArgs", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Indicates that this widget will call resize() on it's child widgets + * when they become visible. + * + */ + "isLayoutContainer": boolean; + set(property:"isLayoutContainer", value: boolean): void; + get(property:"isLayoutContainer"): boolean; + watch(property:"isLayoutContainer", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * True if the ContentPane has data in it, either specified + * during initialization (via href or inline content), or set + * via set('content', ...) / set('href', ...) + * + * False if it doesn't have any content, or if ContentPane is + * still in the process of downloading href. + * + */ + "isLoaded": boolean; + set(property:"isLoaded", value: boolean): void; + get(property:"isLoaded"): boolean; + watch(property:"isLoaded", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Message that shows while downloading + * + */ + "loadingMessage": string; + set(property:"loadingMessage", value: string): void; + get(property:"loadingMessage"): string; + watch(property:"loadingMessage", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Maximum size to allow the dialog to expand to, relative to viewport size + * + */ + "maxRatio": number; + set(property:"maxRatio", value: number): void; + get(property:"maxRatio"): number; + watch(property:"maxRatio", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} + /** + * This is the dojo.Deferred returned by set('href', ...) and refresh(). + * Calling onLoadDeferred.then() registers your + * callback to be called only once, when the prior set('href', ...) call or + * the initial href parameter to the constructor finishes loading. + * + * This is different than an onLoad() handler which gets called any time any href + * or content is loaded. + * + */ + "onLoadDeferred": Object; + set(property:"onLoadDeferred", value: Object): void; + get(property:"onLoadDeferred"): Object; + watch(property:"onLoadDeferred", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * True if Dialog is currently displayed on screen. + * + */ + "open": boolean; + set(property:"open", value: boolean): void; + get(property:"open"): boolean; + watch(property:"open", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Parse content and create the widgets, if any. + * + */ + "parseOnLoad": boolean; + set(property:"parseOnLoad", value: boolean): void; + get(property:"parseOnLoad"): boolean; + watch(property:"parseOnLoad", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Flag passed to parser. Root for attribute names to search for. If scopeName is dojo, + * will search for data-dojo-type (or dojoType). For backwards compatibility + * reasons defaults to dojo._scopeName (which is "dojo" except when + * multi-version support is used, when it will be something like dojo16, dojo20, etc.) + * + */ + "parserScope": string; + set(property:"parserScope", value: string): void; + get(property:"parserScope"): string; + watch(property:"parserScope", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Force load of data on initialization even if pane is hidden. + * + */ + "preload": boolean; + set(property:"preload", value: boolean): void; + get(property:"preload"): boolean; + watch(property:"preload", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Prevent caching of data from href's by appending a timestamp to the href. + * + */ + "preventCache": boolean; + set(property:"preventCache", value: boolean): void; + get(property:"preventCache"): boolean; + watch(property:"preventCache", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * A Toggle to modify the default focus behavior of a Dialog, which + * is to re-focus the element which had focus before being opened. + * False will disable refocusing. Default: true + * + */ + "refocus": boolean; + set(property:"refocus", value: boolean): void; + get(property:"refocus"): boolean; + watch(property:"refocus", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Refresh (re-download) content when pane goes from hidden to shown + * + */ + "refreshOnShow": boolean; + set(property:"refreshOnShow", value: boolean): void; + get(property:"refreshOnShow"): boolean; + watch(property:"refreshOnShow", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * + */ + "searchContainerNode": boolean; + set(property:"searchContainerNode", value: boolean): void; + get(property:"searchContainerNode"): boolean; + watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Will be "Error" if one or more of the child widgets has an invalid value, + * "Incomplete" if not all of the required child widgets are filled in. Otherwise, "", + * which indicates that the form is ready to be submitted. + * + */ + "state": string; + set(property:"state", value: string): void; + get(property:"state"): string; + watch(property:"state", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "stopParser": boolean; + set(property:"stopParser", value: boolean): void; + get(property:"stopParser"): boolean; + watch(property:"stopParser", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": string; + set(property:"style", value: string): void; + get(property:"style"): string; + watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Path to template (HTML file) for this widget relative to dojo.baseUrl. + * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead + * + */ + "templatePath": string; + set(property:"templatePath", value: string): void; + get(property:"templatePath"): string; + watch(property:"templatePath", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "templateString": string; + set(property:"templateString", value: string): void; + get(property:"templateString"): string; + watch(property:"templateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Makes the given widget a child of this widget. + * Inserts specified child widget's dom node as a child of this widget's + * container node, and possibly does other processing (such as layout). + * + * @param widget + * @param insertIndex Optional + */ + addChild(widget: dijit._WidgetBase, insertIndex: number): void; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: String, value: Object): any; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: Object, value: Object): any; + /** + * + */ + buildRendering(): void; + /** + * Cancels an in-flight download of content + * + */ + cancel(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * You can call this function directly, ex. in the event that you + * programmatically add a widget to the form after the form has been + * initialized. + * + * @param inStartup + */ + connectChildren(inStartup: boolean): void; + /** + * + * @param params + * @param srcNodeRef + */ + create(params: any, srcNodeRef: any): void; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * + */ + destroy(): void; + /** + * Destroy all the widgets inside the ContentPane and empty containerNode + * + * @param preserveDom + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy the ContentPane and its contents + * + * @param preserveDom + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Deprecated method. Applications no longer need to call this. Remove for 2.0. + * + */ + disconnectChildren(): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Callback when the user hits the submit button. + * Override this method to handle Dialog execution. + * After the user has pressed the submit button, the Dialog + * first calls onExecute() to notify the container to hide the + * dialog and restore focus to wherever it used to be. + * + * Then this method is called. + * + * @param formContents + */ + execute(formContents: Object): void; + /** + * + */ + focus(): void; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode. + * This method should generally be avoided as it returns widgets declared in templates, which are + * supposed to be internal/hidden, but it's left here for back-compat reasons. + * + */ + getDescendants(): any[]; + /** + * Gets the index of the child in this container or -1 if not found + * + * @param child + */ + getIndexOfChild(child: dijit._WidgetBase): any; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * + */ + getValues(): any; + /** + * Returns true if widget has child widgets, i.e. if this.containerNode contains widgets. + * + */ + hasChildren(): boolean; + /** + * Hide the dialog + * + */ + hide(): any; + /** + * Function that should grab the content specified via href. + * + * @param args An object with the following properties:handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional,json-comment-filtered, javascript, xml. See dojo/_base/xhr.contentHandlerssync (Boolean, optional): false is default. Indicates whether the request shouldbe a synchronous (blocking) request.headers (Object, optional): Additional HTTP headers to send in the request.failOk (Boolean, optional): false is default. Indicates whether a request should beallowed to fail (and therefore no console error message inthe event of a failure)contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false toprevent a Content-Type header from being sent, or to a stringto send a different Content-Type.load: This function will becalled on a successful HTTP response code.error: This function willbe called when the request fails due to a network or server error, the urlis invalid, etc. It will also be called if the load or handle callback throws anexception, unless djConfig.debugAtAllCosts is true. This allows deployed applicationsto continue to run even when a logic error happens in the callback, while makingit easier to troubleshoot while in debug mode.handle: This function willbe called at the end of every request, whether or not an error occurs.url (String): URL to server endpoint.content (Object, optional): Contains properties with string values. Theseproperties will be serialized as name1=value2 andpassed in the request.timeout (Integer, optional): Milliseconds to wait for the response. If this timepasses, the then error callbacks are called.form (DOMNode, optional): DOM node for a form. Used to extract the form valuesand send to the server.preventCache (Boolean, optional): Default is false. If true, then a"dojo.preventCache" parameter is sent in the requestwith a value that changes with each request(timestamp). Useful only with GET-type requests.rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the contentproperty is ignored. This is mostly useful for HTTP methods that havea body to their requests, like PUT or POST. This property can be used insteadof postData and putData for dojo/_base/xhr.rawXhrPost and dojo/_base/xhr.rawXhrPut respectively.ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related toIO operations. Otherwise, if djConfig.ioPublish is set to true, topicswill be published via dojo/topic.publish() for different phases of an IO operation.See dojo/main.__IoPublish for a list of topics that are published. + */ + ioMethod(args: Object): any; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * Returns true if all of the widgets are valid. + * Deprecated, will be removed in 2.0. Use get("state") instead. + * + */ + isValid: {(): boolean}; + /** + * + * @param params + * @param node + * @param ctor + */ + markupFactory(params: any, node: any, ctor: any): any; + /** + * + * @param type protected + * @param func + */ + on(type: String, func: Function): any; + /** + * + * @param type protected + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * + */ + postCreate(): void; + /** + * + */ + postMixInProperties(): void; + /** + * [Re]download contents of href and display + * cancels any currently in-flight requests + * posts "loading..." message + * sends XHR to download new data + * + */ + refresh(): any; + /** + * Removes the passed widget instance from this widget but does + * not destroy it. You can also pass in an integer indicating + * the index within the container to remove (ie, removeChild(5) removes the sixth widget). + * + * @param widget + */ + removeChild(widget: dijit._WidgetBase): void; + /** + * Removes the passed widget instance from this widget but does + * not destroy it. You can also pass in an integer indicating + * the index within the container to remove (ie, removeChild(5) removes the sixth widget). + * + * @param widget + */ + removeChild(widget: number): void; + /** + * + */ + reset(): void; + /** + * See dijit/layout/_LayoutWidget.resize() for description. + * Although ContentPane doesn't extend _LayoutWidget, it does implement + * the same API. + * + * @param changeSize + * @param resultSize + */ + resize(changeSize: any, resultSize: any): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Deprecated. Use set() instead. + * + * @param attr + * @param value + */ + setAttribute(attr: String, value: any): void; + /** + * Deprecated. Use set('content', ...) instead. + * + * @param data + */ + setContent(data: String): void; + /** + * Deprecated. Use set('content', ...) instead. + * + * @param data + */ + setContent(data: HTMLElement): void; + /** + * Deprecated. Use set('content', ...) instead. + * + * @param data + */ + setContent(data: NodeList): void; + /** + * Deprecated. Use set('href', ...) instead. + * + * @param href + */ + setHref(href: String): any; + /** + * Deprecated. Use set('href', ...) instead. + * + * @param href + */ + setHref(href: URL): any; + /** + * + * @param val + */ + setValues(val: any): any; + /** + * Display the dialog + * + */ + show(): any; + /** + * Call startup() on all children including non _Widget ones like dojo/dnd/Source objects + * + */ + startup(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * returns if the form is valid - same as isValid - but + * provides a few additional (ui-specific) features: + * + * it will highlight any sub-widgets that are not valid + * it will call focus() on the first invalid sub-widget + * + */ + validate(): any; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Static method to get a template based on the templatePath or + * templateString key + */ + getCachedTemplate(): any; + /** + * Called when the widget stops being "active" because + * focus moved to something outside of it, or the user + * clicked somewhere outside of it, or the widget was + * hidden. + * + */ + onBlur(): void; + /** + * Called when user has pressed the Dialog's cancel button, to notify container. + * Developer shouldn't override or connect to this method; + * it's a private communication device between the TooltipDialog + * and the thing that opened it (ex: dijit/form/DropDownButton) + * + */ + onCancel(): void; + /** + * Connect to this function to receive notifications of mouse click events. + * + * @param event mouse Event + */ + onClick(event: any): void; + /** + * Called when this widget is being displayed as a popup (ex: a Calendar popped + * up from a DateTextBox), and it is hidden. + * This is called from the dijit.popup code, and should not be called directly. + * + * Also used as a parameter for children of dijit/layout/StackContainer or subclasses. + * Callback if a user tries to close the child. Child will be closed if this function returns true. + * + */ + onClose(): boolean; + /** + * Called on DOM faults, require faults etc. in content. + * + * In order to display an error message in the pane, return + * the error message from this method, as an HTML string. + * + * By default (if this method is not overriden), it returns + * nothing, so the error message is just printed to the console. + * + * @param error + */ + onContentError(error: Error): void; + /** + * Connect to this function to receive notifications of mouse double click events. + * + * @param event mouse Event + */ + onDblClick(event: any): void; + /** + * Called when download is finished. + * + */ + onDownloadEnd(): void; + /** + * Called when download error occurs. + * + * In order to display an error message in the pane, return + * the error message from this method, as an HTML string. + * + * Default behavior (if this method is not overriden) is to display + * the error message inside the pane. + * + * @param error + */ + onDownloadError(error: Error): any; + /** + * Called before download starts. + * The string returned by this function will be the html + * that tells the user we are loading something. + * Override with your own function if you want to change text. + * + */ + onDownloadStart(): any; + /** + * Called when user has pressed the dialog's OK button, to notify container. + * Developer shouldn't override or connect to this method; + * it's a private communication device between the TooltipDialog + * and the thing that opened it (ex: dijit/form/DropDownButton) + * + */ + onExecute(): void; + /** + * Called when the widget becomes "active" because + * it or a widget inside of it either has focus, or has recently + * been clicked. + * + */ + onFocus(): void; + /** + * Called when another widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate hide of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onHide(): void; + /** + * Connect to this function to receive notifications of keys being pressed down. + * + * @param event key Event + */ + onKeyDown(event: any): void; + /** + * Connect to this function to receive notifications of printable keys being typed. + * + * @param event key Event + */ + onKeyPress(event: any): void; + /** + * Connect to this function to receive notifications of keys being released. + * + * @param event key Event + */ + onKeyUp(event: any): void; + /** + * Event hook, is called after everything is loaded and widgetified + * + * @param data + */ + onLoad(data: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is pressed down. + * + * @param event mouse Event + */ + onMouseDown(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto this widget. + * + * @param event mouse Event + */ + onMouseEnter(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of this widget. + * + * @param event mouse Event + */ + onMouseLeave(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves over nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseMove(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOut(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOver(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is released. + * + * @param event mouse Event + */ + onMouseUp(event: any): void; + /** + * Called when this widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate display of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onShow(): void; + /** + * Event hook, is called before old content is cleared + * + */ + onUnload(): void; + /** + * Stub function to connect to if you want to do something + * (like disable/enable a submit button) when the valid + * state changes on the form as a whole. + * + * Deprecated. Will be removed in 2.0. Use watch("state", ...) instead. + * + * @param isValid + */ + onValidStateChange(isValid: boolean): void; + } + module Dialog { + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/Dialog._DialogBase.html + * + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified, replace srcNodeRef with my generated DOM tree. + */ + class _DialogBase extends dijit._TemplatedMixin implements dijit.form._FormMixin, dijit._DialogMixin, dijit._CssStateMixin { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * True if mouse was pressed while over this widget, and hasn't been released yet + * + */ + "active": boolean; + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + /** + * A Toggle to modify the default focus behavior of a Dialog, which + * is to focus on the first dialog element after opening the dialog. + * False will disable autofocusing. Default: true + * + */ + "autofocus": boolean; + /** + * + */ + "baseClass": string; + /** + * Dialog show [x] icon to close itself, and ESC key will close the dialog. + * + */ + "closable": boolean; + /** + * + */ + "cssStateNodes": Object; + /** + * Don't change this parameter from the default value. + * This ContentPane parameter doesn't make sense for Dialog, since Dialog + * is never a child of a layout container, nor can you specify the size of + * Dialog in order to control the size of an inner widget. + * + */ + "doLayout": boolean; + /** + * Toggles the movable aspect of the Dialog. If true, Dialog + * can be dragged by it's title. If false it will remain centered + * in the viewport. + * + */ + "draggable": boolean; + /** + * The time in milliseconds it takes the dialog to fade in and out + * + */ + "duration": number; + /** + * True if cursor is over this widget + * + */ + "hovering": boolean; + /** + * Maximum size to allow the dialog to expand to, relative to viewport size + * + */ + "maxRatio": number; + /** + * True if Dialog is currently displayed on screen. + * + */ + "open": boolean; + /** + * A Toggle to modify the default focus behavior of a Dialog, which + * is to re-focus the element which had focus before being opened. + * False will disable refocusing. Default: true + * + */ + "refocus": boolean; + /** + * + */ + "searchContainerNode": boolean; + /** + * Will be "Error" if one or more of the child widgets has an invalid value, + * "Incomplete" if not all of the required child widgets are filled in. Otherwise, "", + * which indicates that the form is ready to be submitted. + * + */ + "state": string; + /** + * Path to template (HTML file) for this widget relative to dojo.baseUrl. + * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead + * + */ + "templatePath": string; + /** + * + */ + "templateString": string; + /** + * Construct the UI for this widget from a template, setting this.domNode. + * + */ + buildRendering(): void; + /** + * You can call this function directly, ex. in the event that you + * programmatically add a widget to the form after the form has been + * initialized. + * + * @param inStartup + */ + connectChildren(inStartup: boolean): void; + /** + * + */ + destroy(): void; + /** + * + */ + destroyRendering(): void; + /** + * Deprecated method. Applications no longer need to call this. Remove for 2.0. + * + */ + disconnectChildren(): void; + /** + * Callback when the user hits the submit button. + * Override this method to handle Dialog execution. + * After the user has pressed the submit button, the Dialog + * first calls onExecute() to notify the container to hide the + * dialog and restore focus to wherever it used to be. + * + * Then this method is called. + * + * @param formContents + */ + execute(formContents: Object): void; + /** + * + */ + focus(): void; + /** + * + */ + getValues(): any; + /** + * Hide the dialog + * + */ + hide(): any; + /** + * Returns true if all of the widgets are valid. + * Deprecated, will be removed in 2.0. Use get("state") instead. + * + */ + isValid: {(): boolean}; + /** + * + */ + postCreate(): void; + /** + * + */ + postMixInProperties(): void; + /** + * + */ + reset(): void; + /** + * + * @param val + */ + setValues(val: any): any; + /** + * Display the dialog + * + */ + show(): any; + /** + * + */ + startup(): void; + /** + * returns if the form is valid - same as isValid - but + * provides a few additional (ui-specific) features: + * + * it will highlight any sub-widgets that are not valid + * it will call focus() on the first invalid sub-widget + * + */ + validate(): any; + /** + * Static method to get a template based on the templatePath or + * templateString key + */ + getCachedTemplate(): any; + /** + * Called when user has pressed the Dialog's cancel button, to notify container. + * Developer shouldn't override or connect to this method; + * it's a private communication device between the TooltipDialog + * and the thing that opened it (ex: dijit/form/DropDownButton) + * + */ + onCancel(): void; + /** + * Called when user has pressed the dialog's OK button, to notify container. + * Developer shouldn't override or connect to this method; + * it's a private communication device between the TooltipDialog + * and the thing that opened it (ex: dijit/form/DropDownButton) + * + */ + onExecute(): void; + /** + * Called when data has been loaded from an href. + * Unlike most other callbacks, this function can be connected to (via dojo.connect) + * but should not be overridden. + * + */ + onLoad(): void; + /** + * Stub function to connect to if you want to do something + * (like disable/enable a submit button) when the valid + * state changes on the form as a whole. + * + * Deprecated. Will be removed in 2.0. Use watch("state", ...) instead. + * + * @param isValid + */ + onValidStateChange(isValid: boolean): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/Dialog._DialogLevelManager.html + * + * Controls the various active "levels" on the page, starting with the + * stuff initially visible on the page (at z-index 0), and then having an entry for + * each Dialog shown. + * + */ + interface _DialogLevelManager { + /** + * Called when the specified dialog is hidden/destroyed, after the fade-out + * animation ends, in order to reset page focus, fix the underlay, etc. + * If the specified dialog isn't open then does nothing. + * + * Caller is responsible for either setting display:none on the dialog domNode, + * or calling dijit/popup.hide(), or removing it from the page DOM. + * + * @param dialog + */ + hide(dialog: dijit._WidgetBase): void; + /** + * Returns true if specified Dialog is the top in the task + * + * @param dialog + */ + isTop(dialog: dijit._WidgetBase): boolean; + /** + * Call right before fade-in animation for new dialog. + * Saves current focus, displays/adjusts underlay for new dialog, + * and sets the z-index of the dialog itself. + * + * New dialog will be displayed on top of all currently displayed dialogs. + * + * Caller is responsible for setting focus in new dialog after the fade-in + * animation completes. + * + * @param dialog + * @param underlayAttrs + */ + show(dialog: dijit._WidgetBase, underlayAttrs: Object): void; + } + } + + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/ColorPalette.html + * + * A keyboard accessible color-picking widget + * Grid showing various colors, so the user can pick a certain color. + * Can be used standalone, or as a popup. + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree + */ + class ColorPalette extends dijit._Widget implements dijit._TemplatedMixin, dijit._PaletteMixin { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * True if mouse was pressed while over this widget, and hasn't been released yet + * + */ + "active": boolean; + set(property:"active", value: boolean): void; + get(property:"active"): boolean; + watch(property:"active", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + set(property:"attachScope", value: Object): void; + get(property:"attachScope"): Object; + watch(property:"attachScope", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * CSS class applied to each cell in the palette + * + */ + "cellClass": string; + set(property:"cellClass", value: string): void; + get(property:"cellClass"): string; + watch(property:"cellClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Subclasses may define a cssStateNodes property that lists sub-nodes within the widget that + * need CSS classes applied on mouse hover/press and focus. + * + * Each entry in this optional hash is a an attach-point name (like "upArrowButton") mapped to a CSS class name + * (like "dijitUpArrowButton"). Example: + * + * { + * "upArrowButton": "dijitUpArrowButton", + * "downArrowButton": "dijitDownArrowButton" + * } + * The above will set the CSS class dijitUpArrowButton to the this.upArrowButton DOMNode when it + * + * is hovered, etc. + * + */ + "cssStateNodes": Object; + set(property:"cssStateNodes", value: Object): void; + get(property:"cssStateNodes"): Object; + watch(property:"cssStateNodes", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Number of milliseconds before a held key or button becomes typematic + * + */ + "defaultTimeout": number; + set(property:"defaultTimeout", value: number): void; + get(property:"defaultTimeout"): number; + watch(property:"defaultTimeout", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Constructor for Object created for each cell of the palette. + * dyeClass should implement the dijit/_PaletteMixin.__Dye interface. + * + */ + "dyeClass": Function; + set(property:"dyeClass", value: Function): void; + get(property:"dyeClass"): Function; + watch(property:"dyeClass", callback:{(property?:string, oldValue?:Function, newValue?: Function):void}) :{unwatch():void} + /** + * This widget or a widget it contains has focus, or is "active" because + * it was recently clicked. + * + */ + "focused": boolean; + set(property:"focused", value: boolean): void; + get(property:"focused"): boolean; + watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * True if cursor is over this widget + * + */ + "hovering": boolean; + set(property:"hovering", value: boolean): void; + get(property:"hovering"): boolean; + watch(property:"hovering", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Size of grid, either "7x10" or "3x4". + * + */ + "palette": string; + set(property:"palette", value: string): void; + get(property:"palette"): string; + watch(property:"palette", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "searchContainerNode": boolean; + set(property:"searchContainerNode", value: boolean): void; + get(property:"searchContainerNode"): boolean; + watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": string; + set(property:"style", value: string): void; + get(property:"style"): string; + watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Widget tab index. + * + */ + "tabIndex": string; + set(property:"tabIndex", value: string): void; + get(property:"tabIndex"): string; + watch(property:"tabIndex", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Path to template (HTML file) for this widget relative to dojo.baseUrl. + * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead + * + */ + "templatePath": string; + set(property:"templatePath", value: string): void; + get(property:"templatePath"): string; + watch(property:"templatePath", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * The template of this widget. + * + */ + "templateString": string; + set(property:"templateString", value: string): void; + get(property:"templateString"): string; + watch(property:"templateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Fraction of time used to change the typematic timer between events + * 1.0 means that each typematic event fires at defaultTimeout intervals + * Less than 1.0 means that each typematic event fires at an increasing faster rate + * + */ + "timeoutChangeRate": number; + set(property:"timeoutChangeRate", value: number): void; + get(property:"timeoutChangeRate"): number; + watch(property:"timeoutChangeRate", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Currently selected color/emoticon/etc. + * + */ + "value": string; + set(property:"value", value: string): void; + get(property:"value"): string; + watch(property:"value", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: String, value: Object): any; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: Object, value: Object): any; + /** + * + */ + buildRendering(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * Destroy this widget, but not its descendants. Descendants means widgets inside of + * this.containerNode. Will also destroy any resources (including widgets) registered via this.own(). + * + * This method will also destroy internal widgets such as those created from a template, + * assuming those widgets exist inside of this.domNode but outside of this.containerNode. + * + * For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not + * depend on the current ability to destroy a widget without destroying its descendants. Generally + * they should use destroyRecursive() for widgets with children. + * + * @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets + */ + destroy(preserveDom?: boolean): void; + /** + * Recursively destroy the children of this widget and their + * descendants. + * + * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy this widget and its descendants + * This is the generic "destructor" function that all widget users + * should call to cleanly discard with a widget. Once a widget is + * destroyed, it is removed from the manager object. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Focus this widget. Puts focus on the most recently focused cell. + * + */ + focus(): void; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode. + * This method should generally be avoided as it returns widgets declared in templates, which are + * supposed to be internal/hidden, but it's left here for back-compat reasons. + * + */ + getDescendants(): any[]; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * + * @param type protected + * @param func + */ + on(type: String, func: Function): any; + /** + * + * @param type protected + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * + */ + postCreate(): void; + /** + * Called after the parameters to the widget have been read-in, + * but before the widget template is instantiated. Especially + * useful to set properties that are referenced in the widget + * template. + * + */ + postMixInProperties(): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Deprecated. Use set() instead. + * + * @param attr + * @param value + */ + setAttribute(attr: String, value: any): void; + /** + * Processing after the DOM fragment is added to the document + * Called after a widget and its children have been created and added to the page, + * and all related widgets have finished their create() cycle, up through postCreate(). + * + * Note that startup() may be called while the widget is still hidden, for example if the widget is + * inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer. + * For widgets that need to do layout, it's best to put that layout code inside resize(), and then + * extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible. + * + */ + startup(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Static method to get a template based on the templatePath or + * templateString key + */ + getCachedTemplate(): any; + /** + * Called when the widget stops being "active" because + * focus moved to something outside of it, or the user + * clicked somewhere outside of it, or the widget was + * hidden. + * + */ + onBlur(): void; + /** + * Callback when a cell is selected. + * + * @param value Value corresponding to cell. + */ + onChange(value: String): void; + /** + * Connect to this function to receive notifications of mouse click events. + * + * @param event mouse Event + */ + onClick(event: any): void; + /** + * Called when this widget is being displayed as a popup (ex: a Calendar popped + * up from a DateTextBox), and it is hidden. + * This is called from the dijit.popup code, and should not be called directly. + * + * Also used as a parameter for children of dijit/layout/StackContainer or subclasses. + * Callback if a user tries to close the child. Child will be closed if this function returns true. + * + */ + onClose(): boolean; + /** + * Connect to this function to receive notifications of mouse double click events. + * + * @param event mouse Event + */ + onDblClick(event: any): void; + /** + * Called when the widget becomes "active" because + * it or a widget inside of it either has focus, or has recently + * been clicked. + * + */ + onFocus(): void; + /** + * Called when another widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate hide of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onHide(): void; + /** + * Connect to this function to receive notifications of keys being pressed down. + * + * @param event key Event + */ + onKeyDown(event: any): void; + /** + * Connect to this function to receive notifications of printable keys being typed. + * + * @param event key Event + */ + onKeyPress(event: any): void; + /** + * Connect to this function to receive notifications of keys being released. + * + * @param event key Event + */ + onKeyUp(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is pressed down. + * + * @param event mouse Event + */ + onMouseDown(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto this widget. + * + * @param event mouse Event + */ + onMouseEnter(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of this widget. + * + * @param event mouse Event + */ + onMouseLeave(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves over nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseMove(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOut(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOver(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is released. + * + * @param event mouse Event + */ + onMouseUp(event: any): void; + /** + * Called when this widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate display of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onShow(): void; + } + module ColorPalette { + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/ColorPalette._Color.html + * + * Object associated with each cell in a ColorPalette palette. + * Implements dijit/Dye. + * + * @param alias English name of the color. + * @param row Vertical position in grid. + * @param col + * @param title Localized name of the color. + */ + class _Color extends dojo._base.Color { + constructor(alias: String, row: number, col: any, title: String); + /** + * + */ + "a": number; + /** + * + */ + "b": number; + /** + * + */ + "g": number; + /** + * + */ + "hcTemplate": string; + /** + * + */ + "r": number; + /** + * + */ + "template": string; + /** + * + * @param cell + * @param blankGif + */ + fillCell(cell: HTMLElement, blankGif: String): void; + /** + * Note that although dijit._Color is initialized with a value like "white" getValue() always + * returns a hex value + * + */ + getValue(): any; + /** + * makes sure that the object has correct attributes + * + */ + sanitize(): void; + /** + * Takes a named string, hex string, array of rgb or rgba values, + * an object with r, g, b, and a properties, or another Color object + * and sets this color instance to that value. + * + * @param color + */ + setColor(color: any[]): Function; + /** + * Takes a named string, hex string, array of rgb or rgba values, + * an object with r, g, b, and a properties, or another Color object + * and sets this color instance to that value. + * + * @param color + */ + setColor(color: String): Function; + /** + * Takes a named string, hex string, array of rgb or rgba values, + * an object with r, g, b, and a properties, or another Color object + * and sets this color instance to that value. + * + * @param color + */ + setColor(color: Object): Function; + /** + * Returns a css color string in rgb(a) representation + * + * @param includeAlpha Optional + */ + toCss(includeAlpha: boolean): String; + /** + * Returns a CSS color string in hexadecimal representation + * + */ + toHex(): String; + /** + * Returns 3 component array of rgb values + * + */ + toRgb(): any[]; + /** + * Returns a 4 component array of rgba values from the color + * represented by this object. + * + */ + toRgba(): any[]; + /** + * Returns a visual representation of the color + * + */ + toString(): any; + } + } + + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/Fieldset.html + * + * An accessible fieldset that can be expanded or collapsed via + * its legend. Fieldset extends dijit.TitlePane. + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree + */ + class Fieldset extends dijit.TitlePane { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * True if mouse was pressed while over this widget, and hasn't been released yet + * + */ + "active": boolean; + set(property:"active", value: boolean): void; + get(property:"active"): boolean; + watch(property:"active", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + set(property:"attachScope", value: Object): void; + get(property:"attachScope"): Object; + watch(property:"attachScope", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * The root className to use for the various states of this widget + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * The innerHTML of the ContentPane. + * Note that the initialization parameter / argument to set("content", ...) + * can be a String, DomNode, Nodelist, or _Widget. + * + */ + "content": string; + set(property:"content", value: string): void; + get(property:"content"): string; + watch(property:"content", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Subclasses may define a cssStateNodes property that lists sub-nodes within the widget that + * need CSS classes applied on mouse hover/press and focus. + * + * Each entry in this optional hash is a an attach-point name (like "upArrowButton") mapped to a CSS class name + * (like "dijitUpArrowButton"). Example: + * + * { + * "upArrowButton": "dijitUpArrowButton", + * "downArrowButton": "dijitDownArrowButton" + * } + * The above will set the CSS class dijitUpArrowButton to the this.upArrowButton DOMNode when it + * + * is hovered, etc. + * + */ + "cssStateNodes": Object; + set(property:"cssStateNodes", value: Object): void; + get(property:"cssStateNodes"): Object; + watch(property:"cssStateNodes", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Don't change this parameter from the default value. + * This ContentPane parameter doesn't make sense for TitlePane, since TitlePane + * is never a child of a layout container, nor should TitlePane try to control + * the size of an inner widget. + * + */ + "doLayout": boolean; + set(property:"doLayout", value: boolean): void; + get(property:"doLayout"): boolean; + watch(property:"doLayout", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Time in milliseconds to fade in/fade out + * + */ + "duration": number; + set(property:"duration", value: number): void; + get(property:"duration"): number; + watch(property:"duration", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} + /** + * Message that shows if an error occurs + * + */ + "errorMessage": string; + set(property:"errorMessage", value: string): void; + get(property:"errorMessage"): string; + watch(property:"errorMessage", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Extract visible content from inside of .... . + * I.e., strip and (and it's contents) from the href + * + */ + "extractContent": boolean; + set(property:"extractContent", value: boolean): void; + get(property:"extractContent"): boolean; + watch(property:"extractContent", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * This widget or a widget it contains has focus, or is "active" because + * it was recently clicked. + * + */ + "focused": boolean; + set(property:"focused", value: boolean): void; + get(property:"focused"): boolean; + watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * True if cursor is over this widget + * + */ + "hovering": boolean; + set(property:"hovering", value: boolean): void; + get(property:"hovering"): boolean; + watch(property:"hovering", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * The href of the content that displays now. + * Set this at construction if you want to load data externally when the + * pane is shown. (Set preload=true to load it immediately.) + * Changing href after creation doesn't have any effect; Use set('href', ...); + * + */ + "href": string; + set(property:"href", value: string): void; + get(property:"href"): string; + watch(property:"href", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Parameters to pass to xhrGet() request, for example: + * + *
+ * + */ + "ioArgs": Object; + set(property:"ioArgs", value: Object): void; + get(property:"ioArgs"): Object; + watch(property:"ioArgs", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Indicates that this widget will call resize() on it's child widgets + * when they become visible. + * + */ + "isLayoutContainer": boolean; + set(property:"isLayoutContainer", value: boolean): void; + get(property:"isLayoutContainer"): boolean; + watch(property:"isLayoutContainer", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * True if the ContentPane has data in it, either specified + * during initialization (via href or inline content), or set + * via set('content', ...) / set('href', ...) + * + * False if it doesn't have any content, or if ContentPane is + * still in the process of downloading href. + * + */ + "isLoaded": boolean; + set(property:"isLoaded", value: boolean): void; + get(property:"isLoaded"): boolean; + watch(property:"isLoaded", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Message that shows while downloading + * + */ + "loadingMessage": string; + set(property:"loadingMessage", value: string): void; + get(property:"loadingMessage"): string; + watch(property:"loadingMessage", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This is the dojo.Deferred returned by set('href', ...) and refresh(). + * Calling onLoadDeferred.then() registers your + * callback to be called only once, when the prior set('href', ...) call or + * the initial href parameter to the constructor finishes loading. + * + * This is different than an onLoad() handler which gets called any time any href + * or content is loaded. + * + */ + "onLoadDeferred": Object; + set(property:"onLoadDeferred", value: Object): void; + get(property:"onLoadDeferred"): Object; + watch(property:"onLoadDeferred", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Whether fieldset is opened or closed. + * + */ + "open": boolean; + set(property:"open", value: boolean): void; + get(property:"open"): boolean; + watch(property:"open", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Parse content and create the widgets, if any. + * + */ + "parseOnLoad": boolean; + set(property:"parseOnLoad", value: boolean): void; + get(property:"parseOnLoad"): boolean; + watch(property:"parseOnLoad", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Flag passed to parser. Root for attribute names to search for. If scopeName is dojo, + * will search for data-dojo-type (or dojoType). For backwards compatibility + * reasons defaults to dojo._scopeName (which is "dojo" except when + * multi-version support is used, when it will be something like dojo16, dojo20, etc.) + * + */ + "parserScope": string; + set(property:"parserScope", value: string): void; + get(property:"parserScope"): string; + watch(property:"parserScope", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Force load of data on initialization even if pane is hidden. + * + */ + "preload": boolean; + set(property:"preload", value: boolean): void; + get(property:"preload"): boolean; + watch(property:"preload", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Prevent caching of data from href's by appending a timestamp to the href. + * + */ + "preventCache": boolean; + set(property:"preventCache", value: boolean): void; + get(property:"preventCache"): boolean; + watch(property:"preventCache", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Refresh (re-download) content when pane goes from hidden to shown + * + */ + "refreshOnShow": boolean; + set(property:"refreshOnShow", value: boolean): void; + get(property:"refreshOnShow"): boolean; + watch(property:"refreshOnShow", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * + */ + "searchContainerNode": boolean; + set(property:"searchContainerNode", value: boolean): void; + get(property:"searchContainerNode"): boolean; + watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * + */ + "stopParser": boolean; + set(property:"stopParser", value: boolean): void; + get(property:"stopParser"): boolean; + watch(property:"stopParser", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": string; + set(property:"style", value: string): void; + get(property:"style"): string; + watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Tabindex setting for the title (so users can tab to the title then + * use space/enter to open/close the title pane) + * + */ + "tabIndex": string; + set(property:"tabIndex", value: string): void; + get(property:"tabIndex"): string; + watch(property:"tabIndex", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Path to template (HTML file) for this widget relative to dojo.baseUrl. + * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead + * + */ + "templatePath": string; + set(property:"templatePath", value: string): void; + get(property:"templatePath"): string; + watch(property:"templatePath", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "templateString": string; + set(property:"templateString", value: string): void; + get(property:"templateString"): string; + watch(property:"templateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Content of the legend tag. Overrides tag if not empty. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Whether pane can be opened or closed by clicking the title bar. + * + */ + "toggleable": boolean; + set(property:"toggleable", value: boolean): void; + get(property:"toggleable"): boolean; + watch(property:"toggleable", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Makes the given widget a child of this widget. + * Inserts specified child widget's dom node as a child of this widget's + * container node, and possibly does other processing (such as layout). + * + * @param widget + * @param insertIndex Optional + */ + addChild(widget: dijit._WidgetBase, insertIndex: number): void; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: String, value: Object): any; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: Object, value: Object): any; + /** + * + */ + buildRendering(): void; + /** + * Cancels an in-flight download of content + * + */ + cancel(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * + * @param params + * @param srcNodeRef + */ + create(params: any, srcNodeRef: any): void; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * + */ + destroy(): void; + /** + * Destroy all the widgets inside the ContentPane and empty containerNode + * + * @param preserveDom + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy the ContentPane and its contents + * + * @param preserveDom + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode. + * This method should generally be avoided as it returns widgets declared in templates, which are + * supposed to be internal/hidden, but it's left here for back-compat reasons. + * + */ + getDescendants(): any[]; + /** + * Gets the index of the child in this container or -1 if not found + * + * @param child + */ + getIndexOfChild(child: dijit._WidgetBase): any; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Returns true if widget has child widgets, i.e. if this.containerNode contains widgets. + * + */ + hasChildren(): boolean; + /** + * Function that should grab the content specified via href. + * + * @param args An object with the following properties:handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional,json-comment-filtered, javascript, xml. See dojo/_base/xhr.contentHandlerssync (Boolean, optional): false is default. Indicates whether the request shouldbe a synchronous (blocking) request.headers (Object, optional): Additional HTTP headers to send in the request.failOk (Boolean, optional): false is default. Indicates whether a request should beallowed to fail (and therefore no console error message inthe event of a failure)contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false toprevent a Content-Type header from being sent, or to a stringto send a different Content-Type.load: This function will becalled on a successful HTTP response code.error: This function willbe called when the request fails due to a network or server error, the urlis invalid, etc. It will also be called if the load or handle callback throws anexception, unless djConfig.debugAtAllCosts is true. This allows deployed applicationsto continue to run even when a logic error happens in the callback, while makingit easier to troubleshoot while in debug mode.handle: This function willbe called at the end of every request, whether or not an error occurs.url (String): URL to server endpoint.content (Object, optional): Contains properties with string values. Theseproperties will be serialized as name1=value2 andpassed in the request.timeout (Integer, optional): Milliseconds to wait for the response. If this timepasses, the then error callbacks are called.form (DOMNode, optional): DOM node for a form. Used to extract the form valuesand send to the server.preventCache (Boolean, optional): Default is false. If true, then a"dojo.preventCache" parameter is sent in the requestwith a value that changes with each request(timestamp). Useful only with GET-type requests.rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the contentproperty is ignored. This is mostly useful for HTTP methods that havea body to their requests, like PUT or POST. This property can be used insteadof postData and putData for dojo/_base/xhr.rawXhrPost and dojo/_base/xhr.rawXhrPut respectively.ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related toIO operations. Otherwise, if djConfig.ioPublish is set to true, topicswill be published via dojo/topic.publish() for different phases of an IO operation.See dojo/main.__IoPublish for a list of topics that are published. + */ + ioMethod(args: Object): any; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * + * @param params + * @param node + * @param ctor + */ + markupFactory(params: any, node: any, ctor: any): any; + /** + * + * @param type protected + * @param func + */ + on(type: String, func: Function): any; + /** + * + * @param type protected + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * + */ + postCreate(): void; + /** + * + */ + postMixInProperties(): void; + /** + * [Re]download contents of href and display + * cancels any currently in-flight requests + * posts "loading..." message + * sends XHR to download new data + * + */ + refresh(): any; + /** + * Removes the passed widget instance from this widget but does + * not destroy it. You can also pass in an integer indicating + * the index within the container to remove (ie, removeChild(5) removes the sixth widget). + * + * @param widget + */ + removeChild(widget: dijit._WidgetBase): void; + /** + * Removes the passed widget instance from this widget but does + * not destroy it. You can also pass in an integer indicating + * the index within the container to remove (ie, removeChild(5) removes the sixth widget). + * + * @param widget + */ + removeChild(widget: number): void; + /** + * See dijit/layout/_LayoutWidget.resize() for description. + * Although ContentPane doesn't extend _LayoutWidget, it does implement + * the same API. + * + * @param changeSize + * @param resultSize + */ + resize(changeSize: any, resultSize: any): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Deprecated. Use set() instead. + * + * @param attr + * @param value + */ + setAttribute(attr: String, value: any): void; + /** + * Deprecated. Use set('content', ...) instead. + * + * @param data + */ + setContent(data: String): void; + /** + * Deprecated. Use set('content', ...) instead. + * + * @param data + */ + setContent(data: HTMLElement): void; + /** + * Deprecated. Use set('content', ...) instead. + * + * @param data + */ + setContent(data: NodeList): void; + /** + * Deprecated. Use set('href', ...) instead. + * + * @param href + */ + setHref(href: String): any; + /** + * Deprecated. Use set('href', ...) instead. + * + * @param href + */ + setHref(href: URL): any; + /** + * Deprecated. Use set('title', ...) instead. + * + * @param title + */ + setTitle(title: String): void; + /** + * Call startup() on all children including non _Widget ones like dojo/dnd/Source objects + * + */ + startup(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Static method to get a template based on the templatePath or + * templateString key + */ + getCachedTemplate(): any; + /** + * Called when the widget stops being "active" because + * focus moved to something outside of it, or the user + * clicked somewhere outside of it, or the widget was + * hidden. + * + */ + onBlur(): void; + /** + * Connect to this function to receive notifications of mouse click events. + * + * @param event mouse Event + */ + onClick(event: any): void; + /** + * Called when this widget is being displayed as a popup (ex: a Calendar popped + * up from a DateTextBox), and it is hidden. + * This is called from the dijit.popup code, and should not be called directly. + * + * Also used as a parameter for children of dijit/layout/StackContainer or subclasses. + * Callback if a user tries to close the child. Child will be closed if this function returns true. + * + */ + onClose(): boolean; + /** + * Called on DOM faults, require faults etc. in content. + * + * In order to display an error message in the pane, return + * the error message from this method, as an HTML string. + * + * By default (if this method is not overriden), it returns + * nothing, so the error message is just printed to the console. + * + * @param error + */ + onContentError(error: Error): void; + /** + * Connect to this function to receive notifications of mouse double click events. + * + * @param event mouse Event + */ + onDblClick(event: any): void; + /** + * Called when download is finished. + * + */ + onDownloadEnd(): void; + /** + * Called when download error occurs. + * + * In order to display an error message in the pane, return + * the error message from this method, as an HTML string. + * + * Default behavior (if this method is not overriden) is to display + * the error message inside the pane. + * + * @param error + */ + onDownloadError(error: Error): any; + /** + * Called before download starts. + * The string returned by this function will be the html + * that tells the user we are loading something. + * Override with your own function if you want to change text. + * + */ + onDownloadStart(): any; + /** + * Called when the widget becomes "active" because + * it or a widget inside of it either has focus, or has recently + * been clicked. + * + */ + onFocus(): void; + /** + * Called when another widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate hide of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onHide(): void; + /** + * Connect to this function to receive notifications of keys being pressed down. + * + * @param event key Event + */ + onKeyDown(event: any): void; + /** + * Connect to this function to receive notifications of printable keys being typed. + * + * @param event key Event + */ + onKeyPress(event: any): void; + /** + * Connect to this function to receive notifications of keys being released. + * + * @param event key Event + */ + onKeyUp(event: any): void; + /** + * Event hook, is called after everything is loaded and widgetified + * + * @param data + */ + onLoad(data: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is pressed down. + * + * @param event mouse Event + */ + onMouseDown(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto this widget. + * + * @param event mouse Event + */ + onMouseEnter(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of this widget. + * + * @param event mouse Event + */ + onMouseLeave(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves over nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseMove(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOut(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOver(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is released. + * + * @param event mouse Event + */ + onMouseUp(event: any): void; + /** + * Called when this widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate display of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onShow(): void; + /** + * Event hook, is called before old content is cleared + * + */ + onUnload(): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/DropDownMenu.html + * + * A menu, without features for context menu (Meaning, drop down menu) + * + * @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties. + * @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified:use srcNodeRef.innerHTML as my contentsif this is a behavioral widget then apply behavior to that srcNodeRefotherwise, replace srcNodeRef with my generated DOM tree + */ + class DropDownMenu extends dijit._MenuBase implements dijit._OnDijitClickMixin { + constructor(params?: Object, srcNodeRef?: HTMLElement); + /** + * This Menu has been clicked (mouse or via space/arrow key) or opened as a submenu, + * so mere mouseover will open submenus. Focusing a menu via TAB does NOT automatically make it active + * since TAB is a navigation operation and not a selection one. + * For Windows apps, pressing the ALT key focuses the menubar menus (similar to TAB navigation) but the + * menu is not active (ie no dropdown) until an item is clicked. + * + */ + "activated": boolean; + set(property:"activated", value: boolean): void; + get(property:"activated"): boolean; + watch(property:"activated", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * True if mouse was pressed while over this widget, and hasn't been released yet + * + */ + "active": boolean; + set(property:"active", value: boolean): void; + get(property:"active"): boolean; + watch(property:"active", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Object to which attach points and events will be scoped. Defaults + * to 'this'. + * + */ + "attachScope": Object; + set(property:"attachScope", value: Object): void; + get(property:"attachScope"): Object; + watch(property:"attachScope", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute + * for each XXX attribute to be mapped to the DOM. + * + * attributeMap sets up a "binding" between attributes (aka properties) + * of the widget and the widget's DOM. + * Changes to widget attributes listed in attributeMap will be + * reflected into the DOM. + * + * For example, calling set('title', 'hello') + * on a TitlePane will automatically cause the TitlePane's DOM to update + * with the new title. + * + * attributeMap is a hash where the key is an attribute of the widget, + * and the value reflects a binding to a: + * + * DOM node attribute + * focus: {node: "focusNode", type: "attribute"} + * Maps this.focus to this.focusNode.focus + * + * DOM node innerHTML + * title: { node: "titleNode", type: "innerHTML" } + * Maps this.title to this.titleNode.innerHTML + * + * DOM node innerText + * title: { node: "titleNode", type: "innerText" } + * Maps this.title to this.titleNode.innerText + * + * DOM node CSS class + * myClass: { node: "domNode", type: "class" } + * Maps this.myClass to this.domNode.className + * + * If the value is an array, then each element in the array matches one of the + * formats of the above list. + * + * There are also some shorthands for backwards compatibility: + * + * string --> { node: string, type: "attribute" }, for example: + * "focusNode" ---> { node: "focusNode", type: "attribute" } + * "" --> { node: "domNode", type: "attribute" } + * + */ + "attributeMap": Object; + set(property:"attributeMap", value: Object): void; + get(property:"attributeMap"): Object; + watch(property:"attributeMap", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * A toggle to control whether or not a Menu gets focused when opened as a drop down from a MenuBar + * or DropDownButton/ComboButton. Note though that it always get focused when opened via the keyboard. + * + */ + "autoFocus": boolean; + set(property:"autoFocus", value: boolean): void; + get(property:"autoFocus"): boolean; + watch(property:"autoFocus", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * + */ + "baseClass": string; + set(property:"baseClass", value: string): void; + get(property:"baseClass"): string; + watch(property:"baseClass", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "class": string; + set(property:"class", value: string): void; + get(property:"class"): string; + watch(property:"class", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Designates where children of the source DOM node will be placed. + * "Children" in this case refers to both DOM nodes and widgets. + * For example, for myWidget: + * + *
+ * here's a plain DOM node + * and a widget + * and another plain DOM node + *
+ * containerNode would point to: + * + * here's a plain DOM node + * and a widget + * and another plain DOM node + * In templated widgets, "containerNode" is set via a + * data-dojo-attach-point assignment. + * + * containerNode must be defined for any widget that accepts innerHTML + * (like ContentPane or BorderContainer or even Button), and conversely + * is null for widgets that don't, like TextBox. + * + */ + "containerNode": HTMLElement; + set(property:"containerNode", value: HTMLElement): void; + get(property:"containerNode"): HTMLElement; + watch(property:"containerNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * Subclasses may define a cssStateNodes property that lists sub-nodes within the widget that + * need CSS classes applied on mouse hover/press and focus. + * + * Each entry in this optional hash is a an attach-point name (like "upArrowButton") mapped to a CSS class name + * (like "dijitUpArrowButton"). Example: + * + * { + * "upArrowButton": "dijitUpArrowButton", + * "downArrowButton": "dijitDownArrowButton" + * } + * The above will set the CSS class dijitUpArrowButton to the this.upArrowButton DOMNode when it + * + * is hovered, etc. + * + */ + "cssStateNodes": Object; + set(property:"cssStateNodes", value: Object): void; + get(property:"cssStateNodes"): Object; + watch(property:"cssStateNodes", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * Bi-directional support, as defined by the HTML DIR + * attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's + * default direction. + * + */ + "dir": string; + set(property:"dir", value: string): void; + get(property:"dir"): string; + watch(property:"dir", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * This is our visible representation of the widget! Other DOM + * Nodes may by assigned to other properties, usually through the + * template system's data-dojo-attach-point syntax, but the domNode + * property is the canonical "top level" node in widget UI. + * + */ + "domNode": HTMLElement; + set(property:"domNode", value: HTMLElement): void; + get(property:"domNode"): HTMLElement; + watch(property:"domNode", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * This widget or a widget it contains has focus, or is "active" because + * it was recently clicked. + * + */ + "focused": boolean; + set(property:"focused", value: boolean): void; + get(property:"focused"): boolean; + watch(property:"focused", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * The currently focused child widget, or null if there isn't one + * + */ + "focusedChild": Object; + set(property:"focusedChild", value: Object): void; + get(property:"focusedChild"): Object; + watch(property:"focusedChild", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * True if cursor is over this widget + * + */ + "hovering": boolean; + set(property:"hovering", value: boolean): void; + get(property:"hovering"): boolean; + watch(property:"hovering", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * A unique, opaque ID string that can be assigned by users or by the + * system. If the developer passes an ID which is known not to be + * unique, the specified ID is ignored and the system-generated ID is + * used instead. + * + */ + "id": string; + set(property:"id", value: string): void; + get(property:"id"): string; + watch(property:"id", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Rarely used. Overrides the default Dojo locale used to render this widget, + * as defined by the HTML LANG attribute. + * Value must be among the list of locales specified during by the Dojo bootstrap, + * formatted according to RFC 3066 (like en-us). + * + */ + "lang": string; + set(property:"lang", value: string): void; + get(property:"lang"): string; + watch(property:"lang", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * If multiple characters are typed where each keystroke happens within + * multiCharSearchDuration of the previous keystroke, + * search for nodes matching all the keystrokes. + * + * For example, typing "ab" will search for entries starting with + * "ab" unless the delay between "a" and "b" is greater than multiCharSearchDuration. + * + */ + "multiCharSearchDuration": number; + set(property:"multiCharSearchDuration", value: number): void; + get(property:"multiCharSearchDuration"): number; + watch(property:"multiCharSearchDuration", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} + /** + * The document this widget belongs to. If not specified to constructor, will default to + * srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global + * + */ + "ownerDocument": Object; + set(property:"ownerDocument", value: Object): void; + get(property:"ownerDocument"): Object; + watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * pointer to menu that displayed me + * + */ + "parentMenu": Object; + set(property:"parentMenu", value: Object): void; + get(property:"parentMenu"): Object; + watch(property:"parentMenu", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * For a passive (unclicked) Menu, number of milliseconds before hovering (without clicking) will cause + * the popup to open. Default is Infinity, meaning you need to click the menu to open it. + * + */ + "passivePopupDelay": number; + set(property:"passivePopupDelay", value: number): void; + get(property:"passivePopupDelay"): number; + watch(property:"passivePopupDelay", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} + /** + * After a menu has been activated (by clicking on it etc.), number of milliseconds before hovering + * (without clicking) another MenuItem causes that MenuItem's popup to automatically open. + * + */ + "popupDelay": number; + set(property:"popupDelay", value: number): void; + get(property:"popupDelay"): number; + watch(property:"popupDelay", callback:{(property?:string, oldValue?:number, newValue?: number):void}) :{unwatch():void} + /** + * + */ + "searchContainerNode": boolean; + set(property:"searchContainerNode", value: boolean): void; + get(property:"searchContainerNode"): boolean; + watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} + /** + * Currently selected (a.k.a. highlighted) MenuItem, or null if no MenuItem is selected. + * If a submenu is open, will be set to MenuItem that displayed the submenu. OTOH, if + * this Menu is in passive mode (i.e. hasn't been clicked yet), will be null, because + * "selected" is not merely "hovered". + * + */ + "selected": Object; + set(property:"selected", value: Object): void; + get(property:"selected"): Object; + watch(property:"selected", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} + /** + * pointer to original DOM node + * + */ + "srcNodeRef": HTMLElement; + set(property:"srcNodeRef", value: HTMLElement): void; + get(property:"srcNodeRef"): HTMLElement; + watch(property:"srcNodeRef", callback:{(property?:string, oldValue?:HTMLElement, newValue?: HTMLElement):void}) :{unwatch():void} + /** + * HTML style attributes as cssText string or name/value hash + * + */ + "style": string; + set(property:"style", value: string): void; + get(property:"style"): string; + watch(property:"style", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Tab index of the container; same as HTML tabIndex attribute. + * Note then when user tabs into the container, focus is immediately + * moved to the first item in the container. + * + */ + "tabIndex": string; + set(property:"tabIndex", value: string): void; + get(property:"tabIndex"): string; + watch(property:"tabIndex", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * Path to template (HTML file) for this widget relative to dojo.baseUrl. + * Deprecated: use templateString with require([... "dojo/text!..."], ...) instead + * + */ + "templatePath": string; + set(property:"templatePath", value: string): void; + get(property:"templatePath"): string; + watch(property:"templatePath", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + */ + "templateString": string; + set(property:"templateString", value: string): void; + get(property:"templateString"): string; + watch(property:"templateString", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * HTML title attribute. + * + * For form widgets this specifies a tooltip to display when hovering over + * the widget (just like the native HTML title attribute). + * + * For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer, + * etc., it's used to specify the tab label, accordion pane title, etc. In this case it's + * interpreted as HTML. + * + */ + "title": string; + set(property:"title", value: string): void; + get(property:"title"): string; + watch(property:"title", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * When this widget's title attribute is used to for a tab label, accordion pane title, etc., + * this specifies the tooltip to appear when the mouse is hovered over that text. + * + */ + "tooltip": string; + set(property:"tooltip", value: string): void; + get(property:"tooltip"): string; + watch(property:"tooltip", callback:{(property?:string, oldValue?:string, newValue?: string):void}) :{unwatch():void} + /** + * + * @param widget + * @param insertIndex Optional + */ + addChild(widget: dijit._WidgetBase, insertIndex: number): void; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: String, value: Object): any; + /** + * This method is deprecated, use get() or set() directly. + * + * @param name The property to get or set. If an object is passed here and nota string, its keys are used as names of attributes to be setand the value of the object as values to set in the widget. + * @param value OptionalOptional. If provided, attr() operates as a setter. If omitted,the current value of the named property is returned. + */ + attr(name: Object, value: Object): any; + /** + * Construct the UI for this widget, setting this.domNode. + * Most widgets will mixin dijit._TemplatedMixin, which implements this method. + * + */ + buildRendering(): void; + /** + * Selector (passed to on.selector()) used to identify MenuItem child widgets, but exclude inert children + * like MenuSeparator. If subclass overrides to a string (ex: "> *"), the subclass must require dojo/query. + * + * @param node + */ + childSelector(node: HTMLElement): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: String): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: String, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: Object, event: Function, method: Function): any; + /** + * Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead. + * + * Connects specified obj/event to specified method of this object + * and registers for disconnect() on widget destroy. + * + * Provide widget-specific analog to dojo.connect, except with the + * implicit use of this widget as the target object. + * Events connected with this.connect are disconnected upon + * destruction. + * + * @param obj + * @param event + * @param method + */ + connect(obj: any, event: Function, method: Function): any; + /** + * Deprecated. You can call this in postCreate() to attach the keyboard handlers to the container, + * but the preferred method is to override _onLeftArrow() and _onRightArrow(), or + * _onUpArrow() and _onDownArrow(), to call focusPrev() and focusNext(). + * + * @param prevKeyCodes Key codes for navigating to the previous child. + * @param nextKeyCodes Key codes for navigating to the next child. + */ + connectKeyNavHandlers(prevKeyCodes: dojo.keys, nextKeyCodes: dojo.keys): void; + /** + * Wrapper to setTimeout to avoid deferred functions executing + * after the originating widget has been destroyed. + * Returns an object handle with a remove method (that returns null) (replaces clearTimeout). + * + * @param fcn Function reference. + * @param delay OptionalDelay, defaults to 0. + */ + defer(fcn: Function, delay: number): Object; + /** + * Destroy this widget, but not its descendants. Descendants means widgets inside of + * this.containerNode. Will also destroy any resources (including widgets) registered via this.own(). + * + * This method will also destroy internal widgets such as those created from a template, + * assuming those widgets exist inside of this.domNode but outside of this.containerNode. + * + * For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not + * depend on the current ability to destroy a widget without destroying its descendants. Generally + * they should use destroyRecursive() for widgets with children. + * + * @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets + */ + destroy(preserveDom?: boolean): void; + /** + * Recursively destroy the children of this widget and their + * descendants. + * + * @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets. + */ + destroyDescendants(preserveDom?: boolean): void; + /** + * Destroy this widget and its descendants + * This is the generic "destructor" function that all widget users + * should call to cleanly discard with a widget. Once a widget is + * destroyed, it is removed from the manager object. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets. + */ + destroyRecursive(preserveDom?: boolean): void; + /** + * Destroys the DOM nodes associated with this widget. + * + * @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet. + */ + destroyRendering(preserveDom?: boolean): void; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Disconnects handle created by connect. + * + * @param handle + */ + disconnect(handle: any): void; + /** + * Used by widgets to signal that a synthetic event occurred, ex: + * + * myWidget.emit("attrmodified-selectedChildWidget", {}). + * Emits an event on this.domNode named type.toLowerCase(), based on eventObj. + * Also calls onType() method, if present, and returns value from that method. + * By default passes eventObj to callback, but will pass callbackArgs instead, if specified. + * Modifies eventObj by adding missing parameters (bubbles, cancelable, widget). + * + * @param type + * @param eventObj Optional + * @param callbackArgs Optional + */ + emit(type: String, eventObj: Object, callbackArgs: any[]): any; + /** + * Default focus() implementation: focus the first child. + * + */ + focus(): void; + /** + * Focus specified child widget. + * + * @param widget Reference to container's child widget + * @param last If true and if widget has multiple focusable nodes, focus thelast one instead of the first one + */ + focusChild(widget: dijit._WidgetBase, last: boolean): void; + /** + * Focus the first focusable child in the container. + * + */ + focusFirstChild(): void; + /** + * Focus the last focusable child in the container. + * + */ + focusLastChild(): void; + /** + * Focus the next widget + * + */ + focusNext(): void; + /** + * Focus the last focusable node in the previous widget + * (ex: go to the ComboButton icon section rather than button section) + * + */ + focusPrev(): void; + /** + * Get a property from a widget. + * Get a named property from a widget. The property may + * potentially be retrieved via a getter method. If no getter is defined, this + * just retrieves the object's property. + * + * For example, if the widget has properties foo and bar + * and a method named _getFooAttr(), calling: + * myWidget.get("foo") would be equivalent to calling + * widget._getFooAttr() and myWidget.get("bar") + * would be equivalent to the expression + * widget.bar2 + * + * @param name The property to get. + */ + get(name: any): any; + /** + * Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent + * is this widget. Note that it does not return all descendants, but rather just direct children. + * Analogous to Node.childNodes, + * except containing widgets rather than DOMNodes. + * + * The result intentionally excludes internally created widgets (a.k.a. supporting widgets) + * outside of this.containerNode. + * + * Note that the array returned is a simple array. Application code should not assume + * existence of methods like forEach(). + * + */ + getChildren(): any[]; + /** + * Returns all the widgets contained by this, i.e., all widgets underneath this.containerNode. + * This method should generally be avoided as it returns widgets declared in templates, which are + * supposed to be internal/hidden, but it's left here for back-compat reasons. + * + */ + getDescendants(): any[]; + /** + * Gets the index of the child in this container or -1 if not found + * + * @param child + */ + getIndexOfChild(child: dijit._WidgetBase): any; + /** + * Returns the parent widget of this widget. + * + */ + getParent(): any; + /** + * Returns true if widget has child widgets, i.e. if this.containerNode contains widgets. + * + */ + hasChildren(): boolean; + /** + * Return true if this widget can currently be focused + * and false if not + * + */ + isFocusable(): any; + /** + * Return this widget's explicit or implicit orientation (true for LTR, false for RTL) + * + */ + isLeftToRight(): any; + /** + * + * @param type protected + * @param func + */ + on(type: String, func: Function): any; + /** + * + * @param type protected + * @param func + */ + on(type: Function, func: Function): any; + /** + * Track specified handles and remove/destroy them when this instance is destroyed, unless they were + * already removed/destroyed manually. + * + */ + own(): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: String): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: String, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: HTMLElement, position: number): any; + /** + * Place this widget somewhere in the DOM based + * on standard domConstruct.place() conventions. + * A convenience function provided in all _Widgets, providing a simple + * shorthand mechanism to put an existing (or newly created) Widget + * somewhere in the dom, and allow chaining. + * + * @param reference Widget, DOMNode, or id of widget or DOMNode + * @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place(). + */ + placeAt(reference: dijit._WidgetBase, position: number): any; + /** + * + */ + postCreate(): void; + /** + * Called after the parameters to the widget have been read-in, + * but before the widget template is instantiated. Especially + * useful to set properties that are referenced in the widget + * template. + * + */ + postMixInProperties(): void; + /** + * Removes the passed widget instance from this widget but does + * not destroy it. You can also pass in an integer indicating + * the index within the container to remove (ie, removeChild(5) removes the sixth widget). + * + * @param widget + */ + removeChild(widget: dijit._WidgetBase): void; + /** + * Removes the passed widget instance from this widget but does + * not destroy it. You can also pass in an integer indicating + * the index within the container to remove (ie, removeChild(5) removes the sixth widget). + * + * @param widget + */ + removeChild(widget: number): void; + /** + * Set a property on a widget + * Sets named properties on a widget which may potentially be handled by a + * setter in the widget. + * + * For example, if the widget has properties foo and bar + * and a method named _setFooAttr(), calling + * myWidget.set("foo", "Howdy!") would be equivalent to calling + * widget._setFooAttr("Howdy!") and myWidget.set("bar", 3) + * would be equivalent to the statement widget.bar = 3; + * + * set() may also be called with a hash of name/value pairs, ex: + * + * myWidget.set({ + * foo: "Howdy", + * bar: 3 + * }); + * This is equivalent to calling set(foo, "Howdy") and set(bar, 3) + * + * @param name The property to set. + * @param value The value to set in the property. + */ + set(name: any, value: any): any; + /** + * Deprecated. Use set() instead. + * + * @param attr + * @param value + */ + setAttribute(attr: String, value: any): void; + /** + * Processing after the DOM fragment is added to the document + * Called after a widget and its children have been created and added to the page, + * and all related widgets have finished their create() cycle, up through postCreate(). + * + * Note that startup() may be called while the widget is still hidden, for example if the widget is + * inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer. + * For widgets that need to do layout, it's best to put that layout code inside resize(), and then + * extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible. + * + */ + startup(): void; + /** + * + */ + startupKeyNavChildren(): void; + /** + * Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead. + * + * Subscribes to the specified topic and calls the specified method + * of this object and registers for unsubscribe() on widget destroy. + * + * Provide widget-specific analog to dojo.subscribe, except with the + * implicit use of this widget as the target object. + * + * @param t The topic + * @param method The callback + */ + subscribe(t: String, method: Function): any; + /** + * Returns a string that represents the widget. + * When a widget is cast to a string, this method will be used to generate the + * output. Currently, it does not implement any sort of reversible + * serialization. + * + */ + toString(): String; + /** + * Deprecated. Override destroy() instead to implement custom widget tear-down + * behavior. + * + */ + uninitialize(): boolean; + /** + * Deprecated, will be removed in 2.0, use handle.remove() instead. + * + * Unsubscribes handle created by this.subscribe. + * Also removes handle from this widget's list of subscriptions + * + * @param handle + */ + unsubscribe(handle: Object): void; + /** + * Watches a property for changes + * + * @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched + * @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value. + */ + watch(property: string, callback:{(property?:string, oldValue?:any, newValue?: any):void}) :{unwatch():void}; + /** + * Static method to get a template based on the templatePath or + * templateString key + */ + getCachedTemplate(): any; + /** + * Called when the widget stops being "active" because + * focus moved to something outside of it, or the user + * clicked somewhere outside of it, or the widget was + * hidden. + * + */ + onBlur(): void; + /** + * Attach point for notification about when the user cancels the current menu + * This is an internal mechanism used for Menus to signal to their parent to + * close them. In general developers should not attach to or override this method. + * + * @param closeAll + */ + onCancel(closeAll: boolean): void; + /** + * Connect to this function to receive notifications of mouse click events. + * + * @param event mouse Event + */ + onClick(event: any): void; + /** + * Connect to this function to receive notifications of mouse double click events. + * + * @param event mouse Event + */ + onDblClick(event: any): void; + /** + * Attach point for notification about when a menu item has been executed. + * This is an internal mechanism used for Menus to signal to their parent to + * close them, because they are about to execute the onClick handler. In + * general developers should not attach to or override this method. + * + */ + onExecute(): void; + /** + * Called when the widget becomes "active" because + * it or a widget inside of it either has focus, or has recently + * been clicked. + * + */ + onFocus(): void; + /** + * Called when another widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate hide of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onHide(): void; + /** + * Called when cursor is over a MenuItem. + * + * @param item + */ + onItemHover(item: dijit.MenuItem): void; + /** + * Callback fires when mouse exits a MenuItem + * + * @param item + */ + onItemUnhover(item: dijit.MenuItem): void; + /** + * Attach point for notification about when a menu item has been searched for + * via the keyboard search mechanism. + * + * @param item + * @param evt + * @param searchString + * @param numMatches + */ + onKeyboardSearch(item: dijit.MenuItem, evt: Event, searchString: String, numMatches: number): void; + /** + * Connect to this function to receive notifications of keys being pressed down. + * + * @param event key Event + */ + onKeyDown(event: any): void; + /** + * Connect to this function to receive notifications of printable keys being typed. + * + * @param event key Event + */ + onKeyPress(event: any): void; + /** + * Connect to this function to receive notifications of keys being released. + * + * @param event key Event + */ + onKeyUp(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is pressed down. + * + * @param event mouse Event + */ + onMouseDown(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto this widget. + * + * @param event mouse Event + */ + onMouseEnter(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of this widget. + * + * @param event mouse Event + */ + onMouseLeave(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves over nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseMove(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves off of nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOut(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse moves onto nodes contained within this widget. + * + * @param event mouse Event + */ + onMouseOver(event: any): void; + /** + * Connect to this function to receive notifications of when the mouse button is released. + * + * @param event mouse Event + */ + onMouseUp(event: any): void; + /** + * Called when this widget becomes the selected pane in a + * dijit/layout/TabContainer, dijit/layout/StackContainer, + * dijit/layout/AccordionContainer, etc. + * + * Also called to indicate display of a dijit.Dialog, dijit.TooltipDialog, or dijit.TitlePane. + * + */ + onShow(): void; + } + /** + * Permalink: http://dojotoolkit.org/api/1.9/dijit/Editor.html + * + * A rich text Editing widget + * This widget provides basic WYSIWYG editing features, based on the browser's + * underlying rich text editing capability, accompanied by a toolbar (dijit.Toolbar). + * A plugin model is available to extend the editor's capabilities as well as the + * the options available in the toolbar. Content generation may vary across + * browsers, and clipboard operations may have different results, to name + * a few limitations. Note: this widget should not be used with the HTML + * ').val(content)); + } + } +}); \ No newline at end of file diff --git a/jdataview/jdataview.d.ts b/jdataview/jdataview.d.ts new file mode 100644 index 0000000000..cff1160326 --- /dev/null +++ b/jdataview/jdataview.d.ts @@ -0,0 +1,105 @@ +// Type definitions for jDataView +// Project: https://github.com/jDataView/jDataView +// Definitions by: Ingvar Stepanyan +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare class jDataView implements DataView { + constructor(byteCount: number, offset?: number, length?: number, littleEndian?: boolean) + constructor(buffer: string, offset?: number, length?: number, littleEndian?: boolean) + constructor(buffer: jDataView.Bytes, offset?: number, length?: number, littleEndian?: boolean) + buffer: any + byteOffset: number + byteLength: number + + // 64 bit integers + getInt64(byteOffset?: number, littleEndian?: boolean): jDataView.Int64 + setInt64(byteOffset: number, value: jDataView.Int64, littleEndian?: boolean): void + writeInt64(value: jDataView.Int64, littleEndian?: boolean): void + getUint64(byteOffset?: number, littleEndian?: boolean): jDataView.Uint64 + setUint64(byteOffset: number, value: jDataView.Uint64, littleEndian?: boolean): void + writeUint64(value: jDataView.Uint64, littleEndian?: boolean): void + + // Bitfields + getSigned(bitLength: number, byteOffset?: number): number + setSigned(byteOffset: number, value: number, bitLength: number): void + writeSigned(value: number, bitLength: number): void + getUnsigned(bitLength: number, byteOffset?: number): number + setUnsigned(byteOffset: number, value: number, bitLength: number): void + writeUnsigned(value: number, bitLength: number): void + + // Internal utilities + wrapBuffer(string: string): jDataView.Buffer + wrapBuffer(bytes: jDataView.Bytes): jDataView.Buffer + wrapBuffer(byteCount: number): jDataView.Buffer + createBuffer(...bytes: number[]): jDataView.Buffer + + // Operation control + seek(byteOffset: number): number + tell(): number + skip(byteLength: number): number + slice(start: number, end?: number, forceCopy?: boolean): jDataView + + // Specification getters + getInt8(byteOffset?: number): number + getUint8(byteOffset?: number): number + getInt16(byteOffset?: number, littleEndian?: boolean): number + getUint16(byteOffset?: number, littleEndian?: boolean): number + getInt32(byteOffset?: number, littleEndian?: boolean): number + getUint32(byteOffset?: number, littleEndian?: boolean): number + getFloat32(byteOffset?: number, littleEndian?: boolean): number + getFloat64(byteOffset?: number, littleEndian?: boolean): number + + // Specification setters + setInt8(byteOffset: number, value: number): void + setUint8(byteOffset: number, value: number): void + setInt16(byteOffset: number, value: number, littleEndian?: boolean): void + setUint16(byteOffset: number, value: number, littleEndian?: boolean): void + setInt32(byteOffset: number, value: number, littleEndian?: boolean): void + setUint32(byteOffset: number, value: number, littleEndian?: boolean): void + setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void + setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void + + // Strings and Blobs + getChar(byteOffset?: number): string + setChar(byteOffset: number, char: string): void + writeChar(char: string): void + getString(byteLength: number, byteOffset?: number, encoding?: string): string + setString(byteOffset: number, chars: string, encoding?: string): void + writeString(chars: string, encoding?: string): void + getBytes(length: number, byteOffset?: number, littleEndian?: boolean, toArray?: boolean): number[] + setBytes(byteOffset: number, bytes: number[], littleEndian?: boolean): void + writeBytes(bytes: number[], littleEndian?: boolean): void + + // writeXXX methods + writeInt8(value: number): void + writeUint8(value: number): void + writeInt16(value: number, littleEndian?: boolean): void + writeUint16(value: number, littleEndian?: boolean): void + writeInt32(value: number, littleEndian?: boolean): void + writeUint32(value: number, littleEndian?: boolean): void + writeFloat32(value: number, littleEndian?: boolean): void + writeFloat64(value: number, littleEndian?: boolean): void +} + +declare module jDataView { + interface Bytes { + length: number; + [index: number]: number; + } + + interface Buffer extends Bytes { + byteLength: number; + } + + class Uint64 { + lo: number + hi: number + constructor(lo: number, hi: number) + valueOf(): number + static fromNumber(number: number): Uint64 + } + + class Int64 extends Uint64 { + static fromNumber(number: number): Int64 + } +} \ No newline at end of file diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts new file mode 100644 index 0000000000..26048a9dc7 --- /dev/null +++ b/joi/joi-tests.ts @@ -0,0 +1,571 @@ +/// +/// + +import Joi = require('joi'); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var x: any = null; +var value: any = null; +var num: number = 0; +var str: string = ''; +var bool: boolean = false; +var exp: RegExp = null; +var obj: Object = null; +var date: Date = null; +var bin: NodeBuffer = null; +var err: Error = null; +var func: Function = null; + +var anyArr: any[] = []; +var numArr: number[] = []; +var strArr: string[] = []; +var boolArr: boolean[] = []; +var expArr: RegExp[] = []; +var objArr: Object[] = []; +var bufArr: NodeBuffer[] = []; +var errArr: Error[] = []; +var funcArr: Function[] = []; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var schema: Joi.Schema = null; + +var anySchema: Joi.AnySchema = null; +var numSchema: Joi.NumberSchema = null; +var strSchema: Joi.StringSchema = null; +var arrSchema: Joi.ArraySchema = null; +var boolSchema: Joi.BooleanSchema = null; +var binSchema: Joi.BinarySchema = null; +var dateSchema: Joi.DateSchema = null; +var funcSchema: Joi.FunctionSchema = null; +var objSchema: Joi.ObjectSchema = null; +var altSchema: Joi.AlternativesSchema = null; + +var schemaArr: Joi.Schema[] = []; + +var ref: Joi.Reference = null; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var validOpts: Joi.ValidationOptions = null; + +validOpts = {abortEarly: bool}; +validOpts = {convert: bool}; +validOpts = {allowUnknown: bool}; +validOpts = {skipFunctions: bool}; +validOpts = {stripUnknown: bool}; +validOpts = {language: bool}; +validOpts = {context: obj}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var renOpts: Joi.RenameOptions = null; + +renOpts = {alias: bool}; +renOpts = {multiple: bool}; +renOpts = {override: bool}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var whenOpts: Joi.WhenOptions = null; + +whenOpts = {is: schema}; +whenOpts = {is: schema, then: schema}; +whenOpts = {is: schema, otherwise: schema}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var refOpts: Joi.ReferenceOptions = null; + +refOpts = {alias: bool}; +refOpts = {multiple: bool}; +refOpts = {override: bool}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var validErr: Joi.ValidationError = null; +var validErrItem: Joi.ValidationErrorItem; + +validErrItem= { + message: str, + type: str, + path: str +}; + +validErrItem = { + message: str, + type: str, + path: str, + options: validOpts +}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = anySchema; +schema = numSchema; +schema = strSchema; +schema = arrSchema; +schema = boolSchema; +schema = binSchema; +schema = dateSchema; +schema = funcSchema; +schema = objSchema; + +schema = ref; + +anySchema = anySchema; +anySchema = numSchema; +anySchema = strSchema; +anySchema = arrSchema; +anySchema = boolSchema; +anySchema = binSchema; +anySchema = dateSchema; +anySchema = funcSchema; +anySchema = objSchema; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var schemaMap: Joi.SchemaMap = null; + +schemaMap = { + a: numSchema, + b: strSchema +}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +anySchema = Joi.any(); + +module common { + anySchema = anySchema.allow(x); + anySchema = anySchema.allow(x, x); + anySchema = anySchema.allow([x, x, x]); + anySchema = anySchema.valid(x); + anySchema = anySchema.valid(x, x); + anySchema = anySchema.valid([x, x, x]); + anySchema = anySchema.invalid(x); + anySchema = anySchema.invalid(x, x); + anySchema = anySchema.invalid([x, x, x]); + + anySchema = anySchema.default(x); + + anySchema = anySchema.required(); + anySchema = anySchema.optional(); + anySchema = anySchema.forbidden(); + + anySchema = anySchema.description(str); + anySchema = anySchema.notes(str); + anySchema = anySchema.notes(strArr); + anySchema = anySchema.tags(str); + anySchema = anySchema.tags(strArr); + + anySchema = anySchema.meta(obj); + anySchema = anySchema.example(obj); + anySchema = anySchema.unit(str); + + anySchema = anySchema.options(validOpts); + anySchema = anySchema.strict(); + anySchema = anySchema.concat(x); + + altSchema = anySchema.when(str, whenOpts); + altSchema = anySchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +arrSchema = Joi.array(); + +arrSchema = arrSchema.min(num); +arrSchema = arrSchema.max(num); +arrSchema = arrSchema.length(num); + +arrSchema = arrSchema.includes(numSchema); +arrSchema = arrSchema.includes(numSchema, strSchema); +arrSchema = arrSchema.includes([numSchema, strSchema]); + +arrSchema = arrSchema.excludes(numSchema); +arrSchema = arrSchema.excludes(numSchema, strSchema); +arrSchema = arrSchema.excludes([numSchema, strSchema]); + +// - - - - - - - - + +module common_copy_paste { + // use search & replace from any + anySchema = anySchema.allow(x); + anySchema = anySchema.allow(x, x); + anySchema = anySchema.allow([x, x, x]); + anySchema = anySchema.valid(x); + anySchema = anySchema.valid(x, x); + anySchema = anySchema.valid([x, x, x]); + anySchema = anySchema.invalid(x); + anySchema = anySchema.invalid(x, x); + anySchema = anySchema.invalid([x, x, x]); + + anySchema = anySchema.default(x); + + arrSchema = arrSchema.required(); + arrSchema = arrSchema.optional(); + arrSchema = arrSchema.forbidden(); + + arrSchema = arrSchema.description(str); + arrSchema = arrSchema.notes(str); + arrSchema = arrSchema.notes(strArr); + arrSchema = arrSchema.tags(str); + arrSchema = arrSchema.tags(strArr); + + arrSchema = arrSchema.meta(obj); + arrSchema = arrSchema.example(obj); + arrSchema = arrSchema.unit(str); + + arrSchema = arrSchema.options(validOpts); + arrSchema = arrSchema.strict(); + arrSchema = arrSchema.concat(x); + + altSchema = arrSchema.when(str, whenOpts); + altSchema = arrSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +boolSchema = Joi.bool(); +boolSchema = Joi.boolean(); + +module common_copy_paste { + boolSchema = boolSchema.allow(x); + boolSchema = boolSchema.allow(x, x); + boolSchema = boolSchema.allow([x, x, x]); + boolSchema = boolSchema.valid(x); + boolSchema = boolSchema.valid(x, x); + boolSchema = boolSchema.valid([x, x, x]); + boolSchema = boolSchema.invalid(x); + boolSchema = boolSchema.invalid(x, x); + boolSchema = boolSchema.invalid([x, x, x]); + + boolSchema = boolSchema.default(x); + + boolSchema = boolSchema.required(); + boolSchema = boolSchema.optional(); + boolSchema = boolSchema.forbidden(); + + boolSchema = boolSchema.description(str); + boolSchema = boolSchema.notes(str); + boolSchema = boolSchema.notes(strArr); + boolSchema = boolSchema.tags(str); + boolSchema = boolSchema.tags(strArr); + + boolSchema = boolSchema.meta(obj); + boolSchema = boolSchema.example(obj); + boolSchema = boolSchema.unit(str); + + boolSchema = boolSchema.options(validOpts); + boolSchema = boolSchema.strict(); + boolSchema = boolSchema.concat(x); + + altSchema = boolSchema.when(str, whenOpts); + altSchema = boolSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +binSchema = Joi.binary(); + +binSchema = binSchema.min(num); +binSchema = binSchema.max(num); +binSchema = binSchema.length(num); + +module common { + binSchema = binSchema.allow(x); + binSchema = binSchema.allow(x, x); + binSchema = binSchema.allow([x, x, x]); + binSchema = binSchema.valid(x); + binSchema = binSchema.valid(x, x); + binSchema = binSchema.valid([x, x, x]); + binSchema = binSchema.invalid(x); + binSchema = binSchema.invalid(x, x); + binSchema = binSchema.invalid([x, x, x]); + + binSchema = binSchema.default(x); + + binSchema = binSchema.required(); + binSchema = binSchema.optional(); + binSchema = binSchema.forbidden(); + + binSchema = binSchema.description(str); + binSchema = binSchema.notes(str); + binSchema = binSchema.notes(strArr); + binSchema = binSchema.tags(str); + binSchema = binSchema.tags(strArr); + + binSchema = binSchema.meta(obj); + binSchema = binSchema.example(obj); + binSchema = binSchema.unit(str); + + binSchema = binSchema.options(validOpts); + binSchema = binSchema.strict(); + binSchema = binSchema.concat(x); + + altSchema = binSchema.when(str, whenOpts); + altSchema = binSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +dateSchema = Joi.date(); + +dateSchema = dateSchema.min(date); +dateSchema = dateSchema.max(date); + +dateSchema = dateSchema.min(str); +dateSchema = dateSchema.max(str); + +dateSchema = dateSchema.min(num); +dateSchema = dateSchema.max(num); + +module common { + dateSchema = dateSchema.allow(x); + dateSchema = dateSchema.allow(x, x); + dateSchema = dateSchema.allow([x, x, x]); + dateSchema = dateSchema.valid(x); + dateSchema = dateSchema.valid(x, x); + dateSchema = dateSchema.valid([x, x, x]); + dateSchema = dateSchema.invalid(x); + dateSchema = dateSchema.invalid(x, x); + dateSchema = dateSchema.invalid([x, x, x]); + + dateSchema = dateSchema.default(x); + + dateSchema = dateSchema.required(); + dateSchema = dateSchema.optional(); + dateSchema = dateSchema.forbidden(); + + dateSchema = dateSchema.description(str); + dateSchema = dateSchema.notes(str); + dateSchema = dateSchema.notes(strArr); + dateSchema = dateSchema.tags(str); + dateSchema = dateSchema.tags(strArr); + + dateSchema = dateSchema.meta(obj); + dateSchema = dateSchema.example(obj); + dateSchema = dateSchema.unit(str); + + dateSchema = dateSchema.options(validOpts); + dateSchema = dateSchema.strict(); + dateSchema = dateSchema.concat(x); + + altSchema = dateSchema.when(str, whenOpts); + altSchema = dateSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +funcSchema = Joi.func(); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +numSchema = Joi.number(); + +numSchema = numSchema.min(num); +numSchema = numSchema.max(num); +numSchema = numSchema.integer(); + +module common { + numSchema = numSchema.allow(x); + numSchema = numSchema.allow(x, x); + numSchema = numSchema.allow([x, x, x]); + numSchema = numSchema.valid(x); + numSchema = numSchema.valid(x, x); + numSchema = numSchema.valid([x, x, x]); + numSchema = numSchema.invalid(x); + numSchema = numSchema.invalid(x, x); + numSchema = numSchema.invalid([x, x, x]); + + numSchema = numSchema.default(x); + + numSchema = numSchema.required(); + numSchema = numSchema.optional(); + numSchema = numSchema.forbidden(); + + numSchema = numSchema.description(str); + numSchema = numSchema.notes(str); + numSchema = numSchema.notes(strArr); + numSchema = numSchema.tags(str); + numSchema = numSchema.tags(strArr); + + numSchema = numSchema.meta(obj); + numSchema = numSchema.example(obj); + numSchema = numSchema.unit(str); + + numSchema = numSchema.options(validOpts); + numSchema = numSchema.strict(); + numSchema = numSchema.concat(x); + + altSchema = numSchema.when(str, whenOpts); + altSchema = numSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +objSchema = Joi.object(); +objSchema = Joi.object(schemaMap); + +objSchema = objSchema.keys(); +objSchema = objSchema.keys(schemaMap); + +objSchema = objSchema.min(num); +objSchema = objSchema.max(num); +objSchema = objSchema.length(num); + +objSchema = objSchema.pattern(exp, schema); + +objSchema = objSchema.and(str, str, str); +objSchema = objSchema.and(strArr); + +objSchema = objSchema.or(str, str, str); +objSchema = objSchema.or(strArr); + +objSchema = objSchema.xor(str, str, str); +objSchema = objSchema.xor(strArr); + +objSchema = objSchema.with(str, str); +objSchema = objSchema.with(str, strArr); + +objSchema = objSchema.without(str, str); +objSchema = objSchema.without(str, strArr); + +objSchema = objSchema.rename(str, str); +objSchema = objSchema.rename(str, str, renOpts); + +objSchema = objSchema.assert(str, schema, str); +objSchema = objSchema.assert(ref, schema, str); + +objSchema = objSchema.unknown(); +objSchema = objSchema.unknown(bool); + +module common { + objSchema = objSchema.allow(x); + objSchema = objSchema.allow(x, x); + objSchema = objSchema.allow([x, x, x]); + objSchema = objSchema.valid(x); + objSchema = objSchema.valid(x, x); + objSchema = objSchema.valid([x, x, x]); + objSchema = objSchema.invalid(x); + objSchema = objSchema.invalid(x, x); + objSchema = objSchema.invalid([x, x, x]); + + objSchema = objSchema.default(x); + + objSchema = objSchema.required(); + objSchema = objSchema.optional(); + objSchema = objSchema.forbidden(); + + objSchema = objSchema.description(str); + objSchema = objSchema.notes(str); + objSchema = objSchema.notes(strArr); + objSchema = objSchema.tags(str); + objSchema = objSchema.tags(strArr); + + objSchema = objSchema.meta(obj); + objSchema = objSchema.example(obj); + objSchema = objSchema.unit(str); + + objSchema = objSchema.options(validOpts); + objSchema = objSchema.strict(); + objSchema = objSchema.concat(x); + + altSchema = objSchema.when(str, whenOpts); + altSchema = objSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +strSchema = Joi.string(); + +strSchema = strSchema.insensitive(); +strSchema = strSchema.min(num); +strSchema = strSchema.max(num); +strSchema = strSchema.length(num); +strSchema = strSchema.regex(exp); +strSchema = strSchema.alphanum(); +strSchema = strSchema.token(); +strSchema = strSchema.email(); +strSchema = strSchema.guid(); +strSchema = strSchema.isoDate(); +strSchema = strSchema.lowercase(); +strSchema = strSchema.uppercase(); +strSchema = strSchema.trim(); + +module common { + strSchema = strSchema.allow(x); + strSchema = strSchema.allow(x, x); + strSchema = strSchema.allow([x, x, x]); + strSchema = strSchema.valid(x); + strSchema = strSchema.valid(x, x); + strSchema = strSchema.valid([x, x, x]); + strSchema = strSchema.invalid(x); + strSchema = strSchema.invalid(x, x); + strSchema = strSchema.invalid([x, x, x]); + + strSchema = strSchema.default(x); + + strSchema = strSchema.required(); + strSchema = strSchema.optional(); + strSchema = strSchema.forbidden(); + + strSchema = strSchema.description(str); + strSchema = strSchema.notes(str); + strSchema = strSchema.notes(strArr); + strSchema = strSchema.tags(str); + strSchema = strSchema.tags(strArr); + + strSchema = strSchema.meta(obj); + strSchema = strSchema.example(obj); + strSchema = strSchema.unit(str); + + strSchema = strSchema.options(validOpts); + strSchema = strSchema.strict(); + strSchema = strSchema.concat(x); + + altSchema = strSchema.when(str, whenOpts); + altSchema = strSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.alternatives(schemaArr); +schema = Joi.alternatives(schema, anySchema, boolSchema); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +Joi.validate(value, schema); +Joi.validate(value, schema, validOpts); +Joi.validate(value, schema, validOpts, (err, value) => { + x = value; + str = err.message; + str = err.details[0].path; + str = err.details[0].message; + str = err.details[0].type; +}); +Joi.validate(value, schema, (err, value) => { + x = value; + str = err.message; + str = err.details[0].path; + str = err.details[0].message; + str = err.details[0].type; +}); +// variant +Joi.validate(num, schema, validOpts, (err, value) => { + num = value; +}); + +// plain opts +Joi.validate(value, {}); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.compile(obj); + +Joi.assert(obj, schema); + +ref = Joi.ref(str, refOpts); +ref = Joi.ref(str); diff --git a/joi/joi.d.ts b/joi/joi.d.ts new file mode 100644 index 0000000000..57e48a023b --- /dev/null +++ b/joi/joi.d.ts @@ -0,0 +1,481 @@ +// Type definitions for joi v4.6.0 +// Project: https://github.com/spumko/joi +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// TODO express type of Schema in a type-parameter (.default, .valid, .example etc) + +declare module 'joi' { + + export interface ValidationOptions { + // when true, stops validation on the first error, otherwise returns all the errors found. Defaults to true. + abortEarly?: boolean; + // when true, attempts to cast values to the required types (e.g. a string to a number). Defaults to true. + convert?: boolean; + // when true, allows object to contain unknown keys which are ignored. Defaults to false. + allowUnknown?: boolean; + // when true, ignores unknown keys with a function value. Defaults to false. + skipFunctions?: boolean; + // when true, unknown keys are deleted (only when value is an object). Defaults to false. + stripUnknown?: boolean; + // overrides individual error messages. Defaults to no override ({}). + language?: Object + // provides an external data set to be used in references + context?: Object; + } + + export interface RenameOptions { + // if true, does not delete the old key name, keeping both the new and old keys in place. Defaults to false. + alias?: boolean; + // if true, allows renaming multiple keys to the same destination where the last rename wins. Defaults to false. + multiple?: boolean; + // if true, allows renaming a key over an existing key. Defaults to false. + override?: boolean; + } + + export interface WhenOptions { + // the required condition joi type. + is: Schema; + // the alternative schema type if the condition is true. Required if otherwise is missing. + then?: Schema; + // the alternative schema type if the condition is false. Required if then is missing + otherwise?: Schema; + } + + export interface ReferenceOptions { + separator?: string; + contextPrefix?: string; + } + + export interface ValidationError { + message: string; + details: ValidationErrorItem[]; + simple (): string; + annotated (): string; + } + + export interface ValidationErrorItem { + message: string; + type: string; + path: string; + options?: ValidationOptions; + } + + export interface SchemaMap { + [key: string]: Schema; + } + + export interface Schema extends AnySchema { + + } + + export interface Reference extends Schema { + + } + + export interface AnySchema> { + /** + * Whitelists a value + */ + allow(value: any, ...values : any[]): T; + allow(values: any[]): T; + + /** + * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. + */ + valid(value: any, ...values : any[]): T; + valid(values: any[]): T; + + /** + * Blacklists a value + */ + invalid(value: any, ...values : any[]): T; + invalid(values: any[]): T; + + /** + * Marks a key as required which will not allow undefined as value. All keys are optional by default. + */ + required(): T; + + /** + * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. + */ + optional(): T; + + /** + * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. + */ + forbidden(): T; + + /** + * Annotates the key + */ + description(desc: string): T; + + /** + * Annotates the key + */ + notes(notes: string): T; + notes(notes: string[]): T; + + /** + * Annotates the key + */ + tags(notes: string): T; + tags(notes: string[]): T; + + /** + * Attaches metadata to the key. + */ + meta(meta: Object): T; + + /** + * Annotates the key with an example value, must be valid. + */ + example(value: any): T; + + /** + * Annotates the key with an unit name. + */ + unit(name: string): T; + + /** + * Overrides the global validate() options for the current key and any sub-key. + */ + options(options: ValidationOptions): T; + + /** + * Sets the options.convert options to false which prevent type casting for the current key and any child keys. + */ + strict(): T; + + /** + * Sets a default value if the original value is undefined. + */ + default(value: any): T; + + /** + * Returns a new type that is the result of adding the rules of one type to another. + */ + concat(schema: T): T; + + /** + * Converts the type into an alternatives type where the conditions are merged into the type definition where: + */ + when(ref: string, options: WhenOptions): AlternativesSchema; + when(ref: Reference, options: WhenOptions): AlternativesSchema; + } + + export interface BooleanSchema extends AnySchema { + + } + + export interface NumberSchema extends AnySchema { + /** + * Specifies the minimum value. + */ + min(limit: number): NumberSchema; + + /** + * Specifies the maximum value. + */ + max(limit: number): NumberSchema; + + /** + * Requires the number to be an integer (no floating point). + */ + integer(): NumberSchema; + } + + export interface StringSchema extends AnySchema { + /** + * Allows the value to match any whitelist of blacklist item in a case insensitive comparison. + */ + insensitive(): StringSchema; + + /** + * Specifies the minimum number string characters. + */ + min(limit: number): StringSchema; + + /** + * Specifies the maximum number of string characters. + */ + max(limit: number): StringSchema; + + /** + * Specifies the exact string length required + */ + length(limit: number): StringSchema; + + /** + * Defines a regular expression rule. + */ + regex(pattern: RegExp): StringSchema; + + /** + * Requires the string value to only contain a-z, A-Z, and 0-9. + */ + alphanum(): StringSchema; + + /** + * Requires the string value to only contain a-z, A-Z, 0-9, and underscore _. + */ + token(): StringSchema; + + /** + * Requires the string value to be a valid email address. + */ + email(): StringSchema; + + /** + * Requires the string value to be a valid GUID. + */ + guid(): StringSchema; + + /** + * Requires the string value to be in valid ISO 8601 date format. + */ + isoDate(): StringSchema; + + /** + * Requires the string value to be all lowercase. If the validation convert option is on (enabled by default), the string will be forced to lowercase. + */ + lowercase(): StringSchema; + + /** + * Requires the string value to be all uppercase. If the validation convert option is on (enabled by default), the string will be forced to uppercase. + */ + uppercase(): StringSchema; + + /** + * Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed. + */ + trim(): StringSchema; + } + + export interface ArraySchema extends AnySchema { + /** + * List the types allowed for the array value + */ + includes(type: Schema, ...types: Schema[]): ArraySchema; + includes(types: Schema[]): ArraySchema; + + /** + * List the types forbidden for the array values. + */ + excludes(type: Schema, ...types: Schema[]): ArraySchema; + excludes(types: Schema[]): ArraySchema; + + /** + * Specifies the minimum number of items in the array. + */ + min(limit: number): ArraySchema; + + /** + * Specifies the maximum number of items in the array. + */ + max(limit: number): ArraySchema; + + /** + * Specifies the exact number of items in the array. + */ + length(limit: number): ArraySchema; + + } + + export interface ObjectSchema extends AnySchema { + /** + * Sets the allowed object keys. + */ + keys(schema?: SchemaMap): ObjectSchema; + + /** + * Specifies the minimum number of keys in the object. + */ + min(limit: number): ObjectSchema; + + /** + * Specifies the maximum number of keys in the object. + */ + max(limit: number): ObjectSchema; + + /** + * Specifies the exact number of keys in the object. + */ + length(limit: number): ObjectSchema; + + /** + * Specify validation rules for unknown keys matching a pattern. + */ + pattern(regex: RegExp, schema: Schema): ObjectSchema; + + /** + * Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well. + */ + and(peer1: string, peer2: string, ...peers: string[]): ObjectSchema; + and(peers: string[]): ObjectSchema; + + /** + * Defines a relationship between keys where one of the peers is required (and more than one is allowed). + */ + or(peer1: string, peer2: string, ...peers: string[]): ObjectSchema; + or(peers: string[]): ObjectSchema; + + /** + * Defines an exclusive relationship between a set of keys. one of them is required but not at the same time where: + */ + xor(peer1: string, peer2: string, ...peers: string[]): ObjectSchema; + xor(peers: string[]): ObjectSchema; + + /** + * Requires the presence of other keys whenever the specified key is present. + */ + with(key: string, peers: string): ObjectSchema; + with(key: string, peers: string[]): ObjectSchema; + + /** + * Forbids the presence of other keys whenever the specified is present. + */ + without(key: string, peers: string): ObjectSchema; + without(key: string, peers: string[]): ObjectSchema; + + /** + * Renames a key to another name (deletes the renamed key). + */ + rename(from: string, to: string, options?: RenameOptions): ObjectSchema; + + /** + * Verifies an assertion where. + */ + assert(ref: string, schema: Schema, message: string): ObjectSchema; + assert(ref: Reference, schema: Schema, message: string): ObjectSchema; + + /** + * Overrides the handling of unknown keys for the scope of the current object only (does not apply to children). + */ + unknown(allow?:boolean): ObjectSchema; + } + + export interface BinarySchema extends AnySchema { + /** + * Specifies the minimum length of the buffer. + */ + min(limit: number): BinarySchema; + + /** + * Specifies the maximum length of the buffer. + */ + max(limit: number): BinarySchema; + + /** + * Specifies the exact length of the buffer: + */ + length(limit: number): BinarySchema; + } + + export interface DateSchema extends AnySchema { + + /** + * Specifies the oldest date allowed. + */ + min(date: Date): DateSchema; + min(date: number): DateSchema; + min(date: string): DateSchema; + + /** + * Specifies the latest date allowed. + */ + max(date: Date): DateSchema; + max(date: number): DateSchema; + max(date: string): DateSchema; + } + + export interface FunctionSchema extends AnySchema { + + } + + export interface AlternativesSchema extends AnySchema { + try(schemas: Schema[]): AlternativesSchema; + when(ref: string, options: WhenOptions): AlternativesSchema; + when(ref: Reference, options: WhenOptions): AlternativesSchema; + } + + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + + /** + * Generates a schema object that matches any data type. + */ + export function any(): Schema; + + /** + * Generates a schema object that matches an array data type. + */ + export function array(): ArraySchema; + + /** + * Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via bool(). + */ + export function bool(): BooleanSchema; + + export function boolean(): BooleanSchema; + + /** + * Generates a schema object that matches a Buffer data type (as well as the strings which will be converted to Buffers). + */ + export function binary(): BinarySchema; + + /** + * Generates a schema object that matches a date type (as well as a JavaScript date string or number of milliseconds). + */ + export function date(): DateSchema; + + /** + * Generates a schema object that matches a function type. + */ + export function func(): FunctionSchema; + + /** + * Generates a schema object that matches a number data type (as well as strings that can be converted to numbers). + */ + export function number(): NumberSchema; + + /** + * Generates a schema object that matches an object data type (as well as JSON strings that parsed into objects). + */ + export function object(schema?: SchemaMap): ObjectSchema; + + /** + * Generates a schema object that matches a string data type. Note that empty strings are not allowed by default and must be enabled with allow(''). + */ + export function string(): StringSchema; + + /** + * Generates a type that will match one of the provided alternative schemas + */ + export function alternatives(types: Schema[]): Schema; + export function alternatives(type1: Schema, type2: Schema, ...types: Schema[]): Schema; + + /** + * Validates a value using the given schema and options. + */ + export function validate(value: T, schema: Schema, options?: ValidationOptions, callback?: (err: ValidationError, value: T) => void): void; + export function validate(value: T, schema: Object, options?: ValidationOptions, callback?: (err: ValidationError, value: T) => void): void; + export function validate(value: T, schema: Schema, callback: (err: ValidationError, value: T) => void): void; + export function validate(value: T, schema: Object, callback: (err: ValidationError, value: T) => void): void; + + /** + * Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object). + */ + export function compile(schema: Object): Schema; + + /** + * Validates a value against a schema and throws if validation fails. + */ + export function assert(value: any, schema: Schema): void; + + /** + * Generates a reference to the value of the named key. + */ + export function ref(key:string, options?: ReferenceOptions): Reference; +} diff --git a/jointjs/jointjs.d.ts b/jointjs/jointjs.d.ts index f4e0926ea7..c2ff9c1c75 100644 --- a/jointjs/jointjs.d.ts +++ b/jointjs/jointjs.d.ts @@ -38,20 +38,19 @@ declare module joint { attr(attrs: any): Cell; } - - class Element extends Cell { position(x: number, y: number): Element; translate(tx: number, ty?: number): Element; resize(width: number, height: number): Element; rotate(angle: number, absolute): Element; } + interface IDefaults { type: string; } class Link extends Cell { - defaults: IDefaults; + defaults(): IDefaults; disconnect(): Link; label(idx?: number, value?: any): any; // @todo: returns either a label under idx or Link if both idx and value were passed } @@ -65,7 +64,7 @@ declare module joint { linkView: LinkView; } - class Paper extends Backbone.View { + class Paper extends Backbone.View { options: IOptions; setDimensions(width: number, height: number); scale(sx: number, sy?: number, ox?: number, oy?: number): Paper; @@ -80,7 +79,8 @@ declare module joint { class ElementView extends CellView { scale(sx: number, sy: number); } - class CellView extends Backbone.View { + + class CellView extends Backbone.View { getBBox(): { x: number; y: number; width: number; height: number; }; highlight(el?: any); unhighlight(el?: any); @@ -94,7 +94,9 @@ declare module joint { } } + module ui { } + module shapes { module basic { class Generic extends joint.dia.Element { } @@ -104,6 +106,7 @@ declare module joint { class Image extends Generic { } } } + module util { function uuid(): string; function guid(obj: any): string; @@ -112,4 +115,5 @@ declare module joint { function deepMixin(objects: any[]): any; function deepSupplement(objects: any[], defaultIndicator?: any): any; } + } diff --git a/jqrangeslider/jqrangeslider.d.ts b/jqrangeslider/jqrangeslider.d.ts index ef688e5d9d..b41df43c0e 100644 --- a/jqrangeslider/jqrangeslider.d.ts +++ b/jqrangeslider/jqrangeslider.d.ts @@ -1,6 +1,6 @@ // Type definitions for jQRangeSlider 4.2.8 // Project: http://ghusse.github.com/jQRangeSlider -// Definitions by: Dániel Tar https://github.com/qcz +// Definitions by: Dániel Tar // Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/jquery.address/jquery.address.d.ts b/jquery.address/jquery.address.d.ts index bbf91d84a7..43a666e3e8 100644 --- a/jquery.address/jquery.address.d.ts +++ b/jquery.address/jquery.address.d.ts @@ -1,26 +1,173 @@ // Type definitions for jQuery.Address 1.5 // Project: https://github.com/asual/jquery-address -// Definitions by: Martin Duparc <@martinduparc> +// Definitions by: Martin Duparc , Tim Klingeleers // Definitions: https://github.com/borisyankov/DefinitelyTyped/ /// interface JQueryAddressStatic { (); - change(callback: any): void; - value(url: any): void; - update(): void; + /** + * Binds any supported event type to a function with support for an optional map of data. + */ + bind(type: any, data: any, callback: Function): JQueryAddressStatic; + /** + * Binds a function to be executed whenever the address is changed. + * The function receives a single event object parameter that contains the following properties: + * value, path, pathNames, parameterNames, parameters and queryString. + */ + change(callback: Function): JQueryAddressStatic; + /** + * Binds a function to be executed once when the address is initiated. + * The function receives a single event object parameter that contains the following properties: + * value, path, pathNames, parameterNames, parameters and queryString. + */ + init(callback: Function): JQueryAddressStatic; + /** + * Binds a function to be executed when the address is changed from inside the page that uses the plugin. + * The function receives a single event object parameter that contains the following properties: + * value, path, pathNames, parameterNames, parameters and queryString. + */ + internalChange(eventhandler: Function): JQueryAddressStatic; + /** + * Binds a function to be executed when the address is changed from the browser usually when entering the page or using the back and forward buttons. + * The function receives a single event object parameter that contains the following properties: + * value, path, pathNames, parameterNames, parameters and queryString. + */ + externalChange(eventhandler: Function): JQueryAddressStatic; + /** + * Provides the base address of the document. + */ + baseURL(): string; + /** + * Provides the state of the auto update mode. Enabled by default. + */ + autoUpdate(): boolean; + /** + * Enables or disables the auto update mode which can be turned off when multiple parameters values have to be changed at once. + */ + autoUpdate(value: boolean): JQueryAddressStatic; + /** + * Provides the state of the crawling mode. Disables by default. + */ + crawlable(): boolean; + /** + * Enables or disables the crawling mode which will automatically convert the values into a Google Ajax Crawling friendly format. + */ + crawlable(value: boolean): JQueryAddressStatic; + /** + * Provides the hash fragment part of the deep linking value. + */ + hash(): string; + /** + * Sets the hash fragment part of the deep linking value. + */ + hash(value: string): JQueryAddressStatic; + /** + * Provides the state of the history mode setting. Enabled by default. + */ + history(): boolean; + /** + * Enables or disables the history mode which generated entries in the browser history. + */ + history(value: boolean): void; + /** + * Provides the value of a specific query parameter. + */ + parameter(name: string): string; + /** + * Sets a query parameter value. Appending is disabled by default but can be enabled for array values. + */ + parameter(name: string, value: string, append: boolean): JQueryAddressStatic; + /** + * Provides a list of all the query parameter names. + */ + parameterNames(): Array; + /** + * Provides the deep linking value without the query string and the hash fragment. + */ path(): string; - path(value: string): void; - internalChange(eventhandler: Function): void; - externalChange(eventhandler: Function): void; - parameter(name: string, value?: string): string; + /** + * Sets the deep linking value without the query string and the hash fragment. + */ + path(value: string): JQueryAddressStatic; + /** + * Provides a list of all the folders in the deep linking path. + */ + pathNames(): Array; + /** + * Provides the query string part of the deep linking value. + */ + queryString(): string; + /** + * Sets the query string part of the deep linking value. + */ + queryString(value: string): JQueryAddressStatic; + /** + * Provides the value used as a base path for the HTML5 state management. + */ + state(): string; + /** + * Sets the base path of the website that is utilized in HTML5 state management. + */ + state(value: string): JQueryAddressStatic; + /** + * Provides the state of the strict mode setting. Enabled by default. + */ + strict(): boolean; + /** + * Enables or disables the strict mode which automatically appends a slash in the beginning of the deep linking value. + */ + strict(value: boolean): JQueryAddressStatic; + /** + * Provides the title of the HTML document. + */ + title(): string; + /** + * Sets the title of the HTML document. + */ + title(value: string): JQueryAddressStatic; + /** + * Provides the currently set page view tracking function. + */ + tracker(): any; + /** + * Sets a function for page view tracking. Google Analytics tracking is automatically invoked if it exists in the page. + */ + tracker(value: Function): JQueryAddressStatic; + /** + * Provides the current deep linking value. + */ value(): string; - history(value: boolean): void; + /** + * Sets the current deep linking value. + */ + value(url: string): JQueryAddressStatic; + /** + * Updates the value when auto updating is disabled. + */ + update(): JQueryAddressStatic; + /** + * Provides the state of the wrap mode. Disabled by default. + */ + wrap(): boolean; + /** + * Enables or disables the wrap mode which generates a DIV wrapper around the page content and fixes any scroll issues caused by the use of hash fragments. + */ + wrap(value: boolean): JQueryAddressStatic; } interface JQueryAddress { + /** + * Adds the plugin functionality to a DOM element and disables the default behavior. Designed primarily to support links and forms. + * Accepts an optional function parameter that allows custom processing of the deep link value. + */ (): JQuery; + /** + * Adds the plugin functionality to a DOM element and disables the default behavior. Designed primarily to support links and forms. + * Accepts an optional function parameter that allows custom processing of the deep link value. + */ + (fn: Function): JQuery; } interface JQueryStatic { diff --git a/jquery.blockUI/jquery.blockUI-tests.ts b/jquery.blockUI/jquery.blockUI-tests.ts new file mode 100644 index 0000000000..234340b938 --- /dev/null +++ b/jquery.blockUI/jquery.blockUI-tests.ts @@ -0,0 +1,25 @@ +/// + +$.blockUI(); +var opt: JQBlockUIOptions = { + css: { border: "1px solid red" }, + message: "test" +}; +$.blockUI(opt); +$.unblockUI(); +$("#test").block().unblock(); +$("#test").block(opt); + +$.blockUI.defaults.css.border = '5px solid red'; +$.blockUI.defaults.fadeOut = 200; + +$.blockUI({ message: $('#domMessage') }); +$.unblockUI({ fadeOut: 200 }); + +$.blockUI({ + fadeIn: 1000, + timeout: 2000, + onBlock: function() { + alert('Page is now blocked; fadeIn complete'); + } +}); diff --git a/jquery.blockUI/jquery.blockUI.d.ts b/jquery.blockUI/jquery.blockUI.d.ts new file mode 100644 index 0000000000..259044eaf8 --- /dev/null +++ b/jquery.blockUI/jquery.blockUI.d.ts @@ -0,0 +1,129 @@ +// Type definitions for jQuery BlockUI Plugin +// Project: http://malsup.com/jquery/block/ +// Definitions by: Jeffrey Lee +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface JQBlockUIOptions { + /** message displayed when blocking (use null for no message) */ + message?: any; + /** title string; only used when theme == true */ + title?: string; + /** only used when theme == true (requires jquery-ui.js to be loaded) */ + draggable?: boolean; + /** set to true to use with jQuery UI themes */ + theme?: boolean; + + /** + * styles for the message when blocking; if you wish to disable + * these and use an external stylesheet then do this in your code: + * $.blockUI.defaults.css = {}; + */ + css?: any; + + /** minimal style set used when themes are used */ + themedCSS?: any; + + /** styles for the overlay */ + overlayCSS?: any; + + /** style to replace wait cursor before unblocking to correct issue of lingering wait cursor */ + cursorReset?: string; + + /** styles applied when using $.growlUI */ + growlCSS?: any; + /** ifreamSrc for IE */ + iframeSrc?: string; + + /** force usage of iframe in non-IE browsers (handy for blocking applets) */ + forceIframe?: boolean; + + /** z-index for the blocking overlay */ + baseZ?: number; + + + /** set true to have the message automatically centered for X */ + centerX?: boolean; + /** set true to have the message automatically centered for Y */ + centerY?: boolean; + + /** + * allow body element to be stetched in ie6; this makes blocking look better + * on "short" pages. disable if you wish to prevent changes to the body height + */ + allowBodyStretch?: boolean; + + /** enable if you want key and mouse events to be disabled for content that is blocked */ + bindEvents?: boolean; + + /** be default blockUI will supress tab navigation from leaving blocking content(if bindEvents is true) */ + constrainTabKey?: boolean; + + /** fadeIn time in millis; set to 0 to disable fadeIn on block */ + fadeIn?: number; + + /** fadeOut time in millis; set to 0 to disable fadeOut on unblock */ + fadeOut?: number; + + /** time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock */ + timeout?: number; + + /** disable if you don't want to show the overlay */ + showOverlay?: boolean; + + /** if true, focus will be placed in the first available input field when page blocking */ + focusInput?: boolean; + + /** callback method invoked when fadeIn has completed and blocking message is visible */ + onBlock?: () => void; + + /** + * callback method invoked when unblocking has completed; the callback is + * passed the element that has been unblocked (which is the window object for page + * blocks) and the options that were passed to the unblock call: + * onUnblock(element, options) + */ + onUnblock?: (element: any, options: any) => void; + + // don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493 + /** quirksmodeOffsetHack */ + quirksmodeOffsetHack?: number; + + /** class name of the message block */ + blockMsgClass?: string; + + /** if it is already blocked, then ignore it (don't unblock and reblock) */ + ignoreIfBlocked?: boolean; +} + +interface JQBlockUIStatic { + /** default options */ + defaults?: JQBlockUIOptions; + /** block user activity for the page */ + (): void; + /** + * block user activity for the page + * @param options options + */ + (option: JQBlockUIOptions): void; +} + +interface JQueryStatic { + /** block user activity for the page */ + blockUI?: JQBlockUIStatic; + /** unblock the page */ + unblockUI?: JQBlockUIStatic; +} + +interface JQuery { + /** + * block the element(s) + * @param options block options + */ + block(option?: JQBlockUIOptions): JQuery; + /** + * unblock the element(s) + */ + unblock(option?: JQBlockUIOptions): JQuery; +} \ No newline at end of file diff --git a/jquery.clientSideLogging/jquery.clientSideLogging.d.ts b/jquery.clientSideLogging/jquery.clientSideLogging.d.ts index b52f41be18..4f1318a1fd 100644 --- a/jquery.clientSideLogging/jquery.clientSideLogging.d.ts +++ b/jquery.clientSideLogging/jquery.clientSideLogging.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jquery.clientSideLogging. +// Type definitions for jquery.clientSideLogging // Project: https://github.com/remybach/jQuery.clientSideLogging // Definitions by: Diullei Gomes // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/jquery.color/jquery.color.d.ts b/jquery.color/jquery.color.d.ts index 8d5000a6c2..4b41bae514 100644 --- a/jquery.color/jquery.color.d.ts +++ b/jquery.color/jquery.color.d.ts @@ -16,6 +16,11 @@ interface JQueryColor { */ red(val: number): JQueryColor; + /** + * Returns a copy of the color object with the red set to val. + */ + red(val: string): JQueryColor; + /** * Returns the green component of the color (integer from 0 - 255). */ @@ -26,6 +31,11 @@ interface JQueryColor { */ green(val: number): JQueryColor; + /** + * Returns a copy of the color object with the green set to val. + */ + green(val: string): JQueryColor; + /** * Returns the blue component of the color (integer from 0 - 255). */ @@ -35,6 +45,11 @@ interface JQueryColor { * Returns a copy of the color object with the blue set to val. */ blue(val: number): JQueryColor; + + /** + * Returns a copy of the color object with the blue set to val. + */ + blue(val: string): JQueryColor; /** * Returns the alpha value of this color (float from 0.0 - 1.0). @@ -46,6 +61,11 @@ interface JQueryColor { */ alpha(val: number): JQueryColor; + /** + * Returns a copy of the color object with the alpha set to val. + */ + alpha(val: string): JQueryColor; + /** * Returns the hue component of the color (integer from 0 - 359). */ @@ -56,6 +76,11 @@ interface JQueryColor { */ hue(val: number): JQueryColor; + /** + * Returns a copy of the color object with the hue set to val. + */ + hue(val: string): JQueryColor; + /** * Returns the saturation component of the color (float from 0.0 - 1.0). */ @@ -66,6 +91,11 @@ interface JQueryColor { */ saturation(val: number): JQueryColor; + /** + * Returns a copy of the color object with the saturation set to val. + */ + saturation(val: string): JQueryColor; + /** * Returns the lightness component of the color (float from 0.0 - 1.0). */ @@ -76,6 +106,11 @@ interface JQueryColor { */ lightness(val: number): JQueryColor; + /** + * Returns a copy of the color object with the lightness set to val. + */ + lightness(val: string): JQueryColor; + /** * Returns a rgba "tuple" [ red, green, blue, alpha ]. */ diff --git a/jquery.colorbox/jquery.colorbox.d.ts b/jquery.colorbox/jquery.colorbox.d.ts index d284223462..e13b0bbd52 100644 --- a/jquery.colorbox/jquery.colorbox.d.ts +++ b/jquery.colorbox/jquery.colorbox.d.ts @@ -1,6 +1,6 @@ // Type definitions for jQuery.Colorbox 1.4.15 // Project: http://www.jacklmoore.com/colorbox/ -// Definitions by: Gidon Junge <@gjunge> +// Definitions by: Gidon Junge // Definitions: https://github.com/borisyankov/DefinitelyTyped/ /// diff --git a/jquery.cycle/jquery.cycle.d.ts b/jquery.cycle/jquery.cycle.d.ts index dfe8e1c5cc..b482eda803 100644 --- a/jquery.cycle/jquery.cycle.d.ts +++ b/jquery.cycle/jquery.cycle.d.ts @@ -1,6 +1,6 @@ -// Type definitions for jQuery.cycle.js 2.9999.81 (15-JAN-2013) +// Type definitions for jQuery.cycle.js // Project: http://jquery.malsup.com/cycle/ -// Definitions by: François Guillot +// Definitions by: François Guillot // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -90,4 +90,4 @@ interface Cycle { interface JQuery { cycle: Cycle; -} \ No newline at end of file +} diff --git a/jquery.cycle2/jquery.cycle2.d.ts b/jquery.cycle2/jquery.cycle2.d.ts index 699d2aff87..d27fbf1c89 100644 --- a/jquery.cycle2/jquery.cycle2.d.ts +++ b/jquery.cycle2/jquery.cycle2.d.ts @@ -1,5 +1,6 @@ // Type definitions for jQuery Cycle2 version 2.1.2 (build 20140216) -// Project: http://jquery.malsup.com/cycle2/ (also https://github.com/malsup/cycle2) +// Project: http://jquery.malsup.com/cycle2/ +// https://github.com/malsup/cycle2 // Definitions by: Donny Nadolny // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -140,4 +141,4 @@ declare module JQueryCycle2 { interface Transition { before(opts: Options, curr: Element, next: Element, fwd: boolean): void; } -} \ No newline at end of file +} diff --git a/jquery.dataTables/jquery.dataTables.d.ts b/jquery.dataTables/jquery.dataTables.d.ts index d9524cf014..9884b78e29 100755 --- a/jquery.dataTables/jquery.dataTables.d.ts +++ b/jquery.dataTables/jquery.dataTables.d.ts @@ -343,7 +343,7 @@ declare module DataTables bLengthChange: boolean; bPaginate: boolean; bProcessing: boolean; - bServerSize: boolean; + bServerSide: boolean; bSort: boolean; bSortClasses: boolean; bStateSave: boolean; diff --git a/jquery.dynatree/jquery.dynatree.d.ts b/jquery.dynatree/jquery.dynatree.d.ts index 91425644d0..c2dc0f928d 100644 --- a/jquery.dynatree/jquery.dynatree.d.ts +++ b/jquery.dynatree/jquery.dynatree.d.ts @@ -1,22 +1,23 @@ -// Type definitions for jquery.dynatree 1.2 +// Type definitions for jquery.dynatree 1.2.5 // Project: http://code.google.com/p/dynatree/ -// Definitions by: https://github.com/fdecampredon +// Definitions by: François de Campredon // Definitions: https://github.com/borisyankov/DefinitelyTyped /// +/// + +declare module JQueryUI { + interface UI { + dynatree: DynatreeNamespace + } +} interface JQuery { dynatree(options?: DynatreeOptions): DynaTree; dynatree(option?: string, ...rest: any[]): any; } -interface JQueryStatic { - ui: { - dynatree: DynatreeNamespace; - }; -} - interface DynaTree { activateKey(key: string): DynaTreeNode; count(): number; @@ -39,7 +40,7 @@ interface DynaTree { renderInvisibleNodes(): void; selectKey(key: string, flag: string): DynaTreeNode; serializeArray(stopOnParents: boolean): any[]; - toDict(): any; + toDict(includeRoot?: boolean): any; visit(fn: (node: DynaTreeNode) =>boolean, includeRoot: boolean): void; } @@ -77,6 +78,7 @@ interface DynaTreeNode { makeVisible(): boolean; move(targetNode: DynaTreeNode, mode: string): boolean; reload(force: boolean): void; + reloadChildren(callback?: (node: DynaTreeNode, isOk: boolean) => any): void; remove(): void; removeChildren(): void; render(useEffects: boolean, includeInvisible: boolean): void; @@ -177,7 +179,7 @@ interface DynaTreeDataModel { interface DynaTreeDNDOptions { autoExpandMS?: number; // Expand nodes after n milliseconds of hovering. preventVoidMoves?: boolean; // Prevent dropping nodes 'before self', etc. - + revert: boolean; // true: slide helper back to source if drop is rejected // Make tree nodes draggable: onDragStart?: (sourceNode: any) =>void; // Callback(sourceNode), return true, to enable dnd diff --git a/jquery.fileupload/jquery.fileupload-tests.ts b/jquery.fileupload/jquery.fileupload-tests.ts new file mode 100644 index 0000000000..87149e0151 --- /dev/null +++ b/jquery.fileupload/jquery.fileupload-tests.ts @@ -0,0 +1,43 @@ +/// + +/* +* Handle the event of adding a file to the jQuery Upload plugin. +* +*/ +var __handleAddingFile = function (event:any, data:any) +{ + event.preventDefault(); + + // [PERFORM VALIDATION] + // If the data is valid submit the document + data.submit(); +}; + +class TestFileInput { + + // The whole body will be the container for this test + $el = $('body'); + + // Reference to the whole jQueryFileUpload object of the class + fileInput:JQueryFileUpload; + + constructor() { + + // The file upload object receives a fileInputOptions configuration object + this.fileInput = this.$el.fileupload({ + + dataType: 'json', + + // By default, each file of a selection is uploaded using an individual + // request for XHR type uploads. Set to false to upload file + // selections in one request each: + singleFileUploads: true, + // To limit the number of files uploaded with one XHR request, + // set the following option to an integer greater than 0: + limitMultiFileUploads: 1, + + add: __handleAddingFile + + }); + } +} diff --git a/jquery.fileupload/jquery.fileupload.d.ts b/jquery.fileupload/jquery.fileupload.d.ts new file mode 100644 index 0000000000..0ac8b98f96 --- /dev/null +++ b/jquery.fileupload/jquery.fileupload.d.ts @@ -0,0 +1,164 @@ +// Type definitions for jQuery File Upload Plugin 5.40.1 +// Project: https://github.com/blueimp/jQuery-File-Upload +// Definitions by: Rob Alarcon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + + +// Interface options for the plugin +interface JQueryFileInputOptions { + + // The drop target element(s), by the default the complete document. + // Set to null to disable drag & drop support: + dropZone?: HTMLElement; + + // The paste target element(s), by the default the complete document. + // Set to null to disable paste support: + pasteZone?: HTMLElement; + + // The file input field(s), that are listened to for change events. + // If undefined, it is set to the file input fields inside + // of the widget element on plugin initialization. + // Set to null to disable the change listener. + fileInput?: HTMLElement; + + // By default, the file input field is replaced with a clone after + // each input field change event. This is required for iframe transport + // queues and allows change events to be fired for the same file + // selection, but can be disabled by setting the following option to false: + replaceFileInput?: boolean; + + + // The parameter name for the file form data (the request argument name). + // If undefined or empty, the name property of the file input field is + // used, or "files[]" if the file input name property is also empty, + // can be a string or an array of strings: + paramName?: any; + + // By default, each file of a selection is uploaded using an individual + // request for XHR type uploads. Set to false to upload file + // selections in one request each: + singleFileUploads?: boolean; + + // To limit the number of files uploaded with one XHR request, + // set the following option to an integer greater than 0: + limitMultiFileUploads?: number; + + // The following option limits the number of files uploaded with one + // XHR request to keep the request size under or equal to the defined + // limit in bytes: + limitMultiFileUploadSize?: number; + + // Multipart file uploads add a number of bytes to each uploaded file, + // therefore the following option adds an overhead for each file used + // in the limitMultiFileUploadSize configuration: + limitMultiFileUploadSizeOverhead?: number; + + // Set the following option to true to issue all file upload requests + // in a sequential order: + sequentialUploads?: boolean; + + // To limit the number of concurrent uploads, + // set the following option to an integer greater than 0: + limitConcurrentUploads?: number; + + // Set the following option to true to force iframe transport uploads: + forceIframeTransport?: boolean; + + // Set the following option to the location of a redirect url on the + // origin server, for cross-domain iframe transport uploads: + redirect?: string; + + // The parameter name for the redirect url, sent as part of the form + // data and set to 'redirect' if this option is empty: + redirectParamName?: string; + + // Set the following option to the location of a postMessage window, + // to enable postMessage transport uploads: + postMessage?: string; + + // By default, XHR file uploads are sent as multipart/form-data. + // The iframe transport is always using multipart/form-data. + // Set to false to enable non-multipart XHR uploads: + multipart?: boolean; + + // To upload large files in smaller chunks, set the following option + // to a preferred maximum chunk size. If set to 0, null or undefined, + // or the browser does not support the required Blob API, files will + // be uploaded as a whole. + maxChunkSize?: number; + + // When a non-multipart upload or a chunked multipart upload has been + // aborted, this option can be used to resume the upload by setting + // it to the size of the already uploaded bytes. This option is most + // useful when modifying the options object inside of the "add" or + // "send" callbacks, as the options are cloned for each file upload. + uploadedBytes?: number; + + // By default, failed (abort or error) file uploads are removed from the + // global progress calculation. Set the following option to false to + // prevent recalculating the global progress data: + recalculateProgress?: boolean; + + // Interval in milliseconds to calculate and trigger progress events: + progressInterval?: number; + + // Interval in milliseconds to calculate progress bitrate: + bitrateInterval?: number; + + // By default, uploads are started automatically when adding files: + autoUpload?: boolean; + + // Error and info messages: + messages?: any; + + // Translation function, gets the message key to be translated + // and an object with context specific data as arguments: + i18n?: any; + + // Additional form data to be sent along with the file uploads can be set + // using this option, which accepts an array of objects with name and + // value properties, a function returning such an array, a FormData + // object (for XHR file uploads), or a simple object. + // The form of the first fileInput is given as parameter to the function: + formData?: any; + + // The add callback is invoked as soon as files are added to the fileupload + // widget (via file input selection, drag & drop, paste or add API call). + // If the singleFileUploads option is enabled, this callback will be + // called once for each file in the selection for XHR file uploads, else + // once for each file selection. + // + // The upload starts when the submit method is invoked on the data parameter. + // The data object contains a files property holding the added files + // and allows you to override plugin options as well as define ajax settings. + // + // Listeners for this callback can also be bound the following way: + // .bind('fileuploadadd', func); + // + // data.submit() returns a Promise object and allows to attach additional + // handlers using jQuery's Deferred callbacks: + // data.submit().done(func).fail(func).always(func); + add?: any; + + // The plugin options are used as settings object for the ajax calls. + // The following are jQuery ajax settings required for the file uploads: + processData?: boolean; + + contentType?: string; + + cache?: boolean; + +} + +interface JQueryFileUpload { + + contentType:string; +} + +interface JQuery +{ + // Interface to the main method of jQuery File Upload + fileupload(settings: JQueryFileInputOptions): JQueryFileUpload; +} \ No newline at end of file diff --git a/jquery.finger/jquery.finger-tests.ts b/jquery.finger/jquery.finger-tests.ts new file mode 100644 index 0000000000..e50fe1d5f2 --- /dev/null +++ b/jquery.finger/jquery.finger-tests.ts @@ -0,0 +1,37 @@ +/// +/// + +$.Finger.doubleTapInterval = 400; +$.Finger.flickDuration = 250; +$.Finger.pressDuration = 100; +$.Finger.motionThreshhold = 10; +$.Finger.preventDefault = true; +var fingerEventObject: JQueryFingerEventObject; +fingerEventObject.x = 1; +fingerEventObject.y = 2; +fingerEventObject.dx = 3; +fingerEventObject.dy = 4; +fingerEventObject.adx = 3; +fingerEventObject.ady = 4; +fingerEventObject.orientation = 'horizontal'; +fingerEventObject.direction = 1; +$('body').on('drag', e => { + if ('vertical' == e.orientation) return; + e.preventDefault(); +}); + +$('body').on('drag', '.drag', e => { + if ('vertical' == e.orientation) return; + e.preventDefault(); +}); + +$('#menu').on('flick', function (e) { + if ('horizontal' == e.orientation) { + if (1 == e.direction) { + $(this).addClass('is-opened'); + } + else { + $(this).removeClass('is-opened'); + } + } +}); diff --git a/jquery.finger/jquery.finger.d.ts b/jquery.finger/jquery.finger.d.ts new file mode 100644 index 0000000000..0b0cb7ebff --- /dev/null +++ b/jquery.finger/jquery.finger.d.ts @@ -0,0 +1,109 @@ +// Type definitions for jquery.finger.js +// Project: http://ngryman.sh/jquery.finger/ +// Definitions by: Max Ackley +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module JQueryFinger { + export interface JQueryFingerOptions { + /** + * The time the user must hold in order to fire a press event. If this + * time is not reached, a tap event will be fired instead. + * Default: 300(ms). + */ + pressDuration: number; + + /** + * The maximum time between two tap events to fire a doubletap event. + * If this time is reached, two distinct tap events will be fired instead. + * Default: 300(ms). + */ + doubleTapInterval: number; + + /** + * The maximum time the user will have to swipe in order to fire a flick + * event. If this time is reached, only drag events will continue to be + * fired. + * Default: 150(ms). + */ + flickDuration: number; + + /** + * The number of pixels the user will have to move in order to fire motion + * events (drag or flick). If this time is not reached, no motion will + * be handled and tap, doubletap or press event will be fired. + * Default: 5(px). + */ + motionThreshhold: number; + + /** + * Globally prevents every native default behavior. + * Default: undefined. + */ + preventDefault: boolean; + } +} + +interface JQueryFingerEventObject extends JQueryEventObject { + /** + * The x page coordinate. + */ + x: number; + + /** + * The y page coordinate. + */ + y: number; + + /** + * The x delta since the last event. + */ + dx: number; + + /** + * The y delta since the last event. + */ + dy: number; + + /** + * The absolute x delta since the last event. + */ + adx: number; + + /** + * The absolute y delta since the last event. + */ + ady: number; + + /** + * The orientation of the motion. Adjusted by $.Finger.motionThreshhold. + * Value is 'horizontal' or 'vertical'. + */ + orientation: string; + + /** + * The direction of the motion. Value is 1 if the motion is 'positive' + * (left-to-right or top-to-bottom) or -1 if 'negative'(right-to-left or + * bottom-to-top). + */ + direction: number; +} + +interface JQuery { + on(events: 'tap', handler: (eventObject: JQueryFingerEventObject, ...args: any[]) => any): JQuery; + on(events: 'doubletap', handler: (eventObject: JQueryFingerEventObject, ...args: any[]) => any): JQuery; + on(events: 'press', handler: (eventObject: JQueryFingerEventObject, ...args: any[]) => any): JQuery; + on(events: 'drag', handler: (eventObject: JQueryFingerEventObject, ...args: any[]) => any): JQuery; + on(events: 'flick', handler: (eventObject: JQueryFingerEventObject, ...args: any[]) => any): JQuery; + + on(events: 'tap', data: any, handler: (eventObject: JQueryFingerEventObject, ...args: any[]) => any): JQuery; + on(events: 'doubletap', data: any, handler: (eventObject: JQueryFingerEventObject, ...args: any[]) => any): JQuery; + on(events: 'press', data: any, handler: (eventObject: JQueryFingerEventObject, ...args: any[]) => any): JQuery; + on(events: 'drag', data: any, handler: (eventObject: JQueryFingerEventObject, ...args: any[]) => any): JQuery; + on(events: 'flick', data: any, handler: (eventObject: JQueryFingerEventObject, ...args: any[]) => any): JQuery; +} + +interface JQueryStatic { + Finger: JQueryFinger.JQueryFingerOptions; +} diff --git a/jquery.menuaim/jquery.menuaim.d.ts b/jquery.menuaim/jquery.menuaim.d.ts index 54215620af..86000419f6 100644 --- a/jquery.menuaim/jquery.menuaim.d.ts +++ b/jquery.menuaim/jquery.menuaim.d.ts @@ -1,6 +1,6 @@ // Type definitions for jQuery-menu-aim // Project: https://github.com/kamens/jQuery-menu-aim -// Definitions by: Robert Fonseca-Ensor +// Definitions by: Robert Fonseca-Ensor // Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/jquery.notifyBar/jquery.notifyBar-test.ts b/jquery.notifyBar/jquery.notifyBar-test.ts new file mode 100644 index 0000000000..8338fc8304 --- /dev/null +++ b/jquery.notifyBar/jquery.notifyBar-test.ts @@ -0,0 +1,66 @@ +/// + +$(function() { + $.notifyBar({ + html: "Autostart" + }); + + $("#common").click(function () { + $.notifyBar(); + }); + $("#error").click(function () { + $.notifyBar({ cssClass: "error", html: "Error occurred!" }); + }); + $("#success").click(function () { + $.notifyBar({ cssClass: "success", html: "Your data has been changed!" }); + }); + $("#warning").click(function() { + $.notifyBar({ cssClass: "warning", html: "Settings aren't changed!" }); + }) + $("#custom").click(function () { + $.notifyBar({ cssClass: "custom", html: "Your data has been changed!" }); + }); + $("#close").click(function () { + $.notifyBar({ html: "Click 'close' to hide notify bar", close: true, closeOnClick: false }); + }); + $("#position").click(function () { + $.notifyBar({ html: "At bottom", position: "bottom" }); + }); + + $("#events").click(function () { + $.notifyBar({ + html: "Test events", + onBeforeShow: function () { + $("#onBeforeShow").html("onBeforeShow - ok"); + }, + onShow: function () { + $("#onShow").html("onShow - ok"); + }, + onBeforeHide: function () { + $("#onBeforeHide").html("onBeforeHide - ok"); + }, + onHide: function () { + $("#onHide").html("onHide - ok"); + } + }); + }); + + $("#delay").click(function () { + $.notifyBar({ html: "delay 1000000", delay: 1000000 }); + }); + $("#speed-string").click(function () { + $.notifyBar({ html: "speed normal", animationSpeed: "normal" }); + }); + $("#speed-number").click(function () { + $.notifyBar({ html: "speed normal", animationSpeed: 500 }); + }); + $("#jqObject").click(function () { + $.notifyBar({ html: "set jqObject", jqObject: $("#jqObject") }); + }); + $("#closeText").click(function () { + $.notifyBar({ html: "set close text", closeText: "close" }); + }); + $("#closeOnOver").click(function () { + $.notifyBar({ html: "enable close on over", close: false, closeOnClick: false, closeOnOver: true }); + }); +}); diff --git a/jquery.notifyBar/jquery.notifyBar.d.ts b/jquery.notifyBar/jquery.notifyBar.d.ts new file mode 100644 index 0000000000..22e0126737 --- /dev/null +++ b/jquery.notifyBar/jquery.notifyBar.d.ts @@ -0,0 +1,99 @@ +// Type definitions for jQuery Notify Bar 1.4 +// Project: http://www.whoop.ee/posts/2013-04-05-the-resurrection-of-jquery-notify-bar/ +// Definitions by: Shunsuke Ohtani +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module JQueryNotifyBar { + + interface NotifyBarOptions { + /** + * What text will be inside bar. Can be HTML or just text. + */ + html?: string; + + /** + * How long bar will be delayed, doesn't count animation time. + */ + delay?: number; + + /** + * Custom jQuery object for notify bar. + */ + jqObject?: JQuery; + + /** + * You can define own CSS class for Notify bar. There are too premade classes "error", "warning" and "success". + */ + cssClass?: string; + + /** + * If set to true close button will be displayed. + */ + close?: boolean; + + /** + * Sets the text to close button. + */ + closeText?: string; + + /** + * If enabled, user can hide notify bar just by click on it. + */ + closeOnClick?: boolean; + + /** + * If enabled, user can hide notify bar just by moving mouse cursor on it. + */ + closeOnOver?: boolean; + + /** + * Callback on before show. + */ + onBeforeShow?: () => any; + + /** + * Callback on show. + */ + onShow?: () => any; + + /** + * Callback on before hide. + */ + onBeforeHide?: () => any; + + /** + * Callback on hide. + */ + onHide?: () => any; + + /** + * Set the position of notify bar. Possible values are "top", "bottom". + */ + position?: string; + } + + interface NotifyBarOptionsForAnimationSpeedString extends NotifyBarOptions { + /** + * How long this bar will be slided up and down. Possible values are "slow", "default", "normal", "fast". + */ + animationSpeed?: string; + } + + interface NotifyBarOptionsForAnimationSpeedNumber extends NotifyBarOptions { + /** + * How long this bar will be slided up and down. + */ + animationSpeed?: number; + } +} + +interface JQueryStatic { + /** + * Show notify bar. + * + * @param options notify bar options + */ + notifyBar(options?: JQueryNotifyBar.NotifyBarOptions): void; +} diff --git a/jquery.pjax.falsandtru/jquery.pjax-tests.ts b/jquery.pjax.falsandtru/jquery.pjax-tests.ts new file mode 100644 index 0000000000..18eae623c5 --- /dev/null +++ b/jquery.pjax.falsandtru/jquery.pjax-tests.ts @@ -0,0 +1,35 @@ +/// +/// + +function test_pjax() { + $.pjax(); +} + +function test_pjax_selector() { + $('a').pjax(); +} + +function test_pjax_option() { + $.pjax({ + area: 'body', + load: { + head: 'base, meta, link', + css: true, + script: true + }, + cache: { click: true, submit: false, popstate: true }, + server: { query: null } + }); +} + +function test_pjax_event() { + $.pjax({ + wait: 1000 + }); + $(document).bind('pjax.request', function () { + $('div.loading').fadeIn(100); + }); + $(document).bind('pjax.render', function () { + $('div.loading').fadeOut(500); + }); +} diff --git a/jquery.pjax.falsandtru/jquery.pjax.d.ts b/jquery.pjax.falsandtru/jquery.pjax.d.ts new file mode 100644 index 0000000000..07bc153df3 --- /dev/null +++ b/jquery.pjax.falsandtru/jquery.pjax.d.ts @@ -0,0 +1,189 @@ +// Type definitions for jquery.pjax.ts by falsandtru +// Project: https://github.com/falsandtru/jquery.pjax.js/ +// Definitions by: 新ゝ月 NewNotMoon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface PjaxSetting { + gns?: string; + ns?: string; + area?: any; // string, array, function( event, param, origUrl, destUrl ) + link?: string; + filter?: any; // string, function() + form?: string; + scope?: Object; + state?: any; // any, function(event, param, origUrl, destUrl ) + scrollTop?: any; // number, function( event, param, origUrl, destUrl ), null, false + scrollLeft?: any; // number, function( event, param, origUrl, destUrl ), null, false + scroll?: { + delay?: number; + record?: boolean //internal + queue?: number[] //internal + }; + ajax?: JQueryAjaxSettings; + contentType?: string; + load?: { + head?: string; + css?: boolean; + script?: boolean; + execute?: boolean; + reload?: string; + ignore?: string; + sync?: boolean; + ajax?: JQueryAjaxSettings; + rewrite?: (element: any) => any; + redirect?: boolean; + }; + interval?: number; + cache?: { + click?: boolean; + submit?: boolean; + popstate?: boolean; + get?: boolean; + post?: boolean; + page?: boolean; + size?: number; + mix?: number; + expires?: { + min?: number; + max?: number; + }; + }; + wait?: any; // number, function( event, param, origUrl, destUrl ): number + fallback?: any; // boolean, function( event, param, origUrl, destUrl ): boolean + fix?: { + location?: boolean; + history?: boolean; + scroll?: boolean; + reset?: boolean; + }; + database?: boolean; + server?: { + query?: any; // string, object + header?: { + area?: boolean; + head?: boolean; + css?: boolean; + script?: boolean; + }; + }; + callback?: (event: JQueryEventObject, param: any) => any; + callbacks?: { + before?: (event: JQueryEventObject, param: any) => any; + after?: (event: JQueryEventObject, param: any) => any; + ajax?: { + xhr?: (event: JQueryEventObject, param: any) => any; + beforeSend?: (event: JQueryEventObject, param: any, data: any, ajaxSettings: any) => any; + dataFilter?: (event: JQueryEventObject, param: any, data: any, dataType: any) => any; + success?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + error?: (event: JQueryEventObject, param: any, XMLHttpRequest: XMLHttpRequest, textStatus: string, errorThrown: any) => any; + complete?: (event: JQueryEventObject, param: any, XMLHttpRequest: XMLHttpRequest, textStatus: string) => any; + done?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + fail?: (event: JQueryEventObject, param: any, XMLHttpRequest: XMLHttpRequest, textStatus: string, errorThrown: any) => any; + always?: (event: JQueryEventObject, param: any, XMLHttpRequest: XMLHttpRequest, textStatus: string) => any; + }; + update?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + cache?: { + before?: (event: JQueryEventObject, param: any, cache: any) => any; + after?: (event: JQueryEventObject, param: any, cache: any) => any; + }; + redirect?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + url?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + title?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + head?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + content?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + scroll?: { + before?: (event: JQueryEventObject, param: any) => any; + after?: (event: JQueryEventObject, param: any) => any; + }; + css?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + script?: { + before?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + after?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + render?: { + before?: (event: JQueryEventObject, param: any) => any; + after?: (event: JQueryEventObject, param: any) => any; + }; + verify?: { + before?: (event: JQueryEventObject, param: any) => any; + after?: (event: JQueryEventObject, param: any) => any; + }; + success?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + error?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + complete?: (event: JQueryEventObject, param: any, data: any, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any; + }; + param?: any; + + // internal + uuid?: string; + nss?: { + name?: string; + event?: string[]; + click?: string; + submit?: string; + popstate?: string; + scroll?: string; + data?: string; + class4html?: string; + requestHeader?: string; + }; + origLocation?: HTMLAnchorElement; + destLocation?: HTMLAnchorElement; + retry?: boolean; + speedcheck?: boolean; + disable?: boolean; + option?: any; + }; +} + +interface JQueryStatic { + pjax: { + (setting?: PjaxSetting): any; + enable(): any; + disable(): any; + click(url: string, attr: { href?: string; }): any; + click(url: HTMLAnchorElement, attr: { href?: string; }): any; + click(url: JQuery, attr: { href?: string; }): any; + click(url: any, attr: { href?: string; }): any; + submit(url: string, attr: { action?: string; method?: string; }, data: any): any; + submit(url: HTMLFormElement, attr?: { action?: string; method?: string; }, data?: any): any; + submit(url: JQuery, attr?: { action?: string; method?: string; }, data?: any): any; + submit(url: any, attr?: { action?: string; method?: string; }, data?: any): any; + follow(event: JQueryEventObject, ajax: JQueryXHR, timeStamp?: number): boolean; + setCache(): any; + setCache(url: string): any; + setCache(url: string, data: string): any; + setCache(url: string, data: string, textStatus: string, XMLHttpRequest: XMLHttpRequest): any; + getCache(): any; + getCache(url: string): any; + removeCache(url: string): any; + removeCache(): any; + clearCache(): any; + }; +} + +interface JQuery { + pjax(setting?: PjaxSetting): any; +} \ No newline at end of file diff --git a/jquery.pjax/jquery.pjax-tests.ts b/jquery.pjax/jquery.pjax-tests.ts new file mode 100644 index 0000000000..214bb3922d --- /dev/null +++ b/jquery.pjax/jquery.pjax-tests.ts @@ -0,0 +1,60 @@ +/// +/// + +function test_fn_pjax() { + $(document).pjax("a"); + $(document).pjax("a", "#pjax-container"); + $(document).pjax("a", { push: true }); + $(document).pjax("a", "#pjax-container", { push: true }); +} + +function test_pjax() { + $.pjax(); + $.pjax({ + url: "hello.html", + container: "#main" + }); +} + +function test_click() { + var event = $.Event("click"); + $.pjax.click(event, "#pjax-container"); + $.pjax.click(event, { container: "#pjax-container" }); + $.pjax.click(event, "#pjax-container", { push: true }); +} + +function test_submit() { + var event = $.Event("submit"); + $.pjax.submit(event, "#pjax-container"); + $.pjax.submit(event, { container: "#pjax-container" }); + $.pjax.submit(event, "#pjax-container", { push: true }); +} + +function test_enable() { + $.pjax.enable(); +} + +function test_disable() { + $.pjax.disable(); +} + +function test_reload() { + $.pjax.reload(); +} + +function test_defauluts() { + $.pjax.defaults = { + timeout: 650, + push: true, + replace: false, + type: 'GET', + dataType: 'html', + scrollTo: 0, + maxCacheLength: 20, + version: $.noop + }; +} + +function test_support() { + console.log($.support.pjax); +} diff --git a/jquery.pjax/jquery.pjax.d.ts b/jquery.pjax/jquery.pjax.d.ts new file mode 100644 index 0000000000..621d87d218 --- /dev/null +++ b/jquery.pjax/jquery.pjax.d.ts @@ -0,0 +1,142 @@ +// Type definitions for jquery-pjax +// Project: https://github.com/defunkt/jquery-pjax +// Definitions by: Junle Li +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface PjaxSettings extends JQueryAjaxSettings { + /** + * A jQuery selector indicates where to stick the response body. E.g., $(container).html(xhr.responseBody). + * If it is not defined, the `data-pjax` attribute of the link will be treated as container. + * If such an attribute is not defined too, the context will be treated as container. + */ + container?: string; + + /** + * Whether to pushState the URL. Defaults to true. + */ + push?: boolean; + + /** + * Whether to replaceState the URL. Defaults to false. + */ + replace?: boolean; +} + +interface JQuery { + /** + * Tell PJAX to listen links with delegation selector that, when click on them, fetches the href with ajax into the container. + * Tries to make sure the back button and ctrl+click work the way you'd expect. + * If `options.container` is not defined, the `data-pjax` attribute of the link will be treated as container. + * If such an attribute is not defined too, the context runs with this statement will be treated as container. + * @param delegationSelector The selector to limit which links PJAX should listen on. + * @param options PJAX settings, which is a superset of jQuery AJAX settings. It includes the following specific options: + * - container: a jQuery selector indicates where to stick the response body. E.g., $(container).html(xhr.responseBody). + * - push: a boolean indicates whether to pushState the URL. Default is true. + * - replace: a boolean indicates whether to use replaceState instead of pushState. Default is false. + * @return Returns the jQuery object + */ + pjax(delegationSelector: string, options?: PjaxSettings): JQuery; + + /** + * Tell PJAX to listen links with delegation selector that, when click on them, fetches the href with ajax into the container. + * Tries to make sure the back button and ctrl+click work the way you'd expect. + * If `options.container` is not defined, the `data-pjax` attribute of the link will be treated as container. + * If such an attribute is not defined too, the context runs with this statement will be treated as container. + * @param delegationSelector The selector to limit which links PJAX should listen on. + * @param containerSelector A jQuery selector indicates where to stick the response body. E.g., $(containerSelector).html(xhr.responseBody). + * @param options PJAX settings, which is a superset of jQuery AJAX settings. It includes the following specific options: + * - container: a jQuery selector indicates where to stick the response body. The `containerSelector` parameter has priority. + * - push: a boolean indicates whether to pushState the URL. Default is true. + * - replace: a boolean indicates whether to use replaceState instead of pushState. Default is false. + * @return Returns the jQuery object + */ + pjax(delegationSelector: string, containerSelector?: string, options?: PjaxSettings): JQuery; +} + +interface JQueryStatic { + pjax: PjaxStatic; +} + +interface PjaxStatic { + /** + * PJAX default settings. + */ + defaults: PjaxSettings; + + /** + * Loads a URL with ajax, puts the response body inside a container, then pushState()'s the loaded URL. + * Works just like $.ajax in that it accepts a jQuery ajax settings object (with keys like url, type, data, etc). + * @param options PJAX settings, which is a superset of jQuery AJAX settings. It includes the following specific options: + * - container: a jQuery selector indicates where to stick the response body. E.g., $(container).html(xhr.responseBody). + * - push: a boolean indicates whether to pushState the URL. Default is true. + * - replace: a boolean indicates whether to use replaceState instead of pushState. Default is false. + */ + (options?: PjaxSettings): JQueryXHR; + + /** + * PJAX on click handler. + * @param event A jQuery click event. + * @param options PJAX settings, which is a superset of jQuery AJAX settings. It includes the following specific options: + * - container: a jQuery selector indicates where to stick the response body. E.g., $(container).html(xhr.responseBody). + * - push: a boolean indicates whether to pushState the URL. Default is true. + * - replace: a boolean indicates whether to use replaceState instead of pushState. Default is false. + */ + click(event: JQueryEventObject, options?: PjaxSettings): void; + + /** + * PJAX on click handler. + * @param event A jQuery click event. + * @param containerSelector A jQuery selector indicates where to stick the response body. E.g., $(containerSelector).html(xhr.responseBody). + * @param options PJAX settings, which is a superset of jQuery AJAX settings. It includes the following specific options: + * - container: a jQuery selector indicates where to stick the response body. The `containerSelector` parameter has priority. + * - push: a boolean indicates whether to pushState the URL. Default is true. + * - replace: a boolean indicates whether to use replaceState instead of pushState. Default is false. + */ + click(event: JQueryEventObject, containerSelector?: string, options?: PjaxSettings): void; + + /** + * PJAX on form submit handler + * @param event A jQuery click event. + * @param options PJAX settings, which is a superset of jQuery AJAX settings. It includes the following specific options: + * - container: a jQuery selector indicates where to stick the response body. E.g., $(container).html(xhr.responseBody). + * - push: a boolean indicates whether to pushState the URL. Default is true. + * - replace: a boolean indicates whether to use replaceState instead of pushState. Default is false. + */ + submit(event: JQueryEventObject, options?: PjaxSettings): void; + + /** + * PJAX on form submit handler + * @param event A jQuery click event. + * @param containerSelector A jQuery selector indicates where to stick the response body. E.g., $(containerSelector).html(xhr.responseBody). + * @param options PJAX settings, which is a superset of jQuery AJAX settings. It includes the following specific options: + * - container: a jQuery selector indicates where to stick the response body. The `containerSelector` parameter has priority. + * - push: a boolean indicates whether to pushState the URL. Default is true. + * - replace: a boolean indicates whether to use replaceState instead of pushState. Default is false. + */ + submit(event: JQueryEventObject, containerSelector?: string, options?: PjaxSettings): void; + + /** + * Install pjax functions on $.pjax to enable pushState behavior. Does nothing if already enabled. + */ + enable(): void; + + /** + * Disable pushState behavior. + * This is the case when a browser doesn't support pushState. It is sometimes useful to disable pushState for debugging on a modern browser. + */ + disable(): void; + + /** + * Reload current page with pjax. + */ + reload(): JQueryXHR; +} + +interface JQuerySupport { + /** + * A boolean value indicates if pjax is supported by the browser. + */ + pjax: boolean; +} diff --git a/jquery.pnotify/jquery.pnotify.d.ts b/jquery.pnotify/jquery.pnotify.d.ts index d467a99999..73d0411d53 100644 --- a/jquery.pnotify/jquery.pnotify.d.ts +++ b/jquery.pnotify/jquery.pnotify.d.ts @@ -1,6 +1,6 @@ // Type definitions for jquery.pnotify 1.3.1 -// Project: https://github.com/sciactive/pnotify -// Definitions by: https://github.com/DavidSichau +// Project: https://github.com/sciactive/pnotify +// Definitions by: David Sichau // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/jquery.postMessage/jquery.postMessage-tests.ts b/jquery.postMessage/jquery.postMessage-tests.ts new file mode 100644 index 0000000000..077063303d --- /dev/null +++ b/jquery.postMessage/jquery.postMessage-tests.ts @@ -0,0 +1,28 @@ +/// +/// + +function test_postMessage() { + // post plain message + $.postMessage('test message', 'http://dummy.url/', parent); + + // post object message + $.postMessage({ + 'a': '1', + 'b': '2' + }, 'http://dummy.url/', parent); +}; + +function test_receiveMessage() { + // receive plain source origin + $.receiveMessage((e) => { + // e is an instance of MessageEvent + console.log(e.data); + console.log(e.source); + console.log(e.origin); + }, 'http://dummy.url'); + + // receive source origin callback + $.receiveMessage((e) => {}, (sourceOrigin) => { + return sourceOrigin === 'http://dummy.url'; + }, 100); +}; diff --git a/jquery.postMessage/jquery.postMessage.d.ts b/jquery.postMessage/jquery.postMessage.d.ts new file mode 100644 index 0000000000..9494540380 --- /dev/null +++ b/jquery.postMessage/jquery.postMessage.d.ts @@ -0,0 +1,44 @@ +// Type definitions for jQuery postMessage +// Project: http://benalman.com/projects/jquery-postmessage-plugin/ +// Definitions by: Junle Li +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Official docs: http://benalman.com/code/projects/jquery-postmessage/docs/files/jquery-ba-postmessage-js.html + +interface JQueryStatic { + + /** + * This method will call window.postMessage if available, setting the targetOrigin parameter to the base of the targetUrl parameter for maximum security in browsers that support it. If window.postMessage is not available, the target window’s location.hash will be used to pass the message. If an object is passed as the message param, it will be serialized into a string using the jQuery.param method. + * + * @param message A message to be passed to the other frame. + * @param targetUrl The URL of the other frame this window is attempting to communicate with. This must be the exact URL (including any query string) of the other window for this script to work in browsers that don’t support window.postMessage. + * @param target A reference to the other frame this window is attempting to communicate with. If omitted, defaults to `parent`. + */ + postMessage(message: string, targetUrl: string, target?: Window): void; + + /** + * This method will call window.postMessage if available, setting the targetOrigin parameter to the base of the targetUrl parameter for maximum security in browsers that support it. If window.postMessage is not available, the target window’s location.hash will be used to pass the message. If an object is passed as the message param, it will be serialized into a string using the jQuery.param method. + * + * @param message An object to be serialized into a params string, using the jQuery.param method. + * @param targetUrl The URL of the other frame this window is attempting to communicate with. This must be the exact URL (including any query string) of the other window for this script to work in browsers that don’t support window.postMessage. + * @param target A reference to the other frame this window is attempting to communicate with. If omitted, defaults to `parent`. + */ + postMessage(message: { [key: string]: any; }, targetUrl: string, target?: Window): void; + + /** + * Register a single callback for either a window.postMessage call, if supported, or if unsupported, for any change in the current window location.hash. If window.postMessage is supported and sourceOrigin is specified, the source window will be checked against this for maximum security. If window.postMessage is unsupported, a polling loop will be started to watch for changes to the location.hash. + * + * @param callback This callback will execute whenever a jQuery.postMessage message is received, provided the sourceOrigin matches. If callback is omitted, any existing receiveMessage event bind or polling loop will be canceled. + * @param sourceOrigin If window.postMessage is available and this value is not equal to the event.origin property, the callback will not be called. + * @param delay An optional zero-or-greater delay in milliseconds at which the polling loop will execute (for browser that don’t support window.postMessage). If omitted, defaults to 100. + */ + receiveMessage(callback: (event: MessageEvent) => any, sourceOrigin?: string, delay?: number): void; + + /** + * Register a single callback for either a window.postMessage call, if supported, or if unsupported, for any change in the current window location.hash. If window.postMessage is supported and sourceOrigin is specified, the source window will be checked against this for maximum security. If window.postMessage is unsupported, a polling loop will be started to watch for changes to the location.hash. + * + * @param callback This callback will execute whenever a jQuery.postMessage message is received, provided the sourceOrigin matches. If callback is omitted, any existing receiveMessage event bind or polling loop will be canceled. + * @param sourceOrigin If window.postMessage is available and this function returns false when passed the event.origin property, the callback will not be called. + * @param delay An optional zero-or-greater delay in milliseconds at which the polling loop will execute (for browser that don’t support window.postMessage). If omitted, defaults to 100. + */ + receiveMessage(callback: (event: MessageEvent) => any, sourceOrigin?: (origin: string) => boolean, delay?: number): void; +} diff --git a/jquery.prettyphoto/jquery.prettyphoto-tests.ts b/jquery.prettyphoto/jquery.prettyphoto-tests.ts new file mode 100644 index 0000000000..1cf3b40a89 --- /dev/null +++ b/jquery.prettyphoto/jquery.prettyphoto-tests.ts @@ -0,0 +1,34 @@ +// Tests for prettyPhoto library + +/// +/// + +// JQUERY + +$('#id').prettyPhoto(); + +$('#id').prettyPhoto({ animation_speed: 'fast' }); + +// JQUERYSTATIC + +$.prettyPhoto.changeGalleryPage('next'); + +$.prettyPhoto.changeGalleryPage('previous'); + +$.prettyPhoto.changePage('next'); + +$.prettyPhoto.changePage('previous'); + +$.prettyPhoto.close(); + +$.prettyPhoto.open(); + +$.prettyPhoto.open('test.jpg', 'title', 'description'); + +$.prettyPhoto.open(['test1.jpg', 'test2.jpg'], ['title1', 'title2'], ['description1', 'description2']); + +$.prettyPhoto.startSlideshow(); + +$.prettyPhoto.stopSlideshow(); + +$.prettyPhoto.version; diff --git a/jquery.prettyphoto/jquery.prettyphoto.d.ts b/jquery.prettyphoto/jquery.prettyphoto.d.ts new file mode 100644 index 0000000000..f60de3b390 --- /dev/null +++ b/jquery.prettyphoto/jquery.prettyphoto.d.ts @@ -0,0 +1,290 @@ +// Type definitions for jQuery prettyPhoto 3.1.5 +// Project: https://github.com/scaron/prettyphoto +// Definitions by: pgaske +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module scaron_prettyPhoto { + /** + * Pretty photo settings + */ + interface PrettyPhotoSettings { + /** + * the attribute tag to use for prettyPhoto hooks. For HTML5, use "data-rel" or similar. + * @default 'rel' + */ + hook?: string; + + /** + * fast/slow/normal + * @default 'fast' + */ + animation_speed?: string; + + + ajaxcallback?: () => void; + + /** + * false OR interval time in ms + * @default 5000 + */ + slideshow?: any; + + /** + * true/false + * @default false + */ + autoplay_slideshow?: boolean; + + /** + * Value between 0 and 1 + * @default 0.80 + */ + opacity?: number; + + /** + * true/false + * @default true + */ + show_title?: boolean; + + /** + * Resize the photos bigger than viewport. true/false + * @default true + */ + allow_resize?: boolean; + + /** + * Allow the user to expand a resized image. true/false + * @default true + */ + allow_expand?: boolean; + + /** + * Pixels + * @default 500 + */ + default_width?: number; + + /** + * Pixels + * @default 344 + */ + default_height?: number; + + /** + * The separator for the gallery counter 1 "of" 2 + * @default '/' + */ + counter_separator_label?: string; + + /** + * light_rounded / dark_rounded / light_square / dark_square / facebook + * @default 'pp_default' + */ + theme?: string; + + /** + * The padding on each side of the picture + * @default 20 + */ + horizontal_padding?: number; + + /** + * Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto + * @default false + */ + hideflash?: boolean; + + /** + * Set the flash wmode attribute + * @default 'opaque' + */ + wmode?: string; + + /** + * Automatically start videos: True/False + * @default true + */ + autoplay?: boolean; + + /** + * If set to true, only the close button will close the window + * @default false + */ + modal?: boolean; + + /** + * Allow prettyPhoto to update the url to enable deeplinking. + * @default true + */ + deeplinking?: boolean; + + /** + * If set to true, a gallery will overlay the fullscreen image on mouse over + * @default true + */ + overlay_gallery?: boolean; + + /** + * Maximum number of pictures in the overlay gallery + * @default 30 + */ + overlay_gallery_max?: number; + + /** + * Set to false if you open forms inside prettyPhoto + * @default true + */ + keyboard_shortcuts?: boolean; + + /** + * Called everytime an item is shown/changed + * @default function () { } + */ + changepicturecallback?: () => void; + + /** + * Called when prettyPhoto is closed + * @default function () { } + */ + callback?: () => void; + + /** + * @default true + */ + ie6_fallback?: boolean; + + /** + * Markup for pretty photo + * @default omitted for brevity + */ + markup?: string; + + /** + * Markup for pretty photo gallery + * @default omitted for brevity + */ + gallery_markup?: string; + + /** + * Markup for image + * @default '' + */ + image_markup?: string; + + /** + * Markup for flash + * @default '' + */ + flash_markup?: string; + + /** + * Markup for quicktime + * @default '' + */ + quicktime_markup?: string; + + /** + * Markup for iframe + * @default '' + */ + iframe_markup?: string; + + /** + * @default '
{content}
' + */ + inline_markup?: string; + + /** + * @default '' + */ + custom_markup?: string; + + /** + * Markup for social tools, set to html or false to disable + * @default '' + */ + social_tools?: any; + } + + interface moduleJQuery { + /** + * Initialises prettyPhoto + */ + (): JQuery; + + /** + * Initialises prettyPhoto specificying overrides for the defaults + * @param pp_settings custom prettyPhoto settings + */ + (pp_settings: PrettyPhotoSettings): JQuery; + } + + interface moduleJQueryStatic { + /** + * prettyPhoto version number + */ + version: string; + + /** + * Opens the prettyPhoto modal box. + * Note: Always returns false. + */ + open(): boolean; + + /** + * Opens the prettyPhoto modal box. + * Note: Always returns false. + * @param image {String} Full path to the image to be open, can also be an array containing full images paths. + * @param title {String} The title to be displayed with the picture, can also be an array containing all the titles. + * @param description {String} The description to be displayed with the picture, can also be an array containing all the descriptions. + */ + open(image: string, title: string, description: string): boolean; + + /** + * Opens the prettyPhoto modal box. + * Note: Always returns false. + * @param image {Array} Full path to the image to be open, can also be an array containing full images paths. + * @param title {Array} The title to be displayed with the picture, can also be an array containing all the titles. + * @param description {Array} The description to be displayed with the picture, can also be an array containing all the descriptions. + */ + open(images: string[], titles: string[], descriptions: string[]): boolean; + + /** + * Change page in the prettyPhoto modal box + * @param direction {String} Direction of the paging, previous or next. + */ + changePage(direction: string): void; + + /** + * Change gallery page in the prettyPhoto modal box + * @param direction {String} Direction of the paging, previous or next. + */ + changeGalleryPage(direction: string): void; + + /** + * Start the slideshow... + */ + startSlideshow(): void; + + /** + * Stop the slideshow... + */ + stopSlideshow(): void; + + /** + * Closes prettyPhoto. + */ + close(): void; + } +} + +interface JQuery { + prettyPhoto: scaron_prettyPhoto.moduleJQuery; +} + +interface JQueryStatic { + prettyPhoto: scaron_prettyPhoto.moduleJQueryStatic; +} \ No newline at end of file diff --git a/jquery.tagsmanager/jquery.tagsmanager.d.ts b/jquery.tagsmanager/jquery.tagsmanager.d.ts index ce03f2dab5..4523751c49 100644 --- a/jquery.tagsmanager/jquery.tagsmanager.d.ts +++ b/jquery.tagsmanager/jquery.tagsmanager.d.ts @@ -1,6 +1,6 @@ // Type definitions for jQuery Tags Manager // Project: http://welldonethings.com/tags/manager -// Definitions by: https://github.com/vbortone +// Definitions by: Vincent Bortone // Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/jquery.tile/jquery.tile-tests.ts b/jquery.tile/jquery.tile-tests.ts new file mode 100644 index 0000000000..e4f63a0a7f --- /dev/null +++ b/jquery.tile/jquery.tile-tests.ts @@ -0,0 +1,5 @@ +/// + +$('div').tile(); + +$('div').tile(4); diff --git a/jquery.tile/jquery.tile.d.ts b/jquery.tile/jquery.tile.d.ts new file mode 100644 index 0000000000..e27acdad89 --- /dev/null +++ b/jquery.tile/jquery.tile.d.ts @@ -0,0 +1,16 @@ +// Type definitions for jquery.tile.js 1.1.0 +// Project: https://github.com/urin/jquery.tile.js +// Definitions by: Shunsuke Ohtani +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface JQuery { + /** + * Align the height of the largest of the elements arranged in the same row. + * if columns is not specified, align the height of the largest of the all elements. + * + * @param columns Number of elements in a row + */ + tile(columns?: number): void; +} diff --git a/jquery.timepicker/jquery.timepicker.d.ts b/jquery.timepicker/jquery.timepicker.d.ts index a63e073bb6..13a6d2e694 100644 --- a/jquery.timepicker/jquery.timepicker.d.ts +++ b/jquery.timepicker/jquery.timepicker.d.ts @@ -1,6 +1,6 @@ // Type definitions for jQuery UI Timepicker 0.3 // Project: http://fgelinas.com/code/timepicker/ -// Definitions by: https://github.com/anwarjaved +// Definitions by: Anwar Javed // Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/jquery.total-storage/jquery.total-storage-tests.ts b/jquery.total-storage/jquery.total-storage-tests.ts new file mode 100644 index 0000000000..0ba3700eee --- /dev/null +++ b/jquery.total-storage/jquery.total-storage-tests.ts @@ -0,0 +1,21 @@ +// Type definitions for jQueryTotalStorage 1.1.2 +// Project: https://github.com/Upstatement/jquery-total-storage +// Definitions by: Jeremy Brooks +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +//direct call +$.totalStorage("test_key1", "test_value"); +var val1:string = $.totalStorage("test_key"); + +//set/get +$.totalStorage.setItem("test_key2", 123); +var val2:number = $.totalStorage.getItem("test_key2"); + +//get all items +var list = $.totalStorage.getAll(); + +//delete item +var deleted = $.totalStorage.deleteItem("test_key1"); \ No newline at end of file diff --git a/jquery.total-storage/jquery.total-storage.d.ts b/jquery.total-storage/jquery.total-storage.d.ts new file mode 100644 index 0000000000..8bfed0a4d3 --- /dev/null +++ b/jquery.total-storage/jquery.total-storage.d.ts @@ -0,0 +1,64 @@ +// Type definitions for jQueryTotalStorage 1.1.2 +// Project: https://github.com/Upstatement/jquery-total-storage +// Definitions by: Jeremy Brooks +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** +* @desc Set the value of a key to a string +* @example $.totalStorage('the_key', 'the_value'); +* @desc Set the value of a key to a number +* @example $.totalStorage('the_key', 800.2); +* @desc Set the value of a key to a complex Array +* @example var myArray = new Array(); +* myArray.push({name:'Jared', company:'Upstatement', zip:63124}); +* myArray.push({name:'McGruff', company:'Police', zip:60652}; +* $.totalStorage('people', myArray); +* //to return: +* $.totalStorage('people'); +* +*/ + +interface JQueryTotalStorage { + + /** + * @desc Set or get a key's value + * @param key Key to set. + * @param value Value to set for key. If ommited, current value for key is returned. + * @param options Not implemented. + */ + (key: string, value?: any, options?: JQueryTotalStorageOptions): any; + + /** + * @desc Set a key's value + * @param key Key to set. + * @param value Value to set for key. + */ + setItem(key: string, value: any): any; + + /** + * @desc Get a key's value + * @param key Key to get. + */ + getItem(key: string): any; + + /** + * @desc Get all set values + */ + getAll(): any[]; + + /** + * @desc Delete item by key + * @param key Key of item to delete + */ + deleteItem(key: string): boolean; +} + +interface JQueryTotalStorageOptions { + //not implemented... +} + +interface JQueryStatic { + totalStorage: JQueryTotalStorage; +} \ No newline at end of file diff --git a/jquery.ui.datetimepicker/jquery.ui.datetimepicker.d.ts b/jquery.ui.datetimepicker/jquery.ui.datetimepicker.d.ts index 9d452332b9..4e592e7281 100644 --- a/jquery.ui.datetimepicker/jquery.ui.datetimepicker.d.ts +++ b/jquery.ui.datetimepicker/jquery.ui.datetimepicker.d.ts @@ -1,7 +1,6 @@ -// Type definitions for jQuery UI DateTimePicker 0.3 Addon -// +// Type definitions for jQuery UI DateTimePicker 0.3 // Project: http://trentrichardson.com/examples/timepicker/ -// Definitions by: https://github.com/dougajmcdonald +// Definitions by: dougajmcdonald // Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/jquery.validation/jquery.validation.d.ts b/jquery.validation/jquery.validation.d.ts index d0bee32796..f66edadab9 100644 --- a/jquery.validation/jquery.validation.d.ts +++ b/jquery.validation/jquery.validation.d.ts @@ -1,6 +1,6 @@ // Type definitions for jquery.validation 1.11.1 -// Project: http://bassistance.de/jquery-plugins/jquery-plugin-validation/ -// Definitions by: https://github.com/fdecampredon , https://github.com/johnnyreilly +// Project: http://jqueryvalidation.org/ +// Definitions by: François de Campredon , Johj Reilly // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/jquery.watermark/jquery.watermark.d.ts b/jquery.watermark/jquery.watermark.d.ts index fd233ee67a..cb746bee63 100644 --- a/jquery.watermark/jquery.watermark.d.ts +++ b/jquery.watermark/jquery.watermark.d.ts @@ -1,6 +1,6 @@ // Type definitions for Watermark plugin for jQuery 3.1 // Project: http://jquery-watermark.googlecode.com -// Definitions by: https://github.com/anwarjaved +// Definitions by: Anwar Javed // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -27,4 +27,4 @@ interface JQuery { interface JQueryStatic { watermark: Watermark; -} \ No newline at end of file +} diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index 973818f5ae..2f647c4d13 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -6,7 +6,7 @@ function test_add() { $('li').add('p').css('background-color', 'red'); $('li').add(document.getElementsByTagName('p')[0]) - .css('background-color', 'red'); + .css('background-coailor', 'red'); $('li').add('

new paragraph

') .css('background-color', 'red'); $("div").css("border", "2px solid red") @@ -86,6 +86,9 @@ function test_ajax() { success: function (data) { $('.result').html(data); alert('Load was performed.'); + }, + error: function (jqXHR, textStatus, errorThrown) { + alert('Load failed. responseJSON=' + jqXHR.responseJSON); } }); var _super = jQuery.ajaxSettings.xhr; @@ -150,6 +153,52 @@ function test_ajax() { url: "test.js", dataType: "script" }); + + // Test the jqXHR object returned by $.ajax() as of 1.5 + // More details: http://api.jquery.com/jQuery.ajax/#jqXHR + + // done method + $.ajax({ + url: "test.js" + }).done((data, textStatus, jqXHR) => { + console.log(data, textStatus, jqXHR); + }); + + // fail method + $.ajax({ + url: "test.js" + }).fail((jqXHR, textStatus, errorThrown) => { + console.log(jqXHR, textStatus, errorThrown); + }); + + // always method with successful request + $.ajax({ + url: "test.js" + }).always((data, textStatus, jqXHR) => { + console.log(data, textStatus, jqXHR); + }); + + // always method with failed request + $.ajax({ + url: "test.js" + }).always((jqXHR, textStatus, errorThrown) => { + console.log(jqXHR, textStatus, errorThrown); + }); + + // then method (as of 1.8) + $.ajax({ + url: "test.js" + }).then((data, textStatus, jqXHR) => { + console.log(data, textStatus, jqXHR); + }, (jqXHR, textStatus, errorThrown) => { + console.log(jqXHR, textStatus, errorThrown); + }); + + // jqXHR object + var jqXHR = $.ajax({ + url: "test.js" + }); + jqXHR.abort('aborting because I can'); } function test_ajaxComplete() { @@ -727,7 +776,7 @@ function test_callbacksFunctions() { callbacks.add(bar); callbacks.fire('world'); callbacks.disable(); - + // Test the disabled state of the list console.log(callbacks.disabled()); // Outputs: true @@ -1445,6 +1494,9 @@ function test_eventParams() { $('#whichkey').bind('mousedown', function (e) { $('#log').html(e.type + ': ' + e.which); }); + $(window).on('mousewheel', (e) => { + var delta = (e.originalEvent).deltaY; + }); } function test_extend() { @@ -3114,6 +3166,25 @@ function test_parseHTML() { $( "
    " ) .append( nodeNames.join( "" ) ) .appendTo( $log ); + + // parse HTML with all parameters + $.parseHTML( str, document, true ); +} + +// http://api.jquery.com/jQuery.parseJSON/ +function test_parseJSON() { + // Return type should be any, not Object + var i = $.parseJSON('1'); + var a = $.parseJSON('[1]'); + var o = $.parseJSON('{"foo":"bar"}'); + var s = $.parseJSON('"string"'); + var n = $.parseJSON('null'); + + i instanceof Object; // false + a instanceof Object; // true + o instanceof Object; // true + s instanceof Object; // false + n instanceof Object; // false } function test_not() { @@ -3273,4 +3344,3 @@ function test_deferred_promise() { } ); } - diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 8f1bf2527b..e40110c16d 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -1,6 +1,6 @@ // Type definitions for jQuery 1.10.x / 2.0.x // Project: http://jquery.com/ -// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton, Diullei Gomes , Tass Iliopoulos , Jason Swearingen, Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly +// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton , Diullei Gomes , Tass Iliopoulos , Jason Swearingen , Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly // Definitions: https://github.com/borisyankov/DefinitelyTyped /* ***************************************************************************** @@ -80,7 +80,7 @@ interface JQueryAjaxSettings { /** * A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. */ - error? (jqXHR: JQueryXHR, textStatus: string, errorThrow: string): any; + error? (jqXHR: JQueryXHR, textStatus: string, errorThrown: string): any; /** * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events. */ @@ -167,7 +167,20 @@ interface JQueryXHR extends XMLHttpRequest, JQueryPromise { * The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header. As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). */ overrideMimeType(mimeType: string): any; + /** + * Cancel the request. + * + * @param statusText A string passed as the textStatus parameter for the done callback. Default value: "canceled" + */ abort(statusText?: string): void; + /** + * Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details. + */ + then(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => void, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise; + /** + * Property containing the parsed response if the response Content-Type is json + */ + responseJSON?: any; } /** @@ -351,6 +364,11 @@ interface JQueryPromise { */ progress(...progressCallbacks: any[]): JQueryPromise; + /** + * Determine the current state of a Deferred object. + */ + state(): string; + // Deprecated - given no typings pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; @@ -527,9 +545,10 @@ interface BaseJQueryEventObject extends Event { data: any; delegateTarget: Element; isDefaultPrevented(): boolean; - isImmediatePropogationStopped(): boolean; + isImmediatePropagationStopped(): boolean; isPropagationStopped(): boolean; namespace: string; + originalEvent: Event; preventDefault(): any; relatedTarget: Element; result: any; @@ -567,11 +586,7 @@ interface JQueryKeyEventObject extends JQueryInputEventObject { keyCode: number; } -interface JQueryPopStateEventObject extends BaseJQueryEventObject { - originalEvent: PopStateEvent; -} - -interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject, JQueryPopStateEventObject { +interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject{ } /* @@ -1214,7 +1229,7 @@ interface JQueryStatic { * * @param json The JSON string to parse. */ - parseJSON(json: string): Object; + parseJSON(json: string): any; /** * Parses a string into an XML document. @@ -1252,6 +1267,15 @@ interface JQueryStatic { * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string */ parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[]; + + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context DOM element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + */ + parseHTML(data: string, context?: Document, keepScripts?: boolean): any[]; } /** @@ -1512,7 +1536,37 @@ interface JQuery { * * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. */ - val(func: (index: number, value: any) => any): JQuery; + val(func: (index: number, value: string) => string): JQuery; + /** + * Set the value of each element in the set of matched elements. + * + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + val(func: (index: number, value: string[]) => string): JQuery; + /** + * Set the value of each element in the set of matched elements. + * + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + val(func: (index: number, value: number) => string): JQuery; + /** + * Set the value of each element in the set of matched elements. + * + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + val(func: (index: number, value: string) => string[]): JQuery; + /** + * Set the value of each element in the set of matched elements. + * + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + val(func: (index: number, value: string[]) => string[]): JQuery; + /** + * Set the value of each element in the set of matched elements. + * + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + val(func: (index: number, value: number) => string[]): JQuery; /** * Get the value of style properties for the first element in the set of matched elements. @@ -2391,6 +2445,7 @@ interface JQuery { dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + delegate(selector: any, eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Trigger the "focus" event on an element. @@ -3597,7 +3652,7 @@ interface JQuery { * * @param func A function used as a test for each element in the set. this is the current DOM element. */ - filter(func: (index: number) => any): JQuery; + filter(func: (index: number, element: Element) => any): JQuery; /** * Reduce the set of matched elements to those that match the selector or pass the function's test. * diff --git a/jquerymobile/jquerymobile.d.ts b/jquerymobile/jquerymobile.d.ts index ebcaac48fa..f07c73fc34 100644 --- a/jquerymobile/jquerymobile.d.ts +++ b/jquerymobile/jquerymobile.d.ts @@ -335,17 +335,25 @@ interface JQueryMobilePath { } interface ParsedPath { + authority: string; + directory: string; + domain: string; + doubleSlash: string; + filename: string; hash: string; host: string; hostname: string; href: string; + hrefNoHash: string; + hrefNoSearch: string; + password: string; pathname: string; port: string; protocol: string; search: string; + username: string; } - interface JQueryMobile extends JQueryMobileOptions { version: string; diff --git a/jqueryui/jqueryui-tests.ts b/jqueryui/jqueryui-tests.ts index c922ec161a..79263027fe 100644 --- a/jqueryui/jqueryui-tests.ts +++ b/jqueryui/jqueryui-tests.ts @@ -1270,6 +1270,125 @@ function test_datepicker() { // setter var $set: JQuery = $(".selector").datepicker("option", "calculateWeek", myWeekCalc); } + + function changeMonth() { + $(".selector").datepicker({ changeMonth: true }); + + var changeMonth: boolean = $(".selector").datepicker("option", "changeMonth"); + + // setter + var $set: JQuery = $(".selector").datepicker("option", "changeMonth", true); + } + + function changeYear() { + $(".selector").datepicker({ changeYear: true }); + + var changeYear: boolean = $(".selector").datepicker("option", "changeYear"); + + // setter + var $set: JQuery = $(".selector").datepicker("option", "changeYear", true); + } + + function closeText() { + $(".selector").datepicker({ closeText: "Close" }); + + var closeText: string = $(".selector").datepicker("option", "closeText"); + + // setter + var $set: JQuery = $(".selector").datepicker("option", "closeText", "Close"); + } + + function constrainInput() { + $(".selector").datepicker({ constrainInput: false }); + + var constrainInput: boolean = $(".selector").datepicker("option", "constrainInput"); + + // setter + var $set: JQuery = $(".selector").datepicker("option", "constrainInput", false); + } + + function currentText() { + $(".selector").datepicker({ currentText: "Now" }); + + var currentText: string = $(".selector").datepicker("option", "currentText"); + + // setter + var $set: JQuery = $(".selector").datepicker("option", "currentText", "Now"); + } + + function dateFormat() { + $(".selector").datepicker({ dateFormat: "yy-mm-dd" }); + + var dateFormat: string = $(".selector").datepicker("option", "dateFormat"); + + // setter + var $set: JQuery = $(".selector").datepicker("option", "dateFormat", "yy-mm-dd"); + } + + function dayNames() { + $(".selector").datepicker({ dayNames: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"] }); + + var dayNames: string[] = $(".selector").datepicker("option", "dayNames"); + + // setter + var $set: JQuery = $(".selector").datepicker("option", "dayNames", ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"]); + } + + function dayNamesMin() { + $(".selector").datepicker({ dayNamesMin: ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"] }); + + var dayNamesMin: string[] = $(".selector").datepicker("option", "dayNamesMin"); + + // setter + var $set: JQuery = $(".selector").datepicker("option", "dayNamesMin", ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"]); + } + + function dayNamesShort() { + $(".selector").datepicker({ dayNamesShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"] }); + + var dayNamesShort: string[] = $(".selector").datepicker("option", "dayNamesShort"); + + // setter + var $set: JQuery = $(".selector").datepicker("option", "dayNamesShort", ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"]); + } + + function defaultDate() { + $(".selector").datepicker({ defaultDate: +7 }); + + var defaultDate: any = $(".selector").datepicker("option", "defaultDate"); + + // setter + var $set: JQuery = $(".selector").datepicker("option", "defaultDate", +7); + $set = $(".selector").datepicker("option", "defaultDate", new Date()); + $set = $(".selector").datepicker("option", "defaultDate", "+1m +7d"); + } + + function duration() { + $(".selector").datepicker({ duration: "slow" }); + + var duration: string = $(".selector").datepicker("option", "duration"); + + // setter + var $set: JQuery = $(".selector").datepicker("option", "duration", "slow"); + } + + function firstDay() { + $(".selector").datepicker({ firstDay: 1 }); + + var firstDay: number = $(".selector").datepicker("option", "firstDay"); + + // setter + var $set: JQuery = $(".selector").datepicker("option", "firstDay", 1); + } + + function gotoCurrent() { + $(".selector").datepicker({ gotoCurrent: true }); + + var gotoCurrent: boolean = $(".selector").datepicker("option", "gotoCurrent"); + + // setter + var $set: JQuery = $(".selector").datepicker("option", "gotoCurrent", true); + } } diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 083df7b463..26e2d6cdcb 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -180,7 +180,7 @@ declare module JQueryUI { * Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday. * String: A string in the format defined by the dateFormat option, or a relative date. Relative dates must contain value and period pairs; valid periods are "y" for years, "m" for months, "w" for weeks, and "d" for days. For example, "+1m +7d" represents one month and seven days from today. */ - defaultDateType?: any; // Date, number or string + defaultDate?: any; // Date, number or string /** * Control the speed at which the datepicker appears, it may be a time in milliseconds or a string representing one of the three predefined speeds ("slow", "normal", "fast"). */ @@ -609,11 +609,14 @@ declare module JQueryUI { orientation?: string; range?: any; // boolean or string step?: number; - // value?: number; - // values?: number[]; + value?: number; + values?: number[]; } interface SliderUIParams { + handle?: JQuery; + value?: number; + values?: number[]; } interface SliderEvent { @@ -1278,19 +1281,242 @@ interface JQuery { * Get the calculateWeek option, after initialization * * @param methodName 'option' - * @param optionName 'buttonText' + * @param optionName 'calculateWeek' */ datepicker(methodName: 'option', optionName: 'calculateWeek'): (date: Date) => string; /** * Set the calculateWeek option, after initialization * * @param methodName 'option' - * @param optionName 'buttonText' + * @param optionName 'calculateWeek' * @param calculateWeekValue A function to calculate the week of the year for a given date. The default implementation uses the ISO 8601 definition: weeks start on a Monday; the first week of the year contains the first Thursday of the year. - */ datepicker(methodName: 'option', optionName: 'calculateWeek', calculateWeekValue: (date: Date) => string): JQuery; + /** + * Get the changeMonth option, after initialization + * + * @param methodName 'option' + * @param optionName 'changeMonth' + */ + datepicker(methodName: 'option', optionName: 'changeMonth'): boolean; + /** + * Set the changeMonth option, after initialization + * + * @param methodName 'option' + * @param optionName 'changeMonth' + * @param changeMonthValue Whether the month should be rendered as a dropdown instead of text. + */ + datepicker(methodName: 'option', optionName: 'changeMonth', changeMonthValue: boolean): JQuery; + + /** + * Get the changeYear option, after initialization + * + * @param methodName 'option' + * @param optionName 'changeYear' + */ + datepicker(methodName: 'option', optionName: 'changeYear'): boolean; + /** + * Set the changeYear option, after initialization + * + * @param methodName 'option' + * @param optionName 'changeYear' + * @param changeYearValue Whether the year should be rendered as a dropdown instead of text. Use the yearRange option to control which years are made available for selection. + */ + datepicker(methodName: 'option', optionName: 'changeYear', changeYearValue: boolean): JQuery; + + /** + * Get the closeText option, after initialization + * + * @param methodName 'option' + * @param optionName 'closeText' + */ + datepicker(methodName: 'option', optionName: 'closeText'): string; + /** + * Set the closeText option, after initialization + * + * @param methodName 'option' + * @param optionName 'closeText' + * @param closeTextValue The text to display for the close link. Use the showButtonPanel option to display this button. + */ + datepicker(methodName: 'option', optionName: 'closeText', closeTextValue: string): JQuery; + + /** + * Get the constrainInput option, after initialization + * + * @param methodName 'option' + * @param optionName 'constrainInput' + */ + datepicker(methodName: 'option', optionName: 'constrainInput'): boolean; + /** + * Set the constrainInput option, after initialization + * + * @param methodName 'option' + * @param optionName 'constrainInput' + * @param constrainInputValue When true, entry in the input field is constrained to those characters allowed by the current dateFormat option. + */ + datepicker(methodName: 'option', optionName: 'constrainInput', constrainInputValue: boolean): JQuery; + + /** + * Get the currentText option, after initialization + * + * @param methodName 'option' + * @param optionName 'currentText' + */ + datepicker(methodName: 'option', optionName: 'currentText'): string; + /** + * Set the currentText option, after initialization + * + * @param methodName 'option' + * @param optionName 'currentText' + * @param currentTextValue The text to display for the current day link. Use the showButtonPanel option to display this button. + */ + datepicker(methodName: 'option', optionName: 'currentText', currentTextValue: string): JQuery; + + /** + * Get the dateFormat option, after initialization + * + * @param methodName 'option' + * @param optionName 'dateFormat' + */ + datepicker(methodName: 'option', optionName: 'dateFormat'): string; + /** + * Set the dateFormat option, after initialization + * + * @param methodName 'option' + * @param optionName 'dateFormat' + * @param dateFormatValue The format for parsed and displayed dates. For a full list of the possible formats see the formatDate function. + */ + datepicker(methodName: 'option', optionName: 'dateFormat', dateFormatValue: string): JQuery; + + /** + * Get the dayNames option, after initialization + * + * @param methodName 'option' + * @param optionName 'dayNames' + */ + datepicker(methodName: 'option', optionName: 'dayNames'): string[]; + /** + * Set the dayNames option, after initialization + * + * @param methodName 'option' + * @param optionName 'dayNames' + * @param dayNamesValue The list of long day names, starting from Sunday, for use as requested via the dateFormat option. + */ + datepicker(methodName: 'option', optionName: 'dayNames', dayNamesValue: string[]): JQuery; + + /** + * Get the dayNamesMin option, after initialization + * + * @param methodName 'option' + * @param optionName 'dayNamesMin' + */ + datepicker(methodName: 'option', optionName: 'dayNamesMin'): string[]; + /** + * Set the dayNamesMin option, after initialization + * + * @param methodName 'option' + * @param optionName 'dayNamesMin' + * @param dayNamesMinValue The list of minimised day names, starting from Sunday, for use as column headers within the datepicker. + */ + datepicker(methodName: 'option', optionName: 'dayNamesMin', dayNamesMinValue: string[]): JQuery; + + /** + * Get the dayNamesShort option, after initialization + * + * @param methodName 'option' + * @param optionName 'dayNamesShort' + */ + datepicker(methodName: 'option', optionName: 'dayNamesShort'): string[]; + /** + * Set the dayNamesShort option, after initialization + * + * @param methodName 'option' + * @param optionName 'dayNamesShort' + * @param dayNamesShortValue The list of abbreviated day names, starting from Sunday, for use as requested via the dateFormat option. + */ + datepicker(methodName: 'option', optionName: 'dayNamesShort', dayNamesShortValue: string[]): JQuery; + + /** + * Get the defaultDate option, after initialization + * + * @param methodName 'option' + * @param optionName 'defaultDate' + */ + datepicker(methodName: 'option', optionName: 'defaultDate'): any; + /** + * Set the defaultDate option, after initialization + * + * @param methodName 'option' + * @param optionName 'defaultDate' + * @param defaultDateValue A date object containing the default date. + */ + datepicker(methodName: 'option', optionName: 'defaultDate', defaultDateValue: Date): JQuery; + /** + * Set the defaultDate option, after initialization + * + * @param methodName 'option' + * @param optionName 'defaultDate' + * @param defaultDateValue A number of days from today. For example 2 represents two days from today and -1 represents yesterday. + */ + datepicker(methodName: 'option', optionName: 'defaultDate', defaultDateValue: number): JQuery; + /** + * Set the defaultDate option, after initialization + * + * @param methodName 'option' + * @param optionName 'defaultDate' + * @param defaultDateValue A string in the format defined by the dateFormat option, or a relative date. Relative dates must contain value and period pairs; valid periods are "y" for years, "m" for months, "w" for weeks, and "d" for days. For example, "+1m +7d" represents one month and seven days from today. + */ + datepicker(methodName: 'option', optionName: 'defaultDate', defaultDateValue: string): JQuery; + + /** + * Get the duration option, after initialization + * + * @param methodName 'option' + * @param optionName 'duration' + */ + datepicker(methodName: 'option', optionName: 'duration'): string; + /** + * Set the duration option, after initialization + * + * @param methodName 'option' + * @param optionName 'duration' + * @param durationValue Control the speed at which the datepicker appears, it may be a time in milliseconds or a string representing one of the three predefined speeds ("slow", "normal", "fast"). + */ + datepicker(methodName: 'option', optionName: 'duration', durationValue: string): JQuery; + + /** + * Get the firstDay option, after initialization + * + * @param methodName 'option' + * @param optionName 'firstDay' + */ + datepicker(methodName: 'option', optionName: 'firstDay'): number; + /** + * Set the firstDay option, after initialization + * + * @param methodName 'option' + * @param optionName 'firstDay' + * @param firstDayValue Set the first day of the week: Sunday is 0, Monday is 1, etc. + */ + datepicker(methodName: 'option', optionName: 'firstDay', firstDayValue: number): JQuery; + + /** + * Get the gotoCurrent option, after initialization + * + * @param methodName 'option' + * @param optionName 'gotoCurrent' + */ + datepicker(methodName: 'option', optionName: 'gotoCurrent'): boolean; + /** + * Set the gotoCurrent option, after initialization + * + * @param methodName 'option' + * @param optionName 'gotoCurrent' + * @param gotoCurrentValue When true, the current day link moves to the currently selected date instead of today. + */ + datepicker(methodName: 'option', optionName: 'gotoCurrent', gotoCurrentValue: boolean): JQuery; + /** * Gets the value currently associated with the specified optionName. * diff --git a/js-fixtures/fixtures.d.ts b/js-fixtures/fixtures.d.ts index 92bd548e0e..4adb6f378f 100644 --- a/js-fixtures/fixtures.d.ts +++ b/js-fixtures/fixtures.d.ts @@ -1,7 +1,7 @@ // Type definitions for js-fixtures 1.2.0 // Project: https://github.com/badunk/js-fixtures // Definitions by: Kazi Manzur Rashid -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped interface Fixtures { path: string; @@ -18,4 +18,4 @@ interface Fixtures { cleanUp(): void; } -declare var fixtures: Fixtures; \ No newline at end of file +declare var fixtures: Fixtures; diff --git a/js-signals/js-signals.d.ts b/js-signals/js-signals.d.ts index 4d7d33344e..c64c6db2a2 100644 --- a/js-signals/js-signals.d.ts +++ b/js-signals/js-signals.d.ts @@ -1,7 +1,7 @@ // Type definitions for JS-Signals // Project: http://millermedeiros.github.io/js-signals/ // Definitions by: Diullei Gomes -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped interface SignalBinding { active: boolean; diff --git a/js-url/js-url-test.ts b/js-url/js-url-test.ts new file mode 100644 index 0000000000..0b26f6175b --- /dev/null +++ b/js-url/js-url-test.ts @@ -0,0 +1,9 @@ +/// + +url(); + +url('domain'); +url(1); + +url('domain', 'test.www.example.com/path/here'); +url(-1, 'test.www.example.com/path/here'); diff --git a/js-url/js-url.d.ts b/js-url/js-url.d.ts new file mode 100644 index 0000000000..e5df9c246c --- /dev/null +++ b/js-url/js-url.d.ts @@ -0,0 +1,14 @@ +// Type definitions for url v1.8.6 +// Project: https://github.com/websanova/js-url +// Definitions by: MIZUNE Pine +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface UrlStatic { + (): string; + (pattern: string): string; + (pattern: number): string; + (pattern: string, url: string): string; + (pattern: number, url: string): string; +} + +declare var url: UrlStatic; diff --git a/js-yaml/js-yaml.d.ts b/js-yaml/js-yaml.d.ts index 0607b48916..0de5a8f6b3 100644 --- a/js-yaml/js-yaml.d.ts +++ b/js-yaml/js-yaml.d.ts @@ -3,7 +3,7 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module 'js-yaml' { +declare module jsyaml { export function safeLoad(str: string, opts?: LoadOptions): any; export function load(str: string, opts?: LoadOptions): any; @@ -46,3 +46,7 @@ declare module 'js-yaml' { // all supported YAML types. export var DEFAULT_FULL_SCHEMA: any; } + +declare module 'js-yaml' { + export = jsyaml; +} diff --git a/jsfl/jsfl.d.ts b/jsfl/jsfl.d.ts index a8c9911d27..5ef860e85e 100644 --- a/jsfl/jsfl.d.ts +++ b/jsfl/jsfl.d.ts @@ -466,8 +466,9 @@ interface FlashDocument { id: number; // A unique integer (assigned automatically) that library: FlashLibrary; // Read-only; the library object for a document. livePreview: boolean; // A Boolean value that specifies if Live Preview is - name: number; // Read-only; a string that represents the name of a - path: number; // Read-only; a string that represents the path of the + name: string; // Read-only; a string that represents the name of a + path: string; // Read-only; a string that represents the path of the + pathURI: string; // Read-only property; a string that represents the path of the document, expressed as a file:/// URI. If the document has never been saved, this property is undefined. publishProfiles: string[]; // Read-only; an array of the publish profile names for /** Read-only; the current ScreenOutline object for the */ @@ -1146,6 +1147,8 @@ interface FlashTimeline { /** A string that represents the name of the current */ name: string; + + libraryItem:FlashItem; } interface FlashPath { @@ -1271,9 +1274,42 @@ interface FlashTools { toolObjs; } +declare class SpriteSheetExporter { + addBitmap(item:FlashItem); + addSymbol(item:FlashItem, name?:string, beginFrame?:number, endFrame?:number); + algorithm:string; + allowRotate:boolean; + allowTrimming:boolean; + app:string; + autoSize:boolean; + beginExport(); + borderPadding:number; + canBorderPad:boolean; + canRotate:boolean; + canTrim:boolean; + canShapePad:boolean; + canStackDuplicateFrames:boolean; + changeSymbol(); + exportSpriteSheet(fileURL:string,option:Object,writeMetaData?:boolean):string; + format:string; + image:string; + layoutFormat:string; + maxSheetHeight:number; + maxSheetWidth:number; + overflowed:boolean; + removeBitmap(); + removeSymbol(); + shapePadding:number; + sheetHeight:number; + sheetWidth:number; + stackDuplicateFrames:boolean; + version:string; +} + + interface FlashFL { addEventListener(eventType, callbackFunction); - browseForFileURL(browseType, title?, previewArea?); + browseForFileURL(browseType, title?, previewArea?, fileFilter?); browseForFolderURL(description: string); clearPublishCache(): void; clipCopyString(string: string): void; diff --git a/jsplumb/jquery.jsPlumb.d.ts b/jsplumb/jquery.jsPlumb.d.ts index ffa26eea80..39d5bf8694 100644 --- a/jsplumb/jquery.jsPlumb.d.ts +++ b/jsplumb/jquery.jsPlumb.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jsPlumb 1.3.16 jQuery adapter. +// Type definitions for jsPlumb 1.3.16 jQuery adapter // Project: http://jsplumb.org // Definitions by: Steve Shearn // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -19,26 +19,26 @@ interface jsPlumbInstance { addEndpoint(ep: string): any; removeClass(el: any, clazz: string): void; hasClass(el: any, clazz: string): void; - draggable(el: string, options?: DragOptions): jsPlumbInstance; - draggable(ids: string[], options?: DragOptions): jsPlumbInstance; + draggable(el: string, options?: DragOptions): jsPlumbInstance; + draggable(ids: string[], options?: DragOptions): jsPlumbInstance; connect(connection: ConnectParams, referenceParams?: ConnectParams): Connection; makeSource(el: string, options: SourceOptions): void; makeTarget(el: string, options: TargetOptions): void; repaintEverything(): void; detachEveryConnection(): void; detachAllConnections(el: string): void; - removeAllEndpoints(el: string, recurse?: boolean): jsPlumbInstance; - removeAllEndpoints(el: Element, recurse?: boolean): jsPlumbInstance; + removeAllEndpoints(el: string, recurse?: boolean): jsPlumbInstance; + removeAllEndpoints(el: Element, recurse?: boolean): jsPlumbInstance; select(params: SelectParams): Connections; getConnections(options?: any, flat?: any): any[]; - deleteEndpoint(uuid: string, doNotRepaintAfterwards?: boolean): jsPlumbInstance; - deleteEndpoint(endpoint: Endpoint, doNotRepaintAfterwards?: boolean): jsPlumbInstance; - repaint(el: string): jsPlumbInstance; - repaint(el: Element): jsPlumbInstance; - - SVG: string; - CANVAS: string; - VML: string; + deleteEndpoint(uuid: string, doNotRepaintAfterwards?: boolean): jsPlumbInstance; + deleteEndpoint(endpoint: Endpoint, doNotRepaintAfterwards?: boolean): jsPlumbInstance; + repaint(el: string): jsPlumbInstance; + repaint(el: Element): jsPlumbInstance; + + SVG: string; + CANVAS: string; + VML: string; } interface Defaults { @@ -48,8 +48,8 @@ interface Defaults { ConnectionsDetachable?: boolean; ReattachConnections?: boolean; ConnectionOverlays?: any[][]; - Container?: any; // string(selector or id) or element - DragOptions?: DragOptions; + Container?: any; // string(selector or id) or element + DragOptions?: DragOptions; } interface PaintStyle { @@ -76,8 +76,8 @@ interface Connections { } interface ConnectParams { - source?: any; // string, element or endpoint - target?: any; // string, element or endpoint + source?: any; // string, element or endpoint + target?: any; // string, element or endpoint detachable?: boolean; deleteEndpointsOnDetach?: boolean; endPoint?: string; @@ -118,11 +118,11 @@ interface SelectParams { target: string; } -interface Connection { - setDetachable(detachable: boolean): void; - setParameter(name: string, value: T): void; - endpoints: Endpoint[]; -} - -interface Endpoint { -} \ No newline at end of file +interface Connection { + setDetachable(detachable: boolean): void; + setParameter(name: string, value: T): void; + endpoints: Endpoint[]; +} + +interface Endpoint { +} diff --git a/jsrender/jsrender.d.ts b/jsrender/jsrender.d.ts index 8cdfa13a10..755b17f932 100644 --- a/jsrender/jsrender.d.ts +++ b/jsrender/jsrender.d.ts @@ -1,6 +1,6 @@ // Type definitions for JsRender // Project: http://www.jsviews.com/#jsrender -// Definitions by: https://github.com/zakki +// Definitions by: Kensuke Matsuzaki // Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/jstree/jstree-tests.ts b/jstree/jstree-tests.ts new file mode 100644 index 0000000000..ddd1c60ddd --- /dev/null +++ b/jstree/jstree-tests.ts @@ -0,0 +1,67 @@ +/// + +// gets version of lib +var version: string = $.jstree.version; + +// create new instance +var instance1: JSTree = $('div').jstree(); + +// get existing reference +var existingReference: JSTree = $.jstree.reference('sds'); + +// advanced tree creation +var advancedTree = $("#briefcasetree").jstree({ + plugins: ['contextmenu', 'dnd', 'state', 'types', 'unique'], + core: { + check_callback: true, + data: { + cache: false, + url: 'Briefcase/GetProjectTree', + async: true, + type: 'GET', + dataType: 'json' + } + }, + types: { + max_depth: -2, + max_children: -2, + valid_children: ['root_folder_all', 'root_folder'], + types: { + root_folder_all: { + valid_children: ['sub_folder_all'], + start_drag: false, + move_node: false, + delete_node: false, + remove: false + }, + sub_folder_all: { + valid_children: ['sub_folder_all', 'saved_all'], + start_drag: false, + move_node: false, + delete_node: false, + remove: false + }, + saved_all: { + valid_children: [], + start_drag: false, + move_node: false, + delete_node: false, + remove: false + }, + root_folder: { + valid_children: ['sub_folder'], + start_drag: false, + move_node: false, + delete_node: false, + remove: false + }, + sub_folder: { + valid_children: ['sub_folder', 'saved_single'] + }, + saved_single: { + valid_children: 'none' + } + } + } + }); + diff --git a/jstree/jstree.d.ts b/jstree/jstree.d.ts new file mode 100644 index 0000000000..4039795bab --- /dev/null +++ b/jstree/jstree.d.ts @@ -0,0 +1,1127 @@ +// Type definitions for jsTree v3.0.0 +// Project: http://www.jstree.com/ +// Definitions by: Adam Pluciński +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface JQueryStatic { + /** + * holds all jstree related functions and variables, + * including the actual class and methods to create, + * access and manipulate instances. + * @property jstree + * @type {JSTreeStatic} + */ + jstree?: JSTreeStatic; + +} + +interface JSTreeStatic { + /** + * specifies the jstree version in use + * @property version + * @type {string} + */ + version: string; + + /** + * holds all the default options used when creating new instances + * @property defaults + * @type {JSTreeStaticDefaults} + */ + defaults: JSTreeStaticDefaults; + + /** + * stores all loaded jstree plugins (used internally) + */ + plugins: any[]; + path: string; + idregex:any; + /** + * creates a jstree instance + * @param el the element to create the instance on, can be jQuery extended or a selector + * @param options {JSTreeOptions} options for this instance (extends `$.jstree.defaults`) + * @returns {JSTree} the new instance + */ + create(el: any, options?: JSTreeStaticDefaults): JSTree; + + /** + * the jstree class constructor, used only internally + * @param id {number} this instance's index + */ + core(id: number): void; + + /** + * get a reference to an existing instance + * + * __Examples__ + * + * $.jstree.reference('tree'); + * $.jstree.reference('#tree'); + * $.jstree.reference('branch'); + * $.jstree.reference('#branch'); + * + * @param {String} selector + * @returns {JSTree|null} the instance or `null` if not found + */ + reference(selector: string): JSTree; + + /** + * get a reference to an existing instance + * + * __Examples__ + * + * $.jstree.reference(document.getElementByID('tree')); + * $.jstree.reference(document.getElementByID('branch')); + * + * @param {HTMLElement} element + * @returns {JSTree|null} the instance or `null` if not found + */ + reference(element: HTMLElement): JSTree; + + /** + * get a reference to an existing instance + * + * __Examples__ + * + * $.jstree.reference($('#tree')); + * $.jstree.reference($('#branch')); + * + * @param {JQuery} object + * @returns {JSTree|null} the instance or `null` if not found + */ + reference(object: JQuery): JSTree; +} + +interface JSTreeStaticDefaults { + /** + * configure which plugins will be active on an instance. + * Should be an array of strings, where each element is a plugin name. + * The default is [] + */ + plugins: string[]; + /** + * stores all defaults for the core + */ + core: JSTreeStaticDefaultsCore; + /** + * stores all defaults for the checkbox plugin + */ + checkbox?: JSTreeStaticDefaultsCheckbox; + /** + * stores all defaults for the contextmenu plugin + */ + contextmenu?: JSTreeStaticDefaultsContextMenu; + /** + * stores all defaults for the drag'n'drop plugin + */ + dnd?: JSTreeStaticDefaultsDragNDrop; + /** + * stores all defaults for the search plugin + */ + search?: JSTreeStaticDefaultsSearch; + /** + * the settings function used to sort the nodes. + * It is executed in the tree's context, accepts two nodes as arguments and should return `1` or `-1`. + * @name $.jstree.defaults.sort + * @plugin sort + */ + sort?: (x: any, y: any) => number; + /** + * stores all defaults for the state plugin + */ + state?: JSTreeStaticDefaultsState; + /** + * An object storing all types as key value pairs, + * where the key is the type name and the value is an object + * that could contain following keys (all optional). + * max_children the maximum number of immediate children this node type can have. + * Do not specify or set to -1 for unlimited. + * max_depth the maximum number of nesting this node type can have. + * A value of 1 would mean that the node can have children, but no grandchildren. + * Do not specify or set to -1 for unlimited. + * valid_children an array of node type strings, that nodes of this type can have as children. + * Do not specify or set to -1 for no limits. + * icon a string - can be a path to an icon or a className, if using an image + * that is in the current directory use a ./ prefix, otherwise it will be detected as a class. + * Omit to use the default icon from your theme. + * There are two predefined types: + * # represents the root of the tree, for example max_children would control the maximum number of root nodes. + * default represents the default node - any settings here will be applied to all nodes that do not have a type specified. + */ + types?: any; + /** + * stores all defaults for the unique plugin + * @name $.jstree.defaults.unique + * @plugin unique + */ + unique?: JSTreeStaticDefaultsUnique; +} + +interface JSTreeStaticDefaultsCore { + /** + * data configuration + * + * If left as `false` the HTML inside the jstree container element is used to populate the tree (that should be an unordered list with list items). + * + * You can also pass in a HTML string or a JSON array here. + * + * It is possible to pass in a standard jQuery-like AJAX config and jstree will automatically determine if the response is JSON or HTML and use that to populate the tree. + * In addition to the standard jQuery ajax options here you can suppy functions for `data` and `url`, the functions will be run in the current instance's scope and a param will be passed indicating which node is being loaded, the return value of those functions will be used. + * + * The last option is to specify a function, that function will receive the node being loaded as argument and a second param which is a function which should be called with the result. + * + * __Examples__ + * + * // AJAX + * $('#tree').jstree({ + * 'core' : { + * 'data' : { + * 'url' : '/get/children/', + * 'data' : function (node) { + * return { 'id' : node.id }; + * } + * } + * }); + * + * // direct data + * $('#tree').jstree({ + * 'core' : { + * 'data' : [ + * 'Simple root node', + * { + * 'id' : 'node_2', + * 'text' : 'Root node with options', + * 'state' : { 'opened' : true, 'selected' : true }, + * 'children' : [ { 'text' : 'Child 1' }, 'Child 2'] + * } + * ] + * }); + * + * // function + * $('#tree').jstree({ + * 'core' : { + * 'data' : function (obj, callback) { + * callback.call(this, ['Root 1', 'Root 2']); + * } + * }); + * + * @name $.jstree.defaults.core.data + */ + data?: any; + /** + * configure the various strings used throughout the tree + * + * You can use an object where the key is the string you need to replace and the value is your replacement. + * Another option is to specify a function which will be called with an argument of the needed string and should return the replacement. + * If left as `false` no replacement is made. + * + * __Examples__ + * + * $('#tree').jstree({ + * 'core' : { + * 'strings' : { + * 'Loading...' : 'Please wait ...' + * } + * } + * }); + * + * @name $.jstree.defaults.core.strings + */ + strings?: any; + + /** + * determines what happens when a user tries to modify the structure of the tree + * If left as `false` all operations like create, rename, delete, move or copy are prevented. + * You can set this to `true` to allow all interactions or use a function to have better control. + * + * __Examples__ + * + * $('#tree').jstree({ + * 'core' : { + * 'check_callback' : function (operation, node, node_parent, node_position, more) { + * // operation can be 'create_node', 'rename_node', 'delete_node', 'move_node' or 'copy_node' + * // in case of 'rename_node' node_position is filled with the new node name + * return operation === 'rename_node' ? true : false; + * } + * } + * }); + * + * @name $.jstree.defaults.core.check_callback + */ + check_callback?: any; + + /** + * a callback called with a single object parameter in the instance's scope when something goes wrong (operation prevented, ajax failed, etc) + * @name $.jstree.defaults.core.error + */ + error: () => any; + + /** + * the open / close animation duration in milliseconds - set this to `false` to disable the animation (default is `200`) + * @name $.jstree.defaults.core.animation + */ + animation?: any; + /** + * a boolean indicating if multiple nodes can be selected + * @name $.jstree.defaults.core.multiple + */ + multiple?: boolean; + /** + * theme configuration object + * @name $.jstree.defaults.core.themes + */ + themes?: JSTreeStaticDefaultsCoreThemes; + /** + * if left as `true` all parents of all selected nodes will be opened once the tree loads (so that all selected nodes are visible to the user) + * @name $.jstree.defaults.core.expand_selected_onload + */ + expand_selected_onload?: boolean; +} + +interface JSTreeStaticDefaultsCoreThemes { + /** + * the name of the theme to use (if left as false the default theme is used) + */ + name?: string; + /** + * the URL of the theme's CSS file, leave this as false if you have manually + * included the theme CSS (recommended). + * You can set this to true too which will try to autoload the theme. + */ + url?: string; + /** + * the location of all jstree themes - only used if url is set to true + */ + dir?: string; + /** + * a boolean indicating if connecting dots are shown + */ + dots?: boolean; + /** + * a boolean indicating if node icons are shown + */ + icons?: boolean; + /** + * a boolean indicating if the tree background is striped + */ + stripes?: boolean; + /** + * a string (or boolean false) specifying the theme + * variant to use (if the theme supports variants) + */ + variant?: any; + /** + * a boolean specifying if a reponsive version of the theme should kick + * in on smaller screens (if the theme supports it). Defaults to true. + */ + responsive?: boolean; + +} + +interface JSTreeStaticDefaultsCheckbox { + /** + * a boolean indicating if checkboxes should be visible (can be changed at a later time using `show_checkboxes()` and `hide_checkboxes`). Defaults to `true`. + * @name $.jstree.defaults.checkbox.visible + * @plugin checkbox + */ + visible: boolean; + /** + * a boolean indicating if checkboxes should cascade down and have an undetermined state. Defaults to `true`. + * @name $.jstree.defaults.checkbox.three_state + * @plugin checkbox + */ + three_state: boolean; + /** + * a boolean indicating if clicking anywhere on the node should act as clicking on the checkbox. Defaults to `true`. + * @name $.jstree.defaults.checkbox.whole_node + * @plugin checkbox + */ + whole_node: boolean; + /** + * a boolean indicating if the selected style of a node should be kept, or removed. Defaults to `true`. + * @name $.jstree.defaults.checkbox.keep_selected_style + * @plugin checkbox + */ + keep_selected_style: boolean; + /** + * This setting controls how cascading and undetermined nodes are applied. + * If 'up' is in the string - cascading up is enabled, if 'down' is in the string - cascading down is enabled, if 'undetermined' is in the string - undetermined nodes will be used. + * If `three_state` is set to `true` this setting is automatically set to 'up+down+undetermined'. Defaults to ''. + * @name $.jstree.defaults.checkbox.cascade + * @plugin checkbox + */ + cascade:boolean; +} + +interface JSTreeStaticDefaultsContextMenu { + /** + * a boolean indicating if the node should be selected when the context menu is invoked on it. Defaults to `true`. + * @name $.jstree.defaults.contextmenu.select_node + * @plugin contextmenu + */ + select_node: boolean; + /** + * a boolean indicating if the menu should be shown aligned with the node. Defaults to `true`, otherwise the mouse coordinates are used. + * @name $.jstree.defaults.contextmenu.show_at_node + * @plugin contextmenu + */ + show_at_node: boolean; + /** + * an object of actions, or a function that accepts a node and a callback function and calls the callback function with an object of actions available for that node (you can also return the items too). + * + * Each action consists of a key (a unique name) and a value which is an object with the following properties (only label and action are required): + * + * * `separator_before` - a boolean indicating if there should be a separator before this item + * * `separator_after` - a boolean indicating if there should be a separator after this item + * * `_disabled` - a boolean indicating if this action should be disabled + * * `label` - a string - the name of the action (could be a function returning a string) + * * `action` - a function to be executed if this item is chosen + * * `icon` - a string, can be a path to an icon or a className, if using an image that is in the current directory use a `./` prefix, otherwise it will be detected as a class + * * `shortcut` - keyCode which will trigger the action if the menu is open (for example `113` for rename, which equals F2) + * * `shortcut_label` - shortcut label (like for example `F2` for rename) + * + * @name $.jstree.defaults.contextmenu.items + * @plugin contextmenu + */ + items: any; +} + +interface JSTreeStaticDefaultsDragNDrop { + /** + * a boolean indicating if a copy should be possible while dragging (by pressint the meta key or Ctrl). Defaults to `true`. + * @name $.jstree.defaults.dnd.copy + * @plugin dnd + */ + copy: boolean; + /** + * a number indicating how long a node should remain hovered while dragging to be opened. Defaults to `500`. + * @name $.jstree.defaults.dnd.open_timeout + * @plugin dnd + */ + open_timeout: number; + + /** + * a function invoked each time a node is about to be dragged, invoked in the tree's scope and receives the nodes about to be dragged as an argument (array) - return `false` to prevent dragging + * @name $.jstree.defaults.dnd.is_draggable + * @plugin dnd + */ + is_draggable: boolean; + + /** + * a boolean indicating if checks should constantly be made while the user is dragging the node (as opposed to checking only on drop), default is `true` + * @name $.jstree.defaults.dnd.check_while_dragging + * @plugin dnd + */ + check_while_dragging: boolean; + + /** + * a boolean indicating if nodes from this tree should only be copied with dnd (as opposed to moved), default is `false` + * @name $.jstree.defaults.dnd.always_copy + * @plugin dnd + */ + always_copy: boolean; + + /** + * when dropping a node "inside", this setting indicates the position the node should go to - it can be an integer or a string: "first" (same as 0) or "last", default is `0` + * @name $.jstree.defaults.dnd.inside_pos + * @plugin dnd + */ + inside_pos: any; +} + +interface JSTreeStaticDefaultsSearch { + /** + * a jQuery-like AJAX config, which jstree uses if a server should be queried for results. + * + * A `str` (which is the search string) parameter will be added with the request. + * The expected result is a JSON array with nodes that need to be opened so that matching nodes will be revealed. + * Leave this setting as `false` to not query the server. You can also set this to a function, + * which will be invoked in the instance's scope and receive 2 parameters - + * the search string and the callback to call with the array of nodes to load. + * @name $.jstree.defaults.search.ajax + * @plugin search + */ + ajax: any; + /** + * Indicates if the search should be fuzzy or not (should `chnd3` match `child node 3`). Default is `true`. + * @name $.jstree.defaults.search.fuzzy + * @plugin search + */ + fuzzy: boolean; + /** + * Indicates if the search should be case sensitive. Default is `false`. + * @name $.jstree.defaults.search.case_sensitive + * @plugin search + */ + case_sensitive: boolean; + /** + * Indicates if the tree should be filtered to show only matching nodes + * (keep in mind this can be a heavy on large trees in old browsers). Default is `false`. + * @name $.jstree.defaults.search.show_only_matches + * @plugin search + */ + show_only_matches: boolean; + /** + * Indicates if all nodes opened to reveal the search result, + * should be closed when the search is cleared or a new search is performed. Default is `true`. + * @name $.jstree.defaults.search.close_opened_onclear + * @plugin search + */ + close_opened_onclear: boolean; + + /** + * Indicates if only leaf nodes should be included in search results. Default is `false`. + * @name $.jstree.defaults.search.search_leaves_only + * @plugin search + */ + search_leaves_only: boolean; +} + +interface JSTreeStaticDefaultsState { + /** + * A string for the key to use when saving the current tree (change if using multiple trees in your project). Defaults to `jstree`. + * @name $.jstree.defaults.state.key + * @plugin state + */ + key: string; + /** + * A space separated list of events that trigger a state save. Defaults to `changed.jstree open_node.jstree close_node.jstree`. + * @name $.jstree.defaults.state.events + * @plugin state + */ + events: string; + + /** + * Time in milliseconds after which the state will expire. Defaults to 'false' meaning - no expire. + * @name $.jstree.defaults.state.ttl + * @plugin state + */ + ttl: any; + + /** + * A function that will be executed prior to restoring state with one argument - the state object. Can be used to clear unwanted parts of the state. + * @name $.jstree.defaults.state.filter + * @plugin state + */ + filter: any; + +} + +interface JSTreeStaticDefaultsUnique { + /** + * Indicates if the comparison should be case sensitive. Default is `false`. + * @name $.jstree.defaults.unique.case_sensitive + * @plugin unique + */ + case_sensitive:boolean; +} + +interface JQuery { + jstree(): JSTree; + jstree(options: JSTreeStaticDefaults): JSTree; + jstree(arg: boolean): JSTree; + jstree(...args: any[]): JSTree; +} + +interface JSTree extends JQuery { + /** + * destroy an instance + * @name destroy() + * @param {Boolean} keep_html if not set to `true` the container will be emptied, otherwise the current DOM elements will be kept intact + */ + destroy: (keep_html?: boolean) => void; + /** + * returns the jQuery extended instance container + * @name get_container() + * @return {jQuery} + */ + get_container: () => JQuery; + /** + * get the JSON representation of a node (or the actual jQuery extended DOM node) by using any input (child DOM element, ID string, selector, etc) + * @name get_node(obj [, as_dom]) + * @param {mixed} obj + * @param {Boolean} as_dom + * @return {Object|jQuery} + */ + get_node: (obj: any, as_dom?: boolean) => JQuery; + /** + * get the path to a node, either consisting of node texts, or of node IDs, optionally glued together (otherwise an array) + * @name get_path(obj [, glue, ids]) + * @param {mixed} obj the node + * @param {String} glue if you want the path as a string - pass the glue here (for example '/'), if a falsy value is supplied here, an array is returned + * @param {Boolean} ids if set to true build the path using ID, otherwise node text is used + * @return {mixed} + */ + get_path: (obj:any, glue:string, ids:boolean) => JQuery; + /** + * get the next visible node that is below the `obj` node. If `strict` is set to `true` only sibling nodes are returned. + * @name get_next_dom(obj [, strict]) + * @param {mixed} obj + * @param {Boolean} strict + * @return {jQuery} + */ + get_next_dom: (obj:any, strict?:boolean) => JQuery; + /** + * get the previous visible node that is above the `obj` node. If `strict` is set to `true` only sibling nodes are returned. + * @name get_prev_dom(obj [, strict]) + * @param {mixed} obj + * @param {Boolean} strict + * @return {jQuery} + */ + get_prev_dom: (obj: any, strict?: boolean) => JQuery; + /** + * get the parent ID of a node + * @name get_parent(obj) + * @param {mixed} obj + * @return {String} + */ + get_parent: (obj: any) => string; + /** + * get a jQuery collection of all the children of a node (node must be rendered) + * @name get_children_dom(obj) + * @param {mixed} obj + * @return {jQuery} + */ + get_children_dom: (obj: any) => JQuery; + /** + * checks if a node has children + * @name is_parent(obj) + * @param {mixed} obj + * @return {Boolean} + */ + is_parent: (obj: any) => boolean; + /** + * checks if a node is loaded (its children are available) + * @name is_loaded(obj) + * @param {mixed} obj + * @return {Boolean} + */ + is_loaded: (obj: any) => boolean; + /** + * check if a node is currently loading (fetching children) + * @name is_loading(obj) + * @param {mixed} obj + * @return {Boolean} + */ + is_loading: (obj: any) => boolean; + /** + * check if a node is opened + * @name is_open(obj) + * @param {mixed} obj + * @return {Boolean} + */ + is_open: (obj: any) => boolean; + /** + * check if a node is in a closed state + * @name is_closed(obj) + * @param {mixed} obj + * @return {Boolean} + */ + is_closed: (obj: any) => boolean; + /** + * check if a node has no children + * @name is_leaf(obj) + * @param {mixed} obj + * @return {Boolean} + */ + is_leaf: (obj: any) => boolean; + /** + * loads a node (fetches its children using the `core.data` setting). Multiple nodes can be passed to by using an array. + * @name load_node(obj [, callback]) + * @param {mixed} obj + * @param {function} callback a function to be executed once loading is conplete, the function is executed in the instance's scope + * and receives two arguments - the node and a boolean status + * @return {Boolean} + * @trigger load_node.jstree + */ + load_node: (obj: any, callback: any) => boolean; + /** + * redraws all nodes that need to be redrawn or optionally - the whole tree + * @name redraw([full]) + * @param {Boolean} full if set to `true` all nodes are redrawn. + */ + redraw: (full?: boolean) => void; + /** + * opens a node, revaling its children. If the node is not loaded it will be loaded and opened once ready. + * @name open_node(obj [, callback, animation]) + * @param {mixed} obj the node to open + * @param {Function} callback a function to execute once the node is opened + * @param {Number} animation the animation duration in milliseconds + * when opening the node (overrides the `core.animation` setting). Use `false` for no animation. + * @trigger open_node.jstree, after_open.jstree, before_open.jstree + */ + open_node: (obj: any, callback?: any, animation?: any) => void; + /** + * closes a node, hiding its children + * @name close_node(obj [, animation]) + * @param {mixed} obj the node to close + * @param {Number} animation the animation duration in milliseconds + * when closing the node (overrides the `core.animation` setting). Use `false` for no animation. + * @trigger close_node.jstree, after_close.jstree + */ + close_node: (obj: any, animation?: any) => void; + /** + * toggles a node - closing it if it is open, opening it if it is closed + * @name toggle_node(obj) + * @param {mixed} obj the node to toggle + */ + toggle_node: (obj: any) => void; + /** + * opens all nodes within a node (or the tree), revaling their children. If the node is not loaded it will be loaded and opened once ready. + * @name open_all([obj, animation, original_obj]) + * @param {mixed} obj the node to open recursively, omit to open all nodes in the tree + * @param {Number} animation the animation duration in milliseconds when opening the nodes, the default is no animation + * @param {jQuery} reference to the node that started the process (internal use) + * @trigger open_all.jstree + */ + open_all: (obj?: any, animation?: number, original_obj?: any) => void; + /** + * closes all nodes within a node (or the tree), revaling their children + * @name close_all([obj, animation]) + * @param {mixed} obj the node to close recursively, omit to close all nodes in the tree + * @param {Number} animation the animation duration in milliseconds when closing the nodes, the default is no animation + * @trigger close_all.jstree + */ + close_all: (obj?: any, animation?: number) => void; + /** + * checks if a node is disabled (not selectable) + * @name is_disabled(obj) + * @param {mixed} obj + * @return {Boolean} + */ + is_disabled: (obj: any) => boolean; + /** + * enables a node - so that it can be selected + * @name enable_node(obj) + * @param {mixed} obj the node to enable + * @trigger enable_node.jstree + */ + enable_node: (obj: any) => boolean; + /** + * disables a node - so that it can not be selected + * @name disable_node(obj) + * @param {mixed} obj the node to disable + * @trigger disable_node.jstree + */ + disable_node: (obj: any) => boolean; + /** + * select a node + * @name select_node(obj [, supress_event, prevent_open]) + * @param {mixed} obj an array can be used to select multiple nodes + * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered + * @param {Boolean} prevent_open if set to `true` parents of the selected node won't be opened + * @trigger select_node.jstree, changed.jstree + */ + select_node: (obj: any, supress_event?: boolean, prevent_open?: boolean, e?:any) => void; + /** + * deselect a node + * @name deselect_node(obj [, supress_event]) + * @param {mixed} obj an array can be used to deselect multiple nodes + * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered + * @trigger deselect_node.jstree, changed.jstree + */ + deselect_node: (obj: any, supress_event?: boolean, e?:any) => void; + /** + * select all nodes in the tree + * @name select_all([supress_event]) + * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered + * @trigger select_all.jstree, changed.jstree + */ + select_all: (supress_event?: boolean) => void; + /** + * deselect all selected nodes + * @name deselect_all([supress_event]) + * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered + * @trigger deselect_all.jstree, changed.jstree + */ + deselect_all: (supress_event?: boolean) => void; + /** + * checks if a node is selected + * @name is_selected(obj) + * @param {mixed} obj + * @return {Boolean} + */ + is_selected: (obj: any) => boolean; + /** + * get an array of all selected nodes + * @name get_selected([full]) + * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned + * @return {Array} + */ + get_selected: (full?: any) => string[]; + /** + * get an array of all top level selected nodes (ignoring children of selected nodes) + * @name get_top_selected([full]) + * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned + * @return {Array} + */ + get_top_selected: (full?: any) => string[]; + /** + * get an array of all bottom level selected nodes (ignoring selected parents) + * @name get_top_selected([full]) + * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned + * @return {Array} + */ + get_bottom_selected: (full?: any) => string[]; + /** + * refreshes the tree - all nodes are reloaded with calls to `load_node`. + * @name refresh() + * @param {Boolean} skip_loading an option to skip showing the loading indicator + * @trigger refresh.jstree + */ + refresh: (skip_loading:boolean) => void; + /** + * refreshes a node in the tree (reload its children) all opened nodes inside that node are reloaded with calls to `load_node`. + * @name refresh_node(obj) + * @param {Boolean} skip_loading an option to skip showing the loading indicator + * @trigger refresh.jstree + */ + refresh_node: (obj:any) => void; + /** + * set (change) the ID of a node + * @name set_id(obj, id) + * @param {mixed} obj the node + * @param {String} id the new ID + * @return {Boolean} + */ + set_id: (obj: any, id: string) => void; + /** + * get the text value of a node + * @name get_text(obj) + * @param {mixed} obj the node + * @return {String} + */ + get_text: (obj: any) => string; + /** + * gets a JSON representation of a node (or the whole tree) + * @name get_json([obj, options]) + * @param {mixed} obj + * @param {Object} options + * @param {Boolean} options.no_state do not return state information + * @param {Boolean} options.no_id do not return ID + * @param {Boolean} options.no_children do not include children + * @param {Boolean} options.no_data do not include node data + * @param {Boolean} options.flat return flat JSON instead of nested + * @return {Object} + */ + get_json: (obj?: any, options?: JSTreeGetJsonOptions) => any; + /** + * create a new node (do not confuse with load_node) + * @name create_node([obj, node, pos, callback, is_loaded]) + * @param {mixed} par the parent node (to create a root node use either "#" (string) or `null`) + * @param {mixed} node the data for the new node (a valid JSON object, or a simple string with the name) + * @param {mixed} pos the index at which to insert the node, "first" and "last" are also supported, default is "last" + * @param {Function} callback a function to be called once the node is created + * @param {Boolean} is_loaded internal argument indicating if the parent node was succesfully loaded + * @return {String} the ID of the newly create node + * @trigger model.jstree, create_node.jstree + */ + create_node: (obj?: any, node?: any, pos?: any, callback?: any, is_loaded?: boolean) => string; + /** + * set the text value of a node + * @name rename_node(obj, val) + * @param {mixed} obj the node, you can pass an array to rename multiple nodes to the same name + * @param {String} val the new text value + * @return {Boolean} + * @trigger rename_node.jstree + */ + rename_node: (obj: any, val: string) => boolean; + /** + * remove a node + * @name delete_node(obj) + * @param {mixed} obj the node, you can pass an array to delete multiple nodes + * @return {Boolean} + * @trigger delete_node.jstree, changed.jstree + */ + delete_node: (obj: any) => boolean; + /** + * get the last error + * @name last_error() + * @return {Object} + */ + last_error: () => any; + /** + * move a node to a new parent + * @name move_node(obj, par [, pos, callback, is_loaded]) + * @param {mixed} obj the node to move, pass an array to move multiple nodes + * @param {mixed} par the new parent + * @param {mixed} pos the position to insert at (besides integer values, "first" and "last" are supported, as well as "before" and "after"), defaults to integer `0` + * @param {function} callback a function to call once the move is completed, receives 3 arguments - the node, the new parent and the position + * @param {Boolean} internal parameter indicating if the parent node has been loaded + * @trigger move_node.jstree + */ + move_node: (obj: any, par: any, pos?: any, callback?: any, internal?: boolean) => void; + /** + * copy a node to a new parent + * @name copy_node(obj, par [, pos, callback, is_loaded]) + * @param {mixed} obj the node to copy, pass an array to copy multiple nodes + * @param {mixed} par the new parent + * @param {mixed} pos the position to insert at (besides integer values, "first" and "last" are supported, as well as "before" and "after"), defaults to integer `0` + * @param {function} callback a function to call once the move is completed, receives 3 arguments - the node, the new parent and the position + * @param {Boolean} internal parameter indicating if the parent node has been loaded + * @trigger model.jstree copy_node.jstree + */ + copy_node: (obj: any, par: any, pos?: any, callback?: any, internal?: boolean) => void; + /** + * cut a node (a later call to `paste(obj)` would move the node) + * @name cut(obj) + * @param {mixed} obj multiple objects can be passed using an array + * @trigger cut.jstree + */ + cut: (obj: any) => void; + /** + * copy a node (a later call to `paste(obj)` would copy the node) + * @name copy(obj) + * @param {mixed} obj multiple objects can be passed using an array + * @trigger copy.jstre + */ + copy: (obj: any) => void; + /** + * get the current buffer (any nodes that are waiting for a paste operation) + * @name get_buffer() + * @return {Object} an object consisting of `mode` ("copy_node" or "move_node"), `node` (an array of objects) and `inst` (the instance) + */ + get_buffer: () => any; + /** + * check if there is something in the buffer to paste + * @name can_paste() + * @return {Boolean} + */ + can_paste: () => boolean; + /** + * copy or move the previously cut or copied nodes to a new parent + * @name paste(obj [, pos]) + * @param {mixed} obj the new parent + * @param {mixed} pos the position to insert at (besides integer, "first" and "last" are supported), defaults to integer `0` + * @trigger paste.jstree + */ + paste: (obj: any) => void; + /** + * put a node in edit mode (input field to rename the node) + * @name edit(obj [, default_text]) + * @param {mixed} obj + * @param {String} default_text the text to populate the input with (if omitted the node text value is used) + */ + edit: (obj: any, default_text?: string) => void; + /** + * changes the theme + * @name set_theme(theme_name [, theme_url]) + * @param {String} theme_name the name of the new theme to apply + * @param {mixed} theme_url the location of the CSS file for this theme. Omit or set to `false` + * if you manually included the file. Set to `true` to autoload from the `core.themes.dir` directory. + * @trigger set_theme.jstree + */ + set_theme: (theme_name: string, theme_url?: any) => void; + /** + * gets the name of the currently applied theme name + * @name get_theme() + * @return {String} + */ + get_theme: () => string; + /** + * changes the theme variant (if the theme has variants) + * @name set_theme_variant(variant_name) + * @param {String|Boolean} variant_name the variant to apply (if `false` is used the current variant is removed) + */ + set_theme_variant: (variant_name: any) => void; + /** + * gets the name of the currently applied theme variant + * @name get_theme() + * @return {String} + */ + get_theme_variant: () => string; + /** + * shows a striped background on the container (if the theme supports it) + * @name show_stripes() + */ + show_stripes: () => void; + /** + * hides the striped background on the container + * @name hide_stripes() + */ + hide_stripes: () => void; + /** + * toggles the striped background on the container + * @name toggle_stripes() + */ + toggle_stripes: () => void; + /** + * shows the connecting dots (if the theme supports it) + * @name show_dots() + */ + show_dots: () => void; + /** + * hides the connecting dots + * @name hide_dots() + */ + hide_dots: () => void; + /** + * toggles the connecting dots + * @name toggle_dots() + */ + toggle_dots: () => void; + /** + * show the node icons + * @name show_icons() + */ + show_icons: () => void; + /** + * hide the node icons + * @name hide_icons() + */ + hide_icons: () => void; + /** + * toggle the node icons + * @name toggle_icons() + */ + toggle_icons: () => void; + /** + * set the node icon for a node + * @name set_icon(obj, icon) + * @param {mixed} obj + * @param {String} icon the new icon - can be a path to an icon or a className, + * if using an image that is in the current directory use a `./` prefix, otherwise it will be detected as a class + */ + set_icon: (obj: any, icon: string) => void; + /** + * get the node icon for a node + * @name get_icon(obj) + * @param {mixed} obj + * @return {String} + */ + get_icon: (obj: any) => string; + /** + * hide the icon on an individual node + * @name hide_icon(obj) + * @param {mixed} obj + */ + hide_icon: (obj: any) => void; + /** + * show the icon on an individual node + * @name show_icon(obj) + * @param {mixed} obj + */ + show_icon: (obj: any) => void; + /** + */ + redraw_node: (obj: any, deep:boolean, is_callback:boolean) => any; + activate_node: (obj: any, e: any) => any; + + /** + * show the node checkbox icons + * @name show_checkboxes() + * @plugin checkbox + */ + show_checkboxes: () => void; + /** + * hide the node checkbox icons + * @name hide_checkboxes() + * @plugin checkbox + */ + hide_checkboxes: () => void; + /** + * toggle the node icons + * @name toggle_checkboxes() + * @plugin checkbox + */ + toggle_checkboxes: () => void; + /** + * context menu plugin + */ + teardown: () => void; + /** + * prepare and show the context menu for a node + * @name show_contextmenu(obj [, x, y]) + * @param {mixed} obj the node + * @param {Number} x the x-coordinate relative to the document to show the menu at + * @param {Number} y the y-coordinate relative to the document to show the menu at + * @param {Object} e the event if available that triggered the contextmenu + * @plugin contextmenu + * @trigger show_contextmenu.jstree + */ + show_contextmenu: (obj: any, x?: number, y?: number, e?:any) => void; + /** + * used to search the tree nodes for a given string + * @name search(str [, skip_async]) + * @param {String} str the search string + * @param {Boolean} skip_async if set to true server will not be queried even if configured + * @plugin search + * @trigger search.jstree + */ + search: (str: string, skip_async?: boolean) => void; + /** + * used to clear the last search (removes classes and shows all nodes if filtering is on) + * @name clear_search() + * @plugin search + * @trigger clear_search.jstree + */ + clear_search: () => void; + /** + * save the state + * @name save_state() + * @plugin state + */ + save_state: () => void; + /** + * restore the state from the user's computer + * @name restore_state() + * @plugin state + */ + restore_state: () => void; + /** + * clear the state on the user's computer + * @name clear_state() + * @plugin state + */ + clear_state: () => void; + /** + * used to retrieve the type settings object for a node + * @name get_rules(obj) + * @param {mixed} obj the node to find the rules for + * @return {Object} + * @plugin types + */ + get_rules: (obj: any) => any; + /** + * used to retrieve the type string or settings object for a node + * @name get_type(obj [, rules]) + * @param {mixed} obj the node to find the rules for + * @param {Boolean} rules if set to `true` instead of a string the settings object will be returned + * @return {String|Object} + * @plugin types + */ + get_type: (obj: any, rules?: any) => any; + /** + * used to change a node's type + * @name set_type(obj, type) + * @param {mixed} obj the node to change + * @param {String} type the new type + * @plugin types + */ + set_type: (obj: any, type: string) => any; + //bind(eventType: string, handler?: (event: any, data: JSTreeBindOptions) => any): JSTree; +} + +interface JSTreeGetJsonOptions { + /** + * do not return state information + */ + no_state: boolean; + /** + * do not return ID + */ + no_id: boolean; + /** + * do not include children + */ + no_children: boolean; +} + +interface JSTreeBindOptions { + inst?: any; + args?: any; + rslt?: any; + rlbk?: any; +} diff --git a/karma-jasmine/karma-jasmine.d.ts b/karma-jasmine/karma-jasmine.d.ts index 92b5e962d5..e4cdc5a816 100644 --- a/karma-jasmine/karma-jasmine.d.ts +++ b/karma-jasmine/karma-jasmine.d.ts @@ -1,6 +1,6 @@ // Type definitions for karma-jasmine plugin // Project: https://github.com/karma-runner/karma-jasmine -// Definitions by: Michel Salib +// Definitions by: Michel Salib // Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/keymaster/keymaster-tests.ts b/keymaster/keymaster-tests.ts new file mode 100644 index 0000000000..4c7cf3c5b7 --- /dev/null +++ b/keymaster/keymaster-tests.ts @@ -0,0 +1,14 @@ +/// + +// simple key binding without scope +key('shift+a', function (keyboardEvent: KeyboardEvent, keymasterEvent: KeymasterEvent) { +}); + +// simple key binding with scope +key('shift+b', 'aScope', (keyboardEvent, keymasterEvent) => { +}); + +// possible combinations of filtering +key.filter({target: { tagName: 'propertytest'}}); +key.filter({srcElement: { tagName: 'propertytest'}}); + diff --git a/keymaster/keymaster.d.ts b/keymaster/keymaster.d.ts new file mode 100644 index 0000000000..d749f76d17 --- /dev/null +++ b/keymaster/keymaster.d.ts @@ -0,0 +1,60 @@ +// Type definitions for keymaster v1.6.2 +// Project: https://github.com/madrobby/keymaster +// Definitions by: Martin W. Kirst +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies. + +interface KeymasterEvent { + key: string; + method: KeyHandler; + mods: number[]; + scope: string; + shortcut: string; +} + +interface KeyHandler { + (keyboardEvent: KeyboardEvent, keymasterEvent: KeymasterEvent) : void; +} + +interface FilterEvent { + target?: { + tagName?: string; + } + srcElement?: { + tagName?: string; + } +} + +interface Keymaster { + + (key: string, callback: KeyHandler): void; + (key: string, scope: string, callback: KeyHandler): void; + + shift: boolean; + alt: boolean; + option: boolean; + ctrl: boolean; + control: boolean; + command: boolean; + + setScope(scopeName: string): void; + getScope():string; + deleteScope(scopeName: string): void; + + noConflict(): void; + + unbind(key: string): void; + unbind(key: string, scopeName: string): void; + + isPressed(keyCode: number): boolean; + getPressedKeyCodes(): number[]; + + filter(event: FilterEvent): void; +} + +declare var key: Keymaster; + +declare module "keymaster" { +export = key; +} diff --git a/kineticjs/kineticjs.d.ts b/kineticjs/kineticjs.d.ts index bbe2d68e82..b5d56e8468 100644 --- a/kineticjs/kineticjs.d.ts +++ b/kineticjs/kineticjs.d.ts @@ -1,7 +1,7 @@ // Type definitions for KineticJS // Project: http://kineticjs.com/ // Definitions by: Basarat Ali Syed , Ralph de Ruijter -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped declare module Kinetic { @@ -45,7 +45,7 @@ declare module Kinetic { isDraggable(): boolean; isDragging(): boolean; isListening(): boolean; - move(x: number, y: number): void; + move(change:{x: number; y: number}): void; moveDown(): void; moveTo(newContainer: IContainer): void; moveToBottom(): void; @@ -53,6 +53,7 @@ declare module Kinetic { moveUp(): void; name(): string; name(name: string): void; + remove(): any; rotate(theta: number): void; rotateDeg(deg: number): void; @@ -124,7 +125,6 @@ declare module Kinetic { getChildren(): INode[]; getIntersections(point: any): any; isAncestorOf(node: any): any; - remove(child: any): any; removeChildren(): any; } @@ -136,6 +136,7 @@ declare module Kinetic { add(layer: ILayer): any; clear(): any; getContainer(): HTMLElement; + getContent(): HTMLElement; getDOM(): HTMLElement; getHeight(): number; getIntersection(pos: any): any; @@ -481,7 +482,7 @@ declare module Kinetic { interface LineConfig extends DrawOptionsConfig, ObjectOptionsConfig { points: any; lineCap?: string; - dashArray?: any; + dash?: number[]; } interface PolygonConfig extends DrawOptionsConfig, ObjectOptionsConfig { @@ -544,4 +545,4 @@ declare module Kinetic { width: number; height: number; } -} \ No newline at end of file +} diff --git a/knockback/knockback.d.ts b/knockback/knockback.d.ts index 50848e6841..71773ab92b 100644 --- a/knockback/knockback.d.ts +++ b/knockback/knockback.d.ts @@ -126,8 +126,8 @@ declare module Knockback { } interface CollectionObservable extends KnockoutObservableArray { - collection(colleciton: Backbone.Collection); - collection(): Backbone.Collection; + collection(colleciton: Backbone.Collection); + collection(): Backbone.Collection; destroy(); shareOptions(): CollectionOptions; filters(id: any) : Backbone.Model; @@ -163,7 +163,7 @@ declare module Knockback { } interface Static extends Utils { - collectionObservable(model?: Backbone.Collection, options?: CollectionOptions): CollectionObservable; + collectionObservable(model?: Backbone.Collection, options?: CollectionOptions): CollectionObservable; /** Base class for observing model attributes. */ observable( /** the model to observe (can be null) */ diff --git a/knockout.amd.helpers/knockout-amd-helpers-tests.ts b/knockout.amd.helpers/knockout-amd-helpers-tests.ts new file mode 100644 index 0000000000..c5d1b62e03 --- /dev/null +++ b/knockout.amd.helpers/knockout-amd-helpers-tests.ts @@ -0,0 +1,23 @@ +// Tests for knockout.projections.d.ts + +/// +/// + +//The baseDir is used in building the path to use in the require statement. If your modules live in the modules directory, then you can specify it globally here. +ko.bindingHandlers.module.baseDir = "blub"; + +//This allows the ability to globally override the function that the module binding calls after loading an AMD module that does not return a constructor. +ko.bindingHandlers.module.initializer= "initialize"; + +//The dispose method name can be globally overriden. This function is optionally called when a module is being removed/swapped. +ko.bindingHandlers.module.disposeMethod ="dispose"; + +//The templateProperty option can be globally set. If defined, when a module is loaded - if it has a property with the key specified here +// (where the value is a string or function), the value of that property will be used as the template for the module. The result is a fully +// self-contained module (i.e. it has its own template, not an external one). +ko.bindingHandlers.module.templateProperty ="test"; + + +ko.amdTemplateEngine.defaultPath = "your/path/to/templates"; +ko.amdTemplateEngine.defaultSuffix = ".template.html"; +ko.amdTemplateEngine.defaultRequireTextPluginName = "text"; \ No newline at end of file diff --git a/knockout.amd.helpers/knockout-amd-helpers.d.ts b/knockout.amd.helpers/knockout-amd-helpers.d.ts new file mode 100644 index 0000000000..34d4eb0271 --- /dev/null +++ b/knockout.amd.helpers/knockout-amd-helpers.d.ts @@ -0,0 +1,34 @@ +// Type definitions for knockout-amd-helpers +// Project: https://github.com/rniemeyer/knockout-amd-helpers +// Definitions by: David Sichau +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + + +interface KnockoutAMDModule { + baseDir: string; + initializer: string; + disposeMethod: string; + templateProperty: string; +} + +interface KnockoutAMDTemplate { + defaultPath: string; + defaultSuffix: string; + defaultRequireTextPluginName: string; +} + +interface KnockoutBindingHandlers { + module: KnockoutAMDModule; +} +interface KnockoutStatic { + + amdTemplateEngine: KnockoutAMDTemplate +} + +declare module "knockout-amd-helpers" { + export = ko; +} + +declare var ko: KnockoutStatic; diff --git a/knockout.editables/ko.editables.d.ts b/knockout.editables/ko.editables.d.ts index b6da1f13f6..8167b3eaf1 100644 --- a/knockout.editables/ko.editables.d.ts +++ b/knockout.editables/ko.editables.d.ts @@ -1,5 +1,5 @@ // Type definitions for knockout-editables 0.9 -// Project:http://romanych.github.com/ko.editables/ +// Project: http://romanych.github.com/ko.editables/ // Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/knockout.mapper/knockout.mapper.d.ts b/knockout.mapper/knockout.mapper.d.ts index 8052e4cc7e..30476f7460 100644 --- a/knockout.mapper/knockout.mapper.d.ts +++ b/knockout.mapper/knockout.mapper.d.ts @@ -1,7 +1,7 @@ // Type definitions for Knockout.Mapper // Project: https://github.com/LucasLorentz/knockout.mapper // Definitions by: Brandon Meyer -// Definitions https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -12,4 +12,4 @@ interface KnockoutMapper { interface KnockoutStatic { mapper: KnockoutMapper; -} \ No newline at end of file +} diff --git a/knockout.mapping/knockout.mapping.d.ts b/knockout.mapping/knockout.mapping.d.ts index e8ffc807ee..2c8af47855 100644 --- a/knockout.mapping/knockout.mapping.d.ts +++ b/knockout.mapping/knockout.mapping.d.ts @@ -1,7 +1,7 @@ // Type definitions for Knockout.Mapping 2.0 // Project: https://github.com/SteveSanderson/knockout.mapping // Definitions by: Boris Yankov -// Definitions https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/knockout.rx/knockout.rx.d.ts b/knockout.rx/knockout.rx.d.ts index f897bc7619..7b98e25c2b 100644 --- a/knockout.rx/knockout.rx.d.ts +++ b/knockout.rx/knockout.rx.d.ts @@ -1,10 +1,10 @@ -// Type definitions for knockout.rx 0.1 +// Type definitions for knockout.rx 1.0 // Project: https://github.com/Igorbek/knockout.rx // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped /// -/// +/// interface KnockoutSubscribableFunctions { toObservable(event?: string): Rx.Observable; @@ -13,6 +13,7 @@ interface KnockoutSubscribableFunctions { interface KnockoutObservableFunctions { toObservableWithReplyLatest(): Rx.Observable; + toSubject(): Rx.ISubject; } interface KnockoutComputedFunctions { @@ -24,4 +25,8 @@ declare module Rx { toKoSubscribable(): KnockoutSubscribable; toKoObservable(initialValue?: T): KnockoutObservable; } + + interface Subject { + toKoObservable(initialValue?: T): KnockoutObservable; + } } diff --git a/knockout.validation/knockout.validation.d.ts b/knockout.validation/knockout.validation.d.ts index d5e23a9ba1..8317f75526 100644 --- a/knockout.validation/knockout.validation.d.ts +++ b/knockout.validation/knockout.validation.d.ts @@ -142,6 +142,7 @@ interface KnockoutSubscribableFunctions { isValid: KnockoutComputed; isValidating: KnockoutObservable; rules: KnockoutObservableArray; + isModified(val: boolean): void; } declare module "knockout.validation" { diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 7f8451ac5c..8b26c50b92 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Knockout 2.3 +// Type definitions for Knockout v3.2.0-beta // Project: http://knockoutjs.com -// Definitions by: Boris Yankov +// Definitions by: Boris Yankov , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -64,11 +64,12 @@ interface KnockoutComputedStatic { (): KnockoutComputed; (func: () => T, context?: any, options?: any): KnockoutComputed; - (def: KnockoutComputedDefine): KnockoutComputed; - (options?: any): KnockoutComputed; + (def: KnockoutComputedDefine, context?: any): KnockoutComputed; + (options?: any, context?: any): KnockoutComputed; } interface KnockoutComputed extends KnockoutObservable, KnockoutComputedFunctions { + fn: KnockoutComputedFunctions; dispose(): void; isActive(): boolean; @@ -109,6 +110,7 @@ interface KnockoutComputedDefine { disposeWhen? (): boolean; owner?: any; deferEvaluation?: boolean; + pure?: boolean; } interface KnockoutBindingContext { @@ -123,9 +125,15 @@ interface KnockoutBindingContext { createChildContext(dataItemOrAccessor: any, dataItemAlias?: any, extendCallback?: Function): any; } +interface KnockoutAllBindingsAccessor { + (): any; + get(name: string): any; + has(name: string): boolean; +} + interface KnockoutBindingHandler { - init?(element: any, valueAccessor: () => any, allBindingsAccessor: () => any, viewModel: any, bindingContext: KnockoutBindingContext): void; - update?(element: any, valueAccessor: () => any, allBindingsAccessor: () => any, viewModel: any, bindingContext: KnockoutBindingContext): void; + init? (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext): void; + update? (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext): void; options?: any; } @@ -160,7 +168,10 @@ interface KnockoutBindingHandlers { uniqueName: KnockoutBindingHandler; // Rendering templates - template: KnockoutBindingHandler; + template: KnockoutBindingHandler; + + // Components (new for v3.2) + component: KnockoutBindingHandler; } interface KnockoutMemoization { @@ -185,7 +196,12 @@ interface KnockoutVirtualElements { interface KnockoutExtenders { throttle(target: any, timeout: number): KnockoutComputed; - notify(target: any, notifyWhen: string): any; + notify(target: any, notifyWhen: string): any; + + rateLimit(target: any, timeout: number): any; + rateLimit(target: any, options: { timeout: number; method?: string; }): any; + + trackArrayChanges(target: any): any; } interface KnockoutUtils { @@ -274,7 +290,7 @@ interface KnockoutUtils { stringTrim(str: string): string; - stringTokenize(str: string, delimiter: string): string; + stringTokenize(str: string, delimiter: string): string[]; stringStartsWith(str: string, startsWith: string): string; @@ -332,22 +348,28 @@ interface KnockoutArrayChange { ////////////////////////////////// interface KnockoutTemplateSourcesDomElement { + text(): any; + text(value: any): void; - text(valueToWrite?: any): any; - - data(key: string, valueToWrite?: any): any; + data(key: string): any; + data(key: string, value: any): any; } +interface KnockoutTemplateAnonymous extends KnockoutTemplateSourcesDomElement { + nodes(): any; + nodes(value: any): void; +} interface KnockoutTemplateSources { - domElement: KnockoutTemplateSourcesDomElement; + domElement: { + prototype: KnockoutTemplateSourcesDomElement + new (element: Element): KnockoutTemplateSourcesDomElement + }; anonymousTemplate: { - - prototype: KnockoutTemplateSourcesDomElement; - - new (element: Element): KnockoutTemplateSourcesDomElement; + prototype: KnockoutTemplateAnonymous; + new (element: Element): KnockoutTemplateAnonymous; }; } @@ -382,17 +404,28 @@ interface KnockoutTemplateEngine extends KnockoutNativeTemplateEngine { interface KnockoutStatic { utils: KnockoutUtils; memoization: KnockoutMemoization; - bindingHandlers: KnockoutBindingHandlers; + + bindingHandlers: KnockoutBindingHandlers; + getBindingHandler(handler: string): KnockoutBindingHandler; + virtualElements: KnockoutVirtualElements; extenders: KnockoutExtenders; applyBindings(viewModel: any, rootNode?: any): void; - applyBindingsToDescendants(viewModel: any, rootNode: any): void; + applyBindingsToDescendants(viewModel: any, rootNode: any): void; + applyBindingAccessorsToNode(node: Node, bindings: (bindingContext: KnockoutBindingContext, node: Node) => {}, bindingContext: KnockoutBindingContext): void; + applyBindingAccessorsToNode(node: Node, bindings: {}, bindingContext: KnockoutBindingContext): void; + applyBindingAccessorsToNode(node: Node, bindings: (bindingContext: KnockoutBindingContext, node: Node) => {}, viewModel: any): void; + applyBindingAccessorsToNode(node: Node, bindings: {}, viewModel: any): void; applyBindingsToNode(node: Element, options: any, viewModel: any): void; subscribable: KnockoutSubscribableStatic; observable: KnockoutObservableStatic; - computed: KnockoutComputedStatic; + + computed: KnockoutComputedStatic; + pureComputed(evaluatorFunction: () => T, context?: any): KnockoutComputed; + pureComputed(options: KnockoutComputedDefine, context?: any): KnockoutComputed; + observableArray: KnockoutObservableArrayStatic; contextFor(node: any): any; @@ -407,7 +440,9 @@ interface KnockoutStatic { cleanNode(node: Element): Element; renderTemplate(template: Function, viewModel: any, options?: any, target?: any, renderMode?: any): any; renderTemplate(template: string, viewModel: any, options?: any, target?: any, renderMode?: any): any; - unwrap(value: any): any; + unwrap(value: any): any; + + computedContext: KnockoutComputedContext; ////////////////////////////////// // templateSources.js @@ -494,7 +529,10 @@ interface KnockoutStatic { ///////////////////////////////// - bindingProvider: any; + bindingProvider: { + instance: KnockoutBindingProvider; + new (): KnockoutBindingProvider; + } ///////////////////////////////// // selectExtensions.js @@ -508,6 +546,47 @@ interface KnockoutStatic { }; } +interface KnockoutBindingProvider { + nodeHasBindings(node: Node): boolean; + getBindings(node: Node, bindingContext: KnockoutBindingContext): {}; + getBindingAccessors?(node: Node, bindingContext: KnockoutBindingContext): { [key: string]: string; }; +} + +interface KnockoutComponents { + register(componentName: string, definition: KnockoutComponentDefinition): void; + isRegistered(componentName: string): boolean; + unregister(componentName: string): void; + get(componentName: string, callback: (definition: KnockoutComponentDefinition) => void): void; + clearCachedDefinition(componentName: string): void + defaultLoader: KnockoutComponentLoader; + loaders: KnockoutComponentLoader[]; + getComponentNameForNode(node: Node): string; +} + +interface KnockoutComponentDefinition { + template: Node[]; + createViewModel?(params: any, options: { element: Node; }): any; +} + +interface KnockoutComponentLoader { + getConfig? (componentName: string, callback: (result: KnockoutComponentConfig) => void): void; + loadComponent? (componentName: string, config: KnockoutComponentConfig, callback: (result: KnockoutComponentDefinition) => void): void; + loadTemplate? (componentName: string, templateConfig: any, callback: (result: Node[]) => void): void; + loadViewModel? (componentName: string, viewModelConfig: any, callback: (result: any) => void): void; + suppressLoaderExceptions?: boolean; +} + +interface KnockoutComponentConfig { + template: any; + createViewModel?: any; +} + +interface KnockoutComputedContext { + getDependenciesCount(): number; + isInitial: boolean; + isSleeping: boolean; +} + declare module "knockout" { export = ko; } diff --git a/knockout/tests/knockout-templatingBehaviors-tests.ts b/knockout/tests/knockout-templatingBehaviors-tests.ts index 7be02d4cd3..50ec275724 100644 --- a/knockout/tests/knockout-templatingBehaviors-tests.ts +++ b/knockout/tests/knockout-templatingBehaviors-tests.ts @@ -363,11 +363,11 @@ describe('Templating', function() { // and external (non-rewritten) ones var originalBindingProvider = ko.bindingProvider.instance; ko.bindingProvider.instance = { - nodeHasBindings: function(node, bindingContext) { - return (node.tagName == 'EM') || originalBindingProvider.nodeHasBindings(node, bindingContext); + nodeHasBindings: function(node) { + return ((node).tagName == 'EM') || originalBindingProvider.nodeHasBindings(node); }, getBindings: function(node, bindingContext) { - if (node.tagName == 'EM') + if ((node).tagName == 'EM') return { text: ++model.numBindings }; return originalBindingProvider.getBindings(node, bindingContext); } diff --git a/knockout/tests/knockout-tests.ts b/knockout/tests/knockout-tests.ts index 1ebef13ef5..6d4c9e25d8 100644 --- a/knockout/tests/knockout-tests.ts +++ b/knockout/tests/knockout-tests.ts @@ -581,4 +581,25 @@ function test_misc() { } } +} + +interface KnockoutBindingHandlers { + allBindingsAccessorTest: KnockoutBindingHandler; +} + +function test_allBindingsAccessor() { + ko.bindingHandlers.allBindingsAccessorTest = { + init: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => { + var allBindings = allBindingsAccessor(); + var hasBinding = allBindingsAccessor.has("myBindingName"); + var myBinding = allBindingsAccessor.get("myBindingName"); + var fnAccessorBinding = allBindingsAccessor().myBindingName; + }, + update: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => { + var allBindings = allBindingsAccessor(); + var hasBinding = allBindingsAccessor.has("myBindingName"); + var myBinding = allBindingsAccessor.get("myBindingName"); + var fnAccessorBinding = allBindingsAccessor().myBindingName; + } + }; } \ No newline at end of file diff --git a/kolite/kolite-tests.ts b/kolite/kolite-tests.ts index f2013241d8..4306ede537 100644 --- a/kolite/kolite-tests.ts +++ b/kolite/kolite-tests.ts @@ -30,6 +30,22 @@ function test_asyncCommand() { }); } +function test_asyncCommand_isExecuting() { + var primaryCommand = ko.asyncCommand({ + execute: (complete) => { + $.when().always(complete); + }, + canExecute: (isExecuting) => { + return !isExecuting; + } + }); + + var firstRun = true; + var canCancel = ko.computed(() => { + return firstRun && !primaryCommand.isExecuting(); + }); +} + function test_dirtyFlag() { var viewModel; viewModel.dirtyFlag = new ko.DirtyFlag(viewModel.model); diff --git a/kolite/kolite.d.ts b/kolite/kolite.d.ts index 42efda4a94..6310fcad49 100644 --- a/kolite/kolite.d.ts +++ b/kolite/kolite.d.ts @@ -1,7 +1,7 @@ // Type definitions for KoLite 1.1 // Project: https://github.com/CodeSeven/kolite // Definitions by: Boris Yankov -// Definitions https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -58,6 +58,10 @@ interface KoliteCommand { execute(...args: any[]): any; } +interface KoliteAsyncCommand extends KoliteCommand { + isExecuting: KnockoutObservable; +} + interface KoLiteCommandOptions { execute?: any; canExecute?: (isExecuting: boolean) => any; @@ -65,7 +69,7 @@ interface KoLiteCommandOptions { interface KnockoutStatic { command(options: KoLiteCommandOptions): KoliteCommand; - asyncCommand(optons: KoLiteCommandOptions): KoliteCommand; + asyncCommand(optons: KoLiteCommandOptions): KoliteAsyncCommand; } interface KnockoutUtils { @@ -74,4 +78,4 @@ interface KnockoutUtils { interface KnockoutBindingHandlers { command: KnockoutBindingHandler; -} \ No newline at end of file +} diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 3044970b0c..54f0fe4f09 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -474,7 +474,7 @@ declare module L { * positions. * Default value: 'topright'. */ - position: string; + position?: string; } } @@ -773,20 +773,20 @@ declare module L { /** * Create a layer group, optionally given an initial set of layers. */ - function featureGroup(layers?: ILayer[]): FeatureGroup; + function featureGroup(layers?: T[]): FeatureGroup; - export class FeatureGroup extends LayerGroup implements ILayer, IEventPowered { + export class FeatureGroup extends LayerGroup implements ILayer, IEventPowered> { /** * Create a layer group, optionally given an initial set of layers. */ - constructor(layers?: ILayer[]); + constructor(layers?: T[]); /** * Binds a popup with a particular HTML content to a click on any layer from the * group that has a bindPopup method. */ - bindPopup(htmlContent: string, options?: PopupOptions): FeatureGroup; + bindPopup(htmlContent: string, options?: PopupOptions): FeatureGroup; /** * Returns the LatLngBounds of the Feature Group (created from bounds and coordinates @@ -797,17 +797,17 @@ declare module L { /** * Sets the given path options to each layer of the group that has a setStyle method. */ - setStyle(style: PathOptions): FeatureGroup; + setStyle(style: PathOptions): FeatureGroup; /** * Brings the layer group to the top of all other layers. */ - bringToFront(): FeatureGroup; + bringToFront(): FeatureGroup; /** * Brings the layer group to the bottom of all other layers. */ - bringToBack(): FeatureGroup; + bringToBack(): FeatureGroup; //////////// //////////// @@ -826,20 +826,20 @@ declare module L { //////////////// //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): FeatureGroup; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; - fire(type: string, data?: any): FeatureGroup; - addEventListener(eventMap: any, context?: any): FeatureGroup; - removeEventListener(eventMap?: any, context?: any): FeatureGroup; - clearAllEventListeners(): FeatureGroup; - on(eventMap: any, context?: any): FeatureGroup; - off(eventMap?: any, context?: any): FeatureGroup; + fireEvent(type: string, data?: any): FeatureGroup; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; + fire(type: string, data?: any): FeatureGroup; + addEventListener(eventMap: any, context?: any): FeatureGroup; + removeEventListener(eventMap?: any, context?: any): FeatureGroup; + clearAllEventListeners(): FeatureGroup; + on(eventMap: any, context?: any): FeatureGroup; + off(eventMap?: any, context?: any): FeatureGroup; } } @@ -882,7 +882,7 @@ declare module L { */ function geoJson(geojson?: any, options?: GeoJSONOptions): GeoJSON; - export class GeoJSON extends FeatureGroup { + export class GeoJSON extends FeatureGroup { /** * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format @@ -1539,60 +1539,60 @@ declare module L { /** * Create a layer group, optionally given an initial set of layers. */ - function layerGroup(layers?: ILayer[]): LayerGroup; + function layerGroup(layers?: T[]): LayerGroup; - export class LayerGroup extends Class implements ILayer { + export class LayerGroup extends Class implements ILayer { /** * Create a layer group, optionally given an initial set of layers. */ - constructor(layers?: ILayer[]); + constructor(layers?: T[]); /** * Adds the group of layers to the map. */ - addTo(map: Map): LayerGroup; + addTo(map: Map): LayerGroup; /** * Adds a given layer to the group. */ - addLayer(layer: ILayer): LayerGroup; + addLayer(layer: T): LayerGroup; /** * Removes a given layer from the group. */ - removeLayer(layer: ILayer): LayerGroup; + removeLayer(layer: T): LayerGroup; /** * Removes a given layer of the given id from the group. */ - removeLayer(id: string): LayerGroup; + removeLayer(id: string): LayerGroup; /** * Returns true if the given layer is currently added to the group. */ - hasLayer(layer: ILayer): boolean; + hasLayer(layer: T): boolean; /** * Returns the layer with the given id. */ - getLayer(id: string): ILayer; + getLayer(id: string): T; /** * Returns an array of all the layers added to the group. */ - getLayers(): ILayer[]; + getLayers(): T[]; /** * Removes all the layers from the group. */ - clearLayers(): LayerGroup; + clearLayers(): LayerGroup; /** * Iterates over the layers of the group, optionally specifying context of * the iterator function. */ - eachLayer(fn: (layer: ILayer) => void, context?: any): LayerGroup; + eachLayer(fn: (layer: T) => void, context?: any): LayerGroup; /** * Returns a GeoJSON representation of the layer group (GeoJSON FeatureCollection). @@ -2794,7 +2794,7 @@ declare module L { */ function multiPolygon(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; - export class MultiPolygon extends FeatureGroup { + export class MultiPolygon extends FeatureGroup { /** * Instantiates a multi-polyline object given an array of latlngs arrays (one @@ -2829,7 +2829,7 @@ declare module L { */ function multiPolyline(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; - export class MultiPolyline extends FeatureGroup { + export class MultiPolyline extends FeatureGroup { /** * Instantiates a multi-polyline object given an array of arrays of geographical @@ -3655,25 +3655,27 @@ declare module L { } } - export class tileLayer { + export interface TileLayerFactory { /** * Instantiates a tile layer object given a URL template and optionally an options * object. */ - function (urlTemplate: string, options?: TileLayerOptions): TileLayer; + (urlTemplate: string, options?: TileLayerOptions): TileLayer; /** * Instantiates a WMS tile layer object given a base URL of the WMS service and * a WMS parameters/options object. */ - static wms(baseUrl: string, options: WMSOptions): L.TileLayer.WMS; + wms(baseUrl: string, options: WMSOptions): L.TileLayer.WMS; /** * Instantiates a Canvas tile layer object given an options object (optionally). */ - static canvas(options?: TileLayerOptions): L.TileLayer.Canvas; + canvas(options?: TileLayerOptions): L.TileLayer.Canvas; } + + export var tileLayer: TileLayerFactory; } declare module L { diff --git a/less/less.d.ts b/less/less.d.ts index 1ab9293c47..d5787913b9 100644 --- a/less/less.d.ts +++ b/less/less.d.ts @@ -497,6 +497,16 @@ declare module "less" { toCSS(env?: Options): string; eval(): UnicodeDescriptor; } + + export class Attribute implements IInjectable { + constructor(value: string); + + value: string; + + toCSS(env?: Options): string; + genCSS(env: Options, output): string; + eval(): Attribute; + } export var debugInfo: DebugInfoFunction; export function find(obj: any[], fun: Function): any; @@ -539,4 +549,4 @@ declare module "less" { export function writeError(ctx, options: { color: boolean; }): void; export var version: number[]; -} \ No newline at end of file +} diff --git a/linq/linq.3.0.3-Beta4.d.ts b/linq/linq.3.0.3-Beta4.d.ts index d75d0982bc..ff550d6754 100755 --- a/linq/linq.3.0.3-Beta4.d.ts +++ b/linq/linq.3.0.3-Beta4.d.ts @@ -1,6 +1,6 @@ -// Type definitions for linq.js, ver 3.0.3-Beta4 +// Type definitions for linq.js v3.0.3-Beta4 // Project: http://linqjs.codeplex.com/ -// Definitions by: neuecc (http://www.codeplex.com/site/users/view/neuecc) +// Definitions by: neuecc // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module linqjs { diff --git a/linq/linq.d.ts b/linq/linq.d.ts index 960b20a900..d155ba806b 100644 --- a/linq/linq.d.ts +++ b/linq/linq.d.ts @@ -1,6 +1,6 @@ // Type definitions for linq.js 2.2 // Project: http://linqjs.codeplex.com/ -// Definitions by: Marcin Najder +// Definitions by: Marcin Najder // Definitions: https://github.com/borisyankov/DefinitelyTyped // todo: jQuery plugin, RxJS Binding diff --git a/linq/linq.jquery.d.ts b/linq/linq.jquery.d.ts index c4b874baed..c79708f660 100755 --- a/linq/linq.jquery.d.ts +++ b/linq/linq.jquery.d.ts @@ -1,6 +1,6 @@ // Type definitions for linq.jquery (from linq.js) // Project: http://linqjs.codeplex.com/ -// Definitions by: neuecc (http://www.codeplex.com/site/users/view/neuecc) +// Definitions by: neuecc // Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/lockfile/lockfile-tests.ts b/lockfile/lockfile-tests.ts new file mode 100644 index 0000000000..49aa423d94 --- /dev/null +++ b/lockfile/lockfile-tests.ts @@ -0,0 +1,31 @@ +/// + +import lockfile = require('lockfile'); + +var bool: boolean; +var num: number; +var path: string; + +var opts: lockfile.Options; +var callback: (err: Error) => { + +}; + +opts = { + wait: num, + stale: num, + retries: num, + retryWait: num +}; + +lockfile.lock(path, opts, callback); +lockfile.lock(path, callback); +lockfile.lockSync(path, opts); + +lockfile.unlock(path, callback);; +lockfile.unlockSync(path); + +lockfile.check(path, opts, callback); +lockfile.check(path, callback); + +bool = lockfile.checkSync(path, opts); diff --git a/lockfile/lockfile.d.ts b/lockfile/lockfile.d.ts new file mode 100644 index 0000000000..99dfbe28d9 --- /dev/null +++ b/lockfile/lockfile.d.ts @@ -0,0 +1,24 @@ +// Type definitions for lockfile v0.4.2 +// Project: https://github.com/isaacs/lockfile +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'lockfile' { + export interface Options { + wait?: number; + stale?: number; + retries?: number; + retryWait?: number; + } + + export function lock(path: string, opts: Options, callback: (err: Error) => void): void; + export function lock(path: string, callback: (err: Error) => void): void; + export function lockSync(path: string, opts: Options):void; + + export function unlock(path: string, callback: (err: Error) => void): void; + export function unlockSync(path: string):void; + + export function check(path: string, opts: Options, callback: (err: Error) => void): void; + export function check(path: string, callback: (err: Error) => void): void; + export function checkSync(path: string, opts: Options): boolean; +} diff --git a/lodash/lodash-tests.disabled.ts b/lodash/lodash-tests.disabled.ts deleted file mode 100644 index aca0bbdf0b..0000000000 --- a/lodash/lodash-tests.disabled.ts +++ /dev/null @@ -1,979 +0,0 @@ -/// - -declare var $: any, jQuery: any; - -interface IFoodOrganic { - name: string; - organic: boolean; -} - -interface IFoodType { - name: string; - type: string; -} - -interface IFoodCombined { - name: string; - organic: boolean; - type: string; -} - -interface IStoogesQuote { - name: string; - quotes: string[]; -} - -interface IStoogesAge { - name: string; - age: number; -} - -interface IStoogesCombined { - name: string; - age: number; - quotes: string[]; -} - -interface IKey { - dir: string; - code: number; -} - -var foodsOrganic: IFoodOrganic[] = [ - { name: 'banana', organic: true }, - { name: 'beet', organic: false }, -]; -var foodsType: IFoodType[] = [ - { name: 'apple', type: 'fruit' }, - { name: 'banana', type: 'fruit' }, - { name: 'beet', type: 'vegetable' } -]; -var foodsCombined: IFoodCombined[] = [ - { 'name': 'apple', 'organic': false, 'type': 'fruit' }, - { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } -]; - -var stoogesQuotes: IStoogesQuote[] = [ - { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, - { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] } -]; -var stoogesAges: IStoogesAge[] = [ - { 'name': 'moe', 'age': 40 }, - { 'name': 'larry', 'age': 50 } -]; - -var stoogesCombined: IStoogesCombined[] = [ - { 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, - { 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] } -]; - -var keys: IKey[] = [ - { 'dir': 'left', 'code': 97 }, - { 'dir': 'right', 'code': 100 } -]; - -class Dog { - constructor(public name: string) {} - - public bark() { - console.log('Woof, woof!'); - } -} - -var result : any; - -/************* - * Chaining * - *************/ -result = <_.LoDashWrapper>_('test'); -result = <_.LoDashWrapper>_(1); -result = <_.LoDashWrapper>_(true); -result = <_.LoDashArrayWrapper>_(['test1', 'test2']); -result = <_.LoDashObjectWrapper<_.Dictionary>>_({'key1': 'test1', 'key2': 'test2'}); - -result = <_.LoDashWrapper>_.chain('test'); -result = <_.LoDashWrapper>_('test').chain(); -result = <_.LoDashWrapper>_.chain(1); -result = <_.LoDashWrapper>_(1).chain(); -result = <_.LoDashWrapper>_.chain(true); -result = <_.LoDashWrapper>_(true).chain(); -result = <_.LoDashArrayWrapper>_.chain(['test1', 'test2']); -result = <_.LoDashArrayWrapper>_(['test1', 'test2']).chain(); -result = <_.LoDashObjectWrapper<_.Dictionary>>_.chain({'key1': 'test1', 'key2': 'test2'}); -result = <_.LoDashObjectWrapper<_.Dictionary>>_({'key1': 'test1', 'key2': 'test2'}).chain(); - -//Wrapped array shortcut methods -result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).concat(5, 6); -result = <_.LoDashWrapper>_([1, 2, 3, 4]).join(','); -result = <_.LoDashWrapper>_([1, 2, 3, 4]).pop(); -_([1, 2, 3, 4]).push(5, 6, 7); -result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).reverse(); -result = <_.LoDashWrapper>_([1, 2, 3, 4]).shift(); -result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).slice(1, 2); -result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).slice(2); -result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).sort((a, b) => 1); -result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).splice(1); -result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).splice(1, 2, 5, 6); -result = <_.LoDashWrapper>_([1, 2, 3, 4]).unshift(5, 6); - -result = _.tap([1, 2, 3, 4], function(array) { console.log(array); }); -result = <_.LoDashWrapper>_('test').tap(function(value) { console.log(value); }); -result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).tap(function(array) { console.log(array); }); -result = <_.LoDashObjectWrapper<_.Dictionary>>_({'key1': 'test1', 'key2': 'test2'}).tap(function(array) { console.log(array); }); - -result = _('test').toString(); -result = _([1, 2, 3]).toString(); -result = _({'key1': 'test1', 'key2': 'test2'}).toString(); - -result = _('test').valueOf(); -result = _([1, 2, 3]).valueOf(); -result = <_.Dictionary>_({'key1': 'test1', 'key2': 'test2'}).valueOf(); - -result = _('test').value(); -result = _([1, 2, 3]).value(); -result = <_.Dictionary>_({'key1': 'test1', 'key2': 'test2'}).value(); - -// /************* -// * Arrays * -// *************/ -result = _.compact([0, 1, false, 2, '', 3]); - result = <_.LoDashArrayWrapper>_([0, 1, false, 2, '', 3]).compact(); - -result = _.difference([1, 2, 3, 4, 5], [5, 2, 10]); - result = <_.LoDashArrayWrapper>_([1, 2, 3, 4, 5]).difference([5, 2, 10]); - -result = _.rest([1, 2, 3]); -result = _.rest([1, 2, 3], 2); -result = _.rest([1, 2, 3], (num) => num < 3) -result = _.rest(foodsOrganic, 'test'); -result = _.rest(foodsType, { 'type': 'value' }); - -result = _.drop([1, 2, 3]); -result = _.drop([1, 2, 3], 2); -result = _.drop([1, 2, 3], (num) => num < 3) -result = _.drop(foodsOrganic, 'test'); -result = _.drop(foodsType, { 'type': 'value' }); - -result = _.tail([1, 2, 3]) -result = _.tail([1, 2, 3], 2) -result = _.tail([1, 2, 3], (num) => num < 3) -result = _.tail(foodsOrganic, 'test') -result = _.tail(foodsType, { 'type': 'value' }) - -result = _.findIndex(['apple', 'banana', 'beet'], function(f) { - return /^b/.test(f); -}); -result = _.findIndex(['apple', 'banana', 'beet'], 'apple'); -result = _.findIndex([{ food: 'apple' }, { food: 'banana' }, { food: 'beet' }], { food: 'apple'}); - -result = _.findLastIndex(['apple', 'banana', 'beet'], function(f: string) { - return /^b/.test(f); -}); -result = _.findLastIndex(['apple', 'banana', 'beet'], 'apple'); -result = _.findLastIndex([{ food: 'apple' }, { food: 'banana' }, { food: 'beet' }], { food: 'apple'}); - -result = _.first([1, 2, 3]); -result = _.first([1, 2, 3], 2); -result = _.first([1, 2, 3], function(num) { - return num < 3; -}); -result = _.first(foodsOrganic, 'organic'); -result = _.first(foodsType, { 'type': 'fruit' }); - - result = _.head([1, 2, 3]); - result = _.head([1, 2, 3], 2); - result = _.head([1, 2, 3], function(num) { - return num < 3; - }); - result = _.head(foodsOrganic, 'organic'); - result = _.head(foodsType, { 'type': 'fruit' }); - - result = _.take([1, 2, 3]); - result = _.take([1, 2, 3], 2); - result = _.take([1, 2, 3], (num) => num < 3); - result = _.take(foodsOrganic, 'organic'); - result = _.take(foodsType, { 'type': 'fruit' }); - -result = _.flatten([1, [2], [3, [[4]]]]); -result = _.flatten([1, [2], [3, [[4]]]], true); -var result: any -result = _.flatten(stoogesQuotes, 'quotes'); - - result = <_.LoDashArrayWrapper>_([1, [2], [3, [[4]]]]).flatten(); - result = <_.LoDashArrayWrapper>_([1, [2], [3, [[4]]]]).flatten(true); - result = <_.LoDashArrayWrapper>_(stoogesQuotes).flatten('quotes'); - -result = _.indexOf([1, 2, 3, 1, 2, 3], 2); -result = _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); -result = _.indexOf([1, 1, 2, 2, 3, 3], 2, true); - -result = _.initial([1, 2, 3]); -result = _.initial([1, 2, 3], 2); -result = _.initial([1, 2, 3], function(num) { - return num > 1; -}); -result = _.initial(foodsOrganic, 'organic'); -result = _.initial(foodsType, { 'type': 'vegetable' }); - -result = _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); - -result = _.last([1, 2, 3]); -result = _.last([1, 2, 3], 2); -result = _.last([1, 2, 3], function(num) { - return num > 1; -}); -result = _.last(foodsOrganic, 'organic'); -result = _.last(foodsType, { 'type': 'vegetable' }); - -result = _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); -result = _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); - -result = <{[key: string]: any}>_.zipObject(['moe', 'larry'], [30, 40]); -result = <{[key: string]: any}>_.object(['moe', 'larry'], [30, 40]); - -result = _.pull([1, 2, 3, 1, 2, 3], 2, 3); - -result = _.range(10); -result = _.range(1, 11); -result = _.range(0, 30, 5); -result = _.range(0, -10, -1); -result = _.range(1, 4, 0); -result = _.range(0); - -result = _.remove([1, 2, 3, 4, 5, 6], function(num: number) { return num % 2 == 0; }); -result = _.remove(foodsOrganic, 'organic'); -result = _.remove(foodsType, { 'type': 'vegetable'}); - -result = _.sortedIndex([20, 30, 50], 40); -result = _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); -var sortedIndexDict = { - 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } -}; -result = _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { - return sortedIndexDict.wordToNumber[word]; -}); -result = _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { - return this.wordToNumber[word]; -}, sortedIndexDict); - -result = _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); - -result = _.uniq([1, 2, 1, 3, 1]); -result = _.uniq([1, 1, 2, 2, 3], true); -result = _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { - return letter.toLowerCase(); -}); -result = _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); -result = <{x: number;}[]>_.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - - result = _.unique([1, 2, 1, 3, 1]); - result = _.unique([1, 1, 2, 2, 3], true); - result = _.unique(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { - return letter.toLowerCase(); - }); - result = _.unique([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); - result = <{x: number;}[]>_.unique([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - -result = _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); - -result = _.zip(['moe', 'larry'], [30, 40], [true, false]); -result = _.unzip(['moe', 'larry'], [30, 40], [true, false]); - -// /* ************* -// * Collections * -// ************* */ - -result = _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); -result = _.at(['moe', 'larry', 'curly'], 0, 2); - -result = _.contains([1, 2, 3], 1); -result = _.contains([1, 2, 3], 1, 2); -result = _.contains({ 'name': 'moe', 'age': 40 }, 'moe'); -result = _.contains('curly', 'ur'); - - result = _.include([1, 2, 3], 1); - result = _.include([1, 2, 3], 1, 2); - result = _.include({ 'name': 'moe', 'age': 40 }, 'moe'); - result = _.include('curly', 'ur'); - -result = <_.Dictionary>_.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); -result = <_.Dictionary>_.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); -result = <_.Dictionary>_.countBy(['one', 'two', 'three'], 'length'); - - result = <_.LoDashObjectWrapper<_.Dictionary>>_([4.3, 6.1, 6.4]).countBy(function(num) { return Math.floor(num); }); - result = <_.LoDashObjectWrapper<_.Dictionary>>_([4.3, 6.1, 6.4]).countBy(function(num) { return this.floor(num); }, Math); - result = <_.LoDashObjectWrapper<_.Dictionary>>_(['one', 'two', 'three']).countBy('length'); - -result = _.every([true, 1, null, 'yes'], Boolean); -result = _.every(stoogesAges, 'age'); -result = _.every(stoogesAges, { 'age': 50 }); - - result = _.all([true, 1, null, 'yes'], Boolean); - result = _.all(stoogesAges, 'age'); - result = _.all(stoogesAges, { 'age': 50 }); - -result = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); -result = _.filter(foodsCombined, 'organic'); -result = _.filter(foodsCombined, { 'type': 'fruit' }); - - result = _([1, 2, 3, 4, 5, 6]).filter(function(num) { return num % 2 == 0; }).value(); - result = _(foodsCombined).filter('organic').value(); - result = _(foodsCombined).filter({ 'type': 'fruit' }).value(); - - result = _.select([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); - result = _.select(foodsCombined, 'organic'); - result = _.select(foodsCombined, { 'type': 'fruit' }); - - result = _([1, 2, 3, 4, 5, 6]).select(function(num) { return num % 2 == 0; }).value(); - result = _(foodsCombined).select('organic').value(); - result = _(foodsCombined).select({ 'type': 'fruit' }).value(); - -result = _.find([1, 2, 3, 4], function(num) { - return num % 2 == 0; -}); -result = _.find(foodsCombined, { 'type': 'vegetable' }); -result = _.find(foodsCombined, 'organic'); - - result = _.detect([1, 2, 3, 4], function(num) { - return num % 2 == 0; - }); - result = _.detect(foodsCombined, { 'type': 'vegetable' }); - result = _.detect(foodsCombined, 'organic'); - - result = _.findWhere([1, 2, 3, 4], function(num) { - return num % 2 == 0; - }); - result = _.findWhere(foodsCombined, { 'type': 'vegetable' }); - result = _.findWhere(foodsCombined, 'organic'); - -result = _.findLast([1, 2, 3, 4], function(num) { - return num % 2 == 0; -}); -result = _.findLast(foodsCombined, { 'type': 'vegetable' }); -result = _.findLast(foodsCombined, 'organic'); - -result = _.forEach([1, 2, 3], function(num) { console.log(num); }); -result = <_.Dictionary>_.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); - - result = _.each([1, 2, 3], function(num) { console.log(num); }); - result = <_.Dictionary>_.each({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); - - result = <_.LoDashArrayWrapper>_([1, 2, 3]).forEach(function(num) { console.log(num); }); - result = <_.LoDashObjectWrapper<_.Dictionary>>_({ 'one': 1, 'two': 2, 'three': 3 }).forEach(function(num) { console.log(num); }); - - result = <_.LoDashArrayWrapper>_([1, 2, 3]).each(function(num) { console.log(num); }); - result = <_.LoDashObjectWrapper<_.Dictionary>>_({ 'one': 1, 'two': 2, 'three': 3 }).each(function(num) { console.log(num); }); - -result = _.forEachRight([1, 2, 3], function(num) { console.log(num); }); -result = <_.Dictionary>_.forEachRight({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); - - result = _.eachRight([1, 2, 3], function(num) { console.log(num); }); - result = <_.Dictionary>_.eachRight({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); - - result = <_.LoDashArrayWrapper>_([1, 2, 3]).forEachRight(function(num) { console.log(num); }); - result = <_.LoDashObjectWrapper<_.Dictionary>>_({ 'one': 1, 'two': 2, 'three': 3 }).forEachRight(function(num) { console.log(num); }); - - result = <_.LoDashArrayWrapper>_([1, 2, 3]).eachRight(function(num) { console.log(num); }); - result = <_.LoDashObjectWrapper<_.Dictionary>>_({ 'one': 1, 'two': 2, 'three': 3 }).eachRight(function(num) { console.log(num); }); - -result = <_.Dictionary>_.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); -result = <_.Dictionary>_.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); -result = <_.Dictionary>_.groupBy(['one', 'two', 'three'], 'length'); - - result = <_.LoDashObjectWrapper<_.Dictionary>>_([4.2, 6.1, 6.4]).groupBy(function(num) { return Math.floor(num); }); - result = <_.LoDashObjectWrapper<_.Dictionary>>_([4.2, 6.1, 6.4]).groupBy(function(num) { return this.floor(num); }, Math); - result = <_.LoDashObjectWrapper<_.Dictionary>>_(['one', 'two', 'three']).groupBy('length'); - -result = <_.Dictionary>_.indexBy(keys, 'dir'); -result = <_.Dictionary>_.indexBy(keys, function(key) { return String.fromCharCode(key.code); }); -result = <_.Dictionary>_.indexBy(keys, function(key) { this.fromCharCode(key.code); }, String); - -result = _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); -result = _.invoke([123, 456], String.prototype.split, ''); - -result = _.map([1, 2, 3], function(num) { return num * 3; }); -result = _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); -result = _.map(stoogesAges, 'name'); - - result = _([1, 2, 3]).map(function(num) { return num * 3; }).value(); - result = _({ 'one': 1, 'two': 2, 'three': 3 }).map(function(num) { return num * 3; }).value(); - result = _(stoogesAges).map('name').value(); - -result = _.collect([1, 2, 3], function(num) { return num * 3; }); -result = _.collect({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); -result = _.collect(stoogesAges, 'name'); - - result = _([1, 2, 3]).collect(function(num) { return num * 3; }).value(); - result = _({ 'one': 1, 'two': 2, 'three': 3 }).collect(function(num) { return num * 3; }).value(); - result = _(stoogesAges).collect('name').value(); - -result = _.max([4, 2, 8, 6]); -result = _.max(stoogesAges, function(stooge) { return stooge.age; }); -result = _.max(stoogesAges, 'age'); - -result = _.min([4, 2, 8, 6]); -result = _.min(stoogesAges, function(stooge) { return stooge.age; }); -result = _.min(stoogesAges, 'age'); - -result = _.pluck(stoogesAges, 'name'); - -result = _.reduce([1, 2, 3], function(sum: number, num: number) { - return sum + num; -}); -interface ABC { - a: number; - b: number; - c: number; -} -result = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(r: ABC, num, key) { - r[key] = num * 3; - return r; -}, {}); - -result = _.foldl([1, 2, 3], function(sum, num) { - return sum + num; -}); -result = _.foldl({ 'a': 1, 'b': 2, 'c': 3 }, function(r: ABC, num, key) { - r[key] = num * 3; - return r; -}, {}); - -result = _.inject([1, 2, 3], function(sum, num) { - return sum + num; -}); -result = _.inject({ 'a': 1, 'b': 2, 'c': 3 }, function(r: ABC, num, key) { - r[key] = num * 3; - return r; -}, {}); - -result = _.reduceRight([[0, 1], [2, 3], [4, 5]], function(a: number[], b: number[]) { return a.concat(b); }, []); -result = _.foldr([[0, 1], [2, 3], [4, 5]], function(a: number[], b: number[]) { return a.concat(b); }, []); - -result = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); -result = _.reject(foodsCombined, 'organic'); -result = _.reject(foodsCombined, { 'type': 'fruit' }); - -result = _.sample([1, 2, 3, 4]); -result = _.sample([1, 2, 3, 4], 2); - -result = _.shuffle([1, 2, 3, 4, 5, 6]); - -result = _.size([1, 2]); -result = _.size({ 'one': 1, 'two': 2, 'three': 3 }); -result = _.size('curly'); - -result = _.some([null, 0, 'yes', false], Boolean); -result = _.some(foodsCombined, 'organic'); -result = _.some(foodsCombined, { 'type': 'meat' }); - -result = _.any([null, 0, 'yes', false], Boolean); -result = _.any(foodsCombined, 'organic'); -result = _.any(foodsCombined, { 'type': 'meat' }); - -result = _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); -result = _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); -result = _.sortBy(['banana', 'strawberry', 'apple'], 'length'); - -(function(a: number, b: number, c: number, d: number){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4); - -result = _.where(stoogesCombined, { 'age': 40 }); -result = _.where(stoogesCombined, { 'quotes': ['Poifect!'] }); - -/************* - * Functions * - *************/ -var saves = ['profile', 'settings']; -var asyncSave = (obj: any) => obj.done(); -var done: Function; - -done = _.after(saves.length, function() { - console.log('Done saving!'); -}); - -_.forEach(saves, function(type) { - asyncSave({ 'type': type, 'complete': done }); -}); - -done = _(saves.length).after(function() { - console.log('Done saving!'); -}).value(); - -_.forEach(saves, function(type) { - asyncSave({ 'type': type, 'complete': done }); -}); - -var funcBind = function (greeting: string) { return greeting + ' ' + this.name }; -var funcBind2: () => any = _.bind(funcBind, { 'name': 'moe' }, 'hi'); -funcBind2(); - -var funcBind3: () => any = _(funcBind).bind({ 'name': 'moe' }, 'hi').value(); -funcBind3(); - -var view = { - 'label': 'docs', - 'onClick': function() { console.log('clicked ' + this.label); } -}; - -view = _.bindAll(view); -jQuery('#docs').on('click', view.onClick); - -view = _(view).bindAll().value(); -jQuery('#docs').on('click', view.onClick); - -var objectBindKey = { - 'name': 'moe', - 'greet': function(greeting: string) { - return greeting + ' ' + this.name; - } -}; - -var funcBindKey: Function = _.bindKey(objectBindKey, 'greet', 'hi'); -funcBindKey(); - -objectBindKey.greet = function(greeting) { - return greeting + ', ' + this.name + '!'; -}; - -funcBindKey(); - -funcBindKey = _(objectBindKey).bindKey('greet', 'hi').value(); -funcBindKey(); - -var realNameMap = { - 'curly': 'jerome' -}; - -var format = function(name: string) { - name = realNameMap[name.toLowerCase()] || name; - return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase(); -}; - -var greet = function(formatted: string) { - return 'Hiya ' + formatted + '!'; -}; - -result = _.compose(greet, format); -result = <_.LoDashObjectWrapper>_(greet).compose(format); - -var createCallbackObj = { name: 'Joe' }; -result = <() => any>_.createCallback('name'); -result = <() => boolean>_.createCallback(createCallbackObj); -result = <_.LoDashObjectWrapper<() => any>>_('name').createCallback(); -result = <_.LoDashObjectWrapper<() => boolean>>_(createCallbackObj).createCallback(); - -result = _.curry(function(a, b, c) { - console.log(a + b + c); -}); - -result = <_.LoDashObjectWrapper>_(function(a, b, c) { - console.log(a + b + c); -}).curry(); - -declare var source: any; -result = _.debounce(function() {}, 150); - -jQuery('#postbox').on('click', _.debounce(function() {}, 300, { - 'leading': true, - 'trailing': false -})); - -source.addEventListener('message', _.debounce(function() {}, 250, { - 'maxWait': 1000 -}), false); - -result = <_.LoDashObjectWrapper>_(function() {}).debounce(150); - -jQuery('#postbox').on('click', <_.LoDashObjectWrapper>_(function() {}).debounce(300, { - 'leading': true, - 'trailing': false -})); - -source.addEventListener('message', <_.LoDashObjectWrapper>_(function() {}).debounce(250, { - 'maxWait': 1000 -}), false); - -var returnedDebounce = _.throttle(function (a) { return a * 5; }, 5); -returnedThrottled(4); - -result = _.defer(function() { console.log('deferred'); }); -result = <_.LoDashWrapper>_(function() { console.log('deferred'); }).defer(); - -var log = _.bind(console.log, console); -result = _.delay(log, 1000, 'logged later'); -result = <_.LoDashWrapper>_(log).delay(1000, 'logged later'); - -var fibonacci = _.memoize(function(n) { - return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); -}); - -var data = { - 'moe': { 'name': 'moe', 'age': 40 }, - 'curly': { 'name': 'curly', 'age': 60 } -}; - -var stooge = _.memoize(function(name: string) { return data[name]; }, _.identity); -stooge('curly'); - -stooge['cache']['curly'].name = 'jerome'; -stooge('curly'); - -var returnedMemoize = _.throttle(function (a) { return a * 5; }, 5); -returnedMemoize(4); - -var initialize = _.once(function(){ }); -initialize(); -initialize();'' -var returnedOnce = _.throttle(function (a) { return a * 5; }, 5); -returnedOnce(4); - -var greetPartial = function(greeting: string, name: string) { return greeting + ' ' + name; }; -var hi = _.partial(greetPartial, 'hi'); -hi('moe'); - -var defaultsDeep = _.partialRight(_.merge, _.defaults); - -var optionsPartialRight = { - 'variable': 'data', - 'imports': { 'jq': $ } -}; - -defaultsDeep(optionsPartialRight, _.templateSettings); - -var throttled = _.throttle(function () { }, 100); -jQuery(window).on('scroll', throttled); - -jQuery('.interactive').on('click', _.throttle(function() { }, 300000, { - 'trailing': false -})); - -var returnedThrottled = _.throttle(function (a) { return a*5; }, 5); -returnedThrottled(4); - -var helloWrap = function(name: string) { return 'hello ' + name; }; -var helloWrap2 = _.wrap(helloWrap, function(func) { - return 'before, ' + func('moe') + ', after'; -}); -helloWrap2(); - -/********** -* Objects * -***********/ -interface NameAge { - name: string; - age: number; -} -result = _.assign({ 'name': 'moe' }, { 'age': 40 }); -result = _.assign({ 'name': 'moe' }, { 'age': 40 }, function(a, b) { - return typeof a == 'undefined' ? b : a; -}); - -result = <_.LoDashObjectWrapper>_({ 'name': 'moe' }).assign({ 'age': 40 }); -result = <_.LoDashObjectWrapper>_({ 'name': 'moe' }).assign({ 'age': 40 }, function(a, b) { - return typeof a == 'undefined' ? b : a; -}); - -result = _.extend({ 'name': 'moe' }, { 'age': 40 }); -result = _.extend({ 'name': 'moe' }, { 'age': 40 }, function(a, b) { - return typeof a == 'undefined' ? b : a; -}); - -result = <_.LoDashObjectWrapper>_({ 'name': 'moe' }).extend({ 'age': 40 }); -result = <_.LoDashObjectWrapper>_({ 'name': 'moe' }).extend({ 'age': 40 }, function(a, b) { - return typeof a == 'undefined' ? b : a; -}); - -result = _.clone(stoogesAges); -result = _.clone(stoogesAges, true); -result = _.clone(stoogesAges, true, function(value) { - return _.isElement(value) ? value.cloneNode(false) : undefined; -}); - -result = _.cloneDeep(stoogesAges); -result = _.cloneDeep(stoogesAges, function(value) { - return _.isElement(value) ? value.cloneNode(false) : undefined; -}); - -interface Food { - name: string; - type: string; -} -var foodDefaults = { 'name': 'apple' }; -result = _.defaults(foodDefaults, { 'name': 'banana', 'type': 'fruit' }); - result = <_.LoDashObjectWrapper>_(foodDefaults).defaults({ 'name': 'banana', 'type': 'fruit' }); - -result = _.findKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) { - return num % 2 == 0; -}); - -result = _.findLastKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) { - return num % 2 == 1; -}); - -result = _.forIn(new Dog('Dagny'), function(value, key) { - console.log(key); -}); - -result = <_.LoDashObjectWrapper>_(new Dog('Dagny')).forIn(function(value, key) { - console.log(key); -}); - -result = _.forInRight(new Dog('Dagny'), function(value, key) { - console.log(key); -}); - -result = <_.LoDashObjectWrapper>_(new Dog('Dagny')).forInRight(function(value, key) { - console.log(key); -}); - -interface ZeroOne { - 0: string; - 1: string; - one: string; -} - -result = _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { - console.log(key); -}); - - result = <_.LoDashObjectWrapper>_({ '0': 'zero', '1': 'one', 'length': 2 }).forOwn(function(num, key) { - console.log(key); - }); - -result = _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { - console.log(key); -}); - - result = <_.LoDashObjectWrapper>_({ '0': 'zero', '1': 'one', 'length': 2 }).forOwnRight(function(num, key) { - console.log(key); - }); - -result = _.functions(_); -result = _.methods(_); - -result = <_.LoDashArrayWrapper>_(_).functions(); -result = <_.LoDashArrayWrapper>_(_).methods(); - -result = _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); - -interface FirstSecond { - first: string; - second: string; -} -result = _.invert({ 'first': 'moe', 'second': 'larry' }); - -(function(...args: any[]) { return _.isArguments(arguments); })(1, 2, 3); - -(function () { return _.isArray(arguments); })(); -result = _.isArray([1, 2, 3]); - -result = _.isBoolean(null); - -result = _.isDate(new Date()); - -result = _.isElement(document.body); - -result = _.isEmpty([1, 2, 3]); -result = _.isEmpty({}); -result = _.isEmpty(''); - -var moe = { 'name': 'moe', 'age': 40 }; -var copy = { 'name': 'moe', 'age': 40 }; - -result = _.isEqual(moe, copy); - -var words = ['hello', 'goodbye']; -var otherWords = ['hi', 'goodbye']; - -result = _.isEqual(words, otherWords, function(a, b) { - var reGreet = /^(?:hello|hi)$/i, - aGreet = _.isString(a) && reGreet.test(a), - bGreet = _.isString(b) && reGreet.test(b); - - return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; -}); - -result = _.isFinite(-101); -result = _.isFinite('10'); -result = _.isFinite(true); -result = _.isFinite(''); -result = _.isFinite(Infinity); - -result = _.isFunction(_); - -result = _.isNaN(NaN); -result = _.isNaN(new Number(NaN)); -result = _.isNaN(undefined); - -result = _.isNull(null); -result = _.isNull(undefined); - -result = _.isNumber(8.4 * 5); - -result = _.isObject({}); -result = _.isObject([1, 2, 3]); -result = _.isObject(1); - -class Stooge { - constructor( - public name: string, - public age: number - ) {} -} - -result = _.isPlainObject(new Stooge('moe', 40)); -result = _.isPlainObject([1, 2, 3]); -result = _.isPlainObject({ 'name': 'moe', 'age': 40 }); - -result = _.isRegExp(/moe/); - -result = _.isString('moe'); - -result = _.isUndefined(void 0); - -result = _.keys({ 'one': 1, 'two': 2, 'three': 3 }); - -var mergeNames = { - 'stooges': [ - { 'name': 'moe' }, - { 'name': 'larry' } - ] -}; - -var mergeAges = { - 'stooges': [ - { 'age': 40 }, - { 'age': 50 } - ] -}; - -result = _.merge(mergeNames, mergeAges); - -var mergeFood = { - 'fruits': ['apple'], - 'vegetables': ['beet'] -}; - -var mergeOtherFood = { - 'fruits': ['banana'], - 'vegetables': ['carrot'] -}; - -interface FruitVeg { - fruits: string[]; - vegetables: string[] -}; - -result = _.merge(mergeFood, mergeOtherFood, function(a, b) { - return _.isArray(a) ? a.concat(b) : undefined; -}); - -interface HasName { - name: string; -} -result = _.omit({ 'name': 'moe', 'age': 40 }, 'age'); -result = _.omit({ 'name': 'moe', 'age': 40 }, ['age']); -result = _.omit({ 'name': 'moe', 'age': 40 }, function(value) { - return typeof value == 'number'; -}); - -result = _.pairs({ 'moe': 30, 'larry': 40 }); - -result = _.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name'); -result = _.pick({ 'name': 'moe', '_userid': 'moe1' }, ['name']); -result = _.pick({ 'name': 'moe', '_userid': 'moe1' }, function(value, key) { - return key.charAt(0) != '_'; -}); - -result = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(r, num) { - num *= num; - if (num % 2) { - return r.push(num) < 3; - } -}); -// → [1, 9, 25] - -result = <{a:number;b:number;c:number;}>_.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(r, num, key) { - r[key] = num * 3; -}); - -result = _.values({ 'one': 1, 'two': 2, 'three': 3 }); - -/********** -* Utilities * -***********/ - -result = _.escape('Moe, Larry & Curly'); - -result = <{ name: string }>_.identity({ 'name': 'moe' }); - -_.mixin({ - 'capitalize': function(string) { - return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); - } -}); - -var lodash = _.noConflict(); - -result = _.parseInt('08'); - -result = _.random(0, 5); -result = _.random(5); -result = _.random(5, true); -result = _.random(1.2, 5.2); -result = _.random(0, 5, true); - -var object = { - 'cheese': 'crumpets', - 'stuff': function() { - return 'nonsense'; - } -}; - -result = _.result(object, 'cheese'); -result = _.result(object, 'stuff'); - -var tempObject = {}; -result = _.runInContext(tempObject); - -result = <_.TemplateExecutor>_.template('hello <%= name %>'); -result = _.template('<%- value %>', { 'value': ' + * would display “[math]” in place of the math until MathJax is able to typeset it. + */ + preRemoveClass?:string; + /*This value controls whether the Processing Math: nn% messages are displayed in the lower left-hand corner. + * Set to false to prevent those messages (though file loading and other messages will still be shown). + */ + showProcessingMessages?:boolean; + /*This value controls the verbosity of the messages in the lower left-hand corner. Set it to "none" to eliminate + * all messages, or set it to "simple" to show “Loading...” and “Processing...” rather than showing the full file + * name or the percentage of the mathematics processed. + */ + messageStyle?:string; + /*These two parameters control the alignment and shifting of displayed equations. The first can be "left", + * "center", or "right", and determines the alignment of displayed equations. When the alignment is not "center", + * the second determines an indentation from the left or right side for the displayed equations.*/ + displayAlign?:string; + displayIndent?:string; + /*Normally MathJax will perform its startup commands (loading of configuration, styles, jax, and so on) as soon + * as it can. If you expect to be doing additional configuration on the page, however, you may want to have it + * wait until the page’s onload handler is called. If so, set this to "onload". You can also set this to + * "configured", in which case, MathJax will delay its startup until you explicitly call + * MathJax.Hub.Configured(). See Configuring MathJax after it is loaded for more details. + */ + delayStartupUntil?:string; + /*Normally MathJax will typeset the mathematics on the page as soon as the page is loaded. If you want to delay + * that process, in which case you will need to call MathJax.Hub.Typeset() yourself by hand, set this value to + * true. + */ + skipStartupTypeset?:boolean; + /*This is a list of DOM element ID’s that are the ones to process for mathematics when any of the Hub typesetting + * calls (Typeset(), Process(), Update(), etc.) are called with no element specified, and during MathJax’s initial + * typesetting run when it starts up. This lets you restrict the processing to particular containers rather than + * scanning the entire document for mathematics. If none are supplied, the complete document is processed. + */ + elements?:string[]; + /*ince typesetting usually changes the vertical dimensions of the page, if the URL contains an anchor position, + * then after the page is typeset, you may no longer be positioned at the correct position on the page. MathJax + * can reposition to that location after it completes its initial typesetting of the page. This value controls + * whether MathJax will reposition the browser to the #hash location from the page URL after typesetting for + * the page. + */ + positionToHash?:boolean; + /*These control whether to attach the MathJax contextual menu to the expressions typeset by MathJax. Since the + * code for handling MathPlayer in Internet Explorer is somewhat delicate, it is controlled separately via + * showMathMenuMSIE, but the latter is now deprecated in favor of the MathJax contextual menu settings for + * MathPlayer (see below). + * + * If showMathMenu is true, then right-clicking (on Windows or Linux) or control-clicking (on Mac OS X) will + * produce a MathJax menu that allows you to get the source of the mathematics in various formats, change the + * size of the mathematics relative to the surrounding text, get information about MathJax, and configure other + * MathJax settings. + * + * Set this to false to disable the menu. When true, the MathMenu configuration block determines the operation + * of the menu. See the MathMenu options for more details. + * + * These values used to be listed in the separate output jax, but have been moved to this more central location + * since they are shared by all output jax. MathJax will still honor their values from their original positions, + * if they are set there. + */ + showMathMenu?:boolean; + showMathMenuMSIE?:boolean; + /*This block contains settings for the mathematics contextual menu that act as the defaults for the user’s + * settings in that menu. + * There are also settings for format, renderer, font, mpContext, and mpMouse, but these are maintained by + * MathJax and should not be set by the page author. + */ + menuSettings?:IMenuSettings; + /*This block contains settings that control how MathJax responds to unexpected errors while processing + * mathematical equations. Rather than simply crash, MathJax can report an error and go on. + */ + errorSettings?:IErrorSettings; + "v1.0-compatible"?:boolean; + } + + export interface IMathZoom { + /*This is a list of CSS declarations for styling the zoomed mathematics. See the definitions in + * extensions/MathZoom.js for details of what are defined by default. See CSS Style Objects for details on how + * to specify CSS style in a JavaScript object. + */ + styles:any; + } + + export interface IMathMenu { + /*This is the hover delay for the display (in milliseconds) for submenus in the contextual menu: when the mouse + * is over a submenu label for this long, the menu will appear. (The submenu also will appear if you click on its + * label.) + */ + delay?:number; + /*This is the URL for the MathJax Help menu item. When the user selects that item, the browser opens a new window + * with this URL. + */ + helpURL?:string; + /*This controls whether the “Math Renderer” item will be displayed in the “Math Settings” submenu of the MathJax + * contextual menu. It allows the user to change between the HTML-CSS, NativeMML, and SVG output processors for + * the mathematics on the page. Set to false to prevent this menu item from showing. + */ + showRenderer?:boolean; + /*This controls whether the “Font Preference” item will be displayed in the “Math Settings” submenu of the MathJax + * contextual menu. This submenu lets the user select what font to use in the mathematics produced by the HTML-CSS + * output processor. Note that changing the selection in the font menu will cause the page to reload. Set to false + * to prevent this menu item from showing. + * */ + showFontMenu?:boolean; + /*This controls whether the “Language” item will be displayed in the MathJax contextual menu. This submenu allows + * the user to select the language to use for the MathJax user interface, including the contextual menu, the about + * and help dialogs, the message box at the lower left, and any warning messages produced by MathJax. Set this to + * false to prevent this menu item from showing. This will force the user to use the language you have set for + * MathJax. + */ + showLocale?:boolean; + /*This controls whether the “MathPlayer” item will be displayed in the “Math Settings” submenu of the MathJax + * contextual menu. This submenu lets the user select what events should be passed on to the MathPlayer plugin, + * when it is present. Mouse events can be passed on (so that clicks will be processed by MathPlayer rather than + * MathJax), and menu events can be passed on (to allow the user access to the MathPlayer menu). Set to false to + * prevent this menu item from showing. + * */ + showMathPlayer?:boolean; + /*This controls whether the “Contextual Menu” item will be displayed in the “Math Settings” submenu of the MathJax + * contextual menu. It allows the user to decide whether the MathJax menu or the browser’s default contextual menu + * will be shown when the context menu click occurs over mathematics typeset by MathJax. Set to false to prevent + * this menu item from showing. + */ + showContext?:boolean; + /*These are the settings for the Annotation submenu of the “Show Math As” menu. If the root element has a + * child that contains one of the following annotation formats, the source will be available via the + * “Show Math As” menu. Each format has a list of possible encodings. For example, "TeX": ["TeX", "LaTeX", + * "application/x-tex"] will map an annotation with an encoding of "TeX", "LaTeX", or "application/x-tex" to the + * "TeX" menu. + */ + semanticsAnnotations?:any; + /*These are the settings for the window.open() call that creates the Show Source window. The initial width and + * height will be reset after the source is shown in an attempt to make the window fit the output better. + */ + windowSettings?:any; + /*This is a list of CSS declarations for styling the menu components. See the definitions in + * extensions/MathMenu.js for details of what are defined by default. See CSS Style Objects for details on how + * to specify CSS style in a JavaScript object. + */ + styles?:any; + } + + export interface IMathEvents { + /*This value is the time (in milliseconds) that a user must hold the mouse still over a math element before it + * is considered to be hovering over the math. + */ + hover?:number; + /*This is a list of CSS declarations for styling the zoomed mathematics. See the definitions in + * extensions/MathEvents.js for details of what are defined by default. See CSS Style Objects for details on how + * to specify CSS style in a JavaScript object. + */ + styles?:any; + } + + export interface IFontWarnings { + /*This sets the CSS styles to be used for the font warning message window. See the extensions/FontWarnings.js + * file for details of what are set by default. See the CSS style objects for details about how to specify CSS + * styles via javascript objects. + */ + messageStyle?:any; + /*This block contains HTML snippets to be used for the various messages that the FontWarning extension can + * produce. + * See the description of HTML snippets for details about how to describe the messages using HTML snippets. Note + * that in addition to the usual rules for defining such snippets, the FontWarnings snippets can include + * references to pre-defined snippets (that represent elements common to all three messages). These are defined + * below in the HTML block, and are referenced using ["name"] within the snippet, where name is the name of one + * of the snippets defined in the HTML configuration block + */ + Message?:IHTMLMessages; + /*This object defines HTML snippets that are common to more than one message in the Message section above. They + * can be included in other HTML snippets by by using ["name"] in an HTML snippet, where name refers to the name + * of the snippet in the HTML block. + * You can add your own pre-defined HTML snippets to this object, or override the ones that are there with your + * own text. + */ + HTML?:IHTMLSnippets; + /*This is the amount of time to show the FontWarning message, in milliseconds. The default is 12 seconds. + * Setting this value to zero means that the message will not fade out (the user must close it manually). + */ + removeAfter?:number; + /*This is the number of steps to take while fading out the FontWarning message. More steps make for a smoother + * fade-out. Set to zero to cause the message to be removed without fading. + */ + fadeoutSteps?:number; + /*This is the time used to perform the fade-out, in milliseconds. The default is 1.5 seconds.*/ + fadeoutTime?:number; + } + + export interface IHTMLMessages { + /*The message used for when MathJax uses web-based fonts (rather than local fonts installed on the user’s + * system). + */ + webFont?:any[]; + /*The message used for when MathJax must use image fonts rather than local or web-based fonts (for those + * browsers that don’t handle the @font-face CSS directive). + */ + imageFonts?:any[]; + /*The message used when MathJax is unable to find any font to use (i.e., neither local nor web-based nor + * image-based fonts are available). + */ + noFonts?:any[]; + } + + export interface IHTMLSnippets { + /*The HTML for the close box in the FontWarning message.*/ + closeBox?:string; + /*The HTML for a paragraph suggesting an upgrade to a more modern browser that supports web fonts.*/ + webfonts?:string; + /*HTML that includes links to the MathJax and STIX font download pages.*/ + fonts?:string; + /*HTML that gives the download link for the STIX fonts only. (Used in place of fonts when the HTML-CSS option + * for availableFonts only includes the STIX fonts.) + */ + STIXfonts?:string; + /*HTML that gives the download link for the MathJax TeX fonts only. (Used in place of fonts when the HTML-CSS + * option for availableFonts only includes the TeX fonts.) + */ + TeXfonts?:string; + } + + export interface ISafe { + /*This block contains the flags that control what the Safe extension will allow, and what it will block. The + * flags can be set to "all", "none", or "safe". When set to "all", no filtering is done for these values (this + * gives MathJax’s default behavior). When set to "none", these values are always filtered out. When set to + * "safe", then only some values are allowed. + */ + allow?:ISafeAllow; + /*This is the minimum font size (in em’s) that the TeX input jax will allow when fontsize is set to "safe" above. + * The default is the size of \scriptsize. Values less than this are set to this value. + */ + sizeMin?:number; + /*This is the maximum font size (in em’s) that the TeX input jax will allow when fontsize is set to "safe" above. + * The default is the size of \large. Values larger than this are set to this value. + */ + sizeMax?:number; + /*This is an object that lists the protocols that can be used in href attributes and the \href macro when URLs + * is set to "safe" above. + * Note that if a protocol doesn’t appear in the list, it is assumed to be false, so technically, javascript need + * not have been listed, but it is given to make it explicit that it should not be allowed. + */ + safeProtocols?:ISafeProtocols; + /*This is an object that lists the style properties that can be used in MathML style attributes and the \style + * and \bbox macros when styles is set to "safe" in the allowed property above. + * Any style property that doesn’t appear on this list is not allowed to be entered and will be removed (silently) + * from the style definition. + */ + safeStyles?:ISafeStyles; + /*This is an object that lists the TeX extensions that can be loaded via the \require{} macro when require is + * set to "safe" in the allowed property above. + * These configuration options give you a lot of control over what actions MathJax is allowed to take. It is also + * possible override the individual filtering functions in order to customize the filtering even further, should + * that be needed. See the code for the details of the function names and their definitions. + */ + safeRequire?:ISafeRequire; + } + + export interface ISafeAllow { + /*When set to "safe" only URL’s with protocols that are listed in the safeProtocols property (see below) are + * allowed as targets of href attributes or the \href macro. By default, these are http://, https://, and + * file:// URL’s. + */ + URLs?:string; + /*When set to "safe", only class names that begin with MJX- and contain only letters, numbers, or the + * characters -, _, or . are allowed. + */ + classes?:string; + /*When set to "safe", only ID’s that begin with MJX- and contain only letters, numbers, or the characters -, _, + * or . are allowed. + */ + cssIDs?:string; + /*When set to "safe", only styles taken from a predefined set of styles are allowed to be given. These are + * listed in the safeStyles property (see below). + */ + styles?:string; + /*When set to "safe", only the extensions listed in the safeRequire property (see below) are allowed to be + * loaded by the \require{} macro. + */ + require?:string; + /*When set to "safe", MathJax will try to limit the font size to sizes between those given by the sizeMin and + * sizeMax properties. These are .7 and 1.44 by default, which means sizes between \scriptsize and \large are + * allowed. This also filters MathML fontsize, mathsize, and scriptminsize attributes, but here, "safe" acts as + * "none", since they are given in sizes with units, and the actual size of the units is not determined at input + * time (it is part of the output processing). In addition, the scriptlevel attribute is restricted to + * non-negative values (so scripts can’t be made larger), and the scriptsizemultiplier is restricted to being + * no larger than 1, and no less than .6. + */ + fontsize?:string; + } + + export interface ISafeProtocols { + http?:boolean; + https?:boolean; + file?:boolean; + javascript?:boolean; + } + + export interface ISafeStyles { + color?:boolean; + backgroundColor?:boolean; + border?:boolean; + cursor?:boolean; + margin?:boolean; + padding?:boolean; + textShadow?:boolean; + fontFamily?:boolean; + fontSize?:boolean; + fontStyle?:boolean; + fontWeight?:boolean; + opacity?:boolean; + outline?:boolean; + } + + export interface ISafeRequire { + action?:boolean; + amscd?:boolean; + amsmath?:boolean; + amssymbols?:boolean; + autobold?:boolean; + "autoload-all"?:boolean; + bbox?:boolean; + begingroup?:boolean; + boldsymbol?:boolean; + cancel?:boolean; + color?:boolean; + enclose?:boolean; + extpfeil?:boolean; + HTML?:boolean; + mathchoice?:boolean; + mhchem?:boolean; + newcommand?:boolean; + noErrors?:boolean; + noUndefined?:boolean; + unicode?:boolean; + verb?:boolean; + } + + export interface IMatchWebFonts { + /*This block controls whether to apply font size matching for each output mode.*/ + matchFor?:IMatchFor; + /*Initial delay before the first check for web fonts (in milliseconds).*/ + fontCheckDelay?:number; + /*How long to keep looking for fonts (in milliseconds).*/ + fontCheckTimeout?:number; + } + + export interface IMatchFor { + /*Whether to match the font size for the HTML-CSS output.*/ + "HTML-CSS"?:boolean; + /*Whether to match the font size for the NativeMML output.*/ + NativeMML?:boolean; + /*Whether to match the font size for the SVG output.*/ + SVG?:boolean; + } + + export interface ISVGOutputProcessor { + /*The scaling factor (as a percentage) of math with respect to the surrounding text. The SVG output processor + * tries to match the ex-size of the mathematics with that of the text where it is placed, but you may want to + * adjust the results using this scaling factor. The user can also adjust this value using the contextual menu + * item associated with the typeset mathematics. + */ + scale?:number; + /*This gives a minimum scale (as a percent) for the scaling used by MathJax to match the equation to the + * surrounding text. This will prevent MathJax from making the mathematics too small. + */ + minScaleAdjust?:number; + /*This is the font to use for rendering the mathematics. The possible values are TeX, STIX-Web, Asana-Math, + * Neo-Euler, Gyre-Pagella, Gyre-Termes and Latin-Modern. Note that not all mathematical characters are available + * in all fonts (e.g., Neo-Euler does not include italic characters), so some mathematics may work better in some + * fonts than in others. The STIX-Web font is the most complete. + */ + font?:string; + /*This is the stroke width to use for all character paths (1em = 1000 units). This is a cheap way of getting + * slightly lighter or darker characters, but remember that not all displays will act the same, so a value that + * is good for you may not be good for everyone. + */ + blacker?:number; + /*This is the font-family CSS value used for characters that are not in the selected font (e.g., this is where + * to look for characters not included in the MathJax TeX fonts). IE will stop looking after the first font that + * exists on the system (even if it doesn’t contain the needed character), so order these carefully. + */ + undefinedFamily?:string[]; + /*This setting controls whether elements will be typeset using the math fonts or the font of the + * surrounding text. When false, the font for mathvariant="normal" will be used; when true, the font will be + * inherited from the surrounding paragraph. + */ + mtextFontInherit?:boolean; + /*This controls whether the MathML structure is retained and CSS classes are added to mark the original MathML + * elements (as in the output from the HTML-CSS output jax). By default, the SVG output jax removes unneeded + * nesting in order to produce a more efficient markup, but if you want to use CSS to style the elements as if + * they were MathML, you might need to set this to true. + */ + addMMLclasses?:boolean; + /*EqnChunk is the number of equations that will be typeset before they appear on screen. Larger values make for + * less visual flicker as the equations are drawn, but also mean longer delays before the reader sees anything. + */ + EqnChunk?:number; + /*EqChunkFactor is the factor by which the EqnChunk will grow after each chunk is displayed.*/ + EqnChunkFactor?:number; + /*EqChunkDelay is the time (in milliseconds) to delay between chunks (to allow the browser to respond to other + * user interaction). + * Set EqnChunk to 1, EqnChunkFactor to 1, and EqnChunkDelay to 10 to get the behavior from MathJax v1.1 and + * below. + */ + EqnChunkDelay?:number; + /*This option indicates whether MathJax should try to adjust the x-height of equations to match the x-height of + * the surrounding text. See the MatchWebFonts options for finer control, especially if you are using Web fonts. + */ + matchFontHeight?:boolean; + /*This is an object that configures automatic linebreaking in the SVG output. In order to be backward compatible + * with earlier versions of MathJax, only explicit line breaks are performed by default, so you must enable line + * breaks if you want automatic ones. + */ + linebreaks?:ILineBreaks; + /*This is a list of CSS declarations for styling the SVG output. See the definitions in jax/output/SVG/config.js + * for some examples of what are defined by default. See CSS Style Objects for details on how to specify CSS + * style in a JavaScript object. + */ + styles?:any; + /*This sets the configuration options for elements with actiontype="tooltip". (See also the + * #MathJax_Tooltip style setting in jax/output/SVG/config.js, which can be overridden using the styles option + * above.) + */ + tooltip?:IToolTip; + } + + export interface ILineBreaks { + /*This controls the automatic breaking of expressions: when false, only linebreak="newline" is processed; when + * true, line breaks are inserted automatically in long expressions. + */ + automatic?:boolean; + /*This controls how wide the lines of mathematics can be. + * Use an explicit width like "30em" for a fixed width. Use "container" to compute the size from the containing + * element. Use "nn% container" for a portion of the container. Use "nn%" for a portion of the window size. + * The container-based widths may be slower, and may not produce the expected results if the layout width changes + * due to the removal of previews or inclusion of mathematics during typesetting. + */ + width?:string; + } + + export interface IToolTip { + /*The delay (in milliseconds) before the tooltip is posted after the mouse is moved over the maction element.*/ + delayPost:number; + /*The delay (in milliseconds) before the tooltop is cleared after the mouse moves out of the maction element.*/ + delayClear:number; + /*The X offset from the mouse position (in pixels) where the tooltip will be placed.*/ + offsetX:number; + /*The Y offset from the mouse position (in pixels) where the tooltip will be placed.*/ + offsetY:number; + } + + export interface IMMLorHTMLConfiguration { + /*This lets you set the preferred renderer on a browser-by-browser basis. You set the browser to either "MML" or + * "HTML" depending on whether you want to use the NativeMML or HTML-CSS output processor. Note that although + * Opera and Safari do process some MathML natively, their support is not sufficient to handle the more + * complicated output generated by MathJax, so their settings are "HTML" by default. Although Firefox does + * support a large subset of MathJax, it does not implement all the features needed by MathJax, and so it is + * also set to "HTML" by default (this is new in v2.0). + * + * Note that users can still use the MathJax contextual menu to select a different renderer after the default + * one has been chosen by MMLorHTML.js. + */ + prefer?:IBrowserPreference; + } + + export interface IBrowserPreference { + MSIE?:string; + Firefox?:string; + Safari?:string; + Chrome?:string; + Opera?:string; + other?:string; + } + + export interface INativeMMLOutputProcessor { + /*The scaling factor (as a percentage) of math with respect to the surrounding text. The NativeMML output + * processor tries to match the ex-size of the mathematics with that of the text where it is placed, but you may + * want to adjust the results using this scaling factor. The user can also adjust this value using the contextual + * menu item associated with the typeset mathematics. + */ + scale?:number; + /*This gives a minimum scale (as a percent) for the scaling used by MathJax to match the equation to the + * surrounding text. This will prevent MathJax from making the mathematics too small. + */ + minScaleAdjust?:number; + /*This option indicates whether MathJax should try to adjust the x-height of equations to match the x-height of + * the surrounding text. See the MatchWebFonts options for finer control, especially if you are using Web fonts. + */ + matchFontHeight?:boolean; + /*This is a list of CSS declarations for styling the NativeMML output. See the definitions in + * jax/output/NativeMML/config.js for some examples of what are defined by default. See CSS Style Objects for + * details on how to specify CSS style in a JavaScript object. + */ + styles?:any; + } + + export interface IHTMLCSSOutputProcessor { + /*The scaling factor (as a percentage) of math with respect to the surrounding text. The HTML-CSS output + * processor tries to match the ex-size of the mathematics with that of the text where it is placed, but you may + * want to adjust the results using this scaling factor. The user can also adjust this value using the contextual + * menu item associated with the typeset mathematics. + */ + scale?:number; + /*This gives a minimum scale (as a percent) for the scaling used by MathJax to match the equation to the + * surrounding text. This will prevent MathJax from making the mathematics too small. + */ + minScaleAdjust?:number; + /*This is a list of the fonts to look for on a user’s computer in preference to using MathJax’s web-based fonts. + * These must correspond to directories available in the jax/output/HTML-CSS/fonts directory, where MathJax + * stores data about the characters available in the fonts. Set this to ["TeX"], for example, to prevent the use + * of the STIX fonts, or set it to an empty list, [], if you want to force MathJax to use web-based or image + * fonts. + */ + availableFonts?:string[]; + /*Which font to prefer out of the availableFonts list, when more than one is available on the user’s computer. + * Set it to null if you want MathJax to use web-based or image fonts. + */ + preferredFont?:string; + /*This is the web-based font to use when none of the fonts listed above are available on the user’s computer. The + * possible values are TeX, STIX-Web, Asana-Math, Neo-Euler, Gyre-Pagella, Gyre-Termes and Latin-Modern. Note + * that not all mathematical characters are available in all fonts (e.g., Neo-Euler does not include italic + * characters), so some mathematics may work better in some fonts than in others. The STIX-Web font is the most + * complete. + * + * These fonts are stored in the fonts/HTML-CSS folder in the MathJax directory. Set this to null to disable web + * fonts. + */ + webFont?:string; + /* This is the font to use for image fallback mode (when none of the fonts listed above are available and the + * browser doesn’t support web-fonts via the @font-face CSS directive). Note that currently only the TeX font is + * available as an image font (they are stored in the fonts/HTML-CSS directory). + * + * Set this to null if you want to prevent the use of image fonts (e.g., you have deleted or not installed the + * image fonts on your server). In this case, only browsers that support web-based fonts will be able to view + * your pages without having the fonts installed on the client computer. The browsers that support web-based + * fonts include: IE6 and later, Chrome, Safari3.1 and above, Firefox3.5 and later, and Opera10 and later. Note + * that Firefox3.0 is not on this list. + */ + imageFont?:string; + /*This is the font-family CSS value used for characters that are not in the selected font (e.g., for web-based + * fonts, this is where to look for characters not included in the MathJax web fonts). IE will stop looking after + * the first font that exists on the system (even if it doesn’t contain the needed character), so order these + * carefully. + */ + undefinedFamily?:string[]; + /*This setting controls whether elements will be typeset using the math fonts or the font of the + * surrounding text. When false, the font for mathvariant="normal" will be used; when true, the font will be + * inherited from the surrounding paragraph. + */ + mtextFontInherit?:boolean; + /*EqnChunk is the number of equations that will be typeset before they appear on screen. Larger values make for + * less visual flicker as the equations are drawn, but also mean longer delays before the reader sees anything. + */ + EqnChunk?:number; + /*EqChunkFactor is the factor by which the EqnChunk will grow after each chunk is displayed.*/ + EqnChunkFactor?:number; + /*EqChunkDelay is the time (in milliseconds) to delay between chunks (to allow the browser to respond to other + * user interaction). + * Set EqnChunk to 1, EqnChunkFactor to 1, and EqnChunkDelay to 10 to get the behavior from MathJax v1.1 and + * below. + */ + EqnChunkDelay?:number; + /*This option indicates whether MathJax should try to adjust the x-height of equations to match the x-height of + * the surrounding text. See the MatchWebFonts options for finer control, especially if you are using Web fonts. + */ + matchFontHeight?:boolean; + /*This is an object that configures automatic linebreaking in the SVG output. In order to be backward compatible + * with earlier versions of MathJax, only explicit line breaks are performed by default, so you must enable line + * breaks if you want automatic ones. + */ + linebreaks?:ILineBreaks; + /*This is a list of CSS declarations for styling the SVG output. See the definitions in jax/output/SVG/config.js + * for some examples of what are defined by default. See CSS Style Objects for details on how to specify CSS + * style in a JavaScript object. + */ + styles?:any; + /*This value has been moved to the core configuration block, since it applies to all output jax, but it will + * still be honored (for now) if it is set here. See the Core configuration options for more details. + */ + showMathMenu?:boolean; + /*This sets the configuration options for elements with actiontype="tooltip". (See also the + * #MathJax_Tooltip style setting in jax/output/SVG/config.js, which can be overridden using the styles option + * above.) + */ + tooltip?:IToolTip; + } + + export interface IAsciiMathInputProcessor { + /*Determines whether operators like summation symbols will have their limits above and below the operators + * (true) or to their right (false). The former is how they would appear in displayed equations that appear on + * their own lines, while the latter is better suited to in-line equations so that they don’t interfere with the + * line spacing so much. + */ + displaystyle?:boolean; + /*This is the character to be used for decimal points in numbers. if you change this to ",", then you need to be + * careful about entering points or intervals. E.g., use (1, 2) rather than (1,2) in that case. + */ + decimal?:string; + } + + export interface IMathMLInputProcessor { + /*Specifies whether to use TeX spacing or MathML spacing when the HTML-CSS output jax is used.*/ + useMathMLspacing?:boolean; + } + + export interface ITeXInputProcessor { + /*This specifies the side on which \tag{} macros will place the tags. Set it to "left" to place the tags on the + * left-hand side. + */ + TagSide?:string; + /*This is the amount of indentation (from the right or left) for the tags produced by the \tag{} macro.*/ + TagIndent?:string; + /*The width to use for the multline environment that is part of the AMSmath extension. This width gives room for + * tags at either side of the equation, but if you are displaying mathematics in a small area or a thin column of + * text, you might need to change the value to leave sufficient margin for tags. + */ + MultLineWidth?:string; + /*This object controls the automatic equation numbering and the equation referencing.*/ + equationNumbers?:IEquationNumbers; + /*This lists macros to define before the TeX input processor begins. These are name:value pairs where the name + * gives the name of the TeX macro to be defined, and value gives the replacement text for the macro. The value + * can be an array of the form [value,n], where value is the replacement text and n is the number of parameters + * for the macro. Note that since the value is a javascript string, backslashes in the replacement text must be + * doubled to prevent them from acting as javascript escape characters. + */ + Macros?:any; + /*Because a definition of the form \def\x{\x} \x would cause MathJax to loop infinitely, the MAXMACROS constant + * will limit the number of macro substitutions allowed in any expression processed by MathJax. + */ + MAXMACROS?:number; + /*Because a definition of the form \def\x{\x aaa} \x would loop infinitely, and at the same time stack up lots + * of a’s in MathJax’s equation buffer, the MAXBUFFER constant is used to limit the size of the string being + * processed by MathJax. It is set to 5KB, which should be sufficient for any reasonable equation. + */ + MAXBUFFER?:number; + } + + export interface IEquationNumbers { + /*This controls whether equations are numbered and how. By default it is set to "none" to be compatible with + * earlier versions of MathJax where auto-numbering was not performed (so pages will not change their + * appearance). You can change this to "AMS" for equations numbered as the AMSmath package would do, or "all" to + * get an equation number for every displayed equation. + */ + autoNumber?:string; + /*A function that tells MathJax what tag to use for equation number n. This could be used to have the equations + * labeled by a sequence of symbols rather than numbers, or to use section and subsection numbers instead. + */ + formatNumber?:(n:number)=>string; + /*A function that tells MathJax how to format an equation number for displaying as a tag for an equation. This + * is what appears in the margin of a tagged or numbered equation.*/ + formatTag?:(n:number)=>string; + /*A function that tells MathJax what ID to use as an anchor for the equation (so that it can be used in URL + * references). + */ + formatID?:()=>string; + /*A function that takes an equation ID and returns the URL to link to it.*/ + formatURL?:(id:string)=>string; + /*This controls whether element ID’s use the \label name or the equation number. When true, use the label, when + * false, use the equation number. + */ + useLabelIds?:boolean; + } + + export interface IJSMath2jaxPreprocessor { + /*This controls whether jsMath2jax inserts MathJax_Preview spans to make a preview available, and what preview + * to use, when it locates in-line or display mathematics in the page. The default is "TeX", which means use the + * TeX code as the preview (which will be visible until it is processed by MathJax). Set to "none" to prevent + * previews from being inserted (the math will simply disappear until it is typeset). Set to an array containing + * the description of an HTML snippet in order to use the same preview for all equations on the page. + */ + preview:any; + } + + export interface IAsciimath2jaxPreprocessor { + /*Array of pairs of strings that are to be used as math delimiters. The first in each pair is the initial + * delimiter and the second is the terminal delimiter. You can have as many pairs as you want. For example, + * + * delimiters: [ ['$','$'], ['`','`'] ] + * would cause asciimath2jax to look for $...$ and `...` as delimiters for inline mathematics. (Note that the + * single dollar signs are not enabled by default because they are used too frequently in normal text, so if you + * want to use them for math delimiters, you must specify them explicitly.) + * + * Note that the delimiters can’t look like HTML tags (i.e., can’t include the less-than sign), as these would be + * turned into tags by the browser before MathJax has the chance to run. You can only include text, not tags, + * as your math delimiters. + */ + delimiters?:any; + /*This controls whether asciimath2jax inserts MathJax_Preview spans to make a preview available, and what + * preview to use, when it locates in-line or display mathematics in the page. The default is "AsciiMath", which + * means use the ASCIIMath code as the preview (which will be visible until it is processed by MathJax). Set to + * "none" to prevent previews from being inserted (the math will simply disappear until it is typeset). Set to + * an array containing the description of an HTML snippet in order to use the same preview for all equations + * on the page. + * + * Examples: + * + * preview: ["[math]"], // insert the text "[math]" as the preview + * preview: [["img",{src: "/images/mypic.jpg"}]], // insert an image as the preview + */ + preview?:any; + /*This array lists the names of the tags whose contents should not be processed by asciimath2jax (other than to + * look for ignore/process classes as listed below). You can add to (or remove from) this list to prevent MathJax + * from processing mathematics in specific contexts. + */ + skipTags?:string[]; + /*This is the class name used to mark elements whose contents should not be processed by asciimath2jax (other + * than to look for the processClass pattern below). Note that this is a regular expression, and so you need to + * be sure to quote any regexp special characters. The pattern is inserted into one that requires your pattern to + * match a complete word, so setting ignoreClass: "class2" would cause it to match an element with class="class1 + * class2 class3" but not class="myclass2". Note that you can assign several classes by separating them by the + * vertical line character (|). For instance, with ignoreClass: "class1|class2" any element assigned a class of + * either class1 or class2 will be skipped. + */ + ignoreClass?:string; + /*This is the class name used to mark elements whose contents should be processed by asciimath2jax. This is used + * to restart processing within tags that have been marked as ignored via the ignoreClass or to cause a tag that + * appears in the skipTags list to be processed rather than skipped. Note that this is a regular expression, and + * so you need to be sure to quote any regexp special characters. The pattern is inserted into one that requires + * your pattern to match a complete word, so setting processClass: "class2" would cause it to match an element + * with class="class1 class2 class3" but not class="myclass2". Note that you can assign several classes by + * separating them by the vertical line character (|). For instance, with processClass: "class1|class2" any + * element assigned a class of either class1 or class2 will have its contents processed. + */ + processClass?:string; + } + + export interface IMML2jaxPreprocessor { + /*This controls whether mml2jax inserts MathJax_Preview spans to make a preview available, and what preview to + * use, when it locates mathematics on the page. Possible values are: "mathml", "alttext", , "altimg", "none", + * or an HTML snippet. + * + * The default is "mathml", in which case MathJax keeps the content of the tag as the preview (until it is + * processed by MathJax). Set to "alttext", to use the tag’s alttext attribute as the preview, if the tag + * has one. Set to "altimg" to use an image described by the altimg* attributes of the element. Set to + * "none" to prevent the previews from being inserted (the math will simply disappear until it is typeset). Set + * to an array containing the description of an HTML snippet in order to use the same preview for all equations + * on the page (e.g., you could have it say "[math]" or load an image). + * + * Examples: + * + * preview: ["[math]"], // insert the text "[math]" as the preview + * preview: [["img",{src: "/images/mypic.jpg"}]], // insert an image as the preview + */ + preview?:any; + } + + export interface ITEX2jaxPreprocessor { + /*Array of pairs of strings that are to be used as in-line math delimiters. The first in each pair is the + * initial delimiter and the second is the terminal delimiter. You can have as many pairs as you want. For + * example, + * + * inlineMath: [ ['$','$'], ['\\(','\\)'] ] + * would cause tex2jax to look for $...$ and \(...\) as delimiters for inline mathematics. (Note that the single + * dollar signs are not enabled by default because they are used too frequently in normal text, so if you want to + * use them for math delimiters, you must specify them explicitly.) + * + * Note that the delimiters can’t look like HTML tags (i.e., can’t include the less-than sign), as these would be + * turned into tags by the browser before MathJax has the chance to run. You can only include text, not tags, as + * your math delimiters. + */ + inlineMath?:any; + /*Array of pairs of strings that are to be used as delimiters for displayed equations. The first in each pair is + * the initial delimiter and the second is the terminal delimiter. You can have as many pairs as you want. + * + * Note that the delimiters can’t look like HTML tags (i.e., can’t include the less-than sign), as these would be + * turned into tags by the browser before MathJax has the chance to run. You can only include text, not tags, as + * your math delimiters. + */ + displayMath?:any; + /*This value determines whether tex2jax requires braces to be balanced within math delimiters (which allows for + * nested dollar signs). Set to false to get pre-v2.0 compatibility. When true, + * + * $y = x^2 \hbox{ when $x > 2$}$. + * will be properly handled as a single expression. When false, it would be interpreted as two searpate + * expressions, each with improperly balanced braces. + */ + balanceBraces?:boolean; + /*When set to true, you may use \$ to represent a literal dollar sign, rather than using it as a math delimiter. + * When false, \$ will not be altered, and the dollar sign may be considered part of a math delimiter. Typically + * this is set to true if you enable the $ ... $ in-line delimiters, so you can type \$ and tex2jax will convert + * it to a regular dollar sign in the rendered document. + */ + processEscapes?:boolean; + /*When true, tex2jax looks not only for the in-line and display math delimiters, but also for LaTeX environments + * (\begin{something}...\end{something}) and marks them for processing by MathJax. When false, LaTeX environments + * will not be processed outside of math mode. + */ + processEnvironments?:boolean; + /*This controls whether tex2jax inserts MathJax_Preview spans to make a preview available, and what preview to + * use, when it locates in-line or display mathematics in the page. The default is "TeX", which means use the TeX + * code as the preview (which will be visible until it is processed by MathJax). Set to "none" to prevent + * previews from being inserted (the math will simply disappear until it is typeset). Set to an array containing + * the description of an HTML snippet in order to use the same preview for all equations on the page. + * + * Examples: + * + * preview: ["[math]"], // insert the text "[math]" as the preview + * preview: [["img",{src: "/images/mypic.jpg"}]], // insert an image as the preview + */ + preview?:any; + /*This array lists the names of the tags whose contents should not be processed by tex2jax (other than to look + * for ignore/process classes as listed below). You can add to (or remove from) this list to prevent MathJax from + * processing mathematics in specific contexts. + */ + skipTags?:string[]; + /*This is the class name used to mark elements whose contents should not be processed by tex2jax (other than to + * look for the processClass pattern below). Note that this is a regular expression, and so you need to be sure + * to quote any regexp special characters. The pattern is inserted into one that requires your pattern to match + * a complete word, so setting ignoreClass: "class2" would cause it to match an element with class="class1 class2 + * class3" but not class="myclass2". Note that you can assign several classes by separating them by the vertical + * line character (|). For instance, with ignoreClass: "class1|class2" any element assigned a class of either + * class1 or class2 will be skipped. + */ + ignoreClass?:string; + /*This is the class name used to mark elements whose contents should be processed by tex2jax. This is used to + * restart processing within tags that have been marked as ignored via the ignoreClass or to cause a tag that + * appears in the skipTags list to be processed rather than skipped. Note that this is a regular expression, and + * so you need to be sure to quote any regexp special characters. The pattern is inserted into one that requires + * your pattern to match a complete word, so setting processClass: "class2" would cause it to match an element + * with class="class1 class2 class3" but not class="myclass2". Note that you can assign several classes by + * separating them by the vertical line character (|). For instance, with processClass: "class1|class2" any + * element assigned a class of either class1 or class2 will have its contents processed.*/ + processClass?:string; + } + + export interface ILocalization { + /*The currently selected locale, e.g., "fr". This is set by the setLocale() method, and should not be modified + * by hand. + */ + locale:string; + /*The URL for the localization data files. This can be overridden for individual languages or domains + * (see below). The default is [MathJax]/localization. + */ + directory:string; + /*This is the main data structure that holds the translation strings. It consists of an entry for each language + * that MathJax knows about, e.g., there would be an entry with key fr whose value is the data for the French + * translation. Initially, these simply reference the files that define the translation data, which MathJax will + * load when needed. After the file is loaded, they will contain the translation data as well. This is described + * in more detail below. + */ + strings:any; + /*The function (described in detail above) that returns the translated string for a given id, substituting the + * given arguments as needed. + */ + _(id:number, message:string, ...args:any[]):void; + /*Sets the selected locale to the given one*/ + setLocale(locale:string):void; + /*Defines (or adds to) the translation data for the given locale and domain. The def is the definition to be + * merged with the current translation data (if it exists) or to be used as the complete definition (if not). + */ + addTranslation(locale:string, domain:string, def:any):void; + /*Sets the CSS for the given div to reflect the needs of the locale. In particular, it sets the font-family, + * if needed, and the direction (for right-to-left languages). + */ + setCSS(div:any):any; + /*Get the font-family needed to display text in the selected language. Returns null if no special font is + * required. + */ + fontFamily():string; + /*Get the direction needed to display text in the selected language. Returns null if no special font is + * required.*/ + fontDirection():string; + /*The method that returns the index into the list of plural texts for the value n. See the [CLDR rules] + * (http://unicode.org/cldr/charts/supplemental/language_plural_rules.html) for more information. This calls the + * locale’s plural() method, if there is one, otherwise it defaults to the English version. + */ + plural(value:any):number; + /*The method that returns the localized version of the number n. This calls the locale’s number() method, if + * there is one, otherwise it defaults to the English version. + */ + number(value:number):string; + /*This causes MathJax to load the data file for the given domain in the current language, and calls the callback + * when that is complete. If the domain is already loaded, the callback is called immediately. This lets you + * synchronize actions that require localization with the loading of the needed data so that you are sure that + * the needed translations are available. See the section on synchonization above for details. + */ + loadDomain(domain:string):ICallbackObject; + loadDomain(domain:string, callback:ICallbackObject):ICallbackObject; + /*This method runs the function fn with error trapping and if an asynchronous file load is performed (for loading + * localizaton data), reruns the function again after the file loads. This lets you synchronize actions that + * require localization with the loading of the needed data (see the section on synchronization above for + * details). Note that the function should be one that can be run multiple times, if needed. Also note that Try() + * can return before the fn has been completed, so you should consider fn to be running asynchronously (you can + * use callbacks to synchronize with other actions, if needed). + */ + Try(spec:any):void; + } + + export interface IInputJax { + /*The name of the jax.*/ + id:string; + /*The version number of the jax.*/ + version:string; + /*The directory where the jax files are stored (e.g., "[MathJax]/jax/input/TeX").*/ + directory:string; + /*The name of the ElementJax class that this input jax will produce (typically mml, as that is the only + * ElementJax at the moment). + */ + elementJax:string; + /*This is the method that the MathJax.Hub calls when it needs the input jax to process the given math
    "; + // Move the element + Sys.UI.DomElement.setLocation(elementRef, 100, elementLoc.y); + elementLoc = Sys.UI.DomElement.getLocation(elementRef); + result += "After move - Label1 location (x,y) = (" + + elementLoc.x + "," + elementLoc.y + ")
    "; + +} + +function Sys_UI_DomEvent_Tests() { + + var object: any; + + Sys.UI.DomEvent.addHandler(object, "eventName", () => { }); + Sys.UI.DomEvent.addHandler(object, "eventName", () => { }, true); + + Sys.UI.DomEvent.addHandlers(object, object, object, true); + Sys.UI.DomEvent.removeHandler(object, "eventName", () => { }); + Sys.UI.DomEvent.clearHandlers(object); + + var domEvent = new Sys.UI.DomEvent(object); + var altKey: boolean = domEvent.altKey; + var mouseButton: Sys.UI.MouseButton = domEvent.button; + var charCode: number = domEvent.charCode; + var clientX: number = domEvent.clientX; + var ctrlKey: boolean = domEvent.ctrlKey; + var screenX: number = domEvent.screenX; + var screenY: number = domEvent.screenY; + var target: any = domEvent.target; + var shiftKey: boolean = domEvent.shiftKey; + var type: string = domEvent.type; +} + +function Sys_UI_DomElement_Tests() { + + // Add CSS class + Sys.UI.DomElement.addCssClass($get("Button1"), "redBackgroundColor"); + + var elementRef: Sys.UI.DomElement = $get("Label1"); + var elementBounds = Sys.UI.DomElement.getBounds(elementRef); + var toggleCssClassMethod = () => {}; + var removeCssClassMethod = () => {}; + var containsClass = Sys.UI.DomElement.containsCssClass(elementRef, "class-name"); + + // Add handler using the getElementById method + $addHandler(Sys.UI.DomElement.getElementById("Button1"), "click", toggleCssClassMethod); + // Add handler using the shortcut to the getElementById method + $addHandler($get("Button2"), "click", removeCssClassMethod); + + Sys.UI.DomElement.toggleCssClass($get("id"), "redBackgroundColor"); + + + // Add handlers using the $get shortcut to the + // Sys.UI.DomElement.getElementById method + $addHandler($get("Button1"), "click", toggleVisible); + $addHandler($get("Button2"), "click", toggleVisibilityMode); + + // This method is called when Button2 is clicked. + function toggleVisible() { + var anElement = $get("Label1"); + if (Sys.UI.DomElement.getVisible(anElement)) { + Sys.UI.DomElement.setVisible(anElement, false); + } + else { + Sys.UI.DomElement.setVisible(anElement, true); + } + } + + // This method is called when Button1 is clicked. + function toggleVisibilityMode() { + + var anElement = $get("Label1"); + + var visMode = Sys.UI.DomElement.getVisibilityMode(anElement); + + var status = visMode; + + if (visMode === 0) { + Sys.UI.DomElement.setVisibilityMode(anElement, Sys.UI.VisibilityMode.collapse); + if (document.all) { + anElement.innerText = + "Label1 VisibilityMode: Sys.UI.VisibilityMode.collapse"; + } + else { + //Firefox + anElement.textContent = + "Label1 VisibilityMode: Sys.UI.VisibilityMode.collapse"; + } + } + else { + Sys.UI.DomElement.setVisibilityMode(anElement, Sys.UI.VisibilityMode.hide); + if (document.all) { + anElement.innerText = "Label1 VisibilityMode: Sys.UI.VisibilityMode.hide"; + } + else { + //Firefox + anElement.textContent = "Label1 VisibilityMode: Sys.UI.VisibilityMode.hide"; + } + } + } + + +} + +function Sys_Debug_Tests() { + + var condition = true; + + Sys.Debug.assert(condition); + Sys.Debug.assert(condition, "true"); + Sys.Debug.assert(condition, "true", true); + + var obj = {}; + Sys.Debug.traceDump(obj, "Name"); + Sys.Debug.trace("Trace text"); + Sys.Debug.fail("Fail message"); + + Sys.Debug.clearTrace(); +} + +function Sys_CultureInfo_Tests() { + + var currentCultureInfoObj = Sys.CultureInfo.CurrentCulture; + var dtfCCObject = currentCultureInfoObj.dateTimeFormat; + var invariantCultureInfoObj = Sys.CultureInfo.InvariantCulture; + var dtfICObject = invariantCultureInfoObj.dateTimeFormat; + + var newCulture = new Sys.CultureInfo("name", "numberFormat", "dateTimeFormat"); + + var format = newCulture.dateTimeFormat; + var name = newCulture.name; + var numberFormat = newCulture.numberFormat; +} + +function Sys_Res_Tests() { + + var actualValue = Sys.Res.actualValue; + var appLoadTimedout = Sys.Res.appLoadTimedout; + var argument = Sys.Res.argument; + var argumentNull = Sys.Res.argumentNull; + var argumentOutOfRange = Sys.Res.argumentOutOfRange; + var argumentType = Sys.Res.argumentType; + var argumentTypeWithTypes = Sys.Res.argumentTypeWithTypes; + var argumentUndefined = Sys.Res.argumentUndefined; + var assertFailed = Sys.Res.assertFailed; + var assetFailedCaller = Sys.Res.assetFailedCaller; + var badBaseUrl1 = Sys.Res.badBaseUrl1; + var badBaseUrl2 = Sys.Res.badBaseUrl2; + var badBaseUrl3 = Sys.Res.badBaseUrl3; + var breakIntoDebugger = Sys.Res.breakIntoDebugger; + var cannotAbortBeforeStart = Sys.Res.cannotAbortBeforeStart; + var cannotCallBeforeResponse = Sys.Res.cannotCallBeforeResponse; + var cannotCallOnceStarted = Sys.Res.cannotCallOnceStarted; + var cannotCallOutsideHandler = Sys.Res.cannotCallOutsideHandler; + var cannotDeserializeEmptyString = Sys.Res.cannotDeserializeEmptyString; + var cannotSerializeNonFiniteNumbers = Sys.Res.cannotSerializeNonFiniteNumbers; + var controlCantSetId = Sys.Res.controlCantSetId; + var enumInvalidValue = Sys.Res.enumInvalidValue; + var eventHandlerInvalid = Sys.Res.eventHandlerInvalid; + var format = Sys.Res.format; + var formatBadDate = Sys.Res.formatBadDate; + var formatBadFormatSpecifier = Sys.Res.formatBadFormatSpecifier; + var formatInvalidString = Sys.Res.formatInvalidString; + var invalidExecutorType = Sys.Res.invalidExecutorType; + var invalidHttpVerb = Sys.Res.invalidHttpVerb; + var invalidOperation = Sys.Res.invalidOperation; + var invalidTimeout = Sys.Res.invalidTimeout; + var invokeCalledTwice = Sys.Res.invokeCalledTwice; + var notImplemented = Sys.Res.notImplemented; + var nullWebRequest = Sys.Res.nullWebRequest; +} + +function Sys_StringBuilder_Tests() { + + // Example taken from http://msdn.microsoft.com/en-us/library/bb310852(v=vs.100).aspx + function buildAString(title: string) { + var headTagStart = ""; + var headTagEnd = ""; + var titleTagStart = ""; + var titleTagEnd = ""; + + var sb = new Sys.StringBuilder(this._headTagStart); + sb.append(titleTagEnd); + sb.append(title); + sb.append(titleTagEnd); + sb.append(headTagEnd); + // Displays: "The result: A Title" + alert("The result" + sb.toString()); + } + + var title = "A Title"; + buildAString(title); + + +} + +function Sys_Services_Profile_Service_Group_Tests() { + + var Street = Sys.Services.ProfileService.properties.Address.Street; + var City = Sys.Services.ProfileService.properties.Address.City; + + Sys.Services.ProfileService.properties.Address = new Sys.Services.ProfileGroup(); + Sys.Services.ProfileService.properties.Address.Street = "street name"; + Sys.Services.ProfileService.properties.Address.City = "city name"; + Sys.Services.ProfileService.properties.Address.State = "state name"; + + var SaveCompletedCallback = () => { }; + var ProfileFailedCallback = () => { }; + var LoadCompletedCallback = () => { }; + + Sys.Services.ProfileService.save(null, SaveCompletedCallback, ProfileFailedCallback, null); + Sys.Services.ProfileService.load(null, LoadCompletedCallback, ProfileFailedCallback, null); + + Sys.Services.ProfileService.set_defaultFailedCallback("Function"); + var defaultFailedCallback = Sys.Services.ProfileService.get_defaultFailedCallback(); + + Sys.Services.ProfileService.set_defaultLoadCompletedCallback("Function"); + var defaultLoadCompletedCallback = Sys.Services.ProfileService.get_defaultLoadCompletedCallback(); + + Sys.Services.ProfileService.set_defaultSaveCompletedCallback("Function"); + var defaultSaveCompletedCallback = Sys.Services.ProfileService.get_defaultSaveCompletedCallback(); + + Sys.Services.ProfileService.set_path("path"); + Sys.Services.ProfileService.get_path(); + + var timeout = Sys.Services.ProfileService.get_timeout(); + +} + +function Sys_Net_NetworkRequestEventArgs_Tests() { + + var value = new Sys.Net.WebRequest(); + var netWorkEventArgs = new Sys.Net.NetWorkRequestEventArgs(value); + var webRequest = netWorkEventArgs.get_webRequest(); +} + +function Sys_Net_WebRequestManager_Tests() { + + var handler = (sender: any, args: any) => { } + + Sys.Net.WebRequestManager.add_completedRequest(handler); + Sys.Net.WebRequestManager.add_invokingRequest(handler); + Sys.Net.WebRequestManager.executeRequest(new Sys.Net.WebRequest()); + Sys.Net.WebRequestManager.remove_completedRequest(handler); + Sys.Net.WebRequestManager.set_defaultTimeout(100); + var customDefaultTimeout = Sys.Net.WebRequestManager.get_defaultTimeout(); + +} + +function Sys_WebForms_PageRequestManager_Tests() { + + var pageRequestManager: Sys.WebForms.PageRequestManager = Sys.WebForms.PageRequestManager.getInstance(); + + var beginRequestHandler = (sender: any, args: Sys.WebForms.BeginRequestEventArgs) => { + var postBackElement: HTMLElement = args.get_postBackElement(); + var webRequest: Sys.Net.WebRequest = args.get_request(); + var updatePanelsToUpdate: string[] = args.get_updatePanelsToUpdate(); + var empty: Sys.EventArgs = args.Empty; + } + var endRequestHandler = (sender: any, args: Sys.WebForms.EndRequestEventArgs) => { + var dataItems: any = args.get_dataItems(); + var error: Error = args.get_error(); + var errorHandled: boolean = args.get_errorHandled(); + var webRequestExecutor: Sys.Net.WebRequestExecutor = args.get_response(); + args.set_errorHandled(true); + + } + var initializeRequestHandler = (sender: any, args: Sys.WebForms.InitializeRequestEventArgs) => { + var postBackElement: HTMLElement = args.get_postBackElement(); + var webRequestExecutor: Sys.Net.WebRequestExecutor = args.get_request(); + var updatePanelsToUpdate: string[] = args.get_updatePanelsToUpdate(); + var empty: Sys.EventArgs = args.Empty; + } + var pageLoadedRequestHandler = (sender: any, args: Sys.WebForms.PageLoadedEventArgs) => { + var dataItems: any = args.get_dataItems(); + var panelsCreated: HTMLDivElement[] = args.get_panelsCreated(); + var panelsUpdated: HTMLDivElement[] = args.get_panelsUpdated(); + var empty: Sys.EventArgs = args.Empty; + } + var pageLoadingRequestHandler = (sender: any, args: Sys.WebForms.PageLoadingEventArgs) => { + var dataItems: any = args.get_dataItems(); + var panelsDeleted: HTMLDivElement[] = args.get_panelsDeleting(); + var panelsUpdating = args.get_panelsUpdating(); + var empty: Sys.EventArgs = args.Empty; + } + + + var isInAsyncPostBack: boolean = pageRequestManager.get_isInAsyncPostBack(); + + pageRequestManager.add_beginRequest(beginRequestHandler); + pageRequestManager.add_endRequest(endRequestHandler); + pageRequestManager.add_initializeRequest(initializeRequestHandler); + pageRequestManager.add_pageLoading(pageLoadingRequestHandler); + pageRequestManager.add_pageLoaded(pageLoadedRequestHandler); + pageRequestManager.remove_beginRequest(beginRequestHandler); + pageRequestManager.remove_pageLoaded(pageLoadedRequestHandler); + pageRequestManager.remove_pageLoading(pageLoadingRequestHandler); + pageRequestManager.beginAsyncPostBack(); + pageRequestManager.abortPostBack(); + pageRequestManager.dispose(); +} + +function Sys_WebForms_EndRequestEventArgs_Tests() { + + var pageRequestManager: Sys.WebForms.PageRequestManager = Sys.WebForms.PageRequestManager.getInstance(); + + var handler = (sender: any, args: Sys.WebForms.EndRequestEventArgs) => { + + var error: Error = args.get_error(); + var message: string = error.message; + var name: string = error.name; + var response: Sys.Net.WebRequestExecutor = args.get_response(); + var dataItems: any = args.get_dataItems(); + var eventArgs: Sys.EventArgs = args.Empty; + + args.set_errorHandled(true); + var errorHandled: boolean = args.get_errorHandled(); + } + + pageRequestManager.add_endRequest(handler); +} + +function AspNetTypes_Tests() { + + Type.registerNamespace("Samples"); + + var Samples: any; + + Samples.A = function () { }; + var a = Samples.A; + a.registerClass('Samples.A'); + + + Samples.B = function () { }; + var b = Samples.B; + b.registerClass('Samples.B'); + + Samples.C = function () { + var c = Samples.C; + c.initializeBase(this); + }; + + Samples.C.registerClass('Samples.C', Samples.A, Samples.B); + + var isDerived: boolean; + isDerived = Samples.B.inheritsFrom(Samples.A); + // Output: "false". + alert(isDerived); + + isDerived = Samples.C.inheritsFrom(Samples.A); + // Output: "true". + alert(isDerived); + + var implementsInterface: boolean; + implementsInterface = Samples.C.implementsInterface(Samples.B); + // Output: "true". + alert(implementsInterface); +} + +/** Sample code from http://msdn.microsoft.com/en-us/library/bb386520(v=vs.100).aspx */ +function CreatingCustomNonVisualClientComponentsTests() { + + var Demo: any; + Type.registerNamespace("Demo"); + + Demo.Timer = function () { + Demo.Timer.initializeBase(this); + + this._interval = 1000; + this._enabled = false; + this._timer = null; + } + + Demo.Timer.prototype = { + // OK to declare value types in the prototype + + get_interval: function () { + /// Interval in milliseconds + return this._interval; + }, + set_interval: function (value: any) { + if (this._interval !== value) { + this._interval = value; + this.raisePropertyChanged('interval'); + + if (!this.get_isUpdating() && (this._timer !== null)) { + this._restartTimer(); + } + } + }, + + get_enabled: function () { + /// True if timer is enabled, false if disabled. + return this._enabled; + }, + set_enabled: function (value: any) { + if (value !== this.get_enabled()) { + this._enabled = value; + this.raisePropertyChanged('enabled'); + if (!this.get_isUpdating()) { + if (value) { + this._startTimer(); + } + else { + this._stopTimer(); + } + } + } + }, + + // events + add_tick: function (handler: Function) { + /// Adds a event handler for the tick event. + /// The handler to add to the event. + this.get_events().addHandler("tick", handler); + }, + remove_tick: function (handler: Function) { + /// Removes a event handler for the tick event. + /// The handler to remove from the event. + this.get_events().removeHandler("tick", handler); + }, + + dispose: function () { + // call set_enabled so the property changed event fires, for potentially attached listeners. + this.set_enabled(false); + // make sure it stopped so we aren't called after disposal + this._stopTimer(); + // be sure to call base.dispose() + Demo.Timer.callBaseMethod(this, 'dispose'); + }, + + updated: function () { + Demo.Timer.callBaseMethod(this, 'updated'); + // called after batch updates, this.beginUpdate(), this.endUpdate(). + if (this._enabled) { + this._restartTimer(); + } + }, + + _timerCallback: function () { + var handler = this.get_events().getHandler("tick"); + if (handler) { + handler(this, Sys.EventArgs.Empty); + } + }, + + _restartTimer: function () { + this._stopTimer(); + this._startTimer(); + }, + + _startTimer: function () { + // save timer cookie for removal later + this._timer = window.setInterval((Function).createDelegate(this, this._timerCallback), this._interval); + }, + + _stopTimer: function () { + if (this._timer) { + window.clearInterval(this._timer); + this._timer = null; + } + } + } + + Demo.Timer.registerClass('Demo.Timer', Sys.Component); + + // Since this script is not loaded by System.Web.Handlers.ScriptResourceHandler + // invoke Sys.Application.notifyScriptLoaded to notify ScriptManager + // that this is the end of the script. + if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded(); + +} \ No newline at end of file diff --git a/microsoft-ajax/microsoft.ajax.d.ts b/microsoft-ajax/microsoft.ajax.d.ts new file mode 100644 index 0000000000..513488bd19 --- /dev/null +++ b/microsoft-ajax/microsoft.ajax.d.ts @@ -0,0 +1,4012 @@ +// Type definitions for Microsoft ASP.NET Ajax client side library +// Project: http://msdn.microsoft.com/en-us/library/ee341002(v=vs.100).aspx +// Definitions by: Patrick Magee +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +//#region Global Namespace + +/** +* Global Namespace +* This section includes members or types that extend the ECMAScript (JavaScript) Global object and other core objects. +* @see {@link http://msdn.microsoft.com/en-us/library/bb310818(v=vs.100).aspx} +*/ + +//#region JavaScript Base Type Extensions + +/** +* Provides extended reflection-like functionality to the base ECMAScript (JavaScript) Object object. +* Object Type Extensions +* @see {@link http://msdn.microsoft.com/en-us/library/bb397554(v=vs.100).aspx} +*/ +interface Object { + /** + * Formats a number by using the invariant culture. + */ + getType(instance: any): Type; + /** + * Returns a string that identifies the run-time type name of an object. + */ + getTypeName(instance: any): string; +} + +/** +* Provides extensions to the base ECMAScript (JavaScript) Array functionality by adding static methods. +* Array Type Extensions +* @see {@link http://msdn.microsoft.com/en-us/library/bb383786(v=vs.100).aspx} +*/ +interface Array { + + //#region lib.d.ts + + new (arrayLength?: number): any[]; + new (arrayLength: number): T[]; + new (...items: T[]): T[]; + (arrayLength?: number): any[]; + (arrayLength: number): T[]; + (...items: T[]): T[]; + isArray(arg: any): boolean; + prototype: Array; + + ///** + // * Returns a string representation of an array. + // */ + //toString(): string; + //toLocaleString(): string; + ///** + // * Combines two or more arrays. + // * @param items Additional items to add to the end of array1. + // */ + //concat(...items: U[]): T[]; + ///** + // * Combines two or more arrays. + // * @param items Additional items to add to the end of array1. + // */ + //concat(...items: T[]): T[]; + ///** + // * Adds all the elements of an array separated by the specified separator string. + // * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + // */ + //join(separator?: string): string; + ///** + // * Removes the last element from an array and returns it. + // */ + //pop(): T; + ///** + // * Appends new elements to an array, and returns the new length of the array. + // * @param items New elements of the Array. + // */ + //push(...items: T[]): number; + ///** + // * Reverses the elements in an Array. + // */ + //reverse(): T[]; + ///** + // * Removes the first element from an array and returns it. + // */ + //shift(): T; + ///** + // * Returns a section of an array. + // * @param start The beginning of the specified portion of the array. + // * @param end The end of the specified portion of the array. + // */ + //slice(start?: number, end?: number): T[]; + + ///** + // * Sorts an array. + // * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. + // */ + //sort(compareFn?: (a: T, b: T) => number): T[]; + + ///** + // * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + // * @param start The zero-based location in the array from which to start removing elements. + // */ + //splice(start: number): T[]; + + ///** + // * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + // * @param start The zero-based location in the array from which to start removing elements. + // * @param deleteCount The number of elements to remove. + // * @param items Elements to insert into the array in place of the deleted elements. + // */ + //splice(start: number, deleteCount: number, ...items: T[]): T[]; + + ///** + // * Inserts new elements at the start of an array. + // * @param items Elements to insert at the start of the Array. + // */ + //unshift(...items: T[]): number; + + ///** + // * Returns the index of the first occurrence of a value in an array. + // * @param searchElement The value to locate in the array. + // * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + // */ + //indexOf(searchElement: T, fromIndex?: number): number; + + ///** + // * Returns the index of the last occurrence of a specified value in an array. + // * @param searchElement The value to locate in the array. + // * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + // */ + //lastIndexOf(searchElement: T, fromIndex?: number): number; + + ///** + // * Determines whether all the members of an array satisfy the specified test. + // * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + // */ + //every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + ///** + // * Determines whether the specified callback function returns true for any element of an array. + // * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + // */ + //some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + ///** + // * Performs the specified action for each element in an array. + // * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + // */ + //forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + ///** + // * Calls a defined callback function on each element of an array, and returns an array that contains the results. + // * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + // */ + //map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + + ///** + // * Returns the elements of an array that meet the condition specified in a callback function. + // * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + // */ + //filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; + + ///** + // * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + // * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + // * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + // */ + //reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + ///** + // * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + // * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + // * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + // */ + //reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + ///** + // * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + // * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + // * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + // */ + //reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + ///** + // * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + // * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + // * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + // */ + //reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + ///** + // * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. + // */ + //length: number; + + //[n: number]: T; + + //#endregion + + //#region Extensions + + /** + * Adds an element to the end of an Array object. This function is static and is invoked without creating an instance of the object. + * @param array + * The array to add the item to. + * @param item + * + */ + add(array: any[], element: any): void; + /** + * Copies all the elements of the specified array to the end of an Array object. + */ + addRange(array: any, items: any): void; + /** + * Removes all elements from an Array object. + */ + clear(): void; + /** + * Creates a shallow copy of an Array object. + */ + clone(): any[]; + /** + * Determines whether an element is in an Array object. + */ + contains(element: any): boolean; + /** + * Removes the first element from an Array object. + */ + dequeue(): any; + /** + * Adds an element to the end of an Array object. Use the add function instead of the Array.enqueue function. + */ + enqueue(element: any): void; + /** + * Performs a specified action on each element of an Array object. + */ + forEach(array: any[], method: Function, instance: any[]): void; + /** + * Searches for the specified element of an Array object and returns its index. + */ + indexOf(array: any[], item: any, startIndex?: number): number; + /** + * Inserts a value at the specified location in an Array object. + */ + insert(array: any[], index: number, item: any); + /** + * Creates an Array object from a string representation. + */ + parse(value: string): any[]; + /** + * Removes the first occurrence of an element in an Array object. + */ + remove(array: any[], item: any): boolean; + /** + * Removes an element at the specified location in an Array object. + */ + removeAt(array: any[], index: number): void; + + //#endregion +} + +/** +* Extends the base ECMAScript (JavaScript) Number functionality with static and instance methods. +* Number Type Extensions +* @see {@link http://msdn.microsoft.com/en-us/library/bb310835(v=vs.100).aspx} +*/ +interface Number { + /** + * Formats a number by using the invariant culture. + */ + format(format: string): string; + /** + * Formats a number by using the current culture. + */ + localeFormat(format: string): string; + /** + * Returns a numeric value from a string representation of a number. This function is static and can be called without creating an instance of the object. + */ + parseInvariant(format: string): number; + /** + * Creates a numeric value from a locale-specific string. + */ + parseLocale(format: string): number; +} + +/** +* Provides extensions to the base ECMAScript (JavaScript) Date object. +* Date Type Extensions +* @see {@link http://msdn.microsoft.com/en-us/library/bb310850(v=vs.100).aspx} +*/ +interface Date { + + /** + * Formats a date by using the invariant (culture-independent) culture. + */ + format(value: string): string; + /** + * Formats a date by using the current culture. This function is static and can be invoked without creating an instance of the object. + */ + localeFormat(value: string): string; + /** + * Creates a date from a locale-specific string by using the current culture. This function is static and can be invoked without creating an instance of the object. + * @exception (Debug) formats contains an invalid format. + * @param value + * A locale-specific string that represents a date. + * @param formats + * (Optional) An array of custom formats. + */ + parseLocale(value: string): string; + parseLocale(value: string, formats?: string[]): string; + parseLocale(value: string, ...formats: string[]): string; + /** + * Creates a date from a string by using the invariant culture. This function is static and can be invoked without creating an instance of the object. + * @return If value is a valid string representation of a date in the invariant format, an object of type Date; otherwise, null. + * @param value + * A locale-specific string that represents a date. + * @param formats + * (Optional) An array of custom formats. + */ + parseInvariant(value: string): string; + parseInvariant(value: string, formats?: string[]): string; + parseInvariant(value: string, ...formats: string[]): string; +} + +declare module MicrosoftAjaxBaseTypeExtensions { + + /** + * Provides static functions that extend the built-in ECMAScript (JavaScript) Function type by including exception + * details and support for application-compilation modes (debug or release). + * @see {@link http://msdn.microsoft.com/en-us/library/dd409270(v=vs.100).aspx} + */ + interface Function { + + //#region lib.d.ts + + /** + * Creates a new function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): Function; + (...args: string[]): Function; + prototype: Function; + + //#endregion + + //#region Extensions + + /** + * Creates a delegate function that retains the context first used during an objects creation. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393582(v=vs.100).aspx } + */ + createCallback(method: Function, ...context: any[]): Function; + /** + * Creates a callback function that retains the parameter initially used during an object's creation. + * @see {@link http://msdn.microsoft.com/en-us/library/dd409287(v=vs.100).aspx } + */ + createDelegate(instance: any, method: Function): Function; + + /** + * A function that does nothing. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393667(v=vs.100).aspx } + */ + emptyMethod(): Function; + + /** + * Validates the parameters to a method are as expected. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393712(v=vs.100).aspx } + */ + validateParameters(parameters: any, expectedParameters: Object[], validateParameterCount?: boolean): any; + + //#endregion + } + + /** + * Provides static functions that extend the built-in ECMAScript (JavaScript) Error type by including exception details and support for application-compilation modes (debug or release). + * Error Type Extensions + * @see {@link http://msdn.microsoft.com/en-us/library/bb310947(v=vs.100).aspx} + */ + interface Error { + + //#region lib.d.ts + + name: string; + message: string; + + new (message?: string): Error; + (message?: string): Error; + prototype: Error; + + //#endregion + + //#region Extensions + + /** + * Creates an Error object that represents the Sys.ParameterCountException exception. + */ + parameterCount(message?: string): Error; + /** + * Creates an Error object that represents the Sys.NotImplementedException exception. + */ + notImplemented(message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentException exception. + */ + argument(paramName?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentNullException exception. + */ + argumentNull(paramName?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentOutOfRangeException exception. + */ + argumentOutOfRange(paramName?: string, actualValue?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentTypeException exception. + */ + argumentType(paramName?: string, actualType?: any, expectedType?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentUndefinedException exception. + */ + argumentUndefined(paramName?: string, message?: string): Error; + /** + * Creates an Error object that can contain additional error information. + */ + create(message?: string, errorInfo?: Object): Error; + /** + * Creates an Error object that represents the Sys.FormatException exception. + */ + format(message?: string): Error; + /** + * Creates an Error object that represents the Sys.InvalidOperationException exception. + */ + invalidOperation(message?: string): Error; + /** + * Updates the fileName and lineNumber properties of an Error instance to indicate where the error was thrown instead of where the error was created. Use this function if you are creating custom error types. + */ + popStackFrame(): void; + + //#endregion + } + + /** + * Provides extensions to the base ECMAScript (JavaScript) String object by including static and instance methods. + * String Type Extensions + * @see {@link http://msdn.microsoft.com/en-us/library/bb397472(v=vs.100).aspx} + */ + interface String { + + //#region lib.d.ts + + new (value?: any): String; + (value?: any): string; + prototype: String; + fromCharCode(...codes: number[]): 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 number indicating the beginning of the substring. + * @param end Zero-based index number 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; + + /** 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; + + [index: number]: string; + + //#endregion + + //#region Extensions + + /** + * Formats a number by using the invariant culture. + * @returns true if the end of the String object matches suffix; otherwise, false. + */ + endsWith(suffix: string): boolean; + /** + * Replaces each format item in a String object with the text equivalent of a corresponding object's value. + * @returns A copy of the string with the formatting applied. + */ + format(format: string, ...args: any[]): string; + /** + * Replaces the format items in a String object with the text equivalent of a corresponding object's value. The current culture is used to format dates and numbers. + * @returns A copy of the string with the formatting applied. + */ + localeFormat(format: string, ...args: any[]): string; + /** + * Removes leading and trailing white-space characters from a String object. + * @returns A copy of the string with all white-space characters removed from the start and end of the string. + */ + trim(): string; + /** + * Removes trailing white-space characters from a String object. + * @returns A copy of the string with all white-space characters removed from the end of the string. + */ + trimEnd(): string; + /** + * Removes leading white-space characters from a String object. + * @returns A copy of the string with all white-space characters removed from the start of the string. + */ + trimStart(): string; + + //#endregion + } + + /** + * Provides extensions to the base ECMAScript (JavaScript) Boolean object. + * Boolean Type Extensions + * @see {@link http://msdn.microsoft.com/en-us/library/bb397557(v=vs.100).aspx} + */ + interface Boolean { + + //#region lib.d.ts + + new (value?: any): Boolean; + (value?: any): boolean; + prototype: Boolean; + + //#endregion + + //#region Extensions + + /** + * Converts a string representation of a logical value to its Boolean object equivalent. + */ + parse(value: string): Boolean; + + //#endregion + } +} + +//#endregion + +//#region ASP.NET Types + +/** +* Provides a typing and type-reflection system for ECMAScript (JavaScript) object-oriented programming functionality. +* Type Class +* @see {@link http://msdn.microsoft.com/en-us/library/bb397568(v=vs.100).aspx} +*/ +declare class Type { + /** + * Invokes a base method with specified arguments. + * @returns A value of the class that the base method returns. If the base method does not return a value, no value is returned. + */ + callBaseMethod(instance: any, name: string, baseArguments?: any[]): any; + /** + * Creates a callback method, given the function to callback and the parameter to pass to it. + * @return + * The callback function. + * + * @param method + * The function for which the callback method will be created. + * @param context + * The parameter to pass to the function. This parameter can be null, but it cannot be omitted. + */ + static createCallback(method: Function, context: Object): Function; + /** + * Creates a delegate function that keeps the context from its creation. The context defines the object instance to which the this keyword points. + * @param instance + * The object instance that will be the context for the function. This parameter can be null. + * @param method + * The function from which the delegate is created. + * @return The delegate function. + */ + static createDelegate(instance: Object, method: Function): Function; + /** + * Returns the base implementation of a method from the base class of the specified instance. + * @param instance + * The instance for which the base method is requested. + * @param name + * The name of the method to retrieve as a reference. + */ + getBaseMethod(instance: Object, name: string): any; + /** + * Returns the base class of the instance. + * Use the getBaseType method to retrieve the base class of the instance. + */ + getBaseType(): Type; + /** + * Returns an Array object that contains the list of interfaces that the type implements. + * Use the getInterfaces function to return a list of objects that define the interfaces on a type object. + * This enables you to enumerate the array to determine the object's interfaces. + * + * @return An Array object that contains the list of interfaces that the type implements. + */ + getInterfaces(): any[]; + /** + * Returns the name of the type of the instance. + * @return A string representing the fully qualified name of the type of the instance. + * @example Object.getType(c[i]).getName() + */ + getName(): string; + /** + * Returns an Array object containing references to all the root namespaces of the client application. This method is static and is invoked without creating an instance of the object. + * Use the getRootNamespaces function to return an array containing references to all the root namespaces of the client application. + * @return An object containing references to all the root namespaces of the client application. + */ + static getRootNamespaces(): any; + /** + * Determines whether a class implements a specified interface type. + * @param interfaceType + * The interface to test. + * @return true if the class implements interfaceType; otherwise, false. + */ + implementsInterface(interfaceType: Type): boolean; + /** + * Determines whether an instance inherits from a specified class. + * @param parentType + * The fully qualified name of the class to test as a base class for the current instance. + * @return true if the instance inherits from parentType; otherwise, false. + */ + inheritsFrom(parentType: string): boolean; + /** + * Initializes the base class and its members in the context of a given instance, which provides the model for inheritance and for initializing base members. + * @param instance + * The instance to initialize the base class for. Usually this. + * @param baseArguments + * (Optional) The arguments for the base constructor. Can be null. + */ + initializeBase(instance: any, baseArguments?: any[]): any; + /** + * Returns a value that indicates whether the specified type is a class. This method is static and can be invoked without creating an instance of the object. + * @param type + * The type to test. + * @return true if the specified type is a class; otherwise, false. + */ + static isClass(type: any): boolean; + /** + * Indicates whether the specified type is an enumeration. + * @param type + * The type to test. + * @return true if the type is an enumeration; otherwise, false. + */ + static isEnum(type: any): boolean; + /** + * Get a value that indicates whether the specified type is an integer of flags. + * @param + * The type to test. + * @return true if the type is an integer of flags; otherwise, false. + */ + static isFlags(type: any): boolean; + /** + * Determines whether an instance implements an interface. + * @param typeInstanceVar + * The instance on which the interface is tested. + * @return + */ + isImplementedBy(typeInstanceVar: any): boolean; + /** + * Returns a value that indicates whether an object is an instance of a specified class or of one of its derived classes. + * @param instance + * The object to test. + * @return true if instance is an instance of the class; false if instance does not implement the interface, or if it is undefined or null. + */ + isInstanceOfType(instance: any): boolean; + /** + * Returns a value that indicates whether the specified type is an interface. This is a static member that is invoked directly without creating an instance of the class. + * @param type + * The type to test. + * @return true if the specified type is an interface; otherwise, false. + */ + static isInterface(type: any): boolean; + /** + * Returns a value that indicates whether the specified object is a namespace. This is a static member that is invoked directly without creating an instance of the class. + * @param object + * The object to test. + * @return true if the specified object is a namespace; otherwise, false. + */ + static isNamespace(object: any): boolean; + /** + * Returns an instance of the type specified by a type name. This is a static member that is invoked directly without creating an instance of its class. + * @param typeName + * A string that represents a fully qualified class name. Can be null. + * @param ns + * (Optional) The namespace that contains the class. + * @return The class represented by typeName, or null if a class that matches typeName does not occur in the namespace. + */ + static parse(typeName: string, ns?: string): any; + /** + * Registers a class as defined by a constructor with an optional base type and interface type. + * @param typeName + * A string that represents the fully qualified name of the type. + * @param baseType + * (Optional) The base type. + * @param interfaceTypes + * (Optional) An unbounded array of interface type definitions that the type implements. + * @return The registered type. + */ + registerClass(typeName: string, baseType?: any, interfaceTypes?: any[]): any; + /** + * Registers an enumeration. + * @param name + * The fully-qualified name of the enumeration. + * @param flags + * (Optional) true if the enumeration is a collection of flags; otherwise, false. + */ + registerEnum(name: string, flags?: boolean): void; + /** + * Registers an interface defined by a constructor. + * @param typeName + * A string that represents the fully qualified name of the class to be registered as an interface. + * @return The registered interface. + */ + registerInterface(typeName: string): any; + /** + * Creates a namespace. This member is static and can be invoked without creating an instance of the class. + * @param namespacePath + * A string that represents the fully qualified namespace to register. + */ + static registerNamespace(namespacePath: string): void; + /** + * Copies members from the base class to the prototype associated with the derived class, and continues this process up the inheritance chain. This enables you to reflect on the inherited members of a derived type. + * Use the resolveInheritance method to reflect on the inherited members of a derived type. + * You invoke this method from the type that you want to reflect on. + * The resolveInheritance method copies members from the base class to the prototype associated with the derived class, and continues this process up the inheritance chain. + * If the derived type overrides a base type member, the base type member is not copied to the derived type's prototype. + * After invoking a derived type's resolveInheritance method, you can examine the members of the derived type to discover all members, which includes inherited members. + */ + resolveInheritance(): void; +} + +//#endregion + +//#region Shortcuts to commonly used APIs + +/** +* Creates and initializes a component of the specified type. This method is static and can be called without creating an instance of the class. +* @see {@link http://msdn.microsoft.com/en-us/library/bb397487(v=vs.100).aspx} +* +* @param type +* The type of the component to create. +* @param properties +* (Optional) A JSON object that describes the properties and their values. +* @param events +* (Optional) A JSON object that describes the events and their handlers. +* @param references +* (Optional) A JSON object that describes the properties that are references to other components. +* @param element +* (Optional) The DOM element that the component should be attached to. +* @returns A new instance of a component that uses the specified parameters. +*/ +declare function $create(type: Type, properties?: any, events?: any, references?: any, element?: HTMLElement): Sys.Component; + +/** +* Returns the specified Component object. This member is static and can be invoked without creating an instance of the class. +* @see {@link http://msdn.microsoft.com/en-us/library/bb397441(v=vs.100).aspx} +* @param id A string that contains the ID of the component to find. +* @param parent (Optional) The component or element that contains the component to find. +* @return A Component object that contains the component requested by ID, if found; otherwise, null. +*/ +declare function $find(id: string, parent?: Sys.Component): Sys.Component; + +/** +* Returns the specified Component object. This member is static and can be invoked without creating an instance of the class. +* @see {@link http://msdn.microsoft.com/en-us/library/bb397441(v=vs.100).aspx} +* @param id A string that contains the ID of the component to find. +* @param parent (Optional) The component or element that contains the component to find. +* @return A Component object that contains the component requested by ID, if found; otherwise, null. +*/ +declare function $find(id: string, parent?: HTMLElement): Sys.Component; + +/* +* Provides a shortcut to the addHandler method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. +* @see {@link http://msdn.microsoft.com/en-us/library/bb311019(v=vs.100).aspx} +* @param element The DOM element that exposes the event. +* @param eventName The name of the event. +* @param handler The event handler to add. +* @param autoRemove (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. +*/ +declare function $addHandler(element: Sys.UI.DomElement, eventName: string, handler: Function, autoRemove?: boolean): void; + +/** +* Provides a shortcut to the addHandlers method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. +* @see {@link http://msdn.microsoft.com/en-us/library/bb384012(v=vs.100).aspx} +* @param element The DOM element that exposes the event. +* @param events A dictionary of events and their handlers. +* @param handlerOwner (Optional) The object instance that is the context for the delegates that should be created from the handlers. +* @param autoRemove (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. +*/ +declare function $addHandlers(element: Sys.UI.DomElement, events: any, handlerOwner?: any, autoRemove?: boolean): void; + +/** +* Provides a shortcut to the clearHandlers method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. +* For details about the method that this shortcut represents, see Sys.UI.DomEvent clearHandlers Method. +* @see {@link http://msdn.microsoft.com/en-us/library/bb310959(v=vs.100).aspx} +* @param The DOM element that exposes the events. +*/ +declare function $clearHandlers(element: Sys.UI.DomElement): void; + +/** +* Provides a shortcut to the getElementById method of the Sys.UI.DomElement class. This member is static and can be invoked without creating an instance of the class. +* @see {@link http://msdn.microsoft.com/en-us/library/bb397717(v=vs.100).aspx} +* @param id +* The ID of the DOM element to find. +* @param element +* The parent element to search. The default is the document element. +* @return +* The Sys.UI.DomElement +*/ +declare function $get(id: string): any; // Examples use HTMLElement and DomElement +declare function $get(id: string, element?: HTMLElement): HTMLElement; +declare function $get(id: string, element?: Sys.UI.DomElement): Sys.UI.DomElement; + +/** +* Provides a shortcut to the removeHandler method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. +* @see {@link http://msdn.microsoft.com/en-us/library/bb397510(v=vs.100).aspx} +* @param element The DOM element that exposes the event. +* @param eventName The name of the DOM event. +* @param handler The event handler to remove. +*/ +declare function $removeHandler(element: any, eventName: string, handler: Function): void; +declare function $removeHandler(element: HTMLElement, eventName: string, handler: Function): void; +declare function $removeHandler(element: Sys.UI.DomElement, eventName: string, handler: Function): void; + +//#endregion + +//#endregion + +//#region Sys Namespace + +/** +* Represents the root namespace for the Microsoft Ajax Library, which contains all fundamental classes and base classes. +* @see {@link http://msdn.microsoft.com/en-us/library/bb397702(v=vs.100).aspx} +*/ +declare module Sys { + + //#region Classes + + /** + * Provides a run-time object that exposes client events and manages client components that are registered with the application. + * The members of this object are available globally after the client application has been initialized. + * The members can be invoked without creating an instance of the class. + * @see {@link http://msdn.microsoft.com/en-us/library/bb384161(v=vs.100).aspx} + */ + interface Application { + + //#region Constructors + + constructor(): void; + + //#endregion + + //#region Events + + /** + * Raised after all scripts have been loaded but before objects are created. + */ + add_init(handler: Function): void; + /** + * Raised after all scripts have been loaded but before objects are created. + */ + remove_init(handler: Function): void; + /** + * Raised after all scripts have been loaded and after the objects in the application have been created and initialized. + */ + add_load(handler: Function): void; + /** + * Raised after all scripts have been loaded and after the objects in the application have been created and initialized. + */ + remove_load(handler: Function): void; + /** + * Occurs when the user clicks the browser's Back or Forward button. + */ + add_navigate(handler: Function): void; + /** + * Occurs when the user clicks the browser's Back or Forward button. + */ + remove_navigate(handler: Function): void; + + /** + * Raised before all objects in the client application are disposed, typically when the DOM window.unload event is raised. + */ + add_unload(handler: Function): void; + + /** + * Raised before all objects in the client application are disposed, typically when the DOM window.unload event is raised. + */ + remove_unload(handler: Function): void; + + //#endregion + + //#region Methods + + /** + * Registers a component with the application and initializes it if the component is not already initialized. + */ + addComponent(component: any): void; + /** + * Instructs the application to start creating components. + */ + beginCreateComponents(): void; + /** + * Creates a history point and adds it to the browser's history stack. + */ + addHistoryPoint(state: Object, title?: string): void; + /** + * Called by the Sys.Application.beginUpdate Method to indicate that the process of setting component properties of the application has begun. + */ + beginUpdate(): void; + /** + * Releases resources and dependencies held by the client application. + */ + dispose(): void; + /** + * Releases resources and dependencies associated with an element and its child nodes. + * @param element + * The element to dispose. + * @param childNodesOnly + * A boolean value used to determine whether to dispose of the element and its child nodes or to dispose only its child nodes. + */ + disposeElement(element: Element, childNodesOnly: boolean): void; + /** + * Instructs the application to finalize component creation. + */ + endCreateComponents(): void; + /** + * Called by the Sys.Application.endCreateComponents Method to indicate that the process of updating the application has completed. + */ + endUpdate(): void; + /** + * Returns the specified Component object. This member is static and can be invoked without creating an instance of the class. + * @return A Component object that contains the component requested by ID, if found; otherwise, null. + */ + findComponent(id: string, parent?: Sys.Component): Sys.Component; + /** + * Returns the specified Component object. This member is static and can be invoked without creating an instance of the class. + * @return A Component object that contains the component requested by ID, if found; otherwise, null. + */ + findComponent(id: string, parent?: HTMLElement): Sys.Component; + /** + * Returns an array of all components that have been registered with the application by using the addComponent method. This member is static and can be invoked without creating an instance of the class. + */ + getComponents(): Sys.Component[]; + /** + * This function supports the client-script infrastructure and is not intended to be used directly from your code. + */ + initialize(): void; + /** + * Called by a referenced script to indicate that it has been loaded. This API is obsolete. You no longer need to call this method in order to notify the Microsoft Ajax Library that the JavaScript file has been loaded. + */ + notifyScriptLoaded(): void; + /** + * Raises the load event. This member is static and can be invoked without creating an instance of the class. + */ + raiseLoad(): void; + /** + * Raises the Sys.INotifyPropertyChange.propertyChanged event. + */ + raisePropertyChanged(propertyName: string): void; + /** + * Registers with the application an object that will require disposing. This member is static and can be invoked without creating an instance of the class. + */ + registerDisposableObject(object: any): void; + /** + * Removes the object from the application and disposes the object if it is disposable. This member is static and can be invoked without creating an instance of the class. + */ + removeComponent(component: Component): void; + /** + * Unregisters a disposable object from the application. This member is static and can be invoked without creating an instance of the class. + */ + unregisterDisposableObject(object: any): void; + /** + * Called by the Sys.Application.endUpdate method as a placeholder for additional logic. + */ + updated(): void; + + //#endregion + + //#region Properties + + /** + * Gets or sets a value that indicates whether the Web application supports history point management. + */ + get_enableHistory(): boolean; + /** + * Gets or sets a value that indicates whether the Web application supports history point management. + * @param value + * true to allow the Web application to support history points, or false to not allow history points. + */ + set_enableHistory(value: boolean): void; + /** + * Gets a value that indicates whether the application is in the process of creating components. This member is static and can be invoked without creating an instance of the class. + */ + get_isCreatingComponents(): boolean; + /** + * Gets a value that indicates whether the application is in the process of disposing its resources. This member is static and can be invoked without creating an instance of the class. + */ + get_isDisposing(): boolean; + + //#endregion + } + + var Application: Application; + + /** + * Provides information about the current Web browser. + * The Sys.Browser object determines which browser is being used and provides some information about it. You can use this object to help customize your code to the unique requirements or capabilities of the browser. + * @see {@link http://msdn.microsoft.com/en-us/library/cc679064(v=vs.100).aspx} + */ + interface Browser { + + //#region Fields + + /** + * Gets an object that represents the user agent of the browser. + */ + agent: any; + /** + * Gets a value that indicates the document compatibility mode of the browser. + * @return + * + */ + documentMode: number; + /* + * Gets a value that indicates whether the browser supports debug statements. + * @return + * True if the browser supports debug statements + */ + hasDebuggerStatement: boolean; + /** + * Gets the name of the browser. + * @return + * The name of the browser + */ + name: string; + /* + * Gets the version number of the browser. + * @return + * The version of the browser + */ + version: number; + + //#endregion + } + + export function Browser(): Sys.Browser; + + /** + * Provides the base class for the Control and Behavior classes, and for any other object whose lifetime should be managed by the ASP.NET AJAX client library. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397516(v=vs.100).aspx} + */ + class Component { + + //#region Constructors + + /** + * When overridden in a derived class, initializes an instance of that class and registers it with the application as a disposable object. + */ + constructor(); + + //#endregion + + //#region Events + + /** + * Raised when the dispose method is called for a component. + */ + add_disposing(handler: Function): void; + /** + * Raised when the dispose method is called for a component. + */ + remove_disposing(handler: Function): void; + /** + * Raised when the raisePropertyChanged method of the current Component object is called. + */ + add_propertyChanged(handler: Function): void; + /** + * Raised when the raisePropertyChanged method of the current Component object is called. + */ + remove_propertyChanged(handler: Function): void; + + //#endregion + + //#region Methods + + /** + * Called by the create method to indicate that the process of setting properties of a component instance has begun. + */ + beginUpdate(): void; + /** + * Creates and initializes a component of the specified type. This method is static and can be called without creating an instance of the class. + * @param type + * The type of the component to create. + * @param properties + * (Optional) A JSON object that describes the properties and their values. + * @param events + * (Optional) A JSON object that describes the events and their handlers. + * @param references + * (Optional) A JSON object that describes the properties that are references to other components. + * @param element + * (Optional) The DOM element that the component should be attached to. + * + * @returns A new instance of a component that uses the specified parameters. + */ + static create(type: Type, properties?: any, events?: any, references?: any, element?: HTMLElement): Sys.Component; + /** + * Called by the create method to indicate that the process of setting properties of a component instance has finished. + * This method is called by the create method ($create). + * Sets the isUpdating property of the current Component object to false, calls the initialize method if it has not already been called, and then calls the updated method. + */ + endUpdate(): void; + /** + * Initializes the current Component object. + * The initialize method sets the isInitialized property of the current Component object to true. This function is called by the create method ($create) and overridden in derived classes to initialize the component. + */ + initialize(): void; + /** + * Raises the propertyChanged event for the specified property. + * @param propertyName + * The name of the property that changed. + */ + raisePropertyChanged(propertyName: string): void; + /** + * Called by the endUpdate method as a placeholder for additional logic in derived classes. + * Override the updated method in a derived class to add custom post-update logic. + */ + updated(): void; + /** + * Raises the disposing event of the current Component and removes the component from the application. + */ + dispose(): void; + + //#endregion + + //#region Properties + + /** + * Gets an EventHandlerList object that contains references to all the event handlers that are mapped to the current component's events. + * This member supports the client-script infrastructure and is not intended to be used directly from your code. + * @return + * An EventHandlerList object that contains references to all the events and handlers for this component. + */ + get_events(): any; + /** + * Gets the ID of the current Component object. + * @return + * The id + */ + get_id(): string; + /** + * Sets the ID of the current Component object. + * @param value A string that contains the ID of the component. + */ + set_id(value: string): void; + /** + * Gets a value indicating whether the current Component object is initialized. + * @return + * true if the current Component is initialized; otherwise, false. + */ + get_isInitialized(): boolean; + /** + * Gets a value indicating whether the current Component object is updating. + * @return + * true if the current Component object is updating; otherwise, false. + */ + get_isUpdating(): boolean; + + //#endregion + } + + /** + * Represents a culture definition that can be applied to objects that accept a culture-related setting. + * @see {@link http://msdn.microsoft.com/en-us/library/bb384004(v=vs.100).aspx} + */ + class CultureInfo { + + //#region Constructors + + /** + * Initializes a new instance of the Sys.CultureInfo class. + * @param name + * The culture value (locale) that represents a language and region. + * @param numberFormat + * A culture-sensitive numeric formatting string. + * @param dateTimeFormat + * A culture-sensitive date formatting string. + */ + constructor(name: string, numberFormat: string, dateTimeFormat: string); + + //#endregion + + //#region Properties + + /** + * Gets an object that contains an array of culture-sensitive formatting and parsing strings values that can be applied to Number type extensions. + * Use the numberFormat field to retrieve an object that contains an array of formatting strings that are based on the current culture or on the invariant culture. + * Each formatting string can be used to specify how to format Number type extensions. + * @return An object that contains an array of culture-sensitive formatting strings. + */ + numberFormat: string[]; + /** + * Gets the culture value (locale) that represents a language and region. + * @return The culture value (locale) that represents a language and region. + */ + name: string; + /** + * Gets the globalization values of the invariant culture as sent by the server. This member is static and can be invoked without creating an instance of the class. + * The InvariantCulture field contains the following fields associated with the invariant (culture-independent) culture: name, dateTimeFormat, and numberFormat. + * @return A CultureInfo object. + */ + static InvariantCulture: CultureInfo; + /** + * Gets the globalization values of the current culture as sent by the server. This member is static and can be invoked without creating an instance of the class. + * The CurrentCulture field contains the following fields associated with the current culture: name, dateTimeFormat, and numberFormat. + * @return A Sys.CultureInfo object. + */ + static CurrentCulture: CultureInfo; + /** + * Gets an object that contains an array of culture-sensitive formatting and parsing string values that can be applied to Date type extensions. + * Use the dateTimeFormat field to retrieve an object that contains an array of formatting strings that are based on the current culture or on the invariant culture. + * Each formatting string can be used to specify how to format Date type extensions. + * @return An object that contains an array of culture-sensitive formatting strings. + */ + dateTimeFormat: string[]; + + //#endregion + } + + /** + * Provides debugging and tracing functionality for client ECMAScript (JavaScript) code. This class is static and can be invoked directly without creating an instance of the class. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397422(v=vs.100).aspx} + */ + class Debug { + + //#region Constructors + + /** + * Initializes a new instance of the Sys.Debug class. + */ + constructor(); + + //#endregion + + //#region Methods + + /** + * Checks for a condition, and if the condition is false, displays a message and prompts the user to break into the debugger. + * When you call the assert method in your code, express the success of an operation as true or false and use that value for condition. If the operation fails (if condition is false), the assert logic is executed. + * The assert method should be used to catch developer errors. To respond to user errors and to run-time error conditions such as network errors or permission failures, throw an exception. + * Debugging behavior, requirements, and the output of trace messages vary with different browsers. For more information, see Debugging and Tracing Ajax Applications Overview. + * + * @param condition + * true to continue to execute code; false to display message and break into the debugger. + * @param message + * (Optional) The message to display. The default is an empty string (""). + * @param displayCaller + * (Optional) true to indicate that the name of the function that is calling assert should be displayed in the message. The default is false. + */ + static assert(condition: boolean, message?: string, displayCaller?: boolean): void; + /** + * Clears all trace messages from the trace console. + */ + static clearTrace(): void; + /** + * Displays a message in the debugger's output window and breaks into the debugger. + * @param message + * The message to display. + */ + static fail(message: string): void; + /** + * Appends a text line to the debugger console and to the trace console, if available. + * @param text + * The text to display. + */ + static trace(text: string): void; + /** + * Dumps an object to the debugger console and to the trace console, if available. + * @param object + * The object to dump. + * @param name + * (Optional) The name of the object. + */ + static traceDump(object: any, name?: string): void; + + //#endregion + } + + /** + * Describes a change in a collection. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393798(v=vs.100).aspx} + */ + class CollectionChange { + + //#region Constructors + + /** + * Creates a CollectionChange object based on the supplied parameters. + * @param action + * A NotifyCollectionChangedAction enumeration value. + * @param newItems + * (Optional) The items that were added when the action is add or replace. + * @param newStartingIndex + * (Optional) An integer that represents the index where new items have been inserted. + * @param oldItems + * (Optional) The items that were removed when the action is remove or replace. + * @param oldStartingIndex + * (Optional) An integer that represents the index where old items have been removed. + */ + constructor(action: NotifyCollectionChangedAction, newItems: any[], newStartingIndex: number, oldItems: any[], oldStartingIndex: number); + + //#endregion + + //#region Fields + + /** + * Gets a NotifyCollectionChangedAction object that contains the change action enumeration value. + * @return A NotifyCollectionChangedAction object. + */ + action: NotifyCollectionChangedAction; + /** + * @return An array of items that were added. + */ + newItems: any[]; + /** + * The index where new items have been inserted. + * @return An integer that represents the index where new items have been inserted. + */ + newStartingIndex: number; + /** + * The items that were removed when the NotifyCollectionChangedAction object is set to remove. + * @return An array containing the items that were removed. + */ + oldItems: any[]; + /** + * Gets the index where old items have been removed. + * @return An integer that represents the index where old items have been removed. + */ + oldStartingIndex: number; + + //#endregion + } + + /** + * Adds update and management functionality to target objects such as arrays, DOM elements, and objects. + * The Sys.Observer class is based on the Observer pattern. The Sys.Observer class maintains a list of interested dependents (observers) in a separate object (the subject). + * All methods that are contained in the Sys.Observer class are static. + * In order to be used with the Sys.Observer class, an object must be an object, array, or DOM element. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393710(v=vs.100).aspx} + */ + class Observer { + + //#region Methods + + /** + * Adds an item to the collection in an observable manner. + * @param target + * The array to which an item will be added. + * @param item + * The item to add. + */ + static add(target: any[], item: any): void; + /** + * Adds an event handler to the target. + * @param target The array to which an event handler will be added. + * @param handler The event handler. + */ + static addCollectionChanged(target: any, handler: Function): void; + /** + * Adds an observable event handler to the target. + * @param eventName A string that contains the event name. + * @param handler The added function. + */ + static addEventHandler(target: any, eventName: string, handler: Function): void; + /** + * Adds a propertyChanged event handler to the target. + * @param target The object to observe. + * @param handler The function handler to add. + */ + static addPropertyChanged(target: any, handler: Function): void; + /** + * Adds items to the collection in an observable manner. + * @param target The array to which items will be added. + * @param items The array of items to add. + */ + static addRange(target: any[], items: any[]): void; + /** + * Begins the process of updating the target object. + * @param target The object to update. + */ + static beginUpdate(target: any): void; + /** + * Clears the array of its elements in an observable manner. + * @param target The array to clear. + */ + static clear(target: any): void; + /** + * Ends the process of updating the target object. + * @param target The object being updated. + */ + static endUpdate(target: any): void; + /** + * Inserts an item at the specified index in an observable manner. + * @param target The array to which the item is inserted. + * @param index A number that represents the index where the item will be inserted. + * @param item The item to insert. + */ + static insert(target: any, index: number, item: any): void; + /** + * Makes an object directly observable by adding observable methods to it. + * @param target The object, array, or DOM element to make observable. + * @return The observable object. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393633(v=vs.100).aspx} + */ + static makeObservable(target: any): any; + /** + * Raises the collectionChanged event. + * @param target The collection to which an event is raised. + * @param changes A Sys.CollectionChange object that contains the list of changes that were performed on the collection since the last event. + */ + static raiseCollectionChanged(target: any[], changes: Sys.CollectionChange): void; + /** + * Raises an observable event on the target. + * @param target The target object. + * @param eventName A string that contains the event name. + * @param eventArgs A Sys.EventArgs object used to pass event argument information. + */ + static raiseEvent(target: any, eventName: string, eventArgs: Sys.EventArgs): void; + /** + * Raises a propertyChanged notification event. + * @param target The object to which an event is raised. + * @param propertyName The name of the property that changed. + */ + static raisePropertyChanged(target: any, propertyName: string): void; + /** + * Removes the first occurrence of an item from the array in an observable manner. + * @param target The array to which the item will be removed. + * @param item The item to remove. + * @return true if the item is found in the array. Otherwise false. + */ + static remove(target: any[], item: any): boolean; + /** + * Removes the item at the specified index from the array in an observable manner. + * @param target The array to which an item is removed. + * @param index A number that represents the index of the item to remove. + */ + static removeAt(target: any[], index: number): void; + /** + * Removes the collectionChanged event handler from the target. + * @param target The array from which the collectionChanged event handler is removed. + * @param handler The function to remove. + */ + static removeCollectionChanged(target: any, handler: Function): void; + /** + * Removes a propertyChanged event handler from the target. + * @param target The object to observe. + * @param handler The event handler to remove. + */ + static removeEventHandler(target: any, handler: Function): void; + /** + * Sets a property or field on the target in an observable manner. + * The raisePropertyChanged method is called after the setValue method set the value of the target object property. + * @param target The object to which the property is set. + * @param propertyName A string that contains the name of the property or field to set. + * @param value The value to set. + */ + static setValue(target: any, propertyName: string, value: any): void; + + //#endregion + + //#region Properties + + /** + * Indicates that the target is being updated. + * @param target The target object to update. + * @return true if given target argument is currently updating; otherwise false. + */ + static isUpdating(target: any): boolean; + + //#endregion + } + + /** + * Provides static, culture-neutral exception messages that are used by the Microsoft Ajax Library framework. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397705(v=vs.100).aspx} + * This type supports the .NET Framework infrastructure and is not intended to be used directly from your code. + */ + class Res { + + //#region Fields + + /** + * @return "Actual value was {0}." + */ + static actualValue: string; + /** + * @return "The application failed to load within the specified time out period." + */ + static appLoadTimedout: string; + /** + * @return "Value does not fall within the expected range." + */ + static argument: string; + /** + * @return "Value cannot be null." + */ + static argumentNull: string; + /** + * @return "Specified argument was out of the range of valid values. + */ + static argumentOutOfRange: string; + /** + * @return "Object cannot be converted to the required type." + */ + static argumentType: string; + /** + * @return "Object of type '{0}' cannot be converted to type '{1}'." + */ + static argumentTypeWithTypes: string; + /** + * @return "Value cannot be undefined." + */ + static argumentUndefined: string; + /** + * @return "Assertion Failed: {0}" + */ + static assertFailed: string; + /** + * @return "Assertion Failed: {0}\r\nat {1}" + */ + static assetFailedCaller: string; + /** + * @return "Base URL does not contain ://." + */ + static badBaseUrl1: string; + /** + * @return "Base URL does not contain another /." + */ + static badBaseUrl2: string; + /** + * @return "Cannot find last / in base URL." + */ + static badBaseUrl3: string; + /** + * @return "{0}\r\n\r\nBreak into debugger?" + */ + static breakIntoDebugger: string; + /** + * @return "Cannot abort when executor has not started." + */ + static cannotAbortBeforeStart: string; + /** + * @return "Cannot call {0} when responseAvailable is false." + */ + static cannotCallBeforeResponse: string; + /** + * @return "Cannot call {0} once started." + */ + static cannotCallOnceStarted: string; + /** + * @return "Cannot call {0} outside of a completed event handler." + */ + static cannotCallOutsideHandler: string; + /** + * @return "Cannot deserialize empty string." + */ + static cannotDeserializeEmptyString: string; + /** + * @return "Cannot serialize non-finite numbers." + */ + static cannotSerializeNonFiniteNumbers: string; + /** + * @return "The id property can't be set on a control." + */ + static controlCantSetId: string; + /** + * @return "'{0}' is not a valid value for enum {1}." + */ + static enumInvalidValue: string; + /** + * @return "Handler was not added through the Sys.UI.DomEvent.addHandler method. + */ + static eventHandlerInvalid: string; + /** + * @return "One of the identified items was in an invalid format." + */ + static format: string; + /** + * @return "The string was not recognized as a valid Date." + */ + static formatBadDate: string; + /** + * @return "Format specifier was invalid." + */ + static formatBadFormatSpecifier: string; + /** + * @return "Input string was not in a correct format." + */ + static formatInvalidString: string; + /** + * @return "Could not create a valid Sys.Net.WebRequestExecutor from: {0}." + */ + static invalidExecutorType: string; + /** + * @return "httpVerb cannot be set to an empty or null string." + */ + static invalidHttpVerb: string; + /** + * @return "Operation is not valid due to the current state of the object." + */ + static invalidOperation: string; + /** + * @return "Value must be greater than or equal to zero." + */ + static invalidTimeout: string; + /** + * @return "Cannot call invoke more than once." + */ + static invokeCalledTwice: string; + /** + * @return "The method or operation is not implemented." + */ + static notImplemented: string; + /** + * @return "Cannot call executeRequest with a null webRequest." + */ + static nullWebRequest: string; + + //#endregion + } + + /** + * Provides a mechanism to concatenate strings. + * The StringBuilder class represents a mutable string of characters and provides a mechanism to concatenate a sequence of strings. + * @see {@link http://msdn.microsoft.com/en-us/library/bb310852(v=vs.100).aspx} + */ + class StringBuilder { + + //#region Constructors + + /** + * Creates a new instance of StringBuilder and optionally accepts initial text to concatenate. You can specify a string in the optional initialText parameter to initialize the value of the StringBuilder instance. + * @param initialText + * (Optional) The string that is used to initialize the value of the instance. If the value is null, the new StringBuilder instance will contain an empty string (""). + */ + constructor(initialText?: string); + + //#endregion + + //#region Methods + + /** + * Appends a copy of a specified string to the end of the Sys.StringBuilder instance. + * Use the append method to append a copy of a specified string to the end of a StringBuilder instance. If text is an empty string, null, or undefined, the StringBuilder instance remains unchanged. + * @param text + * The string to append to the end of the StringBuilder instance. + */ + append(text: string): void; + + /** + * Appends a string with a line terminator to the end of the Sys.StringBuilder instance. + * Use the appendLine method to append a specified string and a line terminator to the end of a Stringbuilder instance. The line terminator is a combination of a carriage return and a newline character. If no string is specified in text, only the line terminator is appended. + * @param text + * (Optional) The string to append with a line terminator to the end of the StringBuilder instance. + */ + appendLine(text: string): void; + + /** + * Clears the contents of the Sys.StringBuilder instance. + * Use the clear method to clear the StringBuilder instance of its current contents. + */ + clear(): void; + + /** + * Determines whether the Sys.StringBuilder object has content. + * Use the isEmpty method to determine whether a StringBuilder instance has any content. If you append an empty string, null, or an undefined value to an empty StringBuilder instance, the instance remains empty and unchanged. + * @return true if the StringBuilder instance contains no elements; otherwise, false. + */ + isEmpty(): boolean; + + /** + * Creates a string from the contents of a Sys.StringBuilder instance, and optionally inserts a delimiter between each element of the created string. + * Use the toString method to create a string from the contents of a StringBuilder instance. Use the toString method with the optional separator parameter to insert a specified string delimiter between each element of the created string. + * @param separator + * (Optional) A string to append between each element of the string that is returned. + * @return A string representation of the StringBuilder instance. If separator is specified, the delimiter string is inserted between each element of the returned string. + */ + toString(separator?: string): string; + + //#endregion + } + + //#endregion + + //#region Enumerations + + /** + * Describes how a collection has changed. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393774(v=vs.100).aspx} + */ + enum NotifyCollectionChangedAction { + /** + * The integer 0, indicating the changed action to the collection is add. + */ + add = 0, + /** + * The integer 1, indicating the changed action to the collection is remove. + */ + remove = 1, + /** + * The integer 2, indicating the changed action to the collection is reset. + */ + reset = 2 + } + + //#endregion + + //#region Interfaces + + /** + * Provides a common interface for all components that can contain other components. + */ + interface IContainer { + + //#region Methods + + /** + * Adds a Component object to the current container. + * Implement this method for an object that will contain one or more component objects in order to programmatically add components to that container. + * @param component + * The Component object to add. + */ + addComponent(component: Component): void; + /** + * Returns the specified Component instance. + * Implement this method for an object that will contain one or more component objects to access components within that container. + * @param id + * The ID of the Component object to search for. + * @return The Component instance with the specified ID. + */ + findComponent(id: string): Component; + /** + * Returns an array of all objects in the current container that inherit from Component. + * Implement this method for an object that will contain one or more component objects so that the components in that container are available. Types that implement this method should return a copy of the list of components so that modifying the array does not change the contents of the container. + * @return An array of all objects in the current container that inherit from Component. + */ + getComponents(): Component[]; + /** + * Removes a Component object from the current container. + * @param component + * The Component object to remove. + */ + removeComponent(component: Component): void; + + //#endregion + } + + /** + * Provides a common interface for the application-defined tasks of closing, releasing, or resetting resources held by instances of a registered Microsoft Ajax Library class. + * Implement the IDisposable interface to provide a common interface for closing or releasing resources held by instances of your registered Microsoft Ajax Library class. + * You register an interface by when you register the class by calling the Type.registerClass method. You specify IDisposable in the interfaceTypes parameter when you call Type.registerClass. + */ + interface IDisposable { + + //#region Methods + + /** + * Releases resources held by an object that implements the Sys.IDisposable interface. + * Implement the dispose method to close or release resources held by an object, or to prepare an object for reuse. + */ + dispose(): void; + + //#endregion + } + + /** + * Indicates that the type that implements the interface provides disposing notifications. + * Implement this interface if the class must notify other objects when it is releasing resources. The base component class already implements this interface. Therefore, typically this interface is already available. + */ + interface INotifyDisposing { + + //#region Events + + /** + * Occurs when an object's resources are released. + * @param handler + * The name of the event handler for the disposing event. + */ + add_disposing(handler: Function): void; + /** + * Occurs when an object's resources are released. + * @param handler + * The name of the event handler for the disposing event. + */ + remove_disposing(handler: Function): void; + + //#endregion + } + + /** + * Defines the propertyChanged event. + */ + interface INotifyPropertyChange { + + //#region Events + + /** + * Occurs when a component property is set to a new value. + * @param handler + * The name of the event handler for the propertyChanged event. + */ + add_propertyChanged(handler: Function): void; + /** + * Occurs when a component property is set to a new value. + * @param handler + * The name of the event handler for the propertyChanged event. + */ + remove_propertyChanged(handler: Function): void; + + //#endregion + } + + //#endregion + + //#region Event Args + + /* + * Used by the Application class to hold event arguments for the load event. + * @see {@link http://msdn.microsoft.com/en-us/library/bb383787(v=vs.100).aspx} + */ + class ApplicationLoadEventArgs { + + //#region Constructors + + /** + * Initializes a new instance of the ApplicationLoadEventArgs class. + * @param components + * The list of components that were created since the last time the load event was raised. + * @param isPartialLoad + * true to indicate that the event is a partial-page update. + */ + constructor(components: any, isPartialLoad: boolean); + + //#endregion + + //#region Properties + + /** + * Gets an array of all the components that were created since the last time the load event was raised. + * @return An array of all the components that were created since the last time the load event was raised. + */ + get_components(): Component[]; + /** + * Returns a value that indicates whether the page is engaged in a partial-page update. + * @return true if the page is engaged in a partial-page update; otherwise, false. + */ + get_isPartialLoad(): boolean; + + //#endregion + } + + /** + * Provides a base class for classes that are used by event sources to pass event argument information. + * The EventArgs class is a base class and not intended to be used directly. Override this constructor to provide specific functionality. + * @see {@link http://msdn.microsoft.com/en-us/library/bb383795(v=vs.100).aspx} + */ + class EventArgs { + + //#region Constructors + + /** + * Initializes a new instance of the EventArgs class. + */ + constructor(); + + //#endregion + + //#region Fields + + /** + * A static object of type EventArgs that is used as a convenient way to specify an empty EventArgs instance. + */ + static Empty: EventArgs; + + /** + * An object of type EventArgs that is used as a convenient way to specify an empty EventArgs instance. + */ + Empty: EventArgs; + + //#endregion + + } + + /** + * Provides a class for command events. + * Event handlers can use the cancel property to cancel the operation in progress. The semantics of canceling an event depend on the event source. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393715(v=vs.100).aspx + */ + class CommandEventArgs extends EventArgs { + + //#region Constructors + + constructor(commandName: string, commandArgument: any, commandSource: any); + + //#endregion + + //#region Properties + + /** + * Gets a string that specifies the command name. + */ + get_commandName(): string; + + /** + * Gets a value that represents the command argument. + */ + get_commandArgument(): any; + + /** + * Gets a value that represents the command source. + */ + get_commandSource(): any; + + //#endregion + } + + /** + * Provides the base class for events that can be canceled. + * @see {@link http://msdn.microsoft.com/en-us/library/bb311009(v=vs.100).aspx} + */ + class CancelEventArgs extends EventArgs { + + //#region Constructors + + /** + * Initializes a new instance of the CancelEventArgs class. + */ + constructor(); + + //#endregion + + //#region Properties + + /** + * true to request that the event be canceled; otherwise, false. The default is false. + */ + set_cancel(value: boolean): void; + + /* + * true to request that the event be canceled; otherwise, false. The default is false. + * @return if the event is to be canceled; otherwise, false. + */ + get_cancel(): boolean; + + //#endregion + + } + + /** + * This class is used by the Sys.Application Class to hold event arguments for the navigate event. + * @see {@link http://msdn.microsoft.com/en-us/library/cc488008(v=vs.100).aspx} + */ + class HistoryEventArgs extends EventArgs { + + //#region Constructors + + /** + * For a live code example that demonstrates this event in action, and for a view of how this event is used in code, see Managing Browser History Using Client Script. + * @param state Object. A collection of key/value pairs that represent the state data. This data will be added to the main state to form the global state of the new history point. + */ + constructor(state: any); + + //#endregion + + //#region Methods + + /** + * Object. A collection of name/value pairs that represent the state of a Web page. + * The state object stores the data that is required in order to restore a Web page to a specified application state. + * @return Object. A collection of name/value pairs that represent the state of a Web page. + */ + get_State(): any; + + //#endregion + } + + /** + * Describes how the collection was changed. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393665(v=vs.100).aspx} + */ + class NotifyCollectionChangedEventArgs extends EventArgs { + + //#region Constructors + + /** + * Initializes a new instance of the CancelEventArgs class. + * @param changes + * A CollectionChange object that contains an array of changes that were performed on the collection since the last event. + */ + constructor(changes: CollectionChange); + + //#endregion + + //#region Properties + + /** + * Gets an array of changes that were performed on the collection since the last event. + * @return An array of CollectionChange objects that were performed on the collection since the last event. + */ + get_changes(): CollectionChange[]; + + //#endregion + } + + /** + * Used by the propertyChanged event to indicate which property has changed. + * @see {@link http://msdn.microsoft.com/en-us/library/bb310957(v=vs.100).aspx} + */ + class PropertyChangedEventArgs extends EventArgs { + + //#region Constructors + + /** + * Initializes a new instance of the PropertyChangedEventArgs class. + * @param propertyName + * The name of the property that changed. + */ + constructor(propertyName: string); + + //#endregion + + //#region Methods + + /** + * Gets the name of the property that changed. + * Use the propertyName property to determine the name of the property that changed. + * @return A string that contains the name of the property that changed. + */ + propertyName(): string; + + + //#endregion + } + + //#endregion + + //#region Exception Types + + /** + * Raised when a function or method is invoked and at least one of the passed arguments does not meet the parameter specification of the called function or method. + */ + class ArgumentException { + + } + /** + * Raised when an argument has an invalid value of null. + */ + class ArgumentNullException { + + } + /** + * Raised when an argument value is outside an acceptable range. + */ + class ArgumentOutOfRangeException { + + } + /** + * Raised when a parameter is not an allowed type. + */ + class ArgumentTypeException { + + } + /** + * Raised when an argument for a required method parameter is undefined. + */ + class ArgumentUndefinedException { + + } + /** + * + */ + class FormatException { + + } + /** + * Raised when a call to a method has failed, but the reason was not invalid arguments. + */ + class InvalidOperationException { + + } + /** + * Raised when a requested method is not supported by an object. + */ + class NotImplementedException { + + } + /** + * Raised when an invalid number of arguments have been passed to a function. + */ + class ParameterCountException { + + } + /** + * Raised by the Microsoft Ajax Library framework when a script does not load successfully. This exception should not be thrown by the developer. + */ + class ScriptLoadFailedException { + + } + + //#endregion + + //#region Sys.Net Namespace + + /** + * The Sys.Net namespace contains classes that manage communication between AJAX-enabled ASP.NET client applications and Web services on the server. For more information, see Using Web Services in ASP.NET AJAX. The Sys.Net namespace is part of the Microsoft Ajax Library. + * @see {@link http://msdn.microsoft.com/en-us/library/bb310860(v=vs.100).aspx} + */ + module Net { + + /** + * Generated Proxy Classes + * Enables your application to call Web services asynchronously by using ECMAScript (JavaScript). + * @see {@link http://msdn.microsoft.com/en-us/library/bb310823(v=vs.100).aspx} + */ + // Cannot create definitions for generated proxy classes. + + /** + * Contains information about a Web request that is ready to be sent to the current Sys.Net.WebRequestExecutor instance. + * This class represents the type for the second parameter of the callback function added by the add_invokingRequest method. + * The callback function is called before the Web request is routed to the current instance of the WebRequestExecutor class. + * + * @see {@link http://msdn.microsoft.com/en-us/library/bb397488(v=vs.100).aspx} + */ + class NetWorkRequestEventArgs { + + //#region Constructors + + /** + * Initializes a new instance of the Sys.Net.NetworkRequestEventArgs. class. + * @param value + * The current WebRequest instance. + */ + constructor(value: WebRequest); + + //#endregion + + //#region Methods + + //#endregion + + //#region Properties + + /** + * Gets the Web request to be routed to the current Sys.Net.WebRequestExecutor instance. + * Use this property to inspect the contents of a Web request before it is routed to the current instance of the Sys.Net.WebRequestExecutor class. + * You can access the Web request instance from the handler that is called before the request is routed. + * This event handler is added by using the add_invokingRequest method. + * @return + * The WebRequest. + */ + get_webRequest(): WebRequest; + + //#endregion + + } + + /** + * Provides the script API to make a Web request. + * @see {@link http://msdn.microsoft.com/en-us/library/bb310979(v=vs.100).aspx} + */ + class WebRequest { + + //#region Constructors + + /** + * Initializes a new instance of the Sys.Net.WebRequest class. + */ + constructor(); + + //#endregion + + //#region Members + + /** + * Registers a handler for the completed request event of the Web request. + * @see {@link http://msdn.microsoft.com/en-us/library/bb310841(v=vs.100).aspx} + */ + add_completed(handler: (reference: any, eventArgs: Sys.EventArgs) => void): void; + + /** + * Removes the event handler added by the add_completed method. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397454(v=vs.100).aspx} + */ + remove_completed(handler: (reference: any, eventArgs: Sys.EventArgs) => void): void; + + /** + * Gets the resolved URL of the Sys.Net.WebRequest instance. + * @returns The resolved URL that the Web request is directed to. + */ + getResolvedUrl(): string; + + /** + * Executes a Web request. + */ + invoke(): void; + + /** + * Raises the completed event for the associated Sys.Net.WebRequest instance. + * @param eventArgs + * The value to pass to the Web request completed event handler. + */ + completed(eventArgs: Sys.EventArgs): void; + + //#endregion + + } + + /** + * Provides the abstract base class from which network executors derive. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397434(v=vs.100).aspx} + */ + class WebRequestExecutor { + + //#region Constructors + + /** + * Initializes a Sys.Net.WebRequestExecutor instance when implemented in a derived class. + */ + constructor(); + + //#endregion + + //#region Methods + + /** + * Stops the pending network request issued by the executor. + * The specifics of aborting a request vary depending on how an executor is implemented. + * However, all executors that derive from WebRequestExecutor must set their state to aborted and must raise the completed event of the associated Sys.Net.WebRequest object. + * The executor properties do not contain consistent data after abort has been called. + */ + abort(): void; + /** + * Instructs the executor to execute a Web request. + * When this method is called, the executor packages the content of the Web request instance and initiates processing. + * This method is intended to be used by a custom executor. If you are implementing a custom executor, you instantiate the executor, assign it to the Web request instance, and then invoke the method on the executor instance. + * @see {@link http://msdn.microsoft.com/en-us/library/bb383834(v=vs.100).aspx} + */ + executeRequest(): void; + /** + * Gets all the response headers for the current request. + * If a request finished successfully and with valid response data, this method returns all the response headers. + * @return All the response headers + * @see {@link http://msdn.microsoft.com/en-us/library/bb310805(v=vs.100).aspx} + */ + getAllResponseHeaders(): string; + /** + * Gets the value of the specified response header. + * @return The specified response header. + */ + getResponseHeader(): string; + + //#endregion + + //#region Properties + + /** + * Gets the JSON-evaluated object from the response. + * @return The JSON-evaluated response object. + */ + object(): any; + /** + * Gets a value indicating whether the request associated with the executor was aborted. + * When the current instance of the Sys.Net.WebRequestExecutor class is aborted, it must set its state to aborted and it must raise the completed event of the associated request object. + * @return true if the request associated with the executor was aborted; otherwise, false. + */ + get_aborted(): boolean; + /** + * Gets a value indicating whether the request completed successfully. + * Successful completion usually means a well-formed response was received by the executor. + * If a response was received, the current instance of the Sys.Net.WebRequestExecutor class must set its state to completed. + * It must also raise the completed event of the associated request object. + * @return true if the request completed successfully; otherwise, false. + */ + get_responseAvailable(): boolean; + /** + * Gets the text representation of the response body. When a request has completed successfully with valid response data, this property returns the text that is contained in the response body. + * @return The text representation of the response body. + */ + get_responseData(): string; + /** + * Returns a value indicating whether the executor has started processing the request. + * The executor returns true if substantial processing of the request has started. For executors that make network calls, substantial processing means that a network call has been started. + * @return true if the executor has started processing the request; otherwise, false. + */ + get_started(): boolean; + /** + * Gets a success status code. + * The statusCode property returns an integer that specifies that a request completed successfully and with valid response data. + * @return An integer that represents a status code. + */ + get_statusCode(): number; + /** + * Gets status information about a request that completed successfully. + * The statusText property returns status information if a request completed successfully and with valid response data. + * @return the status text + */ + get_statusText(): string; + /** + * Gets a value indicating whether the request timed out. + * Executors use the time-out information associated with the request to raise the completed event on the associated WebRequest object. + * @return true if the request timed out; otherwise, false. + */ + get_timedOut(): boolean; + /** + * Attempts to get the response to the current request as an XMLDOM object. + * If a request finished successfully with valid response data, this method tries to get the response as an XMLDOM object. + */ + get_xml(): XMLDocument; + /** + * Gets the WebRequest object associated with the executor. + * @return The WebRequest object associated with the current executor instance. + */ + get_webRequest(): Sys.Net.WebRequest; + + //#endregion + } + + + /** + * Manages the flow of the Web requests issued by the Sys.Net.WebRequest object to the associated executor object. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397435(v=vs.100).aspx} + */ + class IWebRequestManager { + + //#region Constructor + + /** + * Initializes a new instance of the Sys.Net.WebRequestManager class when implemented in a derived class. + */ + constructor(); + + //#endregion + + //#region Methods + + /** + * Registers a handler for the completed request event of the WebRequestManager. + * @param handler + * The function registered to handle the completed request event. + */ + add_completedRequest(handler: (sender: any, eventArgs: any) => void): void; + /** + * Registers a handler for processing the invoking request event of the WebRequestManager. + * @param handler + * The function registered to handle the invoking request event. + */ + add_invokingRequest(handler: (sender: any, networkRequestEventArgs: any) => void): void; + /** + * Sends Web requests to the default network executor. + * This member supports the client-script infrastructure and is not intended to be used directly from your code. + * @param WebRequest + * An instance of the Sys.Net.WebRequest class. + */ + executeRequest(WebRequest: Sys.Net.WebRequest): void; + /** + * Removes the event handler set by the add_completedRequest method. + * Use the remove_ completedRequest method to remove the event handler you set using the add_ completedRequest method. + * @param handler + * The function that handles the completed request event. + */ + remove_completedRequest(handler: Function): void; + /** + * Removes the event handler set by the add_invokingRequest method. + * Use the remove_invokingRequest method to remove the event handler you set using the add_invokingRequest method. + * @param handler + * The function that handles the invoking request event. + */ + remove_invokingRequest(handler: Function): void; + + //#endregion + + //#region Properties + + /** + * Gets or sets the default network executor type that is used to make network requests. + * @return + * The object that represents the default Web request executor. + */ + get_defaultExecutorType(): Sys.Net.WebRequestExecutor; + /** + * Gets or sets the default network executor type that is used to make network requests. + * @param value + * A reference to an implementation of the WebRequestExecutor class. + */ + set_defaultExecutorType(value: Sys.Net.WebRequestExecutor): void; + /** + * Gets or sets the time-out for the default network executor. + * @return + * An integer value that indicates the current time-out for the default executor. + */ + get_defaultTimeout(): number; + /** + * Gets or sets the time-out for the default network executor. + * + * @throws Sys.ArgumentOutOfRangeException An invalid parameter was passed. + * @param value + * The time in milliseconds that the default executor should wait before timing out a Web request. This value must be 0 or a positive integer. + */ + set_defaultTimeout(value: number): void; + + //#endregion + + } + + export var WebRequestManager: IWebRequestManager; + + } + + //#endregion + + //#region Sys.Serialization Namespace + + /** + * Contains classes related to data serialization for AJAX client functionality in ASP.NET. For more information, see Using Web Services in ASP.NET AJAX. + * @see {@link http://msdn.microsoft.com/en-us/library/bb310840(v=vs.100).aspx} + */ + module Serialization { + + /** + * Serializes JavaScript types into JSON-formatted data and deserializes JSON-formatted data into JavaScript types + * The JavaScriptSerializer class contains only static methods. + * @see {@link http://msdn.microsoft.com/en-us/library/bb310857(v=vs.100).aspx} + */ + class JavaScriptSerializer { + + //#region Constructors + + /** + * Initializes a new instance of the Sys.Serialization.JavaScriptSerializer class. + */ + constructor(); + + //#endregion + + //#region Methods + + /** + * Converts an ECMAScript (JavaScript) object graph into a JSON string. This member is static and can be invoked without creating an instance of the class. + * @static + * @param value + * The JavaScript object graph to serialize. + * @exception Sys.ArgumentException + * value contains a value that cannot be serialized. + */ + static serialize(value: any): string; + + /** + * Converts a JSON string into an ECMAScript (JavaScript) object graph. This member is static and can be invoked without creating an instance of the class. + * @static + * @param value + * The JSON string to deserialize. + */ + static deserialize(value: string): any; + + //#endregion + } + } + + //#endregion + + //#region Sys.Services Namespace + + /** + * Contains types that provide script access in AJAX-enabled ASP.NET client applications to the ASP.NET authentication service, profile service, and other application services. + * The Sys.Services namespace is part of the Microsoft Ajax Library. + * For more information @{see Using Web Services in ASP.NET AJAX {@link http://msdn.microsoft.com/en-us/library/bb515101(v=vs.100).aspx}} + * @see {@link http://msdn.microsoft.com/en-us/library/bb311017(v=vs.100).aspx} + */ + module Services { + + /** + * Provides the client proxy class for the authentication service. + * The AuthenticationService class is a singleton; it has only one instance with a global point of access. + * It is always available to your application and you do not have to instantiate it. + * The AuthenticationService class provides script access to user authentication. + * It calls methods of the authentication service through the same infrastructure used to call any other Web service method. + * @see {@link http://msdn.microsoft.com/en-us/library/bb310861(v=vs.100).aspx} + */ + class AuthenticationService { + + //#region Constructors + + /** + * Initializes a new instance of the Sys.Services.AuthenticationService class. + */ + constructor(); + + //#endregion + + //#region Fields + + /** + * Specifies the path of the default authentication service. + */ + DefaultWebServicePath: string; + + //#endregion + + //#region Methods + + /** + * Authenticates the user's credentials. + * @param userName (required) The user name to authenticate. + * @param password + * The user's password. The default is null. + * @param isPersistent + * true if the issued authentication ticket should be persistent across browser sessions; otherwise, false. The default is false. + * @param redirctUrl + * The URL to redirect the browser to on successful login. The default is null. + * @param customInfo + * + * @param loginCompletedCallback + * The function to call when the login has finished successfully. The default is null. + * @param failedCallback + * The function to call if the login fails. The default is null. + * @param userContext + * User context information that you are passing to the callback functions. + * @exception Sys.ArgumentNullException - username is null. + */ + login(userName: string, password: string, isPersistent: boolean, customInfo: any, redirectUrl: string, loginCompletedCallback: Function, failedCallback: Function, userContext: any): void; + + /** + * Logs out the currently authenticated user. + * + * If redirectUrl is null or is an empty string, the page is redirected to itself after the call to the authentication Web service finishes and the completed callback function is called. + * This makes sure that any user-related data is cleared from the page. If redirectUrl is not null or is a non-empty string, the page is redirected to the specified URL after a successful call to the Web service. + * This URL can be an absolute virtual path, a relative virtual path, or a fully qualified domain name and a path. + * If the call to the Web service fails, the page is not redirected or refreshed. Instead, the failed callback function is called. + * + * @param redirectUrl + * The URL to redirect the browser to on successful logout. The default is null. + * @param logoutCompletedCallback + * The function that is called when the logout has finished. The default is null. + * @param failedCallback + * The function that is called if the logout has failed. The default is null. + * @param userContext + * User context information that you are passing to the callback functions. + */ + logout(redirectUrl: string, logoutCompletedCallback: Function, failedCallback: Function, userContext: any): void; + + //#endregion + + //#region Properties + + /** + * Gets or sets the name of the default failure callback function. + */ + get_defaultFailedCallback(): Function; + /** + * Gets or sets the name of the default failure callback function. + * @param value + * A string that contains the name of the default failure callback function. + */ + set_defaultFailedCallback(value: string): void; + /** + * Gets or sets the default succeeded callback function for the service. + * @return A reference to the succeeded callback function for the service. + */ + defaultSucceededCallback(): Function; + /** + * Gets or sets the default succeeded callback function for the service. + * @param value + * A reference to the succeeded callback function for the service. + */ + defaultSucceededCallback(value: Function): void; + /** + * Gets or sets the default user context for the service. + * @return A reference to the user context for the service. + */ + defaultUserContext(): Object + /** + * Gets or sets the default user context for the service. + * @param value + * A reference to the user context for the service. + */ + defaultUserContext(value: Object): void; + /** + * Gets the authentication state of the current user. + * The value of this property is set by the ScriptManager object during a page request. + * @return true if the current user is logged in; otherwise, false. + */ + get_isLoggedIn(): boolean; + /** + * Gets or sets the authentication service path. + * You usually set the path property in declarative markup. This value can be an absolute virtual path, a relative virtual path, or a fully qualified domain name and a path. + * By default, the path property is set to an empty string. If you do not set the path property, the internal default path is used, which points to the built-in authentication service. + * @param value + * The authentication service path. + */ + set_path(value: string): void; + /** + * Gets or sets the authentication service path. + * By default, the path property is set to an empty string. If you do not set the path property, the internal default path is used, which points to the built-in authentication service. + */ + get_path(): string; + /** + * Gets or sets the authentication service time-out value. + * The timeout property represents the time in milliseconds that the current instance of the Sys.Net.WebRequestExecutor class should wait before timing out the request. + * By setting a time-out interval, you can make sure that a pending request returns based on a time interval that you specify, instead of waiting for the asynchronous communication layer to time out. + * @param value + * The time-out value in milliseconds. + */ + set_timeout(value: number): void; + /** + * Gets or sets the authentication service time-out value. + * The timeout property represents the time in milliseconds that the current instance of the Sys.Net.WebRequestExecutor class should wait before timing out the request. + * The timeout in milliseconds + * @return + * The timeout + */ + get_timeout(): number; + + //#endregion + } + + /** + * Defines a profile group. + * The ProfileGroup class defines the type of an element as a group in the properties collection of the Sys.Services.ProfileService class. + * Profile group properties are accessed as subproperties of the related group, as shown in the following ECMAScript (JavaScript) example: + * @see {@link http://msdn.microsoft.com/en-us/library/bb310801(v=vs.100).aspx} + */ + class ProfileGroup { + + //#region Constructors + + constructor(); + + /** + * Initializes a new instance of the Sys.Services.ProfileGroup class. + * @param properties + * (Optional) An object that contains the settings for this profile group. This parameter can be null. + */ + + constructor(properties: Object); + + //#endregion + + //#region Methods + + + + //#endregion + + } + + /** + * Provides the client proxy class for the role service. + * @see {@link http://msdn.microsoft.com/en-us/library/bb513880(v=vs.100).aspx} + */ + class RoleService { + + } + + /** + * Provides the client proxy class for the profile service. + * @see {@link http://msdn.microsoft.com/en-us/library/bb383800(v=vs.100).aspx} + */ + class ProfileService { + + new(): ProfileService; + + //#region Fields + + /** + * Specifies the path of the default profile service. + */ + static DefaultWebServicePath: string; + /** + * Contains the loaded profile data. You can access the loaded profile data directly from the properties field. + * An element in the properties field can be a property group of type ProfileGroup. If it is, the related properties appear as sub-properties. For more information, see Sys.Services.ProfileGroup Class. + */ + static properties: any; + + //#endregion + + //#region Methods + + /** + * Loads the specified profile properties. + * + * If propertyNames is not supplied, all profile properties enabled for read access are loaded from the server. + * The loaded profile can then be accessed directly from the properties field. + * This enables your application to access the profile properties by using simple field syntax, as shown in the following example: + * @example + * Sys.Services.ProfileService.load(null, LoadCompletedCallback, ProfileFailedCallback, null); + * + * @param propertyName + * A string array that contains the profile properties to load. + * @param loadCompletedCallback + * The function that is called when loading has completed. The default is null. + * @param failedCallback + * The function that is called when loading has failed. The default is null. + * @param userContext + * User context information passed to the callback functions. + */ + static load(propertyNames: string[], loadCompletedCallback: Function, failedCallback: Function, userContext: any): void; + /** + * @param propertyNames + * A string array that contains the profile properties to save. + * @param saveCompletedCallback + * The function that is called when the save method has finished. The default is null. + * @param failedCallback + * The function that is called if the save method has failed. The default is null. + * @param userContext + * User context information passed to the callback functions. + */ + static save(propertyNames: string[], saveCompletedCallback: Function, failedCallback: Function, userContext: any): void; + + //#endregion + + //#region Properties + + /** + * Gets or sets the name of the default failure callback function. + * @param value + * A string that contains the name of the default failure callback function. + */ + static set_defaultFailedCallback(value: string): void; + static get_defaultFailedCallback(): Function; + /** + * Gets or sets the name of the default load-completed callback function. + * + * @param value + * A string that contains the name of the default load-completed callback function. + */ + static set_defaultLoadCompletedCallback(value: string): void; + static get_defaultLoadCompletedCallback(): Function; + /** + * Gets or sets the name of the default save-completed callback function. + * @param value + * A string that contains the name of the default save-completed callback function. + */ + static set_defaultSaveCompletedCallback(value: string): void; + static get_defaultSaveCompletedCallback(): Function; + /** + * Gets or sets the default succeeded callback function for the service. + * @return + * A reference to the succeeded callback function for the service. + */ + static defaultSucceededCallback(): Function; + static defaultSucceededCallback(value: Function): void; + /** + * Gets or sets the default user context for the service. + * @return + * A reference to the user context for the service. + */ + static defaultUserContext(): Object; + /** + * Gets or sets the default user context for the service. + */ + static defaultUserContext(value: Object): void; + /** + * Gets or sets the profile service path. + * @param value + * A string that contains the profile service path. + */ + static set_path(value: string): void; + /** + * Gets or sets the profile service path. + * @return + * The profile path + */ + static get_path(): string; + + /** + * Gets or sets the profile service time-out value. + * The timeout property represents the time in milliseconds that the current instance of the Sys.Net.WebRequestExecutor class should wait before timing out the request. + * By setting a time-out interval, you can make sure that a pending request returns based on a time interval that you specify, instead of waiting for the asynchronous communication layer to time out. + * + * @param value + * The time-out value in milliseconds. + */ + static set_timeout(value: number): void; + /** + * Gets or sets the profile service time-out value. + */ + static get_timeout(): number; + + //#endregion + } + + } + + //#endregion + + //#region Sys.UI Namespace + + /** + * Contains types related to the user interface (UI), such as controls, events, and UI properties in the Microsoft Ajax Library. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397431(v=vs.100).aspx} + */ + module UI { + + /** + * Provides a base class for all ASP.NET AJAX client behaviors. + * @see {@link http://msdn.microsoft.com/en-us/library/bb311020(v=vs.100).aspx} + */ + class Behavior extends Sys.Component { + + //#region Methods + + /** + * Gets a Sys.UI.Behavior instance with the specified name property from the specified HTML Document Object Model (DOM) element. This member a static member and can be invoked without creating an instance of the class. + * @return The specified Behavior object, if found; otherwise, null. + */ + static getBehaviorByName(element: Sys.UI.DomElement, name: string): Behavior; + /** + * Gets an array of Sys.UI.Behavior objects that are of the specified type from the specified HTML Document Object Model (DOM) element. This method is static and can be invoked without creating an instance of the class. + * @return An array of all Behavior objects of the specified type that are associated with the specified DOM element, if found; otherwise, an empty array. + */ + static getBehaviorsByType(element: Sys.UI.DomElement, type: Sys.UI.Behavior): Behavior[]; + /** + * Gets the Sys.UI.Behavior objects that are associated with the specified HTML Document Object Model (DOM) element. This member is static and can be invoked without creating an instance of the class. + * @param element + * The Sys.UI.DomElement object to search. + * @return An array of references to Behavior objects, or null if no references exist. + */ + static getBehaviors(element: DomElement): Behavior[]; + + /** + * Removes the current Behavior object from the application. + * The dispose method releases all resources from the Sys.UI.Behavior object, unbinds it from its associated HTML Document Object Model (DOM) element, and unregisters it from the application. + */ + dispose(): void; + + //#endregion + + //#region Properties + + /** + * Gets the HTML Document Object Model (DOM) element that the current Sys.UI.Behavior object is associated with. + * @return The DOM element that the current Behavior object is associated with. + */ + get_element(): Sys.UI.DomElement; + /** + * Gets or sets the identifier for the Sys.UI.Behavior object. + * A generated identifier that consists of the ID of the associated Sys.UI.DomElement, the "$" character, and the name value of the Behavior object. + */ + get_id(): string; + /** + * Gets or sets the identifier for the Sys.UI.Behavior object. + * @param value + * The string value to use as the identifier. + */ + set_id(value: string): void; + /* + * Gets or sets the name of the Sys.UI.Behavior object. + * If you do not explicitly set the name property, getting the property value sets it to its default value, which is equal to the type of the Behavior object. The name property remains null until it is accessed. + * @param value + * A string value to use as the name. + */ + set_name(value: string): void; + /** + * Gets or sets the name of the Sys.UI.Behavior object. + */ + get_name(): string; + + //#endregion + + } + /** + * Creates an object that contains a set of integer coordinates representing position, width, and height. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397698(v=vs.100).aspx} + */ + class Bounds { + + //#region Constructors + + /** + * Initializes a new instance of the Sys.UI.Bounds class. + */ + constructor(); + + //#endregion + + //#region Fields + + /** + * Gets the height of an object in pixels. This property is read-only. + * @return A number that represents the height of an object in pixels. + */ + height: number; + /** + * Gets the width of an object in pixels. This property is read-only. + * @return A number that represents the width of an object in pixels. + */ + width: number; + /** + * Gets the x-coordinate of an object in pixels. + * @return A number that represents the x-coordinate of an object in pixels. + */ + x: number; + /** + * Gets the y-coordinate of anobject in pixels. + * @return A number that represents the y-coordinate of an object in pixels. + */ + y: number; + + //#endregion + + } + /** + * Provides the base class for all all ASP.NET AJAX client controls. + */ + class Control extends Sys.Component { + + //#region Constructors + + /** + * When called from a derived class, initializes a new instance of that class. + * The Control constructor is a complete constructor function. However, because the Control class is an abstract base class, the constructor should be called only from derived classes. + * @param element + * The Sys.UI.DomElement object that the control will be associated with. + * + * @throws Error.invalidOperation Function + */ + constructor(element: Sys.UI.DomElement); + + //#endregion + + //#region Methods + + /** + * Adds a CSS class to the HTML Document Object Model (DOM) element that the control is attached to. + * Use the addCssClass method to add a CSS class to a control. If the CSS class has already been added to the control, addCssClass makes no changes to the control. + * @param className + * A string that contains the name of the CSS class to add. + */ + addCssClass(className: string): void; + /** + * Removes the current control from the application. + * The dispose method releases all resources from the Sys.UI.Control object, unbinds it from its associated HTML Document Object Model (DOM) element, and unregisters it from the application. + */ + dispose(): void; + /** + * Initializes the current Sys.UI.Control object. + * The initialize method initializes the control and sets the base Sys.Component.isInitialized property to true. You can override this method to include additional initialization logic for your derived class. + */ + initialize(): void; + /** + * Called when an event is raised by the raiseBubbleEvent method. + * + * The onBubbleEvent method returns false to make sure that unhandled events propagate (bubble) to the parent control. + * In derived classes, you should override the onBubbleEvent method and return true when events are handled to prevent the events from bubbling further. + * For an explanation of bubbling, see Sys.UI.Control raiseBubbleEvent Method. + * + * @param source + * The object that triggered the event. + * @param args + * The event arguments. + * @return + * false in all cases. + */ + onBubbleEvent(source: any, args: any): boolean; + /** + * Calls the onBubbleEvent method of the parent control. + * + * When the raiseBubbleEvent method is called, the source object and args values are sent to the onBubbleEvent handler of the current control. + * If onBubbleEvent returns false, they are sent to the onBubbleEvent handler of the parent control. + * This process continues until an onBubbleEvent event handler returns true, which indicates that the event has been handled. + * Any event that bubbles to the Sys.Application instance without being handled is ignored. + * + * @param source + * The object that triggered the event. + * @param args + * The event arguments. + */ + raiseBubbleEvent(source: any, args: any): void; + /** + * Removes a CSS class from the HTML Document Object Model (DOM) element that the control is attached to. + * Use the removeCssClass method to remove a CSS class from a control. If the CSS class has already been removed from the control, removeCssClass makes no changes to the control. + * + * @param className + * A string that contains the name of the CSS class to remove. + */ + removeCssClass(className: string): void; + /** + * Toggles a CSS class of the HTML Document Object Model (DOM) element that the control is attached to. + * @param className + * A string that contains the name of the CSS class to toggle. + */ + toggleCssClass(className: string): void; + + //#endregion + } + /** + * Defines static methods and properties that provide helper APIs for manipulating and inspecting DOM elements. + * @see {@link http://msdn.microsoft.com/en-us/library/bb383788(v=vs.100).aspx} + */ + interface DomElement { + + //#region Constructors + + /** + * Initializes a new instance of the Sys.UI.DomElement class. + */ + constructor(): void; + + //#endregion + + //#region Methods + + /** + * Adds a CSS class to a DOM element if the class is not already part of the DOM element. This member is static and can be invoked without creating an instance of the class. + * If the element does not support a CSS class, no change is made to the element. + * @param element + * The Sys.UI.DomElement object to add the CSS class to. + * @param className + * The name of the CSS class to add. + */ + addCssClass(element: Sys.UI.DomElement, className: string): void; + /** + * Gets a value that indicates whether the DOM element contains the specified CSS class. This member is static and can be invoked without creating an instance of the class. + * @param element + * The Sys.UI.DomElement object to test for the CSS class. + * @param className + * The name of the CSS class to test for. + * @return + * true if the element contains the specified CSS class; otherwise, false. + */ + containsCssClass(element: Sys.UI.DomElement, className: string): boolean; + /** + * Gets a set of integer coordinates that represent the position, width, and height of a DOM element. This member is static and can be invoked without creating an instance of the class. + * + * @param element + * The Sys.UI.DomElement instance to get the coordinates of. + * @return + * An object of the JavaScript type Object that contains the x-coordinate and y-coordinate of the upper-left corner, the width, and the height of the element in pixels. + */ + getBounds(element: Sys.UI.DomElement): Object; + /** + * @param id + * The ID of the element to find. + * @param element + * (optional) The parent element to search in. The default is the document element. + */ + getElementById(id: string): Sys.UI.DomElement; + getElementById(id: string, element?: Sys.UI.DomElement): Sys.UI.DomElement; + getElementById(id: string, element?: HTMLElement): HTMLElement; + getElementById(id: string, element: any): any; + /** + * Gets the absolute position of a DOM element relative to the upper-left corner of the owner frame or window. This member is static and can be invoked without creating an instance of the class. * + * @param element + * The target element. * + * @return + * An object of the JavaScript type Object that contains the x-coordinate and y-coordinate of the element in pixels. + */ + getLocation(element: Sys.UI.DomElement): Sys.UI.Point; + getLocation(element: any): Object; + /* + * Returns a value that represents the layout characteristics of a DOM element when it is hidden by invoking the Sys.UI.DomElement.setVisible method. This member is static and can be invoked without creating an instance of the class. + * @param element + * The target DOM element. + * @return + * A Sys.UI.VisibilityMode enumeration value that indicates the layout characteristics of element when it is hidden by invoking the setVisible method. + */ + getVisibilityMode(element: Sys.UI.DomElement): Sys.UI.VisibilityMode; + getVisibilityMode(element: any): Sys.UI.VisibilityMode; + /** + * Gets a value that indicates whether a DOM element is currently visible on the Web page. This member is static and can be invoked without creating an instance of the class. + * @param element + * The target DOM element. + * @return + * true if element is visible on the Web page; otherwise, false + */ + getVisible(element: any): boolean; + /** + * Determines whether the specified object is a DOM element. + * @param obj + * An object + * @return + * true if the object is a DOM element; otherwise, false. + */ + isDomElement(obj: any): boolean; + /** + * Raises a bubble event. A bubble event causes an event to be raised and then propagated up the control hierarchy until it is handled. + * @param source + * The DOM element that triggers the event. + * @param args + * The event arguments + */ + raiseBubbleEvent(source: Sys.UI.DomElement, args: EventArgs): void; + raiseBubbleEvent(source: any, args: any): void; + /** + * Removes a CSS class from a DOM element. This member is static and can be invoked without creating an instance of the class. If the element does not include a CSS class, no change is made to the element. + * @param element + * The Sys.UI.DomElement object to remove the CSS class from. + * @param className + * The name of the CSS class to remove. + */ + removeCssClass(element: Sys.UI.DomElement, className: string): void; + removeCssClass(element: HTMLElement, className: string): void; + removeCssClass(element: any, className: string): void; + /** + * Returns the element that has either the specified ID in the specified container, or is the specified element itself. + * The resolveElement method is used to verify that an ID or an object can be resolved as an element. * + * @param elementOrElementId + * The element to resolve, or the ID of the element to resolve. This parameter can be null. + * @param containerElement + * (Optional) The specified container. + * @return + * A DOM element. + */ + resolveElement(elementOrElementId: Sys.UI.DomElement, containerElement?: Sys.UI.DomElement): Sys.UI.DomElement; + resolveElement(elementOrElementId: HTMLElement, containerElement?: HTMLElement): HTMLElement; + resolveElement(elementOrElementId: string): any; + /** + * Sets the position of a DOM element. This member is static and can be invoked without creating an instance of the class. + * he left and top style attributes (upper-left corner) of an element specify the relative position of an element. + * The actual position will depend on the offsetParent property of the target element and the positioning mode of the element. * + * @param element The target element. + * @param x The x-coordinate in pixels. + * @param y The y-coordinate in pixels. + */ + setLocation(element: Sys.UI.DomElement, x: number, y: number): void; + setLocation(element: HTMLElement, x: number, y: number): void; + setLocation(element: any, x: number, y: number): void; + /** + * Sets the layout characteristics of a DOM element when it is hidden by invoking the Sys.UI.DomElement.setVisible method. + * This member is static and can be invoked without creating an instance of the class. + * + * Use the setVisibilityMode method to set the layout characteristics of a DOM element when it is hidden by invoking the Sys.UI.DomElement.setVisible method. + * For example, if value is set to Sys.UI.VisibilityMode.collapse, the element uses no space on the page when the setVisible method is called to hide the element. + * + * @param element + * The target DOM element. + * @param value + * A Sys.UI.VisibilityMode enumeration value. + */ + setVisibilityMode(element: Sys.UI.DomElement, value: Sys.UI.VisibilityMode): void; + /** + * Sets a DOM element to be visible or hidden. This member is static and can be invoked without creating an instance of the class. + * + * Use the setVisible method to set a DOM element as visible or hidden on the Web page. + * If you invoke this method with value set to false for an element whose visibility mode is set to "hide," the element will not be visible. + * However, it will occupy space on the page. If the element's visibility mode is set to "collapse," the element will occupy no space in the page. + * For more information about how to set the layout characteristics of hidden DOM elements, see Sys.UI.DomElement setVisibilityMode Method. + * + * @param element + * The target DOM element. + * @param value + * true to make element visible on the Web page; false to hide element. + */ + setVisible(element: Sys.UI.DomElement, value: boolean): void; + setVisible(element: HTMLElement, value: boolean): void; + setVisible(element: any, value: boolean): void; + /** + * Toggles a CSS class in a DOM element. This member is static and can be invoked without creating an instance of the class. + * Use the toggleCssClass method to hide a CSS class of an element if it is shown, or to show a CSS class of an element if it is hidden. + * + * @param element + * The Sys.UI.DomElement object to toggle. + * @param className + * The name of the CSS class to toggle. + */ + toggleCssClass(element: Sys.UI.DomElement, className: string): void; + toggleCssClass(element: HTMLElement, className: string): void; + toggleCssClass(element: any, className: string): void; + + //#endregion + + } + + var DomElement: Sys.UI.DomElement; + + /** + * Provides cross-browser access to DOM event properties and helper APIs that are used to attach handlers to DOM element events. + * @see {@link http://msdn.microsoft.com/en-us/library/bb310935(v=vs.100).aspx} + */ + class DomEvent { + + //#region Constructors + + /** + * Initializes a new instance of the Sys.UI.DomEvent class and associates it with the specified DomElement object. + * @param domElement + * The DomElement object to associate with the event. + */ + constructor(domElement: DomElement); + constructor(domElement: any); + + //#endregion + + //#region Methods + + /** + * Provides a method to add a DOM event handler to the DOM element that exposes the event. This member is static and can be invoked without creating an instance of the class. + * Use the addHandler method to add a DOM event handler to the element that exposes the event. The eventName parameter should not include the "on" prefix. For example, specify "click" instead of "onclick". + * This method can be accessed through the $addHandler shortcut method. + * + * @param element + * The element that exposes the event. + * @param eventName + * The name of the event. + * @param handler + * The client function that is called when the event occurs. + * @param autoRemove + * (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. + */ + static addHandler(element: any, eventName: string, handler: Function, autoRemove?: boolean): void; + /** + * Adds a list of DOM event handlers to the DOM element that exposes the events. This member is static and can be invoked without creating an instance of the class. + * Use the addHandlers method to add a list of DOM event handlers to the element that exposes the event. + * The events parameter takes a comma-separated list of name/value pairs in the format name:value, where name is the name of the DOM event and value is the name of the handler function. + * If there is more than one name/value pair, the list must be enclosed in braces ({}) to identify it as a single parameter. Multiple name/value pairs are separated with commas. + * Event names should not include the "on" prefix. For example, specify "click" instead of "onclick". + * If handlerOwner is specified, delegates are created for each handler. These delegates are attached to the specified object instance, and the this pointer from the delegate handler will refer to the handlerOwner object. + * This method can be accessed through the $addHandlers shortcut method. + * + * @param element + * The DOM element that exposes the events. + * @param events + * A dictionary of event handlers. + * @param handlerOwner + * (Optional) The object instance that is the context for the delegates that should be created from the handlers. + * @param autoRemove + * (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. + * + * @throws Error.invalidOperation - (Debug) One of the handlers specified in events is not a function. + * + */ + static addHandlers(element: any, events: any, handlerOwner?: any, autoRemove?: boolean): void; + /** + * Removes all DOM event handlers from a DOM element that were added through the Sys.UI.DomEvent addHandler or the Sys.UI.DomEvent addHandlers methods. + * This member is static and can be invoked without creating an instance of the class. + * This method can be accessed through the $clearHandlers shortcut method. + * + * @param element + * The element that exposes the events. + */ + static clearHandlers(element: any): void; + /** + * Removes a DOM event handler from the DOM element that exposes the event. This member is static and can be invoked without creating an instance of the class. + * + * @param element + * The element that exposes the event. + * @param eventName + * The name of the event. + * @param handler + * The event handler to remove. + */ + static removeHandler(element: any, eventName: string, handler: Function): void; + /** + * Prevents the default DOM event action from happening. + * Use the preventDefault method to prevent the default event action for the browser from occurring. + * For example, if you prevent the keydown event of an input element from occurring, the character typed by the user is not automatically appended to the input element's value. + */ + preventDefault(): void; + /** + * Prevents an event from being propagated (bubbled) to parent elements. + * By default, event notification is bubbled from a child object to parent objects until it reaches the document object. + * The event notification stops if the event is handled during the propagation process. + * Use the stopPropagation method to prevent an event from being propagated to parent elements. + */ + stopPropagation(): void; + + //#endregion + + //#region Fields + + /** + * Gets a Boolean value that indicates the state of the ALT key when the associated event occurred. + * Use the altKey field to determine whether the ALT key is pressed when the event occurred. + * + * @return true if the ALT key was pressed when the event occurred; otherwise, false. + */ + altKey: boolean; + /** + * Gets a Sys.UI.MouseButton enumeration value that indicates the button state of the mouse when the related event occurred. + * Use the button field to determine which mouse button was pressed when the related event occurred. + * @return A MouseButton value + */ + button: Sys.UI.MouseButton; + /** + * Gets the character code of the key that raised the associated keyPress event. + * Use the charCode field to get the character code of a pressed key or key combination that raised a keyPress event. + * The keyPress event provides a single character code that identifies key combinations. + * The keyPress event is not raised for single modifier keys such as ALT, CTRL, and SHIFT. + * + * @return An integer value that represents the character code of the key or key combination that was pressed to raise the keyPress event. + */ + charCode: number; + /** + * Gets the x-coordinate of the mouse pointer's position relative to the client area of the browser window, excluding window scroll bars. + * @return An integer that represents the x-coordinate in pixels. + */ + clientX: number; + /** + * Gets the y-coordinate of the mouse pointer's position relative to the client area of the browser window, excluding window scroll bars. + * @return An integer that represents the y-coordinate in pixels. + */ + clientY: number; + /** + * Gets a Boolean value that indicates the state of the CTRL key when the associated event occurred. + * @return true if the CTRL key was pressed when the event occurred; otherwise, false. + */ + ctrlKey: boolean; + /** + * Gets the key code of the key that raised the keyUp or keyDown event. + * @return An integer value that represents the key code of the key that was pressed to raise the keyUp or keyDown event. + */ + keyCode: number; + /** + * Gets the x-coordinate of the mouse pointer's position relative to the object that raised the event. + * @return An integer that represents the x-coordinate in pixels. + */ + offsetX: number; + /** + * Gets the y-coordinate of the mouse pointer's position relative to the object that raised the event. + * @return An integer that represents the y-coordinate in pixels. + */ + offsetY: number; + /** + * Gets the x-coordinate of the mouse pointer's position relative to the user's screen. + * @return An integer that represents the x-coordinate in pixels. + */ + screenX: number; + /** + * Gets the y-coordinate of the mouse pointer's position relative to the user's screen. + * @return An integer that represents the y-coordinate in pixels. + */ + screenY: number; + /** + * Gets a Boolean value that indicates the state of the SHIFT key when the associated event occurred. + * @return true if the SHIFT key was pressed when the event occurred; otherwise, false. + */ + shiftKey: boolean; + /** + * Gets the object that the event acted on. + * @return An object that represents the target that the event acted on. + */ + target: any; + /** + * Gets the name of the event that was raised. + * @return A string that represents the name of the event that was raised. + */ + type: string; + + //#endregion + } + /** + * Describes key codes. + * The values correspond to values in the Document Object Model (DOM). + */ + enum Key { + /** + * Represents the BACKSPACE key. + */ + backspace, + /* + * Represents the TAB key. + */ + tab, + /** + * Represents the ENTER key. + */ + enter, + /** + * Represents the ESC key. + */ + esc, + /* + * Represents the SPACEBAR key. + */ + space, + /** + * Represents the PAGE UP key. + */ + pageUp, + /** + * Represents the PAGE DOWN key. + */ + pageDown, + /** + * Represents the END key. + */ + end, + /** + * Represents the HOME key. + */ + home, + /** + * Represents the LEFT ARROW key. + */ + left, + /** + * Represents the UP ARROW key. + */ + up, + /** + * Represents the RIGHT ARROW key. + */ + right, + /** + * Represents the DOWN ARROW key. + */ + down, + /** + * Represents DELETE key. + */ + del + } + /** + * Describes mouse button locations. + */ + enum MouseButton { + // todo + } + /** + * Creates an object that contains a set of integer coordinates that represent a position. The getLocation method of the Sys.UI.DomElement class returns a Point object. + * @see {@link http://msdn.microsoft.com/en-us/library/bb383992(v=vs.100).aspx} * + */ + class Point { + + //#region Constructors + + /** + * Creates an object that contains a set of integer coordinates that represent a position. + * @param x The number of pixels between the location and the left edge of the parent frame. + * @param y The number of pixels between the location and the top edge of the parent frame. + */ + constructor(x: number, y: number); + + //#endregion + + //#region Fields + + /** + * Gets the x-coordinate of a Sys.UI.Point object in pixels. This property is read-only. + * @return A number that represents the x-coordinate of the Point object in pixels. + */ + x: number; + + /** + * Gets the y-coordinate of a Sys.UI.Point object in pixels. This property is read-only. + * @return A number that represents the y-coordinate of the Point object in pixels. + */ + y: number; + + //#endregion + + } + /** + * Describes the layout of a DOM element in the page when the element's visible property is set to false. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397498(v=vs.100).aspx} + */ + enum VisibilityMode { + /** + * The element is not visible, but it occupies space on the page. + */ + hide, + /** + * The element is not visible, and the space it occupies is collapsed. + */ + collapse + } + } + + //#endregion + + //#region Sys.WebForms Namespace + + /** + * The Sys.WebForms namespace contains classes related to partial-page rendering in the Microsoft Ajax Library. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397566(v=vs.100).aspx} + */ + module WebForms { + + /** + * Used by the beginRequest event of the PageRequestManager class to pass argument information to event handlers. + * @see {@link http://msdn.microsoft.com/en-us/library/bb384003(v=vs.100).aspx} + */ + class BeginRequestEventArgs extends EventArgs { + + //#region Constructors + + /** + * Initializes a new instance of the BeginRequestEventArgs class. + * @param request + * A Sys.Net.WebRequest representing the web request for the EventArgs. + * @param postBackElement + * The postback element that initiated the async postback. + * @param updatePanelsToUpdate + * (Optional) A list of UniqueIDs for UpdatePanel controls that are requested to update their rendering by the client. Server-side processing may update additional UpdatePanels. + */ + constructor(request: Sys.Net.WebRequest, postBackElement: any, updatePanelsToUpdate: string[]); + + //#endregion + + //#region Properties + + /** + * Gets the postback element that initiated the asynchronous postback. This property is read-only. + * @readonly + * @return An HTML DOM element. + */ + get_postBackElement(): HTMLElement; + /** + * Gets the request object that represents the current postback. + * @return An instance of the Sys.Net.WebRequest class. + */ + get_request(): Sys.Net.WebRequest; + /** + * Gets a list of UniqueID values for UpdatePanel controls that should re-render their content, as requested by the client. + * Server-side processing might update additional UpdatePanel controls. + * @return An array of UniqueID values for UpdatePanel controls. + */ + get_updatePanelsToUpdate(): string[]; + + //#endregion + } + + /** + * Used by the endRequest event of the PageRequestManager class to pass argument information to event handlers. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397499.aspx} + */ + class EndRequestEventArgs extends EventArgs { + + //#region Constructors + + /** + * Initializes a new instance of the EndRequestEventArgs class. + * @param error + * An error object. + * @param dataItems + * An object containing data items. + * @param response + * An object of type Sys.Net.WebRequestExecutor. + */ + constructor(error: Error, dataItems: any, response: Sys.Net.WebRequestExecutor); + + //#endregion + + //#region Properties + + /** + * Gets a JSON data structure that contains data items that were registered by using the RegisterDataItem method of the ScriptManager class. + * The JavaScript Error object exposes several properties that define the error. The Microsoft Ajax Library provides additional functions for the Error object. + * @return A JSON data structure that contains name/value pairs that were registered as data items by using the RegisterDataItem method of the ScriptManager class. + */ + get_dataItems(): any; + /** + * Gets the Error object. + * @return A base ECMAScript (JavaScript) Error object. + */ + get_error(): Error; + /** + * Get or sets a value that indicates whether the error has been handled. + * Use this property to determine whether an asynchronous postback error has already been handled. If it has not and if you want to take action on the error, you can set the error as handled. + * @return true if the error has been handled; otherwise false. + */ + get_errorHandled(): boolean; + /** + * Get or sets a value that indicates whether the error has been handled. + * Use this property to determine whether an asynchronous postback error has already been handled. If it has not and if you want to take action on the error, you can set the error as handled. + * @param value + * true or false. + */ + set_errorHandled(value: boolean): void; + /** + * Gets a response object that is represented by the Sys.Net.WebRequestExecutor class. + * @return A response object that is represented by the WebRequestExecutor class. + */ + get_response(): Sys.Net.WebRequestExecutor; + + //#endregion + } + + /** + * Used by the initializeRequest event of the PageRequestManager class to pass argument information to event handlers. + * This class contains private members that support the client-script infrastructure and are not intended to be used directly from your code. Names of private members begin with an underscore ( _ ). + * @see {@link http://msdn.microsoft.com/en-us/library/bb311030(v=vs.100).aspx} + */ + class InitializeRequestEventArgs extends EventArgs { + + //#region Constructors + + /** + * Initializes a new instance of the EndRequestEventArgs class. + * @param request + * A Sys.Net.WebRequest object that represents the Web request for the EventArgs object. + * @param datapostBackElementItems + * The postback element that initiated the asynchronous postback. + * @param updatePanelsToUpdate + * (Optional) A list of UniqueID values for UpdatePanel controls that are being requested to update their rendering by the client. Server-side processing might update additional UpdatePanel controls. + */ + constructor(request: Sys.Net.WebRequest, postBackElement: any, updatePanelsToUpdate: string[]); + + //#endregion + + //#region Properties + + /** + * Gets the postback element that initiated the asynchronous postback. + * @return An HTML DOM element. + */ + get_postBackElement(): HTMLElement; + + /** + * Gets the request object that represents the current postback. + * @return A request object that is represented by the Sys.Net.WebRequestExecutor class. + */ + get_request(): Sys.Net.WebRequestExecutor; + + /** + * Gets or sets a list of UniqueID values for UpdatePanel controls that should re-render their content, as requested by the client. + * The returned array can be modified by a client event handler to add or remove UpdatePanel controls that should re-render their content dynamically. Server processing can also modify the array. + * @return An array of UniqueID values for UpdatePanel controls. + */ + get_updatePanelsToUpdate(): string[]; + + //#endregion + + } + + /** + * Used by the pageLoaded event of the PageRequestManager class to send event data that represents the UpdatePanel controls that were updated and created in the most recent postback. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397476(v=vs.100).aspx} + */ + class PageLoadedEventArgs extends EventArgs { + + //#region Constructors + + /** + * Initializes a new instance of the PageLoadedEventArgs class. + */ + constructor(); + + //#endregion + + //#region Properties + + /** + * Gets a JSON data structure that contains data items that were registered by using the RegisterDataItem method of the ScriptManager class. + * A page or control must be in partial-page rendering mode to register data items that use the RegisterDataItem method of the ScriptManager class + * Use the IsInAsyncPostBack property to check whether the page is in partial-page rendering mode.The dataItems property returns a JSON data structure that contains name/value pairs. + * The name is the unique ID of the control that is used in the control parameter of the RegisterDataItem method. The value is the dataItem parameter of the RegisterDataItem method. + * + * @return A JSON data structure that contains name/value pairs that were registered as data items that use the RegisterDataItem method of the ScriptManager class. + */ + get_dataItems(): any; + /** + * Gets an array of HTML div elements that represent UpdatePanel controls that were created when the DOM was updated during the last asynchronous postback. + * If an UpdatePanel control is updated as a result of a partial-page update, the array referenced in the panelsCreated property of the PageLoadedEventArgs class contains a reference to the corresponding div element. + * The pageLoaded event of the Sys.WebForms.PageRequestManager class uses a PageLoadedEventArgs object to return its event data. + * @return An array of div elements that were created during the DOM manipulation that was caused by the last asynchronous postback. If no elements were created, the property returns null. + */ + get_panelsCreated(): HTMLDivElement[]; + /** + * Gets an array of HTML
    elements that represent UpdatePanel controls that were updated when the DOM was updated during the last asynchronous postback. + * If an UpdatePanel control is updated as a result of a partial-page update, the array referenced in the panelsUpdated property of the PageLoadedEventArgs class contains a reference to the corresponding
    element. + * The pageLoaded event of the Sys.WebForms.PageRequestManager class uses a PageLoadedEventArgs object to return its event data. + * @return An array of
    elements that were updated during the DOM manipulation that was the result of the last asynchronous postback. If no elements were created, the property returns null. + */ + get_panelsUpdated(): HTMLDivElement[]; + + //#endregion + } + + /** + * Used by the pageLoading event of the PageRequestManager class to send event data that represents the UpdatePanel controls that are being updated and deleted as a result of the most recent postback. + * @see {@link http://msdn.microsoft.com/en-us/library/bb310960(v=vs.100).aspx} + */ + class PageLoadingEventArgs extends EventArgs { + + //#region Constructors + + /** + * Initializes a new instance of the PageLoadingEventArgs class. + */ + constructor(); + + //#endregion + + //#region Properties + + /** + * Gets a JSON data structure that contains data items that were registered by using the RegisterDataItem method of the ScriptManager class. + * page or control must be in partial-page rendering mode to register data items that use the RegisterDataItem method of the ScriptManager class. + * Use the IsInAsyncPostBack property to check whether the page is in partial-page rendering mode. + * The dataItems property returns a JSON data structure that contains name/value pairs. + * The name is the unique ID of the control that is used in the control parameter of the RegisterDataItem method. The value is the dataItem parameter of the RegisterDataItem method. + * @return A JSON data structure that contains name/value pairs that were registered as data items by using the RegisterDataItem method of the ScriptManager class. + */ + get_dataItems(): any; + /** + * Gets an array of HTML
    elements that represent UpdatePanel controls that will be deleted from the DOM as a result of the current asynchronous postback. + * If the contents of an UpdatePanel control will be deleted as the result of a partial-page update, the array that is referenced in the panelsDeleting property of the PageLoadingEventArgs class contains a reference to the corresponding
    element. + * The pageLoading event of the Sys.WebForms.PageRequestManager class uses a PageLoadingEventArgs object to return its event data. + * @return An array of
    elements that will be deleted from the DOM. If no elements will be deleted, the property returns null. + */ + get_panelsDeleting(): HTMLDivElement[]; + /** + * Gets an array of HTML
    elements that represent UpdatePanel controls that will be updated in the DOM as a result of the current asynchronous postback. + * If the contents of any UpdatePanel controls will be updated as the result of a partial-page update, the panelsUpdating property contains an array that references the corresponding
    elements. + * The pageLoading event of the Sys.WebForms.PageRequestManager class uses a PageLoadingEventArgs object to return its event data. + * @return An array of
    elements that will be updated in the DOM. If no elements will be updated, the property returns null. + */ + get_panelsUpdating(): HTMLDivElement[]; + + //#endregion + + } + + /** + * Manages client partial-page updates of server UpdatePanel controls. In addition, defines properties, events, and methods that can be used to customize a Web page with client script. + * @see {@link http://msdn.microsoft.com/en-us/library/bb311028(v=vs.100).aspx} + */ + class PageRequestManager { + + //#region Constructors + + /** + * Initializes a new instance of the Sys.WebForms.PageRequestManager Class. + */ + constructor(); + + //#endregion + + //#region Events + + /** + * Raised before the processing of an asynchronous postback starts and the postback request is sent to the server. + * @param beginRequestHandler + * The name of the handler method that will be called. + */ + add_beginRequest(beginRequestHandler: (sender: any, args: BeginRequestEventArgs) => void): void; + /** + * Raised before the processing of an asynchronous postback starts and the postback request is sent to the server. + * @param beginRequestHandler + * The handler method that will be removed. + */ + remove_beginRequest(beginRequestHandler: Function): void; + /** + * Raised after an asynchronous postback is finished and control has been returned to the browser. + * @param endRequestHandler + * The name of the handler method that will be called. + */ + add_endRequest(endRequestHandler: (sender: any, args: Sys.WebForms.EndRequestEventArgs) => void): void; + /** + * Raised after an asynchronous postback is finished and control has been returned to the browser. + * @param endRequestHandler + * The name of the handler method that will be removed. + */ + remove_endRequest(endRequestHandler: (sender: any, args: Sys.WebForms.EndRequestEventArgs) => void): void; + /** + * Raised during the initialization of the asynchronous postback. + * @param initializeRequestHandler + * The name of the handler method that will be called. + */ + add_initializeRequest(initializeRequestHandler: (sender: any, args: InitializeRequestEventArgs) => void): void; + /** + * Raised during the initialization of the asynchronous postback. + * @param initializeRequestHandler + * The name of the handler method that will be called. + */ + remove_initializeRequest(initializeRequestHandler: (sender: any, args: InitializeRequestEventArgs) => void): void; + /** + * Raised after all content on the page is refreshed as a result of either a synchronous or an asynchronous postback. + * @param pageLoadedHandler + * The name of the handler method that will be called. + */ + add_pageLoaded(pageLoadedHandler: (sender: any, args: PageLoadedEventArgs) => void): void; + /** + * Raised after all content on the page is refreshed as a result of either a synchronous or an asynchronous postback. + * @param pageLoadedHandler + * The name of the handler method that will be called. + */ + remove_pageLoaded(pageLoadedHandler: (sender: any, args: PageLoadedEventArgs) => void): void; + /** + * Raised after the response from the server to an asynchronous postback is received but before any content on the page is updated. + * @param pageLoadedHandler + * The name of the handler method that will be called. + */ + add_pageLoading(pageLoadingHandler: (sender: any, args: PageLoadingEventArgs) => void): void; + /** + * Raised after the response from the server to an asynchronous postback is received but before any content on the page is updated. + * @param pageLoadedHandler + * The name of the handler method that will be called. + */ + remove_pageLoading(pageLoadingHandler: (sender: any, args: PageLoadingEventArgs) => void): void; + + //#endregion + + //#region Methods + + /** + * Returns the instance of the PageRequestManager class for the page. + * @return The current instance of the PageRequestManager class. You do not create a new instance of the PageRequestManager class directly. Instead, an instance is available when partial-page rendering is enabled. + */ + static getInstance(): PageRequestManager; + + /** + * Stops all updates that would occur as a result of an asynchronous postback. + * The abortPostBack method stops the currently executing postback. To cancel a new postback, provide an event handler for the initializeRequest event and use the cancel event of the Sys.CancelEventArgs class. + */ + abortPostBack(): void; + + /** + * Begins an asynchronous postback. + * @param updatePanelsToUpdate + * (Optional) An array of UniqueID values or ClientID values for UpdatePanel controls that must be re-rendered. + * @param eventTarget + * (Optional) A string that contains the target of the event. + * @param eventArgument + * (Optional) A string that contains an argument for the event. + * @param causesValidation + * (Optional) true to cause validation. + * @param validationGroup + * (Optional) A string that contains the name of the validation group. + */ + beginAsyncPostBack(updatePanelsToUpdate?: string[], eventTarget?: string, eventArgument?: string, causesValidation?: boolean, validationGroup?: string): void; + + /** + * Releases ECMAScript (JavaScript) resources and detaches events. + * the dispose method to free client resources. The PageRequestManager instance calls the dispose method during the window.unload event of the browser. + * If you call the dispose method and then reference members of the PageRequestManager class, an error occurs. In typical page developer scenarios, you do not have to call the dispose method. + */ + dispose(): void; + + //#endregion + + //#region Properties + + get_isInAsyncPostBack(): boolean; + + //#endregion + } + + //#region Exceptions: Defines exceptions that can occur during partial-page updates. + + /** + * Raised when an error occurs while processing the response from the server. + * If the response to an asynchronous postback returns without an error but there is an error processing the response in the client, the Sys.WebForms.PageRequestManagerParserErrorException is raised. + * For information about how to handle this error condition, see Debugging and Tracing Ajax Applications Overview. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397466(v=vs.100).aspx} + */ + class PageRequestManagerParserErrorException { + // Nothing to define + } + + /** + * Raised when an error occurs on the server. + * If an error occurs on the server while the request is being processed, an error response is returned to the browser and the Sys.WebForms.PageRequestManagerServerErrorException exception is raised. + * To customize error handling and to display more information about the server error, handle the AsyncPostBackError event and use the AsyncPostBackErrorMessage and AllowCustomErrorsRedirect properties. + * For an example of how to provide custom error handling during partial-page updates, see Customizing Error Handling for ASP.NET UpdatePanel Controls. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397466(v=vs.100).aspx} * + */ + class PageRequestManagerServerErrorException { + // Nothing to define + } + + /** + * Raised when the request times out. + * A partial-page update is initiated by a client request (an asynchronous postback) to the server. The server processes the request and returns a response to the client. + * If the browser does not receive a response in a specified time, the Sys.WebForms.PageRequestManagerTimeoutException is raised. + * To change the interval that elapses before asynchronous postbacks time out, set the AsyncPostBackTimeout property of the ScriptManager control. + * @see {@link http://msdn.microsoft.com/en-us/library/bb397466(v=vs.100).aspx} + */ + class PageRequestManagerTimeoutException { + // Nothing to define + } + + //#endregion + + } + + //#endregion + +} + +//#endregion diff --git a/microsoft-live-connect/microsoft-live-connect.d.ts b/microsoft-live-connect/microsoft-live-connect.d.ts index 04ff3ef79b..d012f3195c 100644 --- a/microsoft-live-connect/microsoft-live-connect.d.ts +++ b/microsoft-live-connect/microsoft-live-connect.d.ts @@ -1,9 +1,11 @@ -/// -// Type definitions for Microsoft Live Connect v5.0. +// Type definitions for Microsoft Live Connect v5.0 // Project: http://msdn.microsoft.com/en-us/library/live/hh243643.aspx // Definitions by: John Vilk // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// +/// + declare module Microsoft.Live { //#region REST Object Information @@ -632,8 +634,8 @@ declare module Microsoft.Live { /** * A value that specifies whether the event is publicly visible. Valid * values are: - * - public—the event is visible to anyone who can view the calendar. - * - private"—the event is visible only to the event owner. + * - public�the event is visible to anyone who can view the calendar. + * - private"�the event is visible only to the event owner. * @default "public" */ visibility: string; @@ -694,8 +696,8 @@ declare module Microsoft.Live { /** * A value that specifies whether the event is publicly visible. Valid * values are: - * - public—the event is visible to anyone who can view the calendar. - * - private"—the event is visible only to the event owner. + * - public�the event is visible to anyone who can view the calendar. + * - private"�the event is visible only to the event owner. * @default "public" */ visibility?: string; @@ -766,8 +768,8 @@ declare module Microsoft.Live { /** * A value that specifies whether the event is publicly visible. Valid * values are: - * - public—the event is visible to anyone who can view the calendar. - * - private"—the event is visible only to the event owner. + * - public�the event is visible to anyone who can view the calendar. + * - private"�the event is visible only to the event owner. * @default "public" */ visibility: string; @@ -1040,10 +1042,10 @@ declare module Microsoft.Live { source: string; /** * The type of this image of this particular size. Valid values are: - * full (maximum size: 2048 × 2048 pixels) - * - normal (maximum size 800 × 800 pixels) - * - album (maximum size 176 × 176 pixels) - * - small (maximum size 96 × 96 pixels) + * full (maximum size: 2048 � 2048 pixels) + * - normal (maximum size 800 � 800 pixels) + * - album (maximum size 176 � 176 pixels) + * - small (maximum size 96 � 96 pixels) */ type: string; } diff --git a/mime/mime-tests.ts b/mime/mime-tests.ts new file mode 100644 index 0000000000..36f0e5c15d --- /dev/null +++ b/mime/mime-tests.ts @@ -0,0 +1,13 @@ +/// + +import mime = require('mime'); + +var str: string; +var obj: Object; + +str = mime.lookup(str); +str = mime.extension(str); +mime.load(str); +mime.define(obj); + +str = mime.charsets.lookup(str); diff --git a/mime/mime.d.ts b/mime/mime.d.ts new file mode 100644 index 0000000000..bfaa7a51f1 --- /dev/null +++ b/mime/mime.d.ts @@ -0,0 +1,19 @@ +// Type definitions for mime +// Project: https://github.com/broofa/node-mime +// Definitions by: Jeff Goddard +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/mime.d.ts + +declare module "mime" { + export function lookup(path: string): string; + export function extension(mime: string): string; + export function load(filepath: string): void; + export function define(mimes: Object): void; + + interface Charsets { + lookup(mime: string): string; + } + + export var charsets: Charsets; +} diff --git a/minimatch/minimatch-tests.ts b/minimatch/minimatch-tests.ts index b50471826c..a4892ef35e 100644 --- a/minimatch/minimatch-tests.ts +++ b/minimatch/minimatch-tests.ts @@ -9,5 +9,7 @@ var options = { var m = new mm.Minimatch(pattern, options); var r = m.makeRe(); -var f = "test.ts"; +var f = ["test.ts"]; mm.match(f, pattern, options); + +mm.filter('foo')('bar'); diff --git a/minimatch/minimatch.d.ts b/minimatch/minimatch.d.ts index 588e93535a..e83d976a89 100644 --- a/minimatch/minimatch.d.ts +++ b/minimatch/minimatch.d.ts @@ -8,7 +8,8 @@ declare module "minimatch" { function M(target:string, pattern:string, options?:M.IOptions):void; module M { - function match(filename:string, pattern:string, options:IOptions):boolean; + function match(filenames:string[], pattern:string, options?:IOptions):string[]; + function filter(pattern:string, options?:IOptions): (target: string) => boolean; var Minimatch:IMinimatchStatic; @@ -27,7 +28,7 @@ declare module "minimatch" { } interface IMinimatchStatic { - new (pattern:string, options:IOptions):IMinimatch; + new (pattern:string, options?:IOptions):IMinimatch; } interface IMinimatch { @@ -36,11 +37,11 @@ declare module "minimatch" { parseNegate():void; braceExpand(pattern:string, options:IOptions):void; parse(pattern:string, isSub?:boolean):void; - makeRe():any; // regexp or boolean - match(file:string, pattern:string, options:IOptions):boolean; - matchOne(file:string, pattern:string, partial:any):boolean; + makeRe():RegExp; // regexp or boolean + match(file:string):boolean; + matchOne(files:string[], pattern:string[], partial:any):boolean; } } - export = M; +export = M; } diff --git a/mixpanel/mixpanel-tests.ts b/mixpanel/mixpanel-tests.ts new file mode 100644 index 0000000000..a9cf296c3e --- /dev/null +++ b/mixpanel/mixpanel-tests.ts @@ -0,0 +1,70 @@ +/// +function mixpanel_base() +{ + mixpanel.init("new token", { your: "config" }, "library_name"); + + mixpanel.push(['register', { a: 'b' }]); + + mixpanel.disable(['my_event']); + + mixpanel.track("Registered", {"Gender": "Male", "Age": 21}); + + mixpanel.track_links("#nav", "Clicked Nav Link"); + + mixpanel.track_forms("#register", "Created Account"); + + mixpanel.register({device: 'android', version: '4.0.1'}); + + mixpanel.register_once({device: 'android', version: '4.0.1'}); + + mixpanel.unregister('device'); + + mixpanel.identify('234234sdfdsf'); + + mixpanel.get_distinct_id(); + + mixpanel.alias('w3erwfsdf', '234234sdfdsf'); + + mixpanel.set_config({test: true}); + + mixpanel.get_config(); + + mixpanel.get_property('device'); +} + +function mixpanel_people() +{ + mixpanel.people.set('gender', 'm'); + mixpanel.people.set({ + 'Company': 'Acme', + 'Plan': 'Premium', + 'Upgrade date': new Date() + }); + + mixpanel.people.set_once('First Login Date', new Date()); + mixpanel.people.set_once({ + 'First Login Date': new Date(), + 'Starting Plan': 'Premium' + }); + + mixpanel.people.increment('page_views', 1); + mixpanel.people.increment('page_views'); + mixpanel.people.increment('credits_left', -1); + mixpanel.people.increment({ + counter1: 1, + counter2: 1 + }); + + mixpanel.people.append('pages_visited', 'homepage'); + mixpanel.people.append({ + list1: 'bob', + list2: 123 + }); + + mixpanel.people.track_charge(50); + mixpanel.people.track_charge(30.50, {'$time': new Date('jan 1 2012')}); + + mixpanel.people.clear_charges(); + + mixpanel.people.delete_user(); +} diff --git a/mixpanel/mixpanel.d.ts b/mixpanel/mixpanel.d.ts new file mode 100644 index 0000000000..03596a8aaf --- /dev/null +++ b/mixpanel/mixpanel.d.ts @@ -0,0 +1,72 @@ +// Type definitions for Mixpanel +// Project: https://mixpanel.com/ +// https://github.com/mixpanel/mixpanel-js +// Definitions by: Knut Eirik Leira Hjelle +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface Mixpanel +{ + people:Mixpanel.People; + + init(token:string, config:{[index:string]:any}, libraryName:string):Mixpanel; + + push(item:any[]):void; + + disable(events?:string[]):void; + + track(eventName:string, params?:{[index:string]:any}, callback?:() => void):void; + + track_links(querySelector:string, eventName:string, params?:{[index:string]:any}):void; + + track_forms(querySelector:string, eventName:string, params?:{[index:string]:any}):void; + + register(params:{[index:string]:any}, days?:number):void; + + register_once(params:{[index:string]:any}, defaultValue?:string, days?:number):void; + + unregister(propertyName:string):void; + + identify(id:string):void; + + get_distinct_id():string; + + alias(alias:string, currentId?:string):void; + + set_config(config:{[index:string]:any}):void; + + get_config():{[index:string]:any}; + + get_property(propertyName:string):any; +} + +declare module Mixpanel +{ + interface People + { + set(keys:{[index:string]:any}, callback?:() => void):void; + + set(key:string, value:any, callback?:() => void):void; + + set_once(keys:{[index:string]:any}, callback?:() => void):void; + + set_once(key:string, value:any, callback?:() => void):void; + + increment(key:string):void; + + increment(keys:{[index:string]:number}):void; + + increment(key:string, value:number):void; + + append(keys:{[index:string]:any}):void; + + append(key:string, value:any):void; + + track_charge(amount:number, params?:{[index:string]:any}, callback?:() => void):void; + + clear_charges():void; + + delete_user():void; + } +} + +declare var mixpanel:Mixpanel; diff --git a/mocha/mocha-tests.ts b/mocha/mocha-tests.ts index 597d9cbe2c..672fac1cb0 100644 --- a/mocha/mocha-tests.ts +++ b/mocha/mocha-tests.ts @@ -12,6 +12,18 @@ function test_describe() { }); } +function test_context() { + context('some context', () => { }); + + context.only('some context', () => { }); + + context.skip('some context', () => { }); + + context('some context', function() { + this.timeout(2000); + }); +} + function test_it() { it('does something', () => { }); diff --git a/mocha/mocha.d.ts b/mocha/mocha.d.ts index 9b55761c6f..64255a7ba1 100644 --- a/mocha/mocha.d.ts +++ b/mocha/mocha.d.ts @@ -1,7 +1,7 @@ // Type definitions for mocha 1.17.1 // Project: http://visionmedia.github.io/mocha/ -// Definitions by: Kazi Manzur Rashid -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: Kazi Manzur Rashid , otiai10 +// Definitions: https://github.com/borisyankov/DefinitelyTyped interface Mocha { // Setup mocha with the given setting options. @@ -59,6 +59,14 @@ declare var describe : { timeout(ms: number): void; } +// alias for `describe` +declare var context : { + (contextTitle: string, spec: () => void): void; + only(contextTitle: string, spec: () => void): void; + skip(contextTitle: string, spec: () => void): void; + timeout(ms: number): void; +} + declare var it: { (expectation: string, assertion?: () => void): void; (expectation: string, assertion?: (done: MochaDone) => void): void; diff --git a/modernizr/modernizr.d.ts b/modernizr/modernizr.d.ts index 686f40e718..5827bbf9eb 100644 --- a/modernizr/modernizr.d.ts +++ b/modernizr/modernizr.d.ts @@ -1,6 +1,6 @@ // Type definitions for Modernizr 2.6.2 // Project: http://modernizr.com/ -// Definitions by: Boris Yankov and Theodore Brown +// Definitions by: Boris Yankov , Theodore Brown // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/moment/moment-external-tests.ts b/moment/moment-external-tests.ts index 9c61168921..2fbdbb6e71 100644 --- a/moment/moment-external-tests.ts +++ b/moment/moment-external-tests.ts @@ -210,6 +210,12 @@ moment.duration(500).asSeconds(); moment.duration().minutes(); moment.duration().asMinutes(); +var adur = moment.duration(3, 'd'); +var bdur = moment.duration(2, 'd'); +adur.subtract(bdur).days(); +adur.subtract(1).days(); +adur.subtract(1, 'd').days(); + // Defining a custom language: moment.lang('en', { months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], diff --git a/moment/moment-tests.ts b/moment/moment-tests.ts index 68a718a33d..d0dd0bda2b 100644 --- a/moment/moment-tests.ts +++ b/moment/moment-tests.ts @@ -78,6 +78,13 @@ m2.add('hours', 24).hours(); var duration = moment.duration({'days': 1}); moment([2012, 0, 31]).add(duration); +moment().add('seconds', 1); +moment().add('seconds', '1'); +moment().add(1, 'seconds'); + +moment().add('1', 'seconds'); +moment().add('seconds', '1'); + moment().subtract('days', 7); moment().seconds(30); @@ -208,6 +215,12 @@ moment.duration(500).asSeconds(); moment.duration().minutes(); moment.duration().asMinutes(); +var adur = moment.duration(3, 'd'); +var bdur = moment.duration(2, 'd'); +adur.subtract(bdur).days(); +adur.subtract(1).days(); +adur.subtract(1, 'd').days(); + // Defining a custom language: moment.lang('en', { months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], diff --git a/moment/moment.d.ts b/moment/moment.d.ts index cfc19100bf..f14c7d4beb 100644 --- a/moment/moment.d.ts +++ b/moment/moment.d.ts @@ -1,9 +1,7 @@ // Type definitions for Moment.js 2.5.0 // Project: https://github.com/timrwood/moment -// Definitions by: Michael Lakerveld -// Definitions by: Aaron King (2.4.0) -// Definitions by: Hiroki Horiuchi (2.5.0) -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: Michael Lakerveld , Aaron King , Hiroki Horiuchi +// Definitions: https://github.com/borisyankov/DefinitelyTyped interface MomentInput { years?: number; @@ -50,6 +48,9 @@ interface Duration { years(): number; asYears(): number; + subtract(n: number, p: string): Duration; + subtract(n: number): Duration; + subtract(d: Duration): Duration; } interface Moment { @@ -59,14 +60,45 @@ interface Moment { fromNow(withoutSuffix?: boolean): string; - startOf(soort: string): Moment; - endOf(soort: string): Moment; + startOf(unitOfTime: string): Moment; + endOf(unitOfTime: string): Moment; - add(input: MomentInput): Moment; - add(soort: string, aantal: number): Moment; + /** + * Mutates the original moment by adding time. + * + * @param unitOfTime the key of what time you want to add (eg "years" / "hours" etc) + * @param amount the amount you want to add + */ + add(unitOfTime: string, amount: number): Moment; + /** + * Mutates the original moment by adding time. + * + * @param amount the amount you want to add + * @param unitOfTime the key of what time you want to add (eg "years" / "hours" etc) + */ + add(amount: number, unitOfTime: string): Moment; + /** + * Mutates the original moment by adding time. + * + * @param unitOfTime the key of what time you want to add (eg "years" / "hours" etc) + * @param amount the amount you want to add + */ + add(unitOfTime: string, amount: string): Moment; + /** + * Mutates the original moment by adding time. + * + * @param objectLiteral an object literal that describes multiple different keys at the same time {days:7,months:1} + */ + add(objectLiteral: MomentInput): Moment; + /** + * Mutates the original moment by adding time. + * + * @param duration a length of time + */ add(duration: Duration): Moment; + subtract(input: MomentInput): Moment; - subtract(soort: string, aantal: number): Moment; + subtract(unitOfTime: string, amount: number): Moment; calendar(): string; clone(): Moment; @@ -122,8 +154,8 @@ interface Moment { from(date: number[]): string; diff(b: Moment): number; - diff(b: Moment, soort: string): number; - diff(b: Moment, soort: string, round: boolean): number; + diff(b: Moment, unitOfTime: string): number; + diff(b: Moment, unitOfTime: string, round: boolean): number; toDate(): Date; toISOString(): string; @@ -290,7 +322,7 @@ interface MomentStatic { ordinal: (num: number) => string; duration(milliseconds: Number): Duration; - duration(num: Number, soort: string): Duration; + duration(num: Number, unitOfTime: string): Duration; duration(input: MomentInput): Duration; duration(object: any): Duration; duration(): Duration; diff --git a/mongodb/mongodb.d.ts b/mongodb/mongodb.d.ts index 0805e832ab..05f71d20ae 100644 --- a/mongodb/mongodb.d.ts +++ b/mongodb/mongodb.d.ts @@ -129,6 +129,26 @@ declare module "mongodb" { public static createFromHexString(hexString: string): ObjectID; } + // Class documentation : http://mongodb.github.io/node-mongodb-native/api-bson-generated/binary.html + export class Binary { + constructor (buffer: Buffer, subType?: number); + + // Updates this binary with byte_value + put(byte_value: any): void; + + // Writes a buffer or string to the binary + write(buffer: any, offset: number): void; + + // Reads length bytes starting at position. + read(position: number, length: number): Buffer; + + // Returns the value of this binary as a string. + value(): string; + + // The length of the binary. + length(): number; + } + export interface SocketOptions { //= set seconds before connection times out default:0 timeout?: number; @@ -282,8 +302,12 @@ declare module "mongodb" { findOne(selector: Object, fields: any, skip: number, limit: number, callback?: (err: Error, result: any) => void): Cursor; findOne(selector: Object, fields: any, skip: number, limit: number, timeout: number, callback?: (err: Error, result: any) => void): Cursor; + createIndex(fieldOrSpec: any, callback: (err: Error, indexName: string) => void): void; createIndex(fieldOrSpec: any, options: IndexOptions, callback: (err: Error, indexName: string) => void): void; + + ensureIndex(fieldOrSpec: any, callback: (err: Error, indexName: string) => void): void; ensureIndex(fieldOrSpec: any, options: IndexOptions, callback: (err: Error, indexName: string) => void): void; + indexInformation(options: any, callback: Function): void; dropIndex(name: string, callback: Function): void; dropAllIndexes(callback: Function): void; diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts new file mode 100644 index 0000000000..38c469ca15 --- /dev/null +++ b/mongoose/mongoose-tests.ts @@ -0,0 +1,366 @@ +/// + +var fs = require('fs'); +import mongoose = require('mongoose'); + +var createInstance = new mongoose.Mongoose(); + +var Schema = mongoose.Schema; +var CreateSchema = new Schema({}); + +mongoose.connect('mongodb://user:pass@localhost:port/database'); +mongoose.connect('mongodb://hostA:27501,hostB:27501', { mongos: true }); + +var conn: mongoose.Connection = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); +conn = mongoose.createConnection('mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port', { replset: { strategy: 'ping', rs_name: 'testSet' }}); +conn = mongoose.createConnection('localhost', 'database', 27014); +conn = mongoose.createConnection('localhost', 'database', 27014, { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' }); +conn = mongoose.createConnection(); +conn.open('localhost', 'database', 27014, {}); + +var db = mongoose.createConnection(); +db.openSet("mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019"); +db.openSet('mongodb://mongosA:27501,mongosB:27501', 'db', { mongos: true }, (err: any) => {}); +db.close(); + +var collection = db.collection('collection1'); + +mongoose.connection.on('error', (err: any) => {}); +mongoose.disconnect(); + +mongoose.set('test', 1234567890); +var value = mongoose.get('test'); +mongoose.set('debug', true); + +interface IActor extends mongoose.Document { + name: string; +} +mongoose.model('Actor', new Schema({ name: String })); +db.model('Actor', new Schema({ name: String })); +var schema: mongoose.Schema = new Schema({ name: String }, { collection: 'actor' }); +schema.set('collection', 'actor'); +var Model = mongoose.model('Actor', schema, 'actor'); + +var names: string[] = mongoose.modelNames(); +var names: string[] = db.modelNames(); +mongoose.plugin((schema: mongoose.Schema) => { +}, { index: true }); + + +var aggregate = new mongoose.Aggregate(); +var aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }); +var aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 }); +var aggregate = new mongoose.Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]); +aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); +aggregate.append([{ $match: { daw: 'Logic Audio X' }} ]); +aggregate.group({ _id: "$department" }); +aggregate.skip(10); +aggregate.limit(10); +aggregate.match({ department: { $in: [ "sales", "engineering" ] } }); +aggregate.near({ + near: [40.724, -73.997], + distanceField: "dist.calculated", // required + maxDistance: 0.008, + query: { type: "public" }, + includeLocs: "dist.location", + uniqueDocs: true, + num: 5 +}); +aggregate.project("a b -_id"); +aggregate.project({a: 1, b: 1, _id: 0}); +aggregate.project({ + newField: '$b.nested', + plusTen: { $add: ['$val', 10]}, + sub: { + name: '$a' + } +}); +aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } }); +aggregate.sort({ field: 'asc', test: -1 }); +aggregate.sort('field -test'); +aggregate.unwind("tags"); +aggregate.unwind("a", "b", "c"); +var p = aggregate.exec(); +aggregate.read('primaryPreferred').exec((err: any, result: {}) => {}); + + +var p = new mongoose.Promise; +var p2 = p.then(function() { throw new Error('shucks') }).end(); +setTimeout(function() { + p.fulfill({}); +}, 10); +var promise = new mongoose.Promise(); +promise.then(function (meetups: number) { + return new mongoose.Promise(); +}).then(function (people: string[]) { + if (people.length < 10000) { + throw new Error('Too few people!!!'); + } else { + throw new Error('Still need more people!!!'); + } +}).then(null, function (err: Error) { +}).end(); + + +Model.findOne({ name: 'john' }, (err: any, doc: mongoose.Document) => { + doc.invalidate('size', 'must be less than 20', 14); + doc.validate((err: any) => { }); + + doc.set('documents.0.title', 'changed'); + doc.get('documents.0'); + doc.set({ + 'path' : 1, + 'path2' : { + 'path' : 2 + } + }); + doc.set('path', 'value', { strict: false }); + doc.set('path3', '1', Number); + doc.get('path3', Number); + doc.id; + doc._id; + + doc.isModified(); + doc.isModified('documents'); + doc.isModified('documents.0.title'); + doc.isDirectModified('documents.0.title'); + doc.isDirectModified('documents'); + doc.isSelected('name'); + + doc.markModified('mixed.type'); + doc.populate('user'); + doc.populate('other', (err: any, doc: mongoose.Document) => {}); + doc.populated('author'); + doc.save(); + + doc.toJSON({ getters: true, virtuals: false }); + var data: any = doc.toObject(); + delete data['age']; + delete data['weight']; + data['isAwesome'] = true; +}); + +Model.model('User').findById('id', (err: any, res: IActor) => {}); +Model.count({ type: 'jungle' }, (err: any, count: number) => {}); +Model.remove((err: any, res: IActor[]) => {}); +Model.save((err: any, res: IActor, numberAffected: number) => {}); +Model.create({ type: 'jelly bean' }, { type: 'snickers' }, (err: any, res1: IActor, res2: IActor) => {}); +Model.create({ type: 'jawbreaker' }); +Model.distinct('url', { clicks: {$gt: 100}}, (err: any, result: IActor[]) => {}); +Model.distinct('url'); + +Model.aggregate( + { $group: { _id: null, maxBalance: { $max: '$balance' }}}, + { $project: { _id: 0, maxBalance: 1 }}, + (err: any, res: IActor[]) => {}); +Model.aggregate() + .group({ _id: null, maxBalance: { $max: '$balance' } }) + .select('-id maxBalance') + .exec((err: any, res: IActor[]) => {}); +Model.ensureIndexes((err) => {}); + +Model.find({ name: 'john', age: { $gte: 18 }}); +Model.find({ name: 'john', age: { $gte: 18 }}, (err: any, docs: IActor[]) => {}); +Model.find({ name: /john/i }, 'name friends', (err: any, docs: IActor[]) => {}); +Model.find({ name: /john/i }, null, { skip: 10 }); +Model.find({ name: /john/i }, null, { skip: 10 }, (err: any, docs: IActor[]) => {}); +Model.find({ name: /john/i }, null, { skip: 10 }).exec((err: any, docs: IActor[]) => {}); +var query = Model.find({ name: /john/i }, null, { skip: 10 }); +var promise1 = query.exec(); +promise1.addBack((err: any, docs: IActor[]) => {}); + +Model.findById('id', (err: any, res: IActor) => {}); +Model.findById('id').exec((err: any, res: IActor) => {}); +Model.findById('id', 'name length', (err: any, res: IActor) => {}); +Model.findById('id', '-length').exec((err: any, res: IActor) => {}); +Model.findById('id', 'name', { lean: true }, (err: any, res: IActor) => {}); +Model.findById('id', 'name').lean().exec((err: any, res: IActor) => {}); +Model.findByIdAndRemove('id1', { select: 'name' }, (err: any, res: IActor) => {}); +Model.findByIdAndRemove('id1', { select: 'name' }).exec((err: any, res: IActor) => {}); +Model.findByIdAndRemove('id1', (err: any, res: IActor) => {}); +Model.findByIdAndRemove('id1').exec((err: any, res: IActor) => {}); +Model.findByIdAndUpdate('id2', { $set: { name: 'jason borne' }}, { upsert: true }, (err: any, res: IActor) => {}); + +Model.findOne({ type: 'iphone' }, (err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }).exec((err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }, 'name', (err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }, 'name').exec((err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }, 'name', { lean: true }, (err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }, 'name', { lean: true }).exec((err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }).select('name').lean().exec((err: any, res: IActor) => {}); +Model.findOneAndRemove({ type: 'iphone' }, { select: 'name' }, (err: any, res: IActor) => {}); +Model.findOneAndRemove({ type: 'iphone' }, { select: 'name' }).exec((err: any, res: IActor) => {}); +Model.findOneAndUpdate({ type: 'iphone' }, { $set: { name: 'jason borne' }}, { upsert: true }, (err: any, res: IActor) => {}); + +Model.geoNear([1, 3], { maxDistance : 5, spherical : true }, (err: any, res: IActor[]) => {}); +Model.geoNear({ type : "Point", coordinates : [9,9] }, { maxDistance : 5, spherical : true }, (err: any, res: IActor[]) => {}); +Model.geoSearch({ type : "house" }, { near: [10, 10], maxDistance: 5 }, (err: any, res: IActor[]) => {}); + +var o = { + map: function () { this.emit(this.name, 1) }, + reduce: function (k: string, vals: IActor[]) { return vals.length }, +}; +Model.mapReduce(o, (err: any, res: any[]) => {}); + +Model.findById('id', (err: any, res: IActor) => { + var opts = [ + { path: 'company', match: { x: 1 }, select: 'name' }, + { path: 'notes', options: { limit: 10 }, model: 'override' } + ]; + Model.populate(res, opts, (err: any, res: IActor) => {}); +}); +Model.find({ type: 'iphone' }, (err: any, res: IActor[]) => { + var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }]; + var promise = Model.populate(res, opts); + promise.then(console.log).end(); +}); +Model.populate({ name: 'Test A' }, { path: 'weapon', model: 'Weapon' }, (err: any, user: IActor) => {}); +Model.populate([ + { name: 'User hoge' }, + { name: 'User fuga' }, +], { path: 'weapon' }, (err: any, users: IActor[]) => {}); + +Model.remove({ title: 'baby born from alien father' }, (err: any) => {}); +var query2 = Model.remove({ _id: 'id' }); +query2.exec(); +Model.update({ age: { $gt: 18 } }, { oldEnough: true }, (err: any, numberAffected: number, raw: any) => {}); +Model.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, (err: any, numberAffected: number, raw: any) => {}); +Model.update({ _id: 'id' }, { $set: { text: 'changed' }}).exec(); + +Model.where('age').gte(21).lte(65).exec((err: any, res: IActor[]) => {}); +var query3 =Model + .where('age').gt(21).lt(65) + .where('name', /^b/i).all('type', 1); +query3.all(25); +query3.and([{ color: 'green' }, { status: 'ok' }]); +query3.batchSize(100); +query3.where('loc').within().box([40.73083, -73.99756], [40.741404, -73.988135]); +query3.where('loc').within().circle({ center: [50, 50], radius: 10, unique: true }); +query3.circle('loc', { center: [50, 50], radius: 10, unique: true }); +query3.comment('login query'); +query3.where({ 'color': 'black' }).count(); +query3.count({ color: 'black' }).count((err: any, count: number) => {}); +query3.count({ color: 'black' }, (err: any, count: number) => {}); +query3.where({ color: 'black' }).count((err: any, count: number) => {}); +query3.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}); +query3.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}); +query.elemMatch('comment', (elem: mongoose.Query) => { + elem.where('author').equals('autobot'); + elem.where('votes').gte(5); +}); +query3.where('age').equals(49); +query3.where('age', 49); +query3.exec(); +query3.exec('update'); +query3.where('name').exists(); +query3.where('name').exists(true); +query3.find().exists('name'); +query3.where('name').exists(false); +query3.find().exists('name', false); +query3.find({ name: 'Los Pollos Hermanos' }).find((err: any, res: IActor[]) => {}); +query3.where('loc').within().geometry({ type: 'Polygon', coordinates: [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] }); +query3.find().where('age').gt(21); +query3.find().gt('age', 21); +query3.hint({ indexA: 1, indexB: -1}); +query3.where('path').intersects().geometry({ type: 'LineString', coordinates: [[180.0, 11.0], [180, 9.0]] }); +query3.where('path').intersects({ type: 'LineString', coordinates: [[180.0, 11.0], [180, 9.0]] }); +query3.maxScan(100); +query3.where('loc').near({ center: [10, 10] }); +query3.where('loc').near({ center: [10, 10], maxDistance: 5 }); +query3.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); +query3.near('loc', { center: [10, 10], maxDistance: 5 }); +query3.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); +query3.nor([{ color: 'green' }, { status: 'ok' }]); +query3.or([{ color: 'red' }, { status: 'emergency' }]); +query3.where('loc').within().polygon([10,20], [13, 25], [7,15]); +query3.polygon('loc', [10,20], [13, 25], [7,15]); + +query3.findOne().populate('owner').exec((err: any, res: IActor[]) => {}); +query3.find().populate({ + path: 'owner', + select: 'name', + match: { color: 'black' }, + options: { sort: { name: -1 }} +}).exec((err: any, res: IActor[]) => {}); +query3.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec((err: any, res: IActor[]) => {}); + +query3.read('primary'); +query3.read('p'); +query3.read('primaryPreferred'); +query3.read('pp'); +query3.read('secondary'); +query3.read('s'); +query3.read('secondaryPreferred'); +query3.read('sp'); +query3.read('nearest'); +query3.read('n'); +query3.read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]); +query3.remove({ artist: 'Anne Murray' }, (err: any, res: IActor[]) => {}); +query3.select('a b -c'); +query3.select({a: 1, b: 1, c: 0}); +query3.select('+path'); +query3.where('tags').size(0); +query3.skip(100).limit(20); +query3.slaveOk(); +query3.slaveOk(true); +query3.slaveOk(false); +query3.slice('comments', -5); +query3.slice('comments', [10, 5]) +query3.where('comments').slice(5); +query3.where('comments').slice([-10, 5]); +query3.snapshot(); +query3.snapshot(true); +query3.snapshot(false); +query3.sort({ field: 'asc', test: -1 }); +query3.sort('field -test'); +Model.find({ name: /^hello/ }).stream({ transform: JSON.stringify }).pipe(fs.createWriteStream('./test.json')); +var stream = Model.find({ name: /^hello/ }).stream(); +stream + .on('data', (doc: IActor) => {}) + .on('error', (err: any) => {}) + .on('close', () => {}); + +query3.tailable(); +query3.tailable(false); +var AdvQuery = query3.toConstructor(); +query3.update({ title: 'words' }); +query3.update({ $set: { title: 'words' }}); +query3.update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, (err: any, row: number, raw: any) => {}); + +query3.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); +query3.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); +query3.where('loc').within({ polygon: [[],[],[],[]] }); +query3.where('loc').within([], [], []); // polygon +query3.where('loc').within([], []); // box +query3.where('loc').within({ type: 'LineString', coordinates: [] }); // geometry + +mongoose.Query.use$geoWithin = false; + + +var ToySchema = new Schema({}); +ToySchema.add({ name: 'string', color: 'string', price: 'number' }); +schema.eachPath(function(path: string, value: any) {}); +schema.index({ first: 1, last: -1 }); +schema.indexes(); +schema.method('meow', function() { + console.log('meeeeeoooooooooooow'); +}); +var Kitty = mongoose.model('Kitty', schema); +var fizz: any = new Kitty({ name: 'kitty' }); +fizz.meow(); +schema.method({ + purr: function() {}, + scratch: function() {}, +}); +schema.path('name'); +schema.path('name', Number); +schema.pathType('name'); +schema.plugin(function() {}); +schema.post('save', function(doc: IActor) {}); +schema.pre('save', function(next: () => void) {}); +schema.requiredPaths(); +schema.static('findByName', function(name: string, callback: () => void) {}); +schema.virtual('display_name') + .get(function(): string { return this.name; }) + .set((value: string): void => {}); + diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts new file mode 100644 index 0000000000..e9057abc7a --- /dev/null +++ b/mongoose/mongoose.d.ts @@ -0,0 +1,453 @@ +// Type definitions for Mongoose 3.8.5 +// Project: http://mongoosejs.com/ +// Definitions by: horiuchi +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "mongoose" { + function connect(uri: string, options?: ConnectionOption, callback?: (err: any) => void): Mongoose; + function createConnection(): Connection; + function createConnection(uri: string, options?: ConnectionOption): Connection; + function createConnection(host: string, database_name: string, port?: number, options?: ConnectionOption): Connection; + function disconnect(callback?: (err?: any) => void): Mongoose; + + function model(name: string, schema: Schema, collection?: string, skipInit?: boolean): Model; + function modelNames(): string[]; + function plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; + + function get(key: string): any; + function set(key: string, value: any): void; + + var mongo: any; + var mquery: any; + var version: string; + var connection: Connection; + + export class Mongoose { + connect(uri: string, options?: ConnectionOption, callback?: (err: any) => void): Mongoose; + createConnection(): Connection; + createConnection(uri: string, options?: Object): Connection; + createConnection(host: string, database_name: string, port?: number, options?: ConnectionOption): Connection; + disconnect(callback?: (err?: any) => void): Mongoose; + get(key: string): any; + model(name: string, schema: Schema, collection?: string, skipInit?: boolean): Model; + modelNames(): string[]; + plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; + set(key: string, value: any): void; + + mongo: any; + mquery: any; + version: string; + connection: Connection; + } + + export interface Connection extends NodeJS.EventEmitter { + constructor(base: Mongoose): Connection; + + close(callback?: (err: any) => void): Connection; + collection(name: string, options?: Object): Collection; + model(name: string, schema: Schema, collection?: string): Model; + modelNames(): string[]; + open(host: string, database?: string, port?: number, options?: ConnectionOption, callback?: (err: any) => void): Connection; + openSet(uris: string, database?: string, options?: ConnectionSetOption, callback?: (err: any) => void): Connection; + + db: any; + collections: {[index: string]: Collection}; + readyState: number; + } + export interface ConnectionOption { + db?: any; + server?: any; + replset?: any; + user?: string; + pass?: string; + auth?: any; + } + export interface ConnectionSetOption extends ConnectionOption { + mongos?: boolean; + } + + export interface Collection { + } + + + export class SchemaType { } + export class VirtualType { + get(fn: Function): VirtualType; + set(fn: Function): VirtualType; + } + export module Types { + export class ObjectId {} + } + + export class Schema { + static Types: { + String: String; + ObjectId: Types.ObjectId; + OId: Types.ObjectId; + Mixed: any; + }; + constructor(schema?: Object, options?: Object); + + add(obj: Object, prefix?: string): void; + eachPath(fn: (path: string, type: any) => void): Schema; + get(key: string): any; + index(fields: Object, options?: Object): Schema; + indexes(): void; + method(name: string, fn: Function): Schema; + method(method: Object): Schema; + path(path: string): any; + path(path: string, constructor: any): Schema; + pathType(path: string): string; + plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Schema; + post(method: string, fn: Function): Schema; + pre(method: string, callback: Function): Schema; + requiredPaths(): string[]; + set(key: string, value: any): void; + static(name: string, fn: Function): Schema; + virtual(name: string, options?: Object): VirtualType; + virtualpath(name: string): VirtualType; + } + export interface SchemaOption { + autoIndex?: boolean; + bufferCommands?: boolean; + capped?: boolean; + collection?: string; + id?: boolean; + _id?: boolean; + minimize?: boolean; + read?: string; + safe?: boolean; + shardKey?: boolean; + strict?: boolean; + toJSON?: Object; + toObject?: Object; + versionKey?: boolean; + } + + export interface Model { + new(doc: Object): T; + + aggregate(...aggregations: Object[]): Aggregate; + aggregate(aggregation: Object, callback: (err: any, res: T[]) => void): Promise; + aggregate(aggregation1: Object, aggregation2: Object, callback: (err: any, res: T[]) => void): Promise; + aggregate(aggregation1: Object, aggregation2: Object, aggregation3: Object, callback: (err: any, res: T[]) => void): Promise; + count(conditions: Object, callback?: (err: any, count: number) => void): Query; + + create(doc: Object, fn?: (err: any, res: T) => void): Promise; + create(doc1: Object, doc2: Object, fn?: (err: any, res1: T, res2: T) => void): Promise; + create(doc1: Object, doc2: Object, doc3: Object, fn?: (err: any, res1: T, res2: T, res3: T) => void): Promise; + discriminator(name: string, schema: Schema): Model; + distinct(field: string, callback?: (err: any, res: T[]) => void): Query; + distinct(field: string, conditions: Object, callback?: (err: any, res: T[]) => void): Query; + ensureIndexes(callback: (err: any) => void): Promise; + + find(cond: Object, callback?: (err: any, res: T[]) => void): Query; + find(cond: Object, fields: Object, callback?: (err: any, res: T[]) => void): Query; + find(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T[]) => void): Query; + findById(id: string, callback?: (err: any, res: T) => void): Query; + findById(id: string, fields: Object, callback?: (err: any, res: T) => void): Query; + findById(id: string, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findByIdAndRemove(id: string, callback?: (err: any, res: T) => void): Query; + findByIdAndRemove(id: string, options: Object, callback?: (err: any, res: T) => void): Query; + findByIdAndUpdate(id: string, update: Object, callback?: (err: any, res: T) => void): Query; + findByIdAndUpdate(id: string, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; + findOne(cond: Object, callback?: (err: any, res: T) => void): Query; + findOne(cond: Object, fields: Object, callback?: (err: any, res: T) => void): Query; + findOne(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; + + geoNear(point: { type: string; coordinates: number[] }, options: Object, callback?: (err: any, res: T[]) => void): Query; + geoNear(point: number[], options: Object, callback?: (err: any, res: T[]) => void): Query; + geoSearch(cond: Object, options: GeoSearchOption, callback?: (err: any, res: T[]) => void): Query; + increment(): T; + mapReduce(options: MapReduceOption, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; + mapReduce(options: MapReduceOption2, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; + model(name: string): Model; + + populate(doc: U, options: Object, callback?: (err: any, res: U) => void): Promise; + populate(doc: U[], options: Object, callback?: (err: any, res: U[]) => void): Promise; + update(cond: Object, update: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query; + update(cond: Object, update: Object, options: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query; + remove(cond: Object, callback?: (err: any) => void): Query<{}>; + save(callback?: (err: any, result: T, numberAffected: number) => void): Query; + where(path: string, val?: Object): Query; + + $where(argument: string): Query; + $where(argument: Function): Query; + + base: Mongoose; + collection: Collection; + db: any; + discriminators: any; + modelName: string; + schema: Schema; + } + export interface FindAndUpdateOption { + new?: boolean; + upsert?: boolean; + sort?: Object; + select?: Object; + } + export interface GeoSearchOption { + near: number[]; + maxDistance: number; + limit?: number; + lean?: boolean; + } + export interface MapReduceOption { + map: () => void; + reduce: (key: Key, vals: T[]) => Val; + query?: Object; + limit?: number; + keeptemp?: boolean; + finalize?: (key: Key, val: Val) => Val; + scope?: Object; + jsMode?: boolean; + verbose?: boolean; + out?: { + inline?: number; + replace?: string; + reduce?: string; + merge?: string; + }; + } + export interface MapReduceOption2 { + map: string; + reduce: (key: Key, vals: T[]) => Val; + query?: Object; + limit?: number; + keeptemp?: boolean; + finalize?: (key: Key, val: Val) => Val; + scope?: Object; + jsMode?: boolean; + verbose?: boolean; + out?: { + inline?: number; + replace?: string; + reduce?: string; + merge?: string; + }; + } + export interface MapReduceResult { + _id: Key; + value: Val; + } + + export class Query { + exec(callback?: (err: any, res: T) => void): Promise; + exec(operation: string, callback?: (err: any, res: T) => void): Promise; + exec(operation: Function, callback?: (err: any, res: T) => void): Promise; + + all(val: number): Query; + all(path: string, val: number): Query; + and(array: Object[]): Query; + box(val: Object): Query; + box(a: number[], b: number[]): Query; + batchSize(val: number): Query; + cast(model: Model, obj: Object): U; + //center(): Query; + //centerSphere(path: string, val: Object): Query; + circle(area: Object): Query; + circle(path: string, area: Object): Query; + comment(val: any): Query; + count(callback?: (err: any, count: number) => void): Query; + count(criteria: Object, callback?: (err: any, count: number) => void): Query; + distinct(callback?: (err: any, res: T) => void): Query; + distinct(field: string, callback?: (err: any, res: T) => void): Query; + distinct(criteria: Object, field: string, callback?: (err: any, res: T) => void): Query; + distinct(criteria: Query, field: string, callback?: (err: any, res: T) => void): Query; + elemMatch(criteria: Object): Query; + elemMatch(criteria: (elem: Query) => void): Query; + elemMatch(path: string, criteria: Object): Query; + elemMatch(path: string, criteria: (elem: Query) => void): Query; + equals(val: Object): Query; + exists(val?: boolean): Query; + exists(path: string, val?: boolean): Query; + find(callback?: (err: any, res: T) => void): Query; + find(criteria: Object, callback?: (err: any, res: T) => void): Query; + findOne(callback?: (err: any, res: T) => void): Query; + findOne(criteria: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(update: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; + geometry(object: Object): Query; + gt(val: number): Query; + gt(path: string, val: number): Query; + gte(val: number): Query; + gte(path: string, val: number): Query; + hint(val: Object): Query; + in(val: any[]): Query; + in(path: string, val: any[]): Query; + intersects(arg?: Object): Query; + lean(bool?: boolean): Query; + limit(val: number): Query; + lt(val: number): Query; + lt(path: string, val: number): Query; + lte(val: number): Query; + lte(path: string, val: number): Query; + maxDistance(val: number): Query; + maxDistance(path: string, val: number): Query; + maxScan(val: number): Query; + merge(source: Query): Query; + merge(source: Object): Query; + mod(val: number[]): Query; + mod(path: string, val: number[]): Query; + ne(val: any): Query; + ne(path: string, val: any): Query; + near(val: Object): Query; + near(path: string, val: Object): Query; + nearSphere(val: Object): Query; + nearSphere(path: string, val: Object): Query; + nin(val: any[]): Query; + nin(path: string, val: any[]): Query; + nor(array: Object[]): Query; + or(array: Object[]): Query; + polygon(...coordinatePairs: number[][]): Query; + polygon(path: string, ...coordinatePairs: number[][]): Query; + populate(path: string, select?: string, match?: Object, options?: Object): Query; + populate(path: string, select: string, model: string, match?: Object, options?: Object): Query; + populate(opt: PopulateOption): Query; + read(pref: string, tags?: Object[]): Query; + regex(val: RegExp): Query; + regex(path: string, val: RegExp): Query; + remove(callback?: (err: any, res: T) => void): Query; + remove(criteria: Object, callback?: (err: any, res: T) => void): Query; + select(arg: string): Query; + select(arg: Object): Query; + setOptions(options: Object): Query; + size(val: number): Query; + size(path: string, val: number): Query; + skip(val: number): Query; + slaveOk(v?: boolean): Query; + slice(val: number): Query; + slice(val: number[]): Query; + slice(path: string, val: number): Query; + slice(path: string, val: number[]): Query; + snapshot(v?: boolean): Query; + sort(arg: Object): Query; + sort(arg: string): Query; + stream(options?: { transform?: Function; }): QueryStream; + tailable(v?: boolean): Query; + toConstructor(): Query; + update(callback?: (err: any, affectedRows: number, doc: T) => void): Query; + update(doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; + update(criteria: Object, doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; + update(criteria: Object, doc: Object, options: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; + where(path?: string, val?: any): Query; + where(path?: Object, val?: any): Query; + within(val?: Object): Query; + within(coordinate: number[], ...coordinatePairs: number[][]): Query; + + $where(argument: string): Query; + $where(argument: Function): Query; + + static use$geoWithin: boolean; + } + + export interface PopulateOption { + path: string; + select?: string; + model?: string; + match?: Object; + options?: Object; + } + + export interface QueryStream extends NodeJS.EventEmitter { + destory(err?: any): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + paused: number; + readable: boolean; + } + + export interface Document { + id?: string; + _id: string; + + equals(doc: Document): boolean; + get(path: string, type?: new(...args: any[]) => any): any; + inspect(options?: Object): string; + invalidate(path: string, errorMsg: string, value: any): void; + invalidate(path: string, error: Error, value: any): void; + isDirectModified(path: string): boolean; + isInit(path: string): boolean; + isModified(path?: string): boolean; + isSelected(path: string): boolean; + markModified(path: string): void; + modifiedPaths(): string[]; + populate(callback?: (err: any, res: T) => void): Document; + populate(path?: string, callback?: (err: any, res: T) => void): Document; + populate(opt: PopulateOption, callback?: (err: any, res: T) => void): Document; + populated(path: string): any; + remove(callback?: (err: any) => void): Query; + save(callback?: (err: any, res: T) => void): void; + set(path: string, val: any, type?: new(...args: any[]) => any, options?: Object): void; + set(path: string, val: any, options?: Object): void; + set(value: Object): void; + toJSON(options?: Object): Object; + toObject(options?: Object): Object; + toString(): string; + update(doc: Object, options: Object, callback: (err: any, affectedRows: number, raw: any) => void): Query; + validate(cb: (err: any) => void): void; + + isNew: boolean; + errors: Object; + schema: Object; + } + + + export class Aggregate { + constructor(...options: Object[]); + + append(...options: Object[]): Aggregate; + group(arg: Object): Aggregate; + limit(num: number): Aggregate; + match(arg: Object): Aggregate; + near(parameters: Object): Aggregate; + project(arg: string): Aggregate; + project(arg: Object): Aggregate; + select(filter: string): Aggregate; + skip(num: number): Aggregate; + sort(arg: string): Aggregate; + sort(arg: Object): Aggregate; + unwind(fiels: string, ...rest: string[]): Aggregate; + + exec(callback?: (err: any, result: T) => void): Promise; + read(pref: string, ...tags: Object[]): Aggregate; + } + + export class Promise { + constructor(fn?: (err: any, result: T) => void); + + then(onFulFill: (result: T) => void, onReject?: (err: any) => void): Promise; + end(): void; + + fulfill(result: T): Promise; + reject(err: any): Promise; + resolve(err: any, result: T): Promise; + + onFulfill(listener: (result: T) => void): Promise; + onReject(listener: (err: any) => void): Promise; + onResolve(listener: (err: any, result: T) => void): Promise; + on(event: string, listener: Function): Promise; + + // Deprecated methods. + addBack(listener: (err: any, result: T) => void): Promise; + addCallback(listener: (result: T) => void): Promise; + addErrback(listener: (err: any) => void): Promise; + complete(result: T): Promise; + error(err: any): Promise; + } + +} + diff --git a/mousetrap/mousetrap.d.ts b/mousetrap/mousetrap.d.ts index d2ae42aa6d..dee352b42b 100644 --- a/mousetrap/mousetrap.d.ts +++ b/mousetrap/mousetrap.d.ts @@ -1,6 +1,6 @@ // Type definitions for Mousetrap 1.2.2 // Project: http://craig.is/killing/mice -// Definitions by: Dániel Tar https://github.com/qcz +// Definitions by: Dániel Tar // Definitions: https://github.com/borisyankov/DefinitelyTyped interface ExtendedKeyboardEvent extends KeyboardEvent { diff --git a/moviedb/moviedb-tests.ts b/moviedb/moviedb-tests.ts new file mode 100644 index 0000000000..4e75b629c4 --- /dev/null +++ b/moviedb/moviedb-tests.ts @@ -0,0 +1,28 @@ + +/// + +import moviedb = require('moviedb'); + +export class TmbdMovieScanner { + movieDb: MovieDB.IMovieDB; + + constructor() { + this.movieDb = moviedb('YOUR API KEY'); + + // For testing purposes + this.movieDb.searchMovie({ query: "Aliens" }, (err, movies) => { + if (err) { + console.log('Error: ' + err); + return; + } + console.log(movies); + }); + this.movieDb.movieInfo({ id: 666 }, (err, curMovie) => { + if (err) { + console.log('Error: ' + err); + return; + } + console.log(curMovie.overview); + }); + } +} \ No newline at end of file diff --git a/moviedb/moviedb.d.ts b/moviedb/moviedb.d.ts new file mode 100644 index 0000000000..c8ed37727a --- /dev/null +++ b/moviedb/moviedb.d.ts @@ -0,0 +1,94 @@ +// Type definitions for MovieDB +// Project: https://github.com/danzajdband/moviedb +// Definitions by: Basarat Ali Syed +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Ghost module for Types +declare module MovieDB { + export interface IMovieDB { + searchMovie(params: SearchOptions, callback: (err: any, movies: SearchResults) => void): void; + movieInfo(options: InfoOptions, callback: (err: any, curMovie: Movie) => void): void; + + // More methods TBD: + // https://github.com/danzajdband/moviedb#available-methods + } + + export interface SearchOptions { + query: string; + } + + export interface InfoOptions { + id: number; + } + + export interface SearchResults { + page: number; + results: SearchResult[]; + total_Pages: number; + total_results: number; + } + + export interface SearchResult { + adult: boolean; + backdrop_path: string; + id: number; + original_title: string; + release_date: Date; + poster_path: string; + popularity: number; + title: string; + vote_average: number; + vote_count: number; + } + + export interface Movie { + adult: boolean; + backdrop_path: string; + belongs_to_collection: any; + budget: number; + genres: Genre[]; + homepage: string; + id: number; + imdb_id: number; + original_title: string; + overview: string; + popularity: number; + poster_path: string; + production_companies: ProductionCompany[]; + production_countries: ProductionCountry[]; + release_date: Date; + revenue: number; + runtime: number; + spoken_languages: SpokenLanguage[]; + status: string; + tagline: string; + title: string; + vote_average: number; + vote_count: number; + } + + export interface Genre { + id: number; + name: string; + } + + export interface ProductionCompany { + id: number; + name: string; + } + + export interface ProductionCountry { + iso_3166_1: number; + name: string; + } + + export interface SpokenLanguage { + iso_639_1: number; + name: string; + } +} + +declare module 'moviedb' { + function apiKeyAcceptor(key: string): MovieDB.IMovieDB; + export = apiKeyAcceptor; +} \ No newline at end of file diff --git a/msnodesql/msnodesql.d.ts b/msnodesql/msnodesql.d.ts index cadb323dbc..39bf01fb82 100644 --- a/msnodesql/msnodesql.d.ts +++ b/msnodesql/msnodesql.d.ts @@ -7,6 +7,8 @@ /// declare module "msnodesql" { + import events = require('events'); + export function open(connectionString: string, callback?: OpenCallback): Connection; export function query(connectionString: string, query: string, callback?: QueryCallback): StreamEvents; @@ -55,5 +57,5 @@ declare module "msnodesql" { close(immediately: boolean, callback?: ErrorCallback); } - interface StreamEvents extends NodeEventEmitter { } + interface StreamEvents extends events.EventEmitter {} } \ No newline at end of file diff --git a/mu2/mu2-tests.ts b/mu2/mu2-tests.ts new file mode 100644 index 0000000000..24b85ec4df --- /dev/null +++ b/mu2/mu2-tests.ts @@ -0,0 +1,32 @@ +/// +/// + +import mu2 = require('mu2'); +import stream = require('stream'); + +var str: string; +var value: any; +var read: NodeJS.ReadableStream; +var parsed: mu2.IParsed; + +str = mu2.root; + +read = mu2.compileAndRender(str, value); + +mu2.compile(str, (err: Error, parsed: mu2.IParsed) => { + +}); +mu2.compileText(str, str, (err: Error, parsed: mu2.IParsed) => { + +}); +parsed = mu2.compileText(str, str); +parsed = mu2.compileText(str); + +read = mu2.render(str, value); +read = mu2.render(parsed, value); + +read = mu2.renderText(str, value); +read = mu2.renderText(str, value, value); + +mu2.clearCache(); +mu2.clearCache(str); diff --git a/mu2/mu2.d.ts b/mu2/mu2.d.ts new file mode 100644 index 0000000000..714703934c --- /dev/null +++ b/mu2/mu2.d.ts @@ -0,0 +1,29 @@ +// Type definitions for mu2 +// Project: http://github.com/raycmorgan/mu +// Definitions by: Jeff Goddard +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/mu2.d.ts + +/// + +declare module "mu2" { + export var root: string; + + export function compileAndRender(templateName: string, view: any): NodeJS.ReadableStream; + + export function compile(filename: string, callback: (err: Error, parsed: IParsed) => void): void; + + export function compileText(name: string, template: string, callback: (err: Error, parsed: IParsed) => void): void; + export function compileText(name: string, template: string): IParsed; + export function compileText(template: string): IParsed; + + export function render(filenameOrParsed: string, view: any): NodeJS.ReadableStream; + export function render(filenameOrParsed: IParsed, view: any): NodeJS.ReadableStream; + + export function renderText(template: string, view: any, partials?: any): NodeJS.ReadableStream; + + export function clearCache(templateName?: string): void; + + export interface IParsed { } +} diff --git a/nconf/nconf-tests.ts b/nconf/nconf-tests.ts new file mode 100644 index 0000000000..13b314af8e --- /dev/null +++ b/nconf/nconf-tests.ts @@ -0,0 +1,101 @@ +/// + +import nconf = require('nconf'); + +var value: any; +var num: number; +var bool: boolean; +var valueArr: any[]; +var str: string; +var strArr: string[]; +var p: nconf.Provider; +var opts: nconf.IOptions; +var fopts: nconf.IFileOptions; +var store: nconf.IStore; +var callback: (err: Error) => void; + +value = nconf.clear(str, callback); +value = nconf.get (str, callback); +value = nconf.merge(str, value, callback); +value = nconf.set (str, value, callback); +value = nconf.reset(callback); + +value = nconf.load(callback); +nconf.mergeSources(value); +value = nconf.loadSources(); +value = nconf.save(value, callback); + +p = nconf.add(str); +p = nconf.add(str, opts);; + +p = nconf.argv(); +p = nconf.argv(opts); + +p = nconf.env(); +p = nconf.env(opts); + +p = nconf.file(str); +p = nconf.file(str, fopts); +p = nconf.file(fopts); + +p = nconf.use(str); +p = nconf.use(str, opts); + +p = nconf.defaults(); +p = nconf.defaults(opts); + +nconf.init(); +nconf.init(opts); + +p = nconf.overrides(); +p = nconf.overrides(opts); +nconf.remove(str); +store = nconf.create(str, opts); + +str = nconf.key(value, value); +valueArr = nconf.path(value); +nconf.loadFiles(value, callback); +nconf.loadFilesSync(value, callback); + +// - - - - - - - - - - - - - - - - - - - - - - - - - + +str = store.type; +value = store.get(str); +bool = store.set(str, value); +bool = store.clear(str); +bool = store.merge(str, value); +bool = store.reset(callback); + +// - - - - - - - - - - - - - - - - - - - - - - - - - + +p = new nconf.Provider(opts); +value = p.stores; +valueArr = p.sources; + +value = p.clear(str, callback); +value = p.get(str, callback); +value = p.merge(str,value,callback); +value = p.set(str,value,callback); +value = p.reset(callback); + +value = p.load(callback); +p.mergeSources(value); +value = p.loadSources(); +value = p.save(value, callback); + +p = p.add(str); +p = p.add(str, opts); +p = p.argv(); +p = p.argv(opts); +p = p.env(); +p = p.env(opts); +p = p.file(str); +p = p.file(str, fopts); +p = p.file(fopts); +p = p.use(str, opts); + +p = p.defaults(opts); +p.init(opts); +p = p.overrides(opts); +p.remove(str); +store = p.create(str, opts); diff --git a/nconf/nconf.d.ts b/nconf/nconf.d.ts new file mode 100644 index 0000000000..2ebd18a150 --- /dev/null +++ b/nconf/nconf.d.ts @@ -0,0 +1,100 @@ +// Type definitions for nconf +// Project: https://github.com/flatiron/nconf +// Definitions by: Jeff Goddard +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/nconf.d.ts + +declare module "nconf" { + export var version: number; + export var stores: any; + export var sources: any[]; + + export function clear(key: string, callback?: ICallbackFunction): any; + export function get (key: string, callback?: ICallbackFunction): any; + export function merge(key: string, value: any, callback?: ICallbackFunction): any; + export function set (key: string, value: any, callback?: ICallbackFunction): any; + export function reset(callback?: ICallbackFunction): any; + + export function load(callback?: ICallbackFunction): any; + export function mergeSources(data: any): void; + export function loadSources(): any; + export function save(value: any, callback?: ICallbackFunction): any; + + export function add(name: string, options?: IOptions): Provider; + export function argv(options?: IOptions): Provider; + export function env(options?: IOptions): Provider; + export function file(name: string, options?: IFileOptions): Provider; + export function file(options: IFileOptions): Provider; + export function use(name: string, options?: IOptions): Provider; + export function defaults(options?: IOptions): Provider; + export function init(options?: IOptions): void; + export function overrides(options?: IOptions): Provider; + export function remove(name: string): void; + export function create(name: string, options: IOptions): IStore; + + export function key(...values: any[]): string; + export function path(key: any): any[]; + export function loadFiles(files: any, callback?: ICallbackFunction): void; + export function loadFilesSync(files: any, callback?: ICallbackFunction): void; + + export enum formats { + json, + ini + } + + export interface IOptions { + type?: string; + } + + export interface IFileOptions extends IOptions { + file?: string; + dir?: string; + search?: boolean; + json_spacing?: number; + } + + export interface ICallbackFunction { + (err: Error): void; + } + + export class Provider { + constructor(options: IOptions); + + stores: any; + sources: any[]; + + clear(key: string, callback?: ICallbackFunction): any; + get (key: string, callback?: ICallbackFunction): any; + merge(key: string, value: any, callback?: ICallbackFunction): any; + set (key: string, value: any, callback?: ICallbackFunction): any; + reset(callback?: ICallbackFunction): any; + + load(callback?: ICallbackFunction): any; + mergeSources(data: any): void; + loadSources(): any; + save(value: any, callback?: ICallbackFunction): any; + + add(name: string, options?: IOptions): Provider; + argv(options?: IOptions): Provider; + env(options?: IOptions): Provider; + file(name: string, options?: IFileOptions): Provider; + file(options: IFileOptions): Provider; + use(name: string, options?: IOptions): Provider; + + defaults(options?: IOptions): Provider; + init(options?: IOptions): void; + overrides(options?: IOptions): Provider; + remove(name: string): void; + create(name: string, options: IOptions): IStore; + } + + export interface IStore { + type: string; + get (key: string): any; + set (key: string, value: any): boolean; + clear(key: string): boolean; + merge(key: string, value: any): boolean; + reset(callback?: ICallbackFunction): boolean; + } +} diff --git a/ncp/ncp-tests.ts b/ncp/ncp-tests.ts new file mode 100644 index 0000000000..f1ce04c21e --- /dev/null +++ b/ncp/ncp-tests.ts @@ -0,0 +1,32 @@ +/// + +import ncp = require('ncp'); +import stream = require('stream'); + +var opts: ncp.Options; +opts = {}; +opts = { + filter: /abc/ +}; +opts = { + transform: (read: NodeJS.ReadableStream, write: NodeJS.WritableStream) => { + + } +}; +opts = { + clobber: false +}; +opts = { + stopOnErr: false +}; +opts = { + errs: new stream.Writable() +}; + +ncp.ncp('foo', 'bar', (err: Error) => { + +}); + +ncp.ncp('foo', 'bar', opts, (err: Error) => { + +}); diff --git a/ncp/ncp.d.ts b/ncp/ncp.d.ts new file mode 100644 index 0000000000..206d3a18e8 --- /dev/null +++ b/ncp/ncp.d.ts @@ -0,0 +1,19 @@ +// Type definitions for ncp v0.5.1 +// Project: https://github.com/AvianFlu/ncp +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'ncp' { + function ncp (source: string, destination: string, callback: (err: Error) => void): void; + function ncp (source: string, destination: string, options: Options, callback: (err: Error) => void): void; + + interface Options { + filter? : RegExp; + transform? : (read: NodeJS.ReadableStream, write: NodeJS.WritableStream) => void; + clobber? : boolean; + stopOnErr? : boolean; + errs? : NodeJS.WritableStream; + } +} diff --git a/ng-grid/ng-grid-tests.ts b/ng-grid/ng-grid-tests.ts index 53763b1a51..82105ea5b7 100644 --- a/ng-grid/ng-grid-tests.ts +++ b/ng-grid/ng-grid-tests.ts @@ -1,4 +1,5 @@ -/// +/// +/// var options1: ngGrid.IGridOptions = { data: [{ 'Name': 'Bob' }, { 'Name': 'Jane' }] @@ -25,3 +26,288 @@ var options4: ngGrid.IGridOptions = { currentPage: 1 } }; + +var columnDef: ngGrid.IColumnDef = { + width:{}, + minWidth:{}, + visible:false, + field:'', + displayName:'', + sortable:false, + resizable:false, + groupable:false, + pinnable:false, + editableCellTemplate:'', + enableCellEdit:false, + cellEditableCondition:'', + sortFn:(a:any, b:any):number=> { return 0 }, + cellTemplate:'', + cellClass:'', + headerClass:'', + headerCellTemplate:'', + cellFilter:'', + aggLabelFilter:'', + pinned:false +} + +var searchProvider: ngGrid.ISearchProvider = {}; +searchProvider.fieldMap = {}; +searchProvider.extFilter = false; +searchProvider.evalFilter(); + +var nr:number; + +var selectionProvider: ngGrid.ISelectionProvider = {}; +selectionProvider.multi = false; +selectionProvider.selectedItems = []; +selectionProvider.selectedIndex = 1; +selectionProvider.lastClickedRow = {}; +selectionProvider.ignoreSelectedItemChanges = false; +selectionProvider.pKeyParser = {}; +selectionProvider.ChangeSelection({}, {}); +nr = selectionProvider.getSelection({}); +nr = selectionProvider.getSelectionIndex({}); +selectionProvider.setSelection({}, false); +selectionProvider.toggleSelectAll(true, false, false); + +var eventProvider: ngGrid.IEventProvider = {}; +eventProvider.colToMove = {}; +eventProvider.groupToMove = {}; +eventProvider.assignEvents(); +eventProvider.assignGridEventHandlers(); +eventProvider.dragStart({}); +eventProvider.dragOver({}); +eventProvider.setDraggables(); +eventProvider.onGroupMouseDown({}); +eventProvider.onGroupDrop({}); +eventProvider.onHeaderMouseDown({}); +eventProvider.onHeaderDrop({}); + +var aggregate: ngGrid.IAggregate = {}; +aggregate.rowIndex = 0; +aggregate.offsetTop = 0; +aggregate.entity = {}; +aggregate.label = ''; +aggregate.field = ''; +aggregate.depth = 0; +aggregate.parent = {}; +aggregate.children = []; +aggregate.aggChildren = []; +aggregate.aggIndex = 0; +aggregate.collapsed = false; +aggregate.groupInitState = false; +aggregate.rowFactory = {}; +aggregate.rowHeight = 0; +aggregate.isAggRow = false; +aggregate.offsetLeft = 0; +aggregate.aggLabelFilter = {}; + +var rowConfig: ngGrid.IRowConfig = {}; +rowConfig.enableCellSelection = false; +rowConfig.enableRowSelection = false; +rowConfig.jqueryUITheme = false; +rowConfig.rowClasses = ['']; +rowConfig.rowHeight = 0; +rowConfig.selectWithCheckboxOnly = false; +rowConfig.selectedItems = []; +rowConfig.afterSelectionChangeCallback(); +rowConfig.beforeSelectionChangeCallback(); + +var renderedRange: ngGrid.IRenderedRange = {}; +renderedRange.bottomRow = 0; +renderedRange.topRow = 0; + +var rowFactory: ngGrid.IRowFactory = {}; +rowFactory.aggCache= null; +rowFactory.dataChanged= false; +rowFactory.groupedData= null; +rowFactory.numberOfAggregates = 0; +rowFactory.parentCache= []; +rowFactory.parsedData= []; +rowFactory.renderedRange = {}; +rowFactory.rowConfig = {}; +rowFactory.rowHeight = 0; +rowFactory.selectionProvider = {}; +rowFactory.UpdateViewableRange({}); +aggregate = rowFactory.buildAggregateRow({}, 0); +var row:ngGrid.IRow = rowFactory.buildEntityRow({}, 0); +rowFactory.filteredRowsChanged(); +rowFactory.fixRowCache(); +rowFactory.getGrouping({}); +rowFactory.parseGroupData({}); +rowFactory.renderedChange(); +rowFactory.renderedChangeNoGroups(); + +var dimension: ngGrid.IDimension = {}; +dimension.outerHeight = 0; +dimension.outerWidth = 0; +dimension.autoFitHeight = false; + +var elmDimension: ngGrid.IElementDimension = {}; +elmDimension.rootMaxH = 0; +elmDimension.rootMaxW = 0; +elmDimension.rowIndexCellW = 0; +elmDimension.rowSelectedCellW = 0; +elmDimension.scrollH = 0; +elmDimension.scrollW = 0; + +var row: ngGrid.IRow = {}; +row.entity= {}; +row.config = {}; +row.selectionProvider = {}; +row.rowIndex = 0; +row.utils= {}; +row.selected = false; +row.cursor = ''; +row.offsetTop = 0; +row.rowDisplayIndex = 0; +row.afterSelectionChange(); +row.beforeSelectionChange(); +row.setSelection(false); +row.continueSelection({}); +row.ensureEntity({}); +var b:boolean = row.toggleSelected({}); +row.alternatingRowClass(); +var a:any = row.getProperty(''); +var r:ngGrid.IRow = row.copy(); +row.setVars({}); + +var column: ngGrid.IColumn = {}; +column.colDef = {}; +column.width = 0; +column.groupIndex = 0; +column.isGroupedBy = false; +column.minWidth = 0; +column.maxWidth = 0; +column.enableCellEdit = false; +column.cellEditableCondition = {}; +column.headerRowHeight = 0; +column.displayName = ''; +column.index = 0; +column.isAggCol = false; +column.cellClass = ''; +column.sortPriority = 0; +column.cellFilter = {}; +column.field = ''; +column.aggLabelFilter = {}; +column.visible = false; +column.sortable = false; +column.resizable = false; +column.pinnable = false; +column.pinned = false; +column.originalIndex = 0; +column.groupable = false; +column.sortDirection = ''; +column.sortingAlgorithm = ()=>{}; +column.headerClass = ''; +column.cursor = ''; +column.headerCellTemplate = ''; +column.cellTemplate = ''; +var s:string = column.groupedByClass(); +column.toggleVisible(); +b = column.showSortButtonUp(); +b = column.showSortButtonDown(); +b = column.noSortVisible(); +b = column.sort({}); +a = column.gripClick(); +a = column.gripOnMouseDown({}); +column.onMouseMove({}); +column.gripOnMouseUp({}); +var c:ngGrid.IColumn = column.copy(); +column.setVars(c); + +var gridScope: ngGrid.IGridScope = {}; +gridScope.elementsNeedMeasuring = false; +gridScope.columns = []; +gridScope.renderedRows = []; +gridScope.renderedColumns = []; +gridScope.headerRow = {}; +gridScope.rowHeight = 0; +gridScope.jqueryUITheme = {}; +gridScope.showSelectionCheckbox = false; +gridScope.enableCellSelection = false; +gridScope.enableCellEditOnFocus = false; +gridScope.footer = {}; +gridScope.selectedItems = []; +gridScope.multiSelect = false; +gridScope.showFooter = false; +gridScope.footerRowHeight = 0; +gridScope.showColumnMenu = false; +gridScope.forceSyncScrolling = false; +gridScope.showMenu = false; +gridScope.configGroups = []; +gridScope.gridId = ''; +gridScope.enablePaging = false; +gridScope.pagingOptions = {}; +gridScope.i18n = {}; +gridScope.selectionProvider = {}; +gridScope.adjustScrollLeft(0); +gridScope.adjustScrollTop(0, true); +gridScope.toggleShowMenu(); +gridScope.toggleSelectAll(); +nr = gridScope.totalFilteredItemsLength(); +a = gridScope.showGroupPanel(); +nr = gridScope.topPanelHeight(); +nr = gridScope.viewportDimHeight(); +gridScope.groupBy({}); +gridScope.removeGroup(0); +gridScope.togglePin({}); +nr = gridScope.totalRowWidth(); +a = gridScope.headerScrollerDim(); + +var gridInstance: ngGrid.IGridInstance = {}; +gridInstance.$canvas = {}; +gridInstance.$viewport = {}; +gridInstance.$groupPanel = {}; +gridInstance.$footerPanel = {}; +gridInstance.$headerScroller = {}; +gridInstance.$headerContainer = {}; +gridInstance.$headers = {}; +gridInstance.$topPanel = {}; +gridInstance.$root = {}; +gridInstance.config = {}; +gridInstance.data = {}; +gridInstance.elementDims = {}; +gridInstance.eventProvider = {}; +gridInstance.filteredRows = [{}]; +gridInstance.footerController = {}; +gridInstance.gridId = ''; +gridInstance.lastSortedColumns = [{}]; +gridInstance.lateBindColumns = false; +gridInstance.maxCanvasHt = 0; +gridInstance.prevScrollIndex = 0; +gridInstance.prevScrollTop = 0; +gridInstance.rootDim = {}; +gridInstance.rowCache = [{}]; +gridInstance.rowFactory = {}; +gridInstance.rowMap = [{}]; +gridInstance.searchProvider = {}; +gridInstance.styleProvider = {}; +gridInstance.buildColumnDefsFromData(); +gridInstance.buildColumns(); +gridInstance.calcMaxCanvasHeight(); +gridInstance.clearSortingData(); +gridInstance.configureColumnWidths(); +gridInstance.fixColumnIndexes(); +gridInstance.fixGroupIndexes(); +var p:ng.IPromise = gridInstance.getTemplate(''); +p = gridInstance.init(); +p = gridInstance.initTemplates(); +gridInstance.minRowsToRender(); +gridInstance.refreshDomSizes(); +gridInstance.resizeOnData({}); +gridInstance.setRenderedRows([{}]); +gridInstance.sortActual(); +gridInstance.sortColumnsInit(); +gridInstance.sortData({}, {}); + +var test_styleProvider:ngGrid.IStyleProvider = new ngStyleProvider({}, {}); +var test_searchProvider:ngGrid.ISearchProvider = new ngSearchProvider({}, {}, {}); +var test_selectionProvider:ngGrid.ISelectionProvider = new ngSelectionProvider({}, {}, {}); +var test_eventProvider:ngGrid.IEventProvider = new ngEventProvider({}, {}, {}, {}); +var test_aggregate:ngGrid.IAggregate = new ngAggregate({}, {}, 10, true); +var test_renderedRange:ngGrid.IRenderedRange = new ngRenderedRange(1, 2); +var test_dimension:ngGrid.IDimension = new ngDimension({}); +var test_row:ngGrid.IRow = new ngRow({}, {}, {}, 0, {}); +var test_column:ngGrid.IColumn = new ngColumn({}, {}, {}, {}, {}, {}); +var test_footer:ngGrid.IFooter = new ngFooter({}, {}); diff --git a/ng-grid/ng-grid.d.ts b/ng-grid/ng-grid.d.ts index 70f4f569f8..3bb3b2daab 100644 --- a/ng-grid/ng-grid.d.ts +++ b/ng-grid/ng-grid.d.ts @@ -1,23 +1,358 @@ // Type definitions for ng-grid // Project: http://angular-ui.github.io/ng-grid/ -// Definitions by: Ken Smith -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: Ken Smith , Roland Zwaga , Kent Cooper +// Definitions: https://github.com/borisyankov/DefinitelyTyped // These are very definitely preliminary. Please feel free to improve. +// Changelog: +// 25/4/2014: Added interfaces for all classes and services + +/// + declare class ngGridReorderable { constructor(); } +declare var ngStyleProvider:ngGrid.IStyleProviderStatic; +declare var ngSearchProvider:ngGrid.ISearchProviderStatic; +declare var ngSelectionProvider:ngGrid.ISelectionProviderStatic; +declare var ngEventProvider:ngGrid.IEventProviderStatic; +declare var ngAggregate:ngGrid.IAggregateStatic; +declare var ngRenderedRange:ngGrid.IRenderedRangeStatic; +declare var ngDimension:ngGrid.IDimensionStatic; +declare var ngRow:ngGrid.IRowStatic; +declare var ngColumn:ngGrid.IColumnStatic; +declare var ngFooter:ngGrid.IFooterStatic; + declare module ngGrid { + export interface IDomAccessProvider { + previousColumn:IColumn; + grid:IGridInstance; + changeUserSelect(elm:ng.IAugmentedJQuery, value:string):void; + focusCellElement($scope:IGridScope, index:number):void; + selectionHandlers($scope:IGridScope, elm:ng.IAugmentedJQuery):void; + } + + export interface IStyleProviderStatic { + new($scope:IGridScope, grid:IGridInstance):IStyleProvider; + } + + export interface IStyleProvider { + } + + export interface ISearchProviderStatic { + new($scope:IGridScope, grid:IGridInstance, $filter:ng.IFilterService):ISearchProvider; + } + + export interface ISearchProvider { + fieldMap:any; + extFilter:boolean; + evalFilter():void; + } + + export interface ISelectionProviderStatic { + new(grid:IGridInstance, $scope:IGridScope, $parse:ng.IParseService):ISelectionProvider; + } + + export interface ISelectionProvider { + multi:boolean; + selectedItems:any[]; + selectedIndex:number; + lastClickedRow:any; + ignoreSelectedItemChanges:boolean; + pKeyParser:ng.ICompiledExpression; + ChangeSelection(rowItem:any, event:any):void; + getSelection(entity:any):number; + getSelectionIndex(entity:any):number; + setSelection(rowItem:IRow, isSelected:boolean):void; + toggleSelectAll(checkAll:boolean, bypass:boolean, selectFiltered:boolean):void; + } + + export interface IEventProviderStatic { + new(grid:IGridInstance, $scope:IGridScope, domUtilityService:service.IDomUtilityService, $timeout:ng.ITimeoutService):IEventProvider; + } + + export interface IEventProvider { + colToMove:IColumn; + groupToMove:any; + assignEvents():void; + assignGridEventHandlers():void; + dragStart(event:any):void; + dragOver(event:any):void; + setDraggables():void; + onGroupMouseDown(event:any):void; + onGroupDrop(event:any):void; + onHeaderMouseDown(event:any):void; + onHeaderDrop(event:any):void; + } + + export interface IAggregateStatic { + new(aggEntity:any, rowFactory:IRowFactory, rowHeight:number, groupInitState:boolean):IAggregate; + } + + export interface IAggregate { + rowIndex:number; + offsetTop:number; + entity:any; + label:string; + field:string; + depth:number; + parent:any; + children:any[]; + aggChildren:any[]; + aggIndex:number; + collapsed:boolean; + groupInitState:boolean; + rowFactory:IRowFactory; + rowHeight:number; + isAggRow:boolean; + offsetLeft:number; + aggLabelFilter:any; + } + + export interface IRowConfig { + enableCellSelection:boolean; + enableRowSelection:boolean; + jqueryUITheme:boolean; + rowClasses:string[]; + rowHeight:number; + selectWithCheckboxOnly:boolean; + selectedItems:any[]; + + afterSelectionChangeCallback():void; + beforeSelectionChangeCallback():void; + } + + export interface IRenderedRangeStatic { + new(top:number, bottom:number):IRenderedRange; + } + + export interface IRenderedRange { + bottomRow:number; + topRow:number; + } + + export interface IRowFactory { + aggCache:any; + dataChanged:boolean; + groupedData:any; + numberOfAggregates:number; + parentCache:any[]; + parsedData:any[]; + renderedRange:IRenderedRange; + rowConfig:IRowConfig; + rowHeight:number; + selectionProvider:ISelectionProvider; + + UpdateViewableRange(newRange:IRenderedRange):void; + buildAggregateRow(aggEntity:any, rowIndex:number):IAggregate; + buildEntityRow(entity:any, rowIndex:number):IRow; + filteredRowsChanged():void; + fixRowCache():void; + getGrouping(groups:any):void; + parseGroupData(groupData:any):void; + renderedChange():void; + renderedChangeNoGroups():void; + } + + export interface IDimensionStatic { + new(options:any):IDimension; + } + + export interface IDimension { + outerHeight?:number; + outerWidth?:number; + autoFitHeight?:boolean; + } + + export interface IElementDimension { + rootMaxH?:number; + rootMaxW?:number; + rowIndexCellW?:number; + rowSelectedCellW?:number; + scrollH?:number; + scrollW?:number; + } + + export interface IRowStatic { + new(entity:any, config:IRowConfig, selectionProvider:ISelectionProvider, rowIndex:number, $utils:any):IRow; + } + + export interface IRow { + entity:any; + config:IRowConfig; + selectionProvider:ISelectionProvider; + rowIndex:number; + utils:any; + selected:boolean; + cursor:string; + offsetTop:number; + rowDisplayIndex:number; + afterSelectionChange():void; + beforeSelectionChange():void; + setSelection(isSelected:boolean):void; + continueSelection(event:any):void; + ensureEntity(expected:any):void; + toggleSelected(event:any):boolean; + alternatingRowClass():void; + getProperty(path:string):any; + copy():IRow; + setVars(fromRow:IRow):void; + } + + export interface IColumnStatic { + new(config:IGridOptions, $scope:IGridScope, grid:IGridInstance, domUtilityService:service.IDomUtilityService, $templateCache:ng.ITemplateCacheService, $utils:any):IColumn; + } + + export interface IColumn { + colDef:IColumnDef; + width:number; + groupIndex:number; + isGroupedBy:boolean; + minWidth:number; + maxWidth:number; + enableCellEdit:boolean; + cellEditableCondition:any; + headerRowHeight:number; + displayName:string; + index:number; + isAggCol:boolean; + cellClass:string; + sortPriority:number; + cellFilter:any; + field:string; + aggLabelFilter:any; + visible:boolean; + sortable:boolean; + resizable:boolean; + pinnable:boolean; + pinned:boolean; + originalIndex:number; + groupable:boolean; + sortDirection:string; + sortingAlgorithm:Function; + headerClass:string; + cursor:string; + headerCellTemplate:string; + cellTemplate:string; + groupedByClass():string; + toggleVisible():void; + showSortButtonUp():boolean; + showSortButtonDown():boolean; + noSortVisible():boolean; + sort(event:any):boolean; + gripClick():any; + gripOnMouseDown(event:any):any; + onMouseMove(event:any):void; + gripOnMouseUp(event:any):void; + copy():IColumn; + setVars(fromCol:IColumn):void; + } + + export interface IGridScope extends ng.IScope { + elementsNeedMeasuring:boolean; + columns:any[]; + renderedRows:any[]; + renderedColumns:any[]; + headerRow:any; + rowHeight:number; + jqueryUITheme:any; + showSelectionCheckbox:boolean; + enableCellSelection:boolean; + enableCellEditOnFocus:boolean; + footer:IFooter; + selectedItems:any[]; + multiSelect:boolean; + showFooter:boolean; + footerRowHeight:number; + showColumnMenu:boolean; + forceSyncScrolling:boolean; + showMenu:boolean; + configGroups:any[]; + gridId:string; + enablePaging:boolean; + pagingOptions:IPagingOptions; + i18n:any; + selectionProvider:ISelectionProvider; + adjustScrollLeft(scrollLeft:number):void; + adjustScrollTop(scrollTop:number, force:boolean):void; + toggleShowMenu():void; + toggleSelectAll():void; + totalFilteredItemsLength():number; + showGroupPanel():any; + topPanelHeight():number; + viewportDimHeight():number; + groupBy(col:IColumn):void; + removeGroup(index:number):void; + togglePin(col:IColumn):void; + totalRowWidth():number; + headerScrollerDim():any; + } + + export interface IGridInstance { + $canvas:ng.IAugmentedJQuery; + $viewport:ng.IAugmentedJQuery; + $groupPanel:ng.IAugmentedJQuery; + $footerPanel:ng.IAugmentedJQuery; + $headerScroller:ng.IAugmentedJQuery; + $headerContainer:ng.IAugmentedJQuery; + $headers:ng.IAugmentedJQuery; + $topPanel:ng.IAugmentedJQuery; + $root:ng.IAugmentedJQuery; + config:IGridOptions; + data:any; + elementDims:IElementDimension; + eventProvider:IEventProvider; + filteredRows:IRow[]; + footerController:any; + gridId:string; + lastSortedColumns:IColumn[]; + lateBindColumns:boolean; + maxCanvasHt:number; + prevScrollIndex:number; + prevScrollTop:number; + rootDim:IDimension; + rowCache:IRow[]; + rowFactory:IRowFactory; + rowMap:IRow[]; + searchProvider:ISearchProvider; + styleProvider:IStyleProvider; + + buildColumnDefsFromData():void; + buildColumns():void; + calcMaxCanvasHeight():void; + clearSortingData():void; + configureColumnWidths():void; + fixColumnIndexes():void; + fixGroupIndexes():void; + getTemplate(key:string):ng.IPromise; + init():ng.IPromise; + initTemplates():ng.IPromise; + minRowsToRender():void; + refreshDomSizes():void; + resizeOnData(col:IColumn):void; + setRenderedRows(newRows:IRow[]):void; + sortActual():void; + sortColumnsInit():void; + sortData(col:IColumn, event:any):void; + } + + export interface IFooterStatic { + new($scope:IGridScope, grid:IGridInstance):IFooter; + } + + export interface IFooter { + } + export interface IGridOptions { /** Define an aggregate template to customize the rows when grouped. See github wiki for more details. */ aggregateTemplate?: string; /** Callback for when you want to validate something after selection. */ - afterSelectionChange?: (rowItem?: any, event?: any) => void ; + afterSelectionChange?: (rowItem?: IRow, event?: any) => void ; /** Callback if you want to inspect something before selection, return false if you want to cancel the selection. return true otherwise. @@ -25,7 +360,7 @@ declare module ngGrid { use rowItem.changeSelection(event) method after returning false initially. Note: when shift+ Selecting multiple items in the grid this will only get called once and the rowItem will be an array of items that are queued to be selected. */ - beforeSelectionChange?: (rowItem?: any, event?: any) => boolean ; + beforeSelectionChange?: (rowItem?: IRow, event?: any) => boolean ; /** checkbox templates. */ checkboxCellTemplate?: string; @@ -176,11 +511,68 @@ declare module ngGrid { } export interface IColumnDef { + /** + * This can be an absolute numberor it can also be defined in percentages (20%, 30%), + * in weighted *s, or "auto" (which sizes the column based on data length) + * (much like WPF/Silverlight)/ note: "auto" only works in single page apps currently because the re-size + * happens on "document.ready + */ + width?: any; + + /** The minum width the column is allowed to be. See width for the different options */ + minWidth?: any; + + /** Set the default visiblity of the column */ + visible?: boolean; + + /** Can also be a property path on your data model. "foo.bar.myField", "Name.First", etc..*/ field?: string; - width?: any; //**this can be a string containing a relatively, absolute size units or a number: '30%','54px',45 /* + + /** What to display in the column header */ displayName?: string; - cellTemplate?: string; + + /** Restrict or allow the column to be sorted */ + sortable?: boolean; + + /** Restrict or allow the column to be resized */ + resizable?: boolean; + + /** Allows the column to be grouped with drag and drop, but has no effect on gridOptions.groups */ + groupable?: boolean; + + /** Allows the column to be pinned when enablePinning is set to true */ + pinnable?: boolean; + + /** The template to use while editing */ + editableCellTemplate?: string; + + /** Allows the cell to use an edit template when focused (grid option enableCellSelection must be enabled)*/ enableCellEdit?: boolean; + + /** Controls when to use the edit template on per-row basis using an angular expression (enableCellEdit must also be true for editing)*/ + cellEditableCondition?: string; + + /** The funtion to use when filtering values in this column */ + sortFn?: (a: any, b: any) => number; + + /** Html template used to render the cell */ + cellTemplate?: string; + + /** User defined CSS class name */ + cellClass?: string; + + /** User defined CSS class name for the header cell */ + headerClass?: string; + + /** Html template used to render the header cell */ + headerCellTemplate?: string; + + /** string name for filter to use on the cell ('currency', 'date', etc..) */ + cellFilter?: string; + + /** String name for filter to use on the aggregate label ('currency', 'date', etc..) defaults to cellFilter if not set. */ + aggLabelFilter?: string; + pinned?: boolean; } @@ -199,4 +591,60 @@ declare module ngGrid { /** currentPage: the uhm... current page. */ currentPage?: number; } + + export interface IPlugin { + init(childScope:IGridScope, gridInstance:IGridInstance, services:any):void; + } + + export module service { + + export interface IDomUtilityService { + eventStorage:any; + numberOfGrids:number; + immediate:number; + AssignGridContainers($scope:IGridScope, rootel:ng.IAugmentedJQuery, grid:IGridInstance):void; + getRealWidth(obj:IDimension):number; + UpdateGridLayout($scope:IGridScope, grid:IGridInstance):void; + setStyleText(grid:IGridInstance, css:string):void; + BuildStyles($scope:IGridScope, grid:IGridInstance, digest:boolean):void; + setColLeft(col:IColumn, colLeft:number, grid:IGridInstance):void; + RebuildGrid($scope:IGridScope, grid:IGridInstance):void; + digest($scope:IGridScope):void; + ScrollH:number; + ScrollW:number; + LetterW:number; + } + + export interface ISortInfo { + fields:string[]; + } + + export interface ISortService { + colSortFnCache:any; + isCustomSort:boolean; + isSorting:boolean; + guessSortFn(item:any):(a:any, b:any)=>number; + basicSort(a:any, b:any):number; + sortNumber(a:number, b:number):number; + sortNumberStr(a:string, b:string):number; + sortAlpha(a:string, b:string):number; + sortDate(a:Date, b:Date):number; + sortBool(a:boolean, b:boolean):number; + sortData(sortInfo:ISortInfo, data:any):void; + Sort(sortInfo:ISortInfo, data:any):void; + getSortFn(col:IColumn, data:any):(a:any, b:any)=>number; + } + + export interface IUtilityService { + visualLength(node:any):number; + forIn(obj:any, action:(value:any, property:string)=>{}):void; + evalProperty(entity:any, path:string):any; + endsWith(str:string, suffix:string):boolean; + isNullOrUndefined(obj:any):boolean; + getElementsByClassName(cl:string):any[]; + newId():string; + seti18n($scope:IGridScope, language:string):void; + getInstanceType(o:any):string; + } + } } diff --git a/ngprogress-lite/ngprogress-lite-tests.ts b/ngprogress-lite/ngprogress-lite-tests.ts new file mode 100644 index 0000000000..a6d68f08fe --- /dev/null +++ b/ngprogress-lite/ngprogress-lite-tests.ts @@ -0,0 +1,30 @@ +/// +/// + +var app = angular.module('testApp', ['ngProgressLite']); + +app.config( + ['ngProgressLiteProvider', + (ngProgressLiteProvider: ng.progressLite.INgProgressLiteProvider) => { + ngProgressLiteProvider.settings.ease = 'ease'; + ngProgressLiteProvider.settings.minimum = 0.08, + ngProgressLiteProvider.settings.speed = 300; + ngProgressLiteProvider.settings.trickleRate = 0.02; + ngProgressLiteProvider.settings.trickleSpeed = 500; + ngProgressLiteProvider.settings.template = '
    '; + } + ]); + +app.controller('testCtrl', ($scope: ng.IScope, ngProgressLite : ng.progressLite.INgProgressLite) => { + + ngProgressLite.set(0.4); + + ngProgressLite.get(); + + ngProgressLite.inc(); + ngProgressLite.inc(0.1); + + ngProgressLite.start(); + + ngProgressLite.done(); +}); \ No newline at end of file diff --git a/ngprogress-lite/ngprogress-lite.d.ts b/ngprogress-lite/ngprogress-lite.d.ts new file mode 100644 index 0000000000..bdee716732 --- /dev/null +++ b/ngprogress-lite/ngprogress-lite.d.ts @@ -0,0 +1,28 @@ +// Type definitions for ngprogress-lite +// Project: https://github.com/voronianski/ngprogress-lite +// Definitions by: Luke Forder +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module ng.progressLite { + + export interface INgProgressLite { + set(num: number): INgProgressLite; + get(): number; + start(): INgProgressLite; + inc(amount?: number): INgProgressLite; + done(): void; + } + + export interface IConfigurationOptions { + minimum: number; + speed: number; + ease: string; + trickleRate: number; + trickleSpeed: number; + template: string; + } + + export interface INgProgressLiteProvider { + settings: IConfigurationOptions; + } +} \ No newline at end of file diff --git a/noble/noble-tests.ts b/noble/noble-tests.ts new file mode 100644 index 0000000000..4b1d396564 --- /dev/null +++ b/noble/noble-tests.ts @@ -0,0 +1,98 @@ +/// + +import noble = require("noble"); + +function test_startScanning(): void { + "use strict"; + noble.startScanning(); + noble.startScanning(["0x180d"]); + noble.startScanning(["0x180d"], true); +} +test_startScanning(); + +function test_stopScanning(): void { + "use strict"; + noble.stopScanning(); +} +test_stopScanning(); + +noble.on("stateChange", (state: string): void => {}); +noble.on("scanStart", (): void => {}); +noble.on("scanStop", (): void => {}); +noble.on("discover", (peripheral: noble.Peripheral): void => { + peripheral.connect((error: string): void => {}); + peripheral.disconnect((): void => {}); +}); + +var peripheral: noble.Peripheral = new noble.Peripheral(); +peripheral.uuid = "12ad4e81"; +peripheral.advertisement = { + localName: "device", + serviceData: new Buffer(1), + txPowerLevel: 1, + manufacturerData: new Buffer(1), + serviceUuids: ["0x180a", "0x180d"] +}; +peripheral.connect(); +peripheral.connect((error: string): void => {}); +peripheral.disconnect(); +peripheral.disconnect((): void => {}); +peripheral.updateRssi(); +peripheral.updateRssi((error: string, rssi: number): void => {}); +peripheral.discoverServices(["180d"]); +peripheral.discoverServices(["180d"], (error: string, services: noble.Service[]): void => {}); +peripheral.discoverAllServicesAndCharacteristics(); +peripheral.discoverAllServicesAndCharacteristics((error: string, services: noble.Service[], characteristics: noble.Characteristic[]): void => {}); +peripheral.discoverSomeServicesAndCharacteristics(["180d"], ["2a38"]); +peripheral.discoverSomeServicesAndCharacteristics(["180d"], ["2a38"], (error: string, services: noble.Service[], characteristics: noble.Characteristic[]): void => {}); +peripheral.readHandle(new Buffer(1), (error: string, data: NodeBuffer): void => {}); +peripheral.writeHandle(new Buffer(1), new Buffer(1), true, (error: string): void => {}); +peripheral.on("connect", (error: string): void => {}); +peripheral.on("disconnect", (error: string): void => {}); +peripheral.on("rssiUpdate", (rssi: number): void => {}); +peripheral.on("servicesDiscover", (services: noble.Service[]): void => {}); + +var service: noble.Service = new noble.Service(); +service.uuid = "180a"; +service.name = ""; +service.type = ""; +service.includedServiceUuids = ["180d"]; +service.discoverIncludedServices(["180d"]); +service.discoverIncludedServices(["180d"], (error: string, includedServiceUuids: string[]): void => {}); +service.discoverCharacteristics(["2a38"]); +service.discoverCharacteristics(["2a38"], (error: string, characteristics: noble.Characteristic[]): void => {}); +service.on("includedServicesDiscover", (includedServiceUuids: string[]): void => {}); +service.on("characteristicsDiscover", (characteristics: noble.Characteristic[]): void => {}); + +var characteristic: noble.Characteristic = new noble.Characteristic(); +characteristic.uuid = "2a37"; +characteristic.name = ""; +characteristic.type = ""; +characteristic.properties = ["read", "notify"]; +characteristic.read(); +characteristic.read((error: string, data: NodeBuffer): void => {}); +characteristic.write(new Buffer(1), true); +characteristic.write(new Buffer(1), true, (error: string): void => {}); +characteristic.broadcast(true); +characteristic.broadcast(true, (error: string): void => {}); +characteristic.notify(true); +characteristic.notify(true, (error: string): void => {}); +characteristic.discoverDescriptors(); +characteristic.discoverDescriptors((error: string, descriptors: noble.Descriptor[]): void => {}); +characteristic.on("read", (data: NodeBuffer, isNotification: boolean): void => {}); +characteristic.on("write", true, (error: string): void => {}); +characteristic.on("broadcast", (state: string): void => {}); +characteristic.on("notify", (state: string): void => {}); +characteristic.on("descriptorsDiscover", (descriptors: noble.Descriptor[]): void => {}); + +var descriptor: noble.Descriptor = new noble.Descriptor(); +descriptor.uuid = ""; +descriptor.name = ""; +descriptor.type = ""; +descriptor.readValue(); +descriptor.readValue((error: string, data: NodeBuffer): void => {}); +descriptor.writeValue(new Buffer(1)); +descriptor.writeValue(new Buffer(1), (error: string): void => {}); +descriptor.on("valueRead", (error: string, data: NodeBuffer): void => {}); +descriptor.on("valueWrite", (error: string): void => {}); + diff --git a/noble/noble.d.ts b/noble/noble.d.ts new file mode 100644 index 0000000000..fb0a7a491f --- /dev/null +++ b/noble/noble.d.ts @@ -0,0 +1,107 @@ +// Type definitions for noble +// Project: https://github.com/sandeepmistry/noble +// Definitions by: Seon-Wook Park +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "noble" { + import events = require("events"); + + export function startScanning(): void; + export function startScanning(serviceUUIDs: string[]): void; + export function startScanning(serviceUUIDs: string[], allowDuplicates: boolean): void; + export function stopScanning(): void; + + export function on(event: string, listener: Function): events.EventEmitter; + export function on(event: "stateChange", listener: (state: string) => void): events.EventEmitter; + export function on(event: "scanStart", listener: () => void): events.EventEmitter; + export function on(event: "scanStop", listener: () => void): events.EventEmitter; + export function on(event: "discover", listener: (peripheral: Peripheral) => void): events.EventEmitter; + + export class Peripheral extends events.EventEmitter { + uuid: string; + advertisement: Advertisement; + rssi: number; + services: string[]; + + connect(callback?: (error: string) => void): void; + disconnect(callback?: () => void): void; + updateRssi(callback?: (error: string, rssi: number) => void): void; + discoverServices(serviceUUIDs: string[], callback?: (error: string, services: Service[]) => void): void; + discoverAllServicesAndCharacteristics(callback?: (error: string, services: Service[], characteristics: Characteristic[]) => void): void; + discoverSomeServicesAndCharacteristics(serviceUUIDs: string[], characteristicUUIDs: string[], callback?: (error: string, services: Service[], characteristics: Characteristic[]) => void): void; + + readHandle(handle: NodeBuffer, callback: (error: string, data: NodeBuffer) => void): void; + writeHandle(handle: NodeBuffer, data: NodeBuffer, withoutResponse: boolean, callback: (error: string) => void): void; + toString(): string; + + on(event: string, listener: Function): events.EventEmitter; + on(event: "connect", listener: (error: string) => void): events.EventEmitter; + on(event: "disconnect", listener: (error: string) => void): events.EventEmitter; + on(event: "rssiUpdate", listener: (rssi: number) => void): events.EventEmitter; + on(event: "servicesDiscover", listener: (services: Service[]) => void): events.EventEmitter; + } + + export interface Advertisement { + localName: string; + serviceData: NodeBuffer; + txPowerLevel: number; + manufacturerData: NodeBuffer; + serviceUuids: string[]; + } + + export class Service extends events.EventEmitter { + uuid: string; + name: string; + type: string; + includedServiceUuids: string[]; + characteristics: Characteristic[]; + + discoverIncludedServices(serviceUUIDs: string[], callback?: (error: string, includedServiceUuids: string[]) => void): void; + discoverCharacteristics(characteristicUUIDs: string[], callback?: (error: string, characteristics: Characteristic[]) => void): void; + toString(): string; + + on(event: string, listener: Function): events.EventEmitter; + on(event: "includedServicesDiscover", listener: (includedServiceUuids: string[]) => void): events.EventEmitter; + on(event: "characteristicsDiscover", listener: (characteristics: Characteristic[]) => void): events.EventEmitter; + } + + export class Characteristic extends events.EventEmitter { + uuid: string; + name: string; + type: string; + properties: string[]; + descriptors: Descriptor[]; + + read(callback?: (error: string, data: NodeBuffer) => void): void; + write(data: NodeBuffer, notify: boolean, callback?: (error: string) => void): void; + broadcast(broadcast: boolean, callback?: (error: string) => void): void; + notify(notify: boolean, callback?: (error: string) => void): void; + discoverDescriptors(callback?: (error: string, descriptors: Descriptor[]) => void): void; + toString(): string; + + on(event: string, listener: Function): events.EventEmitter; + on(event: string, option: boolean, listener: Function): events.EventEmitter; + on(event: "read", listener: (data: NodeBuffer, isNotification: boolean) => void): events.EventEmitter; + on(event: "write", withoutResponse: boolean, listener: (error: string) => void): events.EventEmitter; + on(event: "broadcast", listener: (state: string) => void): events.EventEmitter; + on(event: "notify", listener: (state: string) => void): events.EventEmitter; + on(event: "descriptorsDiscover", listener: (descriptors: Descriptor[]) => void): events.EventEmitter; + } + + export class Descriptor extends events.EventEmitter { + uuid: string; + name: string; + type: string; + + readValue(callback?: (error: string, data: NodeBuffer) => void): void; + writeValue(data: NodeBuffer, callback?: (error: string) => void): void; + toString(): string; + + on(event: string, listener: Function): events.EventEmitter; + on(event: "valueRead", listener: (error: string, data: NodeBuffer) => void): events.EventEmitter; + on(event: "valueWrite", listener: (error: string) => void): events.EventEmitter; + } +} + diff --git a/nock/nock-tests.ts b/nock/nock-tests.ts new file mode 100644 index 0000000000..f3c166aa1a --- /dev/null +++ b/nock/nock-tests.ts @@ -0,0 +1,63 @@ +/// + +import nock = require('nock'); + +var inst: nock.Scope; +var str: string; +var bool: boolean; +var data: string; +var num: number; +var obj: {}; +var value: any; +var regex: RegExp; +var options: nock.Options; +var headers: Object; + +inst = inst.head(str); +inst = inst.get(str); +inst = inst.get(str, data); +inst = inst.post(str); +inst = inst.post(str, data); +inst = inst.put(str); +inst = inst.put(str, data); + +inst = inst.delete(str); +inst = inst.delete(str, data); + +inst = inst.intercept(str, str); +inst = inst.intercept(str, str, str); +inst = inst.intercept(str, str, str, value); + +inst = inst.reply(num); +inst = inst.reply(num, str); + +inst = inst.reply(num, str, headers); +inst = inst.reply(num, obj, headers); +inst = inst.reply(num, (uri: string, body: string) => { + return str; +}); +inst = inst.reply(num, (uri: string, body: string) => { + return str; +}, headers); +inst = inst.replyWithFile(num, str); + +inst = inst.defaultReplyHeaders(value); +inst = inst.matchHeader(str, str); + +inst = inst.filteringPath(regex, str); +inst = inst.filteringPath((path: string) => { + return str; +}); +inst = inst.filteringRequestBody(regex, str); +inst = inst.filteringRequestBody((path: string) => { + return str; +}); + +inst = inst.persist(); +inst = inst.log(() => { + +}); + +inst.done(); +bool = inst.isDone(); +inst.restore(); diff --git a/nock/nock.d.ts b/nock/nock.d.ts new file mode 100644 index 0000000000..40b728d491 --- /dev/null +++ b/nock/nock.d.ts @@ -0,0 +1,55 @@ +// Type definitions for nock +// Project: https://github.com/pgte/nock +// Definitions by: bonnici +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/nock.d.ts + +declare module "nock" { + export = nock; + + function nock (host: string, options?: nock.Options): nock.Scope; + + module nock { + export function cleanAll(): void; + export var recorder: Recorder; + + export interface Scope { + get(path: string, data?: string): Scope; + post(path: string, data?: string): Scope; + put(path: string, data?: string): Scope; + head(path: string): Scope; + delete(path: string, data?: string): Scope; + intercept(path: string, verb: string, body?: string, options?: any): Scope; + + reply(responseCode: number, body?: string, headers?: Object): Scope; + reply(responseCode: number, body?: Object, headers?: Object): Scope; + reply(responseCode: number, callback: (uri: string, body: string) => string, headers?: Object): Scope; + replyWithFile(responseCode: number, fileName: string): Scope; + + defaultReplyHeaders(headers: Object): Scope; + matchHeader(name: string, value: string): Scope; + + filteringPath(regex: RegExp, replace: string): Scope; + filteringPath(fn: (path: string) => string): Scope; + filteringRequestBody(regex: RegExp, replace: string): Scope; + filteringRequestBody(fn: (path: string) => string): Scope; + + persist(): Scope; + log(out: () => void): Scope; + + done(): void; + isDone(): boolean; + restore(): void; + } + + export interface Recorder { + rec(capture?: boolean): void; + play(): string[]; + } + + export interface Options { + allowUnmocked?: boolean; + } + } +} diff --git a/node-ffi/node-ffi-buffer.d.ts b/node-ffi/node-ffi-buffer.d.ts new file mode 100644 index 0000000000..5203a2d9ee --- /dev/null +++ b/node-ffi/node-ffi-buffer.d.ts @@ -0,0 +1,59 @@ +// DefinitelyTyped: partial + +interface Buffer { + /** Shorthand for `ref.address`. */ + address(): number; + /** Shorthand for `ref.deref`. */ + deref(): any; + /** Shorthand for `ref.isNull`. */ + isNull(): boolean; + /** Shorthand for `ref.readCString`. */ + readCString(offset?: number): string; + /** Shorthand for `ref.readInt64BE`. */ + readInt64BE(offset?: number): string; + /** Shorthand for `ref.readInt64LE`. */ + readInt64LE(offset?: number): string; + /** Shorthand for `ref.readObject`. */ + readObject(offset?: number): string; + /** Shorthand for `ref.readPointer`. */ + readPointer(offset?: number): string; + /** Shorthand for `ref.readUInt64BE`. */ + readUInt64BE(offset?: number): string; + /** Shorthand for `ref.readUInt64LE`. */ + readUInt64LE(offset?: number): string; + /** Shorthand for `ref.ref`. */ + ref(): Buffer; + /** Shorthand for `ref.reinterpret`. */ + reinterpret(size: number, offset?: number): Buffer; + /** Shorthand for `ref.reinterpretUntilZeros`. */ + reinterpretUntilZeros(size: number, offset?: number): Buffer; + /** Shorthand for `ref.writeCString`. */ + writeCString(offset: number, string: string, encoding?: string): void; + /** Shorthand for `ref.writeInt64BE`. */ + writeInt64BE(offset: number, input: number): any; + /** Shorthand for `ref.writeInt64BE`. */ + writeInt64BE(offset: number, input: string): any; + /** Shorthand for `ref.writeInt64LE`. */ + writeInt64LE(offset: number, input: number): any; + /** Shorthand for `ref.writeInt64LE`. */ + writeInt64LE(offset: number, input: string): any; + /** Shorthand for `ref.writeObject`. */ + writeObject(offset: number, object: Object): void; + /** Shorthand for `ref.writePointer`. */ + writePointer(offset: number, pointer: Buffer): void; + /** Shorthand for `ref.writeUInt64BE`. */ + writeUInt64BE(offset: number, input: number): any; + /** Shorthand for `ref.writeUInt64BE`. */ + writeUInt64BE(offset: number, input: string): any; + /** Shorthand for `ref.writeUInt64LE`. */ + writeUInt64LE(offset: number, input: number): any; + /** Shorthand for `ref.writeUInt64LE`. */ + writeUInt64LE(offset: number, input: string): any; + + /** + * Generate string for inspecting. + * String includes the hex-encoded memory address of the Buffer instance. + * @override + */ + inspect(): string; +} diff --git a/node-ffi/node-ffi-tests.ts b/node-ffi/node-ffi-tests.ts index 3834705031..ff9698bfd0 100644 --- a/node-ffi/node-ffi-tests.ts +++ b/node-ffi/node-ffi-tests.ts @@ -1,5 +1,10 @@ /// +/// +/// +/// +/// + import ffi = require('ffi'); import ref = require('ref'); import Struct = require('ref-struct'); diff --git a/node-ffi/node-ffi.d.ts b/node-ffi/node-ffi.d.ts index 957cf5793e..49d6069d49 100644 --- a/node-ffi/node-ffi.d.ts +++ b/node-ffi/node-ffi.d.ts @@ -1,9 +1,12 @@ -// Type definitions for node-ffi, ref, ref-array, ref-struct and ref-union +// Type definitions for node-ffi // Project: https://github.com/rbranson/node-ffi // Definitions by: Paul Loyd // Definitions: https://github.com/borisyankov/DefinitelyTyped /// +/// +/// +/// declare module "ffi" { import ref = require('ref'); @@ -38,13 +41,13 @@ declare module "ffi" { /** The type of arguments. */ argTypes: ref.Type[]; /** Is set for node-ffi functions. */ - ffi_type: NodeBuffer; + ffi_type: Buffer; abi: number; /** Get a `Callback` pointer of this function type. */ - toPointer(fn: (...args: any[]) => any): NodeBuffer; + toPointer(fn: (...args: any[]) => any): Buffer; /** Get a `ForeignFunction` of this function type. */ - toFunction(buf: NodeBuffer): ForeignFunction; + toFunction(buf: Buffer): ForeignFunction; } /** Creates and returns a type for a C function pointer. */ @@ -67,10 +70,10 @@ declare module "ffi" { * execution. */ export var ForeignFunction: { - new (ptr: NodeBuffer, retType: ref.Type, argTypes: any[], abi?: number): ForeignFunction; - new (ptr: NodeBuffer, retType: string, argTypes: any[], abi?: number): ForeignFunction; - (ptr: NodeBuffer, retType: ref.Type, argTypes: any[], abi?: number): ForeignFunction; - (ptr: NodeBuffer, retType: string, argTypes: any[], abi?: number): ForeignFunction; + new (ptr: Buffer, retType: ref.Type, argTypes: any[], abi?: number): ForeignFunction; + new (ptr: Buffer, retType: string, argTypes: any[], abi?: number): ForeignFunction; + (ptr: Buffer, retType: ref.Type, argTypes: any[], abi?: number): ForeignFunction; + (ptr: Buffer, retType: string, argTypes: any[], abi?: number): ForeignFunction; } export interface VariadicForeignFunction { @@ -96,17 +99,17 @@ declare module "ffi" { * contain the same ffi_type argument signature. */ export var VariadicForeignFunction: { - new (ptr: NodeBuffer, ret: ref.Type, fixedArgs: any[], abi?: number): VariadicForeignFunction; - new (ptr: NodeBuffer, ret: string, fixedArgs: any[], abi?: number): VariadicForeignFunction; - (ptr: NodeBuffer, ret: ref.Type, fixedArgs: any[], abi?: number): VariadicForeignFunction; - (ptr: NodeBuffer, ret: string, fixedArgs: any[], abi?: number): VariadicForeignFunction; + new (ptr: Buffer, ret: ref.Type, fixedArgs: any[], abi?: number): VariadicForeignFunction; + new (ptr: Buffer, ret: string, fixedArgs: any[], abi?: number): VariadicForeignFunction; + (ptr: Buffer, ret: ref.Type, fixedArgs: any[], abi?: number): VariadicForeignFunction; + (ptr: Buffer, ret: string, fixedArgs: any[], abi?: number): VariadicForeignFunction; }; export interface DynamicLibrary { /** Close library, returns the result of the `dlclose` system function. */ close(): number; /** Get a symbol from this library. */ - get(symbol: string): NodeBuffer; + get(symbol: string): Buffer; /** Get the result of the `dlerror` system function. */ error(): string; } @@ -126,8 +129,8 @@ declare module "ffi" { RTLD_GLOBAL: number; RTLD_NOLOAD: number; RTLD_NODELETE: number; - RTLD_NEXT: NodeBuffer; - RTLD_DEFAUL: NodeBuffer; + RTLD_NEXT: Buffer; + RTLD_DEFAUL: Buffer; } new (path?: string, mode?: number): DynamicLibrary; @@ -140,24 +143,24 @@ declare module "ffi" { * accept C callback functions. */ export var Callback: { - new (retType: any, argTypes: any[], abi: number, fn: any): NodeBuffer; - new (retType: any, argTypes: any[], fn: any): NodeBuffer; - (retType: any, argTypes: any[], abi: number, fn: any): NodeBuffer; - (retType: any, argTypes: any[], fn: any): NodeBuffer; + new (retType: any, argTypes: any[], abi: number, fn: any): Buffer; + new (retType: any, argTypes: any[], fn: any): Buffer; + (retType: any, argTypes: any[], abi: number, fn: any): Buffer; + (retType: any, argTypes: any[], fn: any): Buffer; } export var ffiType: { /** Get a `ffi_type *` Buffer appropriate for the given type. */ - (type: ref.Type): NodeBuffer + (type: ref.Type): Buffer /** Get a `ffi_type *` Buffer appropriate for the given type. */ - (type: string): NodeBuffer + (type: string): Buffer FFI_TYPE: StructType; } - export var CIF: (retType: any, types: any[], abi?: any) => NodeBuffer - export var CIF_var: (retType: any, types: any[], numFixedArgs: number, abi?: any) => NodeBuffer; + export var CIF: (retType: any, types: any[], abi?: any) => Buffer + export var CIF_var: (retType: any, types: any[], numFixedArgs: number, abi?: any) => Buffer; export var HAS_OBJC: boolean; - export var FFI_TYPES: {[key: string]: NodeBuffer}; + export var FFI_TYPES: {[key: string]: Buffer}; export var FFI_OK: number; export var FFI_BAD_TYPEDEF: number; export var FFI_BAD_ABI: number; @@ -172,8 +175,8 @@ declare module "ffi" { export var RTLD_GLOBAL: number; export var RTLD_NOLOAD: number; export var RTLD_NODELETE: number; - export var RTLD_NEXT: NodeBuffer; - export var RTLD_DEFAULT: NodeBuffer; + export var RTLD_NEXT: Buffer; + export var RTLD_DEFAULT: Buffer; export var LIB_EXT: string; export var FFI_TYPE: StructType; @@ -190,405 +193,3 @@ declare module "ffi" { uint32: ref.Type; short: ref.Type; }; } - -declare module "ref" { - export interface Type { - /** The size in bytes required to hold this datatype. */ - size: number; - /** The current level of indirection of the buffer. */ - indirection: number; - /** To invoke when `ref.get` is invoked on a buffer of this type. */ - get(buffer: NodeBuffer, offset: number): any; - /** To invoke when `ref.set` is invoked on a buffer of this type. */ - set(buffer: NodeBuffer, offset: number, value: any): void; - /** The name to use during debugging for this datatype. */ - name?: string; - /** The alignment of this datatype when placed inside a struct. */ - alignment?: number; - } - - /** A Buffer that references the C NULL pointer. */ - export var NULL: NodeBuffer; - /** A pointer-sized buffer pointing to NULL. */ - export var NULL_POINTER: NodeBuffer; - /** Get the memory address of buffer. */ - export function address(buffer: NodeBuffer): number; - /** Allocate the memory with the given value written to it. */ - export function alloc(type: Type, value?: any): NodeBuffer; - /** Allocate the memory with the given value written to it. */ - export function alloc(type: string, value?: any): NodeBuffer; - - /** - * Allocate the memory with the given string written to it with the given - * encoding (defaults to utf8). The buffer is 1 byte longer than the - * string itself, and is NULL terminated. - */ - export function allocCString(string: string, encoding?: string): NodeBuffer; - - /** Coerce a type.*/ - export function coerceType(type: Type): Type; - /** Coerce a type. String are looked up from the ref.types object. */ - export function coerceType(type: string): Type; - - /** - * Get value after dereferencing buffer. - * That is, first it checks the indirection count of buffer's type, and - * if it's greater than 1 then it merely returns another Buffer, but with - * one level less indirection. - */ - export function deref(buffer: NodeBuffer): any; - - /** Create clone of the type, with decremented indirection level by 1. */ - export function derefType(type: Type): Type; - /** Create clone of the type, with decremented indirection level by 1. */ - export function derefType(type: string): Type; - /** Represents the native endianness of the processor ("LE" or "BE"). */ - export var endianness: string; - /** Check the indirection level and return a dereferenced when necessary. */ - export function get(buffer: NodeBuffer, offset?: number, type?: Type): any; - /** Check the indirection level and return a dereferenced when necessary. */ - export function get(buffer: NodeBuffer, offset?: number, type?: string): any; - /** Get type of the buffer. Create a default type when none exists. */ - export function getType(buffer: NodeBuffer): Type; - /** Check the NULL. */ - export function isNull(buffer: NodeBuffer): boolean; - /** Read C string until the first NULL. */ - export function readCString(buffer: NodeBuffer, offset?: number): string; - - /** - * Read a big-endian signed 64-bit int. - * If there is losing precision, then return a string, otherwise a number. - * @return {number|string} - */ - export function readInt64BE(buffer: NodeBuffer, offset?: number): any; - - /** - * Read a little-endian signed 64-bit int. - * If there is losing precision, then return a string, otherwise a number. - * @return {number|string} - */ - export function readInt64LE(buffer: NodeBuffer, offset?: number): any; - - /** Read a JS Object that has previously been written. */ - export function readObject(buffer: NodeBuffer, offset?: number): Object; - /** Read data from the pointer. */ - export function readPointer(buffer: NodeBuffer, offset?: number, - length?: number): NodeBuffer; - /** - * Read a big-endian unsigned 64-bit int. - * If there is losing precision, then return a string, otherwise a number. - * @return {number|string} - */ - export function readUInt64BE(buffer: NodeBuffer, offset?: number): any; - - /** - * Read a little-endian unsigned 64-bit int. - * If there is losing precision, then return a string, otherwise a number. - * @return {number|string} - */ - export function readUInt64LE(buffer: NodeBuffer, offset?: number): any; - - /** Create pointer to buffer. */ - export function ref(buffer: NodeBuffer): NodeBuffer; - /** Create clone of the type, with incremented indirection level by 1. */ - export function refType(type: Type): Type; - /** Create clone of the type, with incremented indirection level by 1. */ - export function refType(type: string): Type; - - /** - * Create buffer with the specified size, with the same address as source. - * This function "attaches" source to the returned buffer to prevent it from - * being garbage collected. - */ - export function reinterpret(buffer: NodeBuffer, size: number, - offset?: number): NodeBuffer; - /** - * Scan past the boundary of the buffer's length until it finds size number - * of aligned NULL bytes. - */ - export function reinterpretUntilZeros(buffer: NodeBuffer, size: number, - offset?: number): NodeBuffer; - - /** Write pointer if the indirection is 1, otherwise write value. */ - export function set(buffer: NodeBuffer, offset: number, value: any, type?: Type): void; - /** Write pointer if the indirection is 1, otherwise write value. */ - export function set(buffer: NodeBuffer, offset: number, value: any, type?: string): void; - /** Write the string as a NULL terminated. Default encoding is utf8. */ - export function writeCString(buffer: NodeBuffer, offset: number, - string: string, encoding?: string): void; - /** Write a big-endian signed 64-bit int. */ - export function writeInt64BE(buffer: NodeBuffer, offset: number, input: number): void; - /** Write a big-endian signed 64-bit int. */ - export function writeInt64BE(buffer: NodeBuffer, offset: number, input: string): void; - /** Write a little-endian signed 64-bit int. */ - export function writeInt64LE(buffer: NodeBuffer, offset: number, input: number): void; - /** Write a little-endian signed 64-bit int. */ - export function writeInt64LE(buffer: NodeBuffer, offset: number, input: string): void; - - /** - * Write the JS Object. This function "attaches" object to buffer to prevent - * it from being garbage collected. - */ - export function writeObject(buffer: NodeBuffer, offset: number, object: Object): void; - - /** - * Write the memory address of pointer to buffer at the specified offset. This - * function "attaches" object to buffer to prevent it from being garbage collected. - */ - export function writePointer(buffer: NodeBuffer, offset: number, - pointer: NodeBuffer): void; - - /** Write a little-endian unsigned 64-bit int. */ - export function writeUInt64BE(buffer: NodeBuffer, offset: number, input: number): void; - /** Write a little-endian unsigned 64-bit int. */ - export function writeUInt64BE(buffer: NodeBuffer, offset: number, input: string): void; - - /** - * Attach object to buffer such. - * It prevents object from being garbage collected until buffer does. - */ - export function _attach(buffer: NodeBuffer, object: Object): void; - - /** Same as ref.reinterpret, except that this version does not attach buffer. */ - export function _reinterpret(buffer: NodeBuffer, size: number, - offset?: number): NodeBuffer; - /** Same as ref.reinterpretUntilZeros, except that this version does not attach buffer. */ - export function _reinterpretUntilZeros(buffer: NodeBuffer, size: number, - offset?: number): NodeBuffer; - /** Same as ref.writePointer, except that this version does not attach pointer. */ - export function _writePointer(buffer: NodeBuffer, offset: number, - pointer: NodeBuffer): void; - /** Same as ref.writeObject, except that this version does not attach object. */ - export function _writeObject(buffer: NodeBuffer, offset: number, object: Object): void; - - /** Default types. */ - export var types: { - void: Type; int64: Type; ushort: Type; - int: Type; uint64: Type; float: Type; - uint: Type; long: Type; double: Type; - int8: Type; ulong: Type; Object: Type; - uint8: Type; longlong: Type; CString: Type; - int16: Type; ulonglong: Type; bool: Type; - uint16: Type; char: Type; byte: Type; - int32: Type; uchar: Type; size_t: Type; - uint32: Type; short: Type; - }; -} - -interface NodeBuffer { - /** Shorthand for `ref.address`. */ - address(): number; - /** Shorthand for `ref.deref`. */ - deref(): any; - /** Shorthand for `ref.isNull`. */ - isNull(): boolean; - /** Shorthand for `ref.readCString`. */ - readCString(offset?: number): string; - /** Shorthand for `ref.readInt64BE`. */ - readInt64BE(offset?: number): string; - /** Shorthand for `ref.readInt64LE`. */ - readInt64LE(offset?: number): string; - /** Shorthand for `ref.readObject`. */ - readObject(offset?: number): string; - /** Shorthand for `ref.readPointer`. */ - readPointer(offset?: number): string; - /** Shorthand for `ref.readUInt64BE`. */ - readUInt64BE(offset?: number): string; - /** Shorthand for `ref.readUInt64LE`. */ - readUInt64LE(offset?: number): string; - /** Shorthand for `ref.ref`. */ - ref(): NodeBuffer; - /** Shorthand for `ref.reinterpret`. */ - reinterpret(size: number, offset?: number): NodeBuffer; - /** Shorthand for `ref.reinterpretUntilZeros`. */ - reinterpretUntilZeros(size: number, offset?: number): NodeBuffer; - /** Shorthand for `ref.writeCString`. */ - writeCString(offset: number, string: string, encoding?: string): void; - /** Shorthand for `ref.writeInt64BE`. */ - writeInt64BE(offset: number, input: number): any; - /** Shorthand for `ref.writeInt64BE`. */ - writeInt64BE(offset: number, input: string): any; - /** Shorthand for `ref.writeInt64LE`. */ - writeInt64LE(offset: number, input: number): any; - /** Shorthand for `ref.writeInt64LE`. */ - writeInt64LE(offset: number, input: string): any; - /** Shorthand for `ref.writeObject`. */ - writeObject(offset: number, object: Object): void; - /** Shorthand for `ref.writePointer`. */ - writePointer(offset: number, pointer: NodeBuffer): void; - /** Shorthand for `ref.writeUInt64BE`. */ - writeUInt64BE(offset: number, input: number): any; - /** Shorthand for `ref.writeUInt64BE`. */ - writeUInt64BE(offset: number, input: string): any; - /** Shorthand for `ref.writeUInt64LE`. */ - writeUInt64LE(offset: number, input: number): any; - /** Shorthand for `ref.writeUInt64LE`. */ - writeUInt64LE(offset: number, input: string): any; - - /** - * Generate string for inspecting. - * String includes the hex-encoded memory address of the Buffer instance. - * @override - */ - inspect(): string; -} - -declare module "ref-array" { - import ref = require('ref'); - - interface ArrayType extends ref.Type { - BYTES_PER_ELEMENT: number; - fixedLength: number; - /** The reference to the base type. */ - type: ref.Type; - - /** - * Accepts a Buffer instance that should be an already-populated with data - * for the ArrayType. The "length" of the Array is determined by searching - * through the buffer's contents until an aligned NULL pointer is encountered. - */ - untilZeros(buffer: NodeBuffer): { [i: number]: T; length: number; toArray(): T[]; - toJSON(): T[]; inspect(): string; buffer: NodeBuffer; ref(): NodeBuffer; }; - - new (length?: number): { [i: number]: T; length: number; toArray(): T[]; - toJSON(): T[]; inspect(): string; buffer: NodeBuffer; ref(): NodeBuffer; }; - new (data: number[], length?: number): { [i: number]: T; length: number; toArray(): T[]; - toJSON(): T[]; inspect(): string; buffer: NodeBuffer; ref(): NodeBuffer; }; - new (data: NodeBuffer, length?: number): { [i: number]: T; length: number; toArray(): T[]; - toJSON(): T[]; inspect(): string; buffer: NodeBuffer; ref(): NodeBuffer; }; - (length?: number): { [i: number]: T; length: number; toArray(): T[]; - toJSON(): T[]; inspect(): string; buffer: NodeBuffer; ref(): NodeBuffer; }; - (data: number[], length?: number): { [i: number]: T; length: number; toArray(): T[]; - toJSON(): T[]; inspect(): string; buffer: NodeBuffer; ref(): NodeBuffer; }; - (data: NodeBuffer, length?: number): { [i: number]: T; length: number; toArray(): T[]; - toJSON(): T[]; inspect(): string; buffer: NodeBuffer; ref(): NodeBuffer; }; - } - - /** - * The array type meta-constructor. - * The returned constructor's API is highly influenced by the WebGL - * TypedArray API. - */ - var ArrayType: { - new (type: ref.Type, length?: number): ArrayType; - new (type: string, length?: number): ArrayType; - (type: ref.Type, length?: number): ArrayType; - (type: string, length?: number): ArrayType; - }; - - export = ArrayType; -} - -declare module "ref-struct" { - import ref = require('ref'); - - /** - * This is the `constructor` of the Struct type that gets returned. - * - * Invoke it with `new` to create a new Buffer instance backing the struct. - * Pass it an existing Buffer instance to use that as the backing buffer. - * Pass in an Object containing the struct fields to auto-populate the - * struct with the data. - * - * @constructor - */ - interface StructType extends ref.Type { - /** Pass it an existing Buffer instance to use that as the backing buffer. */ - new (arg: NodeBuffer, data?: {}): any; - new (data?: {}): any; - /** Pass it an existing Buffer instance to use that as the backing buffer. */ - (arg: NodeBuffer, data?: {}): any; - (data?: {}): any; - - fields: {[key: string]: {type: ref.Type}}; - - /** - * Adds a new field to the struct instance with the given name and type. - * Note that this function will throw an Error if any instances of the struct - * type have already been created, therefore this function must be called at the - * beginning, before any instances are created. - */ - defineProperty(name: string, type: ref.Type): void; - - /** - * Adds a new field to the struct instance with the given name and type. - * Note that this function will throw an Error if any instances of the struct - * type have already been created, therefore this function must be called at the - * beginning, before any instances are created. - */ - defineProperty(name: string, type: string): void; - - /** - * Custom for struct type instances. - * @override - */ - toString(): string; - } - - /** The struct type meta-constructor. */ - var StructType: { - new (fields?: {}): StructType; - new (fields?: any[]): StructType; - (fields?: {}): StructType; - (fields?: any[]): StructType; - } - - export = StructType; -} - -declare module "ref-union" { - import ref = require('ref'); - - /** - * This is the `constructor` of the Struct type that gets returned. - * - * Invoke it with `new` to create a new Buffer instance backing the union. - * Pass it an existing Buffer instance to use that as the backing buffer. - * Pass in an Object containing the union fields to auto-populate the - * union with the data. - * - * @constructor - */ - interface UnionType extends ref.Type { - /** Pass it an existing Buffer instance to use that as the backing buffer. */ - new (arg: NodeBuffer, data?: {}): any; - new (data?: {}): any; - /** Pass it an existing Buffer instance to use that as the backing buffer. */ - (arg: NodeBuffer, data?: {}): any; - (data?: {}): any; - - fields: {[key: string]: {type: ref.Type}}; - - /** - * Adds a new field to the union instance with the given name and type. - * Note that this function will throw an Error if any instances of the union - * type have already been created, therefore this function must be called at the - * beginning, before any instances are created. - */ - defineProperty(name: string, type: ref.Type): void; - - /** - * Adds a new field to the union instance with the given name and type. - * Note that this function will throw an Error if any instances of the union - * type have already been created, therefore this function must be called at the - * beginning, before any instances are created. - */ - defineProperty(name: string, type: string): void; - - /** - * Custom for union type instances. - * @override - */ - toString(): string; - } - - /** The union type meta-constructor. */ - var UnionType: { - new (fields?: {}): UnionType; - new (fields?: any[]): UnionType; - (fields?: {}): UnionType; - (fields?: any[]): UnionType; - } - - export = UnionType; -} diff --git a/node-form/node-form-tests.ts b/node-form/node-form-tests.ts new file mode 100644 index 0000000000..776014b681 --- /dev/null +++ b/node-form/node-form-tests.ts @@ -0,0 +1,31 @@ +/// +/// +/// +/// + + +export interface IPerson{ + Checked:boolean; + FirstName:string; + LastName:string; + Email:string; +} + +//create custom composite validator +var personValidator = new Validation.AbstractValidator(); + +//create field validators +var required = new Validation.RequiredValidator(); +var email = new Validation.EmailValidator(); +var maxLength = new Validation.MaxLengthValidator(); +maxLength.MaxLength = 15; + + +personValidator.RuleFor("FirstName", required); +personValidator.RuleFor("FirstName", maxLength); + +personValidator.RuleFor("LastName", required); +personValidator.RuleFor("LastName", maxLength); + +personValidator.RuleFor("Email", required); +personValidator.RuleFor("Email", email); diff --git a/node-form/node-form.d.ts b/node-form/node-form.d.ts new file mode 100644 index 0000000000..3e56ddc4ae --- /dev/null +++ b/node-form/node-form.d.ts @@ -0,0 +1,710 @@ +// Type definitions for node-form v1.0.13 +// Project: https://github.com/rsamec/form +// Definitions by: Roman Samec +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// +declare module Validation { + /** + * Custom message functions. + */ + interface IErrorCustomMessage { + (config: any, args: any): string; + } + /** + * It represents a property validator for atomic object. + */ + interface IPropertyValidator { + isAcceptable(s: any): boolean; + customMessage?: IErrorCustomMessage; + tagName?: string; + } + /** + * It represents a property validator for simple string value. + */ + interface IStringValidator extends IPropertyValidator { + isAcceptable(s: string): boolean; + } + /** + * It represents an async property validator for atomic object. + */ + interface IAsyncPropertyValidator { + isAcceptable(s: any): Q.Promise; + customMessage?: IErrorCustomMessage; + isAsync: boolean; + tagName?: string; + } + /** + * It represents an async property validator for simple string value. + */ + interface IAsyncStringPropertyValidator extends IAsyncPropertyValidator { + isAcceptable(s: string): Q.Promise; + } + /** + * It defines compare operators. + */ + enum CompareOperator { + LessThan = 0, + LessThanEqual = 1, + Equal = 2, + NotEqual = 3, + GreaterThanEqual = 4, + GreaterThan = 5, + } + class StringFce { + static format(s: string, args: any): string; + } + class NumberFce { + static GetNegDigits(value: string): number; + } + class LettersOnlyValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class ZipCodeValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class EmailValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class UrlValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class RequiredValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class DateValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class DateISOValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class NumberValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class DigitValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class SignedDigitValidator implements IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; + } + class MinLengthValidator implements IStringValidator { + public MinLength: number; + constructor(MinLength?: number); + public isAcceptable(s: string): boolean; + public tagName: string; + } + class MaxLengthValidator implements IStringValidator { + public MaxLength: number; + constructor(MaxLength?: number); + public isAcceptable(s: string): boolean; + public tagName: string; + } + class RangeLengthValidator implements IStringValidator { + public RangeLength: number[]; + constructor(RangeLength?: number[]); + public isAcceptable(s: string): boolean; + public MinLength : number; + public MaxLength : number; + public tagName: string; + } + class MinValidator implements IPropertyValidator { + public Min: number; + constructor(Min?: number); + public isAcceptable(s: any): boolean; + public tagName: string; + } + class MaxValidator implements IPropertyValidator { + public Max: number; + constructor(Max?: number); + public isAcceptable(s: any): boolean; + public tagName: string; + } + class RangeValidator implements IPropertyValidator { + public Range: number[]; + constructor(Range?: number[]); + public isAcceptable(s: any): boolean; + public Min : number; + public Max : number; + public tagName: string; + } + class StepValidator implements IPropertyValidator { + public Step: string; + constructor(Step?: string); + public isAcceptable(s: any): boolean; + public tagName: string; + } + class PatternValidator implements IStringValidator { + public Pattern: string; + constructor(Pattern?: string); + public isAcceptable(s: string): boolean; + public tagName: string; + } + class ContainsValidator implements IAsyncPropertyValidator { + public Options: Q.Promise; + constructor(Options: Q.Promise); + public isAcceptable(s: string): Q.Promise; + public isAsync: boolean; + public tagName: string; + } +} +declare module Validation { + /** + * basic error structure + */ + interface IError { + HasError: boolean; + ErrorMessage: string; + TranslateArgs?: IErrorTranslateArgs; + } + /** + * support for localization of error messages + */ + interface IErrorTranslateArgs { + TranslateId: string; + MessageArgs: any; + CustomMessage?: IErrorCustomMessage; + } + /** + * It defines conditional function. + */ + interface IOptional { + (): boolean; + } + /** + * It represents the validation result. + */ + interface IValidationFailure extends IError { + IsAsync: boolean; + Error: IError; + } + /** + * This class provides unit of information about error. + * Implements composite design pattern to enable nesting of error information. + */ + interface IValidationResult { + /** + * The name of error collection. + */ + Name: string; + /** + * Add error information to child collection of errors. + * @param validationResult - error information to be added. + */ + Add(validationResult: IValidationResult): void; + /** + * Remove error information from child collection of errors. + * @param index - index of error information to be removed. + */ + Remove(index: number): void; + /** + * Return collections of child errors information. + */ + Children: IValidationResult[]; + /** + * Return true if there is any error. + */ + HasErrors: boolean; + /** + * Return true if there is any error and hasw dirty state. + */ + HasErrorsDirty: boolean; + /** + * Return error message, if there is no error, return empty string. + */ + ErrorMessage: string; + /** + * Return number of errors. + */ + ErrorCount: number; + /** + * It enables to have errors optional. + */ + Optional?: IOptional; + /** + * It enables support for localization of error messages. + */ + TranslateArgs?: IErrorTranslateArgs[]; + } + /** + * + * @ngdoc object + * @name Error + * @module Validation + * + * + * @description + * It represents basic error structure. + */ + class Error implements IError { + public HasError: boolean; + public ErrorMessage: string; + constructor(); + } + /** + * + * @ngdoc object + * @name ValidationFailure + * @module Validation + * + * + * @description + * It represents validation failure. + */ + class ValidationFailure implements IError { + public Error: IError; + public IsAsync: boolean; + constructor(Error: IError, IsAsync: boolean); + public HasError : boolean; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs; + } + /** + * + * @ngdoc object + * @name ValidationResult + * @module Validation + * + * + * @description + * It represents simple abstract error object. + */ + class ValidationResult implements IValidationResult { + public Name: string; + constructor(Name: string); + public IsDirty: boolean; + public Children : IValidationResult[]; + public Add(error: IValidationResult): void; + public Remove(index: number): void; + public Optional: IOptional; + public TranslateArgs: IErrorTranslateArgs[]; + public HasErrorsDirty : boolean; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + } + /** + * + * @ngdoc object + * @name CompositeValidationResult + * @module Validation + * + * + * @description + * It represents composite error object. + */ + class CompositeValidationResult implements IValidationResult { + public Name: string; + public Children: IValidationResult[]; + constructor(Name: string); + public Optional: IOptional; + public AddFirst(error: IValidationResult): void; + public Add(error: IValidationResult): void; + public Remove(index: number): void; + public HasErrorsDirty : boolean; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs[]; + public LogErrors(headerMessage?: string): void; + public Errors : { + [name: string]: IValidationResult; + }; + private FlattenErros; + public SetDirty(): void; + public SetPristine(): void; + private SetDirtyEx(node, dirty); + private flattenErrors(node, errorCollection); + private traverse(node, indent); + } +} +declare module Validation { + /** + * @ngdoc module + * @name Validation + * + * + * @description + * # Validation (core module) + * The module itself contains the essential components for an validation engine to function. The table below + * lists a high level breakdown of each of the components (object, functions) available within this core module. + * + *
    + */ + /** + * It defines validation function. + */ + interface IValidate { + (args: IError): void; + } + /** + * It defines async validation function. + */ + interface IAsyncValidate { + (args: IError): Q.Promise; + } + /** + * It represents named validation function. + */ + interface IValidatorFce { + Name: string; + ValidationFce?: IValidate; + AsyncValidationFce?: IAsyncValidate; + } + /** + * This class represents custom validator. + */ + interface IValidator { + Validate(context: any): IValidationFailure; + ValidateAsync(context: any): Q.Promise; + Error: IError; + } + /** + * It represents abstract validator for type of . + */ + interface IAbstractValidator { + RuleFor(prop: string, validator: IPropertyValidator): any; + ValidationFor(prop: string, validator: IValidatorFce): any; + ValidatorFor(prop: string, validator: IAbstractValidator): any; + /** + * It creates new concrete validation rule and assigned data context to this rule. + * @param name of the rule + * @constructor + */ + CreateRule(name: string): IAbstractValidationRule; + CreateAbstractRule(name: string): IAbstractValidationRule; + CreateAbstractListRule(name: string): IAbstractValidationRule; + /** + * return true if this validation rule is intended for list of items, otherwise true + */ + ForList: boolean; + } + /** + * It represents concrete validation rule for type of . + */ + interface IAbstractValidationRule { + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + Validate(context: T): IValidationResult; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + ValidateAsync(context: T): Q.Promise; + /** + * Performs validation and async validation using a validation context. + */ + ValidateAll(context: T): void; + /** + * Performs validation and async validation using a validation context for a passed field. + */ + ValidateField(context: T, propName: string): void; + /** + * Return validation results. + */ + ValidationResult: IValidationResult; + Rules: { + [name: string]: IPropertyValidationRule; + }; + Validators: { + [name: string]: IValidator; + }; + Children: { + [name: string]: AbstractValidationRule; + }; + } + /** + * It represents property validation rule for type of . + */ + interface IPropertyValidationRule { + /** + *The validators that are grouped under this rule. + */ + Validators: { + [name: string]: any; + }; + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + Validate(context: IValidationContext): IValidationFailure[]; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + ValidateAsync(context: IValidationContext): Q.Promise; + } + /** + * It represents a data context for validation rule. + */ + interface IValidationContext { + /** + * Return current value. + */ + Value: string; + /** + * Return property name for current data context. + */ + Key: string; + /** + * Data context for validation rule. + */ + Data: T; + } + /** + * + * @ngdoc object + * @name AbstractValidator + * @module Validation + * + * + * @description + * It enables to create custom validator for your own abstract object (class) and to assign validation rules to its properties. + * You can assigned these rules + * + * + property validation rules - use _RuleFor_ property + * + property async validation rules - use _RuleFor_ property + * + shared validation rules - use _ValidationFor_ property + * + custom object validator - use _ValidatorFor_ property - enables composition of child custom validators + */ + class AbstractValidator implements IAbstractValidator { + public Validators: { + [name: string]: IPropertyValidator[]; + }; + public AbstractValidators: { + [name: string]: IAbstractValidator; + }; + public ValidationFunctions: { + [name: string]: IValidatorFce[]; + }; + public RuleFor(prop: string, validator: IPropertyValidator): void; + public ValidationFor(prop: string, fce: IValidatorFce): void; + public ValidatorFor(prop: string, validator: IAbstractValidator, forList?: boolean): void; + public CreateAbstractRule(name: string): AbstractValidationRule; + public CreateAbstractListRule(name: string): AbstractListValidationRule; + public CreateRule(name: string): AbstractValidationRule; + /** + * Return true if this validation rule is intended for list of items, otherwise true. + */ + public ForList: boolean; + } + /** + * + * @ngdoc object + * @name AbstractValidationRule + * @module Validation + * + * + * @description + * It represents concreate validator for custom object. It enables to assign validation rules to custom object properties. + */ + class AbstractValidationRule implements IAbstractValidationRule { + public Name: string; + public validator: AbstractValidator; + public ValidationResult: IValidationResult; + public Rules: { + [name: string]: IPropertyValidationRule; + }; + public Validators: { + [name: string]: IValidator; + }; + public Children: { + [name: string]: AbstractValidationRule; + }; + /** + * Return true if this validation rule is intended for list of items, otherwise true. + */ + public ForList: boolean; + constructor(Name: string, validator: AbstractValidator, forList?: boolean); + public addChildren(): void; + public SetOptional(fce: IOptional): void; + private createRuleFor(prop); + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + public Validate(context: T): IValidationResult; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + public ValidateAsync(context: T): Q.Promise; + public ValidateAll(context: T): void; + public ValidateField(context: T, propName: string): void; + } + /** + * + * @ngdoc object + * @name AbstractListValidationRule + * @module Validation + * + * + * @description + * It represents an validator for custom object. It enables to assign rules to custom object properties. + */ + class AbstractListValidationRule extends AbstractValidationRule { + public Name: string; + public validator: AbstractValidator; + constructor(Name: string, validator: AbstractValidator); + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + public Validate(context: any): IValidationResult; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + public ValidateAsync(context: any): Q.Promise; + private getValidationRule(i); + private getIndexedKey(i); + public NotifyListChanged(list: any[]): void; + } + /** + * + * @ngdoc object + * @name ValidationContext + * @module Validation + * + * + * @description + * It represents a data context for validation rule. + */ + class ValidationContext implements IValidationContext { + public Key: string; + public Data: T; + constructor(Key: string, Data: T); + public Value : any; + } + class MessageLocalization { + static customMsg: string; + static defaultMessages: { + "required": string; + "remote": string; + "email": string; + "url": string; + "date": string; + "dateISO": string; + "number": string; + "digits": string; + "signedDigits": string; + "creditcard": string; + "equalTo": string; + "maxlength": string; + "minlength": string; + "rangelength": string; + "range": string; + "max": string; + "min": string; + "step": string; + "contains": string; + "mask": string; + "custom": string; + }; + static ValidationMessages: { + "required": string; + "remote": string; + "email": string; + "url": string; + "date": string; + "dateISO": string; + "number": string; + "digits": string; + "signedDigits": string; + "creditcard": string; + "equalTo": string; + "maxlength": string; + "minlength": string; + "rangelength": string; + "range": string; + "max": string; + "min": string; + "step": string; + "contains": string; + "mask": string; + "custom": string; + }; + static GetValidationMessage(validator: any): string; + } + /** + * + * @ngdoc object + * @name PropertyValidationRule + * @module Validation + * + * + * @description + * It represents a property validation rule. The property has assigned collection of property validators. + */ + class PropertyValidationRule extends ValidationResult implements IPropertyValidationRule { + public Name: string; + public Validators: { + [name: string]: any; + }; + public ValidationFailures: { + [name: string]: IValidationFailure; + }; + constructor(Name: string, validatorsToAdd?: IPropertyValidator[]); + public AddValidator(validator: any): void; + public Errors : { + [name: string]: IValidationFailure; + }; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs[]; + /** + * Performs validation using a validation context and returns a collection of Validation Failures. + */ + public Validate(context: IValidationContext): IValidationFailure[]; + public ValidateEx(value: any): IValidationFailure[]; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + public ValidateAsync(context: IValidationContext): Q.Promise; + /** + * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. + */ + public ValidateAsyncEx(value: string): Q.Promise; + } + /** + * + * @ngdoc object + * @name Validator + * @module Validation + * + * + * @description + * It represents a custom validator. It enables to define your own shared validation rules + */ + class Validator extends ValidationResult implements IValidator { + public Name: string; + private ValidateFce; + private AsyncValidationFce; + public Error: IError; + public ValidationFailures: { + [name: string]: IValidationFailure; + }; + constructor(Name: string, ValidateFce?: IValidate, AsyncValidationFce?: IAsyncValidate); + public Optional: IOptional; + public Validate(context: any): IValidationFailure; + public ValidateAsync(context: any): Q.Promise; + public HasError : boolean; + public Errors : { + [name: string]: IValidationFailure; + }; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs[]; + } +} + +declare module "node-form"{ + export = Validation; +} \ No newline at end of file diff --git a/node-uuid/node-uuid.d.ts b/node-uuid/node-uuid.d.ts new file mode 100644 index 0000000000..d4857cf310 --- /dev/null +++ b/node-uuid/node-uuid.d.ts @@ -0,0 +1,52 @@ +// Type definitions for node-uuid.js +// Project: https://github.com/broofa/node-uuid +// Definitions by: Jeff May +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface UUIDOptions { + + /** + * Node id as Array of 6 bytes (per 4.1.6). + * Default: Randomly generated ID. See note 1. + */ + node: any[] + + /** + * (Number between 0 - 0x3fff) RFC clock sequence. + * Default: An internally maintained clockseq is used. + */ + clockseq: number + + /** + * (Number | Date) Time in milliseconds since unix Epoch. + * Default: The current time is used. + */ + msecs: any + + /** + * (Number between 0-9999) additional time, in 100-nanosecond units. Ignored if msecs is unspecified. + * Default: internal uuid counter is used, as per 4.2.1.2. + */ + nsecs: number +} + +interface UUID { + v1(options?: UUIDOptions, buffer?: number[], offset?: number): string + v1(options?: UUIDOptions, buffer?: Buffer, offset?: number): string + + v2(options?: UUIDOptions, buffer?: number[], offset?: number): string + v2(options?: UUIDOptions, buffer?: Buffer, offset?: number): string + + v3(options?: UUIDOptions, buffer?: number[], offset?: number): string + v3(options?: UUIDOptions, buffer?: Buffer, offset?: number): string + + v4(options?: UUIDOptions, buffer?: number[], offset?: number): string + v4(options?: UUIDOptions, buffer?: Buffer, offset?: number): string +} + +declare module "node-uuid" { + var uuid: UUID; + export = uuid; +} diff --git a/node-uuid/node-uuid.tests.ts b/node-uuid/node-uuid.tests.ts new file mode 100644 index 0000000000..49c8f165a5 --- /dev/null +++ b/node-uuid/node-uuid.tests.ts @@ -0,0 +1,24 @@ +/// + +import uuid = require('node-uuid'); + +var uid1: string = uuid.v1() +var uid2: string = uuid.v2() +var uid3: string = uuid.v3() +var uid4: string = uuid.v4() + +var options: UUIDOptions = { + node: [], + clockseq: 2, + nsecs: 3, + msecs: new Date() +} + +var padding: number[] = [0, 1, 2] + +var offset: number = 15 + +uuid.v1(options, padding, offset) +uuid.v2(options, padding, offset) +uuid.v3(options, padding, offset) +uuid.v4(options, padding, offset) diff --git a/node/node-0.8.8.d.ts b/node/node-0.8.8.d.ts index 39f02a53a6..f236faa895 100644 --- a/node/node-0.8.8.d.ts +++ b/node/node-0.8.8.d.ts @@ -1,5 +1,6 @@ // Type definitions for Node.js v0.8.8 // Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript // Definitions: https://github.com/borisyankov/DefinitelyTyped /************************************************ @@ -44,22 +45,22 @@ declare var module: { // Same as module.exports declare var exports: any; declare var SlowBuffer: { - new (str: string, encoding?: string): NodeBuffer; - new (size: number): NodeBuffer; - new (array: any[]): NodeBuffer; - prototype: NodeBuffer; + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; isBuffer(obj: any): boolean; byteLength(string: string, encoding?: string): number; - concat(list: NodeBuffer[], totalLength?: number): NodeBuffer; + concat(list: Buffer[], totalLength?: number): Buffer; }; declare var Buffer: { - new (str: string, encoding?: string): NodeBuffer; - new (size: number): NodeBuffer; - new (array: any[]): NodeBuffer; - prototype: NodeBuffer; + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; isBuffer(obj: any): boolean; byteLength(string: string, encoding?: string): number; - concat(list: NodeBuffer[], totalLength?: number): NodeBuffer; + concat(list: Buffer[], totalLength?: number): Buffer; } /************************************************ @@ -82,10 +83,10 @@ interface EventEmitter { interface WritableStream extends EventEmitter { writable: boolean; write(str: string, encoding?: string, fd?: string): boolean; - write(buffer: NodeBuffer): boolean; + write(buffer: Buffer): boolean; end(): void; end(str: string, enconding: string): void; - end(buffer: NodeBuffer): void; + end(buffer: Buffer): void; destroy(): void; destroySoon(): void; } @@ -155,13 +156,13 @@ interface NodeProcess extends EventEmitter { } // Buffer class -interface NodeBuffer { +interface Buffer { [index: number]: number; write(string: string, offset?: number, length?: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; length: number; - copy(targetBuffer: NodeBuffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): NodeBuffer; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; readUInt8(offset: number, noAsset?: boolean): number; readUInt16LE(offset: number, noAssert?: boolean): number; readUInt16BE(offset: number, noAssert?: boolean): number; @@ -247,7 +248,7 @@ declare module "http" { export interface ServerResponse extends events.NodeEventEmitter, stream.WritableStream { // Extended base methods write(str: string, encoding?: string, fd?: string): boolean; - write(buffer: NodeBuffer): boolean; + write(buffer: Buffer): boolean; writeContinue(): void; writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; @@ -264,7 +265,7 @@ declare module "http" { export interface ClientRequest extends events.NodeEventEmitter, stream.WritableStream { // Extended base methods write(str: string, encoding?: string, fd?: string): boolean; - write(buffer: NodeBuffer): boolean; + write(buffer: Buffer): boolean; write(chunk: any, encoding?: string): void; end(data?: any, encoding?: string): void; @@ -349,13 +350,13 @@ declare module "zlib" { export function createInflateRaw(options: ZlibOptions): InflateRaw; export function createUnzip(options: ZlibOptions): Unzip; - export function deflate(buf: NodeBuffer, callback: (error: Error, result) =>void ): void; - export function deflateRaw(buf: NodeBuffer, callback: (error: Error, result) =>void ): void; - export function gzip(buf: NodeBuffer, callback: (error: Error, result) =>void ): void; - export function gunzip(buf: NodeBuffer, callback: (error: Error, result) =>void ): void; - export function inflate(buf: NodeBuffer, callback: (error: Error, result) =>void ): void; - export function inflateRaw(buf: NodeBuffer, callback: (error: Error, result) =>void ): void; - export function unzip(buf: NodeBuffer, callback: (error: Error, result) =>void ): void; + export function deflate(buf: Buffer, callback: (error: Error, result) =>void ): void; + export function deflateRaw(buf: Buffer, callback: (error: Error, result) =>void ): void; + export function gzip(buf: Buffer, callback: (error: Error, result) =>void ): void; + export function gunzip(buf: Buffer, callback: (error: Error, result) =>void ): void; + export function inflate(buf: Buffer, callback: (error: Error, result) =>void ): void; + export function inflateRaw(buf: Buffer, callback: (error: Error, result) =>void ): void; + export function unzip(buf: Buffer, callback: (error: Error, result) =>void ): void; // Constants export var Z_NO_FLUSH: number; @@ -556,8 +557,8 @@ declare module "child_process" { timeout?: number; maxBuffer?: number; killSignal?: string; - }, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; - export function exec(command: string, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; + }, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function exec(command: string, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; export function execFile(file: string, args: string[], options: { cwd?: string; stdio?: any; @@ -567,7 +568,7 @@ declare module "child_process" { timeout?: number; maxBuffer?: string; killSignal?: string; - }, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; + }, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; export function fork(modulePath: string, args?: string[], options?: { cwd?: string; env?: any; @@ -615,7 +616,7 @@ declare module "net" { export interface NodeSocket extends stream.ReadWriteStream { // Extended base methods write(str: string, encoding?: string, fd?: string): boolean; - write(buffer: NodeBuffer): boolean; + write(buffer: Buffer): boolean; connect(port: number, host?: string, connectionListener?: Function): void; connect(path: string, connectionListener?: Function): void; @@ -668,7 +669,7 @@ declare module "dgram" { export function createSocket(type: string, callback?: Function): Socket; interface Socket extends events.NodeEventEmitter { - send(buf: NodeBuffer, offset: number, length: number, port: number, address: string, callback?: Function): void; + send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: Function): void; bind(port: number, address?: string): void; close(): void; address: { address: string; family: string; port: number; }; @@ -761,13 +762,13 @@ declare module "fs" { export function futimesSync(fd: string, atime: number, mtime: number): void; export function fsync(fd: string, callback?: Function): void; export function fsyncSync(fd: string): void; - export function write(fd: string, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, written: number, buffer: NodeBuffer) =>any): void; - export function writeSync(fd: string, buffer: NodeBuffer, offset: number, length: number, position: number): void; - export function read(fd: string, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, bytesRead: number, buffer: NodeBuffer) => void): void; - export function readSync(fd: string, buffer: NodeBuffer, offset: number, length: number, position: number): any[]; + export function write(fd: string, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: Error, written: number, buffer: Buffer) =>any): void; + export function writeSync(fd: string, buffer: Buffer, offset: number, length: number, position: number): void; + export function read(fd: string, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: Error, bytesRead: number, buffer: Buffer) => void): void; + export function readSync(fd: string, buffer: Buffer, offset: number, length: number, position: number): any[]; export function readFile(filename: string, encoding: string, callback: (err: Error, data: string) => void ): void; - export function readFile(filename: string, callback: (err: Error, data: NodeBuffer) => void ): void; - export function readFileSync(filename: string): NodeBuffer; + export function readFile(filename: string, callback: (err: Error, data: Buffer) => void ): void; + export function readFileSync(filename: string): Buffer; export function readFileSync(filename: string, encoding: string): string; export function writeFile(filename: string, data: any, callback?: (err) => void): void; export function writeFile(filename: string, data: any, encoding?: string, callback?: (err) => void): void; @@ -811,8 +812,8 @@ declare module "path" { declare module "string_decoder" { export interface NodeStringDecoder { - write(buffer: NodeBuffer): string; - detectIncompleteChar(buffer: NodeBuffer): number; + write(buffer: Buffer): string; + detectIncompleteChar(buffer: Buffer): number; } export var StringDecoder: { new (encoding: string): NodeStringDecoder; @@ -963,7 +964,7 @@ declare module "crypto" { } export function getDiffieHellman(group_name: string): DiffieHellman; export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: string) => any): void; - export function randomBytes(size: number, callback?: (err: Error, buf: NodeBuffer) =>void ); + export function randomBytes(size: number, callback?: (err: Error, buf: Buffer) =>void ); } declare module "stream" { @@ -972,10 +973,10 @@ declare module "stream" { export interface WritableStream extends events.NodeEventEmitter { writable: boolean; write(str: string, encoding?: string, fd?: string): boolean; - write(buffer: NodeBuffer): boolean; + write(buffer: Buffer): boolean; end(): void; end(str: string, enconding: string): void; - end(buffer: NodeBuffer): void; + end(buffer: Buffer): void; destroy(): void; destroySoon(): void; } diff --git a/node/node-tests.ts b/node/node-tests.ts index a77a4b39b6..e9ef58dbbd 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -9,6 +9,7 @@ import util = require("util"); import crypto = require("crypto"); import http = require("http"); import net = require("net"); +import dgram = require("dgram"); assert(1 + 1 - 2 === 0, "The universe isn't how it should."); @@ -39,7 +40,7 @@ fs.writeFile("Harry Potter", assert.ifError); var content: string, - buffer: NodeBuffer; + buffer: Buffer; content = fs.readFileSync('testfile', 'utf8'); content = fs.readFileSync('testfile', {encoding : 'utf8'}); @@ -95,3 +96,30 @@ var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').diges // Make sure .listen() and .close() retuern a Server instance http.createServer().listen(0).close().address(); net.createServer().listen(0).close().address(); + +var request = http.request('http://0.0.0.0'); +request.once('error', function () {}); +request.setNoDelay(true); +request.abort(); + +//////////////////////////////////////////////////// +/// Http tests : http://nodejs.org/api/http.html +//////////////////////////////////////////////////// +module http_tests { + // Status codes + var code = 100; + var codeMessage = http.STATUS_CODES['400']; + var codeMessage = http.STATUS_CODES[400]; +} + +//////////////////////////////////////////////////// +/// Dgram tests : http://nodejs.org/api/dgram.html +//////////////////////////////////////////////////// + +var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { +}); +var ai: dgram.AddressInfo = ds.address(); +ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { +}); + + diff --git a/node/node.d.ts b/node/node.d.ts index 42398496ee..282120dc65 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1,10 +1,11 @@ // Type definitions for Node.js v0.10.1 // Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript , DefinitelyTyped // Definitions: https://github.com/borisyankov/DefinitelyTyped /************************************************ * * -* Node.js v0.10.1 API * +* Node.js v0.10.1 API * * * ************************************************/ @@ -13,17 +14,17 @@ * GLOBAL * * * ************************************************/ -declare var process: NodeProcess; +declare var process: NodeJS.Process; declare var global: any; declare var __filename: string; declare var __dirname: string; -declare function setTimeout(callback: (...args: any[]) => void , ms: number , ...args: any[]): NodeTimer; -declare function clearTimeout(timeoutId: NodeTimer): void; -declare function setInterval(callback: (...args: any[]) => void , ms: number , ...args: any[]): NodeTimer; -declare function clearInterval(intervalId: NodeTimer): void; -declare function setImmediate(callback: (...args: any[]) => void , ...args: any[]): any; +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearTimeout(timeoutId: NodeJS.Timer): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearInterval(intervalId: NodeJS.Timer): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; declare function clearImmediate(immediateId: any): void; declare var require: { @@ -32,7 +33,7 @@ declare var require: { cache: any; extensions: any; main: any; -} +}; declare var module: { exports: any; @@ -42,147 +43,170 @@ declare var module: { loaded: boolean; parent: any; children: any[]; -} +}; // Same as module.exports declare var exports: any; declare var SlowBuffer: { - new (str: string, encoding?: string): NodeBuffer; - new (size: number): NodeBuffer; - new (array: any[]): NodeBuffer; - prototype: NodeBuffer; + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (size: Uint8Array): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; isBuffer(obj: any): boolean; byteLength(string: string, encoding?: string): number; - concat(list: NodeBuffer[], totalLength?: number): NodeBuffer; + concat(list: Buffer[], totalLength?: number): Buffer; }; + + +// Buffer class +interface Buffer extends NodeBuffer {} declare var Buffer: { - new (str: string, encoding?: string): NodeBuffer; - new (size: number): NodeBuffer; - new (array: any[]): NodeBuffer; - prototype: NodeBuffer; + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (size: Uint8Array): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; isBuffer(obj: any): boolean; byteLength(string: string, encoding?: string): number; - concat(list: NodeBuffer[], totalLength?: number): NodeBuffer; -} + concat(list: Buffer[], totalLength?: number): Buffer; +}; /************************************************ * * -* INTERFACES * +* GLOBAL INTERFACES * * * ************************************************/ +declare module NodeJS { + export interface ErrnoException extends Error { + errno?: any; + code?: string; + path?: string; + syscall?: string; + } -interface ErrnoException extends Error { - errno?: any; - code?: string; - path?: string; - syscall?: string; -} + export interface EventEmitter { + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } -interface NodeEventEmitter { - addListener(event: string, listener: Function): NodeEventEmitter; - on(event: string, listener: Function): NodeEventEmitter; - once(event: string, listener: Function): NodeEventEmitter; - removeListener(event: string, listener: Function): NodeEventEmitter; - removeAllListeners(event?: string): NodeEventEmitter; - setMaxListeners(n: number): void; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; -} + export interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + } -interface ReadableStream extends NodeEventEmitter { - readable: boolean; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: NodeBuffer): void; - wrap(oldStream: ReadableStream): ReadableStream; -} + export interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } -interface WritableStream extends NodeEventEmitter { - writable: boolean; - write(buffer: NodeBuffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: NodeBuffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; -} + export interface ReadWriteStream extends ReadableStream, WritableStream {} -interface ReadWriteStream extends ReadableStream, WritableStream { } - -interface NodeProcess extends NodeEventEmitter { - stdout: WritableStream; - stderr: WritableStream; - stdin: ReadableStream; - argv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - env: any; - exit(code?: number): void; - getgid(): number; - setgid(id: number): void; - setgid(id: string): void; - getuid(): number; - setuid(id: number): void; - setuid(id: string): void; - version: string; - versions: { http_parser: string; node: string; v8: string; ares: string; uv: string; zlib: string; openssl: string; }; - config: { - target_defaults: { - cflags: any[]; - default_configuration: string; - defines: string[]; - include_dirs: string[]; - libraries: string[]; + export interface Process extends EventEmitter { + stdout: WritableStream; + stderr: WritableStream; + stdin: ReadableStream; + argv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + env: any; + exit(code?: number): void; + getgid(): number; + setgid(id: number): void; + setgid(id: string): void; + getuid(): number; + setuid(id: number): void; + setuid(id: string): void; + version: string; + versions: { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + openssl: string; }; - variables: { - clang: number; - host_arch: string; - node_install_npm: boolean; - node_install_waf: boolean; - node_prefix: string; - node_shared_openssl: boolean; - node_shared_v8: boolean; - node_shared_zlib: boolean; - node_use_dtrace: boolean; - node_use_etw: boolean; - node_use_openssl: boolean; - target_arch: string; - v8_no_strict_aliasing: number; - v8_use_snapshot: boolean; - visibility: string; - }; - }; - kill(pid: number, signal?: string): void; - pid: number; - title: string; - arch: string; - platform: string; - memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; }; - nextTick(callback: Function): void; - umask(mask?: number): number; - uptime(): number; - hrtime(time?:number[]): number[]; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string): void; + pid: number; + title: string; + arch: string; + platform: string; + memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; }; + nextTick(callback: Function): void; + umask(mask?: number): number; + uptime(): number; + hrtime(time?:number[]): number[]; - // Worker - send?(message: any, sendHandle?: any): void; + // Worker + send?(message: any, sendHandle?: any): void; + } + + export interface Timer { + ref() : void; + unref() : void; + } } -// Buffer class +/** + * @deprecated + */ interface NodeBuffer { [index: number]: number; write(string: string, offset?: number, length?: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; + toJSON(): any; length: number; - copy(targetBuffer: NodeBuffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): NodeBuffer; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; readUInt8(offset: number, noAsset?: boolean): number; readUInt16LE(offset: number, noAssert?: boolean): number; readUInt16BE(offset: number, noAssert?: boolean): number; @@ -214,16 +238,15 @@ interface NodeBuffer { fill(value: any, offset?: number, end?: number): void; } -interface NodeTimer { - ref() : void; - unref() : void; -} - /************************************************ * * * MODULES * * * ************************************************/ +declare module "buffer" { + export var INSPECT_MAX_BYTES: number; +} + declare module "querystring" { export function stringify(obj: any, sep?: string, eq?: string): string; export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; @@ -232,7 +255,7 @@ declare module "querystring" { } declare module "events" { - export class EventEmitter implements NodeEventEmitter { + export class EventEmitter implements NodeJS.EventEmitter { static listenerCount(emitter: EventEmitter, event: string): number; addListener(event: string, listener: Function): EventEmitter; @@ -251,7 +274,7 @@ declare module "http" { import net = require("net"); import stream = require("stream"); - export interface Server extends NodeEventEmitter { + export interface Server extends events.EventEmitter { listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server; listen(path: string, callback?: Function): Server; listen(handle: any, listeningListener?: Function): Server; @@ -259,7 +282,7 @@ declare module "http" { address(): { port: number; family: string; address: string; }; maxHeadersCount: number; } - export interface ServerRequest extends NodeEventEmitter, ReadableStream { + export interface ServerRequest extends events.EventEmitter, stream.Readable { method: string; url: string; headers: any; @@ -270,10 +293,10 @@ declare module "http" { resume(): void; connection: net.Socket; } - export interface ServerResponse extends NodeEventEmitter, WritableStream { + export interface ServerResponse extends events.EventEmitter, stream.Writable { // Extended base methods - write(buffer: NodeBuffer): boolean; - write(buffer: NodeBuffer, cb?: Function): boolean; + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; write(str: string, cb?: Function): boolean; write(str: string, encoding?: string, cb?: Function): boolean; write(str: string, encoding?: string, fd?: string): boolean; @@ -291,15 +314,15 @@ declare module "http" { // Extended base methods end(): void; - end(buffer: NodeBuffer, cb?: Function): void; + end(buffer: Buffer, cb?: Function): void; end(str: string, cb?: Function): void; end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface ClientRequest extends NodeEventEmitter, WritableStream { + export interface ClientRequest extends events.EventEmitter, stream.Writable { // Extended base methods - write(buffer: NodeBuffer): boolean; - write(buffer: NodeBuffer, cb?: Function): boolean; + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; write(str: string, cb?: Function): boolean; write(str: string, encoding?: string, cb?: Function): boolean; write(str: string, encoding?: string, fd?: string): boolean; @@ -307,17 +330,17 @@ declare module "http" { write(chunk: any, encoding?: string): void; abort(): void; setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: Function): void; + setNoDelay(noDelay?: boolean): void; setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; // Extended base methods end(): void; - end(buffer: NodeBuffer, cb?: Function): void; + end(buffer: Buffer, cb?: Function): void; end(str: string, cb?: Function): void; end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface ClientResponse extends NodeEventEmitter, ReadableStream { + export interface ClientResponse extends events.EventEmitter, stream.Readable { statusCode: number; httpVersion: string; headers: any; @@ -328,7 +351,10 @@ declare module "http" { } export interface Agent { maxSockets: number; sockets: any; requests: any; } - export var STATUS_CODES: any; + export var STATUS_CODES: { + [errorCode: number]: string; + [errorCode: string]: string; + }; export function createServer(requestListener?: (request: ServerRequest, response: ServerResponse) =>void ): Server; export function createClient(port?: number, host?: string): any; export function request(options: any, callback?: Function): ClientRequest; @@ -380,13 +406,13 @@ declare module "zlib" { import stream = require("stream"); export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } - export interface Gzip extends ReadWriteStream { } - export interface Gunzip extends ReadWriteStream { } - export interface Deflate extends ReadWriteStream { } - export interface Inflate extends ReadWriteStream { } - export interface DeflateRaw extends ReadWriteStream { } - export interface InflateRaw extends ReadWriteStream { } - export interface Unzip extends ReadWriteStream { } + export interface Gzip extends stream.Transform { } + export interface Gunzip extends stream.Transform { } + export interface Deflate extends stream.Transform { } + export interface Inflate extends stream.Transform { } + export interface DeflateRaw extends stream.Transform { } + export interface InflateRaw extends stream.Transform { } + export interface Unzip extends stream.Transform { } export function createGzip(options?: ZlibOptions): Gzip; export function createGunzip(options?: ZlibOptions): Gunzip; @@ -396,13 +422,13 @@ declare module "zlib" { export function createInflateRaw(options?: ZlibOptions): InflateRaw; export function createUnzip(options?: ZlibOptions): Unzip; - export function deflate(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function deflateRaw(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function gzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function gunzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function inflate(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function inflateRaw(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function unzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; // Constants export var Z_NO_FLUSH: number; @@ -502,8 +528,8 @@ declare module "https" { }; export interface Server extends tls.Server { } export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: NodeEventEmitter) =>void ): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: NodeEventEmitter) =>void ): http.ClientRequest; + export function request(options: RequestOptions, callback?: (res: events.EventEmitter) =>void ): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: events.EventEmitter) =>void ): http.ClientRequest; export var globalAgent: Agent; } @@ -526,8 +552,8 @@ declare module "repl" { export interface ReplOptions { prompt?: string; - input?: ReadableStream; - output?: WritableStream; + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; terminal?: boolean; eval?: Function; useColors?: boolean; @@ -535,14 +561,14 @@ declare module "repl" { ignoreUndefined?: boolean; writer?: Function; } - export function start(options: ReplOptions): NodeEventEmitter; + export function start(options: ReplOptions): events.EventEmitter; } declare module "readline" { import events = require("events"); import stream = require("stream"); - export interface ReadLine extends NodeEventEmitter { + export interface ReadLine extends events.EventEmitter { setPrompt(prompt: string, length: number): void; prompt(preserveCursor?: boolean): void; question(query: string, callback: Function): void; @@ -552,8 +578,8 @@ declare module "readline" { write(data: any, key?: any): void; } export interface ReadLineOptions { - input: ReadableStream; - output: WritableStream; + input: NodeJS.ReadableStream; + output: NodeJS.WritableStream; completer?: Function; terminal?: boolean; } @@ -577,10 +603,10 @@ declare module "child_process" { import events = require("events"); import stream = require("stream"); - export interface ChildProcess extends NodeEventEmitter { - stdin: WritableStream; - stdout: ReadableStream; - stderr: ReadableStream; + export interface ChildProcess extends events.EventEmitter { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; pid: number; kill(signal?: string): void; send(message: any, sendHandle: any): void; @@ -603,8 +629,8 @@ declare module "child_process" { timeout?: number; maxBuffer?: number; killSignal?: string; - }, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; - export function exec(command: string, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; + }, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function exec(command: string, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; export function execFile(file: string, args: string[], options: { cwd?: string; stdio?: any; @@ -614,7 +640,7 @@ declare module "child_process" { timeout?: number; maxBuffer?: string; killSignal?: string; - }, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; + }, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; export function fork(modulePath: string, args?: string[], options?: { cwd?: string; env?: any; @@ -674,10 +700,10 @@ declare module "dns" { declare module "net" { import stream = require("stream"); - export interface Socket extends ReadWriteStream { + export interface Socket extends stream.Duplex { // Extended base methods - write(buffer: NodeBuffer): boolean; - write(buffer: NodeBuffer, cb?: Function): boolean; + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; write(str: string, cb?: Function): boolean; write(str: string, encoding?: string, cb?: Function): boolean; write(str: string, encoding?: string, fd?: string): boolean; @@ -701,7 +727,7 @@ declare module "net" { // Extended base methods end(): void; - end(buffer: NodeBuffer, cb?: Function): void; + end(buffer: Buffer, cb?: Function): void; end(str: string, cb?: Function): void; end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; @@ -736,13 +762,25 @@ declare module "net" { declare module "dgram" { import events = require("events"); - export function createSocket(type: string, callback?: Function): Socket; + interface RemoteInfo { + address: string; + port: number; + size: number; + } + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - interface Socket extends NodeEventEmitter { - send(buf: NodeBuffer, offset: number, length: number, port: number, address: string, callback?: Function): void; - bind(port: number, address?: string): void; + interface Socket extends events.EventEmitter { + send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port: number, address?: string, callback?: () => void): void; close(): void; - address: { address: string; family: string; port: number; }; + address(): AddressInfo; setBroadcast(flag: boolean): void; setMulticastTTL(ttl: number): void; setMulticastLoopback(flag: boolean): void; @@ -753,6 +791,7 @@ declare module "dgram" { declare module "fs" { import stream = require("stream"); + import events = require("events"); interface Stats { isFile(): boolean; @@ -777,97 +816,101 @@ declare module "fs" { ctime: Date; } - interface FSWatcher extends NodeEventEmitter { + interface FSWatcher extends events.EventEmitter { close(): void; } - export interface ReadStream extends ReadableStream { } - export interface WriteStream extends WritableStream { } + export interface ReadStream extends stream.Readable {} + export interface WriteStream extends stream.Writable {} - export function rename(oldPath: string, newPath: string, callback?: (err?: ErrnoException) => void): void; + export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; export function renameSync(oldPath: string, newPath: string): void; - export function truncate(path: string, callback?: (err?: ErrnoException) => void): void; - export function truncate(path: string, len: number, callback?: (err?: ErrnoException) => void): void; + export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function truncateSync(path: string, len?: number): void; - export function ftruncate(fd: number, callback?: (err?: ErrnoException) => void): void; - export function ftruncate(fd: number, len: number, callback?: (err?: ErrnoException) => void): void; + export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function ftruncateSync(fd: number, len?: number): void; - export function chown(path: string, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; + export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function chownSync(path: string, uid: number, gid: number): void; - export function fchown(fd: number, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; + export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fchownSync(fd: number, uid: number, gid: number): void; - export function lchown(path: string, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; + export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function lchownSync(path: string, uid: number, gid: number): void; - export function chmod(path: string, mode: number, callback?: (err?: ErrnoException) => void): void; - export function chmod(path: string, mode: string, callback?: (err?: ErrnoException) => void): void; + export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; export function chmodSync(path: string, mode: number): void; export function chmodSync(path: string, mode: string): void; - export function fchmod(fd: number, mode: number, callback?: (err?: ErrnoException) => void): void; - export function fchmod(fd: number, mode: string, callback?: (err?: ErrnoException) => void): void; + export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fchmodSync(fd: number, mode: number): void; export function fchmodSync(fd: number, mode: string): void; - export function lchmod(path: string, mode: number, callback?: (err?: ErrnoException) => void): void; - export function lchmod(path: string, mode: string, callback?: (err?: ErrnoException) => void): void; + export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; export function lchmodSync(path: string, mode: number): void; export function lchmodSync(path: string, mode: string): void; - export function stat(path: string, callback?: (err: ErrnoException, stats: Stats) => any): void; - export function lstat(path: string, callback?: (err: ErrnoException, stats: Stats) => any): void; - export function fstat(fd: number, callback?: (err: ErrnoException, stats: Stats) => any): void; + export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; export function statSync(path: string): Stats; export function lstatSync(path: string): Stats; export function fstatSync(fd: number): Stats; - export function link(srcpath: string, dstpath: string, callback?: (err?: ErrnoException) => void): void; + export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; export function linkSync(srcpath: string, dstpath: string): void; - export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: ErrnoException) => void): void; + export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; - export function readlink(path: string, callback?: (err: ErrnoException, linkString: string) => any): void; + export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; export function readlinkSync(path: string): string; - export function realpath(path: string, callback?: (err: ErrnoException, resolvedPath: string) => any): void; - export function realpath(path: string, cache: {[path: string]: string}, callback: (err: ErrnoException, resolvedPath: string) =>any): void; + export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; export function realpathSync(path: string, cache?: {[path: string]: string}): string; - export function unlink(path: string, callback?: (err?: ErrnoException) => void): void; + export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; export function unlinkSync(path: string): void; - export function rmdir(path: string, callback?: (err?: ErrnoException) => void): void; + export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; export function rmdirSync(path: string): void; - export function mkdir(path: string, callback?: (err?: ErrnoException) => void): void; - export function mkdir(path: string, mode: number, callback?: (err?: ErrnoException) => void): void; - export function mkdir(path: string, mode: string, callback?: (err?: ErrnoException) => void): void; + export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; export function mkdirSync(path: string, mode?: number): void; export function mkdirSync(path: string, mode?: string): void; - export function readdir(path: string, callback?: (err: ErrnoException, files: string[]) => void): void; + export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; export function readdirSync(path: string): string[]; - export function close(fd: number, callback?: (err?: ErrnoException) => void): void; + export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function closeSync(fd: number): void; - export function open(path: string, flags: string, callback?: (err: ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: number, callback?: (err: ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: string, callback?: (err: ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; export function openSync(path: string, flags: string, mode?: number): number; export function openSync(path: string, flags: string, mode?: string): number; - export function utimes(path: string, atime: number, mtime: number, callback?: (err?: ErrnoException) => void): void; + export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; export function utimesSync(path: string, atime: number, mtime: number): void; - export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: ErrnoException) => void): void; + export function utimesSync(path: string, atime: Date, mtime: Date): void; + export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; export function futimesSync(fd: number, atime: number, mtime: number): void; - export function fsync(fd: number, callback?: (err?: ErrnoException) => void): void; + export function futimesSync(fd: number, atime: Date, mtime: Date): void; + export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fsyncSync(fd: number): void; - export function write(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: ErrnoException, written: number, buffer: NodeBuffer) => void): void; - export function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; - export function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: ErrnoException, bytesRead: number, buffer: NodeBuffer) => void): void; - export function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; - export function readFile(filename: string, encoding: string, callback: (err: ErrnoException, data: string) => void): void; - export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: ErrnoException, data: string) => void): void; - export function readFile(filename: string, options: { flag?: string; }, callback: (err: ErrnoException, data: NodeBuffer) => void): void; - export function readFile(filename: string, callback: (err: ErrnoException, data: NodeBuffer) => void ): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; + export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void ): void; export function readFileSync(filename: string, encoding: string): string; export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; - export function readFileSync(filename: string, options?: { flag?: string; }): NodeBuffer; - export function writeFile(filename: string, data: any, callback?: (err: ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: ErrnoException) => void): void; + export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; + export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: ErrnoException) => void): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: ErrnoException) => void): void; - export function appendFile(filename: string, data: any, callback?: (err: ErrnoException) => void): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; @@ -911,8 +954,8 @@ declare module "path" { declare module "string_decoder" { export interface NodeStringDecoder { - write(buffer: NodeBuffer): string; - detectIncompleteChar(buffer: NodeBuffer): number; + write(buffer: Buffer): string; + detectIncompleteChar(buffer: Buffer): number; } export var StringDecoder: { new (encoding: string): NodeStringDecoder; @@ -974,7 +1017,7 @@ declare module "tls" { connections: number; } - export interface ClearTextStream extends ReadWriteStream { + export interface ClearTextStream extends stream.Duplex { authorized: boolean; authorizationError: Error; getPeerCertificate(): any; @@ -1017,13 +1060,18 @@ declare module "crypto" { export function createCredentials(details: CredentialDetails): Credentials; export function createHash(algorithm: string): Hash; export function createHmac(algorithm: string, key: string): Hmac; + export function createHmac(algorithm: string, key: Buffer): Hmac; interface Hash { update(data: any, input_encoding?: string): Hash; - digest(encoding?: string): string; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; + digest(): Buffer; } interface Hmac { update(data: any, input_encoding?: string): Hmac; - digest(encoding?: string): string; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; + digest(): Buffer; } export function createCipher(algorithm: string, password: any): Cipher; export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; @@ -1031,9 +1079,9 @@ declare module "crypto" { update(data: any, input_encoding?: string, output_encoding?: string): string; final(output_encoding?: string): string; setAutoPadding(auto_padding: boolean): void; - createDecipher(algorithm: string, password: any): Decipher; - createDecipheriv(algorithm: string, key: any, iv: any): Decipher; } + export function createDecipher(algorithm: string, password: any): Decipher; + export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; interface Decipher { update(data: any, input_encoding?: string, output_encoding?: string): void; final(output_encoding?: string): string; @@ -1063,10 +1111,11 @@ declare module "crypto" { } export function getDiffieHellman(group_name: string): DiffieHellman; export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: string) => any): void; - export function randomBytes(size: number): NodeBuffer; - export function randomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; - export function pseudoRandomBytes(size: number): NodeBuffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; + export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer; + export function randomBytes(size: number): Buffer; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; + export function pseudoRandomBytes(size: number): Buffer; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; } declare module "stream" { @@ -1078,7 +1127,7 @@ declare module "stream" { objectMode?: boolean; } - export class Readable extends events.EventEmitter implements ReadableStream { + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { readable: boolean; constructor(opts?: ReadableOptions); _read(size: number): void; @@ -1086,11 +1135,11 @@ declare module "stream" { setEncoding(encoding: string): void; pause(): void; resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; unshift(chunk: string): void; - unshift(chunk: NodeBuffer): void; - wrap(oldStream: ReadableStream): ReadableStream; + unshift(chunk: Buffer): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; push(chunk: any, encoding?: string): boolean; } @@ -1099,16 +1148,16 @@ declare module "stream" { decodeStrings?: boolean; } - export class Writable extends events.EventEmitter implements WritableStream { + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { writable: boolean; constructor(opts?: WritableOptions); - _write(data: NodeBuffer, encoding: string, callback: Function): void; + _write(data: Buffer, encoding: string, callback: Function): void; _write(data: string, encoding: string, callback: Function): void; - write(buffer: NodeBuffer, cb?: Function): boolean; + write(buffer: Buffer, cb?: Function): boolean; write(str: string, cb?: Function): boolean; write(str: string, encoding?: string, cb?: Function): boolean; end(): void; - end(buffer: NodeBuffer, cb?: Function): void; + end(buffer: Buffer, cb?: Function): void; end(str: string, cb?: Function): void; end(str: string, encoding?: string, cb?: Function): void; } @@ -1118,16 +1167,16 @@ declare module "stream" { } // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements ReadWriteStream { + export class Duplex extends Readable implements NodeJS.ReadWriteStream { writable: boolean; constructor(opts?: DuplexOptions); - _write(data: NodeBuffer, encoding: string, callback: Function): void; + _write(data: Buffer, encoding: string, callback: Function): void; _write(data: string, encoding: string, callback: Function): void; - write(buffer: NodeBuffer, cb?: Function): boolean; + write(buffer: Buffer, cb?: Function): boolean; write(str: string, cb?: Function): boolean; write(str: string, encoding?: string, cb?: Function): boolean; end(): void; - end(buffer: NodeBuffer, cb?: Function): void; + end(buffer: Buffer, cb?: Function): void; end(str: string, cb?: Function): void; end(str: string, encoding?: string, cb?: Function): void; } @@ -1135,28 +1184,28 @@ declare module "stream" { export interface TransformOptions extends ReadableOptions, WritableOptions {} // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends events.EventEmitter implements ReadWriteStream { + export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { readable: boolean; writable: boolean; constructor(opts?: TransformOptions); - _transform(chunk: NodeBuffer, encoding: string, callback: Function): void; + _transform(chunk: Buffer, encoding: string, callback: Function): void; _transform(chunk: string, encoding: string, callback: Function): void; _flush(callback: Function): void; read(size?: number): any; setEncoding(encoding: string): void; pause(): void; resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; unshift(chunk: string): void; - unshift(chunk: NodeBuffer): void; - wrap(oldStream: ReadableStream): ReadableStream; + unshift(chunk: Buffer): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; push(chunk: any, encoding?: string): boolean; - write(buffer: NodeBuffer, cb?: Function): boolean; + write(buffer: Buffer, cb?: Function): boolean; write(str: string, cb?: Function): boolean; write(str: string, encoding?: string, cb?: Function): boolean; end(): void; - end(buffer: NodeBuffer, cb?: Function): void; + end(buffer: Buffer, cb?: Function): void; end(str: string, cb?: Function): void; end(str: string, encoding?: string, cb?: Function): void; } @@ -1215,14 +1264,14 @@ declare module "assert" { (block: Function, error: Function, message?: string): void; (block: Function, error: RegExp, message?: string): void; (block: Function, error: (err: any) => boolean, message?: string): void; - } + }; export var doesNotThrow: { (block: Function, message?: string): void; (block: Function, error: Function, message?: string): void; (block: Function, error: RegExp, message?: string): void; (block: Function, error: (err: any) => boolean, message?: string): void; - } + }; export function ifError(value: any): void; } @@ -1249,8 +1298,8 @@ declare module "domain" { export class Domain extends events.EventEmitter { run(fn: Function): void; - add(emitter: NodeEventEmitter): void; - remove(emitter: NodeEventEmitter): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; bind(cb: (err: Error, data: any) => any): any; intercept(cb: (data: any) => any): any; dispose(): void; diff --git a/nodemailer/nodemailer-tests.ts.tscparams b/nodemailer/nodemailer-tests.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/nodemailer/nodemailer-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/nodemailer/nodemailer.d.ts b/nodemailer/nodemailer.d.ts index 7d77a58ae5..c95aee99f9 100644 --- a/nodemailer/nodemailer.d.ts +++ b/nodemailer/nodemailer.d.ts @@ -17,8 +17,8 @@ declare class Transport { options: Object; transportType: string; sendMailWithTransport(emailMessage: MailComposer, callback?: (err: Error) => any): any; - useDKIM(dkim: DKIMOptions); - close(callback?: (err: Error) => any); + useDKIM(dkim: DKIMOptions): void; + close(callback?: (err: Error) => any): any; sendMail(message: MailComposer, callback?: (err: Error) => any): any; send_mail(message:MailComposer, callback?: (err: Error) => any): any; } diff --git a/nodemailer/nodemailer.d.ts.tscparams b/nodemailer/nodemailer.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/nodemailer/nodemailer.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/nodeunit/nodeunit-tests.ts b/nodeunit/nodeunit-tests.ts new file mode 100644 index 0000000000..bdd705b0e3 --- /dev/null +++ b/nodeunit/nodeunit-tests.ts @@ -0,0 +1,59 @@ +/// + +import nodeunit = require('nodeunit'); + +var num: number; +var value: any; +var actual: any; +var expected: any; +var message: string; +var operator: string; +var error: any; +var block: () =>{ + +}; + +export var testGroup: nodeunit.ITestGroup = { + setUp: function (callback: nodeunit.ICallbackFunction) { + callback(); + }, + tearDown: function (callback: nodeunit.ICallbackFunction) { + callback(); + }, + test1: function (test: nodeunit.Test) { + test.expect(num); + + test.fail(actual, expected, message, operator); + test.assert(value, message); + test.ok(value); + test.ok(value, message); + test.equal(actual, expected); + test.equal(actual, expected, message); + test.notEqual(actual, expected); + test.notEqual(actual, expected, message); + test.deepEqual(actual, expected); + test.deepEqual(actual, expected, message); + test.notDeepEqual(actual, expected); + test.notDeepEqual(actual, expected, message); + test.strictEqual(actual, expected); + test.strictEqual(actual, expected, message); + test.notStrictEqual(actual, expected); + test.notStrictEqual(actual, expected, message); + test.throws(block); + test.throws(block, error); + test.throws(block, error, message); + test.doesNotThrow(block); + test.doesNotThrow(block, error); + test.doesNotThrow(block, error, message); + test.ifError(value); + + //assertion wrappers + test.equals(actual, expected); + test.equals(actual, expected, message); + test.same(actual, expected); + test.same(actual, expected, message); + + test.done(error); + test.done(); + } +}; diff --git a/nodeunit/nodeunit.d.ts b/nodeunit/nodeunit.d.ts new file mode 100644 index 0000000000..c427dbf171 --- /dev/null +++ b/nodeunit/nodeunit.d.ts @@ -0,0 +1,59 @@ +// Type definitions for nodeunit +// Project: https://github.com/caolan/nodeunit +// Definitions by: Jeff Goddard +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/nodeunit.d.ts + +declare module 'nodeunit' { + export interface Test { + done: ICallbackFunction; + expect(num: number): void; + + //assersions from node assert module + fail(actual: any, expected: any, message: string, operator: string): void; + assert(value: any, message: string): void; + ok(value: any, message?: string): void; + equal(actual: any, expected: any, message?: string): void; + notEqual(actual: any, expected: any, message?: string): void; + deepEqual(actual: any, expected: any, message?: string): void; + notDeepEqual(actual: any, expected: any, message?: string): void; + strictEqual(actual: any, expected: any, message?: string): void; + notStrictEqual(actual: any, expected: any, message?: string): void; + throws(block: any, error?: any, message?: string): void; + doesNotThrow(block: any, error?: any, message?: string): void; + ifError(value: any): void; + + //assertion wrappers + equals(actual: any, expected: any, message?: string): void; + same(actual: any, expected: any, message?: string): void; + } + + // Test Group Usage: + // var testGroup: nodeunit.ITestGroup = { + // setUp: function (callback: nodeunit.ICallbackFunction): void { + // callback(); + // }, + // tearDown: function (callback: nodeunit.ICallbackFunction): void { + // callback(); + // }, + // test1: function (test: nodeunit.Test): void { + // test.done(); + // } + // } + // exports.testgroup = testGroup; + + export interface ITestBody { + (callback: Test): void; + } + + export interface ITestGroup { + setUp?: (callback: ICallbackFunction) => void; + tearDown?: (callback: ICallbackFunction) => void; + } + + export interface ICallbackFunction { + (err?: any): void; + } +} + diff --git a/nomnom/nomnom-tests.ts.tscparams b/nomnom/nomnom-tests.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/nomnom/nomnom-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/object-path/object-path-tests.ts b/object-path/object-path-tests.ts new file mode 100644 index 0000000000..5984c78a8a --- /dev/null +++ b/object-path/object-path-tests.ts @@ -0,0 +1,68 @@ +/// + +var + object = { + one: 1, + two: { + three: 3, + four: ['4'] + } + }, + array: any[] = [], + Null:any = null; + +objectPath.del(array) === ['12']; +objectPath.del(object) === object; +objectPath.del(object) === object; + +objectPath.del() === void 0; +objectPath.del(object, ['1','2','3']); +objectPath.del(object, [1,2,3]); +objectPath.del(object, 1); +objectPath.del(object, 'one').one === 1; + +objectPath.coalesce(object, ['1','2']) === void 0; +objectPath.coalesce(object, ['1',['2','1']]) === void 0; +objectPath.coalesce(object, ['1',['2','1']], 1) === 1; +objectPath.coalesce(object, [1,1], 1) === 1; +objectPath.coalesce(object, >[1,[1,1]], 1) === 1; + +objectPath.ensureExists(object, '1.2', 2); +objectPath.ensureExists(object, 1, 2); +objectPath.ensureExists(object, [1,2], 2); +objectPath.ensureExists(object, ['1','2'], 2); +objectPath.ensureExists(object, ['1','2'], 2) === 3; +objectPath.ensureExists(object, ['1','2'], 2) === [[]]; + +objectPath.push(object, 1, 1,2,3,4); +objectPath.push(object, 1, 1,'2', 3, false); +objectPath.push(object, 'one.four', 1,'2', 3, false); +objectPath.push(object, ['one','two'], [1,'2', 3, false]); + +objectPath.get(array) === array; +objectPath.get(Null) === Null; +objectPath.get() === void 0; +objectPath.get(object, 'one') === 1; +objectPath.get(object, ['two','three']) === 3; +objectPath.get(object, ['three'], 3) === 3; +objectPath.get(object, 'three', 3) === 3; +objectPath.get(object, 0, 3) === 3; +objectPath.get(object, 0, '3') === '3'; +objectPath.get(object, 0, ['1','2']) === ['1','2']; +objectPath.get(object, 0) === 10; + +objectPath.set(object, '1.2', true); +objectPath.set(object, ['1','2'], true); +objectPath.set(object, [1, 2], true); +objectPath.set(object, '1.2', true, true); +objectPath.set(object, '1.2', true, false); +objectPath.set(object, '1.2', true, false) === ['string']; +objectPath.set(object, '1.2', true, false) === object; + +objectPath.insert(object, '1.2', 1); +objectPath.insert(object, ['1','2'], 1); +objectPath.insert(object, 1, 1); +objectPath.insert(object, [1,2], 1); +objectPath.insert(object, '1.2', 1, 2); +objectPath.insert(object, ['1.2'], 1, 6); + diff --git a/object-path/object-path.d.ts b/object-path/object-path.d.ts new file mode 100644 index 0000000000..fe38f87028 --- /dev/null +++ b/object-path/object-path.d.ts @@ -0,0 +1,238 @@ +// Type definitions for objectPath v0.6.0 +// Project: https://github.com/mariocasciaro/object-path +// Definitions by: Paulo Cesar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var objectPath: objectPath.IObjectPathStatic; + +declare module objectPath { + + interface IStringArray { + [index: number]: string; + } + + interface INumberArray { + [index: number]: number; + } + + interface IObjectPathStatic { + /*======== Del =========*/ + + /** + * Deletes a member from object or array + * @param {object} object + * @param {string[]|string} path + * @return object + */ + del(object: T, path: IStringArray): T; + /** + * @see objectPath.del + */ + del(object: T, path: INumberArray): T; + /** + * @see objectPath.del + */ + del(object: T, path: number): T; + /** + * @see objectPath.del + */ + del(object: T, path: string): T; + /** + * @see objectPath.del + */ + del(object: T): T; + /** + * @see objectPath.del + */ + del():void; + + /*======== Get =========*/ + /** + * Get a path from an object + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} [defaultValue=undefined] + */ + get(object: T, path: string, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: IStringArray, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: number, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: INumberArray, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T): T; + /** + * @see objectPath.get + */ + get():void; + + /*======== Set =========*/ + /** + * Set a path to a value + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} value + * @param {boolean} [doNotReplace=false] + * @return Any existing value on the path if any + */ + set(object: T, path: string, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: number, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: IStringArray, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: INumberArray, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T): T; + /** + * @see objectPath.set + */ + set():void; + + /*======== Push =========*/ + /** + * Create (if path isn't an array) and push the value to it. Can push unlimited number of values + * @param {object} object + */ + push(object: T, path: INumberArray, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: IStringArray, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: number, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: string, ...args:any[]):void; + /** + * @see objectPath.push + */ + push():void; + + /*======== Coalesce =========*/ + /** + * Get the first non undefined property + * @param {object} object + * @param {string[]|string[][]|number[]|number[][]} paths + * @param {*} defaultValue + * @return {*} + */ + coalesce(object: T, paths: IStringArray, defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: INumberArray, defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: IStringArray[], defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: INumberArray[], defaultValue?: any):TResult; + + /*======== Empty =========*/ + /** + * Empty a path. Arrays are set to length 0, objects have all elements deleted, strings + * are set to empty, numbers to 0, everything else is set to null + * @param {object} object + * @param {string|string[]|number[]} path + */ + empty(object: T, path: string):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: INumberArray):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: IStringArray):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: number):TResult; + /** + * @see objectPath.empty + */ + empty(object: T):T; + /** + * @see objectPath.empty + */ + empty():void; + + /*======== EnsureExists =========*/ + /** + * Set a value if it doesn't exist, do nothing if it does + * @param {object} object + * @param {string|string[]|number|number[]} path + */ + ensureExists(object: T, path: string, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: number, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: INumberArray, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: IStringArray, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T): T; + /** + * @see objectPath.ensureExists + */ + ensureExists():void; + + /*======== Insert =========*/ + /** + * Insert an item in an array path + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} value + * @param {number} [at=0] + */ + insert(object: T, path: string, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: INumberArray, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: IStringArray, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: number, value: any, at?: number):void; + } + +} + +declare module 'objectPath' { + export = objectPath; +} \ No newline at end of file diff --git a/oclazyload/oclazyload-tests.ts b/oclazyload/oclazyload-tests.ts new file mode 100644 index 0000000000..3879a564b3 --- /dev/null +++ b/oclazyload/oclazyload-tests.ts @@ -0,0 +1,23 @@ +/// + +var lazyloader:Function = ()=>{}; + +var config1: oc.ILazyLoadConfig = { + asyncLoader: lazyloader +}; + +var config2:oc.ILazyLoadConfig = { + asyncLoader: lazyloader, + loadedModules: ['module1', 'module2'] +}; + +var moduleConfig:oc.ILazyLoadModuleConfig = { + name:'testmodule', + files:['testmodule'] +} + +var config2:oc.ILazyLoadConfig = { + asyncLoader: lazyloader, + loadedModules: ['module1', 'module2'], + modules: [moduleConfig] +}; diff --git a/oclazyload/oclazyload.d.ts b/oclazyload/oclazyload.d.ts new file mode 100644 index 0000000000..22ac45f9d9 --- /dev/null +++ b/oclazyload/oclazyload.d.ts @@ -0,0 +1,34 @@ +// Type definitions for oc.LazyLoad +// Project: https://github.com/ocombe/ocLazyLoad +// Definitions by: Roland Zwaga +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module oc { + + interface ILazyLoadConfig { + asyncLoader:any; + loadedModules?:string[]; + modules?:ILazyLoadModuleConfig[]; + } + + interface ILazyLoadModuleConfig { + name:string; + files:string[]; + } + + interface ILazyLoad { + load(module:any):ng.IPromise; + loadTemplateFile(url:string, config:ILazyLoadModuleConfig):ng.IPromise; + loadTemplateFile(urls:string[], config:ILazyLoadModuleConfig):ng.IPromise; + getModuleName(moduleName:string):string; + getModules():string[]; + getModuleConfig(name:string):ILazyLoadModuleConfig; + setModuleConfig(config:ILazyLoadModuleConfig):void; + } + + interface ILazyLoadProvider { + config(config:ILazyLoadConfig):void; + } +} \ No newline at end of file diff --git a/optimist/optimist-tests.ts b/optimist/optimist-tests.ts new file mode 100644 index 0000000000..aa7f0341ff --- /dev/null +++ b/optimist/optimist-tests.ts @@ -0,0 +1,46 @@ +/// + +import optimist = require('optimist'); + +var fn: Function; +var str: string; +var value: any; +var num: number; +var bool: boolean; +var strArr: string[]; + +var argv: optimist.Argv; +var opt: optimist.Optimist; + +argv = opt.argv; +argv = opt.argv; +argv = optimist(strArr).argv; + +opt = optimist(strArr).default(str, value); +opt = optimist(strArr).default({}); + +opt = optimist(strArr).boolean(str); +opt = optimist(strArr).boolean(strArr); + +opt = optimist(strArr).string(str); +opt = optimist(strArr).string(strArr); + +opt = opt.wrap(num); + +opt.help(); +opt.showHelp(fn); + +opt = opt.usage(str); + +opt = opt.demand(str); +opt = opt.demand(num); +opt = opt.demand(strArr); + +opt = opt.alias(str, str); + +opt = opt.describe(str, str); + +opt = opt.options(str, Object); + +opt.check(fn); +opt = opt.parse(strArr); diff --git a/optimist/optimist.d.ts b/optimist/optimist.d.ts new file mode 100644 index 0000000000..01d44ab630 --- /dev/null +++ b/optimist/optimist.d.ts @@ -0,0 +1,53 @@ +// Type definitions for optimist +// Project: https://github.com/substack/node-optimist +// Definitions by: Carlos Ballesteros Velasco +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/optimist.d.ts + +declare module "optimist" { + + function optimist(args: string[]): optimist.Optimist; + + module optimist { + export interface Optimist { + default(name: string, value: any): Optimist; + default(args: Object): Optimist; + + boolean(name: string): Optimist; + boolean(names: string[]): Optimist; + + string(name: string): Optimist; + string(names: string[]): Optimist; + + wrap(columns: number): Optimist; + + help(): void; + showHelp(fn: Function): void; + + usage(message: string): Optimist; + + demand(key: string): Optimist; + demand(key: number): Optimist; + demand(key: string[]): Optimist; + + alias(key: string, alias: string): Optimist; + + describe(key: string, desc: string): Optimist; + + options(key: string, opt: Object): Optimist; + + check(fn: Function): void; + + parse(args: string[]): Optimist; + + argv: Argv; + } + + export interface Argv extends Object { + _: string[]; + } + } + + export = optimist; +} diff --git a/package.json b/package.json index c45823b827..bd79664473 100644 --- a/package.json +++ b/package.json @@ -20,20 +20,16 @@ "node": ">= 0.10.0" }, "scripts": { - "test": "npm run changes", - "changes": "node ./_infrastructure/tests/runner.js --tsc-version 1.0.0 --test-changes", - "all": "node ./_infrastructure/tests/runner.js --tsc-version 1.0.0", - "dry": "node ./_infrastructure/tests/runner.js --tsc-version 1.0.0 --skip-tests --test-changes", - "list": "node ./_infrastructure/tests/runner.js --tsc-version 1.0.0 --skip-tests --print-files --print-refmap", - "help": "node ./_infrastructure/tests/runner.js -h", - "tsc_runner": "node ./_infrastructure/tests/typescript/1.0.0/tsc ./_infrastructure/tests/runner.ts --target ES5 --out ./_infrastructure/tests/runner.js --module commonjs --sourcemap" + "test": "node ./_infrastructure/runner.js --test-changes", + "changes": "node ./_infrastructure/runner.js --test-changes", + "lint": "node ./_infrastructure/runner.js --lint-changes", + "all": "node ./_infrastructure/runner.js", + "dry": "node ./_infrastructure/runner.js --skip-tests --test-changes", + "list": "node ./_infrastructure/runner.js --skip-tests --print-files --print-refmap", + "help": "node ./_infrastructure/runner.js -h" }, "dependencies": { - "source-map-support": "~0.2.5", - "git-wrapper": "~0.1.1", - "glob": "~3.2.9", - "bluebird": "~1.0.7", - "lazy.js": "~0.3.2", - "optimist": "~0.6.1" - } + "definition-tester": "~0.0.4" + }, + "devDependencies": {} } diff --git a/parsimmon/parsimmon-tests.ts b/parsimmon/parsimmon-tests.ts index 16d1510b5d..3f80198917 100644 --- a/parsimmon/parsimmon-tests.ts +++ b/parsimmon/parsimmon-tests.ts @@ -3,6 +3,7 @@ import P = require('parsimmon'); import Parser = P.Parser; import Mark = P.Mark; +import Result = P.Result; // -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -17,6 +18,7 @@ class Bar { // -- -- -- -- -- -- -- -- -- -- -- -- -- var str: string; +var bool: boolean; var num: number; var regex: RegExp; @@ -50,11 +52,25 @@ var fooMarkPar: Parser>; // -- -- -- -- -- -- -- -- -- -- -- -- -- -foo = fooPar.parse(str); +var fooResult: Result; + +bool = fooResult.status; +foo = fooResult.value; +str = fooResult.expected; +num = fooResult.index; + +// -- -- -- -- -- -- -- -- -- -- -- -- -- + +fooResult = fooPar.parse(str); fooPar = fooPar.or(fooPar); anyPar = fooPar.or(barPar); +barPar = fooPar.chain((f) => { + foo = f; + return barPar; +}); + barPar = fooPar.then((f) => { foo = f; return barPar; @@ -82,6 +98,8 @@ fooArrPar = fooPar.atLeast(num); fooMarkPar = fooPar.mark(); +fooPar = fooPar.desc(str); + // -- -- -- -- -- -- -- -- -- -- -- -- -- strPar = P.string(str); @@ -92,6 +110,10 @@ fooPar = P.succeed(foo); fooArrPar = P.seq(fooPar, fooPar); anyArrPar = P.seq(barPar, fooPar, numPar); +fooPar = P.alt(fooPar, fooPar); +anyPar = P.alt(barPar, fooPar, numPar); + + fooPar = P.lazy(() => { return fooPar; }); @@ -112,5 +134,5 @@ strPar = P.optWhitespace; strPar = P.any; strPar = P.all; -strPar = P.eof; -numPar = P.index; \ No newline at end of file +voidPar = P.eof; +numPar = P.index; diff --git a/parsimmon/parsimmon.d.ts b/parsimmon/parsimmon.d.ts index 435ea285a9..719e9c937d 100644 --- a/parsimmon/parsimmon.d.ts +++ b/parsimmon/parsimmon.d.ts @@ -1,5 +1,5 @@ -// Type definitions for Parsimmon 0.3.0 -// Project: https://github.com/jayferd/parsimmon +// Type definitions for Parsimmon 0.5.0 +// Project: https://github.com/jneen/parsimmon // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -14,16 +14,27 @@ declare module 'parsimmon' { value: T; } + export interface Result { + status: boolean; + value?: T; + expected?: string; + index?: number; + } + export interface Parser { /* parse the string */ - parse(input: string): T; + parse(input: string): Result; /* returns a new parser which tries parser, and if it fails uses otherParser. */ or(otherParser: Parser): Parser; or(otherParser: Parser): Parser; + /* + returns a new parser which tries parser, and on success calls the given function with the result of the parse, which is expected to return another parser, which will be tried next + */ + chain(next: (result: T) => Parser): Parser; /* returns a new parser which tries parser, and on success calls the given function with the result of the parse, which is expected to return another parser. */ @@ -65,9 +76,11 @@ declare module 'parsimmon' { */ atLeast(n: number): Parser; /* - yields an object with start, value, and end keys, where value is the original value yielded by the parser, and start and end are the indices in the stream that contain the parsed text. + returns a new parser whose failure message is the passed description. */ mark(): Parser>; + + desc(description: string): Parser; } /* is a parser that expects to find "my-string", and will yield the same. @@ -87,12 +100,20 @@ declare module 'parsimmon' { /* accepts a variable number of parsers that it expects to find in order, yielding an array of the results. */ + export function seq(...parsers: Parser[]): Parser; export function seq(...parsers: Parser[]): Parser; + /* + accepts a variable number of parsers, and yields the value of the first one that succeeds, backtracking in between. + */ + export function alt(...parsers: Parser[]): Parser; + export function alt(...parsers: Parser[]): Parser; + /* accepts a function that returns a parser, which is evaluated the first time the parser is used. This is useful for referencing parsers that haven't yet been defined. */ export function lazy(f: () => Parser): Parser; + export function lazy(description: string, f: () => Parser): Parser; /* fail paring with a message @@ -135,7 +156,7 @@ declare module 'parsimmon' { /* expects the end of the stream. */ - export var eof: Parser; + export var eof: Parser; /* is a parser that yields the current index of the parse. */ diff --git a/passport-facebook/passport-facebook.d.ts b/passport-facebook/passport-facebook.d.ts index 47c9b68bb8..855b033f58 100644 --- a/passport-facebook/passport-facebook.d.ts +++ b/passport-facebook/passport-facebook.d.ts @@ -1,5 +1,5 @@ // Type definitions for passport-facebook 1.0.3 -// Project: https://github.com/jaredhanson/passport-facebook +// Project: https://github.com/jaredhanson/passport-facebook // Definitions by: James Roland Cabresos // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -10,18 +10,25 @@ declare module 'passport-facebook' { import passport = require('passport'); import express = require('express'); - interface Profile { - id:string; - provider:string; - displayName:string; - name:{familyName:string; givenName:string; middleName:string}; - profileUrl:string; + interface Profile extends passport.Profile { + gender: string; + profileUrl: string; } - class Strategy implements passport.Strategy{ - constructor(options:{clientID:string; clientSecret:string; callbackURL:string}, - verify:(accessToken:string, refreshToken:string, profile:Profile, done:(error:any, user?:any) => void) => void); - name: string; - authenticate:(req: express.Request, options?: Object) => void; + interface IStrategyOption { + clientID: string; + clientSecret: string; + callbackURL: string; + + scopeSeparator?: string; + enableProof?: boolean; + profileFields?: string[]; } -} \ No newline at end of file + + class Strategy implements passport.Strategy { + constructor(options: IStrategyOption, + verify: (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any) => void) => void); + name: string; + authenticate: (req: express.Request, options?: Object) => void; + } +} diff --git a/passport-strategy/passport-strategy-test.ts b/passport-strategy/passport-strategy-test.ts new file mode 100644 index 0000000000..e9c6fd604f --- /dev/null +++ b/passport-strategy/passport-strategy-test.ts @@ -0,0 +1,48 @@ + +import express = require('express'); +import passport = require('passport-strategy'); + + +export class Strategy extends passport.Strategy { + constructor(options: any, verify?: Function) { + if (typeof options == 'function') { + verify = options; + options = {}; + } + if (!verify) { + throw new TypeError('DummyStrategy requires a verify callback'); + } + + super(); + + this.name = 'dummy'; + this._verify = verify; + this._passReqToCallback = options.passReqToCallback; + } + + name: string; + + _verify: Function; + _passReqToCallback: boolean; + + authenticate(req: express.Request, options?: any): void { + options = options || {}; + + // Test fail method. + this.fail({ message: options.missingTokenMessage || 'Missing token' }, 400); + + var self = this; + + function verified(err: Error, user: any, info: any) { + if (err) { + return self.error(err); + } + if (!user) { + return self.fail(info); + } + self.success(user, info); + } + + verified(null, {}, {}); + } +} diff --git a/passport-strategy/passport-strategy.d.ts b/passport-strategy/passport-strategy.d.ts new file mode 100644 index 0000000000..36036f54b2 --- /dev/null +++ b/passport-strategy/passport-strategy.d.ts @@ -0,0 +1,98 @@ +// Type definitions for Passport Strategy module v0.2.0 +// Project: https://github.com/jaredhanson/passport-strategy +// Definitions by: Lior Mualem +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +/** + * Using this module, one can easily implement a strategy using typescript by + * inheriting the 'Strategy' class and reimplementing the 'authenticate' method. + */ + +declare module 'passport-strategy' { + + import passport = require('passport'); + import express = require('express'); + + class Strategy implements passport.Strategy { + /** + * Performs authentication for the request. + * Note: Virtual function - re-implement in the strategy. + * @param req The request to authenticate. + * @param options Options passed to the strategy. + */ + authenticate(req: express.Request, options?: any): void; + + // + // Augmented strategy functions. + // These are available only from the 'authenticate' function. + // They are added manually by the passport framework. + // + + /** + * Authenticate `user`, with optional `info`. + * + * Strategies should call this function to successfully authenticate a + * user. `user` should be an object supplied by the application after it + * has been given an opportunity to verify credentials. `info` is an + * optional argument containing additional user information. This is + * useful for third-party authentication strategies to pass profile + * details. + * + * @param {Object} user + * @param {Object} info + * @api public + */ + success(user: any, info: any): void; + + /** + * Fail authentication, with optional `challenge` and `status`, defaulting + * to 401. + * + * Strategies should call this function to fail an authentication attempt. + * + * @param {String} challenge (Can also be an object with 'message' and 'type' fields). + * @param {Number} status + * @api public + */ + fail(challenge: any, status: number): void; + fail(status: number): void; + + /** + * Redirect to `url` with optional `status`, defaulting to 302. + * + * Strategies should call this function to redirect the user (via their + * user agent) to a third-party website for authentication. + * + * @param {String} url + * @param {Number} status + * @api public + */ + redirect(url: string, status?: number): void; + + /** + * Pass without making a success or fail decision. + * + * Under most circumstances, Strategies should not need to call this + * function. It exists primarily to allow previous authentication state + * to be restored, for example from an HTTP session. + * + * @api public + */ + pass(): void; + + /** + * Internal error while performing authentication. + * + * Strategies should call this function when an internal error occurs + * during the process of performing authentication; for example, if the + * user directory is not available. + * + * @param {Error} err + * @api public + */ + error(err: Error): void; + } +} diff --git a/passport/passport-test.ts b/passport/passport-tests.ts similarity index 61% rename from passport/passport-test.ts rename to passport/passport-tests.ts index e3ee9d4f2b..7542e2e0ed 100644 --- a/passport/passport-test.ts +++ b/passport/passport-tests.ts @@ -34,7 +34,7 @@ app.post('/login', }); app.post('/login', function(req, res, next) { - passport.authenticate('local', function(err, user, info) { + passport.authenticate('local', function(err: any, user: { username: string; }, info: { message: string; }) { if (err) { return next(err) } if (!user) { req.session.error = info.message; @@ -52,6 +52,33 @@ app.get('/logout', function(req, res) { res.redirect('/'); }); +function authSetting(): void { + var authOption = { + successRedirect: '/', + failureRedirect: '/login', + }; + var successCallback = (req: express.Request, res: express.Response) => { + res.redirect('/'); + }; + + app.get('/auth/facebook', + passport.authenticate('facebook')); + app.get('/auth/facebook/callback', + passport.authenticate('facebook', authOption), successCallback); + + app.get('/auth/twitter', + passport.authenticate('twitter')); + app.get('/auth/twitter/callback', + passport.authenticate('twitter', authOption)); + + app.get('/auth/google', + passport.authenticate('google', { scope: + [ 'https://www.googleapis.com/auth/userinfo.profile' ] })); + app.get('/auth/google/callback', + passport.authenticate('google', authOption), successCallback); + +} + function ensureAuthenticated(req: express.Request, res: express.Response, next: (err?: any) => void) { if (req.isAuthenticated()) { return next(); } if (req.isUnauthenticated()) { diff --git a/passport/passport.d.ts b/passport/passport.d.ts index cd86228f62..fc3dd786f4 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -1,10 +1,16 @@ // Type definitions for Passport v0.2.0 // Project: http://passportjs.org // Definitions by: Horiuchi_H -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// +declare module Express { + export interface Request { + session?: any; + } +} + declare module 'passport' { import express = require('express'); @@ -15,8 +21,8 @@ declare module 'passport' { function initialize(options?: { userProperty: string; }): express.Handler; function session(options?: { pauseStream: boolean; }): express.Handler; - function authenticate(strategy: string, options: Object, callback?: express.Handler): express.Handler; - function authenticate(strategy: string, callback2: (err: any, user: any, info: any) => void): express.Handler; + function authenticate(strategy: string, callback?: Function): express.Handler; + function authenticate(strategy: string, options: Object, callback?: Function): express.Handler; function authorize(strategy: string, options: Object, callback?: express.Handler): express.Handler; function serializeUser(fn: (user: any, done: (err: any, id: any) => void) => void): void; function deserializeUser(fn: (id: any, done: (err: any, user: any) => void) => void): void; @@ -42,6 +48,24 @@ declare module 'passport' { name?: string; authenticate(req: express.Request, options?: Object): void; } + + interface Profile { + provider: string; + id: string; + displayName: string; + name? : { + familyName: string; + givenName: string; + middleName?: string; + }; + emails?: { + value: string; + type?: string; + }[]; + photos?: { + value: string; + }[]; + } } declare module Express { @@ -60,3 +84,4 @@ declare module Express { isUnauthenticated(): boolean; } } + diff --git a/pathwatcher/pathwatcher.d.ts b/pathwatcher/pathwatcher.d.ts index 1f481979ba..a4570e1cbe 100644 --- a/pathwatcher/pathwatcher.d.ts +++ b/pathwatcher/pathwatcher.d.ts @@ -6,25 +6,7 @@ /// /// -declare module "pathwatcher" { - - import events = require("events"); - - interface IHandleWatcher extends events.EventEmitter { - onEvent(event:any, filePath:any, oldFilePath:any):any; - start():void; - closeIfNoListener():void; - close():void; - } - - interface IPathWatcher { - isWatchingParent:boolean; - path:any; - handleWatcher:IHandleWatcher; - - close():void; - } - +declare module PathWatcher { interface IFileStatic { new (path:string, symlink?:boolean):IFile; } @@ -75,6 +57,26 @@ declare module "pathwatcher" { unsubscribeFromNativeChangeEvents():void; isPathPrefixOf(prefix:string, fullPath:string):boolean; } +} + +declare module "pathwatcher" { + + import events = require("events"); + + interface IHandleWatcher extends events.EventEmitter { + onEvent(event:any, filePath:any, oldFilePath:any):any; + start():void; + closeIfNoListener():void; + close():void; + } + + interface IPathWatcher { + isWatchingParent:boolean; + path:any; + handleWatcher:IHandleWatcher; + + close():void; + } function watch(path:string, callback:Function):IPathWatcher; @@ -82,6 +84,6 @@ declare module "pathwatcher" { function getWatchedPaths():string[]; - var File:IFileStatic; - var Directory:IDirectoryStatic; + var File:PathWatcher.IFileStatic; + var Directory:PathWatcher.IDirectoryStatic; } diff --git a/pdf/pdf-tests.ts b/pdf/pdf-tests.ts index 90542b503a..6157307808 100644 --- a/pdf/pdf-tests.ts +++ b/pdf/pdf-tests.ts @@ -3,9 +3,18 @@ // // Fetch the PDF document from the URL using promises // +var pdfDoc: PDFDocumentProxy; +var pageNum: number; + PDFJS.getDocument('helloworld.pdf').then(function (pdf) { // Using promise to fetch the page - pdf.getPage(1).then(function (page) { + pdfDoc = pdf; + pageNum = 1; + renderPage(pageNum); +}); + +function renderPage(pageNum: number) { + pdfDoc.getPage(pageNum).then(function (page) { var scale = 1.5; var viewport = page.getViewport(scale); @@ -26,4 +35,11 @@ PDFJS.getDocument('helloworld.pdf').then(function (pdf) { }; page.render(renderContext); }); -}); +} + +function goNext() { + if (pdfDoc && pageNum < pdfDoc.numPages) { + ++pageNum; + renderPage(pageNum); + } +} diff --git a/pdf/pdf.d.ts b/pdf/pdf.d.ts index bd66604f40..94733c3e3a 100644 --- a/pdf/pdf.d.ts +++ b/pdf/pdf.d.ts @@ -74,12 +74,12 @@ interface PDFDocumentProxy { /** * Total number of pages the PDF contains. **/ - numPages(): number; + numPages: number; /** * A unique ID to identify a PDF. Not guaranteed to be unique. [jbaldwin: haha what] **/ - fingerprint(): string; + fingerprint: string; /** * True if embedded document fonts are in use. Will be set during rendering of the pages. diff --git a/pg/pg-tests.ts b/pg/pg-tests.ts new file mode 100644 index 0000000000..dd9c75378d --- /dev/null +++ b/pg/pg-tests.ts @@ -0,0 +1,36 @@ +/// +import pg = require("pg"); +var conString = "postgres://username:password@localhost/database"; + +// Client pooling +pg.connect(conString, (err, client, done) => { + if (err) { + return console.error("Error fetching client from pool", err); + } + client.query("SELECT $1::int AS number", ["1"], (err, result) => { + done(); + if (err) { + return console.error("Error running query", err); + } + console.log(result.rows[0]["number"]); + return null; + }); + return null; +}); + +// Simple +var client = new pg.Client(conString); +client.connect((err) => { + if (err) { + return console.error("Could not connect to postgres", err); + } + client.query("SELECT NOW() AS 'theTime'", (err, result) => { + if (err) { + return console.error("Error running query", err); + } + console.log(result.rows[0]["theTime"]); + client.end(); + return null; + }); + return null; +}); \ No newline at end of file diff --git a/pg/pg.d.ts b/pg/pg.d.ts new file mode 100644 index 0000000000..efdda0e4a4 --- /dev/null +++ b/pg/pg.d.ts @@ -0,0 +1,88 @@ +// Type definitions for pg +// Project: https://github.com/brianc/node-postgres +// Definitions by: Phips Peter +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "pg" { + import events = require("events"); + import stream = require("stream"); + + export function connect(connection: string, callback: (err: Error, client: Client, done: () => void) => void): void; + export function connect(config: ClientConfig, callback: (err: Error, client: Client, done: () => void) => void): void; + export function end(): void; + + export interface ConnectionConfig { + user?: string; + database?: string; + password?: string; + port?: number; + host?: string; + } + + export interface Defaults extends ConnectionConfig { + poolSize?: number; + poolIdleTimeout?: number; + reapIntervalMillis?: number; + binary?: boolean; + parseInt8?: boolean; + } + + export interface ClientConfig extends ConnectionConfig { + ssl?: boolean; + } + + export interface QueryConfig { + name?: string; + text: string; + values?: any[]; + } + + export interface QueryResult { + rows: any[]; + } + + export interface ResultBuilder extends QueryResult { + command: string; + rowCount: number; + oid: number; + addRow(row: any): void; + } + + export class Client extends events.EventEmitter { + constructor(connection: string); + constructor(config: ClientConfig); + + connect(callback?: (err:Error) => void): void; + end(): void; + + query(queryText: string, callback?: (err: Error, result: QueryResult) => void): Query; + query(config: QueryConfig, callback?: (err: Error, result: QueryResult) => void): Query; + query(queryText: string, values: any[], callback?: (err: Error, result: QueryResult) => void): Query; + + copyFrom(queryText: string): stream.Writable; + copyTo(queryText: string): stream.Readable; + + pauseDrain(): void; + resumeDrain(): void; + + public on(event: "drain", listener: () => void): Client; + public on(event: "error", listener: (err: Error) => void): Client; + public on(event: "notification", listener: (message: any) => void): Client; + public on(event: "notice", listener: (message: any) => void): Client; + public on(event: string, listener: Function): Client; + } + + export class Query extends events.EventEmitter { + public on(event: "row", listener: (row: any, result?: ResultBuilder) => void): Query; + public on(event: "error", listener: (err: Error) => void): Query; + public on(event: "end", listener: (result: ResultBuilder) => void): Query; + public on(event: string, listener: Function): Query; + } + + export class Events extends events.EventEmitter { + public on(event: "error", listener: (err: Error, client: Client) => void): Events; + public on(event: string, listener: Function): Events; + } +} \ No newline at end of file diff --git a/phantomjs/phantomjs.d.ts b/phantomjs/phantomjs.d.ts index 58e202ac85..3682024b62 100644 --- a/phantomjs/phantomjs.d.ts +++ b/phantomjs/phantomjs.d.ts @@ -1,6 +1,6 @@ // Type definitions for PhantomJS v1.9.0 API // Project: https://github.com/ariya/phantomjs/wiki/API-Reference -// Definitions by: Jed Hunsaker and Mike Keesey +// Definitions by: Jed Hunsaker , Mike Keesey // Definitions: https://github.com/borisyankov/DefinitelyTyped declare function require(module: string): any; diff --git a/progressjs/progress-tests.ts b/progressjs/progress-tests.ts new file mode 100644 index 0000000000..e2ab62f9af --- /dev/null +++ b/progressjs/progress-tests.ts @@ -0,0 +1,36 @@ +/// + +progressJs(); //without selector, set progress-bar for whole page +progressJs("#targetElement"); //start progress-bar for element id='targetElement' + +progressJs().start(); + +progressJs().set(20); //set progress to 20% + +progressJs().start().autoIncrease(4, 500); //every 500 milliseconds, percentage + 4 + +progressJs().increase(); //increase one percent +progressJs().increase(2); //increase two percent + +progressJs().start().set(20).end(); + +progressJs().setOption("theme", "black"); +progressJs().setOption("overlayMode", true); +progressJs().setOption("considerTransition", false); + +progressJs().setOptions({ 'theme': 'black', 'overlayMode': true }); +progressJs().setOptions({ 'theme': 'black', 'overlayMode': true }); +progressJs().setOptions({ 'theme': 'black', 'overlayMode': true, 'considerTransition': false }); +progressJs().setOptions({ 'overlayMode': true }); + +progressJs().onbeforeend(function() { + alert("before end"); +}); + +progressJs().onbeforestart(function() { + alert("before start"); +}); + +progressJs().onprogress(function(targetElm, percent) { + alert("progress changed to:" + percent); +}); diff --git a/progressjs/progress.d.ts b/progressjs/progress.d.ts new file mode 100644 index 0000000000..a7f9923c3f --- /dev/null +++ b/progressjs/progress.d.ts @@ -0,0 +1,103 @@ +// Type definitions for ProgressJs v0.1.0 +// Project: http://usablica.github.io/progress.js/ +// Definitions by: Shunsuke Ohtani +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface ProgressJsStatic { + + /** + * Creating an ProgressJS object. + * + * @param targetElm String (optional) Should be defined to start progress-bar for specific element. + */ + (targetElm?: string): ProgressJs; +} + +interface ProgressJs { + + /** + * Start the progress-bar for defined element(s). + */ + start(): ProgressJs; + + /** + * Set specific percentage to progress-bar. + * + * @param percent Set to specific percentage. + */ + set(percent: number): ProgressJs; + + /** + * Set an auto-increase timer for the progress-bar. + * + * @param size The size of increment when timer elapsed. + * @param millisecond Timer in milliseconds. + */ + autoIncrease(size: number, millisecond: number): ProgressJs; + + /** + * Increase the progress-bar bar specified size. Default size is 1. + * + * @param size The size of increment. + */ + increase(size?: number): ProgressJs; + + /** + * End the progress-bar and remove the elements from page. + */ + end(): ProgressJs; + + /** + * Set a single option to progressJs object. + * + * @param option Option key name. + * @param value Value of the option. + */ + setOption(option: string, value: string): ProgressJs; + setOption(option: string, value: boolean): ProgressJs; + + /** + * Set a group of options to the progressJs object. + * + * @param options Object that contains option keys with values. + */ + setOptions(options: ProgressJsOptions): ProgressJs; + + /** + * Set a callback function for before end of the progress-bar. + * + * @param providedCallback Callback function. + */ + onbeforeend(providedCallback: () => any): ProgressJs; + + /** + * Set a callback function to call before start the progress-bar. + * + * @param providedCallback Callback function. + */ + onbeforestart(providedCallback: () => any): ProgressJs; + + /** + * Set callback function to call for each change of progress-bar. + * + * @param providedCallback Callback function. + */ + onprogress(providedCallback: (targetElement: string, percent: number) => any): ProgressJs; +} + +interface ProgressJsOptions { + /** + * progress bar theme + */ + theme?: string; + /** + * overlay mode makes an overlay layer in the target element + */ + overlayMode?: boolean; + /** + * to consider CSS3 transitions in events + */ + considerTransition?: boolean; +} + +declare var progressJs: ProgressJsStatic diff --git a/promises-a-plus/promises-a-plus-tests.ts b/promises-a-plus/promises-a-plus-tests.ts index 29ca0989bf..bba2586498 100644 --- a/promises-a-plus/promises-a-plus-tests.ts +++ b/promises-a-plus/promises-a-plus-tests.ts @@ -1,6 +1,6 @@ /// -/// -/// +/// +/// /// import When = require("../when/when"); diff --git a/promises-a-plus/promises-a-plus.d.ts b/promises-a-plus/promises-a-plus.d.ts index 7a3bee7764..808995dc92 100644 --- a/promises-a-plus/promises-a-plus.d.ts +++ b/promises-a-plus/promises-a-plus.d.ts @@ -1,3 +1,8 @@ +// Type definitions for promises-a-plus +// Project: http://promisesaplus.com/ +// Definitions by: Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + declare module PromisesAPlus { interface PromiseCtor { (resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): Thenable; diff --git a/promptly/promptly.d.ts b/promptly/promptly.d.ts index 3469ea04ab..beb8319247 100644 --- a/promptly/promptly.d.ts +++ b/promptly/promptly.d.ts @@ -6,6 +6,7 @@ /// declare module "promptly" { + import stream = require('stream'); interface Callback { (err: Error, value: string): void; @@ -17,8 +18,8 @@ declare module "promptly" { validator?: any; retry?: boolean; silent?: boolean; - input?: ReadableStream; - output?: WritableStream; + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; } export function prompt(message: string, fn?: Callback):any; diff --git a/pubsubjs/pubsub.d.ts b/pubsubjs/pubsub.d.ts index 40158c79b8..e24c901a4d 100644 --- a/pubsubjs/pubsub.d.ts +++ b/pubsubjs/pubsub.d.ts @@ -1,4 +1,4 @@ -// Type definitions for PubSubJS 1.3.5 +// Type definitions for PubSubJS 1.3.5 // Project: https://github.com/mroderick/PubSubJS // Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/purl/purl.d.ts b/purl/purl.d.ts index e937a68f44..00312595e3 100644 --- a/purl/purl.d.ts +++ b/purl/purl.d.ts @@ -48,3 +48,7 @@ declare function purl(): purl.Url; * @param someUrl the url to be parsed */ declare function purl(someUrl: string): purl.Url; + +declare module "purl" { + export = purl; +} diff --git a/q-io/Q-io-tests.ts b/q-io/Q-io-tests.ts index f4ac32e9e5..21b8969884 100644 --- a/q-io/Q-io-tests.ts +++ b/q-io/Q-io-tests.ts @@ -8,7 +8,7 @@ var bool:boolean; var num:number; var x:any; var path:string; -var buffer:NodeBuffer; +var buffer:Buffer; var str:string; var strArr:string[]; var source:string; @@ -22,7 +22,7 @@ var anyQ:Q.Promise; var strQ:Q.Promise; var boolQ:Q.Promise; var dateQ:Q.Promise; -var bufferQ:Q.Promise; +var bufferQ:Q.Promise; var statsQ:Q.Promise; var readQ:Q.Promise; @@ -39,12 +39,12 @@ fs.open(path, options).then((x) => { }); //fs.open(path, options):Q.Promise; //fs.open(path, options):Q.Promise; -//fs.open(path, options):Q.Promise; +//fs.open(path, options):Q.Promise; //TODO how to define the multiple return types? use any for now? anyQ = fs.read(path, options); //strQ = fs.read(path, options); -//fs.read(path, options):Q.Promise; +//fs.read(path, options):Q.Promise; voidQ = fs.write(path, buffer, options); voidQ = fs.write(path, str, options); diff --git a/q-io/Q-io.d.ts b/q-io/Q-io.d.ts index cbe37214e7..1e16e3c33b 100644 --- a/q-io/Q-io.d.ts +++ b/q-io/Q-io.d.ts @@ -1,7 +1,7 @@ // Type definitions for Q-io -// Project:https://github.com/kriskowal/q-io -// Definitions by:Bart van der Schoor -// Definitions:https://github.com/borisyankov/DefinitelyTyped +// Project: https://github.com/kriskowal/q-io +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// /// @@ -18,17 +18,17 @@ declare module QioFS { export function open(path:string, options?:any):Q.Promise; //export function open(path:string, options?:any):Q.Promise; //export function open(path:string, options?:any):Q.Promise; - //export function open(path:string, options?:any):Q.Promise; + //export function open(path:string, options?:any):Q.Promise; //TODO how to define the multiple return types? use any for now? export function read(path:string, options?:any):Q.Promise; //export function read(path:string, options?:any):Q.Promise; - //export function read(path:string, options?:any):Q.Promise; + //export function read(path:string, options?:any):Q.Promise; - export function write(path:string, content:NodeBuffer, options?:any):Q.Promise; + export function write(path:string, content:Buffer, options?:any):Q.Promise; export function write(path:string, content:string, options?:any):Q.Promise; - export function append(path:string, content:NodeBuffer, options?:any):Q.Promise; + export function append(path:string, content:Buffer, options?:any):Q.Promise; export function append(path:string, content:string, options?:any):Q.Promise; export function copy(source:string, target:string):Q.Promise; @@ -102,7 +102,7 @@ declare module QioFS { //this should return a q-io/fs-mock MockFS export function reroot(path:string):typeof QioFS; - export function toObject(path:string):{[path:string]:NodeBuffer}; + export function toObject(path:string):{[path:string]:Buffer}; //listed but not implemented by Q-io //export function glob(pattern):Q.Promise; @@ -189,7 +189,7 @@ declare module QioHTTP { declare module Qio { interface ForEachCallback { - (chunk:NodeBuffer):Q.Promise; + (chunk:Buffer):Q.Promise; (chunk:string):Q.Promise; } interface ForEach { @@ -198,24 +198,24 @@ declare module Qio { interface Reader extends ForEach { read(charset:string):Q.Promise; - read():Q.Promise; + read():Q.Promise; close():void; - node:ReadableStream; + node: NodeJS.ReadableStream; } interface Writer { write(content:string):void; - write(content:NodeBuffer):void; + write(content:Buffer):void; flush():Q.Promise; close():void; destroy():void; - node:WritableStream; + node: NodeJS.WritableStream; } interface Stream { read(charset:string):Q.Promise; - read():Q.Promise; + read():Q.Promise; write(content:string):void; - write(content:NodeBuffer):void; + write(content:Buffer):void; flush():Q.Promise; close():void; destroy():void; @@ -229,15 +229,15 @@ declare module Qio { interface QioBufferReader { new ():Qio.Reader; read(stream:Qio.Reader, charset:string):string; - read(stream:Qio.Reader):NodeBuffer; - join(buffers:NodeBuffer[]):NodeBuffer; + read(stream:Qio.Reader):Buffer; + join(buffers:Buffer[]):Buffer; } interface QioBufferWriter { - (writer:NodeBuffer):Qio.Writer; + (writer:Buffer):Qio.Writer; Writer:Qio.Writer; } interface QioBufferStream { - (buffer:NodeBuffer, encoding:string):Qio.Stream + (buffer:Buffer, encoding:string):Qio.Stream } declare module "q-io/http" { diff --git a/q/Q-tests.ts b/q/Q-tests.ts index 6b69fb228c..48a3224bc1 100644 --- a/q/Q-tests.ts +++ b/q/Q-tests.ts @@ -26,7 +26,7 @@ Q.delay("asdf", 1000).then(x => x.length); var eventualAdd = Q.promised((a?: number, b?: number) => a + b); eventualAdd(Q(1), Q(2)).then(x => x.toExponential()); -var eventually = function (eventually) { +var eventually = function (eventually: any) { return Q.delay(eventually, 1000); }; @@ -38,7 +38,7 @@ Q.when(x, function (x) { Q.all([ eventually(10), eventually(20) -]).spread(function (x, y) { +]).spread(function (x: any, y: any) { console.log(x, y); }); @@ -97,7 +97,7 @@ Q.when(Q(8), num => num + "!").then(str => str.split(',')); declare function saveToDisk(): Q.Promise; declare function saveToCloud(): Q.Promise; -Q.allSettled([saveToDisk(), saveToCloud()]).spread(function (disk, cloud) { +Q.allSettled([saveToDisk(), saveToCloud()]).spread(function (disk: any, cloud: any) { console.log("saved to disk:", disk.state === "fulfilled"); console.log("saved to cloud:", cloud.state === "fulfilled"); @@ -110,8 +110,31 @@ Q.allSettled([saveToDisk(), saveToCloud()]).spread(function (disk, cloud) { }).done(); var nodeStyle = (input: string, cb: Function) => { - cb(null, input); + cb(null, input); }; Q.nfapply(nodeStyle, ["foo"]).done((result: string) => {}); Q.nfcall(nodeStyle, "foo").done((result: string) => {}); +Q.denodeify(nodeStyle)('foo').done((result: string) => {}); +Q.nfbind(nodeStyle)('foo').done((result: string) => {}); + + +class Repo { + private items: any[] = [ + { name: 'Max', cute: false }, + { name: 'Annie', cute: true } + ]; + + find(options: any): Q.Promise { + var result = this.items; + + for (var key in options) { + result = result.filter(i => i[key] == options[key]); + } + + return Q(result); + } +} + +var kitty = new Repo(); +Q.nbind(kitty.find, kitty)({ cute: true }).done((kitties: any[]) => {}); \ No newline at end of file diff --git a/q/Q-tests.ts.tscparams b/q/Q-tests.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/q/Q-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/q/Q.d.ts b/q/Q.d.ts index 65b2b8223d..8e9696be56 100644 --- a/q/Q.d.ts +++ b/q/Q.d.ts @@ -1,6 +1,6 @@ // Type definitions for Q // Project: https://github.com/kriskowal/q -// Definitions by: Barrie Nemetchek, Andrew Gaspar, John Reilly +// Definitions by: Barrie Nemetchek , Andrew Gaspar , John Reilly // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -207,6 +207,8 @@ declare module Q { export function invoke(obj: any, functionName: string, ...args: any[]): Promise; export function mcall(obj: any, functionName: string, ...args: any[]): Promise; + export function denodeify(nodeFunction: Function, ...args: any[]): (...args: any[]) => Promise; + export function nbind(nodeFunction: Function, thisArg: any, ...args: any[]): (...args: any[]) => Promise; export function nfbind(nodeFunction: Function, ...args: any[]): (...args: any[]) => Promise; export function nfcall(nodeFunction: Function, ...args: any[]): Promise; export function nfapply(nodeFunction: Function, args: any[]): Promise; diff --git a/qunit/qunit.d.ts b/qunit/qunit.d.ts index 68d0163b6b..c6fe34f0f7 100644 --- a/qunit/qunit.d.ts +++ b/qunit/qunit.d.ts @@ -1,7 +1,7 @@ // Type definitions for QUnit 1.10 // Project: http://qunitjs.com/ // Definitions by: Diullei Gomes -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped interface DoneCallbackObject { @@ -381,7 +381,7 @@ interface QUnitStatic extends QUnitAssert{ * @param expected Number of assertions in this test * @param test Function to close over assertions */ - asyncTest(name: string, expected: number, test: () => any): any; + asyncTest(name: string, expected: number, test: (assert: QUnitAssert) => any): any; /** * Add an asynchronous test to run. The test must include a call to start(). @@ -392,7 +392,7 @@ interface QUnitStatic extends QUnitAssert{ * @param name Title of unit being tested * @param test Function to close over assertions */ - asyncTest(name: string, test: () => any): any; + asyncTest(name: string, test: (assert: QUnitAssert) => any): any; /** * Specify how many assertions are expected to run within a test. @@ -662,7 +662,7 @@ declare function testStart(callback: (details: TestStartCallbackObject) => any): * @param expected Number of assertions in this test * @param test Function to close over assertions */ -declare function asyncTest(name: string, expected?: any, test?: () => any): any; +declare function asyncTest(name: string, expected?: any, test?: (assert: QUnitAssert) => any): any; /** * Add an asynchronous test to run. The test must include a call to start(). @@ -673,7 +673,7 @@ declare function asyncTest(name: string, expected?: any, test?: () => any): any; * @param name Title of unit being tested * @param test Function to close over assertions */ -declare function asyncTest(name: string, test: () => any): any; +declare function asyncTest(name: string, test: (assert: QUnitAssert) => any): any; /** * Specify how many assertions are expected to run within a test. @@ -720,4 +720,4 @@ declare function equiv(a: any, b: any): any; declare var raises: any; /* QUNIT */ -declare var QUnit: QUnitStatic; \ No newline at end of file +declare var QUnit: QUnitStatic; diff --git a/raphael/raphael.d.ts b/raphael/raphael.d.ts index fc0b26292d..e57aa3954c 100644 --- a/raphael/raphael.d.ts +++ b/raphael/raphael.d.ts @@ -1,7 +1,7 @@ // Type definitions for Raphael 2.1 // Project: http://raphaeljs.com -// Definitions by: https://github.com/CheCoxshall -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: CheCoxshall +// Definitions: https://github.com/borisyankov/DefinitelyTyped interface BoundingBox { diff --git a/readdir-stream/readdir-stream-tests.ts b/readdir-stream/readdir-stream-tests.ts new file mode 100644 index 0000000000..a731e86ba8 --- /dev/null +++ b/readdir-stream/readdir-stream-tests.ts @@ -0,0 +1,8 @@ +/// +/// + +import readdir = require('readdir-stream'); + +var rs: NodeJS.ReadableStream; + +rs = readdir('foo'); diff --git a/readdir-stream/readdir-stream.d.ts b/readdir-stream/readdir-stream.d.ts new file mode 100644 index 0000000000..5c48185077 --- /dev/null +++ b/readdir-stream/readdir-stream.d.ts @@ -0,0 +1,11 @@ +// Type definitions for readdir-stream v0.1.0 +// Project: https://github.com/logicalparadox/readdir-stream +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'readdir-stream' { + function readdir(dir: string): NodeJS.ReadableStream; + export = readdir; +} diff --git a/recaptcha/recaptcha-tests.ts b/recaptcha/recaptcha-tests.ts new file mode 100644 index 0000000000..61ef51d9f1 --- /dev/null +++ b/recaptcha/recaptcha-tests.ts @@ -0,0 +1,52 @@ +/// + +var recaptchaOptions: RecaptchaOptions = { + theme : 'custom', + custom_theme_widget: 'recaptcha_widget' + }; + +var recaptchaOptions: RecaptchaOptions = { + custom_translations: { instructions_visual: "This is my text:" } +}; + +var recaptchaOptions: RecaptchaOptions = { + custom_translations: { + instructions_visual: "Scrivi le due parole:", + instructions_audio: "Trascrivi ci\u00f2 che senti:", + play_again: "Riascolta la traccia audio", + cant_hear_this: "Scarica la traccia in formato MP3", + visual_challenge: "Modalit\u00e0 visiva", + audio_challenge: "Modalit\u00e0 auditiva", + refresh_btn: "Chiedi due nuove parole", + help_btn: "Aiuto", + incorrect_try_again: "Scorretto. Riprova.", + }, + lang: 'it', + theme: 'red' +}; + +var recaptchaOptions: RecaptchaOptions = { + theme : 'white', + tabindex : 2 +}; + +Recaptcha.create("public_key_a", + "element_id_a", + { + theme: "red", + callback: Recaptcha.focus_response_field + } +); + +Recaptcha.create("public_key_b", + "element_id_b", + recaptchaOptions +); + +Recaptcha.switch_type("audio"); +Recaptcha.get_challenge(); +Recaptcha.get_response(); +Recaptcha.reload(); +Recaptcha.showhelp(); +Recaptcha.focus_response_field(); +Recaptcha.destroy(); diff --git a/recaptcha/recaptcha.d.ts b/recaptcha/recaptcha.d.ts new file mode 100644 index 0000000000..db20962759 --- /dev/null +++ b/recaptcha/recaptcha.d.ts @@ -0,0 +1,39 @@ +// Type definitions for Google Recaptcha +// Project: https://www.google.com/recaptcha +// Definitions by: Brent Jenkins +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare class Recaptcha { + constructor(); + static reload(): void; + static switch_type(newtype: string): void; + static showhelp(): void; + static get_challenge(): string; + static get_response(): string; + static focus_response_field(): void; + static create(public_key: string, element: string, options: RecaptchaOptions): void; + static destroy(): void; +} + +interface RecaptchaOptions { + tabindex?: number; + theme?: string; + callback?: Function; + lang?: string; + custom_theme_widget?: string; + custom_translations?: CustomTranslations; +} + +interface CustomTranslations { + visual_challenge?: string; + audio_challenge?: string; + refresh_btn?: string; + instructions_visual?: string; + instructions_audio?: string; + help_btn?: string; + play_again?: string; + cant_hear_this?: string; + incorrect_try_again?: string; + image_alt_text?: string; + privacy_and_terms?: string; +} diff --git a/redis/redis-tests.ts b/redis/redis-tests.ts new file mode 100644 index 0000000000..98ed2371be --- /dev/null +++ b/redis/redis-tests.ts @@ -0,0 +1,62 @@ +/// + +import redis = require('redis'); + +var value: any; +var valueArr: any[]; +var num: number; +var str: string; +var bool: boolean; +var err: Error; +var args: any[]; +var options: redis.ClientOpts; +var client: redis.RedisClient; +var info: redis.ServerInfo; +var resCallback: (err: Error, res: any) => void; +var numCallback: (err: Error, res: number) => void; +var strCallback: (err: Error, res: string) => void; +var messageHandler: (channel: string, message: any) => void; + +// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- + +bool = redis.debug_mode; +redis.print(err, value); + +// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- + +client = redis.createClient(num, str, options); + +bool = client.connected; +num = client.retry_delay; +num = client.retry_backoff; +valueArr = client.command_queue; +valueArr = client.offline_queue; +info = client.server_info; + +// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- + +client.end(); + +// Connection (http://redis.io/commands#connection) +client.auth(str, resCallback); +client.ping(numCallback); + +// Strings (http://redis.io/commands#strings) +client.append(str, str, numCallback); +client.bitcount(str, numCallback); +client.bitcount(str, num, num, numCallback); +client.set(str, str, strCallback); +client.get(str, strCallback); +client.exists(str, str, numCallback); + +client.publish(str, value); +client.subscribe(str); +client.on(str, messageHandler); + +// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- + +// some of the bulk methods +client.get(args); +client.get(args, resCallback); +client.set(args); +client.set(args, resCallback); diff --git a/redis/redis.d.ts b/redis/redis.d.ts new file mode 100644 index 0000000000..e31b130aca --- /dev/null +++ b/redis/redis.d.ts @@ -0,0 +1,224 @@ +// Type definitions for redis +// Project: https://github.com/mranney/node_redis +// Definitions by: Carlos Ballesteros Velasco +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/redis.d.ts + +declare module "redis" { + export function createClient(port_arg: number, host_arg: string, options: ClientOpts): RedisClient; + export function print(err: Error, reply: any): void; + export var debug_mode: boolean; + + interface MessageHandler { + (channel: string, message: any): void; + } + + interface ResCallback { + (err: Error, res: any): void; + } + + interface NumCallback { + (err: Error, reply: number): void; + } + + interface StringCallback { + (err: Error, reply: string): void; + } + + interface ServerInfo { + redis_version: string; + versions: number[]; + } + + interface ClientOpts { + parser: string; + return_buffers?: boolean; + detect_buffers?: boolean; + socket_nodelay?: boolean; + no_ready_check?: boolean; + enable_offline_queue?: boolean; + retry_max_delay?: number; + connect_timeout?: number; + max_attempts?: number; + auth_pass?: boolean; + } + + interface RedisClient { + // event: connect + // event: error + // event: message + // event: pmessage + // event: subscribe + // event: psubscribe + // event: unsubscribe + // event: punsubscribe + + connected: boolean; + retry_delay: number; + retry_backoff: number; + command_queue: any[]; + offline_queue: any[]; + server_info: ServerInfo; + + end(): void; + + // Connection (http://redis.io/commands#connection) + auth(password: string, callback?: ResCallback): void; + ping(callback?: NumCallback): void; + + // Strings (http://redis.io/commands#strings) + append(key: string, value: string, callback?: NumCallback): void; + bitcount(key: string, callback?: NumCallback): void; + bitcount(key: string, start: number, end: number, callback?: NumCallback): void; + set(key: string, value: string, callback?: StringCallback): void; + get(key: string, callback?: StringCallback): void; + exists(key: string, value: string, callback?: NumCallback): void; + + publish(channel: string, value: any): void; + subscribe(channel: string): void; + on(channel: string, handler: MessageHandler): void; + + /* + commands = set_union([ + "get", "set", "setnx", "setex", "append", "strlen", "del", "exists", "setbit", "getbit", "setrange", "getrange", "substr", + "incr", "decr", "mget", "rpush", "lpush", "rpushx", "lpushx", "linsert", "rpop", "lpop", "brpop", "brpoplpush", "blpop", "llen", "lindex", + "lset", "lrange", "ltrim", "lrem", "rpoplpush", "sadd", "srem", "smove", "sismember", "scard", "spop", "srandmember", "sinter", "sinterstore", + "sunion", "sunionstore", "sdiff", "sdiffstore", "smembers", "zadd", "zincrby", "zrem", "zremrangebyscore", "zremrangebyrank", "zunionstore", + "zinterstore", "zrange", "zrangebyscore", "zrevrangebyscore", "zcount", "zrevrange", "zcard", "zscore", "zrank", "zrevrank", "hset", "hsetnx", + "hget", "hmset", "hmget", "hincrby", "hdel", "hlen", "hkeys", "hvals", "hgetall", "hexists", "incrby", "decrby", "getset", "mset", "msetnx", + "randomkey", "select", "move", "rename", "renamenx", "expire", "expireat", "keys", "dbsize", "auth", "ping", "echo", "save", "bgsave", + "bgrewriteaof", "shutdown", "lastsave", "type", "multi", "exec", "discard", "sync", "flushdb", "flushall", "sort", "info", "monitor", "ttl", + "persist", "slaveof", "debug", "config", "subscribe", "unsubscribe", "psubscribe", "punsubscribe", "publish", "watch", "unwatch", "cluster", + "restore", "migrate", "dump", "object", "client", "eval", "evalsha"], require("./lib/commands")); + */ + + get(args: any[], callback?: ResCallback): void; + set(args: any[], callback?: ResCallback): void; + setnx(args: any[], callback?: ResCallback): void; + setex(args: any[], callback?: ResCallback): void; + append(args: any[], callback?: ResCallback): void; + strlen(args: any[], callback?: ResCallback): void; + del(args: any[], callback?: ResCallback): void; + exists(args: any[], callback?: ResCallback): void; + setbit(args: any[], callback?: ResCallback): void; + getbit(args: any[], callback?: ResCallback): void; + setrange(args: any[], callback?: ResCallback): void; + getrange(args: any[], callback?: ResCallback): void; + substr(args: any[], callback?: ResCallback): void; + incr(args: any[], callback?: ResCallback): void; + decr(args: any[], callback?: ResCallback): void; + mget(args: any[], callback?: ResCallback): void; + rpush(args: any[], callback?: ResCallback): void; + lpush(args: any[], callback?: ResCallback): void; + rpushx(args: any[], callback?: ResCallback): void; + lpushx(args: any[], callback?: ResCallback): void; + linsert(args: any[], callback?: ResCallback): void; + rpop(args: any[], callback?: ResCallback): void; + lpop(args: any[], callback?: ResCallback): void; + brpop(args: any[], callback?: ResCallback): void; + brpoplpush(args: any[], callback?: ResCallback): void; + blpop(args: any[], callback?: ResCallback): void; + llen(args: any[], callback?: ResCallback): void; + lindex(args: any[], callback?: ResCallback): void; + lset(args: any[], callback?: ResCallback): void; + lrange(args: any[], callback?: ResCallback): void; + ltrim(args: any[], callback?: ResCallback): void; + lrem(args: any[], callback?: ResCallback): void; + rpoplpush(args: any[], callback?: ResCallback): void; + sadd(args: any[], callback?: ResCallback): void; + srem(args: any[], callback?: ResCallback): void; + smove(args: any[], callback?: ResCallback): void; + sismember(args: any[], callback?: ResCallback): void; + scard(args: any[], callback?: ResCallback): void; + spop(args: any[], callback?: ResCallback): void; + srandmember(args: any[], callback?: ResCallback): void; + sinter(args: any[], callback?: ResCallback): void; + sinterstore(args: any[], callback?: ResCallback): void; + sunion(args: any[], callback?: ResCallback): void; + sunionstore(args: any[], callback?: ResCallback): void; + sdiff(args: any[], callback?: ResCallback): void; + sdiffstore(args: any[], callback?: ResCallback): void; + smembers(args: any[], callback?: ResCallback): void; + zadd(args: any[], callback?: ResCallback): void; + zincrby(args: any[], callback?: ResCallback): void; + zrem(args: any[], callback?: ResCallback): void; + zremrangebyscore(args: any[], callback?: ResCallback): void; + zremrangebyrank(args: any[], callback?: ResCallback): void; + zunionstore(args: any[], callback?: ResCallback): void; + zinterstore(args: any[], callback?: ResCallback): void; + zrange(args: any[], callback?: ResCallback): void; + zrangebyscore(args: any[], callback?: ResCallback): void; + zrevrangebyscore(args: any[], callback?: ResCallback): void; + zcount(args: any[], callback?: ResCallback): void; + zrevrange(args: any[], callback?: ResCallback): void; + zcard(args: any[], callback?: ResCallback): void; + zscore(args: any[], callback?: ResCallback): void; + zrank(args: any[], callback?: ResCallback): void; + zrevrank(args: any[], callback?: ResCallback): void; + hset(args: any[], callback?: ResCallback): void; + hsetnx(args: any[], callback?: ResCallback): void; + hget(args: any[], callback?: ResCallback): void; + hmset(args: any[], callback?: ResCallback): void; + hmget(args: any[], callback?: ResCallback): void; + hincrby(args: any[], callback?: ResCallback): void; + hdel(args: any[], callback?: ResCallback): void; + hlen(args: any[], callback?: ResCallback): void; + hkeys(args: any[], callback?: ResCallback): void; + hvals(args: any[], callback?: ResCallback): void; + hgetall(args: any[], callback?: ResCallback): void; + hexists(args: any[], callback?: ResCallback): void; + incrby(args: any[], callback?: ResCallback): void; + decrby(args: any[], callback?: ResCallback): void; + getset(args: any[], callback?: ResCallback): void; + mset(args: any[], callback?: ResCallback): void; + msetnx(args: any[], callback?: ResCallback): void; + randomkey(args: any[], callback?: ResCallback): void; + select(args: any[], callback?: ResCallback): void; + move(args: any[], callback?: ResCallback): void; + rename(args: any[], callback?: ResCallback): void; + renamenx(args: any[], callback?: ResCallback): void; + expire(args: any[], callback?: ResCallback): void; + expireat(args: any[], callback?: ResCallback): void; + keys(args: any[], callback?: ResCallback): void; + dbsize(args: any[], callback?: ResCallback): void; + auth(args: any[], callback?: ResCallback): void; + ping(args: any[], callback?: ResCallback): void; + echo(args: any[], callback?: ResCallback): void; + save(args: any[], callback?: ResCallback): void; + bgsave(args: any[], callback?: ResCallback): void; + bgrewriteaof(args: any[], callback?: ResCallback): void; + shutdown(args: any[], callback?: ResCallback): void; + lastsave(args: any[], callback?: ResCallback): void; + type(args: any[], callback?: ResCallback): void; + multi(args: any[], callback?: ResCallback): void; + exec(args: any[], callback?: ResCallback): void; + discard(args: any[], callback?: ResCallback): void; + sync(args: any[], callback?: ResCallback): void; + flushdb(args: any[], callback?: ResCallback): void; + flushall(args: any[], callback?: ResCallback): void; + sort(args: any[], callback?: ResCallback): void; + info(args: any[], callback?: ResCallback): void; + monitor(args: any[], callback?: ResCallback): void; + ttl(args: any[], callback?: ResCallback): void; + persist(args: any[], callback?: ResCallback): void; + slaveof(args: any[], callback?: ResCallback): void; + debug(args: any[], callback?: ResCallback): void; + config(args: any[], callback?: ResCallback): void; + subscribe(args: any[], callback?: ResCallback): void; + unsubscribe(args: any[], callback?: ResCallback): void; + psubscribe(args: any[], callback?: ResCallback): void; + punsubscribe(args: any[], callback?: ResCallback): void; + publish(args: any[], callback?: ResCallback): void; + watch(args: any[], callback?: ResCallback): void; + unwatch(args: any[], callback?: ResCallback): void; + cluster(args: any[], callback?: ResCallback): void; + restore(args: any[], callback?: ResCallback): void; + migrate(args: any[], callback?: ResCallback): void; + dump(args: any[], callback?: ResCallback): void; + object(args: any[], callback?: ResCallback): void; + client(args: any[], callback?: ResCallback): void; + eval(args: any[], callback?: ResCallback): void; + evalsha(args: any[], callback?: ResCallback): void; + } +} diff --git a/ref-array/ref-array.d.ts b/ref-array/ref-array.d.ts new file mode 100644 index 0000000000..4066e0d65a --- /dev/null +++ b/ref-array/ref-array.d.ts @@ -0,0 +1,53 @@ +// Type definitions for ref-array +// Project: https://github.com/TooTallNate/ref-array +// Definitions by: Paul Loyd +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "ref-array" { + import ref = require('ref'); + + interface ArrayType extends ref.Type { + BYTES_PER_ELEMENT: number; + fixedLength: number; + /** The reference to the base type. */ + type: ref.Type; + + /** + * Accepts a Buffer instance that should be an already-populated with data + * for the ArrayType. The "length" of the Array is determined by searching + * through the buffer's contents until an aligned NULL pointer is encountered. + */ + untilZeros(buffer: Buffer): { [i: number]: T; length: number; toArray(): T[]; + toJSON(): T[]; inspect(): string; buffer: Buffer; ref(): Buffer; }; + + new (length?: number): { [i: number]: T; length: number; toArray(): T[]; + toJSON(): T[]; inspect(): string; buffer: Buffer; ref(): Buffer; }; + new (data: number[], length?: number): { [i: number]: T; length: number; toArray(): T[]; + toJSON(): T[]; inspect(): string; buffer: Buffer; ref(): Buffer; }; + new (data: Buffer, length?: number): { [i: number]: T; length: number; toArray(): T[]; + toJSON(): T[]; inspect(): string; buffer: Buffer; ref(): Buffer; }; + (length?: number): { [i: number]: T; length: number; toArray(): T[]; + toJSON(): T[]; inspect(): string; buffer: Buffer; ref(): Buffer; }; + (data: number[], length?: number): { [i: number]: T; length: number; toArray(): T[]; + toJSON(): T[]; inspect(): string; buffer: Buffer; ref(): Buffer; }; + (data: Buffer, length?: number): { [i: number]: T; length: number; toArray(): T[]; + toJSON(): T[]; inspect(): string; buffer: Buffer; ref(): Buffer; }; + } + + /** + * The array type meta-constructor. + * The returned constructor's API is highly influenced by the WebGL + * TypedArray API. + */ + var ArrayType: { + new (type: ref.Type, length?: number): ArrayType; + new (type: string, length?: number): ArrayType; + (type: ref.Type, length?: number): ArrayType; + (type: string, length?: number): ArrayType; + }; + +export = ArrayType; +} diff --git a/ref-struct/ref-struct.d.ts b/ref-struct/ref-struct.d.ts new file mode 100644 index 0000000000..7c2019655c --- /dev/null +++ b/ref-struct/ref-struct.d.ts @@ -0,0 +1,64 @@ +// Type definitions for ref-union +// Project: https://github.com/TooTallNate/ref-struct +// Definitions by: Paul Loyd +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "ref-struct" { + import ref = require('ref'); + + /** + * This is the `constructor` of the Struct type that gets returned. + * + * Invoke it with `new` to create a new Buffer instance backing the struct. + * Pass it an existing Buffer instance to use that as the backing buffer. + * Pass in an Object containing the struct fields to auto-populate the + * struct with the data. + * + * @constructor + */ + interface StructType extends ref.Type { + /** Pass it an existing Buffer instance to use that as the backing buffer. */ + new (arg: Buffer, data?: {}): any; + new (data?: {}): any; + /** Pass it an existing Buffer instance to use that as the backing buffer. */ + (arg: Buffer, data?: {}): any; + (data?: {}): any; + + fields: {[key: string]: {type: ref.Type}}; + + /** + * Adds a new field to the struct instance with the given name and type. + * Note that this function will throw an Error if any instances of the struct + * type have already been created, therefore this function must be called at the + * beginning, before any instances are created. + */ + defineProperty(name: string, type: ref.Type): void; + + /** + * Adds a new field to the struct instance with the given name and type. + * Note that this function will throw an Error if any instances of the struct + * type have already been created, therefore this function must be called at the + * beginning, before any instances are created. + */ + defineProperty(name: string, type: string): void; + + /** + * Custom for struct type instances. + * @override + */ + toString(): string; + } + + /** The struct type meta-constructor. */ + var StructType: { + new (fields?: {}): StructType; + new (fields?: any[]): StructType; + (fields?: {}): StructType; + (fields?: any[]): StructType; + } + +export = StructType; +} diff --git a/ref-union/ref-union.d.ts b/ref-union/ref-union.d.ts new file mode 100644 index 0000000000..23dbdae397 --- /dev/null +++ b/ref-union/ref-union.d.ts @@ -0,0 +1,64 @@ +// Type definitions for ref-union +// Project: https://github.com/TooTallNate/ref-union +// Definitions by: Paul Loyd +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "ref-union" { + import ref = require('ref'); + + /** + * This is the `constructor` of the Struct type that gets returned. + * + * Invoke it with `new` to create a new Buffer instance backing the union. + * Pass it an existing Buffer instance to use that as the backing buffer. + * Pass in an Object containing the union fields to auto-populate the + * union with the data. + * + * @constructor + */ + interface UnionType extends ref.Type { + /** Pass it an existing Buffer instance to use that as the backing buffer. */ + new (arg: Buffer, data?: {}): any; + new (data?: {}): any; + /** Pass it an existing Buffer instance to use that as the backing buffer. */ + (arg: Buffer, data?: {}): any; + (data?: {}): any; + + fields: {[key: string]: {type: ref.Type}}; + + /** + * Adds a new field to the union instance with the given name and type. + * Note that this function will throw an Error if any instances of the union + * type have already been created, therefore this function must be called at the + * beginning, before any instances are created. + */ + defineProperty(name: string, type: ref.Type): void; + + /** + * Adds a new field to the union instance with the given name and type. + * Note that this function will throw an Error if any instances of the union + * type have already been created, therefore this function must be called at the + * beginning, before any instances are created. + */ + defineProperty(name: string, type: string): void; + + /** + * Custom for union type instances. + * @override + */ + toString(): string; + } + + /** The union type meta-constructor. */ + var UnionType: { + new (fields?: {}): UnionType; + new (fields?: any[]): UnionType; + (fields?: {}): UnionType; + (fields?: any[]): UnionType; + } + +export = UnionType; +} diff --git a/ref/ref.d.ts b/ref/ref.d.ts new file mode 100644 index 0000000000..86e7840bed --- /dev/null +++ b/ref/ref.d.ts @@ -0,0 +1,190 @@ +// Type definitions for ref-union +// Project: https://github.com/TooTallNate/ref +// Definitions by: Paul Loyd +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "ref" { + export interface Type { + /** The size in bytes required to hold this datatype. */ + size: number; + /** The current level of indirection of the buffer. */ + indirection: number; + /** To invoke when `ref.get` is invoked on a buffer of this type. */ + get(buffer: Buffer, offset: number): any; + /** To invoke when `ref.set` is invoked on a buffer of this type. */ + set(buffer: Buffer, offset: number, value: any): void; + /** The name to use during debugging for this datatype. */ + name?: string; + /** The alignment of this datatype when placed inside a struct. */ + alignment?: number; + } + + /** A Buffer that references the C NULL pointer. */ + export var NULL: Buffer; + /** A pointer-sized buffer pointing to NULL. */ + export var NULL_POINTER: Buffer; + /** Get the memory address of buffer. */ + export function address(buffer: Buffer): number; + /** Allocate the memory with the given value written to it. */ + export function alloc(type: Type, value?: any): Buffer; + /** Allocate the memory with the given value written to it. */ + export function alloc(type: string, value?: any): Buffer; + + /** + * Allocate the memory with the given string written to it with the given + * encoding (defaults to utf8). The buffer is 1 byte longer than the + * string itself, and is NULL terminated. + */ + export function allocCString(string: string, encoding?: string): Buffer; + + /** Coerce a type.*/ + export function coerceType(type: Type): Type; + /** Coerce a type. String are looked up from the ref.types object. */ + export function coerceType(type: string): Type; + + /** + * Get value after dereferencing buffer. + * That is, first it checks the indirection count of buffer's type, and + * if it's greater than 1 then it merely returns another Buffer, but with + * one level less indirection. + */ + export function deref(buffer: Buffer): any; + + /** Create clone of the type, with decremented indirection level by 1. */ + export function derefType(type: Type): Type; + /** Create clone of the type, with decremented indirection level by 1. */ + export function derefType(type: string): Type; + /** Represents the native endianness of the processor ("LE" or "BE"). */ + export var endianness: string; + /** Check the indirection level and return a dereferenced when necessary. */ + export function get(buffer: Buffer, offset?: number, type?: Type): any; + /** Check the indirection level and return a dereferenced when necessary. */ + export function get(buffer: Buffer, offset?: number, type?: string): any; + /** Get type of the buffer. Create a default type when none exists. */ + export function getType(buffer: Buffer): Type; + /** Check the NULL. */ + export function isNull(buffer: Buffer): boolean; + /** Read C string until the first NULL. */ + export function readCString(buffer: Buffer, offset?: number): string; + + /** + * Read a big-endian signed 64-bit int. + * If there is losing precision, then return a string, otherwise a number. + * @return {number|string} + */ + export function readInt64BE(buffer: Buffer, offset?: number): any; + + /** + * Read a little-endian signed 64-bit int. + * If there is losing precision, then return a string, otherwise a number. + * @return {number|string} + */ + export function readInt64LE(buffer: Buffer, offset?: number): any; + + /** Read a JS Object that has previously been written. */ + export function readObject(buffer: Buffer, offset?: number): Object; + /** Read data from the pointer. */ + export function readPointer(buffer: Buffer, offset?: number, + length?: number): Buffer; + /** + * Read a big-endian unsigned 64-bit int. + * If there is losing precision, then return a string, otherwise a number. + * @return {number|string} + */ + export function readUInt64BE(buffer: Buffer, offset?: number): any; + + /** + * Read a little-endian unsigned 64-bit int. + * If there is losing precision, then return a string, otherwise a number. + * @return {number|string} + */ + export function readUInt64LE(buffer: Buffer, offset?: number): any; + + /** Create pointer to buffer. */ + export function ref(buffer: Buffer): Buffer; + /** Create clone of the type, with incremented indirection level by 1. */ + export function refType(type: Type): Type; + /** Create clone of the type, with incremented indirection level by 1. */ + export function refType(type: string): Type; + + /** + * Create buffer with the specified size, with the same address as source. + * This function "attaches" source to the returned buffer to prevent it from + * being garbage collected. + */ + export function reinterpret(buffer: Buffer, size: number, + offset?: number): Buffer; + /** + * Scan past the boundary of the buffer's length until it finds size number + * of aligned NULL bytes. + */ + export function reinterpretUntilZeros(buffer: Buffer, size: number, + offset?: number): Buffer; + + /** Write pointer if the indirection is 1, otherwise write value. */ + export function set(buffer: Buffer, offset: number, value: any, type?: Type): void; + /** Write pointer if the indirection is 1, otherwise write value. */ + export function set(buffer: Buffer, offset: number, value: any, type?: string): void; + /** Write the string as a NULL terminated. Default encoding is utf8. */ + export function writeCString(buffer: Buffer, offset: number, + string: string, encoding?: string): void; + /** Write a big-endian signed 64-bit int. */ + export function writeInt64BE(buffer: Buffer, offset: number, input: number): void; + /** Write a big-endian signed 64-bit int. */ + export function writeInt64BE(buffer: Buffer, offset: number, input: string): void; + /** Write a little-endian signed 64-bit int. */ + export function writeInt64LE(buffer: Buffer, offset: number, input: number): void; + /** Write a little-endian signed 64-bit int. */ + export function writeInt64LE(buffer: Buffer, offset: number, input: string): void; + + /** + * Write the JS Object. This function "attaches" object to buffer to prevent + * it from being garbage collected. + */ + export function writeObject(buffer: Buffer, offset: number, object: Object): void; + + /** + * Write the memory address of pointer to buffer at the specified offset. This + * function "attaches" object to buffer to prevent it from being garbage collected. + */ + export function writePointer(buffer: Buffer, offset: number, + pointer: Buffer): void; + + /** Write a little-endian unsigned 64-bit int. */ + export function writeUInt64BE(buffer: Buffer, offset: number, input: number): void; + /** Write a little-endian unsigned 64-bit int. */ + export function writeUInt64BE(buffer: Buffer, offset: number, input: string): void; + + /** + * Attach object to buffer such. + * It prevents object from being garbage collected until buffer does. + */ + export function _attach(buffer: Buffer, object: Object): void; + + /** Same as ref.reinterpret, except that this version does not attach buffer. */ + export function _reinterpret(buffer: Buffer, size: number, + offset?: number): Buffer; + /** Same as ref.reinterpretUntilZeros, except that this version does not attach buffer. */ + export function _reinterpretUntilZeros(buffer: Buffer, size: number, + offset?: number): Buffer; + /** Same as ref.writePointer, except that this version does not attach pointer. */ + export function _writePointer(buffer: Buffer, offset: number, + pointer: Buffer): void; + /** Same as ref.writeObject, except that this version does not attach object. */ + export function _writeObject(buffer: Buffer, offset: number, object: Object): void; + + /** Default types. */ + export var types: { + void: Type; int64: Type; ushort: Type; + int: Type; uint64: Type; float: Type; + uint: Type; long: Type; double: Type; + int8: Type; ulong: Type; Object: Type; + uint8: Type; longlong: Type; CString: Type; + int16: Type; ulonglong: Type; bool: Type; + uint16: Type; char: Type; byte: Type; + int32: Type; uchar: Type; size_t: Type; + uint32: Type; short: Type; + }; +} diff --git a/request/request-tests.ts b/request/request-tests.ts new file mode 100644 index 0000000000..d422c3abc5 --- /dev/null +++ b/request/request-tests.ts @@ -0,0 +1,198 @@ +/// + +import request = require('request'); +import http = require('http'); +import stream = require('stream'); +import formData = require('form-data'); + +var value: any; +var str: string; +var buffer: NodeBuffer; +var num: number; +var bool: boolean; +var date: Date; +var obj: Object; +var dest: string; + +var uri: string; +var headers: {[key: string]: string}; + +var agent: http.Agent; +var write: stream.Writable; +var req: request.Request; +var form: formData.FormData; + +var bodyArr: request.RequestPart[] = [{ + body: value +}, { + body: value +}, { + body: value +}]; + +// --- --- --- --- --- --- --- --- --- --- --- --- + +str = req.toJSON(); + +var cookieValue: request.CookieValue; +str = cookieValue.name; +value = cookieValue.value; +bool = cookieValue.httpOnly; + +var cookie: request.Cookie; +str = cookie.str; +date = cookie.expires; +str = cookie.path; +str = cookie.toString(); + +var jar: request.CookieJar; +jar.add(cookie); +cookie = jar.get(req); +str = jar.cookieString(req); + +var aws: request.AWSOptions; +str = aws.secret; +str = aws.bucket; + +var oauth: request.OAuthOptions; +str = oauth.callback; +str = oauth.consumer_key; +str = oauth.consumer_secret; +str = oauth.token; +str = oauth.token_secret; +str = oauth.verifier; + +var options: request.Options = { + url: str, + uri: str, + callback: (error: any, response: any, body: any) => { + + }, + jar: value, + form: value, + oauth: value, + aws: aws, + qs: obj, + json: value, + multipart: value, + agentOptions: value, + agentClass: value, + forever: value, + host: str, + port: num, + method: str, + headers: value, + body: value, + followRedirect: bool, + followAllRedirects: bool, + maxRedirects: num, + encoding: str, + pool: value, + timeout: num, + proxy: value, + strictSSL: bool +}; + +// --- --- --- --- --- --- --- --- --- --- --- --- + +agent = req.getAgent(); +//req.start(); +//req.abort(); +req.pipeDest(dest); +req = req.setHeader(str, str); +req = req.setHeader(str, str, bool); +req = req.setHeaders(headers); +req = req.qs(obj); +req = req.qs(obj, bool); +req = req.form(obj); +form = req.form(); +req = req.multipart(bodyArr); +req = req.json(value); +req = req.aws(aws); +req = req.aws(aws, bool); +req = req.oauth(oauth); +req = req.jar(jar); +write = req.pipe(write); +write = req.pipe(write, value); +req.write(); +req.end(str); +req.end(buffer); +req.pause(); +req.resume(); +req.abort(); +req.destroy(); + +// --- --- --- --- --- --- --- --- --- --- --- --- + +var callback: (error: any, response: any, body: any) => void; + +value = request.initParams; + +req = request(uri); +req = request(uri, options); +req = request(uri, options, callback); +req = request(uri, callback); +req = request(options); +req = request(options, callback); + +req = request.request(uri); +req = request.request(uri, options); +req = request.request(uri, options, callback); +req = request.request(uri, callback); +req = request.request(options); +req = request.request(options, callback); + +req = request.get(uri); +req = request.get(uri, options); +req = request.get(uri, options, callback); +req = request.get(uri, callback); +req = request.get(options); +req = request.get(options, callback); + +req = request.post(uri); +req = request.post(uri, options); +req = request.post(uri, options, callback); +req = request.post(uri, callback); +req = request.post(options); +req = request.post(options, callback); + +req = request.put(uri); +req = request.put(uri, options); +req = request.put(uri, options, callback); +req = request.put(uri, callback); +req = request.put(options); +req = request.put(options, callback); + +req = request.head(uri); +req = request.head(uri, options); +req = request.head(uri, options, callback); +req = request.head(uri, callback); +req = request.head(options); +req = request.head(options, callback); + +req = request.patch(uri); +req = request.patch(uri, options); +req = request.patch(uri, options, callback); +req = request.patch(uri, callback); +req = request.patch(options); +req = request.patch(options, callback); + +req = request.del(uri); +req = request.del(uri, options); +req = request.del(uri, options, callback); +req = request.del(uri, callback); +req = request.del(options); +req = request.del(options, callback); + +req = request.forever(value, value); +jar = request.jar(); +cookie = request.cookie(str); + +var r = request.defaults(options); +r(str); +r.get(str); +r.post(str); + +r(options); +r.get(options); +r.post(options); diff --git a/request/request.d.ts b/request/request.d.ts new file mode 100644 index 0000000000..e6a1d100e9 --- /dev/null +++ b/request/request.d.ts @@ -0,0 +1,171 @@ +// Type definitions for request +// Project: https://github.com/mikeal/request +// Definitions by: Carlos Ballesteros Velasco , bonnici , Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/d.ts + +/// +/// + +declare module 'request' { + import stream = require('stream'); + import http = require('http'); + import FormData = require('form-data'); + + export = RequestAPI; + + function RequestAPI(uri: string, options?: RequestAPI.Options, callback?: (error: any, response: any, body: any) => void): RequestAPI.Request; + function RequestAPI(uri: string, callback?: (error: any, response: any, body: any) => void): RequestAPI.Request; + function RequestAPI(options: RequestAPI.Options, callback?: (error: any, response: any, body: any) => void): RequestAPI.Request; + + module RequestAPI { + export function defaults(options: Options): typeof RequestAPI; + + export function request(uri: string, options?: Options, callback?: (error: any, response: any, body: any) => void): Request; + export function request(uri: string, callback?: (error: any, response: any, body: any) => void): Request; + export function request(options?: Options, callback?: (error: any, response: any, body: any) => void): Request; + + export function get(uri: string, options?: Options, callback?: (error: any, response: any, body: any) => void): Request; + export function get(uri: string, callback?: (error: any, response: any, body: any) => void): Request; + export function get(options: Options, callback?: (error: any, response: any, body: any) => void): Request; + + export function post(uri: string, options?: Options, callback?: (error: any, response: any, body: any) => void): Request; + export function post(uri: string, callback?: (error: any, response: any, body: any) => void): Request; + export function post(options: Options, callback?: (error: any, response: any, body: any) => void): Request; + + export function put(uri: string, options?: Options, callback?: (error: any, response: any, body: any) => void): Request; + export function put(uri: string, callback?: (error: any, response: any, body: any) => void): Request; + export function put(options: Options, callback?: (error: any, response: any, body: any) => void): Request; + + export function head(uri: string, options?: Options, callback?: (error: any, response: any, body: any) => void): Request; + export function head(uri: string, callback?: (error: any, response: any, body: any) => void): Request; + export function head(options: Options, callback?: (error: any, response: any, body: any) => void): Request; + + export function patch(uri: string, options?: Options, callback?: (error: any, response: any, body: any) => void): Request; + export function patch(uri: string, callback?: (error: any, response: any, body: any) => void): Request; + export function patch(options: Options, callback?: (error: any, response: any, body: any) => void): Request; + + export function del(uri: string, options?: Options, callback?: (error: any, response: any, body: any) => void): Request; + export function del(uri: string, callback?: (error: any, response: any, body: any) => void): Request; + export function del(options: Options, callback?: (error: any, response: any, body: any) => void): Request; + + export function forever(agentOptions: any, optionsArg: any): Request; + export function jar(): CookieJar; + export function cookie(str: string): Cookie; + + export var initParams: any; + + export interface Options { + url?: string; + uri?: string; + callback?: (error: any, response: any, body: any) => void; + jar?: any; // CookieJar + form?: FormData; + oauth?: OAuthOptions; + aws?: AWSOptions; + hawk ?: HawkOptions; + qs?: Object; + json?: any; + multipart?: RequestPart[]; + agentOptions?: any; + agentClass?: any; + forever?: any; + host?: string; + port?: number; + method?: string; + headers?: Headers; + body?: any; + followRedirect?: boolean; + followAllRedirects?: boolean; + maxRedirects?: number; + encoding?: string; + pool?: any; + timeout?: number; + proxy?: any; + strictSSL?: boolean; + } + + export interface RequestPart { + headers?: Headers; + body: any; + } + + export interface Request { + getAgent(): http.Agent; + //start(): void; + //abort(): void; + pipeDest(dest: any): void; + setHeader(name: string, value: string, clobber?: boolean): Request; + setHeaders(headers: Headers): Request; + qs(q: Object, clobber?: boolean): Request; + form(): FormData.FormData; + form(form: any): Request; + multipart(multipart: RequestPart[]): Request; + json(val: any): Request; + aws(opts: AWSOptions, now?: boolean): Request; + oauth(oauth: OAuthOptions): Request; + jar(jar: CookieJar): Request; + + pipe(dest: stream.Writable, opts?: any): stream.Writable; + write(): void; + end(chunk: string): void; + end(chunk: NodeBuffer): void; + pause(): void; + resume(): void; + abort(): void; + destroy(): void; + toJSON(): string; + } + + export interface Headers { + [key: string]: any; + } + + export interface AuthOptions { + user?: string; + username?: string; + pass?: string; + password?: string; + sendImmediately?: boolean; + } + + export interface OAuthOptions { + callback?: string; + consumer_key?: string; + consumer_secret?: string; + token?: string; + token_secret?: string; + verifier?: string; + } + + export interface HawkOptions { + credentials: any; + } + + export interface AWSOptions { + secret: string; + bucket?: string; + } + + export interface CookieJar { + add(cookie: Cookie): void; + get(req: Request): Cookie; + cookieString(req: Request): string; + } + + export interface CookieValue { + name: string; + value: any; + httpOnly: boolean; + } + + export interface Cookie extends Array { + constructor(name: string, req: Request): void; + str: string; + expires: Date; + path: string; + toString(): string; + } + } +} diff --git a/requirejs/require.d.ts b/requirejs/require.d.ts index 6b2cc125f4..47c754c602 100644 --- a/requirejs/require.d.ts +++ b/requirejs/require.d.ts @@ -262,6 +262,18 @@ interface Require { **/ toUrl(module: string): string; + /** + * Returns true if the module has already been loaded and defined. + * @param module Module to check + **/ + defined(module: string): boolean; + + /** + * Returns true if the module has already been requested or is in the process of loading and should be available at some point. + * @param module Module to check + **/ + specified(module: string): boolean; + /** * On Error override * @param err @@ -330,6 +342,16 @@ interface RequireDefine { * callback return module definition **/ (name: string, ready: Function): void; + + /** + * Used to allow a clear indicator that a global define function (as needed for script src browser loading) conforms + * to the AMD API, any global define function SHOULD have a property called "amd" whose value is an object. + * This helps avoid conflict with any other existing JavaScript code that could have defined a define() function + * that does not conform to the AMD API. + * define.amd.jQuery is specific to jQuery and indicates that the loader is able to account for multiple version + * of jQuery being loaded simultaneously. + */ + amd: Object; } // Ambient declarations for 'require' and 'define' diff --git a/restangular/restangular-tests.ts b/restangular/restangular-tests.ts index 22473e13e2..9d5aa9fb4f 100644 --- a/restangular/restangular-tests.ts +++ b/restangular/restangular-tests.ts @@ -1,145 +1,159 @@ /// -function test_basic() { - var $scope; - Restangular.all('accounts'); - Restangular.one('accounts', 1234); - Restangular.all('users').getList().then(function (users) { - $scope.user = users[0]; - }) - $scope.cars = $scope.user.getList('cars'); - $scope.user.sendMessage(); - $scope.user.one('message', 123).all('unread').getList(); +var myApp = angular.module('testModule'); - var baseAccounts = Restangular.all('accounts'); +myApp.config((RestangularProvider: restangular.IProvider) => { + RestangularProvider.setBaseUrl('/api/v1'); + RestangularProvider.setExtraFields(['name']); + RestangularProvider.setResponseExtractor(function (response, operation) { + return response.data; + }); - $scope.allAccounts = baseAccounts.getList(); + RestangularProvider.setDefaultHttpFields({ cache: true }); + RestangularProvider.setMethodOverriders(["put", "patch"]); - var newAccount = { name: "Gonto's account" }; + RestangularProvider.setErrorInterceptor(function (response) { + console.error('' + response.status + ' ' + response.data); + }); - baseAccounts.post(newAccount); + RestangularProvider.setRequestSuffix('.json'); - Restangular.one('accounts', 123).one('buildings', 456).get() + RestangularProvider.setRequestInterceptor(function (element, operation, route, url) { + }); - Restangular.one('accounts', 123).all('buildings').getList() + RestangularProvider.addElementTransformer('accounts', false, function (elem) { + elem.accountName = 'Changed'; + return elem; + }); - baseAccounts.getList().then(function (accounts) { + RestangularProvider.setRestangularFields({ + id: "_id", + route: "restangularRoute", + selfLink: "self.href" + }); - var firstAccount = accounts[0]; - $scope.buildings = firstAccount.getList("buildings"); - $scope.loggedInPlaces = firstAccount.getList("places", { query: 'wuut' }, { 'x-user': 'mgonto' }) + RestangularProvider.addRequestInterceptor(function(element, operation, route, url) { + delete element.name; + return element; + }); - firstAccount.name = "Gonto" - - var editFirstAccount = Restangular.copy(firstAccount); - - firstAccount.put(); - editFirstAccount.put(); - - firstAccount.remove(); - - var myBuilding = { - name: "Gonto's Building", - place: "Argentina" - }; + RestangularProvider.setFullRequestInterceptor(function(element, operation, route, url, headers, params, httpConfig) { + delete element.name; + return { + element: element, + params: params, + headers: headers, + httpConfig: httpConfig + }; + }); +}); - firstAccount.post("Buildings", myBuilding).then(function () { - console.log("Object saved OK"); - }, function () { - console.log("There was an error saving"); - }); - - - firstAccount.getList("users", { query: 'wuut' }).then(function (users) { - - users.post({ userName: 'unknown' }); - - - users.customGET("messages", { param: "myParam" }) - - var firstUser = users[0]; - - $scope.userFromServer = firstUser.get(); - - firstUser.head() - - }); - - }, function errorCallback() { - alert("Oops error from server :("); - }) - - var account = Restangular.one("accounts", 123); - - $scope.account = account.get({ single: true }); - - account.customPOST("messages", { param: "myParam" }, {}, { name: "My Message" }) +interface MyAppScope extends ng.IScope { + accounts: string[]; + allAccounts: any[]; + account: any; + buildings: restangular.ICollectionPromise; + loggedInPlaces: restangular.ICollectionPromise; + userFromServer: restangular.IPromise; } -function test_config() { - RestangularProvider.setBaseUrl('/api/v1'); - RestangularProvider.setExtraFields(['name']); - RestangularProvider.setResponseExtractor(function (response, operation) { - return response.data; +myApp.controller('TestCtrl', ( + $scope: MyAppScope, + Restangular: restangular.IService + ) => { + var baseAccounts = Restangular.all('accounts'); + + baseAccounts.getList().then(function(accounts) { + $scope.allAccounts = accounts; + }); + + $scope.accounts = Restangular.all('accounts').getList().$object; + var newAccount = {name: "Gonto's account"}; + baseAccounts.post(newAccount); + + Restangular.allUrl('googlers', 'http://www.google.com/').getList(); + Restangular.oneUrl('googlers', 'http://www.google.com/1').get(); + Restangular.one('accounts', 123).one('buildings', 456).get(); + Restangular.one('accounts', 123).getList('buildings'); + + baseAccounts.getList().then(function (accounts) { + var firstAccount = accounts[0]; + $scope.buildings = firstAccount.getList("buildings"); + $scope.loggedInPlaces = firstAccount.getList("places", {query: "param"}, {'x-user': 'mgonto'}); + + firstAccount.name = "Gonto"; + var editFirstAccount = Restangular.copy(firstAccount); + + firstAccount.put(); + editFirstAccount.put(); + + firstAccount.save(); + + firstAccount.remove(); + + var myBuilding = { + name: "Gonto's Building", + place: "Argentina" + }; + + firstAccount.post("Buildings", myBuilding).then(function() { + console.log("Object saved OK"); + }, function() { + console.log("There was an error saving"); }); - RestangularProvider.setDefaultHttpFields({ cache: true }); - RestangularProvider.setMethodOverriders(["put", "patch"]); + firstAccount.getList("users", {query: "params"}).then(function(users) { + users.post({userName: 'unknown'}); + users.customGET("messages", {param: "myParam"}); - RestangularProvider.setErrorInterceptor(function (response) { + var firstUser = users[0]; + $scope.userFromServer = firstUser.get(); + firstUser.head() + + }); + + }, function errorCallback() { + alert("Oops error from server :("); + }); + + var account = Restangular.one("accounts", 123); + + $scope.account = account.get({single: true}); + + account.customPOST({name: "My Message"}, "messages", {param: "myParam"}, {}); + + Restangular.one('accounts', 123).withHttpConfig({timeout: 100}).getList('buildings'); + $scope.account = Restangular.one('accounts', 123); + $scope.account.withHttpConfig({timeout: 100}).put(); + + var myRestangular = Restangular.withConfig((configurer: restangular.IProvider) => { + configurer.setBaseUrl('/api/v1'); + configurer.setExtraFields(['name']); + + configurer.setErrorInterceptor(function (response) { console.error('' + response.status + ' ' + response.data); }); + configurer.setResponseExtractor(function (response, operation) { + return response.data; + }); + configurer.setDefaultHttpFields({ cache: true }); + configurer.setMethodOverriders(["put", "patch"]); - RestangularProvider.setRestangularFields({ + configurer.setRestangularFields({ id: "_id", route: "restangularRoute" }); - RestangularProvider.setRequestSuffix('.json'); + configurer.setRequestSuffix('.json'); - RestangularProvider.setRequestInterceptor(function (element, operation, route, url) { + configurer.setRequestInterceptor(function (element, operation, route, url) { }); - RestangularProvider.addElementTransformer('accounts', false, function (elem) { + configurer.addElementTransformer('accounts', false, function (elem) { elem.accountName = 'Changed'; return elem; }); - - var myRestangular = Restangular.withConfig((configurer: RestangularProvider) => { - configurer.setBaseUrl('/api/v1'); - configurer.setExtraFields(['name']); - - configurer.setErrorInterceptor(function (response) { - console.error('' + response.status + ' ' + response.data); - }); - configurer.setResponseExtractor(function (response, operation) { - return response.data; - }); - configurer.setDefaultHttpFields({ cache: true }); - configurer.setMethodOverriders(["put", "patch"]); - - configurer.setRestangularFields({ - id: "_id", - route: "restangularRoute" - }); - - configurer.setRequestSuffix('.json'); - - configurer.setRequestInterceptor(function (element, operation, route, url) { - }); - - configurer.addElementTransformer('accounts', false, function (elem) { - elem.accountName = 'Changed'; - return elem; - }); - }); -} - -function test_withHttpConfig() { - var $scope; - Restangular.one('accounts', 123).withHttpConfig({timeout: 100}).getList('buildings'); - $scope.account = Restangular.one('accounts', 123); - $scope.account.withHttpConfig({timeout: 100}).put(); -} + }); +}); diff --git a/restangular/restangular.d.ts b/restangular/restangular.d.ts index a5b7de20d9..9fd397bf57 100644 --- a/restangular/restangular.d.ts +++ b/restangular/restangular.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Restangular v1.2.2 +// Type definitions for Restangular v1.4.0 // Project: https://github.com/mgonto/restangular // Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -6,7 +6,23 @@ /// -interface RestangularRequestConfig { + +declare module restangular { + + interface IPromise extends ng.IPromise { + call(methodName: string, params?: any): IPromise; + get(fieldName: string): IPromise; + $object: T; +} + + interface ICollectionPromise extends ng.IPromise { + push(object: any): ICollectionPromise; + call(methodName: string, params?: any): ICollectionPromise; + get(fieldName: string): ICollectionPromise; + $object: T[]; + } + + interface IRequestConfig { params?: any; headers?: any; cache?: any; @@ -15,81 +31,9 @@ interface RestangularRequestConfig { transformRequest?: any; transformResponse?: any; timeout?: any; // number | promise -} + } -interface Restangular extends RestangularCustom { - one(route: string, id?: number): RestangularElement; - one(route: string, id?: string): RestangularElement; - oneUrl(route: string, url: string): RestangularElement; - all(route: string): RestangularCollection; - allUrl(route: string, url: string): RestangularCollection; - copy(fromElement: any): RestangularElement; - withConfig(configurer: (RestangularProvider: RestangularProvider) => any): Restangular; - restangularizeElement(parent: any, element: any, route: string, collection?: any, reqParams?: any): RestangularElement; - restangularizeCollection(parent: any, element: any, route: string): RestangularCollection; - stripRestangular(element: any): any; -} - -interface RestangularElement extends Restangular { - get(queryParams?: any, headers?: any): ng.IPromise; - getList(subElement: any, queryParams?: any, headers?: any): ng.IPromise; - put(queryParams?: any, headers?: any): ng.IPromise; - post(subElement: any, elementToPost: any, queryParams?: any, headers?: any): ng.IPromise; - remove(queryParams?: any, headers?: any): ng.IPromise; - head(queryParams?: any, headers?: any): ng.IPromise; - trace(queryParams?: any, headers?: any): ng.IPromise; - options(queryParams?: any, headers?: any): ng.IPromise; - patch(queryParams?: any, headers?: any): ng.IPromise; - withHttpConfig(httpConfig: RestangularRequestConfig): RestangularElement; - getRestangularUrl(): string; -} - -interface RestangularCollection extends Restangular { - getList(queryParams?: any, headers?: any): ng.IPromise; - post(elementToPost: any, queryParams?: any, headers?: any): ng.IPromise; - head(queryParams?: any, headers?: any): ng.IPromise; - trace(queryParams?: any, headers?: any): ng.IPromise; - options(queryParams?: any, headers?: any): ng.IPromise; - patch(queryParams?: any, headers?: any): ng.IPromise; - putElement(idx: any, params: any, headers: any): ng.IPromise; - withHttpConfig(httpConfig: RestangularRequestConfig): RestangularCollection; - getRestangularUrl(): string; -} - -interface RestangularCustom { - customGET(path: string, params?: any, headers?: any): ng.IPromise; - customGETLIST(path: string, params?: any, headers?: any): ng.IPromise; - customDELETE(path: string, params?: any, headers?: any): ng.IPromise; - customPOST(path: string, params?: any, headers?: any, elem?: any): ng.IPromise; - customPUT(path: string, params?: any, headers?: any, elem?: any): ng.IPromise; - customOperation(operation: string, path: string, params?: any, headers?: any, elem?: any): ng.IPromise; - addRestangularMethod(name: string, operation: string, path?: string, params?: any, headers?: any, elem?: any): ng.IPromise; -} - -interface RestangularProvider { - setBaseUrl(baseUrl: string): void; - setExtraFields(fields: string[]): void; - setParentless(parentless: boolean, routes: string[]): void; - setDefaultHttpFields(httpFields: any): void; - addElementTransformer(route: string, transformer: Function): void; - addElementTransformer(route: string, isCollection: boolean, transformer: Function): void; - setOnElemRestangularized(callback: (elem: any, isCollection: boolean, what: string, restangular: Restangular) => any): void; - setResponseInterceptor(responseInterceptor: (data: any, operation: string, what: string, url: string, response: RestangularResponse, deferred: ng.IDeferred) => any): void; - setResponseExtractor(responseInterceptor: (data: any, operation: string, what: string, url: string, response: RestangularResponse, deferred: ng.IDeferred) => any): void; - setRequestInterceptor(requestInterceptor: (element: any, operation: string, what: string, url: string) => any): void; - setFullRequestInterceptor(fullRequestInterceptor: (element: any, operation: string, what: string, url: string, headers: any, params: any) => {element: any; headers: any; params: any}): void; - setErrorInterceptor(errorInterceptor: (response: RestangularResponse) => any): void; - setRestangularFields(fields: {[fieldName: string]: string}): void; - setMethodOverriders(overriders: string[]): void; - setDefaultRequestParams(params: any): void; - setDefaultRequestParams(methods: any, params: any): void; - setFullResponse(fullResponse: boolean): void; - setDefaultHeaders(headers: any): void; - setRequestSuffix(suffix: string): void; - setUseCannonicalId(useCannonicalId: boolean): void; -} - -interface RestangularResponse { + interface IResponse { status: number; data: any; config: { @@ -97,7 +41,85 @@ interface RestangularResponse { url: string; params: any; } -} + } -declare var Restangular: Restangular; -declare var RestangularProvider: RestangularProvider; + interface IProvider { + setBaseUrl(baseUrl: string): void; + setExtraFields(fields: string[]): void; + setParentless(parentless: boolean, routes: string[]): void; + setDefaultHttpFields(httpFields: any): void; + addElementTransformer(route: string, transformer: Function): void; + addElementTransformer(route: string, isCollection: boolean, transformer: Function): void; + setTransformOnlyServerElements(active: boolean): void; + setOnElemRestangularized(callback: (elem: any, isCollection: boolean, what: string, restangular: IService) => any): void; + setResponseInterceptor(responseInterceptor: (data: any, operation: string, what: string, url: string, response: IResponse, deferred: ng.IDeferred) => any): void; + setResponseExtractor(responseInterceptor: (data: any, operation: string, what: string, url: string, response: IResponse, deferred: ng.IDeferred) => any): void; + addResponseInterceptor(responseInterceptor: (data: any, operation: string, what: string, url: string, response: IResponse, deferred: ng.IDeferred) => any): void; + setRequestInterceptor(requestInterceptor: (element: any, operation: string, what: string, url: string) => any): void; + addRequestInterceptor(requestInterceptor: (element: any, operation: string, what: string, url: string) => any): void; + setFullRequestInterceptor(fullRequestInterceptor: (element: any, operation: string, what: string, url: string, headers: any, params: any, httpConfig: IRequestConfig) => {element: any; headers: any; params: any}): void; + addFullRequestInterceptor(requestInterceptor: (element: any, operation: string, what: string, url: string, headers: any, params: any, httpConfig: IRequestConfig) => {headers: any; params: any; element: any; httpConfig: IRequestConfig}): void; + setErrorInterceptor(errorInterceptor: (response: IResponse, deferred: ng.IDeferred) => any): void; + setRestangularFields(fields: {[fieldName: string]: string}): void; + setMethodOverriders(overriders: string[]): void; + setJsonp(jsonp: boolean): void; + setDefaultRequestParams(params: any): void; + setDefaultRequestParams(method: string, params: any): void; + setDefaultRequestParams(methods: string[], params: any): void; + setFullResponse(fullResponse: boolean): void; + setDefaultHeaders(headers: any): void; + setRequestSuffix(suffix: string): void; + setUseCannonicalId(useCannonicalId: boolean): void; + setEncodeIds(encode: boolean): void; + } + + interface ICustom { + customGET(path: string, params?: any, headers?: any): IPromise; + customGETLIST(path: string, params?: any, headers?: any): ICollectionPromise; + customDELETE(path: string, params?: any, headers?: any): IPromise; + customPOST(elem?: any, path?: string, params?: any, headers?: any): IPromise; + customPUT(elem?: any, path?: string, params?: any, headers?: any): IPromise; + customOperation(operation: string, path: string, params?: any, headers?: any, elem?: any): IPromise; + addRestangularMethod(name: string, operation: string, path?: string, params?: any, headers?: any, elem?: any): IPromise; + } + + interface IService extends ICustom { + one(route: string, id?: number): IElement; + one(route: string, id?: string): IElement; + oneUrl(route: string, url: string): IElement; + all(route: string): IElement; + allUrl(route: string, url: string): IElement; + copy(fromElement: any): IElement; + withConfig(configurer: (RestangularProvider: IProvider) => any): IService; + restangularizeElement(parent: any, element: any, route: string, collection?: any, reqParams?: any): IElement; + restangularizeCollection(parent: any, element: any, route: string): ICollection; + stripRestangular(element: any): any; + } + + interface IElement extends IService { + get(queryParams?: any, headers?: any): IPromise; + getList(subElement?: any, queryParams?: any, headers?: any): ICollectionPromise; + put(queryParams?: any, headers?: any): IPromise; + post(subElement: any, elementToPost: any, queryParams?: any, headers?: any): IPromise; + post(elementToPost: any, queryParams?: any, headers?: any): IPromise; + remove(queryParams?: any, headers?: any): IPromise; + head(queryParams?: any, headers?: any): IPromise; + trace(queryParams?: any, headers?: any): IPromise; + options(queryParams?: any, headers?: any): IPromise; + patch(queryParams?: any, headers?: any): IPromise; + withHttpConfig(httpConfig: IRequestConfig): IElement; + getRestangularUrl(): string; + } + + interface ICollection extends IService { + getList(queryParams?: any, headers?: any): ICollectionPromise; + post(elementToPost: any, queryParams?: any, headers?: any): IPromise; + head(queryParams?: any, headers?: any): IPromise; + trace(queryParams?: any, headers?: any): IPromise; + options(queryParams?: any, headers?: any): IPromise; + patch(queryParams?: any, headers?: any): IPromise; + putElement(idx: any, params: any, headers: any): IPromise; + withHttpConfig(httpConfig: IRequestConfig): ICollection; + getRestangularUrl(): string; + } +} diff --git a/reveal/reveal-tests.ts.tscparams b/reveal/reveal-tests.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/reveal/reveal-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/reveal/reveal.d.ts b/reveal/reveal.d.ts index bfe56bf0be..14393d6501 100644 --- a/reveal/reveal.d.ts +++ b/reveal/reveal.d.ts @@ -10,7 +10,7 @@ interface RevealStatic { configure:(diff:RevealOptions)=>void; // Navigation - slide(h:number, v:number, f?:number, o?:number); + slide(h:number, v:number, f?:number, o?:number):void; left():void; right():void; up():void; diff --git a/reveal/reveal.d.ts.tscparams b/reveal/reveal.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/reveal/reveal.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/rimraf/rimraf-tests.ts b/rimraf/rimraf-tests.ts new file mode 100644 index 0000000000..74e33ce678 --- /dev/null +++ b/rimraf/rimraf-tests.ts @@ -0,0 +1,11 @@ +/// + +import rimraf = require('rimraf'); + +rimraf('./xyz', (err: Error) => { + +}); +rimraf.sync('./xyz'); + +rimraf.EMFILE_MAX = 0; +rimraf.BUSYTRIES_MAX = 0; diff --git a/rimraf/rimraf.d.ts b/rimraf/rimraf.d.ts new file mode 100644 index 0000000000..b02581aefe --- /dev/null +++ b/rimraf/rimraf.d.ts @@ -0,0 +1,16 @@ +// Type definitions for rimraf +// Project: https://github.com/isaacs/rimraf +// Definitions by: Carlos Ballesteros Velasco +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/rimraf.d.ts + +declare module "rimraf" { + function rimraf(path: string, callback: (error: Error) => void): void; + module rimraf { + export function sync(path: string): void; + export var EMFILE_MAX: number; + export var BUSYTRIES_MAX: number; + } + export = rimraf; +} diff --git a/riotjs/riotjs-render.d.ts b/riotjs/riotjs-render.d.ts index fe6cf84dc2..b2b044d938 100644 --- a/riotjs/riotjs-render.d.ts +++ b/riotjs/riotjs-render.d.ts @@ -1,4 +1,4 @@ -// Type definitions for riot.js (ext/render.js) +// Type definitions for riot.js // Project: https://github.com/moot/riotjs // Definitions by: vvakame // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/rtree/rtree-tests.ts b/rtree/rtree-tests.ts new file mode 100644 index 0000000000..67d35a4e61 --- /dev/null +++ b/rtree/rtree-tests.ts @@ -0,0 +1,13 @@ +/// + +var myRTree = RTree(5); +var el = "test"; + +myRTree.insert({x: 0, y: 0, w: 1, h: 1}, el); + +var intersections = myRTree.search({x: 0.5, y: 0.5, w: 1, h: 1}); + +intersections = myRTree.remove({x: 0.5, y: 0.5, w: 1, h: 1}, "notTest!"); + +intersections = myRTree.remove({x: 0.5, y: 0.5, w: 1, h: 1}); + diff --git a/rtree/rtree.d.ts b/rtree/rtree.d.ts new file mode 100644 index 0000000000..fa6276c6ef --- /dev/null +++ b/rtree/rtree.d.ts @@ -0,0 +1,25 @@ +// Type definitions for rtree 1.4.0 +// Project: https://github.com/leaflet-extras/RTree +// Definitions by: Omede Firouz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface Rectangle { + x: number; + y: number; + w: number; + h: number; +} + +interface RTreeStatic { + insert(bounds: Rectangle, element: Object): boolean; + remove(area: Rectangle, element?: Object): any[]; + geoJSON(geoJSON: any): void; + bbox(arg1: any, arg2?: any, arg3?: number, arg4?: number): any[]; + search(area: Rectangle, return_node?: boolean, return_array?: any[]): any[]; +} + +interface RTreeFactory { + (max_node_width?: number): RTreeStatic; +} + +declare var RTree: RTreeFactory; diff --git a/rx.js/rx.jquery.d.ts b/rx-jquery/rx.jquery.d.ts similarity index 96% rename from rx.js/rx.jquery.d.ts rename to rx-jquery/rx.jquery.d.ts index f2dcb284a7..d3d4054510 100644 --- a/rx.js/rx.jquery.d.ts +++ b/rx-jquery/rx.jquery.d.ts @@ -1,10 +1,10 @@ -// Type definitions for bridging RxJS with jQuery. +// Type definitions for RxJS-jQuery // Project: https://github.com/Reactive-Extensions/RxJS-jQuery/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped /// -/// +/// interface RxJQueryAjaxResult { data: T; @@ -60,3 +60,7 @@ interface JQuery { slideToggleAsObservable(duration: number): Rx.Observable; toggleAsObservable(duration: number): Rx.Observable; } + +declare module "rx.jquery" { + export = Rx; +} \ No newline at end of file diff --git a/rx.js/rx.binding.d.ts b/rx.js/rx.binding.d.ts deleted file mode 100644 index cf3744c4e2..0000000000 --- a/rx.js/rx.binding.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Type definitions for RxJS-Binding v2.2.20 -// Project: http://rx.codeplex.com/ -// Definitions by: Carl de Billy -// Definitions by: Igor Oleinikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// - -declare module Rx { - export interface Observable { - replayWhileObserved(bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; - } -} diff --git a/rx.js/rx-lite.d.ts b/rx/rx-lite.d.ts similarity index 88% rename from rx.js/rx-lite.d.ts rename to rx/rx-lite.d.ts index 15767ac61f..c7a1481379 100644 --- a/rx.js/rx-lite.d.ts +++ b/rx/rx-lite.d.ts @@ -1,4 +1,6 @@ -// This file contains common part of defintions for rx.d.ts and rx.lite.d.ts +// DefinitelyTyped: partial + +// This file contains common part of defintions for rx.d.ts and rx.lite.d.ts // Do not include the file separately. declare module Rx { @@ -196,7 +198,6 @@ declare module Rx { export interface Observable extends IObservable { forEach(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): IDisposable; // alias for subscribe - finalValue(): Observable; toArray(): Observable; catch(handler: (exception: any) => Observable): Observable; @@ -228,15 +229,22 @@ declare module Rx { concat(sources: IPromise[]): Observable; concatAll(): T; concatObservable(): T; // alias for concatAll + concatMap(selector: (value: T, index: number) => Observable, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; // alias for selectConcat + concatMap(selector: (value: T, index: number) => IPromise, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; // alias for selectConcat + concatMap(selector: (value: T, index: number) => Observable): Observable; // alias for selectConcat + concatMap(selector: (value: T, index: number) => IPromise): Observable; // alias for selectConcat + concatMap(sequence: Observable): Observable; // alias for selectConcat merge(maxConcurrent: number): T; merge(other: Observable): Observable; merge(other: IPromise): Observable; mergeAll(): T; mergeObservable(): T; // alias for mergeAll skipUntil(other: Observable): Observable; + skipUntil(other: IPromise): Observable; switch(): T; switchLatest(): T; // alias for switch takeUntil(other: Observable): Observable; + takeUntil(other: IPromise): Observable; zip(second: Observable, resultSelector: (v1: T, v2: T2) => TResult): Observable; zip(second: IPromise, resultSelector: (v1: T, v2: T2) => TResult): Observable; zip(second: Observable, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; @@ -292,6 +300,12 @@ declare module Rx { flatMap(other: Observable): Observable; // alias for selectMany flatMap(other: IPromise): Observable; // alias for selectMany + selectConcat(selector: (value: T, index: number) => Observable, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; + selectConcat(selector: (value: T, index: number) => IPromise, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; + selectConcat(selector: (value: T, index: number) => Observable): Observable; + selectConcat(selector: (value: T, index: number) => IPromise): Observable; + selectConcat(sequence: Observable): Observable; + /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. @@ -310,6 +324,16 @@ declare module Rx { * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ flatMapLatest(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; // alias for selectSwitch + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param [thisArg] Object to use as this when executing callback. + * @since 2.2.28 + * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + switchMap(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; // alias for selectSwitch skip(count: number): Observable; skipWhile(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; @@ -338,12 +362,34 @@ declare module Rx { * @returns An ES6 compatible promise with the last value from the observable sequence. */ toPromise(promiseCtor?: { new (resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): IPromise; }): IPromise; + + // Experimental Flattening + + /** + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * Can be applied on `Observable>` or `Observable>`. + * @since 2.2.28 + * @returns A exclusive observable with only the results that happen when subscribed. + */ + exclusive(): Observable; + + /** + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * Can be applied on `Observable>` or `Observable>`. + * @since 2.2.28 + * @param selector Selector to invoke for every item in the current subscription. + * @param [thisArg] An optional context to invoke with the selector parameter. + * @returns {An exclusive observable with only the results that happen when subscribed. + */ + exclusiveMap(selector: (value: I, index: number, source: Observable) => R, thisArg?: any): Observable; } interface ObservableStatic { - create(subscribe: (observer: Observer) => void): Observable; - create(subscribe: (observer: Observer) => () => void): Observable; create(subscribe: (observer: Observer) => IDisposable): Observable; + create(subscribe: (observer: Observer) => () => void): Observable; + create(subscribe: (observer: Observer) => void): Observable; createWithDisposable(subscribe: (observer: Observer) => IDisposable): Observable; defer(observableFactory: () => Observable): Observable; defer(observableFactory: () => IPromise): Observable; @@ -377,9 +423,33 @@ declare module Rx { fromItreable(iterable: {}, scheduler?: IScheduler): Observable; // todo: can't describe ES6 Iterable via TypeScript type system generate(initialState: TState, condition: (state: TState) => boolean, iterate: (state: TState) => TState, resultSelector: (state: TState) => TResult, scheduler?: IScheduler): Observable; never(): Observable; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * + * @example + * var res = Rx.Observable.of(1, 2, 3); + * @since 2.2.28 + * @returns The observable sequence whose elements are pulled from the given arguments. + */ + of(...values: T[]): Observable; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.ofWithScheduler(Rx.Scheduler.timeout, 1, 2, 3); + * @since 2.2.28 + * @param [scheduler] A scheduler to use for scheduling the arguments. + * @returns The observable sequence whose elements are pulled from the given arguments. + */ + ofWithScheduler(scheduler?: IScheduler, ...values: T[]): Observable; range(start: number, count: number, scheduler?: IScheduler): Observable; repeat(value: T, repeatCount?: number, scheduler?: IScheduler): Observable; return(value: T, scheduler?: IScheduler): Observable; + /** + * @since 2.2.28 + */ + just(value: T, scheduler?: IScheduler): Observable; // alias for return returnValue(value: T, scheduler?: IScheduler): Observable; // alias for return throw(exception: Error, scheduler?: IScheduler): Observable; throw(exception: any, scheduler?: IScheduler): Observable; diff --git a/rx.js/rx.aggregates.d.ts b/rx/rx.aggregates.d.ts similarity index 94% rename from rx.js/rx.aggregates.d.ts rename to rx/rx.aggregates.d.ts index ea5cca99ba..001d1b9932 100644 --- a/rx.js/rx.aggregates.d.ts +++ b/rx/rx.aggregates.d.ts @@ -1,13 +1,13 @@ -// Type definitions for RxJS-Aggregates v2.2.20 +// Type definitions for RxJS-Aggregates v2.2.28 // Project: http://rx.codeplex.com/ -// Definitions by: Carl de Billy -// Definitions by: Igor Oleinikov +// Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare module Rx { export interface Observable { + finalValue(): Observable; aggregate(accumulator: (acc: T, value: T) => T): Observable; aggregate(seed: TAcc, accumulator: (acc: TAcc, value: T) => TAcc): Observable; @@ -55,3 +55,7 @@ declare module Rx { findIndex(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; } } + +declare module "rx.aggregates" { + export = Rx; +} \ No newline at end of file diff --git a/rx/rx.all.ts b/rx/rx.all.ts new file mode 100644 index 0000000000..c546477b80 --- /dev/null +++ b/rx/rx.all.ts @@ -0,0 +1,20 @@ +// Type definitions for RxJS-All v2.2.28 +// Project: http://rx.codeplex.com/ +// Definitions by: Carl de Billy , Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +declare module "rx.all" { + export = Rx; +} \ No newline at end of file diff --git a/rx.js/rx.async-lite.d.ts b/rx/rx.async-lite.d.ts similarity index 99% rename from rx.js/rx.async-lite.d.ts rename to rx/rx.async-lite.d.ts index ce0f96778e..be13320c27 100644 --- a/rx.js/rx.async-lite.d.ts +++ b/rx/rx.async-lite.d.ts @@ -1,3 +1,5 @@ +// DefinitelyTyped: partial + // This file contains common part of defintions for rx.async.d.ts and rx.lite.d.ts // Do not include the file separately. diff --git a/rx.js/rx.async-tests.ts b/rx/rx.async-tests.ts similarity index 100% rename from rx.js/rx.async-tests.ts rename to rx/rx.async-tests.ts diff --git a/rx.js/rx.async.d.ts b/rx/rx.async.d.ts similarity index 96% rename from rx.js/rx.async.d.ts rename to rx/rx.async.d.ts index 9a03bb33b4..9370c828bf 100644 --- a/rx.js/rx.async.d.ts +++ b/rx/rx.async.d.ts @@ -1,7 +1,6 @@ -// Type definitions for RxJS-Async v2.2.20 +// Type definitions for RxJS-Async v2.2.28 // Project: http://rx.codeplex.com/ -// Definitions by: zoetrope -// Definitions by: Igor Oleinikov +// Definitions by: zoetrope , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -38,3 +37,7 @@ declare module Rx { toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => Observable; } } + +declare module "rx.async" { + export = Rx; +} \ No newline at end of file diff --git a/rx.js/rx.backpressure-lite.d.ts b/rx/rx.backpressure-lite.d.ts similarity index 93% rename from rx.js/rx.backpressure-lite.d.ts rename to rx/rx.backpressure-lite.d.ts index 420a568f3e..d1c244195f 100644 --- a/rx.js/rx.backpressure-lite.d.ts +++ b/rx/rx.backpressure-lite.d.ts @@ -1,4 +1,6 @@ -// This file contains common part of defintions for rx.backpressure.d.ts and rx.lite.d.ts +// DefinitelyTyped: partial + +// This file contains common part of defintions for rx.backpressure.d.ts and rx.lite.d.ts // Do not include the file separately. /// diff --git a/rx.js/rx.backpressure-tests.ts b/rx/rx.backpressure-tests.ts similarity index 100% rename from rx.js/rx.backpressure-tests.ts rename to rx/rx.backpressure-tests.ts diff --git a/rx.js/rx.backpressure.d.ts b/rx/rx.backpressure.d.ts similarity index 70% rename from rx.js/rx.backpressure.d.ts rename to rx/rx.backpressure.d.ts index 5ec8c3f91f..9c5e8abd50 100644 --- a/rx.js/rx.backpressure.d.ts +++ b/rx/rx.backpressure.d.ts @@ -1,7 +1,11 @@ -// Type definitions for RxJS-BackPressure v2.2.20 +// Type definitions for RxJS-BackPressure v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped /// /// + +declare module "rx.backpressure" { + export = Rx; +} \ No newline at end of file diff --git a/rx.js/rx.binding-lite.d.ts b/rx/rx.binding-lite.d.ts similarity index 96% rename from rx.js/rx.binding-lite.d.ts rename to rx/rx.binding-lite.d.ts index 1e5d95eaf3..f896e260db 100644 --- a/rx.js/rx.binding-lite.d.ts +++ b/rx/rx.binding-lite.d.ts @@ -1,3 +1,5 @@ +// DefinitelyTyped: partial + // This file contains common part of defintions for rx.binding.d.ts and rx.lite.d.ts // Do not include the file separately. @@ -65,5 +67,6 @@ declare module Rx { shareValue(initialValue: T): Observable; replay(selector?: boolean, bufferSize?: number, window?: number, scheduler?: IScheduler): ConnectableObservable; // hack to catch first omitted parameter replay(selector: (source: ConnectableObservable) => Observable, bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; + shareReplay(bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; } } diff --git a/rx/rx.binding.d.ts b/rx/rx.binding.d.ts new file mode 100644 index 0000000000..b93411a528 --- /dev/null +++ b/rx/rx.binding.d.ts @@ -0,0 +1,11 @@ +// Type definitions for RxJS-Binding v2.2.28 +// Project: http://rx.codeplex.com/ +// Definitions by: Carl de Billy , Igor Oleinikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "rx.binding" { + export = Rx; +} \ No newline at end of file diff --git a/rx/rx.coincidence-lite.d.ts b/rx/rx.coincidence-lite.d.ts new file mode 100644 index 0000000000..801e42168c --- /dev/null +++ b/rx/rx.coincidence-lite.d.ts @@ -0,0 +1,34 @@ +// DefinitelyTyped: partial + +// This file contains common part of defintions for rx.time.d.ts and rx.lite.d.ts +// Do not include the file separately. + +/// + +declare module Rx { + + interface Observable { + /** + * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. + * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. + * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. + * @returns An observable that triggers on successive pairs of observations from the input observable as an array. + */ + pairwise(): Observable; + + /** + * Returns two observables which partition the observations of the source by the given function. + * The first will trigger observations for those values for which the predicate returns true. + * The second will trigger observations for those values where the predicate returns false. + * The predicate is executed once for each subscribed observer. + * Both also propagate all error observations arising from the source and each completes + * when the source completes. + * @param predicate + * The function to determine which output Observable will trigger a particular observation. + * @returns + * An array of observables. The first triggers when the predicate returns true, + * and the second triggers when the predicate returns false. + */ + partition(predicate: (value: T, index: number, source: Observable) => boolean, thisArg: any): Observable[]; + } +} diff --git a/rx.js/rx.coincidence.d.ts b/rx/rx.coincidence.d.ts similarity index 86% rename from rx.js/rx.coincidence.d.ts rename to rx/rx.coincidence.d.ts index bf9841b41e..87fa6a55b5 100644 --- a/rx.js/rx.coincidence.d.ts +++ b/rx/rx.coincidence.d.ts @@ -1,10 +1,10 @@ -// Type definitions for RxJS-Coincidence v2.2.20 +// Type definitions for RxJS-Coincidence v2.2.28 // Project: http://rx.codeplex.com/ -// Definitions by: Carl de Billy -// Definitions by: Igor Oleinikov +// Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped /// +/// declare module Rx { @@ -30,3 +30,7 @@ declare module Rx { buffer(bufferOpenings: Observable, bufferClosingSelector: () => Observable): Observable; } } + +declare module "rx.coincidence" { + export = Rx; +} \ No newline at end of file diff --git a/rx.js/rx.d.ts b/rx/rx.d.ts similarity index 98% rename from rx.js/rx.d.ts rename to rx/rx.d.ts index 1a5d775a5e..1f26a94a9a 100644 --- a/rx.js/rx.d.ts +++ b/rx/rx.d.ts @@ -1,7 +1,6 @@ -// Type definitions for RxJS v2.2.20 +// Type definitions for RxJS v2.2.28 // Project: http://rx.codeplex.com/ -// Definitions by: gsino -// Definitions by: Igor Oleinikov +// Definitions by: gsino , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/rx.js/rx.experimental.d.ts b/rx/rx.experimental.d.ts similarity index 99% rename from rx.js/rx.experimental.d.ts rename to rx/rx.experimental.d.ts index 1b92599446..60aec86e1a 100644 --- a/rx.js/rx.experimental.d.ts +++ b/rx/rx.experimental.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Experimental v2.2.20 +// Type definitions for RxJS-Experimental v2.2.28 // Project: https://github.com/Reactive-Extensions/RxJS/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -315,3 +315,7 @@ declare module Rx { forkJoin(...args: IPromise[]): Observable; } } + +declare module "rx.experimental" { + export = Rx; +} \ No newline at end of file diff --git a/rx.js/rx.joinpatterns.d.ts b/rx/rx.joinpatterns.d.ts similarity index 96% rename from rx.js/rx.joinpatterns.d.ts rename to rx/rx.joinpatterns.d.ts index bc1ee2e324..929c66a6f1 100644 --- a/rx.js/rx.joinpatterns.d.ts +++ b/rx/rx.joinpatterns.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Join v2.2.20 +// Type definitions for RxJS-Join v2.2.28 // Project: http://rx.codeplex.com/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -54,3 +54,7 @@ declare module Rx { when(plan: Plan): Observable; } } + +declare module "rx.joinpatterns" { + export = Rx; +} \ No newline at end of file diff --git a/rx.js/rx.lite.d.ts b/rx/rx.lite.d.ts similarity index 89% rename from rx.js/rx.lite.d.ts rename to rx/rx.lite.d.ts index e01b7e34ba..046ef527d6 100644 --- a/rx.js/rx.lite.d.ts +++ b/rx/rx.lite.d.ts @@ -1,7 +1,6 @@ -// Type definitions for RxJS-Lite v2.2.20 +// Type definitions for RxJS-Lite v2.2.28 // Project: http://rx.codeplex.com/ -// Definitions by: gsino -// Definitions by: Igor Oleinikov +// Definitions by: gsino , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -9,6 +8,7 @@ /// /// /// +/// declare module Rx { export class Scheduler implements IScheduler { @@ -43,8 +43,8 @@ declare module Rx { schedulePeriodic(period: number, action: () => void): IDisposable; schedulePeriodicWithState(state: TState, period: number, action: (state: TState) => TState): IDisposable; } - - export interface Observable { - shareReplay(bufferSize?: number, window?: number, scheduler?: IScheduler): Observable; // same as replayWhileObserved in rx.binding.d.ts - } } + +declare module "rx.lite" { + export = Rx; +} \ No newline at end of file diff --git a/rx.js/rx.testing.d.ts b/rx/rx.testing.d.ts similarity index 95% rename from rx.js/rx.testing.d.ts rename to rx/rx.testing.d.ts index 082fdba598..0adc83e506 100644 --- a/rx.js/rx.testing.d.ts +++ b/rx/rx.testing.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS-Testing v2.2.20 +// Type definitions for RxJS-Testing v2.2.28 // Project: https://github.com/Reactive-Extensions/RxJS/ // Definitions by: Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -56,3 +56,7 @@ declare module Rx { export var MockObserver: MockObserverStatic; } + +declare module "rx.testing" { + export = Rx; +} \ No newline at end of file diff --git a/rx.js/rx.time-lite.d.ts b/rx/rx.time-lite.d.ts similarity index 93% rename from rx.js/rx.time-lite.d.ts rename to rx/rx.time-lite.d.ts index 736d872e87..a5b1028276 100644 --- a/rx.js/rx.time-lite.d.ts +++ b/rx/rx.time-lite.d.ts @@ -1,3 +1,5 @@ +// DefinitelyTyped: partial + // This file contains common part of defintions for rx.time.d.ts and rx.lite.d.ts // Do not include the file separately. @@ -39,7 +41,9 @@ declare module Rx { skipWithTime(duration: number, scheduler?: IScheduler): Observable; skipUntilWithTime(startTime: Date, scheduler?: IScheduler): Observable; + skipUntilWithTime(duration: number, scheduler?: IScheduler): Observable; takeUntilWithTime(endTime: Date, scheduler?: IScheduler): Observable; + takeUntilWithTime(duration: number, scheduler?: IScheduler): Observable; } interface ObservableStatic { diff --git a/rx.js/rx.time.d.ts b/rx/rx.time.d.ts similarity index 87% rename from rx.js/rx.time.d.ts rename to rx/rx.time.d.ts index 18cccd4d35..6efd7d9cfc 100644 --- a/rx.js/rx.time.d.ts +++ b/rx/rx.time.d.ts @@ -1,7 +1,6 @@ -// Type definitions for RxJS-Time v2.2.20 +// Type definitions for RxJS-Time v2.2.28 // Project: http://rx.codeplex.com/ -// Definitions by: Carl de Billy -// Definitions by: Igor Oleinikov +// Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -30,3 +29,7 @@ declare module Rx { scheduler?: IScheduler): Observable; } } + +declare module "rx.time" { + export = Rx; +} \ No newline at end of file diff --git a/rx.js/rx.virtualtime.d.ts b/rx/rx.virtualtime.d.ts similarity index 90% rename from rx.js/rx.virtualtime.d.ts rename to rx/rx.virtualtime.d.ts index bba46a761e..50a1bb39b7 100644 --- a/rx.js/rx.virtualtime.d.ts +++ b/rx/rx.virtualtime.d.ts @@ -1,7 +1,6 @@ -// Type definitions for RxJS-VirtualTime v2.2.20 +// Type definitions for RxJS-VirtualTime v2.2.28 // Project: http://rx.codeplex.com/ -// Definitions by: gsino -// Definitions by: Igor Oleinikov +// Definitions by: gsino , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -34,3 +33,7 @@ declare module Rx { constructor(initialClock: number, comparer: (first: number, second: number) => number); } } + +declare module "rx.virtualtime" { + export = Rx; +} \ No newline at end of file diff --git a/sammyjs/sammyjs.d.ts b/sammyjs/sammyjs.d.ts index 136362fbf9..dc41cbf6fd 100644 --- a/sammyjs/sammyjs.d.ts +++ b/sammyjs/sammyjs.d.ts @@ -1,7 +1,6 @@ // Type definitions for Sammy.js // Project: http://sammyjs.org/ -// Definitions by: Boris Yankov -// Definitions by: Oisin Grehan +// Definitions by: Boris Yankov , Oisin Grehan // Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/scroller/easyscroller.d.ts b/scroller/easyscroller.d.ts index edc3c55d6d..fc0418a57e 100644 --- a/scroller/easyscroller.d.ts +++ b/scroller/easyscroller.d.ts @@ -1,6 +1,6 @@ // Type definitions for Zynga EasyScroller // Project: https://github.com/zynga/scroller -// Definitions by: Boris Yankov https://github.com/borisyankov +// Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -12,4 +12,4 @@ declare class EasyScroller { render(): void; reflow(): void; bindEvents(): void; -} \ No newline at end of file +} diff --git a/scroller/scroller.d.ts b/scroller/scroller.d.ts index 842aa8ee0f..09cbbc2910 100644 --- a/scroller/scroller.d.ts +++ b/scroller/scroller.d.ts @@ -1,6 +1,6 @@ // Type definitions for Zynga Scroller // Project: https://github.com/zynga/scroller -// Definitions by: Boris Yankov https://github.com/borisyankov +// Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -47,4 +47,4 @@ declare class Scroller { doTouchStart(touches: any[], timeStamp: number): void; doTouchMove(touches: any[], timeStamp: number, scale?: number): void; doTouchEnd(timeStamp: number): void; -} \ No newline at end of file +} diff --git a/select2/select2.d.ts b/select2/select2.d.ts index b719ecfac8..b1f21f6647 100644 --- a/select2/select2.d.ts +++ b/select2/select2.d.ts @@ -111,39 +111,39 @@ interface JQuery { /** * Reverts changes to DOM done by Select2. Any selection done via Select2 will be preserved. */ - select2(method: 'destroy'): void; + select2(method: 'destroy'): JQuery; /** * Opens the dropdown */ - select2(method: 'open'): void; + select2(method: 'open'): JQuery; /** * Closes the dropdown */ - select2(method: 'close'): void; + select2(method: 'close'): JQuery; /** * Enables or disables Select2 and its underlying form component * @param value True if it should be enabled false if it should be disabled */ - select2(method: 'enable', value: boolean): void; + select2(method: 'enable', value: boolean): JQuery; /** * Toggles readonly mode on Select2 and its underlying form component * @param value True if it should be readonly false if it should be read write */ - select2(method: 'readonly', value: boolean): void; + select2(method: 'readonly', value: boolean): JQuery; /** * Retrieves the main container element that wraps all of DOM added by Select2 */ - select2(method: 'container'): HTMLElement; + select2(method: 'container'): JQuery; /** * Notifies Select2 that a drag and drop sorting operation has started */ - select2(method: 'onSortStart'): void; + select2(method: 'onSortStart'): JQuery; /** * Notifies Select2 that a drag and drop sorting operation has finished */ - select2(method: 'onSortEnd'): void; + select2(method: 'onSortEnd'): JQuery; select2(method: string): any; select2(method: string, value: any, trigger?: boolean): any; select2(options: Select2Options): JQuery; -} +} diff --git a/semver/semver-tests.ts b/semver/semver-tests.ts index 009a47daf2..f339be75ba 100644 --- a/semver/semver-tests.ts +++ b/semver/semver-tests.ts @@ -10,7 +10,7 @@ var exp:RegExp; var strArr:string[]; var numArr:string[]; -var mod:typeof SemverModule; +var mod:typeof SemVerModule; var v1:string, v2:string; var version:string; @@ -42,7 +42,7 @@ bool = mod.gtr(version, str, loose); bool = mod.ltr(version, str, loose); bool = mod.outside(version, str, str, loose); -var ver = new mod.Semver(str, bool); +var ver = new mod.SemVer(str, bool); str = ver.raw; bool = ver.loose; str = ver.format(); @@ -62,7 +62,7 @@ num = ver.comparePre(ver); ver = ver.inc(str); -var comp = new SemverModule.Comparator(str, bool); +var comp = new SemVerModule.Comparator(str, bool); str = comp.raw; bool = comp.loose; str = comp.format(); @@ -76,7 +76,7 @@ comp.parse(str); bool = comp.test(ver); -var range = new SemverModule.Range(str, bool); +var range = new SemVerModule.Range(str, bool); str = range.raw; bool = range.loose; str = range.format(); @@ -85,8 +85,8 @@ str = range.toString(); bool = range.test(ver); -var sets:SemverModule.Comparator[][]; -sets = range.set(); +var sets:SemVerModule.Comparator[][]; +sets = range.set; -var lims:SemverModule.Comparator[]; +var lims:SemVerModule.Comparator[]; lims = range.parseRange(str); diff --git a/semver/semver.d.ts b/semver/semver.d.ts index 67f536af5c..12909d90e1 100644 --- a/semver/semver.d.ts +++ b/semver/semver.d.ts @@ -3,7 +3,7 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module SemverModule { +declare module SemVerModule { function valid(v:string, loose?:boolean):string; // Return the parsed version, or null if it's not valid. //TODO maybe add an enum for release? @@ -28,7 +28,7 @@ declare module SemverModule { function ltr(version:string, range:string, loose?:boolean):boolean; // Return true if version is less than all the versions possible in the range. function outside(version:string, range:string, hilo:string, loose?:boolean):boolean; // Return true if the version is outside the bounds of the range in either the high or low direction. The hilo argument must be either the string '>' or '<'. (This is the function called by gtr and ltr.) - class SemverBase { + class SemVerBase { raw:string; loose:boolean; format():string; @@ -36,7 +36,7 @@ declare module SemverModule { toString():string; } - class Semver extends SemverBase { + class SemVer extends SemVerBase { constructor(version:string, loose?:boolean); major:number; @@ -46,30 +46,30 @@ declare module SemverModule { build:string[]; prerelease:string[]; - compare(other:Semver):number; - compareMain(other:Semver):number; - comparePre(other:Semver):number; - inc(release:string):Semver; + compare(other:SemVer):number; + compareMain(other:SemVer):number; + comparePre(other:SemVer):number; + inc(release:string):SemVer; } - class Comparator extends SemverBase { + class Comparator extends SemVerBase { constructor(comp:string, loose?:boolean); - semver:Semver; + semver:SemVer; operator:string; value:boolean; parse(comp:string) :void; - test(version:Semver):boolean; + test(version:SemVer):boolean; } - class Range extends SemverBase { + class Range extends SemVerBase { constructor(range:string, loose?:boolean); - set():Comparator[][]; + set:Comparator[][]; parseRange(range:string):Comparator[]; - test(version:Semver):boolean; + test(version:SemVer):boolean; } } declare module "semver" { -export = SemverModule; +export = SemVerModule; } diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index b0417fd33b..1f7a2feaf4 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -3,8 +3,6 @@ // Definitions by: Stanislav Vyshchepan , Andrey Markeev // Definitions: https://github.com/borisyankov/DefinitelyTyped - - declare module Sys { export class EventArgs { static Empty: Sys.EventArgs; @@ -154,6 +152,7 @@ declare var $get: { (id: string): HTMLElement; }; declare var $addHandler: { (element: HTMLElement, eventName: string, handler: (e: Event) => void): void; }; declare var $removeHandler: { (element: HTMLElement, eventName: string, handler: (e: Event) => void): void; }; + declare module SP { export class SOD { static execute(fileName: string, functionName: string, ...args: any[]): void; @@ -172,9 +171,108 @@ declare module SP { static get_ribbonImagePrefetchEnabled(): boolean; static set_ribbonImagePrefetchEnabled(value: boolean): void; - - } + + export enum ListLevelPermissionMask { + viewListItems,//: 1, + insertListItems,//: 2, + editListItems,//: 4, + deleteListItems,//: 8, + approveItems,//: 16, + openItems,//: 32, + viewVersions,//: 64, + deleteVersions,//: 128, + breakCheckout,//: 256, + managePersonalViews,//: 512, + manageLists//: 2048 + } + + export class HtmlBuilder { + constructor(); + addAttribute(name: string, value: string): void; + addCssClass(cssClassName: string): void; + addCommunitiesCssClass(cssClassName: string): void; + renderBeginTag(tagName: string): void; + renderEndTag(): void; + write(s: string): void; + writeEncoded(s: string): void; + toString(): string; + } + + export class ScriptHelpers { + static disableWebpartSelection(context: SPClientTemplates.RenderContext): void; + static getDocumentQueryPairs(): { [index: string]: string; }; + static getFieldFromSchema(schema: SPClientTemplates.ListSchema, fieldName: string): SPClientTemplates.FieldSchema; + static getLayoutsPageUrl(pageName: string, webServerRelativeUrl: string): string; + static getListLevelPermissionMask(jsonItem: string): number; + static getTextAreaElementValue(textAreaElement: HTMLTextAreaElement): string; + static getUrlQueryPairs(docUrl: string): { [index: string]: string; }; + static getUserFieldProperty(item: ListItem, fieldName: string, propertyName: string): any; + static hasPermission(listPermissionMask: number, listPermission: ListLevelPermissionMask): boolean; + static newGuid(): SP.Guid; + static isNullOrEmptyString(str: string): boolean; + static isNullOrUndefined(obj: any): boolean; + static isNullOrUndefinedOrEmpty(str: string): boolean; + static isUndefined(obj: any): boolean; + static replaceOrAddQueryString(url: string, key: string, value: string): string; + static removeHtml(str: string): string; + static removeStyleChildren(element: HTMLElement); + static removeHtmlAndTrimStringWithEllipsis(str: string, maxLength: number): string; + static setTextAreaElementValue(textAreaElement: HTMLTextAreaElement, newValue: string): void; + static truncateToInt(n: number): number; + static urlCombine(path1: string, path2: string): string; + static resizeImageToSquareLength(imgElement: HTMLImageElement, squareLength: number): void; + } + + + export class PageContextInfo { + static get_siteServerRelativeUrl(): string; + static get_webServerRelativeUrl(): string; + static get_webAbsoluteUrl(): string; + static get_serverRequestPath(): string; + static get_siteAbsoluteUrl(): string; + static get_webTitle(): string; + static get_tenantAppVersion(): string; + static get_webLogoUrl(): string; + static get_webLanguage(): number; + static get_currentLanguage(): number; + static get_pageItemId(): number; + static get_pageListId(): string; + static get_webPermMasks(): { High: number; Low: number; }; + static get_currentCultureName(): string; + static get_currentUICultureName(): string; + static get_clientServerTimeDelta(): number; + static get_userLoginName(): string; + static get_webTemplate(): string; + get_pagePersonalizationScope(): string; + } + + export class ContextPermissions { + has(perm: number): boolean; + hasPermissions(high: number, low: number): boolean; + fromJson(json: { High: number; Low: number; }): void; + } + + export module ListOperation { + export module ViewOperation { + export function getSelectedView(): string; + export function navigateUp(viewId: string): void; + export function refreshView(viewId: string): void; + } + export module Selection { + export function selectListItem(iid: string, bSelect: boolean); + export function getSelectedItems(): { id: number; fsObjType: FileSystemObjectType; }[]; + export function getSelectedList(): string; + export function getSelectedView(): string; + export function navigateUp(viewId: string): void; + export function deselectAllListItems(iid: string); + } + export module Overrides { + export function overrideDeleteConfirmation(listId: string, overrideText:string):void; + } + } + + } /** Register function to rerun on partial update in MDS-enabled site.*/ @@ -229,6 +327,143 @@ declare function AddEvtHandler(element: HTMLElement, event: string, func: EventL /** Gets query string parameter */ declare function GetUrlKeyValue(key: string): string; + +declare class AjaxNavigate { + update(url:string, updateParts:Object, fullNavigate:boolean, anchorName:string):void; + add_navigate(handler: Function): void; + remove_navigate(handler:Function):void; + submit(formToSubmit:HTMLFormElement):void; + getParam(paramName:string):string; + getSavedFormAction():string; + get_href(): string; + get_hash(): string; + get_search():string; + convertMDSURLtoRegularURL(mdsPath:string):string; +} + +declare var ajaxNavigate: AjaxNavigate; + +declare class Browseris { + firefox: boolean; + firefox36up: boolean; + firefox3up: boolean; + firefox4up: boolean; + ie: boolean; + ie55up: boolean; + ie5up: boolean; + ie7down: boolean; + ie8down: boolean; + ie9down: boolean; + ie8standard: boolean; + ie8standardUp: boolean; + ie9standardUp: boolean; + ipad: boolean; + windowsphone: boolean; + chrome: boolean; + chrome7up: boolean; + chrome8up: boolean; + chrome9up: boolean; + iever: boolean; + mac: boolean; + major: boolean; + msTouch: boolean; + isTouch: boolean; + nav: boolean; + nav6: boolean; + nav6up: boolean; + nav7up: boolean; + osver: boolean; + safari: boolean; + safari125up: boolean; + safari3up: boolean; + verIEFull: boolean; + w3c: boolean; + webKit: boolean; + win: boolean; + win8AppHost: boolean; + win32: boolean; + win64bit: boolean; + winnt: boolean; + armProcessor: boolean +} + +declare var browseris: Browseris; + +interface ContextInfo extends SPClientTemplates.RenderContext { + AllowGridMode: boolean; + BasePermissions: any; + BaseViewID: any; + CascadeDeleteWarningMessage: string; + ContentTypesEnabled: boolean; + CurrentSelectedItems: boolean; + CurrentUserId: number; + EnableMinorVersions: boolean; + ExternalDataList: boolean; + HasRelatedCascadeLists: boolean; + HttpPath: string; + HttpRoot: string; + LastSelectableRowIdx: number; + LastSelectedItemIID: number; + LastRowIndexSelected: number; + RowFocusTimerID: number; + ListData: any;// SPClientTemplates.ListData_InView | SPClientTemplates.ListData_InForm + ListSchema: SPClientTemplates.ListSchema; + ModerationStatus: number; + PortalUrl: string; + RecycleBinEnabled: number; + SelectAllCbx: HTMLElement; + SendToLocationName: string; + SendToLocationUrl: string; + StateInitDone: boolean; + TableCbxFocusHandler: Function; + TableMouseoverHandler: Function; + TotalListItems: number; + WorkflowsAssociated: boolean; + clvp: any; + ctxId: number; + ctxType: any; + dictSel: any; + displayFormUrl: string; + editFormUrl: string; + imagesPath: string; + inGridMode: boolean; + inGridFullRender: boolean; + isForceCheckout: boolean; + isModerated: boolean; + isPortalTemplate: boolean; + isVersions: boolean; + isWebEditorPreview: boolean; + leavingGridMode: boolean; + loadingAsyncData: boolean; + listBaseType: number; + listName: string; + listTemplate: string; + listUrlDir: string; + newFormUrl: string; + onRefreshFailed: Function; + overrideDeleteConfirmation: string; + overrideFilterQstring: string; + recursiveView: boolean; + rootFolderForDisplay: string; + serverUrl: string; + verEnabled: boolean; + view: string; + queryString: string; + IsClientRendering: boolean; + wpq: string; + rootFolder: string; + IsAppWeb: boolean; + NewWOPIDocumentEnabled: boolean; + NewWOPIDocumentUrl: string; + AllowCreateFolder: boolean; + CanShareLinkForNewDocument: boolean; + noGroupCollapse: boolean; + SiteTemplateId: number; + ExcludeFromOfflineClient: boolean; + +} + +declare function GetCurrentCtx():ContextInfo; declare module SP { export enum RequestExecutorErrors { requestAbortedOrTimedout, @@ -246,8 +481,8 @@ declare module SP { set_formDigestHandlingEnabled(value: boolean): void; get_iFrameSourceUrl(): string; set_iFrameSourceUrl(value: string): void; - executeAsync(requestInfo: RequestInfo): void; - attemptLogin(returnUrl: string, success: (response: ResponseInfo) => void, error?: (response: ResponseInfo, error: RequestExecutorErrors, statusText: string) => void): void; + executeAsync(requestInfo:RequestInfo): void; + attemptLogin(returnUrl:string, success: (response: ResponseInfo) => void , error?: (response: ResponseInfo, error: RequestExecutorErrors, statusText: string) => void): void; } export interface RequestInfo { @@ -287,12 +522,13 @@ declare module SP { createWebRequestExecutor(): ProxyWebRequestExecutor; } } -interface MQuery { +interface MQuery +{ (selector: string, context?: any): MQueryResultSetElements; (element: HTMLElement): MQueryResultSetElements; (object: MQueryResultSetElements): MQueryResultSetElements; (object: MQueryResultSet): MQueryResultSet; - (object: T): MQueryResultSet; + (object: T): MQueryResultSet; (elementArray: HTMLElement[]): MQueryResultSetElements; (array: T[]): MQueryResultSet; (): MQueryResultSet; @@ -321,7 +557,7 @@ interface MQuery { isObject(obj: any): boolean; isEmptyObject(obj: any): boolean; - ready(callback: () => void): void; + ready(callback: () => void ): void; contains(container: HTMLElement, contained: HTMLElement): boolean; proxy(fn: (...args: any[]) => any, context: any, ...args: any[]): Function; @@ -363,7 +599,7 @@ interface MQuery { hasData(element: HTMLElement): boolean; } -interface MQueryResultSetElements extends MQueryResultSet { +interface MQueryResultSetElements extends MQueryResultSet{ append(node: HTMLElement): MQueryResultSetElements; append(mQuerySet: MQueryResultSetElements): MQueryResultSetElements; append(html: string): MQueryResultSetElements; @@ -471,26 +707,26 @@ interface MQueryResultSetElements extends MQueryResultSet { submit(): MQueryResultSetElements; submit(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; unload(): MQueryResultSetElements; - unload(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + unload(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; } -interface MQueryResultSet { +interface MQueryResultSet { [index: number]: T; contains(contained: T): boolean; - + filter(fn: (elementOfArray: T, indexInArray: number) => boolean, context?: any): MQueryResultSet; - filter(fn: (elementOfArray: T) => boolean, context?: any): MQueryResultSet; + filter(fn: (elementOfArray: T) => boolean, context?: any): MQueryResultSet; every(fn: (elementOfArray: T, indexInArray: number) => boolean, context?: any): boolean; every(fn: (elementOfArray: T) => boolean, context?: any): boolean; - + some(fn: (elementOfArray: T, indexInArray: number) => boolean, context?: any): boolean; some(fn: (elementOfArray: T) => boolean, context?: any): boolean; - + map(callback: (elementOfArray: T, indexInArray: number) => any): MQueryResultSet; map(callback: (elementOfArray: T) => any): MQueryResultSet; - + forEach(fn: (elementOfArray: T, indexInArray: number) => void, context?: any): void; forEach(fn: (elementOfArray: T) => void, context?: any): void; @@ -579,12 +815,12 @@ declare class CalloutAction { render(): void; isEnabled(): boolean; isVisible(): boolean; - set(options: CalloutActionOptions): void; + set (options: CalloutActionOptions): void; } declare class Callout { /** Sets options for the callout. Not all options can be changed for the callout after its creation. */ - set(options: CalloutOptions); + set (options: CalloutOptions); /** Adds event handler to the callout. @param eventName one of the following: "opened", "opening", "closing", "closed" */ addEventCallback(eventName: string, callback: (callout: Callout) => void); @@ -867,17 +1103,26 @@ declare module SPClientTemplates { PictureOnly: boolean; PictureSize: string; } - /** Represents field schema in Grid mode and on list forms. - Consider casting objects of this type to more specific field types, e.g. FieldSchemaInForm_Lookup */ - export interface FieldSchema_InForm { + + export interface FieldSchema { /** Specifies if the field can be edited while list view is in the Grid mode */ AllowGridEditing: boolean; + /** String representation of the field type, e.g. "Lookup". Same as SPField.TypeAsString */ + FieldType: string; + /** Internal name of the field */ + Name: string; + /** For OOTB fields, returns the type of field. For "UserMulti" returns "User", for "LookupMulti" returns "Lookup". + For custom field types, returns base type of the field. */ + Type: string; + } + +/** Represents field schema in Grid mode and on list forms. + Consider casting objects of this type to more specific field types, e.g. FieldSchemaInForm_Lookup */ + export interface FieldSchema_InForm extends FieldSchema { /** Description for this field. */ Description: string; /** Direction of the reading order for the field. */ Direction: string; - /** String representation of the field type, e.g. "Lookup". Same as SPField.TypeAsString */ - FieldType: string; /** Indicates whether the field is hidden */ Hidden: boolean; /** Guid of the field */ @@ -885,8 +1130,6 @@ declare module SPClientTemplates { /** Specifies Input Method Editor (IME) mode bias to use for the field. The IME enables conversion of keystrokes between languages when one writing system has more characters than can be encoded for the given keyboard. */ IMEMode: any; - /** Internal name of the field */ - Name: string; /** Specifies if the field is read only */ ReadOnlyField: boolean; /** Specifies wherever field requires values */ @@ -894,13 +1137,16 @@ declare module SPClientTemplates { RestrictedMode: boolean; /** Title of the field */ Title: string; - /** For OOTB fields, returns the type of field. For "UserMulti" returns "User", for "LookupMulti" returns "Lookup". - For custom field types, returns base type of the field. */ - Type: string; /** If SPFarm.Local.UseMinWidthForHtmlPicker is true, UseMinWidth will be set to true. Undefined in other cases. */ UseMinWidth: boolean; } - export interface ListSchema_InForm { + + export interface ListSchema { + Field: FieldSchema[]; + } + + + export interface ListSchema_InForm extends ListSchema { Field: FieldSchema_InForm[]; } export interface ListData_InForm { @@ -945,9 +1191,7 @@ declare module SPClientTemplates { DefaultRender: string; } /** Represents field schema in a list view. */ - export interface FieldSchema_InView { - /** Either "TRUE" or "FALSE" */ - AllowGridEditing: string; + export interface FieldSchema_InView extends FieldSchema { /** Either "TRUE" or "FALSE" */ CalloutMenu: string; ClassInfo: string; // e.g. "Menu" @@ -957,8 +1201,6 @@ declare module SPClientTemplates { Explicit: string; fieldRenderer: any; FieldTitle: string; - /** Represents SPField.TypeAsString, e.g. "Computed", "UserMulti", etc. */ - FieldType: string; /** Indicates whether the field can be filtered. Either "TRUE" or "FALSE" */ Filterable: string; /** Set to "TRUE" for fields that comply to the following Xpath query: @@ -971,16 +1213,14 @@ declare module SPClientTemplates { /** Specifies if the field contains list item menu. Corresponds to ViewFields/FieldRef/@ListItemMenu attribute. Either "TRUE" or "FALSE" and might be missing. */ listItemMenu: string; - Name: string; RealFieldName: string; /** Either "TRUE" or "FALSE" */ ReadOnly: string; ResultType: string; /** Indicates whether the field can be sorted. Either "TRUE" or "FALSE" */ Sortable: string; - Type: string; } - export interface ListSchema_InView { + export interface ListSchema_InView extends ListSchema { /** Key-value object that represents all aggregations defined for the view. Key specifies the field internal name, and value specifies the type of the aggregation. */ Aggregate: { [name: string]: string; }; @@ -992,7 +1232,6 @@ declare module SPClientTemplates { /** Either "0" or "1" */ EffectivePresenceEnabled: string; /** If in grid mode (context.inGridMode == true), cast to FieldSchema_InForm[], otherwise cast to FieldSchema_InView[] */ - Field: any[]; FieldSortParam: string; Filter: any; /** Either "0" or "1" */ @@ -1180,26 +1419,26 @@ declare module SPClientTemplates { } export interface RenderContext { - BaseViewID: number; - ControlMode: ClientControlMode; - CurrentCultureName: string; - CurrentLanguage: number; - CurrentSelectedItems: any; - CurrentUICultureName: string; - ListTemplateType: number; - OnPostRender: any; - OnPreRender: any; - onRefreshFailed: any; - RenderBody: (renderContext: RenderContext) => string; - RenderFieldByName: (renderContext: RenderContext, fieldName: string) => string; - RenderFields: (renderContext: RenderContext) => string; - RenderFooter: (renderContext: RenderContext) => string; - RenderGroups: (renderContext: RenderContext) => string; - RenderHeader: (renderContext: RenderContext) => string; - RenderItems: (renderContext: RenderContext) => string; - RenderView: (renderContext: RenderContext) => string; - SiteClientTag: string; - Templates: TemplateOverrides; + BaseViewID?: number; + ControlMode?: ClientControlMode; + CurrentCultureName?: string; + CurrentLanguage?: number; + CurrentSelectedItems?: any; + CurrentUICultureName?: string; + ListTemplateType?: number; + OnPostRender?: any; + OnPreRender?: any; + onRefreshFailed?: any; + RenderBody?: (renderContext: RenderContext) => string; + RenderFieldByName?: (renderContext: RenderContext, fieldName: string) => string; + RenderFields?: (renderContext: RenderContext) => string; + RenderFooter?: (renderContext: RenderContext) => string; + RenderGroups?: (renderContext: RenderContext) => string; + RenderHeader?: (renderContext: RenderContext) => string; + RenderItems?: (renderContext: RenderContext) => string; + RenderView?: (renderContext: RenderContext) => string; + SiteClientTag?: string; + Templates?: Templates; } export interface SingleTemplateCallback { @@ -1214,6 +1453,12 @@ declare module SPClientTemplates { /** Must return null in order to fall back to a more common template or to a system default template */ (renderContext: RenderContext): string; } + + export interface FieldCallback { + /** Must return null in order to fall back to a more common template or to a system default template */ + (renderContext: RenderContext): string; + } + export interface FieldInFormCallback { /** Must return null in order to fall back to a more common template or to a system default template */ (renderContext: RenderContext_FieldInForm): string; @@ -1234,6 +1479,27 @@ declare module SPClientTemplates { View?: FieldInViewCallback; } + export interface FieldTemplates { + [fieldInternalName: string]: FieldCallback; + } + + export interface Templates { + View?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template + Body?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template + /** Defines templates for rendering groups (aggregations). */ + Group?: GroupCallback; + /** Defines templates for list items rendering. */ + Item?: ItemCallback; + /** Defines template for rendering list view header. + Can be either string or SingleTemplateCallback */ + Header?: SingleTemplateCallback; + /** Defines template for rendering list view footer. + Can be either string or SingleTemplateCallback */ + Footer?: SingleTemplateCallback; + /** Defines templates for fields rendering. The field is specified by it's internal name. */ + Fields?: FieldTemplates; + } + export interface FieldTemplateMap { [fieldInternalName: string]: FieldTemplateOverrides; } @@ -1276,6 +1542,7 @@ declare module SPClientTemplates { } export class TemplateManager { static RegisterTemplateOverrides(renderCtx: TemplateOverridesOptions): void; + static GetTemplates(renderCtx: any): Templates; } export interface ClientUserValue { @@ -1349,13 +1616,13 @@ declare module SPClientTemplates { EnableVesioning: boolean; Id: string; }; - registerInitCallback(fieldname: string, callback: () => void): void; - registerFocusCallback(fieldname: string, callback: () => void): void; - registerValidationErrorCallback(fieldname: string, callback: (error: any) => void): void; + registerInitCallback(fieldname: string, callback: () => void ): void; + registerFocusCallback(fieldname: string, callback: () => void ): void; + registerValidationErrorCallback(fieldname: string, callback: (error: any) => void ): void; registerGetValueCallback(fieldname: string, callback: () => any): void; updateControlValue(fieldname: string, value: any): void; registerClientValidator(fieldname: string, validator: SPClientForms.ClientValidation.ValidatorSet): void; - registerHasValueChangedCallback(fieldname: string, callback: (eventArg?: any) => void); + registerHasValueChangedCallback(fieldname: string, callback: (eventArg?: any) => void ); } } @@ -1434,23 +1701,23 @@ declare module SPAnimation { GetDataIndex(attributeId: Attribute): number } - export class Object { - constructor(animationID: ID, delay: number, element: HTMLElement, finalState: State, finishFunc?: (data: any) => void, data?: any); - constructor(animationID: ID, delay: number, element: HTMLElement[], finalState: State, finishFunc?: (data: any) => void, data?: any); + export class Object{ + constructor(animationID: ID, delay: number, element: HTMLElement, finalState: State, finishFunc?: (data: any) => void , data?: any); + constructor(animationID: ID, delay: number, element: HTMLElement[], finalState: State, finishFunc?: (data: any) => void , data?: any); RunAnimation(): void; } } -declare module SPAnimationUtility { +declare module SPAnimationUtility{ export class BasicAnimator { - static FadeIn(element: HTMLElement, finishFunc?: (data: any) => void, data?: any): void; - static FadeOut(element: HTMLElement, finishFunc?: (data: any) => void, data?: any): void; - static Move(element: HTMLElement, posX: number, posY: number, finishFunc?: (data: any) => void, data?: any): void; - static StrikeThrough(element: HTMLElement, strikeThroughWidth: number, finishFunc?: (data: any) => void, data?: any): void; - static Resize(element: HTMLElement, newHeight: number, newWidth: number, finishFunc?: (data: any) => void, data?: any): void; - static CommonResize(element: HTMLElement, newHeight: number, newWidth: number, finishFunc: (data: any) => void, data: any, animationId: SPAnimation.ID): void; - static QuickResize(element: HTMLElement, newHeight: number, newWidth: number, finishFunc?: (data: any) => void, data?: any): void; - static ResizeContainerAndFillContent(element: HTMLElement, newHeight: number, newWidth: number, finishFunc: () => void, fAddToEnd: boolean): void; + static FadeIn(element: HTMLElement, finishFunc?: (data: any) => void , data?: any): void; + static FadeOut (element: HTMLElement, finishFunc?: (data: any) => void , data?: any): void; + static Move(element: HTMLElement, posX:number, posY:number, finishFunc?: (data: any) => void , data?: any): void; + static StrikeThrough(element: HTMLElement, strikeThroughWidth: number, finishFunc?: (data: any) => void , data?: any): void; + static Resize(element: HTMLElement, newHeight: number, newWidth: number, finishFunc?: (data: any) => void , data?: any): void; + static CommonResize(element: HTMLElement, newHeight: number, newWidth: number, finishFunc: (data: any) => void , data: any, animationId:SPAnimation.ID): void; + static QuickResize(element: HTMLElement, newHeight: number, newWidth: number, finishFunc?: (data: any) => void , data?: any): void; + static ResizeContainerAndFillContent(element: HTMLElement, newHeight: number, newWidth: number, finishFunc: () => void , fAddToEnd: boolean): void; static GetWindowScrollPosition(): { x: number; y: number; }; static GetLeftOffset(element: HTMLElement): number; static GetTopOffset(element: HTMLElement): number; @@ -1702,13 +1969,13 @@ declare module SP { get_expectedContentType(): string; set_expectedContentType(value: string): void; post(body: string): void; - get(): void; - static doPost(url: string, body: string, expectedContentType: string, succeededHandler: (sender: any, args: SP.PageRequestSucceededEventArgs) => void, failedHandler: (sender: any, args: SP.PageRequestFailedEventArgs) => void): void; - static doGet(url: string, expectedContentType: string, succeededHandler: (sender: any, args: SP.PageRequestSucceededEventArgs) => void, failedHandler: (sender: any, args: SP.PageRequestFailedEventArgs) => void): void; - add_succeeded(value: (sender: any, args: SP.PageRequestSucceededEventArgs) => void): void; - remove_succeeded(value: (sender: any, args: SP.PageRequestSucceededEventArgs) => void): void; - add_failed(value: (sender: any, args: SP.PageRequestFailedEventArgs) => void): void; - remove_failed(value: (sender: any, args: SP.PageRequestFailedEventArgs) => void): void; + get (): void; + static doPost(url: string, body: string, expectedContentType: string, succeededHandler: (sender: any, args: SP.PageRequestSucceededEventArgs) => void , failedHandler: (sender: any, args: SP.PageRequestFailedEventArgs) => void ): void; + static doGet(url: string, expectedContentType: string, succeededHandler: (sender: any, args: SP.PageRequestSucceededEventArgs) => void , failedHandler: (sender: any, args: SP.PageRequestFailedEventArgs) => void ): void; + add_succeeded(value: (sender: any, args: SP.PageRequestSucceededEventArgs) => void ): void; + remove_succeeded(value: (sender: any, args: SP.PageRequestSucceededEventArgs) => void ): void; + add_failed(value: (sender: any, args: SP.PageRequestFailedEventArgs) => void ): void; + remove_failed(value: (sender: any, args: SP.PageRequestFailedEventArgs) => void ): void; constructor(); } export class ResResources { @@ -1962,10 +2229,10 @@ declare module SP { export class ClientRequest { static get_nextSequenceId(): number; get_webRequest(): Sys.Net.WebRequest; - add_requestSucceeded(value: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void): void; - remove_requestSucceeded(value: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void): void; - add_requestFailed(value: (sender: any, args: SP.ClientRequestFailedEventArgs) => void): void; - remove_requestFailed(value: (sender: any, args: SP.ClientRequestFailedEventArgs) => void): void; + add_requestSucceeded(value: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void ): void; + remove_requestSucceeded(value: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void ): void; + add_requestFailed(value: (sender: any, args: SP.ClientRequestFailedEventArgs) => void ): void; + remove_requestFailed(value: (sender: any, args: SP.ClientRequestFailedEventArgs) => void ): void; get_navigateWhenServerRedirect(): boolean; set_navigateWhenServerRedirect(value: boolean): void; } @@ -2000,18 +2267,18 @@ declare module SP { set_webRequestExecutorFactory(value: SP.IWebRequestExecutorFactory): void; get_pendingRequest(): SP.ClientRequest; get_hasPendingRequest(): boolean; - add_executingWebRequest(value: (sender: any, args: SP.WebRequestEventArgs) => void): void; - remove_executingWebRequest(value: (sender: any, args: SP.WebRequestEventArgs) => void): void; - add_requestSucceeded(value: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void): void; - remove_requestSucceeded(value: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void): void; - add_requestFailed(value: (sender: any, args: SP.ClientRequestFailedEventArgs) => void): void; - remove_requestFailed(value: (sender: any, args: SP.ClientRequestFailedEventArgs) => void): void; - add_beginningRequest(value: (sender: any, args: SP.ClientRequestEventArgs) => void): void; - remove_beginningRequest(value: (sender: any, args: SP.ClientRequestEventArgs) => void): void; + add_executingWebRequest(value: (sender: any, args: SP.WebRequestEventArgs) => void ): void; + remove_executingWebRequest(value: (sender: any, args: SP.WebRequestEventArgs) => void ): void; + add_requestSucceeded(value: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void ): void; + remove_requestSucceeded(value: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void ): void; + add_requestFailed(value: (sender: any, args: SP.ClientRequestFailedEventArgs) => void ): void; + remove_requestFailed(value: (sender: any, args: SP.ClientRequestFailedEventArgs) => void ): void; + add_beginningRequest(value: (sender: any, args: SP.ClientRequestEventArgs) => void ): void; + remove_beginningRequest(value: (sender: any, args: SP.ClientRequestEventArgs) => void ): void; get_requestTimeout(): number; set_requestTimeout(value: number): void; - executeQueryAsync(succeededCallback: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void, failedCallback: (sender: any, args: SP.ClientRequestFailedEventArgs) => void): void; - executeQueryAsync(succeededCallback: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void): void; + executeQueryAsync(succeededCallback: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void , failedCallback: (sender: any, args: SP.ClientRequestFailedEventArgs) => void ): void; + executeQueryAsync(succeededCallback: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void ): void; executeQueryAsync(): void; get_staticObjects(): any; castTo(obj: SP.ClientObject, type: any): SP.ClientObject; @@ -2390,7 +2657,7 @@ declare module SP { constructor(); } export class BasePermissions extends SP.ClientValueObject { - set(perm: SP.PermissionKind): void; + set (perm: SP.PermissionKind): void; clear(perm: SP.PermissionKind): void; clearAll(): void; has(perm: SP.PermissionKind): boolean; @@ -3719,7 +3986,7 @@ declare module SP { choiceField, minMaxField, textField, - } + } /** Represents an item or row in a list. */ export class ListItem extends SP.SecurableObject { get_fieldValues(): any; @@ -4153,7 +4420,7 @@ declare module SP { get_value(): string; static newObject(context: SP.ClientRuntimeContext): SP.RequestVariable; append(value: string): void; - set(value: string): void; + set (value: string): void; } export class RoleAssignment extends SP.ClientObject { get_member(): SP.Principal; @@ -4846,8 +5113,8 @@ declare module SP { set_moreColorsPicker(value: SP.Application.UI.MoreColorsPicker): void; } export class ThemeWebPage extends Sys.UI.Control { - add_themeDisplayUpdated(value: (sender: any, e: Sys.EventArgs) => void): void; - remove_themeDisplayUpdated(value: (sender: any, e: Sys.EventArgs) => void): void; + add_themeDisplayUpdated(value: (sender: any, e: Sys.EventArgs) => void ): void; + remove_themeDisplayUpdated(value: (sender: any, e: Sys.EventArgs) => void ): void; constructor(e: HTMLElement); initialize(): void; dispose(): void; @@ -5033,11 +5300,11 @@ declare module Microsoft.SharePoint.Client.Search { getQuerySuggestionsWithResults: (iNumberOfQuerySuggestions: number, - iNumberOfResultSuggestions: number, - fPreQuerySuggestions: boolean, - fHitHighlighting: boolean, - fCapitalizeFirstLetters: boolean, - fPrefixMatchAllTerms: boolean) => QuerySuggestionResults; + iNumberOfResultSuggestions: number, + fPreQuerySuggestions: boolean, + fHitHighlighting: boolean, + fCapitalizeFirstLetters: boolean, + fPrefixMatchAllTerms: boolean) => QuerySuggestionResults; } @@ -5083,15 +5350,15 @@ declare module Microsoft.SharePoint.Client.Search { executeQuery: (query: Query) => SP.JsonObjectResult; executeQueries: (queryIds: string[], queries: Query[], handleExceptions: boolean) => SP.JsonObjectResult; recordPageClick: ( - pageInfo: string, - clickType: string, - blockType: number, - clickedResultId: string, - subResultIndex: number, - immediacySourceId: string, - immediacyQueryString: string, - immediacyTitle: string, - immediacyUrl: string) => void; + pageInfo: string, + clickType: string, + blockType: number, + clickedResultId: string, + subResultIndex: number, + immediacySourceId: string, + immediacyQueryString: string, + immediacyTitle: string, + immediacyUrl: string) => void; exportPopularQueries: (web: SP.Web, sourceId: SP.Guid) => SP.JsonObjectResult; } @@ -5212,7 +5479,7 @@ declare module Microsoft.SharePoint.Client.Search { itemAt: (index: number) => Sort; get_item: (index: number) => Sort; get_childItemType: () => Object; - add: (property: Sort) => void; + add: (strProperty: string, sortDirection: SortDirection) => void; clear: () => void; } @@ -5397,14 +5664,14 @@ declare module Microsoft.SharePoint.Client.Search { export class DocumentCrawlLog extends SP.ClientObject { constructor(context: SP.ClientContext, site: SP.Site); getCrawledUrls: (getCountOnly: boolean, - maxRows: { High: number; Low: number; }, - queryString: string, - isLike: boolean, - contentSourceID: number, - errorLevel: number, - errorID: number, - startDateTime: Date, - endDateTime: Date) => SP.JsonObjectResult; + maxRows: { High: number; Low: number; }, + queryString: string, + isLike: boolean, + contentSourceID: number, + errorLevel: number, + errorID: number, + startDateTime: Date, + endDateTime: Date) => SP.JsonObjectResult; } export class SearchObjectOwner extends SP.ClientObject { @@ -6062,7 +6329,7 @@ declare module SP { /** Provides access to social feeds. It provides methods to create posts, delete posts, read posts, and perform other operations on posts. */ export class SocialFeedManager extends SP.ClientObject { - constructor(); + constructor(context: SP.ClientRuntimeContext); /** Returns the current user */ get_owner(): SocialActor; /** Specifies the URI of the personal site portal. */ @@ -6138,7 +6405,7 @@ declare module SP { set_newerThan(value: string): string; get_olderThan(): string; set_olderThan(value: string): string; - get_sortOrder(): SocialFeedSortOrder; + get_sortOrder():SocialFeedSortOrder; set_sortOrder(value: SocialFeedSortOrder): SocialFeedSortOrder; } @@ -6547,7 +6814,7 @@ declare module SP { get_isReused(): boolean; get_isRoot(): boolean; get_isSourceTerm(): boolean; - get_labels: LabelCollection; + get_labels(): LabelCollection; get_localCustomProperties(): { [key: string]: string; }; get_mergedTermIds(): SP.Guid[]; get_parent(): Term; @@ -6807,7 +7074,7 @@ declare module SP { get_selectedEntities(): any; set_selectedEntities(value: any): void; get_callback(): (sender: any, e: Sys.EventArgs) => void; - set_callback(value: (sender: any, e: Sys.EventArgs) => void): void; + set_callback(value: (sender: any, e: Sys.EventArgs) => void ): void; get_scopeKey(): string; get_componentType(): SP.UI.ApplicationPages.SelectorType; revertTo(ent: SP.UI.ApplicationPages.ResolveEntity): void; @@ -6825,7 +7092,7 @@ declare module SP { static instance(): SP.UI.ApplicationPages.CalendarSelector; registerSelector(selector: SP.UI.ApplicationPages.ISelectorComponent): void; getSelector(type: SP.UI.ApplicationPages.SelectorType, scopeKey: string): SP.UI.ApplicationPages.ISelectorComponent; - addHandler(scopeKey: string, people: boolean, resource: boolean, handler: (sender: any, selection: SP.UI.ApplicationPages.SelectorSelectionEventArgs) => void): void; + addHandler(scopeKey: string, people: boolean, resource: boolean, handler: (sender: any, selection: SP.UI.ApplicationPages.SelectorSelectionEventArgs) => void ): void; revertTo(scopeKey: string, ent: SP.UI.ApplicationPages.ResolveEntity): void; removeEntity(scopeKey: string, ent: SP.UI.ApplicationPages.ResolveEntity): void; constructor(); @@ -6837,7 +7104,7 @@ declare module SP { get_selectedEntities(): any; set_selectedEntities(value: any): void; get_callback(): (sender: any, e: Sys.EventArgs) => void; - set_callback(value: (sender: any, e: Sys.EventArgs) => void): void; + set_callback(value: (sender: any, e: Sys.EventArgs) => void ): void; revertTo(ent: SP.UI.ApplicationPages.ResolveEntity): void; removeEntity(ent: SP.UI.ApplicationPages.ResolveEntity): void; setEntity(ent: SP.UI.ApplicationPages.ResolveEntity): void; @@ -6952,39 +7219,27 @@ declare module SP { get_textElement(): HTMLElement; constructor(); } - export class Notify { - static addNotification(strHtml: string, bSticky: boolean): string; - static removeNotification(nid: string): void; - constructor(); - } - export enum ContainerID { - Basic, - Status, - } - export enum EventID { - OnShow, - OnHide, - OnDisplayNotification, - OnRemoveNotification, - OnNotificationCountChanged, - } - export class SPNotification { - constructor(containerId: SP.UI.ContainerID, strHtml: string, bSticky: boolean, strTooltip: string, onclickHandler: () => void, extraData: any); - constructor(containerId: SP.UI.ContainerID, strHtml: string, bSticky: boolean, strTooltip: string, onclickHandler: () => void); - constructor(containerId: SP.UI.ContainerID, strHtml: string, bSticky: boolean, strTooltip: string); - constructor(containerId: SP.UI.ContainerID, strHtml: string, bSticky: boolean); - constructor(containerId: SP.UI.ContainerID, strHtml: string); - get_id(): string; - Show(bNoAnimate: boolean): void; - Hide(bNoAnimate: boolean): void; - } - export class SPNotificationContainer { - constructor(id: number, element: any, layer: number, notificationLimit: number); - constructor(id: number, element: any, layer: number); - Clear(): void; - GetCount(): number; - SetEventHandler(eventId: SP.UI.EventID, eventHandler: any): void; + + export module Notify { + export function addNotification(strHtml: string, bSticky: boolean): string; + export function removeNotification(nid: string): void; + export function showLoadingNotification(bSticky: boolean): string; + + + export class Notification { + constructor(containerId: SPNotifications.ContainerID, strHtml: string, bSticky?: boolean, strTooltip?: string, onclickHandler?: () => void, extraData?: SPStatusNotificationData); + get_id(): string; + Show(bNoAnimate: boolean): void; + Hide(bNoAnimate: boolean): void; + } + export class NotificationContainer { + constructor(id: number, element: any, layer: number, notificationLimit?: number); + Clear(): void; + GetCount(): number; + SetEventHandler(eventId: SPNotifications.EventID, eventHandler: any): void; + } } + export class Status { static addStatus(strTitle: string, strHtml: string, atBegining: boolean): string; static appendStatus(sid: string, strTitle: string, strHtml: string): string; @@ -6994,9 +7249,10 @@ declare module SP { static removeAllStatus(hide: boolean): void; constructor(); } - export class Workspace { - static add_resized(handler: () => void): void; - static remove_resized(handler: () => void): void; + + export module Workspace { + export function add_resized(handler: () => void): void; + export function remove_resized(handler: () => void): void; } export class Menu { static create(id: string): SP.UI.Menu; @@ -7139,9 +7395,122 @@ declare module SP { close(dialogResult: SP.UI.DialogResult): void; } + + export class Command { + constructor(name: string, displayName: string); + get_displayName(): string; + set_displayName(value: string): string; + + get_tooltip(): string; + set_tooltip(value: string): string; + + get_isEnabled(): boolean; + set_isEnabled(value: boolean): boolean; + + get_href(): string; + get_name(): string; + get_elementIDPrefix(): string; + set_elementIDPrefix(value: string): string; + + get_linkElement():HTMLAnchorElement; + + get_isDropDownCommand(): boolean; + set_isDropDownCommand(value: boolean): boolean; + + attachEvents(): void; + render(builder: HtmlBuilder): void; + + + /**Should override*/ + onClick(): void; + + } + + + export class CommandBar { + constructor(); + get_commands():Command[]; + get_dropDownThreshold(): number; + set_dropDownThreshold(value: number): number; + get_elementID(): string; + get_overrideClass(): string; + set_overrideClass(value: string): string; + addCommand(action:Command):void; + insertCommand(action: Command, position:number): void; + render(builder: HtmlBuilder): void; + attachEvents(): void; + findCommandByName(name:string):Command; + } + + + export class PagingControl { + constructor(id: string); + render(innerContent:string): string; + postRender():void; + get_innerContent():HTMLSpanElement; + get_innerContentClass():string; + setButtonState(buttonId:number, state:number):void; + getButtonState(buttonId: number): number; + onWindowResized(): void; + + /**Should override*/ + onPrev(): void; + onNext(): void; + + static ButtonIDs: { + prev: number; + next: number; + } + + static ButtonState: { + hidden: number + disabled: number; + enabled: number; + } + } + + export module UIUtility { + export function generateRandomElementId(): string; + export function cancelEvent(evt: Event): void; + export function clearChildNodes(elem: HTMLElement): void; + export function hideElement(elem: HTMLElement): void; + export function showElement(elem: HTMLElement): void; + export function insertBefore(elem: HTMLElement, targetElement: HTMLElement): void; + export function insertAfter(elem: HTMLElement, targetElement: HTMLElement): void; + export function removeNode(elem: HTMLElement): void; + export function calculateOffsetLeft(elem: HTMLElement): number; + export function calculateOffsetTop(elem: HTMLElement): number; + export function createHtmlInputText(text: string): HTMLInputElement; + export function createHtmlInputCheck(isChecked: boolean): HTMLInputElement; + export function setInnerText(elem: HTMLElement, value: string): void; + export function getInnerText(elem: HTMLElement): string; + export function isTextNode(elem: HTMLElement): boolean; + export function isSvgNode(elem: HTMLElement): boolean; + export function isNodeOfType(elem: HTMLElement, tagNames: string[]): boolean; + export function focusValidOnThisNode(elem: HTMLElement): boolean; + } } } +declare module SPNotifications { + + export enum ContainerID { + Basic, + Status, + } + export enum EventID { + OnShow, + OnHide, + OnDisplayNotification, + OnRemoveNotification, + OnNotificationCountChanged, + } +} + +declare class SPStatusNotificationData { + constructor(text: string, subText: string, imageUrl: string, sip: string); +} + declare module SP { export module UI { export module Controls { @@ -7804,8 +8173,20 @@ declare module SP { /** Same as get_url() */ toString(): string; } - } + export class LocUtility { + static getLocalizedCountValue(locText:string, intervals:string, count:number):string; + } + + export class VersionUtility { + static get_layoutsLatestVersionRelativeUrl():string; + static get_layoutsLatestVersionUrl(): string; + static getLayoutsPageUrl(pageName:string): string; + static getImageUrl(imageName:string): string; + } + + } + export module DateTimeUtil { export class SimpleDate { construction(year: number, month: number, day: number, era: number); @@ -8684,12 +9065,338 @@ declare module SP { } } } -declare class SPClientAutoFill { - static MenuOptionType: { + +declare module SP { + export module CompliancePolicy { + export enum SPContainerType { + site,//: 0, + web,//: 1, + list//: 2 + } + + export class SPContainerId extends ClientObject { + constructor(context: ClientRuntimeContext, objectPath: ObjectPath); + static createFromList(context: ClientRuntimeContext, list: List): SPContainerId; + static createFromWeb(context: ClientRuntimeContext, web: Web): SPContainerId; + static createFromSite(context: ClientRuntimeContext, site: Site): SPContainerId; + static create(context: ClientRuntimeContext, containerId): SPContainerId; + + get_containerType(): ContentType; + set_containerType(value: ContentType): ContentType; + + get_listId(): SP.Guid; + set_listId(value: SP.Guid): SP.Guid; + + get_siteId(): SP.Guid; + set_siteId(value: SP.Guid): SP.Guid; + + get_siteUrl(): string; + set_siteUrl(value: string): string; + + get_tenantId(): SP.Guid; + set_tenantId(value: SP.Guid): SP.Guid; + + get_title(): string; + set_title(value: string): string; + + get_version(): any; + set_version(value: any): any; + + get_webId(): SP.Guid; + set_webId(value: SP.Guid): SP.Guid; + + serialize(): SP.StringResult; + } + + export class SPPolicyAssociation extends ClientObject { + constructor(context: ClientRuntimeContext, objectPath: ObjectPath); + + get_allowOverride(): boolean; + set_allowOverride(value: boolean): boolean; + + get_comment(): string; + set_comment(value: string): string; + + get_defaultPolicyDefinitionConfigId(): any[]; + set_defaultPolicyDefinitionConfigId(value: any[]): any[]; + + get_description(): string; + set_description(value: string): string; + + get_identity(): boolean; + set_identity(value: boolean): boolean; + + get_name(): string; + set_name(value: string): string; + + get_policyApplyStatus(): any; + set_policyApplyStatus(value: any): any; + + get_policyDefinitionConfigIds(): any[]; + set_policyDefinitionConfigIds(value: any[]): any[]; + + get_scope(): any; + set_scope(value: any): any; + + get_source(): any; + set_source(value: any): any; + + get_version(): any; + set_version(value: any): any; + + get_whenAppliedUTC(): Date; + set_whenAppliedUTC(value: Date): Date; + + get_whenChangedUTC(): Date; + set_whenChangedUTC(value: Date): Date; + + get_whenCreatedUTC(): Date; + set_whenCreatedUTC(value: Date): Date; + } + + export class SPPolicyBinding extends ClientObject { + constructor(context: ClientRuntimeContext, objectPath: ObjectPath); + + get_identity(): any; + set_identity(value: any): any; + + get_isExempt(): boolean; + set_isExempt(value: boolean): boolean; + + get_mode(): any; + set_mode(value: any): any; + + get_name(): string; + set_name(value: string): string; + + get_policyApplyStatus(): any; + set_policyApplyStatus(value: any): any; + + get_policyAssociationConfigId(): any; + set_policyAssociationConfigId(value: any): any; + + get_policyDefinitionConfigId(): any; + set_policyDefinitionConfigId(value: any): any; + + get_policyRuleConfigId(): any; + set_policyRuleConfigId(value: any): any; + + get_scope(): any; + set_scope(value: any): any; + + get_source(): any; + set_source(value: any): any; + + get_version(): any; + set_version(value: any): any; + + get_whenAppliedUTC(): Date; + set_whenAppliedUTC(value: Date): Date; + + get_whenChangedUTC(): Date; + set_whenChangedUTC(value: Date): Date; + + get_whenCreatedUTC(): Date; + set_whenCreatedUTC(value: Date): Date; + } + + export class SPPolicyDefinition extends ClientObject { + constructor(context: ClientRuntimeContext, objectPath: ObjectPath); + + get_comment(): string; + set_comment(value: string): string; + + get_createdBy(): any; + set_createdBy(value: any): any; + + get_defaultPolicyRuleConfigId + set_defaultPolicyRuleConfigId + + get_description(): string; + set_description(value: string): string; + + get_enabled(): boolean; + set_enabled(value: boolean): boolean; + + get_identity(): any; + set_identity(value: any): any; + + get_lastModifiedBy(): any; + set_lastModifiedBy(value: any): any; + + get_name(): string; + set_name(value: string): string; + + get_mode(): any; + set_mode(value: any): any; + + get_scenario(): any; + set_scenario(value: any): any; + + get_source(): any; + set_source(value: any): any; + + get_version(): any; + set_version(value: any): any; + + get_whenChangedUTC(): Date; + set_whenChangedUTC(value: Date): Date; + + get_whenCreatedUTC(): Date; + set_whenCreatedUTC(value: Date): Date; + + + } + + export class SPPolicyRule extends ClientObject { + constructor(context: ClientRuntimeContext, objectPath: ObjectPath); + + get_comment(): string; + set_comment(value: string): string; + + get_createdBy(): any; + set_createdBy(value: any): any; + + get_description(): string; + set_description(value: string): string; + + get_enabled(): boolean; + set_enabled(value: boolean): boolean; + get_identity(): any; + set_identity(value: any): any; + + get_lastModifiedBy(): any; + set_lastModifiedBy(value: any): any; + + get_mode(): any; + set_mode(value: any): any; + + get_name(): string; + set_name(value: string): string; + + get_policyDefinitionConfigId(): any; + set_policyDefinitionConfigId(value: any): any; + + get_priority(): any; + set_priority(value: any): any; + + get_ruleBlob(): any; + set_ruleBlob(value: any): any; + + get_whenChangedUTC(): Date; + set_whenChangedUTC(value: Date): Date; + + get_whenCreatedUTC(): Date; + set_whenCreatedUTC(value: Date): Date; + } + + export class SPPolicyStore extends ClientObject { + constructor(context: ClientRuntimeContext, web: Web); + + static createPolicyDefinition(context: ClientRuntimeContext): SPPolicyDefinition; + static createPolicyBinding(context: ClientRuntimeContext):SPPolicyBinding; + static createPolicyAssociation(context: ClientRuntimeContext):SPPolicyAssociation; + static createPolicyRule(context: ClientRuntimeContext): SPPolicyRule; + + + updatePolicyRule(policyRule:SPPolicyRule):void; + + getPolicyRule(policyRuleId:any, throwIfNull:boolean):SPPolicyRule; + + deletePolicyRule(policyRuleId: any);void; + + notifyUnifiedPolicySync(notificationId, syncSvcUrl:string, changeInfos, syncNow:boolean, fullSyncForTenant):void; + + updatePolicyDefinition(policyDefinition:SPPolicyDefinition):void; + + getPolicyDefinition(policyDefinitionId):SPPolicyDefinition; + + deletePolicyDefinition(policyDefinitionId):void; + + getPolicyDefinitions(scenario): ClientObjectList; + + updatePolicyBinding(policyBinding:SPPolicyBinding):void; + + getPolicyBinding(policyBindingId): SPPolicyBinding; + + deletePolicyBinding(policyBindingId): void; + + updatePolicyAssociation(policyAssociation: SPPolicyAssociation): void; + + getPolicyAssociation(policyAssociationId): SPPolicyAssociation; + + getPolicyAssociationForContainer(containerId: SPContainerId): SPPolicyAssociation; + + deletePolicyAssociation(policyAssociationId): void; + } + + export class SPPolicyStoreProxy extends ClientObject { + constructor(context: ClientRuntimeContext, web: Web); + + get_policyStoreUrl(): string; + } + + } + + export module Discovery { + + export enum ExportStatus { + notStarted,//: 0, + started,//: 1, + complete,//: 2, + failed//: 3 + } + + export class Case extends ClientObject { + constructor(context: ClientRuntimeContext, web: Web); + getExportContent(sourceIds: number[]): SP.StringResult; + } + export class Export extends ClientObject { + constructor(context: ClientRuntimeContext, item: ListItem); + get_status(): ExportStatus; + set_status(value: ExportStatus): ExportStatus; + update(): void; + getExportContent(): SP.StringResult; + } + } + + export module InformationPolicy { + export class ProjectPolicy extends SP.ClientObject { + constructor(context: ClientRuntimeContext, objectPath: ObjectPath); + get_description(): string; + + get_emailBody(): string; + set_emailBody(value: string): string; + + get_emailBodyWithTeamMailbox(): string; + set_emailBodyWithTeamMailbox(value: string): string; + + get_emailSubject(): string; + set_emailSubject(value: string): string; + + get_name(): string; + savePolicy(): void; + + + static getProjectPolicies(context: ClientRuntimeContext, web: Web): ClientObjectList; + static getCurrentlyAppliedProject(context: ClientRuntimeContext, web: Web): ProjectPolicy; + static applyProjectPolicy(context: ClientRuntimeContext, web: Web, projectPolicy: ProjectPolicy): void; + static openProject(context: ClientRuntimeContext, web: Web): void; + static closeProject(context: ClientRuntimeContext, web: Web): void; + static postponeProject(context: ClientRuntimeContext, web: Web): void; + static doesProjectHavePolicy(context: ClientRuntimeContext, web: Web): SP.BooleanResult; + static isProjectClosed(context: ClientRuntimeContext, web: Web): SP.BooleanResult; + static getProjectCloseDate(context: ClientRuntimeContext, web: Web): SP.DateTimeResult; + static getProjectExpirationDate(context: ClientRuntimeContext, web: Web): SP.DateTimeResult; + } + } +} +declare class SPClientAutoFill{ + static MenuOptionType : { Option: number; Footer: number; Separator: number; - Loading: number; + Loading:number; } static KeyProperty: string; //= 'AutoFillKey'; @@ -8702,7 +9409,7 @@ declare class SPClientAutoFill { static GetAutoFillObjFromContainer(elmChild: HTMLElement): SPClientAutoFill; static GetAutoFillMenuItemFromOption(elmChild: HTMLElement): HTMLElement; - constructor(elmTextId: string, elmContainerId: string, fnPopulateAutoFill: (targetElement: HTMLInputElement) => void); + constructor(elmTextId: string, elmContainerId: string, fnPopulateAutoFill: (targetElement: HTMLInputElement) => void ); public TextElementId: string; public AutoFillContainerId: string; public AutoFillMenuId: string; @@ -8713,16 +9420,16 @@ declare class SPClientAutoFill { public AutoFillCallbackTimeoutID: string; public FuncOnAutoFillClose: (elmTextId: string, ojData: ISPClientAutoFillData) => void; public FuncPopulateAutoFill: (targetElement: HTMLElement) => void; - public AllOptionData: { [key: string]: ISPClientAutoFillData }; + public AllOptionData: { [key:string]: ISPClientAutoFillData }; - PopulateAutoFill(jsonObjSuggestions: ISPClientAutoFillData[], fnOnAutoFillCloseFuncName: (elmTextId: string, objData: ISPClientAutoFillData) => void): void; + PopulateAutoFill(jsonObjSuggestions: ISPClientAutoFillData[], fnOnAutoFillCloseFuncName: (elmTextId: string, objData:ISPClientAutoFillData) => void ): void; IsAutoFillOpen(): boolean; SetAutoFillHeight(): void; - SelectAutoFillOption(elemOption: HTMLElement): void; - FocusAutoFill(): void; + SelectAutoFillOption(elemOption:HTMLElement): void; + FocusAutoFill() :void; BlurAutoFill(): void; CloseAutoFill(ojData: ISPClientAutoFillData): void; - UpdateAutoFillMenuFocus(bMoveNextLink: boolean): void; + UpdateAutoFillMenuFocus(bMoveNextLink:boolean): void; UpdateAutoFillPosition(): void; } @@ -8894,4 +9601,160 @@ declare module Microsoft { } } } +/** Available only in SharePoint Online*/ +declare module Define { + export function loadScript(url: string, successCallback: () => void, errCallback: () => void); + /** Loads script from _layouts/15/[req].js */ + export function require(req: string, callback: Function): void; + /** Loads script from _layouts/15/[req].js */ + export function require(req: string[], callback: Function): void; + export function define(name: string, deps: string[], def: Function): void; +} + +/** Available only in SharePoint Online*/ +declare module Verify { + export function ArgumentType(arg: string, expected: any); +} + + +/** Available only in SharePoint Online*/ +declare module BrowserStorage { + export var local: CachedStorage; + export var session: CachedStorage; + + /** Available only in SharePoint Online*/ + interface CachedStorage { + getItem(key: string): string; + setItem(key: string, value: string); + removeItem(key: string): void; + clead(): void; + length: number; + } +} + +/** Available only in SharePoint Online*/ +declare module BrowserDetection { + export var browseris: Browseris; +} + +/** Available only in SharePoint Online*/ +declare module CSSUtil { + export function HasClass(elem: HTMLElement, className: string): boolean; + export function AddClass(elem: HTMLElement, className: string): void; + export function RemoveClass(elem: HTMLElement, className: string): void; + export function pxToFloat(pxString: string): number; + export function pxToNum(px: string): number; + export function numToPx(n: number): string; + export function getCurrentEltStyleByNames(elem: HTMLElement, styleNames: string[]): string; + export function getCurrentStyle(elem: HTMLElement, cssStyle: string): string; + export function getCurrentStyleCorrect(element: HTMLElement, camelStyleName: string, dashStyleName: string): string; + export function getOpacity(element: HTMLElement): number; + export function setOpacity(element: HTMLElement, value: number): void; +} + +/** Available only in SharePoint Online*/ +declare module DOM { + export var rightToLeft: boolean; + export function cancelDefault(evt: Event): void; + export function AbsLeft(el: HTMLElement): number; + export function AbsTop(el: HTMLElement): number; + export function CancelEvent(evt: Event): void; + export function GetElementsByName(nae: string): NodeList; + export function GetEventCoords(evt: Event): { x: number; y: number; }; + export function GetEventSrcElement(evt: Event): HTMLElement; + export function GetInnerText(el: HTMLElement): string; + export function PreventDefaultNavigation(evt: Event): void; + export function SetEvent(eventName: string, eventFunc: Function, el: HTMLElement); +} + +/** Available only in SharePoint Online*/ +declare module Encoding { + export function EncodeScriptQuote(str: string): string; + export function HtmlEncode(str: string): string; + export function HtmlDecode(str: string): string; + export function AttrQuote(str: string): string; + export function ScriptEncode(str: string): string; + export function ScriptEncodeWithQuote(str: string): string; + export function CanonicalizeUrlEncodingCase(str: string): string; +} + +/** Available only in SharePoint Online*/ +declare module IE8Support { + export function arrayIndexOf(array: T[], item: T, startIdx?: number): number; + export function attachDOMContentLoaded(handler: Function): void; + export function getComputedStyle(domObj: HTMLElement, camelStyleName: string, dashStyleName: string): string; + export function stopPropagation(evt: Event): void; +} + +/** Available only in SharePoint Online*/ +declare module StringUtil { + export function BuildParam(stPattern: string, ...params: any[]); + export function ApplyStringTemplate(str: string, ...params: any[]); +} + +/** Available only in SharePoint Online*/ +declare module TypeUtil { + export function IsArray(value: any): boolean; + export function IsNullOrUndefined(value: any): boolean; +} + +/** Available only in SharePoint Online*/ +declare module Nav { + export var ajaxNavigate: AjaxNavigate; + export function convertRegularURLtoMDSURL(webUrl: string, fullPath: string): string; + export function isMDSUrl(url: string): boolean; + export function isPageUrlValid(url: string): boolean; + export function isPortalTemplatePage(url: string): boolean; + export function getAjaxLocationWindow(): string; + export function getSource(defaultSource?: string): string; + export function getUrlKeyValue(keyName: string, bNoDecode: boolean, url: string, bCaseInsensitive: boolean): string; + export function getWindowLocationNoHash(hre: string): string; + export function goToHistoryLink(el: HTMLAnchorElement, strVersion: string): void; + export function getGoToLinkUrl(el: HTMLAnchorElement): string; + export function goToLink(el: HTMLAnchorElement): void; + export function goToLinkOrDialogNewWindow(el: HTMLAnchorElement): void; + export function goToDiscussion(url: string): void; + export function onClickHook(evt: Event, topElm: HTMLElement): void; + export function pageUrlValidation(url: string, alertString: string): string; + export function parseHash(hash: string): Object; + export function navigate(url: string): void; + export function removeMDSQueryParametersFromUrl(url: string): string; + export function urlFromHashBag(hashObject: Object): string; + export function wantsNewTab(evt: Event): boolean; +} + +/** Available only in SharePoint Online*/ +declare module URI_Encoding { + export function encodeURIComponent(str: string, bAsUrl?: boolean, bForFilterQuery?: boolean, bForCallback?: boolean): string; + export function escapeUrlForCallback(str: string): string; +} + +interface IListItem { + ID: number; + ContentTypeId: string; +} + +/** Available only in SharePoint Online*/ +declare module ListModule { + export module Util { + export function createViewEditUrl(renderCtx: SPClientTemplates.RenderContext, listItem: IListItem, useEditFormUrl?: boolean, appendSource?: boolean): string; + export function createItemPropertiesTitle(renderCtx: SPClientTemplates.RenderContext, listItem: IListItem): string; + export function clearSelectedItemsDict(context: any): void; + export function ctxInitItemState(context: any): void; + export function getAttributeFromItemTable(itemTableParam: HTMLElement, strAttributeName: string, strAttributeOldName: string): string + export function getSelectedItemsDict(context: any): any; + export function removeOnlyPagingArgs(url: string): string; + export function removePagingArgs(url: string): string; + export function showAttachmentRows(): void; + } +} + +/** Available only in SharePoint Online*/ +declare module SPThemeUtils { + export function ApplyCurrentTheme(): void; + export function WithCurrentTheme(resultCallback: Function): void; + export function UseClientSideTheming(): boolean; + export function Suspend(): void; +} + diff --git a/should/should.d.ts b/should/should.d.ts index 13eca9ccfb..8b4c21fc1e 100644 --- a/should/should.d.ts +++ b/should/should.d.ts @@ -1,6 +1,6 @@ // Type definitions for should.js 3.1.2 // Project: https://github.com/visionmedia/should.js -// Definitions by: Alex Varju and Maxime LUCE (1.3+) +// Definitions by: Alex Varju , Maxime LUCE // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Object { diff --git a/siesta/siesta.d.ts b/siesta/siesta.d.ts index f09f3f1274..c9810973af 100644 --- a/siesta/siesta.d.ts +++ b/siesta/siesta.d.ts @@ -256,7 +256,7 @@ declare module Siesta { target?: any; - el?: typeof target; + el?: any; } } diff --git a/signalr/signalr.d.ts b/signalr/signalr.d.ts index 6519f70518..2c6b0f2668 100644 --- a/signalr/signalr.d.ts +++ b/signalr/signalr.d.ts @@ -1,7 +1,6 @@ // Type definitions for SignalR 1.0 // Project: http://www.asp.net/signalr -// Definitions by: Boris Yankov -// Modified by: T. Michael Keesey +// Definitions by: Boris Yankov , T. Michael Keesey // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/sinon-chai/sinon-chai.d.ts b/sinon-chai/sinon-chai.d.ts index fefeb1af67..f8166d4d6c 100644 --- a/sinon-chai/sinon-chai.d.ts +++ b/sinon-chai/sinon-chai.d.ts @@ -1,7 +1,7 @@ // Type definitions for sinon-chai 2.4.0 // Project: https://github.com/domenic/sinon-chai // Definitions by: Kazi Manzur Rashid -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// diff --git a/sinon-chai/sinon-chai.d.ts.tscparams b/sinon-chai/sinon-chai.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/sinon-chai/sinon-chai.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/sinon/sinon.d.ts b/sinon/sinon.d.ts index eb62a286e3..4b86566619 100644 --- a/sinon/sinon.d.ts +++ b/sinon/sinon.d.ts @@ -1,7 +1,7 @@ // Type definitions for Sinon 1.8.1 // Project: http://sinonjs.org/ // Definitions by: William Sears -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped interface SinonSpyCallApi { // Properties @@ -101,6 +101,10 @@ interface SinonStub extends SinonSpy { callsArgOnAsync(index: number, context: any): SinonStub; callsArgWithAsync(index: number, ...args: any[]): SinonStub; callsArgOnWithAsync(index: number, context: any, ...args: any[]): SinonStub; + onCall(n: number): SinonStub; + onFirstCall(): SinonStub; + onSecondCall(): SinonStub; + onThirdCall(): SinonStub; yields(...args: any[]): SinonStub; yieldsOn(context: any, ...args: any[]): SinonStub; yieldsTo(property: string, ...args: any[]): SinonStub; diff --git a/slickgrid/SlickGrid-tests.ts b/slickgrid/SlickGrid-tests.ts index 1b41d1a0b3..e267a85948 100644 --- a/slickgrid/SlickGrid-tests.ts +++ b/slickgrid/SlickGrid-tests.ts @@ -47,7 +47,7 @@ grid.getDataItem(14).title; grid.setData([{ title: "task", duration: "5 days", percentComplete: 5, start: "01/01/2013", finish: "12/12/2013", effortDriven: false }], true); -var ids = []; +var ids: string[] = []; for (i = 0; i < grid.getDataLength(); i++) { ids.push(grid.getDataItem(i).title); } @@ -82,7 +82,7 @@ class SingleCellSelectionModel extends Slick.SelectionModel(); +var gridWithDataView = new Slick.Grid('#grid2', dataView, columns, options); +dataView.getIdxById('foo') + 5; + +columns.forEach(column => { + if (column.editor !== Slick.Editors.Integer) { + return; + } +}); + +grid.onSort.subscribe((e, args) => { + var sortCol:string = args.sortCols[0].sortCol.field; +}); diff --git a/slickgrid/SlickGrid-tests.ts.tscparams b/slickgrid/SlickGrid-tests.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/slickgrid/SlickGrid-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/slickgrid/SlickGrid.d.ts b/slickgrid/SlickGrid.d.ts index b7810f4671..d8a365d940 100644 --- a/slickgrid/SlickGrid.d.ts +++ b/slickgrid/SlickGrid.d.ts @@ -424,7 +424,7 @@ declare module Slick { /** * The editor for cell edits {TextEditor, IntegerEditor, DateEditor...} See slick.editors.js **/ - editor?: Editors.Editor; + editor?: any; // typeof Editors.Editor; /** * The property name in the data object to pull content from. (This is assumed to be on the root of the data object.) @@ -689,8 +689,8 @@ declare module Slick { topPanelHeight?: number; } - export interface DataProvider { - getItem(index: number): SlickData; + export interface DataProvider { + getItem(index: number): T; getLength(): number; } @@ -705,7 +705,7 @@ declare module Slick { * The grid also provides two helper methods to simplify development - getSelectedRows() and setSelectedRows(rowsArray), as well as an onSelectedRowsChanged event. * SlickGrid includes two pre-made selection models - Slick.CellSelectionModel and Slick.RowSelectionModel, but you can easily write a custom one. **/ - export class SelectionModel { + export class SelectionModel { /** * An initializer function that will be called with an instance of the grid whenever a selection model is registered with setSelectionModel. The selection model can use this to initialize its state and subscribe to grid events. **/ @@ -740,12 +740,12 @@ declare module Slick { options: GridOptions); constructor( container: string, - data: DataProvider, + data: DataProvider, columns: Column[], options: GridOptions); constructor( container: HTMLElement, - data: DataProvider, + data: DataProvider, columns: Column[], options: GridOptions); @@ -779,11 +779,18 @@ declare module Slick { /** * Sets a new source for databinding and removes all rendered rows. Note that this doesn't render the new rows - you can follow it with a call to render() to do that. - * @param newData New databinding source. This can either be a regular JavaScript array or a custom object exposing getItem(index) and getLength() functions. + * @param newData New databinding source using a regular JavaScript array.. * @param scrollToTop If true, the grid will reset the vertical scroll position to the top of the grid. **/ public setData(newData: T[], scrollToTop: boolean): void; + /** + * Sets a new source for databinding and removes all rendered rows. Note that this doesn't render the new rows - you can follow it with a call to render() to do that. + * @param newData New databinding source using a custom object exposing getItem(index) and getLength() functions. + * @param scrollToTop If true, the grid will reset the vertical scroll position to the top of the grid. + **/ + public setData(newData: DataProvider, scrollToTop: boolean): void; + /** * Returns the size of the databinding source. * @return @@ -1326,7 +1333,7 @@ declare module Slick { // todo: merge with existing column definition export interface Column { - sortCol?: string; + sortCol?: Column; sortAsc?: boolean; } @@ -1478,7 +1485,7 @@ declare module Slick { * Item -> Data by index * Row -> Data by row **/ - export class DataView implements DataProvider { + export class DataView implements DataProvider { constructor(options?: DataViewOptions); @@ -1532,7 +1539,7 @@ declare module Slick { */ public expandGroup(...varArgs: string[]): void; public getGroups(): Group[]; - public getIdxById(): string; + public getIdxById(id: string): number; public getRowById(): T; public getItemById(id: any): T; public getItemByIdx(): T; @@ -1548,7 +1555,7 @@ declare module Slick { public syncGridCellCssStyles(grid: Grid, key: string): void; public getLength(): number; - public getItem(index: number): SlickData; + public getItem(index: number): T; public getItemMetadata(): void; public onRowCountChanged: Slick.Event; diff --git a/slickgrid/slick.headerbuttons.d.ts b/slickgrid/slick.headerbuttons.d.ts index ab160ea836..613203f438 100644 --- a/slickgrid/slick.headerbuttons.d.ts +++ b/slickgrid/slick.headerbuttons.d.ts @@ -8,7 +8,7 @@ declare module Slick { export interface Column { - header: Header; + header?: Header; } export interface Header { diff --git a/smoothie/smoothie.d.ts b/smoothie/smoothie.d.ts index aae781d51d..18f0cc0a56 100644 --- a/smoothie/smoothie.d.ts +++ b/smoothie/smoothie.d.ts @@ -1,7 +1,6 @@ // Type definitions for Smoothie Charts 1.21 // Project: https://github.com/joewalnes/smoothie -// Definitions by: Drew Noakes -// Mike H. Hawley +// Definitions by: Drew Noakes , Mike H. Hawley // Definitions: https://github.com/borisyankov/DefinitelyTyped/smoothie // NOTE this reference is here to make the DefinitelyTyped `npm test` suite pass and diff --git a/sockjs-node/sockjs-node-tests.ts b/sockjs-node/sockjs-node-tests.ts new file mode 100644 index 0000000000..25e5b496af --- /dev/null +++ b/sockjs-node/sockjs-node-tests.ts @@ -0,0 +1,44 @@ +/// +import sockjs = require("sockjs"); +import http = require("http"); +import stream = require("stream"); + +var server: sockjs.Server, + serverOptions: sockjs.ServerOptions = {}; + +// createServer method +server = sockjs.createServer(); +server = sockjs.createServer(serverOptions); + +// installHandlers method +var httpServer: http.Server = http.createServer(); +server.installHandlers(httpServer); +server.installHandlers(httpServer, serverOptions); + +// serverOptions +serverOptions.sockjs_url = 'http://cdn.sockjs.org/sockjs-0.3.min.js'; +serverOptions.prefix = '/prefix'; +serverOptions.response_limit = 128000; +serverOptions.websocket = true; + +serverOptions.jsessionid = true; +serverOptions.jsessionid = () => true; + +serverOptions.log = (severity, message) => { }; +serverOptions.heartbeat_delay = 25000; +serverOptions.disconnect_delay = 5000; + +// Connection +var connection: sockjs.Connection; + +// on('connection') passes a sockJS connection +server.on('connection', (conn) => { + connection = conn; + conn = connection; +}); + +// connection is a ReadWriteStream +var connectionAsReadWrite: NodeJS.ReadWriteStream = connection; + +connection.on('data', (message: string) => { }); +connection.on('close', () => { }); diff --git a/sockjs-node/sockjs-node.d.ts b/sockjs-node/sockjs-node.d.ts new file mode 100644 index 0000000000..e054fe2ebc --- /dev/null +++ b/sockjs-node/sockjs-node.d.ts @@ -0,0 +1,56 @@ +// Type definitions for sockjs-node 0.3.x +// Project: https://github.com/sockjs/sockjs-node +// Definitions by: Phil McCloghry-Laing +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "sockjs" { + import http = require('http'); + + export interface ServerOptions { + sockjs_url?: string; + prefix?: string; + response_limit?: number; + websocket?: boolean; + jsessionid?: any; + log?: (severity: string, message: string) => void; + heartbeat_delay?: number; + disconnect_delay?: number; + } + + export function createServer(options?: ServerOptions): Server; + + export interface Server extends NodeJS.EventEmitter { + installHandlers(server: http.Server, options?: ServerOptions): any; + + on(event: 'connection', listener: (conn: Connection) => any): Server; + on(event: string, listener: Function): Server; + } + + export interface Connection extends NodeJS.ReadWriteStream { + remoteAddress: string; + remotePort: number; + address: { + [key: string]: { + address: string; + port: number; + }; + }; + headers: { + [key: string]: string; + }; + url: string; + pathname: string; + prefix: string; + protocol: string; + readyState: number; + + close(code?: string, reason?: string): boolean; + destroy(): void; + + on(event: 'data', listener: (message: string) => any): Connection; + on(event: 'close', listener: () => void): Connection; + on(event: string, listener: Function): Connection; + } +} diff --git a/sockjs/sockjs.d.ts b/sockjs/sockjs.d.ts index 7a4316ad6f..3f823a5eeb 100644 --- a/sockjs/sockjs.d.ts +++ b/sockjs/sockjs.d.ts @@ -1,7 +1,7 @@ // Type definitions for SockJS 0.3.x // Project: https://github.com/sockjs/sockjs-client // Definitions by: Emil Ivanov -// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped interface SockJSSimpleEvent { type: string; @@ -36,10 +36,17 @@ interface SockJS extends EventTarget { declare var SockJS: { prototype: SockJS; - new (url: string, options?: { - debug: boolean; - devel: boolean; - protocols_whitelist: string[]; - }): SockJS; - -} \ No newline at end of file + new (url: string, _reserved: any, options?: { + debug?: boolean; + devel?: boolean; + protocols_whitelist?: string[]; + server?: string; + rtt?: number; + rto?: number; + info?: { + websocket?: boolean; + cookie_needed?: boolean; + null_origin?: boolean; + }; + }): SockJS; +}; \ No newline at end of file diff --git a/source-map-support/source-map-support-tests.ts b/source-map-support/source-map-support-tests.ts index ddd6308cc2..09a4fff459 100644 --- a/source-map-support/source-map-support-tests.ts +++ b/source-map-support/source-map-support-tests.ts @@ -3,3 +3,39 @@ import sms = require('source-map-support'); sms.install(); + +function retrieveFile(path: string): string { + return "foo"; +} + +function retrieveSourceMap(source: string): sms.UrlAndMap { + return { + url: "http://foo", + map: "foo" + }; +} + +var options: sms.Options = { + emptyCacheBetweenOperations: false, + handleUncaughtExceptions: false, + retrieveFile: retrieveFile, + retrieveSourceMap: retrieveSourceMap +}; + +sms.install(options); + +var stackFrame: any; // TODO: this should be a StackFrame, but it seems this would need to be defined elsewhere (in e.g. lib.d.ts) +stackFrame = sms.wrapCallSite(stackFrame); + +var s: string; +s = sms.getErrorSource(new Error("foo")); + +var p: sms.Position = { + column: 0, + line: 0, + source: "foo" +}; +p = sms.mapSourcePosition(p); + +var u: sms.UrlAndMap; +u = retrieveSourceMap("foo"); diff --git a/source-map-support/source-map-support.d.ts b/source-map-support/source-map-support.d.ts index 8d4e225796..b0de346a7b 100644 --- a/source-map-support/source-map-support.d.ts +++ b/source-map-support/source-map-support.d.ts @@ -1,8 +1,41 @@ -// Type definitions for source-map-support 0.2.5 +// Type definitions for source-map-support 0.2.6 // Project: https://github.com/evanw/source-map-support // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module 'source-map-support' { - export function install(): any; + /** + * Output of retrieveSourceMap(). + */ + export interface UrlAndMap { + url: string; + map: any; // string or Buffer + } + + /** + * Options to install(). + */ + export interface Options { + handleUncaughtExceptions?: boolean; + emptyCacheBetweenOperations?: boolean; + retrieveFile?: (path: string) => string; + retrieveSourceMap?: (source: string) => UrlAndMap; + } + + export interface Position { + source: string; + line: number; + column: number; + } + + export function wrapCallSite(frame: any /* StackFrame */): any /* StackFrame */; + export function getErrorSource(error: Error): string; + export function mapSourcePosition(position: Position): Position; + export function retrieveSourceMap(source: string): UrlAndMap; + + /** + * Install SourceMap support. + * @param options Can be used to e.g. disable uncaughtException handler. + */ + export function install(options?: Options): void; } diff --git a/space-pen/space-pen.d.ts b/space-pen/space-pen.d.ts index 64d0321557..eb884e289a 100644 --- a/space-pen/space-pen.d.ts +++ b/space-pen/space-pen.d.ts @@ -1,3 +1,8 @@ +// Type definitions for SpacePen +// Project: https://github.com/atom/space-pen +// Definitions by: vvakame +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /// // http://atom.github.io/space-pen/ @@ -60,7 +65,7 @@ declare class View /* implements JQuery */ { static popBuilder():Builder; - static buildHtml(fn:()=>void):any[]; + static buildHtml(fn:()=>void):string[]; static render(fn:()=>void):JQuery; @@ -343,7 +348,7 @@ declare module "space-pen" { static popBuilder():Builder; - static buildHtml(fn:()=>void):any[]; + static buildHtml(fn:()=>void):string[]; static render(fn:()=>void):JQuery; @@ -581,7 +586,11 @@ declare module "space-pen" { end():any; - command(commandName:any, selector:any, options:any, handler:any):any; + command(eventName:string, handler:any):any; + + command(eventName:string, selector:any, handler:any):any; + + command(eventName:string, selector:any, options:any, handler:any):any; preempt(eventName:any, handler:any):any; } diff --git a/spin/spin.d.ts b/spin/spin.d.ts index c7ceac2b6f..02a0e7cd21 100644 --- a/spin/spin.d.ts +++ b/spin/spin.d.ts @@ -1,6 +1,6 @@ // Type definitions for Spin.js 1.3.1 // Project: http://fgnass.github.com/spin.js/ -// Definitions by: Boris Yankov and Theodore Brown +// Definitions by: Boris Yankov , Theodore Brown // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/sprintf/sprintf-tests.ts b/sprintf/sprintf-tests.ts new file mode 100644 index 0000000000..563fbebdd9 --- /dev/null +++ b/sprintf/sprintf-tests.ts @@ -0,0 +1,14 @@ +/// + +import sprintf = require('sprintf'); + +var str: string; +var num: number; + +sprintf.sprintf(str, str); +sprintf.sprintf(str, str, num); +sprintf.sprintf(str, num, str); + +sprintf.vsprintf(str, [str]); +sprintf.vsprintf(str, [str, num]); +sprintf.vsprintf(str, [num, str]); diff --git a/sprintf/sprintf.d.ts b/sprintf/sprintf.d.ts new file mode 100644 index 0000000000..547d93532f --- /dev/null +++ b/sprintf/sprintf.d.ts @@ -0,0 +1,11 @@ +// Type definitions for sprintff +// Project: https://github.com/maritz/node-sprintff +// Definitions by: Carlos Ballesteros Velasco +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/sprintff.d.ts + +declare module "sprintf" { + export function sprintf(fmt: string, ...args: any[]): string; + export function vsprintf(fmt: string, args: any[]): string; +} diff --git a/sqlite3/sqlite3-tests.ts b/sqlite3/sqlite3-tests.ts new file mode 100644 index 0000000000..7059a439af --- /dev/null +++ b/sqlite3/sqlite3-tests.ts @@ -0,0 +1,92 @@ +/// + +import sqlite3 = require('sqlite3'); +sqlite3.verbose(); + +var db: sqlite3.Database; + +function createDb() { + console.log("createDb chain"); + db = new sqlite3.Database('chain.sqlite3', createTable); +} + +function createTable() { + console.log("createTable lorem"); + db.run("CREATE TABLE IF NOT EXISTS lorem (info TEXT)", insertRows); +} + +function insertRows() { + console.log("insertRows Ipsum i"); + var stmt = db.prepare("INSERT INTO lorem VALUES (?)"); + + for (var i = 0; i < 10; i++) { + stmt.run("Ipsum " + i); + } + + stmt.finalize(readAllRows); +} + +function readAllRows() { + console.log("readAllRows lorem"); + db.all("SELECT rowid AS id, info FROM lorem", function(err, rows) { + rows.forEach(function (row) { + console.log(row.id + ": " + row.info); + }); + closeDb(); + }); +} + +function closeDb() { + console.log("closeDb"); + db.close(); +} + +function runChainExample() { + createDb(); +} + +runChainExample(); + +db.serialize(function() { + db.run("CREATE TABLE lorem (info TEXT)"); + + var stmt = db.prepare("INSERT INTO lorem VALUES (?)"); + for (var i = 0; i < 10; i++) { + stmt.run("Ipsum " + i); + } + stmt.finalize(); + + db.each("SELECT rowid AS id, info FROM lorem", function(err, row) { + console.log(row.id + ": " + row.info); + }); +}); + +db.serialize(function() { + // These two queries will run sequentially. + db.run("CREATE TABLE foo (num)"); + db.run("INSERT INTO foo VALUES (?)", 1, function() { + // These queries will run in parallel and the second query will probably + // fail because the table might not exist yet. + db.run("CREATE TABLE bar (num)"); + db.run("INSERT INTO bar VALUES (?)", 1); + }); +}); + +// Directly in the function arguments. +db.run("UPDATE tbl SET name = ? WHERE id = ?", "bar", 2); + +// As an array. +db.run("UPDATE tbl SET name = ? WHERE id = ?", [ "bar", 2 ]); + +// As an object with named parameters. +db.run("UPDATE tbl SET name = $name WHERE id = $id", { + $id: 2, + $name: "bar" +}); + +db.run("UPDATE tbl SET name = ?5 WHERE id = ?", { + 1: 2, + 5: "bar" +}); + +db.close(); diff --git a/sqlite3/sqlite3.d.ts b/sqlite3/sqlite3.d.ts new file mode 100644 index 0000000000..c2c77cad98 --- /dev/null +++ b/sqlite3/sqlite3.d.ts @@ -0,0 +1,81 @@ +// Type definitions for sqlite3 2.2.3 +// Project: https://github.com/mapbox/node-sqlite3 +// Definitions by: Nick Malaguti +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "sqlite3" { + import events = require("events"); + + export var OPEN_READONLY: number; + export var OPEN_READWRITE: number; + export var OPEN_CREATE: number; + + export var cached: { + Database(filename: string, callback?: (err: Error) => void): Database; + Database(filename: string, mode?: number, callback?: (err: Error) => void): Database; + }; + + export interface RunResult { + lastID: number; + changes: number; + } + + export class Statement { + public bind(callback?: (err: Error) => void): Statement; + public bind(...params: any[]): Statement; + + public reset(callback?: (err: Error) => void): Statement; + + public finalize(callback?: (err: Error) => void): Statement; + + public run(callback?: (err: Error) => void): Statement; + public run(...params: any[]): Statement; + + public get(callback?: (err: Error, row: any) => void): Statement; + public get(...params: any[]): Statement; + + public all(callback?: (err: Error, rows: any[]) => void): Statement; + public all(...params: any[]): Statement; + + public each(callback?: (err: Error, row: any) => void, complete?: (err: Error, count: number) => void): Statement; + public each(...params: any[]): Statement; + } + + export class Database extends events.EventEmitter { + constructor(filename: string, callback?: (err: Error) => void); + constructor(filename: string, mode?: number, callback?: (err: Error) => void); + + public close(callback?: (err: Error) => void): void; + + public run(sql: string, callback?: (err: Error) => void): Database; + public run(sql: string, ...params: any[]): Database; + + public get(sql: string, callback?: (err: Error, row: any) => void): Database; + public get(sql: string, ...params: any[]): Database; + + public all(sql: string, callback?: (err: Error, rows: any[]) => void): Database; + public all(sql: string, ...params: any[]): Database; + + public each(sql: string, callback?: (err: Error, row: any) => void, complete?: (err: Error, count: number) => void): Database; + public each(sql: string, ...params: any[]): Database; + + public exec(sql: string, callback?: (err: Error) => void): Database; + + public prepare(sql: string, callback?: (err: Error) => void): Statement; + public prepare(sql: string, ...params: any[]): Statement; + + public serialize(callback?: () => void): void; + public parallelize(callback?: () => void): void; + + public on(event: "trace", listener: (sql: string) => void): Database; + public on(event: "profile", listener: (sql: string, time: number) => void): Database; + public on(event: "error", listener: (err: Error) => void): Database; + public on(event: "open", listener: () => void): Database; + public on(event: "close", listener: () => void): Database; + public on(event: string, listener: Function): Database; + } + + function verbose(): void; +} diff --git a/state-machine/state-machine.d.ts b/state-machine/state-machine.d.ts index c5c9c83bfa..67f7012b1c 100644 --- a/state-machine/state-machine.d.ts +++ b/state-machine/state-machine.d.ts @@ -1,8 +1,6 @@ // Type definitions for Finite State Machine 2.2 // Project: https://github.com/jakesgordon/javascript-state-machine -// Definitions by: Boris Yankov -// Definitions by: Maarten Docter (2013/01/22) -// Definitions by: William Sears (2013/01/25) +// Definitions by: Boris Yankov , Maarten Docter , William Sears // Definitions: https://github.com/borisyankov/DefinitelyTyped interface StateMachineErrorCallback { diff --git a/status-bar/status-bar-tests.ts b/status-bar/status-bar-tests.ts new file mode 100644 index 0000000000..13e1941b66 --- /dev/null +++ b/status-bar/status-bar-tests.ts @@ -0,0 +1,8 @@ +/// + +declare var StatusBarView:StatusBar.IStatusBarViewStatic; + +StatusBarView.content(); + +var statusBar = new StatusBarView(); +statusBar.appendLeft(new View()); diff --git a/status-bar/status-bar.d.ts b/status-bar/status-bar.d.ts new file mode 100644 index 0000000000..6c67887205 --- /dev/null +++ b/status-bar/status-bar.d.ts @@ -0,0 +1,32 @@ +// Type definitions for status-bar +// Project: https://github.com/atom/status-bar +// Definitions by: vvakame +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module StatusBar { + interface IStatusBarViewStatic { + content():any; + + new(...args:any[]):IStatusBarView; + } + + interface IStatusBarView extends View { + + initialize():any; + attach():any; + destroy():any; + appendLeft(view:View):any; + prependLeft(view:View):any; + appendRight(view:View):any; + prependRight(view:View):any; + getActiveBuffer():TextBuffer.ITextBuffer; + getActiveItem():any; + storeActiveBuffer():TextBuffer.ITextBuffer; + subscribeToBuffer(event:string, callback:Function):any; + subscribeAllToBuffer():any[]; + unsubscribeAllFromBuffer():any[]; + } +} diff --git a/stream-to-array/stream-to-array-tests.ts b/stream-to-array/stream-to-array-tests.ts new file mode 100644 index 0000000000..a4803d051b --- /dev/null +++ b/stream-to-array/stream-to-array-tests.ts @@ -0,0 +1,10 @@ +/// +/// + +import toArray = require('stream-to-array'); + +var rs: NodeJS.ReadableStream; + +toArray(rs, (err, arr) => { + +}); diff --git a/stream-to-array/stream-to-array.d.ts b/stream-to-array/stream-to-array.d.ts new file mode 100644 index 0000000000..45239bbb15 --- /dev/null +++ b/stream-to-array/stream-to-array.d.ts @@ -0,0 +1,12 @@ +// Type definitions for stream-to-array +// Project: https://github.com/stream-utils/stream-to-array +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare module 'stream-to-array' { + function toArray(stream: NodeJS.ReadableStream, callback: (err: any, arr: any[]) => void): NodeJS.ReadWriteStream; + export = toArray; +} diff --git a/superagent/superagent.d.ts b/superagent/superagent.d.ts index 860f70ea35..9e6f9c4b5b 100644 --- a/superagent/superagent.d.ts +++ b/superagent/superagent.d.ts @@ -6,6 +6,7 @@ /// declare module "superagent" { + import stream = require('stream'); export interface Response { text: string; body: any; @@ -43,8 +44,8 @@ declare module "superagent" { send(data: string): Request; send(data: Object): Request; write(data: string, encoding: string): boolean; - write(data: NodeBuffer, encoding: string): boolean; - pipe(stream: WritableStream, options?: Object): WritableStream; + write(data: Buffer, encoding: string): boolean; + pipe(stream: NodeJS.WritableStream, options?: Object): stream.Writable; buffer(val: boolean): Request; timeout(ms: number): Request; clearTimeout(): Request; diff --git a/svgjs.draggable/svgjs.draggable.d.ts b/svgjs.draggable/svgjs.draggable.d.ts index 76837f58e0..8a64868c56 100644 --- a/svgjs.draggable/svgjs.draggable.d.ts +++ b/svgjs.draggable/svgjs.draggable.d.ts @@ -1,3 +1,9 @@ +// Type definitions for svgjs.draggable +// Project: http://www.svgjs.com/ +// Definitions by: Luigi Trabacchin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + declare module svgjs { export module draggable { export interface DragDelta { diff --git a/swig/swig-tests.ts b/swig/swig-tests.ts new file mode 100644 index 0000000000..1f68aa44cb --- /dev/null +++ b/swig/swig-tests.ts @@ -0,0 +1,25 @@ +/// + +import swig = require('swig'); + +var value: any; +var str: string; +var num: number; +var bool: boolean; + +var opts: swig.Options = { + allowErrors: bool, + autoescape: bool, + cache: bool, + encoding: str, + filters: value, + root: str, + tags: value, + extensions: value, + tzOffset: num +}; + +swig.init(opts); +value = swig.compileFile(str); +value = swig.compile(str); +value = swig.compile(str, opts); diff --git a/swig/swig.d.ts b/swig/swig.d.ts new file mode 100644 index 0000000000..4d8bc9ebe0 --- /dev/null +++ b/swig/swig.d.ts @@ -0,0 +1,27 @@ +// Type definitions for swig +// Project: http://github.com/paularmstrong/swig +// Definitions by: Carlos Ballesteros Velasco +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/swig.d.ts + +// API Documentation : http://paularmstrong.github.io/swig/docs/api/ + +declare module "swig" { + export function init(options: Options): void; + export function compileFile(filepath: string): any; + export function compile(source: string, options?: Options): any; + export function renderFile(pathName: string, locals?: any, cb?: (err: any, output: string) => void): string; + + export interface Options { + allowErrors?: boolean; + autoescape?: boolean; + cache?: boolean; + encoding?: string; + filters?: any; + root?: string; + tags?: any; + extensions?: any; + tzOffset?: number; + } +} diff --git a/swiz/swiz-tests.ts b/swiz/swiz-tests.ts new file mode 100644 index 0000000000..b156ff1403 --- /dev/null +++ b/swiz/swiz-tests.ts @@ -0,0 +1,172 @@ +/// + +import swiz = require('swiz'); + +var chain: swiz.IChain; +var sw: swiz.Swiz; +var value: any; +var valueArr: any[]; +var str: string; +var strArr: string[]; +var exp: RegExp; +var num: number; +var bool: boolean; +var callback: Function; + +var defs: swiz.struct.IObj[]; +var opts: swiz.ISwizOptions; +var field: swiz.struct.IField; +var ser: swiz.ISerializable; +var fieldArr: swiz.struct.IField[]; + +var opts: swiz.ISwizOptions = { + stripNulls: bool, + stripSerializerType: bool, + for: str +}; + +var obj: swiz.struct.IObj = { + name: str, + options: objOpts, + singular: str, + plural: str, + fields: fieldArr +}; + +var field: swiz.struct.IField = { + name: str, + options: fieldOpts, + src: str, + singular: str, + plural: str, + desc: str, + val: chain, + attribute: bool, + enumerated: bool, + ignorePublic: bool, + filterFrom: strArr, + coerceTo: value +}; + +var objOpts: swiz.struct.IObjOptions = { + singular: str, + plural: str, + fields: fieldArr +}; + +var fieldOpts: swiz.struct.IFieldOptions = { + src: str, + singular: str, + plural: str, + desc: str, + val: chain, + attribute: bool, + enumerated: value, + ignorePublic: bool, + filterFrom: strArr, + coerceTo: str +}; + +var valid: swiz.IValidator; +str = valid.name; +valid.func(value, value, callback); +str = valid.help; + +sw = new swiz.Swiz(defs, opts); +sw.buildObject(value, (err: any, result: any) => { + +}); +value = sw.buildObjectSync(value); +str = sw.serializeJson(value); +str = sw.serializeXml(value); +value = sw.deserializeXml(str); +sw.serialize(swiz.SERIALIZATION.SERIALIZATION_JSON, num, ser, (err: any, str: string) => { + +}); +sw.serializeForPagination(swiz.SERIALIZATION.SERIALIZATION_JSON, valueArr, value, (err: any, str: string) => { + +}); +sw.deserialize(swiz.SERIALIZATION.SERIALIZATION_JSON, num, str, (err: any, result: any) => { + +}); +field = sw.getFieldDefinition(str, str); + +// some of the chain API +chain = swiz.chain(); + +num = chain.getValidatorPos(str); +num = chain.hasValidator(str); + +valid = chain.getValidatorAtPos(num); +chain = chain.isUnique(); +chain = chain.toUnique(); +chain = chain.notIPBlacklisted(); +chain = chain.isCIDR(); +chain = chain.isEmail(); +chain = chain.isUrl(); +chain = chain.isAddressPair(); +chain = chain.isIP(); +chain = chain.isIPv4(); +chain = chain.isIPv6(); +chain = chain.isHostnameOrIp(); +chain = chain.isAllowedFQDNOrIP(); +chain = chain.isAllowedFQDNOrIP(strArr); +chain = chain.isHostname(); +chain = chain.isAlpha(); +chain = chain.isAlphanumeric(); +chain = chain.isNumeric(); +chain = chain.isInt(); +chain = chain.isLowercase(); +chain = chain.isUppercase(); +chain = chain.isDecimal(); +chain = chain.isFloat(); +chain = chain.notNull(); +chain = chain.isNull(); +chain = chain.notEmpty(); +chain = chain.equals(value); +chain = chain.contains(value); +chain = chain.notContains(value); +chain = chain.notIn(valueArr); +chain = chain.notIn(valueArr, bool); +chain = chain.regex(exp); +chain = chain.regex(str); +chain = chain.regex(str, str); +chain = chain.is(str); +chain = chain.is(str, str); +chain = chain.notRegex(exp); +chain = chain.notRegex(str); +chain = chain.notRegex(str, str); +chain = chain.not(str, str); +chain = chain.len(num); +chain = chain.len(num, num); +chain = chain.numItems(num, num); +chain = chain.toFloat(); +chain = chain.toInt(); +chain = chain.toBoolean(); +chain = chain.toBooleanStrict(); +chain = chain.entityDecode(); +chain = chain.entityEncode(); +chain = chain.trim(); +chain = chain.trim(str); +chain = chain.trim(); +chain = chain.trim(str); +chain = chain.ltrim(); +chain = chain.ltrim(str); +chain = chain.rtrim(str); +chain = chain.ifNull(str); +chain = chain.xss(); +chain = chain.xss(bool); +chain = chain.enumerated(value); +chain = chain.inArray(valueArr); +chain = chain.isString(); +chain = chain.isBoolean(); +chain = chain.range(value, value); +chain = chain.optional(); +chain = chain.isPort(); +chain = chain.isV1UUID(); +chain = chain.immutable(); +chain = chain.updateRequired(); +chain = chain.isArray(chain); +chain = chain.isHash(chain, chain); +chain = chain.rename(str); +chain = chain.custom(str); diff --git a/swiz/swiz.d.ts b/swiz/swiz.d.ts new file mode 100644 index 0000000000..4e76fab7d5 --- /dev/null +++ b/swiz/swiz.d.ts @@ -0,0 +1,195 @@ +// Type definitions for swiz +// Project: https://github.com/racker/node-swiz +// Definitions by: Jeff Goddard +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/swiz.d.ts + +declare module "swiz" { + export class Cidr { + constructor(x: string, y?: string); + isInCIDR(x: any): boolean; + } + + export class Valve { + constructor(schema: IValveSchema, baton?: any); + setSchema(schema: IValveSchema): Valve; + addFinalValidator(func: (obj: any, callback: (err: Error, cleaned: any) => void) => void): Valve; + addChainValidator(name: string, description: string, func: (value: any, callback: (err: Error, cleaned: any) => void) => void): void; + check(obj: any, options: ICheckOptions, callback: (err: any, cleaned: any) => void): void; + check(obj: any, callback: (err: any, cleaned: any) => void): void; + checkUpdate(existing: any, obj: any, callback: (err: any, cleaned: any) => void): void; + help(schema: IValveSchema): any; + } + + export interface ICheckOptions { + strict?: boolean; + } + + export interface IValveSchema { + [index: string]: IValveSchemaMember; + } + + export interface IValveSchemaMember {} + + export interface IValveSchemaMemberArray extends IValveSchemaMember { + [index: string]: IValveSchemaMember; + } + + export function Chain(): IChain; + + export function chain(): IChain; + + export interface IChain extends IValveSchemaMember { + getValidatorPos(name: string): number; + hasValidator(name: string): number; + getValidatorAtPos(pos: number): IValidator; + isUnique(): IChain; + toUnique(): IChain; + notIPBlacklisted(): IChain; + isCIDR(): IChain; + isEmail(): IChain; + isUrl(): IChain; + isAddressPair(): IChain; + isIP(): IChain; + isIPv4(): IChain; + isIPv6(): IChain; + isHostnameOrIp(): IChain; + isAllowedFQDNOrIP(blacklist?: string[]): IChain; + isHostname(): IChain; + isAlpha(): IChain; + isAlphanumeric(): IChain; + isNumeric(): IChain; + isInt(): IChain; + isLowercase(): IChain; + isUppercase(): IChain; + isDecimal(): IChain; + isFloat(): IChain; + notNull(): IChain; + isNull(): IChain; + notEmpty(): IChain; + equals(arg: any): IChain; + contains(arg: any): IChain; + notContains(arg: any): IChain; + notIn(values: any[], caseSensitive?: boolean): IChain; + regex(pattern: RegExp): IChain; + regex(pattern: string, modifiers?: string): IChain; + is(pattern: string, modifiers?: string): IChain; + notRegex(pattern: RegExp): IChain; + notRegex(pattern: string, modifiers?: string): IChain; + not(pattern: string, modifiers: string): IChain; + len(min: number, max?: number): IChain; + numItems(min: number, max: number): IChain; + toFloat(): IChain; + toInt(): IChain; + toBoolean(): IChain; + toBooleanStrict(): IChain; + entityDecode(): IChain; + entityEncode(): IChain; + trim(chars?: string): IChain; + ltrim(chars?: string): IChain; + rtrim(chars: string): IChain; + ifNull(replace: string): IChain; + xss(is_image?: boolean): IChain; + enumerated(map: any): IChain; + inArray(array: any[]): IChain; + isString(): IChain; + isBoolean(): IChain; + range(min: any, max: any): IChain; + optional(): IChain; + isPort(): IChain; + isV1UUID(): IChain; + immutable(): IChain; + updateRequired(): IChain; + isArray(chain: IChain): IChain; + isHash(keyChain: IChain, valueChain: IChain): IChain; + rename(target: string): IChain; + custom(name: string): IChain; + } + + export function defToValve(def: struct.IObj[]): IValveSchema[]; + + export class Swiz { + constructor(defs: struct.IObj[], options?: ISwizOptions); + buildObject(obj: any, callback: (err: any, result: any) => void): void; + buildObjectSync(obj: any): any; + serializeJson(obj: any): string; + serializeXml(obj: any): string; + deserializeXml(xml: string): any; + serialize(mode: SERIALIZATION, version: number, obj: ISerializable, callback: (err: any, result: string) => void): void; + serializeForPagination(mode: SERIALIZATION, array: any[], metadata: any, callback: (err: any, result: string) => void): void; + deserialize(mode: SERIALIZATION, version: number, raw: string, callback: (err: any, result: any) => void): void; + getFieldDefinition(stype: string, name: string): struct.IField; + } + + export interface ISerializable { + getSerializerType(): string; + } + + export interface ISwizOptions { + stripNulls?: boolean; + stripSerializerType?: boolean; + for?: string; + } + + interface IValidator { + name: string; + func(value: any, baton: any, callback: Function): void; + help: string; + } + + export function stripSerializerTypes(obj: any): any; + + export module struct { + export function Obj(name: string, options?: IObjOptions): IObj; + export function Field(name: string, options?: IFieldOptions): IField; + export function coerce(value: any, coerceTo: string): any; + + export interface IObj { + name: string; + options: IObjOptions; + singular: string; + plural: string; + fields: IField[]; + } + + export interface IField { + name: string; + options: IFieldOptions; + src: string; + singular: string; + plural: string; + desc?: string; + val?: IChain; + attribute: boolean; + enumerated: boolean; + ignorePublic: boolean; + filterFrom: string[]; + coerceTo: any; + } + + export interface IObjOptions { + singular?: string; + plural?: string; + fields?: IField[]; + } + + export interface IFieldOptions { + src?: string; + singular?: string; + plural?: string; + desc?: string; + val?: IChain; + attribute?: boolean; + enumerated?: any; + ignorePublic?: boolean; + filterFrom?: string[]; + coerceTo?: string; + } + } + + export enum SERIALIZATION { + SERIALIZATION_JSON, + SERIALIZATION_XML + } +} diff --git a/tape/tape-tests.ts b/tape/tape-tests.ts new file mode 100644 index 0000000000..2c4e4ec1bb --- /dev/null +++ b/tape/tape-tests.ts @@ -0,0 +1,106 @@ +/// + +/// + +import tape = require('tape'); + +var x: any; +var value: any; +var err: any; +var a: any; +var b: any; +var err: any; +var num: number; +var name: string; +var msg: string; +var rs: NodeJS.ReadableStream; + +var cb: tape.TestCase; +var t: tape.Test; + +tape(name, cb); +tape(name, (test: tape.Test) => { + t = test; +}); + +tape.skip(name, cb); +tape.only(name, cb); + +rs = tape.createStream(); +rs = tape.createStream(x); + +var tx = tape.createHarness(); +tx(name, cb); +tape.skip(name, cb); +tape.only(name, cb); + +tape(name, (test: tape.Test) => { + + test.plan(num); + test.end(); + + test.fail(msg); + test.pass(msg); + test.skip(msg); + + test.ok(value, msg); + test.true(value, msg); + test.assert(value, msg); + + test.notOk(value, msg); + test.false(value, msg); + test.notok(value, msg); + + test.error(err, msg); + test.ifError(err, msg); + test.ifErr(err, msg); + test.iferror(err, msg); + + test.equal(a, b, msg); + test.equals(a, b, msg); + test.isEqual(a, b, msg); + test.is(a, b, msg); + test.strictEqual(a, b, msg); + test.strictEquals(a, b, msg); + + test.notEqual(a, b, msg); + test.notEquals(a, b, msg); + test.notStrictEqual(a, b, msg); + test.notStrictEquals(a, b, msg); + test.isNotEqual(a, b, msg); + test.isNot(a, b, msg); + test.not(a, b, msg); + test.doesNotEqual(a, b, msg); + test.notEqual(a, b, msg); + test.isInequal(a, b, msg); + + test.deepEqual(a, b, msg); + test.deepEquals(a, b, msg); + test.isEquivalent(a, b, msg); + test.same(a, b, msg); + + test.notDeepEqual(a, b, msg); + test.notEquivalent(a, b, msg); + test.notDeeply(a, b, msg); + test.notSame(a, b, msg); + test.isNotDeepEqual(a, b, msg); + test.isNotDeeply(a, b, msg); + test.isNotEquivalent(a, b, msg); + test.isInequivalent(a, b, msg); + + test.deepLooseEqual(a, b, msg); + test.looseEqual(a, b, msg); + test.looseEquals(a, b, msg); + + test.notDeepLooseEqual(a, b, msg); + test.notLooseEqual(a, b, msg); + test.notLooseEquals(a, b, msg); + + test.throws(() => { + + }, value, msg); + + test.doesNotThrow(() => { + + }, value, msg); +}); diff --git a/tape/tape.d.ts b/tape/tape.d.ts new file mode 100644 index 0000000000..4746e148a0 --- /dev/null +++ b/tape/tape.d.ts @@ -0,0 +1,161 @@ +// Type definitions for tape v2.12.3 +// Project: https://github.com/substack/tape +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'tape' { + export = tape; + + /** + * Create a new test with an optional name string. cb(t) fires with the new test object t once all preceeding tests have finished. Tests execute serially. + */ + function tape(name: string, cb: tape.TestCase): void; + module tape { + + interface TestCase { + (test: Test): void; + } + + /** + * Generate a new test that will be skipped over. + */ + export function skip(name: string, cb: tape.TestCase): void; + + /** + * Like test(name, cb) except if you use .only this is the only test case that will run for the entire process, all other test cases using tape will be ignored + */ + export function only(name: string, cb: tape.TestCase): void; + + /** + * Create a new test harness instance, which is a function like test(), but with a new pending stack and test state. + */ + export function createHarness(): typeof tape; + /** + * Create a stream of output, bypassing the default output stream that writes messages to console.log(). + */ + export function createStream(opts?: any): NodeJS.ReadableStream; + + interface Test { + /** + * Create a subtest with a new test handle st from cb(st) inside the current test cb(st) will only fire when t finishes. Additional tests queued up after t will not be run until all subtests finish. + */ + test(name: string, cb: tape.TestCase): void; + + /** + * Declare that n assertions should be run. end() will be called automatically after the nth assertion. If there are any more assertions after the nth, or after end() is called, they will generate errors. + */ + plan(n: number): void; + + /** + * Declare the end of a test explicitly. + */ + end(): void; + + /** + * Generate a failing assertion with a message msg. + */ + fail(msg?: string): void; + + /** + * Generate a passing assertion with a message msg. + */ + pass(msg?: string): void; + + /** + * Generate an assertion that will be skipped over. + */ + skip(msg?: string): void; + + /** + * Assert that value is truthy with an optional description message msg. + */ + ok(value: any, msg?: string): void; + true(value: any, msg?: string): void; + assert(value: any, msg?: string): void; + + /** + * Assert that value is falsy with an optional description message msg. + */ + notOk(value: any, msg?: string): void; + false(value: any, msg?: string): void; + notok(value: any, msg?: string): void; + + /** + * Assert that err is falsy. If err is non-falsy, use its err.message as the description message. + */ + error(err: any, msg?: string): void; + ifError(err: any, msg?: string): void; + ifErr(err: any, msg?: string): void; + iferror(err: any, msg?: string): void; + + /** + * Assert that a === b with an optional description msg. + */ + equal(a: any, b: any, msg?: string): void; + equals(a: any, b: any, msg?: string): void; + isEqual(a: any, b: any, msg?: string): void; + is(a: any, b: any, msg?: string): void; + strictEqual(a: any, b: any, msg?: string): void; + strictEquals(a: any, b: any, msg?: string): void; + + /** + * Assert that a !== b with an optional description msg. + */ + notEqual(a: any, b: any, msg?: string): void; + notEquals(a: any, b: any, msg?: string): void; + notStrictEqual(a: any, b: any, msg?: string): void; + notStrictEquals(a: any, b: any, msg?: string): void; + isNotEqual(a: any, b: any, msg?: string): void; + isNot(a: any, b: any, msg?: string): void; + not(a: any, b: any, msg?: string): void; + doesNotEqual(a: any, b: any, msg?: string): void; + isInequal(a: any, b: any, msg?: string): void; + + /** + * Assert that a and b have the same structure and nested values using node's deepEqual() algorithm with strict comparisons (===) on leaf nodes and an optional description msg. + */ + deepEqual(a: any, b: any, msg?: string): void; + deepEquals(a: any, b: any, msg?: string): void; + isEquivalent(a: any, b: any, msg?: string): void; + same(a: any, b: any, msg?: string): void; + + /** + * Assert that a and b do not have the same structure and nested values using node's deepEqual() algorithm with strict comparisons (===) on leaf nodes and an optional description msg. + */ + notDeepEqual(a: any, b: any, msg?: string): void; + notEquivalent(a: any, b: any, msg?: string): void; + notDeeply(a: any, b: any, msg?: string): void; + notSame(a: any, b: any, msg?: string): void; + isNotDeepEqual(a: any, b: any, msg?: string): void; + isNotDeeply(a: any, b: any, msg?: string): void; + isNotEquivalent(a: any, b: any, msg?: string): void; + isInequivalent(a: any, b: any, msg?: string): void; + + /** + * Assert that a and b have the same structure and nested values using node's deepEqual() algorithm with loose comparisons (==) on leaf nodes and an optional description msg. + */ + deepLooseEqual(a: any, b: any, msg?: string): void; + looseEqual(a: any, b: any, msg?: string): void; + looseEquals(a: any, b: any, msg?: string): void; + + /** + * Assert that a and b do not have the same structure and nested values using node's deepEqual() algorithm with loose comparisons (==) on leaf nodes and an optional description msg. + */ + notDeepLooseEqual(a: any, b: any, msg?: string): void; + notLooseEqual(a: any, b: any, msg?: string): void; + notLooseEquals(a: any, b: any, msg?: string): void; + + /** + * Assert that the function call fn() throws an exception. + */ + throws(fn: () => void, expected: any, msg?: string): void; + + /** + * Assert that the function call fn() does not throw an exception. + */ + doesNotThrow(fn: () => void, expected: any, msg?: string): void; + } + } +} diff --git a/test-module/test-addon.ts b/test-module/test-addon.ts deleted file mode 100644 index 14c5ba0d6f..0000000000 --- a/test-module/test-addon.ts +++ /dev/null @@ -1,5 +0,0 @@ -/// - -declare module 'test-addon' { - export function addon(): Such; -} diff --git a/test-module/test-module.d.ts b/test-module/test-module.d.ts deleted file mode 100644 index 294e7ea433..0000000000 --- a/test-module/test-module.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -interface Such { - amaze(): void; - much(): void; -} -declare module 'test-module' { - export function wow(): Such; -} diff --git a/text-buffer/text-buffer-tests.ts b/text-buffer/text-buffer-tests.ts new file mode 100644 index 0000000000..8621c30918 --- /dev/null +++ b/text-buffer/text-buffer-tests.ts @@ -0,0 +1,19 @@ +/// + +declare var Point: TextBuffer.IPointStatic; + +var pointA = new Point(1, 2); +pointA.row; +pointA.column; + +var pointB = Point.fromObject({row: 2, column: 3}); +var pointC = Point.min(pointA, pointB); + +declare var TRange: TextBuffer.IRangeStatic; + +var rangeA = new TRange(pointA, pointB); + +declare var TextBufferStatic: TextBuffer.ITextBufferStatic; + +var textBuffer = new TextBufferStatic("Hello, world!"); +textBuffer.getLineCount(); diff --git a/text-buffer/text-buffer.d.ts b/text-buffer/text-buffer.d.ts new file mode 100644 index 0000000000..9296e7c7c0 --- /dev/null +++ b/text-buffer/text-buffer.d.ts @@ -0,0 +1,303 @@ +// Type definitions for text-buffer +// Project: https://github.com/atom/text-buffer +// Definitions by: vvakame +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// + + +declare module TextBuffer { + + interface IPointStatic { + new (row?:number, column?:number):IPoint; + + fromObject(point:IPoint, copy?:boolean):IPoint; + fromObject(object:number[]):IPoint; + fromObject(object:{row:number; column:number;}):IPoint; + + min(point1:IPoint, point2:IPoint):IPoint; + min(point1:number[], point2:IPoint):IPoint; + min(point1:{row:number; column:number;}, point2:IPoint):IPoint; + + min(point1:IPoint, point2:number[]):IPoint; + min(point1:number[], point2:number[]):IPoint; + min(point1:{row:number; column:number;}, point2:number[]):IPoint; + + min(point1:IPoint, point2:{row:number; column:number;}):IPoint; + min(point1:number[], point2:{row:number; column:number;}):IPoint; + min(point1:{row:number; column:number;}, point2:{row:number; column:number;}):IPoint; + } + + interface IPoint { + constructor: IPointStatic; + + row:number; + column:number; + + copy():IPoint; + freeze():IPoint; + + translate(delta:IPoint):IPoint; + translate(delta:number[]):IPoint; + translate(delta:{row:number; column:number;}):IPoint; + + add(other:IPoint):IPoint; + add(other:number[]):IPoint; + add(other:{row:number; column:number;}):IPoint; + + splitAt(column:number):IPoint[]; + compare(other:IPoint):number; + isEqual(other:IPoint):boolean; + isLessThan(other:IPoint):boolean; + isLessThanOrEqual(other:IPoint):boolean; + isGreaterThan(other:IPoint):boolean; + isGreaterThanOrEqual(other:IPoint):boolean; + toArray():number[]; + serialize():number[]; + } + + interface IRangeStatic { + deserialize(array:IPoint[]):IRange; + + fromObject(object:IPoint[]):IRange; + + fromObject(object:IRange, copy?:boolean):IRange; + + fromObject(object:{start: IPoint; end: IPoint}):IRange; + fromObject(object:{start: number[]; end: IPoint}):IRange; + fromObject(object:{start: {row:number; column:number;}; end: IPoint}):IRange; + + fromObject(object:{start: IPoint; end: number[]}):IRange; + fromObject(object:{start: number[]; end: number[]}):IRange; + fromObject(object:{start: {row:number; column:number;}; end: number[]}):IRange; + + fromObject(object:{start: IPoint; end: {row:number; column:number;}}):IRange; + fromObject(object:{start: number[]; end: {row:number; column:number;}}):IRange; + fromObject(object:{start: {row:number; column:number;}; end: {row:number; column:number;}}):IRange; + + fromText(point:IPoint, text:string):IRange; + fromText(point:number[], text:string):IRange; + fromText(point:{row:number; column:number;}, text:string):IRange; + fromText(text:string):IRange; + + fromPointWithDelta(startPoint:IPoint, rowDelta:number, columnDelta:number):IRange; + fromPointWithDelta(startPoint:number[], rowDelta:number, columnDelta:number):IRange; + fromPointWithDelta(startPoint:{row:number; column:number;}, rowDelta:number, columnDelta:number):IRange; + + new(point1:IPoint, point2:IPoint):IRange; + new(point1:number[], point2:IPoint):IRange; + new(point1:{row:number; column:number;}, point2:IPoint):IRange; + + new(point1:IPoint, point2:number[]):IRange; + new(point1:number[], point2:number[]):IRange; + new(point1:{row:number; column:number;}, point2:number[]):IRange; + + new(point1:IPoint, point2:{row:number; column:number;}):IRange; + new(point1:number[], point2:{row:number; column:number;}):IRange; + new(point1:{row:number; column:number;}, point2:{row:number; column:number;}):IRange; + } + + interface IRange { + constructor:IRangeStatic; + + start: IPoint; + end: IPoint; + + serialize():number[][]; + copy():IRange; + freeze():IRange; + isEqual(other:IRange):boolean; + isEqual(other:IPoint[]):boolean; + + compare(object:IPoint[]):number; + + compare(object:{start: IPoint; end: IPoint}):number; + compare(object:{start: number[]; end: IPoint}):number; + compare(object:{start: {row:number; column:number;}; end: IPoint}):number; + + compare(object:{start: IPoint; end: number[]}):number; + compare(object:{start: number[]; end: number[]}):number; + compare(object:{start: {row:number; column:number;}; end: number[]}):number; + + compare(object:{start: IPoint; end: {row:number; column:number;}}):number; + compare(object:{start: number[]; end: {row:number; column:number;}}):number; + compare(object:{start: {row:number; column:number;}; end: {row:number; column:number;}}):number; + + isSingleLine():boolean; + coversSameRows(other:IRange):boolean; + + add(object:IPoint[]):IRange; + + add(object:{start: IPoint; end: IPoint}):IRange; + add(object:{start: number[]; end: IPoint}):IRange; + add(object:{start: {row:number; column:number;}; end: IPoint}):IRange; + + add(object:{start: IPoint; end: number[]}):IRange; + add(object:{start: number[]; end: number[]}):IRange; + add(object:{start: {row:number; column:number;}; end: number[]}):IRange; + + add(object:{start: IPoint; end: {row:number; column:number;}}):IRange; + add(object:{start: number[]; end: {row:number; column:number;}}):IRange; + add(object:{start: {row:number; column:number;}; end: {row:number; column:number;}}):IRange; + + translate(startPoint:IPoint, endPoint:IPoint):IRange; + translate(startPoint:IPoint):IRange; + + intersectsWith(otherRange:IRange):boolean; + containsRange(otherRange:IRange, exclusive:boolean):boolean; + + containsPoint(point:IPoint, exclusive:boolean):boolean; + containsPoint(point:number[], exclusive:boolean):boolean; + containsPoint(point:{row:number; column:number;}, exclusive:boolean):boolean; + + intersectsRow(row:number):boolean; + intersectsRowRange(startRow:number, endRow:number):boolean; + union(otherRange:IRange):IRange; + isEmpty():boolean; + toDelta():IPoint; + getRowCount():number; + getRows():number[]; + } + + interface IHistory { + // TBD + } + + interface IMarkerManager { + // TBD + } + + interface IMarker { + // TBD + } + + interface IBufferPatch { + // TBD + } + + interface ITextBufferStatic { + Point: IPointStatic; + Range: IRangeStatic; + newlineRegex:any; + + new (text:string): ITextBuffer; + new (params:any): ITextBuffer; + } + + interface ITextBuffer extends Emissary.IEmitter, Emissary.ISubscriber { + // Delegator.includeInto(TextBuffer); + // Serializable.includeInto(TextBuffer); + + cachedText:string; + stoppedChangingDelay:number; + stoppedChangingTimeout:any; + cachedDiskContents:string; + conflict:boolean; + file:any; // pathwatcher.IFile + refcount:number; + + lines:string[]; + lineEndings:string[]; + offsetIndex:any; // span-skip-list.SpanSkipList + history:IHistory; + markers:IMarkerManager; + loaded:boolean; + digestWhenLastPersisted:string; + modifiedWhenLastPersisted:boolean; + useSerializedText:boolean; + + deserializeParams(params:any):any; + serializeParams():any; + + getText():string; + getLines():string; + isEmpty():boolean; + getLineCount():number; + getLastRow():number; + lineForRow(row:number):string; + getLastLine():string; + lineEndingForRow(row:number):string; + lineLengthForRow(row:number):number; + setText(text:string):IRange; + setTextViaDiff(text:any):any[]; + setTextInRange(range:IRange, text:string, normalizeLineEndings?:boolean):IRange; + insert(position:IPoint, text:string, normalizeLineEndings?:boolean):IRange; + append(text:string, normalizeLineEndings?:boolean):IRange; + delete(range:IRange):IRange; + deleteRow(row:number):IRange; + deleteRows(startRow:number, endRow:number):IRange; + buildPatch(oldRange:IRange, newText:string, normalizeLineEndings?:boolean):IBufferPatch; + applyPatch(patch:IBufferPatch):any; + getTextInRange(range:IRange):string; + clipRange(range:IRange):IRange; + clipPosition(position:IPoint):IPoint; + getFirstPosition():IPoint; + getEndPosition():IPoint; + getRange():IRange; + rangeForRow(row:number, includeNewline?:boolean):IRange; + characterIndexForPosition(position:IPoint):number; + positionForCharacterIndex(offset:number):IPoint; + getMaxCharacterIndex():number; + loadSync():ITextBuffer; + load():Q.IPromise; + finishLoading():ITextBuffer; + handleTextChange(event:any):any; + destroy():any; + isAlive():boolean; + isDestroyed():boolean; + isRetained():boolean; + retain():ITextBuffer; + release():ITextBuffer; + subscribeToFile():any; + hasMultipleEditors():boolean; + reload():any; + updateCachedDiskContentsSync():string; + updateCachedDiskContents():Q.IPromise; + getBaseName():string; + getPath():string; + getUri():string; + setPath(filePath:string):any; + save():void; + saveAs(filePath:string):any; + isModified():boolean; + isInConflict():boolean; + destroyMarker(id:any):any; + matchesInCharacterRange(regex:any, startIndex:any, endIndex:any):any[]; + scan(regex:any, iterator:any):any; + backwardsScan(regex:any, iterator:any):any; + replace(regex:any, replacementText:any):any; + scanInRange(regex:any, range:any, iterator:any, reverse:any):any; + backwardsScanInRange(regex:any, range:any, iterator:any):any; + isRowBlank(row:number):boolean; + previousNonBlankRow(startRow:number):number; + nextNonBlankRow(startRow:number):number; + usesSoftTabs():boolean; + cancelStoppedChangingTimeout():any; + scheduleModifiedEvents():any; + emitModifiedStatusChanged(modifiedStatus:any):any; + logLines(start:number, end:number):void; + + // delegate to history property + undo():any; + redo():any; + transact(fn:Function):any; + beginTransaction():any; + commitTransaction():any; + abortTransaction():any; + clearUndoStack():any; + + // delegate to markers property + markRange(range:any, properties:any):any; + markPosition(range:any, properties:any):any; + getMarker(id:number):IMarker; + getMarkers():IMarker[]; + getMarkerCount():number; + } +} + +declare module "text-buffer" { + var _: TextBuffer.ITextBufferStatic; + export = _; +} \ No newline at end of file diff --git a/text-encoding/text-encoding-tests.ts b/text-encoding/text-encoding-tests.ts new file mode 100644 index 0000000000..e0274a04c0 --- /dev/null +++ b/text-encoding/text-encoding-tests.ts @@ -0,0 +1,60 @@ +/// + +function test_encoder() { + var text = "plain text"; + var uint8array: Uint8Array; + + // constructor + uint8array = new TextEncoder().encode(text); + uint8array = new TextEncoder('utf-8').encode(text); + uint8array = new TextEncoder('windows-1252', { NONSTANDARD_allowLegacyEncoding: true }).encode(text); + + uint8array = TextEncoder().encode(text); + uint8array = TextEncoder('utf-8').encode(text); + uint8array = TextEncoder('windows-1252', { NONSTANDARD_allowLegacyEncoding: true }).encode(text); + + // attributes + var encoder = new TextEncoder(); + encoder.encoding = 'utf-8'; + var encoding: string = encoder.encoding; + + // methods + encoder.encode(); + encoder.encode(text); + encoder.encode(text, { stream: true }); +} + +function test_decoder() { + var text = "plain text"; + var uint8array: Uint8Array = TextEncoder().encode(text); + + // constructor + text = new TextDecoder().decode(uint8array); + text = new TextDecoder('utf-8').decode(uint8array); + text = new TextDecoder('windows-1252', {}).decode(uint8array); + text = new TextDecoder('windows-1252', { fatal: true }).decode(uint8array); + text = new TextDecoder('windows-1252', { ignoreBOM: true }).decode(uint8array); + + text = TextDecoder().decode(uint8array); + text = TextDecoder('utf-8').decode(uint8array); + text = TextDecoder('windows-1252', {}).decode(uint8array); + text = TextDecoder('windows-1252', { fatal: true }).decode(uint8array); + text = TextDecoder('windows-1252', { ignoreBOM: true }).decode(uint8array); + + // attributes + var decoder = new TextDecoder(); + + decoder.encoding = 'utf-8'; + var encoding: string = decoder.encoding; + + decoder.fatal = true; + var fatal: boolean = decoder.fatal; + + decoder.ignoreBOM = true; + var ignoreBOM: boolean = decoder.ignoreBOM; + + // methods + decoder.decode(); + decoder.decode(uint8array); + decoder.decode(uint8array, { stream: true }); +} \ No newline at end of file diff --git a/text-encoding/text-encoding.d.ts b/text-encoding/text-encoding.d.ts new file mode 100644 index 0000000000..574b25d716 --- /dev/null +++ b/text-encoding/text-encoding.d.ts @@ -0,0 +1,45 @@ +// Type definitions for text-encoding +// Project: https://github.com/inexorabletash/text-encoding +// Definitions by: MIZUNE Pine +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module TextEncoding { + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + + interface TextDecodeOptions { + stream?: boolean; + } + + interface TextEncoderOptions { + NONSTANDARD_allowLegacyEncoding?: boolean; + } + + interface TextDecoder { + encoding: string; + fatal: boolean; + ignoreBOM: boolean; + decode(input?: ArrayBufferView, options?: TextDecodeOptions): string; + } + + interface TextEncoder { + encoding: string; + encode(input?: string, options?: TextEncodeOptions): Uint8Array; + } + + interface TextEncodeOptions { + stream?: boolean; + } +} + +declare var TextDecoder: { + (label?: string, options?: TextEncoding.TextDecoderOptions): TextEncoding.TextDecoder; + new (label?: string, options?: TextEncoding.TextDecoderOptions): TextEncoding.TextDecoder; +}; + +declare var TextEncoder: { + (utfLabel?: string, options?: TextEncoding.TextEncoderOptions): TextEncoding.TextEncoder; + new (utfLabel?: string, options?: TextEncoding.TextEncoderOptions): TextEncoding.TextEncoder; +}; \ No newline at end of file diff --git a/threejs/tests/canvas/canvas_camera_orthographic.ts b/threejs/tests/canvas/canvas_camera_orthographic.ts new file mode 100644 index 0000000000..0674e6fa44 --- /dev/null +++ b/threejs/tests/canvas/canvas_camera_orthographic.ts @@ -0,0 +1,146 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/canvas_camera_orthographic.html + +() => { + + var container, stats; + var camera, scene, renderer; + + init(); + animate(); + + function init() { + + container = document.createElement('div'); + document.body.appendChild(container); + + var info = document.createElement('div'); + info.style.position = 'absolute'; + info.style.top = '10px'; + info.style.width = '100%'; + info.style.textAlign = 'center'; + info.innerHTML = 'three.js - orthographic view'; + container.appendChild(info); + + camera = new THREE.OrthographicCamera(window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, - 500, 1000); + camera.position.x = 200; + camera.position.y = 100; + camera.position.z = 200; + + scene = new THREE.Scene(); + + // Grid + + var size = 500, step = 50; + + var geometry = new THREE.Geometry(); + + for (var i = - size; i <= size; i += step) { + + geometry.vertices.push(new THREE.Vector3(- size, 0, i)); + geometry.vertices.push(new THREE.Vector3(size, 0, i)); + + geometry.vertices.push(new THREE.Vector3(i, 0, - size)); + geometry.vertices.push(new THREE.Vector3(i, 0, size)); + + } + + var material1 = new THREE.LineBasicMaterial({ color: 0x000000, opacity: 0.2 }); + + var line = new THREE.Line(geometry, material1); + line.type = THREE.LinePieces; + scene.add(line); + + // Cubes + + var geometry = new THREE.BoxGeometry(50, 50, 50); + var material2 = new THREE.MeshLambertMaterial({ color: 0xffffff, shading: THREE.FlatShading, overdraw: 0.5 }); + + for (var i = 0; i < 100; i++) { + + var cube = new THREE.Mesh(geometry, material2); + + cube.scale.y = Math.floor(Math.random() * 2 + 1); + + cube.position.x = Math.floor((Math.random() * 1000 - 500) / 50) * 50 + 25; + cube.position.y = (cube.scale.y * 50) / 2; + cube.position.z = Math.floor((Math.random() * 1000 - 500) / 50) * 50 + 25; + + scene.add(cube); + + } + + // Lights + + var ambientLight = new THREE.AmbientLight(Math.random() * 0x10); + scene.add(ambientLight); + + var directionalLight = new THREE.DirectionalLight(Math.random() * 0xffffff); + directionalLight.position.x = Math.random() - 0.5; + directionalLight.position.y = Math.random() - 0.5; + directionalLight.position.z = Math.random() - 0.5; + directionalLight.position.normalize(); + scene.add(directionalLight); + + var directionalLight = new THREE.DirectionalLight(Math.random() * 0xffffff); + directionalLight.position.x = Math.random() - 0.5; + directionalLight.position.y = Math.random() - 0.5; + directionalLight.position.z = Math.random() - 0.5; + directionalLight.position.normalize(); + scene.add(directionalLight); + + renderer = new THREE.CanvasRenderer(); + renderer.setClearColor(0xf0f0f0); + renderer.setSize(window.innerWidth, window.innerHeight); + + container.appendChild(renderer.domElement); + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + container.appendChild(stats.domElement); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + camera.left = window.innerWidth / - 2; + camera.right = window.innerWidth / 2; + camera.top = window.innerHeight / 2; + camera.bottom = window.innerHeight / - 2; + + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + var timer = Date.now() * 0.0001; + + camera.position.x = Math.cos(timer) * 200; + camera.position.z = Math.sin(timer) * 200; + camera.lookAt(scene.position); + + renderer.render(scene, camera); + + } +} \ No newline at end of file diff --git a/threejs/tests/canvas/canvas_geometry_cube.ts b/threejs/tests/canvas/canvas_geometry_cube.ts new file mode 100644 index 0000000000..00c3b0426f --- /dev/null +++ b/threejs/tests/canvas/canvas_geometry_cube.ts @@ -0,0 +1,187 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/canvas_geometry_cube.html + +() => { + var container, stats; + + var camera, scene, renderer; + + var cube, plane; + + var targetRotation = 0; + var targetRotationOnMouseDown = 0; + + var mouseX = 0; + var mouseXOnMouseDown = 0; + + var windowHalfX = window.innerWidth / 2; + var windowHalfY = window.innerHeight / 2; + + init(); + animate(); + + function init() { + + container = document.createElement('div'); + document.body.appendChild(container); + + var info = document.createElement('div'); + info.style.position = 'absolute'; + info.style.top = '10px'; + info.style.width = '100%'; + info.style.textAlign = 'center'; + info.innerHTML = 'Drag to spin the cube'; + container.appendChild(info); + + camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000); + camera.position.y = 150; + camera.position.z = 500; + + scene = new THREE.Scene(); + + // Cube + + var geometry = new THREE.CubeGeometry(200, 200, 200); + + for (var i = 0; i < geometry.faces.length; i += 2) { + + var hex = Math.random() * 0xffffff; + geometry.faces[i].color.setHex(hex); + geometry.faces[i + 1].color.setHex(hex); + + } + + var material = new THREE.MeshBasicMaterial({ vertexColors: THREE.FaceColors, overdraw: 0.5 }); + + cube = new THREE.Mesh(geometry, material); + cube.position.y = 150; + scene.add(cube); + + // Plane + + var geometry = new THREE.PlaneGeometry(200, 200); + geometry.applyMatrix(new THREE.Matrix4().makeRotationX(- Math.PI / 2)); + + var material = new THREE.MeshBasicMaterial({ color: 0xe0e0e0, overdraw: 0.5 }); + + plane = new THREE.Mesh(geometry, material); + scene.add(plane); + + renderer = new THREE.CanvasRenderer(); + renderer.setClearColor(0xf0f0f0); + renderer.setSize(window.innerWidth, window.innerHeight); + + container.appendChild(renderer.domElement); + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + container.appendChild(stats.domElement); + + document.addEventListener('mousedown', onDocumentMouseDown, false); + document.addEventListener('touchstart', onDocumentTouchStart, false); + document.addEventListener('touchmove', onDocumentTouchMove, false); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + windowHalfX = window.innerWidth / 2; + windowHalfY = window.innerHeight / 2; + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + // + + function onDocumentMouseDown(event) { + + event.preventDefault(); + + document.addEventListener('mousemove', onDocumentMouseMove, false); + document.addEventListener('mouseup', onDocumentMouseUp, false); + document.addEventListener('mouseout', onDocumentMouseOut, false); + + mouseXOnMouseDown = event.clientX - windowHalfX; + targetRotationOnMouseDown = targetRotation; + + } + + function onDocumentMouseMove(event) { + + mouseX = event.clientX - windowHalfX; + + targetRotation = targetRotationOnMouseDown + (mouseX - mouseXOnMouseDown) * 0.02; + + } + + function onDocumentMouseUp(event) { + + document.removeEventListener('mousemove', onDocumentMouseMove, false); + document.removeEventListener('mouseup', onDocumentMouseUp, false); + document.removeEventListener('mouseout', onDocumentMouseOut, false); + + } + + function onDocumentMouseOut(event) { + + document.removeEventListener('mousemove', onDocumentMouseMove, false); + document.removeEventListener('mouseup', onDocumentMouseUp, false); + document.removeEventListener('mouseout', onDocumentMouseOut, false); + + } + + function onDocumentTouchStart(event) { + + if (event.touches.length === 1) { + + event.preventDefault(); + + mouseXOnMouseDown = event.touches[0].pageX - windowHalfX; + targetRotationOnMouseDown = targetRotation; + + } + + } + + function onDocumentTouchMove(event) { + + if (event.touches.length === 1) { + + event.preventDefault(); + + mouseX = event.touches[0].pageX - windowHalfX; + targetRotation = targetRotationOnMouseDown + (mouseX - mouseXOnMouseDown) * 0.05; + + } + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + plane.rotation.y = cube.rotation.y += (targetRotation - cube.rotation.y) * 0.05; + renderer.render(scene, camera); + + } +} \ No newline at end of file diff --git a/threejs/tests/canvas/canvas_interactive_cubes_tween.ts b/threejs/tests/canvas/canvas_interactive_cubes_tween.ts new file mode 100644 index 0000000000..8fbd7c2cf7 --- /dev/null +++ b/threejs/tests/canvas/canvas_interactive_cubes_tween.ts @@ -0,0 +1,147 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/canvas_interactive_cubes_tween.html + +() => { + var container, stats; + var camera, scene, projector, renderer; + + init(); + animate(); + + function init() { + + container = document.createElement('div'); + document.body.appendChild(container); + + var info = document.createElement('div'); + info.style.position = 'absolute'; + info.style.top = '10px'; + info.style.width = '100%'; + info.style.textAlign = 'center'; + info.innerHTML = 'three.js - clickable objects'; + container.appendChild(info); + + camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000); + camera.position.y = 300; + camera.position.z = 500; + + scene = new THREE.Scene(); + + var geometry = new THREE.BoxGeometry(100, 100, 100); + + for (var i = 0; i < 20; i++) { + + var object = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ color: Math.random() * 0xffffff, opacity: 0.5 })); + object.position.x = Math.random() * 800 - 400; + object.position.y = Math.random() * 800 - 400; + object.position.z = Math.random() * 800 - 400; + object.scale.x = Math.random() * 2 + 1; + object.scale.y = Math.random() * 2 + 1; + object.scale.z = Math.random() * 2 + 1; + object.rotation.x = Math.random() * 2 * Math.PI; + object.rotation.y = Math.random() * 2 * Math.PI; + object.rotation.z = Math.random() * 2 * Math.PI; + scene.add(object); + + } + + projector = new THREE.Projector(); + + renderer = new THREE.CanvasRenderer(); + renderer.setClearColor(0xf0f0f0); + renderer.setSize(window.innerWidth, window.innerHeight); + + container.appendChild(renderer.domElement); + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + container.appendChild(stats.domElement); + + document.addEventListener('mousedown', onDocumentMouseDown, false); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + function onDocumentMouseDown(event) { + + event.preventDefault(); + + var vector = new THREE.Vector3((event.clientX / window.innerWidth) * 2 - 1, - (event.clientY / window.innerHeight) * 2 + 1, 0.5); + projector.unprojectVector(vector, camera); + + var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize()); + + var intersects = raycaster.intersectObjects(scene.children); + + if (intersects.length > 0) { + + new TWEEN.Tween(intersects[0].object.position).to({ + x: Math.random() * 800 - 400, + y: Math.random() * 800 - 400, + z: Math.random() * 800 - 400 + }, 2000) + .easing(TWEEN.Easing.Elastic.Out).start(); + + new TWEEN.Tween(intersects[0].object.rotation).to({ + x: Math.random() * 2 * Math.PI, + y: Math.random() * 2 * Math.PI, + z: Math.random() * 2 * Math.PI + }, 2000) + .easing(TWEEN.Easing.Elastic.Out).start(); + + } + + /* + // Parse all the faces + for ( var i in intersects ) { + + intersects[ i ].face.material[ 0 ].color.setHex( Math.random() * 0xffffff | 0x80000000 ); + + } + */ + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + var radius = 600; + var theta = 0; + + function render() { + + TWEEN.update(); + + theta += 0.1; + + camera.position.x = radius * Math.sin(THREE.Math.degToRad(theta)); + camera.position.y = radius * Math.sin(THREE.Math.degToRad(theta)); + camera.position.z = radius * Math.cos(THREE.Math.degToRad(theta)); + camera.lookAt(scene.position); + + renderer.render(scene, camera); + + } +} \ No newline at end of file diff --git a/threejs/tests/canvas/canvas_lights_pointlights.ts b/threejs/tests/canvas/canvas_lights_pointlights.ts new file mode 100644 index 0000000000..1b6a6663ff --- /dev/null +++ b/threejs/tests/canvas/canvas_lights_pointlights.ts @@ -0,0 +1,124 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/canvas_lights_pointlights.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + // ------- + var camera, scene, renderer, + particle1, particle2, particle3, + light1, light2, light3, + loader, mesh; + + init(); + animate(); + + function init() { + + var container = document.getElementById('container'); + + camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000); + camera.position.set(0, - 6, 100); + + scene = new THREE.Scene(); + + scene.add(new THREE.AmbientLight(0x00020)); + + light1 = new THREE.PointLight(0xff0040, 1, 50); + scene.add(light1); + + light2 = new THREE.PointLight(0x0040ff, 1, 50); + scene.add(light2); + + light3 = new THREE.PointLight(0x80ff80, 1, 50); + scene.add(light3); + + var PI2 = Math.PI * 2; + var program = function (context) { + + context.beginPath(); + context.arc(0, 0, 0.5, 0, PI2, true); + context.fill(); + + } + + particle1 = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0xff0040, program: program })); + scene.add(particle1); + + particle2 = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0x0040ff, program: program })); + scene.add(particle2); + + particle3 = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0x80ff80, program: program })); + scene.add(particle3); + + loader = new THREE.JSONLoader(); + loader.load('obj/WaltHeadLo.js', function (geometry) { + + mesh = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({ color: 0xffffff, shading: THREE.FlatShading, overdraw: 0.5 })); + scene.add(mesh); + + }); + + renderer = new THREE.CanvasRenderer(); + renderer.setSize(window.innerWidth, window.innerHeight); + container.appendChild(renderer.domElement); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + // + + function animate() { + + requestAnimationFrame(animate); + render(); + + } + + function render() { + + var time = Date.now() * 0.0005; + + if (mesh) mesh.rotation.y -= 0.01; + + particle1.position.x = Math.sin(time * 0.7) * 30; + particle1.position.y = Math.cos(time * 0.5) * 40; + particle1.position.z = Math.cos(time * 0.3) * 30; + + light1.position.x = particle1.position.x; + light1.position.y = particle1.position.y; + light1.position.z = particle1.position.z; + + particle2.position.x = Math.cos(time * 0.3) * 30; + particle2.position.y = Math.sin(time * 0.5) * 40; + particle2.position.z = Math.sin(time * 0.7) * 30; + + light2.position.x = particle2.position.x; + light2.position.y = particle2.position.y; + light2.position.z = particle2.position.z; + + particle3.position.x = Math.sin(time * 0.7) * 30; + particle3.position.y = Math.cos(time * 0.3) * 40; + particle3.position.z = Math.sin(time * 0.5) * 30; + + light3.position.x = particle3.position.x; + light3.position.y = particle3.position.y; + light3.position.z = particle3.position.z; + + renderer.render(scene, camera); + + } +} \ No newline at end of file diff --git a/threejs/tests/canvas/canvas_materials.ts b/threejs/tests/canvas/canvas_materials.ts new file mode 100644 index 0000000000..23524098ae --- /dev/null +++ b/threejs/tests/canvas/canvas_materials.ts @@ -0,0 +1,213 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/canvas_materials.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + var materials: THREE.Material[]; + var debugContext: any; + // ------- + var container, stats; + + var camera, scene, renderer, objects; + var particleLight, pointLight; + + init(); + animate(); + + function init() { + + container = document.createElement('div'); + document.body.appendChild(container); + + camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000); + camera.position.set(0, 200, 800); + + scene = new THREE.Scene(); + + // Grid + + var size = 500, step = 100; + + var geometry = new THREE.Geometry(); + + for (var i = - size; i <= size; i += step) { + + geometry.vertices.push(new THREE.Vector3(- size, - 120, i)); + geometry.vertices.push(new THREE.Vector3(size, - 120, i)); + + geometry.vertices.push(new THREE.Vector3(i, - 120, - size)); + geometry.vertices.push(new THREE.Vector3(i, - 120, size)); + + } + + var material = new THREE.LineBasicMaterial({ color: 0xffffff, opacity: 0.2 }); + + var line = new THREE.Line(geometry, material); + line.type = THREE.LinePieces; + scene.add(line); + + // Spheres + + var geometry = new THREE.SphereGeometry(100, 14, 7); + + materials = [ + + new THREE.MeshBasicMaterial({ color: 0x00ffff, wireframe: true, side: THREE.DoubleSide }), + new THREE.MeshBasicMaterial({ color: 0xff0000, blending: THREE.AdditiveBlending }), + new THREE.MeshLambertMaterial({ color: 0xffffff, shading: THREE.FlatShading, overdraw: 0.5 }), + new THREE.MeshLambertMaterial({ color: 0xffffff, shading: THREE.SmoothShading, overdraw: 0.5 }), + new THREE.MeshDepthMaterial({ overdraw: 0.5 }), + new THREE.MeshNormalMaterial({ overdraw: 0.5 }), + new THREE.MeshBasicMaterial({ map: THREE.ImageUtils.loadTexture('textures/land_ocean_ice_cloud_2048.jpg') }), + new THREE.MeshBasicMaterial({ envMap: THREE.ImageUtils.loadTexture('textures/envmap.png', new THREE.SphericalReflectionMapping()), overdraw: 0.5 }), + new THREE.MeshBasicMaterial({ envMap: THREE.ImageUtils.loadTexture('textures/envmap.png', new THREE.SphericalRefractionMapping()), overdraw: 0.5 }) + + ]; + + for (var i = 0, l = geometry.faces.length; i < l; i++) { + + var face = geometry.faces[i]; + if (Math.random() > 0.5) face.materialIndex = Math.floor(Math.random() * materials.length); + + } + + materials.push(new THREE.MeshFaceMaterial(materials)); + + objects = []; + + for (var i = 0, l = materials.length; i < l; i++) { + + var sphere = new THREE.Mesh(geometry, materials[i]); + + sphere.position.x = (i % 5) * 200 - 400; + sphere.position.z = Math.floor(i / 5) * 200 - 200; + + sphere.rotation.x = Math.random() * 200 - 100; + sphere.rotation.y = Math.random() * 200 - 100; + sphere.rotation.z = Math.random() * 200 - 100; + + objects.push(sphere); + + scene.add(sphere); + + } + + var PI2 = Math.PI * 2; + var program = function (context) { + + context.beginPath(); + context.arc(0, 0, 0.5, 0, PI2, true); + context.fill(); + + } + + particleLight = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0xffffff, program: program })); + particleLight.scale.x = particleLight.scale.y = 8; + scene.add(particleLight); + + // Lights + + scene.add(new THREE.AmbientLight(Math.random() * 0x202020)); + + var directionalLight = new THREE.DirectionalLight(Math.random() * 0xffffff); + directionalLight.position.x = Math.random() - 0.5; + directionalLight.position.y = Math.random() - 0.5; + directionalLight.position.z = Math.random() - 0.5; + directionalLight.position.normalize(); + scene.add(directionalLight); + + pointLight = new THREE.PointLight(0xffffff, 1); + scene.add(pointLight); + + renderer = new THREE.CanvasRenderer(); + renderer.setSize(window.innerWidth, window.innerHeight); + container.appendChild(renderer.domElement); + + var debugCanvas = document.createElement('canvas'); + debugCanvas.width = 512; + debugCanvas.height = 512; + debugCanvas.style.position = 'absolute'; + debugCanvas.style.top = '0px'; + debugCanvas.style.left = '0px'; + + container.appendChild(debugCanvas); + + debugContext = debugCanvas.getContext('2d'); + debugContext.setTransform(1, 0, 0, 1, 256, 256); + debugContext.strokeStyle = '#000000'; + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + container.appendChild(stats.domElement); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + function loadImage(path) { + + var image = document.createElement('img'); + var texture = new THREE.Texture(image, THREE.UVMapping) + + image.onload = function () { texture.needsUpdate = true; }; + image.src = path; + + return texture; + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + var timer = Date.now() * 0.0001; + + camera.position.x = Math.cos(timer) * 1000; + camera.position.z = Math.sin(timer) * 1000; + camera.lookAt(scene.position); + + for (var i = 0, l = objects.length; i < l; i++) { + + var object = objects[i]; + + object.rotation.x += 0.01; + object.rotation.y += 0.005; + + } + + particleLight.position.x = Math.sin(timer * 7) * 300; + particleLight.position.y = Math.cos(timer * 5) * 400; + particleLight.position.z = Math.cos(timer * 3) * 300; + + pointLight.position.x = particleLight.position.x; + pointLight.position.y = particleLight.position.y; + pointLight.position.z = particleLight.position.z; + + renderer.render(scene, camera); + + } + +} \ No newline at end of file diff --git a/threejs/tests/canvas/canvas_particles_floor.ts b/threejs/tests/canvas/canvas_particles_floor.ts new file mode 100644 index 0000000000..4433138dcb --- /dev/null +++ b/threejs/tests/canvas/canvas_particles_floor.ts @@ -0,0 +1,131 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/canvas_particles_floor.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + // ------- + var SEPARATION = 100; + var AMOUNTX = 50; + var AMOUNTY = 50; + + var container, stats; + var camera, scene, renderer, particle; + var mouseX = 0, mouseY = 0; + + var windowHalfX = window.innerWidth / 2; + var windowHalfY = window.innerHeight / 2; + + init(); + animate(); + + function init() { + + container = document.createElement('div'); + document.body.appendChild(container); + + camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000); + camera.position.z = 1000; + + scene = new THREE.Scene(); + + var material = new THREE.SpriteMaterial(); + + for (var ix = 0; ix < AMOUNTX; ix++) { + + for (var iy = 0; iy < AMOUNTY; iy++) { + + particle = new THREE.Sprite(material); + particle.scale.y = 20; + particle.position.x = ix * SEPARATION - ((AMOUNTX * SEPARATION) / 2); + particle.position.z = iy * SEPARATION - ((AMOUNTY * SEPARATION) / 2); + scene.add(particle); + + } + + } + + renderer = new THREE.CanvasRenderer(); + renderer.setSize(window.innerWidth, window.innerHeight); + container.appendChild(renderer.domElement); + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + container.appendChild(stats.domElement); + + document.addEventListener('mousemove', onDocumentMouseMove, false); + document.addEventListener('touchstart', onDocumentTouchStart, false); + document.addEventListener('touchmove', onDocumentTouchMove, false); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + windowHalfX = window.innerWidth / 2; + windowHalfY = window.innerHeight / 2; + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + // + + function onDocumentMouseMove(event) { + + mouseX = event.clientX - windowHalfX; + mouseY = event.clientY - windowHalfY; + } + + function onDocumentTouchStart(event) { + + if (event.touches.length > 1) { + + event.preventDefault(); + + mouseX = event.touches[0].pageX - windowHalfX; + mouseY = event.touches[0].pageY - windowHalfY; + } + } + + function onDocumentTouchMove(event) { + + if (event.touches.length == 1) { + + event.preventDefault(); + + mouseX = event.touches[0].pageX - windowHalfX; + mouseY = event.touches[0].pageY - windowHalfY; + } + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + camera.position.x += (mouseX - camera.position.x) * .05; + camera.position.y += (- mouseY - camera.position.y) * .05; + camera.lookAt(scene.position); + + renderer.render(scene, camera); + + } +} \ No newline at end of file diff --git a/threejs/tests/css3d/css3d_periodictable.ts b/threejs/tests/css3d/css3d_periodictable.ts new file mode 100644 index 0000000000..6ce32c42f6 --- /dev/null +++ b/threejs/tests/css3d/css3d_periodictable.ts @@ -0,0 +1,353 @@ +/// +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/css3d_periodictable.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + var object: any; + // ------- + var table = [ + "H", "Hydrogen", "1.00794", 1, 1, + "He", "Helium", "4.002602", 18, 1, + "Li", "Lithium", "6.941", 1, 2, + "Be", "Beryllium", "9.012182", 2, 2, + "B", "Boron", "10.811", 13, 2, + "C", "Carbon", "12.0107", 14, 2, + "N", "Nitrogen", "14.0067", 15, 2, + "O", "Oxygen", "15.9994", 16, 2, + "F", "Fluorine", "18.9984032", 17, 2, + "Ne", "Neon", "20.1797", 18, 2, + "Na", "Sodium", "22.98976...", 1, 3, + "Mg", "Magnesium", "24.305", 2, 3, + "Al", "Aluminium", "26.9815386", 13, 3, + "Si", "Silicon", "28.0855", 14, 3, + "P", "Phosphorus", "30.973762", 15, 3, + "S", "Sulfur", "32.065", 16, 3, + "Cl", "Chlorine", "35.453", 17, 3, + "Ar", "Argon", "39.948", 18, 3, + "K", "Potassium", "39.948", 1, 4, + "Ca", "Calcium", "40.078", 2, 4, + "Sc", "Scandium", "44.955912", 3, 4, + "Ti", "Titanium", "47.867", 4, 4, + "V", "Vanadium", "50.9415", 5, 4, + "Cr", "Chromium", "51.9961", 6, 4, + "Mn", "Manganese", "54.938045", 7, 4, + "Fe", "Iron", "55.845", 8, 4, + "Co", "Cobalt", "58.933195", 9, 4, + "Ni", "Nickel", "58.6934", 10, 4, + "Cu", "Copper", "63.546", 11, 4, + "Zn", "Zinc", "65.38", 12, 4, + "Ga", "Gallium", "69.723", 13, 4, + "Ge", "Germanium", "72.63", 14, 4, + "As", "Arsenic", "74.9216", 15, 4, + "Se", "Selenium", "78.96", 16, 4, + "Br", "Bromine", "79.904", 17, 4, + "Kr", "Krypton", "83.798", 18, 4, + "Rb", "Rubidium", "85.4678", 1, 5, + "Sr", "Strontium", "87.62", 2, 5, + "Y", "Yttrium", "88.90585", 3, 5, + "Zr", "Zirconium", "91.224", 4, 5, + "Nb", "Niobium", "92.90628", 5, 5, + "Mo", "Molybdenum", "95.96", 6, 5, + "Tc", "Technetium", "(98)", 7, 5, + "Ru", "Ruthenium", "101.07", 8, 5, + "Rh", "Rhodium", "102.9055", 9, 5, + "Pd", "Palladium", "106.42", 10, 5, + "Ag", "Silver", "107.8682", 11, 5, + "Cd", "Cadmium", "112.411", 12, 5, + "In", "Indium", "114.818", 13, 5, + "Sn", "Tin", "118.71", 14, 5, + "Sb", "Antimony", "121.76", 15, 5, + "Te", "Tellurium", "127.6", 16, 5, + "I", "Iodine", "126.90447", 17, 5, + "Xe", "Xenon", "131.293", 18, 5, + "Cs", "Caesium", "132.9054", 1, 6, + "Ba", "Barium", "132.9054", 2, 6, + "La", "Lanthanum", "138.90547", 4, 9, + "Ce", "Cerium", "140.116", 5, 9, + "Pr", "Praseodymium", "140.90765", 6, 9, + "Nd", "Neodymium", "144.242", 7, 9, + "Pm", "Promethium", "(145)", 8, 9, + "Sm", "Samarium", "150.36", 9, 9, + "Eu", "Europium", "151.964", 10, 9, + "Gd", "Gadolinium", "157.25", 11, 9, + "Tb", "Terbium", "158.92535", 12, 9, + "Dy", "Dysprosium", "162.5", 13, 9, + "Ho", "Holmium", "164.93032", 14, 9, + "Er", "Erbium", "167.259", 15, 9, + "Tm", "Thulium", "168.93421", 16, 9, + "Yb", "Ytterbium", "173.054", 17, 9, + "Lu", "Lutetium", "174.9668", 18, 9, + "Hf", "Hafnium", "178.49", 4, 6, + "Ta", "Tantalum", "180.94788", 5, 6, + "W", "Tungsten", "183.84", 6, 6, + "Re", "Rhenium", "186.207", 7, 6, + "Os", "Osmium", "190.23", 8, 6, + "Ir", "Iridium", "192.217", 9, 6, + "Pt", "Platinum", "195.084", 10, 6, + "Au", "Gold", "196.966569", 11, 6, + "Hg", "Mercury", "200.59", 12, 6, + "Tl", "Thallium", "204.3833", 13, 6, + "Pb", "Lead", "207.2", 14, 6, + "Bi", "Bismuth", "208.9804", 15, 6, + "Po", "Polonium", "(209)", 16, 6, + "At", "Astatine", "(210)", 17, 6, + "Rn", "Radon", "(222)", 18, 6, + "Fr", "Francium", "(223)", 1, 7, + "Ra", "Radium", "(226)", 2, 7, + "Ac", "Actinium", "(227)", 4, 10, + "Th", "Thorium", "232.03806", 5, 10, + "Pa", "Protactinium", "231.0588", 6, 10, + "U", "Uranium", "238.02891", 7, 10, + "Np", "Neptunium", "(237)", 8, 10, + "Pu", "Plutonium", "(244)", 9, 10, + "Am", "Americium", "(243)", 10, 10, + "Cm", "Curium", "(247)", 11, 10, + "Bk", "Berkelium", "(247)", 12, 10, + "Cf", "Californium", "(251)", 13, 10, + "Es", "Einstenium", "(252)", 14, 10, + "Fm", "Fermium", "(257)", 15, 10, + "Md", "Mendelevium", "(258)", 16, 10, + "No", "Nobelium", "(259)", 17, 10, + "Lr", "Lawrencium", "(262)", 18, 10, + "Rf", "Rutherfordium", "(267)", 4, 7, + "Db", "Dubnium", "(268)", 5, 7, + "Sg", "Seaborgium", "(271)", 6, 7, + "Bh", "Bohrium", "(272)", 7, 7, + "Hs", "Hassium", "(270)", 8, 7, + "Mt", "Meitnerium", "(276)", 9, 7, + "Ds", "Darmstadium", "(281)", 10, 7, + "Rg", "Roentgenium", "(280)", 11, 7, + "Cn", "Copernicium", "(285)", 12, 7, + "Uut", "Unutrium", "(284)", 13, 7, + "Fl", "Flerovium", "(289)", 14, 7, + "Uup", "Ununpentium", "(288)", 15, 7, + "Lv", "Livermorium", "(293)", 16, 7, + "Uus", "Ununseptium", "(294)", 17, 7, + "Uuo", "Ununoctium", "(294)", 18, 7 + ]; + + var camera, scene, renderer; + var controls; + + var objects = []; + var targets = { table: [], sphere: [], helix: [], grid: [] }; + + init(); + animate(); + + function init() { + + camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 10000); + camera.position.z = 3000; + + scene = new THREE.Scene(); + + // table + + for (var i = 0; i < table.length; i += 5) { + + var element = document.createElement('div'); + element.className = 'element'; + element.style.backgroundColor = 'rgba(0,127,127,' + (Math.random() * 0.5 + 0.25) + ')'; + + var number = document.createElement('div'); + number.className = 'number'; + number.textContent = ((i / 5) + 1).toString(); + element.appendChild(number); + + var symbol = document.createElement('div'); + symbol.className = 'symbol'; + symbol.textContent = (table[i]).toString(); + element.appendChild(symbol); + + var details = document.createElement('div'); + details.className = 'details'; + details.innerHTML = table[i + 1] + '
    ' + table[i + 2]; + element.appendChild(details); + + object = new THREE.CSS3DObject(element); + object.position.x = Math.random() * 4000 - 2000; + object.position.y = Math.random() * 4000 - 2000; + object.position.z = Math.random() * 4000 - 2000; + scene.add(object); + + objects.push(object); + + // + object = new THREE.Object3D(); + object.position.x = (table[i + 3] * 140) - 1330; + object.position.y = - (table[i + 4] * 180) + 990; + + targets.table.push(object); + + } + + // sphere + + var vector = new THREE.Vector3(); + + for (var i = 0, l = objects.length; i < l; i++) { + + var phi = Math.acos(-1 + (2 * i) / l); + var theta = Math.sqrt(l * Math.PI) * phi; + + var object = new THREE.Object3D(); + + object.position.x = 800 * Math.cos(theta) * Math.sin(phi); + object.position.y = 800 * Math.sin(theta) * Math.sin(phi); + object.position.z = 800 * Math.cos(phi); + + vector.copy(object.position).multiplyScalar(2); + + object.lookAt(vector); + + targets.sphere.push(object); + + } + + // helix + + var vector = new THREE.Vector3(); + + for (var i = 0, l = objects.length; i < l; i++) { + + var phi = i * 0.175 + Math.PI; + + var object = new THREE.Object3D(); + + object.position.x = 900 * Math.sin(phi); + object.position.y = - (i * 8) + 450; + object.position.z = 900 * Math.cos(phi); + + vector.x = object.position.x * 2; + vector.y = object.position.y; + vector.z = object.position.z * 2; + + object.lookAt(vector); + + targets.helix.push(object); + + } + + // grid + + for (var i = 0; i < objects.length; i++) { + + var object = new THREE.Object3D(); + + object.position.x = ((i % 5) * 400) - 800; + object.position.y = (- (Math.floor(i / 5) % 5) * 400) + 800; + object.position.z = (Math.floor(i / 25)) * 1000 - 2000; + + targets.grid.push(object); + + } + + // + + renderer = new THREE.CSS3DRenderer(); + renderer.setSize(window.innerWidth, window.innerHeight); + renderer.domElement.style.position = 'absolute'; + document.getElementById('container').appendChild(renderer.domElement); + + // + + controls = new THREE.TrackballControls(camera, renderer.domElement); + controls.rotateSpeed = 0.5; + controls.minDistance = 500; + controls.maxDistance = 6000; + controls.addEventListener('change', render); + + var button = document.getElementById('table'); + button.addEventListener('click', function (event) { + + transform(targets.table, 2000); + + }, false); + + var button = document.getElementById('sphere'); + button.addEventListener('click', function (event) { + + transform(targets.sphere, 2000); + + }, false); + + var button = document.getElementById('helix'); + button.addEventListener('click', function (event) { + + transform(targets.helix, 2000); + + }, false); + + var button = document.getElementById('grid'); + button.addEventListener('click', function (event) { + + transform(targets.grid, 2000); + + }, false); + + transform(targets.table, 5000); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function transform(targets, duration) { + + TWEEN.removeAll(); + + for (var i = 0; i < objects.length; i++) { + + var object = objects[i]; + var target = targets[i]; + + new TWEEN.Tween(object.position) + .to({ x: target.position.x, y: target.position.y, z: target.position.z }, Math.random() * duration + duration) + .easing(TWEEN.Easing.Exponential.InOut) + .start(); + + new TWEEN.Tween(object.rotation) + .to({ x: target.rotation.x, y: target.rotation.y, z: target.rotation.z }, Math.random() * duration + duration) + .easing(TWEEN.Easing.Exponential.InOut) + .start(); + + } + new TWEEN.Tween(this) + .to({}, duration * 2) + .onUpdate(render) + .start(); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + render(); + + } + + function animate() { + + requestAnimationFrame(animate); + + TWEEN.update(); + + controls.update(); + + } + + function render() { + + renderer.render(scene, camera); + + } +} \ No newline at end of file diff --git a/threejs/tests/css3d/css3d_sprites.ts b/threejs/tests/css3d/css3d_sprites.ts new file mode 100644 index 0000000000..20760735a0 --- /dev/null +++ b/threejs/tests/css3d/css3d_sprites.ts @@ -0,0 +1,195 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/css3d_sprites.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + + // ------- + var camera, scene, renderer; + var controls; + + var particlesTotal = 512; + var positions = []; + var objects = []; + var current = 0; + + init(); + animate(); + + function init() { + + camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 5000); + camera.position.set(600, 400, 1500); + camera.lookAt(new THREE.Vector3()); + + scene = new THREE.Scene(); + + var sprite = document.createElement('img'); + sprite.addEventListener('load', function (event) { + + for (var i = 0, j = 0; i < particlesTotal; i++, j += 3) { + + var canvas = document.createElement('canvas'); + canvas.width = sprite.width; + canvas.height = sprite.height; + + var context = canvas.getContext('2d'); + context.drawImage(sprite, 0, 0); + + var object = new THREE.CSS3DSprite(canvas); + object.position.x = Math.random() * 4000 - 2000, + object.position.y = Math.random() * 4000 - 2000, + object.position.z = Math.random() * 4000 - 2000 + scene.add(object); + + objects.push(object); + + } + + transition(); + + }, false); + sprite.src = 'textures/sprite.png'; + + // Plane + + var amountX = 16; + var amountZ = 32; + var separation = 150; + var offsetX = ((amountX - 1) * separation) / 2; + var offsetZ = ((amountZ - 1) * separation) / 2; + + for (var i = 0; i < particlesTotal; i++) { + + var x = (i % amountX) * separation; + var z = Math.floor(i / amountX) * separation; + var y = (Math.sin(x * 0.5) + Math.sin(z * 0.5)) * 200; + + positions.push(x - offsetX, y, z - offsetZ); + + } + + // Cube + + var amount = 8; + var separation = 150; + var offset = ((amount - 1) * separation) / 2; + + for (var i = 0; i < particlesTotal; i++) { + + var x = (i % amount) * separation; + var y = Math.floor((i / amount) % amount) * separation; + var z = Math.floor(i / (amount * amount)) * separation; + + positions.push(x - offset, y - offset, z - offset); + + } + + // Random + + for (var i = 0; i < particlesTotal; i++) { + + positions.push( + Math.random() * 4000 - 2000, + Math.random() * 4000 - 2000, + Math.random() * 4000 - 2000 + ); + + } + + // Sphere + + var radius = 750; + + for (var i = 0; i < particlesTotal; i++) { + + var phi = Math.acos(-1 + (2 * i) / particlesTotal); + var theta = Math.sqrt(particlesTotal * Math.PI) * phi; + + positions.push( + radius * Math.cos(theta) * Math.sin(phi), + radius * Math.sin(theta) * Math.sin(phi), + radius * Math.cos(phi) + ); + + } + + // + + renderer = new THREE.CSS3DRenderer(); + renderer.setSize(window.innerWidth, window.innerHeight); + renderer.domElement.style.position = 'absolute'; + document.getElementById('container').appendChild(renderer.domElement); + + // + + controls = new THREE.TrackballControls(camera, renderer.domElement); + controls.rotateSpeed = 0.5; + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + function transition() { + + var offset = current * particlesTotal * 3; + var duration = 2000; + + for (var i = 0, j = offset; i < particlesTotal; i++, j += 3) { + + var object = objects[i]; + + new TWEEN.Tween(object.position) + .to({ + x: positions[j], + y: positions[j + 1], + z: positions[j + 2] + }, Math.random() * duration + duration) + .easing(TWEEN.Easing.Exponential.InOut) + .start(); + + } + + new TWEEN.Tween(this) + .to({}, duration * 3) + .onComplete(transition) + .start(); + + current = (current + 1) % 4; + + } + + function animate() { + + requestAnimationFrame(animate); + + TWEEN.update(); + controls.update(); + + var time = performance.now(); + + for (var i = 0, l = objects.length; i < l; i++) { + + var object = objects[i]; + var scale = Math.sin((Math.floor(object.position.x) + time) * 0.002) * 0.3 + 1; + object.scale.set(scale, scale, scale); + + } + + renderer.render(scene, camera); + + } +} \ No newline at end of file diff --git a/threejs/tests/math/test_unit_math.ts b/threejs/tests/math/test_unit_math.ts new file mode 100644 index 0000000000..f1c3818ccc --- /dev/null +++ b/threejs/tests/math/test_unit_math.ts @@ -0,0 +1,3084 @@ +/// +/// +/// + + +// https://github.com/mrdoob/three.js/tree/master/test/unit/math + +()=>{ + var x = 2; + var y = 3; + var z = 4; + var w = 5; + + var negInf2 = new THREE.Vector2( -Infinity, -Infinity ); + var posInf2 = new THREE.Vector2( Infinity, Infinity ); + + var zero2 = new THREE.Vector2(); + var one2 = new THREE.Vector2( 1, 1 ); + var two2 = new THREE.Vector2( 2, 2 ); + + var negInf3 = new THREE.Vector3( -Infinity, -Infinity, -Infinity ); + var posInf3 = new THREE.Vector3( Infinity, Infinity, Infinity ); + + var zero3 = new THREE.Vector3(); + var one3 = new THREE.Vector3( 1, 1, 1 ); + var two3 = new THREE.Vector3( 2, 2, 2 ); + + (QUnit.module)( "Box2" ); + + test( "constructor", function() { + var a = new THREE.Box2(); + ok( a.min.equals( posInf2 ), "Passed!" ); + ok( a.max.equals( negInf2 ), "Passed!" ); + + a = new THREE.Box2( zero2.clone(), zero2.clone() ); + ok( a.min.equals( zero2 ), "Passed!" ); + ok( a.max.equals( zero2 ), "Passed!" ); + + a = new THREE.Box2( zero2.clone(), one2.clone() ); + ok( a.min.equals( zero2 ), "Passed!" ); + ok( a.max.equals( one2 ), "Passed!" ); + }); + + test( "copy", function() { + var a = new THREE.Box2( zero2.clone(), one2.clone() ); + var b = new THREE.Box2().copy( a ); + ok( b.min.equals( zero2 ), "Passed!" ); + ok( b.max.equals( one2 ), "Passed!" ); + + // ensure that it is a true copy + a.min = zero2; + a.max = one2; + ok( b.min.equals( zero2 ), "Passed!" ); + ok( b.max.equals( one2 ), "Passed!" ); + }); + + test( "set", function() { + var a = new THREE.Box2(); + + a.set( zero2, one2 ); + ok( a.min.equals( zero2 ), "Passed!" ); + ok( a.max.equals( one2 ), "Passed!" ); + }); + + test( "empty/makeEmpty", function() { + var a = new THREE.Box2(); + + ok( a.empty(), "Passed!" ); + + var a = new THREE.Box2( zero2.clone(), one2.clone() ); + ok( ! a.empty(), "Passed!" ); + + a.makeEmpty(); + ok( a.empty(), "Passed!" ); + }); + + test( "center", function() { + var a = new THREE.Box2( zero2.clone(), zero2.clone() ); + + ok( a.center().equals( zero2 ), "Passed!" ); + + a = new THREE.Box2( zero2, one2 ); + var midpoint = one2.clone().multiplyScalar( 0.5 ); + ok( a.center().equals( midpoint ), "Passed!" ); + }); + + test( "size", function() { + var a = new THREE.Box2( zero2.clone(), zero2.clone() ); + + ok( a.size().equals( zero2 ), "Passed!" ); + + a = new THREE.Box2( zero2.clone(), one2.clone() ); + ok( a.size().equals( one2 ), "Passed!" ); + }); + + test( "expandByPoint", function() { + var a = new THREE.Box2( zero2.clone(), zero2.clone() ); + + a.expandByPoint( zero2 ); + ok( a.size().equals( zero2 ), "Passed!" ); + + a.expandByPoint( one2 ); + ok( a.size().equals( one2 ), "Passed!" ); + + a.expandByPoint( one2.clone().negate() ); + ok( a.size().equals( one2.clone().multiplyScalar( 2 ) ), "Passed!" ); + ok( a.center().equals( zero2 ), "Passed!" ); + }); + + test( "expandByVector", function() { + var a = new THREE.Box2( zero2.clone(), zero2.clone() ); + + a.expandByVector( zero2 ); + ok( a.size().equals( zero2 ), "Passed!" ); + + a.expandByVector( one2 ); + ok( a.size().equals( one2.clone().multiplyScalar( 2 ) ), "Passed!" ); + ok( a.center().equals( zero2 ), "Passed!" ); + }); + + test( "expandByScalar", function() { + var a = new THREE.Box2( zero2.clone(), zero2.clone() ); + + a.expandByScalar( 0 ); + ok( a.size().equals( zero2 ), "Passed!" ); + + a.expandByScalar( 1 ); + ok( a.size().equals( one2.clone().multiplyScalar( 2 ) ), "Passed!" ); + ok( a.center().equals( zero2 ), "Passed!" ); + }); + + test( "containsPoint", function() { + var a = new THREE.Box2( zero2.clone(), zero2.clone() ); + + ok( a.containsPoint( zero2 ), "Passed!" ); + ok( ! a.containsPoint( one2 ), "Passed!" ); + + a.expandByScalar( 1 ); + ok( a.containsPoint( zero2 ), "Passed!" ); + ok( a.containsPoint( one2 ), "Passed!" ); + ok( a.containsPoint( one2.clone().negate() ), "Passed!" ); + }); + + test( "containsBox", function() { + var a = new THREE.Box2( zero2.clone(), zero2.clone() ); + var b = new THREE.Box2( zero2.clone(), one2.clone() ); + var c = new THREE.Box2( one2.clone().negate(), one2.clone() ); + + ok( a.containsBox( a ), "Passed!" ); + ok( ! a.containsBox( b ), "Passed!" ); + ok( ! a.containsBox( c ), "Passed!" ); + + ok( b.containsBox( a ), "Passed!" ); + ok( c.containsBox( a ), "Passed!" ); + ok( ! b.containsBox( c ), "Passed!" ); + }); + + test( "getParameter", function() { + var a = new THREE.Box2( zero2.clone(), one2.clone() ); + var b = new THREE.Box2( one2.clone().negate(), one2.clone() ); + + ok( a.getParameter( new THREE.Vector2( 0, 0 ) ).equals( new THREE.Vector2( 0, 0 ) ), "Passed!" ); + ok( a.getParameter( new THREE.Vector2( 1, 1 ) ).equals( new THREE.Vector2( 1, 1 ) ), "Passed!" ); + + ok( b.getParameter( new THREE.Vector2( -1, -1 ) ).equals( new THREE.Vector2( 0, 0 ) ), "Passed!" ); + ok( b.getParameter( new THREE.Vector2( 0, 0 ) ).equals( new THREE.Vector2( 0.5, 0.5 ) ), "Passed!" ); + ok( b.getParameter( new THREE.Vector2( 1, 1 ) ).equals( new THREE.Vector2( 1, 1 ) ), "Passed!" ); + }); + + test( "clampPoint", function() { + var a = new THREE.Box2( zero2.clone(), zero2.clone() ); + var b = new THREE.Box2( one2.clone().negate(), one2.clone() ); + + ok( a.clampPoint( new THREE.Vector2( 0, 0 ) ).equals( new THREE.Vector2( 0, 0 ) ), "Passed!" ); + ok( a.clampPoint( new THREE.Vector2( 1, 1 ) ).equals( new THREE.Vector2( 0, 0 ) ), "Passed!" ); + ok( a.clampPoint( new THREE.Vector2( -1, -1 ) ).equals( new THREE.Vector2( 0, 0 ) ), "Passed!" ); + + ok( b.clampPoint( new THREE.Vector2( 2, 2 ) ).equals( new THREE.Vector2( 1, 1 ) ), "Passed!" ); + ok( b.clampPoint( new THREE.Vector2( 1, 1 ) ).equals( new THREE.Vector2( 1, 1 ) ), "Passed!" ); + ok( b.clampPoint( new THREE.Vector2( 0, 0 ) ).equals( new THREE.Vector2( 0, 0 ) ), "Passed!" ); + ok( b.clampPoint( new THREE.Vector2( -1, -1 ) ).equals( new THREE.Vector2( -1, -1 ) ), "Passed!" ); + ok( b.clampPoint( new THREE.Vector2( -2, -2 ) ).equals( new THREE.Vector2( -1, -1 ) ), "Passed!" ); + }); + + test( "distanceToPoint", function() { + var a = new THREE.Box2( zero2.clone(), zero2.clone() ); + var b = new THREE.Box2( one2.clone().negate(), one2.clone() ); + + ok( a.distanceToPoint( new THREE.Vector2( 0, 0 ) ) == 0, "Passed!" ); + ok( a.distanceToPoint( new THREE.Vector2( 1, 1 ) ) == Math.sqrt( 2 ), "Passed!" ); + ok( a.distanceToPoint( new THREE.Vector2( -1, -1 ) ) == Math.sqrt( 2 ), "Passed!" ); + + ok( b.distanceToPoint( new THREE.Vector2( 2, 2 ) ) == Math.sqrt( 2 ), "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector2( 1, 1 ) ) == 0, "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector2( 0, 0 ) ) == 0, "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector2( -1, -1 ) ) == 0, "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector2( -2, -2 ) ) == Math.sqrt( 2 ), "Passed!" ); + }); + + test( "distanceToPoint", function() { + var a = new THREE.Box2( zero2.clone(), zero2.clone() ); + var b = new THREE.Box2( one2.clone().negate(), one2.clone() ); + + ok( a.distanceToPoint( new THREE.Vector2( 0, 0 ) ) == 0, "Passed!" ); + ok( a.distanceToPoint( new THREE.Vector2( 1, 1 ) ) == Math.sqrt( 2 ), "Passed!" ); + ok( a.distanceToPoint( new THREE.Vector2( -1, -1 ) ) == Math.sqrt( 2 ), "Passed!" ); + + ok( b.distanceToPoint( new THREE.Vector2( 2, 2 ) ) == Math.sqrt( 2 ), "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector2( 1, 1 ) ) == 0, "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector2( 0, 0 ) ) == 0, "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector2( -1, -1 ) ) == 0, "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector2( -2, -2 ) ) == Math.sqrt( 2 ), "Passed!" ); + }); + + test( "isIntersectionBox", function() { + var a = new THREE.Box2( zero2.clone(), zero2.clone() ); + var b = new THREE.Box2( zero2.clone(), one2.clone() ); + var c = new THREE.Box2( one2.clone().negate(), one2.clone() ); + + ok( a.isIntersectionBox( a ), "Passed!" ); + ok( a.isIntersectionBox( b ), "Passed!" ); + ok( a.isIntersectionBox( c ), "Passed!" ); + + ok( b.isIntersectionBox( a ), "Passed!" ); + ok( c.isIntersectionBox( a ), "Passed!" ); + ok( b.isIntersectionBox( c ), "Passed!" ); + + b.translate( new THREE.Vector2( 2, 2 ) ); + ok( ! a.isIntersectionBox( b ), "Passed!" ); + ok( ! b.isIntersectionBox( a ), "Passed!" ); + ok( ! b.isIntersectionBox( c ), "Passed!" ); + }); + + test( "intersect", function() { + var a = new THREE.Box2( zero2.clone(), zero2.clone() ); + var b = new THREE.Box2( zero2.clone(), one2.clone() ); + var c = new THREE.Box2( one2.clone().negate(), one2.clone() ); + + ok( a.clone().intersect( a ).equals( a ), "Passed!" ); + ok( a.clone().intersect( b ).equals( a ), "Passed!" ); + ok( b.clone().intersect( b ).equals( b ), "Passed!" ); + ok( a.clone().intersect( c ).equals( a ), "Passed!" ); + ok( b.clone().intersect( c ).equals( b ), "Passed!" ); + ok( c.clone().intersect( c ).equals( c ), "Passed!" ); + }); + + test( "union", function() { + var a = new THREE.Box2( zero2.clone(), zero2.clone() ); + var b = new THREE.Box2( zero2.clone(), one2.clone() ); + var c = new THREE.Box2( one2.clone().negate(), one2.clone() ); + + ok( a.clone().union( a ).equals( a ), "Passed!" ); + ok( a.clone().union( b ).equals( b ), "Passed!" ); + ok( a.clone().union( c ).equals( c ), "Passed!" ); + ok( b.clone().union( c ).equals( c ), "Passed!" ); + }); + + test( "translate", function() { + var a = new THREE.Box2( zero2.clone(), zero2.clone() ); + var b = new THREE.Box2( zero2.clone(), one2.clone() ); + var c = new THREE.Box2( one2.clone().negate(), one2.clone() ); + var d = new THREE.Box2( one2.clone().negate(), zero2.clone() ); + + ok( a.clone().translate( one2 ).equals( new THREE.Box2( one2, one2 ) ), "Passed!" ); + ok( a.clone().translate( one2 ).translate( one2.clone().negate() ).equals( a ), "Passed!" ); + ok( d.clone().translate( one2 ).equals( b ), "Passed!" ); + ok( b.clone().translate( one2.clone().negate() ).equals( d ), "Passed!" ); + }); + + test( "constructor", function() { + var a = new THREE.Box3(); + ok( a.min.equals( posInf3 ), "Passed!" ); + ok( a.max.equals( negInf3 ), "Passed!" ); + + a = new THREE.Box3( zero3.clone(), zero3.clone() ); + ok( a.min.equals( zero3 ), "Passed!" ); + ok( a.max.equals( zero3 ), "Passed!" ); + + a = new THREE.Box3( zero3.clone(), one3.clone() ); + ok( a.min.equals( zero3 ), "Passed!" ); + ok( a.max.equals( one3 ), "Passed!" ); + }); + + test( "copy", function() { + var a = new THREE.Box3( zero3.clone(), one3.clone() ); + var b = new THREE.Box3().copy( a ); + ok( b.min.equals( zero3 ), "Passed!" ); + ok( b.max.equals( one3 ), "Passed!" ); + + // ensure that it is a true copy + a.min = zero3; + a.max = one3; + ok( b.min.equals( zero3 ), "Passed!" ); + ok( b.max.equals( one3 ), "Passed!" ); + }); + + test( "set", function() { + var a = new THREE.Box3(); + + a.set( zero3, one3 ); + ok( a.min.equals( zero3 ), "Passed!" ); + ok( a.max.equals( one3 ), "Passed!" ); + }); + + test( "empty/makeEmpty", function() { + var a = new THREE.Box3(); + + ok( a.empty(), "Passed!" ); + + var a = new THREE.Box3( zero3.clone(), one3.clone() ); + ok( ! a.empty(), "Passed!" ); + + a.makeEmpty(); + ok( a.empty(), "Passed!" ); + }); + + test( "center", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + + ok( a.center().equals( zero3 ), "Passed!" ); + + a = new THREE.Box3( zero3.clone(), one3.clone() ); + var midpoint = one3.clone().multiplyScalar( 0.5 ); + ok( a.center().equals( midpoint ), "Passed!" ); + }); + + test( "size", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + + ok( a.size().equals( zero3 ), "Passed!" ); + + a = new THREE.Box3( zero3.clone(), one3.clone() ); + ok( a.size().equals( one3 ), "Passed!" ); + }); + + test( "expandByPoint", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + + a.expandByPoint( zero3 ); + ok( a.size().equals( zero3 ), "Passed!" ); + + a.expandByPoint( one3 ); + ok( a.size().equals( one3 ), "Passed!" ); + + a.expandByPoint( one3.clone().negate() ); + ok( a.size().equals( one3.clone().multiplyScalar( 2 ) ), "Passed!" ); + ok( a.center().equals( zero3 ), "Passed!" ); + }); + + test( "expandByVector", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + + a.expandByVector( zero3 ); + ok( a.size().equals( zero3 ), "Passed!" ); + + a.expandByVector( one3 ); + ok( a.size().equals( one3.clone().multiplyScalar( 2 ) ), "Passed!" ); + ok( a.center().equals( zero3 ), "Passed!" ); + }); + + test( "expandByScalar", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + + a.expandByScalar( 0 ); + ok( a.size().equals( zero3 ), "Passed!" ); + + a.expandByScalar( 1 ); + ok( a.size().equals( one3.clone().multiplyScalar( 2 ) ), "Passed!" ); + ok( a.center().equals( zero3 ), "Passed!" ); + }); + + test( "containsPoint", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + + ok( a.containsPoint( zero3 ), "Passed!" ); + ok( ! a.containsPoint( one3 ), "Passed!" ); + + a.expandByScalar( 1 ); + ok( a.containsPoint( zero3 ), "Passed!" ); + ok( a.containsPoint( one3 ), "Passed!" ); + ok( a.containsPoint( one3.clone().negate() ), "Passed!" ); + }); + + test( "containsBox", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + var b = new THREE.Box3( zero3.clone(), one3.clone() ); + var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); + + ok( a.containsBox( a ), "Passed!" ); + ok( ! a.containsBox( b ), "Passed!" ); + ok( ! a.containsBox( c ), "Passed!" ); + + ok( b.containsBox( a ), "Passed!" ); + ok( c.containsBox( a ), "Passed!" ); + ok( ! b.containsBox( c ), "Passed!" ); + }); + + test( "getParameter", function() { + var a = new THREE.Box3( zero3.clone(), one3.clone() ); + var b = new THREE.Box3( one3.clone().negate(), one3.clone() ); + + ok( a.getParameter( new THREE.Vector3( 0, 0, 0 ) ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + ok( a.getParameter( new THREE.Vector3( 1, 1, 1 ) ).equals( new THREE.Vector3( 1, 1, 1 ) ), "Passed!" ); + + ok( b.getParameter( new THREE.Vector3( -1, -1, -1 ) ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + ok( b.getParameter( new THREE.Vector3( 0, 0, 0 ) ).equals( new THREE.Vector3( 0.5, 0.5, 0.5 ) ), "Passed!" ); + ok( b.getParameter( new THREE.Vector3( 1, 1, 1 ) ).equals( new THREE.Vector3( 1, 1, 1 ) ), "Passed!" ); + }); + + test( "clampPoint", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + var b = new THREE.Box3( one3.clone().negate(), one3.clone() ); + + ok( a.clampPoint( new THREE.Vector3( 0, 0, 0 ) ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + ok( a.clampPoint( new THREE.Vector3( 1, 1, 1 ) ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + ok( a.clampPoint( new THREE.Vector3( -1, -1, -1 ) ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + + ok( b.clampPoint( new THREE.Vector3( 2, 2, 2 ) ).equals( new THREE.Vector3( 1, 1, 1 ) ), "Passed!" ); + ok( b.clampPoint( new THREE.Vector3( 1, 1, 1 ) ).equals( new THREE.Vector3( 1, 1, 1 ) ), "Passed!" ); + ok( b.clampPoint( new THREE.Vector3( 0, 0, 0 ) ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + ok( b.clampPoint( new THREE.Vector3( -1, -1, -1 ) ).equals( new THREE.Vector3( -1, -1, -1 ) ), "Passed!" ); + ok( b.clampPoint( new THREE.Vector3( -2, -2, -2 ) ).equals( new THREE.Vector3( -1, -1, -1 ) ), "Passed!" ); + }); + + test( "distanceToPoint", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + var b = new THREE.Box3( one3.clone().negate(), one3.clone() ); + + ok( a.distanceToPoint( new THREE.Vector3( 0, 0, 0 ) ) == 0, "Passed!" ); + ok( a.distanceToPoint( new THREE.Vector3( 1, 1, 1 ) ) == Math.sqrt( 3 ), "Passed!" ); + ok( a.distanceToPoint( new THREE.Vector3( -1, -1, -1 ) ) == Math.sqrt( 3 ), "Passed!" ); + + ok( b.distanceToPoint( new THREE.Vector3( 2, 2, 2 ) ) == Math.sqrt( 3 ), "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector3( 1, 1, 1 ) ) == 0, "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector3( 0, 0, 0 ) ) == 0, "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector3( -1, -1, -1 ) ) == 0, "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector3( -2, -2, -2 ) ) == Math.sqrt( 3 ), "Passed!" ); + }); + + test( "distanceToPoint", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + var b = new THREE.Box3( one3.clone().negate(), one3.clone() ); + + ok( a.distanceToPoint( new THREE.Vector3( 0, 0, 0 ) ) == 0, "Passed!" ); + ok( a.distanceToPoint( new THREE.Vector3( 1, 1, 1 ) ) == Math.sqrt( 3 ), "Passed!" ); + ok( a.distanceToPoint( new THREE.Vector3( -1, -1, -1 ) ) == Math.sqrt( 3 ), "Passed!" ); + + ok( b.distanceToPoint( new THREE.Vector3( 2, 2, 2 ) ) == Math.sqrt( 3 ), "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector3( 1, 1, 1 ) ) == 0, "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector3( 0, 0, 0 ) ) == 0, "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector3( -1, -1, -1 ) ) == 0, "Passed!" ); + ok( b.distanceToPoint( new THREE.Vector3( -2, -2, -2 ) ) == Math.sqrt( 3 ), "Passed!" ); + }); + + test( "isIntersectionBox", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + var b = new THREE.Box3( zero3.clone(), one3.clone() ); + var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); + + ok( a.isIntersectionBox( a ), "Passed!" ); + ok( a.isIntersectionBox( b ), "Passed!" ); + ok( a.isIntersectionBox( c ), "Passed!" ); + + ok( b.isIntersectionBox( a ), "Passed!" ); + ok( c.isIntersectionBox( a ), "Passed!" ); + ok( b.isIntersectionBox( c ), "Passed!" ); + + b.translate( new THREE.Vector3( 2, 2, 2 ) ); + ok( ! a.isIntersectionBox( b ), "Passed!" ); + ok( ! b.isIntersectionBox( a ), "Passed!" ); + ok( ! b.isIntersectionBox( c ), "Passed!" ); + }); + + test( "getBoundingSphere", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + var b = new THREE.Box3( zero3.clone(), one3.clone() ); + var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); + + ok( a.getBoundingSphere().equals( new THREE.Sphere( zero3, 0 ) ), "Passed!" ); + ok( b.getBoundingSphere().equals( new THREE.Sphere( one3.clone().multiplyScalar( 0.5 ), Math.sqrt( 3 ) * 0.5 ) ), "Passed!" ); + ok( c.getBoundingSphere().equals( new THREE.Sphere( zero3, Math.sqrt( 12 ) * 0.5 ) ), "Passed!" ); + }); + + test( "intersect", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + var b = new THREE.Box3( zero3.clone(), one3.clone() ); + var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); + + ok( a.clone().intersect( a ).equals( a ), "Passed!" ); + ok( a.clone().intersect( b ).equals( a ), "Passed!" ); + ok( b.clone().intersect( b ).equals( b ), "Passed!" ); + ok( a.clone().intersect( c ).equals( a ), "Passed!" ); + ok( b.clone().intersect( c ).equals( b ), "Passed!" ); + ok( c.clone().intersect( c ).equals( c ), "Passed!" ); + }); + + test( "union", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + var b = new THREE.Box3( zero3.clone(), one3.clone() ); + var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); + + ok( a.clone().union( a ).equals( a ), "Passed!" ); + ok( a.clone().union( b ).equals( b ), "Passed!" ); + ok( a.clone().union( c ).equals( c ), "Passed!" ); + ok( b.clone().union( c ).equals( c ), "Passed!" ); + }); + + var compareBox = function ( a, b, threshold? ) { + threshold = threshold || 0.0001; + return ( a.min.distanceTo( b.min ) < threshold && + a.max.distanceTo( b.max ) < threshold ); + }; + + test( "applyMatrix4", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + var b = new THREE.Box3( zero3.clone(), one3.clone() ); + var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); + var d = new THREE.Box3( one3.clone().negate(), zero3.clone() ); + + var m = new THREE.Matrix4().makeTranslation( 1, -2, 1 ); + var t1 = new THREE.Vector3( 1, -2, 1 ); + + ok( compareBox( a.clone().applyMatrix4( m ), a.clone().translate( t1 ) ), "Passed!" ); + ok( compareBox( b.clone().applyMatrix4( m ), b.clone().translate( t1 ) ), "Passed!" ); + ok( compareBox( c.clone().applyMatrix4( m ), c.clone().translate( t1 ) ), "Passed!" ); + ok( compareBox( d.clone().applyMatrix4( m ), d.clone().translate( t1 ) ), "Passed!" ); + }); + + test( "translate", function() { + var a = new THREE.Box3( zero3.clone(), zero3.clone() ); + var b = new THREE.Box3( zero3.clone(), one3.clone() ); + var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); + var d = new THREE.Box3( one3.clone().negate(), zero3.clone() ); + + ok( a.clone().translate( one3 ).equals( new THREE.Box3( one3, one3 ) ), "Passed!" ); + ok( a.clone().translate( one3 ).translate( one3.clone().negate() ).equals( a ), "Passed!" ); + ok( d.clone().translate( one3 ).equals( b ), "Passed!" ); + ok( b.clone().translate( one3.clone().negate() ).equals( d ), "Passed!" ); + }); + + test( "constructor", function(){ + var c = new THREE.Color(); + ok( c.r, "Red: " + c.r ); + ok( c.g, "Green: " + c.g ); + ok( c.b, "Blue: " + c.g ); + }); + + test( "copyHex", function(){ + var c = new THREE.Color(); + var c2 = new THREE.Color(0xF5FFFA); + c.copy(c2); + ok(c.getHex() == c2.getHex(), "Hex c: " + c.getHex() + " Hex c2: " + c2.getHex()); + }); + + test( "copyColorString", function(){ + var c = new THREE.Color(); + var c2 = new THREE.Color('ivory'); + c.copy(c2); + ok(c.getHex() == c2.getHex(), "Hex c: " + c.getHex() + " Hex c2: " + c2.getHex()); + }); + + test( "setRGB", function(){ + var c = new THREE.Color() + c.setRGB(255, 2, 1); + ok( c.r == 255, "Red: " + c.r ); + ok( c.g == 2, "Green: " + c.g ); + ok( c.b == 1, "Blue: " + c.b ); + }); + + test( "copyGammaToLinear", function(){ + var c = new THREE.Color(); + var c2 = new THREE.Color(); + c2.setRGB(2, 4, 8) + c.copyGammaToLinear(c2) + ok( c.r == 4, "Red c: " + c.r + " Red c2: " + c2.r); + ok( c.g == 16, "Green c: " + c.g + " Green c2: " + c2.g); + ok( c.b == 64, "Blue c: " + c.b + " Blue c2: " + c2.b); + }); + + test( "copyLinearToGamma", function(){ + var c = new THREE.Color(); + var c2 = new THREE.Color(); + c2.setRGB(4, 9, 16) + c.copyLinearToGamma(c2) + ok( c.r == 2, "Red c: " + c.r + " Red c2: " + c2.r); + ok( c.g == 3, "Green c: " + c.g + " Green c2: " + c2.g); + ok( c.b == 4, "Blue c: " + c.b + " Blue c2: " + c2.b); + }); + + + test( "convertGammaToLinear", function(){ + var c = new THREE.Color(); + c.setRGB(2, 4, 8) + c.convertGammaToLinear() + ok( c.r == 4, "Red: " + c.r ); + ok( c.g == 16, "Green: " + c.g ); + ok( c.b == 64, "Blue: " + c.b ); + }); + + + test( "convertLinearToGamma", function(){ + var c = new THREE.Color(); + c.setRGB(4, 9, 16) + c.convertLinearToGamma() + ok( c.r == 2, "Red: " + c.r ); + ok( c.g == 3, "Green: " + c.g ); + ok( c.b == 4, "Blue: " + c.b ); + }); + + test("setWithNum", function(){ + var c = new THREE.Color(); + c.set(0xFF0000); + ok( c.r == 1, "Red: " + c.r ); + ok( c.g == 0, "Green: " + c.g ); + ok( c.b == 0, "Blue: " + c.b ); + }); + + + test( "setWithString", function(){ + var c = new THREE.Color(); + c.set('silver'); + ok(c.getHex() == 0xC0C0C0, "Hex c: " + c.getHex()); + }); + + + test( "clone", function(){ + var c = new THREE.Color('teal'); + var c2 = c.clone(); + ok(c2.getHex() == 0x008080, "Hex c2: " + c2.getHex()); + }); + + test( "lerp", function(){ + var c = new THREE.Color(); + var c2 = new THREE.Color(); + c.setRGB(0, 0, 0); + c.lerp(c2, 2); + ok( c.r == 2, "Red: " + c.r ); + ok( c.g == 2, "Green: " + c.g ); + ok( c.b == 2, "Blue: " + c.b ); + + }); + + + test( "setStyleRGBRed", function(){ + var c = new THREE.Color(); + c.setStyle('rgb(255,0,0)'); + ok( c.r == 1, "Red: " + c.r ); + ok( c.g == 0, "Green: " + c.g ); + ok( c.b == 0, "Blue: " + c.b ); + }); + + test( "setStyleRGBPercent", function(){ + var c = new THREE.Color(); + c.setStyle('rgb(100%,50%,10%)'); + ok( c.r == 1, "Red: " + c.r ); + ok( c.g == 0.5, "Green: " + c.g ); + ok( c.b == 0.1, "Blue: " + c.b ); + }); + + test( "setStyleHexSkyBlue", function(){ + var c = new THREE.Color(); + c.setStyle('#87CEEB'); + ok(c.getHex() == 0x87CEEB, "Hex c: " + c.getHex()); + }); + + test( "setStyleHex2Olive", function(){ + var c = new THREE.Color(); + c.setStyle('#F00'); + ok(c.getHex() == 0xFF0000, "Hex c: " + c.getHex()); + }); + + test( "setStyleColorName", function(){ + var c = new THREE.Color(); + c.setStyle('powderblue'); + ok(c.getHex() == 0xB0E0E6, "Hex c: " + c.getHex()); + }); + + + test( "getHex", function(){ + var c = new THREE.Color('red'); + var res = c.getHex(); + ok( res == 0xFF0000, "Hex: " + res ); + }); + + test( "setHex", function(){ + var c = new THREE.Color(); + c.setHex(0xFA8072); + ok( c.getHex() == 0xFA8072, "Hex: " + c.getHex()); + }); + + test( "getHexString", function(){ + var c = new THREE.Color('tomato'); + var res = c.getHexString(); + ok( res == 'ff6347', "Hex: " + res ); + }); + + test( "getStyle", function(){ + var c = new THREE.Color('plum'); + var res = c.getStyle(); + ok( res == 'rgb(221,160,221)', "style: " + res ); + }); + + test( "getHSL", function () { + var c = new THREE.Color( 0x80ffff ); + var hsl = c.getHSL(); + + ok( hsl.h == 0.5, "hue: " + hsl.h ); + ok( hsl.s == 1.0, "saturation: " + hsl.s ); + + + //ok( (Math.round(parseFloat(hsl.l)*100)/100) == 0.75, "lightness: " + hsl.l ); + ok( (Math.round(hsl.l*100)/100) == 0.75, "lightness: " + hsl.l ); + }); + + test( "setHSL", function () { + var c = new THREE.Color(); + c.setHSL(0.75, 1.0, 0.25); + var hsl = c.getHSL(); + + ok( hsl.h == 0.75, "hue: " + hsl.h ); + ok( hsl.s == 1.00, "saturation: " + hsl.s ); + ok( hsl.l == 0.25, "lightness: " + hsl.l ); + }); + + var unit3 = new THREE.Vector3( 1, 0, 0 ); + + var planeEquals = function ( a, b, tolerance ) { + tolerance = tolerance || 0.0001; + if( a.normal.distanceTo( b.normal ) > tolerance ) { + return false; + } + if( Math.abs( a.constant - b.constant ) > tolerance ) { + return false; + } + return true; + }; + + test( "constructor", function() { + var a = new THREE.Frustum(); + + ok( a.planes !== undefined, "Passed!" ); + ok( a.planes.length === 6, "Passed!" ); + + var pDefault = new THREE.Plane(); + for( var i = 0; i < 6; i ++ ) { + ok( a.planes[i].equals( pDefault ), "Passed!" ); + } + + var p0 = new THREE.Plane( unit3, -1 ); + var p1 = new THREE.Plane( unit3, 1 ); + var p2 = new THREE.Plane( unit3, 2 ); + var p3 = new THREE.Plane( unit3, 3 ); + var p4 = new THREE.Plane( unit3, 4 ); + var p5 = new THREE.Plane( unit3, 5 ); + + a = new THREE.Frustum( p0, p1, p2, p3, p4, p5 ); + ok( a.planes[0].equals( p0 ), "Passed!" ); + ok( a.planes[1].equals( p1 ), "Passed!" ); + ok( a.planes[2].equals( p2 ), "Passed!" ); + ok( a.planes[3].equals( p3 ), "Passed!" ); + ok( a.planes[4].equals( p4 ), "Passed!" ); + ok( a.planes[5].equals( p5 ), "Passed!" ); + }); + + test( "copy", function() { + + var p0 = new THREE.Plane( unit3, -1 ); + var p1 = new THREE.Plane( unit3, 1 ); + var p2 = new THREE.Plane( unit3, 2 ); + var p3 = new THREE.Plane( unit3, 3 ); + var p4 = new THREE.Plane( unit3, 4 ); + var p5 = new THREE.Plane( unit3, 5 ); + + var b = new THREE.Frustum( p0, p1, p2, p3, p4, p5 ); + var a = new THREE.Frustum().copy( b ); + ok( a.planes[0].equals( p0 ), "Passed!" ); + ok( a.planes[1].equals( p1 ), "Passed!" ); + ok( a.planes[2].equals( p2 ), "Passed!" ); + ok( a.planes[3].equals( p3 ), "Passed!" ); + ok( a.planes[4].equals( p4 ), "Passed!" ); + ok( a.planes[5].equals( p5 ), "Passed!" ); + + // ensure it is a true copy by modifying source + b.planes[0] = p1; + ok( a.planes[0].equals( p0 ), "Passed!" ); + }); + + test( "setFromMatrix/makeOrthographic/containsPoint", function() { + var m = new THREE.Matrix4().makeOrthographic( -1, 1, -1, 1, 1, 100 ) + var a = new THREE.Frustum().setFromMatrix( m ); + + ok( ! a.containsPoint( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + ok( a.containsPoint( new THREE.Vector3( 0, 0, -50 ) ), "Passed!" ); + ok( a.containsPoint( new THREE.Vector3( 0, 0, -1.001 ) ), "Passed!" ); + ok( a.containsPoint( new THREE.Vector3( -1, -1, -1.001 ) ), "Passed!" ); + ok( ! a.containsPoint( new THREE.Vector3( -1.1, -1.1, -1.001 ) ), "Passed!" ); + ok( a.containsPoint( new THREE.Vector3( 1, 1, -1.001 ) ), "Passed!" ); + ok( ! a.containsPoint( new THREE.Vector3( 1.1, 1.1, -1.001 ) ), "Passed!" ); + ok( a.containsPoint( new THREE.Vector3( 0, 0, -100 ) ), "Passed!" ); + ok( a.containsPoint( new THREE.Vector3( -1, -1, -100 ) ), "Passed!" ); + ok( ! a.containsPoint( new THREE.Vector3( -1.1, -1.1, -100.1 ) ), "Passed!" ); + ok( a.containsPoint( new THREE.Vector3( 1, 1, -100 ) ), "Passed!" ); + ok( ! a.containsPoint( new THREE.Vector3( 1.1, 1.1, -100.1 ) ), "Passed!" ); + ok( ! a.containsPoint( new THREE.Vector3( 0, 0, -101 ) ), "Passed!" ); + + }); + + test( "setFromMatrix/makeFrustum/containsPoint", function() { + var m = new THREE.Matrix4().makeFrustum( -1, 1, -1, 1, 1, 100 ) + var a = new THREE.Frustum().setFromMatrix( m ); + + ok( ! a.containsPoint( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + ok( a.containsPoint( new THREE.Vector3( 0, 0, -50 ) ), "Passed!" ); + ok( a.containsPoint( new THREE.Vector3( 0, 0, -1.001 ) ), "Passed!" ); + ok( a.containsPoint( new THREE.Vector3( -1, -1, -1.001 ) ), "Passed!" ); + ok( ! a.containsPoint( new THREE.Vector3( -1.1, -1.1, -1.001 ) ), "Passed!" ); + ok( a.containsPoint( new THREE.Vector3( 1, 1, -1.001 ) ), "Passed!" ); + ok( ! a.containsPoint( new THREE.Vector3( 1.1, 1.1, -1.001 ) ), "Passed!" ); + ok( a.containsPoint( new THREE.Vector3( 0, 0, -99.999 ) ), "Passed!" ); + ok( a.containsPoint( new THREE.Vector3( -99.999, -99.999, -99.999 ) ), "Passed!" ); + ok( ! a.containsPoint( new THREE.Vector3( -100.1, -100.1, -100.1 ) ), "Passed!" ); + ok( a.containsPoint( new THREE.Vector3( 99.999, 99.999, -99.999 ) ), "Passed!" ); + ok( ! a.containsPoint( new THREE.Vector3( 100.1, 100.1, -100.1 ) ), "Passed!" ); + ok( ! a.containsPoint( new THREE.Vector3( 0, 0, -101 ) ), "Passed!" ); + }); + + test( "setFromMatrix/makeFrustum/intersectsSphere", function() { + var m = new THREE.Matrix4().makeFrustum( -1, 1, -1, 1, 1, 100 ) + var a = new THREE.Frustum().setFromMatrix( m ); + + ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, 0 ), 0 ) ), "Passed!" ); + ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, 0 ), 0.9 ) ), "Passed!" ); + ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, 0 ), 1.1 ) ), "Passed!" ); + ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, -50 ), 0 ) ), "Passed!" ); + ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, -1.001 ), 0 ) ), "Passed!" ); + ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( -1, -1, -1.001 ), 0 ) ), "Passed!" ); + ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( -1.1, -1.1, -1.001 ), 0 ) ), "Passed!" ); + ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( -1.1, -1.1, -1.001 ), 0.5 ) ), "Passed!" ); + ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 1, 1, -1.001 ), 0 ) ), "Passed!" ); + ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 1.1, 1.1, -1.001 ), 0 ) ), "Passed!" ); + ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 1.1, 1.1, -1.001 ), 0.5 ) ), "Passed!" ); + ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, -99.999 ), 0 ) ), "Passed!" ); + ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( -99.999, -99.999, -99.999 ), 0 ) ), "Passed!" ); + ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( -100.1, -100.1, -100.1 ), 0 ) ), "Passed!" ); + ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( -100.1, -100.1, -100.1 ), 0.5 ) ), "Passed!" ); + ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 99.999, 99.999, -99.999 ), 0 ) ), "Passed!" ); + ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 100.1, 100.1, -100.1 ), 0 ) ), "Passed!" ); + ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 100.1, 100.1, -100.1 ), 0.2 ) ), "Passed!" ); + ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, -101 ), 0 ) ), "Passed!" ); + ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, -101 ), 1.1 ) ), "Passed!" ); + }); + + test( "clone", function() { + + var p0 = new THREE.Plane( unit3, -1 ); + var p1 = new THREE.Plane( unit3, 1 ); + var p2 = new THREE.Plane( unit3, 2 ); + var p3 = new THREE.Plane( unit3, 3 ); + var p4 = new THREE.Plane( unit3, 4 ); + var p5 = new THREE.Plane( unit3, 5 ); + + var b = new THREE.Frustum( p0, p1, p2, p3, p4, p5 ); + var a = b.clone(); + ok( a.planes[0].equals( p0 ), "Passed!" ); + ok( a.planes[1].equals( p1 ), "Passed!" ); + ok( a.planes[2].equals( p2 ), "Passed!" ); + ok( a.planes[3].equals( p3 ), "Passed!" ); + ok( a.planes[4].equals( p4 ), "Passed!" ); + ok( a.planes[5].equals( p5 ), "Passed!" ); + + // ensure it is a true copy by modifying source + a.planes[0].copy( p1 ); + ok( b.planes[0].equals( p0 ), "Passed!" ); + }); + + + test( "constructor/equals", function() { + var a = new THREE.Line3(); + ok( a.start.equals( zero3 ), "Passed!" ); + ok( a.end.equals( zero3 ), "Passed!" ); + + a = new THREE.Line3( two3.clone(), one3.clone() ); + ok( a.start.equals( two3 ), "Passed!" ); + ok( a.end.equals( one3 ), "Passed!" ); + }); + + test( "copy/equals", function() { + var a = new THREE.Line3( zero3.clone(), one3.clone() ); + var b = new THREE.Line3().copy( a ); + ok( b.start.equals( zero3 ), "Passed!" ); + ok( b.end.equals( one3 ), "Passed!" ); + + // ensure that it is a true copy + a.start = zero3; + a.end = one3; + ok( b.start.equals( zero3 ), "Passed!" ); + ok( b.end.equals( one3 ), "Passed!" ); + }); + + test( "set", function() { + var a = new THREE.Line3(); + + a.set( one3, one3 ); + ok( a.start.equals( one3 ), "Passed!" ); + ok( a.end.equals( one3 ), "Passed!" ); + }); + + test( "at", function() { + var a = new THREE.Line3( one3.clone(), new THREE.Vector3( 1, 1, 2 ) ); + + ok( a.at( -1 ).distanceTo( new THREE.Vector3( 1, 1, 0 ) ) < 0.0001, "Passed!" ); + ok( a.at( 0 ).distanceTo( one3.clone() ) < 0.0001, "Passed!" ); + ok( a.at( 1 ).distanceTo( new THREE.Vector3( 1, 1, 2 ) ) < 0.0001, "Passed!" ); + ok( a.at( 2 ).distanceTo( new THREE.Vector3( 1, 1, 3 ) ) < 0.0001, "Passed!" ); + }); + + test( "closestPointToPoint/closestPointToPointParameter", function() { + var a = new THREE.Line3( one3.clone(), new THREE.Vector3( 1, 1, 2 ) ); + + // nearby the ray + ok( a.closestPointToPointParameter( zero3.clone(), true ) == 0, "Passed!" ); + var b1 = a.closestPointToPoint( zero3.clone(), true ); + ok( b1.distanceTo( new THREE.Vector3( 1, 1, 1 ) ) < 0.0001, "Passed!" ); + + // nearby the ray + ok( a.closestPointToPointParameter( zero3.clone(), false ) == -1, "Passed!" ); + var b2 = a.closestPointToPoint( zero3.clone(), false ); + console.log( b2 ); + ok( b2.distanceTo( new THREE.Vector3( 1, 1, 0 ) ) < 0.0001, "Passed!" ); + + // nearby the ray + ok( a.closestPointToPointParameter( new THREE.Vector3( 1, 1, 5 ), true ) == 1, "Passed!" ); + var b = a.closestPointToPoint( new THREE.Vector3( 1, 1, 5 ), true ); + ok( b.distanceTo( new THREE.Vector3( 1, 1, 2 ) ) < 0.0001, "Passed!" ); + + // exactly on the ray + ok( a.closestPointToPointParameter( one3.clone(), true ) == 0, "Passed!" ); + var c = a.closestPointToPoint( one3.clone(), true ); + ok( c.distanceTo( one3.clone() ) < 0.0001, "Passed!" ); + }); + + + + var matrixEquals3 = function( a, b, tolerance? ) { + tolerance = tolerance || 0.0001; + if( a.elements.length != b.elements.length ) { + return false; + } + for( var i = 0, il = a.elements.length; i < il; i ++ ) { + var delta = a.elements[i] - b.elements[i]; + if( delta > tolerance ) { + return false; + } + } + return true; + }; + + + var toMatrix4 = function( m3 ) { + var result = new THREE.Matrix4(); + var re = result.elements; + var me = m3.elements; + re[0] = me[0]; + re[1] = me[1]; + re[2] = me[2]; + re[4] = me[3]; + re[5] = me[4]; + re[6] = me[5]; + re[8] = me[6]; + re[9] = me[7]; + re[10] = me[8]; + + return result; + }; + + test( "constructor", function() { + var a = new THREE.Matrix3(); + ok( a.determinant() == 1, "Passed!" ); + + var b = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); + ok( b.elements[0] == 0 ); + ok( b.elements[1] == 3 ); + ok( b.elements[2] == 6 ); + ok( b.elements[3] == 1 ); + ok( b.elements[4] == 4 ); + ok( b.elements[5] == 7 ); + ok( b.elements[6] == 2 ); + ok( b.elements[7] == 5 ); + ok( b.elements[8] == 8 ); + + ok( ! matrixEquals3( a, b ), "Passed!" ); + }); + + test( "copy", function() { + var a = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); + var b = new THREE.Matrix3().copy( a ); + + ok( matrixEquals3( a, b ), "Passed!" ); + + // ensure that it is a true copy + a.elements[0] = 2; + ok( ! matrixEquals3( a, b ), "Passed!" ); + }); + + test( "set", function() { + var b = new THREE.Matrix3(); + ok( b.determinant() == 1, "Passed!" ); + + b.set( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); + ok( b.elements[0] == 0 ); + ok( b.elements[1] == 3 ); + ok( b.elements[2] == 6 ); + ok( b.elements[3] == 1 ); + ok( b.elements[4] == 4 ); + ok( b.elements[5] == 7 ); + ok( b.elements[6] == 2 ); + ok( b.elements[7] == 5 ); + ok( b.elements[8] == 8 ); + }); + + test( "identity", function() { + var b = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); + ok( b.elements[0] == 0 ); + ok( b.elements[1] == 3 ); + ok( b.elements[2] == 6 ); + ok( b.elements[3] == 1 ); + ok( b.elements[4] == 4 ); + ok( b.elements[5] == 7 ); + ok( b.elements[6] == 2 ); + ok( b.elements[7] == 5 ); + ok( b.elements[8] == 8 ); + + var a = new THREE.Matrix3(); + ok( ! matrixEquals3( a, b ), "Passed!" ); + + b.identity(); + ok( matrixEquals3( a, b ), "Passed!" ); + }); + + test( "multiplyScalar", function() { + var b = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); + ok( b.elements[0] == 0 ); + ok( b.elements[1] == 3 ); + ok( b.elements[2] == 6 ); + ok( b.elements[3] == 1 ); + ok( b.elements[4] == 4 ); + ok( b.elements[5] == 7 ); + ok( b.elements[6] == 2 ); + ok( b.elements[7] == 5 ); + ok( b.elements[8] == 8 ); + + b.multiplyScalar( 2 ); + ok( b.elements[0] == 0*2 ); + ok( b.elements[1] == 3*2 ); + ok( b.elements[2] == 6*2 ); + ok( b.elements[3] == 1*2 ); + ok( b.elements[4] == 4*2 ); + ok( b.elements[5] == 7*2 ); + ok( b.elements[6] == 2*2 ); + ok( b.elements[7] == 5*2 ); + ok( b.elements[8] == 8*2 ); + }); + + test( "determinant", function() { + var a = new THREE.Matrix3(); + ok( a.determinant() == 1, "Passed!" ); + + a.elements[0] = 2; + ok( a.determinant() == 2, "Passed!" ); + + a.elements[0] = 0; + ok( a.determinant() == 0, "Passed!" ); + + // calculated via http://www.euclideanspace.com/maths/algebra/matrix/functions/determinant/threeD/index.htm + a.set( 2, 3, 4, 5, 13, 7, 8, 9, 11 ); + ok( a.determinant() == -73, "Passed!" ); + }); + + + test( "getInverse", function() { + var identity = new THREE.Matrix4(); + var a = new THREE.Matrix4(); + var b = new THREE.Matrix3( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + + //var c = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + var c = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + + ok( ! matrixEquals3( a, b ), "Passed!" ); + b.getInverse( a, false ); + ok( matrixEquals3( b, new THREE.Matrix3() ), "Passed!" ); + + try { + b.getInverse( c, true ); + ok( false, "Passed!" ); // should never get here. + } + catch( err ) { + ok( true, "Passed!" ); + } + + var testMatrices = [ + new THREE.Matrix4().makeRotationX( 0.3 ), + new THREE.Matrix4().makeRotationX( -0.3 ), + new THREE.Matrix4().makeRotationY( 0.3 ), + new THREE.Matrix4().makeRotationY( -0.3 ), + new THREE.Matrix4().makeRotationZ( 0.3 ), + new THREE.Matrix4().makeRotationZ( -0.3 ), + new THREE.Matrix4().makeScale( 1, 2, 3 ), + new THREE.Matrix4().makeScale( 1/8, 1/2, 1/3 ) + ]; + + for( var i = 0, il = testMatrices.length; i < il; i ++ ) { + var m = testMatrices[i]; + var mInverse3 = new THREE.Matrix3().getInverse( m ); + + var mInverse = toMatrix4( mInverse3 ); + + // the determinant of the inverse should be the reciprocal + ok( Math.abs( m.determinant() * mInverse3.determinant() - 1 ) < 0.0001, "Passed!" ); + ok( Math.abs( m.determinant() * mInverse.determinant() - 1 ) < 0.0001, "Passed!" ); + + var mProduct = new THREE.Matrix4().multiplyMatrices( m, mInverse ); + ok( Math.abs( mProduct.determinant() - 1 ) < 0.0001, "Passed!" ); + ok( matrixEquals3( mProduct, identity ), "Passed!" ); + } + }); + + test( "transpose", function() { + var a = new THREE.Matrix3(); + var b = a.clone().transpose(); + ok( matrixEquals3( a, b ), "Passed!" ); + + b = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); + var c = b.clone().transpose(); + ok( ! matrixEquals3( b, c ), "Passed!" ); + c.transpose(); + ok( matrixEquals3( b, c ), "Passed!" ); + }); + + test( "clone", function() { + var a = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); + var b = a.clone(); + + ok( matrixEquals3( a, b ), "Passed!" ); + + // ensure that it is a true copy + a.elements[0] = 2; + ok( ! matrixEquals3( a, b ), "Passed!" ); + }); + + var matrixEquals4 = function( a, b, tolerance? ) { + tolerance = tolerance || 0.0001; + if( a.elements.length != b.elements.length ) { + return false; + } + for( var i = 0, il = a.elements.length; i < il; i ++ ) { + var delta = a.elements[i] - b.elements[i]; + if( delta > tolerance ) { + return false; + } + } + return true; + }; + + test( "constructor", function() { + var a = new THREE.Matrix4(); + ok( a.determinant() == 1, "Passed!" ); + + var b = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); + ok( b.elements[0] == 0 ); + ok( b.elements[1] == 4 ); + ok( b.elements[2] == 8 ); + ok( b.elements[3] == 12 ); + ok( b.elements[4] == 1 ); + ok( b.elements[5] == 5 ); + ok( b.elements[6] == 9 ); + ok( b.elements[7] == 13 ); + ok( b.elements[8] == 2 ); + ok( b.elements[9] == 6 ); + ok( b.elements[10] == 10 ); + ok( b.elements[11] == 14 ); + ok( b.elements[12] == 3 ); + ok( b.elements[13] == 7 ); + ok( b.elements[14] == 11 ); + ok( b.elements[15] == 15 ); + + ok( ! matrixEquals4( a, b ), "Passed!" ); + }); + + test( "copy", function() { + var a = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); + var b = new THREE.Matrix4().copy( a ); + + ok( matrixEquals4( a, b ), "Passed!" ); + + // ensure that it is a true copy + a.elements[0] = 2; + ok( ! matrixEquals4( a, b ), "Passed!" ); + }); + + test( "set", function() { + var b = new THREE.Matrix4(); + ok( b.determinant() == 1, "Passed!" ); + + b.set( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); + ok( b.elements[0] == 0 ); + ok( b.elements[1] == 4 ); + ok( b.elements[2] == 8 ); + ok( b.elements[3] == 12 ); + ok( b.elements[4] == 1 ); + ok( b.elements[5] == 5 ); + ok( b.elements[6] == 9 ); + ok( b.elements[7] == 13 ); + ok( b.elements[8] == 2 ); + ok( b.elements[9] == 6 ); + ok( b.elements[10] == 10 ); + ok( b.elements[11] == 14 ); + ok( b.elements[12] == 3 ); + ok( b.elements[13] == 7 ); + ok( b.elements[14] == 11 ); + ok( b.elements[15] == 15 ); + }); + + test( "identity", function() { + var b = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); + ok( b.elements[0] == 0 ); + ok( b.elements[1] == 4 ); + ok( b.elements[2] == 8 ); + ok( b.elements[3] == 12 ); + ok( b.elements[4] == 1 ); + ok( b.elements[5] == 5 ); + ok( b.elements[6] == 9 ); + ok( b.elements[7] == 13 ); + ok( b.elements[8] == 2 ); + ok( b.elements[9] == 6 ); + ok( b.elements[10] == 10 ); + ok( b.elements[11] == 14 ); + ok( b.elements[12] == 3 ); + ok( b.elements[13] == 7 ); + ok( b.elements[14] == 11 ); + ok( b.elements[15] == 15 ); + + var a = new THREE.Matrix4(); + ok( ! matrixEquals4( a, b ), "Passed!" ); + + b.identity(); + ok( matrixEquals4( a, b ), "Passed!" ); + }); + + test( "multiplyScalar", function() { + var b = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); + ok( b.elements[0] == 0 ); + ok( b.elements[1] == 4 ); + ok( b.elements[2] == 8 ); + ok( b.elements[3] == 12 ); + ok( b.elements[4] == 1 ); + ok( b.elements[5] == 5 ); + ok( b.elements[6] == 9 ); + ok( b.elements[7] == 13 ); + ok( b.elements[8] == 2 ); + ok( b.elements[9] == 6 ); + ok( b.elements[10] == 10 ); + ok( b.elements[11] == 14 ); + ok( b.elements[12] == 3 ); + ok( b.elements[13] == 7 ); + ok( b.elements[14] == 11 ); + ok( b.elements[15] == 15 ); + + b.multiplyScalar( 2 ); + ok( b.elements[0] == 0*2 ); + ok( b.elements[1] == 4*2 ); + ok( b.elements[2] == 8*2 ); + ok( b.elements[3] == 12*2 ); + ok( b.elements[4] == 1*2 ); + ok( b.elements[5] == 5*2 ); + ok( b.elements[6] == 9*2 ); + ok( b.elements[7] == 13*2 ); + ok( b.elements[8] == 2*2 ); + ok( b.elements[9] == 6*2 ); + ok( b.elements[10] == 10*2 ); + ok( b.elements[11] == 14*2 ); + ok( b.elements[12] == 3*2 ); + ok( b.elements[13] == 7*2 ); + ok( b.elements[14] == 11*2 ); + ok( b.elements[15] == 15*2 ); + }); + + test( "determinant", function() { + var a = new THREE.Matrix4(); + ok( a.determinant() == 1, "Passed!" ); + + a.elements[0] = 2; + ok( a.determinant() == 2, "Passed!" ); + + a.elements[0] = 0; + ok( a.determinant() == 0, "Passed!" ); + + // calculated via http://www.euclideanspace.com/maths/algebra/matrix/functions/determinant/fourD/index.htm + a.set( 2, 3, 4, 5, -1, -21, -3, -4, 6, 7, 8, 10, -8, -9, -10, -12 ); + ok( a.determinant() == 76, "Passed!" ); + }); + + test( "getInverse", function() { + var identity = new THREE.Matrix4(); + + var a = new THREE.Matrix4(); + var b = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + var c = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + + ok( ! matrixEquals4( a, b ), "Passed!" ); + b.getInverse( a, false ); + ok( matrixEquals4( b, new THREE.Matrix4() ), "Passed!" ); + + try { + b.getInverse( c, true ); + ok( false, "Passed!" ); // should never get here. + } + catch( err ) { + ok( true, "Passed!" ); + } + + var testMatrices = [ + new THREE.Matrix4().makeRotationX( 0.3 ), + new THREE.Matrix4().makeRotationX( -0.3 ), + new THREE.Matrix4().makeRotationY( 0.3 ), + new THREE.Matrix4().makeRotationY( -0.3 ), + new THREE.Matrix4().makeRotationZ( 0.3 ), + new THREE.Matrix4().makeRotationZ( -0.3 ), + new THREE.Matrix4().makeScale( 1, 2, 3 ), + new THREE.Matrix4().makeScale( 1/8, 1/2, 1/3 ), + new THREE.Matrix4().makeFrustum( -1, 1, -1, 1, 1, 1000 ), + new THREE.Matrix4().makeFrustum( -16, 16, -9, 9, 0.1, 10000 ), + new THREE.Matrix4().makeTranslation( 1, 2, 3 ) + ]; + + for( var i = 0, il = testMatrices.length; i < il; i ++ ) { + var m = testMatrices[i]; + + var mInverse = new THREE.Matrix4().getInverse( m ); + + // the determinant of the inverse should be the reciprocal + ok( Math.abs( m.determinant() * mInverse.determinant() - 1 ) < 0.0001, "Passed!" ); + + var mProduct = new THREE.Matrix4().multiplyMatrices( m, mInverse ); + + // the determinant of the identity matrix is 1 + ok( Math.abs( mProduct.determinant() - 1 ) < 0.0001, "Passed!" ); + ok( matrixEquals4( mProduct, identity ), "Passed!" ); + } + }); + + test( "transpose", function() { + var a = new THREE.Matrix4(); + var b = a.clone().transpose(); + ok( matrixEquals4( a, b ), "Passed!" ); + + b = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); + var c = b.clone().transpose(); + ok( ! matrixEquals4( b, c ), "Passed!" ); + c.transpose(); + ok( matrixEquals4( b, c ), "Passed!" ); + }); + + test( "clone", function() { + var a = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); + var b = a.clone(); + + ok( matrixEquals4( a, b ), "Passed!" ); + + // ensure that it is a true copy + a.elements[0] = 2; + ok( ! matrixEquals4( a, b ), "Passed!" ); + }); + + + var comparePlane = function ( a, b, threshold? ) { + threshold = threshold || 0.0001; + return ( a.normal.distanceTo( b.normal ) < threshold && + Math.abs( a.constant - b.constant ) < threshold ); + }; + + + test( "constructor", function() { + var a = new THREE.Plane(); + ok( a.normal.x == 1, "Passed!" ); + ok( a.normal.y == 0, "Passed!" ); + ok( a.normal.z == 0, "Passed!" ); + ok( a.constant == 0, "Passed!" ); + + a = new THREE.Plane( one3.clone(), 0 ); + ok( a.normal.x == 1, "Passed!" ); + ok( a.normal.y == 1, "Passed!" ); + ok( a.normal.z == 1, "Passed!" ); + ok( a.constant == 0, "Passed!" ); + + a = new THREE.Plane( one3.clone(), 1 ); + ok( a.normal.x == 1, "Passed!" ); + ok( a.normal.y == 1, "Passed!" ); + ok( a.normal.z == 1, "Passed!" ); + ok( a.constant == 1, "Passed!" ); + }); + + test( "copy", function() { + var a = new THREE.Plane( new THREE.Vector3( x, y, z ), w ); + var b = new THREE.Plane().copy( a ); + ok( b.normal.x == x, "Passed!" ); + ok( b.normal.y == y, "Passed!" ); + ok( b.normal.z == z, "Passed!" ); + ok( b.constant == w, "Passed!" ); + + // ensure that it is a true copy + a.normal.x = 0; + a.normal.y = -1; + a.normal.z = -2; + a.constant = -3; + ok( b.normal.x == x, "Passed!" ); + ok( b.normal.y == y, "Passed!" ); + ok( b.normal.z == z, "Passed!" ); + ok( b.constant == w, "Passed!" ); + }); + + test( "set", function() { + var a = new THREE.Plane(); + ok( a.normal.x == 1, "Passed!" ); + ok( a.normal.y == 0, "Passed!" ); + ok( a.normal.z == 0, "Passed!" ); + ok( a.constant == 0, "Passed!" ); + + var b = a.clone().set( new THREE.Vector3( x, y, z ), w ); + ok( b.normal.x == x, "Passed!" ); + ok( b.normal.y == y, "Passed!" ); + ok( b.normal.z == z, "Passed!" ); + ok( b.constant == w, "Passed!" ); + }); + + test( "setComponents", function() { + var a = new THREE.Plane(); + ok( a.normal.x == 1, "Passed!" ); + ok( a.normal.y == 0, "Passed!" ); + ok( a.normal.z == 0, "Passed!" ); + ok( a.constant == 0, "Passed!" ); + + var b = a.clone().setComponents( x, y, z , w ); + ok( b.normal.x == x, "Passed!" ); + ok( b.normal.y == y, "Passed!" ); + ok( b.normal.z == z, "Passed!" ); + ok( b.constant == w, "Passed!" ); + }); + + test( "setFromNormalAndCoplanarPoint", function() { + var normal = one3.clone().normalize(); + var a = new THREE.Plane().setFromNormalAndCoplanarPoint( normal, zero3 ); + + ok( a.normal.equals( normal ), "Passed!" ); + ok( a.constant == 0, "Passed!" ); + }); + + test( "normalize", function() { + var a = new THREE.Plane( new THREE.Vector3( 2, 0, 0 ), 2 ); + + a.normalize(); + ok( a.normal.length() == 1, "Passed!" ); + ok( a.normal.equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" ); + ok( a.constant == 1, "Passed!" ); + }); + + test( "negate/distanceToPoint", function() { + var a = new THREE.Plane( new THREE.Vector3( 2, 0, 0 ), -2 ); + + a.normalize(); + ok( a.distanceToPoint( new THREE.Vector3( 4, 0, 0 ) ) === 3, "Passed!" ); + ok( a.distanceToPoint( new THREE.Vector3( 1, 0, 0 ) ) === 0, "Passed!" ); + + a.negate(); + ok( a.distanceToPoint( new THREE.Vector3( 4, 0, 0 ) ) === -3, "Passed!" ); + ok( a.distanceToPoint( new THREE.Vector3( 1, 0, 0 ) ) === 0, "Passed!" ); + }); + + test( "distanceToPoint", function() { + var a = new THREE.Plane( new THREE.Vector3( 2, 0, 0 ), -2 ); + + a.normalize(); + ok( a.distanceToPoint( a.projectPoint( zero3.clone() ) ) === 0, "Passed!" ); + ok( a.distanceToPoint( new THREE.Vector3( 4, 0, 0 ) ) === 3, "Passed!" ); + }); + + test( "distanceToSphere", function() { + var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 ); + + var b = new THREE.Sphere( new THREE.Vector3( 2, 0, 0 ), 1 ); + + ok( a.distanceToSphere( b ) === 1, "Passed!" ); + + a.set( new THREE.Vector3( 1, 0, 0 ), 2 ); + ok( a.distanceToSphere( b ) === 3, "Passed!" ); + a.set( new THREE.Vector3( 1, 0, 0 ), -2 ); + ok( a.distanceToSphere( b ) === -1, "Passed!" ); + }); + + test( "isInterestionLine/intersectLine", function() { + var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 ); + + var l1 = new THREE.Line3( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ); + ok( a.isIntersectionLine( l1 ), "Passed!" ); + ok( a.intersectLine( l1 ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + + a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), -3 ); + + ok( a.isIntersectionLine( l1 ), "Passed!" ); + ok( a.intersectLine( l1 ).equals( new THREE.Vector3( 3, 0, 0 ) ), "Passed!" ); + + + a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), -11 ); + + ok( ! a.isIntersectionLine( l1 ), "Passed!" ); + ok( a.intersectLine( l1 ) === undefined, "Passed!" ); + + a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 11 ); + + ok( ! a.isIntersectionLine( l1 ), "Passed!" ); + ok( a.intersectLine( l1 ) === undefined, "Passed!" ); + + }); + + test( "projectPoint", function() { + var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 ); + + ok( a.projectPoint( new THREE.Vector3( 10, 0, 0 ) ).equals( zero3 ), "Passed!" ); + ok( a.projectPoint( new THREE.Vector3( -10, 0, 0 ) ).equals( zero3 ), "Passed!" ); + + a = new THREE.Plane( new THREE.Vector3( 0, 1, 0 ), -1 ); + ok( a.projectPoint( new THREE.Vector3( 0, 0, 0 ) ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" ); + ok( a.projectPoint( new THREE.Vector3( 0, 1, 0 ) ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" ); + + }); + + test( "orthoPoint", function() { + var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 ); + + ok( a.orthoPoint( new THREE.Vector3( 10, 0, 0 ) ).equals( new THREE.Vector3( 10, 0, 0 ) ), "Passed!" ); + ok( a.orthoPoint( new THREE.Vector3( -10, 0, 0 ) ).equals( new THREE.Vector3( -10, 0, 0 ) ), "Passed!" ); + }); + + test( "coplanarPoint", function() { + var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 ); + ok( a.distanceToPoint( a.coplanarPoint() ) === 0, "Passed!" ); + + a = new THREE.Plane( new THREE.Vector3( 0, 1, 0 ), -1 ); + ok( a.distanceToPoint( a.coplanarPoint() ) === 0, "Passed!" ); + }); + + test( "applyMatrix4/translate", function() { + + var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 ); + + var m = new THREE.Matrix4(); + m.makeRotationZ( Math.PI * 0.5 ); + + ok( comparePlane( a.clone().applyMatrix4( m ), new THREE.Plane( new THREE.Vector3( 0, 1, 0 ), 0 ) ), "Passed!" ); + + a = new THREE.Plane( new THREE.Vector3( 0, 1, 0 ), -1 ); + ok( comparePlane( a.clone().applyMatrix4( m ), new THREE.Plane( new THREE.Vector3( -1, 0, 0 ), -1 ) ), "Passed!" ); + + m.makeTranslation( 1, 1, 1 ); + ok( comparePlane( a.clone().applyMatrix4( m ), a.clone().translate( new THREE.Vector3( 1, 1, 1 ) ) ), "Passed!" ); + }); + + var orders = [ 'XYZ', 'YXZ', 'ZXY', 'ZYX', 'YZX', 'XZY' ]; + var eulerAngles = new THREE.Euler( 0.1, -0.3, 0.25 ); + + + + var qSub = function ( a, b ) { + var result = new THREE.Quaternion(); + result.copy( a ); + + result.x -= b.x; + result.y -= b.y; + result.z -= b.z; + result.w -= b.w; + + return result; + + }; + + test( "constructor", function() { + var a = new THREE.Quaternion(); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + ok( a.z == 0, "Passed!" ); + ok( a.w == 1, "Passed!" ); + + a = new THREE.Quaternion( x, y, z, w ); + ok( a.x === x, "Passed!" ); + ok( a.y === y, "Passed!" ); + ok( a.z === z, "Passed!" ); + ok( a.w === w, "Passed!" ); + }); + + test( "copy", function() { + var a = new THREE.Quaternion( x, y, z, w ); + var b = new THREE.Quaternion().copy( a ); + ok( b.x == x, "Passed!" ); + ok( b.y == y, "Passed!" ); + ok( b.z == z, "Passed!" ); + ok( b.w == w, "Passed!" ); + + // ensure that it is a true copy + a.x = 0; + a.y = -1; + a.z = 0; + a.w = -1; + ok( b.x == x, "Passed!" ); + ok( b.y == y, "Passed!" ); + }); + + test( "set", function() { + var a = new THREE.Quaternion(); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + ok( a.z == 0, "Passed!" ); + ok( a.w == 1, "Passed!" ); + + a.set( x, y, z, w ); + ok( a.x == x, "Passed!" ); + ok( a.y == y, "Passed!" ); + ok( a.z === z, "Passed!" ); + ok( a.w === w, "Passed!" ); + }); + + test( "setFromAxisAngle", function() { + + // TODO: find cases to validate. + ok( true, "Passed!" ); + + var zero = new THREE.Quaternion(); + + var a = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 1, 0, 0 ), 0 ); + ok( a.equals( zero ), "Passed!" ); + a = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), 0 ); + ok( a.equals( zero ), "Passed!" ); + a = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 0, 0, 1 ), 0 ); + ok( a.equals( zero ), "Passed!" ); + + var b1 = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 1, 0, 0 ), Math.PI ); + ok( ! a.equals( b1 ), "Passed!" ); + var b2 = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 1, 0, 0 ), -Math.PI ); + ok( ! a.equals( b2 ), "Passed!" ); + + b1.multiply( b2 ); + ok( a.equals( b1 ), "Passed!" ); + }); + + + test( "setFromEuler/setFromQuaternion", function() { + + var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ]; + + // ensure euler conversion to/from Quaternion matches. + for( var i = 0; i < orders.length; i ++ ) { + for( var j = 0; j < angles.length; j ++ ) { + var eulers2 = new THREE.Euler().setFromQuaternion( + new THREE.Quaternion().setFromEuler(new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i])), + orders[i] + ); + var v = new THREE.Vector3().applyEuler(eulers2); + ok( v.distanceTo( angles[j] ) < 0.001, "Passed!" ); + } + } + + }); + + test( "setFromEuler/setFromRotationMatrix", function() { + + // ensure euler conversion for Quaternion matches that of Matrix4 + for( var i = 0; i < orders.length; i ++ ) { + var q = new THREE.Quaternion().setFromEuler( eulerAngles ); + var m = new THREE.Matrix4().makeRotationFromEuler( eulerAngles ); + var q2 = new THREE.Quaternion().setFromRotationMatrix( m ); + + ok( qSub( q, q2 ).length() < 0.001, "Passed!" ); + } + + }); + + test( "normalize/length/lengthSq", function() { + var a = new THREE.Quaternion( x, y, z, w ); + var b = new THREE.Quaternion( -x, -y, -z, -w ); + + ok( a.length() != 1, "Passed!"); + ok( a.lengthSq() != 1, "Passed!"); + a.normalize(); + ok( a.length() == 1, "Passed!"); + ok( a.lengthSq() == 1, "Passed!"); + + a.set( 0, 0, 0, 0 ); + ok( a.lengthSq() == 0, "Passed!"); + ok( a.length() == 0, "Passed!"); + a.normalize(); + ok( a.lengthSq() == 1, "Passed!"); + ok( a.length() == 1, "Passed!"); + }); + + test( "inverse/conjugate", function() { + var a = new THREE.Quaternion( x, y, z, w ); + + // TODO: add better validation here. + + var b = a.clone().conjugate(); + + ok( a.x == -b.x, "Passed!" ); + ok( a.y == -b.y, "Passed!" ); + ok( a.z == -b.z, "Passed!" ); + ok( a.w == b.w, "Passed!" ); + }); + + + test( "multiplyQuaternions/multiply", function() { + + var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ]; + + var q1 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[0].x, angles[0].y, angles[0].z) ); + var q2 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[1].x, angles[1].y, angles[1].z) ); + var q3 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[2].x, angles[2].y, angles[2].z) ); + + var q = new THREE.Quaternion().multiplyQuaternions( q1, q2 ).multiply( q3 ); + + var m1 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[0].x, angles[0].y, angles[0].z) ); + var m2 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[1].x, angles[1].y, angles[1].z) ); + var m3 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[2].x, angles[2].y, angles[2].z) ); + + var m = new THREE.Matrix4().multiplyMatrices( m1, m2 ).multiply( m3 ); + + var qFromM = new THREE.Quaternion().setFromRotationMatrix( m ); + + ok( qSub( q, qFromM ).length() < 0.001, "Passed!" ); + }); + + test( "multiplyVector3", function() { + + var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ]; + + // ensure euler conversion for Quaternion matches that of Matrix4 + for( var i = 0; i < orders.length; i ++ ) { + for( var j = 0; j < angles.length; j ++ ) { + var q = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i]) ); + var m = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i]) ); + + var v0 = new THREE.Vector3(1, 0, 0); + var qv = v0.clone().applyQuaternion( q ); + var mv = v0.clone().applyMatrix4( m ); + + ok( qv.distanceTo( mv ) < 0.001, "Passed!" ); + } + } + + }); + + test( "equals", function() { + var a = new THREE.Quaternion( x, y, z, w ); + var b = new THREE.Quaternion( -x, -y, -z, -w ); + + ok( a.x != b.x, "Passed!" ); + ok( a.y != b.y, "Passed!" ); + + ok( ! a.equals( b ), "Passed!" ); + ok( ! b.equals( a ), "Passed!" ); + + a.copy( b ); + ok( a.x == b.x, "Passed!" ); + ok( a.y == b.y, "Passed!" ); + + ok( a.equals( b ), "Passed!" ); + ok( b.equals( a ), "Passed!" ); + }); + + + test( "constructor/equals", function() { + var a = new THREE.Ray(); + ok( a.origin.equals( zero3 ), "Passed!" ); + ok( a.direction.equals( zero3 ), "Passed!" ); + + a = new THREE.Ray( two3.clone(), one3.clone() ); + ok( a.origin.equals( two3 ), "Passed!" ); + ok( a.direction.equals( one3 ), "Passed!" ); + }); + + test( "copy/equals", function() { + var a = new THREE.Ray( zero3.clone(), one3.clone() ); + var b = new THREE.Ray().copy( a ); + ok( b.origin.equals( zero3 ), "Passed!" ); + ok( b.direction.equals( one3 ), "Passed!" ); + + // ensure that it is a true copy + a.origin = zero3; + a.direction = one3; + ok( b.origin.equals( zero3 ), "Passed!" ); + ok( b.direction.equals( one3 ), "Passed!" ); + }); + + test( "set", function() { + var a = new THREE.Ray(); + + a.set( one3, one3 ); + ok( a.origin.equals( one3 ), "Passed!" ); + ok( a.direction.equals( one3 ), "Passed!" ); + }); + + test( "at", function() { + var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); + + ok( a.at( 0 ).equals( one3 ), "Passed!" ); + ok( a.at( -1 ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); + ok( a.at( 1 ).equals( new THREE.Vector3( 1, 1, 2 ) ), "Passed!" ); + }); + + test( "recast/clone", function() { + var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); + + ok( a.recast( 0 ).equals( a ), "Passed!" ); + + var b = a.clone(); + ok( b.recast( -1 ).equals( new THREE.Ray( new THREE.Vector3( 1, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ) ), "Passed!" ); + + var c = a.clone(); + ok( c.recast( 1 ).equals( new THREE.Ray( new THREE.Vector3( 1, 1, 2 ), new THREE.Vector3( 0, 0, 1 ) ) ), "Passed!" ); + + var d = a.clone(); + var e = d.clone().recast( 1 ); + ok( d.equals( a ), "Passed!" ); + ok( ! e.equals( d ), "Passed!" ); + ok( e.equals( c ), "Passed!" ); + }); + + test( "closestPointToPoint", function() { + var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); + + // nearby the ray + var b = a.closestPointToPoint( zero3 ); + ok( b.equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); + + // exactly on the ray + var c = a.closestPointToPoint( one3 ); + ok( c.equals( one3 ), "Passed!" ); + }); + + test( "distanceToPoint", function() { + var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); + + // nearby the ray + var b = a.distanceToPoint( zero3 ); + ok( b == Math.sqrt( 2 ), "Passed!" ); + + // exactly on the ray + var c = a.distanceToPoint( one3 ); + ok( c == 0, "Passed!" ); + }); + + test( "isIntersectionSphere", function() { + var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); + var b = new THREE.Sphere( zero3, 0.5 ); + var c = new THREE.Sphere( zero3, 1.5 ); + var d = new THREE.Sphere( one3, 0.1 ); + var e = new THREE.Sphere( two3, 0.1 ); + var f = new THREE.Sphere( two3, 1 ); + + ok( ! a.isIntersectionSphere( b ), "Passed!" ); + ok( a.isIntersectionSphere( c ), "Passed!" ); + ok( a.isIntersectionSphere( d ), "Passed!" ); + ok( ! a.isIntersectionSphere( e ), "Passed!" ); + ok( ! a.isIntersectionSphere( f ), "Passed!" ); + }); + + test( "isIntersectionPlane", function() { + var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); + + // parallel plane behind + var b = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, -1 ) ) ); + ok( a.isIntersectionPlane( b ), "Passed!" ); + + // parallel plane coincident with origin + var c = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, 0 ) ) ); + ok( a.isIntersectionPlane( c ), "Passed!" ); + + // parallel plane infront + var d = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, 1 ) ) ); + ok( a.isIntersectionPlane( d ), "Passed!" ); + + // perpendical ray that overlaps exactly + var e = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), one3 ); + ok( a.isIntersectionPlane( e ), "Passed!" ); + + // perpendical ray that doesn't overlap + var f = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), zero3 ); + ok( ! a.isIntersectionPlane( f ), "Passed!" ); + }); + + test( "intersectPlane", function() { + var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); + + // parallel plane behind + var b = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 1, 1, -1 ) ); + ok( a.intersectPlane( b ).equals( new THREE.Vector3( 1, 1, -1 ) ), "Passed!" ); + + // parallel plane coincident with origin + var c = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 1, 1, 0 ) ); + ok( a.intersectPlane( c ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); + + // parallel plane infront + var d = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 1, 1, 1 ) ); + ok( a.intersectPlane( d ).equals( new THREE.Vector3( 1, 1, 1 ) ), "Passed!" ); + + // perpendical ray that overlaps exactly + var e = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), one3 ); + ok( a.intersectPlane( e ).equals( a.origin ), "Passed!" ); + + // perpendical ray that doesn't overlap + var f = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), zero3 ); + ok( a.intersectPlane( f ) === undefined, "Passed!" ); + }); + + + test( "applyMatrix4", function() { + var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); + var m = new THREE.Matrix4().identity(); + + ok( a.clone().applyMatrix4( m ).equals( a ), "Passed!" ); + + a = new THREE.Ray( zero3.clone(), new THREE.Vector3( 0, 0, 1 ) ); + m.makeRotationAxis( new THREE.Vector3( 0, 0, 1 ), Math.PI ); + ok( a.clone().applyMatrix4( m ).equals( a ), "Passed!" ); + + m.identity().makeRotationX( Math.PI ); + var b = a.clone(); + b.direction.negate(); + var a2 = a.clone().applyMatrix4( m ); + ok( a2.origin.distanceTo( b.origin ) < 0.0001, "Passed!" ); + ok( a2.direction.distanceTo( b.direction ) < 0.0001, "Passed!" ); + + a.origin = new THREE.Vector3( 0, 0, 1 ); + b.origin = new THREE.Vector3( 0, 0, -1 ); + var a2 = a.clone().applyMatrix4( m ); + ok( a2.origin.distanceTo( b.origin ) < 0.0001, "Passed!" ); + ok( a2.direction.distanceTo( b.direction ) < 0.0001, "Passed!" ); + }); + + + test( "constructor", function() { + var a = new THREE.Sphere(); + ok( a.center.equals( zero3 ), "Passed!" ); + ok( a.radius == 0, "Passed!" ); + + a = new THREE.Sphere( one3.clone(), 1 ); + ok( a.center.equals( one3 ), "Passed!" ); + ok( a.radius == 1, "Passed!" ); + }); + + test( "copy", function() { + var a = new THREE.Sphere( one3.clone(), 1 ); + var b = new THREE.Sphere().copy( a ); + + ok( b.center.equals( one3 ), "Passed!" ); + ok( b.radius == 1, "Passed!" ); + + // ensure that it is a true copy + a.center = zero3; + a.radius = 0; + ok( b.center.equals( one3 ), "Passed!" ); + ok( b.radius == 1, "Passed!" ); + }); + + test( "set", function() { + var a = new THREE.Sphere(); + ok( a.center.equals( zero3 ), "Passed!" ); + ok( a.radius == 0, "Passed!" ); + + a.set( one3, 1 ); + ok( a.center.equals( one3 ), "Passed!" ); + ok( a.radius == 1, "Passed!" ); + }); + + test( "empty", function() { + var a = new THREE.Sphere(); + ok( a.empty(), "Passed!" ); + + a.set( one3, 1 ); + ok( ! a.empty(), "Passed!" ); + }); + + test( "containsPoint", function() { + var a = new THREE.Sphere( one3.clone(), 1 ); + + ok( ! a.containsPoint( zero3 ), "Passed!" ); + ok( a.containsPoint( one3 ), "Passed!" ); + }); + + test( "distanceToPoint", function() { + var a = new THREE.Sphere( one3.clone(), 1 ); + + ok( ( a.distanceToPoint( zero3 ) - 0.7320 ) < 0.001, "Passed!" ); + ok( a.distanceToPoint( one3 ) === -1, "Passed!" ); + }); + + test( "intersectsSphere", function() { + var a = new THREE.Sphere( one3.clone(), 1 ); + var b = new THREE.Sphere( zero3.clone(), 1 ); + var c = new THREE.Sphere( zero3.clone(), 0.25 ); + + ok( a.intersectsSphere( b ) , "Passed!" ); + ok( ! a.intersectsSphere( c ) , "Passed!" ); + }); + + test( "clampPoint", function() { + var a = new THREE.Sphere( one3.clone(), 1 ); + + ok( a.clampPoint( new THREE.Vector3( 1, 1, 3 ) ).equals( new THREE.Vector3( 1, 1, 2 ) ), "Passed!" ); + ok( a.clampPoint( new THREE.Vector3( 1, 1, -3 ) ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); + }); + + test( "getBoundingBox", function() { + var a = new THREE.Sphere( one3.clone(), 1 ); + + ok( a.getBoundingBox().equals( new THREE.Box3( zero3, two3 ) ), "Passed!" ); + + a.set( zero3, 0 ) + ok( a.getBoundingBox().equals( new THREE.Box3( zero3, zero3 ) ), "Passed!" ); + }); + + test( "applyMatrix4", function() { + var a = new THREE.Sphere( one3.clone(), 1 ); + + var m = new THREE.Matrix4().makeTranslation( 1, -2, 1 ); + + ok( a.clone().applyMatrix4( m ).getBoundingBox().equals( a.getBoundingBox().applyMatrix4( m ) ), "Passed!" ); + }); + + test( "translate", function() { + var a = new THREE.Sphere( one3.clone(), 1 ); + + a.translate( one3.clone().negate() ); + ok( a.center.equals( zero3 ), "Passed!" ); + }); + + test( "constructor", function() { + var a = new THREE.Triangle(); + ok( a.a.equals( zero3 ), "Passed!" ); + ok( a.b.equals( zero3 ), "Passed!" ); + ok( a.c.equals( zero3 ), "Passed!" ); + + a = new THREE.Triangle( one3.clone().negate(), one3.clone(), two3.clone() ); + ok( a.a.equals( one3.clone().negate() ), "Passed!" ); + ok( a.b.equals( one3 ), "Passed!" ); + ok( a.c.equals( two3 ), "Passed!" ); + }); + + test( "copy", function() { + var a = new THREE.Triangle( one3.clone().negate(), one3.clone(), two3.clone() ); + var b = new THREE.Triangle().copy( a ); + ok( b.a.equals( one3.clone().negate() ), "Passed!" ); + ok( b.b.equals( one3 ), "Passed!" ); + ok( b.c.equals( two3 ), "Passed!" ); + + // ensure that it is a true copy + a.a = one3; + a.b = zero3; + a.c = zero3; + ok( b.a.equals( one3.clone().negate() ), "Passed!" ); + ok( b.b.equals( one3 ), "Passed!" ); + ok( b.c.equals( two3 ), "Passed!" ); + }); + + test( "setFromPointsAndIndices", function() { + var a = new THREE.Triangle(); + + var points = [ one3, one3.clone().negate(), two3 ]; + a.setFromPointsAndIndices( points, 1, 0, 2 ); + ok( a.a.equals( one3.clone().negate() ), "Passed!" ); + ok( a.b.equals( one3 ), "Passed!" ); + ok( a.c.equals( two3 ), "Passed!" ); + + }); + + test( "set", function() { + var a = new THREE.Triangle(); + + a.set( one3.clone().negate(), one3, two3 ); + ok( a.a.equals( one3.clone().negate() ), "Passed!" ); + ok( a.b.equals( one3 ), "Passed!" ); + ok( a.c.equals( two3 ), "Passed!" ); + + }); + + test( "area", function() { + var a = new THREE.Triangle(); + + ok( a.area() == 0, "Passed!" ); + + a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); + ok( a.area() == 0.5, "Passed!" ); + + a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) ); + ok( a.area() == 2, "Passed!" ); + + // colinear triangle. + a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 3, 0, 0 ) ); + ok( a.area() == 0, "Passed!" ); + }); + + test( "midpoint", function() { + var a = new THREE.Triangle(); + + ok( a.midpoint().equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + + a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); + ok( a.midpoint().equals( new THREE.Vector3( 1/3, 1/3, 0 ) ), "Passed!" ); + + a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) ); + ok( a.midpoint().equals( new THREE.Vector3( 2/3, 0, 2/3 ) ), "Passed!" ); + }); + + test( "normal", function() { + var a = new THREE.Triangle(); + + ok( a.normal().equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + + a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); + ok( a.normal().equals( new THREE.Vector3( 0, 0, 1 ) ), "Passed!" ); + + a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) ); + ok( a.normal().equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" ); + }); + + test( "plane", function() { + var a = new THREE.Triangle(); + + // artificial normal is created in this case. + ok( a.plane().distanceToPoint( a.a ) == 0, "Passed!" ); + ok( a.plane().distanceToPoint( a.b ) == 0, "Passed!" ); + ok( a.plane().distanceToPoint( a.c ) == 0, "Passed!" ); + ok( a.plane().normal.equals( a.normal() ), "Passed!" ); + + a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); + ok( a.plane().distanceToPoint( a.a ) == 0, "Passed!" ); + ok( a.plane().distanceToPoint( a.b ) == 0, "Passed!" ); + ok( a.plane().distanceToPoint( a.c ) == 0, "Passed!" ); + ok( a.plane().normal.equals( a.normal() ), "Passed!" ); + + a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) ); + ok( a.plane().distanceToPoint( a.a ) == 0, "Passed!" ); + ok( a.plane().distanceToPoint( a.b ) == 0, "Passed!" ); + ok( a.plane().distanceToPoint( a.c ) == 0, "Passed!" ); + ok( a.plane().normal.clone().normalize().equals( a.normal() ), "Passed!" ); + }); + + test( "barycoordFromPoint", function() { + var a = new THREE.Triangle(); + + var bad = new THREE.Vector3( -2, -1, -1 ); + + ok( a.barycoordFromPoint( a.a ).equals( bad ), "Passed!" ); + ok( a.barycoordFromPoint( a.b ).equals( bad ), "Passed!" ); + ok( a.barycoordFromPoint( a.c ).equals( bad ), "Passed!" ); + + a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); + ok( a.barycoordFromPoint( a.a ).equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" ); + ok( a.barycoordFromPoint( a.b ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" ); + ok( a.barycoordFromPoint( a.c ).equals( new THREE.Vector3( 0, 0, 1 ) ), "Passed!" ); + ok( a.barycoordFromPoint( a.midpoint() ).distanceTo( new THREE.Vector3( 1/3, 1/3, 1/3 ) ) < 0.0001, "Passed!" ); + + a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) ); + ok( a.barycoordFromPoint( a.a ).equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" ); + ok( a.barycoordFromPoint( a.b ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" ); + ok( a.barycoordFromPoint( a.c ).equals( new THREE.Vector3( 0, 0, 1 ) ), "Passed!" ); + ok( a.barycoordFromPoint( a.midpoint() ).distanceTo( new THREE.Vector3( 1/3, 1/3, 1/3 ) ) < 0.0001, "Passed!" ); + }); + + test( "containsPoint", function() { + var a = new THREE.Triangle(); + + ok( ! a.containsPoint( a.a ), "Passed!" ); + ok( ! a.containsPoint( a.b ), "Passed!" ); + ok( ! a.containsPoint( a.c ), "Passed!" ); + + a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); + ok( a.containsPoint( a.a ), "Passed!" ); + ok( a.containsPoint( a.b ), "Passed!" ); + ok( a.containsPoint( a.c ), "Passed!" ); + ok( a.containsPoint( a.midpoint() ), "Passed!" ); + ok( ! a.containsPoint( new THREE.Vector3( -1, -1, -1 ) ), "Passed!" ); + + a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) ); + ok( a.containsPoint( a.a ), "Passed!" ); + ok( a.containsPoint( a.b ), "Passed!" ); + ok( a.containsPoint( a.c ), "Passed!" ); + ok( a.containsPoint( a.midpoint() ), "Passed!" ); + ok( ! a.containsPoint( new THREE.Vector3( -1, -1, -1 ) ), "Passed!" ); + }); + + + test( "constructor", function() { + var a = new THREE.Vector2(); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + + a = new THREE.Vector2( x, y ); + ok( a.x === x, "Passed!" ); + ok( a.y === y, "Passed!" ); + }); + + test( "copy", function() { + var a = new THREE.Vector2( x, y ); + var b = new THREE.Vector2().copy( a ); + ok( b.x == x, "Passed!" ); + ok( b.y == y, "Passed!" ); + + // ensure that it is a true copy + a.x = 0; + a.y = -1; + ok( b.x == x, "Passed!" ); + ok( b.y == y, "Passed!" ); + }); + + test( "set", function() { + var a = new THREE.Vector2(); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + + a.set( x, y ); + ok( a.x == x, "Passed!" ); + ok( a.y == y, "Passed!" ); + }); + + test( "setX,setY", function() { + var a = new THREE.Vector2(); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + + a.setX( x ); + a.setY( y ); + ok( a.x == x, "Passed!" ); + ok( a.y == y, "Passed!" ); + }); + + test( "setComponent,getComponent", function() { + var a = new THREE.Vector2(); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + + a.setComponent( 0, 1 ); + a.setComponent( 1, 2 ); + ok( a.getComponent( 0 ) == 1, "Passed!" ); + ok( a.getComponent( 1 ) == 2, "Passed!" ); + }); + + test( "add", function() { + var a = new THREE.Vector2( x, y ); + var b = new THREE.Vector2( -x, -y ); + + a.add( b ); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + + var c = new THREE.Vector2().addVectors( b, b ); + ok( c.x == -2*x, "Passed!" ); + ok( c.y == -2*y, "Passed!" ); + }); + + test( "sub", function() { + var a = new THREE.Vector2( x, y ); + var b = new THREE.Vector2( -x, -y ); + + a.sub( b ); + ok( a.x == 2*x, "Passed!" ); + ok( a.y == 2*y, "Passed!" ); + + var c = new THREE.Vector2().subVectors( a, a ); + ok( c.x == 0, "Passed!" ); + ok( c.y == 0, "Passed!" ); + }); + + test( "multiply/divide", function() { + var a = new THREE.Vector2( x, y ); + var b = new THREE.Vector2( -x, -y ); + + a.multiplyScalar( -2 ); + ok( a.x == x*-2, "Passed!" ); + ok( a.y == y*-2, "Passed!" ); + + b.multiplyScalar( -2 ); + ok( b.x == 2*x, "Passed!" ); + ok( b.y == 2*y, "Passed!" ); + + a.divideScalar( -2 ); + ok( a.x == x, "Passed!" ); + ok( a.y == y, "Passed!" ); + + b.divideScalar( -2 ); + ok( b.x == -x, "Passed!" ); + ok( b.y == -y, "Passed!" ); + }); + + + test( "min/max/clamp", function() { + var a = new THREE.Vector2( x, y ); + var b = new THREE.Vector2( -x, -y ); + var c = new THREE.Vector2(); + + c.copy( a ).min( b ); + ok( c.x == -x, "Passed!" ); + ok( c.y == -y, "Passed!" ); + + c.copy( a ).max( b ); + ok( c.x == x, "Passed!" ); + ok( c.y == y, "Passed!" ); + + c.set( -2*x, 2*y ); + c.clamp( b, a ); + ok( c.x == -x, "Passed!" ); + ok( c.y == y, "Passed!" ); + }); + + test( "negate", function() { + var a = new THREE.Vector2( x, y ); + + a.negate(); + ok( a.x == -x, "Passed!" ); + ok( a.y == -y, "Passed!" ); + }); + + test( "dot", function() { + var a = new THREE.Vector2( x, y ); + var b = new THREE.Vector2( -x, -y ); + var c = new THREE.Vector2(); + + var result = a.dot( b ); + ok( result == (-x*x-y*y), "Passed!" ); + + result = a.dot( c ); + ok( result == 0, "Passed!" ); + }); + + test( "length/lengthSq", function() { + var a = new THREE.Vector2( x, 0 ); + var b = new THREE.Vector2( 0, -y ); + var c = new THREE.Vector2(); + + ok( a.length() == x, "Passed!" ); + ok( a.lengthSq() == x*x, "Passed!" ); + ok( b.length() == y, "Passed!" ); + ok( b.lengthSq() == y*y, "Passed!" ); + ok( c.length() == 0, "Passed!" ); + ok( c.lengthSq() == 0, "Passed!" ); + + a.set( x, y ); + ok( a.length() == Math.sqrt( x*x + y*y ), "Passed!" ); + ok( a.lengthSq() == ( x*x + y*y ), "Passed!" ); + }); + + test( "normalize", function() { + var a = new THREE.Vector2( x, 0 ); + var b = new THREE.Vector2( 0, -y ); + var c = new THREE.Vector2(); + + a.normalize(); + ok( a.length() == 1, "Passed!" ); + ok( a.x == 1, "Passed!" ); + + b.normalize(); + ok( b.length() == 1, "Passed!" ); + ok( b.y == -1, "Passed!" ); + }); + + test( "distanceTo/distanceToSquared", function() { + var a = new THREE.Vector2( x, 0 ); + var b = new THREE.Vector2( 0, -y ); + var c = new THREE.Vector2(); + + ok( a.distanceTo( c ) == x, "Passed!" ); + ok( a.distanceToSquared( c ) == x*x, "Passed!" ); + + ok( b.distanceTo( c ) == y, "Passed!" ); + ok( b.distanceToSquared( c ) == y*y, "Passed!" ); + }); + + test( "setLength", function() { + var a = new THREE.Vector2( x, 0 ); + + ok( a.length() == x, "Passed!" ); + a.setLength( y ); + ok( a.length() == y, "Passed!" ); + + a = new THREE.Vector2( 0, 0 ); + ok( a.length() == 0, "Passed!" ); + a.setLength( y ); + ok( a.length() == 0, "Passed!" ); + }); + + test( "lerp/clone", function() { + var a = new THREE.Vector2( x, 0 ); + var b = new THREE.Vector2( 0, -y ); + + ok( a.lerp( a, 0 ).equals( a.lerp( a, 0.5 ) ), "Passed!" ); + ok( a.lerp( a, 0 ).equals( a.lerp( a, 1 ) ), "Passed!" ); + + ok( a.clone().lerp( b, 0 ).equals( a ), "Passed!" ); + + ok( a.clone().lerp( b, 0.5 ).x == x*0.5, "Passed!" ); + ok( a.clone().lerp( b, 0.5 ).y == -y*0.5, "Passed!" ); + + ok( a.clone().lerp( b, 1 ).equals( b ), "Passed!" ); + }); + + test( "equals", function() { + var a = new THREE.Vector2( x, 0 ); + var b = new THREE.Vector2( 0, -y ); + + ok( a.x != b.x, "Passed!" ); + ok( a.y != b.y, "Passed!" ); + + ok( ! a.equals( b ), "Passed!" ); + ok( ! b.equals( a ), "Passed!" ); + + a.copy( b ); + ok( a.x == b.x, "Passed!" ); + ok( a.y == b.y, "Passed!" ); + + ok( a.equals( b ), "Passed!" ); + ok( b.equals( a ), "Passed!" ); + }); + + + test( "constructor", function() { + var a = new THREE.Vector3(); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + ok( a.z == 0, "Passed!" ); + + a = new THREE.Vector3( x, y, z ); + ok( a.x === x, "Passed!" ); + ok( a.y === y, "Passed!" ); + ok( a.z === z, "Passed!" ); + }); + + test( "copy", function() { + var a = new THREE.Vector3( x, y, z ); + var b = new THREE.Vector3().copy( a ); + ok( b.x == x, "Passed!" ); + ok( b.y == y, "Passed!" ); + ok( b.z == z, "Passed!" ); + + // ensure that it is a true copy + a.x = 0; + a.y = -1; + a.z = -2; + ok( b.x == x, "Passed!" ); + ok( b.y == y, "Passed!" ); + ok( b.z == z, "Passed!" ); + }); + + test( "set", function() { + var a = new THREE.Vector3(); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + ok( a.z == 0, "Passed!" ); + + a.set( x, y, z ); + ok( a.x == x, "Passed!" ); + ok( a.y == y, "Passed!" ); + ok( a.z == z, "Passed!" ); + }); + + test( "setX,setY,setZ", function() { + var a = new THREE.Vector3(); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + ok( a.z == 0, "Passed!" ); + + a.setX( x ); + a.setY( y ); + a.setZ( z ); + + ok( a.x == x, "Passed!" ); + ok( a.y == y, "Passed!" ); + ok( a.z == z, "Passed!" ); + }); + + test( "setComponent,getComponent", function() { + var a = new THREE.Vector3(); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + ok( a.z == 0, "Passed!" ); + + a.setComponent( 0, 1 ); + a.setComponent( 1, 2 ); + a.setComponent( 2, 3 ); + ok( a.getComponent( 0 ) == 1, "Passed!" ); + ok( a.getComponent( 1 ) == 2, "Passed!" ); + ok( a.getComponent( 2 ) == 3, "Passed!" ); + }); + + test( "add", function() { + var a = new THREE.Vector3( x, y, z ); + var b = new THREE.Vector3( -x, -y, -z ); + + a.add( b ); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + ok( a.z == 0, "Passed!" ); + + var c = new THREE.Vector3().addVectors( b, b ); + ok( c.x == -2*x, "Passed!" ); + ok( c.y == -2*y, "Passed!" ); + ok( c.z == -2*z, "Passed!" ); + }); + + test( "sub", function() { + var a = new THREE.Vector3( x, y, z ); + var b = new THREE.Vector3( -x, -y, -z ); + + a.sub( b ); + ok( a.x == 2*x, "Passed!" ); + ok( a.y == 2*y, "Passed!" ); + ok( a.z == 2*z, "Passed!" ); + + var c = new THREE.Vector3().subVectors( a, a ); + ok( c.x == 0, "Passed!" ); + ok( c.y == 0, "Passed!" ); + ok( c.z == 0, "Passed!" ); + }); + + test( "multiply/divide", function() { + var a = new THREE.Vector3( x, y, z ); + var b = new THREE.Vector3( -x, -y, -z ); + + a.multiplyScalar( -2 ); + ok( a.x == x*-2, "Passed!" ); + ok( a.y == y*-2, "Passed!" ); + ok( a.z == z*-2, "Passed!" ); + + b.multiplyScalar( -2 ); + ok( b.x == 2*x, "Passed!" ); + ok( b.y == 2*y, "Passed!" ); + ok( b.z == 2*z, "Passed!" ); + + a.divideScalar( -2 ); + ok( a.x == x, "Passed!" ); + ok( a.y == y, "Passed!" ); + ok( a.z == z, "Passed!" ); + + b.divideScalar( -2 ); + ok( b.x == -x, "Passed!" ); + ok( b.y == -y, "Passed!" ); + ok( b.z == -z, "Passed!" ); + }); + + test( "min/max/clamp", function() { + var a = new THREE.Vector3( x, y, z ); + var b = new THREE.Vector3( -x, -y, -z ); + var c = new THREE.Vector3(); + + c.copy( a ).min( b ); + ok( c.x == -x, "Passed!" ); + ok( c.y == -y, "Passed!" ); + ok( c.z == -z, "Passed!" ); + + c.copy( a ).max( b ); + ok( c.x == x, "Passed!" ); + ok( c.y == y, "Passed!" ); + ok( c.z == z, "Passed!" ); + + c.set( -2*x, 2*y, -2*z ); + c.clamp( b, a ); + ok( c.x == -x, "Passed!" ); + ok( c.y == y, "Passed!" ); + ok( c.z == -z, "Passed!" ); + }); + + test( "negate", function() { + var a = new THREE.Vector3( x, y, z ); + + a.negate(); + ok( a.x == -x, "Passed!" ); + ok( a.y == -y, "Passed!" ); + ok( a.z == -z, "Passed!" ); + }); + + test( "dot", function() { + var a = new THREE.Vector3( x, y, z ); + var b = new THREE.Vector3( -x, -y, -z ); + var c = new THREE.Vector3(); + + var result = a.dot( b ); + ok( result == (-x*x-y*y-z*z), "Passed!" ); + + result = a.dot( c ); + ok( result == 0, "Passed!" ); + }); + + test( "length/lengthSq", function() { + var a = new THREE.Vector3( x, 0, 0 ); + var b = new THREE.Vector3( 0, -y, 0 ); + var c = new THREE.Vector3( 0, 0, z ); + var d = new THREE.Vector3(); + + ok( a.length() == x, "Passed!" ); + ok( a.lengthSq() == x*x, "Passed!" ); + ok( b.length() == y, "Passed!" ); + ok( b.lengthSq() == y*y, "Passed!" ); + ok( c.length() == z, "Passed!" ); + ok( c.lengthSq() == z*z, "Passed!" ); + ok( d.length() == 0, "Passed!" ); + ok( d.lengthSq() == 0, "Passed!" ); + + a.set( x, y, z ); + ok( a.length() == Math.sqrt( x*x + y*y + z*z ), "Passed!" ); + ok( a.lengthSq() == ( x*x + y*y + z*z ), "Passed!" ); + }); + + test( "normalize", function() { + var a = new THREE.Vector3( x, 0, 0 ); + var b = new THREE.Vector3( 0, -y, 0 ); + var c = new THREE.Vector3( 0, 0, z ); + + a.normalize(); + ok( a.length() == 1, "Passed!" ); + ok( a.x == 1, "Passed!" ); + + b.normalize(); + ok( b.length() == 1, "Passed!" ); + ok( b.y == -1, "Passed!" ); + + c.normalize(); + ok( c.length() == 1, "Passed!" ); + ok( c.z == 1, "Passed!" ); + }); + + test( "distanceTo/distanceToSquared", function() { + var a = new THREE.Vector3( x, 0, 0 ); + var b = new THREE.Vector3( 0, -y, 0 ); + var c = new THREE.Vector3( 0, 0, z ); + var d = new THREE.Vector3(); + + ok( a.distanceTo( d ) == x, "Passed!" ); + ok( a.distanceToSquared( d ) == x*x, "Passed!" ); + + ok( b.distanceTo( d ) == y, "Passed!" ); + ok( b.distanceToSquared( d ) == y*y, "Passed!" ); + + ok( c.distanceTo( d ) == z, "Passed!" ); + ok( c.distanceToSquared( d ) == z*z, "Passed!" ); + }); + + test( "setLength", function() { + var a = new THREE.Vector3( x, 0, 0 ); + + ok( a.length() == x, "Passed!" ); + a.setLength( y ); + ok( a.length() == y, "Passed!" ); + + a = new THREE.Vector3( 0, 0, 0 ); + ok( a.length() == 0, "Passed!" ); + a.setLength( y ); + ok( a.length() == 0, "Passed!" ); + + }); + + test( "projectOnVector", function() { + var a = new THREE.Vector3( 1, 0, 0 ); + var b = new THREE.Vector3(); + var normal = new THREE.Vector3( 10, 0, 0 ); + + ok( b.copy( a ).projectOnVector( normal ).equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" ); + + a.set( 0, 1, 0 ); + ok( b.copy( a ).projectOnVector( normal ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + + a.set( 0, 0, -1 ); + ok( b.copy( a ).projectOnVector( normal ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + + a.set( -1, 0, 0 ); + ok( b.copy( a ).projectOnVector( normal ).equals( new THREE.Vector3( -1, 0, 0 ) ), "Passed!" ); + + }); + + test( "projectOnPlane", function() { + var a = new THREE.Vector3( 1, 0, 0 ); + var b = new THREE.Vector3(); + var normal = new THREE.Vector3( 1, 0, 0 ); + + ok( b.copy( a ).projectOnPlane( normal ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + + a.set( 0, 1, 0 ); + ok( b.copy( a ).projectOnPlane( normal ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" ); + + a.set( 0, 0, -1 ); + ok( b.copy( a ).projectOnPlane( normal ).equals( new THREE.Vector3( 0, 0, -1 ) ), "Passed!" ); + + a.set( -1, 0, 0 ); + ok( b.copy( a ).projectOnPlane( normal ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); + + }); + + test( "reflect", function() { + var a = new THREE.Vector3( 1, 0, 0 ); + var normal = new THREE.Vector3( 1, 0, 0 ); + var b = new THREE.Vector3( 0, 0, 0 ); + + ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" ); + + a.set( 1, -1, 0 ); + ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); + + a.set( 1, -1, 0 ); + normal.set( 0, -1, 0 ); + ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( -1, -1, 0 ) ), "Passed!" ); + }); + + test( "angleTo", function() { + var a = new THREE.Vector3( 0, -0.18851655680720186, 0.9820700116639124 ); + var b = new THREE.Vector3( 0, 0.18851655680720186, -0.9820700116639124 ); + + equal( a.angleTo( a ), 0 ); + equal( a.angleTo( b ), Math.PI ); + + var x = new THREE.Vector3( 1, 0, 0 ); + var y = new THREE.Vector3( 0, 1, 0 ); + var z = new THREE.Vector3( 0, 0, 1 ); + + equal( x.angleTo( y ), Math.PI / 2 ); + equal( x.angleTo( z ), Math.PI / 2 ); + equal( z.angleTo( x ), Math.PI / 2 ); + + ok( Math.abs( x.angleTo( new THREE.Vector3( 1, 1, 0 ) ) - ( Math.PI / 4 ) ) < 0.0000001 ); + }); + + test( "lerp/clone", function() { + var a = new THREE.Vector3( x, 0, z ); + var b = new THREE.Vector3( 0, -y, 0 ); + + ok( a.lerp( a, 0 ).equals( a.lerp( a, 0.5 ) ), "Passed!" ); + ok( a.lerp( a, 0 ).equals( a.lerp( a, 1 ) ), "Passed!" ); + + ok( a.clone().lerp( b, 0 ).equals( a ), "Passed!" ); + + ok( a.clone().lerp( b, 0.5 ).x == x*0.5, "Passed!" ); + ok( a.clone().lerp( b, 0.5 ).y == -y*0.5, "Passed!" ); + ok( a.clone().lerp( b, 0.5 ).z == z*0.5, "Passed!" ); + + ok( a.clone().lerp( b, 1 ).equals( b ), "Passed!" ); + }); + + test( "equals", function() { + var a = new THREE.Vector3( x, 0, z ); + var b = new THREE.Vector3( 0, -y, 0 ); + + ok( a.x != b.x, "Passed!" ); + ok( a.y != b.y, "Passed!" ); + ok( a.z != b.z, "Passed!" ); + + ok( ! a.equals( b ), "Passed!" ); + ok( ! b.equals( a ), "Passed!" ); + + a.copy( b ); + ok( a.x == b.x, "Passed!" ); + ok( a.y == b.y, "Passed!" ); + ok( a.z == b.z, "Passed!" ); + + ok( a.equals( b ), "Passed!" ); + ok( b.equals( a ), "Passed!" ); + }); + + + test( "constructor", function() { + var a = new THREE.Vector4(); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + ok( a.z == 0, "Passed!" ); + ok( a.w == 1, "Passed!" ); + + a = new THREE.Vector4( x, y, z, w ); + ok( a.x === x, "Passed!" ); + ok( a.y === y, "Passed!" ); + ok( a.z === z, "Passed!" ); + ok( a.w === w, "Passed!" ); + }); + + test( "copy", function() { + var a = new THREE.Vector4( x, y, z, w ); + var b = new THREE.Vector4().copy( a ); + ok( b.x == x, "Passed!" ); + ok( b.y == y, "Passed!" ); + ok( b.z == z, "Passed!" ); + ok( b.w == w, "Passed!" ); + + // ensure that it is a true copy + a.x = 0; + a.y = -1; + a.z = -2; + a.w = -3; + ok( b.x == x, "Passed!" ); + ok( b.y == y, "Passed!" ); + ok( b.z == z, "Passed!" ); + ok( b.w == w, "Passed!" ); + }); + + test( "set", function() { + var a = new THREE.Vector4(); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + ok( a.z == 0, "Passed!" ); + ok( a.w == 1, "Passed!" ); + + a.set( x, y, z, w ); + ok( a.x == x, "Passed!" ); + ok( a.y == y, "Passed!" ); + ok( a.z == z, "Passed!" ); + ok( a.w == w, "Passed!" ); + }); + + test( "setX,setY,setZ,setW", function() { + var a = new THREE.Vector4(); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + ok( a.z == 0, "Passed!" ); + ok( a.w == 1, "Passed!" ); + + a.setX( x ); + a.setY( y ); + a.setZ( z ); + a.setW( w ); + + ok( a.x == x, "Passed!" ); + ok( a.y == y, "Passed!" ); + ok( a.z == z, "Passed!" ); + ok( a.w == w, "Passed!" ); + }); + + test( "setComponent,getComponent", function() { + var a = new THREE.Vector4(); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + ok( a.z == 0, "Passed!" ); + ok( a.w == 1, "Passed!" ); + + a.setComponent( 0, 1 ); + a.setComponent( 1, 2 ); + a.setComponent( 2, 3 ); + a.setComponent( 3, 4 ); + ok( a.getComponent( 0 ) == 1, "Passed!" ); + ok( a.getComponent( 1 ) == 2, "Passed!" ); + ok( a.getComponent( 2 ) == 3, "Passed!" ); + ok( a.getComponent( 3 ) == 4, "Passed!" ); + }); + + test( "add", function() { + var a = new THREE.Vector4( x, y, z, w ); + var b = new THREE.Vector4( -x, -y, -z, -w ); + + a.add( b ); + ok( a.x == 0, "Passed!" ); + ok( a.y == 0, "Passed!" ); + ok( a.z == 0, "Passed!" ); + ok( a.w == 0, "Passed!" ); + + var c = new THREE.Vector4().addVectors( b, b ); + ok( c.x == -2*x, "Passed!" ); + ok( c.y == -2*y, "Passed!" ); + ok( c.z == -2*z, "Passed!" ); + ok( c.w == -2*w, "Passed!" ); + }); + + test( "sub", function() { + var a = new THREE.Vector4( x, y, z, w ); + var b = new THREE.Vector4( -x, -y, -z, -w ); + + a.sub( b ); + ok( a.x == 2*x, "Passed!" ); + ok( a.y == 2*y, "Passed!" ); + ok( a.z == 2*z, "Passed!" ); + ok( a.w == 2*w, "Passed!" ); + + var c = new THREE.Vector4().subVectors( a, a ); + ok( c.x == 0, "Passed!" ); + ok( c.y == 0, "Passed!" ); + ok( c.z == 0, "Passed!" ); + ok( c.w == 0, "Passed!" ); + }); + + test( "multiply/divide", function() { + var a = new THREE.Vector4( x, y, z, w ); + var b = new THREE.Vector4( -x, -y, -z, -w ); + + a.multiplyScalar( -2 ); + ok( a.x == x*-2, "Passed!" ); + ok( a.y == y*-2, "Passed!" ); + ok( a.z == z*-2, "Passed!" ); + ok( a.w == w*-2, "Passed!" ); + + b.multiplyScalar( -2 ); + ok( b.x == 2*x, "Passed!" ); + ok( b.y == 2*y, "Passed!" ); + ok( b.z == 2*z, "Passed!" ); + ok( b.w == 2*w, "Passed!" ); + + a.divideScalar( -2 ); + ok( a.x == x, "Passed!" ); + ok( a.y == y, "Passed!" ); + ok( a.z == z, "Passed!" ); + ok( a.w == w, "Passed!" ); + + b.divideScalar( -2 ); + ok( b.x == -x, "Passed!" ); + ok( b.y == -y, "Passed!" ); + ok( b.z == -z, "Passed!" ); + ok( b.w == -w, "Passed!" ); + }); + + test( "min/max/clamp", function() { + var a = new THREE.Vector4( x, y, z, w ); + var b = new THREE.Vector4( -x, -y, -z, -w ); + var c = new THREE.Vector4(); + + c.copy( a ).min( b ); + ok( c.x == -x, "Passed!" ); + ok( c.y == -y, "Passed!" ); + ok( c.z == -z, "Passed!" ); + ok( c.w == -w, "Passed!" ); + + c.copy( a ).max( b ); + ok( c.x == x, "Passed!" ); + ok( c.y == y, "Passed!" ); + ok( c.z == z, "Passed!" ); + ok( c.w == w, "Passed!" ); + + c.set( -2*x, 2*y, -2*z, 2*w ); + c.clamp( b, a ); + ok( c.x == -x, "Passed!" ); + ok( c.y == y, "Passed!" ); + ok( c.z == -z, "Passed!" ); + ok( c.w == w, "Passed!" ); + }); + + test( "negate", function() { + var a = new THREE.Vector4( x, y, z, w ); + + a.negate(); + ok( a.x == -x, "Passed!" ); + ok( a.y == -y, "Passed!" ); + ok( a.z == -z, "Passed!" ); + ok( a.w == -w, "Passed!" ); + }); + + test( "dot", function() { + var a = new THREE.Vector4( x, y, z, w ); + var b = new THREE.Vector4( -x, -y, -z, -w ); + var c = new THREE.Vector4( 0, 0, 0, 0 ); + + var result = a.dot( b ); + ok( result == (-x*x-y*y-z*z-w*w), "Passed!" ); + + result = a.dot( c ); + ok( result == 0, "Passed!" ); + }); + + test( "length/lengthSq", function() { + var a = new THREE.Vector4( x, 0, 0, 0 ); + var b = new THREE.Vector4( 0, -y, 0, 0 ); + var c = new THREE.Vector4( 0, 0, z, 0 ); + var d = new THREE.Vector4( 0, 0, 0, w ); + var e = new THREE.Vector4( 0, 0, 0, 0 ); + + ok( a.length() == x, "Passed!" ); + ok( a.lengthSq() == x*x, "Passed!" ); + ok( b.length() == y, "Passed!" ); + ok( b.lengthSq() == y*y, "Passed!" ); + ok( c.length() == z, "Passed!" ); + ok( c.lengthSq() == z*z, "Passed!" ); + ok( d.length() == w, "Passed!" ); + ok( d.lengthSq() == w*w, "Passed!" ); + ok( e.length() == 0, "Passed!" ); + ok( e.lengthSq() == 0, "Passed!" ); + + a.set( x, y, z, w ); + ok( a.length() == Math.sqrt( x*x + y*y + z*z + w*w ), "Passed!" ); + ok( a.lengthSq() == ( x*x + y*y + z*z + w*w ), "Passed!" ); + }); + + test( "normalize", function() { + var a = new THREE.Vector4( x, 0, 0, 0 ); + var b = new THREE.Vector4( 0, -y, 0, 0 ); + var c = new THREE.Vector4( 0, 0, z, 0 ); + var d = new THREE.Vector4( 0, 0, 0, -w ); + + a.normalize(); + ok( a.length() == 1, "Passed!" ); + ok( a.x == 1, "Passed!" ); + + b.normalize(); + ok( b.length() == 1, "Passed!" ); + ok( b.y == -1, "Passed!" ); + + c.normalize(); + ok( c.length() == 1, "Passed!" ); + ok( c.z == 1, "Passed!" ); + + d.normalize(); + ok( d.length() == 1, "Passed!" ); + ok( d.w == -1, "Passed!" ); + }); + + /* + test( "distanceTo/distanceToSquared", function() { + var a = new THREE.Vector4( x, 0, 0, 0 ); + var b = new THREE.Vector4( 0, -y, 0, 0 ); + var c = new THREE.Vector4( 0, 0, z, 0 ); + var d = new THREE.Vector4( 0, 0, 0, -w ); + var e = new THREE.Vector4(); + + ok( a.distanceTo( e ) == x, "Passed!" ); + ok( a.distanceToSquared( e ) == x*x, "Passed!" ); + + ok( b.distanceTo( e ) == y, "Passed!" ); + ok( b.distanceToSquared( e ) == y*y, "Passed!" ); + + ok( c.distanceTo( e ) == z, "Passed!" ); + ok( c.distanceToSquared( e ) == z*z, "Passed!" ); + + ok( d.distanceTo( e ) == w, "Passed!" ); + ok( d.distanceToSquared( e ) == w*w, "Passed!" ); + }); + */ + + + test( "setLength", function() { + var a = new THREE.Vector4( x, 0, 0, 0 ); + + ok( a.length() == x, "Passed!" ); + a.setLength( y ); + ok( a.length() == y, "Passed!" ); + + a = new THREE.Vector4( 0, 0, 0, 0 ); + ok( a.length() == 0, "Passed!" ); + a.setLength( y ); + ok( a.length() == 0, "Passed!" ); + }); + + test( "lerp/clone", function() { + var a = new THREE.Vector4( x, 0, z, 0 ); + var b = new THREE.Vector4( 0, -y, 0, -w ); + + ok( a.lerp( a, 0 ).equals( a.lerp( a, 0.5 ) ), "Passed!" ); + ok( a.lerp( a, 0 ).equals( a.lerp( a, 1 ) ), "Passed!" ); + + ok( a.clone().lerp( b, 0 ).equals( a ), "Passed!" ); + + ok( a.clone().lerp( b, 0.5 ).x == x*0.5, "Passed!" ); + ok( a.clone().lerp( b, 0.5 ).y == -y*0.5, "Passed!" ); + ok( a.clone().lerp( b, 0.5 ).z == z*0.5, "Passed!" ); + ok( a.clone().lerp( b, 0.5 ).w == -w*0.5, "Passed!" ); + + ok( a.clone().lerp( b, 1 ).equals( b ), "Passed!" ); + }); + + test( "equals", function() { + var a = new THREE.Vector4( x, 0, z, 0 ); + var b = new THREE.Vector4( 0, -y, 0, -w ); + + ok( a.x != b.x, "Passed!" ); + ok( a.y != b.y, "Passed!" ); + ok( a.z != b.z, "Passed!" ); + ok( a.w != b.w, "Passed!" ); + + ok( ! a.equals( b ), "Passed!" ); + ok( ! b.equals( a ), "Passed!" ); + + a.copy( b ); + ok( a.x == b.x, "Passed!" ); + ok( a.y == b.y, "Passed!" ); + ok( a.z == b.z, "Passed!" ); + ok( a.w == b.w, "Passed!" ); + + ok( a.equals( b ), "Passed!" ); + ok( b.equals( a ), "Passed!" ); + }); +}; diff --git a/threejs/tests/three-tests-setup.ts b/threejs/tests/three-tests-setup.ts new file mode 100644 index 0000000000..33b36098bb --- /dev/null +++ b/threejs/tests/three-tests-setup.ts @@ -0,0 +1,26 @@ +///////////////////////////////////////////////////////////// +// https://github.com/mrdoob/three.js/tree/master/examples +////////////////////////////////////////////////////////////// + +declare var Stats: any; +declare var Detector: any; + +declare module THREE { + var AWDLoader: any; + var CSS3DSprite: any; + var CSS3DRenderer: any; + var CSS3DObject: any; + var DotScreenShader: any; + var TrackballControls: any; + var FlyControls: any; + var RenderPass: any; + var EffectComposer: any; + var OrbitControls: any; + var RGBShiftShader: any; + var RenderPass: any; + var BloomPass: any; + var ShaderPass: any; + var FXAAShader: any; + var CopyShader: any; +} + diff --git a/threejs/tests/webgl/webgl_animation_cloth.ts b/threejs/tests/webgl/webgl_animation_cloth.ts new file mode 100644 index 0000000000..58b29f3b50 --- /dev/null +++ b/threejs/tests/webgl/webgl_animation_cloth.ts @@ -0,0 +1,299 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_animation_cloth.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + var cloth: any; + var clothFunction: any; + var ballPosition: any; + var ballSize: any; + var windStrength: any; + var windForce: any; + var simulate: Function; + // ------- + + /* testing cloth simulation */ + var pinsFormation = []; + var pins = [6]; + + pinsFormation.push(pins); + + pins = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + pinsFormation.push(pins); + + pins = [0]; + pinsFormation.push(pins); + + pins = []; // cut the rope ;) + pinsFormation.push(pins); + + pins = [0, cloth.w]; // classic 2 pins + pinsFormation.push(pins); + + pins = pinsFormation[1]; + + + function togglePins() { + + pins = pinsFormation[~~(Math.random() * pinsFormation.length)]; + + } + + if (!Detector.webgl) Detector.addGetWebGLMessage(); + + var container, stats; + var camera, scene, renderer; + + var clothGeometry; + var sphere; + var object, arrow; + + var rotate = true; + + init(); + animate(); + + function init() { + + container = document.createElement('div'); + document.body.appendChild(container); + + // scene + + scene = new THREE.Scene(); + + scene.fog = new THREE.Fog(0xcce0ff, 500, 10000); + + // camera + + camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 1, 10000); + camera.position.y = 50; + camera.position.z = 1500; + scene.add(camera); + + // lights + + var light, materials; + + scene.add(new THREE.AmbientLight(0x666666)); + + light = new THREE.DirectionalLight(0xdfebff, 1.75); + light.position.set(50, 200, 100); + light.position.multiplyScalar(1.3); + + light.castShadow = true; + //light.shadowCameraVisible = true; + + light.shadowMapWidth = 2048; + light.shadowMapHeight = 2048; + + var d = 300; + + light.shadowCameraLeft = -d; + light.shadowCameraRight = d; + light.shadowCameraTop = d; + light.shadowCameraBottom = -d; + + light.shadowCameraFar = 1000; + light.shadowDarkness = 0.5; + + scene.add(light); + + light = new THREE.DirectionalLight(0x3dff0c, 0.35); + light.position.set(0, -1, 0); + + scene.add(light); + + // cloth material + + var clothTexture = THREE.ImageUtils.loadTexture('textures/patterns/circuit_pattern.png'); + clothTexture.wrapS = clothTexture.wrapT = THREE.RepeatWrapping; + clothTexture.anisotropy = 16; + + var clothMaterial = new THREE.MeshPhongMaterial({ alphaTest: 0.5, ambient: 0xffffff, color: 0xffffff, specular: 0x030303, emissive: 0x111111, shiness: 10, map: clothTexture, side: THREE.DoubleSide }); + + // cloth geometry + clothGeometry = new THREE.ParametricGeometry(clothFunction, cloth.w, cloth.h); + clothGeometry.dynamic = true; + clothGeometry.computeFaceNormals(); + + var uniforms = { texture: { type: "t", value: clothTexture } }; + var vertexShader = document.getElementById('vertexShaderDepth').textContent; + var fragmentShader = document.getElementById('fragmentShaderDepth').textContent; + + // cloth mesh + + object = new THREE.Mesh(clothGeometry, clothMaterial); + object.position.set(0, 0, 0); + object.castShadow = true; + object.receiveShadow = true; + scene.add(object); + + object.customDepthMaterial = new THREE.ShaderMaterial({ uniforms: uniforms, vertexShader: vertexShader, fragmentShader: fragmentShader }); + + // sphere + + var ballGeo = new THREE.SphereGeometry(ballSize, 20, 20); + var ballMaterial = new THREE.MeshPhongMaterial({ color: 0xffffff }); + + sphere = new THREE.Mesh(ballGeo, ballMaterial); + sphere.castShadow = true; + sphere.receiveShadow = true; + scene.add(sphere); + + // arrow + + arrow = new THREE.ArrowHelper(new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 0), 50, 0xff0000); + arrow.position.set(-200, 0, -200); + // scene.add( arrow ); + + // ground + + var initColor = new THREE.Color(0x497f13); + var initTexture = THREE.ImageUtils.generateDataTexture(1, 1, initColor); + + var groundMaterial = new THREE.MeshPhongMaterial({ color: 0xffffff, specular: 0x111111, map: initTexture }); + + var groundTexture = THREE.ImageUtils.loadTexture("textures/terrain/grasslight-big.jpg", undefined, function () { groundMaterial.map = groundTexture }); + groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping; + groundTexture.repeat.set(25, 25); + groundTexture.anisotropy = 16; + + var mesh = new THREE.Mesh(new THREE.PlaneGeometry(20000, 20000), groundMaterial); + mesh.position.y = -250; + mesh.rotation.x = - Math.PI / 2; + mesh.receiveShadow = true; + scene.add(mesh); + + // poles + + var poleGeo = new THREE.BoxGeometry(5, 375, 5); + var poleMat = new THREE.MeshPhongMaterial({ color: 0xffffff, specular: 0x111111, shiness: 100 }); + + var mesh = new THREE.Mesh(poleGeo, poleMat); + mesh.position.x = -125; + mesh.position.y = -62; + mesh.receiveShadow = true; + mesh.castShadow = true; + scene.add(mesh); + + var mesh = new THREE.Mesh(poleGeo, poleMat); + mesh.position.x = 125; + mesh.position.y = -62; + mesh.receiveShadow = true; + mesh.castShadow = true; + scene.add(mesh); + + var mesh = new THREE.Mesh(new THREE.BoxGeometry(255, 5, 5), poleMat); + mesh.position.y = -250 + 750 / 2; + mesh.position.x = 0; + mesh.receiveShadow = true; + mesh.castShadow = true; + scene.add(mesh); + + var gg = new THREE.BoxGeometry(10, 10, 10); + var mesh = new THREE.Mesh(gg, poleMat); + mesh.position.y = -250; + mesh.position.x = 125; + mesh.receiveShadow = true; + mesh.castShadow = true; + scene.add(mesh); + + var mesh = new THREE.Mesh(gg, poleMat); + mesh.position.y = -250; + mesh.position.x = -125; + mesh.receiveShadow = true; + mesh.castShadow = true; + scene.add(mesh); + + // + + renderer = new THREE.WebGLRenderer({ antialias: true }); + renderer.setSize(window.innerWidth, window.innerHeight); + renderer.setClearColor(scene.fog.color); + + container.appendChild(renderer.domElement); + + renderer.gammaInput = true; + renderer.gammaOutput = true; + + renderer.shadowMapEnabled = true; + + // + + stats = new Stats(); + container.appendChild(stats.domElement); + + // + + window.addEventListener('resize', onWindowResize, false); + + sphere.visible = !true + + } + + // + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + var time = Date.now(); + + windStrength = Math.cos(time / 7000) * 20 + 40; + windForce.set(Math.sin(time / 2000), Math.cos(time / 3000), Math.sin(time / 1000)).normalize().multiplyScalar(windStrength); + arrow.setLength(windStrength); + arrow.setDirection(windForce); + + simulate(time); + render(); + stats.update(); + + } + + function render() { + + var timer = Date.now() * 0.0002; + + var p = cloth.particles; + + for (var i = 0, il = p.length; i < il; i++) { + + clothGeometry.vertices[i].copy(p[i].position); + + } + + clothGeometry.computeFaceNormals(); + clothGeometry.computeVertexNormals(); + + clothGeometry.normalsNeedUpdate = true; + clothGeometry.verticesNeedUpdate = true; + + sphere.position.copy(ballPosition); + + if (rotate) { + + camera.position.x = Math.cos(timer) * 1500; + camera.position.z = Math.sin(timer) * 1500; + + } + + camera.lookAt(scene.position); + + renderer.render(scene, camera); + + } +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_buffergeometry.ts b/threejs/tests/webgl/webgl_buffergeometry.ts new file mode 100644 index 0000000000..f8d4559324 --- /dev/null +++ b/threejs/tests/webgl/webgl_buffergeometry.ts @@ -0,0 +1,248 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_buffergeometry.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + + // ------- + + if (!Detector.webgl) Detector.addGetWebGLMessage(); + + var container, stats; + + var camera, scene, renderer; + + var mesh; + + init(); + animate(); + + function init() { + + container = document.getElementById('container'); + + // + + camera = new THREE.PerspectiveCamera(27, window.innerWidth / window.innerHeight, 1, 3500); + camera.position.z = 2750; + + scene = new THREE.Scene(); + scene.fog = new THREE.Fog(0x050505, 2000, 3500); + + // + + scene.add(new THREE.AmbientLight(0x444444)); + + var light1 = new THREE.DirectionalLight(0xffffff, 0.5); + light1.position.set(1, 1, 1); + scene.add(light1); + + var light2 = new THREE.DirectionalLight(0xffffff, 1.5); + light2.position.set(0, -1, 0); + scene.add(light2); + + // + + var triangles = 160000; + + var geometry = new THREE.BufferGeometry(); + + geometry.addAttribute('index', new Uint16Array(triangles * 3), 1); + geometry.addAttribute('position', new Float32Array(triangles * 3 * 3), 3); + geometry.addAttribute('normal', new Float32Array(triangles * 3 * 3), 3); + geometry.addAttribute('color', new Float32Array(triangles * 3 * 3), 3); + + // break geometry into + // chunks of 21,845 triangles (3 unique vertices per triangle) + // for indices to fit into 16 bit integer number + // floor(2^16 / 3) = 21845 + + var chunkSize = 21845; + + var indices = geometry.getAttribute('index').array; + + for (var i = 0; i < indices.length; i++) { + + indices[i] = i % (3 * chunkSize); + + } + + var positions = geometry.getAttribute('position').array; + var normals = geometry.getAttribute('normal').array; + var colors = geometry.getAttribute('color').array; + + var color = new THREE.Color(); + + var n = 800, n2 = n / 2; // triangles spread in the cube + var d = 12, d2 = d / 2; // individual triangle size + + var pA = new THREE.Vector3(); + var pB = new THREE.Vector3(); + var pC = new THREE.Vector3(); + + var cb = new THREE.Vector3(); + var ab = new THREE.Vector3(); + + for (var i = 0; i < positions.length; i += 9) { + + // positions + + var x = Math.random() * n - n2; + var y = Math.random() * n - n2; + var z = Math.random() * n - n2; + + var ax = x + Math.random() * d - d2; + var ay = y + Math.random() * d - d2; + var az = z + Math.random() * d - d2; + + var bx = x + Math.random() * d - d2; + var by = y + Math.random() * d - d2; + var bz = z + Math.random() * d - d2; + + var cx = x + Math.random() * d - d2; + var cy = y + Math.random() * d - d2; + var cz = z + Math.random() * d - d2; + + positions[i] = ax; + positions[i + 1] = ay; + positions[i + 2] = az; + + positions[i + 3] = bx; + positions[i + 4] = by; + positions[i + 5] = bz; + + positions[i + 6] = cx; + positions[i + 7] = cy; + positions[i + 8] = cz; + + // flat face normals + + pA.set(ax, ay, az); + pB.set(bx, by, bz); + pC.set(cx, cy, cz); + + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + + cb.normalize(); + + var nx = cb.x; + var ny = cb.y; + var nz = cb.z; + + normals[i] = nx; + normals[i + 1] = ny; + normals[i + 2] = nz; + + normals[i + 3] = nx; + normals[i + 4] = ny; + normals[i + 5] = nz; + + normals[i + 6] = nx; + normals[i + 7] = ny; + normals[i + 8] = nz; + + // colors + + var vx = (x / n) + 0.5; + var vy = (y / n) + 0.5; + var vz = (z / n) + 0.5; + + color.setRGB(vx, vy, vz); + + colors[i] = color.r; + colors[i + 1] = color.g; + colors[i + 2] = color.b; + + colors[i + 3] = color.r; + colors[i + 4] = color.g; + colors[i + 5] = color.b; + + colors[i + 6] = color.r; + colors[i + 7] = color.g; + colors[i + 8] = color.b; + + } + + var offsets = triangles / chunkSize; + + for (var i = 0; i < offsets; i++) { + + var offset = { + start: i * chunkSize * 3, + index: i * chunkSize * 3, + count: Math.min(triangles - (i * chunkSize), chunkSize) * 3 + }; + + geometry.offsets.push(offset); + + } + + geometry.computeBoundingSphere(); + + var material = new THREE.MeshPhongMaterial({ + color: 0xaaaaaa, ambient: 0xaaaaaa, specular: 0xffffff, shininess: 250, + side: THREE.DoubleSide, vertexColors: THREE.VertexColors + }); + + mesh = new THREE.Mesh(geometry, material); + scene.add(mesh); + + // + + renderer = new THREE.WebGLRenderer({ antialias: false }); + renderer.setClearColor(scene.fog.color, 1); + renderer.setSize(window.innerWidth, window.innerHeight); + + renderer.gammaInput = true; + renderer.gammaOutput = true; + + container.appendChild(renderer.domElement); + + // + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + container.appendChild(stats.domElement); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + var time = Date.now() * 0.001; + + mesh.rotation.x = time * 0.25; + mesh.rotation.y = time * 0.5; + + renderer.render(scene, camera); + + } +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_camera.ts b/threejs/tests/webgl/webgl_camera.ts new file mode 100644 index 0000000000..4bf35883cc --- /dev/null +++ b/threejs/tests/webgl/webgl_camera.ts @@ -0,0 +1,218 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_camera.html + +() => { + var SCREEN_WIDTH = window.innerWidth; + var SCREEN_HEIGHT = window.innerHeight; + + var container, stats; + var camera, scene, renderer, mesh; + var cameraRig, activeCamera, activeHelper; + var cameraPerspective, cameraOrtho; + var cameraPerspectiveHelper, cameraOrthoHelper; + + init(); + animate(); + + function init() { + container = document.createElement('div'); + document.body.appendChild(container); + + scene = new THREE.Scene(); + + // + + camera = new THREE.PerspectiveCamera(50, 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000); + camera.position.z = 2500; + + cameraPerspective = new THREE.PerspectiveCamera(50, 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT, 150, 1000); + + cameraPerspectiveHelper = new THREE.CameraHelper(cameraPerspective); + scene.add(cameraPerspectiveHelper); + + // + + cameraOrtho = new THREE.OrthographicCamera(0.5 * SCREEN_WIDTH / - 2, 0.5 * SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, SCREEN_HEIGHT / - 2, 150, 1000); + + cameraOrthoHelper = new THREE.CameraHelper(cameraOrtho); + scene.add(cameraOrthoHelper); + + // + + activeCamera = cameraPerspective; + activeHelper = cameraPerspectiveHelper; + + + // counteract different front orientation of cameras vs rig + + cameraOrtho.rotation.y = Math.PI; + cameraPerspective.rotation.y = Math.PI; + + cameraRig = new THREE.Object3D(); + + cameraRig.add(cameraPerspective); + cameraRig.add(cameraOrtho); + + scene.add(cameraRig); + + // + + mesh = new THREE.Mesh(new THREE.SphereGeometry(100, 16, 8), new THREE.MeshBasicMaterial({ color: 0xffffff, wireframe: true })); + scene.add(mesh); + + var mesh2 = new THREE.Mesh(new THREE.SphereGeometry(50, 16, 8), new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: true })); + mesh2.position.y = 150; + mesh.add(mesh2); + + var mesh3 = new THREE.Mesh(new THREE.SphereGeometry(5, 16, 8), new THREE.MeshBasicMaterial({ color: 0x0000ff, wireframe: true })); + mesh3.position.z = 150; + cameraRig.add(mesh3); + + // + + var geometry = new THREE.Geometry(); + + for (var i = 0; i < 10000; i++) { + + var vertex = new THREE.Vector3(); + vertex.x = THREE.Math.randFloatSpread(2000); + vertex.y = THREE.Math.randFloatSpread(2000); + vertex.z = THREE.Math.randFloatSpread(2000); + + geometry.vertices.push(vertex); + + } + + var particles = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial({ color: 0x888888 })); + scene.add(particles); + + // + + + renderer = new THREE.WebGLRenderer({ antialias: true }); + renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT); + renderer.domElement.style.position = "relative"; + container.appendChild(renderer.domElement); + + renderer.autoClear = false; + + // + + stats = new Stats(); + container.appendChild(stats.domElement); + + // + + window.addEventListener('resize', onWindowResize, false); + document.addEventListener('keydown', onKeyDown, false); + + } + + // + + function onKeyDown(event) { + + switch (event.keyCode) { + + case 79: /*O*/ + + activeCamera = cameraOrtho; + activeHelper = cameraOrthoHelper; + + break; + + case 80: /*P*/ + + activeCamera = cameraPerspective; + activeHelper = cameraPerspectiveHelper; + + break; + + } + + }; + + // + + function onWindowResize(event) { + + SCREEN_WIDTH = window.innerWidth; + SCREEN_HEIGHT = window.innerHeight; + + renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT); + + camera.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT; + camera.updateProjectionMatrix(); + + cameraPerspective.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT; + cameraPerspective.updateProjectionMatrix(); + + cameraOrtho.left = - 0.5 * SCREEN_WIDTH / 2; + cameraOrtho.right = 0.5 * SCREEN_WIDTH / 2; + cameraOrtho.top = SCREEN_HEIGHT / 2; + cameraOrtho.bottom = - SCREEN_HEIGHT / 2; + cameraOrtho.updateProjectionMatrix(); + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + var r = Date.now() * 0.0005; + + mesh.position.x = 700 * Math.cos(r); + mesh.position.z = 700 * Math.sin(r); + mesh.position.y = 700 * Math.sin(r); + + mesh.children[0].position.x = 70 * Math.cos(2 * r); + mesh.children[0].position.z = 70 * Math.sin(r); + + if (activeCamera === cameraPerspective) { + + cameraPerspective.fov = 35 + 30 * Math.sin(0.5 * r); + cameraPerspective.far = mesh.position.length(); + cameraPerspective.updateProjectionMatrix(); + + cameraPerspectiveHelper.update(); + cameraPerspectiveHelper.visible = true; + + cameraOrthoHelper.visible = false; + + } else { + cameraOrtho.far = mesh.position.length(); + cameraOrtho.updateProjectionMatrix(); + + cameraOrthoHelper.update(); + cameraOrthoHelper.visible = true; + + cameraPerspectiveHelper.visible = false; + + } + + cameraRig.lookAt(mesh.position); + + renderer.clear(); + + activeHelper.visible = false; + + renderer.setViewport(0, 0, SCREEN_WIDTH / 2, SCREEN_HEIGHT); + renderer.render(scene, activeCamera); + + activeHelper.visible = true; + + renderer.setViewport(SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2, SCREEN_HEIGHT); + renderer.render(scene, camera); + } +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_custom_attributes.ts b/threejs/tests/webgl/webgl_custom_attributes.ts new file mode 100644 index 0000000000..93d9bfbe92 --- /dev/null +++ b/threejs/tests/webgl/webgl_custom_attributes.ts @@ -0,0 +1,134 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_custom_attributes.html + +() => { + if (!Detector.webgl) Detector.addGetWebGLMessage(); + + var renderer, scene, camera, stats; + + var sphere, uniforms, attributes; + + var noise = []; + + var WIDTH = window.innerWidth, + HEIGHT = window.innerHeight; + + init(); + animate(); + + function init() { + + camera = new THREE.PerspectiveCamera(30, WIDTH / HEIGHT, 1, 10000); + camera.position.z = 300; + + scene = new THREE.Scene(); + + attributes = { + + displacement: { type: 'f', value: [] } + + }; + + uniforms = { + + amplitude: { type: "f", value: 1.0 }, + color: { type: "c", value: new THREE.Color(0xff2200) }, + texture: { type: "t", value: THREE.ImageUtils.loadTexture("textures/water.jpg") } + + }; + + uniforms.texture.value.wrapS = uniforms.texture.value.wrapT = THREE.RepeatWrapping; + + var shaderMaterial = new THREE.ShaderMaterial({ + + uniforms: uniforms, + attributes: attributes, + vertexShader: document.getElementById('vertexshader').textContent, + fragmentShader: document.getElementById('fragmentshader').textContent + + }); + + + var radius = 50, segments = 128, rings = 64; + var geometry = new THREE.SphereGeometry(radius, segments, rings); + geometry.dynamic = true; + + sphere = new THREE.Mesh(geometry, shaderMaterial); + + var vertices = sphere.geometry.vertices; + var values = attributes.displacement.value; + + for (var v = 0; v < vertices.length; v++) { + + values[v] = 0; + noise[v] = Math.random() * 5; + + } + + scene.add(sphere); + + renderer = new THREE.WebGLRenderer(); + renderer.setClearColor(0x050505, 1); + renderer.setSize(WIDTH, HEIGHT); + + var container = document.getElementById('container'); + container.appendChild(renderer.domElement); + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + container.appendChild(stats.domElement); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + var time = Date.now() * 0.01; + + sphere.rotation.y = sphere.rotation.z = 0.01 * time; + + uniforms.amplitude.value = 2.5 * Math.sin(sphere.rotation.y * 0.125); + uniforms.color.value.offsetHSL(0.0005, 0, 0); + + for (var i = 0; i < attributes.displacement.value.length; i++) { + + attributes.displacement.value[i] = Math.sin(0.1 * i + time); + + noise[i] += 0.5 * (0.5 - Math.random()); + noise[i] = THREE.Math.clamp(noise[i], -5, 5); + + attributes.displacement.value[i] += noise[i]; + + } + + attributes.displacement.needsUpdate = true; + + renderer.render(scene, camera); + + } + +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_geometries.ts b/threejs/tests/webgl/webgl_geometries.ts new file mode 100644 index 0000000000..f56a5ab41f --- /dev/null +++ b/threejs/tests/webgl/webgl_geometries.ts @@ -0,0 +1,170 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometries.html + +() => { + if (!Detector.webgl) Detector.addGetWebGLMessage(); + + var container, stats; + + var camera, scene, renderer; + + init(); + animate(); + + function init() { + + container = document.createElement('div'); + document.body.appendChild(container); + + camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000); + camera.position.y = 400; + + scene = new THREE.Scene(); + + var light, object; + + scene.add(new THREE.AmbientLight(0x404040)); + + light = new THREE.DirectionalLight(0xffffff); + light.position.set(0, 1, 0); + scene.add(light); + + var map = THREE.ImageUtils.loadTexture('textures/UV_Grid_Sm.jpg'); + map.wrapS = map.wrapT = THREE.RepeatWrapping; + map.anisotropy = 16; + + var material = new THREE.MeshLambertMaterial({ ambient: 0xbbbbbb, map: map, side: THREE.DoubleSide }); + + // + + object = new THREE.Mesh(new THREE.SphereGeometry(75, 20, 10), material); + object.position.set(-400, 0, 200); + scene.add(object); + + object = new THREE.Mesh(new THREE.IcosahedronGeometry(75, 1), material); + object.position.set(-200, 0, 200); + scene.add(object); + + object = new THREE.Mesh(new THREE.OctahedronGeometry(75, 2), material); + object.position.set(0, 0, 200); + scene.add(object); + + object = new THREE.Mesh(new THREE.TetrahedronGeometry(75, 0), material); + object.position.set(200, 0, 200); + scene.add(object); + + // + + object = new THREE.Mesh(new THREE.PlaneGeometry(100, 100, 4, 4), material); + object.position.set(-400, 0, 0); + scene.add(object); + + object = new THREE.Mesh(new THREE.BoxGeometry(100, 100, 100, 4, 4, 4), material); + object.position.set(-200, 0, 0); + scene.add(object); + + object = new THREE.Mesh(new THREE.CircleGeometry(50, 20, 0, Math.PI * 2), material); + object.position.set(0, 0, 0); + scene.add(object); + + object = new THREE.Mesh(new THREE.RingGeometry(10, 50, 20, 5, 0, Math.PI * 2), material); + object.position.set(200, 0, 0); + scene.add(object); + + object = new THREE.Mesh(new THREE.CylinderGeometry(25, 75, 100, 40, 5), material); + object.position.set(400, 0, 0); + scene.add(object); + + // + + var points = []; + + for (var i = 0; i < 50; i++) { + + points.push(new THREE.Vector3(Math.sin(i * 0.2) * Math.sin(i * 0.1) * 15 + 50, 0, (i - 5) * 2)); + + } + + object = new THREE.Mesh(new THREE.LatheGeometry(points, 20), material); + object.position.set(-400, 0, -200); + scene.add(object); + + object = new THREE.Mesh(new THREE.TorusGeometry(50, 20, 20, 20), material); + object.position.set(-200, 0, -200); + scene.add(object); + + object = new THREE.Mesh(new THREE.TorusKnotGeometry(50, 10, 50, 20), material); + object.position.set(0, 0, -200); + scene.add(object); + + object = new THREE.AxisHelper(50); + object.position.set(200, 0, -200); + scene.add(object); + + object = new THREE.ArrowHelper(new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 0), 50); + object.position.set(400, 0, -200); + scene.add(object); + + // + + renderer = new THREE.WebGLRenderer({ antialias: true }); + renderer.setSize(window.innerWidth, window.innerHeight); + + container.appendChild(renderer.domElement); + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + container.appendChild(stats.domElement); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + var timer = Date.now() * 0.0001; + + camera.position.x = Math.cos(timer) * 800; + camera.position.z = Math.sin(timer) * 800; + + camera.lookAt(scene.position); + + for (var i = 0, l = scene.children.length; i < l; i++) { + + var object = scene.children[i]; + + object.rotation.x = timer * 5; + object.rotation.y = timer * 2.5; + + } + + renderer.render(scene, camera); + + } + +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_helpers.ts b/threejs/tests/webgl/webgl_helpers.ts new file mode 100644 index 0000000000..3f324316b2 --- /dev/null +++ b/threejs/tests/webgl/webgl_helpers.ts @@ -0,0 +1,92 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_helpers.html + +() => { + var scene, renderer; + var camera, light; + + init(); + animate(); + + function init() { + + renderer = new THREE.WebGLRenderer(); + renderer.setSize(window.innerWidth, window.innerHeight); + document.body.appendChild(renderer.domElement); + + // + + camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000); + camera.position.z = 400; + + scene = new THREE.Scene(); + + light = new THREE.PointLight(); + light.position.set(200, 100, 150); + scene.add(light); + + scene.add(new THREE.PointLightHelper(light, 5)); + + var helper = new THREE.GridHelper(200, 10); + helper.setColors(0x0000ff, 0x808080); + helper.position.y = - 150; + scene.add(helper); + + var loader = new THREE.JSONLoader(); + loader.load('obj/leeperrysmith/LeePerrySmith.js', function (geometry, materials) { + + var material = new THREE.MeshLambertMaterial(); + + var mesh = new THREE.Mesh(geometry, material); + mesh.scale.multiplyScalar(50); + scene.add(mesh); + + scene.add(new THREE.FaceNormalsHelper(mesh, 10)); + scene.add(new THREE.VertexNormalsHelper(mesh, 10)); + + var helper = new THREE.WireframeHelper(mesh); + helper.material.depthTest = false; + helper.material.opacity = 0.25; + helper.material.transparent = true; + scene.add(helper); + + scene.add(new THREE.BoxHelper(mesh)); + + }); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + function animate() { + + requestAnimationFrame(animate); + + var time = - performance.now() * 0.0003; + + camera.position.x = 400 * Math.cos(time); + camera.position.z = 400 * Math.sin(time); + camera.lookAt(scene.position); + + light.position.x = Math.sin(time * 1.7) * 300; + light.position.y = Math.cos(time * 1.5) * 400; + light.position.z = Math.cos(time * 1.3) * 300; + + renderer.render(scene, camera); + + } + +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_interactive_cubes.ts b/threejs/tests/webgl/webgl_interactive_cubes.ts new file mode 100644 index 0000000000..a99345e9f5 --- /dev/null +++ b/threejs/tests/webgl/webgl_interactive_cubes.ts @@ -0,0 +1,155 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_interactive_cubes.html + +() => { + var container, stats; + var camera, scene, projector, raycaster, renderer; + + var mouse = new THREE.Vector2(), INTERSECTED; + var radius = 100, theta = 0; + + init(); + animate(); + + function init() { + + container = document.createElement('div'); + document.body.appendChild(container); + + var info = document.createElement('div'); + info.style.position = 'absolute'; + info.style.top = '10px'; + info.style.width = '100%'; + info.style.textAlign = 'center'; + info.innerHTML = 'three.js webgl - interactive cubes'; + container.appendChild(info); + + camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000); + + scene = new THREE.Scene(); + + var light = new THREE.DirectionalLight(0xffffff, 2); + light.position.set(1, 1, 1).normalize(); + scene.add(light); + + var light = new THREE.DirectionalLight(0xffffff); + light.position.set(-1, -1, -1).normalize(); + scene.add(light); + + var geometry = new THREE.BoxGeometry(20, 20, 20); + + for (var i = 0; i < 2000; i++) { + + var object = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({ color: Math.random() * 0xffffff })); + + object.position.x = Math.random() * 800 - 400; + object.position.y = Math.random() * 800 - 400; + object.position.z = Math.random() * 800 - 400; + + object.rotation.x = Math.random() * 2 * Math.PI; + object.rotation.y = Math.random() * 2 * Math.PI; + object.rotation.z = Math.random() * 2 * Math.PI; + + object.scale.x = Math.random() + 0.5; + object.scale.y = Math.random() + 0.5; + object.scale.z = Math.random() + 0.5; + + scene.add(object); + + } + + projector = new THREE.Projector(); + raycaster = new THREE.Raycaster(); + + renderer = new THREE.WebGLRenderer(); + renderer.setClearColor(0xf0f0f0); + renderer.setSize(window.innerWidth, window.innerHeight); + renderer.sortObjects = false; + container.appendChild(renderer.domElement); + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + container.appendChild(stats.domElement); + + document.addEventListener('mousemove', onDocumentMouseMove, false); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + function onDocumentMouseMove(event) { + + event.preventDefault(); + + mouse.x = (event.clientX / window.innerWidth) * 2 - 1; + mouse.y = - (event.clientY / window.innerHeight) * 2 + 1; + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + theta += 0.1; + + camera.position.x = radius * Math.sin(THREE.Math.degToRad(theta)); + camera.position.y = radius * Math.sin(THREE.Math.degToRad(theta)); + camera.position.z = radius * Math.cos(THREE.Math.degToRad(theta)); + camera.lookAt(scene.position); + + // find intersections + + var vector = new THREE.Vector3(mouse.x, mouse.y, 1); + projector.unprojectVector(vector, camera); + + raycaster.set(camera.position, vector.sub(camera.position).normalize()); + + var intersects = raycaster.intersectObjects(scene.children); + + if (intersects.length > 0) { + + if (INTERSECTED != intersects[0].object) { + + if (INTERSECTED) INTERSECTED.material.emissive.setHex(INTERSECTED.currentHex); + + INTERSECTED = intersects[0].object; + INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex(); + INTERSECTED.material.emissive.setHex(0xff0000); + + } + + } else { + + if (INTERSECTED) INTERSECTED.material.emissive.setHex(INTERSECTED.currentHex); + + INTERSECTED = null; + + } + + renderer.render(scene, camera); + + } +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_lensflares.ts b/threejs/tests/webgl/webgl_lensflares.ts new file mode 100644 index 0000000000..c8e1bfed49 --- /dev/null +++ b/threejs/tests/webgl/webgl_lensflares.ts @@ -0,0 +1,205 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_lensflares.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + var controls: any; + // ------- + + var container, stats; + + var camera, scene, renderer; + + var clock = new THREE.Clock(); + + var composer; + + init(); + animate(); + + function init() { + + container = document.createElement('div'); + document.body.appendChild(container); + + // camera + + camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 15000); + camera.position.z = 250; + + controls = new THREE.FlyControls(camera); + + controls.movementSpeed = 2500; + controls.domElement = container; + controls.rollSpeed = Math.PI / 6; + controls.autoForward = false; + controls.dragToLook = false + + // scene + + scene = new THREE.Scene(); + scene.fog = new THREE.Fog(0x000000, 3500, 15000); + scene.fog.color.setHSL(0.51, 0.4, 0.01); + + // world + + var s = 250; + + var cube = new THREE.BoxGeometry(s, s, s); + var material = new THREE.MeshPhongMaterial({ ambient: 0x333333, color: 0xffffff, specular: 0xffffff, shininess: 50 }); + + + for (var i = 0; i < 3000; i++) { + + var mesh = new THREE.Mesh(cube, material); + + mesh.position.x = 8000 * (2.0 * Math.random() - 1.0); + mesh.position.y = 8000 * (2.0 * Math.random() - 1.0); + mesh.position.z = 8000 * (2.0 * Math.random() - 1.0); + + mesh.rotation.x = Math.random() * Math.PI; + mesh.rotation.y = Math.random() * Math.PI; + mesh.rotation.z = Math.random() * Math.PI; + + mesh.matrixAutoUpdate = false; + mesh.updateMatrix(); + + scene.add(mesh); + + } + + + // lights + + var ambient = new THREE.AmbientLight(0xffffff); + ambient.color.setHSL(0.1, 0.3, 0.2); + scene.add(ambient); + + + var dirLight = new THREE.DirectionalLight(0xffffff, 0.125); + dirLight.position.set(0, -1, 0).normalize(); + scene.add(dirLight); + + dirLight.color.setHSL(0.1, 0.7, 0.5); + + // lens flares + + var textureFlare0 = THREE.ImageUtils.loadTexture("textures/lensflare/lensflare0.png"); + var textureFlare2 = THREE.ImageUtils.loadTexture("textures/lensflare/lensflare2.png"); + var textureFlare3 = THREE.ImageUtils.loadTexture("textures/lensflare/lensflare3.png"); + + addLight(0.55, 0.9, 0.5, 5000, 0, -1000); + addLight(0.08, 0.8, 0.5, 0, 0, -1000); + addLight(0.995, 0.5, 0.9, 5000, 5000, -1000); + + function addLight(h, s, l, x, y, z) { + + var light = new THREE.PointLight(0xffffff, 1.5, 4500); + light.color.setHSL(h, s, l); + light.position.set(x, y, z); + scene.add(light); + + var flareColor = new THREE.Color(0xffffff); + flareColor.setHSL(h, s, l + 0.5); + + var lensFlare = new THREE.LensFlare(textureFlare0, 700, 0.0, THREE.AdditiveBlending, flareColor); + + lensFlare.add(textureFlare2, 512, 0.0, THREE.AdditiveBlending); + lensFlare.add(textureFlare2, 512, 0.0, THREE.AdditiveBlending); + lensFlare.add(textureFlare2, 512, 0.0, THREE.AdditiveBlending); + + lensFlare.add(textureFlare3, 60, 0.6, THREE.AdditiveBlending); + lensFlare.add(textureFlare3, 70, 0.7, THREE.AdditiveBlending); + lensFlare.add(textureFlare3, 120, 0.9, THREE.AdditiveBlending); + lensFlare.add(textureFlare3, 70, 1.0, THREE.AdditiveBlending); + + lensFlare.customUpdateCallback = lensFlareUpdateCallback; + lensFlare.position = light.position; + + scene.add(lensFlare); + + } + + // renderer + + renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); + renderer.setSize(window.innerWidth, window.innerHeight); + renderer.setClearColor(scene.fog.color, 1); + + container.appendChild(renderer.domElement); + + // + + renderer.gammaInput = true; + renderer.gammaOutput = true; + + // stats + + stats = new Stats(); + container.appendChild(stats.domElement); + + // events + + window.addEventListener('resize', onWindowResize, false); + + } + + // + + function lensFlareUpdateCallback(object) { + + var f, fl = object.lensFlares.length; + var flare; + var vecX = -object.positionScreen.x * 2; + var vecY = -object.positionScreen.y * 2; + + + for (f = 0; f < fl; f++) { + + flare = object.lensFlares[f]; + + flare.x = object.positionScreen.x + vecX * flare.distance; + flare.y = object.positionScreen.y + vecY * flare.distance; + + flare.rotation = 0; + + } + + object.lensFlares[2].y += 0.025; + object.lensFlares[3].rotation = object.positionScreen.x * 0.5 + THREE.Math.degToRad(45); + + } + + // + + function onWindowResize(event) { + + renderer.setSize(window.innerWidth, window.innerHeight); + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + var delta = clock.getDelta(); + + controls.update(delta); + renderer.render(scene, camera); + + } +} diff --git a/threejs/tests/webgl/webgl_lights_heimsphere.ts b/threejs/tests/webgl/webgl_lights_heimsphere.ts new file mode 100644 index 0000000000..4339fe6336 --- /dev/null +++ b/threejs/tests/webgl/webgl_lights_heimsphere.ts @@ -0,0 +1,236 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_lights_hemisphere.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + var morph: any; + // ------- + if (!Detector.webgl) Detector.addGetWebGLMessage(); + + var camera, scene, renderer, dirLight, hemiLight; + var morphs = []; + var stats; + + var clock = new THREE.Clock(); + + init(); + animate(); + + function init() { + + var container = document.getElementById('container'); + + camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 1, 5000); + camera.position.set(0, 0, 250); + + scene = new THREE.Scene(); + + scene.fog = new THREE.Fog(0xffffff, 1, 5000); + scene.fog.color.setHSL(0.6, 0, 1); + + /* + controls = new THREE.TrackballControls( camera ); + + controls.rotateSpeed = 1.0; + controls.zoomSpeed = 1.2; + controls.panSpeed = 0.8; + + controls.noZoom = false; + controls.noPan = false; + + controls.staticMoving = true; + controls.dynamicDampingFactor = 0.15; + */ + + // LIGHTS + + hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.6); + hemiLight.color.setHSL(0.6, 1, 0.6); + hemiLight.groundColor.setHSL(0.095, 1, 0.75); + hemiLight.position.set(0, 500, 0); + scene.add(hemiLight); + + // + + dirLight = new THREE.DirectionalLight(0xffffff, 1); + dirLight.color.setHSL(0.1, 1, 0.95); + dirLight.position.set(-1, 1.75, 1); + dirLight.position.multiplyScalar(50); + scene.add(dirLight); + + dirLight.castShadow = true; + + dirLight.shadowMapWidth = 2048; + dirLight.shadowMapHeight = 2048; + + var d = 50; + + dirLight.shadowCameraLeft = -d; + dirLight.shadowCameraRight = d; + dirLight.shadowCameraTop = d; + dirLight.shadowCameraBottom = -d; + + dirLight.shadowCameraFar = 3500; + dirLight.shadowBias = -0.0001; + dirLight.shadowDarkness = 0.35; + //dirLight.shadowCameraVisible = true; + + // GROUND + + var groundGeo = new THREE.PlaneGeometry(10000, 10000); + var groundMat = new THREE.MeshPhongMaterial({ ambient: 0xffffff, color: 0xffffff, specular: 0x050505 }); + groundMat.color.setHSL(0.095, 1, 0.75); + + var ground = new THREE.Mesh(groundGeo, groundMat); + ground.rotation.x = -Math.PI / 2; + ground.position.y = -33; + scene.add(ground); + + ground.receiveShadow = true; + + // SKYDOME + + var vertexShader = document.getElementById('vertexShader').textContent; + var fragmentShader = document.getElementById('fragmentShader').textContent; + var uniforms = { + topColor: { type: "c", value: new THREE.Color(0x0077ff) }, + bottomColor: { type: "c", value: new THREE.Color(0xffffff) }, + offset: { type: "f", value: 33 }, + exponent: { type: "f", value: 0.6 } + } + uniforms.topColor.value.copy(hemiLight.color); + + scene.fog.color.copy(uniforms.bottomColor.value); + + var skyGeo = new THREE.SphereGeometry(4000, 32, 15); + var skyMat = new THREE.ShaderMaterial({ vertexShader: vertexShader, fragmentShader: fragmentShader, uniforms: uniforms, side: THREE.BackSide }); + + var sky = new THREE.Mesh(skyGeo, skyMat); + scene.add(sky); + + // MODEL + + var loader = new THREE.JSONLoader(); + + loader.load("models/animated/flamingo.js", function (geometry) { + + morphColorsToFaceColors(geometry); + geometry.computeMorphNormals(); + + var material = new THREE.MeshPhongMaterial({ color: 0xffffff, specular: 0xffffff, shininess: 20, morphTargets: true, morphNormals: true, vertexColors: THREE.FaceColors, shading: THREE.FlatShading }); + var meshAnim = new THREE.MorphAnimMesh(geometry, material); + + meshAnim.duration = 1000; + + var s = 0.35; + meshAnim.scale.set(s, s, s); + meshAnim.position.y = 15; + meshAnim.rotation.y = -1; + + meshAnim.castShadow = true; + meshAnim.receiveShadow = true; + + scene.add(meshAnim); + morphs.push(meshAnim); + + }); + + // RENDERER + + renderer = new THREE.WebGLRenderer({ antialias: true }); + renderer.setSize(window.innerWidth, window.innerHeight); + container.appendChild(renderer.domElement); + + renderer.setClearColor(scene.fog.color, 1); + + renderer.gammaInput = true; + renderer.gammaOutput = true; + + renderer.shadowMapEnabled = true; + renderer.shadowMapCullFace = THREE.CullFaceBack; + + // STATS + + stats = new Stats(); + container.appendChild(stats.domElement); + + // + + window.addEventListener('resize', onWindowResize, false); + document.addEventListener('keydown', onKeyDown, false); + + } + + function morphColorsToFaceColors(geometry) { + + if (geometry.morphColors && geometry.morphColors.length) { + + var colorMap = geometry.morphColors[0]; + + for (var i = 0; i < colorMap.colors.length; i++) { + + geometry.faces[i].color = colorMap.colors[i]; + + } + + } + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + function onKeyDown(event) { + + switch (event.keyCode) { + + case 72: /*h*/ + + hemiLight.visible = !hemiLight.visible; + break; + + case 68: /*d*/ + + dirLight.visible = !dirLight.visible; + break; + + } + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + var delta = clock.getDelta(); + + //controls.update(); + + for (var i = 0; i < morphs.length; i++) { + + morph = morphs[i]; + morph.updateAnimation(1000 * delta); + + } + + renderer.render(scene, camera); + + } +} diff --git a/threejs/tests/webgl/webgl_lines_colors.ts b/threejs/tests/webgl/webgl_lines_colors.ts new file mode 100644 index 0000000000..9a96214794 --- /dev/null +++ b/threejs/tests/webgl/webgl_lines_colors.ts @@ -0,0 +1,216 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_lines_colors.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + var hilbert3D: any; + var stats: any; + // ------- + + if (!Detector.webgl) Detector.addGetWebGLMessage(); + + var effectFXAA; + + var mouseX = 0, mouseY = 0, + + windowHalfX = window.innerWidth / 2, + windowHalfY = window.innerHeight / 2, + + camera, scene, renderer, material, composer; + + init(); + animate(); + + function init() { + + var i, container; + + container = document.createElement('div'); + document.body.appendChild(container); + + camera = new THREE.PerspectiveCamera(33, window.innerWidth / window.innerHeight, 1, 10000); + camera.position.z = 700; + + scene = new THREE.Scene(); + + renderer = new THREE.WebGLRenderer({ antialias: false }); + renderer.setSize(window.innerWidth, window.innerHeight); + renderer.autoClear = false; + + container.appendChild(renderer.domElement); + + var geometry = new THREE.Geometry(), + geometry2 = new THREE.Geometry(), + geometry3 = new THREE.Geometry(), + points = hilbert3D(new THREE.Vector3(0, 0, 0), 200.0, 2, 0, 1, 2, 3, 4, 5, 6, 7), + colors = [], colors2 = [], colors3 = []; + + for (i = 0; i < points.length; i++) { + + geometry.vertices.push(points[i]); + + colors[i] = new THREE.Color(0xffffff); + colors[i].setHSL(0.6, 1.0, Math.max(0, (200 - points[i].x) / 400) * 0.5 + 0.5); + + colors2[i] = new THREE.Color(0xffffff); + colors2[i].setHSL(0.3, 1.0, Math.max(0, (200 + points[i].x) / 400) * 0.5); + + colors3[i] = new THREE.Color(0xffffff); + colors3[i].setHSL(i / points.length, 1.0, 0.5); + + } + + geometry2.vertices = geometry3.vertices = geometry.vertices; + + geometry.colors = colors; + geometry2.colors = colors2; + geometry3.colors = colors3; + + // lines + + material = new THREE.LineBasicMaterial({ color: 0xffffff, opacity: 1, linewidth: 3, vertexColors: THREE.VertexColors }); + + var line, p, scale = 0.3, d = 225; + var parameters = [ + [material, scale * 1.5, [-d, 0, 0], geometry], + [material, scale * 1.5, [0, 0, 0], geometry2], + [material, scale * 1.5, [d, 0, 0], geometry3] + ]; + + for (i = 0; i < parameters.length; ++i) { + + p = parameters[i]; + line = new THREE.Line(p[3], p[0]); + line.scale.x = line.scale.y = line.scale.z = p[1]; + line.position.x = p[2][0]; + line.position.y = p[2][1]; + line.position.z = p[2][2]; + scene.add(line); + + } + + // + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + //container.appendChild( stats.domElement ); + + // + + document.addEventListener('mousemove', onDocumentMouseMove, false); + document.addEventListener('touchstart', onDocumentTouchStart, false); + document.addEventListener('touchmove', onDocumentTouchMove, false); + + // + + var renderModel = new THREE.RenderPass(scene, camera); + var effectBloom = new THREE.BloomPass(1.3); + var effectCopy = new THREE.ShaderPass(THREE.CopyShader); + + effectFXAA = new THREE.ShaderPass(THREE.FXAAShader); + + var width = window.innerWidth || 2; + var height = window.innerHeight || 2; + + effectFXAA.uniforms['resolution'].value.set(1 / width, 1 / height); + + effectCopy.renderToScreen = true; + + composer = new THREE.EffectComposer(renderer); + + composer.addPass(renderModel); + composer.addPass(effectFXAA); + composer.addPass(effectBloom); + composer.addPass(effectCopy); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + windowHalfX = window.innerWidth / 2; + windowHalfY = window.innerHeight / 2; + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + effectFXAA.uniforms['resolution'].value.set(1 / window.innerWidth, 1 / window.innerHeight); + + composer.reset(); + + } + + // + + function onDocumentMouseMove(event) { + + mouseX = event.clientX - windowHalfX; + mouseY = event.clientY - windowHalfY; + + } + + function onDocumentTouchStart(event) { + + if (event.touches.length > 1) { + + event.preventDefault(); + + mouseX = event.touches[0].pageX - windowHalfX; + mouseY = event.touches[0].pageY - windowHalfY; + + } + + } + + function onDocumentTouchMove(event) { + + if (event.touches.length == 1) { + + event.preventDefault(); + + mouseX = event.touches[0].pageX - windowHalfX; + mouseY = event.touches[0].pageY - windowHalfY; + } + + } + + // + + function animate() { + + requestAnimationFrame(animate); + render(); + + stats.update(); + + } + + function render() { + + camera.position.x += (mouseX - camera.position.x) * .05; + camera.position.y += (- mouseY + 200 - camera.position.y) * .05; + + camera.lookAt(scene.position); + + var time = Date.now() * 0.0005; + + for (var i = 0; i < scene.children.length; i++) { + + var object = scene.children[i]; + if (object instanceof THREE.Line) object.rotation.y = time * (i % 2 ? 1 : -1); + + } + + renderer.clear(); + composer.render(); + + } +} diff --git a/threejs/tests/webgl/webgl_loader_awd.ts b/threejs/tests/webgl/webgl_loader_awd.ts new file mode 100644 index 0000000000..71c9c99f68 --- /dev/null +++ b/threejs/tests/webgl/webgl_loader_awd.ts @@ -0,0 +1,116 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_loader_awd.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + + // ------- + + if (!Detector.webgl) Detector.addGetWebGLMessage(); + + var container, stats; + + var camera, scene, renderer, objects, controls; + var particleLight, pointLight; + var trunk; + + var loader = new THREE.AWDLoader(); + + loader.materialFactory = createMaterial; + loader.load('./models/awd/simple/simple.awd', function (_trunk) { + + trunk = _trunk; + + init(); + render(); + + }); + + + function createMaterial(name) { + // console.log( name ); + // var mat = new THREE.MeshPhongMaterial({ + // color: 0xaaaaaa, + // shininess: 20 + + // }); + // return mat; + return null; + } + + + function init() { + + container = document.createElement('div'); + document.body.appendChild(container); + + camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000); + camera.position.set(70, 50, -100); + + controls = new THREE.OrbitControls(camera); + + scene = new THREE.Scene(); + + + // Add the AWD SCENE + + scene.add(trunk); + + + // Lights + + scene.add(new THREE.AmbientLight(0x606060)); + + var directionalLight = new THREE.DirectionalLight(/*Math.random() * 0xffffff*/0xeeeeee); + directionalLight.position.set(.2, -1, .2); + directionalLight.position.normalize(); + scene.add(directionalLight); + + pointLight = new THREE.PointLight(0xffffff, .6); + scene.add(pointLight); + + renderer = new THREE.WebGLRenderer(); + renderer.setSize(window.innerWidth, window.innerHeight); + + container.appendChild(renderer.domElement); + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + container.appendChild(stats.domElement); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + + + function render() { + + requestAnimationFrame(render); + + var timer = Date.now() * 0.0005; + + pointLight.position.x = Math.sin(timer * 4) * 3000; + pointLight.position.y = 600 + pointLight.position.z = Math.cos(timer * 4) * 3000; + + renderer.render(scene, camera); + + stats.update(); + + } +} diff --git a/threejs/tests/webgl/webgl_materials.ts b/threejs/tests/webgl/webgl_materials.ts new file mode 100644 index 0000000000..1f1dab70c7 --- /dev/null +++ b/threejs/tests/webgl/webgl_materials.ts @@ -0,0 +1,238 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_materials.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + var geometry: THREE.Geometry; + // ------- + + if (!Detector.webgl) Detector.addGetWebGLMessage(); + var container, stats; + + var camera, scene, renderer, objects; + var particleLight, pointLight; + + var materials = []; + + init(); + animate(); + + function init() { + + container = document.createElement('div'); + document.body.appendChild(container); + + camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000); + camera.position.set(0, 200, 800); + + scene = new THREE.Scene(); + + // Grid + + var line_material = new THREE.LineBasicMaterial({ color: 0x303030 }), + geometry = new THREE.Geometry(), + floor = -75, step = 25; + + for (var i = 0; i <= 40; i++) { + + geometry.vertices.push(new THREE.Vector3(- 500, floor, i * step - 500)); + geometry.vertices.push(new THREE.Vector3(500, floor, i * step - 500)); + + geometry.vertices.push(new THREE.Vector3(i * step - 500, floor, -500)); + geometry.vertices.push(new THREE.Vector3(i * step - 500, floor, 500)); + + } + + var line = new THREE.Line(geometry, line_material, THREE.LinePieces); + scene.add(line); + + // Materials + + var texture = new THREE.Texture(generateTexture()); + texture.needsUpdate = true; + + materials.push(new THREE.MeshLambertMaterial({ map: texture, transparent: true })); + materials.push(new THREE.MeshLambertMaterial({ color: 0xdddddd, shading: THREE.FlatShading })); + materials.push(new THREE.MeshPhongMaterial({ ambient: 0x030303, color: 0xdddddd, specular: 0x009900, shininess: 30, shading: THREE.FlatShading })); + materials.push(new THREE.MeshNormalMaterial()); + materials.push(new THREE.MeshBasicMaterial({ color: 0xffaa00, transparent: true, blending: THREE.AdditiveBlending })); + //materials.push( new THREE.MeshBasicMaterial( { color: 0xff0000, blending: THREE.SubtractiveBlending } ) ); + + materials.push(new THREE.MeshLambertMaterial({ color: 0xdddddd, shading: THREE.SmoothShading })); + materials.push(new THREE.MeshPhongMaterial({ ambient: 0x030303, color: 0xdddddd, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, map: texture, transparent: true })); + materials.push(new THREE.MeshNormalMaterial({ shading: THREE.SmoothShading })); + materials.push(new THREE.MeshBasicMaterial({ color: 0xffaa00, wireframe: true })); + + materials.push(new THREE.MeshDepthMaterial()); + + materials.push(new THREE.MeshLambertMaterial({ color: 0x666666, emissive: 0xff0000, ambient: 0x000000, shading: THREE.SmoothShading })); + materials.push(new THREE.MeshPhongMaterial({ color: 0x000000, specular: 0x666666, emissive: 0xff0000, ambient: 0x000000, shininess: 10, shading: THREE.SmoothShading, opacity: 0.9, transparent: true })); + + materials.push(new THREE.MeshBasicMaterial({ map: texture, transparent: true })); + + // Spheres geometry + + var geometry_smooth = new THREE.SphereGeometry(70, 32, 16); + var geometry_flat = new THREE.SphereGeometry(70, 32, 16); + var geometry_pieces = new THREE.SphereGeometry(70, 32, 16); // Extra geometry to be broken down for MeshFaceMaterial + + for (var i = 0, l = geometry_pieces.faces.length; i < l; i++) { + + var face = geometry_pieces.faces[i]; + face.materialIndex = Math.floor(Math.random() * materials.length); + + } + + materials.push(new THREE.MeshFaceMaterial(materials)); + + objects = []; + + var sphere, material; + + for (var i = 0, l = materials.length; i < l; i++) { + + material = materials[i]; + + geometry = material instanceof THREE.MeshFaceMaterial ? geometry_pieces : + (material.shading == THREE.FlatShading ? geometry_flat : geometry_smooth); + + sphere = new THREE.Mesh(geometry, material); + + sphere.position.x = (i % 4) * 200 - 400; + sphere.position.z = Math.floor(i / 4) * 200 - 200; + + sphere.rotation.x = Math.random() * 200 - 100; + sphere.rotation.y = Math.random() * 200 - 100; + sphere.rotation.z = Math.random() * 200 - 100; + + objects.push(sphere); + + scene.add(sphere); + + } + + particleLight = new THREE.Mesh(new THREE.SphereGeometry(4, 8, 8), new THREE.MeshBasicMaterial({ color: 0xffffff })); + scene.add(particleLight); + + // Lights + + scene.add(new THREE.AmbientLight(0x111111)); + + var directionalLight = new THREE.DirectionalLight( /*Math.random() * */ 0xffffff, 0.125); + + directionalLight.position.x = Math.random() - 0.5; + directionalLight.position.y = Math.random() - 0.5; + directionalLight.position.z = Math.random() - 0.5; + + directionalLight.position.normalize(); + + scene.add(directionalLight); + + pointLight = new THREE.PointLight(0xffffff, 1); + scene.add(pointLight); + + // + + renderer = new THREE.WebGLRenderer({ antialias: true }); + renderer.setSize(window.innerWidth, window.innerHeight); + + container.appendChild(renderer.domElement); + + // + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + + container.appendChild(stats.domElement); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + function generateTexture() { + + var canvas = document.createElement('canvas'); + canvas.width = 256; + canvas.height = 256; + + var context = canvas.getContext('2d'); + var image = context.getImageData(0, 0, 256, 256); + + var x = 0, y = 0; + + for (var i = 0, j = 0, l = image.data.length; i < l; i += 4, j++) { + + x = j % 256; + y = x == 0 ? y + 1 : y; + + image.data[i] = 255; + image.data[i + 1] = 255; + image.data[i + 2] = 255; + image.data[i + 3] = Math.floor(x ^ y); + + } + + context.putImageData(image, 0, 0); + + return canvas; + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + var timer = 0.0001 * Date.now(); + + camera.position.x = Math.cos(timer) * 1000; + camera.position.z = Math.sin(timer) * 1000; + + camera.lookAt(scene.position); + + for (var i = 0, l = objects.length; i < l; i++) { + + var object = objects[i]; + + object.rotation.x += 0.01; + object.rotation.y += 0.005; + + } + + materials[materials.length - 3].emissive.setHSL(0.54, 1, 0.35 * (0.5 + 0.5 * Math.sin(35 * timer))); + materials[materials.length - 4].emissive.setHSL(0.04, 1, 0.35 * (0.5 + 0.5 * Math.cos(35 * timer))); + + particleLight.position.x = Math.sin(timer * 7) * 300; + particleLight.position.y = Math.cos(timer * 5) * 400; + particleLight.position.z = Math.cos(timer * 3) * 300; + + pointLight.position.x = particleLight.position.x; + pointLight.position.y = particleLight.position.y; + pointLight.position.z = particleLight.position.z; + + renderer.render(scene, camera); + + } +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_morphtargets.ts b/threejs/tests/webgl/webgl_morphtargets.ts new file mode 100644 index 0000000000..db4fe0f2ba --- /dev/null +++ b/threejs/tests/webgl/webgl_morphtargets.ts @@ -0,0 +1,131 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_morphtargets.html + +() => { + if (!Detector.webgl) Detector.addGetWebGLMessage(); + + var container, stats; + + var camera, scene, renderer; + + var geometry, objects; + + var mouseX = 0, mouseY = 0; + + var mesh; + var windowHalfX = window.innerWidth / 2; + var windowHalfY = window.innerHeight / 2; + + document.addEventListener('mousemove', onDocumentMouseMove, false); + + init(); + animate(); + + function init() { + var light: THREE.Light; + + container = document.createElement('div'); + document.body.appendChild(container); + + camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 15000); + camera.position.z = 500; + + scene = new THREE.Scene(); + scene.fog = new THREE.Fog(0x000000, 1, 15000); + + light = new THREE.PointLight(0xff2200); + light.position.set(100, 100, 100); + scene.add(light); + + light = new THREE.AmbientLight(0x111111); + scene.add(light); + + + var geometry = new THREE.BoxGeometry(100, 100, 100); + var material = new THREE.MeshLambertMaterial({ color: 0xffffff, morphTargets: true }); + + // construct 8 blend shapes + + for (var i = 0; i < geometry.vertices.length; i++) { + + var vertices = []; + + for (var v = 0; v < geometry.vertices.length; v++) { + + vertices.push(geometry.vertices[v].clone()); + + if (v === i) { + + vertices[vertices.length - 1].x *= 2; + vertices[vertices.length - 1].y *= 2; + vertices[vertices.length - 1].z *= 2; + + } + + } + + geometry.morphTargets.push({ name: "target" + i, vertices: vertices }); + + } + + mesh = new THREE.Mesh(geometry, material); + + scene.add(mesh); + + // + + renderer = new THREE.WebGLRenderer(); + renderer.setClearColor(0x222222, 1); + renderer.setSize(window.innerWidth, window.innerHeight); + renderer.sortObjects = false; + container.appendChild(renderer.domElement); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + windowHalfX = window.innerWidth / 2; + windowHalfY = window.innerHeight / 2; + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + function onDocumentMouseMove(event) { + + mouseX = (event.clientX - windowHalfX); + mouseY = (event.clientY - windowHalfY) * 2; + + } + + function animate() { + + requestAnimationFrame(animate); + render(); + + } + + function render() { + + mesh.rotation.y += 0.01; + + //mesh.morphTargetInfluences[ 0 ] = Math.sin( mesh.rotation.y ) * 0.5 + 0.5; + + //camera.position.x += ( mouseX - camera.position.x ) * .005; + camera.position.y += (- mouseY - camera.position.y) * .01; + + camera.lookAt(scene.position); + + renderer.render(scene, camera); + + } +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_particles_billboards.ts b/threejs/tests/webgl/webgl_particles_billboards.ts new file mode 100644 index 0000000000..8e786303d7 --- /dev/null +++ b/threejs/tests/webgl/webgl_particles_billboards.ts @@ -0,0 +1,147 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_particles_billboards.html + +() => { + if (!Detector.webgl) Detector.addGetWebGLMessage(); + + var container, stats; + var camera, scene, renderer, particles, geometry, material, i, h, color, sprite, size; + var mouseX = 0, mouseY = 0; + + var windowHalfX = window.innerWidth / 2; + var windowHalfY = window.innerHeight / 2; + + init(); + animate(); + + function init() { + + container = document.createElement('div'); + document.body.appendChild(container); + + camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 2, 2000); + camera.position.z = 1000; + + scene = new THREE.Scene(); + scene.fog = new THREE.FogExp2(0x000000, 0.001); + + geometry = new THREE.Geometry(); + + sprite = THREE.ImageUtils.loadTexture("textures/sprites/disc.png"); + + for (i = 0; i < 10000; i++) { + + var vertex = new THREE.Vector3(); + vertex.x = 2000 * Math.random() - 1000; + vertex.y = 2000 * Math.random() - 1000; + vertex.z = 2000 * Math.random() - 1000; + + geometry.vertices.push(vertex); + + } + + material = new THREE.ParticleSystemMaterial({ size: 35, sizeAttenuation: false, map: sprite, transparent: true }); + material.color.setHSL(1.0, 0.3, 0.7); + + particles = new THREE.ParticleSystem(geometry, material); + particles.sortParticles = true; + scene.add(particles); + + // + + renderer = new THREE.WebGLRenderer({ clearAlpha: 1 }); + renderer.setSize(window.innerWidth, window.innerHeight); + container.appendChild(renderer.domElement); + + // + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + container.appendChild(stats.domElement); + + // + + document.addEventListener('mousemove', onDocumentMouseMove, false); + document.addEventListener('touchstart', onDocumentTouchStart, false); + document.addEventListener('touchmove', onDocumentTouchMove, false); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + windowHalfX = window.innerWidth / 2; + windowHalfY = window.innerHeight / 2; + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + function onDocumentMouseMove(event) { + + mouseX = event.clientX - windowHalfX; + mouseY = event.clientY - windowHalfY; + + } + + function onDocumentTouchStart(event) { + + if (event.touches.length == 1) { + + event.preventDefault(); + + mouseX = event.touches[0].pageX - windowHalfX; + mouseY = event.touches[0].pageY - windowHalfY; + + } + } + + function onDocumentTouchMove(event) { + + if (event.touches.length == 1) { + + event.preventDefault(); + + mouseX = event.touches[0].pageX - windowHalfX; + mouseY = event.touches[0].pageY - windowHalfY; + + } + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + var time = Date.now() * 0.00005; + + camera.position.x += (mouseX - camera.position.x) * 0.05; + camera.position.y += (- mouseY - camera.position.y) * 0.05; + + camera.lookAt(scene.position); + + h = (360 * (1.0 + time) % 360) / 360; + material.color.setHSL(h, 0.5, 0.5); + + renderer.render(scene, camera); + + } +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_postprocessing.ts b/threejs/tests/webgl/webgl_postprocessing.ts new file mode 100644 index 0000000000..e3aaff31ad --- /dev/null +++ b/threejs/tests/webgl/webgl_postprocessing.ts @@ -0,0 +1,91 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_postprocessing.html + +() => { + var camera, scene, renderer, composer; + var object, light; + + init(); + animate(); + + function init() { + + renderer = new THREE.WebGLRenderer(); + renderer.setSize(window.innerWidth, window.innerHeight); + document.body.appendChild(renderer.domElement); + + // + + camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000); + camera.position.z = 400; + + scene = new THREE.Scene(); + scene.fog = new THREE.Fog(0x000000, 1, 1000); + + object = new THREE.Object3D(); + scene.add(object); + + var geometry = new THREE.SphereGeometry(1, 4, 4); + var material = new THREE.MeshPhongMaterial({ color: 0xffffff, shading: THREE.FlatShading }); + + for (var i = 0; i < 100; i++) { + + var mesh = new THREE.Mesh(geometry, material); + mesh.position.set(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5).normalize(); + mesh.position.multiplyScalar(Math.random() * 400); + mesh.rotation.set(Math.random() * 2, Math.random() * 2, Math.random() * 2); + mesh.scale.x = mesh.scale.y = mesh.scale.z = Math.random() * 50; + object.add(mesh); + + } + + scene.add(new THREE.AmbientLight(0x222222)); + + light = new THREE.DirectionalLight(0xffffff); + light.position.set(1, 1, 1); + scene.add(light); + + // postprocessing + + composer = new THREE.EffectComposer(renderer); + composer.addPass(new THREE.RenderPass(scene, camera)); + + var effect = new THREE.ShaderPass(THREE.DotScreenShader); + effect.uniforms['scale'].value = 4; + composer.addPass(effect); + + var effect = new THREE.ShaderPass(THREE.RGBShiftShader); + effect.uniforms['amount'].value = 0.0015; + effect.renderToScreen = true; + composer.addPass(effect); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + function animate() { + + requestAnimationFrame(animate); + + var time = Date.now(); + + object.rotation.x += 0.005; + object.rotation.y += 0.01; + + composer.render(); + + } +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_shader.ts b/threejs/tests/webgl/webgl_shader.ts new file mode 100644 index 0000000000..a55d35b6d8 --- /dev/null +++ b/threejs/tests/webgl/webgl_shader.ts @@ -0,0 +1,86 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_shader.html + +() => { + if (!Detector.webgl) Detector.addGetWebGLMessage(); + + var container, stats; + + var camera, scene, renderer; + + var uniforms; + + init(); + animate(); + + function init() { + + container = document.getElementById('container'); + + camera = new THREE.Camera(); + camera.position.z = 1; + + scene = new THREE.Scene(); + + var geometry = new THREE.PlaneGeometry(2, 2); + + uniforms = { + time: { type: "f", value: 1.0 }, + resolution: { type: "v2", value: new THREE.Vector2() } + }; + + var material = new THREE.ShaderMaterial({ + + uniforms: uniforms, + vertexShader: document.getElementById('vertexShader').textContent, + fragmentShader: document.getElementById('fragmentShader').textContent + + }); + + var mesh = new THREE.Mesh(geometry, material); + scene.add(mesh); + + renderer = new THREE.WebGLRenderer(); + container.appendChild(renderer.domElement); + + stats = new Stats(); + stats.domElement.style.position = 'absolute'; + stats.domElement.style.top = '0px'; + container.appendChild(stats.domElement); + + onWindowResize(); + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + uniforms.resolution.value.x = window.innerWidth; + uniforms.resolution.value.y = window.innerHeight; + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + uniforms.time.value += 0.05; + + renderer.render(scene, camera); + + } +} \ No newline at end of file diff --git a/threejs/tests/webgl/webgl_sprites.ts b/threejs/tests/webgl/webgl_sprites.ts new file mode 100644 index 0000000000..360a4f53d3 --- /dev/null +++ b/threejs/tests/webgl/webgl_sprites.ts @@ -0,0 +1,215 @@ +/// +/// + +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_sprites.html + +() => { + // ------- variable definitions that does not exist in the original code. These are for typescript. + var material: THREE.SpriteMaterial; + // ------- + + var camera, scene, renderer; + var cameraOrtho, sceneOrtho; + + var spriteTL, spriteTR, spriteBL, spriteBR, spriteC; + + var mapC; + + var group; + + init(); + animate(); + + function init() { + + var width = window.innerWidth; + var height = window.innerHeight; + + camera = new THREE.PerspectiveCamera(60, width / height, 1, 2100); + camera.position.z = 1500; + + cameraOrtho = new THREE.OrthographicCamera(- width / 2, width / 2, height / 2, - height / 2, 1, 10); + cameraOrtho.position.z = 10; + + scene = new THREE.Scene(); + scene.fog = new THREE.Fog(0x000000, 1500, 2100); + + sceneOrtho = new THREE.Scene(); + + // create sprites + + var amount = 200; + var radius = 500; + + var mapA = THREE.ImageUtils.loadTexture("textures/sprite0.png", undefined, createHUDSprites); + var mapB = THREE.ImageUtils.loadTexture("textures/sprite1.png"); + mapC = THREE.ImageUtils.loadTexture("textures/sprite2.png"); + + group = new THREE.Object3D(); + + var materialC = new THREE.SpriteMaterial({ map: mapC, color: 0xffffff, fog: true }); + var materialB = new THREE.SpriteMaterial({ map: mapB, color: 0xffffff, fog: true }); + + for (var a = 0; a < amount; a++) { + + var x = Math.random() - 0.5; + var y = Math.random() - 0.5; + var z = Math.random() - 0.5; + + if (z < 0) { + + material = materialB.clone(); + + } else { + + material = materialC.clone(); + material.color.setHSL(0.5 * Math.random(), 0.75, 0.5); + material.map.offset.set(-0.5, -0.5); + material.map.repeat.set(2, 2); + + } + + var sprite = new THREE.Sprite(material); + + sprite.position.set(x, y, z); + sprite.position.normalize(); + sprite.position.multiplyScalar(radius); + + group.add(sprite); + + } + + scene.add(group); + + // renderer + + renderer = new THREE.WebGLRenderer(); + renderer.setSize(window.innerWidth, window.innerHeight); + renderer.autoClear = false; // To allow render overlay on top of sprited sphere + + document.body.appendChild(renderer.domElement); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function createHUDSprites(texture) { + + var material = new THREE.SpriteMaterial({ map: texture }); + + var width = material.map.image.width; + var height = material.map.image.height; + + spriteTL = new THREE.Sprite(material); + spriteTL.scale.set(width, height, 1); + sceneOrtho.add(spriteTL); + + spriteTR = new THREE.Sprite(material); + spriteTR.scale.set(width, height, 1); + sceneOrtho.add(spriteTR); + + spriteBL = new THREE.Sprite(material); + spriteBL.scale.set(width, height, 1); + sceneOrtho.add(spriteBL); + + spriteBR = new THREE.Sprite(material); + spriteBR.scale.set(width, height, 1); + sceneOrtho.add(spriteBR); + + spriteC = new THREE.Sprite(material); + spriteC.scale.set(width, height, 1); + sceneOrtho.add(spriteC); + + updateHUDSprites(); + + }; + + function updateHUDSprites() { + + var width = window.innerWidth / 2; + var height = window.innerHeight / 2; + + var material = spriteTL.material; + + var imageWidth = material.map.image.width / 2; + var imageHeight = material.map.image.height / 2; + + spriteTL.position.set(- width + imageWidth, height - imageHeight, 1); // top left + spriteTR.position.set(width - imageWidth, height - imageHeight, 1); // top right + spriteBL.position.set(- width + imageWidth, - height + imageHeight, 1); // bottom left + spriteBR.position.set(width - imageWidth, - height + imageHeight, 1); // bottom right + spriteC.position.set(0, 0, 1); // center + + }; + + function onWindowResize() { + + var width = window.innerWidth; + var height = window.innerHeight; + + camera.aspect = width / height; + camera.updateProjectionMatrix(); + + cameraOrtho.left = - width / 2; + cameraOrtho.right = width / 2; + cameraOrtho.top = height / 2; + cameraOrtho.bottom = - height / 2; + cameraOrtho.updateProjectionMatrix(); + + updateHUDSprites(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + function animate() { + + requestAnimationFrame(animate); + render(); + + } + + function render() { + + var time = Date.now() / 1000; + + for (var i = 0, l = group.children.length; i < l; i++) { + + var sprite = group.children[i]; + var material = sprite.material; + var scale = Math.sin(time + sprite.position.x * 0.01) * 0.3 + 1.0; + + var imageWidth = 1; + var imageHeight = 1; + + if (material.map && material.map.image && material.map.image.width) { + + imageWidth = material.map.image.width; + imageHeight = material.map.image.height; + + } + + sprite.material.rotation += 0.1 * (i / l); + sprite.scale.set(scale * imageWidth, scale * imageHeight, 1.0); + + if (material.map !== mapC) { + + material.opacity = Math.sin(time + sprite.position.x * 0.01) * 0.4 + 0.6; + + } + + } + + group.rotation.x = time * 0.5; + group.rotation.y = time * 0.75; + group.rotation.z = time * 1.0; + + renderer.clear(); + renderer.render(scene, camera); + renderer.clearDepth(); + renderer.render(sceneOrtho, cameraOrtho); + + } +} \ No newline at end of file diff --git a/threejs/three-tests.ts b/threejs/three-tests.ts index 8207933bcd..4ff78b618f 100644 --- a/threejs/three-tests.ts +++ b/threejs/three-tests.ts @@ -1,32 +1,3 @@ -/// -/// - -///////////////////////////////////////////////////////////////////// -// Lib.d.ts browser specific fixes necessary for these tests to work : -///////////////////////////////////////////////////////////////////// -interface CSSStyleDeclaration { - WebkitFilter: string; -} -interface Document { - pointerLockElement: any; - mozPointerLockElement: any; - webkitPointerLockElement: any; - fullscreenElement: any; - mozFullscreenElement: any; - mozFullScreenElement: any; - webkitFullscreenElement: any; -} -interface HTMLElement { - requestPointerLock: any; - mozRequestPointerLock: any; - webkitRequestPointerLock: any; - requestFullScreen: any; - requestFullscreen: any; - mozRequestFullScreen: any; - mozRequestFullscreen: any; - webkitRequestFullscreen: any; -} - /* The MIT License @@ -51,23605 +22,35 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -// https://github.com/mrdoob/three.js/tree/master/test/unit/math - -()=>{ - var x = 2; - var y = 3; - var z = 4; - var w = 5; - - var negInf2 = new THREE.Vector2( -Infinity, -Infinity ); - var posInf2 = new THREE.Vector2( Infinity, Infinity ); - - var zero2 = new THREE.Vector2(); - var one2 = new THREE.Vector2( 1, 1 ); - var two2 = new THREE.Vector2( 2, 2 ); - - var negInf3 = new THREE.Vector3( -Infinity, -Infinity, -Infinity ); - var posInf3 = new THREE.Vector3( Infinity, Infinity, Infinity ); - - var zero3 = new THREE.Vector3(); - var one3 = new THREE.Vector3( 1, 1, 1 ); - var two3 = new THREE.Vector3( 2, 2, 2 ); - - (QUnit.module)( "Box2" ); - - test( "constructor", function() { - var a = new THREE.Box2(); - ok( a.min.equals( posInf2 ), "Passed!" ); - ok( a.max.equals( negInf2 ), "Passed!" ); - - a = new THREE.Box2( zero2.clone(), zero2.clone() ); - ok( a.min.equals( zero2 ), "Passed!" ); - ok( a.max.equals( zero2 ), "Passed!" ); - - a = new THREE.Box2( zero2.clone(), one2.clone() ); - ok( a.min.equals( zero2 ), "Passed!" ); - ok( a.max.equals( one2 ), "Passed!" ); - }); - - test( "copy", function() { - var a = new THREE.Box2( zero2.clone(), one2.clone() ); - var b = new THREE.Box2().copy( a ); - ok( b.min.equals( zero2 ), "Passed!" ); - ok( b.max.equals( one2 ), "Passed!" ); - - // ensure that it is a true copy - a.min = zero2; - a.max = one2; - ok( b.min.equals( zero2 ), "Passed!" ); - ok( b.max.equals( one2 ), "Passed!" ); - }); - - test( "set", function() { - var a = new THREE.Box2(); - - a.set( zero2, one2 ); - ok( a.min.equals( zero2 ), "Passed!" ); - ok( a.max.equals( one2 ), "Passed!" ); - }); - - test( "empty/makeEmpty", function() { - var a = new THREE.Box2(); - - ok( a.empty(), "Passed!" ); - - var a = new THREE.Box2( zero2.clone(), one2.clone() ); - ok( ! a.empty(), "Passed!" ); - - a.makeEmpty(); - ok( a.empty(), "Passed!" ); - }); - - test( "center", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - - ok( a.center().equals( zero2 ), "Passed!" ); - - a = new THREE.Box2( zero2, one2 ); - var midpoint = one2.clone().multiplyScalar( 0.5 ); - ok( a.center().equals( midpoint ), "Passed!" ); - }); - - test( "size", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - - ok( a.size().equals( zero2 ), "Passed!" ); - - a = new THREE.Box2( zero2.clone(), one2.clone() ); - ok( a.size().equals( one2 ), "Passed!" ); - }); - - test( "expandByPoint", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - - a.expandByPoint( zero2 ); - ok( a.size().equals( zero2 ), "Passed!" ); - - a.expandByPoint( one2 ); - ok( a.size().equals( one2 ), "Passed!" ); - - a.expandByPoint( one2.clone().negate() ); - ok( a.size().equals( one2.clone().multiplyScalar( 2 ) ), "Passed!" ); - ok( a.center().equals( zero2 ), "Passed!" ); - }); - - test( "expandByVector", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - - a.expandByVector( zero2 ); - ok( a.size().equals( zero2 ), "Passed!" ); - - a.expandByVector( one2 ); - ok( a.size().equals( one2.clone().multiplyScalar( 2 ) ), "Passed!" ); - ok( a.center().equals( zero2 ), "Passed!" ); - }); - - test( "expandByScalar", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - - a.expandByScalar( 0 ); - ok( a.size().equals( zero2 ), "Passed!" ); - - a.expandByScalar( 1 ); - ok( a.size().equals( one2.clone().multiplyScalar( 2 ) ), "Passed!" ); - ok( a.center().equals( zero2 ), "Passed!" ); - }); - - test( "containsPoint", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - - ok( a.containsPoint( zero2 ), "Passed!" ); - ok( ! a.containsPoint( one2 ), "Passed!" ); - - a.expandByScalar( 1 ); - ok( a.containsPoint( zero2 ), "Passed!" ); - ok( a.containsPoint( one2 ), "Passed!" ); - ok( a.containsPoint( one2.clone().negate() ), "Passed!" ); - }); - - test( "containsBox", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - var b = new THREE.Box2( zero2.clone(), one2.clone() ); - var c = new THREE.Box2( one2.clone().negate(), one2.clone() ); - - ok( a.containsBox( a ), "Passed!" ); - ok( ! a.containsBox( b ), "Passed!" ); - ok( ! a.containsBox( c ), "Passed!" ); - - ok( b.containsBox( a ), "Passed!" ); - ok( c.containsBox( a ), "Passed!" ); - ok( ! b.containsBox( c ), "Passed!" ); - }); - - test( "getParameter", function() { - var a = new THREE.Box2( zero2.clone(), one2.clone() ); - var b = new THREE.Box2( one2.clone().negate(), one2.clone() ); - - ok( a.getParameter( new THREE.Vector2( 0, 0 ) ).equals( new THREE.Vector2( 0, 0 ) ), "Passed!" ); - ok( a.getParameter( new THREE.Vector2( 1, 1 ) ).equals( new THREE.Vector2( 1, 1 ) ), "Passed!" ); - - ok( b.getParameter( new THREE.Vector2( -1, -1 ) ).equals( new THREE.Vector2( 0, 0 ) ), "Passed!" ); - ok( b.getParameter( new THREE.Vector2( 0, 0 ) ).equals( new THREE.Vector2( 0.5, 0.5 ) ), "Passed!" ); - ok( b.getParameter( new THREE.Vector2( 1, 1 ) ).equals( new THREE.Vector2( 1, 1 ) ), "Passed!" ); - }); - - test( "clampPoint", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - var b = new THREE.Box2( one2.clone().negate(), one2.clone() ); - - ok( a.clampPoint( new THREE.Vector2( 0, 0 ) ).equals( new THREE.Vector2( 0, 0 ) ), "Passed!" ); - ok( a.clampPoint( new THREE.Vector2( 1, 1 ) ).equals( new THREE.Vector2( 0, 0 ) ), "Passed!" ); - ok( a.clampPoint( new THREE.Vector2( -1, -1 ) ).equals( new THREE.Vector2( 0, 0 ) ), "Passed!" ); - - ok( b.clampPoint( new THREE.Vector2( 2, 2 ) ).equals( new THREE.Vector2( 1, 1 ) ), "Passed!" ); - ok( b.clampPoint( new THREE.Vector2( 1, 1 ) ).equals( new THREE.Vector2( 1, 1 ) ), "Passed!" ); - ok( b.clampPoint( new THREE.Vector2( 0, 0 ) ).equals( new THREE.Vector2( 0, 0 ) ), "Passed!" ); - ok( b.clampPoint( new THREE.Vector2( -1, -1 ) ).equals( new THREE.Vector2( -1, -1 ) ), "Passed!" ); - ok( b.clampPoint( new THREE.Vector2( -2, -2 ) ).equals( new THREE.Vector2( -1, -1 ) ), "Passed!" ); - }); - - test( "distanceToPoint", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - var b = new THREE.Box2( one2.clone().negate(), one2.clone() ); - - ok( a.distanceToPoint( new THREE.Vector2( 0, 0 ) ) == 0, "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector2( 1, 1 ) ) == Math.sqrt( 2 ), "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector2( -1, -1 ) ) == Math.sqrt( 2 ), "Passed!" ); - - ok( b.distanceToPoint( new THREE.Vector2( 2, 2 ) ) == Math.sqrt( 2 ), "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( 1, 1 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( 0, 0 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( -1, -1 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( -2, -2 ) ) == Math.sqrt( 2 ), "Passed!" ); - }); - - test( "distanceToPoint", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - var b = new THREE.Box2( one2.clone().negate(), one2.clone() ); - - ok( a.distanceToPoint( new THREE.Vector2( 0, 0 ) ) == 0, "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector2( 1, 1 ) ) == Math.sqrt( 2 ), "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector2( -1, -1 ) ) == Math.sqrt( 2 ), "Passed!" ); - - ok( b.distanceToPoint( new THREE.Vector2( 2, 2 ) ) == Math.sqrt( 2 ), "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( 1, 1 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( 0, 0 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( -1, -1 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector2( -2, -2 ) ) == Math.sqrt( 2 ), "Passed!" ); - }); - - test( "isIntersectionBox", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - var b = new THREE.Box2( zero2.clone(), one2.clone() ); - var c = new THREE.Box2( one2.clone().negate(), one2.clone() ); - - ok( a.isIntersectionBox( a ), "Passed!" ); - ok( a.isIntersectionBox( b ), "Passed!" ); - ok( a.isIntersectionBox( c ), "Passed!" ); - - ok( b.isIntersectionBox( a ), "Passed!" ); - ok( c.isIntersectionBox( a ), "Passed!" ); - ok( b.isIntersectionBox( c ), "Passed!" ); - - b.translate( new THREE.Vector2( 2, 2 ) ); - ok( ! a.isIntersectionBox( b ), "Passed!" ); - ok( ! b.isIntersectionBox( a ), "Passed!" ); - ok( ! b.isIntersectionBox( c ), "Passed!" ); - }); - - test( "intersect", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - var b = new THREE.Box2( zero2.clone(), one2.clone() ); - var c = new THREE.Box2( one2.clone().negate(), one2.clone() ); - - ok( a.clone().intersect( a ).equals( a ), "Passed!" ); - ok( a.clone().intersect( b ).equals( a ), "Passed!" ); - ok( b.clone().intersect( b ).equals( b ), "Passed!" ); - ok( a.clone().intersect( c ).equals( a ), "Passed!" ); - ok( b.clone().intersect( c ).equals( b ), "Passed!" ); - ok( c.clone().intersect( c ).equals( c ), "Passed!" ); - }); - - test( "union", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - var b = new THREE.Box2( zero2.clone(), one2.clone() ); - var c = new THREE.Box2( one2.clone().negate(), one2.clone() ); - - ok( a.clone().union( a ).equals( a ), "Passed!" ); - ok( a.clone().union( b ).equals( b ), "Passed!" ); - ok( a.clone().union( c ).equals( c ), "Passed!" ); - ok( b.clone().union( c ).equals( c ), "Passed!" ); - }); - - test( "translate", function() { - var a = new THREE.Box2( zero2.clone(), zero2.clone() ); - var b = new THREE.Box2( zero2.clone(), one2.clone() ); - var c = new THREE.Box2( one2.clone().negate(), one2.clone() ); - var d = new THREE.Box2( one2.clone().negate(), zero2.clone() ); - - ok( a.clone().translate( one2 ).equals( new THREE.Box2( one2, one2 ) ), "Passed!" ); - ok( a.clone().translate( one2 ).translate( one2.clone().negate() ).equals( a ), "Passed!" ); - ok( d.clone().translate( one2 ).equals( b ), "Passed!" ); - ok( b.clone().translate( one2.clone().negate() ).equals( d ), "Passed!" ); - }); - - test( "constructor", function() { - var a = new THREE.Box3(); - ok( a.min.equals( posInf3 ), "Passed!" ); - ok( a.max.equals( negInf3 ), "Passed!" ); - - a = new THREE.Box3( zero3.clone(), zero3.clone() ); - ok( a.min.equals( zero3 ), "Passed!" ); - ok( a.max.equals( zero3 ), "Passed!" ); - - a = new THREE.Box3( zero3.clone(), one3.clone() ); - ok( a.min.equals( zero3 ), "Passed!" ); - ok( a.max.equals( one3 ), "Passed!" ); - }); - - test( "copy", function() { - var a = new THREE.Box3( zero3.clone(), one3.clone() ); - var b = new THREE.Box3().copy( a ); - ok( b.min.equals( zero3 ), "Passed!" ); - ok( b.max.equals( one3 ), "Passed!" ); - - // ensure that it is a true copy - a.min = zero3; - a.max = one3; - ok( b.min.equals( zero3 ), "Passed!" ); - ok( b.max.equals( one3 ), "Passed!" ); - }); - - test( "set", function() { - var a = new THREE.Box3(); - - a.set( zero3, one3 ); - ok( a.min.equals( zero3 ), "Passed!" ); - ok( a.max.equals( one3 ), "Passed!" ); - }); - - test( "empty/makeEmpty", function() { - var a = new THREE.Box3(); - - ok( a.empty(), "Passed!" ); - - var a = new THREE.Box3( zero3.clone(), one3.clone() ); - ok( ! a.empty(), "Passed!" ); - - a.makeEmpty(); - ok( a.empty(), "Passed!" ); - }); - - test( "center", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - - ok( a.center().equals( zero3 ), "Passed!" ); - - a = new THREE.Box3( zero3.clone(), one3.clone() ); - var midpoint = one3.clone().multiplyScalar( 0.5 ); - ok( a.center().equals( midpoint ), "Passed!" ); - }); - - test( "size", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - - ok( a.size().equals( zero3 ), "Passed!" ); - - a = new THREE.Box3( zero3.clone(), one3.clone() ); - ok( a.size().equals( one3 ), "Passed!" ); - }); - - test( "expandByPoint", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - - a.expandByPoint( zero3 ); - ok( a.size().equals( zero3 ), "Passed!" ); - - a.expandByPoint( one3 ); - ok( a.size().equals( one3 ), "Passed!" ); - - a.expandByPoint( one3.clone().negate() ); - ok( a.size().equals( one3.clone().multiplyScalar( 2 ) ), "Passed!" ); - ok( a.center().equals( zero3 ), "Passed!" ); - }); - - test( "expandByVector", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - - a.expandByVector( zero3 ); - ok( a.size().equals( zero3 ), "Passed!" ); - - a.expandByVector( one3 ); - ok( a.size().equals( one3.clone().multiplyScalar( 2 ) ), "Passed!" ); - ok( a.center().equals( zero3 ), "Passed!" ); - }); - - test( "expandByScalar", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - - a.expandByScalar( 0 ); - ok( a.size().equals( zero3 ), "Passed!" ); - - a.expandByScalar( 1 ); - ok( a.size().equals( one3.clone().multiplyScalar( 2 ) ), "Passed!" ); - ok( a.center().equals( zero3 ), "Passed!" ); - }); - - test( "containsPoint", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - - ok( a.containsPoint( zero3 ), "Passed!" ); - ok( ! a.containsPoint( one3 ), "Passed!" ); - - a.expandByScalar( 1 ); - ok( a.containsPoint( zero3 ), "Passed!" ); - ok( a.containsPoint( one3 ), "Passed!" ); - ok( a.containsPoint( one3.clone().negate() ), "Passed!" ); - }); - - test( "containsBox", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - var b = new THREE.Box3( zero3.clone(), one3.clone() ); - var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); - - ok( a.containsBox( a ), "Passed!" ); - ok( ! a.containsBox( b ), "Passed!" ); - ok( ! a.containsBox( c ), "Passed!" ); - - ok( b.containsBox( a ), "Passed!" ); - ok( c.containsBox( a ), "Passed!" ); - ok( ! b.containsBox( c ), "Passed!" ); - }); - - test( "getParameter", function() { - var a = new THREE.Box3( zero3.clone(), one3.clone() ); - var b = new THREE.Box3( one3.clone().negate(), one3.clone() ); - - ok( a.getParameter( new THREE.Vector3( 0, 0, 0 ) ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - ok( a.getParameter( new THREE.Vector3( 1, 1, 1 ) ).equals( new THREE.Vector3( 1, 1, 1 ) ), "Passed!" ); - - ok( b.getParameter( new THREE.Vector3( -1, -1, -1 ) ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - ok( b.getParameter( new THREE.Vector3( 0, 0, 0 ) ).equals( new THREE.Vector3( 0.5, 0.5, 0.5 ) ), "Passed!" ); - ok( b.getParameter( new THREE.Vector3( 1, 1, 1 ) ).equals( new THREE.Vector3( 1, 1, 1 ) ), "Passed!" ); - }); - - test( "clampPoint", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - var b = new THREE.Box3( one3.clone().negate(), one3.clone() ); - - ok( a.clampPoint( new THREE.Vector3( 0, 0, 0 ) ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - ok( a.clampPoint( new THREE.Vector3( 1, 1, 1 ) ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - ok( a.clampPoint( new THREE.Vector3( -1, -1, -1 ) ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - - ok( b.clampPoint( new THREE.Vector3( 2, 2, 2 ) ).equals( new THREE.Vector3( 1, 1, 1 ) ), "Passed!" ); - ok( b.clampPoint( new THREE.Vector3( 1, 1, 1 ) ).equals( new THREE.Vector3( 1, 1, 1 ) ), "Passed!" ); - ok( b.clampPoint( new THREE.Vector3( 0, 0, 0 ) ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - ok( b.clampPoint( new THREE.Vector3( -1, -1, -1 ) ).equals( new THREE.Vector3( -1, -1, -1 ) ), "Passed!" ); - ok( b.clampPoint( new THREE.Vector3( -2, -2, -2 ) ).equals( new THREE.Vector3( -1, -1, -1 ) ), "Passed!" ); - }); - - test( "distanceToPoint", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - var b = new THREE.Box3( one3.clone().negate(), one3.clone() ); - - ok( a.distanceToPoint( new THREE.Vector3( 0, 0, 0 ) ) == 0, "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector3( 1, 1, 1 ) ) == Math.sqrt( 3 ), "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector3( -1, -1, -1 ) ) == Math.sqrt( 3 ), "Passed!" ); - - ok( b.distanceToPoint( new THREE.Vector3( 2, 2, 2 ) ) == Math.sqrt( 3 ), "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector3( 1, 1, 1 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector3( 0, 0, 0 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector3( -1, -1, -1 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector3( -2, -2, -2 ) ) == Math.sqrt( 3 ), "Passed!" ); - }); - - test( "distanceToPoint", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - var b = new THREE.Box3( one3.clone().negate(), one3.clone() ); - - ok( a.distanceToPoint( new THREE.Vector3( 0, 0, 0 ) ) == 0, "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector3( 1, 1, 1 ) ) == Math.sqrt( 3 ), "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector3( -1, -1, -1 ) ) == Math.sqrt( 3 ), "Passed!" ); - - ok( b.distanceToPoint( new THREE.Vector3( 2, 2, 2 ) ) == Math.sqrt( 3 ), "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector3( 1, 1, 1 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector3( 0, 0, 0 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector3( -1, -1, -1 ) ) == 0, "Passed!" ); - ok( b.distanceToPoint( new THREE.Vector3( -2, -2, -2 ) ) == Math.sqrt( 3 ), "Passed!" ); - }); - - test( "isIntersectionBox", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - var b = new THREE.Box3( zero3.clone(), one3.clone() ); - var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); - - ok( a.isIntersectionBox( a ), "Passed!" ); - ok( a.isIntersectionBox( b ), "Passed!" ); - ok( a.isIntersectionBox( c ), "Passed!" ); - - ok( b.isIntersectionBox( a ), "Passed!" ); - ok( c.isIntersectionBox( a ), "Passed!" ); - ok( b.isIntersectionBox( c ), "Passed!" ); - - b.translate( new THREE.Vector3( 2, 2, 2 ) ); - ok( ! a.isIntersectionBox( b ), "Passed!" ); - ok( ! b.isIntersectionBox( a ), "Passed!" ); - ok( ! b.isIntersectionBox( c ), "Passed!" ); - }); - - test( "getBoundingSphere", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - var b = new THREE.Box3( zero3.clone(), one3.clone() ); - var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); - - ok( a.getBoundingSphere().equals( new THREE.Sphere( zero3, 0 ) ), "Passed!" ); - ok( b.getBoundingSphere().equals( new THREE.Sphere( one3.clone().multiplyScalar( 0.5 ), Math.sqrt( 3 ) * 0.5 ) ), "Passed!" ); - ok( c.getBoundingSphere().equals( new THREE.Sphere( zero3, Math.sqrt( 12 ) * 0.5 ) ), "Passed!" ); - }); - - test( "intersect", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - var b = new THREE.Box3( zero3.clone(), one3.clone() ); - var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); - - ok( a.clone().intersect( a ).equals( a ), "Passed!" ); - ok( a.clone().intersect( b ).equals( a ), "Passed!" ); - ok( b.clone().intersect( b ).equals( b ), "Passed!" ); - ok( a.clone().intersect( c ).equals( a ), "Passed!" ); - ok( b.clone().intersect( c ).equals( b ), "Passed!" ); - ok( c.clone().intersect( c ).equals( c ), "Passed!" ); - }); - - test( "union", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - var b = new THREE.Box3( zero3.clone(), one3.clone() ); - var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); - - ok( a.clone().union( a ).equals( a ), "Passed!" ); - ok( a.clone().union( b ).equals( b ), "Passed!" ); - ok( a.clone().union( c ).equals( c ), "Passed!" ); - ok( b.clone().union( c ).equals( c ), "Passed!" ); - }); - - var compareBox = function ( a, b, threshold? ) { - threshold = threshold || 0.0001; - return ( a.min.distanceTo( b.min ) < threshold && - a.max.distanceTo( b.max ) < threshold ); - }; - - test( "applyMatrix4", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - var b = new THREE.Box3( zero3.clone(), one3.clone() ); - var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); - var d = new THREE.Box3( one3.clone().negate(), zero3.clone() ); - - var m = new THREE.Matrix4().makeTranslation( 1, -2, 1 ); - var t1 = new THREE.Vector3( 1, -2, 1 ); - - ok( compareBox( a.clone().applyMatrix4( m ), a.clone().translate( t1 ) ), "Passed!" ); - ok( compareBox( b.clone().applyMatrix4( m ), b.clone().translate( t1 ) ), "Passed!" ); - ok( compareBox( c.clone().applyMatrix4( m ), c.clone().translate( t1 ) ), "Passed!" ); - ok( compareBox( d.clone().applyMatrix4( m ), d.clone().translate( t1 ) ), "Passed!" ); - }); - - test( "translate", function() { - var a = new THREE.Box3( zero3.clone(), zero3.clone() ); - var b = new THREE.Box3( zero3.clone(), one3.clone() ); - var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); - var d = new THREE.Box3( one3.clone().negate(), zero3.clone() ); - - ok( a.clone().translate( one3 ).equals( new THREE.Box3( one3, one3 ) ), "Passed!" ); - ok( a.clone().translate( one3 ).translate( one3.clone().negate() ).equals( a ), "Passed!" ); - ok( d.clone().translate( one3 ).equals( b ), "Passed!" ); - ok( b.clone().translate( one3.clone().negate() ).equals( d ), "Passed!" ); - }); - - test( "constructor", function(){ - var c = new THREE.Color(); - ok( c.r, "Red: " + c.r ); - ok( c.g, "Green: " + c.g ); - ok( c.b, "Blue: " + c.g ); - }); - - test( "copyHex", function(){ - var c = new THREE.Color(); - var c2 = new THREE.Color(0xF5FFFA); - c.copy(c2); - ok(c.getHex() == c2.getHex(), "Hex c: " + c.getHex() + " Hex c2: " + c2.getHex()); - }); - - test( "copyColorString", function(){ - var c = new THREE.Color(); - var c2 = new THREE.Color('ivory'); - c.copy(c2); - ok(c.getHex() == c2.getHex(), "Hex c: " + c.getHex() + " Hex c2: " + c2.getHex()); - }); - - test( "setRGB", function(){ - var c = new THREE.Color() - c.setRGB(255, 2, 1); - ok( c.r == 255, "Red: " + c.r ); - ok( c.g == 2, "Green: " + c.g ); - ok( c.b == 1, "Blue: " + c.b ); - }); - - test( "copyGammaToLinear", function(){ - var c = new THREE.Color(); - var c2 = new THREE.Color(); - c2.setRGB(2, 4, 8) - c.copyGammaToLinear(c2) - ok( c.r == 4, "Red c: " + c.r + " Red c2: " + c2.r); - ok( c.g == 16, "Green c: " + c.g + " Green c2: " + c2.g); - ok( c.b == 64, "Blue c: " + c.b + " Blue c2: " + c2.b); - }); - - test( "copyLinearToGamma", function(){ - var c = new THREE.Color(); - var c2 = new THREE.Color(); - c2.setRGB(4, 9, 16) - c.copyLinearToGamma(c2) - ok( c.r == 2, "Red c: " + c.r + " Red c2: " + c2.r); - ok( c.g == 3, "Green c: " + c.g + " Green c2: " + c2.g); - ok( c.b == 4, "Blue c: " + c.b + " Blue c2: " + c2.b); - }); - - - test( "convertGammaToLinear", function(){ - var c = new THREE.Color(); - c.setRGB(2, 4, 8) - c.convertGammaToLinear() - ok( c.r == 4, "Red: " + c.r ); - ok( c.g == 16, "Green: " + c.g ); - ok( c.b == 64, "Blue: " + c.b ); - }); - - - test( "convertLinearToGamma", function(){ - var c = new THREE.Color(); - c.setRGB(4, 9, 16) - c.convertLinearToGamma() - ok( c.r == 2, "Red: " + c.r ); - ok( c.g == 3, "Green: " + c.g ); - ok( c.b == 4, "Blue: " + c.b ); - }); - - test("setWithNum", function(){ - var c = new THREE.Color(); - c.set(0xFF0000); - ok( c.r == 1, "Red: " + c.r ); - ok( c.g == 0, "Green: " + c.g ); - ok( c.b == 0, "Blue: " + c.b ); - }); - - - test( "setWithString", function(){ - var c = new THREE.Color(); - c.set('silver'); - ok(c.getHex() == 0xC0C0C0, "Hex c: " + c.getHex()); - }); - - - test( "clone", function(){ - var c = new THREE.Color('teal'); - var c2 = c.clone(); - ok(c2.getHex() == 0x008080, "Hex c2: " + c2.getHex()); - }); - - test( "lerp", function(){ - var c = new THREE.Color(); - var c2 = new THREE.Color(); - c.setRGB(0, 0, 0); - c.lerp(c2, 2); - ok( c.r == 2, "Red: " + c.r ); - ok( c.g == 2, "Green: " + c.g ); - ok( c.b == 2, "Blue: " + c.b ); - - }); - - - test( "setStyleRGBRed", function(){ - var c = new THREE.Color(); - c.setStyle('rgb(255,0,0)'); - ok( c.r == 1, "Red: " + c.r ); - ok( c.g == 0, "Green: " + c.g ); - ok( c.b == 0, "Blue: " + c.b ); - }); - - test( "setStyleRGBPercent", function(){ - var c = new THREE.Color(); - c.setStyle('rgb(100%,50%,10%)'); - ok( c.r == 1, "Red: " + c.r ); - ok( c.g == 0.5, "Green: " + c.g ); - ok( c.b == 0.1, "Blue: " + c.b ); - }); - - test( "setStyleHexSkyBlue", function(){ - var c = new THREE.Color(); - c.setStyle('#87CEEB'); - ok(c.getHex() == 0x87CEEB, "Hex c: " + c.getHex()); - }); - - test( "setStyleHex2Olive", function(){ - var c = new THREE.Color(); - c.setStyle('#F00'); - ok(c.getHex() == 0xFF0000, "Hex c: " + c.getHex()); - }); - - test( "setStyleColorName", function(){ - var c = new THREE.Color(); - c.setStyle('powderblue'); - ok(c.getHex() == 0xB0E0E6, "Hex c: " + c.getHex()); - }); - - - test( "getHex", function(){ - var c = new THREE.Color('red'); - var res = c.getHex(); - ok( res == 0xFF0000, "Hex: " + res ); - }); - - test( "setHex", function(){ - var c = new THREE.Color(); - c.setHex(0xFA8072); - ok( c.getHex() == 0xFA8072, "Hex: " + c.getHex()); - }); - - test( "getHexString", function(){ - var c = new THREE.Color('tomato'); - var res = c.getHexString(); - ok( res == 'ff6347', "Hex: " + res ); - }); - - test( "getStyle", function(){ - var c = new THREE.Color('plum'); - var res = c.getStyle(); - ok( res == 'rgb(221,160,221)', "style: " + res ); - }); - - test( "getHSL", function () { - var c = new THREE.Color( 0x80ffff ); - var hsl = c.getHSL(); - - ok( hsl.h == 0.5, "hue: " + hsl.h ); - ok( hsl.s == 1.0, "saturation: " + hsl.s ); - - - //ok( (Math.round(parseFloat(hsl.l)*100)/100) == 0.75, "lightness: " + hsl.l ); - ok( (Math.round(hsl.l*100)/100) == 0.75, "lightness: " + hsl.l ); - }); - - test( "setHSL", function () { - var c = new THREE.Color(); - c.setHSL(0.75, 1.0, 0.25); - var hsl = c.getHSL(); - - ok( hsl.h == 0.75, "hue: " + hsl.h ); - ok( hsl.s == 1.00, "saturation: " + hsl.s ); - ok( hsl.l == 0.25, "lightness: " + hsl.l ); - }); - - var unit3 = new THREE.Vector3( 1, 0, 0 ); - - var planeEquals = function ( a, b, tolerance ) { - tolerance = tolerance || 0.0001; - if( a.normal.distanceTo( b.normal ) > tolerance ) { - return false; - } - if( Math.abs( a.constant - b.constant ) > tolerance ) { - return false; - } - return true; - }; - - test( "constructor", function() { - var a = new THREE.Frustum(); - - ok( a.planes !== undefined, "Passed!" ); - ok( a.planes.length === 6, "Passed!" ); - - var pDefault = new THREE.Plane(); - for( var i = 0; i < 6; i ++ ) { - ok( a.planes[i].equals( pDefault ), "Passed!" ); - } - - var p0 = new THREE.Plane( unit3, -1 ); - var p1 = new THREE.Plane( unit3, 1 ); - var p2 = new THREE.Plane( unit3, 2 ); - var p3 = new THREE.Plane( unit3, 3 ); - var p4 = new THREE.Plane( unit3, 4 ); - var p5 = new THREE.Plane( unit3, 5 ); - - a = new THREE.Frustum( p0, p1, p2, p3, p4, p5 ); - ok( a.planes[0].equals( p0 ), "Passed!" ); - ok( a.planes[1].equals( p1 ), "Passed!" ); - ok( a.planes[2].equals( p2 ), "Passed!" ); - ok( a.planes[3].equals( p3 ), "Passed!" ); - ok( a.planes[4].equals( p4 ), "Passed!" ); - ok( a.planes[5].equals( p5 ), "Passed!" ); - }); - - test( "copy", function() { - - var p0 = new THREE.Plane( unit3, -1 ); - var p1 = new THREE.Plane( unit3, 1 ); - var p2 = new THREE.Plane( unit3, 2 ); - var p3 = new THREE.Plane( unit3, 3 ); - var p4 = new THREE.Plane( unit3, 4 ); - var p5 = new THREE.Plane( unit3, 5 ); - - var b = new THREE.Frustum( p0, p1, p2, p3, p4, p5 ); - var a = new THREE.Frustum().copy( b ); - ok( a.planes[0].equals( p0 ), "Passed!" ); - ok( a.planes[1].equals( p1 ), "Passed!" ); - ok( a.planes[2].equals( p2 ), "Passed!" ); - ok( a.planes[3].equals( p3 ), "Passed!" ); - ok( a.planes[4].equals( p4 ), "Passed!" ); - ok( a.planes[5].equals( p5 ), "Passed!" ); - - // ensure it is a true copy by modifying source - b.planes[0] = p1; - ok( a.planes[0].equals( p0 ), "Passed!" ); - }); - - test( "setFromMatrix/makeOrthographic/containsPoint", function() { - var m = new THREE.Matrix4().makeOrthographic( -1, 1, -1, 1, 1, 100 ) - var a = new THREE.Frustum().setFromMatrix( m ); - - ok( ! a.containsPoint( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - ok( a.containsPoint( new THREE.Vector3( 0, 0, -50 ) ), "Passed!" ); - ok( a.containsPoint( new THREE.Vector3( 0, 0, -1.001 ) ), "Passed!" ); - ok( a.containsPoint( new THREE.Vector3( -1, -1, -1.001 ) ), "Passed!" ); - ok( ! a.containsPoint( new THREE.Vector3( -1.1, -1.1, -1.001 ) ), "Passed!" ); - ok( a.containsPoint( new THREE.Vector3( 1, 1, -1.001 ) ), "Passed!" ); - ok( ! a.containsPoint( new THREE.Vector3( 1.1, 1.1, -1.001 ) ), "Passed!" ); - ok( a.containsPoint( new THREE.Vector3( 0, 0, -100 ) ), "Passed!" ); - ok( a.containsPoint( new THREE.Vector3( -1, -1, -100 ) ), "Passed!" ); - ok( ! a.containsPoint( new THREE.Vector3( -1.1, -1.1, -100.1 ) ), "Passed!" ); - ok( a.containsPoint( new THREE.Vector3( 1, 1, -100 ) ), "Passed!" ); - ok( ! a.containsPoint( new THREE.Vector3( 1.1, 1.1, -100.1 ) ), "Passed!" ); - ok( ! a.containsPoint( new THREE.Vector3( 0, 0, -101 ) ), "Passed!" ); - - }); - - test( "setFromMatrix/makeFrustum/containsPoint", function() { - var m = new THREE.Matrix4().makeFrustum( -1, 1, -1, 1, 1, 100 ) - var a = new THREE.Frustum().setFromMatrix( m ); - - ok( ! a.containsPoint( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - ok( a.containsPoint( new THREE.Vector3( 0, 0, -50 ) ), "Passed!" ); - ok( a.containsPoint( new THREE.Vector3( 0, 0, -1.001 ) ), "Passed!" ); - ok( a.containsPoint( new THREE.Vector3( -1, -1, -1.001 ) ), "Passed!" ); - ok( ! a.containsPoint( new THREE.Vector3( -1.1, -1.1, -1.001 ) ), "Passed!" ); - ok( a.containsPoint( new THREE.Vector3( 1, 1, -1.001 ) ), "Passed!" ); - ok( ! a.containsPoint( new THREE.Vector3( 1.1, 1.1, -1.001 ) ), "Passed!" ); - ok( a.containsPoint( new THREE.Vector3( 0, 0, -99.999 ) ), "Passed!" ); - ok( a.containsPoint( new THREE.Vector3( -99.999, -99.999, -99.999 ) ), "Passed!" ); - ok( ! a.containsPoint( new THREE.Vector3( -100.1, -100.1, -100.1 ) ), "Passed!" ); - ok( a.containsPoint( new THREE.Vector3( 99.999, 99.999, -99.999 ) ), "Passed!" ); - ok( ! a.containsPoint( new THREE.Vector3( 100.1, 100.1, -100.1 ) ), "Passed!" ); - ok( ! a.containsPoint( new THREE.Vector3( 0, 0, -101 ) ), "Passed!" ); - }); - - test( "setFromMatrix/makeFrustum/intersectsSphere", function() { - var m = new THREE.Matrix4().makeFrustum( -1, 1, -1, 1, 1, 100 ) - var a = new THREE.Frustum().setFromMatrix( m ); - - ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, 0 ), 0 ) ), "Passed!" ); - ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, 0 ), 0.9 ) ), "Passed!" ); - ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, 0 ), 1.1 ) ), "Passed!" ); - ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, -50 ), 0 ) ), "Passed!" ); - ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, -1.001 ), 0 ) ), "Passed!" ); - ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( -1, -1, -1.001 ), 0 ) ), "Passed!" ); - ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( -1.1, -1.1, -1.001 ), 0 ) ), "Passed!" ); - ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( -1.1, -1.1, -1.001 ), 0.5 ) ), "Passed!" ); - ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 1, 1, -1.001 ), 0 ) ), "Passed!" ); - ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 1.1, 1.1, -1.001 ), 0 ) ), "Passed!" ); - ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 1.1, 1.1, -1.001 ), 0.5 ) ), "Passed!" ); - ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, -99.999 ), 0 ) ), "Passed!" ); - ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( -99.999, -99.999, -99.999 ), 0 ) ), "Passed!" ); - ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( -100.1, -100.1, -100.1 ), 0 ) ), "Passed!" ); - ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( -100.1, -100.1, -100.1 ), 0.5 ) ), "Passed!" ); - ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 99.999, 99.999, -99.999 ), 0 ) ), "Passed!" ); - ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 100.1, 100.1, -100.1 ), 0 ) ), "Passed!" ); - ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 100.1, 100.1, -100.1 ), 0.2 ) ), "Passed!" ); - ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, -101 ), 0 ) ), "Passed!" ); - ok( a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, -101 ), 1.1 ) ), "Passed!" ); - }); - - test( "clone", function() { - - var p0 = new THREE.Plane( unit3, -1 ); - var p1 = new THREE.Plane( unit3, 1 ); - var p2 = new THREE.Plane( unit3, 2 ); - var p3 = new THREE.Plane( unit3, 3 ); - var p4 = new THREE.Plane( unit3, 4 ); - var p5 = new THREE.Plane( unit3, 5 ); - - var b = new THREE.Frustum( p0, p1, p2, p3, p4, p5 ); - var a = b.clone(); - ok( a.planes[0].equals( p0 ), "Passed!" ); - ok( a.planes[1].equals( p1 ), "Passed!" ); - ok( a.planes[2].equals( p2 ), "Passed!" ); - ok( a.planes[3].equals( p3 ), "Passed!" ); - ok( a.planes[4].equals( p4 ), "Passed!" ); - ok( a.planes[5].equals( p5 ), "Passed!" ); - - // ensure it is a true copy by modifying source - a.planes[0].copy( p1 ); - ok( b.planes[0].equals( p0 ), "Passed!" ); - }); - - - test( "constructor/equals", function() { - var a = new THREE.Line3(); - ok( a.start.equals( zero3 ), "Passed!" ); - ok( a.end.equals( zero3 ), "Passed!" ); - - a = new THREE.Line3( two3.clone(), one3.clone() ); - ok( a.start.equals( two3 ), "Passed!" ); - ok( a.end.equals( one3 ), "Passed!" ); - }); - - test( "copy/equals", function() { - var a = new THREE.Line3( zero3.clone(), one3.clone() ); - var b = new THREE.Line3().copy( a ); - ok( b.start.equals( zero3 ), "Passed!" ); - ok( b.end.equals( one3 ), "Passed!" ); - - // ensure that it is a true copy - a.start = zero3; - a.end = one3; - ok( b.start.equals( zero3 ), "Passed!" ); - ok( b.end.equals( one3 ), "Passed!" ); - }); - - test( "set", function() { - var a = new THREE.Line3(); - - a.set( one3, one3 ); - ok( a.start.equals( one3 ), "Passed!" ); - ok( a.end.equals( one3 ), "Passed!" ); - }); - - test( "at", function() { - var a = new THREE.Line3( one3.clone(), new THREE.Vector3( 1, 1, 2 ) ); - - ok( a.at( -1 ).distanceTo( new THREE.Vector3( 1, 1, 0 ) ) < 0.0001, "Passed!" ); - ok( a.at( 0 ).distanceTo( one3.clone() ) < 0.0001, "Passed!" ); - ok( a.at( 1 ).distanceTo( new THREE.Vector3( 1, 1, 2 ) ) < 0.0001, "Passed!" ); - ok( a.at( 2 ).distanceTo( new THREE.Vector3( 1, 1, 3 ) ) < 0.0001, "Passed!" ); - }); - - test( "closestPointToPoint/closestPointToPointParameter", function() { - var a = new THREE.Line3( one3.clone(), new THREE.Vector3( 1, 1, 2 ) ); - - // nearby the ray - ok( a.closestPointToPointParameter( zero3.clone(), true ) == 0, "Passed!" ); - var b1 = a.closestPointToPoint( zero3.clone(), true ); - ok( b1.distanceTo( new THREE.Vector3( 1, 1, 1 ) ) < 0.0001, "Passed!" ); - - // nearby the ray - ok( a.closestPointToPointParameter( zero3.clone(), false ) == -1, "Passed!" ); - var b2 = a.closestPointToPoint( zero3.clone(), false ); - console.log( b2 ); - ok( b2.distanceTo( new THREE.Vector3( 1, 1, 0 ) ) < 0.0001, "Passed!" ); - - // nearby the ray - ok( a.closestPointToPointParameter( new THREE.Vector3( 1, 1, 5 ), true ) == 1, "Passed!" ); - var b = a.closestPointToPoint( new THREE.Vector3( 1, 1, 5 ), true ); - ok( b.distanceTo( new THREE.Vector3( 1, 1, 2 ) ) < 0.0001, "Passed!" ); - - // exactly on the ray - ok( a.closestPointToPointParameter( one3.clone(), true ) == 0, "Passed!" ); - var c = a.closestPointToPoint( one3.clone(), true ); - ok( c.distanceTo( one3.clone() ) < 0.0001, "Passed!" ); - }); - - - - var matrixEquals3 = function( a, b, tolerance? ) { - tolerance = tolerance || 0.0001; - if( a.elements.length != b.elements.length ) { - return false; - } - for( var i = 0, il = a.elements.length; i < il; i ++ ) { - var delta = a.elements[i] - b.elements[i]; - if( delta > tolerance ) { - return false; - } - } - return true; - }; - - - var toMatrix4 = function( m3 ) { - var result = new THREE.Matrix4(); - var re = result.elements; - var me = m3.elements; - re[0] = me[0]; - re[1] = me[1]; - re[2] = me[2]; - re[4] = me[3]; - re[5] = me[4]; - re[6] = me[5]; - re[8] = me[6]; - re[9] = me[7]; - re[10] = me[8]; - - return result; - }; - - test( "constructor", function() { - var a = new THREE.Matrix3(); - ok( a.determinant() == 1, "Passed!" ); - - var b = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); - ok( b.elements[0] == 0 ); - ok( b.elements[1] == 3 ); - ok( b.elements[2] == 6 ); - ok( b.elements[3] == 1 ); - ok( b.elements[4] == 4 ); - ok( b.elements[5] == 7 ); - ok( b.elements[6] == 2 ); - ok( b.elements[7] == 5 ); - ok( b.elements[8] == 8 ); - - ok( ! matrixEquals3( a, b ), "Passed!" ); - }); - - test( "copy", function() { - var a = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); - var b = new THREE.Matrix3().copy( a ); - - ok( matrixEquals3( a, b ), "Passed!" ); - - // ensure that it is a true copy - a.elements[0] = 2; - ok( ! matrixEquals3( a, b ), "Passed!" ); - }); - - test( "set", function() { - var b = new THREE.Matrix3(); - ok( b.determinant() == 1, "Passed!" ); - - b.set( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); - ok( b.elements[0] == 0 ); - ok( b.elements[1] == 3 ); - ok( b.elements[2] == 6 ); - ok( b.elements[3] == 1 ); - ok( b.elements[4] == 4 ); - ok( b.elements[5] == 7 ); - ok( b.elements[6] == 2 ); - ok( b.elements[7] == 5 ); - ok( b.elements[8] == 8 ); - }); - - test( "identity", function() { - var b = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); - ok( b.elements[0] == 0 ); - ok( b.elements[1] == 3 ); - ok( b.elements[2] == 6 ); - ok( b.elements[3] == 1 ); - ok( b.elements[4] == 4 ); - ok( b.elements[5] == 7 ); - ok( b.elements[6] == 2 ); - ok( b.elements[7] == 5 ); - ok( b.elements[8] == 8 ); - - var a = new THREE.Matrix3(); - ok( ! matrixEquals3( a, b ), "Passed!" ); - - b.identity(); - ok( matrixEquals3( a, b ), "Passed!" ); - }); - - test( "multiplyScalar", function() { - var b = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); - ok( b.elements[0] == 0 ); - ok( b.elements[1] == 3 ); - ok( b.elements[2] == 6 ); - ok( b.elements[3] == 1 ); - ok( b.elements[4] == 4 ); - ok( b.elements[5] == 7 ); - ok( b.elements[6] == 2 ); - ok( b.elements[7] == 5 ); - ok( b.elements[8] == 8 ); - - b.multiplyScalar( 2 ); - ok( b.elements[0] == 0*2 ); - ok( b.elements[1] == 3*2 ); - ok( b.elements[2] == 6*2 ); - ok( b.elements[3] == 1*2 ); - ok( b.elements[4] == 4*2 ); - ok( b.elements[5] == 7*2 ); - ok( b.elements[6] == 2*2 ); - ok( b.elements[7] == 5*2 ); - ok( b.elements[8] == 8*2 ); - }); - - test( "determinant", function() { - var a = new THREE.Matrix3(); - ok( a.determinant() == 1, "Passed!" ); - - a.elements[0] = 2; - ok( a.determinant() == 2, "Passed!" ); - - a.elements[0] = 0; - ok( a.determinant() == 0, "Passed!" ); - - // calculated via http://www.euclideanspace.com/maths/algebra/matrix/functions/determinant/threeD/index.htm - a.set( 2, 3, 4, 5, 13, 7, 8, 9, 11 ); - ok( a.determinant() == -73, "Passed!" ); - }); - - - test( "getInverse", function() { - var identity = new THREE.Matrix4(); - var a = new THREE.Matrix4(); - var b = new THREE.Matrix3( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - - //var c = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - var c = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - - ok( ! matrixEquals3( a, b ), "Passed!" ); - b.getInverse( a, false ); - ok( matrixEquals3( b, new THREE.Matrix3() ), "Passed!" ); - - try { - b.getInverse( c, true ); - ok( false, "Passed!" ); // should never get here. - } - catch( err ) { - ok( true, "Passed!" ); - } - - var testMatrices = [ - new THREE.Matrix4().makeRotationX( 0.3 ), - new THREE.Matrix4().makeRotationX( -0.3 ), - new THREE.Matrix4().makeRotationY( 0.3 ), - new THREE.Matrix4().makeRotationY( -0.3 ), - new THREE.Matrix4().makeRotationZ( 0.3 ), - new THREE.Matrix4().makeRotationZ( -0.3 ), - new THREE.Matrix4().makeScale( 1, 2, 3 ), - new THREE.Matrix4().makeScale( 1/8, 1/2, 1/3 ) - ]; - - for( var i = 0, il = testMatrices.length; i < il; i ++ ) { - var m = testMatrices[i]; - var mInverse3 = new THREE.Matrix3().getInverse( m ); - - var mInverse = toMatrix4( mInverse3 ); - - // the determinant of the inverse should be the reciprocal - ok( Math.abs( m.determinant() * mInverse3.determinant() - 1 ) < 0.0001, "Passed!" ); - ok( Math.abs( m.determinant() * mInverse.determinant() - 1 ) < 0.0001, "Passed!" ); - - var mProduct = new THREE.Matrix4().multiplyMatrices( m, mInverse ); - ok( Math.abs( mProduct.determinant() - 1 ) < 0.0001, "Passed!" ); - ok( matrixEquals3( mProduct, identity ), "Passed!" ); - } - }); - - test( "transpose", function() { - var a = new THREE.Matrix3(); - var b = a.clone().transpose(); - ok( matrixEquals3( a, b ), "Passed!" ); - - b = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); - var c = b.clone().transpose(); - ok( ! matrixEquals3( b, c ), "Passed!" ); - c.transpose(); - ok( matrixEquals3( b, c ), "Passed!" ); - }); - - test( "clone", function() { - var a = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); - var b = a.clone(); - - ok( matrixEquals3( a, b ), "Passed!" ); - - // ensure that it is a true copy - a.elements[0] = 2; - ok( ! matrixEquals3( a, b ), "Passed!" ); - }); - - var matrixEquals4 = function( a, b, tolerance? ) { - tolerance = tolerance || 0.0001; - if( a.elements.length != b.elements.length ) { - return false; - } - for( var i = 0, il = a.elements.length; i < il; i ++ ) { - var delta = a.elements[i] - b.elements[i]; - if( delta > tolerance ) { - return false; - } - } - return true; - }; - - test( "constructor", function() { - var a = new THREE.Matrix4(); - ok( a.determinant() == 1, "Passed!" ); - - var b = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); - ok( b.elements[0] == 0 ); - ok( b.elements[1] == 4 ); - ok( b.elements[2] == 8 ); - ok( b.elements[3] == 12 ); - ok( b.elements[4] == 1 ); - ok( b.elements[5] == 5 ); - ok( b.elements[6] == 9 ); - ok( b.elements[7] == 13 ); - ok( b.elements[8] == 2 ); - ok( b.elements[9] == 6 ); - ok( b.elements[10] == 10 ); - ok( b.elements[11] == 14 ); - ok( b.elements[12] == 3 ); - ok( b.elements[13] == 7 ); - ok( b.elements[14] == 11 ); - ok( b.elements[15] == 15 ); - - ok( ! matrixEquals4( a, b ), "Passed!" ); - }); - - test( "copy", function() { - var a = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); - var b = new THREE.Matrix4().copy( a ); - - ok( matrixEquals4( a, b ), "Passed!" ); - - // ensure that it is a true copy - a.elements[0] = 2; - ok( ! matrixEquals4( a, b ), "Passed!" ); - }); - - test( "set", function() { - var b = new THREE.Matrix4(); - ok( b.determinant() == 1, "Passed!" ); - - b.set( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); - ok( b.elements[0] == 0 ); - ok( b.elements[1] == 4 ); - ok( b.elements[2] == 8 ); - ok( b.elements[3] == 12 ); - ok( b.elements[4] == 1 ); - ok( b.elements[5] == 5 ); - ok( b.elements[6] == 9 ); - ok( b.elements[7] == 13 ); - ok( b.elements[8] == 2 ); - ok( b.elements[9] == 6 ); - ok( b.elements[10] == 10 ); - ok( b.elements[11] == 14 ); - ok( b.elements[12] == 3 ); - ok( b.elements[13] == 7 ); - ok( b.elements[14] == 11 ); - ok( b.elements[15] == 15 ); - }); - - test( "identity", function() { - var b = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); - ok( b.elements[0] == 0 ); - ok( b.elements[1] == 4 ); - ok( b.elements[2] == 8 ); - ok( b.elements[3] == 12 ); - ok( b.elements[4] == 1 ); - ok( b.elements[5] == 5 ); - ok( b.elements[6] == 9 ); - ok( b.elements[7] == 13 ); - ok( b.elements[8] == 2 ); - ok( b.elements[9] == 6 ); - ok( b.elements[10] == 10 ); - ok( b.elements[11] == 14 ); - ok( b.elements[12] == 3 ); - ok( b.elements[13] == 7 ); - ok( b.elements[14] == 11 ); - ok( b.elements[15] == 15 ); - - var a = new THREE.Matrix4(); - ok( ! matrixEquals4( a, b ), "Passed!" ); - - b.identity(); - ok( matrixEquals4( a, b ), "Passed!" ); - }); - - test( "multiplyScalar", function() { - var b = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); - ok( b.elements[0] == 0 ); - ok( b.elements[1] == 4 ); - ok( b.elements[2] == 8 ); - ok( b.elements[3] == 12 ); - ok( b.elements[4] == 1 ); - ok( b.elements[5] == 5 ); - ok( b.elements[6] == 9 ); - ok( b.elements[7] == 13 ); - ok( b.elements[8] == 2 ); - ok( b.elements[9] == 6 ); - ok( b.elements[10] == 10 ); - ok( b.elements[11] == 14 ); - ok( b.elements[12] == 3 ); - ok( b.elements[13] == 7 ); - ok( b.elements[14] == 11 ); - ok( b.elements[15] == 15 ); - - b.multiplyScalar( 2 ); - ok( b.elements[0] == 0*2 ); - ok( b.elements[1] == 4*2 ); - ok( b.elements[2] == 8*2 ); - ok( b.elements[3] == 12*2 ); - ok( b.elements[4] == 1*2 ); - ok( b.elements[5] == 5*2 ); - ok( b.elements[6] == 9*2 ); - ok( b.elements[7] == 13*2 ); - ok( b.elements[8] == 2*2 ); - ok( b.elements[9] == 6*2 ); - ok( b.elements[10] == 10*2 ); - ok( b.elements[11] == 14*2 ); - ok( b.elements[12] == 3*2 ); - ok( b.elements[13] == 7*2 ); - ok( b.elements[14] == 11*2 ); - ok( b.elements[15] == 15*2 ); - }); - - test( "determinant", function() { - var a = new THREE.Matrix4(); - ok( a.determinant() == 1, "Passed!" ); - - a.elements[0] = 2; - ok( a.determinant() == 2, "Passed!" ); - - a.elements[0] = 0; - ok( a.determinant() == 0, "Passed!" ); - - // calculated via http://www.euclideanspace.com/maths/algebra/matrix/functions/determinant/fourD/index.htm - a.set( 2, 3, 4, 5, -1, -21, -3, -4, 6, 7, 8, 10, -8, -9, -10, -12 ); - ok( a.determinant() == 76, "Passed!" ); - }); - - test( "getInverse", function() { - var identity = new THREE.Matrix4(); - - var a = new THREE.Matrix4(); - var b = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - var c = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - - ok( ! matrixEquals4( a, b ), "Passed!" ); - b.getInverse( a, false ); - ok( matrixEquals4( b, new THREE.Matrix4() ), "Passed!" ); - - try { - b.getInverse( c, true ); - ok( false, "Passed!" ); // should never get here. - } - catch( err ) { - ok( true, "Passed!" ); - } - - var testMatrices = [ - new THREE.Matrix4().makeRotationX( 0.3 ), - new THREE.Matrix4().makeRotationX( -0.3 ), - new THREE.Matrix4().makeRotationY( 0.3 ), - new THREE.Matrix4().makeRotationY( -0.3 ), - new THREE.Matrix4().makeRotationZ( 0.3 ), - new THREE.Matrix4().makeRotationZ( -0.3 ), - new THREE.Matrix4().makeScale( 1, 2, 3 ), - new THREE.Matrix4().makeScale( 1/8, 1/2, 1/3 ), - new THREE.Matrix4().makeFrustum( -1, 1, -1, 1, 1, 1000 ), - new THREE.Matrix4().makeFrustum( -16, 16, -9, 9, 0.1, 10000 ), - new THREE.Matrix4().makeTranslation( 1, 2, 3 ) - ]; - - for( var i = 0, il = testMatrices.length; i < il; i ++ ) { - var m = testMatrices[i]; - - var mInverse = new THREE.Matrix4().getInverse( m ); - - // the determinant of the inverse should be the reciprocal - ok( Math.abs( m.determinant() * mInverse.determinant() - 1 ) < 0.0001, "Passed!" ); - - var mProduct = new THREE.Matrix4().multiplyMatrices( m, mInverse ); - - // the determinant of the identity matrix is 1 - ok( Math.abs( mProduct.determinant() - 1 ) < 0.0001, "Passed!" ); - ok( matrixEquals4( mProduct, identity ), "Passed!" ); - } - }); - - test( "transpose", function() { - var a = new THREE.Matrix4(); - var b = a.clone().transpose(); - ok( matrixEquals4( a, b ), "Passed!" ); - - b = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); - var c = b.clone().transpose(); - ok( ! matrixEquals4( b, c ), "Passed!" ); - c.transpose(); - ok( matrixEquals4( b, c ), "Passed!" ); - }); - - test( "clone", function() { - var a = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); - var b = a.clone(); - - ok( matrixEquals4( a, b ), "Passed!" ); - - // ensure that it is a true copy - a.elements[0] = 2; - ok( ! matrixEquals4( a, b ), "Passed!" ); - }); - - - var comparePlane = function ( a, b, threshold? ) { - threshold = threshold || 0.0001; - return ( a.normal.distanceTo( b.normal ) < threshold && - Math.abs( a.constant - b.constant ) < threshold ); - }; - - - test( "constructor", function() { - var a = new THREE.Plane(); - ok( a.normal.x == 1, "Passed!" ); - ok( a.normal.y == 0, "Passed!" ); - ok( a.normal.z == 0, "Passed!" ); - ok( a.constant == 0, "Passed!" ); - - a = new THREE.Plane( one3.clone(), 0 ); - ok( a.normal.x == 1, "Passed!" ); - ok( a.normal.y == 1, "Passed!" ); - ok( a.normal.z == 1, "Passed!" ); - ok( a.constant == 0, "Passed!" ); - - a = new THREE.Plane( one3.clone(), 1 ); - ok( a.normal.x == 1, "Passed!" ); - ok( a.normal.y == 1, "Passed!" ); - ok( a.normal.z == 1, "Passed!" ); - ok( a.constant == 1, "Passed!" ); - }); - - test( "copy", function() { - var a = new THREE.Plane( new THREE.Vector3( x, y, z ), w ); - var b = new THREE.Plane().copy( a ); - ok( b.normal.x == x, "Passed!" ); - ok( b.normal.y == y, "Passed!" ); - ok( b.normal.z == z, "Passed!" ); - ok( b.constant == w, "Passed!" ); - - // ensure that it is a true copy - a.normal.x = 0; - a.normal.y = -1; - a.normal.z = -2; - a.constant = -3; - ok( b.normal.x == x, "Passed!" ); - ok( b.normal.y == y, "Passed!" ); - ok( b.normal.z == z, "Passed!" ); - ok( b.constant == w, "Passed!" ); - }); - - test( "set", function() { - var a = new THREE.Plane(); - ok( a.normal.x == 1, "Passed!" ); - ok( a.normal.y == 0, "Passed!" ); - ok( a.normal.z == 0, "Passed!" ); - ok( a.constant == 0, "Passed!" ); - - var b = a.clone().set( new THREE.Vector3( x, y, z ), w ); - ok( b.normal.x == x, "Passed!" ); - ok( b.normal.y == y, "Passed!" ); - ok( b.normal.z == z, "Passed!" ); - ok( b.constant == w, "Passed!" ); - }); - - test( "setComponents", function() { - var a = new THREE.Plane(); - ok( a.normal.x == 1, "Passed!" ); - ok( a.normal.y == 0, "Passed!" ); - ok( a.normal.z == 0, "Passed!" ); - ok( a.constant == 0, "Passed!" ); - - var b = a.clone().setComponents( x, y, z , w ); - ok( b.normal.x == x, "Passed!" ); - ok( b.normal.y == y, "Passed!" ); - ok( b.normal.z == z, "Passed!" ); - ok( b.constant == w, "Passed!" ); - }); - - test( "setFromNormalAndCoplanarPoint", function() { - var normal = one3.clone().normalize(); - var a = new THREE.Plane().setFromNormalAndCoplanarPoint( normal, zero3 ); - - ok( a.normal.equals( normal ), "Passed!" ); - ok( a.constant == 0, "Passed!" ); - }); - - test( "normalize", function() { - var a = new THREE.Plane( new THREE.Vector3( 2, 0, 0 ), 2 ); - - a.normalize(); - ok( a.normal.length() == 1, "Passed!" ); - ok( a.normal.equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" ); - ok( a.constant == 1, "Passed!" ); - }); - - test( "negate/distanceToPoint", function() { - var a = new THREE.Plane( new THREE.Vector3( 2, 0, 0 ), -2 ); - - a.normalize(); - ok( a.distanceToPoint( new THREE.Vector3( 4, 0, 0 ) ) === 3, "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector3( 1, 0, 0 ) ) === 0, "Passed!" ); - - a.negate(); - ok( a.distanceToPoint( new THREE.Vector3( 4, 0, 0 ) ) === -3, "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector3( 1, 0, 0 ) ) === 0, "Passed!" ); - }); - - test( "distanceToPoint", function() { - var a = new THREE.Plane( new THREE.Vector3( 2, 0, 0 ), -2 ); - - a.normalize(); - ok( a.distanceToPoint( a.projectPoint( zero3.clone() ) ) === 0, "Passed!" ); - ok( a.distanceToPoint( new THREE.Vector3( 4, 0, 0 ) ) === 3, "Passed!" ); - }); - - test( "distanceToSphere", function() { - var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 ); - - var b = new THREE.Sphere( new THREE.Vector3( 2, 0, 0 ), 1 ); - - ok( a.distanceToSphere( b ) === 1, "Passed!" ); - - a.set( new THREE.Vector3( 1, 0, 0 ), 2 ); - ok( a.distanceToSphere( b ) === 3, "Passed!" ); - a.set( new THREE.Vector3( 1, 0, 0 ), -2 ); - ok( a.distanceToSphere( b ) === -1, "Passed!" ); - }); - - test( "isInterestionLine/intersectLine", function() { - var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 ); - - var l1 = new THREE.Line3( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ); - ok( a.isIntersectionLine( l1 ), "Passed!" ); - ok( a.intersectLine( l1 ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - - a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), -3 ); - - ok( a.isIntersectionLine( l1 ), "Passed!" ); - ok( a.intersectLine( l1 ).equals( new THREE.Vector3( 3, 0, 0 ) ), "Passed!" ); - - - a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), -11 ); - - ok( ! a.isIntersectionLine( l1 ), "Passed!" ); - ok( a.intersectLine( l1 ) === undefined, "Passed!" ); - - a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 11 ); - - ok( ! a.isIntersectionLine( l1 ), "Passed!" ); - ok( a.intersectLine( l1 ) === undefined, "Passed!" ); - - }); - - test( "projectPoint", function() { - var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 ); - - ok( a.projectPoint( new THREE.Vector3( 10, 0, 0 ) ).equals( zero3 ), "Passed!" ); - ok( a.projectPoint( new THREE.Vector3( -10, 0, 0 ) ).equals( zero3 ), "Passed!" ); - - a = new THREE.Plane( new THREE.Vector3( 0, 1, 0 ), -1 ); - ok( a.projectPoint( new THREE.Vector3( 0, 0, 0 ) ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" ); - ok( a.projectPoint( new THREE.Vector3( 0, 1, 0 ) ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" ); - - }); - - test( "orthoPoint", function() { - var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 ); - - ok( a.orthoPoint( new THREE.Vector3( 10, 0, 0 ) ).equals( new THREE.Vector3( 10, 0, 0 ) ), "Passed!" ); - ok( a.orthoPoint( new THREE.Vector3( -10, 0, 0 ) ).equals( new THREE.Vector3( -10, 0, 0 ) ), "Passed!" ); - }); - - test( "coplanarPoint", function() { - var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 ); - ok( a.distanceToPoint( a.coplanarPoint() ) === 0, "Passed!" ); - - a = new THREE.Plane( new THREE.Vector3( 0, 1, 0 ), -1 ); - ok( a.distanceToPoint( a.coplanarPoint() ) === 0, "Passed!" ); - }); - - test( "applyMatrix4/translate", function() { - - var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 ); - - var m = new THREE.Matrix4(); - m.makeRotationZ( Math.PI * 0.5 ); - - ok( comparePlane( a.clone().applyMatrix4( m ), new THREE.Plane( new THREE.Vector3( 0, 1, 0 ), 0 ) ), "Passed!" ); - - a = new THREE.Plane( new THREE.Vector3( 0, 1, 0 ), -1 ); - ok( comparePlane( a.clone().applyMatrix4( m ), new THREE.Plane( new THREE.Vector3( -1, 0, 0 ), -1 ) ), "Passed!" ); - - m.makeTranslation( 1, 1, 1 ); - ok( comparePlane( a.clone().applyMatrix4( m ), a.clone().translate( new THREE.Vector3( 1, 1, 1 ) ) ), "Passed!" ); - }); - - var orders = [ 'XYZ', 'YXZ', 'ZXY', 'ZYX', 'YZX', 'XZY' ]; - var eulerAngles = new THREE.Euler( 0.1, -0.3, 0.25 ); - - - - var qSub = function ( a, b ) { - var result = new THREE.Quaternion(); - result.copy( a ); - - result.x -= b.x; - result.y -= b.y; - result.z -= b.z; - result.w -= b.w; - - return result; - - }; - - test( "constructor", function() { - var a = new THREE.Quaternion(); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - ok( a.z == 0, "Passed!" ); - ok( a.w == 1, "Passed!" ); - - a = new THREE.Quaternion( x, y, z, w ); - ok( a.x === x, "Passed!" ); - ok( a.y === y, "Passed!" ); - ok( a.z === z, "Passed!" ); - ok( a.w === w, "Passed!" ); - }); - - test( "copy", function() { - var a = new THREE.Quaternion( x, y, z, w ); - var b = new THREE.Quaternion().copy( a ); - ok( b.x == x, "Passed!" ); - ok( b.y == y, "Passed!" ); - ok( b.z == z, "Passed!" ); - ok( b.w == w, "Passed!" ); - - // ensure that it is a true copy - a.x = 0; - a.y = -1; - a.z = 0; - a.w = -1; - ok( b.x == x, "Passed!" ); - ok( b.y == y, "Passed!" ); - }); - - test( "set", function() { - var a = new THREE.Quaternion(); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - ok( a.z == 0, "Passed!" ); - ok( a.w == 1, "Passed!" ); - - a.set( x, y, z, w ); - ok( a.x == x, "Passed!" ); - ok( a.y == y, "Passed!" ); - ok( a.z === z, "Passed!" ); - ok( a.w === w, "Passed!" ); - }); - - test( "setFromAxisAngle", function() { - - // TODO: find cases to validate. - ok( true, "Passed!" ); - - var zero = new THREE.Quaternion(); - - var a = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 1, 0, 0 ), 0 ); - ok( a.equals( zero ), "Passed!" ); - a = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), 0 ); - ok( a.equals( zero ), "Passed!" ); - a = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 0, 0, 1 ), 0 ); - ok( a.equals( zero ), "Passed!" ); - - var b1 = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 1, 0, 0 ), Math.PI ); - ok( ! a.equals( b1 ), "Passed!" ); - var b2 = new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 1, 0, 0 ), -Math.PI ); - ok( ! a.equals( b2 ), "Passed!" ); - - b1.multiply( b2 ); - ok( a.equals( b1 ), "Passed!" ); - }); - - - test( "setFromEuler/setFromQuaternion", function() { - - var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ]; - - // ensure euler conversion to/from Quaternion matches. - for( var i = 0; i < orders.length; i ++ ) { - for( var j = 0; j < angles.length; j ++ ) { - var eulers2 = new THREE.Euler().setFromQuaternion( - new THREE.Quaternion().setFromEuler(new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i])), - orders[i] - ); - var v = new THREE.Vector3().applyEuler(eulers2); - ok( v.distanceTo( angles[j] ) < 0.001, "Passed!" ); - } - } - - }); - - test( "setFromEuler/setFromRotationMatrix", function() { - - // ensure euler conversion for Quaternion matches that of Matrix4 - for( var i = 0; i < orders.length; i ++ ) { - var q = new THREE.Quaternion().setFromEuler( eulerAngles ); - var m = new THREE.Matrix4().makeRotationFromEuler( eulerAngles ); - var q2 = new THREE.Quaternion().setFromRotationMatrix( m ); - - ok( qSub( q, q2 ).length() < 0.001, "Passed!" ); - } - - }); - - test( "normalize/length/lengthSq", function() { - var a = new THREE.Quaternion( x, y, z, w ); - var b = new THREE.Quaternion( -x, -y, -z, -w ); - - ok( a.length() != 1, "Passed!"); - ok( a.lengthSq() != 1, "Passed!"); - a.normalize(); - ok( a.length() == 1, "Passed!"); - ok( a.lengthSq() == 1, "Passed!"); - - a.set( 0, 0, 0, 0 ); - ok( a.lengthSq() == 0, "Passed!"); - ok( a.length() == 0, "Passed!"); - a.normalize(); - ok( a.lengthSq() == 1, "Passed!"); - ok( a.length() == 1, "Passed!"); - }); - - test( "inverse/conjugate", function() { - var a = new THREE.Quaternion( x, y, z, w ); - - // TODO: add better validation here. - - var b = a.clone().conjugate(); - - ok( a.x == -b.x, "Passed!" ); - ok( a.y == -b.y, "Passed!" ); - ok( a.z == -b.z, "Passed!" ); - ok( a.w == b.w, "Passed!" ); - }); - - - test( "multiplyQuaternions/multiply", function() { - - var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ]; - - var q1 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[0].x, angles[0].y, angles[0].z) ); - var q2 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[1].x, angles[1].y, angles[1].z) ); - var q3 = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[2].x, angles[2].y, angles[2].z) ); - - var q = new THREE.Quaternion().multiplyQuaternions( q1, q2 ).multiply( q3 ); - - var m1 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[0].x, angles[0].y, angles[0].z) ); - var m2 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[1].x, angles[1].y, angles[1].z) ); - var m3 = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[2].x, angles[2].y, angles[2].z) ); - - var m = new THREE.Matrix4().multiplyMatrices( m1, m2 ).multiply( m3 ); - - var qFromM = new THREE.Quaternion().setFromRotationMatrix( m ); - - ok( qSub( q, qFromM ).length() < 0.001, "Passed!" ); - }); - - test( "multiplyVector3", function() { - - var angles = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ]; - - // ensure euler conversion for Quaternion matches that of Matrix4 - for( var i = 0; i < orders.length; i ++ ) { - for( var j = 0; j < angles.length; j ++ ) { - var q = new THREE.Quaternion().setFromEuler( new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i]) ); - var m = new THREE.Matrix4().makeRotationFromEuler( new THREE.Euler(angles[j].x, angles[j].y, angles[j].z, orders[i]) ); - - var v0 = new THREE.Vector3(1, 0, 0); - var qv = v0.clone().applyQuaternion( q ); - var mv = v0.clone().applyMatrix4( m ); - - ok( qv.distanceTo( mv ) < 0.001, "Passed!" ); - } - } - - }); - - test( "equals", function() { - var a = new THREE.Quaternion( x, y, z, w ); - var b = new THREE.Quaternion( -x, -y, -z, -w ); - - ok( a.x != b.x, "Passed!" ); - ok( a.y != b.y, "Passed!" ); - - ok( ! a.equals( b ), "Passed!" ); - ok( ! b.equals( a ), "Passed!" ); - - a.copy( b ); - ok( a.x == b.x, "Passed!" ); - ok( a.y == b.y, "Passed!" ); - - ok( a.equals( b ), "Passed!" ); - ok( b.equals( a ), "Passed!" ); - }); - - - test( "constructor/equals", function() { - var a = new THREE.Ray(); - ok( a.origin.equals( zero3 ), "Passed!" ); - ok( a.direction.equals( zero3 ), "Passed!" ); - - a = new THREE.Ray( two3.clone(), one3.clone() ); - ok( a.origin.equals( two3 ), "Passed!" ); - ok( a.direction.equals( one3 ), "Passed!" ); - }); - - test( "copy/equals", function() { - var a = new THREE.Ray( zero3.clone(), one3.clone() ); - var b = new THREE.Ray().copy( a ); - ok( b.origin.equals( zero3 ), "Passed!" ); - ok( b.direction.equals( one3 ), "Passed!" ); - - // ensure that it is a true copy - a.origin = zero3; - a.direction = one3; - ok( b.origin.equals( zero3 ), "Passed!" ); - ok( b.direction.equals( one3 ), "Passed!" ); - }); - - test( "set", function() { - var a = new THREE.Ray(); - - a.set( one3, one3 ); - ok( a.origin.equals( one3 ), "Passed!" ); - ok( a.direction.equals( one3 ), "Passed!" ); - }); - - test( "at", function() { - var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - - ok( a.at( 0 ).equals( one3 ), "Passed!" ); - ok( a.at( -1 ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); - ok( a.at( 1 ).equals( new THREE.Vector3( 1, 1, 2 ) ), "Passed!" ); - }); - - test( "recast/clone", function() { - var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - - ok( a.recast( 0 ).equals( a ), "Passed!" ); - - var b = a.clone(); - ok( b.recast( -1 ).equals( new THREE.Ray( new THREE.Vector3( 1, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ) ), "Passed!" ); - - var c = a.clone(); - ok( c.recast( 1 ).equals( new THREE.Ray( new THREE.Vector3( 1, 1, 2 ), new THREE.Vector3( 0, 0, 1 ) ) ), "Passed!" ); - - var d = a.clone(); - var e = d.clone().recast( 1 ); - ok( d.equals( a ), "Passed!" ); - ok( ! e.equals( d ), "Passed!" ); - ok( e.equals( c ), "Passed!" ); - }); - - test( "closestPointToPoint", function() { - var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - - // nearby the ray - var b = a.closestPointToPoint( zero3 ); - ok( b.equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); - - // exactly on the ray - var c = a.closestPointToPoint( one3 ); - ok( c.equals( one3 ), "Passed!" ); - }); - - test( "distanceToPoint", function() { - var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - - // nearby the ray - var b = a.distanceToPoint( zero3 ); - ok( b == Math.sqrt( 2 ), "Passed!" ); - - // exactly on the ray - var c = a.distanceToPoint( one3 ); - ok( c == 0, "Passed!" ); - }); - - test( "isIntersectionSphere", function() { - var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - var b = new THREE.Sphere( zero3, 0.5 ); - var c = new THREE.Sphere( zero3, 1.5 ); - var d = new THREE.Sphere( one3, 0.1 ); - var e = new THREE.Sphere( two3, 0.1 ); - var f = new THREE.Sphere( two3, 1 ); - - ok( ! a.isIntersectionSphere( b ), "Passed!" ); - ok( a.isIntersectionSphere( c ), "Passed!" ); - ok( a.isIntersectionSphere( d ), "Passed!" ); - ok( ! a.isIntersectionSphere( e ), "Passed!" ); - ok( ! a.isIntersectionSphere( f ), "Passed!" ); - }); - - test( "isIntersectionPlane", function() { - var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - - // parallel plane behind - var b = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, -1 ) ) ); - ok( a.isIntersectionPlane( b ), "Passed!" ); - - // parallel plane coincident with origin - var c = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, 0 ) ) ); - ok( a.isIntersectionPlane( c ), "Passed!" ); - - // parallel plane infront - var d = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, 1 ) ) ); - ok( a.isIntersectionPlane( d ), "Passed!" ); - - // perpendical ray that overlaps exactly - var e = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), one3 ); - ok( a.isIntersectionPlane( e ), "Passed!" ); - - // perpendical ray that doesn't overlap - var f = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), zero3 ); - ok( ! a.isIntersectionPlane( f ), "Passed!" ); - }); - - test( "intersectPlane", function() { - var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - - // parallel plane behind - var b = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 1, 1, -1 ) ); - ok( a.intersectPlane( b ).equals( new THREE.Vector3( 1, 1, -1 ) ), "Passed!" ); - - // parallel plane coincident with origin - var c = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 1, 1, 0 ) ); - ok( a.intersectPlane( c ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); - - // parallel plane infront - var d = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 1, 1, 1 ) ); - ok( a.intersectPlane( d ).equals( new THREE.Vector3( 1, 1, 1 ) ), "Passed!" ); - - // perpendical ray that overlaps exactly - var e = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), one3 ); - ok( a.intersectPlane( e ).equals( a.origin ), "Passed!" ); - - // perpendical ray that doesn't overlap - var f = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), zero3 ); - ok( a.intersectPlane( f ) === undefined, "Passed!" ); - }); - - - test( "applyMatrix4", function() { - var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - var m = new THREE.Matrix4().identity(); - - ok( a.clone().applyMatrix4( m ).equals( a ), "Passed!" ); - - a = new THREE.Ray( zero3.clone(), new THREE.Vector3( 0, 0, 1 ) ); - m.makeRotationAxis( new THREE.Vector3( 0, 0, 1 ), Math.PI ); - ok( a.clone().applyMatrix4( m ).equals( a ), "Passed!" ); - - m.identity().makeRotationX( Math.PI ); - var b = a.clone(); - b.direction.negate(); - var a2 = a.clone().applyMatrix4( m ); - ok( a2.origin.distanceTo( b.origin ) < 0.0001, "Passed!" ); - ok( a2.direction.distanceTo( b.direction ) < 0.0001, "Passed!" ); - - a.origin = new THREE.Vector3( 0, 0, 1 ); - b.origin = new THREE.Vector3( 0, 0, -1 ); - var a2 = a.clone().applyMatrix4( m ); - ok( a2.origin.distanceTo( b.origin ) < 0.0001, "Passed!" ); - ok( a2.direction.distanceTo( b.direction ) < 0.0001, "Passed!" ); - }); - - - test( "constructor", function() { - var a = new THREE.Sphere(); - ok( a.center.equals( zero3 ), "Passed!" ); - ok( a.radius == 0, "Passed!" ); - - a = new THREE.Sphere( one3.clone(), 1 ); - ok( a.center.equals( one3 ), "Passed!" ); - ok( a.radius == 1, "Passed!" ); - }); - - test( "copy", function() { - var a = new THREE.Sphere( one3.clone(), 1 ); - var b = new THREE.Sphere().copy( a ); - - ok( b.center.equals( one3 ), "Passed!" ); - ok( b.radius == 1, "Passed!" ); - - // ensure that it is a true copy - a.center = zero3; - a.radius = 0; - ok( b.center.equals( one3 ), "Passed!" ); - ok( b.radius == 1, "Passed!" ); - }); - - test( "set", function() { - var a = new THREE.Sphere(); - ok( a.center.equals( zero3 ), "Passed!" ); - ok( a.radius == 0, "Passed!" ); - - a.set( one3, 1 ); - ok( a.center.equals( one3 ), "Passed!" ); - ok( a.radius == 1, "Passed!" ); - }); - - test( "empty", function() { - var a = new THREE.Sphere(); - ok( a.empty(), "Passed!" ); - - a.set( one3, 1 ); - ok( ! a.empty(), "Passed!" ); - }); - - test( "containsPoint", function() { - var a = new THREE.Sphere( one3.clone(), 1 ); - - ok( ! a.containsPoint( zero3 ), "Passed!" ); - ok( a.containsPoint( one3 ), "Passed!" ); - }); - - test( "distanceToPoint", function() { - var a = new THREE.Sphere( one3.clone(), 1 ); - - ok( ( a.distanceToPoint( zero3 ) - 0.7320 ) < 0.001, "Passed!" ); - ok( a.distanceToPoint( one3 ) === -1, "Passed!" ); - }); - - test( "intersectsSphere", function() { - var a = new THREE.Sphere( one3.clone(), 1 ); - var b = new THREE.Sphere( zero3.clone(), 1 ); - var c = new THREE.Sphere( zero3.clone(), 0.25 ); - - ok( a.intersectsSphere( b ) , "Passed!" ); - ok( ! a.intersectsSphere( c ) , "Passed!" ); - }); - - test( "clampPoint", function() { - var a = new THREE.Sphere( one3.clone(), 1 ); - - ok( a.clampPoint( new THREE.Vector3( 1, 1, 3 ) ).equals( new THREE.Vector3( 1, 1, 2 ) ), "Passed!" ); - ok( a.clampPoint( new THREE.Vector3( 1, 1, -3 ) ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); - }); - - test( "getBoundingBox", function() { - var a = new THREE.Sphere( one3.clone(), 1 ); - - ok( a.getBoundingBox().equals( new THREE.Box3( zero3, two3 ) ), "Passed!" ); - - a.set( zero3, 0 ) - ok( a.getBoundingBox().equals( new THREE.Box3( zero3, zero3 ) ), "Passed!" ); - }); - - test( "applyMatrix4", function() { - var a = new THREE.Sphere( one3.clone(), 1 ); - - var m = new THREE.Matrix4().makeTranslation( 1, -2, 1 ); - - ok( a.clone().applyMatrix4( m ).getBoundingBox().equals( a.getBoundingBox().applyMatrix4( m ) ), "Passed!" ); - }); - - test( "translate", function() { - var a = new THREE.Sphere( one3.clone(), 1 ); - - a.translate( one3.clone().negate() ); - ok( a.center.equals( zero3 ), "Passed!" ); - }); - - test( "constructor", function() { - var a = new THREE.Triangle(); - ok( a.a.equals( zero3 ), "Passed!" ); - ok( a.b.equals( zero3 ), "Passed!" ); - ok( a.c.equals( zero3 ), "Passed!" ); - - a = new THREE.Triangle( one3.clone().negate(), one3.clone(), two3.clone() ); - ok( a.a.equals( one3.clone().negate() ), "Passed!" ); - ok( a.b.equals( one3 ), "Passed!" ); - ok( a.c.equals( two3 ), "Passed!" ); - }); - - test( "copy", function() { - var a = new THREE.Triangle( one3.clone().negate(), one3.clone(), two3.clone() ); - var b = new THREE.Triangle().copy( a ); - ok( b.a.equals( one3.clone().negate() ), "Passed!" ); - ok( b.b.equals( one3 ), "Passed!" ); - ok( b.c.equals( two3 ), "Passed!" ); - - // ensure that it is a true copy - a.a = one3; - a.b = zero3; - a.c = zero3; - ok( b.a.equals( one3.clone().negate() ), "Passed!" ); - ok( b.b.equals( one3 ), "Passed!" ); - ok( b.c.equals( two3 ), "Passed!" ); - }); - - test( "setFromPointsAndIndices", function() { - var a = new THREE.Triangle(); - - var points = [ one3, one3.clone().negate(), two3 ]; - a.setFromPointsAndIndices( points, 1, 0, 2 ); - ok( a.a.equals( one3.clone().negate() ), "Passed!" ); - ok( a.b.equals( one3 ), "Passed!" ); - ok( a.c.equals( two3 ), "Passed!" ); - - }); - - test( "set", function() { - var a = new THREE.Triangle(); - - a.set( one3.clone().negate(), one3, two3 ); - ok( a.a.equals( one3.clone().negate() ), "Passed!" ); - ok( a.b.equals( one3 ), "Passed!" ); - ok( a.c.equals( two3 ), "Passed!" ); - - }); - - test( "area", function() { - var a = new THREE.Triangle(); - - ok( a.area() == 0, "Passed!" ); - - a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); - ok( a.area() == 0.5, "Passed!" ); - - a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) ); - ok( a.area() == 2, "Passed!" ); - - // colinear triangle. - a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 3, 0, 0 ) ); - ok( a.area() == 0, "Passed!" ); - }); - - test( "midpoint", function() { - var a = new THREE.Triangle(); - - ok( a.midpoint().equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - - a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); - ok( a.midpoint().equals( new THREE.Vector3( 1/3, 1/3, 0 ) ), "Passed!" ); - - a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) ); - ok( a.midpoint().equals( new THREE.Vector3( 2/3, 0, 2/3 ) ), "Passed!" ); - }); - - test( "normal", function() { - var a = new THREE.Triangle(); - - ok( a.normal().equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - - a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); - ok( a.normal().equals( new THREE.Vector3( 0, 0, 1 ) ), "Passed!" ); - - a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) ); - ok( a.normal().equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" ); - }); - - test( "plane", function() { - var a = new THREE.Triangle(); - - // artificial normal is created in this case. - ok( a.plane().distanceToPoint( a.a ) == 0, "Passed!" ); - ok( a.plane().distanceToPoint( a.b ) == 0, "Passed!" ); - ok( a.plane().distanceToPoint( a.c ) == 0, "Passed!" ); - ok( a.plane().normal.equals( a.normal() ), "Passed!" ); - - a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); - ok( a.plane().distanceToPoint( a.a ) == 0, "Passed!" ); - ok( a.plane().distanceToPoint( a.b ) == 0, "Passed!" ); - ok( a.plane().distanceToPoint( a.c ) == 0, "Passed!" ); - ok( a.plane().normal.equals( a.normal() ), "Passed!" ); - - a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) ); - ok( a.plane().distanceToPoint( a.a ) == 0, "Passed!" ); - ok( a.plane().distanceToPoint( a.b ) == 0, "Passed!" ); - ok( a.plane().distanceToPoint( a.c ) == 0, "Passed!" ); - ok( a.plane().normal.clone().normalize().equals( a.normal() ), "Passed!" ); - }); - - test( "barycoordFromPoint", function() { - var a = new THREE.Triangle(); - - var bad = new THREE.Vector3( -2, -1, -1 ); - - ok( a.barycoordFromPoint( a.a ).equals( bad ), "Passed!" ); - ok( a.barycoordFromPoint( a.b ).equals( bad ), "Passed!" ); - ok( a.barycoordFromPoint( a.c ).equals( bad ), "Passed!" ); - - a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); - ok( a.barycoordFromPoint( a.a ).equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" ); - ok( a.barycoordFromPoint( a.b ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" ); - ok( a.barycoordFromPoint( a.c ).equals( new THREE.Vector3( 0, 0, 1 ) ), "Passed!" ); - ok( a.barycoordFromPoint( a.midpoint() ).distanceTo( new THREE.Vector3( 1/3, 1/3, 1/3 ) ) < 0.0001, "Passed!" ); - - a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) ); - ok( a.barycoordFromPoint( a.a ).equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" ); - ok( a.barycoordFromPoint( a.b ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" ); - ok( a.barycoordFromPoint( a.c ).equals( new THREE.Vector3( 0, 0, 1 ) ), "Passed!" ); - ok( a.barycoordFromPoint( a.midpoint() ).distanceTo( new THREE.Vector3( 1/3, 1/3, 1/3 ) ) < 0.0001, "Passed!" ); - }); - - test( "containsPoint", function() { - var a = new THREE.Triangle(); - - ok( ! a.containsPoint( a.a ), "Passed!" ); - ok( ! a.containsPoint( a.b ), "Passed!" ); - ok( ! a.containsPoint( a.c ), "Passed!" ); - - a = new THREE.Triangle( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) ); - ok( a.containsPoint( a.a ), "Passed!" ); - ok( a.containsPoint( a.b ), "Passed!" ); - ok( a.containsPoint( a.c ), "Passed!" ); - ok( a.containsPoint( a.midpoint() ), "Passed!" ); - ok( ! a.containsPoint( new THREE.Vector3( -1, -1, -1 ) ), "Passed!" ); - - a = new THREE.Triangle( new THREE.Vector3( 2, 0, 0 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 2 ) ); - ok( a.containsPoint( a.a ), "Passed!" ); - ok( a.containsPoint( a.b ), "Passed!" ); - ok( a.containsPoint( a.c ), "Passed!" ); - ok( a.containsPoint( a.midpoint() ), "Passed!" ); - ok( ! a.containsPoint( new THREE.Vector3( -1, -1, -1 ) ), "Passed!" ); - }); - - - test( "constructor", function() { - var a = new THREE.Vector2(); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - - a = new THREE.Vector2( x, y ); - ok( a.x === x, "Passed!" ); - ok( a.y === y, "Passed!" ); - }); - - test( "copy", function() { - var a = new THREE.Vector2( x, y ); - var b = new THREE.Vector2().copy( a ); - ok( b.x == x, "Passed!" ); - ok( b.y == y, "Passed!" ); - - // ensure that it is a true copy - a.x = 0; - a.y = -1; - ok( b.x == x, "Passed!" ); - ok( b.y == y, "Passed!" ); - }); - - test( "set", function() { - var a = new THREE.Vector2(); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - - a.set( x, y ); - ok( a.x == x, "Passed!" ); - ok( a.y == y, "Passed!" ); - }); - - test( "setX,setY", function() { - var a = new THREE.Vector2(); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - - a.setX( x ); - a.setY( y ); - ok( a.x == x, "Passed!" ); - ok( a.y == y, "Passed!" ); - }); - - test( "setComponent,getComponent", function() { - var a = new THREE.Vector2(); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - - a.setComponent( 0, 1 ); - a.setComponent( 1, 2 ); - ok( a.getComponent( 0 ) == 1, "Passed!" ); - ok( a.getComponent( 1 ) == 2, "Passed!" ); - }); - - test( "add", function() { - var a = new THREE.Vector2( x, y ); - var b = new THREE.Vector2( -x, -y ); - - a.add( b ); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - - var c = new THREE.Vector2().addVectors( b, b ); - ok( c.x == -2*x, "Passed!" ); - ok( c.y == -2*y, "Passed!" ); - }); - - test( "sub", function() { - var a = new THREE.Vector2( x, y ); - var b = new THREE.Vector2( -x, -y ); - - a.sub( b ); - ok( a.x == 2*x, "Passed!" ); - ok( a.y == 2*y, "Passed!" ); - - var c = new THREE.Vector2().subVectors( a, a ); - ok( c.x == 0, "Passed!" ); - ok( c.y == 0, "Passed!" ); - }); - - test( "multiply/divide", function() { - var a = new THREE.Vector2( x, y ); - var b = new THREE.Vector2( -x, -y ); - - a.multiplyScalar( -2 ); - ok( a.x == x*-2, "Passed!" ); - ok( a.y == y*-2, "Passed!" ); - - b.multiplyScalar( -2 ); - ok( b.x == 2*x, "Passed!" ); - ok( b.y == 2*y, "Passed!" ); - - a.divideScalar( -2 ); - ok( a.x == x, "Passed!" ); - ok( a.y == y, "Passed!" ); - - b.divideScalar( -2 ); - ok( b.x == -x, "Passed!" ); - ok( b.y == -y, "Passed!" ); - }); - - - test( "min/max/clamp", function() { - var a = new THREE.Vector2( x, y ); - var b = new THREE.Vector2( -x, -y ); - var c = new THREE.Vector2(); - - c.copy( a ).min( b ); - ok( c.x == -x, "Passed!" ); - ok( c.y == -y, "Passed!" ); - - c.copy( a ).max( b ); - ok( c.x == x, "Passed!" ); - ok( c.y == y, "Passed!" ); - - c.set( -2*x, 2*y ); - c.clamp( b, a ); - ok( c.x == -x, "Passed!" ); - ok( c.y == y, "Passed!" ); - }); - - test( "negate", function() { - var a = new THREE.Vector2( x, y ); - - a.negate(); - ok( a.x == -x, "Passed!" ); - ok( a.y == -y, "Passed!" ); - }); - - test( "dot", function() { - var a = new THREE.Vector2( x, y ); - var b = new THREE.Vector2( -x, -y ); - var c = new THREE.Vector2(); - - var result = a.dot( b ); - ok( result == (-x*x-y*y), "Passed!" ); - - result = a.dot( c ); - ok( result == 0, "Passed!" ); - }); - - test( "length/lengthSq", function() { - var a = new THREE.Vector2( x, 0 ); - var b = new THREE.Vector2( 0, -y ); - var c = new THREE.Vector2(); - - ok( a.length() == x, "Passed!" ); - ok( a.lengthSq() == x*x, "Passed!" ); - ok( b.length() == y, "Passed!" ); - ok( b.lengthSq() == y*y, "Passed!" ); - ok( c.length() == 0, "Passed!" ); - ok( c.lengthSq() == 0, "Passed!" ); - - a.set( x, y ); - ok( a.length() == Math.sqrt( x*x + y*y ), "Passed!" ); - ok( a.lengthSq() == ( x*x + y*y ), "Passed!" ); - }); - - test( "normalize", function() { - var a = new THREE.Vector2( x, 0 ); - var b = new THREE.Vector2( 0, -y ); - var c = new THREE.Vector2(); - - a.normalize(); - ok( a.length() == 1, "Passed!" ); - ok( a.x == 1, "Passed!" ); - - b.normalize(); - ok( b.length() == 1, "Passed!" ); - ok( b.y == -1, "Passed!" ); - }); - - test( "distanceTo/distanceToSquared", function() { - var a = new THREE.Vector2( x, 0 ); - var b = new THREE.Vector2( 0, -y ); - var c = new THREE.Vector2(); - - ok( a.distanceTo( c ) == x, "Passed!" ); - ok( a.distanceToSquared( c ) == x*x, "Passed!" ); - - ok( b.distanceTo( c ) == y, "Passed!" ); - ok( b.distanceToSquared( c ) == y*y, "Passed!" ); - }); - - test( "setLength", function() { - var a = new THREE.Vector2( x, 0 ); - - ok( a.length() == x, "Passed!" ); - a.setLength( y ); - ok( a.length() == y, "Passed!" ); - - a = new THREE.Vector2( 0, 0 ); - ok( a.length() == 0, "Passed!" ); - a.setLength( y ); - ok( a.length() == 0, "Passed!" ); - }); - - test( "lerp/clone", function() { - var a = new THREE.Vector2( x, 0 ); - var b = new THREE.Vector2( 0, -y ); - - ok( a.lerp( a, 0 ).equals( a.lerp( a, 0.5 ) ), "Passed!" ); - ok( a.lerp( a, 0 ).equals( a.lerp( a, 1 ) ), "Passed!" ); - - ok( a.clone().lerp( b, 0 ).equals( a ), "Passed!" ); - - ok( a.clone().lerp( b, 0.5 ).x == x*0.5, "Passed!" ); - ok( a.clone().lerp( b, 0.5 ).y == -y*0.5, "Passed!" ); - - ok( a.clone().lerp( b, 1 ).equals( b ), "Passed!" ); - }); - - test( "equals", function() { - var a = new THREE.Vector2( x, 0 ); - var b = new THREE.Vector2( 0, -y ); - - ok( a.x != b.x, "Passed!" ); - ok( a.y != b.y, "Passed!" ); - - ok( ! a.equals( b ), "Passed!" ); - ok( ! b.equals( a ), "Passed!" ); - - a.copy( b ); - ok( a.x == b.x, "Passed!" ); - ok( a.y == b.y, "Passed!" ); - - ok( a.equals( b ), "Passed!" ); - ok( b.equals( a ), "Passed!" ); - }); - - - test( "constructor", function() { - var a = new THREE.Vector3(); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - ok( a.z == 0, "Passed!" ); - - a = new THREE.Vector3( x, y, z ); - ok( a.x === x, "Passed!" ); - ok( a.y === y, "Passed!" ); - ok( a.z === z, "Passed!" ); - }); - - test( "copy", function() { - var a = new THREE.Vector3( x, y, z ); - var b = new THREE.Vector3().copy( a ); - ok( b.x == x, "Passed!" ); - ok( b.y == y, "Passed!" ); - ok( b.z == z, "Passed!" ); - - // ensure that it is a true copy - a.x = 0; - a.y = -1; - a.z = -2; - ok( b.x == x, "Passed!" ); - ok( b.y == y, "Passed!" ); - ok( b.z == z, "Passed!" ); - }); - - test( "set", function() { - var a = new THREE.Vector3(); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - ok( a.z == 0, "Passed!" ); - - a.set( x, y, z ); - ok( a.x == x, "Passed!" ); - ok( a.y == y, "Passed!" ); - ok( a.z == z, "Passed!" ); - }); - - test( "setX,setY,setZ", function() { - var a = new THREE.Vector3(); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - ok( a.z == 0, "Passed!" ); - - a.setX( x ); - a.setY( y ); - a.setZ( z ); - - ok( a.x == x, "Passed!" ); - ok( a.y == y, "Passed!" ); - ok( a.z == z, "Passed!" ); - }); - - test( "setComponent,getComponent", function() { - var a = new THREE.Vector3(); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - ok( a.z == 0, "Passed!" ); - - a.setComponent( 0, 1 ); - a.setComponent( 1, 2 ); - a.setComponent( 2, 3 ); - ok( a.getComponent( 0 ) == 1, "Passed!" ); - ok( a.getComponent( 1 ) == 2, "Passed!" ); - ok( a.getComponent( 2 ) == 3, "Passed!" ); - }); - - test( "add", function() { - var a = new THREE.Vector3( x, y, z ); - var b = new THREE.Vector3( -x, -y, -z ); - - a.add( b ); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - ok( a.z == 0, "Passed!" ); - - var c = new THREE.Vector3().addVectors( b, b ); - ok( c.x == -2*x, "Passed!" ); - ok( c.y == -2*y, "Passed!" ); - ok( c.z == -2*z, "Passed!" ); - }); - - test( "sub", function() { - var a = new THREE.Vector3( x, y, z ); - var b = new THREE.Vector3( -x, -y, -z ); - - a.sub( b ); - ok( a.x == 2*x, "Passed!" ); - ok( a.y == 2*y, "Passed!" ); - ok( a.z == 2*z, "Passed!" ); - - var c = new THREE.Vector3().subVectors( a, a ); - ok( c.x == 0, "Passed!" ); - ok( c.y == 0, "Passed!" ); - ok( c.z == 0, "Passed!" ); - }); - - test( "multiply/divide", function() { - var a = new THREE.Vector3( x, y, z ); - var b = new THREE.Vector3( -x, -y, -z ); - - a.multiplyScalar( -2 ); - ok( a.x == x*-2, "Passed!" ); - ok( a.y == y*-2, "Passed!" ); - ok( a.z == z*-2, "Passed!" ); - - b.multiplyScalar( -2 ); - ok( b.x == 2*x, "Passed!" ); - ok( b.y == 2*y, "Passed!" ); - ok( b.z == 2*z, "Passed!" ); - - a.divideScalar( -2 ); - ok( a.x == x, "Passed!" ); - ok( a.y == y, "Passed!" ); - ok( a.z == z, "Passed!" ); - - b.divideScalar( -2 ); - ok( b.x == -x, "Passed!" ); - ok( b.y == -y, "Passed!" ); - ok( b.z == -z, "Passed!" ); - }); - - test( "min/max/clamp", function() { - var a = new THREE.Vector3( x, y, z ); - var b = new THREE.Vector3( -x, -y, -z ); - var c = new THREE.Vector3(); - - c.copy( a ).min( b ); - ok( c.x == -x, "Passed!" ); - ok( c.y == -y, "Passed!" ); - ok( c.z == -z, "Passed!" ); - - c.copy( a ).max( b ); - ok( c.x == x, "Passed!" ); - ok( c.y == y, "Passed!" ); - ok( c.z == z, "Passed!" ); - - c.set( -2*x, 2*y, -2*z ); - c.clamp( b, a ); - ok( c.x == -x, "Passed!" ); - ok( c.y == y, "Passed!" ); - ok( c.z == -z, "Passed!" ); - }); - - test( "negate", function() { - var a = new THREE.Vector3( x, y, z ); - - a.negate(); - ok( a.x == -x, "Passed!" ); - ok( a.y == -y, "Passed!" ); - ok( a.z == -z, "Passed!" ); - }); - - test( "dot", function() { - var a = new THREE.Vector3( x, y, z ); - var b = new THREE.Vector3( -x, -y, -z ); - var c = new THREE.Vector3(); - - var result = a.dot( b ); - ok( result == (-x*x-y*y-z*z), "Passed!" ); - - result = a.dot( c ); - ok( result == 0, "Passed!" ); - }); - - test( "length/lengthSq", function() { - var a = new THREE.Vector3( x, 0, 0 ); - var b = new THREE.Vector3( 0, -y, 0 ); - var c = new THREE.Vector3( 0, 0, z ); - var d = new THREE.Vector3(); - - ok( a.length() == x, "Passed!" ); - ok( a.lengthSq() == x*x, "Passed!" ); - ok( b.length() == y, "Passed!" ); - ok( b.lengthSq() == y*y, "Passed!" ); - ok( c.length() == z, "Passed!" ); - ok( c.lengthSq() == z*z, "Passed!" ); - ok( d.length() == 0, "Passed!" ); - ok( d.lengthSq() == 0, "Passed!" ); - - a.set( x, y, z ); - ok( a.length() == Math.sqrt( x*x + y*y + z*z ), "Passed!" ); - ok( a.lengthSq() == ( x*x + y*y + z*z ), "Passed!" ); - }); - - test( "normalize", function() { - var a = new THREE.Vector3( x, 0, 0 ); - var b = new THREE.Vector3( 0, -y, 0 ); - var c = new THREE.Vector3( 0, 0, z ); - - a.normalize(); - ok( a.length() == 1, "Passed!" ); - ok( a.x == 1, "Passed!" ); - - b.normalize(); - ok( b.length() == 1, "Passed!" ); - ok( b.y == -1, "Passed!" ); - - c.normalize(); - ok( c.length() == 1, "Passed!" ); - ok( c.z == 1, "Passed!" ); - }); - - test( "distanceTo/distanceToSquared", function() { - var a = new THREE.Vector3( x, 0, 0 ); - var b = new THREE.Vector3( 0, -y, 0 ); - var c = new THREE.Vector3( 0, 0, z ); - var d = new THREE.Vector3(); - - ok( a.distanceTo( d ) == x, "Passed!" ); - ok( a.distanceToSquared( d ) == x*x, "Passed!" ); - - ok( b.distanceTo( d ) == y, "Passed!" ); - ok( b.distanceToSquared( d ) == y*y, "Passed!" ); - - ok( c.distanceTo( d ) == z, "Passed!" ); - ok( c.distanceToSquared( d ) == z*z, "Passed!" ); - }); - - test( "setLength", function() { - var a = new THREE.Vector3( x, 0, 0 ); - - ok( a.length() == x, "Passed!" ); - a.setLength( y ); - ok( a.length() == y, "Passed!" ); - - a = new THREE.Vector3( 0, 0, 0 ); - ok( a.length() == 0, "Passed!" ); - a.setLength( y ); - ok( a.length() == 0, "Passed!" ); - - }); - - test( "projectOnVector", function() { - var a = new THREE.Vector3( 1, 0, 0 ); - var b = new THREE.Vector3(); - var normal = new THREE.Vector3( 10, 0, 0 ); - - ok( b.copy( a ).projectOnVector( normal ).equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" ); - - a.set( 0, 1, 0 ); - ok( b.copy( a ).projectOnVector( normal ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - - a.set( 0, 0, -1 ); - ok( b.copy( a ).projectOnVector( normal ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - - a.set( -1, 0, 0 ); - ok( b.copy( a ).projectOnVector( normal ).equals( new THREE.Vector3( -1, 0, 0 ) ), "Passed!" ); - - }); - - test( "projectOnPlane", function() { - var a = new THREE.Vector3( 1, 0, 0 ); - var b = new THREE.Vector3(); - var normal = new THREE.Vector3( 1, 0, 0 ); - - ok( b.copy( a ).projectOnPlane( normal ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - - a.set( 0, 1, 0 ); - ok( b.copy( a ).projectOnPlane( normal ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" ); - - a.set( 0, 0, -1 ); - ok( b.copy( a ).projectOnPlane( normal ).equals( new THREE.Vector3( 0, 0, -1 ) ), "Passed!" ); - - a.set( -1, 0, 0 ); - ok( b.copy( a ).projectOnPlane( normal ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); - - }); - - test( "reflect", function() { - var a = new THREE.Vector3( 1, 0, 0 ); - var normal = new THREE.Vector3( 1, 0, 0 ); - var b = new THREE.Vector3( 0, 0, 0 ); - - ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" ); - - a.set( 1, -1, 0 ); - ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" ); - - a.set( 1, -1, 0 ); - normal.set( 0, -1, 0 ); - ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( -1, -1, 0 ) ), "Passed!" ); - }); - - test( "angleTo", function() { - var a = new THREE.Vector3( 0, -0.18851655680720186, 0.9820700116639124 ); - var b = new THREE.Vector3( 0, 0.18851655680720186, -0.9820700116639124 ); - - equal( a.angleTo( a ), 0 ); - equal( a.angleTo( b ), Math.PI ); - - var x = new THREE.Vector3( 1, 0, 0 ); - var y = new THREE.Vector3( 0, 1, 0 ); - var z = new THREE.Vector3( 0, 0, 1 ); - - equal( x.angleTo( y ), Math.PI / 2 ); - equal( x.angleTo( z ), Math.PI / 2 ); - equal( z.angleTo( x ), Math.PI / 2 ); - - ok( Math.abs( x.angleTo( new THREE.Vector3( 1, 1, 0 ) ) - ( Math.PI / 4 ) ) < 0.0000001 ); - }); - - test( "lerp/clone", function() { - var a = new THREE.Vector3( x, 0, z ); - var b = new THREE.Vector3( 0, -y, 0 ); - - ok( a.lerp( a, 0 ).equals( a.lerp( a, 0.5 ) ), "Passed!" ); - ok( a.lerp( a, 0 ).equals( a.lerp( a, 1 ) ), "Passed!" ); - - ok( a.clone().lerp( b, 0 ).equals( a ), "Passed!" ); - - ok( a.clone().lerp( b, 0.5 ).x == x*0.5, "Passed!" ); - ok( a.clone().lerp( b, 0.5 ).y == -y*0.5, "Passed!" ); - ok( a.clone().lerp( b, 0.5 ).z == z*0.5, "Passed!" ); - - ok( a.clone().lerp( b, 1 ).equals( b ), "Passed!" ); - }); - - test( "equals", function() { - var a = new THREE.Vector3( x, 0, z ); - var b = new THREE.Vector3( 0, -y, 0 ); - - ok( a.x != b.x, "Passed!" ); - ok( a.y != b.y, "Passed!" ); - ok( a.z != b.z, "Passed!" ); - - ok( ! a.equals( b ), "Passed!" ); - ok( ! b.equals( a ), "Passed!" ); - - a.copy( b ); - ok( a.x == b.x, "Passed!" ); - ok( a.y == b.y, "Passed!" ); - ok( a.z == b.z, "Passed!" ); - - ok( a.equals( b ), "Passed!" ); - ok( b.equals( a ), "Passed!" ); - }); - - - test( "constructor", function() { - var a = new THREE.Vector4(); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - ok( a.z == 0, "Passed!" ); - ok( a.w == 1, "Passed!" ); - - a = new THREE.Vector4( x, y, z, w ); - ok( a.x === x, "Passed!" ); - ok( a.y === y, "Passed!" ); - ok( a.z === z, "Passed!" ); - ok( a.w === w, "Passed!" ); - }); - - test( "copy", function() { - var a = new THREE.Vector4( x, y, z, w ); - var b = new THREE.Vector4().copy( a ); - ok( b.x == x, "Passed!" ); - ok( b.y == y, "Passed!" ); - ok( b.z == z, "Passed!" ); - ok( b.w == w, "Passed!" ); - - // ensure that it is a true copy - a.x = 0; - a.y = -1; - a.z = -2; - a.w = -3; - ok( b.x == x, "Passed!" ); - ok( b.y == y, "Passed!" ); - ok( b.z == z, "Passed!" ); - ok( b.w == w, "Passed!" ); - }); - - test( "set", function() { - var a = new THREE.Vector4(); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - ok( a.z == 0, "Passed!" ); - ok( a.w == 1, "Passed!" ); - - a.set( x, y, z, w ); - ok( a.x == x, "Passed!" ); - ok( a.y == y, "Passed!" ); - ok( a.z == z, "Passed!" ); - ok( a.w == w, "Passed!" ); - }); - - test( "setX,setY,setZ,setW", function() { - var a = new THREE.Vector4(); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - ok( a.z == 0, "Passed!" ); - ok( a.w == 1, "Passed!" ); - - a.setX( x ); - a.setY( y ); - a.setZ( z ); - a.setW( w ); - - ok( a.x == x, "Passed!" ); - ok( a.y == y, "Passed!" ); - ok( a.z == z, "Passed!" ); - ok( a.w == w, "Passed!" ); - }); - - test( "setComponent,getComponent", function() { - var a = new THREE.Vector4(); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - ok( a.z == 0, "Passed!" ); - ok( a.w == 1, "Passed!" ); - - a.setComponent( 0, 1 ); - a.setComponent( 1, 2 ); - a.setComponent( 2, 3 ); - a.setComponent( 3, 4 ); - ok( a.getComponent( 0 ) == 1, "Passed!" ); - ok( a.getComponent( 1 ) == 2, "Passed!" ); - ok( a.getComponent( 2 ) == 3, "Passed!" ); - ok( a.getComponent( 3 ) == 4, "Passed!" ); - }); - - test( "add", function() { - var a = new THREE.Vector4( x, y, z, w ); - var b = new THREE.Vector4( -x, -y, -z, -w ); - - a.add( b ); - ok( a.x == 0, "Passed!" ); - ok( a.y == 0, "Passed!" ); - ok( a.z == 0, "Passed!" ); - ok( a.w == 0, "Passed!" ); - - var c = new THREE.Vector4().addVectors( b, b ); - ok( c.x == -2*x, "Passed!" ); - ok( c.y == -2*y, "Passed!" ); - ok( c.z == -2*z, "Passed!" ); - ok( c.w == -2*w, "Passed!" ); - }); - - test( "sub", function() { - var a = new THREE.Vector4( x, y, z, w ); - var b = new THREE.Vector4( -x, -y, -z, -w ); - - a.sub( b ); - ok( a.x == 2*x, "Passed!" ); - ok( a.y == 2*y, "Passed!" ); - ok( a.z == 2*z, "Passed!" ); - ok( a.w == 2*w, "Passed!" ); - - var c = new THREE.Vector4().subVectors( a, a ); - ok( c.x == 0, "Passed!" ); - ok( c.y == 0, "Passed!" ); - ok( c.z == 0, "Passed!" ); - ok( c.w == 0, "Passed!" ); - }); - - test( "multiply/divide", function() { - var a = new THREE.Vector4( x, y, z, w ); - var b = new THREE.Vector4( -x, -y, -z, -w ); - - a.multiplyScalar( -2 ); - ok( a.x == x*-2, "Passed!" ); - ok( a.y == y*-2, "Passed!" ); - ok( a.z == z*-2, "Passed!" ); - ok( a.w == w*-2, "Passed!" ); - - b.multiplyScalar( -2 ); - ok( b.x == 2*x, "Passed!" ); - ok( b.y == 2*y, "Passed!" ); - ok( b.z == 2*z, "Passed!" ); - ok( b.w == 2*w, "Passed!" ); - - a.divideScalar( -2 ); - ok( a.x == x, "Passed!" ); - ok( a.y == y, "Passed!" ); - ok( a.z == z, "Passed!" ); - ok( a.w == w, "Passed!" ); - - b.divideScalar( -2 ); - ok( b.x == -x, "Passed!" ); - ok( b.y == -y, "Passed!" ); - ok( b.z == -z, "Passed!" ); - ok( b.w == -w, "Passed!" ); - }); - - test( "min/max/clamp", function() { - var a = new THREE.Vector4( x, y, z, w ); - var b = new THREE.Vector4( -x, -y, -z, -w ); - var c = new THREE.Vector4(); - - c.copy( a ).min( b ); - ok( c.x == -x, "Passed!" ); - ok( c.y == -y, "Passed!" ); - ok( c.z == -z, "Passed!" ); - ok( c.w == -w, "Passed!" ); - - c.copy( a ).max( b ); - ok( c.x == x, "Passed!" ); - ok( c.y == y, "Passed!" ); - ok( c.z == z, "Passed!" ); - ok( c.w == w, "Passed!" ); - - c.set( -2*x, 2*y, -2*z, 2*w ); - c.clamp( b, a ); - ok( c.x == -x, "Passed!" ); - ok( c.y == y, "Passed!" ); - ok( c.z == -z, "Passed!" ); - ok( c.w == w, "Passed!" ); - }); - - test( "negate", function() { - var a = new THREE.Vector4( x, y, z, w ); - - a.negate(); - ok( a.x == -x, "Passed!" ); - ok( a.y == -y, "Passed!" ); - ok( a.z == -z, "Passed!" ); - ok( a.w == -w, "Passed!" ); - }); - - test( "dot", function() { - var a = new THREE.Vector4( x, y, z, w ); - var b = new THREE.Vector4( -x, -y, -z, -w ); - var c = new THREE.Vector4( 0, 0, 0, 0 ); - - var result = a.dot( b ); - ok( result == (-x*x-y*y-z*z-w*w), "Passed!" ); - - result = a.dot( c ); - ok( result == 0, "Passed!" ); - }); - - test( "length/lengthSq", function() { - var a = new THREE.Vector4( x, 0, 0, 0 ); - var b = new THREE.Vector4( 0, -y, 0, 0 ); - var c = new THREE.Vector4( 0, 0, z, 0 ); - var d = new THREE.Vector4( 0, 0, 0, w ); - var e = new THREE.Vector4( 0, 0, 0, 0 ); - - ok( a.length() == x, "Passed!" ); - ok( a.lengthSq() == x*x, "Passed!" ); - ok( b.length() == y, "Passed!" ); - ok( b.lengthSq() == y*y, "Passed!" ); - ok( c.length() == z, "Passed!" ); - ok( c.lengthSq() == z*z, "Passed!" ); - ok( d.length() == w, "Passed!" ); - ok( d.lengthSq() == w*w, "Passed!" ); - ok( e.length() == 0, "Passed!" ); - ok( e.lengthSq() == 0, "Passed!" ); - - a.set( x, y, z, w ); - ok( a.length() == Math.sqrt( x*x + y*y + z*z + w*w ), "Passed!" ); - ok( a.lengthSq() == ( x*x + y*y + z*z + w*w ), "Passed!" ); - }); - - test( "normalize", function() { - var a = new THREE.Vector4( x, 0, 0, 0 ); - var b = new THREE.Vector4( 0, -y, 0, 0 ); - var c = new THREE.Vector4( 0, 0, z, 0 ); - var d = new THREE.Vector4( 0, 0, 0, -w ); - - a.normalize(); - ok( a.length() == 1, "Passed!" ); - ok( a.x == 1, "Passed!" ); - - b.normalize(); - ok( b.length() == 1, "Passed!" ); - ok( b.y == -1, "Passed!" ); - - c.normalize(); - ok( c.length() == 1, "Passed!" ); - ok( c.z == 1, "Passed!" ); - - d.normalize(); - ok( d.length() == 1, "Passed!" ); - ok( d.w == -1, "Passed!" ); - }); - - /* - test( "distanceTo/distanceToSquared", function() { - var a = new THREE.Vector4( x, 0, 0, 0 ); - var b = new THREE.Vector4( 0, -y, 0, 0 ); - var c = new THREE.Vector4( 0, 0, z, 0 ); - var d = new THREE.Vector4( 0, 0, 0, -w ); - var e = new THREE.Vector4(); - - ok( a.distanceTo( e ) == x, "Passed!" ); - ok( a.distanceToSquared( e ) == x*x, "Passed!" ); - - ok( b.distanceTo( e ) == y, "Passed!" ); - ok( b.distanceToSquared( e ) == y*y, "Passed!" ); - - ok( c.distanceTo( e ) == z, "Passed!" ); - ok( c.distanceToSquared( e ) == z*z, "Passed!" ); - - ok( d.distanceTo( e ) == w, "Passed!" ); - ok( d.distanceToSquared( e ) == w*w, "Passed!" ); - }); - */ - - - test( "setLength", function() { - var a = new THREE.Vector4( x, 0, 0, 0 ); - - ok( a.length() == x, "Passed!" ); - a.setLength( y ); - ok( a.length() == y, "Passed!" ); - - a = new THREE.Vector4( 0, 0, 0, 0 ); - ok( a.length() == 0, "Passed!" ); - a.setLength( y ); - ok( a.length() == 0, "Passed!" ); - }); - - test( "lerp/clone", function() { - var a = new THREE.Vector4( x, 0, z, 0 ); - var b = new THREE.Vector4( 0, -y, 0, -w ); - - ok( a.lerp( a, 0 ).equals( a.lerp( a, 0.5 ) ), "Passed!" ); - ok( a.lerp( a, 0 ).equals( a.lerp( a, 1 ) ), "Passed!" ); - - ok( a.clone().lerp( b, 0 ).equals( a ), "Passed!" ); - - ok( a.clone().lerp( b, 0.5 ).x == x*0.5, "Passed!" ); - ok( a.clone().lerp( b, 0.5 ).y == -y*0.5, "Passed!" ); - ok( a.clone().lerp( b, 0.5 ).z == z*0.5, "Passed!" ); - ok( a.clone().lerp( b, 0.5 ).w == -w*0.5, "Passed!" ); - - ok( a.clone().lerp( b, 1 ).equals( b ), "Passed!" ); - }); - - test( "equals", function() { - var a = new THREE.Vector4( x, 0, z, 0 ); - var b = new THREE.Vector4( 0, -y, 0, -w ); - - ok( a.x != b.x, "Passed!" ); - ok( a.y != b.y, "Passed!" ); - ok( a.z != b.z, "Passed!" ); - ok( a.w != b.w, "Passed!" ); - - ok( ! a.equals( b ), "Passed!" ); - ok( ! b.equals( a ), "Passed!" ); - - a.copy( b ); - ok( a.x == b.x, "Passed!" ); - ok( a.y == b.y, "Passed!" ); - ok( a.z == b.z, "Passed!" ); - ok( a.w == b.w, "Passed!" ); - - ok( a.equals( b ), "Passed!" ); - ok( b.equals( a ), "Passed!" ); - }); -}; - -///////////////////////////////////////////////////////////// -// https://github.com/mrdoob/three.js/tree/master/examples -////////////////////////////////////////////////////////////// - - -declare var Stats: any; -declare var TWEEN: any; -declare var Detector: any; -declare var Qrcode: any; -declare var ImprovedNoise: any; - - -declare module THREE{ - var PDBLoader: any; - var CSS3Renderer: any; - var CSS3DSprite: any; - var CSS3DRenderer: any; - var CSS3DObject: any; - var TrackballControls: any; - var FlyControls: any; - var RenderPass: any; - var FilmPass: any; - var EffectComposer: any; - var OrbitControls: any; - var PathControls: any; - var PointerLockControls: any; - var RollControls: any; - var FirstPersonControls: any; - var SVGRenderer: any; - var SoftwareRenderer: any; - var UVsDebug: any; - var UVsUtils: any; - var Curves: any; - var ParametricGeometries: any; - var BinaryLoader: any; - var OculusRiftEffect: any; - var SubdivisionModifier: any; - var TessellateModifier: any; - var ExplodeModifier: any; - var RenderPass: any; - var BloomPass:any; - var FilmPass: any; - var ShaderPass: any; - var FXAAShader: any; - var CopyShader: any; - var ColladaLoader: any; - var CTMLoader: any; - var VTKLoader: any; - var STLLoader: any; - var OBJLoader: any; - var ColladaLoader: any; - var UTF8Loader: any; - var UnpackDepthRGBAShader: any; -} - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_camera_orthographic.html - -()=>{ - var container, stats; - var camera, scene, renderer; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - var info = document.createElement( 'div' ); - info.style.position = 'absolute'; - info.style.top = '10px'; - info.style.width = '100%'; - info.style.textAlign = 'center'; - info.innerHTML = 'three.js - orthographic view'; - container.appendChild( info ); - - camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, - 500, 1000 ); - camera.position.x = 200; - camera.position.y = 100; - camera.position.z = 200; - - scene = new THREE.Scene(); - - // Grid - - var size = 500, step = 50; - - var geometry = new THREE.Geometry(); - - for ( var i = - size; i <= size; i += step ) { - - geometry.vertices.push( new THREE.Vector3( - size, 0, i ) ); - geometry.vertices.push( new THREE.Vector3( size, 0, i ) ); - - geometry.vertices.push( new THREE.Vector3( i, 0, - size ) ); - geometry.vertices.push( new THREE.Vector3( i, 0, size ) ); - - } - - var materialLine = new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.2 } ); - - var line = new THREE.Line( geometry, materialLine ); - line.type = THREE.LinePieces; - scene.add( line ); - - // Cubes - - geometry = new THREE.CubeGeometry( 50, 50, 50 ); - var materialCube = new THREE.MeshLambertMaterial( { color: 0xffffff, shading: THREE.FlatShading, overdraw: true } ); - - for ( var i = 0; i < 100; i ++ ) { - - var cube = new THREE.Mesh( geometry, materialCube ); - - cube.scale.y = Math.floor( Math.random() * 2 + 1 ); - - cube.position.x = Math.floor( ( Math.random() * 1000 - 500 ) / 50 ) * 50 + 25; - cube.position.y = ( cube.scale.y * 50 ) / 2; - cube.position.z = Math.floor( ( Math.random() * 1000 - 500 ) / 50 ) * 50 + 25; - - scene.add( cube ); - - } - - // Lights - - var ambientLight = new THREE.AmbientLight( Math.random() * 0x10 ); - scene.add( ambientLight ); - - var directionalLight = new THREE.DirectionalLight( Math.random() * 0xffffff ); - directionalLight.position.x = Math.random() - 0.5; - directionalLight.position.y = Math.random() - 0.5; - directionalLight.position.z = Math.random() - 0.5; - directionalLight.position.normalize(); - scene.add( directionalLight ); - - var directionalLight = new THREE.DirectionalLight( Math.random() * 0xffffff ); - directionalLight.position.x = Math.random() - 0.5; - directionalLight.position.y = Math.random() - 0.5; - directionalLight.position.z = Math.random() - 0.5; - directionalLight.position.normalize(); - scene.add( directionalLight ); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.left = window.innerWidth / - 2; - camera.right = window.innerWidth / 2; - camera.top = window.innerHeight / 2; - camera.bottom = window.innerHeight / - 2; - - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var timer = Date.now() * 0.0001; - - camera.position.x = Math.cos( timer ) * 200; - camera.position.z = Math.sin( timer ) * 200; - camera.lookAt( scene.position ); - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_geometry_cube.html - -()=>{ - - var container, stats; - - var camera, scene, renderer; - - var cube, plane; - - var targetRotation = 0; - var targetRotationOnMouseDown = 0; - - var mouseX = 0; - var mouseXOnMouseDown = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - var info = document.createElement( 'div' ); - info.style.position = 'absolute'; - info.style.top = '10px'; - info.style.width = '100%'; - info.style.textAlign = 'center'; - info.innerHTML = 'Drag to spin the cube'; - container.appendChild( info ); - - camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.y = 150; - camera.position.z = 500; - - scene = new THREE.Scene(); - - // Cube - - var geometryCube = new THREE.CubeGeometry( 200, 200, 200 ); - - for ( var i = 0; i < geometryCube.faces.length; i ++ ) { - - geometryCube.faces[ i ].color.setHex( Math.random() * 0xffffff ); - - } - - var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors } ); - - cube = new THREE.Mesh( geometryCube, material ); - cube.position.y = 150; - scene.add( cube ); - - // Plane - - var geometryPlane = new THREE.PlaneGeometry( 200, 200 ); - geometryPlane.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) ); - - var material = new THREE.MeshBasicMaterial( { color: 0xe0e0e0 } ); - - plane = new THREE.Mesh( geometryPlane, material ); - scene.add( plane ); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousedown', onDocumentMouseDown, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function onDocumentMouseDown( event ) { - - event.preventDefault(); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'mouseup', onDocumentMouseUp, false ); - document.addEventListener( 'mouseout', onDocumentMouseOut, false ); - - mouseXOnMouseDown = event.clientX - windowHalfX; - targetRotationOnMouseDown = targetRotation; - - } - - function onDocumentMouseMove( event ) { - - mouseX = event.clientX - windowHalfX; - - targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.02; - - } - - function onDocumentMouseUp( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - document.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - document.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - - } - - function onDocumentMouseOut( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - document.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - document.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length === 1 ) { - - event.preventDefault(); - - mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX; - targetRotationOnMouseDown = targetRotation; - - } - - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length === 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05; - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - plane.rotation.y = cube.rotation.y += ( targetRotation - cube.rotation.y ) * 0.05; - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_geometry_hierarchy.html - -()=>{ - var container, stats; - - var camera, scene, renderer; - - var geometry, group; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.z = 500; - - scene = new THREE.Scene(); - - var geometry = new THREE.CubeGeometry( 100, 100, 100 ); - var material = new THREE.MeshNormalMaterial(); - - group = new THREE.Object3D(); - - for ( var i = 0; i < 200; i ++ ) { - - var mesh = new THREE.Mesh( geometry, material ); - mesh.position.x = Math.random() * 2000 - 1000; - mesh.position.y = Math.random() * 2000 - 1000; - mesh.position.z = Math.random() * 2000 - 1000; - mesh.rotation.x = Math.random() * 2 * Math.PI; - mesh.rotation.y = Math.random() * 2 * Math.PI; - mesh.matrixAutoUpdate = false; - mesh.updateMatrix(); - group.add( mesh ); - - } - - scene.add( group ); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.sortObjects = false; - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onDocumentMouseMove(event) { - - mouseX = ( event.clientX - windowHalfX ) * 10; - mouseY = ( event.clientY - windowHalfY ) * 10; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y += ( - mouseY - camera.position.y ) * .05; - camera.lookAt( scene.position ); - - var currentSeconds = Date.now(); - group.rotation.x = Math.sin( currentSeconds * 0.0007 ) * 0.5; - group.rotation.y = Math.sin( currentSeconds * 0.0003 ) * 0.5; - group.rotation.z = Math.sin( currentSeconds * 0.0002 ) * 0.5; - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_geometry_panorama.html - -()=>{ - var camera, scene, renderer; - - var texture_placeholder, - isUserInteracting = false, - onPointerDownPointerX = 0, onPointerDownPointerY = 0, - lon = 90, onPointerDownLon = 0, - lat = 0, onPointerDownLat = 0, - phi = 0, theta = 0, - target = new THREE.Vector3(); - - init(); - - function init() { - - var container, mesh; - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1100 ); - - scene = new THREE.Scene(); - - texture_placeholder = document.createElement( 'canvas' ); - texture_placeholder.width = 128; - texture_placeholder.height = 128; - - var context = texture_placeholder.getContext( '2d' ); - context.fillStyle = 'rgb( 200, 200, 200 )'; - context.fillRect( 0, 0, texture_placeholder.width, texture_placeholder.height ); - - var materials = [ - - loadTexture( 'textures/cube/skybox/px.jpg' ), // right - loadTexture( 'textures/cube/skybox/nx.jpg' ), // left - loadTexture( 'textures/cube/skybox/py.jpg' ), // top - loadTexture( 'textures/cube/skybox/ny.jpg' ), // bottom - loadTexture( 'textures/cube/skybox/pz.jpg' ), // back - loadTexture( 'textures/cube/skybox/nz.jpg' ) // front - - ]; - - mesh = new THREE.Mesh( new THREE.CubeGeometry( 300, 300, 300, 7, 7, 7 ), new THREE.MeshFaceMaterial( materials ) ); - mesh.scale.x = - 1; - scene.add( mesh ); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - document.addEventListener( 'mousedown', onDocumentMouseDown, false ); - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'mouseup', onDocumentMouseUp, false ); - document.addEventListener( 'mousewheel', onDocumentMouseWheel, false ); - - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - render(); - - } - - function loadTexture( path ) { - - var texture = new THREE.Texture( texture_placeholder ); - var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: true } ); - - var image = new Image(); - image.onload = function () { - - texture.needsUpdate = true; - material.map.image = this; - - render(); - - }; - image.src = path; - - return material; - - } - - function onDocumentMouseDown( event ) { - - event.preventDefault(); - - isUserInteracting = true; - - onPointerDownPointerX = event.clientX; - onPointerDownPointerY = event.clientY; - - onPointerDownLon = lon; - onPointerDownLat = lat; - - } - - function onDocumentMouseMove( event ) { - - if ( isUserInteracting ) { - - lon = ( onPointerDownPointerX - event.clientX ) * 0.1 + onPointerDownLon; - lat = ( event.clientY - onPointerDownPointerY ) * 0.1 + onPointerDownLat; - render(); - - } - - } - - function onDocumentMouseUp( event ) { - - isUserInteracting = false; - render(); - - } - - function onDocumentMouseWheel( event ) { - - camera.fov -= event.wheelDeltaY * 0.05; - camera.updateProjectionMatrix(); - - render(); - - } - - - function onDocumentTouchStart( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - onPointerDownPointerX = event.touches[ 0 ].pageX; - onPointerDownPointerY = event.touches[ 0 ].pageY; - - onPointerDownLon = lon; - onPointerDownLat = lat; - - } - - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - lon = ( onPointerDownPointerX - event.touches[0].pageX ) * 0.1 + onPointerDownLon; - lat = ( event.touches[0].pageY - onPointerDownPointerY ) * 0.1 + onPointerDownLat; - - render(); - - } - - } - - function render() { - - lat = Math.max( - 85, Math.min( 85, lat ) ); - phi = THREE.Math.degToRad( 90 - lat ); - theta = THREE.Math.degToRad( lon ); - - target.x = 500 * Math.sin( phi ) * Math.cos( theta ); - target.y = 500 * Math.cos( phi ); - target.z = 500 * Math.sin( phi ) * Math.sin( theta ); - - camera.lookAt( target ); - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_geometry_panorama_fisheye.html - -()=>{ - var camera, scene, renderer; - - var texture_placeholder, - isUserInteracting = false, - onPointerDownPointerX = 0, onPointerDownPointerY = 0, - lon = 90, onPointerDownLon = 0, - lat = 0, onPointerDownLat = 0, - phi = 0, theta = 0, - target = new THREE.Vector3(); - - init(); - - function init() { - - var container, mesh; - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1100 ); - - scene = new THREE.Scene(); - - texture_placeholder = document.createElement( 'canvas' ); - texture_placeholder.width = 128; - texture_placeholder.height = 128; - - var context = texture_placeholder.getContext( '2d' ); - context.fillStyle = 'rgb( 200, 200, 200 )'; - context.fillRect( 0, 0, texture_placeholder.width, texture_placeholder.height ); - - var materials = [ - - loadTexture( 'textures/cube/skybox/px.jpg' ), // right - loadTexture( 'textures/cube/skybox/nx.jpg' ), // left - loadTexture( 'textures/cube/skybox/py.jpg' ), // top - loadTexture( 'textures/cube/skybox/ny.jpg' ), // bottom - loadTexture( 'textures/cube/skybox/pz.jpg' ), // back - loadTexture( 'textures/cube/skybox/nz.jpg' ) // front - - ]; - - mesh = new THREE.Mesh( new THREE.CubeGeometry( 300, 300, 300, 7, 7, 7 ), new THREE.MeshFaceMaterial( materials ) ); - mesh.scale.x = - 1; - scene.add( mesh ); - - for ( var i = 0, l = mesh.geometry.vertices.length; i < l; i ++ ) { - - var vertex = mesh.geometry.vertices[ i ]; - - vertex.normalize(); - vertex.multiplyScalar( 550 ); - - } - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - document.addEventListener( 'mousedown', onDocumentMouseDown, false ); - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'mouseup', onDocumentMouseUp, false ); - document.addEventListener( 'mousewheel', onDocumentMouseWheel, false ); - document.addEventListener( 'DOMMouseScroll', onDocumentMouseWheel, false); - - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - render(); - - } - - function loadTexture( path ) { - - var texture = new THREE.Texture( texture_placeholder ); - var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: true } ); - - var image = new Image(); - image.onload = function () { - - texture.needsUpdate = true; - material.map.image = this; - - render(); - - }; - image.src = path; - - return material; - - } - - function onDocumentMouseDown( event ) { - - event.preventDefault(); - - isUserInteracting = true; - - onPointerDownPointerX = event.clientX; - onPointerDownPointerY = event.clientY; - - onPointerDownLon = lon; - onPointerDownLat = lat; - - } - - function onDocumentMouseMove( event ) { - - if ( isUserInteracting ) { - - lon = ( onPointerDownPointerX - event.clientX ) * 0.1 + onPointerDownLon; - lat = ( event.clientY - onPointerDownPointerY ) * 0.1 + onPointerDownLat; - render(); - - } - } - - function onDocumentMouseUp( event ) { - - isUserInteracting = false; - render(); - - } - - function onDocumentMouseWheel( event ) { - - // WebKit - - if ( event.wheelDeltaY ) { - - camera.fov -= event.wheelDeltaY * 0.05; - - // Opera / Explorer 9 - - } else if ( event.wheelDelta ) { - - camera.fov -= event.wheelDelta * 0.05; - - // Firefox - - } else if ( event.detail ) { - - camera.fov -= event.detail * 0.05; - - } - - camera.updateProjectionMatrix(); - - render(); - - } - - - function onDocumentTouchStart( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - onPointerDownPointerX = event.touches[ 0 ].pageX; - onPointerDownPointerY = event.touches[ 0 ].pageY; - - onPointerDownLon = lon; - onPointerDownLat = lat; - - } - - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - lon = ( onPointerDownPointerX - event.touches[0].pageX ) * 0.1 + onPointerDownLon; - lat = ( event.touches[0].pageY - onPointerDownPointerY ) * 0.1 + onPointerDownLat; - - render(); - - } - - } - - function render() { - - lat = Math.max( - 85, Math.min( 85, lat ) ); - phi = THREE.Math.degToRad( 90 - lat ); - theta = THREE.Math.degToRad( lon ); - - target.x = 500 * Math.sin( phi ) * Math.cos( theta ); - target.y = 500 * Math.cos( phi ); - target.z = 500 * Math.sin( phi ) * Math.sin( theta ); - - camera.position.x = - target.x; - camera.position.y = - target.y; - camera.position.z = - target.z; - camera.lookAt( target ); - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_geometry_shapes.html - -()=>{ -var container, stats; - - var camera, scene, renderer; - - var text, plane; - - var targetRotation = 0; - var targetRotationOnMouseDown = 0; - - var mouseX = 0; - var mouseXOnMouseDown = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var parent; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.set( 0, 150, 500 ); - - scene = new THREE.Scene(); - - parent = new THREE.Object3D(); - parent.position.y = 50; - scene.add( parent ); - - function addShape( shape, color, x, y, z, rx, ry, rz, s ) { - - // flat shape - - var geometry = new THREE.ShapeGeometry( shape ); - var materialMesh = new THREE.MeshBasicMaterial( { color: color, overdraw: true } ); - - var mesh = new THREE.Mesh( geometry, materialMesh ); - mesh.position.set( x, y, z ); - mesh.rotation.set( rx, ry, rz ); - mesh.scale.set( s, s, s ); - parent.add( mesh ); - - // line - - geometry = shape.createPointsGeometry(); - var materialLine = new THREE.LineBasicMaterial( { linewidth: 10, color: 0x333333, transparent: true } ); - - var line = new THREE.Line( geometry, materialLine ); - line.position.set( x, y, z ); - line.rotation.set( rx, ry, rz ); - line.scale.set( s, s, s ); - parent.add( line ); - - } - - - // California - - var californiaPts = []; - - californiaPts.push( new THREE.Vector2 ( 610, 320 ) ); - californiaPts.push( new THREE.Vector2 ( 450, 300 ) ); - californiaPts.push( new THREE.Vector2 ( 392, 392 ) ); - californiaPts.push( new THREE.Vector2 ( 266, 438 ) ); - californiaPts.push( new THREE.Vector2 ( 190, 570 ) ); - californiaPts.push( new THREE.Vector2 ( 190, 600 ) ); - californiaPts.push( new THREE.Vector2 ( 160, 620 ) ); - californiaPts.push( new THREE.Vector2 ( 160, 650 ) ); - californiaPts.push( new THREE.Vector2 ( 180, 640 ) ); - californiaPts.push( new THREE.Vector2 ( 165, 680 ) ); - californiaPts.push( new THREE.Vector2 ( 150, 670 ) ); - californiaPts.push( new THREE.Vector2 ( 90, 737 ) ); - californiaPts.push( new THREE.Vector2 ( 80, 795 ) ); - californiaPts.push( new THREE.Vector2 ( 50, 835 ) ); - californiaPts.push( new THREE.Vector2 ( 64, 870 ) ); - californiaPts.push( new THREE.Vector2 ( 60, 945 ) ); - californiaPts.push( new THREE.Vector2 ( 300, 945 ) ); - californiaPts.push( new THREE.Vector2 ( 300, 743 ) ); - californiaPts.push( new THREE.Vector2 ( 600, 473 ) ); - californiaPts.push( new THREE.Vector2 ( 626, 425 ) ); - californiaPts.push( new THREE.Vector2 ( 600, 370 ) ); - californiaPts.push( new THREE.Vector2 ( 610, 320 ) ); - - var californiaShape = new THREE.Shape( californiaPts ); - - - // Triangle - - var triangleShape = new THREE.Shape(); - triangleShape.moveTo( 80, 20 ); - triangleShape.lineTo( 40, 80 ); - triangleShape.lineTo( 120, 80 ); - triangleShape.lineTo( 80, 20 ); // close path - - - // Heart - - var x = 0, y = 0; - - var heartShape = new THREE.Shape(); // From http://blog.burlock.org/html5/130-paths - - heartShape.moveTo( x + 25, y + 25 ); - heartShape.bezierCurveTo( x + 25, y + 25, x + 20, y, x, y ); - heartShape.bezierCurveTo( x - 30, y, x - 30, y + 35,x - 30,y + 35 ); - heartShape.bezierCurveTo( x - 30, y + 55, x - 10, y + 77, x + 25, y + 95 ); - heartShape.bezierCurveTo( x + 60, y + 77, x + 80, y + 55, x + 80, y + 35 ); - heartShape.bezierCurveTo( x + 80, y + 35, x + 80, y, x + 50, y ); - heartShape.bezierCurveTo( x + 35, y, x + 25, y + 25, x + 25, y + 25 ); - - - // Square - - var sqLength = 80; - - var squareShape = new THREE.Shape(); - squareShape.moveTo( 0,0 ); - squareShape.lineTo( 0, sqLength ); - squareShape.lineTo( sqLength, sqLength ); - squareShape.lineTo( sqLength, 0 ); - squareShape.lineTo( 0, 0 ); - - - // Rectangle - - var rectLength = 120, rectWidth = 40; - - var rectShape = new THREE.Shape(); - rectShape.moveTo( 0,0 ); - rectShape.lineTo( 0, rectWidth ); - rectShape.lineTo( rectLength, rectWidth ); - rectShape.lineTo( rectLength, 0 ); - rectShape.lineTo( 0, 0 ); - - - // Rounded rectangle - - var roundedRectShape = new THREE.Shape(); - - ( function roundedRect( ctx, x, y, width, height, radius ){ - - ctx.moveTo( x, y + radius ); - ctx.lineTo( x, y + height - radius ); - ctx.quadraticCurveTo( x, y + height, x + radius, y + height ); - ctx.lineTo( x + width - radius, y + height) ; - ctx.quadraticCurveTo( x + width, y + height, x + width, y + height - radius ); - ctx.lineTo( x + width, y + radius ); - ctx.quadraticCurveTo( x + width, y, x + width - radius, y ); - ctx.lineTo( x + radius, y ); - ctx.quadraticCurveTo( x, y, x, y + radius ); - - } )( roundedRectShape, 0, 0, 50, 50, 20 ); - - - // Circle - - var circleRadius = 40; - var circleShape = new THREE.Shape(); - circleShape.moveTo( 0, circleRadius ); - circleShape.quadraticCurveTo( circleRadius, circleRadius, circleRadius, 0 ); - circleShape.quadraticCurveTo( circleRadius, -circleRadius, 0, -circleRadius ); - circleShape.quadraticCurveTo( -circleRadius, -circleRadius, -circleRadius, 0 ); - circleShape.quadraticCurveTo( -circleRadius, circleRadius, 0, circleRadius ); - - - // Fish - - x = y = 0; - - var fishShape = new THREE.Shape(); - - fishShape.moveTo(x,y); - fishShape.quadraticCurveTo(x + 50, y - 80, x + 90, y - 10); - fishShape.quadraticCurveTo(x + 100, y - 10, x + 115, y - 40); - fishShape.quadraticCurveTo(x + 115, y, x + 115, y + 40); - fishShape.quadraticCurveTo(x + 100, y + 10, x + 90, y + 10); - fishShape.quadraticCurveTo(x + 50, y + 80, x, y); - - - // Arc circle - - var arcShape = new THREE.Shape(); - arcShape.moveTo( 50, 10 ); - arcShape.absarc( 10, 10, 40, 0, Math.PI*2, false ); - - var holePath = new THREE.Path(); - holePath.moveTo( 20, 10 ); - holePath.absarc( 10, 10, 10, 0, Math.PI*2, true ); - arcShape.holes.push( holePath ); - - - // Smiley - - var smileyShape = new THREE.Shape(); - smileyShape.moveTo( 80, 40 ); - smileyShape.absarc( 40, 40, 40, 0, Math.PI*2, false ); - - var smileyEye1Path = new THREE.Path(); - smileyEye1Path.moveTo( 35, 20 ); - // smileyEye1Path.absarc( 25, 20, 10, 0, Math.PI*2, true ); - smileyEye1Path.absellipse( 25, 20, 10, 10, 0, Math.PI*2, true ); - - smileyShape.holes.push( smileyEye1Path ); - - var smileyEye2Path = new THREE.Path(); - smileyEye2Path.moveTo( 65, 20 ); - smileyEye2Path.absarc( 55, 20, 10, 0, Math.PI*2, true ); - smileyShape.holes.push( smileyEye2Path ); - - var smileyMouthPath = new THREE.Path(); - // ugly box mouth - // smileyMouthPath.moveTo( 20, 40 ); - // smileyMouthPath.lineTo( 60, 40 ); - // smileyMouthPath.lineTo( 60, 60 ); - // smileyMouthPath.lineTo( 20, 60 ); - // smileyMouthPath.lineTo( 20, 40 ); - - smileyMouthPath.moveTo( 20, 40 ); - smileyMouthPath.quadraticCurveTo( 40, 60, 60, 40 ); - smileyMouthPath.bezierCurveTo( 70, 45, 70, 50, 60, 60 ); - smileyMouthPath.quadraticCurveTo( 40, 80, 20, 60 ); - smileyMouthPath.quadraticCurveTo( 5, 50, 20, 40 ); - - smileyShape.holes.push( smileyMouthPath ); - - - // Spline shape + path extrusion - - var splinepts = []; - splinepts.push( new THREE.Vector2 ( 350, 100 ) ); - splinepts.push( new THREE.Vector2 ( 400, 450 ) ); - splinepts.push( new THREE.Vector2 ( -140, 350 ) ); - splinepts.push( new THREE.Vector2 ( 0, 0 ) ); - - var splineShape = new THREE.Shape( ); - splineShape.moveTo( 0, 0 ); - splineShape.splineThru( splinepts ); - - - // addShape( shape, color, x, y, z, rx, ry,rz, s ); - - addShape( californiaShape, 0xffaa00, -300, -100, 0, 0, 0, 0, 0.25 ); - addShape( triangleShape, 0xffee00, -180, 0, 0, 0, 0, 0, 1 ); - addShape( roundedRectShape, 0x005500, -150, 150, 0, 0, 0, 0, 1 ); - addShape( squareShape, 0x0055ff, 150, 100, 0, 0, 0, 0, 1 ); - addShape( heartShape, 0xff1100, 60, 100, 0, 0, 0, Math.PI, 1 ); - addShape( circleShape, 0x00ff11, 120, 250, 0, 0, 0, 0, 1 ); - addShape( fishShape, 0x222222, -60, 200, 0, 0, 0, 0, 1 ); - addShape( smileyShape, 0xee00ff, -200, 250, 0, 0, 0, Math.PI, 1 ); - addShape( arcShape, 0xbb4422, 150, 0, 0, 0, 0, 0, 1 ); - addShape( splineShape, 0x888888, -50, -100, 0, 0, 0, 0, 0.2 ); - - // - - renderer = new THREE.CanvasRenderer( { antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.sortObjects = false; - renderer.sortElements = false; - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousedown', onDocumentMouseDown, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function onDocumentMouseDown( event ) { - - event.preventDefault(); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'mouseup', onDocumentMouseUp, false ); - document.addEventListener( 'mouseout', onDocumentMouseOut, false ); - - mouseXOnMouseDown = event.clientX - windowHalfX; - targetRotationOnMouseDown = targetRotation; - - } - - function onDocumentMouseMove( event ) { - - mouseX = event.clientX - windowHalfX; - - targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.02; - - } - - function onDocumentMouseUp( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - document.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - document.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - - } - - function onDocumentMouseOut( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - document.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - document.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX; - targetRotationOnMouseDown = targetRotation; - - } - - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05; - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - parent.rotation.y += ( targetRotation - parent.rotation.y ) * 0.05; - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_interactive_cubes.html - -()=>{ - var container, stats; - var camera, scene, projector, renderer; - var particleMaterial; - - var objects = []; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - var info = document.createElement( 'div' ); - info.style.position = 'absolute'; - info.style.top = '10px'; - info.style.width = '100%'; - info.style.textAlign = 'center'; - info.innerHTML = 'three.js - clickable objects'; - container.appendChild( info ); - - camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.set( 0, 300, 500 ); - - scene = new THREE.Scene(); - - var geometry = new THREE.CubeGeometry( 100, 100, 100 ); - - for ( var i = 0; i < 10; i ++ ) { - - var object = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, opacity: 0.5 } ) ); - object.position.x = Math.random() * 800 - 400; - object.position.y = Math.random() * 800 - 400; - object.position.z = Math.random() * 800 - 400; - - object.scale.x = Math.random() * 2 + 1; - object.scale.y = Math.random() * 2 + 1; - object.scale.z = Math.random() * 2 + 1; - - object.rotation.x = Math.random() * 2 * Math.PI; - object.rotation.y = Math.random() * 2 * Math.PI; - object.rotation.z = Math.random() * 2 * Math.PI; - - scene.add( object ); - - objects.push( object ); - - } - - var PI2 = Math.PI * 2; - particleMaterial = new THREE.ParticleSystemMaterial( { - - color: 0x000000, - program: function ( context ) { - - context.beginPath(); - context.arc( 0, 0, 1, 0, PI2, true ); - context.closePath(); - context.fill(); - - } - - } ); - - projector = new THREE.Projector(); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousedown', onDocumentMouseDown, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onDocumentMouseDown( event ) { - - event.preventDefault(); - - var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 ); - projector.unprojectVector( vector, camera ); - - var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() ); - - var intersects = raycaster.intersectObjects( objects ); - - if ( intersects.length > 0 ) { - - var mesh = intersects[ 0 ].object; - var mat = mesh.material; - mat.color.setHex( Math.random() * 0xffffff ); - - var geometry = new THREE.Geometry(); - var particle = new THREE.ParticleSystem(geometry, particleMaterial ); - particle.position = intersects[ 0 ].point; - particle.scale.x = particle.scale.y = 8; - scene.add( particle ); - - } - - /* - // Parse all the faces - for ( var i in intersects ) { - - intersects[ i ].face.material[ 0 ].color.setHex( Math.random() * 0xffffff | 0x80000000 ); - - } - */ - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - var radius = 600; - var theta = 0; - - function render() { - - theta += 0.1; - - camera.position.x = radius * Math.sin( THREE.Math.degToRad( theta ) ); - camera.position.y = radius * Math.sin( THREE.Math.degToRad( theta ) ); - camera.position.z = radius * Math.cos( THREE.Math.degToRad( theta ) ); - camera.lookAt( scene.position ); - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_interactive_particles.html - -()=>{ - var container, stats; - var camera, scene, projector, renderer; - - var PI2 = Math.PI * 2; - - var programFill = function ( context ) { - - context.beginPath(); - context.arc( 0, 0, 1, 0, PI2, true ); - context.closePath(); - context.fill(); - - } - - var programStroke = function ( context ) { - - context.lineWidth = 0.05; - context.beginPath(); - context.arc( 0, 0, 1, 0, PI2, true ); - context.closePath(); - context.stroke(); - - } - - var mouse = { x: 0, y: 0 }, INTERSECTED; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - var info = document.createElement( 'div' ); - info.style.position = 'absolute'; - info.style.top = '10px'; - info.style.width = '100%'; - info.style.textAlign = 'center'; - info.innerHTML = 'three.js canvas - interactive particles'; - container.appendChild( info ); - - camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.set( 0, 300, 500 ); - - scene = new THREE.Scene(); - - for ( var i = 0; i < 100; i ++ ) { - var geometry = new THREE.Geometry(); - var particle = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: Math.random() * 0x808080 + 0x808080, program: programStroke } ) ); - particle.position.x = Math.random() * 800 - 400; - particle.position.y = Math.random() * 800 - 400; - particle.position.z = Math.random() * 800 - 400; - particle.scale.x = particle.scale.y = Math.random() * 10 + 10; - scene.add( particle ); - - } - - projector = new THREE.Projector(); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onDocumentMouseMove( event ) { - - event.preventDefault(); - - mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; - mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - var radius = 600; - var theta = 0; - - function render() { - - // rotate camera - - theta += 0.1; - - camera.position.x = radius * Math.sin( THREE.Math.degToRad( theta ) ); - camera.position.y = radius * Math.sin( THREE.Math.degToRad( theta ) ); - camera.position.z = radius * Math.cos( THREE.Math.degToRad( theta ) ); - camera.lookAt( scene.position ); - - // find intersections - - camera.updateMatrixWorld(); - - var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 ); - projector.unprojectVector( vector, camera ); - - var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() ); - - var intersects = raycaster.intersectObjects( scene.children ); - - if ( intersects.length > 0 ) { - - if ( INTERSECTED != intersects[ 0 ].object ) { - - if ( INTERSECTED ) INTERSECTED.material.program = programStroke; - - INTERSECTED = intersects[ 0 ].object; - INTERSECTED.material.program = programFill; - - } - - } else { - - if ( INTERSECTED ) INTERSECTED.material.program = programStroke; - - INTERSECTED = null; - - } - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_camera_orthographic.html - -()=>{ - var container, stats; - var camera, scene, renderer; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - var info = document.createElement( 'div' ); - info.style.position = 'absolute'; - info.style.top = '10px'; - info.style.width = '100%'; - info.style.textAlign = 'center'; - info.innerHTML = 'three.js - orthographic view'; - container.appendChild( info ); - - camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, - 500, 1000 ); - camera.position.x = 200; - camera.position.y = 100; - camera.position.z = 200; - - scene = new THREE.Scene(); - - // Grid - - var size = 500, step = 50; - - var geometry = new THREE.Geometry(); - - for ( var i = - size; i <= size; i += step ) { - - geometry.vertices.push( new THREE.Vector3( - size, 0, i ) ); - geometry.vertices.push( new THREE.Vector3( size, 0, i ) ); - - geometry.vertices.push( new THREE.Vector3( i, 0, - size ) ); - geometry.vertices.push( new THREE.Vector3( i, 0, size ) ); - - } - - var lineMaterial = new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.2 } ); - - var line = new THREE.Line( geometry, lineMaterial ); - line.type = THREE.LinePieces; - scene.add( line ); - - // Cubes - - geometry = new THREE.CubeGeometry( 50, 50, 50 ); - var cubeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, shading: THREE.FlatShading, overdraw: true } ); - - for ( var i = 0; i < 100; i ++ ) { - - var cube = new THREE.Mesh( geometry, cubeMaterial ); - - cube.scale.y = Math.floor( Math.random() * 2 + 1 ); - - cube.position.x = Math.floor( ( Math.random() * 1000 - 500 ) / 50 ) * 50 + 25; - cube.position.y = ( cube.scale.y * 50 ) / 2; - cube.position.z = Math.floor( ( Math.random() * 1000 - 500 ) / 50 ) * 50 + 25; - - scene.add( cube ); - - } - - // Lights - - var ambientLight = new THREE.AmbientLight( Math.random() * 0x10 ); - scene.add( ambientLight ); - - var directionalLight = new THREE.DirectionalLight( Math.random() * 0xffffff ); - directionalLight.position.x = Math.random() - 0.5; - directionalLight.position.y = Math.random() - 0.5; - directionalLight.position.z = Math.random() - 0.5; - directionalLight.position.normalize(); - scene.add( directionalLight ); - - var directionalLight = new THREE.DirectionalLight( Math.random() * 0xffffff ); - directionalLight.position.x = Math.random() - 0.5; - directionalLight.position.y = Math.random() - 0.5; - directionalLight.position.z = Math.random() - 0.5; - directionalLight.position.normalize(); - scene.add( directionalLight ); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.left = window.innerWidth / - 2; - camera.right = window.innerWidth / 2; - camera.top = window.innerHeight / 2; - camera.bottom = window.innerHeight / - 2; - - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var timer = Date.now() * 0.0001; - - camera.position.x = Math.cos( timer ) * 200; - camera.position.z = Math.sin( timer ) * 200; - camera.lookAt( scene.position ); - - renderer.render( scene, camera ); - - } - -}; - - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_interactive_voxelpainter.html - -()=>{ - var container, stats; - var camera, scene, renderer; - var projector, plane; - var mouse2D, mouse3D, raycaster, theta = 45, - isShiftDown = false, isCtrlDown = false, - target = new THREE.Vector3( 0, 200, 0 ); - var ROLLOVERED; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - var info = document.createElement( 'div' ); - info.style.position = 'absolute'; - info.style.top = '10px'; - info.style.width = '100%'; - info.style.textAlign = 'center'; - info.innerHTML = 'three.js - voxel painter
    click: add voxel, control + click: remove voxel, shift: rotate, save .png'; - container.appendChild( info ); - - camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.y = 800; - - scene = new THREE.Scene(); - - // Grid - - var size = 500, step = 50; - - var geometry = new THREE.Geometry(); - - for ( var i = - size; i <= size; i += step ) { - - geometry.vertices.push( new THREE.Vector3( - size, 0, i ) ); - geometry.vertices.push( new THREE.Vector3( size, 0, i ) ); - - geometry.vertices.push( new THREE.Vector3( i, 0, - size ) ); - geometry.vertices.push( new THREE.Vector3( i, 0, size ) ); - - } - - var material = new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.2 } ); - - var line = new THREE.Line( geometry, material ); - line.type = THREE.LinePieces; - scene.add( line ); - - // - - projector = new THREE.Projector(); - - plane = new THREE.Mesh( new THREE.PlaneGeometry( 1000, 1000 ), new THREE.MeshBasicMaterial() ); - plane.rotation.x = - Math.PI / 2; - plane.visible = false; - scene.add( plane ); - - mouse2D = new THREE.Vector3( 0, 10000, 0.5 ); - - // Lights - - var ambientLight = new THREE.AmbientLight( 0x606060 ); - scene.add( ambientLight ); - - var directionalLight = new THREE.DirectionalLight( 0xffffff ); - directionalLight.position.x = Math.random() - 0.5; - directionalLight.position.y = Math.random() - 0.5; - directionalLight.position.z = Math.random() - 0.5; - directionalLight.position.normalize(); - scene.add( directionalLight ); - - var directionalLight = new THREE.DirectionalLight( 0x808080 ); - directionalLight.position.x = Math.random() - 0.5; - directionalLight.position.y = Math.random() - 0.5; - directionalLight.position.z = Math.random() - 0.5; - directionalLight.position.normalize(); - scene.add( directionalLight ); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild(renderer.domElement); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'mousedown', onDocumentMouseDown, false ); - document.addEventListener( 'keydown', onDocumentKeyDown, false ); - document.addEventListener( 'keyup', onDocumentKeyUp, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onDocumentMouseMove( event ) { - - event.preventDefault(); - - mouse2D.x = ( event.clientX / window.innerWidth ) * 2 - 1; - mouse2D.y = - ( event.clientY / window.innerHeight ) * 2 + 1; - - var intersects = raycaster.intersectObjects( scene.children ); - - if ( intersects.length > 0 ) { - - if ( ROLLOVERED ) ROLLOVERED.color.setHex( 0x00ff80 ); - - ROLLOVERED = intersects[ 0 ].face; - ROLLOVERED.color.setHex( 0xff8000 ) - - } - - } - - function onDocumentMouseDown( event ) { - - event.preventDefault(); - - var intersects = raycaster.intersectObjects( scene.children ); - - if ( intersects.length > 0 ) { - - var interect = intersects[ 0 ]; - - if ( isCtrlDown ) { - - if ( interect.object != plane ) { - - scene.remove( interect.object ); - - } - - } else { - - var normal = interect.face.normal.clone(); - normal.applyMatrix4( interect.object.matrixRotationWorld ); - - var position = new THREE.Vector3().addVectors( interect.point, normal ); - - var geometry = new THREE.CubeGeometry( 50, 50, 50 ); - - for ( var i = 0; i < geometry.faces.length; i ++ ) { - - geometry.faces[ i ].color.setHex( 0x00ff80 ); - - } - - var material = new THREE.MeshLambertMaterial( { vertexColors: THREE.FaceColors } ); - - var voxel = new THREE.Mesh( geometry, material ); - voxel.position.x = Math.floor( position.x / 50 ) * 50 + 25; - voxel.position.y = Math.floor( position.y / 50 ) * 50 + 25; - voxel.position.z = Math.floor( position.z / 50 ) * 50 + 25; - voxel.matrixAutoUpdate = false; - voxel.updateMatrix(); - scene.add( voxel ); - - } - - } - } - - function onDocumentKeyDown( event ) { - - switch( event.keyCode ) { - - case 16: isShiftDown = true; break; - case 17: isCtrlDown = true; break; - - } - - } - - function onDocumentKeyUp( event ) { - - switch( event.keyCode ) { - - case 16: isShiftDown = false; break; - case 17: isCtrlDown = false; break; - - } - } - - function save() { - - window.open( renderer.domElement.toDataURL('image/png'), 'mywindow' ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - if ( isShiftDown ) { - - theta += mouse2D.x * 3; - - } - - camera.position.x = 1400 * Math.sin( theta * Math.PI / 360 ); - camera.position.z = 1400 * Math.cos( theta * Math.PI / 360 ); - camera.lookAt( target ); - - raycaster = projector.pickingRay( mouse2D.clone(), camera ); - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_lights_pointlights.html - -()=>{ - var camera, scene, renderer, - particle1, particle2, particle3, - light1, light2, light3, - loader, mesh; - - init(); - animate(); - - function init() { - - var container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.set( 0, - 6, 100 ); - - scene = new THREE.Scene(); - - scene.add( new THREE.AmbientLight( 0x00020 ) ); - - light1 = new THREE.PointLight( 0xff0040, 1, 50 ); - scene.add( light1 ); - - light2 = new THREE.PointLight( 0x0040ff, 1, 50 ); - scene.add( light2 ); - - light3 = new THREE.PointLight( 0x80ff80, 1, 50 ); - scene.add( light3 ); - - var PI2 = Math.PI * 2; - var program = function ( context ) { - - context.beginPath(); - context.arc( 0, 0, 1, 0, PI2, true ); - context.fill(); - - } - - var geometry = new THREE.Geometry(); - particle1 = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: 0xff0040, program: program } ) ); - particle1.scale.x = particle1.scale.y = particle1.scale.z = 0.5; - scene.add( particle1 ); - - particle2 = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: 0x0040ff, program: program } ) ); - particle2.scale.x = particle2.scale.y = particle2.scale.z = 0.5; - scene.add( particle2 ); - - particle3 = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: 0x80ff80, program: program } ) ); - particle3.scale.x = particle3.scale.y = particle3.scale.z = 0.5; - scene.add( particle3 ); - - loader = new THREE.JSONLoader(); - loader.load( 'obj/WaltHeadLo.js', function ( geometry ) { - - mesh = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: 0xffffff, shading: THREE.FlatShading, overdraw: true } ) ); - scene.add( mesh ); - - } ); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - container.appendChild( renderer.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - render(); - - } - - function render() { - - var time = Date.now() * 0.0005; - - if ( mesh ) mesh.rotation.y -= 0.01; - - particle1.position.x = Math.sin( time * 0.7 ) * 30; - particle1.position.y = Math.cos( time * 0.5 ) * 40; - particle1.position.z = Math.cos( time * 0.3 ) * 30; - - light1.position.x = particle1.position.x; - light1.position.y = particle1.position.y; - light1.position.z = particle1.position.z; - - particle2.position.x = Math.cos( time * 0.3 ) * 30; - particle2.position.y = Math.sin( time * 0.5 ) * 40; - particle2.position.z = Math.sin( time * 0.7 ) * 30; - - light2.position.x = particle2.position.x; - light2.position.y = particle2.position.y; - light2.position.z = particle2.position.z; - - particle3.position.x = Math.sin( time * 0.7 ) * 30; - particle3.position.y = Math.cos( time * 0.3 ) * 40; - particle3.position.z = Math.sin( time * 0.5 ) * 30; - - light3.position.x = particle3.position.x; - light3.position.y = particle3.position.y; - light3.position.z = particle3.position.z; - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_lights_pointlights_smooth.html - -()=>{ - var camera, scene, renderer, - particle1, particle2, particle3, - light1, light2, light3, - loader, mesh; - - init(); - animate(); - - function init() { - - var container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.set( 0, - 6, 100 ); - - scene = new THREE.Scene(); - - scene.add( new THREE.AmbientLight( 0x00020 ) ); - - light1 = new THREE.PointLight( 0xff0040, 1, 50 ); - scene.add( light1 ); - - light2 = new THREE.PointLight( 0x0040ff, 1, 50 ); - scene.add( light2 ); - - light3 = new THREE.PointLight( 0x80ff80, 1, 50 ); - scene.add( light3 ); - - var PI2 = Math.PI * 2; - var program = function ( context ) { - - context.beginPath(); - context.arc( 0, 0, 1, 0, PI2, true ); - context.fill(); - - } - - var geometry = new THREE.Geometry(); - particle1 = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: 0xff0040, program: program } ) ); - particle1.scale.x = particle1.scale.y = particle1.scale.z = 0.5; - scene.add( particle1 ); - - particle2 = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: 0x0040ff, program: program } ) ); - particle2.scale.x = particle2.scale.y = particle2.scale.z = 0.5; - scene.add( particle2 ); - - particle3 = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: 0x80ff80, program: program } ) ); - particle3.scale.x = particle3.scale.y = particle3.scale.z = 0.5; - scene.add( particle3 ); - - loader = new THREE.JSONLoader(); - loader.load( 'obj/WaltHeadLo.js', function ( geometry ) { - - geometry.computeVertexNormals(); - - mesh = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: 0xffffff, overdraw: true } ) ); - scene.add( mesh ); - - } ); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - container.appendChild( renderer.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - - } - - function render() { - - var time = Date.now() * 0.0005; - - if ( mesh ) mesh.rotation.y -= 0.01; - - particle1.position.x = Math.sin( time * 0.7 ) * 30; - particle1.position.y = Math.cos( time * 0.5 ) * 40; - particle1.position.z = Math.cos( time * 0.3 ) * 30; - - light1.position.x = particle1.position.x; - light1.position.y = particle1.position.y; - light1.position.z = particle1.position.z; - - particle2.position.x = Math.cos( time * 0.3 ) * 30; - particle2.position.y = Math.sin( time * 0.5 ) * 40; - particle2.position.z = Math.sin( time * 0.7 ) * 30; - - light2.position.x = particle2.position.x; - light2.position.y = particle2.position.y; - light2.position.z = particle2.position.z; - - particle3.position.x = Math.sin( time * 0.7 ) * 30; - particle3.position.y = Math.cos( time * 0.3 ) * 40; - particle3.position.z = Math.sin( time * 0.5 ) * 30; - - light3.position.x = particle3.position.x; - light3.position.y = particle3.position.y; - light3.position.z = particle3.position.z; - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_lines.html - -()=>{ - - var mouseX = 0, mouseY = 0, - - windowHalfX = window.innerWidth / 2, - windowHalfY = window.innerHeight / 2, - - SEPARATION = 200, - AMOUNTX = 10, - AMOUNTY = 10, - - camera, scene, renderer; - - init(); - animate(); - - function init() { - - var container, separation = 100, amountX = 50, amountY = 50, - particles, particle; - - container = document.createElement('div'); - document.body.appendChild(container); - - camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.z = 100; - - scene = new THREE.Scene(); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - container.appendChild( renderer.domElement ); - - // particles - - var PI2 = Math.PI * 2; - var material = new THREE.ParticleSystemMaterial( { - - color: 0xffffff, - program: function ( context ) { - - context.beginPath(); - context.arc( 0, 0, 1, 0, PI2, true ); - context.closePath(); - context.fill(); - - } - - } ); - - var geometry = new THREE.Geometry(); - - for ( var i = 0; i < 100; i ++ ) { - - particle = new THREE.ParticleSystem(geometry, material ); - particle.position.x = Math.random() * 2 - 1; - particle.position.y = Math.random() * 2 - 1; - particle.position.z = Math.random() * 2 - 1; - particle.position.normalize(); - particle.position.multiplyScalar( Math.random() * 10 + 450 ); - particle.scale.x = particle.scale.y = 5; - scene.add( particle ); - - geometry.vertices.push( particle.position ); - - } - - // lines - - var line = new THREE.Line( geometry, new THREE.LineBasicMaterial( { color: 0xffffff, opacity: 0.5 } ) ); - scene.add( line ); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function onDocumentMouseMove(event) { - - mouseX = event.clientX - windowHalfX; - mouseY = event.clientY - windowHalfY; - - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length > 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - - } - - function render() { - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y += ( - mouseY + 200 - camera.position.y ) * .05; - camera.lookAt( scene.position ); - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_lines_sphere.html - -()=>{ - - var SCREEN_WIDTH = window.innerWidth, - SCREEN_HEIGHT = window.innerHeight, - - mouseX = 0, mouseY = 0, - - windowHalfX = window.innerWidth / 2, - windowHalfY = window.innerHeight / 2, - - SEPARATION = 200, - AMOUNTX = 10, - AMOUNTY = 10, - - camera, scene, renderer; - - init(); - animate(); - - function init() { - - var container, separation = 100, amountX = 50, amountY = 50, - particles, particle; - - container = document.createElement('div'); - document.body.appendChild(container); - - camera = new THREE.PerspectiveCamera( 75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 ); - camera.position.z = 1000; - - scene = new THREE.Scene(); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - container.appendChild( renderer.domElement ); - - // particles - - var PI2 = Math.PI * 2; - var material = new THREE.ParticleSystemMaterial( { - - color: 0xffffff, - program: function ( context ) { - - context.beginPath(); - context.arc( 0, 0, 1, 0, PI2, true ); - context.closePath(); - context.fill(); - - } - - } ); - - var geometry = new THREE.Geometry(); - for ( var i = 0; i < 1000; i ++ ) { - - particle = new THREE.ParticleSystem(geometry, material ); - particle.position.x = Math.random() * 2 - 1; - particle.position.y = Math.random() * 2 - 1; - particle.position.z = Math.random() * 2 - 1; - particle.position.normalize(); - particle.position.multiplyScalar( Math.random() * 10 + 450 ); - scene.add( particle ); - - } - - // lines - - for (var i = 0; i < 300; i++) { - - var geometry = new THREE.Geometry(); - - var vertex = new THREE.Vector3( Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 2 - 1 ); - vertex.normalize(); - vertex.multiplyScalar( 450 ); - - geometry.vertices.push( vertex ); - - var vertex2 = vertex.clone(); - vertex2.multiplyScalar( Math.random() * 0.3 + 1 ); - - geometry.vertices.push( vertex2 ); - - var line = new THREE.Line( geometry, new THREE.LineBasicMaterial( { color: 0xffffff, opacity: Math.random() } ) ); - scene.add( line ); - } - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function onDocumentMouseMove(event) { - - mouseX = event.clientX - windowHalfX; - mouseY = event.clientY - windowHalfY; - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length > 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - - } - - function render() { - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y += ( - mouseY + 200 - camera.position.y ) * .05; - camera.lookAt( scene.position ); - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_materials.html - -()=>{ - - var container, stats; - - var camera, scene, renderer, objects; - var particleLight, pointLight; - - init(); - animate(); - - function init() { - - container = document.createElement('div'); - document.body.appendChild(container); - - camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 ); - camera.position.set( 0, 200, 800 ); - - scene = new THREE.Scene(); - - // Grid - - var size = 500, step = 100; - - var geometry = new THREE.Geometry(); - - for ( var i = - size; i <= size; i += step ) { - - geometry.vertices.push( new THREE.Vector3( - size, - 120, i ) ); - geometry.vertices.push( new THREE.Vector3( size, - 120, i ) ); - - geometry.vertices.push( new THREE.Vector3( i, - 120, - size ) ); - geometry.vertices.push( new THREE.Vector3( i, - 120, size ) ); - - } - - var material = new THREE.LineBasicMaterial( { color: 0xffffff, opacity: 0.2 } ); - - var line = new THREE.Line( geometry, material ); - line.type = THREE.LinePieces; - scene.add( line ); - - // Spheres - - geometry = new THREE.SphereGeometry( 100, 14, 7 ); - - var materials:THREE.Material[] = [ - - new THREE.MeshBasicMaterial( { color: 0x00ffff, wireframe: true, side: THREE.DoubleSide } ), - new THREE.MeshBasicMaterial( { color: 0xff0000, blending: THREE.AdditiveBlending, side: THREE.DoubleSide } ), - new THREE.MeshLambertMaterial( { color: 0xffffff, shading: THREE.FlatShading, side: THREE.DoubleSide, overdraw: true } ), - new THREE.MeshLambertMaterial( { color: 0xffffff, shading: THREE.SmoothShading, overdraw: true } ), - new THREE.MeshDepthMaterial( { overdraw: true } ), - new THREE.MeshNormalMaterial( { overdraw: true } ), - new THREE.MeshNormalMaterial( { shading: THREE.SmoothShading, overdraw: true } ), - new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/land_ocean_ice_cloud_2048.jpg' ) } ), - new THREE.MeshBasicMaterial( { envMap: THREE.ImageUtils.loadTexture( 'textures/envmap.png', new THREE.SphericalReflectionMapping() ) } ) - - ]; - - for ( var i = 0, l = geometry.faces.length; i < l; i ++ ) { - - var face = geometry.faces[ i ]; - if ( Math.random() > 0.5 ) face.materialIndex = Math.floor( Math.random() * materials.length ); - - } - - materials.push( new THREE.MeshFaceMaterial( materials ) ); - - objects = []; - - for ( var i = 0, l = materials.length; i < l; i ++ ) { - - var sphere = new THREE.Mesh( geometry, materials[ i ] ); - - sphere.position.x = ( i % 5 ) * 200 - 400; - sphere.position.z = Math.floor( i / 5 ) * 200 - 200; - - sphere.rotation.x = Math.random() * 200 - 100; - sphere.rotation.y = Math.random() * 200 - 100; - sphere.rotation.z = Math.random() * 200 - 100; - - objects.push( sphere ); - - scene.add( sphere ); - - } - - var PI2 = Math.PI * 2; - var program = function ( context ) { - - context.beginPath(); - context.arc( 0, 0, 1, 0, PI2, true ); - context.closePath(); - context.fill(); - - } - - var geometry = new THREE.Geometry(); - particleLight = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: 0xffffff, program: program } ) ); - particleLight.scale.x = particleLight.scale.y = particleLight.scale.z = 4; - scene.add( particleLight ); - - // Lights - - scene.add( new THREE.AmbientLight( Math.random() * 0x202020 ) ); - - var directionalLight = new THREE.DirectionalLight( Math.random() * 0xffffff ); - directionalLight.position.x = Math.random() - 0.5; - directionalLight.position.y = Math.random() - 0.5; - directionalLight.position.z = Math.random() - 0.5; - directionalLight.position.normalize(); - scene.add( directionalLight ); - - pointLight = new THREE.PointLight( 0xffffff, 1 ); - scene.add( pointLight ); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - container.appendChild( renderer.domElement ); - - var debugCanvas:HTMLCanvasElement = document.createElement( 'canvas' ); - debugCanvas.width = 512; - debugCanvas.height = 512; - debugCanvas.style.position = 'absolute'; - debugCanvas.style.top = '0px'; - debugCanvas.style.left = '0px'; - - container.appendChild( debugCanvas ); - - var debugContext = debugCanvas.getContext( '2d' ); - debugContext.setTransform( 1, 0, 0, 1, 256, 256 ); - debugContext.strokeStyle = '#000000'; - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild(stats.domElement); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function loadImage( path ) { - - var image:HTMLImageElement = document.createElement( 'img' ); - var texture = new THREE.Texture( image, new THREE.UVMapping() ) - - image.onload = function () { texture.needsUpdate = true; }; - image.src = path; - - return texture; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var timer = Date.now() * 0.0001; - - camera.position.x = Math.cos( timer ) * 1000; - camera.position.z = Math.sin( timer ) * 1000; - camera.lookAt( scene.position ); - - for ( var i = 0, l = objects.length; i < l; i++ ) { - - var object = objects[ i ]; - - object.rotation.x += 0.01; - object.rotation.y += 0.005; - - } - - particleLight.position.x = Math.sin( timer * 7 ) * 300; - particleLight.position.y = Math.cos( timer * 5 ) * 400; - particleLight.position.z = Math.cos( timer * 3 ) * 300; - - pointLight.position.x = particleLight.position.x; - pointLight.position.y = particleLight.position.y; - pointLight.position.z = particleLight.position.z; - - renderer.render( scene, camera ); - - } - -}; - - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_materials_depth.html - -()=>{ - var container, stats; - - var camera, scene, renderer; - - var cube, plane, objects = []; - - var targetRotation = 0; - var targetRotationOnMouseDown = 0; - - var mouseX = 0; - var mouseXOnMouseDown = 0; - - var moveForward = false; - var moveBackwards = false; - var moveLeft = false; - var moveRight = false; - var moveUp = false; - var moveDown = false; - - var targetMoveLeft = false; - var targetMoveRight = false; - - var debugContext; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 ); - camera.position.set( 1000, 1000, 1000 ); - camera.target = new THREE.Vector3( 0, 150, 0 ); - - scene = new THREE.Scene(); - - // Plane - - var material = new THREE.MeshDepthMaterial( { side: THREE.DoubleSide, overdraw: true } ); - - plane = new THREE.Mesh( new THREE.PlaneGeometry( 1000, 1000, 10, 10 ), material ); - plane.position.y = - 100; - plane.rotation.x = - Math.PI / 2; - scene.add( plane ); - - // Cubes - - var geometry = new THREE.CubeGeometry( 100, 100, 100 ); - material = new THREE.MeshDepthMaterial( { overdraw: true } ); - - for ( var i = 0; i < 20; i ++ ) { - - cube = new THREE.Mesh( geometry, material ); - - cube.position.x = ( i % 5 ) * 200 - 400; - cube.position.z = Math.floor( i / 5 ) * 200 - 350; - - cube.rotation.x = Math.random() * 200 - 100; - cube.rotation.y = Math.random() * 200 - 100; - cube.rotation.z = Math.random() * 200 - 100; - - scene.add( cube ); - - objects.push( cube ); - - } - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - var debugCanvas = document.createElement( 'canvas' ); - debugCanvas.width = 512; - debugCanvas.height = 512; - debugCanvas.style.position = 'absolute'; - debugCanvas.style.top = '0px'; - debugCanvas.style.left = '0px'; - - container.appendChild( debugCanvas ); - - debugContext = debugCanvas.getContext( '2d' ); - debugContext.setTransform( 1, 0, 0, 1, 256, 256 ); - debugContext.strokeStyle = '#808080'; - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild(stats.domElement); - - document.addEventListener( 'keydown', onDocumentKeyDown, false ); - document.addEventListener( 'keyup', onDocumentKeyUp, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onDocumentKeyDown( event ) { - - switch ( event.keyCode ) { - - case 38: moveForward = true; break; // up - case 40: moveBackwards = true; break; // down - case 37: moveLeft = true; break; // left - case 39: moveRight = true; break; // right - case 87: moveUp = true; break; // w - case 83: moveDown = true; break; // s - case 65: targetMoveLeft = true; break; // a - case 68: targetMoveRight = true; break; // d - - } - - } - - function onDocumentKeyUp( event ) { - - switch ( event.keyCode ) { - - case 38: moveForward = false; break; // up - case 40: moveBackwards = false; break; // down - case 37: moveLeft = false; break; // left - case 39: moveRight = false; break; // right - case 87: moveUp = false; break; // w - case 83: moveDown = false; break; // s - case 65: targetMoveLeft = false; break; // a - case 68: targetMoveRight = false; break; // d - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - if ( moveForward ) camera.position.z -= 10; - if ( moveBackwards ) camera.position.z += 10; - - if ( moveLeft ) camera.position.x -= 10; - if ( moveRight ) camera.position.x += 10; - - if ( moveUp ) camera.position.y += 10; - if ( moveDown ) camera.position.y -= 10; - - if ( targetMoveLeft ) camera.target.x -= 10; - if ( targetMoveRight ) camera.target.x += 10; - - camera.lookAt( camera.target ); - - debugContext.clearRect( - 256, - 256, 512, 512 ); - - debugContext.beginPath(); - - // center - debugContext.moveTo( - 10, 0 ); - debugContext.lineTo( 10, 0 ); - debugContext.moveTo( 0, - 10 ); - debugContext.lineTo( 0, 10 ); - - // camera - - debugContext.moveTo( camera.position.x * 0.1, camera.position.z * 0.1 ); - debugContext.lineTo( camera.target.x * 0.1, camera.target.z * 0.1 ); - debugContext.rect( camera.position.x * 0.1 - 5, camera.position.z * 0.1 - 5, 10, 10 ); - debugContext.rect( camera.target.x * 0.1 - 5, camera.target.z * 0.1 - 5, 10, 10 ); - debugContext.rect( - 50, - 50, 100, 100 ); - - for ( var i = 0; i < objects.length; i++ ) { - - var object = objects[ i ]; - - object.rotation.x += 0.01; - object.rotation.y += 0.005; - object.position.y = Math.sin( object.rotation.x ) * 200 + 200; - - debugContext.rect( object.position.x * 0.1 - 5, object.position.z * 0.1 - 5, 10, 10 ); - - } - - debugContext.closePath(); - debugContext.stroke(); - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_materials_normal.html - -()=>{ - var camera, scene, renderer, - loader, mesh; - - init(); - animate(); - - function init() { - - var container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 2000 ); - camera.position.set( 0, - 6, 100 ); - - scene = new THREE.Scene(); - - loader = new THREE.JSONLoader(); - loader.load( 'obj/WaltHeadLo.js', function ( geometry ) { - - mesh = new THREE.Mesh( geometry, new THREE.MeshNormalMaterial( { overdraw: true } ) ); - scene.add( mesh ); - - } ); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - container.appendChild( renderer.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - render(); - - } - - function render() { - - var time = Date.now() * 0.0005; - - if ( mesh ) { - - mesh.rotation.x -= 0.005; - mesh.rotation.y -= 0.01; - - } - - renderer.render( scene, camera ); - - } -}; - - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_materials_reflection.html - -()=>{ - - var camera, scene, renderer, - particle1, particle2, particle2, - light1, light2, light3, - loader, mesh; - - init(); - animate(); - - function init() { - - var container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.set( 0, - 6, 100 ); - - scene = new THREE.Scene(); - - loader = new THREE.JSONLoader(); - loader.load( 'obj/WaltHeadLo.js', function ( geometry ) { - - geometry.computeVertexNormals(); - - mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { envMap: THREE.ImageUtils.loadTexture( 'textures/metal.jpg', new THREE.SphericalReflectionMapping() ), overdraw: true } ) ); - scene.add( mesh ); - - } ); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - container.appendChild( renderer.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - - } - - function render() { - - var time = Date.now() * 0.0005; - - if ( mesh ) mesh.rotation.y -= 0.01; - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_materials_video.html - -()=>{ - var AMOUNT = 100; - - var container, stats; - - var camera, scene, renderer; - - var video, image, imageContext, - imageReflection, imageReflectionContext, imageReflectionGradient, - texture, textureReflection; - - var mesh; - - var mouseX = 0; - var mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - var info = document.createElement( 'div' ); - info.style.position = 'absolute'; - info.style.top = '10px'; - info.style.width = '100%'; - info.style.textAlign = 'center'; - info.innerHTML = 'three.js - video demo. playing sintel trailer'; - container.appendChild( info ); - - camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.z = 1000; - - scene = new THREE.Scene(); - - video = document.getElementById( 'video' ); - - // - - image = document.createElement( 'canvas' ); - image.width = 480; - image.height = 204; - - imageContext = image.getContext( '2d' ); - imageContext.fillStyle = '#000000'; - imageContext.fillRect( 0, 0, 480, 204 ); - - texture = new THREE.Texture( image ); - texture.minFilter = THREE.LinearFilter; - texture.magFilter = THREE.LinearFilter; - - var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: true } ); - - imageReflection = document.createElement( 'canvas' ); - imageReflection.width = 480; - imageReflection.height = 204; - - imageReflectionContext = imageReflection.getContext( '2d' ); - imageReflectionContext.fillStyle = '#000000'; - imageReflectionContext.fillRect( 0, 0, 480, 204 ); - - imageReflectionGradient = imageReflectionContext.createLinearGradient( 0, 0, 0, 204 ); - imageReflectionGradient.addColorStop( 0.2, 'rgba(240, 240, 240, 1)' ); - imageReflectionGradient.addColorStop( 1, 'rgba(240, 240, 240, 0.8)' ); - - textureReflection = new THREE.Texture( imageReflection ); - textureReflection.minFilter = THREE.LinearFilter; - textureReflection.magFilter = THREE.LinearFilter; - - var materialReflection = new THREE.MeshBasicMaterial( { map: textureReflection, side: THREE.BackSide, overdraw: true } ); - - // - - var plane = new THREE.PlaneGeometry( 480, 204, 4, 4 ); - - mesh = new THREE.Mesh( plane, material ); - mesh.scale.x = mesh.scale.y = mesh.scale.z = 1.5; - scene.add(mesh); - - mesh = new THREE.Mesh( plane, materialReflection ); - mesh.position.y = -306; - mesh.rotation.x = - Math.PI; - mesh.scale.x = mesh.scale.y = mesh.scale.z = 1.5; - scene.add( mesh ); - - // - - var separation = 150; - var amountx = 10; - var amounty = 10; - - var PI2 = Math.PI * 2; - var materialParticle = new THREE.ParticleSystemMaterial( { - - color: 0x0808080, - program: function ( context ) { - - context.beginPath(); - context.arc( 0, 0, 1, 0, PI2, true ); - context.closePath(); - context.fill(); - - } - - } ); - - var geometry = new THREE.Geometry(); - for ( var ix = 0; ix < amountx; ix++ ) { - for ( var iy = 0; iy < amounty; iy++ ) { - var particle = new THREE.ParticleSystem(geometry, materialParticle ); - particle.position.x = ix * separation - ( ( amountx * separation ) / 2 ); - particle.position.y = -153 - particle.position.z = iy * separation - ( ( amounty * separation ) / 2 ); - scene.add( particle ); - - } - - } - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onDocumentMouseMove( event ) { - - mouseX = ( event.clientX - windowHalfX ); - mouseY = ( event.clientY - windowHalfY ) * 0.2; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - camera.position.x += ( mouseX - camera.position.x ) * 0.05; - camera.position.y += ( - mouseY - camera.position.y ) * 0.05; - camera.lookAt( scene.position ); - - if ( video.readyState === video.HAVE_ENOUGH_DATA ) { - - imageContext.drawImage( video, 0, 0 ); - - if ( texture ) texture.needsUpdate = true; - if ( textureReflection ) textureReflection.needsUpdate = true; - - } - - imageReflectionContext.drawImage( image, 0, 0 ); - imageReflectionContext.fillStyle = imageReflectionGradient; - imageReflectionContext.fillRect( 0, 0, 480, 204 ); - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_particles_floor.html - -()=>{ - var SEPARATION = 100; - var AMOUNTX = 50; - var AMOUNTY = 50; - - var container, stats; - var camera, scene, renderer, particle; - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.z = 1000; - - scene = new THREE.Scene(); - - var material = new THREE.ParticleSystemMaterial(); - var geometry = new THREE.Geometry(); - for ( var ix = 0; ix < AMOUNTX; ix++ ) { - - for ( var iy = 0; iy < AMOUNTY; iy++ ) { - - particle = new THREE.ParticleSystem(geometry, material ); - particle.scale.y = 4; - particle.position.x = ix * SEPARATION - ( ( AMOUNTX * SEPARATION ) / 2 ); - particle.position.z = iy * SEPARATION - ( ( AMOUNTY * SEPARATION ) / 2 ); - scene.add( particle ); - } - } - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function onDocumentMouseMove( event ) { - - mouseX = event.clientX - windowHalfX; - mouseY = event.clientY - windowHalfY; - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length > 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - } - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y += ( - mouseY - camera.position.y ) * .05; - camera.lookAt( scene.position ); - - renderer.render( scene, camera ); - - } -}; - - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_particles_random.html - -()=>{ - var container, stats; - var camera, scene, renderer, group, particle; - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 ); - camera.position.z = 1000; - - scene = new THREE.Scene(); - - var PI2 = Math.PI * 2; - var program = function ( context ) { - - context.beginPath(); - context.arc( 0, 0, 1, 0, PI2, true ); - context.closePath(); - context.fill(); - - } - - group = new THREE.Object3D(); - scene.add( group ); - - var geometry = new THREE.Geometry(); - for ( var i = 0; i < 1000; i++ ) { - - particle = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: Math.random() * 0x808008 + 0x808080, program: program } ) ); - particle.position.x = Math.random() * 2000 - 1000; - particle.position.y = Math.random() * 2000 - 1000; - particle.position.z = Math.random() * 2000 - 1000; - particle.scale.x = particle.scale.y = Math.random() * 10 + 5; - group.add( particle ); - } - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function onDocumentMouseMove( event ) { - - mouseX = event.clientX - windowHalfX; - mouseY = event.clientY - windowHalfY; - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length === 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length === 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - camera.position.x += ( mouseX - camera.position.x ) * 0.05; - camera.position.y += ( - mouseY - camera.position.y ) * 0.05; - camera.lookAt( scene.position ); - - group.rotation.x += 0.01; - group.rotation.y += 0.02; - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_particles_sprites.html - -() => { - var container, stats; - var camera, scene, renderer, particle; - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - init(); - animate(); - - function init() { - - container = document.createElement('div'); - document.body.appendChild(container); - - camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 5000); - camera.position.z = 1000; - - scene = new THREE.Scene(); - - var material = new THREE.ParticleSystemMaterial({ map: new THREE.Texture(generateSprite()), blending: THREE.AdditiveBlending }); - var geometry = new THREE.Geometry(); - for (var i = 0; i < 1000; i++) { - - particle = new THREE.ParticleSystem(geometry, material); - - initParticle(particle, i * 10); - - scene.add(particle); - } - - renderer = new THREE.CanvasRenderer(); - renderer.setSize(window.innerWidth, window.innerHeight); - renderer.sortElements = false; - renderer.setClearColorHex(0x0000ff, 0.25); - container.appendChild(renderer.domElement); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild(stats.domElement); - - document.addEventListener('mousemove', onDocumentMouseMove, false); - document.addEventListener('touchstart', onDocumentTouchStart, false); - document.addEventListener('touchmove', onDocumentTouchMove, false); - - // - - window.addEventListener('resize', onWindowResize, false); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize(window.innerWidth, window.innerHeight); - - } - - function generateSprite() { - - var canvas = document.createElement('canvas'); - canvas.width = 16; - canvas.height = 16; - - var context = canvas.getContext('2d'); - var gradient = context.createRadialGradient(canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2); - gradient.addColorStop(0, 'rgba(255,255,255,1)'); - gradient.addColorStop(0.2, 'rgba(0,255,255,1)'); - gradient.addColorStop(0.4, 'rgba(0,0,64,1)'); - gradient.addColorStop(1, 'rgba(0,0,0,1)'); - - context.fillStyle = gradient; - context.fillRect(0, 0, canvas.width, canvas.height); - - return canvas; - - } - - function initParticle(particle, delay) { - - var particle = this instanceof THREE.ParticleSystem ? this : particle; - var delay = delay !== undefined ? delay : 0; - - particle.position.x = 0; - particle.position.y = 0; - particle.position.z = 0; - particle.scale.x = particle.scale.y = Math.random() * 3 + 1; - - new TWEEN.Tween(particle) - .delay(delay) - .to({}, 10000) - .onComplete(initParticle) - .start(); - - new TWEEN.Tween(particle.position) - .delay(delay) - .to({ x: Math.random() * 4000 - 2000, y: Math.random() * 1000 - 500, z: Math.random() * 4000 - 2000 }, 10000) - .start(); - - new TWEEN.Tween(particle.scale) - .delay(delay) - .to({ x: 0, y: 0 }, 10000) - .start(); - - } - - // - - function onDocumentMouseMove(event) { - - mouseX = event.clientX - windowHalfX; - mouseY = event.clientY - windowHalfY; - } - - function onDocumentTouchStart(event) { - - if (event.touches.length == 1) { - - event.preventDefault(); - - mouseX = event.touches[0].pageX - windowHalfX; - mouseY = event.touches[0].pageY - windowHalfY; - - } - - } - - function onDocumentTouchMove(event) { - - if (event.touches.length == 1) { - - event.preventDefault(); - - mouseX = event.touches[0].pageX - windowHalfX; - mouseY = event.touches[0].pageY - windowHalfY; - - } - - } - - // - - function animate() { - - requestAnimationFrame(animate); - - render(); - stats.update(); - - } - - function render() { - - TWEEN.update(); - - camera.position.x += (mouseX - camera.position.x) * 0.05; - camera.position.y += (- mouseY - camera.position.y) * 0.05; - camera.lookAt(scene.position); - - renderer.render(scene, camera); - - } -}; -() => { - var container, stats; - var camera, scene, renderer, particle; - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 5000 ); - camera.position.z = 1000; - - scene = new THREE.Scene(); - - var material = new THREE.ParticleSystemMaterial( { map: new THREE.Texture( generateSprite() ), blending: THREE.AdditiveBlending } ); - var geometry = new THREE.Geometry(); - for ( var i = 0; i < 1000; i++ ) { - - particle = new THREE.ParticleSystem(geometry, material ); - - initParticle( particle, i * 10 ); - - scene.add( particle ); - } - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.sortElements = false; - renderer.setClearColorHex( 0x0000ff, 0.25 ); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function generateSprite() { - - var canvas = document.createElement( 'canvas' ); - canvas.width = 16; - canvas.height = 16; - - var context = canvas.getContext( '2d' ); - var gradient = context.createRadialGradient( canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2 ); - gradient.addColorStop( 0, 'rgba(255,255,255,1)' ); - gradient.addColorStop( 0.2, 'rgba(0,255,255,1)' ); - gradient.addColorStop( 0.4, 'rgba(0,0,64,1)' ); - gradient.addColorStop( 1, 'rgba(0,0,0,1)' ); - - context.fillStyle = gradient; - context.fillRect( 0, 0, canvas.width, canvas.height ); - - return canvas; - - } - - function initParticle( particle, delay ) { - - var particle = this instanceof THREE.ParticleSystem ? this : particle; - var delay = delay !== undefined ? delay : 0; - - particle.position.x = 0; - particle.position.y = 0; - particle.position.z = 0; - particle.scale.x = particle.scale.y = Math.random() * 3 + 1; - - new TWEEN.Tween( particle ) - .delay( delay ) - .to( {}, 10000 ) - .onComplete( initParticle ) - .start(); - - new TWEEN.Tween( particle.position ) - .delay( delay ) - .to( { x: Math.random() * 4000 - 2000, y: Math.random() * 1000 - 500, z: Math.random() * 4000 - 2000 }, 10000 ) - .start(); - - new TWEEN.Tween( particle.scale ) - .delay( delay ) - .to( { x: 0, y: 0 }, 10000 ) - .start(); - - } - - // - - function onDocumentMouseMove( event ) { - - mouseX = event.clientX - windowHalfX; - mouseY = event.clientY - windowHalfY; - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - TWEEN.update(); - - camera.position.x += ( mouseX - camera.position.x ) * 0.05; - camera.position.y += ( - mouseY - camera.position.y ) * 0.05; - camera.lookAt( scene.position ); - - renderer.render( scene, camera ); - - } - -}; - - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_particles_waves.html - -()=>{ - var SEPARATION = 100, AMOUNTX = 50, AMOUNTY = 50; - - var container, stats; - var camera, scene, renderer; - - var particles, particle, count = 0; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.z = 1000; - - scene = new THREE.Scene(); - - particles = new Array(); - - var PI2 = Math.PI * 2; - var material = new THREE.ParticleSystemMaterial( { - - color: 0xffffff, - program: function ( context ) { - - context.beginPath(); - context.arc( 0, 0, 1, 0, PI2, true ); - context.fill(); - - } - - } ); - - var i = 0; - var geometry = new THREE.Geometry(); - for ( var ix = 0; ix < AMOUNTX; ix ++ ) { - - for ( var iy = 0; iy < AMOUNTY; iy ++ ) { - - particle = particles[ i ++ ] = new THREE.ParticleSystem(geometry, material ); - particle.position.x = ix * SEPARATION - ( ( AMOUNTX * SEPARATION ) / 2 ); - particle.position.z = iy * SEPARATION - ( ( AMOUNTY * SEPARATION ) / 2 ); - scene.add( particle ); - - } - - } - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function onDocumentMouseMove( event ) { - - mouseX = event.clientX - windowHalfX; - mouseY = event.clientY - windowHalfY; - - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length === 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length === 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y += ( - mouseY - camera.position.y ) * .05; - camera.lookAt( scene.position ); - - var i = 0; - - for ( var ix = 0; ix < AMOUNTX; ix ++ ) { - - for ( var iy = 0; iy < AMOUNTY; iy ++ ) { - - particle = particles[ i++ ]; - particle.position.y = ( Math.sin( ( ix + count ) * 0.3 ) * 50 ) + ( Math.sin( ( iy + count ) * 0.5 ) * 50 ); - particle.scale.x = particle.scale.y = ( Math.sin( ( ix + count ) * 0.3 ) + 1 ) * 2 + ( Math.sin( ( iy + count ) * 0.5 ) + 1 ) * 2; - - } - - } - - renderer.render( scene, camera ); - - count += 0.1; - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_performance.html - -()=>{ - var container, stats; - - var camera, scene, renderer; - - var sphere, plane; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.set( 0, 1000, 1000 ); - - scene = new THREE.Scene(); - - // Grid - - var size = 500, step = 100; - - var geometry = new THREE.Geometry(); - - for ( var i = - size; i <= size; i += step ) { - - geometry.vertices.push( new THREE.Vector3( - size, 0, i ) ); - geometry.vertices.push( new THREE.Vector3( size, 0, i ) ); - - geometry.vertices.push( new THREE.Vector3( i, 0, - size ) ); - geometry.vertices.push( new THREE.Vector3( i, 0, size ) ); - - } - - var material = new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.5 } ); - - var line = new THREE.Line( geometry, material ); - line.type = THREE.LinePieces; - scene.add( line ); - - // Spheres - - geometry = new THREE.SphereGeometry( 100, 26, 18 ); - var materialLambert = new THREE.MeshLambertMaterial( { color: 0xffffff, shading: THREE.FlatShading, overdraw: true } ); - - for ( var i = 0; i < 20; i ++ ) { - - sphere = new THREE.Mesh( geometry, materialLambert ); - - sphere.position.x = ( i % 5 ) * 200 - 400; - sphere.position.z = Math.floor( i / 5 ) * 200 - 400; - - scene.add( sphere ); - - } - - // Lights - - var ambientLight = new THREE.AmbientLight( Math.random() * 0x202020 ); - scene.add( ambientLight ); - - var directionalLight = new THREE.DirectionalLight( Math.random() * 0xffffff ); - directionalLight.position.set( 0, 1, 0 ); - scene.add( directionalLight ); - - var pointLight = new THREE.PointLight( 0xff0000, 1, 500 ); - scene.add( pointLight ); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild(stats.domElement); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - camera.lookAt( scene.position ); - - renderer.render( scene, camera ); - - } -}; - - -// https://github.com/mrdoob/three.js/blob/master/examples/canvas_sandbox.html - -()=>{ - var container, stats; - - var camera, scene, renderer, objects; - var pointLight; - - var sphere; - - var targetRotation = 0; - var targetRotationOnMouseDown = 0; - - var mouseX = 0; - var mouseXOnMouseDown = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var moveForward = false; - var moveBackwards = false; - var moveLeft = false; - var moveRight = false; - var moveUp = false; - var moveDown = false; - - var targetMoveLeft = false; - var targetMoveRight = false; - - var debugContext; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.set( 0, 150, 400 ); - camera.target = new THREE.Vector3( 0, 150, 0 ); - - scene = new THREE.Scene(); - - - // Grid - - var size = 500, step = 100; - - var geometry = new THREE.Geometry(); - - for ( var i = - size; i <= size; i += step ) { - - geometry.vertices.push( new THREE.Vector3( - size, 0, i ) ); - geometry.vertices.push( new THREE.Vector3( size, 0, i ) ); - - geometry.vertices.push( new THREE.Vector3( i, 0, - size ) ); - geometry.vertices.push( new THREE.Vector3( i, 0, size ) ); - - } - - var material = new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.5 } ); - - var line = new THREE.Line( geometry, material ); - line.type = THREE.LinePieces; - scene.add( line ); - - // Spheres - - objects = []; - - geometry = new THREE.IcosahedronGeometry( 100, 1 ); - - var materialBasic = new THREE.MeshBasicMaterial( { envMap: THREE.ImageUtils.loadTexture( 'textures/metal.jpg', new THREE.SphericalReflectionMapping() ), overdraw: true } ); - - for ( var i = 0; i < 10; i ++ ) { - - sphere = new THREE.Mesh( geometry, materialBasic ); - - sphere.position.x = Math.random() * 1000 - 500; - sphere.position.y = Math.random() * 1000 - 500; - sphere.position.z = Math.random() * 1000 - 500; - - sphere.rotation.x = Math.random() * 200 - 100; - sphere.rotation.y = Math.random() * 200 - 100; - sphere.rotation.z = Math.random() * 200 - 100; - - sphere.scale.x = sphere.scale.y = sphere.scale.z = Math.random() + 0.5; - - objects.push( sphere ); - - scene.add( sphere ); - - } - - // Lights - - var ambientLight = new THREE.AmbientLight( Math.random() * 0x202020 ); - scene.add( ambientLight ); - - var directionalLight = new THREE.DirectionalLight( Math.random() * 0xffffff ); - directionalLight.position.x = Math.random() - 0.5; - directionalLight.position.y = Math.random() - 0.5; - directionalLight.position.z = Math.random() - 0.5; - directionalLight.position.normalize(); - scene.add( directionalLight ); - - pointLight = new THREE.PointLight( 0xff0000, 1 ); - scene.add( pointLight ); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - var debugCanvas = document.createElement( 'canvas' ); - debugCanvas.width = 512; - debugCanvas.height = 512; - debugCanvas.style.position = 'absolute'; - debugCanvas.style.top = '0px'; - debugCanvas.style.left = '0px'; - - container.appendChild( debugCanvas ); - - debugContext = debugCanvas.getContext( '2d' ); - debugContext.setTransform( 1, 0, 0, 1, 256, 256 ); - debugContext.strokeStyle = '#000000'; - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild(stats.domElement); - - document.addEventListener( 'keydown', onDocumentKeyDown, false ); - document.addEventListener( 'keyup', onDocumentKeyUp, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onDocumentKeyDown( event ) { - - switch ( event.keyCode ) { - - case 38: moveForward = true; break; // up - case 40: moveBackwards = true; break; // down - case 37: moveLeft = true; break; // left - case 39: moveRight = true; break; // right - case 87: moveUp = true; break; // w - case 83: moveDown = true; break; // s - case 65: targetMoveLeft = true; break; // a - case 68: targetMoveRight = true; break; // d - - } - - } - - function onDocumentKeyUp( event ) { - - switch ( event.keyCode ) { - - case 38: moveForward = false; break; // up - case 40: moveBackwards = false; break; // down - case 37: moveLeft = false; break; // left - case 39: moveRight = false; break; // right - case 87: moveUp = false; break; // w - case 83: moveDown = false; break; // s - case 65: targetMoveLeft = false; break; // a - case 68: targetMoveRight = false; break; // d - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - if ( moveForward ) camera.position.z -= 10; - if ( moveBackwards ) camera.position.z += 10; - - if ( moveLeft ) camera.position.x -= 10; - if ( moveRight ) camera.position.x += 10; - - if ( moveUp ) camera.position.y += 10; - if ( moveDown ) camera.position.y -= 10; - - if ( targetMoveLeft ) camera.target.x -= 10; - if ( targetMoveRight ) camera.target.x += 10; - - camera.lookAt( camera.target ); - - debugContext.clearRect( -256, -256, 512, 512 ); - - debugContext.beginPath(); - - // center - debugContext.moveTo( -10, 0 ); - debugContext.lineTo( 10, 0 ); - debugContext.moveTo( 0, -10 ); - debugContext.lineTo( 0, 10 ); - - // camera - - debugContext.moveTo( camera.position.x * 0.1, camera.position.z * 0.1 ); - debugContext.lineTo( camera.target.x * 0.1, camera.target.z * 0.1 ); - debugContext.rect( camera.position.x * 0.1 - 5, camera.position.z * 0.1 - 5, 10, 10 ); - debugContext.rect( camera.target.x * 0.1 - 5, camera.target.z * 0.1 - 5, 10, 10 ); - debugContext.rect( - 50, - 50, 100, 100 ); - - for ( var i = 0, l = objects.length; i < l; i++ ) { - - var object = objects[ i ]; - - object.rotation.x += 0.01; - object.rotation.y += 0.005; - object.position.y = Math.sin( object.rotation.x ) * 200; - - debugContext.rect( object.position.x * 0.1 - 5, object.position.z * 0.1 - 5, 10, 10 ); - - } - - - debugContext.closePath(); - debugContext.stroke(); - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/css3d_molecules.html - -()=>{ - var camera, scene, renderer; - var controls; - var root; - - var objects = []; - var tmpVec1 = new THREE.Vector3(); - var tmpVec2 = new THREE.Vector3(); - var tmpVec3 = new THREE.Vector3(); - var tmpVec4 = new THREE.Vector3(); - - var visualizationType = 2; - - var MOLECULES = { - "Ethanol" :"ethanol.pdb", - "Aspirin" :"aspirin.pdb", - "Caffeine" :"caffeine.pdb", - "Nicotine" :"nicotine.pdb", - "LSD" :"lsd.pdb", - "Cocaine" :"cocaine.pdb", - "Cholesterol" :"cholesterol.pdb", - "Lycopene" :"lycopene.pdb", - "Glucose" : "glucose.pdb", - "Aluminium oxide":"Al2O3.pdb", - "Cubane" :"cubane.pdb", - "Copper" :"cu.pdb", - "Fluorite" :"caf2.pdb", - "Salt" :"nacl.pdb", - "YBCO superconductor":"ybco.pdb", - "Buckyball" : "buckyball.pdb", - //"Diamond" :"diamond.pdb", - "Graphite" :"graphite.pdb" - }; - - var loader = new THREE.PDBLoader(); - var colorSpriteMap = {}; - var baseSprite = document.createElement( 'img' ); - - var menu = document.getElementById( "menu" ); - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 5000 ); - camera.position.z = 1500; - - scene = new THREE.Scene(); - - root = new THREE.Object3D(); - scene.add( root ); - - // - - renderer = new THREE.CSS3DRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - document.getElementById( 'container' ).appendChild( renderer.domElement ); - - // - - controls = new THREE.TrackballControls( camera, renderer.domElement ); - controls.rotateSpeed = 0.5; - controls.addEventListener( 'change', render ); - - // - - baseSprite.onload = function () { - - loadMolecule( "models/molecules/caffeine.pdb" ); - createMenu(); - - }; - - baseSprite.src = 'textures/sprites/ball.png'; - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - // - - function generateButtonCallback( url ) { - - return function ( event ) { - - loadMolecule( url ); - - } - - } - - function createMenu() { - - for ( var m in MOLECULES ) { - - var button = document.createElement( 'button' ); - button.innerHTML = m; - menu.appendChild( button ); - - var url = "models/molecules/" + MOLECULES[ m ]; - - button.addEventListener( 'click', generateButtonCallback( url ), false ); - - } - - var b_a = document.getElementById( "b_a" ); - var b_b = document.getElementById( "b_b" ); - var b_ab = document.getElementById( "b_ab" ); - - b_a.addEventListener( 'click', function() { visualizationType = 0; showAtoms() } ); - b_b.addEventListener( 'click', function() { visualizationType = 1; showBonds() } ); - b_ab.addEventListener( 'click', function() { visualizationType = 2; showAtomsBonds() } ); - - } - - // - - function showAtoms() { - - for ( var i = 0; i < objects.length; i ++ ) { - - var object = objects[ i ]; - - if ( object instanceof THREE.CSS3DSprite ) { - - object.element.style.display = ""; - object.visible = true; - - } else { - - object.element.style.display = "none"; - object.visible = false; - - } - - } - - } - - function showBonds() { - - for ( var i = 0; i < objects.length; i ++ ) { - - var object = objects[ i ]; - - if ( object instanceof THREE.CSS3DSprite ) { - - object.element.style.display = "none"; - object.visible = false; - - } else { - - object.element.style.display = ""; - object.element.style.height = object.properties.bondLengthFull; - object.visible = true; - - } - - } - - } - - function showAtomsBonds() { - - for ( var i = 0; i < objects.length; i ++ ) { - - var object = objects[ i ]; - - object.element.style.display = ""; - object.visible = true; - - if ( ! ( object instanceof THREE.CSS3DSprite ) ) { - - object.element.style.height = object.properties.bondLengthShort; - - } - - } - - } - - // - - function colorify( ctx, width, height, color, a ) { - - var r = color.r; - var g = color.g; - var b = color.b; - - var imageData = ctx.getImageData( 0, 0, width, height ); - var data = imageData.data; - - for ( var y = 0; y < height; y ++ ) { - - for ( var x = 0; x < width; x ++ ) { - - var index = ( y * width + x ) * 4; - - data[ index ] *= r; - data[ index + 1 ] *= g; - data[ index + 2 ] *= b; - data[ index + 3 ] *= a; - - } - - } - - ctx.putImageData( imageData, 0, 0 ); - - } - - function imageToCanvas( image ) { - - var width = image.width; - var height = image.height; - - var canvas = document.createElement( 'canvas' ); - - canvas.width = width; - canvas.height = height; - - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, width, height ); - - return canvas; - - } - - // - - function loadMolecule( url ) { - - for ( var i = 0; i < objects.length; i ++ ) { - - var object = objects[ i ]; - - object.parent.remove( object ); - - if ( object.element.parentNode === renderer.cameraElement ) { - - renderer.cameraElement.removeChild( object.element ); - - } - - if ( object.properties.joint ) { - - object.properties.joint.parent.remove( object.properties.joint ); - - } - - } - - objects = []; - - loader.load( url, function ( geometry, geometryBonds ) { - - var offset = THREE.GeometryUtils.center( geometry ); - geometryBonds.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) ); - - for ( var i = 0; i < geometry.vertices.length; i ++ ) { - - var position = geometry.vertices[ i ]; - var color = geometry.colors[ i ]; - var element = geometry.elements[ i ]; - - if ( ! colorSpriteMap[ element ] ) { - - var canvas = imageToCanvas( baseSprite ); - var context = canvas.getContext( '2d' ); - - colorify( context, canvas.width, canvas.height, color, 1 ); - - var dataUrl = canvas.toDataURL(); - - colorSpriteMap[ element ] = dataUrl; - - } - - var colorSprite = colorSpriteMap[ element ]; - - var atom = document.createElement( 'img' ); - atom.src = colorSprite; - - var object = new THREE.CSS3DSprite( atom ); - object.position.copy( position ); - object.position.multiplyScalar( 75 ); - object.billboard = true; - - object.matrixAutoUpdate = false; - object.updateMatrix(); - - root.add( object ); - - objects.push( object ); - - } - - for ( var i = 0; i < geometryBonds.vertices.length; i += 2 ) { - - var start = geometryBonds.vertices[ i ]; - var end = geometryBonds.vertices[ i + 1 ]; - - start.multiplyScalar( 75 ); - end.multiplyScalar( 75 ); - - tmpVec1.subVectors( end, start ); - var bondLength = tmpVec1.length() - 50; - - - // - - var bond = document.createElement( 'div' ); - bond.className = "bond"; - bond.style.height = bondLength + "px"; - - var object = new THREE.CSS3DObject( bond ); - object.position.copy( start ); - object.position.lerp( end, 0.5 ); - - object.properties.bondLengthShort = bondLength + "px"; - object.properties.bondLengthFull = ( bondLength + 55 ) + "px"; - - // - - var axis = tmpVec2.set( 0, 1, 0 ).cross( tmpVec1 ); - var radians = Math.acos( tmpVec3.set( 0, 1, 0 ).dot( tmpVec4.copy( tmpVec1 ).normalize() ) ); - - var objMatrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians ); - object.matrix = objMatrix; - object.rotation.setEulerFromRotationMatrix( object.matrix, object.eulerOrder ); - - object.matrixAutoUpdate = false; - object.updateMatrix(); - - root.add( object ); - - objects.push( object ); - - // - - var bond = document.createElement( 'div' ); - bond.className = "bond"; - bond.style.height = bondLength + "px"; - - - // three-tests/ts: - // var joint = new THREE.Object3D( bond ); - // It seems a parameter "bond" is not used by Object3D. - var joint = new THREE.Object3D(); - - - joint.position.copy( start ); - joint.position.lerp( end, 0.5 ); - - joint.matrix.copy(objMatrix); - joint.rotation = new THREE.Euler().setFromRotationMatrix(joint.matrix, joint.eulerOrder); - - joint.matrixAutoUpdate = false; - joint.updateMatrix(); - - var object = new THREE.CSS3DObject( bond ); - object.rotation.y = Math.PI/2; - - object.matrixAutoUpdate = false; - object.updateMatrix(); - - object.properties.bondLengthShort = bondLength + "px"; - object.properties.bondLengthFull = ( bondLength + 55 ) + "px"; - - object.properties.joint = joint; - - joint.add( object ); - root.add( joint ); - - objects.push( object ); - - } - - //console.log( "CSS3DObjects:", objects.length ); - - switch ( visualizationType ) { - - case 0: showAtoms(); break; - case 1: showBonds(); break; - case 2: showAtomsBonds(); break; - - } - - render(); - - } ); - - - } - - // - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - render(); - - } - - function animate() { - - requestAnimationFrame( animate ); - controls.update(); - - var time = Date.now() * 0.0004; - - root.rotation.x = time; - root.rotation.y = time * 0.7; - - render(); - - } - - function render() { - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/css3d_panorama.html - -()=>{ - var camera, scene, renderer; - var geometry, material, mesh; - var target = new THREE.Vector3(); - - var lon = 90, lat = 0; - var phi = 0, theta = 0; - - var touchX, touchY; - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1000 ); - - scene = new THREE.Scene(); - - var sides = [ - { - url: 'textures/cube/Bridge2/posx.jpg', - position: new THREE.Vector3( -512, 0, 0 ), - rotation: new THREE.Vector3( 0, Math.PI / 2, 0 ) - }, - { - url: 'textures/cube/Bridge2/negx.jpg', - position: new THREE.Vector3( 512, 0, 0 ), - rotation: new THREE.Vector3( 0, -Math.PI / 2, 0 ) - }, - { - url: 'textures/cube/Bridge2/posy.jpg', - position: new THREE.Vector3( 0, 512, 0 ), - rotation: new THREE.Vector3( Math.PI / 2, 0, Math.PI ) - }, - { - url: 'textures/cube/Bridge2/negy.jpg', - position: new THREE.Vector3( 0, -512, 0 ), - rotation: new THREE.Vector3( - Math.PI / 2, 0, Math.PI ) - }, - { - url: 'textures/cube/Bridge2/posz.jpg', - position: new THREE.Vector3( 0, 0, 512 ), - rotation: new THREE.Vector3( 0, Math.PI, 0 ) - }, - { - url: 'textures/cube/Bridge2/negz.jpg', - position: new THREE.Vector3( 0, 0, -512 ), - rotation: new THREE.Vector3( 0, 0, 0 ) - } - ]; - - for ( var i = 0; i < sides.length; i ++ ) { - - var side = sides[ i ]; - - var element = document.createElement( 'img' ); - element.width = 1026; // 2 pixels extra to close the gap. - element.src = side.url; - - var object = new THREE.CSS3DObject( element ); - object.position = side.position; - object.rotation = side.rotation; - scene.add( object ); - - } - - renderer = new THREE.CSS3DRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - document.body.appendChild( renderer.domElement ); - - // - - document.addEventListener( 'mousedown', onDocumentMouseDown, false ); - document.addEventListener( 'mousewheel', onDocumentMouseWheel, false ); - - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onDocumentMouseDown( event ) { - - event.preventDefault(); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'mouseup', onDocumentMouseUp, false ); - - } - - function onDocumentMouseMove( event ) { - - var movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0; - var movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0; - - lon -= movementX * 0.1; - lat += movementY * 0.1; - - } - - function onDocumentMouseUp( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove ); - document.removeEventListener( 'mouseup', onDocumentMouseUp ); - - } - - function onDocumentMouseWheel( event ) { - - camera.fov -= event.wheelDeltaY * 0.05; - camera.updateProjectionMatrix(); - - } - - function onDocumentTouchStart( event ) { - - event.preventDefault(); - - var touch = event.touches[ 0 ]; - - touchX = touch.screenX; - touchY = touch.screenY; - - } - - function onDocumentTouchMove( event ) { - - event.preventDefault(); - - var touch = event.touches[ 0 ]; - - lon -= ( touch.screenX - touchX ) * 0.1; - lat += ( touch.screenY - touchY ) * 0.1; - - touchX = touch.screenX; - touchY = touch.screenY; - - } - - function animate() { - - requestAnimationFrame( animate ); - - lon += 0.1; - lat = Math.max( - 85, Math.min( 85, lat ) ); - phi = THREE.Math.degToRad( 90 - lat ); - theta = THREE.Math.degToRad( lon ); - - target.x = Math.sin( phi ) * Math.cos( theta ); - target.y = Math.cos( phi ); - target.z = Math.sin( phi ) * Math.sin( theta ); - - camera.lookAt( target ); - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/css3d_periodictable.html - -()=>{ - - var table: any[][] = [ - [ "H", "Hydrogen", "1.00794", 1, 1 ], - [ "He", "Helium", "4.002602", 18, 1 ], - [ "Li", "Lithium", "6.941", 1, 2 ], - [ "Be", "Beryllium", "9.012182", 2, 2 ], - [ "B", "Boron", "10.811", 13, 2 ], - [ "C", "Carbon", "12.0107", 14, 2 ], - [ "N", "Nitrogen", "14.0067", 15, 2 ], - [ "O", "Oxygen", "15.9994", 16, 2 ], - [ "F", "Fluorine", "18.9984032", 17, 2 ], - [ "Ne", "Neon", "20.1797", 18, 2 ], - [ "Na", "Sodium", "22.98976...", 1, 3 ], - [ "Mg", "Magnesium", "24.305", 2, 3 ], - [ "Al", "Aluminium", "26.9815386", 13, 3 ], - [ "Si", "Silicon", "28.0855", 14, 3 ], - [ "P", "Phosphorus", "30.973762", 15, 3 ], - [ "S", "Sulfur", "32.065", 16, 3 ], - [ "Cl", "Chlorine", "35.453", 17, 3 ], - [ "Ar", "Argon", "39.948", 18, 3 ], - [ "K", "Potassium", "39.948", 1, 4 ], - [ "Ca", "Calcium", "40.078", 2, 4 ], - [ "Sc", "Scandium", "44.955912", 3, 4 ], - [ "Ti", "Titanium", "47.867", 4, 4 ], - [ "V", "Vanadium", "50.9415", 5, 4 ], - [ "Cr", "Chromium", "51.9961", 6, 4 ], - [ "Mn", "Manganese", "54.938045", 7, 4 ], - [ "Fe", "Iron", "55.845", 8, 4 ], - [ "Co", "Cobalt", "58.933195", 9, 4 ], - [ "Ni", "Nickel", "58.6934", 10, 4 ], - [ "Cu", "Copper", "63.546", 11, 4 ], - [ "Zn", "Zinc", "65.38", 12, 4 ], - [ "Ga", "Gallium", "69.723", 13, 4 ], - [ "Ge", "Germanium", "72.63", 14, 4 ], - [ "As", "Arsenic", "74.9216", 15, 4 ], - [ "Se", "Selenium", "78.96", 16, 4 ], - [ "Br", "Bromine", "79.904", 17, 4 ], - [ "Kr", "Krypton", "83.798", 18, 4 ], - [ "Rb", "Rubidium", "85.4678", 1, 5 ], - [ "Sr", "Strontium", "87.62", 2, 5 ], - [ "Y", "Yttrium", "88.90585", 3, 5 ], - [ "Zr", "Zirconium", "91.224", 4, 5 ], - [ "Nb", "Niobium", "92.90628", 5, 5 ], - [ "Mo", "Molybdenum", "95.96", 6, 5 ], - [ "Tc", "Technetium", "(98)", 7, 5 ], - [ "Ru", "Ruthenium", "101.07", 8, 5 ], - [ "Rh", "Rhodium", "102.9055", 9, 5 ], - [ "Pd", "Palladium", "106.42", 10, 5 ], - [ "Ag", "Silver", "107.8682", 11, 5 ], - [ "Cd", "Cadmium", "112.411", 12, 5 ], - [ "In", "Indium", "114.818", 13, 5 ], - [ "Sn", "Tin", "118.71", 14, 5 ], - [ "Sb", "Antimony", "121.76", 15, 5 ], - [ "Te", "Tellurium", "127.6", 16, 5 ], - [ "I", "Iodine", "126.90447", 17, 5 ], - [ "Xe", "Xenon", "131.293", 18, 5 ], - [ "Cs", "Caesium", "132.9054", 1, 6 ], - [ "Ba", "Barium", "132.9054", 2, 6 ], - [ "La", "Lanthanum", "138.90547", 4, 9 ], - [ "Ce", "Cerium", "140.116", 5, 9 ], - [ "Pr", "Praseodymium", "140.90765", 6, 9 ], - [ "Nd", "Neodymium", "144.242", 7, 9 ], - [ "Pm", "Promethium", "(145)", 8, 9 ], - [ "Sm", "Samarium", "150.36", 9, 9 ], - [ "Eu", "Europium", "151.964", 10, 9 ], - [ "Gd", "Gadolinium", "157.25", 11, 9 ], - [ "Tb", "Terbium", "158.92535", 12, 9 ], - [ "Dy", "Dysprosium", "162.5", 13, 9 ], - [ "Ho", "Holmium", "164.93032", 14, 9 ], - [ "Er", "Erbium", "167.259", 15, 9 ], - [ "Tm", "Thulium", "168.93421", 16, 9 ], - [ "Yb", "Ytterbium", "173.054", 17, 9 ], - [ "Lu", "Lutetium", "174.9668", 18, 9 ], - [ "Hf", "Hafnium", "178.49", 4, 6 ], - [ "Ta", "Tantalum", "180.94788", 5, 6 ], - [ "W", "Tungsten", "183.84", 6, 6 ], - [ "Re", "Rhenium", "186.207", 7, 6 ], - [ "Os", "Osmium", "190.23", 8, 6 ], - [ "Ir", "Iridium", "192.217", 9, 6 ], - [ "Pt", "Platinum", "195.084", 10, 6 ], - [ "Au", "Gold", "196.966569", 11, 6 ], - [ "Hg", "Mercury", "200.59", 12, 6 ], - [ "Tl", "Thallium", "204.3833", 13, 6 ], - [ "Pb", "Lead", "207.2", 14, 6 ], - [ "Bi", "Bismuth", "208.9804", 15, 6 ], - [ "Po", "Polonium", "(209)", 16, 6 ], - [ "At", "Astatine", "(210)", 17, 6 ], - [ "Rn", "Radon", "(222)", 18, 6 ], - [ "Fr", "Francium", "(223)", 1, 7 ], - [ "Ra", "Radium", "(226)", 2, 7 ], - [ "Ac", "Actinium", "(227)", 4, 10 ], - [ "Th", "Thorium", "232.03806", 5, 10 ], - [ "Pa", "Protactinium", "231.0588", 6, 10 ], - [ "U", "Uranium", "238.02891", 7, 10 ], - [ "Np", "Neptunium", "(237)", 8, 10 ], - [ "Pu", "Plutonium", "(244)", 9, 10 ], - [ "Am", "Americium", "(243)", 10, 10 ], - [ "Cm", "Curium", "(247)", 11, 10 ], - [ "Bk", "Berkelium", "(247)", 12, 10 ], - [ "Cf", "Californium", "(251)", 13, 10 ], - [ "Es", "Einstenium", "(252)", 14, 10 ], - [ "Fm", "Fermium", "(257)", 15, 10 ], - [ "Md", "Mendelevium", "(258)", 16, 10 ], - [ "No", "Nobelium", "(259)", 17, 10 ], - [ "Lr", "Lawrencium", "(262)", 18, 10 ], - [ "Rf", "Rutherfordium", "(267)", 4, 7 ], - [ "Db", "Dubnium", "(268)", 5, 7 ], - [ "Sg", "Seaborgium", "(271)", 6, 7 ], - [ "Bh", "Bohrium", "(272)", 7, 7 ], - [ "Hs", "Hassium", "(270)", 8, 7 ], - [ "Mt", "Meitnerium", "(276)", 9, 7 ], - [ "Ds", "Darmstadium", "(281)", 10, 7 ], - [ "Rg", "Roentgenium", "(280)", 11, 7 ], - [ "Cn", "Copernicium", "(285)", 12, 7 ], - [ "Uut", "Unutrium", "(284)", 13, 7 ], - [ "Fl", "Flerovium", "(289)", 14, 7 ], - [ "Uup", "Ununpentium", "(288)", 15, 7 ], - [ "Lv", "Livermorium", "(293)", 16, 7 ], - [ "Uus", "Ununseptium", "(294)", 17, 7 ], - [ "Uuo", "Ununoctium", "(294)", 18, 7 ] - ]; - - var camera, scene, renderer; - var controls; - - var objects = []; - var targets = { table: [], sphere: [], helix: [], grid: [] }; - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 5000 ); - camera.position.z = 1800; - - scene = new THREE.Scene(); - - for ( var i = 0; i < table.length; i ++ ) { - - var item = table[ i ]; - - var element = document.createElement( 'div' ); - element.className = 'element'; - element.style.backgroundColor = 'rgba(0,127,127,' + ( Math.random() * 0.5 + 0.25 ) + ')'; - - var number = document.createElement( 'div' ); - number.className = 'number'; - number.textContent = (i + 1).toString(); - element.appendChild( number ); - - var symbol = document.createElement( 'div' ); - symbol.className = 'symbol'; - symbol.textContent = item[ 0 ]; - element.appendChild( symbol ); - - var details = document.createElement( 'div' ); - details.className = 'details'; - details.innerHTML = item[ 1 ] + '
    ' + item[ 2 ]; - element.appendChild( details ); - - var object = new THREE.CSS3DObject( element ); - object.position.x = Math.random() * 4000 - 2000; - object.position.y = Math.random() * 4000 - 2000; - object.position.z = Math.random() * 4000 - 2000; - scene.add( object ); - - objects.push( object ); - - } - - // table - - for ( var i = 0; i < objects.length; i ++ ) { - - var item = table[ i ]; - - var object2 = new THREE.Object3D(); - object2.position.x = ( item[ 3 ] * 160 ) - 1540; - object2.position.y = - ( item[ 4 ] * 200 ) + 1100; - - targets.table.push( object ); - - } - - // sphere - - var vector = new THREE.Vector3(); - - for ( var i = 0, l = objects.length; i < l; i ++ ) { - - var phi = Math.acos( -1 + ( 2 * i ) / l ); - var theta = Math.sqrt( l * Math.PI ) * phi; - - var object3 = new THREE.Object3D(); - - object3.position.x = 1000 * Math.cos( theta ) * Math.sin( phi ); - object3.position.y = 1000 * Math.sin( theta ) * Math.sin( phi ); - object3.position.z = 1000 * Math.cos( phi ); - - vector.copy( object3.position ).multiplyScalar( 2 ); - - object3.lookAt( vector ); - - targets.sphere.push( object3 ); - - } - - // helix - - var vector = new THREE.Vector3(); - - for ( var i = 0, l = objects.length; i < l; i ++ ) { - - var phi = i * 0.175 + Math.PI; - - var object4 = new THREE.Object3D(); - - object4.position.x = 1100 * Math.sin( phi ); - object4.position.y = - ( i * 8 ) + 450; - object4.position.z = 1100 * Math.cos( phi ); - - vector.copy( object4.position ); - vector.x *= 2; - vector.z *= 2; - - object4.lookAt( vector ); - - targets.helix.push( object4 ); - - } - - // grid - - for ( var i = 0; i < objects.length; i ++ ) { - - var object5 = new THREE.Object3D(); - - object5.position.x = ( ( i % 5 ) * 400 ) - 800; - object5.position.y = ( - ( Math.floor( i / 5 ) % 5 ) * 400 ) + 800; - object5.position.z = ( Math.floor( i / 25 ) ) * 1000 - 2000; - - targets.grid.push( object5 ); - - } - - // - - renderer = new THREE.CSS3DRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.domElement.style.position = 'absolute'; - document.getElementById( 'container' ).appendChild( renderer.domElement ); - - // - - controls = new THREE.TrackballControls( camera, renderer.domElement ); - controls.rotateSpeed = 0.5; - controls.addEventListener( 'change', render ); - - var button = document.getElementById( 'table' ); - button.addEventListener( 'click', function ( event ) { - - transform( targets.table, 2000 ); - - }, false ); - - var button = document.getElementById( 'sphere' ); - button.addEventListener( 'click', function ( event ) { - - transform( targets.sphere, 2000 ); - - }, false ); - - var button = document.getElementById( 'helix' ); - button.addEventListener( 'click', function ( event ) { - - transform( targets.helix, 2000 ); - - }, false ); - - var button = document.getElementById( 'grid' ); - button.addEventListener( 'click', function ( event ) { - - transform( targets.grid, 2000 ); - - }, false ); - - transform( targets.table, 5000 ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function transform( targets, duration ) { - - TWEEN.removeAll(); - - for ( var i = 0; i < objects.length; i ++ ) { - - var object = objects[ i ]; - var target = targets[ i ]; - - new TWEEN.Tween( object.position ) - .to( { x: target.position.x, y: target.position.y, z: target.position.z }, Math.random() * duration + duration ) - .easing( TWEEN.Easing.Exponential.InOut ) - .start(); - - new TWEEN.Tween( object.rotation ) - .to( { x: target.rotation.x, y: target.rotation.y, z: target.rotation.z }, Math.random() * duration + duration ) - .easing( TWEEN.Easing.Exponential.InOut ) - .start(); - - } - - new TWEEN.Tween( this ) - .to( {}, duration * 2 ) - .onUpdate( render ) - .start(); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function animate() { - - requestAnimationFrame( animate ); - - TWEEN.update(); - controls.update(); - - } - - function render() { - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/css3d_sandbox.html - -()=>{ - var camera, scene, renderer; - var geometry, material, mesh; - - var scene2, renderer2; - - var controls; - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.set( 200, 200, 200 ); - - controls = new THREE.TrackballControls( camera ); - - controls.rotateSpeed = 1.0; - controls.zoomSpeed = 1.2; - controls.panSpeed = 0.8; - - controls.noZoom = false; - controls.noPan = false; - - controls.staticMoving = false; - controls.dynamicDampingFactor = 0.3; - - controls.keys = [ 65, 83, 68 ]; - - scene = new THREE.Scene(); - - geometry = new THREE.CubeGeometry( 200, 200, 200 ); - material = new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true, wireframeLinewidth: 1 } ); - - mesh = new THREE.Mesh( geometry, material ); - scene.add( mesh ); - - renderer = new THREE.CanvasRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - document.body.appendChild( renderer.domElement ); - - // - - scene2 = new THREE.Scene(); - - for ( var i = 0; i < 20; i ++ ) { - - var element = document.createElement( 'div' ); - element.style.width = '100px'; - element.style.height = '100px'; - element.style.background = new THREE.Color( Math.random() * 0xffffff ).getStyle(); - - var object = new THREE.CSS3DObject( element ); - object.position.x = Math.random() * 200 - 100; - object.position.y = Math.random() * 200 - 100; - object.position.z = Math.random() * 200 - 100; - object.scale.x = Math.random() + 0.5; - object.scale.y = Math.random() + 0.5; - scene2.add( object ); - - } - - // - - renderer2 = new THREE.CSS3DRenderer(); - renderer2.setSize( window.innerWidth, window.innerHeight ); - renderer2.domElement.style.position = 'absolute'; - renderer2.domElement.style.top = 0; - document.body.appendChild( renderer2.domElement ); - - } - - function animate() { - - requestAnimationFrame( animate ); - - controls.update(); - - renderer.render( scene, camera ); - renderer2.render( scene2, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/css3d_youtube.html - -()=>{ - var camera, scene, renderer; - var objects = [], player; - - var auto = true; - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 5000 ); - camera.position.y = - 25; - - scene = new THREE.Scene(); - - renderer = new THREE.CSS3DRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.domElement.style.position = 'absolute'; - renderer.domElement.style.top = 0; - document.getElementById( 'container' ).appendChild( renderer.domElement ); - - // - - var query = document.getElementById( 'query' ); - query.addEventListener( 'keyup', function ( event:KeyboardEvent ) { - - if ( event.keyCode === 13 ) { - - search( query.value ); - - } - - }, false ); - - var button = document.getElementById( 'button' ); - button.addEventListener( 'click', function ( event ) { - - search( query.value ); - - }, false ); - - if ( window.location.hash.length > 0 ) { - - query.value = window.location.hash.substr( 1 ); - - } - - search( query.value ); - - document.body.addEventListener( 'mousewheel', onMouseWheel, false ); - - document.body.addEventListener( 'click', function ( event ) { - - auto = true; - - if ( player !== undefined ) { - - player.parentNode.removeChild( player ); - player = undefined; - - } - - new TWEEN.Tween( camera.position ) - .to( { x: 0, y: - 25 }, 1500 ) - .easing( TWEEN.Easing.Exponential.Out ) - .start(); - - }, false ); - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function search( query ) { - - window.location.hash = query; - - for ( var i = 0, l = objects.length; i < l; i ++ ) { - - var object = objects[ i ]; - var delay = Math.random() * 1000; - - new TWEEN.Tween( object.position ) - .to( { y: - 3000 }, 1000 ) - .delay( delay ) - .easing( TWEEN.Easing.Exponential.In ) - .start(); - - new TWEEN.Tween( object ) - .to( {}, 2000 ) - .delay( delay ) - .onComplete( function () { - - scene.remove( this ); - renderer.cameraElement.removeChild( this.element ); - - var index = objects.indexOf( this ); - objects.splice( index, 1 ); - - } ) - .start(); - - } - - var request = new XMLHttpRequest(); - request.addEventListener( 'load', onData, false ); - request.open( 'GET', 'https://gdata.youtube.com/feeds/api/videos?v=2&alt=json&max-results=50&q=' + query, true ); - request.send( null ); - - } - - function onData( event ) { - - var data = JSON.parse( event.target.responseText ); - var entries = data.feed.entry; - - // console.log( entries ); - - for ( var i = 0; i < entries.length; i ++ ) { - - var entry = entries[ i ]; - - var element = document.createElement( 'div' ); - element.style.width = '480px'; - element.style.height = '360px'; - - var image = document.createElement( 'img' ); - image.addEventListener( 'load', function ( event ) { - - var object = this.properties.object; - var button = this.properties.button; - - button.style.visibility = 'visible'; - - new TWEEN.Tween( object.position ) - .to( { y: Math.random() * 2000 - 1000 }, 2000 ) - .easing( TWEEN.Easing.Exponential.Out ) - .start(); - - }, false ); - image.style.position = 'absolute'; - image.style.width = '480px'; - image.style.height = '360px'; - image.src = entry.media$group.media$thumbnail[ 2 ].url; - element.appendChild( image ); - - var button = document.createElement( 'img' ); - button.style.position = 'absolute'; - button.style.left = ( ( 480 - 86 ) / 2 ) + 'px'; - button.style.top = ( ( 360 - 61 ) / 2 ) + 'px'; - button.style.visibility = 'hidden'; - button.style.WebkitFilter = 'grayscale()'; - button.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFYAAAA9CAYAAAA3ZZ5uAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wLBQ0uMbsnLZIAAAbXSURBVHja7ZxvbBvlHcc/z/maf4PGg9FtbaZeS2I1iUgP1q7QEmFpmxB7AYxXk/aCvETaC/Zy2qSpk7apL/YCTbCyoU0uUAGdRv8uVCorzsQGSRu4tFoahbYxpEkKayvHaRInvnt+e5HEzb92cez4bHRfyS/ufPbd8/H3vs/vZ99Zkac+erB5OxhhAG1oS4myZp5RYVFi5/PeSpSFwrrd84I4QDLH93RAksusjwM89PH5DgoglcvGZ+ymp8RQTytRliCWUsriyywhCTiiJKFQCaUmXtjRfXk0b7Bnv7211vUq2xSqDaVsAoGII0jMDE3F7gT5tmA/tJue0qiYgnBAczkzkzSQtoed3qMrBvt+y7ZnlTJiAb6VGFi3PXqu78D/Bft+y7ZnhQBqbhPVUrgLwP6rsXGza+IEp3/usWC62HsuXPh0bp05f4NMSGKgwhKwylXhTIgXgB8ucezp5sh2MJyAUR7O1cr67qxrs471kDZF4NW8slbpNuBXC8CKNmxRAZz8LKuiS8BqJBoYNm9FF2Rs+7b6x8CIB1wKIR39Qd/FDnOmyFU2gV0LlbQ2MAPW02Ip5UPAVlXB44/Dxk0zy8NDcOYMDA+XcScmVjZjtWD7URFU79zJzp//gtraWgBGR0cZGBhgsLMT3nyjLAGLYGfBimhbKL5jv7FnTxYqQG1tLbZtE4lE6N+1i5Hjx5n+x7vlBVjkFlitlC8t7Ncbm5ZdX1NTg23bNDc30//MM3wWj5P+66HyADzLUv1ty5bN2lAJP46h9bXXuW/XrhVt29/fT197O96Rw0iJAza0WKYnYkkZdAaRSIRIJMLlJ5+k7+23mTx+vGQBi4hlagiL+FNqrWavW7du5VvPP0//E0+QaG9n4sQJZGiotNIAwqaA7RNXRITVfKimadLU1IRlWfRGowydepfMyZPo0gFsm54mjPKLbH4vr6mpYceOHTQ0NHDu0T1cO3aMqXdOwuSkz1lA2NQitn/7L8wHWltbS2trK4OWRX80SrL9Habicf8AC7apfexkRaCQ+V5XV0ddXR399fVc2rObsTcPkTl/3pcz0dRI2D+wwlpMnA0NDWzatIlPGhsZPHWK1FuH0DduFHNoYVOD7df3L3qNwAJUV1fT0tJCfX09Zx94gKuxA0x1dhVv8tIiPkaBRkSv7fcR1VW0fv97DNTfz5lf/5Z0vKMoYzNmcs6vhxTtYVkWj+z9JcbGjUUZm6+O1SLoIs6eVckUjKYoxph9joK1y9jFutrZyennfkJmbKwo+/O53JI1z9jpVIre2Ks4v3+pqGPzNwq0Rmu9hi7tous3+7hxoa/oYzO1f4ZFa1kTsDevDOG8+AcuHj7q29jMSddzKkOGL22tlsI69ubQEM6L+30FCjDlacesMFTSrzSYiQKvAECHuXj4GD0vvVwSX21VGCo5O3mJj2BX79jp1Bi9rx2k99WDZMZuUkoytXgOGNFyAjudGuOz0+/Rte93JQcUIK11whStkn79MuNpjed5OQG9ePQEPfv/VJJA51SJSpifuy5fM82Sj4Le19+gZ/8rJQ10TtdcF/MejLhfTYKnPTzPvb1Dx8YYfO+f9Lz8Z8aHr1Iuugcjbn7iprnfqPblAEa6urnvwe1LZ/nhET4/+zHn/vgXxkfKB+icLrlpzEtpN7Glwp8D+M/BQ3yzdTdfjTRkgQ78/STnX4lRzrqUdhMK4Gd33SvrlH/XFmx4aMa1X3zUQ7krI8K+m9eVCTCudXK9EfLtJ5qr3eUPdE7jWidh7opuEUeLRAmUv0ScLNgJTydqlBFAKYAmPJ3Igp0UHB1c0F0QTQq3HDuQmXY2hkIBlQJoIDPtwLwb6H687m7ZYJgBmTx0Q3scyKTUrckLmBKJC8EElo9S4mXv7MyC/UJ7RzaoUNRUwV10q9V1rbOdjXGr/pqMXRMvoLNK/Vd7uFqOLAHbDaMj4sZcCcqDXOWKcEUysX+T/nQJWADPY29Cu8kAVW5KaDfpeeydv25BjTWIO3qvClVVoKJfCRqGFemyznAd77kPJN1xW7AAV8TtuAvDAuz1Adw7nv4JcbkmXtuHXnrJf8Is2xVcEffoelQ4KfrhdUpRHQBeAPS6aC5LJpny3B91ytRby213x9rqEaoekxB7K1DRShTzHVyBolIpalB8mUu0lGjGZi+DSolmAo0nxDI6/dNuyP1/t+ZrN1WbBSwxmN9AWCgsEbGVUuEaFKFF8AHuXrTsd7xMiTA1+3P/hGjmF5jjs8sewgQCQgJFQkQchUoqTXyatHMnoDmBXYm+w7rtIULhRfBBsbibK5nuTkQcpVQSIQEkAARJGlo5ChLzy6dc9T9S8wu+HzDbBQAAAABJRU5ErkJggg=='; - element.appendChild( button ); - - var blocker = document.createElement( 'div' ); - blocker.style.position = 'absolute'; - blocker.style.width = '480px'; - blocker.style.height = '360px'; - blocker.style.background = 'rgba(0,0,0,0.5)'; - blocker.style.cursor = 'pointer'; - element.appendChild( blocker ); - - var object = new THREE.CSS3DObject( element ); - object.position.x = Math.random() * 4000 - 2000; - // object.position.y = Math.random() * 2000 - 1000; - object.position.y = 3000; - object.position.z = Math.random() * - 5000; - scene.add( object ); - - objects.push( object ); - - // - - var properties = { data: entry, blocker: blocker, button: button, object: object } - - element["properties"] = properties; - image["properties"] = properties; - - element.addEventListener( 'mouseover', function () { - - this.properties.button.style.WebkitFilter = ''; - this.properties.blocker.style.background = 'rgba(0,0,0,0)'; - - }, false ); - - element.addEventListener( 'mouseout', function () { - - this.properties.button.style.WebkitFilter = 'grayscale()'; - this.properties.blocker.style.background = 'rgba(0,0,0,0.75)'; - - }, false ); - - element.addEventListener( 'click', function ( event ) { - - event.stopPropagation(); - - var data = this.properties.data; - var object = this.properties.object; - - auto = false; - - if ( player !== undefined ) { - - player.parentNode.removeChild( player ); - player = undefined; - - } - - player = document.createElement( 'iframe' ); - player.style.position = 'absolute'; - player.style.width = '480px'; - player.style.height = '360px'; - player.style.border = '0px'; - player.src = 'http://www.youtube.com/embed/' + data.id.$t.split( ':' ).pop() + '?rel=0&autoplay=1&controls=1&showinfo=0'; - this.appendChild( player ); - - // - - var prev = object.position.z + 400; - - new TWEEN.Tween( camera.position ) - .to( { x: object.position.x, y: object.position.y - 25 }, 1500 ) - .easing( TWEEN.Easing.Exponential.Out ) - .start(); - - new TWEEN.Tween( { value: prev } ) - .to( { value: 0 }, 2000 ) - .onUpdate( function () { - - move( this.value - prev ); - prev = this.value; - - } ) - .easing( TWEEN.Easing.Exponential.Out ) - .start(); - - }, false ); - - } - - } - - function move( delta ) { - - for ( var i = 0; i < objects.length; i ++ ) { - - var object = objects[ i ]; - - object.position.z += delta; - - if ( object.position.z > 0 ) { - - object.position.z -= 5000; - - } else if ( object.position.z < - 5000 ) { - - object.position.z += 5000; - - } - - } - - } - - function onMouseWheel( event ) { - - move( event.wheelDelta ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function animate() { - - requestAnimationFrame( animate ); - - TWEEN.update(); - - if ( auto === true ) { - - move( 1 ); - - } - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/misc_controls_fly.html - -()=>{ - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var radius = 6371; - var tilt = 0.41; - var rotationSpeed = 0.02; - - var cloudsScale = 1.005; - var moonScale = 0.23; - - var MARGIN = 0; - var SCREEN_HEIGHT = window.innerHeight - MARGIN * 2; - var SCREEN_WIDTH = window.innerWidth; - - var container, stats; - var camera, controls, scene, sceneCube, renderer; - var geometry, meshPlanet, meshClouds, meshMoon; - var dirLight, pointLight, ambientLight; - - var d, dPlanet, dMoon, dMoonVec = new THREE.Vector3(); - - var clock = new THREE.Clock(); - - var composer; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 25, SCREEN_WIDTH / SCREEN_HEIGHT, 50, 1e7 ); - camera.position.z = radius * 5; - - scene = new THREE.Scene(); - scene.fog = new THREE.FogExp2( 0x000000, 0.00000025 ); - - controls = new THREE.FlyControls( camera ); - - controls.movementSpeed = 1000; - controls.domElement = container; - controls.rollSpeed = Math.PI / 24; - controls.autoForward = false; - controls.dragToLook = false; - - dirLight = new THREE.DirectionalLight( 0xffffff ); - dirLight.position.set( -1, 0, 1 ).normalize(); - scene.add( dirLight ); - - ambientLight = new THREE.AmbientLight( 0x000000 ); - scene.add( ambientLight ); - - var planetTexture = THREE.ImageUtils.loadTexture( "textures/planets/earth_atmos_2048.jpg" ); - var cloudsTexture = THREE.ImageUtils.loadTexture( "textures/planets/earth_clouds_1024.png" ); - var normalTexture = THREE.ImageUtils.loadTexture( "textures/planets/earth_normal_2048.jpg" ); - var specularTexture = THREE.ImageUtils.loadTexture( "textures/planets/earth_specular_2048.jpg" ); - - var moonTexture = THREE.ImageUtils.loadTexture( "textures/planets/moon_1024.jpg" ); - - var shader = THREE.ShaderLib[ "normalmap" ]; - var uniforms = THREE.UniformsUtils.clone( shader.uniforms ); - - uniforms[ "tNormal" ].value = normalTexture; - uniforms[ "uNormalScale" ].value.set( 0.85, 0.85 ); - - uniforms[ "tDiffuse" ].value = planetTexture; - uniforms[ "tSpecular" ].value = specularTexture; - - uniforms[ "enableAO" ].value = false; - uniforms[ "enableDiffuse" ].value = true; - uniforms[ "enableSpecular" ].value = true; - - uniforms[ "uDiffuseColor" ].value.setHex( 0xffffff ); - uniforms[ "uSpecularColor" ].value.setHex( 0x333333 ); - uniforms[ "uAmbientColor" ].value.setHex( 0x000000 ); - - uniforms[ "uShininess" ].value = 15; - - var parameters = { - - fragmentShader: shader.fragmentShader, - vertexShader: shader.vertexShader, - uniforms: uniforms, - lights: true, - fog: true - - }; - - var materialNormalMap = new THREE.ShaderMaterial( parameters ); - - // planet - - geometry = new THREE.SphereGeometry( radius, 100, 50 ); - geometry.computeTangents(); - - meshPlanet = new THREE.Mesh( geometry, materialNormalMap ); - meshPlanet.rotation.y = 0; - meshPlanet.rotation.z = tilt; - scene.add( meshPlanet ); - - // clouds - - var materialClouds = new THREE.MeshLambertMaterial( { color: 0xffffff, map: cloudsTexture, transparent: true } ); - - meshClouds = new THREE.Mesh( geometry, materialClouds ); - meshClouds.scale.set( cloudsScale, cloudsScale, cloudsScale ); - meshClouds.rotation.z = tilt; - scene.add( meshClouds ); - - // moon - - var materialMoon = new THREE.MeshPhongMaterial( { color: 0xffffff, map: moonTexture } ); - - meshMoon = new THREE.Mesh( geometry, materialMoon ); - meshMoon.position.set( radius * 5, 0, 0 ); - meshMoon.scale.set( moonScale, moonScale, moonScale ); - scene.add( meshMoon ); - - // stars - - var i, r = radius, starsGeometry = [ new THREE.Geometry(), new THREE.Geometry() ]; - - for ( i = 0; i < 250; i ++ ) { - - var vertex = new THREE.Vector3(); - vertex.x = Math.random() * 2 - 1; - vertex.y = Math.random() * 2 - 1; - vertex.z = Math.random() * 2 - 1; - vertex.multiplyScalar( r ); - - starsGeometry[ 0 ].vertices.push( vertex ); - - } - - for ( i = 0; i < 1500; i ++ ) { - - var vertex = new THREE.Vector3(); - vertex.x = Math.random() * 2 - 1; - vertex.y = Math.random() * 2 - 1; - vertex.z = Math.random() * 2 - 1; - vertex.multiplyScalar( r ); - - starsGeometry[ 1 ].vertices.push( vertex ); - - } - - var stars; - var starsMaterials = [ - new THREE.ParticleSystemMaterial( { color: 0x555555, size: 2, sizeAttenuation: false } ), - new THREE.ParticleSystemMaterial( { color: 0x555555, size: 1, sizeAttenuation: false } ), - new THREE.ParticleSystemMaterial( { color: 0x333333, size: 2, sizeAttenuation: false } ), - new THREE.ParticleSystemMaterial( { color: 0x3a3a3a, size: 1, sizeAttenuation: false } ), - new THREE.ParticleSystemMaterial( { color: 0x1a1a1a, size: 2, sizeAttenuation: false } ), - new THREE.ParticleSystemMaterial( { color: 0x1a1a1a, size: 1, sizeAttenuation: false } ) - ]; - - for ( i = 10; i < 30; i ++ ) { - - stars = new THREE.ParticleSystem( starsGeometry[ i % 2 ], starsMaterials[ i % 6 ] ); - - stars.rotation.x = Math.random() * 6; - stars.rotation.y = Math.random() * 6; - stars.rotation.z = Math.random() * 6; - - var s = i * 10; - stars.scale.set( s, s, s ); - - stars.matrixAutoUpdate = false; - stars.updateMatrix(); - - scene.add( stars ); - - } - - renderer = new THREE.WebGLRenderer( { clearColor: 0x000000, clearAlpha: 1 } ); - renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - renderer.sortObjects = false; - - renderer.autoClear = false; - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - window.addEventListener( 'resize', onWindowResize, false ); - - // postprocessing - - var renderModel = new THREE.RenderPass( scene, camera ); - var effectFilm = new THREE.FilmPass( 0.35, 0.75, 2048, false ); - - effectFilm.renderToScreen = true; - - composer = new THREE.EffectComposer( renderer ); - - composer.addPass( renderModel ); - composer.addPass( effectFilm ); - - }; - - function onWindowResize( event ) { - - SCREEN_HEIGHT = window.innerHeight; - SCREEN_WIDTH = window.innerWidth; - - renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - - camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT; - camera.updateProjectionMatrix(); - - composer.reset(); - - }; - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - }; - - function render() { - - // rotate the planet and clouds - - var delta = clock.getDelta(); - - meshPlanet.rotation.y += rotationSpeed * delta; - meshClouds.rotation.y += 1.25 * rotationSpeed * delta; - - // slow down as we approach the surface - - dPlanet = camera.position.length(); - - dMoonVec.subVectors( camera.position, meshMoon.position ); - dMoon = dMoonVec.length(); - - if ( dMoon < dPlanet ) { - - d = ( dMoon - radius * moonScale * 1.01 ); - - } else { - - d = ( dPlanet - radius * 1.01 ); - - } - - controls.movementSpeed = 0.33 * d; - controls.update( delta ); - - renderer.clear(); - composer.render( delta ); - - }; -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/misc_controls_orbit.html - -()=>{ - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, controls, scene, renderer; - - var cross; - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.z = 500; - - controls = new THREE.OrbitControls( camera ); - controls.addEventListener( 'change', render ); - - scene = new THREE.Scene(); - scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 ); - - // world - - var geometry = new THREE.CylinderGeometry( 0, 10, 30, 4, 1 ); - var material = new THREE.MeshLambertMaterial( { color:0xffffff, shading: THREE.FlatShading } ); - - for ( var i = 0; i < 500; i ++ ) { - - var mesh = new THREE.Mesh( geometry, material ); - mesh.position.x = ( Math.random() - 0.5 ) * 1000; - mesh.position.y = ( Math.random() - 0.5 ) * 1000; - mesh.position.z = ( Math.random() - 0.5 ) * 1000; - mesh.updateMatrix(); - mesh.matrixAutoUpdate = false; - scene.add( mesh ); - - } - - - // lights - - var light = new THREE.DirectionalLight( 0xffffff ); - light.position.set( 1, 1, 1 ); - scene.add( light ); - - light = new THREE.DirectionalLight( 0x002288 ); - light.position.set( -1, -1, -1 ); - scene.add( light ); - - var lightAmbient = new THREE.AmbientLight( 0x222222 ); - scene.add( lightAmbient ); - - - // renderer - - renderer = new THREE.WebGLRenderer( { antialias: false } ); - renderer.setClearColor( scene.fog.color, 1 ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container = document.getElementById( 'container' ); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - render(); - - } - - function animate() { - - requestAnimationFrame( animate ); - controls.update(); - - } - - function render() { - - renderer.render( scene, camera ); - stats.update(); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/misc_controls_path.html - -()=>{ - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, controls, scene, renderer; - - var cross; - - var clock = new THREE.Clock(); - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 1000 ); - - controls = new THREE.PathControls( camera ); - - controls.waypoints = [ [ -500, 0, 0 ], [ 0, 200, 0 ], [ 500, 0, 0 ] ]; - controls.duration = 28 - controls.useConstantSpeed = true; - //controls.createDebugPath = true; - //controls.createDebugDummy = true; - controls.lookSpeed = 0.06; - controls.lookVertical = true; - controls.lookHorizontal = true; - controls.verticalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 1.1, 3.8 ] }; - controls.horizontalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0.3, Math.PI - 0.3 ] }; - controls.lon = 180; - - controls.init(); - - // world - - scene = new THREE.Scene(); - scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 ); - - scene.add( controls.animationParent ); - - var geometry = new THREE.CylinderGeometry( 0, 10, 30, 4, 1 ); - var material = new THREE.MeshLambertMaterial( { color:0xffffff, shading: THREE.FlatShading } ); - - for ( var i = 0; i < 500; i ++ ) { - - var mesh = new THREE.Mesh( geometry, material ); - mesh.position.x = ( Math.random() - 0.5 ) * 1000; - mesh.position.y = ( Math.random() - 0.5 ) * 1000; - mesh.position.z = ( Math.random() - 0.5 ) * 1000; - mesh.updateMatrix(); - mesh.matrixAutoUpdate = false; - scene.add( mesh ); - - } - - // lights - - var light = new THREE.DirectionalLight( 0xffffff ); - light.position.set( 1, 1, 1 ); - scene.add( light ); - - light = new THREE.DirectionalLight( 0x002288 ); - light.position.set( -1, -1, -1 ); - scene.add( light ); - - var lightAmbient = new THREE.AmbientLight( 0x222222 ); - scene.add( lightAmbient ); - - - // renderer - - renderer = new THREE.WebGLRenderer( { antialias: false } ); - renderer.setClearColor( scene.fog.color, 1 ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container = document.getElementById( 'container' ); - container.appendChild( renderer.domElement ); - - // stats - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - // start animation - - controls.animation.play( true, 0 ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - controls.handleResize(); - - } - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var delta = clock.getDelta(); - - THREE.AnimationHandler.update( delta ); - - controls.update( delta ); - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/misc_controls_pointerlock.html - -()=>{ - var camera, scene, renderer; - var geometry, material, mesh; - var controls,time = Date.now(); - - var objects = []; - - var ray; - - var blocker = document.getElementById( 'blocker' ); - var instructions = document.getElementById( 'instructions' ); - - // http://www.html5rocks.com/en/tutorials/pointerlock/intro/ - - var havePointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; - - if ( havePointerLock ) { - - var element = document.body; - - var pointerlockchange = function ( event ) { - - if ( document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element ) { - - controls.enabled = true; - - blocker.style.display = 'none'; - - } else { - - controls.enabled = false; - - blocker.style.display = '-webkit-box'; - blocker.style.display = '-moz-box'; - blocker.style.display = 'box'; - - instructions.style.display = ''; - - } - - } - - var pointerlockerror = function ( event ) { - - instructions.style.display = ''; - - } - - // Hook pointer lock state change events - document.addEventListener( 'pointerlockchange', pointerlockchange, false ); - document.addEventListener( 'mozpointerlockchange', pointerlockchange, false ); - document.addEventListener( 'webkitpointerlockchange', pointerlockchange, false ); - - document.addEventListener( 'pointerlockerror', pointerlockerror, false ); - document.addEventListener( 'mozpointerlockerror', pointerlockerror, false ); - document.addEventListener( 'webkitpointerlockerror', pointerlockerror, false ); - - instructions.addEventListener( 'click', function ( event ) { - - instructions.style.display = 'none'; - - // Ask the browser to lock the pointer - element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; - - if ( /Firefox/i.test( navigator.userAgent ) ) { - - var fullscreenchange = function ( event ) { - - if ( document.fullscreenElement === element || document.mozFullscreenElement === element || document.mozFullScreenElement === element ) { - - document.removeEventListener( 'fullscreenchange', fullscreenchange ); - document.removeEventListener( 'mozfullscreenchange', fullscreenchange ); - - element.requestPointerLock(); - } - - } - - document.addEventListener( 'fullscreenchange', fullscreenchange, false ); - document.addEventListener( 'mozfullscreenchange', fullscreenchange, false ); - - element.requestFullscreen = element.requestFullscreen || element.mozRequestFullscreen || element.mozRequestFullScreen || element.webkitRequestFullscreen; - - element.requestFullscreen(); - - } else { - - element.requestPointerLock(); - - } - - }, false ); - - } else { - - instructions.innerHTML = 'Your browser doesn\'t seem to support Pointer Lock API'; - - } - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1000 ); - - scene = new THREE.Scene(); - scene.fog = new THREE.Fog( 0xffffff, 0, 750 ); - - var light = new THREE.DirectionalLight( 0xffffff, 1.5 ); - light.position.set( 1, 1, 1 ); - scene.add( light ); - - var light = new THREE.DirectionalLight( 0xffffff, 0.75 ); - light.position.set( -1, - 0.5, -1 ); - scene.add( light ); - - controls = new THREE.PointerLockControls( camera ); - scene.add( controls.getObject() ); - - ray = new THREE.Raycaster(); - ray.ray.direction.set( 0, -1, 0 ); - - // floor - - geometry = new THREE.PlaneGeometry( 2000, 2000, 100, 100 ); - geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) ); - - for ( var i = 0, l = geometry.vertices.length; i < l; i ++ ) { - - var vertex = geometry.vertices[ i ]; - vertex.x += Math.random() * 20 - 10; - vertex.y += Math.random() * 2; - vertex.z += Math.random() * 20 - 10; - - } - - for ( var i = 0, l = geometry.faces.length; i < l; i ++ ) { - - var face = geometry.faces[ i ]; - face.vertexColors[ 0 ] = new THREE.Color().setHSL( Math.random() * 0.2 + 0.5, 0.75, Math.random() * 0.25 + 0.75 ); - face.vertexColors[ 1 ] = new THREE.Color().setHSL( Math.random() * 0.2 + 0.5, 0.75, Math.random() * 0.25 + 0.75 ); - face.vertexColors[ 2 ] = new THREE.Color().setHSL( Math.random() * 0.2 + 0.5, 0.75, Math.random() * 0.25 + 0.75 ); - face.vertexColors[ 3 ] = new THREE.Color().setHSL( Math.random() * 0.2 + 0.5, 0.75, Math.random() * 0.25 + 0.75 ); - - } - - material = new THREE.MeshBasicMaterial( { vertexColors: THREE.VertexColors } ); - - mesh = new THREE.Mesh( geometry, material ); - scene.add( mesh ); - - // objects - - geometry = new THREE.CubeGeometry( 20, 20, 20 ); - - for ( var i = 0, l = geometry.faces.length; i < l; i ++ ) { - - var face = geometry.faces[ i ]; - face.vertexColors[ 0 ] = new THREE.Color().setHSL( Math.random() * 0.2 + 0.5, 0.75, Math.random() * 0.25 + 0.75 ); - face.vertexColors[ 1 ] = new THREE.Color().setHSL( Math.random() * 0.2 + 0.5, 0.75, Math.random() * 0.25 + 0.75 ); - face.vertexColors[ 2 ] = new THREE.Color().setHSL( Math.random() * 0.2 + 0.5, 0.75, Math.random() * 0.25 + 0.75 ); - face.vertexColors[ 3 ] = new THREE.Color().setHSL( Math.random() * 0.2 + 0.5, 0.75, Math.random() * 0.25 + 0.75 ); - - } - - for ( var i = 0; i < 500; i ++ ) { - - material = new THREE.MeshPhongMaterial( { specular: 0xffffff, shading: THREE.FlatShading, vertexColors: THREE.VertexColors } ); - - var mesh = new THREE.Mesh( geometry, material ); - mesh.position.x = Math.floor( Math.random() * 20 - 10 ) * 20; - mesh.position.y = Math.floor( Math.random() * 20 ) * 20 + 10; - mesh.position.z = Math.floor( Math.random() * 20 - 10 ) * 20; - scene.add( mesh ); - - material.color.setHSL( Math.random() * 0.2 + 0.5, 0.75, Math.random() * 0.25 + 0.75 ); - - objects.push( mesh ); - - } - - // - - renderer = new THREE.WebGLRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - document.body.appendChild( renderer.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function animate() { - - requestAnimationFrame( animate ); - - // - - controls.isOnObject( false ); - - ray.ray.origin.copy( controls.getObject().position ); - ray.ray.origin.y -= 10; - - var intersections = ray.intersectObjects( objects ); - - if ( intersections.length > 0 ) { - - var distance = intersections[ 0 ].distance; - - if ( distance > 0 && distance < 10 ) { - - controls.isOnObject( true ); - - } - - } - - controls.update( Date.now() - time ); - - renderer.render( scene, camera ); - - time = Date.now(); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/misc_controls_roll.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, controls, scene, renderer; - - var cross; - - var clock = new THREE.Clock(); - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 ); - - controls = new THREE.RollControls( camera ); - - controls.movementSpeed = 100; - controls.lookSpeed = 3; - controls.constrainVertical = [ -0.5, 0.5 ]; - //controls.autoForward = true; - - // world - - scene = new THREE.Scene(); - scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 ); - - var geometry = new THREE.CylinderGeometry( 0, 10, 30, 4, 1 ); - var material = new THREE.MeshLambertMaterial( { color:0xffffff, shading: THREE.FlatShading } ); - - for ( var i = 0; i < 500; i ++ ) { - - var mesh = new THREE.Mesh( geometry, material ); - mesh.position.x = ( Math.random() - 0.5 ) * 1000; - mesh.position.y = ( Math.random() - 0.5 ) * 1000; - mesh.position.z = ( Math.random() - 0.5 ) * 1000; - mesh.updateMatrix(); - mesh.matrixAutoUpdate = false; - scene.add( mesh ); - - } - - // lights - - var light = new THREE.DirectionalLight( 0xffffff ); - light.position.set( 1, 1, 1 ); - scene.add( light ); - - light = new THREE.DirectionalLight( 0x002288 ); - light.position.set( -1, -1, -1 ); - scene.add( light ); - - var lightAmbient = new THREE.AmbientLight( 0x555555 ); - scene.add( lightAmbient ); - - - // renderer - - renderer = new THREE.WebGLRenderer( { antialias: false } ); - renderer.setClearColor( scene.fog.color, 1 ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container = document.getElementById( 'container' ); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - controls.handleResize(); - - } - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - controls.update( clock.getDelta() ); - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/misc_controls_trackball.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, controls, scene, renderer; - - var cross; - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.z = 500; - - controls = new THREE.TrackballControls( camera ); - - controls.rotateSpeed = 1.0; - controls.zoomSpeed = 1.2; - controls.panSpeed = 0.8; - - controls.noZoom = false; - controls.noPan = false; - - controls.staticMoving = true; - controls.dynamicDampingFactor = 0.3; - - controls.keys = [ 65, 83, 68 ]; - - controls.addEventListener( 'change', render ); - - // world - - scene = new THREE.Scene(); - scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 ); - - var geometry = new THREE.CylinderGeometry( 0, 10, 30, 4, 1 ); - var material = new THREE.MeshLambertMaterial( { color:0xffffff, shading: THREE.FlatShading } ); - - for ( var i = 0; i < 500; i ++ ) { - - var mesh = new THREE.Mesh( geometry, material ); - mesh.position.x = ( Math.random() - 0.5 ) * 1000; - mesh.position.y = ( Math.random() - 0.5 ) * 1000; - mesh.position.z = ( Math.random() - 0.5 ) * 1000; - mesh.updateMatrix(); - mesh.matrixAutoUpdate = false; - scene.add( mesh ); - - } - - - // lights - - var light = new THREE.DirectionalLight( 0xffffff ); - light.position.set( 1, 1, 1 ); - scene.add( light ); - - light = new THREE.DirectionalLight( 0x002288 ); - light.position.set( -1, -1, -1 ); - scene.add( light ); - - var lightAmbient = new THREE.AmbientLight( 0x222222 ); - scene.add( lightAmbient ); - - - // renderer - - renderer = new THREE.WebGLRenderer( { antialias: false } ); - renderer.setClearColor( scene.fog.color, 1 ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container = document.getElementById( 'container' ); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - controls.handleResize(); - - render(); - - } - - function animate() { - - requestAnimationFrame( animate ); - controls.update(); - - } - - function render() { - - renderer.render( scene, camera ); - stats.update(); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/misc_lights_test.html - -()=>{ - var SCREEN_WIDTH = window.innerWidth / 2; - var SCREEN_HEIGHT = window.innerHeight; - var FLOOR = -250; - - var container, stats; - - var camera, scene, canvasRenderer, webglRenderer; - - var mesh, zmesh, lightMesh, geometry; - var materialSpheres, materialTorus; - - var directionalLight, pointLight; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var render_canvas = true, render_gl = true; - var has_gl = 0; - - var lightAdded = false; - - var clock = new THREE.Clock(); - - var bcanvas = document.getElementById( 'rcanvas' ); - var bwebgl = document.getElementById( 'rwebgl' ); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - init(); - animate(); - - //render_canvas = !has_gl; - bwebgl.style.display = has_gl ? 'inline' : 'none'; - bcanvas.className = render_canvas ? 'button' : 'button inactive'; - - function init() { - - container = document.createElement('div'); - document.body.appendChild(container); - - camera = new THREE.PerspectiveCamera( 75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 100000 ); - camera.position.z = 500; - - scene = new THREE.Scene(); - - // Spheres - - var geometry = new THREE.SphereGeometry( 100, 16, 8 ); - materialSpheres = new THREE.MeshLambertMaterial( { color: 0xffffff, shading: THREE.FlatShading, overdraw: true } ); - - for ( var i = 0; i < 30; i ++ ) { - - mesh = new THREE.Mesh( geometry, materialSpheres ); - mesh.position.x = 500 * ( Math.random() - 0.5 ); - mesh.position.y = 500 * ( Math.random() - 0.5 ); - mesh.position.z = 500 * ( Math.random() - 0.5 ); - mesh.scale.x = mesh.scale.y = mesh.scale.z = 0.25 * ( Math.random() + 0.5 ); - scene.add( mesh ); - - } - - // Torus - - materialTorus = new THREE.MeshLambertMaterial( { color: 0xffffff, overdraw: true } ); - mesh = new THREE.Mesh( new THREE.TorusGeometry( 100, 25, 15, 30 ), materialTorus ); - scene.add( mesh ); - - // Lights - - var ambient = new THREE.AmbientLight( 0x101010 ); - scene.add( ambient ); - - directionalLight = new THREE.DirectionalLight( 0xffffff ); - directionalLight.position.set( 0, -70, 100 ).normalize(); - //scene.add( directionalLight ); - - pointLight = new THREE.PointLight( 0xffaa00 ); - scene.add( pointLight ); - - lightMesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { color: 0xffaa00 } ) ); - lightMesh.scale.x = lightMesh.scale.y = lightMesh.scale.z = 0.05; - lightMesh.position = pointLight.position; - scene.add( lightMesh ); - - - if ( render_canvas ) { - - canvasRenderer = new THREE.CanvasRenderer(); - canvasRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - container.appendChild( canvasRenderer.domElement ); - - } - - if ( render_gl ) { - - try { - - webglRenderer = new THREE.WebGLRenderer( { alpha: true } ); - webglRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - webglRenderer.domElement.style.position = "relative"; - container.appendChild( webglRenderer.domElement ); - - has_gl = 1; - - } catch (e) { - - } - - } - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - bcanvas.addEventListener("click", toggleCanvas, false); - bwebgl.addEventListener("click", toggleWebGL, false); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - SCREEN_WIDTH = window.innerWidth / 2; - SCREEN_HEIGHT = window.innerHeight; - - camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT; - camera.updateProjectionMatrix(); - - if ( canvasRenderer ) canvasRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - if ( webglRenderer ) webglRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - - } - - function onDocumentMouseMove( event ) { - - mouseX = ( event.clientX - windowHalfX ); - mouseY = ( event.clientY - windowHalfY ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var delta = clock.getDelta(); - var r = clock.getElapsedTime(); - - if ( ! lightAdded && r >= 3.0 ) { - - scene.add( directionalLight ); - - materialTorus.needsUpdate = true; - materialSpheres.needsUpdate = true; - - lightAdded = true; - - } - - camera.position.x += ( mouseX - camera.position.x ) * 0.05; - camera.position.y += ( - mouseY - camera.position.y ) * 0.05; - - camera.lookAt( scene.position ); - - for ( var i = 0, l = scene.children.length; i < l; i ++ ) { - - var object = scene.children[ i ]; - - if ( object instanceof THREE.Mesh ) { - - if ( i % 3 == 1 ) - - object.rotation.z += 1.5 * delta; - - else if ( i % 3 == 2 ) - - object.rotation.y += 1.5 * delta; - - else if ( i % 3 == 0 ) - - object.rotation.x += 1.5 * delta; - - } - - } - - - lightMesh.position.x = 200 * Math.cos( r ); - lightMesh.position.z = 200 * Math.sin( r ); - - if ( render_canvas ) canvasRenderer.render( scene, camera ); - if ( render_gl && has_gl ) webglRenderer.render( scene, camera ); - - } - - function toggleCanvas() { - - render_canvas = !render_canvas; - bcanvas.className = render_canvas ? "button" : "button inactive"; - - render_gl = !render_canvas; - bwebgl.className = render_gl ? "button" : "button inactive"; - - if( has_gl ) - webglRenderer.domElement.style.display = render_gl ? "block" : "none"; - - canvasRenderer.domElement.style.display = render_canvas ? "block" : "none"; - - } - - function toggleWebGL() { - - render_gl = !render_gl; - bwebgl.className = render_gl ? "button" : "button inactive"; - - render_canvas = !render_gl; - bcanvas.className = render_canvas ? "button" : "button inactive"; - - if( has_gl ) - webglRenderer.domElement.style.display = render_gl ? "block" : "none"; - - canvasRenderer.domElement.style.display = render_canvas ? "block" : "none"; - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/misc_lookat.html - -()=>{ - - var container, stats; - - var camera, scene, renderer; - - var mesh, geometry, sphere; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - init(); - animate(); - - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 15000 ); - camera.position.z = 3200; - - scene = new THREE.Scene(); - - sphere = new THREE.Mesh( new THREE.SphereGeometry( 100, 20, 20 ), new THREE.MeshNormalMaterial( { shading: THREE.SmoothShading } ) ); - scene.add( sphere ); - - var geometry = new THREE.CylinderGeometry(0, 10, 100, 3); - var v = new THREE.Vector3(Math.PI / 2, Math.PI, 0); - geometry.applyMatrix(new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(v.x, v.y, v.z) ) ); - - var material = new THREE.MeshNormalMaterial(); - - for ( var i = 0; i < 1000; i ++ ) { - - var mesh = new THREE.Mesh( geometry, material ); - mesh.position.x = Math.random() * 4000 - 2000; - mesh.position.y = Math.random() * 4000 - 2000; - mesh.position.z = Math.random() * 4000 - 2000; - mesh.scale.x = mesh.scale.y = mesh.scale.z = Math.random() * 4 + 2; - scene.add( mesh ); - - } - - scene.matrixAutoUpdate = false; - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.sortObjects = false; - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onDocumentMouseMove(event) { - - mouseX = ( event.clientX - windowHalfX ) * 10; - mouseY = ( event.clientY - windowHalfY ) * 10; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = Date.now() * 0.0005; - - sphere.position.x = Math.sin( time * 0.7 ) * 2000; - sphere.position.y = Math.cos( time * 0.5 ) * 2000; - sphere.position.z = Math.cos( time * 0.3 ) * 2000; - - for ( var i = 1, l = scene.children.length; i < l; i ++ ) { - - scene.children[ i ].lookAt( sphere.position ); - - } - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y += ( - mouseY - camera.position.y ) * .05; - camera.lookAt( scene.position ); - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/misc_sound.html - -()=>{ - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container; - var camera, controls, scene, renderer; - var light, pointLight; - - var mesh; - var material_sphere1, material_sphere2; - - var sound1, sound2; - - var clock = new THREE.Clock(); - - var Sound = function ( sources, radius, volume ) { - - var audio = document.createElement( 'audio' ); - - for ( var i = 0; i < sources.length; i ++ ) { - - var source = document.createElement( 'source' ); - source.src = sources[ i ]; - - audio.appendChild( source ); - - } - - this.position = new THREE.Vector3(); - - this.play = function () { - - audio.play(); - - } - - this.update = function ( camera ) { - - var distance = this.position.distanceTo( camera.position ); - - if ( distance <= radius ) { - - audio.volume = volume * ( 1 - distance / radius ); - - } else { - - audio.volume = 0; - - } - - } - - } - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.set( 0, 25, 0 ); - - controls = new THREE.FirstPersonControls( camera ); - - controls.movementSpeed = 70; - controls.lookSpeed = 0.05; - controls.noFly = true; - controls.lookVertical = false; - - scene = new THREE.Scene(); - scene.fog = new THREE.FogExp2( 0x000000, 0.0035 ); - - light = new THREE.DirectionalLight( 0xffffff ); - light.position.set( 0, 0.5, 1 ).normalize(); - scene.add( light ); - - var sphere = new THREE.SphereGeometry( 20, 32, 16 ); - - material_sphere1 = new THREE.MeshLambertMaterial( { color: 0xffaa00, shading: THREE.FlatShading } ); - material_sphere2 = new THREE.MeshLambertMaterial( { color: 0xff2200, shading: THREE.FlatShading } ); - - // sound spheres - - var s = 1; - - var mesh1 = new THREE.Mesh( sphere, material_sphere1 ); - mesh1.position.set( -250, 30, 0 ); - mesh1.scale.set( s, s, s ); - scene.add( mesh1 ); - - sound1 = new Sound( [ 'sounds/358232_j_s_song.mp3', 'sounds/358232_j_s_song.ogg' ], 275, 1 ); - sound1.position.copy( mesh1.position ); - sound1.play(); - - // - - var mesh2 = new THREE.Mesh( sphere, material_sphere2 ); - mesh2.position.set( 250, 30, 0 ); - mesh2.scale.set( s, s, s ); - scene.add( mesh2 ); - - sound2 = new Sound( [ 'sounds/376737_Skullbeatz___Bad_Cat_Maste.mp3', 'sounds/376737_Skullbeatz___Bad_Cat_Maste.ogg' ], 275, 1 ); - sound2.position.copy( mesh2.position ); - sound2.play(); - - - // ground - - var material = new THREE.MeshLambertMaterial( { color: 0x7f7566, wireframe: true, wireframeLinewidth: 1 } ); - - mesh = new THREE.Mesh( new THREE.PlaneGeometry( 1000, 1000, 100, 100 ), material ); - mesh.position.y = 0.1; - mesh.rotation.x = - Math.PI / 2; - scene.add( mesh ); - - // - - renderer = new THREE.WebGLRenderer( { clearColor: 0x000000, clearAlpha: 1, antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.innerHTML = ""; - container.appendChild( renderer.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - controls.handleResize(); - - } - - function animate() { - - requestAnimationFrame( animate ); - render(); - - } - - - function render() { - - var delta = clock.getDelta(), - time = clock.getElapsedTime() * 5; - - controls.update( delta ); - - material_sphere1.color.setHSL( 0.0, 0.3 + 0.7 * ( 1 + Math.cos( time ) ) / 2, 0.5 ); - material_sphere2.color.setHSL( 0.1, 0.3 + 0.7 * ( 1 + Math.sin( time ) ) / 2, 0.5 ); - - renderer.render( scene, camera ); - - sound1.update( camera ); - sound2.update( camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/misc_ubiquity_test.html - -()=>{ - var SCREEN_WIDTH = window.innerWidth / 2; - var SCREEN_HEIGHT = window.innerHeight / 2; - var AMOUNT = 100; - - var container, stats; - - var camera, scene; - var canvasRenderer, svgRenderer, softwareRenderer, webglRenderer; - - var mesh, group; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 100000 ); - camera.position.z = 500; - - scene = new THREE.Scene(); - - // QRCODE - - mesh = new THREE.Mesh( new Qrcode(), new THREE.MeshLambertMaterial( { /*emissive: 0xff0000,*/ vertexColors: THREE.FaceColors } ) ); - mesh.scale.x = mesh.scale.y = mesh.scale.z = 2; - scene.add( mesh ); - - // CUBES - - var cube = new THREE.CubeGeometry( 100, 100, 100 ); - - mesh = new THREE.Mesh( cube, new THREE.MeshBasicMaterial( { color: 0x0000ff, opacity: 0.5, transparent: true } ) ); - mesh.position.x = 500; - mesh.rotation.x = Math.random(); - mesh.rotation.y = Math.random(); - mesh.scale.x = mesh.scale.y = mesh.scale.z = 2; - scene.add( mesh ); - - mesh = new THREE.Mesh( cube, new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ) ); - mesh.position.x = 500; - mesh.position.y = 500; - mesh.rotation.x = Math.random(); - mesh.rotation.y = Math.random(); - mesh.scale.x = mesh.scale.y = mesh.scale.z = 2; - scene.add( mesh ); - - // PLANE - - mesh = new THREE.Mesh( new THREE.PlaneGeometry( 100, 100 ), new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, side: THREE.DoubleSide } ) ); - mesh.position.y = -500; - mesh.scale.x = mesh.scale.y = mesh.scale.z = 2; - scene.add( mesh ); - - // CYLINDER - - mesh = new THREE.Mesh( new THREE.CylinderGeometry( 20, 100, 200, 10 ), new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ) ); - mesh.position.x = -500; - mesh.rotation.x = - Math.PI / 2; - mesh.scale.x = mesh.scale.y = mesh.scale.z = 2; - scene.add( mesh ); - - // POLYFIELD - - var geometry = new THREE.Geometry(); - var materials = []; - - for ( var i = 0; i < 100; i ++ ) { - - var v = new THREE.Vector3( Math.random() * 1000 - 500, Math.random() * 1000 - 500, Math.random() * 1000 - 500 ); - - var v0 = new THREE.Vector3( Math.random() * 100 - 50, Math.random() * 100 - 50, Math.random() * 100 - 50 ); - var v1 = new THREE.Vector3( Math.random() * 100 - 50, Math.random() * 100 - 50, Math.random() * 100 - 50 ); - var v2 = new THREE.Vector3( Math.random() * 100 - 50, Math.random() * 100 - 50, Math.random() * 100 - 50 ); - - v0.add( v ); - v1.add( v ); - v2.add( v ); - - var face = new THREE.Face3( geometry.vertices.push( v0 ) - 1, geometry.vertices.push( v1 ) - 1, geometry.vertices.push( v2 ) - 1, null, null, i ); - - geometry.faces.push( face ); - - materials.push( new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, side: THREE.DoubleSide } ) ); - - } - - geometry.computeFaceNormals(); - geometry.computeCentroids(); - - group = new THREE.Object3D(); - group.scale.x = group.scale.y = group.scale.z = 2; - scene.add( group ); - - mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) ); - group.add( mesh ); - - // LIGHTS - - var ambient = new THREE.AmbientLight( 0x80ffff ); - scene.add( ambient ); - - var directional = new THREE.DirectionalLight( 0xffff00 ); - directional.position.set( - 1, 0.5, 0 ); - scene.add( directional ); - - canvasRenderer = new THREE.CanvasRenderer(); - canvasRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - container.appendChild( canvasRenderer.domElement ); - - svgRenderer = new THREE.SVGRenderer(); - svgRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - svgRenderer.setQuality( 'low' ); - container.appendChild( svgRenderer.domElement ); - - softwareRenderer = new THREE.SoftwareRenderer(); - softwareRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - container.appendChild( softwareRenderer.domElement ); - - webglRenderer = new THREE.WebGLRenderer( { antialias: true } ); - webglRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - container.appendChild( webglRenderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - SCREEN_WIDTH = window.innerWidth / 2; - SCREEN_HEIGHT = window.innerHeight / 2; - - camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT; - camera.updateProjectionMatrix(); - - canvasRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - svgRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - softwareRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - webglRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - - } - - function onDocumentMouseMove(event) { - - mouseX = ( event.clientX - windowHalfX ); - mouseY = ( event.clientY - windowHalfY ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y += ( - mouseY - camera.position.y ) * .05; - camera.lookAt( scene.position ); - - group.rotation.y += 0.01; - - canvasRenderer.render( scene, camera ); - svgRenderer.render( scene, camera ); - softwareRenderer.render( scene, camera ); - webglRenderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/misc_uv_tests.html - -()=>{ - /* - * This is to help debug UVs problems in geometry, - * as well as allow a new user to visualize what UVs are about. - */ - - - function test(name, geometry) { - - var d = document.createElement('div'); - d.innerHTML = '

    ' + name + '
    '; - d.appendChild(THREE.UVsDebug(geometry)); - document.body.appendChild(d); - - } - - - test('new THREE.PlaneGeometry( 100, 100, 4, 4 )', new THREE.PlaneGeometry( 100, 100, 4, 4 )); - test('new THREE.SphereGeometry( 75, 12, 6 )', new THREE.SphereGeometry( 75, 12, 6 )); - - test('new THREE.IcosahedronGeometry( 30, 1 )', new THREE.IcosahedronGeometry( 30, 1 )); - test('new THREE.OctahedronGeometry( 30, 2 )', new THREE.OctahedronGeometry( 30, 2 )); - - test('new THREE.CylinderGeometry( 25, 75, 100, 10, 5 )', new THREE.CylinderGeometry( 25, 75, 100, 10, 5 )); - - test('new THREE.CubeGeometry( 100, 100, 100, 4, 4, 4 )', new THREE.CubeGeometry( 100, 100, 100, 4, 4, 4 )); - - var points = []; - - for ( var i = 0; i < 10; i ++ ) { - - points.push( new THREE.Vector3( Math.sin( i * 0.2 ) * 15 + 50, 0, ( i - 5 ) * 2 ) ); - - } - - - test('new THREE.LatheGeometry( points, 8 )', new THREE.LatheGeometry( points, 8 )); - test('new THREE.TorusGeometry( 50, 20, 8, 8 )', new THREE.TorusGeometry( 50, 20, 8, 8 )); - test('new THREE.TorusKnotGeometry( 50, 10, 12, 6 )', new THREE.TorusKnotGeometry( 50, 10, 12, 6 )); - - /* - Not sure how UVs for ExtrudeGeometry are done currently... - */ - - var pts = [], starPoints = 5, l; - for (i=0; i{ - var container, stats; - - var camera, controls, scene, renderer; - - var torus, cube; - - var start = Date.now(); - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - var info = document.createElement( 'div' ); - info.style.position = 'absolute'; - info.style.top = '10px'; - info.style.width = '100%'; - info.style.textAlign = 'center'; - info.innerHTML = 'three.js - software renderer
    drag to change the point of view'; - container.appendChild( info ); - - camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.z = 600; - - controls = new THREE.TrackballControls( camera ); - - scene = new THREE.Scene(); - - torus = new THREE.Mesh( new THREE.TorusKnotGeometry( 150 ), new THREE.MeshBasicMaterial( { color: 0x0000ff } ) ); - scene.add( torus ); - - // Plane - - cube = new THREE.Mesh( new THREE.CubeGeometry( 200, 200, 200 ), new THREE.MeshBasicMaterial( { color: 0x00ff00 } ) ); - scene.add( cube ); - - renderer = new THREE.SoftwareRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var timer = Date.now() - start; - - torus.position.y = Math.sin( timer * 0.002 ) * 150; - torus.rotation.x = timer * 0.0003; - torus.rotation.z = timer * 0.0002; - - cube.rotation.x = timer * 0.0002; - cube.rotation.z = timer * 0.0003; - - - controls.update(); - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_animation_cloth.html - - -declare var cloth: any; -declare var clothFunction: any; -declare var ballSize: number; -declare var windStrength: number; -declare var windForce: THREE.Vector3; -declare function simulate(time: number); -declare var ballPosition: THREE.Vector3; -()=>{ - /* testing cloth simulation */ - - var pinsFormation = []; - var pins = [6]; - - pinsFormation.push( pins ); - - pins = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; - pinsFormation.push( pins ); - - pins = [ 0 ]; - pinsFormation.push( pins ); - - pins = []; // cut the rope ;) - pinsFormation.push( pins ); - - pins = [ 0, cloth.w ]; // classic 2 pins - pinsFormation.push( pins ); - - pins = pinsFormation[ 1 ]; - - - function togglePins() { - - pins = pinsFormation[ ~~( Math.random() * pinsFormation.length ) ]; - - } - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - var camera, scene, renderer; - - var clothGeometry; - var sphere; - var object, arrow; - - var rotate = true; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - // scene - - scene = new THREE.Scene(); - - scene.fog = new THREE.Fog( 0xcce0ff, 500, 10000 ); - - // camera - - camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.y = 50; - camera.position.z = 1500; - scene.add( camera ); - - // lights - - var light, materials; - - scene.add( new THREE.AmbientLight( 0x666666 ) ); - - light = new THREE.DirectionalLight( 0xdfebff, 1.75 ); - light.position.set( 50, 200, 100 ); - light.position.multiplyScalar( 1.3 ); - - light.castShadow = true; - //light.shadowCameraVisible = true; - - light.shadowMapWidth = 2048; - light.shadowMapHeight = 2048; - - var d = 300; - - light.shadowCameraLeft = -d; - light.shadowCameraRight = d; - light.shadowCameraTop = d; - light.shadowCameraBottom = -d; - - light.shadowCameraFar = 1000; - light.shadowDarkness = 0.5; - - scene.add( light ); - - light = new THREE.DirectionalLight( 0x3dff0c, 0.35 ); - light.position.set( 0, -1, 0 ); - - scene.add( light ); - - // cloth material - - var clothTexture = THREE.ImageUtils.loadTexture( 'textures/patterns/circuit_pattern.png' ); - clothTexture.wrapS = clothTexture.wrapT = THREE.RepeatWrapping; - clothTexture.anisotropy = 16; - - var clothMaterial = new THREE.MeshPhongMaterial( { alphaTest: 0.5, ambient: 0xffffff, color: 0xffffff, specular: 0x030303, emissive: 0x111111, shiness: 10, map: clothTexture, side: THREE.DoubleSide } ); - - // cloth geometry - clothGeometry = new THREE.ParametricGeometry( clothFunction, cloth.w, cloth.h, true ); - clothGeometry.dynamic = true; - clothGeometry.computeFaceNormals(); - - var uniforms = { texture: { type: "t", value: clothTexture } }; - var vertexShader = document.getElementById( 'vertexShaderDepth' ).textContent; - var fragmentShader = document.getElementById( 'fragmentShaderDepth' ).textContent; - - // cloth mesh - - object = new THREE.Mesh( clothGeometry, clothMaterial ); - object.position.set( 0, 0, 0 ); - object.castShadow = true; - object.receiveShadow = true; - scene.add( object ); - - // TS bug: https://typescript.codeplex.com/workitem/2036 - //object.customDepthMaterial = new THREE.ShaderMaterial( { uniforms: uniforms, vertexShader: vertexShader, fragmentShader: fragmentShader } ); - object.customDepthMaterial = new THREE.ShaderMaterial( { uniforms: uniforms, vertexShader: vertexShader, fragmentShader: fragmentShader } ); - - // sphere - - var ballGeo = new THREE.SphereGeometry( ballSize, 20, 20 ); - var ballMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff } ); - - sphere = new THREE.Mesh( ballGeo, ballMaterial ); - sphere.castShadow = true; - sphere.receiveShadow = true; - scene.add( sphere ); - - // arrow - - arrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 0 ), 50, 0xff0000 ); - arrow.position.set( -200, 0, -200 ); - // scene.add( arrow ); - - // ground - - var initColor = new THREE.Color( 0x497f13 ); - var initTexture = THREE.ImageUtils.generateDataTexture( 1, 1, initColor ); - - var groundMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0x111111, map: initTexture } ); - - var groundTexture = THREE.ImageUtils.loadTexture( "textures/terrain/grasslight-big.jpg", undefined, function() { groundMaterial.map = groundTexture } ); - groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping; - groundTexture.repeat.set( 25, 25 ); - groundTexture.anisotropy = 16; - - var mesh = new THREE.Mesh( new THREE.PlaneGeometry( 20000, 20000 ), groundMaterial ); - mesh.position.y = -250; - mesh.rotation.x = - Math.PI / 2; - mesh.receiveShadow = true; - scene.add( mesh ); - - // poles - - var poleGeo = new THREE.CubeGeometry( 5, 375, 5 ); - var poleMat = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0x111111, shiness: 100 } ); - - var mesh = new THREE.Mesh( poleGeo, poleMat ); - mesh.position.x = -125; - mesh.position.y = -62; - mesh.receiveShadow = true; - mesh.castShadow = true; - scene.add( mesh ); - - var mesh = new THREE.Mesh( poleGeo, poleMat ); - mesh.position.x = 125; - mesh.position.y = -62; - mesh.receiveShadow = true; - mesh.castShadow = true; - scene.add( mesh ); - - var mesh = new THREE.Mesh( new THREE.CubeGeometry( 255, 5, 5 ), poleMat ); - mesh.position.y = -250 + 750/2; - mesh.position.x = 0; - mesh.receiveShadow = true; - mesh.castShadow = true; - scene.add( mesh ); - - var gg = new THREE.CubeGeometry( 10, 10, 10 ); - var mesh = new THREE.Mesh( gg, poleMat ); - mesh.position.y = -250; - mesh.position.x = 125; - mesh.receiveShadow = true; - mesh.castShadow = true; - scene.add( mesh ); - - var mesh = new THREE.Mesh( gg, poleMat ); - mesh.position.y = -250; - mesh.position.x = -125; - mesh.receiveShadow = true; - mesh.castShadow = true; - scene.add( mesh ); - - // - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.setClearColor( scene.fog.color ); - - container.appendChild( renderer.domElement ); - - renderer.gammaInput = true; - renderer.gammaOutput = true; - renderer.physicallyBasedShading = true; - - renderer.shadowMapEnabled = true; - - // - - stats = new Stats(); - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - sphere.visible = !true - - } - - // - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - var time = Date.now(); - - windStrength = Math.cos( time / 7000 ) * 20 + 40; - windForce.set( Math.sin( time / 2000 ), Math.cos( time / 3000 ), Math.sin( time / 1000 ) ).normalize().multiplyScalar( windStrength ); - arrow.setLength( windStrength ); - arrow.setDirection( windForce ); - - simulate(time); - render(); - stats.update(); - - } - - function render() { - - var timer = Date.now() * 0.0002; - - var p = cloth.particles; - - for ( var i = 0, il = p.length; i < il; i ++ ) { - - clothGeometry.vertices[ i ].copy( p[ i ].position ); - - } - - clothGeometry.computeFaceNormals(); - clothGeometry.computeVertexNormals(); - - clothGeometry.normalsNeedUpdate = true; - clothGeometry.verticesNeedUpdate = true; - - sphere.position.copy( ballPosition ); - - if ( rotate ) { - - camera.position.x = Math.cos( timer ) * 1500; - camera.position.z = Math.sin( timer ) * 1500; - - } - - camera.lookAt( scene.position ); - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_animation_skinning.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - window.onload = init; - - var container, stats; - - var camera, scene, renderer; - - var mesh, light; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var animations = []; - var buffalos = []; - var offset = []; - - var floor, dz = 0, dstep = -10, playback = false; - - var clock = new THREE.Clock(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 25, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.set( 0, 185, 2500 ); - - scene = new THREE.Scene(); - scene.fog = new THREE.FogExp2( 0xfff4e5, 0.0003 ); - - light = new THREE.DirectionalLight( 0xffffff, 1.5 ); - light.position.set( 0, 1, 1 ).normalize(); - scene.add( light ); - - var planeSimple = new THREE.PlaneGeometry( 200, 300 ); - var planeTesselated = new THREE.PlaneGeometry( 100, 300, 25, 40 ); - var matWire = new THREE.MeshBasicMaterial( { color: 0x110000, wireframe: true, wireframeLinewidth: 2 } ); - var matSolid = new THREE.MeshBasicMaterial( { color: 0xffb23f } ); - - floor = new THREE.Mesh( planeSimple, matSolid ); - floor.position.y = -10; - floor.rotation.x = - Math.PI / 2; - floor.scale.set( 25, 25, 25 ); - scene.add( floor ); - - floor = new THREE.Mesh( planeTesselated, matWire ); - floor.rotation.x = - Math.PI / 2; - floor.scale.set( 25, 25, 25 ); - scene.add( floor ); - - renderer = new THREE.WebGLRenderer( { clearColor: 0xffffff, clearAlpha: 1, antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.setClearColor( scene.fog.color, 1 ); - renderer.sortObjects = false; - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'click', startAnimation, false ); - - var loader = new THREE.JSONLoader(); - loader.load( "obj/buffalo/buffalo.js", createScene ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - // - - loop(); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function createScene( geometry, materials ) { - - buffalos = []; - animations = []; - - var x:number, y, - buffalo, animation, - gridx = 25, gridz = 15, - sepx = 150, sepz = 300; - - var material = new THREE.MeshFaceMaterial( materials ); - - var originalMaterial = materials[ 0 ]; - - originalMaterial.skinning = true; - originalMaterial.transparent = true; - originalMaterial.alphaTest = 0.75; - - THREE.AnimationHandler.add( geometry.animation ); - - for(var x = 0; x < gridx; x ++ ) { - - for(var z = 0; z < gridz; z ++ ) { - - buffalo = new THREE.SkinnedMesh( geometry, material, false ); - - buffalo.position.x = - ( gridx - 1 ) * sepx * 0.5 + x * sepx + Math.random() * 0.5 * sepx; - buffalo.position.z = - ( gridz - 1 ) * sepz * 0.5 + z * sepz + Math.random() * 0.5 * sepz - 500; - - buffalo.position.y = buffalo.geometry.boundingSphere.radius * 0.5; - buffalo.rotation.y = 0.2 - Math.random() * 0.4; - - scene.add( buffalo ); - - buffalos.push( buffalo ); - - animation = new THREE.Animation( buffalo, "take_001" ); - animations.push( animation ); - - offset.push( Math.random() ); - - } - - } - - } - - function startAnimation() { - - for( var i = 0; i < animations.length; i ++ ) { - - animations[ i ].offset = 0.05 * Math.random(); - animations[ i ].play(); - - } - - dz = dstep; - playback = true; - - } - - - function onDocumentMouseMove( event ) { - - mouseX = ( event.clientX - windowHalfX ); - mouseY = ( event.clientY - windowHalfY ); - - } - - function loop() { - - requestAnimationFrame( loop ); - - var delta = clock.getDelta(); - - THREE.AnimationHandler.update( delta ); - - camera.position.x += ( mouseX - camera.position.x ) * 0.05; - camera.lookAt( scene.position ); - - if ( buffalos && playback ) { - - var elapsed = clock.getElapsedTime(); - - camera.position.z += 2 * Math.sin( elapsed ); - - for(var i = 0; i < buffalos.length; i++ ) { - - buffalos[ i ].position.z += 2 * Math.sin( elapsed + offset[ i ] ); - - } - - } - - floor.position.z += dz; - if( floor.position.z < -500 ) floor.position.z = 0; - - - renderer.render( scene, camera ); - - stats.update(); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_animation_skinning_morph.html - -()=>{ - var SCREEN_WIDTH = window.innerWidth; - var SCREEN_HEIGHT = window.innerHeight; - var FLOOR = -250; - - var container,stats; - - var camera, scene; - var renderer; - - var mesh; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var clock = new THREE.Clock(); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 30, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 ); - camera.position.z = 2200; - - scene = new THREE.Scene(); - - scene.fog = new THREE.Fog( 0xffffff, 2000, 10000 ); - - scene.add( camera ); - - // GROUND - - var groundMaterial = new THREE.MeshPhongMaterial( { emissive: 0xbbbbbb } ); - var planeGeometry = new THREE.PlaneGeometry( 16000, 16000 ); - - var ground = new THREE.Mesh( planeGeometry, groundMaterial ); - ground.position.set( 0, FLOOR, 0 ); - ground.rotation.x = -Math.PI/2; - scene.add( ground ); - - ground.receiveShadow = true; - - - // LIGHTS - - var ambient = new THREE.AmbientLight( 0x222222 ); - scene.add( ambient ); - - - var light = new THREE.DirectionalLight( 0xebf3ff, 1.6 ); - light.position.set( 0, 140, 500 ).multiplyScalar( 1.1 ); - scene.add( light ); - - light.castShadow = true; - - light.shadowMapWidth = 2048; - light.shadowMapHeight = 2048; - - var d = 390; - - light.shadowCameraLeft = -d * 2; - light.shadowCameraRight = d * 2; - light.shadowCameraTop = d * 1.5; - light.shadowCameraBottom = -d; - - light.shadowCameraFar = 3500; - //light.shadowCameraVisible = true; - - // - - var light = new THREE.DirectionalLight( 0x497f13, 1 ); - light.position.set( 0, -1, 0 ); - scene.add( light ); - - // RENDERER - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - renderer.domElement.style.position = "relative"; - - renderer.setClearColor( scene.fog.color, 1 ); - - container.appendChild( renderer.domElement ); - - renderer.gammaInput = true; - renderer.gammaOutput = true; - renderer.physicallyBasedShading = true; - - renderer.shadowMapEnabled = true; - - - // STATS - - stats = new Stats(); - container.appendChild( stats.domElement ); - - // - - var loader = new THREE.JSONLoader(); - loader.load( "models/skinned/knight.js", function ( geometry, materials ) { createScene( geometry, materials, 0, FLOOR, -300, 60 ) } ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function ensureLoop( animation ) { - - for ( var i = 0; i < animation.hierarchy.length; i ++ ) { - - var bone = animation.hierarchy[ i ]; - - var first = bone.keys[ 0 ]; - var last = bone.keys[ bone.keys.length - 1 ]; - - last.pos = first.pos; - last.rot = first.rot; - last.scl = first.scl; - - } - - } - - function createScene( geometry, materials, x, y, z, s ) { - - ensureLoop( geometry.animation ); - - geometry.computeBoundingBox(); - var bb = geometry.boundingBox; - - THREE.AnimationHandler.add( geometry.animation ); - - var path = "textures/cube/Park2/"; - var format = '.jpg'; - var urls = [ - path + 'posx' + format, path + 'negx' + format, - path + 'posy' + format, path + 'negy' + format, - path + 'posz' + format, path + 'negz' + format - ]; - - - //var envMap = THREE.ImageUtils.loadTextureCube( urls ); - - //var map = THREE.ImageUtils.loadTexture( "textures/ash_uvgrid01.jpg" ); - - //var bumpMap = THREE.ImageUtils.generateDataTexture( 1, 1, new THREE.Color() ); - //var bumpMap = THREE.ImageUtils.loadTexture( "textures/water.jpg" ); - - for ( var i = 0; i < materials.length; i ++ ) { - - var m = materials[ i ]; - m.skinning = true; - m.morphTargets = true; - - m.specular.setHSL( 0, 0, 0.1 ); - - m.color.setHSL( 0.6, 0, 0.6 ); - m.ambient.copy( m.color ); - - //m.map = map; - //m.envMap = envMap; - //m.bumpMap = bumpMap; - //m.bumpScale = 2; - - //m.combine = THREE.MixOperation; - //m.reflectivity = 0.75; - - m.wrapAround = true; - - } - - mesh = new THREE.SkinnedMesh( geometry, new THREE.MeshFaceMaterial( materials ) ); - mesh.position.set( x, y - bb.min.y * s, z ); - mesh.scale.set( s, s, s ); - scene.add( mesh ); - - mesh.castShadow = true; - mesh.receiveShadow = true; - - var animation = new THREE.Animation( mesh, geometry.animation.name ); - animation.interpolationType = THREE.AnimationHandler.LINEAR; - - animation.play(); - - } - - function onDocumentMouseMove( event ) { - - mouseX = ( event.clientX - windowHalfX ); - mouseY = ( event.clientY - windowHalfY ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var delta = 0.75 * clock.getDelta(); - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y = THREE.Math.clamp( camera.position.y + ( - mouseY - camera.position.y ) * .05, 0, 1000 ); - - camera.lookAt( scene.position ); - - // update skinning - - THREE.AnimationHandler.update( delta ); - - // update morphs - - if ( mesh ) { - - var time = Date.now() * 0.001; - - // mouth - - mesh.morphTargetInfluences[ 1 ] = ( 1 + Math.sin( 4 * time ) ) / 2; - - // frown ? - - mesh.morphTargetInfluences[ 2 ] = ( 1 + Math.sin( 2 * time ) ) / 2; - - // eyes - - mesh.morphTargetInfluences[ 3 ] = ( 1 + Math.cos( 4 * time ) ) / 2; - - } - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_buffergeometry.html - -()=>{ - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, scene, renderer; - - var mesh; - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - // - - camera = new THREE.PerspectiveCamera( 27, window.innerWidth / window.innerHeight, 1, 3500 ); - camera.position.z = 2750; - - scene = new THREE.Scene(); - scene.fog = new THREE.Fog( 0x050505, 2000, 3500 ); - - // - - scene.add( new THREE.AmbientLight( 0x444444 ) ); - - var light1 = new THREE.DirectionalLight( 0xffffff, 0.5 ); - light1.position.set( 1, 1, 1 ); - scene.add( light1 ); - - var light2 = new THREE.DirectionalLight( 0xffffff, 1.5 ); - light2.position.set( 0, -1, 0 ); - scene.add( light2 ); - - // - - var triangles = 160000; - - var geometry = new THREE.BufferGeometry(); - geometry.attributes = { - index: { - itemSize: 1, - array: new Uint16Array( triangles * 3 ), - numItems: triangles * 3 - }, - position: { - itemSize: 3, - array: new Float32Array( triangles * 3 * 3 ), - numItems: triangles * 3 * 3 - }, - normal: { - itemSize: 3, - array: new Float32Array( triangles * 3 * 3 ), - numItems: triangles * 3 * 3 - }, - color: { - itemSize: 3, - array: new Float32Array( triangles * 3 * 3 ), - numItems: triangles * 3 * 3 - } - } - - // break geometry into - // chunks of 21,845 triangles (3 unique vertices per triangle) - // for indices to fit into 16 bit integer number - // floor(2^16 / 3) = 21845 - - var chunkSize = 21845; - - var indices = geometry.attributes.index.array; - - for ( var i = 0; i < indices.length; i ++ ) { - - indices[ i ] = i % ( 3 * chunkSize ); - - } - - var positions = geometry.attributes.position.array; - var normals = geometry.attributes.normal.array; - var colors = geometry.attributes.color.array; - - var color = new THREE.Color(); - - var n = 800, n2 = n/2; // triangles spread in the cube - var d = 12, d2 = d/2; // individual triangle size - - var pA = new THREE.Vector3(); - var pB = new THREE.Vector3(); - var pC = new THREE.Vector3(); - - var cb = new THREE.Vector3(); - var ab = new THREE.Vector3(); - - for ( var i = 0; i < positions.length; i += 9 ) { - - // positions - - var x = Math.random() * n - n2; - var y = Math.random() * n - n2; - var z = Math.random() * n - n2; - - var ax = x + Math.random() * d - d2; - var ay = y + Math.random() * d - d2; - var az = z + Math.random() * d - d2; - - var bx = x + Math.random() * d - d2; - var by = y + Math.random() * d - d2; - var bz = z + Math.random() * d - d2; - - var cx = x + Math.random() * d - d2; - var cy = y + Math.random() * d - d2; - var cz = z + Math.random() * d - d2; - - positions[ i ] = ax; - positions[ i + 1 ] = ay; - positions[ i + 2 ] = az; - - positions[ i + 3 ] = bx; - positions[ i + 4 ] = by; - positions[ i + 5 ] = bz; - - positions[ i + 6 ] = cx; - positions[ i + 7 ] = cy; - positions[ i + 8 ] = cz; - - // flat face normals - - pA.set( ax, ay, az ); - pB.set( bx, by, bz ); - pC.set( cx, cy, cz ); - - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); - - cb.normalize(); - - var nx = cb.x; - var ny = cb.y; - var nz = cb.z; - - normals[ i ] = nx; - normals[ i + 1 ] = ny; - normals[ i + 2 ] = nz; - - normals[ i + 3 ] = nx; - normals[ i + 4 ] = ny; - normals[ i + 5 ] = nz; - - normals[ i + 6 ] = nx; - normals[ i + 7 ] = ny; - normals[ i + 8 ] = nz; - - // colors - - var vx = ( x / n ) + 0.5; - var vy = ( y / n ) + 0.5; - var vz = ( z / n ) + 0.5; - - //color.setHSV( 0.5 + 0.5 * vx, 0.25 + 0.75 * vy, 0.25 + 0.75 * vz ); - color.setRGB( vx, vy, vz ); - - colors[ i ] = color.r; - colors[ i + 1 ] = color.g; - colors[ i + 2 ] = color.b; - - colors[ i + 3 ] = color.r; - colors[ i + 4 ] = color.g; - colors[ i + 5 ] = color.b; - - colors[ i + 6 ] = color.r; - colors[ i + 7 ] = color.g; - colors[ i + 8 ] = color.b; - - } - - geometry.offsets = []; - - var offsets = triangles / chunkSize; - - for ( var i = 0; i < offsets; i ++ ) { - - var offset = { - start: i * chunkSize * 3, - index: i * chunkSize * 3, - count: Math.min( triangles - ( i * chunkSize ), chunkSize ) * 3 - }; - - geometry.offsets.push( offset ); - - } - - geometry.computeBoundingSphere(); - - var material = new THREE.MeshPhongMaterial( { - color: 0xaaaaaa, ambient: 0xaaaaaa, specular: 0xffffff, shininess: 250, - side: THREE.DoubleSide, vertexColors: THREE.VertexColors - } ); - - mesh = new THREE.Mesh( geometry, material ); - scene.add( mesh ); - - // - - renderer = new THREE.WebGLRenderer( { antialias: false, clearColor: 0x333333, clearAlpha: 1, alpha: false } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.setClearColor( scene.fog.color, 1 ); - - renderer.gammaInput = true; - renderer.gammaOutput = true; - renderer.physicallyBasedShading = true; - - container.appendChild( renderer.domElement ); - - // - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = Date.now() * 0.001; - - mesh.rotation.x = time * 0.25; - mesh.rotation.y = time * 0.5; - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_buffergeometry_lines.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, scene, renderer; - - var mesh; - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - // - - camera = new THREE.PerspectiveCamera( 27, window.innerWidth / window.innerHeight, 1, 4000 ); - camera.position.z = 2750; - - scene = new THREE.Scene(); - - - var segments = 10000; - - var geometry = new THREE.BufferGeometry(); - var material = new THREE.LineBasicMaterial({ vertexColors: THREE.VertexColors }); - - geometry.attributes = { - position: { - itemSize: 3, - array: new Float32Array(segments * 3), - numItems: segments * 3 - }, - color: { - itemSize: 3, - array: new Float32Array(segments * 3), - numItems: segments * 3 - } - }; - - var positions = geometry.attributes.position.array; - var colors = geometry.attributes.color.array; - - var r = 800; - - for ( var i = 0; i < segments; i ++ ) { - - var x = Math.random() * r - r / 2; - var y = Math.random() * r - r / 2; - var z = Math.random() * r - r / 2; - - // positions - - positions[ i * 3 ] = x; - positions[ i * 3 + 1 ] = y; - positions[ i * 3 + 2 ] = z; - - // colors - - colors[ i * 3 ] = ( x / r ) + 0.5; - colors[ i * 3 + 1 ] = ( y / r ) + 0.5; - colors[ i * 3 + 2 ] = ( z / r ) + 0.5; - - } - - geometry.computeBoundingSphere(); - - mesh = new THREE.Line( geometry, material ); - scene.add( mesh ); - - // - - renderer = new THREE.WebGLRenderer( { antialias: false, clearColor: 0x000000, clearAlpha: 0, alpha: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - renderer.gammaInput = true; - renderer.gammaOutput = true; - renderer.physicallyBasedShading = true; - - container.appendChild( renderer.domElement ); - - // - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = Date.now() * 0.001; - - mesh.rotation.x = time * 0.25; - mesh.rotation.y = time * 0.5; - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_buffergeometry_particles.html - -()=>{ - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, scene, renderer; - - var mesh; - - var particleSystem; - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - // - - camera = new THREE.PerspectiveCamera( 27, window.innerWidth / window.innerHeight, 5, 3500 ); - camera.position.z = 2750; - - scene = new THREE.Scene(); - scene.fog = new THREE.Fog( 0x050505, 2000, 3500 ); - - // - - var particles = 500000; - - var geometry = new THREE.BufferGeometry(); - geometry.attributes = { - - position: { - itemSize: 3, - array: new Float32Array( particles * 3 ), - numItems: particles * 3 - }, - color: { - itemSize: 3, - array: new Float32Array( particles * 3 ), - numItems: particles * 3 - } - - } - - - var positions = geometry.attributes.position.array; - var colors = geometry.attributes.color.array; - - var color = new THREE.Color(); - - var n = 1000, n2 = n / 2; // particles spread in the cube - - for ( var i = 0; i < positions.length; i += 3 ) { - - // positions - - var x = Math.random() * n - n2; - var y = Math.random() * n - n2; - var z = Math.random() * n - n2; - - positions[ i ] = x; - positions[ i + 1 ] = y; - positions[ i + 2 ] = z; - - // colors - - var vx = ( x / n ) + 0.5; - var vy = ( y / n ) + 0.5; - var vz = ( z / n ) + 0.5; - - color.setRGB( vx, vy, vz ); - - colors[ i ] = color.r; - colors[ i + 1 ] = color.g; - colors[ i + 2 ] = color.b; - - } - - geometry.computeBoundingSphere(); - - // - - var material = new THREE.ParticleSystemMaterial( { size: 15, vertexColors: true } ); - - particleSystem = new THREE.ParticleSystem( geometry, material ); - scene.add( particleSystem ); - - // - - renderer = new THREE.WebGLRenderer( { antialias: false, clearColor: 0x333333, clearAlpha: 1, alpha: false } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.setClearColor( scene.fog.color, 1 ); - - container.appendChild( renderer.domElement ); - - // - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = Date.now() * 0.001; - - particleSystem.rotation.x = time * 0.25; - particleSystem.rotation.y = time * 0.5; - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_camera.html - -()=>{ - var SCREEN_WIDTH = window.innerWidth; - var SCREEN_HEIGHT = window.innerHeight; - - var container, stats; - var camera, scene, renderer, mesh; - var cameraRig, activeCamera, activeHelper; - var cameraPerspective, cameraOrtho; - var cameraPerspectiveHelper, cameraOrthoHelper; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - scene = new THREE.Scene(); - - // - - camera = new THREE.PerspectiveCamera( 50, 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 ); - camera.position.z = 2500; - - cameraPerspective = new THREE.PerspectiveCamera( 50, 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT, 150, 1000 ); - - cameraPerspectiveHelper = new THREE.CameraHelper( cameraPerspective ); - scene.add( cameraPerspectiveHelper ); - - // - - cameraOrtho = new THREE.OrthographicCamera( 0.5 * SCREEN_WIDTH / - 2, 0.5 * SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, SCREEN_HEIGHT / - 2, 150, 1000 ); - - cameraOrthoHelper = new THREE.CameraHelper( cameraOrtho ); - scene.add( cameraOrthoHelper ); - - // - - activeCamera = cameraPerspective; - activeHelper = cameraPerspectiveHelper; - - - // counteract different front orientation of cameras vs rig - - cameraOrtho.rotation.y = Math.PI; - cameraPerspective.rotation.y = Math.PI; - - cameraRig = new THREE.Object3D(); - - cameraRig.add( cameraPerspective ); - cameraRig.add( cameraOrtho ); - - scene.add( cameraRig ); - - // - - mesh = new THREE.Mesh( new THREE.SphereGeometry( 100, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true } ) ); - scene.add( mesh ); - - var mesh2 = new THREE.Mesh( new THREE.SphereGeometry( 50, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0x00ff00, wireframe: true } ) ); - mesh2.position.y = 150; - mesh.add( mesh2 ); - - var mesh3 = new THREE.Mesh( new THREE.SphereGeometry( 5, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0x0000ff, wireframe: true } ) ); - mesh3.position.z = 150; - cameraRig.add( mesh3 ); - - // - - var geometry = new THREE.Geometry(); - - for ( var i = 0; i < 10000; i ++ ) { - - var vertex = new THREE.Vector3(); - vertex.x = THREE.Math.randFloatSpread( 2000 ); - vertex.y = THREE.Math.randFloatSpread( 2000 ); - vertex.z = THREE.Math.randFloatSpread( 2000 ); - - geometry.vertices.push( vertex ); - - } - - var particles = new THREE.ParticleSystem( geometry, new THREE.ParticleSystemMaterial( { color: 0x888888 } ) ); - scene.add( particles ); - - // - - - renderer = new THREE.WebGLRenderer( { antialias: true, clearColor: 0x000000, clearAlpha: 1 } ); - renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - renderer.domElement.style.position = "relative"; - container.appendChild( renderer.domElement ); - - renderer.autoClear = false; - - // - - stats = new Stats(); - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - document.addEventListener( 'keydown', onKeyDown, false ); - - } - - // - - function onKeyDown ( event ) { - - switch( event.keyCode ) { - - case 79: /*O*/ - - activeCamera = cameraOrtho; - activeHelper = cameraOrthoHelper; - - break; - - case 80: /*P*/ - - activeCamera = cameraPerspective; - activeHelper = cameraPerspectiveHelper; - - break; - - } - - }; - - // - - function onWindowResize( event ) { - - SCREEN_WIDTH = window.innerWidth; - SCREEN_HEIGHT = window.innerHeight; - - renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - - camera.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT; - camera.updateProjectionMatrix(); - - cameraPerspective.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT; - cameraPerspective.updateProjectionMatrix(); - - cameraOrtho.left = - 0.5 * SCREEN_WIDTH / 2; - cameraOrtho.right = 0.5 * SCREEN_WIDTH / 2; - cameraOrtho.top = SCREEN_HEIGHT / 2; - cameraOrtho.bottom = - SCREEN_HEIGHT / 2; - cameraOrtho.updateProjectionMatrix(); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - - function render() { - - var r = Date.now() * 0.0005; - - mesh.position.x = 700 * Math.cos( r ); - mesh.position.z = 700 * Math.sin( r ); - mesh.position.y = 700 * Math.sin( r ); - - mesh.children[ 0 ].position.x = 70 * Math.cos( 2 * r ); - mesh.children[ 0 ].position.z = 70 * Math.sin( r ); - - if ( activeCamera === cameraPerspective ) { - - cameraPerspective.fov = 35 + 30 * Math.sin( 0.5 * r ); - cameraPerspective.far = mesh.position.length(); - cameraPerspective.updateProjectionMatrix(); - - cameraPerspectiveHelper.update(); - cameraPerspectiveHelper.visible = true; - - cameraOrthoHelper.visible = false; - - } else { - - cameraOrtho.far = mesh.position.length(); - cameraOrtho.updateProjectionMatrix(); - - cameraOrthoHelper.update(); - cameraOrthoHelper.visible = true; - - cameraPerspectiveHelper.visible = false; - - } - - cameraRig.lookAt( mesh.position ); - - renderer.clear(); - - activeHelper.visible = false; - - renderer.setViewport( 0, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT ); - renderer.render( scene, activeCamera ); - - activeHelper.visible = true; - - renderer.setViewport( SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT ); - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_custom_attributes.html - -()=>{ - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var renderer, scene, camera, stats; - - var sphere, uniforms, attributes; - - var noise = []; - - var WIDTH = window.innerWidth, - HEIGHT = window.innerHeight; - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 30, WIDTH / HEIGHT, 1, 10000 ); - camera.position.z = 300; - - scene = new THREE.Scene(); - - attributes = { - - displacement: { type: 'f', value: [] } - - }; - - uniforms = { - - amplitude: { type: "f", value: 1.0 }, - color: { type: "c", value: new THREE.Color( 0xff2200 ) }, - texture: { type: "t", value: THREE.ImageUtils.loadTexture( "textures/water.jpg" ) }, - - }; - - uniforms.texture.value.wrapS = uniforms.texture.value.wrapT = THREE.RepeatWrapping; - - var shaderMaterial = new THREE.ShaderMaterial( { - - uniforms: uniforms, - attributes: attributes, - vertexShader: document.getElementById( 'vertexshader' ).textContent, - fragmentShader: document.getElementById( 'fragmentshader' ).textContent - - }); - - - var radius = 50, segments = 128, rings = 64; - var geometry = new THREE.SphereGeometry( radius, segments, rings ); - geometry.dynamic = true; - - sphere = new THREE.Mesh( geometry, shaderMaterial ); - - var vertices = sphere.geometry.vertices; - var values = attributes.displacement.value; - - for ( var v = 0; v < vertices.length; v++ ) { - - values[ v ] = 0; - noise[ v ] = Math.random() * 5; - - } - - scene.add( sphere ); - - renderer = new THREE.WebGLRenderer( { clearColor: 0x050505, clearAlpha: 1 } ); - renderer.setSize( WIDTH, HEIGHT ); - - var container = document.getElementById( 'container' ); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = Date.now() * 0.01; - - sphere.rotation.y = sphere.rotation.z = 0.01 * time; - - uniforms.amplitude.value = 2.5 * Math.sin( sphere.rotation.y * 0.125 ); - uniforms.color.value.offsetHSL( 0.0005, 0, 0 ); - - for ( var i = 0; i < attributes.displacement.value.length; i ++ ) { - - attributes.displacement.value[ i ] = Math.sin( 0.1 * i + time ); - - noise[ i ] += 0.5 * ( 0.5 - Math.random() ); - noise[ i ] = THREE.Math.clamp( noise[ i ], -5, 5 ); - - attributes.displacement.value[ i ] += noise[ i ]; - - } - - attributes.displacement.needsUpdate = true; - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_custom_attributes_lines.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var renderer, scene, camera, stats; - - var object, uniforms, attributes; - - var text = "three.js", - - height = 15, - size = 50, - - curveSegments = 10, - steps = 40, - - bevelThickness = 5, - bevelSize = 1.5, - bevelSegments = 10, - bevelEnabled = true, - - font = "helvetiker", // helvetiker, optimer, gentilis, droid sans, droid serif - weight = "bold", // normal bold - style = "normal"; // normal italic - - var WIDTH = window.innerWidth, - HEIGHT = window.innerHeight; - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 30, WIDTH / HEIGHT, 1, 10000 ); - camera.position.z = 400; - - scene = new THREE.Scene(); - - attributes = { - - displacement: { type: 'v3', value: [] }, - customColor: { type: 'c', value: [] } - - }; - - uniforms = { - - amplitude: { type: "f", value: 5.0 }, - opacity: { type: "f", value: 0.3 }, - color: { type: "c", value: new THREE.Color( 0xff0000 ) } - - }; - - var shaderMaterial = new THREE.ShaderMaterial( { - - uniforms: uniforms, - attributes: attributes, - vertexShader: document.getElementById( 'vertexshader' ).textContent, - fragmentShader: document.getElementById( 'fragmentshader' ).textContent, - blending: THREE.AdditiveBlending, - depthTest: false, - transparent: true - - }); - - (shaderMaterial).linewidth = 1; - - var geometry = new THREE.TextGeometry( text, { - - size: size, - height: height, - curveSegments: curveSegments, - - font: font, - weight: weight, - style: style, - - bevelThickness: bevelThickness, - bevelSize: bevelSize, - bevelEnabled: bevelEnabled, - bevelSegments: bevelSegments, - - steps: steps - - }); - - geometry.dynamic = true; - - THREE.GeometryUtils.center( geometry ); - - object = new THREE.Line( geometry, shaderMaterial, THREE.LineStrip ); - - var vertices = object.geometry.vertices; - - var displacement = attributes.displacement.value; - var color = attributes.customColor.value; - - for( var v = 0; v < vertices.length; v ++ ) { - - displacement[ v ] = new THREE.Vector3(); - - color[ v ] = new THREE.Color( 0xffffff ); - color[ v ].setHSL( v / vertices.length, 0.5, 0.5 ); - - } - - object.rotation.x = 0.2; - - scene.add( object ); - - renderer = new THREE.WebGLRenderer( { clearColor: 0x050505, clearAlpha: 1, antialias: true } ); - renderer.setSize( WIDTH, HEIGHT ); - - var container = document.getElementById( 'container' ); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = Date.now() * 0.001; - - object.rotation.y = 0.25 * time; - - uniforms.amplitude.value = 0.5 * Math.sin( 0.5 * time ); - uniforms.color.value.offsetHSL( 0.0005, 0, 0 ); - - var nx, ny, nz, value; - - for( var i = 0, il = attributes.displacement.value.length; i < il; i ++ ) { - - nx = 0.3 * ( 0.5 - Math.random() ); - ny = 0.3 * ( 0.5 - Math.random() ); - nz = 0.3 * ( 0.5 - Math.random() ); - - value = attributes.displacement.value[ i ]; - - value.x += nx; - value.y += ny; - value.z += nz; - - } - - attributes.displacement.needsUpdate = true; - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_custom_attributes_particles.html - -()=>{ - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var renderer, scene, camera, stats; - - var sphere, uniforms, attributes; - - var noise = []; - - var WIDTH = window.innerWidth; - var HEIGHT = window.innerHeight; - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 40, WIDTH / HEIGHT, 1, 10000 ); - camera.position.z = 300; - - scene = new THREE.Scene(); - - attributes = { - - size: { type: 'f', value: [] }, - customColor: { type: 'c', value: [] } - - }; - - uniforms = { - - amplitude: { type: "f", value: 1.0 }, - color: { type: "c", value: new THREE.Color( 0xffffff ) }, - texture: { type: "t", value: THREE.ImageUtils.loadTexture( "textures/sprites/spark1.png" ) }, - - }; - - var shaderMaterial = new THREE.ShaderMaterial( { - - uniforms: uniforms, - attributes: attributes, - vertexShader: document.getElementById( 'vertexshader' ).textContent, - fragmentShader: document.getElementById( 'fragmentshader' ).textContent, - - blending: THREE.AdditiveBlending, - depthTest: false, - transparent: true - - }); - - - var radius = 200; - var geometry = new THREE.Geometry(); - - for ( var i = 0; i < 100000; i++ ) { - - var vertex = new THREE.Vector3(); - vertex.x = Math.random() * 2 - 1; - vertex.y = Math.random() * 2 - 1; - vertex.z = Math.random() * 2 - 1; - vertex.multiplyScalar( radius ); - - geometry.vertices.push( vertex ); - - } - - sphere = new THREE.ParticleSystem( geometry, shaderMaterial ); - - sphere.dynamic = true; - //sphere.sortParticles = true; - - var vertices = sphere.geometry.vertices; - var values_size = attributes.size.value; - var values_color = attributes.customColor.value; - - - for( var v = 0; v < vertices.length; v++ ) { - - values_size[ v ] = 10; - values_color[ v ] = new THREE.Color( 0xffaa00 ); - - if ( vertices[ v ].x < 0 ) - values_color[ v ].setHSL( 0.5 + 0.1 * ( v / vertices.length ), 0.7, 0.9 ); - else - values_color[ v ].setHSL( 0.0 + 0.1 * ( v / vertices.length ), 0.9, 0.9 ); - - } - - scene.add( sphere ); - - renderer = new THREE.WebGLRenderer( { clearColor: 0x000000, clearAlpha: 1 } ); - renderer.setSize( WIDTH, HEIGHT ); - - var container = document.getElementById( 'container' ); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = Date.now() * 0.005; - - sphere.rotation.z = 0.01 * time; - - for( var i = 0; i < attributes.size.value.length; i++ ) { - - attributes.size.value[ i ] = 14 + 13 * Math.sin( 0.1 * i + time ); - - - } - - attributes.size.needsUpdate = true; - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_custom_attributes_particles2.html - -()=>{ - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var renderer, scene, camera, stats; - - var sphere, uniforms, attributes; - - var vc1; - - var WIDTH = window.innerWidth; - var HEIGHT = window.innerHeight; - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 45, WIDTH / HEIGHT, 1, 10000 ); - camera.position.z = 300; - - scene = new THREE.Scene(); - - attributes = { - - size: { type: 'f', value: [] }, - ca: { type: 'c', value: [] } - - }; - - uniforms = { - - amplitude: { type: "f", value: 1.0 }, - color: { type: "c", value: new THREE.Color( 0xffffff ) }, - texture: { type: "t", value: THREE.ImageUtils.loadTexture( "textures/sprites/disc.png" ) }, - - }; - - uniforms.texture.value.wrapS = uniforms.texture.value.wrapT = THREE.RepeatWrapping; - - var shaderMaterial = new THREE.ShaderMaterial( { - - uniforms: uniforms, - attributes: attributes, - vertexShader: document.getElementById( 'vertexshader' ).textContent, - fragmentShader: document.getElementById( 'fragmentshader' ).textContent, - transparent: true - - }); - - - var radius = 100, segments = 68, rings = 38; - var geometry = new THREE.SphereGeometry( radius, segments, rings ); - - vc1 = geometry.vertices.length; - - var geometry2 = new THREE.CubeGeometry( 0.8 * radius, 0.8 * radius, 0.8 * radius, 10, 10, 10 ); - - THREE.GeometryUtils.merge( geometry, geometry2 ); - - sphere = new THREE.ParticleSystem( geometry, shaderMaterial ); - - sphere.dynamic = true; - sphere.sortParticles = true; - - var vertices = sphere.geometry.vertices; - var values_size = attributes.size.value; - var values_color = attributes.ca.value; - - for( var v = 0; v < vertices.length; v++ ) { - - values_size[ v ] = 10; - values_color[ v ] = new THREE.Color( 0xffffff ); - - if ( v < vc1 ) { - - values_color[ v ].setHSL( 0.01 + 0.1 * ( v / vc1 ), 0.99, ( vertices[ v ].y + radius ) / ( 2 *radius ) ); - - } else { - - values_size[ v ] = 40; - values_color[ v ].setHSL( 0.6, 0.75, 0.5 + vertices[ v ].y / ( 0.8 * radius ) ); - - } - - } - - scene.add( sphere ); - - renderer = new THREE.WebGLRenderer( { clearColor: 0x000000, clearAlpha: 1 } ); - renderer.setSize( WIDTH, HEIGHT ); - - var container = document.getElementById( 'container' ); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = Date.now() * 0.005; - - sphere.rotation.y = 0.02 * time; - sphere.rotation.z = 0.02 * time; - - for( var i = 0; i < attributes.size.value.length; i ++ ) { - - if ( i < vc1 ) - attributes.size.value[ i ] = 16 + 12 * Math.sin( 0.1 * i + time ); - - - } - - attributes.size.needsUpdate = true; - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_custom_attributes_particles3.html - -()=>{ - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var renderer, scene, camera, stats; - - var object, uniforms, attributes; - - var vc1; - - var WIDTH = window.innerWidth; - var HEIGHT = window.innerHeight; - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 40, WIDTH / HEIGHT, 1, 1000 ); - camera.position.z = 500; - - scene = new THREE.Scene(); - - attributes = { - - size: { type: 'f', value: [] }, - ca: { type: 'c', value: [] } - - }; - - uniforms = { - - amplitude: { type: "f", value: 1.0 }, - color: { type: "c", value: new THREE.Color( 0xffffff ) }, - texture: { type: "t", value: THREE.ImageUtils.loadTexture( "textures/sprites/ball.png" ) }, - - }; - - uniforms.texture.value.wrapS = uniforms.texture.value.wrapT = THREE.RepeatWrapping; - - var shaderMaterial = new THREE.ShaderMaterial( { - - uniforms: uniforms, - attributes: attributes, - vertexShader: document.getElementById( 'vertexshader' ).textContent, - fragmentShader: document.getElementById( 'fragmentshader' ).textContent - - }); - - - var radius = 100, inner = 0.6 * radius; - var geometry = new THREE.Geometry(); - - for ( var i = 0; i < 100000; i ++ ) { - - var vertex = new THREE.Vector3(); - vertex.x = Math.random() * 2 - 1; - vertex.y = Math.random() * 2 - 1; - vertex.z = Math.random() * 2 - 1; - vertex.multiplyScalar( radius ); - - if ( ( vertex.x > inner || vertex.x < -inner ) || - ( vertex.y > inner || vertex.y < -inner ) || - ( vertex.z > inner || vertex.z < -inner ) ) - - geometry.vertices.push( vertex ); - - } - - vc1 = geometry.vertices.length; - - var m, dummyMaterial = new THREE.MeshFaceMaterial(); - - radius = 200; - var geometry2 = new THREE.CubeGeometry( radius, 0.1 * radius, 0.1 * radius, 50, 5, 5 ); - - function addGeo( geo, x, y, z, ry ) { - - m = new THREE.Mesh( geo, dummyMaterial ); - m.position.set( x, y, z ); - m.rotation.y = ry; - - THREE.GeometryUtils.merge( geometry, m ); - - } - - // side 1 - - addGeo( geometry2, 0, 110, 110, 0 ); - addGeo( geometry2, 0, 110, -110, 0 ); - addGeo( geometry2, 0, -110, 110, 0 ); - addGeo( geometry2, 0, -110, -110, 0 ); - - // side 2 - - addGeo( geometry2, 110, 110, 0, Math.PI/2 ); - addGeo( geometry2, 110, -110, 0, Math.PI/2 ); - addGeo( geometry2, -110, 110, 0, Math.PI/2 ); - addGeo( geometry2, -110, -110, 0, Math.PI/2 ); - - // corner edges - - var geometry3 = new THREE.CubeGeometry( 0.1 * radius, radius * 1.2, 0.1 * radius, 5, 60, 5 ); - - addGeo( geometry3, 110, 0, 110, 0 ); - addGeo( geometry3, 110, 0, -110, 0 ); - addGeo( geometry3, -110, 0, 110, 0 ); - addGeo( geometry3, -110, 0, -110, 0 ); - - // particle system - - object = new THREE.ParticleSystem( geometry, shaderMaterial ); - object.dynamic = true; - - // custom attributes - - var vertices = object.geometry.vertices; - - var values_size = attributes.size.value; - var values_color = attributes.ca.value; - - for( var v = 0; v < vertices.length; v ++ ) { - - values_size[ v ] = 10; - values_color[ v ] = new THREE.Color( 0xffffff ); - - if ( v < vc1 ) { - - values_color[ v ].setHSL( 0.5 + 0.2 * ( v / vc1 ), 0.99, 1.0 ); - - } else { - - values_size[ v ] = 55; - values_color[ v ].setHSL( 0.1, 0.99, 1.0 ); - - } - - } - - //console.log( vertices.length ); - - scene.add( object ); - - renderer = new THREE.WebGLRenderer( { clearColor: 0x000000, clearAlpha: 1 } ); - renderer.setSize( WIDTH, HEIGHT ); - - var container = document.getElementById( 'container' ); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = Date.now() * 0.01; - - object.rotation.y = object.rotation.z = 0.02 * time; - - for( var i = 0; i < attributes.size.value.length; i ++ ) { - - if ( i < vc1 ) - attributes.size.value[ i ] = Math.max(0, 26 + 32 * Math.sin( 0.1 * i + 0.6 * time )); - - - } - - attributes.size.needsUpdate = true; - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_custom_attributes_ribbons.html - -()=>{ - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - var camera, scene, renderer; - - var materials = []; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 3000 ); - camera.position.z = 1200; - - scene = new THREE.Scene(); - scene.fog = new THREE.FogExp2( 0x000000, 0.0016 ); - - // - - var vertexShader = document.getElementById( 'vertexShader' ).textContent; - var fragmentShader = document.getElementById( 'fragmentShader' ).textContent; - - var attributes = { customColor: { type: 'c', boundTo: 'vertices', value: [] }, - position2: { type: 'v3', boundTo: 'vertices', value: [] } - }; - - var uniforms = { ratio: { type: "f", value: 1.0 }, - color: { type: "c", value: new THREE.Color( 0xffffff ) } - }; - - //TS bug: https://typescript.codeplex.com/workitem/2036 - //var material = new THREE.ShaderMaterial( { uniforms: uniforms, attributes: attributes, vertexShader: vertexShader, fragmentShader: fragmentShader, side: THREE.DoubleSide } ); - var material = new THREE.ShaderMaterial( { uniforms: uniforms, attributes: attributes, vertexShader: vertexShader, fragmentShader: fragmentShader, side: THREE.DoubleSide } ); - - var position2 = attributes.position2.value; - var colors = attributes.customColor.value; - - // - - var geometry = new THREE.Geometry(); - - var i, i2; - var x1, y1, z1; - var x2, y2, z2; - var color; - - var n = 200; - - for ( i = -n; i < n; i ++ ) { - - i2 = i + n; - - x1 = 10 * i; - y1 = - 50 + ( i2 % 2 ) * 100 - Math.cos( 4 * Math.PI * i/n ) * 50; - z1 = 0; - - x2 = x1; - y2 = y1 + Math.cos( 4 * Math.PI * i/n ) * 100; - z2 = z1; - - var h = i2 % 2 ? 1 : 0.15; - if ( i2 % 4 <= 2 ) h -= 0.15; - - color = new THREE.Color( 0xffffff ); - color.setHSL( 0.1 * Math.random(), 0.15, h ); - - position2[ geometry.vertices.length ] = new THREE.Vector3( x2, y2, z2 ); - colors[ geometry.vertices.length ] = color; - - geometry.vertices.push( new THREE.Vector3( x1, y1, z1 ) ); - - } - // - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.setClearColor( scene.fog.color, 1 ); - - container.appendChild( renderer.domElement ); - - // - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onDocumentMouseMove( event ) { - - mouseX = event.clientX - windowHalfX; - mouseY = event.clientY - windowHalfY; - - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length === 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length === 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = Date.now() * 0.0025; - - //camera.position.x += ( mouseX - camera.position.x ) * 0.036; - //camera.position.y += ( - mouseY - camera.position.y ) * 0.036; - - camera.lookAt( scene.position ); - - for ( var i = 0; i < materials.length; i ++ ) { - - var uniforms = materials[ i ].uniforms; - uniforms.ratio.value = 0.5 * ( Math.sin( time ) + 1 ); - - } - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometries.html - -()=>{ - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, scene, renderer; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 ); - camera.position.y = 400; - - scene = new THREE.Scene(); - - var light, object, object2, materials: THREE.Material[]; - - scene.add( new THREE.AmbientLight( 0x404040 ) ); - - light = new THREE.DirectionalLight( 0xffffff ); - light.position.set( 0, 1, 0 ); - scene.add( light ); - - var map = THREE.ImageUtils.loadTexture( 'textures/ash_uvgrid01.jpg' ); - map.wrapS = map.wrapT = THREE.RepeatWrapping; - map.anisotropy = 16; - - materials = [ - new THREE.MeshLambertMaterial( { ambient: 0xbbbbbb, map: map, side: THREE.DoubleSide } ), - new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true, transparent: true, opacity: 0.1, side: THREE.DoubleSide } ) - ]; - - object = THREE.SceneUtils.createMultiMaterialObject( new THREE.CubeGeometry( 100, 100, 100, 4, 4, 4 ), materials ); - object.position.set( -200, 0, 400 ); - scene.add( object ); - - object = THREE.SceneUtils.createMultiMaterialObject( new THREE.CylinderGeometry( 25, 75, 100, 40, 5 ), materials ); - object.position.set( 0, 0, 400 ); - scene.add( object ); - - object = THREE.SceneUtils.createMultiMaterialObject( new THREE.IcosahedronGeometry( 75, 1 ), materials ); - object.position.set( -200, 0, 200 ); - scene.add( object ); - - object = THREE.SceneUtils.createMultiMaterialObject( new THREE.OctahedronGeometry( 75, 2 ), materials ); - object.position.set( 0, 0, 200 ); - scene.add( object ); - - - object = THREE.SceneUtils.createMultiMaterialObject( new THREE.TetrahedronGeometry( 75, 0 ), materials ); - object.position.set( 200, 0, 200 ); - scene.add( object ); - - object = THREE.SceneUtils.createMultiMaterialObject( new THREE.PlaneGeometry( 100, 100, 4, 4 ), materials ); - object.position.set( -200, 0, 0 ); - scene.add( object ); - - object2 = THREE.SceneUtils.createMultiMaterialObject( new THREE.CircleGeometry( 50, 10, 0, Math.PI ), materials ); - object2.rotation.x = Math.PI/2; - object.add( object2 ); - - object = THREE.SceneUtils.createMultiMaterialObject( new THREE.SphereGeometry( 75, 20, 10 ), materials ); - object.position.set( 0, 0, 0 ); - scene.add( object ); - - var points = []; - - for ( var i = 0; i < 50; i ++ ) { - - points.push( new THREE.Vector3( Math.sin( i * 0.2 ) * 15 + 50, 0, ( i - 5 ) * 2 ) ); - - } - - object = THREE.SceneUtils.createMultiMaterialObject( new THREE.LatheGeometry( points, 20 ), materials ); - object.position.set( 200, 0, 0 ); - scene.add( object ); - - object = THREE.SceneUtils.createMultiMaterialObject( new THREE.TorusGeometry( 50, 20, 20, 20 ), materials ); - object.position.set( -200, 0, -200 ); - scene.add( object ); - - object = THREE.SceneUtils.createMultiMaterialObject( new THREE.TorusKnotGeometry( 50, 10, 50, 20 ), materials ); - object.position.set( 0, 0, -200 ); - scene.add( object ); - - object = new THREE.AxisHelper( 50 ); - object.position.set( 200, 0, -200 ); - scene.add( object ); - - object = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 0 ), 50 ); - object.position.set( 200, 0, 400 ); - scene.add( object ); - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var timer = Date.now() * 0.0001; - - camera.position.x = Math.cos( timer ) * 800; - camera.position.z = Math.sin( timer ) * 800; - - camera.lookAt( scene.position ); - - for ( var i = 0, l = scene.children.length; i < l; i ++ ) { - - var object = scene.children[ i ]; - - object.rotation.x = timer * 5; - object.rotation.y = timer * 2.5; - - } - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometries2.html - -()=>{ - /* Testing the new Parametric Surfaces Geometries*/ - - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, scene, renderer; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 ); - camera.position.y = 400; - - scene = new THREE.Scene(); - - var light, object, materials: THREE.Material[]; - - scene.add( new THREE.AmbientLight( 0x404040 ) ); - - light = new THREE.DirectionalLight( 0xffffff ); - light.position.set( 0, 0, 1 ); - scene.add( light ); - - var map = THREE.ImageUtils.loadTexture( 'textures/ash_uvgrid01.jpg' ); - map.wrapS = map.wrapT = THREE.RepeatWrapping; - map.anisotropy = 16; - - materials = [ - new THREE.MeshLambertMaterial( { ambient: 0xbbbbbb, map: map, side: THREE.DoubleSide } ), - new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true, transparent: true, opacity: 0.1, side: THREE.DoubleSide } ) - ]; - - - var heightScale = 1; - var p = 2; - var q = 3; - var radius = 150, tube = 10, segmentsR = 50, segmentsT = 20; - - var GrannyKnot = new THREE.Curves.GrannyKnot(); - - var torus2 = new THREE.ParametricGeometries.TorusKnotGeometry( radius, tube, segmentsR, segmentsT, p , q, heightScale ); - var sphere2 = new THREE.ParametricGeometries.SphereGeometry( 75, 20, 10 ); - var tube2 = new THREE.ParametricGeometries.TubeGeometry( GrannyKnot, 150, 2, 8, true, false ); - - // var torus = new THREE.TorusKnotGeometry( radius, tube, segmentsR, segmentsT, p , q, heightScale ); - // var sphere = new THREE.SphereGeometry( 75, 20, 10 ); - // var tube = new THREE.TubeGeometry( GrannyKnot, 150, 2, 8, true, false ); - - - // var benchmarkCopies = 1000; - // var benchmarkObject = tube; - // var rand = function() { return (Math.random() - 0.5 ) * 600; }; - // for (var b=0;b{ - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, scene, renderer; - - var mesh, mesh2, mesh3, light; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.z = 1800; - - scene = new THREE.Scene(); - - light = new THREE.DirectionalLight( 0xffffff ); - light.position.set( 0, 0, 1 ).normalize(); - scene.add( light ); - - var loader = new THREE.JSONLoader(); - - loader.load( "obj/cubecolors/cubecolors.js", createScene1 ); - loader.load( "obj/cubecolors/cube_fvc.js", createScene2 ); - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function createScene1( geometry, materials ) { - - materials[ 0 ].shading = THREE.FlatShading; - - mesh = new THREE.Object3D(); - mesh.position.x = 400; - mesh.scale.x = mesh.scale.y = mesh.scale.z = 250; - scene.add( mesh ); - - var part1 = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) ); - mesh.add( part1 ); - - var part2 = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: 0xffffff, opacity: 0.9, shading: THREE.FlatShading, wireframe: true, wireframeLinewidth: 2, transparent: true } ) ); - mesh.add( part2 ); - - } - - function createScene2( geometry, materials ) { - - materials[ 0 ].shading = THREE.FlatShading; - - mesh2 = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) ); - mesh2.position.x = - 400; - mesh2.scale.x = mesh2.scale.y = mesh2.scale.z = 250; - scene.add( mesh2 ); - - } - - function onDocumentMouseMove( event ) { - - mouseX = ( event.clientX - windowHalfX ); - mouseY = ( event.clientY - windowHalfY ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - camera.position.x += ( mouseX - camera.position.x ) * 0.05; - camera.position.y += ( - mouseY - camera.position.y ) * 0.05; - - camera.lookAt( scene.position ); - - if ( mesh ) { - - mesh.rotation.x += 0.01; - mesh.rotation.y += 0.01; - } - - if ( mesh2 ) { - - mesh2.rotation.x += 0.01; - mesh2.rotation.y += 0.01; - - } - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_convex.html - -()=>{ - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, scene, renderer; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 ); - camera.position.y = 400; - - scene = new THREE.Scene(); - - var light, object, materials: THREE.Material[]; - - scene.add( new THREE.AmbientLight( 0x404040 ) ); - - light = new THREE.DirectionalLight( 0xffffff ); - light.position.set( 0, 1, 0 ); - scene.add( light ); - - var map = THREE.ImageUtils.loadTexture( 'textures/ash_uvgrid01.jpg' ); - map.wrapS = map.wrapT = THREE.RepeatWrapping; - map.anisotropy = 16; - - materials = [ - new THREE.MeshLambertMaterial( { ambient: 0xbbbbbb, map: map } ), - new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true, transparent: true, opacity: 0.1 } ) - ]; - - object = new THREE.AxisHelper( 50 ); - object.position.set( 200, 0, -200 ); - scene.add( object ); - - object = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 0 ), 50 ); - object.position.set( 200, 0, 400 ); - scene.add( object ); - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - - function randomPointInSphere( radius ) { - - return new THREE.Vector3( - ( Math.random() - 0.5 ) * 2 * radius, - ( Math.random() - 0.5 ) * 2 * radius, - ( Math.random() - 0.5 ) * 2 * radius - ); - - } - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var timer = Date.now() * 0.0001; - - camera.position.x = Math.cos( timer ) * 800; - camera.position.z = Math.sin( timer ) * 800; - - camera.lookAt( scene.position ); - - for ( var i = 0, l = scene.children.length; i < l; i ++ ) { - - var object = scene.children[ i ]; - - object.rotation.x = timer * 5; - object.rotation.y = timer * 2.5; - - } - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_cube.html - -()=>{ - var camera, scene, renderer; - var mesh; - - init(); - animate(); - - function init() { - - renderer = new THREE.WebGLRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - document.body.appendChild( renderer.domElement ); - - // - - camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.z = 400; - - scene = new THREE.Scene(); - - var geometry = new THREE.CubeGeometry( 200, 200, 200 ); - - var texture = THREE.ImageUtils.loadTexture( 'textures/crate.gif' ); - texture.anisotropy = renderer.getMaxAnisotropy(); - - var material = new THREE.MeshBasicMaterial( { map: texture } ); - - mesh = new THREE.Mesh( geometry, material ); - scene.add( mesh ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function animate() { - - requestAnimationFrame( animate ); - - mesh.rotation.x += 0.005; - mesh.rotation.y += 0.01; - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_dynamic.html - -()=>{ - if ( ! Detector.webgl ) { - - Detector.addGetWebGLMessage(); - document.getElementById( 'container' ).innerHTML = ""; - - } - - var container, stats; - - var camera, controls, scene, renderer; - - var mesh, texture, geometry, material; - - var worldWidth = 128, worldDepth = 128, - worldHalfWidth = worldWidth / 2, worldHalfDepth = worldDepth / 2; - - var clock = new THREE.Clock(); - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 20000 ); - camera.position.y = 200; - - controls = new THREE.FirstPersonControls( camera ); - - controls.movementSpeed = 500; - controls.lookSpeed = 0.1 - - scene = new THREE.Scene(); - scene.fog = new THREE.FogExp2( 0xaaccff, 0.0007 ); - - geometry = new THREE.PlaneGeometry( 20000, 20000, worldWidth - 1, worldDepth - 1 ); - geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) ); - geometry.dynamic = true; - - var i, j, il, jl; - - for ( i = 0, il = geometry.vertices.length; i < il; i ++ ) { - - geometry.vertices[ i ].y = 35 * Math.sin( i/2 ); - - } - - - //console.log( "triangles: " + geometry.faces.length * 2 + " faces: " + geometry.faces.length + " vertices: " + geometry.vertices.length ); - - geometry.computeFaceNormals(); - geometry.computeVertexNormals(); - - var texture = THREE.ImageUtils.loadTexture( "textures/water.jpg" ); - texture.wrapS = texture.wrapT = THREE.RepeatWrapping; - texture.repeat.set( 5, 5 ); - - material = new THREE.MeshBasicMaterial( { color: 0x0044ff, map: texture } ); - - mesh = new THREE.Mesh( geometry, material ); - scene.add( mesh ); - - renderer = new THREE.WebGLRenderer( { clearColor: 0xaaccff, clearAlpha: 1 } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.innerHTML = ""; - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - controls.handleResize(); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var delta = clock.getDelta(), - time = clock.getElapsedTime() * 10; - - for ( var i = 0, l = geometry.vertices.length; i < l; i ++ ) { - - geometry.vertices[ i ].y = 35 * Math.sin( i / 5 + ( time + i ) / 7 ); - - } - - //geometry.computeFaceNormals(); - //geometry.computeVertexNormals(); - - mesh.geometry.verticesNeedUpdate = true; - //mesh.geometry.normalsNeedUpdate = true; - - controls.update( delta ); - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_extrude_shapes.html - -()=>{ - var container, stats; - - var camera, scene, renderer; - - var text, plane; - - var targetRotation = 0; - var targetRotationOnMouseDown = 0; - - var mouseX = 0; - var mouseXOnMouseDown = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var parent; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - var info = document.createElement( 'div' ); - info.style.position = 'absolute'; - info.style.top = '10px'; - info.style.width = '100%'; - info.style.textAlign = 'center'; - info.innerHTML = 'Shapes Extrusion via Spline path
    Drag to spin'; - container.appendChild( info ); - - camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.set( 0, 150, 500 ); - - scene = new THREE.Scene(); - - var light = new THREE.DirectionalLight( 0xffffff ); - light.position.set( 0, 0, 1 ); - scene.add( light ); - - parent = new THREE.Object3D(); - parent.position.y = 50; - scene.add( parent ); - - function addGeometry( geometry, color, x, y, z, rx, ry, rz, s ) { - - // 3d shape - - var mesh = THREE.SceneUtils.createMultiMaterialObject( geometry, [ new THREE.MeshLambertMaterial( { color: color, opacity: 0.2, transparent: true } ), new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true, opacity: 0.3 } ) ] ); - - mesh.position.set( x, y, z - 75 ); - // mesh.rotation.set( rx, ry, rz ); - mesh.scale.set( s, s, s ); - - if ( geometry.debug ) mesh.add( geometry.debug ); - - parent.add( mesh ); - - } - - var extrudeSettings: { amount: number; bevelEnabled: boolean; bevelSegments: number; steps: number; extrudePath: THREE.Path; }; - extrudeSettings = { amount: 200, bevelEnabled: true, bevelSegments: 2, steps: 150, extrudePath: new THREE.Path() }; // bevelSegments: 2, steps: 2 , bevelSegments: 5, bevelSize: 8, bevelThickness:5, - - // var extrudePath = new THREE.Path(); - - // extrudePath.moveTo( 0, 0 ); - // extrudePath.lineTo( 10, 10 ); - // extrudePath.quadraticCurveTo( 80, 60, 160, 10 ); - // extrudePath.quadraticCurveTo( 240, -40, 320, 10 ); - - - extrudeSettings.bevelEnabled = false; - - // Circle - - var circleRadius = 4; - var circleShape = new THREE.Shape(); - circleShape.moveTo( 0, circleRadius ); - circleShape.quadraticCurveTo( circleRadius, circleRadius, circleRadius, 0 ); - circleShape.quadraticCurveTo( circleRadius, -circleRadius, 0, -circleRadius ); - circleShape.quadraticCurveTo( -circleRadius, -circleRadius, -circleRadius, 0 ); - circleShape.quadraticCurveTo( -circleRadius, circleRadius, 0, circleRadius); - - var rectLength = 12, rectWidth = 4; - - var rectShape = new THREE.Shape(); - - rectShape.moveTo( -rectLength/2, -rectWidth/2 ); - rectShape.lineTo( -rectLength/2, rectWidth/2 ); - rectShape.lineTo( rectLength/2, rectWidth/2 ); - rectShape.lineTo( rectLength/2, -rectLength/2 ); - rectShape.lineTo( -rectLength/2, -rectLength/2 ); - - - var pts = [], starPoints = 5, l; - - for ( var i = 0; i < starPoints * 2; i ++ ) { - - if ( i % 2 == 1 ) { - - l = 5; - - } else { - - l = 10; - - } - - var a = i / starPoints * Math.PI; - pts.push( new THREE.Vector2 ( Math.cos( a ) * l, Math.sin( a ) * l ) ); - - } - - var starShape = new THREE.Shape( pts ); - - // Smiley - - var smileyShape = new THREE.Shape(); - smileyShape.moveTo( 80, 40 ); - smileyShape.arc( 40, 40, 40, 0, Math.PI*2, false ); - - var smileyEye1Path = new THREE.Path(); - smileyEye1Path.moveTo( 35, 20 ); - smileyEye1Path.arc( 25, 20, 10, 0, Math.PI*2, true ); - smileyShape.holes.push( smileyEye1Path ); - - var smileyEye2Path = new THREE.Path(); - smileyEye2Path.moveTo( 65, 20 ); - smileyEye2Path.arc( 55, 20, 10, 0, Math.PI*2, true ); - smileyShape.holes.push( smileyEye2Path ); - - var smileyMouthPath = new THREE.Path(); - - smileyMouthPath.moveTo( 20, 40 ); - smileyMouthPath.quadraticCurveTo( 40, 60, 60, 40 ); - smileyMouthPath.bezierCurveTo( 70, 45, 70, 50, 60, 60 ); - smileyMouthPath.quadraticCurveTo( 40, 80, 20, 60 ); - smileyMouthPath.quadraticCurveTo( 5, 50, 20, 40 ); - - smileyShape.holes.push( smileyMouthPath ); - - var circle3d = starShape.extrude( extrudeSettings ); //circleShape rectShape smileyShape starShape - // var circle3d = new THREE.ExtrudeGeometry(circleShape, extrudeBend, extrudeSettings ); - - var tube = new THREE.TubeGeometry(extrudeSettings.extrudePath, 150, 4, 5, false); - // new THREE.TubeGeometry(extrudePath, segments, 2, radiusSegments, closed2, debug); - - - addGeometry( circle3d, 0xff1111, -100, 0, 0, 0, 0, 0, 1 ); - addGeometry( tube, 0x00ff11, 0, 0, 0, 0, 0, 0, 1 ); - console.log(tube); - - // - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousedown', onDocumentMouseDown, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - -} - -function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - -} - -// - -function onDocumentMouseDown( event ) { - - event.preventDefault(); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'mouseup', onDocumentMouseUp, false ); - document.addEventListener( 'mouseout', onDocumentMouseOut, false ); - - mouseXOnMouseDown = event.clientX - windowHalfX; - targetRotationOnMouseDown = targetRotation; - -} - -function onDocumentMouseMove( event ) { - - mouseX = event.clientX - windowHalfX; - - targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.02; - -} - -function onDocumentMouseUp( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - document.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - document.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - -} - -function onDocumentMouseOut( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - document.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - document.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - -} - -function onDocumentTouchStart( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX; - targetRotationOnMouseDown = targetRotation; - - } - -} - -function onDocumentTouchMove( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05; - - } - -} - -// - -function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - -} - -function render() { - - parent.rotation.y += ( targetRotation - parent.rotation.y ) * 0.05; - renderer.render( scene, camera ); - -} -}; - - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_extrude_splines.html - -()=>{ - var container, stats; - - var camera, scene, renderer, splineCamera, cameraHelper, cameraEye; - - var text, plane; - - var targetRotation = 0; - var targetRotationOnMouseDown = 0; - - var mouseX = 0; - var mouseXOnMouseDown = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var binormal = new THREE.Vector3(); - var normal = new THREE.Vector3(); - - // Keep a dictionary of Curve instances - var splines = { - GrannyKnot: new THREE.Curves.GrannyKnot(), - HeartCurve: new THREE.Curves.HeartCurve(3.5), - VivianiCurve: new THREE.Curves.VivianiCurve(70), - KnotCurve: new THREE.Curves.KnotCurve(), - HelixCurve: new THREE.Curves.HelixCurve(), - TrefoilKnot: new THREE.Curves.TrefoilKnot(), - TorusKnot: new THREE.Curves.TorusKnot(20), - CinquefoilKnot: new THREE.Curves.CinquefoilKnot(20), - TrefoilPolynomialKnot: new THREE.Curves.TrefoilPolynomialKnot(14), - FigureEightPolynomialKnot: new THREE.Curves.FigureEightPolynomialKnot(), - DecoratedTorusKnot4a: new THREE.Curves.DecoratedTorusKnot4a(), - DecoratedTorusKnot4b: new THREE.Curves.DecoratedTorusKnot4b(), - DecoratedTorusKnot5a: new THREE.Curves.DecoratedTorusKnot5a(), - DecoratedTorusKnot5c: new THREE.Curves.DecoratedTorusKnot5c() - }; - - - - - var extrudePath = new THREE.Curves.TrefoilKnot(); - - var dropdown = ''; - - var closed2 = true; - var debug = true; - var parent; - var tube, tubeMesh; - var animation = false, lookAhead = false; - var scale; - var showCameraHelper = false; - - function addTube() { - - var value = (document.getElementById('dropdown')).value; - - var segments = parseInt((document.getElementById('segments')).value); - closed2 = (document.getElementById('closed')).checked; - debug = (document.getElementById('debug')).checked; - - var radiusSegments = parseInt((document.getElementById('radiusSegments')).value); - - console.log('adding tube', value, closed2, debug, radiusSegments); - if (tubeMesh) parent.remove(tubeMesh); - - extrudePath = splines[value]; - - tube = new THREE.TubeGeometry(extrudePath, segments, 2, radiusSegments, closed2); - - addGeometry(tube, 0xff00ff); - setScale(); - - } - - function setScale() { - - scale = parseInt( (document.getElementById('scale')).value ); - tubeMesh.scale.set( scale, scale, scale ); - - } - - - function addGeometry( geometry, color ) { - - // 3d shape - - tubeMesh = THREE.SceneUtils.createMultiMaterialObject( geometry, [ - new THREE.MeshLambertMaterial({ - color: color, - opacity: geometry.debug ? 0.2 : 0.8, - transparent: true - }), - new THREE.MeshBasicMaterial({ - color: 0x000000, - opacity: 0.5, - wireframe: true - })]); - - if ( geometry.debug ) tubeMesh.add( geometry.debug ); - - parent.add( tubeMesh ); - - } - - function animateCamera( toggle ) { - - if ( toggle ) { - - animation = animation === false; - (document.getElementById('animation')).value = 'Camera Spline Animation View: ' + (animation? 'ON': 'OFF'); - - } - - lookAhead = (document.getElementById('lookAhead')).checked; - - showCameraHelper = (document.getElementById('cameraHelper')).checked; - - cameraHelper.visible = showCameraHelper; - cameraEye.visible = showCameraHelper; - } - - - init(); - animate(); - - function init() { - - container = document.createElement('div'); - document.body.appendChild(container); - - var info = document.createElement('div'); - info.style.position = 'absolute'; - info.style.top = '10px'; - info.style.width = '100%'; - info.style.textAlign = 'center'; - info.innerHTML = 'Spline Extrusion Examples by
    zz85
    Select spline:'; - - info.innerHTML += dropdown; - - info.innerHTML += '
    Scale: '; - info.innerHTML += '
    Extrusion Segments: '; - info.innerHTML += '
    Radius Segments: '; - info.innerHTML += '
    Debug normals: Closed:'; - - info.innerHTML += '


    Look Ahead Camera Helper '; - - container.appendChild(info); - - // - - camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.01, 1000); - camera.position.set(0, 50, 500); - - scene = new THREE.Scene(); - - var light = new THREE.DirectionalLight( 0xffffff ); - light.position.set( 0, 0, 1 ); - scene.add( light ); - - parent = new THREE.Object3D(); - parent.position.y = 100; - scene.add( parent ); - - splineCamera = new THREE.PerspectiveCamera( 84, window.innerWidth / window.innerHeight, 0.01, 1000 ); - parent.add( splineCamera ); - - cameraHelper = new THREE.CameraHelper( splineCamera ); - scene.add( cameraHelper ); - - addTube(); - - // Debug point - - cameraEye = new THREE.Mesh( new THREE.SphereGeometry( 5 ), new THREE.MeshBasicMaterial( { color: 0xdddddd } ) ); - parent.add( cameraEye ); - - cameraHelper.visible = showCameraHelper; - cameraEye.visible = showCameraHelper; - - // - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - renderer.domElement.addEventListener( 'mousedown', onDocumentMouseDown, false ); - renderer.domElement.addEventListener( 'touchstart', onDocumentTouchStart, false ); - renderer.domElement.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function onDocumentMouseDown(event) { - - event.preventDefault(); - - renderer.domElement.addEventListener( 'mousemove', onDocumentMouseMove, false ); - renderer.domElement.addEventListener( 'mouseup', onDocumentMouseUp, false ); - renderer.domElement.addEventListener( 'mouseout', onDocumentMouseOut, false ); - - mouseXOnMouseDown = event.clientX - windowHalfX; - targetRotationOnMouseDown = targetRotation; - - } - - function onDocumentMouseMove(event) { - - mouseX = event.clientX - windowHalfX; - - targetRotation = targetRotationOnMouseDown + (mouseX - mouseXOnMouseDown) * 0.02; - - } - - function onDocumentMouseUp(event) { - - renderer.domElement.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - renderer.domElement.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - renderer.domElement.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - - } - - function onDocumentMouseOut(event) { - - renderer.domElement.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - renderer.domElement.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - renderer.domElement.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - - } - - function onDocumentTouchStart(event) { - - if (event.touches.length == 1) { - - event.preventDefault(); - - mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX; - targetRotationOnMouseDown = targetRotation; - - } - - } - - function onDocumentTouchMove(event) { - - if (event.touches.length == 1) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05; - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - // Try Animate Camera Along Spline - var time = Date.now(); - var looptime = 20 * 1000; - var t = ( time % looptime ) / looptime; - - var pos = tube.path.getPointAt( t ); - pos.multiplyScalar( scale ); - - // interpolation - var segments = tube.tangents.length; - var pickt = t * segments; - var pick = Math.floor( pickt ); - var pickNext = ( pick + 1 ) % segments; - - binormal.subVectors( tube.binormals[ pickNext ], tube.binormals[ pick ] ); - binormal.multiplyScalar( pickt - pick ).add( tube.binormals[ pick ] ); - - - var dir = tube.path.getTangentAt( t ); - - var offset = 15; - - normal.copy( binormal ).cross( dir ); - - // We move on a offset on its binormal - pos.add( normal.clone().multiplyScalar( offset ) ); - - splineCamera.position = pos; - cameraEye.position = pos; - - - // Camera Orientation 1 - default look at - // splineCamera.lookAt( lookAt ); - - // Using arclength for stablization in look ahead. - var lookAt = tube.path.getPointAt( ( t + 30 / tube.path.getLength() ) % 1 ).multiplyScalar( scale ); - - // Camera Orientation 2 - up orientation via normal - if (!lookAhead) - lookAt.copy( pos ).add( dir ); - splineCamera.matrix.lookAt(splineCamera.position, lookAt, normal); - splineCamera.rotation.setEulerFromRotationMatrix( splineCamera.matrix, splineCamera.eulerOrder ); - - cameraHelper.update(); - - parent.rotation.y += ( targetRotation - parent.rotation.y ) * 0.05; - - renderer.render( scene, animation === true ? splineCamera : camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_extrude_uvs2.html - -()=>{ - (function(){ - 'use strict'; - - var tex; - var testShape; - var holeShape; - var testMesh = null; - var WIDTH = 640; - var HEIGHT = 480; - var targetCanvas; - var uvGenerator; - - var scene, renderer, camera; - - var rX = 0; - var rY = 0; - - window["launch"] = function() { - - camera = new THREE.PerspectiveCamera(30, WIDTH / HEIGHT); - camera.position.z = 20; - - scene = new THREE.Scene(); - - /** Custom UV mapper **/ - uvGenerator = new THREE.UVsUtils.CylinderUVGenerator(); - testShape = setupShape(8, 3); - holeShape = setupShape(8, 2); - testShape.holes.push(holeShape); - - tex = setupTexture(TestTextureData); - renewMesh(); - - renderer = new THREE.WebGLRenderer(); - renderer.setSize(WIDTH, HEIGHT); - - // show canvas - targetCanvas = renderer.domElement; - targetCanvas.width = WIDTH; - targetCanvas.height = HEIGHT; - document.getElementById('canvas-container').appendChild(targetCanvas); - - setupAnimation(); - render(); - }; - - function setupAnimation(n?) { - new AnimationController( - document.getElementById('html-el'), - function(x, y) { - rX = x; - rY = y; - render(); - }); - } - - function updateRotation() { - rX = (rX + 3600) % 360; - rY = (rY + 3600) % 360; - testMesh.rotation.set( THREE.Math.degToRad( rY ), 0, THREE.Math.degToRad( rX ) ); - } - - function render() { - if (testMesh) { - var rx = pickRepeatSetting(); - if (uvGenerator.uRepeat != rx) { - uvGenerator.uRepeat = rx; - renewMesh(); - } - - updateRotation(); - renderer.render( scene, camera ); - } - } - - function pickRepeatSetting() { - var radios = (document.getElementById('repeat-setting'))["repeat"]; - for (var i = 0;i < 3;i++) { - if (radios[i].checked) { return radios[i].value - 0; } - } - - return 1; - } - - function setupShape(n, r) { - // Make shape - var sh = new THREE.Shape(); - for (var i = 0; i < n;i++) { - var method = i ? 'lineTo' : 'moveTo'; - var a = (i/n) * Math.PI * 2; - var x = Math.cos(a) * r; - var y = Math.sin(a) * r; - sh[method](x, y); - } - - return sh; - } - - function setupGeometry(shape) { - // Make extruded geometory - var exoption = { - bevelEnabled: true, - bevelSize: 1, - amount: 3, - extrudeMaterial: 0, - material: 1, - uvGenerator: uvGenerator - }; - - var geom = shape.extrude(exoption); - return geom; - } - - function setupTexture(dat) { - var img = new Image(); - var t = new THREE.Texture(img); - t.wrapS = THREE.RepeatWrapping; - - img.onload = function() { - t.needsUpdate = true; - render(); - }; - img.src = dat; - return t; - } - - function setupMesh(geom, side_texture) { - var materials = [ - new THREE.MeshBasicMaterial( { map: side_texture } ), - new THREE.MeshBasicMaterial( { color: 0x447766 } ) - ]; - var mesh = new THREE.Mesh(geom, new THREE.MeshFaceMaterial(materials)); - - scene.add(mesh); - return mesh; - } - - function renewMesh() { - if (testMesh) { - scene.remove(testMesh); - } - - testMesh = setupMesh( setupGeometry(testShape) , tex); - testMesh.position.set(0, 0, -30); - } - - function AnimationController(target, callback) { - var _this = this; - this.callback = callback; - target.addEventListener('mousemove', function(e) { - _this.onMouseMove(e); - }, false); - } - - AnimationController.prototype = { - onMouseMove: function(e) { - this.callback(e.clientX, e.clientY); - } - }; - - var TestTextureData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEABAMAAACuXLVVAAAAAXNSR0IArs4c6QAAADBQTFRFB1B5B1iEA16QAGCPAGaWE2WXJHJMJntSLoJVKopbQX+fMJBgLZlnbZuyZaiGgrCY0v66KwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wEEBE0NIvLSa4AAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAa7ElEQVR42u1cTWwbR5YuUuIlQAA2qb4YEMCm3JcBDEhyeBlgAdsJLwECsJus41xlEiImN0eCCeQmk2AjvlFssDDJZmcvAXS1SbAxvlHd6ELW1iQXAbzOTrDB+OZx4EC936tuyXIws4ct7M4uQEZ/MfsVu169+t73Xr1+jHNuchffnLt22TUlXl4UyEjOpSelz2sN2+U2XcXtht2UQ7wde5EcyHksA6krz0rczjsGzztV2zWNZiGaz6WI8CV8XCMPMQAv4pLSmlPLbZuV4KHsRmEvnHfkJJSDWFeemY5tuBBscLtpb3EzCvwIA0g1Siw9x2zwKjcd+so3axZmIGQsw/SKQOrKM6iuzHnTdHnN5S1egwJjucA7ePWkDBwokPO6w+0WtFjjcoIBIjnFN2bg+7ryrO6U87Q4Dq9atuHkQ188HR4FgyMx9vcjv920HbvSxDRMxzDdgisPw14UBsdyLAc0UV15LIGR54bLi5gG7IjT/QUR7o+0FAUCMtxyCzCihskd08X76WuSzlJXHksAC4WaylzpistfvHi9mQ6NSWCAZuBBMBr6shP2Ynkw15VnroO7y1VMwzEd03LWnspBqh7YcT+c9GBEJrRoWTCz4p2Cc9gLu7PT3hMxiXHFINaVZxbnVjPP+Y4Le951Csp28SOUx54fBUED1ovBoUIXmoYKSbt0hVR/SV15BgWWOCaBgRo2dCTTpUmXES+X0w5KgSSPhcTQAggyhh0DbwZSV57Z7obFC9jMHIZsWHYoBtHhOBZT+UT60wj7eIcGqNhmo2xiu8veKW1zH58TEJLpyjNOpoMb3M3gMr4yH4IJKRpQHRC2CZwhS+KkYZohrBkDTaSuPG6gvoF/51a95tg1bmfSUGE6lFN3ecE1W7SG/K7pRl4Y+EeYZufp4WjeiXXlmXW3lCsWGhsGLzVgyoWo3Q4fjuL2g6AtZscTr2FW3NyddcsxK2bFMCsTcQrVyXmQfZKuPEHx5Uspc3Eoo1R7Us4i6TUIQmmKmMmu2ufKuAjP8SViXXlWNWjx0gHqNrefSDWASJdJ9siK67jEhY2VXBsqPA0m43F7dv9YPBAHY115ZuRauUaOmxVm7hjrTmksx0960wEcdifqHE27MGBsHnu3srHNgSUlbOF4OFNmBI8vpa48U4TimhbVwij7ERHp0cEOJxRtYib2L6CWLtOVT29AbSNaQ8fOdpCcZV7DzQbgtkVo7/oAUAweYJMfjuXRXFeelXbcvJN3GDOMom0U8+N5ZxQcxQeDeBh1QJy2a0WeA4wX1w3ODF4MRAiI7UVyL8ZAB1JXXmkA27SmLKlE+xi7ZJaqCIDec+o7dOdV3DxN1FD2HQJNOsqKI115dQNw06kp1xSpjACUeDOIYEkC+MrT5bvHay2eA9ETk4UcjbsYP05JqY48s5v3gOSOZTqFOyUTWD4ajg59KcawYsBZt4EBNir1HHytW8BOkr1YpB+RvnTlWYrkXJEF+iu6slFB0+gR1SDaTQ6NmKeyMAU00Rz0U+rKwxeQI3fJn7bIisf0dqwYaywG0nOxsLR85FQwQDX2ppP+02AQe+OxP8YNaMqz0vZWubhmWTnD3rbMit2X+yOxF+0fgz12B1Fv2zTcXNE0ts0dByo0Qo+4HqaXgbmuPONKcUBKMhVoMcAigbtfEhapdrhCcks5VQnOfcnqMU5fV54BqM1sAOjIMYPYI8aK9Qtgo7HHifJyxTa4eZeXInEcDMbSB7kOaBq68sywiU06Vp18BQaII29B9tOfdSJvfLrfsPPwI2ZZbSeLIh81O8B4pKiFrjwjwyHOCFXW6AeAJFQzUIsUScW1HZpejf66JBwHMlh4I18MdOVBSkGYTacKI0WE42yIGPjVh+4yZ3KPxIt8AxN0TMzxNBj1xbHcpwhM4YCmPCKjZs3hDu0l011r5CUcNlTY34e5eqEIrHqxiAGwg5hbqzr2acYkKPYOVGSkJ69IqXPJZ8DhJe2TOCZEV/ze4beV6u4S94atUdwPK+4tuos9DzG4rjxDQLle4WyH4ocmjGj2VCzkfeKrwcgbh55BSAbjoTdL4HxhfDD3ZnIYBYuAYj9deYWEFs9h+RDnYxSfNirWx5Od8WQ8kSCbTs0gTmsSt7DDjPVmrEPqymek9JLWkRWnjO4yiM1I/9VLDTCW'+ - 'D+PJWPZjv68rz+wNp3YXN5hvYqO6OR5Q0NqJZTfynmIQAAnWDpzCIXdTctkjsTiY9ONuPPDJkua68swGQhZv5oHTds4xqnwciTDaj+fdcAgjirpuk6Je4hQGqCXFfuF1fyd15QmKyYrJoZl02VBxCZlu05BIJWKqe2/VLCn1FEsfbCNuj6O2rjyza0Qbqw7lkCiJIIgsDOMB9nAo+lIYfN25adwrFaFrG1hCQW03DD6LheJdQleemVWKbGGkjgPQdvmEcOxQDrGW00BEnpVyCV5qFYrV9UY9C/subUzqyjOyXPfKRltcKdC75PZEq2vNd3k/gL5PUX4Ud8bBRFcefKBSA5927DKvNW4a9mAq/RiEMYAxyYfwdkDR1lrD3P7AVpg3EgNiOvuhfKRIp648s0uV2g7RpuaHICxOvR/LR7Ib7g/DXoi19Ix7a266xHDpu00+IgvDHCnXitdQV56puP0amqgEGuBcJTCECr2U6po0ACYxloMYzhRXdOTkqRzoyjOedwCkZiMHzNwBlohTDypckDPFNWREnDwpb1QxwbxTCikB5tMMyOHiAzTlGd8FSpC3dNPQZv8U7oqgNAx8uR/LCs836muOvZNFH1kSShE+isF15VmK07ZzqcIgvQIoJjLCAcF1oGmduzV80TYPYMVHwaHfGY8PdOWZS2/yUsM2mohe7nLs0o58GLUnp14sJpEog2UQxADoHbPaMEfBOPb68aBPWSZsNV15ZgC9cjwHILFhqZX6w1OsUHchQNkAKZEogeryDXfDpk0OPcdyEgeTdI/TdteVZ8QWSsSsFWuscWXAKW0P6RaVZnOcb9VaLqV9Kcsu9gnOOlEXe0lXHjZg8Fw93zCLPG8Yxj1vEfixryJ4bJIw2ALLKGGAKt+hbEvpVE6iwIu8fhrcCF15ZuXp/kvg7q2yDc9GAUss/LAbgrsexLJEdDPNQbZoMmqC4HyU6hTRYKIrfz1Nx6+n2ymZp4CkZatkbwlu9TbczSkgdNAOsdAHsjd+J03335JnlbpTY4ov0KEK42IKpPBArkPMZF8OKL9bLTTsSqnkVDHRqZzHh0JeOTRdecZs8CVuVHGL8NZAsihG6BzNek/Ekzl2kkVHHtDeJeBOs6AzogMBbGpteZU9yMImohbB2xwaBRgSpNetEuXlNQdoaj+S/ZEcxw+PfTHCKnu68ozSZzCjpl0x63SZOA3mcBUzOOwnUS8UhmM2SiVrgw4byJ58yq6ouCYLvzXlmQrryUoQvFIWg/Zx1JUqjKc0V+tvGVk6zVPpTwJdeXVoBRW6tsqkVDj+WZIRXZJXJWXylsHrxfKOZYbzTtRvx96TuBvKIy/WlWc2MwDVdOrEK0VY8eFIHp52wz3xSI6EiGc5a227lrubY27OqBr3eH/qhYEEr6fpkbPRlGeEECY5bEyAMtuwTGwjxG2xxIaKhbFDh478KiWcWZhQSp7Iia48S9+6pDUuD2C7sVCptJBMRaUXCs3LJEzLJ7bvEeEbULJtqCvPLCLVDggFcLpRa/CH9LaHPXosj2HFwQ62D8WVao7A9AGpLqBTJy89MdGUZ+7l/YNZKiOKKZUrswgqBKtNVbfO1ZkT7fOQ+FYPWCcWk4muPJagRGefnKvowuDBQganFLlTggF6NCm5VnYdBOBFx3byg2C4GLbDtoiVHqWuPCsWii55s3yOks6W642ktxCDBZbx0fTh8axQMStb607VbJnKtU8UlbwMLaXUlVeREVeHeumpBu4qXSRiNuk+Thl16x1vB8jvYQbxga48bmCLl51aEf7CpHSWgBWr5MkozWgTpW8R7XLsYtls5P1wGE46YXc02w9xrdSVxy7IAUhgn0WYsrlDWO4vglnoPQWjOww9s2E27q1XKAen8jA+bWHvKvSTuvKXhKR2mei6dvI6J03CsFXQefMalkdpig0R9rSvK8927Y8osrvNyxTlVgnJgvAKRijy4VtuzeXsQ161imsuvFx45IXD4UKM5F4/1pVnRqHi5pzbzAFU5yuFxrAftQ+kfzQAZ4S7irHH8latQkUYCL24AwubZ4cOVI4ideUzQsILrZRR/KIEg86EKL9gXHpTRwiZESrayDOpK09AxNP6Bu5AU67CMVokBHcIr8ZUIXOXAo8iN8BqKmIYt5+KAVjvuJtuMz155rTW3fUdC+FLuQhYL/pU1xDiCoS5UFSfm9sEcq1qiZDcqNIeVicymRnryjMoiCC65qQqKstrZkw6VMUZ2aEc/U75zISSjZgg1lhTninVqS2kynBMVV8SUYYFHiseCleV6OQbtgPWAU1jesO+bMf9Pfkw9DtSV56BVG/Xq0auaOWLJVYunHpTuTce9o/EI39/sT8tlixuIO60CfIBdrITqvxCj4rmyBdoyjOHvBW37S0iDlZaYJC6iTFFkDJNxtdaWb7XlT06EFGHEYSkUl'+ - 'f+emjmwKXYaaFbShmoFIEyzXTmaZucSmG2ZfcUCEM5prBLyQZdeaYSiVaTwpciSMXGaTDATvL3qcbncDRpO3nDrCh31iyQW1PpF5X9SA1ZV55ZTTgxdbYNK23xWpxVFqgkkko0qveyYh2+C70GEwqq8OZTKFNXnrlNeGqjCaeNyNFQBYlyMiMY9dR9ko+nCiVcY9+pmkbYe4LYfhgGhws4vGGkK88chE5lY8egarNC0Sqcimk08GNvgYsOx2JALtYih4vxaQpZGZgyITp+0pVn6qTpbRkOfwsjqS076p8LCmzrnComSQxQ681g55NYV55R9Mq3VPhMHqMuo0MYiS+P04zzkM6DjEbBsfJ3bOaU2LR3JIaL7pPBfijHQghdeUZ1gFYe2jN2c2WEsDMYyL4fBfdlO/RGY7HDc9XiLs+wzq7J1OGHGdRKXXl2edj0yxSL'+ - 'zAIHnp77vfu+GoAOyT2pK8+4Q8kzB0NsUXRnwlFQ8Ij/PFXnsAXNNl1YUm7HLiO2mXoR2KxYyPZ45i0QHWvKM4PdZka+YuagSifn5I8HXuiDTI4ItMeyXUTcTQUgDmDEdGq1OFWhqpmkRJSuPLt26KeOVi9teBZ31dmTqoNUNqbovcJ6ygXCq6sYVFeebqDOFZ2E0+INDDAHn53KfgxF+WGvxXPNtGCyAfrHy6E3o9QCBbmBVKGZnjyzmG1U1orNnGMwnrO4PzoMZ+1ZCqSATQvjFygLs66KAPjboCqmeq25rjydG+b5ZRLNzKxUXKZxpCxBwzbVbRPe3OV2JOaUAzwMRX/WfhT4uvIshSmVaaZaMx4ovor1Cb1wcjCZFRxKqNfKQFy3VNzaONqfhd2ncSeU7ZlIYz8teWbCn7oI7Qzu5Iv8rj2Ieguf4uaFt5gM4wGnqJYqZeyrfUxkwrs6N9SUz+oJd7L0Aedp1C7TraKCSzXBumvuqlRD5sg9ORtIMY7buvIMQZvhbFi8VG0UuJtrerR7+weyfRSMo+HULzXg5SqmUSkZrm055qkQZMOIrQd08CZ05Zlpp1lGk/w2/uey7FpkBWfZmVvdrV+pME7fVnoMdOX/brr+qjrezWrVlI5dE+NO5YiOnidUnzrUlYcRshLVIJUqhumUjOL+6eQwnvRDj7CkM5vligVrhzXXKioZ7hRGAR3OXlXLSV15Zju1qiqCspyagyhOUq7XwxVPwCoRZtG5+BXc2i4CDy9OT1s8KtUa6MqzKyqTZRmUpxbKitUtAscV46ES9bLZMCOElbI97TwCv/ajyUBXntUct9Cwcm6JzjRaeRduYnxMBQ50+ipGAXAcwU8T/nSjYdec2tFVMV4KqLryjO80VSlkTcXxNr86+U9rgyWo9kdpAuZa3fBlzn0GI9OUv7YLSFM3nWHKJuMgO3dS+LLVRNRhursbFVvE4lgeRmBbh0eftQNfV56VqNYRsWU+V+RgJ8XO0aAdtu8fDw6OO4v+wM9vm2S9puHmGzU4lA6VHXTDICN1A115LMFtu2EbO7x+N4XKt08oqBkUHJ7V7HJ1+CSyCpBpyjs8XXnG7awY7W8ASTbAhzSyxW3Lrll1byGOhB8HPYnY8pEQuvKslndLKs9cxq26ue1gDMb0EHxmFPQjuR/R0zm80DB3Ff/f4r1Q0KN06txT7QJNeWiA6iFrdzhiWN5E9HqcZtBgoaoOQCXBMI3qL2cYCSpVkLryLFPgHXpWTW2jcfqISJpOwwBU+YFp5NybMOTKRzChvjyMhwOq3B3EA115littE2PcJqCCpTrykdwbi2Ho9UfdhXd8RDBCBcFm01Ql+nC3AxXgxz2FJbryTOW3XLMIVdYJrKWqyw2yMD+MeYmvKQN2a6pSQ0X2ILwy9OJxN/R15dUugJpqnLI8agD1KFz2KFZfUokMB6kzG3mLCmG6oTiIuiMxWYhTEUQTXXnWLDQMKr12mbGVr+Qqnf5M+H6bDp3apxNP7tLBMJUhudmxmwoq5FVVnq68MsL6WyNtpo5aXFpxVKcTCZNnD/NxOhmdU65TlaSB+OrKs7eOIgX0q5PdCV0jQtBdqpim0wirWd5pDo/lAT2a4IXBlFBVV54ZIJTlHW7QM2vFml2kBxEj4R+Lw7AznndDrGGJMISy0U3bdUUGpIE6HQ6lrjxrphUWW2ShZewTUo9K6WdwQSZEGE7pSDoWUo/0Dg4Ad5LOx/q68syBYEHlOGknmU3ZlkBT3GSkyKvvrLn5O2aF0uHMqua2geRDOpgEjvmEprryzOEVdeBHlae7O4BSjx4C6sTyCFqKJ8Ix3fRxRjoYwDzk27BPpEkoPXmWPSWmftWvsDq4uuz6g2yX'+ - '6fY4fWhTIBL3deWZRZXx2EZNYCaIsyWHkQc+EwWA82jela0CPR5QrdpuHdy74GJmiDvlFDAyj7HeuvKsxIsmjDNnwanmHLs687A5ov0wGC68Iy+IgOPYQdv0RCnV49GZj0dPTMtQVYbOdeVZSlTqGW0nFcaBevhBYYmUiOsBpPTcMj0qYTv+MOo9nXViSjMhupzpyqtitpTQbvFqnW9R+YEawIvVqYoagFgVPS0Fjq9Ou6R6jGEo1amZnjxb9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R9Y9R/4P99/oLj7v9J/oIpXaqZgEe/0D6jks/4BLdPaNf+L/gPVX/QfIHc/kTGIImJWGGq1hK8r+eH0nf4DLsPLVv0Djh+82z/g1lnWP8DK4Rrr7/cfyOSv+g882Q/jvdkePQmaKznqE67Jf3b4Tv8Bd4mXslX+6at3+wdsnqX9A7Yr7y2X35T+bv8BN5O/6j/w7I0fJfNkm+cbyzWnulymn5HJP3v9Tv8BdQOtrVaryR//NBdzGc/nEX7h9+aZebe5VufF9+iaFx+E84EM+rF3FByO2/3+we0STP/2huMuq1Vsw11ICeVpnr2RcRK8/Lq+8evzdc7TG7hbngEmJgfy81d+51r/AXdZgSEzVmKlT1/t3X/QfnB/7+nwgfCP9t4/W6sg8jSLJ+d3Nz5+Xnqwtzf3jvBTTj5r7w3GbI3fg263i0vGKrkiG7fl/fZ+1J48exNPktnj5+7aP31H/Qdat56bO0W25x0f7e35+Jj9a/0H3KVVteyTr6yTr5MkeZ38NvkpeTJMggcvk5OzfPFk+ZX5q2Ud9tS0HicXh/PfJsmfgxiX/fsXy3++Y723PM/dwvxuPT9ZfvpKjBPqP/DsTRgns9+d2/mTf1X9B26dtaxvlhcPj18myQAf8+Za/wF3SUb4yXc3l3V6R33PoMDPk2R5Zp1g7A9unLfcXevmDbz3aowfidemn8ny3LqB9//4G7oBfH9xEfzuIlA2gBuYf3tuV5cfqf4Dt17UcWXy+ovsI3661n/gnjKQ9eV7f7z3+FXQTy4GkbqBT18Hn7y4sfwwd/L15nc7DcbyJ3+dP774IvnzF8mPk+THb5MfP16yk/Pb753nl3Z+c/kv94aJ9/kb6j/w7M3TOJkGy93yMu0/sPm8evKd8ezi8V+HX/z58at3+g+kRlg+Ofk9f/xahonnh8l0AhuO5ftnm88Zw88z3oQRLvf29pIvL2L5+M0s8cJkaC0NUt+yurxZ3vyOc/Fy+PgH6j/w7M0xNCBPvr5xnvYfuHXWPIENQPqzfoxdcL3/gLukp/Favzq/yb9UxovvOb7wx62zTbq7s80/mg7dAKn901ehePzms6Q7SuawfmXf1SWtMoDo3354qThXugvkJy82v6ur/gObL3ZwXZJgCf40xjyv9x/AKNQ/4MaS1aGbftKDFsZYhWQyeP/F+zT+9zfO887uZnYD2MSPf54ksMOgsrTUDQAH7FtnjItnf01U/4Fnr2dhEgw2X7z/PO0/8P6LqrqB2bcvk/949tM7/QfcpYF1Mk5OvuKPsUGTXjRNHnyW+EmfbuB5qbpjfrw0dqubZ8u9yezoy9eT2eOfJrQEA7bEBqwytrUsGbfOgITfXlyo/gNfvj56lMTiV+cnX6f9B6CfpVEd9afjycs3z15NvWv9B9JdUD7/5Hnty4u9wwQ3l/zpt4CRv94/gRF+xW6cGcvzInv/xcmrB3uf/yF5sJf8gBsYJT13uXVyztg3Nq66dWZxaOVnNbVvkwefX0gJw7mX9h/YfG6dvGB7Lz9/sPfpT4QD1/oPKCM0N7/7YFn7gnDAC2fYrMmMtuGLDdqGZ8YnCgl/TUsg8eYFrTC+oLyP1R7CVUoDi+SHtP8ALvw5FMZymfUf2Hzh/pqW4Eu88R/4mJ+v9x9Qu+Dkq42T33svkx+TrpR/wC8pXl588j3/6GR5/hFvfQNfUG/9Jbn4i/zDy4sfoSTpJwFfOi3cwe9hQMvffO9yb/Hyx7T/wLfJBfUfODnPCnp/8z3HlRd/gQlAM/iY/6H+A4uXwT+2/8DRxT+4/8CXP/+D+w+8/HHVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf2DVf+D/V/+B/wT15JbOMyhx1QAAAABJRU5ErkJggg=='; - - })(); -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_hierarchy.html - -()=>{ - var container, stats; - - var camera, scene, renderer; - - var geometry, group; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.z = 500; - - scene = new THREE.Scene(); - scene.fog = new THREE.Fog( 0xffffff, 1, 10000 ); - - var geometry = new THREE.CubeGeometry( 100, 100, 100 ); - var material = new THREE.MeshNormalMaterial(); - - group = new THREE.Object3D(); - - for ( var i = 0; i < 1000; i ++ ) { - - var mesh = new THREE.Mesh( geometry, material ); - mesh.position.x = Math.random() * 2000 - 1000; - mesh.position.y = Math.random() * 2000 - 1000; - mesh.position.z = Math.random() * 2000 - 1000; - - mesh.rotation.x = Math.random() * 2 * Math.PI; - mesh.rotation.y = Math.random() * 2 * Math.PI; - - mesh.matrixAutoUpdate = false; - mesh.updateMatrix(); - - group.add( mesh ); - - } - - scene.add( group ); - - renderer = new THREE.WebGLRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.sortObjects = false; - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onDocumentMouseMove(event) { - - mouseX = ( event.clientX - windowHalfX ) * 10; - mouseY = ( event.clientY - windowHalfY ) * 10; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = Date.now() * 0.001; - - var rx = Math.sin( time * 0.7 ) * 0.5, - ry = Math.sin( time * 0.3 ) * 0.5, - rz = Math.sin( time * 0.2 ) * 0.5; - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y += ( - mouseY - camera.position.y ) * .05; - - camera.lookAt( scene.position ); - - group.rotation.x = rx; - group.rotation.y = ry; - group.rotation.z = rz; - - renderer.render( scene, camera ); - - } - -}; - - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_hierarchy2.html - -()=>{ - var container, stats; - - var camera, scene, renderer; - - var geometry, root; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 15000 ); - camera.position.z = 500; - - scene = new THREE.Scene(); - - var geometry = new THREE.CubeGeometry( 100, 100, 100 ); - var material = new THREE.MeshNormalMaterial(); - - root = new THREE.Mesh( geometry, material ); - root.position.x = 1000; - scene.add( root ); - - var amount = 200, object, parent = root; - - for ( var i = 0; i < amount; i ++ ) { - - object = new THREE.Mesh( geometry, material ); - object.position.x = 100; - - parent.add( object ); - parent = object; - - } - - parent = root; - - for ( var i = 0; i < amount; i ++ ) { - - object = new THREE.Mesh( geometry, material ); - object.position.x = - 100; - - parent.add( object ); - parent = object; - - } - - parent = root; - - for ( var i = 0; i < amount; i ++ ) { - - object = new THREE.Mesh( geometry, material ); - object.position.y = - 100; - - parent.add( object ); - parent = object; - - } - - parent = root; - - for ( var i = 0; i < amount; i ++ ) { - - object = new THREE.Mesh( geometry, material ); - object.position.y = 100; - - parent.add( object ); - parent = object; - - } - - parent = root; - - for ( var i = 0; i < amount; i ++ ) { - - object = new THREE.Mesh( geometry, material ); - object.position.z = - 100; - - parent.add( object ); - parent = object; - - } - - parent = root; - - for ( var i = 0; i < amount; i ++ ) { - - object = new THREE.Mesh( geometry, material ); - object.position.z = 100; - - parent.add( object ); - parent = object; - - } - - renderer = new THREE.WebGLRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.sortObjects = false; - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onDocumentMouseMove(event) { - - mouseX = ( event.clientX - windowHalfX ) * 10; - mouseY = ( event.clientY - windowHalfY ) * 10; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = Date.now() * 0.001; - - var rx = Math.sin( time * 0.7 ) * 0.2; - var ry = Math.sin( time * 0.3 ) * 0.1; - var rz = Math.sin( time * 0.2 ) * 0.1; - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y += ( - mouseY - camera.position.y ) * .05; - - camera.lookAt( scene.position ); - - root.traverse( function ( object ) { - - object.rotation.x = rx; - object.rotation.y = ry; - object.rotation.z = rz; - - } ); - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_large_mesh.html - -()=>{ - var SCREEN_WIDTH = window.innerWidth; - var SCREEN_HEIGHT = window.innerHeight; - var FLOOR = -250; - - var container, stats; - - var camera, scene, canvasRenderer, webglRenderer; - - var loader; - - var mesh, zmesh, lightMesh; - - var directionalLight, pointLight; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var render_canvas = true, render_gl = true; - var has_gl = false; - - var bcanvas = document.getElementById( "rcanvas" ); - var bwebgl = document.getElementById( "rwebgl" ); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - init(); - animate(); - - render_canvas = !has_gl; - bwebgl.style.display = has_gl ? "inline" : "none"; - bcanvas.className = render_canvas ? "button" : "button inactive"; - - function addMesh( geometry, scale, x, y, z, rx, ry, rz, material ) { - - mesh = new THREE.Mesh( geometry, material ); - - mesh.scale.set( scale, scale, scale ); - mesh.position.set( x, y, z ); - mesh.rotation.set( rx, ry, rz ); - - scene.add( mesh ); - - } - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 50, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 100000 ); - camera.position.z = 1500; - - scene = new THREE.Scene(); - - // LIGHTS - - var ambient = new THREE.AmbientLight( 0x101010 ); - scene.add( ambient ); - - directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 ); - directionalLight.position.set( 1, 1, 2 ).normalize(); - scene.add( directionalLight ); - - pointLight = new THREE.PointLight( 0xffaa00 ); - pointLight.position.set( 0, 0, 0 ); - scene.add( pointLight ); - - // light representation - - var sphere = new THREE.SphereGeometry( 100, 16, 8, 1 ); - lightMesh = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0xffaa00 } ) ); - lightMesh.scale.set( 0.05, 0.05, 0.05 ); - lightMesh.position = pointLight.position; - scene.add( lightMesh ); - - - if ( render_gl ) { - try { - - webglRenderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } ); - webglRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - webglRenderer.domElement.style.position = "relative"; - container.appendChild( webglRenderer.domElement ); - has_gl = true; - - } - catch (e) { - } - } - - if( render_canvas ) { - - canvasRenderer = new THREE.CanvasRenderer(); - canvasRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - container.appendChild( canvasRenderer.domElement ); - - } - - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - bcanvas.addEventListener( "click", toggleCanvas, false ); - bwebgl.addEventListener( "click", toggleWebGL, false ); - - var loader = new THREE.BinaryLoader( true ); - //loader = new THREE.JSONLoader( true ); - document.body.appendChild( loader.statusDomElement ); - - var start = Date.now(); - - //loader.load( 'obj/lucy/Lucy100k_slim.js', callback ); - loader.load( 'obj/lucy/Lucy100k_bin.js', function ( geometry, materials ) { - - addMesh( geometry, 0.75, 900, 0, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x030303, specular: 0x990000, shininess: 30 } ) ); - addMesh( geometry, 0.75, 300, 0, 0, 0,0,0, new THREE.MeshFaceMaterial( materials ) ); - addMesh( geometry, 0.75, -300, 0, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x111111, specular: 0xffaa00, shininess: 10 } ) ); - addMesh( geometry, 0.75, -900, 0, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x555555, specular: 0x666666, shininess: 10 } ) ); - - loader.statusDomElement.style.display = "none"; - - _log( "geometry.vertices: " + geometry.vertices.length ); - _log( "geometry.faces: " + geometry.faces.length ); - - _log( "model loaded and created in " + ( Date.now() - start ) + " ms" ); - - } ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - if ( render_canvas ) canvasRenderer.setSize( window.innerWidth, window.innerHeight ); - if ( render_gl && has_gl ) webglRenderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onDocumentMouseMove( event ) { - - mouseX = ( event.clientX - windowHalfX ); - mouseY = ( event.clientY - windowHalfY ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - var r = 0; - - function render() { - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y += ( - mouseY - camera.position.y ) * .05; - - camera.lookAt( scene.position ); - - lightMesh.position.x = 700 * Math.cos( r ); - lightMesh.position.z = 700 * Math.sin( r ); - - r += 0.01; - - if ( render_canvas ) canvasRenderer.render( scene, camera ); - if ( render_gl && has_gl ) webglRenderer.render( scene, camera ); - - } - - function _log( text ) { - - var e = document.getElementById( "log" ); - e.innerHTML = text + "
    " + e.innerHTML; - - } - - function toggleCanvas() { - - render_canvas = !render_canvas; - bcanvas.className = render_canvas ? "button" : "button inactive"; - - render_gl = !render_canvas; - bwebgl.className = render_gl ? "button" : "button inactive"; - - if( has_gl ) - webglRenderer.domElement.style.display = render_gl ? "block" : "none"; - - canvasRenderer.domElement.style.display = render_canvas ? "block" : "none"; - - } - - function toggleWebGL() { - - render_gl = !render_gl; - bwebgl.className = render_gl ? "button" : "button inactive"; - - render_canvas = !render_gl; - bcanvas.className = render_canvas ? "button" : "button inactive"; - - if( has_gl ) - webglRenderer.domElement.style.display = render_gl ? "block" : "none"; - - canvasRenderer.domElement.style.display = render_canvas ? "block" : "none"; - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_minecraft.html - -()=>{ - - if ( ! Detector.webgl ) { - - Detector.addGetWebGLMessage(); - document.getElementById( 'container' ).innerHTML = ""; - - } - - var container, stats; - - var camera, controls, scene, renderer; - - var mesh; - - var worldWidth = 128, worldDepth = 128, - worldHalfWidth = worldWidth / 2, worldHalfDepth = worldDepth / 2, - data = generateHeight( worldWidth, worldDepth ); - - var clock = new THREE.Clock(); - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 20000 ); - camera.position.y = getY( worldHalfWidth, worldHalfDepth ) * 100 + 100; - - controls = new THREE.FirstPersonControls( camera ); - - controls.movementSpeed = 1000; - controls.lookSpeed = 0.125; - controls.lookVertical = true; - - scene = new THREE.Scene(); - - // sides - - var matrix = new THREE.Matrix4(); - - var pxGeometry = new THREE.PlaneGeometry( 100, 100 ); - pxGeometry.faces[ 0 ].materialIndex = 1; - pxGeometry.applyMatrix( matrix.makeRotationY( Math.PI / 2 ) ); - pxGeometry.applyMatrix( matrix.makeTranslation( 50, 0, 0 ) ); - - var nxGeometry = new THREE.PlaneGeometry( 100, 100 ); - nxGeometry.faces[ 0 ].materialIndex = 1; - nxGeometry.applyMatrix( matrix.makeRotationY( - Math.PI / 2 ) ); - nxGeometry.applyMatrix( matrix.makeTranslation( - 50, 0, 0 ) ); - - var pyGeometry = new THREE.PlaneGeometry( 100, 100 ); - pyGeometry.faces[ 0 ].materialIndex = 0; - pyGeometry.applyMatrix( matrix.makeRotationX( - Math.PI / 2 ) ); - pyGeometry.applyMatrix( matrix.makeTranslation( 0, 50, 0 ) ); - - var pzGeometry = new THREE.PlaneGeometry( 100, 100 ); - pzGeometry.faces[ 0 ].materialIndex = 1; - pzGeometry.applyMatrix( matrix.makeTranslation( 0, 0, 50 ) ); - - var nzGeometry = new THREE.PlaneGeometry( 100, 100 ); - nzGeometry.faces[ 0 ].materialIndex = 1; - nzGeometry.applyMatrix( matrix.makeRotationY( Math.PI ) ); - nzGeometry.applyMatrix( matrix.makeTranslation( 0, 0, -50 ) ); - // - - var geometry = new THREE.Geometry(); - var dummy = new THREE.Mesh(); - - for ( var z = 0; z < worldDepth; z ++ ) { - - for ( var x = 0; x < worldWidth; x ++ ) { - - var h = getY( x, z ); - - dummy.position.x = x * 100 - worldHalfWidth * 100; - dummy.position.y = h * 100; - dummy.position.z = z * 100 - worldHalfDepth * 100; - - var px = getY( x + 1, z ); - var nx = getY( x - 1, z ); - var pz = getY( x, z + 1 ); - var nz = getY( x, z - 1 ); - - dummy.geometry = pyGeometry; - THREE.GeometryUtils.merge( geometry, dummy ); - - if ( ( px != h && px != h + 1 ) || x == 0 ) { - - dummy.geometry = pxGeometry; - THREE.GeometryUtils.merge( geometry, dummy ); - - } - - if ( ( nx != h && nx != h + 1 ) || x == worldWidth - 1 ) { - - dummy.geometry = nxGeometry; - THREE.GeometryUtils.merge( geometry, dummy ); - - } - - if ( ( pz != h && pz != h + 1 ) || z == worldDepth - 1 ) { - - dummy.geometry = pzGeometry; - THREE.GeometryUtils.merge( geometry, dummy ); - - } - - if ( ( nz != h && nz != h + 1 ) || z == 0 ) { - - dummy.geometry = nzGeometry; - THREE.GeometryUtils.merge( geometry, dummy ); - - } - - } - - } - - var textureGrass = THREE.ImageUtils.loadTexture( 'textures/minecraft/grass.png' ); - textureGrass.magFilter = THREE.NearestFilter; - textureGrass.minFilter = THREE.LinearMipMapLinearFilter; - - var textureGrassDirt = THREE.ImageUtils.loadTexture( 'textures/minecraft/grass_dirt.png' ); - textureGrassDirt.magFilter = THREE.NearestFilter; - textureGrassDirt.minFilter = THREE.LinearMipMapLinearFilter; - - var material1 = new THREE.MeshLambertMaterial( { map: textureGrass, ambient: 0xbbbbbb } ); - var material2 = new THREE.MeshLambertMaterial( { map: textureGrassDirt, ambient: 0xbbbbbb } ); - - var mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( [ material1, material2 ] ) ); - scene.add( mesh ); - - var ambientLight = new THREE.AmbientLight( 0xcccccc ); - scene.add( ambientLight ); - - var directionalLight = new THREE.DirectionalLight( 0xffffff, 2 ); - directionalLight.position.set( 1, 1, 0.5 ).normalize(); - scene.add( directionalLight ); - - renderer = new THREE.WebGLRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.innerHTML = ""; - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - controls.handleResize(); - - } - - function generateHeight( width, height ) { - - var data = [], perlin = new ImprovedNoise(), - size = width * height, quality = 2, z = Math.random() * 100; - - for ( var j = 0; j < 4; j ++ ) { - - if ( j == 0 ) for ( var i = 0; i < size; i ++ ) data[ i ] = 0; - - for ( var i = 0; i < size; i ++ ) { - - var x = i % width, y = ( i / width ) | 0; - data[ i ] += perlin.noise( x / quality, y / quality, z ) * quality; - - - } - - quality *= 4 - - } - - return data; - - } - - function getY( x, z ) { - - return ( data[ x + z * worldWidth ] * 0.2 ) | 0; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - controls.update( clock.getDelta() ); - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_minecraft_ao.html - -()=>{ - - if ( ! Detector.webgl ) { - - Detector.addGetWebGLMessage(); - document.getElementById( 'container' ).innerHTML = ""; - - } - - var fogExp2 = true; - - var container, stats; - - var camera, controls, scene, renderer; - - var mesh, mat; - - var worldWidth = 200, worldDepth = 200, - worldHalfWidth = worldWidth / 2, worldHalfDepth = worldDepth / 2, - data = generateHeight( worldWidth, worldDepth ); - - var clock = new THREE.Clock(); - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 20000 ); - camera.position.y = getY( worldHalfWidth, worldHalfDepth ) * 100 + 100; - - controls = new THREE.FirstPersonControls( camera ); - - controls.movementSpeed = 1000; - controls.lookSpeed = 0.125; - controls.lookVertical = true; - controls.constrainVertical = true; - controls.verticalMin = 1.1; - controls.verticalMax = 2.2; - - scene = new THREE.Scene(); - scene.fog = new THREE.FogExp2( 0xffffff, 0.00015 ); - - // sides - - var light = new THREE.Color( 0xffffff ); - var shadow = new THREE.Color( 0x505050 ); - - var matrix = new THREE.Matrix4(); - - var pxGeometry = new THREE.PlaneGeometry( 100, 100 ); - pxGeometry.faces[ 0 ].materialIndex = 1; - pxGeometry.faces[ 0 ].vertexColors = [ light, shadow, shadow, light ]; - pxGeometry.applyMatrix( matrix.makeRotationY( Math.PI / 2 ) ); - pxGeometry.applyMatrix( matrix.makeTranslation( 50, 0, 0 ) ); - - var nxGeometry = new THREE.PlaneGeometry( 100, 100 ); - nxGeometry.faces[ 0 ].materialIndex = 1; - nxGeometry.faces[ 0 ].vertexColors = [ light, shadow, shadow, light ]; - nxGeometry.applyMatrix( matrix.makeRotationY( - Math.PI / 2 ) ); - nxGeometry.applyMatrix( matrix.makeTranslation( - 50, 0, 0 ) ); - - var pyGeometry = new THREE.PlaneGeometry( 100, 100 ); - pyGeometry.faces[ 0 ].materialIndex = 0; - pyGeometry.faces[ 0 ].vertexColors = [ light, light, light, light ]; - pyGeometry.applyMatrix( matrix.makeRotationX( - Math.PI / 2 ) ); - pyGeometry.applyMatrix( matrix.makeTranslation( 0, 50, 0 ) ); - - var pzGeometry = new THREE.PlaneGeometry( 100, 100 ); - pzGeometry.faces[ 0 ].materialIndex = 1; - pzGeometry.faces[ 0 ].vertexColors = [ light, shadow, shadow, light ]; - pzGeometry.applyMatrix( matrix.makeTranslation( 0, 0, 50 ) ); - - var nzGeometry = new THREE.PlaneGeometry( 100, 100 ); - nzGeometry.faces[ 0 ].materialIndex = 1; - nzGeometry.faces[ 0 ].vertexColors = [ light, shadow, shadow, light ]; - nzGeometry.applyMatrix( matrix.makeRotationY( Math.PI ) ); - nzGeometry.applyMatrix( matrix.makeTranslation( 0, 0, -50 ) ); - - // - - var geometry = new THREE.Geometry(); - var dummy = new THREE.Mesh(); - - for ( var z = 0; z < worldDepth; z ++ ) { - - for ( var x = 0; x < worldWidth; x ++ ) { - - var h = getY( x, z ); - - dummy.position.x = x * 100 - worldHalfWidth * 100; - dummy.position.y = h * 100; - dummy.position.z = z * 100 - worldHalfDepth * 100; - - var px = getY( x + 1, z ); - var nx = getY( x - 1, z ); - var pz = getY( x, z + 1 ); - var nz = getY( x, z - 1 ); - - var pxpz = getY( x + 1, z + 1 ); - var nxpz = getY( x - 1, z + 1 ); - var pxnz = getY( x + 1, z - 1 ); - var nxnz = getY( x - 1, z - 1 ); - - dummy.geometry = pyGeometry; - - var colors = dummy.geometry.faces[ 0 ].vertexColors; - colors[ 0 ] = nx > h || nz > h || nxnz > h ? shadow : light; - colors[ 1 ] = nx > h || pz > h || nxpz > h ? shadow : light; - colors[ 2 ] = px > h || pz > h || pxpz > h ? shadow : light; - colors[ 3 ] = px > h || nz > h || pxnz > h ? shadow : light; - - THREE.GeometryUtils.merge( geometry, dummy ); - - if ( ( px != h && px != h + 1 ) || x == 0 ) { - - dummy.geometry = pxGeometry; - - var colors = dummy.geometry.faces[ 0 ].vertexColors; - colors[ 0 ] = pxpz > px && x > 0 ? shadow : light; - colors[ 3 ] = pxnz > px && x > 0 ? shadow : light; - - THREE.GeometryUtils.merge( geometry, dummy ); - - } - - if ( ( nx != h && nx != h + 1 ) || x == worldWidth - 1 ) { - - dummy.geometry = nxGeometry; - - var colors = dummy.geometry.faces[ 0 ].vertexColors; - colors[ 0 ] = nxnz > nx && x < worldWidth - 1 ? shadow : light; - colors[ 3 ] = nxpz > nx && x < worldWidth - 1 ? shadow : light; - - THREE.GeometryUtils.merge( geometry, dummy ); - - } - - if ( ( pz != h && pz != h + 1 ) || z == worldDepth - 1 ) { - - dummy.geometry = pzGeometry; - - var colors = dummy.geometry.faces[ 0 ].vertexColors; - colors[ 0 ] = nxpz > pz && z < worldDepth - 1 ? shadow : light; - colors[ 3 ] = pxpz > pz && z < worldDepth - 1 ? shadow : light; - - THREE.GeometryUtils.merge( geometry, dummy ); - - } - - if ( ( nz != h && nz != h + 1 ) || z == 0 ) { - - dummy.geometry = nzGeometry; - - var colors = dummy.geometry.faces[ 0 ].vertexColors; - colors[ 0 ] = pxnz > nz && z > 0 ? shadow : light; - colors[ 3 ] = nxnz > nz && z > 0 ? shadow : light; - - THREE.GeometryUtils.merge( geometry, dummy ); - - } - - } - - } - - var textureGrass = THREE.ImageUtils.loadTexture( 'textures/minecraft/grass.png' ); - textureGrass.magFilter = THREE.NearestFilter; - textureGrass.minFilter = THREE.LinearMipMapLinearFilter; - - var textureGrassDirt = THREE.ImageUtils.loadTexture( 'textures/minecraft/grass_dirt.png' ); - textureGrassDirt.magFilter = THREE.NearestFilter; - textureGrassDirt.minFilter = THREE.LinearMipMapLinearFilter; - - var material1 = new THREE.MeshLambertMaterial( { map: textureGrass, ambient: 0xbbbbbb, vertexColors: THREE.VertexColors } ); - var material2 = new THREE.MeshLambertMaterial( { map: textureGrassDirt, ambient: 0xbbbbbb, vertexColors: THREE.VertexColors } ); - - var mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( [ material1, material2 ] ) ); - scene.add( mesh ); - - var ambientLight = new THREE.AmbientLight( 0xcccccc ); - scene.add( ambientLight ); - - var directionalLight = new THREE.DirectionalLight( 0xffffff, 2 ); - directionalLight.position.set( 1, 1, 0.5 ).normalize(); - scene.add( directionalLight ); - - renderer = new THREE.WebGLRenderer( { clearColor: 0xffffff } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.innerHTML = ""; - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - controls.handleResize(); - - } - - function loadTexture( path, callback ) { - - var image = new Image(); - - image.onload = function () { callback(); }; - image.src = path; - - return image; - - } - - function generateHeight( width, height ) { - - var data = [], perlin = new ImprovedNoise(), - size = width * height, quality = 2, z = Math.random() * 100; - - for ( var j = 0; j < 4; j ++ ) { - - if ( j == 0 ) for ( var i = 0; i < size; i ++ ) data[ i ] = 0; - - for ( var i = 0; i < size; i ++ ) { - - var x = i % width, y = ( i / width ) | 0; - data[ i ] += perlin.noise( x / quality, y / quality, z ) * quality; - - } - - quality *= 4 - - } - - return data; - - } - - function getY( x, z ) { - - return ( data[ x + z * worldWidth ] * 0.2 ) | 0; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - controls.update( clock.getDelta() ); - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_minecraft_oculusrift.html - -()=>{ - - if ( ! Detector.webgl ) { - - Detector.addGetWebGLMessage(); - document.getElementById( 'container' ).innerHTML = ""; - - } - - var container, stats; - - var camera, controls, scene, renderer; - - var mesh; - - var effect; - - var worldWidth = 128, worldDepth = 128, - worldHalfWidth = worldWidth / 2, worldHalfDepth = worldDepth / 2, - data = generateHeight( worldWidth, worldDepth ); - - var clock = new THREE.Clock(); - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 20000 ); - camera.position.y = getY( worldHalfWidth, worldHalfDepth ) * 100 + 100; - - controls = new THREE.FirstPersonControls( camera ); - - controls.movementSpeed = 1000; - controls.lookSpeed = 0.125; - controls.lookVertical = true; - - scene = new THREE.Scene(); - - // sides - - var matrix = new THREE.Matrix4(); - - var pxGeometry = new THREE.PlaneGeometry( 100, 100 ); - pxGeometry.faces[ 0 ].materialIndex = 1; - pxGeometry.applyMatrix( matrix.makeRotationY( Math.PI / 2 ) ); - pxGeometry.applyMatrix( matrix.makeTranslation( 50, 0, 0 ) ); - - var nxGeometry = new THREE.PlaneGeometry( 100, 100 ); - nxGeometry.faces[ 0 ].materialIndex = 1; - nxGeometry.applyMatrix( matrix.makeRotationY( - Math.PI / 2 ) ); - nxGeometry.applyMatrix( matrix.makeTranslation( - 50, 0, 0 ) ); - - var pyGeometry = new THREE.PlaneGeometry( 100, 100 ); - pyGeometry.faces[ 0 ].materialIndex = 0; - pyGeometry.applyMatrix( matrix.makeRotationX( - Math.PI / 2 ) ); - pyGeometry.applyMatrix( matrix.makeTranslation( 0, 50, 0 ) ); - - var pzGeometry = new THREE.PlaneGeometry( 100, 100 ); - pzGeometry.faces[ 0 ].materialIndex = 1; - pzGeometry.applyMatrix( matrix.makeTranslation( 0, 0, 50 ) ); - - var nzGeometry = new THREE.PlaneGeometry( 100, 100 ); - nzGeometry.faces[ 0 ].materialIndex = 1; - nzGeometry.applyMatrix( matrix.makeRotationY( Math.PI ) ); - nzGeometry.applyMatrix( matrix.makeTranslation( 0, 0, -50 ) ); - // - - var geometry = new THREE.Geometry(); - var dummy = new THREE.Mesh(); - - for ( var z = 0; z < worldDepth; z ++ ) { - - for ( var x = 0; x < worldWidth; x ++ ) { - - var h = getY( x, z ); - - dummy.position.x = x * 100 - worldHalfWidth * 100; - dummy.position.y = h * 100; - dummy.position.z = z * 100 - worldHalfDepth * 100; - - var px = getY( x + 1, z ); - var nx = getY( x - 1, z ); - var pz = getY( x, z + 1 ); - var nz = getY( x, z - 1 ); - - dummy.geometry = pyGeometry; - THREE.GeometryUtils.merge( geometry, dummy ); - - if ( ( px != h && px != h + 1 ) || x == 0 ) { - - dummy.geometry = pxGeometry; - THREE.GeometryUtils.merge( geometry, dummy ); - - } - - if ( ( nx != h && nx != h + 1 ) || x == worldWidth - 1 ) { - - dummy.geometry = nxGeometry; - THREE.GeometryUtils.merge( geometry, dummy ); - - } - - if ( ( pz != h && pz != h + 1 ) || z == worldDepth - 1 ) { - - dummy.geometry = pzGeometry; - THREE.GeometryUtils.merge( geometry, dummy ); - - } - - if ( ( nz != h && nz != h + 1 ) || z == 0 ) { - - dummy.geometry = nzGeometry; - THREE.GeometryUtils.merge( geometry, dummy ); - - } - - } - - } - - var textureGrass = THREE.ImageUtils.loadTexture( 'textures/minecraft/grass.png' ); - textureGrass.magFilter = THREE.NearestFilter; - textureGrass.minFilter = THREE.LinearMipMapLinearFilter; - - var textureGrassDirt = THREE.ImageUtils.loadTexture( 'textures/minecraft/grass_dirt.png' ); - textureGrassDirt.magFilter = THREE.NearestFilter; - textureGrassDirt.minFilter = THREE.LinearMipMapLinearFilter; - - var material1 = new THREE.MeshLambertMaterial( { map: textureGrass, ambient: 0xbbbbbb } ); - var material2 = new THREE.MeshLambertMaterial( { map: textureGrassDirt, ambient: 0xbbbbbb } ); - - var mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( [ material1, material2 ] ) ); - scene.add( mesh ); - - var ambientLight = new THREE.AmbientLight( 0xcccccc ); - scene.add( ambientLight ); - - var directionalLight = new THREE.DirectionalLight( 0xffffff, 2 ); - directionalLight.position.set( 1, 1, 0.5 ).normalize(); - scene.add( directionalLight ); - - renderer = new THREE.WebGLRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - effect = new THREE.OculusRiftEffect( renderer ); - effect.setSize( window.innerWidth, window.innerHeight ); - - // Right Oculus Parameters are yet to be determined - effect.separation = 20; - effect.distortion = 0.1; - effect.fov = 110; - - - document.getElementById( 'distVal' ).innerHTML = effect.distortion.toFixed(2); - document.getElementById( 'sepVal' ).innerHTML = effect.separation; - document.getElementById( 'fovVal' ).innerHTML = effect.fov; - - - container.innerHTML = ""; - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // GUI - window.addEventListener( 'resize', onWindowResize, false ); - document.addEventListener( 'keydown', keyPressed, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - effect.setSize( window.innerWidth, window.innerHeight ); - - controls.handleResize(); - - } - - function keyPressed (event) { - switch ( event.keyCode ) { - case 79: /*O*/ effect.distortion -= 0.01; document.getElementById( 'distVal' ).innerHTML = effect.distortion.toFixed(2); break; - case 80: /*P*/ effect.distortion += 0.01; document.getElementById( 'distVal' ).innerHTML = effect.distortion.toFixed(2); break; - case 75: /*K*/ effect.separation -= 1; document.getElementById( 'sepVal' ).innerHTML = effect.separation; break; - case 76: /*L*/ effect.separation += 1; document.getElementById( 'sepVal' ).innerHTML = effect.separation; break; - case 78: /*N*/ effect.fov -= 1; document.getElementById( 'fovVal' ).innerHTML = effect.fov; break; - case 77: /*M*/ effect.fov += 1; document.getElementById( 'fovVal' ).innerHTML = effect.fov; break; - - } - } - - function generateHeight( width, height ) { - - var data = [], perlin = new ImprovedNoise(), - size = width * height, quality = 2, z = Math.random() * 100; - - for ( var j = 0; j < 4; j ++ ) { - - if ( j == 0 ) for ( var i = 0; i < size; i ++ ) data[ i ] = 0; - - for ( var i = 0; i < size; i ++ ) { - - var x = i % width, y = ( i / width ) | 0; - data[ i ] += perlin.noise( x / quality, y / quality, z ) * quality; - - - } - - quality *= 4 - - } - - return data; - - } - - function getY( x, z ) { - - return ( data[ x + z * worldWidth ] * 0.2 ) | 0; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - controls.update( clock.getDelta() ); - effect.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_normals.html - -()=>{ - - var container, stats; - - var camera, scene, renderer; - - var cube, plane; - - var targetYRotation = 0; - var targetXRotation = 0; - var targetYRotationOnMouseDown = 0; - var targetXRotationOnMouseDown = 0; - - var mouseX = 0, mouseY = 0; - var mouseXOnMouseDown = 0; - var mouseYOnMouseDown = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var group; - - var targetRotationOnMouseDown; - var targetRotation; - - - // Create new object by parameters - - var createSomething = function( klass, args ) { - - var F = function( klass, args ) { - - return klass.apply( this, args ); - - } - - F.prototype = klass.prototype; - - return F( klass, args ); - - }; - - - // Cube - - var materials = []; - - for ( var i = 0; i < 6; i ++ ) { - - materials.push( [ new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: false } ) ] ); - - } - - - - var geometriesParams: {type:string;args:any[];}[] = [ - - { type: 'CubeGeometry', args: [ 200, 200, 200, 2, 2, 2, materials ] }, - { type: 'TorusGeometry', args: [ 100, 60, 12, 12 ] }, - { type: 'TorusKnotGeometry', args: [ ] }, - { type: 'SphereGeometry', args: [ 100, 12, 12 ] }, - { type: 'SphereGeometry', args: [ 100, 5, 5 ] }, - { type: 'SphereGeometry', args: [ 100, 13, 13 ] }, - { type: 'IcosahedronGeometry', args: [ 100, 1 ] }, - { type: 'CylinderGeometry', args: [ 25, 75, 200, 8, 3 ]} , - { type: 'OctahedronGeometry', args: [200, 0] }, - { type: 'LatheGeometry', args: [ [ - new THREE.Vector3(0,0,-100), - new THREE.Vector3(0,50,-50), - new THREE.Vector3(0,10,0), - new THREE.Vector3(0,50,50), - new THREE.Vector3(0,0,100) ] ]}, - { type: 'LatheGeometry', args: [ [ - new THREE.Vector3(0,0,-100), - new THREE.Vector3(0,50,-50), - new THREE.Vector3(0,10,0), - new THREE.Vector3(0,50,50), - new THREE.Vector3(0,100,100) ], 12, 0, Math.PI ] }, - { type: 'LatheGeometry', args: [ [ - new THREE.Vector3(0,10,-100), - new THREE.Vector3(0,50,-50), - new THREE.Vector3(0,10,0), - new THREE.Vector3(0,50,50), - new THREE.Vector3(0,0,100) ], 12, Math.PI*2/3, Math.PI*3/2 ] }, - { type: 'TextGeometry', args: ['&', { - size: 200, - height: 50, - curveSegments: 1, - font: "helvetiker" - - }]}, - { type: 'PlaneGeometry', args: [ 200, 200, 4, 4 ] } - - ]; - - var info; - var geometryIndex = 0; - - // start scene - - init(); - animate(); - - function nextGeometry() { - - geometryIndex ++; - - if ( geometryIndex > geometriesParams.length - 1 ) { - - geometryIndex = 0; - - } - - addStuff(); - - } - - function switchGeometry(i) { - - geometryIndex = i; - - addStuff(); - } - - function updateInfo() { - - var params = geometriesParams[ geometryIndex ]; - - var dropdown = ''; - - var text = - 'Drag to spin THREE.' + params.type + - '
    ' + - '
    Geometry: ' + dropdown + ' next'; - - text += - '

    Blue Arrows: Face Normals' + - '
    Red Arrows: Vertex Normals before Geometry.mergeVertices' + - '
    Black Arrows: Vertex Normals after Geometry.mergeVertices'; - - info.innerHTML = text; - - } - - function addStuff() { - - if ( group !== undefined ) { - - scene.remove( group ); - - } - - - - var params = geometriesParams[ geometryIndex ]; - - var geometry = createSomething( THREE[ params.type ], params.args ); - - // scale geometry to a uniform size - geometry.computeBoundingSphere(); - - var scaleFactor = 160 / geometry.boundingSphere.radius; - geometry.applyMatrix( new THREE.Matrix4().makeScale( scaleFactor, scaleFactor, scaleFactor ) ); - - var originalGeometry = geometry.clone(); - originalGeometry.computeFaceNormals(); - originalGeometry.computeVertexNormals( true ); - - // in case of duplicated vertices - geometry.mergeVertices(); - geometry.computeCentroids(); - geometry.computeFaceNormals(); - geometry.computeVertexNormals( true ); - - updateInfo(); - - var faceABCD = "abcd"; - var color, f, p, n, vertexIndex; - - for ( i = 0; i < geometry.faces.length; i ++ ) { - - f = geometry.faces[ i ]; - - - n = ( f instanceof THREE.Face3 ) ? 3 : 4; - - for( var j = 0; j < n; j++ ) { - - vertexIndex = f[ faceABCD.charAt( j ) ]; - - p = geometry.vertices[ vertexIndex ]; - - color = new THREE.Color( 0xffffff ); - color.setHSL( ( p.y ) / 400 + 0.5, 1.0, 1.0 ); - - f.vertexColors[ j ] = color; - - } - - } - - - group = new THREE.Object3D(); - var mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { color: 0xfefefe, wireframe: true, opacity: 0.5 } ) ); - group.add( mesh ); - scene.add( group ); - - var fvNames = [ 'a', 'b', 'c', 'd' ]; - - var normalLength = 15; - - var fl: number; - var face: THREE.Face; - - for( f = 0, fl = geometry.faces.length; f < fl; f ++ ) { - face = geometry.faces[ f ]; - var arrow = new THREE.ArrowHelper( - face.normal, - face.centroid, - normalLength, - 0x3333FF ); - mesh.add( arrow ); - } - - for( f = 0, fl = originalGeometry.faces.length; f < fl; f ++ ) { - face = originalGeometry.faces[ f ]; - if( face.vertexNormals === undefined ) { - continue; - } - for( var v = 0, vl = face.vertexNormals.length; v < vl; v ++ ) { - var arrow = new THREE.ArrowHelper( - face.vertexNormals[ v ], - originalGeometry.vertices[ face[ fvNames[ v ] ] ], - normalLength, - 0xFF3333 ); - mesh.add( arrow ); - } - } - - for( f = 0, fl = mesh.geometry.faces.length; f < fl; f ++ ) { - face = mesh.geometry.faces[ f ]; - if( face.vertexNormals === undefined ) { - continue; - } - for( var v = 0, vl = face.vertexNormals.length; v < vl; v ++ ) { - var arrow = new THREE.ArrowHelper( - face.vertexNormals[ v ], - mesh.geometry.vertices[ face[ fvNames[ v ] ] ], - normalLength, - 0x000000 ); - mesh.add( arrow ); - } - } - - } - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - info = document.createElement( 'div' ); - info.style.position = 'absolute'; - info.style.top = '10px'; - info.style.width = '100%'; - info.style.textAlign = 'center'; - info.innerHTML = 'Drag to spin the geometry '; - container.appendChild( info ); - - camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.z = 500; - - scene = new THREE.Scene(); - - var light = new THREE.PointLight( 0xffffff, 1.5 ); - light.position.set( 1000, 1000, 2000 ); - scene.add( light ); - - addStuff(); - - renderer = new THREE.WebGLRenderer( { antialias: true } ); // WebGLRenderer CanvasRenderer - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousedown', onDocumentMouseDown, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function onDocumentMouseDown( event ) { - - //event.preventDefault(); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'mouseup', onDocumentMouseUp, false ); - document.addEventListener( 'mouseout', onDocumentMouseOut, false ); - - mouseXOnMouseDown = event.clientX - windowHalfX; - mouseYOnMouseDown = event.clientY - windowHalfY; - targetYRotationOnMouseDown = targetYRotation; - targetXRotationOnMouseDown = targetXRotation; - - } - - function onDocumentMouseMove( event ) { - - mouseX = event.clientX - windowHalfX; - mouseY = event.clientY - windowHalfY; - - targetYRotation = targetYRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.02; - targetXRotation = targetXRotationOnMouseDown + ( mouseY - mouseYOnMouseDown ) * 0.02; - - } - - function onDocumentMouseUp( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - document.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - document.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - } - - function onDocumentMouseOut( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - document.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - document.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX; - targetRotationOnMouseDown = targetRotation; - - } - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05; - - } - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - group.rotation.x = ( targetXRotation) * 0.15; - group.rotation.y = ( targetYRotation ) * 0.15; - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_shapes.html - -()=>{ - - var container, stats; - - var camera, scene, renderer; - - var text, plane; - - var targetRotation = 0; - var targetRotationOnMouseDown = 0; - - var mouseX = 0; - var mouseXOnMouseDown = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var parent; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - var info = document.createElement( 'div' ); - info.style.position = 'absolute'; - info.style.top = '10px'; - info.style.width = '100%'; - info.style.textAlign = 'center'; - info.innerHTML = 'Simple procedurally generated 3D shapes example by zz85
    Drag to spin'; - container.appendChild( info ); - - camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.set( 0, 150, 500 ); - - scene = new THREE.Scene(); - - var light = new THREE.DirectionalLight( 0xffffff ); - light.position.set( 0, 0, 1 ); - scene.add( light ); - - parent = new THREE.Object3D(); - parent.position.y = 50; - scene.add( parent ); - - function addShape( shape, extrudeSettings, color, x, y, z, rx, ry, rz, s ) { - - var points = shape.createPointsGeometry(); - var spacedPoints = shape.createSpacedPointsGeometry( 100 ); - - // flat shape - - var geometry = new THREE.ShapeGeometry( shape ); - - var mesh = THREE.SceneUtils.createMultiMaterialObject( geometry, [ new THREE.MeshLambertMaterial( { color: color } ), new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true, transparent: true } ) ] ); - mesh.position.set( x, y, z - 125 ); - mesh.rotation.set( rx, ry, rz ); - mesh.scale.set( s, s, s ); - parent.add( mesh ); - - // 3d shape - - var geometryExtrude = new THREE.ExtrudeGeometry( shape, extrudeSettings ); - - var mesh = THREE.SceneUtils.createMultiMaterialObject( geometryExtrude, [ new THREE.MeshLambertMaterial( { color: color } ), new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true, transparent: true } ) ] ); - mesh.position.set( x, y, z - 75 ); - mesh.rotation.set( rx, ry, rz ); - mesh.scale.set( s, s, s ); - parent.add( mesh ); - - // solid line - - var line = new THREE.Line( points, new THREE.LineBasicMaterial( { color: color, linewidth: 2 } ) ); - line.position.set( x, y, z + 25 ); - line.rotation.set( rx, ry, rz ); - line.scale.set( s, s, s ); - parent.add( line ); - - // transparent line from real points - - var line = new THREE.Line( points, new THREE.LineBasicMaterial( { color: color, opacity: 0.5 } ) ); - line.position.set( x, y, z + 75 ); - line.rotation.set( rx, ry, rz ); - line.scale.set( s, s, s ); - parent.add( line ); - - // vertices from real points - - var pgeo = points.clone(); - var particles = new THREE.ParticleSystem( pgeo, new THREE.ParticleSystemMaterial( { color: color, size: 2, opacity: 0.75 } ) ); - particles.position.set( x, y, z + 75 ); - particles.rotation.set( rx, ry, rz ); - particles.scale.set( s, s, s ); - parent.add( particles ); - - // transparent line from equidistance sampled points - - var line = new THREE.Line( spacedPoints, new THREE.LineBasicMaterial( { color: color, opacity: 0.2 } ) ); - line.position.set( x, y, z + 125 ); - line.rotation.set( rx, ry, rz ); - line.scale.set( s, s, s ); - parent.add( line ); - - // equidistance sampled points - - var pgeo = spacedPoints.clone(); - var particles2 = new THREE.ParticleSystem( pgeo, new THREE.ParticleSystemMaterial( { color: color, size: 2, opacity: 0.5 } ) ); - particles2.position.set( x, y, z + 125 ); - particles2.rotation.set( rx, ry, rz ); - particles2.scale.set( s, s, s ); - parent.add( particles2 ); - - } - - - // California - - var californiaPts = []; - - californiaPts.push( new THREE.Vector2 ( 610, 320 ) ); - californiaPts.push( new THREE.Vector2 ( 450, 300 ) ); - californiaPts.push( new THREE.Vector2 ( 392, 392 ) ); - californiaPts.push( new THREE.Vector2 ( 266, 438 ) ); - californiaPts.push( new THREE.Vector2 ( 190, 570 ) ); - californiaPts.push( new THREE.Vector2 ( 190, 600 ) ); - californiaPts.push( new THREE.Vector2 ( 160, 620 ) ); - californiaPts.push( new THREE.Vector2 ( 160, 650 ) ); - californiaPts.push( new THREE.Vector2 ( 180, 640 ) ); - californiaPts.push( new THREE.Vector2 ( 165, 680 ) ); - californiaPts.push( new THREE.Vector2 ( 150, 670 ) ); - californiaPts.push( new THREE.Vector2 ( 90, 737 ) ); - californiaPts.push( new THREE.Vector2 ( 80, 795 ) ); - californiaPts.push( new THREE.Vector2 ( 50, 835 ) ); - californiaPts.push( new THREE.Vector2 ( 64, 870 ) ); - californiaPts.push( new THREE.Vector2 ( 60, 945 ) ); - californiaPts.push( new THREE.Vector2 ( 300, 945 ) ); - californiaPts.push( new THREE.Vector2 ( 300, 743 ) ); - californiaPts.push( new THREE.Vector2 ( 600, 473 ) ); - californiaPts.push( new THREE.Vector2 ( 626, 425 ) ); - californiaPts.push( new THREE.Vector2 ( 600, 370 ) ); - californiaPts.push( new THREE.Vector2 ( 610, 320 ) ); - - var californiaShape = new THREE.Shape( californiaPts ); - - - // Triangle - - var triangleShape = new THREE.Shape(); - triangleShape.moveTo( 80, 20 ); - triangleShape.lineTo( 40, 80 ); - triangleShape.lineTo( 120, 80 ); - triangleShape.lineTo( 80, 20 ); // close path - - - // Heart - - var x = 0, y = 0; - - var heartShape = new THREE.Shape(); // From http://blog.burlock.org/html5/130-paths - - heartShape.moveTo( x + 25, y + 25 ); - heartShape.bezierCurveTo( x + 25, y + 25, x + 20, y, x, y ); - heartShape.bezierCurveTo( x - 30, y, x - 30, y + 35,x - 30,y + 35 ); - heartShape.bezierCurveTo( x - 30, y + 55, x - 10, y + 77, x + 25, y + 95 ); - heartShape.bezierCurveTo( x + 60, y + 77, x + 80, y + 55, x + 80, y + 35 ); - heartShape.bezierCurveTo( x + 80, y + 35, x + 80, y, x + 50, y ); - heartShape.bezierCurveTo( x + 35, y, x + 25, y + 25, x + 25, y + 25 ); - - - // Square - - var sqLength = 80; - - var squareShape = new THREE.Shape(); - squareShape.moveTo( 0,0 ); - squareShape.lineTo( 0, sqLength ); - squareShape.lineTo( sqLength, sqLength ); - squareShape.lineTo( sqLength, 0 ); - squareShape.lineTo( 0, 0 ); - - - // Rectangle - - var rectLength = 120, rectWidth = 40; - - var rectShape = new THREE.Shape(); - rectShape.moveTo( 0,0 ); - rectShape.lineTo( 0, rectWidth ); - rectShape.lineTo( rectLength, rectWidth ); - rectShape.lineTo( rectLength, 0 ); - rectShape.lineTo( 0, 0 ); - - - // Rounded rectangle - - var roundedRectShape = new THREE.Shape(); - - ( function roundedRect( ctx, x, y, width, height, radius ){ - - ctx.moveTo( x, y + radius ); - ctx.lineTo( x, y + height - radius ); - ctx.quadraticCurveTo( x, y + height, x + radius, y + height ); - ctx.lineTo( x + width - radius, y + height) ; - ctx.quadraticCurveTo( x + width, y + height, x + width, y + height - radius ); - ctx.lineTo( x + width, y + radius ); - ctx.quadraticCurveTo( x + width, y, x + width - radius, y ); - ctx.lineTo( x + radius, y ); - ctx.quadraticCurveTo( x, y, x, y + radius ); - - } )( roundedRectShape, 0, 0, 50, 50, 20 ); - - - // Circle - - var circleRadius = 40; - var circleShape = new THREE.Shape(); - circleShape.moveTo( 0, circleRadius ); - circleShape.quadraticCurveTo( circleRadius, circleRadius, circleRadius, 0 ); - circleShape.quadraticCurveTo( circleRadius, -circleRadius, 0, -circleRadius ); - circleShape.quadraticCurveTo( -circleRadius, -circleRadius, -circleRadius, 0 ); - circleShape.quadraticCurveTo( -circleRadius, circleRadius, 0, circleRadius ); - - - // Fish - - x = y = 0; - - var fishShape = new THREE.Shape(); - - fishShape.moveTo(x,y); - fishShape.quadraticCurveTo(x + 50, y - 80, x + 90, y - 10); - fishShape.quadraticCurveTo(x + 100, y - 10, x + 115, y - 40); - fishShape.quadraticCurveTo(x + 115, y, x + 115, y + 40); - fishShape.quadraticCurveTo(x + 100, y + 10, x + 90, y + 10); - fishShape.quadraticCurveTo(x + 50, y + 80, x, y); - - - // Arc circle - - var arcShape = new THREE.Shape(); - arcShape.moveTo( 50, 10 ); - arcShape.absarc( 10, 10, 40, 0, Math.PI*2, false ); - - var holePath = new THREE.Path(); - holePath.moveTo( 20, 10 ); - holePath.absarc( 10, 10, 10, 0, Math.PI*2, true ); - arcShape.holes.push( holePath ); - - - // Smiley - - var smileyShape = new THREE.Shape(); - smileyShape.moveTo( 80, 40 ); - smileyShape.absarc( 40, 40, 40, 0, Math.PI*2, false ); - - var smileyEye1Path = new THREE.Path(); - smileyEye1Path.moveTo( 35, 20 ); - // smileyEye1Path.absarc( 25, 20, 10, 0, Math.PI*2, true ); - smileyEye1Path.absellipse( 25, 20, 10, 10, 0, Math.PI*2, true ); - - smileyShape.holes.push( smileyEye1Path ); - - var smileyEye2Path = new THREE.Path(); - smileyEye2Path.moveTo( 65, 20 ); - smileyEye2Path.absarc( 55, 20, 10, 0, Math.PI*2, true ); - smileyShape.holes.push( smileyEye2Path ); - - var smileyMouthPath = new THREE.Path(); - // ugly box mouth - // smileyMouthPath.moveTo( 20, 40 ); - // smileyMouthPath.lineTo( 60, 40 ); - // smileyMouthPath.lineTo( 60, 60 ); - // smileyMouthPath.lineTo( 20, 60 ); - // smileyMouthPath.lineTo( 20, 40 ); - - smileyMouthPath.moveTo( 20, 40 ); - smileyMouthPath.quadraticCurveTo( 40, 60, 60, 40 ); - smileyMouthPath.bezierCurveTo( 70, 45, 70, 50, 60, 60 ); - smileyMouthPath.quadraticCurveTo( 40, 80, 20, 60 ); - smileyMouthPath.quadraticCurveTo( 5, 50, 20, 40 ); - - smileyShape.holes.push( smileyMouthPath ); - - - // Spline shape + path extrusion - - var splinepts = []; - splinepts.push( new THREE.Vector2 ( 350, 100 ) ); - splinepts.push( new THREE.Vector2 ( 400, 450 ) ); - splinepts.push( new THREE.Vector2 ( -140, 350 ) ); - splinepts.push( new THREE.Vector2 ( 0, 0 ) ); - - var splineShape = new THREE.Shape( ); - splineShape.moveTo( 0, 0 ); - splineShape.splineThru( splinepts ); - - // splineShape.debug( document.getElementById("debug") ); - - // TODO 3d path? - - - var extrudeSettings:any = { amount: 20 }; // bevelSegments: 2, steps: 2 , bevelSegments: 5, bevelSize: 8, bevelThickness:5 - - // addShape( shape, color, x, y, z, rx, ry,rz, s ); - - addShape( californiaShape, extrudeSettings, 0xffaa00, -300, -100, 0, 0, 0, 0, 0.25 ); - - extrudeSettings.bevelEnabled = true; - extrudeSettings.bevelSegments = 2; - extrudeSettings.steps = 2; - - addShape( triangleShape, extrudeSettings, 0xffee00, -180, 0, 0, 0, 0, 0, 1 ); - addShape( roundedRectShape, extrudeSettings, 0x005500, -150, 150, 0, 0, 0, 0, 1 ); - addShape( squareShape, extrudeSettings, 0x0055ff, 150, 100, 0, 0, 0, 0, 1 ); - addShape( heartShape, extrudeSettings, 0xff1100, 60, 100, 0, 0, 0, Math.PI, 1 ); - addShape( circleShape, extrudeSettings, 0x00ff11, 120, 250, 0, 0, 0, 0, 1 ); - addShape( fishShape, extrudeSettings, 0x222222, -60, 200, 0, 0, 0, 0, 1 ); - addShape( smileyShape, extrudeSettings, 0xee00ff, -200, 250, 0, 0, 0, Math.PI, 1 ); - addShape( arcShape, extrudeSettings, 0xbb4422, 150, 0, 0, 0, 0, 0, 1 ); - - extrudeSettings.bevelEnabled = false; - extrudeSettings.steps = 20; - - addShape( splineShape, extrudeSettings, 0x888888, -50, -100, -50, 0, 0, 0, 0.2 ); - - // - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousedown', onDocumentMouseDown, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function onDocumentMouseDown( event ) { - - event.preventDefault(); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'mouseup', onDocumentMouseUp, false ); - document.addEventListener( 'mouseout', onDocumentMouseOut, false ); - - mouseXOnMouseDown = event.clientX - windowHalfX; - targetRotationOnMouseDown = targetRotation; - - } - - function onDocumentMouseMove( event ) { - - mouseX = event.clientX - windowHalfX; - - targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.02; - - } - - function onDocumentMouseUp( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - document.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - document.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - - } - - function onDocumentMouseOut( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - document.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - document.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX; - targetRotationOnMouseDown = targetRotation; - - } - - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05; - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - parent.rotation.y += ( targetRotation - parent.rotation.y ) * 0.05; - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_subdivision.html - -()=>{ - - var container, stats; - - var camera, scene, renderer; - - var cube, plane; - - var targetYRotation = 0; - var targetXRotation = 0; - var targetYRotationOnMouseDown = 0; - var targetXRotationOnMouseDown = 0; - var targetRotationOnMouseDown = 0; - var targetRotation = 0; - - var mouseX = 0, mouseY = 0; - var mouseXOnMouseDown = 0; - var mouseYOnMouseDown = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var scene, group, cube, geometry, smooth; - - - // Create new object by parameters - - var createSomething = function( klass, args ) { - - var F = function( klass, args ) { - - return klass.apply( this, args ); - - } - - F.prototype = klass.prototype; - - return F( klass, args ); - - }; - - - // Cube - - var materials = []; - - for ( var i = 0; i < 6; i ++ ) { - - materials.push( [ new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: false } ) ] ); - - } - - - - var geometriesParams:{type:string;args:any[];}[] = [ - - { type: 'CubeGeometry', args: [ 200, 200, 200, 2, 2, 2, materials ] }, - { type: 'TorusGeometry', args: [ 100, 60, 4, 8, Math.PI*2 ] }, - { type: 'TorusKnotGeometry', args: [ ], scale:0.25, meshScale:4 }, - { type: 'SphereGeometry', args: [ 100, 3, 3 ], meshScale:2 }, - { type: 'IcosahedronGeometry', args: [ 100, 1 ], meshScale:2 }, - { type: 'CylinderGeometry', args: [ 25, 75, 200, 8, 3 ]} , - { type: 'OctahedronGeometry', args: [200, 0], meshScale:2 }, - { type: 'LatheGeometry', args: [ [ - new THREE.Vector3(0,0,0), - new THREE.Vector3(0,50,50), - new THREE.Vector3(0,10,100), - new THREE.Vector3(0,50,150), - new THREE.Vector3(0,0,200) ] ]}, - { type: 'TextGeometry', args: ['&', { - size: 200, - height: 50, - curveSegments: 1, - font: "helvetiker" - - }]}, - { type: 'PlaneGeometry', args: [ 200, 200, 4, 4 ] } - - ]; - - var loader = new THREE.JSONLoader(); - loader.load( 'obj/WaltHeadLo.js', function ( geometry ) { - - geometriesParams.push({type: 'WaltHead', args: [ ], meshScale: 6 }); - - THREE["WaltHead"] = function() { - return geometry.clone(); - }; - - updateInfo() - - }); - - var loader2 = new THREE.JSONLoader(); - loader2.load( 'obj/Suzanne.js', function ( geometry ) { - - geometriesParams.push({type: 'Suzanne', args: [ ], scale: 100, meshScale:2 }); - - THREE["Suzanne"] = function() { - return geometry.clone(); - }; - - updateInfo() - - } ); - - - var info; - var subdivisions = 2; - var geometryIndex = 0; - - // start scene - - init(); - animate(); - - function nextSubdivision( x ) { - - subdivisions = Math.max( 0, subdivisions + x ); - addStuff(); - - } - - function nextGeometry() { - - geometryIndex ++; - - if ( geometryIndex > geometriesParams.length - 1 ) { - - geometryIndex = 0; - - } - - addStuff(); - - } - - function switchGeometry(i) { - - geometryIndex = i; - - addStuff(); - } - - function updateInfo() { - - var params = geometriesParams[ geometryIndex ]; - - var dropdown = ''; - - info.innerHTML = 'Drag to spin THREE.' + params.type + - - '

    Subdivisions: ' + subdivisions + - ' more/less' + - '
    Geometry: ' + dropdown + ' next' + - '

    Vertices count: before ' + geometry.vertices.length + ' after ' + smooth.vertices.length + - '
    Face count: before ' + geometry.faces.length + ' after ' + smooth.faces.length - ; //+ params.args; - } - - function addStuff() { - - if ( cube ) { - - scene.remove( group ); - scene.remove( cube ); - - } - - - var modifier = new THREE.SubdivisionModifier( subdivisions ); - - - var params:any = geometriesParams[ geometryIndex ]; - - geometry = createSomething( THREE[ params.type ], params.args ); - - // Scale Geometry - - if ( params.scale ) { - - geometry.applyMatrix( new THREE.Matrix4().makeScale( params.scale, params.scale, params.scale ) ); - - } - - // Cloning original geometry for debuging - - var smooth = geometry.clone(); - - // mergeVertices(); is run in case of duplicated vertices - smooth.mergeVertices(); - - smooth.computeCentroids(); - smooth.computeFaceNormals(); - smooth.computeVertexNormals(); - - modifier.modify( smooth ); - - updateInfo(); - - var faceABCD = "abcd"; - var color, f, p, n, vertexIndex; - - for ( i = 0; i < smooth.faces.length; i ++ ) { - - f = smooth.faces[ i ]; - - - n = ( f instanceof THREE.Face3 ) ? 3 : 4; - - for( var j = 0; j < n; j++ ) { - - vertexIndex = f[ faceABCD.charAt( j ) ]; - - p = smooth.vertices[ vertexIndex ]; - - color = new THREE.Color( 0xffffff ); - color.setHSL( ( p.y ) / 200 + 0.5, 1.0, 1.0 ); - - f.vertexColors[ j ] = color; - - } - - } - - - group = new THREE.Object3D(); - group.add( new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { color: 0xfefefe, wireframe: true, opacity: 0.5 } ) ) ); - scene.add( group ); - - - var debugNewPoints = false; - var debugOldPoints = false; - - // Debug new Points - - if (debugNewPoints) { - var PI2 = Math.PI * 2; - var program = function ( context ) { - - context.beginPath(); - context.arc( 0, 0, 1, 0, PI2, true ); - context.closePath(); - context.fill(); - - } - - for ( var i = 0; i < smooth.vertices.length; i++ ) { - var geometry = new THREE.Geometry(); - var particle = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: Math.random() * 0x808008 + 0x808080, program: program } ) ); - particle.position = smooth.vertices[ i ]; - particle.scale.x = particle.scale.y = 5; - group.add( particle ); - } - - } - - - //Debug original points - - if (debugOldPoints) { - - var drawText = function(i) { - - return function ( context ) { - - context.beginPath(); - context.scale(0.1,-0.1); - - context.fillText(i, 0,0); - - }; - - } - - for ( var i = 0; i < geometry.vertices.length; i++ ) { - var geometry = new THREE.Geometry(); - particle = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial( { color: Math.random() * 0x808008 + 0x808080, program: drawText(i) } ) ); - particle.position = smooth.vertices[ i ]; - particle.scale.x = particle.scale.y = 30; - group.add( particle ); - } - } - - - var meshmaterials:THREE.Material[] = [ - new THREE.MeshLambertMaterial( { color: 0xffffff, shading: THREE.FlatShading, vertexColors: THREE.VertexColors } ), - new THREE.MeshBasicMaterial( { color: 0x405040, wireframe: true, opacity: 0.8, transparent: true } ) - ]; - - cube = THREE.SceneUtils.createMultiMaterialObject( smooth, meshmaterials ); - - var meshScale = params.meshScale ? params.meshScale : 1; - - cube.scale.x = meshScale; - cube.scale.y = meshScale; - cube.scale.z = meshScale; - - scene.add( cube ); - - group.scale.copy( cube.scale ); - - } - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - info = document.createElement( 'div' ); - info.style.position = 'absolute'; - info.style.top = '10px'; - info.style.width = '100%'; - info.style.textAlign = 'center'; - info.innerHTML = 'Drag to spin the geometry '; - container.appendChild( info ); - - camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.z = 500; - - scene = new THREE.Scene(); - - var light = new THREE.PointLight( 0xffffff, 1.5 ); - light.position.set( 1000, 1000, 2000 ); - scene.add( light ); - - addStuff(); - - renderer = new THREE.WebGLRenderer( { antialias: true } ); // WebGLRenderer CanvasRenderer - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousedown', onDocumentMouseDown, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function onDocumentMouseDown( event ) { - - //event.preventDefault(); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'mouseup', onDocumentMouseUp, false ); - document.addEventListener( 'mouseout', onDocumentMouseOut, false ); - - mouseXOnMouseDown = event.clientX - windowHalfX; - mouseYOnMouseDown = event.clientY - windowHalfY; - targetYRotationOnMouseDown = targetYRotation; - targetXRotationOnMouseDown = targetXRotation; - - } - - function onDocumentMouseMove( event ) { - - mouseX = event.clientX - windowHalfX; - mouseY = event.clientY - windowHalfY; - - targetYRotation = targetYRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.02; - targetXRotation = targetXRotationOnMouseDown + ( mouseY - mouseYOnMouseDown ) * 0.02; - - } - - function onDocumentMouseUp( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - document.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - document.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - } - - function onDocumentMouseOut( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - document.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - document.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX; - targetRotationOnMouseDown = targetRotation; - - } - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05; - - } - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - group.rotation.x = cube.rotation.x += ( targetXRotation - cube.rotation.x ) * 0.05; - group.rotation.y = cube.rotation.y += ( targetYRotation - cube.rotation.y ) * 0.05; - - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_terrain.html - -()=>{ - - if ( ! Detector.webgl ) { - - Detector.addGetWebGLMessage(); - document.getElementById( 'container' ).innerHTML = ""; - - } - - var container, stats; - - var camera, controls, scene, renderer; - - var mesh, texture; - - var worldWidth = 256, worldDepth = 256, - worldHalfWidth = worldWidth / 2, worldHalfDepth = worldDepth / 2; - - var clock = new THREE.Clock(); - - var data; - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 20000 ); - - scene = new THREE.Scene(); - - controls = new THREE.FirstPersonControls( camera ); - controls.movementSpeed = 1000; - controls.lookSpeed = 0.1; - - data = generateHeight( worldWidth, worldDepth ); - - camera.position.y = data[ worldHalfWidth + worldHalfDepth * worldWidth ] + 500; - - var geometry = new THREE.PlaneGeometry( 7500, 7500, worldWidth - 1, worldDepth - 1 ); - geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) ); - - for ( var i = 0, l = geometry.vertices.length; i < l; i ++ ) { - - geometry.vertices[ i ].y = data[ i ] * 10; - - } - - texture = new THREE.Texture( generateTexture( data, worldWidth, worldDepth ), new THREE.UVMapping(), THREE.ClampToEdgeWrapping, THREE.ClampToEdgeWrapping ); - texture.needsUpdate = true; - - mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { map: texture } ) ); - scene.add( mesh ); - - renderer = new THREE.WebGLRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.innerHTML = ""; - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - controls.handleResize(); - - } - - function generateHeight( width, height ) { - - var size = width * height, data = new Float32Array( size ), - perlin = new ImprovedNoise(), quality = 1, z = Math.random() * 100; - - for ( var i = 0; i < size; i ++ ) { - - data[ i ] = 0 - - } - - for ( var j = 0; j < 4; j ++ ) { - - for ( var i = 0; i < size; i ++ ) { - - var x = i % width, y = ~~ ( i / width ); - data[ i ] += Math.abs( perlin.noise( x / quality, y / quality, z ) * quality * 1.75 ); - - - } - - quality *= 5; - - } - - return data; - - } - - function generateTexture( data, width, height ) { - - var canvas, canvasScaled, context, image, imageData, - level, diff, vector3, sun, shade; - - vector3 = new THREE.Vector3( 0, 0, 0 ); - - sun = new THREE.Vector3( 1, 1, 1 ); - sun.normalize(); - - canvas = document.createElement( 'canvas' ); - canvas.width = width; - canvas.height = height; - - context = canvas.getContext( '2d' ); - context.fillStyle = '#000'; - context.fillRect( 0, 0, width, height ); - - image = context.getImageData( 0, 0, canvas.width, canvas.height ); - imageData = image.data; - - for ( var i = 0, j = 0, l = imageData.length; i < l; i += 4, j ++ ) { - - vector3.x = data[ j - 2 ] - data[ j + 2 ]; - vector3.y = 2; - vector3.z = data[ j - width * 2 ] - data[ j + width * 2 ]; - vector3.normalize(); - - shade = vector3.dot( sun ); - - imageData[ i ] = ( 96 + shade * 128 ) * ( 0.5 + data[ j ] * 0.007 ); - imageData[ i + 1 ] = ( 32 + shade * 96 ) * ( 0.5 + data[ j ] * 0.007 ); - imageData[ i + 2 ] = ( shade * 96 ) * ( 0.5 + data[ j ] * 0.007 ); - } - - context.putImageData( image, 0, 0 ); - - // Scaled 4x - - canvasScaled = document.createElement( 'canvas' ); - canvasScaled.width = width * 4; - canvasScaled.height = height * 4; - - context = canvasScaled.getContext( '2d' ); - context.scale( 4, 4 ); - context.drawImage( canvas, 0, 0 ); - - image = context.getImageData( 0, 0, canvasScaled.width, canvasScaled.height ); - imageData = image.data; - - for ( var i = 0, l = imageData.length; i < l; i += 4 ) { - - var v = ~~ ( Math.random() * 5 ); - - imageData[ i ] += v; - imageData[ i + 1 ] += v; - imageData[ i + 2 ] += v; - - } - - context.putImageData( image, 0, 0 ); - - return canvasScaled; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - controls.update( clock.getDelta() ); - renderer.render( scene, camera ); - - } - -}; - - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_terrain_fog.html - -()=>{ - - if ( ! Detector.webgl ) { - - Detector.addGetWebGLMessage(); - document.getElementById( 'container' ).innerHTML = ""; - - } - - var container, stats; - - var camera, controls, scene, renderer; - - var mesh, texture; - - var worldWidth = 256, worldDepth = 256, - worldHalfWidth = worldWidth / 2, worldHalfDepth = worldDepth / 2; - - var clock = new THREE.Clock(); - - var data; - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 ); - - controls = new THREE.FirstPersonControls( camera ); - controls.movementSpeed = 150; - controls.lookSpeed = 0.1; - - scene = new THREE.Scene(); - scene.fog = new THREE.FogExp2( 0xefd1b5, 0.0025 ); - - data = generateHeight( worldWidth, worldDepth ); - - camera.position.y = data[ worldHalfWidth + worldHalfDepth * worldWidth ] * 10 + 500; - - var geometry = new THREE.PlaneGeometry( 7500, 7500, worldWidth - 1, worldDepth - 1 ); - geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) ); - - for ( var i = 0, l = geometry.vertices.length; i < l; i ++ ) { - - geometry.vertices[ i ].y = data[ i ] * 10; - - } - - texture = new THREE.Texture( generateTexture( data, worldWidth, worldDepth ), new THREE.UVMapping(), THREE.ClampToEdgeWrapping, THREE.ClampToEdgeWrapping ); - texture.needsUpdate = true; - - mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { map: texture } ) ); - scene.add( mesh ); - - renderer = new THREE.WebGLRenderer( { clearColor: 0xefd1b5, clearAlpha: 1 } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.innerHTML = ""; - - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - controls.handleResize(); - - } - - function generateHeight( width, height ) { - - var size = width * height, data = new Float32Array( size ), - perlin = new ImprovedNoise(), quality = 1, z = Math.random() * 100; - - for ( var i = 0; i < size; i ++ ) { - - data[ i ] = 0 - - } - - for ( var j = 0; j < 4; j ++ ) { - - for ( var i = 0; i < size; i ++ ) { - - var x = i % width, y = ~~ ( i / width ); - data[ i ] += Math.abs( perlin.noise( x / quality, y / quality, z ) * quality * 1.75 ); - - - } - - quality *= 5; - - } - - return data; - - } - - function generateTexture( data, width, height ) { - - var canvas, canvasScaled, context, image, imageData, - level, diff, vector3, sun, shade; - - vector3 = new THREE.Vector3( 0, 0, 0 ); - - sun = new THREE.Vector3( 1, 1, 1 ); - sun.normalize(); - - canvas = document.createElement( 'canvas' ); - canvas.width = width; - canvas.height = height; - - context = canvas.getContext( '2d' ); - context.fillStyle = '#000'; - context.fillRect( 0, 0, width, height ); - - image = context.getImageData( 0, 0, canvas.width, canvas.height ); - imageData = image.data; - - for ( var i = 0, j = 0, l = imageData.length; i < l; i += 4, j ++ ) { - - vector3.x = data[ j - 2 ] - data[ j + 2 ]; - vector3.y = 2; - vector3.z = data[ j - width * 2 ] - data[ j + width * 2 ]; - vector3.normalize(); - - shade = vector3.dot( sun ); - - imageData[ i ] = ( 96 + shade * 128 ) * ( 0.5 + data[ j ] * 0.007 ); - imageData[ i + 1 ] = ( 32 + shade * 96 ) * ( 0.5 + data[ j ] * 0.007 ); - imageData[ i + 2 ] = ( shade * 96 ) * ( 0.5 + data[ j ] * 0.007 ); - - } - - context.putImageData( image, 0, 0 ); - - // Scaled 4x - - canvasScaled = document.createElement( 'canvas' ); - canvasScaled.width = width * 4; - canvasScaled.height = height * 4; - - context = canvasScaled.getContext( '2d' ); - context.scale( 4, 4 ); - context.drawImage( canvas, 0, 0 ); - - image = context.getImageData( 0, 0, canvasScaled.width, canvasScaled.height ); - imageData = image.data; - - for ( var i = 0, l = imageData.length; i < l; i += 4 ) { - - var v = ~~ ( Math.random() * 5 ); - - imageData[ i ] += v; - imageData[ i + 1 ] += v; - imageData[ i + 2 ] += v; - - } - - context.putImageData( image, 0, 0 ); - - return canvasScaled; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - - function render() { - - controls.update( clock.getDelta() ); - renderer.render( scene, camera ); - - } -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_tessellation.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var renderer, scene, camera, stats; - - var mesh, uniforms, attributes; - - var WIDTH = window.innerWidth, - HEIGHT = window.innerHeight; - - var controls; - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 25, WIDTH / HEIGHT, 1, 10000 ); - camera.position.z = 350; - - controls = new THREE.TrackballControls( camera ); - - scene = new THREE.Scene(); - - // - - attributes = { - - displacement: { type: 'v3', value: [] }, - customColor: { type: 'c', value: [] } - - }; - - uniforms = { - - amplitude: { type: "f", value: 0.0 } - - }; - - var shaderMaterial = new THREE.ShaderMaterial( { - - uniforms: uniforms, - attributes: attributes, - vertexShader: document.getElementById( 'vertexshader' ).textContent, - fragmentShader: document.getElementById( 'fragmentshader' ).textContent, - shading: THREE.FlatShading, - side: THREE.DoubleSide - - }); - - - var geometry = new THREE.TextGeometry( "THREE.JS", { - - size: 40, - height: 5, - curveSegments: 3, - - font: "helvetiker", - weight: "bold", - style: "normal", - - bevelThickness: 2, - bevelSize: 1, - bevelEnabled: true - - }); - - geometry.dynamic = true; - - THREE.GeometryUtils.center( geometry ); - - var tessellateModifier = new THREE.TessellateModifier( 4 ); - - for ( var i = 0; i < 6; i ++ ) { - - tessellateModifier.modify( geometry ); - - } - - var explodeModifier = new THREE.ExplodeModifier(); - explodeModifier.modify( geometry ); - - var vertices = geometry.vertices; - - var colors = attributes.customColor.value; - var displacement = attributes.displacement.value; - - var h, d, x, y, z, s; - var nv, v = 0; - - for( var f = 0; f < geometry.faces.length; f ++ ) { - - var face = geometry.faces[ f ]; - - if ( face instanceof THREE.Face3 ) { - - nv = 3; - - } else { - - nv = 4; - - } - - h = 0.15 * Math.random(); - s = 0.7 * Math.random(); - - d = 10 * ( 0.5 - Math.random() ); - - x = 2 * ( 0.5 - Math.random() ); - y = 2 * ( 0.5 - Math.random() ); - z = 2 * ( 0.5 - Math.random() ); - - for ( var i = 0; i < nv; i ++ ) { - - colors[ v ] = new THREE.Color(); - displacement[ v ] = new THREE.Vector3(); - - colors[ v ].setHSL( h, s, 1 ); - colors[ v ].convertGammaToLinear(); - - displacement[ v ].set( x, y, z ); - - v += 1; - - } - - } - - console.log( "faces", geometry.faces.length ); - - mesh = new THREE.Mesh( geometry, shaderMaterial ); - mesh.rotation.set( 0.5, 0.5, 0 ); - - scene.add( mesh ); - - renderer = new THREE.WebGLRenderer( { clearColor: 0x050505, clearAlpha: 1, antialias: true } ); - renderer.setSize( WIDTH, HEIGHT ); - - var container = document.getElementById( 'container' ); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = Date.now() * 0.001; - - uniforms.amplitude.value = 0.125 * Math.sin( time * 0.5 ); - - controls.update(); - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_text.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats, permalink, hex, color; - - var camera, cameraTarget, scene, renderer; - - var composer; - var effectFXAA; - - var textMesh1, textMesh2, textGeo, material, parent; - - var firstLetter = true; - - var text = "three.js", - - height = 20, - size = 70, - hover = 30, - - curveSegments = 4, - - bevelThickness = 2, - bevelSize = 1.5, - bevelSegments = 3, - bevelEnabled = true, - - font = "optimer", // helvetiker, optimer, gentilis, droid sans, droid serif - weight = "bold", // normal bold - style = "normal"; // normal italic - - var mirror = true; - - var fontMap = { - - "helvetiker": 0, - "optimer": 1, - "gentilis": 2, - "droid sans": 3, - "droid serif": 4 - - }; - - var weightMap = { - - "normal": 0, - "bold": 1 - - }; - - var reverseFontMap = {}; - var reverseWeightMap = {}; - - for ( var i in fontMap ) reverseFontMap[ fontMap[i] ] = i; - for ( var i in weightMap ) reverseWeightMap[ weightMap[i] ] = i; - - var targetRotation = 0; - var targetRotationOnMouseDown = 0; - - var mouseX = 0; - var mouseXOnMouseDown = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var postprocessing = { enabled : false }; - var glow = 0.9; - - init(); - animate(); - - function capitalize( txt ) { - - return txt.substring( 0, 1 ).toUpperCase() + txt.substring( 1 ); - - } - - function decimalToHex( d ) { - - var hex = Number( d ).toString( 16 ); - hex = "000000".substr( 0, 6 - hex.length ) + hex; - return hex.toUpperCase(); - - } - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - permalink = document.getElementById( "permalink" ); - - // CAMERA - - camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 1500 ); - camera.position.set( 0, 400, 700 ); - - cameraTarget = new THREE.Vector3( 0, 150, 0 ); - - // SCENE - - scene = new THREE.Scene(); - scene.fog = new THREE.Fog( 0x000000, 250, 1400 ); - - // LIGHTS - - var dirLight = new THREE.DirectionalLight( 0xffffff, 0.125 ); - dirLight.position.set( 0, 0, 1 ).normalize(); - scene.add( dirLight ); - - var pointLight = new THREE.PointLight( 0xffffff, 1.5 ); - pointLight.position.set( 0, 100, 90 ); - scene.add( pointLight ); - - //text = capitalize( font ) + " " + capitalize( weight ); - //text = "abcdefghijklmnopqrstuvwxyz0123456789"; - //text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - - // Get text from hash - - var hash = document.location.hash.substr( 1 ); - - if ( hash.length !== 0 ) { - - var colorhash = hash.substring( 0, 6 ); - var fonthash = hash.substring( 6, 7 ); - var weighthash = hash.substring( 7, 8 ); - var pphash = hash.substring( 8, 9 ); - var bevelhash = hash.substring( 9, 10 ); - var texthash = hash.substring( 10 ); - - hex = colorhash; - pointLight.color.setHex( parseInt( colorhash, 16 ) ); - - font = reverseFontMap[ parseInt( fonthash ) ]; - weight = reverseWeightMap[ parseInt( weighthash ) ]; - - postprocessing.enabled = parseInt( pphash ) ? true : false; - bevelEnabled = parseInt( bevelhash ) ? true : false; - - text = decodeURI( texthash ); - - updatePermalink(); - - } else { - - pointLight.color.setHSL( Math.random(), 0.95, 0.85 ); - hex = decimalToHex( pointLight.color.getHex() ); - - } - - material = new THREE.MeshFaceMaterial( [ - new THREE.MeshPhongMaterial( { color: 0xffffff, shading: THREE.FlatShading } ), // front - new THREE.MeshPhongMaterial( { color: 0xffffff, shading: THREE.SmoothShading } ) // side - ] ); - - parent = new THREE.Object3D(); - parent.position.y = 100; - - scene.add( parent ); - - createText(); - - var plane = new THREE.Mesh( new THREE.PlaneGeometry( 10000, 10000 ), new THREE.MeshBasicMaterial( { color: 0xffffff, opacity: 0.5, transparent: true } ) ); - plane.position.y = 100; - plane.rotation.x = - Math.PI / 2; - scene.add( plane ); - - // RENDERER - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - renderer.setClearColor( scene.fog.color, 1 ); - - container.appendChild( renderer.domElement ); - - // STATS - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - //container.appendChild( stats.domElement ); - - // EVENTS - - document.addEventListener( 'mousedown', onDocumentMouseDown, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - document.addEventListener( 'keypress', onDocumentKeyPress, false ); - document.addEventListener( 'keydown', onDocumentKeyDown, false ); - - document.getElementById( "color" ).addEventListener( 'click', function() { - - pointLight.color.setHSL( Math.random(), 0.95, 0.85 ); - hex = decimalToHex( pointLight.color.getHex() ); - - updatePermalink(); - - }, false ); - - document.getElementById( "font" ).addEventListener( 'click', function() { - - if ( font == "helvetiker" ) { - - font = "optimer"; - - } else if ( font == "optimer" ) { - - font = "gentilis"; - - } else if ( font == "gentilis" ) { - - font = "droid sans"; - - } else if ( font == "droid sans" ) { - - font = "droid serif"; - - } else { - - font = "helvetiker"; - - } - - refreshText(); - - }, false ); - - document.getElementById( "weight" ).addEventListener( 'click', function() { - - if ( weight == "bold" ) { - - weight = "normal"; - - } else { - - weight = "bold"; - - } - - refreshText(); - - }, false ); - - document.getElementById( "bevel" ).addEventListener( 'click', function() { - - bevelEnabled = !bevelEnabled; - - refreshText(); - - }, false ); - - document.getElementById( "postprocessing" ).addEventListener( 'click', function() { - - postprocessing.enabled = !postprocessing.enabled; - updatePermalink(); - - }, false ); - - - // POSTPROCESSING - - renderer.autoClear = false; - - var renderModel = new THREE.RenderPass( scene, camera ); - var effectBloom = new THREE.BloomPass( 0.25 ); - var effectFilm = new THREE.FilmPass( 0.5, 0.125, 2048, false ); - - effectFXAA = new THREE.ShaderPass( THREE.FXAAShader ); - - var width = window.innerWidth || 2; - var height = window.innerHeight || 2; - - effectFXAA.uniforms[ 'resolution' ].value.set( 1 / width, 1 / height ); - - effectFilm.renderToScreen = true; - - composer = new THREE.EffectComposer( renderer ); - - composer.addPass( renderModel ); - composer.addPass( effectFXAA ); - composer.addPass( effectBloom ); - composer.addPass( effectFilm ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - composer.reset(); - - effectFXAA.uniforms[ 'resolution' ].value.set( 1 / window.innerWidth, 1 / window.innerHeight ); - - } - - // - - function boolToNum( b ) { - - return b ? 1 : 0; - - } - - function updatePermalink() { - - var link = hex + fontMap[ font ] + weightMap[ weight ] + boolToNum( postprocessing.enabled ) + boolToNum( bevelEnabled ) + "#" + encodeURI( text ); - - permalink.href = "#" + link; - window.location.hash = link; - - } - - function onDocumentKeyDown( event ) { - - if ( firstLetter ) { - - firstLetter = false; - text = ""; - - } - - var keyCode = event.keyCode; - - // backspace - - if ( keyCode == 8 ) { - - event.preventDefault(); - - text = text.substring( 0, text.length - 1 ); - refreshText(); - - return false; - - } - - } - - function onDocumentKeyPress( event ) { - - var keyCode = event.which; - - // backspace - - if ( keyCode == 8 ) { - - event.preventDefault(); - - } else { - - var ch = String.fromCharCode( keyCode ); - text += ch; - - refreshText(); - - } - - } - - function createText() { - - textGeo = new THREE.TextGeometry( text, { - - size: size, - height: height, - curveSegments: curveSegments, - - font: font, - weight: weight, - style: style, - - bevelThickness: bevelThickness, - bevelSize: bevelSize, - bevelEnabled: bevelEnabled, - - material: 0, - extrudeMaterial: 1 - - }); - - textGeo.computeBoundingBox(); - textGeo.computeVertexNormals(); - - // "fix" side normals by removing z-component of normals for side faces - // (this doesn't work well for beveled geometry as then we lose nice curvature around z-axis) - - if ( ! bevelEnabled ) { - - var triangleAreaHeuristics = 0.1 * ( height * size ); - - for ( var i = 0; i < textGeo.faces.length; i ++ ) { - - var face = textGeo.faces[ i ]; - - if ( face.materialIndex == 1 ) { - - for ( var j = 0; j < face.vertexNormals.length; j ++ ) { - - face.vertexNormals[ j ].z = 0; - face.vertexNormals[ j ].normalize(); - - } - - var va = textGeo.vertices[ face.a ]; - var vb = textGeo.vertices[ face.b ]; - var vc = textGeo.vertices[ face.c ]; - - var s = THREE.GeometryUtils.triangleArea( va, vb, vc ); - - if ( s > triangleAreaHeuristics ) { - - for ( var j = 0; j < face.vertexNormals.length; j ++ ) { - - face.vertexNormals[ j ].copy( face.normal ); - - } - - } - - } - - } - - } - - var centerOffset = -0.5 * ( textGeo.boundingBox.max.x - textGeo.boundingBox.min.x ); - - textMesh1 = new THREE.Mesh( textGeo, material ); - - textMesh1.position.x = centerOffset; - textMesh1.position.y = hover; - textMesh1.position.z = 0; - - textMesh1.rotation.x = 0; - textMesh1.rotation.y = Math.PI * 2; - - parent.add( textMesh1 ); - - if ( mirror ) { - - textMesh2 = new THREE.Mesh( textGeo, material ); - - textMesh2.position.x = centerOffset; - textMesh2.position.y = -hover; - textMesh2.position.z = height; - - textMesh2.rotation.x = Math.PI; - textMesh2.rotation.y = Math.PI * 2; - - parent.add( textMesh2 ); - - } - - } - - function refreshText() { - - updatePermalink(); - - parent.remove( textMesh1 ); - if ( mirror ) parent.remove( textMesh2 ); - - if ( !text ) return; - - createText(); - - } - - function onDocumentMouseDown( event ) { - - event.preventDefault(); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'mouseup', onDocumentMouseUp, false ); - document.addEventListener( 'mouseout', onDocumentMouseOut, false ); - - mouseXOnMouseDown = event.clientX - windowHalfX; - targetRotationOnMouseDown = targetRotation; - - } - - function onDocumentMouseMove( event ) { - - mouseX = event.clientX - windowHalfX; - - targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.02; - - } - - function onDocumentMouseUp( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - document.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - document.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - - } - - function onDocumentMouseOut( event ) { - - document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); - document.removeEventListener( 'mouseup', onDocumentMouseUp, false ); - document.removeEventListener( 'mouseout', onDocumentMouseOut, false ); - - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX; - targetRotationOnMouseDown = targetRotation; - - } - - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05; - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - parent.rotation.y += ( targetRotation - parent.rotation.y ) * 0.05; - - camera.lookAt( cameraTarget ); - - renderer.clear(); - - if ( postprocessing.enabled ) { - - composer.render( 0.05 ); - - } else { - - renderer.render( scene, camera ); - - } - - } -}; - - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_hdr.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, scene, renderer; - var materialHDR, quad; - - var sign = 1, rate = 1; - - var clock = new THREE.Clock(); - - var delta; - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.z = 900; - - scene = new THREE.Scene(); - - var texture = THREE.ImageUtils.loadTexture( "textures/memorial.png" ); - texture.minFilter = THREE.LinearFilter; - texture.magFilter = THREE.NearestFilter; - - materialHDR = new THREE.ShaderMaterial( { - - uniforms: { - tDiffuse: { type: "t", value: texture }, - exposure: { type: "f", value: 0.125 }, - brightMax: { type: "f", value: 0.5 } - }, - vertexShader: getText( 'vs-hdr' ), - fragmentShader: getText( 'fs-hdr' ) - - } ); - - var plane = new THREE.PlaneGeometry( 512, 768 ); - - quad = new THREE.Mesh( plane, materialHDR ); - quad.position.z = -100; - scene.add( quad ); - - renderer = new THREE.WebGLRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function getText( id ) { - - return document.getElementById( id ).textContent; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - delta = clock.getDelta() * 5; - - if ( materialHDR.uniforms.exposure.value > 0 || materialHDR.uniforms.exposure.value < 1 ) { - - rate = 0.25; - - } else { - - rate = 1; - - } - - if ( materialHDR.uniforms.exposure.value > 5 || materialHDR.uniforms.exposure.value <= 0 ) { - - sign *= -1; - - } - - materialHDR.uniforms.exposure.value += sign * rate * delta; - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_interactive_cubes.html - -()=>{ - - var container, stats; - var camera, scene, projector, renderer; - - var mouse = { x: 0, y: 0 }, INTERSECTED; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - var info = document.createElement( 'div' ); - info.style.position = 'absolute'; - info.style.top = '10px'; - info.style.width = '100%'; - info.style.textAlign = 'center'; - info.innerHTML = 'three.js webgl - interactive cubes'; - container.appendChild( info ); - - camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.set( 0, 300, 500 ); - - scene = new THREE.Scene(); - - var light = new THREE.DirectionalLight( 0xffffff, 2 ); - light.position.set( 1, 1, 1 ).normalize(); - scene.add( light ); - - var light = new THREE.DirectionalLight( 0xffffff ); - light.position.set( -1, -1, -1 ).normalize(); - scene.add( light ); - - var geometry = new THREE.CubeGeometry( 20, 20, 20 ); - - for ( var i = 0; i < 2000; i ++ ) { - - var object = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: Math.random() * 0xffffff } ) ); - - object.position.x = Math.random() * 800 - 400; - object.position.y = Math.random() * 800 - 400; - object.position.z = Math.random() * 800 - 400; - - object.rotation.x = Math.random() * 2 * Math.PI; - object.rotation.y = Math.random() * 2 * Math.PI; - object.rotation.z = Math.random() * 2 * Math.PI; - - object.scale.x = Math.random() + 0.5; - object.scale.y = Math.random() + 0.5; - object.scale.z = Math.random() + 0.5; - - scene.add( object ); - - } - - projector = new THREE.Projector(); - - renderer = new THREE.WebGLRenderer(); - renderer.sortObjects = false; - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild(renderer.domElement); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onDocumentMouseMove( event ) { - - event.preventDefault(); - - mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; - mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - var radius = 100; - var theta = 0; - - function render() { - - theta += 0.1; - - camera.position.x = radius * Math.sin( THREE.Math.degToRad( theta ) ); - camera.position.y = radius * Math.sin( THREE.Math.degToRad( theta ) ); - camera.position.z = radius * Math.cos( THREE.Math.degToRad( theta ) ); - - camera.lookAt( scene.position ); - - // find intersections - - var vector = new THREE.Vector3( mouse.x, mouse.y, 1 ); - projector.unprojectVector( vector, camera ); - - var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() ); - - var intersects = raycaster.intersectObjects( scene.children ); - - if ( intersects.length > 0 ) { - - if ( INTERSECTED != intersects[ 0 ].object ) { - - if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex ); - - INTERSECTED = intersects[ 0 ].object; - INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex(); - INTERSECTED.material.emissive.setHex( 0xff0000 ); - - } - - } else { - - if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex ); - - INTERSECTED = null; - - } - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_interactive_cubes_gpu.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_interactive_draggablecubes.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_interactive_voxelpainter.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_kinect.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_lensflares.html - -()=>{ - - var container, stats; - - var camera, scene, renderer; - - var clock = new THREE.Clock(); - - var composer; - - var controls; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - // camera - - camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 15000 ); - camera.position.z = 250; - - controls = new THREE.FlyControls( camera ); - - controls.movementSpeed = 2500; - controls.domElement = container; - controls.rollSpeed = Math.PI / 6; - controls.autoForward = false; - controls.dragToLook = false - - // scene - - scene = new THREE.Scene(); - scene.fog = new THREE.Fog( 0x000000, 3500, 15000 ); - scene.fog.color.setHSL( 0.51, 0.6, 0.025 ); - - // world - - var s = 250; - - var cube = new THREE.CubeGeometry( s, s, s ); - var material = new THREE.MeshPhongMaterial( { ambient: 0x333333, color: 0xffffff, specular: 0xffffff, shininess: 50 } ); - - - for ( var i = 0; i < 3000; i ++ ) { - - var mesh = new THREE.Mesh( cube, material ); - - mesh.position.x = 8000 * ( 2.0 * Math.random() - 1.0 ); - mesh.position.y = 8000 * ( 2.0 * Math.random() - 1.0 ); - mesh.position.z = 8000 * ( 2.0 * Math.random() - 1.0 ); - - mesh.rotation.x = Math.random() * Math.PI; - mesh.rotation.y = Math.random() * Math.PI; - mesh.rotation.z = Math.random() * Math.PI; - - mesh.matrixAutoUpdate = false; - mesh.updateMatrix(); - - scene.add( mesh ); - - } - - - // lights - - var ambient = new THREE.AmbientLight( 0xffffff ); - ambient.color.setHSL( 0.1, 0.5, 0.3 ); - scene.add( ambient ); - - - var dirLight = new THREE.DirectionalLight( 0xffffff, 0.125 ); - dirLight.position.set( 0, -1, 0 ).normalize(); - scene.add( dirLight ); - - dirLight.color.setHSL( 0.1, 0.725, 0.9 ); - - // lens flares - - var textureFlare0 = THREE.ImageUtils.loadTexture( "textures/lensflare/lensflare0.png" ); - var textureFlare2 = THREE.ImageUtils.loadTexture( "textures/lensflare/lensflare2.png" ); - var textureFlare3 = THREE.ImageUtils.loadTexture( "textures/lensflare/lensflare3.png" ); - - addLight( 0.55, 0.825, 0.99, 5000, 0, -1000 ); - addLight( 0.08, 0.825, 0.99, 0, 0, -1000 ); - addLight( 0.995, 0.025, 0.99, 5000, 5000, -1000 ); - - function addLight( h, s, v, x, y, z ) { - - var light = new THREE.PointLight( 0xffffff, 1.5, 4500 ); - light.color.setHSL( h, s, v ); - light.position.set( x, y, z ); - scene.add( light ); - - var flareColor = new THREE.Color( 0xffffff ); - flareColor.setHSL( h, s - 0.5, v + 0.5 ); - - var lensFlare = new THREE.LensFlare( textureFlare0, 700, 0.0, THREE.AdditiveBlending, flareColor ); - - lensFlare.add( textureFlare2, 512, 0.0, THREE.AdditiveBlending ); - lensFlare.add( textureFlare2, 512, 0.0, THREE.AdditiveBlending ); - lensFlare.add( textureFlare2, 512, 0.0, THREE.AdditiveBlending ); - - lensFlare.add( textureFlare3, 60, 0.6, THREE.AdditiveBlending ); - lensFlare.add( textureFlare3, 70, 0.7, THREE.AdditiveBlending ); - lensFlare.add( textureFlare3, 120, 0.9, THREE.AdditiveBlending ); - lensFlare.add( textureFlare3, 70, 1.0, THREE.AdditiveBlending ); - - lensFlare.customUpdateCallback = lensFlareUpdateCallback; - lensFlare.position = light.position; - - scene.add( lensFlare ); - - } - - // renderer - - renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.setClearColor( scene.fog.color, 1 ); - - container.appendChild( renderer.domElement ); - - // - - renderer.gammaInput = true; - renderer.gammaOutput = true; - renderer.physicallyBasedShading = true; - - // stats - - stats = new Stats(); - container.appendChild( stats.domElement ); - - // events - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - // - - function lensFlareUpdateCallback( object ) { - - var f, fl = object.lensFlares.length; - var flare; - var vecX = -object.positionScreen.x * 2; - var vecY = -object.positionScreen.y * 2; - - - for( f = 0; f < fl; f++ ) { - - flare = object.lensFlares[ f ]; - - flare.x = object.positionScreen.x + vecX * flare.distance; - flare.y = object.positionScreen.y + vecY * flare.distance; - - flare.rotation = 0; - - } - - object.lensFlares[ 2 ].y += 0.025; - object.lensFlares[ 3 ].rotation = object.positionScreen.x * 0.5 + THREE.Math.degToRad( 45 ); - - } - - // - - function onWindowResize( event ) { - - renderer.setSize( window.innerWidth, window.innerHeight ); - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var delta = clock.getDelta(); - - controls.update( delta ); - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_lights_hemisphere.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var camera, scene, renderer, dirLight, hemiLight; - var morphs = []; - var stats; - - var clock = new THREE.Clock(); - - var morph: THREE.MorphAnimMesh; - - init(); - animate(); - - function init() { - - var container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 5000 ); - camera.position.set( 0, 0, 250 ); - - scene = new THREE.Scene(); - - scene.fog = new THREE.Fog( 0xffffff, 1, 5000 ); - scene.fog.color.setHSL( 0.6, 0, 1 ); - - /* - controls = new THREE.TrackballControls( camera ); - - controls.rotateSpeed = 1.0; - controls.zoomSpeed = 1.2; - controls.panSpeed = 0.8; - - controls.noZoom = false; - controls.noPan = false; - - controls.staticMoving = true; - controls.dynamicDampingFactor = 0.15; - */ - - // LIGHTS - - hemiLight = new THREE.HemisphereLight( 0xffffff, 0xffffff, 0.6 ); - hemiLight.color.setHSL( 0.6, 0.75, 1 ); - hemiLight.groundColor.setHSL( 0.095, 0.5, 1 ); - hemiLight.position.set( 0, 500, 0 ); - scene.add( hemiLight ); - - // - - dirLight = new THREE.DirectionalLight( 0xffffff, 1 ); - dirLight.color.setHSL( 0.1, 0.1, 1 ); - dirLight.position.set( -1, 1.75, 1 ); - dirLight.position.multiplyScalar( 50 ); - scene.add( dirLight ); - - dirLight.castShadow = true; - - dirLight.shadowMapWidth = 2048; - dirLight.shadowMapHeight = 2048; - - var d = 50; - - dirLight.shadowCameraLeft = -d; - dirLight.shadowCameraRight = d; - dirLight.shadowCameraTop = d; - dirLight.shadowCameraBottom = -d; - - dirLight.shadowCameraFar = 3500; - dirLight.shadowBias = -0.0001; - dirLight.shadowDarkness = 0.35; - //dirLight.shadowCameraVisible = true; - - // GROUND - - var groundGeo = new THREE.PlaneGeometry( 10000, 10000 ); - var groundMat = new THREE.MeshPhongMaterial( { ambient: 0xffffff, color: 0xffffff, specular: 0x050505 } ); - groundMat.color.setHSL( 0.095, 0.5, 1 ); - - var ground = new THREE.Mesh( groundGeo, groundMat ); - ground.rotation.x = -Math.PI/2; - ground.position.y = -33; - scene.add( ground ); - - ground.receiveShadow = true; - - // SKYDOME - - var vertexShader = document.getElementById( 'vertexShader' ).textContent; - var fragmentShader = document.getElementById( 'fragmentShader' ).textContent; - var uniforms = { - topColor: { type: "c", value: new THREE.Color( 0x0077ff ) }, - bottomColor: { type: "c", value: new THREE.Color( 0xffffff ) }, - offset: { type: "f", value: 33 }, - exponent: { type: "f", value: 0.6 } - } - uniforms.topColor.value.copy( hemiLight.color ); - - scene.fog.color.copy( uniforms.bottomColor.value ); - - var skyGeo = new THREE.SphereGeometry( 4000, 32, 15 ); - //TS bug: https://typescript.codeplex.com/workitem/2036 - //var skyMat = new THREE.ShaderMaterial( { vertexShader: vertexShader, fragmentShader: fragmentShader, uniforms: uniforms, side: THREE.BackSide } ); - var skyMat = new THREE.ShaderMaterial( { vertexShader: vertexShader, fragmentShader: fragmentShader, uniforms: uniforms, side: THREE.BackSide } ); - - var sky = new THREE.Mesh( skyGeo, skyMat ); - scene.add( sky ); - - // MODEL - - var loader = new THREE.JSONLoader(); - - loader.load( "models/animated/flamingo.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - geometry.computeMorphNormals(); - - var material = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0xffffff, shininess: 20, morphTargets: true, morphNormals: true, vertexColors: THREE.FaceColors, shading: THREE.FlatShading } ); - var meshAnim = new THREE.MorphAnimMesh( geometry, material ); - - meshAnim.duration = 1000; - - var s = 0.35; - meshAnim.scale.set( s, s, s ); - meshAnim.position.y = 15; - meshAnim.rotation.y = -1; - - meshAnim.castShadow = true; - meshAnim.receiveShadow = true; - - scene.add( meshAnim ); - morphs.push( meshAnim ); - - } ); - - // RENDERER - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - container.appendChild( renderer.domElement ); - - renderer.setClearColor( scene.fog.color, 1 ); - - renderer.gammaInput = true; - renderer.gammaOutput = true; - renderer.physicallyBasedShading = true; - - renderer.shadowMapEnabled = true; - renderer.shadowMapCullFace = THREE.CullFaceBack; - - // STATS - - stats = new Stats(); - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - document.addEventListener( 'keydown', onKeyDown, false ); - - } - - function morphColorsToFaceColors( geometry ) { - - if ( geometry.morphColors && geometry.morphColors.length ) { - - var colorMap = geometry.morphColors[ 0 ]; - - for ( var i = 0; i < colorMap.colors.length; i ++ ) { - - geometry.faces[ i ].color = colorMap.colors[ i ]; - - } - - } - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function onKeyDown ( event ) { - - switch ( event.keyCode ) { - - case 72: /*h*/ - - hemiLight.visible = !hemiLight.visible; - break; - - case 68: /*d*/ - - dirLight.visible = !dirLight.visible; - break; - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var delta = clock.getDelta(); - - //controls.update(); - - for ( var i = 0; i < morphs.length; i ++ ) { - - morph = morphs[ i ]; - morph.updateAnimation( 1000 * delta ); - - } - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_lights_pointlights.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_lights_pointlights2.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_lines_colors.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var effectFXAA; - - var mouseX = 0, mouseY = 0, - - windowHalfX = window.innerWidth / 2, - windowHalfY = window.innerHeight / 2, - - camera, scene, renderer, material, composer; - - var stats: any; - - init(); - animate(); - - function init() { - - var i, container; - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 33, window.innerWidth / window.innerHeight, 1, 10000 ); - camera.position.z = 700; - - scene = new THREE.Scene(); - - renderer = new THREE.WebGLRenderer( { clearColor: 0x000000, clearAlpha: 1, antialias: false } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.autoClear = false; - - container.appendChild( renderer.domElement ); - - var geometry = new THREE.Geometry(), - geometry2 = new THREE.Geometry(), - geometry3 = new THREE.Geometry(), - points = hilbert3D( new THREE.Vector3( 0,0,0 ), 200.0, 2, 0, 1, 2, 3, 4, 5, 6, 7 ), - colors = [], colors2 = [], colors3 = []; - - for ( i = 0; i < points.length; i ++ ) { - - geometry.vertices.push( points[ i ] ); - - colors[ i ] = new THREE.Color( 0xffffff ); - colors[ i ].setHSV( 0.6, ( 200 + points[ i ].x ) / 400, 1.0 ); - - colors2[ i ] = new THREE.Color( 0xffffff ); - colors2[ i ].setHSV( 0.3, 1.0, ( 200 + points[ i ].x ) / 400 ); - - colors3[ i ] = new THREE.Color( 0xffffff ); - colors3[ i ].setHSV( i / points.length, 1.0, 1.0 ); - - } - - geometry2.vertices = geometry3.vertices = geometry.vertices; - - geometry.colors = colors; - geometry2.colors = colors2; - geometry3.colors = colors3; - - // lines - - material = new THREE.LineBasicMaterial( { color: 0xffffff, opacity: 1, linewidth: 3, vertexColors: THREE.VertexColors } ); - - var line, p, scale = 0.3, d = 225; - var parameters = [ - [ material, scale*1.5, [-d,0,0], geometry ], - [ material, scale*1.5, [0,0,0], geometry2 ], - [ material, scale*1.5, [d,0,0], geometry3 ] - ]; - - for ( i = 0; i < parameters.length; ++i ) { - - p = parameters[ i ]; - line = new THREE.Line( p[ 3 ], p[ 0 ] ); - line.scale.x = line.scale.y = line.scale.z = p[ 1 ]; - line.position.x = p[ 2 ][ 0 ]; - line.position.y = p[ 2 ][ 1 ]; - line.position.z = p[ 2 ][ 2 ]; - scene.add( line ); - - } - - // - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - //container.appendChild( stats.domElement ); - - // - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - var renderModel = new THREE.RenderPass( scene, camera ); - var effectBloom = new THREE.BloomPass( 1.3 ); - var effectCopy = new THREE.ShaderPass( THREE.CopyShader ); - - effectFXAA = new THREE.ShaderPass( THREE.FXAAShader ); - - var width = window.innerWidth || 2; - var height = window.innerHeight || 2; - - effectFXAA.uniforms[ 'resolution' ].value.set( 1 / width, 1 / height ); - - effectCopy.renderToScreen = true; - - composer = new THREE.EffectComposer( renderer ); - - composer.addPass( renderModel ); - composer.addPass( effectFXAA ); - composer.addPass( effectBloom ); - composer.addPass( effectCopy ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - effectFXAA.uniforms[ 'resolution' ].value.set( 1 / window.innerWidth, 1 / window.innerHeight ); - - composer.reset(); - - } - - // port of Processing Java code by Thomas Diewald - // http://www.openprocessing.org/visuals/?visualID=15599 - - function hilbert3D( center, side, iterations, v0, v1, v2, v3, v4, v5, v6, v7 ) { - - var half = side / 2, - - vec_s = [ - - new THREE.Vector3( center.x - half, center.y + half, center.z - half ), - new THREE.Vector3( center.x - half, center.y + half, center.z + half ), - new THREE.Vector3( center.x - half, center.y - half, center.z + half ), - new THREE.Vector3( center.x - half, center.y - half, center.z - half ), - new THREE.Vector3( center.x + half, center.y - half, center.z - half ), - new THREE.Vector3( center.x + half, center.y - half, center.z + half ), - new THREE.Vector3( center.x + half, center.y + half, center.z + half ), - new THREE.Vector3( center.x + half, center.y + half, center.z - half ) - - ], - - vec = [ vec_s[ v0 ], vec_s[ v1 ], vec_s[ v2 ], vec_s[ v3 ], vec_s[ v4 ], vec_s[ v5 ], vec_s[ v6 ], vec_s[ v7 ] ]; - - if( --iterations >= 0 ) { - - var tmp = []; - - Array.prototype.push.apply( tmp, hilbert3D ( vec[ 0 ], half, iterations, v0, v3, v4, v7, v6, v5, v2, v1 ) ); - Array.prototype.push.apply( tmp, hilbert3D ( vec[ 1 ], half, iterations, v0, v7, v6, v1, v2, v5, v4, v3 ) ); - Array.prototype.push.apply( tmp, hilbert3D ( vec[ 2 ], half, iterations, v0, v7, v6, v1, v2, v5, v4, v3 ) ); - Array.prototype.push.apply( tmp, hilbert3D ( vec[ 3 ], half, iterations, v2, v3, v0, v1, v6, v7, v4, v5 ) ); - Array.prototype.push.apply( tmp, hilbert3D ( vec[ 4 ], half, iterations, v2, v3, v0, v1, v6, v7, v4, v5 ) ); - Array.prototype.push.apply( tmp, hilbert3D ( vec[ 5 ], half, iterations, v4, v3, v2, v5, v6, v1, v0, v7 ) ); - Array.prototype.push.apply( tmp, hilbert3D ( vec[ 6 ], half, iterations, v4, v3, v2, v5, v6, v1, v0, v7 ) ); - Array.prototype.push.apply( tmp, hilbert3D ( vec[ 7 ], half, iterations, v6, v5, v2, v1, v0, v3, v4, v7 ) ); - - return tmp; - - } - - return vec; - } - - // - - function onDocumentMouseMove( event ) { - - mouseX = event.clientX - windowHalfX; - mouseY = event.clientY - windowHalfY; - - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length > 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length == 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - render(); - - stats.update(); - - } - - function render() { - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y += ( - mouseY + 200 - camera.position.y ) * .05; - - camera.lookAt( scene.position ); - - var time = Date.now() * 0.0005; - - for ( var i = 0; i < scene.children.length; i ++ ) { - - var object = scene.children[ i ]; - if ( object instanceof THREE.Line ) object.rotation.y = time * ( i % 2 ? 1 : -1 ); - - } - - renderer.clear(); - composer.render(); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_lines_cubes.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_lines_dashed.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_lines_sphere.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_lines_splines.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_loader_collada.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_loader_collada_keyframe.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_loader_ctm.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_loader_ctm_materials.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_loader_json_blender.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, scene, renderer, objects; - var particleLight, pointLight; - var dae, skin; - - var clock = new THREE.Clock(); - var morphs = []; - var morph: THREE.MorphAnimMesh; - - // Collada model - - var loader = new THREE.ColladaLoader(); - loader.options.convertUpAxis = true; - loader.load( 'models/collada/monster/monster.dae', function ( collada ) { - - dae = collada.scene; - skin = collada.skins[ 0 ]; - - dae.scale.x = dae.scale.y = dae.scale.z = 0.002; - dae.position.x = -1; - dae.updateMatrix(); - - init(); - animate(); - - } ); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 2000 ); - camera.position.set( 2, 4, 5 ); - - scene = new THREE.Scene(); - scene.fog = new THREE.FogExp2( 0x000000, 0.035 ); - - // Add Blender exported Collada model - - var loader = new THREE.JSONLoader(); - loader.load( 'models/animated/monster/monster.js', function ( geometry, materials ) { - - // adjust color a bit - - var material = materials[ 0 ]; - material.morphTargets = true; - material.color.setHex( 0xffaaaa ); - material.ambient.setHex( 0x222222 ); - - var faceMaterial = new THREE.MeshFaceMaterial( materials ); - - for ( var i = 0; i < 729; i ++ ) { - - // random placement in a grid - - var x = ( ( i % 27 ) - 13.5 ) * 2 + THREE.Math.randFloatSpread( 1 ); - var z = ( Math.floor( i / 27 ) - 13.5 ) * 2 + THREE.Math.randFloatSpread( 1 ); - - // leave space for big monster - - if ( Math.abs( x ) < 2 && Math.abs( z ) < 2 ) continue; - - morph = new THREE.MorphAnimMesh( geometry, faceMaterial ); - - // one second duration - - morph.duration = 1000; - - // random animation offset - - morph.time = 1000 * Math.random(); - - var s = THREE.Math.randFloat( 0.00075, 0.001 ); - morph.scale.set( s, s, s ); - - morph.position.set( x, 0, z ); - morph.rotation.y = THREE.Math.randFloat( -0.25, 0.25 ); - - morph.matrixAutoUpdate = false; - morph.updateMatrix(); - - scene.add( morph ); - - morphs.push( morph ); - - } - - } ); - - - // Add the COLLADA - - scene.add( dae ); - - // Lights - - scene.add( new THREE.AmbientLight( 0xcccccc ) ); - - pointLight = new THREE.PointLight( 0xff4400, 5, 30 ); - pointLight.position.set( 5, 0, 0 ); - scene.add( pointLight ); - - // Renderer - - renderer = new THREE.WebGLRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - // Stats - - stats = new Stats(); - container.appendChild( stats.domElement ); - - // Events - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - // - - function onWindowResize( event ) { - - renderer.setSize( window.innerWidth, window.innerHeight ); - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - } - - // - - var t = 0; - function animate() { - - requestAnimationFrame( animate ); - - // animate Collada model - - if ( t > 30 ) t = 0; - - if ( skin ) { - - // guess this can be done smarter... - - // (Indeed, there are way more frames than needed and interpolation is not used at all - // could be something like - one morph per each skinning pose keyframe, or even less, - // animation could be resampled, morphing interpolation handles sparse keyframes quite well. - // Simple animation cycles like this look ok with 10-15 frames instead of 100 ;) - - for ( var i = 0; i < skin.morphTargetInfluences.length; i++ ) { - - skin.morphTargetInfluences[ i ] = 0; - - } - - skin.morphTargetInfluences[ Math.floor( t ) ] = 1; - - t += 0.5; - - } - - // animate morphs - - var delta = clock.getDelta(); - - if ( morphs.length ) { - - for ( var i = 0; i < morphs.length; i ++ ) - morphs[ i ].updateAnimation( 1000 * delta ); - - - } - - render(); - stats.update(); - - } - - function render() { - - var timer = Date.now() * 0.0005; - - camera.position.x = Math.cos( timer ) * 10; - camera.position.y = 4; - camera.position.z = Math.sin( timer ) * 10; - - camera.lookAt( scene.position ); - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_loader_json_objconverter.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_loader_obj.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_loader_obj_mtl.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_loader_scene.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var SCREEN_WIDTH = window.innerWidth; - var SCREEN_HEIGHT = window.innerHeight; - - var container,stats; - - var camera, scene, loaded; - var renderer; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var rotatingObjects = []; - var morphAnimatedObjects = []; - - var clock = new THREE.Clock(); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - init(); - animate(); - - function $( id ) { - - return document.getElementById( id ); - - } - - function handle_update( result, pieces ) { - - refreshSceneView( result ); - //renderer.initWebGLObjects( result.scene ); - - var m, material, count = 0; - - for ( m in result.materials ) { - - material = result.materials[ m ]; - if ( ! ( material instanceof THREE.MeshFaceMaterial || material instanceof THREE.ShaderMaterial || material.morphTargets ) ) { - - if( !material.program ) { - - renderer.initMaterial( material, result.scene.__lights, result.scene.fog ); - - count += 1; - - if( count > pieces ) { - - //console.log("xxxxxxxxx"); - break; - - } - - } - - } - - } - - } - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - var loadScene = createLoadScene(); - - camera = loadScene.camera; - scene = loadScene.scene; - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - renderer.domElement.style.position = "relative"; - container.appendChild( renderer.domElement ); - - renderer.gammaInput = true; - renderer.gammaOutput = true; - renderer.physicallyBasedShading = true; - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.right = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - $( "start" ).addEventListener( 'click', onStartClick, false ); - - var callbackProgress = function( progress, result ) { - - var bar = 250, - total = progress.totalModels + progress.totalTextures, - loaded = progress.loadedModels + progress.loadedTextures; - - if ( total ) - bar = Math.floor( bar * loaded / total ); - - $( "bar" ).style.width = bar + "px"; - - var count = 0; - for ( var m in result.materials ) count++; - - handle_update( result, Math.floor( count/total ) ); - - } - - var callbackSync = function( result ) { - - /* - - // uncomment to see progressive scene loading - - scene = result.scene; - camera = result.currentCamera; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - */ - - //handle_update( result, 1 ); - - } - - var callbackFinished = function ( result ) { - - loaded = result; - - $( "message" ).style.display = "none"; - $( "progressbar" ).style.display = "none"; - $( "start" ).style.display = "block"; - $( "start" ).className = "enabled"; - - handle_update( result, 1 ); - - result.scene.traverse( function ( object ) { - - if ( object.properties.rotating === true ) { - - rotatingObjects.push( object ); - - } - - if ( object instanceof THREE.MorphAnimMesh ) { - - morphAnimatedObjects.push( object ); - - } - - if ( object instanceof THREE.SkinnedMesh ) { - - if ( object.geometry.animation ) { - - THREE.AnimationHandler.add( object.geometry.animation ); - - var animation = new THREE.Animation( object, object.geometry.animation.name ); - animation.interpolationType = THREE.AnimationHandler.LINEAR; - - animation.play(); - - } - - } - - } ); - - } - - $( "progress" ).style.display = "block"; - - var loader = new THREE.SceneLoader(); - - loader.addGeometryHandler( "binary", THREE.BinaryLoader ); - loader.addGeometryHandler( "ctm", THREE.CTMLoader ); - loader.addGeometryHandler( "vtk", THREE.VTKLoader ); - loader.addGeometryHandler( "stl", THREE.STLLoader ); - - loader.addHierarchyHandler( "obj", THREE.OBJLoader ); - loader.addHierarchyHandler( "dae", THREE.ColladaLoader ); - loader.addHierarchyHandler( "utf8", THREE.UTF8Loader ); - - loader.callbackSync = callbackSync; - loader.callbackProgress = callbackProgress; - - loader.load( "scenes/test_scene.js", callbackFinished ); - - $( "plus_exp" ).addEventListener( 'click', createToggle( "exp" ), false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function setButtonActive( id ) { - - $( "start" ).style.backgroundColor = "green"; - - } - - function onStartClick() { - - $( "progress" ).style.display = "none"; - - camera = loaded.currentCamera; - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - scene = loaded.scene; - - } - - function onDocumentMouseMove( event ) { - - mouseX = ( event.clientX - windowHalfX ); - mouseY = ( event.clientY - windowHalfY ); - - } - - function createLoadScene() { - - var result = { - - scene: new THREE.Scene(), - camera: new THREE.PerspectiveCamera( 65, window.innerWidth / window.innerHeight, 1, 1000 ) - - }; - - result.camera.position.z = 100; - result.scene.add( result.camera ); - - var object, geometry, material, light, count = 500, range = 200; - - material = new THREE.MeshLambertMaterial( { color:0xffffff } ); - geometry = new THREE.CubeGeometry( 5, 5, 5 ); - - for( var i = 0; i < count; i++ ) { - - object = new THREE.Mesh( geometry, material ); - - object.position.x = ( Math.random() - 0.5 ) * range; - object.position.y = ( Math.random() - 0.5 ) * range; - object.position.z = ( Math.random() - 0.5 ) * range; - - object.rotation.x = Math.random() * 6; - object.rotation.y = Math.random() * 6; - object.rotation.z = Math.random() * 6; - - object.matrixAutoUpdate = false; - object.updateMatrix(); - - result.scene.add( object ); - - } - - result.scene.matrixAutoUpdate = false; - - light = new THREE.PointLight( 0xffffff ); - result.scene.add( light ); - - light = new THREE.DirectionalLight( 0x111111 ); - light.position.x = 1; - result.scene.add( light ); - - return result; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var delta = clock.getDelta(); - - camera.position.x += ( mouseX - camera.position.x ) * .001; - camera.position.y += ( - mouseY - camera.position.y ) * .001; - - camera.lookAt( scene.position ); - - // update skinning - - THREE.AnimationHandler.update( delta * 0.75 ); - - for ( var i = 0; i < rotatingObjects.length; i ++ ) { - - var object = rotatingObjects[ i ]; - - if ( object.properties.rotateX ) object.rotation.x += 1 * delta; - if ( object.properties.rotateY ) object.rotation.y += 0.5 * delta; - - } - - for ( var i = 0; i < morphAnimatedObjects.length; i ++ ) { - - var object = morphAnimatedObjects[ i ]; - - object.updateAnimation( 1000 * delta ); - - } - - renderer.render( scene, camera ); - - } - - // Scene explorer user interface - - function toggle( id ) { - - var scn = $( "section_" + id ).style, - btn = $( "plus_" + id ); - - if ( scn.display == "block" ) { - - scn.display = "none"; - btn.innerHTML = "[+]"; - - } - else { - - scn.display = "block"; - btn.innerHTML = "[-]"; - - } - - } - - function createToggle( label ) { return function() { toggle( label ) } }; - - function refreshSceneView( result ) { - - $( "section_exp" ).innerHTML = generateSceneView( result ); - - var config = [ "obj", "geo", "mat", "tex", "lit", "cam" ]; - - for ( var i = 0; i < config.length; i++ ) - $( "plus_" + config[i] ).addEventListener( 'click', createToggle( config[i] ), false ); - - } - - function generateSection( label, id, objects ) { - - var html = ""; - - html += "

    [+] " + label + "

    "; - html += "
    "; - - for( var o in objects ) { - - html += o + "
    "; - - } - html += "
    "; - - return html; - - } - - function generateSceneView( result ) { - - var config = [ - [ "Objects", "obj", result.objects ], - [ "Geometries", "geo", result.geometries ], - [ "Materials", "mat", result.materials ], - [ "Textures", "tex", result.textures ], - [ "Lights", "lit", result.lights ], - [ "Cameras", "cam", result.cameras ] - ]; - - var html = ""; - - for ( var i = 0; i < config.length; i++ ) - html += generateSection( config[i][0], config[i][1], config[i][2] ); - - return html; - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_loader_scene_blender.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var SCREEN_WIDTH = window.innerWidth; - var SCREEN_HEIGHT = window.innerHeight; - - var container,stats; - - var camera, scene: THREE.Scene, loaded; - var renderer; - - var mesh, zmesh, geometry; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - init(); - animate(); - - function $( id ) { - - return document.getElementById( id ); - - } - - function handle_update( result, pieces ) { - - refreshSceneView( result ); - //renderer.initWebGLObjects( result.scene ); - - var m, material, count = 0; - - for ( m in result.materials ) { - - material = result.materials[ m ]; - if ( ! ( material instanceof THREE.MeshFaceMaterial ) ) { - - if( !material.program ) { - - console.log(m); - renderer.initMaterial( material, result.scene.__lights, result.scene.fog ); - - count += 1; - if( count > pieces ) { - - //console.log("xxxxxxxxx"); - break; - - } - - } - - } - - } - - } - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - var loadScene = createLoadScene(); - - camera = loadScene.camera; - scene = loadScene.scene; - - renderer = new THREE.WebGLRenderer(); - renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - renderer.domElement.style.position = "relative"; - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.right = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - $( "start" ).addEventListener( 'click', onStartClick, false ); - - var callbackProgress = function( progress, result ) { - - var bar = 250, - total = progress.total_models + progress.total_textures, - loaded = progress.loaded_models + progress.loaded_textures; - - if ( total ) - bar = Math.floor( bar * loaded / total ); - - $( "bar" ).style.width = bar + "px"; - - var count = 0; - for ( var m in result.materials ) count++; - - handle_update( result, Math.floor( count/total ) ); - - } - - var callbackFinished = function( result ) { - - loaded = result; - - $( "message" ).style.display = "none"; - $( "progressbar" ).style.display = "none"; - $( "start" ).style.display = "block"; - $( "start" ).className = "enabled"; - - handle_update( result, 1 ); - - } - - $( "progress" ).style.display = "block"; - - var loader = new THREE.SceneLoader(); - loader.callbackProgress = callbackProgress; - - loader.load( "obj/blenderscene/scene.js", callbackFinished ); - - $( "plus_exp" ).addEventListener( 'click', createToggle( "exp" ), false ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function setButtonActive( id ) { - - $( "start" ).style.backgroundColor = "green"; - - } - - function onStartClick() { - - $( "progress" ).style.display = "none"; - - camera = loaded.currentCamera; - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - scene = loaded.scene; - - } - - function onDocumentMouseMove(event) { - - mouseX = ( event.clientX - windowHalfX ); - mouseY = ( event.clientY - windowHalfY ); - - } - - function createLoadScene() { - - var result = { - - scene: new THREE.Scene(), - camera: new THREE.PerspectiveCamera( 65, window.innerWidth / window.innerHeight, 1, 1000 ) - - }; - - result.camera.position.z = 100; - - var object, geometry, material, light, count = 500, range = 200; - - material = new THREE.MeshLambertMaterial( { color:0xffffff } ); - geometry = new THREE.CubeGeometry( 5, 5, 5 ); - - for( var i = 0; i < count; i++ ) { - - object = new THREE.Mesh( geometry, material ); - - object.position.x = ( Math.random() - 0.5 ) * range; - object.position.y = ( Math.random() - 0.5 ) * range; - object.position.z = ( Math.random() - 0.5 ) * range; - - object.rotation.x = Math.random() * 6; - object.rotation.y = Math.random() * 6; - object.rotation.z = Math.random() * 6; - - object.matrixAutoUpdate = false; - object.updateMatrix(); - - result.scene.add( object ); - - } - - result.scene.matrixAutoUpdate = false; - - light = new THREE.PointLight( 0xffffff ); - result.scene.add( light ); - - light = new THREE.DirectionalLight( 0x111111 ); - light.position.x = 1; - result.scene.add( light ); - - return result; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - camera.position.x += ( mouseX - camera.position.x ) * .001; - camera.position.y += ( - mouseY - camera.position.y ) * .001; - - camera.lookAt( scene.position ); - - renderer.render( scene, camera ); - - } - - // Scene explorer user interface - - function toggle( id ) { - - var scn = $( "section_" + id ).style, - btn = $( "plus_" + id ); - - if ( scn.display == "block" ) { - - scn.display = "none"; - btn.innerHTML = "[+]"; - - } - else { - - scn.display = "block"; - btn.innerHTML = "[-]"; - - } - - } - - function createToggle( label ) { return function() { toggle( label ) } }; - - function refreshSceneView( result ) { - - $( "section_exp" ).innerHTML = generateSceneView( result ); - - var config = [ "obj", "geo", "mat", "tex", "lit", "cam" ]; - - for ( var i = 0; i < config.length; i++ ) - $( "plus_" + config[i] ).addEventListener( 'click', createToggle( config[i] ), false ); - - } - - function generateSection( label, id, objects ) { - - var html = ""; - - html += "

    [+] " + label + "

    "; - html += "
    "; - - for( var o in objects ) { - - html += o + "
    "; - - } - html += "
    "; - - return html; - - } - - function generateSceneView( result ) { - - var config = [ - [ "Objects", "obj", result.objects ], - [ "Geometries", "geo", result.geometries ], - [ "Materials", "mat", result.materials ], - [ "Textures", "tex", result.textures ], - [ "Lights", "lit", result.lights ], - [ "Cameras", "cam", result.cameras ] - ]; - - var html = ""; - - for ( var i = 0; i < config.length; i++ ) - html += generateSection( config[i][0], config[i][1], config[i][2] ); - - return html; - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_loader_stl.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_loader_utf8.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_loader_vtk.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_lod.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_marching_cubes.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, scene, renderer, objects; - var particleLight, pointLight; - - var materials = []; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 ); - camera.position.set( 0, 200, 800 ); - - scene = new THREE.Scene(); - - // Grid - - var line_material = new THREE.LineBasicMaterial( { color: 0x303030 } ), - geometry = new THREE.Geometry(), - floor = -75, step = 25; - - for ( var i = 0; i <= 40; i ++ ) { - - geometry.vertices.push( new THREE.Vector3( - 500, floor, i * step - 500 ) ); - geometry.vertices.push( new THREE.Vector3( 500, floor, i * step - 500 ) ); - - geometry.vertices.push( new THREE.Vector3( i * step - 500, floor, -500 ) ); - geometry.vertices.push( new THREE.Vector3( i * step - 500, floor, 500 ) ); - - } - - var line = new THREE.Line( geometry, line_material, THREE.LinePieces ); - scene.add( line ); - - // Materials - - var texture = new THREE.Texture( generateTexture() ); - texture.needsUpdate = true; - - materials.push( new THREE.MeshLambertMaterial( { map: texture, transparent: true } ) ); - materials.push( new THREE.MeshLambertMaterial( { color: 0xdddddd, shading: THREE.FlatShading } ) ); - materials.push( new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0xdddddd, specular: 0x009900, shininess: 30, shading: THREE.FlatShading } ) ); - materials.push( new THREE.MeshNormalMaterial( ) ); - materials.push( new THREE.MeshBasicMaterial( { color: 0xffaa00, transparent: true, blending: THREE.AdditiveBlending } ) ); - //materials.push( new THREE.MeshBasicMaterial( { color: 0xff0000, blending: THREE.SubtractiveBlending } ) ); - - materials.push( new THREE.MeshLambertMaterial( { color: 0xdddddd, shading: THREE.SmoothShading } ) ); - materials.push( new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0xdddddd, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, map: texture, transparent: true } ) ); - materials.push( new THREE.MeshNormalMaterial( { shading: THREE.SmoothShading } ) ); - materials.push( new THREE.MeshBasicMaterial( { color: 0xffaa00, wireframe: true } ) ); - - materials.push( new THREE.MeshDepthMaterial() ); - - materials.push( new THREE.MeshLambertMaterial( { color: 0x666666, emissive: 0xff0000, ambient: 0x000000, shading: THREE.SmoothShading } ) ); - materials.push( new THREE.MeshPhongMaterial( { color: 0x000000, specular: 0x666666, emissive: 0xff0000, ambient: 0x000000, shininess: 10, shading: THREE.SmoothShading, opacity: 0.9, transparent: true } ) ); - - materials.push( new THREE.MeshBasicMaterial( { map: texture, transparent: true } ) ); - - // Spheres geometry - - var geometry_smooth = new THREE.SphereGeometry( 70, 32, 16 ); - var geometry_flat = new THREE.SphereGeometry( 70, 32, 16 ); - var geometry_pieces = new THREE.SphereGeometry( 70, 32, 16 ); // Extra geometry to be broken down for MeshFaceMaterial - - for ( var i = 0, l = geometry_pieces.faces.length; i < l; i ++ ) { - - var face = geometry_pieces.faces[ i ]; - face.materialIndex = Math.floor( Math.random() * materials.length ); - - } - - geometry_pieces["materials"] = materials; - - materials.push( new THREE.MeshFaceMaterial( materials ) ); - - objects = []; - - var sphere, material; - - for ( var i = 0, l = materials.length; i < l; i ++ ) { - - material = materials[ i ]; - - geometry = material instanceof THREE.MeshFaceMaterial ? geometry_pieces : - ( material.shading == THREE.FlatShading ? geometry_flat : geometry_smooth ); - - sphere = new THREE.Mesh( geometry, material ); - - sphere.position.x = ( i % 4 ) * 200 - 400; - sphere.position.z = Math.floor( i / 4 ) * 200 - 200; - - sphere.rotation.x = Math.random() * 200 - 100; - sphere.rotation.y = Math.random() * 200 - 100; - sphere.rotation.z = Math.random() * 200 - 100; - - objects.push( sphere ); - - scene.add( sphere ); - - } - - particleLight = new THREE.Mesh( new THREE.SphereGeometry( 4, 8, 8 ), new THREE.MeshBasicMaterial( { color: 0xffffff } ) ); - scene.add( particleLight ); - - // Lights - - scene.add( new THREE.AmbientLight( 0x111111 ) ); - - var directionalLight = new THREE.DirectionalLight( /*Math.random() * */ 0xffffff, 0.125 ); - - directionalLight.position.x = Math.random() - 0.5; - directionalLight.position.y = Math.random() - 0.5; - directionalLight.position.z = Math.random() - 0.5; - - directionalLight.position.normalize(); - - scene.add( directionalLight ); - - pointLight = new THREE.PointLight( 0xffffff, 1 ); - scene.add( pointLight ); - - // - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - - container.appendChild( renderer.domElement ); - - // - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function generateTexture() { - - var canvas = document.createElement( 'canvas' ); - canvas.width = 256; - canvas.height = 256; - - var context = canvas.getContext( '2d' ); - var image = context.getImageData( 0, 0, 256, 256 ); - - var x = 0, y = 0; - - for ( var i = 0, j = 0, l = image.data.length; i < l; i += 4, j ++ ) { - - x = j % 256; - y = x == 0 ? y + 1 : y; - - image.data[ i ] = 255; - image.data[ i + 1 ] = 255; - image.data[ i + 2 ] = 255; - image.data[ i + 3 ] = Math.floor( x ^ y ); - - } - - context.putImageData( image, 0, 0 ); - - return canvas; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var timer = 0.0001 * Date.now(); - - camera.position.x = Math.cos( timer ) * 1000; - camera.position.z = Math.sin( timer ) * 1000; - - camera.lookAt( scene.position ); - - for ( var i = 0, l = objects.length; i < l; i ++ ) { - - var object = objects[ i ]; - - object.rotation.x += 0.01; - object.rotation.y += 0.005; - - } - - materials[ materials.length - 3 ].emissive.setHSV( 0.54, 1, 0.7 * ( 0.5 + 0.5 * Math.sin( 35 * timer ) ) ); - materials[ materials.length - 4 ].emissive.setHSV( 0.04, 1, 0.7 * ( 0.5 + 0.5 * Math.cos( 35 * timer ) ) ); - - particleLight.position.x = Math.sin( timer * 7 ) * 300; - particleLight.position.y = Math.cos( timer * 5 ) * 400; - particleLight.position.z = Math.cos( timer * 3 ) * 300; - - pointLight.position.x = particleLight.position.x; - pointLight.position.y = particleLight.position.y; - pointLight.position.z = particleLight.position.z; - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials2.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, scene, renderer, objects; - var particleLight, pointLight; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 2000 ); - camera.position.set( 0, 200, 0 ); - - scene = new THREE.Scene(); - - // Materials - - var imgTexture2 = THREE.ImageUtils.loadTexture( "textures/planets/moon_1024.jpg" ); - imgTexture2.wrapS = imgTexture2.wrapT = THREE.RepeatWrapping; - imgTexture2.anisotropy = 16; - - var imgTexture = THREE.ImageUtils.loadTexture( "textures/lava/lavatile.jpg" ); - imgTexture.repeat.set( 4, 2 ); - imgTexture.wrapS = imgTexture.wrapT = THREE.RepeatWrapping; - imgTexture.anisotropy = 16; - - var shininess = 50, specular = 0x333333, bumpScale = 1, shading = THREE.SmoothShading; - - var materials = []; - - materials.push( new THREE.MeshPhongMaterial( { map: imgTexture, bumpMap: imgTexture, bumpScale: bumpScale, color: 0xffffff, ambient: 0x777777, specular: specular, shininess: shininess, shading: shading } ) ); - materials.push( new THREE.MeshPhongMaterial( { map: imgTexture, bumpMap: imgTexture, bumpScale: bumpScale, color: 0x00ff00, ambient: 0x777777, specular: specular, shininess: shininess, shading: shading } ) ); - materials.push( new THREE.MeshPhongMaterial( { map: imgTexture, bumpMap: imgTexture, bumpScale: bumpScale, color: 0x00ff00, ambient: 0x007700, specular: specular, shininess: shininess, shading: shading } ) ); - materials.push( new THREE.MeshPhongMaterial( { map: imgTexture, bumpMap: imgTexture, bumpScale: bumpScale, color: 0x000000, ambient: 0x00ff00, specular: specular, shininess: shininess, shading: shading } ) ); - - materials.push( new THREE.MeshLambertMaterial( { map: imgTexture, color: 0xffffff, ambient: 0x777777, shading: shading } ) ); - materials.push( new THREE.MeshLambertMaterial( { map: imgTexture, color: 0xff0000, ambient: 0x777777, shading: shading } ) ); - materials.push( new THREE.MeshLambertMaterial( { map: imgTexture, color: 0xff0000, ambient: 0x770000, shading: shading } ) ); - materials.push( new THREE.MeshLambertMaterial( { map: imgTexture, color: 0x000000, ambient: 0xff0000, shading: shading } ) ); - - shininess = 15; - - materials.push( new THREE.MeshPhongMaterial( { map: imgTexture2, bumpMap: imgTexture2, bumpScale: bumpScale, color: 0x000000, ambient: 0x000000, specular: 0xffaa00, shininess: shininess, metal: true, shading: shading } ) ); - materials.push( new THREE.MeshPhongMaterial( { map: imgTexture2, bumpMap: imgTexture2, bumpScale: bumpScale, color: 0x000000, ambient: 0x000000, specular: 0xaaff00, shininess: shininess, metal: true, shading: shading } ) ); - materials.push( new THREE.MeshPhongMaterial( { map: imgTexture2, bumpMap: imgTexture2, bumpScale: bumpScale, color: 0x000000, ambient: 0x000000, specular: 0x00ffaa, shininess: shininess, metal: true, shading: shading } ) ); - materials.push( new THREE.MeshPhongMaterial( { map: imgTexture2, bumpMap: imgTexture2, bumpScale: bumpScale, color: 0x000000, ambient: 0x000000, specular: 0x00aaff, shininess: shininess, metal: true, shading: shading } ) ); - - // Spheres geometry - - var geometry_smooth = new THREE.SphereGeometry( 70, 32, 16 ); - var geometry_flat = new THREE.SphereGeometry( 70, 32, 16 ); - - objects = []; - - var sphere, geometry, material; - - for ( var i = 0, l = materials.length; i < l; i ++ ) { - - material = materials[ i ]; - - geometry = material.shading == THREE.FlatShading ? geometry_flat : geometry_smooth; - - sphere = new THREE.Mesh( geometry, material ); - - sphere.position.x = ( i % 4 ) * 200 - 200; - sphere.position.z = Math.floor( i / 4 ) * 200 - 200; - - objects.push( sphere ); - - scene.add( sphere ); - - } - - particleLight = new THREE.Mesh( new THREE.SphereGeometry( 4, 8, 8 ), new THREE.MeshBasicMaterial( { color: 0xffffff } ) ); - scene.add( particleLight ); - - // Lights - - scene.add( new THREE.AmbientLight( 0x444444 ) ); - - var directionalLight = new THREE.DirectionalLight( 0xffffff, 1 ); - directionalLight.position.set( 1, 1, 1 ).normalize(); - scene.add( directionalLight ); - - pointLight = new THREE.PointLight( 0xffffff, 2, 800 ); - scene.add( pointLight ); - - particleLight.material.color = pointLight.color; - pointLight.position = particleLight.position; - - // - - renderer = new THREE.WebGLRenderer( { clearColor: 0x0a0a0a, clearAlpha: 1, antialias: true } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.sortObjects = true; - - container.appendChild( renderer.domElement ); - - renderer.gammaInput = true; - renderer.gammaOutput = true; - renderer.physicallyBasedShading = true; - - // - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var timer = Date.now() * 0.00025; - - camera.position.x = Math.cos( timer ) * 800; - camera.position.z = Math.sin( timer ) * 800; - - camera.lookAt( scene.position ); - - for ( var i = 0, l = objects.length; i < l; i ++ ) { - - var object = objects[ i ]; - - object.rotation.y += 0.005; - - } - - particleLight.position.x = Math.sin( timer * 7 ) * 300; - particleLight.position.y = Math.cos( timer * 5 ) * 400; - particleLight.position.z = Math.cos( timer * 3 ) * 300; - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_blending.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var camera, scene, renderer; - var mesh; - - init(); - animate(); - - function init() { - - // CAMERA - - camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.z = 600; - - // SCENE - - scene = new THREE.Scene(); - - // BACKGROUND - - var x = document.createElement( "canvas" ); - var xc = x.getContext( "2d" ); - x.width = x.height = 128; - xc.fillStyle = "#ddd"; - xc.fillRect( 0, 0, 128, 128 ); - xc.fillStyle = "#555"; - xc.fillRect( 0, 0, 64, 64 ); - xc.fillStyle = "#999"; - xc.fillRect( 32, 32, 32, 32 ); - xc.fillStyle = "#555"; - xc.fillRect( 64, 64, 64, 64 ); - xc.fillStyle = "#777"; - xc.fillRect( 96, 96, 32, 32 ); - - var mapBg = new THREE.Texture( x ); - mapBg.wrapS = mapBg.wrapT = THREE.RepeatWrapping; - mapBg.repeat.set( 128, 64 ); - mapBg.needsUpdate = true; - - /* - var mapBg = THREE.ImageUtils.loadTexture( "textures/disturb.jpg" ); - mapBg.wrapS = mapBg.wrapT = THREE.RepeatWrapping; - mapBg.repeat.set( 8, 4 ); - */ - - var materialBg = new THREE.MeshBasicMaterial( { map: mapBg } ); - - var meshBg = new THREE.Mesh( new THREE.PlaneGeometry( 4000, 2000 ), materialBg ); - meshBg.position.set( 0, 0, -1 ); - scene.add( meshBg ); - - // OBJECTS - - var blendings = [ "NoBlending", "NormalBlending", "AdditiveBlending", "SubtractiveBlending", "MultiplyBlending", "AdditiveAlphaBlending" ]; - - var map0 = THREE.ImageUtils.loadTexture( 'textures/ash_uvgrid01.jpg' ); - var map1 = THREE.ImageUtils.loadTexture( 'textures/sprite0.jpg' ); - var map2 = THREE.ImageUtils.loadTexture( 'textures/sprite0.png' ); - var map3 = THREE.ImageUtils.loadTexture( 'textures/lensflare/lensflare0.png' ); - var map4 = THREE.ImageUtils.loadTexture( 'textures/lensflare/lensflare0_alpha.png' ); - - var geo1 = new THREE.PlaneGeometry( 100, 100 ); - var geo2 = new THREE.PlaneGeometry( 100, 25 ); - - addImageRow( map0, 300 ); - addImageRow( map1, 150 ); - addImageRow( map2, 0 ); - addImageRow( map3, -150 ); - addImageRow( map4, -300 ); - - function addImageRow( map, y ) { - - for ( var i = 0; i < blendings.length; i ++ ) { - - var blending = blendings[ i ]; - - var material = new THREE.MeshBasicMaterial( { map: map } ); - material.transparent = true; - material.blending = THREE[ blending ]; - - var x = ( i - blendings.length / 2 ) * 110; - var z = 0; - - var mesh = new THREE.Mesh( geo1, material ); - mesh.position.set( x, y, z ); - scene.add( mesh ); - - - var mesh = new THREE.Mesh( geo2, generateLabelMaterial( blending.replace( "Blending", "" ) ) ); - mesh.position.set( x, y - 75, z ); - scene.add( mesh ); - - } - - } - - // RENDERER - - renderer = new THREE.WebGLRenderer( { clearColor: 0x000000, clearAlpha: 1 } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - document.body.appendChild( renderer.domElement ); - - // EVENTS - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - // - - function onWindowResize( event ) { - - var SCREEN_WIDTH = window.innerWidth; - var SCREEN_HEIGHT = window.innerHeight; - - renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - - camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT; - camera.updateProjectionMatrix(); - - } - - - function generateLabelMaterial( text ) { - - var x = document.createElement( "canvas" ); - var xc = x.getContext( "2d" ); - x.width = 128; - x.height = 32; - - xc.fillStyle = "rgba( 0, 0, 0, 0.95 )"; - xc.fillRect( 0, 0, 128, 32 ); - - xc.fillStyle = "white"; - xc.font = "12pt arial bold"; - xc.fillText( text, 10, 22 ); - - var map = new THREE.Texture( x ); - map.needsUpdate = true; - - var material = new THREE.MeshBasicMaterial( { map: map, transparent: true } ); - return material; - - } - - function animate() { - - requestAnimationFrame( animate ); - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_blending_custom.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_bumpmap.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_bumpmap_skin.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_cars.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var STATS_ENABLED = false; - - var CARS = { - - "veyron": { - - name: "Bugatti Veyron", - url: "obj/veyron/VeyronNoUv_bin.js", - author: 'Troyano', - init_rotation: [ 0, 0, 0 ], - scale: 5.5, - init_material: 4, - body_materials: [ 2 ], - - object: null, - buttons: null, - materials: null, - mmap: null - - }, - - "gallardo": { - - name: "Lamborghini Gallardo", - url: "obj/gallardo/GallardoNoUv_bin.js", - author: 'machman_3d', - init_rotation: [ 0, 0, 0 ], - scale: 3.7, - init_material: 9, - body_materials: [ 3 ], - - object: null, - buttons: null, - materials: null, - mmap: null - - }, - - "f50": { - - name: "Ferrari F50", - url: "obj/f50/F50NoUv_bin.js", - author: 'daniel sathya', - init_rotation: [ 0, 0, 0 ], - scale: 0.175, - init_material: 2, - body_materials: [ 3, 6, 7, 8, 9, 10, 23, 24 ], - - object: null, - buttons: null, - materials: null, - mmap: null - - }, - - "camaro": { - - name: "Chevrolet Camaro", - url: "obj/camaro/CamaroNoUv_bin.js", - author: 'dskfnwn', - init_rotation: [ 0.0, 0.0, 0.0 /*0, 1, 0*/ ], - scale: 75, - init_material: 0, - body_materials: [ 0 ], - - object: null, - buttons: null, - materials: null, - mmap: null - - } - - }; - - - var container, stats; - - var camera, scene, renderer; - var cameraCube, sceneCube; - - var m, mi; - - var directionalLight, pointLight; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var loader = new THREE.BinaryLoader( true ); - document.body.appendChild( loader.statusDomElement ); - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - // CAMERAS - - camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 100000 ); - cameraCube = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 100000 ); - - // SCENE - - scene = new THREE.Scene(); - sceneCube = new THREE.Scene(); - - // LIGHTS - - var ambient = new THREE.AmbientLight( 0x050505 ); - scene.add( ambient ); - - directionalLight = new THREE.DirectionalLight( 0xffffff, 2 ); - directionalLight.position.set( 2, 1.2, 10 ).normalize(); - scene.add( directionalLight ); - - directionalLight = new THREE.DirectionalLight( 0xffffff, 1 ); - directionalLight.position.set( -2, 1.2, -10 ).normalize(); - scene.add( directionalLight ); - - pointLight = new THREE.PointLight( 0xffaa00, 2 ); - pointLight.position.set( 2000, 1200, 10000 ); - scene.add( pointLight ); - - // Skybox - - var shader = THREE.ShaderLib[ "cube" ]; - shader.uniforms[ "tCube" ].value = textureCube; - - var material = new THREE.ShaderMaterial( { - - fragmentShader: shader.fragmentShader, - vertexShader: shader.vertexShader, - uniforms: shader.uniforms, - depthWrite: false, - side: THREE.BackSide - - } ), - - mesh = new THREE.Mesh( new THREE.CubeGeometry( 100, 100, 100 ), material ); - sceneCube.add( mesh ); - - // - - renderer = new THREE.WebGLRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.setFaceCulling( THREE.CullFaceNone ); - renderer.autoClear = false; - - container.appendChild( renderer.domElement ); - - if ( STATS_ENABLED ) { - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - } - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - - var r = "textures/cube/Bridge2/"; - var urls = [ r + "posx.jpg", r + "negx.jpg", - r + "posy.jpg", r + "negy.jpg", - r + "posz.jpg", r + "negz.jpg" ]; - - var textureCube = THREE.ImageUtils.loadTextureCube( urls ); - textureCube.format = THREE.RGBFormat; - - // common materials - - var mlib = { - - "Orange": new THREE.MeshLambertMaterial( { color: 0xff6600, ambient: 0xff2200, envMap: textureCube, combine: THREE.MixOperation, reflectivity: 0.3 } ), - "Blue": new THREE.MeshLambertMaterial( { color: 0x001133, ambient: 0x001133, envMap: textureCube, combine: THREE.MixOperation, reflectivity: 0.3 } ), - "Red": new THREE.MeshLambertMaterial( { color: 0x660000, ambient: 0x330000, envMap: textureCube, combine: THREE.MixOperation, reflectivity: 0.25 } ), - "Black": new THREE.MeshLambertMaterial( { color: 0x000000, ambient: 0x000000, envMap: textureCube, combine: THREE.MixOperation, reflectivity: 0.15 } ), - "White": new THREE.MeshLambertMaterial( { color: 0xffffff, ambient: 0x666666, envMap: textureCube, combine: THREE.MixOperation, reflectivity: 0.25 } ), - - "Carmine": new THREE.MeshPhongMaterial( { color: 0x770000, specular:0xffaaaa, envMap: textureCube, combine: THREE.MultiplyOperation } ), - "Gold": new THREE.MeshPhongMaterial( { color: 0xaa9944, specular:0xbbaa99, shininess:50, envMap: textureCube, combine: THREE.MultiplyOperation } ), - "Bronze": new THREE.MeshPhongMaterial( { color: 0x150505, specular:0xee6600, shininess:10, envMap: textureCube, combine: THREE.MixOperation, reflectivity: 0.25 } ), - "Chrome": new THREE.MeshPhongMaterial( { color: 0xffffff, specular:0xffffff, envMap: textureCube, combine: THREE.MultiplyOperation } ), - - "Orange metal": new THREE.MeshLambertMaterial( { color: 0xff6600, ambient: 0xff2200, envMap: textureCube, combine: THREE.MultiplyOperation } ), - "Blue metal": new THREE.MeshLambertMaterial( { color: 0x001133, ambient: 0x002266, envMap: textureCube, combine: THREE.MultiplyOperation } ), - "Red metal": new THREE.MeshLambertMaterial( { color: 0x770000, envMap: textureCube, combine: THREE.MultiplyOperation } ), - "Green metal": new THREE.MeshLambertMaterial( { color: 0x007711, envMap: textureCube, combine: THREE.MultiplyOperation } ), - "Black metal": new THREE.MeshLambertMaterial( { color: 0x222222, envMap: textureCube, combine: THREE.MultiplyOperation } ), - - "Pure chrome": new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: textureCube } ), - "Dark chrome": new THREE.MeshLambertMaterial( { color: 0x444444, envMap: textureCube } ), - "Darker chrome":new THREE.MeshLambertMaterial( { color: 0x222222, envMap: textureCube } ), - - "Black glass": new THREE.MeshLambertMaterial( { color: 0x101016, envMap: textureCube, opacity: 0.975, transparent: true } ), - "Dark glass": new THREE.MeshLambertMaterial( { color: 0x101046, envMap: textureCube, opacity: 0.25, transparent: true } ), - "Blue glass": new THREE.MeshLambertMaterial( { color: 0x668899, envMap: textureCube, opacity: 0.75, transparent: true } ), - "Light glass": new THREE.MeshBasicMaterial( { color: 0x223344, envMap: textureCube, opacity: 0.25, transparent: true, combine: THREE.MixOperation, reflectivity: 0.25 } ), - - "Red glass": new THREE.MeshLambertMaterial( { color: 0xff0000, opacity: 0.75, transparent: true } ), - "Yellow glass": new THREE.MeshLambertMaterial( { color: 0xffffaa, opacity: 0.75, transparent: true } ), - "Orange glass": new THREE.MeshLambertMaterial( { color: 0x995500, opacity: 0.75, transparent: true } ), - - "Orange glass 50": new THREE.MeshLambertMaterial( { color: 0xffbb00, opacity: 0.5, transparent: true } ), - "Red glass 50": new THREE.MeshLambertMaterial( { color: 0xff0000, opacity: 0.5, transparent: true } ), - - "Fullblack rough": new THREE.MeshLambertMaterial( { color: 0x000000 } ), - "Black rough": new THREE.MeshLambertMaterial( { color: 0x050505 } ), - "Darkgray rough": new THREE.MeshLambertMaterial( { color: 0x090909 } ), - "Red rough": new THREE.MeshLambertMaterial( { color: 0x330500 } ), - - "Darkgray shiny": new THREE.MeshPhongMaterial( { color: 0x000000, specular: 0x050505 } ), - "Gray shiny": new THREE.MeshPhongMaterial( { color: 0x050505, shininess: 20 } ) - - } - - // Gallardo materials - - CARS[ "gallardo" ].materials = { - - body: [ - - [ "Orange", mlib[ "Orange" ] ], - [ "Blue", mlib[ "Blue" ] ], - [ "Red", mlib[ "Red" ] ], - [ "Black", mlib[ "Black" ] ], - [ "White", mlib[ "White" ] ], - - [ "Orange metal", mlib[ "Orange metal" ] ], - [ "Blue metal", mlib[ "Blue metal" ] ], - [ "Green metal", mlib[ "Green metal" ] ], - [ "Black metal", mlib[ "Black metal" ] ], - - [ "Carmine", mlib[ "Carmine" ] ], - [ "Gold", mlib[ "Gold" ] ], - [ "Bronze", mlib[ "Bronze" ] ], - [ "Chrome", mlib[ "Chrome" ] ] - - ] - - } - - m = CARS[ "gallardo" ].materials; - mi = CARS[ "gallardo" ].init_material; - - CARS[ "gallardo" ].mmap = { - - 0: mlib[ "Pure chrome" ], // wheels chrome - 1: mlib[ "Black rough" ], // tire - 2: mlib[ "Black glass" ], // windshield - 3: m.body[ mi ][ 1 ], // body - 4: mlib[ "Red glass" ], // back lights - 5: mlib[ "Yellow glass" ], // front lights - 6: mlib[ "Dark chrome" ] // windshield rim - - } - - // Veyron materials - - CARS[ "veyron" ].materials = { - - body: [ - - [ "Orange metal", mlib[ "Orange metal" ] ], - [ "Blue metal", mlib[ "Blue metal" ] ], - [ "Red metal", mlib[ "Red metal" ] ], - [ "Green metal", mlib[ "Green metal" ] ], - [ "Black metal", mlib[ "Black metal" ] ], - - [ "Gold", mlib[ "Gold" ] ], - [ "Bronze", mlib[ "Bronze" ] ], - [ "Chrome", mlib[ "Chrome" ] ] - - ], - - } - - m = CARS[ "veyron" ].materials; - mi = CARS[ "veyron" ].init_material; - - CARS[ "veyron" ].mmap = { - - 0: mlib[ "Black rough" ], // tires + inside - 1: mlib[ "Pure chrome" ], // wheels + extras chrome - 2: m.body[ mi ][ 1 ], // back / top / front torso - 3: mlib[ "Dark glass" ], // glass - 4: mlib[ "Pure chrome" ], // sides torso - 5: mlib[ "Pure chrome" ], // engine - 6: mlib[ "Red glass 50" ], // backlights - 7: mlib[ "Orange glass 50" ] // backsignals - - } - - // F50 materials - - CARS[ "f50" ].materials = { - - body: [ - - [ "Orange", mlib[ "Orange" ] ], - [ "Blue", mlib[ "Blue" ] ], - [ "Red", mlib[ "Red" ] ], - [ "Black", mlib[ "Black" ] ], - [ "White", mlib[ "White" ] ], - - [ "Orange metal", mlib[ "Orange metal" ] ], - [ "Blue metal", mlib[ "Blue metal" ] ], - [ "Black metal", mlib[ "Black metal" ] ], - - [ "Carmine", mlib[ "Carmine" ] ], - [ "Gold", mlib[ "Gold" ] ], - [ "Bronze", mlib[ "Bronze" ] ], - [ "Chrome", mlib[ "Chrome" ] ] - - ], - - } - - m = CARS[ "f50" ].materials; - mi = CARS[ "f50" ].init_material; - - CARS[ "f50" ].mmap = { - - 0: mlib[ "Dark chrome" ], // interior + rim - 1: mlib[ "Pure chrome" ], // wheels + gears chrome - 2: mlib[ "Blue glass" ], // glass - 3: m.body[ mi ][ 1 ], // torso mid + front spoiler - 4: mlib[ "Darkgray shiny" ], // interior + behind seats - 5: mlib[ "Darkgray shiny" ], // tiny dots in interior - 6: m.body[ mi ][ 1 ], // back torso - 7: m.body[ mi ][ 1 ], // right mirror decal - 8: m.body[ mi ][ 1 ], // front decal - 9: m.body[ mi ][ 1 ], // front torso - 10: m.body[ mi ][ 1 ], // left mirror decal - 11: mlib[ "Pure chrome" ], // engine - 12: mlib[ "Darkgray rough" ], // tires side - 13: mlib[ "Darkgray rough" ], // tires bottom - 14: mlib[ "Darkgray shiny" ], // bottom - 15: mlib[ "Black rough" ], // ??? - 16: mlib[ "Orange glass" ], // front signals - 17: mlib[ "Dark chrome" ], // wheels center - 18: mlib[ "Red glass" ], // back lights - 19: mlib[ "Black rough" ], // ??? - 20: mlib[ "Red rough" ], // seats - 21: mlib[ "Black rough" ], // back plate - 22: mlib[ "Black rough" ], // front light dots - 23: m.body[ mi ][ 1 ], // back torso - 24: m.body[ mi ][ 1 ] // back torso center - - } - - - // Camero materials - - CARS[ "camaro" ].materials = { - - body: [ - - [ "Orange", mlib[ "Orange" ] ], - [ "Blue", mlib[ "Blue" ] ], - [ "Red", mlib[ "Red" ] ], - [ "Black", mlib[ "Black" ] ], - [ "White", mlib[ "White" ] ], - - [ "Orange metal", mlib[ "Orange metal" ] ], - [ "Blue metal", mlib[ "Blue metal" ] ], - [ "Red metal", mlib[ "Red metal" ] ], - [ "Green metal", mlib[ "Green metal" ] ], - [ "Black metal", mlib[ "Black metal" ] ], - - [ "Gold", mlib[ "Gold" ] ], - [ "Bronze", mlib[ "Bronze" ] ], - [ "Chrome", mlib[ "Chrome" ] ] - - ], - - } - - m = CARS[ "camaro" ].materials; - mi = CARS[ "camaro" ].init_material; - - CARS[ "camaro" ].mmap = { - - 0: m.body[ mi ][ 1 ], // car body - 1: mlib[ "Pure chrome" ], // wheels chrome - 2: mlib[ "Pure chrome" ], // grille chrome - 3: mlib[ "Dark chrome" ], // door lines - 4: mlib[ "Light glass" ], // windshield - 5: mlib[ "Gray shiny" ], // interior - 6: mlib[ "Black rough" ], // tire - 7: mlib[ "Fullblack rough" ], // tireling - 8: mlib[ "Fullblack rough" ] // behind grille - - } - - loader.load( CARS[ "veyron" ].url, function( geometry ) { createScene( geometry, "veyron" ) } ); - - for( var c in CARS ) initCarButton( c ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - cameraCube.aspect = window.innerWidth / window.innerHeight; - cameraCube.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function initCarButton( car ) { - - $( car ).addEventListener( 'click', function() { - - if ( ! CARS[ car ].object ) { - - loader.statusDomElement.style.display = "block"; - loader.load( CARS[ car ].url, function( geometry ) { createScene( geometry, car ) } ); - - } else { - - switchCar( car ); - - } - - }, false ); - - } - - function $( id ) { return document.getElementById( id ) } - function button_name( car, index ) { return "m_" + car + "_" + index } - - function switchCar( car ) { - - for ( var c in CARS ) { - - if ( c != car && CARS[ c ].object ) { - - CARS[ c ].object.visible = false; - CARS[ c ].buttons.style.display = "none"; - - } - } - - CARS[ car ].object.visible = true; - CARS[ car ].buttons.style.display = "block"; - - $( "car_name" ).innerHTML = CARS[ car ].name + " model"; - $( "car_author" ).innerHTML = CARS[ car ].author; - - } - - function createButtons( materials, car ) { - - var buttons, i, src = ""; - - for( i = 0; i < materials.length; i ++ ) { - - src += ' '; - - } - - buttons = document.createElement( "div" ); - buttons.innerHTML = src; - - $( "buttons_materials" ).appendChild( buttons ); - - return buttons; - - } - - function attachButtonMaterials( materials, faceMaterial, material_indices, car ) { - - for( var i = 0; i < materials.length; i ++ ) { - - $( button_name( car, i ) )["counter"] = i; - $( button_name( car, i ) ).addEventListener( 'click', function() { - - for ( var j = 0; j < material_indices.length; j ++ ) { - - faceMaterial.materials[ material_indices [ j ] ] = materials[ this.counter ][ 1 ]; - - } - - }, false ); - - } - - } - - function createScene( geometry, car ) { - - loader.statusDomElement.innerHTML = "Creating model ..."; - - var m = new THREE.MeshFaceMaterial(), - s = CARS[ car ].scale * 1, - r = CARS[ car ].init_rotation, - materials = CARS[ car ].materials, - mi = CARS[ car ].init_material, - bm = CARS[ car ].body_materials; - - for ( var i in CARS[ car ].mmap ) { - - m.materials[ i ] = CARS[ car ].mmap[ i ]; - - } - - var mesh = new THREE.Mesh( geometry, m ); - - mesh.rotation.x = r[ 0 ]; - mesh.rotation.y = r[ 1 ]; - mesh.rotation.z = r[ 2 ]; - - mesh.scale.x = mesh.scale.y = mesh.scale.z = s; - - scene.add( mesh ); - - CARS[ car ].object = mesh; - - CARS[ car ].buttons = createButtons( materials.body, car ); - attachButtonMaterials( materials.body, m, bm, car ); - - switchCar( car ); - - loader.statusDomElement.style.display = "none"; - loader.statusDomElement.innerHTML = "Loading model ..."; - - } - - function onDocumentMouseMove(event) { - - mouseY = ( event.clientY - window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - - } - - function render() { - - var timer = -0.0002 * Date.now(); - - camera.position.x = 1000 * Math.cos( timer ); - camera.position.y += ( - mouseY - camera.position.y ) * .05; - camera.position.z = 1000 * Math.sin( timer ); - - camera.lookAt( scene.position ); - cameraCube.rotation.copy( camera.rotation ); - - renderer.render( sceneCube, cameraCube ); - renderer.render( scene, camera ); - - if ( STATS_ENABLED ) stats.update(); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_cars_anaglyph.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_cars_camaro.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_cars_camaro_crosseyed.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_cars_parallaxbarrier.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_cubemap.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, scene, renderer; - var cameraCube, sceneCube; - - var mesh, lightMesh, geometry; - - var loader; - - var directionalLight, pointLight; - - var mouseX = 0; - var mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - document.addEventListener('mousemove', onDocumentMouseMove, false); - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 5000 ); - camera.position.z = 2000; - - cameraCube = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 100 ); - - scene = new THREE.Scene(); - sceneCube = new THREE.Scene(); - - // LIGHTS - - var ambient = new THREE.AmbientLight( 0xffffff ); - scene.add( ambient ); - - pointLight = new THREE.PointLight( 0xffffff, 2 ); - scene.add( pointLight ); - - // light representation - - var sphere = new THREE.SphereGeometry( 100, 16, 8 ); - lightMesh = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0xffaa00 } ) ); - lightMesh.position = pointLight.position; - lightMesh.scale.x = lightMesh.scale.y = lightMesh.scale.z = 0.05; - scene.add( lightMesh ); - - var path = "textures/cube/SwedishRoyalCastle/"; - var format = '.jpg'; - var urls = [ - path + 'px' + format, path + 'nx' + format, - path + 'py' + format, path + 'ny' + format, - path + 'pz' + format, path + 'nz' + format - ]; - - var reflectionCube = THREE.ImageUtils.loadTextureCube( urls ); - reflectionCube.format = THREE.RGBFormat; - - var refractionCube = new THREE.Texture( reflectionCube.image, new THREE.CubeRefractionMapping() ); - refractionCube.format = THREE.RGBFormat; - - //var cubeMaterial3 = new THREE.MeshPhongMaterial( { color: 0x000000, specular:0xaa0000, envMap: reflectionCube, combine: THREE.MixOperation, reflectivity: 0.25 } ); - var cubeMaterial3 = new THREE.MeshLambertMaterial( { color: 0xff6600, ambient: 0x993300, envMap: reflectionCube, combine: THREE.MixOperation, reflectivity: 0.3 } ); - var cubeMaterial2 = new THREE.MeshLambertMaterial( { color: 0xffee00, ambient: 0x996600, envMap: refractionCube, refractionRatio: 0.95 } ); - var cubeMaterial1 = new THREE.MeshLambertMaterial( { color: 0xffffff, ambient: 0xaaaaaa, envMap: reflectionCube } ) - - // Skybox - - var shader = THREE.ShaderLib[ "cube" ]; - shader.uniforms[ "tCube" ].value = reflectionCube; - - var material = new THREE.ShaderMaterial( { - - fragmentShader: shader.fragmentShader, - vertexShader: shader.vertexShader, - uniforms: shader.uniforms, - depthWrite: false, - side: THREE.BackSide - - } ), - - mesh = new THREE.Mesh( new THREE.CubeGeometry( 100, 100, 100 ), material ); - sceneCube.add( mesh ); - - // - - renderer = new THREE.WebGLRenderer(); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.autoClear = false; - container.appendChild( renderer.domElement ); - - // - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - // - - loader = new THREE.BinaryLoader( true ); - document.body.appendChild( loader.statusDomElement ); - - loader.load( "obj/walt/WaltHead_bin.js", function( geometry ) { createScene( geometry, cubeMaterial1, cubeMaterial2, cubeMaterial3 ) } ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - cameraCube.aspect = window.innerWidth / window.innerHeight; - cameraCube.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function createScene( geometry, m1, m2, m3 ) { - - var s = 15; - - var mesh = new THREE.Mesh( geometry, m1 ); - mesh.position.z = - 100; - mesh.scale.x = mesh.scale.y = mesh.scale.z = s; - scene.add( mesh ); - - var mesh = new THREE.Mesh( geometry, m2 ); - mesh.position.x = - 900; - mesh.position.z = - 100; - mesh.scale.x = mesh.scale.y = mesh.scale.z = s; - scene.add( mesh ); - - var mesh = new THREE.Mesh( geometry, m3 ); - mesh.position.x = 900; - mesh.position.z = - 100; - mesh.scale.x = mesh.scale.y = mesh.scale.z = s; - scene.add( mesh ); - - loader.statusDomElement.style.display = "none"; - - } - - function onDocumentMouseMove(event) { - - mouseX = ( event.clientX - windowHalfX ) * 4; - mouseY = ( event.clientY - windowHalfY ) * 4; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var timer = -0.0002 * Date.now(); - - lightMesh.position.x = 1500 * Math.cos( timer ); - lightMesh.position.z = 1500 * Math.sin( timer ); - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y += ( - mouseY - camera.position.y ) * .05; - - camera.lookAt( scene.position ); - cameraCube.rotation.copy( camera.rotation ); - - renderer.render( sceneCube, cameraCube ); - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_cubemap_balls_reflection.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_cubemap_balls_reflection_anaglyph.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_cubemap_balls_refraction.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_cubemap_balls_refraction_crosseyed.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_cubemap_dynamic.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_cubemap_dynamic2.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_cubemap_escher.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_cubemap_refraction.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_grass.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var camera, scene, renderer, - mesh, levels = []; - - init(); - animate(); - - function init() { - - camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 ); - camera.position.set( 0, 75, 100 ); - - scene = new THREE.Scene(); - - var geometry = new THREE.PlaneGeometry( 100, 100 ); - - var bitmap = generateTextureBase(); - - for ( var i = 0; i < 15; i ++ ) { - - mesh = levels[ i ] = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { map: new THREE.Texture( generateTextureLevel( bitmap ) ), transparent: true, depthWrite: false, depthTest: false } ) ); - mesh.material.map.needsUpdate = true; - - mesh.position.y = i * 0.25; - mesh.rotation.x = - Math.PI / 2; - - scene.add( mesh ); - - } - - renderer = new THREE.WebGLRenderer(); - renderer.sortObjects = false; - renderer.setSize( window.innerWidth, window.innerHeight ); - document.body.appendChild( renderer.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function generateTextureBase() { - - var canvas = document.createElement( 'canvas' ); - canvas.width = 512; - canvas.height = 512; - - var context = canvas.getContext( '2d' ); - - for ( var i = 0; i < 20000; i ++ ) { - - context.fillStyle = 'rgba(0,' + Math.floor( Math.random() * 64 + 32 ) + ',16,1)'; - context.beginPath(); - context.arc( Math.random() * canvas.width, Math.random() * canvas.height, Math.random() * 1 + 0.5, 0, Math.PI * 2, true ); - context.closePath(); - context.fill(); - - } - - context.globalAlpha = 0.075; - context.globalCompositeOperation = 'lighter'; - - return canvas; - - } - - function generateTextureLevel( texture ) { - - texture.getContext( '2d' ).drawImage( texture, 0, 0 ); - - var canvas = document.createElement( 'canvas' ); - canvas.width = texture.width; - canvas.height = texture.height; - - canvas.getContext( '2d' ).drawImage( texture, 0, 0 ); - - return canvas; - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - - } - - function render() { - - var time = Date.now() / 6000; - - camera.position.x = 80 * Math.cos( time ); - camera.position.z = 80 * Math.sin( time ); - - camera.lookAt( scene.position ); - - for ( var i = 0, l = levels.length; i < l; i ++ ) { - - mesh = levels[ i ]; - mesh.position.x = Math.sin( time * 4 ) * i * i * 0.005; - mesh.position.z = Math.cos( time * 6 ) * i * i * 0.005; - - } - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_lightmap.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_normalmap.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_normalmap2.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_shaders.html - -()=>{ - - var SCREEN_WIDTH = window.innerWidth; - var SCREEN_HEIGHT = window.innerHeight; - var FLOOR = -250; - - var container, stats; - - var camera, scene, canvasRenderer, webglRenderer; - - var mesh, zmesh, lightMesh, geometry; - - var directionalLight, pointLight; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var render_canvas = false, render_gl = true; - var has_gl = false; - - var bcanvas = document.getElementById( "rcanvas" ); - var bwebgl = document.getElementById( "rwebgl" ); - - init(); - animate(); - - render_canvas = !has_gl; - bwebgl.style.display = has_gl ? "inline" : "none"; - bcanvas.className = render_canvas ? "button" : "button inactive"; - - function addMesh( geometry, scale, x, y, z, rx, ry, rz, material ) { - - mesh = new THREE.Mesh( geometry, material ); - - mesh.scale.set( scale, scale, scale ); - mesh.position.set( x, y, z ); - mesh.rotation.set( rx, ry, rz ); - - scene.add( mesh ); - - } - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 100000 ); - camera.position.z = 1000; - - scene = new THREE.Scene(); - - // LIGHTS - - var ambient = new THREE.AmbientLight( 0x101010 ); - scene.add( ambient ); - - directionalLight = new THREE.DirectionalLight( 0xffffff ); - directionalLight.position.set( 1, 1, 2 ).normalize(); - scene.add( directionalLight ); - - pointLight = new THREE.PointLight( 0xffffff ); - scene.add( pointLight ); - - // light representation - - var sphere = new THREE.SphereGeometry( 100, 16, 8 ); - lightMesh = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( { color: 0xffaa00 } ) ); - lightMesh.scale.set( 0.05, 0.05, 0.05 ); - lightMesh.position = pointLight.position; - scene.add( lightMesh ); - - // material samples - - sphere = new THREE.SphereGeometry( 100, 32, 32 ); - - var y1 = 0, y2 = - 200; - - addMesh( sphere, 1, -600, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x050505, color: 0x000000, specular: 0x555555, shininess: 30 } ) ); - addMesh( sphere, 1, -600, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { color: 0x050505 } ) ); - - addMesh( sphere, 1, -400, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, color: 0xffffff, specular: 0x555555, shininess: 30 } ) ); - addMesh( sphere, 1, -400, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { color: 0xffffff } ) ); - - addMesh( sphere, 1, -200, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, color: 0xff5500, specular: 0x555555, shininess: 10 } ) ); - addMesh( sphere, 1, -200, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { color: 0xff5500 } ) ); - - addMesh( sphere, 1, 0, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, color: 0xffaa00, specular: 0x555555, shininess: 30 } ) ); - addMesh( sphere, 1, 0, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { color: 0xffaa00 } ) ); - - addMesh( sphere, 1, 200, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, color: 0x55ff00, specular: 0x555555, shininess: 30 } ) ); - addMesh( sphere, 1, 200, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { color: 0x55ff00 } ) ); - - addMesh( sphere, 1, 400, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, color: 0x0055ff, specular: 0x555555, shininess: 30 } ) ); - addMesh( sphere, 1, 400, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { color: 0x0055ff } ) ); - - addMesh( sphere, 1, 600, y1, 0, 0,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, color: 0x5500ff, specular: 0x555555, shininess: 30 } ) ); - addMesh( sphere, 1, 600, y2, 0, 0,0,0, new THREE.MeshLambertMaterial( { color: 0x5500ff } ) ); - - addToruses( new THREE.TorusGeometry( 100, 20, 32, 32 ) ); - - // - - if ( render_gl ) { - - try { - - webglRenderer = new THREE.WebGLRenderer(); - webglRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - webglRenderer.domElement.style.position = "relative"; - container.appendChild( webglRenderer.domElement ); - has_gl = true; - - } catch (e) { - - } - - } - - canvasRenderer = new THREE.CanvasRenderer(); - canvasRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - container.appendChild( canvasRenderer.domElement ); - - // - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - bcanvas.addEventListener("click", toggleCanvas, false); - bwebgl.addEventListener("click", toggleWebGL, false); - - document.addEventListener('mousemove', onDocumentMouseMove, false); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - if ( webglRenderer ) webglRenderer.setSize( window.innerWidth, window.innerHeight ); - if ( canvasRenderer ) canvasRenderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function addToruses( geometry ) { - - var s = 0.85, t = s + 100, y = 200, rx = 0; - - addMesh( geometry, s, -6*t, y, 0, rx,0,0, new THREE.MeshPhongMaterial( { ambient: 0x000000, color: 0x000000, specular: 0x333333, shininess: 10 } ) ); - addMesh( geometry, s, -4*t, y, 0, rx,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x888888, specular: 0x333333, shininess: 10 } ) ); - addMesh( geometry, s, -2*t, y, 0, rx,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x030303, specular: 0xff5500, shininess: 10 } ) ); - addMesh( geometry, s, 0, y, 0, rx,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x030303, specular: 0xffaa00, shininess: 10 } ) ); - addMesh( geometry, s, 2*t, y, 0, rx,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x030303, specular: 0x55ff00, shininess: 10 } ) ); - addMesh( geometry, s, 4*t, y, 0, rx,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x030303, specular: 0x0055ff, shininess: 10 } ) ); - addMesh( geometry, s, 6*t, y, 0, rx,0,0, new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0x030303, specular: 0x5500ff, shininess: 10 } ) ); - - } - - - function onDocumentMouseMove(event) { - - mouseX = ( event.clientX - windowHalfX ); - mouseY = ( event.clientY - windowHalfY ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var timer = -0.0002 * Date.now(); - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y += ( - mouseY - camera.position.y ) * .05; - - camera.lookAt( scene.position ); - - lightMesh.position.x = 700 * Math.cos( timer ); - lightMesh.position.z = 700 * Math.sin( timer ); - - if ( render_canvas ) canvasRenderer.render( scene, camera ); - if ( render_gl && has_gl ) webglRenderer.render( scene, camera ); - - } - - function toggleCanvas() { - - render_canvas = !render_canvas; - bcanvas.className = render_canvas ? "button" : "button inactive"; - - render_gl = !render_canvas; - bwebgl.className = render_gl ? "button" : "button inactive"; - - if( has_gl ) - webglRenderer.domElement.style.display = render_gl ? "block" : "none"; - - canvasRenderer.domElement.style.display = render_canvas ? "block" : "none"; - - } - - function toggleWebGL() { - - render_gl = !render_gl; - bwebgl.className = render_gl ? "button" : "button inactive"; - - render_canvas = !render_gl; - bcanvas.className = render_canvas ? "button" : "button inactive"; - - if( has_gl ) - webglRenderer.domElement.style.display = render_gl ? "block" : "none"; - - canvasRenderer.domElement.style.display = render_canvas ? "block" : "none"; - - } -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_shaders_fresnel.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_skin.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_texture_anisotropy.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_texture_compressed.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_texture_filters.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_texture_manualmipmap.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_video.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_materials_wireframe.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_morphnormals.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_morphtargets.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_morphtargets_horse.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_morphtargets_md2.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_morphtargets_md2_control.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_multiple_canvases_circle.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_multiple_canvases_complex.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_multiple_canvases_grid.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_multiple_views.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_panorama_equirectangular.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_particles_billboards.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_particles_billboards_colors.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_particles_dynamic.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_particles_random.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_particles_shapes.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_particles_sprites.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_performance.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_performance_doublesided.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_performance_static.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_postprocessing.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_postprocessing2.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_postprocessing_advanced.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_postprocessing_dof.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_postprocessing_godrays.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_ribbons.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - var camera, scene, renderer, ribbon, geometry, geometry2, ribbons = [], - parameters, i, i2, h, color, x, y, z, z2, s, n, n2, nribbons, grid; - - var mouseX = 0, mouseY = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var postprocessing = { enabled : true }; - - var composer; - - init(); - animate(); - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 3000 ); - camera.position.z = 1200; - - scene = new THREE.Scene(); - scene.fog = new THREE.FogExp2( 0x000000, 0.0016 ); - - geometry = new THREE.Geometry(); - geometry2 = new THREE.Geometry(); - - n = 1000; - n2 = 2 * n; - - for ( i = -n; i < n; i++ ) { - - i2 = i + n; - - x = i * 1.175; - y = ( i2 % 2 ) * 5; - - if ( i2 % 2 ) { - - z = 10 * Math.sin( i2 * 0.3 ) * Math.cos( i2 * 0.1 ); - - } - - geometry.vertices.push( new THREE.Vector3( x, y, z ) ); - geometry2.vertices.push( new THREE.Vector3( x, y, z ) ); - - h = i2 % 2 ? 1 : 0.15; - if( i2 % 4 <= 2 ) h -= 0.15; - - color = new THREE.Color( 0xffffff ); - color.setHSL( 0.1, 0, h ); - geometry.colors.push( color ); - geometry2.colors.push( color ); - - } - - // - - renderer = new THREE.WebGLRenderer( { antialias: false } ); - renderer.setSize( window.innerWidth, window.innerHeight ); - renderer.autoClear = false; - renderer.setClearColor( scene.fog.color, 1 ); - - container.appendChild( renderer.domElement ); - - // - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - // - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); - document.addEventListener( 'touchstart', onDocumentTouchStart, false ); - document.addEventListener( 'touchmove', onDocumentTouchMove, false ); - - // - - var renderModel = new THREE.RenderPass( scene, camera ); - var effectBloom = new THREE.BloomPass( 1.0 ); - var effectCopy = new THREE.ShaderPass( THREE.CopyShader ); - - effectCopy.renderToScreen = true; - - composer = new THREE.EffectComposer( renderer ); - - composer.addPass( renderModel ); - composer.addPass( effectBloom ); - composer.addPass( effectCopy ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - composer.reset(); - - } - - function onDocumentMouseMove( event ) { - - mouseX = event.clientX - windowHalfX; - mouseY = event.clientY - windowHalfY; - - } - - function onDocumentTouchStart( event ) { - - if ( event.touches.length === 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - function onDocumentTouchMove( event ) { - - if ( event.touches.length === 1 ) { - - event.preventDefault(); - - mouseX = event.touches[ 0 ].pageX - windowHalfX; - mouseY = event.touches[ 0 ].pageY - windowHalfY; - - } - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = Date.now() * 0.00005; - - camera.position.x += ( mouseX - camera.position.x ) * 0.036; - camera.position.y += ( - mouseY - camera.position.y ) * 0.036; - - camera.lookAt( scene.position ); - - for ( i = -n; i < n; i ++ ) { - - i2 = i + n; - - z = 10 * Math.sin( i2 * 0.1 + time*30 ); - z2 = 20 * Math.cos( Math.sin( i2 * 0.1 + time * 20 ) ); - - geometry.vertices[ i2 ].z = z; - geometry2.vertices[ i2 ].z = z2; - - } - - geometry.verticesNeedUpdate = true; - geometry2.verticesNeedUpdate = true; - - for ( i = 0; i < nribbons; i++ ) { - - h = ( 360 * ( i / nribbons + time ) % 360 ) / 360; - ribbons[ i ].material.color.setHSL( h, ( i % 20 / 20 ) * 0.3 + 0.7, 0.6 ); - - } - - renderer.clear(); - composer.render( 0.1 ); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_rtt.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_sandbox.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_shader.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var camera, scene, renderer; - - var uniforms, material, mesh; - - var mouseX = 0, mouseY = 0, - lat = 0, lon = 0, phy = 0, theta = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.Camera(); - camera.position.z = 1; - - scene = new THREE.Scene(); - - uniforms = { - time: { type: "f", value: 1.0 }, - resolution: { type: "v2", value: new THREE.Vector2() } - }; - - material = new THREE.ShaderMaterial( { - - uniforms: uniforms, - vertexShader: document.getElementById( 'vertexShader' ).textContent, - fragmentShader: document.getElementById( 'fragmentShader' ).textContent - - } ); - - mesh = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), material ); - scene.add( mesh ); - - renderer = new THREE.WebGLRenderer(); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - onWindowResize(); - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize( event? ) { - - uniforms.resolution.value.x = window.innerWidth; - uniforms.resolution.value.y = window.innerHeight; - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - uniforms.time.value += 0.05; - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_shader2.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var container, stats; - - var start_time; - - var camera, scene, renderer; - - var uniforms1, uniforms2, material1, material2, mesh, meshes = []; - - var mouseX = 0, mouseY = 0, - lat = 0, lon = 0, phy = 0, theta = 0; - - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var clock = new THREE.Clock(); - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 40, windowHalfX / windowHalfY, 1, 3000 ); - camera.position.z = 4; - - scene = new THREE.Scene(); - - start_time = Date.now(); - - uniforms1 = { - time: { type: "f", value: 1.0 }, - resolution: { type: "v2", value: new THREE.Vector2() } - }; - - uniforms2 = { - time: { type: "f", value: 1.0 }, - resolution: { type: "v2", value: new THREE.Vector2() }, - texture: { type: "t", value: THREE.ImageUtils.loadTexture( "textures/disturb.jpg" ) } - }; - - uniforms2.texture.value.wrapS = uniforms2.texture.value.wrapT = THREE.RepeatWrapping; - - var size = 0.75, mlib = [], - params = [ [ 'fragment_shader1', uniforms1 ], [ 'fragment_shader2', uniforms2 ], [ 'fragment_shader3', uniforms1 ], [ 'fragment_shader4', uniforms1 ] ]; - - for( var i = 0; i < params.length; i++ ) { - - var material = new THREE.ShaderMaterial( { - - uniforms: params[ i ][ 1 ], - vertexShader: document.getElementById( 'vertexShader' ).textContent, - fragmentShader: document.getElementById( params[ i ][ 0 ] ).textContent - - } ); - - mlib[ i ] = material; - - mesh = new THREE.Mesh( new THREE.CubeGeometry( size, size, size ), new THREE.MeshFaceMaterial( [ mlib[ i ], mlib[ i ], mlib[ i ], mlib[ i ], mlib[ i ], mlib[ i ] ] ) ); - mesh.position.x = i - ( params.length - 1 ) / 2; - mesh.position.y = i % 2 - 0.5; - scene.add( mesh ); - - meshes[ i ] = mesh; - - } - - renderer = new THREE.WebGLRenderer(); - container.appendChild( renderer.domElement ); - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - container.appendChild( stats.domElement ); - - onWindowResize(); - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize( event? ) { - - uniforms1.resolution.value.x = window.innerWidth; - uniforms1.resolution.value.y = window.innerHeight; - - uniforms2.resolution.value.x = window.innerWidth; - uniforms2.resolution.value.y = window.innerHeight; - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var delta = clock.getDelta(); - - uniforms1.time.value += delta * 5; - uniforms2.time.value = clock.elapsedTime; - - for( var i = 0; i < meshes.length; ++ i ) { - - meshes[ i ].rotation.y += delta * 0.5 * ( i % 2 ? 1 : -1 ); - meshes[ i ].rotation.x += delta * 0.5 * ( i % 2 ? -1 : 1 ); - - } - - renderer.render( scene, camera ); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_shader_lava.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_shading_physical.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_shadowmap.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var SHADOW_MAP_WIDTH = 2048, SHADOW_MAP_HEIGHT = 1024; - - var MARGIN = 100; - - var SCREEN_WIDTH = window.innerWidth; - var SCREEN_HEIGHT = window.innerHeight - 2 * MARGIN; - var FLOOR = -250; - - var camera, controls, scene, renderer; - var container, stats; - - var NEAR = 5, FAR = 3000; - - var sceneHUD, cameraOrtho, hudMaterial; - - var morph, morphs = []; - - var light; - - var clock = new THREE.Clock(); - - init(); - animate(); - - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - // SCENE CAMERA - - camera = new THREE.PerspectiveCamera( 23, SCREEN_WIDTH / SCREEN_HEIGHT, NEAR, FAR ); - camera.position.set( 700, 50, 1900 ); - - controls = new THREE.FirstPersonControls( camera ); - - controls.lookSpeed = 0.0125; - controls.movementSpeed = 500; - controls.noFly = false; - controls.lookVertical = true; - controls.constrainVertical = true; - controls.verticalMin = 1.5; - controls.verticalMax = 2.0; - - controls.lon = -110; - - // SCENE - - scene = new THREE.Scene(); - scene.fog = new THREE.Fog( 0x59472b, 1000, FAR ); - - // LIGHTS - - var ambient = new THREE.AmbientLight( 0x444444 ); - scene.add( ambient ); - - light = new THREE.SpotLight( 0xffffff, 1, 0, Math.PI, 1 ); - light.position.set( 0, 1500, 1000 ); - light.target.position.set( 0, 0, 0 ); - - light.castShadow = true; - - light.shadowCameraNear = 700; - light.shadowCameraFar = camera.far; - light.shadowCameraFov = 50; - - //light.shadowCameraVisible = true; - - light.shadowBias = 0.0001; - light.shadowDarkness = 0.5; - - light.shadowMapWidth = SHADOW_MAP_WIDTH; - light.shadowMapHeight = SHADOW_MAP_HEIGHT; - - scene.add( light ); - - createHUD(); - createScene(); - - // RENDERER - - renderer = new THREE.WebGLRenderer( { clearColor: 0x000000, clearAlpha: 1, antialias: false } ); - renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - renderer.domElement.style.position = "relative"; - renderer.domElement.style.top = MARGIN + 'px'; - container.appendChild( renderer.domElement ); - - renderer.setClearColor( scene.fog.color, 1 ); - renderer.autoClear = false; - - // - - renderer.shadowMapEnabled = true; - renderer.shadowMapType = THREE.PCFShadowMap; - - // STATS - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - //container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - SCREEN_WIDTH = window.innerWidth; - SCREEN_HEIGHT = window.innerHeight - 2 * MARGIN; - - camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT; - camera.updateProjectionMatrix(); - - renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - - controls.handleResize(); - - } - - function createHUD() { - - cameraOrtho = new THREE.OrthographicCamera( SCREEN_WIDTH / - 2, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, SCREEN_HEIGHT / - 2, -10, 1000 ); - cameraOrtho.position.z = 10; - - var shader = THREE.UnpackDepthRGBAShader; - var uniforms = THREE.UniformsUtils.clone( shader.uniforms ); - - hudMaterial = new THREE.ShaderMaterial( { vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader, uniforms: uniforms } ); - - var hudGeo = new THREE.PlaneGeometry( SHADOW_MAP_WIDTH / 2, SHADOW_MAP_HEIGHT / 2 ); - var hudMesh = new THREE.Mesh( hudGeo, hudMaterial ); - hudMesh.position.x = ( SCREEN_WIDTH - SHADOW_MAP_WIDTH / 2 ) * -0.5; - hudMesh.position.y = ( SCREEN_HEIGHT - SHADOW_MAP_HEIGHT / 2 ) * -0.5; - hudMesh.rotation.x = Math.PI / 2; - - sceneHUD = new THREE.Scene(); - sceneHUD.add( hudMesh ); - - cameraOrtho.lookAt( sceneHUD.position ); - - } - - function createScene( ) { - - // GROUND - - var geometry = new THREE.PlaneGeometry( 100, 100 ); - var planeMaterial = new THREE.MeshPhongMaterial( { color: 0xffdd99 } ); - planeMaterial.ambient = planeMaterial.color; - - var ground = new THREE.Mesh( geometry, planeMaterial ); - - ground.position.set( 0, FLOOR, 0 ); - ground.rotation.x = - Math.PI / 2; - ground.scale.set( 100, 100, 100 ); - - ground.castShadow = false; - ground.receiveShadow = true; - - scene.add( ground ); - - // TEXT - - var textGeo = new THREE.TextGeometry( "THREE.JS", { - - size: 200, - height: 50, - curveSegments: 12, - - font: "helvetiker", - weight: "bold", - style: "normal", - - bevelThickness: 2, - bevelSize: 5, - bevelEnabled: true - - }); - - textGeo.computeBoundingBox(); - var centerOffset = -0.5 * ( textGeo.boundingBox.max.x - textGeo.boundingBox.min.x ); - - var textMaterial = new THREE.MeshPhongMaterial( { color: 0xff0000, specular: 0xffffff, ambient: 0xaa0000 } ); - - var mesh = new THREE.Mesh( textGeo, textMaterial ); - mesh.position.x = centerOffset; - mesh.position.y = FLOOR + 67; - - mesh.castShadow = true; - mesh.receiveShadow = true; - - scene.add( mesh ); - - // CUBES - - var mesh = new THREE.Mesh( new THREE.CubeGeometry( 1500, 220, 150 ), planeMaterial ); - - mesh.position.y = FLOOR - 50; - mesh.position.z = 20; - - mesh.castShadow = true; - mesh.receiveShadow = true; - - scene.add( mesh ); - - var mesh = new THREE.Mesh( new THREE.CubeGeometry( 1600, 170, 250 ), planeMaterial ); - - mesh.position.y = FLOOR - 50; - mesh.position.z = 20; - - mesh.castShadow = true; - mesh.receiveShadow = true; - - scene.add( mesh ); - - // MORPHS - - function addMorph( geometry, speed, duration, x, y, z, fudgeColor ) { - - var material = new THREE.MeshLambertMaterial( { color: 0xffaa55, morphTargets: true, vertexColors: THREE.FaceColors } ); - - if ( fudgeColor ) { - - material.color.offsetHSL( 0, Math.random() * 0.5 - 0.25, Math.random() * 0.5 - 0.25 ); - material.ambient = material.color; - - } - - var meshAnim = new THREE.MorphAnimMesh( geometry, material ); - - (meshAnim).speed = speed; - meshAnim.duration = duration; - meshAnim.time = 600 * Math.random(); - - meshAnim.position.set( x, y, z ); - meshAnim.rotation.y = Math.PI/2; - - meshAnim.castShadow = true; - meshAnim.receiveShadow = true; - - scene.add( meshAnim ); - - morphs.push( meshAnim ); - - } - - function morphColorsToFaceColors( geometry ) { - - if ( geometry.morphColors && geometry.morphColors.length ) { - - var colorMap = geometry.morphColors[ 0 ]; - - for ( var i = 0; i < colorMap.colors.length; i ++ ) { - - geometry.faces[ i ].color = colorMap.colors[ i ]; - - } - - } - - } - - var loader = new THREE.JSONLoader(); - - loader.load( "models/animated/horse.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - - addMorph( geometry, 550, 1000, 100 - Math.random() * 1000, FLOOR, 300, true ); - addMorph( geometry, 550, 1000, 100 - Math.random() * 1000, FLOOR, 450, true ); - addMorph( geometry, 550, 1000, 100 - Math.random() * 1000, FLOOR, 600, true ); - - addMorph( geometry, 550, 1000, 100 - Math.random() * 1000, FLOOR, -300, true ); - addMorph( geometry, 550, 1000, 100 - Math.random() * 1000, FLOOR, -450, true ); - addMorph( geometry, 550, 1000, 100 - Math.random() * 1000, FLOOR, -600, true ); - - } ); - - /* - loader.load( "obj/morphs/fox.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - addMorph( geometry, 200, 1000, 100 - Math.random() * 500, FLOOR - 5, 600 ); - - } ); - - loader.load( "obj/morphs/shdw3walk.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - addMorph( geometry, 40, 2000, -500, FLOOR + 60, 245 ); - - } ); - - loader.load( "obj/morphs/flamingo.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - addMorph( geometry, 500, 1000, 500 - Math.random() * 500, FLOOR + 350, 40 ); - - } ); - - loader.load( "obj/morphs/stork.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - addMorph( geometry, 350, 1000, 500 - Math.random() * 500, FLOOR + 350, 340 ); - - } ); - - loader.load( "obj/morphs/mountainlion.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - addMorph( geometry, 400, 1000, 500 - Math.random() * 500, FLOOR - 5, 700 ); - - } ); - - loader.load( "obj/morphs/bearBrown.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - addMorph( geometry, 300, 2500, -500, FLOOR - 5, -750 ); - - } ); - - loader.load( "obj/morphs/parrot.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - addMorph( geometry, 450, 500, 500 - Math.random() * 500, FLOOR + 300, 700 ); - - } ); - */ - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var delta = clock.getDelta(); - - for ( var i = 0; i < morphs.length; i ++ ) { - - morph = morphs[ i ]; - - morph.updateAnimation( 1000 * delta ); - - morph.position.x += morph.speed * delta; - - if ( morph.position.x > 2000 ) { - - morph.position.x = -1000 - Math.random() * 500; - - } - - } - - controls.update( delta ); - - renderer.clear(); - renderer.render( scene, camera ); - - // Render debug HUD with shadow map - - //hudMaterial.uniforms.tDiffuse.texture = light.shadowMap; - //renderer.render( sceneHUD, cameraOrtho ); - - } -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_shadowmap_performance.html - -()=>{ - - if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - - var SHADOW_MAP_WIDTH = 2048, SHADOW_MAP_HEIGHT = 1024; - - var MARGIN = 100; - - var SCREEN_WIDTH = window.innerWidth; - var SCREEN_HEIGHT = window.innerHeight - 2 * MARGIN; - var FLOOR = -250; - - var camera, controls, scene, renderer; - var container, stats; - - var NEAR = 5, FAR = 3000; - - var sceneHUD, cameraOrtho, hudMaterial; - - var morph, morphs = []; - - var light; - - var clock = new THREE.Clock(); - - init(); - animate(); - - - function init() { - - container = document.createElement( 'div' ); - document.body.appendChild( container ); - - // SCENE CAMERA - - camera = new THREE.PerspectiveCamera( 23, SCREEN_WIDTH / SCREEN_HEIGHT, NEAR, FAR ); - camera.position.set( 700, 50, 1900 ); - - controls = new THREE.FirstPersonControls( camera ); - - controls.lookSpeed = 0.0125; - controls.movementSpeed = 500; - controls.noFly = false; - controls.lookVertical = true; - controls.constrainVertical = true; - controls.verticalMin = 1.5; - controls.verticalMax = 2.0; - - controls.lon = -110; - - // SCENE - - scene = new THREE.Scene(); - scene.fog = new THREE.Fog( 0x59472b, 1000, FAR ); - - // LIGHTS - - var ambient = new THREE.AmbientLight( 0x444444 ); - scene.add( ambient ); - - light = new THREE.SpotLight( 0xffffff, 1, 0, Math.PI, 1 ); - light.position.set( 0, 1500, 1000 ); - light.target.position.set( 0, 0, 0 ); - - light.castShadow = true; - - light.shadowCameraNear = 700; - light.shadowCameraFar = camera.far; - light.shadowCameraFov = 50; - - //light.shadowCameraVisible = true; - - light.shadowBias = 0.0001; - light.shadowDarkness = 0.5; - - light.shadowMapWidth = SHADOW_MAP_WIDTH; - light.shadowMapHeight = SHADOW_MAP_HEIGHT; - - scene.add( light ); - - createHUD(); - createScene(); - - // RENDERER - - renderer = new THREE.WebGLRenderer( { clearColor: 0x000000, clearAlpha: 1, antialias: false } ); - renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - renderer.domElement.style.position = "relative"; - renderer.domElement.style.top = MARGIN + 'px'; - container.appendChild( renderer.domElement ); - - renderer.setClearColor( scene.fog.color, 1 ); - renderer.autoClear = false; - - // - - renderer.shadowMapEnabled = true; - renderer.shadowMapType = THREE.PCFSoftShadowMap; - - // STATS - - stats = new Stats(); - stats.domElement.style.position = 'absolute'; - stats.domElement.style.top = '0px'; - stats.domElement.style.zIndex = 100; - container.appendChild( stats.domElement ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - SCREEN_WIDTH = window.innerWidth; - SCREEN_HEIGHT = window.innerHeight - 2 * MARGIN; - - camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT; - camera.updateProjectionMatrix(); - - renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - - controls.handleResize(); - - } - - function createHUD() { - - cameraOrtho = new THREE.OrthographicCamera( SCREEN_WIDTH / - 2, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, SCREEN_HEIGHT / - 2, -10, 1000 ); - cameraOrtho.position.z = 10; - - var shader = THREE.UnpackDepthRGBAShader; - var uniforms = THREE.UniformsUtils.clone( shader.uniforms ); - - hudMaterial = new THREE.ShaderMaterial( { vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader, uniforms: uniforms } ); - - var hudGeo = new THREE.PlaneGeometry( SHADOW_MAP_WIDTH / 2, SHADOW_MAP_HEIGHT / 2 ); - var hudMesh = new THREE.Mesh( hudGeo, hudMaterial ); - hudMesh.position.x = ( SCREEN_WIDTH - SHADOW_MAP_WIDTH / 2 ) * -0.5; - hudMesh.position.y = ( SCREEN_HEIGHT - SHADOW_MAP_HEIGHT / 2 ) * -0.5; - hudMesh.rotation.x = Math.PI / 2; - - sceneHUD = new THREE.Scene(); - sceneHUD.add( hudMesh ); - - cameraOrtho.lookAt( sceneHUD.position ); - - } - - function createScene( ) { - - // GROUND - - var geometry = new THREE.PlaneGeometry( 100, 100 ); - var planeMaterial = new THREE.MeshPhongMaterial( { color: 0xffdd99 } ); - planeMaterial.ambient = planeMaterial.color; - - var ground = new THREE.Mesh( geometry, planeMaterial ); - - ground.position.set( 0, FLOOR, 0 ); - ground.rotation.x = - Math.PI / 2; - ground.scale.set( 100, 100, 100 ); - - ground.castShadow = false; - ground.receiveShadow = true; - - scene.add( ground ); - - // TEXT - - var textGeo = new THREE.TextGeometry( "THREE.JS", { - - size: 200, - height: 50, - curveSegments: 12, - - font: "helvetiker", - weight: "bold", - style: "normal", - - bevelThickness: 2, - bevelSize: 5, - bevelEnabled: true - - }); - - textGeo.computeBoundingBox(); - var centerOffset = -0.5 * ( textGeo.boundingBox.max.x - textGeo.boundingBox.min.x ); - - var textMaterial = new THREE.MeshPhongMaterial( { color: 0xff0000, specular: 0xffffff, ambient: 0xaa0000 } ); - - var mesh = new THREE.Mesh( textGeo, textMaterial ); - mesh.position.x = centerOffset; - mesh.position.y = FLOOR + 67; - - mesh.castShadow = true; - mesh.receiveShadow = true; - - scene.add( mesh ); - - // CUBES - - var mesh = new THREE.Mesh( new THREE.CubeGeometry( 1500, 220, 150 ), planeMaterial ); - - mesh.position.y = FLOOR - 50; - mesh.position.z = 20; - - mesh.castShadow = true; - mesh.receiveShadow = true; - - scene.add( mesh ); - - var mesh = new THREE.Mesh( new THREE.CubeGeometry( 1600, 170, 250 ), planeMaterial ); - - mesh.position.y = FLOOR - 50; - mesh.position.z = 20; - - mesh.castShadow = true; - mesh.receiveShadow = true; - - scene.add( mesh ); - - // MORPHS - - function addMorph( geometry, speed, duration, x, y, z, fudgeColor ) { - - var material = new THREE.MeshLambertMaterial( { color: 0xffaa55, morphTargets: true, vertexColors: THREE.FaceColors } ); - - if ( fudgeColor ) { - - material.color.offsetHSL( 0, Math.random() * 0.5 - 0.25, Math.random() * 0.5 - 0.25 ); - material.ambient = material.color; - - } - - var meshAnim = new THREE.MorphAnimMesh( geometry, material ); - - (meshAnim).speed = speed; - meshAnim.duration = duration; - meshAnim.time = 600 * Math.random(); - - meshAnim.position.set( x, y, z ); - meshAnim.rotation.y = Math.PI/2; - - meshAnim.castShadow = true; - meshAnim.receiveShadow = true; - - scene.add( meshAnim ); - - morphs.push( meshAnim ); - - } - - function morphColorsToFaceColors( geometry ) { - - if ( geometry.morphColors && geometry.morphColors.length ) { - - var colorMap = geometry.morphColors[ 0 ]; - - for ( var i = 0; i < colorMap.colors.length; i ++ ) { - - geometry.faces[ i ].color = colorMap.colors[ i ]; - - } - - } - - } - - var loader = new THREE.JSONLoader(); - - loader.load( "models/animated/horse.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - - - var i = -600; - while (i < 601){ - addMorph( geometry, 550, 1000, 100 - Math.random() * 3000, FLOOR, i, true ); - i += 2; - } - - } ); - - /* - loader.load( "obj/morphs/fox.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - addMorph( geometry, 200, 1000, 100 - Math.random() * 500, FLOOR - 5, 600 ); - - } ); - - loader.load( "obj/morphs/shdw3walk.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - addMorph( geometry, 40, 2000, -500, FLOOR + 60, 245 ); - - } ); - - loader.load( "obj/morphs/flamingo.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - addMorph( geometry, 500, 1000, 500 - Math.random() * 500, FLOOR + 350, 40 ); - - } ); - - loader.load( "obj/morphs/stork.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - addMorph( geometry, 350, 1000, 500 - Math.random() * 500, FLOOR + 350, 340 ); - - } ); - - loader.load( "obj/morphs/mountainlion.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - addMorph( geometry, 400, 1000, 500 - Math.random() * 500, FLOOR - 5, 700 ); - - } ); - - loader.load( "obj/morphs/bearBrown.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - addMorph( geometry, 300, 2500, -500, FLOOR - 5, -750 ); - - } ); - - loader.load( "obj/morphs/parrot.js", function( geometry ) { - - morphColorsToFaceColors( geometry ); - addMorph( geometry, 450, 500, 500 - Math.random() * 500, FLOOR + 300, 700 ); - - } ); - */ - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var delta = clock.getDelta(); - - for ( var i = 0; i < morphs.length; i ++ ) { - - morph = morphs[ i ]; - - morph.updateAnimation( 1000 * delta ); - - morph.position.x += morph.speed * delta; - - if ( morph.position.x > 2000 ) { - - morph.position.x = -1000 - Math.random() * 500; - - } - - } - - controls.update( delta ); - - renderer.clear(); - renderer.render( scene, camera ); - - // Render debug HUD with shadow map - - //hudMaterial.uniforms.tDiffuse.texture = light.shadowMap; - //renderer.render( sceneHUD, cameraOrtho ); - - } - -}; - -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_sprites.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_terrain_dynamic.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_test_memory.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_test_memory2.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgl_trails.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgldeferred_animation.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgldeferred_arealights.html -// https://github.com/mrdoob/three.js/tree/master/examples/webgldeferred_pointlights.html \ No newline at end of file +/// + +// webGL renderer test. +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +// css3d renderer test. +/// +/// + +// canvas renderer test. +/// +/// +/// +/// +/// +/// diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 27938939aa..7489001666 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -1,4 +1,4 @@ -// Type definitions for three.js -- r66 +// Type definitions for three.js r67 // Project: http://mrdoob.github.com/three.js/ // Definitions by: Kon , Satoru Kimura // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -15,7 +15,7 @@ declare module THREE { export var AddEquation: BlendingEquation; export var SubtractEquation: BlendingEquation; export var ReverseSubtractEquation: BlendingEquation; - + // custom blending destination factors export enum BlendingDstFactor { } export var ZeroFactor: BlendingDstFactor; @@ -177,8 +177,8 @@ declare module THREE { /** * Camera with orthographic projection * - * @example - * var camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 ); + * @example + * var camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 ); * scene.add( camera ); * * @see src/cameras/OrthographicCamera.js @@ -281,20 +281,20 @@ declare module THREE { /** * Sets an offset in a larger frustum. This is useful for multi-window or multi-monitor/multi-machine setups. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and the monitors are in grid like this: - * + * * +---+---+---+ * | A | B | C | * +---+---+---+ * | D | E | F | * +---+---+---+ - * + * * then for each monitor you would call it like this: - * + * * var w = 1920; * var h = 1080; * var fullWidth = w * 3; * var fullHeight = h * 2; - * + * * // A * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); * // B @@ -307,13 +307,13 @@ declare module THREE { * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); * // F * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); Note there is no reason monitors have to be the same size or in a grid. - * + * * @param fullWidth full width of multiview setup * @param fullHeight full height of multiview setup * @param x horizontal offset of subcamera * @param y vertical offset of subcamera * @param width width of subcamera - * @param height height of subcamera + * @param height height of subcamera */ setViewOffset(fullWidth: number, fullHeight: number, x: number, y: number, width: number, height: number): void; @@ -325,27 +325,48 @@ declare module THREE { } // Core /////////////////////////////////////////////////////////////////////////////////////////////// + export class BufferAttribute { + constructor(); - interface BufferGeometryAttributeArray extends ArrayBufferView{ - length: number; - } - - interface BufferGeometryAttribute{ - itemSize: number; - array: BufferGeometryAttributeArray; - numItems: number; + set(value: number): void; + setX(index: number, x: number): void; + setY(index: number, y: number): void; + setZ(index: number, z: number): void; + setXY(index: number, x: number, y: number): void; + setXYZ(index: number, x: number, y: number, z: number): void; + setXYZW(index: number, x: number, y: number, z: number, w: number): void; } - interface BufferGeometryAttributes{ - [name: string]: BufferGeometryAttribute; - index?: BufferGeometryAttribute; - position?: BufferGeometryAttribute; - normal?: BufferGeometryAttribute; - color?: BufferGeometryAttribute; + export class Int8Attribute extends BufferAttribute{ + constructor(size: number, itemSize: number); + } + export class Uint8Attribute extends BufferAttribute { + constructor(size: number, itemSize: number); + } + export class Uint8ClampedAttribute extends BufferAttribute { + constructor(size: number, itemSize: number); + } + export class Int16Attribute extends BufferAttribute { + constructor(size: number, itemSize: number); + } + export class Uint16Attribute extends BufferAttribute { + constructor(size: number, itemSize: number); + } + export class Int32Attribute extends BufferAttribute { + constructor(size: number, itemSize: number); + } + export class Uint32Attribute extends BufferAttribute { + constructor(size: number, itemSize: number); + } + export class Float32Attribute extends BufferAttribute { + constructor(size: number, itemSize: number); + } + export class Float64Attribute extends BufferAttribute { + constructor(size: number, itemSize: number); } /** - * This is a superefficent class for geometries because it saves all data in buffers. + * This is a superefficent class for geometries because it saves all data in buffers. * It reduces memory costs and cpu cycles. But it is not as easy to work with because of all the nessecary buffer calculations. * It is mainly interesting when working with static objects. * @@ -361,51 +382,25 @@ declare module THREE { * Unique number of this buffergeometry instance */ id: number; - - /** - * This hashmap has as id the name of the attribute to be set and as value the buffer to set it to. - */ - attributes: BufferGeometryAttributes; - - /** - * When set, it holds certain buffers in memory to have faster updates for this object. When unset, it deletes those buffers and saves memory. - */ - dynamic: boolean; - + + uuid: number; + name: string; + attributes: BufferAttribute[]; + drawcalls: { start: number; count: number; index: number; }[]; offsets: { start: number; count: number; index: number; }[]; - - /** - * Bounding box. - */ boundingBox: BoundingBox3D; - - /** - * Bounding sphere. - */ boundingSphere: BoundingSphere; - morphTargets: any[]; - hasTangents: boolean; - - addAttribute(name: string, type: Function, numItems: number, itemSize: number): any; + addAttribute(name: string, attribute: BufferAttribute): any; + addAttribute(name: string, array: any, itemSize: number): any; + getAttribute(name: string): any; + addDrawCall(start: number, count: number, index: number): void; /** * Bakes matrix transform directly into vertex coordinates. */ applyMatrix(matrix: Matrix4): void; - /** - * Computes vertex normals by averaging face normals. - */ - computeVertexNormals(): void; - - /** - * Computes vertex tangents. - * Based on http://www.terathon.com/code/tangent.html - * Geometry must have vertex UVs (layer 0 will be used). - */ - computeTangents(): void; - /** * Computes bounding box of the geometry, updating Geometry.boundingBox attribute. * Bounding boxes aren't computed by default. They need to be explicitly computed, otherwise they are null. @@ -419,14 +414,29 @@ declare module THREE { computeBoundingSphere(): void; /** - * Disposes the object from memory. + * Computes vertex normals by averaging face normals. + */ + computeVertexNormals(): void; + + /** + * Computes vertex tangents. + * Based on http://www.terathon.com/code/tangent.html + * Geometry must have vertex UVs (layer 0 will be used). + */ + computeTangents(): void; + + computeOffsets(indexBufferSize: number): void; + merge(): void; + normalizeNormals(): void; + reorderBuffers(indexBuffer: number, indexMap: number[], vertexCount: number): void; + clone(): BufferGeometry; + + /** + * Disposes the object from memory. * You need to call this when you want the bufferGeometry removed while the application is running. */ dispose(): void; - normalizeNormals(): void; - - clone(): BufferGeometry; } /** @@ -446,7 +456,7 @@ declare module THREE { autoStart: boolean; /** - * When the clock is running, It holds the starttime of the clock. + * When the clock is running, It holds the starttime of the clock. * This counted from the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. */ startTime: number; @@ -503,7 +513,7 @@ declare module THREE { * }; * * }; - * + * * var car = new Car(); * car.addEventListener( 'start', function ( event ) { * @@ -547,57 +557,18 @@ declare module THREE { */ dispatchEvent(event: { type: string; target: any; }): void; } - - export interface Face { - /** - * Face normal. - */ - normal: Vector3; - - /** - * Face color. - */ - color: Color; - - /** - * Array of 4 vertex normals. - */ - vertexNormals: Vector3[]; - - /** - * Array of 4 vertex normals. - */ - vertexColors: Color[]; - - /** - * Array of 4 vertex tangets. - */ - vertexTangents: number[]; - - /** - * Material index (points to {@link Geometry.materials}). - */ - materialIndex: number; - - /** - * Face centroid. - */ - centroid: Vector3; - - clone(): Face; - } /** * Triangle face. * * # Example - * var normal = new THREE.Vector3( 0, 1, 0 ); - * var color = new THREE.Color( 0xffaa00 ); + * var normal = new THREE.Vector3( 0, 1, 0 ); + * var color = new THREE.Color( 0xffaa00 ); * var face = new THREE.Face3( 0, 1, 2, normal, color, 0 ); * * @source https://github.com/mrdoob/three.js/blob/master/src/core/Face3.js */ - export class Face3 implements Face { + export class Face3 { /** * @param a Vertex A index. * @param b Vertex B index. @@ -658,10 +629,6 @@ declare module THREE { */ materialIndex: number; - /** - * Face centroid. - */ - centroid: Vector3; clone(): Face3; } @@ -692,13 +659,13 @@ declare module THREE { /** * Base class for geometries - * + * * # Example * var geometry = new THREE.Geometry(); - * geometry.vertices.push( new THREE.Vector3( -10, 10, 0 ) ); - * geometry.vertices.push( new THREE.Vector3( -10, -10, 0 ) ); - * geometry.vertices.push( new THREE.Vector3( 10, -10, 0 ) ); - * geometry.faces.push( new THREE.Face3( 0, 1, 2 ) ); + * geometry.vertices.push( new THREE.Vector3( -10, 10, 0 ) ); + * geometry.vertices.push( new THREE.Vector3( -10, -10, 0 ) ); + * geometry.vertices.push( new THREE.Vector3( 10, -10, 0 ) ); + * geometry.faces.push( new THREE.Face3( 0, 1, 2 ) ); * geometry.computeBoundingSphere(); * * @see https://github.com/mrdoob/three.js/blob/master/src/core/Geometry.js @@ -732,7 +699,7 @@ declare module THREE { /** * Array of vertex normals, matching number and order of vertices. - * Normal vectors are nessecary for lighting + * Normal vectors are nessecary for lighting * To signal an update in this array, Geometry.normalsNeedUpdate needs to be set to true. */ // normals: Vector3[]; @@ -742,7 +709,7 @@ declare module THREE { * The array of faces describe how each vertex in the model is connected with each other. * To signal an update in this array, Geometry.elementsNeedUpdate needs to be set to true. */ - faces: Face[]; + faces: Face3[]; /** * Array of face UV layers. @@ -863,11 +830,6 @@ declare module THREE { */ applyMatrix(matrix: Matrix4): void; - /** - * Computes centroids for all faces. - */ - computeCentroids(): void; - /** * Computes face normals. */ @@ -890,7 +852,7 @@ declare module THREE { * Geometry must have vertex UVs (layer 0 will be used). */ computeTangents(): void; - + /** * Computes bounding box of the geometry, updating {@link Geometry.boundingBox} attribute. */ @@ -902,6 +864,8 @@ declare module THREE { */ computeBoundingSphere(): void; + merge( geometry: Geometry, matrix: Matrix, materialIndexOffset: number): void; + /** * Checks for duplicate vertices using hashmap. * Duplicated vertices are removed and faces' vertices are updated. @@ -914,19 +878,14 @@ declare module THREE { clone(): Geometry; /** - * Removes The object from memory. + * Removes The object from memory. * Don't forget to call this method when you remove an geometry because it can cuase meomory leaks. */ dispose(): void; computeLineDistances(): void; - } - - export class Geometry2 extends BufferGeometry { - vertices: Float32Array; - normals: Float32Array; - uvs: Float32Array; + makeGroups(usesFaceMaterial: boolean, maxVerticesInGroup: number): void; } /** @@ -1145,7 +1104,7 @@ declare module THREE { /** * Rotate an object along an axis in object space. The axis is assumed to be normalized. - * @param axis A normalized vector in object space. + * @param axis A normalized vector in object space. * @param angle The angle in radians. */ rotateOnAxis(axis: Vector3, angle: number): Object3D; @@ -1168,7 +1127,7 @@ declare module THREE { /** * Transforms a 3D scene object into 2D render data that can be rendered in a screen with your renderer of choice, projecting and clipping things out according to the used camera. - * If the scene were a real scene, this method would be the equivalent of taking a picture with the camera (and developing the film would be the next step, using a Renderer). + * If the scene were a real scene, this method would be the equivalent of taking a picture with the camera (and developing the film would be the next step, using a Renderer). * * @param scene scene to project. * @param camera camera to use in the projection. @@ -1178,14 +1137,14 @@ declare module THREE { objects: Object3D[]; // Mesh, Line or other object sprites: Object3D[]; // Sprite or Particle lights: Light[]; - elements: Face[]; // Line, Particle, Face3 or Face4 + elements: Face3[]; // Line, Particle, Face3 or Face4 }; } export interface Intersection { distance: number; point: Vector3; - face: Face; + face: Face3; object: Object3D; } @@ -1214,9 +1173,9 @@ declare module THREE { /** * This light's color gets applied to all the objects in the scene globally. - * + * * # example - * var light = new THREE.AmbientLight( 0x404040 ); // soft white light + * var light = new THREE.AmbientLight( 0x404040 ); // soft white light * scene.add( light ); * * @source https://github.com/mrdoob/three.js/blob/master/src/lights/AmbientLight.js @@ -1249,9 +1208,9 @@ declare module THREE { * Affects objects using MeshLambertMaterial or MeshPhongMaterial. * * @example - * // White directional light at half intensity shining from the top. - * var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 ); - * directionalLight.position.set( 0, 1, 0 ); + * // White directional light at half intensity shining from the top. + * var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 ); + * directionalLight.position.set( 0, 1, 0 ); * scene.add( directionalLight ); * * @see src/lights/DirectionalLight.js @@ -1351,7 +1310,7 @@ declare module THREE { /** * Shadow map texture height in pixels. - * Default — 512. + * Default — 512. */ shadowMapHeight: number; @@ -1425,7 +1384,7 @@ declare module THREE { export class HemisphereLight extends Light { constructor(skyColorHex?: number, groundColorHex?: number, intensity?: number); - + position: Vector3; groundColor: Color; intensity: number; @@ -1438,7 +1397,7 @@ declare module THREE { * * @example * var light = new THREE.PointLight( 0xff0000, 1, 100 ); - * light.position.set( 50, 50, 50 ); + * light.position.set( 50, 50, 50 ); * scene.add( light ); */ export class PointLight extends Light { @@ -1469,15 +1428,15 @@ declare module THREE { * A point light that can cast shadow in one direction. * * @example - * // white spotlight shining from the side, casting shadow + * // white spotlight shining from the side, casting shadow * var spotLight = new THREE.SpotLight( 0xffffff ); * spotLight.position.set( 100, 1000, 100 ); - * spotLight.castShadow = true; + * spotLight.castShadow = true; * spotLight.shadowMapWidth = 1024; - * spotLight.shadowMapHeight = 1024; + * spotLight.shadowMapHeight = 1024; * spotLight.shadowCameraNear = 500; - * spotLight.shadowCameraFar = 4000; - * spotLight.shadowCameraFov = 30; + * spotLight.shadowCameraFar = 4000; + * spotLight.shadowCameraFov = 30; * scene.add( spotLight ); */ export class SpotLight extends Light { @@ -1601,7 +1560,7 @@ declare module THREE { * load * Dispatched when the image has completed loading * content — loaded image - * + * * error * * Dispatched when the image can't be loaded @@ -1658,17 +1617,19 @@ declare module THREE { load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void): void; setCrossOrigin(crossOrigin: string): void; parse(json: any): BufferGeometry; - + } - export class Geometry2Loader { - constructor(manager?: LoadingManager); + export class Cache{ + constructor(); - load(url: string, onLoad: (geometry2: Geometry2) => void): void; - setCrossOrigin(crossOrigin: string): void; - parse(json: any): Geometry2; + files: any[]; + + add(key: string, file: any): void; + get(key: string): any; + remove(key: string): void; + clear(): void; } - /** * A loader for loading an image. * Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object. @@ -1740,7 +1701,7 @@ declare module THREE { setCrossOrigin(crossOrigin: string): void; parse(json: any): Material; } - + export class ObjectLoader extends EventDispatcher { constructor(manager?: LoadingManager); @@ -1840,14 +1801,11 @@ declare module THREE { export class XHRLoader extends EventDispatcher { constructor(manager?: LoadingManager); + + cache: Cache; crossOrigin: string; - /** - * Begin loading from url - * - * @param url - */ - constructor(onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void); - load(onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + + load(url: string, onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; setCrossOrigin(crossOrigin: string): void; } @@ -1921,12 +1879,12 @@ declare module THREE { */ polygonOffsetFactor: number; - /** + /** * Sets the polygon offset units. Default is 0. */ polygonOffsetUnits: number; - /** + /** * Sets the alpha value to be used when running an alpha test. Default is 0. */ alphaTest: number; @@ -2207,7 +2165,7 @@ declare module THREE { normalMap: Texture; bumpMap: Texture; wrapRGB: Vector3; - + clone(): MeshPhongMaterial; } @@ -2232,14 +2190,13 @@ declare module THREE { clone(): ParticleSystemMaterial; } - export interface Uniforms { - [name: string]: { type: string; value: any; }; + export class RawShaderMaterial extends ShaderMaterial { + constructor(parameters?: ShaderMaterialParameters); - color?: { type: string; value: THREE.Color; }; } export interface ShaderMaterialParameters { - uniforms?: Uniforms; + uniforms?: any; fragmentShader?: string; vertexShader?: string; morphTargets?: boolean; @@ -2259,7 +2216,7 @@ declare module THREE { export class ShaderMaterial extends Material { constructor(parameters?: ShaderMaterialParameters); - uniforms: Uniforms; + uniforms: any; fragmentShader: string; vertexShader: string; morphTargets: boolean; @@ -2274,7 +2231,7 @@ declare module THREE { linewidth: number; wireframeLinewidth: number; defines: any; - + clone(): ShaderMaterial; } @@ -2355,7 +2312,7 @@ declare module THREE { constructor(min?: Vector3, max?: Vector3); max: Vector3; min: Vector3; - + set(min: Vector3, max: Vector3): Box3; applyMatrix4(matrix: Matrix4): Box3; expandByPoint(point: Vector3): Box3; @@ -2391,7 +2348,7 @@ declare module THREE { /** * Represents a color. See also {@link ColorUtils}. * - * @example + * @example * var color = new THREE.Color( 0xff0000 ); * * @see src/math/Color.js @@ -2475,7 +2432,7 @@ declare module THREE { */ setStyle(style: string): Color; - /** + /** * Returns the value of this color in CSS context style. * Example: rgb(r, g, b) */ @@ -2579,7 +2536,7 @@ declare module THREE { /** * Clamps the x to be larger than a. - * + * * @param x — Value to be clamped. * @param a — Minimum value */ @@ -2587,7 +2544,7 @@ declare module THREE { /** * Linear mapping of x from range [a1, a2] to range [b1, b2]. - * + * * @param x Value to be mapped. * @param a1 Minimum value for range A. * @param a2 Maximum value for range A. @@ -2713,7 +2670,10 @@ declare module THREE { determinant(): number; set(n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number): Matrix3; multiplyScalar(s: number): Matrix3; + // DEPRECATED multiplyVector3Array(a: number[]): number[]; + applyToVector3Array(array: number[], offset?: number, length?: number): number[]; + flattenToArrayOffset(array: number[], offset: number): number[]; getNormalMatrix(m: Matrix4): Matrix3; getInverse(matrix: Matrix3, throwOnInvertible?: boolean): Matrix3; getInverse(matrix: Matrix4, throwOnInvertible?: boolean): Matrix3; @@ -2726,19 +2686,19 @@ declare module THREE { * A 4x4 Matrix. * * @example - * // Simple rig for rotating around 3 axes - * var m = new THREE.Matrix4(); - * var m1 = new THREE.Matrix4(); - * var m2 = new THREE.Matrix4(); - * var m3 = new THREE.Matrix4(); - * var alpha = 0; - * var beta = Math.PI; - * var gamma = Math.PI/2; - * m1.makeRotationX( alpha ); - * m2.makeRotationY( beta ); - * m3.makeRotationZ( gamma ); - * m.multiplyMatrices( m1, m2 ); - * m.multiply( m3 ); + * // Simple rig for rotating around 3 axes + * var m = new THREE.Matrix4(); + * var m1 = new THREE.Matrix4(); + * var m2 = new THREE.Matrix4(); + * var m3 = new THREE.Matrix4(); + * var alpha = 0; + * var beta = Math.PI; + * var gamma = Math.PI/2; + * m1.makeRotationX( alpha ); + * m2.makeRotationY( beta ); + * m3.makeRotationZ( gamma ); + * m.multiplyMatrices( m1, m2 ); + * m.multiply( m3 ); */ export class Matrix4 implements Matrix { @@ -2758,7 +2718,7 @@ declare module THREE { */ elements: Float32Array; - /** + /** * Sets all fields of this matrix. */ set(n11: number, n12: number, n13: number, n14: number, n21: number, n22: number, n23: number, n24: number, n31: number, n32: number, n33: number, n34: number, n41: number, n42: number, n43: number, n44: number): Matrix4; @@ -2816,15 +2776,10 @@ declare module THREE { */ transpose(): Matrix4; - /** - * Flattens this matrix into supplied flat array. - */ - flattenToArray(flat: number[]): number[]; - /** * Flattens this matrix into supplied flat array starting from offset position in the array. */ - flattenToArrayOffset(flat: number[], offset: number): number[]; + flattenToArrayOffset(array: number[], offset: number): number[]; /** * Sets the position component for this matrix from vector v. @@ -2870,7 +2825,7 @@ declare module THREE { /** * Sets this matrix as rotation transform around y axis by theta radians. - * + * * @param theta Rotation angle in radians. */ makeRotationY(theta: number): Matrix4; @@ -2886,7 +2841,7 @@ declare module THREE { * Sets this matrix as rotation transform around axis by angle radians. * Based on http://www.gamedev.net/reference/articles/article1199.asp. * - * @param axis Rotation axis. + * @param axis Rotation axis. * @param theta Rotation angle in radians. */ makeRotationAxis(axis: Vector3, angle: number): Matrix4; @@ -2896,7 +2851,7 @@ declare module THREE { */ makeScale(x: number, y: number, z: number): Matrix4; - /** + /** * Creates a frustum matrix. */ makeFrustum(left: number, right: number, bottom: number, top: number, near: number, far: number): Matrix4; @@ -2916,7 +2871,10 @@ declare module THREE { */ clone(): Matrix4; + // DEPRECATED multiplyVector3Array(a: number[]): number[]; + applyToVector3Array(array: number[], offset?: number, length?: number): number[]; + getMaxScaleOnAxis(): number; } @@ -2950,9 +2908,9 @@ declare module THREE { * Implementation of a quaternion. This is used for rotating things without incurring in the dreaded gimbal lock issue, amongst other advantages. * * @example - * var quaternion = new THREE.Quaternion(); - * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 ); - * var vector = new THREE.Vector3( 1, 0, 0 ); + * var quaternion = new THREE.Quaternion(); + * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 ); + * var vector = new THREE.Vector3( 1, 0, 0 ); * vector.applyQuaternion( quaternion ); */ export class Quaternion { @@ -3100,7 +3058,7 @@ declare module THREE { /** * Represents a spline. - * + * * @see src/math/Spline.js */ export class Spline { @@ -3163,7 +3121,7 @@ declare module THREE { plane(optionalTarget?: Vector3): Plane; containsPoint(point: Vector3): boolean; copy(triangle: Triangle): Triangle; - + static normal(a: Vector3, b: Vector3, c: Vector3, optionalTarget?: Vector3): Vector3; static barycoordFromPoint(point: Vector3, a: Vector3, b: Vector3, c: Vector3, optionalTarget: Vector3): Vector3; static containsPoint(point: Vector3, a: Vector3, b: Vector3, c: Vector3): boolean; @@ -3248,7 +3206,7 @@ declare module THREE { /** * NOTE: Vector4 doesn't have the property. - * + * * distanceTo(v:T):number; */ distanceTo(v: Vector): number; @@ -3283,7 +3241,7 @@ declare module THREE { /** * 2D vector. - * + * * ( class Vector2 implements Vector ) */ export class Vector2 implements Vector { @@ -3333,7 +3291,7 @@ declare module THREE { */ divideScalar(s: number): Vector2; - /** + /** * Inverts this vector. */ negate(): Vector2; @@ -3400,7 +3358,7 @@ declare module THREE { /** * Gets a component of this vector. - */ + */ getComponent(index: number): number; fromArray(xy: number[]): Vector2; @@ -3426,9 +3384,9 @@ declare module THREE { * 3D vector. * * @example - * var a = new THREE.Vector3( 1, 0, 0 ); - * var b = new THREE.Vector3( 0, 1, 0 ); - * var c = new THREE.Vector3(); + * var a = new THREE.Vector3( 1, 0, 0 ); + * var b = new THREE.Vector3( 0, 1, 0 ); + * var c = new THREE.Vector3(); * c.crossVectors( a, b ); * * @see src/math/Vector3.js @@ -3478,7 +3436,7 @@ declare module THREE { */ addVectors(a: Vector3, b: Vector3): Vector3; - /** + /** * Subtracts v from this vector. */ sub(a: Vector3): Vector3; @@ -3488,7 +3446,7 @@ declare module THREE { */ subVectors(a: Vector3, b: Vector3): Vector3; - /** + /** * Multiplies this vector by scalar s. */ multiplyScalar(s: number): Vector3; @@ -3657,7 +3615,7 @@ declare module THREE { */ dot(v: Vector4): number; - /** + /** * Computes squared length of this vector. */ lengthSq(): number; @@ -3737,7 +3695,7 @@ declare module THREE { */ setW(w: number): Vector2; - /** + /** * NOTE: Vector4 doesn't have the property. * * distanceToSquared(v:T):number; @@ -3759,6 +3717,11 @@ declare module THREE { skinMatrix: Matrix4; skin: SkinnedMesh; + + accumulatedRotWeight: number; + accumulatedPosWeight: number; + accumulatedSclWeight: number; + update(parentSkinMatrix?: Matrix4, forceUpdate?: boolean): void; } @@ -3795,7 +3758,7 @@ declare module THREE { geometry: Geometry; material: Material; - + getMorphTargetIndexByName(name: string): number; updateMorphTargets(): void; clone(object?: Mesh): Mesh; @@ -3828,13 +3791,13 @@ declare module THREE { parseAnimations(): void; updateAnimation(delta: number): void; setAnimationLabel(label: string, start: number, end: number): void; - + clone(object?: MorphAnimMesh): MorphAnimMesh; } /** * A class for displaying particles in the form of variable size points. For example, if using the WebGLRenderer, the particles are displayed using GL_POINTS. - * + * * @see src/objects/ParticleSystem.js */ export class ParticleSystem extends Object3D { @@ -3846,7 +3809,7 @@ declare module THREE { constructor(geometry: Geometry, material?: ParticleSystemMaterial); constructor(geometry: Geometry, material?: ShaderMaterial); constructor(geometry: BufferGeometry, material?: ParticleSystemMaterial); - constructor(geometry: BufferGeometry, material?: ShaderMaterial); + constructor(geometry: BufferGeometry, material?: ShaderMaterial); /** * An instance of Geometry, where each vertex designates the position of a particle in the system. @@ -3868,6 +3831,16 @@ declare module THREE { clone(object?: ParticleSystem): ParticleSystem; } + export class Skeleton extends Mesh { + constructor(boneList: Bone[], useVertexTexture: boolean); + bones: Bone[]; + useVertexTexture: boolean; + boneMatrices: Float32Array; + + addBone(bone: Bone): Bone; + calculateInverses(bone: Bone): void; + } + export class SkinnedMesh extends Mesh { constructor(geometry?: Geometry, material?: MeshBasicMaterial, useVertexTexture?: boolean); constructor(geometry?: Geometry, material?: MeshDepthMaterial, useVertexTexture?: boolean); @@ -3877,20 +3850,18 @@ declare module THREE { constructor(geometry?: Geometry, material?: MeshPhongMaterial, useVertexTexture?: boolean); constructor(geometry?: Geometry, material?: ShaderMaterial, useVertexTexture?: boolean); - bones: Bone[]; identityMatrix: Matrix4; - useVertexTexture: boolean; - boneMatrices: Float32Array; - + pose(): void; - addBone(bone?: Bone): Bone; + normalizeSkinWeights(): void; clone(object?: SkinnedMesh): SkinnedMesh; } export class Sprite extends Object3D { constructor(material?: Material); - material: Material; + geometry: BufferGeometry; + material: SpriteMaterial; updateMatrix(): void; clone(object?: Sprite): Sprite; @@ -3917,7 +3888,7 @@ declare module THREE { autoClear: boolean; sortObjects: boolean; sortElements: boolean; - + getMaxAnisotropy(): number; render(scene: Scene, camera: Camera): void; clear(): void; @@ -3928,6 +3899,7 @@ declare module THREE { supportsVertexTextures(): void; setSize(width: number, height: number, updateStyle?: boolean): void; setClearColorHex(hex: number, alpha?: number): void; + setViewport(x: number, y: number, width: number, height: number): void; } export interface RendererPlugin { @@ -3936,7 +3908,7 @@ declare module THREE { } export interface WebGLRendererParameters { - /** + /** * A Canvas where the renderer draws its output. */ canvas?: HTMLCanvasElement; @@ -4045,7 +4017,7 @@ declare module THREE { */ gammaInput: boolean; - /** + /** * Default is false. */ gammaOutput: boolean; @@ -4077,7 +4049,7 @@ declare module THREE { shadowMapDebug: boolean; /** - * Default is false. + * Default is false. */ shadowMapCascade: boolean; @@ -4137,6 +4109,9 @@ declare module THREE { * Return a Boolean true if the context supports vertex textures. */ supportsVertexTextures(): boolean; + supportsFloatTextures(): boolean; + supportsStandardDerivatives(): boolean; + supportsCompressedTextureS3TC(): boolean; /** * Resizes the output canvas to (width, height), and also sets the viewport to fit that size, starting in (0, 0). @@ -4153,7 +4128,7 @@ declare module THREE { */ setScissor(x: number, y: number, width: number, height: number): void; - /** + /** * Enable the scissor test. When this is enabled, only the pixels within the defined scissor area will be affected by further renderer actions. */ enableScissorTest(enable: boolean): void; @@ -4181,6 +4156,10 @@ declare module THREE { */ clear(color?: boolean, depth?: boolean, stencil?: boolean): void; + clearColor(): void; + clearDepth(): void; + clearStencil(): void; + /** * Initialises the postprocessing plugin, and adds it to the renderPluginsPost array. */ @@ -4193,7 +4172,7 @@ declare module THREE { /** * Tells the shadow map plugin to update using the passed scene and camera parameters. - * + * * @param scene an instance of Scene * @param camera — an instance of Camera */ @@ -4218,30 +4197,27 @@ declare module THREE { /** * Used for setting the gl frontFace, cullFace states in the GPU, thus enabling/disabling face culling when rendering. * If cullFace is false, culling will be disabled. - * @param cullFace "back", "front", "front_and_back", or false. + * @param cullFace "back", "front", "front_and_back", or false. * @param frontFace "ccw" or "cw */ - setFaceCulling(cullFace?: string, frontFace?: FrontFaceDirection): void; + setFaceCulling(cullFace?: CullFace, frontFace?: FrontFaceDirection): void; setDepthTest(depthTest: boolean): void; setDepthWrite(depthWrite: boolean): void; setBlending(blending: Blending, blendEquation: BlendingEquation, blendSrc: BlendingSrcFactor, blendDst: BlendingDstFactor): void; setTexture(texture: Texture, slot: number): void; setRenderTarget(renderTarget: RenderTarget): void; - supportsCompressedTextureS3TC(): any; getMaxAnisotropy(): number; getPrecision(): string; setMaterialFaces(material: Material): void; - supportsStandardDerivatives(): any; - supportsFloatTextures(): any; clearTarget(renderTarget:WebGLRenderTarget, color: boolean, depth: boolean, stencil: boolean): void; /** * Sets the clear color, using hex for the color and alpha for the opacity. - * + * * @example - * // Creates a renderer with black background - * var renderer = new THREE.WebGLRenderer(); - * renderer.setSize(200, 100); + * // Creates a renderer with black background + * var renderer = new THREE.WebGLRenderer(); + * renderer.setSize(200, 100); * renderer.setClearColorHex(0x000000, 1); */ setClearColorHex(hex: number, alpha: number): void; @@ -4292,16 +4268,13 @@ declare module THREE { export class RenderableFace { constructor(); - vertexNormalsModelView: Vector3[]; - normalWorld: Vector3; color: number; material: Material; uvs: Vector2[][]; v1: RenderableVertex; v2: RenderableVertex; v3: RenderableVertex; - normalModelView: Vector3; - centroidModel: Vector3; + normalModel: Vector3; vertexNormalsLength: number; z: number; vertexNormalsModel: Vector3[]; @@ -4342,11 +4315,11 @@ declare module THREE { visible: boolean; positionScreen: Vector4; positionWorld: Vector3; - + copy(vertex: RenderableVertex): void; } - // Shaders ///////////////////////////////////////////////////////////////////// + // Renderers / Shaders ///////////////////////////////////////////////////////////////////// export interface ShaderChunk { [name: string]: string; fog_pars_fragment: string; @@ -4400,24 +4373,22 @@ declare module THREE { export var ShaderChunk: ShaderChunk; export var UniformsUtils: { - merge(uniforms: Object[]): Uniforms; - merge(uniforms: Uniforms[]): Uniforms; - clone(uniforms_src: Uniforms): Uniforms; + merge(uniforms: any[]): any; + clone(uniforms_src: any): any; }; export var UniformsLib: { - common: Uniforms; - bump: Uniforms; - normalmap: Uniforms; - fog: Uniforms; - lights: Uniforms; - particle: Uniforms; - shadowmap: Uniforms; + common: any; + bump: any; + normalmap: any; + fog: any; + lights: any; + particle: any; + shadowmap: any; }; - export interface Shader { - uniforms: Uniforms; + uniforms: any; vertexShader: string; fragmentShader: string; } @@ -4436,11 +4407,22 @@ declare module THREE { depthRGBA: Shader; }; + + + // Renderers / WebGL ///////////////////////////////////////////////////////////////////// + export class WebGLProgram{ + constructor(renderer: WebGLRenderer, code: string, material: ShaderMaterial, parameters: WebGLRendererParameters); + } + + export class WebGLShader{ + constructor(gl: any, type: string, string: string); + } + // Scenes ///////////////////////////////////////////////////////////////////// export interface IFog { name:string; - color: Color; + color: Color; clone():IFog; } @@ -4450,7 +4432,7 @@ declare module THREE { */ export class Fog implements IFog { constructor(hex: number, near?: number, far?: number); - + name:string; /** @@ -4527,8 +4509,8 @@ declare module THREE { magFilter?: TextureFilter, minFilter?: TextureFilter, anisotropy?: number - ); - + ); + clone(): CompressedTexture; } @@ -4545,14 +4527,14 @@ declare module THREE { magFilter: TextureFilter, minFilter: TextureFilter, anisotropy?: number - ); + ); clone(): DataTexture; } export class Texture { constructor( - image: HTMLImageElement, + image: any, // HTMLImageElement or HTMLCanvasElement mapping?: Mapping, wrapS?: Wrapping, wrapT?: Wrapping, @@ -4561,7 +4543,7 @@ declare module THREE { format?: PixelFormat, type?: TextureDataType, anisotropy?: number - ); + ); constructor( image: HTMLCanvasElement, mapping?: Mapping, @@ -4572,7 +4554,7 @@ declare module THREE { format?: PixelFormat, type?: TextureDataType, anisotropy?: number - ); + ); constructor( image: HTMLImageElement, mapping?: MappingConstructor, @@ -4594,9 +4576,9 @@ declare module THREE { format?: PixelFormat, type?: TextureDataType, anisotropy?: number - ); + ); - image: Object; // HTMLImageElement or ImageData ; + image: any; // HTMLImageElement or ImageData ; mapping: Mapping; wrapS: Wrapping; wrapT: Wrapping; @@ -4635,29 +4617,30 @@ declare module THREE { style: string; weight: string; face: string; - faces: { [weight: string]: { [style: string]: Face; }; }; + faces: { [weight: string]: { [style: string]: Face3; }; }; size: number; - + drawText(text: string): { paths: Path[]; offset: number; }; Triangulate: { (contour: Vector2[], indices: boolean): Vector2[]; area(contour: Vector2[]): number; }; - extractGlyphPoints(c: string, face: Face, scale: number, offset: number, path: Path): { offset: number; path: Path; }; + extractGlyphPoints(c: string, face: Face3, scale: number, offset: number, path: Path): { offset: number; path: Path; }; generateShapes(text: string, parameters?: { size?: number; curveSegments?: number; font?: string; weight?: string; style?: string; }): Shape[]; loadFace(data: TypefaceData): TypefaceData; - getFace(): Face; + getFace(): Face3; }; export var GeometryUtils: { + // DEPRECATED merge(geometry1: Geometry, object2: Mesh, materialIndexOffset?: number): void; + // DEPRECATED merge(geometry1: Geometry, object2: Geometry, materialIndexOffset?: number): void; randomPointInTriangle(vectorA: Vector3, vectorB: Vector3, vectorC: Vector3): Vector3; - randomPointInFace(face: Face, geometry: Geometry, useCachedAreas: boolean): Vector3; + randomPointInFace(face: Face3, geometry: Geometry, useCachedAreas: boolean): Vector3; randomPointsInGeometry(geometry: Geometry, points: number): Vector3; triangleArea(vectorA: Vector3, vectorB: Vector3, vectorC: Vector3): number; center(geometry: Geometry): Vector3; - triangulateQuads(geometry: Geometry): void; }; export var ImageUtils: { @@ -4702,7 +4685,7 @@ declare module THREE { export class Animation { constructor(root: Mesh, name: string); - + root: Mesh; data: AnimationData; hierarchy: Bone[]; @@ -4711,9 +4694,11 @@ declare module THREE { isPlaying: boolean; isPaused: boolean; loop: boolean; + weight: number; interpolationType: AnimationInterpolation; + keyTypes: string[]; - play(loop?: boolean, startTimeMS?: number): void; + play(startTime?: number, weight?: number): void; pause(): void; stop(): void; reset(): void; @@ -4730,10 +4715,12 @@ declare module THREE { CATMULLROM: AnimationInterpolation; CATMULLROM_FORWARD: AnimationInterpolation; LINEAR: AnimationInterpolation; + + remove(name: string): void; removeFromUpdate(animation: Animation): void; get(name: string): AnimationData; update(deltaTimeMS: number): void; - parse(root: SkinnedMesh): Object3D[]; + parse(root: Mesh): Object3D[]; add(data: AnimationData): void; addToUpdate(animation: Animation): void; }; @@ -4779,7 +4766,7 @@ declare module THREE { export class CombinedCamera extends Camera { constructor(width: number, height: number, fov: number, near: number, far: number, orthoNear: number, orthoFar: number); - + fov: number; right: number; bottom: number; @@ -4815,6 +4802,103 @@ declare module THREE { updateCubeMap(renderer: Renderer, scene: Scene): void; } + // Extras / Curves ///////////////////////////////////////////////////////////////////// + export class ArcCurve extends EllipseCurve { + constructor(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); + } + export class ClosedSplineCurve3 extends Curve { + constructor( points:Vector3[] ); + + points:Vector3[]; + + getPoint(t: number): Vector3; + } + export class CubicBezierCurve extends Curve { + constructor( v0: Vector2, v1: Vector2, v2: Vector2, v3: Vector2 ); + + v0: Vector2; + v1: Vector2; + v2: Vector2; + v3: Vector2; + + getPoint(t: number): Vector2; + } + export class CubicBezierCurve3 extends Curve { + constructor( v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3 ); + + v0: Vector2; + v1: Vector2; + v2: Vector2; + v3: Vector2; + + getPoint(t: number): Vector3; + } + export class EllipseCurve extends Curve { + constructor( aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); + + ax: number; + ay: number; + xRadius: number; + yRadius: number; + aStartAngle: number; + aEndAngle: number; + aClockwise: boolean; + + getPoint(t: number): Vector2; + } + export class LineCurve extends Curve { + constructor( v1: Vector2, v2: Vector2 ); + + v1: Vector2; + v2: Vector2; + + getPoint(t: number): Vector2; + getPointAt(u: number): Vector2; + getTangent(t: number): Vector2; + } + export class LineCurve3 extends Curve { + constructor( v1: Vector3, v2: Vector3 ); + + v1: Vector2; + v2: Vector2; + + getPoint(t: number): Vector3; + } + export class QuadraticBezierCurve extends Curve { + constructor( v0: Vector2, v1: Vector2, v2: Vector2 ); + + v0: Vector2; + v1: Vector2; + v2: Vector2; + + getPoint(t: number): Vector2; + getTangent(t: number): Vector2; + } + export class QuadraticBezierCurve3 extends Curve { + constructor( v0: Vector3, v1: Vector3, v2: Vector3 ); + + v0: Vector2; + v1: Vector2; + v2: Vector2; + + getPoint(t: number): Vector3; + } + export class SplineCurve extends Curve { + constructor( points: Vector2[] ); + + points:Vector2[]; + + getPoint(t: number): Vector2; + } + export class SplineCurve3 extends Curve { + constructor( points: Vector3[] ); + + points:Vector3[]; + + getPoint(t: number): Vector3; + } + + // Extras / Core ///////////////////////////////////////////////////////////////////// /** @@ -5006,18 +5090,6 @@ declare module THREE { constructor(width: number, height: number, depth: number, widthSegments?: number, heightSegments?: number, depthSegments?: number); } - export class BoxGeometry2 extends Geometry2 { - /** - * @param width — Width of the sides on the X axis. - * @param height — Height of the sides on the Y axis. - * @param depth — Depth of the sides on the Z axis. - * @param widthSegments — Number of segmented faces along the width of the sides. - * @param heightSegments — Number of segmented faces along the height of the sides. - * @param depthSegments — Number of segmented faces along the depth of the sides. - */ - constructor(width: number, height: number, depth: number, widthSegments?: number, heightSegments?: number, depthSegments?: number); - } - export class CircleGeometry extends Geometry { constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number); } @@ -5033,7 +5105,7 @@ declare module THREE { * @param radiusSegments — Number of segmented faces around the circumference of the cylinder. * @param heightSegments — Number of rows of faces along the height of the cylinder. * @param openEnded - A Boolean indicating whether or not to cap the ends of the cylinder. - */ + */ constructor(radiusTop?: number, radiusBottom?: number, height?: number, radiusSegments?: number, heightSegments?: number, openEnded?: boolean); } @@ -5065,12 +5137,8 @@ declare module THREE { constructor(width: number, height: number, widthSegments?: number, heightSegments?: number); } - export class PlaneGeometry2 extends Geometry2 { - constructor(width: number, height: number, widthSegments?: number, heightSegments?: number); - } - export class PolyhedronGeometry extends Geometry { - constructor(vertices: Vector3[], faces: Face[], radius?: number, detail?: number); + constructor(vertices: Vector3[], faces: Face3[], radius?: number, detail?: number); } export class RingGeometry extends Geometry { @@ -5191,13 +5259,14 @@ declare module THREE { } export class DirectionalLightHelper extends Object3D { - constructor(light: Light, sphereSize: number, arrowLength: number); + constructor(light: Light, size: number); - lightSphere: Mesh; + lightPlane: Line; light: Light; targetLine: Line; update(): void; + dispose(): void; } export class EdgesHelper extends Line { @@ -5236,7 +5305,16 @@ declare module THREE { lightSphere: Mesh; light: Light; - + + update(): void; + } + + export class SkeletonHelper extends Line { + constructor(bone: Bone); + + skeleton: Skeleton; + matrixAutoUpdate: boolean; + update(): void; } @@ -5305,8 +5383,9 @@ declare module THREE { positionScreen: Vector3; customUpdateCallback: (object: LensFlare) => void; - add(obj: Object3D): void; add(texture: Texture, size?: number, distance?: number, blending?: Blending, color?: Color): void; + add(obj: Object3D): void; + updateLensFlares(): void; } diff --git a/through/through.d.ts b/through/through.d.ts index 8a617c4241..1491085a2f 100644 --- a/through/through.d.ts +++ b/through/through.d.ts @@ -6,7 +6,7 @@ /// declare module "through" { - import Stream = require("stream"); + import stream = require("stream"); function through(write?: (data) => void, end?: () => void, @@ -15,7 +15,7 @@ declare module "through" { }): through.ThroughStream; module through { - export interface ThroughStream extends ReadWriteStream { + export interface ThroughStream extends stream.Transform { autoDestroy: boolean; } } diff --git a/through2/through2-tests.ts b/through2/through2-tests.ts new file mode 100644 index 0000000000..6ea9a52d5f --- /dev/null +++ b/through2/through2-tests.ts @@ -0,0 +1,44 @@ +/// +/// + +import through2 = require('through2'); + +var rws: NodeJS.ReadWriteStream; + +rws = through2({ + objectMode: true, + allowHalfOpen: true +}, function (entry: any, enc: string, callback: () => void) { + this.push('foo'); + callback(); +}, () => { + +}); + +rws = through2(function (entry: any, enc: string, callback: () => void) { + this.push('foo'); + callback(); +}, () => { + +}); + +rws = through2(function (entry: any, enc: string, callback: () => void) { + this.push('foo'); + callback(); +}); + +rws = through2(); + +// obj +rws = through2.obj(function (entry: any, enc: string, callback: () => void) { + this.push('foo'); + callback(); +}, () => { + +}); + +rws = through2.obj(function (entry: any, enc: string, callback: () => void) { + this.push('foo'); + callback(); +}); + diff --git a/through2/through2.d.ts b/through2/through2.d.ts new file mode 100644 index 0000000000..3eb16f2e6d --- /dev/null +++ b/through2/through2.d.ts @@ -0,0 +1,23 @@ +// Type definitions for through2 v 0.4.2 +// Project: https://github.com/rvagg/through2 +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'through2' { + import stream = require('stream'); + + var mod: mod.Through2; + + module mod { + interface Through2 { + (transform?: (entry: any, enc: string, callback: () => void) => void, flush?: () => void): NodeJS.ReadWriteStream; + (opts: stream.DuplexOptions, transform?: (entry: any, enc: string, callback: () => void) => void, flush?: () => void): NodeJS.ReadWriteStream; + obj(transform: (entry: any, enc: string, callback: () => void) => void, flush?: () => void): NodeJS.ReadWriteStream; + push(data: any): void; + } + } + export = mod; +} + diff --git a/timelinejs/timelinejs-tests.ts b/timelinejs/timelinejs-tests.ts new file mode 100644 index 0000000000..da6aef9669 --- /dev/null +++ b/timelinejs/timelinejs-tests.ts @@ -0,0 +1,41 @@ +/** + * Created by Roland on 6/15/2014. + */ +/// + +var timelineSource:knightlab.ITimelineModel = { + timeline: { + headline: 'Test Headline', + type: 'default', + text: 'Test Text', + asset: { + media: 'http://www.vertex42.com/ExcelArticles/Images/timeline/Timeline-for-Benjamin-Franklin.gif', + credit: 'http://www.vertex42.com', + caption: 'Test Caption' + }, + date: [ + { + startDate: '2011,12,09', + endDate: '2011,12,10', + headline: 'Test Date Headline', + text: 'Test test test test' + }, + { + startDate: '2012,12,09', + endDate: '2012,12,10', + headline: 'Test Date Headline 2', + text: 'Test2 test2 test2 test2' + } + ] + } +}; + +var source:knightlab.ITimeLineConfiguration = { + width: '100%', + height: '100%', + type: 'timeline', + embed_id: 'test', + source: timelineSource +}; + +createStoryJS(source); \ No newline at end of file diff --git a/timelinejs/timelinejs.d.ts b/timelinejs/timelinejs.d.ts new file mode 100644 index 0000000000..6101b93aa5 --- /dev/null +++ b/timelinejs/timelinejs.d.ts @@ -0,0 +1,136 @@ +// Type definitions for timelinejs +// Project: https://github.com/NUKnightLab/TimelineJS +// Definitions by: Roland Zwaga +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare function createStoryJS(config:knightlab.ITimeLineConfiguration):void; + +declare module knightlab { + + export interface ITimeLineConfiguration { + width: string; + height: string; + /* + * path to json/ or link to googlespreadsheet + * source Should be either the path to the JSON resource to load, or a JavaScript object corresponding to the + * Timeline model. + * + * Here is an example using a data object: + * + * var dataObject = {timeline: {headline: "Headline", type: ... }} + * createStoryJS({ + * type: 'timeline', + * width: '800', + * height: '600', + * source: dataObject, + * embed_id: 'my-timeline' + * }); + * If source is a string, we will try to automatically recognize resources that are Twitter searches, Google + * Spreadsheets or Storify stories. Failing that, we assume the source is either JSON or JSONP. If string + * matches on .jsonp, we will treat it as JSONP, otherwise, we will append ?callback=onJSONP_Data. + */ + source: any; + type?: string; + /* + * Optional use a different div id for embed + */ + embed_id?: string; + /* + * Optional start at latest date + */ + start_at_end?: boolean; + /* + * Optional start at specific slide + */ + start_at_slide?: string; + /* + * Optional tweak the default zoom level + */ + start_zoom_adjust?: string; + /* + * Optional location bar hashes + */ + hash_bookmark?: boolean; + /* + * Optional font + */ + font?: string; + /* + * Optional debug to console + */ + debug?: boolean; + /* + * Optional language + */ + lang?: string; + /* + * Optional path to css + */ + css?: string; + /* + * Optional path to js + */ + js?: string; + /* + * required in order to use maptype + */ + gmap_key?: string; + /* + * Stamen Maps: + * toner + * toner-lines + * toner-labels + * watercolor + * sterrain + * + * Google Maps: + * ROADMAP + * TERRAIN + * HYBRID + * SATELLITE + * + * OpenStreetMap: + * osm + */ + maptype?: string; + } + + export interface ITimelineModel { + timeline:ITimeLine; + } + + export interface ITimeLine { + headline?:string; + type?:string; + text?:string; + asset?:ITimeLineAsset; + date?:ITimelineDate[]; + era?:ITimelineEra[]; + } + + export interface ITimeLineAsset { + media:string; + thumbnail?:string; + credit:string; + caption:string; + } + + export interface ITimelineDate extends ITimelineEra { + classname?:string; + asset?:ITimeLineAsset; + } + + export interface ITimelineEra { + /* + * format example: 2011,12,10 + */ + startDate:string; + /* + * format example: 2011,12,10 + */ + endDate:string; + headline:string; + text:string; + tag?:string; + } +} \ No newline at end of file diff --git a/timezone-js/timezone-js-tests.ts b/timezone-js/timezone-js-tests.ts new file mode 100644 index 0000000000..9484d16406 --- /dev/null +++ b/timezone-js/timezone-js-tests.ts @@ -0,0 +1,26 @@ +/// + +import timezone = require('timezone-js'); +var tz = timezone.timezone; + +var value: any; +var str: string; +var bool: boolean; + +var opts: timezone.TimezoneJsOptions = { + async: bool, + success: (data: string) => { + + }, + error: (err: Error) => { + + }, + url: str +}; + +str = tz.zoneFileBasePath; +tz.loadingScheme; +tz.loadingSchemes; + +value = tz.transport(opts); +value = tz.init(opts); diff --git a/timezone-js/timezone-js.d.ts b/timezone-js/timezone-js.d.ts new file mode 100644 index 0000000000..9aca2738e2 --- /dev/null +++ b/timezone-js/timezone-js.d.ts @@ -0,0 +1,93 @@ +// Type definitions for timezone-js +// Project: https://github.com/mde/timezone-js +// Definitions by: bonnici +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/timezone-js.d.ts + +declare module "timezone-js" { + export var timezone: TimezoneJs; + + export class Date { + constructor(timezone?: string); + // Note due to naming conflict I have not found a way to introduce the constructor + // that takes a regular Date object. Instead, I defined it to take an Object. + constructor(date: Object, timezone?: string); + constructor(utcMillis: number, timezone?: string); + constructor(time: string, timezone?: string); + constructor(year?: number, month?: number, day?: number, hour?: number, minute?: number, second?: number, millisecond?: number, timezone?: string); + setTimezone: (timezone: string) => void; + + // regular Date members + toString(): string; + toDateString(): string; + toTimeString(): string; + toLocaleString(): string; + toLocaleDateString(): string; + toLocaleTimeString(): string; + valueOf(): number; + getTime(): number; + getFullYear(): number; + getUTCFullYear(): number; + getMonth(): number; + getUTCMonth(): number; + getDate(): number; + getUTCDate(): number; + getDay(): number; + getUTCDay(): number; + getHours(): number; + getUTCHours(): number; + getMinutes(): number; + getUTCMinutes(): number; + getSeconds(): number; + getUTCSeconds(): number; + getMilliseconds(): number; + getUTCMilliseconds(): number; + getTimezoneOffset(): number; + setTime(time: number): number; + + // Note the setters have a non-void return type. Date has them as well, according to TypeScript + setMilliseconds(ms: number): number; + setUTCMilliseconds(ms: number): number; + setSeconds(sec: number, ms?: number): number; + setUTCSeconds(sec: number, ms?: number): number; + setMinutes(min: number, sec?: number, ms?: number): number; + setUTCMinutes(min: number, sec?: number, ms?: number): number; + setHours(hours: number, min?: number, sec?: number, ms?: number): number; + setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; + setDate(date: number): number; + setUTCDate(date: number): number; + setMonth(month: number, date?: number): number; + setUTCMonth(month: number, date?: number): number; + setFullYear(year: number, month?: number, date?: number): number; + setUTCFullYear(year: number, month?: number, date?: number): number; + toUTCString(): string; + toISOString(): string; + toJSON(key?: any): string; + } + + + export interface TimezoneJs { + zoneFileBasePath: string; + loadingScheme: number; + loadingSchemes: TimezoneJsLoadingSchemes; + + transport(opts: TimezoneJsOptions): any; + init(opts?: TimezoneJsOptions): any; + getAllZones(): string[]; + loadZoneDataFromObject(obj: Object): void; + } + + export interface TimezoneJsOptions { + async?: boolean; + success?: (data: string) => void; + error?: (err: Error) => void; + url?: string; + } + + export class TimezoneJsLoadingSchemes { + PRELOAD_ALL: number; + LAZY_LOAD: number; + MANUAL_LOAD: number; + } + } diff --git a/timezonecomplete/timezonecomplete-1.2.0-tests.ts b/timezonecomplete/timezonecomplete-1.2.0-tests.ts new file mode 100644 index 0000000000..03f94e44bd --- /dev/null +++ b/timezonecomplete/timezonecomplete-1.2.0-tests.ts @@ -0,0 +1,169 @@ +/// + +import tc = require("timezonecomplete"); + +var b: boolean = tc.isLeapYear(2014); +var n: number = tc.daysInMonth(2014, 10); +var s: string = tc.isoString(2014, 6, 30, 22, 10, 11, 230); + +// DURATION + +var d: tc.Duration; +var d1: tc.Duration = tc.Duration.hours(24); +var d2: tc.Duration = tc.Duration.minutes(24); +var d3: tc.Duration = tc.Duration.seconds(24); +var d4: tc.Duration = tc.Duration.milliseconds(24); +var d5: tc.Duration = new tc.Duration(24); +var d6: tc.Duration = new tc.Duration("00:01"); +var d7: tc.Duration = d6.clone(); + +n = d7.wholeHours(); +n = d7.hours(); +n = d7.minutes(); +n = d7.minute(); +n = d7.seconds(); +n = d7.second(); +n = d7.milliseconds(); +n = d7.millisecond(); +s = d7.sign(); +b = d7.lessThan(d6); +b = d7.greaterThan(d6); +d = d7.min(d6); +d = d7.max(d6); +d = d7.multiply(3); +d = d7.add(d6); +d = d7.sub(d6); +s = d7.toString(); + +// TIMEZONE + +var t: tc.TimeZone; +var k: tc.TimeZoneKind; + +t = tc.TimeZone.local(); +t = tc.TimeZone.utc(); +t = tc.TimeZone.zone(2); +t = tc.TimeZone.zone("+01:00"); +s = t.name(); +k = t.kind(); +b = t.equals(t); +b = t.isUtc(); +n = t.offsetForUtc(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForZone(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForUtcDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.Get); +n = t.offsetForZoneDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.GetUTC); +s = t.toString(); +s = tc.TimeZone.offsetToString(2); +n = tc.TimeZone.stringToOffset("+00:01"); + +// REALTIMESOURCE + +var date: Date = (new tc.RealTimeSource()).now(); + +// DATETIME + +var dt: tc.DateTime; + +var ts: tc.TimeSource = tc.DateTime.timeSource; + +dt = tc.DateTime.nowLocal(); +dt = tc.DateTime.nowUtc(); +dt = tc.DateTime.now(tc.TimeZone.local()); +dt = new tc.DateTime(); +dt = new tc.DateTime("2014-01-01T13:05:01.123 UTC"); +dt = new tc.DateTime("2014-01-01T13:05:01.123", tc.TimeZone.utc()); +dt = new tc.DateTime(date, tc.DateFunctions.Get); +dt = new tc.DateTime(date, tc.DateFunctions.Get, tc.TimeZone.utc()); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123, tc.TimeZone.utc()); +dt = new tc.DateTime(89949284); +dt = new tc.DateTime(89949284, tc.TimeZone.utc()); +dt = dt.clone(); +t = dt.zone(); +n = dt.offset(); +n = dt.year(); +n = dt.month(); +n = dt.day(); +n = dt.hour(); +n = dt.minute(); +n = dt.second(); +n = dt.millisecond(); +n = dt.unixUtcMillis(); +n = dt.utcYear(); +n = dt.utcMonth(); +n = dt.utcDay(); +n = dt.utcHour(); +n = dt.utcMinute(); +n = dt.utcSecond(); +n = dt.utcMillisecond(); +dt.convert(tc.TimeZone.local()); +dt = dt.toZone(tc.TimeZone.utc()); +date = dt.toDate(); +dt = dt.add(tc.Duration.seconds(2)); +dt = dt.add(2, tc.TimeUnit.Year); +dt = dt.add(2, tc.TimeUnit.Month); +dt = dt.add(2, tc.TimeUnit.Week); +dt = dt.add(2, tc.TimeUnit.Day); +dt = dt.add(2, tc.TimeUnit.Hour); +dt = dt.add(2, tc.TimeUnit.Minute); +dt = dt.add(2, tc.TimeUnit.Second); +dt = dt.addLocal(2, tc.TimeUnit.Second); +dt = dt.sub(tc.Duration.seconds(2)); +dt = dt.sub(2, tc.TimeUnit.Year); +dt = dt.sub(2, tc.TimeUnit.Month); +dt = dt.sub(2, tc.TimeUnit.Week); +dt = dt.sub(2, tc.TimeUnit.Day); +dt = dt.sub(2, tc.TimeUnit.Hour); +dt = dt.sub(2, tc.TimeUnit.Minute); +dt = dt.sub(2, tc.TimeUnit.Second); +dt = dt.subLocal(2, tc.TimeUnit.Second); +d = dt.diff(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +s = dt.toIsoString(); +s = dt.toString(); +s = dt.toUtcString(); + +// PERIOD + +s = tc.periodDstToString(tc.PeriodDst.RegularIntervals); +s = tc.periodDstToString(tc.PeriodDst.RegularLocalTime); + +var p: tc.Period; + +p = new tc.Period(tc.DateTime.nowLocal(), 1, tc.TimeUnit.Hour, tc.PeriodDst.RegularLocalTime); +dt = p.start(); +n = p.amount(); +var tu: tc.TimeUnit = p.unit(); +var pd: tc.PeriodDst = p.dst(); +dt = p.findFirst(tc.DateTime.nowLocal()); +dt = p.findNext(dt); +s = p.toIsoString(); +s = p.toString(); + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/timezonecomplete/timezonecomplete-1.2.0.d.ts b/timezonecomplete/timezonecomplete-1.2.0.d.ts new file mode 100644 index 0000000000..2f1b969bce --- /dev/null +++ b/timezonecomplete/timezonecomplete-1.2.0.d.ts @@ -0,0 +1,681 @@ +// Type definitions for timezonecomplete +// Project: https://github.com/SpiritIT/timezonecomplete +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Generated by dts-bundle 0.1.1 + +declare module 'timezonecomplete' { + /** + * @return True iff the given year is a leap year. + */ + export function isLeapYear(year: number): boolean; + /** + * @param year The full year + * @param month The month 1-12 + * @return The number of days in the given month + */ + export function daysInMonth(year: number, month: number): number; + /** + * Returns an ISO time string. Note that months are 1-12. + */ + export function isoString(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number): string; + /** + * Time units + */ + export enum TimeUnit { + Second = 0, + Minute = 1, + Hour = 2, + Day = 3, + Week = 4, + Month = 5, + Year = 6, + } + /** + * Time duration. Create one e.g. like this: var d = Duration.hours(1). + * Note that time durations do not take leap seconds etc. into account: + * one hour is simply represented as 3600000 milliseconds. + */ + export class Duration { + /** + * Positive number of milliseconds + * Stored positive because otherwise we constantly have to choose + * between Math.floor() and Math.ceil() + */ + /** + * Sign: 1 or -1 + */ + /** + * Construct a time duration + * @param n Number of hours + * @return A duration of n hours + */ + static hours(n: number): Duration; + /** + * Construct a time duration + * @param n Number of minutes + * @return A duration of n minutes + */ + static minutes(n: number): Duration; + /** + * Construct a time duration + * @param n Number of seconds + * @return A duration of n seconds + */ + static seconds(n: number): Duration; + /** + * Construct a time duration + * @param n Number of milliseconds + * @return A duration of n milliseconds + */ + static milliseconds(n: number): Duration; + /** + * Construct a time duration of 0 + */ + constructor(); + /** + * Construct a time duration from a number of milliseconds + */ + constructor(milliseconds: number); + /** + * Construct a time duration from a string in format + * [-]h[:m[:s[.n]]] e.g. -01:00:30.501 + */ + constructor(input: string); + /** + * @return another instance of Duration with the same value. + */ + clone(): Duration; + /** + * The entire duration in milliseconds (negative or positive) + */ + milliseconds(): number; + /** + * The millisecond part of the duration (always positive) + * @return e.g. 400 for a -01:02:03.400 duration + */ + millisecond(): number; + /** + * The entire duration in seconds (negative or positive, fractional) + * @return e.g. 1.5 for a 1500 milliseconds duration + */ + seconds(): number; + /** + * The second part of the duration (always positive) + * @return e.g. 3 for a -01:02:03.400 duration + */ + second(): number; + /** + * The entire duration in minutes (negative or positive, fractional) + * @return e.g. 1.5 for a 90000 milliseconds duration + */ + minutes(): number; + /** + * The minute part of the duration (always positive) + * @return e.g. 2 for a -01:02:03.400 duration + */ + minute(): number; + /** + * The entire duration in hours (negative or positive, fractional) + * @return e.g. 1.5 for a 5400000 milliseconds duration + */ + hours(): number; + /** + * The hour part of the duration (always positive). + * Note that this part can exceed 23 hours, because for + * now, we do not have a days() function + * @return e.g. 25 for a -25:02:03.400 duration + */ + wholeHours(): number; + /** + * Sign + * @return "-" if the duration is negative + */ + sign(): string; + /** + * @return True iff (this < other) + */ + lessThan(other: Duration): boolean; + /** + * @return True iff this and other represent the same time duration + */ + equals(other: Duration): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: Duration): boolean; + /** + * @return The minimum (most negative) of this and other + */ + min(other: Duration): Duration; + /** + * @return The maximum (most positive) of this and other + */ + max(other: Duration): Duration; + /** + * @return a new Duration of (this * value) + */ + multiply(value: number): Duration; + /** + * Add a duration. + * @return a new Duration of (this + value) + */ + add(value: Duration): Duration; + /** + * Subtract a duration. + * @return a new Duration of (this - value) + */ + sub(value: Duration): Duration; + /** + * String in [-]hh:mm:ss.nnn notation. All fields are + * always present except the sign. + */ + toFullString(): string; + /** + * String in [-]hh[:mm[:ss[.nnn]]] notation. Fields are + * added as necessary + */ + toString(): string; + } + /** + * The type of time zone + */ + export enum TimeZoneKind { + /** + * Local time offset as determined by JavaScript Date class. + */ + Local = 0, + /** + * Fixed offset from UTC, without DST. + */ + Offset = 1, + /** + * IANA timezone managed through Olsen TZ database. Includes + * DST if applicable. + */ + Proper = 2, + } + /** + * Time zone. The object is immutable because it is cached: + * requesting a time zone twice yields the very same object. + * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), + * i.e. offset 90 means +01:30. + * + * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, + * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST + * applied depending on the time zone rules. + */ + export class TimeZone { + /** + * The local time zone for a given date. Note that + * the time zone varies with the date: amsterdam time for + * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 + */ + static local(): TimeZone; + /** + * The UTC time zone. + */ + static utc(): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @return The time zone with the given offset w.r.t. UTC in minutes, e.g. 90 for +01:30 + */ + static zone(offset: number): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @param s: Empty string for local time, a TZ database time zone name (e.g. Europe/Amsterdam) + * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: + * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + */ + static zone(s: string): TimeZone; + /** + * The time zone identifier. Can be an offset "-01:30" or an + * IANA time zone name "Europe/Amsterdam", or "localtime" for + * the local time zone. + */ + name(): string; + /** + * The kind of time zone (Local/Offset/Proper) + */ + kind(): TimeZoneKind; + /** + * Equality operator. Maps zero offsets and different names for UTC onto + * each other. Other time zones are not mapped onto each other. + */ + equals(other: TimeZone): boolean; + /** + * Is this zone equivalent to UTC? + */ + isUtc(): boolean; + /** + * Calculate timezone offset from a UTC time. + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time. + */ + offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Calculate timezone offset from a zone-local time (NOT a UTC time). + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time. + */ + offsetForZone(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForUtcDate(date: Date, funcs: DateFunctions): number; + /** + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForZoneDate(date: Date, funcs: DateFunctions): number; + /** + * The time zone identifier (normalized). + * Either "localtime", IANA name, or "+hh:mm" offset. + */ + toString(): string; + /** + * Convert an offset number into an offset string + * @param offset The offset in minutes from UTC e.g. 90 minutes + * @return the offset in ISO notation "+01:30" for +90 minutes + */ + static offsetToString(offset: number): string; + /** + * String to offset conversion. + * @param s Formats: "-01:00", "-0100", "-01", "Z" + * @return offset w.r.t. UTC in minutes + */ + static stringToOffset(s: string): number; + } + /** + * For testing purposes, we often need to manipulate what the current + * time is. This is an interface for a custom time source object + * so in tests you can use a custom time source. + */ + export interface TimeSource { + /** + * Return the current date+time as a javascript Date object + */ + now(): Date; + } + /** + * Default time source, returns actual time + */ + export class RealTimeSource implements TimeSource { + now(): Date; + } + /** + * Indicates how a Date object should be interpreted. + * Either we can take getYear(), getMonth() etc for our field + * values, or we can take getUTCYear() etc to do that. + */ + export enum DateFunctions { + /** + * Use the Date.getFullYear(), Date.getMonth(), ... functions. + */ + Get = 0, + /** + * Use the Date.getUTCFullYear(), Date.getUTCMonth(), ... functions. + */ + GetUTC = 1, + } + /** + * Our very own DateTime class which is time zone-aware + * and which can be mocked for testing purposes + */ + export class DateTime { + /** + * Actual time source in use. Setting this property allows to + * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() + * use this property for obtaining the current time. + */ + static timeSource: TimeSource; + /** + * Current date+time in local time (derived from DateTime.timeSource.now()). + */ + static nowLocal(): DateTime; + /** + * Current date+time in UTC time (derived from DateTime.timeSource.now()). + */ + static nowUtc(): DateTime; + /** + * Current date+time in the given time zone (derived from DateTime.timeSource.now()). + * @param timeZone The desired time zone. + */ + static now(timeZone: TimeZone): DateTime; + /** + * Constructor. Creates current time in local timezone. + */ + constructor(); + /** + * Constructor + * @param isoString String in ISO 8601 format. Instead of ISO time zone, + * it may include a space and then and IANA time zone. + * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) + * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) + * or "2007-04-05T12:30:40.500Z" (UTC) + * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) + * @param timeZone if given, the date in the string is assumed to be in this time zone. + * Note that it is NOT CONVERTED to the time zone. Useful + * for strings without a time zone + */ + constructor(isoString: string, timeZone?: TimeZone); + /** + * Constructor. You provide a date, then you say whether to take the + * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, + * and then you state which time zone that date is in. + * + * @param date A date object. + * @param getters Specifies which set of Date getters contains the date in the given time zone: the + * Date.getXxx() methods or the Date.getUTCXxx() methods. + * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) + */ + constructor(date: Date, getFuncs: DateFunctions, timeZone?: TimeZone); + /** + * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. + * Use the add(duration) or sub(duration) for arithmetic. + * @param year The full year (e.g. 2014) + * @param month The month [1-12] (note this deviates from JavaScript Date) + * @param day The day of the month [1-31] + * @param hour The hour of the day [0-24) + * @param minute The minute of the hour [0-59] + * @param second The second of the minute [0-59] + * @param millisecond The millisecond of the second [0-999] + * @param timeZone The time zone, or null (for unaware dates) + */ + constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, timeZone?: TimeZone); + /** + * Constructor + * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 + * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). + */ + constructor(unixTimestamp: number, timeZone?: TimeZone); + /** + * @return a copy of this object + */ + clone(): DateTime; + /** + * @return The time zone that the date is in. May be null for unaware dates. + */ + zone(): TimeZone; + /** + * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. + */ + offset(): number; + /** + * @return The full year e.g. 2014 + */ + year(): number; + /** + * @return The month 1-12 (note this deviates from JavaScript Date) + */ + month(): number; + /** + * @return The day of the month 1-31 + */ + day(): number; + /** + * @return The hour 0-23 + */ + hour(): number; + /** + * @return the minutes 0-59 + */ + minute(): number; + /** + * @return the seconds 0-59 + */ + second(): number; + /** + * @return the milliseconds 0-999 + */ + millisecond(): number; + /** + * @return Milliseconds since 1970-01-01T00:00:00.000Z + */ + unixUtcMillis(): number; + /** + * @return The full year e.g. 2014 + */ + utcYear(): number; + /** + * @return The UTC month 1-12 (note this deviates from JavaScript Date) + */ + utcMonth(): number; + /** + * @return The UTC day of the month 1-31 + */ + utcDay(): number; + /** + * @return The UTC hour 0-23 + */ + utcHour(): number; + /** + * @return The UTC minutes 0-59 + */ + utcMinute(): number; + /** + * @return The UTC seconds 0-59 + */ + utcSecond(): number; + /** + * @return The UTC milliseconds 0-999 + */ + utcMillisecond(): number; + /** + * Convert this date to the given time zone (in-place). + * Throws if this date does not have a time zone. + * @return this (for chaining) + */ + convert(zone?: TimeZone): DateTime; + /** + * Returns this date converted to the given time zone. + * Unaware dates can only be converted to unaware dates (clone) + * For unaware dates, an exception is thrown + * @param zone The new time zone. This may be null to create unaware date. + * @return The converted date + */ + toZone(zone?: TimeZone): DateTime; + /** + * Convert to JavaScript date with the zone time in the getX() methods. + * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. + */ + toDate(): Date; + /** + * Add a time duration. Note that this simply adds a number + * of milliseconds to UTC and converts back to zone(), + * so in the presence of e.g. leap seconds there may be a + * shift in the seconds field if you add an hour. + * There is not DST handling and no leap second handling. + * @return this + duration + */ + add(duration: Duration): DateTime; + /** + * Add an amount of time to UTC, taking leap seconds etc into account. + * Adding e.g. 1 hour will increment the utcHour() field + * date by one. In case of DST changes, the local hour() field + * may not increase or increase by 2 hours. So if you add a month, the + * local time may vary by an hour. There will not be a shift + * in seconds due to leap seconds. + */ + add(amount: number, unit: TimeUnit): DateTime; + /** + * Add an amount of time to the zone time, as regularly as possible. + * Adding e.g. 1 hour will increment the hour() field of the zone + * date by one. In case of DST changes, the utcHour() field may + * increase by 1 or increase by 2. Adding a day will leave the time portion + * intact. However, adding an hour around a forward DST change adds two hours, + * since there is a zone time (2AM in Holland) that does not exist. + */ + addLocal(amount: number, unit: TimeUnit): DateTime; + /** + * Same as add(-1*duration); + */ + sub(duration: Duration): DateTime; + /** + * Same as add(-1*amount, unit); + */ + sub(amount: number, unit: TimeUnit): DateTime; + /** + * Same as addLocal(-1*amount, unit); + */ + subLocal(amount: number, unit: TimeUnit): DateTime; + /** + * Time difference between two DateTimes + * @return this - other + */ + diff(other: DateTime): Duration; + /** + * @return True iff (this < other) + */ + lessThan(other: DateTime): boolean; + /** + * @return True iff (this <= other) + */ + lessEqual(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time in UTC + */ + equals(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time and + * have the same zone + */ + identical(other: DateTime): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: DateTime): boolean; + /** + * @return True iff this >= other + */ + greaterEqual(other: DateTime): boolean; + /** + * Proper ISO 8601 format string with any IANA zone converted to ISO offset + * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam + */ + toIsoString(): string; + /** + * Modified ISO 8601 format string with IANA name if applicable. + * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" + */ + toString(): string; + /** + * Modified ISO 8601 format string in UTC without time zone info + */ + toUtcString(): string; + } + /** + * Specifies how the period should repeat across the day + * during DST changes. + */ + export enum PeriodDst { + /** + * Keep repeating in similar intervals measured in UTC, + * unaffected by Daylight Saving Time. + * E.g. a repetition of one hour will take one real hour + * every time, even in a time zone with DST. + * Leap seconds, leap days and month length + * differences will still make the intervals different. + */ + RegularIntervals = 0, + /** + * Ensure that the time at which the intervals occur stay + * at the same place in the day, local time. So e.g. + * a period of one day, starting at 8:05AM Europe/Amsterdam time + * will always start at 8:05 Europe/Amsterdam. This means that + * in UTC time, some intervals will be 25 hours and some + * 23 hours during DST changes. + * Another example: an hourly interval will be hourly in local time, + * skipping an hour in UTC for a DST backward change. + */ + RegularLocalTime = 1, + } + /** + * Convert a PeriodDst to a string: "regular intervals" or "regular local time" + */ + export function periodDstToString(p: PeriodDst): string; + /** + * Repeating time period: consists of a starting point and + * a time length. This class accounts for leap seconds and leap days. + */ + export class Period { + /** + * Constructor + * LIMITATION: if dst equals RegularLocalTime, and unit is Second, Minute or Hour, + * then the amount must be a factor of 24. So 120 seconds is allowed while 121 seconds is not. + * This is due to the enormous processing power required by these cases. They are not + * implemented and you will get an assert. + * + * @param start The start of the period. If the period is in Months or Years, and + * the day is 29 or 30 or 31, the results are maximised to end-of-month. + * @param amount The amount of units. + * @param unit The unit. + * @param dst Specifies how to handle Daylight Saving Time. Not relevant + * if the time zone of the start datetime does not have DST. + */ + constructor(start: DateTime, amount: number, unit: TimeUnit, dst: PeriodDst); + /** + * The start date + */ + start(): DateTime; + /** + * The amount of units + */ + amount(): number; + /** + * The unit + */ + unit(): TimeUnit; + /** + * The dst handling mode + */ + dst(): PeriodDst; + /** + * The first occurrence of the period greater than + * the given date. The given date need not be at a period boundary. + * Pre: the fromdate and startdate must either both have timezones or not + * @param fromDate: the date after which to return the next date + * @return the first date matching the period after fromDate, given + * in the same zone as the fromDate. + */ + findFirst(fromDate: DateTime): DateTime; + /** + * Returns the next timestamp in the period. The given timestamp must + * be at a period boundary, otherwise the answer is incorrect. + * This function has MUCH better performance than findFirst. + * Returns the datetime "count" times away from the given datetime. + * @param prev Boundary date. Must have a time zone (any time zone) iff the period start date has one. + * @param count Optional, must be >= 1 and whole. + * @return (prev + count * period), in the same timezone as prev. + */ + findNext(prev: DateTime, count?: number): DateTime; + /** + * Returns an ISO duration string + * P[n]Y[n]M[n]DT[n]H[n]M[n][.n]S or P[n]W + */ + toIsoString(): string; + /** + * A string representation e.g. + * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam keeping regular intervals". + */ + toString(): string; + } +} + diff --git a/timezonecomplete/timezonecomplete-tests.ts b/timezonecomplete/timezonecomplete-tests.ts new file mode 100644 index 0000000000..142b3f25af --- /dev/null +++ b/timezonecomplete/timezonecomplete-tests.ts @@ -0,0 +1,174 @@ +/// + +import tc = require("timezonecomplete"); + +var b: boolean = tc.isLeapYear(2014); +var n: number = tc.daysInMonth(2014, 10); +var s: string = tc.isoString(2014, 6, 30, 22, 10, 11, 230); + +// DURATION + +var d: tc.Duration; +var d1: tc.Duration = tc.Duration.hours(24); +var d2: tc.Duration = tc.Duration.minutes(24); +var d3: tc.Duration = tc.Duration.seconds(24); +var d4: tc.Duration = tc.Duration.milliseconds(24); +var d5: tc.Duration = new tc.Duration(24); +var d6: tc.Duration = new tc.Duration("00:01"); +var d7: tc.Duration = d6.clone(); + +n = d7.wholeHours(); +n = d7.hours(); +n = d7.minutes(); +n = d7.minute(); +n = d7.seconds(); +n = d7.second(); +n = d7.milliseconds(); +n = d7.millisecond(); +s = d7.sign(); +b = d7.lessThan(d6); +b = d7.greaterThan(d6); +d = d7.min(d6); +d = d7.max(d6); +d = d7.multiply(3); +d = d7.divide(0.3); +d = d7.add(d6); +d = d7.sub(d6); +s = d7.toString(); + +// TIMEZONE + +var t: tc.TimeZone; +var k: tc.TimeZoneKind; + +t = tc.TimeZone.local(); +t = tc.TimeZone.utc(); +t = tc.TimeZone.zone(2); +t = tc.TimeZone.zone("+01:00"); +s = t.name(); +k = t.kind(); +b = t.equals(t); +b = t.isUtc(); +n = t.offsetForUtc(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForZone(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForUtcDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.Get); +n = t.offsetForZoneDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.GetUTC); +s = t.toString(); +s = tc.TimeZone.offsetToString(2); +n = tc.TimeZone.stringToOffset("+00:01"); + +// REALTIMESOURCE + +var date: Date = (new tc.RealTimeSource()).now(); + +// DATETIME + +var dt: tc.DateTime; + +var ts: tc.TimeSource = tc.DateTime.timeSource; + +dt = tc.DateTime.nowLocal(); +dt = tc.DateTime.nowUtc(); +dt = tc.DateTime.now(tc.TimeZone.local()); +dt = new tc.DateTime(); +dt = new tc.DateTime("2014-01-01T13:05:01.123 UTC"); +dt = new tc.DateTime("2014-01-01T13:05:01.123", tc.TimeZone.utc()); +dt = new tc.DateTime(date, tc.DateFunctions.Get); +dt = new tc.DateTime(date, tc.DateFunctions.Get, tc.TimeZone.utc()); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123, tc.TimeZone.utc()); +dt = new tc.DateTime(89949284); +dt = new tc.DateTime(89949284, tc.TimeZone.utc()); +dt = dt.clone(); +t = dt.zone(); +n = dt.offset(); +n = dt.year(); +n = dt.month(); +n = dt.day(); +n = dt.hour(); +n = dt.minute(); +n = dt.second(); +n = dt.millisecond(); +n = dt.unixUtcMillis(); +n = dt.utcYear(); +n = dt.utcMonth(); +n = dt.utcDay(); +n = dt.utcHour(); +n = dt.utcMinute(); +n = dt.utcSecond(); +n = dt.utcMillisecond(); +dt.convert(tc.TimeZone.local()); +dt = dt.toZone(tc.TimeZone.utc()); +date = dt.toDate(); +dt = dt.add(tc.Duration.seconds(2)); +dt = dt.add(2, tc.TimeUnit.Year); +dt = dt.add(2, tc.TimeUnit.Month); +dt = dt.add(2, tc.TimeUnit.Week); +dt = dt.add(2, tc.TimeUnit.Day); +dt = dt.add(2, tc.TimeUnit.Hour); +dt = dt.add(2, tc.TimeUnit.Minute); +dt = dt.add(2, tc.TimeUnit.Second); +dt = dt.addLocal(2, tc.TimeUnit.Second); +dt = dt.sub(tc.Duration.seconds(2)); +dt = dt.sub(2, tc.TimeUnit.Year); +dt = dt.sub(2, tc.TimeUnit.Month); +dt = dt.sub(2, tc.TimeUnit.Week); +dt = dt.sub(2, tc.TimeUnit.Day); +dt = dt.sub(2, tc.TimeUnit.Hour); +dt = dt.sub(2, tc.TimeUnit.Minute); +dt = dt.sub(2, tc.TimeUnit.Second); +dt = dt.subLocal(2, tc.TimeUnit.Second); +d = dt.diff(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +s = dt.toIsoString(); +s = dt.toString(); +s = dt.toUtcString(); + +var wd: tc.WeekDay; +wd = dt.weekDay(); +wd = dt.utcWeekDay(); + +// PERIOD + +s = tc.periodDstToString(tc.PeriodDst.RegularIntervals); +s = tc.periodDstToString(tc.PeriodDst.RegularLocalTime); + +var p: tc.Period; + +p = new tc.Period(tc.DateTime.nowLocal(), 1, tc.TimeUnit.Hour, tc.PeriodDst.RegularLocalTime); +dt = p.start(); +n = p.amount(); +var tu: tc.TimeUnit = p.unit(); +var pd: tc.PeriodDst = p.dst(); +dt = p.findFirst(tc.DateTime.nowLocal()); +dt = p.findNext(dt); +s = p.toIsoString(); +s = p.toString(); + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/timezonecomplete/timezonecomplete.d.ts b/timezonecomplete/timezonecomplete.d.ts new file mode 100644 index 0000000000..6fbea6f6f3 --- /dev/null +++ b/timezonecomplete/timezonecomplete.d.ts @@ -0,0 +1,702 @@ +// Type definitions for timezonecomplete 1.3.0 +// Project: https://github.com/SpiritIT/timezonecomplete +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Generated by dts-bundle v0.2.0 + +declare module 'timezonecomplete' { + /** + * @return True iff the given year is a leap year. + */ + export function isLeapYear(year: number): boolean; + /** + * @param year The full year + * @param month The month 1-12 + * @return The number of days in the given month + */ + export function daysInMonth(year: number, month: number): number; + /** + * Returns an ISO time string. Note that months are 1-12. + */ + export function isoString(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number): string; + /** + * Time units + */ + export enum TimeUnit { + Second = 0, + Minute = 1, + Hour = 2, + Day = 3, + Week = 4, + Month = 5, + Year = 6, + } + /** + * Time duration. Create one e.g. like this: var d = Duration.hours(1). + * Note that time durations do not take leap seconds etc. into account: + * one hour is simply represented as 3600000 milliseconds. + */ + export class Duration { + /** + * Construct a time duration + * @param n Number of hours + * @return A duration of n hours + */ + static hours(n: number): Duration; + /** + * Construct a time duration + * @param n Number of minutes + * @return A duration of n minutes + */ + static minutes(n: number): Duration; + /** + * Construct a time duration + * @param n Number of seconds + * @return A duration of n seconds + */ + static seconds(n: number): Duration; + /** + * Construct a time duration + * @param n Number of milliseconds + * @return A duration of n milliseconds + */ + static milliseconds(n: number): Duration; + /** + * Construct a time duration of 0 + */ + constructor(); + /** + * Construct a time duration from a number of milliseconds + */ + constructor(milliseconds: number); + /** + * Construct a time duration from a string in format + * [-]h[:m[:s[.n]]] e.g. -01:00:30.501 + */ + constructor(input: string); + /** + * @return another instance of Duration with the same value. + */ + clone(): Duration; + /** + * The entire duration in milliseconds (negative or positive) + */ + milliseconds(): number; + /** + * The millisecond part of the duration (always positive) + * @return e.g. 400 for a -01:02:03.400 duration + */ + millisecond(): number; + /** + * The entire duration in seconds (negative or positive, fractional) + * @return e.g. 1.5 for a 1500 milliseconds duration + */ + seconds(): number; + /** + * The second part of the duration (always positive) + * @return e.g. 3 for a -01:02:03.400 duration + */ + second(): number; + /** + * The entire duration in minutes (negative or positive, fractional) + * @return e.g. 1.5 for a 90000 milliseconds duration + */ + minutes(): number; + /** + * The minute part of the duration (always positive) + * @return e.g. 2 for a -01:02:03.400 duration + */ + minute(): number; + /** + * The entire duration in hours (negative or positive, fractional) + * @return e.g. 1.5 for a 5400000 milliseconds duration + */ + hours(): number; + /** + * The hour part of the duration (always positive). + * Note that this part can exceed 23 hours, because for + * now, we do not have a days() function + * @return e.g. 25 for a -25:02:03.400 duration + */ + wholeHours(): number; + /** + * Sign + * @return "-" if the duration is negative + */ + sign(): string; + /** + * @return True iff (this < other) + */ + lessThan(other: Duration): boolean; + /** + * @return True iff this and other represent the same time duration + */ + equals(other: Duration): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: Duration): boolean; + /** + * @return The minimum (most negative) of this and other + */ + min(other: Duration): Duration; + /** + * @return The maximum (most positive) of this and other + */ + max(other: Duration): Duration; + /** + * Multiply with a fixed number. + * @return a new Duration of (this * value) + */ + multiply(value: number): Duration; + /** + * Divide by a fixed number. + * @return a new Duration of (this / value) + */ + divide(value: number): Duration; + /** + * Add a duration. + * @return a new Duration of (this + value) + */ + add(value: Duration): Duration; + /** + * Subtract a duration. + * @return a new Duration of (this - value) + */ + sub(value: Duration): Duration; + /** + * String in [-]hh:mm:ss.nnn notation. All fields are + * always present except the sign. + */ + toFullString(): string; + /** + * String in [-]hh[:mm[:ss[.nnn]]] notation. Fields are + * added as necessary + */ + toString(): string; + } + /** + * The type of time zone + */ + export enum TimeZoneKind { + /** + * Local time offset as determined by JavaScript Date class. + */ + Local = 0, + /** + * Fixed offset from UTC, without DST. + */ + Offset = 1, + /** + * IANA timezone managed through Olsen TZ database. Includes + * DST if applicable. + */ + Proper = 2, + } + /** + * Time zone. The object is immutable because it is cached: + * requesting a time zone twice yields the very same object. + * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), + * i.e. offset 90 means +01:30. + * + * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, + * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST + * applied depending on the time zone rules. + */ + export class TimeZone { + /** + * The local time zone for a given date. Note that + * the time zone varies with the date: amsterdam time for + * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 + */ + static local(): TimeZone; + /** + * The UTC time zone. + */ + static utc(): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @return The time zone with the given offset w.r.t. UTC in minutes, e.g. 90 for +01:30 + */ + static zone(offset: number): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @param s: Empty string for local time, a TZ database time zone name (e.g. Europe/Amsterdam) + * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: + * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + */ + static zone(s: string): TimeZone; + /** + * The time zone identifier. Can be an offset "-01:30" or an + * IANA time zone name "Europe/Amsterdam", or "localtime" for + * the local time zone. + */ + name(): string; + /** + * The kind of time zone (Local/Offset/Proper) + */ + kind(): TimeZoneKind; + /** + * Equality operator. Maps zero offsets and different names for UTC onto + * each other. Other time zones are not mapped onto each other. + */ + equals(other: TimeZone): boolean; + /** + * Is this zone equivalent to UTC? + */ + isUtc(): boolean; + /** + * Calculate timezone offset from a UTC time. + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time. + */ + offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Calculate timezone offset from a zone-local time (NOT a UTC time). + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time. + */ + offsetForZone(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForUtcDate(date: Date, funcs: DateFunctions): number; + /** + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForZoneDate(date: Date, funcs: DateFunctions): number; + /** + * The time zone identifier (normalized). + * Either "localtime", IANA name, or "+hh:mm" offset. + */ + toString(): string; + /** + * Convert an offset number into an offset string + * @param offset The offset in minutes from UTC e.g. 90 minutes + * @return the offset in ISO notation "+01:30" for +90 minutes + */ + static offsetToString(offset: number): string; + /** + * String to offset conversion. + * @param s Formats: "-01:00", "-0100", "-01", "Z" + * @return offset w.r.t. UTC in minutes + */ + static stringToOffset(s: string): number; + } + /** + * For testing purposes, we often need to manipulate what the current + * time is. This is an interface for a custom time source object + * so in tests you can use a custom time source. + */ + export interface TimeSource { + /** + * Return the current date+time as a javascript Date object + */ + now(): Date; + } + /** + * Default time source, returns actual time + */ + export class RealTimeSource implements TimeSource { + now(): Date; + } + /** + * Indicates how a Date object should be interpreted. + * Either we can take getYear(), getMonth() etc for our field + * values, or we can take getUTCYear() etc to do that. + */ + export enum DateFunctions { + /** + * Use the Date.getFullYear(), Date.getMonth(), ... functions. + */ + Get = 0, + /** + * Use the Date.getUTCFullYear(), Date.getUTCMonth(), ... functions. + */ + GetUTC = 1, + } + /** + * Day-of-week. Note the enum values correspond to JavaScript day-of-week: + * Sunday = 0, Monday = 1 etc + */ + export enum WeekDay { + Sunday = 0, + Monday = 1, + Tuesday = 2, + Wednesday = 3, + Thursday = 4, + Friday = 5, + Saturday = 6, + } + /** + * Our very own DateTime class which is time zone-aware + * and which can be mocked for testing purposes + */ + export class DateTime { + /** + * Actual time source in use. Setting this property allows to + * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() + * use this property for obtaining the current time. + */ + static timeSource: TimeSource; + /** + * Current date+time in local time (derived from DateTime.timeSource.now()). + */ + static nowLocal(): DateTime; + /** + * Current date+time in UTC time (derived from DateTime.timeSource.now()). + */ + static nowUtc(): DateTime; + /** + * Current date+time in the given time zone (derived from DateTime.timeSource.now()). + * @param timeZone The desired time zone. + */ + static now(timeZone: TimeZone): DateTime; + /** + * Constructor. Creates current time in local timezone. + */ + constructor(); + /** + * Constructor + * @param isoString String in ISO 8601 format. Instead of ISO time zone, + * it may include a space and then and IANA time zone. + * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) + * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) + * or "2007-04-05T12:30:40.500Z" (UTC) + * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) + * @param timeZone if given, the date in the string is assumed to be in this time zone. + * Note that it is NOT CONVERTED to the time zone. Useful + * for strings without a time zone + */ + constructor(isoString: string, timeZone?: TimeZone); + /** + * Constructor. You provide a date, then you say whether to take the + * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, + * and then you state which time zone that date is in. + * + * @param date A date object. + * @param getters Specifies which set of Date getters contains the date in the given time zone: the + * Date.getXxx() methods or the Date.getUTCXxx() methods. + * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) + */ + constructor(date: Date, getFuncs: DateFunctions, timeZone?: TimeZone); + /** + * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. + * Use the add(duration) or sub(duration) for arithmetic. + * @param year The full year (e.g. 2014) + * @param month The month [1-12] (note this deviates from JavaScript Date) + * @param day The day of the month [1-31] + * @param hour The hour of the day [0-24) + * @param minute The minute of the hour [0-59] + * @param second The second of the minute [0-59] + * @param millisecond The millisecond of the second [0-999] + * @param timeZone The time zone, or null (for unaware dates) + */ + constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, timeZone?: TimeZone); + /** + * Constructor + * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 + * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). + */ + constructor(unixTimestamp: number, timeZone?: TimeZone); + /** + * @return a copy of this object + */ + clone(): DateTime; + /** + * @return The time zone that the date is in. May be null for unaware dates. + */ + zone(): TimeZone; + /** + * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. + */ + offset(): number; + /** + * @return The full year e.g. 2014 + */ + year(): number; + /** + * @return The month 1-12 (note this deviates from JavaScript Date) + */ + month(): number; + /** + * @return The day of the month 1-31 + */ + day(): number; + /** + * @return The hour 0-23 + */ + hour(): number; + /** + * @return the minutes 0-59 + */ + minute(): number; + /** + * @return the seconds 0-59 + */ + second(): number; + /** + * @return the milliseconds 0-999 + */ + millisecond(): number; + /** + * @return the day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + weekDay(): WeekDay; + /** + * @return Milliseconds since 1970-01-01T00:00:00.000Z + */ + unixUtcMillis(): number; + /** + * @return The full year e.g. 2014 + */ + utcYear(): number; + /** + * @return The UTC month 1-12 (note this deviates from JavaScript Date) + */ + utcMonth(): number; + /** + * @return The UTC day of the month 1-31 + */ + utcDay(): number; + /** + * @return The UTC hour 0-23 + */ + utcHour(): number; + /** + * @return The UTC minutes 0-59 + */ + utcMinute(): number; + /** + * @return The UTC seconds 0-59 + */ + utcSecond(): number; + /** + * @return The UTC milliseconds 0-999 + */ + utcMillisecond(): number; + /** + * @return the UTC day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + utcWeekDay(): WeekDay; + /** + * Convert this date to the given time zone (in-place). + * Throws if this date does not have a time zone. + * @return this (for chaining) + */ + convert(zone?: TimeZone): DateTime; + /** + * Returns this date converted to the given time zone. + * Unaware dates can only be converted to unaware dates (clone) + * For unaware dates, an exception is thrown + * @param zone The new time zone. This may be null to create unaware date. + * @return The converted date + */ + toZone(zone?: TimeZone): DateTime; + /** + * Convert to JavaScript date with the zone time in the getX() methods. + * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. + */ + toDate(): Date; + /** + * Add a time duration. Note that this simply adds a number + * of milliseconds to UTC and converts back to zone(), + * so in the presence of e.g. leap seconds there may be a + * shift in the seconds field if you add an hour. + * There is not DST handling and no leap second handling. + * @return this + duration + */ + add(duration: Duration): DateTime; + /** + * Add an amount of time to UTC, taking leap seconds etc into account. + * Adding e.g. 1 hour will increment the utcHour() field + * date by one. In case of DST changes, the local hour() field + * may not increase or increase by 2 hours. So if you add a month, the + * local time may vary by an hour. There will not be a shift + * in seconds due to leap seconds. + */ + add(amount: number, unit: TimeUnit): DateTime; + /** + * Add an amount of time to the zone time, as regularly as possible. + * Adding e.g. 1 hour will increment the hour() field of the zone + * date by one. In case of DST changes, the utcHour() field may + * increase by 1 or increase by 2. Adding a day will leave the time portion + * intact. However, adding an hour around a forward DST change adds two hours, + * since there is a zone time (2AM in Holland) that does not exist. + */ + addLocal(amount: number, unit: TimeUnit): DateTime; + /** + * Same as add(-1*duration); + */ + sub(duration: Duration): DateTime; + /** + * Same as add(-1*amount, unit); + */ + sub(amount: number, unit: TimeUnit): DateTime; + /** + * Same as addLocal(-1*amount, unit); + */ + subLocal(amount: number, unit: TimeUnit): DateTime; + /** + * Time difference between two DateTimes + * @return this - other + */ + diff(other: DateTime): Duration; + /** + * @return True iff (this < other) + */ + lessThan(other: DateTime): boolean; + /** + * @return True iff (this <= other) + */ + lessEqual(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time in UTC + */ + equals(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time and + * have the same zone + */ + identical(other: DateTime): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: DateTime): boolean; + /** + * @return True iff this >= other + */ + greaterEqual(other: DateTime): boolean; + /** + * Proper ISO 8601 format string with any IANA zone converted to ISO offset + * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam + */ + toIsoString(): string; + /** + * Modified ISO 8601 format string with IANA name if applicable. + * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" + */ + toString(): string; + /** + * Modified ISO 8601 format string in UTC without time zone info + */ + toUtcString(): string; + } + /** + * Specifies how the period should repeat across the day + * during DST changes. + */ + export enum PeriodDst { + /** + * Keep repeating in similar intervals measured in UTC, + * unaffected by Daylight Saving Time. + * E.g. a repetition of one hour will take one real hour + * every time, even in a time zone with DST. + * Leap seconds, leap days and month length + * differences will still make the intervals different. + */ + RegularIntervals = 0, + /** + * Ensure that the time at which the intervals occur stay + * at the same place in the day, local time. So e.g. + * a period of one day, starting at 8:05AM Europe/Amsterdam time + * will always start at 8:05 Europe/Amsterdam. This means that + * in UTC time, some intervals will be 25 hours and some + * 23 hours during DST changes. + * Another example: an hourly interval will be hourly in local time, + * skipping an hour in UTC for a DST backward change. + */ + RegularLocalTime = 1, + } + /** + * Convert a PeriodDst to a string: "regular intervals" or "regular local time" + */ + export function periodDstToString(p: PeriodDst): string; + /** + * Repeating time period: consists of a starting point and + * a time length. This class accounts for leap seconds and leap days. + */ + export class Period { + /** + * Constructor + * LIMITATION: if dst equals RegularLocalTime, and unit is Second, Minute or Hour, + * then the amount must be a factor of 24. So 120 seconds is allowed while 121 seconds is not. + * This is due to the enormous processing power required by these cases. They are not + * implemented and you will get an assert. + * + * @param start The start of the period. If the period is in Months or Years, and + * the day is 29 or 30 or 31, the results are maximised to end-of-month. + * @param amount The amount of units. + * @param unit The unit. + * @param dst Specifies how to handle Daylight Saving Time. Not relevant + * if the time zone of the start datetime does not have DST. + */ + constructor(start: DateTime, amount: number, unit: TimeUnit, dst: PeriodDst); + /** + * The start date + */ + start(): DateTime; + /** + * The amount of units + */ + amount(): number; + /** + * The unit + */ + unit(): TimeUnit; + /** + * The dst handling mode + */ + dst(): PeriodDst; + /** + * The first occurrence of the period greater than + * the given date. The given date need not be at a period boundary. + * Pre: the fromdate and startdate must either both have timezones or not + * @param fromDate: the date after which to return the next date + * @return the first date matching the period after fromDate, given + * in the same zone as the fromDate. + */ + findFirst(fromDate: DateTime): DateTime; + /** + * Returns the next timestamp in the period. The given timestamp must + * be at a period boundary, otherwise the answer is incorrect. + * This function has MUCH better performance than findFirst. + * Returns the datetime "count" times away from the given datetime. + * @param prev Boundary date. Must have a time zone (any time zone) iff the period start date has one. + * @param count Optional, must be >= 1 and whole. + * @return (prev + count * period), in the same timezone as prev. + */ + findNext(prev: DateTime, count?: number): DateTime; + /** + * Returns an ISO duration string + * P[n]Y[n]M[n]DT[n]H[n]M[n][.n]S or P[n]W + */ + toIsoString(): string; + /** + * A string representation e.g. + * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam keeping regular intervals". + */ + toString(): string; + } +} + diff --git a/tsd.json b/tsd.json deleted file mode 100644 index 60f508161b..0000000000 --- a/tsd.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "version": "v4", - "repo": "borisyankov/DefinitelyTyped", - "ref": "master", - "path": "_infrastructure/tests/typings", - "bundle": "_infrastructure/tests/typings/tsd.d.ts", - "installed": { - "bluebird/bluebird.d.ts": { - "commit": "bac5b4311465c7052467ec315d0cbb1c640a69d6" - }, - "node/node.d.ts": { - "commit": "bac5b4311465c7052467ec315d0cbb1c640a69d6" - } - } -} diff --git a/tspromise/tspromise-test.ts b/tspromise/tspromise-test.ts new file mode 100644 index 0000000000..79903f0ce2 --- /dev/null +++ b/tspromise/tspromise-test.ts @@ -0,0 +1,21 @@ +/// + +import Promise = require('tspromise'); + +var MyFuncFunc = Promise.async((a: boolean, b: number) => { + console.log('[a] ' + a); + yield(Promise.waitAsync(1000)); + console.log('[b]' + b); +}); + +MyFuncFunc(true, 10); + +Promise.all([Promise.waitAsync(10), Promise.waitAsync(20)]).then(() => { + return new Promise((resolve, reject) => { + resolve('test'); + }); +}).then(() => { + throw (new Error()); +}).catch((e) => { + console.log(e.message); +}); \ No newline at end of file diff --git a/tspromise/tspromise.d.ts b/tspromise/tspromise.d.ts new file mode 100644 index 0000000000..0d1132ed1e --- /dev/null +++ b/tspromise/tspromise.d.ts @@ -0,0 +1,40 @@ +// Type definitions for tspromise 0.0.4 +// Project: https://github.com/soywiz/tspromise +// Definitions by: Carlos Ballesteros Velasco +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare class Thenable { + then(onFulfilled: (value: T) => Thenable, onRejected?: (error: Error) => TR): Thenable; + then(onFulfilled: (value: T) => Thenable, onRejected?: (error: Error) => void): Thenable; + then(onFulfilled: (value: T) => TR, onRejected?: (error: Error) => void): Thenable; + then(onFulfilled: (value: T) => TR, onRejected?: (error: Error) => TR): Thenable; + catch(onRejected: (error: Error) => T): Thenable; +} + +interface NodeCallback { + (err: Error, value: T): void; +} + +declare module "tspromise" { + class Promise extends Thenable { + constructor(callback: (resolve: (value?: T) => void, reject?: (error: Error) => void) => void); + static resolve(value?: T): Thenable; + static resolve(promise: Thenable): Thenable; + static reject(error: Error): Thenable; + static all(promises: Thenable[]): Thenable; + static async(callback: () => TR): () => Thenable; + static async(callback: (p1: T1) => TR): (p1: T1) => Thenable; + static async(callback: (p1: T1, p2: T2) => TR): (p1: T1, p2: T2) => Thenable; + static async(callback: (p1: T1, p2: T2, p3: T3) => TR): (p1: T1, p2: T2, p3: T3) => Thenable; + static async(callback: (p1: T1, p2: T2, p3: T3, p4: T4) => TR): (p1: T1, p2: T2, p3: T3, p4: T4) => Thenable; + static spawn(generatorFunction: () => TR): Thenable; + static rewriteFolderSync(path: string): void; + static waitAsync(time: number): Thenable<{}>; + static nfcall(obj: any, methodName: String, ...args: any[]): Thenable; + } + + export = Promise; +} + +declare function yield(promise: Thenable): T; diff --git a/twig/twig-tests.ts b/twig/twig-tests.ts new file mode 100644 index 0000000000..bf41affd1c --- /dev/null +++ b/twig/twig-tests.ts @@ -0,0 +1,45 @@ +/// + +import twig = require('twig'); + +var value: any; +var str: string; +var num: number; +var bool: boolean; + +var params: twig.Parameters = { + id: value, + ref: value, + href: value, + path: value, + debug: bool, + trace: bool, + strict_variables: bool, + data: value +}; + +var temp: twig.Template; +var compOpts: twig.CompileOptions = { + filename: str, + settings: value +}; + +var compiled:(context: any) => any; + +temp = twig.twig(params); +twig.extendFilter(str, (left: any, ...params: any[]) => { + return str; +}); +twig.extendFunction(str, (...params: any[]) => { + return str; +}); +twig.extendTest(str, (value: any) => bool); +twig.extendTag(value); +compiled = twig.compile(str, compOpts); +twig.renderFile(str, compOpts, (err, result) => { + +}); +twig.__express(str, compOpts, (err, result) => { + +}); +twig.cache(bool); diff --git a/twig/twig.d.ts b/twig/twig.d.ts new file mode 100644 index 0000000000..0ce655272f --- /dev/null +++ b/twig/twig.d.ts @@ -0,0 +1,37 @@ +// Type definitions for twig +// Project: https://github.com/justjohn/twig.js +// Definitions by: Carlos Ballesteros Velasco +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/twig.d.ts + +declare module "twig" { + export interface Parameters { + id?: any; + ref?: any; + href?: any; + path?: any; + debug?: boolean; + trace?: boolean; + strict_variables?: boolean; + data: any; + } + + export interface Template { + } + + export interface CompileOptions { + filename: string; + settings: any; + } + + export function twig(params: Parameters): Template; + export function extendFilter(name: string, definition: (left: any, ...params: any[]) => string): void; + export function extendFunction(name: string, definition: (...params: any[]) => string): void; + export function extendTest(name: string, definition: (value: any) => boolean): void; + export function extendTag(definition: any): void; + export function compile(markup: string, options: CompileOptions): (context: any) => any; + export function renderFile(path: string, options: CompileOptions, fn: (err: Error, result: any) => void): void; + export function __express(path: string, options: CompileOptions, fn: (err: Error, result: any) => void): void; + export function cache(value: boolean): void; +} diff --git a/type-detect/type-detect-tests.ts b/type-detect/type-detect-tests.ts new file mode 100644 index 0000000000..b747de2b98 --- /dev/null +++ b/type-detect/type-detect-tests.ts @@ -0,0 +1,20 @@ +/// + +import td = require('type-detect'); + +var str: string; +var bool: boolean; +var x: any; + +str = td(123); + +var lib: td.Library = new td.Library(); + +lib.define(str, /aa/); +lib.define(str, (val) => { + return bool; +}); +str = lib.of(x); +bool = lib.test(x, str); + + diff --git a/type-detect/type-detect.d.ts b/type-detect/type-detect.d.ts new file mode 100644 index 0000000000..be31896715 --- /dev/null +++ b/type-detect/type-detect.d.ts @@ -0,0 +1,18 @@ +// Type definitions for type-detect v0.1.2 +// Project: https://github.com/chaijs/type-detect +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'type-detect' { + function type(val: any): string; + + module type { + export class Library { + of(val: any): string; + define (type: string, test: RegExp): void; + define (type: string, test: (val: any) => boolean): void; + test (val: any, type: string): boolean; + } + } + export = type; +} diff --git a/typeahead/typeahead-tests.ts b/typeahead/typeahead-tests.ts index 67fc8d31a3..1044fe3bff 100644 --- a/typeahead/typeahead-tests.ts +++ b/typeahead/typeahead-tests.ts @@ -85,3 +85,8 @@ $('.example-countries .typeahead').typeahead({ prefetch: '../data/countries.json', limit: 10 }); + +module valueTest { + var value: string = $('foo').typeahead('val'); + $('foo').typeahead('val', value); +} \ No newline at end of file diff --git a/typeahead/typeahead.d.ts b/typeahead/typeahead.d.ts index f6f387986b..bb8aaf31dc 100644 --- a/typeahead/typeahead.d.ts +++ b/typeahead/typeahead.d.ts @@ -60,6 +60,17 @@ interface JQuery { * @param dataset Array of datasets */ typeahead(options: Twitter.Typeahead.Options, dataset: Twitter.Typeahead.Dataset): JQuery; + + /** + * Returns the current value of the typeahead. The value is the text the user has entered into the input element. + */ + typeahead(methodName: 'val'): string; + typeahead(methodName: string): string; + + /** + * Sets the value of the typeahead. This should be used in place of jQuery#val. + */ + typeahead(methodName: 'val', value: string): JQuery; } declare module Twitter.Typeahead { diff --git a/typescript-services/typescriptServices-tests.ts b/typescript-services/typescriptServices-tests.ts new file mode 100644 index 0000000000..ab0da7a092 --- /dev/null +++ b/typescript-services/typescriptServices-tests.ts @@ -0,0 +1,8 @@ +/// + +import ts = require('typescript-services'); + +// formatter: +var snapshot = ts.SimpleText.fromString('var foo = 123;'); +var formatter = new ts.Services.Formatting.TextSnapshot(snapshot); +console.log(formatter); diff --git a/typescript-services/typescriptServices.d.ts b/typescript-services/typescriptServices.d.ts new file mode 100644 index 0000000000..25f174b43b --- /dev/null +++ b/typescript-services/typescriptServices.d.ts @@ -0,0 +1,9320 @@ +// Type definitions for TypeScript-Services +// Project: https://www.npmjs.org/package/typescript-services +// Definitions by: Basarat Ali Syed +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module TypeScript { + var DiagnosticCode: { + error_TS_0_1: string; + warning_TS_0_1: string; + Unrecognized_escape_sequence: string; + Unexpected_character_0: string; + Missing_close_quote_character: string; + Identifier_expected: string; + _0_keyword_expected: string; + _0_expected: string; + Identifier_expected_0_is_a_keyword: string; + Automatic_semicolon_insertion_not_allowed: string; + Unexpected_token_0_expected: string; + Trailing_separator_not_allowed: string; + AsteriskSlash_expected: string; + public_or_private_modifier_must_precede_static: string; + Unexpected_token: string; + Catch_clause_parameter_cannot_have_a_type_annotation: string; + Rest_parameter_must_be_last_in_list: string; + Parameter_cannot_have_question_mark_and_initializer: string; + Required_parameter_cannot_follow_optional_parameter: string; + Index_signatures_cannot_have_rest_parameters: string; + Index_signature_parameter_cannot_have_accessibility_modifiers: string; + Index_signature_parameter_cannot_have_a_question_mark: string; + Index_signature_parameter_cannot_have_an_initializer: string; + Index_signature_must_have_a_type_annotation: string; + Index_signature_parameter_must_have_a_type_annotation: string; + Index_signature_parameter_type_must_be_string_or_number: string; + extends_clause_already_seen: string; + extends_clause_must_precede_implements_clause: string; + Classes_can_only_extend_a_single_class: string; + implements_clause_already_seen: string; + Accessibility_modifier_already_seen: string; + _0_modifier_must_precede_1_modifier: string; + _0_modifier_already_seen: string; + _0_modifier_cannot_appear_on_a_class_element: string; + Interface_declaration_cannot_have_implements_clause: string; + super_invocation_cannot_have_type_arguments: string; + Only_ambient_modules_can_use_quoted_names: string; + Statements_are_not_allowed_in_ambient_contexts: string; + Implementations_are_not_allowed_in_ambient_contexts: string; + declare_modifier_not_allowed_for_code_already_in_an_ambient_context: string; + Initializers_are_not_allowed_in_ambient_contexts: string; + Parameter_property_declarations_can_only_be_used_in_a_non_ambient_constructor_declaration: string; + Function_implementation_expected: string; + Constructor_implementation_expected: string; + Function_overload_name_must_be_0: string; + _0_modifier_cannot_appear_on_a_module_element: string; + declare_modifier_cannot_appear_on_an_interface_declaration: string; + declare_modifier_required_for_top_level_element: string; + Rest_parameter_cannot_be_optional: string; + Rest_parameter_cannot_have_an_initializer: string; + set_accessor_must_have_one_and_only_one_parameter: string; + set_accessor_parameter_cannot_be_optional: string; + set_accessor_parameter_cannot_have_an_initializer: string; + set_accessor_cannot_have_rest_parameter: string; + get_accessor_cannot_have_parameters: string; + Modifiers_cannot_appear_here: string; + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: string; + Class_name_cannot_be_0: string; + Interface_name_cannot_be_0: string; + Enum_name_cannot_be_0: string; + Module_name_cannot_be_0: string; + Enum_member_must_have_initializer: string; + Export_assignment_cannot_be_used_in_internal_modules: string; + Export_assignment_not_allowed_in_module_with_exported_element: string; + Module_cannot_have_multiple_export_assignments: string; + Ambient_enum_elements_can_only_have_integer_literal_initializers: string; + module_class_interface_enum_import_or_statement: string; + constructor_function_accessor_or_variable: string; + statement: string; + case_or_default_clause: string; + identifier: string; + call_construct_index_property_or_function_signature: string; + expression: string; + type_name: string; + property_or_accessor: string; + parameter: string; + type: string; + type_parameter: string; + declare_modifier_not_allowed_on_import_declaration: string; + Function_overload_must_be_static: string; + Function_overload_must_not_be_static: string; + Parameter_property_declarations_cannot_be_used_in_a_constructor_overload: string; + Invalid_reference_directive_syntax: string; + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: string; + Accessors_are_not_allowed_in_ambient_contexts: string; + _0_modifier_cannot_appear_on_a_constructor_declaration: string; + _0_modifier_cannot_appear_on_a_parameter: string; + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: string; + Type_parameters_cannot_appear_on_a_constructor_declaration: string; + Type_annotation_cannot_appear_on_a_constructor_declaration: string; + Duplicate_identifier_0: string; + The_name_0_does_not_exist_in_the_current_scope: string; + The_name_0_does_not_refer_to_a_value: string; + super_can_only_be_used_inside_a_class_instance_method: string; + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_property_or_indexer: string; + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: string; + Value_of_type_0_is_not_callable: string; + Value_of_type_0_is_not_newable: string; + Value_of_type_0_is_not_indexable_by_type_1: string; + Operator_0_cannot_be_applied_to_types_1_and_2: string; + Operator_0_cannot_be_applied_to_types_1_and_2_3: string; + Cannot_convert_0_to_1: string; + Cannot_convert_0_to_1_NL_2: string; + Expected_var_class_interface_or_module: string; + Operator_0_cannot_be_applied_to_type_1: string; + Getter_0_already_declared: string; + Setter_0_already_declared: string; + Exported_class_0_extends_private_class_1: string; + Exported_class_0_implements_private_interface_1: string; + Exported_interface_0_extends_private_interface_1: string; + Exported_class_0_extends_class_from_inaccessible_module_1: string; + Exported_class_0_implements_interface_from_inaccessible_module_1: string; + Exported_interface_0_extends_interface_from_inaccessible_module_1: string; + Public_static_property_0_of_exported_class_has_or_is_using_private_type_1: string; + Public_property_0_of_exported_class_has_or_is_using_private_type_1: string; + Property_0_of_exported_interface_has_or_is_using_private_type_1: string; + Exported_variable_0_has_or_is_using_private_type_1: string; + Public_static_property_0_of_exported_class_is_using_inaccessible_module_1: string; + Public_property_0_of_exported_class_is_using_inaccessible_module_1: string; + Property_0_of_exported_interface_is_using_inaccessible_module_1: string; + Exported_variable_0_is_using_inaccessible_module_1: string; + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_type_1: string; + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_type_1: string; + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_type_1: string; + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1: string; + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1: string; + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1: string; + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1: string; + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1: string; + Parameter_0_of_exported_function_has_or_is_using_private_type_1: string; + Parameter_0_of_constructor_from_exported_class_is_using_inaccessible_module_1: string; + Parameter_0_of_public_static_property_setter_from_exported_class_is_using_inaccessible_module_1: string; + Parameter_0_of_public_property_setter_from_exported_class_is_using_inaccessible_module_1: string; + Parameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1: string; + Parameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1: string; + Parameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1: string; + Parameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1: string; + Parameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1: string; + Parameter_0_of_exported_function_is_using_inaccessible_module_1: string; + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_type_0: string; + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_type_0: string; + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_0: string; + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_type_0: string; + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_type_0: string; + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_type_0: string; + Return_type_of_public_method_from_exported_class_has_or_is_using_private_type_0: string; + Return_type_of_method_from_exported_interface_has_or_is_using_private_type_0: string; + Return_type_of_exported_function_has_or_is_using_private_type_0: string; + Return_type_of_public_static_property_getter_from_exported_class_is_using_inaccessible_module_0: string; + Return_type_of_public_property_getter_from_exported_class_is_using_inaccessible_module_0: string; + Return_type_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_0: string; + Return_type_of_call_signature_from_exported_interface_is_using_inaccessible_module_0: string; + Return_type_of_index_signature_from_exported_interface_is_using_inaccessible_module_0: string; + Return_type_of_public_static_method_from_exported_class_is_using_inaccessible_module_0: string; + Return_type_of_public_method_from_exported_class_is_using_inaccessible_module_0: string; + Return_type_of_method_from_exported_interface_is_using_inaccessible_module_0: string; + Return_type_of_exported_function_is_using_inaccessible_module_0: string; + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: string; + A_parameter_list_must_follow_a_generic_type_argument_list_expected: string; + Multiple_constructor_implementations_are_not_allowed: string; + Unable_to_resolve_external_module_0: string; + Module_cannot_be_aliased_to_a_non_module_type: string; + A_class_may_only_extend_another_class: string; + A_class_may_only_implement_another_class_or_interface: string; + An_interface_may_only_extend_another_class_or_interface: string; + Unable_to_resolve_type: string; + Unable_to_resolve_type_of_0: string; + Unable_to_resolve_type_parameter_constraint: string; + Type_parameter_constraint_cannot_be_a_primitive_type: string; + Supplied_parameters_do_not_match_any_signature_of_call_target: string; + Supplied_parameters_do_not_match_any_signature_of_call_target_NL_0: string; + Invalid_new_expression: string; + Call_signatures_used_in_a_new_expression_must_have_a_void_return_type: string; + Could_not_select_overload_for_new_expression: string; + Type_0_does_not_satisfy_the_constraint_1_for_type_parameter_2: string; + Could_not_select_overload_for_call_expression: string; + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: string; + Calls_to_super_are_only_valid_inside_a_class: string; + Generic_type_0_requires_1_type_argument_s: string; + Type_of_array_literal_cannot_be_determined_Best_common_type_could_not_be_found_for_array_elements: string; + Could_not_find_enclosing_symbol_for_dotted_name_0: string; + The_property_0_does_not_exist_on_value_of_type_1: string; + Could_not_find_symbol_0: string; + get_and_set_accessor_must_have_the_same_type: string; + this_cannot_be_referenced_in_current_location: string; + Static_members_cannot_reference_class_type_parameters: string; + Class_0_is_recursively_referenced_as_a_base_type_of_itself: string; + Interface_0_is_recursively_referenced_as_a_base_type_of_itself: string; + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: string; + super_cannot_be_referenced_in_non_derived_classes: string; + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: string; + Constructors_for_derived_classes_must_contain_a_super_call: string; + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: string; + _0_1_is_inaccessible: string; + this_cannot_be_referenced_within_module_bodies: string; + Invalid_expression_types_not_known_to_support_the_addition_operator: string; + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: string; + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: string; + The_type_of_a_unary_arithmetic_operation_operand_must_be_of_type_any_number_or_an_enum_type: string; + Variable_declarations_of_a_for_statement_cannot_use_a_type_annotation: string; + Variable_declarations_of_a_for_statement_must_be_of_types_string_or_any: string; + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: string; + The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number: string; + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: string; + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: string; + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: string; + Setters_cannot_return_a_value: string; + Tried_to_query_type_of_uninitialized_module_0: string; + Tried_to_set_variable_type_to_uninitialized_module_type_0: string; + Type_0_does_not_have_type_parameters: string; + Getters_must_return_a_value: string; + Getter_and_setter_accessors_do_not_agree_in_visibility: string; + Invalid_left_hand_side_of_assignment_expression: string; + Function_declared_a_non_void_return_type_but_has_no_return_expression: string; + Cannot_resolve_return_type_reference: string; + Constructors_cannot_have_a_return_type_of_void: string; + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: string; + All_symbols_within_a_with_block_will_be_resolved_to_any: string; + Import_declarations_in_an_internal_module_cannot_reference_an_external_module: string; + Class_0_declares_interface_1_but_does_not_implement_it_NL_2: string; + Class_0_declares_class_1_as_an_interface_but_does_not_implement_it_NL_2: string; + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: string; + this_cannot_be_referenced_in_static_initializers_in_a_class_body: string; + Class_0_cannot_extend_class_1_NL_2: string; + Interface_0_cannot_extend_class_1_NL_2: string; + Interface_0_cannot_extend_interface_1_NL_2: string; + Duplicate_overload_signature_for_0: string; + Duplicate_constructor_overload_signature: string; + Duplicate_overload_call_signature: string; + Duplicate_overload_construct_signature: string; + Overload_signature_is_not_compatible_with_function_definition: string; + Overload_signature_is_not_compatible_with_function_definition_NL_0: string; + Overload_signatures_must_all_be_public_or_private: string; + Overload_signatures_must_all_be_exported_or_not_exported: string; + Overload_signatures_must_all_be_ambient_or_non_ambient: string; + Overload_signatures_must_all_be_optional_or_required: string; + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: string; + this_cannot_be_referenced_in_constructor_arguments: string; + Instance_member_cannot_be_accessed_off_a_class: string; + Untyped_function_calls_may_not_accept_type_arguments: string; + Non_generic_functions_may_not_accept_type_arguments: string; + A_generic_type_may_not_reference_itself_with_a_wrapped_form_of_its_own_type_parameters: string; + Rest_parameters_must_be_array_types: string; + Overload_signature_implementation_cannot_use_specialized_type: string; + Export_assignments_may_only_be_used_at_the_top_level_of_external_modules: string; + Export_assignments_may_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: string; + Only_public_methods_of_the_base_class_are_accessible_via_the_super_keyword: string; + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1: string; + Numeric_indexer_type_0_must_be_assignable_to_string_indexer_type_1_NL_2: string; + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0: string; + All_numerically_named_properties_must_be_assignable_to_numeric_indexer_type_0_NL_1: string; + All_named_properties_must_be_assignable_to_string_indexer_type_0: string; + All_named_properties_must_be_assignable_to_string_indexer_type_0_NL_1: string; + Generic_type_references_must_include_all_type_arguments: string; + Default_arguments_are_only_allowed_in_implementation: string; + Overloads_cannot_differ_only_by_return_type: string; + Function_expression_declared_a_non_void_return_type_but_has_no_return_expression: string; + Import_declaration_referencing_identifier_from_internal_module_can_only_be_made_with_variables_functions_classes_interfaces_enums_and_internal_modules: string; + Could_not_find_symbol_0_in_module_1: string; + Unable_to_resolve_module_reference_0: string; + Could_not_find_module_0_in_module_1: string; + Exported_import_declaration_0_is_assigned_value_with_type_that_has_or_is_using_private_type_1: string; + Exported_import_declaration_0_is_assigned_value_with_type_that_is_using_inaccessible_module_1: string; + Exported_import_declaration_0_is_assigned_type_that_has_or_is_using_private_type_1: string; + Exported_import_declaration_0_is_assigned_type_that_is_using_inaccessible_module_1: string; + Exported_import_declaration_0_is_assigned_container_that_is_or_is_using_inaccessible_module_1: string; + Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_1: string; + Internal_module_reference_0_in_import_declaration_does_not_reference_module_instance_for_1: string; + Module_0_cannot_merge_with_previous_declaration_of_1_in_a_different_file_2: string; + Interface_0_cannot_simultaneously_extend_types_1_and_2_NL_3: string; + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: string; + Ambient_external_module_declaration_cannot_be_reopened: string; + All_declarations_of_merged_declaration_0_must_be_exported_or_not_exported: string; + super_cannot_be_referenced_in_constructor_arguments: string; + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: string; + Ambient_external_module_declaration_must_be_defined_in_global_context: string; + Ambient_external_module_declaration_cannot_specify_relative_module_name: string; + Import_declaration_in_an_ambient_external_module_declaration_cannot_reference_external_module_through_relative_external_module_name: string; + Could_not_find_the_best_common_type_of_types_of_all_return_statement_expressions: string; + Import_declaration_cannot_refer_to_external_module_reference_when_noResolve_option_is_set: string; + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: string; + continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: string; + break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: string; + Jump_target_not_found: string; + Jump_target_cannot_cross_function_boundary: string; + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: string; + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: string; + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: string; + TypeParameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_type_1: string; + TypeParameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_type_1: string; + TypeParameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_type_1: string; + TypeParameter_0_of_public_method_from_exported_class_has_or_is_using_private_type_1: string; + TypeParameter_0_of_method_from_exported_interface_has_or_is_using_private_type_1: string; + TypeParameter_0_of_exported_function_has_or_is_using_private_type_1: string; + TypeParameter_0_of_constructor_signature_from_exported_interface_is_using_inaccessible_module_1: string; + TypeParameter_0_of_call_signature_from_exported_interface_is_using_inaccessible_module_1: string; + TypeParameter_0_of_public_static_method_from_exported_class_is_using_inaccessible_module_1: string; + TypeParameter_0_of_public_method_from_exported_class_is_using_inaccessible_module_1: string; + TypeParameter_0_of_method_from_exported_interface_is_using_inaccessible_module_1: string; + TypeParameter_0_of_exported_function_is_using_inaccessible_module_1: string; + TypeParameter_0_of_exported_class_has_or_is_using_private_type_1: string; + TypeParameter_0_of_exported_interface_has_or_is_using_private_type_1: string; + TypeParameter_0_of_exported_class_is_using_inaccessible_module_1: string; + TypeParameter_0_of_exported_interface_is_using_inaccessible_module_1: string; + Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter: string; + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: string; + Type_of_conditional_0_must_be_identical_to_1_or_2: string; + Type_of_conditional_0_must_be_identical_to_1_2_or_3: string; + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module: string; + Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: string; + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: string; + Parameter_0_cannot_be_referenced_in_its_initializer: string; + Duplicate_string_index_signature: string; + Duplicate_number_index_signature: string; + All_declarations_of_an_interface_must_have_identical_type_parameters: string; + Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter: string; + Type_0_is_missing_property_1_from_type_2: string; + Types_of_property_0_of_types_1_and_2_are_incompatible: string; + Types_of_property_0_of_types_1_and_2_are_incompatible_NL_3: string; + Property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2: string; + Property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2: string; + Types_0_and_1_define_property_2_as_private: string; + Call_signatures_of_types_0_and_1_are_incompatible: string; + Call_signatures_of_types_0_and_1_are_incompatible_NL_2: string; + Type_0_requires_a_call_signature_but_type_1_lacks_one: string; + Construct_signatures_of_types_0_and_1_are_incompatible: string; + Construct_signatures_of_types_0_and_1_are_incompatible_NL_2: string; + Type_0_requires_a_construct_signature_but_type_1_lacks_one: string; + Index_signatures_of_types_0_and_1_are_incompatible: string; + Index_signatures_of_types_0_and_1_are_incompatible_NL_2: string; + Call_signature_expects_0_or_fewer_parameters: string; + Could_not_apply_type_0_to_argument_1_which_is_of_type_2: string; + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: string; + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: string; + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: string; + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: string; + Types_of_static_property_0_of_class_1_and_class_2_are_incompatible: string; + Types_of_static_property_0_of_class_1_and_class_2_are_incompatible_NL_3: string; + Type_reference_cannot_refer_to_container_0: string; + Type_reference_must_refer_to_type: string; + In_enums_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_the_first_enum_element: string; + _0_overload_s: string; + Variable_declaration_cannot_have_the_same_name_as_an_import_declaration: string; + Signature_expected_0_type_arguments_got_1_instead: string; + Property_0_defined_as_optional_in_type_1_but_is_required_in_type_2: string; + Types_0_and_1_originating_in_infinitely_expanding_type_reference_do_not_refer_to_same_named_type: string; + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments: string; + Types_0_and_1_originating_in_infinitely_expanding_type_reference_have_incompatible_type_arguments_NL_2: string; + Named_properties_0_of_types_1_and_2_are_not_identical: string; + Types_of_string_indexer_of_types_0_and_1_are_not_identical: string; + Types_of_number_indexer_of_types_0_and_1_are_not_identical: string; + Type_of_number_indexer_in_type_0_is_not_assignable_to_string_indexer_type_in_type_1_NL_2: string; + Type_of_property_0_in_type_1_is_not_assignable_to_string_indexer_type_in_type_2_NL_3: string; + Type_of_property_0_in_type_1_is_not_assignable_to_number_indexer_type_in_type_2_NL_3: string; + Static_property_0_defined_as_private_in_type_1_is_defined_as_public_in_type_2: string; + Static_property_0_defined_as_public_in_type_1_is_defined_as_private_in_type_2: string; + Types_0_and_1_define_static_property_2_as_private: string; + Current_host_does_not_support_0_option: string; + ECMAScript_target_version_0_not_supported_Specify_a_valid_target_version_1_default_or_2: string; + Module_code_generation_0_not_supported: string; + Could_not_find_file_0: string; + A_file_cannot_have_a_reference_to_itself: string; + Cannot_resolve_referenced_file_0: string; + Cannot_find_the_common_subdirectory_path_for_the_input_files: string; + Emit_Error_0: string; + Cannot_read_file_0_1: string; + Unsupported_file_encoding: string; + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: string; + Unsupported_locale_0: string; + Execution_Failed_NL: string; + Invalid_call_to_up: string; + Invalid_call_to_down: string; + Base64_value_0_finished_with_a_continuation_bit: string; + Unknown_option_0: string; + Expected_0_arguments_to_message_got_1_instead: string; + Expected_the_message_0_to_have_1_arguments_but_it_had_2: string; + Could_not_delete_file_0: string; + Could_not_create_directory_0: string; + Error_while_executing_file_0: string; + Cannot_compile_external_modules_unless_the_module_flag_is_provided: string; + Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: string; + Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: string; + Options_mapRoot_and_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: string; + Option_0_specified_without_1: string; + codepage_option_not_supported_on_current_platform: string; + Concatenate_and_emit_output_to_single_file: string; + Generates_corresponding_0_file: string; + Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: string; + Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: string; + Watch_input_files: string; + Redirect_output_structure_to_the_directory: string; + Do_not_emit_comments_to_output: string; + Skip_resolution_and_preprocessing: string; + Specify_ECMAScript_target_version_0_default_or_1: string; + Specify_module_code_generation_0_or_1: string; + Print_this_message: string; + Print_the_compiler_s_version_0: string; + Allow_use_of_deprecated_0_keyword_when_referencing_an_external_module: string; + Specify_locale_for_errors_and_messages_For_example_0_or_1: string; + Syntax_0: string; + options: string; + file1: string; + Examples: string; + Options: string; + Insert_command_line_options_and_files_from_a_file: string; + Version_0: string; + Use_the_0_flag_to_see_options: string; + NL_Recompiling_0: string; + STRING: string; + KIND: string; + file2: string; + VERSION: string; + LOCATION: string; + DIRECTORY: string; + NUMBER: string; + Specify_the_codepage_to_use_when_opening_source_files: string; + Additional_locations: string; + This_version_of_the_Javascript_runtime_does_not_support_the_0_function: string; + Unknown_rule: string; + Invalid_line_number_0: string; + Warn_on_expressions_and_declarations_with_an_implied_any_type: string; + Variable_0_implicitly_has_an_any_type: string; + Parameter_0_of_1_implicitly_has_an_any_type: string; + Parameter_0_of_function_type_implicitly_has_an_any_type: string; + Member_0_of_object_type_implicitly_has_an_any_type: string; + new_expression_which_lacks_a_constructor_signature_implicitly_has_an_any_type: string; + _0_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: string; + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: string; + Parameter_0_of_lambda_function_implicitly_has_an_any_type: string; + Constructor_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: string; + Lambda_Function_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: string; + Array_Literal_implicitly_has_an_any_type_from_widening: string; + _0_which_lacks_get_accessor_and_parameter_type_annotation_on_set_accessor_implicitly_has_an_any_type: string; + Index_signature_of_object_type_implicitly_has_an_any_type: string; + Object_literal_s_property_0_implicitly_has_an_any_type_from_widening: string; + }; +} +declare module TypeScript { + class ArrayUtilities { + static isArray(value: any): boolean; + static sequenceEquals(array1: T[], array2: T[], equals: (v1: T, v2: T) => boolean): boolean; + static contains(array: T[], value: T): boolean; + static groupBy(array: T[], func: (v: T) => string): any; + static distinct(array: T[], equalsFn?: (a: T, b: T) => boolean): T[]; + static min(array: T[], func: (v: T) => number): number; + static max(array: T[], func: (v: T) => number): number; + static last(array: T[]): T; + static lastOrDefault(array: T[], predicate: (v: T, index: number) => boolean): T; + static firstOrDefault(array: T[], func: (v: T, index: number) => boolean): T; + static first(array: T[], func?: (v: T, index: number) => boolean): T; + static sum(array: T[], func: (v: T) => number): number; + static select(values: T[], func: (v: T) => S): S[]; + static where(values: T[], func: (v: T) => boolean): T[]; + static any(array: T[], func: (v: T) => boolean): boolean; + static all(array: T[], func: (v: T) => boolean): boolean; + static binarySearch(array: number[], value: number): number; + static createArray(length: number, defaultValue: any): T[]; + static grow(array: T[], length: number, defaultValue: T): void; + static copy(sourceArray: T[], sourceIndex: number, destinationArray: T[], destinationIndex: number, length: number): void; + static indexOf(array: T[], predicate: (v: T) => boolean): number; + } +} +declare module TypeScript { + interface IBitVector { + valueAt(index: number): boolean; + setValueAt(index: number, value: boolean): void; + release(): void; + } + module BitVector { + function getBitVector(allowUndefinedValues: boolean): IBitVector; + } +} +declare module TypeScript { + interface IBitMatrix { + valueAt(x: number, y: number): boolean; + setValueAt(x: number, y: number, value: boolean): void; + release(): void; + } + module BitMatrix { + function getBitMatrix(allowUndefinedValues: boolean): IBitMatrix; + } +} +declare module TypeScript { + enum Constants { + Max31BitInteger = 1073741823, + Min31BitInteger = -1073741824, + } +} +declare module TypeScript { + enum AssertionLevel { + None = 0, + Normal = 1, + Aggressive = 2, + VeryAggressive = 3, + } + class Debug { + private static currentAssertionLevel; + static shouldAssert(level: AssertionLevel): boolean; + static assert(expression: any, message?: string, verboseDebugInfo?: () => string): void; + static fail(message?: string): void; + } +} +declare module TypeScript { + var LocalizedDiagnosticMessages: IIndexable; + class Location { + private _fileName; + private _lineMap; + private _start; + private _length; + constructor(fileName: string, lineMap: LineMap, start: number, length: number); + public fileName(): string; + public lineMap(): LineMap; + public line(): number; + public character(): number; + public start(): number; + public length(): number; + static equals(location1: Location, location2: Location): boolean; + } + class Diagnostic extends Location { + private _diagnosticKey; + private _arguments; + private _additionalLocations; + constructor(fileName: string, lineMap: LineMap, start: number, length: number, diagnosticKey: string, _arguments?: any[], additionalLocations?: Location[]); + public toJSON(key: any): any; + public diagnosticKey(): string; + public arguments(): any[]; + public text(): string; + public message(): string; + public additionalLocations(): Location[]; + static equals(diagnostic1: Diagnostic, diagnostic2: Diagnostic): boolean; + public info(): DiagnosticInfo; + } + function newLine(): string; + function getLocalizedText(diagnosticKey: string, args: any[]): string; + function getDiagnosticMessage(diagnosticKey: string, args: any[]): string; +} +declare module TypeScript { + interface DiagnosticInfo { + category: DiagnosticCategory; + message: string; + code: number; + } +} +declare module TypeScript { + class Errors { + static argument(argument: string, message?: string): Error; + static argumentOutOfRange(argument: string): Error; + static argumentNull(argument: string): Error; + static abstract(): Error; + static notYetImplemented(): Error; + static invalidOperation(message?: string): Error; + } +} +declare module TypeScript { + class Hash { + private static FNV_BASE; + private static FNV_PRIME; + private static computeFnv1aCharArrayHashCode(text, start, len); + static computeSimple31BitCharArrayHashCode(key: number[], start: number, len: number): number; + static computeSimple31BitStringHashCode(key: string): number; + static computeMurmur2StringHashCode(key: string, seed: number): number; + private static primes; + static getPrime(min: number): number; + static expandPrime(oldSize: number): number; + static combine(value: number, currentHash: number): number; + } +} +declare module TypeScript.Collections { + var DefaultHashTableCapacity: number; + class HashTable { + private hash; + private entries; + private count; + constructor(capacity: number, hash: (k: TKey) => number); + public set(key: TKey, value: TValue): void; + public add(key: TKey, value: TValue): void; + public containsKey(key: TKey): boolean; + public get(key: TKey): TValue; + private computeHashCode(key); + private addOrSet(key, value, throwOnExistingEntry); + private findEntry(key, hashCode); + private addEntry(key, value, hashCode); + private grow(); + } + function createHashTable(capacity?: number, hash?: (k: TKey) => number): HashTable; + function identityHashCode(value: any): number; +} +declare class Enumerator { + public atEnd(): boolean; + public moveNext(): boolean; + public item(): any; + constructor(o: any); +} +declare module TypeScript { + var nodeMakeDirectoryTime: number; + var nodeCreateBufferTime: number; + var nodeWriteFileSyncTime: number; + enum ByteOrderMark { + None = 0, + Utf8 = 1, + Utf16BigEndian = 2, + Utf16LittleEndian = 3, + } + class FileInformation { + public contents: string; + public byteOrderMark: ByteOrderMark; + constructor(contents: string, byteOrderMark: ByteOrderMark); + } + interface IEnvironment { + supportsCodePage(): boolean; + readFile(path: string, codepage: number): FileInformation; + writeFile(path: string, contents: string, writeByteOrderMark: boolean): void; + deleteFile(path: string): void; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + listFiles(path: string, re?: RegExp, options?: { + recursive?: boolean; + }): string[]; + arguments: string[]; + standardOut: ITextWriter; + currentDirectory(): string; + newLine: string; + } + var Environment: IEnvironment; +} +declare module TypeScript { + interface IIndexable { + [s: string]: T; + } +} +declare module TypeScript { + module IntegerUtilities { + function integerDivide(numerator: number, denominator: number): number; + function integerMultiplyLow32Bits(n1: number, n2: number): number; + function integerMultiplyHigh32Bits(n1: number, n2: number): number; + function isInteger(text: string): boolean; + function isHexInteger(text: string): boolean; + } +} +declare module TypeScript { + interface Iterator { + moveNext(): boolean; + current(): T; + } +} +declare module TypeScript { + interface ILineAndCharacter { + line: number; + character: number; + } +} +declare module TypeScript { + class LineMap { + private _computeLineStarts; + private length; + static empty: LineMap; + private _lineStarts; + constructor(_computeLineStarts: () => number[], length: number); + public toJSON(key: any): { + lineStarts: number[]; + length: number; + }; + public equals(other: LineMap): boolean; + public lineStarts(): number[]; + public lineCount(): number; + public getPosition(line: number, character: number): number; + public getLineNumberFromPosition(position: number): number; + public getLineStartPosition(lineNumber: number): number; + public fillLineAndCharacterFromPosition(position: number, lineAndCharacter: ILineAndCharacter): void; + public getLineAndCharacterFromPosition(position: number): LineAndCharacter; + } +} +declare module TypeScript { + class LineAndCharacter { + private _line; + private _character; + constructor(line: number, character: number); + public line(): number; + public character(): number; + } +} +declare module TypeScript { + class MathPrototype { + static max(a: number, b: number): number; + static min(a: number, b: number): number; + } +} +declare module TypeScript.Collections { + var DefaultStringTableCapacity: number; + class StringTable { + private entries; + private count; + constructor(capacity: number); + public addCharArray(key: number[], start: number, len: number): string; + private findCharArrayEntry(key, start, len, hashCode); + private addEntry(text, hashCode); + private grow(); + private static textCharArrayEquals(text, array, start, length); + } + var DefaultStringTable: StringTable; +} +declare module TypeScript { + class StringUtilities { + static isString(value: any): boolean; + static fromCharCodeArray(array: number[]): string; + static endsWith(string: string, value: string): boolean; + static startsWith(string: string, value: string): boolean; + static copyTo(source: string, sourceIndex: number, destination: number[], destinationIndex: number, count: number): void; + static repeat(value: string, count: number): string; + static stringEquals(val1: string, val2: string): boolean; + } +} +declare module TypeScript { + class Timer { + public startTime: number; + public time: number; + public start(): void; + public end(): void; + } +} +declare module TypeScript { + enum DiagnosticCategory { + Warning = 0, + Error = 1, + Message = 2, + NoPrefix = 3, + } +} +declare module TypeScript { + var diagnosticInformationMap: IIndexable; +} +declare module TypeScript { + enum CharacterCodes { + nullCharacter = 0, + maxAsciiCharacter = 127, + lineFeed = 10, + carriageReturn = 13, + lineSeparator = 8232, + paragraphSeparator = 8233, + nextLine = 133, + space = 32, + nonBreakingSpace = 160, + enQuad = 8192, + emQuad = 8193, + enSpace = 8194, + emSpace = 8195, + threePerEmSpace = 8196, + fourPerEmSpace = 8197, + sixPerEmSpace = 8198, + figureSpace = 8199, + punctuationSpace = 8200, + thinSpace = 8201, + hairSpace = 8202, + zeroWidthSpace = 8203, + narrowNoBreakSpace = 8239, + ideographicSpace = 12288, + _ = 95, + $ = 36, + _0 = 48, + _7 = 55, + _9 = 57, + a = 97, + b = 98, + c = 99, + d = 100, + e = 101, + f = 102, + g = 103, + h = 104, + i = 105, + k = 107, + l = 108, + m = 109, + n = 110, + o = 111, + p = 112, + q = 113, + r = 114, + s = 115, + t = 116, + u = 117, + v = 118, + w = 119, + x = 120, + y = 121, + z = 122, + A = 65, + E = 69, + F = 70, + X = 88, + Z = 90, + ampersand = 38, + asterisk = 42, + at = 64, + backslash = 92, + bar = 124, + caret = 94, + closeBrace = 125, + closeBracket = 93, + closeParen = 41, + colon = 58, + comma = 44, + dot = 46, + doubleQuote = 34, + equals = 61, + exclamation = 33, + greaterThan = 62, + lessThan = 60, + minus = 45, + openBrace = 123, + openBracket = 91, + openParen = 40, + percent = 37, + plus = 43, + question = 63, + semicolon = 59, + singleQuote = 39, + slash = 47, + tilde = 126, + backspace = 8, + formFeed = 12, + byteOrderMark = 65279, + tab = 9, + verticalTab = 11, + } +} +declare module TypeScript { + interface IScriptSnapshot { + getText(start: number, end: number): string; + getLength(): number; + getLineStartPositions(): number[]; + getTextChangeRangeSinceVersion(scriptVersion: number): TextChangeRange; + } + module ScriptSnapshot { + function fromString(text: string): IScriptSnapshot; + } +} +declare module TypeScript { + interface ISimpleText { + length(): number; + copyTo(sourceIndex: number, destination: number[], destinationIndex: number, count: number): void; + substr(start: number, length: number, intern: boolean): string; + subText(span: TextSpan): ISimpleText; + charCodeAt(index: number): number; + lineMap(): LineMap; + } + interface IText extends ISimpleText { + lineCount(): number; + lines(): ITextLine[]; + charCodeAt(position: number): number; + getLineFromLineNumber(lineNumber: number): ITextLine; + getLineFromPosition(position: number): ITextLine; + getLineNumberFromPosition(position: number): number; + getLinePosition(position: number): LineAndCharacter; + toString(span?: TextSpan): string; + } +} +declare module TypeScript { + interface ITextLine { + start(): number; + end(): number; + endIncludingLineBreak(): number; + extent(): TextSpan; + extentIncludingLineBreak(): TextSpan; + toString(): string; + lineNumber(): number; + } +} +declare module TypeScript { + module LineMap1 { + function fromSimpleText(text: ISimpleText): LineMap; + function fromScriptSnapshot(scriptSnapshot: IScriptSnapshot): LineMap; + function fromString(text: string): LineMap; + } +} +declare module TypeScript.TextFactory { + function createText(value: string): IText; +} +declare module TypeScript.SimpleText { + function fromString(value: string): ISimpleText; + function fromScriptSnapshot(scriptSnapshot: IScriptSnapshot): ISimpleText; +} +declare module TypeScript.TextUtilities { + interface ICharacterSequence { + charCodeAt(index: number): number; + length: number; + } + function parseLineStarts(text: ICharacterSequence): number[]; + function getLengthOfLineBreakSlow(text: ICharacterSequence, index: number, c: number): number; + function getLengthOfLineBreak(text: ICharacterSequence, index: number): number; + function isAnyLineBreakCharacter(c: number): boolean; +} +declare module TypeScript { + class TextSpan { + private _start; + private _length; + constructor(start: number, length: number); + public start(): number; + public length(): number; + public end(): number; + public isEmpty(): boolean; + public containsPosition(position: number): boolean; + public containsTextSpan(span: TextSpan): boolean; + public overlapsWith(span: TextSpan): boolean; + public overlap(span: TextSpan): TextSpan; + public intersectsWithTextSpan(span: TextSpan): boolean; + public intersectsWith(start: number, length: number): boolean; + public intersectsWithPosition(position: number): boolean; + public intersection(span: TextSpan): TextSpan; + static fromBounds(start: number, end: number): TextSpan; + } +} +declare module TypeScript { + class TextChangeRange { + static unchanged: TextChangeRange; + private _span; + private _newLength; + constructor(span: TextSpan, newLength: number); + public span(): TextSpan; + public newLength(): number; + public newSpan(): TextSpan; + public isUnchanged(): boolean; + static collapseChangesFromSingleVersion(changes: TextChangeRange[]): TextChangeRange; + static collapseChangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; + } +} +declare module TypeScript { + class CharacterInfo { + static isDecimalDigit(c: number): boolean; + static isOctalDigit(c: number): boolean; + static isHexDigit(c: number): boolean; + static hexValue(c: number): number; + static isWhitespace(ch: number): boolean; + static isLineTerminator(ch: number): boolean; + } +} +declare module TypeScript { + enum SyntaxConstants { + TriviaNewLineMask = 1, + TriviaCommentMask = 2, + TriviaFullWidthShift = 2, + NodeDataComputed = 1, + NodeIncrementallyUnusableMask = 2, + NodeParsedInStrictModeMask = 4, + NodeFullWidthShift = 3, + IsVariableWidthKeyword = -2147483648, + } +} +declare class FormattingOptions { + public useTabs: boolean; + public spacesPerTab: number; + public indentSpaces: number; + public newLineCharacter: string; + constructor(useTabs: boolean, spacesPerTab: number, indentSpaces: number, newLineCharacter: string); + static defaultOptions: FormattingOptions; +} +declare module TypeScript.Indentation { + function columnForEndOfToken(token: ISyntaxToken, syntaxInformationMap: SyntaxInformationMap, options: FormattingOptions): number; + function columnForStartOfToken(token: ISyntaxToken, syntaxInformationMap: SyntaxInformationMap, options: FormattingOptions): number; + function columnForStartOfFirstTokenInLineContainingToken(token: ISyntaxToken, syntaxInformationMap: SyntaxInformationMap, options: FormattingOptions): number; + function columnForPositionInString(input: string, position: number, options: FormattingOptions): number; + function indentationString(column: number, options: FormattingOptions): string; + function indentationTrivia(column: number, options: FormattingOptions): ISyntaxTrivia; + function firstNonWhitespacePosition(value: string): number; +} +declare module TypeScript { + enum LanguageVersion { + EcmaScript3 = 0, + EcmaScript5 = 1, + } +} +declare module TypeScript { + class ParseOptions { + private _languageVersion; + private _allowAutomaticSemicolonInsertion; + constructor(languageVersion: LanguageVersion, allowAutomaticSemicolonInsertion: boolean); + public toJSON(key: any): { + allowAutomaticSemicolonInsertion: boolean; + }; + public languageVersion(): LanguageVersion; + public allowAutomaticSemicolonInsertion(): boolean; + } +} +declare module TypeScript { + class PositionedElement { + private _parent; + private _element; + private _fullStart; + constructor(parent: PositionedElement, element: ISyntaxElement, fullStart: number); + static create(parent: PositionedElement, element: ISyntaxElement, fullStart: number): PositionedElement; + public parent(): PositionedElement; + public parentElement(): ISyntaxElement; + public element(): ISyntaxElement; + public kind(): SyntaxKind; + public childIndex(child: ISyntaxElement): number; + public childCount(): number; + public childAt(index: number): PositionedElement; + public childStart(child: ISyntaxElement): number; + public childEnd(child: ISyntaxElement): number; + public childStartAt(index: number): number; + public childEndAt(index: number): number; + public getPositionedChild(child: ISyntaxElement): PositionedElement; + public fullStart(): number; + public fullEnd(): number; + public fullWidth(): number; + public start(): number; + public end(): number; + public root(): PositionedNode; + public containingNode(): PositionedNode; + } + class PositionedNodeOrToken extends PositionedElement { + constructor(parent: PositionedElement, nodeOrToken: ISyntaxNodeOrToken, fullStart: number); + public nodeOrToken(): ISyntaxNodeOrToken; + } + class PositionedNode extends PositionedNodeOrToken { + constructor(parent: PositionedElement, node: SyntaxNode, fullStart: number); + public node(): SyntaxNode; + } + class PositionedToken extends PositionedNodeOrToken { + constructor(parent: PositionedElement, token: ISyntaxToken, fullStart: number); + public token(): ISyntaxToken; + public previousToken(includeSkippedTokens?: boolean): PositionedToken; + public nextToken(includeSkippedTokens?: boolean): PositionedToken; + } + class PositionedList extends PositionedElement { + constructor(parent: PositionedElement, list: ISyntaxList, fullStart: number); + public list(): ISyntaxList; + } + class PositionedSeparatedList extends PositionedElement { + constructor(parent: PositionedElement, list: ISeparatedSyntaxList, fullStart: number); + public list(): ISeparatedSyntaxList; + } + class PositionedSkippedToken extends PositionedToken { + private _parentToken; + constructor(parentToken: PositionedToken, token: ISyntaxToken, fullStart: number); + public parentToken(): PositionedToken; + public previousToken(includeSkippedTokens?: boolean): PositionedToken; + public nextToken(includeSkippedTokens?: boolean): PositionedToken; + } +} +declare module TypeScript { + enum SyntaxKind { + None = 0, + List = 1, + SeparatedList = 2, + TriviaList = 3, + WhitespaceTrivia = 4, + NewLineTrivia = 5, + MultiLineCommentTrivia = 6, + SingleLineCommentTrivia = 7, + SkippedTokenTrivia = 8, + ErrorToken = 9, + EndOfFileToken = 10, + IdentifierName = 11, + RegularExpressionLiteral = 12, + NumericLiteral = 13, + StringLiteral = 14, + BreakKeyword = 15, + CaseKeyword = 16, + CatchKeyword = 17, + ContinueKeyword = 18, + DebuggerKeyword = 19, + DefaultKeyword = 20, + DeleteKeyword = 21, + DoKeyword = 22, + ElseKeyword = 23, + FalseKeyword = 24, + FinallyKeyword = 25, + ForKeyword = 26, + FunctionKeyword = 27, + IfKeyword = 28, + InKeyword = 29, + InstanceOfKeyword = 30, + NewKeyword = 31, + NullKeyword = 32, + ReturnKeyword = 33, + SwitchKeyword = 34, + ThisKeyword = 35, + ThrowKeyword = 36, + TrueKeyword = 37, + TryKeyword = 38, + TypeOfKeyword = 39, + VarKeyword = 40, + VoidKeyword = 41, + WhileKeyword = 42, + WithKeyword = 43, + ClassKeyword = 44, + ConstKeyword = 45, + EnumKeyword = 46, + ExportKeyword = 47, + ExtendsKeyword = 48, + ImportKeyword = 49, + SuperKeyword = 50, + ImplementsKeyword = 51, + InterfaceKeyword = 52, + LetKeyword = 53, + PackageKeyword = 54, + PrivateKeyword = 55, + ProtectedKeyword = 56, + PublicKeyword = 57, + StaticKeyword = 58, + YieldKeyword = 59, + AnyKeyword = 60, + BooleanKeyword = 61, + ConstructorKeyword = 62, + DeclareKeyword = 63, + GetKeyword = 64, + ModuleKeyword = 65, + RequireKeyword = 66, + NumberKeyword = 67, + SetKeyword = 68, + StringKeyword = 69, + OpenBraceToken = 70, + CloseBraceToken = 71, + OpenParenToken = 72, + CloseParenToken = 73, + OpenBracketToken = 74, + CloseBracketToken = 75, + DotToken = 76, + DotDotDotToken = 77, + SemicolonToken = 78, + CommaToken = 79, + LessThanToken = 80, + GreaterThanToken = 81, + LessThanEqualsToken = 82, + GreaterThanEqualsToken = 83, + EqualsEqualsToken = 84, + EqualsGreaterThanToken = 85, + ExclamationEqualsToken = 86, + EqualsEqualsEqualsToken = 87, + ExclamationEqualsEqualsToken = 88, + PlusToken = 89, + MinusToken = 90, + AsteriskToken = 91, + PercentToken = 92, + PlusPlusToken = 93, + MinusMinusToken = 94, + LessThanLessThanToken = 95, + GreaterThanGreaterThanToken = 96, + GreaterThanGreaterThanGreaterThanToken = 97, + AmpersandToken = 98, + BarToken = 99, + CaretToken = 100, + ExclamationToken = 101, + TildeToken = 102, + AmpersandAmpersandToken = 103, + BarBarToken = 104, + QuestionToken = 105, + ColonToken = 106, + EqualsToken = 107, + PlusEqualsToken = 108, + MinusEqualsToken = 109, + AsteriskEqualsToken = 110, + PercentEqualsToken = 111, + LessThanLessThanEqualsToken = 112, + GreaterThanGreaterThanEqualsToken = 113, + GreaterThanGreaterThanGreaterThanEqualsToken = 114, + AmpersandEqualsToken = 115, + BarEqualsToken = 116, + CaretEqualsToken = 117, + SlashToken = 118, + SlashEqualsToken = 119, + SourceUnit = 120, + QualifiedName = 121, + ObjectType = 122, + FunctionType = 123, + ArrayType = 124, + ConstructorType = 125, + GenericType = 126, + TypeQuery = 127, + InterfaceDeclaration = 128, + FunctionDeclaration = 129, + ModuleDeclaration = 130, + ClassDeclaration = 131, + EnumDeclaration = 132, + ImportDeclaration = 133, + ExportAssignment = 134, + MemberFunctionDeclaration = 135, + MemberVariableDeclaration = 136, + ConstructorDeclaration = 137, + IndexMemberDeclaration = 138, + GetAccessor = 139, + SetAccessor = 140, + PropertySignature = 141, + CallSignature = 142, + ConstructSignature = 143, + IndexSignature = 144, + MethodSignature = 145, + Block = 146, + IfStatement = 147, + VariableStatement = 148, + ExpressionStatement = 149, + ReturnStatement = 150, + SwitchStatement = 151, + BreakStatement = 152, + ContinueStatement = 153, + ForStatement = 154, + ForInStatement = 155, + EmptyStatement = 156, + ThrowStatement = 157, + WhileStatement = 158, + TryStatement = 159, + LabeledStatement = 160, + DoStatement = 161, + DebuggerStatement = 162, + WithStatement = 163, + PlusExpression = 164, + NegateExpression = 165, + BitwiseNotExpression = 166, + LogicalNotExpression = 167, + PreIncrementExpression = 168, + PreDecrementExpression = 169, + DeleteExpression = 170, + TypeOfExpression = 171, + VoidExpression = 172, + CommaExpression = 173, + AssignmentExpression = 174, + AddAssignmentExpression = 175, + SubtractAssignmentExpression = 176, + MultiplyAssignmentExpression = 177, + DivideAssignmentExpression = 178, + ModuloAssignmentExpression = 179, + AndAssignmentExpression = 180, + ExclusiveOrAssignmentExpression = 181, + OrAssignmentExpression = 182, + LeftShiftAssignmentExpression = 183, + SignedRightShiftAssignmentExpression = 184, + UnsignedRightShiftAssignmentExpression = 185, + ConditionalExpression = 186, + LogicalOrExpression = 187, + LogicalAndExpression = 188, + BitwiseOrExpression = 189, + BitwiseExclusiveOrExpression = 190, + BitwiseAndExpression = 191, + EqualsWithTypeConversionExpression = 192, + NotEqualsWithTypeConversionExpression = 193, + EqualsExpression = 194, + NotEqualsExpression = 195, + LessThanExpression = 196, + GreaterThanExpression = 197, + LessThanOrEqualExpression = 198, + GreaterThanOrEqualExpression = 199, + InstanceOfExpression = 200, + InExpression = 201, + LeftShiftExpression = 202, + SignedRightShiftExpression = 203, + UnsignedRightShiftExpression = 204, + MultiplyExpression = 205, + DivideExpression = 206, + ModuloExpression = 207, + AddExpression = 208, + SubtractExpression = 209, + PostIncrementExpression = 210, + PostDecrementExpression = 211, + MemberAccessExpression = 212, + InvocationExpression = 213, + ArrayLiteralExpression = 214, + ObjectLiteralExpression = 215, + ObjectCreationExpression = 216, + ParenthesizedExpression = 217, + ParenthesizedArrowFunctionExpression = 218, + SimpleArrowFunctionExpression = 219, + CastExpression = 220, + ElementAccessExpression = 221, + FunctionExpression = 222, + OmittedExpression = 223, + VariableDeclaration = 224, + VariableDeclarator = 225, + ArgumentList = 226, + ParameterList = 227, + TypeArgumentList = 228, + TypeParameterList = 229, + ExtendsHeritageClause = 230, + ImplementsHeritageClause = 231, + EqualsValueClause = 232, + CaseSwitchClause = 233, + DefaultSwitchClause = 234, + ElseClause = 235, + CatchClause = 236, + FinallyClause = 237, + TypeParameter = 238, + Constraint = 239, + SimplePropertyAssignment = 240, + FunctionPropertyAssignment = 241, + Parameter = 242, + EnumElement = 243, + TypeAnnotation = 244, + ExternalModuleReference = 245, + ModuleNameModuleReference = 246, + Last = 246, + FirstStandardKeyword = 15, + LastStandardKeyword = 43, + FirstFutureReservedKeyword = 44, + LastFutureReservedKeyword = 50, + FirstFutureReservedStrictKeyword = 51, + LastFutureReservedStrictKeyword = 59, + FirstTypeScriptKeyword = 60, + LastTypeScriptKeyword = 69, + FirstKeyword = 15, + LastKeyword = 69, + FirstToken = 9, + LastToken = 119, + FirstPunctuation = 70, + LastPunctuation = 119, + FirstFixedWidth = 15, + LastFixedWidth = 119, + FirstTrivia = 4, + LastTrivia = 8, + } +} +declare module TypeScript.SyntaxFacts { + function getTokenKind(text: string): SyntaxKind; + function getText(kind: SyntaxKind): string; + function isTokenKind(kind: SyntaxKind): boolean; + function isAnyKeyword(kind: SyntaxKind): boolean; + function isStandardKeyword(kind: SyntaxKind): boolean; + function isFutureReservedKeyword(kind: SyntaxKind): boolean; + function isFutureReservedStrictKeyword(kind: SyntaxKind): boolean; + function isAnyPunctuation(kind: SyntaxKind): boolean; + function isPrefixUnaryExpressionOperatorToken(tokenKind: SyntaxKind): boolean; + function isBinaryExpressionOperatorToken(tokenKind: SyntaxKind): boolean; + function getPrefixUnaryExpressionFromOperatorToken(tokenKind: SyntaxKind): SyntaxKind; + function getPostfixUnaryExpressionFromOperatorToken(tokenKind: SyntaxKind): SyntaxKind; + function getBinaryExpressionFromOperatorToken(tokenKind: SyntaxKind): SyntaxKind; + function getOperatorTokenFromBinaryExpression(tokenKind: SyntaxKind): SyntaxKind; + function isAnyDivideToken(kind: SyntaxKind): boolean; + function isAnyDivideOrRegularExpressionToken(kind: SyntaxKind): boolean; +} +declare module TypeScript { + class Scanner implements ISlidingWindowSource { + private slidingWindow; + private fileName; + private text; + private _languageVersion; + constructor(fileName: string, text: ISimpleText, languageVersion: LanguageVersion, window?: number[]); + public languageVersion(): LanguageVersion; + public fetchMoreItems(argument: any, sourceIndex: number, window: number[], destinationIndex: number, spaceAvailable: number): number; + private currentCharCode(); + public absoluteIndex(): number; + public setAbsoluteIndex(index: number): void; + public scan(diagnostics: Diagnostic[], allowRegularExpression: boolean): ISyntaxToken; + private createToken(fullStart, leadingTriviaInfo, start, kind, end, fullEnd, trailingTriviaInfo, isVariableWidthKeyword); + private static triviaWindow; + static scanTrivia(text: ISimpleText, start: number, length: number, isTrailing: boolean): ISyntaxTriviaList; + private scanTrivia(underlyingText, underlyingTextStart, isTrailing); + private scanTriviaInfo(diagnostics, isTrailing); + private isNewLineCharacter(ch); + private scanWhitespaceTrivia(underlyingText, underlyingTextStart); + private scanSingleLineCommentTrivia(underlyingText, underlyingTextStart); + private scanSingleLineCommentTriviaLength(); + private scanMultiLineCommentTrivia(underlyingText, underlyingTextStart); + private scanMultiLineCommentTriviaLength(diagnostics); + private scanLineTerminatorSequenceTrivia(ch); + private scanLineTerminatorSequenceLength(ch); + private scanSyntaxToken(diagnostics, allowRegularExpression); + private isIdentifierStart(interpretedChar); + private isIdentifierPart(interpretedChar); + private tryFastScanIdentifierOrKeyword(firstCharacter); + private slowScanIdentifierOrKeyword(diagnostics); + private scanNumericLiteral(diagnostics); + private isOctalNumericLiteral(); + private scanOctalNumericLiteral(diagnostics); + private scanDecimalDigits(); + private scanDecimalNumericLiteral(); + private scanHexNumericLiteral(); + private isHexNumericLiteral(); + private advanceAndSetTokenKind(kind); + private scanLessThanToken(); + private scanBarToken(); + private scanCaretToken(); + private scanAmpersandToken(); + private scanPercentToken(); + private scanMinusToken(); + private scanPlusToken(); + private scanAsteriskToken(); + private scanEqualsToken(); + private isDotPrefixedNumericLiteral(); + private scanDotToken(diagnostics); + private scanSlashToken(allowRegularExpression); + private tryScanRegularExpressionToken(); + private scanExclamationToken(); + private scanDefaultCharacter(character, diagnostics); + private getErrorMessageText(text); + private skipEscapeSequence(diagnostics); + private scanStringLiteral(diagnostics); + private isUnicodeEscape(character); + private peekCharOrUnicodeEscape(); + private peekUnicodeOrHexEscape(); + private scanCharOrUnicodeEscape(errors); + private scanUnicodeOrHexEscape(errors); + public substring(start: number, end: number, intern: boolean): string; + private createIllegalEscapeDiagnostic(start, end); + static isValidIdentifier(text: ISimpleText, languageVersion: LanguageVersion): boolean; + } +} +declare module TypeScript { + class ScannerUtilities { + static identifierKind(array: number[], startIndex: number, length: number): SyntaxKind; + } +} +declare module TypeScript { + interface ISeparatedSyntaxList extends ISyntaxElement { + childAt(index: number): ISyntaxNodeOrToken; + toArray(): ISyntaxNodeOrToken[]; + toNonSeparatorArray(): ISyntaxNodeOrToken[]; + separatorCount(): number; + separatorAt(index: number): ISyntaxToken; + nonSeparatorCount(): number; + nonSeparatorAt(index: number): ISyntaxNodeOrToken; + insertChildrenInto(array: ISyntaxElement[], index: number): void; + } +} +declare module TypeScript.Syntax { + var emptySeparatedList: ISeparatedSyntaxList; + function separatedList(nodes: ISyntaxNodeOrToken[]): ISeparatedSyntaxList; +} +declare module TypeScript { + interface ISlidingWindowSource { + fetchMoreItems(argument: any, sourceIndex: number, window: any[], destinationIndex: number, spaceAvailable: number): number; + } + class SlidingWindow { + private source; + public window: any[]; + private defaultValue; + private sourceLength; + public windowCount: number; + public windowAbsoluteStartIndex: number; + public currentRelativeItemIndex: number; + private _pinCount; + private firstPinnedAbsoluteIndex; + constructor(source: ISlidingWindowSource, window: any[], defaultValue: any, sourceLength?: number); + private windowAbsoluteEndIndex(); + private addMoreItemsToWindow(argument); + private tryShiftOrGrowWindow(); + public absoluteIndex(): number; + public isAtEndOfSource(): boolean; + public getAndPinAbsoluteIndex(): number; + public releaseAndUnpinAbsoluteIndex(absoluteIndex: number): void; + public rewindToPinnedIndex(absoluteIndex: number): void; + public currentItem(argument: any): any; + public peekItemN(n: number): any; + public moveToNextItem(): void; + public disgardAllItemsFromCurrentIndexOnwards(): void; + public setAbsoluteIndex(absoluteIndex: number): void; + public pinCount(): number; + } +} +declare module TypeScript { +} +declare module TypeScript.Syntax { + function emptySourceUnit(): SourceUnitSyntax; + function getStandaloneExpression(positionedToken: PositionedToken): PositionedNodeOrToken; + function isInModuleOrTypeContext(positionedToken: PositionedToken): boolean; + function isInTypeOnlyContext(positionedToken: PositionedToken): boolean; + function childOffset(parent: ISyntaxElement, child: ISyntaxElement): number; + function childOffsetAt(parent: ISyntaxElement, index: number): number; + function childIndex(parent: ISyntaxElement, child: ISyntaxElement): number; + function nodeStructuralEquals(node1: SyntaxNode, node2: SyntaxNode): boolean; + function nodeOrTokenStructuralEquals(node1: ISyntaxNodeOrToken, node2: ISyntaxNodeOrToken): boolean; + function tokenStructuralEquals(token1: ISyntaxToken, token2: ISyntaxToken): boolean; + function triviaListStructuralEquals(triviaList1: ISyntaxTriviaList, triviaList2: ISyntaxTriviaList): boolean; + function triviaStructuralEquals(trivia1: ISyntaxTrivia, trivia2: ISyntaxTrivia): boolean; + function listStructuralEquals(list1: ISyntaxList, list2: ISyntaxList): boolean; + function separatedListStructuralEquals(list1: ISeparatedSyntaxList, list2: ISeparatedSyntaxList): boolean; + function elementStructuralEquals(element1: ISyntaxElement, element2: ISyntaxElement): boolean; + function identifierName(text: string, info?: ITokenInfo): ISyntaxToken; + function trueExpression(): IUnaryExpressionSyntax; + function falseExpression(): IUnaryExpressionSyntax; + function numericLiteralExpression(text: string): IUnaryExpressionSyntax; + function stringLiteralExpression(text: string): IUnaryExpressionSyntax; + function isSuperInvocationExpression(node: IExpressionSyntax): boolean; + function isSuperInvocationExpressionStatement(node: SyntaxNode): boolean; + function isSuperMemberAccessExpression(node: IExpressionSyntax): boolean; + function isSuperMemberAccessInvocationExpression(node: SyntaxNode): boolean; + function assignmentExpression(left: IExpressionSyntax, token: ISyntaxToken, right: IExpressionSyntax): BinaryExpressionSyntax; + function nodeHasSkippedOrMissingTokens(node: SyntaxNode): boolean; + function isUnterminatedStringLiteral(token: ISyntaxToken): boolean; + function isUnterminatedMultilineCommentTrivia(trivia: ISyntaxTrivia): boolean; + function isEntirelyInsideCommentTrivia(trivia: ISyntaxTrivia, fullStart: number, position: number): boolean; + function isEntirelyInsideComment(sourceUnit: SourceUnitSyntax, position: number): boolean; + function isEntirelyInStringOrRegularExpressionLiteral(sourceUnit: SourceUnitSyntax, position: number): boolean; + function findSkippedTokenInLeadingTriviaList(positionedToken: PositionedToken, position: number): PositionedSkippedToken; + function findSkippedTokenInTrailingTriviaList(positionedToken: PositionedToken, position: number): PositionedSkippedToken; + function findSkippedTokenInPositionedToken(positionedToken: PositionedToken, position: number): PositionedSkippedToken; + function findSkippedTokenOnLeft(positionedToken: PositionedToken, position: number): PositionedSkippedToken; + function getAncestorOfKind(positionedToken: PositionedElement, kind: SyntaxKind): PositionedElement; + function hasAncestorOfKind(positionedToken: PositionedElement, kind: SyntaxKind): boolean; + function isIntegerLiteral(expression: IExpressionSyntax): boolean; +} +declare module TypeScript { + interface ISyntaxElement { + kind(): SyntaxKind; + isNode(): boolean; + isToken(): boolean; + isList(): boolean; + isSeparatedList(): boolean; + childCount(): number; + childAt(index: number): ISyntaxElement; + isTypeScriptSpecific(): boolean; + isIncrementallyUnusable(): boolean; + fullWidth(): number; + width(): number; + fullText(): string; + leadingTrivia(): ISyntaxTriviaList; + trailingTrivia(): ISyntaxTriviaList; + leadingTriviaWidth(): number; + trailingTriviaWidth(): number; + firstToken(): ISyntaxToken; + lastToken(): ISyntaxToken; + collectTextElements(elements: string[]): void; + } + interface ISyntaxNode extends ISyntaxNodeOrToken { + } + interface IModuleReferenceSyntax extends ISyntaxNode { + isModuleReference(): boolean; + } + interface IModuleElementSyntax extends ISyntaxNode { + } + interface IStatementSyntax extends IModuleElementSyntax { + isStatement(): boolean; + } + interface IIterationStatementSyntax extends IStatementSyntax { + isIterationStatement(): boolean; + } + interface ITypeMemberSyntax extends ISyntaxNode { + } + interface IClassElementSyntax extends ISyntaxNode { + } + interface IMemberDeclarationSyntax extends IClassElementSyntax { + } + interface IPropertyAssignmentSyntax extends IClassElementSyntax { + } + interface ISwitchClauseSyntax extends ISyntaxNode { + isSwitchClause(): boolean; + statements: ISyntaxList; + } + interface IExpressionSyntax extends ISyntaxNodeOrToken { + isExpression(): boolean; + withLeadingTrivia(trivia: ISyntaxTriviaList): IExpressionSyntax; + withTrailingTrivia(trivia: ISyntaxTriviaList): IExpressionSyntax; + } + interface IUnaryExpressionSyntax extends IExpressionSyntax { + isUnaryExpression(): boolean; + } + interface IArrowFunctionExpressionSyntax extends IUnaryExpressionSyntax { + isArrowFunctionExpression(): boolean; + equalsGreaterThanToken: ISyntaxToken; + block: BlockSyntax; + expression: IExpressionSyntax; + } + interface IPostfixExpressionSyntax extends IUnaryExpressionSyntax { + isPostfixExpression(): boolean; + } + interface IMemberExpressionSyntax extends IPostfixExpressionSyntax { + isMemberExpression(): boolean; + } + interface IPrimaryExpressionSyntax extends IMemberExpressionSyntax { + isPrimaryExpression(): boolean; + } + interface ITypeSyntax extends ISyntaxNodeOrToken { + } + interface INameSyntax extends ITypeSyntax { + } +} +declare module TypeScript.Syntax { + interface IFactory { + sourceUnit(moduleElements: ISyntaxList, endOfFileToken: ISyntaxToken): SourceUnitSyntax; + externalModuleReference(requireKeyword: ISyntaxToken, openParenToken: ISyntaxToken, stringLiteral: ISyntaxToken, closeParenToken: ISyntaxToken): ExternalModuleReferenceSyntax; + moduleNameModuleReference(moduleName: INameSyntax): ModuleNameModuleReferenceSyntax; + importDeclaration(modifiers: ISyntaxList, importKeyword: ISyntaxToken, identifier: ISyntaxToken, equalsToken: ISyntaxToken, moduleReference: IModuleReferenceSyntax, semicolonToken: ISyntaxToken): ImportDeclarationSyntax; + exportAssignment(exportKeyword: ISyntaxToken, equalsToken: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken): ExportAssignmentSyntax; + classDeclaration(modifiers: ISyntaxList, classKeyword: ISyntaxToken, identifier: ISyntaxToken, typeParameterList: TypeParameterListSyntax, heritageClauses: ISyntaxList, openBraceToken: ISyntaxToken, classElements: ISyntaxList, closeBraceToken: ISyntaxToken): ClassDeclarationSyntax; + interfaceDeclaration(modifiers: ISyntaxList, interfaceKeyword: ISyntaxToken, identifier: ISyntaxToken, typeParameterList: TypeParameterListSyntax, heritageClauses: ISyntaxList, body: ObjectTypeSyntax): InterfaceDeclarationSyntax; + heritageClause(kind: SyntaxKind, extendsOrImplementsKeyword: ISyntaxToken, typeNames: ISeparatedSyntaxList): HeritageClauseSyntax; + moduleDeclaration(modifiers: ISyntaxList, moduleKeyword: ISyntaxToken, name: INameSyntax, stringLiteral: ISyntaxToken, openBraceToken: ISyntaxToken, moduleElements: ISyntaxList, closeBraceToken: ISyntaxToken): ModuleDeclarationSyntax; + functionDeclaration(modifiers: ISyntaxList, functionKeyword: ISyntaxToken, identifier: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): FunctionDeclarationSyntax; + variableStatement(modifiers: ISyntaxList, variableDeclaration: VariableDeclarationSyntax, semicolonToken: ISyntaxToken): VariableStatementSyntax; + variableDeclaration(varKeyword: ISyntaxToken, variableDeclarators: ISeparatedSyntaxList): VariableDeclarationSyntax; + variableDeclarator(propertyName: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, equalsValueClause: EqualsValueClauseSyntax): VariableDeclaratorSyntax; + equalsValueClause(equalsToken: ISyntaxToken, value: IExpressionSyntax): EqualsValueClauseSyntax; + prefixUnaryExpression(kind: SyntaxKind, operatorToken: ISyntaxToken, operand: IUnaryExpressionSyntax): PrefixUnaryExpressionSyntax; + arrayLiteralExpression(openBracketToken: ISyntaxToken, expressions: ISeparatedSyntaxList, closeBracketToken: ISyntaxToken): ArrayLiteralExpressionSyntax; + omittedExpression(): OmittedExpressionSyntax; + parenthesizedExpression(openParenToken: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken): ParenthesizedExpressionSyntax; + simpleArrowFunctionExpression(identifier: ISyntaxToken, equalsGreaterThanToken: ISyntaxToken, block: BlockSyntax, expression: IExpressionSyntax): SimpleArrowFunctionExpressionSyntax; + parenthesizedArrowFunctionExpression(callSignature: CallSignatureSyntax, equalsGreaterThanToken: ISyntaxToken, block: BlockSyntax, expression: IExpressionSyntax): ParenthesizedArrowFunctionExpressionSyntax; + qualifiedName(left: INameSyntax, dotToken: ISyntaxToken, right: ISyntaxToken): QualifiedNameSyntax; + typeArgumentList(lessThanToken: ISyntaxToken, typeArguments: ISeparatedSyntaxList, greaterThanToken: ISyntaxToken): TypeArgumentListSyntax; + constructorType(newKeyword: ISyntaxToken, typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, equalsGreaterThanToken: ISyntaxToken, type: ITypeSyntax): ConstructorTypeSyntax; + functionType(typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, equalsGreaterThanToken: ISyntaxToken, type: ITypeSyntax): FunctionTypeSyntax; + objectType(openBraceToken: ISyntaxToken, typeMembers: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken): ObjectTypeSyntax; + arrayType(type: ITypeSyntax, openBracketToken: ISyntaxToken, closeBracketToken: ISyntaxToken): ArrayTypeSyntax; + genericType(name: INameSyntax, typeArgumentList: TypeArgumentListSyntax): GenericTypeSyntax; + typeQuery(typeOfKeyword: ISyntaxToken, name: INameSyntax): TypeQuerySyntax; + typeAnnotation(colonToken: ISyntaxToken, type: ITypeSyntax): TypeAnnotationSyntax; + block(openBraceToken: ISyntaxToken, statements: ISyntaxList, closeBraceToken: ISyntaxToken): BlockSyntax; + parameter(dotDotDotToken: ISyntaxToken, modifiers: ISyntaxList, identifier: ISyntaxToken, questionToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, equalsValueClause: EqualsValueClauseSyntax): ParameterSyntax; + memberAccessExpression(expression: IExpressionSyntax, dotToken: ISyntaxToken, name: ISyntaxToken): MemberAccessExpressionSyntax; + postfixUnaryExpression(kind: SyntaxKind, operand: IMemberExpressionSyntax, operatorToken: ISyntaxToken): PostfixUnaryExpressionSyntax; + elementAccessExpression(expression: IExpressionSyntax, openBracketToken: ISyntaxToken, argumentExpression: IExpressionSyntax, closeBracketToken: ISyntaxToken): ElementAccessExpressionSyntax; + invocationExpression(expression: IMemberExpressionSyntax, argumentList: ArgumentListSyntax): InvocationExpressionSyntax; + argumentList(typeArgumentList: TypeArgumentListSyntax, openParenToken: ISyntaxToken, arguments: ISeparatedSyntaxList, closeParenToken: ISyntaxToken): ArgumentListSyntax; + binaryExpression(kind: SyntaxKind, left: IExpressionSyntax, operatorToken: ISyntaxToken, right: IExpressionSyntax): BinaryExpressionSyntax; + conditionalExpression(condition: IExpressionSyntax, questionToken: ISyntaxToken, whenTrue: IExpressionSyntax, colonToken: ISyntaxToken, whenFalse: IExpressionSyntax): ConditionalExpressionSyntax; + constructSignature(newKeyword: ISyntaxToken, callSignature: CallSignatureSyntax): ConstructSignatureSyntax; + methodSignature(propertyName: ISyntaxToken, questionToken: ISyntaxToken, callSignature: CallSignatureSyntax): MethodSignatureSyntax; + indexSignature(openBracketToken: ISyntaxToken, parameter: ParameterSyntax, closeBracketToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax): IndexSignatureSyntax; + propertySignature(propertyName: ISyntaxToken, questionToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax): PropertySignatureSyntax; + callSignature(typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, typeAnnotation: TypeAnnotationSyntax): CallSignatureSyntax; + parameterList(openParenToken: ISyntaxToken, parameters: ISeparatedSyntaxList, closeParenToken: ISyntaxToken): ParameterListSyntax; + typeParameterList(lessThanToken: ISyntaxToken, typeParameters: ISeparatedSyntaxList, greaterThanToken: ISyntaxToken): TypeParameterListSyntax; + typeParameter(identifier: ISyntaxToken, constraint: ConstraintSyntax): TypeParameterSyntax; + constraint(extendsKeyword: ISyntaxToken, type: ITypeSyntax): ConstraintSyntax; + elseClause(elseKeyword: ISyntaxToken, statement: IStatementSyntax): ElseClauseSyntax; + ifStatement(ifKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax, elseClause: ElseClauseSyntax): IfStatementSyntax; + expressionStatement(expression: IExpressionSyntax, semicolonToken: ISyntaxToken): ExpressionStatementSyntax; + constructorDeclaration(modifiers: ISyntaxList, constructorKeyword: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): ConstructorDeclarationSyntax; + memberFunctionDeclaration(modifiers: ISyntaxList, propertyName: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): MemberFunctionDeclarationSyntax; + getAccessor(modifiers: ISyntaxList, getKeyword: ISyntaxToken, propertyName: ISyntaxToken, parameterList: ParameterListSyntax, typeAnnotation: TypeAnnotationSyntax, block: BlockSyntax): GetAccessorSyntax; + setAccessor(modifiers: ISyntaxList, setKeyword: ISyntaxToken, propertyName: ISyntaxToken, parameterList: ParameterListSyntax, block: BlockSyntax): SetAccessorSyntax; + memberVariableDeclaration(modifiers: ISyntaxList, variableDeclarator: VariableDeclaratorSyntax, semicolonToken: ISyntaxToken): MemberVariableDeclarationSyntax; + indexMemberDeclaration(modifiers: ISyntaxList, indexSignature: IndexSignatureSyntax, semicolonToken: ISyntaxToken): IndexMemberDeclarationSyntax; + throwStatement(throwKeyword: ISyntaxToken, expression: IExpressionSyntax, semicolonToken: ISyntaxToken): ThrowStatementSyntax; + returnStatement(returnKeyword: ISyntaxToken, expression: IExpressionSyntax, semicolonToken: ISyntaxToken): ReturnStatementSyntax; + objectCreationExpression(newKeyword: ISyntaxToken, expression: IMemberExpressionSyntax, argumentList: ArgumentListSyntax): ObjectCreationExpressionSyntax; + switchStatement(switchKeyword: ISyntaxToken, openParenToken: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken, openBraceToken: ISyntaxToken, switchClauses: ISyntaxList, closeBraceToken: ISyntaxToken): SwitchStatementSyntax; + caseSwitchClause(caseKeyword: ISyntaxToken, expression: IExpressionSyntax, colonToken: ISyntaxToken, statements: ISyntaxList): CaseSwitchClauseSyntax; + defaultSwitchClause(defaultKeyword: ISyntaxToken, colonToken: ISyntaxToken, statements: ISyntaxList): DefaultSwitchClauseSyntax; + breakStatement(breakKeyword: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken): BreakStatementSyntax; + continueStatement(continueKeyword: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken): ContinueStatementSyntax; + forStatement(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken, variableDeclaration: VariableDeclarationSyntax, initializer: IExpressionSyntax, firstSemicolonToken: ISyntaxToken, condition: IExpressionSyntax, secondSemicolonToken: ISyntaxToken, incrementor: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): ForStatementSyntax; + forInStatement(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken, variableDeclaration: VariableDeclarationSyntax, left: IExpressionSyntax, inKeyword: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): ForInStatementSyntax; + whileStatement(whileKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): WhileStatementSyntax; + withStatement(withKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): WithStatementSyntax; + enumDeclaration(modifiers: ISyntaxList, enumKeyword: ISyntaxToken, identifier: ISyntaxToken, openBraceToken: ISyntaxToken, enumElements: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken): EnumDeclarationSyntax; + enumElement(propertyName: ISyntaxToken, equalsValueClause: EqualsValueClauseSyntax): EnumElementSyntax; + castExpression(lessThanToken: ISyntaxToken, type: ITypeSyntax, greaterThanToken: ISyntaxToken, expression: IUnaryExpressionSyntax): CastExpressionSyntax; + objectLiteralExpression(openBraceToken: ISyntaxToken, propertyAssignments: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken): ObjectLiteralExpressionSyntax; + simplePropertyAssignment(propertyName: ISyntaxToken, colonToken: ISyntaxToken, expression: IExpressionSyntax): SimplePropertyAssignmentSyntax; + functionPropertyAssignment(propertyName: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax): FunctionPropertyAssignmentSyntax; + functionExpression(functionKeyword: ISyntaxToken, identifier: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax): FunctionExpressionSyntax; + emptyStatement(semicolonToken: ISyntaxToken): EmptyStatementSyntax; + tryStatement(tryKeyword: ISyntaxToken, block: BlockSyntax, catchClause: CatchClauseSyntax, finallyClause: FinallyClauseSyntax): TryStatementSyntax; + catchClause(catchKeyword: ISyntaxToken, openParenToken: ISyntaxToken, identifier: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, closeParenToken: ISyntaxToken, block: BlockSyntax): CatchClauseSyntax; + finallyClause(finallyKeyword: ISyntaxToken, block: BlockSyntax): FinallyClauseSyntax; + labeledStatement(identifier: ISyntaxToken, colonToken: ISyntaxToken, statement: IStatementSyntax): LabeledStatementSyntax; + doStatement(doKeyword: ISyntaxToken, statement: IStatementSyntax, whileKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, semicolonToken: ISyntaxToken): DoStatementSyntax; + typeOfExpression(typeOfKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax): TypeOfExpressionSyntax; + deleteExpression(deleteKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax): DeleteExpressionSyntax; + voidExpression(voidKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax): VoidExpressionSyntax; + debuggerStatement(debuggerKeyword: ISyntaxToken, semicolonToken: ISyntaxToken): DebuggerStatementSyntax; + } + class NormalModeFactory implements IFactory { + public sourceUnit(moduleElements: ISyntaxList, endOfFileToken: ISyntaxToken): SourceUnitSyntax; + public externalModuleReference(requireKeyword: ISyntaxToken, openParenToken: ISyntaxToken, stringLiteral: ISyntaxToken, closeParenToken: ISyntaxToken): ExternalModuleReferenceSyntax; + public moduleNameModuleReference(moduleName: INameSyntax): ModuleNameModuleReferenceSyntax; + public importDeclaration(modifiers: ISyntaxList, importKeyword: ISyntaxToken, identifier: ISyntaxToken, equalsToken: ISyntaxToken, moduleReference: IModuleReferenceSyntax, semicolonToken: ISyntaxToken): ImportDeclarationSyntax; + public exportAssignment(exportKeyword: ISyntaxToken, equalsToken: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken): ExportAssignmentSyntax; + public classDeclaration(modifiers: ISyntaxList, classKeyword: ISyntaxToken, identifier: ISyntaxToken, typeParameterList: TypeParameterListSyntax, heritageClauses: ISyntaxList, openBraceToken: ISyntaxToken, classElements: ISyntaxList, closeBraceToken: ISyntaxToken): ClassDeclarationSyntax; + public interfaceDeclaration(modifiers: ISyntaxList, interfaceKeyword: ISyntaxToken, identifier: ISyntaxToken, typeParameterList: TypeParameterListSyntax, heritageClauses: ISyntaxList, body: ObjectTypeSyntax): InterfaceDeclarationSyntax; + public heritageClause(kind: SyntaxKind, extendsOrImplementsKeyword: ISyntaxToken, typeNames: ISeparatedSyntaxList): HeritageClauseSyntax; + public moduleDeclaration(modifiers: ISyntaxList, moduleKeyword: ISyntaxToken, name: INameSyntax, stringLiteral: ISyntaxToken, openBraceToken: ISyntaxToken, moduleElements: ISyntaxList, closeBraceToken: ISyntaxToken): ModuleDeclarationSyntax; + public functionDeclaration(modifiers: ISyntaxList, functionKeyword: ISyntaxToken, identifier: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): FunctionDeclarationSyntax; + public variableStatement(modifiers: ISyntaxList, variableDeclaration: VariableDeclarationSyntax, semicolonToken: ISyntaxToken): VariableStatementSyntax; + public variableDeclaration(varKeyword: ISyntaxToken, variableDeclarators: ISeparatedSyntaxList): VariableDeclarationSyntax; + public variableDeclarator(propertyName: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, equalsValueClause: EqualsValueClauseSyntax): VariableDeclaratorSyntax; + public equalsValueClause(equalsToken: ISyntaxToken, value: IExpressionSyntax): EqualsValueClauseSyntax; + public prefixUnaryExpression(kind: SyntaxKind, operatorToken: ISyntaxToken, operand: IUnaryExpressionSyntax): PrefixUnaryExpressionSyntax; + public arrayLiteralExpression(openBracketToken: ISyntaxToken, expressions: ISeparatedSyntaxList, closeBracketToken: ISyntaxToken): ArrayLiteralExpressionSyntax; + public omittedExpression(): OmittedExpressionSyntax; + public parenthesizedExpression(openParenToken: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken): ParenthesizedExpressionSyntax; + public simpleArrowFunctionExpression(identifier: ISyntaxToken, equalsGreaterThanToken: ISyntaxToken, block: BlockSyntax, expression: IExpressionSyntax): SimpleArrowFunctionExpressionSyntax; + public parenthesizedArrowFunctionExpression(callSignature: CallSignatureSyntax, equalsGreaterThanToken: ISyntaxToken, block: BlockSyntax, expression: IExpressionSyntax): ParenthesizedArrowFunctionExpressionSyntax; + public qualifiedName(left: INameSyntax, dotToken: ISyntaxToken, right: ISyntaxToken): QualifiedNameSyntax; + public typeArgumentList(lessThanToken: ISyntaxToken, typeArguments: ISeparatedSyntaxList, greaterThanToken: ISyntaxToken): TypeArgumentListSyntax; + public constructorType(newKeyword: ISyntaxToken, typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, equalsGreaterThanToken: ISyntaxToken, type: ITypeSyntax): ConstructorTypeSyntax; + public functionType(typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, equalsGreaterThanToken: ISyntaxToken, type: ITypeSyntax): FunctionTypeSyntax; + public objectType(openBraceToken: ISyntaxToken, typeMembers: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken): ObjectTypeSyntax; + public arrayType(type: ITypeSyntax, openBracketToken: ISyntaxToken, closeBracketToken: ISyntaxToken): ArrayTypeSyntax; + public genericType(name: INameSyntax, typeArgumentList: TypeArgumentListSyntax): GenericTypeSyntax; + public typeQuery(typeOfKeyword: ISyntaxToken, name: INameSyntax): TypeQuerySyntax; + public typeAnnotation(colonToken: ISyntaxToken, type: ITypeSyntax): TypeAnnotationSyntax; + public block(openBraceToken: ISyntaxToken, statements: ISyntaxList, closeBraceToken: ISyntaxToken): BlockSyntax; + public parameter(dotDotDotToken: ISyntaxToken, modifiers: ISyntaxList, identifier: ISyntaxToken, questionToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, equalsValueClause: EqualsValueClauseSyntax): ParameterSyntax; + public memberAccessExpression(expression: IExpressionSyntax, dotToken: ISyntaxToken, name: ISyntaxToken): MemberAccessExpressionSyntax; + public postfixUnaryExpression(kind: SyntaxKind, operand: IMemberExpressionSyntax, operatorToken: ISyntaxToken): PostfixUnaryExpressionSyntax; + public elementAccessExpression(expression: IExpressionSyntax, openBracketToken: ISyntaxToken, argumentExpression: IExpressionSyntax, closeBracketToken: ISyntaxToken): ElementAccessExpressionSyntax; + public invocationExpression(expression: IMemberExpressionSyntax, argumentList: ArgumentListSyntax): InvocationExpressionSyntax; + public argumentList(typeArgumentList: TypeArgumentListSyntax, openParenToken: ISyntaxToken, _arguments: ISeparatedSyntaxList, closeParenToken: ISyntaxToken): ArgumentListSyntax; + public binaryExpression(kind: SyntaxKind, left: IExpressionSyntax, operatorToken: ISyntaxToken, right: IExpressionSyntax): BinaryExpressionSyntax; + public conditionalExpression(condition: IExpressionSyntax, questionToken: ISyntaxToken, whenTrue: IExpressionSyntax, colonToken: ISyntaxToken, whenFalse: IExpressionSyntax): ConditionalExpressionSyntax; + public constructSignature(newKeyword: ISyntaxToken, callSignature: CallSignatureSyntax): ConstructSignatureSyntax; + public methodSignature(propertyName: ISyntaxToken, questionToken: ISyntaxToken, callSignature: CallSignatureSyntax): MethodSignatureSyntax; + public indexSignature(openBracketToken: ISyntaxToken, parameter: ParameterSyntax, closeBracketToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax): IndexSignatureSyntax; + public propertySignature(propertyName: ISyntaxToken, questionToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax): PropertySignatureSyntax; + public callSignature(typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, typeAnnotation: TypeAnnotationSyntax): CallSignatureSyntax; + public parameterList(openParenToken: ISyntaxToken, parameters: ISeparatedSyntaxList, closeParenToken: ISyntaxToken): ParameterListSyntax; + public typeParameterList(lessThanToken: ISyntaxToken, typeParameters: ISeparatedSyntaxList, greaterThanToken: ISyntaxToken): TypeParameterListSyntax; + public typeParameter(identifier: ISyntaxToken, constraint: ConstraintSyntax): TypeParameterSyntax; + public constraint(extendsKeyword: ISyntaxToken, type: ITypeSyntax): ConstraintSyntax; + public elseClause(elseKeyword: ISyntaxToken, statement: IStatementSyntax): ElseClauseSyntax; + public ifStatement(ifKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax, elseClause: ElseClauseSyntax): IfStatementSyntax; + public expressionStatement(expression: IExpressionSyntax, semicolonToken: ISyntaxToken): ExpressionStatementSyntax; + public constructorDeclaration(modifiers: ISyntaxList, constructorKeyword: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): ConstructorDeclarationSyntax; + public memberFunctionDeclaration(modifiers: ISyntaxList, propertyName: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): MemberFunctionDeclarationSyntax; + public getAccessor(modifiers: ISyntaxList, getKeyword: ISyntaxToken, propertyName: ISyntaxToken, parameterList: ParameterListSyntax, typeAnnotation: TypeAnnotationSyntax, block: BlockSyntax): GetAccessorSyntax; + public setAccessor(modifiers: ISyntaxList, setKeyword: ISyntaxToken, propertyName: ISyntaxToken, parameterList: ParameterListSyntax, block: BlockSyntax): SetAccessorSyntax; + public memberVariableDeclaration(modifiers: ISyntaxList, variableDeclarator: VariableDeclaratorSyntax, semicolonToken: ISyntaxToken): MemberVariableDeclarationSyntax; + public indexMemberDeclaration(modifiers: ISyntaxList, indexSignature: IndexSignatureSyntax, semicolonToken: ISyntaxToken): IndexMemberDeclarationSyntax; + public throwStatement(throwKeyword: ISyntaxToken, expression: IExpressionSyntax, semicolonToken: ISyntaxToken): ThrowStatementSyntax; + public returnStatement(returnKeyword: ISyntaxToken, expression: IExpressionSyntax, semicolonToken: ISyntaxToken): ReturnStatementSyntax; + public objectCreationExpression(newKeyword: ISyntaxToken, expression: IMemberExpressionSyntax, argumentList: ArgumentListSyntax): ObjectCreationExpressionSyntax; + public switchStatement(switchKeyword: ISyntaxToken, openParenToken: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken, openBraceToken: ISyntaxToken, switchClauses: ISyntaxList, closeBraceToken: ISyntaxToken): SwitchStatementSyntax; + public caseSwitchClause(caseKeyword: ISyntaxToken, expression: IExpressionSyntax, colonToken: ISyntaxToken, statements: ISyntaxList): CaseSwitchClauseSyntax; + public defaultSwitchClause(defaultKeyword: ISyntaxToken, colonToken: ISyntaxToken, statements: ISyntaxList): DefaultSwitchClauseSyntax; + public breakStatement(breakKeyword: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken): BreakStatementSyntax; + public continueStatement(continueKeyword: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken): ContinueStatementSyntax; + public forStatement(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken, variableDeclaration: VariableDeclarationSyntax, initializer: IExpressionSyntax, firstSemicolonToken: ISyntaxToken, condition: IExpressionSyntax, secondSemicolonToken: ISyntaxToken, incrementor: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): ForStatementSyntax; + public forInStatement(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken, variableDeclaration: VariableDeclarationSyntax, left: IExpressionSyntax, inKeyword: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): ForInStatementSyntax; + public whileStatement(whileKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): WhileStatementSyntax; + public withStatement(withKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): WithStatementSyntax; + public enumDeclaration(modifiers: ISyntaxList, enumKeyword: ISyntaxToken, identifier: ISyntaxToken, openBraceToken: ISyntaxToken, enumElements: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken): EnumDeclarationSyntax; + public enumElement(propertyName: ISyntaxToken, equalsValueClause: EqualsValueClauseSyntax): EnumElementSyntax; + public castExpression(lessThanToken: ISyntaxToken, type: ITypeSyntax, greaterThanToken: ISyntaxToken, expression: IUnaryExpressionSyntax): CastExpressionSyntax; + public objectLiteralExpression(openBraceToken: ISyntaxToken, propertyAssignments: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken): ObjectLiteralExpressionSyntax; + public simplePropertyAssignment(propertyName: ISyntaxToken, colonToken: ISyntaxToken, expression: IExpressionSyntax): SimplePropertyAssignmentSyntax; + public functionPropertyAssignment(propertyName: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax): FunctionPropertyAssignmentSyntax; + public functionExpression(functionKeyword: ISyntaxToken, identifier: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax): FunctionExpressionSyntax; + public emptyStatement(semicolonToken: ISyntaxToken): EmptyStatementSyntax; + public tryStatement(tryKeyword: ISyntaxToken, block: BlockSyntax, catchClause: CatchClauseSyntax, finallyClause: FinallyClauseSyntax): TryStatementSyntax; + public catchClause(catchKeyword: ISyntaxToken, openParenToken: ISyntaxToken, identifier: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, closeParenToken: ISyntaxToken, block: BlockSyntax): CatchClauseSyntax; + public finallyClause(finallyKeyword: ISyntaxToken, block: BlockSyntax): FinallyClauseSyntax; + public labeledStatement(identifier: ISyntaxToken, colonToken: ISyntaxToken, statement: IStatementSyntax): LabeledStatementSyntax; + public doStatement(doKeyword: ISyntaxToken, statement: IStatementSyntax, whileKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, semicolonToken: ISyntaxToken): DoStatementSyntax; + public typeOfExpression(typeOfKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax): TypeOfExpressionSyntax; + public deleteExpression(deleteKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax): DeleteExpressionSyntax; + public voidExpression(voidKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax): VoidExpressionSyntax; + public debuggerStatement(debuggerKeyword: ISyntaxToken, semicolonToken: ISyntaxToken): DebuggerStatementSyntax; + } + class StrictModeFactory implements IFactory { + public sourceUnit(moduleElements: ISyntaxList, endOfFileToken: ISyntaxToken): SourceUnitSyntax; + public externalModuleReference(requireKeyword: ISyntaxToken, openParenToken: ISyntaxToken, stringLiteral: ISyntaxToken, closeParenToken: ISyntaxToken): ExternalModuleReferenceSyntax; + public moduleNameModuleReference(moduleName: INameSyntax): ModuleNameModuleReferenceSyntax; + public importDeclaration(modifiers: ISyntaxList, importKeyword: ISyntaxToken, identifier: ISyntaxToken, equalsToken: ISyntaxToken, moduleReference: IModuleReferenceSyntax, semicolonToken: ISyntaxToken): ImportDeclarationSyntax; + public exportAssignment(exportKeyword: ISyntaxToken, equalsToken: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken): ExportAssignmentSyntax; + public classDeclaration(modifiers: ISyntaxList, classKeyword: ISyntaxToken, identifier: ISyntaxToken, typeParameterList: TypeParameterListSyntax, heritageClauses: ISyntaxList, openBraceToken: ISyntaxToken, classElements: ISyntaxList, closeBraceToken: ISyntaxToken): ClassDeclarationSyntax; + public interfaceDeclaration(modifiers: ISyntaxList, interfaceKeyword: ISyntaxToken, identifier: ISyntaxToken, typeParameterList: TypeParameterListSyntax, heritageClauses: ISyntaxList, body: ObjectTypeSyntax): InterfaceDeclarationSyntax; + public heritageClause(kind: SyntaxKind, extendsOrImplementsKeyword: ISyntaxToken, typeNames: ISeparatedSyntaxList): HeritageClauseSyntax; + public moduleDeclaration(modifiers: ISyntaxList, moduleKeyword: ISyntaxToken, name: INameSyntax, stringLiteral: ISyntaxToken, openBraceToken: ISyntaxToken, moduleElements: ISyntaxList, closeBraceToken: ISyntaxToken): ModuleDeclarationSyntax; + public functionDeclaration(modifiers: ISyntaxList, functionKeyword: ISyntaxToken, identifier: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): FunctionDeclarationSyntax; + public variableStatement(modifiers: ISyntaxList, variableDeclaration: VariableDeclarationSyntax, semicolonToken: ISyntaxToken): VariableStatementSyntax; + public variableDeclaration(varKeyword: ISyntaxToken, variableDeclarators: ISeparatedSyntaxList): VariableDeclarationSyntax; + public variableDeclarator(propertyName: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, equalsValueClause: EqualsValueClauseSyntax): VariableDeclaratorSyntax; + public equalsValueClause(equalsToken: ISyntaxToken, value: IExpressionSyntax): EqualsValueClauseSyntax; + public prefixUnaryExpression(kind: SyntaxKind, operatorToken: ISyntaxToken, operand: IUnaryExpressionSyntax): PrefixUnaryExpressionSyntax; + public arrayLiteralExpression(openBracketToken: ISyntaxToken, expressions: ISeparatedSyntaxList, closeBracketToken: ISyntaxToken): ArrayLiteralExpressionSyntax; + public omittedExpression(): OmittedExpressionSyntax; + public parenthesizedExpression(openParenToken: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken): ParenthesizedExpressionSyntax; + public simpleArrowFunctionExpression(identifier: ISyntaxToken, equalsGreaterThanToken: ISyntaxToken, block: BlockSyntax, expression: IExpressionSyntax): SimpleArrowFunctionExpressionSyntax; + public parenthesizedArrowFunctionExpression(callSignature: CallSignatureSyntax, equalsGreaterThanToken: ISyntaxToken, block: BlockSyntax, expression: IExpressionSyntax): ParenthesizedArrowFunctionExpressionSyntax; + public qualifiedName(left: INameSyntax, dotToken: ISyntaxToken, right: ISyntaxToken): QualifiedNameSyntax; + public typeArgumentList(lessThanToken: ISyntaxToken, typeArguments: ISeparatedSyntaxList, greaterThanToken: ISyntaxToken): TypeArgumentListSyntax; + public constructorType(newKeyword: ISyntaxToken, typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, equalsGreaterThanToken: ISyntaxToken, type: ITypeSyntax): ConstructorTypeSyntax; + public functionType(typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, equalsGreaterThanToken: ISyntaxToken, type: ITypeSyntax): FunctionTypeSyntax; + public objectType(openBraceToken: ISyntaxToken, typeMembers: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken): ObjectTypeSyntax; + public arrayType(type: ITypeSyntax, openBracketToken: ISyntaxToken, closeBracketToken: ISyntaxToken): ArrayTypeSyntax; + public genericType(name: INameSyntax, typeArgumentList: TypeArgumentListSyntax): GenericTypeSyntax; + public typeQuery(typeOfKeyword: ISyntaxToken, name: INameSyntax): TypeQuerySyntax; + public typeAnnotation(colonToken: ISyntaxToken, type: ITypeSyntax): TypeAnnotationSyntax; + public block(openBraceToken: ISyntaxToken, statements: ISyntaxList, closeBraceToken: ISyntaxToken): BlockSyntax; + public parameter(dotDotDotToken: ISyntaxToken, modifiers: ISyntaxList, identifier: ISyntaxToken, questionToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, equalsValueClause: EqualsValueClauseSyntax): ParameterSyntax; + public memberAccessExpression(expression: IExpressionSyntax, dotToken: ISyntaxToken, name: ISyntaxToken): MemberAccessExpressionSyntax; + public postfixUnaryExpression(kind: SyntaxKind, operand: IMemberExpressionSyntax, operatorToken: ISyntaxToken): PostfixUnaryExpressionSyntax; + public elementAccessExpression(expression: IExpressionSyntax, openBracketToken: ISyntaxToken, argumentExpression: IExpressionSyntax, closeBracketToken: ISyntaxToken): ElementAccessExpressionSyntax; + public invocationExpression(expression: IMemberExpressionSyntax, argumentList: ArgumentListSyntax): InvocationExpressionSyntax; + public argumentList(typeArgumentList: TypeArgumentListSyntax, openParenToken: ISyntaxToken, _arguments: ISeparatedSyntaxList, closeParenToken: ISyntaxToken): ArgumentListSyntax; + public binaryExpression(kind: SyntaxKind, left: IExpressionSyntax, operatorToken: ISyntaxToken, right: IExpressionSyntax): BinaryExpressionSyntax; + public conditionalExpression(condition: IExpressionSyntax, questionToken: ISyntaxToken, whenTrue: IExpressionSyntax, colonToken: ISyntaxToken, whenFalse: IExpressionSyntax): ConditionalExpressionSyntax; + public constructSignature(newKeyword: ISyntaxToken, callSignature: CallSignatureSyntax): ConstructSignatureSyntax; + public methodSignature(propertyName: ISyntaxToken, questionToken: ISyntaxToken, callSignature: CallSignatureSyntax): MethodSignatureSyntax; + public indexSignature(openBracketToken: ISyntaxToken, parameter: ParameterSyntax, closeBracketToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax): IndexSignatureSyntax; + public propertySignature(propertyName: ISyntaxToken, questionToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax): PropertySignatureSyntax; + public callSignature(typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, typeAnnotation: TypeAnnotationSyntax): CallSignatureSyntax; + public parameterList(openParenToken: ISyntaxToken, parameters: ISeparatedSyntaxList, closeParenToken: ISyntaxToken): ParameterListSyntax; + public typeParameterList(lessThanToken: ISyntaxToken, typeParameters: ISeparatedSyntaxList, greaterThanToken: ISyntaxToken): TypeParameterListSyntax; + public typeParameter(identifier: ISyntaxToken, constraint: ConstraintSyntax): TypeParameterSyntax; + public constraint(extendsKeyword: ISyntaxToken, type: ITypeSyntax): ConstraintSyntax; + public elseClause(elseKeyword: ISyntaxToken, statement: IStatementSyntax): ElseClauseSyntax; + public ifStatement(ifKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax, elseClause: ElseClauseSyntax): IfStatementSyntax; + public expressionStatement(expression: IExpressionSyntax, semicolonToken: ISyntaxToken): ExpressionStatementSyntax; + public constructorDeclaration(modifiers: ISyntaxList, constructorKeyword: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): ConstructorDeclarationSyntax; + public memberFunctionDeclaration(modifiers: ISyntaxList, propertyName: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): MemberFunctionDeclarationSyntax; + public getAccessor(modifiers: ISyntaxList, getKeyword: ISyntaxToken, propertyName: ISyntaxToken, parameterList: ParameterListSyntax, typeAnnotation: TypeAnnotationSyntax, block: BlockSyntax): GetAccessorSyntax; + public setAccessor(modifiers: ISyntaxList, setKeyword: ISyntaxToken, propertyName: ISyntaxToken, parameterList: ParameterListSyntax, block: BlockSyntax): SetAccessorSyntax; + public memberVariableDeclaration(modifiers: ISyntaxList, variableDeclarator: VariableDeclaratorSyntax, semicolonToken: ISyntaxToken): MemberVariableDeclarationSyntax; + public indexMemberDeclaration(modifiers: ISyntaxList, indexSignature: IndexSignatureSyntax, semicolonToken: ISyntaxToken): IndexMemberDeclarationSyntax; + public throwStatement(throwKeyword: ISyntaxToken, expression: IExpressionSyntax, semicolonToken: ISyntaxToken): ThrowStatementSyntax; + public returnStatement(returnKeyword: ISyntaxToken, expression: IExpressionSyntax, semicolonToken: ISyntaxToken): ReturnStatementSyntax; + public objectCreationExpression(newKeyword: ISyntaxToken, expression: IMemberExpressionSyntax, argumentList: ArgumentListSyntax): ObjectCreationExpressionSyntax; + public switchStatement(switchKeyword: ISyntaxToken, openParenToken: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken, openBraceToken: ISyntaxToken, switchClauses: ISyntaxList, closeBraceToken: ISyntaxToken): SwitchStatementSyntax; + public caseSwitchClause(caseKeyword: ISyntaxToken, expression: IExpressionSyntax, colonToken: ISyntaxToken, statements: ISyntaxList): CaseSwitchClauseSyntax; + public defaultSwitchClause(defaultKeyword: ISyntaxToken, colonToken: ISyntaxToken, statements: ISyntaxList): DefaultSwitchClauseSyntax; + public breakStatement(breakKeyword: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken): BreakStatementSyntax; + public continueStatement(continueKeyword: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken): ContinueStatementSyntax; + public forStatement(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken, variableDeclaration: VariableDeclarationSyntax, initializer: IExpressionSyntax, firstSemicolonToken: ISyntaxToken, condition: IExpressionSyntax, secondSemicolonToken: ISyntaxToken, incrementor: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): ForStatementSyntax; + public forInStatement(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken, variableDeclaration: VariableDeclarationSyntax, left: IExpressionSyntax, inKeyword: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): ForInStatementSyntax; + public whileStatement(whileKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): WhileStatementSyntax; + public withStatement(withKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): WithStatementSyntax; + public enumDeclaration(modifiers: ISyntaxList, enumKeyword: ISyntaxToken, identifier: ISyntaxToken, openBraceToken: ISyntaxToken, enumElements: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken): EnumDeclarationSyntax; + public enumElement(propertyName: ISyntaxToken, equalsValueClause: EqualsValueClauseSyntax): EnumElementSyntax; + public castExpression(lessThanToken: ISyntaxToken, type: ITypeSyntax, greaterThanToken: ISyntaxToken, expression: IUnaryExpressionSyntax): CastExpressionSyntax; + public objectLiteralExpression(openBraceToken: ISyntaxToken, propertyAssignments: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken): ObjectLiteralExpressionSyntax; + public simplePropertyAssignment(propertyName: ISyntaxToken, colonToken: ISyntaxToken, expression: IExpressionSyntax): SimplePropertyAssignmentSyntax; + public functionPropertyAssignment(propertyName: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax): FunctionPropertyAssignmentSyntax; + public functionExpression(functionKeyword: ISyntaxToken, identifier: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax): FunctionExpressionSyntax; + public emptyStatement(semicolonToken: ISyntaxToken): EmptyStatementSyntax; + public tryStatement(tryKeyword: ISyntaxToken, block: BlockSyntax, catchClause: CatchClauseSyntax, finallyClause: FinallyClauseSyntax): TryStatementSyntax; + public catchClause(catchKeyword: ISyntaxToken, openParenToken: ISyntaxToken, identifier: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, closeParenToken: ISyntaxToken, block: BlockSyntax): CatchClauseSyntax; + public finallyClause(finallyKeyword: ISyntaxToken, block: BlockSyntax): FinallyClauseSyntax; + public labeledStatement(identifier: ISyntaxToken, colonToken: ISyntaxToken, statement: IStatementSyntax): LabeledStatementSyntax; + public doStatement(doKeyword: ISyntaxToken, statement: IStatementSyntax, whileKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, semicolonToken: ISyntaxToken): DoStatementSyntax; + public typeOfExpression(typeOfKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax): TypeOfExpressionSyntax; + public deleteExpression(deleteKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax): DeleteExpressionSyntax; + public voidExpression(voidKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax): VoidExpressionSyntax; + public debuggerStatement(debuggerKeyword: ISyntaxToken, semicolonToken: ISyntaxToken): DebuggerStatementSyntax; + } + var normalModeFactory: IFactory; + var strictModeFactory: IFactory; +} +declare module TypeScript.SyntaxFacts { + function isDirectivePrologueElement(node: ISyntaxNodeOrToken): boolean; + function isUseStrictDirective(node: ISyntaxNodeOrToken): boolean; + function isIdentifierNameOrAnyKeyword(token: ISyntaxToken): boolean; +} +declare module TypeScript { + interface ISyntaxList extends ISyntaxElement { + childAt(index: number): ISyntaxNodeOrToken; + toArray(): ISyntaxNodeOrToken[]; + insertChildrenInto(array: ISyntaxElement[], index: number): void; + } +} +declare module TypeScript.Syntax { + class EmptySyntaxList implements ISyntaxList { + public kind(): SyntaxKind; + public isNode(): boolean; + public isToken(): boolean; + public isList(): boolean; + public isSeparatedList(): boolean; + public toJSON(key: any): any; + public childCount(): number; + public childAt(index: number): ISyntaxNodeOrToken; + public toArray(): ISyntaxNodeOrToken[]; + public collectTextElements(elements: string[]): void; + public firstToken(): ISyntaxToken; + public lastToken(): ISyntaxToken; + public fullWidth(): number; + public width(): number; + public leadingTrivia(): ISyntaxTriviaList; + public trailingTrivia(): ISyntaxTriviaList; + public leadingTriviaWidth(): number; + public trailingTriviaWidth(): number; + public fullText(): string; + public isTypeScriptSpecific(): boolean; + public isIncrementallyUnusable(): boolean; + public findTokenInternal(parent: PositionedElement, position: number, fullStart: number): PositionedToken; + public insertChildrenInto(array: ISyntaxElement[], index: number): void; + } + var emptyList: ISyntaxList; + function list(nodes: ISyntaxNodeOrToken[]): ISyntaxList; +} +declare module TypeScript { + class SyntaxNode implements ISyntaxNodeOrToken { + private _data; + constructor(parsedInStrictMode: boolean); + public isNode(): boolean; + public isToken(): boolean; + public isList(): boolean; + public isSeparatedList(): boolean; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public firstToken(): ISyntaxToken; + public lastToken(): ISyntaxToken; + public insertChildrenInto(array: ISyntaxElement[], index: number): void; + public leadingTrivia(): ISyntaxTriviaList; + public trailingTrivia(): ISyntaxTriviaList; + public toJSON(key: any): any; + public accept(visitor: ISyntaxVisitor): any; + public fullText(): string; + public collectTextElements(elements: string[]): void; + public replaceToken(token1: ISyntaxToken, token2: ISyntaxToken): SyntaxNode; + public withLeadingTrivia(trivia: ISyntaxTriviaList): SyntaxNode; + public withTrailingTrivia(trivia: ISyntaxTriviaList): SyntaxNode; + public hasLeadingTrivia(): boolean; + public hasTrailingTrivia(): boolean; + public isTypeScriptSpecific(): boolean; + public isIncrementallyUnusable(): boolean; + public parsedInStrictMode(): boolean; + public fullWidth(): number; + private computeData(); + private data(); + public findToken(position: number, includeSkippedTokens?: boolean): PositionedToken; + private tryGetEndOfFileAt(position); + private findTokenInternal(parent, position, fullStart); + public findTokenOnLeft(position: number, includeSkippedTokens?: boolean): PositionedToken; + public findCompleteTokenOnLeft(position: number, includeSkippedTokens?: boolean): PositionedToken; + public isModuleElement(): boolean; + public isClassElement(): boolean; + public isTypeMember(): boolean; + public isStatement(): boolean; + public isExpression(): boolean; + public isSwitchClause(): boolean; + public structuralEquals(node: SyntaxNode): boolean; + public width(): number; + public leadingTriviaWidth(): number; + public trailingTriviaWidth(): number; + } +} +declare module TypeScript { + interface ISyntaxNodeOrToken extends ISyntaxElement { + withLeadingTrivia(leadingTrivia: ISyntaxTriviaList): ISyntaxNodeOrToken; + withTrailingTrivia(trailingTrivia: ISyntaxTriviaList): ISyntaxNodeOrToken; + accept(visitor: ISyntaxVisitor): any; + } +} +declare module TypeScript { + class SourceUnitSyntax extends SyntaxNode { + public moduleElements: ISyntaxList; + public endOfFileToken: ISyntaxToken; + constructor(moduleElements: ISyntaxList, endOfFileToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(moduleElements: ISyntaxList, endOfFileToken: ISyntaxToken): SourceUnitSyntax; + static create(endOfFileToken: ISyntaxToken): SourceUnitSyntax; + static create1(endOfFileToken: ISyntaxToken): SourceUnitSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): SourceUnitSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): SourceUnitSyntax; + public withModuleElements(moduleElements: ISyntaxList): SourceUnitSyntax; + public withModuleElement(moduleElement: IModuleElementSyntax): SourceUnitSyntax; + public withEndOfFileToken(endOfFileToken: ISyntaxToken): SourceUnitSyntax; + public isTypeScriptSpecific(): boolean; + } + class ExternalModuleReferenceSyntax extends SyntaxNode implements IModuleReferenceSyntax { + public requireKeyword: ISyntaxToken; + public openParenToken: ISyntaxToken; + public stringLiteral: ISyntaxToken; + public closeParenToken: ISyntaxToken; + constructor(requireKeyword: ISyntaxToken, openParenToken: ISyntaxToken, stringLiteral: ISyntaxToken, closeParenToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isModuleReference(): boolean; + public update(requireKeyword: ISyntaxToken, openParenToken: ISyntaxToken, stringLiteral: ISyntaxToken, closeParenToken: ISyntaxToken): ExternalModuleReferenceSyntax; + static create1(stringLiteral: ISyntaxToken): ExternalModuleReferenceSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ExternalModuleReferenceSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ExternalModuleReferenceSyntax; + public withRequireKeyword(requireKeyword: ISyntaxToken): ExternalModuleReferenceSyntax; + public withOpenParenToken(openParenToken: ISyntaxToken): ExternalModuleReferenceSyntax; + public withStringLiteral(stringLiteral: ISyntaxToken): ExternalModuleReferenceSyntax; + public withCloseParenToken(closeParenToken: ISyntaxToken): ExternalModuleReferenceSyntax; + public isTypeScriptSpecific(): boolean; + } + class ModuleNameModuleReferenceSyntax extends SyntaxNode implements IModuleReferenceSyntax { + public moduleName: INameSyntax; + constructor(moduleName: INameSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isModuleReference(): boolean; + public update(moduleName: INameSyntax): ModuleNameModuleReferenceSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ModuleNameModuleReferenceSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ModuleNameModuleReferenceSyntax; + public withModuleName(moduleName: INameSyntax): ModuleNameModuleReferenceSyntax; + public isTypeScriptSpecific(): boolean; + } + class ImportDeclarationSyntax extends SyntaxNode implements IModuleElementSyntax { + public modifiers: ISyntaxList; + public importKeyword: ISyntaxToken; + public identifier: ISyntaxToken; + public equalsToken: ISyntaxToken; + public moduleReference: IModuleReferenceSyntax; + public semicolonToken: ISyntaxToken; + constructor(modifiers: ISyntaxList, importKeyword: ISyntaxToken, identifier: ISyntaxToken, equalsToken: ISyntaxToken, moduleReference: IModuleReferenceSyntax, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isModuleElement(): boolean; + public update(modifiers: ISyntaxList, importKeyword: ISyntaxToken, identifier: ISyntaxToken, equalsToken: ISyntaxToken, moduleReference: IModuleReferenceSyntax, semicolonToken: ISyntaxToken): ImportDeclarationSyntax; + static create(importKeyword: ISyntaxToken, identifier: ISyntaxToken, equalsToken: ISyntaxToken, moduleReference: IModuleReferenceSyntax, semicolonToken: ISyntaxToken): ImportDeclarationSyntax; + static create1(identifier: ISyntaxToken, moduleReference: IModuleReferenceSyntax): ImportDeclarationSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ImportDeclarationSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ImportDeclarationSyntax; + public withModifiers(modifiers: ISyntaxList): ImportDeclarationSyntax; + public withModifier(modifier: ISyntaxToken): ImportDeclarationSyntax; + public withImportKeyword(importKeyword: ISyntaxToken): ImportDeclarationSyntax; + public withIdentifier(identifier: ISyntaxToken): ImportDeclarationSyntax; + public withEqualsToken(equalsToken: ISyntaxToken): ImportDeclarationSyntax; + public withModuleReference(moduleReference: IModuleReferenceSyntax): ImportDeclarationSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): ImportDeclarationSyntax; + public isTypeScriptSpecific(): boolean; + } + class ExportAssignmentSyntax extends SyntaxNode implements IModuleElementSyntax { + public exportKeyword: ISyntaxToken; + public equalsToken: ISyntaxToken; + public identifier: ISyntaxToken; + public semicolonToken: ISyntaxToken; + constructor(exportKeyword: ISyntaxToken, equalsToken: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isModuleElement(): boolean; + public update(exportKeyword: ISyntaxToken, equalsToken: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken): ExportAssignmentSyntax; + static create1(identifier: ISyntaxToken): ExportAssignmentSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ExportAssignmentSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ExportAssignmentSyntax; + public withExportKeyword(exportKeyword: ISyntaxToken): ExportAssignmentSyntax; + public withEqualsToken(equalsToken: ISyntaxToken): ExportAssignmentSyntax; + public withIdentifier(identifier: ISyntaxToken): ExportAssignmentSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): ExportAssignmentSyntax; + public isTypeScriptSpecific(): boolean; + } + class ClassDeclarationSyntax extends SyntaxNode implements IModuleElementSyntax { + public modifiers: ISyntaxList; + public classKeyword: ISyntaxToken; + public identifier: ISyntaxToken; + public typeParameterList: TypeParameterListSyntax; + public heritageClauses: ISyntaxList; + public openBraceToken: ISyntaxToken; + public classElements: ISyntaxList; + public closeBraceToken: ISyntaxToken; + constructor(modifiers: ISyntaxList, classKeyword: ISyntaxToken, identifier: ISyntaxToken, typeParameterList: TypeParameterListSyntax, heritageClauses: ISyntaxList, openBraceToken: ISyntaxToken, classElements: ISyntaxList, closeBraceToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isModuleElement(): boolean; + public update(modifiers: ISyntaxList, classKeyword: ISyntaxToken, identifier: ISyntaxToken, typeParameterList: TypeParameterListSyntax, heritageClauses: ISyntaxList, openBraceToken: ISyntaxToken, classElements: ISyntaxList, closeBraceToken: ISyntaxToken): ClassDeclarationSyntax; + static create(classKeyword: ISyntaxToken, identifier: ISyntaxToken, openBraceToken: ISyntaxToken, closeBraceToken: ISyntaxToken): ClassDeclarationSyntax; + static create1(identifier: ISyntaxToken): ClassDeclarationSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ClassDeclarationSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ClassDeclarationSyntax; + public withModifiers(modifiers: ISyntaxList): ClassDeclarationSyntax; + public withModifier(modifier: ISyntaxToken): ClassDeclarationSyntax; + public withClassKeyword(classKeyword: ISyntaxToken): ClassDeclarationSyntax; + public withIdentifier(identifier: ISyntaxToken): ClassDeclarationSyntax; + public withTypeParameterList(typeParameterList: TypeParameterListSyntax): ClassDeclarationSyntax; + public withHeritageClauses(heritageClauses: ISyntaxList): ClassDeclarationSyntax; + public withHeritageClause(heritageClause: HeritageClauseSyntax): ClassDeclarationSyntax; + public withOpenBraceToken(openBraceToken: ISyntaxToken): ClassDeclarationSyntax; + public withClassElements(classElements: ISyntaxList): ClassDeclarationSyntax; + public withClassElement(classElement: IClassElementSyntax): ClassDeclarationSyntax; + public withCloseBraceToken(closeBraceToken: ISyntaxToken): ClassDeclarationSyntax; + public isTypeScriptSpecific(): boolean; + } + class InterfaceDeclarationSyntax extends SyntaxNode implements IModuleElementSyntax { + public modifiers: ISyntaxList; + public interfaceKeyword: ISyntaxToken; + public identifier: ISyntaxToken; + public typeParameterList: TypeParameterListSyntax; + public heritageClauses: ISyntaxList; + public body: ObjectTypeSyntax; + constructor(modifiers: ISyntaxList, interfaceKeyword: ISyntaxToken, identifier: ISyntaxToken, typeParameterList: TypeParameterListSyntax, heritageClauses: ISyntaxList, body: ObjectTypeSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isModuleElement(): boolean; + public update(modifiers: ISyntaxList, interfaceKeyword: ISyntaxToken, identifier: ISyntaxToken, typeParameterList: TypeParameterListSyntax, heritageClauses: ISyntaxList, body: ObjectTypeSyntax): InterfaceDeclarationSyntax; + static create(interfaceKeyword: ISyntaxToken, identifier: ISyntaxToken, body: ObjectTypeSyntax): InterfaceDeclarationSyntax; + static create1(identifier: ISyntaxToken): InterfaceDeclarationSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): InterfaceDeclarationSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): InterfaceDeclarationSyntax; + public withModifiers(modifiers: ISyntaxList): InterfaceDeclarationSyntax; + public withModifier(modifier: ISyntaxToken): InterfaceDeclarationSyntax; + public withInterfaceKeyword(interfaceKeyword: ISyntaxToken): InterfaceDeclarationSyntax; + public withIdentifier(identifier: ISyntaxToken): InterfaceDeclarationSyntax; + public withTypeParameterList(typeParameterList: TypeParameterListSyntax): InterfaceDeclarationSyntax; + public withHeritageClauses(heritageClauses: ISyntaxList): InterfaceDeclarationSyntax; + public withHeritageClause(heritageClause: HeritageClauseSyntax): InterfaceDeclarationSyntax; + public withBody(body: ObjectTypeSyntax): InterfaceDeclarationSyntax; + public isTypeScriptSpecific(): boolean; + } + class HeritageClauseSyntax extends SyntaxNode { + public extendsOrImplementsKeyword: ISyntaxToken; + public typeNames: ISeparatedSyntaxList; + private _kind; + constructor(kind: SyntaxKind, extendsOrImplementsKeyword: ISyntaxToken, typeNames: ISeparatedSyntaxList, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public kind(): SyntaxKind; + public update(kind: SyntaxKind, extendsOrImplementsKeyword: ISyntaxToken, typeNames: ISeparatedSyntaxList): HeritageClauseSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): HeritageClauseSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): HeritageClauseSyntax; + public withKind(kind: SyntaxKind): HeritageClauseSyntax; + public withExtendsOrImplementsKeyword(extendsOrImplementsKeyword: ISyntaxToken): HeritageClauseSyntax; + public withTypeNames(typeNames: ISeparatedSyntaxList): HeritageClauseSyntax; + public withTypeName(typeName: INameSyntax): HeritageClauseSyntax; + public isTypeScriptSpecific(): boolean; + } + class ModuleDeclarationSyntax extends SyntaxNode implements IModuleElementSyntax { + public modifiers: ISyntaxList; + public moduleKeyword: ISyntaxToken; + public name: INameSyntax; + public stringLiteral: ISyntaxToken; + public openBraceToken: ISyntaxToken; + public moduleElements: ISyntaxList; + public closeBraceToken: ISyntaxToken; + constructor(modifiers: ISyntaxList, moduleKeyword: ISyntaxToken, name: INameSyntax, stringLiteral: ISyntaxToken, openBraceToken: ISyntaxToken, moduleElements: ISyntaxList, closeBraceToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isModuleElement(): boolean; + public update(modifiers: ISyntaxList, moduleKeyword: ISyntaxToken, name: INameSyntax, stringLiteral: ISyntaxToken, openBraceToken: ISyntaxToken, moduleElements: ISyntaxList, closeBraceToken: ISyntaxToken): ModuleDeclarationSyntax; + static create(moduleKeyword: ISyntaxToken, openBraceToken: ISyntaxToken, closeBraceToken: ISyntaxToken): ModuleDeclarationSyntax; + static create1(): ModuleDeclarationSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ModuleDeclarationSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ModuleDeclarationSyntax; + public withModifiers(modifiers: ISyntaxList): ModuleDeclarationSyntax; + public withModifier(modifier: ISyntaxToken): ModuleDeclarationSyntax; + public withModuleKeyword(moduleKeyword: ISyntaxToken): ModuleDeclarationSyntax; + public withName(name: INameSyntax): ModuleDeclarationSyntax; + public withStringLiteral(stringLiteral: ISyntaxToken): ModuleDeclarationSyntax; + public withOpenBraceToken(openBraceToken: ISyntaxToken): ModuleDeclarationSyntax; + public withModuleElements(moduleElements: ISyntaxList): ModuleDeclarationSyntax; + public withModuleElement(moduleElement: IModuleElementSyntax): ModuleDeclarationSyntax; + public withCloseBraceToken(closeBraceToken: ISyntaxToken): ModuleDeclarationSyntax; + public isTypeScriptSpecific(): boolean; + } + class FunctionDeclarationSyntax extends SyntaxNode implements IStatementSyntax { + public modifiers: ISyntaxList; + public functionKeyword: ISyntaxToken; + public identifier: ISyntaxToken; + public callSignature: CallSignatureSyntax; + public block: BlockSyntax; + public semicolonToken: ISyntaxToken; + constructor(modifiers: ISyntaxList, functionKeyword: ISyntaxToken, identifier: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(modifiers: ISyntaxList, functionKeyword: ISyntaxToken, identifier: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): FunctionDeclarationSyntax; + static create(functionKeyword: ISyntaxToken, identifier: ISyntaxToken, callSignature: CallSignatureSyntax): FunctionDeclarationSyntax; + static create1(identifier: ISyntaxToken): FunctionDeclarationSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): FunctionDeclarationSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): FunctionDeclarationSyntax; + public withModifiers(modifiers: ISyntaxList): FunctionDeclarationSyntax; + public withModifier(modifier: ISyntaxToken): FunctionDeclarationSyntax; + public withFunctionKeyword(functionKeyword: ISyntaxToken): FunctionDeclarationSyntax; + public withIdentifier(identifier: ISyntaxToken): FunctionDeclarationSyntax; + public withCallSignature(callSignature: CallSignatureSyntax): FunctionDeclarationSyntax; + public withBlock(block: BlockSyntax): FunctionDeclarationSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): FunctionDeclarationSyntax; + public isTypeScriptSpecific(): boolean; + } + class VariableStatementSyntax extends SyntaxNode implements IStatementSyntax { + public modifiers: ISyntaxList; + public variableDeclaration: VariableDeclarationSyntax; + public semicolonToken: ISyntaxToken; + constructor(modifiers: ISyntaxList, variableDeclaration: VariableDeclarationSyntax, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(modifiers: ISyntaxList, variableDeclaration: VariableDeclarationSyntax, semicolonToken: ISyntaxToken): VariableStatementSyntax; + static create(variableDeclaration: VariableDeclarationSyntax, semicolonToken: ISyntaxToken): VariableStatementSyntax; + static create1(variableDeclaration: VariableDeclarationSyntax): VariableStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): VariableStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): VariableStatementSyntax; + public withModifiers(modifiers: ISyntaxList): VariableStatementSyntax; + public withModifier(modifier: ISyntaxToken): VariableStatementSyntax; + public withVariableDeclaration(variableDeclaration: VariableDeclarationSyntax): VariableStatementSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): VariableStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class VariableDeclarationSyntax extends SyntaxNode { + public varKeyword: ISyntaxToken; + public variableDeclarators: ISeparatedSyntaxList; + constructor(varKeyword: ISyntaxToken, variableDeclarators: ISeparatedSyntaxList, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(varKeyword: ISyntaxToken, variableDeclarators: ISeparatedSyntaxList): VariableDeclarationSyntax; + static create1(variableDeclarators: ISeparatedSyntaxList): VariableDeclarationSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): VariableDeclarationSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): VariableDeclarationSyntax; + public withVarKeyword(varKeyword: ISyntaxToken): VariableDeclarationSyntax; + public withVariableDeclarators(variableDeclarators: ISeparatedSyntaxList): VariableDeclarationSyntax; + public withVariableDeclarator(variableDeclarator: VariableDeclaratorSyntax): VariableDeclarationSyntax; + public isTypeScriptSpecific(): boolean; + } + class VariableDeclaratorSyntax extends SyntaxNode { + public propertyName: ISyntaxToken; + public typeAnnotation: TypeAnnotationSyntax; + public equalsValueClause: EqualsValueClauseSyntax; + constructor(propertyName: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, equalsValueClause: EqualsValueClauseSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(propertyName: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, equalsValueClause: EqualsValueClauseSyntax): VariableDeclaratorSyntax; + static create(propertyName: ISyntaxToken): VariableDeclaratorSyntax; + static create1(propertyName: ISyntaxToken): VariableDeclaratorSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): VariableDeclaratorSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): VariableDeclaratorSyntax; + public withPropertyName(propertyName: ISyntaxToken): VariableDeclaratorSyntax; + public withTypeAnnotation(typeAnnotation: TypeAnnotationSyntax): VariableDeclaratorSyntax; + public withEqualsValueClause(equalsValueClause: EqualsValueClauseSyntax): VariableDeclaratorSyntax; + public isTypeScriptSpecific(): boolean; + } + class EqualsValueClauseSyntax extends SyntaxNode { + public equalsToken: ISyntaxToken; + public value: IExpressionSyntax; + constructor(equalsToken: ISyntaxToken, value: IExpressionSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(equalsToken: ISyntaxToken, value: IExpressionSyntax): EqualsValueClauseSyntax; + static create1(value: IExpressionSyntax): EqualsValueClauseSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): EqualsValueClauseSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): EqualsValueClauseSyntax; + public withEqualsToken(equalsToken: ISyntaxToken): EqualsValueClauseSyntax; + public withValue(value: IExpressionSyntax): EqualsValueClauseSyntax; + public isTypeScriptSpecific(): boolean; + } + class PrefixUnaryExpressionSyntax extends SyntaxNode implements IUnaryExpressionSyntax { + public operatorToken: ISyntaxToken; + public operand: IUnaryExpressionSyntax; + private _kind; + constructor(kind: SyntaxKind, operatorToken: ISyntaxToken, operand: IUnaryExpressionSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public kind(): SyntaxKind; + public update(kind: SyntaxKind, operatorToken: ISyntaxToken, operand: IUnaryExpressionSyntax): PrefixUnaryExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): PrefixUnaryExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): PrefixUnaryExpressionSyntax; + public withKind(kind: SyntaxKind): PrefixUnaryExpressionSyntax; + public withOperatorToken(operatorToken: ISyntaxToken): PrefixUnaryExpressionSyntax; + public withOperand(operand: IUnaryExpressionSyntax): PrefixUnaryExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class ArrayLiteralExpressionSyntax extends SyntaxNode implements IPrimaryExpressionSyntax { + public openBracketToken: ISyntaxToken; + public expressions: ISeparatedSyntaxList; + public closeBracketToken: ISyntaxToken; + constructor(openBracketToken: ISyntaxToken, expressions: ISeparatedSyntaxList, closeBracketToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isPrimaryExpression(): boolean; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public update(openBracketToken: ISyntaxToken, expressions: ISeparatedSyntaxList, closeBracketToken: ISyntaxToken): ArrayLiteralExpressionSyntax; + static create(openBracketToken: ISyntaxToken, closeBracketToken: ISyntaxToken): ArrayLiteralExpressionSyntax; + static create1(): ArrayLiteralExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ArrayLiteralExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ArrayLiteralExpressionSyntax; + public withOpenBracketToken(openBracketToken: ISyntaxToken): ArrayLiteralExpressionSyntax; + public withExpressions(expressions: ISeparatedSyntaxList): ArrayLiteralExpressionSyntax; + public withExpression(expression: IExpressionSyntax): ArrayLiteralExpressionSyntax; + public withCloseBracketToken(closeBracketToken: ISyntaxToken): ArrayLiteralExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class OmittedExpressionSyntax extends SyntaxNode implements IExpressionSyntax { + constructor(parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isExpression(): boolean; + public update(): OmittedExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): OmittedExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): OmittedExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class ParenthesizedExpressionSyntax extends SyntaxNode implements IPrimaryExpressionSyntax { + public openParenToken: ISyntaxToken; + public expression: IExpressionSyntax; + public closeParenToken: ISyntaxToken; + constructor(openParenToken: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isPrimaryExpression(): boolean; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public update(openParenToken: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken): ParenthesizedExpressionSyntax; + static create1(expression: IExpressionSyntax): ParenthesizedExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ParenthesizedExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ParenthesizedExpressionSyntax; + public withOpenParenToken(openParenToken: ISyntaxToken): ParenthesizedExpressionSyntax; + public withExpression(expression: IExpressionSyntax): ParenthesizedExpressionSyntax; + public withCloseParenToken(closeParenToken: ISyntaxToken): ParenthesizedExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class SimpleArrowFunctionExpressionSyntax extends SyntaxNode implements IArrowFunctionExpressionSyntax { + public identifier: ISyntaxToken; + public equalsGreaterThanToken: ISyntaxToken; + public block: BlockSyntax; + public expression: IExpressionSyntax; + constructor(identifier: ISyntaxToken, equalsGreaterThanToken: ISyntaxToken, block: BlockSyntax, expression: IExpressionSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isArrowFunctionExpression(): boolean; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public update(identifier: ISyntaxToken, equalsGreaterThanToken: ISyntaxToken, block: BlockSyntax, expression: IExpressionSyntax): SimpleArrowFunctionExpressionSyntax; + static create(identifier: ISyntaxToken, equalsGreaterThanToken: ISyntaxToken): SimpleArrowFunctionExpressionSyntax; + static create1(identifier: ISyntaxToken): SimpleArrowFunctionExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): SimpleArrowFunctionExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): SimpleArrowFunctionExpressionSyntax; + public withIdentifier(identifier: ISyntaxToken): SimpleArrowFunctionExpressionSyntax; + public withEqualsGreaterThanToken(equalsGreaterThanToken: ISyntaxToken): SimpleArrowFunctionExpressionSyntax; + public withBlock(block: BlockSyntax): SimpleArrowFunctionExpressionSyntax; + public withExpression(expression: IExpressionSyntax): SimpleArrowFunctionExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class ParenthesizedArrowFunctionExpressionSyntax extends SyntaxNode implements IArrowFunctionExpressionSyntax { + public callSignature: CallSignatureSyntax; + public equalsGreaterThanToken: ISyntaxToken; + public block: BlockSyntax; + public expression: IExpressionSyntax; + constructor(callSignature: CallSignatureSyntax, equalsGreaterThanToken: ISyntaxToken, block: BlockSyntax, expression: IExpressionSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isArrowFunctionExpression(): boolean; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public update(callSignature: CallSignatureSyntax, equalsGreaterThanToken: ISyntaxToken, block: BlockSyntax, expression: IExpressionSyntax): ParenthesizedArrowFunctionExpressionSyntax; + static create(callSignature: CallSignatureSyntax, equalsGreaterThanToken: ISyntaxToken): ParenthesizedArrowFunctionExpressionSyntax; + static create1(): ParenthesizedArrowFunctionExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ParenthesizedArrowFunctionExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ParenthesizedArrowFunctionExpressionSyntax; + public withCallSignature(callSignature: CallSignatureSyntax): ParenthesizedArrowFunctionExpressionSyntax; + public withEqualsGreaterThanToken(equalsGreaterThanToken: ISyntaxToken): ParenthesizedArrowFunctionExpressionSyntax; + public withBlock(block: BlockSyntax): ParenthesizedArrowFunctionExpressionSyntax; + public withExpression(expression: IExpressionSyntax): ParenthesizedArrowFunctionExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class QualifiedNameSyntax extends SyntaxNode implements INameSyntax { + public left: INameSyntax; + public dotToken: ISyntaxToken; + public right: ISyntaxToken; + constructor(left: INameSyntax, dotToken: ISyntaxToken, right: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isName(): boolean; + public isType(): boolean; + public update(left: INameSyntax, dotToken: ISyntaxToken, right: ISyntaxToken): QualifiedNameSyntax; + static create1(left: INameSyntax, right: ISyntaxToken): QualifiedNameSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): QualifiedNameSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): QualifiedNameSyntax; + public withLeft(left: INameSyntax): QualifiedNameSyntax; + public withDotToken(dotToken: ISyntaxToken): QualifiedNameSyntax; + public withRight(right: ISyntaxToken): QualifiedNameSyntax; + public isTypeScriptSpecific(): boolean; + } + class TypeArgumentListSyntax extends SyntaxNode { + public lessThanToken: ISyntaxToken; + public typeArguments: ISeparatedSyntaxList; + public greaterThanToken: ISyntaxToken; + constructor(lessThanToken: ISyntaxToken, typeArguments: ISeparatedSyntaxList, greaterThanToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(lessThanToken: ISyntaxToken, typeArguments: ISeparatedSyntaxList, greaterThanToken: ISyntaxToken): TypeArgumentListSyntax; + static create(lessThanToken: ISyntaxToken, greaterThanToken: ISyntaxToken): TypeArgumentListSyntax; + static create1(): TypeArgumentListSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): TypeArgumentListSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): TypeArgumentListSyntax; + public withLessThanToken(lessThanToken: ISyntaxToken): TypeArgumentListSyntax; + public withTypeArguments(typeArguments: ISeparatedSyntaxList): TypeArgumentListSyntax; + public withTypeArgument(typeArgument: ITypeSyntax): TypeArgumentListSyntax; + public withGreaterThanToken(greaterThanToken: ISyntaxToken): TypeArgumentListSyntax; + public isTypeScriptSpecific(): boolean; + } + class ConstructorTypeSyntax extends SyntaxNode implements ITypeSyntax { + public newKeyword: ISyntaxToken; + public typeParameterList: TypeParameterListSyntax; + public parameterList: ParameterListSyntax; + public equalsGreaterThanToken: ISyntaxToken; + public type: ITypeSyntax; + constructor(newKeyword: ISyntaxToken, typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, equalsGreaterThanToken: ISyntaxToken, type: ITypeSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isType(): boolean; + public update(newKeyword: ISyntaxToken, typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, equalsGreaterThanToken: ISyntaxToken, type: ITypeSyntax): ConstructorTypeSyntax; + static create(newKeyword: ISyntaxToken, parameterList: ParameterListSyntax, equalsGreaterThanToken: ISyntaxToken, type: ITypeSyntax): ConstructorTypeSyntax; + static create1(type: ITypeSyntax): ConstructorTypeSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ConstructorTypeSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ConstructorTypeSyntax; + public withNewKeyword(newKeyword: ISyntaxToken): ConstructorTypeSyntax; + public withTypeParameterList(typeParameterList: TypeParameterListSyntax): ConstructorTypeSyntax; + public withParameterList(parameterList: ParameterListSyntax): ConstructorTypeSyntax; + public withEqualsGreaterThanToken(equalsGreaterThanToken: ISyntaxToken): ConstructorTypeSyntax; + public withType(type: ITypeSyntax): ConstructorTypeSyntax; + public isTypeScriptSpecific(): boolean; + } + class FunctionTypeSyntax extends SyntaxNode implements ITypeSyntax { + public typeParameterList: TypeParameterListSyntax; + public parameterList: ParameterListSyntax; + public equalsGreaterThanToken: ISyntaxToken; + public type: ITypeSyntax; + constructor(typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, equalsGreaterThanToken: ISyntaxToken, type: ITypeSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isType(): boolean; + public update(typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, equalsGreaterThanToken: ISyntaxToken, type: ITypeSyntax): FunctionTypeSyntax; + static create(parameterList: ParameterListSyntax, equalsGreaterThanToken: ISyntaxToken, type: ITypeSyntax): FunctionTypeSyntax; + static create1(type: ITypeSyntax): FunctionTypeSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): FunctionTypeSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): FunctionTypeSyntax; + public withTypeParameterList(typeParameterList: TypeParameterListSyntax): FunctionTypeSyntax; + public withParameterList(parameterList: ParameterListSyntax): FunctionTypeSyntax; + public withEqualsGreaterThanToken(equalsGreaterThanToken: ISyntaxToken): FunctionTypeSyntax; + public withType(type: ITypeSyntax): FunctionTypeSyntax; + public isTypeScriptSpecific(): boolean; + } + class ObjectTypeSyntax extends SyntaxNode implements ITypeSyntax { + public openBraceToken: ISyntaxToken; + public typeMembers: ISeparatedSyntaxList; + public closeBraceToken: ISyntaxToken; + constructor(openBraceToken: ISyntaxToken, typeMembers: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isType(): boolean; + public update(openBraceToken: ISyntaxToken, typeMembers: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken): ObjectTypeSyntax; + static create(openBraceToken: ISyntaxToken, closeBraceToken: ISyntaxToken): ObjectTypeSyntax; + static create1(): ObjectTypeSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ObjectTypeSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ObjectTypeSyntax; + public withOpenBraceToken(openBraceToken: ISyntaxToken): ObjectTypeSyntax; + public withTypeMembers(typeMembers: ISeparatedSyntaxList): ObjectTypeSyntax; + public withTypeMember(typeMember: ITypeMemberSyntax): ObjectTypeSyntax; + public withCloseBraceToken(closeBraceToken: ISyntaxToken): ObjectTypeSyntax; + public isTypeScriptSpecific(): boolean; + } + class ArrayTypeSyntax extends SyntaxNode implements ITypeSyntax { + public type: ITypeSyntax; + public openBracketToken: ISyntaxToken; + public closeBracketToken: ISyntaxToken; + constructor(type: ITypeSyntax, openBracketToken: ISyntaxToken, closeBracketToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isType(): boolean; + public update(type: ITypeSyntax, openBracketToken: ISyntaxToken, closeBracketToken: ISyntaxToken): ArrayTypeSyntax; + static create1(type: ITypeSyntax): ArrayTypeSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ArrayTypeSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ArrayTypeSyntax; + public withType(type: ITypeSyntax): ArrayTypeSyntax; + public withOpenBracketToken(openBracketToken: ISyntaxToken): ArrayTypeSyntax; + public withCloseBracketToken(closeBracketToken: ISyntaxToken): ArrayTypeSyntax; + public isTypeScriptSpecific(): boolean; + } + class GenericTypeSyntax extends SyntaxNode implements ITypeSyntax { + public name: INameSyntax; + public typeArgumentList: TypeArgumentListSyntax; + constructor(name: INameSyntax, typeArgumentList: TypeArgumentListSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isType(): boolean; + public update(name: INameSyntax, typeArgumentList: TypeArgumentListSyntax): GenericTypeSyntax; + static create1(name: INameSyntax): GenericTypeSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): GenericTypeSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): GenericTypeSyntax; + public withName(name: INameSyntax): GenericTypeSyntax; + public withTypeArgumentList(typeArgumentList: TypeArgumentListSyntax): GenericTypeSyntax; + public isTypeScriptSpecific(): boolean; + } + class TypeQuerySyntax extends SyntaxNode implements ITypeSyntax { + public typeOfKeyword: ISyntaxToken; + public name: INameSyntax; + constructor(typeOfKeyword: ISyntaxToken, name: INameSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isType(): boolean; + public update(typeOfKeyword: ISyntaxToken, name: INameSyntax): TypeQuerySyntax; + static create1(name: INameSyntax): TypeQuerySyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): TypeQuerySyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): TypeQuerySyntax; + public withTypeOfKeyword(typeOfKeyword: ISyntaxToken): TypeQuerySyntax; + public withName(name: INameSyntax): TypeQuerySyntax; + public isTypeScriptSpecific(): boolean; + } + class TypeAnnotationSyntax extends SyntaxNode { + public colonToken: ISyntaxToken; + public type: ITypeSyntax; + constructor(colonToken: ISyntaxToken, type: ITypeSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(colonToken: ISyntaxToken, type: ITypeSyntax): TypeAnnotationSyntax; + static create1(type: ITypeSyntax): TypeAnnotationSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): TypeAnnotationSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): TypeAnnotationSyntax; + public withColonToken(colonToken: ISyntaxToken): TypeAnnotationSyntax; + public withType(type: ITypeSyntax): TypeAnnotationSyntax; + public isTypeScriptSpecific(): boolean; + } + class BlockSyntax extends SyntaxNode implements IStatementSyntax { + public openBraceToken: ISyntaxToken; + public statements: ISyntaxList; + public closeBraceToken: ISyntaxToken; + constructor(openBraceToken: ISyntaxToken, statements: ISyntaxList, closeBraceToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(openBraceToken: ISyntaxToken, statements: ISyntaxList, closeBraceToken: ISyntaxToken): BlockSyntax; + static create(openBraceToken: ISyntaxToken, closeBraceToken: ISyntaxToken): BlockSyntax; + static create1(): BlockSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): BlockSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): BlockSyntax; + public withOpenBraceToken(openBraceToken: ISyntaxToken): BlockSyntax; + public withStatements(statements: ISyntaxList): BlockSyntax; + public withStatement(statement: IStatementSyntax): BlockSyntax; + public withCloseBraceToken(closeBraceToken: ISyntaxToken): BlockSyntax; + public isTypeScriptSpecific(): boolean; + } + class ParameterSyntax extends SyntaxNode { + public dotDotDotToken: ISyntaxToken; + public modifiers: ISyntaxList; + public identifier: ISyntaxToken; + public questionToken: ISyntaxToken; + public typeAnnotation: TypeAnnotationSyntax; + public equalsValueClause: EqualsValueClauseSyntax; + constructor(dotDotDotToken: ISyntaxToken, modifiers: ISyntaxList, identifier: ISyntaxToken, questionToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, equalsValueClause: EqualsValueClauseSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(dotDotDotToken: ISyntaxToken, modifiers: ISyntaxList, identifier: ISyntaxToken, questionToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, equalsValueClause: EqualsValueClauseSyntax): ParameterSyntax; + static create(identifier: ISyntaxToken): ParameterSyntax; + static create1(identifier: ISyntaxToken): ParameterSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ParameterSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ParameterSyntax; + public withDotDotDotToken(dotDotDotToken: ISyntaxToken): ParameterSyntax; + public withModifiers(modifiers: ISyntaxList): ParameterSyntax; + public withModifier(modifier: ISyntaxToken): ParameterSyntax; + public withIdentifier(identifier: ISyntaxToken): ParameterSyntax; + public withQuestionToken(questionToken: ISyntaxToken): ParameterSyntax; + public withTypeAnnotation(typeAnnotation: TypeAnnotationSyntax): ParameterSyntax; + public withEqualsValueClause(equalsValueClause: EqualsValueClauseSyntax): ParameterSyntax; + public isTypeScriptSpecific(): boolean; + } + class MemberAccessExpressionSyntax extends SyntaxNode implements IMemberExpressionSyntax { + public expression: IExpressionSyntax; + public dotToken: ISyntaxToken; + public name: ISyntaxToken; + constructor(expression: IExpressionSyntax, dotToken: ISyntaxToken, name: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public update(expression: IExpressionSyntax, dotToken: ISyntaxToken, name: ISyntaxToken): MemberAccessExpressionSyntax; + static create1(expression: IExpressionSyntax, name: ISyntaxToken): MemberAccessExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): MemberAccessExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): MemberAccessExpressionSyntax; + public withExpression(expression: IExpressionSyntax): MemberAccessExpressionSyntax; + public withDotToken(dotToken: ISyntaxToken): MemberAccessExpressionSyntax; + public withName(name: ISyntaxToken): MemberAccessExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class PostfixUnaryExpressionSyntax extends SyntaxNode implements IPostfixExpressionSyntax { + public operand: IMemberExpressionSyntax; + public operatorToken: ISyntaxToken; + private _kind; + constructor(kind: SyntaxKind, operand: IMemberExpressionSyntax, operatorToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public kind(): SyntaxKind; + public update(kind: SyntaxKind, operand: IMemberExpressionSyntax, operatorToken: ISyntaxToken): PostfixUnaryExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): PostfixUnaryExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): PostfixUnaryExpressionSyntax; + public withKind(kind: SyntaxKind): PostfixUnaryExpressionSyntax; + public withOperand(operand: IMemberExpressionSyntax): PostfixUnaryExpressionSyntax; + public withOperatorToken(operatorToken: ISyntaxToken): PostfixUnaryExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class ElementAccessExpressionSyntax extends SyntaxNode implements IMemberExpressionSyntax { + public expression: IExpressionSyntax; + public openBracketToken: ISyntaxToken; + public argumentExpression: IExpressionSyntax; + public closeBracketToken: ISyntaxToken; + constructor(expression: IExpressionSyntax, openBracketToken: ISyntaxToken, argumentExpression: IExpressionSyntax, closeBracketToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public update(expression: IExpressionSyntax, openBracketToken: ISyntaxToken, argumentExpression: IExpressionSyntax, closeBracketToken: ISyntaxToken): ElementAccessExpressionSyntax; + static create1(expression: IExpressionSyntax, argumentExpression: IExpressionSyntax): ElementAccessExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ElementAccessExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ElementAccessExpressionSyntax; + public withExpression(expression: IExpressionSyntax): ElementAccessExpressionSyntax; + public withOpenBracketToken(openBracketToken: ISyntaxToken): ElementAccessExpressionSyntax; + public withArgumentExpression(argumentExpression: IExpressionSyntax): ElementAccessExpressionSyntax; + public withCloseBracketToken(closeBracketToken: ISyntaxToken): ElementAccessExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class InvocationExpressionSyntax extends SyntaxNode implements IMemberExpressionSyntax { + public expression: IMemberExpressionSyntax; + public argumentList: ArgumentListSyntax; + constructor(expression: IMemberExpressionSyntax, argumentList: ArgumentListSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public update(expression: IMemberExpressionSyntax, argumentList: ArgumentListSyntax): InvocationExpressionSyntax; + static create1(expression: IMemberExpressionSyntax): InvocationExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): InvocationExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): InvocationExpressionSyntax; + public withExpression(expression: IMemberExpressionSyntax): InvocationExpressionSyntax; + public withArgumentList(argumentList: ArgumentListSyntax): InvocationExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class ArgumentListSyntax extends SyntaxNode { + public typeArgumentList: TypeArgumentListSyntax; + public openParenToken: ISyntaxToken; + public closeParenToken: ISyntaxToken; + public arguments: ISeparatedSyntaxList; + constructor(typeArgumentList: TypeArgumentListSyntax, openParenToken: ISyntaxToken, _arguments: ISeparatedSyntaxList, closeParenToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(typeArgumentList: TypeArgumentListSyntax, openParenToken: ISyntaxToken, _arguments: ISeparatedSyntaxList, closeParenToken: ISyntaxToken): ArgumentListSyntax; + static create(openParenToken: ISyntaxToken, closeParenToken: ISyntaxToken): ArgumentListSyntax; + static create1(): ArgumentListSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ArgumentListSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ArgumentListSyntax; + public withTypeArgumentList(typeArgumentList: TypeArgumentListSyntax): ArgumentListSyntax; + public withOpenParenToken(openParenToken: ISyntaxToken): ArgumentListSyntax; + public withArguments(_arguments: ISeparatedSyntaxList): ArgumentListSyntax; + public withArgument(_argument: IExpressionSyntax): ArgumentListSyntax; + public withCloseParenToken(closeParenToken: ISyntaxToken): ArgumentListSyntax; + public isTypeScriptSpecific(): boolean; + } + class BinaryExpressionSyntax extends SyntaxNode implements IExpressionSyntax { + public left: IExpressionSyntax; + public operatorToken: ISyntaxToken; + public right: IExpressionSyntax; + private _kind; + constructor(kind: SyntaxKind, left: IExpressionSyntax, operatorToken: ISyntaxToken, right: IExpressionSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isExpression(): boolean; + public kind(): SyntaxKind; + public update(kind: SyntaxKind, left: IExpressionSyntax, operatorToken: ISyntaxToken, right: IExpressionSyntax): BinaryExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): BinaryExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): BinaryExpressionSyntax; + public withKind(kind: SyntaxKind): BinaryExpressionSyntax; + public withLeft(left: IExpressionSyntax): BinaryExpressionSyntax; + public withOperatorToken(operatorToken: ISyntaxToken): BinaryExpressionSyntax; + public withRight(right: IExpressionSyntax): BinaryExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class ConditionalExpressionSyntax extends SyntaxNode implements IExpressionSyntax { + public condition: IExpressionSyntax; + public questionToken: ISyntaxToken; + public whenTrue: IExpressionSyntax; + public colonToken: ISyntaxToken; + public whenFalse: IExpressionSyntax; + constructor(condition: IExpressionSyntax, questionToken: ISyntaxToken, whenTrue: IExpressionSyntax, colonToken: ISyntaxToken, whenFalse: IExpressionSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isExpression(): boolean; + public update(condition: IExpressionSyntax, questionToken: ISyntaxToken, whenTrue: IExpressionSyntax, colonToken: ISyntaxToken, whenFalse: IExpressionSyntax): ConditionalExpressionSyntax; + static create1(condition: IExpressionSyntax, whenTrue: IExpressionSyntax, whenFalse: IExpressionSyntax): ConditionalExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ConditionalExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ConditionalExpressionSyntax; + public withCondition(condition: IExpressionSyntax): ConditionalExpressionSyntax; + public withQuestionToken(questionToken: ISyntaxToken): ConditionalExpressionSyntax; + public withWhenTrue(whenTrue: IExpressionSyntax): ConditionalExpressionSyntax; + public withColonToken(colonToken: ISyntaxToken): ConditionalExpressionSyntax; + public withWhenFalse(whenFalse: IExpressionSyntax): ConditionalExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class ConstructSignatureSyntax extends SyntaxNode implements ITypeMemberSyntax { + public newKeyword: ISyntaxToken; + public callSignature: CallSignatureSyntax; + constructor(newKeyword: ISyntaxToken, callSignature: CallSignatureSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isTypeMember(): boolean; + public update(newKeyword: ISyntaxToken, callSignature: CallSignatureSyntax): ConstructSignatureSyntax; + static create1(): ConstructSignatureSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ConstructSignatureSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ConstructSignatureSyntax; + public withNewKeyword(newKeyword: ISyntaxToken): ConstructSignatureSyntax; + public withCallSignature(callSignature: CallSignatureSyntax): ConstructSignatureSyntax; + public isTypeScriptSpecific(): boolean; + } + class MethodSignatureSyntax extends SyntaxNode implements ITypeMemberSyntax { + public propertyName: ISyntaxToken; + public questionToken: ISyntaxToken; + public callSignature: CallSignatureSyntax; + constructor(propertyName: ISyntaxToken, questionToken: ISyntaxToken, callSignature: CallSignatureSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isTypeMember(): boolean; + public update(propertyName: ISyntaxToken, questionToken: ISyntaxToken, callSignature: CallSignatureSyntax): MethodSignatureSyntax; + static create(propertyName: ISyntaxToken, callSignature: CallSignatureSyntax): MethodSignatureSyntax; + static create1(propertyName: ISyntaxToken): MethodSignatureSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): MethodSignatureSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): MethodSignatureSyntax; + public withPropertyName(propertyName: ISyntaxToken): MethodSignatureSyntax; + public withQuestionToken(questionToken: ISyntaxToken): MethodSignatureSyntax; + public withCallSignature(callSignature: CallSignatureSyntax): MethodSignatureSyntax; + public isTypeScriptSpecific(): boolean; + } + class IndexSignatureSyntax extends SyntaxNode implements ITypeMemberSyntax { + public openBracketToken: ISyntaxToken; + public parameter: ParameterSyntax; + public closeBracketToken: ISyntaxToken; + public typeAnnotation: TypeAnnotationSyntax; + constructor(openBracketToken: ISyntaxToken, parameter: ParameterSyntax, closeBracketToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isTypeMember(): boolean; + public update(openBracketToken: ISyntaxToken, parameter: ParameterSyntax, closeBracketToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax): IndexSignatureSyntax; + static create(openBracketToken: ISyntaxToken, parameter: ParameterSyntax, closeBracketToken: ISyntaxToken): IndexSignatureSyntax; + static create1(parameter: ParameterSyntax): IndexSignatureSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): IndexSignatureSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): IndexSignatureSyntax; + public withOpenBracketToken(openBracketToken: ISyntaxToken): IndexSignatureSyntax; + public withParameter(parameter: ParameterSyntax): IndexSignatureSyntax; + public withCloseBracketToken(closeBracketToken: ISyntaxToken): IndexSignatureSyntax; + public withTypeAnnotation(typeAnnotation: TypeAnnotationSyntax): IndexSignatureSyntax; + public isTypeScriptSpecific(): boolean; + } + class PropertySignatureSyntax extends SyntaxNode implements ITypeMemberSyntax { + public propertyName: ISyntaxToken; + public questionToken: ISyntaxToken; + public typeAnnotation: TypeAnnotationSyntax; + constructor(propertyName: ISyntaxToken, questionToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isTypeMember(): boolean; + public update(propertyName: ISyntaxToken, questionToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax): PropertySignatureSyntax; + static create(propertyName: ISyntaxToken): PropertySignatureSyntax; + static create1(propertyName: ISyntaxToken): PropertySignatureSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): PropertySignatureSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): PropertySignatureSyntax; + public withPropertyName(propertyName: ISyntaxToken): PropertySignatureSyntax; + public withQuestionToken(questionToken: ISyntaxToken): PropertySignatureSyntax; + public withTypeAnnotation(typeAnnotation: TypeAnnotationSyntax): PropertySignatureSyntax; + public isTypeScriptSpecific(): boolean; + } + class CallSignatureSyntax extends SyntaxNode implements ITypeMemberSyntax { + public typeParameterList: TypeParameterListSyntax; + public parameterList: ParameterListSyntax; + public typeAnnotation: TypeAnnotationSyntax; + constructor(typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, typeAnnotation: TypeAnnotationSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isTypeMember(): boolean; + public update(typeParameterList: TypeParameterListSyntax, parameterList: ParameterListSyntax, typeAnnotation: TypeAnnotationSyntax): CallSignatureSyntax; + static create(parameterList: ParameterListSyntax): CallSignatureSyntax; + static create1(): CallSignatureSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): CallSignatureSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): CallSignatureSyntax; + public withTypeParameterList(typeParameterList: TypeParameterListSyntax): CallSignatureSyntax; + public withParameterList(parameterList: ParameterListSyntax): CallSignatureSyntax; + public withTypeAnnotation(typeAnnotation: TypeAnnotationSyntax): CallSignatureSyntax; + public isTypeScriptSpecific(): boolean; + } + class ParameterListSyntax extends SyntaxNode { + public openParenToken: ISyntaxToken; + public parameters: ISeparatedSyntaxList; + public closeParenToken: ISyntaxToken; + constructor(openParenToken: ISyntaxToken, parameters: ISeparatedSyntaxList, closeParenToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(openParenToken: ISyntaxToken, parameters: ISeparatedSyntaxList, closeParenToken: ISyntaxToken): ParameterListSyntax; + static create(openParenToken: ISyntaxToken, closeParenToken: ISyntaxToken): ParameterListSyntax; + static create1(): ParameterListSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ParameterListSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ParameterListSyntax; + public withOpenParenToken(openParenToken: ISyntaxToken): ParameterListSyntax; + public withParameters(parameters: ISeparatedSyntaxList): ParameterListSyntax; + public withParameter(parameter: ParameterSyntax): ParameterListSyntax; + public withCloseParenToken(closeParenToken: ISyntaxToken): ParameterListSyntax; + public isTypeScriptSpecific(): boolean; + } + class TypeParameterListSyntax extends SyntaxNode { + public lessThanToken: ISyntaxToken; + public typeParameters: ISeparatedSyntaxList; + public greaterThanToken: ISyntaxToken; + constructor(lessThanToken: ISyntaxToken, typeParameters: ISeparatedSyntaxList, greaterThanToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(lessThanToken: ISyntaxToken, typeParameters: ISeparatedSyntaxList, greaterThanToken: ISyntaxToken): TypeParameterListSyntax; + static create(lessThanToken: ISyntaxToken, greaterThanToken: ISyntaxToken): TypeParameterListSyntax; + static create1(): TypeParameterListSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): TypeParameterListSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): TypeParameterListSyntax; + public withLessThanToken(lessThanToken: ISyntaxToken): TypeParameterListSyntax; + public withTypeParameters(typeParameters: ISeparatedSyntaxList): TypeParameterListSyntax; + public withTypeParameter(typeParameter: TypeParameterSyntax): TypeParameterListSyntax; + public withGreaterThanToken(greaterThanToken: ISyntaxToken): TypeParameterListSyntax; + public isTypeScriptSpecific(): boolean; + } + class TypeParameterSyntax extends SyntaxNode { + public identifier: ISyntaxToken; + public constraint: ConstraintSyntax; + constructor(identifier: ISyntaxToken, constraint: ConstraintSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(identifier: ISyntaxToken, constraint: ConstraintSyntax): TypeParameterSyntax; + static create(identifier: ISyntaxToken): TypeParameterSyntax; + static create1(identifier: ISyntaxToken): TypeParameterSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): TypeParameterSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): TypeParameterSyntax; + public withIdentifier(identifier: ISyntaxToken): TypeParameterSyntax; + public withConstraint(constraint: ConstraintSyntax): TypeParameterSyntax; + public isTypeScriptSpecific(): boolean; + } + class ConstraintSyntax extends SyntaxNode { + public extendsKeyword: ISyntaxToken; + public type: ITypeSyntax; + constructor(extendsKeyword: ISyntaxToken, type: ITypeSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(extendsKeyword: ISyntaxToken, type: ITypeSyntax): ConstraintSyntax; + static create1(type: ITypeSyntax): ConstraintSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ConstraintSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ConstraintSyntax; + public withExtendsKeyword(extendsKeyword: ISyntaxToken): ConstraintSyntax; + public withType(type: ITypeSyntax): ConstraintSyntax; + public isTypeScriptSpecific(): boolean; + } + class ElseClauseSyntax extends SyntaxNode { + public elseKeyword: ISyntaxToken; + public statement: IStatementSyntax; + constructor(elseKeyword: ISyntaxToken, statement: IStatementSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(elseKeyword: ISyntaxToken, statement: IStatementSyntax): ElseClauseSyntax; + static create1(statement: IStatementSyntax): ElseClauseSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ElseClauseSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ElseClauseSyntax; + public withElseKeyword(elseKeyword: ISyntaxToken): ElseClauseSyntax; + public withStatement(statement: IStatementSyntax): ElseClauseSyntax; + public isTypeScriptSpecific(): boolean; + } + class IfStatementSyntax extends SyntaxNode implements IStatementSyntax { + public ifKeyword: ISyntaxToken; + public openParenToken: ISyntaxToken; + public condition: IExpressionSyntax; + public closeParenToken: ISyntaxToken; + public statement: IStatementSyntax; + public elseClause: ElseClauseSyntax; + constructor(ifKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax, elseClause: ElseClauseSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(ifKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax, elseClause: ElseClauseSyntax): IfStatementSyntax; + static create(ifKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): IfStatementSyntax; + static create1(condition: IExpressionSyntax, statement: IStatementSyntax): IfStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): IfStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): IfStatementSyntax; + public withIfKeyword(ifKeyword: ISyntaxToken): IfStatementSyntax; + public withOpenParenToken(openParenToken: ISyntaxToken): IfStatementSyntax; + public withCondition(condition: IExpressionSyntax): IfStatementSyntax; + public withCloseParenToken(closeParenToken: ISyntaxToken): IfStatementSyntax; + public withStatement(statement: IStatementSyntax): IfStatementSyntax; + public withElseClause(elseClause: ElseClauseSyntax): IfStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class ExpressionStatementSyntax extends SyntaxNode implements IStatementSyntax { + public expression: IExpressionSyntax; + public semicolonToken: ISyntaxToken; + constructor(expression: IExpressionSyntax, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(expression: IExpressionSyntax, semicolonToken: ISyntaxToken): ExpressionStatementSyntax; + static create1(expression: IExpressionSyntax): ExpressionStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ExpressionStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ExpressionStatementSyntax; + public withExpression(expression: IExpressionSyntax): ExpressionStatementSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): ExpressionStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class ConstructorDeclarationSyntax extends SyntaxNode implements IClassElementSyntax { + public modifiers: ISyntaxList; + public constructorKeyword: ISyntaxToken; + public callSignature: CallSignatureSyntax; + public block: BlockSyntax; + public semicolonToken: ISyntaxToken; + constructor(modifiers: ISyntaxList, constructorKeyword: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isClassElement(): boolean; + public update(modifiers: ISyntaxList, constructorKeyword: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): ConstructorDeclarationSyntax; + static create(constructorKeyword: ISyntaxToken, callSignature: CallSignatureSyntax): ConstructorDeclarationSyntax; + static create1(): ConstructorDeclarationSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ConstructorDeclarationSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ConstructorDeclarationSyntax; + public withModifiers(modifiers: ISyntaxList): ConstructorDeclarationSyntax; + public withModifier(modifier: ISyntaxToken): ConstructorDeclarationSyntax; + public withConstructorKeyword(constructorKeyword: ISyntaxToken): ConstructorDeclarationSyntax; + public withCallSignature(callSignature: CallSignatureSyntax): ConstructorDeclarationSyntax; + public withBlock(block: BlockSyntax): ConstructorDeclarationSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): ConstructorDeclarationSyntax; + public isTypeScriptSpecific(): boolean; + } + class MemberFunctionDeclarationSyntax extends SyntaxNode implements IMemberDeclarationSyntax { + public modifiers: ISyntaxList; + public propertyName: ISyntaxToken; + public callSignature: CallSignatureSyntax; + public block: BlockSyntax; + public semicolonToken: ISyntaxToken; + constructor(modifiers: ISyntaxList, propertyName: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isMemberDeclaration(): boolean; + public isClassElement(): boolean; + public update(modifiers: ISyntaxList, propertyName: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): MemberFunctionDeclarationSyntax; + static create(propertyName: ISyntaxToken, callSignature: CallSignatureSyntax): MemberFunctionDeclarationSyntax; + static create1(propertyName: ISyntaxToken): MemberFunctionDeclarationSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): MemberFunctionDeclarationSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): MemberFunctionDeclarationSyntax; + public withModifiers(modifiers: ISyntaxList): MemberFunctionDeclarationSyntax; + public withModifier(modifier: ISyntaxToken): MemberFunctionDeclarationSyntax; + public withPropertyName(propertyName: ISyntaxToken): MemberFunctionDeclarationSyntax; + public withCallSignature(callSignature: CallSignatureSyntax): MemberFunctionDeclarationSyntax; + public withBlock(block: BlockSyntax): MemberFunctionDeclarationSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): MemberFunctionDeclarationSyntax; + public isTypeScriptSpecific(): boolean; + } + class GetAccessorSyntax extends SyntaxNode implements IMemberDeclarationSyntax, IPropertyAssignmentSyntax { + public modifiers: ISyntaxList; + public getKeyword: ISyntaxToken; + public propertyName: ISyntaxToken; + public parameterList: ParameterListSyntax; + public typeAnnotation: TypeAnnotationSyntax; + public block: BlockSyntax; + constructor(modifiers: ISyntaxList, getKeyword: ISyntaxToken, propertyName: ISyntaxToken, parameterList: ParameterListSyntax, typeAnnotation: TypeAnnotationSyntax, block: BlockSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isMemberDeclaration(): boolean; + public isPropertyAssignment(): boolean; + public isClassElement(): boolean; + public update(modifiers: ISyntaxList, getKeyword: ISyntaxToken, propertyName: ISyntaxToken, parameterList: ParameterListSyntax, typeAnnotation: TypeAnnotationSyntax, block: BlockSyntax): GetAccessorSyntax; + static create(getKeyword: ISyntaxToken, propertyName: ISyntaxToken, parameterList: ParameterListSyntax, block: BlockSyntax): GetAccessorSyntax; + static create1(propertyName: ISyntaxToken): GetAccessorSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): GetAccessorSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): GetAccessorSyntax; + public withModifiers(modifiers: ISyntaxList): GetAccessorSyntax; + public withModifier(modifier: ISyntaxToken): GetAccessorSyntax; + public withGetKeyword(getKeyword: ISyntaxToken): GetAccessorSyntax; + public withPropertyName(propertyName: ISyntaxToken): GetAccessorSyntax; + public withParameterList(parameterList: ParameterListSyntax): GetAccessorSyntax; + public withTypeAnnotation(typeAnnotation: TypeAnnotationSyntax): GetAccessorSyntax; + public withBlock(block: BlockSyntax): GetAccessorSyntax; + public isTypeScriptSpecific(): boolean; + } + class SetAccessorSyntax extends SyntaxNode implements IMemberDeclarationSyntax, IPropertyAssignmentSyntax { + public modifiers: ISyntaxList; + public setKeyword: ISyntaxToken; + public propertyName: ISyntaxToken; + public parameterList: ParameterListSyntax; + public block: BlockSyntax; + constructor(modifiers: ISyntaxList, setKeyword: ISyntaxToken, propertyName: ISyntaxToken, parameterList: ParameterListSyntax, block: BlockSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isMemberDeclaration(): boolean; + public isPropertyAssignment(): boolean; + public isClassElement(): boolean; + public update(modifiers: ISyntaxList, setKeyword: ISyntaxToken, propertyName: ISyntaxToken, parameterList: ParameterListSyntax, block: BlockSyntax): SetAccessorSyntax; + static create(setKeyword: ISyntaxToken, propertyName: ISyntaxToken, parameterList: ParameterListSyntax, block: BlockSyntax): SetAccessorSyntax; + static create1(propertyName: ISyntaxToken): SetAccessorSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): SetAccessorSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): SetAccessorSyntax; + public withModifiers(modifiers: ISyntaxList): SetAccessorSyntax; + public withModifier(modifier: ISyntaxToken): SetAccessorSyntax; + public withSetKeyword(setKeyword: ISyntaxToken): SetAccessorSyntax; + public withPropertyName(propertyName: ISyntaxToken): SetAccessorSyntax; + public withParameterList(parameterList: ParameterListSyntax): SetAccessorSyntax; + public withBlock(block: BlockSyntax): SetAccessorSyntax; + public isTypeScriptSpecific(): boolean; + } + class MemberVariableDeclarationSyntax extends SyntaxNode implements IMemberDeclarationSyntax { + public modifiers: ISyntaxList; + public variableDeclarator: VariableDeclaratorSyntax; + public semicolonToken: ISyntaxToken; + constructor(modifiers: ISyntaxList, variableDeclarator: VariableDeclaratorSyntax, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isMemberDeclaration(): boolean; + public isClassElement(): boolean; + public update(modifiers: ISyntaxList, variableDeclarator: VariableDeclaratorSyntax, semicolonToken: ISyntaxToken): MemberVariableDeclarationSyntax; + static create(variableDeclarator: VariableDeclaratorSyntax, semicolonToken: ISyntaxToken): MemberVariableDeclarationSyntax; + static create1(variableDeclarator: VariableDeclaratorSyntax): MemberVariableDeclarationSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): MemberVariableDeclarationSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): MemberVariableDeclarationSyntax; + public withModifiers(modifiers: ISyntaxList): MemberVariableDeclarationSyntax; + public withModifier(modifier: ISyntaxToken): MemberVariableDeclarationSyntax; + public withVariableDeclarator(variableDeclarator: VariableDeclaratorSyntax): MemberVariableDeclarationSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): MemberVariableDeclarationSyntax; + public isTypeScriptSpecific(): boolean; + } + class IndexMemberDeclarationSyntax extends SyntaxNode implements IClassElementSyntax { + public modifiers: ISyntaxList; + public indexSignature: IndexSignatureSyntax; + public semicolonToken: ISyntaxToken; + constructor(modifiers: ISyntaxList, indexSignature: IndexSignatureSyntax, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isClassElement(): boolean; + public update(modifiers: ISyntaxList, indexSignature: IndexSignatureSyntax, semicolonToken: ISyntaxToken): IndexMemberDeclarationSyntax; + static create(indexSignature: IndexSignatureSyntax, semicolonToken: ISyntaxToken): IndexMemberDeclarationSyntax; + static create1(indexSignature: IndexSignatureSyntax): IndexMemberDeclarationSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): IndexMemberDeclarationSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): IndexMemberDeclarationSyntax; + public withModifiers(modifiers: ISyntaxList): IndexMemberDeclarationSyntax; + public withModifier(modifier: ISyntaxToken): IndexMemberDeclarationSyntax; + public withIndexSignature(indexSignature: IndexSignatureSyntax): IndexMemberDeclarationSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): IndexMemberDeclarationSyntax; + public isTypeScriptSpecific(): boolean; + } + class ThrowStatementSyntax extends SyntaxNode implements IStatementSyntax { + public throwKeyword: ISyntaxToken; + public expression: IExpressionSyntax; + public semicolonToken: ISyntaxToken; + constructor(throwKeyword: ISyntaxToken, expression: IExpressionSyntax, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(throwKeyword: ISyntaxToken, expression: IExpressionSyntax, semicolonToken: ISyntaxToken): ThrowStatementSyntax; + static create1(expression: IExpressionSyntax): ThrowStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ThrowStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ThrowStatementSyntax; + public withThrowKeyword(throwKeyword: ISyntaxToken): ThrowStatementSyntax; + public withExpression(expression: IExpressionSyntax): ThrowStatementSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): ThrowStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class ReturnStatementSyntax extends SyntaxNode implements IStatementSyntax { + public returnKeyword: ISyntaxToken; + public expression: IExpressionSyntax; + public semicolonToken: ISyntaxToken; + constructor(returnKeyword: ISyntaxToken, expression: IExpressionSyntax, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(returnKeyword: ISyntaxToken, expression: IExpressionSyntax, semicolonToken: ISyntaxToken): ReturnStatementSyntax; + static create(returnKeyword: ISyntaxToken, semicolonToken: ISyntaxToken): ReturnStatementSyntax; + static create1(): ReturnStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ReturnStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ReturnStatementSyntax; + public withReturnKeyword(returnKeyword: ISyntaxToken): ReturnStatementSyntax; + public withExpression(expression: IExpressionSyntax): ReturnStatementSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): ReturnStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class ObjectCreationExpressionSyntax extends SyntaxNode implements IMemberExpressionSyntax { + public newKeyword: ISyntaxToken; + public expression: IMemberExpressionSyntax; + public argumentList: ArgumentListSyntax; + constructor(newKeyword: ISyntaxToken, expression: IMemberExpressionSyntax, argumentList: ArgumentListSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public update(newKeyword: ISyntaxToken, expression: IMemberExpressionSyntax, argumentList: ArgumentListSyntax): ObjectCreationExpressionSyntax; + static create(newKeyword: ISyntaxToken, expression: IMemberExpressionSyntax): ObjectCreationExpressionSyntax; + static create1(expression: IMemberExpressionSyntax): ObjectCreationExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ObjectCreationExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ObjectCreationExpressionSyntax; + public withNewKeyword(newKeyword: ISyntaxToken): ObjectCreationExpressionSyntax; + public withExpression(expression: IMemberExpressionSyntax): ObjectCreationExpressionSyntax; + public withArgumentList(argumentList: ArgumentListSyntax): ObjectCreationExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class SwitchStatementSyntax extends SyntaxNode implements IStatementSyntax { + public switchKeyword: ISyntaxToken; + public openParenToken: ISyntaxToken; + public expression: IExpressionSyntax; + public closeParenToken: ISyntaxToken; + public openBraceToken: ISyntaxToken; + public switchClauses: ISyntaxList; + public closeBraceToken: ISyntaxToken; + constructor(switchKeyword: ISyntaxToken, openParenToken: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken, openBraceToken: ISyntaxToken, switchClauses: ISyntaxList, closeBraceToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(switchKeyword: ISyntaxToken, openParenToken: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken, openBraceToken: ISyntaxToken, switchClauses: ISyntaxList, closeBraceToken: ISyntaxToken): SwitchStatementSyntax; + static create(switchKeyword: ISyntaxToken, openParenToken: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken, openBraceToken: ISyntaxToken, closeBraceToken: ISyntaxToken): SwitchStatementSyntax; + static create1(expression: IExpressionSyntax): SwitchStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): SwitchStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): SwitchStatementSyntax; + public withSwitchKeyword(switchKeyword: ISyntaxToken): SwitchStatementSyntax; + public withOpenParenToken(openParenToken: ISyntaxToken): SwitchStatementSyntax; + public withExpression(expression: IExpressionSyntax): SwitchStatementSyntax; + public withCloseParenToken(closeParenToken: ISyntaxToken): SwitchStatementSyntax; + public withOpenBraceToken(openBraceToken: ISyntaxToken): SwitchStatementSyntax; + public withSwitchClauses(switchClauses: ISyntaxList): SwitchStatementSyntax; + public withSwitchClause(switchClause: ISwitchClauseSyntax): SwitchStatementSyntax; + public withCloseBraceToken(closeBraceToken: ISyntaxToken): SwitchStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class CaseSwitchClauseSyntax extends SyntaxNode implements ISwitchClauseSyntax { + public caseKeyword: ISyntaxToken; + public expression: IExpressionSyntax; + public colonToken: ISyntaxToken; + public statements: ISyntaxList; + constructor(caseKeyword: ISyntaxToken, expression: IExpressionSyntax, colonToken: ISyntaxToken, statements: ISyntaxList, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isSwitchClause(): boolean; + public update(caseKeyword: ISyntaxToken, expression: IExpressionSyntax, colonToken: ISyntaxToken, statements: ISyntaxList): CaseSwitchClauseSyntax; + static create(caseKeyword: ISyntaxToken, expression: IExpressionSyntax, colonToken: ISyntaxToken): CaseSwitchClauseSyntax; + static create1(expression: IExpressionSyntax): CaseSwitchClauseSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): CaseSwitchClauseSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): CaseSwitchClauseSyntax; + public withCaseKeyword(caseKeyword: ISyntaxToken): CaseSwitchClauseSyntax; + public withExpression(expression: IExpressionSyntax): CaseSwitchClauseSyntax; + public withColonToken(colonToken: ISyntaxToken): CaseSwitchClauseSyntax; + public withStatements(statements: ISyntaxList): CaseSwitchClauseSyntax; + public withStatement(statement: IStatementSyntax): CaseSwitchClauseSyntax; + public isTypeScriptSpecific(): boolean; + } + class DefaultSwitchClauseSyntax extends SyntaxNode implements ISwitchClauseSyntax { + public defaultKeyword: ISyntaxToken; + public colonToken: ISyntaxToken; + public statements: ISyntaxList; + constructor(defaultKeyword: ISyntaxToken, colonToken: ISyntaxToken, statements: ISyntaxList, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isSwitchClause(): boolean; + public update(defaultKeyword: ISyntaxToken, colonToken: ISyntaxToken, statements: ISyntaxList): DefaultSwitchClauseSyntax; + static create(defaultKeyword: ISyntaxToken, colonToken: ISyntaxToken): DefaultSwitchClauseSyntax; + static create1(): DefaultSwitchClauseSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): DefaultSwitchClauseSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): DefaultSwitchClauseSyntax; + public withDefaultKeyword(defaultKeyword: ISyntaxToken): DefaultSwitchClauseSyntax; + public withColonToken(colonToken: ISyntaxToken): DefaultSwitchClauseSyntax; + public withStatements(statements: ISyntaxList): DefaultSwitchClauseSyntax; + public withStatement(statement: IStatementSyntax): DefaultSwitchClauseSyntax; + public isTypeScriptSpecific(): boolean; + } + class BreakStatementSyntax extends SyntaxNode implements IStatementSyntax { + public breakKeyword: ISyntaxToken; + public identifier: ISyntaxToken; + public semicolonToken: ISyntaxToken; + constructor(breakKeyword: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(breakKeyword: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken): BreakStatementSyntax; + static create(breakKeyword: ISyntaxToken, semicolonToken: ISyntaxToken): BreakStatementSyntax; + static create1(): BreakStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): BreakStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): BreakStatementSyntax; + public withBreakKeyword(breakKeyword: ISyntaxToken): BreakStatementSyntax; + public withIdentifier(identifier: ISyntaxToken): BreakStatementSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): BreakStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class ContinueStatementSyntax extends SyntaxNode implements IStatementSyntax { + public continueKeyword: ISyntaxToken; + public identifier: ISyntaxToken; + public semicolonToken: ISyntaxToken; + constructor(continueKeyword: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(continueKeyword: ISyntaxToken, identifier: ISyntaxToken, semicolonToken: ISyntaxToken): ContinueStatementSyntax; + static create(continueKeyword: ISyntaxToken, semicolonToken: ISyntaxToken): ContinueStatementSyntax; + static create1(): ContinueStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ContinueStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ContinueStatementSyntax; + public withContinueKeyword(continueKeyword: ISyntaxToken): ContinueStatementSyntax; + public withIdentifier(identifier: ISyntaxToken): ContinueStatementSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): ContinueStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class ForStatementSyntax extends SyntaxNode implements IIterationStatementSyntax { + public forKeyword: ISyntaxToken; + public openParenToken: ISyntaxToken; + public variableDeclaration: VariableDeclarationSyntax; + public initializer: IExpressionSyntax; + public firstSemicolonToken: ISyntaxToken; + public condition: IExpressionSyntax; + public secondSemicolonToken: ISyntaxToken; + public incrementor: IExpressionSyntax; + public closeParenToken: ISyntaxToken; + public statement: IStatementSyntax; + constructor(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken, variableDeclaration: VariableDeclarationSyntax, initializer: IExpressionSyntax, firstSemicolonToken: ISyntaxToken, condition: IExpressionSyntax, secondSemicolonToken: ISyntaxToken, incrementor: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isIterationStatement(): boolean; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken, variableDeclaration: VariableDeclarationSyntax, initializer: IExpressionSyntax, firstSemicolonToken: ISyntaxToken, condition: IExpressionSyntax, secondSemicolonToken: ISyntaxToken, incrementor: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): ForStatementSyntax; + static create(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken, firstSemicolonToken: ISyntaxToken, secondSemicolonToken: ISyntaxToken, closeParenToken: ISyntaxToken, statement: IStatementSyntax): ForStatementSyntax; + static create1(statement: IStatementSyntax): ForStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ForStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ForStatementSyntax; + public withForKeyword(forKeyword: ISyntaxToken): ForStatementSyntax; + public withOpenParenToken(openParenToken: ISyntaxToken): ForStatementSyntax; + public withVariableDeclaration(variableDeclaration: VariableDeclarationSyntax): ForStatementSyntax; + public withInitializer(initializer: IExpressionSyntax): ForStatementSyntax; + public withFirstSemicolonToken(firstSemicolonToken: ISyntaxToken): ForStatementSyntax; + public withCondition(condition: IExpressionSyntax): ForStatementSyntax; + public withSecondSemicolonToken(secondSemicolonToken: ISyntaxToken): ForStatementSyntax; + public withIncrementor(incrementor: IExpressionSyntax): ForStatementSyntax; + public withCloseParenToken(closeParenToken: ISyntaxToken): ForStatementSyntax; + public withStatement(statement: IStatementSyntax): ForStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class ForInStatementSyntax extends SyntaxNode implements IIterationStatementSyntax { + public forKeyword: ISyntaxToken; + public openParenToken: ISyntaxToken; + public variableDeclaration: VariableDeclarationSyntax; + public left: IExpressionSyntax; + public inKeyword: ISyntaxToken; + public expression: IExpressionSyntax; + public closeParenToken: ISyntaxToken; + public statement: IStatementSyntax; + constructor(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken, variableDeclaration: VariableDeclarationSyntax, left: IExpressionSyntax, inKeyword: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isIterationStatement(): boolean; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken, variableDeclaration: VariableDeclarationSyntax, left: IExpressionSyntax, inKeyword: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): ForInStatementSyntax; + static create(forKeyword: ISyntaxToken, openParenToken: ISyntaxToken, inKeyword: ISyntaxToken, expression: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): ForInStatementSyntax; + static create1(expression: IExpressionSyntax, statement: IStatementSyntax): ForInStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ForInStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ForInStatementSyntax; + public withForKeyword(forKeyword: ISyntaxToken): ForInStatementSyntax; + public withOpenParenToken(openParenToken: ISyntaxToken): ForInStatementSyntax; + public withVariableDeclaration(variableDeclaration: VariableDeclarationSyntax): ForInStatementSyntax; + public withLeft(left: IExpressionSyntax): ForInStatementSyntax; + public withInKeyword(inKeyword: ISyntaxToken): ForInStatementSyntax; + public withExpression(expression: IExpressionSyntax): ForInStatementSyntax; + public withCloseParenToken(closeParenToken: ISyntaxToken): ForInStatementSyntax; + public withStatement(statement: IStatementSyntax): ForInStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class WhileStatementSyntax extends SyntaxNode implements IIterationStatementSyntax { + public whileKeyword: ISyntaxToken; + public openParenToken: ISyntaxToken; + public condition: IExpressionSyntax; + public closeParenToken: ISyntaxToken; + public statement: IStatementSyntax; + constructor(whileKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isIterationStatement(): boolean; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(whileKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): WhileStatementSyntax; + static create1(condition: IExpressionSyntax, statement: IStatementSyntax): WhileStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): WhileStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): WhileStatementSyntax; + public withWhileKeyword(whileKeyword: ISyntaxToken): WhileStatementSyntax; + public withOpenParenToken(openParenToken: ISyntaxToken): WhileStatementSyntax; + public withCondition(condition: IExpressionSyntax): WhileStatementSyntax; + public withCloseParenToken(closeParenToken: ISyntaxToken): WhileStatementSyntax; + public withStatement(statement: IStatementSyntax): WhileStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class WithStatementSyntax extends SyntaxNode implements IStatementSyntax { + public withKeyword: ISyntaxToken; + public openParenToken: ISyntaxToken; + public condition: IExpressionSyntax; + public closeParenToken: ISyntaxToken; + public statement: IStatementSyntax; + constructor(withKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(withKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, statement: IStatementSyntax): WithStatementSyntax; + static create1(condition: IExpressionSyntax, statement: IStatementSyntax): WithStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): WithStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): WithStatementSyntax; + public withWithKeyword(withKeyword: ISyntaxToken): WithStatementSyntax; + public withOpenParenToken(openParenToken: ISyntaxToken): WithStatementSyntax; + public withCondition(condition: IExpressionSyntax): WithStatementSyntax; + public withCloseParenToken(closeParenToken: ISyntaxToken): WithStatementSyntax; + public withStatement(statement: IStatementSyntax): WithStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class EnumDeclarationSyntax extends SyntaxNode implements IModuleElementSyntax { + public modifiers: ISyntaxList; + public enumKeyword: ISyntaxToken; + public identifier: ISyntaxToken; + public openBraceToken: ISyntaxToken; + public enumElements: ISeparatedSyntaxList; + public closeBraceToken: ISyntaxToken; + constructor(modifiers: ISyntaxList, enumKeyword: ISyntaxToken, identifier: ISyntaxToken, openBraceToken: ISyntaxToken, enumElements: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isModuleElement(): boolean; + public update(modifiers: ISyntaxList, enumKeyword: ISyntaxToken, identifier: ISyntaxToken, openBraceToken: ISyntaxToken, enumElements: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken): EnumDeclarationSyntax; + static create(enumKeyword: ISyntaxToken, identifier: ISyntaxToken, openBraceToken: ISyntaxToken, closeBraceToken: ISyntaxToken): EnumDeclarationSyntax; + static create1(identifier: ISyntaxToken): EnumDeclarationSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): EnumDeclarationSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): EnumDeclarationSyntax; + public withModifiers(modifiers: ISyntaxList): EnumDeclarationSyntax; + public withModifier(modifier: ISyntaxToken): EnumDeclarationSyntax; + public withEnumKeyword(enumKeyword: ISyntaxToken): EnumDeclarationSyntax; + public withIdentifier(identifier: ISyntaxToken): EnumDeclarationSyntax; + public withOpenBraceToken(openBraceToken: ISyntaxToken): EnumDeclarationSyntax; + public withEnumElements(enumElements: ISeparatedSyntaxList): EnumDeclarationSyntax; + public withEnumElement(enumElement: EnumElementSyntax): EnumDeclarationSyntax; + public withCloseBraceToken(closeBraceToken: ISyntaxToken): EnumDeclarationSyntax; + public isTypeScriptSpecific(): boolean; + } + class EnumElementSyntax extends SyntaxNode { + public propertyName: ISyntaxToken; + public equalsValueClause: EqualsValueClauseSyntax; + constructor(propertyName: ISyntaxToken, equalsValueClause: EqualsValueClauseSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(propertyName: ISyntaxToken, equalsValueClause: EqualsValueClauseSyntax): EnumElementSyntax; + static create(propertyName: ISyntaxToken): EnumElementSyntax; + static create1(propertyName: ISyntaxToken): EnumElementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): EnumElementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): EnumElementSyntax; + public withPropertyName(propertyName: ISyntaxToken): EnumElementSyntax; + public withEqualsValueClause(equalsValueClause: EqualsValueClauseSyntax): EnumElementSyntax; + public isTypeScriptSpecific(): boolean; + } + class CastExpressionSyntax extends SyntaxNode implements IUnaryExpressionSyntax { + public lessThanToken: ISyntaxToken; + public type: ITypeSyntax; + public greaterThanToken: ISyntaxToken; + public expression: IUnaryExpressionSyntax; + constructor(lessThanToken: ISyntaxToken, type: ITypeSyntax, greaterThanToken: ISyntaxToken, expression: IUnaryExpressionSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public update(lessThanToken: ISyntaxToken, type: ITypeSyntax, greaterThanToken: ISyntaxToken, expression: IUnaryExpressionSyntax): CastExpressionSyntax; + static create1(type: ITypeSyntax, expression: IUnaryExpressionSyntax): CastExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): CastExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): CastExpressionSyntax; + public withLessThanToken(lessThanToken: ISyntaxToken): CastExpressionSyntax; + public withType(type: ITypeSyntax): CastExpressionSyntax; + public withGreaterThanToken(greaterThanToken: ISyntaxToken): CastExpressionSyntax; + public withExpression(expression: IUnaryExpressionSyntax): CastExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class ObjectLiteralExpressionSyntax extends SyntaxNode implements IPrimaryExpressionSyntax { + public openBraceToken: ISyntaxToken; + public propertyAssignments: ISeparatedSyntaxList; + public closeBraceToken: ISyntaxToken; + constructor(openBraceToken: ISyntaxToken, propertyAssignments: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isPrimaryExpression(): boolean; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public update(openBraceToken: ISyntaxToken, propertyAssignments: ISeparatedSyntaxList, closeBraceToken: ISyntaxToken): ObjectLiteralExpressionSyntax; + static create(openBraceToken: ISyntaxToken, closeBraceToken: ISyntaxToken): ObjectLiteralExpressionSyntax; + static create1(): ObjectLiteralExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): ObjectLiteralExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): ObjectLiteralExpressionSyntax; + public withOpenBraceToken(openBraceToken: ISyntaxToken): ObjectLiteralExpressionSyntax; + public withPropertyAssignments(propertyAssignments: ISeparatedSyntaxList): ObjectLiteralExpressionSyntax; + public withPropertyAssignment(propertyAssignment: IPropertyAssignmentSyntax): ObjectLiteralExpressionSyntax; + public withCloseBraceToken(closeBraceToken: ISyntaxToken): ObjectLiteralExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class SimplePropertyAssignmentSyntax extends SyntaxNode implements IPropertyAssignmentSyntax { + public propertyName: ISyntaxToken; + public colonToken: ISyntaxToken; + public expression: IExpressionSyntax; + constructor(propertyName: ISyntaxToken, colonToken: ISyntaxToken, expression: IExpressionSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isPropertyAssignment(): boolean; + public update(propertyName: ISyntaxToken, colonToken: ISyntaxToken, expression: IExpressionSyntax): SimplePropertyAssignmentSyntax; + static create1(propertyName: ISyntaxToken, expression: IExpressionSyntax): SimplePropertyAssignmentSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): SimplePropertyAssignmentSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): SimplePropertyAssignmentSyntax; + public withPropertyName(propertyName: ISyntaxToken): SimplePropertyAssignmentSyntax; + public withColonToken(colonToken: ISyntaxToken): SimplePropertyAssignmentSyntax; + public withExpression(expression: IExpressionSyntax): SimplePropertyAssignmentSyntax; + public isTypeScriptSpecific(): boolean; + } + class FunctionPropertyAssignmentSyntax extends SyntaxNode implements IPropertyAssignmentSyntax { + public propertyName: ISyntaxToken; + public callSignature: CallSignatureSyntax; + public block: BlockSyntax; + constructor(propertyName: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isPropertyAssignment(): boolean; + public update(propertyName: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax): FunctionPropertyAssignmentSyntax; + static create1(propertyName: ISyntaxToken): FunctionPropertyAssignmentSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): FunctionPropertyAssignmentSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): FunctionPropertyAssignmentSyntax; + public withPropertyName(propertyName: ISyntaxToken): FunctionPropertyAssignmentSyntax; + public withCallSignature(callSignature: CallSignatureSyntax): FunctionPropertyAssignmentSyntax; + public withBlock(block: BlockSyntax): FunctionPropertyAssignmentSyntax; + public isTypeScriptSpecific(): boolean; + } + class FunctionExpressionSyntax extends SyntaxNode implements IPrimaryExpressionSyntax { + public functionKeyword: ISyntaxToken; + public identifier: ISyntaxToken; + public callSignature: CallSignatureSyntax; + public block: BlockSyntax; + constructor(functionKeyword: ISyntaxToken, identifier: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isPrimaryExpression(): boolean; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public update(functionKeyword: ISyntaxToken, identifier: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax): FunctionExpressionSyntax; + static create(functionKeyword: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax): FunctionExpressionSyntax; + static create1(): FunctionExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): FunctionExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): FunctionExpressionSyntax; + public withFunctionKeyword(functionKeyword: ISyntaxToken): FunctionExpressionSyntax; + public withIdentifier(identifier: ISyntaxToken): FunctionExpressionSyntax; + public withCallSignature(callSignature: CallSignatureSyntax): FunctionExpressionSyntax; + public withBlock(block: BlockSyntax): FunctionExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class EmptyStatementSyntax extends SyntaxNode implements IStatementSyntax { + public semicolonToken: ISyntaxToken; + constructor(semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(semicolonToken: ISyntaxToken): EmptyStatementSyntax; + static create1(): EmptyStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): EmptyStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): EmptyStatementSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): EmptyStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class TryStatementSyntax extends SyntaxNode implements IStatementSyntax { + public tryKeyword: ISyntaxToken; + public block: BlockSyntax; + public catchClause: CatchClauseSyntax; + public finallyClause: FinallyClauseSyntax; + constructor(tryKeyword: ISyntaxToken, block: BlockSyntax, catchClause: CatchClauseSyntax, finallyClause: FinallyClauseSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(tryKeyword: ISyntaxToken, block: BlockSyntax, catchClause: CatchClauseSyntax, finallyClause: FinallyClauseSyntax): TryStatementSyntax; + static create(tryKeyword: ISyntaxToken, block: BlockSyntax): TryStatementSyntax; + static create1(): TryStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): TryStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): TryStatementSyntax; + public withTryKeyword(tryKeyword: ISyntaxToken): TryStatementSyntax; + public withBlock(block: BlockSyntax): TryStatementSyntax; + public withCatchClause(catchClause: CatchClauseSyntax): TryStatementSyntax; + public withFinallyClause(finallyClause: FinallyClauseSyntax): TryStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class CatchClauseSyntax extends SyntaxNode { + public catchKeyword: ISyntaxToken; + public openParenToken: ISyntaxToken; + public identifier: ISyntaxToken; + public typeAnnotation: TypeAnnotationSyntax; + public closeParenToken: ISyntaxToken; + public block: BlockSyntax; + constructor(catchKeyword: ISyntaxToken, openParenToken: ISyntaxToken, identifier: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, closeParenToken: ISyntaxToken, block: BlockSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(catchKeyword: ISyntaxToken, openParenToken: ISyntaxToken, identifier: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, closeParenToken: ISyntaxToken, block: BlockSyntax): CatchClauseSyntax; + static create(catchKeyword: ISyntaxToken, openParenToken: ISyntaxToken, identifier: ISyntaxToken, closeParenToken: ISyntaxToken, block: BlockSyntax): CatchClauseSyntax; + static create1(identifier: ISyntaxToken): CatchClauseSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): CatchClauseSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): CatchClauseSyntax; + public withCatchKeyword(catchKeyword: ISyntaxToken): CatchClauseSyntax; + public withOpenParenToken(openParenToken: ISyntaxToken): CatchClauseSyntax; + public withIdentifier(identifier: ISyntaxToken): CatchClauseSyntax; + public withTypeAnnotation(typeAnnotation: TypeAnnotationSyntax): CatchClauseSyntax; + public withCloseParenToken(closeParenToken: ISyntaxToken): CatchClauseSyntax; + public withBlock(block: BlockSyntax): CatchClauseSyntax; + public isTypeScriptSpecific(): boolean; + } + class FinallyClauseSyntax extends SyntaxNode { + public finallyKeyword: ISyntaxToken; + public block: BlockSyntax; + constructor(finallyKeyword: ISyntaxToken, block: BlockSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public update(finallyKeyword: ISyntaxToken, block: BlockSyntax): FinallyClauseSyntax; + static create1(): FinallyClauseSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): FinallyClauseSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): FinallyClauseSyntax; + public withFinallyKeyword(finallyKeyword: ISyntaxToken): FinallyClauseSyntax; + public withBlock(block: BlockSyntax): FinallyClauseSyntax; + public isTypeScriptSpecific(): boolean; + } + class LabeledStatementSyntax extends SyntaxNode implements IStatementSyntax { + public identifier: ISyntaxToken; + public colonToken: ISyntaxToken; + public statement: IStatementSyntax; + constructor(identifier: ISyntaxToken, colonToken: ISyntaxToken, statement: IStatementSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(identifier: ISyntaxToken, colonToken: ISyntaxToken, statement: IStatementSyntax): LabeledStatementSyntax; + static create1(identifier: ISyntaxToken, statement: IStatementSyntax): LabeledStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): LabeledStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): LabeledStatementSyntax; + public withIdentifier(identifier: ISyntaxToken): LabeledStatementSyntax; + public withColonToken(colonToken: ISyntaxToken): LabeledStatementSyntax; + public withStatement(statement: IStatementSyntax): LabeledStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class DoStatementSyntax extends SyntaxNode implements IIterationStatementSyntax { + public doKeyword: ISyntaxToken; + public statement: IStatementSyntax; + public whileKeyword: ISyntaxToken; + public openParenToken: ISyntaxToken; + public condition: IExpressionSyntax; + public closeParenToken: ISyntaxToken; + public semicolonToken: ISyntaxToken; + constructor(doKeyword: ISyntaxToken, statement: IStatementSyntax, whileKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isIterationStatement(): boolean; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(doKeyword: ISyntaxToken, statement: IStatementSyntax, whileKeyword: ISyntaxToken, openParenToken: ISyntaxToken, condition: IExpressionSyntax, closeParenToken: ISyntaxToken, semicolonToken: ISyntaxToken): DoStatementSyntax; + static create1(statement: IStatementSyntax, condition: IExpressionSyntax): DoStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): DoStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): DoStatementSyntax; + public withDoKeyword(doKeyword: ISyntaxToken): DoStatementSyntax; + public withStatement(statement: IStatementSyntax): DoStatementSyntax; + public withWhileKeyword(whileKeyword: ISyntaxToken): DoStatementSyntax; + public withOpenParenToken(openParenToken: ISyntaxToken): DoStatementSyntax; + public withCondition(condition: IExpressionSyntax): DoStatementSyntax; + public withCloseParenToken(closeParenToken: ISyntaxToken): DoStatementSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): DoStatementSyntax; + public isTypeScriptSpecific(): boolean; + } + class TypeOfExpressionSyntax extends SyntaxNode implements IUnaryExpressionSyntax { + public typeOfKeyword: ISyntaxToken; + public expression: IUnaryExpressionSyntax; + constructor(typeOfKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public update(typeOfKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax): TypeOfExpressionSyntax; + static create1(expression: IUnaryExpressionSyntax): TypeOfExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): TypeOfExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): TypeOfExpressionSyntax; + public withTypeOfKeyword(typeOfKeyword: ISyntaxToken): TypeOfExpressionSyntax; + public withExpression(expression: IUnaryExpressionSyntax): TypeOfExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class DeleteExpressionSyntax extends SyntaxNode implements IUnaryExpressionSyntax { + public deleteKeyword: ISyntaxToken; + public expression: IUnaryExpressionSyntax; + constructor(deleteKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public update(deleteKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax): DeleteExpressionSyntax; + static create1(expression: IUnaryExpressionSyntax): DeleteExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): DeleteExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): DeleteExpressionSyntax; + public withDeleteKeyword(deleteKeyword: ISyntaxToken): DeleteExpressionSyntax; + public withExpression(expression: IUnaryExpressionSyntax): DeleteExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class VoidExpressionSyntax extends SyntaxNode implements IUnaryExpressionSyntax { + public voidKeyword: ISyntaxToken; + public expression: IUnaryExpressionSyntax; + constructor(voidKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isUnaryExpression(): boolean; + public isExpression(): boolean; + public update(voidKeyword: ISyntaxToken, expression: IUnaryExpressionSyntax): VoidExpressionSyntax; + static create1(expression: IUnaryExpressionSyntax): VoidExpressionSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): VoidExpressionSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): VoidExpressionSyntax; + public withVoidKeyword(voidKeyword: ISyntaxToken): VoidExpressionSyntax; + public withExpression(expression: IUnaryExpressionSyntax): VoidExpressionSyntax; + public isTypeScriptSpecific(): boolean; + } + class DebuggerStatementSyntax extends SyntaxNode implements IStatementSyntax { + public debuggerKeyword: ISyntaxToken; + public semicolonToken: ISyntaxToken; + constructor(debuggerKeyword: ISyntaxToken, semicolonToken: ISyntaxToken, parsedInStrictMode: boolean); + public accept(visitor: ISyntaxVisitor): any; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(slot: number): ISyntaxElement; + public isStatement(): boolean; + public isModuleElement(): boolean; + public update(debuggerKeyword: ISyntaxToken, semicolonToken: ISyntaxToken): DebuggerStatementSyntax; + static create1(): DebuggerStatementSyntax; + public withLeadingTrivia(trivia: ISyntaxTriviaList): DebuggerStatementSyntax; + public withTrailingTrivia(trivia: ISyntaxTriviaList): DebuggerStatementSyntax; + public withDebuggerKeyword(debuggerKeyword: ISyntaxToken): DebuggerStatementSyntax; + public withSemicolonToken(semicolonToken: ISyntaxToken): DebuggerStatementSyntax; + public isTypeScriptSpecific(): boolean; + } +} +declare module TypeScript { + class SyntaxRewriter implements ISyntaxVisitor { + public visitToken(token: ISyntaxToken): ISyntaxToken; + public visitNode(node: SyntaxNode): SyntaxNode; + public visitNodeOrToken(node: ISyntaxNodeOrToken): ISyntaxNodeOrToken; + public visitList(list: ISyntaxList): ISyntaxList; + public visitSeparatedList(list: ISeparatedSyntaxList): ISeparatedSyntaxList; + public visitSourceUnit(node: SourceUnitSyntax): any; + public visitExternalModuleReference(node: ExternalModuleReferenceSyntax): any; + public visitModuleNameModuleReference(node: ModuleNameModuleReferenceSyntax): any; + public visitImportDeclaration(node: ImportDeclarationSyntax): any; + public visitExportAssignment(node: ExportAssignmentSyntax): any; + public visitClassDeclaration(node: ClassDeclarationSyntax): any; + public visitInterfaceDeclaration(node: InterfaceDeclarationSyntax): any; + public visitHeritageClause(node: HeritageClauseSyntax): any; + public visitModuleDeclaration(node: ModuleDeclarationSyntax): any; + public visitFunctionDeclaration(node: FunctionDeclarationSyntax): any; + public visitVariableStatement(node: VariableStatementSyntax): any; + public visitVariableDeclaration(node: VariableDeclarationSyntax): any; + public visitVariableDeclarator(node: VariableDeclaratorSyntax): any; + public visitEqualsValueClause(node: EqualsValueClauseSyntax): any; + public visitPrefixUnaryExpression(node: PrefixUnaryExpressionSyntax): any; + public visitArrayLiteralExpression(node: ArrayLiteralExpressionSyntax): any; + public visitOmittedExpression(node: OmittedExpressionSyntax): any; + public visitParenthesizedExpression(node: ParenthesizedExpressionSyntax): any; + public visitSimpleArrowFunctionExpression(node: SimpleArrowFunctionExpressionSyntax): any; + public visitParenthesizedArrowFunctionExpression(node: ParenthesizedArrowFunctionExpressionSyntax): any; + public visitQualifiedName(node: QualifiedNameSyntax): any; + public visitTypeArgumentList(node: TypeArgumentListSyntax): any; + public visitConstructorType(node: ConstructorTypeSyntax): any; + public visitFunctionType(node: FunctionTypeSyntax): any; + public visitObjectType(node: ObjectTypeSyntax): any; + public visitArrayType(node: ArrayTypeSyntax): any; + public visitGenericType(node: GenericTypeSyntax): any; + public visitTypeQuery(node: TypeQuerySyntax): any; + public visitTypeAnnotation(node: TypeAnnotationSyntax): any; + public visitBlock(node: BlockSyntax): any; + public visitParameter(node: ParameterSyntax): any; + public visitMemberAccessExpression(node: MemberAccessExpressionSyntax): any; + public visitPostfixUnaryExpression(node: PostfixUnaryExpressionSyntax): any; + public visitElementAccessExpression(node: ElementAccessExpressionSyntax): any; + public visitInvocationExpression(node: InvocationExpressionSyntax): any; + public visitArgumentList(node: ArgumentListSyntax): any; + public visitBinaryExpression(node: BinaryExpressionSyntax): any; + public visitConditionalExpression(node: ConditionalExpressionSyntax): any; + public visitConstructSignature(node: ConstructSignatureSyntax): any; + public visitMethodSignature(node: MethodSignatureSyntax): any; + public visitIndexSignature(node: IndexSignatureSyntax): any; + public visitPropertySignature(node: PropertySignatureSyntax): any; + public visitCallSignature(node: CallSignatureSyntax): any; + public visitParameterList(node: ParameterListSyntax): any; + public visitTypeParameterList(node: TypeParameterListSyntax): any; + public visitTypeParameter(node: TypeParameterSyntax): any; + public visitConstraint(node: ConstraintSyntax): any; + public visitElseClause(node: ElseClauseSyntax): any; + public visitIfStatement(node: IfStatementSyntax): any; + public visitExpressionStatement(node: ExpressionStatementSyntax): any; + public visitConstructorDeclaration(node: ConstructorDeclarationSyntax): any; + public visitMemberFunctionDeclaration(node: MemberFunctionDeclarationSyntax): any; + public visitGetAccessor(node: GetAccessorSyntax): any; + public visitSetAccessor(node: SetAccessorSyntax): any; + public visitMemberVariableDeclaration(node: MemberVariableDeclarationSyntax): any; + public visitIndexMemberDeclaration(node: IndexMemberDeclarationSyntax): any; + public visitThrowStatement(node: ThrowStatementSyntax): any; + public visitReturnStatement(node: ReturnStatementSyntax): any; + public visitObjectCreationExpression(node: ObjectCreationExpressionSyntax): any; + public visitSwitchStatement(node: SwitchStatementSyntax): any; + public visitCaseSwitchClause(node: CaseSwitchClauseSyntax): any; + public visitDefaultSwitchClause(node: DefaultSwitchClauseSyntax): any; + public visitBreakStatement(node: BreakStatementSyntax): any; + public visitContinueStatement(node: ContinueStatementSyntax): any; + public visitForStatement(node: ForStatementSyntax): any; + public visitForInStatement(node: ForInStatementSyntax): any; + public visitWhileStatement(node: WhileStatementSyntax): any; + public visitWithStatement(node: WithStatementSyntax): any; + public visitEnumDeclaration(node: EnumDeclarationSyntax): any; + public visitEnumElement(node: EnumElementSyntax): any; + public visitCastExpression(node: CastExpressionSyntax): any; + public visitObjectLiteralExpression(node: ObjectLiteralExpressionSyntax): any; + public visitSimplePropertyAssignment(node: SimplePropertyAssignmentSyntax): any; + public visitFunctionPropertyAssignment(node: FunctionPropertyAssignmentSyntax): any; + public visitFunctionExpression(node: FunctionExpressionSyntax): any; + public visitEmptyStatement(node: EmptyStatementSyntax): any; + public visitTryStatement(node: TryStatementSyntax): any; + public visitCatchClause(node: CatchClauseSyntax): any; + public visitFinallyClause(node: FinallyClauseSyntax): any; + public visitLabeledStatement(node: LabeledStatementSyntax): any; + public visitDoStatement(node: DoStatementSyntax): any; + public visitTypeOfExpression(node: TypeOfExpressionSyntax): any; + public visitDeleteExpression(node: DeleteExpressionSyntax): any; + public visitVoidExpression(node: VoidExpressionSyntax): any; + public visitDebuggerStatement(node: DebuggerStatementSyntax): any; + } +} +declare module TypeScript { + class SyntaxDedenter extends SyntaxRewriter { + private dedentationAmount; + private minimumIndent; + private options; + private lastTriviaWasNewLine; + constructor(dedentFirstToken: boolean, dedentationAmount: number, minimumIndent: number, options: FormattingOptions); + private abort(); + private isAborted(); + public visitToken(token: ISyntaxToken): ISyntaxToken; + private dedentTriviaList(triviaList); + private dedentSegment(segment, hasFollowingNewLineTrivia); + private dedentWhitespace(trivia, hasFollowingNewLineTrivia); + private dedentMultiLineComment(trivia); + static dedentNode(node: ISyntaxNode, dedentFirstToken: boolean, dedentAmount: number, minimumIndent: number, options: FormattingOptions): ISyntaxNode; + } +} +declare module TypeScript { + class SyntaxIndenter extends SyntaxRewriter { + private indentationAmount; + private options; + private lastTriviaWasNewLine; + private indentationTrivia; + constructor(indentFirstToken: boolean, indentationAmount: number, options: FormattingOptions); + public visitToken(token: ISyntaxToken): ISyntaxToken; + public indentTriviaList(triviaList: ISyntaxTriviaList): ISyntaxTriviaList; + private indentSegment(segment); + private indentWhitespace(trivia, indentThisTrivia, result); + private indentSingleLineOrSkippedText(trivia, indentThisTrivia, result); + private indentMultiLineComment(trivia, indentThisTrivia, result); + static indentNode(node: ISyntaxNode, indentFirstToken: boolean, indentAmount: number, options: FormattingOptions): SyntaxNode; + static indentNodes(nodes: SyntaxNode[], indentFirstToken: boolean, indentAmount: number, options: FormattingOptions): SyntaxNode[]; + } +} +declare module TypeScript.Syntax { + class VariableWidthTokenWithNoTrivia implements ISyntaxToken { + private _fullText; + public tokenKind: SyntaxKind; + constructor(fullText: string, kind: SyntaxKind); + public clone(): ISyntaxToken; + public isNode(): boolean; + public isToken(): boolean; + public isList(): boolean; + public isSeparatedList(): boolean; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(index: number): ISyntaxElement; + public fullWidth(): number; + public width(): number; + public text(): string; + public fullText(): string; + public value(): any; + public valueText(): string; + public hasLeadingTrivia(): boolean; + public hasLeadingComment(): boolean; + public hasLeadingNewLine(): boolean; + public hasLeadingSkippedText(): boolean; + public leadingTriviaWidth(): number; + public leadingTrivia(): ISyntaxTriviaList; + public hasTrailingTrivia(): boolean; + public hasTrailingComment(): boolean; + public hasTrailingNewLine(): boolean; + public hasTrailingSkippedText(): boolean; + public trailingTriviaWidth(): number; + public trailingTrivia(): ISyntaxTriviaList; + public hasSkippedToken(): boolean; + public toJSON(key: any): any; + public firstToken(): ISyntaxToken; + public lastToken(): ISyntaxToken; + public isTypeScriptSpecific(): boolean; + public isIncrementallyUnusable(): boolean; + public accept(visitor: ISyntaxVisitor): any; + private realize(); + public collectTextElements(elements: string[]): void; + private findTokenInternal(parent, position, fullStart); + public withLeadingTrivia(leadingTrivia: ISyntaxTriviaList): ISyntaxToken; + public withTrailingTrivia(trailingTrivia: ISyntaxTriviaList): ISyntaxToken; + public isExpression(): boolean; + public isPrimaryExpression(): boolean; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + } + class VariableWidthTokenWithLeadingTrivia implements ISyntaxToken { + private _fullText; + public tokenKind: SyntaxKind; + private _leadingTriviaInfo; + constructor(fullText: string, kind: SyntaxKind, leadingTriviaInfo: number); + public clone(): ISyntaxToken; + public isNode(): boolean; + public isToken(): boolean; + public isList(): boolean; + public isSeparatedList(): boolean; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(index: number): ISyntaxElement; + public fullWidth(): number; + public width(): number; + public text(): string; + public fullText(): string; + public value(): any; + public valueText(): string; + public hasLeadingTrivia(): boolean; + public hasLeadingComment(): boolean; + public hasLeadingNewLine(): boolean; + public hasLeadingSkippedText(): boolean; + public leadingTriviaWidth(): number; + public leadingTrivia(): ISyntaxTriviaList; + public hasTrailingTrivia(): boolean; + public hasTrailingComment(): boolean; + public hasTrailingNewLine(): boolean; + public hasTrailingSkippedText(): boolean; + public trailingTriviaWidth(): number; + public trailingTrivia(): ISyntaxTriviaList; + public hasSkippedToken(): boolean; + public toJSON(key: any): any; + public firstToken(): ISyntaxToken; + public lastToken(): ISyntaxToken; + public isTypeScriptSpecific(): boolean; + public isIncrementallyUnusable(): boolean; + public accept(visitor: ISyntaxVisitor): any; + private realize(); + public collectTextElements(elements: string[]): void; + private findTokenInternal(parent, position, fullStart); + public withLeadingTrivia(leadingTrivia: ISyntaxTriviaList): ISyntaxToken; + public withTrailingTrivia(trailingTrivia: ISyntaxTriviaList): ISyntaxToken; + public isExpression(): boolean; + public isPrimaryExpression(): boolean; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + } + class VariableWidthTokenWithTrailingTrivia implements ISyntaxToken { + private _fullText; + public tokenKind: SyntaxKind; + private _trailingTriviaInfo; + constructor(fullText: string, kind: SyntaxKind, trailingTriviaInfo: number); + public clone(): ISyntaxToken; + public isNode(): boolean; + public isToken(): boolean; + public isList(): boolean; + public isSeparatedList(): boolean; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(index: number): ISyntaxElement; + public fullWidth(): number; + public width(): number; + public text(): string; + public fullText(): string; + public value(): any; + public valueText(): string; + public hasLeadingTrivia(): boolean; + public hasLeadingComment(): boolean; + public hasLeadingNewLine(): boolean; + public hasLeadingSkippedText(): boolean; + public leadingTriviaWidth(): number; + public leadingTrivia(): ISyntaxTriviaList; + public hasTrailingTrivia(): boolean; + public hasTrailingComment(): boolean; + public hasTrailingNewLine(): boolean; + public hasTrailingSkippedText(): boolean; + public trailingTriviaWidth(): number; + public trailingTrivia(): ISyntaxTriviaList; + public hasSkippedToken(): boolean; + public toJSON(key: any): any; + public firstToken(): ISyntaxToken; + public lastToken(): ISyntaxToken; + public isTypeScriptSpecific(): boolean; + public isIncrementallyUnusable(): boolean; + public accept(visitor: ISyntaxVisitor): any; + private realize(); + public collectTextElements(elements: string[]): void; + private findTokenInternal(parent, position, fullStart); + public withLeadingTrivia(leadingTrivia: ISyntaxTriviaList): ISyntaxToken; + public withTrailingTrivia(trailingTrivia: ISyntaxTriviaList): ISyntaxToken; + public isExpression(): boolean; + public isPrimaryExpression(): boolean; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + } + class VariableWidthTokenWithLeadingAndTrailingTrivia implements ISyntaxToken { + private _fullText; + public tokenKind: SyntaxKind; + private _leadingTriviaInfo; + private _trailingTriviaInfo; + constructor(fullText: string, kind: SyntaxKind, leadingTriviaInfo: number, trailingTriviaInfo: number); + public clone(): ISyntaxToken; + public isNode(): boolean; + public isToken(): boolean; + public isList(): boolean; + public isSeparatedList(): boolean; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(index: number): ISyntaxElement; + public fullWidth(): number; + public width(): number; + public text(): string; + public fullText(): string; + public value(): any; + public valueText(): string; + public hasLeadingTrivia(): boolean; + public hasLeadingComment(): boolean; + public hasLeadingNewLine(): boolean; + public hasLeadingSkippedText(): boolean; + public leadingTriviaWidth(): number; + public leadingTrivia(): ISyntaxTriviaList; + public hasTrailingTrivia(): boolean; + public hasTrailingComment(): boolean; + public hasTrailingNewLine(): boolean; + public hasTrailingSkippedText(): boolean; + public trailingTriviaWidth(): number; + public trailingTrivia(): ISyntaxTriviaList; + public hasSkippedToken(): boolean; + public toJSON(key: any): any; + public firstToken(): ISyntaxToken; + public lastToken(): ISyntaxToken; + public isTypeScriptSpecific(): boolean; + public isIncrementallyUnusable(): boolean; + public accept(visitor: ISyntaxVisitor): any; + private realize(); + public collectTextElements(elements: string[]): void; + private findTokenInternal(parent, position, fullStart); + public withLeadingTrivia(leadingTrivia: ISyntaxTriviaList): ISyntaxToken; + public withTrailingTrivia(trailingTrivia: ISyntaxTriviaList): ISyntaxToken; + public isExpression(): boolean; + public isPrimaryExpression(): boolean; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + } + class FixedWidthTokenWithNoTrivia implements ISyntaxToken { + public tokenKind: SyntaxKind; + constructor(kind: SyntaxKind); + public clone(): ISyntaxToken; + public isNode(): boolean; + public isToken(): boolean; + public isList(): boolean; + public isSeparatedList(): boolean; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(index: number): ISyntaxElement; + public fullWidth(): number; + public width(): number; + public text(): string; + public fullText(): string; + public value(): any; + public valueText(): string; + public hasLeadingTrivia(): boolean; + public hasLeadingComment(): boolean; + public hasLeadingNewLine(): boolean; + public hasLeadingSkippedText(): boolean; + public leadingTriviaWidth(): number; + public leadingTrivia(): ISyntaxTriviaList; + public hasTrailingTrivia(): boolean; + public hasTrailingComment(): boolean; + public hasTrailingNewLine(): boolean; + public hasTrailingSkippedText(): boolean; + public trailingTriviaWidth(): number; + public trailingTrivia(): ISyntaxTriviaList; + public hasSkippedToken(): boolean; + public toJSON(key: any): any; + public firstToken(): ISyntaxToken; + public lastToken(): ISyntaxToken; + public isTypeScriptSpecific(): boolean; + public isIncrementallyUnusable(): boolean; + public accept(visitor: ISyntaxVisitor): any; + private realize(); + public collectTextElements(elements: string[]): void; + private findTokenInternal(parent, position, fullStart); + public withLeadingTrivia(leadingTrivia: ISyntaxTriviaList): ISyntaxToken; + public withTrailingTrivia(trailingTrivia: ISyntaxTriviaList): ISyntaxToken; + public isExpression(): boolean; + public isPrimaryExpression(): boolean; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + } + class FixedWidthTokenWithLeadingTrivia implements ISyntaxToken { + private _fullText; + public tokenKind: SyntaxKind; + private _leadingTriviaInfo; + constructor(fullText: string, kind: SyntaxKind, leadingTriviaInfo: number); + public clone(): ISyntaxToken; + public isNode(): boolean; + public isToken(): boolean; + public isList(): boolean; + public isSeparatedList(): boolean; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(index: number): ISyntaxElement; + public fullWidth(): number; + public width(): number; + public text(): string; + public fullText(): string; + public value(): any; + public valueText(): string; + public hasLeadingTrivia(): boolean; + public hasLeadingComment(): boolean; + public hasLeadingNewLine(): boolean; + public hasLeadingSkippedText(): boolean; + public leadingTriviaWidth(): number; + public leadingTrivia(): ISyntaxTriviaList; + public hasTrailingTrivia(): boolean; + public hasTrailingComment(): boolean; + public hasTrailingNewLine(): boolean; + public hasTrailingSkippedText(): boolean; + public trailingTriviaWidth(): number; + public trailingTrivia(): ISyntaxTriviaList; + public hasSkippedToken(): boolean; + public toJSON(key: any): any; + public firstToken(): ISyntaxToken; + public lastToken(): ISyntaxToken; + public isTypeScriptSpecific(): boolean; + public isIncrementallyUnusable(): boolean; + public accept(visitor: ISyntaxVisitor): any; + private realize(); + public collectTextElements(elements: string[]): void; + private findTokenInternal(parent, position, fullStart); + public withLeadingTrivia(leadingTrivia: ISyntaxTriviaList): ISyntaxToken; + public withTrailingTrivia(trailingTrivia: ISyntaxTriviaList): ISyntaxToken; + public isExpression(): boolean; + public isPrimaryExpression(): boolean; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + } + class FixedWidthTokenWithTrailingTrivia implements ISyntaxToken { + private _fullText; + public tokenKind: SyntaxKind; + private _trailingTriviaInfo; + constructor(fullText: string, kind: SyntaxKind, trailingTriviaInfo: number); + public clone(): ISyntaxToken; + public isNode(): boolean; + public isToken(): boolean; + public isList(): boolean; + public isSeparatedList(): boolean; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(index: number): ISyntaxElement; + public fullWidth(): number; + public width(): number; + public text(): string; + public fullText(): string; + public value(): any; + public valueText(): string; + public hasLeadingTrivia(): boolean; + public hasLeadingComment(): boolean; + public hasLeadingNewLine(): boolean; + public hasLeadingSkippedText(): boolean; + public leadingTriviaWidth(): number; + public leadingTrivia(): ISyntaxTriviaList; + public hasTrailingTrivia(): boolean; + public hasTrailingComment(): boolean; + public hasTrailingNewLine(): boolean; + public hasTrailingSkippedText(): boolean; + public trailingTriviaWidth(): number; + public trailingTrivia(): ISyntaxTriviaList; + public hasSkippedToken(): boolean; + public toJSON(key: any): any; + public firstToken(): ISyntaxToken; + public lastToken(): ISyntaxToken; + public isTypeScriptSpecific(): boolean; + public isIncrementallyUnusable(): boolean; + public accept(visitor: ISyntaxVisitor): any; + private realize(); + public collectTextElements(elements: string[]): void; + private findTokenInternal(parent, position, fullStart); + public withLeadingTrivia(leadingTrivia: ISyntaxTriviaList): ISyntaxToken; + public withTrailingTrivia(trailingTrivia: ISyntaxTriviaList): ISyntaxToken; + public isExpression(): boolean; + public isPrimaryExpression(): boolean; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + } + class FixedWidthTokenWithLeadingAndTrailingTrivia implements ISyntaxToken { + private _fullText; + public tokenKind: SyntaxKind; + private _leadingTriviaInfo; + private _trailingTriviaInfo; + constructor(fullText: string, kind: SyntaxKind, leadingTriviaInfo: number, trailingTriviaInfo: number); + public clone(): ISyntaxToken; + public isNode(): boolean; + public isToken(): boolean; + public isList(): boolean; + public isSeparatedList(): boolean; + public kind(): SyntaxKind; + public childCount(): number; + public childAt(index: number): ISyntaxElement; + public fullWidth(): number; + public width(): number; + public text(): string; + public fullText(): string; + public value(): any; + public valueText(): string; + public hasLeadingTrivia(): boolean; + public hasLeadingComment(): boolean; + public hasLeadingNewLine(): boolean; + public hasLeadingSkippedText(): boolean; + public leadingTriviaWidth(): number; + public leadingTrivia(): ISyntaxTriviaList; + public hasTrailingTrivia(): boolean; + public hasTrailingComment(): boolean; + public hasTrailingNewLine(): boolean; + public hasTrailingSkippedText(): boolean; + public trailingTriviaWidth(): number; + public trailingTrivia(): ISyntaxTriviaList; + public hasSkippedToken(): boolean; + public toJSON(key: any): any; + public firstToken(): ISyntaxToken; + public lastToken(): ISyntaxToken; + public isTypeScriptSpecific(): boolean; + public isIncrementallyUnusable(): boolean; + public accept(visitor: ISyntaxVisitor): any; + private realize(); + public collectTextElements(elements: string[]): void; + private findTokenInternal(parent, position, fullStart); + public withLeadingTrivia(leadingTrivia: ISyntaxTriviaList): ISyntaxToken; + public withTrailingTrivia(trailingTrivia: ISyntaxTriviaList): ISyntaxToken; + public isExpression(): boolean; + public isPrimaryExpression(): boolean; + public isMemberExpression(): boolean; + public isPostfixExpression(): boolean; + public isUnaryExpression(): boolean; + } +} +declare module TypeScript { + interface ISyntaxToken extends ISyntaxNodeOrToken, INameSyntax, IPrimaryExpressionSyntax { + tokenKind: SyntaxKind; + text(): string; + value(): any; + valueText(): string; + hasLeadingTrivia(): boolean; + hasLeadingComment(): boolean; + hasLeadingNewLine(): boolean; + hasLeadingSkippedText(): boolean; + hasTrailingTrivia(): boolean; + hasTrailingComment(): boolean; + hasTrailingNewLine(): boolean; + hasTrailingSkippedText(): boolean; + hasSkippedToken(): boolean; + leadingTrivia(): ISyntaxTriviaList; + trailingTrivia(): ISyntaxTriviaList; + withLeadingTrivia(leadingTrivia: ISyntaxTriviaList): ISyntaxToken; + withTrailingTrivia(trailingTrivia: ISyntaxTriviaList): ISyntaxToken; + clone(): ISyntaxToken; + } + interface ITokenInfo { + leadingTrivia?: ISyntaxTrivia[]; + text?: string; + trailingTrivia?: ISyntaxTrivia[]; + } +} +declare module TypeScript.Syntax { + function isExpression(token: ISyntaxToken): boolean; + function realizeToken(token: ISyntaxToken): ISyntaxToken; + function convertToIdentifierName(token: ISyntaxToken): ISyntaxToken; + function tokenToJSON(token: ISyntaxToken): any; + function value(token: ISyntaxToken): any; + function massageEscapes(text: string): string; + function valueText(token: ISyntaxToken): string; + function emptyToken(kind: SyntaxKind): ISyntaxToken; + function token(kind: SyntaxKind, info?: ITokenInfo): ISyntaxToken; + function identifier(text: string, info?: ITokenInfo): ISyntaxToken; +} +declare module TypeScript { + class SyntaxTokenReplacer extends SyntaxRewriter { + private token1; + private token2; + constructor(token1: ISyntaxToken, token2: ISyntaxToken); + public visitToken(token: ISyntaxToken): ISyntaxToken; + public visitNode(node: SyntaxNode): SyntaxNode; + public visitList(list: ISyntaxList): ISyntaxList; + public visitSeparatedList(list: ISeparatedSyntaxList): ISeparatedSyntaxList; + } +} +declare module TypeScript { + interface ISyntaxTrivia { + kind(): SyntaxKind; + isWhitespace(): boolean; + isComment(): boolean; + isNewLine(): boolean; + isSkippedToken(): boolean; + fullWidth(): number; + fullText(): string; + skippedToken(): ISyntaxToken; + } +} +declare module TypeScript.Syntax { + function deferredTrivia(kind: SyntaxKind, text: ISimpleText, fullStart: number, fullWidth: number): ISyntaxTrivia; + function trivia(kind: SyntaxKind, text: string): ISyntaxTrivia; + function skippedTokenTrivia(token: ISyntaxToken): ISyntaxTrivia; + function spaces(count: number): ISyntaxTrivia; + function whitespace(text: string): ISyntaxTrivia; + function multiLineComment(text: string): ISyntaxTrivia; + function singleLineComment(text: string): ISyntaxTrivia; + var spaceTrivia: ISyntaxTrivia; + var lineFeedTrivia: ISyntaxTrivia; + var carriageReturnTrivia: ISyntaxTrivia; + var carriageReturnLineFeedTrivia: ISyntaxTrivia; + function splitMultiLineCommentTriviaIntoMultipleLines(trivia: ISyntaxTrivia): string[]; +} +declare module TypeScript { + interface ISyntaxTriviaList { + count(): number; + syntaxTriviaAt(index: number): ISyntaxTrivia; + fullWidth(): number; + fullText(): string; + hasComment(): boolean; + hasNewLine(): boolean; + hasSkippedToken(): boolean; + last(): ISyntaxTrivia; + toArray(): ISyntaxTrivia[]; + concat(trivia: ISyntaxTriviaList): ISyntaxTriviaList; + collectTextElements(elements: string[]): void; + } +} +declare module TypeScript.Syntax { + var emptyTriviaList: ISyntaxTriviaList; + function triviaList(trivia: ISyntaxTrivia[]): ISyntaxTriviaList; + var spaceTriviaList: ISyntaxTriviaList; +} +declare module TypeScript { + class SyntaxUtilities { + static isAngleBracket(positionedElement: PositionedElement): boolean; + static getToken(list: ISyntaxList, kind: SyntaxKind): ISyntaxToken; + static containsToken(list: ISyntaxList, kind: SyntaxKind): boolean; + static hasExportKeyword(moduleElement: IModuleElementSyntax): boolean; + static getExportKeyword(moduleElement: IModuleElementSyntax): ISyntaxToken; + static isAmbientDeclarationSyntax(positionNode: PositionedNode): boolean; + } +} +declare module TypeScript { + interface ISyntaxVisitor { + visitToken(token: ISyntaxToken): any; + visitSourceUnit(node: SourceUnitSyntax): any; + visitExternalModuleReference(node: ExternalModuleReferenceSyntax): any; + visitModuleNameModuleReference(node: ModuleNameModuleReferenceSyntax): any; + visitImportDeclaration(node: ImportDeclarationSyntax): any; + visitExportAssignment(node: ExportAssignmentSyntax): any; + visitClassDeclaration(node: ClassDeclarationSyntax): any; + visitInterfaceDeclaration(node: InterfaceDeclarationSyntax): any; + visitHeritageClause(node: HeritageClauseSyntax): any; + visitModuleDeclaration(node: ModuleDeclarationSyntax): any; + visitFunctionDeclaration(node: FunctionDeclarationSyntax): any; + visitVariableStatement(node: VariableStatementSyntax): any; + visitVariableDeclaration(node: VariableDeclarationSyntax): any; + visitVariableDeclarator(node: VariableDeclaratorSyntax): any; + visitEqualsValueClause(node: EqualsValueClauseSyntax): any; + visitPrefixUnaryExpression(node: PrefixUnaryExpressionSyntax): any; + visitArrayLiteralExpression(node: ArrayLiteralExpressionSyntax): any; + visitOmittedExpression(node: OmittedExpressionSyntax): any; + visitParenthesizedExpression(node: ParenthesizedExpressionSyntax): any; + visitSimpleArrowFunctionExpression(node: SimpleArrowFunctionExpressionSyntax): any; + visitParenthesizedArrowFunctionExpression(node: ParenthesizedArrowFunctionExpressionSyntax): any; + visitQualifiedName(node: QualifiedNameSyntax): any; + visitTypeArgumentList(node: TypeArgumentListSyntax): any; + visitConstructorType(node: ConstructorTypeSyntax): any; + visitFunctionType(node: FunctionTypeSyntax): any; + visitObjectType(node: ObjectTypeSyntax): any; + visitArrayType(node: ArrayTypeSyntax): any; + visitGenericType(node: GenericTypeSyntax): any; + visitTypeQuery(node: TypeQuerySyntax): any; + visitTypeAnnotation(node: TypeAnnotationSyntax): any; + visitBlock(node: BlockSyntax): any; + visitParameter(node: ParameterSyntax): any; + visitMemberAccessExpression(node: MemberAccessExpressionSyntax): any; + visitPostfixUnaryExpression(node: PostfixUnaryExpressionSyntax): any; + visitElementAccessExpression(node: ElementAccessExpressionSyntax): any; + visitInvocationExpression(node: InvocationExpressionSyntax): any; + visitArgumentList(node: ArgumentListSyntax): any; + visitBinaryExpression(node: BinaryExpressionSyntax): any; + visitConditionalExpression(node: ConditionalExpressionSyntax): any; + visitConstructSignature(node: ConstructSignatureSyntax): any; + visitMethodSignature(node: MethodSignatureSyntax): any; + visitIndexSignature(node: IndexSignatureSyntax): any; + visitPropertySignature(node: PropertySignatureSyntax): any; + visitCallSignature(node: CallSignatureSyntax): any; + visitParameterList(node: ParameterListSyntax): any; + visitTypeParameterList(node: TypeParameterListSyntax): any; + visitTypeParameter(node: TypeParameterSyntax): any; + visitConstraint(node: ConstraintSyntax): any; + visitElseClause(node: ElseClauseSyntax): any; + visitIfStatement(node: IfStatementSyntax): any; + visitExpressionStatement(node: ExpressionStatementSyntax): any; + visitConstructorDeclaration(node: ConstructorDeclarationSyntax): any; + visitMemberFunctionDeclaration(node: MemberFunctionDeclarationSyntax): any; + visitGetAccessor(node: GetAccessorSyntax): any; + visitSetAccessor(node: SetAccessorSyntax): any; + visitMemberVariableDeclaration(node: MemberVariableDeclarationSyntax): any; + visitIndexMemberDeclaration(node: IndexMemberDeclarationSyntax): any; + visitThrowStatement(node: ThrowStatementSyntax): any; + visitReturnStatement(node: ReturnStatementSyntax): any; + visitObjectCreationExpression(node: ObjectCreationExpressionSyntax): any; + visitSwitchStatement(node: SwitchStatementSyntax): any; + visitCaseSwitchClause(node: CaseSwitchClauseSyntax): any; + visitDefaultSwitchClause(node: DefaultSwitchClauseSyntax): any; + visitBreakStatement(node: BreakStatementSyntax): any; + visitContinueStatement(node: ContinueStatementSyntax): any; + visitForStatement(node: ForStatementSyntax): any; + visitForInStatement(node: ForInStatementSyntax): any; + visitWhileStatement(node: WhileStatementSyntax): any; + visitWithStatement(node: WithStatementSyntax): any; + visitEnumDeclaration(node: EnumDeclarationSyntax): any; + visitEnumElement(node: EnumElementSyntax): any; + visitCastExpression(node: CastExpressionSyntax): any; + visitObjectLiteralExpression(node: ObjectLiteralExpressionSyntax): any; + visitSimplePropertyAssignment(node: SimplePropertyAssignmentSyntax): any; + visitFunctionPropertyAssignment(node: FunctionPropertyAssignmentSyntax): any; + visitFunctionExpression(node: FunctionExpressionSyntax): any; + visitEmptyStatement(node: EmptyStatementSyntax): any; + visitTryStatement(node: TryStatementSyntax): any; + visitCatchClause(node: CatchClauseSyntax): any; + visitFinallyClause(node: FinallyClauseSyntax): any; + visitLabeledStatement(node: LabeledStatementSyntax): any; + visitDoStatement(node: DoStatementSyntax): any; + visitTypeOfExpression(node: TypeOfExpressionSyntax): any; + visitDeleteExpression(node: DeleteExpressionSyntax): any; + visitVoidExpression(node: VoidExpressionSyntax): any; + visitDebuggerStatement(node: DebuggerStatementSyntax): any; + } + class SyntaxVisitor implements ISyntaxVisitor { + public defaultVisit(node: ISyntaxNodeOrToken): any; + public visitToken(token: ISyntaxToken): any; + public visitSourceUnit(node: SourceUnitSyntax): any; + public visitExternalModuleReference(node: ExternalModuleReferenceSyntax): any; + public visitModuleNameModuleReference(node: ModuleNameModuleReferenceSyntax): any; + public visitImportDeclaration(node: ImportDeclarationSyntax): any; + public visitExportAssignment(node: ExportAssignmentSyntax): any; + public visitClassDeclaration(node: ClassDeclarationSyntax): any; + public visitInterfaceDeclaration(node: InterfaceDeclarationSyntax): any; + public visitHeritageClause(node: HeritageClauseSyntax): any; + public visitModuleDeclaration(node: ModuleDeclarationSyntax): any; + public visitFunctionDeclaration(node: FunctionDeclarationSyntax): any; + public visitVariableStatement(node: VariableStatementSyntax): any; + public visitVariableDeclaration(node: VariableDeclarationSyntax): any; + public visitVariableDeclarator(node: VariableDeclaratorSyntax): any; + public visitEqualsValueClause(node: EqualsValueClauseSyntax): any; + public visitPrefixUnaryExpression(node: PrefixUnaryExpressionSyntax): any; + public visitArrayLiteralExpression(node: ArrayLiteralExpressionSyntax): any; + public visitOmittedExpression(node: OmittedExpressionSyntax): any; + public visitParenthesizedExpression(node: ParenthesizedExpressionSyntax): any; + public visitSimpleArrowFunctionExpression(node: SimpleArrowFunctionExpressionSyntax): any; + public visitParenthesizedArrowFunctionExpression(node: ParenthesizedArrowFunctionExpressionSyntax): any; + public visitQualifiedName(node: QualifiedNameSyntax): any; + public visitTypeArgumentList(node: TypeArgumentListSyntax): any; + public visitConstructorType(node: ConstructorTypeSyntax): any; + public visitFunctionType(node: FunctionTypeSyntax): any; + public visitObjectType(node: ObjectTypeSyntax): any; + public visitArrayType(node: ArrayTypeSyntax): any; + public visitGenericType(node: GenericTypeSyntax): any; + public visitTypeQuery(node: TypeQuerySyntax): any; + public visitTypeAnnotation(node: TypeAnnotationSyntax): any; + public visitBlock(node: BlockSyntax): any; + public visitParameter(node: ParameterSyntax): any; + public visitMemberAccessExpression(node: MemberAccessExpressionSyntax): any; + public visitPostfixUnaryExpression(node: PostfixUnaryExpressionSyntax): any; + public visitElementAccessExpression(node: ElementAccessExpressionSyntax): any; + public visitInvocationExpression(node: InvocationExpressionSyntax): any; + public visitArgumentList(node: ArgumentListSyntax): any; + public visitBinaryExpression(node: BinaryExpressionSyntax): any; + public visitConditionalExpression(node: ConditionalExpressionSyntax): any; + public visitConstructSignature(node: ConstructSignatureSyntax): any; + public visitMethodSignature(node: MethodSignatureSyntax): any; + public visitIndexSignature(node: IndexSignatureSyntax): any; + public visitPropertySignature(node: PropertySignatureSyntax): any; + public visitCallSignature(node: CallSignatureSyntax): any; + public visitParameterList(node: ParameterListSyntax): any; + public visitTypeParameterList(node: TypeParameterListSyntax): any; + public visitTypeParameter(node: TypeParameterSyntax): any; + public visitConstraint(node: ConstraintSyntax): any; + public visitElseClause(node: ElseClauseSyntax): any; + public visitIfStatement(node: IfStatementSyntax): any; + public visitExpressionStatement(node: ExpressionStatementSyntax): any; + public visitConstructorDeclaration(node: ConstructorDeclarationSyntax): any; + public visitMemberFunctionDeclaration(node: MemberFunctionDeclarationSyntax): any; + public visitGetAccessor(node: GetAccessorSyntax): any; + public visitSetAccessor(node: SetAccessorSyntax): any; + public visitMemberVariableDeclaration(node: MemberVariableDeclarationSyntax): any; + public visitIndexMemberDeclaration(node: IndexMemberDeclarationSyntax): any; + public visitThrowStatement(node: ThrowStatementSyntax): any; + public visitReturnStatement(node: ReturnStatementSyntax): any; + public visitObjectCreationExpression(node: ObjectCreationExpressionSyntax): any; + public visitSwitchStatement(node: SwitchStatementSyntax): any; + public visitCaseSwitchClause(node: CaseSwitchClauseSyntax): any; + public visitDefaultSwitchClause(node: DefaultSwitchClauseSyntax): any; + public visitBreakStatement(node: BreakStatementSyntax): any; + public visitContinueStatement(node: ContinueStatementSyntax): any; + public visitForStatement(node: ForStatementSyntax): any; + public visitForInStatement(node: ForInStatementSyntax): any; + public visitWhileStatement(node: WhileStatementSyntax): any; + public visitWithStatement(node: WithStatementSyntax): any; + public visitEnumDeclaration(node: EnumDeclarationSyntax): any; + public visitEnumElement(node: EnumElementSyntax): any; + public visitCastExpression(node: CastExpressionSyntax): any; + public visitObjectLiteralExpression(node: ObjectLiteralExpressionSyntax): any; + public visitSimplePropertyAssignment(node: SimplePropertyAssignmentSyntax): any; + public visitFunctionPropertyAssignment(node: FunctionPropertyAssignmentSyntax): any; + public visitFunctionExpression(node: FunctionExpressionSyntax): any; + public visitEmptyStatement(node: EmptyStatementSyntax): any; + public visitTryStatement(node: TryStatementSyntax): any; + public visitCatchClause(node: CatchClauseSyntax): any; + public visitFinallyClause(node: FinallyClauseSyntax): any; + public visitLabeledStatement(node: LabeledStatementSyntax): any; + public visitDoStatement(node: DoStatementSyntax): any; + public visitTypeOfExpression(node: TypeOfExpressionSyntax): any; + public visitDeleteExpression(node: DeleteExpressionSyntax): any; + public visitVoidExpression(node: VoidExpressionSyntax): any; + public visitDebuggerStatement(node: DebuggerStatementSyntax): any; + } +} +declare module TypeScript { + class SyntaxWalker implements ISyntaxVisitor { + public visitToken(token: ISyntaxToken): void; + public visitNode(node: SyntaxNode): void; + public visitNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void; + private visitOptionalToken(token); + public visitOptionalNode(node: SyntaxNode): void; + public visitOptionalNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void; + public visitList(list: ISyntaxList): void; + public visitSeparatedList(list: ISeparatedSyntaxList): void; + public visitSourceUnit(node: SourceUnitSyntax): void; + public visitExternalModuleReference(node: ExternalModuleReferenceSyntax): void; + public visitModuleNameModuleReference(node: ModuleNameModuleReferenceSyntax): void; + public visitImportDeclaration(node: ImportDeclarationSyntax): void; + public visitExportAssignment(node: ExportAssignmentSyntax): void; + public visitClassDeclaration(node: ClassDeclarationSyntax): void; + public visitInterfaceDeclaration(node: InterfaceDeclarationSyntax): void; + public visitHeritageClause(node: HeritageClauseSyntax): void; + public visitModuleDeclaration(node: ModuleDeclarationSyntax): void; + public visitFunctionDeclaration(node: FunctionDeclarationSyntax): void; + public visitVariableStatement(node: VariableStatementSyntax): void; + public visitVariableDeclaration(node: VariableDeclarationSyntax): void; + public visitVariableDeclarator(node: VariableDeclaratorSyntax): void; + public visitEqualsValueClause(node: EqualsValueClauseSyntax): void; + public visitPrefixUnaryExpression(node: PrefixUnaryExpressionSyntax): void; + public visitArrayLiteralExpression(node: ArrayLiteralExpressionSyntax): void; + public visitOmittedExpression(node: OmittedExpressionSyntax): void; + public visitParenthesizedExpression(node: ParenthesizedExpressionSyntax): void; + public visitSimpleArrowFunctionExpression(node: SimpleArrowFunctionExpressionSyntax): void; + public visitParenthesizedArrowFunctionExpression(node: ParenthesizedArrowFunctionExpressionSyntax): void; + public visitQualifiedName(node: QualifiedNameSyntax): void; + public visitTypeArgumentList(node: TypeArgumentListSyntax): void; + public visitConstructorType(node: ConstructorTypeSyntax): void; + public visitFunctionType(node: FunctionTypeSyntax): void; + public visitObjectType(node: ObjectTypeSyntax): void; + public visitArrayType(node: ArrayTypeSyntax): void; + public visitGenericType(node: GenericTypeSyntax): void; + public visitTypeQuery(node: TypeQuerySyntax): void; + public visitTypeAnnotation(node: TypeAnnotationSyntax): void; + public visitBlock(node: BlockSyntax): void; + public visitParameter(node: ParameterSyntax): void; + public visitMemberAccessExpression(node: MemberAccessExpressionSyntax): void; + public visitPostfixUnaryExpression(node: PostfixUnaryExpressionSyntax): void; + public visitElementAccessExpression(node: ElementAccessExpressionSyntax): void; + public visitInvocationExpression(node: InvocationExpressionSyntax): void; + public visitArgumentList(node: ArgumentListSyntax): void; + public visitBinaryExpression(node: BinaryExpressionSyntax): void; + public visitConditionalExpression(node: ConditionalExpressionSyntax): void; + public visitConstructSignature(node: ConstructSignatureSyntax): void; + public visitMethodSignature(node: MethodSignatureSyntax): void; + public visitIndexSignature(node: IndexSignatureSyntax): void; + public visitPropertySignature(node: PropertySignatureSyntax): void; + public visitCallSignature(node: CallSignatureSyntax): void; + public visitParameterList(node: ParameterListSyntax): void; + public visitTypeParameterList(node: TypeParameterListSyntax): void; + public visitTypeParameter(node: TypeParameterSyntax): void; + public visitConstraint(node: ConstraintSyntax): void; + public visitElseClause(node: ElseClauseSyntax): void; + public visitIfStatement(node: IfStatementSyntax): void; + public visitExpressionStatement(node: ExpressionStatementSyntax): void; + public visitConstructorDeclaration(node: ConstructorDeclarationSyntax): void; + public visitMemberFunctionDeclaration(node: MemberFunctionDeclarationSyntax): void; + public visitGetAccessor(node: GetAccessorSyntax): void; + public visitSetAccessor(node: SetAccessorSyntax): void; + public visitMemberVariableDeclaration(node: MemberVariableDeclarationSyntax): void; + public visitIndexMemberDeclaration(node: IndexMemberDeclarationSyntax): void; + public visitThrowStatement(node: ThrowStatementSyntax): void; + public visitReturnStatement(node: ReturnStatementSyntax): void; + public visitObjectCreationExpression(node: ObjectCreationExpressionSyntax): void; + public visitSwitchStatement(node: SwitchStatementSyntax): void; + public visitCaseSwitchClause(node: CaseSwitchClauseSyntax): void; + public visitDefaultSwitchClause(node: DefaultSwitchClauseSyntax): void; + public visitBreakStatement(node: BreakStatementSyntax): void; + public visitContinueStatement(node: ContinueStatementSyntax): void; + public visitForStatement(node: ForStatementSyntax): void; + public visitForInStatement(node: ForInStatementSyntax): void; + public visitWhileStatement(node: WhileStatementSyntax): void; + public visitWithStatement(node: WithStatementSyntax): void; + public visitEnumDeclaration(node: EnumDeclarationSyntax): void; + public visitEnumElement(node: EnumElementSyntax): void; + public visitCastExpression(node: CastExpressionSyntax): void; + public visitObjectLiteralExpression(node: ObjectLiteralExpressionSyntax): void; + public visitSimplePropertyAssignment(node: SimplePropertyAssignmentSyntax): void; + public visitFunctionPropertyAssignment(node: FunctionPropertyAssignmentSyntax): void; + public visitFunctionExpression(node: FunctionExpressionSyntax): void; + public visitEmptyStatement(node: EmptyStatementSyntax): void; + public visitTryStatement(node: TryStatementSyntax): void; + public visitCatchClause(node: CatchClauseSyntax): void; + public visitFinallyClause(node: FinallyClauseSyntax): void; + public visitLabeledStatement(node: LabeledStatementSyntax): void; + public visitDoStatement(node: DoStatementSyntax): void; + public visitTypeOfExpression(node: TypeOfExpressionSyntax): void; + public visitDeleteExpression(node: DeleteExpressionSyntax): void; + public visitVoidExpression(node: VoidExpressionSyntax): void; + public visitDebuggerStatement(node: DebuggerStatementSyntax): void; + } +} +declare module TypeScript { + class PositionTrackingWalker extends SyntaxWalker { + private _position; + public visitToken(token: ISyntaxToken): void; + public position(): number; + public skip(element: ISyntaxElement): void; + } +} +declare module TypeScript { + interface ITokenInformation { + previousToken: ISyntaxToken; + nextToken: ISyntaxToken; + } + class SyntaxInformationMap extends SyntaxWalker { + private trackParents; + private trackPreviousToken; + private tokenToInformation; + private elementToPosition; + private _previousToken; + private _previousTokenInformation; + private _currentPosition; + private _elementToParent; + private _parentStack; + constructor(trackParents: boolean, trackPreviousToken: boolean); + static create(node: SyntaxNode, trackParents: boolean, trackPreviousToken: boolean): SyntaxInformationMap; + public visitNode(node: SyntaxNode): void; + public visitToken(token: ISyntaxToken): void; + public parent(element: ISyntaxElement): SyntaxNode; + public fullStart(element: ISyntaxElement): number; + public start(element: ISyntaxElement): number; + public end(element: ISyntaxElement): number; + public previousToken(token: ISyntaxToken): ISyntaxToken; + public tokenInformation(token: ISyntaxToken): ITokenInformation; + public firstTokenInLineContainingToken(token: ISyntaxToken): ISyntaxToken; + public isFirstTokenInLine(token: ISyntaxToken): boolean; + private isFirstTokenInLineWorker(information); + } +} +declare module TypeScript { + class SyntaxNodeInvariantsChecker extends SyntaxWalker { + private tokenTable; + static checkInvariants(node: SyntaxNode): void; + public visitToken(token: ISyntaxToken): void; + } +} +declare module TypeScript { + class DepthLimitedWalker extends PositionTrackingWalker { + private _depth; + private _maximumDepth; + constructor(maximumDepth: number); + public visitNode(node: SyntaxNode): void; + } +} +declare module TypeScript.Parser { + function parse(fileName: string, text: ISimpleText, isDeclaration: boolean, options: ParseOptions): SyntaxTree; + function incrementalParse(oldSyntaxTree: SyntaxTree, textChangeRange: TextChangeRange, newText: ISimpleText): SyntaxTree; +} +declare module TypeScript { + class SyntaxTree { + private _sourceUnit; + private _isDeclaration; + private _parserDiagnostics; + private _allDiagnostics; + private _fileName; + private _lineMap; + private _parseOptions; + constructor(sourceUnit: SourceUnitSyntax, isDeclaration: boolean, diagnostics: Diagnostic[], fileName: string, lineMap: LineMap, parseOtions: ParseOptions); + public toJSON(key: any): any; + public sourceUnit(): SourceUnitSyntax; + public isDeclaration(): boolean; + private computeDiagnostics(); + public diagnostics(): Diagnostic[]; + public fileName(): string; + public lineMap(): LineMap; + public parseOptions(): ParseOptions; + public structuralEquals(tree: SyntaxTree): boolean; + } +} +declare module TypeScript { + class Unicode { + static unicodeES3IdentifierStart: number[]; + static unicodeES3IdentifierPart: number[]; + static unicodeES5IdentifierStart: number[]; + static unicodeES5IdentifierPart: number[]; + static lookupInUnicodeMap(code: number, map: number[]): boolean; + static isIdentifierStart(code: number, languageVersion: LanguageVersion): boolean; + static isIdentifierPart(code: number, languageVersion: LanguageVersion): boolean; + } +} +declare module TypeScript { + module CompilerDiagnostics { + var debug: boolean; + interface IDiagnosticWriter { + Alert(output: string): void; + } + var diagnosticWriter: IDiagnosticWriter; + var analysisPass: number; + function Alert(output: string): void; + function debugPrint(s: string): void; + function assert(condition: boolean, s: string): void; + } + interface ILogger { + information(): boolean; + debug(): boolean; + warning(): boolean; + error(): boolean; + fatal(): boolean; + log(s: string): void; + } + class NullLogger implements ILogger { + public information(): boolean; + public debug(): boolean; + public warning(): boolean; + public error(): boolean; + public fatal(): boolean; + public log(s: string): void; + } + function timeFunction(logger: ILogger, funcDescription: string, func: () => any): any; +} +declare module TypeScript { + class Document { + private _compiler; + private _semanticInfoChain; + public fileName: string; + public referencedFiles: string[]; + private _scriptSnapshot; + public byteOrderMark: ByteOrderMark; + public version: number; + public isOpen: boolean; + private _syntaxTree; + private _topLevelDecl; + private _diagnostics; + private _bloomFilter; + private _sourceUnit; + private _lineMap; + private _declASTMap; + private _astDeclMap; + private _amdDependencies; + private _externalModuleIndicatorSpan; + constructor(_compiler: TypeScriptCompiler, _semanticInfoChain: SemanticInfoChain, fileName: string, referencedFiles: string[], _scriptSnapshot: IScriptSnapshot, byteOrderMark: ByteOrderMark, version: number, isOpen: boolean, _syntaxTree: SyntaxTree, _topLevelDecl: PullDecl); + public invalidate(): void; + public isDeclareFile(): boolean; + private cacheSyntaxTreeInfo(syntaxTree); + private getAmdDependency(comment); + private getImplicitImportSpan(sourceUnitLeadingTrivia); + private getImplicitImportSpanWorker(trivia, position); + private getTopLevelImportOrExportSpan(node); + public sourceUnit(): SourceUnit; + public diagnostics(): Diagnostic[]; + public lineMap(): LineMap; + public isExternalModule(): boolean; + public externalModuleIndicatorSpan(): TextSpan; + public amdDependencies(): string[]; + public syntaxTree(): SyntaxTree; + public bloomFilter(): BloomFilter; + public emitToOwnOutputFile(): boolean; + public update(scriptSnapshot: IScriptSnapshot, version: number, isOpen: boolean, textChangeRange: TextChangeRange): Document; + static create(compiler: TypeScriptCompiler, semanticInfoChain: SemanticInfoChain, fileName: string, scriptSnapshot: IScriptSnapshot, byteOrderMark: ByteOrderMark, version: number, isOpen: boolean, referencedFiles: string[]): Document; + public topLevelDecl(): PullDecl; + public _getDeclForAST(ast: AST): PullDecl; + public getEnclosingDecl(ast: AST): PullDecl; + public _setDeclForAST(ast: AST, decl: PullDecl): void; + public _getASTForDecl(decl: PullDecl): AST; + public _setASTForDecl(decl: PullDecl, ast: AST): void; + } +} +declare module TypeScript { + function hasFlag(val: number, flag: number): boolean; + enum TypeRelationshipFlags { + SuccessfulComparison = 0, + RequiredPropertyIsMissing = 2, + IncompatibleSignatures = 4, + SourceSignatureHasTooManyParameters = 3, + IncompatibleReturnTypes = 16, + IncompatiblePropertyTypes = 32, + IncompatibleParameterTypes = 64, + InconsistantPropertyAccesibility = 128, + } + enum ModuleGenTarget { + Unspecified = 0, + Synchronous = 1, + Asynchronous = 2, + } +} +declare module TypeScript { + function createIntrinsicsObject(): IIndexable; + interface IHashTable { + getAllKeys(): string[]; + add(key: string, data: T): boolean; + addOrUpdate(key: string, data: T): boolean; + map(fn: (k: string, value: T, context: any) => void, context: any): void; + every(fn: (k: string, value: T, context: any) => void, context: any): boolean; + some(fn: (k: string, value: T, context: any) => void, context: any): boolean; + count(): number; + lookup(key: string): T; + } + class StringHashTable implements IHashTable { + private itemCount; + private table; + public getAllKeys(): string[]; + public add(key: string, data: T): boolean; + public addOrUpdate(key: string, data: T): boolean; + public map(fn: (k: string, value: T, context: any) => void, context: any): void; + public every(fn: (k: string, value: T, context: any) => void, context: any): boolean; + public some(fn: (k: string, value: T, context: any) => void, context: any): boolean; + public count(): number; + public lookup(key: string): T; + public remove(key: string): void; + } + class IdentiferNameHashTable extends StringHashTable { + public getAllKeys(): string[]; + public add(key: string, data: T): boolean; + public addOrUpdate(key: string, data: T): boolean; + public map(fn: (k: string, value: T, context: any) => void, context: any): void; + public every(fn: (k: string, value: T, context: any) => void, context: any): boolean; + public some(fn: (k: string, value: any, context: any) => void, context: any): boolean; + public lookup(key: string): T; + } +} +declare module TypeScript { + interface IParameters { + length: number; + lastParameterIsRest(): boolean; + ast: AST; + astAt(index: number): AST; + identifierAt(index: number): Identifier; + typeAt(index: number): AST; + initializerAt(index: number): EqualsValueClause; + isOptionalAt(index: number): boolean; + } +} +declare module TypeScript.ASTHelpers { + function scriptIsElided(sourceUnit: SourceUnit): boolean; + function moduleIsElided(declaration: ModuleDeclaration): boolean; + function enumIsElided(declaration: EnumDeclaration): boolean; + function isValidAstNode(ast: IASTSpan): boolean; + function getAstAtPosition(script: AST, pos: number, useTrailingTriviaAsLimChar?: boolean, forceInclusive?: boolean): AST; + function getExtendsHeritageClause(clauses: ISyntaxList2): HeritageClause; + function getImplementsHeritageClause(clauses: ISyntaxList2): HeritageClause; + function isCallExpression(ast: AST): boolean; + function isCallExpressionTarget(ast: AST): boolean; + function isDeclarationASTOrDeclarationNameAST(ast: AST): boolean; + function getEnclosingParameterForInitializer(ast: AST): Parameter; + function getEnclosingMemberVariableDeclaration(ast: AST): MemberVariableDeclaration; + function isNameOfFunction(ast: AST): boolean; + function isNameOfMemberFunction(ast: AST): boolean; + function isNameOfMemberAccessExpression(ast: AST): boolean; + function isRightSideOfQualifiedName(ast: AST): boolean; + function parentIsModuleDeclaration(ast: AST): boolean; + function parametersFromIdentifier(id: Identifier): IParameters; + function parametersFromParameter(parameter: Parameter): IParameters; + function parametersFromParameterList(list: ParameterList): IParameters; + function isDeclarationAST(ast: AST): boolean; + function docComments(ast: AST): Comment[]; + function getParameterList(ast: AST): ParameterList; + function getType(ast: AST): AST; + function getVariableDeclaratorModifiers(variableDeclarator: VariableDeclarator): PullElementFlags[]; + function isIntegerLiteralAST(expression: AST): boolean; + function getEnclosingModuleDeclaration(ast: AST): ModuleDeclaration; + function getModuleDeclarationFromNameAST(ast: AST): ModuleDeclaration; + function isLastNameOfModule(ast: ModuleDeclaration, astName: AST): boolean; + function getNameOfIdenfierOrQualifiedName(name: AST): string; + function getModuleNames(name: AST, result?: Identifier[]): Identifier[]; +} +declare module TypeScript { + class AstWalkOptions { + public goChildren: boolean; + public stopWalking: boolean; + } + interface IAstWalker { + options: AstWalkOptions; + state: any; + } + class AstWalkerFactory { + public walk(ast: AST, pre: (ast: AST, walker: IAstWalker) => void, post?: (ast: AST, walker: IAstWalker) => void, state?: any): void; + public simpleWalk(ast: AST, pre: (ast: AST, state: any) => void, post?: (ast: AST, state: any) => void, state?: any): void; + } + function getAstWalkerFactory(): AstWalkerFactory; +} +declare module TypeScript { + class Base64VLQFormat { + static encode(inValue: number): string; + static decode(inString: string): { + value: number; + rest: string; + }; + } +} +declare module TypeScript { + class SourceMapPosition { + public sourceLine: number; + public sourceColumn: number; + public emittedLine: number; + public emittedColumn: number; + } + class SourceMapping { + public start: SourceMapPosition; + public end: SourceMapPosition; + public nameIndex: number; + public childMappings: SourceMapping[]; + } + class SourceMapEntry { + public emittedFile: string; + public emittedLine: number; + public emittedColumn: number; + public sourceFile: string; + public sourceLine: number; + public sourceColumn: number; + public sourceName: string; + constructor(emittedFile: string, emittedLine: number, emittedColumn: number, sourceFile: string, sourceLine: number, sourceColumn: number, sourceName: string); + } + class SourceMapper { + private jsFile; + private sourceMapOut; + static MapFileExtension: string; + private jsFileName; + private sourceMapPath; + private sourceMapDirectory; + private sourceRoot; + public names: string[]; + private mappingLevel; + private tsFilePaths; + private allSourceMappings; + public currentMappings: SourceMapping[][]; + public currentNameIndex: number[]; + private sourceMapEntries; + constructor(jsFile: TextWriter, sourceMapOut: TextWriter, document: Document, jsFilePath: string, emitOptions: EmitOptions, resolvePath: (path: string) => string); + public getOutputFile(): OutputFile; + public increaseMappingLevel(ast: IASTSpan): void; + public decreaseMappingLevel(ast: IASTSpan): void; + public setNewSourceFile(document: Document, emitOptions: EmitOptions): void; + private setSourceMapOptions(document, jsFilePath, emitOptions, resolvePath); + private setNewSourceFilePath(document, emitOptions); + public emitSourceMapping(): void; + } +} +declare module TypeScript { + enum EmitContainer { + Prog = 0, + Module = 1, + DynamicModule = 2, + Class = 3, + Constructor = 4, + Function = 5, + Args = 6, + Interface = 7, + } + class EmitState { + public column: number; + public line: number; + public container: EmitContainer; + constructor(); + } + class EmitOptions { + public resolvePath: (path: string) => string; + private _diagnostic; + private _settings; + private _commonDirectoryPath; + private _sharedOutputFile; + private _sourceRootDirectory; + private _sourceMapRootDirectory; + private _outputDirectory; + public diagnostic(): Diagnostic; + public commonDirectoryPath(): string; + public sharedOutputFile(): string; + public sourceRootDirectory(): string; + public sourceMapRootDirectory(): string; + public outputDirectory(): string; + public compilationSettings(): ImmutableCompilationSettings; + constructor(compiler: TypeScriptCompiler, resolvePath: (path: string) => string); + private determineCommonDirectoryPath(compiler); + } + class Indenter { + static indentStep: number; + static indentStepString: string; + static indentStrings: string[]; + public indentAmt: number; + public increaseIndent(): void; + public decreaseIndent(): void; + public getIndent(): string; + } + function lastParameterIsRest(parameterList: ParameterList): boolean; + class Emitter { + public emittingFileName: string; + public outfile: TextWriter; + public emitOptions: EmitOptions; + private semanticInfoChain; + public globalThisCapturePrologueEmitted: boolean; + public extendsPrologueEmitted: boolean; + public thisClassNode: ClassDeclaration; + public inArrowFunction: boolean; + public moduleName: string; + public emitState: EmitState; + public indenter: Indenter; + public sourceMapper: SourceMapper; + public captureThisStmtString: string; + private currentVariableDeclaration; + private declStack; + private exportAssignment; + private inWithBlock; + public document: Document; + private detachedCommentsElement; + constructor(emittingFileName: string, outfile: TextWriter, emitOptions: EmitOptions, semanticInfoChain: SemanticInfoChain); + private pushDecl(decl); + private popDecl(decl); + private getEnclosingDecl(); + public setExportAssignment(exportAssignment: ExportAssignment): void; + public getExportAssignment(): ExportAssignment; + public setDocument(document: Document): void; + public shouldEmitImportDeclaration(importDeclAST: ImportDeclaration): boolean; + public emitImportDeclaration(importDeclAST: ImportDeclaration): void; + public createSourceMapper(document: Document, jsFileName: string, jsFile: TextWriter, sourceMapOut: TextWriter, resolvePath: (path: string) => string): void; + public setSourceMapperNewSourceFile(document: Document): void; + private updateLineAndColumn(s); + public writeToOutputWithSourceMapRecord(s: string, astSpan: IASTSpan): void; + public writeToOutput(s: string): void; + public writeLineToOutput(s: string, force?: boolean): void; + public writeCaptureThisStatement(ast: AST): void; + public setContainer(c: number): number; + private getIndentString(); + public emitIndent(): void; + public emitComment(comment: Comment, trailing: boolean, first: boolean): void; + public emitComments(ast: AST, pre: boolean, onlyPinnedOrTripleSlashComments?: boolean): void; + private isPinnedOrTripleSlash(comment); + public emitCommentsArray(comments: Comment[], trailing: boolean): void; + public emitObjectLiteralExpression(objectLiteral: ObjectLiteralExpression): void; + public emitArrayLiteralExpression(arrayLiteral: ArrayLiteralExpression): void; + public emitObjectCreationExpression(objectCreationExpression: ObjectCreationExpression): void; + public getConstantDecl(dotExpr: MemberAccessExpression): PullEnumElementDecl; + public tryEmitConstant(dotExpr: MemberAccessExpression): boolean; + public emitInvocationExpression(callNode: InvocationExpression): void; + private emitParameterList(list); + private emitFunctionParameters(parameters); + private emitFunctionBodyStatements(name, funcDecl, parameterList, block, bodyExpression); + private emitDefaultValueAssignments(parameters); + private emitRestParameterInitializer(parameters); + private getImportDecls(fileName); + public getModuleImportAndDependencyList(sourceUnit: SourceUnit): { + importList: string; + dependencyList: string; + }; + public shouldCaptureThis(ast: AST): boolean; + public emitEnum(moduleDecl: EnumDeclaration): void; + private getModuleDeclToVerifyChildNameCollision(moduleDecl, changeNameIfAnyDeclarationInContext); + private hasChildNameCollision(moduleName, parentDecl); + private getModuleName(moduleDecl, changeNameIfAnyDeclarationInContext?); + private emitModuleDeclarationWorker(moduleDecl); + public emitSingleModuleDeclaration(moduleDecl: ModuleDeclaration, moduleName: IASTToken): void; + public emitEnumElement(varDecl: EnumElement): void; + public emitElementAccessExpression(expression: ElementAccessExpression): void; + public emitSimpleArrowFunctionExpression(arrowFunction: SimpleArrowFunctionExpression): void; + public emitParenthesizedArrowFunctionExpression(arrowFunction: ParenthesizedArrowFunctionExpression): void; + private emitAnyArrowFunctionExpression(arrowFunction, funcName, parameters, block, expression); + public emitConstructor(funcDecl: ConstructorDeclaration): void; + public emitGetAccessor(accessor: GetAccessor): void; + public emitSetAccessor(accessor: SetAccessor): void; + public emitFunctionExpression(funcDecl: FunctionExpression): void; + public emitFunction(funcDecl: FunctionDeclaration): void; + public emitAmbientVarDecl(varDecl: VariableDeclarator): void; + public emitVarDeclVar(): void; + public emitVariableDeclaration(declaration: VariableDeclaration): void; + private emitMemberVariableDeclaration(varDecl); + public emitVariableDeclarator(varDecl: VariableDeclarator): void; + private symbolIsUsedInItsEnclosingContainer(symbol, dynamic?); + private shouldQualifySymbolNameWithParentName(symbol); + private getSymbolForEmit(ast); + public emitName(name: Identifier, addThis: boolean): void; + public recordSourceMappingNameStart(name: string): void; + public recordSourceMappingNameEnd(): void; + public recordSourceMappingStart(ast: IASTSpan): void; + public recordSourceMappingEnd(ast: IASTSpan): void; + public getOutputFiles(): OutputFile[]; + private emitParameterPropertyAndMemberVariableAssignments(); + private isOnSameLine(pos1, pos2); + private emitCommaSeparatedList(parent, list, buffer, preserveNewLines); + public emitList(list: ISyntaxList2, useNewLineSeparator?: boolean, startInclusive?: number, endExclusive?: number): void; + public emitSeparatedList(list: ISeparatedSyntaxList2, useNewLineSeparator?: boolean, startInclusive?: number, endExclusive?: number): void; + private isDirectivePrologueElement(node); + public emitSpaceBetweenConstructs(node1: AST, node2: AST): void; + private getDetachedComments(element); + private emitPossibleCopyrightHeaders(script); + private emitDetachedComments(list); + public emitScriptElements(sourceUnit: SourceUnit): void; + public emitConstructorStatements(funcDecl: ConstructorDeclaration): void; + public emitJavascript(ast: AST, startLine: boolean): void; + public emitAccessorMemberDeclaration(funcDecl: AST, name: IASTToken, className: string, isProto: boolean): void; + private emitAccessorBody(funcDecl, parameterList, block); + public emitClass(classDecl: ClassDeclaration): void; + private emitClassMembers(classDecl); + private emitClassMemberFunctionDeclaration(classDecl, funcDecl); + private requiresExtendsBlock(moduleElements); + public emitPrologue(sourceUnit: SourceUnit): void; + public emitThis(): void; + public emitBlockOrStatement(node: AST): void; + public emitLiteralExpression(expression: LiteralExpression): void; + public emitThisExpression(expression: ThisExpression): void; + public emitSuperExpression(expression: SuperExpression): void; + public emitParenthesizedExpression(parenthesizedExpression: ParenthesizedExpression): void; + public emitCastExpression(expression: CastExpression): void; + public emitPrefixUnaryExpression(expression: PrefixUnaryExpression): void; + public emitPostfixUnaryExpression(expression: PostfixUnaryExpression): void; + public emitTypeOfExpression(expression: TypeOfExpression): void; + public emitDeleteExpression(expression: DeleteExpression): void; + public emitVoidExpression(expression: VoidExpression): void; + private canEmitDottedNameMemberAccessExpression(expression); + private emitDottedNameMemberAccessExpression(expression); + private emitDottedNameMemberAccessExpressionRecurse(expression); + public emitMemberAccessExpression(expression: MemberAccessExpression): void; + public emitQualifiedName(name: QualifiedName): void; + public emitBinaryExpression(expression: BinaryExpression): void; + public emitSimplePropertyAssignment(property: SimplePropertyAssignment): void; + public emitFunctionPropertyAssignment(funcProp: FunctionPropertyAssignment): void; + public emitConditionalExpression(expression: ConditionalExpression): void; + public emitThrowStatement(statement: ThrowStatement): void; + public emitExpressionStatement(statement: ExpressionStatement): void; + public emitLabeledStatement(statement: LabeledStatement): void; + public emitBlock(block: Block): void; + public emitBreakStatement(jump: BreakStatement): void; + public emitContinueStatement(jump: ContinueStatement): void; + public emitWhileStatement(statement: WhileStatement): void; + public emitDoStatement(statement: DoStatement): void; + public emitIfStatement(statement: IfStatement): void; + public emitElseClause(elseClause: ElseClause): void; + public emitReturnStatement(statement: ReturnStatement): void; + public emitForInStatement(statement: ForInStatement): void; + public emitForStatement(statement: ForStatement): void; + public emitWithStatement(statement: WithStatement): void; + public emitSwitchStatement(statement: SwitchStatement): void; + public emitCaseSwitchClause(clause: CaseSwitchClause): void; + private emitSwitchClauseBody(body); + public emitDefaultSwitchClause(clause: DefaultSwitchClause): void; + public emitTryStatement(statement: TryStatement): void; + public emitCatchClause(clause: CatchClause): void; + public emitFinallyClause(clause: FinallyClause): void; + public emitDebuggerStatement(statement: DebuggerStatement): void; + public emitNumericLiteral(literal: NumericLiteral): void; + public emitRegularExpressionLiteral(literal: RegularExpressionLiteral): void; + public emitStringLiteral(literal: StringLiteral): void; + public emitEqualsValueClause(clause: EqualsValueClause): void; + public emitParameter(parameter: Parameter): void; + public emitConstructorDeclaration(declaration: ConstructorDeclaration): void; + public shouldEmitFunctionDeclaration(declaration: FunctionDeclaration): boolean; + public emitFunctionDeclaration(declaration: FunctionDeclaration): void; + private emitSourceUnit(sourceUnit); + public shouldEmitEnumDeclaration(declaration: EnumDeclaration): boolean; + public emitEnumDeclaration(declaration: EnumDeclaration): void; + public shouldEmitModuleDeclaration(declaration: ModuleDeclaration): boolean; + private emitModuleDeclaration(declaration); + public shouldEmitClassDeclaration(declaration: ClassDeclaration): boolean; + public emitClassDeclaration(declaration: ClassDeclaration): void; + public shouldEmitInterfaceDeclaration(declaration: InterfaceDeclaration): boolean; + public emitInterfaceDeclaration(declaration: InterfaceDeclaration): void; + private firstVariableDeclarator(statement); + private isNotAmbientOrHasInitializer(variableStatement); + public shouldEmitVariableStatement(statement: VariableStatement): boolean; + public emitVariableStatement(statement: VariableStatement): void; + public emitGenericType(type: GenericType): void; + private shouldEmit(ast); + private emit(ast); + private emitWorker(ast); + } + function getLastConstructor(classDecl: ClassDeclaration): ConstructorDeclaration; + function getTrimmedTextLines(comment: Comment): string[]; +} +declare module TypeScript { + class MemberName { + public prefix: string; + public suffix: string; + public isString(): boolean; + public isArray(): boolean; + public isMarker(): boolean; + public toString(): string; + static memberNameToString(memberName: MemberName, markerInfo?: number[], markerBaseLength?: number): string; + static create(text: string): MemberName; + static create(entry: MemberName, prefix: string, suffix: string): MemberName; + } + class MemberNameString extends MemberName { + public text: string; + constructor(text: string); + public isString(): boolean; + } + class MemberNameArray extends MemberName { + public delim: string; + public entries: MemberName[]; + public isArray(): boolean; + public add(entry: MemberName): void; + public addAll(entries: MemberName[]): void; + constructor(); + } +} +declare module TypeScript { + function stripStartAndEndQuotes(str: string): string; + function isSingleQuoted(str: string): boolean; + function isDoubleQuoted(str: string): boolean; + function isQuoted(str: string): boolean; + function quoteStr(str: string): string; + function switchToForwardSlashes(path: string): string; + function trimModName(modName: string): string; + function getDeclareFilePath(fname: string): string; + function isTSFile(fname: string): boolean; + function isDTSFile(fname: string): boolean; + function getPrettyName(modPath: string, quote?: boolean, treatAsFileName?: boolean): any; + function getPathComponents(path: string): string[]; + function getRelativePathToFixedPath(fixedModFilePath: string, absoluteModPath: string, isAbsoultePathURL?: boolean): string; + function changePathToDTS(modPath: string): string; + function isRelative(path: string): boolean; + function isRooted(path: string): boolean; + function getRootFilePath(outFname: string): string; + function filePathComponents(fullPath: string): string[]; + function filePath(fullPath: string): string; + function convertToDirectoryPath(dirPath: string): string; + function normalizePath(path: string): string; +} +declare module TypeScript { + interface IFileReference extends ILineAndCharacter { + path: string; + isResident: boolean; + position: number; + length: number; + } +} +declare module TypeScript { + interface IPreProcessedFileInfo { + referencedFiles: IFileReference[]; + importedFiles: IFileReference[]; + diagnostics: Diagnostic[]; + isLibFile: boolean; + } + var tripleSlashReferenceRegExp: RegExp; + function preProcessFile(fileName: string, sourceText: IScriptSnapshot, readImportFiles?: boolean): IPreProcessedFileInfo; + function getParseOptions(settings: ImmutableCompilationSettings): ParseOptions; + function getReferencedFiles(fileName: string, sourceText: IScriptSnapshot): IFileReference[]; +} +declare module TypeScript { + interface IResolvedFile { + path: string; + referencedFiles: string[]; + importedFiles: string[]; + } + interface IReferenceResolverHost { + getScriptSnapshot(fileName: string): IScriptSnapshot; + resolveRelativePath(path: string, directory: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + getParentDirectory(path: string): string; + } + class ReferenceResolutionResult { + public resolvedFiles: IResolvedFile[]; + public diagnostics: Diagnostic[]; + public seenNoDefaultLibTag: boolean; + } + class ReferenceResolver { + private useCaseSensitiveFileResolution; + private inputFileNames; + private host; + private visited; + constructor(inputFileNames: string[], host: IReferenceResolverHost, useCaseSensitiveFileResolution: boolean); + static resolve(inputFileNames: string[], host: IReferenceResolverHost, useCaseSensitiveFileResolution: boolean): ReferenceResolutionResult; + public resolveInputFiles(): ReferenceResolutionResult; + private resolveIncludedFile(path, referenceLocation, resolutionResult); + private resolveImportedFile(path, referenceLocation, resolutionResult); + private resolveFile(normalizedPath, resolutionResult); + private getNormalizedFilePath(path, parentFilePath); + private getUniqueFileId(filePath); + private recordVisitedFile(filePath); + private isVisited(filePath); + private isSameFile(filePath1, filePath2); + } +} +declare module TypeScript { + class TextWriter { + private name; + private writeByteOrderMark; + private outputFileType; + private contents; + public onNewLine: boolean; + constructor(name: string, writeByteOrderMark: boolean, outputFileType: OutputFileType); + public Write(s: string): void; + public WriteLine(s: string): void; + public Close(): void; + public getOutputFile(): OutputFile; + } + class DeclarationEmitter { + private emittingFileName; + public document: Document; + private compiler; + private emitOptions; + private semanticInfoChain; + private declFile; + private indenter; + private emittedReferencePaths; + constructor(emittingFileName: string, document: Document, compiler: TypeScriptCompiler, emitOptions: EmitOptions, semanticInfoChain: SemanticInfoChain); + public getOutputFile(): OutputFile; + public emitDeclarations(sourceUnit: SourceUnit): void; + private emitDeclarationsForList(list); + private emitSeparatedList(list); + private emitDeclarationsForAST(ast); + private getIndentString(declIndent?); + private emitIndent(); + private canEmitDeclarations(declAST); + private getDeclFlagsString(pullDecl, typeString); + private emitDeclFlags(declarationAST, typeString); + private emitTypeNamesMember(memberName, emitIndent?); + private emitTypeSignature(ast, type); + private emitComment(comment); + private emitDeclarationComments(ast, endLine?); + private writeDeclarationComments(declComments, endLine?); + private emitTypeOfVariableDeclaratorOrParameter(boundDecl); + private emitPropertySignature(varDecl); + private emitVariableDeclarator(varDecl, isFirstVarInList, isLastVarInList); + private emitClassElementModifiers(modifiers); + private emitDeclarationsForMemberVariableDeclaration(varDecl); + private emitDeclarationsForVariableStatement(variableStatement); + private emitDeclarationsForVariableDeclaration(variableDeclaration); + private emitArgDecl(argDecl, id, isOptional, isPrivate); + private isOverloadedCallSignature(funcDecl); + private emitDeclarationsForConstructorDeclaration(funcDecl); + private emitParameterList(isPrivate, parameterList); + private emitParameters(isPrivate, parameterList); + private emitMemberFunctionDeclaration(funcDecl); + private emitCallSignature(funcDecl); + private emitConstructSignature(funcDecl); + private emitMethodSignature(funcDecl); + private emitDeclarationsForFunctionDeclaration(funcDecl); + private emitIndexMemberDeclaration(funcDecl); + private emitIndexSignature(funcDecl); + private emitBaseList(bases, useExtendsList); + private emitAccessorDeclarationComments(funcDecl); + private emitDeclarationsForGetAccessor(funcDecl); + private emitDeclarationsForSetAccessor(funcDecl); + private emitMemberAccessorDeclaration(funcDecl, modifiers, name); + private emitClassMembersFromConstructorDefinition(funcDecl); + private emitDeclarationsForClassDeclaration(classDecl); + private emitHeritageClauses(clauses); + private emitHeritageClause(clause); + static getEnclosingContainer(ast: AST): AST; + private emitTypeParameters(typeParams, funcSignature?); + private emitDeclarationsForInterfaceDeclaration(interfaceDecl); + private emitDeclarationsForImportDeclaration(importDeclAST); + private emitDeclarationsForEnumDeclaration(moduleDecl); + private emitDeclarationsForModuleDeclaration(moduleDecl); + private emitDeclarationsForExportAssignment(ast); + private resolveScriptReference(document, reference); + private emitReferencePaths(sourceUnit); + private emitDeclarationsForSourceUnit(sourceUnit); + } +} +declare module TypeScript { + class BloomFilter { + private bitArray; + private hashFunctionCount; + static falsePositiveProbability: number; + constructor(expectedCount: number); + static computeM(expectedCount: number): number; + static computeK(expectedCount: number): number; + private computeHash(key, seed); + public addKeys(keys: IIndexable): void; + public add(value: string): void; + public probablyContains(value: string): boolean; + public isEquivalent(filter: BloomFilter): boolean; + static isEquivalent(array1: boolean[], array2: boolean[]): boolean; + } +} +declare module TypeScript { + class IdentifierWalker extends SyntaxWalker { + public list: IIndexable; + constructor(list: IIndexable); + public visitToken(token: ISyntaxToken): void; + } +} +declare module TypeScript { + class CompilationSettings { + public propagateEnumConstants: boolean; + public removeComments: boolean; + public watch: boolean; + public noResolve: boolean; + public allowAutomaticSemicolonInsertion: boolean; + public noImplicitAny: boolean; + public noLib: boolean; + public codeGenTarget: LanguageVersion; + public moduleGenTarget: ModuleGenTarget; + public outFileOption: string; + public outDirOption: string; + public mapSourceFiles: boolean; + public mapRoot: string; + public sourceRoot: string; + public generateDeclarationFiles: boolean; + public useCaseSensitiveFileResolution: boolean; + public gatherDiagnostics: boolean; + public codepage: number; + public createFileLog: boolean; + } + class ImmutableCompilationSettings { + private static _defaultSettings; + private _propagateEnumConstants; + private _removeComments; + private _watch; + private _noResolve; + private _allowAutomaticSemicolonInsertion; + private _noImplicitAny; + private _noLib; + private _codeGenTarget; + private _moduleGenTarget; + private _outFileOption; + private _outDirOption; + private _mapSourceFiles; + private _mapRoot; + private _sourceRoot; + private _generateDeclarationFiles; + private _useCaseSensitiveFileResolution; + private _gatherDiagnostics; + private _codepage; + private _createFileLog; + public propagateEnumConstants(): boolean; + public removeComments(): boolean; + public watch(): boolean; + public noResolve(): boolean; + public allowAutomaticSemicolonInsertion(): boolean; + public noImplicitAny(): boolean; + public noLib(): boolean; + public codeGenTarget(): LanguageVersion; + public moduleGenTarget(): ModuleGenTarget; + public outFileOption(): string; + public outDirOption(): string; + public mapSourceFiles(): boolean; + public mapRoot(): string; + public sourceRoot(): string; + public generateDeclarationFiles(): boolean; + public useCaseSensitiveFileResolution(): boolean; + public gatherDiagnostics(): boolean; + public codepage(): number; + public createFileLog(): boolean; + constructor(propagateEnumConstants: boolean, removeComments: boolean, watch: boolean, noResolve: boolean, allowAutomaticSemicolonInsertion: boolean, noImplicitAny: boolean, noLib: boolean, codeGenTarget: LanguageVersion, moduleGenTarget: ModuleGenTarget, outFileOption: string, outDirOption: string, mapSourceFiles: boolean, mapRoot: string, sourceRoot: string, generateDeclarationFiles: boolean, useCaseSensitiveFileResolution: boolean, gatherDiagnostics: boolean, codepage: number, createFileLog: boolean); + static defaultSettings(): ImmutableCompilationSettings; + static fromCompilationSettings(settings: CompilationSettings): ImmutableCompilationSettings; + public toCompilationSettings(): any; + } +} +declare module TypeScript { + enum PullElementFlags { + None = 0, + Exported = 1, + Private = 2, + Public = 4, + Ambient = 8, + Static = 16, + Optional = 128, + Signature = 2048, + Enum = 4096, + ArrowFunction = 8192, + ClassConstructorVariable = 16384, + InitializedModule = 32768, + InitializedDynamicModule = 65536, + MustCaptureThis = 262144, + DeclaredInAWithBlock = 2097152, + HasReturnStatement = 4194304, + PropertyParameter = 8388608, + IsAnnotatedWithAny = 16777216, + HasDefaultArgs = 33554432, + ConstructorParameter = 67108864, + ImplicitVariable = 118784, + SomeInitializedModule = 102400, + } + function hasModifier(modifiers: PullElementFlags[], flag: PullElementFlags): boolean; + enum PullElementKind { + None = 0, + Global = 0, + Script = 1, + Primitive = 2, + Container = 4, + Class = 8, + Interface = 16, + DynamicModule = 32, + Enum = 64, + TypeAlias = 128, + ObjectLiteral = 256, + Variable = 512, + CatchVariable = 1024, + Parameter = 2048, + Property = 4096, + TypeParameter = 8192, + Function = 16384, + ConstructorMethod = 32768, + Method = 65536, + FunctionExpression = 131072, + GetAccessor = 262144, + SetAccessor = 524288, + CallSignature = 1048576, + ConstructSignature = 2097152, + IndexSignature = 4194304, + ObjectType = 8388608, + FunctionType = 16777216, + ConstructorType = 33554432, + EnumMember = 67108864, + WithBlock = 134217728, + CatchBlock = 268435456, + All = 536869887, + SomeFunction = 1032192, + SomeValue = 68147712, + SomeType = 58728795, + AcceptableAlias = 59753052, + SomeContainer = 164, + SomeSignature = 7340032, + SomeTypeReference = 58720272, + SomeInstantiatableType = 8216, + } +} +declare module TypeScript { + class PullDecl { + public kind: PullElementKind; + public name: string; + private declDisplayName; + public semanticInfoChain: SemanticInfoChain; + public declID: number; + public flags: PullElementFlags; + private declGroups; + private childDecls; + private typeParameters; + private synthesizedValDecl; + private containerDecl; + public childDeclTypeCache: IIndexable; + public childDeclValueCache: IIndexable; + public childDeclNamespaceCache: IIndexable; + public childDeclTypeParameterCache: IIndexable; + constructor(declName: string, displayName: string, kind: PullElementKind, declFlags: PullElementFlags, semanticInfoChain: SemanticInfoChain); + public fileName(): string; + public getParentPath(): PullDecl[]; + public getParentDecl(): PullDecl; + public isExternalModule(): boolean; + public getEnclosingDecl(): PullDecl; + public _getEnclosingDeclFromParentDecl(): PullDecl; + public getDisplayName(): string; + public setSymbol(symbol: PullSymbol): void; + public ensureSymbolIsBound(): void; + public getSymbol(): PullSymbol; + public hasSymbol(): boolean; + public setSignatureSymbol(signatureSymbol: PullSignatureSymbol): void; + public getSignatureSymbol(): PullSignatureSymbol; + public hasSignatureSymbol(): boolean; + public setFlags(flags: PullElementFlags): void; + public setFlag(flags: PullElementFlags): void; + public setValueDecl(valDecl: PullDecl): void; + public getValueDecl(): PullDecl; + public getContainerDecl(): PullDecl; + private getChildDeclCache(declKind); + public addChildDecl(childDecl: PullDecl): void; + public searchChildDecls(declName: string, searchKind: PullElementKind): PullDecl[]; + public getChildDecls(): PullDecl[]; + public getTypeParameters(): PullDecl[]; + public addVariableDeclToGroup(decl: PullDecl): void; + public getVariableDeclGroups(): PullDecl[][]; + public hasBeenBound(): boolean; + public isSynthesized(): boolean; + public ast(): AST; + public isRootDecl(): boolean; + } + class RootPullDecl extends PullDecl { + private _isExternalModule; + private _fileName; + constructor(name: string, fileName: string, kind: PullElementKind, declFlags: PullElementFlags, semanticInfoChain: SemanticInfoChain, isExternalModule: boolean); + public fileName(): string; + public getParentPath(): PullDecl[]; + public getParentDecl(): PullDecl; + public isExternalModule(): boolean; + public getEnclosingDecl(): RootPullDecl; + public isRootDecl(): boolean; + } + class NormalPullDecl extends PullDecl { + private parentDecl; + public _rootDecl: RootPullDecl; + private parentPath; + constructor(declName: string, displayName: string, kind: PullElementKind, declFlags: PullElementFlags, parentDecl: PullDecl, addToParent?: boolean); + public fileName(): string; + public getParentDecl(): PullDecl; + public getParentPath(): PullDecl[]; + public isExternalModule(): boolean; + public getEnclosingDecl(): PullDecl; + public isRootDecl(): boolean; + } + class PullEnumElementDecl extends NormalPullDecl { + public constantValue: number; + constructor(declName: string, displayName: string, parentDecl: PullDecl); + } + class PullFunctionExpressionDecl extends NormalPullDecl { + private functionExpressionName; + constructor(expressionName: string, declFlags: PullElementFlags, parentDecl: PullDecl, displayName?: string); + public getFunctionExpressionName(): string; + } + class PullSynthesizedDecl extends NormalPullDecl { + constructor(declName: string, displayName: string, kind: PullElementKind, declFlags: PullElementFlags, parentDecl: PullDecl, semanticInfoChain: SemanticInfoChain); + public isSynthesized(): boolean; + public fileName(): string; + } + class PullDeclGroup { + public name: string; + private _decls; + constructor(name: string); + public addDecl(decl: PullDecl): void; + public getDecls(): PullDecl[]; + } +} +declare module TypeScript { + var pullSymbolID: number; + var sentinelEmptyArray: any[]; + class PullSymbol { + public pullSymbolID: number; + public name: string; + public kind: PullElementKind; + private _container; + public type: PullTypeSymbol; + private _declarations; + public isResolved: boolean; + public isOptional: boolean; + public inResolution: boolean; + private isSynthesized; + public isVarArg: boolean; + private rootSymbol; + private _enclosingSignature; + private _docComments; + public isPrinting: boolean; + public isAny(): boolean; + public isType(): boolean; + public isTypeReference(): boolean; + public isSignature(): boolean; + public isArrayNamedTypeReference(): boolean; + public isPrimitive(): boolean; + public isAccessor(): boolean; + public isError(): boolean; + public isInterface(): boolean; + public isMethod(): boolean; + public isProperty(): boolean; + public isAlias(): boolean; + public isContainer(): boolean; + constructor(name: string, declKind: PullElementKind); + private findAliasedTypeSymbols(scopeSymbol, skipScopeSymbolAliasesLookIn?, lookIntoOnlyExportedAlias?, aliasSymbols?, visitedScopeDeclarations?); + public getExternalAliasedSymbols(scopeSymbol: PullSymbol): PullTypeAliasSymbol[]; + static _isExternalModuleReferenceAlias(aliasSymbol: PullTypeAliasSymbol): boolean; + private getExportedInternalAliasSymbol(scopeSymbol); + public getAliasSymbolName(scopeSymbol: PullSymbol, aliasNameGetter: (symbol: PullTypeAliasSymbol) => string, aliasPartsNameGetter: (symbol: PullTypeAliasSymbol) => string, skipInternalAlias?: boolean): string; + public _getResolver(): PullTypeResolver; + public _resolveDeclaredSymbol(): PullSymbol; + public getName(scopeSymbol?: PullSymbol, useConstraintInName?: boolean): string; + public getDisplayName(scopeSymbol?: PullSymbol, useConstraintInName?: boolean, skipInternalAliasName?: boolean): string; + public getIsSpecialized(): boolean; + public getRootSymbol(): PullSymbol; + public setRootSymbol(symbol: PullSymbol): void; + public setIsSynthesized(value?: boolean): void; + public getIsSynthesized(): any; + public setEnclosingSignature(signature: PullSignatureSymbol): void; + public getEnclosingSignature(): PullSignatureSymbol; + public addDeclaration(decl: PullDecl): void; + public getDeclarations(): PullDecl[]; + public hasDeclaration(decl: PullDecl): boolean; + public setContainer(containerSymbol: PullTypeSymbol): void; + public getContainer(): PullTypeSymbol; + public setResolved(): void; + public startResolving(): void; + public setUnresolved(): void; + public anyDeclHasFlag(flag: PullElementFlags): boolean; + public allDeclsHaveFlag(flag: PullElementFlags): boolean; + public pathToRoot(): PullSymbol[]; + private static unqualifiedNameReferencesDifferentSymbolInScope(symbol, scopePath, endScopePathIndex); + private findQualifyingSymbolPathInScopeSymbol(scopeSymbol); + public toString(scopeSymbol?: PullSymbol, useConstraintInName?: boolean): string; + public getNamePartForFullName(): string; + public fullName(scopeSymbol?: PullSymbol): string; + public getScopedName(scopeSymbol?: PullSymbol, skipTypeParametersInName?: boolean, useConstraintInName?: boolean, skipInternalAliasName?: boolean): string; + public getScopedNameEx(scopeSymbol?: PullSymbol, skipTypeParametersInName?: boolean, useConstraintInName?: boolean, getPrettyTypeName?: boolean, getTypeParamMarkerInfo?: boolean, skipInternalAliasName?: boolean): MemberName; + public getTypeName(scopeSymbol?: PullSymbol, getPrettyTypeName?: boolean): string; + public getTypeNameEx(scopeSymbol?: PullSymbol, getPrettyTypeName?: boolean): MemberName; + private getTypeNameForFunctionSignature(prefix, scopeSymbol?, getPrettyTypeName?); + public getNameAndTypeName(scopeSymbol?: PullSymbol): string; + public getNameAndTypeNameEx(scopeSymbol?: PullSymbol): MemberName; + static getTypeParameterString(typars: PullTypeSymbol[], scopeSymbol?: PullSymbol, useContraintInName?: boolean): string; + static getTypeParameterStringEx(typeParameters: PullTypeSymbol[], scopeSymbol?: PullSymbol, getTypeParamMarkerInfo?: boolean, useContraintInName?: boolean): MemberNameArray; + static getIsExternallyVisible(symbol: PullSymbol, fromIsExternallyVisibleSymbol: PullSymbol, inIsExternallyVisibleSymbols: PullSymbol[]): boolean; + public isExternallyVisible(inIsExternallyVisibleSymbols?: PullSymbol[]): boolean; + private getDocCommentsOfDecl(decl); + private getDocCommentArray(symbol); + private static getDefaultConstructorSymbolForDocComments(classSymbol); + private getDocCommentText(comments); + private getDocCommentTextValue(comment); + public docComments(useConstructorAsClass?: boolean): string; + private getParameterDocCommentText(param, fncDocComments); + private cleanJSDocComment(content, spacesToRemove?); + private consumeLeadingSpace(line, startIndex, maxSpacesToRemove?); + private isSpaceChar(line, index); + private cleanDocCommentLine(line, jsDocStyleComment, jsDocLineSpaceToRemove?); + } + interface InstantiableSymbol { + getIsSpecialized(): boolean; + getAllowedToReferenceTypeParameters(): PullTypeParameterSymbol[]; + getTypeParameterArgumentMap(): TypeArgumentMap; + } + class PullSignatureSymbol extends PullSymbol implements InstantiableSymbol { + private _isDefinition; + private _memberTypeParameterNameCache; + private _stringConstantOverload; + public parameters: PullSymbol[]; + public _typeParameters: PullTypeParameterSymbol[]; + public returnType: PullTypeSymbol; + public functionType: PullTypeSymbol; + public hasOptionalParam: boolean; + public nonOptionalParamCount: number; + public hasVarArgs: boolean; + private _allowedToReferenceTypeParameters; + private _instantiationCache; + public hasBeenChecked: boolean; + public inWrapCheck: boolean; + public inWrapInfiniteExpandingReferenceCheck: boolean; + private _wrapsTypeParameterCache; + constructor(kind: PullElementKind, _isDefinition?: boolean); + public isDefinition(): boolean; + public isGeneric(): boolean; + public addParameter(parameter: PullSymbol, isOptional?: boolean): void; + public addTypeParameter(typeParameter: PullTypeParameterSymbol): void; + public addTypeParametersFromReturnType(): void; + public getTypeParameters(): PullTypeParameterSymbol[]; + public findTypeParameter(name: string): PullTypeParameterSymbol; + public getTypeParameterArgumentMap(): TypeArgumentMap; + public getAllowedToReferenceTypeParameters(): PullTypeParameterSymbol[]; + public addSpecialization(specializedVersionOfThisSignature: PullSignatureSymbol, typeArgumentMap: TypeArgumentMap): void; + public getSpecialization(typeArgumentMap: TypeArgumentMap): PullSignatureSymbol; + public isStringConstantOverloadSignature(): boolean; + public getParameterTypeAtIndex(iParam: number): PullTypeSymbol; + static getSignatureTypeMemberName(candidateSignature: PullSignatureSymbol, signatures: PullSignatureSymbol[], scopeSymbol: PullSymbol): MemberNameArray; + static getSignaturesTypeNameEx(signatures: PullSignatureSymbol[], prefix: string, shortform: boolean, brackets: boolean, scopeSymbol?: PullSymbol, getPrettyTypeName?: boolean, candidateSignature?: PullSignatureSymbol): MemberName[]; + public toString(scopeSymbol?: PullSymbol, useConstraintInName?: boolean): string; + public getSignatureTypeNameEx(prefix: string, shortform: boolean, brackets: boolean, scopeSymbol?: PullSymbol, getParamMarkerInfo?: boolean, getTypeParamMarkerInfo?: boolean): MemberNameArray; + public forAllParameterTypes(length: number, predicate: (parameterType: PullTypeSymbol, iterationIndex: number) => boolean): boolean; + public forAllCorrespondingParameterTypesInThisAndOtherSignature(otherSignature: PullSignatureSymbol, predicate: (thisSignatureParameterType: PullTypeSymbol, otherSignatureParameterType: PullTypeSymbol, iterationIndex: number) => boolean): boolean; + public wrapsSomeTypeParameter(typeParameterArgumentMap: TypeArgumentMap): boolean; + public getWrappingTypeParameterID(typeParameterArgumentMap: TypeArgumentMap): number; + public getWrappingTypeParameterIDWorker(typeParameterArgumentMap: TypeArgumentMap): number; + public _wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType: PullTypeSymbol, knownWrapMap: IBitMatrix): boolean; + public _wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker(enclosingType: PullTypeSymbol, knownWrapMap: IBitMatrix): boolean; + } + class PullTypeSymbol extends PullSymbol implements InstantiableSymbol { + private _members; + private _enclosedMemberTypes; + private _enclosedMemberContainers; + private _typeParameters; + private _allowedToReferenceTypeParameters; + private _specializedVersionsOfThisType; + private _arrayVersionOfThisType; + private _implementedTypes; + private _extendedTypes; + private _typesThatExplicitlyImplementThisType; + private _typesThatExtendThisType; + private _callSignatures; + private _allCallSignatures; + private _constructSignatures; + private _allConstructSignatures; + private _indexSignatures; + private _allIndexSignatures; + private _allIndexSignaturesOfAugmentedType; + private _memberNameCache; + private _enclosedTypeNameCache; + private _enclosedContainerCache; + private _typeParameterNameCache; + private _containedNonMemberNameCache; + private _containedNonMemberTypeNameCache; + private _containedNonMemberContainerCache; + private _simpleInstantiationCache; + private _complexInstantiationCache; + private _hasGenericSignature; + private _hasGenericMember; + private _hasBaseTypeConflict; + private _knownBaseTypeCount; + private _associatedContainerTypeSymbol; + private _constructorMethod; + private _hasDefaultConstructor; + private _functionSymbol; + private _inMemberTypeNameEx; + public inSymbolPrivacyCheck: boolean; + public inWrapCheck: boolean; + public inWrapInfiniteExpandingReferenceCheck: boolean; + public typeReference: PullTypeReferenceSymbol; + private _widenedType; + private _wrapsTypeParameterCache; + constructor(name: string, kind: PullElementKind); + private _isArrayNamedTypeReference; + public isArrayNamedTypeReference(): boolean; + private computeIsArrayNamedTypeReference(); + public isType(): boolean; + public isClass(): boolean; + public isFunction(): boolean; + public isConstructor(): boolean; + public isTypeParameter(): boolean; + public isTypeVariable(): boolean; + public isError(): boolean; + public isEnum(): boolean; + public getTypeParameterArgumentMap(): TypeArgumentMap; + public isObject(): boolean; + public isFunctionType(): boolean; + public getKnownBaseTypeCount(): number; + public resetKnownBaseTypeCount(): void; + public incrementKnownBaseCount(): void; + public setHasBaseTypeConflict(): void; + public hasBaseTypeConflict(): boolean; + public hasMembers(): boolean; + public setHasGenericSignature(): void; + public getHasGenericSignature(): boolean; + public setHasGenericMember(): void; + public getHasGenericMember(): boolean; + public setAssociatedContainerType(type: PullTypeSymbol): void; + public getAssociatedContainerType(): PullTypeSymbol; + public getArrayType(): PullTypeSymbol; + public getElementType(): PullTypeSymbol; + public setArrayType(arrayType: PullTypeSymbol): void; + public getFunctionSymbol(): PullSymbol; + public setFunctionSymbol(symbol: PullSymbol): void; + public findContainedNonMember(name: string): PullSymbol; + public findContainedNonMemberType(typeName: string, kind?: PullElementKind): PullTypeSymbol; + public findContainedNonMemberContainer(containerName: string, kind?: PullElementKind): PullTypeSymbol; + public addMember(memberSymbol: PullSymbol): void; + public addEnclosedMemberType(enclosedType: PullTypeSymbol): void; + public addEnclosedMemberContainer(enclosedContainer: PullTypeSymbol): void; + public addEnclosedNonMember(enclosedNonMember: PullSymbol): void; + public addEnclosedNonMemberType(enclosedNonMemberType: PullTypeSymbol): void; + public addEnclosedNonMemberContainer(enclosedNonMemberContainer: PullTypeSymbol): void; + public addTypeParameter(typeParameter: PullTypeParameterSymbol): void; + public getMembers(): PullSymbol[]; + public setHasDefaultConstructor(hasOne?: boolean): void; + public getHasDefaultConstructor(): boolean; + public getConstructorMethod(): PullSymbol; + public setConstructorMethod(constructorMethod: PullSymbol): void; + public getTypeParameters(): PullTypeParameterSymbol[]; + public getAllowedToReferenceTypeParameters(): PullTypeParameterSymbol[]; + public isGeneric(): boolean; + private canUseSimpleInstantiationCache(typeArgumentMap); + private getSimpleInstantiationCacheId(typeArgumentMap); + public addSpecialization(specializedVersionOfThisType: PullTypeSymbol, typeArgumentMap: TypeArgumentMap): void; + public getSpecialization(typeArgumentMap: TypeArgumentMap): PullTypeSymbol; + public getKnownSpecializations(): PullTypeSymbol[]; + public getTypeArguments(): PullTypeSymbol[]; + public getTypeArgumentsOrTypeParameters(): PullTypeSymbol[]; + private addCallOrConstructSignaturePrerequisiteBase(signature); + private addCallSignaturePrerequisite(callSignature); + public appendCallSignature(callSignature: PullSignatureSymbol): void; + public insertCallSignatureAtIndex(callSignature: PullSignatureSymbol, index: number): void; + private addConstructSignaturePrerequisite(constructSignature); + public appendConstructSignature(constructSignature: PullSignatureSymbol): void; + public insertConstructSignatureAtIndex(constructSignature: PullSignatureSymbol, index: number): void; + public addIndexSignature(indexSignature: PullSignatureSymbol): void; + public hasOwnCallSignatures(): boolean; + public getOwnCallSignatures(): PullSignatureSymbol[]; + public getCallSignatures(): PullSignatureSymbol[]; + public hasOwnConstructSignatures(): boolean; + public getOwnDeclaredConstructSignatures(): PullSignatureSymbol[]; + public getConstructSignatures(): PullSignatureSymbol[]; + public hasOwnIndexSignatures(): boolean; + public getOwnIndexSignatures(): PullSignatureSymbol[]; + public getIndexSignatures(): PullSignatureSymbol[]; + public getIndexSignaturesOfAugmentedType(resolver: PullTypeResolver, globalFunctionInterface: PullTypeSymbol, globalObjectInterface: PullTypeSymbol): PullSignatureSymbol[]; + private getBaseClassConstructSignatures(baseType); + private getDefaultClassConstructSignature(); + public addImplementedType(implementedType: PullTypeSymbol): void; + public getImplementedTypes(): PullTypeSymbol[]; + public addExtendedType(extendedType: PullTypeSymbol): void; + public getExtendedTypes(): PullTypeSymbol[]; + public addTypeThatExtendsThisType(type: PullTypeSymbol): void; + public getTypesThatExtendThisType(): PullTypeSymbol[]; + public addTypeThatExplicitlyImplementsThisType(type: PullTypeSymbol): void; + public getTypesThatExplicitlyImplementThisType(): PullTypeSymbol[]; + public hasBase(potentialBase: PullTypeSymbol, visited?: PullSymbol[]): boolean; + public isValidBaseKind(baseType: PullTypeSymbol, isExtendedType: boolean): boolean; + public findMember(name: string, lookInParent: boolean): PullSymbol; + public findNestedType(name: string, kind?: PullElementKind): PullTypeSymbol; + public findNestedContainer(name: string, kind?: PullElementKind): PullTypeSymbol; + public getAllMembers(searchDeclKind: PullElementKind, memberVisiblity: GetAllMembersVisiblity): PullSymbol[]; + public findTypeParameter(name: string): PullTypeParameterSymbol; + public setResolved(): void; + public getNamePartForFullName(): string; + public getScopedName(scopeSymbol?: PullSymbol, skipTypeParametersInName?: boolean, useConstraintInName?: boolean, skipInternalAliasName?: boolean): string; + public isNamedTypeSymbol(): boolean; + public toString(scopeSymbol?: PullSymbol, useConstraintInName?: boolean): string; + public getScopedNameEx(scopeSymbol?: PullSymbol, skipTypeParametersInName?: boolean, useConstraintInName?: boolean, getPrettyTypeName?: boolean, getTypeParamMarkerInfo?: boolean, skipInternalAliasName?: boolean, shouldAllowArrayType?: boolean): MemberName; + public hasOnlyOverloadCallSignatures(): boolean; + public getTypeOfSymbol(): PullSymbol; + private getMemberTypeNameEx(topLevel, scopeSymbol?, getPrettyTypeName?); + public getGenerativeTypeClassification(enclosingType: PullTypeSymbol): GenerativeTypeClassification; + public wrapsSomeTypeParameter(typeParameterArgumentMap: CandidateInferenceInfo[]): boolean; + public wrapsSomeTypeParameter(typeParameterArgumentMap: TypeArgumentMap, skipTypeArgumentCheck?: boolean): boolean; + public getWrappingTypeParameterID(typeParameterArgumentMap: TypeArgumentMap, skipTypeArgumentCheck?: boolean): number; + private getWrappingTypeParameterIDFromSignatures(signatures, typeParameterArgumentMap); + private getWrappingTypeParameterIDWorker(typeParameterArgumentMap, skipTypeArgumentCheck); + public wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReference(enclosingType: PullTypeSymbol): boolean; + public _wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceRecurse(enclosingType: PullTypeSymbol, knownWrapMap: IBitMatrix): boolean; + private _wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceWorker(enclosingType, knownWrapMap); + private _wrapsSomeTypeParameterIntoInfinitelyExpandingTypeReferenceStructure(enclosingType, knownWrapMap); + public widenedType(resolver: PullTypeResolver, ast: AST, context: PullTypeResolutionContext): PullTypeSymbol; + } + class PullPrimitiveTypeSymbol extends PullTypeSymbol { + constructor(name: string); + public isAny(): boolean; + public isNull(): boolean; + public isUndefined(): boolean; + public isStringConstant(): boolean; + public setUnresolved(): void; + public getDisplayName(): string; + } + class PullStringConstantTypeSymbol extends PullPrimitiveTypeSymbol { + constructor(name: string); + public isStringConstant(): boolean; + } + class PullErrorTypeSymbol extends PullPrimitiveTypeSymbol { + public _anyType: PullTypeSymbol; + constructor(_anyType: PullTypeSymbol, name: string); + public isError(): boolean; + public _getResolver(): PullTypeResolver; + public getName(scopeSymbol?: PullSymbol, useConstraintInName?: boolean): string; + public getDisplayName(scopeSymbol?: PullSymbol, useConstraintInName?: boolean, skipInternalAliasName?: boolean): string; + public toString(scopeSymbol?: PullSymbol, useConstraintInName?: boolean): string; + } + class PullContainerSymbol extends PullTypeSymbol { + public instanceSymbol: PullSymbol; + private assignedValue; + private assignedType; + private assignedContainer; + constructor(name: string, kind: PullElementKind); + public isContainer(): boolean; + public setInstanceSymbol(symbol: PullSymbol): void; + public getInstanceSymbol(): PullSymbol; + public setExportAssignedValueSymbol(symbol: PullSymbol): void; + public getExportAssignedValueSymbol(): PullSymbol; + public setExportAssignedTypeSymbol(type: PullTypeSymbol): void; + public getExportAssignedTypeSymbol(): PullTypeSymbol; + public setExportAssignedContainerSymbol(container: PullContainerSymbol): void; + public getExportAssignedContainerSymbol(): PullContainerSymbol; + public hasExportAssignment(): boolean; + static usedAsSymbol(containerSymbol: PullSymbol, symbol: PullSymbol): boolean; + public getInstanceType(): PullTypeSymbol; + } + class PullTypeAliasSymbol extends PullTypeSymbol { + private _assignedValue; + private _assignedType; + private _assignedContainer; + private _isUsedAsValue; + private _typeUsedExternally; + private _isUsedInExportAlias; + private retrievingExportAssignment; + private linkedAliasSymbols; + constructor(name: string); + public isUsedInExportedAlias(): boolean; + public typeUsedExternally(): boolean; + public isUsedAsValue(): boolean; + public setTypeUsedExternally(): void; + public setIsUsedInExportedAlias(): void; + public addLinkedAliasSymbol(contingentValueSymbol: PullTypeAliasSymbol): void; + public setIsUsedAsValue(): void; + public assignedValue(): PullSymbol; + public assignedType(): PullTypeSymbol; + public assignedContainer(): PullContainerSymbol; + public isAlias(): boolean; + public isContainer(): boolean; + public setAssignedValueSymbol(symbol: PullSymbol): void; + public getExportAssignedValueSymbol(): PullSymbol; + public setAssignedTypeSymbol(type: PullTypeSymbol): void; + public getExportAssignedTypeSymbol(): PullTypeSymbol; + public setAssignedContainerSymbol(container: PullContainerSymbol): void; + public getExportAssignedContainerSymbol(): PullContainerSymbol; + public getMembers(): PullSymbol[]; + public getCallSignatures(): PullSignatureSymbol[]; + public getConstructSignatures(): PullSignatureSymbol[]; + public getIndexSignatures(): PullSignatureSymbol[]; + public findMember(name: string): PullSymbol; + public findNestedType(name: string): PullTypeSymbol; + public findNestedContainer(name: string): PullTypeSymbol; + public getAllMembers(searchDeclKind: PullElementKind, memberVisibility: GetAllMembersVisiblity): PullSymbol[]; + } + class PullTypeParameterSymbol extends PullTypeSymbol { + private _constraint; + constructor(name: string); + public isTypeParameter(): boolean; + public setConstraint(constraintType: PullTypeSymbol): void; + public getConstraint(): PullTypeSymbol; + public getBaseConstraint(semanticInfoChain: SemanticInfoChain): PullTypeSymbol; + private getConstraintRecursively(visitedTypeParameters); + public getDefaultConstraint(semanticInfoChain: SemanticInfoChain): PullTypeSymbol; + public getCallSignatures(): PullSignatureSymbol[]; + public getConstructSignatures(): PullSignatureSymbol[]; + public getIndexSignatures(): PullSignatureSymbol[]; + public isGeneric(): boolean; + public fullName(scopeSymbol?: PullSymbol): string; + public getName(scopeSymbol?: PullSymbol, useConstraintInName?: boolean): string; + public getDisplayName(scopeSymbol?: PullSymbol, useConstraintInName?: boolean, skipInternalAliasName?: boolean): string; + public isExternallyVisible(inIsExternallyVisibleSymbols?: PullSymbol[]): boolean; + } + class PullAccessorSymbol extends PullSymbol { + private _getterSymbol; + private _setterSymbol; + constructor(name: string); + public isAccessor(): boolean; + public setSetter(setter: PullSymbol): void; + public getSetter(): PullSymbol; + public setGetter(getter: PullSymbol): void; + public getGetter(): PullSymbol; + } + function getIDForTypeSubstitutions(instantiatingType: PullTypeSymbol, typeArgumentMap: TypeArgumentMap): string; + function getIDForTypeSubstitutions(instantiatingSignature: PullSignatureSymbol, typeArgumentMap: TypeArgumentMap): string; + enum GetAllMembersVisiblity { + all = 0, + internallyVisible = 1, + externallyVisible = 2, + } +} +declare module TypeScript { + class EnclosingTypeWalkerState { + public _hasSetEnclosingType: boolean; + public _currentSymbols: PullSymbol[]; + static getDefaultEnclosingTypeWalkerState(): EnclosingTypeWalkerState; + static getNonGenericEnclosingTypeWalkerState(): EnclosingTypeWalkerState; + static getGenericEnclosingTypeWalkerState(genericEnclosingType: PullTypeSymbol): EnclosingTypeWalkerState; + } + class PullTypeEnclosingTypeWalker { + private static _defaultEnclosingTypeWalkerState; + private static _nonGenericEnclosingTypeWalkerState; + private enclosingTypeWalkerState; + constructor(); + private setDefaultTypeWalkerState(); + private setNonGenericEnclosingTypeWalkerState(); + private canSymbolOrDeclBeUsedAsEnclosingTypeHelper(name, kind); + private canDeclBeUsedAsEnclosingType(decl); + private canSymbolBeUsedAsEnclosingType(symbol); + public getEnclosingType(): PullTypeSymbol; + public _canWalkStructure(): boolean; + public _getCurrentSymbol(): PullSymbol; + public getGenerativeClassification(): GenerativeTypeClassification; + private _pushSymbol(symbol); + private _popSymbol(); + private setSymbolAsEnclosingType(type); + private _setEnclosingTypeOfParentDecl(decl, setSignature); + public setEnclosingTypeForSymbol(symbol: PullSymbol): EnclosingTypeWalkerState; + public startWalkingType(symbol: PullTypeSymbol): EnclosingTypeWalkerState; + public endWalkingType(stateWhenStartedWalkingTypes: EnclosingTypeWalkerState): void; + public walkMemberType(memberName: string, resolver: PullTypeResolver): void; + public postWalkMemberType(): void; + public walkSignature(kind: PullElementKind, index: number): void; + public postWalkSignature(): void; + public walkTypeArgument(index: number): void; + public postWalkTypeArgument(): void; + public walkTypeParameterConstraint(index: number): void; + public postWalkTypeParameterConstraint(): void; + public walkReturnType(): void; + public postWalkReturnType(): void; + public walkParameterType(iParam: number): void; + public postWalkParameterType(): void; + public getBothKindOfIndexSignatures(resolver: PullTypeResolver, context: PullTypeResolutionContext, includeAugmentedType: boolean): IndexSignatureInfo; + public walkIndexSignatureReturnType(indexSigInfo: IndexSignatureInfo, useStringIndexSignature: boolean, onlySignature?: boolean): void; + public postWalkIndexSignatureReturnType(onlySignature?: boolean): void; + public resetEnclosingTypeWalkerState(): EnclosingTypeWalkerState; + public setEnclosingTypeWalkerState(enclosingTypeWalkerState: EnclosingTypeWalkerState): void; + } +} +declare module TypeScript { + class CandidateInferenceInfo { + public typeParameter: PullTypeParameterSymbol; + public _inferredTypeAfterFixing: PullTypeSymbol; + public inferenceCandidates: PullTypeSymbol[]; + public addCandidate(candidate: PullTypeSymbol): void; + public isFixed(): boolean; + public fixTypeParameter(resolver: PullTypeResolver, context: PullTypeResolutionContext): void; + } + class TypeArgumentInferenceContext { + public resolver: PullTypeResolver; + public context: PullTypeResolutionContext; + public signatureBeingInferred: PullSignatureSymbol; + public inferenceCache: IBitMatrix; + public candidateCache: CandidateInferenceInfo[]; + constructor(resolver: PullTypeResolver, context: PullTypeResolutionContext, signatureBeingInferred: PullSignatureSymbol); + public alreadyRelatingTypes(objectType: PullTypeSymbol, parameterType: PullTypeSymbol): boolean; + public resetRelationshipCache(): void; + public addInferenceRoot(param: PullTypeParameterSymbol): void; + public getInferenceInfo(param: PullTypeParameterSymbol): CandidateInferenceInfo; + public addCandidateForInference(param: PullTypeParameterSymbol, candidate: PullTypeSymbol): void; + public inferTypeArguments(): PullTypeSymbol[]; + public fixTypeParameter(typeParameter: PullTypeParameterSymbol): void; + public _finalizeInferredTypeArguments(): PullTypeSymbol[]; + public isInvocationInferenceContext(): boolean; + } + class InvocationTypeArgumentInferenceContext extends TypeArgumentInferenceContext { + public argumentASTs: ISeparatedSyntaxList2; + constructor(resolver: PullTypeResolver, context: PullTypeResolutionContext, signatureBeingInferred: PullSignatureSymbol, argumentASTs: ISeparatedSyntaxList2); + public isInvocationInferenceContext(): boolean; + public inferTypeArguments(): PullTypeSymbol[]; + } + class ContextualSignatureInstantiationTypeArgumentInferenceContext extends TypeArgumentInferenceContext { + private contextualSignature; + private shouldFixContextualSignatureParameterTypes; + constructor(resolver: PullTypeResolver, context: PullTypeResolutionContext, signatureBeingInferred: PullSignatureSymbol, contextualSignature: PullSignatureSymbol, shouldFixContextualSignatureParameterTypes: boolean); + public isInvocationInferenceContext(): boolean; + public inferTypeArguments(): PullTypeSymbol[]; + } + class PullContextualTypeContext { + public contextualType: PullTypeSymbol; + public provisional: boolean; + public isInferentiallyTyping: boolean; + public typeArgumentInferenceContext: TypeArgumentInferenceContext; + public provisionallyTypedSymbols: PullSymbol[]; + public hasProvisionalErrors: boolean; + private astSymbolMap; + constructor(contextualType: PullTypeSymbol, provisional: boolean, isInferentiallyTyping: boolean, typeArgumentInferenceContext: TypeArgumentInferenceContext); + public recordProvisionallyTypedSymbol(symbol: PullSymbol): void; + public invalidateProvisionallyTypedSymbols(): void; + public setSymbolForAST(ast: AST, symbol: PullSymbol): void; + public getSymbolForAST(ast: AST): PullSymbol; + } + class PullTypeResolutionContext { + private resolver; + public inTypeCheck: boolean; + public fileName: string; + private contextStack; + private typeCheckedNodes; + private enclosingTypeWalker1; + private enclosingTypeWalker2; + constructor(resolver: PullTypeResolver, inTypeCheck?: boolean, fileName?: string); + public setTypeChecked(ast: AST): void; + public canTypeCheckAST(ast: AST): boolean; + private _pushAnyContextualType(type, provisional, isInferentiallyTyping, argContext); + public pushNewContextualType(type: PullTypeSymbol): void; + public propagateContextualType(type: PullTypeSymbol): void; + public pushInferentialType(type: PullTypeSymbol, typeArgumentInferenceContext: TypeArgumentInferenceContext): void; + public pushProvisionalType(type: PullTypeSymbol): void; + public popAnyContextualType(): PullContextualTypeContext; + public hasProvisionalErrors(): boolean; + public getContextualType(): PullTypeSymbol; + public fixAllTypeParametersReferencedByType(type: PullTypeSymbol, resolver: PullTypeResolver, argContext?: TypeArgumentInferenceContext): PullTypeSymbol; + private getCurrentTypeArgumentInferenceContext(); + public isInferentiallyTyping(): boolean; + public inProvisionalResolution(): boolean; + private inBaseTypeResolution; + public isInBaseTypeResolution(): boolean; + public startBaseTypeResolution(): boolean; + public doneBaseTypeResolution(wasInBaseTypeResolution: boolean): void; + public setTypeInContext(symbol: PullSymbol, type: PullTypeSymbol): void; + public postDiagnostic(diagnostic: Diagnostic): void; + public typeCheck(): boolean; + public setSymbolForAST(ast: AST, symbol: PullSymbol): void; + public getSymbolForAST(ast: AST): PullSymbol; + public startWalkingTypes(symbol1: PullTypeSymbol, symbol2: PullTypeSymbol): { + stateWhenStartedWalkingTypes1: EnclosingTypeWalkerState; + stateWhenStartedWalkingTypes2: EnclosingTypeWalkerState; + }; + public endWalkingTypes(statesWhenStartedWalkingTypes: { + stateWhenStartedWalkingTypes1: EnclosingTypeWalkerState; + stateWhenStartedWalkingTypes2: EnclosingTypeWalkerState; + }): void; + public setEnclosingTypeForSymbols(symbol1: PullSymbol, symbol2: PullSymbol): { + enclosingTypeWalkerState1: EnclosingTypeWalkerState; + enclosingTypeWalkerState2: EnclosingTypeWalkerState; + }; + public walkMemberTypes(memberName: string): void; + public postWalkMemberTypes(): void; + public walkSignatures(kind: PullElementKind, index: number, index2?: number): void; + public postWalkSignatures(): void; + public walkTypeParameterConstraints(index: number): void; + public postWalkTypeParameterConstraints(): void; + public walkTypeArgument(index: number): void; + public postWalkTypeArgument(): void; + public walkReturnTypes(): void; + public postWalkReturnTypes(): void; + public walkParameterTypes(iParam: number): void; + public postWalkParameterTypes(): void; + public getBothKindOfIndexSignatures(includeAugmentedType1: boolean, includeAugmentedType2: boolean): { + indexSigs1: IndexSignatureInfo; + indexSigs2: IndexSignatureInfo; + }; + public walkIndexSignatureReturnTypes(indexSigs: { + indexSigs1: IndexSignatureInfo; + indexSigs2: IndexSignatureInfo; + }, useStringIndexSignature1: boolean, useStringIndexSignature2: boolean, onlySignature?: boolean): void; + public postWalkIndexSignatureReturnTypes(onlySignature?: boolean): void; + public swapEnclosingTypeWalkers(): void; + public oneOfClassificationsIsInfinitelyExpanding(): boolean; + public resetEnclosingTypeWalkerStates(): { + enclosingTypeWalkerState1: EnclosingTypeWalkerState; + enclosingTypeWalkerState2: EnclosingTypeWalkerState; + }; + public setEnclosingTypeWalkerStates(enclosingTypeWalkerStates: { + enclosingTypeWalkerState1: EnclosingTypeWalkerState; + enclosingTypeWalkerState2: EnclosingTypeWalkerState; + }): void; + } +} +declare module TypeScript { + interface IPullTypeCollection { + getLength(): number; + getTypeAtIndex(index: number): PullTypeSymbol; + } + class PullAdditionalCallResolutionData { + public targetSymbol: PullSymbol; + public resolvedSignatures: PullSignatureSymbol[]; + public candidateSignature: PullSignatureSymbol; + public actualParametersContextTypeSymbols: PullTypeSymbol[]; + public diagnosticsFromOverloadResolution: Diagnostic[]; + } + class PullAdditionalObjectLiteralResolutionData { + public membersContextTypeSymbols: PullTypeSymbol[]; + } + interface IndexSignatureInfo { + numericSignature: PullSignatureSymbol; + stringSignature: PullSignatureSymbol; + } + class PullTypeResolver { + private compilationSettings; + public semanticInfoChain: SemanticInfoChain; + private _cachedArrayInterfaceType; + private _cachedNumberInterfaceType; + private _cachedStringInterfaceType; + private _cachedBooleanInterfaceType; + private _cachedObjectInterfaceType; + private _cachedFunctionInterfaceType; + private _cachedIArgumentsInterfaceType; + private _cachedRegExpInterfaceType; + private _cachedAnyTypeArgs; + private typeCheckCallBacks; + private postTypeCheckWorkitems; + private _cachedFunctionArgumentsSymbol; + private assignableCache; + private subtypeCache; + private identicalCache; + private inResolvingOtherDeclsWalker; + constructor(compilationSettings: ImmutableCompilationSettings, semanticInfoChain: SemanticInfoChain); + private cachedArrayInterfaceType(); + public getArrayNamedType(): PullTypeSymbol; + private cachedNumberInterfaceType(); + private cachedStringInterfaceType(); + private cachedBooleanInterfaceType(); + private cachedObjectInterfaceType(); + private cachedFunctionInterfaceType(); + private cachedIArgumentsInterfaceType(); + private cachedRegExpInterfaceType(); + private cachedFunctionArgumentsSymbol(); + private getApparentType(type); + private setTypeChecked(ast, context); + private canTypeCheckAST(ast, context); + private setSymbolForAST(ast, symbol, context); + private getSymbolForAST(ast, context); + public getASTForDecl(decl: PullDecl): AST; + public getNewErrorTypeSymbol(name?: string): PullErrorTypeSymbol; + public getEnclosingDecl(decl: PullDecl): PullDecl; + private getExportedMemberSymbol(symbol, parent); + public _getNamedPropertySymbolOfAugmentedType(symbolName: string, parent: PullTypeSymbol): PullSymbol; + private getNamedPropertySymbol(symbolName, declSearchKind, parent); + private getSymbolFromDeclPath(symbolName, declPath, declSearchKind); + private getVisibleDeclsFromDeclPath(declPath, declSearchKind); + private addFilteredDecls(decls, declSearchKind, result); + public getVisibleDecls(enclosingDecl: PullDecl): PullDecl[]; + public getVisibleContextSymbols(enclosingDecl: PullDecl, context: PullTypeResolutionContext): PullSymbol[]; + public getVisibleMembersFromExpression(expression: AST, enclosingDecl: PullDecl, context: PullTypeResolutionContext): PullSymbol[]; + private isAnyOrEquivalent(type); + private resolveExternalModuleReference(idText, currentFileName); + public resolveDeclaredSymbol(symbol: TSymbol, context?: PullTypeResolutionContext): TSymbol; + private resolveDeclaredSymbolWorker(symbol, context); + private resolveOtherDecl(otherDecl, context); + private resolveOtherDeclarations(astName, context); + private resolveSourceUnit(sourceUnit, context); + private typeCheckSourceUnit(sourceUnit, context); + private verifyUniquenessOfImportNamesInSourceUnit(sourceUnit); + private resolveEnumDeclaration(ast, context); + private typeCheckEnumDeclaration(ast, context); + private postTypeCheckEnumDeclaration(ast, context); + private checkInitializersInEnumDeclarations(decl, context); + private resolveModuleDeclaration(ast, context); + private ensureAllSymbolsAreBound(containerSymbol); + private resolveModuleSymbol(containerSymbol, context, moduleDeclAST, moduleDeclNameAST, sourceUnitAST); + private resolveFirstExportAssignmentStatement(moduleElements, context); + private resolveSingleModuleDeclaration(ast, astName, context); + private typeCheckModuleDeclaration(ast, context); + private typeCheckSingleModuleDeclaration(ast, astName, context); + private verifyUniquenessOfImportNamesInModule(decl); + private checkUniquenessOfImportNames(decls, doesNameExistOutside?); + private scanVariableDeclarationGroups(enclosingDecl, firstDeclHandler, subsequentDeclHandler?); + private postTypeCheckModuleDeclaration(ast, context); + private isTypeRefWithoutTypeArgs(term); + public createInstantiatedType(type: PullTypeSymbol, typeArguments: PullTypeSymbol[]): PullTypeSymbol; + private resolveReferenceTypeDeclaration(classOrInterface, name, heritageClauses, context); + private resolveClassDeclaration(classDeclAST, context); + private typeCheckTypeParametersOfTypeDeclaration(classOrInterface, context); + private typeCheckClassDeclaration(classDeclAST, context); + private postTypeCheckClassDeclaration(classDeclAST, context); + private resolveTypeSymbolSignatures(typeSymbol, context); + private resolveInterfaceDeclaration(interfaceDeclAST, context); + private typeCheckInterfaceDeclaration(interfaceDeclAST, context); + private checkInterfaceDeclForIdenticalTypeParameters(interfaceDeclAST, context); + private checkTypeForDuplicateIndexSignatures(enclosingTypeSymbol); + private filterSymbol(symbol, kind, enclosingDecl, context); + private getMemberSymbolOfKind(symbolName, kind, pullTypeSymbol, enclosingDecl, context); + private resolveIdentifierOfInternalModuleReference(importDecl, identifier, moduleSymbol, enclosingDecl, context); + private resolveModuleReference(importDecl, moduleNameExpr, enclosingDecl, context, declPath); + private resolveInternalModuleReference(importStatementAST, context); + private resolveImportDeclaration(importStatementAST, context); + private typeCheckImportDeclaration(importStatementAST, context); + private postTypeCheckImportDeclaration(importStatementAST, context); + private resolveExportAssignmentStatement(exportAssignmentAST, context); + private resolveAnyFunctionTypeSignature(funcDeclAST, typeParameters, parameterList, returnTypeAnnotation, context); + private resolveFunctionTypeSignatureParameter(argDeclAST, signature, enclosingDecl, context); + private resolveFunctionExpressionParameter(argDeclAST, id, typeExpr, equalsValueClause, contextParam, enclosingDecl, context); + private checkNameForCompilerGeneratedDeclarationCollision(astWithName, isDeclaration, name, context); + private hasRestParameterCodeGen(someFunctionDecl); + private checkArgumentsCollides(ast, context); + private checkIndexOfRestArgumentInitializationCollides(ast, isDeclaration, context); + private checkExternalModuleRequireExportsCollides(ast, name, context); + private resolveObjectTypeTypeReference(objectType, context); + private typeCheckObjectTypeTypeReference(objectType, context); + private resolveTypeAnnotation(typeAnnotation, context); + public resolveTypeReference(typeRef: AST, context: PullTypeResolutionContext): PullTypeSymbol; + private getArrayType(elementType); + private computeTypeReferenceSymbol(term, context); + private genericTypeIsUsedWithoutRequiredTypeArguments(typeSymbol, term, context); + private resolveMemberVariableDeclaration(varDecl, context); + private resolvePropertySignature(varDecl, context); + private resolveVariableDeclarator(varDecl, context); + private resolveParameterList(list, context); + private resolveParameter(parameter, context); + private getEnumTypeSymbol(enumElement, context); + private resolveEnumElement(enumElement, context); + private typeCheckEnumElement(enumElement, context); + private resolveEqualsValueClause(clause, isContextuallyTyped, context); + private resolveVariableDeclaratorOrParameterOrEnumElement(varDeclOrParameter, modifiers, name, typeExpr, init, context); + private resolveAndTypeCheckVariableDeclarationTypeExpr(varDeclOrParameter, name, typeExpr, context); + private resolveAndTypeCheckVariableDeclaratorOrParameterInitExpr(varDeclOrParameter, name, typeExpr, init, context, typeExprSymbol); + private typeCheckPropertySignature(varDecl, context); + private typeCheckMemberVariableDeclaration(varDecl, context); + private typeCheckVariableDeclarator(varDecl, context); + private typeCheckParameter(parameter, context); + private typeCheckVariableDeclaratorOrParameterOrEnumElement(varDeclOrParameter, modifiers, name, typeExpr, init, context); + private isForInVariableDeclarator(ast); + private checkSuperCaptureVariableCollides(superAST, isDeclaration, context); + private checkThisCaptureVariableCollides(_thisAST, isDeclaration, context); + private postTypeCheckVariableDeclaratorOrParameter(varDeclOrParameter, context); + private resolveTypeParameterDeclaration(typeParameterAST, context); + private resolveFirstTypeParameterDeclaration(typeParameterSymbol, context); + private typeCheckTypeParameterDeclaration(typeParameterAST, context); + private resolveConstraint(constraint, context); + private resolveFunctionBodyReturnTypes(funcDeclAST, block, bodyExpression, signature, useContextualType, enclosingDecl, context); + private typeCheckConstructorDeclaration(funcDeclAST, context); + private constructorHasSuperCall(constructorDecl); + private typeCheckFunctionExpression(funcDecl, isContextuallyTyped, context); + private typeCheckCallSignature(funcDecl, context); + private typeCheckConstructSignature(funcDecl, context); + private typeCheckMethodSignature(funcDecl, context); + private typeCheckMemberFunctionDeclaration(funcDecl, context); + private containsSingleThrowStatement(block); + private typeCheckAnyFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameters, returnTypeAnnotation, block, context); + private checkThatNonVoidFunctionHasReturnExpressionOrThrowStatement(functionDecl, returnTypeAnnotation, returnTypeSymbol, block, context); + private typeCheckIndexSignature(funcDeclAST, context); + private postTypeCheckFunctionDeclaration(funcDeclAST, context); + private resolveReturnTypeAnnotationOfFunctionDeclaration(funcDeclAST, returnTypeAnnotation, context); + private resolveMemberFunctionDeclaration(funcDecl, context); + private resolveCallSignature(funcDecl, context); + private resolveConstructSignature(funcDecl, context); + private resolveMethodSignature(funcDecl, context); + private resolveAnyFunctionDeclaration(funcDecl, context); + private resolveFunctionExpression(funcDecl, isContextuallyTyped, context); + private resolveSimpleArrowFunctionExpression(funcDecl, isContextuallyTyped, context); + private resolveParenthesizedArrowFunctionExpression(funcDecl, isContextuallyTyped, context); + private getEnclosingClassDeclaration(ast); + private resolveConstructorDeclaration(funcDeclAST, context); + private resolveIndexMemberDeclaration(ast, context); + private resolveIndexSignature(funcDeclAST, context); + private resolveFunctionDeclaration(funcDeclAST, isStatic, name, typeParameters, parameterList, returnTypeAnnotation, block, context); + private resolveGetterReturnTypeAnnotation(getterFunctionDeclarationAst, enclosingDecl, context); + private resolveSetterArgumentTypeAnnotation(setterFunctionDeclarationAst, enclosingDecl, context); + private resolveAccessorDeclaration(funcDeclAst, context); + private typeCheckAccessorDeclaration(funcDeclAst, context); + private resolveGetAccessorDeclaration(funcDeclAST, parameters, returnTypeAnnotation, block, setterAnnotatedType, context); + private checkIfGetterAndSetterTypeMatch(funcDeclAST, context); + private typeCheckGetAccessorDeclaration(funcDeclAST, context); + static hasSetAccessorParameterTypeAnnotation(setAccessor: SetAccessor): boolean; + private resolveSetAccessorDeclaration(funcDeclAST, parameterList, context); + private typeCheckSetAccessorDeclaration(funcDeclAST, context); + private resolveList(list, context); + private resolveSeparatedList(list, context); + private resolveVoidExpression(ast, context); + private resolveLogicalOperation(ast, context); + private typeCheckLogicalOperation(binex, context); + private resolveLogicalNotExpression(ast, context); + private resolveUnaryArithmeticOperation(ast, context); + private resolvePostfixUnaryExpression(ast, context); + private isAnyOrNumberOrEnum(type); + private typeCheckUnaryArithmeticOperation(unaryExpression, context); + private typeCheckPostfixUnaryExpression(unaryExpression, context); + private resolveBinaryArithmeticExpression(binaryExpression, context); + private typeCheckBinaryArithmeticExpression(binaryExpression, context); + private resolveTypeOfExpression(ast, context); + private resolveThrowStatement(ast, context); + private resolveDeleteExpression(ast, context); + private resolveInstanceOfExpression(ast, context); + private typeCheckInstanceOfExpression(binaryExpression, context); + private resolveCommaExpression(commaExpression, context); + private resolveInExpression(ast, context); + private typeCheckInExpression(binaryExpression, context); + private resolveForStatement(ast, context); + private resolveForInStatement(forInStatement, context); + private typeCheckForInStatement(forInStatement, context); + private resolveWhileStatement(ast, context); + private typeCheckWhileStatement(ast, context); + private resolveDoStatement(ast, context); + private typeCheckDoStatement(ast, context); + private resolveIfStatement(ast, context); + private typeCheckIfStatement(ast, context); + private resolveElseClause(ast, context); + private typeCheckElseClause(ast, context); + private resolveBlock(ast, context); + private resolveVariableStatement(ast, context); + private resolveVariableDeclarationList(ast, context); + private resolveWithStatement(ast, context); + private typeCheckWithStatement(ast, context); + private resolveTryStatement(ast, context); + private typeCheckTryStatement(ast, context); + private resolveCatchClause(ast, context); + private typeCheckCatchClause(ast, context); + private resolveFinallyClause(ast, context); + private typeCheckFinallyClause(ast, context); + private getEnclosingFunctionDeclaration(ast); + private resolveReturnExpression(expression, enclosingFunction, context); + private typeCheckReturnExpression(expression, expressionType, enclosingFunction, context); + private resolveReturnStatement(returnAST, context); + private resolveSwitchStatement(ast, context); + private typeCheckSwitchStatement(ast, context); + private resolveLabeledStatement(ast, context); + private typeCheckLabeledStatement(ast, context); + private labelIsOnContinuableConstruct(statement); + private resolveContinueStatement(ast, context); + private isIterationStatement(ast); + private isAnyFunctionExpressionOrDeclaration(ast); + private inSwitchStatement(ast); + private inIterationStatement(ast, crossFunctions); + private getEnclosingLabels(ast, breakable, crossFunctions); + private typeCheckContinueStatement(ast, context); + private resolveBreakStatement(ast, context); + private typeCheckBreakStatement(ast, context); + public resolveAST(ast: AST, isContextuallyTyped: boolean, context: PullTypeResolutionContext): PullSymbol; + private resolveExpressionAST(ast, isContextuallyOrInferentiallyTyped, context); + private resolveExpressionWorker(ast, isContextuallyTyped, context); + private typeCheckAST(ast, isContextuallyTyped, context); + private processPostTypeCheckWorkItems(context); + private postTypeCheck(ast, context); + private resolveRegularExpressionLiteral(); + private postTypeCheckNameExpression(nameAST, context); + private typeCheckNameExpression(nameAST, context); + private resolveNameExpression(nameAST, context); + private isInEnumDecl(decl); + private getSomeInnermostFunctionScopeDecl(declPath); + private isFromFunctionScope(nameSymbol, functionScopeDecl); + private findConstructorDeclOfEnclosingType(decl); + private checkNameAsPartOfInitializerExpressionForInstanceMemberVariable(nameAST, nameSymbol, context); + private computeNameExpression(nameAST, context); + private getCurrentParameterIndexForFunction(parameter, funcDecl); + private resolveMemberAccessExpression(dottedNameAST, context); + private resolveDottedNameExpression(dottedNameAST, expression, name, context); + private computeDottedNameExpression(expression, name, context, checkSuperPrivateAndStaticAccess); + private computeDottedNameExpressionFromLHS(lhs, expression, name, context, checkSuperPrivateAndStaticAccess); + private resolveTypeNameExpression(nameAST, context); + private computeTypeNameExpression(nameAST, context); + private isInStaticMemberContext(decl); + private isLeftSideOfQualifiedName(ast); + private resolveGenericTypeReference(genericTypeAST, context); + private resolveQualifiedName(dottedNameAST, context); + private isLastNameOfModuleNameModuleReference(ast); + private computeQualifiedName(dottedNameAST, context); + private shouldContextuallyTypeAnyFunctionExpression(functionExpressionAST, typeParameters, parameters, returnTypeAnnotation, context); + private resolveAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context); + private resolveAnyFunctionExpressionParameters(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, isContextuallyTyped, context); + private typeCheckSimpleArrowFunctionExpression(arrowFunction, isContextuallyTyped, context); + private typeCheckParenthesizedArrowFunctionExpression(arrowFunction, isContextuallyTyped, context); + private typeCheckAnyFunctionExpression(funcDeclAST, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, isContextuallyTyped, context); + private resolveThisExpression(thisExpression, context); + private inTypeArgumentList(ast); + private inClassExtendsHeritageClause(ast); + private inTypeQuery(ast); + private inArgumentListOfSuperInvocation(ast); + private inConstructorParameterList(ast); + private isFunctionAccessorOrNonArrowFunctionExpression(decl); + private isFunctionOrNonArrowFunctionExpression(decl); + private typeCheckThisExpression(thisExpression, context, enclosingDecl); + private getContextualClassSymbolForEnclosingDecl(ast, enclosingDecl); + private inStaticMemberVariableDeclaration(ast); + private resolveSuperExpression(ast, context); + private typeCheckSuperExpression(ast, context, enclosingDecl); + private resolveSimplePropertyAssignment(propertyAssignment, isContextuallyTyped, context); + private resolveFunctionPropertyAssignment(funcProp, isContextuallyTyped, context); + private typeCheckFunctionPropertyAssignment(funcProp, isContextuallyTyped, context); + public resolveObjectLiteralExpression(expressionAST: ObjectLiteralExpression, isContextuallyTyped: boolean, context: PullTypeResolutionContext, additionalResults?: PullAdditionalObjectLiteralResolutionData): PullSymbol; + private bindObjectLiteralMembers(objectLiteralDeclaration, objectLiteralTypeSymbol, objectLiteralMembers, isUsingExistingSymbol, pullTypeContext); + private resolveObjectLiteralMembers(objectLiteralDeclaration, objectLiteralTypeSymbol, objectLiteralContextualType, objectLiteralMembers, stringIndexerSignature, numericIndexerSignature, allMemberTypes, allNumericMemberTypes, boundMemberSymbols, isUsingExistingSymbol, pullTypeContext, additionalResults?); + private computeObjectLiteralExpression(objectLitAST, isContextuallyTyped, context, additionalResults?); + private getPropertyAssignmentName(propertyAssignment); + private stampObjectLiteralWithIndexSignature(objectLiteralSymbol, indexerTypeCandidates, contextualIndexSignature, context); + private resolveArrayLiteralExpression(arrayLit, isContextuallyTyped, context); + private computeArrayLiteralExpressionSymbol(arrayLit, isContextuallyTyped, context); + private resolveElementAccessExpression(callEx, context); + private typeCheckElementAccessExpression(callEx, context, symbolAndDiagnostic); + private computeElementAccessExpressionSymbolAndDiagnostic(callEx, context); + private getBothKindsOfIndexSignaturesIncludingAugmentedType(enclosingType, context); + private getBothKindsOfIndexSignaturesExcludingAugmentedType(enclosingType, context); + public _getBothKindsOfIndexSignatures(enclosingType: PullTypeSymbol, context: PullTypeResolutionContext, includeAugmentedType: boolean): IndexSignatureInfo; + public _addUnhiddenSignaturesFromBaseType(derivedTypeSignatures: PullSignatureSymbol[], baseTypeSignatures: PullSignatureSymbol[], signaturesBeingAggregated: PullSignatureSymbol[]): void; + private resolveBinaryAdditionOperation(binaryExpression, context); + private bestCommonTypeOfTwoTypes(type1, type2, context); + private bestCommonTypeOfThreeTypes(type1, type2, type3, context); + private resolveLogicalOrExpression(binex, isContextuallyTyped, context); + private resolveLogicalAndExpression(binex, context); + private computeTypeOfConditionalExpression(leftType, rightType, isContextuallyTyped, context); + private resolveConditionalExpression(trinex, isContextuallyTyped, context); + private conditionExpressionTypesAreValid(leftType, rightType, expressionType, isContextuallyTyped, context); + private resolveParenthesizedExpression(ast, context); + private resolveExpressionStatement(ast, context); + public resolveInvocationExpression(callEx: InvocationExpression, context: PullTypeResolutionContext, additionalResults?: PullAdditionalCallResolutionData): PullSymbol; + private typeCheckInvocationExpression(callEx, context); + private computeInvocationExpressionSymbol(callEx, context, additionalResults); + public resolveObjectCreationExpression(callEx: ObjectCreationExpression, context: PullTypeResolutionContext, additionalResults?: PullAdditionalCallResolutionData): PullSymbol; + private typeCheckObjectCreationExpression(callEx, context); + private postOverloadResolutionDiagnostics(diagnostic, additionalResults, context); + private computeObjectCreationExpressionSymbol(callEx, context, additionalResults); + private instantiateSignatureInContext(signatureAToInstantiate, contextualSignatureB, context, shouldFixContextualSignatureParameterTypes); + private resolveCastExpression(assertionExpression, context); + private typeCheckCastExpression(assertionExpression, context, typeAssertionType); + private resolveAssignmentExpression(binaryExpression, context); + private getInstanceTypeForAssignment(lhs, type, context); + public widenType(type: PullTypeSymbol, ast: AST, context: PullTypeResolutionContext): PullTypeSymbol; + private widenArrayType(type, ast, context); + private widenObjectLiteralType(type, ast, context); + private needsToWidenObjectLiteralType(type, ast, context); + public findBestCommonType(collection: IPullTypeCollection, context: PullTypeResolutionContext, comparisonInfo?: TypeComparisonInfo): PullTypeSymbol; + private typeIsBestCommonTypeCandidate(candidateType, collection, context); + private typesAreIdenticalInEnclosingTypes(t1, t2, context); + private typesAreIdenticalWithNewEnclosingTypes(t1, t2, context); + public typesAreIdentical(t1: PullTypeSymbol, t2: PullTypeSymbol, context: PullTypeResolutionContext): boolean; + private typesAreIdenticalWorker(t1, t2, context); + private propertiesAreIdentical(propertySymbol1, propertySymbol2, context); + private propertiesAreIdenticalWithNewEnclosingTypes(type1, type2, property1, property2, context); + private signatureGroupsAreIdentical(sg1, sg2, context); + private typeParametersAreIdentical(tp1, tp2, context); + private typeParametersAreIdenticalWorker(tp1, tp2, context); + private setTypeParameterIdentity(tp1, tp2, val); + public signaturesAreIdenticalWithNewEnclosingTypes(s1: PullSignatureSymbol, s2: PullSignatureSymbol, context: PullTypeResolutionContext, includingReturnType?: boolean): boolean; + private signaturesAreIdentical(s1, s2, context, includingReturnType?); + public signaturesAreIdenticalWorker(s1: PullSignatureSymbol, s2: PullSignatureSymbol, context: PullTypeResolutionContext, includingReturnType?: boolean): boolean; + private signatureTypeParametersParametersAndReturnTypesAreIdentical(s1, s2, context, includingReturnType?); + public signatureReturnTypesAreIdentical(s1: PullSignatureSymbol, s2: PullSignatureSymbol, context: PullTypeResolutionContext): boolean; + private symbolsShareDeclaration(symbol1, symbol2); + private sourceIsSubtypeOfTarget(source, target, ast, context, comparisonInfo?, isComparingInstantiatedSignatures?); + private sourceMembersAreAssignableToTargetMembers(source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures?); + private sourcePropertyIsAssignableToTargetProperty(source, target, sourceProp, targetProp, ast, context, comparisonInfo, isComparingInstantiatedSignatures?); + private sourceCallSignaturesAreAssignableToTargetCallSignatures(source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures?); + private sourceConstructSignaturesAreAssignableToTargetConstructSignatures(source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures?); + private sourceIndexSignaturesAreAssignableToTargetIndexSignatures(source, target, ast, context, comparisonInfo, isComparingInstantiatedSignatures?); + private typeIsAssignableToFunction(source, ast, context); + private signatureIsAssignableToTarget(s1, s2, ast, context, comparisonInfo?, isComparingInstantiatedSignatures?); + private sourceIsAssignableToTarget(source, target, ast, context, comparisonInfo?, isComparingInstantiatedSignatures?); + private sourceIsAssignableToTargetWithNewEnclosingTypes(source, target, ast, context, comparisonInfo?, isComparingInstantiatedSignatures?); + private getSymbolForRelationshipCheck(symbol); + private sourceIsRelatableToTargetInEnclosingTypes(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + private sourceIsRelatableToTargetWithNewEnclosingTypes(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + private sourceIsRelatableToTargetInCache(source, target, comparisonCache, comparisonInfo); + private sourceIsRelatableToTarget(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + private isSourceTypeParameterConstrainedToTargetTypeParameter(source, target); + private sourceIsRelatableToTargetWorker(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + private sourceMembersAreRelatableToTargetMembers(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + private infinitelyExpandingSourceTypeIsRelatableToTargetType(sourceType, targetType, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + private infinitelyExpandingTypesAreIdentical(sourceType, targetType, context); + private sourcePropertyIsRelatableToTargetProperty(source, target, sourceProp, targetProp, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + private sourceCallSignaturesAreRelatableToTargetCallSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + private sourceConstructSignaturesAreRelatableToTargetConstructSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + private sourceIndexSignaturesAreRelatableToTargetIndexSignatures(source, target, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + private signatureGroupIsRelatableToTarget(source, target, sourceSG, targetSG, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + private signatureIsRelatableToTarget(sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + private signatureIsRelatableToTargetWorker(sourceSig, targetSig, assignableTo, comparisonCache, ast, context, comparisonInfo, isComparingInstantiatedSignatures); + private resolveOverloads(application, group, haveTypeArgumentsAtCallSite, context, diagnostics); + private getCallTargetErrorSpanAST(callEx); + private overloadHasCorrectArity(signature, args); + private overloadIsApplicable(signature, args, context, comparisonInfo); + private overloadIsApplicableForArgument(paramType, arg, argIndex, context, comparisonInfo); + private overloadIsApplicableForAnyFunctionExpressionArgument(paramType, arg, typeParameters, parameters, returnTypeAnnotation, block, bodyExpression, argIndex, context, comparisonInfo); + private overloadIsApplicableForObjectLiteralArgument(paramType, arg, argIndex, context, comparisonInfo); + private overloadIsApplicableForArrayLiteralArgument(paramType, arg, argIndex, context, comparisonInfo); + private overloadIsApplicableForOtherArgument(paramType, arg, argIndex, context, comparisonInfo); + private overloadIsApplicableForArgumentHelper(paramType, argSym, argumentIndex, comparisonInfo, arg, context); + private inferArgumentTypesForSignature(argContext, comparisonInfo, context); + private typeParametersAreInScopeAtArgumentList(typeParameters, args); + private relateTypeToTypeParametersInEnclosingType(expressionType, parameterType, argContext, context); + public relateTypeToTypeParametersWithNewEnclosingTypes(expressionType: PullTypeSymbol, parameterType: PullTypeSymbol, argContext: TypeArgumentInferenceContext, context: PullTypeResolutionContext): void; + public relateTypeToTypeParameters(expressionType: PullTypeSymbol, parameterType: PullTypeSymbol, argContext: TypeArgumentInferenceContext, context: PullTypeResolutionContext): void; + private relateTypeArgumentsOfTypeToTypeParameters(expressionType, parameterType, argContext, context); + private relateInifinitelyExpandingTypeToTypeParameters(expressionType, parameterType, argContext, context); + private relateFunctionSignatureToTypeParameters(expressionSignature, parameterSignature, argContext, context); + private relateObjectTypeToTypeParameters(objectType, parameterType, argContext, context); + private relateSignatureGroupToTypeParameters(argumentSignatures, parameterSignatures, signatureKind, argContext, context); + private alterPotentialGenericFunctionTypeToInstantiatedFunctionTypeForTypeArgumentInference(expressionSymbol, context); + private isFunctionTypeWithExactlyOneCallSignatureAndNoOtherMembers(type, callSignatureShouldBeGeneric); + public instantiateTypeToAny(typeToSpecialize: PullTypeSymbol, context: PullTypeResolutionContext): PullTypeSymbol; + public instantiateSignatureToAny(signature: PullSignatureSymbol): PullSignatureSymbol; + static globalTypeCheckPhase: number; + static typeCheck(compilationSettings: ImmutableCompilationSettings, semanticInfoChain: SemanticInfoChain, document: Document): void; + private validateVariableDeclarationGroups(enclosingDecl, context); + private typeCheckFunctionOverloads(funcDecl, context, signature?, allSignatures?); + private checkSymbolPrivacy(declSymbol, symbol, privacyErrorReporter); + private checkTypePrivacyOfSignatures(declSymbol, signatures, privacyErrorReporter); + private typeParameterOfTypeDeclarationPrivacyErrorReporter(classOrInterface, typeParameterAST, typeParameter, symbol, context); + private baseListPrivacyErrorReporter(classOrInterface, declSymbol, baseAst, isExtendedType, symbol, context); + private variablePrivacyErrorReporter(declAST, declSymbol, symbol, context); + private checkFunctionTypePrivacy(funcDeclAST, isStatic, typeParameters, parameters, returnTypeAnnotation, block, context); + private functionTypeArgumentArgumentTypePrivacyErrorReporter(declAST, isStatic, typeParameterAST, typeParameter, symbol, context); + private functionArgumentTypePrivacyErrorReporter(declAST, isStatic, parameters, argIndex, paramSymbol, symbol, context); + private functionReturnTypePrivacyErrorReporter(declAST, isStatic, returnTypeAnnotation, block, funcReturnType, symbol, context); + private enclosingClassIsDerived(classDecl); + private isSuperInvocationExpression(ast); + private isSuperInvocationExpressionStatement(node); + private getFirstStatementOfBlockOrNull(block); + private superCallMustBeFirstStatementInConstructor(constructorDecl); + private checkForThisCaptureInArrowFunction(expression); + private typeCheckMembersAgainstIndexer(containerType, containerTypeDecl, context); + private determineRelevantIndexerForMember(member, numberIndexSignature, stringIndexSignature); + private reportErrorThatMemberIsNotSubtypeOfIndexer(member, indexSignature, astForError, context, comparisonInfo); + private typeCheckIfTypeMemberPropertyOkToOverride(typeSymbol, extendedType, typeMember, extendedTypeMember, enclosingDecl, comparisonInfo); + private typeCheckIfTypeExtendsType(classOrInterface, name, typeSymbol, extendedType, enclosingDecl, context); + private typeCheckIfClassImplementsType(classDecl, classSymbol, implementedType, enclosingDecl, context); + private computeValueSymbolFromAST(valueDeclAST, context); + private hasClassTypeSymbolConflictAsValue(baseDeclAST, typeSymbol, enclosingDecl, context); + private typeCheckBase(classOrInterface, name, typeSymbol, baseDeclAST, isExtendedType, enclosingDecl, context); + private typeCheckBases(classOrInterface, name, heritageClauses, typeSymbol, enclosingDecl, context); + private checkTypeCompatibilityBetweenBases(name, typeSymbol, context); + private checkNamedPropertyIdentityBetweenBases(interfaceName, interfaceSymbol, baseTypeSymbol, inheritedMembersMap, context); + private checkIndexSignatureIdentityBetweenBases(interfaceName, interfaceSymbol, baseTypeSymbol, allInheritedSignatures, derivedTypeHasOwnNumberSignature, derivedTypeHasOwnStringSignature, context); + private checkInheritedMembersAgainstInheritedIndexSignatures(interfaceName, interfaceSymbol, inheritedIndexSignatures, inheritedMembers, context); + private checkThatInheritedNumberSignatureIsSubtypeOfInheritedStringSignature(interfaceName, interfaceSymbol, inheritedIndexSignatures, context); + private checkAssignability(ast, source, target, context); + private isReference(ast, astSymbol); + private checkForSuperMemberAccess(expression, name, resolvedName, context); + private getEnclosingDeclForAST(ast); + private getEnclosingSymbolForAST(ast); + private checkForPrivateMemberAccess(name, expressionType, resolvedName, context); + public instantiateType(type: PullTypeSymbol, typeParameterArgumentMap: TypeArgumentMap): PullTypeSymbol; + public instantiateTypeParameter(typeParameter: PullTypeParameterSymbol, typeParameterArgumentMap: TypeArgumentMap): PullTypeParameterSymbol; + public instantiateSignature(signature: PullSignatureSymbol, typeParameterArgumentMap: TypeArgumentMap): PullSignatureSymbol; + } + class TypeComparisonInfo { + public onlyCaptureFirstError: boolean; + public flags: TypeRelationshipFlags; + public message: string; + public stringConstantVal: AST; + private indent; + constructor(sourceComparisonInfo?: TypeComparisonInfo, useSameIndent?: boolean); + private indentString(); + public addMessage(message: string): void; + } + function getPropertyAssignmentNameTextFromIdentifier(identifier: AST): { + actualText: string; + memberName: string; + }; + function isTypesOnlyLocation(ast: AST): boolean; +} +declare module TypeScript { + var declCacheHit: number; + var declCacheMiss: number; + var symbolCacheHit: number; + var symbolCacheMiss: number; + class SemanticInfoChain { + private compiler; + private logger; + private documents; + private fileNameToDocument; + public anyTypeDecl: PullDecl; + public booleanTypeDecl: PullDecl; + public numberTypeDecl: PullDecl; + public stringTypeDecl: PullDecl; + public nullTypeDecl: PullDecl; + public undefinedTypeDecl: PullDecl; + public voidTypeDecl: PullDecl; + public undefinedValueDecl: PullDecl; + public anyTypeSymbol: PullPrimitiveTypeSymbol; + public booleanTypeSymbol: PullPrimitiveTypeSymbol; + public numberTypeSymbol: PullPrimitiveTypeSymbol; + public stringTypeSymbol: PullPrimitiveTypeSymbol; + public nullTypeSymbol: PullPrimitiveTypeSymbol; + public undefinedTypeSymbol: PullPrimitiveTypeSymbol; + public voidTypeSymbol: PullPrimitiveTypeSymbol; + public undefinedValueSymbol: PullSymbol; + public emptyTypeSymbol: PullTypeSymbol; + private astSymbolMap; + private astAliasSymbolMap; + private astCallResolutionDataMap; + private declSymbolMap; + private declSignatureSymbolMap; + private declCache; + private symbolCache; + private fileNameToDiagnostics; + private _binder; + private _resolver; + private _topLevelDecls; + private _fileNames; + constructor(compiler: TypeScriptCompiler, logger: ILogger); + public getDocument(fileName: string): Document; + public lineMap(fileName: string): LineMap; + public fileNames(): string[]; + private bindPrimitiveSymbol(decl, newSymbol); + private addPrimitiveTypeSymbol(decl); + private addPrimitiveValueSymbol(decl, type); + private resetGlobalSymbols(); + public addDocument(document: Document): void; + public removeDocument(fileName: string): void; + private getDeclPathCacheID(declPath, declKind); + public findTopLevelSymbol(name: string, kind: PullElementKind, doNotGoPastThisDecl: PullDecl): PullSymbol; + private findTopLevelSymbolInDecl(topLevelDecl, name, kind, doNotGoPastThisDecl); + public findExternalModule(id: string): PullContainerSymbol; + public findAmbientExternalModuleInGlobalContext(id: string): PullContainerSymbol; + public findDecls(declPath: string[], declKind: PullElementKind): PullDecl[]; + public findDeclsFromPath(declPath: PullDecl[], declKind: PullElementKind): PullDecl[]; + public findSymbol(declPath: string[], declType: PullElementKind): PullSymbol; + public cacheGlobalSymbol(symbol: PullSymbol, kind: PullElementKind): void; + public invalidate(oldSettings?: ImmutableCompilationSettings, newSettings?: ImmutableCompilationSettings): void; + private settingsChangeAffectsSyntax(before, after); + public setSymbolForAST(ast: AST, symbol: PullSymbol): void; + public getSymbolForAST(ast: AST): PullSymbol; + public setAliasSymbolForAST(ast: AST, symbol: PullTypeAliasSymbol): void; + public getAliasSymbolForAST(ast: AST): PullTypeAliasSymbol; + public getCallResolutionDataForAST(ast: AST): PullAdditionalCallResolutionData; + public setCallResolutionDataForAST(ast: AST, callResolutionData: PullAdditionalCallResolutionData): void; + public setSymbolForDecl(decl: PullDecl, symbol: PullSymbol): void; + public getSymbolForDecl(decl: PullDecl): PullSymbol; + public setSignatureSymbolForDecl(decl: PullDecl, signatureSymbol: PullSignatureSymbol): void; + public getSignatureSymbolForDecl(decl: PullDecl): PullSignatureSymbol; + public addDiagnostic(diagnostic: Diagnostic): void; + public getDiagnostics(fileName: string): Diagnostic[]; + public getBinder(): PullSymbolBinder; + public getResolver(): PullTypeResolver; + public addSyntheticIndexSignature(containingDecl: PullDecl, containingSymbol: PullTypeSymbol, ast: AST, indexParamName: string, indexParamType: PullTypeSymbol, returnType: PullTypeSymbol): void; + public getDeclForAST(ast: AST): PullDecl; + public getEnclosingDecl(ast: AST): PullDecl; + public setDeclForAST(ast: AST, decl: PullDecl): void; + public getASTForDecl(decl: PullDecl): AST; + public setASTForDecl(decl: PullDecl, ast: AST): void; + public topLevelDecl(fileName: string): PullDecl; + public topLevelDecls(): PullDecl[]; + public addDiagnosticFromAST(ast: AST, diagnosticKey: string, _arguments?: any[], additionalLocations?: Location[]): void; + public diagnosticFromAST(ast: AST, diagnosticKey: string, _arguments?: any[], additionalLocations?: Location[]): Diagnostic; + public locationFromAST(ast: AST): Location; + public duplicateIdentifierDiagnosticFromAST(ast: AST, identifier: string, additionalLocationAST: AST): Diagnostic; + public addDuplicateIdentifierDiagnosticFromAST(ast: AST, identifier: string, additionalLocationAST: AST): void; + } +} +declare module TypeScript { + module DeclarationCreator { + function create(document: Document, semanticInfoChain: SemanticInfoChain, compilationSettings: ImmutableCompilationSettings): PullDecl; + } +} +declare module TypeScript { + class PullSymbolBinder { + private semanticInfoChain; + private declsBeingBound; + private inBindingOtherDeclsWalker; + constructor(semanticInfoChain: SemanticInfoChain); + private getParent(decl, returnInstanceType?); + private findDeclsInContext(startingDecl, declKind, searchGlobally); + private getExistingSymbol(decl, searchKind, parent); + private checkThatExportsMatch(decl, prevSymbol, reportError?); + private getIndexForInsertingSignatureAtEndOfEnclosingDeclInSignatureList(signature, currentSignatures); + private bindEnumDeclarationToPullSymbol(enumContainerDecl); + private bindEnumIndexerDeclsToPullSymbols(enumContainerSymbol); + private findExistingVariableSymbolForModuleValueDecl(decl); + private bindModuleDeclarationToPullSymbol(moduleContainerDecl); + private bindImportDeclaration(importDeclaration); + private ensurePriorDeclarationsAreBound(container, currentDecl); + private bindClassDeclarationToPullSymbol(classDecl); + private bindInterfaceDeclarationToPullSymbol(interfaceDecl); + private bindObjectTypeDeclarationToPullSymbol(objectDecl); + private bindConstructorTypeDeclarationToPullSymbol(constructorTypeDeclaration); + private bindVariableDeclarationToPullSymbol(variableDeclaration); + private bindCatchVariableToPullSymbol(variableDeclaration); + private bindEnumMemberDeclarationToPullSymbol(propertyDeclaration); + private bindPropertyDeclarationToPullSymbol(propertyDeclaration); + private bindParameterSymbols(functionDeclaration, parameterList, funcType, signatureSymbol); + private bindFunctionDeclarationToPullSymbol(functionDeclaration); + private bindFunctionExpressionToPullSymbol(functionExpressionDeclaration); + private bindFunctionTypeDeclarationToPullSymbol(functionTypeDeclaration); + private bindMethodDeclarationToPullSymbol(methodDeclaration); + private bindStaticPrototypePropertyOfClass(classAST, classTypeSymbol, constructorTypeSymbol); + private bindConstructorDeclarationToPullSymbol(constructorDeclaration); + private bindConstructSignatureDeclarationToPullSymbol(constructSignatureDeclaration); + private bindCallSignatureDeclarationToPullSymbol(callSignatureDeclaration); + private bindIndexSignatureDeclarationToPullSymbol(indexSignatureDeclaration); + private bindGetAccessorDeclarationToPullSymbol(getAccessorDeclaration); + private bindSetAccessorDeclarationToPullSymbol(setAccessorDeclaration); + private getDeclsToBind(decl); + private shouldBindDeclaration(decl); + public bindDeclToPullSymbol(decl: PullDecl): void; + private bindAllDeclsToPullSymbol(askedDecl); + private bindSingleDeclToPullSymbol(decl); + } +} +declare module TypeScript { + module PullHelpers { + function diagnosticFromDecl(decl: PullDecl, diagnosticKey: string, _arguments?: any[], additionalLocations?: Location[]): Diagnostic; + function resolveDeclaredSymbolToUseType(symbol: PullSymbol): void; + interface SignatureInfoForFuncDecl { + signature: PullSignatureSymbol; + allSignatures: PullSignatureSymbol[]; + } + function getSignatureForFuncDecl(functionDecl: PullDecl): { + signature: PullSignatureSymbol; + allSignatures: PullSignatureSymbol[]; + }; + function getAccessorSymbol(getterOrSetter: AST, semanticInfoChain: SemanticInfoChain): PullAccessorSymbol; + function getGetterAndSetterFunction(funcDecl: AST, semanticInfoChain: SemanticInfoChain): { + getter: GetAccessor; + setter: SetAccessor; + }; + function symbolIsEnum(source: PullSymbol): boolean; + function symbolIsModule(symbol: PullSymbol): boolean; + function isNameNumeric(name: string): boolean; + function typeSymbolsAreIdentical(a: PullTypeSymbol, b: PullTypeSymbol): boolean; + function getRootType(type: PullTypeSymbol): PullTypeSymbol; + function isSymbolLocal(symbol: PullSymbol): boolean; + function isExportedSymbolInClodule(symbol: PullSymbol): boolean; + function isSymbolDeclaredInScopeChain(symbol: PullSymbol, scopeSymbol: PullSymbol): boolean; + interface PullTypeSymbolStructureWalker { + memberSymbolWalk(memberSymbol: PullSymbol): boolean; + callSignatureWalk(signatureSymbol: PullSignatureSymbol): boolean; + constructSignatureWalk(signatureSymbol: PullSignatureSymbol): boolean; + indexSignatureWalk(signatureSymbol: PullSignatureSymbol): boolean; + signatureParameterWalk(parameterSymbol: PullSymbol): boolean; + signatureReturnTypeWalk(returnType: PullTypeSymbol): boolean; + } + function walkPullTypeSymbolStructure(typeSymbol: PullTypeSymbol, walker: PullTypeSymbolStructureWalker): void; + class OtherPullDeclsWalker { + private currentlyWalkingOtherDecls; + public walkOtherPullDecls(currentDecl: PullDecl, otherDecls: PullDecl[], callBack: (otherDecl: PullDecl) => void): void; + } + } +} +declare module TypeScript { + class WrapsTypeParameterCache { + private _wrapsTypeParameterCache; + public getWrapsTypeParameter(typeParameterArgumentMap: TypeArgumentMap): number; + public setWrapsTypeParameter(typeParameterArgumentMap: TypeArgumentMap, wrappingTypeParameterID: number): void; + } + module PullInstantiationHelpers { + class MutableTypeArgumentMap { + public typeParameterArgumentMap: TypeArgumentMap; + public createdDuplicateTypeArgumentMap: boolean; + constructor(typeParameterArgumentMap: TypeArgumentMap); + public ensureTypeArgumentCopy(): void; + } + function instantiateTypeArgument(resolver: PullTypeResolver, symbol: InstantiableSymbol, mutableTypeParameterMap: MutableTypeArgumentMap): void; + function cleanUpTypeArgumentMap(symbol: InstantiableSymbol, mutableTypeArgumentMap: MutableTypeArgumentMap): void; + function getAllowedToReferenceTypeParametersFromDecl(decl: PullDecl): PullTypeParameterSymbol[]; + function createTypeParameterArgumentMap(typeParameters: PullTypeParameterSymbol[], typeArguments: PullTypeSymbol[]): TypeArgumentMap; + function updateTypeParameterArgumentMap(typeParameters: PullTypeParameterSymbol[], typeArguments: PullTypeSymbol[], typeParameterArgumentMap: TypeArgumentMap): TypeArgumentMap; + function updateMutableTypeParameterArgumentMap(typeParameters: PullTypeParameterSymbol[], typeArguments: PullTypeSymbol[], mutableMap: MutableTypeArgumentMap): void; + function twoTypesAreInstantiationsOfSameNamedGenericType(type1: PullTypeSymbol, type2: PullTypeSymbol): boolean; + } +} +declare module TypeScript { + var fileResolutionTime: number; + var fileResolutionIOTime: number; + var fileResolutionScanImportsTime: number; + var fileResolutionImportFileSearchTime: number; + var fileResolutionGetDefaultLibraryTime: number; + var sourceCharactersCompiled: number; + var syntaxTreeParseTime: number; + var syntaxDiagnosticsTime: number; + var astTranslationTime: number; + var typeCheckTime: number; + var compilerResolvePathTime: number; + var compilerDirectoryNameTime: number; + var compilerDirectoryExistsTime: number; + var compilerFileExistsTime: number; + var emitTime: number; + var emitWriteFileTime: number; + var declarationEmitTime: number; + var declarationEmitIsExternallyVisibleTime: number; + var declarationEmitTypeSignatureTime: number; + var declarationEmitGetBoundDeclTypeTime: number; + var declarationEmitIsOverloadedCallSignatureTime: number; + var declarationEmitFunctionDeclarationGetSymbolTime: number; + var declarationEmitGetBaseTypeTime: number; + var declarationEmitGetAccessorFunctionTime: number; + var declarationEmitGetTypeParameterSymbolTime: number; + var declarationEmitGetImportDeclarationSymbolTime: number; + var ioHostResolvePathTime: number; + var ioHostDirectoryNameTime: number; + var ioHostCreateDirectoryStructureTime: number; + var ioHostWriteFileTime: number; + interface PullSymbolInfo { + symbol: PullSymbol; + aliasSymbol: PullTypeAliasSymbol; + ast: AST; + enclosingScopeSymbol: PullSymbol; + } + interface PullCallSymbolInfo { + targetSymbol: PullSymbol; + resolvedSignatures: PullSignatureSymbol[]; + candidateSignature: PullSignatureSymbol; + isConstructorCall: boolean; + ast: AST; + enclosingScopeSymbol: PullSymbol; + } + interface PullVisibleSymbolsInfo { + symbols: PullSymbol[]; + enclosingScopeSymbol: PullSymbol; + } + enum EmitOutputResult { + Succeeded = 0, + FailedBecauseOfSyntaxErrors = 1, + FailedBecauseOfCompilerOptionsErrors = 2, + FailedToGenerateDeclarationsBecauseOfSemanticErrors = 3, + } + class EmitOutput { + public outputFiles: OutputFile[]; + public emitOutputResult: EmitOutputResult; + constructor(emitOutputResult?: EmitOutputResult); + } + enum OutputFileType { + JavaScript = 0, + SourceMap = 1, + Declaration = 2, + } + class OutputFile { + public name: string; + public writeByteOrderMark: boolean; + public text: string; + public fileType: OutputFileType; + public sourceMapEntries: SourceMapEntry[]; + constructor(name: string, writeByteOrderMark: boolean, text: string, fileType: OutputFileType, sourceMapEntries?: SourceMapEntry[]); + } + class CompileResult { + public diagnostics: Diagnostic[]; + public outputFiles: OutputFile[]; + static fromDiagnostics(diagnostics: Diagnostic[]): CompileResult; + static fromOutputFiles(outputFiles: OutputFile[]): CompileResult; + } + class TypeScriptCompiler { + public logger: ILogger; + private _settings; + private semanticInfoChain; + constructor(logger?: ILogger, _settings?: ImmutableCompilationSettings); + public compilationSettings(): ImmutableCompilationSettings; + public setCompilationSettings(newSettings: ImmutableCompilationSettings): void; + public getDocument(fileName: string): Document; + public cleanupSemanticCache(): void; + public addFile(fileName: string, scriptSnapshot: IScriptSnapshot, byteOrderMark: ByteOrderMark, version: number, isOpen: boolean, referencedFiles?: string[]): void; + public updateFile(fileName: string, scriptSnapshot: IScriptSnapshot, version: number, isOpen: boolean, textChangeRange: TextChangeRange): void; + public removeFile(fileName: string): void; + public mapOutputFileName(document: Document, emitOptions: EmitOptions, extensionChanger: (fname: string, wholeFileNameReplaced: boolean) => string): string; + private writeByteOrderMarkForDocument(document); + static mapToDTSFileName(fileName: string, wholeFileNameReplaced: boolean): string; + public _shouldEmit(document: Document): boolean; + public _shouldEmitDeclarations(document: Document): boolean; + private emitDocumentDeclarationsWorker(document, emitOptions, declarationEmitter?); + public _emitDocumentDeclarations(document: Document, emitOptions: EmitOptions, onSingleFileEmitComplete: (files: OutputFile) => void, sharedEmitter: DeclarationEmitter): DeclarationEmitter; + public emitAllDeclarations(resolvePath: (path: string) => string): EmitOutput; + public emitDeclarations(fileName: string, resolvePath: (path: string) => string): EmitOutput; + public canEmitDeclarations(fileName: string): boolean; + static mapToFileNameExtension(extension: string, fileName: string, wholeFileNameReplaced: boolean): string; + static mapToJSFileName(fileName: string, wholeFileNameReplaced: boolean): string; + private emitDocumentWorker(document, emitOptions, emitter?); + public _emitDocument(document: Document, emitOptions: EmitOptions, onSingleFileEmitComplete: (files: OutputFile[]) => void, sharedEmitter: Emitter): Emitter; + public emitAll(resolvePath: (path: string) => string): EmitOutput; + public emit(fileName: string, resolvePath: (path: string) => string): EmitOutput; + public compile(resolvePath: (path: string) => string, continueOnDiagnostics?: boolean): Iterator; + public getSyntacticDiagnostics(fileName: string): Diagnostic[]; + private getSyntaxTree(fileName); + private getSourceUnit(fileName); + public getSemanticDiagnostics(fileName: string): Diagnostic[]; + public getCompilerOptionsDiagnostics(resolvePath: (path: string) => string): Diagnostic[]; + public resolveAllFiles(): void; + public getSymbolOfDeclaration(decl: PullDecl): PullSymbol; + private extractResolutionContextFromAST(resolver, ast, document, propagateContextualTypes); + private extractResolutionContextForVariable(inContextuallyTypedAssignment, propagateContextualTypes, resolver, resolutionContext, enclosingDecl, assigningAST, init); + private getASTPath(ast); + public pullGetSymbolInformationFromAST(ast: AST, document: Document): PullSymbolInfo; + public pullGetCallInformationFromAST(ast: AST, document: Document): PullCallSymbolInfo; + public pullGetVisibleMemberSymbolsFromAST(ast: AST, document: Document): PullVisibleSymbolsInfo; + public pullGetVisibleDeclsFromAST(ast: AST, document: Document): PullDecl[]; + public pullGetContextualMembersFromAST(ast: AST, document: Document): PullVisibleSymbolsInfo; + public pullGetDeclInformation(decl: PullDecl, ast: AST, document: Document): PullSymbolInfo; + public topLevelDeclaration(fileName: string): PullDecl; + public getDeclForAST(ast: AST): PullDecl; + public fileNames(): string[]; + public topLevelDecl(fileName: string): PullDecl; + private static getLocationText(location, resolvePath); + static getFullDiagnosticText(diagnostic: Diagnostic, resolvePath: (path: string) => string): string; + } + function compareDataObjects(dst: any, src: any): boolean; +} +declare module TypeScript { + enum GenerativeTypeClassification { + Unknown = 0, + Open = 1, + Closed = 2, + InfinitelyExpanding = 3, + } + interface TypeArgumentMap { + [n: number]: PullTypeSymbol; + } + class PullTypeReferenceSymbol extends PullTypeSymbol { + public referencedTypeSymbol: PullTypeSymbol; + static createTypeReference(type: PullTypeSymbol): PullTypeReferenceSymbol; + constructor(referencedTypeSymbol: PullTypeSymbol); + public isTypeReference(): boolean; + public isResolved: boolean; + public setResolved(): void; + public setUnresolved(): void; + public invalidate(): void; + public ensureReferencedTypeIsResolved(): void; + public getReferencedTypeSymbol(): PullTypeSymbol; + public _getResolver(): PullTypeResolver; + public hasMembers(): boolean; + public setAssociatedContainerType(type: PullTypeSymbol): void; + public getAssociatedContainerType(): PullTypeSymbol; + public getFunctionSymbol(): PullSymbol; + public setFunctionSymbol(symbol: PullSymbol): void; + public addContainedNonMember(nonMember: PullSymbol): void; + public findContainedNonMemberContainer(containerName: string, kind?: PullElementKind): PullTypeSymbol; + public addMember(memberSymbol: PullSymbol): void; + public addEnclosedMemberType(enclosedType: PullTypeSymbol): void; + public addEnclosedMemberContainer(enclosedContainer: PullTypeSymbol): void; + public addEnclosedNonMember(enclosedNonMember: PullSymbol): void; + public addEnclosedNonMemberType(enclosedNonMemberType: PullTypeSymbol): void; + public addEnclosedNonMemberContainer(enclosedNonMemberContainer: PullTypeSymbol): void; + public addTypeParameter(typeParameter: PullTypeParameterSymbol): void; + public addConstructorTypeParameter(typeParameter: PullTypeParameterSymbol): void; + public findContainedNonMember(name: string): PullSymbol; + public findContainedNonMemberType(typeName: string, kind?: PullElementKind): PullTypeSymbol; + public getMembers(): PullSymbol[]; + public setHasDefaultConstructor(hasOne?: boolean): void; + public getHasDefaultConstructor(): boolean; + public getConstructorMethod(): PullSymbol; + public setConstructorMethod(constructorMethod: PullSymbol): void; + public getTypeParameters(): PullTypeParameterSymbol[]; + public isGeneric(): boolean; + public addSpecialization(specializedVersionOfThisType: PullTypeSymbol, substitutingTypes: PullTypeSymbol[]): void; + public getSpecialization(substitutingTypes: PullTypeSymbol[]): PullTypeSymbol; + public getKnownSpecializations(): PullTypeSymbol[]; + public getTypeArguments(): PullTypeSymbol[]; + public getTypeArgumentsOrTypeParameters(): PullTypeSymbol[]; + public appendCallSignature(callSignature: PullSignatureSymbol): void; + public insertCallSignatureAtIndex(callSignature: PullSignatureSymbol, index: number): void; + public appendConstructSignature(callSignature: PullSignatureSymbol): void; + public insertConstructSignatureAtIndex(callSignature: PullSignatureSymbol, index: number): void; + public addIndexSignature(indexSignature: PullSignatureSymbol): void; + public hasOwnCallSignatures(): boolean; + public getCallSignatures(): PullSignatureSymbol[]; + public hasOwnConstructSignatures(): boolean; + public getConstructSignatures(): PullSignatureSymbol[]; + public hasOwnIndexSignatures(): boolean; + public getIndexSignatures(): PullSignatureSymbol[]; + public addImplementedType(implementedType: PullTypeSymbol): void; + public getImplementedTypes(): PullTypeSymbol[]; + public addExtendedType(extendedType: PullTypeSymbol): void; + public getExtendedTypes(): PullTypeSymbol[]; + public addTypeThatExtendsThisType(type: PullTypeSymbol): void; + public getTypesThatExtendThisType(): PullTypeSymbol[]; + public addTypeThatExplicitlyImplementsThisType(type: PullTypeSymbol): void; + public getTypesThatExplicitlyImplementThisType(): PullTypeSymbol[]; + public isValidBaseKind(baseType: PullTypeSymbol, isExtendedType: boolean): boolean; + public findMember(name: string, lookInParent?: boolean): PullSymbol; + public findNestedType(name: string, kind?: PullElementKind): PullTypeSymbol; + public findNestedContainer(name: string, kind?: PullElementKind): PullTypeSymbol; + public getAllMembers(searchDeclKind: PullElementKind, memberVisiblity: GetAllMembersVisiblity): PullSymbol[]; + public findTypeParameter(name: string): PullTypeParameterSymbol; + public hasOnlyOverloadCallSignatures(): boolean; + } + var nSpecializationsCreated: number; + var nSpecializedSignaturesCreated: number; + var nSpecializedTypeParameterCreated: number; + class PullInstantiatedTypeReferenceSymbol extends PullTypeReferenceSymbol { + public referencedTypeSymbol: PullTypeSymbol; + private _typeParameterArgumentMap; + public isInstanceReferenceType: boolean; + private _instantiatedMembers; + private _allInstantiatedMemberNameCache; + private _instantiatedMemberNameCache; + private _instantiatedCallSignatures; + private _instantiatedConstructSignatures; + private _instantiatedIndexSignatures; + private _typeArgumentReferences; + private _instantiatedConstructorMethod; + private _instantiatedAssociatedContainerType; + private _isArray; + public getIsSpecialized(): boolean; + private _generativeTypeClassification; + public getGenerativeTypeClassification(enclosingType: PullTypeSymbol): GenerativeTypeClassification; + public isArrayNamedTypeReference(): boolean; + public getElementType(): PullTypeSymbol; + public getReferencedTypeSymbol(): PullTypeSymbol; + static create(resolver: PullTypeResolver, type: PullTypeSymbol, typeParameterArgumentMap: TypeArgumentMap): PullInstantiatedTypeReferenceSymbol; + constructor(referencedTypeSymbol: PullTypeSymbol, _typeParameterArgumentMap: TypeArgumentMap, isInstanceReferenceType: boolean); + public isGeneric(): boolean; + public getTypeParameterArgumentMap(): TypeArgumentMap; + public getTypeArguments(): PullTypeSymbol[]; + public getTypeArgumentsOrTypeParameters(): PullTypeSymbol[]; + private populateInstantiatedMemberFromReferencedMember(referencedMember); + public getMembers(): PullSymbol[]; + public findMember(name: string, lookInParent?: boolean): PullSymbol; + public getAllMembers(searchDeclKind: PullElementKind, memberVisiblity: GetAllMembersVisiblity): PullSymbol[]; + public getConstructorMethod(): PullSymbol; + public getAssociatedContainerType(): PullTypeSymbol; + public getCallSignatures(): PullSignatureSymbol[]; + public getConstructSignatures(): PullSignatureSymbol[]; + public getIndexSignatures(): PullSignatureSymbol[]; + } + class PullInstantiatedSignatureSymbol extends PullSignatureSymbol { + private _typeParameterArgumentMap; + public getTypeParameterArgumentMap(): TypeArgumentMap; + constructor(rootSignature: PullSignatureSymbol, _typeParameterArgumentMap: TypeArgumentMap); + public getIsSpecialized(): boolean; + public _getResolver(): PullTypeResolver; + public getTypeParameters(): PullTypeParameterSymbol[]; + public getAllowedToReferenceTypeParameters(): PullTypeParameterSymbol[]; + } + class PullInstantiatedTypeParameterSymbol extends PullTypeParameterSymbol { + constructor(rootTypeParameter: PullTypeSymbol, constraintType: PullTypeSymbol); + public _getResolver(): PullTypeResolver; + } +} +declare module TypeScript { + class SyntaxTreeToAstVisitor implements ISyntaxVisitor { + private fileName; + public lineMap: LineMap; + private compilationSettings; + public position: number; + public previousTokenTrailingComments: Comment[]; + constructor(fileName: string, lineMap: LineMap, compilationSettings: ImmutableCompilationSettings); + static visit(syntaxTree: SyntaxTree, fileName: string, compilationSettings: ImmutableCompilationSettings, incrementalAST: boolean): SourceUnit; + public movePast(element: ISyntaxElement): void; + private moveTo(element1, element2); + private setCommentsAndSpan(ast, fullStart, node); + public createTokenSpan(fullStart: number, element: ISyntaxToken): ASTSpan; + public setSpan(span: AST, fullStart: number, element: ISyntaxElement, firstToken?: ISyntaxToken, lastToken?: ISyntaxToken): void; + public setSpanExplicit(span: IASTSpan, start: number, end: number): void; + public visitSyntaxList(node: ISyntaxList): ISyntaxList2; + public visitSeparatedSyntaxList(list: ISeparatedSyntaxList): ISeparatedSyntaxList2; + private convertComment(trivia, commentStartPosition, hasTrailingNewLine); + private convertComments(triviaList, commentStartPosition); + private mergeComments(comments1, comments2); + private convertTokenLeadingComments(token, commentStartPosition); + private convertTokenTrailingComments(token, commentStartPosition); + private convertNodeTrailingComments(node, lastToken, nodeStart); + private visitIdentifier(token); + public visitToken(token: ISyntaxToken): IASTToken; + public visitTokenWorker(token: ISyntaxToken): IASTToken; + public visitSourceUnit(node: SourceUnitSyntax): SourceUnit; + public visitExternalModuleReference(node: ExternalModuleReferenceSyntax): ExternalModuleReference; + public visitModuleNameModuleReference(node: ModuleNameModuleReferenceSyntax): ModuleNameModuleReference; + public visitClassDeclaration(node: ClassDeclarationSyntax): ClassDeclaration; + private visitModifiers(modifiers); + public visitInterfaceDeclaration(node: InterfaceDeclarationSyntax): InterfaceDeclaration; + public visitHeritageClause(node: HeritageClauseSyntax): HeritageClause; + public visitModuleDeclaration(node: ModuleDeclarationSyntax): ModuleDeclaration; + public visitFunctionDeclaration(node: FunctionDeclarationSyntax): FunctionDeclaration; + public visitEnumDeclaration(node: EnumDeclarationSyntax): EnumDeclaration; + public visitEnumElement(node: EnumElementSyntax): EnumElement; + public visitImportDeclaration(node: ImportDeclarationSyntax): ImportDeclaration; + public visitExportAssignment(node: ExportAssignmentSyntax): ExportAssignment; + public visitVariableStatement(node: VariableStatementSyntax): VariableStatement; + public visitVariableDeclaration(node: VariableDeclarationSyntax): VariableDeclaration; + public visitVariableDeclarator(node: VariableDeclaratorSyntax): VariableDeclarator; + public visitEqualsValueClause(node: EqualsValueClauseSyntax): EqualsValueClause; + public visitPrefixUnaryExpression(node: PrefixUnaryExpressionSyntax): PrefixUnaryExpression; + public visitArrayLiteralExpression(node: ArrayLiteralExpressionSyntax): ArrayLiteralExpression; + public visitOmittedExpression(node: OmittedExpressionSyntax): OmittedExpression; + public visitParenthesizedExpression(node: ParenthesizedExpressionSyntax): ParenthesizedExpression; + public visitSimpleArrowFunctionExpression(node: SimpleArrowFunctionExpressionSyntax): SimpleArrowFunctionExpression; + public visitParenthesizedArrowFunctionExpression(node: ParenthesizedArrowFunctionExpressionSyntax): ParenthesizedArrowFunctionExpression; + public visitType(type: ITypeSyntax): AST; + public visitTypeQuery(node: TypeQuerySyntax): TypeQuery; + public visitQualifiedName(node: QualifiedNameSyntax): QualifiedName; + public visitTypeArgumentList(node: TypeArgumentListSyntax): TypeArgumentList; + public visitConstructorType(node: ConstructorTypeSyntax): ConstructorType; + public visitFunctionType(node: FunctionTypeSyntax): FunctionType; + public visitObjectType(node: ObjectTypeSyntax): ObjectType; + public visitArrayType(node: ArrayTypeSyntax): ArrayType; + public visitGenericType(node: GenericTypeSyntax): GenericType; + public visitTypeAnnotation(node: TypeAnnotationSyntax): TypeAnnotation; + public visitBlock(node: BlockSyntax): Block; + public visitParameter(node: ParameterSyntax): Parameter; + public visitMemberAccessExpression(node: MemberAccessExpressionSyntax): MemberAccessExpression; + public visitPostfixUnaryExpression(node: PostfixUnaryExpressionSyntax): PostfixUnaryExpression; + public visitElementAccessExpression(node: ElementAccessExpressionSyntax): ElementAccessExpression; + public visitInvocationExpression(node: InvocationExpressionSyntax): InvocationExpression; + public visitArgumentList(node: ArgumentListSyntax): ArgumentList; + public visitBinaryExpression(node: BinaryExpressionSyntax): BinaryExpression; + public visitConditionalExpression(node: ConditionalExpressionSyntax): ConditionalExpression; + public visitConstructSignature(node: ConstructSignatureSyntax): ConstructSignature; + public visitMethodSignature(node: MethodSignatureSyntax): MethodSignature; + public visitIndexSignature(node: IndexSignatureSyntax): IndexSignature; + public visitPropertySignature(node: PropertySignatureSyntax): PropertySignature; + public visitParameterList(node: ParameterListSyntax): ParameterList; + public visitCallSignature(node: CallSignatureSyntax): CallSignature; + public visitTypeParameterList(node: TypeParameterListSyntax): TypeParameterList; + public visitTypeParameter(node: TypeParameterSyntax): TypeParameter; + public visitConstraint(node: ConstraintSyntax): Constraint; + public visitIfStatement(node: IfStatementSyntax): IfStatement; + public visitElseClause(node: ElseClauseSyntax): ElseClause; + public visitExpressionStatement(node: ExpressionStatementSyntax): ExpressionStatement; + public visitConstructorDeclaration(node: ConstructorDeclarationSyntax): ConstructorDeclaration; + public visitIndexMemberDeclaration(node: IndexMemberDeclarationSyntax): IndexMemberDeclaration; + public visitMemberFunctionDeclaration(node: MemberFunctionDeclarationSyntax): MemberFunctionDeclaration; + public visitGetAccessor(node: GetAccessorSyntax): GetAccessor; + public visitSetAccessor(node: SetAccessorSyntax): SetAccessor; + public visitMemberVariableDeclaration(node: MemberVariableDeclarationSyntax): MemberVariableDeclaration; + public visitThrowStatement(node: ThrowStatementSyntax): ThrowStatement; + public visitReturnStatement(node: ReturnStatementSyntax): ReturnStatement; + public visitObjectCreationExpression(node: ObjectCreationExpressionSyntax): ObjectCreationExpression; + public visitSwitchStatement(node: SwitchStatementSyntax): SwitchStatement; + public visitCaseSwitchClause(node: CaseSwitchClauseSyntax): CaseSwitchClause; + public visitDefaultSwitchClause(node: DefaultSwitchClauseSyntax): DefaultSwitchClause; + public visitBreakStatement(node: BreakStatementSyntax): BreakStatement; + public visitContinueStatement(node: ContinueStatementSyntax): ContinueStatement; + public visitForStatement(node: ForStatementSyntax): ForStatement; + public visitForInStatement(node: ForInStatementSyntax): ForInStatement; + public visitWhileStatement(node: WhileStatementSyntax): WhileStatement; + public visitWithStatement(node: WithStatementSyntax): WithStatement; + public visitCastExpression(node: CastExpressionSyntax): CastExpression; + public visitObjectLiteralExpression(node: ObjectLiteralExpressionSyntax): ObjectLiteralExpression; + public visitSimplePropertyAssignment(node: SimplePropertyAssignmentSyntax): SimplePropertyAssignment; + public visitFunctionPropertyAssignment(node: FunctionPropertyAssignmentSyntax): FunctionPropertyAssignment; + public visitFunctionExpression(node: FunctionExpressionSyntax): FunctionExpression; + public visitEmptyStatement(node: EmptyStatementSyntax): EmptyStatement; + public visitTryStatement(node: TryStatementSyntax): TryStatement; + public visitCatchClause(node: CatchClauseSyntax): CatchClause; + public visitFinallyClause(node: FinallyClauseSyntax): FinallyClause; + public visitLabeledStatement(node: LabeledStatementSyntax): LabeledStatement; + public visitDoStatement(node: DoStatementSyntax): DoStatement; + public visitTypeOfExpression(node: TypeOfExpressionSyntax): TypeOfExpression; + public visitDeleteExpression(node: DeleteExpressionSyntax): DeleteExpression; + public visitVoidExpression(node: VoidExpressionSyntax): VoidExpression; + public visitDebuggerStatement(node: DebuggerStatementSyntax): DebuggerStatement; + } +} +declare module TypeScript { + interface IASTSpan { + _start: number; + _end: number; + start(): number; + end(): number; + } + class ASTSpan implements IASTSpan { + public _start: number; + public _end: number; + constructor(_start: number, _end: number); + public start(): number; + public end(): number; + } + function structuralEqualsNotIncludingPosition(ast1: AST, ast2: AST): boolean; + function structuralEqualsIncludingPosition(ast1: AST, ast2: AST): boolean; + class AST implements IASTSpan { + public parent: AST; + public _start: number; + public _end: number; + public _trailingTriviaWidth: number; + private _astID; + private _preComments; + private _postComments; + constructor(); + public syntaxID(): number; + public start(): number; + public end(): number; + public trailingTriviaWidth(): number; + public fileName(): string; + public kind(): SyntaxKind; + public preComments(): Comment[]; + public postComments(): Comment[]; + public setPreComments(comments: Comment[]): void; + public setPostComments(comments: Comment[]): void; + public width(): number; + public structuralEquals(ast: AST, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + interface IASTToken extends AST { + text(): string; + valueText(): string; + } + class ISyntaxList2 extends AST { + private _fileName; + private members; + constructor(_fileName: string, members: AST[]); + public childCount(): number; + public childAt(index: number): AST; + public fileName(): string; + public kind(): SyntaxKind; + public firstOrDefault(func: (v: AST, index: number) => boolean): AST; + public lastOrDefault(func: (v: AST, index: number) => boolean): AST; + public any(func: (v: AST) => boolean): boolean; + public structuralEquals(ast: ISyntaxList2, includingPosition: boolean): boolean; + } + class ISeparatedSyntaxList2 extends AST { + private _fileName; + private members; + private _separatorCount; + constructor(_fileName: string, members: AST[], _separatorCount: number); + public nonSeparatorCount(): number; + public separatorCount(): number; + public nonSeparatorAt(index: number): AST; + public nonSeparatorIndexOf(ast: AST): number; + public fileName(): string; + public kind(): SyntaxKind; + public structuralEquals(ast: ISeparatedSyntaxList2, includingPosition: boolean): boolean; + } + class SourceUnit extends AST { + public moduleElements: ISyntaxList2; + public endOfFileTokenLeadingComments: Comment[]; + private _fileName; + constructor(moduleElements: ISyntaxList2, endOfFileTokenLeadingComments: Comment[], _fileName: string); + public fileName(): string; + public kind(): SyntaxKind; + public structuralEquals(ast: SourceUnit, includingPosition: boolean): boolean; + } + class Identifier extends AST implements IASTToken { + private _text; + private _valueText; + constructor(_text: string); + public text(): string; + public valueText(): string; + public kind(): SyntaxKind; + public structuralEquals(ast: Identifier, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class LiteralExpression extends AST { + private _nodeType; + private _text; + private _valueText; + constructor(_nodeType: SyntaxKind, _text: string, _valueText: string); + public text(): string; + public valueText(): string; + public kind(): SyntaxKind; + public structuralEquals(ast: ParenthesizedExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class ThisExpression extends AST implements IASTToken { + private _text; + private _valueText; + constructor(_text: string, _valueText: string); + public text(): string; + public valueText(): string; + public kind(): SyntaxKind; + public structuralEquals(ast: ParenthesizedExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class SuperExpression extends AST implements IASTToken { + private _text; + private _valueText; + constructor(_text: string, _valueText: string); + public text(): string; + public valueText(): string; + public kind(): SyntaxKind; + public structuralEquals(ast: ParenthesizedExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class NumericLiteral extends AST implements IASTToken { + private _value; + private _text; + private _valueText; + constructor(_value: number, _text: string, _valueText: string); + public text(): string; + public valueText(): string; + public value(): any; + public kind(): SyntaxKind; + public structuralEquals(ast: NumericLiteral, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class RegularExpressionLiteral extends AST implements IASTToken { + private _text; + private _valueText; + constructor(_text: string, _valueText: string); + public text(): string; + public valueText(): string; + public kind(): SyntaxKind; + public isExpression(): boolean; + } + class StringLiteral extends AST implements IASTToken { + private _text; + private _valueText; + constructor(_text: string, _valueText: string); + public text(): string; + public valueText(): string; + public kind(): SyntaxKind; + public structuralEquals(ast: StringLiteral, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class TypeAnnotation extends AST { + public type: AST; + constructor(type: AST); + public kind(): SyntaxKind; + } + class BuiltInType extends AST implements IASTToken { + private _nodeType; + private _text; + private _valueText; + constructor(_nodeType: SyntaxKind, _text: string, _valueText: string); + public text(): string; + public valueText(): string; + public kind(): SyntaxKind; + } + class ExternalModuleReference extends AST { + public stringLiteral: StringLiteral; + constructor(stringLiteral: StringLiteral); + public kind(): SyntaxKind; + } + class ModuleNameModuleReference extends AST { + public moduleName: AST; + constructor(moduleName: AST); + public kind(): SyntaxKind; + } + class ImportDeclaration extends AST { + public modifiers: PullElementFlags[]; + public identifier: Identifier; + public moduleReference: AST; + constructor(modifiers: PullElementFlags[], identifier: Identifier, moduleReference: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: ImportDeclaration, includingPosition: boolean): boolean; + } + class ExportAssignment extends AST { + public identifier: Identifier; + constructor(identifier: Identifier); + public kind(): SyntaxKind; + public structuralEquals(ast: ExportAssignment, includingPosition: boolean): boolean; + } + class TypeParameterList extends AST { + public typeParameters: ISeparatedSyntaxList2; + constructor(typeParameters: ISeparatedSyntaxList2); + public kind(): SyntaxKind; + } + class ClassDeclaration extends AST { + public modifiers: PullElementFlags[]; + public identifier: Identifier; + public typeParameterList: TypeParameterList; + public heritageClauses: ISyntaxList2; + public classElements: ISyntaxList2; + public closeBraceToken: ASTSpan; + constructor(modifiers: PullElementFlags[], identifier: Identifier, typeParameterList: TypeParameterList, heritageClauses: ISyntaxList2, classElements: ISyntaxList2, closeBraceToken: ASTSpan); + public kind(): SyntaxKind; + public structuralEquals(ast: ClassDeclaration, includingPosition: boolean): boolean; + } + class InterfaceDeclaration extends AST { + public modifiers: PullElementFlags[]; + public identifier: Identifier; + public typeParameterList: TypeParameterList; + public heritageClauses: ISyntaxList2; + public body: ObjectType; + constructor(modifiers: PullElementFlags[], identifier: Identifier, typeParameterList: TypeParameterList, heritageClauses: ISyntaxList2, body: ObjectType); + public kind(): SyntaxKind; + public structuralEquals(ast: InterfaceDeclaration, includingPosition: boolean): boolean; + } + class HeritageClause extends AST { + private _nodeType; + public typeNames: ISeparatedSyntaxList2; + constructor(_nodeType: SyntaxKind, typeNames: ISeparatedSyntaxList2); + public kind(): SyntaxKind; + public structuralEquals(ast: HeritageClause, includingPosition: boolean): boolean; + } + class ModuleDeclaration extends AST { + public modifiers: PullElementFlags[]; + public name: AST; + public stringLiteral: StringLiteral; + public moduleElements: ISyntaxList2; + public endingToken: ASTSpan; + constructor(modifiers: PullElementFlags[], name: AST, stringLiteral: StringLiteral, moduleElements: ISyntaxList2, endingToken: ASTSpan); + public kind(): SyntaxKind; + public structuralEquals(ast: ModuleDeclaration, includingPosition: boolean): boolean; + } + class FunctionDeclaration extends AST { + public modifiers: PullElementFlags[]; + public identifier: Identifier; + public callSignature: CallSignature; + public block: Block; + constructor(modifiers: PullElementFlags[], identifier: Identifier, callSignature: CallSignature, block: Block); + public kind(): SyntaxKind; + public structuralEquals(ast: FunctionDeclaration, includingPosition: boolean): boolean; + } + class VariableStatement extends AST { + public modifiers: PullElementFlags[]; + public declaration: VariableDeclaration; + constructor(modifiers: PullElementFlags[], declaration: VariableDeclaration); + public kind(): SyntaxKind; + public structuralEquals(ast: VariableStatement, includingPosition: boolean): boolean; + } + class VariableDeclaration extends AST { + public declarators: ISeparatedSyntaxList2; + constructor(declarators: ISeparatedSyntaxList2); + public kind(): SyntaxKind; + public structuralEquals(ast: VariableDeclaration, includingPosition: boolean): boolean; + } + class VariableDeclarator extends AST { + public propertyName: IASTToken; + public typeAnnotation: TypeAnnotation; + public equalsValueClause: EqualsValueClause; + constructor(propertyName: IASTToken, typeAnnotation: TypeAnnotation, equalsValueClause: EqualsValueClause); + public kind(): SyntaxKind; + } + class EqualsValueClause extends AST { + public value: AST; + constructor(value: AST); + public kind(): SyntaxKind; + } + class PrefixUnaryExpression extends AST { + private _nodeType; + public operand: AST; + constructor(_nodeType: SyntaxKind, operand: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: PrefixUnaryExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class ArrayLiteralExpression extends AST { + public expressions: ISeparatedSyntaxList2; + constructor(expressions: ISeparatedSyntaxList2); + public kind(): SyntaxKind; + public structuralEquals(ast: ArrayLiteralExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class OmittedExpression extends AST { + public kind(): SyntaxKind; + public structuralEquals(ast: CatchClause, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class ParenthesizedExpression extends AST { + public openParenTrailingComments: Comment[]; + public expression: AST; + constructor(openParenTrailingComments: Comment[], expression: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: ParenthesizedExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + interface ICallExpression extends IASTSpan { + expression: AST; + argumentList: ArgumentList; + } + class SimpleArrowFunctionExpression extends AST { + public identifier: Identifier; + public block: Block; + public expression: AST; + constructor(identifier: Identifier, block: Block, expression: AST); + public kind(): SyntaxKind; + public isExpression(): boolean; + } + class ParenthesizedArrowFunctionExpression extends AST { + public callSignature: CallSignature; + public block: Block; + public expression: AST; + constructor(callSignature: CallSignature, block: Block, expression: AST); + public kind(): SyntaxKind; + public isExpression(): boolean; + } + class QualifiedName extends AST { + public left: AST; + public right: Identifier; + constructor(left: AST, right: Identifier); + public kind(): SyntaxKind; + public structuralEquals(ast: QualifiedName, includingPosition: boolean): boolean; + } + class ParameterList extends AST { + public openParenTrailingComments: Comment[]; + public parameters: ISeparatedSyntaxList2; + constructor(openParenTrailingComments: Comment[], parameters: ISeparatedSyntaxList2); + public kind(): SyntaxKind; + } + class ConstructorType extends AST { + public typeParameterList: TypeParameterList; + public parameterList: ParameterList; + public type: AST; + constructor(typeParameterList: TypeParameterList, parameterList: ParameterList, type: AST); + public kind(): SyntaxKind; + } + class FunctionType extends AST { + public typeParameterList: TypeParameterList; + public parameterList: ParameterList; + public type: AST; + constructor(typeParameterList: TypeParameterList, parameterList: ParameterList, type: AST); + public kind(): SyntaxKind; + } + class ObjectType extends AST { + public typeMembers: ISeparatedSyntaxList2; + constructor(typeMembers: ISeparatedSyntaxList2); + public kind(): SyntaxKind; + public structuralEquals(ast: ObjectType, includingPosition: boolean): boolean; + } + class ArrayType extends AST { + public type: AST; + constructor(type: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: ArrayType, includingPosition: boolean): boolean; + } + class TypeArgumentList extends AST { + public typeArguments: ISeparatedSyntaxList2; + constructor(typeArguments: ISeparatedSyntaxList2); + public kind(): SyntaxKind; + } + class GenericType extends AST { + public name: AST; + public typeArgumentList: TypeArgumentList; + constructor(name: AST, typeArgumentList: TypeArgumentList); + public kind(): SyntaxKind; + public structuralEquals(ast: GenericType, includingPosition: boolean): boolean; + } + class TypeQuery extends AST { + public name: AST; + constructor(name: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: TypeQuery, includingPosition: boolean): boolean; + } + class Block extends AST { + public statements: ISyntaxList2; + public closeBraceLeadingComments: Comment[]; + public closeBraceToken: IASTSpan; + constructor(statements: ISyntaxList2, closeBraceLeadingComments: Comment[], closeBraceToken: IASTSpan); + public kind(): SyntaxKind; + public structuralEquals(ast: Block, includingPosition: boolean): boolean; + } + class Parameter extends AST { + public dotDotDotToken: ASTSpan; + public modifiers: PullElementFlags[]; + public identifier: Identifier; + public questionToken: ASTSpan; + public typeAnnotation: TypeAnnotation; + public equalsValueClause: EqualsValueClause; + constructor(dotDotDotToken: ASTSpan, modifiers: PullElementFlags[], identifier: Identifier, questionToken: ASTSpan, typeAnnotation: TypeAnnotation, equalsValueClause: EqualsValueClause); + public kind(): SyntaxKind; + } + class MemberAccessExpression extends AST { + public expression: AST; + public name: Identifier; + constructor(expression: AST, name: Identifier); + public kind(): SyntaxKind; + public structuralEquals(ast: MemberAccessExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class PostfixUnaryExpression extends AST { + private _nodeType; + public operand: AST; + constructor(_nodeType: SyntaxKind, operand: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: PostfixUnaryExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class ElementAccessExpression extends AST { + public expression: AST; + public argumentExpression: AST; + constructor(expression: AST, argumentExpression: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: ElementAccessExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class InvocationExpression extends AST implements ICallExpression { + public expression: AST; + public argumentList: ArgumentList; + constructor(expression: AST, argumentList: ArgumentList); + public kind(): SyntaxKind; + public structuralEquals(ast: InvocationExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class ArgumentList extends AST { + public typeArgumentList: TypeArgumentList; + public closeParenToken: ASTSpan; + public arguments: ISeparatedSyntaxList2; + constructor(typeArgumentList: TypeArgumentList, _arguments: ISeparatedSyntaxList2, closeParenToken: ASTSpan); + public kind(): SyntaxKind; + } + class BinaryExpression extends AST { + private _nodeType; + public left: AST; + public right: AST; + constructor(_nodeType: SyntaxKind, left: AST, right: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: BinaryExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class ConditionalExpression extends AST { + public condition: AST; + public whenTrue: AST; + public whenFalse: AST; + constructor(condition: AST, whenTrue: AST, whenFalse: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: ConditionalExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class ConstructSignature extends AST { + public callSignature: CallSignature; + constructor(callSignature: CallSignature); + public kind(): SyntaxKind; + } + class MethodSignature extends AST { + public propertyName: IASTToken; + public questionToken: ASTSpan; + public callSignature: CallSignature; + constructor(propertyName: IASTToken, questionToken: ASTSpan, callSignature: CallSignature); + public kind(): SyntaxKind; + } + class IndexSignature extends AST { + public parameter: Parameter; + public typeAnnotation: TypeAnnotation; + constructor(parameter: Parameter, typeAnnotation: TypeAnnotation); + public kind(): SyntaxKind; + } + class PropertySignature extends AST { + public propertyName: IASTToken; + public questionToken: ASTSpan; + public typeAnnotation: TypeAnnotation; + constructor(propertyName: IASTToken, questionToken: ASTSpan, typeAnnotation: TypeAnnotation); + public kind(): SyntaxKind; + } + class CallSignature extends AST { + public typeParameterList: TypeParameterList; + public parameterList: ParameterList; + public typeAnnotation: TypeAnnotation; + constructor(typeParameterList: TypeParameterList, parameterList: ParameterList, typeAnnotation: TypeAnnotation); + public kind(): SyntaxKind; + } + class TypeParameter extends AST { + public identifier: Identifier; + public constraint: Constraint; + constructor(identifier: Identifier, constraint: Constraint); + public kind(): SyntaxKind; + public structuralEquals(ast: TypeParameter, includingPosition: boolean): boolean; + } + class Constraint extends AST { + public type: AST; + constructor(type: AST); + public kind(): SyntaxKind; + } + class ElseClause extends AST { + public statement: AST; + constructor(statement: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: ElseClause, includingPosition: boolean): boolean; + } + class IfStatement extends AST { + public condition: AST; + public statement: AST; + public elseClause: ElseClause; + constructor(condition: AST, statement: AST, elseClause: ElseClause); + public kind(): SyntaxKind; + public structuralEquals(ast: IfStatement, includingPosition: boolean): boolean; + } + class ExpressionStatement extends AST { + public expression: AST; + constructor(expression: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: ExpressionStatement, includingPosition: boolean): boolean; + } + class ConstructorDeclaration extends AST { + public callSignature: CallSignature; + public block: Block; + constructor(callSignature: CallSignature, block: Block); + public kind(): SyntaxKind; + } + class MemberFunctionDeclaration extends AST { + public modifiers: PullElementFlags[]; + public propertyName: IASTToken; + public callSignature: CallSignature; + public block: Block; + constructor(modifiers: PullElementFlags[], propertyName: IASTToken, callSignature: CallSignature, block: Block); + public kind(): SyntaxKind; + } + class GetAccessor extends AST { + public modifiers: PullElementFlags[]; + public propertyName: IASTToken; + public parameterList: ParameterList; + public typeAnnotation: TypeAnnotation; + public block: Block; + constructor(modifiers: PullElementFlags[], propertyName: IASTToken, parameterList: ParameterList, typeAnnotation: TypeAnnotation, block: Block); + public kind(): SyntaxKind; + } + class SetAccessor extends AST { + public modifiers: PullElementFlags[]; + public propertyName: IASTToken; + public parameterList: ParameterList; + public block: Block; + constructor(modifiers: PullElementFlags[], propertyName: IASTToken, parameterList: ParameterList, block: Block); + public kind(): SyntaxKind; + } + class MemberVariableDeclaration extends AST { + public modifiers: PullElementFlags[]; + public variableDeclarator: VariableDeclarator; + constructor(modifiers: PullElementFlags[], variableDeclarator: VariableDeclarator); + public kind(): SyntaxKind; + } + class IndexMemberDeclaration extends AST { + public indexSignature: IndexSignature; + constructor(indexSignature: IndexSignature); + public kind(): SyntaxKind; + } + class ThrowStatement extends AST { + public expression: AST; + constructor(expression: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: ThrowStatement, includingPosition: boolean): boolean; + } + class ReturnStatement extends AST { + public expression: AST; + constructor(expression: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: ReturnStatement, includingPosition: boolean): boolean; + } + class ObjectCreationExpression extends AST implements ICallExpression { + public expression: AST; + public argumentList: ArgumentList; + constructor(expression: AST, argumentList: ArgumentList); + public kind(): SyntaxKind; + public structuralEquals(ast: ObjectCreationExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class SwitchStatement extends AST { + public expression: AST; + public closeParenToken: ASTSpan; + public switchClauses: ISyntaxList2; + constructor(expression: AST, closeParenToken: ASTSpan, switchClauses: ISyntaxList2); + public kind(): SyntaxKind; + public structuralEquals(ast: SwitchStatement, includingPosition: boolean): boolean; + } + class CaseSwitchClause extends AST { + public expression: AST; + public statements: ISyntaxList2; + constructor(expression: AST, statements: ISyntaxList2); + public kind(): SyntaxKind; + public structuralEquals(ast: CaseSwitchClause, includingPosition: boolean): boolean; + } + class DefaultSwitchClause extends AST { + public statements: ISyntaxList2; + constructor(statements: ISyntaxList2); + public kind(): SyntaxKind; + public structuralEquals(ast: DefaultSwitchClause, includingPosition: boolean): boolean; + } + class BreakStatement extends AST { + public identifier: Identifier; + constructor(identifier: Identifier); + public kind(): SyntaxKind; + public structuralEquals(ast: BreakStatement, includingPosition: boolean): boolean; + } + class ContinueStatement extends AST { + public identifier: Identifier; + constructor(identifier: Identifier); + public kind(): SyntaxKind; + public structuralEquals(ast: ContinueStatement, includingPosition: boolean): boolean; + } + class ForStatement extends AST { + public variableDeclaration: VariableDeclaration; + public initializer: AST; + public condition: AST; + public incrementor: AST; + public statement: AST; + constructor(variableDeclaration: VariableDeclaration, initializer: AST, condition: AST, incrementor: AST, statement: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: ForStatement, includingPosition: boolean): boolean; + } + class ForInStatement extends AST { + public variableDeclaration: VariableDeclaration; + public left: AST; + public expression: AST; + public statement: AST; + constructor(variableDeclaration: VariableDeclaration, left: AST, expression: AST, statement: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: ForInStatement, includingPosition: boolean): boolean; + } + class WhileStatement extends AST { + public condition: AST; + public statement: AST; + constructor(condition: AST, statement: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: WhileStatement, includingPosition: boolean): boolean; + } + class WithStatement extends AST { + public condition: AST; + public statement: AST; + constructor(condition: AST, statement: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: WithStatement, includingPosition: boolean): boolean; + } + class EnumDeclaration extends AST { + public modifiers: PullElementFlags[]; + public identifier: Identifier; + public enumElements: ISeparatedSyntaxList2; + constructor(modifiers: PullElementFlags[], identifier: Identifier, enumElements: ISeparatedSyntaxList2); + public kind(): SyntaxKind; + } + class EnumElement extends AST { + public propertyName: IASTToken; + public equalsValueClause: EqualsValueClause; + constructor(propertyName: IASTToken, equalsValueClause: EqualsValueClause); + public kind(): SyntaxKind; + } + class CastExpression extends AST { + public type: AST; + public expression: AST; + constructor(type: AST, expression: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: CastExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class ObjectLiteralExpression extends AST { + public propertyAssignments: ISeparatedSyntaxList2; + constructor(propertyAssignments: ISeparatedSyntaxList2); + public kind(): SyntaxKind; + public structuralEquals(ast: ObjectLiteralExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class SimplePropertyAssignment extends AST { + public propertyName: Identifier; + public expression: AST; + constructor(propertyName: Identifier, expression: AST); + public kind(): SyntaxKind; + } + class FunctionPropertyAssignment extends AST { + public propertyName: Identifier; + public callSignature: CallSignature; + public block: Block; + constructor(propertyName: Identifier, callSignature: CallSignature, block: Block); + public kind(): SyntaxKind; + } + class FunctionExpression extends AST { + public identifier: Identifier; + public callSignature: CallSignature; + public block: Block; + constructor(identifier: Identifier, callSignature: CallSignature, block: Block); + public kind(): SyntaxKind; + public isExpression(): boolean; + } + class EmptyStatement extends AST { + public kind(): SyntaxKind; + public structuralEquals(ast: CatchClause, includingPosition: boolean): boolean; + } + class TryStatement extends AST { + public block: Block; + public catchClause: CatchClause; + public finallyClause: FinallyClause; + constructor(block: Block, catchClause: CatchClause, finallyClause: FinallyClause); + public kind(): SyntaxKind; + public structuralEquals(ast: TryStatement, includingPosition: boolean): boolean; + } + class CatchClause extends AST { + public identifier: Identifier; + public typeAnnotation: TypeAnnotation; + public block: Block; + constructor(identifier: Identifier, typeAnnotation: TypeAnnotation, block: Block); + public kind(): SyntaxKind; + public structuralEquals(ast: CatchClause, includingPosition: boolean): boolean; + } + class FinallyClause extends AST { + public block: Block; + constructor(block: Block); + public kind(): SyntaxKind; + public structuralEquals(ast: CatchClause, includingPosition: boolean): boolean; + } + class LabeledStatement extends AST { + public identifier: Identifier; + public statement: AST; + constructor(identifier: Identifier, statement: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: LabeledStatement, includingPosition: boolean): boolean; + } + class DoStatement extends AST { + public statement: AST; + public whileKeyword: ASTSpan; + public condition: AST; + constructor(statement: AST, whileKeyword: ASTSpan, condition: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: DoStatement, includingPosition: boolean): boolean; + } + class TypeOfExpression extends AST { + public expression: AST; + constructor(expression: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: TypeOfExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class DeleteExpression extends AST { + public expression: AST; + constructor(expression: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: DeleteExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class VoidExpression extends AST { + public expression: AST; + constructor(expression: AST); + public kind(): SyntaxKind; + public structuralEquals(ast: VoidExpression, includingPosition: boolean): boolean; + public isExpression(): boolean; + } + class DebuggerStatement extends AST { + public kind(): SyntaxKind; + } + class Comment { + private _trivia; + public endsLine: boolean; + public _start: number; + public _end: number; + constructor(_trivia: ISyntaxTrivia, endsLine: boolean, _start: number, _end: number); + public start(): number; + public end(): number; + public fullText(): string; + public kind(): SyntaxKind; + public structuralEquals(ast: Comment, includingPosition: boolean): boolean; + } +} +declare module TypeScript.Services { + enum EndOfLineState { + Start = 0, + InMultiLineCommentTrivia = 1, + InSingleQuoteStringLiteral = 2, + InDoubleQuoteStringLiteral = 3, + } + enum TokenClass { + Punctuation = 0, + Keyword = 1, + Operator = 2, + Comment = 3, + Whitespace = 4, + Identifier = 5, + NumberLiteral = 6, + StringLiteral = 7, + RegExpLiteral = 8, + } + class Classifier { + public host: IClassifierHost; + private scanner; + private characterWindow; + private diagnostics; + constructor(host: IClassifierHost); + public getClassificationsForLine(text: string, lexState: EndOfLineState): ClassificationResult; + private processToken(text, offset, token, result); + private processTriviaList(text, offset, triviaList, result); + private addResult(text, offset, result, length, kind); + private classFromKind(kind); + } + interface IClassifierHost extends ILogger { + } + class ClassificationResult { + public finalLexState: EndOfLineState; + public entries: ClassificationInfo[]; + constructor(); + } + class ClassificationInfo { + public length: number; + public classification: TokenClass; + constructor(length: number, classification: TokenClass); + } +} +declare module TypeScript.Services { + interface ILanguageServicesDiagnostics { + log(content: string): void; + } +} +declare module TypeScript.Services { + interface ILanguageServiceHost extends ILogger, IReferenceResolverHost { + getCompilationSettings(): CompilationSettings; + getScriptFileNames(): string[]; + getScriptVersion(fileName: string): number; + getScriptIsOpen(fileName: string): boolean; + getScriptByteOrderMark(fileName: string): ByteOrderMark; + getScriptSnapshot(fileName: string): IScriptSnapshot; + getDiagnosticsObject(): ILanguageServicesDiagnostics; + getLocalizedDiagnosticMessages(): any; + } + interface ILanguageService { + refresh(): void; + cleanupSemanticCache(): void; + getSyntacticDiagnostics(fileName: string): Diagnostic[]; + getSemanticDiagnostics(fileName: string): Diagnostic[]; + getCompilerOptionsDiagnostics(): Diagnostic[]; + getCompletionsAtPosition(fileName: string, position: number, isMemberCompletion: boolean): CompletionInfo; + getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; + getTypeAtPosition(fileName: string, position: number): TypeInfo; + getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): SpanInfo; + getBreakpointStatementAtPosition(fileName: string, position: number): SpanInfo; + getSignatureAtPosition(fileName: string, position: number): SignatureInfo; + getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + getImplementorsAtPosition(fileName: string, position: number): ReferenceEntry[]; + getNavigateToItems(searchValue: string): NavigateToItem[]; + getScriptLexicalStructure(fileName: string): NavigateToItem[]; + getOutliningRegions(fileName: string): TextSpan[]; + getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; + getFormattingEditsForRange(fileName: string, minChar: number, limChar: number, options: FormatCodeOptions): TextEdit[]; + getFormattingEditsForDocument(fileName: string, minChar: number, limChar: number, options: FormatCodeOptions): TextEdit[]; + getFormattingEditsOnPaste(fileName: string, minChar: number, limChar: number, options: FormatCodeOptions): TextEdit[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextEdit[]; + getEmitOutput(fileName: string): EmitOutput; + getSyntaxTree(fileName: string): SyntaxTree; + } + function logInternalError(logger: ILogger, err: Error): void; + class ReferenceEntry { + public fileName: string; + public minChar: number; + public limChar: number; + public isWriteAccess: boolean; + constructor(fileName: string, minChar: number, limChar: number, isWriteAccess: boolean); + } + class NavigateToItem { + public name: string; + public kind: string; + public kindModifiers: string; + public matchKind: string; + public fileName: string; + public minChar: number; + public limChar: number; + public additionalSpans: SpanInfo[]; + public containerName: string; + public containerKind: string; + } + class TextEdit { + public minChar: number; + public limChar: number; + public text: string; + constructor(minChar: number, limChar: number, text: string); + static createInsert(pos: number, text: string): TextEdit; + static createDelete(minChar: number, limChar: number): TextEdit; + static createReplace(minChar: number, limChar: number, text: string): TextEdit; + } + class EditorOptions { + public IndentSize: number; + public TabSize: number; + public NewLineCharacter: string; + public ConvertTabsToSpaces: boolean; + static clone(objectToClone: EditorOptions): EditorOptions; + } + class FormatCodeOptions extends EditorOptions { + public InsertSpaceAfterCommaDelimiter: boolean; + public InsertSpaceAfterSemicolonInForStatements: boolean; + public InsertSpaceBeforeAndAfterBinaryOperators: boolean; + public InsertSpaceAfterKeywordsInControlFlowStatements: boolean; + public InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; + public InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; + public PlaceOpenBraceOnNewLineForFunctions: boolean; + public PlaceOpenBraceOnNewLineForControlBlocks: boolean; + static clone(objectToClone: FormatCodeOptions): FormatCodeOptions; + } + class DefinitionInfo { + public fileName: string; + public minChar: number; + public limChar: number; + public kind: string; + public name: string; + public containerKind: string; + public containerName: string; + constructor(fileName: string, minChar: number, limChar: number, kind: string, name: string, containerKind: string, containerName: string); + } + class TypeInfo { + public memberName: MemberName; + public docComment: string; + public fullSymbolName: string; + public kind: string; + public minChar: number; + public limChar: number; + constructor(memberName: MemberName, docComment: string, fullSymbolName: string, kind: string, minChar: number, limChar: number); + } + class SpanInfo { + public minChar: number; + public limChar: number; + public text: string; + constructor(minChar: number, limChar: number, text?: string); + } + class SignatureInfo { + public actual: ActualSignatureInfo; + public formal: FormalSignatureItemInfo[]; + public activeFormal: number; + } + class FormalSignatureItemInfo { + public signatureInfo: string; + public typeParameters: FormalTypeParameterInfo[]; + public parameters: FormalParameterInfo[]; + public docComment: string; + } + class FormalTypeParameterInfo { + public name: string; + public docComment: string; + public minChar: number; + public limChar: number; + } + class FormalParameterInfo { + public name: string; + public isVariable: boolean; + public docComment: string; + public minChar: number; + public limChar: number; + } + class ActualSignatureInfo { + public parameterMinChar: number; + public parameterLimChar: number; + public currentParameterIsTypeParameter: boolean; + public currentParameter: number; + } + class CompletionInfo { + public maybeInaccurate: boolean; + public isMemberCompletion: boolean; + public entries: CompletionEntry[]; + } + interface CompletionEntry { + name: string; + kind: string; + kindModifiers: string; + } + interface CompletionEntryDetails { + name: string; + kind: string; + kindModifiers: string; + type: string; + fullSymbolName: string; + docComment: string; + } + class ScriptElementKind { + static unknown: string; + static keyword: string; + static scriptElement: string; + static moduleElement: string; + static classElement: string; + static interfaceElement: string; + static enumElement: string; + static variableElement: string; + static localVariableElement: string; + static functionElement: string; + static localFunctionElement: string; + static memberFunctionElement: string; + static memberGetAccessorElement: string; + static memberSetAccessorElement: string; + static memberVariableElement: string; + static constructorImplementationElement: string; + static callSignatureElement: string; + static indexSignatureElement: string; + static constructSignatureElement: string; + static parameterElement: string; + static typeParameterElement: string; + static primitiveType: string; + } + class ScriptElementKindModifier { + static none: string; + static publicMemberModifier: string; + static privateMemberModifier: string; + static exportedModifier: string; + static ambientModifier: string; + static staticModifier: string; + } + class MatchKind { + static none: string; + static exact: string; + static subString: string; + static prefix: string; + } + class DiagnosticCategory { + static none: string; + static error: string; + static warning: string; + static message: string; + } +} +declare module TypeScript.Services.Formatting { + interface ITextSnapshot { + getText(span: TextSpan): string; + getLineNumberFromPosition(position: number): number; + getLineFromPosition(position: number): ITextSnapshotLine; + getLineFromLineNumber(lineNumber: number): ITextSnapshotLine; + } + class TextSnapshot implements ITextSnapshot { + private snapshot; + private lines; + constructor(snapshot: ISimpleText); + public getText(span: TextSpan): string; + public getLineNumberFromPosition(position: number): number; + public getLineFromPosition(position: number): ITextSnapshotLine; + public getLineFromLineNumber(lineNumber: number): ITextSnapshotLine; + private getLineFromLineNumberWorker(lineNumber); + } +} +declare module TypeScript.Services.Formatting { + interface ITextSnapshotLine { + snapshot(): ITextSnapshot; + start(): SnapshotPoint; + startPosition(): number; + end(): SnapshotPoint; + endPosition(): number; + endIncludingLineBreak(): SnapshotPoint; + endIncludingLineBreakPosition(): number; + length(): number; + lineNumber(): number; + getText(): string; + } + class TextSnapshotLine implements ITextSnapshotLine { + private _snapshot; + private _lineNumber; + private _start; + private _end; + private _lineBreak; + constructor(_snapshot: ITextSnapshot, _lineNumber: number, _start: number, _end: number, _lineBreak: string); + public snapshot(): ITextSnapshot; + public start(): SnapshotPoint; + public startPosition(): number; + public end(): SnapshotPoint; + public endPosition(): number; + public endIncludingLineBreak(): SnapshotPoint; + public endIncludingLineBreakPosition(): number; + public length(): number; + public lineNumber(): number; + public getText(): string; + } +} +declare module TypeScript.Services.Formatting { + class SnapshotPoint { + public snapshot: ITextSnapshot; + public position: number; + constructor(snapshot: ITextSnapshot, position: number); + public getContainingLine(): ITextSnapshotLine; + public add(offset: number): SnapshotPoint; + } +} +declare module TypeScript.Services.Formatting { + class FormattingContext { + private snapshot; + public formattingRequestKind: FormattingRequestKind; + public currentTokenSpan: TokenSpan; + public nextTokenSpan: TokenSpan; + public contextNode: IndentationNodeContext; + public currentTokenParent: IndentationNodeContext; + public nextTokenParent: IndentationNodeContext; + private contextNodeAllOnSameLine; + private nextNodeAllOnSameLine; + private tokensAreOnSameLine; + private contextNodeBlockIsOnOneLine; + private nextNodeBlockIsOnOneLine; + constructor(snapshot: ITextSnapshot, formattingRequestKind: FormattingRequestKind); + public updateContext(currentTokenSpan: TokenSpan, currentTokenParent: IndentationNodeContext, nextTokenSpan: TokenSpan, nextTokenParent: IndentationNodeContext, commonParent: IndentationNodeContext): void; + public ContextNodeAllOnSameLine(): boolean; + public NextNodeAllOnSameLine(): boolean; + public TokensAreOnSameLine(): boolean; + public ContextNodeBlockIsOnOneLine(): boolean; + public NextNodeBlockIsOnOneLine(): boolean; + public NodeIsOnOneLine(node: IndentationNodeContext): boolean; + public BlockIsOnOneLine(node: IndentationNodeContext): boolean; + } +} +declare module TypeScript.Services.Formatting { + class FormattingManager { + private syntaxTree; + private snapshot; + private rulesProvider; + private options; + constructor(syntaxTree: SyntaxTree, snapshot: ITextSnapshot, rulesProvider: RulesProvider, editorOptions: EditorOptions); + public formatSelection(minChar: number, limChar: number): TextEdit[]; + public formatDocument(minChar: number, limChar: number): TextEdit[]; + public formatOnPaste(minChar: number, limChar: number): TextEdit[]; + public formatOnSemicolon(caretPosition: number): TextEdit[]; + public formatOnClosingCurlyBrace(caretPosition: number): TextEdit[]; + public formatOnEnter(caretPosition: number): TextEdit[]; + private formatSpan(span, formattingRequestKind); + } +} +declare module TypeScript.Services.Formatting { + enum FormattingRequestKind { + FormatDocument = 0, + FormatSelection = 1, + FormatOnEnter = 2, + FormatOnSemicolon = 3, + FormatOnClosingCurlyBrace = 4, + FormatOnPaste = 5, + } +} +declare module TypeScript.Services.Formatting { + class Rule { + public Descriptor: RuleDescriptor; + public Operation: RuleOperation; + public Flag: RuleFlags; + constructor(Descriptor: RuleDescriptor, Operation: RuleOperation, Flag?: RuleFlags); + public toString(): string; + } +} +declare module TypeScript.Services.Formatting { + enum RuleAction { + Ignore = 0, + Space = 1, + NewLine = 2, + Delete = 3, + } +} +declare module TypeScript.Services.Formatting { + class RuleDescriptor { + public LeftTokenRange: Shared.TokenRange; + public RightTokenRange: Shared.TokenRange; + constructor(LeftTokenRange: Shared.TokenRange, RightTokenRange: Shared.TokenRange); + public toString(): string; + static create1(left: SyntaxKind, right: SyntaxKind): RuleDescriptor; + static create2(left: Shared.TokenRange, right: SyntaxKind): RuleDescriptor; + static create3(left: SyntaxKind, right: Shared.TokenRange): RuleDescriptor; + static create4(left: Shared.TokenRange, right: Shared.TokenRange): RuleDescriptor; + } +} +declare module TypeScript.Services.Formatting { + enum RuleFlags { + None = 0, + CanDeleteNewLines = 1, + } +} +declare module TypeScript.Services.Formatting { + class RuleOperation { + public Context: RuleOperationContext; + public Action: RuleAction; + constructor(); + public toString(): string; + static create1(action: RuleAction): RuleOperation; + static create2(context: RuleOperationContext, action: RuleAction): RuleOperation; + } +} +declare module TypeScript.Services.Formatting { + class RuleOperationContext { + private customContextChecks; + constructor(...funcs: { + (context: FormattingContext): boolean; + }[]); + static Any: RuleOperationContext; + public IsAny(): boolean; + public InContext(context: FormattingContext): boolean; + } +} +declare module TypeScript.Services.Formatting { + class Rules { + public getRuleName(rule: Rule): any; + [name: string]: any; + public IgnoreBeforeComment: Rule; + public IgnoreAfterLineComment: Rule; + public NoSpaceBeforeSemicolon: Rule; + public NoSpaceBeforeColon: Rule; + public NoSpaceBeforeQMark: Rule; + public SpaceAfterColon: Rule; + public SpaceAfterQMark: Rule; + public SpaceAfterSemicolon: Rule; + public SpaceAfterCloseBrace: Rule; + public SpaceBetweenCloseBraceAndElse: Rule; + public SpaceBetweenCloseBraceAndWhile: Rule; + public NoSpaceAfterCloseBrace: Rule; + public NoSpaceBeforeDot: Rule; + public NoSpaceAfterDot: Rule; + public NoSpaceBeforeOpenBracket: Rule; + public NoSpaceAfterOpenBracket: Rule; + public NoSpaceBeforeCloseBracket: Rule; + public NoSpaceAfterCloseBracket: Rule; + public SpaceAfterOpenBrace: Rule; + public SpaceBeforeCloseBrace: Rule; + public NoSpaceBetweenEmptyBraceBrackets: Rule; + public NewLineAfterOpenBraceInBlockContext: Rule; + public NewLineBeforeCloseBraceInBlockContext: Rule; + public NoSpaceAfterUnaryPrefixOperator: Rule; + public NoSpaceAfterUnaryPreincrementOperator: Rule; + public NoSpaceAfterUnaryPredecrementOperator: Rule; + public NoSpaceBeforeUnaryPostincrementOperator: Rule; + public NoSpaceBeforeUnaryPostdecrementOperator: Rule; + public SpaceAfterPostincrementWhenFollowedByAdd: Rule; + public SpaceAfterAddWhenFollowedByUnaryPlus: Rule; + public SpaceAfterAddWhenFollowedByPreincrement: Rule; + public SpaceAfterPostdecrementWhenFollowedBySubtract: Rule; + public SpaceAfterSubtractWhenFollowedByUnaryMinus: Rule; + public SpaceAfterSubtractWhenFollowedByPredecrement: Rule; + public NoSpaceBeforeComma: Rule; + public SpaceAfterCertainKeywords: Rule; + public NoSpaceBeforeOpenParenInFuncCall: Rule; + public SpaceAfterFunctionInFuncDecl: Rule; + public NoSpaceBeforeOpenParenInFuncDecl: Rule; + public SpaceAfterVoidOperator: Rule; + public NoSpaceBetweenReturnAndSemicolon: Rule; + public SpaceBetweenStatements: Rule; + public SpaceAfterTryFinally: Rule; + public SpaceAfterGetSetInMember: Rule; + public SpaceBeforeBinaryKeywordOperator: Rule; + public SpaceAfterBinaryKeywordOperator: Rule; + public NoSpaceAfterConstructor: Rule; + public NoSpaceAfterModuleImport: Rule; + public SpaceAfterCertainTypeScriptKeywords: Rule; + public SpaceBeforeCertainTypeScriptKeywords: Rule; + public SpaceAfterModuleName: Rule; + public SpaceAfterArrow: Rule; + public NoSpaceAfterEllipsis: Rule; + public NoSpaceAfterOptionalParameters: Rule; + public NoSpaceBeforeOpenAngularBracket: Rule; + public NoSpaceBetweenCloseParenAndAngularBracket: Rule; + public NoSpaceAfterOpenAngularBracket: Rule; + public NoSpaceBeforeCloseAngularBracket: Rule; + public NoSpaceAfterCloseAngularBracket: Rule; + public NoSpaceBetweenEmptyInterfaceBraceBrackets: Rule; + public HighPriorityCommonRules: Rule[]; + public LowPriorityCommonRules: Rule[]; + public SpaceAfterComma: Rule; + public NoSpaceAfterComma: Rule; + public SpaceBeforeBinaryOperator: Rule; + public SpaceAfterBinaryOperator: Rule; + public NoSpaceBeforeBinaryOperator: Rule; + public NoSpaceAfterBinaryOperator: Rule; + public SpaceAfterKeywordInControl: Rule; + public NoSpaceAfterKeywordInControl: Rule; + public FunctionOpenBraceLeftTokenRange: Shared.TokenRange; + public SpaceBeforeOpenBraceInFunction: Rule; + public NewLineBeforeOpenBraceInFunction: Rule; + public TypeScriptOpenBraceLeftTokenRange: Shared.TokenRange; + public SpaceBeforeOpenBraceInTypeScriptDeclWithBlock: Rule; + public NewLineBeforeOpenBraceInTypeScriptDeclWithBlock: Rule; + public ControlOpenBraceLeftTokenRange: Shared.TokenRange; + public SpaceBeforeOpenBraceInControl: Rule; + public NewLineBeforeOpenBraceInControl: Rule; + public SpaceAfterSemicolonInFor: Rule; + public NoSpaceAfterSemicolonInFor: Rule; + public SpaceAfterOpenParen: Rule; + public SpaceBeforeCloseParen: Rule; + public NoSpaceBetweenParens: Rule; + public NoSpaceAfterOpenParen: Rule; + public NoSpaceBeforeCloseParen: Rule; + public SpaceAfterAnonymousFunctionKeyword: Rule; + public NoSpaceAfterAnonymousFunctionKeyword: Rule; + constructor(); + static IsForContext(context: FormattingContext): boolean; + static IsNotForContext(context: FormattingContext): boolean; + static IsBinaryOpContext(context: FormattingContext): boolean; + static IsNotBinaryOpContext(context: FormattingContext): boolean; + static IsSameLineTokenOrBeforeMultilineBlockContext(context: FormattingContext): boolean; + static IsBeforeMultilineBlockContext(context: FormattingContext): boolean; + static IsMultilineBlockContext(context: FormattingContext): boolean; + static IsSingleLineBlockContext(context: FormattingContext): boolean; + static IsBlockContext(context: FormattingContext): boolean; + static IsBeforeBlockContext(context: FormattingContext): boolean; + static NodeIsBlockContext(node: IndentationNodeContext): boolean; + static IsFunctionDeclContext(context: FormattingContext): boolean; + static IsTypeScriptDeclWithBlockContext(context: FormattingContext): boolean; + static NodeIsTypeScriptDeclWithBlockContext(node: IndentationNodeContext): boolean; + static IsAfterCodeBlockContext(context: FormattingContext): boolean; + static IsControlDeclContext(context: FormattingContext): boolean; + static IsObjectContext(context: FormattingContext): boolean; + static IsFunctionCallContext(context: FormattingContext): boolean; + static IsNewContext(context: FormattingContext): boolean; + static IsFunctionCallOrNewContext(context: FormattingContext): boolean; + static IsSameLineTokenContext(context: FormattingContext): boolean; + static IsNotFormatOnEnter(context: FormattingContext): boolean; + static IsModuleDeclContext(context: FormattingContext): boolean; + static IsObjectTypeContext(context: FormattingContext): boolean; + static IsTypeArgumentOrParameter(tokenKind: SyntaxKind, parentKind: SyntaxKind): boolean; + static IsTypeArgumentOrParameterContext(context: FormattingContext): boolean; + static IsVoidOpContext(context: FormattingContext): boolean; + } +} +declare module TypeScript.Services.Formatting { + class RulesMap { + public map: RulesBucket[]; + public mapRowLength: number; + constructor(); + static create(rules: Rule[]): RulesMap; + public Initialize(rules: Rule[]): RulesBucket[]; + public FillRules(rules: Rule[], rulesBucketConstructionStateList: RulesBucketConstructionState[]): void; + private GetRuleBucketIndex(row, column); + private FillRule(rule, rulesBucketConstructionStateList); + public GetRule(context: FormattingContext): Rule; + } + enum RulesPosition { + IgnoreRulesSpecific = 0, + IgnoreRulesAny, + ContextRulesSpecific, + ContextRulesAny, + NoContextRulesSpecific, + NoContextRulesAny, + } + class RulesBucketConstructionState { + private rulesInsertionIndexBitmap; + constructor(); + public GetInsertionIndex(maskPosition: RulesPosition): number; + public IncreaseInsertionIndex(maskPosition: RulesPosition): void; + } + class RulesBucket { + private rules; + constructor(); + public Rules(): Rule[]; + public AddRule(rule: Rule, specificTokens: boolean, constructionState: RulesBucketConstructionState[], rulesBucketIndex: number): void; + } +} +declare module TypeScript.Services.Formatting { + class RulesProvider { + private logger; + private globalRules; + private options; + private activeRules; + private rulesMap; + constructor(logger: ILogger); + public getRuleName(rule: Rule): string; + public getRuleByName(name: string): Rule; + public getRulesMap(): RulesMap; + public ensureUpToDate(options: FormatCodeOptions): void; + private createActiveRules(options); + } +} +declare module TypeScript.Services.Formatting { + class TextEditInfo { + public position: number; + public length: number; + public replaceWith: string; + constructor(position: number, length: number, replaceWith: string); + public toString(): string; + } +} +declare module TypeScript.Services.Formatting { + module Shared { + interface ITokenAccess { + GetTokens(): SyntaxKind[]; + Contains(token: SyntaxKind): boolean; + } + class TokenRangeAccess implements ITokenAccess { + private tokens; + constructor(from: SyntaxKind, to: SyntaxKind, except: SyntaxKind[]); + public GetTokens(): SyntaxKind[]; + public Contains(token: SyntaxKind): boolean; + public toString(): string; + } + class TokenValuesAccess implements ITokenAccess { + private tokens; + constructor(tks: SyntaxKind[]); + public GetTokens(): SyntaxKind[]; + public Contains(token: SyntaxKind): boolean; + } + class TokenSingleValueAccess implements ITokenAccess { + public token: SyntaxKind; + constructor(token: SyntaxKind); + public GetTokens(): SyntaxKind[]; + public Contains(tokenValue: SyntaxKind): boolean; + public toString(): string; + } + class TokenAllAccess implements ITokenAccess { + public GetTokens(): SyntaxKind[]; + public Contains(tokenValue: SyntaxKind): boolean; + public toString(): string; + } + class TokenRange { + public tokenAccess: ITokenAccess; + constructor(tokenAccess: ITokenAccess); + static FromToken(token: SyntaxKind): TokenRange; + static FromTokens(tokens: SyntaxKind[]): TokenRange; + static FromRange(f: SyntaxKind, to: SyntaxKind, except?: SyntaxKind[]): TokenRange; + static AllTokens(): TokenRange; + public GetTokens(): SyntaxKind[]; + public Contains(token: SyntaxKind): boolean; + public toString(): string; + static Any: TokenRange; + static AnyIncludingMultilineComments: TokenRange; + static Keywords: TokenRange; + static Operators: TokenRange; + static BinaryOperators: TokenRange; + static BinaryKeywordOperators: TokenRange; + static ReservedKeywords: TokenRange; + static UnaryPrefixOperators: TokenRange; + static UnaryPrefixExpressions: TokenRange; + static UnaryPreincrementExpressions: TokenRange; + static UnaryPostincrementExpressions: TokenRange; + static UnaryPredecrementExpressions: TokenRange; + static UnaryPostdecrementExpressions: TokenRange; + static Comments: TokenRange; + static TypeNames: TokenRange; + } + } +} +declare module TypeScript.Services.Formatting { + class TokenSpan extends TextSpan { + private _kind; + constructor(kind: SyntaxKind, start: number, length: number); + public kind(): SyntaxKind; + } +} +declare module TypeScript.Services.Formatting { + class IndentationNodeContext { + private _node; + private _parent; + private _fullStart; + private _indentationAmount; + private _childIndentationAmountDelta; + private _depth; + private _hasSkippedOrMissingTokenChild; + constructor(parent: IndentationNodeContext, node: SyntaxNode, fullStart: number, indentationAmount: number, childIndentationAmountDelta: number); + public parent(): IndentationNodeContext; + public node(): SyntaxNode; + public fullStart(): number; + public fullWidth(): number; + public start(): number; + public end(): number; + public indentationAmount(): number; + public childIndentationAmountDelta(): number; + public depth(): number; + public kind(): SyntaxKind; + public hasSkippedOrMissingTokenChild(): boolean; + public clone(pool: IndentationNodeContextPool): IndentationNodeContext; + public update(parent: IndentationNodeContext, node: SyntaxNode, fullStart: number, indentationAmount: number, childIndentationAmountDelta: number): void; + } +} +declare module TypeScript.Services.Formatting { + class IndentationNodeContextPool { + private nodes; + public getNode(parent: IndentationNodeContext, node: SyntaxNode, fullStart: number, indentationLevel: number, childIndentationLevelDelta: number): IndentationNodeContext; + public releaseNode(node: IndentationNodeContext, recursive?: boolean): void; + } +} +declare module TypeScript.Services.Formatting { + class IndentationTrackingWalker extends SyntaxWalker { + public options: FormattingOptions; + private _position; + private _parent; + private _textSpan; + private _snapshot; + private _lastTriviaWasNewLine; + private _indentationNodeContextPool; + constructor(textSpan: TextSpan, sourceUnit: SourceUnitSyntax, snapshot: ITextSnapshot, indentFirstToken: boolean, options: FormattingOptions); + public position(): number; + public parent(): IndentationNodeContext; + public textSpan(): TextSpan; + public snapshot(): ITextSnapshot; + public indentationNodeContextPool(): IndentationNodeContextPool; + public forceIndentNextToken(tokenStart: number): void; + public forceSkipIndentingNextToken(tokenStart: number): void; + public indentToken(token: ISyntaxToken, indentationAmount: number, commentIndentationAmount: number): void; + public visitTokenInSpan(token: ISyntaxToken): void; + public visitToken(token: ISyntaxToken): void; + public visitNode(node: SyntaxNode): void; + private getTokenIndentationAmount(token); + private getCommentIndentationAmount(token); + private getNodeIndentation(node, newLineInsertedByFormatting?); + private shouldIndentBlockInParent(parent); + private forceRecomputeIndentationOfParent(tokenStart, newLineAdded); + } +} +declare module TypeScript.Services.Formatting { + class MultipleTokenIndenter extends IndentationTrackingWalker { + private _edits; + constructor(textSpan: TextSpan, sourceUnit: SourceUnitSyntax, snapshot: ITextSnapshot, indentFirstToken: boolean, options: FormattingOptions); + public indentToken(token: ISyntaxToken, indentationAmount: number, commentIndentationAmount: number): void; + public edits(): TextEditInfo[]; + public recordEdit(position: number, length: number, replaceWith: string): void; + private recordIndentationEditsForToken(token, indentationString, commentIndentationString); + private recordIndentationEditsForSingleLineOrSkippedText(trivia, fullStart, indentationString); + private recordIndentationEditsForWhitespace(trivia, fullStart, indentationString); + private recordIndentationEditsForMultiLineComment(trivia, fullStart, indentationString, leadingWhiteSpace, firstLineAlreadyIndented); + private recordIndentationEditsForSegment(segment, fullStart, indentationColumns, whiteSpaceColumnsInFirstSegment); + } +} +declare module TypeScript.Services.Formatting { + class SingleTokenIndenter extends IndentationTrackingWalker { + private indentationAmount; + private indentationPosition; + constructor(indentationPosition: number, sourceUnit: SourceUnitSyntax, snapshot: ITextSnapshot, indentFirstToken: boolean, options: FormattingOptions); + static getIndentationAmount(position: number, sourceUnit: SourceUnitSyntax, snapshot: ITextSnapshot, options: FormattingOptions): number; + public indentToken(token: ISyntaxToken, indentationAmount: number, commentIndentationAmount: number): void; + } +} +declare module TypeScript.Services.Formatting { + class Formatter extends MultipleTokenIndenter { + private previousTokenSpan; + private previousTokenParent; + private scriptHasErrors; + private rulesProvider; + private formattingRequestKind; + private formattingContext; + constructor(textSpan: TextSpan, sourceUnit: SourceUnitSyntax, indentFirstToken: boolean, options: FormattingOptions, snapshot: ITextSnapshot, rulesProvider: RulesProvider, formattingRequestKind: FormattingRequestKind); + static getEdits(textSpan: TextSpan, sourceUnit: SourceUnitSyntax, options: FormattingOptions, indentFirstToken: boolean, snapshot: ITextSnapshot, rulesProvider: RulesProvider, formattingRequestKind: FormattingRequestKind): TextEditInfo[]; + public visitTokenInSpan(token: ISyntaxToken): void; + private processToken(token); + private processTrivia(triviaList, fullStart); + private findCommonParents(parent1, parent2); + private formatPair(t1, t1Parent, t2, t2Parent); + private getLineNumber(span); + private trimWhitespaceInLineRange(startLine, endLine, token?); + private trimWhitespace(line, token?); + private RecordRuleEdits(rule, t1, t2); + } +} +declare var debugObjectHost: any; +declare module TypeScript.Services { + interface ICoreServicesHost { + logger: ILogger; + } + class CoreServices { + public host: ICoreServicesHost; + constructor(host: ICoreServicesHost); + public getPreProcessedFileInfo(fileName: string, sourceText: IScriptSnapshot): IPreProcessedFileInfo; + public getDefaultCompilationSettings(): CompilationSettings; + public dumpMemory(): string; + public getMemoryInfo(): any[]; + public collectGarbage(): void; + } +} +declare module TypeScript.Services { + class SyntaxTreeCache { + private _host; + private _hostCache; + private _currentFileName; + private _currentFileVersion; + private _currentFileSyntaxTree; + private _currentFileScriptSnapshot; + constructor(_host: ILanguageServiceHost); + public getCurrentFileSyntaxTree(fileName: string): SyntaxTree; + private createSyntaxTree(fileName, scriptSnapshot); + private updateSyntaxTree(fileName, scriptSnapshot, previousSyntaxTree, previousFileVersion); + private ensureInvariants(fileName, editRange, incrementalTree, oldScriptSnapshot, newScriptSnapshot); + } + class LanguageServiceCompiler { + private host; + private logger; + private compiler; + private hostCache; + constructor(host: ILanguageServiceHost); + private synchronizeHostData(); + private synchronizeHostDataWorker(); + private tryUpdateFile(compiler, fileName); + public getScriptSnapshot(fileName: string): IScriptSnapshot; + public getCachedHostFileName(fileName: string): string; + public getCachedTopLevelDeclaration(fileName: string): PullDecl; + public compilationSettings(): ImmutableCompilationSettings; + public fileNames(): string[]; + public cleanupSemanticCache(): void; + public getDocument(fileName: string): Document; + public getSyntacticDiagnostics(fileName: string): Diagnostic[]; + public getSemanticDiagnostics(fileName: string): Diagnostic[]; + public getCompilerOptionsDiagnostics(resolvePath: (path: string) => string): Diagnostic[]; + public getSymbolInformationFromAST(ast: AST, document: Document): PullSymbolInfo; + public getCallInformationFromAST(ast: AST, document: Document): PullCallSymbolInfo; + public getVisibleMemberSymbolsFromAST(ast: AST, document: Document): PullVisibleSymbolsInfo; + public getVisibleDeclsFromAST(ast: AST, document: Document): PullDecl[]; + public getContextualMembersFromAST(ast: AST, document: Document): PullVisibleSymbolsInfo; + public pullGetDeclInformation(decl: PullDecl, ast: AST, document: Document): PullSymbolInfo; + public topLevelDeclaration(fileName: string): PullDecl; + public getDeclForAST(ast: AST): PullDecl; + public emit(fileName: string, resolvePath: (path: string) => string): EmitOutput; + public emitDeclarations(fileName: string, resolvePath: (path: string) => string): EmitOutput; + public canEmitDeclarations(fileName: string): boolean; + } +} +declare module TypeScript.Services { + class CompletionHelpers { + private static getSpan(ast); + private static symbolDeclarationIntersectsPosition(symbol, fileName, position); + static filterContextualMembersList(contextualMemberSymbols: PullSymbol[], existingMembers: PullVisibleSymbolsInfo, fileName: string, position: number): PullSymbol[]; + static isCompletionListBlocker(sourceUnit: SourceUnitSyntax, position: number): boolean; + static getContainingObjectLiteralApplicableForCompletion(sourceUnit: SourceUnitSyntax, position: number): PositionedElement; + static isIdentifierDefinitionLocation(sourceUnit: SourceUnitSyntax, position: number): boolean; + static getNonIdentifierCompleteTokenOnLeft(sourceUnit: SourceUnitSyntax, position: number): PositionedToken; + static isRightOfIllegalDot(sourceUnit: SourceUnitSyntax, position: number): boolean; + static getValidCompletionEntryDisplayName(displayName: string): string; + } +} +declare module TypeScript.Services { + class KeywordCompletions { + private static keywords; + private static keywordCompletions; + static getKeywordCompltions(): ResolvedCompletionEntry[]; + } +} +declare module TypeScript.Services { + interface IPartiallyWrittenTypeArgumentListInformation { + genericIdentifer: PositionedToken; + lessThanToken: PositionedToken; + argumentIndex: number; + } + class SignatureInfoHelpers { + static isInPartiallyWrittenTypeArgumentList(syntaxTree: SyntaxTree, position: number): IPartiallyWrittenTypeArgumentListInformation; + static getSignatureInfoFromSignatureSymbol(symbol: PullSymbol, signatures: PullSignatureSymbol[], enclosingScopeSymbol: PullSymbol, compilerState: LanguageServiceCompiler): FormalSignatureItemInfo[]; + static getSignatureInfoFromGenericSymbol(symbol: PullSymbol, enclosingScopeSymbol: PullSymbol, compilerState: LanguageServiceCompiler): FormalSignatureItemInfo[]; + static getActualSignatureInfoFromCallExpression(ast: ICallExpression, caretPosition: number, typeParameterInformation: IPartiallyWrittenTypeArgumentListInformation): ActualSignatureInfo; + static getActualSignatureInfoFromPartiallyWritenGenericExpression(caretPosition: number, typeParameterInformation: IPartiallyWrittenTypeArgumentListInformation): ActualSignatureInfo; + static isSignatureHelpBlocker(sourceUnit: SourceUnitSyntax, position: number): boolean; + static isTargetOfObjectCreationExpression(positionedToken: PositionedToken): boolean; + private static moveBackUpTillMatchingTokenKind(token, tokenKind, matchingTokenKind); + } +} +declare module TypeScript.Services { + interface CachedCompletionEntryDetails extends CompletionEntryDetails { + isResolved(): boolean; + } + class ResolvedCompletionEntry implements CachedCompletionEntryDetails { + public name: string; + public kind: string; + public kindModifiers: string; + public type: string; + public fullSymbolName: string; + public docComment: string; + constructor(name: string, kind: string, kindModifiers: string, type: string, fullSymbolName: string, docComment: string); + public isResolved(): boolean; + } + class DeclReferenceCompletionEntry implements CachedCompletionEntryDetails { + public name: string; + public kind: string; + public kindModifiers: string; + public decl: PullDecl; + public type: string; + public fullSymbolName: string; + public docComment: string; + private hasBeenResolved; + constructor(name: string, kind: string, kindModifiers: string, decl: PullDecl); + public isResolved(): boolean; + public resolve(type: string, fullSymbolName: string, docComments: string): void; + } + class CompletionSession { + public fileName: string; + public position: number; + public entries: IdentiferNameHashTable; + constructor(fileName: string, position: number, entries: IdentiferNameHashTable); + } +} +declare module TypeScript.Services { + class LanguageService implements ILanguageService { + public host: ILanguageServiceHost; + private logger; + private compiler; + private _syntaxTreeCache; + private formattingRulesProvider; + private activeCompletionSession; + constructor(host: ILanguageServiceHost); + public cleanupSemanticCache(): void; + public refresh(): void; + private getSymbolInfoAtPosition(fileName, pos, requireName); + public getReferencesAtPosition(fileName: string, pos: number): ReferenceEntry[]; + private getSymbolScopeAST(symbol, ast); + public getOccurrencesAtPosition(fileName: string, pos: number): ReferenceEntry[]; + private getSingleNodeReferenceAtPosition(fileName, position); + public getImplementorsAtPosition(fileName: string, pos: number): ReferenceEntry[]; + public getOverrides(container: PullTypeSymbol, memberSym: PullSymbol): PullTypeSymbol[]; + private getImplementorsInFile(fileName, symbol); + private getReferencesInFile(fileName, symbol, containingASTOpt); + private isWriteAccess(current); + private isLetterOrDigit(char); + private getPossibleSymbolReferencePositions(fileName, symbolName); + public getSignatureAtPosition(fileName: string, position: number): SignatureInfo; + private getTypeParameterSignatureFromPartiallyWrittenExpression(document, position, genericTypeArgumentListInfo); + public getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + private addDeclarations(symbolKind, symbolName, containerKind, containerName, declarations, result); + private addDeclaration(symbolKind, symbolName, containerKind, containerName, declaration, result); + private tryAddDefinition(symbolKind, symbolName, containerKind, containerName, declarations, result); + private tryAddSignatures(symbolKind, symbolName, containerKind, containerName, declarations, result); + private tryAddConstructor(symbolKind, symbolName, containerKind, containerName, declarations, result); + public getNavigateToItems(searchValue: string): NavigateToItem[]; + private hasAnyUpperCaseCharacter(s); + private findSearchValueInPullDecl(fileName, declarations, results, searchTerms, parentName?, parentkindName?); + private getScriptElementKindModifiersFromDecl(decl); + private isContainerDeclaration(declaration); + private shouldIncludeDeclarationInNavigationItems(declaration); + public getSyntacticDiagnostics(fileName: string): Diagnostic[]; + public getSemanticDiagnostics(fileName: string): Diagnostic[]; + private _getHostSpecificDiagnosticWithFileName(diagnostic); + public getCompilerOptionsDiagnostics(): Diagnostic[]; + private _getHostFileName(fileName); + public getEmitOutput(fileName: string): EmitOutput; + private getAllSyntacticDiagnostics(); + private getAllSemanticDiagnostics(); + private containErrors(diagnostics); + private getFullNameOfSymbol(symbol, enclosingScopeSymbol); + private getTypeInfoEligiblePath(fileName, position, isConstructorValidPosition); + public getTypeAtPosition(fileName: string, position: number): TypeInfo; + public getCompletionsAtPosition(fileName: string, position: number, isMemberCompletion: boolean): CompletionInfo; + private getCompletionEntriesFromSymbols(symbolInfo, result); + private getCompletionEntriesFromDecls(decls, result); + private getResolvedCompletionEntryDetailsFromSymbol(symbol, enclosingScopeSymbol); + private getCompletionEntriesForKeywords(keywords, result); + public getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; + private tryFindDeclFromPreviousCompilerVersion(invalidatedDecl); + private getModuleOrEnumKind(symbol); + private mapPullElementKind(kind, symbol?, useConstructorAsClass?, varIsFunction?, functionIsConstructor?); + private getScriptElementKindModifiers(symbol); + private getScriptElementKindModifiersFromFlags(flags); + public getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): SpanInfo; + public getBreakpointStatementAtPosition(fileName: string, pos: number): SpanInfo; + public getFormattingEditsForRange(fileName: string, minChar: number, limChar: number, options: FormatCodeOptions): TextEdit[]; + public getFormattingEditsForDocument(fileName: string, minChar: number, limChar: number, options: FormatCodeOptions): TextEdit[]; + public getFormattingEditsOnPaste(fileName: string, minChar: number, limChar: number, options: FormatCodeOptions): TextEdit[]; + public getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextEdit[]; + private getFormattingManager(fileName, options); + public getOutliningRegions(fileName: string): TextSpan[]; + public getIndentationAtPosition(fileName: string, position: number, editorOptions: EditorOptions): number; + public getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; + public getScriptLexicalStructure(fileName: string): NavigateToItem[]; + public getSyntaxTree(fileName: string): SyntaxTree; + } +} +declare module TypeScript.Services { + class FindReferenceHelpers { + static compareSymbolsForLexicalIdentity(firstSymbol: PullSymbol, secondSymbol: PullSymbol): boolean; + private static checkSymbolsForDeclarationEquality(firstSymbol, secondSymbol); + private static declarationsAreSameOrParents(firstDecl, secondDecl); + } +} +declare module TypeScript.Services { + interface IScriptSnapshotShim { + getText(start: number, end: number): string; + getLength(): number; + getLineStartPositions(): string; + getTextChangeRangeSinceVersion(scriptVersion: number): string; + } + interface ILanguageServiceShimHost extends ILogger { + getCompilationSettings(): string; + getScriptFileNames(): string; + getScriptVersion(fileName: string): number; + getScriptIsOpen(fileName: string): boolean; + getScriptByteOrderMark(fileName: string): number; + getScriptSnapshot(fileName: string): IScriptSnapshotShim; + resolveRelativePath(path: string, directory: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + getParentDirectory(path: string): string; + getDiagnosticsObject(): ILanguageServicesDiagnostics; + getLocalizedDiagnosticMessages(): string; + } + interface IShimFactory { + registerShim(shim: IShim): void; + unregisterShim(shim: IShim): void; + } + interface IShim { + dispose(dummy: any): void; + } + class ShimBase implements IShim { + private factory; + constructor(factory: IShimFactory); + public dispose(dummy: any): void; + } + interface ILanguageServiceShim extends IShim { + languageService: ILanguageService; + dispose(dummy: any): void; + refresh(throwOnError: boolean): void; + cleanupSemanticCache(): void; + getSyntacticDiagnostics(fileName: string): string; + getSemanticDiagnostics(fileName: string): string; + getCompilerOptionsDiagnostics(): string; + getCompletionsAtPosition(fileName: string, position: number, isMemberCompletion: boolean): string; + getCompletionEntryDetails(fileName: string, position: number, entryName: string): string; + getTypeAtPosition(fileName: string, position: number): string; + getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string; + getBreakpointStatementAtPosition(fileName: string, position: number): string; + getSignatureAtPosition(fileName: string, position: number): string; + getDefinitionAtPosition(fileName: string, position: number): string; + getReferencesAtPosition(fileName: string, position: number): string; + getOccurrencesAtPosition(fileName: string, position: number): string; + getImplementorsAtPosition(fileName: string, position: number): string; + getNavigateToItems(searchValue: string): string; + getScriptLexicalStructure(fileName: string): string; + getOutliningRegions(fileName: string): string; + getBraceMatchingAtPosition(fileName: string, position: number): string; + getIndentationAtPosition(fileName: string, position: number, options: string): string; + getFormattingEditsForRange(fileName: string, minChar: number, limChar: number, options: string): string; + getFormattingEditsForDocument(fileName: string, minChar: number, limChar: number, options: string): string; + getFormattingEditsOnPaste(fileName: string, minChar: number, limChar: number, options: string): string; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string): string; + getEmitOutput(fileName: string): string; + } + class LanguageServiceShimHostAdapter implements ILanguageServiceHost { + private shimHost; + constructor(shimHost: ILanguageServiceShimHost); + public information(): boolean; + public debug(): boolean; + public warning(): boolean; + public error(): boolean; + public fatal(): boolean; + public log(s: string): void; + public getCompilationSettings(): CompilationSettings; + public getScriptFileNames(): string[]; + public getScriptSnapshot(fileName: string): IScriptSnapshot; + public getScriptVersion(fileName: string): number; + public getScriptIsOpen(fileName: string): boolean; + public getScriptByteOrderMark(fileName: string): ByteOrderMark; + public getDiagnosticsObject(): ILanguageServicesDiagnostics; + public getLocalizedDiagnosticMessages(): any; + public resolveRelativePath(path: string, directory: string): string; + public fileExists(path: string): boolean; + public directoryExists(path: string): boolean; + public getParentDirectory(path: string): string; + } + function simpleForwardCall(logger: ILogger, actionDescription: string, action: () => any): any; + function forwardJSONCall(logger: ILogger, actionDescription: string, action: () => any): string; + class LanguageServiceShim extends ShimBase implements ILanguageServiceShim { + private host; + public languageService: ILanguageService; + private logger; + constructor(factory: IShimFactory, host: ILanguageServiceShimHost, languageService: ILanguageService); + public forwardJSONCall(actionDescription: string, action: () => any): string; + public dispose(dummy: any): void; + public refresh(throwOnError: boolean): void; + public cleanupSemanticCache(): void; + private static realizeDiagnosticCategory(category); + private static realizeDiagnostic(diagnostic); + private realizeDiagnosticWithFileName(diagnostic); + public getSyntacticDiagnostics(fileName: string): string; + public getSemanticDiagnostics(fileName: string): string; + public getCompilerOptionsDiagnostics(): string; + public getTypeAtPosition(fileName: string, position: number): string; + public getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string; + public getBreakpointStatementAtPosition(fileName: string, position: number): string; + public getSignatureAtPosition(fileName: string, position: number): string; + public getDefinitionAtPosition(fileName: string, position: number): string; + public getBraceMatchingAtPosition(fileName: string, position: number): string; + public getIndentationAtPosition(fileName: string, position: number, options: string): string; + public getReferencesAtPosition(fileName: string, position: number): string; + public getOccurrencesAtPosition(fileName: string, position: number): string; + public getImplementorsAtPosition(fileName: string, position: number): string; + public getCompletionsAtPosition(fileName: string, position: number, isMemberCompletion: boolean): string; + public getCompletionEntryDetails(fileName: string, position: number, entryName: string): string; + public getFormattingEditsForRange(fileName: string, minChar: number, limChar: number, options: string): string; + public getFormattingEditsForDocument(fileName: string, minChar: number, limChar: number, options: string): string; + public getFormattingEditsOnPaste(fileName: string, minChar: number, limChar: number, options: string): string; + public getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string): string; + public getNavigateToItems(searchValue: string): string; + public getScriptLexicalStructure(fileName: string): string; + public getOutliningRegions(fileName: string): string; + public getEmitOutput(fileName: string): string; + private _navigateToItemsToString(items); + } + class ClassifierShim extends ShimBase { + public host: IClassifierHost; + public classifier: Classifier; + constructor(factory: IShimFactory, host: IClassifierHost); + public getClassificationsForLine(text: string, lexState: EndOfLineState): string; + } + class CoreServicesShim extends ShimBase { + public host: ICoreServicesHost; + public logger: ILogger; + public services: CoreServices; + constructor(factory: IShimFactory, host: ICoreServicesHost); + private forwardJSONCall(actionDescription, action); + public getPreProcessedFileInfo(fileName: string, sourceText: IScriptSnapshot): string; + public getDefaultCompilationSettings(): string; + public dumpMemory(dummy: any): string; + public getMemoryInfo(dummy: any): string; + } +} +declare module TypeScript.Services { + class OutliningElementsCollector extends DepthLimitedWalker { + private static MaximumDepth; + private inObjectLiteralExpression; + private elements; + constructor(); + public visitClassDeclaration(node: ClassDeclarationSyntax): void; + public visitInterfaceDeclaration(node: InterfaceDeclarationSyntax): void; + public visitModuleDeclaration(node: ModuleDeclarationSyntax): void; + public visitEnumDeclaration(node: EnumDeclarationSyntax): void; + public visitFunctionDeclaration(node: FunctionDeclarationSyntax): void; + public visitFunctionExpression(node: FunctionExpressionSyntax): void; + public visitConstructorDeclaration(node: ConstructorDeclarationSyntax): void; + public visitMemberFunctionDeclaration(node: MemberFunctionDeclarationSyntax): void; + public visitGetAccessor(node: GetAccessorSyntax): void; + public visitSetAccessor(node: SetAccessorSyntax): void; + public visitObjectLiteralExpression(node: ObjectLiteralExpressionSyntax): void; + private addOutlineRange(node, startElement, endElement); + static collectElements(node: SourceUnitSyntax): TextSpan[]; + } +} +declare module TypeScript.Services { + class Indenter { + static getIndentation(node: SourceUnitSyntax, soruceText: IScriptSnapshot, position: number, editorOptions: EditorOptions): number; + private static belongsToBracket(sourceText, token, position); + private static isInContainerNode(parent, element); + private static getCustomListIndentation(list, element); + private static getListItemIndentation(list, elementIndex); + } +} +declare module TypeScript.Services.Breakpoints { + function getBreakpointLocation(syntaxTree: SyntaxTree, askedPos: number): SpanInfo; +} +declare module TypeScript.Services { + class GetScriptLexicalStructureWalker extends PositionTrackingWalker { + private fileName; + private nameStack; + private kindStack; + private currentMemberVariableDeclaration; + private currentVariableStatement; + private currentInterfaceDeclaration; + private parentScopes; + private currentScope; + private createScope(); + private pushNewContainerScope(containerName, kind); + private popScope(); + constructor(fileName: string); + private collectItems(items, scope?); + static getListsOfAllScriptLexicalStructure(items: NavigateToItem[], fileName: string, unit: SourceUnitSyntax): void; + private createItem(node, modifiers, kind, name); + private addAdditionalSpan(node, key); + private getKindModifiers(modifiers); + public visitModuleDeclaration(node: ModuleDeclarationSyntax): void; + private visitModuleDeclarationWorker(node, names, nameIndex); + private getModuleNames(node); + private getModuleNamesHelper(name, result); + public visitClassDeclaration(node: ClassDeclarationSyntax): void; + public visitInterfaceDeclaration(node: InterfaceDeclarationSyntax): void; + public visitObjectType(node: ObjectTypeSyntax): void; + public visitEnumDeclaration(node: EnumDeclarationSyntax): void; + public visitConstructorDeclaration(node: ConstructorDeclarationSyntax): void; + public visitMemberFunctionDeclaration(node: MemberFunctionDeclarationSyntax): void; + public visitGetAccessor(node: GetAccessorSyntax): void; + public visitSetAccessor(node: SetAccessorSyntax): void; + public visitMemberVariableDeclaration(node: MemberVariableDeclarationSyntax): void; + public visitVariableStatement(node: VariableStatementSyntax): void; + public visitVariableDeclarator(node: VariableDeclaratorSyntax): void; + public visitIndexSignature(node: IndexSignatureSyntax): void; + public visitEnumElement(node: EnumElementSyntax): void; + public visitCallSignature(node: CallSignatureSyntax): void; + public visitConstructSignature(node: ConstructSignatureSyntax): void; + public visitMethodSignature(node: MethodSignatureSyntax): void; + public visitPropertySignature(node: PropertySignatureSyntax): void; + public visitFunctionDeclaration(node: FunctionDeclarationSyntax): void; + public visitBlock(node: BlockSyntax): void; + public visitIfStatement(node: IfStatementSyntax): void; + public visitExpressionStatement(node: ExpressionStatementSyntax): void; + public visitThrowStatement(node: ThrowStatementSyntax): void; + public visitReturnStatement(node: ReturnStatementSyntax): void; + public visitSwitchStatement(node: SwitchStatementSyntax): void; + public visitWithStatement(node: WithStatementSyntax): void; + public visitTryStatement(node: TryStatementSyntax): void; + public visitLabeledStatement(node: LabeledStatementSyntax): void; + } +} +declare module TypeScript.Services { + function copyDataObject(dst: any, src: any): any; + class TypeScriptServicesFactory implements IShimFactory { + private _shims; + public createPullLanguageService(host: ILanguageServiceHost): ILanguageService; + public createLanguageServiceShim(host: ILanguageServiceShimHost): ILanguageServiceShim; + public createClassifier(host: IClassifierHost): Classifier; + public createClassifierShim(host: IClassifierHost): ClassifierShim; + public createCoreServices(host: ICoreServicesHost): CoreServices; + public createCoreServicesShim(host: ICoreServicesHost): CoreServicesShim; + public close(): void; + public registerShim(shim: IShim): void; + public unregisterShim(shim: IShim): void; + } +} +declare module TypeScript.Services { + class BraceMatcher { + static getMatchSpans(syntaxTree: SyntaxTree, position: number): TextSpan[]; + private static getMatchingCloseBrace(currentToken, position, result); + private static getMatchingOpenBrace(currentToken, position, result); + private static getMatchingCloseBraceTokenKind(positionedElement); + private static getMatchingOpenBraceTokenKind(positionedElement); + } +} + +declare module 'typescript-services' { + export = TypeScript; +} diff --git a/underscore.string/underscore.string.d.ts b/underscore.string/underscore.string.d.ts index db9ec042d4..9c828fdf7b 100644 --- a/underscore.string/underscore.string.d.ts +++ b/underscore.string/underscore.string.d.ts @@ -562,7 +562,8 @@ interface UnderscoreStringStaticExports { toBoolean(str: string, trueValues?: any[], falseValues?: any[]): boolean; } -declare module "underscore.string" { -export = UnderscoreStringStatic; +declare module 'underscore.string' { + var underscoreString: UnderscoreStringStatic; + export = underscoreString; } // TODO interface UnderscoreString extends Underscore diff --git a/underscore/underscore-tests.ts b/underscore/underscore-tests.ts index d3eb87f6aa..8b638ee508 100644 --- a/underscore/underscore-tests.ts +++ b/underscore/underscore-tests.ts @@ -3,10 +3,10 @@ declare var $; _.each([1, 2, 3], (num) => alert(num.toString())); -_.each({ one: 1, two: 2, three: 3 }, (value) => alert(value.toString())); +_.each({ one: 1, two: 2, three: 3 }, (value, key) => alert(value.toString())); _.map([1, 2, 3], (num) => num * 3); -_.map({ one: 1, two: 2, three: 3 }, (value: number, key?: string) => value * 3); +_.map({ one: 1, two: 2, three: 3 }, (value, key) => value * 3); //var sum = _.reduce([1, 2, 3], (memo, num) => memo + num, 0); // https://typescript.codeplex.com/workitem/1960 var sum = _.reduce([1, 2, 3], (memo, num) => memo + num, 0); @@ -16,21 +16,27 @@ var list = [[0, 1], [2, 3], [4, 5]]; //var flat = _.reduceRight(list, (a, b) => a.concat(b), []); // https://typescript.codeplex.com/workitem/1960 var flat = _.reduceRight(list, (a, b) => a.concat(b), []); -var even = _.find([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); +var even = _.find([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); -var evens = _.filter([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); +var firstCapitalLetter = _.find({ a: 'a', b: 'B', c: 'C', d: 'd' }, l => l === l.toUpperCase()); + +var evens = _.filter([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); + +var capitalLetters = _.filter({ a: 'a', b: 'B', c: 'C', d: 'd' }, l => l === l.toUpperCase()); var listOfPlays = [{ title: "Cymbeline", author: "Shakespeare", year: 1611 }, { title: "The Tempest", author: "Shakespeare", year: 1611 }, { title: "Other", author: "Not Shakespeare", year: 2012 }]; _.where(listOfPlays, { author: "Shakespeare", year: 1611 }); -var odds = _.reject([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); +var odds = _.reject([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); -//_.every([true, 1, null, 'yes'], _.identity); // https://typescript.codeplex.com/workitem/1960 -_.every([true, 1, null, 'yes'], _.identity); -_.every<{}>([true, 1, null, 'yes']); +_.every([true, 1, null, 'yes'], _.identity); _.any([null, 0, 'yes', false]); +_.some([1, 2, 3, 4], l => l % 3 === 0); + +_.some({ a: 'a', b: 'B', c: 'C', d: 'd' }, l => l === l.toUpperCase()); + _.contains([1, 2, 3], 3); _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); @@ -38,18 +44,18 @@ _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); var stooges = [{ name: 'moe', age: 40 }, { name: 'larry', age: 50 }, { name: 'curly', age: 60 }]; _.pluck(stooges, 'name'); -_.max<{ name: string; age: number }>(stooges, (stooge) => stooge.age); - -_.max([1, 2, 3, 4, 5]); +_.max(stooges, (stooge) => stooge.age); +_.min(stooges, (stooge) => stooge.age); var numbers = [10, 5, 100, 2, 1000]; +_.max(numbers); _.min(numbers); _.sortBy([1, 2, 3, 4, 5, 6], (num) => Math.sin(num)); _([1.3, 2.1, 2.4]).groupBy((e) => Math.floor(e)); -_.groupBy([1.3, 2.1, 2.4], (num: number) => Math.floor(num).toString()); +_.groupBy([1.3, 2.1, 2.4], (num) => Math.floor(num).toString()); _.groupBy(['one', 'two', 'three'], 'length'); _.indexBy(stooges, 'age')['40'].age; @@ -59,14 +65,25 @@ _(stooges) .indexBy('age') .value()['40'].age; -_.countBy([1, 2, 3, 4, 5], (num) => (num % 2 == 0) ? 'even' : 'odd'); +_.countBy([1, 2, 3, 4, 5], (num) => (num % 2 == 0) ? 'even' : 'odd'); _.shuffle([1, 2, 3, 4, 5, 6]); -(function(a, b, c, d){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4); +(function (a, b, c, d) { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); _.size({ one: 1, two: 2, three: 3 }); +_.partition([0, 1, 2, 3, 4, 5], (num) => {return num % 2 == 0 }); + +interface Family { + name: string; + relation: string; +} +var isUncleMoe = _.matches({ name: 'moe', relation: 'uncle' }); +_.filter([{ name: 'larry', relation: 'father' }, { name: 'moe', relation: 'uncle' }], isUncleMoe); + + + /////////////////////////////////////////////////////////////////////////////////////// _.first([5, 4, 3, 2, 1]); @@ -76,19 +93,19 @@ _.rest([5, 4, 3, 2, 1]); _.compact([0, 1, false, 2, '', 3]); _.flatten([1, 2, 3, 4]); -_.flatten([1, [2]]); +_.flatten([1, [2]]); // typescript doesn't like the elements being different -_.flatten([1, [2], [3, [[4]]]]); -_.flatten([1, [2], [3, [[4]]]], true); +_.flatten([1, [2], [3, [[4]]]]); +_.flatten([1, [2], [3, [[4]]]], true); _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); _.difference([1, 2, 3, 4, 5], [5, 2, 10]); _.uniq([1, 2, 1, 3, 1, 4]); _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); -var r = _.object<{ [key: string]: number }>(['moe', 'larry', 'curly'], [30, 40, 50]); -_.object([['moe', 30], ['larry', 40], ['curly', 50]]); +var r = _.object(['moe', 'larry', 'curly'], [30, 40, 50]); +_.object([['moe', 30], ['larry', 40], ['curly', 50]]); _.indexOf([1, 2, 3], 2); _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); _.sortedIndex([10, 20, 30, 40, 50], 35); @@ -172,18 +189,15 @@ _.clone(['i', 'am', 'an', 'object!']); _([1, 2, 3, 4]) .chain() - .filter((num: number) => { - return num % 2 == 0; - }).tap(alert) - .map((num: number) => { - return num * num; - }) + .filter((num) => { return num % 2 == 0; }) + .tap(alert) + .map((num) => { return num * num; }) .value(); _.chain([1, 2, 3, 200]) - .filter(function (num: number) { return num % 2 == 0; }) + .filter((num) => { return num % 2 == 0; }) .tap(alert) - .map(function (num: number) { return num * num }) + .map((num) => { return num * num; }) .value(); _.has({ a: 1, b: 2, c: 3 }, "b"); @@ -204,6 +218,8 @@ _.isArray([1, 2, 3]); _.isObject({}); _.isObject(1); +_.property('name')(moe); + // (() => { return _.isArguments(arguments); })(1, 2, 3); _.isArguments([1, 2, 3]); @@ -235,13 +251,18 @@ _.isUndefined((window).missingVariable); /////////////////////////////////////////////////////////////////////////////////////// +var UncleMoe = { name: 'moe' }; +_.constant(UncleMoe)(); + +typeof _.now() === "number"; + var underscore = _.noConflict(); var moe2 = { name: 'moe' }; moe2 === _.identity(moe); var genie; -var r2 = _.times(3, (n) => { return n * n }); +var r2 = _.times(3, (n) => { return n * n }); _(3).times(function (n) { genie.grantWishNumber(n); }); _.random(0, 100); @@ -283,30 +304,32 @@ _(['test', 'test']).pick(['test2', 'test2']); //////////////// Chain Tests function chain_tests() { // https://typescript.codeplex.com/workitem/1960 - var numArray: number[] = _.chain([1, 2, 3, 4, 5, 6, 7, 8]) + var numArray = _.chain([1, 2, 3, 4, 5, 6, 7, 8]) .filter(num => num % 2 == 0) .map(num => num * num) .value(); - var strArray: string[] = _([1, 2, 3, 4]) + var strArray = _([1, 2, 3, 4]) .chain() .filter(num => num % 2 == 0) .tap(alert) .map(num => "string" + num) .value(); - var n : number = _.chain([1, 2, 3, 200]) + var n = _.chain([1, 2, 3, 200]) .filter(num => num % 2 == 0) .tap(alert) .map(num => num * num) .max() .value(); - //If using alternate definition of map (~ line 2200), .value returns any - // because.map matches _Chain as opposed to _ChainOfArrays , which breaks typing on flatten - var hoverOverValueShouldBeNumberNotAny : number = _([1, 2, 3]).chain() - .map(num=> [num, num + 1]) + var hoverOverValueShouldBeNumberNotAny = _([1, 2, 3]).chain() + .map(num => [num, num + 1]) .flatten() .find(num => num % 2 == 0) .value(); + + var firstVal: number = _.chain([1, 2, 3]) + .first() + .value(); } diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 9e44c0c63e..7d9c84f826 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -1,7 +1,6 @@ -// Type definitions for Underscore 1.5.2 +// Type definitions for Underscore 1.6.0 // Project: http://underscorejs.org/ -// Definitions by: Boris Yankov -// Definitions by: Josh Baldwin +// Definitions by: Boris Yankov , Josh Baldwin // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module _ { @@ -23,7 +22,7 @@ declare module _ { /** * underscore.js template settings, set templateSettings or pass as an argument - * to 'template()' to overide defaults. + * to 'template()' to override defaults. **/ interface TemplateSettings { /** @@ -92,34 +91,34 @@ interface UnderscoreStatic { each( list: _.List, iterator: _.ListIterator, - context?: any): void; + context?: any): _.List; /** * @see _.each - * @param object Iterators over this object's properties. - * @param iterator Iterator function for each property on `obj`. + * @param object Iterates over properties of this object. + * @param iterator Iterator function for each property on `object`. * @param context 'this' object in `iterator`, optional. **/ each( object: _.Dictionary, iterator: _.ObjectIterator, - context?: any): void; + context?: any): _.Dictionary; /** * @see _.each **/ forEach( list: _.List, - iterator: _.ListIterator, - context?: any): void; + iterator: _.ListIterator, + context?: any): _.List; /** * @see _.each **/ forEach( object: _.Dictionary, - iterator: _.ObjectIterator, - context?: any): void; + iterator: _.ObjectIterator, + context?: any): _.Dictionary; /** * Produces a new array of values by mapping each value in list through a transformation function @@ -138,7 +137,7 @@ interface UnderscoreStatic { /** * @see _.map * @param object Maps the properties of this object. - * @param iterator Map iterator function for each property on `obj`. + * @param iterator Map iterator function for each property on `object`. * @param context `this` object in `iterator`, optional. * @return The mapped object result. **/ @@ -151,8 +150,8 @@ interface UnderscoreStatic { * @see _.map **/ collect( - list: _.List, iterator: - _.ListIterator, + list: _.List, + iterator: _.ListIterator, context?: any): TResult[]; /** @@ -200,7 +199,7 @@ interface UnderscoreStatic { /** * The right-associative version of reduce. Delegates to the JavaScript 1.8 version of - * reduceRight, if it exists. Foldr is not as useful in JavaScript as it would be in a + * reduceRight, if it exists. `foldr` is not as useful in JavaScript as it would be in a * language with lazy evaluation. * @param list Reduces the elements of this array. * @param iterator Reduce iterator function for each element in `list`. @@ -233,7 +232,23 @@ interface UnderscoreStatic { * @return The first acceptable found element in `list`, if nothing is found undefined/null is returned. **/ find( - list: _.Collection, + list: _.List, + iterator: _.ListIterator, + context?: any): T; + + /** + * @see _.find + **/ + find( + object: _.Dictionary, + iterator: _.ObjectIterator, + context?: any): T; + + /** + * @see _.find + **/ + detect( + list: _.List, iterator: _.ListIterator, context?: any): T; @@ -241,8 +256,8 @@ interface UnderscoreStatic { * @see _.find **/ detect( - list: _.Collection, - iterator: _.ListIterator, + object: _.Dictionary, + iterator: _.ObjectIterator, context?: any): T; /** @@ -254,7 +269,23 @@ interface UnderscoreStatic { * @return The filtered list of elements. **/ filter( - list: _.Collection, + list: _.List, + iterator: _.ListIterator, + context?: any): T[]; + + /** + * @see _.filter + **/ + filter( + object: _.Dictionary, + iterator: _.ObjectIterator, + context?: any): T[]; + + /** + * @see _.filter + **/ + select( + list: _.List, iterator: _.ListIterator, context?: any): T[]; @@ -262,8 +293,8 @@ interface UnderscoreStatic { * @see _.filter **/ select( - list: _.Collection, - iterator: _.ListIterator, + object: _.Dictionary, + iterator: _.ObjectIterator, context?: any): T[]; /** @@ -274,7 +305,7 @@ interface UnderscoreStatic { * @return The elements within `list` that contain the required `properties`. **/ where( - list: _.Collection, + list: _.List, properties: U): T[]; /** @@ -297,10 +328,18 @@ interface UnderscoreStatic { * @return The rejected list of elements. **/ reject( - list: _.Collection, + list: _.List, iterator: _.ListIterator, context?: any): T[]; + /** + * @see _.reject + **/ + reject( + object: _.Dictionary, + iterator: _.ObjectIterator, + context?: any): T[]; + /** * Returns true if all of the values in the list pass the iterator truth test. Delegates to the * native method every, if present. @@ -310,18 +349,34 @@ interface UnderscoreStatic { * @return True if all elements passed the truth test, otherwise false. **/ every( - list: _.Collection, + list: _.List, iterator?: _.ListIterator, context?: any): boolean; /** - * @see _.all + * @see _.every + **/ + every( + list: _.Dictionary, + iterator?: _.ObjectIterator, + context?: any): boolean; + + /** + * @see _.every **/ all( - list: _.Collection, + list: _.List, iterator?: _.ListIterator, context?: any): boolean; + /** + * @see _.every + **/ + all( + list: _.Dictionary, + iterator?: _.ObjectIterator, + context?: any): boolean; + /** * Returns true if any of the values in the list pass the iterator truth test. Short-circuits and * stops traversing the list if a true element is found. Delegates to the native method some, if present. @@ -330,19 +385,35 @@ interface UnderscoreStatic { * @param context `this` object in `iterator`, optional. * @return True if any elements passed the truth test, otherwise false. **/ - any( - list: _.Collection, + some( + list: _.List, iterator?: _.ListIterator, context?: any): boolean; /** - * @see _.any + * @see _.some **/ some( - list: _.Collection, + object: _.Dictionary, + iterator?: _.ObjectIterator, + context?: any): boolean; + + /** + * @see _.some + **/ + any( + list: _.List, iterator?: _.ListIterator, context?: any): boolean; + /** + * @see _.some + **/ + any( + object: _.Dictionary, + iterator?: _.ObjectIterator, + context?: any): boolean; + /** * Returns true if the value is present in the list. Uses indexOf internally, * if list is an Array. @@ -351,7 +422,14 @@ interface UnderscoreStatic { * @return True if `value` is present in `list`, otherwise false. **/ contains( - list: _.Collection, + list: _.List, + value: T): boolean; + + /** + * @see _.contains + **/ + contains( + object: _.Dictionary, value: T): boolean; /** @@ -361,6 +439,13 @@ interface UnderscoreStatic { list: _.Collection, value: T): boolean; + /** + * @see _.contains + **/ + include( + object: _.Dictionary, + value: T): boolean; + /** * Calls the method named by methodName on each value in the list. Any extra arguments passed to * invoke will be forwarded on to the method invocation. @@ -369,7 +454,7 @@ interface UnderscoreStatic { * @param arguments Additional arguments to pass to the method `methodName`. **/ invoke( - list: _.Collection, + list: _.List, methodName: string, ...arguments: any[]): any; @@ -381,7 +466,7 @@ interface UnderscoreStatic { * @return The list of elements within `list` that have the property `propertyName`. **/ pluck( - list: _.Collection, + list: _.List, propertyName: string): any[]; /** @@ -400,7 +485,7 @@ interface UnderscoreStatic { * @return The maximum element within `list`. **/ max( - list: _.Collection, + list: _.List, iterator?: _.ListIterator, context?: any): T; @@ -420,7 +505,7 @@ interface UnderscoreStatic { * @return The minimum element within `list`. **/ min( - list: _.Collection, + list: _.List, iterator?: _.ListIterator, context?: any): T; @@ -497,7 +582,7 @@ interface UnderscoreStatic { * @return An object with the group names as properties where each property contains the number of elements in that group. **/ countBy( - list: _.Collection, + list: _.List, iterator?: _.ListIterator, context?: any): _.Dictionary; @@ -506,7 +591,7 @@ interface UnderscoreStatic { * @param iterator Function name **/ countBy( - list: _.Collection, + list: _.List, iterator: string, context?: any): _.Dictionary; @@ -544,6 +629,19 @@ interface UnderscoreStatic { **/ size(list: _.Collection): number; + /** + * Split array into two arrays: + * one whose elements all satisfy predicate and one whose elements all do not satisfy predicate. + * @param array Array to split in two. + * @param iterator Filter iterator function for each element in `array`. + * @param context `this` object in `iterator`, optional. + * @return Array where Array[0] are the elements in `array` that satisfies the predicate, and Array[1] the elements that did not. + **/ + partition( + array: Array, + iterator: _.ListIterator, + context?: any): T[][]; + /********* * Arrays * **********/ @@ -590,7 +688,7 @@ interface UnderscoreStatic { /** * Returns everything but the last entry of the array. Especially useful on the arguments object. * Pass n to exclude the last n elements from the result. - * @param array Retreive all elements except the last `n`. + * @param array Retrieve all elements except the last `n`. * @param n Leaves this many elements behind, optional. * @return Returns everything but the last `n` elements of `array`. **/ @@ -698,7 +796,7 @@ interface UnderscoreStatic { * advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If * you want to compute unique items based on a transformation, pass an iterator function. * @param array Array to remove duplicates from. - * @param isSorted True if `array` is already sorted, optiona, default = false. + * @param isSorted True if `array` is already sorted, optional, default = false. * @param iterator Transform the elements of `array` before comparisons for uniqueness. * @param context 'this' object in `iterator`, optional. * @return Copy of `array` where all elements are unique. @@ -804,7 +902,7 @@ interface UnderscoreStatic { * @param array The array to search for the last index of `value`. * @param value The value to search for within `array`. * @param from The starting index for the search, optional. - * @return The index of the last occurance of `value` within `array`. + * @return The index of the last occurrence of `value` within `array`. **/ lastIndexOf( array: _.List, @@ -880,7 +978,8 @@ interface UnderscoreStatic { /** * Partially apply a function by filling in any number of its arguments, without changing its dynamic this value. - * A close cousin of bind. + * A close cousin of bind. You may pass _ in your list of arguments to specify an argument that should not be + * pre-filled, but left open to supply at call-time. * @param fn Function to partially fill in arguments. * @param arguments The partial arguments. * @return `fn` with partially filled in arguments. @@ -905,7 +1004,7 @@ interface UnderscoreStatic { /** * Much like setTimeout, invokes function after wait milliseconds. If you pass the optional arguments, * they will be forwarded on to the function when it is invoked. - * @param fn Function to delay `waitMS` amount of ms. + * @param func Function to delay `waitMS` amount of ms. * @param wait The amount of milliseconds to delay `fn`. * @arguments Additional arguments to pass to `fn`. **/ @@ -941,7 +1040,7 @@ interface UnderscoreStatic { * if you call it again any number of times during the wait period, as soon as that period is over. * If you'd like to disable the leading-edge call, pass {leading: false}, and if you'd like to disable * the execution on the trailing-edge, pass {trailing: false}. - * @param fn Function to throttle `waitMS` ms. + * @param func Function to throttle `waitMS` ms. * @param wait The number of milliseconds to wait before `fn` can be invoked again. * @param options Allows for disabling execution of the throttled function on either the leading or trailing edge. * @return `fn` with a throttle of `wait`. @@ -1017,14 +1116,14 @@ interface UnderscoreStatic { /** * Retrieve all the names of the object's properties. - * @param object Retreive the key or property names from this object. + * @param object Retrieve the key or property names from this object. * @return List of all the property names on `object`. **/ keys(object: any): string[]; /** * Return all of the values of the object's properties. - * @param object Retreive the values of all the properties on this object. + * @param object Retrieve the values of all the properties on this object. * @return List of all the values on `object`. **/ values(object: any): any[]; @@ -1134,6 +1233,20 @@ interface UnderscoreStatic { **/ has(object: any, key: string): boolean; + /** + * Returns a predicate function that will tell you if a passed in object contains all of the key/value properties present in attrs. + * @param attrs Object with key values pair + * @return Predicate function + **/ + matches(attrs: T): _.ListIterator; + + /** + * Returns a function that will itself return the key property of any passed-in object. + * @param key Property of the object. + * @return Function which accept an object an returns the value of key in that object. + **/ + property(key: string): (object: Object) => any; + /** * Performs an optimized deep comparison between the two objects, * to determine if they should be considered equal. @@ -1270,6 +1383,13 @@ interface UnderscoreStatic { **/ identity(value: T): T; + /** + * Creates a function that returns the same value that is used as the argument of _.constant + * @param value Identity of this object. + * @return Function that return value. + **/ + constant(value: T): () => T; + /** * Invokes the given iterator function n times. * Each invocation of iterator is called with an index argument @@ -1322,6 +1442,13 @@ interface UnderscoreStatic { **/ escape(str: string): string; + /** + * The opposite of escape, replaces &, <, >, ", and ' with their unescaped counterparts. + * @param str HTML escaped string. + * @return `str` Raw string. + **/ + unescape(str: string): string; + /** * If the value of the named property is a function then invoke it; otherwise, return it. * @param object Object to maybe invoke function `property` on. @@ -1353,6 +1480,11 @@ interface UnderscoreStatic { **/ templateSettings: _.TemplateSettings; + /** + * Returns an integer timestamp for the current time, using the fastest method available in the runtime. Useful for implementing timing/animation functions. + **/ + now(): number; + /* ********** * Chaining * *********** */ @@ -1384,22 +1516,22 @@ interface Underscore { * Wrapped type `any[]`. * @see _.each **/ - each(iterator: _.ListIterator, context?: any): void; + each(iterator: _.ListIterator, context?: any): T[]; /** * @see _.each **/ - each(iterator: _.ObjectIterator, context?: any): void; + each(iterator: _.ObjectIterator, context?: any): T[]; /** * @see _.each **/ - forEach(iterator: _.ListIterator, context?: any): void; + forEach(iterator: _.ListIterator, context?: any): T[]; /** * @see _.each **/ - forEach(iterator: _.ObjectIterator, context?: any): void; + forEach(iterator: _.ObjectIterator, context?: any): T[]; /** * Wrapped type `any[]`. @@ -1737,6 +1869,12 @@ interface Underscore { **/ without(...values: T[]): T[]; + /** + * Wrapped type `any[]`. + * @see _.partition + **/ + partition(iterator: _.ListIterator, context?: any): T[][]; + /** * Wrapped type `any[][]`. * @see _.union @@ -1993,6 +2131,18 @@ interface Underscore { **/ has(key: string): boolean; + /** + * Wrapped type `any[]`. + * @see _.matches + **/ + matches(): _.ListIterator; + + /** + * Wrapped type `string`. + * @see _.property + **/ + property(): (object: Object) => any; + /** * Wrapped type `object`. * @see _.isEqual @@ -2099,6 +2249,12 @@ interface Underscore { **/ identity(): any; + /** + * Wrapped type `any`. + * @see _.constant + **/ + constant(): () => T; + /** * Wrapped type `number`. * @see _.times @@ -2134,6 +2290,12 @@ interface Underscore { **/ escape(): string; + /** + * Wrapped type `string`. + * @see _.unescape + **/ + unescape(): string; + /** * Wrapped type `object`. * @see _.result @@ -2173,30 +2335,28 @@ interface _Chain { * Wrapped type `any[]`. * @see _.each **/ - each(iterator: _.ListIterator, context?: any): _Chain; + each(iterator: _.ListIterator, context?: any): _Chain; /** * @see _.each **/ - each(iterator: _.ObjectIterator, context?: any): _Chain; + each(iterator: _.ObjectIterator, context?: any): _Chain; /** * @see _.each **/ - forEach(iterator: _.ListIterator, context?: any): _Chain; + forEach(iterator: _.ListIterator, context?: any): _Chain; /** * @see _.each **/ - forEach(iterator: _.ObjectIterator, context?: any): _Chain; + forEach(iterator: _.ObjectIterator, context?: any): _Chain; /** * Wrapped type `any[]`. * @see _.map **/ - map(iterator: (value: T, index: number, list: T[]) => TArray[], context?: any): _ChainOfArrays; - //Not sure why this won't work, might be a TypeScript error? - //map(iterator: _.ListIterator, context?: any): _ChainOfArrays; + map(iterator: _.ListIterator, context?: any): _ChainOfArrays; /** * Wrapped type `any[]`. @@ -2208,10 +2368,8 @@ interface _Chain { * Wrapped type `any[]`. * @see _.map **/ - map(iterator: (element: T, key: string, list: any) => TArray[], context?: any): _ChainOfArrays; - //Not sure why this won't work, might be a TypeScript error? - //map(iterator: _.ObjectIterator, context?: any): _ChainOfArrays; - + map(iterator: _.ObjectIterator, context?: any): _ChainOfArrays; + /** * Wrapped type `any[]`. * @see _.map @@ -2462,7 +2620,7 @@ interface _Chain { * Wrapped type `any[]`. * @see _.first **/ - first(): _Chain; + first(): _ChainSingle; /** * Wrapped type `any[]`. @@ -2542,6 +2700,12 @@ interface _Chain { **/ without(...values: T[]): _Chain; + /** + * Wrapped type `any[]`. + * @see _.partition + **/ + partition(iterator: _.ListIterator, context?: any): _Chain; + /** * Wrapped type `any[][]`. * @see _.union @@ -2796,6 +2960,18 @@ interface _Chain { **/ has(key: string): _Chain; + /** + * Wrapped type `any[]`. + * @see _.matches + **/ + matches(): _Chain; + + /** + * Wrapped type `string`. + * @see _.property + **/ + property(): _Chain; + /** * Wrapped type `object`. * @see _.isEqual @@ -2902,6 +3078,12 @@ interface _Chain { **/ identity(): _Chain; + /** + * Wrapped type `any`. + * @see _.constant + **/ + constant(): _Chain; + /** * Wrapped type `number`. * @see _.times @@ -2937,6 +3119,12 @@ interface _Chain { **/ escape(): _Chain; + /** + * Wrapped type `string`. + * @see _.unescape + **/ + unescape(): _Chain; + /** * Wrapped type `object`. * @see _.result diff --git a/velocity-animate/velocity-animate-tests.ts b/velocity-animate/velocity-animate-tests.ts new file mode 100644 index 0000000000..96400d3650 --- /dev/null +++ b/velocity-animate/velocity-animate-tests.ts @@ -0,0 +1,295 @@ +/// + +function basics_arguments() { + var $el: JQuery; + $el.velocity({ + top: 10, + left: 10 + }, { + /* Velocity's default options: */ + duration: 400, + easing: "swing", + queue: "", + begin: null, + progress: null, + complete: null, + loop: false, + delay: false, + display: false, + mobileHA: true + }); + + $el.velocity({ top: 50 }, 1000); + $el.velocity({ top: 50 }, 1000, "swing"); + $el.velocity({ top: 50 }, "swing"); + $el.velocity({ top: 50 }, 1000, function() { alert("Hi"); }); + + $el.velocity({ + properties: { opacity: 1 }, + options: { duration: 500 } + }); +} + +function basics_values() { + var $el: JQuery; + $el.velocity({ + top: 50, // Defaults to the px unit type + left: "50%", + width: "+=5rem", // Add 5rem to the current rem value + height: "*=2" // Double the current height + }); +} + +function options_duration() { + var $el: JQuery; + $el.velocity({ opacity: 1 }, { duration: 1000 }); + $el.velocity({ opacity: 1 }, { duration: "slow" }); +} + +function options_easing() { + var $el: JQuery; + /* Use one of the jQuery UI easings. */ + $el.velocity({ width: 50 }, "easeInSine"); + /* Use a custom bezier curve. */ + $el.velocity({ width: 50 }, [ 0.17, 0.67, 0.83, 0.67 ]); + /* Use spring physics. */ + $el.velocity({ width: 50 }, [ 250, 15 ]); + + $el.velocity({ + borderBottomWidth: [ "2px", "spring" ], // Uses "spring" + width: [ "100px", [ 250, 15 ] ], // Uses custom spring physics + height: "100px" // Defaults to easeInSine + }, { + easing: "easeInSine" // The call's default easing + }); +} + +function options_queue() { + var $el: JQuery; + /* Trigger the first animation: Animate width. */ + $el.velocity({ width: "500px" }, { duration: 10000 }); + /* Trigger the second animation: Animate height. */ + setTimeout(function() { + /* Will run in parallel starting at the 5000ms mark. */ + $el.velocity({ height: "500px" }, { queue: false }); + }, 5000); +} + +function options_complete() { + var $el: JQuery; + $el.velocity({ + opacity: 0 + }, { + /* Logs all the animated divs. */ + complete: function(elements) { console.log(elements); } + }); +} + +function options_begin() { + var $el: JQuery; + $el.velocity({ + opacity: 0 + }, { + /* Logs all the animated divs. */ + begin: function(elements) { console.log(elements); } + }); +} + +function options_progress() { + var $el: JQuery; + var $percentComplete: JQuery; + var $timeRemaining: JQuery; + $el.velocity({ + opacity: 0 + }, { + progress: function(elements, percentComplete, timeRemaining, timeStart) { + $percentComplete.html((percentComplete * 100) + "%"); + $timeRemaining.html(timeRemaining + "ms remaining!"); + } + }); +} + +function options_mobileHA() { + var $el: JQuery; + $el.velocity({ height: "10em" }, { mobileHA: false }); +} + +function options_loop() { + var $el: JQuery; + $el.velocity({ height: "10em" }, { loop: 2 }); +} + +function options_delay() { + var $el: JQuery; + $el.velocity({ + height: "+=10em" + }, { + loop: 4, + /* Wait 100ms before alternating. */ + delay: 100 + }); +} + +function options_display() { + var $el: JQuery; + /* Animate down to zero then set display to "none". */ + $el.velocity({ opacity: 0 }, { display: "none" }); + /* Set display to "block" then animate from opacity:0. */ + $el.velocity({ opacity: 1 }, { display: "block" }); +} + +function command_scroll() { + var $el: JQuery; + $el + .velocity("scroll", { duration: 1500, easing: "spring" }) + .velocity({ opacity: 1 }); + + /* Scroll container to the top of the targeted div. */ + $el.velocity("scroll", { container: $("#container") }); + + /* Scroll the browser to the LEFT edge of the targeted div. */ + $el.velocity("scroll", { axis: "x" }); + + /* Scroll to a position 50 pixels above the div. */ + $el + .velocity("scroll", { duration: 750, offset: -50 }) + /* Then scroll to a position 250 pixels beyond the div. */ + .velocity("scroll", { duration: 750, offset: 250 }); +} + +function command_stop() { + var $el: JQuery; + $el.velocity("stop"); +} + +function command_reverse() { + var $el: JQuery; + $el.velocity("reverse"); + $el.velocity("reverse", { duration: 2000 }); +} + +function command_fadeIn_fadeOut() { + var $el: JQuery; + $el + .velocity("fadeIn", { duration: 1500 }) + .velocity("fadeOut", { delay: 500, duration: 1500 }); +} + +function command_slideDown_slideUp() { + var $el: JQuery; + $el + .velocity("slideDown", { duration: 1500 }) + .velocity("slideUp", { delay: 500, duration: 1500 }); +} + +function feature_transforms() { + var $el: JQuery; + /* Translate to the right and rotate clockwise. */ + $el.velocity({ + translateX: "200px", + rotateZ: "45deg" + }); + + /* Translate to the right and rotate clockwise. */ + $el.velocity({ + translateZ: 0, // Force HA by animating a 3D property + translateX: "200px", + rotateZ: "45deg" + }); +} + +function feature_hooks() { + var $el: JQuery; + $el.velocity({ textShadowBlur: "10px" }); +} + +function feature_colors() { + var $el: JQuery; + $el.velocity({ + /* Animate red to 50% (0.5 * 255). */ + colorRed: "50%", + /* Concurrently animate to a richer blue. */ + colorBlue: "+=50", + /* Fade the text down to 85% opacity. */ + colorAlpha: 0.85 + }); +} + +function feature_sequences() { + var $el: JQuery; + $.Velocity.Sequences.hover = function (element: HTMLElement, options: {duration?: number}) { + var duration = options.duration || 750; + $.Velocity.animate(element, + { + translateY: "-=10px", + }, { + /* Delay is relative to user-adjustable duration. */ + delay: duration * 0.033, + duration: duration, + loop: 3, + easing: "easeInOutSine" + }); + }; + + /* Later on in your code, trigger the sequence: */ + /* Note: As normal, you may optionally pass in options. */ + $el.velocity("hover", { duration: 450 }); + + $.Velocity.Sequences.hover = function (element: HTMLElement, options: {duration?: number}) { + var duration = options.duration || 750; + /* Pre-construct animation maps before chaining. */ + var calls = [ + { + properties: { translateY: "-10px" }, + options: { + delay: duration * 0.033, + duration: duration, + loop: 3, + easing: "easeInOutSine" + } + } + ]; + /* Iteratively chain the calls. */ + $.each(calls, function(i, call) { + $.Velocity.animate( + element, + call.properties, + call.options + ); + }); + }; +} + +function advanced_value_functions() { + var $el: JQuery; + $el.velocity({ + opacity: function() { return Math.random() } + }); + $el.velocity({ + translateX: function(i: number, total: number) { + /* Generate translateX's end value. */ + return (i * 10) + "px"; + } + }); +} + +function advanced_forcefeeding() { + var $el: JQuery; + $el.velocity({ + translateX: [ 500, 0 ], + opacity: [ 0, "easeInSine", 1 ] + }); + $el + .velocity({ translateX: [ 500, 0 ] }) + .velocity({ translateX: 1000 }); +} + +function advanced_utility_function () { + var divs = document.getElementsByTagName("div"); + $.Velocity.animate(divs, { opacity: 0 }, { duration: 1500 }); + $.Velocity.animate({ + elements: divs, + properties: { opacity: 0 }, + options: { duration: 1500 } + }); +} diff --git a/velocity-animate/velocity-animate.d.ts b/velocity-animate/velocity-animate.d.ts new file mode 100644 index 0000000000..00c4218965 --- /dev/null +++ b/velocity-animate/velocity-animate.d.ts @@ -0,0 +1,52 @@ +// Type definitions for Velocity 0.0.22 +// Project: http://velocityjs.org/ +// Definitions by: Greg Smith +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface JQuery { + velocity(options: {properties: Object; options: jquery.velocity.VelocityOptions}): JQuery; + velocity(properties: Object, options: jquery.velocity.VelocityOptions): JQuery; + velocity(properties: Object, duration?: number, easing?: string, complete?: jquery.velocity.ElementCallback): JQuery; + velocity(properties: Object, duration?: number, easing?: number[], complete?: jquery.velocity.ElementCallback): JQuery; + velocity(properties: Object, duration?: number, complete?: jquery.velocity.ElementCallback): JQuery; + velocity(properties: Object, easing?: string, complete?: jquery.velocity.ElementCallback): JQuery; + velocity(properties: Object, easing?: number[], complete?: jquery.velocity.ElementCallback): JQuery; + velocity(properties: Object, complete?: jquery.velocity.ElementCallback): JQuery; +} + +interface JQueryStatic { + Velocity: jquery.velocity.VelocityStatic; +} + +declare module jquery.velocity { + interface ElementCallback { + (elements: NodeListOf): void; + } + + interface ProgressCallback { + (elements: NodeListOf, percentComplete: number, timeRemaining: number, timeStart: number): void; + } + + interface VelocityStatic { + Sequences: any; + animate(options: {elements: NodeListOf; properties: Object; options: VelocityOptions}): void; + animate(elements: NodeListOf, properties: Object, options: VelocityOptions): void; + animate(element: HTMLElement, properties: Object, options: VelocityOptions): void; + } + + interface VelocityOptions { + queue?: any; + duration?: any; + easing?: any; + begin?: ElementCallback; + complete?: ElementCallback; + progress?: ProgressCallback; + display?: any; + loop?: any; + delay?: any; + mobileHA?: boolean; + _cacheValues?: boolean; + } +} diff --git a/viewporter/viewporter.d.ts b/viewporter/viewporter.d.ts index c0f441c032..1e85cc5f6c 100644 --- a/viewporter/viewporter.d.ts +++ b/viewporter/viewporter.d.ts @@ -1,6 +1,6 @@ // Type definitions for Zynga Viewporter v2.1 // Project: https://github.com/zynga/viewporter -// Definitions by: Boris Yankov https://github.com/borisyankov +// Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Viewporter { @@ -15,4 +15,4 @@ interface Viewporter { refresh(): void; } -declare var viewporter: Viewporter; \ No newline at end of file +declare var viewporter: Viewporter; diff --git a/vinyl-fs/vinyl-fs-tests.ts b/vinyl-fs/vinyl-fs-tests.ts new file mode 100644 index 0000000000..016da5e8b3 --- /dev/null +++ b/vinyl-fs/vinyl-fs-tests.ts @@ -0,0 +1,531 @@ +/// +/// + +/// + +/// + + +// from src + +import vfs = require('vinyl-fs'); + +import path = require('path'); +import fs = require('fs'); // require('graceful-fs'); + +// import bufEqual = require('buffer-equal'); +declare var bufEqual: any; +// import through = require('through2'); +declare var through: any; +import File = require('vinyl'); + +import should = require('should'); +require('mocha'); + +declare var gulp: any; +declare var bufferStream: any; + +var dataWrap = function(fn:any) { + return function(data:any, enc:any, cb:any) { + fn(data); + cb(); + }; +}; + +describe('source stream', function() { + + it('should explode on invalid glob (empty)', function(done) { + var stream:any; + try { + stream = gulp.src(); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should explode on invalid glob (number)', function(done) { + var stream:any; + try { + stream = gulp.src(123); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should explode on invalid glob (empty array)', function(done) { + var stream:any; + try { + stream = gulp.src([]); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should pass through writes', function(done) { + var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + var expectedContent = fs.readFileSync(expectedPath); + + var expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: expectedPath, + contents: expectedContent + }); + + var onEnd = function(){ + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + var stream = vfs.src("./fixtures/nothing.coffee"); + + var buffered:any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should glob a file with default settings', function(done) { + var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + var expectedContent = fs.readFileSync(expectedPath); + + var onEnd = function(){ + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isBuffer().should.equal(true); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + var stream = vfs.src("./fixtures/*.coffee", {cwd: __dirname}); + + var buffered:any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with default settings and relative cwd', function(done) { + var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + var expectedContent = fs.readFileSync(expectedPath); + + var onEnd = function(){ + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isBuffer().should.equal(true); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + var stream = vfs.src("./fixtures/*.coffee", {cwd: path.relative(process.cwd(), __dirname)}); + + var buffered:any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a directory with default settings', function(done) { + var expectedPath = path.join(__dirname, "./fixtures/wow"); + + var onEnd = function(){ + buffered.length.should.equal(1); + buffered[0].path.should.equal(expectedPath); + buffered[0].isNull().should.equal(true); + buffered[0].isDirectory().should.equal(true); + done(); + }; + + var stream = vfs.src("./fixtures/wow/", {cwd: __dirname}); + + var buffered:any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with with no contents', function(done) { + var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + var expectedContent = fs.readFileSync(expectedPath); + + var onEnd = function(){ + buffered.length.should.equal(1); + buffered[0].path.should.equal(expectedPath); + buffered[0].isNull().should.equal(true); + should.not.exist(buffered[0].contents); + done(); + }; + + var stream = vfs.src("./fixtures/*.coffee", {cwd: __dirname, read: false}); + + var buffered:any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with streaming contents', function(done) { + var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + var expectedContent = fs.readFileSync(expectedPath); + + var onEnd = function(){ + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isStream().should.equal(true); + + var contentBuffer = new Buffer([]); + var contentBufferStream = through(dataWrap(function(data:any){ + contentBuffer = Buffer.concat([contentBuffer, data]); + })); + buffered[0].contents.pipe(contentBufferStream); + buffered[0].contents.once('end', function(){ + bufEqual(contentBuffer, expectedContent); + done(); + }); + }; + + var stream = vfs.src("./fixtures/*.coffee", {cwd: __dirname, buffer: false}); + + var buffered:any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + +}); + +// from dest +// var vfs = require('../'); + +// var path = require('path'); +// var fs = require('graceful-fs'); +import rimraf = require('rimraf'); + +// var bufEqual = require('buffer-equal'); +// var through = require('through2'); +// var File = require('vinyl'); + +// var should = require('should'); +require('mocha'); + +var wipeOut = function(cb:any) { + rimraf(path.join(__dirname, "./out-fixtures/"), cb); +}; + +var dataWrap = function(fn:any) { + return function(data:any, enc:any, cb:any) { + fn(data); + cb(); + }; +}; + +var realMode = function(n:any) { + return n & 07777; +}; + +describe('dest stream', function() { + beforeEach(wipeOut); + afterEach(wipeOut); + + it('should explode on invalid folder', function(done) { + var stream:any; + try { + stream = gulp.dest(); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should pass through writes with cwd', function(done) { + var inputPath = path.join(__dirname, "./fixtures/test.coffee"); + + var expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: inputPath, + contents: null + }); + + var onEnd = function(){ + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + done(); + }; + + var stream = vfs.dest("./out-fixtures/", {cwd: __dirname}); + + var buffered:any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should pass through writes with default cwd', function(done) { + var inputPath = path.join(__dirname, "./fixtures/test.coffee"); + + var expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: inputPath, + contents: null + }); + + var onEnd = function(){ + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + done(); + }; + + var stream = vfs.dest(path.join(__dirname, "./out-fixtures/")); + + var buffered:any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should not write null files', function(done) { + var inputPath = path.join(__dirname, "./fixtures/test.coffee"); + var inputBase = path.join(__dirname, "./fixtures/"); + var expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + var expectedCwd = __dirname; + var expectedBase = path.join(__dirname, "./out-fixtures"); + + var expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: null + }); + + var onEnd = function(){ + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(false); + done(); + }; + + var stream = vfs.dest("./out-fixtures/", {cwd: __dirname}); + + var buffered:any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write buffer files to the right folder with relative cwd', function(done) { + var inputPath = path.join(__dirname, "./fixtures/test.coffee"); + var inputBase = path.join(__dirname, "./fixtures/"); + var expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + var expectedCwd = __dirname; + var expectedBase = path.join(__dirname, "./out-fixtures"); + var expectedContents = fs.readFileSync(inputPath); + + var expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents + }); + + var onEnd = function(){ + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + done(); + }; + + var stream = vfs.dest("./out-fixtures/", {cwd: path.relative(process.cwd(), __dirname)}); + + var buffered:any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write buffer files to the right folder', function(done) { + var inputPath = path.join(__dirname, "./fixtures/test.coffee"); + var inputBase = path.join(__dirname, "./fixtures/"); + var expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + var expectedContents = fs.readFileSync(inputPath); + var expectedCwd = __dirname; + var expectedBase = path.join(__dirname, "./out-fixtures"); + var expectedMode = 0655; + + var expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents, + stat: { + mode: expectedMode + } + }); + + var onEnd = function(){ + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + var stream = vfs.dest("./out-fixtures/", {cwd: __dirname}); + + var buffered:any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write streaming files to the right folder', function(done) { + var inputPath = path.join(__dirname, "./fixtures/test.coffee"); + var inputBase = path.join(__dirname, "./fixtures/"); + var expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + var expectedContents = fs.readFileSync(inputPath); + var expectedCwd = __dirname; + var expectedBase = path.join(__dirname, "./out-fixtures"); + var expectedMode = 0655; + + var contentStream = through.obj(); + var expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: contentStream, + stat: { + mode: expectedMode + } + }); + + var onEnd = function(){ + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + var stream = vfs.dest("./out-fixtures/", {cwd: __dirname}); + + var buffered:any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + setTimeout(function(){ + contentStream.write(expectedContents); + contentStream.end(); + }, 100); + stream.end(); + }); + + it('should write directories to the right folder', function(done) { + var inputPath = path.join(__dirname, "./fixtures/test"); + var inputBase = path.join(__dirname, "./fixtures/"); + var expectedPath = path.join(__dirname, "./out-fixtures/test"); + var expectedCwd = __dirname; + var expectedBase = path.join(__dirname, "./out-fixtures"); + var expectedMode = 0655; + + var expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: null, + stat: { + isDirectory: function(){ + return true; + }, + mode: expectedMode + } + }); + + var onEnd = function(){ + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + fs.lstatSync(expectedPath).isDirectory().should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + var stream = vfs.dest("./out-fixtures/", {cwd: __dirname}); + + var buffered:any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should allow piping multiple dests in streaming mode', function(done) { + var inputPath1 = path.join(__dirname, "./out-fixtures/multiple-first"); + var inputPath2 = path.join(__dirname, "./out-fixtures/multiple-second"); + var inputBase = path.join(__dirname, "./out-fixtures/"); + var srcPath = path.join(__dirname, "./fixtures/test.coffee"); + var stream1 = vfs.dest('./out-fixtures/', {cwd: __dirname}); + var stream2 = vfs.dest('./out-fixtures/', {cwd: __dirname}); + var content = fs.readFileSync(srcPath); + var rename = through.obj(function(file:any, _:any, next:any) { + file.path = inputPath2; + this.push(file); + next(); + }); + + stream1.on('data', function(file:any) { + file.path.should.equal(inputPath1); + }) + + stream1.pipe(rename).pipe(stream2); + stream2.on('data', function(file:any) { + file.path.should.equal(inputPath2); + }).once('end', function() { + fs.readFileSync(inputPath1, 'utf8').should.equal(content.toString()); + fs.readFileSync(inputPath2, 'utf8').should.equal(content.toString()); + done(); + }); + + var file = new File({ + base: inputBase, + path: inputPath1, + cwd: __dirname, + contents: content + }) + + stream1.write(file); + stream1.end(); + }) + +}); diff --git a/vinyl-fs/vinyl-fs.d.ts b/vinyl-fs/vinyl-fs.d.ts new file mode 100644 index 0000000000..e9f5491610 --- /dev/null +++ b/vinyl-fs/vinyl-fs.d.ts @@ -0,0 +1,31 @@ +// Type definitions for vinyl-fs +// Project: https://github.com/wearefractal/vinyl-fs +// Definitions by: vvakame +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module NodeJS { + interface WritableStream { + write(buffer: any/* Vinyl.IFile */, cb?: Function): boolean; + } +} + +declare module "vinyl-fs" { + import _events = require("events"); + + function src(globs:string, opt?:{read?:boolean;buffer?:boolean;}):NodeJS.ReadWriteStream; + + function src(globs:string[], opt?:{read?:boolean;buffer?:boolean;}):NodeJS.ReadWriteStream; + + function watch(globs:string, cb?:(outEvt:{type:any;path:any;old:any;})=>void):_events.EventEmitter; + + function watch(globs:string[], cb?:(outEvt:{type:any;path:any;old:any;})=>void):_events.EventEmitter; + + function watch(globs:string, opt?:{interval?:number;debounceDelay?:number;cwd?:string;maxListeners?:Function;}, cb?:(outEvt:{type:any;path:any;old:any;})=>void):_events.EventEmitter; + + function watch(globs:string[], opt?:{interval?:number;debounceDelay?:number;cwd?:string;maxListeners?:Function;}, cb?:(outEvt:{type:any;path:any;old:any;})=>void):_events.EventEmitter; + + function dest(folder:string, opt?:{cwd?:string; mode?:any/* number or string */;}):NodeJS.ReadWriteStream; +} diff --git a/vinyl/vinyl-tests.ts b/vinyl/vinyl-tests.ts new file mode 100644 index 0000000000..e09539990b --- /dev/null +++ b/vinyl/vinyl-tests.ts @@ -0,0 +1,544 @@ +/// +/// + +/// + +import File = require('vinyl'); +import Stream = require('stream'); +import fs = require('fs'); + +import should = require('should'); + +describe('File', function() { + + describe('constructor()', function() { + it('should default cwd to process.cwd', function(done) { + var file = new File(); + file.cwd.should.equal(process.cwd()); + done(); + }); + + it('should default base to cwd', function(done) { + var cwd = "/"; + var file = new File({cwd: cwd}); + file.base.should.equal(cwd); + done(); + }); + + it('should default base to cwd even when none is given', function(done) { + var file = new File(); + file.base.should.equal(process.cwd()); + done(); + }); + + it('should default path to null', function(done) { + var file = new File(); + should.not.exist(file.path); + done(); + }); + + it('should default stat to null', function(done) { + var file = new File(); + should.not.exist(file.stat); + done(); + }); + + it('should default contents to null', function(done) { + var file = new File(); + should.not.exist(file.contents); + done(); + }); + + it('should set base to given value', function(done) { + var val = "/"; + var file = new File({base: val}); + file.base.should.equal(val); + done(); + }); + + it('should set cwd to given value', function(done) { + var val = "/"; + var file = new File({cwd: val}); + file.cwd.should.equal(val); + done(); + }); + + it('should set path to given value', function(done) { + var val = "/test.coffee"; + var file = new File({path: val}); + file.path.should.equal(val); + done(); + }); + + it('should set stat to given value', function(done) { + var val = {}; + var file = new File({stat: val}); + file.stat.should.equal(val); + done(); + }); + + it('should set contents to given value', function(done) { + var val = new Buffer("test"); + var file = new File({contents: val}); + file.contents.should.equal(val); + done(); + }); + }); + + describe('isBuffer()', function() { + it('should return true when the contents are a Buffer', function(done) { + var val = new Buffer("test"); + var file = new File({contents: val}); + file.isBuffer().should.equal(true); + done(); + }); + + it('should return false when the contents are a Stream', function(done) { + var val: NodeJS.ReadWriteStream; // = new Stream(); + var file = new File({contents: val}); + file.isBuffer().should.equal(false); + done(); + }); + + it('should return false when the contents are a null', function(done) { + var file = new File({contents: null}); + file.isBuffer().should.equal(false); + done(); + }); + }); + + describe('isStream()', function() { + it('should return false when the contents are a Buffer', function(done) { + var val = new Buffer("test"); + var file = new File({contents: val}); + file.isStream().should.equal(false); + done(); + }); + + it('should return true when the contents are a Stream', function(done) { + var val: NodeJS.ReadWriteStream; // = new Stream(); + var file = new File({contents: val}); + file.isStream().should.equal(true); + done(); + }); + + it('should return false when the contents are a null', function(done) { + var file = new File({contents: null}); + file.isStream().should.equal(false); + done(); + }); + }); + + describe('isNull()', function() { + it('should return false when the contents are a Buffer', function(done) { + var val = new Buffer("test"); + var file = new File({contents: val}); + file.isNull().should.equal(false); + done(); + }); + + it('should return false when the contents are a Stream', function(done) { + var val: NodeJS.ReadWriteStream; // = new Stream(); + var file = new File({contents: val}); + file.isNull().should.equal(false); + done(); + }); + + it('should return true when the contents are a null', function(done) { + var file = new File({contents: null}); + file.isNull().should.equal(true); + done(); + }); + }); + + describe('isDirectory()', function() { + var fakeStat = { + isDirectory: function() { + return true; + } + }; + + it('should return false when the contents are a Buffer', function(done) { + var val = new Buffer("test"); + var file = new File({contents: val, stat: fakeStat}); + file.isDirectory().should.equal(false); + done(); + }); + + it('should return false when the contents are a Stream', function(done) { + var val: NodeJS.ReadWriteStream; // = new Stream(); + var file = new File({contents: val, stat: fakeStat}); + file.isDirectory().should.equal(false); + done(); + }); + + it('should return true when the contents are a null', function(done) { + var file = new File({contents: null, stat: fakeStat}); + file.isDirectory().should.equal(true); + done(); + }); + }); + + describe('clone()', function() { + it('should copy all attributes over with Buffer', function(done) { + var options = { + cwd: "/", + base: "/test/", + path: "/test/test.coffee", + contents: new Buffer("test") + }; + var file = new File(options); + var file2 = file.clone(); + + file2.should.not.equal(file, 'refs should be different'); + file2.cwd.should.equal(file.cwd); + file2.base.should.equal(file.base); + file2.path.should.equal(file.path); + file2.contents.should.not.equal(file.contents, 'buffer ref should be different'); + file2.contents.toString('utf8').should.equal(file.contents.toString('utf8')); + done(); + }); + + it('should copy all attributes over with Stream', function(done) { + var options = { + cwd: "/", + base: "/test/", + path: "/test/test.coffee", + contents: null // new Stream() + }; + var file = new File(options); + var file2 = file.clone(); + + file2.should.not.equal(file, 'refs should be different'); + file2.cwd.should.equal(file.cwd); + file2.base.should.equal(file.base); + file2.path.should.equal(file.path); + file2.contents.should.equal(file.contents, 'stream ref should be the same'); + done(); + }); + + it('should copy all attributes over with null', function(done) { + var options = { + cwd: "/", + base: "/test/", + path: "/test/test.coffee", + contents: null + }; + var file = new File(options); + var file2 = file.clone(); + + file2.should.not.equal(file, 'refs should be different'); + file2.cwd.should.equal(file.cwd); + file2.base.should.equal(file.base); + file2.path.should.equal(file.path); + should.not.exist(file2.contents); + done(); + }); + + it('should properly clone the `stat` property', function(done) { + var options = { + cwd: "/", + base: "/test/", + path: "/test/test.js", + contents: new Buffer("test"), + stat: fs.statSync(__filename) + }; + + var file = new File(options); + var copy = file.clone(); + + copy.stat.isFile().should.be.true; + copy.stat.isDirectory().should.be.false; + // should(file.stat instanceof fs.Stats).be.true; + // should(copy.stat instanceof fs.Stats).be.true; + + done(); + }); + }); + + describe('pipe()', function() { + it('should write to stream with Buffer', function(done) { + var options = { + cwd: "/", + base: "/test/", + path: "/test/test.coffee", + contents: new Buffer("test") + }; + var file = new File(options); + var stream = new Stream.PassThrough(); + stream.on('data', function(chunk:any) { + should.exist(chunk); + (chunk instanceof Buffer).should.equal(true, 'should write as a buffer'); + chunk.toString('utf8').should.equal(options.contents.toString('utf8')); + }); + stream.on('end', function(chunk:any) { + done(); + }); + var ret = file.pipe(stream); + ret.should.equal(stream, 'should return the stream'); + }); + + it('should pipe to stream with Stream', function(done) { + var testChunk = new Buffer("test"); + var options = { + cwd: "/", + base: "/test/", + path: "/test/test.coffee", + contents: new Stream.PassThrough() + }; + var file = new File(options); + var stream = new Stream.PassThrough(); + stream.on('data', function(chunk:any) { + should.exist(chunk); + (chunk instanceof Buffer).should.equal(true, 'should write as a buffer'); + chunk.toString('utf8').should.equal(testChunk.toString('utf8')); + done(); + }); + var ret = file.pipe(stream); + ret.should.equal(stream, 'should return the stream'); + + file.contents.write(testChunk); + }); + + it('should do nothing with null', function(done) { + var options = { + cwd: "/", + base: "/test/", + path: "/test/test.coffee", + contents: null + }; + var file = new File(options); + var stream = new Stream.PassThrough(); + stream.on('data', function(chunk:any) { + throw new Error("should not write"); + }); + stream.on('end', function() { + done(); + }); + var ret = file.pipe(stream); + ret.should.equal(stream, 'should return the stream'); + }); + + it('should write to stream with Buffer', function(done) { + var options = { + cwd: "/", + base: "/test/", + path: "/test/test.coffee", + contents: new Buffer("test") + }; + var file = new File(options); + var stream = new Stream.PassThrough(); + stream.on('data', function(chunk:any) { + should.exist(chunk); + (chunk instanceof Buffer).should.equal(true, 'should write as a buffer'); + chunk.toString('utf8').should.equal(options.contents.toString('utf8')); + done(); + }); + stream.on('end', function(chunk:any) { + throw new Error("should not end"); + }); + var ret = file.pipe(stream, {end: false}); + ret.should.equal(stream, 'should return the stream'); + }); + + it('should pipe to stream with Stream', function(done) { + var testChunk = new Buffer("test"); + var options = { + cwd: "/", + base: "/test/", + path: "/test/test.coffee", + contents: new Stream.PassThrough() + }; + var file = new File(options); + var stream = new Stream.PassThrough(); + stream.on('data', function(chunk:any) { + should.exist(chunk); + (chunk instanceof Buffer).should.equal(true, 'should write as a buffer'); + chunk.toString('utf8').should.equal(testChunk.toString('utf8')); + done(); + }); + stream.on('end', function(chunk:any) { + throw new Error("should not end"); + }); + var ret = file.pipe(stream, {end: false}); + ret.should.equal(stream, 'should return the stream'); + + file.contents.write(testChunk); + }); + + it('should do nothing with null', function(done) { + var options = { + cwd: "/", + base: "/test/", + path: "/test/test.coffee", + contents: null + }; + var file = new File(options); + var stream = new Stream.PassThrough(); + stream.on('data', function(chunk:any) { + throw new Error("should not write"); + }); + stream.on('end', function(chunk:any) { + throw new Error("should not end"); + }); + var ret = file.pipe(stream, {end: false}); + ret.should.equal(stream, 'should return the stream'); + process.nextTick(done); + }); + }); + + describe('inspect()', function() { + it('should return correct format when no contents and no path', function(done) { + var file = new File(); + file.inspect().should.equal(''); + done(); + }); + + it('should return correct format when Buffer and no path', function(done) { + var val = new Buffer("test"); + var file = new File({ + contents: val + }); + file.inspect().should.equal('>'); + done(); + }); + + it('should return correct format when Buffer and relative path', function(done) { + var val = new Buffer("test"); + var file = new File({ + cwd: "/", + base: "/test/", + path: "/test/test.coffee", + contents: val + }); + file.inspect().should.equal('>'); + done(); + }); + + it('should return correct format when Buffer and only path and no base', function(done) { + var val = new Buffer("test"); + var file = new File({ + cwd: "/", + path: "/test/test.coffee", + contents: val + }); + delete file.base; + file.inspect().should.equal('>'); + done(); + }); + + it('should return correct format when Stream and relative path', function(done) { + var file = new File({ + cwd: "/", + base: "/test/", + path: "/test/test.coffee", + contents: new Stream.PassThrough() + }); + file.inspect().should.equal('>'); + done(); + }); + + it('should return correct format when null and relative path', function(done) { + var file = new File({ + cwd: "/", + base: "/test/", + path: "/test/test.coffee", + contents: null + }); + file.inspect().should.equal(''); + done(); + }); + }); + + describe('contents get/set', function() { + it('should work with Buffer', function(done) { + var val = new Buffer("test"); + var file = new File(); + file.contents = val; + file.contents.should.equal(val); + done(); + }); + + it('should work with Stream', function(done) { + var val = new Stream.PassThrough(); + var file = new File(); + file.contents = val; + file.contents.should.equal(val); + done(); + }); + + it('should work with null', function(done) { + var val:any = null; + var file = new File(); + file.contents = val; + (file.contents === null).should.equal(true); + done(); + }); + + it('should not work with string', function(done) { + var val = "test"; + var file = new File(); + try { + file.contents = val; + } catch (err) { + should.exist(err); + done(); + } + }); + }); + + describe('relative get/set', function() { + it('should error on set', function(done) { + var file = new File(); + try { + file.relative = "test"; + } catch (err) { + should.exist(err); + done(); + } + }); + + it('should error on get when no base', function(done) { + var a:any; + var file = new File(); + delete file.base; + try { + a = file.relative; + } catch (err) { + should.exist(err); + done(); + } + }); + + it('should error on get when no path', function(done) { + var a:any; + var file = new File(); + try { + a = file.relative; + } catch (err) { + should.exist(err); + done(); + } + }); + + it('should return a relative path from base', function(done) { + var file = new File({ + cwd: "/", + base: "/test/", + path: "/test/test.coffee" + }); + file.relative.should.equal("test.coffee"); + done(); + }); + + it('should return a relative path from cwd', function(done) { + var file = new File({ + cwd: "/", + path: "/test/test.coffee" + }); + file.relative.should.equal("test/test.coffee"); + done(); + }); + }); + +}); diff --git a/vinyl/vinyl.d.ts b/vinyl/vinyl.d.ts new file mode 100644 index 0000000000..72b688a5f1 --- /dev/null +++ b/vinyl/vinyl.d.ts @@ -0,0 +1,41 @@ +// Type definitions for vinyl +// Project: https://github.com/wearefractal/vinyl +// Definitions by: vvakame +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Vinyl { + interface IOptions { + cwd?:string; + base?:string; + path?:string; + contents?:any; // Buffer or Stream + } + + interface IFileStatic { + new (file?:IOptions):IFile; + } + + interface IFile { + cwd:string; + base:string; + path:string; + stat:any; // stat = fs stats object + contents:any; // Buffer or Stream + relative:string; + + isBuffer():boolean; + isStream():boolean; + isNull():boolean; + isDirectory():boolean; + clone():IFile; + pipe(stream:T, opts?:{ end?: boolean; }):T; + inspect():string; + } +} + +declare module "vinyl" { + var _:Vinyl.IFileStatic; + export = _; +} diff --git a/watch/watch-tests.ts b/watch/watch-tests.ts new file mode 100644 index 0000000000..4888d41e2e --- /dev/null +++ b/watch/watch-tests.ts @@ -0,0 +1,32 @@ +/// + +import watch = require('watch'); +import fs = require('fs'); + +var value: any; +var str: string; +var num: number; +var bool: boolean; + +var mon: watch.Monitor; +var opts: watch.Options = { + ignoreDotFiles: bool, + filter: value +}; + +mon.on('foo', () => { + +}); + +watch.watchTree(str, (f: any, curr: fs.Stats, prev: fs.Stats) => { + +}); +watch.watchTree(str, opts, (f: any, curr: fs.Stats, prev: fs.Stats) => { + +}); +watch.createMonitor(str, (monitor: watch.Monitor) => { + +}); +watch.createMonitor(str, opts, (monitor: watch.Monitor) => { + +}); diff --git a/watch/watch.d.ts b/watch/watch.d.ts new file mode 100644 index 0000000000..d011b11f76 --- /dev/null +++ b/watch/watch.d.ts @@ -0,0 +1,35 @@ +// Type definitions for watch +// Project: https://github.com/mikeal/watch +// Definitions by: Carlos Ballesteros Velasco +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/watch.d.ts + +/// + +declare module "watch" { + import fs = require("fs"); + import events = require("events"); + + export interface Monitor extends events.EventEmitter { + // event: created + // event: removed + // event: changed + + // export function onCreated(callback, function(f, stat: fs.Stats) { }); + // export function onChanged(callback, function(f, curr: fs.Stats, prev: fs.Stats) { }); + // export function onRemoved(callback, function(f, stat: fs.Stats) { }); + } + + export interface Options { + persistent?: boolean; + ignoreDotFiles?: boolean; + filter?: any; + interval?: number; + } + + export function watchTree(root: string, callback: (f: any, curr: fs.Stats, prev: fs.Stats) => void): void; + export function watchTree(root: string, options: Options, callback: (f: any, curr: fs.Stats, prev: fs.Stats) => void): void; + export function createMonitor(root: string, callback: (monitor: Monitor) => void): void; + export function createMonitor(root: string, options: Options, callback: (monitor: Monitor) => void): void; +} diff --git a/webaudioapi/waa-20120802.d.ts b/webaudioapi/waa-20120802.d.ts index 64dc658764..a2039bf614 100644 --- a/webaudioapi/waa-20120802.d.ts +++ b/webaudioapi/waa-20120802.d.ts @@ -1,6 +1,6 @@ // Type definitions for Web Audio API // Project: http://www.w3.org/TR/2012/WD-webaudio-20120802/ -// Definitions by: Baruch Berger (https://github.com/bbss) +// Definitions by: Baruch Berger // Definitions: https://github.com/borisyankov/DefinitelyTyped // Conforms to the: http://www.w3.org/TR/2012/WD-webaudio-20120802/ specification diff --git a/webaudioapi/waa-nightly.d.ts b/webaudioapi/waa-nightly.d.ts index 79566f9396..0d83c25339 100644 --- a/webaudioapi/waa-nightly.d.ts +++ b/webaudioapi/waa-nightly.d.ts @@ -1,6 +1,6 @@ // Type definitions for Web Audio API (nightly) // Project: http://www.w3.org/TR/2012/WD-webaudio-20120802/ -// Definitions by: Baruch Berger (https://github.com/bbss) +// Definitions by: Baruch Berger // Definitions: https://github.com/borisyankov/DefinitelyTyped // Conforms to the: http://www.w3.org/TR/2012/WD-webaudio-20120802/ specification diff --git a/webaudioapi/waa-tests.ts b/webaudioapi/waa-tests.ts index 39d7549e3b..20e49f8ea7 100644 --- a/webaudioapi/waa-tests.ts +++ b/webaudioapi/waa-tests.ts @@ -60,6 +60,9 @@ declare var footstepsBuffer: any; lowpassFilter.connect(wet1); dry1.connect(masterDry); wet1.connect(reverb); + source1.loop = true; + source1.loopStart = 0; + source1.loopEnd = 300; // Connect source2 var dry2 = context.createGain(); @@ -303,3 +306,9 @@ declare var footstepsBuffer: any; } }; +()=>{ + var context = new webkitOfflineAudioContext(1, 2, 44100.5); + context.startRendering(); + context.oncomplete(context.createBufferSource().buffer); +} + diff --git a/webaudioapi/waa-tests.ts.tscparams b/webaudioapi/waa-tests.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/webaudioapi/waa-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/webaudioapi/waa.d.ts b/webaudioapi/waa.d.ts index cd53babc0c..43aa8c4eaa 100644 --- a/webaudioapi/waa.d.ts +++ b/webaudioapi/waa.d.ts @@ -1,5 +1,5 @@ // Type definitions for Web Audio API -// Project: http://www.w3.org/TR/2012/WD-webaudio-20121213/ +// Project: http://www.w3.org/TR/webaudio/ // Definitions by: Baruch Berger , Kon // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -180,11 +180,14 @@ interface OfflineRenderSuccessCallback{ * var offlineContext = new OfflineAudioContext(unsigned long numberOfChannels, unsigned long length, float sampleRate); */ interface OfflineAudioContext extends AudioContext{ - constructor(); startRendering(): void; oncomplete: OfflineRenderSuccessCallback; } +declare var webkitOfflineAudioContext: { + new (numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; +} + /** * AudioNodes are the building blocks of an AudioContext. This interface represents audio sources, the audio destination, and intermediate processing modules. These modules can be connected together to form processing graphs for rendering audio to the audio hardware. Each node can have inputs and/or outputs. An AudioSourceNode has no inputs and a single output. An AudioDestinationNode has one input and no outputs and represents the final destination to the audio hardware. Most processing nodes such as filters will have one input and one output. Each type of AudioNode differs in the details of how it processes or synthesizes audio. But, in general, AudioNodes will process its inputs (if it has any), and generate audio for its outputs (if it has any). * @@ -520,6 +523,21 @@ interface AudioBufferSourceNode extends AudioSourceNode { */ loop: boolean; + /** + * An optional value in seconds where looping should begin if the loop attribute is true. Its default value is 0, and it may usefully be set to any value between 0 and the duration of the buffer. + */ + loopStart: number; + + /** + * An optional value in seconds where looping should end if the loop attribute is true. Its default value is 0, and it may usefully be set to any value between 0 and the duration of the buffer. + */ + loopEnd: number; + + /** + * A property used to set the EventHandler for the ended event that is dispatched to AudioBufferSourceNode node types. When the playback of the buffer for an AudioBufferSourceNode is finished, an event of type Event will be dispatched to the event handler. + */ + onended: EventListener; + /** * Schedules a sound to playback at an exact time. * diff --git a/webaudioapi/waa.d.ts.tscparams b/webaudioapi/waa.d.ts.tscparams deleted file mode 100644 index e16c76dff8..0000000000 --- a/webaudioapi/waa.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/webcrypto/WebCrypto.d.ts b/webcrypto/WebCrypto.d.ts new file mode 100644 index 0000000000..069f0ca254 --- /dev/null +++ b/webcrypto/WebCrypto.d.ts @@ -0,0 +1,13 @@ +// Type definitions for WebCrypto +// Project: http://www.w3.org/TR/WebCryptoAPI/ +// Definitions by: Lucas Dixon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module crypto { + + // A cryptographically strong pseudo-random number generator seeded with + // truly random values. The buffer passed in is modified, and a reference to + // argument is returned for convenience. + function getRandomValues(array: ArrayBufferView) : ArrayBufferView + +} diff --git a/webcrypto/readme.md b/webcrypto/readme.md new file mode 100644 index 0000000000..420dc479f8 --- /dev/null +++ b/webcrypto/readme.md @@ -0,0 +1,17 @@ +# WebCrypto Definition Notes + +## The WebCrypto specification + +The WebCrypto specification is for performing basic cryptographic operations in +web applications, such as hashing, signature generation and verification, and +encryption and decryption. The API is also for applications to generate and/or +manage the keying material necessary to perform these operations. Uses for this +API range from user or service authentication, document or code signing, and the confidentiality and integrity of communications. + +The latest version of the specification can be found at: http://www.w3.org/TR/WebCryptoAPI/ + +## Adding the reference to your project + +``` +/// +``` diff --git a/webrtc/MediaStream-tests.ts b/webrtc/MediaStream-tests.ts index 290e2ff3c7..14c2fab7c7 100644 --- a/webrtc/MediaStream-tests.ts +++ b/webrtc/MediaStream-tests.ts @@ -6,27 +6,27 @@ var mediaTrackConstraintArray: MediaTrackConstraint[] = []; var mediaTrackConstraints: MediaTrackConstraints = { mandatory: mediaTrackConstraintSet, optional: mediaTrackConstraintArray } navigator.getUserMedia(mediaStreamConstraints, - stream => { - console.log('label:' + stream.label); - console.log('ended:' + stream.ended); - stream.onended = event => console.log('Stream ended'); - var objectUrl = URL.createObjectURL(stream); - var wkObjectUrl = webkitURL.createObjectURL(stream); - }, - error => { - console.log('Error message: ' + error.message); - console.log('Error name: ' + error.name); - }); + stream => { + console.log('label:' + stream.label); + console.log('ended:' + stream.ended); + stream.onended = (event:Event) => console.log('Stream ended'); + var objectUrl = URL.createObjectURL(stream); + var wkObjectUrl = webkitURL.createObjectURL(stream); + }, + error => { + console.log('Error message: ' + error.message); + console.log('Error name: ' + error.name); + }); navigator.webkitGetUserMedia(mediaStreamConstraints, - stream => { - console.log('label:' + stream.label); - console.log('ended:' + stream.ended); - stream.onended = event => console.log('Stream ended'); - var objectUrl = URL.createObjectURL(stream); - var wkObjectUrl = webkitURL.createObjectURL(stream); - }, - error => { - console.log('Error message: ' + error.message); - console.log('Error name: ' + error.name); - }); \ No newline at end of file + stream => { + console.log('label:' + stream.label); + console.log('ended:' + stream.ended); + stream.onended = (event:Event) => console.log('Stream ended'); + var objectUrl = URL.createObjectURL(stream); + var wkObjectUrl = webkitURL.createObjectURL(stream); + }, + error => { + console.log('Error message: ' + error.message); + console.log('Error name: ' + error.name); + }); diff --git a/webrtc/MediaStream.d.ts b/webrtc/MediaStream.d.ts index ddf2200be3..e159dff294 100644 --- a/webrtc/MediaStream.d.ts +++ b/webrtc/MediaStream.d.ts @@ -6,136 +6,158 @@ // Taken from http://dev.w3.org/2011/webrtc/editor/getusermedia.html interface MediaStreamConstraints { - audio: boolean; - video: boolean; + audio: any; + video: any; } declare var MediaStreamConstraints: { - prototype: MediaStreamConstraints; - new (): MediaStreamConstraints; + prototype: MediaStreamConstraints; + new (): MediaStreamConstraints; } interface MediaTrackConstraints { - mandatory: MediaTrackConstraintSet; - optional: MediaTrackConstraint[]; + mandatory: MediaTrackConstraintSet; + optional: MediaTrackConstraint[]; } declare var MediaTrackConstraints: { - prototype: MediaTrackConstraints; - new (): MediaTrackConstraints; + prototype: MediaTrackConstraints; + new (): MediaTrackConstraints; } // ks - Not defined in the source doc. interface MediaTrackConstraintSet { } declare var MediaTrackConstraintSet: { - prototype: MediaTrackConstraintSet; - new (): MediaTrackConstraintSet; + prototype: MediaTrackConstraintSet; + new (): MediaTrackConstraintSet; } // ks - Not defined in the source doc. interface MediaTrackConstraint { } declare var MediaTrackConstraint: { - prototype: MediaTrackConstraint; - new (): MediaTrackConstraints; + prototype: MediaTrackConstraint; + new (): MediaTrackConstraints; } interface Navigator { - getUserMedia(constraints: MediaStreamConstraints, successCallback: (stream: any) => void , errorCallback: (error: Error) => void ); - webkitGetUserMedia(constraints: MediaStreamConstraints, successCallback: (stream: any) => void , errorCallback: (error: Error) => void ); + getUserMedia(constraints: MediaStreamConstraints, + successCallback: (stream: any) => void, + errorCallback: (error: Error) => void) : void; + webkitGetUserMedia(constraints: MediaStreamConstraints, + successCallback: (stream: any) => void, + errorCallback: (error: Error) => void): void; } interface EventHandler { (event: Event): void; } -interface NavigatorUserMediaSuccessCallback { (stream: LocalMediaStream): void; } +interface NavigatorUserMediaSuccessCallback { + (stream: LocalMediaStream): void; +} interface NavigatorUserMediaError { - PERMISSION_DENIED: number; // = 1; - code: number; + PERMISSION_DENIED: number; // = 1; + code: number; } declare var NavigatorUserMediaError: { - prototype: NavigatorUserMediaError; - new (): NavigatorUserMediaError; - PERMISSION_DENIED: number; // = 1; + prototype: NavigatorUserMediaError; + new (): NavigatorUserMediaError; + PERMISSION_DENIED: number; // = 1; } -interface NavigatorUserMediaErrorCallback { (error: NavigatorUserMediaError): void; } +interface NavigatorUserMediaErrorCallback { + (error: NavigatorUserMediaError): void; +} interface MediaStreamTrackList { - length: number; - item: MediaStreamTrack; - add(track: MediaStreamTrack): void; - remove(track: MediaStreamTrack): void; - onaddtrack: (event: Event) => void; - onremovetrack: (event: Event) => void; + length: number; + item: MediaStreamTrack; + add(track: MediaStreamTrack): void; + remove(track: MediaStreamTrack): void; + onaddtrack: (event: Event) => void; + onremovetrack: (event: Event) => void; } declare var MediaStreamTrackList: { - prototype: MediaStreamTrackList; - new (): MediaStreamTrackList; + prototype: MediaStreamTrackList; + new (): MediaStreamTrackList; } declare var webkitMediaStreamTrackList: { - prototype: MediaStreamTrackList; - new (): MediaStreamTrackList; + prototype: MediaStreamTrackList; + new (): MediaStreamTrackList; } interface MediaStream { - label: string; - getAudioTracks(): MediaStreamTrackList; - getVideoTracks(): MediaStreamTrackList; - ended: boolean; - onended: (event: Event) => void; + label: string; + id: string; + getAudioTracks(): MediaStreamTrackList; + getVideoTracks(): MediaStreamTrackList; + ended: boolean; + onended: (event: Event) => void; } declare var MediaStream: { - prototype: MediaStream; - new (): MediaStream; - new (trackContainers: MediaStream[]): MediaStream; - new (trackContainers: MediaStreamTrackList[]): MediaStream; - new (trackContainers: MediaStreamTrack[]): MediaStream; + prototype: MediaStream; + new (): MediaStream; + new (trackContainers: MediaStream[]): MediaStream; + new (trackContainers: MediaStreamTrackList[]): MediaStream; + new (trackContainers: MediaStreamTrack[]): MediaStream; } declare var webkitMediaStream: { - prototype: MediaStream; - new (): MediaStream; - new (trackContainers: MediaStream[]): MediaStream; - new (trackContainers: MediaStreamTrackList[]): MediaStream; - new (trackContainers: MediaStreamTrack[]): MediaStream; + prototype: MediaStream; + new (): MediaStream; + new (trackContainers: MediaStream[]): MediaStream; + new (trackContainers: MediaStreamTrackList[]): MediaStream; + new (trackContainers: MediaStreamTrack[]): MediaStream; +} + +// an - not defined in source doc. +interface SourceInfo { + label: string; + id: string; + kind: string; + facing: string; +} +declare var SourceInfo: { + prototype: SourceInfo; } interface LocalMediaStream extends MediaStream { - stop(): void; + stop(): void; } interface MediaStreamTrack { - kind: string; - label: string; - enabled: boolean; - LIVE: number; // = 0; - MUTED: number; // = 1; - ENDED: number; // = 2; - readyState: number; - onmute: (event: Event) => void; - onunmute: (event: Event) => void; - onended: (event: Event) => void; + kind: string; + label: string; + enabled: boolean; + LIVE: number; // = 0; + MUTED: number; // = 1; + ENDED: number; // = 2; + readyState: number; + onmute: (event: Event) => void; + onunmute: (event: Event) => void; + onended: (event: Event) => void; } -declare var MediaStramTrack: { - prototype: MediaStreamTrack; - new (): MediaStreamTrack; - LIVE: number; // = 0; - MUTED: number; // = 1; - ENDED: number; // = 2; +declare var MediaStreamTrack: { + prototype: MediaStreamTrack; + new (): MediaStreamTrack; + LIVE: number; // = 0; + MUTED: number; // = 1; + ENDED: number; // = 2; + getSources: (callback: (sources: SourceInfo[]) => void) => void; } interface streamURL extends URL { - createObjectURL(stream: MediaStream): string; + createObjectURL(stream: MediaStream): string; } //declare var URL: { -// prototype: MediaStreamTrack; -// new (): URL; -// createObjectURL(stream: MediaStream): string; +// prototype: MediaStreamTrack; +// new (): URL; +// createObjectURL(stream: MediaStream): string; //} interface WebkitURL extends streamURL { } declare var webkitURL: { - prototype: WebkitURL; - new (): streamURL; - createObjectURL(stream: MediaStream): string; + prototype: WebkitURL; + new (): streamURL; + createObjectURL(stream: MediaStream): string; } + diff --git a/webrtc/RTCPeerConnection-tests.ts b/webrtc/RTCPeerConnection-tests.ts index d7b5a07f74..0b05fcdd88 100644 --- a/webrtc/RTCPeerConnection-tests.ts +++ b/webrtc/RTCPeerConnection-tests.ts @@ -1,19 +1,22 @@ /// /// -var config: RTCConfiguration = { iceServers: [{ url: "stun.l.google.com:19302" }] }; -var constraints: MediaConstraints = { mandatory: { OfferToReceiveAudio: true, OfferToReceiveVideo: true } }; +var config: RTCConfiguration = + { iceServers: [{ url: "stun.l.google.com:19302" }] }; +var constraints: RTCMediaConstraints = + { mandatory: { OfferToReceiveAudio: true, OfferToReceiveVideo: true } }; -var peerConnection: RTCPeerConnection = new RTCPeerConnection(config, constraints); +var peerConnection: RTCPeerConnection = + new RTCPeerConnection(config, constraints); navigator.getUserMedia({ audio: true, video: true }, - stream => { - peerConnection.addStream(stream); - }, - error => { - console.log('Error message: ' + error.message); - console.log('Error name: ' + error.name); - }); + stream => { + peerConnection.addStream(stream); + }, + error => { + console.log('Error message: ' + error.message); + console.log('Error name: ' + error.name); + }); peerConnection.onaddstream = ev => console.log(ev.type); peerConnection.ondatachannel = ev => console.log(ev.type); @@ -25,27 +28,31 @@ peerConnection.onremovestream = ev => console.log(ev.type); peerConnection.onstatechange = ev => console.log(ev.type); peerConnection.createOffer( - offer => { - peerConnection.setLocalDescription(offer, - () => console.log("set local description"), - error => console.log("Error setting local description: " + error)); - }, - error => console.log("Error creating offer: " + error)); + offer => { + peerConnection.setLocalDescription(offer, + () => console.log("set local description"), + error => console.log("Error setting local description: " + error)); + }, + error => console.log("Error creating offer: " + error)); -var type: RTCSdpType = RTCSdpType.offer; +var type: string = RTCSdpType[RTCSdpType.offer]; var offer: RTCSessionDescriptionInit = { type: type, sdp: "some sdp" }; var sessionDescription = new RTCSessionDescription(offer); peerConnection.setRemoteDescription(sessionDescription, () => { - peerConnection.createAnswer( - answer => { - peerConnection.setLocalDescription(answer, - () => console.log('Set local description'), - error => console.log("Error setting local description from created answer: " + error + "; answer.sdp=" + answer.sdp)); - }, - error => console.log("Error creating answer: " + error)); + peerConnection.createAnswer( + answer => { + peerConnection.setLocalDescription(answer, + () => console.log('Set local description'), + error => console.log( + "Error setting local description from created answer: " + error + + "; answer.sdp=" + answer.sdp)); + }, + error => console.log("Error creating answer: " + error)); }, -error => console.log('Error setting remote description: ' + error + "; offer.sdp=" + offer.sdp)); +error => console.log('Error setting remote description: ' + error + + "; offer.sdp=" + offer.sdp)); -var wkPeerConnection: webkitRTCPeerConnection = new webkitRTCPeerConnection(config, constraints); +var wkPeerConnection: webkitRTCPeerConnection = + new webkitRTCPeerConnection(config, constraints); diff --git a/webrtc/RTCPeerConnection.d.ts b/webrtc/RTCPeerConnection.d.ts index d66ad6cf0f..edde45ae05 100644 --- a/webrtc/RTCPeerConnection.d.ts +++ b/webrtc/RTCPeerConnection.d.ts @@ -2,229 +2,308 @@ // Project: http://dev.w3.org/2011/webrtc/ // Definitions by: Ken Smith // Definitions: https://github.com/borisyankov/DefinitelyTyped - +// // Definitions taken from http://dev.w3.org/2011/webrtc/editor/webrtc.html +// +// For example code see: +// https://code.google.com/p/webrtc/source/browse/stable/samples/js/apprtc/js/main.js +// +// For a generic implementation see that deals with browser differences, see: +// https://code.google.com/p/webrtc/source/browse/stable/samples/js/base/adapter.js -/// +/// + +// TODO(1): Get Typescript to have string-enum types as WebRtc is full of string +// enums. +// https://typescript.codeplex.com/discussions/549207 + +// TODO(2): get Typescript to have union types as WebRtc uses them. +// https://typescript.codeplex.com/workitem/1364 interface RTCConfiguration { - iceServers: RTCIceServer[]; + iceServers: RTCIceServer[]; } declare var RTCConfiguration: { - prototype: RTCConfiguration; - new (): RTCConfiguration; + prototype: RTCConfiguration; + new (): RTCConfiguration; } interface RTCIceServer { - url: string; - credential?: string; + url: string; + credential?: string; } declare var RTCIceServer: { - prototype: RTCIceServer; - new (): RTCIceServer; + prototype: RTCIceServer; + new (): RTCIceServer; } +// moz (Firefox) specific prefixes. +interface mozRTCPeerConnection extends RTCPeerConnection { +} +declare var mozRTCPeerConnection: { + prototype: mozRTCPeerConnection; + new (settings: RTCPeerConnectionConfig, + constraints?:RTCMediaConstraints): mozRTCPeerConnection; +} +// webkit (Chrome) specific prefixes. interface webkitRTCPeerConnection extends RTCPeerConnection { } declare var webkitRTCPeerConnection: { - prototype: webkitRTCPeerConnection; - new (settings: RTCPeerConnectionConfig, constraints?:MediaConstraints): webkitRTCPeerConnection; + prototype: webkitRTCPeerConnection; + new (settings: RTCPeerConnectionConfig, + constraints?:RTCMediaConstraints): webkitRTCPeerConnection; } -interface IceState { -} -declare var IceState: { - prototype: IceState; - new (): IceState; +// For Chrome, look at the code here: +// https://code.google.com/p/chromium/codesearch#chromium/src/third_party/libjingle/source/talk/app/webrtc/webrtcsession.cc&sq=package:chromium&dr=C&l=63 +interface RTCOptionalMediaConstraint { + // When true, will use DTLS/SCTP data channels + DtlsSrtpKeyAgreement?: boolean; + // When true will use Rtp-based data channels (depreicated) + RtpDataChannels?: boolean; } // ks 12/20/12 - There's more here that doesn't seem to be documented very well yet. -interface MediaConstraints { - mandatory: MediaOfferConstraints; +// http://www.w3.org/TR/2013/WD-webrtc-20130910/ +interface RTCMediaConstraints { + mandatory?: RTCMediaOfferConstraints; + optional?: RTCOptionalMediaConstraint[] } -interface MediaOfferConstraints { - OfferToReceiveAudio: boolean; - OfferToReceiveVideo: boolean; -} - -interface RTCSessionDescription { - type?: RTCSdpType; - sdp?: string; -} -declare var RTCSessionDescription: { - prototype: RTCSessionDescription; - new (descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; +interface RTCMediaOfferConstraints { + OfferToReceiveAudio: boolean; + OfferToReceiveVideo: boolean; } interface RTCSessionDescriptionInit { - type: RTCSdpType; - sdp: string; -} -declare var RTCSessionDescriptionInit: { - prototype: RTCSessionDescriptionInit; - new (): RTCSessionDescriptionInit; + type: string; // RTCSdpType; See TODO(1) + sdp: string; } -interface SdpType { +interface RTCSessionDescription { + type?: string; // RTCSdpType; See TODO(1) + sdp?: string; } - -interface RTCPeerState { +declare var RTCSessionDescription: { + prototype: RTCSessionDescription; + new (descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; + // TODO: Add serializer. + // See: http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSdpType) } interface RTCDataChannelInit { - reliable: boolean; + ordered ?: boolean; // messages must be sent in-order. + maxPacketLifeTime ?: number; // unsigned short + maxRetransmits ?: number; // unsigned short + protocol ?: string; // default = '' + negotiated ?: boolean; // default = false; + id ?: number; // unsigned short } +// TODO(1) declare enum RTCSdpType { - offer, - pranswer, - answer + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcsdptype + 'offer', + 'pranswer', + 'answer' } +interface RTCMessageEvent { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#event-datachannel-message + // At present, this can be an: ArrayBuffer, a string, or a Blob. + // See TODO(2) + data: any; +} + +// TODO(1) declare enum RTCDataChannelState { - connecting, - open, - closing, - closed + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCDataChannelState + 'connecting', + 'open', + 'closing', + 'closed' } interface RTCDataChannel extends EventTarget { - label: string; - reliable: boolean; - readyState: RTCDataChannelState; - bufferedAmount: number; - onopen: (event: Event)=> void; - onerror: (event: Event)=> void; - onclose: (event: Event)=> void; - close(): void; - onmessage: (event: Event)=> void; - binaryType: string; - send(data: string); - send(data: ArrayBuffer); - send(data: Blob); + label: string; + reliable: boolean; + readyState: string; // RTCDataChannelState; see TODO(1) + bufferedAmount: number; + binaryType: string; + + onopen: (event: Event) => void; + onerror: (event: Event) => void; + onclose: (event: Event) => void; + onmessage: (event: RTCMessageEvent) => void; + + close(): void; + + send(data: string): void ; + send(data: ArrayBuffer): void; + send(data: ArrayBufferView): void; + send(data: Blob): void; } declare var RTCDataChannel: { - prototype: RTCDataChannel; - new (): RTCDataChannel; + prototype: RTCDataChannel; + new (): RTCDataChannel; } interface RTCDataChannelEvent extends Event { - constructor (eventInitDict: RTCDataChannelEventInit); - channel: RTCDataChannel; + channel: RTCDataChannel; } declare var RTCDataChannelEvent: { - prototype: RTCDataChannelEvent; - new (eventInitDict: RTCDataChannelEventInit); + prototype: RTCDataChannelEvent; + new (eventInitDict: RTCDataChannelEventInit): RTCDataChannelEvent; } -interface RTCIceCandidateEvent extends Event{ - candidate: RTCIceCandidate; +interface RTCIceCandidateEvent extends Event { + candidate: RTCIceCandidate; } interface RTCMediaStreamEvent extends Event { - stream: MediaStream; + stream: MediaStream; } interface EventInit { } interface RTCDataChannelEventInit extends EventInit { - channel: RTCDataChannel; + channel: RTCDataChannel; } interface RTCVoidCallback { - (): void; + (): void; } interface RTCSessionDescriptionCallback { - (sdp: RTCSessionDescription): void; + (sdp: RTCSessionDescription): void; } interface RTCPeerConnectionErrorCallback { - (errorInformation: string): void; + (errorInformation: DOMError): void; } -/** This should be an enum */ -interface RTCIceGatheringState { - string; +// TODO(1) +declare enum RTCIceGatheringState { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcicegatheringstate-enum + 'new', + 'gathering', + 'complete' } -/** This should be an enum */ -interface RTCIceConnectionState { - string; +// TODO(1) +declare enum RTCIceConnectionState { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCIceConnectionState + 'new', + 'checking', + 'connected', + 'completed', + 'failed', + 'disconnected', + 'closed' } -/** This should be an enum */ -interface RTCSignalingState{ - string; +// TODO(1) +declare enum RTCSignalingState { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSignalingState + 'stable', + 'have-local-offer', + 'have-remote-offer', + 'have-local-pranswer', + 'have-remote-pranswer', + 'closed' +} + +// This is based on the current implementation of WebRtc in Chrome; the spec is +// a little unclear on this. +// http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCStatsReport +interface RTCStatsReport { + stat(id: string): string; +} + +interface RTCStatsCallback { + (report: RTCStatsReport): void; } interface RTCPeerConnection { - createOffer(successCallback: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, constraints?: MediaConstraints): void; - createAnswer(successCallback: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, constraints?: MediaConstraints): void; - setLocalDescription(description: RTCSessionDescription, successCallback?: RTCVoidCallback, failureCallback?: RTCPeerConnectionErrorCallback): void; - localDescription: RTCSessionDescription; - setRemoteDescription(description: RTCSessionDescription, successCallback?: RTCVoidCallback, failureCallback?: RTCPeerConnectionErrorCallback): void; - remoteDescription: RTCSessionDescription; - signalingState: RTCSignalingState; - updateIce(configuration?: RTCConfiguration, constraints?: MediaConstraints): void; - addIceCandidate(candidate: RTCIceCandidate): void; - iceGatheringState: RTCIceGatheringState; - iceConnectionState: RTCIceConnectionState; - getLocalStreams(): MediaStream[]; - getRemoteStreams(): MediaStream[]; - createDataChannel(label?: string, dataChannelDict?: RTCDataChannelInit): RTCDataChannel; - ondatachannel: (event: Event)=> void; - addStream(stream: MediaStream, constraints?: MediaConstraints): void; - removeStream(stream: MediaStream): void; - close(): void; - onnegotiationneeded: (event: Event)=> void; - onconnecting: (event: Event)=> void; - onopen: (event: Event)=> void; - onaddstream: (event: RTCMediaStreamEvent)=> void; - onremovestream: (event: RTCMediaStreamEvent)=> void; - onstatechange: (event: Event)=> void; - onicechange: (event: Event)=> void; - onicecandidate: (event: RTCIceCandidateEvent)=> void; - onidentityresult: (event: Event)=> void; + createOffer(successCallback: RTCSessionDescriptionCallback, + failureCallback?: RTCPeerConnectionErrorCallback, + constraints?: RTCMediaConstraints): void; + createAnswer(successCallback: RTCSessionDescriptionCallback, + failureCallback?: RTCPeerConnectionErrorCallback, + constraints?: RTCMediaConstraints): void; + setLocalDescription(description: RTCSessionDescription, + successCallback?: RTCVoidCallback, + failureCallback?: RTCPeerConnectionErrorCallback): void; + localDescription: RTCSessionDescription; + setRemoteDescription(description: RTCSessionDescription, + successCallback?: RTCVoidCallback, + failureCallback?: RTCPeerConnectionErrorCallback): void; + remoteDescription: RTCSessionDescription; + signalingState: string; // RTCSignalingState; see TODO(1) + updateIce(configuration?: RTCConfiguration, + constraints?: RTCMediaConstraints): void; + addIceCandidate(candidate: RTCIceCandidate): void; + iceGatheringState: string; // RTCIceGatheringState; see TODO(1) + iceConnectionState: string; // RTCIceConnectionState; see TODO(1) + getLocalStreams(): MediaStream[]; + getRemoteStreams(): MediaStream[]; + createDataChannel(label?: string, + dataChannelDict?: RTCDataChannelInit): RTCDataChannel; + ondatachannel: (event: Event) => void; + addStream(stream: MediaStream, constraints?: RTCMediaConstraints): void; + removeStream(stream: MediaStream): void; + close(): void; + onnegotiationneeded: (event: Event) => void; + onconnecting: (event: Event) => void; + onopen: (event: Event) => void; + onaddstream: (event: RTCMediaStreamEvent) => void; + onremovestream: (event: RTCMediaStreamEvent) => void; + onstatechange: (event: Event) => void; + onicechange: (event: Event) => void; + onicecandidate: (event: RTCIceCandidateEvent) => void; + onidentityresult: (event: Event) => void; + onsignalingstatechange: (event: Event) => void; + getStats: (successCallback: RTCStatsCallback, + failureCallback: RTCPeerConnectionErrorCallback) => void; } declare var RTCPeerConnection: { - prototype: RTCPeerConnection; - new (configuration: RTCConfiguration, constraints?: MediaConstraints): RTCPeerConnection; + prototype: RTCPeerConnection; + new (configuration: RTCConfiguration, + constraints?: RTCMediaConstraints): RTCPeerConnection; } interface RTCIceCandidate { - candidate?: string; - sdpMid?: string; - sdpMLineIndex?: number; + candidate?: string; + sdpMid?: string; + sdpMLineIndex?: number; } declare var RTCIceCandidate: { - prototype: RTCIceCandidate; - new (candidateInitDict?: RTCIceCandidate); + prototype: RTCIceCandidate; + new (candidateInitDict?: RTCIceCandidate): RTCIceCandidate; } interface RTCIceCandidateInit { - candidate: string; - sdpMid: string; - sdpMLineIndex: number; + candidate: string; + sdpMid: string; + sdpMLineIndex: number; } declare var RTCIceCandidateInit:{ - prototype: RTCIceCandidateInit; - new (): RTCIceCandidateInit; + prototype: RTCIceCandidateInit; + new (): RTCIceCandidateInit; } interface PeerConnectionIceEvent { - peer: RTCPeerConnection; - candidate: RTCIceCandidate; + peer: RTCPeerConnection; + candidate: RTCIceCandidate; } declare var PeerConnectionIceEvent: { - prototype: PeerConnectionIceEvent; - new (): PeerConnectionIceEvent; + prototype: PeerConnectionIceEvent; + new (): PeerConnectionIceEvent; } interface RTCPeerConnectionConfig { - iceServers: RTCIceServer[]; + iceServers: RTCIceServer[]; } declare var RTCPeerConnectionConfig: { - prototype: RTCPeerConnectionConfig; - new (): RTCPeerConnectionConfig; + prototype: RTCPeerConnectionConfig; + new (): RTCPeerConnectionConfig; } diff --git a/websocket/websocket.d.ts b/websocket/websocket.d.ts index cc22b89eaa..d984e1beac 100644 --- a/websocket/websocket.d.ts +++ b/websocket/websocket.d.ts @@ -128,11 +128,11 @@ declare module "websocket" { constructor(serverConfig?: IServerConfig); /** Send binary message for each connection */ - broadcast(data: NodeBuffer): void; + broadcast(data: Buffer): void; /** Send UTF-8 message for each connection */ broadcast(data: IStringified): void; /** Send binary message for each connection */ - broadcastBytes(data: NodeBuffer): void; + broadcastBytes(data: Buffer): void; /** Send UTF-8 message for each connection */ broadcastUTF(data: IStringified): void; /** Attach the `server` instance to a Node http.Server instance */ @@ -251,26 +251,26 @@ declare module "websocket" { export interface IMessage { type: string; utf8Data?: string; - binaryData?: NodeBuffer; + binaryData?: Buffer; } export interface IBufferList extends events.EventEmitter { encoding: string; length: number; - write(buf: NodeBuffer): boolean; - end(buf: NodeBuffer): void; + write(buf: Buffer): boolean; + end(buf: Buffer): void; /** * For each buffer, perform some action. * If fn's result is a true value, cut out early. */ - forEach(fn: (buf: NodeBuffer) => boolean): void; + forEach(fn: (buf: Buffer) => boolean): void; /** Create a single buffer out of all the chunks */ - join(start: number, end: number): NodeBuffer; + join(start: number, end: number): Buffer; /** Join all the chunks to existing buffer */ - joinInto(buf: NodeBuffer, offset: number, start: number, end: number): NodeBuffer; + joinInto(buf: Buffer, offset: number, start: number, end: number): Buffer; /** * Advance the buffer stream by `n` bytes. @@ -290,10 +290,10 @@ declare module "websocket" { // Events on(event: string, listener: () => void): IBufferList; on(event: 'advance', cb: (n: number) => void): IBufferList; - on(event: 'write', cb: (buf: NodeBuffer) => void): IBufferList; + on(event: 'write', cb: (buf: Buffer) => void): IBufferList; addListener(event: string, listener: () => void): IBufferList; addListener(event: 'advance', cb: (n: number) => void): IBufferList; - addListener(event: 'write', cb: (buf: NodeBuffer) => void): IBufferList; + addListener(event: 'write', cb: (buf: Buffer) => void): IBufferList; } class connection extends events.EventEmitter { @@ -330,8 +330,8 @@ declare module "websocket" { config: IConfig; socket: net.Socket; maskOutgoingPackets: boolean; - maskBytes: NodeBuffer; - frameHeader: NodeBuffer; + maskBytes: Buffer; + frameHeader: Buffer; bufferList: IBufferList; currentFrame: frame; fragmentationSize: number; @@ -390,14 +390,14 @@ declare module "websocket" { * to the remote peer. If config.fragmentOutgoingMessages is true the message may be * sent as multiple fragments if it exceeds config.fragmentationThreshold bytes. */ - sendBytes(buffer: NodeBuffer): void; + sendBytes(buffer: Buffer): void; /** Auto-detect the data type and send UTF-8 or Binary message */ - send(data: NodeBuffer): void; + send(data: Buffer): void; send(data: IStringified): void; /** Sends a ping frame. Ping frames must not exceed 125 bytes in length. */ - ping(data: NodeBuffer): void; + ping(data: Buffer): void; ping(data: IStringified): void; /** @@ -408,7 +408,7 @@ declare module "websocket" { * be no need to use this method to respond to pings. * Pong frames must not exceed 125 bytes in length. */ - pong(buffer: NodeBuffer): void; + pong(buffer: Buffer): void; /** * Serializes a `frame` object into binary data and immediately sends it to @@ -494,10 +494,10 @@ declare module "websocket" { * The binary payload data. * Even text frames are sent with a Buffer providing the binary payload data. */ - binaryPayload: NodeBuffer; + binaryPayload: Buffer; - maskBytes: NodeBuffer; - frameHeader: NodeBuffer; + maskBytes: Buffer; + frameHeader: Buffer; config: IConfig; maxReceivedFrameSize: number; protocolError: boolean; @@ -507,7 +507,7 @@ declare module "websocket" { addData(bufferList: IBufferList): boolean; throwAwayPayload(bufferList: IBufferList): boolean; - toBuffer(nullMask: boolean): NodeBuffer; + toBuffer(nullMask: boolean): Buffer; } export interface IClientConfig extends IConfig { diff --git a/winjs/winjs-1.0.d.ts b/winjs/winjs-1.0.d.ts new file mode 100644 index 0000000000..0952b03fe3 --- /dev/null +++ b/winjs/winjs-1.0.d.ts @@ -0,0 +1,6709 @@ +// Type definitions for WinJS +// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* ***************************************************************************** +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. +***************************************************************************** */ + +/** + * Defines an Element object. +**/ +interface Element { + winControl: any; // TODO: This should be control? +} + +/** + * Utility class for easy access to operations on application folders +**/ +interface IOHelper { + /** + * Determines whether the specified file exists in the folder. + * @param filename The name of the file. + * @returns A promise that completes with a value of either true (if the file exists) or false. + **/ + exists(filename: string): WinJS.Promise; + + /** + * Reads the specified file. If the file doesn't exist, the specified default value is returned. + * @param fileName The file to read from. + * @param def The default value to be returned if the file failed to open. + * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. + **/ + readText(fileName: string, def?: string): WinJS.Promise; + + /** + * Deletes a file from the folder. + * @param fileName The file to be deleted. + * @returns A promise that is fulfilled when the file has been deleted. + **/ + remove(fileName: string): WinJS.Promise; + + /** + * Writes the specified text to the specified file. + * @param fileName The name of the file. + * @param text The content to be written to the file. + * @returns A promise that completes with a value that is the number of characters written. + **/ + writeText(fileName: string, text: string): WinJS.Promise; +} + +/** + * Provides application-level functionality, for example activation, storage, and application events. +**/ +declare module WinJS.Application { + //#region Objects + + /** + * The local storage of the application. + **/ + var local: IOHelper; + + /** + * The roaming storage of the application. + **/ + var roaming: IOHelper; + + /** + * The temp storage of the application. + **/ + var temp: IOHelper; + + /** + * An object used for storing app information that can be used to restore the app's state after it has been suspended and then resumed. Data that can usefully be contained in this object includes the current navigation page or any information the user has added to the input controls on the page. You should not add information about customization (for example colors) or user-defined lists of content. + **/ + var sessionState: any; + + //#endregion Objects + + //#region Functions + + /** + * Adds an event listener for application-level events: activated, checkpoint, error, loaded, ready, settings, and unload. + * @param type The type (name) of the event. You can use any of the following:"activated", "checkpoint", "error", "loaded", "ready", "settings", and" unload". + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + function addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Queues a checkpoint event. + **/ + function checkpoint(): void; + + /** + * Queues an event to be processed by the WinJS.Application event queue. + * @param eventRecord The event object is expected to have a type property that is used as the event name when dispatching on the WinJS.Application event queue. The entire object is provided to event listeners in the detail property of the event. + **/ + function queueEvent(eventRecord: any): void; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: any): void; + + /** + * Starts dispatching application events (the activated, checkpoint, error, loaded, ready, settings, and unload events). + **/ + function start(): void; + + /** + * Stops application event processing and resets WinJS.Application to its initial state. All WinJS.Application event listeners (for the activated, checkpoint, error, loaded, ready, settings, and unload events) are removed. + **/ + function stop(): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs when WinRT activation has occurred. The name of this event is "activated" (and also "mainwindowactivated"). This event occurs after the loaded event and before the ready event. + * @param eventInfo An object that contains information about the event. For more information about event arguments, see the WinRT event argument classes: WebUICachedFileUpdaterActivatedEventArgs, WebUICameraSettingsActivatedEventArgs, WebUIContactPickerActivatedEventArgs, WebUIDeviceActivatedEventArgs, WebUIFileActivatedEventArgs, WebUIFileOpenPickerActivatedEventArgs, WebUIFileSavePickerActivatedEventArgs, WebUILaunchActivatedEventArgs, WebUIPrintTaskSettingsActivatedEventArgs, WebUIProtocolActivatedEventArgs, WebUISearchActivatedEventArgs, WebUIShareTargetActivatedEventArgs. + **/ + function onactivated(eventInfo: CustomEvent): void; + + /** + * Occurs when receiving PLM notification or when the checkpoint function is called. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function oncheckpoint(eventInfo: CustomEvent): void; + + /** + * Occurs when an unhandled error has been raised. + * @param eventInfo An object that contains information about the event. + **/ + function onerror(eventInfo: CustomEvent): void; + + /** + * Occurs after the DOMContentLoaded event, which fires after the page has been parsed but before all the resources are loaded. This event occurs before the activated event and the ready event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function onloaded(eventInfo: CustomEvent): void; + + /** + * Occurs when the application is ready. This event occurs after the loaded event and the activated event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onready(eventInfo: CustomEvent): void; + + /** + * Occurs when the settings charm is invoked. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: type, applicationcommands. + **/ + function onsettings(eventInfo: CustomEvent): void; + + /** + * Occurs when the application is about to be unloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onunload(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides functionality for data and template binding. +**/ +declare module WinJS.Binding { + //#region Properties + + /** + * Determines whether or not binding should automatically set the ID of an element. This property should be set to true in apps that use WinJS (WinJS) binding. + **/ + var optimizeBindingReferences: boolean; + + //#endregion Properties + + //#region Objects + + /** + * Allows you to add bindable properties dynamically. + **/ + var dynamicObservableMixin: { + //#region Methods + + /** + * Adds a property with change notification to this object, including a ECMAScript5 property definition. + * @param name The name of the property to add. + * @param value This object is returned. + **/ + addProperty(name: string, value: any): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Do not instantiate. A list returned by the createFiltered method. + **/ + class FilteredListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. A list of groups. + **/ + class GroupsListProjection extends ListBase { + //#region Methods + + /** + * Gets a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. Sorts the underlying list by group key and within a group respects the position of the item in the underlying list. Returned by createGrouped. + **/ + class GroupedSortedListProjection extends SortedListProjection { + //#region Properties + + /** + * Gets a List, which is a projection of the groups that were identified in this list. + **/ + groups: GroupsListProjection; + + //#endregion Properties + + } + + /** + * Represents a list of objects that can be accessed by index or by a string key. Provides methods to search, sort, filter, and manipulate the data. + **/ + class List extends ListBaseWithMutators { + //#region Constructors + + /** + * Creates a List object. + * @constructor + * @param list The array containing the elements to initalize the list. + * @param options You can set two Boolean options: binding and proxy. If options.binding is true, the list contains the result of calling as on the element values. If options.proxy is true, the list specified as the first parameter is used as the storage for the List. This option should be used with care, because uncoordinated edits to the data storage may result in errors. + **/ + constructor(list?: T[], options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Gets a key/data pair for the specified list index. + * @param index The index of value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the list item key specified. + * @param key The key of the value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Gets the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Moves the value at index to the specified position. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Returns a list with the elements reversed. This method reverses the elements of a list object in place. It does not create a new list object during execution. + **/ + reverse(): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + /** + * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. + * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + **/ + sort(sortFunction: (left: T, right: T) => number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list, which is an integer value one higher than the highest element defined in the list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Represents a base class for lists. + **/ + class ListBase { + //#region Events + + /** + * An item in the list has changed its value. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, newItem, newValue, oldItem, oldValue. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * A new item has been inserted into the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * An item has been changed locations in the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * An item has been mutated. This event occurs as a result of calling the notifyMutated method. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmutated(eventInfo: CustomEvent): void; + + /** + * An item has been removed from the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * The list has been refreshed. Any references to items in the list may be incorrect. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. + **/ + onreload(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Returns a new list consisting of a combination of two arrays. + * @param item Additional items to add to the end of the list. + * @returns An array containing the concatenation of the list and any other supplied items. + **/ + concat(...item: T[]): T[]; + + /** + * Creates a live filtered projection over this list. As the list changes, the filtered projection reacts to those changes and may also change. + * @param predicate A function that accepts a single argument. The createFiltered function calls the callback with each element in the list. If the function returns true, that element will be included in the filtered list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A filtered projection over the list. + **/ + createFiltered(predicate: (x: T) => boolean): FilteredListProjection; + + /** + * Creates a live grouped projection over this list. As the list changes, the grouped projection reacts to those changes and may also change. The grouped projection sorts all the elements of the list to be in group-contiguous order. The grouped projection also contains a .groups property, which is a List representing the groups that were found in the list. + * @param groupKey A function that accepts a single argument. The function is called with each element in the list, the function should return a string representing the group containing the element. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param groupData A function that accepts a single argument. The function is called once, on one element per group. It should return the value that should be set as the data of the .groups list element for this group. The data value usually serves as summary or header information for the group. + * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). + * @returns A grouped projection over the list. + **/ + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + + /** + * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. + * @param sorter A function that accepts two arguments. The function is called with elements in the list. It must return one of the following numeric values: negative if the first argument is less than the second, zero if the two arguments are equivalent, positive if the first argument is greater than the second. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A sorted projection over the list. + **/ + createSorted(sorter: (left: T, right: T) => number): SortedListProjection; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Checks whether the specified callback function returns true for all elements in a list. + * @param callback A function that accepts up to three arguments. This function is called for each element in the list until it returns false or the end of the list is reached. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if the callback returns true for all elements in the list. + **/ + every(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Returns the elements of a list that meet the condition specified in a callback function. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the elements that meet the condition specified in the callback function. + **/ + filter(callback: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; + + /** + * Calls the specified callback function for each element in a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. The arguments are as follows: value, index, array. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + **/ + forEach(callback: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + /** + * Gets the value at the specified index. + * @param index The index of the value to get. + * @returns The value at the specified index. + **/ + getAt(index: number): T; + + /** + * Gets the index of the first occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + * @returns The index of the first occurrence of a value in a list or -1 if not found. + **/ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns a string consisting of all the elements of a list separated by the specified separator string. + * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. + * @returns The elements of a list separated by the specified separator string. + **/ + join(separator: string): string; + + /** + * Gets the index of the last occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. + * @returns The index of the last occurrence of a value in a list, or -1 if not found. + **/ + lastIndexOf(searchElement: T, fromIndex: number): number; + + /** + * Calls the specified callback function on each element of a list, and returns an array that contains the results. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. + * @param thisArg n object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the result of calling the callback function on each element in the list. + **/ + map(callback: (value: T, index: number, array: T[]) => G, thisArg?: any): G[]; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Forces the list to send a reload notification to any listeners. + **/ + notifyReload(): void; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initiallValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the function provides this value as an argument instead of a list value. + * @returns The return value from the last call to the callback function. + **/ + reduce(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initiallValue?: T): T; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list, starting with the last member of the list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initialValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the callback function provides this value as an argument instead of a list value. + * @returns The return value from the last call to callback function. + **/ + reduceRight(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initialValue?: T): T; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Extracts a section of a list and returns a new list. + * @param begin The index that specifies the beginning of the section. + * @param end The index that specifies the end of the section. + * @returns Returns a section of list. + **/ + slice(begin: number, end: number): T[]; + + /** + * Checks whether the specified callback function returns true for any element of a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list until it returns true, or until the end of the list. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if callback returns true for any element in the list. + **/ + some(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + //#region Properties + + /** + * Gets the IListDataSource for the list. The only purpose of this property is to adapt a List to the data model that is used by ListView and FlipView. + **/ + dataSource: WinJS.UI.IListDataSource; + + /** + * Indicates that the object is compatibile with declarative processing. + **/ + static supportedForProcessing: boolean; + + //#endregion Properties + } + + /** + * Represents a base class for normal list modifying operations. + **/ + class ListBaseWithMutators extends ListBase { + //#region Methods + + /** + * Removes the last element from a list and returns it. + * @returns The last element from the list. + **/ + pop(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the end of the list. + * @returns The new length of the list. + **/ + push(value: T): number; + + /** + * Removes the first element from a list and returns it. + * @returns The first element from the list. + **/ + shift(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the start of the list. + * @returns The new length of the list. + **/ + unshift(value: T): number; + + //#endregion Methods + } + + /** + * Represents a base class for list projections. + **/ + class ListProjection extends ListBaseWithMutators { + //#region Methods + + /** + * Disconnects a WinJS.Binding.List projection from its underlying WinJS.Binding.List. It's only important to call this method when the WinJS.Binding.List projection and the WinJS.Binding.List have different lifetimes. (Call this method on the WinJS.Binding.List projection, not the underlying WinJS.Binding.List.) + **/ + dispose(): void; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Moves the value at index to position newIndex. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + } + + /** + * Provides a standard implementation of the bindable contract, as well as a basic storage mechanism that participates in change notification and an asynchronous notification implementation. + **/ + var mixin: { + //#region Methods + + /** + * Adds a property to the object. The property includes change notification and an ECMAScript 5 property definition . + * @param name The name of the property to add. + * @param value The value of the property. + * @returns This object is returned. + **/ + addProperty(name: string, value: any): any; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Provides functions that can make an object observable. + **/ + var observableMixin: { + //#region Methods + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + }; + + /** + * Do not instantiate. Returned by the createSorted method. + **/ + class SortedListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value to be replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list. Returns an integer value one higher than the highest element defined in a list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Provides a reusable declarative binding element. + **/ + class Template { + //#region Constructors + + /** + * Creates a template that provides a reusable declarative binding element. + * @constructor + * @param element The DOM element to convert to a template. + * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. + **/ + constructor(element: HTMLElement, options?: string); + + //#endregion Constructors + + //#region Methods + + render: { + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + (dataContext: any, container?: HTMLElement): Promise; + + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + value(href: string, dataContext: any, container?: HTMLElement): Promise; + }; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that is used as the template. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + //#endregion Objects + + //#region Functions + + /** + * Returns an observable object. This may be an observable proxy for the specified object, an existing proxy, or the specified object itself if it directly supports observation. + * @param data The object to observe. + * @returns The observable object. + **/ + function as(data: U): U; + + /** + * Binds to one or more properties on the observable object or or on child values of that object. + * @param observable The object to bind to. + * @param bindingDescriptor An object literal containing the binding declarations. Binding declarations take the form: { propertyName: (function | bindingDeclaration), ... }. + * @returns An object that contains at least a "cancel" field, which is a function that removes all bindings associated with this bind request. + **/ + function bind(observable: any, bindingDescriptor: any): any; + + /** + * Creates a default binding initializer for binding between a source property and a destination property with the specified converter function that is executed on the value of the source property. + * @param convert The conversion function that takes the source property and produces a value that is set to the destination property. This function must be accessible from the global namespace. + * @returns The binding initializer. + **/ + function converter(convert: Function): Function; + + /** + * Creates a one-way binding between the source object and the destination object. Warning Do not attempt to bind data to the ID of an HTML element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function defaultBind(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Creates a new constructor function that supports observability with the specified set of properties. + * @param data The object to use as the pattern for defining the set of properties. + * @returns A constructor function with 1 optional argument that is the initial state of the properties. + **/ + function define(data: any): Function; + + /** + * Wraps the specified object so that all its properties are instrumented for binding. This is meant to be used in conjunction with the binding mixin. + * @param shape The specification for the bindable object. + * @returns An object with a set of properties all of which are wired for binding. + **/ + function expandProperties(shape: any): any; + + /** + * Marks a custom initializer function as being compatible with declarative data binding. + * @param customInitializer The custom initializer to be marked as compatible with declarative data binding. + * @returns The input customInitializer. + **/ + function initializer(customInitializer: Function): Function; + + /** + * Sets the destination property to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function oneTime(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Binds the values of an object to the values of a DOM element that has the data-win-bind attribute. If multiple DOM elements are to be bound, you must set the attribute on all of them. See the example below for details. + * @param rootElement Optional. The element at which to start traversing to find elements to bind to. If this parameter is omitted, the entire document is searched. + * @param dataContext The object that contains the values to which the DOM element should be bound. + * @param skipRoot If true, specifies that only the children of rootElement should be bound, otherwise rootElement should be bound as well. + * @param bindingCache The cached binding data. + * @param defaultInitializer The binding initializer to use in the case that one is not specified in a binding expression. If not provided, the behavior is the same as Binding.defaultBind. + * @returns A Promise that completes when every item that contains the data-win-bind attribute has been processed and the update has started. + **/ + function processAll(rootElement?: Element, dataContext?: any, skipRoot?: boolean, bindingCache?: any, defaultInitializer?: Function): Promise; + + /** + * Creates a one-way binding between the source object and an attribute on the destination element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + * @returns An object with a cancel() method that is used to coalesce bindings. + **/ + function setAttribute(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): any; + + /** + * Sets an attribute on the destination element to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + **/ + function setAttributeOneTime(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): void; + + /** + * Returns the original (non-observable) object is returned if the specified object is an observable proxy, + * @param data The object for which to retrieve the original value. + * @returns If the specified object is an observable proxy, the original object is returned, otherwise the same object is returned. + **/ + function unwrap(data: any): any; + + //#endregion Functions + + //#region Interfaces + + interface IKeyDataPair { + key: string; + data: T; + } + + //#endregion Interfaces + +} +/** + * Provides helper functions for defining Classes. +**/ +declare module WinJS.Class { + //#region Functions + + /** + * Defines a class using the given constructor and the specified instance members. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods made available on the type. + * @param staticMembers The set of static fields, properties, and methods made available on the type. + * @returns The newly-defined type. + **/ + function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + + /** + * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. + * @param baseClass The type to inherit from. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods to be made available on the type. + * @param staticMembers The set of static fields, properties, and methods to be made available on the type. + * @returns The newly-defined type. + **/ + function derive(baseClass: any, constructor: Function, instanceMembers?: any, staticMembers?: any): any; + + /** + * Defines a class using the given constructor and the union of the set of instance members specified by all the mixin objects. The mixin parameter list is of variable length. For more information, see Adding functionality with WinJS mixins. + * @param constructor A constructor function that will be used to instantiate this class. + * @param mixin An object declaring the set of instance members. The mixin parameter list is of variable length. + * @returns The newly defined class. + **/ + function mix(constructor: Function, ...mixin: any[]): any; + + //#endregion Functions + +} +/** + * The WinJS namespace provides special Windows Library for JavaScript functionality, including Promise and xhr. +**/ +declare module WinJS { + //#region Properties + + /** + * Can be set to show the results of a validation process. + **/ + var validation: boolean; + + //#endregion Properties + + //#region Objects + + /** + * An error object. + **/ + class ErrorFromName { + //#region Constructors + + /** + * Creates an Error object with the specified name and message properties. + * @constructor + * @param name The name of this error. The name is meant to be consumed programmatically and should not be localized. + * @param message The message for this error. The message is meant to be consumed by humans and should be localized. + **/ + constructor(name: string, message?: string); + + //#endregion Constructors + + } + + /** + * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + **/ + class Promise { + //#region Constructors + + /** + * A promise provides a mechanism to schedule work to be done on a value that has not yet been computed. It is a convenient abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + * @constructor + * @param init The function that is called during construction of the Promise that contains the implementation of the operation that the Promise will represent. This can be synchronous or asynchronous, depending on the nature of the operation. Note that placing code within this function does not automatically run it asynchronously; that must be done explicitly with other asynchronous APIs such as setImmediate, setTimeout, requestAnimationFrame, and the Windows Runtime asynchronous APIs. The init function is given three arguments: completeDispatch, errorDispatch, progressDispatch. This parameter is optional. + * @param onCancel The function to call if a consumer of this promise wants to cancel its undone work. Promises are not required to support cancellation. + **/ + constructor(init?: (completeDispatch: any, errorDispatch: any, progressDispatch: any) => void, onCancel?: Function); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when there is an error in processing a promise. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener for the promise. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Returns a promise that is fulfilled when one of the input promises has been fulfilled. + * @param value An array that contains Promise objects or objects whose property values include Promise objects. + * @returns A promise that on fulfillment yields the value of the input (complete or error). + **/ + static any(value: Promise[]): Promise; + + /** + * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. + * @param value The value to be treated as a Promise. + * @returns The promise. + **/ + static as(value: U): Promise; + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Raises an event of the specified type and properties. + * @param type The type (name) of the event. + * @param details The set of additional properties to be attached to the event object. + * @returns true if preventDefault was called on the event; otherwise, false. + **/ + dispatchEvent(type: string, details: any): boolean; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + + /** + * Determines whether a value fulfills the promise contract. + * @param value A value that may be a promise. + * @returns true if the object conforms to the promise contract (has a then function), otherwise false. + **/ + static is(value: any): boolean; + + /** + * Creates a Promise that is fulfilled when all the values are fulfilled. + * @param values An object whose members contain values, some of which may be promises. + * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. + **/ + static join(values: any): Promise; + + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param capture Specifies whether or not to initiate capture. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + + /** + * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. + * @param values A set of values (which could be either an array or an object) of which some or all are promises.. + * @param complete The function to be called if the promise is fulfilled with a value. This function takes a single argument, which is the fulfilled value of the promise. + * @param error The function to be called if the promise is fulfilled with an error. This function takes a single argument, which is the error value of the promise. + * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. + * @returns A Promise that is the result of calling join on the values parameter. + **/ + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + + /** + * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. + * @param timeout The timeout period in milliseconds. If this value is zero or not specified, msSetImmediate is called, otherwise setTimeout is called. + * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. + * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. + **/ + static timeout(timeout: number, promise?: Promise): Promise; + + /** + * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. + * @param value Some non-promise value to be wrapped in a promise. + * @returns A promise that is successfully fulfilled with the specified value. + **/ + static wrap(value: U): Promise; + + /** + * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. + * @param error A non-promise error value to be wrapped in a promise. + * @returns A promise that is in an error state with the specified value. + **/ + static wrapError(error: U): Promise; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * You can provide an implementation of this method yourself, or use WinJS.Utilities.startLog to create one that logs to the JavaScript console. + * @param message The message to log. + * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). + * @param type The type of message (error, warning, info, etc.). + **/ + function log(message: string, tags: string, type: string): void; + + /** + * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. + **/ + function strictProcessing(): void; + + /** + * Wraps calls to XMLHttpRequest in a promise. + * @param options The options that are applied to the XMLHttpRequest object, as follows: type, url, user, password, responseType, headers, data, customRequestInitializer. + * @returns A promise that returns the XMLHttpRequest object when it completes. + **/ + function xhr(options: IXHROptions): Promise; + + //#endregion Functions + + //#region Interfaces + + interface IXHROptions { + type?: string; + url: string; + user?: string; + password?: string; + headers?: any; + data: any; + responseType?: string; + } + + //#endregion Interfaces +} +/** + * Provides helper functions for defining namespaces. For more information, see Organizing your code with WinJS.Namespace. +**/ +declare module WinJS.Namespace { + //#region Functions + + /** + * Defines a new namespace with the specified name. For more information, see Organizing your code with WinJS.Namespace. + * @param name The name of the namespace. This could be a dot-separated name for nested namespaces. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function define(name?: string, members?: any): any; + + /** + * Defines a new namespace with the specified name under the specified parent namespace. For more information, see Organizing your code with WinJS.Namespace. + * @param parentNamespace The parent namespace. + * @param name The name of the new namespace. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function defineWithParent(parentNamespace?: any, name?: string, members?: any): any; + + //#endregion Functions + +} +/** + * Provides functionality for dealing with basic navigation, including the navigation stack. +**/ +declare module WinJS.Navigation { + //#region Properties + + /** + * Determines whether it is possible to navigate backwards. + **/ + var canGoBack: boolean; + + /** + * Determines if it is possible to navigate forwards. + **/ + var canGoForward: boolean; + + /** + * Gets or sets the navigation history. + **/ + var history: any; + + /** + * Gets or sets the current location. + **/ + var location: string; + + /** + * Gets or sets a user-defined object that represents the state associated with the current location. + **/ + var state: any; + + //#endregion Properties + + //#region Functions + + /** + * Adds an event listener to the control. + * @param eventType The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + function addEventListener(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Navigates backwards. + * @param distance The number of entries to go back into the history. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function back(distance?: number): Promise; + + /** + * Navigates forwards. + * @param distance The number of entries to go forward. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function forward(distance?: number): Promise; + + /** + * Navigates to a location. + * @param location The location to navigate to. Generally the location is a string containing the URL, but it may be anything. + * @param initialState A user-defined object that represents the navigation state that may be accessed through state. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful (true if successful, otherwise false). + **/ + function navigate(location: any, initialState?: any): Promise; + + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(eventType: string, listener: Function, useCapture?: boolean): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs before navigation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onbeforenavigate(eventInfo: CustomEvent): void; + + /** + * Occurs after navigation has taken place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigated(eventInfo: CustomEvent): void; + + /** + * Occurs when navigation is taking place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigating(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides functions for accessing resources and localizing content. +**/ +declare module WinJS.Resources { + //#region Functions + + /** + * Registers an event handler for the specified event. Use this method to register for events that are related to resources, such as when the app's language, scale, or contrast changes. + * @param type The name of the event to handle. + * @param listener The listener (event handler function) to associate with the event. + * @param useCapture Set to true to register the listener for the capturing phase; otherwise, set to false to register the listener for the bubbling phase. + **/ + function addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The name of the event to raise. + * @param details The set of additional properties to attach to the event object. + **/ + function dispatchEvent(type: string, details: any): void; + + /** + * Retrieves the resource string that has the specified resource identifier. + * @param resourceId The resource ID of the string to retrieve. + * @returns An object that can contain these properties: value, empty, lang. + **/ + function getString(resourceId: string): { value: string; empty?: boolean; lang?: string; }; + + /** + * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. + * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. + **/ + function processAll(rootElement?: HTMLElement): void; + + /** + * Removes an event listener that the addEventListener method registered. + * @param type The name of the event that the event listener is registered for. + * @param listener The listener (event handler function) to remove. + * @param useCapture Set to true to remove the capturing phase listener; set to false to remove the bubbling phase listener. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs when the user changes the system's language or contrast, or the scale of the display, or when the user changes any of the items in the current context's qualifier values list. For more info about the current context's qualifier values list, see the Remarks section. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.qualifier, detail.changed. + **/ + function oncontextchanged(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides access to the Windows animations. These functions provide developers with the ability to use animations in their custom controls that are consistent with animations used by Windows controls. +**/ +declare module WinJS.UI.Animation { + //#region Functions + + /** + * Creates an object that performs an animation that adds an item or items to a list. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToListAnimation(added: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that adds an item or items to a list of search results. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToSearchListAnimation(added: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that collapses a list. + * @param hidden Element or elements hidden as a result of the collapse. + * @param affected Element or elements affected by the hidden items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createCollapseAnimation(hidden: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that removes an item or items from a list. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that removes an item or items from a list of search results. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromSearchListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that expands a list. + * @param revealed Element or elements revealed by the expansion. + * @param affected Element or elements affected by the newly revealed items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createExpandAnimation(revealed: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs a peek animation. + * @param element Element or elements involved in the peek. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createPeekAnimation(element: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that moves an item or items. + * @param element Element or elements involved in the reposition. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise object that completes when the animation is finished. + **/ + function createRepositionAnimation(element: any): IAnimationMethodResponse; + + /** + * Performs an animation that fades an item or items in, fading out existing items that occupy the same space. + * @param incoming Element or elements being faded in. + * @param outgoing Element or elements being replaced. + * @returns An object that completes when the animation has finished. + **/ + function crossFade(incoming: any, outgoing: any): Promise; + + /** + * Performs an animation when a dragged object is moved such that dropping it in that position would move other items. The potentially affected items are animated out of the way to show where the object would be dropped. + * @param target Element or elements that the dragged object would cause to be moved if it were dropped. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenEnter(target: any, offset: any): Promise; + + /** + * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. + * @param target Element or elements that the dragged object would no longer cause to be displaced, due to its moving away. This should be the same element or element collection passed as the target parameter in the dragBetweenEnter animation. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenLeave(target: any): Promise; + + /** + * Performs an animation when the user finishes dragging an object. + * @param dragSource Element or elements that were dragged. + * @param offset Initial offset from the drop point. The dropped object begins at the offset and animates to its final position at the drop point. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + + /** + * Performs an animation when the user begins to drag an object. + * @param dragSource Element or elements being dragged. + * @param affected Element or elements whose position is affected by the movement of the dragged object. Typically, this is all other items in a reorderable list. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceStart(dragSource: any, affected?: any): Promise; + + /** + * Performs an animation that displays one or more elements on a page. + * @param incoming Element or elements that compose the incoming content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function enterContent(incoming: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. + * @param element Element or an array of elements that represent the content. If element refers to an array of elements, the elements enter in array order. + * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function enterPage(element: any, offset: any): Promise; + + /** + * Performs an animation that hides one or more elements on a page. + * @param outgoing Element or elements that compose the outgoing content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitContent(outgoing: any, offset: any): Promise; + + /** + * Performs an animation that dismisses the current page when transitioning between pages in an app. + * @param outgoing Element or elements that compose the outgoing page. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitPage(outgoing: any, offset: any): Promise; + + /** + * Performs an animation that fades an item or set of items into view. + * @param shown Element or elements being faded in. + * @returns An object that completes when the animation has finished. Use this object when subsequent actions need this animation to finish before they take place. + **/ + function fadeIn(shown: any): Promise; + + /** + * Performs an animation that fades an item or set of items out of view. + * @param hidden Element or elements being faded out. + * @returns An object that completes when the animation is finished. + **/ + function fadeOut(hidden: any): Promise; + + /** + * Performs an animation that hides edge-based user interface (UI). + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function hideEdgeUI(element: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that hides a panel. + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function hidePanel(element: any, offset: any): Promise; + + /** + * Performs an animation that removes pop-up user interface (UI). + * @param element Element or elements that are being hidden. + * @returns An object that completes when the animation is finished. + **/ + function hidePopup(element: any): Promise; + + /** + * Performs an animation when a pointer is pressed on an object. + * @param element Element or elements on which the pointer is pressed. + * @returns An object that completes when the animation is finished. + **/ + function pointerDown(element: any): Promise; + + /** + * Performs an animation when a pointer is released. + * @param element Element or elements that the pointer was pressed on. + * @returns An object that completes when the animation is finished. + **/ + function pointerUp(element: any): Promise; + + /** + * Performs an animation that slides a narrow, edge-based user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function showEdgeUI(element: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that slides a large panel user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPanel(element: any, offset: any): Promise; + + /** + * Performs an animation that displays a pop-up user interface (UI). + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPopup(element: any, offset: any): Promise; + + /** + * Performs a deselection animation in response to a swipe interaction. + * @param deselected Element or elements that become unselected. + * @param selection Element or elements that represent the selection, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeDeselect(deselected: any, selection: any): Promise; + + /** + * Performs an animation that reveals an item or items in response to a swipe interaction. + * @param target Element or elements being revealed. + * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function swipeReveal(target: any, offset: any): Promise; + + /** + * Performs a selection animation in response to a swipe interaction. + * @param selected Element or elements being selected. + * @param selection Element or elements that show that something is selected, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeSelect(selected: any, selection: any): Promise; + + /** + * Performs an animation that updates a badge. + * @param incoming Element or elements that comprise the new badge. + * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function updateBadge(incoming: any, offset: any): Promise; + + //#endregion Functions + + //#region Interfaces + + interface IAnimationMethodResponse { + execute(): Promise; + } + + //#endregion Interfaces + +} +/** + * Provides controls and objects that manipulate data. +**/ +declare module WinJS.UI { + //#region Enumerations + + /** + * Specifies an icon that appears in an AppBarCommand object. + **/ + enum AppBarIcon { + previous, + next, + play, + pause, + edit, + save, + clear, + delete, + remove, + add, + cancel, + accept, + more, + redo, + undo, + home, + up, + forward, + right, + back, + left, + favorite, + camera, + settings, + video, + sync, + download, + mail, + find, + help, + upload, + emoji, + twopage, + leavechat, + mailforward, + clock, + send, + crop, + rotatecamera, + people, + closepane, + openpane, + world, + flag, + previewlink, + globe, + trim, + attachcamera, + zoomin, + bookmarks, + document, + protecteddocument, + page, + bullets, + comment, + mail2, + contactinfo, + hangup, + viewall, + mappin, + phone, + videochat, + switch, + contact, + rename, + pin, + musicinfo, + go, + keyboard, + dockleft, + dockright, + dockbottom, + remote, + refresh, + rotate, + shuffle, + list, + shop, + selectall, + orientation, + import, + importall, + browsephotos, + webcam, + pictures, + savelocal, + caption, + stop, + showresults, + volume, + repair, + message, + page2, + calendarday, + calendarweek, + calendar, + characters, + mailreplyall, + read, + link, + accounts, + showbcc, + hidebcc, + cut, + attach, + paste, + filter, + copy, + emoji2, + important, + mailreply, + slideshow, + sort, + manage, + allapps, + disconnectdrive, + mapdrive, + newwindow, + openwith, + contactpresence, + priority, + uploadskydrive, + gototoday, + font, + fontcolor, + contact2, + folder, + audio, + placeholder, + view, + setlockscreen, + settile, + cc, + stopslideshow, + permissions, + highlight, + disableupdates, + unfavorite, + unpin, + openlocal, + mute, + italic, + underline, + bold, + movetofolder, + likedislike, + dislike, + like, + alignright, + aligncenter, + alignleft, + zoom, + zoomout, + openfile, + otheruser, + admin, + street, + map, + clearselection, + fontdecrease, + fontincrease, + fontsize, + cellphone, + reshare, + tag, + repeatone, + repeatall, + outlinestar, + solidstar, + calculator, + directions, + target, + library, + phonebook, + memo, + microphone, + postupdate, + backtowindow, + fullscreen, + newfolder, + calendarreply, + unsyncfolder, + reporthacked, + syncfolder, + blockcontact, + switchapps, + addfriend, + touchpointer, + gotostart, + zerobars, + onebar, + twobars, + threebars, + fourbars, + scan, + preview + } + + /** + * Indicates whether the IListDataAdapter was able to provide a count. + **/ + enum CountResult { + /** + * Indicates no count is available. + **/ + unknown + } + + /** + * Indicates that the IListDataAdapter was unable to provide a count. + **/ + enum CountError { + /** + * An attempt to count items timed out. + **/ + noResponse + } + + /** + * Describes the status of an IListDataSource. + **/ + enum DataSourceStatus { + /** + * The IListDataSource is ready. + **/ + ready, + /** + * The IListDataSource is still loading. + **/ + waiting, + /** + * The IListDataSource failed to load. + **/ + failure + } + + /** + * Specifies the type of error that occurred during an edit operation on a IListDataSource or an IListDataAdapter. + **/ + enum EditError { + /** + * The edit operation timed out. + **/ + noResponse, + /** + * The data source cannot be written to. + **/ + notPermitted, + /** + * The item has changed. + **/ + noLongerMeaningful + } + + /** + * Specifies the type of error encountered when retrieving items from an IListDataAdapter. + **/ + enum FetchError { + /** + * The fetch operation timed out. + **/ + noResponse, + /** + * The specified item could not be located. + **/ + doesNotExist + } + + /** + * Specifies the position of group headers relative to their items in a ListView. + **/ + enum HeaderPosition { + /** + * Group headers appear to the left of items. + **/ + left, + /** + * Group headers appear above items. + **/ + top + } + + /** + * Specifies that type of animation for which a contentanimating event was raised. + **/ + enum ListViewAnimationType { + /** + * The animation plays when the ListView is first displayed. + **/ + entrance, + /** + * The animation plays when the ListView is changing its content. + **/ + contentTransition + } + + /** + * Specifies the selection mode of a ListView. + **/ + enum SelectionMode { + /** + * Items cannot be selected. + **/ + none, + /** + * A single item may be selected. + **/ + single, + /** + * Multiple items may be selected. Clicking additional items adds them to the selection. + **/ + multi + } + + /** + * Specifies whether elements are selected when the user performs a swipe interaction. + **/ + enum SwipeBehavior { + /** + * The swipe interaction selects the elements touched by the swipe. + **/ + select, + /** + * The swipe interaction does not change which elements are selected. + **/ + none + } + + /** + * Specifies how items in a ListView respond to the tap interaction. + **/ + enum TapBehavior { + /** + * The item is selected and invoked. + **/ + directSelect, + /** + * The item is selected if was not already selected, and its deselected if it was already selected. + **/ + toggleSelect, + /** + * The item is invoked but not selected. + **/ + invokeOnly, + /** + * Nothing happens. + **/ + none + } + + //#endregion Enumerations + + //#region Interfaces + + /** + * Contains items that were requested from an IListDataAdapter and provides some information about those items. + **/ + interface IFetchResult { + //#region Properties + + /** + * Gets or sets the index of the requested item in the IListDataAdapter object's data source. + **/ + absoluteIndex: number; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the last items at the end of the IListDataAdapter object's data source. + **/ + atEnd: boolean; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the first items at the beginning of the IListDataAdapter object's data source. + **/ + atStart: boolean; + + /** + * Gets or sets the items returned by the fetch operation. + **/ + items: T[]; + + /** + * Gets or sets the location of the requested item within the items array. + **/ + offset: number; + + /** + * Gets or sets the number of items in the IListDataAdapter object's underlying data source. + **/ + totalCount: number; + + //#endregion Properties + + } + + /** + * Represents an item in a list. + **/ + interface IItem { + //#region Properties + + /** + * Gets or sets the item's data. + **/ + data: T; + + /** + * Gets the group key for the item. This property is only available for items that belong to a grouped data source. + **/ + groupKey: string; + + /** + * Gets the temporary ID of the item. + **/ + handle: string; + + /** + * Gets the item's index in the IListDataSource. + **/ + index: number; + + /** + * Gets or sets the key the identifies the item. + **/ + key: string; + + //#endregion Properties + + } + + /** + * Provides a mechanism for retrieving IItem objects asynchronously. + **/ + interface IItemPromise { + //#region Events + + /** + * Occurs when there is an error in processing. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; + + /** + * Stops change notification tracking for the IItem that fulfills this IItemPromise. + **/ + release(): void; + + /** + * Begins change notification tracking for the IItem that fulfills this IItemPromise. + **/ + retain(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the complete or error function. + **/ + then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the temporary ID of the IItem that fulfills this promise. + **/ + handle: string; + + /** + * Gets or sets the index of the IItem contained by this IItemPromise. + **/ + index: number; + + //#endregion Properties + + } + + /** + * Represents a layout for the ListView. + **/ + interface ILayout { + //#region Methods + + /** + * Calculates the index of the first visible item. + * @param beginScrollPosition The first visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the first visible item at the specified point. + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): Promise; + + /** + * Calculates the index of the last visible item. + * @param endScrollPosition The last visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the last visible item at the specified point. + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): Promise; + + /** + * Ends the layout process. + * @returns A object that has these properties: animationPromise, newEndIndex. + **/ + endLayout(): any; + + /** + * Calculates the dimensions of an item. + * @param itemIndex The index of the item. + * @returns A Promise that returns an object with these properties: left, top, contentWidth, contentHeight, totalWidth, totalHeight. + **/ + getItemPosition(itemIndex: number): Promise; + + /** + * Gets the index of the next item relatively to the supplied index and keypress. + * @param itemIndex The data source index of the current item. + * @param element The element for the current item. + * @param keyPressed The key that was pressed. This function must check for the arrow keys (leftArrow, upArrow, rightArrow, downArrow), pageDown, and pageUp and determine which item the user navigated to. + * @returns A Promise that contains the index of the next item (This item becomes the current item). + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: WinJS.Utilities.Key): Promise; + + /** + * Gets the scrollbar range. + * @returns A Promise that returns an object that has these properties: beginScrollPosition, endScrollPosition. + **/ + getScrollBarRange(): Promise; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate to test. + * @param y The y-coordinate to test. + **/ + hitTest(x: number, y: number): void; + + /** + * Notifies of items being added. + * @param elements The elements that represent the items that were added. + **/ + itemsAdded(elements: HTMLElement[]): void; + + /** + * Notifies of items being moved. + **/ + itemsMoved(): void; + + /** + * Notifies of items being removed. + * @param elements The elements that represent the items that were removed. + **/ + itemsRemoved(elements: HTMLElement[]): void; + + /** + * Lays out the specified header at the specified index. + * @param groupIndex The index of the group in the group data source. + * @param element The element to render for the group header. + **/ + layoutHeader(groupIndex: number, element: HTMLElement): void; + + /** + * Lays out the specified item at the speficied index. + * @param itemIndex The index of the item in the data source. + * @param element The element to render for the item. + **/ + layoutItem(itemIndex: number, element: HTMLElement): void; + + /** + * Prepares the header element. + * @param element The element that represents a header in the data source. + **/ + prepareHeader(element: HTMLElement): void; + + /** + * Prepares the item element. + * @param element An element that represents an item in the data source. + **/ + prepareItem(element: HTMLElement): void; + + /** + * Releases the item. + * @param element The element being released. + **/ + releaseItem(element: HTMLElement): void; + + /** + * Resets the layout. + **/ + reset(): void; + + /** + * Sets the ILayoutSite object. + * @param site The layout site for the layout. You can use this object to query the hosting ListView for info you might need to lay out items. + **/ + setSite(site: ILayoutSite): void; + + /** + * Starts the layout. + * @param beginScrollPosition The starting pixel of the area to which the items are rendered. + * @param endScrollPosition The last pixel of the area to which the items are rendered. + * @param count The upper bound of the number of items to render. + * @returns A Promise that returns an object that has these properties: beginIndex, endIndex. + **/ + startLayout(beginScrollPosition: number, endScrollPosition: number, count: number): Promise; + + //#endregion Methods + + //#region Properties + + /** + * A flag indicating whether the direction of this layout implementation is horizontal. + **/ + horizontal: boolean; + + //#endregion Properties + + } + + /** + * Represents a rendering site for an ILayout. + **/ + interface ILayoutSite { + //#region Properties + + /** + * Gets or sets whether animations are disabled. + **/ + animationsDisabled: boolean; + + /** + * Gets the item surface element. + **/ + itemSurface: HTMLElement; + + /** + * Gets or sets whether this layout is in RTL mode. + **/ + rtl: boolean; + + /** + * Gets or sets the scrollbar position. + **/ + scrollbarPos: number; + + /** + * Gets the surface element. + **/ + surface: HTMLElement; + + /** + * Gets the viewport element. + **/ + viewport: HTMLElement; + + /** + * Gets the viewport size. + **/ + viewportSize: any; + + //#endregion Properties + + } + + /** + * Retrieves items from a IListDataSource, enumerates the contents of a IListDataSource, and can optionally register for change notifications. + **/ + interface IListBinding { + //#region Methods + + /** + * Retrieves the current item. + * @returns An IItemPromise that contains the current item. If the cursor has moved past the start or end of the list, the promise completes with a value of null. If the current item has been moved or deleted, the promise returns an error. + **/ + current(): IItemPromise>; + + /** + * Gets the first item from the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. If the list is empty, the promise completes with a value of null. + **/ + first(): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified description and makes it the current item. + * @param description A domain-specific description, to be interpreted by the IListDataAdapter, that identifies the item to retrieve. + * @returns An IItemPromise that contains the requested IItem object. If the item wasn't found, the promise completes with a value of null. + **/ + fromDescription(description: string): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified index and makes it the current item. + * @param index A value greater than or equal to 0 that is the index of the item to retrieve. + * @returns An IItemPromise that contains the requested IItem. If the item wasn't found, the promise completes with a value of null. + **/ + fromIndex(index: number): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified key and makes it the current item. + * @param key The key that identifies the item to retrieve. This value must be a non-empty string. + * @param hints Domain-specific information that provides additional information to the IListDataAdapter to improve retrieval time. + * @returns An IItemPromise that contains the requested IItem. If they item couldn't be found, the promise completes with a value of null. + **/ + fromKey(key: string, hints?: any): IItemPromise>; + + /** + * Makes the specified IItem or IItemPromise the current item. + * @param item The IItem or IItemPromise that will become the current item. + * @returns An IItemPromise that contains the specified item, if it exists. If the specified item is not in the list, the promise completes with a value of null. + **/ + jumpToItem(item: IItem): IItemPromise>; + + /** + * Retrieves the last item in the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. f the list is empty, the promise completes with a value of null. + **/ + last(): IItemPromise>; + + /** + * Retrieves the item after the current item and makes it the current item. + * @returns An IItemPromise that contains the item after the current item. If the cursor moves past the end of the list, the promise completes with a value of null. + **/ + next(): IItemPromise>; + + /** + * Retrieves the item before the current item and makes it the current item. + * @returns An IItemPromise that contains the item before the current item. If the cursor moves past the start of the list, the promise completes with a value of null. + **/ + previous(): IItemPromise>; + + /** + * Releases resources, stops notifications, and cancels outstanding promises for all tracked items returned by this IListBinding. + **/ + release(): void; + + /** + * Creates a request to stop change notifications for the specified item. The change notifications stop when the number of releaseItem calls matches the number of IIItemPromise.retain calls. + * @param item The IItem or IItemPromise that should stop receiving notifications. + **/ + releaseItem(item: IItem): void; + + //#endregion Methods + + } + + /** + * Accesses data for an IListDataSource. + **/ + interface IListDataAdapter { + //#region Methods + + /** + * Overwrites the data of the specified item. + * @param key The key of the item to overwrite. + * @param newData The new data for the item. + * @param indexHint The index of the item, if known. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + change(key: string, newData: T, indexHint: number): Promise; + + /** + * Gets the number of items in the IListDataAdapter object's data source. + * @returns A Promise that contains the number of items the IListDataAdapter contains, or an approximate value if the actual number is unknown. + **/ + getCount(): Promise; + + /** + * Inserts the specified data after the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param previousKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted after this item. + * @param previousIndexHint The index of the item to insert the new data after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string, previousIndexHint: number): Promise>; + + /** + * Adds the specified key and data to the end of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds the specified key and data to the beginning of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts the specified data before the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param nextKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted before this item. + * @param nextIndexHint The index of the item to insert the new data before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string, nextIndexHint: number): Promise>; + + /** + * Retrieves the item that matches the specified description and also retrieves the specified number of items before and after the matched item. + * @param description A description of the item to locate. + * @param countBefore The number of items before the matched item to retrieve. + * @param countAfter The number of items after the matched item to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromDescription(description: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the end of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromEnd(count: number): Promise>; + + /** + * Retrieves the item at the specified index and also retrieves the specified number of items before and after the selected item. + * @param index The index of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromIndex(index: number, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the item that has the specified key and also retrieves the specified number of items before and after the selected item. + * @param key The key of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromKey(key: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the beginning of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromStart(count: number): Promise>; + + /** + * Returns a string representation of the specified item that can be used for comparisons. + * @param item The item for which to generate a signature. + * @returns The signature representation of the specified item. + **/ + itemSignature(item: IItem): string; + + /** + * Moves the specified item to just after another item. + * @param key A key of the item to move. + * @param previousKey The key of another item. The item to move will be moved to just after this item. + * @param indexHint The index of the item to move, if known. + * @param previousIndexHint The index to move the item after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: any, indexHint: string, previousIndexHint: number): Promise>; + + /** + * Moves the specified item to just before another item. + * @param key A key of the item to move. + * @param nextKey The key of another item. The item to move will be moved to just before this item. + * @param indexHint The index of the item to move, if known. + * @param nextIndexHint The index to move the item before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: any, indexHint: string, nextIndexHint: number): Promise>; + + /** + * Moves the specified item to the end of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToEnd(key: string, indexHint: number): Promise>; + + /** + * Moves the specified item to the beginning of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToStart(key: string, indexHint: number): Promise>; + + /** + * Removes the specified item from the IListDataAdapter object's data source. + * @param key The key of the item to remove. + * @param data The new data for the item. + * @param indexHint The index of the item. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + remove(key: string, data: T, indexHint: number): Promise; + + /** + * Registers a notification handler. The IListDataAdapter uses the handler to notify listening objects when its data changes. + * @param notificationHandler The notification handler that the IListDataAdapter will use to provide change notifications. . + **/ + setNotificationHandler(notificationHandler: IListDataNotificationHandler): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether to use an object's identity to determine if an item has changed. + **/ + compareByIdentity: boolean; + + //#endregion Properties + + } + + /** + * Notifies clients when an IListDataAdapter object's data changes. + **/ + interface IListDataNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Raises a notification that an item in the IListDataAdapter object's data source has changed. + * @param item The item that changed. + **/ + changed(item: IItem): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Raises a notification that an item has been added to the IListDataAdapter object's data source. + * @param newItem The new item added to the IListDataAdapter object's data source. + * @param previousKey The key of the item that now precedes the new item, or null if the item was inserted at the start of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was inserted at the end of the list. If previousKey is provided, this parameter may be null. + * @param index The index of the new item. + **/ + inserted(newItem: IItem, previousKey: string, nextKey: string, index?: number): void; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all change notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Raises a notification that an item was moved within the IListDataAdapter object's data source. + * @param item The item that was moved. + * @param previousKey The key of the item that now precedes the new item, or null if the item was moved to the beginning of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was moved to the end of the list. If previousKey is provided, this parameter may be null. + * @param oldIndex The item's original index. + * @param newIndex The item's new index. + **/ + moved(item: IItem, previousKey: string, nextKey: string, oldIndex?: number, newIndex?: number): void; + + /** + * Reloads data from the IListDataAdapter. + **/ + reload(): void; + + /** + * Raises a notification that an item was removed from the IListDataAdapter object's data source. + * @param key The key of the item that was removed. + * @param index The index of the item that was removed. + **/ + removed(key: string, index?: number): void; + + //#endregion Methods + + } + + /** + * Provides access to a data source and enables you to bind, change, add, remove, and move items in that data source. + **/ + interface IListDataSource { + //#region Events + + /** + * Occurs when the status of the IListDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Notifies the IListDataSource that a sequence of edits is about to begin. The IListDataSource will defer notifications until endEdits is called. + **/ + beginEdits(): void; + + /** + * Overwrites the data of the specified item. + * @param key The key for the item to replace. + * @param newData The new data for the item. + * @returns A Promise that contains the IItem that was updated or an EditError if an error was encountered. + **/ + change(key: string, newData: T): Promise>; + + /** + * Creates an IListBinding that can retrieve items from the IListDataSource, enumerate the contents of the IListDataSource object's data, and optionally register for change notifications. + * @param notificationHandler Enables the IListBinding to register for change notifications for individual items obtained from the IListDataSource. If you omit this parameter, change notifications won't be available. + * @returns The new IListBinding. + **/ + createListBinding(notificationHandler?: IListNotificationHandler): IListBinding; + + /** + * Notifies the IListDataSource that the batch of edits that began with the last beginEdits call has completed. The IListDataSource will submit notifications for any changes that occurred between the beginEdits and endEdits calls as a batch and resume normal change notifications. + **/ + endEdits(): void; + + /** + * Retrieves the number of items in the data source. + * @returns A Promise that provides a Number that is the number of items in the data source. + **/ + getCount(): Promise; + + /** + * Inserts a new item after another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param previousKey The key for an item in the data source. The new item will be added after this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string): Promise>; + + /** + * Adds an item to the end of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds an item to the beginning of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts an item before another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param nextKey The key of an item in the data source. The new item will be inserted before this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string): Promise>; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Retrieves the item that has the specified description. + * @param description Domain-specific information, to be interpreted by the IListDataAdapter, that describes the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromDescription(description: any): Promise>; + + /** + * Retrieves the item at the specified index. + * @param index A value that is greater than or equal to zero that is the index of the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromIndex(index: number): Promise>; + + /** + * Retrieves the item with the specified key. + * @param key The key of the item to retrieve. It must be a non-empty string. + * @param description Domain-specific information that IListDataAdapter can use to improve the retrieval time. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item was not found, the promise completes with a null value. + **/ + itemFromKey(key: string, description?: any): Promise>; + + /** + * Moves an item to just after another item. + * @param key The key that identifies the item to move. + * @param previousKey The key of another item in the data source. The item specified by the key parameter will be moved after this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: string): Promise>; + + /** + * Moves an item before another item. + * @param key The key that identifies the item to move. + * @param nextKey The key of another item in the data source. The item specified by the key parameter will be moved before this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: string): Promise>; + + /** + * Moves an item to the end of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToEnd(key: string): Promise>; + + /** + * Moves the specified item to the beginning of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToStart(key: string): Promise>; + + /** + * Removes the specified item from the data source. + * @param key The key that identifies the item to remove. + * @returns A Promise that contains nothing if the operation was successful or an EditError if an error was encountered. + **/ + remove(key: string): Promise>; + + //#endregion Methods + + } + + /** + * Used by an IListBinding to provide change notifications when items in a IListDataSource change. + **/ + interface IListNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Indicates that an item changed. + * @param newItem The updated item. + * @param oldItem The original item. + **/ + changed(newItem: IItem, oldItem: IItem): void; + + /** + * Indicates that the number of items in the IListDataSource has changed. + * @param newCount The updated count. + * @param oldCount The original count. + **/ + countChanged(newCount: number, oldCount: number): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Indicates that the index of an item changed. + * @param handle The temporary ID of the item. + * @param newIndex The new index. + * @param oldIndex The original index. + **/ + indexChanged(handle: string, newIndex: number, oldIndex: number): void; + + /** + * Indicates that an item was added to the IListDataSource. + * @param itemPromise A promise for the new IItem. + * @param previousHandle The temporary ID of the item that precedes the new item. + * @param nextHandle The temporary ID of the item that follows the new item. + **/ + inserted(itemPromise: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an IItemPromise was fulfilled and that the item is now available. + * @param item The fulfilled item. + **/ + itemAvailable(item: IItem): void; + + /** + * Indicates that an item was moved. + * @param item A promise for the IItem that was moved. + * @param previousHandle The temporary ID of the item that now precedes the moved item. + * @param nextHandle The temporary ID of the item that now follows the moved item. + **/ + moved(item: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an item was removed. + * @param handle The temporary ID of the item that was removed. + * @param mirage true if the item never actually existed; false if the item was actually present in the IListDataSource. + **/ + removed(handle: string, mirage: boolean): void; + + //#endregion Methods + + } + + /** + * Used by ListView's currentItem API + **/ + interface IListViewItem { + /** + * Gets or sets index of the ListView item. + **/ + index?: number; + + /** + * Gets or sets key of the ListView item. + **/ + key?: string; + + /** + * Gets or sets whether the ListView item is focused. + **/ + hasFocus?: boolean; + + /** + * Gets or sets whether the ListView item is focused and is showing its focus visual. + **/ + showFocus?: boolean; + } + + /** + * Represents a selection of ListView items. + **/ + interface ISelection { + //#region Methods + + /** + * Adds one or more items to the selection. + * @param items The indexes or keys of the items to add. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + add(items: any): Promise; + + /** + * Clears the selection. + * @returns A Promise that is fulfilled when the clear operation completes. + **/ + clear(): Promise; + + /** + * Returns the number of items in the selection. + * @returns The number of items in the selection. + **/ + count(): number; + + /** + * Returns a list of the indexes for the items in the selection. + * @returns The list of indexes for the items in the selection as an array of Number objects. + **/ + getIndices(): number[]; + + /** + * Returns an array that contains the items in the selection. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + getItems(): Promise[]>; + + /** + * Gets an array of the index ranges for the selected items. + * @returns An array that contains an ISelectionRange object for each index range in the selection. + **/ + getRanges(): ISelectionRange[]; + + /** + * Returns a value that indicates whether the selection contains every item in the data source. + * @returns true if the selection contains every item in the data source; otherwise, false. + **/ + isEverything(): boolean; + + /** + * Removes the specified items from the selection. + * @param items The indexes or keys of the items to remove. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + remove(items: any): Promise; + + /** + * Adds all the items in the ListView to the selection. + **/ + selectAll(): void; + + /** + * Clears the current selection and replaces it with the specified items. + * @param items The indexes or keys of the items that make up the selection. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + set(items: any): Promise; + + //#endregion Methods + + } + + /** + * Represents a range of indexes or keys in an ISelection. + **/ + interface ISelectionRange { + //#region Properties + + /** + * Gets or sets the index of the first item in the range. + **/ + firstIndex: number; + + /** + * Gets or sets the key of the first item in the range. + **/ + firstKey: any; + + /** + * Gets or sets the index of the last item in the range. + **/ + lastIndex: number; + + /** + * Gets or sets of the key of the last item in the range. + **/ + lastKey: any; + + //#endregion Properties + + } + + /** + * Supports semantic zoom functionality by exposing a control as either the zoomed in or the zoomed out view of the SemanticZoom control. + **/ + interface IZoomableView { + //#region Methods + + /** + * Initiates semantic zoom on the custom control. + **/ + beginZoom(): void; + + /** + * Initializes the semantic zoom state for the custom control. + * @param isZoomedOut True if this is the zoomed out view; otherwise false. + * @param isCurrentView True if this is the current view; otherwise false. + * @param triggerZoom The function that manages semantic zoom behavior. Triggers a zoom in or zoom out if the control is the visible control. + * @param prefetchedPages The number of pages of content to pre-fetch for zooming. This value is dependent on the size of the semantic zoom container. More content can be displayed based on the zoom factor and the size of the container. + **/ + configureForZoom(isZoomedOut: boolean, isCurrentView: boolean, triggerZoom: Function, prefetchedPages: number): void; + + /** + * Terminates semantic zoom on the zoomed in or zoomed out child of the custom control. + * @param isCurrentView True if the control is the visible control; otherwise false. + **/ + endZoom(isCurrentView: boolean): void; + + /** + * Retrieves the current item of the zoomed in or zoomed out child of the custom control. + * @returns An object that represents the selected item. This return value must be a Promise for the following: item, position. + **/ + getCurrentItem(): Promise<{ item: T; position: Utilities.IPosition }>; + + /** + * Retrieves the panning axis of the zoomed-in or zoomed-out child of the custom control. + * @returns Identifies the panning axis of the child control. Implementation specific. + **/ + getPanAxis(): string; + + /** + * Manages pointer input for the custom control. + * @param pointerId The ID of the pointer. + **/ + handlePointer(pointerId: string): void; + + /** + * Positions the specified item within the viewport of the child control when panning or zooming begins. + * @param item The object to position within the viewport of the child control. item can be a number, a string, or an object with any number of properties. + * @param position An object that contains the position data of the item relative to the child control. position must be an object with four number properties: left, top, width, and height. These values specify a rectangle that is typically the bounding box of the current item, though the details are up to the control. The units of the position must be in pixels. And the coordinates must be relative to the top-left of the control viewport (which should occupy the same area as the semantic zoom viewport), except when in RTL mode. In RTL mode, return coordinates relative to the top-right off the control viewport. The rectangle is transformed from the coordinate system of one control to that of the other. + **/ + positionItem(item: T, position: Utilities.IPosition): void; + + /** + * Selects the item closest to the specified screen coordinates. + * @param x The x-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport. + * @param y The y-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport.. + **/ + setCurrentItem(x: number, y: number): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * Represents an application toolbar for displaying commands. + **/ + class AppBar { + //#region Constructors + + /** + * Creates a new AppBar object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBar. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the AppBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs after the AppBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the AppBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden AppBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Returns the AppBarCommand object identified by id. + * @param id The element idenitifier (ID) of the command to be returned. + * @returns The command identified by id. If multiple commands have the same ID, returns an array of all the commands matching the ID. + **/ + getCommandById(id: string): AppBarCommand; + + /** + * Hides the AppBar. + **/ + hide(): void; + + /** + * Hides the specified commands of the AppBar. + * @param commands The commands to hide. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate?: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the AppBar if it is not disabled. + **/ + show(): void; + + /** + * Shows the specified commands of the AppBar. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate?: boolean): void; + + /** + * Shows the specified commands of the AppBar while hiding all other commands. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Sets the AppBarCommand objects that appear in the app bar. + **/ + commands: AppBarCommand[]; + + /** + * Gets or sets a value that indicates whether the AppBar is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBar. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the AppBar is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the layout of the app bar contents. + **/ + layout: string; + + /** + * Gets or sets a value that specifies whether the AppBar appears at the top or bottom of the main view. + **/ + placement: string; + + /** + * Gets or sets a value that indicates whether the AppBar is sticky (won't light dismiss). If not sticky, the app bar dismisses normally when the user touches outside of the appbar. + **/ + sticky: boolean; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in an app bar. + **/ + class AppBarCommand { + //#region Constructors + + /** + * Creates a new AppBarCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBarCommand. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the AppBarCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBarCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the AppBarCommand's button is invoked. + **/ + flyout: Flyout; + + /** + * Gets or sets a value that indicates whether the AppBarCommand is hiding or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the icon of the AppBarCommand. + **/ + icon: string; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets the section of the app bar that the command is in. + **/ + section: string; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets or sets the tooltip of the command. + **/ + tooltip: string; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Allows users to pick a date value. + **/ + class DatePicker { + //#region Constructors + + /** + * Initializes a new instance of the DatePicker control. + * @constructor + * @param element The DOM element associated with the DatePicker control. + * @param options The set of options to be applied initially to the DatePicker control. The options are the following: calendar, current, datePattern, disabled, maxYear, minYear, monthPattern, yearPattern. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when any of the controls are changed by the user. + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener. + * @param type The type (name) of the event. + * @param listener The function that handles the event. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes a listener for the specified event. + * @param type The name of the event for which to remove a listener. + * @param listener The listener. + * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. + **/ + removeEventListener(type: string, listener: Function, useCapture?: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the calendar to use. + **/ + calendar: string; + + /** + * Gets or sets the current date of the DatePicker. You can use either a date string or a Date object to set this property. + **/ + current: Date; + + /** + * Gets or sets the display pattern for the date. The default date pattern is day.integer(2). You can change the date pattern by changing the number of integers displayed. + **/ + datePattern: string; + + /** + * Specifies whether the DatePicker is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element for the DatePicker. + **/ + element: HTMLElement; + + /** + * Gets or sets the maximum Gregorian year available for picking. + **/ + maxYear: number; + + /** + * Gets or sets the minimum Gregorian year available for picking. + **/ + minYear: number; + + /** + * Gets or sets the display pattern for the month. The default month pattern is month.abbreviated. You can change the month pattern to the following values: month.full. The full name of the month. month.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. If you do specify the number of letters, the actual length of the month name that appears may vary. month.solo.full. A representation of the month that is suitable for stand-alone display. You can also use month.solo.abbreviated(n). month.integer(n). You can use integer with or without specifying the number of integers. + **/ + monthPattern: string; + + /** + * Gets or sets the display pattern for the year. The default year pattern is year.full. You can change the year pattern to the following values: year.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. + **/ + yearPattern: string; + + //#endregion Properties + + } + + /** + * Adds event-related methods to the control. + **/ + class DOMEventMixin { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture true to initiate capture; otherwise, false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type, adding the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true to initiate capture; otherwise, false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If the name of the options property begins with "on", the property value is a function and the control supports addEventListener. This method calls the addEventListener method on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + setOptions(control: any, options: any): void; + + //#endregion Methods + + } + + /** + * Displays a collection, such as a set of photos, one item at a time. + **/ + class FlipView { + //#region Constructors + + /** + * Creates a new FlipView. + * @constructor + * @param element The DOM element that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the pageselected event, add a property named "onpageselected" and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the datasource count changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: source. + **/ + ondatasourcecountchanged(eventInfo: Event): void; + + /** + * Raised when the FlipView flips to a page and its renderer function completes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpagecompleted(eventInfo: CustomEvent): void; + + /** + * Raised when the FlipView flips to a page. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpageselected(eventInfo: CustomEvent): void; + + /** + * Occurs when an item becomes invisible or visible. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source, detail.visible. + **/ + onpagevisibilitychanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. For a list of events, see the FlipView object page. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Returns the number of items in the FlipView control's itemDataSource. + * @returns A Promise that contains the number of items in the list or WinJS.UI.CountResult.unknown if the count is unavailable. + **/ + count(): Promise; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Forces the FlipView to update its layout. Use this function when making the FlipView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Navigates to the next page. + * @returns true if the FlipView begins navigating to the next page; false if the FlipView is already at the last item or is in the middle of another navigation animation. + **/ + next(): boolean; + + /** + * Navigates to the previous item. + * @returns true if the FlipView begins navigating to the previous page; nfalse if the FlipView is already at the first page or is in the middle of another navigation animation. + **/ + previous(): boolean; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event. + * @param eventHandler The event handler function to remove. + * @param useCapture Set to true to unregister the event handler for the capturing phase; otherwise, set to false to unregister the event handler for the bubbling phase. + **/ + removeEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Sets custom animations for the FlipView to use when navigating between pages. + * @param animations An object that contains up to three fields, one for each navigation action: next, previous, and jump. Each of those fields must be a function with this signature: function (outgoingPage, incomingPage) Each function must return a WinJS.Promise that completes once the animations are finished. If a field is null or undefined, the FlipView reverts to its default animation for that action. + **/ + setCustomAnimations(animations: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the index of the currently displayed page. + **/ + currentPage: number; + + /** + * Gets the HTML element that hosts this FlipView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that provides the FlipView with items to display. The FlipView displays one item at a time, on its own page. + **/ + itemDataSource: IListDataSource; + + /** + * Gets or sets the spacing between each item, in pixels. + **/ + itemSpacing: number; + + /** + * Gets or sets a Template or function that defines the HTML for each item's page. + **/ + itemTemplate: any; + + /** + * Gets or sets the orientation of the FlipView, horizontal or vertical. + **/ + orientation: string; + + //#endregion Properties + + } + + /** + * Displays lightweight UI that is either information, or requires user interaction. Unlike a dialog, a Flyout can be light dismissed by clicking or tapping off of it. + **/ + class Flyout { + //#region Constructors + + /** + * Creates a new Flyout object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new Flyout. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised immediately after a flyout is fully hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised immediately after a flyout is fully shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before hiding a flyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Raised just before showing a flyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Hides the Flyout, if visible, regardless of other states. + **/ + hide(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the Flyout, if hidden, regardless of other states. + * @param anchor Required. The DOM element to anchor the Flyout. + * @param placement The placement of the Flyout to the anchor: the string literal "top", "bottom", "left", or "right". + * @param alignment For "top" or "bottom" placement, the alignment of the Flyout to the anchor's edge: the string literal "center", "left", or "right". + **/ + show(anchor: HTMLElement, placement: string, alignment: string): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default alignment to be used for this Flyout. + **/ + alignment: string; + + /** + * Gets or sets the default anchor to be used for this Flyout. + **/ + anchor: HTMLElement; + + /** + * Gets the DOM element that hosts the Flyout. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the Flyout is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the default placement to be used for this Flyout. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Represents a grid layout for the ListView in which items are arranged in a horizontal grid. + **/ + class GridLayout { + //#region Constructors + + /** + * Creates a new GridLayout object. + * @constructor + * @param options The set of properties and values to apply to the new GridLayout. + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Calculates the index of the first visible item. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * Calculates the index of the last visible item. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * Ends the layout process. + **/ + endLayout(): void; + + /** + * Calculates the dimensions of an item. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * Gets the index of the next item relatively to the supplied index and keypress. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: any, keyPressed: any): void; + + /** + * Gets the scrollbar range. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * Initializes this layout. + **/ + init(): void; + + /** + * Notifies of items being added. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * Notifies of items being moved. + **/ + itemsMoved(): void; + + /** + * Notifies of items being removed. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * Lays out the specified header at the specified index. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * Lays out the specified item at the speficied index. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * Prepares the header element. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * Prepares the item element. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * Releases the item. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * Resets the layout. + **/ + reset(): void; + + /** + * Sets the ILayoutSite object. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * Starts the layout. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * Updates the backdrop count. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the backdrop css color. + **/ + backdropColor: string; + + /** + * Gets or sets whether backdrops are disabled. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * Gets or sets the groupInfo function. + **/ + groupInfo: Function; + + /** + * Gets or sets whether the orientation of this layout is horizontal. + **/ + horizontal: boolean; + + /** + * Gets or sets the itemInfo function. + **/ + itemInfo: Function; + + /** + * Gets or sets the maximum number of rows to display. + **/ + maxRows: number; + + //#endregion Properties + + } + + /** + * Enables you to include an HTML page dynamically. As part of the constructor, you must include an option indicating the URI of the page. + **/ + class HtmlControl { + //#region Constructors + + /** + * Initializes a new instance of HtmlControl to define a new page control. + * @constructor + * @param element The element that hosts the HtmlControl. + * @param options The options for configuring the page. The uri option is required in order to specify the source document for the content of the page. Other options are the ones used by the WinJS.Pages.render method. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + } + + /** + * This object supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + class Layout { + } + + /** + * Represents a layout for the ListView in which items are arranged in a vertical list. + **/ + class ListLayout { + //#region Constructors + + /** + * Creates a new ListLayout. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new ListLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Calculates the index of the first visible item. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * Calculates the index of the last visible item. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * Ends the layout process. + **/ + endLayout(): void; + + /** + * Calculates the dimensions of an item. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * Gets the index of the next item relatively to the supplied index and keypress. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: any): void; + + /** + * Gets the scrollbar range. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * Initializes this layout. + **/ + init(): void; + + /** + * Notifies of items being added. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel + * @param lastPixel + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * Notifies of items being moved. + **/ + itemsMoved(): void; + + /** + * Notifies of items being removed. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * Lays out the specified header at the specified index. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * Lays out the specified item at the speficied index. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * Prepares the header element. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * Prepares the item element. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * Releases the item. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * Resets the layout. + **/ + reset(): void; + + /** + * Sets the ILayoutSite object. + * @param layoutSite + **/ + setSite(layoutSite: ILayoutSite): void; + + /** + * Starts the layout. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * Updates the backdrop count. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the backdrop css color. + **/ + backdropColor: string; + + /** + * Gets or sets whether backdrops are disabled. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * Gets or sets the groupInfo function. + **/ + groupInfo: Function; + + /** + * Gets or sets whether the orientation of this layout is horizontal. + **/ + horizontal: boolean; + + /** + * Gets or sets the itemInfo function. + **/ + itemInfo: Function; + + //#endregion Properties + + } + + /** + * Displays data items in a customizable list or grid. + **/ + class ListView { + //#region Constructors + + /** + * Creates a new ListView. + * @constructor + * @param element The DOM element that hosts the ListView control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the selectionchanged event, add a property named "onselectionchanged" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ListView is about to play an entrance or contentTransition animation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.setPromise. + **/ + oncontentanimating(eventInfo: CustomEvent): void; + + /** + * Occurs when the user taps or clicks an item. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.itemIndex. + **/ + oniteminvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the focused item changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.oldFocus, detail.oldNewFocus. + **/ + onkeyboardnavigating(eventInfo: CustomEvent): void; + + /** + * Occurs when the ListView control's loadingState changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.scrolling. + **/ + onloadingstatechanged(eventInfo: CustomEvent): void; + + /** + * Occurs after the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. To obtain the selected items, use the ListView.selection property. + **/ + onselectionchanged(eventInfo: CustomEvent): void; + + /** + * Occurs just before the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.newSelection, detail.preventTapBehavior. + **/ + onselectionchanging(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the ListView object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onselectionchange", you specify "selectionchange". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Returns the DOM element that represents the item at the specified index. + * @param itemIndex The index of the item. + * @returns The DOM element that represents the item at the specified index. + **/ + elementFromIndex(itemIndex: number): HTMLElement; + + /** + * Makes the item at the specified index visible. If necessary, the ListView will scroll to the item. + * @param itemIndex The index of the item to scroll into view. + **/ + ensureVisible(itemIndex: number): void; + + /** + * Forces the ListView to update its layout. Use this function when making the ListView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Returns the index of the item that the specified DOM element displays. + * @param element The DOM element that displays the item. + * @returns The index of the item displayed by element. + **/ + indexOfElement(element: HTMLElement): number; + + /** + * Loads the next set of pages if the ListView control's loadingBehavior is set to "incremental" (otherwise, it does nothing). The number of pages to be loaded is determined by the pagesToLoad property. + **/ + loadMorePages(): void; + + /** + * Repositions all the visible items in the ListView to adjust for items whose sizes have changed. Most apps won’t ever need to call this method. For more info, see the Remarks section. + **/ + recalculateItemPosition(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Triggers the ListView disposal service manually. + **/ + static triggerDispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the next set of pages is automatically loaded when the user scrolls beyond the number of pages specified by the pagesToLoadThreshold property. + **/ + automaticallyLoadPages: boolean; + + /** + * Gets or sets an IListViewItem that indicates which item should have keyboard focus and the focus state of that item. + **/ + currentItem: IListViewItem; + + /** + * Gets the HTML element that hosts this ListView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that contains the groups for the items in the itemDataSource. + **/ + groupDataSource: IListDataSource; + + /** + * Gets or sets the Template or function that creates the DOM elements for each group header in the groupDataSource. Each group header can contain multiple elements, but it must have a single root element. + **/ + groupHeaderTemplate: any; + + /** + * Gets or sets the first visible item. + **/ + indexOfFirstVisible: number; + + /** + * Gets the index of the last visible item in the ListView. + **/ + indexOfLastVisible: number; + + /** + * Gets or sets the data source that provides the ListView with items. + **/ + itemDataSource: IListDataSource; + + /** + * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the itemDataSource. Each item can contain multiple elements, but it must have a single root element. + **/ + itemTemplate: any; + + /** + * Gets or sets an object that controls the layout of the ListView. + **/ + layout: ILayout; + + /** + * Gets or sets a value that specifies how the ListView fetches items and adds and removes them to the DOM. Don't change the value of this property after the ListView has begun loading data. + **/ + loadingBehavior: string; + + /** + * Gets a value that indicates whether the ListView is still loading or whether loading is complete. + **/ + loadingState: string; + + /** + * Gets or sets the number of pages to load when the loadingBehavior property is set to "incremental" and the user scrolls beyond the threshold specified by the pagesToLoadThreshold property. + **/ + pagesToLoad: number; + + /** + * Gets or sets the threshold (in pages) for initiating an incremental load. When the last visible item is within the specified number of pages from the end of the loaded portion of the list, and if automaticallyLoadPages is true and loadingBehavior is set to "incremental", the ListView initiates an incremental load. + **/ + pagesToLoadThreshold: number; + + /** + * Gets or sets the function that is called when the ListView discards or recycles the element representation of a group header. + **/ + resetGroupHeader: (header: any, element: HTMLElement) => void; + + /** + * Gets or sets the function that is called when an item is removed, an item is changed, or an item falls outside of the realized range of the ListView. + **/ + resetItem: (item: T, element: HTMLElement) => void; + + /** + * Gets or sets the distance, in pixels, of the start of the viewable area within the viewport. + **/ + scrollPosition: number; + + /** + * Gets an ISelection that contains the range of currently selected items. + **/ + selection: ISelection; + + /** + * Gets or sets the selection mode of the ListView. + **/ + selectionMode: SelectionMode; + + /** + * Gets or sets how the ListView reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. + **/ + swipeBehavior: WinJS.UI.SwipeBehavior; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + /** + * Gets a ZoomableView that supports semantic zoom functionality. This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. + **/ + zoomableView: IZoomableView>; + + //#endregion Properties + + } + + /** + * Represents a menu flyout for displaying commands. + **/ + class Menu { + //#region Constructors + + /** + * Creates a new Menu object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new Menu. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the Menu is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs after the Menu is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the Menu is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden Menu is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Returns the MenuCommand object identified by id. + * @param id The element identifier (ID) of the command to be returned. + * @returns The command identified by id. + **/ + getCommandById(id: string): MenuCommand; + + /** + * Hides the Menu. + **/ + hide(): void; + + /** + * Hides the specified commands of the Menu. + * @param commands The commands to hide. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the Menu, if hidden, regardless of other states. + * @param anchor Required. The DOM element to anchor the Menu. + * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. + * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. + **/ + show(anchor: HTMLElement, placement: string, alignment: string): void; + + /** + * Shows the specified commands of the Menu. + * @param commands The commands to show. The array elements may be Menu objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate: boolean): void; + + /** + * Shows the specified commands of the Menu while hiding all other commands. + * @param commands The commands to show. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default alignment to be used for this Menu. + **/ + alignment: string; + + /** + * Gets or sets the default anchor to be used for this Menu. + **/ + anchor: HTMLElement; + + /** + * Sets the MenuCommand objects that appear in the menu. + **/ + commands: MenuCommand[]; + + /** + * Gets the DOM element that hosts the Menu. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the Menu is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the default placement to be used for this Menu. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in a Menu object. + **/ + class MenuCommand { + //#region Constructors + + /** + * Creates a new MenuCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new MenuCommand. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the MenuCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the MenuCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the MenuCommand's button is invoked. + **/ + flyout: Flyout; + + /** + * Gets a value that indicates whether the MenuCommand is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Lets the user rate something by clicking an icon that represents a rating. The Rating control can display three types of ratings: an average rating, a tentative rating, and the user's rating. + **/ + class Rating { + //#region Constructors + + /** + * Creates a new Rating. + * @constructor + * @param element The DOM element hosts the new Rating. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the user finishes interacting with the rating control without committing a tentative rating. + * @param eventInfo An object that contains information about the event. + **/ + oncancel(eventInfo: Event): void; + + /** + * Raised when the user commits a change to the userRating. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. + **/ + onchange(eventInfo: CustomEvent): void; + + /** + * Raised when the user is choosing a new tentative Rating. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. + **/ + onpreviewchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the average rating. + **/ + averageRating: number; + + /** + * Gets or sets whether the control is disabled. When the control is disabled, the user can't specify a new user rating or modify an existing rating. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the Rating. + **/ + element: HTMLElement; + + /** + * Gets or sets whether control lets the user clear the rating. + **/ + enableClear: boolean; + + /** + * Gets or sets the maximum possible rating value. + **/ + maxRating: number; + + /** + * Gets or sets a set of descriptions to show for rating values in the tooltip. + **/ + tooltipStrings: string[]; + + /** + * Gets or sets the user's rating. + **/ + userRating: number; + + //#endregion Properties + + } + + /** + * Enables the user to zoom between two different views supplied by two child controls. One child control supplies the zoomed-out view and the other provides the zoomed-in view. + **/ + class SemanticZoom { + //#region Constructors + + /** + * Creates a new SemanticZoom. + * @constructor + * @param element The DOM element that hosts the SemanticZoom. + * @param options An object that contains one or more property/value pairs to apply to the new control. This object can contain these properties: initiallyZoomedOut Boolean, zoomFactor 0.2–0.85. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the control zooms in or out. + * @param eventInfo An object that contains information about the event. The detail property of this object is true when the control is zoomed out. Otherwise, it's false. + **/ + onzoomchanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Forces the SemanticZoom to update its layout. Use this function when making the SemanticZoom visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the SemanticZoom control. + **/ + element: HTMLElement; + + /** + * Gets or a sets a value that specifies whether to display the SemanticZoom zoom out button. + **/ + enableButton: boolean; + + /** + * Determines whether any controls contained in a SemanticZoom should be processed separately. This property is always true, meaning that the SemanticZoom takes care of processing its own controls. + **/ + isDeclarativeControlContainer: boolean; + + /** + * Gets or sets a value that indicates whether SemanticZoom is locked and zooming between views is disabled. + **/ + locked: boolean; + + /** + * Gets or sets a value that indicates whether the control is zoomed out. + **/ + zoomedOut: boolean; + + /** + * Gets or sets a value that specifies how much the scaling the cross-fade animation performs when the SemanticZoom transitions between views. + **/ + zoomFactor: number; + + //#endregion Properties + + } + + /** + * Provides users with fast, in-context access to settings that affect the current Windows Store app. + **/ + class SettingsFlyout { + //#region Constructors + + /** + * Creates a new SettingsFlyout object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new SettingsFlyout. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised immediately after the SettingsFlyout is completely hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised immediately after a SettingsFlyout is fully shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before hiding a SettingsFlyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Raised just before showing a SettingsFlyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Hides the SettingsFlyout, if visible, regardless of other states. + **/ + hide(): void; + + /** + * Loads a fragment of the SettingsFlyout. Your app calls this when the user invokes a settings command and the WinJS.Application.onsettings event occurs. + * @param e An object that contains information about the event, received from the WinJS.Application.onsettings event. The detail property of this object contains the applicationcommands sub-property that you set to an array of settings commands. You then populate the SettingsFlyout with these commands by a call to populateSettings. + **/ + static populateSettings(e: CustomEvent): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the SettingsPane UI, if hidden. + **/ + show(): void; + + /** + * Shows the SettingsPane UI, if hidden, regardless of other state. + **/ + static show(): void; + + /** + * Show the Settings flyout using the Settings element identifier (ID) and the path of the page that contains the Settings element. + * @param id The ID of the Settings element. + * @param path The path of the page that contains the Settings element. + **/ + static showSettings(id: string, path: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element the SettingsFlyout is attached to. + **/ + element: HTMLElement; + + /** + * Gets whether the SettingsFlyout is hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the settings command Id for the SettingsFlyout control. + **/ + settingsCommandId: string; + + /** + * This property may be unavailable or altered in future versions. Use the CSS width property of the element that has the win-settingsflyout class instead. + **/ + width: string; + + //#endregion Properties + + } + + /** + * A type of IListDataSource that provides read-access to an object that implements the IStorageQueryResultBase interface. A StorageDataSource enables you to query and bind to items in the data source. + **/ + class StorageDataSource { + //#region Constructors + + /** + * Creates a new StorageDataSource object. + * @constructor + * @param query The IStorageQueryResultBase that the StorageDataSource obtains its items from. Instead of IStorageQueryResultBase, you can also pass one of these string values: Music, Pictures, Videos, Documents. + * @param options The set of properties and values to apply to the new StorageDataSource. Properties on this object may include: mode , requestedThumbnailSize , thumbnailOptions , synchronous . + **/ + constructor(query: any, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Draws the thumbnail for the specified item to the specified img element. + * @param item The item to retrieve the thumbnail for. + * @param image The img element that will display the thumbnail. + * @returns A Promise that completes when the full-quality thumbnail is visible. + **/ + loadThumbnail(item: IItem, image: HTMLImageElement): Promise; + + //#endregion Methods + + } + + /** + * Prevents a DOM sub-tree from receiving tab navigations and focus. + **/ + class TabContainer { + //#region Constructors + + /** + * Creates a new TabContainer. + * @constructor + * @param element The DOM element that hosts the TabContainer control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Properties + + /** + * Gets or sets the child DOM element that receives tab focus. + **/ + childFocus: HTMLElement; + + /** + * Gets or sets the tab index of this container. + **/ + tabIndex: number; + + //#endregion Properties + + } + + /** + * Allows users to select time values. + **/ + class TimePicker { + //#region Constructors + + /** + * Initializes a new instance of a TimePicker control. + * @constructor + * @param element The DOM element associated with the TimePicker control. + * @param options The set of options to be applied initially to the TimePicker control. The options are the following: clock. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when any of the controls are changed by the user. + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener. + * @param type The type (name) of the event. + * @param listener The function that handles the event. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes a listener for the specified event. + * @param type The name of the event for which to remove a listener. + * @param listener The listener. + * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. + **/ + removeEventListener(type: string, listener: Function, useCapture?: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the type of clock to display (12HourClock or 24HourClock). It defaults to the user setting. + **/ + clock: string; + + /** + * Gets or sets the current time of the TimePicker. Note that the date value is always July 15, 2011. + **/ + current: Date; + + /** + * Specifies whether the TimePicker is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element for the TimePicker. + **/ + element: HTMLElement; + + /** + * Gets or sets the display pattern for the hour. The default hour pattern is hour.integer(2). You can change the hour pattern by changing the number of integers displayed. + **/ + hourPattern: string; + + /** + * Gets or sets the minute increment. For example, 15 specifies that the TimePicker minute control should display only the choices 00, 15, 30, 45. + **/ + minuteIncrement: number; + + /** + * Gets or sets the display pattern for the minute. The default minute pattern is minute.integer(2). You can change the minute pattern by changing the number of integers displayed. + **/ + minutePattern: string; + + /** + * Gets or sets the display pattern for the period. The default period pattern is period.abbreviated(2). You can change the period pattern by changing the number of integers displayed. + **/ + periodPattern: string; + + //#endregion Properties + + } + + /** + * A control that lets the user switch an option between two states: on (checked is set to true) and off (checked is set to false). + **/ + class ToggleSwitch { + //#region Constructors + + /** + * Creates a new ToggleSwitch. + * @constructor + * @param element The DOM that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the change event, add a property named "onchange" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ToggleSwitch control is flipped to on (checked == true) or off (checked == false). + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Handles the specified event. + * @param event The event. + **/ + handleEvent(event: any): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the control is on or off. + **/ + checked: boolean; + + /** + * Gets or sets a value that specifies whether the control is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the ToggleSwitch. + **/ + element: HTMLElement; + + /** + * Gets or sets the text that displays when the ToggleSwitch is off (checked is set to false). + **/ + labelOff: string; + + /** + * Gets or sets the text that displays when the ToggleSwitch is on (checked is set to true). + **/ + labelOn: string; + + /** + * Gets or sets the main text for the ToggleSwitch control. This text is always displayed, regardless of whether the control is switched on or off. + **/ + title: string; + + //#endregion Properties + + } + + /** + * Displays a tooltip that can contain images and formatting. + **/ + class Tooltip { + //#region Constructors + + /** + * Creates a new Tooltip. + * @constructor + * @param element The DOM element associated that hosts the Tooltip. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the opened event, add a property named "onopened" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised just before the Tooltip is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeclose(eventInfo: CustomEvent): void; + + /** + * Raised just before the Tooltip appears. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeopen(eventInfo: CustomEvent): void; + + /** + * Raised when the Tooltip is no longer displayed. + * @param eventInfo An object that contains information about the event. + **/ + onclosed(eventInfo: CustomEvent): void; + + /** + * Raised when the Tooltip is shown. + * @param eventInfo An object that contains information about the event. + **/ + onopened(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Hides the Tooltip. + **/ + close(): void; + + /** + * Shows the Tooltip. + * @param type A value that specifies when to show the Tooltip. The default value is "mousedown". + **/ + open(type?: string): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the HTML element that is the content of the Tooltip. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts the Tooltip control. + **/ + element: HTMLElement; + + /** + * Gets or appends additional CSS classes to apply to the element that hosts the Tooltip. + **/ + extraClass: string; + + /** + * Gets or sets a value that specifies whether the Tooltip is an infotip, a tooltip that contains a lot of info and should be displayed for longer than a typical Tooltip. + **/ + infotip: boolean; + + /** + * Gets or sets the HTML content of the Tooltip. + **/ + innerHTML: string; + + /** + * Gets or sets the position for the Tooltip relative to its target element: top, bottom, left or right. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Scales a single child element to fill the available space without resizing it. This control reacts to changes in the size of the container as well as changes in size of the child element. For example, a media query may result in a change in aspect ratio. + **/ + class ViewBox { + //#region Constructors + + /** + * Initializes a new instance of the ViewBox control. + * @constructor + * @param element The DOM element that functions as the scaling box. This element fills 100% of the width and height allotted to it. + * @param options The set of options to be applied initially to the ViewBox control. There are currently no options on this control, and any options included in this parameter are ignored. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Forces the ViewBox to update its layout. Use this function when making the ViewBox visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that functions as the scaling box. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + /** + * Serves as the base class for a custom IListDataSource. + **/ + class VirtualizedDataSource { + //#region Constructors + + /** + * Initializes the VirtualizedDataSource base class of a custom data source. + * @constructor + * @param listDataAdapter The object that supplies data to the VirtualizedDataSource. + * @param options An object that can contain properties that specify additional options for the VirtualizedDataSource. It supports these properties: cacheSize. + **/ + constructor(listDataAdapter: IListDataAdapter, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the status of the VirtualizedDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the VirtualizedDataSource object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onstatuschanged", you specify "statuschanged". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. See the VirtualizedDataSource object page for a list of events. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * Returns a new IListDataSource that adds group information to the items of another IListDataSource. + * @param listDataSource The data source for the individual items to group. + * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. + * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. + * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. + * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + **/ + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + + /** + * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. + **/ + function disableAnimations(): void; + + /** + * Used to enable all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be enabled, as the determination is made based on several factors. + **/ + function enableAnimations(): void; + + /** + * Marks a event handler function as being compatible with declarative processing. + * @param handler The handler to be marked as compatible with declarative processing. + * @returns The handler, marked as compatible with declarative processing. + **/ + function eventHandler(handler: any): any; + + /** + * Asynchronously executes a collection of CSS animations on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements to be animated. This parameter can be expressed in several ways: As the special value "undefined", which means that the animation has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param animation The animation description or an array of animation descriptions to apply to element. An animation description is a JavaScript object with specific properties, listed below. There are two types of animation descriptions: one for keyframe-based animations and one for explicit animations. These types are distinguished by whether the keyframe property has a defined value. The following properties are required for both types of animation descriptions: property (string), delay (number), duration (number), timing (string). If an animation has a keyframe property with a defined, non-null value, then the animation is a keyframe-based animation. A keyframe-based animation description requires the following property in addition to those mentioned above: keyframe (string). If an animation does not have a keyframe property, or if the value of the property is null or undefined, then the animation is an explicit animation. An explicit animation description requires the following properties in addition to the common properties mentioned above: from, to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise object that completes when the CSS animation is complete. + **/ + function executeAnimation(element: HTMLElement, animation: any): Promise; + + /** + * Asynchronously executes a collection of CSS transitions on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements on which to perform the transition. This parameter can be expressed in several ways: As the special value "undefined", which means that the transition has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param transition The transition description or an array of transition descriptions to apply to element. A transition description is a JavaScript object with these properties: property (string), delay (number), duration (number), timing (string), from (optional), to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise that completes when the transition is finished. + **/ + function executeTransition(element: HTMLElement, transition: any): Promise; + + /** + * Retrieves the items in the specified index range. + * @param dataSource The data source that contains the items to retrieve. + * @param ranges An array of ISelectionRange objects that have firstIndex and lastIndex values. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + function getItemsFromRanges(dataSource: IListDataSource, ranges: ISelectionRange[]): Promise>; + + /** + * Determines whether the Animations Library and ListView animations will be performed if called. + * @returns Returns true if animations will be performed; otherwise false. + **/ + function isAnimationEnabled(): boolean; + + /** + * Applies declarative control binding to all elements, starting at the specified root element. + * @param rootElement The element at which to start applying the binding. If this parameter is not specified, the binding is applied to the entire document. + * @param skipRoot If true, the elements to be bound skip the specified root element and include only the children. + * @returns A promise that is fulfilled when binding has been applied to all the controls. + **/ + function processAll(rootElement?: Element, skipRoot?: boolean): Promise; + + /** + * Applies declarative control binding to the specified element. + * @param element The element to bind. + * @returns A promise that is fulfilled after the control is activated. The value of the promise is the control that is attached to element. + **/ + function process(element: Element): Promise; + + /** + * Walks the DOM tree from the given element to the root of the document. Whenever a selector scope is encountered, this method performs a lookup within that scope for the specified selector string. The first matching element is returned. + * @param selector The selector string. + * @param element The element to begin walking to the root of the document from. + * @returns The target element, if found. + **/ + function scopedSelect(selector: string, element: HTMLElement): HTMLElement; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If name of the options property begins with "on", the property value is a function and the control supports addEventListener. setControl calls addEventListener on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + function setOptions(control: any, options?: any): void; + + //#endregion Functions + +} +/** + * Provides functions to load HTML content programmatically. +**/ +declare module WinJS.UI.Fragments { + //#region Functions + + /** + * Starts loading the fragment at the specified location. The returned promise completes when the fragment is ready to be copied. + * @param href The URI that contains the fragment to be copied. + * @returns A promise that is fulfilled when the fragment has been prepared for copying. + **/ + function cache(href: string): Promise; + + /** + * Removes any cached information about the specified fragment. This method does not unload any scripts or styles that are referenced by the fragment. + * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. + **/ + function clearCache(href: string): void; + + /** + * Loads the contents of the specified URI into the specified element without copying it. + * @param href The URI that contains the fragment to copy. + * @param element Optional. The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The element is not added to the cache. See also rendercopy, where the element is added to the cache. + **/ + function render(href: string, element?: HTMLElement): Promise; + + /** + * Loads and copies the contents of the specified URI into the specified element. + * @param href The URI that contains the fragment to copy. + * @param target The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. + **/ + function renderCopy(href: string, target?: HTMLElement): Promise; + + //#endregion Functions + +} +/** + * Provides methods for defining and displaying PageControl objects. +**/ +declare module WinJS.UI.Pages { + //#region Interfaces + + /** + * Provides members for a PageControl. You implement this interface when defining a new PageControl. + **/ + interface IPageControlMembers { + //#region Methods + + /** + * Called if any error occurs during the processing of the page. + * @param err The error that occurred. + * @returns Nothing if the error was handled, or an error promise if the error was not handled. + **/ + error? (err: any): Promise; + + /** + * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + init? (element: HTMLElement, options: any): Promise; + + /** + * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. + * @param uri The URI from which to create DOM objects. + * @returns A promise whose fulfilled value is the set of unparented DOM objects. + **/ + load? (uri: string): Promise; + + /** + * Initializes the control after the content of the control is set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options that are to be passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + processed? (element: HTMLElement, options: any): Promise; + + /** + * Called after all initialization and rendering is complete. At this time, the element is ready for use. + * @param element The DOM element that contains all the content for the page. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. + **/ + ready? (element: HTMLElement, options: any): Promise; + + /** + * Takes the elements returned by the load method and attaches them to the specified element. + * @param element The DOM element to which the loadResult elements are appended. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param loadResult A Promise that contains the elements returned from the load method. + **/ + render? (element: HTMLElement, options: any, loadResult: Promise): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. + **/ + class PageControl { + } + + //#endregion Objects + + //#region Functions + + /** + * Creates a new PageControl from the specified URI that contains the specified members. Multiple calls to this method for the same URI are allowed, and all members will be merged. + * @param uri The URI for the content that defines the page. + * @param members An object that defines the members that the control will have. + * @returns A constructor function that creates the PageControl. + **/ + function define(uri: string, members: IPageControlMembers): PageControl; + + /** + * Gets an already-defined page control for the specified URI, or creates a new one. + * @param uri The URI for the content that defines the page. + * @returns A constructor function that creates the page. + **/ + function get(uri: string): Function; + + /** + * Creates a PageControl from the specified URI and inserts it inside the specified element. + * @param uri The URI for the content that defines the page. + * @param element The DOM element to which the PageControl is appended. + * @param options An object that contains one or more property/value pairs to apply to the new PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. + * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + + //#endregion Functions + +} +/** + * Provides methods for detecting when the user tabs to or from DOM elements. +**/ +declare module WinJS.UI.TrackTabBehavior { + //#region Functions + + /** + * Sets the tab order for the specified element within its container. + * @param element The element to update. + * @param tabIndex The index value of the element within its container. + **/ + function attach(element: HTMLElement, tabIndex: number): void; + + /** + * Removes the tab order information from the specified element. + * @param element The element to remove tab information from. + **/ + function detatch(element: HTMLElement): void; + + //#endregion Functions + +} +/** + * Provides helper functions, for example, functions to add and remove CSS classes. +**/ +declare module WinJS.Utilities { + //#region Enumerations + + /** + * Defines a set of keyboard values. + **/ + enum Key { + /** + * The BACKSPACE key. + **/ + backspace, + /** + * The TAB key. + **/ + tab, + /** + * The ENTER key. + **/ + enter, + /** + * The SHIFT key. + **/ + shift, + /** + * The CTRL key. + **/ + ctrl, + /** + * The ALT key. + **/ + alt, + /** + * The PAUSE key. + **/ + pause, + /** + * The CAPS LOCK key. + **/ + capsLock, + /** + * The ESCAPE key. + **/ + escape, + /** + * The SPACE key. + **/ + space, + /** + * The PAGE UP key. + **/ + pageUp, + /** + * The PAGE DOWN key. + **/ + pageDown, + /** + * The END key. + **/ + end, + /** + * The HOME key. + **/ + home, + /** + * The LEFT ARROW key. + **/ + leftArrow, + /** + * The UP ARROW key. + **/ + upArrow, + /** + * The RIGHT ARROW key. + **/ + rightArrow, + /** + * The DOWN ARROW key. + **/ + downArrow, + /** + * The INSERT key. + **/ + insert, + /** + * The DELETE key. + **/ + deleteKey, + /** + * The 0 key. + **/ + num0, + /** + * The 1 key. + **/ + num1, + /** + * The 2 key. + **/ + num2, + /** + * The 3 key. + **/ + num3, + /** + * The 4 key. + **/ + num4, + /** + * The 5 key. + **/ + num5, + /** + * The 6 key. + **/ + num6, + /** + * The 7 key. + **/ + num7, + /** + * The 8 key. + **/ + num8, + /** + * The 9 key. + **/ + num9, + /** + * The a key. + **/ + a, + /** + * The b key. + **/ + b, + /** + * The c key. + **/ + c, + /** + * The d key. + **/ + d, + /** + * The e key. + **/ + e, + /** + * The f key. + **/ + f, + /** + * The g key. + **/ + g, + /** + * The h key. + **/ + h, + /** + * The i key. + **/ + i, + /** + * The j key. + **/ + j, + /** + * The k key. + **/ + k, + /** + * The l key. + **/ + l, + /** + * The m key. + **/ + m, + /** + * The n key. + **/ + n, + /** + * The o key. + **/ + o, + /** + * The p key. + **/ + p, + /** + * The q key. + **/ + q, + /** + * The r key. + **/ + r, + /** + * The s key. + **/ + s, + /** + * The t key. + **/ + t, + /** + * The u key. + **/ + u, + /** + * The v key. + **/ + v, + /** + * The w key. + **/ + w, + /** + * The x key. + **/ + x, + /** + * The y key. + **/ + y, + /** + * The z key. + **/ + z, + /** + * The left Windows key. + **/ + leftWindows, + /** + * The right Windows key. + **/ + rightWindows, + /** + * The menu key. + **/ + menu, + /** + * The 0 key on the numerical keypad. + **/ + numPad0, + /** + * The 1 key on the numerical keypad. + **/ + numPad1, + /** + * The 2 key on the numerical keypad. + **/ + numPad2, + /** + * The 3 key on the numerical keypad. + **/ + numPad3, + /** + * The 4 key on the numerical keypad. + **/ + numPad4, + /** + * The 5 key on the numerical keypad. + **/ + numPad5, + /** + * The 6 key on the numerical keypad. + **/ + numPad6, + /** + * The 7 key on the numerical keypad. + **/ + numPad7, + /** + * The 8 key on the numerical keypad. + **/ + numPad8, + /** + * The 9 key on the numerical keypad. + **/ + numPad9, + /** + * The multiplication key (*). + **/ + multiply, + /** + * The addition key (+). + **/ + add, + /** + * The subtraction key (-). + **/ + subtract, + /** + * The decimal point key (.) + **/ + decimalPoint, + /** + * The division key (/). + **/ + divide, + /** + * The F1 key. + **/ + F1, + /** + * The F2 key. + **/ + F2, + /** + * The F3 key. + **/ + F3, + /** + * The F4 key. + **/ + F4, + /** + * The F5 key. + **/ + F5, + /** + * The F6 key. + **/ + F6, + /** + * The F7 key. + **/ + F7, + /** + * The F8 key. + **/ + F8, + /** + * The F9 key. + **/ + F9, + /** + * The F10 key. + **/ + F10, + /** + * The F11 key. + **/ + F11, + /** + * The F12 key. + **/ + F12, + /** + * The NUMBER LOCK key. + **/ + numLock, + /** + * The SCROLL LOCK key. + **/ + scrollLock, + /** + * The browser BACK key. + **/ + browserBack, + /** + * The browser FORWARD key. + **/ + browserForward, + /** + * The semicolon key (;). + **/ + semicolon, + /** + * The equals key (=). + **/ + equal, + /** + * The comma key (,). + **/ + comma, + /** + * The dash key (-). + **/ + dash, + /** + * The period key (.). + **/ + period, + /** + * The forward slash key (/). + **/ + forwardSlash, + /** + * The grave accent key (`). + **/ + graveAccent, + /** + * The open bracket key ([). + **/ + openBracket, + /** + * The backslash key (\). + **/ + backSlash, + /** + * The close bracket key (]). + **/ + closeBracket, + /** + * The single quote key ('). + **/ + singleQuote + } + + //#endregion Enumerations + + //#region Objects + + /** + * A mixin that contains event-related functions. + **/ + var eventMixin: { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + }; + + /** + * Represents the result of a query selector, and provides various operations that perform actions over the elements of the collection. + **/ + interface QueryCollection extends Array { + //#region Methods + + /** + * Adds the specified class to all the elements in the collection. + * @param name The name of the class to add. + * @returns This QueryCollection object. + **/ + addClass(name: string): QueryCollection; + + /** + * Creates a QueryCollection that contains the children of the specified parent element. + * @param element The parent element. + * @returns The QueryCollection that contains the children of the element. + **/ + children(element: HTMLElement): QueryCollection; + + /** + * Clears the specified style property for all the elements in the collection. + * @param name The name of the style property to be cleared. + * @returns This QueryCollection object. + **/ + clearStyle(name: string): QueryCollection; + + /** + * Creates controls that are attached to the elements in this QueryCollection, if the ctor parameter is a function, or configures the controls that are attached to the elements in this QueryCollection, if the ctor parameter is an object. + * @param ctor If this parameter is a function, it is a constructor function that is used to create controls to attach to the elements. If it is an object, it is the set of options passed to the controls. + * @param options The options passed to the newly-created controls. + * @returns This QueryCollection object. + **/ + control(ctor: any, options?: any): QueryCollection; + + /** + * Performs an action on each item in the QueryCollection. + * @param callbackFn The action to perform on each item. + * @param thisArg The argument to bind to callbackFn. + * @returns The QueryCollection. + **/ + forEach(callbackFn: (value: T, index: number, array: T[]) => void, thisArg?: any): QueryCollection; + + /** + * Gets an item from the QueryCollection. + * @param index The index of the item to return. + * @returns A single item from the collection. + **/ + get(index: number): T; + + /** + * Gets an attribute value from the first element in the collection. + * @param name The name of the attribute. + * @returns The value of the attribute. + **/ + getAttribute(name: string): any; + + /** + * Determines whether the specified class exists on the first element of the collection. + * @param name The name of the class. + * @returns true if the element has the specified class; otherwise, false. + **/ + hasClass(name: string): boolean; + + /** + * Looks up an element by ID and wraps the result in a QueryCollection. + * @param id The ID of the element. + * @returns A QueryCollection that contains the element, if it is found. + **/ + id(id: string): QueryCollection; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T): void; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T[]): void; + + /** + * Registers the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function to be called when the event occurs. + * @param capture true if capture == true is to be passed to addEventListener; otherwise, false. + **/ + listen(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Executes a query selector on all the elements in the collection and aggregates the result into a QueryCollection. + * @param query The query selector string. + * @returns A QueryCollection object containing the aggregate results of executing the query on all the elements in the collection. + **/ + query(query: any): QueryCollection; + + /** + * Removes the specified class from all the elements in the collection. + * @param name The name of the class to be removed. + * @returns his QueryCollection object. + **/ + removeClass(name: string): QueryCollection; + + /** + * Unregisters the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function. + * @param capture true if capture == true; otherwise, false. + * @returns This QueryCollection object. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): QueryCollection; + + /** + * Sets an attribute value on all the items in the collection. + * @param name The name of the attribute to be set. + * @param value The value of the attribute to be set. + * @returns This QueryCollection object. + **/ + setAttribute(name: string, value: any): QueryCollection; + + /** + * Sets the specified style property for all the elements in the collection. + * @param name The name of the style property. + * @param value The value for the property. + * @returns This QueryCollection object. + **/ + setStyle(name: string, value: any): QueryCollection; + + /** + * Renders a template that is bound to the given data and parented to the elements included in the QueryCollection. If the QueryCollection contains multiple elements, the template is rendered multiple times, once at each element in the QueryCollection per item of data passed. + * @param templateElement The DOM element to which the template control is attached. + * @param data The data to render. If the data is an array (or any other object that has a forEach method) then the template is rendered multiple times, once for each item in the collection. + * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. + * @returns The QueryCollection. + **/ + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + + /** + * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. + * @param name The name of the class to be toggled. + * @returns This QueryCollection object. + **/ + toggleClass(name: string): QueryCollection; + + //#endregion Methods + + } + + /** + * Constructor support for QueryCollection interface + **/ + export var QueryCollection: { + new (items: T[]): QueryCollection; + prototype: QueryCollection; + } + + //#endregion Objects + + //#region Functions + + /** + * Adds the specified class to the specified element. + * @param e The element to which to add the class. + * @param name The name of the class to add. + * @returns The element. + **/ + function addClass(e: T, name: string): T; + + /** + * Gets a collection of elements that are the direct children of the specified element. + * @param element The parent element. + * @returns The collection of children of the element. + **/ + function children(element: HTMLElement): QueryCollection; + + /** + * Converts a CSS positioning string for the specified element to pixels. + * @param element The element. + * @param value The CSS positioning string. + * @returns The number of pixels. + **/ + function convertToPixels(element: HTMLElement, value: string): number; + + /** + * Creates an object that has one event for each name passed to the function. + * @param events A variable list of property names. + * @returns The object with the specified properties. The names of the properties are prefixed with 'on'. + **/ + function createEventProperties(...events: string[]): any; + + /** + * Gets the data value associated with the specified element. + * @param element The element. + * @returns The value associated with the element. + **/ + function data(element: HTMLElement): any; + + /** + * Removes all the child nodes from the specified element. + * @param element The element. + * @returns The element. + **/ + function empty(element: T): T; + + /** + * Determines whether the specified event occurred within the specified element. + * @param element The element. + * @param event The event. + * @returns true if the event occurred within the element; otherwise, false. + **/ + function eventWithinElement(element: HTMLElement, event: Event): boolean; + + /** + * Adds tags and type to a logging message. + * @param message The message to be formatted. + * @param tag The tag(s) to be applied to the message. Multiple tags should be separated by spaces. + * @param type The type of the message. + * @returns The formatted message. + **/ + function formatLog(message: string, tag: string, type: string): string; + + /** + * Gets the height of the content of the specified element. The content height does not include borders or padding. + * @param element The element. + * @returns The content height of the element. + **/ + function getContentHeight(element: HTMLElement): number; + + /** + * Gets the width of the content of the specified element. The content width does not include borders or padding. + * @param element The element. + * @returns The content width of the element. + **/ + function getContentWidth(element: HTMLElement): number; + + /** + * Gets the leaf-level type or namespace specified by the name parameter. + * @param name The name of the member. + * @param root The root to start in. Defaults to the global object. + * @returns The leaf-level type or namespace in the specified parent namespace. + **/ + function getMember(name: string, root?: any): any; + + /** + * Gets the position of the specified element. + * @param element The element. + * @returns An object that contains the left, top, width and height properties of the element. + **/ + function getPosition(element: HTMLElement): IPosition; + + /** + * Gets the left coordinate of the specified element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative left coordinate. + **/ + function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the top coordinate of the element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative top coordinate. + **/ + function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the height of the element, including its margins. + * @param element The element. + * @returns The height of the element including margins. + **/ + function getTotalHeight(element: HTMLElement): number; + + /** + * Gets the width of the element, including margins. + * @param element The element. + * @returns The width of the element including margins. + **/ + function getTotalWidth(element: HTMLElement): number; + + /** + * Determines whether the specified element has the specified class. + * @param e The element. + * @param name The name of the class. + * @returns true if the element has the class, otherwise false. + **/ + function hasClass(e: HTMLElement, name: string): boolean; + + /** + * Returns a collection with zero or one elements matching the specified id. + * @param id The ID of the element (or elements). + * @returns A collection of elements whose id matches the id parameter. + **/ + function id(id: string): QueryCollection; + + /** + * Calls insertAdjacentHTML on the specified element. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text The text to insert. + **/ + function insertAdjacentHTML(element: HTMLElement, position: string, text: string): void; + + /** + * Calls insertAdjacentHTML on the specified element in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text Value to be provided to insertAdjacentHTML. + **/ + function insertAdjacentHTMLUnsafe(element: HTMLElement, position: string, text: string): void; + + /** + * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. + * @param func The function to be marked as compatible with declarative processing. + * @returns The input function, marked as compatible with declarative processing. + **/ + function markSupportedForProcessing(func: U): U; + + /** + * Returns a QueryCollection with zero or one elements matching the specified selector query. + * @param query The CSS selector to use. See Selectors for more information. + * @param element Optional. The root element at which to start the query. If this parameter is omitted, the scope of the query is the entire document. + * @returns A QueryCollection with zero or one elements matching the specified selector query. + **/ + function query(query: any, element?: HTMLElement): QueryCollection; + + /** + * Ensures that the specified function executes only after the DOMContentLoaded event has fired for the current page. The DOMContentLoaded event occurs after the page has been parsed but before all the resources are loaded. + * @param callback A function that executes after the DOMContentLoaded event has occurred. + * @param async If true, the callback should be executed asynchronously. + * @returns A promise that completes after the DOMContentLoaded event has occurred. + **/ + function ready(callback?: Function, async?: boolean): Promise; + + /** + * Removes the specified class from the specified element. + * @param e The element from which to remove the class. + * @param name The name of the class to remove. + * @returns The element. + **/ + function removeClass(e: T, name: string): T; + + /** + * Asserts that the value is compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. If the value is not compatible, and strictProcessing is on, an exception is thrown. All functions that have been declared using WinJS.Class.define, WinJS.Class.derive, WinJS.UI.Pages.define, or WinJS.Binding.converter are automatically marked as supported for declarative processing. Any other function that you use from a declarative context (that is, a context in which an HTML element has a data-win-control or data-win-options attribute) must be marked manually by calling this function. When you mark a function as supported for declarative processing, you are guaranteeing that the code in the function is secure from injection of third-party content. + * @param value The value to be tested for compatibility with declarative processing. If the value is a function it must be marked with a property supportedForProcessing with a value of true when strictProcessing is on. For more information, see WinJS.Utilities.markSupportedForProcessing. + * @returns The input value. + **/ + function requireSupportedForProcessing(value: T): T; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTML(element: HTMLElement, text: string): void; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTML(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Configures a logger that writes messages containing the specified tags to the JavaScript console. + * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. + **/ + function startLog(options?: ILogOptions): void; + + /** + * Removes the WinJS logger that had previously been set up. + **/ + function stopLog(): void; + + /** + * Toggles (adds or removes) the specified class on the specified element. If the class is present, it is removed; if it is absent, it is added. + * @param e The element on which to toggle the class. + * @param name The name of the class to toggle. + * @returns The element. + **/ + function toggleClass(e: T, name: string): T; + + //#endregion Functions + + //#region Properties + + /** + * Gets whether the current script context has access to WinRT APIs. + **/ + var hasWinRT: boolean; + + //#endregion Properties + + //#region Interfaces + + interface ILogOptions { + type: string; + action?: (message: string, tags: string, type: string) => void; + excludeTags: string; + tags: string; + } + + interface IPosition { + left: number; + top: number; + width: number; + height: number; + } + + //#endregion Interfaces + +} diff --git a/winjs/winjs-2.0.d.ts b/winjs/winjs-2.0.d.ts new file mode 100644 index 0000000000..205b418892 --- /dev/null +++ b/winjs/winjs-2.0.d.ts @@ -0,0 +1,8554 @@ +// Type definitions for WinJS +// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* ***************************************************************************** +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. +***************************************************************************** */ + +/** + * Defines an Element object. +**/ +interface Element { + winControl: any; // TODO: This should be control? +} + +/** + * Utility class for easy access to operations on application folders +**/ +interface IOHelper { + /** + * Determines whether the specified file exists in the folder. + * @param filename The name of the file. + * @returns A promise that completes with a value of either true (if the file exists) or false. + **/ + exists(filename: string): WinJS.Promise; + + /** + * Reads the specified file. If the file doesn't exist, the specified default value is returned. + * @param fileName The file to read from. + * @param def The default value to be returned if the file failed to open. + * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. + **/ + readText(fileName: string, def?: string): WinJS.Promise; + + /** + * Deletes a file from the folder. + * @param fileName The file to be deleted. + * @returns A promise that is fulfilled when the file has been deleted. + **/ + remove(fileName: string): WinJS.Promise; + + /** + * Writes the specified text to the specified file. + * @param fileName The name of the file. + * @param text The content to be written to the file. + * @returns A promise that completes with a value that is the number of characters written. + **/ + writeText(fileName: string, text: string): WinJS.Promise; +} + +/** + * Provides application-level functionality, for example activation, storage, and application events. +**/ +declare module WinJS.Application { + //#region Objects + + /** + * The local storage of the application. + **/ + var local: IOHelper; + + /** + * The roaming storage of the application. + **/ + var roaming: IOHelper; + + /** + * The temp storage of the application. + **/ + var temp: IOHelper; + + /** + * An object used for storing app information that can be used to restore the app's state after it has been suspended and then resumed. Data that can usefully be contained in this object includes the current navigation page or any information the user has added to the input controls on the page. You should not add information about customization (for example colors) or user-defined lists of content. + **/ + var sessionState: any; + + //#endregion Objects + + //#region Methods + + /** + * Informs the application object that asynchronous work is being performed, and that this event handler should not be considered complete until the promise completes. This function can be set inside the handlers for all WinJS.Application events: onactivated oncheckpoint onerror onloaded onready onsettings onunload. + * @param promise The promise that should complete before processing is complete. + **/ + function setPromise(promise: Promise): void; + + //#endregion Methods + + //#region Functions + + /** + * Adds an event listener for application-level events: activated, checkpoint, error, loaded, ready, settings, and unload. + * @param type The type (name) of the event. You can use any of the following:"activated", "checkpoint", "error", "loaded", "ready", "settings", and" unload". + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + function addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Queues a checkpoint event. + **/ + function checkpoint(): void; + + /** + * Queues an event to be processed by the WinJS.Application event queue. + * @param eventRecord The event object is expected to have a type property that is used as the event name when dispatching on the WinJS.Application event queue. The entire object is provided to event listeners in the detail property of the event. + **/ + function queueEvent(eventRecord: any): void; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: any): void; + + /** + * Starts dispatching application events (the activated, checkpoint, error, loaded, ready, settings, and unload events). + **/ + function start(): void; + + /** + * Stops application event processing and resets WinJS.Application to its initial state. All WinJS.Application event listeners (for the activated, checkpoint, error, loaded, ready, settings, and unload events) are removed. + **/ + function stop(): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs when WinRT activation has occurred. The name of this event is "activated" (and also "mainwindowactivated"). This event occurs after the loaded event and before the ready event. + * @param eventInfo An object that contains information about the event. For more information about event arguments, see the WinRT event argument classes: WebUICachedFileUpdaterActivatedEventArgs, WebUICameraSettingsActivatedEventArgs, WebUIContactPickerActivatedEventArgs, WebUIDeviceActivatedEventArgs, WebUIFileActivatedEventArgs, WebUIFileOpenPickerActivatedEventArgs, WebUIFileSavePickerActivatedEventArgs, WebUILaunchActivatedEventArgs, WebUIPrintTaskSettingsActivatedEventArgs, WebUIProtocolActivatedEventArgs, WebUISearchActivatedEventArgs, WebUIShareTargetActivatedEventArgs. + **/ + function onactivated(eventInfo: CustomEvent): void; + + /** + * Occurs when receiving PLM notification or when the checkpoint function is called. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function oncheckpoint(eventInfo: CustomEvent): void; + + /** + * Occurs when an unhandled error has been raised. + * @param eventInfo An object that contains information about the event. + **/ + function onerror(eventInfo: CustomEvent): void; + + /** + * Occurs after the DOMContentLoaded event, which fires after the page has been parsed but before all the resources are loaded. This event occurs before the activated event and the ready event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function onloaded(eventInfo: CustomEvent): void; + + /** + * Occurs when the application is ready. This event occurs after the loaded event and the activated event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onready(eventInfo: CustomEvent): void; + + /** + * Occurs when the settings charm is invoked. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: type, applicationcommands. + **/ + function onsettings(eventInfo: CustomEvent): void; + + /** + * Occurs when the application is about to be unloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onunload(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides functionality for data and template binding. +**/ +declare module WinJS.Binding { + //#region Properties + + /** + * Determines whether or not binding should automatically set the ID of an element. This property should be set to true in apps that use WinJS (WinJS) binding. + **/ + var optimizeBindingReferences: boolean; + + //#endregion Properties + + //#region Objects + + /** + * Allows you to add bindable properties dynamically. + **/ + var dynamicObservableMixin: { + //#region Methods + + /** + * Adds a property with change notification to this object, including a ECMAScript5 property definition. + * @param name The name of the property to add. + * @param value This object is returned. + **/ + addProperty(name: string, value: any): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Do not instantiate. A list returned by the createFiltered method. + **/ + class FilteredListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. A list of groups. + **/ + class GroupsListProjection extends ListBase { + //#region Methods + + /** + * Gets a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. Sorts the underlying list by group key and within a group respects the position of the item in the underlying list. Returned by createGrouped. + **/ + class GroupedSortedListProjection extends SortedListProjection { + //#region Properties + + /** + * Gets a List, which is a projection of the groups that were identified in this list. + **/ + groups: GroupsListProjection; + + //#endregion Properties + + } + + /** + * Represents a list of objects that can be accessed by index or by a string key. Provides methods to search, sort, filter, and manipulate the data. + **/ + class List extends ListBaseWithMutators { + //#region Constructors + + /** + * Creates a List object. + * @constructor + * @param list The array containing the elements to initalize the list. + * @param options You can set two Boolean options: binding and proxy. If options.binding is true, the list contains the result of calling as on the element values. If options.proxy is true, the list specified as the first parameter is used as the storage for the List. This option should be used with care, because uncoordinated edits to the data storage may result in errors. + **/ + constructor(list?: T[], options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Gets a key/data pair for the specified list index. + * @param index The index of value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the list item key specified. + * @param key The key of the value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Gets the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Moves the value at index to the specified position. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Returns a list with the elements reversed. This method reverses the elements of a list object in place. It does not create a new list object during execution. + **/ + reverse(): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + /** + * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. + * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + **/ + sort(sortFunction: (left: T, right: T) => number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list, which is an integer value one higher than the highest element defined in the list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Represents a base class for lists. + **/ + class ListBase { + //#region Events + + /** + * An item in the list has changed its value. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, newItem, newValue, oldItem, oldValue. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * A new item has been inserted into the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * An item has been changed locations in the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * An item has been mutated. This event occurs as a result of calling the notifyMutated method. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmutated(eventInfo: CustomEvent): void; + + /** + * An item has been removed from the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * The list has been refreshed. Any references to items in the list may be incorrect. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. + **/ + onreload(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Returns a new list consisting of a combination of two arrays. + * @param item Additional items to add to the end of the list. + * @returns An array containing the concatenation of the list and any other supplied items. + **/ + concat(...item: T[]): T[]; + + /** + * Creates a live filtered projection over this list. As the list changes, the filtered projection reacts to those changes and may also change. + * @param predicate A function that accepts a single argument. The createFiltered function calls the callback with each element in the list. If the function returns true, that element will be included in the filtered list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A filtered projection over the list. + **/ + createFiltered(predicate: (x: T) => boolean): FilteredListProjection; + + /** + * Creates a live grouped projection over this list. As the list changes, the grouped projection reacts to those changes and may also change. The grouped projection sorts all the elements of the list to be in group-contiguous order. The grouped projection also contains a .groups property, which is a List representing the groups that were found in the list. + * @param groupKey A function that accepts a single argument. The function is called with each element in the list, the function should return a string representing the group containing the element. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param groupData A function that accepts a single argument. The function is called once, on one element per group. It should return the value that should be set as the data of the .groups list element for this group. The data value usually serves as summary or header information for the group. + * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). + * @returns A grouped projection over the list. + **/ + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + + /** + * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. + * @param sorter A function that accepts two arguments. The function is called with elements in the list. It must return one of the following numeric values: negative if the first argument is less than the second, zero if the two arguments are equivalent, positive if the first argument is greater than the second. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A sorted projection over the list. + **/ + createSorted(sorter: (left: T, right: T) => number): SortedListProjection; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Checks whether the specified callback function returns true for all elements in a list. + * @param callback A function that accepts up to three arguments. This function is called for each element in the list until it returns false or the end of the list is reached. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if the callback returns true for all elements in the list. + **/ + every(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Returns the elements of a list that meet the condition specified in a callback function. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the elements that meet the condition specified in the callback function. + **/ + filter(callback: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; + + /** + * Calls the specified callback function for each element in a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. The arguments are as follows: value, index, array. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + **/ + forEach(callback: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + /** + * Gets the value at the specified index. + * @param index The index of the value to get. + * @returns The value at the specified index. + **/ + getAt(index: number): T; + + /** + * Gets the index of the first occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + * @returns The index of the first occurrence of a value in a list or -1 if not found. + **/ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns a string consisting of all the elements of a list separated by the specified separator string. + * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. + * @returns The elements of a list separated by the specified separator string. + **/ + join(separator: string): string; + + /** + * Gets the index of the last occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. + * @returns The index of the last occurrence of a value in a list, or -1 if not found. + **/ + lastIndexOf(searchElement: T, fromIndex: number): number; + + /** + * Calls the specified callback function on each element of a list, and returns an array that contains the results. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. + * @param thisArg n object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the result of calling the callback function on each element in the list. + **/ + map(callback: (value: T, index: number, array: T[]) => G, thisArg?: any): G[]; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Forces the list to send a reload notification to any listeners. + **/ + notifyReload(): void; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initiallValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the function provides this value as an argument instead of a list value. + * @returns The return value from the last call to the callback function. + **/ + reduce(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initiallValue?: T): T; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list, starting with the last member of the list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initialValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the callback function provides this value as an argument instead of a list value. + * @returns The return value from the last call to callback function. + **/ + reduceRight(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initialValue?: T): T; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Extracts a section of a list and returns a new list. + * @param begin The index that specifies the beginning of the section. + * @param end The index that specifies the end of the section. + * @returns Returns a section of list. + **/ + slice(begin: number, end: number): T[]; + + /** + * Checks whether the specified callback function returns true for any element of a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list until it returns true, or until the end of the list. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if callback returns true for any element in the list. + **/ + some(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + //#region Properties + + /** + * Gets the IListDataSource for the list. The only purpose of this property is to adapt a List to the data model that is used by ListView and FlipView. + **/ + dataSource: WinJS.UI.IListDataSource; + + /** + * Indicates that the object is compatibile with declarative processing. + **/ + static supportedForProcessing: boolean; + + //#endregion Properties + } + + /** + * Represents a base class for normal list modifying operations. + **/ + class ListBaseWithMutators extends ListBase { + //#region Methods + + /** + * Removes the last element from a list and returns it. + * @returns The last element from the list. + **/ + pop(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the end of the list. + * @returns The new length of the list. + **/ + push(value: T): number; + + /** + * Removes the first element from a list and returns it. + * @returns The first element from the list. + **/ + shift(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the start of the list. + * @returns The new length of the list. + **/ + unshift(value: T): number; + + //#endregion Methods + } + + /** + * Represents a base class for list projections. + **/ + class ListProjection extends ListBaseWithMutators { + //#region Methods + + /** + * Disconnects a WinJS.Binding.List projection from its underlying WinJS.Binding.List. It's only important to call this method when the WinJS.Binding.List projection and the WinJS.Binding.List have different lifetimes. (Call this method on the WinJS.Binding.List projection, not the underlying WinJS.Binding.List.) + **/ + dispose(): void; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Moves the value at index to position newIndex. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + } + + /** + * Provides a standard implementation of the bindable contract, as well as a basic storage mechanism that participates in change notification and an asynchronous notification implementation. + **/ + var mixin: { + //#region Methods + + /** + * Adds a property to the object. The property includes change notification and an ECMAScript 5 property definition . + * @param name The name of the property to add. + * @param value The value of the property. + * @returns This object is returned. + **/ + addProperty(name: string, value: any): any; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Provides functions that can make an object observable. + **/ + var observableMixin: { + //#region Methods + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + }; + + /** + * Do not instantiate. Returned by the createSorted method. + **/ + class SortedListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value to be replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list. Returns an integer value one higher than the highest element defined in a list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Provides a reusable declarative binding element. + **/ + class Template { + //#region Constructors + + /** + * Creates a template that provides a reusable declarative binding element. + * @constructor + * @param element The DOM element to convert to a template. + * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. + **/ + constructor(element: HTMLElement, options?: string); + + //#endregion Constructors + + //#region Methods + + render: { + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + (dataContext: any, container?: HTMLElement): Promise; + + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + value(href: string, dataContext: any, container?: HTMLElement): Promise; + }; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default binding initializer for the template. + **/ + bindingInitializer: any; + + /** + * Gets or sets a value that specifies whether a debug break is inserted into the first rendering of each template. This property only has an effect when the app is in debug mode. + **/ + debugBreakOnRender: boolean; + + /** + * This property is deprecated and might not be available in future versions of the WinJS. Gets or sets a value that specifies whether optimized template processing has been disabled. + **/ + disableOptimizedProcessing: boolean; + + /** + * Gets the DOM element that is used as the template. + **/ + element: HTMLElement; + + /** + * Gets a value that specifies whether templates should be instantiated without the creation of an additional child element. + **/ + extractChild: boolean; + + /** + * Determines whether the Template contains declarative controls that must be processed separately. This property is always true. The controls that belong to a Template object's children are instantiated when a Template instance is rendered. + **/ + isDeclarativeControlContainer: boolean; + + //#endregion Properties + + } + + //#endregion Objects + + //#region Functions + + /** + * Adds a CSS class from the specified path of the source object to a destination object. + * @param source The source object that has the class to copy. + * @param sourceProperties The path on the source object to the source class. + * @param dest The destination object. + **/ + function addClassOneTime(source: any, sourceProperties: any[], dest: HTMLElement): void; + + /** + * Returns an observable object. This may be an observable proxy for the specified object, an existing proxy, or the specified object itself if it directly supports observation. + * @param data The object to observe. + * @returns The observable object. + **/ + function as(data: U): U; + + /** + * Binds to one or more properties on the observable object or or on child values of that object. + * @param observable The object to bind to. + * @param bindingDescriptor An object literal containing the binding declarations. Binding declarations take the form: { propertyName: (function | bindingDeclaration), ... }. + * @returns An object that contains at least a "cancel" field, which is a function that removes all bindings associated with this bind request. + **/ + function bind(observable: any, bindingDescriptor: any): any; + + /** + * Creates a default binding initializer for binding between a source property and a destination property with the specified converter function that is executed on the value of the source property. + * @param convert The conversion function that takes the source property and produces a value that is set to the destination property. This function must be accessible from the global namespace. + * @returns The binding initializer. + **/ + function converter(convert: Function): Function; + + /** + * Creates a one-way binding between the source object and the destination object. Warning Do not attempt to bind data to the ID of an HTML element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function defaultBind(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Creates a new constructor function that supports observability with the specified set of properties. + * @param data The object to use as the pattern for defining the set of properties. + * @returns A constructor function with 1 optional argument that is the initial state of the properties. + **/ + function define(data: any): Function; + + /** + * Wraps the specified object so that all its properties are instrumented for binding. This is meant to be used in conjunction with the binding mixin. + * @param shape The specification for the bindable object. + * @returns An object with a set of properties all of which are wired for binding. + **/ + function expandProperties(shape: any): any; + + /** + * Marks a custom initializer function as being compatible with declarative data binding. + * @param customInitializer The custom initializer to be marked as compatible with declarative data binding. + * @returns The input customInitializer. + **/ + function initializer(customInitializer: Function): Function; + + /** + * Sets the destination property to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function oneTime(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Binds the values of an object to the values of a DOM element that has the data-win-bind attribute. If multiple DOM elements are to be bound, you must set the attribute on all of them. See the example below for details. + * @param rootElement Optional. The element at which to start traversing to find elements to bind to. If this parameter is omitted, the entire document is searched. + * @param dataContext The object that contains the values to which the DOM element should be bound. + * @param skipRoot If true, specifies that only the children of rootElement should be bound, otherwise rootElement should be bound as well. + * @param bindingCache The cached binding data. + * @param defaultInitializer The binding initializer to use in the case that one is not specified in a binding expression. If not provided, the behavior is the same as Binding.defaultBind. + * @returns A Promise that completes when every item that contains the data-win-bind attribute has been processed and the update has started. + **/ + function processAll(rootElement?: Element, dataContext?: any, skipRoot?: boolean, bindingCache?: any, defaultInitializer?: Function): Promise; + + /** + * Creates a one-way binding between the source object and an attribute on the destination element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + * @returns An object with a cancel() method that is used to coalesce bindings. + **/ + function setAttribute(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): any; + + /** + * Sets an attribute on the destination element to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + **/ + function setAttributeOneTime(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): void; + + /** + * Returns the original (non-observable) object is returned if the specified object is an observable proxy, + * @param data The object for which to retrieve the original value. + * @returns If the specified object is an observable proxy, the original object is returned, otherwise the same object is returned. + **/ + function unwrap(data: any): any; + + //#endregion Functions + + //#region Interfaces + + interface IKeyDataPair { + key: string; + data: T; + } + + //#endregion Interfaces + +} +/** + * Provides helper functions for defining Classes. +**/ +declare module WinJS.Class { + //#region Functions + + /** + * Defines a class using the given constructor and the specified instance members. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods made available on the type. + * @param staticMembers The set of static fields, properties, and methods made available on the type. + * @returns The newly-defined type. + **/ + function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + + /** + * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. + * @param baseClass The type to inherit from. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods to be made available on the type. + * @param staticMembers The set of static fields, properties, and methods to be made available on the type. + * @returns The newly-defined type. + **/ + function derive(baseClass: any, constructor: Function, instanceMembers?: any, staticMembers?: any): any; + + /** + * Defines a class using the given constructor and the union of the set of instance members specified by all the mixin objects. The mixin parameter list is of variable length. For more information, see Adding functionality with WinJS mixins. + * @param constructor A constructor function that will be used to instantiate this class. + * @param mixin An object declaring the set of instance members. The mixin parameter list is of variable length. + * @returns The newly defined class. + **/ + function mix(constructor: Function, ...mixin: any[]): any; + + //#endregion Functions + +} +/** + * The WinJS namespace provides special Windows Library for JavaScript functionality, including Promise and xhr. +**/ +declare module WinJS { + //#region Properties + + /** + * Can be set to show the results of a validation process. + **/ + var validation: boolean; + + //#endregion Properties + + //#region Objects + + /** + * An error object. + **/ + class ErrorFromName { + //#region Constructors + + /** + * Creates an Error object with the specified name and message properties. + * @constructor + * @param name The name of this error. The name is meant to be consumed programmatically and should not be localized. + * @param message The message for this error. The message is meant to be consumed by humans and should be localized. + **/ + constructor(name: string, message?: string); + + //#endregion Constructors + + } + + /** + * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + **/ + class Promise { + //#region Constructors + + /** + * A promise provides a mechanism to schedule work to be done on a value that has not yet been computed. It is a convenient abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + * @constructor + * @param init The function that is called during construction of the Promise that contains the implementation of the operation that the Promise will represent. This can be synchronous or asynchronous, depending on the nature of the operation. Note that placing code within this function does not automatically run it asynchronously; that must be done explicitly with other asynchronous APIs such as setImmediate, setTimeout, requestAnimationFrame, and the Windows Runtime asynchronous APIs. The init function is given three arguments: completeDispatch, errorDispatch, progressDispatch. This parameter is optional. + * @param onCancel The function to call if a consumer of this promise wants to cancel its undone work. Promises are not required to support cancellation. + **/ + constructor(init?: (completeDispatch: any, errorDispatch: any, progressDispatch: any) => void, onCancel?: Function); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when there is an error in processing a promise. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener for the promise. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Returns a promise that is fulfilled when one of the input promises has been fulfilled. + * @param value An array that contains Promise objects or objects whose property values include Promise objects. + * @returns A promise that on fulfillment yields the value of the input (complete or error). + **/ + static any(value: Promise[]): Promise; + + /** + * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. + * @param value The value to be treated as a Promise. + * @returns The promise. + **/ + static as(value: U): Promise; + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Raises an event of the specified type and properties. + * @param type The type (name) of the event. + * @param details The set of additional properties to be attached to the event object. + * @returns true if preventDefault was called on the event; otherwise, false. + **/ + dispatchEvent(type: string, details: any): boolean; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + + /** + * Determines whether a value fulfills the promise contract. + * @param value A value that may be a promise. + * @returns true if the object conforms to the promise contract (has a then function), otherwise false. + **/ + static is(value: any): boolean; + + /** + * Creates a Promise that is fulfilled when all the values are fulfilled. + * @param values An object whose members contain values, some of which may be promises. + * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. + **/ + static join(values: any): Promise; + + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param capture Specifies whether or not to initiate capture. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + + /** + * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. + * @param values A set of values (which could be either an array or an object) of which some or all are promises.. + * @param complete The function to be called if the promise is fulfilled with a value. This function takes a single argument, which is the fulfilled value of the promise. + * @param error The function to be called if the promise is fulfilled with an error. This function takes a single argument, which is the error value of the promise. + * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. + * @returns A Promise that is the result of calling join on the values parameter. + **/ + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + + /** + * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. + * @param timeout The timeout period in milliseconds. If this value is zero or not specified, msSetImmediate is called, otherwise setTimeout is called. + * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. + * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. + **/ + static timeout(timeout: number, promise?: Promise): Promise; + + /** + * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. + * @param value Some non-promise value to be wrapped in a promise. + * @returns A promise that is successfully fulfilled with the specified value. + **/ + static wrap(value: U): Promise; + + /** + * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. + * @param error A non-promise error value to be wrapped in a promise. + * @returns A promise that is in an error state with the specified value. + **/ + static wrapError(error: U): Promise; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * You can provide an implementation of this method yourself, or use WinJS.Utilities.startLog to create one that logs to the JavaScript console. + * @param message The message to log. + * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). + * @param type The type of message (error, warning, info, etc.). + **/ + function log(message: string, tags: string, type: string): void; + + /** + * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. + **/ + function strictProcessing(): void; + + /** + * Wraps calls to XMLHttpRequest in a promise. + * @param options The options that are applied to the XMLHttpRequest object, as follows: type, url, user, password, responseType, headers, data, customRequestInitializer. + * @returns A promise that returns the XMLHttpRequest object when it completes. + **/ + function xhr(options: IXHROptions): Promise; + + //#endregion Functions + + //#region Interfaces + + interface IXHROptions { + type?: string; + url: string; + user?: string; + password?: string; + headers?: any; + data: any; + responseType?: string; + } + + //#endregion Interfaces +} +/** + * Provides helper functions for defining namespaces. For more information, see Organizing your code with WinJS.Namespace. +**/ +declare module WinJS.Namespace { + //#region Functions + + /** + * Defines a new namespace with the specified name. For more information, see Organizing your code with WinJS.Namespace. + * @param name The name of the namespace. This could be a dot-separated name for nested namespaces. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function define(name?: string, members?: any): any; + + /** + * Defines a new namespace with the specified name under the specified parent namespace. For more information, see Organizing your code with WinJS.Namespace. + * @param parentNamespace The parent namespace. + * @param name The name of the new namespace. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function defineWithParent(parentNamespace?: any, name?: string, members?: any): any; + + //#endregion Functions + +} +/** + * Provides functionality for dealing with basic navigation, including the navigation stack. +**/ +declare module WinJS.Navigation { + //#region Properties + + /** + * Determines whether it is possible to navigate backwards. + **/ + var canGoBack: boolean; + + /** + * Determines if it is possible to navigate forwards. + **/ + var canGoForward: boolean; + + /** + * Gets or sets the navigation history. + **/ + var history: any; + + /** + * Gets or sets the current location. + **/ + var location: string; + + /** + * Gets or sets a user-defined object that represents the state associated with the current location. + **/ + var state: any; + + //#endregion Properties + + //#region Functions + + /** + * Adds an event listener to the control. + * @param eventType The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + function addEventListener(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Navigates backwards. + * @param distance The number of entries to go back into the history. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function back(distance?: number): Promise; + + /** + * Navigates forwards. + * @param distance The number of entries to go forward. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function forward(distance?: number): Promise; + + /** + * Navigates to a location. + * @param location The location to navigate to. Generally the location is a string containing the URL, but it may be anything. + * @param initialState A user-defined object that represents the navigation state that may be accessed through state. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful (true if successful, otherwise false). + **/ + function navigate(location: any, initialState?: any): Promise; + + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(eventType: string, listener: Function, useCapture?: boolean): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs before navigation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onbeforenavigate(eventInfo: CustomEvent): void; + + /** + * Occurs after navigation has taken place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigated(eventInfo: CustomEvent): void; + + /** + * Occurs when navigation is taking place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigating(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides functions for accessing resources and localizing content. +**/ +declare module WinJS.Resources { + //#region Functions + + /** + * Registers an event handler for the specified event. Use this method to register for events that are related to resources, such as when the app's language, scale, or contrast changes. + * @param type The name of the event to handle. + * @param listener The listener (event handler function) to associate with the event. + * @param useCapture Set to true to register the listener for the capturing phase; otherwise, set to false to register the listener for the bubbling phase. + **/ + function addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The name of the event to raise. + * @param details The set of additional properties to attach to the event object. + **/ + function dispatchEvent(type: string, details: any): void; + + /** + * Retrieves the resource string that has the specified resource identifier. + * @param resourceId The resource ID of the string to retrieve. + * @returns An object that can contain these properties: value, empty, lang. + **/ + function getString(resourceId: string): { value: string; empty?: boolean; lang?: string; }; + + /** + * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. + * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. + **/ + function processAll(rootElement?: HTMLElement): void; + + /** + * Removes an event listener that the addEventListener method registered. + * @param type The name of the event that the event listener is registered for. + * @param listener The listener (event handler function) to remove. + * @param useCapture Set to true to remove the capturing phase listener; set to false to remove the bubbling phase listener. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs when the user changes the system's language or contrast, or the scale of the display, or when the user changes any of the items in the current context's qualifier values list. For more info about the current context's qualifier values list, see the Remarks section. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.qualifier, detail.changed. + **/ + function oncontextchanged(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides access to the Windows animations. These functions provide developers with the ability to use animations in their custom controls that are consistent with animations used by Windows controls. +**/ +declare module WinJS.UI.Animation { + //#region Functions + + /** + * Creates an object that performs an animation that adds an item or items to a list. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToListAnimation(added: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that adds an item or items to a list of search results. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToSearchListAnimation(added: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that collapses a list. + * @param hidden Element or elements hidden as a result of the collapse. + * @param affected Element or elements affected by the hidden items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createCollapseAnimation(hidden: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that removes an item or items from a list. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that removes an item or items from a list of search results. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromSearchListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that expands a list. + * @param revealed Element or elements revealed by the expansion. + * @param affected Element or elements affected by the newly revealed items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createExpandAnimation(revealed: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs a peek animation. + * @param element Element or elements involved in the peek. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createPeekAnimation(element: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that moves an item or items. + * @param element Element or elements involved in the reposition. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise object that completes when the animation is finished. + **/ + function createRepositionAnimation(element: any): IAnimationMethodResponse; + + /** + * Performs an animation that fades an item or items in, fading out existing items that occupy the same space. + * @param incoming Element or elements being faded in. + * @param outgoing Element or elements being replaced. + * @returns An object that completes when the animation has finished. + **/ + function crossFade(incoming: any, outgoing: any): Promise; + + /** + * Performs an animation when a dragged object is moved such that dropping it in that position would move other items. The potentially affected items are animated out of the way to show where the object would be dropped. + * @param target Element or elements that the dragged object would cause to be moved if it were dropped. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenEnter(target: any, offset: any): Promise; + + /** + * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. + * @param target Element or elements that the dragged object would no longer cause to be displaced, due to its moving away. This should be the same element or element collection passed as the target parameter in the dragBetweenEnter animation. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenLeave(target: any): Promise; + + /** + * Performs an animation when the user finishes dragging an object. + * @param dragSource Element or elements that were dragged. + * @param offset Initial offset from the drop point. The dropped object begins at the offset and animates to its final position at the drop point. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + + /** + * Performs an animation when the user begins to drag an object. + * @param dragSource Element or elements being dragged. + * @param affected Element or elements whose position is affected by the movement of the dragged object. Typically, this is all other items in a reorderable list. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceStart(dragSource: any, affected?: any): Promise; + + /** + * Performs an animation that displays one or more elements on a page. + * @param incoming Element or elements that compose the incoming content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function enterContent(incoming: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. + * @param element Element or an array of elements that represent the content. If element refers to an array of elements, the elements enter in array order. + * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function enterPage(element: any, offset: any): Promise; + + /** + * Performs an animation that hides one or more elements on a page. + * @param outgoing Element or elements that compose the outgoing content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitContent(outgoing: any, offset: any): Promise; + + /** + * Performs an animation that dismisses the current page when transitioning between pages in an app. + * @param outgoing Element or elements that compose the outgoing page. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitPage(outgoing: any, offset: any): Promise; + + /** + * Performs an animation that fades an item or set of items into view. + * @param shown Element or elements being faded in. + * @returns An object that completes when the animation has finished. Use this object when subsequent actions need this animation to finish before they take place. + **/ + function fadeIn(shown: any): Promise; + + /** + * Performs an animation that fades an item or set of items out of view. + * @param hidden Element or elements being faded out. + * @returns An object that completes when the animation is finished. + **/ + function fadeOut(hidden: any): Promise; + + /** + * Performs an animation that hides edge-based user interface (UI). + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function hideEdgeUI(element: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that hides a panel. + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function hidePanel(element: any, offset: any): Promise; + + /** + * Performs an animation that removes pop-up user interface (UI). + * @param element Element or elements that are being hidden. + * @returns An object that completes when the animation is finished. + **/ + function hidePopup(element: any): Promise; + + /** + * Performs an animation when a pointer is pressed on an object. + * @param element Element or elements on which the pointer is pressed. + * @returns An object that completes when the animation is finished. + **/ + function pointerDown(element: any): Promise; + + /** + * Performs an animation when a pointer is released. + * @param element Element or elements that the pointer was pressed on. + * @returns An object that completes when the animation is finished. + **/ + function pointerUp(element: any): Promise; + + /** + * Performs an animation that slides a narrow, edge-based user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function showEdgeUI(element: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that slides a large panel user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPanel(element: any, offset: any): Promise; + + /** + * Performs an animation that displays a pop-up user interface (UI). + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPopup(element: any, offset: any): Promise; + + /** + * Performs a deselection animation in response to a swipe interaction. + * @param deselected Element or elements that become unselected. + * @param selection Element or elements that represent the selection, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeDeselect(deselected: any, selection: any): Promise; + + /** + * Performs an animation that reveals an item or items in response to a swipe interaction. + * @param target Element or elements being revealed. + * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function swipeReveal(target: any, offset: any): Promise; + + /** + * Performs a selection animation in response to a swipe interaction. + * @param selected Element or elements being selected. + * @param selection Element or elements that show that something is selected, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeSelect(selected: any, selection: any): Promise; + + /** + * Performs an animation that updates a badge. + * @param incoming Element or elements that comprise the new badge. + * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function updateBadge(incoming: any, offset: any): Promise; + + //#endregion Functions + + //#region Interfaces + + interface IAnimationMethodResponse { + execute(): Promise; + } + + //#endregion Interfaces + +} +/** + * Provides controls and objects that manipulate data. +**/ +declare module WinJS.UI { + //#region Enumerations + + /** + * Specifies an icon that appears in an AppBarCommand object. + **/ + enum AppBarIcon { + previous, + next, + play, + pause, + edit, + save, + clear, + delete, + remove, + add, + cancel, + accept, + more, + redo, + undo, + home, + up, + forward, + right, + back, + left, + favorite, + camera, + settings, + video, + sync, + download, + mail, + find, + help, + upload, + emoji, + twopage, + leavechat, + mailforward, + clock, + send, + crop, + rotatecamera, + people, + closepane, + openpane, + world, + flag, + previewlink, + globe, + trim, + attachcamera, + zoomin, + bookmarks, + document, + protecteddocument, + page, + bullets, + comment, + mail2, + contactinfo, + hangup, + viewall, + mappin, + phone, + videochat, + switch, + contact, + rename, + pin, + musicinfo, + go, + keyboard, + dockleft, + dockright, + dockbottom, + remote, + refresh, + rotate, + shuffle, + list, + shop, + selectall, + orientation, + import, + importall, + browsephotos, + webcam, + pictures, + savelocal, + caption, + stop, + showresults, + volume, + repair, + message, + page2, + calendarday, + calendarweek, + calendar, + characters, + mailreplyall, + read, + link, + accounts, + showbcc, + hidebcc, + cut, + attach, + paste, + filter, + copy, + emoji2, + important, + mailreply, + slideshow, + sort, + manage, + allapps, + disconnectdrive, + mapdrive, + newwindow, + openwith, + contactpresence, + priority, + uploadskydrive, + gototoday, + font, + fontcolor, + contact2, + folder, + audio, + placeholder, + view, + setlockscreen, + settile, + cc, + stopslideshow, + permissions, + highlight, + disableupdates, + unfavorite, + unpin, + openlocal, + mute, + italic, + underline, + bold, + movetofolder, + likedislike, + dislike, + like, + alignright, + aligncenter, + alignleft, + zoom, + zoomout, + openfile, + otheruser, + admin, + street, + map, + clearselection, + fontdecrease, + fontincrease, + fontsize, + cellphone, + reshare, + tag, + repeatone, + repeatall, + outlinestar, + solidstar, + calculator, + directions, + target, + library, + phonebook, + memo, + microphone, + postupdate, + backtowindow, + fullscreen, + newfolder, + calendarreply, + unsyncfolder, + reporthacked, + syncfolder, + blockcontact, + switchapps, + addfriend, + touchpointer, + gotostart, + zerobars, + onebar, + twobars, + threebars, + fourbars, + scan, + preview + } + + /** + * Indicates whether the IListDataAdapter was able to provide a count. + **/ + enum CountResult { + /** + * Indicates no count is available. + **/ + unknown + } + + /** + * Indicates that the IListDataAdapter was unable to provide a count. + **/ + enum CountError { + /** + * An attempt to count items timed out. + **/ + noResponse + } + + /** + * Describes the status of an IListDataSource. + **/ + enum DataSourceStatus { + /** + * The IListDataSource is ready. + **/ + ready, + /** + * The IListDataSource is still loading. + **/ + waiting, + /** + * The IListDataSource failed to load. + **/ + failure + } + + /** + * Specifies the type of error that occurred during an edit operation on a IListDataSource or an IListDataAdapter. + **/ + enum EditError { + /** + * The edit operation timed out. + **/ + noResponse, + /** + * The data source cannot be written to. + **/ + notPermitted, + /** + * The item has changed. + **/ + noLongerMeaningful + } + + /** + * Specifies the type of error encountered when retrieving items from an IListDataAdapter. + **/ + enum FetchError { + /** + * The fetch operation timed out. + **/ + noResponse, + /** + * The specified item could not be located. + **/ + doesNotExist + } + + /** + * Specifies how group headers in a ListView respond to the tap interaction. + **/ + enum GroupHeaderTapBehavior { + /** + * The group is invoked. + **/ + invoke, + /** + * Nothing happens. + **/ + none + } + + /** + * Specifies the position of group headers relative to their items in a ListView. + **/ + enum HeaderPosition { + /** + * Group headers appear to the left of items. + **/ + left, + /** + * Group headers appear above items. + **/ + top + } + + /** + * Specifies that type of animation for which a contentanimating event was raised. + **/ + enum ListViewAnimationType { + /** + * The animation plays when the ListView is first displayed. + **/ + entrance, + /** + * The animation plays when the ListView is changing its content. + **/ + contentTransition + } + + /** + * Describes the type of object in a ListView. + **/ + enum ObjectType { + /** + * The object is a group header in the list. + **/ + groupHeader, + /** + * The object is an item in the list. + **/ + item + } + + /** + * Specifies the orientation of a control. + **/ + enum Orientation { + /** + * A horizontal layout. + **/ + horizontal, + /** + * A vertical layout. + **/ + vertical + } + + /** + * Specifies the selection mode of a ListView. + **/ + enum SelectionMode { + /** + * Items cannot be selected. + **/ + none, + /** + * A single item may be selected. + **/ + single, + /** + * Multiple items may be selected. Clicking additional items adds them to the selection. + **/ + multi + } + + /** + * Specifies whether elements are selected when the user performs a swipe interaction. + **/ + enum SwipeBehavior { + /** + * The swipe interaction selects the elements touched by the swipe. + **/ + select, + /** + * The swipe interaction does not change which elements are selected. + **/ + none + } + + /** + * Specifies how items in a ListView respond to the tap interaction. + **/ + enum TapBehavior { + /** + * The item is selected and invoked. + **/ + directSelect, + /** + * The item is selected if was not already selected, and its deselected if it was already selected. + **/ + toggleSelect, + /** + * The item is invoked but not selected. + **/ + invokeOnly, + /** + * Nothing happens. + **/ + none + } + + //#endregion Enumerations + + //#region Interfaces + + /** + * Contains items that were requested from an IListDataAdapter and provides some information about those items. + **/ + interface IFetchResult { + //#region Properties + + /** + * Gets or sets the index of the requested item in the IListDataAdapter object's data source. + **/ + absoluteIndex: number; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the last items at the end of the IListDataAdapter object's data source. + **/ + atEnd: boolean; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the first items at the beginning of the IListDataAdapter object's data source. + **/ + atStart: boolean; + + /** + * Gets or sets the items returned by the fetch operation. + **/ + items: T[]; + + /** + * Gets or sets the location of the requested item within the items array. + **/ + offset: number; + + /** + * Gets or sets the number of items in the IListDataAdapter object's underlying data source. + **/ + totalCount: number; + + //#endregion Properties + + } + + /** + * Represents an item in a list. + **/ + interface IItem { + //#region Properties + + /** + * Gets or sets the item's data. + **/ + data: T; + + /** + * Gets the group key for the item. This property is only available for items that belong to a grouped data source. + **/ + groupKey: string; + + /** + * Gets the temporary ID of the item. + **/ + handle: string; + + /** + * Gets the item's index in the IListDataSource. + **/ + index: number; + + /** + * Gets or sets the key the identifies the item. + **/ + key: string; + + //#endregion Properties + + } + + /** + * Provides a mechanism for retrieving IItem objects asynchronously. + **/ + interface IItemPromise { + //#region Events + + /** + * Occurs when there is an error in processing. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; + + /** + * Stops change notification tracking for the IItem that fulfills this IItemPromise. + **/ + release(): void; + + /** + * Begins change notification tracking for the IItem that fulfills this IItemPromise. + **/ + retain(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the complete or error function. + **/ + then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the temporary ID of the IItem that fulfills this promise. + **/ + handle: string; + + /** + * Gets or sets the index of the IItem contained by this IItemPromise. + **/ + index: number; + + //#endregion Properties + + } + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. Represents a layout for the ListView. + **/ + interface ILayout { + //#region Methods + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param beginScrollPosition The first visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the first visible item at the specified point. + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param endScrollPosition The last visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the last visible item at the specified point. + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @returns A object that has these properties: animationPromise, newEndIndex. + **/ + endLayout(): any; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The index of the item. + * @returns A Promise that returns an object with these properties: left, top, contentWidth, contentHeight, totalWidth, totalHeight. + **/ + getItemPosition(itemIndex: number): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The data source index of the current item. + * @param element The element for the current item. + * @param keyPressed The key that was pressed. This function must check for the arrow keys (leftArrow, upArrow, rightArrow, downArrow), pageDown, and pageUp and determine which item the user navigated to. + * @returns A Promise that contains the index of the next item (This item becomes the current item). + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: WinJS.Utilities.Key): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @returns A Promise that returns an object that has these properties: beginScrollPosition, endScrollPosition. + **/ + getScrollBarRange(): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param x The x-coordinate to test. + * @param y The y-coordinate to test. + **/ + hitTest(x: number, y: number): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param elements The elements that represent the items that were added. + **/ + itemsAdded(elements: HTMLElement[]): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + itemsMoved(): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param elements The elements that represent the items that were removed. + **/ + itemsRemoved(elements: HTMLElement[]): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param groupIndex The index of the group in the group data source. + * @param element The element to render for the group header. + **/ + layoutHeader(groupIndex: number, element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The index of the item in the data source. + * @param element The element to render for the item. + **/ + layoutItem(itemIndex: number, element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element The element that represents a header in the data source. + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element An element that represents an item in the data source. + **/ + prepareItem(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element The element being released. + **/ + releaseItem(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + reset(): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param site The layout site for the layout. You can use this object to query the hosting ListView for info you might need to lay out items. + **/ + setSite(site: ILayoutSite): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param beginScrollPosition The starting pixel of the area to which the items are rendered. + * @param endScrollPosition The last pixel of the area to which the items are rendered. + * @param count The upper bound of the number of items to render. + * @returns A Promise that returns an object that has these properties: beginIndex, endIndex. + **/ + startLayout(beginScrollPosition: number, endScrollPosition: number, count: number): Promise; + + //#endregion Methods + + //#region Properties + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + horizontal: boolean; + + //#endregion Properties + + } + + /** + * Represents a layout for the ListView. + **/ + interface ILayout2 { + //#region Methods + + /** + * Called when the ListView finishes a drag operation. + **/ + dragLeave(): void; + + /** + * Called when the ListView initiates a drag operation. + * @param x The x-coordinate of the drag. + * @param y The y-coordinate of the drag. + * @param dragInfo An object that indicates whether the item is selected. + **/ + dragOver(x: number, y: number, dragInfo: number): void; + + /** + * Called when the ListView requests that the ILayout2 execute animations. + **/ + executeAnimations(): void; + + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + + /** + * Gets the item at the specified hit-test coordinates. These coordinates are absolute coordinates (they are not relative to the layout's content area). + * @param x The x-coordinate to test for. + * @param y The y-coordinate to test for. + * @returns An object that describes the item at the hit test coordinates. It has these properties: type, index. + **/ + hitTest(x: number, y: number): any; + + /** + * Sets the rendering site and specifies whether the layout supports groups. This method is called by the ListView to initialize the layout. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * Retrieves the indexes of the items in the specified pixel range. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * Performs a layout pass. + * @param tree A structure representing the layout tree that is returned from the ListView. + * @param changedRange An object that lists the index of the first item in the changed item range. This object has these properties: startIndex. + * @param modifiedItems An object that contains the old and new indexes of the items that have been modified in the tree. + * @param modifiedGroups An object that contains the old and new indexes of the group elements that have been modified in the tree. + * @returns A Promise that executes after layout is complete, or an object that contains two Promise objects: realizedRangeComplete, layoutComplete. + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): any; + + /** + * Called when the ListView requests that the ILayout2 set up animations. + **/ + setupAnimations(): void; + + /** + * Releases resources that were obtained during the call to initialize. + **/ + uninitialize(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the orientation of the layout. + **/ + orientation: any; + + //#endregion Properties + + } + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayoutSite2 interface. Represents a rendering site for an ILayout. + **/ + interface ILayoutSite { + //#region Properties + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + animationsDisabled: boolean; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + itemSurface: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + rtl: boolean; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + scrollbarPos: number; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + surface: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + viewport: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + viewportSize: any; + + //#endregion Properties + + } + + /** + * Represents a rendering site for an ILayout2. + **/ + interface ILayoutSite2 { + //#region Properties + + /** + * Gets the number of groups in the site. + **/ + groupCount: number; + + /** + * Gets the number of items in the site. + **/ + itemCount: Promise; + + /** + * Gets the pixel range of the realization area. + **/ + realizedRange: any; + + /** + * Gets the tree for use by an object that implements the ILayout2 interface. + **/ + tree: any; + + /** + * Gets the pixel range of visible items in the site. + **/ + visibleRange: any; + + //#endregion Properties + + } + + /** + * Retrieves items from a IListDataSource, enumerates the contents of a IListDataSource, and can optionally register for change notifications. + **/ + interface IListBinding { + //#region Methods + + /** + * Retrieves the current item. + * @returns An IItemPromise that contains the current item. If the cursor has moved past the start or end of the list, the promise completes with a value of null. If the current item has been moved or deleted, the promise returns an error. + **/ + current(): IItemPromise>; + + /** + * Gets the first item from the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. If the list is empty, the promise completes with a value of null. + **/ + first(): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified description and makes it the current item. + * @param description A domain-specific description, to be interpreted by the IListDataAdapter, that identifies the item to retrieve. + * @returns An IItemPromise that contains the requested IItem object. If the item wasn't found, the promise completes with a value of null. + **/ + fromDescription(description: string): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified index and makes it the current item. + * @param index A value greater than or equal to 0 that is the index of the item to retrieve. + * @returns An IItemPromise that contains the requested IItem. If the item wasn't found, the promise completes with a value of null. + **/ + fromIndex(index: number): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified key and makes it the current item. + * @param key The key that identifies the item to retrieve. This value must be a non-empty string. + * @param hints Domain-specific information that provides additional information to the IListDataAdapter to improve retrieval time. + * @returns An IItemPromise that contains the requested IItem. If they item couldn't be found, the promise completes with a value of null. + **/ + fromKey(key: string, hints?: any): IItemPromise>; + + /** + * Makes the specified IItem or IItemPromise the current item. + * @param item The IItem or IItemPromise that will become the current item. + * @returns An IItemPromise that contains the specified item, if it exists. If the specified item is not in the list, the promise completes with a value of null. + **/ + jumpToItem(item: IItem): IItemPromise>; + + /** + * Retrieves the last item in the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. f the list is empty, the promise completes with a value of null. + **/ + last(): IItemPromise>; + + /** + * Retrieves the item after the current item and makes it the current item. + * @returns An IItemPromise that contains the item after the current item. If the cursor moves past the end of the list, the promise completes with a value of null. + **/ + next(): IItemPromise>; + + /** + * Retrieves the item before the current item and makes it the current item. + * @returns An IItemPromise that contains the item before the current item. If the cursor moves past the start of the list, the promise completes with a value of null. + **/ + previous(): IItemPromise>; + + /** + * Releases resources, stops notifications, and cancels outstanding promises for all tracked items returned by this IListBinding. + **/ + release(): void; + + /** + * Creates a request to stop change notifications for the specified item. The change notifications stop when the number of releaseItem calls matches the number of IIItemPromise.retain calls. + * @param item The IItem or IItemPromise that should stop receiving notifications. + **/ + releaseItem(item: IItem): void; + + //#endregion Methods + + } + + /** + * Accesses data for an IListDataSource. + **/ + interface IListDataAdapter { + //#region Methods + + /** + * Overwrites the data of the specified item. + * @param key The key of the item to overwrite. + * @param newData The new data for the item. + * @param indexHint The index of the item, if known. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + change(key: string, newData: T, indexHint: number): Promise; + + /** + * Gets the number of items in the IListDataAdapter object's data source. + * @returns A Promise that contains the number of items the IListDataAdapter contains, or an approximate value if the actual number is unknown. + **/ + getCount(): Promise; + + /** + * Inserts the specified data after the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param previousKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted after this item. + * @param previousIndexHint The index of the item to insert the new data after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string, previousIndexHint: number): Promise>; + + /** + * Adds the specified key and data to the end of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds the specified key and data to the beginning of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts the specified data before the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param nextKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted before this item. + * @param nextIndexHint The index of the item to insert the new data before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string, nextIndexHint: number): Promise>; + + /** + * Retrieves the item that matches the specified description and also retrieves the specified number of items before and after the matched item. + * @param description A description of the item to locate. + * @param countBefore The number of items before the matched item to retrieve. + * @param countAfter The number of items after the matched item to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromDescription(description: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the end of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromEnd(count: number): Promise>; + + /** + * Retrieves the item at the specified index and also retrieves the specified number of items before and after the selected item. + * @param index The index of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromIndex(index: number, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the item that has the specified key and also retrieves the specified number of items before and after the selected item. + * @param key The key of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromKey(key: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the beginning of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromStart(count: number): Promise>; + + /** + * Returns a string representation of the specified item that can be used for comparisons. + * @param item The item for which to generate a signature. + * @returns The signature representation of the specified item. + **/ + itemSignature(item: IItem): string; + + /** + * Moves the specified item to just after another item. + * @param key A key of the item to move. + * @param previousKey The key of another item. The item to move will be moved to just after this item. + * @param indexHint The index of the item to move, if known. + * @param previousIndexHint The index to move the item after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: any, indexHint: string, previousIndexHint: number): Promise>; + + /** + * Moves the specified item to just before another item. + * @param key A key of the item to move. + * @param nextKey The key of another item. The item to move will be moved to just before this item. + * @param indexHint The index of the item to move, if known. + * @param nextIndexHint The index to move the item before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: any, indexHint: string, nextIndexHint: number): Promise>; + + /** + * Moves the specified item to the end of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToEnd(key: string, indexHint: number): Promise>; + + /** + * Moves the specified item to the beginning of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToStart(key: string, indexHint: number): Promise>; + + /** + * Removes the specified item from the IListDataAdapter object's data source. + * @param key The key of the item to remove. + * @param data The new data for the item. + * @param indexHint The index of the item. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + remove(key: string, data: T, indexHint: number): Promise; + + /** + * Registers a notification handler. The IListDataAdapter uses the handler to notify listening objects when its data changes. + * @param notificationHandler The notification handler that the IListDataAdapter will use to provide change notifications. . + **/ + setNotificationHandler(notificationHandler: IListDataNotificationHandler): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether to use an object's identity to determine if an item has changed. + **/ + compareByIdentity: boolean; + + //#endregion Properties + + } + + /** + * Notifies clients when an IListDataAdapter object's data changes. + **/ + interface IListDataNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Raises a notification that an item in the IListDataAdapter object's data source has changed. + * @param item The item that changed. + **/ + changed(item: IItem): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Raises a notification that an item has been added to the IListDataAdapter object's data source. + * @param newItem The new item added to the IListDataAdapter object's data source. + * @param previousKey The key of the item that now precedes the new item, or null if the item was inserted at the start of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was inserted at the end of the list. If previousKey is provided, this parameter may be null. + * @param index The index of the new item. + **/ + inserted(newItem: IItem, previousKey: string, nextKey: string, index?: number): void; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all change notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Raises a notification that an item was moved within the IListDataAdapter object's data source. + * @param item The item that was moved. + * @param previousKey The key of the item that now precedes the new item, or null if the item was moved to the beginning of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was moved to the end of the list. If previousKey is provided, this parameter may be null. + * @param oldIndex The item's original index. + * @param newIndex The item's new index. + **/ + moved(item: IItem, previousKey: string, nextKey: string, oldIndex?: number, newIndex?: number): void; + + /** + * Reloads data from the IListDataAdapter. + **/ + reload(): void; + + /** + * Raises a notification that an item was removed from the IListDataAdapter object's data source. + * @param key The key of the item that was removed. + * @param index The index of the item that was removed. + **/ + removed(key: string, index?: number): void; + + //#endregion Methods + + } + + /** + * Provides access to a data source and enables you to bind, change, add, remove, and move items in that data source. + **/ + interface IListDataSource { + //#region Events + + /** + * Occurs when the status of the IListDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Notifies the IListDataSource that a sequence of edits is about to begin. The IListDataSource will defer notifications until endEdits is called. + **/ + beginEdits(): void; + + /** + * Overwrites the data of the specified item. + * @param key The key for the item to replace. + * @param newData The new data for the item. + * @returns A Promise that contains the IItem that was updated or an EditError if an error was encountered. + **/ + change(key: string, newData: T): Promise>; + + /** + * Creates an IListBinding that can retrieve items from the IListDataSource, enumerate the contents of the IListDataSource object's data, and optionally register for change notifications. + * @param notificationHandler Enables the IListBinding to register for change notifications for individual items obtained from the IListDataSource. If you omit this parameter, change notifications won't be available. + * @returns The new IListBinding. + **/ + createListBinding(notificationHandler?: IListNotificationHandler): IListBinding; + + /** + * Notifies the IListDataSource that the batch of edits that began with the last beginEdits call has completed. The IListDataSource will submit notifications for any changes that occurred between the beginEdits and endEdits calls as a batch and resume normal change notifications. + **/ + endEdits(): void; + + /** + * Retrieves the number of items in the data source. + * @returns A Promise that provides a Number that is the number of items in the data source. + **/ + getCount(): Promise; + + /** + * Inserts a new item after another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param previousKey The key for an item in the data source. The new item will be added after this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string): Promise>; + + /** + * Adds an item to the end of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds an item to the beginning of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts an item before another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param nextKey The key of an item in the data source. The new item will be inserted before this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string): Promise>; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Retrieves the item that has the specified description. + * @param description Domain-specific information, to be interpreted by the IListDataAdapter, that describes the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromDescription(description: any): Promise>; + + /** + * Retrieves the item at the specified index. + * @param index A value that is greater than or equal to zero that is the index of the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromIndex(index: number): Promise>; + + /** + * Retrieves the item with the specified key. + * @param key The key of the item to retrieve. It must be a non-empty string. + * @param description Domain-specific information that IListDataAdapter can use to improve the retrieval time. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item was not found, the promise completes with a null value. + **/ + itemFromKey(key: string, description?: any): Promise>; + + /** + * Moves an item to just after another item. + * @param key The key that identifies the item to move. + * @param previousKey The key of another item in the data source. The item specified by the key parameter will be moved after this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: string): Promise>; + + /** + * Moves an item before another item. + * @param key The key that identifies the item to move. + * @param nextKey The key of another item in the data source. The item specified by the key parameter will be moved before this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: string): Promise>; + + /** + * Moves an item to the end of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToEnd(key: string): Promise>; + + /** + * Moves the specified item to the beginning of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToStart(key: string): Promise>; + + /** + * Removes the specified item from the data source. + * @param key The key that identifies the item to remove. + * @returns A Promise that contains nothing if the operation was successful or an EditError if an error was encountered. + **/ + remove(key: string): Promise>; + + //#endregion Methods + + } + + /** + * Used by an IListBinding to provide change notifications when items in a IListDataSource change. + **/ + interface IListNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Indicates that an item changed. + * @param newItem The updated item. + * @param oldItem The original item. + **/ + changed(newItem: IItem, oldItem: IItem): void; + + /** + * Indicates that the number of items in the IListDataSource has changed. + * @param newCount The updated count. + * @param oldCount The original count. + **/ + countChanged(newCount: number, oldCount: number): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Indicates that the index of an item changed. + * @param handle The temporary ID of the item. + * @param newIndex The new index. + * @param oldIndex The original index. + **/ + indexChanged(handle: string, newIndex: number, oldIndex: number): void; + + /** + * Indicates that an item was added to the IListDataSource. + * @param itemPromise A promise for the new IItem. + * @param previousHandle The temporary ID of the item that precedes the new item. + * @param nextHandle The temporary ID of the item that follows the new item. + **/ + inserted(itemPromise: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an IItemPromise was fulfilled and that the item is now available. + * @param item The fulfilled item. + **/ + itemAvailable(item: IItem): void; + + /** + * Indicates that an item was moved. + * @param item A promise for the IItem that was moved. + * @param previousHandle The temporary ID of the item that now precedes the moved item. + * @param nextHandle The temporary ID of the item that now follows the moved item. + **/ + moved(item: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an item was removed. + * @param handle The temporary ID of the item that was removed. + * @param mirage true if the item never actually existed; false if the item was actually present in the IListDataSource. + **/ + removed(handle: string, mirage: boolean): void; + + //#endregion Methods + + } + + /** + * Used by ListView's currentItem API + **/ + interface IListViewItem { + /** + * Gets or sets index of the ListView item. + **/ + index?: number; + + /** + * Gets or sets key of the ListView item. + **/ + key?: string; + + /** + * Gets or sets whether the ListView item is focused. + **/ + hasFocus?: boolean; + + /** + * Gets or sets whether the ListView item is focused and is showing its focus visual. + **/ + showFocus?: boolean; + } + + /** + * Represents a selection of ListView items. + **/ + interface ISelection { + //#region Methods + + /** + * Adds one or more items to the selection. + * @param items The indexes or keys of the items to add. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + add(items: any): Promise; + + /** + * Clears the selection. + * @returns A Promise that is fulfilled when the clear operation completes. + **/ + clear(): Promise; + + /** + * Returns the number of items in the selection. + * @returns The number of items in the selection. + **/ + count(): number; + + /** + * Returns a list of the indexes for the items in the selection. + * @returns The list of indexes for the items in the selection as an array of Number objects. + **/ + getIndices(): number[]; + + /** + * Returns an array that contains the items in the selection. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + getItems(): Promise[]>; + + /** + * Gets an array of the index ranges for the selected items. + * @returns An array that contains an ISelectionRange object for each index range in the selection. + **/ + getRanges(): ISelectionRange[]; + + /** + * Returns a value that indicates whether the selection contains every item in the data source. + * @returns true if the selection contains every item in the data source; otherwise, false. + **/ + isEverything(): boolean; + + /** + * Removes the specified items from the selection. + * @param items The indexes or keys of the items to remove. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + remove(items: any): Promise; + + /** + * Adds all the items in the ListView to the selection. + **/ + selectAll(): void; + + /** + * Clears the current selection and replaces it with the specified items. + * @param items The indexes or keys of the items that make up the selection. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + set(items: any): Promise; + + //#endregion Methods + + } + + /** + * Represents a range of indexes or keys in an ISelection. + **/ + interface ISelectionRange { + //#region Properties + + /** + * Gets or sets the index of the first item in the range. + **/ + firstIndex: number; + + /** + * Gets or sets the key of the first item in the range. + **/ + firstKey: any; + + /** + * Gets or sets the index of the last item in the range. + **/ + lastIndex: number; + + /** + * Gets or sets of the key of the last item in the range. + **/ + lastKey: any; + + //#endregion Properties + + } + + /** + * Supports semantic zoom functionality by exposing a control as either the zoomed in or the zoomed out view of the SemanticZoom control. + **/ + interface IZoomableView { + //#region Methods + + /** + * Initiates semantic zoom on the custom control. + **/ + beginZoom(): void; + + /** + * Initializes the semantic zoom state for the custom control. + * @param isZoomedOut True if this is the zoomed out view; otherwise false. + * @param isCurrentView True if this is the current view; otherwise false. + * @param triggerZoom The function that manages semantic zoom behavior. Triggers a zoom in or zoom out if the control is the visible control. + * @param prefetchedPages The number of pages of content to pre-fetch for zooming. This value is dependent on the size of the semantic zoom container. More content can be displayed based on the zoom factor and the size of the container. + **/ + configureForZoom(isZoomedOut: boolean, isCurrentView: boolean, triggerZoom: Function, prefetchedPages: number): void; + + /** + * Terminates semantic zoom on the zoomed in or zoomed out child of the custom control. + * @param isCurrentView True if the control is the visible control; otherwise false. + **/ + endZoom(isCurrentView: boolean): void; + + /** + * Retrieves the current item of the zoomed in or zoomed out child of the custom control. + * @returns An object that represents the selected item. This return value must be a Promise for the following: item, position. + **/ + getCurrentItem(): Promise<{ item: T; position: Utilities.IPosition }>; + + /** + * Retrieves the panning axis of the zoomed-in or zoomed-out child of the custom control. + * @returns Identifies the panning axis of the child control. Implementation specific. + **/ + getPanAxis(): string; + + /** + * Manages pointer input for the custom control. + * @param pointerId The ID of the pointer. + **/ + handlePointer(pointerId: string): void; + + /** + * Positions the specified item within the viewport of the child control when panning or zooming begins. + * @param item The object to position within the viewport of the child control. item can be a number, a string, or an object with any number of properties. + * @param position An object that contains the position data of the item relative to the child control. position must be an object with four number properties: left, top, width, and height. These values specify a rectangle that is typically the bounding box of the current item, though the details are up to the control. The units of the position must be in pixels. And the coordinates must be relative to the top-left of the control viewport (which should occupy the same area as the semantic zoom viewport), except when in RTL mode. In RTL mode, return coordinates relative to the top-right off the control viewport. The rectangle is transformed from the coordinate system of one control to that of the other. + **/ + positionItem(item: T, position: Utilities.IPosition): void; + + /** + * Selects the item closest to the specified screen coordinates. + * @param x The x-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport. + * @param y The y-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport.. + **/ + setCurrentItem(x: number, y: number): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * Represents an application toolbar for displaying commands. + **/ + class AppBar { + //#region Constructors + + /** + * Creates a new AppBar object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBar. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the AppBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs after the AppBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the AppBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden AppBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this AppBar. Call this method when the AppBar is no longer needed. After calling this method, the AppBar becomes unusable. + **/ + dispose(): void; + + /** + * Returns the AppBarCommand object identified by id. + * @param id The element idenitifier (ID) of the command to be returned. + * @returns The command identified by id. If multiple commands have the same ID, returns an array of all the commands matching the ID. + **/ + getCommandById(id: string): AppBarCommand; + + /** + * Hides the AppBar. + **/ + hide(): void; + + /** + * Hides the specified commands of the AppBar. + * @param commands The commands to hide. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate?: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the AppBar if it is not disabled. + **/ + show(): void; + + /** + * Shows the specified commands of the AppBar. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate?: boolean): void; + + /** + * Shows the specified commands of the AppBar while hiding all other commands. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Sets the AppBarCommand objects that appear in the app bar. + **/ + commands: AppBarCommand[]; + + /** + * Gets or sets a value that indicates whether the AppBar is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBar. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the AppBar is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the layout of the app bar contents. + **/ + layout: string; + + /** + * Gets or sets a value that specifies whether the AppBar appears at the top or bottom of the main view. + **/ + placement: string; + + /** + * Gets or sets a value that indicates whether the AppBar is sticky (won't light dismiss). If not sticky, the app bar dismisses normally when the user touches outside of the appbar. + **/ + sticky: boolean; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in an app bar. + **/ + class AppBarCommand { + //#region Constructors + + /** + * Creates a new AppBarCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBarCommand. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this AppBarCommand. Call this method when the AppBarCommand is no longer needed. After calling this method, the AppBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the AppBarCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBarCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing HOME or the arrow keys, from the previous AppBarCommand to this AppBarCommand. + **/ + firstElementFocus: HTMLElement; + + /** + * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the AppBarCommand's button is invoked. + **/ + flyout: Flyout; + + /** + * Gets or sets a value that indicates whether the AppBarCommand is hiding or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the icon of the AppBarCommand. + **/ + icon: string; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing END or the arrow keys, from the previous AppBarCommand to this AppBarCommand. + **/ + lastElementFocus: HTMLElement; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets the section of the app bar that the command is in. + **/ + section: string; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets or sets the tooltip of the command. + **/ + tooltip: string; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Provides backwards navigation in the form of a button. + **/ + class BackButton { + //#region Constructors + + /** + * Creates a new BackButton. + * @constructor + * @param element The DOM element hosts the new BackButton. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this BackButton. Call this method when the BackButton is no longer needed. After calling this method, the BackButton becomes unusable. + **/ + dispose(): void; + + /** + * Checks the current navigation history and updates the value of the control's disabled attribute. + **/ + refresh(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the HTML element that hosts this BackButton. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + /** + * Represents a layout for the ListView in which items are arranged in a grid and items can span multiple grid cells. + **/ + class CellSpanningLayout { + //#region Constructors + + /** + * Creates a new CellSpanningLayout. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new CellSpanningLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: ILayoutSite2, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the position of group headers relative to their items. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * Gets or sets a function that enables cell-spanning and establishes base cell dimensions. + **/ + groupInfo: Function; + + /** + * Gets or sets a function that returns the width and height of an item, as well as whether it should appear in a new column. Setting this function improves performance because the ListView can allocate space for an item without having to measure it first. + **/ + itemInfo: Function; + + /** + * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. + **/ + maximumRowsOrColumns: number; + + /** + * This API supports the Windows Library for JavaScript infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets the orientation of the CellSpanningLayout. For a CellSpanningLayout, this property always returns Orientation.horizontal. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Allows users to pick a date value. + **/ + class DatePicker { + //#region Constructors + + /** + * Initializes a new instance of the DatePicker control. + * @constructor + * @param element The DOM element associated with the DatePicker control. + * @param options The set of options to be applied initially to the DatePicker control. The options are the following: calendar, current, datePattern, disabled, maxYear, minYear, monthPattern, yearPattern. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when any of the controls are changed by the user. + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener. + * @param type The type (name) of the event. + * @param listener The function that handles the event. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this DatePicker. Call this method when the DatePicker is no longer needed. After calling this method, the DatePicker becomes unusable. + **/ + dispose(): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes a listener for the specified event. + * @param type The name of the event for which to remove a listener. + * @param listener The listener. + * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. + **/ + removeEventListener(type: string, listener: Function, useCapture?: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the calendar to use. + **/ + calendar: string; + + /** + * Gets or sets the current date of the DatePicker. You can use either a date string or a Date object to set this property. + **/ + current: Date; + + /** + * Gets or sets the display pattern for the date. The default date pattern is day.integer(2). You can change the date pattern by changing the number of integers displayed. + **/ + datePattern: string; + + /** + * Specifies whether the DatePicker is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element for the DatePicker. + **/ + element: HTMLElement; + + /** + * Gets or sets the maximum Gregorian year available for picking. + **/ + maxYear: number; + + /** + * Gets or sets the minimum Gregorian year available for picking. + **/ + minYear: number; + + /** + * Gets or sets the display pattern for the month. The default month pattern is month.abbreviated. You can change the month pattern to the following values: month.full. The full name of the month. month.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. If you do specify the number of letters, the actual length of the month name that appears may vary. month.solo.full. A representation of the month that is suitable for stand-alone display. You can also use month.solo.abbreviated(n). month.integer(n). You can use integer with or without specifying the number of integers. + **/ + monthPattern: string; + + /** + * Gets or sets the display pattern for the year. The default year pattern is year.full. You can change the year pattern to the following values: year.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. + **/ + yearPattern: string; + + //#endregion Properties + + } + + /** + * Adds event-related methods to the control. + **/ + class DOMEventMixin { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture true to initiate capture; otherwise, false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type, adding the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true to initiate capture; otherwise, false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If the name of the options property begins with "on", the property value is a function and the control supports addEventListener. This method calls the addEventListener method on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + setOptions(control: any, options: any): void; + + //#endregion Methods + + } + + /** + * Displays a collection, such as a set of photos, one item at a time. + **/ + class FlipView { + //#region Constructors + + /** + * Creates a new FlipView. + * @constructor + * @param element The DOM element that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the pageselected event, add a property named "onpageselected" and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the datasource count changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: source. + **/ + ondatasourcecountchanged(eventInfo: Event): void; + + /** + * Raised when the FlipView flips to a page and its renderer function completes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpagecompleted(eventInfo: CustomEvent): void; + + /** + * Raised when the FlipView flips to a page. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpageselected(eventInfo: CustomEvent): void; + + /** + * Occurs when an item becomes invisible or visible. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source, detail.visible. + **/ + onpagevisibilitychanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. For a list of events, see the FlipView object page. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Returns the number of items in the FlipView control's itemDataSource. + * @returns A Promise that contains the number of items in the list or WinJS.UI.CountResult.unknown if the count is unavailable. + **/ + count(): Promise; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this FlipView. Call this method when the FlipView is no longer needed. After calling this method, the FlipView becomes unusable. + **/ + dispose(): void; + + /** + * Forces the FlipView to update its layout. Use this function when making the FlipView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Navigates to the next page. + * @returns true if the FlipView begins navigating to the next page; false if the FlipView is already at the last item or is in the middle of another navigation animation. + **/ + next(): boolean; + + /** + * Navigates to the previous item. + * @returns true if the FlipView begins navigating to the previous page; nfalse if the FlipView is already at the first page or is in the middle of another navigation animation. + **/ + previous(): boolean; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event. + * @param eventHandler The event handler function to remove. + * @param useCapture Set to true to unregister the event handler for the capturing phase; otherwise, set to false to unregister the event handler for the bubbling phase. + **/ + removeEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Sets custom animations for the FlipView to use when navigating between pages. + * @param animations An object that contains up to three fields, one for each navigation action: next, previous, and jump. Each of those fields must be a function with this signature: function (outgoingPage, incomingPage) Each function must return a WinJS.Promise that completes once the animations are finished. If a field is null or undefined, the FlipView reverts to its default animation for that action. + **/ + setCustomAnimations(animations: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the index of the currently displayed page. + **/ + currentPage: number; + + /** + * Gets the HTML element that hosts this FlipView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that provides the FlipView with items to display. The FlipView displays one item at a time, on its own page. + **/ + itemDataSource: IListDataSource; + + /** + * Gets or sets the spacing between each item, in pixels. + **/ + itemSpacing: number; + + /** + * Gets or sets a Template or function that defines the HTML for each item's page. + **/ + itemTemplate: any; + + /** + * Gets or sets the orientation of the FlipView, horizontal or vertical. + **/ + orientation: string; + + //#endregion Properties + + } + + /** + * Displays lightweight UI that is either information, or requires user interaction. Unlike a dialog, a Flyout can be light dismissed by clicking or tapping off of it. + **/ + class Flyout { + //#region Constructors + + /** + * Creates a new Flyout object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new Flyout. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised immediately after a flyout is fully hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised immediately after a flyout is fully shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before hiding a flyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Raised just before showing a flyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. + **/ + dispose(): void; + + /** + * Hides the Flyout, if visible, regardless of other states. + **/ + hide(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the Flyout, if hidden, regardless of other states. + * @param anchor Required. The DOM element to anchor the Flyout. + * @param placement The placement of the Flyout to the anchor: the string literal "top", "bottom", "left", or "right". + * @param alignment For "top" or "bottom" placement, the alignment of the Flyout to the anchor's edge: the string literal "center", "left", or "right". + **/ + show(anchor: HTMLElement, placement: string, alignment: string): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default alignment to be used for this Flyout. + **/ + alignment: string; + + /** + * Gets or sets the default anchor to be used for this Flyout. + **/ + anchor: HTMLElement; + + /** + * Gets the DOM element that hosts the Flyout. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the Flyout is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the default placement to be used for this Flyout. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Represents a grid layout for the ListView in which items are arranged in a horizontal grid. + **/ + class GridLayout { + //#region Constructors + + /** + * Creates a new GridLayout object. + * @constructor + * @param options The set of properties and values to apply to the new GridLayout. + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * This method is no longer supported. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This method is no longer supported. + **/ + endLayout(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This method is no longer supported. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: any, keyPressed: any): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This method is no longer supported. + **/ + init(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This method is no longer supported. + **/ + itemsMoved(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This method is no longer supported. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * This method is no longer supported. + **/ + reset(): void; + + /** + * This method is no longer supported. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + /** + * This method is no longer supported. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + backdropColor: string; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + groupInfo: Function; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. + **/ + horizontal: boolean; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + itemInfo: Function; + + /** + * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. + **/ + maximumRowsOrColumns: number; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the maximumRowsOrColumns property. + **/ + maxRows: number; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets or sets the orientation of the GridLayout. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Creates a hub navigation pattern consisting of sections that can be navigated to. Each section is defined by a HubSection object. + **/ + class Hub { + //#region Constructors + + /** + * Creates a new Hub control. + * @constructor + * @param element The DOM element that will host the Hub control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the contentanimating event, add a property named "oncontentanimating" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the Hub is about to play entrance, content transition, insert, or remove animations. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.index, detail.section. + **/ + oncontentanimating(eventInfo: CustomEvent): void; + + /** + * Raised when the user clicks on an interactive header. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.section. + **/ + onheaderinvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the Hub control's loadingState changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: loadingState. + **/ + onloadingstatechanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Hub. Call this method when the Hub is no longer needed. After calling this method, the Hub becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the Hub control. + **/ + element: HTMLElement; + + /** + * Gets or sets the Template or templating function that creates the DOM elements for each HubSection header. Your HubSection object should provide strings for HubSection.header property. + **/ + headerTemplate: any; + + /** + * Gets or sets the index of the first HubSection at least partially in view. This property is useful for animating the visible content in the Hub. + **/ + indexOfFirstVisible: number; + + /** + * Gets or sets the index of last HubSection at least partially in view. Used for animating the visible content in the Hub. + **/ + indexOfLastVisible: number; + + /** + * Gets a value that indicates whether the hub is still loading or whether loading is complete. The value changes to complete after all the sections and content inside them has loaded. + **/ + loadingState: string; + + /** + * Gets or sets the orientation of sections within the Hub. + **/ + orientation: Orientation; + + /** + * Gets or sets the distance between the start of the Hub and the current viewable area. + **/ + scrollPosition: number; + + /** + * Gets or sets the index of the first visible HubSection. + **/ + sectionOnScreen: number; + + /** + * Gets or sets the List that contains the HubSection objects that belong to this Hub. + **/ + sections: WinJS.Binding.List; + + /** + * This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. + **/ + zoomableView: IZoomableView; + + //#endregion Properties + + } + + /** + * Defines a section of a Hub. + **/ + class HubSection { + //#region Constructors + + /** + * Creates a new HubSection. + * @constructor + * @param element The DOM element hosts the new HubSection. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this HubSection. Call this method when the HubSection is no longer needed. After calling this method, the HubSection becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the HubSection control's content. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts this HubSection. + **/ + element: HTMLElement; + + /** + * Gets or sets the header for this HubSection. + **/ + header: string; + + /** + * Gets a value that specifies whether the header is static. + **/ + isHeaderStatic: boolean; + + //#endregion Properties + + } + + /** + * Enables you to include an HTML page dynamically. As part of the constructor, you must include an option indicating the URI of the page. + **/ + class HtmlControl { + //#region Constructors + + /** + * Initializes a new instance of HtmlControl to define a new page control. + * @constructor + * @param element The element that hosts the HtmlControl. + * @param options The options for configuring the page. The uri option is required in order to specify the source document for the content of the page. Other options are the ones used by the WinJS.Pages.render method. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + } + + /** + * Defines an item that can be pressed, swiped, and dragged. + **/ + class ItemContainer { + //#region Constructors + + /** + * Creates a new ItemContainer. + * @constructor + * @param element The DOM element hosts the new ItemContainer. For the ItemContainer to be accessible, this element must have its role attribute set to "list" or "listbox". If tapBehavior is set to none and selectionDisabled is true, then use the "list" role; otherwise, use the "listbox" role. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the item is invoked. (You can use the tapBehavior property to specify whether taps and clicks invoke the item.) + * @param eventInfo An object that contains information about the event. + **/ + oninvoked(eventInfo: CustomEvent): void; + + /** + * Raised after the item is selected or deselected. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanged(eventInfo: CustomEvent): void; + + /** + * Raised just before the current selection changes. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanging(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this ItemContainer. Call this method when the ItemContainer is no longer needed. After calling this method, the ItemContainer becomes unusable. + **/ + dispose(): void; + + /** + * Forces the ItemContainer to update its layout. Call this function when the reading direction of the app changes after the control has been initialized. + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the item can be dragged. + **/ + draggable: boolean; + + /** + * Gets the element that hosts this ItemContainer. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether the item is selected. + **/ + selected: boolean; + + /** + * Gets or sets a value that specifies whether selection of this item is disabled. + **/ + selectionDisabled: boolean; + + /** + * Gets or sets how the ItemContainer reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. + **/ + swipeBehavior: WinJS.UI.SwipeBehavior; + + /** + * Gets or sets the orientation of swipe gestures. + **/ + swipeOrientation: Orientation; + + /** + * Gets or sets how the ItemContainer reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + //#endregion Properties + + } + + /** + * This object supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + class Layout { + } + + /** + * Represents a layout for the ListView in which items are arranged in a vertical list. + **/ + class ListLayout { + //#region Constructors + + /** + * Creates a new ListLayout. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new ListLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * This method is no longer supported. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This method is no longer supported. + **/ + endLayout(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This method is no longer supported. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: any): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This method is no longer supported. + **/ + init(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + initialize(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel + * @param lastPixel + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This method is no longer supported. + **/ + itemsMoved(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This method is no longer supported. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * This method is no longer supported. + **/ + reset(): void; + + /** + * This method is no longer supported. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + /** + * This method is no longer supported. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + backdropColor: string; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + groupInfo: Function; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. + **/ + horizontal: boolean; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + itemInfo: Function; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets or sets the orientation of the GridLayout. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Displays data items in a customizable list or grid. + **/ + class ListView { + //#region Constructors + + /** + * Creates a new ListView. + * @constructor + * @param element The DOM element that hosts the ListView control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the selectionchanged event, add a property named "onselectionchanged" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ListView is about to play an entrance or contentTransition animation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.setPromise. + **/ + oncontentanimating(eventInfo: CustomEvent): void; + + /** + * Raised when the user taps or clicks a group header. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.groupHeaderIndex, detail.groupHeaderPromise. + **/ + ongroupheaderinvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the ListView is a drop target and the onitemdragenter has been disabled. This is raised every time the cursor is moved between a new pair of items. If you call preventDefault on this event, then the ListView does not move the items slightly above/below the cursor to provide visual feedback for a drop. + * @param eventInfo An object that contains information about the event. The detail property of this object contains additional information about the event. + **/ + onitemdragbetween(eventInfo: CustomEvent): void; + + /** + * Raised when the user is dragging an item from the ListView and the datasource changes while the user is dragging. + * @param eventInfo An object that contains information about the event. The detail property of this object contains additional information about the event. + **/ + onitemdragchanged(eventInfo: CustomEvent): void; + + /** + * Raised when an item is dropped onto the ListView as the result of a drag operation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer, detail.index, detail.insertAfterIndex. + **/ + onitemdragdrop(eventInfo: CustomEvent): void; + + /** + * Raised when the user drops an item dragged from a ListView. + * @param eventInfo An object that contains information about the event. + **/ + onitemdragend(eventInfo: CustomEvent): void; + + /** + * Raised when an dragged item enters the bounds of the ListView control. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer. + **/ + onitemdragenter(eventInfo: CustomEvent): void; + + /** + * Raised when a draggable item leaves the bounds of a ListView control. + * @param eventInfo An object that contains information about the event. + **/ + onitemdragleave(eventInfo: CustomEvent): void; + + /** + * Raised when the user begins to drag an item from a ListView control. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer, detail.dragInfo. + **/ + onitemdragstart(eventInfo: CustomEvent): void; + + /** + * Occurs when the user taps or clicks an item. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.itemIndex. + **/ + oniteminvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the focused item changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.oldFocus, detail.oldNewFocus. + **/ + onkeyboardnavigating(eventInfo: CustomEvent): void; + + /** + * Occurs when the ListView control's loadingState changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.scrolling. + **/ + onloadingstatechanged(eventInfo: CustomEvent): void; + + /** + * Occurs after the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. To obtain the selected items, use the ListView.selection property. + **/ + onselectionchanged(eventInfo: CustomEvent): void; + + /** + * Occurs just before the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.newSelection, detail.preventTapBehavior. + **/ + onselectionchanging(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the ListView object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onselectionchange", you specify "selectionchange". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. + **/ + dispose(): void; + + /** + * Returns the DOM element that represents the item at the specified index. + * @param itemIndex The index of the item. + * @returns The DOM element that represents the item at the specified index. + **/ + elementFromIndex(itemIndex: number): HTMLElement; + + /** + * Makes the item at the specified index visible. If necessary, the ListView will scroll to the item. + * @param itemIndex The index of the item to scroll into view. + **/ + ensureVisible(itemIndex: number): void; + + /** + * Forces the ListView to update its layout. Use this function when making the ListView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Returns the index of the item that the specified DOM element displays. + * @param element The DOM element that displays the item. + * @returns The index of the item displayed by element. + **/ + indexOfElement(element: HTMLElement): number; + + /** + * Loads the next set of pages if the ListView control's loadingBehavior is set to "incremental" (otherwise, it does nothing). The number of pages to be loaded is determined by the pagesToLoad property. + **/ + loadMorePages(): void; + + /** + * Repositions all the visible items in the ListView to adjust for items whose sizes have changed. Most apps won’t ever need to call this method. For more info, see the Remarks section. + **/ + recalculateItemPosition(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Triggers the ListView disposal service manually. + **/ + static triggerDispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the next set of pages is automatically loaded when the user scrolls beyond the number of pages specified by the pagesToLoadThreshold property. + **/ + automaticallyLoadPages: boolean; + + /** + * Gets or sets an IListViewItem that indicates which item should have keyboard focus and the focus state of that item. + **/ + currentItem: IListViewItem; + + /** + * Gets the HTML element that hosts this ListView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that contains the groups for the items in the itemDataSource. + **/ + groupDataSource: IListDataSource; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks a group header. + **/ + groupHeaderTapBehavior: GroupHeaderTapBehavior; + + /** + * Gets or sets the Template or function that creates the DOM elements for each group header in the groupDataSource. Each group header can contain multiple elements, but it must have a single root element. + **/ + groupHeaderTemplate: any; + + /** + * Gets or sets the first visible item. + **/ + indexOfFirstVisible: number; + + /** + * Gets the index of the last visible item in the ListView. + **/ + indexOfLastVisible: number; + + /** + * Gets or sets the data source that provides the ListView with items. + **/ + itemDataSource: IListDataSource; + + /** + * Go Gets or sets a value that specifies whether items can be dragged. When this is set to true the ListView provides built in behaviors related to item dragging. + **/ + itemsDraggable: boolean; + + /** + * Gets or sets whether the ListView control's items can be reordered within itself by dragging and dropping. + **/ + itemsReorderable: boolean; + + /** + * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the itemDataSource. Each item can contain multiple elements, but it must have a single root element. + **/ + itemTemplate: any; + + /** + * Gets or sets an object that controls the layout of the ListView. + **/ + layout: ILayout2; + + /** + * Gets or sets a value that specifies how the ListView fetches items and adds and removes them to the DOM. Don't change the value of this property after the ListView has begun loading data. + **/ + loadingBehavior: string; + + /** + * Gets a value that indicates whether the ListView is still loading or whether loading is complete. + **/ + loadingState: string; + + /** + * Gets or sets the maximum number of realized items. + **/ + maxDeferredItemCleanup: number; + + /** + * Gets or sets the number of pages to load when the loadingBehavior property is set to "incremental" and the user scrolls beyond the threshold specified by the pagesToLoadThreshold property. + **/ + pagesToLoad: number; + + /** + * Gets or sets the threshold (in pages) for initiating an incremental load. When the last visible item is within the specified number of pages from the end of the loaded portion of the list, and if automaticallyLoadPages is true and loadingBehavior is set to "incremental", the ListView initiates an incremental load. + **/ + pagesToLoadThreshold: number; + + /** + * Gets or sets the function that is called when the ListView discards or recycles the element representation of a group header. + **/ + resetGroupHeader: (header: any, element: HTMLElement) => void; + + /** + * Gets or sets the function that is called when an item is removed, an item is changed, or an item falls outside of the realized range of the ListView. + **/ + resetItem: (item: T, element: HTMLElement) => void; + + /** + * Gets or sets the distance, in pixels, of the start of the viewable area within the viewport. + **/ + scrollPosition: number; + + /** + * Gets an ISelection that contains the range of currently selected items. + **/ + selection: ISelection; + + /** + * Gets or sets the selection mode of the ListView. + **/ + selectionMode: SelectionMode; + + /** + * Gets or sets how the ListView reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. + **/ + swipeBehavior: WinJS.UI.SwipeBehavior; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + /** + * Gets a ZoomableView that supports semantic zoom functionality. This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. + **/ + zoomableView: IZoomableView>; + + //#endregion Properties + + } + + /** + * Represents a menu flyout for displaying commands. + **/ + class Menu { + //#region Constructors + + /** + * Creates a new Menu object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new Menu. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the Menu is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs after the Menu is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the Menu is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden Menu is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this Menu. Call this method when the Menu is no longer needed. After calling this method, the Menu becomes unusable. + **/ + dispose(): void; + + /** + * Returns the MenuCommand object identified by id. + * @param id The element identifier (ID) of the command to be returned. + * @returns The command identified by id. + **/ + getCommandById(id: string): MenuCommand; + + /** + * Hides the Menu. + **/ + hide(): void; + + /** + * Hides the specified commands of the Menu. + * @param commands The commands to hide. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the Menu, if hidden, regardless of other states. + * @param anchor Required. The DOM element to anchor the Menu. + * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. + * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. + **/ + show(anchor: HTMLElement, placement: string, alignment: string): void; + + /** + * Shows the specified commands of the Menu. + * @param commands The commands to show. The array elements may be Menu objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate: boolean): void; + + /** + * Shows the specified commands of the Menu while hiding all other commands. + * @param commands The commands to show. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default alignment to be used for this Menu. + **/ + alignment: string; + + /** + * Gets or sets the default anchor to be used for this Menu. + **/ + anchor: HTMLElement; + + /** + * Sets the MenuCommand objects that appear in the menu. + **/ + commands: MenuCommand[]; + + /** + * Gets the DOM element that hosts the Menu. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the Menu is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the default placement to be used for this Menu. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in a Menu object. + **/ + class MenuCommand { + //#region Constructors + + /** + * Creates a new MenuCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new MenuCommand. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Disposes this control. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the MenuCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the MenuCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the MenuCommand's button is invoked. + **/ + flyout: Flyout; + + /** + * Gets a value that indicates whether the MenuCommand is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Displays navigation commands in a toolbar that the user can show or hide. + **/ + class NavBar { + //#region Constructors + + /** + * Creates a new NavBar. + * @constructor + * @param element The DOM element that will host the new NavBar. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the NavBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised after the NavBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before the NavBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden NavBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + /** + * Occurs after the NavBar has finished processing its child elements. + * @param eventInfo An object that contains information about the event. + **/ + onchildrenprocessed(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBar. Call this method when the NavBar is no longer needed. After calling this method, the NavBar becomes unusable. + **/ + dispose(): void; + + /** + * Hides the NavBar. + **/ + hide(): void; + + /** + * Hides the specified commands of the NavBar. + * @param commands The commands to hide. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Shows the NavBar if it is not disabled. + **/ + show(): void; + + /** + * Shows the specified commands of the NavBar. + * @param commands The commands to show. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate: boolean): void; + + /** + * Shows the specified commands of the NavBar while hiding all other commands. + * @param commands The commands to show. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + commands: AppBarCommand; + + /** + * Gets or sets a value that indicates whether the NavBar is disabled. + **/ + disabled: boolean; + + /** + * Gets the HTML element that hosts this NavBar. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the NavBar is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + layout: string; + + /** + * Gets or sets a value that specifies whether the NavBar appears at the top or bottom of the main view. + **/ + placement: string; + + /** + * Gets or sets a value that indicates whether the NavBar is sticky (won't light dismiss). If not sticky, the NavBar dismisses normally when the user touches outside of the NavBar. + **/ + sticky: boolean; + + //#endregion Properties + + } + + /** + * Represents a navigation command in a NavBarContainer. + **/ + class NavBarCommand { + //#region Constructors + + /** + * Creates a new NavBarCommand. + * @constructor + * @param element The DOM element hosts the new NavBarCommand. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBarCommand. Call this method when the NavBarCommand is no longer needed. After calling this method, the NavBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the HTML element that hosts this NavBarCommand. + **/ + element: HTMLElement; + + /** + * Gets or sets the command's icon. + **/ + icon: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Get or sets the location to navigate to when this command is invoked. + **/ + location: any; + + /** + * Gets or sets a value that specifies whether to show the split tab stop. + **/ + splitButton: boolean; + + /** + * Gets a value that indicates whether the splitButton is open. + **/ + splitOpened: boolean; + + /** + * Gets or sets a user-defined object that represents the state associated with the command's location. + **/ + state: any; + + /** + * Gets or sets the tooltip of the command. + **/ + tooltip: any; + + //#endregion Properties + + } + + /** + * Contains a group of NavBarCommand objects in a NavBar. + **/ + class NavBarContainer { + //#region Constructors + + /** + * Creates a new NavBarContainer. + * @constructor + * @param element The DOM element hosts the new NavBarContainer. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when a child NavBarCommand object's click event fires. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.navbarcommand, detail.data. + **/ + oninvoked(eventInfo: CustomEvent): void; + + /** + * Occurs when the split button of a child NavBarCommand is opened or closed. A split button is toggled when the user navigates to another page or opens another split button. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.opened, detail.index, detail.navbarcommand, detail.data. + **/ + onsplittoggle(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBarCommand. Call this method when the NavBarCommand is no longer needed. After calling this method, the NavBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Forces the NavBarContainer to update its layout. Use this function when making the NavBarContainer visible again after you set its style.display property to "none". + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the index of the current item. + **/ + currentIndex: number; + + /** + * Gets or sets a WinJS.Binding.List that generates NavBarCommand objects. + **/ + data: WinJS.Binding.List; + + /** + * Gets the HTML element that hosts this NavBarContainer. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether NavBarCommand objects in this container use a fixed or dynamic width. + **/ + fixedSize: boolean; + + /** + * Gets or sets a value that specifies whether the NavBarContainer has a horizontal or vertical layout. + **/ + layout: Orientation; + + /** + * Gets or sets a value that specifies how many rows of navigation commands to display on a page. + **/ + maxRows: number; + + /** + * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the data source. Each item can contain multiple elements, but it must have a single root element. + **/ + template: WinJS.Binding.Template; + + //#endregion Properties + + } + + /** + * Lets the user rate something by clicking an icon that represents a rating. The Rating control can display three types of ratings: an average rating, a tentative rating, and the user's rating. + **/ + class Rating { + //#region Constructors + + /** + * Creates a new Rating. + * @constructor + * @param element The DOM element hosts the new Rating. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the user finishes interacting with the rating control without committing a tentative rating. + * @param eventInfo An object that contains information about the event. + **/ + oncancel(eventInfo: Event): void; + + /** + * Raised when the user commits a change to the userRating. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. + **/ + onchange(eventInfo: CustomEvent): void; + + /** + * Raised when the user is choosing a new tentative Rating. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. + **/ + onpreviewchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this Rating. Call this method when the Rating is no longer needed. After calling this method, the Rating becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the average rating. + **/ + averageRating: number; + + /** + * Gets or sets whether the control is disabled. When the control is disabled, the user can't specify a new user rating or modify an existing rating. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the Rating. + **/ + element: HTMLElement; + + /** + * Gets or sets whether control lets the user clear the rating. + **/ + enableClear: boolean; + + /** + * Gets or sets the maximum possible rating value. + **/ + maxRating: number; + + /** + * Gets or sets a set of descriptions to show for rating values in the tooltip. + **/ + tooltipStrings: string[]; + + /** + * Gets or sets the user's rating. + **/ + userRating: number; + + //#endregion Properties + + } + + /** + * Generates HTML from a set of data. Use this control to generate lists of items. + **/ + class Repeater { + //#region Constructors + + /** + * Creates a new Repeater control. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised after an item in the Repeater control's data source changes and after the corresponding DOM element has been updated. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * Raised after an item in the Repeater control's data source changes but before the corresponding DOM element has been updated. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. + **/ + onitemchanging(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been added to the Repeater control's data source and after the corresponding DOM element has been added. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been added to the Repeater control's data source but before the corresponding DOM element has been added. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. + **/ + oniteminserting(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source but before the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. + **/ + onitemmoving(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been removed from the Repeater control's data source but before the corresponding DOM element has been removed. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. + **/ + onitemremoving(eventInfo: CustomEvent): void; + + /** + * Raised when the Repeater has finished loading a new set of data. This event is only fired on construction. This event is only raised when the Repeater is constructed or its data source or template changes. + * @param eventInfo An object that contains information about the event. + **/ + onitemsloaded(eventInfo: CustomEvent): void; + + /** + * Raised after the Repeater control's underlying data has been updated and after the updated HTML has been reloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements. + **/ + onitemsreloaded(eventInfo: CustomEvent): void; + + /** + * Raised after the Repeater control's underlying data has been updated but before the updated HTML has been reloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements, detail.setPromise. + **/ + onitemsreloading(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Repeater. Call this method when the Repeater is no longer needed. After calling this method, the Repeater becomes unusable. + **/ + dispose(): void; + + /** + * Returns the HTML element for the item at the specified index. + * @param index The index of the item. + * @returns The DOM element for the specified item. + **/ + elementFromIndex(index: number): HTMLElement; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the List that provides the Repeater with items to display. + **/ + data: WinJS.Binding.List; + + /** + * Gets the DOM element that hosts the Repeater. + **/ + element: HTMLElement; + + /** + * Gets the number of items in the Repeater control. + **/ + length: number; + + /** + * Gets or sets a WinJS.Binding.Template or custom rendering function that defines the HTML of each item within the Repeater. + **/ + template: WinJS.Binding.Template; + + //#endregion Properties + + } + + /** + * Enables the user to perform search queries and select suggestions. + **/ + class SearchBox { + //#region Constructors + + /** + * Creates a new SearchBox. + * @constructor + * @param element The DOM element hosts the new SearchBox. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the user or the app changes the queryText. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.queryText, detail.linguisticDetails. + **/ + onquerychanged(eventInfo: CustomEvent): void; + + /** + * Raised awhen the user clicks the search glyph or presses Enter. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.queryText, detail.linguisticDetails, detail.keyModifiers. + **/ + onquerysubmitted(eventInfo: CustomEvent): void; + + /** + * Raised when the app automatically redirects focus to the search box. This event can only be raised when the focusOnKeyboardInput property is set to true. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.propertyName. + **/ + onreceivingfocusonkeyboardinput(eventInfo: CustomEvent): void; + + /** + * Raised when the user selects a suggested option for the search. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tag, detail.keyModifiers, detail.storageFile. + **/ + onresultsuggestionschosen(eventInfo: CustomEvent): void; + + /** + * Raised when the system requests search suggestions from this app. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.linguisticDetails, detail.queryText, detail.searchSuggestionCollection. + **/ + onsuggestionsrequested(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SearchBox. Call this method when the SearchBox is no longer needed. After calling this method, the SearchBox becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Specifies whether suggestions based on local files are automatically displayed in the search pane, and defines the criteria that Windows uses to locate and filter these suggestions. + * @param settings The new settings for local content suggestions. + **/ + setLocalContentSuggestionSettings(settings: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets whether the first suggestion is chosen when the user presses Enter. + **/ + chooseSuggestionOnEnter: boolean; + + /** + * Gets or sets a value that specifies whether the SearchBox is disabled. If the control is disabled, it won't receive focus. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the SearchBox. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether the search box automatically receives focus when the user types into the app window. + **/ + focusOnKeyboardInput: boolean; + + /** + * Gets or sets the placeholder text for the SearchBox. This text is displayed if there is no other text in the input box. + **/ + placeholderText: string; + + /** + * Gets or sets the query text for the SearchBox. + **/ + queryText: string; + + /** + * Gets or sets the search history context. This context is used a secondary key (the app ID is the primary key) for storing search history. + **/ + searchHistoryContext: string; + + /** + * Gets or sets a value that specifies whether search history is disabled. + **/ + searchHistoryDisabled: boolean; + + //#endregion Properties + + } + + /** + * Enables the user to zoom between two different views supplied by two child controls. One child control supplies the zoomed-out view and the other provides the zoomed-in view. + **/ + class SemanticZoom { + //#region Constructors + + /** + * Creates a new SemanticZoom. + * @constructor + * @param element The DOM element that hosts the SemanticZoom. + * @param options An object that contains one or more property/value pairs to apply to the new control. This object can contain these properties: initiallyZoomedOut Boolean, zoomFactor 0.2–0.85. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the control zooms in or out. + * @param eventInfo An object that contains information about the event. The detail property of this object is true when the control is zoomed out. Otherwise, it's false. + **/ + onzoomchanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SemanticZoom. Call this method when the SemanticZoom is no longer needed. After calling this method, the SemanticZoom becomes unusable. + **/ + dispose(): void; + + /** + * Forces the SemanticZoom to update its layout. Use this function when making the SemanticZoom visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the SemanticZoom control. + **/ + element: HTMLElement; + + /** + * Gets or a sets a value that specifies whether to display the SemanticZoom zoom out button. + **/ + enableButton: boolean; + + /** + * Determines whether any controls contained in a SemanticZoom should be processed separately. This property is always true, meaning that the SemanticZoom takes care of processing its own controls. + **/ + isDeclarativeControlContainer: boolean; + + /** + * Gets or sets a value that indicates whether SemanticZoom is locked and zooming between views is disabled. + **/ + locked: boolean; + + /** + * Gets or sets a value that indicates whether the control is zoomed out. + **/ + zoomedOut: boolean; + + /** + * Gets or sets a value that specifies how much the scaling the cross-fade animation performs when the SemanticZoom transitions between views. + **/ + zoomFactor: number; + + //#endregion Properties + + } + + /** + * Provides users with fast, in-context access to settings that affect the current Windows Store app. + **/ + class SettingsFlyout { + //#region Constructors + + /** + * Creates a new SettingsFlyout object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new SettingsFlyout. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised immediately after the SettingsFlyout is completely hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised immediately after a SettingsFlyout is fully shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before hiding a SettingsFlyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Raised just before showing a SettingsFlyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SettingsFlyout. Call this method when the SettingsFlyout is no longer needed. After calling this method, the SettingsFlyout becomes unusable. + **/ + dispose(): void; + + /** + * Hides the SettingsFlyout, if visible, regardless of other states. + **/ + hide(): void; + + /** + * Loads a fragment of the SettingsFlyout. Your app calls this when the user invokes a settings command and the WinJS.Application.onsettings event occurs. + * @param e An object that contains information about the event, received from the WinJS.Application.onsettings event. The detail property of this object contains the applicationcommands sub-property that you set to an array of settings commands. You then populate the SettingsFlyout with these commands by a call to populateSettings. + **/ + static populateSettings(e: CustomEvent): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the SettingsPane UI, if hidden. + **/ + show(): void; + + /** + * Shows the SettingsPane UI, if hidden, regardless of other state. + **/ + static show(): void; + + /** + * Show the Settings flyout using the Settings element identifier (ID) and the path of the page that contains the Settings element. + * @param id The ID of the Settings element. + * @param path The path of the page that contains the Settings element. + **/ + static showSettings(id: string, path: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element the SettingsFlyout is attached to. + **/ + element: HTMLElement; + + /** + * Gets whether the SettingsFlyout is hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the settings command Id for the SettingsFlyout control. + **/ + settingsCommandId: string; + + /** + * This property may be unavailable or altered in future versions. Use the CSS width property of the element that has the win-settingsflyout class instead. + **/ + width: string; + + //#endregion Properties + + } + + /** + * A type of IListDataSource that provides read-access to an object that implements the IStorageQueryResultBase interface. A StorageDataSource enables you to query and bind to items in the data source. + **/ + class StorageDataSource { + //#region Constructors + + /** + * Creates a new StorageDataSource object. + * @constructor + * @param query The IStorageQueryResultBase that the StorageDataSource obtains its items from. Instead of IStorageQueryResultBase, you can also pass one of these string values: Music, Pictures, Videos, Documents. + * @param options The set of properties and values to apply to the new StorageDataSource. Properties on this object may include: mode , requestedThumbnailSize , thumbnailOptions , synchronous . + **/ + constructor(query: any, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Draws the thumbnail for the specified item to the specified img element. + * @param item The item to retrieve the thumbnail for. + * @param image The img element that will display the thumbnail. + * @returns A Promise that completes when the full-quality thumbnail is visible. + **/ + loadThumbnail(item: IItem, image: HTMLImageElement): Promise; + + //#endregion Methods + + } + + /** + * Prevents a DOM sub-tree from receiving tab navigations and focus. + **/ + class TabContainer { + //#region Constructors + + /** + * Creates a new TabContainer. + * @constructor + * @param element The DOM element that hosts the TabContainer control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this TabContainer. Call this method when the TabContainer is no longer needed. After calling this method, the TabContainer becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the child DOM element that receives tab focus. + **/ + childFocus: HTMLElement; + + /** + * Gets or sets the tab index of this container. + **/ + tabIndex: number; + + //#endregion Properties + + } + + /** + * Allows users to select time values. + **/ + class TimePicker { + //#region Constructors + + /** + * Initializes a new instance of a TimePicker control. + * @constructor + * @param element The DOM element associated with the TimePicker control. + * @param options The set of options to be applied initially to the TimePicker control. The options are the following: clock. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when any of the controls are changed by the user. + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener. + * @param type The type (name) of the event. + * @param listener The function that handles the event. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this TimePicker. Call this method when the TimePicker is no longer needed. After calling this method, the TimePicker becomes unusable. + **/ + dispose(): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes a listener for the specified event. + * @param type The name of the event for which to remove a listener. + * @param listener The listener. + * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. + **/ + removeEventListener(type: string, listener: Function, useCapture?: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the type of clock to display (12HourClock or 24HourClock). It defaults to the user setting. + **/ + clock: string; + + /** + * Gets or sets the current time of the TimePicker. Note that the date value is always July 15, 2011. + **/ + current: Date; + + /** + * Specifies whether the TimePicker is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element for the TimePicker. + **/ + element: HTMLElement; + + /** + * Gets or sets the display pattern for the hour. The default hour pattern is hour.integer(2). You can change the hour pattern by changing the number of integers displayed. + **/ + hourPattern: string; + + /** + * Gets or sets the minute increment. For example, 15 specifies that the TimePicker minute control should display only the choices 00, 15, 30, 45. + **/ + minuteIncrement: number; + + /** + * Gets or sets the display pattern for the minute. The default minute pattern is minute.integer(2). You can change the minute pattern by changing the number of integers displayed. + **/ + minutePattern: string; + + /** + * Gets or sets the display pattern for the period. The default period pattern is period.abbreviated(2). You can change the period pattern by changing the number of integers displayed. + **/ + periodPattern: string; + + //#endregion Properties + + } + + /** + * A control that lets the user switch an option between two states: on (checked is set to true) and off (checked is set to false). + **/ + class ToggleSwitch { + //#region Constructors + + /** + * Creates a new ToggleSwitch. + * @constructor + * @param element The DOM that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the change event, add a property named "onchange" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ToggleSwitch control is flipped to on (checked == true) or off (checked == false). + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this ToggleSwitch. Call this method when the ToggleSwitch is no longer needed. After calling this method, the ToggleSwitch becomes unusable. + **/ + dispose(): void; + + /** + * Handles the specified event. + * @param event The event. + **/ + handleEvent(event: any): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the control is on or off. + **/ + checked: boolean; + + /** + * Gets or sets a value that specifies whether the control is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the ToggleSwitch. + **/ + element: HTMLElement; + + /** + * Gets or sets the text that displays when the ToggleSwitch is off (checked is set to false). + **/ + labelOff: string; + + /** + * Gets or sets the text that displays when the ToggleSwitch is on (checked is set to true). + **/ + labelOn: string; + + /** + * Gets or sets the main text for the ToggleSwitch control. This text is always displayed, regardless of whether the control is switched on or off. + **/ + title: string; + + //#endregion Properties + + } + + /** + * Displays a tooltip that can contain images and formatting. + **/ + class Tooltip { + //#region Constructors + + /** + * Creates a new Tooltip. + * @constructor + * @param element The DOM element associated that hosts the Tooltip. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the opened event, add a property named "onopened" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised just before the Tooltip is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeclose(eventInfo: CustomEvent): void; + + /** + * Raised just before the Tooltip appears. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeopen(eventInfo: CustomEvent): void; + + /** + * Raised when the Tooltip is no longer displayed. + * @param eventInfo An object that contains information about the event. + **/ + onclosed(eventInfo: CustomEvent): void; + + /** + * Raised when the Tooltip is shown. + * @param eventInfo An object that contains information about the event. + **/ + onopened(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Hides the Tooltip. + **/ + close(): void; + + /** + * Releases resources held by this Tooltip. Call this method when the Tooltip is no longer needed. After calling this method, the Tooltip becomes unusable. + **/ + dispose(): void; + + /** + * Shows the Tooltip. + * @param type A value that specifies when to show the Tooltip. The default value is "mousedown". + **/ + open(type?: string): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the HTML element that is the content of the Tooltip. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts the Tooltip control. + **/ + element: HTMLElement; + + /** + * Gets or appends additional CSS classes to apply to the element that hosts the Tooltip. + **/ + extraClass: string; + + /** + * Gets or sets a value that specifies whether the Tooltip is an infotip, a tooltip that contains a lot of info and should be displayed for longer than a typical Tooltip. + **/ + infotip: boolean; + + /** + * Gets or sets the HTML content of the Tooltip. + **/ + innerHTML: string; + + /** + * Gets or sets the position for the Tooltip relative to its target element: top, bottom, left or right. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Scales a single child element to fill the available space without resizing it. This control reacts to changes in the size of the container as well as changes in size of the child element. For example, a media query may result in a change in aspect ratio. + **/ + class ViewBox { + //#region Constructors + + /** + * Initializes a new instance of the ViewBox control. + * @constructor + * @param element The DOM element that functions as the scaling box. This element fills 100% of the width and height allotted to it. + * @param options The set of options to be applied initially to the ViewBox control. There are currently no options on this control, and any options included in this parameter are ignored. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this ViewBox. Call this method when the ViewBox is no longer needed. After calling this method, the ViewBox becomes unusable. + **/ + dispose(): void; + + /** + * Forces the ViewBox to update its layout. Use this function when making the ViewBox visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that functions as the scaling box. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + /** + * Serves as the base class for a custom IListDataSource. + **/ + class VirtualizedDataSource { + //#region Constructors + + /** + * Initializes the VirtualizedDataSource base class of a custom data source. + * @constructor + * @param listDataAdapter The object that supplies data to the VirtualizedDataSource. + * @param options An object that can contain properties that specify additional options for the VirtualizedDataSource. It supports these properties: cacheSize. + **/ + constructor(listDataAdapter: IListDataAdapter, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the status of the VirtualizedDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the VirtualizedDataSource object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onstatuschanged", you specify "statuschanged". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. See the VirtualizedDataSource object page for a list of events. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * Returns a new IListDataSource that adds group information to the items of another IListDataSource. + * @param listDataSource The data source for the individual items to group. + * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. + * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. + * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. + * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + **/ + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + + /** + * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. + **/ + function disableAnimations(): void; + + /** + * Used to enable all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be enabled, as the determination is made based on several factors. + **/ + function enableAnimations(): void; + + /** + * Marks a event handler function as being compatible with declarative processing. + * @param handler The handler to be marked as compatible with declarative processing. + * @returns The handler, marked as compatible with declarative processing. + **/ + function eventHandler(handler: any): any; + + /** + * Asynchronously executes a collection of CSS animations on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements to be animated. This parameter can be expressed in several ways: As the special value "undefined", which means that the animation has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param animation The animation description or an array of animation descriptions to apply to element. An animation description is a JavaScript object with specific properties, listed below. There are two types of animation descriptions: one for keyframe-based animations and one for explicit animations. These types are distinguished by whether the keyframe property has a defined value. The following properties are required for both types of animation descriptions: property (string), delay (number), duration (number), timing (string). If an animation has a keyframe property with a defined, non-null value, then the animation is a keyframe-based animation. A keyframe-based animation description requires the following property in addition to those mentioned above: keyframe (string). If an animation does not have a keyframe property, or if the value of the property is null or undefined, then the animation is an explicit animation. An explicit animation description requires the following properties in addition to the common properties mentioned above: from, to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise object that completes when the CSS animation is complete. + **/ + function executeAnimation(element: HTMLElement, animation: any): Promise; + + /** + * Asynchronously executes a collection of CSS transitions on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements on which to perform the transition. This parameter can be expressed in several ways: As the special value "undefined", which means that the transition has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param transition The transition description or an array of transition descriptions to apply to element. A transition description is a JavaScript object with these properties: property (string), delay (number), duration (number), timing (string), from (optional), to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise that completes when the transition is finished. + **/ + function executeTransition(element: HTMLElement, transition: any): Promise; + + /** + * Retrieves the items in the specified index range. + * @param dataSource The data source that contains the items to retrieve. + * @param ranges An array of ISelectionRange objects that have firstIndex and lastIndex values. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + function getItemsFromRanges(dataSource: IListDataSource, ranges: ISelectionRange[]): Promise>; + + /** + * Determines whether the Animations Library and ListView animations will be performed if called. + * @returns Returns true if animations will be performed; otherwise false. + **/ + function isAnimationEnabled(): boolean; + + /** + * Applies declarative control binding to all elements, starting at the specified root element. + * @param rootElement The element at which to start applying the binding. If this parameter is not specified, the binding is applied to the entire document. + * @param skipRoot If true, the elements to be bound skip the specified root element and include only the children. + * @returns A promise that is fulfilled when binding has been applied to all the controls. + **/ + function processAll(rootElement?: Element, skipRoot?: boolean): Promise; + + /** + * Applies declarative control binding to the specified element. + * @param element The element to bind. + * @returns A promise that is fulfilled after the control is activated. The value of the promise is the control that is attached to element. + **/ + function process(element: Element): Promise; + + /** + * Walks the DOM tree from the given element to the root of the document. Whenever a selector scope is encountered, this method performs a lookup within that scope for the specified selector string. The first matching element is returned. + * @param selector The selector string. + * @param element The element to begin walking to the root of the document from. + * @returns The target element, if found. + **/ + function scopedSelect(selector: string, element: HTMLElement): HTMLElement; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If name of the options property begins with "on", the property value is a function and the control supports addEventListener. setControl calls addEventListener on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + function setOptions(control: any, options?: any): void; + + //#endregion Functions + +} +/** + * Provides functions to load HTML content programmatically. +**/ +declare module WinJS.UI.Fragments { + //#region Functions + + /** + * Starts loading the fragment at the specified location. The returned promise completes when the fragment is ready to be copied. + * @param href The URI that contains the fragment to be copied. + * @returns A promise that is fulfilled when the fragment has been prepared for copying. + **/ + function cache(href: string): Promise; + + /** + * Removes any cached information about the specified fragment. This method does not unload any scripts or styles that are referenced by the fragment. + * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. + **/ + function clearCache(href: string): void; + + /** + * Loads the contents of the specified URI into the specified element without copying it. + * @param href The URI that contains the fragment to copy. + * @param element Optional. The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The element is not added to the cache. See also rendercopy, where the element is added to the cache. + **/ + function render(href: string, element?: HTMLElement): Promise; + + /** + * Loads and copies the contents of the specified URI into the specified element. + * @param href The URI that contains the fragment to copy. + * @param target The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. + **/ + function renderCopy(href: string, target?: HTMLElement): Promise; + + //#endregion Functions + +} +/** + * Provides methods for defining and displaying PageControl objects. +**/ +declare module WinJS.UI.Pages { + //#region Interfaces + + /** + * Provides members for a PageControl. You implement this interface when defining a new PageControl. + **/ + interface IPageControlMembers { + //#region Methods + + /** + * Called if any error occurs during the processing of the page. + * @param err The error that occurred. + * @returns Nothing if the error was handled, or an error promise if the error was not handled. + **/ + error? (err: any): Promise; + + /** + * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + init? (element: HTMLElement, options: any): Promise; + + /** + * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. + * @param uri The URI from which to create DOM objects. + * @returns A promise whose fulfilled value is the set of unparented DOM objects. + **/ + load? (uri: string): Promise; + + /** + * Initializes the control after the content of the control is set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options that are to be passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + processed? (element: HTMLElement, options: any): Promise; + + /** + * Called after all initialization and rendering is complete. At this time, the element is ready for use. + * @param element The DOM element that contains all the content for the page. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. + **/ + ready? (element: HTMLElement, options: any): Promise; + + /** + * Takes the elements returned by the load method and attaches them to the specified element. + * @param element The DOM element to which the loadResult elements are appended. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param loadResult A Promise that contains the elements returned from the load method. + **/ + render? (element: HTMLElement, options: any, loadResult: Promise): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. + **/ + class PageControl { + } + + //#endregion Objects + + //#region Functions + + /** + * Creates a new PageControl from the specified URI that contains the specified members. Multiple calls to this method for the same URI are allowed, and all members will be merged. + * @param uri The URI for the content that defines the page. + * @param members An object that defines the members that the control will have. + * @returns A constructor function that creates the PageControl. + **/ + function define(uri: string, members: IPageControlMembers): PageControl; + + /** + * Gets an already-defined page control for the specified URI, or creates a new one. + * @param uri The URI for the content that defines the page. + * @returns A constructor function that creates the page. + **/ + function get(uri: string): Function; + + /** + * Creates a PageControl from the specified URI and inserts it inside the specified element. + * @param uri The URI for the content that defines the page. + * @param element The DOM element to which the PageControl is appended. + * @param options An object that contains one or more property/value pairs to apply to the new PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. + * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + + //#endregion Functions + +} +/** + * Provides methods for detecting when the user tabs to or from DOM elements. +**/ +declare module WinJS.UI.TrackTabBehavior { + //#region Functions + + /** + * Sets the tab order for the specified element within its container. + * @param element The element to update. + * @param tabIndex The index value of the element within its container. + **/ + function attach(element: HTMLElement, tabIndex: number): void; + + /** + * Removes the tab order information from the specified element. + * @param element The element to remove tab information from. + **/ + function detatch(element: HTMLElement): void; + + //#endregion Functions + +} +/** + * Provides helper functions, for example, functions to add and remove CSS classes. +**/ +declare module WinJS.Utilities { + //#region Enumerations + + /** + * Defines a set of keyboard values. + **/ + enum Key { + /** + * The BACKSPACE key. + **/ + backspace, + /** + * The TAB key. + **/ + tab, + /** + * The ENTER key. + **/ + enter, + /** + * The SHIFT key. + **/ + shift, + /** + * The CTRL key. + **/ + ctrl, + /** + * The ALT key. + **/ + alt, + /** + * The PAUSE key. + **/ + pause, + /** + * The CAPS LOCK key. + **/ + capsLock, + /** + * The ESCAPE key. + **/ + escape, + /** + * The SPACE key. + **/ + space, + /** + * The PAGE UP key. + **/ + pageUp, + /** + * The PAGE DOWN key. + **/ + pageDown, + /** + * The END key. + **/ + end, + /** + * The HOME key. + **/ + home, + /** + * The LEFT ARROW key. + **/ + leftArrow, + /** + * The UP ARROW key. + **/ + upArrow, + /** + * The RIGHT ARROW key. + **/ + rightArrow, + /** + * The DOWN ARROW key. + **/ + downArrow, + /** + * The INSERT key. + **/ + insert, + /** + * The DELETE key. + **/ + deleteKey, + /** + * The 0 key. + **/ + num0, + /** + * The 1 key. + **/ + num1, + /** + * The 2 key. + **/ + num2, + /** + * The 3 key. + **/ + num3, + /** + * The 4 key. + **/ + num4, + /** + * The 5 key. + **/ + num5, + /** + * The 6 key. + **/ + num6, + /** + * The 7 key. + **/ + num7, + /** + * The 8 key. + **/ + num8, + /** + * The 9 key. + **/ + num9, + /** + * The a key. + **/ + a, + /** + * The b key. + **/ + b, + /** + * The c key. + **/ + c, + /** + * The d key. + **/ + d, + /** + * The e key. + **/ + e, + /** + * The f key. + **/ + f, + /** + * The g key. + **/ + g, + /** + * The h key. + **/ + h, + /** + * The i key. + **/ + i, + /** + * The j key. + **/ + j, + /** + * The k key. + **/ + k, + /** + * The l key. + **/ + l, + /** + * The m key. + **/ + m, + /** + * The n key. + **/ + n, + /** + * The o key. + **/ + o, + /** + * The p key. + **/ + p, + /** + * The q key. + **/ + q, + /** + * The r key. + **/ + r, + /** + * The s key. + **/ + s, + /** + * The t key. + **/ + t, + /** + * The u key. + **/ + u, + /** + * The v key. + **/ + v, + /** + * The w key. + **/ + w, + /** + * The x key. + **/ + x, + /** + * The y key. + **/ + y, + /** + * The z key. + **/ + z, + /** + * The left Windows key. + **/ + leftWindows, + /** + * The right Windows key. + **/ + rightWindows, + /** + * The menu key. + **/ + menu, + /** + * The 0 key on the numerical keypad. + **/ + numPad0, + /** + * The 1 key on the numerical keypad. + **/ + numPad1, + /** + * The 2 key on the numerical keypad. + **/ + numPad2, + /** + * The 3 key on the numerical keypad. + **/ + numPad3, + /** + * The 4 key on the numerical keypad. + **/ + numPad4, + /** + * The 5 key on the numerical keypad. + **/ + numPad5, + /** + * The 6 key on the numerical keypad. + **/ + numPad6, + /** + * The 7 key on the numerical keypad. + **/ + numPad7, + /** + * The 8 key on the numerical keypad. + **/ + numPad8, + /** + * The 9 key on the numerical keypad. + **/ + numPad9, + /** + * The multiplication key (*). + **/ + multiply, + /** + * The addition key (+). + **/ + add, + /** + * The subtraction key (-). + **/ + subtract, + /** + * The decimal point key (.) + **/ + decimalPoint, + /** + * The division key (/). + **/ + divide, + /** + * The F1 key. + **/ + F1, + /** + * The F2 key. + **/ + F2, + /** + * The F3 key. + **/ + F3, + /** + * The F4 key. + **/ + F4, + /** + * The F5 key. + **/ + F5, + /** + * The F6 key. + **/ + F6, + /** + * The F7 key. + **/ + F7, + /** + * The F8 key. + **/ + F8, + /** + * The F9 key. + **/ + F9, + /** + * The F10 key. + **/ + F10, + /** + * The F11 key. + **/ + F11, + /** + * The F12 key. + **/ + F12, + /** + * The NUMBER LOCK key. + **/ + numLock, + /** + * The SCROLL LOCK key. + **/ + scrollLock, + /** + * The browser BACK key. + **/ + browserBack, + /** + * The browser FORWARD key. + **/ + browserForward, + /** + * The semicolon key (;). + **/ + semicolon, + /** + * The equals key (=). + **/ + equal, + /** + * The comma key (,). + **/ + comma, + /** + * The dash key (-). + **/ + dash, + /** + * The period key (.). + **/ + period, + /** + * The forward slash key (/). + **/ + forwardSlash, + /** + * The grave accent key (`). + **/ + graveAccent, + /** + * The open bracket key ([). + **/ + openBracket, + /** + * The backslash key (\). + **/ + backSlash, + /** + * The close bracket key (]). + **/ + closeBracket, + /** + * The single quote key ('). + **/ + singleQuote + } + + //#endregion Enumerations + + //#region Objects + + /** + * A mixin that contains event-related functions. + **/ + var eventMixin: { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + }; + + /** + * Represents the result of a query selector, and provides various operations that perform actions over the elements of the collection. + **/ + interface QueryCollection extends Array { + //#region Methods + + /** + * Adds the specified class to all the elements in the collection. + * @param name The name of the class to add. + * @returns This QueryCollection object. + **/ + addClass(name: string): QueryCollection; + + /** + * Creates a QueryCollection that contains the children of the specified parent element. + * @param element The parent element. + * @returns The QueryCollection that contains the children of the element. + **/ + children(element: HTMLElement): QueryCollection; + + /** + * Clears the specified style property for all the elements in the collection. + * @param name The name of the style property to be cleared. + * @returns This QueryCollection object. + **/ + clearStyle(name: string): QueryCollection; + + /** + * Creates controls that are attached to the elements in this QueryCollection, if the ctor parameter is a function, or configures the controls that are attached to the elements in this QueryCollection, if the ctor parameter is an object. + * @param ctor If this parameter is a function, it is a constructor function that is used to create controls to attach to the elements. If it is an object, it is the set of options passed to the controls. + * @param options The options passed to the newly-created controls. + * @returns This QueryCollection object. + **/ + control(ctor: any, options?: any): QueryCollection; + + /** + * Performs an action on each item in the QueryCollection. + * @param callbackFn The action to perform on each item. + * @param thisArg The argument to bind to callbackFn. + * @returns The QueryCollection. + **/ + forEach(callbackFn: (value: T, index: number, array: T[]) => void, thisArg?: any): QueryCollection; + + /** + * Gets an item from the QueryCollection. + * @param index The index of the item to return. + * @returns A single item from the collection. + **/ + get(index: number): T; + + /** + * Gets an attribute value from the first element in the collection. + * @param name The name of the attribute. + * @returns The value of the attribute. + **/ + getAttribute(name: string): any; + + /** + * Determines whether the specified class exists on the first element of the collection. + * @param name The name of the class. + * @returns true if the element has the specified class; otherwise, false. + **/ + hasClass(name: string): boolean; + + /** + * Looks up an element by ID and wraps the result in a QueryCollection. + * @param id The ID of the element. + * @returns A QueryCollection that contains the element, if it is found. + **/ + id(id: string): QueryCollection; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T): void; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T[]): void; + + /** + * Registers the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function to be called when the event occurs. + * @param capture true if capture == true is to be passed to addEventListener; otherwise, false. + **/ + listen(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Executes a query selector on all the elements in the collection and aggregates the result into a QueryCollection. + * @param query The query selector string. + * @returns A QueryCollection object containing the aggregate results of executing the query on all the elements in the collection. + **/ + query(query: any): QueryCollection; + + /** + * Removes the specified class from all the elements in the collection. + * @param name The name of the class to be removed. + * @returns his QueryCollection object. + **/ + removeClass(name: string): QueryCollection; + + /** + * Unregisters the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function. + * @param capture true if capture == true; otherwise, false. + * @returns This QueryCollection object. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): QueryCollection; + + /** + * Sets an attribute value on all the items in the collection. + * @param name The name of the attribute to be set. + * @param value The value of the attribute to be set. + * @returns This QueryCollection object. + **/ + setAttribute(name: string, value: any): QueryCollection; + + /** + * Sets the specified style property for all the elements in the collection. + * @param name The name of the style property. + * @param value The value for the property. + * @returns This QueryCollection object. + **/ + setStyle(name: string, value: any): QueryCollection; + + /** + * Renders a template that is bound to the given data and parented to the elements included in the QueryCollection. If the QueryCollection contains multiple elements, the template is rendered multiple times, once at each element in the QueryCollection per item of data passed. + * @param templateElement The DOM element to which the template control is attached. + * @param data The data to render. If the data is an array (or any other object that has a forEach method) then the template is rendered multiple times, once for each item in the collection. + * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. + * @returns The QueryCollection. + **/ + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + + /** + * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. + * @param name The name of the class to be toggled. + * @returns This QueryCollection object. + **/ + toggleClass(name: string): QueryCollection; + + //#endregion Methods + + } + + /** + * Constructor support for QueryCollection interface + **/ + export var QueryCollection: { + new (items: T[]): QueryCollection; + prototype: QueryCollection; + } + + //#endregion Objects + + //#region Functions + + /** + * Adds the specified class to the specified element. + * @param e The element to which to add the class. + * @param name The name of the class to add. + * @returns The element. + **/ + function addClass(e: T, name: string): T; + + /** + * Gets a collection of elements that are the direct children of the specified element. + * @param element The parent element. + * @returns The collection of children of the element. + **/ + function children(element: HTMLElement): QueryCollection; + + /** + * Converts a CSS positioning string for the specified element to pixels. + * @param element The element. + * @param value The CSS positioning string. + * @returns The number of pixels. + **/ + function convertToPixels(element: HTMLElement, value: string): number; + + /** + * Creates an object that has one event for each name passed to the function. + * @param events A variable list of property names. + * @returns The object with the specified properties. The names of the properties are prefixed with 'on'. + **/ + function createEventProperties(...events: string[]): any; + + /** + * Gets the data value associated with the specified element. + * @param element The element. + * @returns The value associated with the element. + **/ + function data(element: HTMLElement): any; + + /** + * Disposes all first-generation disposable elements that are descendents of the specified element. The specified element itself is not disposed. + * @param element The root element whose sub-tree is to be disposed. + **/ + function disposeSubTree(element: HTMLElement): void; + + /** + * Removes all the child nodes from the specified element. + * @param element The element. + * @returns The element. + **/ + function empty(element: T): T; + + /** + * Determines whether the specified event occurred within the specified element. + * @param element The element. + * @param event The event. + * @returns true if the event occurred within the element; otherwise, false. + **/ + function eventWithinElement(element: HTMLElement, event: Event): boolean; + + /** + * Adds tags and type to a logging message. + * @param message The message to be formatted. + * @param tag The tag(s) to be applied to the message. Multiple tags should be separated by spaces. + * @param type The type of the message. + * @returns The formatted message. + **/ + function formatLog(message: string, tag: string, type: string): string; + + /** + * Gets the height of the content of the specified element. The content height does not include borders or padding. + * @param element The element. + * @returns The content height of the element. + **/ + function getContentHeight(element: HTMLElement): number; + + /** + * Gets the width of the content of the specified element. The content width does not include borders or padding. + * @param element The element. + * @returns The content width of the element. + **/ + function getContentWidth(element: HTMLElement): number; + + /** + * Gets the leaf-level type or namespace specified by the name parameter. + * @param name The name of the member. + * @param root The root to start in. Defaults to the global object. + * @returns The leaf-level type or namespace in the specified parent namespace. + **/ + function getMember(name: string, root?: any): any; + + /** + * Gets the position of the specified element. + * @param element The element. + * @returns An object that contains the left, top, width and height properties of the element. + **/ + function getPosition(element: HTMLElement): IPosition; + + /** + * Gets the left coordinate of the specified element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative left coordinate. + **/ + function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the top coordinate of the element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative top coordinate. + **/ + function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the height of the element, including its margins. + * @param element The element. + * @returns The height of the element including margins. + **/ + function getTotalHeight(element: HTMLElement): number; + + /** + * Gets the width of the element, including margins. + * @param element The element. + * @returns The width of the element including margins. + **/ + function getTotalWidth(element: HTMLElement): number; + + /** + * Determines whether the specified element has the specified class. + * @param e The element. + * @param name The name of the class. + * @returns true if the element has the class, otherwise false. + **/ + function hasClass(e: HTMLElement, name: string): boolean; + + /** + * Returns a collection with zero or one elements matching the specified id. + * @param id The ID of the element (or elements). + * @returns A collection of elements whose id matches the id parameter. + **/ + function id(id: string): QueryCollection; + + /** + * Calls insertAdjacentHTML on the specified element. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text The text to insert. + **/ + function insertAdjacentHTML(element: HTMLElement, position: string, text: string): void; + + /** + * Calls insertAdjacentHTML on the specified element in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text Value to be provided to insertAdjacentHTML. + **/ + function insertAdjacentHTMLUnsafe(element: HTMLElement, position: string, text: string): void; + + /** + * Attaches the default dispose API wrapping the dispose implementation to the specified element. + * @param element The element to mark as disposable. + * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. + **/ + function markDisposable(element: HTMLElement, disposeImpl: Function): void; + + /** + * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. + * @param func The function to be marked as compatible with declarative processing. + * @returns The input function, marked as compatible with declarative processing. + **/ + function markSupportedForProcessing(func: U): U; + + /** + * Returns a QueryCollection with zero or one elements matching the specified selector query. + * @param query The CSS selector to use. See Selectors for more information. + * @param element Optional. The root element at which to start the query. If this parameter is omitted, the scope of the query is the entire document. + * @returns A QueryCollection with zero or one elements matching the specified selector query. + **/ + function query(query: any, element?: HTMLElement): QueryCollection; + + /** + * Ensures that the specified function executes only after the DOMContentLoaded event has fired for the current page. The DOMContentLoaded event occurs after the page has been parsed but before all the resources are loaded. + * @param callback A function that executes after the DOMContentLoaded event has occurred. + * @param async If true, the callback should be executed asynchronously. + * @returns A promise that completes after the DOMContentLoaded event has occurred. + **/ + function ready(callback?: Function, async?: boolean): Promise; + + /** + * Removes the specified class from the specified element. + * @param e The element from which to remove the class. + * @param name The name of the class to remove. + * @returns The element. + **/ + function removeClass(e: T, name: string): T; + + /** + * Asserts that the value is compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. If the value is not compatible, and strictProcessing is on, an exception is thrown. All functions that have been declared using WinJS.Class.define, WinJS.Class.derive, WinJS.UI.Pages.define, or WinJS.Binding.converter are automatically marked as supported for declarative processing. Any other function that you use from a declarative context (that is, a context in which an HTML element has a data-win-control or data-win-options attribute) must be marked manually by calling this function. When you mark a function as supported for declarative processing, you are guaranteeing that the code in the function is secure from injection of third-party content. + * @param value The value to be tested for compatibility with declarative processing. If the value is a function it must be marked with a property supportedForProcessing with a value of true when strictProcessing is on. For more information, see WinJS.Utilities.markSupportedForProcessing. + * @returns The input value. + **/ + function requireSupportedForProcessing(value: T): T; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTML(element: HTMLElement, text: string): void; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTML(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Configures a logger that writes messages containing the specified tags to the JavaScript console. + * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. + **/ + function startLog(options?: ILogOptions): void; + + /** + * Removes the WinJS logger that had previously been set up. + **/ + function stopLog(): void; + + /** + * Toggles (adds or removes) the specified class on the specified element. If the class is present, it is removed; if it is absent, it is added. + * @param e The element on which to toggle the class. + * @param name The name of the class to toggle. + * @returns The element. + **/ + function toggleClass(e: T, name: string): T; + + //#endregion Functions + + //#region Properties + + /** + * Gets whether the current script context has access to WinRT APIs. + **/ + var hasWinRT: boolean; + + //#endregion Properties + + //#region Interfaces + + interface ILogOptions { + type: string; + action?: (message: string, tags: string, type: string) => void; + excludeTags: string; + tags: string; + } + + interface IPosition { + left: number; + top: number; + width: number; + height: number; + } + + //#endregion Interfaces + +} +/** + * Provides functions and objects for scheduling and managing asynchronous tasks. +**/ +declare module WinJS.Utilities.Scheduler { + //#region Enumerations + + /** + * Represents a priority for a job managed by the Scheduler. + **/ + enum Priority { + /** + * A priority higher than the normal priority level. + **/ + aboveNormal, + /** + * A priority less than the normal priority level. + **/ + belowNormal, + /** + * A high priority. + **/ + high, + /** + * The idle priority for work items. + **/ + idle, + /** + * The highest priority. + **/ + max, + /** + * The lowest priority. + **/ + min, + /** + * The normal priority for work items. + **/ + normal + } + + //#endregion Enumerations + + //#region Interfaces + + /** + * Represents a work item that's executed by the Scheduler. + **/ + interface IJob { + //#region Methods + + /** + * Cancels the job. + **/ + cancel(): void; + + /** + * Pauses the job. + **/ + pause(): void; + + /** + * Resumes the job. + **/ + resume(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets a value that indicates whether the job has successfully completed. + **/ + completed: boolean; + + /** + * Gets the unique numeric identifier assigned to the job. + **/ + id: number; + + /** + * Gets or sets the name of the job. + **/ + name: string; + + /** + * Gets or sets the owner of the job. + **/ + owner: IOwnerToken; + + /** + * Gets or sets the priority of the job. + **/ + priority: Priority; + + //#endregion Properties + + } + + /** + * Provides a control mechanism that allows a job to cooperatively yield. This object is passed to your work function when you schedule it. + **/ + interface IJobInfo { + //#region Methods + + /** + * Uses a Promise to determine how long the scheduler should wait before rescheduling the job after it yields. + * @param promise Once the work item yields, the scheduler will wait for this Promise to complete before rescheduling the job. + **/ + setPromise(promise: Promise): void; + + /** + * Specifies the next unit of work to run once this job yields. + * @param work The next unit of work to run once this job yields. + **/ + setWork(work: Function): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the work item associated with this IJobInfo. + **/ + job: IJob; + + /** + * Gets a value that specifies whether the job should yield. + **/ + shouldYield: boolean; + + //#endregion Properties + + } + + /** + * Represents an object that owns jobs. You can use this object to cancel a set of jobs. + **/ + interface IOwnerToken { + //#region Methods + + /** + * Synchronously cancels the job that this token owns, including paused and blocked jobs. + **/ + cancelAll(): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Functions + + /** + * Creates and returns a new IOwnerToken which can be set to the owner property of one or more jobs. + * @returns A new IOwnerToken which can be set to the owner property of one or more jobs. + **/ + function createOwnerToken(): IOwnerToken; + + /** + * Runs the specified callback in a high priority context. + * @param callback The callback to run in a high priority callback. + * @returns The return value of the callback. + **/ + function execHigh(callback: () => U): U; + + /** + * Returns a string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. + * @returns A string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. + **/ + function retrieveState(): string; + + /** + * Runs jobs in the scheduler without timeslicing until all jobs at the specified priority and higher have executed. + * @param priority The priority to which the scheduler should drain. The default is -15. + * @param name An optional description of the drain request for diagnostics. + * @returns A Promise which completes when the drain has finished. Canceling this Promise cancels the drain request. This Promise will never enter an error state. + **/ + function requestDrain(priority?: Priority, name?: string): Promise; + + /** + * Schedules the specified function to execute asynchronously. + * @param work A function that represents the work item to be scheduled. When called the work item will receive as its first argument an object which allows the work item to ask the scheduler if it should yield cooperatively and if so allows the work item to either provide a function to be run as a continuation or a WinJS.Promise which will when complete provide a function to run as a continuation. Provide these fields for the object: shouldYield, setWork(work), setPromise(promise), job. + * @param priority The priority of the work item. If you don't specify a priority, it defaults to WinJS.Utilities.Scheduler.Priority.normal. + * @param thisArg A "this" instance to be bound to the work item. The default value is null. + * @param name A description of the work item for diagnostics. The default value is an empty string. + * @returns The job instance that represents this work item. + **/ + function schedule(work: (jobInfo: IJobInfo) => any, priority?: Priority, thisArg?: any, name?: string): IJob; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.aboveNormal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of aboveNormal priority. + **/ + function schedulePromiseAboveNormal(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.belowNormal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of belowNormal priority. + **/ + function schedulePromiseBelowNormal(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.high priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of high priority. + **/ + function schedulePromiseHigh(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.Idle priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of idle priority. + **/ + function schedulePromiseIdle(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.normal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of normal priority. + **/ + function schedulePromiseNormal(promiseValue?: U, jobName?: string): Promise; + + //#endregion Functions + +} diff --git a/winjs/winjs-2.1.d.ts b/winjs/winjs-2.1.d.ts new file mode 100644 index 0000000000..66afeb69ef --- /dev/null +++ b/winjs/winjs-2.1.d.ts @@ -0,0 +1,7000 @@ +// Type definitions for WinJS +// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* ***************************************************************************** +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. +***************************************************************************** */ + +/** + * Defines an Element object. +**/ +interface Element { + winControl: any; // TODO: This should be control? +} + +/** + * Utility class for easy access to operations on application folders +**/ +interface IOHelper { + /** + * Determines whether the specified file exists in the folder. + * @param filename The name of the file. + * @returns A promise that completes with a value of either true (if the file exists) or false. + **/ + exists(filename: string): WinJS.Promise; + + /** + * Reads the specified file. If the file doesn't exist, the specified default value is returned. + * @param fileName The file to read from. + * @param def The default value to be returned if the file failed to open. + * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. + **/ + readText(fileName: string, def?: string): WinJS.Promise; + + /** + * Deletes a file from the folder. + * @param fileName The file to be deleted. + * @returns A promise that is fulfilled when the file has been deleted. + **/ + remove(fileName: string): WinJS.Promise; + + /** + * Writes the specified text to the specified file. + * @param fileName The name of the file. + * @param text The content to be written to the file. + * @returns A promise that completes with a value that is the number of characters written. + **/ + writeText(fileName: string, text: string): WinJS.Promise; +} + +/** + * Provides application-level functionality, for example activation, storage, and application events. +**/ +declare module WinJS.Application { + //#region Objects + + /** + * The local storage of the application. + **/ + var local: IOHelper; + + /** + * The roaming storage of the application. + **/ + var roaming: IOHelper; + + /** + * The temp storage of the application. + **/ + var temp: IOHelper; + + /** + * An object used for storing app information that can be used to restore the app's state after it has been suspended and then resumed. Data that can usefully be contained in this object includes the current navigation page or any information the user has added to the input controls on the page. You should not add information about customization (for example colors) or user-defined lists of content. + **/ + var sessionState: any; + + //#endregion Objects + + //#region Methods + + /** + * Informs the application object that asynchronous work is being performed, and that this event handler should not be considered complete until the promise completes. This function can be set inside the handlers for all WinJS.Application events: onactivated oncheckpoint onerror onloaded onready onsettings onunload. + * @param promise The promise that should complete before processing is complete. + **/ + function setPromise(promise: Promise): void; + + //#endregion Methods + + //#region Functions + + /** + * Adds an event listener for application-level events: activated, checkpoint, error, loaded, ready, settings, and unload. + * @param type The type (name) of the event. You can use any of the following:"activated", "checkpoint", "error", "loaded", "ready", "settings", and" unload". + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + function addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Queues a checkpoint event. + **/ + function checkpoint(): void; + + /** + * Queues an event to be processed by the WinJS.Application event queue. + * @param eventRecord The event object is expected to have a type property that is used as the event name when dispatching on the WinJS.Application event queue. The entire object is provided to event listeners in the detail property of the event. + **/ + function queueEvent(eventRecord: any): void; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: any): void; + + /** + * Starts dispatching application events (the activated, checkpoint, error, loaded, ready, settings, and unload events). + **/ + function start(): void; + + /** + * Stops application event processing and resets WinJS.Application to its initial state. All WinJS.Application event listeners (for the activated, checkpoint, error, loaded, ready, settings, and unload events) are removed. + **/ + function stop(): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs when WinRT activation has occurred. The name of this event is "activated" (and also "mainwindowactivated"). This event occurs after the loaded event and before the ready event. + * @param eventInfo An object that contains information about the event. For more information about event arguments, see the WinRT event argument classes: WebUICachedFileUpdaterActivatedEventArgs, WebUICameraSettingsActivatedEventArgs, WebUIContactPickerActivatedEventArgs, WebUIDeviceActivatedEventArgs, WebUIFileActivatedEventArgs, WebUIFileOpenPickerActivatedEventArgs, WebUIFileSavePickerActivatedEventArgs, WebUILaunchActivatedEventArgs, WebUIPrintTaskSettingsActivatedEventArgs, WebUIProtocolActivatedEventArgs, WebUISearchActivatedEventArgs, WebUIShareTargetActivatedEventArgs. + **/ + function onactivated(eventInfo: CustomEvent): void; + + /** + * Raised when the users clicks the backbutton on a Windows Phone. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type + **/ + function onbackclick(eventInfo: CustomEvent): void; + + /** + * Occurs when receiving PLM notification or when the checkpoint function is called. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function oncheckpoint(eventInfo: CustomEvent): void; + + /** + * Occurs when an unhandled error has been raised. + * @param eventInfo An object that contains information about the event. + **/ + function onerror(eventInfo: CustomEvent): void; + + /** + * Occurs after the DOMContentLoaded event, which fires after the page has been parsed but before all the resources are loaded. This event occurs before the activated event and the ready event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function onloaded(eventInfo: CustomEvent): void; + + /** + * Occurs when the application is ready. This event occurs after the loaded event and the activated event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onready(eventInfo: CustomEvent): void; + + /** + * Occurs when the settings charm is invoked. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: type, applicationcommands. + **/ + function onsettings(eventInfo: CustomEvent): void; + + /** + * Occurs when the application is about to be unloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onunload(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides functionality for data and template binding. +**/ +declare module WinJS.Binding { + //#region Properties + + /** + * Determines whether or not binding should automatically set the ID of an element. This property should be set to true in apps that use WinJS (WinJS) binding. + **/ + var optimizeBindingReferences: boolean; + + //#endregion Properties + + //#region Objects + + /** + * Allows you to add bindable properties dynamically. + **/ + var dynamicObservableMixin: { + //#region Methods + + /** + * Adds a property with change notification to this object, including a ECMAScript5 property definition. + * @param name The name of the property to add. + * @param value This object is returned. + **/ + addProperty(name: string, value: any): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Do not instantiate. A list returned by the createFiltered method. + **/ + class FilteredListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. A list of groups. + **/ + class GroupsListProjection extends ListBase { + //#region Methods + + /** + * Gets a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. Sorts the underlying list by group key and within a group respects the position of the item in the underlying list. Returned by createGrouped. + **/ + class GroupedSortedListProjection extends SortedListProjection { + //#region Properties + + /** + * Gets a List, which is a projection of the groups that were identified in this list. + **/ + groups: GroupsListProjection; + + //#endregion Properties + + } + + /** + * Represents a list of objects that can be accessed by index or by a string key. Provides methods to search, sort, filter, and manipulate the data. + **/ + class List extends ListBaseWithMutators { + //#region Constructors + + /** + * Creates a List object. + * @constructor + * @param list The array containing the elements to initalize the list. + * @param options You can set two Boolean options: binding and proxy. If options.binding is true, the list contains the result of calling as on the element values. If options.proxy is true, the list specified as the first parameter is used as the storage for the List. This option should be used with care, because uncoordinated edits to the data storage may result in errors. + **/ + constructor(list?: T[], options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Gets a key/data pair for the specified list index. + * @param index The index of value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the list item key specified. + * @param key The key of the value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Gets the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Moves the value at index to the specified position. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Returns a list with the elements reversed. This method reverses the elements of a list object in place. It does not create a new list object during execution. + **/ + reverse(): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + /** + * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. + * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + **/ + sort(sortFunction: (left: T, right: T) => number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list, which is an integer value one higher than the highest element defined in the list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Represents a base class for lists. + **/ + class ListBase { + //#region Events + + /** + * An item in the list has changed its value. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, newItem, newValue, oldItem, oldValue. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * A new item has been inserted into the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * An item has been changed locations in the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * An item has been mutated. This event occurs as a result of calling the notifyMutated method. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmutated(eventInfo: CustomEvent): void; + + /** + * An item has been removed from the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * The list has been refreshed. Any references to items in the list may be incorrect. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. + **/ + onreload(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Returns a new list consisting of a combination of two arrays. + * @param item Additional items to add to the end of the list. + * @returns An array containing the concatenation of the list and any other supplied items. + **/ + concat(...item: T[]): T[]; + + /** + * Creates a live filtered projection over this list. As the list changes, the filtered projection reacts to those changes and may also change. + * @param predicate A function that accepts a single argument. The createFiltered function calls the callback with each element in the list. If the function returns true, that element will be included in the filtered list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A filtered projection over the list. + **/ + createFiltered(predicate: (x: T) => boolean): FilteredListProjection; + + /** + * Creates a live grouped projection over this list. As the list changes, the grouped projection reacts to those changes and may also change. The grouped projection sorts all the elements of the list to be in group-contiguous order. The grouped projection also contains a .groups property, which is a List representing the groups that were found in the list. + * @param groupKey A function that accepts a single argument. The function is called with each element in the list, the function should return a string representing the group containing the element. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param groupData A function that accepts a single argument. The function is called once, on one element per group. It should return the value that should be set as the data of the .groups list element for this group. The data value usually serves as summary or header information for the group. + * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). + * @returns A grouped projection over the list. + **/ + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + + /** + * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. + * @param sorter A function that accepts two arguments. The function is called with elements in the list. It must return one of the following numeric values: negative if the first argument is less than the second, zero if the two arguments are equivalent, positive if the first argument is greater than the second. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A sorted projection over the list. + **/ + createSorted(sorter: (left: T, right: T) => number): SortedListProjection; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Checks whether the specified callback function returns true for all elements in a list. + * @param callback A function that accepts up to three arguments. This function is called for each element in the list until it returns false or the end of the list is reached. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if the callback returns true for all elements in the list. + **/ + every(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Returns the elements of a list that meet the condition specified in a callback function. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the elements that meet the condition specified in the callback function. + **/ + filter(callback: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; + + /** + * Calls the specified callback function for each element in a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. The arguments are as follows: value, index, array. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + **/ + forEach(callback: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + /** + * Gets the value at the specified index. + * @param index The index of the value to get. + * @returns The value at the specified index. + **/ + getAt(index: number): T; + + /** + * Gets the index of the first occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + * @returns The index of the first occurrence of a value in a list or -1 if not found. + **/ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns a string consisting of all the elements of a list separated by the specified separator string. + * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. + * @returns The elements of a list separated by the specified separator string. + **/ + join(separator: string): string; + + /** + * Gets the index of the last occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. + * @returns The index of the last occurrence of a value in a list, or -1 if not found. + **/ + lastIndexOf(searchElement: T, fromIndex: number): number; + + /** + * Calls the specified callback function on each element of a list, and returns an array that contains the results. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. + * @param thisArg n object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the result of calling the callback function on each element in the list. + **/ + map(callback: (value: T, index: number, array: T[]) => G, thisArg?: any): G[]; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Forces the list to send a reload notification to any listeners. + **/ + notifyReload(): void; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initiallValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the function provides this value as an argument instead of a list value. + * @returns The return value from the last call to the callback function. + **/ + reduce(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initiallValue?: T): T; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list, starting with the last member of the list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initialValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the callback function provides this value as an argument instead of a list value. + * @returns The return value from the last call to callback function. + **/ + reduceRight(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initialValue?: T): T; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Extracts a section of a list and returns a new list. + * @param begin The index that specifies the beginning of the section. + * @param end The index that specifies the end of the section. + * @returns Returns a section of list. + **/ + slice(begin: number, end: number): T[]; + + /** + * Checks whether the specified callback function returns true for any element of a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list until it returns true, or until the end of the list. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if callback returns true for any element in the list. + **/ + some(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + //#region Properties + + /** + * Gets the IListDataSource for the list. The only purpose of this property is to adapt a List to the data model that is used by ListView and FlipView. + **/ + dataSource: WinJS.UI.IListDataSource; + + /** + * Indicates that the object is compatibile with declarative processing. + **/ + static supportedForProcessing: boolean; + + //#endregion Properties + } + + /** + * Represents a base class for normal list modifying operations. + **/ + class ListBaseWithMutators extends ListBase { + //#region Methods + + /** + * Removes the last element from a list and returns it. + * @returns The last element from the list. + **/ + pop(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the end of the list. + * @returns The new length of the list. + **/ + push(value: T): number; + + /** + * Removes the first element from a list and returns it. + * @returns The first element from the list. + **/ + shift(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the start of the list. + * @returns The new length of the list. + **/ + unshift(value: T): number; + + //#endregion Methods + } + + /** + * Represents a base class for list projections. + **/ + class ListProjection extends ListBaseWithMutators { + //#region Methods + + /** + * Disconnects a WinJS.Binding.List projection from its underlying WinJS.Binding.List. It's only important to call this method when the WinJS.Binding.List projection and the WinJS.Binding.List have different lifetimes. (Call this method on the WinJS.Binding.List projection, not the underlying WinJS.Binding.List.) + **/ + dispose(): void; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Moves the value at index to position newIndex. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + } + + /** + * Provides a standard implementation of the bindable contract, as well as a basic storage mechanism that participates in change notification and an asynchronous notification implementation. + **/ + var mixin: { + //#region Methods + + /** + * Adds a property to the object. The property includes change notification and an ECMAScript 5 property definition . + * @param name The name of the property to add. + * @param value The value of the property. + * @returns This object is returned. + **/ + addProperty(name: string, value: any): any; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Provides functions that can make an object observable. + **/ + var observableMixin: { + //#region Methods + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + }; + + /** + * Do not instantiate. Returned by the createSorted method. + **/ + class SortedListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value to be replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list. Returns an integer value one higher than the highest element defined in a list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Provides a reusable declarative binding element. + **/ + class Template { + //#region Constructors + + /** + * Creates a template that provides a reusable declarative binding element. + * @constructor + * @param element The DOM element to convert to a template. + * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. + **/ + constructor(element: HTMLElement, options?: string); + + //#endregion Constructors + + //#region Methods + + render: { + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + (dataContext: any, container?: HTMLElement): Promise; + + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + value(href: string, dataContext: any, container?: HTMLElement): Promise; + }; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default binding initializer for the template. + **/ + bindingInitializer: any; + + /** + * Gets or sets a value that specifies whether a debug break is inserted into the first rendering of each template. This property only has an effect when the app is in debug mode. + **/ + debugBreakOnRender: boolean; + + /** + * This property is deprecated and might not be available in future versions of the WinJS. Gets or sets a value that specifies whether optimized template processing has been disabled. + **/ + disableOptimizedProcessing: boolean; + + /** + * Gets the DOM element that is used as the template. + **/ + element: HTMLElement; + + /** + * Gets a value that specifies whether templates should be instantiated without the creation of an additional child element. + **/ + extractChild: boolean; + + /** + * Determines whether the Template contains declarative controls that must be processed separately. This property is always true. The controls that belong to a Template object's children are instantiated when a Template instance is rendered. + **/ + isDeclarativeControlContainer: boolean; + + //#endregion Properties + + } + + //#endregion Objects + + //#region Functions + + /** + * Adds a CSS class from the specified path of the source object to a destination object. + * @param source The source object that has the class to copy. + * @param sourceProperties The path on the source object to the source class. + * @param dest The destination object. + **/ + function addClassOneTime(source: any, sourceProperties: any[], dest: HTMLElement): void; + + /** + * Returns an observable object. This may be an observable proxy for the specified object, an existing proxy, or the specified object itself if it directly supports observation. + * @param data The object to observe. + * @returns The observable object. + **/ + function as(data: U): U; + + /** + * Binds to one or more properties on the observable object or or on child values of that object. + * @param observable The object to bind to. + * @param bindingDescriptor An object literal containing the binding declarations. Binding declarations take the form: { propertyName: (function | bindingDeclaration), ... }. + * @returns An object that contains at least a "cancel" field, which is a function that removes all bindings associated with this bind request. + **/ + function bind(observable: any, bindingDescriptor: any): any; + + /** + * Creates a default binding initializer for binding between a source property and a destination property with the specified converter function that is executed on the value of the source property. + * @param convert The conversion function that takes the source property and produces a value that is set to the destination property. This function must be accessible from the global namespace. + * @returns The binding initializer. + **/ + function converter(convert: Function): Function; + + /** + * Creates a one-way binding between the source object and the destination object. Warning Do not attempt to bind data to the ID of an HTML element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function defaultBind(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Creates a new constructor function that supports observability with the specified set of properties. + * @param data The object to use as the pattern for defining the set of properties. + * @returns A constructor function with 1 optional argument that is the initial state of the properties. + **/ + function define(data: any): Function; + + /** + * Wraps the specified object so that all its properties are instrumented for binding. This is meant to be used in conjunction with the binding mixin. + * @param shape The specification for the bindable object. + * @returns An object with a set of properties all of which are wired for binding. + **/ + function expandProperties(shape: any): any; + + /** + * Marks a custom initializer function as being compatible with declarative data binding. + * @param customInitializer The custom initializer to be marked as compatible with declarative data binding. + * @returns The input customInitializer. + **/ + function initializer(customInitializer: Function): Function; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + function notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Sets the destination property to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function oneTime(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Binds the values of an object to the values of a DOM element that has the data-win-bind attribute. If multiple DOM elements are to be bound, you must set the attribute on all of them. See the example below for details. + * @param rootElement Optional. The element at which to start traversing to find elements to bind to. If this parameter is omitted, the entire document is searched. + * @param dataContext The object that contains the values to which the DOM element should be bound. + * @param skipRoot If true, specifies that only the children of rootElement should be bound, otherwise rootElement should be bound as well. + * @param bindingCache The cached binding data. + * @param defaultInitializer The binding initializer to use in the case that one is not specified in a binding expression. If not provided, the behavior is the same as Binding.defaultBind. + * @returns A Promise that completes when every item that contains the data-win-bind attribute has been processed and the update has started. + **/ + function processAll(rootElement?: Element, dataContext?: any, skipRoot?: boolean, bindingCache?: any, defaultInitializer?: Function): Promise; + + /** + * Creates a one-way binding between the source object and an attribute on the destination element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + * @returns An object with a cancel() method that is used to coalesce bindings. + **/ + function setAttribute(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): any; + + /** + * Sets an attribute on the destination element to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + **/ + function setAttributeOneTime(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): void; + + /** + * Returns the original (non-observable) object is returned if the specified object is an observable proxy, + * @param data The object for which to retrieve the original value. + * @returns If the specified object is an observable proxy, the original object is returned, otherwise the same object is returned. + **/ + function unwrap(data: any): any; + + //#endregion Functions + + //#region Interfaces + + interface IKeyDataPair { + key: string; + data: T; + } + + //#endregion Interfaces + +} +/** + * Provides helper functions for defining Classes. +**/ +declare module WinJS.Class { + //#region Functions + + /** + * Defines a class using the given constructor and the specified instance members. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods made available on the type. + * @param staticMembers The set of static fields, properties, and methods made available on the type. + * @returns The newly-defined type. + **/ + function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + + /** + * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. + * @param baseClass The type to inherit from. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods to be made available on the type. + * @param staticMembers The set of static fields, properties, and methods to be made available on the type. + * @returns The newly-defined type. + **/ + function derive(baseClass: any, constructor: Function, instanceMembers?: any, staticMembers?: any): any; + + /** + * Defines a class using the given constructor and the union of the set of instance members specified by all the mixin objects. The mixin parameter list is of variable length. For more information, see Adding functionality with WinJS mixins. + * @param constructor A constructor function that will be used to instantiate this class. + * @param mixin An object declaring the set of instance members. The mixin parameter list is of variable length. + * @returns The newly defined class. + **/ + function mix(constructor: Function, ...mixin: any[]): any; + + //#endregion Functions + +} +/** + * The WinJS namespace provides special Windows Library for JavaScript functionality, including Promise and xhr. +**/ +declare module WinJS { + //#region Properties + + /** + * Can be set to show the results of a validation process. + **/ + var validation: boolean; + + //#endregion Properties + + //#region Objects + + /** + * An error object. + **/ + class ErrorFromName { + //#region Constructors + + /** + * Creates an Error object with the specified name and message properties. + * @constructor + * @param name The name of this error. The name is meant to be consumed programmatically and should not be localized. + * @param message The message for this error. The message is meant to be consumed by humans and should be localized. + **/ + constructor(name: string, message?: string); + + //#endregion Constructors + + } + + /** + * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + **/ + class Promise { + //#region Constructors + + /** + * A promise provides a mechanism to schedule work to be done on a value that has not yet been computed. It is a convenient abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + * @constructor + * @param init The function that is called during construction of the Promise that contains the implementation of the operation that the Promise will represent. This can be synchronous or asynchronous, depending on the nature of the operation. Note that placing code within this function does not automatically run it asynchronously; that must be done explicitly with other asynchronous APIs such as setImmediate, setTimeout, requestAnimationFrame, and the Windows Runtime asynchronous APIs. The init function is given three arguments: completeDispatch, errorDispatch, progressDispatch. This parameter is optional. + * @param onCancel The function to call if a consumer of this promise wants to cancel its undone work. Promises are not required to support cancellation. + **/ + constructor(init?: (completeDispatch: any, errorDispatch: any, progressDispatch: any) => void, onCancel?: Function); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when there is an error in processing a promise. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener for the promise. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Returns a promise that is fulfilled when one of the input promises has been fulfilled. + * @param value An array that contains Promise objects or objects whose property values include Promise objects. + * @returns A promise that on fulfillment yields the value of the input (complete or error). + **/ + static any(value: Promise[]): Promise; + + /** + * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. + * @param value The value to be treated as a Promise. + * @returns The promise. + **/ + static as(value: U): Promise; + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Raises an event of the specified type and properties. + * @param type The type (name) of the event. + * @param details The set of additional properties to be attached to the event object. + * @returns true if preventDefault was called on the event; otherwise, false. + **/ + dispatchEvent(type: string, details: any): boolean; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + + /** + * Determines whether a value fulfills the promise contract. + * @param value A value that may be a promise. + * @returns true if the object conforms to the promise contract (has a then function), otherwise false. + **/ + static is(value: any): boolean; + + /** + * Creates a Promise that is fulfilled when all the values are fulfilled. + * @param values An object whose members contain values, some of which may be promises. + * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. + **/ + static join(values: any): Promise; + + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param capture Specifies whether or not to initiate capture. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + + /** + * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. + * @param values A set of values (which could be either an array or an object) of which some or all are promises.. + * @param complete The function to be called if the promise is fulfilled with a value. This function takes a single argument, which is the fulfilled value of the promise. + * @param error The function to be called if the promise is fulfilled with an error. This function takes a single argument, which is the error value of the promise. + * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. + * @returns A Promise that is the result of calling join on the values parameter. + **/ + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + + /** + * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. + * @param timeout The timeout period in milliseconds. If this value is zero or not specified, msSetImmediate is called, otherwise setTimeout is called. + * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. + * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. + **/ + static timeout(timeout: number, promise?: Promise): Promise; + + /** + * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. + * @param value Some non-promise value to be wrapped in a promise. + * @returns A promise that is successfully fulfilled with the specified value. + **/ + static wrap(value: U): Promise; + + /** + * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. + * @param error A non-promise error value to be wrapped in a promise. + * @returns A promise that is in an error state with the specified value. + **/ + static wrapError(error: U): Promise; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * You can provide an implementation of this method yourself, or use WinJS.Utilities.startLog to create one that logs to the JavaScript console. + * @param message The message to log. + * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). + * @param type The type of message (error, warning, info, etc.). + **/ + function log(message: string, tags: string, type: string): void; + + /** + * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. + **/ + function strictProcessing(): void; + + /** + * Wraps calls to XMLHttpRequest in a promise. + * @param options The options that are applied to the XMLHttpRequest object, as follows: type, url, user, password, responseType, headers, data, customRequestInitializer. + * @returns A promise that returns the XMLHttpRequest object when it completes. + **/ + function xhr(options: IXHROptions): Promise; + + //#endregion Functions + + //#region Interfaces + + interface IXHROptions { + type?: string; + url: string; + user?: string; + password?: string; + headers?: any; + data: any; + responseType?: string; + } + + //#endregion Interfaces +} +/** + * Provides helper functions for defining namespaces. For more information, see Organizing your code with WinJS.Namespace. +**/ +declare module WinJS.Namespace { + //#region Functions + + /** + * Defines a new namespace with the specified name. For more information, see Organizing your code with WinJS.Namespace. + * @param name The name of the namespace. This could be a dot-separated name for nested namespaces. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function define(name?: string, members?: any): any; + + /** + * Defines a new namespace with the specified name under the specified parent namespace. For more information, see Organizing your code with WinJS.Namespace. + * @param parentNamespace The parent namespace. + * @param name The name of the new namespace. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function defineWithParent(parentNamespace?: any, name?: string, members?: any): any; + + //#endregion Functions + +} +/** + * Provides functionality for dealing with basic navigation, including the navigation stack. +**/ +declare module WinJS.Navigation { + //#region Properties + + /** + * Determines whether it is possible to navigate backwards. + **/ + var canGoBack: boolean; + + /** + * Determines if it is possible to navigate forwards. + **/ + var canGoForward: boolean; + + /** + * Gets or sets the navigation history. + **/ + var history: any; + + /** + * Gets or sets the current location. + **/ + var location: string; + + /** + * Gets or sets a user-defined object that represents the state associated with the current location. + **/ + var state: any; + + //#endregion Properties + + //#region Functions + + /** + * Adds an event listener to the control. + * @param eventType The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + function addEventListener(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Navigates backwards. + * @param distance The number of entries to go back into the history. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function back(distance?: number): Promise; + + /** + * Navigates forwards. + * @param distance The number of entries to go forward. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function forward(distance?: number): Promise; + + /** + * Navigates to a location. + * @param location The location to navigate to. Generally the location is a string containing the URL, but it may be anything. + * @param initialState A user-defined object that represents the navigation state that may be accessed through state. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful (true if successful, otherwise false). + **/ + function navigate(location: any, initialState?: any): Promise; + + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(eventType: string, listener: Function, useCapture?: boolean): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs before navigation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onbeforenavigate(eventInfo: CustomEvent): void; + + /** + * Occurs after navigation has taken place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigated(eventInfo: CustomEvent): void; + + /** + * Occurs when navigation is taking place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigating(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides functions for accessing resources and localizing content. +**/ +declare module WinJS.Resources { + //#region Functions + + /** + * Registers an event handler for the specified event. Use this method to register for events that are related to resources, such as when the app's language, scale, or contrast changes. + * @param type The name of the event to handle. + * @param listener The listener (event handler function) to associate with the event. + * @param useCapture Set to true to register the listener for the capturing phase; otherwise, set to false to register the listener for the bubbling phase. + **/ + function addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The name of the event to raise. + * @param details The set of additional properties to attach to the event object. + **/ + function dispatchEvent(type: string, details: any): void; + + /** + * Retrieves the resource string that has the specified resource identifier. + * @param resourceId The resource ID of the string to retrieve. + * @returns An object that can contain these properties: value, empty, lang. + **/ + function getString(resourceId: string): { value: string; empty?: boolean; lang?: string; }; + + /** + * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. + * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. + **/ + function processAll(rootElement?: HTMLElement): void; + + /** + * Removes an event listener that the addEventListener method registered. + * @param type The name of the event that the event listener is registered for. + * @param listener The listener (event handler function) to remove. + * @param useCapture Set to true to remove the capturing phase listener; set to false to remove the bubbling phase listener. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Functions + + //#region Events + + /** + * Occurs when the user changes the system's language or contrast, or the scale of the display, or when the user changes any of the items in the current context's qualifier values list. For more info about the current context's qualifier values list, see the Remarks section. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.qualifier, detail.changed. + **/ + function oncontextchanged(eventInfo: CustomEvent): void; + + //#endregion Events + +} +/** + * Provides access to the Windows animations. These functions provide developers with the ability to use animations in their custom controls that are consistent with animations used by Windows controls. +**/ +declare module WinJS.UI.Animation { + //#region Functions + + /** + * Scales up an incoming page while scaling, rotating (clockwise), and translating an incoming item into place. + * @param incomingPage A single element to be scaled up that is the page root and does not contain the incoming item. + * @param incomingItemRoot The root of the item. This is translated during the continuum animation. + * @param incomingItemContent The content of the item. This is scaled and rotated during the continuum animation. + * @returns An object that returns when the animation has finished. + **/ + function continuumForwardIn(incomingPage: any, incomingItemRoot: any, incomingItemContent: any): Promise; + + /** + * Scales down a page while scaling, rotating (clockwise), and translating an outgoing item. + * @param outgoingPage A single element to be scaled down that is the page root and contains the outgoing item. + * @param outgoingItem A single element to be scaled, rotated, and translated away from the outgoing page. + * @returns An object that returns when the animation has finished. + **/ + function continuumForwardOut(outgoingPage: any, outgoingItem: any): Promise; + + /** + * Scales down an incoming page while scaling, rotating (counterclockwise), and translating an incoming item into place. + * @param incomingPage A single element to be scaled down that is the page root and contains the incoming item. + * @param incomingItem A single element to be scaled, rotated, and translated into its final position on the page. + * @returns An object that returns when the animation has finished. + **/ + function continuumBackwardIn(incomingPage: any, incomingItem: any): Promise; + + /** + * Scales, rotates (counterclockwise), and translates an outgoing page as it is removed. + * @param incomingPage A single element to be scaled down that is the page root. + * @returns An object that returns when the animation has finished. + **/ + function continuumBackwardOut(outgoingPage: any): Promise; + + /** + * Creates an object that performs an animation that adds an item or items to a list. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToListAnimation(added: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that adds an item or items to a list of search results. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToSearchListAnimation(added: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that collapses a list. + * @param hidden Element or elements hidden as a result of the collapse. + * @param affected Element or elements affected by the hidden items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createCollapseAnimation(hidden: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that removes an item or items from a list. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that removes an item or items from a list of search results. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromSearchListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that expands a list. + * @param revealed Element or elements revealed by the expansion. + * @param affected Element or elements affected by the newly revealed items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createExpandAnimation(revealed: any, affected: any): IAnimationMethodResponse; + + /** + * Creates an exit and entrance animation to play for a page navigation given the current and incoming pages' animation preferences and whether the pages are navigating forwards or backwards. + * @param currentPreferredAnimation Describes the animation the current page prefers to use. + * @param nextPreferredAnimation Describes the animation the incoming page prefers to use. + * @param movingBackwards Determines whether the navigation is moving backwards + * @returns An object that contains an exit method used for animating exiting pages and an enter method used for animating entering pages. + **/ + function createPageNavigationAnimation(currentPreferredAnimation: PageNavigationAnimation, nextPreferredAnimation: PageNavigationAnimation, movingBackwards: boolean): { enter: () => any; exit: () => any; }; + + /** + * Creates an object that performs a peek animation. + * @param element Element or elements involved in the peek. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createPeekAnimation(element: any): IAnimationMethodResponse; + + /** + * Creates an object that performs an animation that moves an item or items. + * @param element Element or elements involved in the reposition. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise object that completes when the animation is finished. + **/ + function createRepositionAnimation(element: any): IAnimationMethodResponse; + + /** + * Performs an animation that fades an item or items in, fading out existing items that occupy the same space. + * @param incoming Element or elements being faded in. + * @param outgoing Element or elements being replaced. + * @returns An object that completes when the animation has finished. + **/ + function crossFade(incoming: any, outgoing: any): Promise; + + /** + * Performs an animation when a dragged object is moved such that dropping it in that position would move other items. The potentially affected items are animated out of the way to show where the object would be dropped. + * @param target Element or elements that the dragged object would cause to be moved if it were dropped. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenEnter(target: any, offset: any): Promise; + + /** + * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. + * @param target Element or elements that the dragged object would no longer cause to be displaced, due to its moving away. This should be the same element or element collection passed as the target parameter in the dragBetweenEnter animation. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenLeave(target: any): Promise; + + /** + * Performs an animation when the user finishes dragging an object. + * @param dragSource Element or elements that were dragged. + * @param offset Initial offset from the drop point. The dropped object begins at the offset and animates to its final position at the drop point. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + + /** + * Performs an animation when the user begins to drag an object. + * @param dragSource Element or elements being dragged. + * @param affected Element or elements whose position is affected by the movement of the dragged object. Typically, this is all other items in a reorderable list. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceStart(dragSource: any, affected?: any): Promise; + + /** + * Performs an animation that displays one or more elements on a page. + * @param incoming Element or elements that compose the incoming content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function enterContent(incoming: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. + * @param element Element or an array of elements that represent the content. If element refers to an array of elements, the elements enter in array order. + * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function enterPage(element: any, offset: any): Promise; + + /** + * Performs an animation that hides one or more elements on a page. + * @param outgoing Element or elements that compose the outgoing content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitContent(outgoing: any, offset: any): Promise; + + /** + * Performs an animation that dismisses the current page when transitioning between pages in an app. + * @param outgoing Element or elements that compose the outgoing page. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitPage(outgoing: any, offset: any): Promise; + + /** + * Performs an animation that fades an item or set of items into view. + * @param shown Element or elements being faded in. + * @returns An object that completes when the animation has finished. Use this object when subsequent actions need this animation to finish before they take place. + **/ + function fadeIn(shown: any): Promise; + + /** + * Performs an animation that fades an item or set of items out of view. + * @param hidden Element or elements being faded out. + * @returns An object that completes when the animation is finished. + **/ + function fadeOut(hidden: any): Promise; + + /** + * Performs an animation that hides edge-based user interface (UI). + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function hideEdgeUI(element: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that hides a panel. + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function hidePanel(element: any, offset: any): Promise; + + /** + * Performs an animation that removes pop-up user interface (UI). + * @param element Element or elements that are being hidden. + * @returns An object that completes when the animation is finished. + **/ + function hidePopup(element: any): Promise; + + /** + * Performs an animation when a pointer is pressed on an object. + * @param element Element or elements on which the pointer is pressed. + * @returns An object that completes when the animation is finished. + **/ + function pointerDown(element: any): Promise; + + /** + * Performs an animation when a pointer is released. + * @param element Element or elements that the pointer was pressed on. + * @returns An object that completes when the animation is finished. + **/ + function pointerUp(element: any): Promise; + + /** + * Performs an animation that slides a narrow, edge-based user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function showEdgeUI(element: any, offset: any, options?: any): Promise; + + /** + * Performs an animation that slides a large panel user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPanel(element: any, offset: any): Promise; + + /** + * Performs an animation that displays a pop-up user interface (UI). + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPopup(element: any, offset: any): Promise; + + /** + * Slides elements off through the bottom of the screen. + * @param outgoing Single element or an array of elements that represent the content. If an array of elements, the elements exit in array order. + * @returns An object that completes when the animation is finished. + **/ + function slideDown(outgoing: any): Promise; + + /** + * Slides elements up into view from the bottom of the screen. + * @param incoming Single element or an array of elements that represent the content. If an array of elements, the elements exit in array order. + * @returns An object that completes when the animation is finished. + **/ + function slideUp(outgoing: any): Promise; + + /** + * Slides elements in from the right side of the screen. + * @param page A page that contains all of the elements to slide in. + * @param firstIncomingElements A single element or an array of elements to slide in first. If this is an array of elements, all elements enter at once. + * @param secondIncomingElements A single element or an array of elements to slide in once the firstIncomingElements are in place. If this is an array of elements, all elements enter at once. These elements are offset slightly more than the firstIncomingElements. + * @param thirdIncomingElements A single element or an array of elements to slide in once the secondIncomingElements are in place. If this is an array of elements, all elements enter at once. These elements are offset slightly more than the secondIncomingElements. + * @returns An object that completes when the animation is finished. + **/ + function slideRightIn(page: any, firstIncomingElements: any, secondIncomingElements: any, thirdIncomingElements: any): Promise; + + /** + * Slides elements out through the right side of the screen. + * @param page A page that contains all of the elements to slide out. + * @param firstOutgoingElements A single element or an array of elements to slide out first. If this is an array of elements, the elements exit in array order. + * @param secondOutgoingElements A single element or an array of elements to slide out once the firstOutgoingElements are gone. If this is an array of elements, the elements exit simultaneously. These elements are offset slightly more than the firstOutgoingElements. + * @param thirdOutgoingElements A single element or an array of elements to slide out once the secondOutgoingElements are gone. If this is an array of elements, the elements exit simultaneously. These elements are offset slightly more than the secondOutgoingElements. + * @returns An object that completes when the animation is finished. + **/ + function slideRightOut(page: any, firstOutgoingElements: any, secondOutgoingElements: any, thirdOutgoingElements: any): Promise; + + /** + * Slides elements in from the left side of the screen. + * @param page A page that contains all of the elements to slide in. + * @param firstIncomingElements A single element or an array of elements to slide in first. If this is an array of elements, all elements enter at once. + * @param secondIncomingElements A single element or an array of elements to slide in once the firstIncomingElements are in place. If this is an array of elements, all elements enter at once. These elements are offset slightly more than the firstIncomingElements. + * @param thirdIncomingElements A single element or an array of elements to slide in once the secondIncomingElements are in place. If this is an array of elements, all elements enter at once. These elements are offset slightly more than the secondIncomingElements. + * @returns An object that completes when the animation is finished. + **/ + function slideLeftIn(page: any, firstIncomingElements: any, secondIncomingElements: any, thirdIncomingElements: any): Promise; + + /** + * Slides elements out through the left side of the screen. + * @param page A page that contains all of the elements to slide out. + * @param firstOutgoingElements A single element or an array of elements to slide out first. If this is an array of elements, the elements exit in array order. + * @param secondOutgoingElements A single element or an array of elements to slide out once the firstOutgoingElements are gone. If this is an array of elements, the elements exit simultaneously. These elements are offset slightly more than the firstOutgoingElements. + * @param thirdOutgoingElements A single element or an array of elements to slide out once the secondOutgoingElements are gone. If this is an array of elements, the elements exit simultaneously. These elements are offset slightly more than the secondOutgoingElements. + * @returns An object that completes when the animation is finished. + **/ + function slideLeftOut(page: any, firstOutgoingElements: any, secondOutgoingElements: any, thirdOutgoingElements: any): Promise; + + /** + * Performs a deselection animation in response to a swipe interaction. + * @param deselected Element or elements that become unselected. + * @param selection Element or elements that represent the selection, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeDeselect(deselected: any, selection: any): Promise; + + /** + * Performs an animation that reveals an item or items in response to a swipe interaction. + * @param target Element or elements being revealed. + * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function swipeReveal(target: any, offset: any): Promise; + + /** + * Performs a selection animation in response to a swipe interaction. + * @param selected Element or elements being selected. + * @param selection Element or elements that show that something is selected, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeSelect(selected: any, selection: any): Promise; + + /** + * Rotates an element clockwise onto the page. + * @param incoming Single element or an array of elements that represent the content. If an array of elements, the elements enter in array order.. + * @returns An promise that completes when the animation has finished. + **/ + function turnstileForwardIn(incoming: any): Promise; + + /** + * Rotates an element clockwise off the page. + * @param outgoing Single element or an array of elements that represent the content. If an array of elements, the elements enter in array order.. + * @returns An promise that completes when the animation has finished. + **/ + function turnstileForwardOut(outgoing: any): Promise; + + /** + * Rotates an element counterclockwise onto the page. + * @param incoming Single element or an array of elements that represent the content. If an array of elements, the elements enter in array order.. + * @returns An promise that completes when the animation has finished. + **/ + function turnstileBackwardIn(incoming: any): Promise; + + /** + * Rotates an element counterclockwise off the page. + * @param outgoing Single element or an array of elements that represent the content. If an array of elements, the elements enter in array order.. + * @returns An promise that completes when the animation has finished. + **/ + function turnstileBackwardOut(outgoing: any): Promise; + + + /** + * Performs an animation that updates a badge. + * @param incoming Element or elements that comprise the new badge. + * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function updateBadge(incoming: any, offset: any): Promise; + + //#endregion Functions + + //#region Interfaces + + interface IAnimationMethodResponse { + execute(): Promise; + } + + //#endregion Interfaces + +} +/** + * Provides controls and objects that manipulate data. +**/ +declare module WinJS.UI { + //#region Enumerations + + /** + * Specifies an icon that appears in an AppBarCommand object. + **/ + enum AppBarIcon { + previous, + next, + play, + pause, + edit, + save, + clear, + delete, + remove, + add, + cancel, + accept, + more, + redo, + undo, + home, + up, + forward, + right, + back, + left, + favorite, + camera, + settings, + video, + sync, + download, + mail, + find, + help, + upload, + emoji, + twopage, + leavechat, + mailforward, + clock, + send, + crop, + rotatecamera, + people, + closepane, + openpane, + world, + flag, + previewlink, + globe, + trim, + attachcamera, + zoomin, + bookmarks, + document, + protecteddocument, + page, + bullets, + comment, + mail2, + contactinfo, + hangup, + viewall, + mappin, + phone, + videochat, + switch, + contact, + rename, + pin, + musicinfo, + go, + keyboard, + dockleft, + dockright, + dockbottom, + remote, + refresh, + rotate, + shuffle, + list, + shop, + selectall, + orientation, + import, + importall, + browsephotos, + webcam, + pictures, + savelocal, + caption, + stop, + showresults, + volume, + repair, + message, + page2, + calendarday, + calendarweek, + calendar, + characters, + mailreplyall, + read, + link, + accounts, + showbcc, + hidebcc, + cut, + attach, + paste, + filter, + copy, + emoji2, + important, + mailreply, + slideshow, + sort, + manage, + allapps, + disconnectdrive, + mapdrive, + newwindow, + openwith, + contactpresence, + priority, + uploadskydrive, + gototoday, + font, + fontcolor, + contact2, + folder, + audio, + placeholder, + view, + setlockscreen, + settile, + cc, + stopslideshow, + permissions, + highlight, + disableupdates, + unfavorite, + unpin, + openlocal, + mute, + italic, + underline, + bold, + movetofolder, + likedislike, + dislike, + like, + alignright, + aligncenter, + alignleft, + zoom, + zoomout, + openfile, + otheruser, + admin, + street, + map, + clearselection, + fontdecrease, + fontincrease, + fontsize, + cellphone, + reshare, + tag, + repeatone, + repeatall, + outlinestar, + solidstar, + calculator, + directions, + target, + library, + phonebook, + memo, + microphone, + postupdate, + backtowindow, + fullscreen, + newfolder, + calendarreply, + unsyncfolder, + reporthacked, + syncfolder, + blockcontact, + switchapps, + addfriend, + touchpointer, + gotostart, + zerobars, + onebar, + twobars, + threebars, + fourbars, + scan, + preview + } + + /** + * Indicates whether the IListDataAdapter was able to provide a count. + **/ + enum CountResult { + /** + * Indicates no count is available. + **/ + unknown + } + + /** + * Indicates that the IListDataAdapter was unable to provide a count. + **/ + enum CountError { + /** + * An attempt to count items timed out. + **/ + noResponse + } + + /** + * Describes the status of an IListDataSource. + **/ + enum DataSourceStatus { + /** + * The IListDataSource is ready. + **/ + ready, + /** + * The IListDataSource is still loading. + **/ + waiting, + /** + * The IListDataSource failed to load. + **/ + failure + } + + /** + * Specifies the type of error that occurred during an edit operation on a IListDataSource or an IListDataAdapter. + **/ + enum EditError { + /** + * The edit operation timed out. + **/ + noResponse, + /** + * The data source cannot be written to. + **/ + notPermitted, + /** + * The item has changed. + **/ + noLongerMeaningful + } + + /** + * Specifies the type of error encountered when retrieving items from an IListDataAdapter. + **/ + enum FetchError { + /** + * The fetch operation timed out. + **/ + noResponse, + /** + * The specified item could not be located. + **/ + doesNotExist + } + + /** + * Specifies how group headers in a ListView respond to the tap interaction. + **/ + enum GroupHeaderTapBehavior { + /** + * The group is invoked. + **/ + invoke, + /** + * Nothing happens. + **/ + none + } + + /** + * Specifies the position of group headers relative to their items in a ListView. + **/ + enum HeaderPosition { + /** + * Group headers appear to the left of items. + **/ + left, + /** + * Group headers appear above items. + **/ + top + } + + /** + * Specifies that type of animation for which a contentanimating event was raised. + **/ + enum ListViewAnimationType { + /** + * The animation plays when the ListView is first displayed. + **/ + entrance, + /** + * The animation plays when the ListView is changing its content. + **/ + contentTransition + } + + /** + * Describes the type of object in a ListView. + **/ + enum ObjectType { + /** + * The object is a group header in the list. + **/ + groupHeader, + /** + * The object is an item in the list. + **/ + item + } + + /** + * Specifies the orientation of a control. + **/ + enum Orientation { + /** + * A horizontal layout. + **/ + horizontal, + /** + * A vertical layout. + **/ + vertical + } + + enum PageNavigationAnimation { + /** + * The pages exit and enter using a turnstile animation. + **/ + turnstile, + /** + * The pages exit and enter using an animation that slides up/down. + **/ + slide, + /** + * The pages enter using an enterPage animation, and exit with no animation. + **/ + enterPage, + /** + * The pages exit and enter using a continuum animation. + **/ + continuum + } + + /** + * Specifies the selection mode of a ListView. + **/ + enum SelectionMode { + /** + * Items cannot be selected. + **/ + none, + /** + * Multiple items may be selected. Clicking additional items adds them to the selection. + **/ + multi + } + + /** + * Specifies how items in a ListView respond to the tap interaction. + **/ + enum TapBehavior { + /** + * The item is selected and invoked. + **/ + directSelect, + /** + * The item is selected if was not already selected, and its deselected if it was already selected. + **/ + toggleSelect, + /** + * The item is invoked but not selected. + **/ + invokeOnly, + /** + * Nothing happens. + **/ + none + } + + //#endregion Enumerations + + //#region Interfaces + + /** + * Contains items that were requested from an IListDataAdapter and provides some information about those items. + **/ + interface IFetchResult { + //#region Properties + + /** + * Gets or sets the index of the requested item in the IListDataAdapter object's data source. + **/ + absoluteIndex: number; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the last items at the end of the IListDataAdapter object's data source. + **/ + atEnd: boolean; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the first items at the beginning of the IListDataAdapter object's data source. + **/ + atStart: boolean; + + /** + * Gets or sets the items returned by the fetch operation. + **/ + items: T[]; + + /** + * Gets or sets the location of the requested item within the items array. + **/ + offset: number; + + /** + * Gets or sets the number of items in the IListDataAdapter object's underlying data source. + **/ + totalCount: number; + + //#endregion Properties + + } + + /** + * Represents an item in a list. + **/ + interface IItem { + //#region Properties + + /** + * Gets or sets the item's data. + **/ + data: T; + + /** + * Gets the group key for the item. This property is only available for items that belong to a grouped data source. + **/ + groupKey: string; + + /** + * Gets the temporary ID of the item. + **/ + handle: string; + + /** + * Gets the item's index in the IListDataSource. + **/ + index: number; + + /** + * Gets or sets the key the identifies the item. + **/ + key: string; + + //#endregion Properties + + } + + /** + * Provides a mechanism for retrieving IItem objects asynchronously. + **/ + interface IItemPromise { + //#region Events + + /** + * Occurs when there is an error in processing. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; + + /** + * Stops change notification tracking for the IItem that fulfills this IItemPromise. + **/ + release(): void; + + /** + * Begins change notification tracking for the IItem that fulfills this IItemPromise. + **/ + retain(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the complete or error function. + **/ + then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the temporary ID of the IItem that fulfills this promise. + **/ + handle: string; + + /** + * Gets or sets the index of the IItem contained by this IItemPromise. + **/ + index: number; + + //#endregion Properties + + } + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. Represents a layout for the ListView. + **/ + interface ILayout { + //#region Methods + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param beginScrollPosition The first visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the first visible item at the specified point. + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param endScrollPosition The last visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the last visible item at the specified point. + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @returns A object that has these properties: animationPromise, newEndIndex. + **/ + endLayout(): any; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The index of the item. + * @returns A Promise that returns an object with these properties: left, top, contentWidth, contentHeight, totalWidth, totalHeight. + **/ + getItemPosition(itemIndex: number): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The data source index of the current item. + * @param element The element for the current item. + * @param keyPressed The key that was pressed. This function must check for the arrow keys (leftArrow, upArrow, rightArrow, downArrow), pageDown, and pageUp and determine which item the user navigated to. + * @returns A Promise that contains the index of the next item (This item becomes the current item). + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: WinJS.Utilities.Key): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @returns A Promise that returns an object that has these properties: beginScrollPosition, endScrollPosition. + **/ + getScrollBarRange(): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param x The x-coordinate to test. + * @param y The y-coordinate to test. + **/ + hitTest(x: number, y: number): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param elements The elements that represent the items that were added. + **/ + itemsAdded(elements: HTMLElement[]): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + itemsMoved(): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param elements The elements that represent the items that were removed. + **/ + itemsRemoved(elements: HTMLElement[]): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param groupIndex The index of the group in the group data source. + * @param element The element to render for the group header. + **/ + layoutHeader(groupIndex: number, element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The index of the item in the data source. + * @param element The element to render for the item. + **/ + layoutItem(itemIndex: number, element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element The element that represents a header in the data source. + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element An element that represents an item in the data source. + **/ + prepareItem(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element The element being released. + **/ + releaseItem(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + reset(): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param site The layout site for the layout. You can use this object to query the hosting ListView for info you might need to lay out items. + **/ + setSite(site: ILayoutSite): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param beginScrollPosition The starting pixel of the area to which the items are rendered. + * @param endScrollPosition The last pixel of the area to which the items are rendered. + * @param count The upper bound of the number of items to render. + * @returns A Promise that returns an object that has these properties: beginIndex, endIndex. + **/ + startLayout(beginScrollPosition: number, endScrollPosition: number, count: number): Promise; + + //#endregion Methods + + //#region Properties + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + horizontal: boolean; + + //#endregion Properties + + } + + /** + * Represents a layout for the ListView. + **/ + interface ILayout2 { + //#region Methods + + /** + * Called when the ListView finishes a drag operation. + **/ + dragLeave(): void; + + /** + * Called when the ListView initiates a drag operation. + * @param x The x-coordinate of the drag. + * @param y The y-coordinate of the drag. + * @param dragInfo An object that indicates whether the item is selected. + **/ + dragOver(x: number, y: number, dragInfo: number): void; + + /** + * Called when the ListView requests that the ILayout2 execute animations. + **/ + executeAnimations(): void; + + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + + /** + * Gets the item at the specified hit-test coordinates. These coordinates are absolute coordinates (they are not relative to the layout's content area). + * @param x The x-coordinate to test for. + * @param y The y-coordinate to test for. + * @returns An object that describes the item at the hit test coordinates. It has these properties: type, index. + **/ + hitTest(x: number, y: number): any; + + /** + * Sets the rendering site and specifies whether the layout supports groups. This method is called by the ListView to initialize the layout. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * Retrieves the indexes of the items in the specified pixel range. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * Performs a layout pass. + * @param tree A structure representing the layout tree that is returned from the ListView. + * @param changedRange An object that lists the index of the first item in the changed item range. This object has these properties: startIndex. + * @param modifiedItems An object that contains the old and new indexes of the items that have been modified in the tree. + * @param modifiedGroups An object that contains the old and new indexes of the group elements that have been modified in the tree. + * @returns A Promise that executes after layout is complete, or an object that contains two Promise objects: realizedRangeComplete, layoutComplete. + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): any; + + /** + * Called when the ListView requests that the ILayout2 set up animations. + **/ + setupAnimations(): void; + + /** + * Releases resources that were obtained during the call to initialize. + **/ + uninitialize(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the orientation of the layout. + **/ + orientation: any; + + //#endregion Properties + + } + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayoutSite2 interface. Represents a rendering site for an ILayout. + **/ + interface ILayoutSite { + //#region Properties + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + animationsDisabled: boolean; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + itemSurface: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + rtl: boolean; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + scrollbarPos: number; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + surface: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + viewport: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + viewportSize: any; + + //#endregion Properties + + } + + /** + * Represents a rendering site for an ILayout2. + **/ + interface ILayoutSite2 { + //#region Properties + + /** + * Gets the number of groups in the site. + **/ + groupCount: number; + + /** + * Gets the number of items in the site. + **/ + itemCount: Promise; + + /** + * Gets the pixel range of the realization area. + **/ + realizedRange: any; + + /** + * Gets the tree for use by an object that implements the ILayout2 interface. + **/ + tree: any; + + /** + * Gets the pixel range of visible items in the site. + **/ + visibleRange: any; + + //#endregion Properties + + } + + /** + * Retrieves items from a IListDataSource, enumerates the contents of a IListDataSource, and can optionally register for change notifications. + **/ + interface IListBinding { + //#region Methods + + /** + * Retrieves the current item. + * @returns An IItemPromise that contains the current item. If the cursor has moved past the start or end of the list, the promise completes with a value of null. If the current item has been moved or deleted, the promise returns an error. + **/ + current(): IItemPromise>; + + /** + * Gets the first item from the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. If the list is empty, the promise completes with a value of null. + **/ + first(): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified description and makes it the current item. + * @param description A domain-specific description, to be interpreted by the IListDataAdapter, that identifies the item to retrieve. + * @returns An IItemPromise that contains the requested IItem object. If the item wasn't found, the promise completes with a value of null. + **/ + fromDescription(description: string): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified index and makes it the current item. + * @param index A value greater than or equal to 0 that is the index of the item to retrieve. + * @returns An IItemPromise that contains the requested IItem. If the item wasn't found, the promise completes with a value of null. + **/ + fromIndex(index: number): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified key and makes it the current item. + * @param key The key that identifies the item to retrieve. This value must be a non-empty string. + * @param hints Domain-specific information that provides additional information to the IListDataAdapter to improve retrieval time. + * @returns An IItemPromise that contains the requested IItem. If they item couldn't be found, the promise completes with a value of null. + **/ + fromKey(key: string, hints?: any): IItemPromise>; + + /** + * Makes the specified IItem or IItemPromise the current item. + * @param item The IItem or IItemPromise that will become the current item. + * @returns An IItemPromise that contains the specified item, if it exists. If the specified item is not in the list, the promise completes with a value of null. + **/ + jumpToItem(item: IItem): IItemPromise>; + + /** + * Retrieves the last item in the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. f the list is empty, the promise completes with a value of null. + **/ + last(): IItemPromise>; + + /** + * Retrieves the item after the current item and makes it the current item. + * @returns An IItemPromise that contains the item after the current item. If the cursor moves past the end of the list, the promise completes with a value of null. + **/ + next(): IItemPromise>; + + /** + * Retrieves the item before the current item and makes it the current item. + * @returns An IItemPromise that contains the item before the current item. If the cursor moves past the start of the list, the promise completes with a value of null. + **/ + previous(): IItemPromise>; + + /** + * Releases resources, stops notifications, and cancels outstanding promises for all tracked items returned by this IListBinding. + **/ + release(): void; + + /** + * Creates a request to stop change notifications for the specified item. The change notifications stop when the number of releaseItem calls matches the number of IIItemPromise.retain calls. + * @param item The IItem or IItemPromise that should stop receiving notifications. + **/ + releaseItem(item: IItem): void; + + //#endregion Methods + + } + + /** + * Accesses data for an IListDataSource. + **/ + interface IListDataAdapter { + //#region Methods + + /** + * Overwrites the data of the specified item. + * @param key The key of the item to overwrite. + * @param newData The new data for the item. + * @param indexHint The index of the item, if known. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + change(key: string, newData: T, indexHint: number): Promise; + + /** + * Gets the number of items in the IListDataAdapter object's data source. + * @returns A Promise that contains the number of items the IListDataAdapter contains, or an approximate value if the actual number is unknown. + **/ + getCount(): Promise; + + /** + * Inserts the specified data after the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param previousKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted after this item. + * @param previousIndexHint The index of the item to insert the new data after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string, previousIndexHint: number): Promise>; + + /** + * Adds the specified key and data to the end of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds the specified key and data to the beginning of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts the specified data before the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param nextKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted before this item. + * @param nextIndexHint The index of the item to insert the new data before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string, nextIndexHint: number): Promise>; + + /** + * Retrieves the item that matches the specified description and also retrieves the specified number of items before and after the matched item. + * @param description A description of the item to locate. + * @param countBefore The number of items before the matched item to retrieve. + * @param countAfter The number of items after the matched item to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromDescription(description: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the end of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromEnd(count: number): Promise>; + + /** + * Retrieves the item at the specified index and also retrieves the specified number of items before and after the selected item. + * @param index The index of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromIndex(index: number, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the item that has the specified key and also retrieves the specified number of items before and after the selected item. + * @param key The key of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromKey(key: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the beginning of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromStart(count: number): Promise>; + + /** + * Returns a string representation of the specified item that can be used for comparisons. + * @param item The item for which to generate a signature. + * @returns The signature representation of the specified item. + **/ + itemSignature(item: IItem): string; + + /** + * Moves the specified item to just after another item. + * @param key A key of the item to move. + * @param previousKey The key of another item. The item to move will be moved to just after this item. + * @param indexHint The index of the item to move, if known. + * @param previousIndexHint The index to move the item after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: any, indexHint: string, previousIndexHint: number): Promise>; + + /** + * Moves the specified item to just before another item. + * @param key A key of the item to move. + * @param nextKey The key of another item. The item to move will be moved to just before this item. + * @param indexHint The index of the item to move, if known. + * @param nextIndexHint The index to move the item before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: any, indexHint: string, nextIndexHint: number): Promise>; + + /** + * Moves the specified item to the end of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToEnd(key: string, indexHint: number): Promise>; + + /** + * Moves the specified item to the beginning of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToStart(key: string, indexHint: number): Promise>; + + /** + * Removes the specified item from the IListDataAdapter object's data source. + * @param key The key of the item to remove. + * @param data The new data for the item. + * @param indexHint The index of the item. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + remove(key: string, data: T, indexHint: number): Promise; + + /** + * Registers a notification handler. The IListDataAdapter uses the handler to notify listening objects when its data changes. + * @param notificationHandler The notification handler that the IListDataAdapter will use to provide change notifications. . + **/ + setNotificationHandler(notificationHandler: IListDataNotificationHandler): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether to use an object's identity to determine if an item has changed. + **/ + compareByIdentity: boolean; + + //#endregion Properties + + } + + /** + * Notifies clients when an IListDataAdapter object's data changes. + **/ + interface IListDataNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Raises a notification that an item in the IListDataAdapter object's data source has changed. + * @param item The item that changed. + **/ + changed(item: IItem): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Raises a notification that an item has been added to the IListDataAdapter object's data source. + * @param newItem The new item added to the IListDataAdapter object's data source. + * @param previousKey The key of the item that now precedes the new item, or null if the item was inserted at the start of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was inserted at the end of the list. If previousKey is provided, this parameter may be null. + * @param index The index of the new item. + **/ + inserted(newItem: IItem, previousKey: string, nextKey: string, index?: number): void; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all change notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Raises a notification that an item was moved within the IListDataAdapter object's data source. + * @param item The item that was moved. + * @param previousKey The key of the item that now precedes the new item, or null if the item was moved to the beginning of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was moved to the end of the list. If previousKey is provided, this parameter may be null. + * @param oldIndex The item's original index. + * @param newIndex The item's new index. + **/ + moved(item: IItem, previousKey: string, nextKey: string, oldIndex?: number, newIndex?: number): void; + + /** + * Reloads data from the IListDataAdapter. + **/ + reload(): void; + + /** + * Raises a notification that an item was removed from the IListDataAdapter object's data source. + * @param key The key of the item that was removed. + * @param index The index of the item that was removed. + **/ + removed(key: string, index?: number): void; + + //#endregion Methods + + } + + /** + * Provides access to a data source and enables you to bind, change, add, remove, and move items in that data source. + **/ + interface IListDataSource { + //#region Events + + /** + * Occurs when the status of the IListDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Notifies the IListDataSource that a sequence of edits is about to begin. The IListDataSource will defer notifications until endEdits is called. + **/ + beginEdits(): void; + + /** + * Overwrites the data of the specified item. + * @param key The key for the item to replace. + * @param newData The new data for the item. + * @returns A Promise that contains the IItem that was updated or an EditError if an error was encountered. + **/ + change(key: string, newData: T): Promise>; + + /** + * Creates an IListBinding that can retrieve items from the IListDataSource, enumerate the contents of the IListDataSource object's data, and optionally register for change notifications. + * @param notificationHandler Enables the IListBinding to register for change notifications for individual items obtained from the IListDataSource. If you omit this parameter, change notifications won't be available. + * @returns The new IListBinding. + **/ + createListBinding(notificationHandler?: IListNotificationHandler): IListBinding; + + /** + * Notifies the IListDataSource that the batch of edits that began with the last beginEdits call has completed. The IListDataSource will submit notifications for any changes that occurred between the beginEdits and endEdits calls as a batch and resume normal change notifications. + **/ + endEdits(): void; + + /** + * Retrieves the number of items in the data source. + * @returns A Promise that provides a Number that is the number of items in the data source. + **/ + getCount(): Promise; + + /** + * Inserts a new item after another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param previousKey The key for an item in the data source. The new item will be added after this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string): Promise>; + + /** + * Adds an item to the end of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds an item to the beginning of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts an item before another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param nextKey The key of an item in the data source. The new item will be inserted before this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string): Promise>; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Retrieves the item that has the specified description. + * @param description Domain-specific information, to be interpreted by the IListDataAdapter, that describes the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromDescription(description: any): Promise>; + + /** + * Retrieves the item at the specified index. + * @param index A value that is greater than or equal to zero that is the index of the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromIndex(index: number): Promise>; + + /** + * Retrieves the item with the specified key. + * @param key The key of the item to retrieve. It must be a non-empty string. + * @param description Domain-specific information that IListDataAdapter can use to improve the retrieval time. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item was not found, the promise completes with a null value. + **/ + itemFromKey(key: string, description?: any): Promise>; + + /** + * Moves an item to just after another item. + * @param key The key that identifies the item to move. + * @param previousKey The key of another item in the data source. The item specified by the key parameter will be moved after this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: string): Promise>; + + /** + * Moves an item before another item. + * @param key The key that identifies the item to move. + * @param nextKey The key of another item in the data source. The item specified by the key parameter will be moved before this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: string): Promise>; + + /** + * Moves an item to the end of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToEnd(key: string): Promise>; + + /** + * Moves the specified item to the beginning of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToStart(key: string): Promise>; + + /** + * Removes the specified item from the data source. + * @param key The key that identifies the item to remove. + * @returns A Promise that contains nothing if the operation was successful or an EditError if an error was encountered. + **/ + remove(key: string): Promise>; + + //#endregion Methods + + } + + /** + * Used by an IListBinding to provide change notifications when items in a IListDataSource change. + **/ + interface IListNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Indicates that an item changed. + * @param newItem The updated item. + * @param oldItem The original item. + **/ + changed(newItem: IItem, oldItem: IItem): void; + + /** + * Indicates that the number of items in the IListDataSource has changed. + * @param newCount The updated count. + * @param oldCount The original count. + **/ + countChanged(newCount: number, oldCount: number): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Indicates that the index of an item changed. + * @param handle The temporary ID of the item. + * @param newIndex The new index. + * @param oldIndex The original index. + **/ + indexChanged(handle: string, newIndex: number, oldIndex: number): void; + + /** + * Indicates that an item was added to the IListDataSource. + * @param itemPromise A promise for the new IItem. + * @param previousHandle The temporary ID of the item that precedes the new item. + * @param nextHandle The temporary ID of the item that follows the new item. + **/ + inserted(itemPromise: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an IItemPromise was fulfilled and that the item is now available. + * @param item The fulfilled item. + **/ + itemAvailable(item: IItem): void; + + /** + * Indicates that an item was moved. + * @param item A promise for the IItem that was moved. + * @param previousHandle The temporary ID of the item that now precedes the moved item. + * @param nextHandle The temporary ID of the item that now follows the moved item. + **/ + moved(item: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an item was removed. + * @param handle The temporary ID of the item that was removed. + * @param mirage true if the item never actually existed; false if the item was actually present in the IListDataSource. + **/ + removed(handle: string, mirage: boolean): void; + + //#endregion Methods + + } + + /** + * Used by ListView's currentItem API + **/ + interface IListViewItem { + /** + * Gets or sets index of the ListView item. + **/ + index?: number; + + /** + * Gets or sets key of the ListView item. + **/ + key?: string; + + /** + * Gets or sets whether the ListView item is focused. + **/ + hasFocus?: boolean; + + /** + * Gets or sets whether the ListView item is focused and is showing its focus visual. + **/ + showFocus?: boolean; + } + + /** + * Represents a selection of ListView items. + **/ + interface ISelection { + //#region Methods + + /** + * Adds one or more items to the selection. + * @param items The indexes or keys of the items to add. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + add(items: any): Promise; + + /** + * Clears the selection. + * @returns A Promise that is fulfilled when the clear operation completes. + **/ + clear(): Promise; + + /** + * Returns the number of items in the selection. + * @returns The number of items in the selection. + **/ + count(): number; + + /** + * Returns a list of the indexes for the items in the selection. + * @returns The list of indexes for the items in the selection as an array of Number objects. + **/ + getIndices(): number[]; + + /** + * Returns an array that contains the items in the selection. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + getItems(): Promise[]>; + + /** + * Gets an array of the index ranges for the selected items. + * @returns An array that contains an ISelectionRange object for each index range in the selection. + **/ + getRanges(): ISelectionRange[]; + + /** + * Returns a value that indicates whether the selection contains every item in the data source. + * @returns true if the selection contains every item in the data source; otherwise, false. + **/ + isEverything(): boolean; + + /** + * Removes the specified items from the selection. + * @param items The indexes or keys of the items to remove. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + remove(items: any): Promise; + + /** + * Adds all the items in the ListView to the selection. + **/ + selectAll(): void; + + /** + * Clears the current selection and replaces it with the specified items. + * @param items The indexes or keys of the items that make up the selection. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + set(items: any): Promise; + + //#endregion Methods + + } + + /** + * Represents a range of indexes or keys in an ISelection. + **/ + interface ISelectionRange { + //#region Properties + + /** + * Gets or sets the index of the first item in the range. + **/ + firstIndex: number; + + /** + * Gets or sets the key of the first item in the range. + **/ + firstKey: any; + + /** + * Gets or sets the index of the last item in the range. + **/ + lastIndex: number; + + /** + * Gets or sets of the key of the last item in the range. + **/ + lastKey: any; + + //#endregion Properties + + } + + /** + * Supports semantic zoom functionality by exposing a control as either the zoomed in or the zoomed out view of the SemanticZoom control. + **/ + interface IZoomableView { + //#region Methods + + /** + * Initiates semantic zoom on the custom control. + **/ + beginZoom(): void; + + /** + * Initializes the semantic zoom state for the custom control. + * @param isZoomedOut True if this is the zoomed out view; otherwise false. + * @param isCurrentView True if this is the current view; otherwise false. + * @param triggerZoom The function that manages semantic zoom behavior. Triggers a zoom in or zoom out if the control is the visible control. + * @param prefetchedPages The number of pages of content to pre-fetch for zooming. This value is dependent on the size of the semantic zoom container. More content can be displayed based on the zoom factor and the size of the container. + **/ + configureForZoom(isZoomedOut: boolean, isCurrentView: boolean, triggerZoom: Function, prefetchedPages: number): void; + + /** + * Terminates semantic zoom on the zoomed in or zoomed out child of the custom control. + * @param isCurrentView True if the control is the visible control; otherwise false. + **/ + endZoom(isCurrentView: boolean): void; + + /** + * Retrieves the current item of the zoomed in or zoomed out child of the custom control. + * @returns An object that represents the selected item. This return value must be a Promise for the following: item, position. + **/ + getCurrentItem(): Promise<{ item: T; position: Utilities.IPosition }>; + + /** + * Retrieves the panning axis of the zoomed-in or zoomed-out child of the custom control. + * @returns Identifies the panning axis of the child control. Implementation specific. + **/ + getPanAxis(): string; + + /** + * Manages pointer input for the custom control. + * @param pointerId The ID of the pointer. + **/ + handlePointer(pointerId: string): void; + + /** + * Positions the specified item within the viewport of the child control when panning or zooming begins. + * @param item The object to position within the viewport of the child control. item can be a number, a string, or an object with any number of properties. + * @param position An object that contains the position data of the item relative to the child control. position must be an object with four number properties: left, top, width, and height. These values specify a rectangle that is typically the bounding box of the current item, though the details are up to the control. The units of the position must be in pixels. And the coordinates must be relative to the top-left of the control viewport (which should occupy the same area as the semantic zoom viewport), except when in RTL mode. In RTL mode, return coordinates relative to the top-right off the control viewport. The rectangle is transformed from the coordinate system of one control to that of the other. + **/ + positionItem(item: T, position: Utilities.IPosition): void; + + /** + * Selects the item closest to the specified screen coordinates. + * @param x The x-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport. + * @param y The y-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport.. + **/ + setCurrentItem(x: number, y: number): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * Represents an application toolbar for displaying commands. + **/ + class AppBar { + //#region Constructors + + /** + * Creates a new AppBar object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBar. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the AppBar goes to its closed state. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs when the AppBar goes to its opened state. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the AppBar goes to its closed state. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before the AppBar goes to its opened state. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this AppBar. Call this method when the AppBar is no longer needed. After calling this method, the AppBar becomes unusable. + **/ + dispose(): void; + + /** + * Returns the AppBarCommand object identified by id. + * @param id The element idenitifier (ID) of the command to be returned. + * @returns The command identified by id. If multiple commands have the same ID, returns an array of all the commands matching the ID. + **/ + getCommandById(id: string): AppBarCommand; + + /** + * Makes the AppBar go to its closed state. + **/ + hide(): void; + + /** + * Hides the specified commands of the AppBar. + * @param commands The commands to hide. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate?: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Makes the AppBar go to its opened state. + **/ + show(): void; + + /** + * Shows the specified commands of the AppBar. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate?: boolean): void; + + /** + * Shows the specified commands of the AppBar while hiding all other commands. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets how the app bar is displayed when hidden is true. + **/ + closedDisplayMode: string; + + /** + * Sets the AppBarCommand objects that appear in the app bar. + **/ + commands: AppBarCommand[]; + + /** + * Gets or sets a value that indicates whether the AppBar is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBar. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the AppBar control is in its closed state. + **/ + hidden: boolean; + + /** + * Gets or sets the layout of the app bar contents. + **/ + layout: string; + + /** + * Gets or sets a value that specifies whether the AppBar appears at the top or bottom of the main view. + **/ + placement: string; + + /** + * Gets or sets a value that indicates whether the AppBar is sticky (won't light dismiss). If not sticky, the app bar dismisses normally when the user touches outside of the appbar. + **/ + sticky: boolean; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in an app bar. + **/ + class AppBarCommand { + //#region Constructors + + /** + * Creates a new AppBarCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBarCommand. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this AppBarCommand. Call this method when the AppBarCommand is no longer needed. After calling this method, the AppBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the AppBarCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBarCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing HOME or the arrow keys, from the previous AppBarCommand to this AppBarCommand. + **/ + firstElementFocus: HTMLElement; + + /** + * Gets or sets a value that indicates whether the AppBarCommand is hiding or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the icon of the AppBarCommand. + **/ + icon: string; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing END or the arrow keys, from the previous AppBarCommand to this AppBarCommand. + **/ + lastElementFocus: HTMLElement; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets the section of the app bar that the command is in. + **/ + section: string; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets or sets the tooltip of the command. + **/ + tooltip: string; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Adds event-related methods to the control. + **/ + class DOMEventMixin { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture true to initiate capture; otherwise, false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type, adding the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true to initiate capture; otherwise, false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If the name of the options property begins with "on", the property value is a function and the control supports addEventListener. This method calls the addEventListener method on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + setOptions(control: any, options: any): void; + + //#endregion Methods + + } + + /** + * Displays a collection, such as a set of photos, one item at a time. + **/ + class FlipView { + //#region Constructors + + /** + * Creates a new FlipView. + * @constructor + * @param element The DOM element that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the pageselected event, add a property named "onpageselected" and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the datasource count changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: source. + **/ + ondatasourcecountchanged(eventInfo: Event): void; + + /** + * Raised when the FlipView flips to a page and its renderer function completes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpagecompleted(eventInfo: CustomEvent): void; + + /** + * Raised when the FlipView flips to a page. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpageselected(eventInfo: CustomEvent): void; + + /** + * Occurs when an item becomes invisible or visible. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source, detail.visible. + **/ + onpagevisibilitychanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. For a list of events, see the FlipView object page. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Returns the number of items in the FlipView control's itemDataSource. + * @returns A Promise that contains the number of items in the list or WinJS.UI.CountResult.unknown if the count is unavailable. + **/ + count(): Promise; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this FlipView. Call this method when the FlipView is no longer needed. After calling this method, the FlipView becomes unusable. + **/ + dispose(): void; + + /** + * Forces the FlipView to update its layout. Use this function when making the FlipView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Navigates to the next page. + * @returns true if the FlipView begins navigating to the next page; false if the FlipView is already at the last item or is in the middle of another navigation animation. + **/ + next(): boolean; + + /** + * Navigates to the previous item. + * @returns true if the FlipView begins navigating to the previous page; nfalse if the FlipView is already at the first page or is in the middle of another navigation animation. + **/ + previous(): boolean; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event. + * @param eventHandler The event handler function to remove. + * @param useCapture Set to true to unregister the event handler for the capturing phase; otherwise, set to false to unregister the event handler for the bubbling phase. + **/ + removeEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Sets custom animations for the FlipView to use when navigating between pages. + * @param animations An object that contains up to three fields, one for each navigation action: next, previous, and jump. Each of those fields must be a function with this signature: function (outgoingPage, incomingPage) Each function must return a WinJS.Promise that completes once the animations are finished. If a field is null or undefined, the FlipView reverts to its default animation for that action. + **/ + setCustomAnimations(animations: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the index of the currently displayed page. + **/ + currentPage: number; + + /** + * Gets the HTML element that hosts this FlipView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that provides the FlipView with items to display. The FlipView displays one item at a time, on its own page. + **/ + itemDataSource: IListDataSource; + + /** + * Gets or sets the spacing between each item, in pixels. + **/ + itemSpacing: number; + + /** + * Gets or sets a Template or function that defines the HTML for each item's page. + **/ + itemTemplate: any; + + /** + * Gets or sets the orientation of the FlipView, horizontal or vertical. + **/ + orientation: string; + + //#endregion Properties + + } + + /** + * Represents a grid layout for the ListView in which items are arranged in a horizontal grid. + **/ + class GridLayout { + //#region Constructors + + /** + * Creates a new GridLayout object. + * @constructor + * @param options The set of properties and values to apply to the new GridLayout. + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * This method is no longer supported. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This method is no longer supported. + **/ + endLayout(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This method is no longer supported. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: any, keyPressed: any): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This method is no longer supported. + **/ + init(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This method is no longer supported. + **/ + itemsMoved(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This method is no longer supported. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * This method is no longer supported. + **/ + reset(): void; + + /** + * This method is no longer supported. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + /** + * This method is no longer supported. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + backdropColor: string; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + groupInfo: Function; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. + **/ + horizontal: boolean; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + itemInfo: Function; + + /** + * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. + **/ + maximumRowsOrColumns: number; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the maximumRowsOrColumns property. + **/ + maxRows: number; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets or sets the orientation of the GridLayout. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Enables you to include an HTML page dynamically. As part of the constructor, you must include an option indicating the URI of the page. + **/ + class HtmlControl { + //#region Constructors + + /** + * Initializes a new instance of HtmlControl to define a new page control. + * @constructor + * @param element The element that hosts the HtmlControl. + * @param options The options for configuring the page. The uri option is required in order to specify the source document for the content of the page. Other options are the ones used by the WinJS.Pages.render method. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + } + + /** + * Defines an item that can be pressed, swiped, and dragged. + **/ + class ItemContainer { + //#region Constructors + + /** + * Creates a new ItemContainer. + * @constructor + * @param element The DOM element hosts the new ItemContainer. For the ItemContainer to be accessible, this element must have its role attribute set to "list" or "listbox". If tapBehavior is set to none and selectionDisabled is true, then use the "list" role; otherwise, use the "listbox" role. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the item is invoked. (You can use the tapBehavior property to specify whether taps and clicks invoke the item.) + * @param eventInfo An object that contains information about the event. + **/ + oninvoked(eventInfo: CustomEvent): void; + + /** + * Raised after the item is selected or deselected. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanged(eventInfo: CustomEvent): void; + + /** + * Raised just before the current selection changes. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanging(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this ItemContainer. Call this method when the ItemContainer is no longer needed. After calling this method, the ItemContainer becomes unusable. + **/ + dispose(): void; + + /** + * Forces the ItemContainer to update its layout. Call this function when the reading direction of the app changes after the control has been initialized. + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the item can be dragged. + **/ + draggable: boolean; + + /** + * Gets the element that hosts this ItemContainer. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether the item is selected. + **/ + selected: boolean; + + /** + * Gets or sets a value that specifies whether selection of this item is disabled. + **/ + selectionDisabled: boolean; + + /** + * Gets or sets the orientation of swipe gestures. + **/ + swipeOrientation: Orientation; + + /** + * Gets or sets how the ItemContainer reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + //#endregion Properties + + } + + /** + * This object supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + class Layout { + } + + /** + * Represents a layout for the ListView in which items are arranged in a vertical list. + **/ + class ListLayout { + //#region Constructors + + /** + * Creates a new ListLayout. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new ListLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * This method is no longer supported. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This method is no longer supported. + **/ + endLayout(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This method is no longer supported. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: any): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This method is no longer supported. + **/ + init(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + initialize(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel + * @param lastPixel + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This method is no longer supported. + **/ + itemsMoved(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This method is no longer supported. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * This method is no longer supported. + **/ + reset(): void; + + /** + * This method is no longer supported. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + /** + * This method is no longer supported. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + backdropColor: string; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + groupInfo: Function; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. + **/ + horizontal: boolean; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + itemInfo: Function; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets or sets the orientation of the GridLayout. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Displays data items in a customizable list or grid. + **/ + class ListView { + //#region Constructors + + /** + * Creates a new ListView. + * @constructor + * @param element The DOM element that hosts the ListView control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the selectionchanged event, add a property named "onselectionchanged" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ListView is about to play an entrance or contentTransition animation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.setPromise. + **/ + oncontentanimating(eventInfo: CustomEvent): void; + + /** + * Raised when the user taps or clicks a group header. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.groupHeaderIndex, detail.groupHeaderPromise. + **/ + ongroupheaderinvoked(eventInfo: CustomEvent): void; + + /** + * Occurs when the user taps or clicks an item. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.itemIndex. + **/ + oniteminvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the focused item changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.oldFocus, detail.oldNewFocus. + **/ + onkeyboardnavigating(eventInfo: CustomEvent): void; + + /** + * Occurs when the ListView control's loadingState changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.scrolling. + **/ + onloadingstatechanged(eventInfo: CustomEvent): void; + + /** + * Occurs after the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. To obtain the selected items, use the ListView.selection property. + **/ + onselectionchanged(eventInfo: CustomEvent): void; + + /** + * Occurs just before the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.newSelection, detail.preventTapBehavior. + **/ + onselectionchanging(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the ListView object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onselectionchange", you specify "selectionchange". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. + **/ + dispose(): void; + + /** + * Returns the DOM element that represents the item at the specified index. + * @param itemIndex The index of the item. + * @returns The DOM element that represents the item at the specified index. + **/ + elementFromIndex(itemIndex: number): HTMLElement; + + /** + * Makes the item at the specified index visible. If necessary, the ListView will scroll to the item. + * @param itemIndex The index of the item to scroll into view. + **/ + ensureVisible(itemIndex: number): void; + + /** + * Forces the ListView to update its layout. Use this function when making the ListView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Returns the index of the item that the specified DOM element displays. + * @param element The DOM element that displays the item. + * @returns The index of the item displayed by element. + **/ + indexOfElement(element: HTMLElement): number; + + /** + * Loads the next set of pages if the ListView control's loadingBehavior is set to "incremental" (otherwise, it does nothing). The number of pages to be loaded is determined by the pagesToLoad property. + **/ + loadMorePages(): void; + + /** + * Repositions all the visible items in the ListView to adjust for items whose sizes have changed. Most apps won’t ever need to call this method. For more info, see the Remarks section. + **/ + recalculateItemPosition(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Triggers the ListView disposal service manually. + **/ + static triggerDispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the next set of pages is automatically loaded when the user scrolls beyond the number of pages specified by the pagesToLoadThreshold property. + **/ + automaticallyLoadPages: boolean; + + /** + * Gets or sets an IListViewItem that indicates which item should have keyboard focus and the focus state of that item. + **/ + currentItem: IListViewItem; + + /** + * Gets the HTML element that hosts this ListView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that contains the groups for the items in the itemDataSource. + **/ + groupDataSource: IListDataSource; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks a group header. + **/ + groupHeaderTapBehavior: GroupHeaderTapBehavior; + + /** + * Gets or sets the Template or function that creates the DOM elements for each group header in the groupDataSource. Each group header can contain multiple elements, but it must have a single root element. + **/ + groupHeaderTemplate: any; + + /** + * Gets or sets the first visible item. + **/ + indexOfFirstVisible: number; + + /** + * Gets the index of the last visible item in the ListView. + **/ + indexOfLastVisible: number; + + /** + * Gets or sets the data source that provides the ListView with items. + **/ + itemDataSource: IListDataSource; + + /** + * Gets or sets whether the ListView control's items can be reordered within itself by dragging and dropping. + **/ + itemsReorderable: boolean; + + /** + * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the itemDataSource. Each item can contain multiple elements, but it must have a single root element. + **/ + itemTemplate: any; + + /** + * Gets or sets an object that controls the layout of the ListView. + **/ + layout: ILayout2; + + /** + * Gets or sets a value that specifies how the ListView fetches items and adds and removes them to the DOM. Don't change the value of this property after the ListView has begun loading data. + **/ + loadingBehavior: string; + + /** + * Gets a value that indicates whether the ListView is still loading or whether loading is complete. + **/ + loadingState: string; + + /** + * Gets or sets the maximum number of realized items. + **/ + maxDeferredItemCleanup: number; + + /** + * Gets or sets the number of pages to load when the loadingBehavior property is set to "incremental" and the user scrolls beyond the threshold specified by the pagesToLoadThreshold property. + **/ + pagesToLoad: number; + + /** + * Gets or sets the threshold (in pages) for initiating an incremental load. When the last visible item is within the specified number of pages from the end of the loaded portion of the list, and if automaticallyLoadPages is true and loadingBehavior is set to "incremental", the ListView initiates an incremental load. + **/ + pagesToLoadThreshold: number; + + /** + * Gets or sets the function that is called when the ListView discards or recycles the element representation of a group header. + **/ + resetGroupHeader: (header: any, element: HTMLElement) => void; + + /** + * Gets or sets the function that is called when an item is removed, an item is changed, or an item falls outside of the realized range of the ListView. + **/ + resetItem: (item: T, element: HTMLElement) => void; + + /** + * Gets or sets the distance, in pixels, of the start of the viewable area within the viewport. + **/ + scrollPosition: number; + + /** + * Gets an ISelection that contains the range of currently selected items. + **/ + selection: ISelection; + + /** + * Gets or sets the selection mode of the ListView. + **/ + selectionMode: SelectionMode; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + /** + * Gets a ZoomableView that supports semantic zoom functionality. This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. + **/ + zoomableView: IZoomableView>; + + //#endregion Properties + + } + + /** + * A tab control that displays multiple items. + **/ + class Pivot { + //#region Constructors + + /** + * Creates a new Pivot. + * @constructor + * @param element The DOM element hosts the new Pivot. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when a PivotItem control's animation ends. + * @param eventInfo An object that contains information about the event. + **/ + onitemanimationend(eventInfo: Event): void; + + /** + * Raised when a PivotItem control's animation starts. + * @param eventInfo An object that contains information about the event. + **/ + onitemanimationstart(eventInfo: Event): void; + + /** + * Raised when the user navigates to a different PivotItem. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanged(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Pivot. Call this method when the Pivot is no longer needed. After calling this method, the Pivot becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the Pivot control. + **/ + element: HTMLElement; + + /** + * Gets or sets the Binding.List that contains the PivotItem objects that belong to this Pivot. + **/ + items: Binding.List; + + /** + * Gets or sets a value that specifies whether the Pivot control is locked to the current item. + **/ + locked: boolean; + + /** + * Gets or sets the index of the PivotItem control in view. + **/ + selectedIndex: number; + + /** + * Gets or sets the PivotItem control in view within the Pivot control. + **/ + selectedItem: PivotItem; + + /** + * Gets or sets the title displayed above the PivotItem controls. + **/ + title: string; + + //#endregion Properties + } + + /** + * An item within a Pivot control. + **/ + class PivotItem { + //#region Constructors + + /** + * Creates a new PivotItem. + * @constructor + * @param element The DOM element hosts the new PivotItem. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this PivotItem. Call this method when the PivotItem is no longer needed. After calling this method, the PivotItem becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the PivotItem control's content. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts the PivotItem control. + **/ + element: HTMLElement; + + /** + * Gets or sets the header for this PivotItem. + **/ + header: HTMLElement; + + //#endregion Properties + } + + /** + * Generates HTML from a set of data. Use this control to generate lists of items. + **/ + class Repeater { + //#region Constructors + + /** + * Creates a new Repeater control. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised after an item in the Repeater control's data source changes and after the corresponding DOM element has been updated. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * Raised after an item in the Repeater control's data source changes but before the corresponding DOM element has been updated. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. + **/ + onitemchanging(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been added to the Repeater control's data source and after the corresponding DOM element has been added. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been added to the Repeater control's data source but before the corresponding DOM element has been added. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. + **/ + oniteminserting(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source but before the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. + **/ + onitemmoving(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been removed from the Repeater control's data source but before the corresponding DOM element has been removed. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. + **/ + onitemremoving(eventInfo: CustomEvent): void; + + /** + * Raised when the Repeater has finished loading a new set of data. This event is only fired on construction. This event is only raised when the Repeater is constructed or its data source or template changes. + * @param eventInfo An object that contains information about the event. + **/ + onitemsloaded(eventInfo: CustomEvent): void; + + /** + * Raised after the Repeater control's underlying data has been updated and after the updated HTML has been reloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements. + **/ + onitemsreloaded(eventInfo: CustomEvent): void; + + /** + * Raised after the Repeater control's underlying data has been updated but before the updated HTML has been reloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements, detail.setPromise. + **/ + onitemsreloading(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Repeater. Call this method when the Repeater is no longer needed. After calling this method, the Repeater becomes unusable. + **/ + dispose(): void; + + /** + * Returns the HTML element for the item at the specified index. + * @param index The index of the item. + * @returns The DOM element for the specified item. + **/ + elementFromIndex(index: number): HTMLElement; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the List that provides the Repeater with items to display. + **/ + data: WinJS.Binding.List; + + /** + * Gets the DOM element that hosts the Repeater. + **/ + element: HTMLElement; + + /** + * Gets the number of items in the Repeater control. + **/ + length: number; + + /** + * Gets or sets a WinJS.Binding.Template or custom rendering function that defines the HTML of each item within the Repeater. + **/ + template: WinJS.Binding.Template; + + //#endregion Properties + + } + + /** + * Enables the user to zoom between two different views supplied by two child controls. One child control supplies the zoomed-out view and the other provides the zoomed-in view. + **/ + class SemanticZoom { + //#region Constructors + + /** + * Creates a new SemanticZoom. + * @constructor + * @param element The DOM element that hosts the SemanticZoom. + * @param options An object that contains one or more property/value pairs to apply to the new control. This object can contain these properties: initiallyZoomedOut Boolean, zoomFactor 0.2–0.85. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the control zooms in or out. + * @param eventInfo An object that contains information about the event. The detail property of this object is true when the control is zoomed out. Otherwise, it's false. + **/ + onzoomchanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SemanticZoom. Call this method when the SemanticZoom is no longer needed. After calling this method, the SemanticZoom becomes unusable. + **/ + dispose(): void; + + /** + * Forces the SemanticZoom to update its layout. Use this function when making the SemanticZoom visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the SemanticZoom control. + **/ + element: HTMLElement; + + /** + * Determines whether any controls contained in a SemanticZoom should be processed separately. This property is always true, meaning that the SemanticZoom takes care of processing its own controls. + **/ + isDeclarativeControlContainer: boolean; + + /** + * Gets or sets a value that indicates whether SemanticZoom is locked and zooming between views is disabled. + **/ + locked: boolean; + + /** + * Gets or sets a value that indicates whether the control is zoomed out. + **/ + zoomedOut: boolean; + + /** + * Gets or sets a value that specifies how much the scaling the cross-fade animation performs when the SemanticZoom transitions between views. + **/ + zoomFactor: number; + + //#endregion Properties + + } + + /** + * A type of IListDataSource that provides read-access to an object that implements the IStorageQueryResultBase interface. A StorageDataSource enables you to query and bind to items in the data source. + **/ + class StorageDataSource { + //#region Constructors + + /** + * Creates a new StorageDataSource object. + * @constructor + * @param query The IStorageQueryResultBase that the StorageDataSource obtains its items from. Instead of IStorageQueryResultBase, you can also pass one of these string values: Music, Pictures, Videos, Documents. + * @param options The set of properties and values to apply to the new StorageDataSource. Properties on this object may include: mode , requestedThumbnailSize , thumbnailOptions , synchronous . + **/ + constructor(query: any, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Draws the thumbnail for the specified item to the specified img element. + * @param item The item to retrieve the thumbnail for. + * @param image The img element that will display the thumbnail. + * @returns A Promise that completes when the full-quality thumbnail is visible. + **/ + loadThumbnail(item: IItem, image: HTMLImageElement): Promise; + + //#endregion Methods + + } + + /** + * Prevents a DOM sub-tree from receiving tab navigations and focus. + **/ + class TabContainer { + //#region Constructors + + /** + * Creates a new TabContainer. + * @constructor + * @param element The DOM element that hosts the TabContainer control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this TabContainer. Call this method when the TabContainer is no longer needed. After calling this method, the TabContainer becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the child DOM element that receives tab focus. + **/ + childFocus: HTMLElement; + + /** + * Gets or sets the tab index of this container. + **/ + tabIndex: number; + + //#endregion Properties + + } + + /** + * A control that lets the user switch an option between two states: on (checked is set to true) and off (checked is set to false). + **/ + class ToggleSwitch { + //#region Constructors + + /** + * Creates a new ToggleSwitch. + * @constructor + * @param element The DOM that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the change event, add a property named "onchange" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ToggleSwitch control is flipped to on (checked == true) or off (checked == false). + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this ToggleSwitch. Call this method when the ToggleSwitch is no longer needed. After calling this method, the ToggleSwitch becomes unusable. + **/ + dispose(): void; + + /** + * Handles the specified event. + * @param event The event. + **/ + handleEvent(event: any): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the control is on or off. + **/ + checked: boolean; + + /** + * Gets or sets a value that specifies whether the control is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the ToggleSwitch. + **/ + element: HTMLElement; + + /** + * Gets or sets the text that displays when the ToggleSwitch is off (checked is set to false). + **/ + labelOff: string; + + /** + * Gets or sets the text that displays when the ToggleSwitch is on (checked is set to true). + **/ + labelOn: string; + + /** + * Gets or sets the main text for the ToggleSwitch control. This text is always displayed, regardless of whether the control is switched on or off. + **/ + title: string; + + //#endregion Properties + + } + + /** + * Scales a single child element to fill the available space without resizing it. This control reacts to changes in the size of the container as well as changes in size of the child element. For example, a media query may result in a change in aspect ratio. + **/ + class ViewBox { + //#region Constructors + + /** + * Initializes a new instance of the ViewBox control. + * @constructor + * @param element The DOM element that functions as the scaling box. This element fills 100% of the width and height allotted to it. + * @param options The set of options to be applied initially to the ViewBox control. There are currently no options on this control, and any options included in this parameter are ignored. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this ViewBox. Call this method when the ViewBox is no longer needed. After calling this method, the ViewBox becomes unusable. + **/ + dispose(): void; + + /** + * Forces the ViewBox to update its layout. Use this function when making the ViewBox visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that functions as the scaling box. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + /** + * Serves as the base class for a custom IListDataSource. + **/ + class VirtualizedDataSource { + //#region Constructors + + /** + * Initializes the VirtualizedDataSource base class of a custom data source. + * @constructor + * @param listDataAdapter The object that supplies data to the VirtualizedDataSource. + * @param options An object that can contain properties that specify additional options for the VirtualizedDataSource. It supports these properties: cacheSize. + **/ + constructor(listDataAdapter: IListDataAdapter, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the status of the VirtualizedDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the VirtualizedDataSource object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onstatuschanged", you specify "statuschanged". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. See the VirtualizedDataSource object page for a list of events. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * Returns a new IListDataSource that adds group information to the items of another IListDataSource. + * @param listDataSource The data source for the individual items to group. + * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. + * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. + * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. + * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + **/ + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + + /** + * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. + **/ + function disableAnimations(): void; + + /** + * Used to enable all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be enabled, as the determination is made based on several factors. + **/ + function enableAnimations(): void; + + /** + * Marks a event handler function as being compatible with declarative processing. + * @param handler The handler to be marked as compatible with declarative processing. + * @returns The handler, marked as compatible with declarative processing. + **/ + function eventHandler(handler: any): any; + + /** + * Asynchronously executes a collection of CSS animations on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements to be animated. This parameter can be expressed in several ways: As the special value "undefined", which means that the animation has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param animation The animation description or an array of animation descriptions to apply to element. An animation description is a JavaScript object with specific properties, listed below. There are two types of animation descriptions: one for keyframe-based animations and one for explicit animations. These types are distinguished by whether the keyframe property has a defined value. The following properties are required for both types of animation descriptions: property (string), delay (number), duration (number), timing (string). If an animation has a keyframe property with a defined, non-null value, then the animation is a keyframe-based animation. A keyframe-based animation description requires the following property in addition to those mentioned above: keyframe (string). If an animation does not have a keyframe property, or if the value of the property is null or undefined, then the animation is an explicit animation. An explicit animation description requires the following properties in addition to the common properties mentioned above: from, to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise object that completes when the CSS animation is complete. + **/ + function executeAnimation(element: HTMLElement, animation: any): Promise; + + /** + * Asynchronously executes a collection of CSS transitions on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements on which to perform the transition. This parameter can be expressed in several ways: As the special value "undefined", which means that the transition has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param transition The transition description or an array of transition descriptions to apply to element. A transition description is a JavaScript object with these properties: property (string), delay (number), duration (number), timing (string), from (optional), to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise that completes when the transition is finished. + **/ + function executeTransition(element: HTMLElement, transition: any): Promise; + + /** + * Retrieves the items in the specified index range. + * @param dataSource The data source that contains the items to retrieve. + * @param ranges An array of ISelectionRange objects that have firstIndex and lastIndex values. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + function getItemsFromRanges(dataSource: IListDataSource, ranges: ISelectionRange[]): Promise>; + + /** + * Determines whether the Animations Library and ListView animations will be performed if called. + * @returns Returns true if animations will be performed; otherwise false. + **/ + function isAnimationEnabled(): boolean; + + /** + * Applies declarative control binding to all elements, starting at the specified root element. + * @param rootElement The element at which to start applying the binding. If this parameter is not specified, the binding is applied to the entire document. + * @param skipRoot If true, the elements to be bound skip the specified root element and include only the children. + * @returns A promise that is fulfilled when binding has been applied to all the controls. + **/ + function processAll(rootElement?: Element, skipRoot?: boolean): Promise; + + /** + * Applies declarative control binding to the specified element. + * @param element The element to bind. + * @returns A promise that is fulfilled after the control is activated. The value of the promise is the control that is attached to element. + **/ + function process(element: Element): Promise; + + /** + * Walks the DOM tree from the given element to the root of the document. Whenever a selector scope is encountered, this method performs a lookup within that scope for the specified selector string. The first matching element is returned. + * @param selector The selector string. + * @param element The element to begin walking to the root of the document from. + * @returns The target element, if found. + **/ + function scopedSelect(selector: string, element: HTMLElement): HTMLElement; + + /** + * Given a DOM element and a control, attaches the control to the element. + * @param element Element to associate with the control. + * @param control The control to attach to the element. + **/ + function setControl(element: HTMLElement, control: any): void; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If name of the options property begins with "on", the property value is a function and the control supports addEventListener. setControl calls addEventListener on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + function setOptions(control: any, options?: any): void; + + //#endregion Functions + +} +/** + * Provides functions to load HTML content programmatically. +**/ +declare module WinJS.UI.Fragments { + //#region Functions + + /** + * Starts loading the fragment at the specified location. The returned promise completes when the fragment is ready to be copied. + * @param href The URI that contains the fragment to be copied. + * @returns A promise that is fulfilled when the fragment has been prepared for copying. + **/ + function cache(href: string): Promise; + + /** + * Removes any cached information about the specified fragment. This method does not unload any scripts or styles that are referenced by the fragment. + * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. + **/ + function clearCache(href: string): void; + + /** + * Loads the contents of the specified URI into the specified element without copying it. + * @param href The URI that contains the fragment to copy. + * @param element Optional. The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The element is not added to the cache. See also rendercopy, where the element is added to the cache. + **/ + function render(href: string, element?: HTMLElement): Promise; + + /** + * Loads and copies the contents of the specified URI into the specified element. + * @param href The URI that contains the fragment to copy. + * @param target The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. + **/ + function renderCopy(href: string, target?: HTMLElement): Promise; + + //#endregion Functions + +} +/** + * Provides methods for defining and displaying PageControl objects. +**/ +declare module WinJS.UI.Pages { + //#region Interfaces + + /** + * Provides members for a PageControl. You implement this interface when defining a new PageControl. + **/ + interface IPageControlMembers { + //#region Methods + + /** + * Called if any error occurs during the processing of the page. + * @param err The error that occurred. + * @returns Nothing if the error was handled, or an error promise if the error was not handled. + **/ + error? (err: any): Promise; + + /** + * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + init? (element: HTMLElement, options: any): Promise; + + /** + * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. + * @param uri The URI from which to create DOM objects. + * @returns A promise whose fulfilled value is the set of unparented DOM objects. + **/ + load? (uri: string): Promise; + + /** + * Initializes the control after the content of the control is set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options that are to be passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + processed? (element: HTMLElement, options: any): Promise; + + /** + * Called after all initialization and rendering is complete. At this time, the element is ready for use. + * @param element The DOM element that contains all the content for the page. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. + **/ + ready? (element: HTMLElement, options: any): Promise; + + /** + * Takes the elements returned by the load method and attaches them to the specified element. + * @param element The DOM element to which the loadResult elements are appended. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param loadResult A Promise that contains the elements returned from the load method. + **/ + render? (element: HTMLElement, options: any, loadResult: Promise): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. + **/ + class PageControl { + } + + //#endregion Objects + + //#region Functions + + /** + * Creates a new PageControl from the specified URI that contains the specified members. Multiple calls to this method for the same URI are allowed, and all members will be merged. + * @param uri The URI for the content that defines the page. + * @param members An object that defines the members that the control will have. + * @returns A constructor function that creates the PageControl. + **/ + function define(uri: string, members: IPageControlMembers): PageControl; + + /** + * Gets an already-defined page control for the specified URI, or creates a new one. + * @param uri The URI for the content that defines the page. + * @returns A constructor function that creates the page. + **/ + function get(uri: string): Function; + + /** + * Creates a PageControl from the specified URI and inserts it inside the specified element. + * @param uri The URI for the content that defines the page. + * @param element The DOM element to which the PageControl is appended. + * @param options An object that contains one or more property/value pairs to apply to the new PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. + * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + + //#endregion Functions + +} +/** + * Provides methods for detecting when the user tabs to or from DOM elements. +**/ +declare module WinJS.UI.TrackTabBehavior { + //#region Functions + + /** + * Sets the tab order for the specified element within its container. + * @param element The element to update. + * @param tabIndex The index value of the element within its container. + **/ + function attach(element: HTMLElement, tabIndex: number): void; + + /** + * Removes the tab order information from the specified element. + * @param element The element to remove tab information from. + **/ + function detatch(element: HTMLElement): void; + + //#endregion Functions + +} +/** + * Provides helper functions, for example, functions to add and remove CSS classes. +**/ +declare module WinJS.Utilities { + //#region Enumerations + + /** + * Defines a set of keyboard values. + **/ + enum Key { + /** + * The BACKSPACE key. + **/ + backspace, + /** + * The TAB key. + **/ + tab, + /** + * The ENTER key. + **/ + enter, + /** + * The SHIFT key. + **/ + shift, + /** + * The CTRL key. + **/ + ctrl, + /** + * The ALT key. + **/ + alt, + /** + * The PAUSE key. + **/ + pause, + /** + * The CAPS LOCK key. + **/ + capsLock, + /** + * The ESCAPE key. + **/ + escape, + /** + * The SPACE key. + **/ + space, + /** + * The PAGE UP key. + **/ + pageUp, + /** + * The PAGE DOWN key. + **/ + pageDown, + /** + * The END key. + **/ + end, + /** + * The HOME key. + **/ + home, + /** + * The LEFT ARROW key. + **/ + leftArrow, + /** + * The UP ARROW key. + **/ + upArrow, + /** + * The RIGHT ARROW key. + **/ + rightArrow, + /** + * The DOWN ARROW key. + **/ + downArrow, + /** + * The INSERT key. + **/ + insert, + /** + * The DELETE key. + **/ + deleteKey, + /** + * The 0 key. + **/ + num0, + /** + * The 1 key. + **/ + num1, + /** + * The 2 key. + **/ + num2, + /** + * The 3 key. + **/ + num3, + /** + * The 4 key. + **/ + num4, + /** + * The 5 key. + **/ + num5, + /** + * The 6 key. + **/ + num6, + /** + * The 7 key. + **/ + num7, + /** + * The 8 key. + **/ + num8, + /** + * The 9 key. + **/ + num9, + /** + * The a key. + **/ + a, + /** + * The b key. + **/ + b, + /** + * The c key. + **/ + c, + /** + * The d key. + **/ + d, + /** + * The e key. + **/ + e, + /** + * The f key. + **/ + f, + /** + * The g key. + **/ + g, + /** + * The h key. + **/ + h, + /** + * The i key. + **/ + i, + /** + * The j key. + **/ + j, + /** + * The k key. + **/ + k, + /** + * The l key. + **/ + l, + /** + * The m key. + **/ + m, + /** + * The n key. + **/ + n, + /** + * The o key. + **/ + o, + /** + * The p key. + **/ + p, + /** + * The q key. + **/ + q, + /** + * The r key. + **/ + r, + /** + * The s key. + **/ + s, + /** + * The t key. + **/ + t, + /** + * The u key. + **/ + u, + /** + * The v key. + **/ + v, + /** + * The w key. + **/ + w, + /** + * The x key. + **/ + x, + /** + * The y key. + **/ + y, + /** + * The z key. + **/ + z, + /** + * The left Windows key. + **/ + leftWindows, + /** + * The right Windows key. + **/ + rightWindows, + /** + * The menu key. + **/ + menu, + /** + * The 0 key on the numerical keypad. + **/ + numPad0, + /** + * The 1 key on the numerical keypad. + **/ + numPad1, + /** + * The 2 key on the numerical keypad. + **/ + numPad2, + /** + * The 3 key on the numerical keypad. + **/ + numPad3, + /** + * The 4 key on the numerical keypad. + **/ + numPad4, + /** + * The 5 key on the numerical keypad. + **/ + numPad5, + /** + * The 6 key on the numerical keypad. + **/ + numPad6, + /** + * The 7 key on the numerical keypad. + **/ + numPad7, + /** + * The 8 key on the numerical keypad. + **/ + numPad8, + /** + * The 9 key on the numerical keypad. + **/ + numPad9, + /** + * The multiplication key (*). + **/ + multiply, + /** + * The addition key (+). + **/ + add, + /** + * The subtraction key (-). + **/ + subtract, + /** + * The decimal point key (.) + **/ + decimalPoint, + /** + * The division key (/). + **/ + divide, + /** + * The F1 key. + **/ + F1, + /** + * The F2 key. + **/ + F2, + /** + * The F3 key. + **/ + F3, + /** + * The F4 key. + **/ + F4, + /** + * The F5 key. + **/ + F5, + /** + * The F6 key. + **/ + F6, + /** + * The F7 key. + **/ + F7, + /** + * The F8 key. + **/ + F8, + /** + * The F9 key. + **/ + F9, + /** + * The F10 key. + **/ + F10, + /** + * The F11 key. + **/ + F11, + /** + * The F12 key. + **/ + F12, + /** + * The NUMBER LOCK key. + **/ + numLock, + /** + * The SCROLL LOCK key. + **/ + scrollLock, + /** + * The browser BACK key. + **/ + browserBack, + /** + * The browser FORWARD key. + **/ + browserForward, + /** + * The semicolon key (;). + **/ + semicolon, + /** + * The equals key (=). + **/ + equal, + /** + * The comma key (,). + **/ + comma, + /** + * The dash key (-). + **/ + dash, + /** + * The period key (.). + **/ + period, + /** + * The forward slash key (/). + **/ + forwardSlash, + /** + * The grave accent key (`). + **/ + graveAccent, + /** + * The open bracket key ([). + **/ + openBracket, + /** + * The backslash key (\). + **/ + backSlash, + /** + * The close bracket key (]). + **/ + closeBracket, + /** + * The single quote key ('). + **/ + singleQuote + } + + //#endregion Enumerations + + //#region Objects + + /** + * A mixin that contains event-related functions. + **/ + var eventMixin: { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + }; + + /** + * Represents the result of a query selector, and provides various operations that perform actions over the elements of the collection. + **/ + interface QueryCollection extends Array { + //#region Methods + + /** + * Adds the specified class to all the elements in the collection. + * @param name The name of the class to add. + * @returns This QueryCollection object. + **/ + addClass(name: string): QueryCollection; + + /** + * Creates a QueryCollection that contains the children of the specified parent element. + * @param element The parent element. + * @returns The QueryCollection that contains the children of the element. + **/ + children(element: HTMLElement): QueryCollection; + + /** + * Clears the specified style property for all the elements in the collection. + * @param name The name of the style property to be cleared. + * @returns This QueryCollection object. + **/ + clearStyle(name: string): QueryCollection; + + /** + * Creates controls that are attached to the elements in this QueryCollection, if the ctor parameter is a function, or configures the controls that are attached to the elements in this QueryCollection, if the ctor parameter is an object. + * @param ctor If this parameter is a function, it is a constructor function that is used to create controls to attach to the elements. If it is an object, it is the set of options passed to the controls. + * @param options The options passed to the newly-created controls. + * @returns This QueryCollection object. + **/ + control(ctor: any, options?: any): QueryCollection; + + /** + * Performs an action on each item in the QueryCollection. + * @param callbackFn The action to perform on each item. + * @param thisArg The argument to bind to callbackFn. + * @returns The QueryCollection. + **/ + forEach(callbackFn: (value: T, index: number, array: T[]) => void, thisArg?: any): QueryCollection; + + /** + * Gets an item from the QueryCollection. + * @param index The index of the item to return. + * @returns A single item from the collection. + **/ + get(index: number): T; + + /** + * Gets an attribute value from the first element in the collection. + * @param name The name of the attribute. + * @returns The value of the attribute. + **/ + getAttribute(name: string): any; + + /** + * Determines whether the specified class exists on the first element of the collection. + * @param name The name of the class. + * @returns true if the element has the specified class; otherwise, false. + **/ + hasClass(name: string): boolean; + + /** + * Looks up an element by ID and wraps the result in a QueryCollection. + * @param id The ID of the element. + * @returns A QueryCollection that contains the element, if it is found. + **/ + id(id: string): QueryCollection; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T): void; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T[]): void; + + /** + * Registers the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function to be called when the event occurs. + * @param capture true if capture == true is to be passed to addEventListener; otherwise, false. + **/ + listen(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Executes a query selector on all the elements in the collection and aggregates the result into a QueryCollection. + * @param query The query selector string. + * @returns A QueryCollection object containing the aggregate results of executing the query on all the elements in the collection. + **/ + query(query: any): QueryCollection; + + /** + * Removes the specified class from all the elements in the collection. + * @param name The name of the class to be removed. + * @returns his QueryCollection object. + **/ + removeClass(name: string): QueryCollection; + + /** + * Unregisters the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function. + * @param capture true if capture == true; otherwise, false. + * @returns This QueryCollection object. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): QueryCollection; + + /** + * Sets an attribute value on all the items in the collection. + * @param name The name of the attribute to be set. + * @param value The value of the attribute to be set. + * @returns This QueryCollection object. + **/ + setAttribute(name: string, value: any): QueryCollection; + + /** + * Sets the specified style property for all the elements in the collection. + * @param name The name of the style property. + * @param value The value for the property. + * @returns This QueryCollection object. + **/ + setStyle(name: string, value: any): QueryCollection; + + /** + * Renders a template that is bound to the given data and parented to the elements included in the QueryCollection. If the QueryCollection contains multiple elements, the template is rendered multiple times, once at each element in the QueryCollection per item of data passed. + * @param templateElement The DOM element to which the template control is attached. + * @param data The data to render. If the data is an array (or any other object that has a forEach method) then the template is rendered multiple times, once for each item in the collection. + * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. + * @returns The QueryCollection. + **/ + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + + /** + * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. + * @param name The name of the class to be toggled. + * @returns This QueryCollection object. + **/ + toggleClass(name: string): QueryCollection; + + //#endregion Methods + + } + + /** + * Constructor support for QueryCollection interface + **/ + export var QueryCollection: { + new (items: T[]): QueryCollection; + prototype: QueryCollection; + } + + //#endregion Objects + + //#region Functions + + /** + * Adds the specified class to the specified element. + * @param e The element to which to add the class. + * @param name The name of the class to add. + * @returns The element. + **/ + function addClass(e: T, name: string): T; + + /** + * Gets a collection of elements that are the direct children of the specified element. + * @param element The parent element. + * @returns The collection of children of the element. + **/ + function children(element: HTMLElement): QueryCollection; + + /** + * Converts a CSS positioning string for the specified element to pixels. + * @param element The element. + * @param value The CSS positioning string. + * @returns The number of pixels. + **/ + function convertToPixels(element: HTMLElement, value: string): number; + + /** + * Creates an object that has one event for each name passed to the function. + * @param events A variable list of property names. + * @returns The object with the specified properties. The names of the properties are prefixed with 'on'. + **/ + function createEventProperties(...events: string[]): any; + + /** + * Gets the data value associated with the specified element. + * @param element The element. + * @returns The value associated with the element. + **/ + function data(element: HTMLElement): any; + + /** + * Disposes all first-generation disposable elements that are descendents of the specified element. The specified element itself is not disposed. + * @param element The root element whose sub-tree is to be disposed. + **/ + function disposeSubTree(element: HTMLElement): void; + + /** + * Removes all the child nodes from the specified element. + * @param element The element. + * @returns The element. + **/ + function empty(element: T): T; + + /** + * Determines whether the specified event occurred within the specified element. + * @param element The element. + * @param event The event. + * @returns true if the event occurred within the element; otherwise, false. + **/ + function eventWithinElement(element: HTMLElement, event: Event): boolean; + + /** + * Adds tags and type to a logging message. + * @param message The message to be formatted. + * @param tag The tag(s) to be applied to the message. Multiple tags should be separated by spaces. + * @param type The type of the message. + * @returns The formatted message. + **/ + function formatLog(message: string, tag: string, type: string): string; + + /** + * Gets the height of the content of the specified element. The content height does not include borders or padding. + * @param element The element. + * @returns The content height of the element. + **/ + function getContentHeight(element: HTMLElement): number; + + /** + * Gets the width of the content of the specified element. The content width does not include borders or padding. + * @param element The element. + * @returns The content width of the element. + **/ + function getContentWidth(element: HTMLElement): number; + + /** + * Gets the leaf-level type or namespace specified by the name parameter. + * @param name The name of the member. + * @param root The root to start in. Defaults to the global object. + * @returns The leaf-level type or namespace in the specified parent namespace. + **/ + function getMember(name: string, root?: any): any; + + /** + * Gets the position of the specified element. + * @param element The element. + * @returns An object that contains the left, top, width and height properties of the element. + **/ + function getPosition(element: HTMLElement): IPosition; + + /** + * Gets the left coordinate of the specified element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative left coordinate. + **/ + function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the top coordinate of the element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative top coordinate. + **/ + function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the height of the element, including its margins. + * @param element The element. + * @returns The height of the element including margins. + **/ + function getTotalHeight(element: HTMLElement): number; + + /** + * Gets the width of the element, including margins. + * @param element The element. + * @returns The width of the element including margins. + **/ + function getTotalWidth(element: HTMLElement): number; + + /** + * Determines whether the specified element has the specified class. + * @param e The element. + * @param name The name of the class. + * @returns true if the element has the class, otherwise false. + **/ + function hasClass(e: HTMLElement, name: string): boolean; + + /** + * Returns a collection with zero or one elements matching the specified id. + * @param id The ID of the element (or elements). + * @returns A collection of elements whose id matches the id parameter. + **/ + function id(id: string): QueryCollection; + + /** + * Calls insertAdjacentHTML on the specified element. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text The text to insert. + **/ + function insertAdjacentHTML(element: HTMLElement, position: string, text: string): void; + + /** + * Calls insertAdjacentHTML on the specified element in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text Value to be provided to insertAdjacentHTML. + **/ + function insertAdjacentHTMLUnsafe(element: HTMLElement, position: string, text: string): void; + + /** + * Attaches the default dispose API wrapping the dispose implementation to the specified element. + * @param element The element to mark as disposable. + * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. + **/ + function markDisposable(element: HTMLElement, disposeImpl: Function): void; + + /** + * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. + * @param func The function to be marked as compatible with declarative processing. + * @returns The input function, marked as compatible with declarative processing. + **/ + function markSupportedForProcessing(func: U): U; + + /** + * Returns a QueryCollection with zero or one elements matching the specified selector query. + * @param query The CSS selector to use. See Selectors for more information. + * @param element Optional. The root element at which to start the query. If this parameter is omitted, the scope of the query is the entire document. + * @returns A QueryCollection with zero or one elements matching the specified selector query. + **/ + function query(query: any, element?: HTMLElement): QueryCollection; + + /** + * Ensures that the specified function executes only after the DOMContentLoaded event has fired for the current page. The DOMContentLoaded event occurs after the page has been parsed but before all the resources are loaded. + * @param callback A function that executes after the DOMContentLoaded event has occurred. + * @param async If true, the callback should be executed asynchronously. + * @returns A promise that completes after the DOMContentLoaded event has occurred. + **/ + function ready(callback?: Function, async?: boolean): Promise; + + /** + * Removes the specified class from the specified element. + * @param e The element from which to remove the class. + * @param name The name of the class to remove. + * @returns The element. + **/ + function removeClass(e: T, name: string): T; + + /** + * Asserts that the value is compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. If the value is not compatible, and strictProcessing is on, an exception is thrown. All functions that have been declared using WinJS.Class.define, WinJS.Class.derive, WinJS.UI.Pages.define, or WinJS.Binding.converter are automatically marked as supported for declarative processing. Any other function that you use from a declarative context (that is, a context in which an HTML element has a data-win-control or data-win-options attribute) must be marked manually by calling this function. When you mark a function as supported for declarative processing, you are guaranteeing that the code in the function is secure from injection of third-party content. + * @param value The value to be tested for compatibility with declarative processing. If the value is a function it must be marked with a property supportedForProcessing with a value of true when strictProcessing is on. For more information, see WinJS.Utilities.markSupportedForProcessing. + * @returns The input value. + **/ + function requireSupportedForProcessing(value: T): T; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTML(element: HTMLElement, text: string): void; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTML(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Configures a logger that writes messages containing the specified tags to the JavaScript console. + * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. + **/ + function startLog(options?: ILogOptions): void; + + /** + * Removes the WinJS logger that had previously been set up. + **/ + function stopLog(): void; + + /** + * Toggles (adds or removes) the specified class on the specified element. If the class is present, it is removed; if it is absent, it is added. + * @param e The element on which to toggle the class. + * @param name The name of the class to toggle. + * @returns The element. + **/ + function toggleClass(e: T, name: string): T; + + //#endregion Functions + + //#region Properties + + /** + * Gets whether the current script context has access to WinRT APIs. + **/ + var hasWinRT: boolean; + + /** + * Indicates whether the app is running on Windows Phone. + **/ + var isPhone: boolean; + + //#endregion Properties + + //#region Interfaces + + interface ILogOptions { + type: string; + action?: (message: string, tags: string, type: string) => void; + excludeTags: string; + tags: string; + } + + interface IPosition { + left: number; + top: number; + width: number; + height: number; + } + + //#endregion Interfaces + +} +/** + * Provides functions and objects for scheduling and managing asynchronous tasks. +**/ +declare module WinJS.Utilities.Scheduler { + //#region Enumerations + + /** + * Represents a priority for a job managed by the Scheduler. + **/ + enum Priority { + /** + * A priority higher than the normal priority level. + **/ + aboveNormal, + /** + * A priority less than the normal priority level. + **/ + belowNormal, + /** + * A high priority. + **/ + high, + /** + * The idle priority for work items. + **/ + idle, + /** + * The highest priority. + **/ + max, + /** + * The lowest priority. + **/ + min, + /** + * The normal priority for work items. + **/ + normal + } + + //#endregion Enumerations + + //#region Interfaces + + /** + * Represents a work item that's executed by the Scheduler. + **/ + interface IJob { + //#region Methods + + /** + * Cancels the job. + **/ + cancel(): void; + + /** + * Pauses the job. + **/ + pause(): void; + + /** + * Resumes the job. + **/ + resume(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets a value that indicates whether the job has successfully completed. + **/ + completed: boolean; + + /** + * Gets the unique numeric identifier assigned to the job. + **/ + id: number; + + /** + * Gets or sets the name of the job. + **/ + name: string; + + /** + * Gets or sets the owner of the job. + **/ + owner: IOwnerToken; + + /** + * Gets or sets the priority of the job. + **/ + priority: Priority; + + //#endregion Properties + + } + + /** + * Provides a control mechanism that allows a job to cooperatively yield. This object is passed to your work function when you schedule it. + **/ + interface IJobInfo { + //#region Methods + + /** + * Uses a Promise to determine how long the scheduler should wait before rescheduling the job after it yields. + * @param promise Once the work item yields, the scheduler will wait for this Promise to complete before rescheduling the job. + **/ + setPromise(promise: Promise): void; + + /** + * Specifies the next unit of work to run once this job yields. + * @param work The next unit of work to run once this job yields. + **/ + setWork(work: Function): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the work item associated with this IJobInfo. + **/ + job: IJob; + + /** + * Gets a value that specifies whether the job should yield. + **/ + shouldYield: boolean; + + //#endregion Properties + + } + + /** + * Represents an object that owns jobs. You can use this object to cancel a set of jobs. + **/ + interface IOwnerToken { + //#region Methods + + /** + * Synchronously cancels the job that this token owns, including paused and blocked jobs. + **/ + cancelAll(): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Functions + + /** + * Creates and returns a new IOwnerToken which can be set to the owner property of one or more jobs. + * @returns A new IOwnerToken which can be set to the owner property of one or more jobs. + **/ + function createOwnerToken(): IOwnerToken; + + /** + * Runs the specified callback in a high priority context. + * @param callback The callback to run in a high priority callback. + * @returns The return value of the callback. + **/ + function execHigh(callback: () => U): U; + + /** + * Returns a string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. + * @returns A string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. + **/ + function retrieveState(): string; + + /** + * Runs jobs in the scheduler without timeslicing until all jobs at the specified priority and higher have executed. + * @param priority The priority to which the scheduler should drain. The default is -15. + * @param name An optional description of the drain request for diagnostics. + * @returns A Promise which completes when the drain has finished. Canceling this Promise cancels the drain request. This Promise will never enter an error state. + **/ + function requestDrain(priority?: Priority, name?: string): Promise; + + /** + * Schedules the specified function to execute asynchronously. + * @param work A function that represents the work item to be scheduled. When called the work item will receive as its first argument an object which allows the work item to ask the scheduler if it should yield cooperatively and if so allows the work item to either provide a function to be run as a continuation or a WinJS.Promise which will when complete provide a function to run as a continuation. Provide these fields for the object: shouldYield, setWork(work), setPromise(promise), job. + * @param priority The priority of the work item. If you don't specify a priority, it defaults to WinJS.Utilities.Scheduler.Priority.normal. + * @param thisArg A "this" instance to be bound to the work item. The default value is null. + * @param name A description of the work item for diagnostics. The default value is an empty string. + * @returns The job instance that represents this work item. + **/ + function schedule(work: (jobInfo: IJobInfo) => any, priority?: Priority, thisArg?: any, name?: string): IJob; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.aboveNormal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of aboveNormal priority. + **/ + function schedulePromiseAboveNormal(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.belowNormal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of belowNormal priority. + **/ + function schedulePromiseBelowNormal(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.high priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of high priority. + **/ + function schedulePromiseHigh(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.Idle priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of idle priority. + **/ + function schedulePromiseIdle(promiseValue?: U, jobName?: string): Promise; + + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.normal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of normal priority. + **/ + function schedulePromiseNormal(promiseValue?: U, jobName?: string): Promise; + + //#endregion Functions + +} diff --git a/winjs/winjs.d.ts b/winjs/winjs.d.ts index 20263a3bb9..811e4893fd 100644 --- a/winjs/winjs.d.ts +++ b/winjs/winjs.d.ts @@ -18,8367 +18,8294 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ -/// - /** * Defines an Element object. **/ interface Element { - winControl: any; // TODO: This should be control? -}/** + winControl: any; // TODO: This should be control? +} + +/** + * Utility class for easy access to operations on application folders +**/ +interface IOHelper { + /** + * Determines whether the specified file exists in the folder. + * @param filename The name of the file. + * @returns A promise that completes with a value of either true (if the file exists) or false. + **/ + exists(filename: string): WinJS.Promise; + + /** + * Reads the specified file. If the file doesn't exist, the specified default value is returned. + * @param fileName The file to read from. + * @param def The default value to be returned if the file failed to open. + * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. + **/ + readText(fileName: string, def?: string): WinJS.Promise; + + /** + * Deletes a file from the folder. + * @param fileName The file to be deleted. + * @returns A promise that is fulfilled when the file has been deleted. + **/ + remove(fileName: string): WinJS.Promise; + + /** + * Writes the specified text to the specified file. + * @param fileName The name of the file. + * @param text The content to be written to the file. + * @returns A promise that completes with a value that is the number of characters written. + **/ + writeText(fileName: string, text: string): WinJS.Promise; +} + +/** * Provides application-level functionality, for example activation, storage, and application events. **/ declare module WinJS.Application { - //#region Objects + //#region Objects - /** - * The local storage of the application. - **/ - var local: { - //#region Methods + /** + * The local storage of the application. + **/ + var local: IOHelper; - /** - * Determines whether the specified file exists in the folder. - * @param filename The name of the file. - * @returns A promise that completes with a value of either true (if the file exists) or false. - **/ - exists(filename: string): Promise; + /** + * The roaming storage of the application. + **/ + var roaming: IOHelper; - /** - * Reads the specified file. If the file doesn't exist, the specified default value is returned. - * @param fileName The file to read from. - * @param def The default value to be returned if the file failed to open. - * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. - **/ - readText(fileName: string, def?: string): Promise; + /** + * The temp storage of the application. + **/ + var temp: IOHelper; - /** - * Deletes a file from the folder. - * @param fileName The file to be deleted. - * @returns A promise that is fulfilled when the file has been deleted. - **/ - remove(fileName: string): Promise; + /** + * An object used for storing app information that can be used to restore the app's state after it has been suspended and then resumed. Data that can usefully be contained in this object includes the current navigation page or any information the user has added to the input controls on the page. You should not add information about customization (for example colors) or user-defined lists of content. + **/ + var sessionState: any; - /** - * Writes the specified text to the specified file. - * @param fileName The name of the file. - * @param text The content to be written to the file. - * @returns A promise that completes with a value that is the number of characters written. - **/ - writeText(fileName: string, text: string): Promise; + //#endregion Objects - //#endregion Methods + //#region Methods - }; + /** + * Informs the application object that asynchronous work is being performed, and that this event handler should not be considered complete until the promise completes. This function can be set inside the handlers for all WinJS.Application events: onactivated oncheckpoint onerror onloaded onready onsettings onunload. + * @param promise The promise that should complete before processing is complete. + **/ + function setPromise(promise: Promise): void; - /** - * The roaming storage of the application. - **/ - var roaming: { - //#region Methods + //#endregion Methods - /** - * Determines whether the specified file exists in the folder. - * @param filename The name of the file. - * @returns A promise that completes with a value of either true (if the file exists) or false. - **/ - exists(filename: string): Promise; + //#region Functions - /** - * Reads the specified file. If the file doesn't exist, the specified default value is returned. - * @param fileName The file to read from. - * @param def The default value to be returned if the file failed to open. - * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. - **/ - readText(fileName: string, def?: string): Promise; + /** + * Adds an event listener for application-level events: activated, checkpoint, error, loaded, ready, settings, and unload. + * @param type The type (name) of the event. You can use any of the following:"activated", "checkpoint", "error", "loaded", "ready", "settings", and" unload". + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + function addEventListener(type: string, listener: Function, capture?: boolean): void; - /** - * Deletes a file from the folder. - * @param fileName The file to be deleted. - * @returns A promise that is fulfilled when the file has been deleted. - **/ - remove(fileName: string): Promise; + /** + * Queues a checkpoint event. + **/ + function checkpoint(): void; - /** - * Writes the specified text to the specified file. - * @param fileName The name of the file. - * @param text The content to be written to the file. - * @returns A promise that completes with a value that is the number of characters written. - **/ - writeText(fileName: string, text: string): Promise; + /** + * Queues an event to be processed by the WinJS.Application event queue. + * @param eventRecord The event object is expected to have a type property that is used as the event name when dispatching on the WinJS.Application event queue. The entire object is provided to event listeners in the detail property of the event. + **/ + function queueEvent(eventRecord: any): void; - //#endregion Methods + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: any): void; - }; + /** + * Starts dispatching application events (the activated, checkpoint, error, loaded, ready, settings, and unload events). + **/ + function start(): void; - /** - * An object used for storing app information that can be used to restore the app's state after it has been suspended and then resumed. Data that can usefully be contained in this object includes the current navigation page or any information the user has added to the input controls on the page. You should not add information about customization (for example colors) or user-defined lists of content. - **/ - var sessionState: any; + /** + * Stops application event processing and resets WinJS.Application to its initial state. All WinJS.Application event listeners (for the activated, checkpoint, error, loaded, ready, settings, and unload events) are removed. + **/ + function stop(): void; - /** - * The temp storage of the application. - **/ - var temp: { - //#region Methods + //#endregion Functions - /** - * Determines whether the specified file exists in the folder. - * @param filename The name of the file. - * @returns A promise that completes with a value of either true (if the file exists) or false. - **/ - exists(filename: string): Promise; + //#region Events - /** - * Reads the specified file. If the file doesn't exist, the specified default value is returned. - * @param fileName The file to read from. - * @param def The default value to be returned if the file failed to open. - * @returns A promise that completes with a value that is either the contents of the file, or the specified default value. - **/ - readText(fileName: string, def?: string): Promise; + /** + * Occurs when WinRT activation has occurred. The name of this event is "activated" (and also "mainwindowactivated"). This event occurs after the loaded event and before the ready event. + * @param eventInfo An object that contains information about the event. For more information about event arguments, see the WinRT event argument classes: WebUICachedFileUpdaterActivatedEventArgs, WebUICameraSettingsActivatedEventArgs, WebUIContactPickerActivatedEventArgs, WebUIDeviceActivatedEventArgs, WebUIFileActivatedEventArgs, WebUIFileOpenPickerActivatedEventArgs, WebUIFileSavePickerActivatedEventArgs, WebUILaunchActivatedEventArgs, WebUIPrintTaskSettingsActivatedEventArgs, WebUIProtocolActivatedEventArgs, WebUISearchActivatedEventArgs, WebUIShareTargetActivatedEventArgs. + **/ + function onactivated(eventInfo: CustomEvent): void; - /** - * Deletes a file from the folder. - * @param fileName The file to be deleted. - * @returns A promise that is fulfilled when the file has been deleted. - **/ - remove(fileName: string): Promise; + /** + * Occurs when receiving PLM notification or when the checkpoint function is called. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function oncheckpoint(eventInfo: CustomEvent): void; - /** - * Writes the specified text to the specified file. - * @param fileName The name of the file. - * @param text The text to write. - * @returns A Promise that completes with the number of bytes successfully written to the file. - **/ - writeText(fileName: string, text: string): Promise; + /** + * Occurs when an unhandled error has been raised. + * @param eventInfo An object that contains information about the event. + **/ + function onerror(eventInfo: CustomEvent): void; - //#endregion Methods + /** + * Occurs after the DOMContentLoaded event, which fires after the page has been parsed but before all the resources are loaded. This event occurs before the activated event and the ready event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. + **/ + function onloaded(eventInfo: CustomEvent): void; - }; + /** + * Occurs when the application is ready. This event occurs after the loaded event and the activated event. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onready(eventInfo: CustomEvent): void; - //#endregion Objects + /** + * Occurs when the settings charm is invoked. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: type, applicationcommands. + **/ + function onsettings(eventInfo: CustomEvent): void; - //#region Methods + /** + * Occurs when the application is about to be unloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. + **/ + function onunload(eventInfo: CustomEvent): void; - /** - * Informs the application object that asynchronous work is being performed, and that this event handler should not be considered complete until the promise completes. This function can be set inside the handlers for all WinJS.Application events: onactivated oncheckpoint onerror onloaded onready onsettings onunload. - * @param promise The promise that should complete before processing is complete. - **/ - function setPromise(promise: Promise): void; - - //#endregion Methods - - //#region Functions - - /** - * Adds an event listener for application-level events: activated, checkpoint, error, loaded, ready, settings, and unload. - * @param type The type (name) of the event. You can use any of the following:"activated", "checkpoint", "error", "loaded", "ready", "settings", and" unload". - * @param listener The listener to invoke when the event is raised. - * @param capture true to initiate capture, otherwise false. - **/ - function addEventListener(type: string, listener: Function, capture?: boolean): void; - - /** - * Queues a checkpoint event. - **/ - function checkpoint(): void; - - /** - * Queues an event to be processed by the WinJS.Application event queue. - * @param eventRecord The event object is expected to have a type property that is used as the event name when dispatching on the WinJS.Application event queue. The entire object is provided to event listeners in the detail property of the event. - **/ - function queueEvent(eventRecord: any): void; - - /** - * Removes an event listener from the control. - * @param type The type (name) of the event. - * @param listener The listener to remove. - * @param useCapture Specifies whether or not to initiate capture. - **/ - function removeEventListener(type: string, listener: Function, useCapture?: any): void; - - /** - * Starts dispatching application events (the activated, checkpoint, error, loaded, ready, settings, and unload events). - **/ - function start(): void; - - /** - * Stops application event processing and resets WinJS.Application to its initial state. All WinJS.Application event listeners (for the activated, checkpoint, error, loaded, ready, settings, and unload events) are removed. - **/ - function stop(): void; - - //#endregion Functions - - //#region Events - - /** - * Occurs when WinRT activation has occurred. The name of this event is "activated" (and also "mainwindowactivated"). This event occurs after the loaded event and before the ready event. - * @param eventInfo An object that contains information about the event. For more information about event arguments, see the WinRT event argument classes: WebUICachedFileUpdaterActivatedEventArgs, WebUICameraSettingsActivatedEventArgs, WebUIContactPickerActivatedEventArgs, WebUIDeviceActivatedEventArgs, WebUIFileActivatedEventArgs, WebUIFileOpenPickerActivatedEventArgs, WebUIFileSavePickerActivatedEventArgs, WebUILaunchActivatedEventArgs, WebUIPrintTaskSettingsActivatedEventArgs, WebUIProtocolActivatedEventArgs, WebUISearchActivatedEventArgs, WebUIShareTargetActivatedEventArgs. - **/ - function onactivated(eventInfo: CustomEvent): void; - - /** - * Occurs when receiving PLM notification or when the checkpoint function is called. - * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. - **/ - function oncheckpoint(eventInfo: CustomEvent): void; - - /** - * Occurs when an unhandled error has been raised. - * @param eventInfo An object that contains information about the event. - **/ - function onerror(eventInfo: CustomEvent): void; - - /** - * Occurs after the DOMContentLoaded event, which fires after the page has been parsed but before all the resources are loaded. This event occurs before the activated event and the ready event. - * @param eventInfo An object that contains information about the event. The detail property of this object includes the following subproperties: type, setPromise. - **/ - function onloaded(eventInfo: CustomEvent): void; - - /** - * Occurs when the application is ready. This event occurs after the loaded event and the activated event. - * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. - **/ - function onready(eventInfo: CustomEvent): void; - - /** - * Occurs when the settings charm is invoked. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: type, applicationcommands. - **/ - function onsettings(eventInfo: CustomEvent): void; - - /** - * Occurs when the application is about to be unloaded. - * @param eventInfo An object that contains information about the event. The detail property of this object includes the following sub-properties: type, setPromise. - **/ - function onunload(eventInfo: CustomEvent): void; - - //#endregion Events + //#endregion Events } /** * Provides functionality for data and template binding. **/ declare module WinJS.Binding { - //#region Properties - - /** - * Determines whether or not binding should automatically set the ID of an element. This property should be set to true in apps that use WinJS (WinJS) binding. - **/ - var optimizeBindingReferences: boolean; - - //#endregion Properties - - //#region Objects - - /** - * Allows you to add bindable properties dynamically. - **/ - var dynamicObservableMixin: { - //#region Methods - - /** - * Adds a property with change notification to this object, including a ECMAScript5 property definition. - * @param name The name of the property to add. - * @param value This object is returned. - **/ - addProperty(name: string, value: any): void; - - /** - * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. - * @param name The name of the property to which to bind the action. - * @param action The function to invoke asynchronously when the property may have changed. - * @returns This object is returned. - **/ - bind(name: string, action: any): Function; - - /** - * Gets a property value by name. - * @param name The name of the property to get. - * @returns The value of the property as an observable object. - **/ - getProperty(name: string): any; - - /** - * Notifies listeners that a property value was updated. - * @param name The name of the property that is being updated. - * @param newValue The new value for the property. - * @param oldValue The old value for the property. - * @returns A promise that is completed when the notifications are complete. - **/ - notify(name: string, newValue: string, oldValue: string): Promise; - - /** - * Removes a property value. - * @param name The name of the property to remove. - * @returns This object is returned. - **/ - removeProperty(name: string): any; - - /** - * Updates a property value and notifies any listeners. - * @param name The name of the property to update. - * @param value The new value of the property. - * @returns This object is returned. - **/ - setProperty(name: string, value: any): any; - - /** - * Removes one or more listeners from the notification list for a given property. - * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. - * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. - * @returns This object is returned. - **/ - unbind(name: string, action: Function): any; - - /** - * Updates a property value and notifies any listeners. - * @param name The name of the property to update. - * @param value The new value of the property. - * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. - **/ - updateProperty(name: string, value: any): Promise; - - //#endregion Methods - - }; - - /** - * Do not instantiate. A list returned by the createFiltered method. - **/ - class FilteredListProjection extends ListProjection { - //#region Methods - - /** - * Returns a key/data pair for the specified index. - * @param index The index of the value to retrieve. - * @returns An object that has two properties: key and data. - **/ - getItem(index: number): IKeyDataPair; - - /** - * Returns the index of the first occurrence of a key in a list. - * @param key The key to locate in the list. - * @returns The index of the first occurrence of a key in a list, or -1 if not found. - **/ - indexOfKey(key: string): number; - - /** - * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. - * @param index The index of the value that was mutated. - **/ - notifyMutated(index: number): void; - - /** - * Replaces the value at the specified index with a new value. - * @param index The index of the value that was replaced. - * @param newValue The new value. - **/ - setAt(index: number, newValue: T): void; - - //#endregion Methods - - //#region Properties - - /** - * The length of the list. Returns an integer value one higher than the highest element defined in an list. - **/ - length: number; - - //#endregion Properties - - } - - /** - * Do not instantiate. A list of groups. - **/ - class GroupsListProjection extends ListBase { - //#region Methods - - /** - * Gets a key/data pair for the specified index. - * @param index The index of the value to retrieve. - * @returns An object that has two properties: key and data. - **/ - getItem(index: number): IKeyDataPair; - - /** - * Gets a key/data pair for the specified key. - * @param key The key of the value to retrieve. - * @returns An object with two properties: key and data. - **/ - getItemFromKey(key: string): IKeyDataPair; - - /** - * Returns the index of the first occurrence of a key in a list. - * @param key The key to locate in the list. - * @returns The index of the first occurrence of a key in a list, or -1 if not found. - **/ - indexOfKey(key: string): number; - - //#endregion Methods - - //#region Properties - - /** - * The length of the list. Returns an integer value one higher than the highest element defined in an list. - **/ - length: number; - - //#endregion Properties - - } - - /** - * Do not instantiate. Sorts the underlying list by group key and within a group respects the position of the item in the underlying list. Returned by createGrouped. - **/ - class GroupedSortedListProjection extends SortedListProjection { - //#region Properties - - /** - * Gets a List, which is a projection of the groups that were identified in this list. - **/ - groups: GroupsListProjection; - - //#endregion Properties - - } - - /** - * Represents a list of objects that can be accessed by index or by a string key. Provides methods to search, sort, filter, and manipulate the data. - **/ - class List extends ListBaseWithMutators { - //#region Constructors - - /** - * Creates a List object. - * @constructor - * @param list The array containing the elements to initalize the list. - * @param options You can set two Boolean options: binding and proxy. If options.binding is true, the list contains the result of calling as on the element values. If options.proxy is true, the list specified as the first parameter is used as the storage for the List. This option should be used with care, because uncoordinated edits to the data storage may result in errors. - **/ - constructor(list?: T[], options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Gets a key/data pair for the specified list index. - * @param index The index of value to retrieve. - * @returns An object with .key and .data properties. - **/ - getItem(index: number): IKeyDataPair; - - /** - * Gets a key/data pair for the list item key specified. - * @param key The key of the value to retrieve. - * @returns An object with .key and .data properties. - **/ - getItemFromKey(key: string): IKeyDataPair; - - /** - * Gets the index of the first occurrence of a key in a list. - * @param key The key to locate in the list. - * @returns The index of the first occurrence of a key in a list, or -1 if not found. - **/ - indexOfKey(key: string): number; - - /** - * Moves the value at index to the specified position. - * @param index The original index of the value. - * @param newIndex The index of the value after the move. - **/ - move(index: number, newIndex: number): void; - - /** - * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. - * @param index The index of the value that was mutated. - **/ - notifyMutated(index: number): void; - - /** - * Returns a list with the elements reversed. This method reverses the elements of a list object in place. It does not create a new list object during execution. - **/ - reverse(): void; - - /** - * Replaces the value at the specified index with a new value. - * @param index The index of the value that was replaced. - * @param newValue The new value. - **/ - setAt(index: number, newValue: T): void; - - /** - * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. - * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. - **/ - sort(sortFunction: (left: T, right: T) => number): void; - - /** - * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the list from which to start removing elements. - * @param howMany The number of elements to remove. - * @param item The elements to insert into the list in place of the deleted elements. - * @returns The deleted elements. - **/ - splice(start: number, howMany?: number, ...item: T[]): T[]; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the length of the list, which is an integer value one higher than the highest element defined in the list. - **/ - length: number; - - //#endregion Properties - - } - - /** - * Represents a base class for lists. - **/ - class ListBase { - //#region Events - - /** - * An item in the list has changed its value. - * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, newItem, newValue, oldItem, oldValue. - **/ - onitemchanged(eventInfo: CustomEvent): void; - - /** - * A new item has been inserted into the list. - * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. - **/ - oniteminserted(eventInfo: CustomEvent): void; - - /** - * An item has been changed locations in the list. - * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. - **/ - onitemmoved(eventInfo: CustomEvent): void; - - /** - * An item has been mutated. This event occurs as a result of calling the notifyMutated method. - * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. - **/ - onitemmutated(eventInfo: CustomEvent): void; - - /** - * An item has been removed from the list. - * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. - **/ - onitemremoved(eventInfo: CustomEvent): void; - - /** - * The list has been refreshed. Any references to items in the list may be incorrect. - * @param eventInfo An object that contains information about the event. The detail property of this object is null. - **/ - onreload(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Adds an event listener to the control. - * @param type The type (name) of the event. - * @param listener The listener to invoke when the event gets raised. - * @param useCapture If true, initiates capture, otherwise false. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. - * @param name The name of the property to which to bind the action. - * @param action The function to invoke asynchronously when the property may have changed. - * @returns A reference to this observableMixin object. - **/ - bind(name: string, action: Function): any; - - /** - * Returns a new list consisting of a combination of two arrays. - * @param item Additional items to add to the end of the list. - * @returns An array containing the concatenation of the list and any other supplied items. - **/ - concat(...item: T[]): T[]; - - /** - * Creates a live filtered projection over this list. As the list changes, the filtered projection reacts to those changes and may also change. - * @param predicate A function that accepts a single argument. The createFiltered function calls the callback with each element in the list. If the function returns true, that element will be included in the filtered list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. - * @returns A filtered projection over the list. - **/ - createFiltered(predicate: (x: T) => boolean): FilteredListProjection; - - /** - * Creates a live grouped projection over this list. As the list changes, the grouped projection reacts to those changes and may also change. The grouped projection sorts all the elements of the list to be in group-contiguous order. The grouped projection also contains a .groups property, which is a List representing the groups that were found in the list. - * @param groupKey A function that accepts a single argument. The function is called with each element in the list, the function should return a string representing the group containing the element. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. - * @param groupData A function that accepts a single argument. The function is called once, on one element per group. It should return the value that should be set as the data of the .groups list element for this group. The data value usually serves as summary or header information for the group. - * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). - * @returns A grouped projection over the list. - **/ - createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; - - /** - * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. - * @param sorter A function that accepts two arguments. The function is called with elements in the list. It must return one of the following numeric values: negative if the first argument is less than the second, zero if the two arguments are equivalent, positive if the first argument is greater than the second. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. - * @returns A sorted projection over the list. - **/ - createSorted(sorter: (left: T, right: T) => number): SortedListProjection; - - /** - * Raises an event of the specified type and with the specified additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Checks whether the specified callback function returns true for all elements in a list. - * @param callback A function that accepts up to three arguments. This function is called for each element in the list until it returns false or the end of the list is reached. - * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. - * @returns true if the callback returns true for all elements in the list. - **/ - every(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - - /** - * Returns the elements of a list that meet the condition specified in a callback function. - * @param callback A function that accepts up to three arguments. The function is called for each element in the list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. - * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. - * @returns An array containing the elements that meet the condition specified in the callback function. - **/ - filter(callback: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; - - /** - * Calls the specified callback function for each element in a list. - * @param callback A function that accepts up to three arguments. The function is called for each element in the list. The arguments are as follows: value, index, array. - * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. - **/ - forEach(callback: (value: T, index: number, array: T[]) => void, thisArg?: any): void; - - /** - * Gets the value at the specified index. - * @param index The index of the value to get. - * @returns The value at the specified index. - **/ - getAt(index: number): T; - - /** - * Gets the index of the first occurrence of the specified value in a list. - * @param searchElement The value to locate in the list. - * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - * @returns The index of the first occurrence of a value in a list or -1 if not found. - **/ - indexOf(searchElement: T, fromIndex?: number): number; - - /** - * Returns a string consisting of all the elements of a list separated by the specified separator string. - * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. - * @returns The elements of a list separated by the specified separator string. - **/ - join(separator: string): string; - - /** - * Gets the index of the last occurrence of the specified value in a list. - * @param searchElement The value to locate in the list. - * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. - * @returns The index of the last occurrence of a value in a list, or -1 if not found. - **/ - lastIndexOf(searchElement: T, fromIndex: number): number; - - /** - * Calls the specified callback function on each element of a list, and returns an array that contains the results. - * @param callback A function that accepts up to three arguments. The function is called for each element in the list. - * @param thisArg n object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. - * @returns An array containing the result of calling the callback function on each element in the list. - **/ - map(callback: (value: T, index: number, array: T[]) => G, thisArg?: any): G[]; - - /** - * Notifies listeners that a property value was updated. - * @param name The name of the property that is being updated. - * @param newValue The new value for the property. - * @param oldValue The old value for the property. - * @returns A promise that is completed when the notifications are complete. - **/ - notify(name: string, newValue: any, oldValue: any): Promise; - - /** - * Forces the list to send a reload notification to any listeners. - **/ - notifyReload(): void; - - /** - * Accumulates a single result by calling the specified callback function for all elements in a list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. - * @param initiallValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the function provides this value as an argument instead of a list value. - * @returns The return value from the last call to the callback function. - **/ - reduce(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initiallValue?: T): T; - - /** - * Accumulates a single result by calling the specified callback function for all elements in a list, starting with the last member of the list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. - * @param initialValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the callback function provides this value as an argument instead of a list value. - * @returns The return value from the last call to callback function. - **/ - reduceRight(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initialValue?: T): T; - - /** - * Removes an event listener from the control. - * @param type The type (name) of the event. - * @param listener The listener to remove. - * @param useCapture true if capture is to be initiated, otherwise false. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Extracts a section of a list and returns a new list. - * @param begin The index that specifies the beginning of the section. - * @param end The index that specifies the end of the section. - * @returns Returns a section of list. - **/ - slice(begin: number, end: number): T[]; - - /** - * Checks whether the specified callback function returns true for any element of a list. - * @param callback A function that accepts up to three arguments. The function is called for each element in the list until it returns true, or until the end of the list. - * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. - * @returns true if callback returns true for any element in the list. - **/ - some(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - - /** - * Removes one or more listeners from the notification list for a given property. - * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. - * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. - * @returns This object is returned. - **/ - unbind(name: string, action: Function): any; - - //#endregion Methods - - //#region Properties - - /** - * Gets the IListDataSource for the list. The only purpose of this property is to adapt a List to the data model that is used by ListView and FlipView. - **/ - dataSource: WinJS.UI.IListDataSource; - - /** - * Indicates that the object is compatibile with declarative processing. - **/ - static supportedForProcessing: boolean; - - //#endregion Properties - } - - /** - * Represents a base class for normal list modifying operations. - **/ - class ListBaseWithMutators extends ListBase { - //#region Methods - - /** - * Removes the last element from a list and returns it. - * @returns The last element from the list. - **/ - pop(): T; - - /** - * Appends new element(s) to a list, and returns the new length of the list. - * @param value The element to insert at the end of the list. - * @returns The new length of the list. - **/ - push(value: T): number; - - /** - * Removes the first element from a list and returns it. - * @returns The first element from the list. - **/ - shift(): T; - - /** - * Appends new element(s) to a list, and returns the new length of the list. - * @param value The element to insert at the start of the list. - * @returns The new length of the list. - **/ - unshift(value: T): number; - - //#endregion Methods - } - - /** - * Represents a base class for list projections. - **/ - class ListProjection extends ListBaseWithMutators { - //#region Methods - - /** - * Disconnects a WinJS.Binding.List projection from its underlying WinJS.Binding.List. It's only important to call this method when the WinJS.Binding.List projection and the WinJS.Binding.List have different lifetimes. (Call this method on the WinJS.Binding.List projection, not the underlying WinJS.Binding.List.) - **/ - dispose(): void; - - /** - * Gets a key/data pair for the specified key. - * @param key The key of the value to retrieve. - * @returns An object with two properties: key and data. - **/ - getItemFromKey(key: string): IKeyDataPair; - - /** - * Moves the value at index to position newIndex. - * @param index The original index of the value. - * @param newIndex The index of the value after the move. - **/ - move(index: number, newIndex: number): void; - - /** - * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the list from which to start removing elements. - * @param howMany The number of elements to remove. - * @param item The elements to insert into the list in place of the deleted elements. - * @returns The deleted elements. - **/ - splice(start: number, howMany?: number, ...item: T[]): T[]; - - //#endregion Methods - } - - /** - * Provides a standard implementation of the bindable contract, as well as a basic storage mechanism that participates in change notification and an asynchronous notification implementation. - **/ - var mixin: { - //#region Methods - - /** - * Adds a property to the object. The property includes change notification and an ECMAScript 5 property definition . - * @param name The name of the property to add. - * @param value The value of the property. - * @returns This object is returned. - **/ - addProperty(name: string, value: any): any; - - /** - * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. - * @param name The name of the property to which to bind the action. - * @param action The function to invoke asynchronously when the property may have changed. - * @returns This object is returned. - **/ - bind(name: string, action: any): Function; - - /** - * Gets a property value by name. - * @param name The name of the property to get. - * @returns The value of the property as an observable object. - **/ - getProperty(name: string): any; - - /** - * Notifies listeners that a property value was updated. - * @param name The name of the property that is being updated. - * @param newValue The new value for the property. - * @param oldValue The old value for the property. - * @returns A promise that is completed when the notifications are complete. - **/ - notify(name: string, newValue: string, oldValue: string): Promise; - - /** - * Removes a property value. - * @param name The name of the property to remove. - * @returns This object is returned. - **/ - removeProperty(name: string): any; - - /** - * Updates a property value and notifies any listeners. - * @param name The name of the property to update. - * @param value The new value of the property. - * @returns This object is returned. - **/ - setProperty(name: string, value: any): any; - - /** - * Removes one or more listeners from the notification list for a given property. - * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. - * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. - * @returns This object is returned. - **/ - unbind(name: string, action: Function): any; - - /** - * Updates a property value and notifies any listeners. - * @param name The name of the property to update. - * @param value The new value of the property. - * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. - **/ - updateProperty(name: string, value: any): Promise; - - //#endregion Methods - - }; - - /** - * Provides functions that can make an object observable. - **/ - var observableMixin: { - //#region Methods - - /** - * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. - * @param name The name of the property to which to bind the action. - * @param action The function to invoke asynchronously when the property may have changed. - * @returns A reference to this observableMixin object. - **/ - bind(name: string, action: Function): any; - - /** - * Notifies listeners that a property value was updated. - * @param name The name of the property that is being updated. - * @param newValue The new value for the property. - * @param oldValue The old value for the property. - * @returns A promise that is completed when the notifications are complete. - **/ - notify(name: string, newValue: any, oldValue: any): Promise; - - /** - * Removes one or more listeners from the notification list for a given property. - * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. - * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. - * @returns This object is returned. - **/ - unbind(name: string, action: Function): any; - - //#endregion Methods - - }; - - /** - * Do not instantiate. Returned by the createSorted method. - **/ - class SortedListProjection extends ListProjection { - //#region Methods - - /** - * Returns a key/data pair for the specified index. - * @param index The index of the value to retrieve. - * @returns An object that has two properties: key and data. - **/ - getItem(index: number): IKeyDataPair; - - /** - * Returns the index of the first occurrence of a key. - * @param key The key to locate in the list. - * @returns The index of the first occurrence of a key in a list, or -1 if not found. - **/ - indexOfKey(key: string): number; - - /** - * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. - * @param index The index of the value that was mutated. - **/ - notifyMutated(index: number): void; - - /** - * Replaces the value at the specified index with a new value. - * @param index The index of the value to be replaced. - * @param newValue The new value. - **/ - setAt(index: number, newValue: T): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the length of the list. Returns an integer value one higher than the highest element defined in a list. - **/ - length: number; - - //#endregion Properties - - } - - /** - * Provides a reusable declarative binding element. - **/ - class Template { - //#region Constructors - - /** - * Creates a template that provides a reusable declarative binding element. - * @constructor - * @param element The DOM element to convert to a template. - * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. - **/ - constructor(element: HTMLElement, options?: string); - - //#endregion Constructors - - //#region Methods - - render: { - /** - * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. - **/ - (dataContext: any, container?: HTMLElement): Promise; - - /** - * Renders a template based on the specified URI (static method). - * @param href The URI from which to load the template. - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. - **/ - value(href: string, dataContext: any, container?: HTMLElement): Promise; - }; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the default binding initializer for the template. - **/ - bindingInitializer: any; - - /** - * Gets or sets a value that specifies whether a debug break is inserted into the first rendering of each template. This property only has an effect when the app is in debug mode. - **/ - debugBreakOnRender: boolean; - - /** - * This property is deprecated and might not be available in future versions of the WinJS. Gets or sets a value that specifies whether optimized template processing has been disabled. - **/ - disableOptimizedProcessing: boolean; - - /** - * Gets the DOM element that is used as the template. - **/ - element: HTMLElement; - - /** - * Gets a value that specifies whether templates should be instantiated without the creation of an additional child element. - **/ - extractChild: boolean; - - /** - * Determines whether the Template contains declarative controls that must be processed separately. This property is always true. The controls that belong to a Template object's children are instantiated when a Template instance is rendered. - **/ - isDeclarativeControlContainer: boolean; - - //#endregion Properties - - } - - //#endregion Objects - - //#region Functions - - /** - * Adds a CSS class from the specified path of the source object to a destination object. - * @param source The source object that has the class to copy. - * @param sourceProperties The path on the source object to the source class. - * @param dest The destination object. - **/ - function addClassOneTime(source: any, sourceProperties: any[], dest: HTMLElement): void; - - /** - * Returns an observable object. This may be an observable proxy for the specified object, an existing proxy, or the specified object itself if it directly supports observation. - * @param data The object to observe. - * @returns The observable object. - **/ - function as(data: U): U; - - /** - * Binds to one or more properties on the observable object or or on child values of that object. - * @param observable The object to bind to. - * @param bindingDescriptor An object literal containing the binding declarations. Binding declarations take the form: { propertyName: (function | bindingDeclaration), ... }. - * @returns An object that contains at least a "cancel" field, which is a function that removes all bindings associated with this bind request. - **/ - function bind(observable: any, bindingDescriptor: any): any; - - /** - * Creates a default binding initializer for binding between a source property and a destination property with the specified converter function that is executed on the value of the source property. - * @param convert The conversion function that takes the source property and produces a value that is set to the destination property. This function must be accessible from the global namespace. - * @returns The binding initializer. - **/ - function converter(convert: Function): Function; - - /** - * Creates a one-way binding between the source object and the destination object. Warning Do not attempt to bind data to the ID of an HTML element. - * @param source The source object. - * @param sourceProperties The path on the source object to the source property. - * @param dest The destination object. - * @param destProperties The path on the destination object to the destination property. - * @returns An object with a cancel method that is used to coalesce bindings. - **/ - function defaultBind(source: any, sourceProperties: any, dest: any, destProperties: any): any; - - /** - * Creates a new constructor function that supports observability with the specified set of properties. - * @param data The object to use as the pattern for defining the set of properties. - * @returns A constructor function with 1 optional argument that is the initial state of the properties. - **/ - function define(data: any): Function; - - /** - * Wraps the specified object so that all its properties are instrumented for binding. This is meant to be used in conjunction with the binding mixin. - * @param shape The specification for the bindable object. - * @returns An object with a set of properties all of which are wired for binding. - **/ - function expandProperties(shape: any): any; - - /** - * Marks a custom initializer function as being compatible with declarative data binding. - * @param customInitializer The custom initializer to be marked as compatible with declarative data binding. - * @returns The input customInitializer. - **/ - function initializer(customInitializer: Function): Function; - - /** - * Notifies listeners that a property value was updated. - * @param name The name of the property that is being updated. - * @param newValue The new value for the property. - * @param oldValue The old value for the property. - * @returns A promise that is completed when the notifications are complete. - **/ - function notify(name: string, newValue: string, oldValue: string): Promise; - - /** - * Sets the destination property to the value of the source property. - * @param source The source object. - * @param sourceProperties The path on the source object to the source property. - * @param dest The destination object. - * @param destProperties The path on the destination object to the destination property. - * @returns An object with a cancel method that is used to coalesce bindings. - **/ - function oneTime(source: any, sourceProperties: any, dest: any, destProperties: any): any; - - /** - * Binds the values of an object to the values of a DOM element that has the data-win-bind attribute. If multiple DOM elements are to be bound, you must set the attribute on all of them. See the example below for details. - * @param rootElement Optional. The element at which to start traversing to find elements to bind to. If this parameter is omitted, the entire document is searched. - * @param dataContext The object that contains the values to which the DOM element should be bound. - * @param skipRoot If true, specifies that only the children of rootElement should be bound, otherwise rootElement should be bound as well. - * @param bindingCache The cached binding data. - * @param defaultInitializer The binding initializer to use in the case that one is not specified in a binding expression. If not provided, the behavior is the same as Binding.defaultBind. - * @returns A Promise that completes when every item that contains the data-win-bind attribute has been processed and the update has started. - **/ - function processAll(rootElement?: Element, dataContext?: any, skipRoot?: boolean, bindingCache?: any, defaultInitializer?: Function): Promise; - - /** - * Creates a one-way binding between the source object and an attribute on the destination element. - * @param source The source object. - * @param sourceProperties The path on the source object to the source property. - * @param dest The destination object. - * @param destProperties The path on the destination object to the destination property. This must be a single name. - * @returns An object with a cancel() method that is used to coalesce bindings. - **/ - function setAttribute(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): any; - - /** - * Sets an attribute on the destination element to the value of the source property. - * @param source The source object. - * @param sourceProperties The path on the source object to the source property. - * @param dest The destination object. - * @param destProperties The path on the destination object to the destination property. This must be a single name. - **/ - function setAttributeOneTime(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): void; - - /** - * Returns the original (non-observable) object is returned if the specified object is an observable proxy, - * @param data The object for which to retrieve the original value. - * @returns If the specified object is an observable proxy, the original object is returned, otherwise the same object is returned. - **/ - function unwrap(data: any): any; - - //#endregion Functions - - //#region Interfaces - - interface IKeyDataPair { - key: string; - data: T; - } - - //#endregion Interfaces + //#region Properties + + /** + * Determines whether or not binding should automatically set the ID of an element. This property should be set to true in apps that use WinJS (WinJS) binding. + **/ + var optimizeBindingReferences: boolean; + + //#endregion Properties + + //#region Objects + + /** + * Allows you to add bindable properties dynamically. + **/ + var dynamicObservableMixin: { + //#region Methods + + /** + * Adds a property with change notification to this object, including a ECMAScript5 property definition. + * @param name The name of the property to add. + * @param value This object is returned. + **/ + addProperty(name: string, value: any): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Do not instantiate. A list returned by the createFiltered method. + **/ + class FilteredListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. A list of groups. + **/ + class GroupsListProjection extends ListBase { + //#region Methods + + /** + * Gets a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + //#endregion Methods + + //#region Properties + + /** + * The length of the list. Returns an integer value one higher than the highest element defined in an list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Do not instantiate. Sorts the underlying list by group key and within a group respects the position of the item in the underlying list. Returned by createGrouped. + **/ + class GroupedSortedListProjection extends SortedListProjection { + //#region Properties + + /** + * Gets a List, which is a projection of the groups that were identified in this list. + **/ + groups: GroupsListProjection; + + //#endregion Properties + + } + + /** + * Represents a list of objects that can be accessed by index or by a string key. Provides methods to search, sort, filter, and manipulate the data. + **/ + class List extends ListBaseWithMutators { + //#region Constructors + + /** + * Creates a List object. + * @constructor + * @param list The array containing the elements to initalize the list. + * @param options You can set two Boolean options: binding and proxy. If options.binding is true, the list contains the result of calling as on the element values. If options.proxy is true, the list specified as the first parameter is used as the storage for the List. This option should be used with care, because uncoordinated edits to the data storage may result in errors. + **/ + constructor(list?: T[], options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Gets a key/data pair for the specified list index. + * @param index The index of value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Gets a key/data pair for the list item key specified. + * @param key The key of the value to retrieve. + * @returns An object with .key and .data properties. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Gets the index of the first occurrence of a key in a list. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Moves the value at index to the specified position. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Returns a list with the elements reversed. This method reverses the elements of a list object in place. It does not create a new list object during execution. + **/ + reverse(): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value that was replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + /** + * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. + * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + **/ + sort(sortFunction: (left: T, right: T) => number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list, which is an integer value one higher than the highest element defined in the list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Represents a base class for lists. + **/ + class ListBase { + //#region Events + + /** + * An item in the list has changed its value. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, newItem, newValue, oldItem, oldValue. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * A new item has been inserted into the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * An item has been changed locations in the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * An item has been mutated. This event occurs as a result of calling the notifyMutated method. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemmutated(eventInfo: CustomEvent): void; + + /** + * An item has been removed from the list. + * @param eventInfo An object that contains information about the event. The detail contains the following information: index, key, value. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * The list has been refreshed. Any references to items in the list may be incorrect. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. + **/ + onreload(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Returns a new list consisting of a combination of two arrays. + * @param item Additional items to add to the end of the list. + * @returns An array containing the concatenation of the list and any other supplied items. + **/ + concat(...item: T[]): T[]; + + /** + * Creates a live filtered projection over this list. As the list changes, the filtered projection reacts to those changes and may also change. + * @param predicate A function that accepts a single argument. The createFiltered function calls the callback with each element in the list. If the function returns true, that element will be included in the filtered list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A filtered projection over the list. + **/ + createFiltered(predicate: (x: T) => boolean): FilteredListProjection; + + /** + * Creates a live grouped projection over this list. As the list changes, the grouped projection reacts to those changes and may also change. The grouped projection sorts all the elements of the list to be in group-contiguous order. The grouped projection also contains a .groups property, which is a List representing the groups that were found in the list. + * @param groupKey A function that accepts a single argument. The function is called with each element in the list, the function should return a string representing the group containing the element. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param groupData A function that accepts a single argument. The function is called once, on one element per group. It should return the value that should be set as the data of the .groups list element for this group. The data value usually serves as summary or header information for the group. + * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). + * @returns A grouped projection over the list. + **/ + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + + /** + * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. + * @param sorter A function that accepts two arguments. The function is called with elements in the list. It must return one of the following numeric values: negative if the first argument is less than the second, zero if the two arguments are equivalent, positive if the first argument is greater than the second. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @returns A sorted projection over the list. + **/ + createSorted(sorter: (left: T, right: T) => number): SortedListProjection; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Checks whether the specified callback function returns true for all elements in a list. + * @param callback A function that accepts up to three arguments. This function is called for each element in the list until it returns false or the end of the list is reached. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if the callback returns true for all elements in the list. + **/ + every(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Returns the elements of a list that meet the condition specified in a callback function. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the elements that meet the condition specified in the callback function. + **/ + filter(callback: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; + + /** + * Calls the specified callback function for each element in a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. The arguments are as follows: value, index, array. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + **/ + forEach(callback: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + /** + * Gets the value at the specified index. + * @param index The index of the value to get. + * @returns The value at the specified index. + **/ + getAt(index: number): T; + + /** + * Gets the index of the first occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + * @returns The index of the first occurrence of a value in a list or -1 if not found. + **/ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns a string consisting of all the elements of a list separated by the specified separator string. + * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. + * @returns The elements of a list separated by the specified separator string. + **/ + join(separator: string): string; + + /** + * Gets the index of the last occurrence of the specified value in a list. + * @param searchElement The value to locate in the list. + * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. + * @returns The index of the last occurrence of a value in a list, or -1 if not found. + **/ + lastIndexOf(searchElement: T, fromIndex: number): number; + + /** + * Calls the specified callback function on each element of a list, and returns an array that contains the results. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list. + * @param thisArg n object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns An array containing the result of calling the callback function on each element in the list. + **/ + map(callback: (value: T, index: number, array: T[]) => G, thisArg?: any): G[]; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Forces the list to send a reload notification to any listeners. + **/ + notifyReload(): void; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initiallValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the function provides this value as an argument instead of a list value. + * @returns The return value from the last call to the callback function. + **/ + reduce(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initiallValue?: T): T; + + /** + * Accumulates a single result by calling the specified callback function for all elements in a list, starting with the last member of the list. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callback A function that accepts up to four arguments. These arguments are: previousValue, currentValue, currentIndex, array. The function is called for each element in the list. + * @param initialValue If initialValue is specified, it is used as the value with which to start the accumulation. The first call to the callback function provides this value as an argument instead of a list value. + * @returns The return value from the last call to callback function. + **/ + reduceRight(callback: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => T, initialValue?: T): T; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Extracts a section of a list and returns a new list. + * @param begin The index that specifies the beginning of the section. + * @param end The index that specifies the end of the section. + * @returns Returns a section of list. + **/ + slice(begin: number, end: number): T[]; + + /** + * Checks whether the specified callback function returns true for any element of a list. + * @param callback A function that accepts up to three arguments. The function is called for each element in the list until it returns true, or until the end of the list. + * @param thisArg An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used. + * @returns true if callback returns true for any element in the list. + **/ + some(callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + //#region Properties + + /** + * Gets the IListDataSource for the list. The only purpose of this property is to adapt a List to the data model that is used by ListView and FlipView. + **/ + dataSource: WinJS.UI.IListDataSource; + + /** + * Indicates that the object is compatibile with declarative processing. + **/ + static supportedForProcessing: boolean; + + //#endregion Properties + } + + /** + * Represents a base class for normal list modifying operations. + **/ + class ListBaseWithMutators extends ListBase { + //#region Methods + + /** + * Removes the last element from a list and returns it. + * @returns The last element from the list. + **/ + pop(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the end of the list. + * @returns The new length of the list. + **/ + push(value: T): number; + + /** + * Removes the first element from a list and returns it. + * @returns The first element from the list. + **/ + shift(): T; + + /** + * Appends new element(s) to a list, and returns the new length of the list. + * @param value The element to insert at the start of the list. + * @returns The new length of the list. + **/ + unshift(value: T): number; + + //#endregion Methods + } + + /** + * Represents a base class for list projections. + **/ + class ListProjection extends ListBaseWithMutators { + //#region Methods + + /** + * Disconnects a WinJS.Binding.List projection from its underlying WinJS.Binding.List. It's only important to call this method when the WinJS.Binding.List projection and the WinJS.Binding.List have different lifetimes. (Call this method on the WinJS.Binding.List projection, not the underlying WinJS.Binding.List.) + **/ + dispose(): void; + + /** + * Gets a key/data pair for the specified key. + * @param key The key of the value to retrieve. + * @returns An object with two properties: key and data. + **/ + getItemFromKey(key: string): IKeyDataPair; + + /** + * Moves the value at index to position newIndex. + * @param index The original index of the value. + * @param newIndex The index of the value after the move. + **/ + move(index: number, newIndex: number): void; + + /** + * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the list from which to start removing elements. + * @param howMany The number of elements to remove. + * @param item The elements to insert into the list in place of the deleted elements. + * @returns The deleted elements. + **/ + splice(start: number, howMany?: number, ...item: T[]): T[]; + + //#endregion Methods + } + + /** + * Provides a standard implementation of the bindable contract, as well as a basic storage mechanism that participates in change notification and an asynchronous notification implementation. + **/ + var mixin: { + //#region Methods + + /** + * Adds a property to the object. The property includes change notification and an ECMAScript 5 property definition . + * @param name The name of the property to add. + * @param value The value of the property. + * @returns This object is returned. + **/ + addProperty(name: string, value: any): any; + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns This object is returned. + **/ + bind(name: string, action: any): Function; + + /** + * Gets a property value by name. + * @param name The name of the property to get. + * @returns The value of the property as an observable object. + **/ + getProperty(name: string): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Removes a property value. + * @param name The name of the property to remove. + * @returns This object is returned. + **/ + removeProperty(name: string): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns This object is returned. + **/ + setProperty(name: string, value: any): any; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + /** + * Updates a property value and notifies any listeners. + * @param name The name of the property to update. + * @param value The new value of the property. + * @returns A promise that completes when the notifications for this property change have been processed. If multiple notifications are coalesced, the promise may be canceled or the value of the promise may be updated. The fulfilled value of the promise is the new value of the property for which the notifications have been completed. + **/ + updateProperty(name: string, value: any): Promise; + + //#endregion Methods + + }; + + /** + * Provides functions that can make an object observable. + **/ + var observableMixin: { + //#region Methods + + /** + * Links the specified action to the property specified in the name parameter. This function is invoked when the value of the property may have changed. It is not guaranteed that the action will be called only when a value has actually changed, nor is it guaranteed that the action will be called for every value change. The implementation of this function coalesces change notifications, such that multiple updates to a property value may result in only a single call to the specified action. + * @param name The name of the property to which to bind the action. + * @param action The function to invoke asynchronously when the property may have changed. + * @returns A reference to this observableMixin object. + **/ + bind(name: string, action: Function): any; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + notify(name: string, newValue: any, oldValue: any): Promise; + + /** + * Removes one or more listeners from the notification list for a given property. + * @param name The name of the property to unbind. If this parameter is omitted, all listeners for all events are removed. + * @param action The function to remove from the listener list for the specified property. If this parameter is omitted, all listeners are removed for the specific property. + * @returns This object is returned. + **/ + unbind(name: string, action: Function): any; + + //#endregion Methods + + }; + + /** + * Do not instantiate. Returned by the createSorted method. + **/ + class SortedListProjection extends ListProjection { + //#region Methods + + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IKeyDataPair; + + /** + * Returns the index of the first occurrence of a key. + * @param key The key to locate in the list. + * @returns The index of the first occurrence of a key in a list, or -1 if not found. + **/ + indexOfKey(key: string): number; + + /** + * Forces the list to send a itemmutated notification to any listeners for the value at the specified index. + * @param index The index of the value that was mutated. + **/ + notifyMutated(index: number): void; + + /** + * Replaces the value at the specified index with a new value. + * @param index The index of the value to be replaced. + * @param newValue The new value. + **/ + setAt(index: number, newValue: T): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the length of the list. Returns an integer value one higher than the highest element defined in a list. + **/ + length: number; + + //#endregion Properties + + } + + /** + * Provides a reusable declarative binding element. + **/ + class Template { + //#region Constructors + + /** + * Creates a template that provides a reusable declarative binding element. + * @constructor + * @param element The DOM element to convert to a template. + * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. + **/ + constructor(element: HTMLElement, options?: string); + + //#endregion Constructors + + //#region Methods + + render: { + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + (dataContext: any, container?: HTMLElement): Promise; + + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + value(href: string, dataContext: any, container?: HTMLElement): Promise; + }; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default binding initializer for the template. + **/ + bindingInitializer: any; + + /** + * Gets or sets a value that specifies whether a debug break is inserted into the first rendering of each template. This property only has an effect when the app is in debug mode. + **/ + debugBreakOnRender: boolean; + + /** + * This property is deprecated and might not be available in future versions of the WinJS. Gets or sets a value that specifies whether optimized template processing has been disabled. + **/ + disableOptimizedProcessing: boolean; + + /** + * Gets the DOM element that is used as the template. + **/ + element: HTMLElement; + + /** + * Gets a value that specifies whether templates should be instantiated without the creation of an additional child element. + **/ + extractChild: boolean; + + /** + * Determines whether the Template contains declarative controls that must be processed separately. This property is always true. The controls that belong to a Template object's children are instantiated when a Template instance is rendered. + **/ + isDeclarativeControlContainer: boolean; + + //#endregion Properties + + } + + //#endregion Objects + + //#region Functions + + /** + * Adds a CSS class from the specified path of the source object to a destination object. + * @param source The source object that has the class to copy. + * @param sourceProperties The path on the source object to the source class. + * @param dest The destination object. + **/ + function addClassOneTime(source: any, sourceProperties: any[], dest: HTMLElement): void; + + /** + * Returns an observable object. This may be an observable proxy for the specified object, an existing proxy, or the specified object itself if it directly supports observation. + * @param data The object to observe. + * @returns The observable object. + **/ + function as(data: U): U; + + /** + * Binds to one or more properties on the observable object or or on child values of that object. + * @param observable The object to bind to. + * @param bindingDescriptor An object literal containing the binding declarations. Binding declarations take the form: { propertyName: (function | bindingDeclaration), ... }. + * @returns An object that contains at least a "cancel" field, which is a function that removes all bindings associated with this bind request. + **/ + function bind(observable: any, bindingDescriptor: any): any; + + /** + * Creates a default binding initializer for binding between a source property and a destination property with the specified converter function that is executed on the value of the source property. + * @param convert The conversion function that takes the source property and produces a value that is set to the destination property. This function must be accessible from the global namespace. + * @returns The binding initializer. + **/ + function converter(convert: Function): Function; + + /** + * Creates a one-way binding between the source object and the destination object. Warning Do not attempt to bind data to the ID of an HTML element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function defaultBind(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Creates a new constructor function that supports observability with the specified set of properties. + * @param data The object to use as the pattern for defining the set of properties. + * @returns A constructor function with 1 optional argument that is the initial state of the properties. + **/ + function define(data: any): Function; + + /** + * Wraps the specified object so that all its properties are instrumented for binding. This is meant to be used in conjunction with the binding mixin. + * @param shape The specification for the bindable object. + * @returns An object with a set of properties all of which are wired for binding. + **/ + function expandProperties(shape: any): any; + + /** + * Marks a custom initializer function as being compatible with declarative data binding. + * @param customInitializer The custom initializer to be marked as compatible with declarative data binding. + * @returns The input customInitializer. + **/ + function initializer(customInitializer: Function): Function; + + /** + * Notifies listeners that a property value was updated. + * @param name The name of the property that is being updated. + * @param newValue The new value for the property. + * @param oldValue The old value for the property. + * @returns A promise that is completed when the notifications are complete. + **/ + function notify(name: string, newValue: string, oldValue: string): Promise; + + /** + * Sets the destination property to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. + * @returns An object with a cancel method that is used to coalesce bindings. + **/ + function oneTime(source: any, sourceProperties: any, dest: any, destProperties: any): any; + + /** + * Binds the values of an object to the values of a DOM element that has the data-win-bind attribute. If multiple DOM elements are to be bound, you must set the attribute on all of them. See the example below for details. + * @param rootElement Optional. The element at which to start traversing to find elements to bind to. If this parameter is omitted, the entire document is searched. + * @param dataContext The object that contains the values to which the DOM element should be bound. + * @param skipRoot If true, specifies that only the children of rootElement should be bound, otherwise rootElement should be bound as well. + * @param bindingCache The cached binding data. + * @param defaultInitializer The binding initializer to use in the case that one is not specified in a binding expression. If not provided, the behavior is the same as Binding.defaultBind. + * @returns A Promise that completes when every item that contains the data-win-bind attribute has been processed and the update has started. + **/ + function processAll(rootElement?: Element, dataContext?: any, skipRoot?: boolean, bindingCache?: any, defaultInitializer?: Function): Promise; + + /** + * Creates a one-way binding between the source object and an attribute on the destination element. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + * @returns An object with a cancel() method that is used to coalesce bindings. + **/ + function setAttribute(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): any; + + /** + * Sets an attribute on the destination element to the value of the source property. + * @param source The source object. + * @param sourceProperties The path on the source object to the source property. + * @param dest The destination object. + * @param destProperties The path on the destination object to the destination property. This must be a single name. + **/ + function setAttributeOneTime(source: any, sourceProperties: any[], dest: Element, destProperties: any[]): void; + + /** + * Returns the original (non-observable) object is returned if the specified object is an observable proxy, + * @param data The object for which to retrieve the original value. + * @returns If the specified object is an observable proxy, the original object is returned, otherwise the same object is returned. + **/ + function unwrap(data: any): any; + + //#endregion Functions + + //#region Interfaces + + interface IKeyDataPair { + key: string; + data: T; + } + + //#endregion Interfaces } /** * Provides helper functions for defining Classes. **/ declare module WinJS.Class { - //#region Functions + //#region Functions - /** - * Defines a class using the given constructor and the specified instance members. - * @param constructor A constructor function that is used to instantiate this type. - * @param instanceMembers The set of instance fields, properties, and methods made available on the type. - * @param staticMembers The set of static fields, properties, and methods made available on the type. - * @returns The newly-defined type. - **/ - function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + /** + * Defines a class using the given constructor and the specified instance members. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods made available on the type. + * @param staticMembers The set of static fields, properties, and methods made available on the type. + * @returns The newly-defined type. + **/ + function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; - /** - * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. - * @param baseClass The type to inherit from. - * @param constructor A constructor function that is used to instantiate this type. - * @param instanceMembers The set of instance fields, properties, and methods to be made available on the type. - * @param staticMembers The set of static fields, properties, and methods to be made available on the type. - * @returns The newly-defined type. - **/ - function derive(baseClass: any, constructor: Function, instanceMembers?: any, staticMembers?: any): any; + /** + * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. + * @param baseClass The type to inherit from. + * @param constructor A constructor function that is used to instantiate this type. + * @param instanceMembers The set of instance fields, properties, and methods to be made available on the type. + * @param staticMembers The set of static fields, properties, and methods to be made available on the type. + * @returns The newly-defined type. + **/ + function derive(baseClass: any, constructor: Function, instanceMembers?: any, staticMembers?: any): any; - /** - * Defines a class using the given constructor and the union of the set of instance members specified by all the mixin objects. The mixin parameter list is of variable length. For more information, see Adding functionality with WinJS mixins. - * @param constructor A constructor function that will be used to instantiate this class. - * @param mixin An object declaring the set of instance members. The mixin parameter list is of variable length. - * @returns The newly defined class. - **/ - function mix(constructor: Function, ...mixin: any[]): any; + /** + * Defines a class using the given constructor and the union of the set of instance members specified by all the mixin objects. The mixin parameter list is of variable length. For more information, see Adding functionality with WinJS mixins. + * @param constructor A constructor function that will be used to instantiate this class. + * @param mixin An object declaring the set of instance members. The mixin parameter list is of variable length. + * @returns The newly defined class. + **/ + function mix(constructor: Function, ...mixin: any[]): any; - //#endregion Functions + //#endregion Functions } /** * The WinJS namespace provides special Windows Library for JavaScript functionality, including Promise and xhr. **/ declare module WinJS { - //#region Properties + //#region Properties - /** - * Can be set to show the results of a validation process. - **/ - var validation: boolean; + /** + * Can be set to show the results of a validation process. + **/ + var validation: boolean; - //#endregion Properties + //#endregion Properties - //#region Objects + //#region Objects - /** - * An error object. - **/ - class ErrorFromName { - //#region Constructors + /** + * An error object. + **/ + class ErrorFromName { + //#region Constructors - /** - * Creates an Error object with the specified name and message properties. - * @constructor - * @param name The name of this error. The name is meant to be consumed programmatically and should not be localized. - * @param message The message for this error. The message is meant to be consumed by humans and should be localized. - **/ - constructor(name: string, message?: string); + /** + * Creates an Error object with the specified name and message properties. + * @constructor + * @param name The name of this error. The name is meant to be consumed programmatically and should not be localized. + * @param message The message for this error. The message is meant to be consumed by humans and should be localized. + **/ + constructor(name: string, message?: string); - //#endregion Constructors + //#endregion Constructors - } + } - /** - * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. - **/ - class Promise implements Windows.Foundation.IPromise { - //#region Constructors + /** + * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + **/ + class Promise { + //#region Constructors - /** - * A promise provides a mechanism to schedule work to be done on a value that has not yet been computed. It is a convenient abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. - * @constructor - * @param init The function that is called during construction of the Promise that contains the implementation of the operation that the Promise will represent. This can be synchronous or asynchronous, depending on the nature of the operation. Note that placing code within this function does not automatically run it asynchronously; that must be done explicitly with other asynchronous APIs such as setImmediate, setTimeout, requestAnimationFrame, and the Windows Runtime asynchronous APIs. The init function is given three arguments: completeDispatch, errorDispatch, progressDispatch. This parameter is optional. - * @param onCancel The function to call if a consumer of this promise wants to cancel its undone work. Promises are not required to support cancellation. - **/ - constructor(init?: (completeDispatch: any, errorDispatch: any, progressDispatch: any) => void, onCancel?: Function); + /** + * A promise provides a mechanism to schedule work to be done on a value that has not yet been computed. It is a convenient abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. + * @constructor + * @param init The function that is called during construction of the Promise that contains the implementation of the operation that the Promise will represent. This can be synchronous or asynchronous, depending on the nature of the operation. Note that placing code within this function does not automatically run it asynchronously; that must be done explicitly with other asynchronous APIs such as setImmediate, setTimeout, requestAnimationFrame, and the Windows Runtime asynchronous APIs. The init function is given three arguments: completeDispatch, errorDispatch, progressDispatch. This parameter is optional. + * @param onCancel The function to call if a consumer of this promise wants to cancel its undone work. Promises are not required to support cancellation. + **/ + constructor(init?: (completeDispatch: any, errorDispatch: any, progressDispatch: any) => void, onCancel?: Function); - //#endregion Constructors + //#endregion Constructors - //#region Events + //#region Events - /** - * Occurs when there is an error in processing a promise. - * @param eventInfo An object that contains information about the event. - **/ - onerror(eventInfo: CustomEvent): void; + /** + * Occurs when there is an error in processing a promise. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; - //#endregion Events + //#endregion Events - //#region Methods + //#region Methods - /** - * Adds an event listener for the promise. - * @param type The type (name) of the event. - * @param listener The listener to invoke when the event is raised. - * @param capture true to initiate capture, otherwise false. - **/ - addEventListener(type: string, listener: Function, capture?: boolean): void; + /** + * Adds an event listener for the promise. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; - /** - * Returns a promise that is fulfilled when one of the input promises has been fulfilled. - * @param value An array that contains Promise objects or objects whose property values include Promise objects. - * @returns A promise that on fulfillment yields the value of the input (complete or error). - **/ - static any(value: Promise[]): Promise; + /** + * Returns a promise that is fulfilled when one of the input promises has been fulfilled. + * @param value An array that contains Promise objects or objects whose property values include Promise objects. + * @returns A promise that on fulfillment yields the value of the input (complete or error). + **/ + static any(value: Promise[]): Promise; - /** - * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. - * @param value The value to be treated as a Promise. - * @returns The promise. - **/ - static as(value: U): Promise; + /** + * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. + * @param value The value to be treated as a Promise. + * @returns The promise. + **/ + static as(value: U): Promise; - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - **/ - cancel(): void; + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; - /** - * Raises an event of the specified type and properties. - * @param type The type (name) of the event. - * @param details The set of additional properties to be attached to the event object. - * @returns true if preventDefault was called on the event; otherwise, false. - **/ - dispatchEvent(type: string, details: any): boolean; + /** + * Raises an event of the specified type and properties. + * @param type The type (name) of the event. + * @param details The set of additional properties to be attached to the event object. + * @returns true if preventDefault was called on the event; otherwise, false. + **/ + dispatchEvent(type: string, details: any): boolean; - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - **/ - done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; - /** - * Determines whether a value fulfills the promise contract. - * @param value A value that may be a promise. - * @returns true if the object conforms to the promise contract (has a then function), otherwise false. - **/ - static is(value: any): boolean; + /** + * Determines whether a value fulfills the promise contract. + * @param value A value that may be a promise. + * @returns true if the object conforms to the promise contract (has a then function), otherwise false. + **/ + static is(value: any): boolean; - /** - * Creates a Promise that is fulfilled when all the values are fulfilled. - * @param values An object whose members contain values, some of which may be promises. - * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. - **/ - static join(values: any): Promise; + /** + * Creates a Promise that is fulfilled when all the values are fulfilled. + * @param values An object whose members contain values, some of which may be promises. + * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. + **/ + static join(values: any): Promise; - /** - * Removes an event listener from the control. - * @param eventType The type (name) of the event. - * @param listener The listener to remove. - * @param capture Specifies whether or not to initiate capture. - **/ - removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param capture Specifies whether or not to initiate capture. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): void; - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the onComplete function. - **/ - then(onComplete?: (value: T) => Windows.Foundation.IPromise, onError?: (error: any) => Windows.Foundation.IPromise, onProgress?: (progress: any) => void): Windows.Foundation.IPromise; + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the onComplete function. - **/ - then(onComplete?: (value: T) => Windows.Foundation.IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Windows.Foundation.IPromise; + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the onComplete function. - **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => Windows.Foundation.IPromise, onProgress?: (progress: any) => void): Windows.Foundation.IPromise; + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the onComplete function. - **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Windows.Foundation.IPromise; + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; - /** - * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. - * @param values A set of values (which could be either an array or an object) of which some or all are promises.. - * @param complete The function to be called if the promise is fulfilled with a value. This function takes a single argument, which is the fulfilled value of the promise. - * @param error The function to be called if the promise is fulfilled with an error. This function takes a single argument, which is the error value of the promise. - * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. - * @returns A Promise that is the result of calling join on the values parameter. - **/ - static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + /** + * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. + * @param values A set of values (which could be either an array or an object) of which some or all are promises.. + * @param complete The function to be called if the promise is fulfilled with a value. This function takes a single argument, which is the fulfilled value of the promise. + * @param error The function to be called if the promise is fulfilled with an error. This function takes a single argument, which is the error value of the promise. + * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. + * @returns A Promise that is the result of calling join on the values parameter. + **/ + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; - /** - * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. - * @param timeout The timeout period in milliseconds. If this value is zero or not specified, msSetImmediate is called, otherwise setTimeout is called. - * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. - * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. - **/ - static timeout(timeout: number, promise?: Promise): Promise; + /** + * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. + * @param timeout The timeout period in milliseconds. If this value is zero or not specified, msSetImmediate is called, otherwise setTimeout is called. + * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. + * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. + **/ + static timeout(timeout: number, promise?: Promise): Promise; - /** - * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. - * @param value Some non-promise value to be wrapped in a promise. - * @returns A promise that is successfully fulfilled with the specified value. - **/ - static wrap(value: U): Promise; + /** + * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. + * @param value Some non-promise value to be wrapped in a promise. + * @returns A promise that is successfully fulfilled with the specified value. + **/ + static wrap(value: U): Promise; - /** - * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. - * @param error A non-promise error value to be wrapped in a promise. - * @returns A promise that is in an error state with the specified value. - **/ - static wrapError(error: U): Promise; + /** + * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. + * @param error A non-promise error value to be wrapped in a promise. + * @returns A promise that is in an error state with the specified value. + **/ + static wrapError(error: U): Promise; - //#endregion Methods + //#endregion Methods - } + } - //#endregion Objects + //#endregion Objects - //#region Functions + //#region Functions - /** - * You can provide an implementation of this method yourself, or use WinJS.Utilities.startLog to create one that logs to the JavaScript console. - * @param message The message to log. - * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). - * @param type The type of message (error, warning, info, etc.). - **/ - function log(message: string, tags: string, type: string): void; + /** + * You can provide an implementation of this method yourself, or use WinJS.Utilities.startLog to create one that logs to the JavaScript console. + * @param message The message to log. + * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). + * @param type The type of message (error, warning, info, etc.). + **/ + function log(message: string, tags: string, type: string): void; - /** - * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. - **/ - function strictProcessing(): void; + /** + * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. + **/ + function strictProcessing(): void; - /** - * Wraps calls to XMLHttpRequest in a promise. - * @param options The options that are applied to the XMLHttpRequest object, as follows: type, url, user, password, responseType, headers, data, customRequestInitializer. - * @returns A promise that returns the XMLHttpRequest object when it completes. - **/ - function xhr(options: IXHROptions): Promise; + /** + * Wraps calls to XMLHttpRequest in a promise. + * @param options The options that are applied to the XMLHttpRequest object, as follows: type, url, user, password, responseType, headers, data, customRequestInitializer. + * @returns A promise that returns the XMLHttpRequest object when it completes. + **/ + function xhr(options: IXHROptions): Promise; - //#endregion Functions + //#endregion Functions - //#region Interfaces + //#region Interfaces - interface IXHROptions { - type?: string; - url: string; - user?: string; - password?: string; - headers?: any; - data: any; - responseType?: string; - } + interface IXHROptions { + type?: string; + url: string; + user?: string; + password?: string; + headers?: any; + data: any; + responseType?: string; + } - //#endregion Interfaces + //#endregion Interfaces } /** * Provides helper functions for defining namespaces. For more information, see Organizing your code with WinJS.Namespace. **/ declare module WinJS.Namespace { - //#region Functions + //#region Functions - /** - * Defines a new namespace with the specified name. For more information, see Organizing your code with WinJS.Namespace. - * @param name The name of the namespace. This could be a dot-separated name for nested namespaces. - * @param members The members of the new namespace. - * @returns The newly-defined namespace. - **/ - function define(name?: string, members?: any): any; + /** + * Defines a new namespace with the specified name. For more information, see Organizing your code with WinJS.Namespace. + * @param name The name of the namespace. This could be a dot-separated name for nested namespaces. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function define(name?: string, members?: any): any; - /** - * Defines a new namespace with the specified name under the specified parent namespace. For more information, see Organizing your code with WinJS.Namespace. - * @param parentNamespace The parent namespace. - * @param name The name of the new namespace. - * @param members The members of the new namespace. - * @returns The newly-defined namespace. - **/ - function defineWithParent(parentNamespace?: any, name?: string, members?: any): any; + /** + * Defines a new namespace with the specified name under the specified parent namespace. For more information, see Organizing your code with WinJS.Namespace. + * @param parentNamespace The parent namespace. + * @param name The name of the new namespace. + * @param members The members of the new namespace. + * @returns The newly-defined namespace. + **/ + function defineWithParent(parentNamespace?: any, name?: string, members?: any): any; - //#endregion Functions + //#endregion Functions } /** * Provides functionality for dealing with basic navigation, including the navigation stack. **/ declare module WinJS.Navigation { - //#region Properties + //#region Properties - /** - * Determines whether it is possible to navigate backwards. - **/ - var canGoBack: boolean; + /** + * Determines whether it is possible to navigate backwards. + **/ + var canGoBack: boolean; - /** - * Determines if it is possible to navigate forwards. - **/ - var canGoForward: boolean; + /** + * Determines if it is possible to navigate forwards. + **/ + var canGoForward: boolean; - /** - * Gets or sets the navigation history. - **/ - var history: any; + /** + * Gets or sets the navigation history. + **/ + var history: any; - /** - * Gets or sets the current location. - **/ - var location: string; + /** + * Gets or sets the current location. + **/ + var location: string; - /** - * Gets or sets a user-defined object that represents the state associated with the current location. - **/ - var state: any; + /** + * Gets or sets a user-defined object that represents the state associated with the current location. + **/ + var state: any; - //#endregion Properties + //#endregion Properties - //#region Functions + //#region Functions - /** - * Adds an event listener to the control. - * @param eventType The type (name) of the event. - * @param listener The listener to invoke when the event gets raised. - * @param capture If true, specifies that capture should be initiated, otherwise false. - **/ - function addEventListener(eventType: string, listener: Function, capture?: boolean): void; + /** + * Adds an event listener to the control. + * @param eventType The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + function addEventListener(eventType: string, listener: Function, capture?: boolean): void; - /** - * Navigates backwards. - * @param distance The number of entries to go back into the history. - * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. - **/ - function back(distance?: number): Promise; + /** + * Navigates backwards. + * @param distance The number of entries to go back into the history. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function back(distance?: number): Promise; - /** - * Navigates forwards. - * @param distance The number of entries to go forward. - * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. - **/ - function forward(distance?: number): Promise; + /** + * Navigates forwards. + * @param distance The number of entries to go forward. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful. + **/ + function forward(distance?: number): Promise; - /** - * Navigates to a location. - * @param location The location to navigate to. Generally the location is a string containing the URL, but it may be anything. - * @param initialState A user-defined object that represents the navigation state that may be accessed through state. - * @returns A promise that is completed with a value that indicates whether or not the navigation was successful (true if successful, otherwise false). - **/ - function navigate(location: any, initialState?: any): Promise; + /** + * Navigates to a location. + * @param location The location to navigate to. Generally the location is a string containing the URL, but it may be anything. + * @param initialState A user-defined object that represents the navigation state that may be accessed through state. + * @returns A promise that is completed with a value that indicates whether or not the navigation was successful (true if successful, otherwise false). + **/ + function navigate(location: any, initialState?: any): Promise; - /** - * Removes an event listener from the control. - * @param eventType The type (name) of the event. - * @param listener The listener to remove. - * @param useCapture Specifies whether or not to initiate capture. - **/ - function removeEventListener(eventType: string, listener: Function, useCapture?: boolean): void; + /** + * Removes an event listener from the control. + * @param eventType The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture Specifies whether or not to initiate capture. + **/ + function removeEventListener(eventType: string, listener: Function, useCapture?: boolean): void; - //#endregion Functions + //#endregion Functions - //#region Events + //#region Events - /** - * Occurs before navigation. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. - **/ - function onbeforenavigate(eventInfo: CustomEvent): void; + /** + * Occurs before navigation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onbeforenavigate(eventInfo: CustomEvent): void; - /** - * Occurs after navigation has taken place. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. - **/ - function onnavigated(eventInfo: CustomEvent): void; + /** + * Occurs after navigation has taken place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigated(eventInfo: CustomEvent): void; - /** - * Occurs when navigation is taking place. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. - **/ - function onnavigating(eventInfo: CustomEvent): void; + /** + * Occurs when navigation is taking place. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: location, state. + **/ + function onnavigating(eventInfo: CustomEvent): void; - //#endregion Events + //#endregion Events } /** * Provides functions for accessing resources and localizing content. **/ declare module WinJS.Resources { - //#region Functions + //#region Functions - /** - * Registers an event handler for the specified event. Use this method to register for events that are related to resources, such as when the app's language, scale, or contrast changes. - * @param type The name of the event to handle. - * @param listener The listener (event handler function) to associate with the event. - * @param useCapture Set to true to register the listener for the capturing phase; otherwise, set to false to register the listener for the bubbling phase. - **/ - function addEventListener(type: string, listener: Function, useCapture?: boolean): void; + /** + * Registers an event handler for the specified event. Use this method to register for events that are related to resources, such as when the app's language, scale, or contrast changes. + * @param type The name of the event to handle. + * @param listener The listener (event handler function) to associate with the event. + * @param useCapture Set to true to register the listener for the capturing phase; otherwise, set to false to register the listener for the bubbling phase. + **/ + function addEventListener(type: string, listener: Function, useCapture?: boolean): void; - /** - * Raises an event of the specified type and with the specified additional properties. - * @param type The name of the event to raise. - * @param details The set of additional properties to attach to the event object. - **/ - function dispatchEvent(type: string, details: any): void; + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The name of the event to raise. + * @param details The set of additional properties to attach to the event object. + **/ + function dispatchEvent(type: string, details: any): void; - /** - * Retrieves the resource string that has the specified resource identifier. - * @param resourceId The resource ID of the string to retrieve. - * @returns An object that can contain these properties: value, empty, lang. - **/ - function getString(resourceId: string): { value: string; empty?: boolean; lang?: string; }; + /** + * Retrieves the resource string that has the specified resource identifier. + * @param resourceId The resource ID of the string to retrieve. + * @returns An object that can contain these properties: value, empty, lang. + **/ + function getString(resourceId: string): { value: string; empty?: boolean; lang?: string; }; - /** - * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. - * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. - **/ - function processAll(rootElement?: HTMLElement): void; + /** + * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. + * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. + **/ + function processAll(rootElement?: HTMLElement): void; - /** - * Removes an event listener that the addEventListener method registered. - * @param type The name of the event that the event listener is registered for. - * @param listener The listener (event handler function) to remove. - * @param useCapture Set to true to remove the capturing phase listener; set to false to remove the bubbling phase listener. - **/ - function removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + /** + * Removes an event listener that the addEventListener method registered. + * @param type The name of the event that the event listener is registered for. + * @param listener The listener (event handler function) to remove. + * @param useCapture Set to true to remove the capturing phase listener; set to false to remove the bubbling phase listener. + **/ + function removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - //#endregion Functions + //#endregion Functions - //#region Events + //#region Events - /** - * Occurs when the user changes the system's language or contrast, or the scale of the display, or when the user changes any of the items in the current context's qualifier values list. For more info about the current context's qualifier values list, see the Remarks section. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.qualifier, detail.changed. - **/ - function oncontextchanged(eventInfo: CustomEvent): void; + /** + * Occurs when the user changes the system's language or contrast, or the scale of the display, or when the user changes any of the items in the current context's qualifier values list. For more info about the current context's qualifier values list, see the Remarks section. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.qualifier, detail.changed. + **/ + function oncontextchanged(eventInfo: CustomEvent): void; - //#endregion Events + //#endregion Events } /** * Provides access to the Windows animations. These functions provide developers with the ability to use animations in their custom controls that are consistent with animations used by Windows controls. **/ declare module WinJS.UI.Animation { - //#region Functions + //#region Functions - /** - * Creates an object that performs an animation that adds an item or items to a list. - * @param added Element or elements to add to the list. - * @param affected Element or elements affected by the added items. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. - **/ - function createAddToListAnimation(added: any, affected: any): IAnimationMethodResponse; + /** + * Creates an object that performs an animation that adds an item or items to a list. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToListAnimation(added: any, affected: any): IAnimationMethodResponse; - /** - * Creates an object that performs an animation that adds an item or items to a list of search results. - * @param added Element or elements to add to the list. - * @param affected Element or elements affected by the added items. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. - **/ - function createAddToSearchListAnimation(added: any, affected: any): IAnimationMethodResponse; + /** + * Creates an object that performs an animation that adds an item or items to a list of search results. + * @param added Element or elements to add to the list. + * @param affected Element or elements affected by the added items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createAddToSearchListAnimation(added: any, affected: any): IAnimationMethodResponse; - /** - * Creates an object that performs an animation that collapses a list. - * @param hidden Element or elements hidden as a result of the collapse. - * @param affected Element or elements affected by the hidden items. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. - **/ - function createCollapseAnimation(hidden: any, affected: any): IAnimationMethodResponse; + /** + * Creates an object that performs an animation that collapses a list. + * @param hidden Element or elements hidden as a result of the collapse. + * @param affected Element or elements affected by the hidden items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createCollapseAnimation(hidden: any, affected: any): IAnimationMethodResponse; - /** - * Creates an object that performs an animation that removes an item or items from a list. - * @param deleted Element or elements to delete from the list. - * @param remaining Element or elements affected by the removal of the deleted items. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. - **/ - function createDeleteFromListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + /** + * Creates an object that performs an animation that removes an item or items from a list. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; - /** - * Creates an object that performs an animation that removes an item or items from a list of search results. - * @param deleted Element or elements to delete from the list. - * @param remaining Element or elements affected by the removal of the deleted items. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. - **/ - function createDeleteFromSearchListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; + /** + * Creates an object that performs an animation that removes an item or items from a list of search results. + * @param deleted Element or elements to delete from the list. + * @param remaining Element or elements affected by the removal of the deleted items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createDeleteFromSearchListAnimation(deleted: any, remaining: any): IAnimationMethodResponse; - /** - * Creates an object that performs an animation that expands a list. - * @param revealed Element or elements revealed by the expansion. - * @param affected Element or elements affected by the newly revealed items. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. - **/ - function createExpandAnimation(revealed: any, affected: any): IAnimationMethodResponse; + /** + * Creates an object that performs an animation that expands a list. + * @param revealed Element or elements revealed by the expansion. + * @param affected Element or elements affected by the newly revealed items. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createExpandAnimation(revealed: any, affected: any): IAnimationMethodResponse; - /** - * Creates an object that performs a peek animation. - * @param element Element or elements involved in the peek. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. - **/ - function createPeekAnimation(element: any): IAnimationMethodResponse; + /** + * Creates an object that performs a peek animation. + * @param element Element or elements involved in the peek. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise that completes when the animation is finished. + **/ + function createPeekAnimation(element: any): IAnimationMethodResponse; - /** - * Creates an object that performs an animation that moves an item or items. - * @param element Element or elements involved in the reposition. - * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise object that completes when the animation is finished. - **/ - function createRepositionAnimation(element: any): IAnimationMethodResponse; + /** + * Creates an object that performs an animation that moves an item or items. + * @param element Element or elements involved in the reposition. + * @returns An object whose execute method is used to execute the animation. The execute method returns a Promise object that completes when the animation is finished. + **/ + function createRepositionAnimation(element: any): IAnimationMethodResponse; - /** - * Performs an animation that fades an item or items in, fading out existing items that occupy the same space. - * @param incoming Element or elements being faded in. - * @param outgoing Element or elements being replaced. - * @returns An object that completes when the animation has finished. - **/ - function crossFade(incoming: any, outgoing: any): Promise; + /** + * Performs an animation that fades an item or items in, fading out existing items that occupy the same space. + * @param incoming Element or elements being faded in. + * @param outgoing Element or elements being replaced. + * @returns An object that completes when the animation has finished. + **/ + function crossFade(incoming: any, outgoing: any): Promise; - /** - * Performs an animation when a dragged object is moved such that dropping it in that position would move other items. The potentially affected items are animated out of the way to show where the object would be dropped. - * @param target Element or elements that the dragged object would cause to be moved if it were dropped. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function dragBetweenEnter(target: any, offset: any): Promise; + /** + * Performs an animation when a dragged object is moved such that dropping it in that position would move other items. The potentially affected items are animated out of the way to show where the object would be dropped. + * @param target Element or elements that the dragged object would cause to be moved if it were dropped. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenEnter(target: any, offset: any): Promise; - /** - * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. - * @param target Element or elements that the dragged object would no longer cause to be displaced, due to its moving away. This should be the same element or element collection passed as the target parameter in the dragBetweenEnter animation. - * @returns An object that completes when the animation is finished. - **/ - function dragBetweenLeave(target: any): Promise; + /** + * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. + * @param target Element or elements that the dragged object would no longer cause to be displaced, due to its moving away. This should be the same element or element collection passed as the target parameter in the dragBetweenEnter animation. + * @returns An object that completes when the animation is finished. + **/ + function dragBetweenLeave(target: any): Promise; - /** - * Performs an animation when the user finishes dragging an object. - * @param dragSource Element or elements that were dragged. - * @param offset Initial offset from the drop point. The dropped object begins at the offset and animates to its final position at the drop point. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. - * @returns An object that completes when the animation is finished. - **/ - function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + /** + * Performs an animation when the user finishes dragging an object. + * @param dragSource Element or elements that were dragged. + * @param offset Initial offset from the drop point. The dropped object begins at the offset and animates to its final position at the drop point. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; - /** - * Performs an animation when the user begins to drag an object. - * @param dragSource Element or elements being dragged. - * @param affected Element or elements whose position is affected by the movement of the dragged object. Typically, this is all other items in a reorderable list. - * @returns An object that completes when the animation is finished. - **/ - function dragSourceStart(dragSource: any, affected?: any): Promise; + /** + * Performs an animation when the user begins to drag an object. + * @param dragSource Element or elements being dragged. + * @param affected Element or elements whose position is affected by the movement of the dragged object. Typically, this is all other items in a reorderable list. + * @returns An object that completes when the animation is finished. + **/ + function dragSourceStart(dragSource: any, affected?: any): Promise; - /** - * Performs an animation that displays one or more elements on a page. - * @param incoming Element or elements that compose the incoming content. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. - * @returns An object that completes when the animation is finished. - **/ - function enterContent(incoming: any, offset: any, options?: any): Promise; + /** + * Performs an animation that displays one or more elements on a page. + * @param incoming Element or elements that compose the incoming content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function enterContent(incoming: any, offset: any, options?: any): Promise; - /** - * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. - * @param element Element or an array of elements that represent the content. If element refers to an array of elements, the elements enter in array order. - * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function enterPage(element: any, offset: any): Promise; + /** + * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. + * @param element Element or an array of elements that represent the content. If element refers to an array of elements, the elements enter in array order. + * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function enterPage(element: any, offset: any): Promise; - /** - * Performs an animation that hides one or more elements on a page. - * @param outgoing Element or elements that compose the outgoing content. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function exitContent(outgoing: any, offset: any): Promise; + /** + * Performs an animation that hides one or more elements on a page. + * @param outgoing Element or elements that compose the outgoing content. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitContent(outgoing: any, offset: any): Promise; - /** - * Performs an animation that dismisses the current page when transitioning between pages in an app. - * @param outgoing Element or elements that compose the outgoing page. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function exitPage(outgoing: any, offset: any): Promise; + /** + * Performs an animation that dismisses the current page when transitioning between pages in an app. + * @param outgoing Element or elements that compose the outgoing page. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function exitPage(outgoing: any, offset: any): Promise; - /** - * Performs an animation that fades an item or set of items into view. - * @param shown Element or elements being faded in. - * @returns An object that completes when the animation has finished. Use this object when subsequent actions need this animation to finish before they take place. - **/ - function fadeIn(shown: any): Promise; + /** + * Performs an animation that fades an item or set of items into view. + * @param shown Element or elements being faded in. + * @returns An object that completes when the animation has finished. Use this object when subsequent actions need this animation to finish before they take place. + **/ + function fadeIn(shown: any): Promise; - /** - * Performs an animation that fades an item or set of items out of view. - * @param hidden Element or elements being faded out. - * @returns An object that completes when the animation is finished. - **/ - function fadeOut(hidden: any): Promise; + /** + * Performs an animation that fades an item or set of items out of view. + * @param hidden Element or elements being faded out. + * @returns An object that completes when the animation is finished. + **/ + function fadeOut(hidden: any): Promise; - /** - * Performs an animation that hides edge-based user interface (UI). - * @param element Element or elements that are being hidden. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. - * @returns An object that completes when the animation is finished. - **/ - function hideEdgeUI(element: any, offset: any, options?: any): Promise; + /** + * Performs an animation that hides edge-based user interface (UI). + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function hideEdgeUI(element: any, offset: any, options?: any): Promise; - /** - * Performs an animation that hides a panel. - * @param element Element or elements that are being hidden. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function hidePanel(element: any, offset: any): Promise; + /** + * Performs an animation that hides a panel. + * @param element Element or elements that are being hidden. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function hidePanel(element: any, offset: any): Promise; - /** - * Performs an animation that removes pop-up user interface (UI). - * @param element Element or elements that are being hidden. - * @returns An object that completes when the animation is finished. - **/ - function hidePopup(element: any): Promise; + /** + * Performs an animation that removes pop-up user interface (UI). + * @param element Element or elements that are being hidden. + * @returns An object that completes when the animation is finished. + **/ + function hidePopup(element: any): Promise; - /** - * Performs an animation when a pointer is pressed on an object. - * @param element Element or elements on which the pointer is pressed. - * @returns An object that completes when the animation is finished. - **/ - function pointerDown(element: any): Promise; + /** + * Performs an animation when a pointer is pressed on an object. + * @param element Element or elements on which the pointer is pressed. + * @returns An object that completes when the animation is finished. + **/ + function pointerDown(element: any): Promise; - /** - * Performs an animation when a pointer is released. - * @param element Element or elements that the pointer was pressed on. - * @returns An object that completes when the animation is finished. - **/ - function pointerUp(element: any): Promise; + /** + * Performs an animation when a pointer is released. + * @param element Element or elements that the pointer was pressed on. + * @returns An object that completes when the animation is finished. + **/ + function pointerUp(element: any): Promise; - /** - * Performs an animation that slides a narrow, edge-based user interface (UI) into view. - * @param element Element or elements that are being shown. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. - * @returns An object that completes when the animation is finished. - **/ - function showEdgeUI(element: any, offset: any, options?: any): Promise; + /** + * Performs an animation that slides a narrow, edge-based user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. + * @returns An object that completes when the animation is finished. + **/ + function showEdgeUI(element: any, offset: any, options?: any): Promise; - /** - * Performs an animation that slides a large panel user interface (UI) into view. - * @param element Element or elements that are being shown. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function showPanel(element: any, offset: any): Promise; + /** + * Performs an animation that slides a large panel user interface (UI) into view. + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPanel(element: any, offset: any): Promise; - /** - * Performs an animation that displays a pop-up user interface (UI). - * @param element Element or elements that are being shown. - * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function showPopup(element: any, offset: any): Promise; + /** + * Performs an animation that displays a pop-up user interface (UI). + * @param element Element or elements that are being shown. + * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function showPopup(element: any, offset: any): Promise; - /** - * Performs a deselection animation in response to a swipe interaction. - * @param deselected Element or elements that become unselected. - * @param selection Element or elements that represent the selection, typically a check mark. - * @returns An object that completes when the animation is finished. - **/ - function swipeDeselect(deselected: any, selection: any): Promise; + /** + * Performs a deselection animation in response to a swipe interaction. + * @param deselected Element or elements that become unselected. + * @param selection Element or elements that represent the selection, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeDeselect(deselected: any, selection: any): Promise; - /** - * Performs an animation that reveals an item or items in response to a swipe interaction. - * @param target Element or elements being revealed. - * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function swipeReveal(target: any, offset: any): Promise; + /** + * Performs an animation that reveals an item or items in response to a swipe interaction. + * @param target Element or elements being revealed. + * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function swipeReveal(target: any, offset: any): Promise; - /** - * Performs a selection animation in response to a swipe interaction. - * @param selected Element or elements being selected. - * @param selection Element or elements that show that something is selected, typically a check mark. - * @returns An object that completes when the animation is finished. - **/ - function swipeSelect(selected: any, selection: any): Promise; + /** + * Performs a selection animation in response to a swipe interaction. + * @param selected Element or elements being selected. + * @param selection Element or elements that show that something is selected, typically a check mark. + * @returns An object that completes when the animation is finished. + **/ + function swipeSelect(selected: any, selection: any): Promise; - /** - * Performs an animation that updates a badge. - * @param incoming Element or elements that comprise the new badge. - * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. - * @returns An object that completes when the animation is finished. - **/ - function updateBadge(incoming: any, offset: any): Promise; + /** + * Performs an animation that updates a badge. + * @param incoming Element or elements that comprise the new badge. + * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. + * @returns An object that completes when the animation is finished. + **/ + function updateBadge(incoming: any, offset: any): Promise; - //#endregion Functions + //#endregion Functions - //#region Interfaces + //#region Interfaces - interface IAnimationMethodResponse { - execute(): Promise; - } + interface IAnimationMethodResponse { + execute(): Promise; + } - //#endregion Interfaces + //#endregion Interfaces } /** * Provides controls and objects that manipulate data. **/ declare module WinJS.UI { - //#region Enumerations - - /** - * Specifies an icon that appears in an AppBarCommand object. - **/ - enum AppBarIcon { - previous, - next, - play, - pause, - edit, - save, - clear, - delete, - remove, - add, - cancel, - accept, - more, - redo, - undo, - home, - up, - forward, - right, - back, - left, - favorite, - camera, - settings, - video, - sync, - download, - mail, - find, - help, - upload, - emoji, - twopage, - leavechat, - mailforward, - clock, - send, - crop, - rotatecamera, - people, - closepane, - openpane, - world, - flag, - previewlink, - globe, - trim, - attachcamera, - zoomin, - bookmarks, - document, - protecteddocument, - page, - bullets, - comment, - mail2, - contactinfo, - hangup, - viewall, - mappin, - phone, - videochat, - switch, - contact, - rename, - pin, - musicinfo, - go, - keyboard, - dockleft, - dockright, - dockbottom, - remote, - refresh, - rotate, - shuffle, - list, - shop, - selectall, - orientation, - import, - importall, - browsephotos, - webcam, - pictures, - savelocal, - caption, - stop, - showresults, - volume, - repair, - message, - page2, - calendarday, - calendarweek, - calendar, - characters, - mailreplyall, - read, - link, - accounts, - showbcc, - hidebcc, - cut, - attach, - paste, - filter, - copy, - emoji2, - important, - mailreply, - slideshow, - sort, - manage, - allapps, - disconnectdrive, - mapdrive, - newwindow, - openwith, - contactpresence, - priority, - uploadskydrive, - gototoday, - font, - fontcolor, - contact2, - folder, - audio, - placeholder, - view, - setlockscreen, - settile, - cc, - stopslideshow, - permissions, - highlight, - disableupdates, - unfavorite, - unpin, - openlocal, - mute, - italic, - underline, - bold, - movetofolder, - likedislike, - dislike, - like, - alignright, - aligncenter, - alignleft, - zoom, - zoomout, - openfile, - otheruser, - admin, - street, - map, - clearselection, - fontdecrease, - fontincrease, - fontsize, - cellphone, - reshare, - tag, - repeatone, - repeatall, - outlinestar, - solidstar, - calculator, - directions, - target, - library, - phonebook, - memo, - microphone, - postupdate, - backtowindow, - fullscreen, - newfolder, - calendarreply, - unsyncfolder, - reporthacked, - syncfolder, - blockcontact, - switchapps, - addfriend, - touchpointer, - gotostart, - zerobars, - onebar, - twobars, - threebars, - fourbars, - scan, - preview - } - - /** - * Indicates whether the IListDataAdapter was able to provide a count. - **/ - enum CountResult { - /** - * Indicates no count is available. - **/ - unknown - } - - /** - * Indicates that the IListDataAdapter was unable to provide a count. - **/ - enum CountError { - /** - * An attempt to count items timed out. - **/ - noResponse - } - - /** - * Describes the status of an IListDataSource. - **/ - enum DataSourceStatus { - /** - * The IListDataSource is ready. - **/ - ready, - /** - * The IListDataSource is still loading. - **/ - waiting, - /** - * The IListDataSource failed to load. - **/ - failure - } - - /** - * Specifies the type of error that occurred during an edit operation on a IListDataSource or an IListDataAdapter. - **/ - enum EditError { - /** - * The edit operation timed out. - **/ - noResponse, - /** - * The data source cannot be written to. - **/ - notPermitted, - /** - * The item has changed. - **/ - noLongerMeaningful - } - - /** - * Specifies the type of error encountered when retrieving items from an IListDataAdapter. - **/ - enum FetchError { - /** - * The fetch operation timed out. - **/ - noResponse, - /** - * The specified item could not be located. - **/ - doesNotExist - } - - /** - * Specifies how group headers in a ListView respond to the tap interaction. - **/ - enum GroupHeaderTapBehavior { - /** - * The group is invoked. - **/ - invoke, - /** - * Nothing happens. - **/ - none - } - - /** - * Specifies the position of group headers relative to their items in a ListView. - **/ - enum HeaderPosition { - /** - * Group headers appear to the left of items. - **/ - left, - /** - * Group headers appear above items. - **/ - top - } - - /** - * Specifies that type of animation for which a contentanimating event was raised. - **/ - enum ListViewAnimationType { - /** - * The animation plays when the ListView is first displayed. - **/ - entrance, - /** - * The animation plays when the ListView is changing its content. - **/ - contentTransition - } - - /** - * Describes the type of object in a ListView. - **/ - enum ObjectType { - /** - * The object is a group header in the list. - **/ - groupHeader, - /** - * The object is an item in the list. - **/ - item - } - - /** - * Specifies the orientation of a control. - **/ - enum Orientation { - /** - * A horizontal layout. - **/ - horizontal, - /** - * A vertical layout. - **/ - vertical - } - - /** - * Specifies the selection mode of a ListView. - **/ - enum SelectionMode { - /** - * Items cannot be selected. - **/ - none, - /** - * A single item may be selected. - **/ - single, - /** - * Multiple items may be selected. Clicking additional items adds them to the selection. - **/ - multi - } - - /** - * Specifies whether elements are selected when the user performs a swipe interaction. - **/ - enum SwipeBehavior { - /** - * The swipe interaction selects the elements touched by the swipe. - **/ - select, - /** - * The swipe interaction does not change which elements are selected. - **/ - none - } - - /** - * Specifies how items in a ListView respond to the tap interaction. - **/ - enum TapBehavior { - /** - * The item is selected and invoked. - **/ - directSelect, - /** - * The item is selected if was not already selected, and its deselected if it was already selected. - **/ - toggleSelect, - /** - * The item is invoked but not selected. - **/ - invokeOnly, - /** - * Nothing happens. - **/ - none - } - - //#endregion Enumerations - - //#region Interfaces - - /** - * Contains items that were requested from an IListDataAdapter and provides some information about those items. - **/ - interface IFetchResult { - //#region Properties - - /** - * Gets or sets the index of the requested item in the IListDataAdapter object's data source. - **/ - absoluteIndex: number; - - /** - * Gets or sets a value that indicates whether this IFetchResult contains the last items at the end of the IListDataAdapter object's data source. - **/ - atEnd: boolean; - - /** - * Gets or sets a value that indicates whether this IFetchResult contains the first items at the beginning of the IListDataAdapter object's data source. - **/ - atStart: boolean; - - /** - * Gets or sets the items returned by the fetch operation. - **/ - items: T[]; - - /** - * Gets or sets the location of the requested item within the items array. - **/ - offset: number; - - /** - * Gets or sets the number of items in the IListDataAdapter object's underlying data source. - **/ - totalCount: number; - - //#endregion Properties - - } - - /** - * Represents an item in a list. - **/ - interface IItem { - //#region Properties - - /** - * Gets or sets the item's data. - **/ - data: T; - - /** - * Gets the group key for the item. This property is only available for items that belong to a grouped data source. - **/ - groupKey: string; - - /** - * Gets the temporary ID of the item. - **/ - handle: string; - - /** - * Gets the item's index in the IListDataSource. - **/ - index: number; - - /** - * Gets or sets the key the identifies the item. - **/ - key: string; - - //#endregion Properties - - } - - /** - * Provides a mechanism for retrieving IItem objects asynchronously. - **/ - interface IItemPromise { - //#region Events - - /** - * Occurs when there is an error in processing. - * @param eventInfo An object that contains information about the event. - **/ - onerror(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - **/ - cancel(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - **/ - done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; - - /** - * Stops change notification tracking for the IItem that fulfills this IItemPromise. - **/ - release(): void; - - /** - * Begins change notification tracking for the IItem that fulfills this IItemPromise. - **/ - retain(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the complete or error function. - **/ - then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the temporary ID of the IItem that fulfills this promise. - **/ - handle: string; - - /** - * Gets or sets the index of the IItem contained by this IItemPromise. - **/ - index: number; - - //#endregion Properties - - } - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. Represents a layout for the ListView. - **/ - interface ILayout { - //#region Methods - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param beginScrollPosition The first visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. - * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. - * @returns A Promise for the index of the first visible item at the specified point. - **/ - calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): Promise; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param endScrollPosition The last visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. - * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. - * @returns A Promise for the index of the last visible item at the specified point. - **/ - calculateLastVisible(endScrollPosition: number, wholeItem: boolean): Promise; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @returns A object that has these properties: animationPromise, newEndIndex. - **/ - endLayout(): any; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param itemIndex The index of the item. - * @returns A Promise that returns an object with these properties: left, top, contentWidth, contentHeight, totalWidth, totalHeight. - **/ - getItemPosition(itemIndex: number): Promise; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param itemIndex The data source index of the current item. - * @param element The element for the current item. - * @param keyPressed The key that was pressed. This function must check for the arrow keys (leftArrow, upArrow, rightArrow, downArrow), pageDown, and pageUp and determine which item the user navigated to. - * @returns A Promise that contains the index of the next item (This item becomes the current item). - **/ - getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: WinJS.Utilities.Key): Promise; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @returns A Promise that returns an object that has these properties: beginScrollPosition, endScrollPosition. - **/ - getScrollBarRange(): Promise; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param x The x-coordinate to test. - * @param y The y-coordinate to test. - **/ - hitTest(x: number, y: number): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param elements The elements that represent the items that were added. - **/ - itemsAdded(elements: HTMLElement[]): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - **/ - itemsMoved(): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param elements The elements that represent the items that were removed. - **/ - itemsRemoved(elements: HTMLElement[]): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param groupIndex The index of the group in the group data source. - * @param element The element to render for the group header. - **/ - layoutHeader(groupIndex: number, element: HTMLElement): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param itemIndex The index of the item in the data source. - * @param element The element to render for the item. - **/ - layoutItem(itemIndex: number, element: HTMLElement): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param element The element that represents a header in the data source. - **/ - prepareHeader(element: HTMLElement): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param element An element that represents an item in the data source. - **/ - prepareItem(element: HTMLElement): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param element The element being released. - **/ - releaseItem(element: HTMLElement): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - **/ - reset(): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param site The layout site for the layout. You can use this object to query the hosting ListView for info you might need to lay out items. - **/ - setSite(site: ILayoutSite): void; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - * @param beginScrollPosition The starting pixel of the area to which the items are rendered. - * @param endScrollPosition The last pixel of the area to which the items are rendered. - * @param count The upper bound of the number of items to render. - * @returns A Promise that returns an object that has these properties: beginIndex, endIndex. - **/ - startLayout(beginScrollPosition: number, endScrollPosition: number, count: number): Promise; - - //#endregion Methods - - //#region Properties - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. - **/ - horizontal: boolean; - - //#endregion Properties - - } - - /** - * Represents a layout for the ListView. - **/ - interface ILayout2 { - //#region Methods - - /** - * Called when the ListView finishes a drag operation. - **/ - dragLeave(): void; - - /** - * Called when the ListView initiates a drag operation. - * @param x The x-coordinate of the drag. - * @param y The y-coordinate of the drag. - * @param dragInfo An object that indicates whether the item is selected. - **/ - dragOver(x: number, y: number, dragInfo: number): void; - - /** - * Called when the ListView requests that the ILayout2 execute animations. - **/ - executeAnimations(): void; - - /** - * Determines the next item to receive keyboard focus. - * @param currentItem An object that describes the current item. It has these properties: index, type. - * @param pressedKey The key that was pressed. - * @returns An object that describes the next item that should receive focus. It has these properties: index, type. - **/ - getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; - - /** - * Gets the item at the specified hit-test coordinates. These coordinates are absolute coordinates (they are not relative to the layout's content area). - * @param x The x-coordinate to test for. - * @param y The y-coordinate to test for. - * @returns An object that describes the item at the hit test coordinates. It has these properties: type, index. - **/ - hitTest(x: number, y: number): any; - - /** - * Sets the rendering site and specifies whether the layout supports groups. This method is called by the ListView to initialize the layout. - * @param site The rendering site for the layout. - * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. - **/ - initialize(site: ILayoutSite2, groupsEnabled: boolean): void; - - /** - * Retrieves the indexes of the items in the specified pixel range. - * @param firstPixel The first pixel the range of items falls between. - * @param lastPixel The last pixel the range of items falls between. - **/ - itemsFromRange(firstPixel: number, lastPixel: number): void; - - /** - * Performs a layout pass. - * @param tree A structure representing the layout tree that is returned from the ListView. - * @param changedRange An object that lists the index of the first item in the changed item range. This object has these properties: startIndex. - * @param modifiedItems An object that contains the old and new indexes of the items that have been modified in the tree. - * @param modifiedGroups An object that contains the old and new indexes of the group elements that have been modified in the tree. - * @returns A Promise that executes after layout is complete, or an object that contains two Promise objects: realizedRangeComplete, layoutComplete. - **/ - layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): any; - - /** - * Called when the ListView requests that the ILayout2 set up animations. - **/ - setupAnimations(): void; - - /** - * Releases resources that were obtained during the call to initialize. - **/ - uninitialize(): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the orientation of the layout. - **/ - orientation: any; - - //#endregion Properties - - } - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayoutSite2 interface. Represents a rendering site for an ILayout. - **/ - interface ILayoutSite { - //#region Properties - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. - **/ - animationsDisabled: boolean; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. - **/ - itemSurface: HTMLElement; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. - **/ - rtl: boolean; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. - **/ - scrollbarPos: number; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. - **/ - surface: HTMLElement; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. - **/ - viewport: HTMLElement; - - /** - * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. - **/ - viewportSize: any; - - //#endregion Properties - - } - - /** - * Represents a rendering site for an ILayout2. - **/ - interface ILayoutSite2 { - //#region Properties - - /** - * Gets the number of groups in the site. - **/ - groupCount: number; - - /** - * Gets the number of items in the site. - **/ - itemCount: Promise; - - /** - * Gets the pixel range of the realization area. - **/ - realizedRange: any; - - /** - * Gets the tree for use by an object that implements the ILayout2 interface. - **/ - tree: any; - - /** - * Gets the pixel range of visible items in the site. - **/ - visibleRange: any; - - //#endregion Properties - - } - - /** - * Retrieves items from a IListDataSource, enumerates the contents of a IListDataSource, and can optionally register for change notifications. - **/ - interface IListBinding { - //#region Methods - - /** - * Retrieves the current item. - * @returns An IItemPromise that contains the current item. If the cursor has moved past the start or end of the list, the promise completes with a value of null. If the current item has been moved or deleted, the promise returns an error. - **/ - current(): IItemPromise>; - - /** - * Gets the first item from the IListDataSource and makes it the current item. - * @returns An IItemPromise that contains the requested IItem. If the list is empty, the promise completes with a value of null. - **/ - first(): IItemPromise>; - - /** - * Retrieves the item from the IListDataSource that has the specified description and makes it the current item. - * @param description A domain-specific description, to be interpreted by the IListDataAdapter, that identifies the item to retrieve. - * @returns An IItemPromise that contains the requested IItem object. If the item wasn't found, the promise completes with a value of null. - **/ - fromDescription(description: string): IItemPromise>; - - /** - * Retrieves the item from the IListDataSource that has the specified index and makes it the current item. - * @param index A value greater than or equal to 0 that is the index of the item to retrieve. - * @returns An IItemPromise that contains the requested IItem. If the item wasn't found, the promise completes with a value of null. - **/ - fromIndex(index: number): IItemPromise>; - - /** - * Retrieves the item from the IListDataSource that has the specified key and makes it the current item. - * @param key The key that identifies the item to retrieve. This value must be a non-empty string. - * @param hints Domain-specific information that provides additional information to the IListDataAdapter to improve retrieval time. - * @returns An IItemPromise that contains the requested IItem. If they item couldn't be found, the promise completes with a value of null. - **/ - fromKey(key: string, hints?: any): IItemPromise>; - - /** - * Makes the specified IItem or IItemPromise the current item. - * @param item The IItem or IItemPromise that will become the current item. - * @returns An IItemPromise that contains the specified item, if it exists. If the specified item is not in the list, the promise completes with a value of null. - **/ - jumpToItem(item: IItem): IItemPromise>; - - /** - * Retrieves the last item in the IListDataSource and makes it the current item. - * @returns An IItemPromise that contains the requested IItem. f the list is empty, the promise completes with a value of null. - **/ - last(): IItemPromise>; - - /** - * Retrieves the item after the current item and makes it the current item. - * @returns An IItemPromise that contains the item after the current item. If the cursor moves past the end of the list, the promise completes with a value of null. - **/ - next(): IItemPromise>; - - /** - * Retrieves the item before the current item and makes it the current item. - * @returns An IItemPromise that contains the item before the current item. If the cursor moves past the start of the list, the promise completes with a value of null. - **/ - previous(): IItemPromise>; - - /** - * Releases resources, stops notifications, and cancels outstanding promises for all tracked items returned by this IListBinding. - **/ - release(): void; - - /** - * Creates a request to stop change notifications for the specified item. The change notifications stop when the number of releaseItem calls matches the number of IIItemPromise.retain calls. - * @param item The IItem or IItemPromise that should stop receiving notifications. - **/ - releaseItem(item: IItem): void; - - //#endregion Methods - - } - - /** - * Accesses data for an IListDataSource. - **/ - interface IListDataAdapter { - //#region Methods - - /** - * Overwrites the data of the specified item. - * @param key The key of the item to overwrite. - * @param newData The new data for the item. - * @param indexHint The index of the item, if known. - * @returns A Promise that returns null or undefined when the operation completes. - **/ - change(key: string, newData: T, indexHint: number): Promise; - - /** - * Gets the number of items in the IListDataAdapter object's data source. - * @returns A Promise that contains the number of items the IListDataAdapter contains, or an approximate value if the actual number is unknown. - **/ - getCount(): Promise; - - /** - * Inserts the specified data after the specified item. - * @param key A key that can be used to retrieve the new data. - * @param data The new data to add to the IListDataAdapter object's data source. - * @param previousKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted after this item. - * @param previousIndexHint The index of the item to insert the new data after, if known. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertAfter(key: string, data: T, previousKey: string, previousIndexHint: number): Promise>; - - /** - * Adds the specified key and data to the end of the IListDataAdapter object's data source. - * @param key A key that can be used to retrieve the new data. - * @param data The new data to add to the IListDataAdapter object's data source. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertAtEnd(key: string, data: T): Promise>; - - /** - * Adds the specified key and data to the beginning of the IListDataAdapter object's data source. - * @param key A key that can be used to retrieve the new data. - * @param data The new data to add to the IListDataAdapter object's data source. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertAtStart(key: string, data: T): Promise>; - - /** - * Inserts the specified data before the specified item. - * @param key A key that can be used to retrieve the new data. - * @param data The new data to add to the IListDataAdapter object's data source. - * @param nextKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted before this item. - * @param nextIndexHint The index of the item to insert the new data before, if known. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertBefore(key: string, data: T, nextKey: string, nextIndexHint: number): Promise>; - - /** - * Retrieves the item that matches the specified description and also retrieves the specified number of items before and after the matched item. - * @param description A description of the item to locate. - * @param countBefore The number of items before the matched item to retrieve. - * @param countAfter The number of items after the matched item to retrieve. - * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. - **/ - itemsFromDescription(description: string, countBefore: number, countAfter: number): Promise>; - - /** - * Retrieves the specified number of items from the end of the IListDataAdapter object's data source. - * @param count The number of items to retrieve. - * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. - **/ - itemsFromEnd(count: number): Promise>; - - /** - * Retrieves the item at the specified index and also retrieves the specified number of items before and after the selected item. - * @param index The index of the item to retrieve. - * @param countBefore The number of items to retrieve from before the selected item. - * @param countAfter The number of items to retrieve from after the selected item. - * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. - **/ - itemsFromIndex(index: number, countBefore: number, countAfter: number): Promise>; - - /** - * Retrieves the item that has the specified key and also retrieves the specified number of items before and after the selected item. - * @param key The key of the item to retrieve. - * @param countBefore The number of items to retrieve from before the selected item. - * @param countAfter The number of items to retrieve from after the selected item. - * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. - **/ - itemsFromKey(key: string, countBefore: number, countAfter: number): Promise>; - - /** - * Retrieves the specified number of items from the beginning of the IListDataAdapter object's data source. - * @param count The number of items to retrieve. - * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. - **/ - itemsFromStart(count: number): Promise>; - - /** - * Returns a string representation of the specified item that can be used for comparisons. - * @param item The item for which to generate a signature. - * @returns The signature representation of the specified item. - **/ - itemSignature(item: IItem): string; - - /** - * Moves the specified item to just after another item. - * @param key A key of the item to move. - * @param previousKey The key of another item. The item to move will be moved to just after this item. - * @param indexHint The index of the item to move, if known. - * @param previousIndexHint The index to move the item after, if known. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - moveAfter(key: string, previousKey: any, indexHint: string, previousIndexHint: number): Promise>; - - /** - * Moves the specified item to just before another item. - * @param key A key of the item to move. - * @param nextKey The key of another item. The item to move will be moved to just before this item. - * @param indexHint The index of the item to move, if known. - * @param nextIndexHint The index to move the item before, if known. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - moveBefore(key: string, nextKey: any, indexHint: string, nextIndexHint: number): Promise>; - - /** - * Moves the specified item to the end of the IListDataAdapter object's data source. - * @param key The key for the item to move. - * @param indexHint The index of the item to move, if known. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - moveToEnd(key: string, indexHint: number): Promise>; - - /** - * Moves the specified item to the beginning of the IListDataAdapter object's data source. - * @param key The key for the item to move. - * @param indexHint The index of the item to move, if known. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - moveToStart(key: string, indexHint: number): Promise>; - - /** - * Removes the specified item from the IListDataAdapter object's data source. - * @param key The key of the item to remove. - * @param data The new data for the item. - * @param indexHint The index of the item. - * @returns A Promise that returns null or undefined when the operation completes. - **/ - remove(key: string, data: T, indexHint: number): Promise; - - /** - * Registers a notification handler. The IListDataAdapter uses the handler to notify listening objects when its data changes. - * @param notificationHandler The notification handler that the IListDataAdapter will use to provide change notifications. . - **/ - setNotificationHandler(notificationHandler: IListDataNotificationHandler): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets a value that specifies whether to use an object's identity to determine if an item has changed. - **/ - compareByIdentity: boolean; - - //#endregion Properties - - } - - /** - * Notifies clients when an IListDataAdapter object's data changes. - **/ - interface IListDataNotificationHandler { - //#region Methods - - /** - * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. - **/ - beginNotifications(): void; - - /** - * Raises a notification that an item in the IListDataAdapter object's data source has changed. - * @param item The item that changed. - **/ - changed(item: IItem): void; - - /** - * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. - **/ - endNotifications(): void; - - /** - * Raises a notification that an item has been added to the IListDataAdapter object's data source. - * @param newItem The new item added to the IListDataAdapter object's data source. - * @param previousKey The key of the item that now precedes the new item, or null if the item was inserted at the start of the list. If nextKey is provided, this parameter may be null. - * @param nextKey The key of the item that now follows the new item, or null if the item was inserted at the end of the list. If previousKey is provided, this parameter may be null. - * @param index The index of the new item. - **/ - inserted(newItem: IItem, previousKey: string, nextKey: string, index?: number): void; - - /** - * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. - * @returns A Promise that completes when the data has been completely refreshed and all change notifications have been sent. - **/ - invalidateAll(): Promise; - - /** - * Raises a notification that an item was moved within the IListDataAdapter object's data source. - * @param item The item that was moved. - * @param previousKey The key of the item that now precedes the new item, or null if the item was moved to the beginning of the list. If nextKey is provided, this parameter may be null. - * @param nextKey The key of the item that now follows the new item, or null if the item was moved to the end of the list. If previousKey is provided, this parameter may be null. - * @param oldIndex The item's original index. - * @param newIndex The item's new index. - **/ - moved(item: IItem, previousKey: string, nextKey: string, oldIndex?: number, newIndex?: number): void; - - /** - * Reloads data from the IListDataAdapter. - **/ - reload(): void; - - /** - * Raises a notification that an item was removed from the IListDataAdapter object's data source. - * @param key The key of the item that was removed. - * @param index The index of the item that was removed. - **/ - removed(key: string, index?: number): void; - - //#endregion Methods - - } - - /** - * Provides access to a data source and enables you to bind, change, add, remove, and move items in that data source. - **/ - interface IListDataSource { - //#region Events - - /** - * Occurs when the status of the IListDataSource changes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. - **/ - statuschanged(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Notifies the IListDataSource that a sequence of edits is about to begin. The IListDataSource will defer notifications until endEdits is called. - **/ - beginEdits(): void; - - /** - * Overwrites the data of the specified item. - * @param key The key for the item to replace. - * @param newData The new data for the item. - * @returns A Promise that contains the IItem that was updated or an EditError if an error was encountered. - **/ - change(key: string, newData: T): Promise>; - - /** - * Creates an IListBinding that can retrieve items from the IListDataSource, enumerate the contents of the IListDataSource object's data, and optionally register for change notifications. - * @param notificationHandler Enables the IListBinding to register for change notifications for individual items obtained from the IListDataSource. If you omit this parameter, change notifications won't be available. - * @returns The new IListBinding. - **/ - createListBinding(notificationHandler?: IListNotificationHandler): IListBinding; - - /** - * Notifies the IListDataSource that the batch of edits that began with the last beginEdits call has completed. The IListDataSource will submit notifications for any changes that occurred between the beginEdits and endEdits calls as a batch and resume normal change notifications. - **/ - endEdits(): void; - - /** - * Retrieves the number of items in the data source. - * @returns A Promise that provides a Number that is the number of items in the data source. - **/ - getCount(): Promise; - - /** - * Inserts a new item after another item. - * @param key The key that can be used to retrieve the new item, if known. - * @param data The data for the item to add. - * @param previousKey The key for an item in the data source. The new item will be added after this item. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertAfter(key: string, data: T, previousKey: string): Promise>; - - /** - * Adds an item to the end of the data source. - * @param key The key that can be used to retrieve the new item, if known. - * @param data The data for the item to add. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertAtEnd(key: string, data: T): Promise>; - - /** - * Adds an item to the beginning of the data source. - * @param key The key that can be used to retrieve the new item, if known. - * @param data The data for the item to add. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertAtStart(key: string, data: T): Promise>; - - /** - * Inserts an item before another item. - * @param key The key that can be used to retrieve the new item, if known. - * @param data The data for the item to add. - * @param nextKey The key of an item in the data source. The new item will be inserted before this item. - * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. - **/ - insertBefore(key: string, data: T, nextKey: string): Promise>; - - /** - * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. - * @returns A Promise that completes when the data has been completely refreshed and all notifications have been sent. - **/ - invalidateAll(): Promise; - - /** - * Retrieves the item that has the specified description. - * @param description Domain-specific information, to be interpreted by the IListDataAdapter, that describes the item to retrieve. - * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. - **/ - itemFromDescription(description: any): Promise>; - - /** - * Retrieves the item at the specified index. - * @param index A value that is greater than or equal to zero that is the index of the item to retrieve. - * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. - **/ - itemFromIndex(index: number): Promise>; - - /** - * Retrieves the item with the specified key. - * @param key The key of the item to retrieve. It must be a non-empty string. - * @param description Domain-specific information that IListDataAdapter can use to improve the retrieval time. - * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item was not found, the promise completes with a null value. - **/ - itemFromKey(key: string, description?: any): Promise>; - - /** - * Moves an item to just after another item. - * @param key The key that identifies the item to move. - * @param previousKey The key of another item in the data source. The item specified by the key parameter will be moved after this item. - * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. - **/ - moveAfter(key: string, previousKey: string): Promise>; - - /** - * Moves an item before another item. - * @param key The key that identifies the item to move. - * @param nextKey The key of another item in the data source. The item specified by the key parameter will be moved before this item. - * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. - **/ - moveBefore(key: string, nextKey: string): Promise>; - - /** - * Moves an item to the end of the data source. - * @param key The key that identifies the item to move. - * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. - **/ - moveToEnd(key: string): Promise>; - - /** - * Moves the specified item to the beginning of the data source. - * @param key The key that identifies the item to move. - * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. - **/ - moveToStart(key: string): Promise>; - - /** - * Removes the specified item from the data source. - * @param key The key that identifies the item to remove. - * @returns A Promise that contains nothing if the operation was successful or an EditError if an error was encountered. - **/ - remove(key: string): Promise>; - - //#endregion Methods - - } - - /** - * Used by an IListBinding to provide change notifications when items in a IListDataSource change. - **/ - interface IListNotificationHandler { - //#region Methods - - /** - * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. - **/ - beginNotifications(): void; - - /** - * Indicates that an item changed. - * @param newItem The updated item. - * @param oldItem The original item. - **/ - changed(newItem: IItem, oldItem: IItem): void; - - /** - * Indicates that the number of items in the IListDataSource has changed. - * @param newCount The updated count. - * @param oldCount The original count. - **/ - countChanged(newCount: number, oldCount: number): void; - - /** - * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. - **/ - endNotifications(): void; - - /** - * Indicates that the index of an item changed. - * @param handle The temporary ID of the item. - * @param newIndex The new index. - * @param oldIndex The original index. - **/ - indexChanged(handle: string, newIndex: number, oldIndex: number): void; - - /** - * Indicates that an item was added to the IListDataSource. - * @param itemPromise A promise for the new IItem. - * @param previousHandle The temporary ID of the item that precedes the new item. - * @param nextHandle The temporary ID of the item that follows the new item. - **/ - inserted(itemPromise: IItemPromise, previousHandle: string, nextHandle: string): void; - - /** - * Indicates that an IItemPromise was fulfilled and that the item is now available. - * @param item The fulfilled item. - **/ - itemAvailable(item: IItem): void; - - /** - * Indicates that an item was moved. - * @param item A promise for the IItem that was moved. - * @param previousHandle The temporary ID of the item that now precedes the moved item. - * @param nextHandle The temporary ID of the item that now follows the moved item. - **/ - moved(item: IItemPromise, previousHandle: string, nextHandle: string): void; - - /** - * Indicates that an item was removed. - * @param handle The temporary ID of the item that was removed. - * @param mirage true if the item never actually existed; false if the item was actually present in the IListDataSource. - **/ - removed(handle: string, mirage: boolean): void; - - //#endregion Methods - - } + //#region Enumerations + + /** + * Specifies an icon that appears in an AppBarCommand object. + **/ + enum AppBarIcon { + previous, + next, + play, + pause, + edit, + save, + clear, + delete, + remove, + add, + cancel, + accept, + more, + redo, + undo, + home, + up, + forward, + right, + back, + left, + favorite, + camera, + settings, + video, + sync, + download, + mail, + find, + help, + upload, + emoji, + twopage, + leavechat, + mailforward, + clock, + send, + crop, + rotatecamera, + people, + closepane, + openpane, + world, + flag, + previewlink, + globe, + trim, + attachcamera, + zoomin, + bookmarks, + document, + protecteddocument, + page, + bullets, + comment, + mail2, + contactinfo, + hangup, + viewall, + mappin, + phone, + videochat, + switch, + contact, + rename, + pin, + musicinfo, + go, + keyboard, + dockleft, + dockright, + dockbottom, + remote, + refresh, + rotate, + shuffle, + list, + shop, + selectall, + orientation, + import, + importall, + browsephotos, + webcam, + pictures, + savelocal, + caption, + stop, + showresults, + volume, + repair, + message, + page2, + calendarday, + calendarweek, + calendar, + characters, + mailreplyall, + read, + link, + accounts, + showbcc, + hidebcc, + cut, + attach, + paste, + filter, + copy, + emoji2, + important, + mailreply, + slideshow, + sort, + manage, + allapps, + disconnectdrive, + mapdrive, + newwindow, + openwith, + contactpresence, + priority, + uploadskydrive, + gototoday, + font, + fontcolor, + contact2, + folder, + audio, + placeholder, + view, + setlockscreen, + settile, + cc, + stopslideshow, + permissions, + highlight, + disableupdates, + unfavorite, + unpin, + openlocal, + mute, + italic, + underline, + bold, + movetofolder, + likedislike, + dislike, + like, + alignright, + aligncenter, + alignleft, + zoom, + zoomout, + openfile, + otheruser, + admin, + street, + map, + clearselection, + fontdecrease, + fontincrease, + fontsize, + cellphone, + reshare, + tag, + repeatone, + repeatall, + outlinestar, + solidstar, + calculator, + directions, + target, + library, + phonebook, + memo, + microphone, + postupdate, + backtowindow, + fullscreen, + newfolder, + calendarreply, + unsyncfolder, + reporthacked, + syncfolder, + blockcontact, + switchapps, + addfriend, + touchpointer, + gotostart, + zerobars, + onebar, + twobars, + threebars, + fourbars, + scan, + preview + } + + /** + * Indicates whether the IListDataAdapter was able to provide a count. + **/ + enum CountResult { + /** + * Indicates no count is available. + **/ + unknown + } + + /** + * Indicates that the IListDataAdapter was unable to provide a count. + **/ + enum CountError { + /** + * An attempt to count items timed out. + **/ + noResponse + } + + /** + * Describes the status of an IListDataSource. + **/ + enum DataSourceStatus { + /** + * The IListDataSource is ready. + **/ + ready, + /** + * The IListDataSource is still loading. + **/ + waiting, + /** + * The IListDataSource failed to load. + **/ + failure + } + + /** + * Specifies the type of error that occurred during an edit operation on a IListDataSource or an IListDataAdapter. + **/ + enum EditError { + /** + * The edit operation timed out. + **/ + noResponse, + /** + * The data source cannot be written to. + **/ + notPermitted, + /** + * The item has changed. + **/ + noLongerMeaningful + } + + /** + * Specifies the type of error encountered when retrieving items from an IListDataAdapter. + **/ + enum FetchError { + /** + * The fetch operation timed out. + **/ + noResponse, + /** + * The specified item could not be located. + **/ + doesNotExist + } + + /** + * Specifies how group headers in a ListView respond to the tap interaction. + **/ + enum GroupHeaderTapBehavior { + /** + * The group is invoked. + **/ + invoke, + /** + * Nothing happens. + **/ + none + } + + /** + * Specifies the position of group headers relative to their items in a ListView. + **/ + enum HeaderPosition { + /** + * Group headers appear to the left of items. + **/ + left, + /** + * Group headers appear above items. + **/ + top + } + + /** + * Specifies that type of animation for which a contentanimating event was raised. + **/ + enum ListViewAnimationType { + /** + * The animation plays when the ListView is first displayed. + **/ + entrance, + /** + * The animation plays when the ListView is changing its content. + **/ + contentTransition + } + + /** + * Describes the type of object in a ListView. + **/ + enum ObjectType { + /** + * The object is a group header in the list. + **/ + groupHeader, + /** + * The object is an item in the list. + **/ + item + } + + /** + * Specifies the orientation of a control. + **/ + enum Orientation { + /** + * A horizontal layout. + **/ + horizontal, + /** + * A vertical layout. + **/ + vertical + } + + /** + * Specifies the selection mode of a ListView. + **/ + enum SelectionMode { + /** + * Items cannot be selected. + **/ + none, + /** + * A single item may be selected. + **/ + single, + /** + * Multiple items may be selected. Clicking additional items adds them to the selection. + **/ + multi + } + + /** + * Specifies whether elements are selected when the user performs a swipe interaction. + **/ + enum SwipeBehavior { + /** + * The swipe interaction selects the elements touched by the swipe. + **/ + select, + /** + * The swipe interaction does not change which elements are selected. + **/ + none + } + + /** + * Specifies how items in a ListView respond to the tap interaction. + **/ + enum TapBehavior { + /** + * The item is selected and invoked. + **/ + directSelect, + /** + * The item is selected if was not already selected, and its deselected if it was already selected. + **/ + toggleSelect, + /** + * The item is invoked but not selected. + **/ + invokeOnly, + /** + * Nothing happens. + **/ + none + } + + //#endregion Enumerations + + //#region Interfaces + + /** + * Contains items that were requested from an IListDataAdapter and provides some information about those items. + **/ + interface IFetchResult { + //#region Properties + + /** + * Gets or sets the index of the requested item in the IListDataAdapter object's data source. + **/ + absoluteIndex: number; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the last items at the end of the IListDataAdapter object's data source. + **/ + atEnd: boolean; + + /** + * Gets or sets a value that indicates whether this IFetchResult contains the first items at the beginning of the IListDataAdapter object's data source. + **/ + atStart: boolean; + + /** + * Gets or sets the items returned by the fetch operation. + **/ + items: T[]; + + /** + * Gets or sets the location of the requested item within the items array. + **/ + offset: number; + + /** + * Gets or sets the number of items in the IListDataAdapter object's underlying data source. + **/ + totalCount: number; + + //#endregion Properties + + } + + /** + * Represents an item in a list. + **/ + interface IItem { + //#region Properties + + /** + * Gets or sets the item's data. + **/ + data: T; + + /** + * Gets the group key for the item. This property is only available for items that belong to a grouped data source. + **/ + groupKey: string; + + /** + * Gets the temporary ID of the item. + **/ + handle: string; + + /** + * Gets the item's index in the IListDataSource. + **/ + index: number; + + /** + * Gets or sets the key the identifies the item. + **/ + key: string; + + //#endregion Properties + + } + + /** + * Provides a mechanism for retrieving IItem objects asynchronously. + **/ + interface IItemPromise { + //#region Events + + /** + * Occurs when there is an error in processing. + * @param eventInfo An object that contains information about the event. + **/ + onerror(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + **/ + cancel(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + **/ + done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; + + /** + * Stops change notification tracking for the IItem that fulfills this IItemPromise. + **/ + release(): void; + + /** + * Begins change notification tracking for the IItem that fulfills this IItemPromise. + **/ + retain(): void; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the complete or error function. + **/ + then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the temporary ID of the IItem that fulfills this promise. + **/ + handle: string; + + /** + * Gets or sets the index of the IItem contained by this IItemPromise. + **/ + index: number; + + //#endregion Properties + + } + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. Represents a layout for the ListView. + **/ + interface ILayout { + //#region Methods + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param beginScrollPosition The first visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the first visible item at the specified point. + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param endScrollPosition The last visible pixel in the ListView. For horizontal layouts, this is the x-coordinate of the pixel. For vertical layouts, this is the y-coordinate. + * @param wholeItem true if the item must be completely visible; otherwise, false if its ok for the item to be partially visible. Promise. + * @returns A Promise for the index of the last visible item at the specified point. + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @returns A object that has these properties: animationPromise, newEndIndex. + **/ + endLayout(): any; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The index of the item. + * @returns A Promise that returns an object with these properties: left, top, contentWidth, contentHeight, totalWidth, totalHeight. + **/ + getItemPosition(itemIndex: number): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The data source index of the current item. + * @param element The element for the current item. + * @param keyPressed The key that was pressed. This function must check for the arrow keys (leftArrow, upArrow, rightArrow, downArrow), pageDown, and pageUp and determine which item the user navigated to. + * @returns A Promise that contains the index of the next item (This item becomes the current item). + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: WinJS.Utilities.Key): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @returns A Promise that returns an object that has these properties: beginScrollPosition, endScrollPosition. + **/ + getScrollBarRange(): Promise; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param x The x-coordinate to test. + * @param y The y-coordinate to test. + **/ + hitTest(x: number, y: number): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param elements The elements that represent the items that were added. + **/ + itemsAdded(elements: HTMLElement[]): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + itemsMoved(): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param elements The elements that represent the items that were removed. + **/ + itemsRemoved(elements: HTMLElement[]): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param groupIndex The index of the group in the group data source. + * @param element The element to render for the group header. + **/ + layoutHeader(groupIndex: number, element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param itemIndex The index of the item in the data source. + * @param element The element to render for the item. + **/ + layoutItem(itemIndex: number, element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element The element that represents a header in the data source. + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element An element that represents an item in the data source. + **/ + prepareItem(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param element The element being released. + **/ + releaseItem(element: HTMLElement): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + reset(): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param site The layout site for the layout. You can use this object to query the hosting ListView for info you might need to lay out items. + **/ + setSite(site: ILayoutSite): void; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + * @param beginScrollPosition The starting pixel of the area to which the items are rendered. + * @param endScrollPosition The last pixel of the area to which the items are rendered. + * @param count The upper bound of the number of items to render. + * @returns A Promise that returns an object that has these properties: beginIndex, endIndex. + **/ + startLayout(beginScrollPosition: number, endScrollPosition: number, count: number): Promise; + + //#endregion Methods + + //#region Properties + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayout2 interface. + **/ + horizontal: boolean; + + //#endregion Properties + + } + + /** + * Represents a layout for the ListView. + **/ + interface ILayout2 { + //#region Methods + + /** + * Called when the ListView finishes a drag operation. + **/ + dragLeave(): void; + + /** + * Called when the ListView initiates a drag operation. + * @param x The x-coordinate of the drag. + * @param y The y-coordinate of the drag. + * @param dragInfo An object that indicates whether the item is selected. + **/ + dragOver(x: number, y: number, dragInfo: number): void; + + /** + * Called when the ListView requests that the ILayout2 execute animations. + **/ + executeAnimations(): void; + + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + + /** + * Gets the item at the specified hit-test coordinates. These coordinates are absolute coordinates (they are not relative to the layout's content area). + * @param x The x-coordinate to test for. + * @param y The y-coordinate to test for. + * @returns An object that describes the item at the hit test coordinates. It has these properties: type, index. + **/ + hitTest(x: number, y: number): any; + + /** + * Sets the rendering site and specifies whether the layout supports groups. This method is called by the ListView to initialize the layout. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * Retrieves the indexes of the items in the specified pixel range. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * Performs a layout pass. + * @param tree A structure representing the layout tree that is returned from the ListView. + * @param changedRange An object that lists the index of the first item in the changed item range. This object has these properties: startIndex. + * @param modifiedItems An object that contains the old and new indexes of the items that have been modified in the tree. + * @param modifiedGroups An object that contains the old and new indexes of the group elements that have been modified in the tree. + * @returns A Promise that executes after layout is complete, or an object that contains two Promise objects: realizedRangeComplete, layoutComplete. + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): any; + + /** + * Called when the ListView requests that the ILayout2 set up animations. + **/ + setupAnimations(): void; + + /** + * Releases resources that were obtained during the call to initialize. + **/ + uninitialize(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the orientation of the layout. + **/ + orientation: any; + + //#endregion Properties + + } + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use the ILayoutSite2 interface. Represents a rendering site for an ILayout. + **/ + interface ILayoutSite { + //#region Properties + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + animationsDisabled: boolean; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + itemSurface: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + rtl: boolean; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + scrollbarPos: number; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + surface: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + viewport: HTMLElement; + + /** + * This API is no longer supported. Starting with the Windows Library for JavaScript 2.0 Preview, use a the ILayoutSite2 interface. + **/ + viewportSize: any; + + //#endregion Properties + + } + + /** + * Represents a rendering site for an ILayout2. + **/ + interface ILayoutSite2 { + //#region Properties + + /** + * Gets the number of groups in the site. + **/ + groupCount: number; + + /** + * Gets the number of items in the site. + **/ + itemCount: Promise; + + /** + * Gets the pixel range of the realization area. + **/ + realizedRange: any; + + /** + * Gets the tree for use by an object that implements the ILayout2 interface. + **/ + tree: any; + + /** + * Gets the pixel range of visible items in the site. + **/ + visibleRange: any; + + //#endregion Properties + + } + + /** + * Retrieves items from a IListDataSource, enumerates the contents of a IListDataSource, and can optionally register for change notifications. + **/ + interface IListBinding { + //#region Methods + + /** + * Retrieves the current item. + * @returns An IItemPromise that contains the current item. If the cursor has moved past the start or end of the list, the promise completes with a value of null. If the current item has been moved or deleted, the promise returns an error. + **/ + current(): IItemPromise>; + + /** + * Gets the first item from the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. If the list is empty, the promise completes with a value of null. + **/ + first(): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified description and makes it the current item. + * @param description A domain-specific description, to be interpreted by the IListDataAdapter, that identifies the item to retrieve. + * @returns An IItemPromise that contains the requested IItem object. If the item wasn't found, the promise completes with a value of null. + **/ + fromDescription(description: string): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified index and makes it the current item. + * @param index A value greater than or equal to 0 that is the index of the item to retrieve. + * @returns An IItemPromise that contains the requested IItem. If the item wasn't found, the promise completes with a value of null. + **/ + fromIndex(index: number): IItemPromise>; + + /** + * Retrieves the item from the IListDataSource that has the specified key and makes it the current item. + * @param key The key that identifies the item to retrieve. This value must be a non-empty string. + * @param hints Domain-specific information that provides additional information to the IListDataAdapter to improve retrieval time. + * @returns An IItemPromise that contains the requested IItem. If they item couldn't be found, the promise completes with a value of null. + **/ + fromKey(key: string, hints?: any): IItemPromise>; + + /** + * Makes the specified IItem or IItemPromise the current item. + * @param item The IItem or IItemPromise that will become the current item. + * @returns An IItemPromise that contains the specified item, if it exists. If the specified item is not in the list, the promise completes with a value of null. + **/ + jumpToItem(item: IItem): IItemPromise>; + + /** + * Retrieves the last item in the IListDataSource and makes it the current item. + * @returns An IItemPromise that contains the requested IItem. f the list is empty, the promise completes with a value of null. + **/ + last(): IItemPromise>; + + /** + * Retrieves the item after the current item and makes it the current item. + * @returns An IItemPromise that contains the item after the current item. If the cursor moves past the end of the list, the promise completes with a value of null. + **/ + next(): IItemPromise>; + + /** + * Retrieves the item before the current item and makes it the current item. + * @returns An IItemPromise that contains the item before the current item. If the cursor moves past the start of the list, the promise completes with a value of null. + **/ + previous(): IItemPromise>; + + /** + * Releases resources, stops notifications, and cancels outstanding promises for all tracked items returned by this IListBinding. + **/ + release(): void; + + /** + * Creates a request to stop change notifications for the specified item. The change notifications stop when the number of releaseItem calls matches the number of IIItemPromise.retain calls. + * @param item The IItem or IItemPromise that should stop receiving notifications. + **/ + releaseItem(item: IItem): void; + + //#endregion Methods + + } + + /** + * Accesses data for an IListDataSource. + **/ + interface IListDataAdapter { + //#region Methods + + /** + * Overwrites the data of the specified item. + * @param key The key of the item to overwrite. + * @param newData The new data for the item. + * @param indexHint The index of the item, if known. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + change(key: string, newData: T, indexHint: number): Promise; + + /** + * Gets the number of items in the IListDataAdapter object's data source. + * @returns A Promise that contains the number of items the IListDataAdapter contains, or an approximate value if the actual number is unknown. + **/ + getCount(): Promise; + + /** + * Inserts the specified data after the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param previousKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted after this item. + * @param previousIndexHint The index of the item to insert the new data after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string, previousIndexHint: number): Promise>; + + /** + * Adds the specified key and data to the end of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds the specified key and data to the beginning of the IListDataAdapter object's data source. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts the specified data before the specified item. + * @param key A key that can be used to retrieve the new data. + * @param data The new data to add to the IListDataAdapter object's data source. + * @param nextKey The key of an item in the IListDataAdapter object's data source. The new data will be inserted before this item. + * @param nextIndexHint The index of the item to insert the new data before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string, nextIndexHint: number): Promise>; + + /** + * Retrieves the item that matches the specified description and also retrieves the specified number of items before and after the matched item. + * @param description A description of the item to locate. + * @param countBefore The number of items before the matched item to retrieve. + * @param countAfter The number of items after the matched item to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromDescription(description: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the end of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromEnd(count: number): Promise>; + + /** + * Retrieves the item at the specified index and also retrieves the specified number of items before and after the selected item. + * @param index The index of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromIndex(index: number, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the item that has the specified key and also retrieves the specified number of items before and after the selected item. + * @param key The key of the item to retrieve. + * @param countBefore The number of items to retrieve from before the selected item. + * @param countAfter The number of items to retrieve from after the selected item. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromKey(key: string, countBefore: number, countAfter: number): Promise>; + + /** + * Retrieves the specified number of items from the beginning of the IListDataAdapter object's data source. + * @param count The number of items to retrieve. + * @returns A Promise that provides an IFetchResult that contains the selected items or a FetchError if an error was encountered. + **/ + itemsFromStart(count: number): Promise>; + + /** + * Returns a string representation of the specified item that can be used for comparisons. + * @param item The item for which to generate a signature. + * @returns The signature representation of the specified item. + **/ + itemSignature(item: IItem): string; + + /** + * Moves the specified item to just after another item. + * @param key A key of the item to move. + * @param previousKey The key of another item. The item to move will be moved to just after this item. + * @param indexHint The index of the item to move, if known. + * @param previousIndexHint The index to move the item after, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: any, indexHint: string, previousIndexHint: number): Promise>; + + /** + * Moves the specified item to just before another item. + * @param key A key of the item to move. + * @param nextKey The key of another item. The item to move will be moved to just before this item. + * @param indexHint The index of the item to move, if known. + * @param nextIndexHint The index to move the item before, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: any, indexHint: string, nextIndexHint: number): Promise>; + + /** + * Moves the specified item to the end of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToEnd(key: string, indexHint: number): Promise>; + + /** + * Moves the specified item to the beginning of the IListDataAdapter object's data source. + * @param key The key for the item to move. + * @param indexHint The index of the item to move, if known. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + moveToStart(key: string, indexHint: number): Promise>; + + /** + * Removes the specified item from the IListDataAdapter object's data source. + * @param key The key of the item to remove. + * @param data The new data for the item. + * @param indexHint The index of the item. + * @returns A Promise that returns null or undefined when the operation completes. + **/ + remove(key: string, data: T, indexHint: number): Promise; + + /** + * Registers a notification handler. The IListDataAdapter uses the handler to notify listening objects when its data changes. + * @param notificationHandler The notification handler that the IListDataAdapter will use to provide change notifications. . + **/ + setNotificationHandler(notificationHandler: IListDataNotificationHandler): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether to use an object's identity to determine if an item has changed. + **/ + compareByIdentity: boolean; + + //#endregion Properties + + } + + /** + * Notifies clients when an IListDataAdapter object's data changes. + **/ + interface IListDataNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Raises a notification that an item in the IListDataAdapter object's data source has changed. + * @param item The item that changed. + **/ + changed(item: IItem): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Raises a notification that an item has been added to the IListDataAdapter object's data source. + * @param newItem The new item added to the IListDataAdapter object's data source. + * @param previousKey The key of the item that now precedes the new item, or null if the item was inserted at the start of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was inserted at the end of the list. If previousKey is provided, this parameter may be null. + * @param index The index of the new item. + **/ + inserted(newItem: IItem, previousKey: string, nextKey: string, index?: number): void; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all change notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Raises a notification that an item was moved within the IListDataAdapter object's data source. + * @param item The item that was moved. + * @param previousKey The key of the item that now precedes the new item, or null if the item was moved to the beginning of the list. If nextKey is provided, this parameter may be null. + * @param nextKey The key of the item that now follows the new item, or null if the item was moved to the end of the list. If previousKey is provided, this parameter may be null. + * @param oldIndex The item's original index. + * @param newIndex The item's new index. + **/ + moved(item: IItem, previousKey: string, nextKey: string, oldIndex?: number, newIndex?: number): void; + + /** + * Reloads data from the IListDataAdapter. + **/ + reload(): void; + + /** + * Raises a notification that an item was removed from the IListDataAdapter object's data source. + * @param key The key of the item that was removed. + * @param index The index of the item that was removed. + **/ + removed(key: string, index?: number): void; + + //#endregion Methods + + } + + /** + * Provides access to a data source and enables you to bind, change, add, remove, and move items in that data source. + **/ + interface IListDataSource { + //#region Events + + /** + * Occurs when the status of the IListDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Notifies the IListDataSource that a sequence of edits is about to begin. The IListDataSource will defer notifications until endEdits is called. + **/ + beginEdits(): void; + + /** + * Overwrites the data of the specified item. + * @param key The key for the item to replace. + * @param newData The new data for the item. + * @returns A Promise that contains the IItem that was updated or an EditError if an error was encountered. + **/ + change(key: string, newData: T): Promise>; + + /** + * Creates an IListBinding that can retrieve items from the IListDataSource, enumerate the contents of the IListDataSource object's data, and optionally register for change notifications. + * @param notificationHandler Enables the IListBinding to register for change notifications for individual items obtained from the IListDataSource. If you omit this parameter, change notifications won't be available. + * @returns The new IListBinding. + **/ + createListBinding(notificationHandler?: IListNotificationHandler): IListBinding; + + /** + * Notifies the IListDataSource that the batch of edits that began with the last beginEdits call has completed. The IListDataSource will submit notifications for any changes that occurred between the beginEdits and endEdits calls as a batch and resume normal change notifications. + **/ + endEdits(): void; + + /** + * Retrieves the number of items in the data source. + * @returns A Promise that provides a Number that is the number of items in the data source. + **/ + getCount(): Promise; + + /** + * Inserts a new item after another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param previousKey The key for an item in the data source. The new item will be added after this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAfter(key: string, data: T, previousKey: string): Promise>; + + /** + * Adds an item to the end of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtEnd(key: string, data: T): Promise>; + + /** + * Adds an item to the beginning of the data source. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertAtStart(key: string, data: T): Promise>; + + /** + * Inserts an item before another item. + * @param key The key that can be used to retrieve the new item, if known. + * @param data The data for the item to add. + * @param nextKey The key of an item in the data source. The new item will be inserted before this item. + * @returns A Promise that contains the IItem that was added or an EditError if an error was encountered. + **/ + insertBefore(key: string, data: T, nextKey: string): Promise>; + + /** + * Indicates that all previous data obtained from the IListDataAdapter is invalid and should be refreshed. + * @returns A Promise that completes when the data has been completely refreshed and all notifications have been sent. + **/ + invalidateAll(): Promise; + + /** + * Retrieves the item that has the specified description. + * @param description Domain-specific information, to be interpreted by the IListDataAdapter, that describes the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromDescription(description: any): Promise>; + + /** + * Retrieves the item at the specified index. + * @param index A value that is greater than or equal to zero that is the index of the item to retrieve. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item wasn't found, the promise completes with a value of null. + **/ + itemFromIndex(index: number): Promise>; + + /** + * Retrieves the item with the specified key. + * @param key The key of the item to retrieve. It must be a non-empty string. + * @param description Domain-specific information that IListDataAdapter can use to improve the retrieval time. + * @returns A Promise that provides an IItem that contains the requested item or a FetchError if an error was encountered. If the item was not found, the promise completes with a null value. + **/ + itemFromKey(key: string, description?: any): Promise>; + + /** + * Moves an item to just after another item. + * @param key The key that identifies the item to move. + * @param previousKey The key of another item in the data source. The item specified by the key parameter will be moved after this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveAfter(key: string, previousKey: string): Promise>; + + /** + * Moves an item before another item. + * @param key The key that identifies the item to move. + * @param nextKey The key of another item in the data source. The item specified by the key parameter will be moved before this item. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveBefore(key: string, nextKey: string): Promise>; + + /** + * Moves an item to the end of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToEnd(key: string): Promise>; + + /** + * Moves the specified item to the beginning of the data source. + * @param key The key that identifies the item to move. + * @returns A Promise that contains the IItem that was moved or an EditError if an error was encountered. + **/ + moveToStart(key: string): Promise>; + + /** + * Removes the specified item from the data source. + * @param key The key that identifies the item to remove. + * @returns A Promise that contains nothing if the operation was successful or an EditError if an error was encountered. + **/ + remove(key: string): Promise>; + + //#endregion Methods + + } + + /** + * Used by an IListBinding to provide change notifications when items in a IListDataSource change. + **/ + interface IListNotificationHandler { + //#region Methods + + /** + * Indicates the start of a notification batch. Objects that are listening for notifications should defer making updates until endNotifications is called. + **/ + beginNotifications(): void; + + /** + * Indicates that an item changed. + * @param newItem The updated item. + * @param oldItem The original item. + **/ + changed(newItem: IItem, oldItem: IItem): void; + + /** + * Indicates that the number of items in the IListDataSource has changed. + * @param newCount The updated count. + * @param oldCount The original count. + **/ + countChanged(newCount: number, oldCount: number): void; + + /** + * Indicates the end of a notification batch. When the beginNotifications method is called, objects listening for notifications should defer making updates until endNotifications is called. + **/ + endNotifications(): void; + + /** + * Indicates that the index of an item changed. + * @param handle The temporary ID of the item. + * @param newIndex The new index. + * @param oldIndex The original index. + **/ + indexChanged(handle: string, newIndex: number, oldIndex: number): void; + + /** + * Indicates that an item was added to the IListDataSource. + * @param itemPromise A promise for the new IItem. + * @param previousHandle The temporary ID of the item that precedes the new item. + * @param nextHandle The temporary ID of the item that follows the new item. + **/ + inserted(itemPromise: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an IItemPromise was fulfilled and that the item is now available. + * @param item The fulfilled item. + **/ + itemAvailable(item: IItem): void; + + /** + * Indicates that an item was moved. + * @param item A promise for the IItem that was moved. + * @param previousHandle The temporary ID of the item that now precedes the moved item. + * @param nextHandle The temporary ID of the item that now follows the moved item. + **/ + moved(item: IItemPromise, previousHandle: string, nextHandle: string): void; + + /** + * Indicates that an item was removed. + * @param handle The temporary ID of the item that was removed. + * @param mirage true if the item never actually existed; false if the item was actually present in the IListDataSource. + **/ + removed(handle: string, mirage: boolean): void; + + //#endregion Methods + + } /** * Used by ListView's currentItem API **/ interface IListViewItem { /** - * Gets or sets index of the ListView item. - **/ + * Gets or sets index of the ListView item. + **/ index?: number; /** - * Gets or sets key of the ListView item. - **/ + * Gets or sets key of the ListView item. + **/ key?: string; /** - * Gets or sets whether the ListView item is focused. - **/ + * Gets or sets whether the ListView item is focused. + **/ hasFocus?: boolean; /** - * Gets or sets whether the ListView item is focused and is showing its focus visual. - **/ + * Gets or sets whether the ListView item is focused and is showing its focus visual. + **/ showFocus?: boolean; } - /** - * Represents a selection of ListView items. - **/ - interface ISelection { - //#region Methods - - /** - * Adds one or more items to the selection. - * @param items The indexes or keys of the items to add. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. - * @returns A Promise that is fulfilled when the operation completes. - **/ - add(items: any): Promise; - - /** - * Clears the selection. - * @returns A Promise that is fulfilled when the clear operation completes. - **/ - clear(): Promise; - - /** - * Returns the number of items in the selection. - * @returns The number of items in the selection. - **/ - count(): number; - - /** - * Returns a list of the indexes for the items in the selection. - * @returns The list of indexes for the items in the selection as an array of Number objects. - **/ - getIndices(): number[]; - - /** - * Returns an array that contains the items in the selection. - * @returns A Promise that contains an array of the requested IItem objects. - **/ - getItems(): Promise[]>; - - /** - * Gets an array of the index ranges for the selected items. - * @returns An array that contains an ISelectionRange object for each index range in the selection. - **/ - getRanges(): ISelectionRange[]; - - /** - * Returns a value that indicates whether the selection contains every item in the data source. - * @returns true if the selection contains every item in the data source; otherwise, false. - **/ - isEverything(): boolean; - - /** - * Removes the specified items from the selection. - * @param items The indexes or keys of the items to remove. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. - * @returns A Promise that is fulfilled when the operation completes. - **/ - remove(items: any): Promise; - - /** - * Adds all the items in the ListView to the selection. - **/ - selectAll(): void; - - /** - * Clears the current selection and replaces it with the specified items. - * @param items The indexes or keys of the items that make up the selection. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. - * @returns A Promise that is fulfilled when the operation completes. - **/ - set(items: any): Promise; - - //#endregion Methods - - } - - /** - * Represents a range of indexes or keys in an ISelection. - **/ - interface ISelectionRange { - //#region Properties - - /** - * Gets or sets the index of the first item in the range. - **/ - firstIndex: number; - - /** - * Gets or sets the key of the first item in the range. - **/ - firstKey: any; - - /** - * Gets or sets the index of the last item in the range. - **/ - lastIndex: number; - - /** - * Gets or sets of the key of the last item in the range. - **/ - lastKey: any; - - //#endregion Properties - - } - - /** - * Supports semantic zoom functionality by exposing a control as either the zoomed in or the zoomed out view of the SemanticZoom control. - **/ - interface IZoomableView { - //#region Methods - - /** - * Initiates semantic zoom on the custom control. - **/ - beginZoom(): void; - - /** - * Initializes the semantic zoom state for the custom control. - * @param isZoomedOut True if this is the zoomed out view; otherwise false. - * @param isCurrentView True if this is the current view; otherwise false. - * @param triggerZoom The function that manages semantic zoom behavior. Triggers a zoom in or zoom out if the control is the visible control. - * @param prefetchedPages The number of pages of content to pre-fetch for zooming. This value is dependent on the size of the semantic zoom container. More content can be displayed based on the zoom factor and the size of the container. - **/ - configureForZoom(isZoomedOut: boolean, isCurrentView: boolean, triggerZoom: Function, prefetchedPages: number): void; - - /** - * Terminates semantic zoom on the zoomed in or zoomed out child of the custom control. - * @param isCurrentView True if the control is the visible control; otherwise false. - **/ - endZoom(isCurrentView: boolean): void; - - /** - * Retrieves the current item of the zoomed in or zoomed out child of the custom control. - * @returns An object that represents the selected item. This return value must be a Promise for the following: item, position. - **/ - getCurrentItem(): Promise<{ item: T; position: Utilities.IPosition }>; - - /** - * Retrieves the panning axis of the zoomed-in or zoomed-out child of the custom control. - * @returns Identifies the panning axis of the child control. Implementation specific. - **/ - getPanAxis(): string; - - /** - * Manages pointer input for the custom control. - * @param pointerId The ID of the pointer. - **/ - handlePointer(pointerId: string): void; - - /** - * Positions the specified item within the viewport of the child control when panning or zooming begins. - * @param item The object to position within the viewport of the child control. item can be a number, a string, or an object with any number of properties. - * @param position An object that contains the position data of the item relative to the child control. position must be an object with four number properties: left, top, width, and height. These values specify a rectangle that is typically the bounding box of the current item, though the details are up to the control. The units of the position must be in pixels. And the coordinates must be relative to the top-left of the control viewport (which should occupy the same area as the semantic zoom viewport), except when in RTL mode. In RTL mode, return coordinates relative to the top-right off the control viewport. The rectangle is transformed from the coordinate system of one control to that of the other. - **/ - positionItem(item: T, position: Utilities.IPosition): void; - - /** - * Selects the item closest to the specified screen coordinates. - * @param x The x-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport. - * @param y The y-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport.. - **/ - setCurrentItem(x: number, y: number): void; - - //#endregion Methods - - } - - //#endregion Interfaces - - //#region Objects - - /** - * Represents an application toolbar for displaying commands. - **/ - class AppBar { - //#region Constructors - - /** - * Creates a new AppBar object. - * @constructor - * @param element The DOM element that will host the control. - * @param options The set of properties and values to apply to the new AppBar. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs immediately after the AppBar is hidden. - * @param eventInfo An object that contains information about the event. - **/ - onafterhide(eventInfo: Event): void; - - /** - * Occurs after the AppBar is shown. - * @param eventInfo An object that contains information about the event. - **/ - onaftershow(eventInfo: Event): void; - - /** - * Occurs before the AppBar is hidden. - * @param eventInfo An object that contains information about the event. - **/ - onbeforehide(eventInfo: Event): void; - - /** - * Occurs before a hidden AppBar is shown. - * @param eventInfo An object that contains information about the event. - **/ - onbeforeshow(eventInfo: Event): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this AppBar. Call this method when the AppBar is no longer needed. After calling this method, the AppBar becomes unusable. - **/ - dispose(): void; - - /** - * Returns the AppBarCommand object identified by id. - * @param id The element idenitifier (ID) of the command to be returned. - * @returns The command identified by id. If multiple commands have the same ID, returns an array of all the commands matching the ID. - **/ - getCommandById(id: string): AppBarCommand; - - /** - * Hides the AppBar. - **/ - hide(): void; - - /** - * Hides the specified commands of the AppBar. - * @param commands The commands to hide. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. - **/ - hideCommands(commands: any[], immediate?: boolean): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Shows the AppBar if it is not disabled. - **/ - show(): void; - - /** - * Shows the specified commands of the AppBar. - * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. - **/ - showCommands(commands: any[], immediate?: boolean): void; - - /** - * Shows the specified commands of the AppBar while hiding all other commands. - * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. - **/ - showOnlyCommands(commands: any[], immediate?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Sets the AppBarCommand objects that appear in the app bar. - **/ - commands: AppBarCommand[]; - - /** - * Gets or sets a value that indicates whether the AppBar is disabled. - **/ - disabled: boolean; - - /** - * Gets the DOM element that hosts the AppBar. - **/ - element: HTMLElement; - - /** - * Gets a value that indicates whether the AppBar is hidden or in the process of becoming hidden. - **/ - hidden: boolean; - - /** - * Gets or sets the layout of the app bar contents. - **/ - layout: string; - - /** - * Gets or sets a value that specifies whether the AppBar appears at the top or bottom of the main view. - **/ - placement: string; - - /** - * Gets or sets a value that indicates whether the AppBar is sticky (won't light dismiss). If not sticky, the app bar dismisses normally when the user touches outside of the appbar. - **/ - sticky: boolean; - - //#endregion Properties - - } - - /** - * Represents a command to be displayed in an app bar. - **/ - class AppBarCommand { - //#region Constructors - - /** - * Creates a new AppBarCommand object. - * @constructor - * @param element The DOM element that will host the control. - * @param options The set of properties and values to apply to the new AppBarCommand. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param type The event type to register. - * @param listener The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Releases resources held by this AppBarCommand. Call this method when the AppBarCommand is no longer needed. After calling this method, the AppBarCommand becomes unusable. - **/ - dispose(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets a value that indicates whether the AppBarCommand is disabled. - **/ - disabled: boolean; - - /** - * Gets the DOM element that hosts the AppBarCommand. - **/ - element: HTMLElement; - - /** - * Adds an extra CSS class during construction. - **/ - extraClass: string; - - /** - * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing HOME or the arrow keys, from the previous AppBarCommand to this AppBarCommand. - **/ - firstElementFocus: HTMLElement; - - /** - * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the AppBarCommand's button is invoked. - **/ - flyout: Flyout; - - /** - * Gets or sets a value that indicates whether the AppBarCommand is hiding or in the process of becoming hidden. - **/ - hidden: boolean; - - /** - * Gets or sets the icon of the AppBarCommand. - **/ - icon: string; - - /** - * Gets the element identifier (ID) of the command. - **/ - id: string; - - /** - * Gets or sets the label of the command. - **/ - label: string; - - /** - * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing END or the arrow keys, from the previous AppBarCommand to this AppBarCommand. - **/ - lastElementFocus: HTMLElement; - - /** - * Gets or sets the function to be invoked when the command is clicked. - **/ - onclick: Function; - - /** - * Gets the section of the app bar that the command is in. - **/ - section: string; - - /** - * Gets or sets the selected state of a toggle button. - **/ - selected: boolean; - - /** - * Gets or sets the tooltip of the command. - **/ - tooltip: string; - - /** - * Gets the type of the command. - **/ - type: string; - - //#endregion Properties - - } - - /** - * Provides backwards navigation in the form of a button. - **/ - class BackButton { - //#region Constructors - - /** - * Creates a new BackButton. - * @constructor - * @param element The DOM element hosts the new BackButton. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this BackButton. Call this method when the BackButton is no longer needed. After calling this method, the BackButton becomes unusable. - **/ - dispose(): void; - - /** - * Checks the current navigation history and updates the value of the control's disabled attribute. - **/ - refresh(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets the HTML element that hosts this BackButton. - **/ - element: HTMLElement; - - //#endregion Properties - - } - - /** - * Represents a layout for the ListView in which items are arranged in a grid and items can span multiple grid cells. - **/ - class CellSpanningLayout { - //#region Constructors - - /** - * Creates a new CellSpanningLayout. - * @constructor - * @param options An object that contains one or more property/value pairs to apply to the new CellSpanningLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". - **/ - constructor(options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - dragLeave(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - dragOver(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - executeAnimations(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param currentItem An object that describes the current item. It has these properties: index, type. - * @param pressedKey The key that was pressed. - * @returns An object that describes the next item that should receive focus. It has these properties: index, type. - **/ - getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param x The x-coordinate, or the horizontal position on the screen. - * @param y The y-coordinate, or the vertical position on the screen. - **/ - hitTest(x: number, y: number): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param site The rendering site for the layout. - * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. - **/ - initialize(site: ILayoutSite2, groupsEnabled: boolean): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param firstPixel The first pixel the range of items falls between. - * @param lastPixel The last pixel the range of items falls between. - **/ - itemsFromRange(firstPixel: number, lastPixel: number): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param tree - * @param changedRange - * @param modifiedItems - * @param modifiedGroups - **/ - layout(tree: ILayoutSite2, changedRange: any, modifiedItems: any, modifiedGroups: any): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - setupAnimations(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - uninitialize(): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the position of group headers relative to their items. - **/ - groupHeaderPosition: WinJS.UI.HeaderPosition; - - /** - * Gets or sets a function that enables cell-spanning and establishes base cell dimensions. - **/ - groupInfo: Function; - - /** - * Gets or sets a function that returns the width and height of an item, as well as whether it should appear in a new column. Setting this function improves performance because the ListView can allocate space for an item without having to measure it first. - **/ - itemInfo: Function; - - /** - * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. - **/ - maximumRowsOrColumns: number; - - /** - * This API supports the Windows Library for JavaScript infrastructure and is not intended to be used directly from your code. - **/ - numberOfItemsPerItemsBlock: any; - - /** - * Gets the orientation of the CellSpanningLayout. For a CellSpanningLayout, this property always returns Orientation.horizontal. - **/ - orientation: WinJS.UI.Orientation; - - //#endregion Properties - - } - - /** - * Allows users to pick a date value. - **/ - class DatePicker { - //#region Constructors - - /** - * Initializes a new instance of the DatePicker control. - * @constructor - * @param element The DOM element associated with the DatePicker control. - * @param options The set of options to be applied initially to the DatePicker control. The options are the following: calendar, current, datePattern, disabled, maxYear, minYear, monthPattern, yearPattern. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs when any of the controls are changed by the user. - * @param eventInfo An object that contains information about the event. - **/ - onchange(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Adds an event listener. - * @param type The type (name) of the event. - * @param listener The function that handles the event. - * @param capture If true, specifies that capture should be initiated, otherwise false. - **/ - addEventListener(type: string, listener: Function, capture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this DatePicker. Call this method when the DatePicker is no longer needed. After calling this method, the DatePicker becomes unusable. - **/ - dispose(): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - raiseEvent(type: string, eventProperties: any): boolean; - - /** - * Removes a listener for the specified event. - * @param type The name of the event for which to remove a listener. - * @param listener The listener. - * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. - **/ - removeEventListener(type: string, listener: Function, useCapture?: any): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the calendar to use. - **/ - calendar: string; - - /** - * Gets or sets the current date of the DatePicker. You can use either a date string or a Date object to set this property. - **/ - current: Date; - - /** - * Gets or sets the display pattern for the date. The default date pattern is day.integer(2). You can change the date pattern by changing the number of integers displayed. - **/ - datePattern: string; - - /** - * Specifies whether the DatePicker is disabled. - **/ - disabled: boolean; - - /** - * Gets the DOM element for the DatePicker. - **/ - element: HTMLElement; - - /** - * Gets or sets the maximum Gregorian year available for picking. - **/ - maxYear: number; - - /** - * Gets or sets the minimum Gregorian year available for picking. - **/ - minYear: number; - - /** - * Gets or sets the display pattern for the month. The default month pattern is month.abbreviated. You can change the month pattern to the following values: month.full. The full name of the month. month.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. If you do specify the number of letters, the actual length of the month name that appears may vary. month.solo.full. A representation of the month that is suitable for stand-alone display. You can also use month.solo.abbreviated(n). month.integer(n). You can use integer with or without specifying the number of integers. - **/ - monthPattern: string; - - /** - * Gets or sets the display pattern for the year. The default year pattern is year.full. You can change the year pattern to the following values: year.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. - **/ - yearPattern: string; - - //#endregion Properties - - } - - /** - * Adds event-related methods to the control. - **/ - class DOMEventMixin { - //#region Methods - - /** - * Adds an event listener to the control. - * @param type The type (name) of the event. - * @param listener The listener to invoke when the event gets raised. - * @param useCapture true to initiate capture; otherwise, false. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type, adding the specified additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Removes an event listener from the control. - * @param type The type (name) of the event. - * @param listener The listener to remove. - * @param useCapture true to initiate capture; otherwise, false. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Adds the set of declaratively specified options (properties and events) to the specified control. If the name of the options property begins with "on", the property value is a function and the control supports addEventListener. This method calls the addEventListener method on the control. - * @param control The control on which the properties and events are to be applied. - * @param options The set of options that are specified declaratively. - **/ - setOptions(control: any, options: any): void; - - //#endregion Methods - - } - - /** - * Displays a collection, such as a set of photos, one item at a time. - **/ - class FlipView { - //#region Constructors - - /** - * Creates a new FlipView. - * @constructor - * @param element The DOM element that hosts the control. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the pageselected event, add a property named "onpageselected" and set its value to the event handler. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs when the datasource count changes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: source. - **/ - ondatasourcecountchanged(eventInfo: Event): void; - - /** - * Raised when the FlipView flips to a page and its renderer function completes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. - **/ - onpagecompleted(eventInfo: CustomEvent): void; - - /** - * Raised when the FlipView flips to a page. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. - **/ - onpageselected(eventInfo: CustomEvent): void; - - /** - * Occurs when an item becomes invisible or visible. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source, detail.visible. - **/ - onpagevisibilitychanged(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. For a list of events, see the FlipView object page. - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Returns the number of items in the FlipView control's itemDataSource. - * @returns A Promise that contains the number of items in the list or WinJS.UI.CountResult.unknown if the count is unavailable. - **/ - count(): Promise; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this FlipView. Call this method when the FlipView is no longer needed. After calling this method, the FlipView becomes unusable. - **/ - dispose(): void; - - /** - * Forces the FlipView to update its layout. Use this function when making the FlipView visible again after its style.display property had been set to "none". - **/ - forceLayout(): void; - - /** - * Navigates to the next page. - * @returns true if the FlipView begins navigating to the next page; false if the FlipView is already at the last item or is in the middle of another navigation animation. - **/ - next(): boolean; - - /** - * Navigates to the previous item. - * @returns true if the FlipView begins navigating to the previous page; nfalse if the FlipView is already at the first page or is in the middle of another navigation animation. - **/ - previous(): boolean; - - /** - * Unregisters an event handler for the specified event. - * @param eventName The name of the event. - * @param eventHandler The event handler function to remove. - * @param useCapture Set to true to unregister the event handler for the capturing phase; otherwise, set to false to unregister the event handler for the bubbling phase. - **/ - removeEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Sets custom animations for the FlipView to use when navigating between pages. - * @param animations An object that contains up to three fields, one for each navigation action: next, previous, and jump. Each of those fields must be a function with this signature: function (outgoingPage, incomingPage) Each function must return a WinJS.Promise that completes once the animations are finished. If a field is null or undefined, the FlipView reverts to its default animation for that action. - **/ - setCustomAnimations(animations: any): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the index of the currently displayed page. - **/ - currentPage: number; - - /** - * Gets the HTML element that hosts this FlipView. - **/ - element: HTMLElement; - - /** - * Gets or sets the data source that provides the FlipView with items to display. The FlipView displays one item at a time, on its own page. - **/ - itemDataSource: IListDataSource; - - /** - * Gets or sets the spacing between each item, in pixels. - **/ - itemSpacing: number; - - /** - * Gets or sets a Template or function that defines the HTML for each item's page. - **/ - itemTemplate: any; - - /** - * Gets or sets the orientation of the FlipView, horizontal or vertical. - **/ - orientation: string; - - //#endregion Properties - - } - - /** - * Displays lightweight UI that is either information, or requires user interaction. Unlike a dialog, a Flyout can be light dismissed by clicking or tapping off of it. - **/ - class Flyout { - //#region Constructors - - /** - * Creates a new Flyout object. - * @constructor - * @param element The DOM element that will host the control. - * @param options The set of properties and values to apply to the new Flyout. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised immediately after a flyout is fully hidden. - * @param eventInfo An object that contains information about the event. - **/ - onafterhide(eventInfo: Event): void; - - /** - * Raised immediately after a flyout is fully shown. - * @param eventInfo An object that contains information about the event. - **/ - onaftershow(eventInfo: Event): void; - - /** - * Raised just before hiding a flyout. - * @param eventInfo An object that contains information about the event. - **/ - onbeforehide(eventInfo: Event): void; - - /** - * Raised just before showing a flyout. - * @param eventInfo An object that contains information about the event. - **/ - onbeforeshow(eventInfo: Event): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. - **/ - dispose(): void; - - /** - * Hides the Flyout, if visible, regardless of other states. - **/ - hide(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Shows the Flyout, if hidden, regardless of other states. - * @param anchor Required. The DOM element to anchor the Flyout. - * @param placement The placement of the Flyout to the anchor: the string literal "top", "bottom", "left", or "right". - * @param alignment For "top" or "bottom" placement, the alignment of the Flyout to the anchor's edge: the string literal "center", "left", or "right". - **/ - show(anchor: HTMLElement, placement: string, alignment: string): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the default alignment to be used for this Flyout. - **/ - alignment: string; - - /** - * Gets or sets the default anchor to be used for this Flyout. - **/ - anchor: HTMLElement; - - /** - * Gets the DOM element that hosts the Flyout. - **/ - element: HTMLElement; - - /** - * Gets a value that indicates whether the Flyout is hidden or in the process of becoming hidden. - **/ - hidden: boolean; - - /** - * Gets or sets the default placement to be used for this Flyout. - **/ - placement: string; - - //#endregion Properties - - } - - /** - * Represents a grid layout for the ListView in which items are arranged in a horizontal grid. - **/ - class GridLayout { - //#region Constructors - - /** - * Creates a new GridLayout object. - * @constructor - * @param options The set of properties and values to apply to the new GridLayout. - **/ - constructor(options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * This method is no longer supported. - * @param beginScrollPosition - * @param wholeItem - **/ - calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; - - /** - * This method is no longer supported. - * @param endScrollPosition - * @param wholeItem - **/ - calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - dragLeave(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - dragOver(): void; - - /** - * This method is no longer supported. - **/ - endLayout(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - executeAnimations(): void; - - /** - * This method is no longer supported. - * @param itemIndex - **/ - getItemPosition(itemIndex: number): void; - - /** - * This method is no longer supported. - * @param itemIndex - * @param element - * @param keyPressed - **/ - getKeyboardNavigatedItem(itemIndex: number, element: any, keyPressed: any): void; - - /** - * This method is no longer supported. - * @param beginScrollPosition - * @param endScrollPosition - **/ - getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param x The x-coordinate, or the horizontal position on the screen. - * @param y The y-coordinate, or the vertical position on the screen. - **/ - hitTest(x: number, y: number): void; - - /** - * This method is no longer supported. - **/ - init(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param site The rendering site for the layout. - * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. - **/ - initialize(site: ILayoutSite2, groupsEnabled: boolean): void; - - /** - * This method is no longer supported. - * @param elements - **/ - itemsAdded(elements: any): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param firstPixel The first pixel the range of items falls between. - * @param lastPixel The last pixel the range of items falls between. - **/ - itemsFromRange(firstPixel: number, lastPixel: number): void; - - /** - * This method is no longer supported. - **/ - itemsMoved(): void; - - /** - * This method is no longer supported. - * @param elements - **/ - itemsRemoved(elements: any): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param tree - * @param changedRange - * @param modifiedItems - * @param modifiedGroups - **/ - layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; - - /** - * This method is no longer supported. - * @param groupIndex - * @param element A DOM element. - **/ - layoutHeader(groupIndex: number, element: any): void; - - /** - * This method is no longer supported. - * @param itemIndex - * @param element A DOM element. - **/ - layoutItem(itemIndex: number, element: any): void; - - /** - * This method is no longer supported. - * @param element - **/ - prepareHeader(element: HTMLElement): void; - - /** - * This method is no longer supported. - * @param itemIndex - * @param element A DOM element. - **/ - prepareItem(itemIndex: number, element: any): void; - - /** - * This method is no longer supported. - * @param item - * @param newItem - **/ - releaseItem(item: any, newItem: any): void; - - /** - * This method is no longer supported. - **/ - reset(): void; - - /** - * This method is no longer supported. - * @param layoutSite - **/ - setSite(layoutSite: any): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - setupAnimations(): void; - - /** - * This method is no longer supported. - * @param beginScrollPosition - * @param endScrollPositionScrollPosition - **/ - startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - uninitialize(): void; - - /** - * This method is no longer supported. - * @param count - **/ - updateBackdrop(count: number): void; - - //#endregion Methods - - //#region Properties - - /** - * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. - **/ - backdropColor: string; - - /** - * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. - **/ - disableBackdrop: boolean; - - /** - * Gets or sets the position of group headers. - **/ - groupHeaderPosition: WinJS.UI.HeaderPosition; - - /** - * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. - **/ - groupInfo: Function; - - /** - * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. - **/ - horizontal: boolean; - - /** - * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. - **/ - itemInfo: Function; - - /** - * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. - **/ - maximumRowsOrColumns: number; - - /** - * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the maximumRowsOrColumns property. - **/ - maxRows: number; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - numberOfItemsPerItemsBlock: any; - - /** - * Gets or sets the orientation of the GridLayout. - **/ - orientation: WinJS.UI.Orientation; - - //#endregion Properties - - } - - /** - * Creates a hub navigation pattern consisting of sections that can be navigated to. Each section is defined by a HubSection object. - **/ - class Hub { - //#region Constructors - - /** - * Creates a new Hub control. - * @constructor - * @param element The DOM element that will host the Hub control. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the contentanimating event, add a property named "oncontentanimating" to the options object and set its value to the event handler. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised when the Hub is about to play entrance, content transition, insert, or remove animations. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.index, detail.section. - **/ - oncontentanimating(eventInfo: CustomEvent): void; - - /** - * Raised when the user clicks on an interactive header. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.section. - **/ - onheaderinvoked(eventInfo: CustomEvent): void; - - /** - * Raised when the Hub control's loadingState changes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: loadingState. - **/ - onloadingstatechanged(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this Hub. Call this method when the Hub is no longer needed. After calling this method, the Hub becomes unusable. - **/ - dispose(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets the DOM element that hosts the Hub control. - **/ - element: HTMLElement; - - /** - * Gets or sets the Template or templating function that creates the DOM elements for each HubSection header. Your HubSection object should provide strings for HubSection.header property. - **/ - headerTemplate: any; - - /** - * Gets or sets the index of the first HubSection at least partially in view. This property is useful for animating the visible content in the Hub. - **/ - indexOfFirstVisible: number; - - /** - * Gets or sets the index of last HubSection at least partially in view. Used for animating the visible content in the Hub. - **/ - indexOfLastVisible: number; - - /** - * Gets a value that indicates whether the hub is still loading or whether loading is complete. The value changes to complete after all the sections and content inside them has loaded. - **/ - loadingState: string; - - /** - * Gets or sets the orientation of sections within the Hub. - **/ - orientation: Orientation; - - /** - * Gets or sets the distance between the start of the Hub and the current viewable area. - **/ - scrollPosition: number; - - /** - * Gets or sets the index of the first visible HubSection. - **/ - sectionOnScreen: number; - - /** - * Gets or sets the List that contains the HubSection objects that belong to this Hub. - **/ - sections: WinJS.Binding.List; - - /** - * This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. - **/ - zoomableView: IZoomableView; - - //#endregion Properties - - } - - /** - * Defines a section of a Hub. - **/ - class HubSection { - //#region Constructors - - /** - * Creates a new HubSection. - * @constructor - * @param element The DOM element hosts the new HubSection. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Releases resources held by this HubSection. Call this method when the HubSection is no longer needed. After calling this method, the HubSection becomes unusable. - **/ - dispose(): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets the DOM element that hosts the HubSection control's content. - **/ - contentElement: HTMLElement; - - /** - * Gets the DOM element that hosts this HubSection. - **/ - element: HTMLElement; - - /** - * Gets or sets the header for this HubSection. - **/ - header: string; - - /** - * Gets a value that specifies whether the header is static. - **/ - isHeaderStatic: boolean; - - //#endregion Properties - - } - - /** - * Enables you to include an HTML page dynamically. As part of the constructor, you must include an option indicating the URI of the page. - **/ - class HtmlControl { - //#region Constructors - - /** - * Initializes a new instance of HtmlControl to define a new page control. - * @constructor - * @param element The element that hosts the HtmlControl. - * @param options The options for configuring the page. The uri option is required in order to specify the source document for the content of the page. Other options are the ones used by the WinJS.Pages.render method. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - } - - /** - * Defines an item that can be pressed, swiped, and dragged. - **/ - class ItemContainer { - //#region Constructors - - /** - * Creates a new ItemContainer. - * @constructor - * @param element The DOM element hosts the new ItemContainer. For the ItemContainer to be accessible, this element must have its role attribute set to "list" or "listbox". If tapBehavior is set to none and selectionDisabled is true, then use the "list" role; otherwise, use the "listbox" role. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised when the item is invoked. (You can use the tapBehavior property to specify whether taps and clicks invoke the item.) - * @param eventInfo An object that contains information about the event. - **/ - oninvoked(eventInfo: CustomEvent): void; - - /** - * Raised after the item is selected or deselected. - * @param eventInfo An object that contains information about the event. - **/ - onselectionchanged(eventInfo: CustomEvent): void; - - /** - * Raised just before the current selection changes. - * @param eventInfo An object that contains information about the event. - **/ - onselectionchanging(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this ItemContainer. Call this method when the ItemContainer is no longer needed. After calling this method, the ItemContainer becomes unusable. - **/ - dispose(): void; - - /** - * Forces the ItemContainer to update its layout. Call this function when the reading direction of the app changes after the control has been initialized. - **/ - forceLayout(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets a value that specifies whether the item can be dragged. - **/ - draggable: boolean; - - /** - * Gets the element that hosts this ItemContainer. - **/ - element: HTMLElement; - - /** - * Gets or sets a value that specifies whether the item is selected. - **/ - selected: boolean; - - /** - * Gets or sets a value that specifies whether selection of this item is disabled. - **/ - selectionDisabled: boolean; - - /** - * Gets or sets how the ItemContainer reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. - **/ - swipeBehavior: WinJS.UI.SwipeBehavior; - - /** - * Gets or sets the orientation of swipe gestures. - **/ - swipeOrientation: Orientation; - - /** - * Gets or sets how the ItemContainer reacts when the user taps or clicks an item. - **/ - tapBehavior: TapBehavior; - - //#endregion Properties - - } - - /** - * This object supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - class Layout { - } - - /** - * Represents a layout for the ListView in which items are arranged in a vertical list. - **/ - class ListLayout { - //#region Constructors - - /** - * Creates a new ListLayout. - * @constructor - * @param options An object that contains one or more property/value pairs to apply to the new ListLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". - **/ - constructor(options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * This method is no longer supported. - * @param beginScrollPosition - * @param wholeItem - **/ - calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; - - /** - * This method is no longer supported. - * @param endScrollPosition - * @param wholeItem - **/ - calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - dragLeave(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - dragOver(): void; - - /** - * This method is no longer supported. - **/ - endLayout(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - executeAnimations(): void; - - /** - * This method is no longer supported. - * @param itemIndex - **/ - getItemPosition(itemIndex: number): void; - - /** - * This method is no longer supported. - * @param itemIndex - * @param element - * @param keyPressed - **/ - getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: any): void; - - /** - * This method is no longer supported. - * @param beginScrollPosition - * @param endScrollPosition - **/ - getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param x The x-coordinate, or the horizontal position on the screen. - * @param y The y-coordinate, or the vertical position on the screen. - **/ - hitTest(x: number, y: number): void; - - /** - * This method is no longer supported. - **/ - init(): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - initialize(): void; - - /** - * This method is no longer supported. - * @param elements - **/ - itemsAdded(elements: any): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param firstPixel - * @param lastPixel - **/ - itemsFromRange(firstPixel: number, lastPixel: number): void; - - /** - * This method is no longer supported. - **/ - itemsMoved(): void; - - /** - * This method is no longer supported. - * @param elements - **/ - itemsRemoved(elements: any): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - * @param tree - * @param changedRange - * @param modifiedItems - * @param modifiedGroups - **/ - layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; - - /** - * This method is no longer supported. - * @param groupIndex - * @param element A DOM element. - **/ - layoutHeader(groupIndex: number, element: any): void; - - /** - * This method is no longer supported. - * @param itemIndex - * @param element A DOM element. - **/ - layoutItem(itemIndex: number, element: any): void; - - /** - * This method is no longer supported. - * @param element - **/ - prepareHeader(element: HTMLElement): void; - - /** - * This method is no longer supported. - * @param itemIndex - * @param element A DOM element. - **/ - prepareItem(itemIndex: number, element: any): void; - - /** - * This method is no longer supported. - * @param item - * @param newItem - **/ - releaseItem(item: any, newItem: any): void; - - /** - * This method is no longer supported. - **/ - reset(): void; - - /** - * This method is no longer supported. - * @param layoutSite - **/ - setSite(layoutSite: any): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - setupAnimations(): void; - - /** - * This method is no longer supported. - * @param beginScrollPosition - * @param endScrollPositionScrollPosition - **/ - startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - uninitialize(): void; - - /** - * This method is no longer supported. - * @param count - **/ - updateBackdrop(count: number): void; - - //#endregion Methods - - //#region Properties - - /** - * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. - **/ - backdropColor: string; - - /** - * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. - **/ - disableBackdrop: boolean; - - /** - * Gets or sets the position of group headers. - **/ - groupHeaderPosition: WinJS.UI.HeaderPosition; - - /** - * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. - **/ - groupInfo: Function; - - /** - * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. - **/ - horizontal: boolean; - - /** - * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. - **/ - itemInfo: Function; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - numberOfItemsPerItemsBlock: any; - - /** - * Gets or sets the orientation of the GridLayout. - **/ - orientation: WinJS.UI.Orientation; - - //#endregion Properties - - } - - /** - * Displays data items in a customizable list or grid. - **/ + /** + * Represents a selection of ListView items. + **/ + interface ISelection { + //#region Methods + + /** + * Adds one or more items to the selection. + * @param items The indexes or keys of the items to add. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + add(items: any): Promise; + + /** + * Clears the selection. + * @returns A Promise that is fulfilled when the clear operation completes. + **/ + clear(): Promise; + + /** + * Returns the number of items in the selection. + * @returns The number of items in the selection. + **/ + count(): number; + + /** + * Returns a list of the indexes for the items in the selection. + * @returns The list of indexes for the items in the selection as an array of Number objects. + **/ + getIndices(): number[]; + + /** + * Returns an array that contains the items in the selection. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + getItems(): Promise[]>; + + /** + * Gets an array of the index ranges for the selected items. + * @returns An array that contains an ISelectionRange object for each index range in the selection. + **/ + getRanges(): ISelectionRange[]; + + /** + * Returns a value that indicates whether the selection contains every item in the data source. + * @returns true if the selection contains every item in the data source; otherwise, false. + **/ + isEverything(): boolean; + + /** + * Removes the specified items from the selection. + * @param items The indexes or keys of the items to remove. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + remove(items: any): Promise; + + /** + * Adds all the items in the ListView to the selection. + **/ + selectAll(): void; + + /** + * Clears the current selection and replaces it with the specified items. + * @param items The indexes or keys of the items that make up the selection. You can provide different types of objects for the items parameter: you can specify an index, a key, or a range of indexes. It can also be an array that contains one or more of these objects. For more info, see the Remarks section. + * @returns A Promise that is fulfilled when the operation completes. + **/ + set(items: any): Promise; + + //#endregion Methods + + } + + /** + * Represents a range of indexes or keys in an ISelection. + **/ + interface ISelectionRange { + //#region Properties + + /** + * Gets or sets the index of the first item in the range. + **/ + firstIndex: number; + + /** + * Gets or sets the key of the first item in the range. + **/ + firstKey: any; + + /** + * Gets or sets the index of the last item in the range. + **/ + lastIndex: number; + + /** + * Gets or sets of the key of the last item in the range. + **/ + lastKey: any; + + //#endregion Properties + + } + + /** + * Supports semantic zoom functionality by exposing a control as either the zoomed in or the zoomed out view of the SemanticZoom control. + **/ + interface IZoomableView { + //#region Methods + + /** + * Initiates semantic zoom on the custom control. + **/ + beginZoom(): void; + + /** + * Initializes the semantic zoom state for the custom control. + * @param isZoomedOut True if this is the zoomed out view; otherwise false. + * @param isCurrentView True if this is the current view; otherwise false. + * @param triggerZoom The function that manages semantic zoom behavior. Triggers a zoom in or zoom out if the control is the visible control. + * @param prefetchedPages The number of pages of content to pre-fetch for zooming. This value is dependent on the size of the semantic zoom container. More content can be displayed based on the zoom factor and the size of the container. + **/ + configureForZoom(isZoomedOut: boolean, isCurrentView: boolean, triggerZoom: Function, prefetchedPages: number): void; + + /** + * Terminates semantic zoom on the zoomed in or zoomed out child of the custom control. + * @param isCurrentView True if the control is the visible control; otherwise false. + **/ + endZoom(isCurrentView: boolean): void; + + /** + * Retrieves the current item of the zoomed in or zoomed out child of the custom control. + * @returns An object that represents the selected item. This return value must be a Promise for the following: item, position. + **/ + getCurrentItem(): Promise<{ item: T; position: Utilities.IPosition }>; + + /** + * Retrieves the panning axis of the zoomed-in or zoomed-out child of the custom control. + * @returns Identifies the panning axis of the child control. Implementation specific. + **/ + getPanAxis(): string; + + /** + * Manages pointer input for the custom control. + * @param pointerId The ID of the pointer. + **/ + handlePointer(pointerId: string): void; + + /** + * Positions the specified item within the viewport of the child control when panning or zooming begins. + * @param item The object to position within the viewport of the child control. item can be a number, a string, or an object with any number of properties. + * @param position An object that contains the position data of the item relative to the child control. position must be an object with four number properties: left, top, width, and height. These values specify a rectangle that is typically the bounding box of the current item, though the details are up to the control. The units of the position must be in pixels. And the coordinates must be relative to the top-left of the control viewport (which should occupy the same area as the semantic zoom viewport), except when in RTL mode. In RTL mode, return coordinates relative to the top-right off the control viewport. The rectangle is transformed from the coordinate system of one control to that of the other. + **/ + positionItem(item: T, position: Utilities.IPosition): void; + + /** + * Selects the item closest to the specified screen coordinates. + * @param x The x-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport. + * @param y The y-coordinate in DIPs relative to the upper-left corner of the SemanticZoom viewport.. + **/ + setCurrentItem(x: number, y: number): void; + + //#endregion Methods + + } + + //#endregion Interfaces + + //#region Objects + + /** + * Represents an application toolbar for displaying commands. + **/ + class AppBar { + //#region Constructors + + /** + * Creates a new AppBar object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBar. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the AppBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs after the AppBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the AppBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden AppBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this AppBar. Call this method when the AppBar is no longer needed. After calling this method, the AppBar becomes unusable. + **/ + dispose(): void; + + /** + * Returns the AppBarCommand object identified by id. + * @param id The element idenitifier (ID) of the command to be returned. + * @returns The command identified by id. If multiple commands have the same ID, returns an array of all the commands matching the ID. + **/ + getCommandById(id: string): AppBarCommand; + + /** + * Hides the AppBar. + **/ + hide(): void; + + /** + * Hides the specified commands of the AppBar. + * @param commands The commands to hide. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate?: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the AppBar if it is not disabled. + **/ + show(): void; + + /** + * Shows the specified commands of the AppBar. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate?: boolean): void; + + /** + * Shows the specified commands of the AppBar while hiding all other commands. + * @param commands The commands to show. The array elements may be AppBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Sets the AppBarCommand objects that appear in the app bar. + **/ + commands: AppBarCommand[]; + + /** + * Gets or sets a value that indicates whether the AppBar is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBar. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the AppBar is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the layout of the app bar contents. + **/ + layout: string; + + /** + * Gets or sets a value that specifies whether the AppBar appears at the top or bottom of the main view. + **/ + placement: string; + + /** + * Gets or sets a value that indicates whether the AppBar is sticky (won't light dismiss). If not sticky, the app bar dismisses normally when the user touches outside of the appbar. + **/ + sticky: boolean; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in an app bar. + **/ + class AppBarCommand { + //#region Constructors + + /** + * Creates a new AppBarCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new AppBarCommand. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this AppBarCommand. Call this method when the AppBarCommand is no longer needed. After calling this method, the AppBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the AppBarCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the AppBarCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing HOME or the arrow keys, from the previous AppBarCommand to this AppBarCommand. + **/ + firstElementFocus: HTMLElement; + + /** + * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the AppBarCommand's button is invoked. + **/ + flyout: Flyout; + + /** + * Gets or sets a value that indicates whether the AppBarCommand is hiding or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the icon of the AppBarCommand. + **/ + icon: string; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the HTMLElement with a 'content' type AppBarCommand that should receive focus whenever focus moves by the user pressing END or the arrow keys, from the previous AppBarCommand to this AppBarCommand. + **/ + lastElementFocus: HTMLElement; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets the section of the app bar that the command is in. + **/ + section: string; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets or sets the tooltip of the command. + **/ + tooltip: string; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Provides backwards navigation in the form of a button. + **/ + class BackButton { + //#region Constructors + + /** + * Creates a new BackButton. + * @constructor + * @param element The DOM element hosts the new BackButton. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this BackButton. Call this method when the BackButton is no longer needed. After calling this method, the BackButton becomes unusable. + **/ + dispose(): void; + + /** + * Checks the current navigation history and updates the value of the control's disabled attribute. + **/ + refresh(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the HTML element that hosts this BackButton. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + /** + * Represents a layout for the ListView in which items are arranged in a grid and items can span multiple grid cells. + **/ + class CellSpanningLayout { + //#region Constructors + + /** + * Creates a new CellSpanningLayout. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new CellSpanningLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: ILayoutSite2, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the position of group headers relative to their items. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * Gets or sets a function that enables cell-spanning and establishes base cell dimensions. + **/ + groupInfo: Function; + + /** + * Gets or sets a function that returns the width and height of an item, as well as whether it should appear in a new column. Setting this function improves performance because the ListView can allocate space for an item without having to measure it first. + **/ + itemInfo: Function; + + /** + * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. + **/ + maximumRowsOrColumns: number; + + /** + * This API supports the Windows Library for JavaScript infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets the orientation of the CellSpanningLayout. For a CellSpanningLayout, this property always returns Orientation.horizontal. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Allows users to pick a date value. + **/ + class DatePicker { + //#region Constructors + + /** + * Initializes a new instance of the DatePicker control. + * @constructor + * @param element The DOM element associated with the DatePicker control. + * @param options The set of options to be applied initially to the DatePicker control. The options are the following: calendar, current, datePattern, disabled, maxYear, minYear, monthPattern, yearPattern. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when any of the controls are changed by the user. + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener. + * @param type The type (name) of the event. + * @param listener The function that handles the event. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this DatePicker. Call this method when the DatePicker is no longer needed. After calling this method, the DatePicker becomes unusable. + **/ + dispose(): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes a listener for the specified event. + * @param type The name of the event for which to remove a listener. + * @param listener The listener. + * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. + **/ + removeEventListener(type: string, listener: Function, useCapture?: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the calendar to use. + **/ + calendar: string; + + /** + * Gets or sets the current date of the DatePicker. You can use either a date string or a Date object to set this property. + **/ + current: Date; + + /** + * Gets or sets the display pattern for the date. The default date pattern is day.integer(2). You can change the date pattern by changing the number of integers displayed. + **/ + datePattern: string; + + /** + * Specifies whether the DatePicker is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element for the DatePicker. + **/ + element: HTMLElement; + + /** + * Gets or sets the maximum Gregorian year available for picking. + **/ + maxYear: number; + + /** + * Gets or sets the minimum Gregorian year available for picking. + **/ + minYear: number; + + /** + * Gets or sets the display pattern for the month. The default month pattern is month.abbreviated. You can change the month pattern to the following values: month.full. The full name of the month. month.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. If you do specify the number of letters, the actual length of the month name that appears may vary. month.solo.full. A representation of the month that is suitable for stand-alone display. You can also use month.solo.abbreviated(n). month.integer(n). You can use integer with or without specifying the number of integers. + **/ + monthPattern: string; + + /** + * Gets or sets the display pattern for the year. The default year pattern is year.full. You can change the year pattern to the following values: year.abbreviated(n). You can use abbreviated with or without specifying the number of letters in the abbreviation. + **/ + yearPattern: string; + + //#endregion Properties + + } + + /** + * Adds event-related methods to the control. + **/ + class DOMEventMixin { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture true to initiate capture; otherwise, false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type, adding the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true to initiate capture; otherwise, false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If the name of the options property begins with "on", the property value is a function and the control supports addEventListener. This method calls the addEventListener method on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + setOptions(control: any, options: any): void; + + //#endregion Methods + + } + + /** + * Displays a collection, such as a set of photos, one item at a time. + **/ + class FlipView { + //#region Constructors + + /** + * Creates a new FlipView. + * @constructor + * @param element The DOM element that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the pageselected event, add a property named "onpageselected" and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the datasource count changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: source. + **/ + ondatasourcecountchanged(eventInfo: Event): void; + + /** + * Raised when the FlipView flips to a page and its renderer function completes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpagecompleted(eventInfo: CustomEvent): void; + + /** + * Raised when the FlipView flips to a page. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source. + **/ + onpageselected(eventInfo: CustomEvent): void; + + /** + * Occurs when an item becomes invisible or visible. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.source, detail.visible. + **/ + onpagevisibilitychanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. For a list of events, see the FlipView object page. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Returns the number of items in the FlipView control's itemDataSource. + * @returns A Promise that contains the number of items in the list or WinJS.UI.CountResult.unknown if the count is unavailable. + **/ + count(): Promise; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this FlipView. Call this method when the FlipView is no longer needed. After calling this method, the FlipView becomes unusable. + **/ + dispose(): void; + + /** + * Forces the FlipView to update its layout. Use this function when making the FlipView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Navigates to the next page. + * @returns true if the FlipView begins navigating to the next page; false if the FlipView is already at the last item or is in the middle of another navigation animation. + **/ + next(): boolean; + + /** + * Navigates to the previous item. + * @returns true if the FlipView begins navigating to the previous page; nfalse if the FlipView is already at the first page or is in the middle of another navigation animation. + **/ + previous(): boolean; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event. + * @param eventHandler The event handler function to remove. + * @param useCapture Set to true to unregister the event handler for the capturing phase; otherwise, set to false to unregister the event handler for the bubbling phase. + **/ + removeEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Sets custom animations for the FlipView to use when navigating between pages. + * @param animations An object that contains up to three fields, one for each navigation action: next, previous, and jump. Each of those fields must be a function with this signature: function (outgoingPage, incomingPage) Each function must return a WinJS.Promise that completes once the animations are finished. If a field is null or undefined, the FlipView reverts to its default animation for that action. + **/ + setCustomAnimations(animations: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the index of the currently displayed page. + **/ + currentPage: number; + + /** + * Gets the HTML element that hosts this FlipView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that provides the FlipView with items to display. The FlipView displays one item at a time, on its own page. + **/ + itemDataSource: IListDataSource; + + /** + * Gets or sets the spacing between each item, in pixels. + **/ + itemSpacing: number; + + /** + * Gets or sets a Template or function that defines the HTML for each item's page. + **/ + itemTemplate: any; + + /** + * Gets or sets the orientation of the FlipView, horizontal or vertical. + **/ + orientation: string; + + //#endregion Properties + + } + + /** + * Displays lightweight UI that is either information, or requires user interaction. Unlike a dialog, a Flyout can be light dismissed by clicking or tapping off of it. + **/ + class Flyout { + //#region Constructors + + /** + * Creates a new Flyout object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new Flyout. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised immediately after a flyout is fully hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised immediately after a flyout is fully shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before hiding a flyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Raised just before showing a flyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. + **/ + dispose(): void; + + /** + * Hides the Flyout, if visible, regardless of other states. + **/ + hide(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the Flyout, if hidden, regardless of other states. + * @param anchor Required. The DOM element to anchor the Flyout. + * @param placement The placement of the Flyout to the anchor: the string literal "top", "bottom", "left", or "right". + * @param alignment For "top" or "bottom" placement, the alignment of the Flyout to the anchor's edge: the string literal "center", "left", or "right". + **/ + show(anchor: HTMLElement, placement: string, alignment: string): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default alignment to be used for this Flyout. + **/ + alignment: string; + + /** + * Gets or sets the default anchor to be used for this Flyout. + **/ + anchor: HTMLElement; + + /** + * Gets the DOM element that hosts the Flyout. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the Flyout is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the default placement to be used for this Flyout. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Represents a grid layout for the ListView in which items are arranged in a horizontal grid. + **/ + class GridLayout { + //#region Constructors + + /** + * Creates a new GridLayout object. + * @constructor + * @param options The set of properties and values to apply to the new GridLayout. + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * This method is no longer supported. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This method is no longer supported. + **/ + endLayout(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This method is no longer supported. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: any, keyPressed: any): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This method is no longer supported. + **/ + init(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param site The rendering site for the layout. + * @param groupsEnabled Set to true if this layout supports groups; set to false if it does not. + **/ + initialize(site: ILayoutSite2, groupsEnabled: boolean): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel The first pixel the range of items falls between. + * @param lastPixel The last pixel the range of items falls between. + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This method is no longer supported. + **/ + itemsMoved(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This method is no longer supported. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * This method is no longer supported. + **/ + reset(): void; + + /** + * This method is no longer supported. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + /** + * This method is no longer supported. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + backdropColor: string; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + groupInfo: Function; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. + **/ + horizontal: boolean; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + itemInfo: Function; + + /** + * Gets or set the maximum number of rows or columns, depending on the orientation, to display before content begins to wrap. + **/ + maximumRowsOrColumns: number; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the maximumRowsOrColumns property. + **/ + maxRows: number; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets or sets the orientation of the GridLayout. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Creates a hub navigation pattern consisting of sections that can be navigated to. Each section is defined by a HubSection object. + **/ + class Hub { + //#region Constructors + + /** + * Creates a new Hub control. + * @constructor + * @param element The DOM element that will host the Hub control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the contentanimating event, add a property named "oncontentanimating" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the Hub is about to play entrance, content transition, insert, or remove animations. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.index, detail.section. + **/ + oncontentanimating(eventInfo: CustomEvent): void; + + /** + * Raised when the user clicks on an interactive header. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.section. + **/ + onheaderinvoked(eventInfo: CustomEvent): void; + + /** + * Raised when the Hub control's loadingState changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: loadingState. + **/ + onloadingstatechanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Hub. Call this method when the Hub is no longer needed. After calling this method, the Hub becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the Hub control. + **/ + element: HTMLElement; + + /** + * Gets or sets the Template or templating function that creates the DOM elements for each HubSection header. Your HubSection object should provide strings for HubSection.header property. + **/ + headerTemplate: any; + + /** + * Gets or sets the index of the first HubSection at least partially in view. This property is useful for animating the visible content in the Hub. + **/ + indexOfFirstVisible: number; + + /** + * Gets or sets the index of last HubSection at least partially in view. Used for animating the visible content in the Hub. + **/ + indexOfLastVisible: number; + + /** + * Gets a value that indicates whether the hub is still loading or whether loading is complete. The value changes to complete after all the sections and content inside them has loaded. + **/ + loadingState: string; + + /** + * Gets or sets the orientation of sections within the Hub. + **/ + orientation: Orientation; + + /** + * Gets or sets the distance between the start of the Hub and the current viewable area. + **/ + scrollPosition: number; + + /** + * Gets or sets the index of the first visible HubSection. + **/ + sectionOnScreen: number; + + /** + * Gets or sets the List that contains the HubSection objects that belong to this Hub. + **/ + sections: WinJS.Binding.List; + + /** + * This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. + **/ + zoomableView: IZoomableView; + + //#endregion Properties + + } + + /** + * Defines a section of a Hub. + **/ + class HubSection { + //#region Constructors + + /** + * Creates a new HubSection. + * @constructor + * @param element The DOM element hosts the new HubSection. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this HubSection. Call this method when the HubSection is no longer needed. After calling this method, the HubSection becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the HubSection control's content. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts this HubSection. + **/ + element: HTMLElement; + + /** + * Gets or sets the header for this HubSection. + **/ + header: string; + + /** + * Gets a value that specifies whether the header is static. + **/ + isHeaderStatic: boolean; + + //#endregion Properties + + } + + /** + * Enables you to include an HTML page dynamically. As part of the constructor, you must include an option indicating the URI of the page. + **/ + class HtmlControl { + //#region Constructors + + /** + * Initializes a new instance of HtmlControl to define a new page control. + * @constructor + * @param element The element that hosts the HtmlControl. + * @param options The options for configuring the page. The uri option is required in order to specify the source document for the content of the page. Other options are the ones used by the WinJS.Pages.render method. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + } + + /** + * Defines an item that can be pressed, swiped, and dragged. + **/ + class ItemContainer { + //#region Constructors + + /** + * Creates a new ItemContainer. + * @constructor + * @param element The DOM element hosts the new ItemContainer. For the ItemContainer to be accessible, this element must have its role attribute set to "list" or "listbox". If tapBehavior is set to none and selectionDisabled is true, then use the "list" role; otherwise, use the "listbox" role. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the item is invoked. (You can use the tapBehavior property to specify whether taps and clicks invoke the item.) + * @param eventInfo An object that contains information about the event. + **/ + oninvoked(eventInfo: CustomEvent): void; + + /** + * Raised after the item is selected or deselected. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanged(eventInfo: CustomEvent): void; + + /** + * Raised just before the current selection changes. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanging(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this ItemContainer. Call this method when the ItemContainer is no longer needed. After calling this method, the ItemContainer becomes unusable. + **/ + dispose(): void; + + /** + * Forces the ItemContainer to update its layout. Call this function when the reading direction of the app changes after the control has been initialized. + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the item can be dragged. + **/ + draggable: boolean; + + /** + * Gets the element that hosts this ItemContainer. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether the item is selected. + **/ + selected: boolean; + + /** + * Gets or sets a value that specifies whether selection of this item is disabled. + **/ + selectionDisabled: boolean; + + /** + * Gets or sets how the ItemContainer reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. + **/ + swipeBehavior: WinJS.UI.SwipeBehavior; + + /** + * Gets or sets the orientation of swipe gestures. + **/ + swipeOrientation: Orientation; + + /** + * Gets or sets how the ItemContainer reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + //#endregion Properties + + } + + /** + * This object supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + class Layout { + } + + /** + * Represents a layout for the ListView in which items are arranged in a vertical list. + **/ + class ListLayout { + //#region Constructors + + /** + * Creates a new ListLayout. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new ListLayout. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param wholeItem + **/ + calculateFirstVisible(beginScrollPosition: number, wholeItem: boolean): void; + + /** + * This method is no longer supported. + * @param endScrollPosition + * @param wholeItem + **/ + calculateLastVisible(endScrollPosition: number, wholeItem: boolean): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragLeave(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + dragOver(): void; + + /** + * This method is no longer supported. + **/ + endLayout(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + executeAnimations(): void; + + /** + * This method is no longer supported. + * @param itemIndex + **/ + getItemPosition(itemIndex: number): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element + * @param keyPressed + **/ + getKeyboardNavigatedItem(itemIndex: number, element: HTMLElement, keyPressed: any): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPosition + **/ + getScrollbarRange(beginScrollPosition: number, endScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param x The x-coordinate, or the horizontal position on the screen. + * @param y The y-coordinate, or the vertical position on the screen. + **/ + hitTest(x: number, y: number): void; + + /** + * This method is no longer supported. + **/ + init(): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + initialize(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsAdded(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param firstPixel + * @param lastPixel + **/ + itemsFromRange(firstPixel: number, lastPixel: number): void; + + /** + * This method is no longer supported. + **/ + itemsMoved(): void; + + /** + * This method is no longer supported. + * @param elements + **/ + itemsRemoved(elements: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + * @param tree + * @param changedRange + * @param modifiedItems + * @param modifiedGroups + **/ + layout(tree: any, changedRange: any, modifiedItems: any, modifiedGroups: any): void; + + /** + * This method is no longer supported. + * @param groupIndex + * @param element A DOM element. + **/ + layoutHeader(groupIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + layoutItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param element + **/ + prepareHeader(element: HTMLElement): void; + + /** + * This method is no longer supported. + * @param itemIndex + * @param element A DOM element. + **/ + prepareItem(itemIndex: number, element: any): void; + + /** + * This method is no longer supported. + * @param item + * @param newItem + **/ + releaseItem(item: any, newItem: any): void; + + /** + * This method is no longer supported. + **/ + reset(): void; + + /** + * This method is no longer supported. + * @param layoutSite + **/ + setSite(layoutSite: any): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + setupAnimations(): void; + + /** + * This method is no longer supported. + * @param beginScrollPosition + * @param endScrollPositionScrollPosition + **/ + startLayout(beginScrollPosition: number, endScrollPositionScrollPosition: number): void; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + uninitialize(): void; + + /** + * This method is no longer supported. + * @param count + **/ + updateBackdrop(count: number): void; + + //#endregion Methods + + //#region Properties + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + backdropColor: string; + + /** + * This property is no longer supported. Starting with Windows Library for JavaScript 2.0, use the .win-listview.win-container.win-backdrop CSS selector. + **/ + disableBackdrop: boolean; + + /** + * Gets or sets the position of group headers. + **/ + groupHeaderPosition: WinJS.UI.HeaderPosition; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + groupInfo: Function; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use the orientation property instead. + **/ + horizontal: boolean; + + /** + * This property is no longer supported. Starting with the Windows Library for JavaScript 2.0, use a CellSpanningLayout. + **/ + itemInfo: Function; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + numberOfItemsPerItemsBlock: any; + + /** + * Gets or sets the orientation of the GridLayout. + **/ + orientation: WinJS.UI.Orientation; + + //#endregion Properties + + } + + /** + * Displays data items in a customizable list or grid. + **/ class ListView { - //#region Constructors + //#region Constructors - /** - * Creates a new ListView. - * @constructor - * @param element The DOM element that hosts the ListView control. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the selectionchanged event, add a property named "onselectionchanged" to the options object and set its value to the event handler. - **/ - constructor(element?: HTMLElement, options?: any); + /** + * Creates a new ListView. + * @constructor + * @param element The DOM element that hosts the ListView control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the selectionchanged event, add a property named "onselectionchanged" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); - //#endregion Constructors + //#endregion Constructors - //#region Events + //#region Events - /** - * Occurs when the ListView is about to play an entrance or contentTransition animation. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.setPromise. - **/ - oncontentanimating(eventInfo: CustomEvent): void; + /** + * Occurs when the ListView is about to play an entrance or contentTransition animation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.type, detail.setPromise. + **/ + oncontentanimating(eventInfo: CustomEvent): void; - /** - * Raised when the user taps or clicks a group header. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.groupHeaderIndex, detail.groupHeaderPromise. - **/ - ongroupheaderinvoked(eventInfo: CustomEvent): void; + /** + * Raised when the user taps or clicks a group header. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.groupHeaderIndex, detail.groupHeaderPromise. + **/ + ongroupheaderinvoked(eventInfo: CustomEvent): void; - /** - * Raised when the ListView is a drop target and the onitemdragenter has been disabled. This is raised every time the cursor is moved between a new pair of items. If you call preventDefault on this event, then the ListView does not move the items slightly above/below the cursor to provide visual feedback for a drop. - * @param eventInfo An object that contains information about the event. The detail property of this object contains additional information about the event. - **/ - onitemdragbetween(eventInfo: CustomEvent): void; + /** + * Raised when the ListView is a drop target and the onitemdragenter has been disabled. This is raised every time the cursor is moved between a new pair of items. If you call preventDefault on this event, then the ListView does not move the items slightly above/below the cursor to provide visual feedback for a drop. + * @param eventInfo An object that contains information about the event. The detail property of this object contains additional information about the event. + **/ + onitemdragbetween(eventInfo: CustomEvent): void; - /** - * Raised when the user is dragging an item from the ListView and the datasource changes while the user is dragging. - * @param eventInfo An object that contains information about the event. The detail property of this object contains additional information about the event. - **/ - onitemdragchanged(eventInfo: CustomEvent): void; + /** + * Raised when the user is dragging an item from the ListView and the datasource changes while the user is dragging. + * @param eventInfo An object that contains information about the event. The detail property of this object contains additional information about the event. + **/ + onitemdragchanged(eventInfo: CustomEvent): void; - /** - * Raised when an item is dropped onto the ListView as the result of a drag operation. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer, detail.index, detail.insertAfterIndex. - **/ - onitemdragdrop(eventInfo: CustomEvent): void; + /** + * Raised when an item is dropped onto the ListView as the result of a drag operation. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer, detail.index, detail.insertAfterIndex. + **/ + onitemdragdrop(eventInfo: CustomEvent): void; - /** - * Raised when the user drops an item dragged from a ListView. - * @param eventInfo An object that contains information about the event. - **/ - onitemdragend(eventInfo: CustomEvent): void; + /** + * Raised when the user drops an item dragged from a ListView. + * @param eventInfo An object that contains information about the event. + **/ + onitemdragend(eventInfo: CustomEvent): void; - /** - * Raised when an dragged item enters the bounds of the ListView control. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer. - **/ - onitemdragenter(eventInfo: CustomEvent): void; + /** + * Raised when an dragged item enters the bounds of the ListView control. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer. + **/ + onitemdragenter(eventInfo: CustomEvent): void; - /** - * Raised when a draggable item leaves the bounds of a ListView control. - * @param eventInfo An object that contains information about the event. - **/ - onitemdragleave(eventInfo: CustomEvent): void; + /** + * Raised when a draggable item leaves the bounds of a ListView control. + * @param eventInfo An object that contains information about the event. + **/ + onitemdragleave(eventInfo: CustomEvent): void; - /** - * Raised when the user begins to drag an item from a ListView control. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer, detail.dragInfo. - **/ - onitemdragstart(eventInfo: CustomEvent): void; + /** + * Raised when the user begins to drag an item from a ListView control. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.dataTransfer, detail.dragInfo. + **/ + onitemdragstart(eventInfo: CustomEvent): void; - /** - * Occurs when the user taps or clicks an item. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.itemIndex. - **/ - oniteminvoked(eventInfo: CustomEvent): void; + /** + * Occurs when the user taps or clicks an item. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.itemIndex. + **/ + oniteminvoked(eventInfo: CustomEvent): void; - /** - * Raised when the focused item changes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.oldFocus, detail.oldNewFocus. - **/ - onkeyboardnavigating(eventInfo: CustomEvent): void; + /** + * Raised when the focused item changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.oldFocus, detail.oldNewFocus. + **/ + onkeyboardnavigating(eventInfo: CustomEvent): void; - /** - * Occurs when the ListView control's loadingState changes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.scrolling. - **/ - onloadingstatechanged(eventInfo: CustomEvent): void; + /** + * Occurs when the ListView control's loadingState changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.scrolling. + **/ + onloadingstatechanged(eventInfo: CustomEvent): void; - /** - * Occurs after the current selection changes. - * @param eventInfo An object that contains information about the event. The detail property of this object is null. To obtain the selected items, use the ListView.selection property. - **/ - onselectionchanged(eventInfo: CustomEvent): void; + /** + * Occurs after the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object is null. To obtain the selected items, use the ListView.selection property. + **/ + onselectionchanged(eventInfo: CustomEvent): void; - /** - * Occurs just before the current selection changes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.newSelection, detail.preventTapBehavior. - **/ - onselectionchanging(eventInfo: CustomEvent): void; + /** + * Occurs just before the current selection changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.newSelection, detail.preventTapBehavior. + **/ + onselectionchanging(eventInfo: CustomEvent): void; - //#endregion Events + //#endregion Events - //#region Methods + //#region Methods - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. See the ListView object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onselectionchange", you specify "selectionchange". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the ListView object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onselectionchange", you specify "selectionchange". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; - /** - * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. - **/ - dispose(): void; + /** + * Releases resources held by this object. Call this method when the object is no longer needed. After calling this method, the object becomes unusable. + **/ + dispose(): void; - /** - * Returns the DOM element that represents the item at the specified index. - * @param itemIndex The index of the item. - * @returns The DOM element that represents the item at the specified index. - **/ - elementFromIndex(itemIndex: number): HTMLElement; + /** + * Returns the DOM element that represents the item at the specified index. + * @param itemIndex The index of the item. + * @returns The DOM element that represents the item at the specified index. + **/ + elementFromIndex(itemIndex: number): HTMLElement; - /** - * Makes the item at the specified index visible. If necessary, the ListView will scroll to the item. - * @param itemIndex The index of the item to scroll into view. - **/ - ensureVisible(itemIndex: number): void; + /** + * Makes the item at the specified index visible. If necessary, the ListView will scroll to the item. + * @param itemIndex The index of the item to scroll into view. + **/ + ensureVisible(itemIndex: number): void; - /** - * Forces the ListView to update its layout. Use this function when making the ListView visible again after its style.display property had been set to "none". - **/ - forceLayout(): void; + /** + * Forces the ListView to update its layout. Use this function when making the ListView visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; - /** - * Returns the index of the item that the specified DOM element displays. - * @param element The DOM element that displays the item. - * @returns The index of the item displayed by element. - **/ - indexOfElement(element: HTMLElement): number; + /** + * Returns the index of the item that the specified DOM element displays. + * @param element The DOM element that displays the item. + * @returns The index of the item displayed by element. + **/ + indexOfElement(element: HTMLElement): number; - /** - * Loads the next set of pages if the ListView control's loadingBehavior is set to "incremental" (otherwise, it does nothing). The number of pages to be loaded is determined by the pagesToLoad property. - **/ - loadMorePages(): void; + /** + * Loads the next set of pages if the ListView control's loadingBehavior is set to "incremental" (otherwise, it does nothing). The number of pages to be loaded is determined by the pagesToLoad property. + **/ + loadMorePages(): void; - /** - * Repositions all the visible items in the ListView to adjust for items whose sizes have changed. Most apps won’t ever need to call this method. For more info, see the Remarks section. - **/ - recalculateItemPosition(): void; + /** + * Repositions all the visible items in the ListView to adjust for items whose sizes have changed. Most apps won’t ever need to call this method. For more info, see the Remarks section. + **/ + recalculateItemPosition(): void; - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; /** * Triggers the ListView disposal service manually. **/ static triggerDispose(): void; - //#endregion Methods + //#endregion Methods - //#region Properties + //#region Properties - /** - * Gets or sets a value that indicates whether the next set of pages is automatically loaded when the user scrolls beyond the number of pages specified by the pagesToLoadThreshold property. - **/ - automaticallyLoadPages: boolean; + /** + * Gets or sets a value that indicates whether the next set of pages is automatically loaded when the user scrolls beyond the number of pages specified by the pagesToLoadThreshold property. + **/ + automaticallyLoadPages: boolean; /** * Gets or sets an IListViewItem that indicates which item should have keyboard focus and the focus state of that item. **/ currentItem: IListViewItem; - /** - * Gets the HTML element that hosts this ListView. - **/ - element: HTMLElement; - - /** - * Gets or sets the data source that contains the groups for the items in the itemDataSource. - **/ - groupDataSource: IListDataSource; - - /** - * Gets or sets how the ListView reacts when the user taps or clicks a group header. - **/ - groupHeaderTapBehavior: GroupHeaderTapBehavior; - - /** - * Gets or sets the Template or function that creates the DOM elements for each group header in the groupDataSource. Each group header can contain multiple elements, but it must have a single root element. - **/ - groupHeaderTemplate: any; - - /** - * Gets or sets the first visible item. - **/ - indexOfFirstVisible: number; - - /** - * Gets the index of the last visible item in the ListView. - **/ - indexOfLastVisible: number; - - /** - * Gets or sets the data source that provides the ListView with items. - **/ - itemDataSource: IListDataSource; - - /** - * Go Gets or sets a value that specifies whether items can be dragged. When this is set to true the ListView provides built in behaviors related to item dragging. - **/ - itemsDraggable: boolean; - - /** - * Gets or sets whether the ListView control's items can be reordered within itself by dragging and dropping. - **/ - itemsReorderable: boolean; - - /** - * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the itemDataSource. Each item can contain multiple elements, but it must have a single root element. - **/ - itemTemplate: any; - - /** - * Gets or sets an object that controls the layout of the ListView. - **/ - layout: ILayout2; - - /** - * Gets or sets a value that specifies how the ListView fetches items and adds and removes them to the DOM. Don't change the value of this property after the ListView has begun loading data. - **/ - loadingBehavior: string; - - /** - * Gets a value that indicates whether the ListView is still loading or whether loading is complete. - **/ - loadingState: string; - - /** - * Gets or sets the maximum number of realized items. - **/ - maxDeferredItemCleanup: number; - - /** - * Gets or sets the number of pages to load when the loadingBehavior property is set to "incremental" and the user scrolls beyond the threshold specified by the pagesToLoadThreshold property. - **/ - pagesToLoad: number; - - /** - * Gets or sets the threshold (in pages) for initiating an incremental load. When the last visible item is within the specified number of pages from the end of the loaded portion of the list, and if automaticallyLoadPages is true and loadingBehavior is set to "incremental", the ListView initiates an incremental load. - **/ - pagesToLoadThreshold: number; - - /** - * Gets or sets the function that is called when the ListView discards or recycles the element representation of a group header. - **/ - resetGroupHeader: (header: any, element: HTMLElement) => void; - - /** - * Gets or sets the function that is called when an item is removed, an item is changed, or an item falls outside of the realized range of the ListView. - **/ - resetItem: (item: T, element: HTMLElement) => void; - - /** - * Gets or sets the distance, in pixels, of the start of the viewable area within the viewport. - **/ - scrollPosition: number; - - /** - * Gets an ISelection that contains the range of currently selected items. - **/ - selection: ISelection; - - /** - * Gets or sets the selection mode of the ListView. - **/ - selectionMode: SelectionMode; - - /** - * Gets or sets how the ListView reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. - **/ - swipeBehavior: WinJS.UI.SwipeBehavior; - - /** - * Gets or sets how the ListView reacts when the user taps or clicks an item. - **/ - tapBehavior: TapBehavior; - - /** - * Gets a ZoomableView that supports semantic zoom functionality. This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. - **/ - zoomableView: IZoomableView>; - - //#endregion Properties - - } - - /** - * Represents a menu flyout for displaying commands. - **/ - class Menu { - //#region Constructors - - /** - * Creates a new Menu object. - * @constructor - * @param element The DOM element that will host the control. - * @param options The set of properties and values to apply to the new Menu. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs immediately after the Menu is hidden. - * @param eventInfo An object that contains information about the event. - **/ - onafterhide(eventInfo: Event): void; - - /** - * Occurs after the Menu is shown. - * @param eventInfo An object that contains information about the event. - **/ - onaftershow(eventInfo: Event): void; - - /** - * Occurs before the Menu is hidden. - * @param eventInfo An object that contains information about the event. - **/ - onbeforehide(eventInfo: Event): void; - - /** - * Occurs before a hidden Menu is shown. - * @param eventInfo An object that contains information about the event. - **/ - onbeforeshow(eventInfo: Event): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Releases resources held by this Menu. Call this method when the Menu is no longer needed. After calling this method, the Menu becomes unusable. - **/ - dispose(): void; - - /** - * Returns the MenuCommand object identified by id. - * @param id The element identifier (ID) of the command to be returned. - * @returns The command identified by id. - **/ - getCommandById(id: string): MenuCommand; - - /** - * Hides the Menu. - **/ - hide(): void; - - /** - * Hides the specified commands of the Menu. - * @param commands The commands to hide. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. - **/ - hideCommands(commands: any[], immediate: boolean): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Shows the Menu, if hidden, regardless of other states. - * @param anchor Required. The DOM element to anchor the Menu. - * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. - * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. - **/ - show(anchor: HTMLElement, placement: string, alignment: string): void; - - /** - * Shows the specified commands of the Menu. - * @param commands The commands to show. The array elements may be Menu objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. - **/ - showCommands(commands: any[], immediate: boolean): void; - - /** - * Shows the specified commands of the Menu while hiding all other commands. - * @param commands The commands to show. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. - **/ - showOnlyCommands(commands: any[], immediate: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the default alignment to be used for this Menu. - **/ - alignment: string; - - /** - * Gets or sets the default anchor to be used for this Menu. - **/ - anchor: HTMLElement; - - /** - * Sets the MenuCommand objects that appear in the menu. - **/ - commands: MenuCommand[]; - - /** - * Gets the DOM element that hosts the Menu. - **/ - element: HTMLElement; - - /** - * Gets a value that indicates whether the Menu is hidden or in the process of becoming hidden. - **/ - hidden: boolean; - - /** - * Gets or sets the default placement to be used for this Menu. - **/ - placement: string; - - //#endregion Properties - - } - - /** - * Represents a command to be displayed in a Menu object. - **/ - class MenuCommand { - //#region Constructors - - /** - * Creates a new MenuCommand object. - * @constructor - * @param element The DOM element that will host the control. - * @param options The set of properties and values to apply to the new MenuCommand. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Disposes this control. - **/ - dispose(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets a value that indicates whether the MenuCommand is disabled. - **/ - disabled: boolean; - - /** - * Gets the DOM element that hosts the MenuCommand. - **/ - element: HTMLElement; - - /** - * Adds an extra CSS class during construction. - **/ - extraClass: string; - - /** - * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the MenuCommand's button is invoked. - **/ - flyout: Flyout; - - /** - * Gets a value that indicates whether the MenuCommand is hidden or in the process of becoming hidden. - **/ - hidden: boolean; - - /** - * Gets the element identifier (ID) of the command. - **/ - id: string; - - /** - * Gets or sets the label of the command. - **/ - label: string; - - /** - * Gets or sets the function to be invoked when the command is clicked. - **/ - onclick: Function; - - /** - * Gets or sets the selected state of a toggle button. - **/ - selected: boolean; - - /** - * Gets the type of the command. - **/ - type: string; - - //#endregion Properties - - } - - /** - * Displays navigation commands in a toolbar that the user can show or hide. - **/ - class NavBar { - //#region Constructors - - /** - * Creates a new NavBar. - * @constructor - * @param element The DOM element that will host the new NavBar. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs immediately after the NavBar is hidden. - * @param eventInfo An object that contains information about the event. - **/ - onafterhide(eventInfo: Event): void; - - /** - * Raised after the NavBar is shown. - * @param eventInfo An object that contains information about the event. - **/ - onaftershow(eventInfo: Event): void; - - /** - * Raised just before the NavBar is hidden. - * @param eventInfo An object that contains information about the event. - **/ - onbeforehide(eventInfo: Event): void; - - /** - * Occurs before a hidden NavBar is shown. - * @param eventInfo An object that contains information about the event. - **/ - onbeforeshow(eventInfo: Event): void; - - /** - * Occurs after the NavBar has finished processing its child elements. - * @param eventInfo An object that contains information about the event. - **/ - onchildrenprocessed(eventInfo: Event): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this NavBar. Call this method when the NavBar is no longer needed. After calling this method, the NavBar becomes unusable. - **/ - dispose(): void; - - /** - * Hides the NavBar. - **/ - hide(): void; - - /** - * Hides the specified commands of the NavBar. - * @param commands The commands to hide. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. - **/ - hideCommands(commands: any[], immediate: boolean): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - /** - * Shows the NavBar if it is not disabled. - **/ - show(): void; - - /** - * Shows the specified commands of the NavBar. - * @param commands The commands to show. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. - **/ - showCommands(commands: any[], immediate: boolean): void; - - /** - * Shows the specified commands of the NavBar while hiding all other commands. - * @param commands The commands to show. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. - * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. - **/ - showOnlyCommands(commands: any[], immediate: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - commands: AppBarCommand; - - /** - * Gets or sets a value that indicates whether the NavBar is disabled. - **/ - disabled: boolean; - - /** - * Gets the HTML element that hosts this NavBar. - **/ - element: HTMLElement; - - /** - * Gets a value that indicates whether the NavBar is hidden or in the process of becoming hidden. - **/ - hidden: boolean; - - /** - * This API supports the WinJS infrastructure and is not intended to be used directly from your code. - **/ - layout: string; - - /** - * Gets or sets a value that specifies whether the NavBar appears at the top or bottom of the main view. - **/ - placement: string; - - /** - * Gets or sets a value that indicates whether the NavBar is sticky (won't light dismiss). If not sticky, the NavBar dismisses normally when the user touches outside of the NavBar. - **/ - sticky: boolean; - - //#endregion Properties - - } - - /** - * Represents a navigation command in a NavBarContainer. - **/ - class NavBarCommand { - //#region Constructors - - /** - * Creates a new NavBarCommand. - * @constructor - * @param element The DOM element hosts the new NavBarCommand. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this NavBarCommand. Call this method when the NavBarCommand is no longer needed. After calling this method, the NavBarCommand becomes unusable. - **/ - dispose(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets the HTML element that hosts this NavBarCommand. - **/ - element: HTMLElement; - - /** - * Gets or sets the command's icon. - **/ - icon: string; - - /** - * Gets or sets the label of the command. - **/ - label: string; - - /** - * Get or sets the location to navigate to when this command is invoked. - **/ - location: any; - - /** - * Gets or sets a value that specifies whether to show the split tab stop. - **/ - splitButton: boolean; - - /** - * Gets a value that indicates whether the splitButton is open. - **/ - splitOpened: boolean; - - /** - * Gets or sets a user-defined object that represents the state associated with the command's location. - **/ - state: any; - - /** - * Gets or sets the tooltip of the command. - **/ - tooltip: any; - - //#endregion Properties - - } - - /** - * Contains a group of NavBarCommand objects in a NavBar. - **/ - class NavBarContainer { - //#region Constructors - - /** - * Creates a new NavBarContainer. - * @constructor - * @param element The DOM element hosts the new NavBarContainer. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs when a child NavBarCommand object's click event fires. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.navbarcommand, detail.data. - **/ - oninvoked(eventInfo: CustomEvent): void; - - /** - * Occurs when the split button of a child NavBarCommand is opened or closed. A split button is toggled when the user navigates to another page or opens another split button. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.opened, detail.index, detail.navbarcommand, detail.data. - **/ - onsplittoggle(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this NavBarCommand. Call this method when the NavBarCommand is no longer needed. After calling this method, the NavBarCommand becomes unusable. - **/ - dispose(): void; - - /** - * Forces the NavBarContainer to update its layout. Use this function when making the NavBarContainer visible again after you set its style.display property to "none". - **/ - forceLayout(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the index of the current item. - **/ - currentIndex: number; - - /** - * Gets or sets a WinJS.Binding.List that generates NavBarCommand objects. - **/ - data: WinJS.Binding.List; - - /** - * Gets the HTML element that hosts this NavBarContainer. - **/ - element: HTMLElement; - - /** - * Gets or sets a value that specifies whether NavBarCommand objects in this container use a fixed or dynamic width. - **/ - fixedSize: boolean; - - /** - * Gets or sets a value that specifies whether the NavBarContainer has a horizontal or vertical layout. - **/ - layout: Orientation; - - /** - * Gets or sets a value that specifies how many rows of navigation commands to display on a page. - **/ - maxRows: number; - - /** - * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the data source. Each item can contain multiple elements, but it must have a single root element. - **/ - template: WinJS.Binding.Template; - - //#endregion Properties - - } - - /** - * Lets the user rate something by clicking an icon that represents a rating. The Rating control can display three types of ratings: an average rating, a tentative rating, and the user's rating. - **/ - class Rating { - //#region Constructors - - /** - * Creates a new Rating. - * @constructor - * @param element The DOM element hosts the new Rating. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised when the user finishes interacting with the rating control without committing a tentative rating. - * @param eventInfo An object that contains information about the event. - **/ - oncancel(eventInfo: Event): void; - - /** - * Raised when the user commits a change to the userRating. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. - **/ - onchange(eventInfo: CustomEvent): void; - - /** - * Raised when the user is choosing a new tentative Rating. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. - **/ - onpreviewchange(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Releases resources held by this Rating. Call this method when the Rating is no longer needed. After calling this method, the Rating becomes unusable. - **/ - dispose(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the average rating. - **/ - averageRating: number; - - /** - * Gets or sets whether the control is disabled. When the control is disabled, the user can't specify a new user rating or modify an existing rating. - **/ - disabled: boolean; - - /** - * Gets the DOM element that hosts the Rating. - **/ - element: HTMLElement; - - /** - * Gets or sets whether control lets the user clear the rating. - **/ - enableClear: boolean; - - /** - * Gets or sets the maximum possible rating value. - **/ - maxRating: number; - - /** - * Gets or sets a set of descriptions to show for rating values in the tooltip. - **/ - tooltipStrings: string[]; - - /** - * Gets or sets the user's rating. - **/ - userRating: number; - - //#endregion Properties - - } - - /** - * Generates HTML from a set of data. Use this control to generate lists of items. - **/ - class Repeater { - //#region Constructors - - /** - * Creates a new Repeater control. - * @constructor - * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". - **/ - constructor(options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised after an item in the Repeater control's data source changes and after the corresponding DOM element has been updated. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. - **/ - onitemchanged(eventInfo: CustomEvent): void; - - /** - * Raised after an item in the Repeater control's data source changes but before the corresponding DOM element has been updated. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. - **/ - onitemchanging(eventInfo: CustomEvent): void; - - /** - * Raised after an item has been added to the Repeater control's data source and after the corresponding DOM element has been added. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. - **/ - oniteminserted(eventInfo: CustomEvent): void; - - /** - * Raised after an item has been added to the Repeater control's data source but before the corresponding DOM element has been added. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. - **/ - oniteminserting(eventInfo: CustomEvent): void; - - /** - * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. - **/ - onitemmoved(eventInfo: CustomEvent): void; - - /** - * Raised after an item has been moved from one index to another in the Repeater control's data source but before the corresponding DOM element has been moved. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. - **/ - onitemmoving(eventInfo: CustomEvent): void; - - /** - * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. - **/ - onitemremoved(eventInfo: CustomEvent): void; - - /** - * Raised after an item has been removed from the Repeater control's data source but before the corresponding DOM element has been removed. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. - **/ - onitemremoving(eventInfo: CustomEvent): void; - - /** - * Raised when the Repeater has finished loading a new set of data. This event is only fired on construction. This event is only raised when the Repeater is constructed or its data source or template changes. - * @param eventInfo An object that contains information about the event. - **/ - onitemsloaded(eventInfo: CustomEvent): void; - - /** - * Raised after the Repeater control's underlying data has been updated and after the updated HTML has been reloaded. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements. - **/ - onitemsreloaded(eventInfo: CustomEvent): void; - - /** - * Raised after the Repeater control's underlying data has been updated but before the updated HTML has been reloaded. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements, detail.setPromise. - **/ - onitemsreloading(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this Repeater. Call this method when the Repeater is no longer needed. After calling this method, the Repeater becomes unusable. - **/ - dispose(): void; - - /** - * Returns the HTML element for the item at the specified index. - * @param index The index of the item. - * @returns The DOM element for the specified item. - **/ - elementFromIndex(index: number): HTMLElement; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the List that provides the Repeater with items to display. - **/ - data: WinJS.Binding.List; - - /** - * Gets the DOM element that hosts the Repeater. - **/ - element: HTMLElement; - - /** - * Gets the number of items in the Repeater control. - **/ - length: number; - - /** - * Gets or sets a WinJS.Binding.Template or custom rendering function that defines the HTML of each item within the Repeater. - **/ - template: WinJS.Binding.Template; - - //#endregion Properties - - } - - /** - * Enables the user to perform search queries and select suggestions. - **/ - class SearchBox { - //#region Constructors - - /** - * Creates a new SearchBox. - * @constructor - * @param element The DOM element hosts the new SearchBox. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised when the user or the app changes the queryText. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.queryText, detail.linguisticDetails. - **/ - onquerychanged(eventInfo: CustomEvent): void; - - /** - * Raised awhen the user clicks the search glyph or presses Enter. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.queryText, detail.linguisticDetails, detail.keyModifiers. - **/ - onquerysubmitted(eventInfo: CustomEvent): void; - - /** - * Raised when the app automatically redirects focus to the search box. This event can only be raised when the focusOnKeyboardInput property is set to true. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.propertyName. - **/ - onreceivingfocusonkeyboardinput(eventInfo: CustomEvent): void; - - /** - * Raised when the user selects a suggested option for the search. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tag, detail.keyModifiers, detail.storageFile. - **/ - onresultsuggestionschosen(eventInfo: CustomEvent): void; - - /** - * Raised when the system requests search suggestions from this app. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.linguisticDetails, detail.queryText, detail.searchSuggestionCollection. - **/ - onsuggestionsrequested(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this SearchBox. Call this method when the SearchBox is no longer needed. After calling this method, the SearchBox becomes unusable. - **/ - dispose(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - /** - * Specifies whether suggestions based on local files are automatically displayed in the search pane, and defines the criteria that Windows uses to locate and filter these suggestions. - * @param settings The new settings for local content suggestions. - **/ - setLocalContentSuggestionSettings(settings: Windows.ApplicationModel.Search.LocalContentSuggestionSettings): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets whether the first suggestion is chosen when the user presses Enter. - **/ - chooseSuggestionOnEnter: boolean; - - /** - * Gets or sets a value that specifies whether the SearchBox is disabled. If the control is disabled, it won't receive focus. - **/ - disabled: boolean; - - /** - * Gets the DOM element that hosts the SearchBox. - **/ - element: HTMLElement; - - /** - * Gets or sets a value that specifies whether the search box automatically receives focus when the user types into the app window. - **/ - focusOnKeyboardInput: boolean; - - /** - * Gets or sets the placeholder text for the SearchBox. This text is displayed if there is no other text in the input box. - **/ - placeholderText: string; - - /** - * Gets or sets the query text for the SearchBox. - **/ - queryText: string; - - /** - * Gets or sets the search history context. This context is used a secondary key (the app ID is the primary key) for storing search history. - **/ - searchHistoryContext: string; - - /** - * Gets or sets a value that specifies whether search history is disabled. - **/ - searchHistoryDisabled: boolean; - - //#endregion Properties - - } - - /** - * Enables the user to zoom between two different views supplied by two child controls. One child control supplies the zoomed-out view and the other provides the zoomed-in view. - **/ - class SemanticZoom { - //#region Constructors - - /** - * Creates a new SemanticZoom. - * @constructor - * @param element The DOM element that hosts the SemanticZoom. - * @param options An object that contains one or more property/value pairs to apply to the new control. This object can contain these properties: initiallyZoomedOut Boolean, zoomFactor 0.2–0.85. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs when the control zooms in or out. - * @param eventInfo An object that contains information about the event. The detail property of this object is true when the control is zoomed out. Otherwise, it's false. - **/ - onzoomchanged(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this SemanticZoom. Call this method when the SemanticZoom is no longer needed. After calling this method, the SemanticZoom becomes unusable. - **/ - dispose(): void; - - /** - * Forces the SemanticZoom to update its layout. Use this function when making the SemanticZoom visible again after its style.display property had been set to "none". - **/ - forceLayout(): void; - - /** - * Unregisters an event handler for the specified event. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets the DOM element that hosts the SemanticZoom control. - **/ - element: HTMLElement; - - /** - * Gets or a sets a value that specifies whether to display the SemanticZoom zoom out button. - **/ - enableButton: boolean; - - /** - * Determines whether any controls contained in a SemanticZoom should be processed separately. This property is always true, meaning that the SemanticZoom takes care of processing its own controls. - **/ - isDeclarativeControlContainer: boolean; - - /** - * Gets or sets a value that indicates whether SemanticZoom is locked and zooming between views is disabled. - **/ - locked: boolean; - - /** - * Gets or sets a value that indicates whether the control is zoomed out. - **/ - zoomedOut: boolean; - - /** - * Gets or sets a value that specifies how much the scaling the cross-fade animation performs when the SemanticZoom transitions between views. - **/ - zoomFactor: number; - - //#endregion Properties - - } - - /** - * Provides users with fast, in-context access to settings that affect the current Windows Store app. - **/ - class SettingsFlyout { - //#region Constructors - - /** - * Creates a new SettingsFlyout object. - * @constructor - * @param element The DOM element that will host the control. - * @param options The set of properties and values to apply to the new SettingsFlyout. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised immediately after the SettingsFlyout is completely hidden. - * @param eventInfo An object that contains information about the event. - **/ - onafterhide(eventInfo: Event): void; - - /** - * Raised immediately after a SettingsFlyout is fully shown. - * @param eventInfo An object that contains information about the event. - **/ - onaftershow(eventInfo: Event): void; - - /** - * Raised just before hiding a SettingsFlyout. - * @param eventInfo An object that contains information about the event. - **/ - onbeforehide(eventInfo: Event): void; - - /** - * Raised just before showing a SettingsFlyout. - * @param eventInfo An object that contains information about the event. - **/ - onbeforeshow(eventInfo: Event): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this SettingsFlyout. Call this method when the SettingsFlyout is no longer needed. After calling this method, the SettingsFlyout becomes unusable. - **/ - dispose(): void; - - /** - * Hides the SettingsFlyout, if visible, regardless of other states. - **/ - hide(): void; - - /** - * Loads a fragment of the SettingsFlyout. Your app calls this when the user invokes a settings command and the WinJS.Application.onsettings event occurs. - * @param e An object that contains information about the event, received from the WinJS.Application.onsettings event. The detail property of this object contains the applicationcommands sub-property that you set to an array of settings commands. You then populate the SettingsFlyout with these commands by a call to populateSettings. - **/ - static populateSettings(e: CustomEvent): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. - * @param listener The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Shows the SettingsPane UI, if hidden. - **/ - show(): void; - - /** - * Shows the SettingsPane UI, if hidden, regardless of other state. - **/ - static show(): void; - - /** - * Show the Settings flyout using the Settings element identifier (ID) and the path of the page that contains the Settings element. - * @param id The ID of the Settings element. - * @param path The path of the page that contains the Settings element. - **/ - static showSettings(id: string, path: any): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets the DOM element the SettingsFlyout is attached to. - **/ - element: HTMLElement; - - /** - * Gets whether the SettingsFlyout is hidden. - **/ - hidden: boolean; - - /** - * Gets or sets the settings command Id for the SettingsFlyout control. - **/ - settingsCommandId: string; - - /** - * This property may be unavailable or altered in future versions. Use the CSS width property of the element that has the win-settingsflyout class instead. - **/ - width: string; - - //#endregion Properties - - } - - /** - * A type of IListDataSource that provides read-access to an object that implements the IStorageQueryResultBase interface. A StorageDataSource enables you to query and bind to items in the data source. - **/ - class StorageDataSource { - //#region Constructors - - /** - * Creates a new StorageDataSource object. - * @constructor - * @param query The IStorageQueryResultBase that the StorageDataSource obtains its items from. Instead of IStorageQueryResultBase, you can also pass one of these string values: Music, Pictures, Videos, Documents. - * @param options The set of properties and values to apply to the new StorageDataSource. Properties on this object may include: mode , requestedThumbnailSize , thumbnailOptions , synchronous . - **/ - constructor(query: Windows.Storage.Search.IStorageQueryResultBase, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Draws the thumbnail for the specified item to the specified img element. - * @param item The item to retrieve the thumbnail for. - * @param image The img element that will display the thumbnail. - * @returns A Promise that completes when the full-quality thumbnail is visible. - **/ - loadThumbnail(item: IItem, image: HTMLImageElement): Promise; - - //#endregion Methods - - } - - /** - * Prevents a DOM sub-tree from receiving tab navigations and focus. - **/ - class TabContainer { - //#region Constructors - - /** - * Creates a new TabContainer. - * @constructor - * @param element The DOM element that hosts the TabContainer control. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties. - **/ - constructor(element: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Releases resources held by this TabContainer. Call this method when the TabContainer is no longer needed. After calling this method, the TabContainer becomes unusable. - **/ - dispose(): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the child DOM element that receives tab focus. - **/ - childFocus: HTMLElement; - - /** - * Gets or sets the tab index of this container. - **/ - tabIndex: number; - - //#endregion Properties - - } - - /** - * Allows users to select time values. - **/ - class TimePicker { - //#region Constructors - - /** - * Initializes a new instance of a TimePicker control. - * @constructor - * @param element The DOM element associated with the TimePicker control. - * @param options The set of options to be applied initially to the TimePicker control. The options are the following: clock. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs when any of the controls are changed by the user. - * @param eventInfo An object that contains information about the event. - **/ - onchange(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Adds an event listener. - * @param type The type (name) of the event. - * @param listener The function that handles the event. - * @param capture If true, specifies that capture should be initiated, otherwise false. - **/ - addEventListener(type: string, listener: Function, capture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this TimePicker. Call this method when the TimePicker is no longer needed. After calling this method, the TimePicker becomes unusable. - **/ - dispose(): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - raiseEvent(type: string, eventProperties: any): boolean; - - /** - * Removes a listener for the specified event. - * @param type The name of the event for which to remove a listener. - * @param listener The listener. - * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. - **/ - removeEventListener(type: string, listener: Function, useCapture?: any): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the type of clock to display (12HourClock or 24HourClock). It defaults to the user setting. - **/ - clock: string; - - /** - * Gets or sets the current time of the TimePicker. Note that the date value is always July 15, 2011. - **/ - current: Date; - - /** - * Specifies whether the TimePicker is disabled. - **/ - disabled: boolean; - - /** - * Gets the DOM element for the TimePicker. - **/ - element: HTMLElement; - - /** - * Gets or sets the display pattern for the hour. The default hour pattern is hour.integer(2). You can change the hour pattern by changing the number of integers displayed. - **/ - hourPattern: string; - - /** - * Gets or sets the minute increment. For example, 15 specifies that the TimePicker minute control should display only the choices 00, 15, 30, 45. - **/ - minuteIncrement: number; - - /** - * Gets or sets the display pattern for the minute. The default minute pattern is minute.integer(2). You can change the minute pattern by changing the number of integers displayed. - **/ - minutePattern: string; - - /** - * Gets or sets the display pattern for the period. The default period pattern is period.abbreviated(2). You can change the period pattern by changing the number of integers displayed. - **/ - periodPattern: string; - - //#endregion Properties - - } - - /** - * A control that lets the user switch an option between two states: on (checked is set to true) and off (checked is set to false). - **/ - class ToggleSwitch { - //#region Constructors - - /** - * Creates a new ToggleSwitch. - * @constructor - * @param element The DOM that hosts the control. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the change event, add a property named "onchange" to the options object and set its value to the event handler. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs when the ToggleSwitch control is flipped to on (checked == true) or off (checked == false). - * @param eventInfo An object that contains information about the event. - **/ - onchange(eventInfo: Event): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Releases resources held by this ToggleSwitch. Call this method when the ToggleSwitch is no longer needed. After calling this method, the ToggleSwitch becomes unusable. - **/ - dispose(): void; - - /** - * Handles the specified event. - * @param event The event. - **/ - handleEvent(event: any): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - raiseEvent(type: string, eventProperties: any): boolean; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets a value that specifies whether the control is on or off. - **/ - checked: boolean; - - /** - * Gets or sets a value that specifies whether the control is disabled. - **/ - disabled: boolean; - - /** - * Gets the DOM element that hosts the ToggleSwitch. - **/ - element: HTMLElement; - - /** - * Gets or sets the text that displays when the ToggleSwitch is off (checked is set to false). - **/ - labelOff: string; - - /** - * Gets or sets the text that displays when the ToggleSwitch is on (checked is set to true). - **/ - labelOn: string; - - /** - * Gets or sets the main text for the ToggleSwitch control. This text is always displayed, regardless of whether the control is switched on or off. - **/ - title: string; - - //#endregion Properties - - } - - /** - * Displays a tooltip that can contain images and formatting. - **/ - class Tooltip { - //#region Constructors - - /** - * Creates a new Tooltip. - * @constructor - * @param element The DOM element associated that hosts the Tooltip. - * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the opened event, add a property named "onopened" to the options object and set its value to the event handler. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Raised just before the Tooltip is hidden. - * @param eventInfo An object that contains information about the event. - **/ - onbeforeclose(eventInfo: CustomEvent): void; - - /** - * Raised just before the Tooltip appears. - * @param eventInfo An object that contains information about the event. - **/ - onbeforeopen(eventInfo: CustomEvent): void; - - /** - * Raised when the Tooltip is no longer displayed. - * @param eventInfo An object that contains information about the event. - **/ - onclosed(eventInfo: CustomEvent): void; - - /** - * Raised when the Tooltip is shown. - * @param eventInfo An object that contains information about the event. - **/ - onopened(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Adds an event handler for the specified event. - * @param eventName The name of the event to handle. - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Hides the Tooltip. - **/ - close(): void; - - /** - * Releases resources held by this Tooltip. Call this method when the Tooltip is no longer needed. After calling this method, the Tooltip becomes unusable. - **/ - dispose(): void; - - /** - * Shows the Tooltip. - * @param type A value that specifies when to show the Tooltip. The default value is "mousedown". - **/ - open(type?: string): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets or sets the HTML element that is the content of the Tooltip. - **/ - contentElement: HTMLElement; - - /** - * Gets the DOM element that hosts the Tooltip control. - **/ - element: HTMLElement; - - /** - * Gets or appends additional CSS classes to apply to the element that hosts the Tooltip. - **/ - extraClass: string; - - /** - * Gets or sets a value that specifies whether the Tooltip is an infotip, a tooltip that contains a lot of info and should be displayed for longer than a typical Tooltip. - **/ - infotip: boolean; - - /** - * Gets or sets the HTML content of the Tooltip. - **/ - innerHTML: string; - - /** - * Gets or sets the position for the Tooltip relative to its target element: top, bottom, left or right. - **/ - placement: string; - - //#endregion Properties - - } - - /** - * Scales a single child element to fill the available space without resizing it. This control reacts to changes in the size of the container as well as changes in size of the child element. For example, a media query may result in a change in aspect ratio. - **/ - class ViewBox { - //#region Constructors - - /** - * Initializes a new instance of the ViewBox control. - * @constructor - * @param element The DOM element that functions as the scaling box. This element fills 100% of the width and height allotted to it. - * @param options The set of options to be applied initially to the ViewBox control. There are currently no options on this control, and any options included in this parameter are ignored. - **/ - constructor(element?: HTMLElement, options?: any); - - //#endregion Constructors - - //#region Methods - - /** - * Adds an event handler for the specified event. - * @param eventName The name of the event to handle. - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Releases resources held by this ViewBox. Call this method when the ViewBox is no longer needed. After calling this method, the ViewBox becomes unusable. - **/ - dispose(): void; - - /** - * Forces the ViewBox to update its layout. Use this function when making the ViewBox visible again after its style.display property had been set to "none". - **/ - forceLayout(): void; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - //#region Properties - - /** - * Gets the DOM element that functions as the scaling box. - **/ - element: HTMLElement; - - //#endregion Properties - - } - - /** - * Serves as the base class for a custom IListDataSource. - **/ - class VirtualizedDataSource { - //#region Constructors - - /** - * Initializes the VirtualizedDataSource base class of a custom data source. - * @constructor - * @param listDataAdapter The object that supplies data to the VirtualizedDataSource. - * @param options An object that can contain properties that specify additional options for the VirtualizedDataSource. It supports these properties: cacheSize. - **/ - constructor(listDataAdapter: IListDataAdapter, options?: any); - - //#endregion Constructors - - //#region Events - - /** - * Occurs when the status of the VirtualizedDataSource changes. - * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. - **/ - statuschanged(eventInfo: CustomEvent): void; - - //#endregion Events - - //#region Methods - - /** - * Registers an event handler for the specified event. - * @param eventName The name of the event to handle. See the VirtualizedDataSource object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onstatuschanged", you specify "statuschanged". - * @param eventHandler The event handler function to associate with the event. - * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. - **/ - addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event, otherwise false. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Removes an event handler that the addEventListener method registered. - * @param eventName The name of the event that the event handler is registered for. See the VirtualizedDataSource object page for a list of events. - * @param eventCallback The event handler function to remove. - * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. - **/ - removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; - - //#endregion Methods - - } - - //#endregion Objects - - //#region Functions - - /** - * Returns a new IListDataSource that adds group information to the items of another IListDataSource. - * @param listDataSource The data source for the individual items to group. - * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. - * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. - * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. - * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. - **/ - function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; - - /** - * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. - **/ - function disableAnimations(): void; - - /** - * Used to enable all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be enabled, as the determination is made based on several factors. - **/ - function enableAnimations(): void; - - /** - * Marks a event handler function as being compatible with declarative processing. - * @param handler The handler to be marked as compatible with declarative processing. - * @returns The handler, marked as compatible with declarative processing. - **/ - function eventHandler(handler: any): any; - - /** - * Asynchronously executes a collection of CSS animations on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. - * @param element Element or elements to be animated. This parameter can be expressed in several ways: As the special value "undefined", which means that the animation has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. - * @param animation The animation description or an array of animation descriptions to apply to element. An animation description is a JavaScript object with specific properties, listed below. There are two types of animation descriptions: one for keyframe-based animations and one for explicit animations. These types are distinguished by whether the keyframe property has a defined value. The following properties are required for both types of animation descriptions: property (string), delay (number), duration (number), timing (string). If an animation has a keyframe property with a defined, non-null value, then the animation is a keyframe-based animation. A keyframe-based animation description requires the following property in addition to those mentioned above: keyframe (string). If an animation does not have a keyframe property, or if the value of the property is null or undefined, then the animation is an explicit animation. An explicit animation description requires the following properties in addition to the common properties mentioned above: from, to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). - * @returns Returns a Promise object that completes when the CSS animation is complete. - **/ - function executeAnimation(element: HTMLElement, animation: any): Promise; - - /** - * Asynchronously executes a collection of CSS transitions on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. - * @param element Element or elements on which to perform the transition. This parameter can be expressed in several ways: As the special value "undefined", which means that the transition has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. - * @param transition The transition description or an array of transition descriptions to apply to element. A transition description is a JavaScript object with these properties: property (string), delay (number), duration (number), timing (string), from (optional), to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). - * @returns Returns a Promise that completes when the transition is finished. - **/ - function executeTransition(element: HTMLElement, transition: any): Promise; - - /** - * Retrieves the items in the specified index range. - * @param dataSource The data source that contains the items to retrieve. - * @param ranges An array of ISelectionRange objects that have firstIndex and lastIndex values. - * @returns A Promise that contains an array of the requested IItem objects. - **/ - function getItemsFromRanges(dataSource: IListDataSource, ranges: ISelectionRange[]): Promise>; - - /** - * Determines whether the Animations Library and ListView animations will be performed if called. - * @returns Returns true if animations will be performed; otherwise false. - **/ - function isAnimationEnabled(): boolean; - - /** - * Applies declarative control binding to all elements, starting at the specified root element. - * @param rootElement The element at which to start applying the binding. If this parameter is not specified, the binding is applied to the entire document. - * @param skipRoot If true, the elements to be bound skip the specified root element and include only the children. - * @returns A promise that is fulfilled when binding has been applied to all the controls. - **/ - function processAll(rootElement?: Element, skipRoot?: boolean): Promise; - - /** - * Applies declarative control binding to the specified element. - * @param element The element to bind. - * @returns A promise that is fulfilled after the control is activated. The value of the promise is the control that is attached to element. - **/ - function process(element: Element): Promise; - - /** - * Walks the DOM tree from the given element to the root of the document. Whenever a selector scope is encountered, this method performs a lookup within that scope for the specified selector string. The first matching element is returned. - * @param selector The selector string. - * @param element The element to begin walking to the root of the document from. - * @returns The target element, if found. - **/ - function scopedSelect(selector: string, element: HTMLElement): HTMLElement; - - /** - * Given a DOM element and a control, attaches the control to the element. - * @param element Element to associate with the control. - * @param control The control to attach to the element. - **/ - function setControl(element: HTMLElement, control: any): void; - - /** - * Adds the set of declaratively specified options (properties and events) to the specified control. If name of the options property begins with "on", the property value is a function and the control supports addEventListener. setControl calls addEventListener on the control. - * @param control The control on which the properties and events are to be applied. - * @param options The set of options that are specified declaratively. - **/ - function setOptions(control: any, options?: any): void; - - //#endregion Functions + /** + * Gets the HTML element that hosts this ListView. + **/ + element: HTMLElement; + + /** + * Gets or sets the data source that contains the groups for the items in the itemDataSource. + **/ + groupDataSource: IListDataSource; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks a group header. + **/ + groupHeaderTapBehavior: GroupHeaderTapBehavior; + + /** + * Gets or sets the Template or function that creates the DOM elements for each group header in the groupDataSource. Each group header can contain multiple elements, but it must have a single root element. + **/ + groupHeaderTemplate: any; + + /** + * Gets or sets the first visible item. + **/ + indexOfFirstVisible: number; + + /** + * Gets the index of the last visible item in the ListView. + **/ + indexOfLastVisible: number; + + /** + * Gets or sets the data source that provides the ListView with items. + **/ + itemDataSource: IListDataSource; + + /** + * Go Gets or sets a value that specifies whether items can be dragged. When this is set to true the ListView provides built in behaviors related to item dragging. + **/ + itemsDraggable: boolean; + + /** + * Gets or sets whether the ListView control's items can be reordered within itself by dragging and dropping. + **/ + itemsReorderable: boolean; + + /** + * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the itemDataSource. Each item can contain multiple elements, but it must have a single root element. + **/ + itemTemplate: any; + + /** + * Gets or sets an object that controls the layout of the ListView. + **/ + layout: ILayout2; + + /** + * Gets or sets a value that specifies how the ListView fetches items and adds and removes them to the DOM. Don't change the value of this property after the ListView has begun loading data. + **/ + loadingBehavior: string; + + /** + * Gets a value that indicates whether the ListView is still loading or whether loading is complete. + **/ + loadingState: string; + + /** + * Gets or sets the maximum number of realized items. + **/ + maxDeferredItemCleanup: number; + + /** + * Gets or sets the number of pages to load when the loadingBehavior property is set to "incremental" and the user scrolls beyond the threshold specified by the pagesToLoadThreshold property. + **/ + pagesToLoad: number; + + /** + * Gets or sets the threshold (in pages) for initiating an incremental load. When the last visible item is within the specified number of pages from the end of the loaded portion of the list, and if automaticallyLoadPages is true and loadingBehavior is set to "incremental", the ListView initiates an incremental load. + **/ + pagesToLoadThreshold: number; + + /** + * Gets or sets the function that is called when the ListView discards or recycles the element representation of a group header. + **/ + resetGroupHeader: (header: any, element: HTMLElement) => void; + + /** + * Gets or sets the function that is called when an item is removed, an item is changed, or an item falls outside of the realized range of the ListView. + **/ + resetItem: (item: T, element: HTMLElement) => void; + + /** + * Gets or sets the distance, in pixels, of the start of the viewable area within the viewport. + **/ + scrollPosition: number; + + /** + * Gets an ISelection that contains the range of currently selected items. + **/ + selection: ISelection; + + /** + * Gets or sets the selection mode of the ListView. + **/ + selectionMode: SelectionMode; + + /** + * Gets or sets how the ListView reacts to the swipe gesture. The swipe gesture can select the swiped items or can have no effect on the current selection. + **/ + swipeBehavior: WinJS.UI.SwipeBehavior; + + /** + * Gets or sets how the ListView reacts when the user taps or clicks an item. + **/ + tapBehavior: TapBehavior; + + /** + * Gets a ZoomableView that supports semantic zoom functionality. This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. + **/ + zoomableView: IZoomableView>; + + //#endregion Properties + + } + + /** + * Represents a menu flyout for displaying commands. + **/ + class Menu { + //#region Constructors + + /** + * Creates a new Menu object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new Menu. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the Menu is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Occurs after the Menu is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Occurs before the Menu is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden Menu is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this Menu. Call this method when the Menu is no longer needed. After calling this method, the Menu becomes unusable. + **/ + dispose(): void; + + /** + * Returns the MenuCommand object identified by id. + * @param id The element identifier (ID) of the command to be returned. + * @returns The command identified by id. + **/ + getCommandById(id: string): MenuCommand; + + /** + * Hides the Menu. + **/ + hide(): void; + + /** + * Hides the specified commands of the Menu. + * @param commands The commands to hide. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the Menu, if hidden, regardless of other states. + * @param anchor Required. The DOM element to anchor the Menu. + * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. + * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. + **/ + show(anchor: HTMLElement, placement: string, alignment: string): void; + + /** + * Shows the specified commands of the Menu. + * @param commands The commands to show. The array elements may be Menu objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate: boolean): void; + + /** + * Shows the specified commands of the Menu while hiding all other commands. + * @param commands The commands to show. The array elements may be MenuCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the default alignment to be used for this Menu. + **/ + alignment: string; + + /** + * Gets or sets the default anchor to be used for this Menu. + **/ + anchor: HTMLElement; + + /** + * Sets the MenuCommand objects that appear in the menu. + **/ + commands: MenuCommand[]; + + /** + * Gets the DOM element that hosts the Menu. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the Menu is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the default placement to be used for this Menu. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Represents a command to be displayed in a Menu object. + **/ + class MenuCommand { + //#region Constructors + + /** + * Creates a new MenuCommand object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new MenuCommand. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Disposes this control. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that indicates whether the MenuCommand is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the MenuCommand. + **/ + element: HTMLElement; + + /** + * Adds an extra CSS class during construction. + **/ + extraClass: string; + + /** + * Gets or sets the Flyout object displayed by this command. The specified flyout is shown when the MenuCommand's button is invoked. + **/ + flyout: Flyout; + + /** + * Gets a value that indicates whether the MenuCommand is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * Gets the element identifier (ID) of the command. + **/ + id: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Gets or sets the function to be invoked when the command is clicked. + **/ + onclick: Function; + + /** + * Gets or sets the selected state of a toggle button. + **/ + selected: boolean; + + /** + * Gets the type of the command. + **/ + type: string; + + //#endregion Properties + + } + + /** + * Displays navigation commands in a toolbar that the user can show or hide. + **/ + class NavBar { + //#region Constructors + + /** + * Creates a new NavBar. + * @constructor + * @param element The DOM element that will host the new NavBar. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs immediately after the NavBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised after the NavBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before the NavBar is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Occurs before a hidden NavBar is shown. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + /** + * Occurs after the NavBar has finished processing its child elements. + * @param eventInfo An object that contains information about the event. + **/ + onchildrenprocessed(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBar. Call this method when the NavBar is no longer needed. After calling this method, the NavBar becomes unusable. + **/ + dispose(): void; + + /** + * Hides the NavBar. + **/ + hide(): void; + + /** + * Hides the specified commands of the NavBar. + * @param commands The commands to hide. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to hide the commands immediately, without animating them; otherwise, false. + **/ + hideCommands(commands: any[], immediate: boolean): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Shows the NavBar if it is not disabled. + **/ + show(): void; + + /** + * Shows the specified commands of the NavBar. + * @param commands The commands to show. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the commands immediately, without animating them; otherwise, false. + **/ + showCommands(commands: any[], immediate: boolean): void; + + /** + * Shows the specified commands of the NavBar while hiding all other commands. + * @param commands The commands to show. The array elements may be NavBarCommand objects, or the string identifiers (IDs) of commands. + * @param immediate The parameter immediate is not supported and may be altered or unavailable in the future. true to show the specified commands (and hide the others) immediately, without animating them; otherwise, false. + **/ + showOnlyCommands(commands: any[], immediate: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + commands: AppBarCommand; + + /** + * Gets or sets a value that indicates whether the NavBar is disabled. + **/ + disabled: boolean; + + /** + * Gets the HTML element that hosts this NavBar. + **/ + element: HTMLElement; + + /** + * Gets a value that indicates whether the NavBar is hidden or in the process of becoming hidden. + **/ + hidden: boolean; + + /** + * This API supports the WinJS infrastructure and is not intended to be used directly from your code. + **/ + layout: string; + + /** + * Gets or sets a value that specifies whether the NavBar appears at the top or bottom of the main view. + **/ + placement: string; + + /** + * Gets or sets a value that indicates whether the NavBar is sticky (won't light dismiss). If not sticky, the NavBar dismisses normally when the user touches outside of the NavBar. + **/ + sticky: boolean; + + //#endregion Properties + + } + + /** + * Represents a navigation command in a NavBarContainer. + **/ + class NavBarCommand { + //#region Constructors + + /** + * Creates a new NavBarCommand. + * @constructor + * @param element The DOM element hosts the new NavBarCommand. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBarCommand. Call this method when the NavBarCommand is no longer needed. After calling this method, the NavBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the HTML element that hosts this NavBarCommand. + **/ + element: HTMLElement; + + /** + * Gets or sets the command's icon. + **/ + icon: string; + + /** + * Gets or sets the label of the command. + **/ + label: string; + + /** + * Get or sets the location to navigate to when this command is invoked. + **/ + location: any; + + /** + * Gets or sets a value that specifies whether to show the split tab stop. + **/ + splitButton: boolean; + + /** + * Gets a value that indicates whether the splitButton is open. + **/ + splitOpened: boolean; + + /** + * Gets or sets a user-defined object that represents the state associated with the command's location. + **/ + state: any; + + /** + * Gets or sets the tooltip of the command. + **/ + tooltip: any; + + //#endregion Properties + + } + + /** + * Contains a group of NavBarCommand objects in a NavBar. + **/ + class NavBarContainer { + //#region Constructors + + /** + * Creates a new NavBarContainer. + * @constructor + * @param element The DOM element hosts the new NavBarContainer. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when a child NavBarCommand object's click event fires. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.navbarcommand, detail.data. + **/ + oninvoked(eventInfo: CustomEvent): void; + + /** + * Occurs when the split button of a child NavBarCommand is opened or closed. A split button is toggled when the user navigates to another page or opens another split button. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.opened, detail.index, detail.navbarcommand, detail.data. + **/ + onsplittoggle(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this NavBarCommand. Call this method when the NavBarCommand is no longer needed. After calling this method, the NavBarCommand becomes unusable. + **/ + dispose(): void; + + /** + * Forces the NavBarContainer to update its layout. Use this function when making the NavBarContainer visible again after you set its style.display property to "none". + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the index of the current item. + **/ + currentIndex: number; + + /** + * Gets or sets a WinJS.Binding.List that generates NavBarCommand objects. + **/ + data: WinJS.Binding.List; + + /** + * Gets the HTML element that hosts this NavBarContainer. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether NavBarCommand objects in this container use a fixed or dynamic width. + **/ + fixedSize: boolean; + + /** + * Gets or sets a value that specifies whether the NavBarContainer has a horizontal or vertical layout. + **/ + layout: Orientation; + + /** + * Gets or sets a value that specifies how many rows of navigation commands to display on a page. + **/ + maxRows: number; + + /** + * Gets or sets the WinJS.Binding.Template or templating function that creates the DOM elements for each item in the data source. Each item can contain multiple elements, but it must have a single root element. + **/ + template: WinJS.Binding.Template; + + //#endregion Properties + + } + + /** + * Lets the user rate something by clicking an icon that represents a rating. The Rating control can display three types of ratings: an average rating, a tentative rating, and the user's rating. + **/ + class Rating { + //#region Constructors + + /** + * Creates a new Rating. + * @constructor + * @param element The DOM element hosts the new Rating. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the user finishes interacting with the rating control without committing a tentative rating. + * @param eventInfo An object that contains information about the event. + **/ + oncancel(eventInfo: Event): void; + + /** + * Raised when the user commits a change to the userRating. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. + **/ + onchange(eventInfo: CustomEvent): void; + + /** + * Raised when the user is choosing a new tentative Rating. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tentativeRating. + **/ + onpreviewchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this Rating. Call this method when the Rating is no longer needed. After calling this method, the Rating becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the average rating. + **/ + averageRating: number; + + /** + * Gets or sets whether the control is disabled. When the control is disabled, the user can't specify a new user rating or modify an existing rating. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the Rating. + **/ + element: HTMLElement; + + /** + * Gets or sets whether control lets the user clear the rating. + **/ + enableClear: boolean; + + /** + * Gets or sets the maximum possible rating value. + **/ + maxRating: number; + + /** + * Gets or sets a set of descriptions to show for rating values in the tooltip. + **/ + tooltipStrings: string[]; + + /** + * Gets or sets the user's rating. + **/ + userRating: number; + + //#endregion Properties + + } + + /** + * Generates HTML from a set of data. Use this control to generate lists of items. + **/ + class Repeater { + //#region Constructors + + /** + * Creates a new Repeater control. + * @constructor + * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". + **/ + constructor(options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised after an item in the Repeater control's data source changes and after the corresponding DOM element has been updated. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. + **/ + onitemchanged(eventInfo: CustomEvent): void; + + /** + * Raised after an item in the Repeater control's data source changes but before the corresponding DOM element has been updated. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.index, detail.key, detail.newElement, detail.newItem, detail.newValue, detail.oldElement, detail.oldItem, detail.oldValue, detail.setPromise. + **/ + onitemchanging(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been added to the Repeater control's data source and after the corresponding DOM element has been added. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. + **/ + oniteminserted(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been added to the Repeater control's data source but before the corresponding DOM element has been added. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.value. + **/ + oniteminserting(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. + **/ + onitemmoved(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source but before the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.key, detail.oldIndex, detail.newIndex. + **/ + onitemmoving(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been moved from one index to another in the Repeater control's data source and after the corresponding DOM element has been moved. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. + **/ + onitemremoved(eventInfo: CustomEvent): void; + + /** + * Raised after an item has been removed from the Repeater control's data source but before the corresponding DOM element has been removed. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElement, detail.index, detail.item, detail.setPromise. + **/ + onitemremoving(eventInfo: CustomEvent): void; + + /** + * Raised when the Repeater has finished loading a new set of data. This event is only fired on construction. This event is only raised when the Repeater is constructed or its data source or template changes. + * @param eventInfo An object that contains information about the event. + **/ + onitemsloaded(eventInfo: CustomEvent): void; + + /** + * Raised after the Repeater control's underlying data has been updated and after the updated HTML has been reloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements. + **/ + onitemsreloaded(eventInfo: CustomEvent): void; + + /** + * Raised after the Repeater control's underlying data has been updated but before the updated HTML has been reloaded. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.affectedElements, detail.setPromise. + **/ + onitemsreloading(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Repeater. Call this method when the Repeater is no longer needed. After calling this method, the Repeater becomes unusable. + **/ + dispose(): void; + + /** + * Returns the HTML element for the item at the specified index. + * @param index The index of the item. + * @returns The DOM element for the specified item. + **/ + elementFromIndex(index: number): HTMLElement; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the List that provides the Repeater with items to display. + **/ + data: WinJS.Binding.List; + + /** + * Gets the DOM element that hosts the Repeater. + **/ + element: HTMLElement; + + /** + * Gets the number of items in the Repeater control. + **/ + length: number; + + /** + * Gets or sets a WinJS.Binding.Template or custom rendering function that defines the HTML of each item within the Repeater. + **/ + template: WinJS.Binding.Template; + + //#endregion Properties + + } + + /** + * Enables the user to perform search queries and select suggestions. + **/ + class SearchBox { + //#region Constructors + + /** + * Creates a new SearchBox. + * @constructor + * @param element The DOM element hosts the new SearchBox. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when the user or the app changes the queryText. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.queryText, detail.linguisticDetails. + **/ + onquerychanged(eventInfo: CustomEvent): void; + + /** + * Raised awhen the user clicks the search glyph or presses Enter. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.queryText, detail.linguisticDetails, detail.keyModifiers. + **/ + onquerysubmitted(eventInfo: CustomEvent): void; + + /** + * Raised when the app automatically redirects focus to the search box. This event can only be raised when the focusOnKeyboardInput property is set to true. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.propertyName. + **/ + onreceivingfocusonkeyboardinput(eventInfo: CustomEvent): void; + + /** + * Raised when the user selects a suggested option for the search. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.tag, detail.keyModifiers, detail.storageFile. + **/ + onresultsuggestionschosen(eventInfo: CustomEvent): void; + + /** + * Raised when the system requests search suggestions from this app. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: detail.language, detail.linguisticDetails, detail.queryText, detail.searchSuggestionCollection. + **/ + onsuggestionsrequested(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. Note that you drop the "on" when specifying the event name. For example, instead of specifying "onclick", you specify "click". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SearchBox. Call this method when the SearchBox is no longer needed. After calling this method, the SearchBox becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + /** + * Specifies whether suggestions based on local files are automatically displayed in the search pane, and defines the criteria that Windows uses to locate and filter these suggestions. + * @param settings The new settings for local content suggestions. + **/ + setLocalContentSuggestionSettings(settings: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets whether the first suggestion is chosen when the user presses Enter. + **/ + chooseSuggestionOnEnter: boolean; + + /** + * Gets or sets a value that specifies whether the SearchBox is disabled. If the control is disabled, it won't receive focus. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the SearchBox. + **/ + element: HTMLElement; + + /** + * Gets or sets a value that specifies whether the search box automatically receives focus when the user types into the app window. + **/ + focusOnKeyboardInput: boolean; + + /** + * Gets or sets the placeholder text for the SearchBox. This text is displayed if there is no other text in the input box. + **/ + placeholderText: string; + + /** + * Gets or sets the query text for the SearchBox. + **/ + queryText: string; + + /** + * Gets or sets the search history context. This context is used a secondary key (the app ID is the primary key) for storing search history. + **/ + searchHistoryContext: string; + + /** + * Gets or sets a value that specifies whether search history is disabled. + **/ + searchHistoryDisabled: boolean; + + //#endregion Properties + + } + + /** + * Enables the user to zoom between two different views supplied by two child controls. One child control supplies the zoomed-out view and the other provides the zoomed-in view. + **/ + class SemanticZoom { + //#region Constructors + + /** + * Creates a new SemanticZoom. + * @constructor + * @param element The DOM element that hosts the SemanticZoom. + * @param options An object that contains one or more property/value pairs to apply to the new control. This object can contain these properties: initiallyZoomedOut Boolean, zoomFactor 0.2–0.85. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the control zooms in or out. + * @param eventInfo An object that contains information about the event. The detail property of this object is true when the control is zoomed out. Otherwise, it's false. + **/ + onzoomchanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SemanticZoom. Call this method when the SemanticZoom is no longer needed. After calling this method, the SemanticZoom becomes unusable. + **/ + dispose(): void; + + /** + * Forces the SemanticZoom to update its layout. Use this function when making the SemanticZoom visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Unregisters an event handler for the specified event. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the SemanticZoom control. + **/ + element: HTMLElement; + + /** + * Gets or a sets a value that specifies whether to display the SemanticZoom zoom out button. + **/ + enableButton: boolean; + + /** + * Determines whether any controls contained in a SemanticZoom should be processed separately. This property is always true, meaning that the SemanticZoom takes care of processing its own controls. + **/ + isDeclarativeControlContainer: boolean; + + /** + * Gets or sets a value that indicates whether SemanticZoom is locked and zooming between views is disabled. + **/ + locked: boolean; + + /** + * Gets or sets a value that indicates whether the control is zoomed out. + **/ + zoomedOut: boolean; + + /** + * Gets or sets a value that specifies how much the scaling the cross-fade animation performs when the SemanticZoom transitions between views. + **/ + zoomFactor: number; + + //#endregion Properties + + } + + /** + * Provides users with fast, in-context access to settings that affect the current Windows Store app. + **/ + class SettingsFlyout { + //#region Constructors + + /** + * Creates a new SettingsFlyout object. + * @constructor + * @param element The DOM element that will host the control. + * @param options The set of properties and values to apply to the new SettingsFlyout. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised immediately after the SettingsFlyout is completely hidden. + * @param eventInfo An object that contains information about the event. + **/ + onafterhide(eventInfo: Event): void; + + /** + * Raised immediately after a SettingsFlyout is fully shown. + * @param eventInfo An object that contains information about the event. + **/ + onaftershow(eventInfo: Event): void; + + /** + * Raised just before hiding a SettingsFlyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforehide(eventInfo: Event): void; + + /** + * Raised just before showing a SettingsFlyout. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeshow(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param type The event type to register. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this SettingsFlyout. Call this method when the SettingsFlyout is no longer needed. After calling this method, the SettingsFlyout becomes unusable. + **/ + dispose(): void; + + /** + * Hides the SettingsFlyout, if visible, regardless of other states. + **/ + hide(): void; + + /** + * Loads a fragment of the SettingsFlyout. Your app calls this when the user invokes a settings command and the WinJS.Application.onsettings event occurs. + * @param e An object that contains information about the event, received from the WinJS.Application.onsettings event. The detail property of this object contains the applicationcommands sub-property that you set to an array of settings commands. You then populate the SettingsFlyout with these commands by a call to populateSettings. + **/ + static populateSettings(e: CustomEvent): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param type The event type to unregister. It must be beforeshow, beforehide, aftershow, or afterhide. + * @param listener The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Shows the SettingsPane UI, if hidden. + **/ + show(): void; + + /** + * Shows the SettingsPane UI, if hidden, regardless of other state. + **/ + static show(): void; + + /** + * Show the Settings flyout using the Settings element identifier (ID) and the path of the page that contains the Settings element. + * @param id The ID of the Settings element. + * @param path The path of the page that contains the Settings element. + **/ + static showSettings(id: string, path: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element the SettingsFlyout is attached to. + **/ + element: HTMLElement; + + /** + * Gets whether the SettingsFlyout is hidden. + **/ + hidden: boolean; + + /** + * Gets or sets the settings command Id for the SettingsFlyout control. + **/ + settingsCommandId: string; + + /** + * This property may be unavailable or altered in future versions. Use the CSS width property of the element that has the win-settingsflyout class instead. + **/ + width: string; + + //#endregion Properties + + } + + /** + * A type of IListDataSource that provides read-access to an object that implements the IStorageQueryResultBase interface. A StorageDataSource enables you to query and bind to items in the data source. + **/ + class StorageDataSource { + //#region Constructors + + /** + * Creates a new StorageDataSource object. + * @constructor + * @param query The IStorageQueryResultBase that the StorageDataSource obtains its items from. Instead of IStorageQueryResultBase, you can also pass one of these string values: Music, Pictures, Videos, Documents. + * @param options The set of properties and values to apply to the new StorageDataSource. Properties on this object may include: mode , requestedThumbnailSize , thumbnailOptions , synchronous . + **/ + constructor(query: any, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Draws the thumbnail for the specified item to the specified img element. + * @param item The item to retrieve the thumbnail for. + * @param image The img element that will display the thumbnail. + * @returns A Promise that completes when the full-quality thumbnail is visible. + **/ + loadThumbnail(item: IItem, image: HTMLImageElement): Promise; + + //#endregion Methods + + } + + /** + * Prevents a DOM sub-tree from receiving tab navigations and focus. + **/ + class TabContainer { + //#region Constructors + + /** + * Creates a new TabContainer. + * @constructor + * @param element The DOM element that hosts the TabContainer control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties. + **/ + constructor(element: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this TabContainer. Call this method when the TabContainer is no longer needed. After calling this method, the TabContainer becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the child DOM element that receives tab focus. + **/ + childFocus: HTMLElement; + + /** + * Gets or sets the tab index of this container. + **/ + tabIndex: number; + + //#endregion Properties + + } + + /** + * Allows users to select time values. + **/ + class TimePicker { + //#region Constructors + + /** + * Initializes a new instance of a TimePicker control. + * @constructor + * @param element The DOM element associated with the TimePicker control. + * @param options The set of options to be applied initially to the TimePicker control. The options are the following: clock. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when any of the controls are changed by the user. + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event listener. + * @param type The type (name) of the event. + * @param listener The function that handles the event. + * @param capture If true, specifies that capture should be initiated, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this TimePicker. Call this method when the TimePicker is no longer needed. After calling this method, the TimePicker becomes unusable. + **/ + dispose(): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes a listener for the specified event. + * @param type The name of the event for which to remove a listener. + * @param listener The listener. + * @param useCapture Optional. The same value that was passed to addEventListener for this listener. It may be omitted if it was omitted when calling addEventListener. + **/ + removeEventListener(type: string, listener: Function, useCapture?: any): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the type of clock to display (12HourClock or 24HourClock). It defaults to the user setting. + **/ + clock: string; + + /** + * Gets or sets the current time of the TimePicker. Note that the date value is always July 15, 2011. + **/ + current: Date; + + /** + * Specifies whether the TimePicker is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element for the TimePicker. + **/ + element: HTMLElement; + + /** + * Gets or sets the display pattern for the hour. The default hour pattern is hour.integer(2). You can change the hour pattern by changing the number of integers displayed. + **/ + hourPattern: string; + + /** + * Gets or sets the minute increment. For example, 15 specifies that the TimePicker minute control should display only the choices 00, 15, 30, 45. + **/ + minuteIncrement: number; + + /** + * Gets or sets the display pattern for the minute. The default minute pattern is minute.integer(2). You can change the minute pattern by changing the number of integers displayed. + **/ + minutePattern: string; + + /** + * Gets or sets the display pattern for the period. The default period pattern is period.abbreviated(2). You can change the period pattern by changing the number of integers displayed. + **/ + periodPattern: string; + + //#endregion Properties + + } + + /** + * A control that lets the user switch an option between two states: on (checked is set to true) and off (checked is set to false). + **/ + class ToggleSwitch { + //#region Constructors + + /** + * Creates a new ToggleSwitch. + * @constructor + * @param element The DOM that hosts the control. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the change event, add a property named "onchange" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the ToggleSwitch control is flipped to on (checked == true) or off (checked == false). + * @param eventInfo An object that contains information about the event. + **/ + onchange(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this ToggleSwitch. Call this method when the ToggleSwitch is no longer needed. After calling this method, the ToggleSwitch becomes unusable. + **/ + dispose(): void; + + /** + * Handles the specified event. + * @param event The event. + **/ + handleEvent(event: any): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + raiseEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets a value that specifies whether the control is on or off. + **/ + checked: boolean; + + /** + * Gets or sets a value that specifies whether the control is disabled. + **/ + disabled: boolean; + + /** + * Gets the DOM element that hosts the ToggleSwitch. + **/ + element: HTMLElement; + + /** + * Gets or sets the text that displays when the ToggleSwitch is off (checked is set to false). + **/ + labelOff: string; + + /** + * Gets or sets the text that displays when the ToggleSwitch is on (checked is set to true). + **/ + labelOn: string; + + /** + * Gets or sets the main text for the ToggleSwitch control. This text is always displayed, regardless of whether the control is switched on or off. + **/ + title: string; + + //#endregion Properties + + } + + /** + * Displays a tooltip that can contain images and formatting. + **/ + class Tooltip { + //#region Constructors + + /** + * Creates a new Tooltip. + * @constructor + * @param element The DOM element associated that hosts the Tooltip. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the opened event, add a property named "onopened" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised just before the Tooltip is hidden. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeclose(eventInfo: CustomEvent): void; + + /** + * Raised just before the Tooltip appears. + * @param eventInfo An object that contains information about the event. + **/ + onbeforeopen(eventInfo: CustomEvent): void; + + /** + * Raised when the Tooltip is no longer displayed. + * @param eventInfo An object that contains information about the event. + **/ + onclosed(eventInfo: CustomEvent): void; + + /** + * Raised when the Tooltip is shown. + * @param eventInfo An object that contains information about the event. + **/ + onopened(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Hides the Tooltip. + **/ + close(): void; + + /** + * Releases resources held by this Tooltip. Call this method when the Tooltip is no longer needed. After calling this method, the Tooltip becomes unusable. + **/ + dispose(): void; + + /** + * Shows the Tooltip. + * @param type A value that specifies when to show the Tooltip. The default value is "mousedown". + **/ + open(type?: string): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets or sets the HTML element that is the content of the Tooltip. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts the Tooltip control. + **/ + element: HTMLElement; + + /** + * Gets or appends additional CSS classes to apply to the element that hosts the Tooltip. + **/ + extraClass: string; + + /** + * Gets or sets a value that specifies whether the Tooltip is an infotip, a tooltip that contains a lot of info and should be displayed for longer than a typical Tooltip. + **/ + infotip: boolean; + + /** + * Gets or sets the HTML content of the Tooltip. + **/ + innerHTML: string; + + /** + * Gets or sets the position for the Tooltip relative to its target element: top, bottom, left or right. + **/ + placement: string; + + //#endregion Properties + + } + + /** + * Scales a single child element to fill the available space without resizing it. This control reacts to changes in the size of the container as well as changes in size of the child element. For example, a media query may result in a change in aspect ratio. + **/ + class ViewBox { + //#region Constructors + + /** + * Initializes a new instance of the ViewBox control. + * @constructor + * @param element The DOM element that functions as the scaling box. This element fills 100% of the width and height allotted to it. + * @param options The set of options to be applied initially to the ViewBox control. There are currently no options on this control, and any options included in this parameter are ignored. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Adds an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Releases resources held by this ViewBox. Call this method when the ViewBox is no longer needed. After calling this method, the ViewBox becomes unusable. + **/ + dispose(): void; + + /** + * Forces the ViewBox to update its layout. Use this function when making the ViewBox visible again after its style.display property had been set to "none". + **/ + forceLayout(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that functions as the scaling box. + **/ + element: HTMLElement; + + //#endregion Properties + + } + + /** + * Serves as the base class for a custom IListDataSource. + **/ + class VirtualizedDataSource { + //#region Constructors + + /** + * Initializes the VirtualizedDataSource base class of a custom data source. + * @constructor + * @param listDataAdapter The object that supplies data to the VirtualizedDataSource. + * @param options An object that can contain properties that specify additional options for the VirtualizedDataSource. It supports these properties: cacheSize. + **/ + constructor(listDataAdapter: IListDataAdapter, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Occurs when the status of the VirtualizedDataSource changes. + * @param eventInfo An object that contains information about the event. The detail property of this object contains the following sub-properties: status. + **/ + statuschanged(eventInfo: CustomEvent): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. See the VirtualizedDataSource object page for a list of events. Note that you drop the "on" when specifying the event name for the addEventListener method. For example, instead of specifying "onstatuschanged", you specify "statuschanged". + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. See the VirtualizedDataSource object page for a list of events. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + } + + //#endregion Objects + + //#region Functions + + /** + * Returns a new IListDataSource that adds group information to the items of another IListDataSource. + * @param listDataSource The data source for the individual items to group. + * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. + * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. + * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. + * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + **/ + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + + /** + * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. + **/ + function disableAnimations(): void; + + /** + * Used to enable all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be enabled, as the determination is made based on several factors. + **/ + function enableAnimations(): void; + + /** + * Marks a event handler function as being compatible with declarative processing. + * @param handler The handler to be marked as compatible with declarative processing. + * @returns The handler, marked as compatible with declarative processing. + **/ + function eventHandler(handler: any): any; + + /** + * Asynchronously executes a collection of CSS animations on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements to be animated. This parameter can be expressed in several ways: As the special value "undefined", which means that the animation has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param animation The animation description or an array of animation descriptions to apply to element. An animation description is a JavaScript object with specific properties, listed below. There are two types of animation descriptions: one for keyframe-based animations and one for explicit animations. These types are distinguished by whether the keyframe property has a defined value. The following properties are required for both types of animation descriptions: property (string), delay (number), duration (number), timing (string). If an animation has a keyframe property with a defined, non-null value, then the animation is a keyframe-based animation. A keyframe-based animation description requires the following property in addition to those mentioned above: keyframe (string). If an animation does not have a keyframe property, or if the value of the property is null or undefined, then the animation is an explicit animation. An explicit animation description requires the following properties in addition to the common properties mentioned above: from, to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise object that completes when the CSS animation is complete. + **/ + function executeAnimation(element: HTMLElement, animation: any): Promise; + + /** + * Asynchronously executes a collection of CSS transitions on a collection of elements. This is the underlying animation mechanism used by the Animations Library. Apps are encouraged to use the Animations Library to conform with the standard look and feel of the rest of the system, rather than calling this function directly. + * @param element Element or elements on which to perform the transition. This parameter can be expressed in several ways: As the special value "undefined", which means that the transition has no target, As a single object, As a JavaScript array (possibly empty), in which each element of the array can be a single element or a JavaScript array of elements., As a NodeList (for example, the result of querySelectorAll), As an HTMLCollection. + * @param transition The transition description or an array of transition descriptions to apply to element. A transition description is a JavaScript object with these properties: property (string), delay (number), duration (number), timing (string), from (optional), to. The values given in the from and to properties must be valid for the CSS property specified by the property property. For example, if the CSS property is "opacity", then the from and to properties must be numbers between 0 and 1 (inclusive). + * @returns Returns a Promise that completes when the transition is finished. + **/ + function executeTransition(element: HTMLElement, transition: any): Promise; + + /** + * Retrieves the items in the specified index range. + * @param dataSource The data source that contains the items to retrieve. + * @param ranges An array of ISelectionRange objects that have firstIndex and lastIndex values. + * @returns A Promise that contains an array of the requested IItem objects. + **/ + function getItemsFromRanges(dataSource: IListDataSource, ranges: ISelectionRange[]): Promise>; + + /** + * Determines whether the Animations Library and ListView animations will be performed if called. + * @returns Returns true if animations will be performed; otherwise false. + **/ + function isAnimationEnabled(): boolean; + + /** + * Applies declarative control binding to all elements, starting at the specified root element. + * @param rootElement The element at which to start applying the binding. If this parameter is not specified, the binding is applied to the entire document. + * @param skipRoot If true, the elements to be bound skip the specified root element and include only the children. + * @returns A promise that is fulfilled when binding has been applied to all the controls. + **/ + function processAll(rootElement?: Element, skipRoot?: boolean): Promise; + + /** + * Applies declarative control binding to the specified element. + * @param element The element to bind. + * @returns A promise that is fulfilled after the control is activated. The value of the promise is the control that is attached to element. + **/ + function process(element: Element): Promise; + + /** + * Walks the DOM tree from the given element to the root of the document. Whenever a selector scope is encountered, this method performs a lookup within that scope for the specified selector string. The first matching element is returned. + * @param selector The selector string. + * @param element The element to begin walking to the root of the document from. + * @returns The target element, if found. + **/ + function scopedSelect(selector: string, element: HTMLElement): HTMLElement; + + /** + * Given a DOM element and a control, attaches the control to the element. + * @param element Element to associate with the control. + * @param control The control to attach to the element. + **/ + function setControl(element: HTMLElement, control: any): void; + + /** + * Adds the set of declaratively specified options (properties and events) to the specified control. If name of the options property begins with "on", the property value is a function and the control supports addEventListener. setControl calls addEventListener on the control. + * @param control The control on which the properties and events are to be applied. + * @param options The set of options that are specified declaratively. + **/ + function setOptions(control: any, options?: any): void; + + //#endregion Functions } /** * Provides functions to load HTML content programmatically. **/ declare module WinJS.UI.Fragments { - //#region Functions + //#region Functions - /** - * Starts loading the fragment at the specified location. The returned promise completes when the fragment is ready to be copied. - * @param href The URI that contains the fragment to be copied. - * @returns A promise that is fulfilled when the fragment has been prepared for copying. - **/ - function cache(href: string): Promise; + /** + * Starts loading the fragment at the specified location. The returned promise completes when the fragment is ready to be copied. + * @param href The URI that contains the fragment to be copied. + * @returns A promise that is fulfilled when the fragment has been prepared for copying. + **/ + function cache(href: string): Promise; - /** - * Removes any cached information about the specified fragment. This method does not unload any scripts or styles that are referenced by the fragment. - * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. - **/ - function clearCache(href: string): void; + /** + * Removes any cached information about the specified fragment. This method does not unload any scripts or styles that are referenced by the fragment. + * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. + **/ + function clearCache(href: string): void; - /** - * Loads the contents of the specified URI into the specified element without copying it. - * @param href The URI that contains the fragment to copy. - * @param element Optional. The element to which the fragment is appended. - * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The element is not added to the cache. See also rendercopy, where the element is added to the cache. - **/ - function render(href: string, element?: HTMLElement): Promise; + /** + * Loads the contents of the specified URI into the specified element without copying it. + * @param href The URI that contains the fragment to copy. + * @param element Optional. The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The element is not added to the cache. See also rendercopy, where the element is added to the cache. + **/ + function render(href: string, element?: HTMLElement): Promise; - /** - * Loads and copies the contents of the specified URI into the specified element. - * @param href The URI that contains the fragment to copy. - * @param target The element to which the fragment is appended. - * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. - **/ - function renderCopy(href: string, target?: HTMLElement): Promise; + /** + * Loads and copies the contents of the specified URI into the specified element. + * @param href The URI that contains the fragment to copy. + * @param target The element to which the fragment is appended. + * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. + **/ + function renderCopy(href: string, target?: HTMLElement): Promise; - //#endregion Functions + //#endregion Functions } /** * Provides methods for defining and displaying PageControl objects. **/ declare module WinJS.UI.Pages { - //#region Interfaces + //#region Interfaces - /** - * Provides members for a PageControl. You implement this interface when defining a new PageControl. - **/ - interface IPageControlMembers { - //#region Methods + /** + * Provides members for a PageControl. You implement this interface when defining a new PageControl. + **/ + interface IPageControlMembers { + //#region Methods - /** - * Called if any error occurs during the processing of the page. - * @param err The error that occurred. - * @returns Nothing if the error was handled, or an error promise if the error was not handled. - **/ - error?(err: any): Promise; + /** + * Called if any error occurs during the processing of the page. + * @param err The error that occurred. + * @returns Nothing if the error was handled, or an error promise if the error was not handled. + **/ + error? (err: any): Promise; - /** - * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. - * @param element The DOM element that will contain all the content for the page. - * @param options The options passed to the constructor of the page. - * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. - **/ - init?(element: HTMLElement, options: any): Promise; + /** + * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + init? (element: HTMLElement, options: any): Promise; - /** - * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. - * @param uri The URI from which to create DOM objects. - * @returns A promise whose fulfilled value is the set of unparented DOM objects. - **/ - load?(uri: string): Promise; + /** + * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. + * @param uri The URI from which to create DOM objects. + * @returns A promise whose fulfilled value is the set of unparented DOM objects. + **/ + load? (uri: string): Promise; - /** - * Initializes the control after the content of the control is set. - * @param element The DOM element that will contain all the content for the page. - * @param options The options that are to be passed to the constructor of the page. - * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. - **/ - processed?(element: HTMLElement, options: any): Promise; + /** + * Initializes the control after the content of the control is set. + * @param element The DOM element that will contain all the content for the page. + * @param options The options that are to be passed to the constructor of the page. + * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + processed? (element: HTMLElement, options: any): Promise; - /** - * Called after all initialization and rendering is complete. At this time, the element is ready for use. - * @param element The DOM element that contains all the content for the page. - * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. - * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. - **/ - ready?(element: HTMLElement, options: any): Promise; + /** + * Called after all initialization and rendering is complete. At this time, the element is ready for use. + * @param element The DOM element that contains all the content for the page. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. + **/ + ready? (element: HTMLElement, options: any): Promise; - /** - * Takes the elements returned by the load method and attaches them to the specified element. - * @param element The DOM element to which the loadResult elements are appended. - * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. - * @param loadResult A Promise that contains the elements returned from the load method. - **/ - render?(element: HTMLElement, options: any, loadResult: Promise): void; + /** + * Takes the elements returned by the load method and attaches them to the specified element. + * @param element The DOM element to which the loadResult elements are appended. + * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param loadResult A Promise that contains the elements returned from the load method. + **/ + render? (element: HTMLElement, options: any, loadResult: Promise): void; - //#endregion Methods + //#endregion Methods - } + } - //#endregion Interfaces + //#endregion Interfaces - //#region Objects + //#region Objects - /** - * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. - **/ - class PageControl { - } + /** + * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. + **/ + class PageControl { + } - //#endregion Objects + //#endregion Objects - //#region Functions + //#region Functions - /** - * Creates a new PageControl from the specified URI that contains the specified members. Multiple calls to this method for the same URI are allowed, and all members will be merged. - * @param uri The URI for the content that defines the page. - * @param members An object that defines the members that the control will have. - * @returns A constructor function that creates the PageControl. - **/ - function define(uri: string, members: IPageControlMembers): PageControl; + /** + * Creates a new PageControl from the specified URI that contains the specified members. Multiple calls to this method for the same URI are allowed, and all members will be merged. + * @param uri The URI for the content that defines the page. + * @param members An object that defines the members that the control will have. + * @returns A constructor function that creates the PageControl. + **/ + function define(uri: string, members: IPageControlMembers): PageControl; - /** - * Gets an already-defined page control for the specified URI, or creates a new one. - * @param uri The URI for the content that defines the page. - * @returns A constructor function that creates the page. - **/ - function get(uri: string): Function; + /** + * Gets an already-defined page control for the specified URI, or creates a new one. + * @param uri The URI for the content that defines the page. + * @returns A constructor function that creates the page. + **/ + function get(uri: string): Function; - /** - * Creates a PageControl from the specified URI and inserts it inside the specified element. - * @param uri The URI for the content that defines the page. - * @param element The DOM element to which the PageControl is appended. - * @param options An object that contains one or more property/value pairs to apply to the new PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. - * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. - * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. - **/ - function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + /** + * Creates a PageControl from the specified URI and inserts it inside the specified element. + * @param uri The URI for the content that defines the page. + * @param element The DOM element to which the PageControl is appended. + * @param options An object that contains one or more property/value pairs to apply to the new PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. + * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. + * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. + **/ + function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; - //#endregion Functions + //#endregion Functions } /** * Provides methods for detecting when the user tabs to or from DOM elements. **/ declare module WinJS.UI.TrackTabBehavior { - //#region Functions + //#region Functions - /** - * Sets the tab order for the specified element within its container. - * @param element The element to update. - * @param tabIndex The index value of the element within its container. - **/ - function attach(element: HTMLElement, tabIndex: number): void; + /** + * Sets the tab order for the specified element within its container. + * @param element The element to update. + * @param tabIndex The index value of the element within its container. + **/ + function attach(element: HTMLElement, tabIndex: number): void; - /** - * Removes the tab order information from the specified element. - * @param element The element to remove tab information from. - **/ - function detatch(element: HTMLElement): void; + /** + * Removes the tab order information from the specified element. + * @param element The element to remove tab information from. + **/ + function detatch(element: HTMLElement): void; - //#endregion Functions + //#endregion Functions } /** * Provides helper functions, for example, functions to add and remove CSS classes. **/ declare module WinJS.Utilities { - //#region Enumerations - - /** - * Defines a set of keyboard values. - **/ - enum Key { - /** - * The BACKSPACE key. - **/ - backspace, - /** - * The TAB key. - **/ - tab, - /** - * The ENTER key. - **/ - enter, - /** - * The SHIFT key. - **/ - shift, - /** - * The CTRL key. - **/ - ctrl, - /** - * The ALT key. - **/ - alt, - /** - * The PAUSE key. - **/ - pause, - /** - * The CAPS LOCK key. - **/ - capsLock, - /** - * The ESCAPE key. - **/ - escape, - /** - * The SPACE key. - **/ - space, - /** - * The PAGE UP key. - **/ - pageUp, - /** - * The PAGE DOWN key. - **/ - pageDown, - /** - * The END key. - **/ - end, - /** - * The HOME key. - **/ - home, - /** - * The LEFT ARROW key. - **/ - leftArrow, - /** - * The UP ARROW key. - **/ - upArrow, - /** - * The RIGHT ARROW key. - **/ - rightArrow, - /** - * The DOWN ARROW key. - **/ - downArrow, - /** - * The INSERT key. - **/ - insert, - /** - * The DELETE key. - **/ - deleteKey, - /** - * The 0 key. - **/ - num0, - /** - * The 1 key. - **/ - num1, - /** - * The 2 key. - **/ - num2, - /** - * The 3 key. - **/ - num3, - /** - * The 4 key. - **/ - num4, - /** - * The 5 key. - **/ - num5, - /** - * The 6 key. - **/ - num6, - /** - * The 7 key. - **/ - num7, - /** - * The 8 key. - **/ - num8, - /** - * The 9 key. - **/ - num9, - /** - * The a key. - **/ - a, - /** - * The b key. - **/ - b, - /** - * The c key. - **/ - c, - /** - * The d key. - **/ - d, - /** - * The e key. - **/ - e, - /** - * The f key. - **/ - f, - /** - * The g key. - **/ - g, - /** - * The h key. - **/ - h, - /** - * The i key. - **/ - i, - /** - * The j key. - **/ - j, - /** - * The k key. - **/ - k, - /** - * The l key. - **/ - l, - /** - * The m key. - **/ - m, - /** - * The n key. - **/ - n, - /** - * The o key. - **/ - o, - /** - * The p key. - **/ - p, - /** - * The q key. - **/ - q, - /** - * The r key. - **/ - r, - /** - * The s key. - **/ - s, - /** - * The t key. - **/ - t, - /** - * The u key. - **/ - u, - /** - * The v key. - **/ - v, - /** - * The w key. - **/ - w, - /** - * The x key. - **/ - x, - /** - * The y key. - **/ - y, - /** - * The z key. - **/ - z, - /** - * The left Windows key. - **/ - leftWindows, - /** - * The right Windows key. - **/ - rightWindows, - /** - * The menu key. - **/ - menu, - /** - * The 0 key on the numerical keypad. - **/ - numPad0, - /** - * The 1 key on the numerical keypad. - **/ - numPad1, - /** - * The 2 key on the numerical keypad. - **/ - numPad2, - /** - * The 3 key on the numerical keypad. - **/ - numPad3, - /** - * The 4 key on the numerical keypad. - **/ - numPad4, - /** - * The 5 key on the numerical keypad. - **/ - numPad5, - /** - * The 6 key on the numerical keypad. - **/ - numPad6, - /** - * The 7 key on the numerical keypad. - **/ - numPad7, - /** - * The 8 key on the numerical keypad. - **/ - numPad8, - /** - * The 9 key on the numerical keypad. - **/ - numPad9, - /** - * The multiplication key (*). - **/ - multiply, - /** - * The addition key (+). - **/ - add, - /** - * The subtraction key (-). - **/ - subtract, - /** - * The decimal point key (.) - **/ - decimalPoint, - /** - * The division key (/). - **/ - divide, - /** - * The F1 key. - **/ - F1, - /** - * The F2 key. - **/ - F2, - /** - * The F3 key. - **/ - F3, - /** - * The F4 key. - **/ - F4, - /** - * The F5 key. - **/ - F5, - /** - * The F6 key. - **/ - F6, - /** - * The F7 key. - **/ - F7, - /** - * The F8 key. - **/ - F8, - /** - * The F9 key. - **/ - F9, - /** - * The F10 key. - **/ - F10, - /** - * The F11 key. - **/ - F11, - /** - * The F12 key. - **/ - F12, - /** - * The NUMBER LOCK key. - **/ - numLock, - /** - * The SCROLL LOCK key. - **/ - scrollLock, - /** - * The browser BACK key. - **/ - browserBack, - /** - * The browser FORWARD key. - **/ - browserForward, - /** - * The semicolon key (;). - **/ - semicolon, - /** - * The equals key (=). - **/ - equal, - /** - * The comma key (,). - **/ - comma, - /** - * The dash key (-). - **/ - dash, - /** - * The period key (.). - **/ - period, - /** - * The forward slash key (/). - **/ - forwardSlash, - /** - * The grave accent key (`). - **/ - graveAccent, - /** - * The open bracket key ([). - **/ - openBracket, - /** - * The backslash key (\). - **/ - backSlash, - /** - * The close bracket key (]). - **/ - closeBracket, - /** - * The single quote key ('). - **/ - singleQuote - } - - //#endregion Enumerations - - //#region Objects - - /** - * A mixin that contains event-related functions. - **/ - var eventMixin: { - //#region Methods - - /** - * Adds an event listener to the control. - * @param type The type (name) of the event. - * @param listener The listener to invoke when the event gets raised. - * @param useCapture If true, initiates capture, otherwise false. - **/ - addEventListener(type: string, listener: Function, useCapture?: boolean): void; - - /** - * Raises an event of the specified type and with the specified additional properties. - * @param type The type (name) of the event. - * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. - * @returns true if preventDefault was called on the event. - **/ - dispatchEvent(type: string, eventProperties: any): boolean; - - /** - * Removes an event listener from the control. - * @param type The type (name) of the event. - * @param listener The listener to remove. - * @param useCapture true if capture is to be initiated, otherwise false. - **/ - removeEventListener(type: string, listener: Function, useCapture?: boolean): void; - - //#endregion Methods - - }; - - /** - * Represents the result of a query selector, and provides various operations that perform actions over the elements of the collection. - **/ - class QueryCollection { - //#region Constructors - - /** - * Initializes a new instance of a QueryCollection. - * @constructor - * @param items The items resulting from the query. - **/ - constructor(items: T[]); - - //#endregion Constructors - - //#region Methods - - /** - * Adds the specified class to all the elements in the collection. - * @param name The name of the class to add. - * @returns This QueryCollection object. - **/ - addClass(name: string): QueryCollection; - - /** - * Creates a QueryCollection that contains the children of the specified parent element. - * @param element The parent element. - * @returns The QueryCollection that contains the children of the element. - **/ - children(element: HTMLElement): QueryCollection; - - /** - * Clears the specified style property for all the elements in the collection. - * @param name The name of the style property to be cleared. - * @returns This QueryCollection object. - **/ - clearStyle(name: string): QueryCollection; - - /** - * Creates controls that are attached to the elements in this QueryCollection, if the ctor parameter is a function, or configures the controls that are attached to the elements in this QueryCollection, if the ctor parameter is an object. - * @param ctor If this parameter is a function, it is a constructor function that is used to create controls to attach to the elements. If it is an object, it is the set of options passed to the controls. - * @param options The options passed to the newly-created controls. - * @returns This QueryCollection object. - **/ - control(ctor: any, options?: any): QueryCollection; - - /** - * Performs an action on each item in the QueryCollection. - * @param callbackFn The action to perform on each item. - * @param thisArg The argument to bind to callbackFn. - * @returns The QueryCollection. - **/ - forEach(callbackFn: (value: T, index: number, array: T[]) => void, thisArg?: any): QueryCollection; - - /** - * Gets an item from the QueryCollection. - * @param index The index of the item to return. - * @returns A single item from the collection. - **/ - get(index: number): T; - - /** - * Gets an attribute value from the first element in the collection. - * @param name The name of the attribute. - * @returns The value of the attribute. - **/ - getAttribute(name: string): any; - - /** - * Determines whether the specified class exists on the first element of the collection. - * @param name The name of the class. - * @returns true if the element has the specified class; otherwise, false. - **/ - hasClass(name: string): boolean; - - /** - * Looks up an element by ID and wraps the result in a QueryCollection. - * @param id The ID of the element. - * @returns A QueryCollection that contains the element, if it is found. - **/ - id(id: string): QueryCollection; - - /** - * Adds a set of items to this QueryCollection. - * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. - **/ - include(items: T): void; - - /** - * Adds a set of items to this QueryCollection. - * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. - **/ - include(items: T[]): void; - - /** - * Registers the listener for the specified event on all the elements in the collection. - * @param eventType The name of the event. - * @param listener The event handler function to be called when the event occurs. - * @param capture true if capture == true is to be passed to addEventListener; otherwise, false. - **/ - listen(eventType: string, listener: Function, capture?: boolean): void; - - /** - * Executes a query selector on all the elements in the collection and aggregates the result into a QueryCollection. - * @param query The query selector string. - * @returns A QueryCollection object containing the aggregate results of executing the query on all the elements in the collection. - **/ - query(query: any): QueryCollection; - - /** - * Removes the specified class from all the elements in the collection. - * @param name The name of the class to be removed. - * @returns his QueryCollection object. - **/ - removeClass(name: string): QueryCollection; - - /** - * Unregisters the listener for the specified event on all the elements in the collection. - * @param eventType The name of the event. - * @param listener The event handler function. - * @param capture true if capture == true; otherwise, false. - * @returns This QueryCollection object. - **/ - removeEventListener(eventType: string, listener: Function, capture?: boolean): QueryCollection; - - /** - * Sets an attribute value on all the items in the collection. - * @param name The name of the attribute to be set. - * @param value The value of the attribute to be set. - * @returns This QueryCollection object. - **/ - setAttribute(name: string, value: any): QueryCollection; - - /** - * Sets the specified style property for all the elements in the collection. - * @param name The name of the style property. - * @param value The value for the property. - * @returns This QueryCollection object. - **/ - setStyle(name: string, value: any): QueryCollection; - - /** - * Renders a template that is bound to the given data and parented to the elements included in the QueryCollection. If the QueryCollection contains multiple elements, the template is rendered multiple times, once at each element in the QueryCollection per item of data passed. - * @param templateElement The DOM element to which the template control is attached. - * @param data The data to render. If the data is an array (or any other object that has a forEach method) then the template is rendered multiple times, once for each item in the collection. - * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. - * @returns The QueryCollection. - **/ - template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; - - /** - * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. - * @param name The name of the class to be toggled. - * @returns This QueryCollection object. - **/ - toggleClass(name: string): QueryCollection; - - //#endregion Methods - - } - - //#endregion Objects - - //#region Functions - - /** - * Adds the specified class to the specified element. - * @param e The element to which to add the class. - * @param name The name of the class to add. - * @returns The element. - **/ - function addClass(e: T, name: string): T; - - /** - * Gets a collection of elements that are the direct children of the specified element. - * @param element The parent element. - * @returns The collection of children of the element. - **/ - function children(element: HTMLElement): QueryCollection; - - /** - * Converts a CSS positioning string for the specified element to pixels. - * @param element The element. - * @param value The CSS positioning string. - * @returns The number of pixels. - **/ - function convertToPixels(element: HTMLElement, value: string): number; - - /** - * Creates an object that has one event for each name passed to the function. - * @param events A variable list of property names. - * @returns The object with the specified properties. The names of the properties are prefixed with 'on'. - **/ - function createEventProperties(...events: string[]): any; - - /** - * Gets the data value associated with the specified element. - * @param element The element. - * @returns The value associated with the element. - **/ - function data(element: HTMLElement): any; - - /** - * Disposes all first-generation disposable elements that are descendents of the specified element. The specified element itself is not disposed. - * @param element The root element whose sub-tree is to be disposed. - **/ - function disposeSubTree(element: HTMLElement): void; - - /** - * Removes all the child nodes from the specified element. - * @param element The element. - * @returns The element. - **/ - function empty(element: T): T; - - /** - * Determines whether the specified event occurred within the specified element. - * @param element The element. - * @param event The event. - * @returns true if the event occurred within the element; otherwise, false. - **/ - function eventWithinElement(element: HTMLElement, event: Event): boolean; - - /** - * Adds tags and type to a logging message. - * @param message The message to be formatted. - * @param tag The tag(s) to be applied to the message. Multiple tags should be separated by spaces. - * @param type The type of the message. - * @returns The formatted message. - **/ - function formatLog(message: string, tag: string, type: string): string; - - /** - * Gets the height of the content of the specified element. The content height does not include borders or padding. - * @param element The element. - * @returns The content height of the element. - **/ - function getContentHeight(element: HTMLElement): number; - - /** - * Gets the width of the content of the specified element. The content width does not include borders or padding. - * @param element The element. - * @returns The content width of the element. - **/ - function getContentWidth(element: HTMLElement): number; - - /** - * Gets the leaf-level type or namespace specified by the name parameter. - * @param name The name of the member. - * @param root The root to start in. Defaults to the global object. - * @returns The leaf-level type or namespace in the specified parent namespace. - **/ - function getMember(name: string, root?: any): any; - - /** - * Gets the position of the specified element. - * @param element The element. - * @returns An object that contains the left, top, width and height properties of the element. - **/ - function getPosition(element: HTMLElement): IPosition; - - /** - * Gets the left coordinate of the specified element relative to the specified parent. - * @param element The element. - * @param parent The parent element. - * @returns The relative left coordinate. - **/ - function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; - - /** - * Gets the top coordinate of the element relative to the specified parent. - * @param element The element. - * @param parent The parent element. - * @returns The relative top coordinate. - **/ - function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; - - /** - * Gets the height of the element, including its margins. - * @param element The element. - * @returns The height of the element including margins. - **/ - function getTotalHeight(element: HTMLElement): number; - - /** - * Gets the width of the element, including margins. - * @param element The element. - * @returns The width of the element including margins. - **/ - function getTotalWidth(element: HTMLElement): number; - - /** - * Determines whether the specified element has the specified class. - * @param e The element. - * @param name The name of the class. - * @returns true if the element has the class, otherwise false. - **/ - function hasClass(e: HTMLElement, name: string): boolean; - - /** - * Returns a collection with zero or one elements matching the specified id. - * @param id The ID of the element (or elements). - * @returns A collection of elements whose id matches the id parameter. - **/ - function id(id: string): QueryCollection; - - /** - * Calls insertAdjacentHTML on the specified element. - * @param element The element on which insertAdjacentHTML is to be called. - * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. - * @param text The text to insert. - **/ - function insertAdjacentHTML(element: HTMLElement, position: string, text: string): void; - - /** - * Calls insertAdjacentHTML on the specified element in the context of MSApp.execUnsafeLocalFunction. - * @param element The element on which insertAdjacentHTML is to be called. - * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. - * @param text Value to be provided to insertAdjacentHTML. - **/ - function insertAdjacentHTMLUnsafe(element: HTMLElement, position: string, text: string): void; - - /** - * Attaches the default dispose API wrapping the dispose implementation to the specified element. - * @param element The element to mark as disposable. - * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. - **/ - function markDisposable(element: HTMLElement, disposeImpl: Function): void; - - /** - * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. - * @param func The function to be marked as compatible with declarative processing. - * @returns The input function, marked as compatible with declarative processing. - **/ - function markSupportedForProcessing(func: U): U; - - /** - * Returns a QueryCollection with zero or one elements matching the specified selector query. - * @param query The CSS selector to use. See Selectors for more information. - * @param element Optional. The root element at which to start the query. If this parameter is omitted, the scope of the query is the entire document. - * @returns A QueryCollection with zero or one elements matching the specified selector query. - **/ - function query(query: any, element: HTMLElement): QueryCollection; - - /** - * Ensures that the specified function executes only after the DOMContentLoaded event has fired for the current page. The DOMContentLoaded event occurs after the page has been parsed but before all the resources are loaded. - * @param callback A function that executes after the DOMContentLoaded event has occurred. - * @param async If true, the callback should be executed asynchronously. - * @returns A promise that completes after the DOMContentLoaded event has occurred. - **/ - function ready(callback?: Function, async?: boolean): Promise; - - /** - * Removes the specified class from the specified element. - * @param e The element from which to remove the class. - * @param name The name of the class to remove. - * @returns The element. - **/ - function removeClass(e: T, name: string): T; - - /** - * Asserts that the value is compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. If the value is not compatible, and strictProcessing is on, an exception is thrown. All functions that have been declared using WinJS.Class.define, WinJS.Class.derive, WinJS.UI.Pages.define, or WinJS.Binding.converter are automatically marked as supported for declarative processing. Any other function that you use from a declarative context (that is, a context in which an HTML element has a data-win-control or data-win-options attribute) must be marked manually by calling this function. When you mark a function as supported for declarative processing, you are guaranteeing that the code in the function is secure from injection of third-party content. - * @param value The value to be tested for compatibility with declarative processing. If the value is a function it must be marked with a property supportedForProcessing with a value of true when strictProcessing is on. For more information, see WinJS.Utilities.markSupportedForProcessing. - * @returns The input value. - **/ - function requireSupportedForProcessing(value: T): T; - - /** - * Sets the innerHTML property of the specified element to the specified text. - * @param element The element on which the innerHTML property is to be set. - * @param text The value to be set to the innerHTML property. - **/ - function setInnerHTML(element: HTMLElement, text: string): void; - - /** - * Sets the innerHTML property of the specified element to the specified text. - * @param element The element on which the innerHTML property is to be set. - * @param text The value to be set to the innerHTML property. - **/ - function setInnerHTMLUnsafe(element: HTMLElement, text: string): void; - - /** - * Sets the outerHTML property of the specified element to the specified text. - * @param element The element on which the outerHTML property is to be set. - * @param text The value to be set to the outerHTML property. - **/ - function setOuterHTML(element: HTMLElement, text: string): void; - - /** - * Sets the outerHTML property of the specified element to the specified text in the context of MSApp.execUnsafeLocalFunction. - * @param element The element on which the outerHTML property is to be set. - * @param text The value to be set to the outerHTML property. - **/ - function setOuterHTMLUnsafe(element: HTMLElement, text: string): void; - - /** - * Configures a logger that writes messages containing the specified tags to the JavaScript console. - * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. - **/ + //#region Enumerations + + /** + * Defines a set of keyboard values. + **/ + enum Key { + /** + * The BACKSPACE key. + **/ + backspace, + /** + * The TAB key. + **/ + tab, + /** + * The ENTER key. + **/ + enter, + /** + * The SHIFT key. + **/ + shift, + /** + * The CTRL key. + **/ + ctrl, + /** + * The ALT key. + **/ + alt, + /** + * The PAUSE key. + **/ + pause, + /** + * The CAPS LOCK key. + **/ + capsLock, + /** + * The ESCAPE key. + **/ + escape, + /** + * The SPACE key. + **/ + space, + /** + * The PAGE UP key. + **/ + pageUp, + /** + * The PAGE DOWN key. + **/ + pageDown, + /** + * The END key. + **/ + end, + /** + * The HOME key. + **/ + home, + /** + * The LEFT ARROW key. + **/ + leftArrow, + /** + * The UP ARROW key. + **/ + upArrow, + /** + * The RIGHT ARROW key. + **/ + rightArrow, + /** + * The DOWN ARROW key. + **/ + downArrow, + /** + * The INSERT key. + **/ + insert, + /** + * The DELETE key. + **/ + deleteKey, + /** + * The 0 key. + **/ + num0, + /** + * The 1 key. + **/ + num1, + /** + * The 2 key. + **/ + num2, + /** + * The 3 key. + **/ + num3, + /** + * The 4 key. + **/ + num4, + /** + * The 5 key. + **/ + num5, + /** + * The 6 key. + **/ + num6, + /** + * The 7 key. + **/ + num7, + /** + * The 8 key. + **/ + num8, + /** + * The 9 key. + **/ + num9, + /** + * The a key. + **/ + a, + /** + * The b key. + **/ + b, + /** + * The c key. + **/ + c, + /** + * The d key. + **/ + d, + /** + * The e key. + **/ + e, + /** + * The f key. + **/ + f, + /** + * The g key. + **/ + g, + /** + * The h key. + **/ + h, + /** + * The i key. + **/ + i, + /** + * The j key. + **/ + j, + /** + * The k key. + **/ + k, + /** + * The l key. + **/ + l, + /** + * The m key. + **/ + m, + /** + * The n key. + **/ + n, + /** + * The o key. + **/ + o, + /** + * The p key. + **/ + p, + /** + * The q key. + **/ + q, + /** + * The r key. + **/ + r, + /** + * The s key. + **/ + s, + /** + * The t key. + **/ + t, + /** + * The u key. + **/ + u, + /** + * The v key. + **/ + v, + /** + * The w key. + **/ + w, + /** + * The x key. + **/ + x, + /** + * The y key. + **/ + y, + /** + * The z key. + **/ + z, + /** + * The left Windows key. + **/ + leftWindows, + /** + * The right Windows key. + **/ + rightWindows, + /** + * The menu key. + **/ + menu, + /** + * The 0 key on the numerical keypad. + **/ + numPad0, + /** + * The 1 key on the numerical keypad. + **/ + numPad1, + /** + * The 2 key on the numerical keypad. + **/ + numPad2, + /** + * The 3 key on the numerical keypad. + **/ + numPad3, + /** + * The 4 key on the numerical keypad. + **/ + numPad4, + /** + * The 5 key on the numerical keypad. + **/ + numPad5, + /** + * The 6 key on the numerical keypad. + **/ + numPad6, + /** + * The 7 key on the numerical keypad. + **/ + numPad7, + /** + * The 8 key on the numerical keypad. + **/ + numPad8, + /** + * The 9 key on the numerical keypad. + **/ + numPad9, + /** + * The multiplication key (*). + **/ + multiply, + /** + * The addition key (+). + **/ + add, + /** + * The subtraction key (-). + **/ + subtract, + /** + * The decimal point key (.) + **/ + decimalPoint, + /** + * The division key (/). + **/ + divide, + /** + * The F1 key. + **/ + F1, + /** + * The F2 key. + **/ + F2, + /** + * The F3 key. + **/ + F3, + /** + * The F4 key. + **/ + F4, + /** + * The F5 key. + **/ + F5, + /** + * The F6 key. + **/ + F6, + /** + * The F7 key. + **/ + F7, + /** + * The F8 key. + **/ + F8, + /** + * The F9 key. + **/ + F9, + /** + * The F10 key. + **/ + F10, + /** + * The F11 key. + **/ + F11, + /** + * The F12 key. + **/ + F12, + /** + * The NUMBER LOCK key. + **/ + numLock, + /** + * The SCROLL LOCK key. + **/ + scrollLock, + /** + * The browser BACK key. + **/ + browserBack, + /** + * The browser FORWARD key. + **/ + browserForward, + /** + * The semicolon key (;). + **/ + semicolon, + /** + * The equals key (=). + **/ + equal, + /** + * The comma key (,). + **/ + comma, + /** + * The dash key (-). + **/ + dash, + /** + * The period key (.). + **/ + period, + /** + * The forward slash key (/). + **/ + forwardSlash, + /** + * The grave accent key (`). + **/ + graveAccent, + /** + * The open bracket key ([). + **/ + openBracket, + /** + * The backslash key (\). + **/ + backSlash, + /** + * The close bracket key (]). + **/ + closeBracket, + /** + * The single quote key ('). + **/ + singleQuote + } + + //#endregion Enumerations + + //#region Objects + + /** + * A mixin that contains event-related functions. + **/ + var eventMixin: { + //#region Methods + + /** + * Adds an event listener to the control. + * @param type The type (name) of the event. + * @param listener The listener to invoke when the event gets raised. + * @param useCapture If true, initiates capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with the specified additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Removes an event listener from the control. + * @param type The type (name) of the event. + * @param listener The listener to remove. + * @param useCapture true if capture is to be initiated, otherwise false. + **/ + removeEventListener(type: string, listener: Function, useCapture?: boolean): void; + + //#endregion Methods + + }; + + /** + * Represents the result of a query selector, and provides various operations that perform actions over the elements of the collection. + **/ + interface QueryCollection extends Array { + //#region Methods + + /** + * Adds the specified class to all the elements in the collection. + * @param name The name of the class to add. + * @returns This QueryCollection object. + **/ + addClass(name: string): QueryCollection; + + /** + * Creates a QueryCollection that contains the children of the specified parent element. + * @param element The parent element. + * @returns The QueryCollection that contains the children of the element. + **/ + children(element: HTMLElement): QueryCollection; + + /** + * Clears the specified style property for all the elements in the collection. + * @param name The name of the style property to be cleared. + * @returns This QueryCollection object. + **/ + clearStyle(name: string): QueryCollection; + + /** + * Creates controls that are attached to the elements in this QueryCollection, if the ctor parameter is a function, or configures the controls that are attached to the elements in this QueryCollection, if the ctor parameter is an object. + * @param ctor If this parameter is a function, it is a constructor function that is used to create controls to attach to the elements. If it is an object, it is the set of options passed to the controls. + * @param options The options passed to the newly-created controls. + * @returns This QueryCollection object. + **/ + control(ctor: any, options?: any): QueryCollection; + + /** + * Performs an action on each item in the QueryCollection. + * @param callbackFn The action to perform on each item. + * @param thisArg The argument to bind to callbackFn. + * @returns The QueryCollection. + **/ + forEach(callbackFn: (value: T, index: number, array: T[]) => void, thisArg?: any): QueryCollection; + + /** + * Gets an item from the QueryCollection. + * @param index The index of the item to return. + * @returns A single item from the collection. + **/ + get(index: number): T; + + /** + * Gets an attribute value from the first element in the collection. + * @param name The name of the attribute. + * @returns The value of the attribute. + **/ + getAttribute(name: string): any; + + /** + * Determines whether the specified class exists on the first element of the collection. + * @param name The name of the class. + * @returns true if the element has the specified class; otherwise, false. + **/ + hasClass(name: string): boolean; + + /** + * Looks up an element by ID and wraps the result in a QueryCollection. + * @param id The ID of the element. + * @returns A QueryCollection that contains the element, if it is found. + **/ + id(id: string): QueryCollection; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T): void; + + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: T[]): void; + + /** + * Registers the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function to be called when the event occurs. + * @param capture true if capture == true is to be passed to addEventListener; otherwise, false. + **/ + listen(eventType: string, listener: Function, capture?: boolean): void; + + /** + * Executes a query selector on all the elements in the collection and aggregates the result into a QueryCollection. + * @param query The query selector string. + * @returns A QueryCollection object containing the aggregate results of executing the query on all the elements in the collection. + **/ + query(query: any): QueryCollection; + + /** + * Removes the specified class from all the elements in the collection. + * @param name The name of the class to be removed. + * @returns his QueryCollection object. + **/ + removeClass(name: string): QueryCollection; + + /** + * Unregisters the listener for the specified event on all the elements in the collection. + * @param eventType The name of the event. + * @param listener The event handler function. + * @param capture true if capture == true; otherwise, false. + * @returns This QueryCollection object. + **/ + removeEventListener(eventType: string, listener: Function, capture?: boolean): QueryCollection; + + /** + * Sets an attribute value on all the items in the collection. + * @param name The name of the attribute to be set. + * @param value The value of the attribute to be set. + * @returns This QueryCollection object. + **/ + setAttribute(name: string, value: any): QueryCollection; + + /** + * Sets the specified style property for all the elements in the collection. + * @param name The name of the style property. + * @param value The value for the property. + * @returns This QueryCollection object. + **/ + setStyle(name: string, value: any): QueryCollection; + + /** + * Renders a template that is bound to the given data and parented to the elements included in the QueryCollection. If the QueryCollection contains multiple elements, the template is rendered multiple times, once at each element in the QueryCollection per item of data passed. + * @param templateElement The DOM element to which the template control is attached. + * @param data The data to render. If the data is an array (or any other object that has a forEach method) then the template is rendered multiple times, once for each item in the collection. + * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. + * @returns The QueryCollection. + **/ + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + + /** + * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. + * @param name The name of the class to be toggled. + * @returns This QueryCollection object. + **/ + toggleClass(name: string): QueryCollection; + + //#endregion Methods + + } + + /** + * Constructor support for QueryCollection interface + **/ + export var QueryCollection: { + new (items: T[]): QueryCollection; + prototype: QueryCollection; + } + + //#endregion Objects + + //#region Functions + + /** + * Adds the specified class to the specified element. + * @param e The element to which to add the class. + * @param name The name of the class to add. + * @returns The element. + **/ + function addClass(e: T, name: string): T; + + /** + * Gets a collection of elements that are the direct children of the specified element. + * @param element The parent element. + * @returns The collection of children of the element. + **/ + function children(element: HTMLElement): QueryCollection; + + /** + * Converts a CSS positioning string for the specified element to pixels. + * @param element The element. + * @param value The CSS positioning string. + * @returns The number of pixels. + **/ + function convertToPixels(element: HTMLElement, value: string): number; + + /** + * Creates an object that has one event for each name passed to the function. + * @param events A variable list of property names. + * @returns The object with the specified properties. The names of the properties are prefixed with 'on'. + **/ + function createEventProperties(...events: string[]): any; + + /** + * Gets the data value associated with the specified element. + * @param element The element. + * @returns The value associated with the element. + **/ + function data(element: HTMLElement): any; + + /** + * Disposes all first-generation disposable elements that are descendents of the specified element. The specified element itself is not disposed. + * @param element The root element whose sub-tree is to be disposed. + **/ + function disposeSubTree(element: HTMLElement): void; + + /** + * Removes all the child nodes from the specified element. + * @param element The element. + * @returns The element. + **/ + function empty(element: T): T; + + /** + * Determines whether the specified event occurred within the specified element. + * @param element The element. + * @param event The event. + * @returns true if the event occurred within the element; otherwise, false. + **/ + function eventWithinElement(element: HTMLElement, event: Event): boolean; + + /** + * Adds tags and type to a logging message. + * @param message The message to be formatted. + * @param tag The tag(s) to be applied to the message. Multiple tags should be separated by spaces. + * @param type The type of the message. + * @returns The formatted message. + **/ + function formatLog(message: string, tag: string, type: string): string; + + /** + * Gets the height of the content of the specified element. The content height does not include borders or padding. + * @param element The element. + * @returns The content height of the element. + **/ + function getContentHeight(element: HTMLElement): number; + + /** + * Gets the width of the content of the specified element. The content width does not include borders or padding. + * @param element The element. + * @returns The content width of the element. + **/ + function getContentWidth(element: HTMLElement): number; + + /** + * Gets the leaf-level type or namespace specified by the name parameter. + * @param name The name of the member. + * @param root The root to start in. Defaults to the global object. + * @returns The leaf-level type or namespace in the specified parent namespace. + **/ + function getMember(name: string, root?: any): any; + + /** + * Gets the position of the specified element. + * @param element The element. + * @returns An object that contains the left, top, width and height properties of the element. + **/ + function getPosition(element: HTMLElement): IPosition; + + /** + * Gets the left coordinate of the specified element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative left coordinate. + **/ + function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the top coordinate of the element relative to the specified parent. + * @param element The element. + * @param parent The parent element. + * @returns The relative top coordinate. + **/ + function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + + /** + * Gets the height of the element, including its margins. + * @param element The element. + * @returns The height of the element including margins. + **/ + function getTotalHeight(element: HTMLElement): number; + + /** + * Gets the width of the element, including margins. + * @param element The element. + * @returns The width of the element including margins. + **/ + function getTotalWidth(element: HTMLElement): number; + + /** + * Determines whether the specified element has the specified class. + * @param e The element. + * @param name The name of the class. + * @returns true if the element has the class, otherwise false. + **/ + function hasClass(e: HTMLElement, name: string): boolean; + + /** + * Returns a collection with zero or one elements matching the specified id. + * @param id The ID of the element (or elements). + * @returns A collection of elements whose id matches the id parameter. + **/ + function id(id: string): QueryCollection; + + /** + * Calls insertAdjacentHTML on the specified element. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text The text to insert. + **/ + function insertAdjacentHTML(element: HTMLElement, position: string, text: string): void; + + /** + * Calls insertAdjacentHTML on the specified element in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which insertAdjacentHTML is to be called. + * @param position The position relative to the element at which to insert the HTML. Possible values are: beforebegin, afterbegin, beforeend, afterend. + * @param text Value to be provided to insertAdjacentHTML. + **/ + function insertAdjacentHTMLUnsafe(element: HTMLElement, position: string, text: string): void; + + /** + * Attaches the default dispose API wrapping the dispose implementation to the specified element. + * @param element The element to mark as disposable. + * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. + **/ + function markDisposable(element: HTMLElement, disposeImpl: Function): void; + + /** + * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. + * @param func The function to be marked as compatible with declarative processing. + * @returns The input function, marked as compatible with declarative processing. + **/ + function markSupportedForProcessing(func: U): U; + + /** + * Returns a QueryCollection with zero or one elements matching the specified selector query. + * @param query The CSS selector to use. See Selectors for more information. + * @param element Optional. The root element at which to start the query. If this parameter is omitted, the scope of the query is the entire document. + * @returns A QueryCollection with zero or one elements matching the specified selector query. + **/ + function query(query: any, element?: HTMLElement): QueryCollection; + + /** + * Ensures that the specified function executes only after the DOMContentLoaded event has fired for the current page. The DOMContentLoaded event occurs after the page has been parsed but before all the resources are loaded. + * @param callback A function that executes after the DOMContentLoaded event has occurred. + * @param async If true, the callback should be executed asynchronously. + * @returns A promise that completes after the DOMContentLoaded event has occurred. + **/ + function ready(callback?: Function, async?: boolean): Promise; + + /** + * Removes the specified class from the specified element. + * @param e The element from which to remove the class. + * @param name The name of the class to remove. + * @returns The element. + **/ + function removeClass(e: T, name: string): T; + + /** + * Asserts that the value is compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. If the value is not compatible, and strictProcessing is on, an exception is thrown. All functions that have been declared using WinJS.Class.define, WinJS.Class.derive, WinJS.UI.Pages.define, or WinJS.Binding.converter are automatically marked as supported for declarative processing. Any other function that you use from a declarative context (that is, a context in which an HTML element has a data-win-control or data-win-options attribute) must be marked manually by calling this function. When you mark a function as supported for declarative processing, you are guaranteeing that the code in the function is secure from injection of third-party content. + * @param value The value to be tested for compatibility with declarative processing. If the value is a function it must be marked with a property supportedForProcessing with a value of true when strictProcessing is on. For more information, see WinJS.Utilities.markSupportedForProcessing. + * @returns The input value. + **/ + function requireSupportedForProcessing(value: T): T; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTML(element: HTMLElement, text: string): void; + + /** + * Sets the innerHTML property of the specified element to the specified text. + * @param element The element on which the innerHTML property is to be set. + * @param text The value to be set to the innerHTML property. + **/ + function setInnerHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTML(element: HTMLElement, text: string): void; + + /** + * Sets the outerHTML property of the specified element to the specified text in the context of MSApp.execUnsafeLocalFunction. + * @param element The element on which the outerHTML property is to be set. + * @param text The value to be set to the outerHTML property. + **/ + function setOuterHTMLUnsafe(element: HTMLElement, text: string): void; + + /** + * Configures a logger that writes messages containing the specified tags to the JavaScript console. + * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. + **/ function startLog(options?: ILogOptions): void; - /** - * Removes the WinJS logger that had previously been set up. - **/ - function stopLog(): void; + /** + * Removes the WinJS logger that had previously been set up. + **/ + function stopLog(): void; - /** - * Toggles (adds or removes) the specified class on the specified element. If the class is present, it is removed; if it is absent, it is added. - * @param e The element on which to toggle the class. - * @param name The name of the class to toggle. - * @returns The element. - **/ - function toggleClass(e: T, name: string): T; + /** + * Toggles (adds or removes) the specified class on the specified element. If the class is present, it is removed; if it is absent, it is added. + * @param e The element on which to toggle the class. + * @param name The name of the class to toggle. + * @returns The element. + **/ + function toggleClass(e: T, name: string): T; - //#endregion Functions + //#endregion Functions //#region Properties @@ -8387,9 +8314,14 @@ declare module WinJS.Utilities { **/ var hasWinRT: boolean; + /** + * Indicates whether the app is running on Windows Phone. + **/ + var isPhone: boolean; + //#endregion Properties - //#region Interfaces + //#region Interfaces interface ILogOptions { type: string; @@ -8398,246 +8330,246 @@ declare module WinJS.Utilities { tags: string; } - interface IPosition { - left: number; - top: number; - width: number; - height: number; - } + interface IPosition { + left: number; + top: number; + width: number; + height: number; + } - //#endregion Interfaces + //#endregion Interfaces } /** * Provides functions and objects for scheduling and managing asynchronous tasks. **/ declare module WinJS.Utilities.Scheduler { - //#region Enumerations + //#region Enumerations - /** - * Represents a priority for a job managed by the Scheduler. - **/ - enum Priority { - /** - * A priority higher than the normal priority level. - **/ - aboveNormal, - /** - * A priority less than the normal priority level. - **/ - belowNormal, - /** - * A high priority. - **/ - high, - /** - * The idle priority for work items. - **/ - idle, - /** - * The highest priority. - **/ - max, - /** - * The lowest priority. - **/ - min, - /** - * The normal priority for work items. - **/ - normal - } + /** + * Represents a priority for a job managed by the Scheduler. + **/ + enum Priority { + /** + * A priority higher than the normal priority level. + **/ + aboveNormal, + /** + * A priority less than the normal priority level. + **/ + belowNormal, + /** + * A high priority. + **/ + high, + /** + * The idle priority for work items. + **/ + idle, + /** + * The highest priority. + **/ + max, + /** + * The lowest priority. + **/ + min, + /** + * The normal priority for work items. + **/ + normal + } - //#endregion Enumerations + //#endregion Enumerations - //#region Interfaces + //#region Interfaces - /** - * Represents a work item that's executed by the Scheduler. - **/ - interface IJob { - //#region Methods + /** + * Represents a work item that's executed by the Scheduler. + **/ + interface IJob { + //#region Methods - /** - * Cancels the job. - **/ - cancel(): void; + /** + * Cancels the job. + **/ + cancel(): void; - /** - * Pauses the job. - **/ - pause(): void; + /** + * Pauses the job. + **/ + pause(): void; - /** - * Resumes the job. - **/ - resume(): void; + /** + * Resumes the job. + **/ + resume(): void; - //#endregion Methods + //#endregion Methods - //#region Properties + //#region Properties - /** - * Gets a value that indicates whether the job has successfully completed. - **/ - completed: boolean; + /** + * Gets a value that indicates whether the job has successfully completed. + **/ + completed: boolean; - /** - * Gets the unique numeric identifier assigned to the job. - **/ - id: number; + /** + * Gets the unique numeric identifier assigned to the job. + **/ + id: number; - /** - * Gets or sets the name of the job. - **/ - name: string; + /** + * Gets or sets the name of the job. + **/ + name: string; - /** - * Gets or sets the owner of the job. - **/ - owner: IOwnerToken; + /** + * Gets or sets the owner of the job. + **/ + owner: IOwnerToken; - /** - * Gets or sets the priority of the job. - **/ - priority: Priority; + /** + * Gets or sets the priority of the job. + **/ + priority: Priority; - //#endregion Properties + //#endregion Properties - } + } - /** - * Provides a control mechanism that allows a job to cooperatively yield. This object is passed to your work function when you schedule it. - **/ - interface IJobInfo { - //#region Methods + /** + * Provides a control mechanism that allows a job to cooperatively yield. This object is passed to your work function when you schedule it. + **/ + interface IJobInfo { + //#region Methods - /** - * Uses a Promise to determine how long the scheduler should wait before rescheduling the job after it yields. - * @param promise Once the work item yields, the scheduler will wait for this Promise to complete before rescheduling the job. - **/ - setPromise(promise: Promise): void; + /** + * Uses a Promise to determine how long the scheduler should wait before rescheduling the job after it yields. + * @param promise Once the work item yields, the scheduler will wait for this Promise to complete before rescheduling the job. + **/ + setPromise(promise: Promise): void; - /** - * Specifies the next unit of work to run once this job yields. - * @param work The next unit of work to run once this job yields. - **/ - setWork(work: Function): void; + /** + * Specifies the next unit of work to run once this job yields. + * @param work The next unit of work to run once this job yields. + **/ + setWork(work: Function): void; - //#endregion Methods + //#endregion Methods - //#region Properties + //#region Properties - /** - * Gets the work item associated with this IJobInfo. - **/ - job: IJob; + /** + * Gets the work item associated with this IJobInfo. + **/ + job: IJob; - /** - * Gets a value that specifies whether the job should yield. - **/ - shouldYield: boolean; + /** + * Gets a value that specifies whether the job should yield. + **/ + shouldYield: boolean; - //#endregion Properties + //#endregion Properties - } + } - /** - * Represents an object that owns jobs. You can use this object to cancel a set of jobs. - **/ - interface IOwnerToken { - //#region Methods + /** + * Represents an object that owns jobs. You can use this object to cancel a set of jobs. + **/ + interface IOwnerToken { + //#region Methods - /** - * Synchronously cancels the job that this token owns, including paused and blocked jobs. - **/ - cancelAll(): void; + /** + * Synchronously cancels the job that this token owns, including paused and blocked jobs. + **/ + cancelAll(): void; - //#endregion Methods + //#endregion Methods - } + } - //#endregion Interfaces + //#endregion Interfaces - //#region Functions + //#region Functions - /** - * Creates and returns a new IOwnerToken which can be set to the owner property of one or more jobs. - * @returns A new IOwnerToken which can be set to the owner property of one or more jobs. - **/ - function createOwnerToken(): IOwnerToken; + /** + * Creates and returns a new IOwnerToken which can be set to the owner property of one or more jobs. + * @returns A new IOwnerToken which can be set to the owner property of one or more jobs. + **/ + function createOwnerToken(): IOwnerToken; - /** - * Runs the specified callback in a high priority context. - * @param callback The callback to run in a high priority callback. - * @returns The return value of the callback. - **/ - function execHigh(callback: () => U): U; + /** + * Runs the specified callback in a high priority context. + * @param callback The callback to run in a high priority callback. + * @returns The return value of the callback. + **/ + function execHigh(callback: () => U): U; - /** - * Returns a string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. - * @returns A string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. - **/ - function retrieveState(): string; + /** + * Returns a string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. + * @returns A string representation of the scheduler's state for diagnostic purposes. The jobs and drain requests are displayed in the order in which they are currently expected to be processed. The current job and drain request are marked by an asterisk. + **/ + function retrieveState(): string; - /** - * Runs jobs in the scheduler without timeslicing until all jobs at the specified priority and higher have executed. - * @param priority The priority to which the scheduler should drain. The default is -15. - * @param name An optional description of the drain request for diagnostics. - * @returns A Promise which completes when the drain has finished. Canceling this Promise cancels the drain request. This Promise will never enter an error state. - **/ - function requestDrain(priority?: Priority, name?: string): Promise; + /** + * Runs jobs in the scheduler without timeslicing until all jobs at the specified priority and higher have executed. + * @param priority The priority to which the scheduler should drain. The default is -15. + * @param name An optional description of the drain request for diagnostics. + * @returns A Promise which completes when the drain has finished. Canceling this Promise cancels the drain request. This Promise will never enter an error state. + **/ + function requestDrain(priority?: Priority, name?: string): Promise; - /** - * Schedules the specified function to execute asynchronously. - * @param work A function that represents the work item to be scheduled. When called the work item will receive as its first argument an object which allows the work item to ask the scheduler if it should yield cooperatively and if so allows the work item to either provide a function to be run as a continuation or a WinJS.Promise which will when complete provide a function to run as a continuation. Provide these fields for the object: shouldYield, setWork(work), setPromise(promise), job. - * @param priority The priority of the work item. If you don't specify a priority, it defaults to WinJS.Utilities.Scheduler.Priority.normal. - * @param thisArg A "this" instance to be bound to the work item. The default value is null. - * @param name A description of the work item for diagnostics. The default value is an empty string. - * @returns The job instance that represents this work item. - **/ - function schedule(work: (jobInfo: IJobInfo) => any, priority?: Priority, thisArg?: any, name?: string): IJob; + /** + * Schedules the specified function to execute asynchronously. + * @param work A function that represents the work item to be scheduled. When called the work item will receive as its first argument an object which allows the work item to ask the scheduler if it should yield cooperatively and if so allows the work item to either provide a function to be run as a continuation or a WinJS.Promise which will when complete provide a function to run as a continuation. Provide these fields for the object: shouldYield, setWork(work), setPromise(promise), job. + * @param priority The priority of the work item. If you don't specify a priority, it defaults to WinJS.Utilities.Scheduler.Priority.normal. + * @param thisArg A "this" instance to be bound to the work item. The default value is null. + * @param name A description of the work item for diagnostics. The default value is an empty string. + * @returns The job instance that represents this work item. + **/ + function schedule(work: (jobInfo: IJobInfo) => any, priority?: Priority, thisArg?: any, name?: string): IJob; - /** - * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.aboveNormal priority. - * @param promiseValue The value returned by the completed Promise. - * @param jobName A string that describes the job for diagnostic purposes. - * @returns A Promise that completes within a job of aboveNormal priority. - **/ - function schedulePromiseAboveNormal(promiseValue?: U, jobName?: string): Promise; + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.aboveNormal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of aboveNormal priority. + **/ + function schedulePromiseAboveNormal(promiseValue?: U, jobName?: string): Promise; - /** - * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.belowNormal priority. - * @param promiseValue The value returned by the completed Promise. - * @param jobName A string that describes the job for diagnostic purposes. - * @returns A Promise that completes within a job of belowNormal priority. - **/ - function schedulePromiseBelowNormal(promiseValue?: U, jobName?: string): Promise; + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.belowNormal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of belowNormal priority. + **/ + function schedulePromiseBelowNormal(promiseValue?: U, jobName?: string): Promise; - /** - * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.high priority. - * @param promiseValue The value returned by the completed Promise. - * @param jobName A string that describes the job for diagnostic purposes. - * @returns A Promise that completes within a job of high priority. - **/ - function schedulePromiseHigh(promiseValue?: U, jobName?: string): Promise; + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.high priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of high priority. + **/ + function schedulePromiseHigh(promiseValue?: U, jobName?: string): Promise; - /** - * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.Idle priority. - * @param promiseValue The value returned by the completed Promise. - * @param jobName A string that describes the job for diagnostic purposes. - * @returns A Promise that completes within a job of idle priority. - **/ - function schedulePromiseIdle(promiseValue?: U, jobName?: string): Promise; + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.Idle priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of idle priority. + **/ + function schedulePromiseIdle(promiseValue?: U, jobName?: string): Promise; - /** - * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.normal priority. - * @param promiseValue The value returned by the completed Promise. - * @param jobName A string that describes the job for diagnostic purposes. - * @returns A Promise that completes within a job of normal priority. - **/ - function schedulePromiseNormal(promiseValue?: U, jobName?: string): Promise; + /** + * Schedules a job to complete the returned Promise at WinJS.Utilities.Scheduler.Priority.normal priority. + * @param promiseValue The value returned by the completed Promise. + * @param jobName A string that describes the job for diagnostic purposes. + * @returns A Promise that completes within a job of normal priority. + **/ + function schedulePromiseNormal(promiseValue?: U, jobName?: string): Promise; - //#endregion Functions + //#endregion Functions } diff --git a/winston/winston-tests.ts b/winston/winston-tests.ts new file mode 100644 index 0000000000..499b427a62 --- /dev/null +++ b/winston/winston-tests.ts @@ -0,0 +1,40 @@ +/// + +import winston = require('winston'); + +var str: string; +var bool: boolean; +var metadata: any; +var options: any; +var value: any; +var transport: winston.Transport; + +transport = winston.transports.File; +transport = winston.transports.Console; +transport = winston.transports.Loggly; + +winston.log(str, str); +winston.log(str, str, metadata); +winston.debug(str); +winston.debug(str, metadata); +winston.info(str); +winston.info(str, metadata); +winston.warn(str); +winston.warn(str, metadata); +winston.error(str); +winston.error(str, metadata); + +winston.add(transport, options); +winston.remove(transport); + +winston.profile(str); + +winston.query(options, (err: any, results: any) => { + +}); + +value = winston.stream(options); + +winston.handleExceptions(transport); +winston.exitOnError = bool; + diff --git a/winston/winston.d.ts b/winston/winston.d.ts new file mode 100644 index 0000000000..8ebd618ff6 --- /dev/null +++ b/winston/winston.d.ts @@ -0,0 +1,39 @@ +// Type definitions for winston +// Project: https://github.com/flatiron/winston +// Definitions by: bonnici +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/winston.d.ts + +declare module "winston" { + export function log(level: string, message: string, metadata?: any): void; + export function debug(message: string, metadata?: any): void; + export function info(message: string, metadata?: any): void; + export function warn(message: string, metadata?: any): void; + export function error(message: string, metadata?: any): void; + + export function add(transport: Transport, options: any): void; + export function remove(transport: Transport): void; + + export function profile(name: string): void; + + export function query(options: any, done: (err: any, results: any) => void): void; + + export function stream(options: any): any; + + export function handleExceptions(transport: Transport): void; + + export class Logger { + + } + + export interface Transport { + } + export interface Transports { + File: Transport; + Console: Transport; + Loggly: Transport; + } + export var transports: Transports; + export var exitOnError: boolean; +} diff --git a/wrench/wrench-tests.ts b/wrench/wrench-tests.ts new file mode 100644 index 0000000000..c75a4ddb00 --- /dev/null +++ b/wrench/wrench-tests.ts @@ -0,0 +1,36 @@ +/// + +import wrench = require('wrench'); + +var str: string; +var num: number; +var bool: boolean; +var strArr: string[]; +var line: wrench.LineReader; + +strArr = wrench.readdirSyncRecursive(str); +wrench.rmdirSyncRecursive(str); +wrench.rmdirSyncRecursive(str, bool); +wrench.copyDirSyncRecursive(str, str); +wrench.copyDirSyncRecursive(str, str, { + preserve: bool +}); +wrench.chmodSyncRecursive(str, num); +wrench.chownSyncRecursive(str, num, num); +wrench.mkdirSyncRecursivefunction(str, num); +wrench.readdirRecursive(str, (err: Error, files: string[]) => { + +}); +wrench.rmdirRecursive(str, (err: Error) => { + +}); +wrench.copyDirRecursive(str, str, (err: Error) => { + +}); + +line = new wrench.LineReader(str); +line = new wrench.LineReader(str, num); + +str = line.getNextLine(); +bool = line.hasNextLine(); +num = line.getBufferAndSetCurrentPosition(num); diff --git a/wrench/wrench.d.ts b/wrench/wrench.d.ts new file mode 100644 index 0000000000..d3c03fc774 --- /dev/null +++ b/wrench/wrench.d.ts @@ -0,0 +1,27 @@ +// Type definitions for wrench +// Project: https://github.com/ryanmcgrath/wrench-js +// Definitions by: Carlos Ballesteros Velasco +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/wrench.d.ts + +declare module "wrench" { + export function readdirSyncRecursive(baseDir: string): string[]; + export function rmdirSyncRecursive(path: string, failSilent?: boolean): void; + export function copyDirSyncRecursive(sourceDir: string, newDirLocation: string, opts?: { preserve?: boolean; }): void; + export function chmodSyncRecursive(sourceDir: string, filemode: number): void; + export function chownSyncRecursive(sourceDir: string, uid: number, gid: number): void; + export function mkdirSyncRecursivefunction(path: string, mode: number): void; + + export function readdirRecursive(baseDir: string, fn: (err: Error, files: string[]) => void): void; + export function rmdirRecursive(path: string, fn: (err: Error) => void): void; + export function copyDirRecursive(srcDir: string, newDir: string, fn: (err: Error) => void): void; + + export class LineReader { + constructor (filename: string, bufferSize?: number); + + getBufferAndSetCurrentPosition(position: number): number; + hasNextLine(): boolean; + getNextLine(): string; + } +} diff --git a/ws/ws.d.ts b/ws/ws.d.ts index 2a3dbae405..d12e2913f3 100644 --- a/ws/ws.d.ts +++ b/ws/ws.d.ts @@ -60,28 +60,29 @@ declare module "ws" { terminate(): void; // HTML5 WebSocket events - addEventListener(method: string, listener?: () => void): void; addEventListener(method: 'message', cb?: (event: {data: any; type: string; target: WebSocket}) => void): void; addEventListener(method: 'close', cb?: (event: {wasClean: boolean; code: number; reason: string; target: WebSocket}) => void): void; addEventListener(method: 'error', cb?: (err: Error) => void): void; addEventListener(method: 'open', cb?: (event: {target: WebSocket}) => void): void; + addEventListener(method: string, listener?: () => void): void; // Events - on(event: string, listener: () => void): WebSocket; on(event: 'error', cb: (err: Error) => void): WebSocket; on(event: 'close', cb: (code: number, message: string) => void): WebSocket; on(event: 'message', cb: (data: any, flags: {binary: boolean}) => void): WebSocket; on(event: 'ping', cb: (data: any, flags: {binary: boolean}) => void): WebSocket; on(event: 'pong', cb: (data: any, flags: {binary: boolean}) => void): WebSocket; on(event: 'open', cb: () => void): WebSocket; - addListener(event: string, listener: () => void): WebSocket; + on(event: string, listener: () => void): WebSocket; + addListener(event: 'error', cb: (err: Error) => void): WebSocket; addListener(event: 'close', cb: (code: number, message: string) => void): WebSocket; addListener(event: 'message', cb: (data: any, flags: {binary: boolean}) => void): WebSocket; addListener(event: 'ping', cb: (data: any, flags: {binary: boolean}) => void): WebSocket; addListener(event: 'pong', cb: (data: any, flags: {binary: boolean}) => void): WebSocket; addListener(event: 'open', cb: () => void): WebSocket; + addListener(event: string, listener: () => void): WebSocket; } module WebSocket { @@ -90,8 +91,8 @@ declare module "ws" { port?: number; server?: http.Server; verifyClient?: { - (info: {origin: string; secure: boolean; req: http.ClientRequest}): boolean; - (info: {origin: string; secure: boolean; req: http.ClientRequest}, + (info: {origin: string; secure: boolean; req: http.ServerRequest}): boolean; + (info: {origin: string; secure: boolean; req: http.ServerRequest}, callback: (res: boolean) => void): void; }; handleProtocols?: any; @@ -109,18 +110,19 @@ declare module "ws" { constructor(options?: IServerOptions, callback?: Function); close(): void; - handleUpgrade(request: http.ClientRequest, socket: net.Socket, - upgradeHead: NodeBuffer, callback: (client: WebSocket) => void): void; + handleUpgrade(request: http.ServerRequest, socket: net.Socket, + upgradeHead: Buffer, callback: (client: WebSocket) => void): void; // Events - on(event: string, listener: () => void): Server; on(event: 'error', cb: (err: Error) => void): Server; on(event: 'headers', cb: (headers: string[]) => void): Server; on(event: 'connection', cb: (client: WebSocket) => void): Server; - addListener(event: string, listener: () => void): Server; + on(event: string, listener: () => void): Server; + addListener(event: 'error', cb: (err: Error) => void): Server; addListener(event: 'headers', cb: (headers: string[]) => void): Server; addListener(event: 'connection', cb: (client: WebSocket) => void): Server; + addListener(event: string, listener: () => void): Server; } export function createServer(options?: IServerOptions, diff --git a/x2js/xml2json-tests.ts b/x2js/xml2json-tests.ts new file mode 100644 index 0000000000..d5a8568e8a --- /dev/null +++ b/x2js/xml2json-tests.ts @@ -0,0 +1,300 @@ +/// + +// Create x2js instance with default config +var x2js = new X2JS(); + +// JSON to DOM +var xmlDoc = x2js.json2xml( + { + MyRoot: { + MyChild: 'my_child_value', + MyAnotherChild: 10, + MyArray: [ 'test', 'test2' ], + MyArrayRecords: [ + { + ttt: 'vvvv' + }, + { + ttt: 'vvvv2' + } + ] + } + } +); + + +// JSON to XML string +var xmlDocStr = x2js.json2xml_str( + { + MyRoot: { + MyChild: 'my_child_value', + MyAnotherChild: 10, + MyArray: [ 'test', 'test2' ], + MyArrayRecords: [ + { + ttt: 'vvvv' + }, + { + ttt: 'vvvv2' + } + ] + } + } +); + +console.log(xmlDocStr); + +// JSON arrays to string +var xmlDocStr = x2js.json2xml_str( + { + MyRoot: { + namedItemArray: { + item: [ + { first: 'success1' } , + { first: 'success2' } + ] + }, + namedArray: [ + { first: 'success1' } , + { first: 'success2' } + ], + justArray: [ 'just success1', 'just success2' ], + arrayWithAttrs: [ + { + _test: 'successAttr', + __text: 'success', + temp: 'successTemp' + }, + { + _test: 'successAttr2', + __text: 'success2', + temp: 'successTemp2' + } + ] + } + } +); + +console.log(xmlDocStr); + +// XML string to JSON +var xmlText = "Successddsfgdsdgfdgfd"; +var jsonObj = x2js.xml_str2json(xmlText); +console.log(jsonObj.MyOperation.test); + +// Array access form examples +console.log(x2js.asArray(jsonObj.MyOperation.test)[0]); +// Or old style (1.0.+): +var x2jsOld = new X2JS({arrayAccessForm: "property"}); +jsonObj = x2jsOld.xml_str2json(xmlText); +console.log("Old is " + jsonObj.MyOperation.test_asArray[0]); + +// XML/DOM to JSON +var xmlText = " - Success - TestText ddsfg TestText2 dsdgfdgfd" +xmlDoc = x2js.parseXmlString(xmlText); + +var jsonObj = x2js.xml2json(xmlDoc); +console.log(jsonObj.MyOperation.test); + +// Parsing XML attrs +var xmlText = "SUCCESS TXTSuccessddsfgdsdgfdgfd"; +var jsonObj = x2js.xml_str2json(xmlText); +console.log(jsonObj.MyOperation._myAttr); +console.log(jsonObj.MyOperation.test2._myAttr); +console.log(jsonObj.MyOperation.txtAttrChild._sAttr); +console.log(jsonObj.MyOperation.txtAttrChild.__text); +console.log(jsonObj.MyOperation.txtAttrChild.toString()); + +// JSON to XML attrs +var xmlDocStr = x2js.json2xml_str( + { + TestAttrRoot: { + _myAttr: 'myAttrValue', + MyChild: 'my_child_value', + MyAnotherChild: 10, + MyTextAttrChild: { + _myTextAttr: 'myTextAttrValue', + __text: 'HelloText' + } + } + } +); + +console.log(xmlDocStr); + +//Change prefix for attributes +var x2jsChangedAttrs = new X2JS({ + // XML attributes. Default is "_" + attributePrefix: "$" +}); +jsonObj = x2jsChangedAttrs.xml_str2json(xmlText); +console.log(jsonObj.MyOperation.$myAttr); +console.log(jsonObj.MyOperation.test2.$myAttr); +console.log(jsonObj.MyOperation.txtAttrChild.$sAttr); + +xmlDocStr = x2jsChangedAttrs.json2xml_str({ + TestAttrRoot: { + _myAttr: 'myAttrValue', + MyChild: 'my_child_value', + MyAnotherChild: 10, + MyTextAttrChild: { + $myTextAttr: 'myTextAttrValue', + __text: 'HelloText' + } + } + } +); + +console.log(xmlDocStr); + + +// Parse XML with namespaces +var xmlText = "SuccessddsfgdsdgfdgfdtestArrSize"; +var jsonObj = x2js.xml_str2json(xmlText); +console.log(jsonObj.MyOperation.test); +if (jsonObj.MyOperation.test2.item.length > 2) + console.log("Error! Incorrect array len!"); + +var testObjC = { + 'm:TestAttrRoot': { + '_tns:m': 'http://www.example.org', + '_tns:cms': 'http://www.example.org', + MyChild: 'my_child_value', + 'cms:MyAnotherChild': 'vdfd' + } +} + +// Parse JSON object with namespaces +var xmlDocStr = x2js.json2xml_str( + testObjC +); + +console.log(xmlDocStr); + +// Parse JSON object constructed with another NS-style +var testObjNew = { + TestAttrRoot: { + __prefix: 'm', + '_tns:m': 'http://www.example.org', + '_tns:cms': 'http://www.example.org', + MyChild: 'my_child_value', + MyAnotherChild: { + __prefix: 'cms', + __text: 'vdfd' + } + } +} + +// Parse JSON object with namespaces +var xmlDocStr = x2js.json2xml_str( + testObjNew +); + +console.log(xmlDocStr); + +// Parse XML with header +var xmlText = "\n" + + "XML HEADER SUCCESS!"; + +var jsonObj = x2js.xml_str2json(xmlText); +console.log(jsonObj.test); + +// Parse XML with CDATA +var xmlText = "simple success]]> "; + +var jsonObj = x2js.xml_str2json(xmlText); +console.log(jsonObj.test.data.toString()); +console.log(jsonObj.test.data.__cdata); +console.log(jsonObj.test.simple); + + +// Parse JSON object with CDATA +var xmlDocStr = x2js.json2xml_str( + jsonObj +); +console.log(xmlDocStr); + +// Parse JSON with emtpy attributes +var xmlDocStr = x2js.json2xml_str( + { + MyRoot: { + MyNullChild: null, + MyNullChild2: undefined, + MyAnotherChild: 10, + MyEmptyChild: { + _attr: "test" + }, + MyEmptyChild2: { + _attr: "test", + __text: "Empty Nodes Test" + } + } + } +); + +console.log(xmlDocStr); + +// Escaping XML characters +xmlDocStr = x2js.json2xml_str( + { + MyRoot: { + MyEscapeXmlChild: " & \" ' / ", + MyEscapeXmlChild2: { + _attr: "success", + __text: " & \" ' / " + }, + MyEscapeXmlChildNonString: false + } + } +); + +console.log(xmlDocStr); + +jsonObj = x2js.xml_str2json(xmlDocStr); +console.log(jsonObj.MyRoot.MyEscapeXmlChild); +console.log(jsonObj.MyRoot.MyEscapeXmlChild2.toString()); + +console.log(x2js.getVersion()); + +// Array access path demos +x2js = new X2JS({ + arrayAccessFormPaths: [ + "MyArrays.test4.item", + /.*\.test3\.item/ + ] +}); + +xmlText = "" + + "successsecond" + + "success" + + "success" + + "success" + + ""; + + +jsonObj = x2js.xml_str2json(xmlText); +console.log(jsonObj.MyArrays.test3.item[0]); +console.log(jsonObj.MyArrays.test4.item[0]); +console.log(jsonObj.MyArrays.test5.item); + +// Working with datetimes +x2js = new X2JS({ + datetimeAccessFormPaths: [ + "MyDts.testds", + /.*\.testdt.*/ + ] +}); + +xmlText = "" + + "2002-10-10T12:00:00+04:00" + + "2002-10-10T12:00:00Z" + + "2002-10-10T12:00:00" + + "2002-10-10T12:00:00Z" + + ""; +jsonObj = x2js.xml_str2json(xmlText); + +console.log(jsonObj.MyDts.testds); +console.log(jsonObj.MyDts.testdt1); +console.log(jsonObj.MyDts.testdt2); +console.log(x2js.asDateTime(jsonObj.MyDts.testdc)); + diff --git a/x2js/xml2json.d.ts b/x2js/xml2json.d.ts new file mode 100644 index 0000000000..1b55262f25 --- /dev/null +++ b/x2js/xml2json.d.ts @@ -0,0 +1,36 @@ +// Type definitions for x2js +// Project: https://code.google.com/p/x2js/ +// Definitions by: Horiuchi_H +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface IX2JS { + new (config?: IX2JSOption): IX2JS; + + getVersion(): string; + + xml2json(dom: Node): T; + json2xml(json: T): Node; + xml_str2json(xml: string): T; + json2xml_str(json: T): string; + parseXmlString(xml: string): Node; + + asArray(prop: any): any[]; + asDateTime(key: string): string; + asXmlDateTime(date: Date): string; + asXmlDateTime(date: number): string; +} + +interface IX2JSOption { + escapeMode?: boolean; + attributePrefix?: string; + arrayAccessForm?: string; + emptyNodeForm?: string; + enableToStringFunc?: boolean; + arrayAccessFormPaths?: any[]; + skipEmptyTextNodesForObj?: boolean; + stripWhitespaces?: boolean; + datetimeAccessFormPaths?: any[]; +} + +declare var X2JS: IX2JS; + diff --git a/xml2js/xml2js-tests.ts b/xml2js/xml2js-tests.ts new file mode 100644 index 0000000000..3e3fbb661c --- /dev/null +++ b/xml2js/xml2js-tests.ts @@ -0,0 +1,7 @@ +/// + +import xml2js = require('xml2js'); + +xml2js.parseString("Hello xml2js!", (err: any, result: any) => { }); + +xml2js.parseString("Hello xml2js!", {trim: true}, (err: any, result: any) => { }); diff --git a/xml2js/xml2js.d.ts b/xml2js/xml2js.d.ts new file mode 100644 index 0000000000..30aa64a876 --- /dev/null +++ b/xml2js/xml2js.d.ts @@ -0,0 +1,36 @@ +// Type definitions for node-xml2js +// Project: https://github.com/Leonidas-from-XIV/node-xml2js +// Definitions by: Michel Salib +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'xml2js' { + + export = xml2js; + + module xml2js { + function parseString(xml:string, callback: (err: any, result:any) => void): void; + function parseString(xml:string, options: Options, callback: (err: any, result:any) => void): void; + + interface Options { + attrkey?: string; + charkey?: string; + explicitCharkey?: boolean; + trim?: boolean; + normalizeTags?: boolean; + normalize?: boolean; + explicitRoot?: boolean; + emptyTag?: any; + explicitArray?: boolean; + ignoreAttrs?: boolean; + mergeAttrs?: boolean; + validator?: Function; + xmlns?: boolean; + explicitChildren?: boolean; + charsAsChildren?: boolean; + async?: boolean; + strict?: boolean; + attrNameProcessors?: (name: string) => string; + tagNameProcessors?: (name: string) => string; + } + } +} diff --git a/youtube/youtube.d.ts b/youtube/youtube.d.ts index efb4ba344b..cfdba0efb0 100644 --- a/youtube/youtube.d.ts +++ b/youtube/youtube.d.ts @@ -1,7 +1,6 @@ // Type definitions for YouTube // Project: https://developers.google.com/youtube/ -// Definitions by: Daz Wilkin -// Definitions by: Ian Obermiller +// Definitions by: Daz Wilkin , Ian Obermiller // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module YT { @@ -72,6 +71,13 @@ declare module YT { suggestedQuality?: string; } + export interface VideoData + { + video_id: string; + author: string; + title: string; + } + export class Player { // Constructor constructor(id: string, playerOptions: PlayerOptions); @@ -89,7 +95,7 @@ declare module YT { // Properties size; - + // Playing playVideo(): void; pauseVideo(): void; @@ -116,7 +122,7 @@ declare module YT { getPlaybackRate(): number; setPlaybackRate(suggestedRate:number): void; getAvailablePlaybackRates(): number[]; - + // Behavior setLoop(loopPlaylists: boolean): void; setShuffle(shufflePlaylist: boolean): void; @@ -133,11 +139,12 @@ declare module YT { getDuration(): number; getVideoUrl(): string; getVideoEmbedCode(): string; + getVideoData(): VideoData; // Playlist getPlaylist(): any[]; getPlaylistIndex(): number; - + // Event Listener addEventListener(event: string, listener: string): void; } diff --git a/yui/yui-test.d.ts b/yui/yui-test.d.ts index f72784ffa4..a9df722327 100644 --- a/yui/yui-test.d.ts +++ b/yui/yui-test.d.ts @@ -1,7 +1,7 @@ // Type definitions for yui 3.14.0 // Project: https://github.com/yui/yui3/blob/release-3.14.0/src/test/js -// Definitions by: -// Gia Bảo @ Sân Đình +// Definitions by: Gia Bảo @ Sân Đình +// Definitions: https://github.com/borisyankov/DefinitelyTyped declare module YUITest { interface YUITestStatic{ diff --git a/zeroclipboard/zeroclipboard.d.ts b/zeroclipboard/zeroclipboard.d.ts index 76086f5bdb..6db1ba180d 100644 --- a/zeroclipboard/zeroclipboard.d.ts +++ b/zeroclipboard/zeroclipboard.d.ts @@ -1,8 +1,6 @@ // Type definitions for ZeroClipboard // Project: https://github.com/jonrohan/ZeroClipboard -// Definitions by: Eric J. Smith -// Definitions by: Blake Niemyjski -// Definitions by: György Balássy +// Definitions by: Eric J. Smith , Blake Niemyjski , György Balássy // Definitions: https://github.com/borisyankov/DefinitelyTyped declare class ZeroClipboard {